Open History to see the last commit
1import { toolDefinition } from '@tanstack/ai'
2import { isHumanTarget } from './log-records'
3import { isRecord } from './utils'
4import type {
5 AnyChatMiddleware,
6 ModelMessage,
7 SubagentRouterPick,
8} from '@tanstack/ai'
9import type { MessageStore } from '@tanstack/ai-persistence'
10import type { AnyAgent } from './agents'
11import type { HarnessRouterPick } from './define'
12import type { HandoffRecord, HumanTarget } from './log-records'
13
14/** What `ctx.harness.handoff` takes. */
15export interface HandoffOptions {
16 /**
17 * The root agent that answers next, `'main'` for the main model, or
18 * `{ human: true }` for a person. A handoff to a person needs
19 * `routing.allowHandoffToHuman`. It opens a `human` wait, and the session pauses until
20 * an operator answers it.
21 */
22 to: string | HumanTarget
23 /** A note for the target. The log and the `harness.handoff` event keep it. */
24 note?: string
25}
26
27/** The name of the tool that hands the turn to another agent. */
28export const HANDOFF_TOOL = 'handoff'
29
30/**
31 * The most handoffs in one turn. Two agents that hand the turn to each other
32 * again and again stop here.
33 */
34const MAX_HANDOFFS = 10
35
36/** A handoff without the turn that made it. */
37type Handoff = Omit<HandoffRecord, 'runId'>
38
39/** The target of a handoff to a person. */
40const HUMAN: HumanTarget = { human: true }
41
42/** How a text names the target of a handoff. */
43function targetName(to: HandoffRecord['to']) {
44 if (to === null) return 'main'
45 return isHumanTarget(to) ? 'a person' : to
46}
47
48/** The result text of a `handoff` tool call to `to`. */
49function handoffText(to: string | HumanTarget) {
50 if (typeof to !== 'string') {
51 return 'Handed off to a person. The session waits for an operator.'
52 }
53 return `Handed off to ${to}. ${to} answers next.`
54}
55
56/**
57 * The messages that show a router or code handoff in the transcript, so the
58 * target knows that it got the conversation, and why. They look like a
59 * `handoff` tool call of the model and its result. With `asTool: false` (the
60 * models have no `handoff` tool) they are one plain assistant note, with
61 * the message id `id`.
62 */
63export function handoffMessages(
64 record: Handoff,
65 id: string,
66 asTool: boolean,
67): Array<ModelMessage> {
68 const to = isHumanTarget(record.to) ? HUMAN : (record.to ?? 'main')
69 const metadata = {
70 harness: {
71 ...(typeof record.from === 'string' ? { agent: record.from } : {}),
72 handoff: { by: record.by },
73 },
74 }
75 const result = handoffText(to)
76 if (!asTool) {
77 const note = record.note === undefined ? '' : ` Note: ${record.note}`
78 return [{ id, role: 'assistant', content: result + note, metadata }]
79 }
80 const args = {
81 to,
82 ...(record.note !== undefined ? { note: record.note } : {}),
83 }
84 return [
85 {
86 id,
87 role: 'assistant',
88 content: null,
89 toolCalls: [
90 {
91 id,
92 type: 'function',
93 function: { name: HANDOFF_TOOL, arguments: JSON.stringify(args) },
94 },
95 ],
96 metadata,
97 },
98 {
99 id: `${id}_result`,
100 role: 'tool',
101 toolCallId: id,
102 content: result,
103 metadata,
104 },
105 ]
106}
107
108/**
109 * The handoffs of one turn of a harness with `routing`. The router, the
110 * `handoff` tool, and `ctx.harness.handoff` go through it. Each handoff
111 * appends one `harness.handoff` record, before the target runs, and
112 * publishes one `harness.handoff` event. A tool or code handoff ends the
113 * part that made it. Then the turn runs the target.
114 */
115export class TurnHandoffs {
116 /** The handoff that ends the current part. */
117 private pending: Handoff | undefined
118 private count = 0
119
120 constructor(
121 private readonly options: {
122 /** The operation id of the turn. */
123 runId: string
124 /**
125 * The key of the ids of the handoff notes: the input of the turn, which
126 * a run of the turn on the next host keeps.
127 */
128 noteKey: string
129 /** The agents a handoff can go to. */
130 rootAgents: ReadonlyArray<AnyAgent>
131 /** The names of the agents that are only subagents, for the error text. */
132 subagents: ReadonlyArray<string>
133 /** `routing.allowHandoffToHuman`: a handoff can go to a person. */
134 humans: boolean
135 /** `routing.giveModelsHandoffTool`: the root agents get the `handoff` tool. */
136 tool: boolean
137 /**
138 * Append the record. A handoff to a person opens its `human` wait in
139 * the same append. Resolves with the record as the log keeps it.
140 */
141 append: (record: HandoffRecord) => Promise<HandoffRecord>
142 publish: (value: HandoffRecord) => void
143 },
144 ) {}
145
146 /**
147 * The pick that `chat()` runs for a router answer. A pick that changes who
148 * answers the thread is a handoff with `by: 'router'`. `messages` show
149 * that handoff in the transcript.
150 */
151 async route(
152 chosen: HarnessRouterPick,
153 activeAgent: string | null,
154 ): Promise<{ pick: SubagentRouterPick; messages: Array<ModelMessage> }> {
155 const { pick, handoff } = routerTarget(
156 chosen,
157 activeAgent,
158 this.options.rootAgents,
159 )
160 if (!handoff) return { pick, messages: [] }
161 const record = await this.write({ ...handoff, by: 'router' })
162 return { pick, messages: this.messages(record) }
163 }
164
165 /**
166 * The messages that show a router or code handoff in the transcript. None
167 * for a `handoff` tool call: the call of the model is there already.
168 */
169 messages(handoff: Handoff): Array<ModelMessage> {
170 if (handoff.by !== 'router' && handoff.by !== 'code') return []
171 // A turn that runs again after a crash makes the same ids, so the store
172 // keeps each note once.
173 const id = `handoff_${this.options.noteKey}_${this.count}`
174 return handoffMessages(handoff, id, this.options.tool)
175 }
176
177 /**
178 * Hand the turn from `from` (an agent name, or `null` for the main model)
179 * to `options.to`. The part of `from` ends, and the target answers next.
180 * A handoff to a person ends the turn, and the session pauses. Throws for
181 * a target that is not a root agent, for a person without
182 * `routing.allowHandoffToHuman`, and for a second handoff in the same part.
183 */
184 async handoff(
185 options: HandoffOptions,
186 from: string | null,
187 by: 'tool' | 'code',
188 ): Promise<void> {
189 const { to, note } = options
190 const isHuman = isHumanTarget(to)
191 if (isHuman && !this.options.humans) {
192 throw new Error(
193 'A handoff to a person needs `routing: { humans: true }` in the harness.',
194 )
195 }
196 if (!isHuman && typeof to !== 'string') {
197 throw new Error(
198 'A handoff needs `to`: the name of a root agent, or { human: true }.',
199 )
200 }
201 const names = this.options.rootAgents.map((agent) => agent.name)
202 if (!isHuman && to !== 'main' && !names.includes(to)) {
203 const kind = this.options.subagents.includes(to)
204 ? `Agent "${to}" is only a subagent.`
205 : `Unknown agent "${to}".`
206 throw new Error(
207 `${kind} A handoff goes to a root agent (${[...names, "'main'"].join(', ')}).`,
208 )
209 }
210 const target = isHuman ? HUMAN : to === 'main' ? null : to
211 if (target === from) {
212 throw new Error(
213 `${targetName(target)} answers already. Hand off to another agent.`,
214 )
215 }
216 if (this.pending) {
217 throw new Error(
218 `This part handed off to ${targetName(this.pending.to)} already.`,
219 )
220 }
221 if (this.count >= MAX_HANDOFFS) {
222 throw new Error(
223 `A turn can hand off ${MAX_HANDOFFS} times at most. Answer the user.`,
224 )
225 }
226 const handoff: Handoff = {
227 from,
228 to: target,
229 ...(typeof note === 'string' ? { note } : {}),
230 by,
231 // The agents an operator can hand back to: the ones this turn offers.
232 ...(isHuman ? { agents: names } : {}),
233 }
234 this.pending = await this.write(handoff)
235 }
236
237 /** The handoff that ended the last part, once. */
238 take(): Handoff | undefined {
239 const { pending } = this
240 this.pending = undefined
241 return pending
242 }
243
244 /**
245 * Make `handoff` pending again, with no new record: the log has it. A
246 * resolve turn gets the handoff of the part that stopped for interrupts.
247 * Its part ends after the answered tools, and the target runs.
248 */
249 restore(handoff: Handoff) {
250 this.count += 1
251 this.pending = handoff
252 }
253
254 /**
255 * The `handoff` tool of `from`: the main model (`null`) or a root agent.
256 * Its `to` lists the root agents, and `'main'` for an agent, but not
257 * `from`. With `routing.allowHandoffToHuman`, `{ human: true }` hands the conversation
258 * to a person.
259 */
260 tool(from: string | null) {
261 const { humans } = this.options
262 const targets = [
263 ...this.options.rootAgents.map((agent) => agent.name),
264 ...(from === null ? [] : ['main']),
265 ].filter((name) => name !== from)
266 const agents = { type: 'string', enum: targets }
267 const person = {
268 type: 'object',
269 properties: { human: { type: 'boolean', const: true } },
270 required: ['human'],
271 }
272 return toolDefinition({
273 name: HANDOFF_TOOL,
274 description: `Hand the conversation to another agent. That agent answers the user next, in this turn and in later turns.${humans ? ' Use { human: true } only when the user needs a person.' : ''} Stop after this call.`,
275 inputSchema: {
276 type: 'object',
277 properties: {
278 to: humans ? { anyOf: [agents, person] } : agents,
279 note: {
280 type: 'string',
281 description: 'What the next agent must know.',
282 },
283 },
284 required: ['to'],
285 },
286 }).server(async (args: unknown) => {
287 const to = isRecord(args) ? args.to : undefined
288 const note = isRecord(args) ? args.note : undefined
289 const target = isHumanTarget(to) ? HUMAN : to
290 if (typeof target !== 'string' && !isHumanTarget(target)) {
291 throw new Error('A handoff needs `to`: the name of an agent.')
292 }
293 await this.handoff(
294 { to: target, ...(typeof note === 'string' ? { note } : {}) },
295 from,
296 'tool',
297 )
298 return handoffText(target)
299 })
300 }
301
302 /**
303 * Middleware for the chat calls of a turn: a pending handoff stops the
304 * tool loop of the chat that made it, so the target answers next. Other
305 * chats of the part (a sibling root agent, a tool-mode child) go on. With
306 * `roots`, it also gives each routed root agent its `handoff` tool, unless
307 * `routing.giveModelsHandoffTool` is false. A nested child of a root agent gets no
308 * tool, so it cannot move the whole session.
309 */
310 middleware(options: { roots?: boolean } = {}): AnyChatMiddleware {
311 return {
312 name: 'harness:handoff',
313 onConfig: (ctx, config) => {
314 const isRoot =
315 options.roots === true &&
316 this.options.tool &&
317 ctx.subagentName !== undefined &&
318 ctx.parentSubagentRunId === undefined
319 if (!isRoot) return
320 if (config.tools.some((tool) => tool.name === HANDOFF_TOOL)) return
321 return { tools: [...config.tools, this.tool(ctx.subagentName ?? null)] }
322 },
323 onShouldContinue: (ctx) => {
324 const { pending } = this
325 if (!pending || ctx.parentSubagentRunId !== undefined) return undefined
326 // ponytail: a chat is known by its agent name ('main' has none). The
327 // root agents of one pick have different names.
328 return (ctx.subagentName ?? null) === pending.from ? false : undefined
329 },
330 }
331 }
332
333 private async write(handoff: Handoff) {
334 this.count += 1
335 const record = await this.options.append({
336 ...handoff,
337 runId: this.options.runId,
338 })
339 this.options.publish(record)
340 return record
341 }
342}
343
344/**
345 * The pick that `chat()` runs for a router answer, and the handoff that the
346 * log keeps, when the answer changes who answers the thread.
347 */
348function routerTarget(
349 chosen: HarnessRouterPick,
350 activeAgent: string | null,
351 rootAgents: ReadonlyArray<AnyAgent>,
352): {
353 pick: SubagentRouterPick
354 handoff?: Pick<HandoffRecord, 'from' | 'to' | 'note'>
355} {
356 const isRoot = (name: string) =>
357 rootAgents.some((agent) => agent.name === name)
358 if (chosen === undefined) {
359 if (activeAgent === null || isRoot(activeAgent)) {
360 return { pick: activeAgent ?? 'main' }
361 }
362 // An active agent that this turn does not have (a plugin went away)
363 // gives the turn to the main model. The log keeps that, so the next
364 // turn does not read the missing agent again.
365 return { pick: 'main', handoff: { from: activeAgent, to: null } }
366 }
367 if (typeof chosen === 'object' && 'handoff' in chosen) {
368 const to = chosen.handoff === 'main' ? null : chosen.handoff
369 // An unknown name writes nothing. chat() fails the turn for it.
370 if (to !== null && !isRoot(to)) return { pick: to }
371 return {
372 pick: chosen.handoff,
373 handoff: {
374 from: activeAgent,
375 to,
376 ...(chosen.note !== undefined ? { note: chosen.note } : {}),
377 },
378 }
379 }
380 if (typeof chosen !== 'string') return { pick: chosen }
381 const to = chosen === 'main' ? null : chosen
382 const changes = to !== activeAgent && (to === null || isRoot(to))
383 return changes
384 ? { pick: chosen, handoff: { from: activeAgent, to } }
385 : { pick: chosen }
386}
387
388/** The agent that answers a part of a routed turn, when one agent does. */
389export function answererOf(pick: SubagentRouterPick | undefined) {
390 if (typeof pick === 'string') return pick === 'main' ? null : pick
391 if (typeof pick === 'object' && 'name' in pick) return pick.name
392 return undefined
393}
394
395/**
396 * The message of a routed run in the thread: chat() keeps the text of the
397 * root agents of run `runId` in one assistant message.
398 */
399function routedIndex(messages: ReadonlyArray<ModelMessage>, runId: string) {
400 return messages.findIndex((message) => {
401 const tanstack = message.metadata?.tanstack
402 return isRecord(tanstack) && tanstack.runId === runId
403 })
404}
405
406/**
407 * Mark the routed message of run `runId` with the agent that wrote it, in
408 * `metadata.harness.agent`. A routed pass that runs again on the same run id
409 * (a handoff to another root agent, a late join, a hook) first keeps this
410 * message under its own id, so each pass keeps its own message.
411 */
412export async function markRouted(
413 store: MessageStore,
414 threadId: string,
415 runId: string,
416 mark: { agent?: string },
417) {
418 const { agent } = mark
419 if (agent === undefined) return
420 const history = await store.loadThread(threadId)
421 const index = routedIndex(history, runId)
422 const message = history[index]
423 if (!message) return
424 const harness = isRecord(message.metadata?.harness)
425 ? message.metadata.harness
426 : {}
427 const updated: ModelMessage = {
428 ...message,
429 metadata: {
430 ...message.metadata,
431 harness: { ...harness, agent },
432 },
433 }
434 await store.saveThread(threadId, history.with(index, updated))
435}