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

workers.md

172 lines7.6 KB

1---
2title: Run background work on workers
3id: harness-workers
4order: 4
5description: "Run harness threads that no user has open: inputs that a server submits, schedules, tools that wait for hours, and the work that a deploy cut. A worker takes each thread from the session log."
6keywords:
7 - tanstack ai
8 - harness
9 - worker
10 - createHarnessWorker
11 - submit
12 - schedule
13 - step.sleep
14 - deploy
15---
16​
17Some work has no user who waits for it: a report that a cron job asks for, a reminder in one day, a tool that waits for a payment, or a turn that a deploy cut. Nobody opens these threads, so nothing runs them. A worker finds each thread in the session log that has work and no live host, takes it, runs the work, and gives it back.
18​
19Every host on this page shares one log store. In production, that is your [`LogStore`](../persistence/store-reference#logstore). Here, `memoryLogState()` gives two hosts one memory log, the same as two servers on one database.
20​
21## 1. Start a worker
22​
23Make a host for the worker, and start the worker on it:
24​
25```ts group=harness-workers
26import {
27 createHarnessHost,
28 createHarnessWorker,
29 defineHarness,
30} from '@tanstack/ai-harness'
31import { memoryLogState, memoryLogStore } from '@tanstack/ai-persistence'
32import { openaiText } from '@tanstack/ai-openai'
33​
34const assistant = defineHarness({
35 name: 'acme/assistant',
36 adapter: openaiText('gpt-6.1-sol'),
37})
38​
39// One log store for every host. Swap in your own store.
40const state = memoryLogState()
41const hostOn = () =>
42 createHarnessHost({ persistence: { stores: { log: memoryLogStore({ state }) } } })
43​
44const workerHost = hostOn()
45const worker = createHarnessWorker({ host: workerHost, harnesses: [assistant] })
46```
47​
48- `harnesses`: the harnesses whose threads the worker runs, matched by name.
49- `concurrency`: at most how many threads the worker runs at the same time. The default is 8.
50- `pollMs`: how long the worker waits after a look that found no work. The wait doubles after each empty look, up to 30 seconds. The default is 1 000.
51- `signal`: an `AbortSignal` that stops the worker, the same as `stop()`.
52​
53Run as many workers as you want, on as many machines. Each thread goes to one of them. Each thread opens in its own tenant, with no user.
54​
55If a thread fails to open, the worker logs the error and skips that thread for a time. The time doubles after each failure in a row, up to 5 minutes. The other threads still run.
56​
57## 2. Submit an input from any server
58​
59A cron route or a webhook wants the agent to do a job, but it must not wait for the turn. `host.submit` stores the input in the log and runs nothing:
60​
61```ts group=harness-workers
62const apiHost = hostOn()
63​
64const receipt = await apiHost.submit({
65 harness: assistant,
66 threadId: 'weekly-report',
67 input: { op: 'prompt', message: 'Write the weekly report.' },
68 inputId: 'weekly-report-2026-42',
69})
70console.log(receipt.status) // 'queued'
71```
72​
73- The input waits until a host owns the thread. That is the host that runs the thread now, or a worker.
74- Pass `inputId` so that a retry is safe. The same id with the same input is a duplicate. The same id with another input gets `rejected` with `conflict`.
75- `input` is any input that runs on the owner: a prompt, a steer, a follow-up, an answer, a cancel, a command, and more.
76- On a host with [`access`](./access), pass `user`. The input needs the same action as on a handle, else `submit` throws `AccessDeniedError` and stores nothing.
77- An answer or a cancel is checked with the run that it targets, from the log. A cancel must name its `operationId`. A run that the log does not have gets `rejected` with `unknown_run`. To drop an input that waits, use `cancelInput`.
78​
79## 3. Run an input later
80​
81`session.schedule` runs an input at a time that you pick. The log keeps the schedule, so it runs once, also after a restart or on another machine:
82​
83```ts group=harness-workers
84const session = await apiHost.open(assistant, { threadId: 'daily-summary' })
85​
86const { scheduleId } = await session.schedule({
87 at: Date.now() + 60 * 60 * 1000,
88 input: { op: 'prompt', message: 'Write the daily summary.' },
89})
90await session.close()
91```
92​
93- While a host has the thread open, that host runs the input at `at`.
94- When no host has the thread open, the log store wakes a worker at `at`.
95- A time that passed runs at once.
96- Pass `scheduleId` to pick the id. A second call with the id of a schedule that waits writes nothing.
97- `user` is who sends the input when it runs. The default is the user of the open.
98​
99To stop a schedule that did not run yet:
100​
101```ts group=harness-workers
102const later = await apiHost.open(assistant, { threadId: 'daily-summary' })
103await later.cancelSchedule({ scheduleId })
104await later.close()
105```
106​
107A schedule that ran, or an unknown id, changes nothing. While another live host owns the thread, `schedule` and `cancelSchedule` throw.
108​
109## 4. Wait inside a tool
110​
111A tool sends a reminder, waits one day, and then sends a follow-up. `step.sleep` in a [durable tool](./durable-tools) waits, and the log keeps the time it wakes:
112​
113```ts group=harness-workers
114import { toolDefinition } from '@tanstack/ai'
115import { durableTool } from '@tanstack/ai-harness'
116import { z } from 'zod'
117​
118declare const mail: {
119 send: (message: { to: string; text: string }) => Promise<void>
121​
122export const remind = durableTool(
123 toolDefinition({
124 name: 'remind',
125 description: 'Remind a customer, and follow up one day later',
126 inputSchema: z.object({ to: z.string() }),
127 }),
128 async ({ to }, { step }) => {
129 await step.do('send-reminder', () => mail.send({ to, text: 'Your invoice is due.' }))
130 await step.sleep({ name: 'wait-a-day', ms: 24 * 60 * 60 * 1000 })
131 await step.do('send-follow-up', () => mail.send({ to, text: 'Your invoice is late.' }))
132 return 'Sent.'
133 },
135```
136​
137- A sleep of 30 seconds or less waits in the process. The host keeps the thread while it waits.
138- A longer sleep on a thread that only a worker runs gives the thread back to the log store with a wake. The worker slot is free, and `worker.stop()` does not wait for the sleep. On a thread that your app has open, the sleep waits in the process.
139- At the wake time, or when the host stops, a worker runs the tool call again. The finished steps return their stored values, and the sleep waits only for the time that is left.
140- `name` is a step name. Use the same name on every run, and not the name of a `do` step of the same call.
141- Agent code has the same `step.sleep` on `ctx.harness.step`, in a run started with `runAgainAfterCrash: true`. See [Keep a background agent going after a crash](./subagents#keep-a-background-agent-going-after-a-crash).
142​
143## 5. Restart for a deploy
144​
145Stop a server with `recoverable: true`. Its running work stops, and the host gives each busy thread back with a wake, so a worker takes it at once:
146​
147```ts group=harness-workers
148process.on('SIGTERM', async () => {
149 await apiHost.close({ recoverable: true })
150 process.exit(0)
151})
152```
153​
154A worker host stops the same way. To let its threads end their work first, call `worker.stop()`. It stops the looks for work, and waits until the threads that the worker runs close:
155​
156```ts group=harness-workers
157process.on('SIGTERM', async () => {
158 await worker.stop()
159 await workerHost.close()
160})
161```
162​
163To stop the work at once, close the host with `recoverable: true` instead. Another worker runs that work again.
164​
165## What you have now
166​
167- A pool of workers that runs every thread with work and no live host.
168- Inputs that any server submits, and inputs that run at a time you pick.
169- Tools that wait for hours, and continue on another machine after a stop.
170- Deploys that hand the cut work to a worker at once.
171​
172A client reads these threads as any other thread. See [Connect clients](./connect).