Open History to see the last commit
1/**
2 * The wire contract for the ONE request that crosses the DO → container boundary
3 * to start a run: `POST /run` on the in-container runner.
4 *
5 * Defined ONCE here so both sides import the same shape AND the same narrowing
6 * guard, with NO runtime-specific imports (no `cloudflare:*`, no `node:*`):
7 * - the `ContainerSandboxCoordinator` (Workers side) builds a
8 * {@link ContainerRunRequest} and POSTs it (re-exported from `/agent`);
9 * - the in-container `runInContainerHarness` (Node side) validates the body
10 * with {@link parseContainerRunRequest} before running `chat()` (imported
11 * from `/runner`).
12 *
13 * It carries the run identity + conversation + serialized host-tool descriptors
14 * + the tool-exec callback, plus the `harness`/`model`/`workspace` the runner
15 * needs to build the right adapter and sandbox.
16 *
17 * NOTE: the workspace's secret VALUES do NOT cross this boundary — `createSecrets`
18 * stores them under a non-enumerable symbol, so JSON-serializing the workspace
19 * carries only the secret NAMES. The runner reconstructs runtime secrets from
20 * the container env (the DO injects them via `sandbox.setEnvVars`).
21 */
22import type { ModelMessage } from '@tanstack/ai'
23import type { ToolDescriptor, WorkspaceDefinition } from '@tanstack/ai-sandbox'
24
25/**
26 * The in-sandbox harnesses the runner can spawn. Single source of truth: the
27 * {@link HarnessId} type is DERIVED from this list, and {@link isHarnessId}
28 * validates against it — so the runtime guard and the compile-time type can
29 * never drift.
30 */
31const HARNESS_IDS = ['claude-code', 'codex', 'opencode'] as const
32
33/**
34 * Identifier for the in-sandbox harness the runner spawns. The runner maps this
35 * to the matching `*Text` adapter (via the caller's `resolveAdapter`); the DO
36 * never imports the adapter packages.
37 */
38export type HarnessId = (typeof HARNESS_IDS)[number]
39
40/**
41 * The body of `POST /run`: the run identity + conversation + serialized
42 * host-tool descriptors + the tool-exec callback, plus the harness/model/
43 * workspace the runner needs to build the right adapter.
44 */
45export interface ContainerRunRequest {
46 runId: string
47 threadId: string
48 messages: Array<ModelMessage>
49 harness: HarnessId
50 model: string
51 workspace: WorkspaceDefinition
52 /** Host-tool descriptors serialized by `toolDescriptors()` on the DO. */
53 toolDescriptors: Array<ToolDescriptor>
54 /** DO endpoint the in-container `httpRemoteToolExecutor` POSTs tool calls to. */
55 toolExecUrl: string
56 /** Per-run bearer token gating that tool-exec endpoint. */
57 toolExecToken: string
58}
59
60function isHarnessId(value: unknown): value is HarnessId {
61 return (
62 typeof value === 'string' &&
63 (HARNESS_IDS as ReadonlyArray<string>).includes(value)
64 )
65}
66
67function isToolDescriptor(value: unknown): value is ToolDescriptor {
68 return (
69 value !== null &&
70 typeof value === 'object' &&
71 'name' in value &&
72 typeof value.name === 'string'
73 )
74}
75
76function isWorkspaceDefinition(value: unknown): value is WorkspaceDefinition {
77 return (
78 value !== null &&
79 typeof value === 'object' &&
80 'source' in value &&
81 value.source !== null &&
82 typeof value.source === 'object'
83 )
84}
85
86/**
87 * Assert enough of a message to fail fast on garbage (a non-empty `role` and a
88 * `content` field). The chat engine validates the full shape downstream; this
89 * narrows the array element to {@link ModelMessage} without a cast.
90 */
91function isModelMessage(value: unknown): value is ModelMessage {
92 return (
93 value !== null &&
94 typeof value === 'object' &&
95 'role' in value &&
96 typeof value.role === 'string' &&
97 'content' in value
98 )
99}
100
101/** Narrow `unknown` to an indexable record (a predicate, not a cast). */
102function isRecord(value: unknown): value is Record<string, unknown> {
103 return value !== null && typeof value === 'object'
104}
105
106function requireNonEmptyString(
107 value: Record<string, unknown>,
108 key: string,
109): string {
110 const found = value[key]
111 if (typeof found !== 'string' || found === '') {
112 throw new Error(`run request: ${key} must be a non-empty string`)
113 }
114 return found
115}
116
117/**
118 * Narrow an unknown `POST /run` body into a {@link ContainerRunRequest} (project
119 * rule: no `as`). The message and descriptor shapes are validated downstream by
120 * the chat engine and the tool bridge; here we only assert enough to fail fast
121 * with a clear error on a malformed request.
122 */
123export function parseContainerRunRequest(value: unknown): ContainerRunRequest {
124 if (!isRecord(value)) {
125 throw new Error('run request must be a JSON object')
126 }
127 const runId = requireNonEmptyString(value, 'runId')
128 const threadId = requireNonEmptyString(value, 'threadId')
129 const model = requireNonEmptyString(value, 'model')
130 const toolExecUrl = requireNonEmptyString(value, 'toolExecUrl')
131 const toolExecToken = requireNonEmptyString(value, 'toolExecToken')
132
133 const messages = value['messages']
134 if (
135 !Array.isArray(messages) ||
136 messages.length === 0 ||
137 !messages.every(isModelMessage)
138 ) {
139 throw new Error('run request: messages must be a non-empty ModelMessage[]')
140 }
141
142 const harness = value['harness']
143 if (!isHarnessId(harness)) {
144 throw new Error('run request: harness must be a known harness id')
145 }
146
147 const workspace = value['workspace']
148 if (!isWorkspaceDefinition(workspace)) {
149 throw new Error('run request: workspace must be a WorkspaceDefinition')
150 }
151
152 const toolDescriptors = value['toolDescriptors']
153 if (
154 !Array.isArray(toolDescriptors) ||
155 !toolDescriptors.every(isToolDescriptor)
156 ) {
157 throw new Error('run request: toolDescriptors must be a ToolDescriptor[]')
158 }
159
160 return {
161 runId,
162 threadId,
163 messages,
164 harness,
165 model,
166 workspace,
167 toolDescriptors,
168 toolExecUrl,
169 toolExecToken,
170 }
171}