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

define.ts

612 lines23.2 KB

1import { assertMetadataSchema } from './session-entry'
2import type {
3 AgentLoopStrategy,
4 AnyChatMiddleware,
5 AnyTextAdapter,
6 AnyTool,
7 InferToolInput,
8 InterruptDefinition,
9 KeyedAdapter,
10 ModelMessage,
11 PromptCacheOptions,
12 ReasoningOption,
13 SchemaInput,
14 SubagentRouterPick,
15 SubagentsBag,
16 SystemPrompt,
17} from '@tanstack/ai'
18import type { AnyAgent } from './agents'
19import type { ProjectOptions, ReduceOptions } from './log'
20import type { MediaOptions } from './media'
21import type { HarnessPlugin, PluginMetadataCheck, PluginModel } from './plugins'
22import type { HarnessSession } from './session/index'
23import type { MetadataOf } from './session-entry'
24import type { HarnessTurnOptions, RecoverHook } from './turn'
25import type {
26 BusyPolicy,
27 HarnessUser,
28 ThreadSettings,
29 UserInput,
30} from './types'
31​
32/**
33 * The `subagents` option: the same as `chat({ subagents })`, without
34 * `binding` and `keys`. The session binds its own provider keys.
35 */
36export type HarnessSubagents<TSubagents extends ReadonlyArray<AnyAgent>> = Omit<
37 SubagentsBag<TSubagents>,
38 'binding' | 'keys'
39> & {
40 /**
41 * `false`: the agent tools offer the model no `background` field, so
42 * every child the model calls ends inside the turn that called it.
43 * Default: `true`.
44 */
45 background?: boolean
47​
48/**
49 * What `routing.router` gets: the fields of the `subagents.router` context,
50 * plus the harness fields of the turn.
51 */
52export interface HarnessRouterContext<TMetadataSchema = any> {
53 /** The model messages of the turn: the history, then the new user message. */
54 messages: Array<ModelMessage>
55 /**
56 * The root agents of this turn, in registration order: the harness
57 * `agents`, then the `agents` of session plugins, then of turn plugins. An
58 * agent that is only in `subagents` is not in this list.
59 */
60 agents: ReadonlyArray<AnyAgent>
61 /** Aborted when the turn is cancelled. */
62 abortSignal?: AbortSignal
63 session: SessionWithMetadata<TMetadataSchema>
64 /**
65 * The user input of the turn as sent: text, or content parts. `undefined`
66 * for a turn with no new user message.
67 */
68 input?: UserInput
69 /** The id of the turn operation. */
70 operationId: string
71 /** The id of the turn input, when the turn has one. */
72 inputId?: string
73 /** Who sent the turn input. Default: the user that opened the session. */
74 user?: HarnessUser
75 /** The `context` of the turn input. Client data: do not trust it. */
76 context?: unknown
77 /** The main text adapter of the turn, with the user's keys bound. */
78 adapter: AnyTextAdapter
79 /**
80 * Call a model to pick the agent, as `ctx.model.chat` of a plugin does.
81 * The call has the keys of the sender and the signal of the turn. Its
82 * usage counts in the session (`session.usage().bySource` under
83 * `router`) and in the turn. The `run` option is ignored: the call is
84 * always for this turn.
85 *
86 * @example
87 * ```ts
88 * router: async ({ model, messages }) => {
89 * const { text } = await model.chat({
90 * options: {
91 * messages,
92 * systemPrompts: ['Answer "billing" or "support". Nothing else.'],
93 * },
94 * label: 'pick',
95 * })
96 * return text.trim() === 'billing' ? 'billing' : undefined
97 * }
98 * ```
99 */
100 model: PluginModel
101 /**
102 * The root agent that answers the turns of this thread since the last
103 * handoff. `undefined`: the main model answers. Return `undefined` from
104 * the router to send the turn to it.
105 *
106 * The `agents()` plugin has its own primary agent (its `agent` config and
107 * `/agent`). That one changes the prompt and tools of the main model. It
108 * is not this value, and neither one changes the other.
109 */
110 activeAgent?: string
112​
113/**
114 * What `routing.router` returns: a pick of `subagents.router`, a handoff, or
115 * `undefined`.
116 * - `undefined`: the active agent answers, else the main model.
117 * - One agent name: that agent answers, and it becomes the active agent.
118 * - `'main'`: the main model answers, and no agent is active.
119 * - `{ handoff, note }`: a handoff to that root agent (or `'main'`). The log
120 * keeps the note. Then the target answers, and it becomes the active agent.
121 * - `{ name, input }`, a list, `{ names }`, or `{ steps }`: those agents
122 * answer. The active agent does not change.
123 */
124export type HarnessRouterPick =
125 | SubagentRouterPick
126 | { handoff: string; note?: string }
127 | undefined
128​
129/**
130 * The `routing` option. The other fields mean the same as in `subagents`.
131 * `limits` defaults to `subagents.limits`. The `strategy` of `subagents` is
132 * not here: use `afterAgentsAnswer`.
133 */
134export interface HarnessRouting<TMetadataSchema = any> extends Pick<
135 SubagentsBag,
136 'order' | 'limits' | 'sandbox'
137> {
138 /**
139 * Pick who answers the turn: `undefined` (the active agent), `'main'`, an
140 * agent name, a list of names, `{ names, order }`, `{ steps }`, or
141 * `{ handoff, note }`. Give an agent with `inputSchema` its input with
142 * `{ name, input }`. A throw fails the turn. See {@link HarnessRouterPick}.
143 */
144 router: (
145 ctx: HarnessRouterContext<TMetadataSchema>,
146 ) => HarnessRouterPick | Promise<HarnessRouterPick>
147 /**
148 * What happens after the picked agents answer. `'end-turn'`: the turn
149 * ends. `'main-answers'`: the main model answers next, in the same turn,
150 * with their answers in the transcript, and it keeps its `subagents`.
151 * Default `'end-turn'`.
152 */
153 afterAgentsAnswer?: 'end-turn' | 'main-answers'
154 /**
155 * Let the models and your code hand the turn to a person. When true, the
156 * `to` of the `handoff` tool also takes `{ human: true }`, and
157 * `ctx.harness.handoff({ to: { human: true } })` and `run.handoff` open a
158 * `human` wait. When false, the `handoff` tool offers only the agents and
159 * `'main'`, and a handoff to a person rejects. Default `false`.
160 */
161 allowHandoffToHuman?: boolean
162 /**
163 * Give the main model and each root agent the `handoff` tool. When false,
164 * no model gets it, and an app tool can use the name `handoff`. The
165 * router and your code (`ctx.harness.handoff`, `run.handoff`) can still
166 * hand off. Default `true`.
167 */
168 giveModelsHandoffTool?: boolean
170​
171/**
172 * Limits for one input, and how the host folds your own log records.
173 */
174export interface HarnessDurability<
175 TMetadataSchema = any,
176 TLogState = undefined,
177> {
178 /**
179 * Total attempts for one input, the first run included. Each recovery after
180 * a crash is one more attempt. When no attempt is left, the input fails
181 * with code `'attempts_exhausted'`. Default 10.
182 */
183 maxAttempts?: number
184 /**
185 * Time from the first run of an input until it fails with code
186 * `'timeout'`, in milliseconds. Retries do not reset it. Default: no
187 * timeout.
188 */
189 timeoutMs?: number
190 /**
191 * Decide how an input that a crashed host left recovers: an input that
192 * never ran, and a turn whose host stopped. The context has the decision
193 * the harness takes by default. Return `undefined` to keep it. Return
194 * `{ action: 'run', overrides }` to run the turn with `TurnOverrides`.
195 */
196 recover?: RecoverHook<TMetadataSchema>
197 /**
198 * The tool result that recovery gives a `replay: 'never'` tool call that
199 * a crash cut: the content and the error of its tool message. Default: a
200 * JSON note that the tool may or may not have run.
201 */
202 interruptedToolResult?: string
203 /**
204 * The tool result of each tool call of an answer that stopped at the output
205 * limit (finish reason `length`): the content and the error of its tool
206 * message. The function form gets the call. Such a call never runs, also
207 * with `replay: 'safe'`. When set, the answer keeps its calls, each cut
208 * call gets this text, and the turn calls the model again. Recovery gives
209 * the same text to a cut call with no result in the log. Not set: a cut
210 * answer ends the turn, and recovery uses the default. Default: `'The answer was cut off at the output limit before
211 * this tool call was complete. The call did not run.'`
212 */
213 truncatedToolResult?:
214 | string
215 | ((call: { toolCallId: string; toolName: string }) => string)
216 /**
217 * Continue an answer that a crash cut. Before the recovered attempt runs,
218 * recovery adds the part of the answer that the log has as an assistant
219 * message, then one user message for each note, in order, in one append.
220 * The model goes on after the notes. The assistant message has the answer
221 * text and each signed thinking block (a finished block with its
222 * signature, as the transcript keeps thinking), so the provider can replay
223 * it. A thinking block with no signature and tool calls are not kept. An
224 * attempt that streamed no answer text and no signed thinking (for example
225 * only thinking with no signature) runs again with no partial and no note.
226 * Signed thinking alone is enough to continue. A string `note` is one
227 * note. Default `false`. The default note: `'The previous answer was cut
228 * off. Continue exactly where it stopped, without repeating it.'`
229 */
230 continueCutOff?: boolean | { note?: string | ReadonlyArray<string> }
231 /**
232 * Run again an agent that the model started with `background: true`, when
233 * the host stopped during the run. The next host continues it with the
234 * same `subagentRunId`, as a start with `runAgainAfterCrash: true`: the agent code runs
235 * again from its start, `ctx.chat` continues from its saved transcript,
236 * and `ctx.harness.step` keeps its values. A tool call that finished does
237 * not run again. A tool call that ran at the stop runs again. The turn
238 * plugins of the turn that started it are gone. `false`: the run fails, as
239 * a start without `runAgainAfterCrash`. A child that did not start yet still starts.
240 * Default `true`.
241 */
242 resumeBackgroundAgents?: boolean
243 /**
244 * The waits of an agent that the main model calls as a tool: an approval,
245 * a question, a sign-in, an app interrupt, a client tool, and `step.ask`.
246 * `true`: each one is a wait of the turn, in `snapshot().pendingWaits`.
247 * After the answer, the agent goes on from where it stopped, and its
248 * result goes to the main model. `false`: the agent does not wait. A call
249 * that needs an approval gets a tool error, and `step.ask` throws.
250 * Default `true`.
251 */
252 agentToolWaits?: boolean
253 /**
254 * How a durable host folds your own log records into the model context of
255 * each session.
256 */
257 addRecordsToModelContext?: ProjectOptions
258 /**
259 * A fold of every host record of the log of a session tree: the root
260 * thread and its child threads (agent chains and subagent runs), in log
261 * order. Read it with `session.logState()`, or with `view.logState()` of
262 * `host.observe`, on any machine.
263 */
264 logState?: ReduceOptions<TLogState>
266​
267/**
268 * What `defineHarness` takes. Where it overlaps with `chat()`, the option
269 * names and types are the same.
270 */
271export interface HarnessConfig<
272 TAdapter extends AnyTextAdapter = AnyTextAdapter,
273 TAgents extends ReadonlyArray<AnyAgent> = ReadonlyArray<AnyAgent>,
274 TSubagents extends ReadonlyArray<AnyAgent> = ReadonlyArray<AnyAgent>,
275 TMetadataSchema = undefined,
276 TTools extends ReadonlyArray<AnyTool> = ReadonlyArray<AnyTool>,
277 TLogState = undefined,
278> {
279 /** A stable name, for example `'acme/studio'`. */
280 name: string
281 /** What the harness does. Shown when another agent can call it. */
282 description?: string
283 /**
284 * The main agent-loop model, the same as `chat({ adapter })`. A
285 * `keyedAdapter(...)` is built for each turn with the user's own key: the
286 * key saved with `/connect <provider>`, else the provider's env var.
287 * Leave it out when a plugin `adapter()` picks the model of every turn. A
288 * turn that gets no model from any of them fails.
289 */
290 adapter?: TAdapter | KeyedAdapter<TAdapter>
291 /**
292 * Models a thread can pick by name with `session.updateThreadSettings({ model })`.
293 * The stored name picks the model of each turn, after `overrides.adapter`
294 * and before a plugin `adapter()`.
295 */
296 models?: Record<string, AnyTextAdapter | KeyedAdapter<AnyTextAdapter>>
297 systemPrompts?: Array<SystemPrompt>
298 tools?: TTools
299 middleware?: ReadonlyArray<AnyChatMiddleware>
300 /**
301 * When a turn stops calling the model. Defaults to `maxIterations(50)`.
302 * Without `durability.truncatedToolResult`, the turn also stops after an
303 * answer cut at the output limit.
304 */
305 agentLoopStrategy?: AgentLoopStrategy
306 /**
307 * How the server tools of one model call run, the same as
308 * `chat({ toolExecution })`. `'parallel'` starts them together.
309 * `'sequential'` runs them one at a time, in call order. Default
310 * `'parallel'`.
311 */
312 toolExecution?: 'parallel' | 'sequential'
313 modelOptions?: TAdapter['~types']['providerOptions']
314 /**
315 * Automatic prompt caching for every session, the same as
316 * `chat({ promptCache })`. Default `'short'`. `'none'` turns it off. A
317 * `key` here is shared by all sessions, so usually leave it out: then each
318 * session uses its threadId as the key.
319 */
320 promptCache?: PromptCacheOptions
321 /**
322 * How hard the main model thinks on every turn, as the adapter gets it in
323 * `TextOptions`. Not set: no reasoning is sent, and the provider default
324 * applies. `overrides.reasoning` of a turn replaces it.
325 */
326 reasoning?: ReasoningOption
327 interrupts?: ReadonlyArray<InterruptDefinition<any, any, any, any>>
328 /**
329 * Runtime context passed to middleware hooks and server tools. When this
330 * and the `context` of a turn input are both plain objects, a turn gets
331 * both merged, and this value wins for a key in both, so a client cannot
332 * replace a server value. Otherwise a turn gets this value when it is set,
333 * else the input's.
334 */
335 context?: unknown
336 /**
337 * Typed agents the session can run from code, commands, plugins, and
338 * exposed clients: `session.agents.<name>.run(input)`.
339 */
340 agents?: TAgents
341 /**
342 * Agents the main model can call as tools, the same as `chat({ subagents })`.
343 * They are also registered in `session.agents`.
344 */
345 subagents?: HarnessSubagents<TSubagents>
346 /**
347 * A router for each new turn. It sends the turn to the main model, or to
348 * root agents: the harness `agents` and the `agents` of plugins. A resolve
349 * continues the turn it answers, so it does not call the router.
350 */
351 routing?: HarnessRouting<TMetadataSchema>
352 /** Called once per session, so every session gets fresh plugin instances. */
353 plugins?: () => ReadonlyArray<
354 HarnessPlugin & PluginMetadataCheck<MetadataOf<TMetadataSchema>>
355 >
356 /**
357 * The shape of the `metadata` of the session index entry of each thread,
358 * as a Standard Schema (for example a zod object). Each write checks it:
359 * `host.sessions.update`, the `update` op of `POST sessions`, and
360 * `updateIndexEntry` of plugins and sessions. A write it refuses throws
361 * `SessionMetadataError` and writes nothing. It also types the metadata
362 * of those writes, of `session.indexEntry()`, of the hooks, and of a client
363 * made with `createHarnessClient<typeof harness>`.
364 */
365 metadataSchema?: TMetadataSchema
366 /** What a `prompt` does while a chat turn runs. Default `'queue'`. */
367 busy?: BusyPolicy
368 /**
369 * Attempt and time limits for each input on a durable host, and how that
370 * host folds your own log records (`addRecordsToModelContext` and `logState`).
371 */
372 durability?: HarnessDurability<TMetadataSchema, TLogState>
373 /** Hooks that control a chat turn: retries, joins, and the end of a turn. */
374 turn?: HarnessTurnOptions<TMetadataSchema>
375 /**
376 * Files sent to a turn, and media agents make: the size limit, the kinds a
377 * user can send, the kinds the model reads, and an optional transcriber for
378 * audio the model cannot read.
379 */
380 media?: MediaOptions
381 /** What clients may call. Nothing is exposed by default. */
382 expose?: {
383 agents?: ReadonlyArray<TAgents[number]['name'] | TSubagents[number]['name']>
384 /**
385 * The thread settings a client may change with a `configure` input. An
386 * input with any other field is refused with `not_exposed`. Server code
387 * that calls `session.updateThreadSettings()` can change every field. `plugins` and
388 * `instructions` let a client turn off a plugin and write into the
389 * system prompt, so expose them only to clients you trust.
390 */
391 settings?: ReadonlyArray<keyof ThreadSettings>
392 /**
393 * The plugin config keys a client may set with a `config` input, for
394 * example `client.setPluginSetting({ key: 'model', value: 'fast' })`. An input with any other
395 * key is refused with `not_exposed`. Server code that calls
396 * `session.setPluginSetting()` can set every key. Warning: `mode` of
397 * `permissions()` lets a client turn approvals off with `bypass`. Keep
398 * `mode` on the server, or expose it only to clients you trust.
399 */
400 config?: ReadonlyArray<string>
401 /**
402 * The commands a client may run with a `command` input, for example
403 * `client.runCommand({ name: 'undo' })`, or `/undo` in a session view on a
404 * client. An input with any other command is refused with `not_exposed`.
405 * Server code that calls `session.runCommand()` can run every command. Warning:
406 * `/mode bypass` of `permissions()` turns approvals off, so expose `mode`
407 * only to clients you trust. Plugins add their commands when a session
408 * opens, so `defineHarness` does not check these names.
409 */
410 commands?: ReadonlyArray<string>
411 /**
412 * The harness `tools` a client may run with a `tool` input, with no model
413 * turn, for example from a schedule or a webhook. An input for any other
414 * tool is refused with `not_exposed`. The call goes through the same
415 * middleware, input check, and `permissions()` rules as a model call.
416 */
417 tools?: ReadonlyArray<TTools[number]['name']>
418 /**
419 * The host record types a client may add with an `append` input, for
420 * example a webhook that adds `{ type: 'app.signal', text }`. An input
421 * with any other type, or with a `thread` field, is refused with
422 * `not_exposed`. Server code that calls `session.appendRecords()` can add every
423 * type. The log keeps the records, and `durability.addRecordsToModelContext` decides
424 * what the model sees of them.
425 */
426 records?: ReadonlyArray<string>
427 }
429​
430const HARNESS_KIND = 'tanstack-ai-harness' as const
431​
432/** An immutable harness definition. Importing it starts nothing. */
433export type HarnessDefinition<
434 TAdapter extends AnyTextAdapter = AnyTextAdapter,
435 TAgents extends ReadonlyArray<AnyAgent> = ReadonlyArray<AnyAgent>,
436 TSubagents extends ReadonlyArray<AnyAgent> = ReadonlyArray<AnyAgent>,
437 TMetadataSchema = undefined,
438 TTools extends ReadonlyArray<AnyTool> = ReadonlyArray<AnyTool>,
439 TLogState = undefined,
440> = Readonly<
441 HarnessConfig<
442 TAdapter,
443 TAgents,
444 TSubagents,
445 TMetadataSchema,
446 TTools,
447 TLogState
448 >
449> & {
450 readonly kind: typeof HARNESS_KIND
451 readonly version: 1
453​
454/** A harness definition with any type parameters. */
455export type AnyHarness = HarnessDefinition<
456 any,
457 any,
458 any,
459 any,
460 ReadonlyArray<AnyTool>,
461 any
463​
464/** A session whose harness has the metadata schema `TMetadataSchema`. */
465export type SessionWithMetadata<TMetadataSchema> = HarnessSession<
466 HarnessDefinition<any, any, any, TMetadataSchema, ReadonlyArray<AnyTool>, any>
468​
469// `durability.logState` makes the log state type invariant, so each pattern
470// below takes any log state (the last `any`).
471​
472/** The type of the session index `metadata` of a harness. */
473export type SessionMetadataOf<THarness> =
474 THarness extends HarnessDefinition<
475 any,
476 any,
477 any,
478 infer TMetadataSchema,
479 ReadonlyArray<AnyTool>,
480 any
481 >
482 ? MetadataOf<TMetadataSchema>
483 : Record<string, unknown>
484​
485/** Every agent a harness registers, as a union. */
486export type HarnessAgentsOf<THarness> =
487 THarness extends HarnessDefinition<
488 any,
489 infer TAgents,
490 infer TSubagents,
491 any,
492 ReadonlyArray<AnyTool>,
493 any
494 >
495 ? TAgents[number] | TSubagents[number]
496 : never
497​
498/** The `tools` of a harness, as a union. */
499export type HarnessToolsOf<THarness> =
500 THarness extends HarnessDefinition<any, any, any, any, infer TTools, any>
501 ? TTools[number]
502 : never
503​
504/**
505 * The state of the `durability.logState` fold of a harness, as
506 * `session.logState()` returns it. `undefined` for a harness without `durability.logState`.
507 */
508export type HarnessLogStateOf<THarness> = THarness extends {
509 durability?: { logState?: ReduceOptions<infer TLogState> }
511 ? TLogState
512 : undefined
513​
514/**
515 * The input of the harness tool `TName`, from its input schema. `unknown`
516 * for a tool that is not in `tools`, for example a plugin tool.
517 */
518export type HarnessToolInput<THarness, TName> = [
519 Extract<HarnessToolsOf<THarness>, { name: TName }>,
520] extends [never]
521 ? unknown
522 : InferToolInput<Extract<HarnessToolsOf<THarness>, { name: TName }>>
523​
524/** True for a value made with `defineHarness`. */
525export function isHarnessDefinition(value: unknown): value is AnyHarness {
526 return (
527 typeof value === 'object' &&
528 value !== null &&
529 (value as { kind?: unknown }).kind === HARNESS_KIND &&
530 (value as { version?: unknown }).version === 1
531 )
533​
534/**
535 * Define a harness: a reusable, typed agent configuration. Use the same option
536 * names as `chat()`, plus `agents`, `plugins`, `busy`, `expose`, and `media`.
537 *
538 * @example
539 * ```ts
540 * const studio = defineHarness({
541 * name: 'acme/studio',
542 * adapter: anthropicText('claude-sonnet-4-5'),
543 * agents: [heroImage],
544 * subagents: { agents: [researcher] },
545 * })
546 * ```
547 */
548export function defineHarness<
549 TAdapter extends AnyTextAdapter = AnyTextAdapter,
550 const TAgents extends ReadonlyArray<AnyAgent> = readonly [],
551 const TSubagents extends ReadonlyArray<AnyAgent> = readonly [],
552 TMetadataSchema extends SchemaInput | undefined = undefined,
553 const TTools extends ReadonlyArray<AnyTool> = readonly [],
554 TLogState = undefined,
555>(
556 config: HarnessConfig<
557 TAdapter,
558 TAgents,
559 TSubagents,
560 TMetadataSchema,
561 TTools,
562 TLogState
563 >,
564): HarnessDefinition<
565 TAdapter,
566 TAgents,
567 TSubagents,
568 TMetadataSchema,
569 TTools,
570 TLogState
571> {
572 if (config.name.trim() === '') {
573 throw new Error('defineHarness requires a non-empty name')
574 }
575 assertMetadataSchema(`defineHarness "${config.name}"`, config.metadataSchema)
576 const byName = new Map<string, AnyAgent>()
577 for (const agent of [
578 ...(config.agents ?? []),
579 ...(config.subagents?.agents ?? []),
580 ]) {
581 const existing = byName.get(agent.name)
582 if (existing && existing !== agent) {
583 throw new Error(
584 `defineHarness "${config.name}": two different agents are named "${agent.name}".`,
585 )
586 }
587 byName.set(agent.name, agent)
588 }
589 for (const name of config.expose?.agents ?? []) {
590 if (!byName.has(name)) {
591 throw new Error(
592 `defineHarness "${config.name}": expose.agents names "${name}", which is not a registered agent.`,
593 )
594 }
595 }
596 const toolNames = new Set((config.tools ?? []).map((tool) => tool.name))
597 for (const name of config.expose?.tools ?? []) {
598 if (!toolNames.has(name)) {
599 throw new Error(
600 `defineHarness "${config.name}": expose.tools names "${name}", which is not in tools.`,
601 )
602 }
603 }
604 for (const type of config.expose?.records ?? []) {
605 if (type.startsWith('harness.')) {
606 throw new Error(
607 `defineHarness "${config.name}": expose.records names "${type}", but the harness owns the record types that start with "harness.".`,
608 )
609 }
610 }
611 return Object.freeze({ ...config, kind: HARNESS_KIND, version: 1 as const })