Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

deploy.md

180 lines8.7 KB

1---
2title: Deploy a harness
3id: harness-deploy
4order: 6
5description: "Run a harness in your server, on background workers, as a worker process, on another machine, or as a single executable."
6keywords:
7 - tanstack ai
8 - harness
9 - deploy
10 - build
11 - worker
12---
13​
14Your harness works on your laptop. Now it needs to run next to your API, in its own process, on a different machine, or as a CLI your team can download. You pick the place. The harness definition stays the same.
15​
16| Place | How |
17|---|---|
18| Your server | `createHarnessHost` and `createHarnessHandler` in your routes. No build step. |
19| Background workers | `createHarnessWorker` on a host that shares the log store. See [Run background work on workers](./workers). |
20| A worker process | `buildHarness`, then `artifactText(dir)` as the model of a `chat()` call. |
21| Another machine | `createHarnessHandler` there, then `harnessText({ url, token })` here. |
22| A single executable | `buildHarness({ compile })` with Bun. |
23​
24## Run more than one server
25​
26Give every server the same log store. Then any server can take a request for any thread:
27​
28- One server owns a thread at a time. An input that reaches another server waits in the log for the owner. See [One host drives a thread](./durable-sessions#one-host-drives-a-thread).
29- A [worker](./workers) runs the threads that no server has open: submitted inputs, schedules, and the work that a deploy cut.
30- Set the same `media: { secret }` on the handler of each server, so each server checks the media URLs of the others. See [Serve the session over HTTP](./connect#serve-the-session-over-http).
31- Stop each server with `host.close({ recoverable: true })`. A worker takes its cut work at once. See [Stop a host for a deploy](./durable-sessions#stop-a-host-for-a-deploy).
32- If your agents use the [coding tools](./coding-tools) on the disk of a server, set `ownership: { hostId }` on each host. Then a thread stays on the server that has its folder, while that server sends heartbeats. Use an id that stays the same after a restart, like the pod name of a StatefulSet, and keep a restart shorter than `ownership.expiresAfterMs`. See [Move a thread to another server](./coding-workspaces#5-move-a-thread-to-another-server).
33​
34## Build a worker artifact
35​
36`buildHarness` bundles the harness with Bun and writes a manifest next to it. Install [Bun](https://bun.sh) on the build machine.
37​
38```ts group=harness-deploy
39import { artifactText, buildHarness } from '@tanstack/ai-harness/build'
40​
41const { manifest } = await buildHarness({
42 entry: './src/studio.ts',
43 export: 'studio',
44 outDir: './dist/studio',
45})
46console.log(manifest.name, manifest.digest)
47```
48​
49- `dist/studio/harness.js` starts the harness as a worker. It reads session frames on stdin and writes them on stdout.
50- `dist/studio/harness.manifest.json` names the harness, its agents and plugins, what it needs (file system, processes, network), and the sha256 digest of the bundle.
51​
52The build imports your entry in a child process to read the harness name, agents, and plugins. Importing a module runs its code.
53​
54## Run the artifact as a model
55​
56`artifactText` starts one worker process per outer thread and checks the digest first. A changed bundle is refused.
57​
58```ts group=harness-deploy
59import { chat } from '@tanstack/ai'
60​
61const model = await artifactText('./dist/studio')
62const stream = chat({
63 adapter: model,
64 messages: [{ role: 'user', content: 'Plan the launch post.' }],
65 threadId: 'thread-1',
66})
67// When you are done with the workers:
68model.dispose()
69```
70​
71The 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.
72​
73## Use a harness on another machine
74​
75On the other machine, serve the harness with `createHarnessHandler`. Check the bearer token in `getUser` of the host `access`. See [Serve the session over HTTP](./connect#serve-the-session-over-http).
76​
77Here, use it as a model:
78​
79```ts group=harness-deploy
80import { harnessText } from '@tanstack/ai-harness'
81​
82const remote = harnessText({ url: 'http://build-box:8787', token: 'your-token' })
83```
84​
85The remote session keeps the conversation, so each call sends only the new message.
86​
87## Ship a single executable
88​
89Point `compile.entry` at the file that starts your app, for example a server or a command-line tool that imports the harness:
90​
91```ts group=harness-deploy
92await buildHarness({
93 entry: './src/studio.ts',
94 export: 'studio',
95 outDir: './dist/studio',
96 compile: { entry: './src/main.ts', outfile: './dist/studio-app', target: 'bun-linux-x64' },
97})
98```
99​
100Bun can build for another platform with `target`, for example `bun-darwin-arm64` or `bun-windows-x64`.
101​
102## Trace runs and report operations
103​
104A turn is slow or fails on one of your servers, and you cannot see which run or which server. Give the host a tracer and an `onOperation` listener. The host then writes a span for each run, and tells your listener when each run starts and ends.
105​
106Pass an OpenTelemetry tracer as it is. Install `@opentelemetry/api` in your app first. It is an optional peer dependency of the harness.
107​
108```ts
109import { trace } from '@opentelemetry/api'
110import { createHarnessHost } from '@tanstack/ai-harness'
111​
112const host = createHarnessHost({
113 observability: {
114 tracer: trace.getTracer('support-app'),
115 onOperation: ({ phase, operation }) => {
116 if (phase !== 'settled') return
117 console.log(operation.kind, operation.status, operation.durationMs)
118 console.log('tokens', operation.usage?.totalTokens)
119 },
120 },
121})
122```
123​
124The host writes these spans:
125​
126| Span | When |
127|---|---|
128| `harness.operation` | For each turn, agent run, and command that this host runs. A child agent run on the same host is a child span of the run that started it. |
129| `harness.recovery` | This host takes the work of a host that stopped. |
130| `harness.wait` | A wait for a person ends. The span starts at the time that the wait opened, also when another host opened it. |
131| `harness.transfer` | `host.transfer` moves a conversation. |
132​
133Each span has `harness.thread_id`, and `harness.tenant_id` for a tenant. A `harness.operation` span also has `harness.run_id`, `harness.parent_run_id`, `harness.operation.kind`, `harness.agent`, and `harness.operation.status`.
134​
135`onOperation` gets one `started` report and one `settled` report for each operation:
136​
137- Only the host that runs the operation calls it. A server that only passed the input on reports nothing.
138- A `settled` report has `status`, `durationMs`, and `usage`. The usage counts the model calls of the run, of its child runs, and of plugins in the run.
139- A failed operation has `error`, with its `message`, and its `code` when it has one.
140- If your listener throws, the host sends a `harness.plugin.warning` event and goes on.
141​
142Without `observability`, the host writes no spans and does no work for them.
143​
144### Join a turn to the trace of your app
145​
146Send the `traceparent` of your current span with the message:
147​
148```ts
149import { context, propagation } from '@opentelemetry/api'
150import { createHarnessClient } from '@tanstack/ai-harness/client'
151​
152const client = createHarnessClient({ url: '/api/harness', threadId: 'thread-1' })
153​
154const carrier: Record<string, string> = {}
155propagation.inject(context.active(), carrier)
156const traceparent = carrier.traceparent
157await client.send('Where is my order?', traceparent ? { traceparent } : {})
158```
159​
160The client sends it as the `traceparent` header. The `harness.operation` span of the turn gets a link to your span, on the server that runs the turn. To send it from another language, see [Traces](./protocol#traces).
161​
162## Known limits
163​
164Check these before you run many servers or long threads.
165​
166Across servers and restarts:
167​
168- A [`harnessAgent`](./subagents#call-a-harness-as-a-child) child waits only in memory. Its parent run waits on the same host. Another host, or a crash, does not resume it. After a crash, the next owner of the log ends the waits of the child.
169- A [log snapshot](./durable-sessions#keep-a-long-log-fast-to-open) holds the full fold of the thread, so it grows with the thread. To keep the log small, drop the old records with [`keepLogRecords: 'since-snapshot'`](./lifecycle#drop-the-records-before-a-snapshot).
170- `host.resumePending` opens the threads that it takes one at a time. A `GET run` by run id looks through the open sessions one at a time too.
171​
172Users and plugins:
173​
174- With an [OAuth MCP server](./mcp#3-sign-in-to-an-oauth-server), the MCP SDK sends its own refresh request for each session. Only the save of the new token is single-flight, so two sessions can use a rotating refresh token at the same time.
175- Plugin tools do not reach background agents. The `question` tool works only in a turn of the lead agent.
176​
177## What you have now
178​
179- The same harness in your server, on background workers, in a worker process, on another machine, or as a binary.
180- A span and a report for each run, linked to the trace of your app.