Open History to see the last commit
1import type {
2 AgentProduces,
3 DefinedAgent,
4 InferSchemaType,
5 SchemaInput,
6 StreamChunk,
7 SubagentRunContext,
8} from '@tanstack/ai'
9import { askWithoutSession, stepRunWithoutSession } from './durable-tool'
10import { waitUntil } from './utils'
11import type { ToolStep } from './durable-tool'
12import type { HandoffOptions } from './handoff'
13import type {
14 AgentRunOptions,
15 AgentStartOptions,
16 RunArgs,
17} from './session/types'
18import type { AgentRun, RunContext } from './types'
19import type { PluginState } from './plugins'
20import type { AnyHarness } from './define'
21
22/** Any agent made with `defineAgent`, with its types kept. */
23export type AnyAgent = DefinedAgent<any, any, any, any, any, any, any>
24
25/** The input an agent takes: its `inputSchema` type, or `undefined`. */
26export type AgentInputOf<TAgent> = TAgent extends {
27 inputSchema?: infer TSchema
28}
29 ? TSchema extends SchemaInput
30 ? InferSchemaType<TSchema>
31 : undefined
32 : undefined
33
34/**
35 * What running an agent resolves to:
36 * - its `outputSchema` type, when it has one;
37 * - else the value its promise `run` resolves to;
38 * - else the child's text.
39 */
40export type AgentResultOf<TAgent> =
41 TAgent extends DefinedAgent<
42 any,
43 any,
44 infer TSchema,
45 any,
46 any,
47 infer TResult,
48 any
49 >
50 ? TSchema extends SchemaInput
51 ? InferSchemaType<TSchema>
52 : unknown extends TResult
53 ? string
54 : TResult
55 : unknown
56
57/** A read-only view of the agents a session can run. */
58export interface AgentRegistryView {
59 /** Every agent, in registration order. */
60 list: () => ReadonlyArray<AnyAgent>
61 /** The agent named `name`, or `undefined`. */
62 get: (name: string) => AnyAgent | undefined
63 /** The first agent whose `produces` matches, or `undefined`. */
64 find: (query: { produces: AgentProduces }) => AnyAgent | undefined
65}
66
67/**
68 * The agents of one session, with the owner of each (the harness, or a
69 * plugin name). Adding a name twice with two different agents is an error that
70 * names both owners. Adding the same agent object twice is allowed, so an
71 * agent can sit in both `agents` and `subagents.agents`.
72 */
73export class AgentRegistry implements AgentRegistryView {
74 private readonly agents = new Map<
75 string,
76 { agent: AnyAgent; owner: string }
77 >()
78
79 add(agent: AnyAgent, owner: string): void {
80 const existing = this.agents.get(agent.name)
81 if (existing && existing.agent !== agent) {
82 throw new Error(
83 `Duplicate agent "${agent.name}": first owner ${existing.owner}, second owner ${owner}.`,
84 )
85 }
86 if (!existing) this.agents.set(agent.name, { agent, owner })
87 }
88
89 /** Add `owner`'s agent, or replace it. A name another owner has throws. */
90 set(agent: AnyAgent, owner: string): void {
91 const existing = this.agents.get(agent.name)
92 if (existing && existing.owner !== owner) {
93 throw new Error(
94 `Agent "${agent.name}" belongs to ${existing.owner}. ${owner} cannot replace it.`,
95 )
96 }
97 this.agents.set(agent.name, { agent, owner })
98 }
99
100 /** Remove `owner`'s agent `name`. Another owner's name does nothing. */
101 delete(name: string, owner: string): void {
102 if (this.agents.get(name)?.owner === owner) this.agents.delete(name)
103 }
104
105 /** Remove every agent that the harness itself did not add. */
106 deletePluginAgents(): void {
107 for (const [name, entry] of this.agents) {
108 if (entry.owner !== 'the harness') this.agents.delete(name)
109 }
110 }
111
112 list(): ReadonlyArray<AnyAgent> {
113 return [...this.agents.values()].map((entry) => entry.agent)
114 }
115
116 get(name: string): AnyAgent | undefined {
117 return this.agents.get(name)?.agent
118 }
119
120 /** Who added the agent `name`: `'the harness'` or a plugin name. */
121 ownerOf(name: string): string | undefined {
122 return this.agents.get(name)?.owner
123 }
124
125 find(query: { produces: AgentProduces }): AnyAgent | undefined {
126 return this.list().find((agent) => agent.produces === query.produces)
127 }
128
129 /** A copy for one chat turn, so turn plugins can add agents for that turn only. */
130 fork(): AgentRegistry {
131 const copy = new AgentRegistry()
132 for (const [name, entry] of this.agents) copy.agents.set(name, entry)
133 return copy
134 }
135}
136
137/**
138 * Start one agent: a definition, typed from its schemas, or a name the
139 * session knows, untyped.
140 */
141export interface AgentCall<TOptions> {
142 <TAgent extends AnyAgent>(
143 agent: TAgent,
144 ...args: RunArgs<TAgent, TOptions>
145 ): AgentRun<AgentResultOf<TAgent>>
146 (agent: string, input?: unknown, options?: TOptions): AgentRun<unknown>
147}
148
149/** How a group of agents runs. */
150export interface AgentGroupOptions {
151 /** How many children run at the same time. Default: all of them. */
152 concurrency?: number
153 /**
154 * `'cancel-siblings'` (default): the first failure cancels the other
155 * children, and `group` rejects with that error. `'collect'`: every child
156 * runs to its end, and `group` resolves to one entry per child.
157 */
158 onFailure?: 'cancel-siblings' | 'collect'
159 /**
160 * The durable name of the group in the run that starts it. Default: the
161 * order of the `group` calls in that run.
162 */
163 key?: string
164}
165
166/** One child of a `group` with `onFailure: 'collect'`. */
167export type AgentSettled<TResult> =
168 | { ok: true; value: TResult }
169 | { ok: false; error: unknown }
170
171/** The children of one `group` call. */
172export interface AgentGroup {
173 /** Start a child of the group. Its run is like the run of `start`. */
174 start: AgentCall<AgentStartOptions>
175}
176
177/**
178 * Start agents and run them: `start` in the background, `run` and `group` to
179 * get the results. `ctx.harness.agents` in agent code and `ctx.agents` in a
180 * plugin have this shape.
181 */
182export interface AgentActions {
183 /**
184 * Start `agent` (a definition, or a name the session knows) in the
185 * background, and return its run at once. In agent code, the child counts
186 * against the subagent tree budget of the run that starts it. Over the
187 * budget, `start` throws and nothing starts.
188 */
189 start: AgentCall<AgentStartOptions>
190 /**
191 * `start` without a wake turn. Await the run to get the result. The run
192 * can still be cancelled and get messages.
193 */
194 run: AgentCall<AgentRunOptions>
195 /**
196 * Run children together. `body` starts them with `g.start` and returns
197 * their runs. `group` resolves to their results, in the same order. Every
198 * child that `body` started settles before `group` returns.
199 */
200 group: {
201 <const TRuns extends ReadonlyArray<AgentRun<unknown>>>(
202 options: AgentGroupOptions & { onFailure: 'collect' },
203 body: (g: AgentGroup) => TRuns | Promise<TRuns>,
204 ): Promise<{
205 -readonly [K in keyof TRuns]: AgentSettled<Awaited<TRuns[K]>>
206 }>
207 <const TRuns extends ReadonlyArray<AgentRun<unknown>>>(
208 options: AgentGroupOptions & { onFailure?: 'cancel-siblings' },
209 body: (g: AgentGroup) => TRuns | Promise<TRuns>,
210 ): Promise<{ -readonly [K in keyof TRuns]: Awaited<TRuns[K]> }>
211 }
212}
213
214/** What a harness session adds to an agent run that it starts from code. */
215export interface HarnessAgentContext {
216 /**
217 * The steps of the run. In a run started with `runAgainAfterCrash: true`, a
218 * finished step returns its stored value when the run
219 * runs again, and `fn` does not run again. Else `fn` runs each time,
220 * and `sleep` waits its full time.
221 */
222 step: ToolStep
223 /** Start and run agents, as children of this run. */
224 agents: AgentActions
225 /**
226 * Hand the turn to another root agent, or to `'main'` (the main model).
227 * The target answers next, in this turn, and the later turns go to it.
228 * `{ human: true }` hands it to a person, when `routing.allowHandoffToHuman` is true:
229 * the turn ends `interrupted`, and the session pauses until an operator
230 * answers the `human` wait.
231 * It works in a root agent that answers a turn of a harness with
232 * `routing`. Anywhere else it throws. It throws for a target that is not a
233 * root agent too.
234 *
235 * @example
236 * ```ts
237 * await ctx.harness.handoff({ to: 'billing', note: 'Refund for order 42' })
238 * ```
239 */
240 handoff: (options: HandoffOptions) => Promise<void>
241 /**
242 * State that the agents of one session share, by `key`. The session log
243 * keeps it, so it survives a restart, and a fork of the thread has it.
244 * Before the first update, `get` gives `initial`. The value is JSON.
245 *
246 * @example
247 * ```ts
248 * const seen = ctx.harness.state({ key: 'seen', initial: [] as Array<string> })
249 * await seen.update((list) => [...list, 'docs.md'])
250 * ```
251 */
252 state: <T>(options: { key: string; initial: T }) => PluginState<T>
253}
254
255const noSessionState = () => {
256 throw new Error(
257 'ctx.harness.state needs a run that a harness session started.',
258 )
259}
260
261const noSessionAgents = () => {
262 throw new Error(
263 'ctx.harness.agents needs a run that a harness session started.',
264 )
265}
266
267const noTurnHandoff = () =>
268 Promise.reject(
269 new Error(
270 'ctx.harness.handoff needs a root agent that answers a turn of a harness with routing.',
271 ),
272 )
273
274/**
275 * The parts of `ctx.harness` that a tool-mode child of a chat turn gets in
276 * place of a durable session context: `step.do`
277 * runs `fn` each time, `step.sleep` waits its full time, `step.ask`
278 * throws, and each call of `agents`, `state`, and `handoff` throws.
279 */
280export const NO_SESSION_CONTEXT: HarnessAgentContext = {
281 // `fn` runs each time, so it needs no JSON copy.
282 step: {
283 do: async (name, fn) => fn(stepRunWithoutSession(name)),
284 sleep: ({ ms }) => waitUntil(Date.now() + ms),
285 ask: askWithoutSession,
286 },
287 agents: {
288 start: noSessionAgents,
289 run: noSessionAgents,
290 group: noSessionAgents,
291 },
292 handoff: noTurnHandoff,
293 state: noSessionState,
294}
295
296/**
297 * Run `harness` as a child session of the run that owns a `ctx.harness`, and
298 * stream its events. See `harnessAgent`.
299 */
300export type HarnessChildRun = (
301 harness: AnyHarness,
302 ctx: SubagentRunContext,
303) => AsyncIterable<StreamChunk>
304
305/**
306 * The child hook of each `ctx.harness` that a session made. Not a field of
307 * the context, so agent code cannot call it. `NO_SESSION_CONTEXT` has none.
308 */
309const childRuns = new WeakMap<HarnessAgentContext, HarnessChildRun>()
310
311/** The run context of the run of each `ctx.harness` that a session made. */
312const runContexts = new WeakMap<HarnessAgentContext, RunContext>()
313
314/**
315 * @internal Give `context` the child hook `run`, and the run context of the
316 * run that it belongs to. Returns `context`.
317 */
318export function withHarnessChild(
319 context: HarnessAgentContext,
320 run: HarnessChildRun,
321 runContext: RunContext,
322): HarnessAgentContext {
323 childRuns.set(context, run)
324 runContexts.set(context, runContext)
325 return context
326}
327
328/**
329 * @internal The run context of the run of `context`: for an agent that runs
330 * as a tool of a turn, the run of that turn. `undefined` outside a run that
331 * a harness session started.
332 */
333export function runContextOf(context: HarnessAgentContext | undefined) {
334 return context ? runContexts.get(context) : undefined
335}
336
337/**
338 * @internal The child hook of `context`, or `undefined` outside a run that
339 * a harness session started.
340 */
341export function harnessChildOf(context: HarnessAgentContext | undefined) {
342 return context ? childRuns.get(context) : undefined
343}
344
345declare module '@tanstack/ai' {
346 /**
347 * `ctx.harness` in the `run` of an agent: `step`, `agents`, `state`, and
348 * `handoff`. A harness gives it to every agent run in a session, and to
349 * the children those runs start through `ctx.chat({ subagents })`. A run
350 * that a plain `chat()` starts has no `ctx.harness`, so check it before
351 * you use it. `handoff` works only in a root agent that answers a turn of
352 * a harness with `routing`.
353 *
354 * @example
355 * ```ts
356 * if (!ctx.harness) throw new Error('This agent must run in a harness.')
357 * const total = await ctx.harness.step.do('sum', () => 1 + 2)
358 * ```
359 */
360 interface SubagentContextExtension {
361 harness?: HarnessAgentContext
362 }
363}