Open History to see the last commit
1---
2title: Send inputs safely
3id: harness-inputs
4order: 4
5description: "Give each prompt your own id, so a network retry does not run it twice. Ask the session how an input ended, and cancel or move a message that waits."
6keywords:
7 - tanstack ai
8 - harness
9 - inputId
10 - idempotency
11 - settled
12 - steer
13 - cancelInput
14 - changeInputDelivery
15 - moveToolCallToBackground
16---
17
18A network retry can send the same prompt twice, and a client that reconnects does not know how its last prompt ended. Give each input your own id. A retry with the same id runs nothing again, and the session tells you how the input ended.
19
20## Send a prompt with your own id
21
22On the server, pass `inputId` to `send`. `await turn.receipt` resolves when the session stored the input.
23
24```ts group=harness-inputs
25import { createHarnessHost, defineHarness } from '@tanstack/ai-harness'
26import { memoryPersistence } from '@tanstack/ai-persistence'
27import { openaiText } from '@tanstack/ai-openai'
28
29const assistant = defineHarness({
30 name: 'acme/assistant',
31 adapter: openaiText('gpt-6.1-sol'),
32})
33const host = createHarnessHost({ persistence: memoryPersistence() })
34const session = await host.open(assistant, { threadId: 'user-1-thread' })
35
36const turn = session.send('Summarize the report.', { inputId: 'req-42' })
37const receipt = await turn.receipt
38console.log(receipt.status) // 'accepted' or 'queued'
39```
40
41- The same id and the same message: you get the first input's operation, and the model is not called again.
42- The same id and another message: the receipt has `status: 'rejected'` and `reason: 'conflict'`, and `await turn` rejects with `InputRejectedError`.
43- An input to a thread that was deleted: the receipt has `status: 'rejected'` and `reason: 'deleted'`, and `await turn` rejects with `InputRejectedError`. Nothing runs.
44- `send` with `mode: 'steer'` or `mode: 'followUp'`, and `resolve`, take `{ inputId }` too.
45- [`configure`](./thread-settings) and [`reset`](./fork-and-reset#reset-with-a-handoff-note) are inputs too. They take `{ inputId }` and run once per id.
46
47## Retry from the client
48
49The client sends the same `inputId` again after a network error. The second call gets the first receipt.
50
51```ts group=harness-inputs-client
52import { createHarnessClient } from '@tanstack/ai-harness/client'
53import type { AnyHarness } from '@tanstack/ai-harness'
54
55const client = createHarnessClient<AnyHarness>({
56 url: '/api/harness',
57 threadId: 'user-1-thread',
58})
59
60const send = () => client.send('Summarize the report.', { inputId: 'req-42' })
61const receipt = await send().catch(send)
62console.log(receipt.operationId)
63```
64
65Make the id once per user action (a button press), and keep it for every retry of that action.
66
67This works for every input over HTTP and the socket. A `command` or an `agent` input that the client sends again with the same `inputId` also runs once. The `inputId` of its receipt is the id that the client sent.
68
69## Wait for the outcome
70
71On the server, `session.settled({ inputId })` waits until the input ends. It reads the log, so on a [durable host](./durable-sessions) it also works after a restart and on another host that opens the thread.
72
73```ts group=harness-inputs
74const settlement = await session.settled({
75 inputId: 'req-42',
76 signal: AbortSignal.timeout(60_000),
77})
78if (settlement.outcome === 'failed') {
79 console.log(settlement.error?.code) // 'attempts_exhausted', 'timeout', or undefined
80}
81```
82
83`signal` is optional. When it aborts first, `settled` rejects with its reason. The input keeps running.
84
85On a host that does not own the thread, the input waits for the owner. If the owner refuses it, `settled` rejects with `InputRejectedError`. The owner refuses an input when the thread is busy and the input has `busy: 'reject'`, or when the log has its id with another message. The log then has a `harness.offer.rejected` record.
86
87- `completed`: the turn has its answer.
88- `failed`: the turn failed. `error.code` is set for a limit.
89- `aborted`: someone cancelled the turn. The text that the model streamed before the cancel stays in the transcript as its answer.
90- `interrupted`: the turn waits for a person. The `resolve` that answers it is a new input. See [Wait for a person](./waits).
91
92If the turn fails after an approved tool ran (for example, the next model call fails), the interrupt is used up, and the tool does not run again. Its result stays in the transcript. To go on, send a new message. If a resume stopped before its tool ran, the interrupt stays open, and you can resolve it again.
93
94A client gets the same answer as a `harness.input.settled` event:
95
96```ts group=harness-inputs-client
97for await (const entry of client.events()) {
98 const { event } = entry
99 if (event.type === 'CUSTOM' && event.name === 'harness.input.settled') {
100 console.log(event.value)
101 }
102}
103```
104
105## Continue without a new message
106
107Sometimes the transcript already holds what the model must answer, for example a tool result that your own system stored. Start a turn with `continueWithoutMessage`, and the model answers the stored transcript. No new user message goes in:
108
109```ts group=harness-inputs
110const continued = session.continueWithoutMessage({ inputId: 'req-43' })
111await continued
112```
113
114From the client:
115
116```ts group=harness-inputs-client
117const continuedReceipt = await client.continueWithoutMessage({ inputId: 'req-43' })
118```
119
120- `inputId` works as for `send`: a retry with the same id runs once.
121- `continueWithoutMessage` takes `overrides`, `user`, and `context` too, as `send` does. On a host with [`access`](./access), a session acts only as the user that opened it, so leave out `user`.
122- When the turn starts, the last message of the transcript must be a user message or a tool result. Else the input is rejected with the reason `nothing_to_continue`, and `await continued` rejects with `InputRejectedError`.
123- A `continueWithoutMessage` that a host left after a crash runs on the next host, as a prompt does.
124
125## Give the model a note for one turn
126
127A reminder such as "call `finish` or `give_up`" helps the model in one turn, but it does not belong in the transcript. Pass it as `ephemeral` to `send` or `continueWithoutMessage`:
128
129```ts group=harness-inputs
130const reminded = session.continueWithoutMessage({
131 inputId: 'req-44',
132 ephemeral: [{ role: 'user', content: 'Call finish or give_up now.' }],
133})
134await reminded
135```
136
137From the client:
138
139```ts group=harness-inputs-client
140const remindedReceipt = await client.send('Summarize the report.', {
141 inputId: 'req-45',
142 ephemeral: [{ role: 'user', content: 'Answer in three bullets.' }],
143})
144```
145
146- Each model call of the turn gets the messages right after the turn's own message (or the last stored message, for `continueWithoutMessage`), before the answers and tool results of the turn.
147- The transcript, the session log, and the message store never keep them.
148- A retry with the same `inputId` gets the first input, also when its `ephemeral` messages are different.
149- A turn that recovery runs again after a crash has no `ephemeral` messages, because the log does not keep them.
150- From the client, `ephemeral` takes user messages only. On the server, `session.send` and `session.continue` take any message.
151
152To add a note from a hook when the model stops, see [Remind the model without saving the reminder](./turn-control#remind-the-model-without-saving-the-reminder).
153
154## Add a system note from server code
155
156The model needs standing context for a turn: the team's memory, the tenant's rules, or the user's plan. It is not a user message, and it should not go in the transcript. Pass `systemPreamble` to `session.send`. The strings go in ahead of the harness's own system prompts, for this one turn.
157
158```ts group=harness-inputs
159const drafted = session.send('Draft a reply to the ticket.', {
160 inputId: 'req-50',
161 systemPreamble: [
162 'Team memory: keep the tone terse.',
163 'Tenant rule: never promise a refund.',
164 ],
165})
166await drafted
167```
168
169- `systemPreamble` comes from server code only. A client input cannot set it, so client text never reaches the system prompt.
170- The strings go first, ahead of `harness.systemPrompts` and the plugin prompts.
171- The harness keeps them in memory for the turn, like `ephemeral`. The transcript and the session log never store them.
172- A turn that recovery runs again after a crash has no `systemPreamble`, because the log does not keep it.
173
174## Get a typed answer from a turn
175
176Pass `outputSchema` to `session.send`. The turn's `chat()` call gets the schema, and the result has the checked object as `structured`, typed from the schema.
177
178```ts group=harness-inputs
179import { z } from 'zod'
180
181const Ticket = z.object({
182 title: z.string(),
183 priority: z.enum(['low', 'high']),
184})
185
186const triaged = await session.send('Triage: the login page is down.', {
187 inputId: 'req-60',
188 outputSchema: Ticket,
189})
190console.log(triaged.structured?.priority) // 'low' | 'high' | undefined
191```
192
193- `structured` is set when the turn completes. A turn that stops for an approval or another wait has no `structured`.
194- The transcript keeps the answer that `chat()` writes for structured output: the JSON text of the object.
195
196If the object fails the schema, the turn fails:
197
1981. `await triaged` rejects. The error has `code` and `rawText`.
1992. `session.settled({ inputId: 'req-60' })` resolves to `outcome: 'failed'`, with the same `error.code` and `error.rawText`.
200
201The `code` is `structured-output-validation-failed` (the JSON parsed, but the object failed the schema) or `structured-output-parse-failed` (the text was not JSON). `rawText` is the text of the model.
202
203Where the schema applies:
204
205- **One send only.** Thread settings and `overrides` do not keep it. The next turn runs without it.
206- **Server code only.** A schema is code, so clients cannot send it. The HTTP handler and the client protocol do not take `outputSchema`.
207- **A recovered turn runs without it.** The session log keeps only JSON, so a turn that recovery runs again after a crash has no schema. The session writes a `harness:overrides` warning to the log.
208- **A joined steer ignores it.** A `busy: 'steer'` message that joins a running turn uses that turn's settings. A steer that runs as its own turn uses its schema.
209
210## Send a message while a turn runs
211
212With `busy: 'steer'` or `mode: 'steer'`, a message joins the running turn. It reaches the model at the next model call, in the order the messages arrived, and it ends with that turn.
213
214```ts group=harness-inputs
215const running = session.send('Plan the migration.', { inputId: 'req-43' })
216const joined = session.send('Keep it under five steps.', {
217 busy: 'steer',
218 inputId: 'req-44',
219})
220// One turn answers both, so both get its result.
221await Promise.all([running, joined])
222console.log((await session.settled({ inputId: 'req-44' })).operationId === running.id) // true
223```
224
225A message that arrives while the model writes its final answer still gets an answer in the same turn.
226
227Waiting `steer` inputs join before each model call, in the order they arrived. They join as a prefix: the join stops at the first input that has an abort request, or that `turn.canJoin` refuses. The inputs after it wait.
228
229- The `operationId` in the receipt of a `busy: 'steer'` or `mode: 'steer'` message is the running turn. A cancel with that id cancels the turn.
230- Without `turn.canJoin`, a steer from another sender does not join. Its receipt is `queued`, and its `operationId` is its own operation.
231- A `busy: 'steer'` message also has its own operation, `joined`. To stop it before it joins, call `joined.cancel()` or `session.cancel({ operationId: joined.id })`. It does not join, and it settles `aborted` when the running turn ends.
232- The session rejects a cancel that comes after the join started, with `reason: 'not_running'`.
233- A refused or late input runs as its own turn after the running one.
234
235To choose which inputs join, or to add records when they join, see [Choose which messages join a turn](./turn-control#choose-which-messages-join-a-turn).
236
237## Cancel or move a waiting message
238
239A user sends two more messages while a turn runs. Before they run, the user wants to cancel one, and wants the other to reach the running turn now. `session.waitingInputs()` lists the inputs that wait. `cancelInput` cancels one, and `changeInputDelivery` moves one:
240
241```ts group=harness-inputs
242const migration = session.send('Plan the migration.', { inputId: 'req-45' })
243// The turn runs, so these two wait for their own turns.
244const tests = session.send('Then write the tests.', { inputId: 'req-46', mode: 'followUp' })
245const style = session.send('Use tabs, not spaces.', { inputId: 'req-47', mode: 'followUp' })
246await Promise.all([tests.receipt, style.receipt])
247
248for (const input of session.waitingInputs()) {
249 console.log(input.inputId, input.delivery, input.message)
250}
251
252await session.cancelInput({ inputId: 'req-46' })
253await session.changeInputDelivery({ inputId: 'req-47', delivery: 'steer' })
254await migration
255```
256
257- `waitingInputs()` lists the inputs in the order they run: first the steers for the running turn, then the queued turns.
258- `delivery: 'steer'`: the input joins the running turn at the next model call. `'queue'`: it runs as its own turn, after the turns before it.
259- A cancelled input never runs, also after a restart. It settles `aborted`.
260- The log keeps a new delivery, and a restart obeys it.
261- If the input started, or joins the running turn now, the receipt has `status: 'rejected'` and `reason: 'not_waiting'`. To stop it, cancel its operation with `session.cancel({ operationId })`.
262
263A client reads the waiting inputs from the snapshot, and sends the same two inputs:
264
265```ts group=harness-inputs-client
266const { waitingInputs = [] } = await client.snapshot()
267for (const input of waitingInputs) {
268 console.log(input.inputId, input.delivery)
269}
270
271await client.cancelInput({ inputId: 'req-46' })
272await client.changeInputDelivery({ inputId: 'req-47', delivery: 'steer' })
273```
274
275Over `POST control`, they are `{ op: 'cancelInput', inputId }` and `{ op: 'setDelivery', inputId, delivery }`. In these two inputs, `inputId` is the id of the input that waits. A move sends a `harness.input.delivery` event with `inputId` and `delivery`, so every client can update its list.
276
277## Move a running tool call to the background
278
279A long command or a subagent blocks the turn, and the user wants to go on. `session.moveToolCallToBackground()` moves the running tool call to the background:
280
281```ts group=harness-inputs
282const build = session.send('Run the full test suite.', { inputId: 'req-48' })
283// Later, while the `bash` call of that turn runs:
284const moved = await session.moveToolCallToBackground()
285console.log(moved.status) // 'accepted', or 'rejected' with 'not_running'
286await build
287```
288
289- The tool call returns at once. The model gets a short note with the job id, and the turn goes on.
290- The job keeps running. When it ends, the model gets its result as a note, and an idle session starts a new turn.
291- Without an argument, it moves every running call that supports it. Pass `{ toolCallId }` to move one call.
292- `bash` and the single `subagent` tool support it. Other tools keep running as before.
293- With no running call that supports it, the receipt has `status: 'rejected'` and `reason: 'not_running'`.
294- The log keeps each job until it ends. When a crash stops a job, the next host adds the note "Background job call-1 stopped when the host restarted."
295
296The session stays open while a job of this host runs, also when no handle holds it. A sweep with `close: 'whenIdle'` waits for these jobs too. The wake turn of a `bash` job runs as the user whose run started the job.
297
298A client sends `{ op: 'background' }` over `POST control`. It runs no new code, so it needs no `expose` entry:
299
300```ts group=harness-inputs-client
301await fetch('/api/harness/control', {
302 method: 'POST',
303 headers: { 'content-type': 'application/json' },
304 body: JSON.stringify({
305 threadId: 'user-1-thread',
306 input: { op: 'background' },
307 }),
308})
309```
310
311Your own tool can support it too. Pass its work to `detach` from the tool context, and race the two promises:
312
313```ts group=harness-inputs
314const longReport = toolDefinition({
315 name: 'longReport',
316 description: 'Build the monthly report',
317 inputSchema: z.object({}),
318}).server((_input, toolContext) => {
319 const work = new Promise<string>((resolve) => {
320 setTimeout(() => resolve('The report is ready.'), 60_000)
321 })
322 const detach = toolContext?.detach
323 return detach ? Promise.race([work, detach(work)]) : work
324})
325```
326
327## Send context with a message
328
329Your tools often need to know what the user looks at: the open record, the page, or the locale. Send it as the `context` of the input. The session stores it with the input, so a turn that runs again after a restart gets the same value.
330
331On the server, a tool reads it from its tool context:
332
333```ts group=harness-inputs
334import { toolDefinition } from '@tanstack/ai'
335
336const openRecord = toolDefinition({
337 name: 'openRecord',
338 description: 'Read the id of the record that the user has open',
339 inputSchema: z.object({}),
340}).server(async (_input, toolContext) => {
341 const context = toolContext?.context
342 const recordId =
343 typeof context === 'object' && context !== null && 'recordId' in context
344 ? String(context.recordId)
345 : 'none'
346 return { recordId }
347})
348
349const records = defineHarness({
350 name: 'acme/records',
351 adapter: openaiText('gpt-6.1-sol'),
352 tools: [openRecord],
353})
354const recordSession = await host.open(records, { threadId: 'user-1-records' })
355
356await recordSession.send('Summarize the record I have open.', {
357 context: { recordId: 'inv-42' },
358})
359```
360
361`send` takes `context` in every mode. A client sends it in a `control` input:
362
363```ts group=harness-inputs-client
364await fetch('/api/harness/control', {
365 method: 'POST',
366 headers: { 'content-type': 'application/json' },
367 body: JSON.stringify({
368 threadId: 'user-1-thread',
369 input: {
370 op: 'prompt',
371 message: 'Summarize the record I have open.',
372 context: { recordId: 'inv-42' },
373 },
374 }),
375})
376```
377
378On `POST run`, the AG-UI `forwardedProps` of the request are the `context`, for example `useChat({ forwardedProps })`. See [Connect clients to a harness](./connect).
379
380- The `context` is part of the input for the `inputId` check. An input with the same id and another `context` gets `'conflict'`.
381- When `HarnessConfig.context` and the input `context` are both plain objects, tools get them merged, and the harness value wins for a key in both. In all other cases, tools get the harness value. If the harness has no value, tools get the input value.
382- The harness adds the run of the turn to a plain-object context as `run`, and it replaces a `run` key that a client sent. A context that is not a plain object gets no `run`, so tools that read `ctx.context.run` fail. See [Act as the user of a run](./plugins#act-as-the-user-of-a-run).
383- Plugins and the router get it as `turn.context`. See [Pick the model of a turn](./plugins#pick-the-model-of-a-turn).
384- The `context` is client data, so do not trust it. Who sent the input comes from the server: the user of the request, or of the session handle. See [Access and tenants](./access). To check the `context` or replace it, see [Check an input on the server](#check-an-input-on-the-server).
385
386## Check an input on the server
387
388Give the host `acceptInput`. It gets each input after the access check, and before the log keeps the input. Return the input, a changed input, or `{ refuse: reason }`:
389
390```ts group=harness-inputs
391// Your own data: the plan of each user.
392const plans = new Map([['ada', 'pro']])
393
394const checkedHost = createHarnessHost({
395 persistence: memoryPersistence(),
396 acceptInput: (input, { user }) => {
397 if (input.op !== 'prompt') return input
398 if (typeof input.message === 'string' && input.message.length > 20_000) {
399 return { refuse: 'message_too_long' }
400 }
401 // The server sets the plan. A plan that the client sent is dropped.
402 return { ...input, context: { plan: plans.get(user?.id ?? '') ?? 'free' } }
403 },
404})
405```
406
407What you return decides what happens:
408
409- The same input: the session stores it as it came.
410- A changed input with the same `op`: the log, the turn, and the tools get the changed input. An input with another `op` is refused.
411- `{ refuse: reason }`: nothing is stored. The receipt has `status: 'rejected'` and your `reason`, and `await turn` rejects with `InputRejectedError`.
412
413`acceptInput` also gets `threadId`. It runs for the calls of a session from `host.open`, for `host.submit`, and so for every `POST control` and `POST run` request. Inputs that the harness makes itself, such as a scheduled input when it runs, skip it.
414
415On the client, a refused `control` input answers with the rejected receipt:
416
417```ts group=harness-inputs-client
418const response = await fetch('/api/harness/control', {
419 method: 'POST',
420 headers: { 'content-type': 'application/json' },
421 body: JSON.stringify({
422 threadId: 'user-1-thread',
423 input: { op: 'prompt', message: 'Summarize the report.' },
424 }),
425})
426const sent = await response.json()
427if (sent.status === 'rejected') console.warn(sent.reason) // 'message_too_long'
428```
429
430A refused `POST run` answers `409` with `{ error: reason }`, so `useChat` gets an error.
431
432- The `inputId` check compares the changed input. Return the same change for the same input: no random values and no times.
433- A retry of a changed prompt on another host, or after a restart, gets `'conflict'`.
434
435## What you have now
436
437- Retries that never run a prompt twice.
438- The outcome of each input by its id, also after a restart.
439- Typed answers from a turn, checked against your schema.
440- Messages that join a running turn in order.
441- Waiting messages that a user can cancel, or move into the running turn, and running jobs that a user can move to the background.
442- Context from the client that tools read, also after a restart.
443- A server check that changes or refuses each input before the log keeps it.