Open History to see the last commit
1/**
2 * `runInContainerHarness` — the IN-CONTAINER harness runner, shipped from the
3 * package so a co-located app's container program is a single function call.
4 *
5 * This is the heart of the CO-LOCATED model: the agent harness loop AND its MCP
6 * tool-bridge run HERE, on the container's own localhost. The Durable Object
7 * outside never calls `chat()`; it POSTs `/run` to this server and reads the
8 * NDJSON stream back.
9 *
10 * DO ── POST /run {messages, harness, model, workspace, toolDescriptors,
11 * toolExecUrl, toolExecToken} ──▶ THIS
12 * THIS ── NDJSON stream of StreamChunk ──────────────────────────────────▶ DO
13 *
14 * It is a tiny `node:http` server (NODE/container side — NOT Workers; it uses
15 * `localProcessSandbox`). On `POST /run` it validates the {@link
16 * ContainerRunRequest}, builds `chat()` with the in-container `local-process`
17 * sandbox and the adapter the CALLER resolves, and streams each {@link
18 * StreamChunk} back as NDJSON (one JSON object per line).
19 *
20 * Why the MCP bridge is genuinely in-container: the in-container sandbox is
21 * `localProcessSandbox()` — the container IS the host — so the harness adapter
22 * serves its tool-bridge over the container's own `localhost` and feeds the
23 * prompt over NATIVE writable stdin (no file-redirect; the bridge URL/token
24 * never leave the container). The MCP protocol never crosses the network.
25 *
26 * The ONE thing that still crosses back to the DO is host-tool EXECUTION: each
27 * tool rebuilt by {@link remoteToolStubs} delegates its `execute()` to {@link
28 * httpRemoteToolExecutor}, which POSTs `{ name, args }` (bearer-gated) to the
29 * DO's `toolExecUrl`:
30 *
31 * agent → in-container MCP bridge → stub.execute → httpRemoteToolExecutor → DO
32 *
33 * The app supplies only `resolveAdapter` — which `*Text` adapter to build for a
34 * given `{ harness, model }`. The server + `chat()` wiring lives here, so the
35 * package doesn't depend on every adapter package.
36 *
37 * NOTE: container-side Node code — compiles against the real TanStack AI types;
38 * not runtime-verified in this repo (no container build in CI).
39 */
40import { createServer } from 'node:http'
41import { EventType, chat } from '@tanstack/ai'
42import {
43 createSecrets,
44 defineSandbox,
45 defineWorkspace,
46 httpRemoteToolExecutor,
47 remoteToolStubs,
48 withSandbox,
49} from '@tanstack/ai-sandbox'
50import { localProcessSandbox } from '@tanstack/ai-sandbox-local-process'
51import { parseContainerRunRequest } from './protocol'
52import type { IncomingMessage, Server, ServerResponse } from 'node:http'
53import type { AnyTextAdapter, StreamChunk } from '@tanstack/ai'
54import type { WorkspaceDefinition } from '@tanstack/ai-sandbox'
55import type { ContainerRunRequest, HarnessId } from './protocol'
56
57/** The `{ harness, model }` the caller maps to a concrete `*Text` adapter. */
58export interface ResolveAdapterInput {
59 harness: HarnessId
60 model: string
61}
62
63/** Options for {@link runInContainerHarness}. */
64export interface RunInContainerHarnessOptions {
65 /**
66 * Build the text adapter `chat()` runs for one request's `{ harness, model }`.
67 * The app supplies this so the package doesn't depend on every adapter package
68 * — e.g. `({ model }) => claudeCodeText(model)`.
69 */
70 resolveAdapter: (input: ResolveAdapterInput) => AnyTextAdapter
71 /** Port to listen on. Defaults to `RUNNER_PORT` env, then `8080`. */
72 port?: number
73}
74
75/** What {@link runInContainerHarness} returns: the listening `node:http` server. */
76export interface ContainerHarnessServer {
77 /** The underlying `node:http` server (already `listen()`ing). */
78 server: Server
79 /** The port it is listening on. */
80 port: number
81}
82
83/** Read a request body fully into a string (small JSON payloads only). */
84function readBody(req: IncomingMessage): Promise<string> {
85 return new Promise((resolve, reject) => {
86 let body = ''
87 req.setEncoding('utf8')
88 req.on('data', (chunk: string) => {
89 body += chunk
90 })
91 req.on('end', () => resolve(body))
92 req.on('error', reject)
93 })
94}
95
96/**
97 * Rebuild the request's workspace with a real `createSecrets`, pulling each
98 * referenced secret's VALUE from the container env. Secret values never cross
99 * the `POST /run` boundary (`createSecrets` stores them under a non-enumerable
100 * symbol, so serializing the workspace carries only the names) — the DO injects
101 * them into the container env via `sandbox.setEnvVars`, and we reconstitute them
102 * here. A referenced secret missing from the env is a hard error, never a silent
103 * keyless run.
104 */
105function reconstituteWorkspace(
106 workspace: WorkspaceDefinition,
107): WorkspaceDefinition {
108 if (workspace.secrets === undefined) return workspace
109 const names = Object.keys(workspace.secrets)
110 if (names.length === 0) return workspace
111 const values: Record<string, string> = {}
112 for (const name of names) {
113 const value = process.env[name]
114 if (value === undefined || value === '') {
115 throw new Error(
116 `runInContainerHarness: secret "${name}" is not set in the container env`,
117 )
118 }
119 values[name] = value
120 }
121 return defineWorkspace({ ...workspace, secrets: createSecrets(values) })
122}
123
124/**
125 * Build the `chat()` stream that runs the harness on THIS container via the
126 * `local-process` sandbox. The agent's `chat()` tools are stubs that delegate
127 * back to the DO; everything else (the harness loop, the MCP bridge, stdin)
128 * stays on localhost.
129 */
130function runAgent(
131 request: ContainerRunRequest,
132 resolveAdapter: (input: ResolveAdapterInput) => AnyTextAdapter,
133): AsyncIterable<StreamChunk> {
134 const sandbox = defineSandbox({
135 // The container IS the host: no isolation, just run on its own filesystem.
136 id: 'colocated-in-container',
137 provider: localProcessSandbox(),
138 // Honor the app's workspace (source / setup / skills / …), with the secrets
139 // re-resolved from the container env.
140 workspace: reconstituteWorkspace(request.workspace),
141 })
142
143 // `stream: true` (no outputSchema) makes chat() return AsyncIterable<StreamChunk>.
144 return chat({
145 threadId: request.threadId,
146 adapter: resolveAdapter({
147 harness: request.harness,
148 model: request.model,
149 }),
150 messages: request.messages,
151 stream: true,
152 // Rebuild the DO's host tools as stubs whose execute() POSTs back to the DO.
153 // The adapter bridges them over the in-container localhost MCP transport.
154 tools: remoteToolStubs(
155 request.toolDescriptors,
156 httpRemoteToolExecutor(request.toolExecUrl, request.toolExecToken),
157 ),
158 // Provide the in-container local-process sandbox handle the adapter needs.
159 middleware: [withSandbox(sandbox)],
160 })
161}
162
163/** Stream the agent's chunks to the response as NDJSON, one object per line. */
164async function handleRun(
165 req: IncomingMessage,
166 res: ServerResponse,
167 resolveAdapter: (input: ResolveAdapterInput) => AnyTextAdapter,
168): Promise<void> {
169 const parsed: unknown = JSON.parse(await readBody(req))
170 const request = parseContainerRunRequest(parsed)
171 res.writeHead(200, {
172 'content-type': 'application/x-ndjson',
173 'cache-control': 'no-cache',
174 })
175 // The DO appends each line to its durable run-log; here we are the producer,
176 // so we surface a mid-stream failure as a terminal RUN_ERROR line the DO will
177 // append + finish on, never a silently truncated stream.
178 try {
179 for await (const chunk of runAgent(request, resolveAdapter)) {
180 res.write(`${JSON.stringify(chunk)}\n`)
181 }
182 } catch (error) {
183 const message = error instanceof Error ? error.message : String(error)
184 res.write(`${JSON.stringify({ type: EventType.RUN_ERROR, message })}\n`)
185 } finally {
186 res.end()
187 }
188}
189
190/**
191 * Start the in-container harness runner: a `node:http` server with `GET /health`
192 * and `POST /run`. Call this as the container's program; the app supplies only
193 * `resolveAdapter`.
194 */
195export function runInContainerHarness(
196 options: RunInContainerHarnessOptions,
197): ContainerHarnessServer {
198 const port =
199 options.port ?? Number.parseInt(process.env.RUNNER_PORT ?? '8080', 10)
200
201 const server = createServer((req, res) => {
202 if (req.method === 'POST' && req.url === '/run') {
203 handleRun(req, res, options.resolveAdapter).catch((error: unknown) => {
204 // A failure BEFORE we start streaming (e.g. a malformed body) is a 400 —
205 // surfaced, never swallowed.
206 const message = error instanceof Error ? error.message : String(error)
207 if (!res.headersSent) {
208 res.writeHead(400, { 'content-type': 'text/plain' })
209 }
210 res.end(message)
211 })
212 return
213 }
214 if (req.method === 'GET' && req.url === '/health') {
215 res.writeHead(200).end('ok')
216 return
217 }
218 res.writeHead(404).end('not found')
219 })
220
221 server.listen(port, () => {
222 console.log(`[container-runner] listening on :${port}`)
223 })
224
225 return { server, port }
226}