feat(ai, ai-harness): TanStack AI harness, phases 0 to 13 (combined stack) #1551
ClosedAlemTuzlakwants to merge 97 commits into
main fromfeat/harness-p13-agent-middlewareopened View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) assignedtombeckenham
github-actions[bot](GitHub profile, opens in a new tab) added labelsmerge-conflicts
github-actions[bot](GitHub profile, opens in a new tab) added labelswaiting-on: author
- @@ -0,0 +19,21 @@19+Mount one fetch handler on a route. `authorize` is required, so no endpoint is open by accident.20+21+```ts group=harness-connect22+import { defineHarness, createHarnessHandler, createHarnessHost } from '@tanstack/ai-harness'23+import { memoryPersistence } from '@tanstack/ai-persistence'24+import { openaiText } from '@tanstack/ai-openai'25+26+export const assistant = defineHarness({27+ name: 'acme/assistant',28+ adapter: openaiText('gpt-5.6'),29+})30+31+const host = createHarnessHost({ persistence: memoryPersistence() })32+33+export const handler = createHarnessHandler({34+ host,35+ harness: assistant,36+ authorize: (request) =>37+ request.headers.get('authorization') === `Bearer ${process.env.HARNESS_TOKEN}`38+ ? { id: 'user-1' }39+ : null,@@ -0,0 +55,21 @@55+})56+// When you are done with the workers:57+model.dispose()58+```59+60+The worker keeps the conversation of its thread between calls. Workers get the environment of the process that starts them, so they can read your provider keys.61+62+## Use a harness on another machine63+64+On the other machine, serve the harness with the CLI. It prints a token unless you set one:65+66+```bash67+HARNESS_TOKEN=your-token npx tsx cli.ts --serve --host 0.0.0.068+```69+70+Here, use it as a model:71+72+```ts group=harness-deploy73+import { harnessText } from '@tanstack/ai-harness'74+75+const remote = harnessText({ url: 'http://build-box:8787', token: 'your-token' })@@ -0,0 +9,21 @@9+ * survive a restart. The file is readable by your user only. A production10+ * store would encrypt the values.11+ */12+export function fileCredentials(13+ file = join(homedir(), '.tanstack-harness-example', 'credentials.json'),14+) {15+ type Saved = Record<string, Record<string, Credential>>16+ const load = async (): Promise<Saved> => {17+ try {18+ const parsed: unknown = JSON.parse(await readFile(file, 'utf8'))19+ return typeof parsed === 'object' && parsed !== null20+ ? (parsed as Saved)21+ : {}22+ } catch {23+ return {}24+ }25+ }26+ const save = async (all: Saved) => {27+ await mkdir(dirname(file), { recursive: true })28+ await writeFile(file, JSON.stringify(all, null, 2), { mode: 0o600 })29+ }@@ -0,0 +194,21 @@194+ }195+196+ return agent()197+ .onRequest('initialize', () => ({198+ protocolVersion: PROTOCOL_VERSION,199+ info: { name: harness.name, version: options.version ?? '0.0.0' },200+ capabilities: {},201+ }))202+ .onRequest('session/new', async () => {203+ const sessionId = `acp-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 9)}`204+ await sessionFor(sessionId)205+ return { sessionId }206+ })207+ .onRequest('session/resume', async ({ params }) => {208+ await sessionFor(params.sessionId)209+ return {}210+ })211+ .onRequest('session/prompt', async ({ params, client }) => {212+ const session = await sessionFor(params.sessionId)213+ const operation = session.prompt(promptText(params.prompt))214+ void pump(client, params.sessionId, session, operation)@@ -0,0 +206,21 @@206+ message: error instanceof Error ? error.message : String(error),207+ },208+ ],209+ })210+ }211+ }212+ }213+214+ // The control stream, with reconnects.215+ void (async () => {216+ let delay = options.reconnectDelayMs ?? 1000217+ while (!stopped.signal.aborted) {218+ try {219+ const response = await doFetch(`${base}/api/host/stream`, {220+ headers,221+ signal: stopped.signal,222+ })223+ if (response.status === 401)224+ throw new Error('The dashboard refused this host token.')225+ delay = options.reconnectDelayMs ?? 1000226+ for await (const envelope of sseData(response)) void handle(envelope)@@ -0,0 +227,21 @@227+ code,228+ name:229+ typeof input.name === 'string' ? input.name.slice(0, 100) : 'host',230+ expiresAt: Date.now() + 10 * 60_000,231+ })232+ json(res, 200, { pairingId, code })233+ return234+ }235+ if (method === 'GET' && path === '/api/pair/status') {236+ const pairing = pairings.get(url.searchParams.get('pairingId') ?? '')237+ if (!pairing || pairing.expiresAt < Date.now())238+ return json(res, 404, { error: 'unknown or expired pairing' })239+ if (!pairing.hostId) return json(res, 200, { status: 'pending' })240+ const host = hosts.get(pairing.hostId)241+ pairings.delete(url.searchParams.get('pairingId') ?? '')242+ return json(res, 200, {243+ status: 'approved',244+ hostId: pairing.hostId,245+ token: host?.token,246+ })247+ }@@ -0,0 +39,21 @@39+ }40+ const hasBody = req.method !== 'GET' && req.method !== 'HEAD'41+ const chunks: Array<Buffer> = []42+ if (hasBody) for await (const chunk of req) chunks.push(Buffer.from(chunk))43+ return new Request(new URL(req.url ?? '/', base), {44+ method: req.method ?? 'GET',45+ headers,46+ signal,47+ ...(hasBody ? { body: Buffer.concat(chunks) } : {}),48+ })49+}50+51+async function send(res: ServerResponse, response: Response): Promise<void> {52+ res.writeHead(response.status, Object.fromEntries(response.headers))53+ if (!response.body) {54+ res.end()55+ return56+ }57+ // `Readable.fromWeb` takes the stream type from node:stream/web.58+ Readable.fromWeb(response.body as NodeReadableStream).pipe(res)59+}@@ -0,0 +115,21 @@115+ )116+ await mkdir(outDir, { recursive: true })117+118+ // Temporary files sit next to the entry, so its imports resolve the same way.119+ const id = randomUUID().slice(0, 8)120+ const bootstrap = join(dirname(entry), `.harness-worker-${id}.mjs`)121+ const describe = join(dirname(entry), `.harness-describe-${id}.mjs`)122+ await writeFile(123+ bootstrap,124+ [125+ `import * as entry from ${JSON.stringify(entryPath)}`,126+ `import { runHarnessWorker } from ${JSON.stringify(workerModule)}`,127+ `await runHarnessWorker(entry[${JSON.stringify(exportName)}])`,128+ ].join('\n'),129+ )130+ await writeFile(131+ describe,132+ [133+ `const entry = await import(${JSON.stringify(entryPath)})`,134+ `const harness = entry[${JSON.stringify(exportName)}]`,135+ `if (!harness || harness.kind !== 'tanstack-ai-harness') throw new Error('Export ${exportName} of ${entry.replace(/\\/g, '/')} is not a harness.')`,@@ -0,0 +253,21 @@253+ const frame = JSON.parse(line) as HostFrame254+ for (const listener of listeners) listener(frame)255+ } catch {256+ // A line that is not a frame (for example a stray log) is skipped.257+ }258+ })259+ const send = (frame: object) =>260+ child.stdin.write(`${JSON.stringify(frame)}\n`)261+ send({ type: 'harness.subscribe', threadId })262+ return {263+ send,264+ frames: (listener) => {265+ listeners.add(listener)266+ return () => listeners.delete(listener)267+ },268+ kill: () => {269+ child.stdin.end()270+ child.kill()271+ },272+ }273+}@@ -0,0 +37,21 @@37+ * label: 'GitHub',38+ * oauth: { authorizationUrl, tokenUrl, deviceUrl, clientId, scopes: ['repo'] },39+ * tools: (token) => [listIssues(token)],40+ * })41+ * ```42+ */43+export function oauthConnector(options: OAuthConnectorOptions) {44+ const { id, label, oauth } = options45+ return definePlugin({46+ name: `connector/${id}`,47+ setup: (ctx) => {48+ const token = async (): Promise<string> => {49+ let credential = await ctx.credentials.require(id)50+ if (credential.type === 'api_key') return credential.value51+ if (isExpired(credential) && credential.refreshToken) {52+ credential = await refreshCredential(oauth, credential, options.fetch)53+ await ctx.credentials.set(id, credential)54+ }55+ if (credential.type === 'api_key') return credential.value56+ return credential.accessToken57+ }@@ -0,0 +83,21 @@83+ if (!session) {84+ const created = new HarnessSession({85+ harness,86+ threadId,87+ persistence,88+ inbox,89+ credentials,90+ hostId,91+ ...(principal ? { principal } : {}),92+ onClose: () => sessions.delete(key),93+ })94+ session = created.open().then(95+ () => created,96+ (error: unknown) => {97+ sessions.delete(key)98+ throw error99+ },100+ )101+ sessions.set(key, session)102+ }103+ return session as Promise<HarnessSession<typeof harness>>@@ -0,0 +287,21 @@287+ }288+ session = await host.open(harness, {289+ threadId: frame.threadId,290+ principal,291+ })292+ send({293+ type: 'harness.hello',294+ v: HARNESS_PROTOCOL_VERSION,295+ threadId: frame.threadId,296+ })297+ const events = session.events({298+ ...(frame.from ? { from: frame.from } : {}),299+ signal: reader.signal,300+ })301+ void (async () => {302+ for await (const entry of events)303+ send({ type: 'harness.event', ...entry })304+ })()305+ return306+ }307+ if (!session) throw new Error('Send harness.subscribe first.')@@ -0,0 +1200,21 @@1200+ ...(turn.parentRunId ? { parentRunId: turn.parentRunId } : {}),1201+ ...(turn.resume ? { resume: turn.resume } : {}),1202+ abortController: operation.abortController,1203+ stream: true,1204+ } as never) as AsyncIterable<StreamChunk>1205+1206+ for await (const chunk of stream) {1207+ operation.publish(chunk)1208+ if (1209+ chunk.type === EventType.TEXT_MESSAGE_CONTENT &&1210+ !('subagentRunId' in chunk && chunk.subagentRunId)1211+ ) {1212+ text += chunk.delta1213+ }1214+ if (1215+ chunk.type === EventType.RUN_FINISHED &&1216+ chunk.outcome?.type === 'interrupt'1217+ ) {1218+ interrupts = chunk.outcome.interrupts1219+ }1220+ if (chunk.type === EventType.RUN_ERROR) failure = chunk.message@@ -324,8 +356,10 @@324356 this.values.set(namespace, bucket)325357 }326358 bucket.set(key, value)359+ this.bump(namespace, key)327360 return Promise.resolve()328361 }329362 delete(namespace: string, key: string): Promise<void> {330363 const bucket = this.values.get(namespace)331364 if (!bucket) return Promise.resolve()365+ this.revisions.get(namespace)?.delete(key)@@ -68,0 +80,21 @@80+ * A string longer than {@link MODEL_RESULT_MAX_STRING} (for example a base6481+ * image) becomes a short note, so one image result cannot fill the context.82+ * The full result still travels on `SUBAGENT_FINISHED` for the UI.83+ */84+export function compactForModel(value: unknown, depth = 0): unknown {85+ if (typeof value === 'string') {86+ return value.length > MODEL_RESULT_MAX_STRING87+ ? `[omitted ${value.length} characters]`88+ : value89+ }90+ if (depth > 20 || typeof value !== 'object' || value === null) return value91+ if (Array.isArray(value)) {92+ return value.map((item) => compactForModel(item, depth + 1))93+ }94+ return Object.fromEntries(95+ Object.entries(value).map(([key, item]) => [96+ key,97+ compactForModel(item, depth + 1),98+ ]),99+ )100+}
AlemTuzlak closed this
Sign in to join this conversation.
Navigate logical layers of code changes, visualize relationships, and explore their blast radius.
📝 Walkthrough
Walkthrough#
This pull request adds a harness runtime for persistent AI sessions, typed agents and plugins, session transports, and user interfaces. It also adds OAuth and MCP connectors, first-party plugins, CLI and dashboard packages, build and worker tools, and changes to subagent results, context, and limits.
Changes#
Harness runtime and durable session behavior
packages/ai-harness/src/*,packages/ai-harness/src/first-party/*,packages/ai-harness/tests/*packages/ai/src/activities/chat/agents/*,packages/ai/src/activities/chat/middleware/*,packages/ai-persistence/src/*,packages/ai/tests/*packages/ai-harness/src/http.ts,client.ts,worker.ts,harness-text.ts,view/*,packages/ai-harness/tests/*CLI, dashboard, and agent integrations
packages/ai-acp/*,packages/ai-code-mode/*,packages/ai-mcp/*,packages/ai-sandbox/*packages/ai-harness-cli/*,packages/ai-dashboard/*docs/harness/*,docs/chat/subagents.md,docs/config.json,examples/harness-cli/*,examples/README.md,examples/ts-*/package.jsontesting/e2e/*Priority: ➖ Normal
Estimated code review effort: 5 (Critical) | ~90 minutes
Sequence Diagram(s)#
Merge Risk: 🟠 High · up to
a3b36Another authorized user can receive a session bound to the first user’s credentials, and several reachable failures can leave sessions stuck or exhaust dashboard memory. These issues should be fixed before merging.
Security Architecture Review#
Security architecture risk: 🟠 High · up to
a3b36The new session and remote-access designs need security review before deployment. A session can retain the first user’s credential identity when another authorized user opens the same conversation, and the cross-machine deployment example sends its access token over an unencrypted connection.
Retained concerns
Security review details
Security Blast Radius
Security Findings and Attack Paths
Trust Boundaries and Controls
Resilience and Maintainability Implications
Hardening Proposals
🚥 Pre-merge checks | ✅ 4 | ❌ 1
❌ Failed checks (1 warning)#
✅ Passed checks (4 passed)
Full details: Docstring Coverage
Explanation
Docstring coverage is 61.86% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 97 functions across 58 files. (6 skipped: 6 unsupported.)
✨ Finishing Touches 💡 2
📝 Generate docstrings 💡
🧪 Generate unit tests (beta)
🛠️ Fix failing CI checks 💡
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
❤️ Share