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

subagent-runs.ts

886 lines29.4 KB

1import {
2 StreamProcessor,
3 convertMessagesToModelMessages,
4 modelMessagesToUIMessages,
5 subagentHostMessageId,
6 subagentInputOf,
7 wireSubagentInfo,
8} from '@tanstack/ai'
9import type {
10 Interrupt,
11 ModelMessage,
12 RunAgentResumeItem,
13 RunStore,
14 StreamChunk,
15 SubagentStatus,
16 SubagentWireInfo,
17 UIMessage,
18} from '@tanstack/ai'
19import { mergeStoredMessages } from './merge-stored'
20import type { InterruptStore, MessageStore, SessionIndexStore } from './types'
21​
22function withSubagentInfo(
23 metadata: ModelMessage['metadata'],
24 info: SubagentWireInfo,
25): Record<string, unknown> {
26 const source =
27 metadata != null && typeof metadata === 'object'
28 ? (metadata as Record<string, unknown>)
29 : {}
30 const tanstack =
31 source.tanstack != null && typeof source.tanstack === 'object'
32 ? (source.tanstack as Record<string, unknown>)
33 : {}
34 return { ...source, tanstack: { ...tanstack, subagent: info } }
36​
37function childStoreId(subagentRunId: string) {
38 return `subagent:${subagentRunId}`
40​
41/**
42 * Head metadata key for what a later call of the child needs:
43 * - `base`: how many stored messages came before the current call. A resume
44 * of that call keeps the number.
45 * - `parentThreadId`: the thread that started the child. Only that thread can
46 * continue it.
47 * - `prompt`: the task of the first call, the first user message of the child.
48 */
49const CHILD_KEY = 'tanstack:subagentChild'
50​
51function storedMarker(messages: ReadonlyArray<ModelMessage>) {
52 const marker: unknown = messages[0]?.metadata?.[CHILD_KEY]
53 const read = (key: string) =>
54 marker !== null && typeof marker === 'object'
55 ? Reflect.get(marker, key)
56 : undefined
57 const base = read('base')
58 const parentThreadId = read('parentThreadId')
59 const prompt = read('prompt')
60 return {
61 ...(typeof base === 'number' && { base }),
62 ...(typeof parentThreadId === 'string' && { parentThreadId }),
63 ...(typeof prompt === 'string' && { prompt }),
64 }
66​
67/** The thread a chat writes its children under: its own child thread, if any. */
68function ownerThread(caller: { threadId: string; subagentRunId?: string }) {
69 return caller.subagentRunId === undefined
70 ? caller.threadId
71 : childStoreId(caller.subagentRunId)
73​
74/** The task of a child's first call, as its first user message. */
75function taskOf(
76 subagentRunId: string,
77 prompt: string | undefined,
78): Array<ModelMessage> {
79 if (prompt === undefined) return []
80 return [
81 {
82 id: `${childStoreId(subagentRunId)}:prompt`,
83 role: 'user',
84 content: prompt,
85 },
86 ]
88​
89/**
90 * The stored transcript of a child agent run of `threadId`, for a UI. It
91 * starts with the task of the first call as a user message. Each message
92 * keeps its card in `metadata.tanstack.subagent`. A nested child
93 * belongs to `threadId` when its parents do. `undefined` for an unknown id
94 * and for a child of another thread.
95 */
96export async function loadChildTranscript(
97 messages: MessageStore,
98 subagentRunId: string,
99 threadId: string,
100): Promise<Array<ModelMessage> | undefined> {
101 const stored = await messages.loadThread(childStoreId(subagentRunId))
102 const marker = storedMarker(stored)
103 // The id can come from a prompt injection. Walk up to the thread, and stop
104 // at the depth cap of `lineage`, so a loop in stored data ends.
105 let parent = marker.parentThreadId
106 for (let depth = 0; parent !== threadId; depth++) {
107 if (parent === undefined || depth >= 64) return undefined
108 if (!parent.startsWith('subagent:')) return undefined
109 parent = storedMarker(await messages.loadThread(parent)).parentThreadId
110 }
111 // A child with no messages keeps its card-only head, so a UI can read how
112 // it ended. The head has no content.
113 return [...taskOf(subagentRunId, marker.prompt), ...stored]
115​
116/** The `prompt` of an agent tool call, if any. */
117function promptOf(call: { args: string } | undefined) {
118 if (call === undefined) return undefined
119 let args: unknown
120 try {
121 args = JSON.parse(call.args)
122 } catch {
123 return undefined
124 }
125 const prompt =
126 args !== null && typeof args === 'object'
127 ? Reflect.get(args, 'prompt')
128 : undefined
129 return typeof prompt === 'string' ? prompt : undefined
131​
132function readSubagentRunId(chunk: StreamChunk) {
133 if (!('subagentRunId' in chunk)) return
134 const id = chunk.subagentRunId
135 return typeof id === 'string' && id !== '' ? id : undefined
137​
138function assistantId(runId: string) {
139 return subagentHostMessageId(runId)
141​
142function messageText(message: ModelMessage) {
143 return typeof message.content === 'string' ? message.content : ''
145​
146function readModelRunId(message: ModelMessage) {
147 const metadata = message.metadata
148 if (metadata == null || typeof metadata !== 'object') return
149 if (!('tanstack' in metadata)) return
150 const tanstack = metadata.tanstack
151 if (tanstack == null || typeof tanstack !== 'object') return
152 if (!('runId' in tanstack)) return
153 const runId = tanstack.runId
154 return typeof runId === 'string' && runId !== '' ? runId : undefined
156​
157function withRunId(message: ModelMessage, runId: string): ModelMessage {
158 const metadata = message.metadata
159 const tanstack =
160 metadata != null &&
161 typeof metadata === 'object' &&
162 'tanstack' in metadata &&
163 metadata.tanstack != null &&
164 typeof metadata.tanstack === 'object'
165 ? metadata.tanstack
166 : {}
167 return {
168 ...message,
169 metadata: {
170 ...metadata,
171 tanstack: { ...tanstack, runId },
172 },
173 }
175​
176function sameChildText(stored: string, incoming: string) {
177 if (stored === '' || incoming === '') return false
178 if (stored === incoming) return true
179 const blocks = stored.split('\n\n').filter((block) => block.includes(':\n'))
180 if (blocks.length === 0) return false
181 return blocks.every((block) => incoming.includes(block))
183​
184/** A tool result, or an assistant message that calls tools. */
185function isToolStep(message: ModelMessage) {
186 return message.role === 'tool' || (message.toolCalls?.length ?? 0) > 0
188​
189// A live client mints its own assistant id. The stored row uses
190// `assistant:${runId}`. When the client sends the turn again, copy `runId`
191// onto the new row so the cards still rebuild.
192function keepSubagentRunIds(
193 stored: ReadonlyArray<ModelMessage>,
194 merged: Array<ModelMessage>,
195) {
196 const dropped = stored.filter((message) => {
197 const runId = readModelRunId(message)
198 if (runId === undefined) return false
199 return !merged.some(
200 (item) => item.id !== undefined && item.id === message.id,
201 )
202 })
203 // The user message before a message, as the turn it answers.
204 const turnOf = (list: ReadonlyArray<ModelMessage>, index: number) =>
205 list.slice(0, index).findLast((message) => message.role === 'user')?.id
206 const used = new Set<number>()
207 for (const previous of dropped) {
208 const runId = readModelRunId(previous)
209 if (runId === undefined) continue
210 if (merged.some((message) => readModelRunId(message) === runId)) continue
211 const previousText = messageText(previous)
212 const previousTurn = turnOf(stored, stored.indexOf(previous))
213 const index = merged.findIndex((message, messageIndex) => {
214 if (used.has(messageIndex)) return false
215 if (message.role !== 'assistant') return false
216 if (readModelRunId(message) !== undefined) return false
217 // No child text yet (a child waits for approval): match the first
218 // assistant reply to the same user message. A finished tool call
219 // before it (a handoff) is not that reply.
220 if (previousText === '') {
221 const before = merged
222 .slice(0, messageIndex)
223 .findLast((item) => !isToolStep(item))
224 return (
225 previousTurn !== undefined &&
226 turnOf(merged, messageIndex) === previousTurn &&
227 !isToolStep(message) &&
228 before?.role === 'user'
229 )
230 }
231 return sameChildText(previousText, messageText(message))
232 })
233 if (index === -1) continue
234 const host = merged[index]
235 if (!host) continue
236 used.add(index)
237 merged[index] = withRunId(host, runId)
238 }
239 return merged
241function childText(messages: ReadonlyArray<UIMessage>) {
242 return messages
243 .flatMap((message) =>
244 message.role === 'assistant'
245 ? message.parts.flatMap((part) =>
246 part.type === 'text' && part.content.trim() !== ''
247 ? [part.content.trim()]
248 : [],
249 )
250 : [],
251 )
252 .join('\n\n')
254​
255// Nested children have their own run and transcript. Leave their cards out
256// of this child's transcript, so a rebuilt card does not show them twice.
257function withoutCards(messages: ReadonlyArray<UIMessage>): Array<UIMessage> {
258 return messages.map((message) => ({
259 ...message,
260 parts: message.parts.filter((part) => part.type !== 'subagent'),
261 }))
263​
264/**
265 * Card data for a stored child transcript. It rides on the first message, in
266 * `metadata.tanstack.subagent`, the same shape the wire uses.
267 */
268export function storedSubagentInfo(
269 messages: ReadonlyArray<ModelMessage>,
270): SubagentWireInfo | undefined {
271 // Same validation as the wire path. Malformed stored data reads as absent.
272 return wireSubagentInfo(messages[0])
274​
275/** A stored child transcript without its card-only placeholder. */
276function withoutPlaceholder(messages: ReadonlyArray<ModelMessage>) {
277 return messages.filter(
278 (message) => storedSubagentInfo([message])?.placeholder !== true,
279 )
281​
282type ChildNote = {
283 name: string
284 /** The thread and run that feed this note now. */
285 threadId: string
286 runId: string
287 /** Last transcript write, for the write interval. */
288 savedAt: number
289 /** The run that started this child. A resume keeps it. */
290 parentRunId: string
291 parentSubagentRunId?: string
292 parentToolCallId?: string
293 processor: StreamProcessor
294 status: SubagentStatus
295 interruptIds?: Array<string>
296 error?: { message: string; code?: string }
297 metadata?: Record<string, unknown>
298 /** Stored messages from before the current call. A resume keeps it. */
299 base: number
300 /** The thread that started this child. */
301 parentThreadId: string
302 /** The task of the first call. */
303 prompt?: string
305​
306export function createSubagentRunRecorder(stores: {
307 messages: MessageStore
308 runs?: RunStore
309 interrupts?: InterruptStore
310 /** When present, each child gets a session index entry. */
311 sessions?: SessionIndexStore
312 /**
313 * The tenant of the threads, for the session index. The parent entry is
314 * read from it and each child entry is written in it. Without it, the
315 * default tenant.
316 */
317 tenantId?: string
318 /** Minimum milliseconds between writes while a child streams. */
319 intervalMs?: number
320}) {
321 // One recorder serves every run of a middleware instance. Notes leave the
322 // map when their child or their run ends.
323 const children = new Map<string, ChildNote>()
324 const intervalMs = stores.intervalMs ?? 1000
325 // Resume entries each run answers. Committed when the run finishes or
326 // suspends. Dropped on abort.
327 const answered = new Map<string, Array<RunAgentResumeItem>>()
328 const parentSavedAt = new Map<string, number>()
329 // Name and arguments of each open tool call, by id. A child that a call
330 // starts reads its task from here. The run's end drops the calls that are
331 // still open.
332 const calls = new Map<string, { name: string; args: string; runId: string }>()
333​
334 /** Drop the open tool calls of a run that ended. */
335 function dropCalls(runId: string) {
336 for (const [id, call] of calls) if (call.runId === runId) calls.delete(id)
337 }
338​
339 async function loadMessages(threadId: string) {
340 return stores.messages.loadThread(threadId)
341 }
342​
343 // The child and its ancestors, nearest first. Each keeps its own stream.
344 function lineage(subagentRunId: string) {
345 const notes: Array<ChildNote> = []
346 let id: string | undefined = subagentRunId
347 for (let depth = 0; id !== undefined && depth < 64; depth++) {
348 const note = children.get(id)
349 if (!note) break
350 notes.push(note)
351 id = note.parentSubagentRunId
352 }
353 return notes
354 }
355​
356 async function saveChild(subagentRunId: string) {
357 const note = children.get(subagentRunId)
358 if (!note) return
359 note.savedAt = Date.now()
360 const info: SubagentWireInfo = {
361 name: note.name,
362 status: note.status,
363 ...(note.parentSubagentRunId !== undefined && {
364 parentSubagentRunId: note.parentSubagentRunId,
365 }),
366 ...(note.parentToolCallId !== undefined && {
367 parentToolCallId: note.parentToolCallId,
368 }),
369 ...(note.interruptIds !== undefined && {
370 interruptIds: note.interruptIds,
371 }),
372 ...(note.error !== undefined && { error: note.error }),
373 ...(note.metadata !== undefined && { metadata: note.metadata }),
374 }
375 const transcript = convertMessagesToModelMessages(
376 withoutCards(note.processor.getMessages()),
377 )
378 const marker = {
379 [CHILD_KEY]: {
380 base: note.base,
381 parentThreadId: note.parentThreadId,
382 ...(note.prompt !== undefined && { prompt: note.prompt }),
383 },
384 }
385 const [first, ...rest] = transcript
386 const head: ModelMessage = first
387 ? {
388 ...first,
389 metadata: { ...withSubagentInfo(first.metadata, info), ...marker },
390 }
391 : {
392 id: `child:${subagentRunId}`,
393 role: 'assistant',
394 content: '',
395 metadata: {
396 ...withSubagentInfo(undefined, { ...info, placeholder: true }),
397 ...marker,
398 },
399 }
400 await stores.messages.saveThread(childStoreId(subagentRunId), [
401 head,
402 ...rest,
403 ])
404 }
405​
406 // The parent message for a routed run holds the children's text. It exists
407 // even before any child writes text, so a reload can show a waiting card.
408 async function saveParent(threadId: string, runId: string) {
409 const notes = [...children.values()].filter(
410 (note) =>
411 note.parentRunId === runId &&
412 note.parentSubagentRunId === undefined &&
413 note.parentToolCallId === undefined,
414 )
415 if (notes.length === 0) return
416 const content = notes
417 .map((note) => {
418 const text = childText(note.processor.getMessages())
419 return text === '' ? '' : `${note.name}:\n${text}`
420 })
421 .filter((block) => block !== '')
422 .join('\n\n')
423 const stored = await loadMessages(threadId)
424 // A resume updates the message of the run that started the child.
425 const index = stored.findIndex(
426 (message) => readModelRunId(message) === runId,
427 )
428 const host = stored[index]
429 if (host) {
430 const next = [...stored]
431 next[index] = { ...host, content }
432 await stores.messages.saveThread(threadId, next)
433 return
434 }
435 const assistant: ModelMessage = {
436 id: assistantId(runId),
437 role: 'assistant',
438 content,
439 metadata: { tanstack: { runId } },
440 }
441 await stores.messages.saveThread(threadId, [...stored, assistant])
442 }
443​
444 async function startChild(
445 input: { threadId: string; runId: string; subagentRunId?: string },
446 chunk: Extract<StreamChunk, { type: 'SUBAGENT_STARTED' }>,
447 ) {
448 const id = chunk.subagentRunId
449 const call =
450 chunk.parentToolCallId === undefined
451 ? undefined
452 : calls.get(chunk.parentToolCallId)
453 if (chunk.parentToolCallId !== undefined) {
454 calls.delete(chunk.parentToolCallId)
455 }
456 const record = await stores.runs?.createOrResume({
457 runId: id,
458 threadId: childStoreId(id),
459 startedAt: Date.now(),
460 parentRunId: chunk.parentSubagentRunId ?? input.runId,
461 subagentRunId: id,
462 name: chunk.name,
463 })
464 const existing = children.get(id)
465 if (existing) {
466 existing.threadId = input.threadId
467 existing.runId = input.runId
468 existing.status = 'running'
469 delete existing.interruptIds
470 if (chunk.metadata !== undefined) existing.metadata = chunk.metadata
471 } else {
472 // A resume or a continue goes on from the stored transcript.
473 const raw = await loadMessages(childStoreId(id))
474 const stored = withoutPlaceholder(raw)
475 const marker = storedMarker(raw)
476 // A resume keeps the base of the call it resumes. A new call starts
477 // after the whole stored transcript.
478 const resumes = storedSubagentInfo(raw)?.status === 'suspended'
479 // An agent with `inputSchema` has its checked input on the card. An
480 // agent without one gets the `prompt` of the call as a user message.
481 const checked = subagentInputOf(chunk.metadata)
482 // Only the first call gives the task. A later call keeps it.
483 const prompt =
484 raw.length > 0
485 ? marker.prompt
486 : checked === undefined
487 ? promptOf(call)
488 : JSON.stringify(checked)
489 // Core does not stream that user message, so store it here.
490 const followUp =
491 raw.length > 0 && !resumes && checked === undefined
492 ? promptOf(call)
493 : undefined
494 const initial: Array<ModelMessage> =
495 followUp === undefined
496 ? stored
497 : [
498 ...stored,
499 {
500 id: `${childStoreId(id)}:prompt:${stored.length}`,
501 role: 'user',
502 content: followUp,
503 },
504 ]
505 children.set(id, {
506 name: chunk.name,
507 threadId: input.threadId,
508 runId: input.runId,
509 savedAt: 0,
510 parentRunId:
511 record?.parentRunId ?? chunk.parentSubagentRunId ?? input.runId,
512 ...(chunk.parentSubagentRunId !== undefined && {
513 parentSubagentRunId: chunk.parentSubagentRunId,
514 }),
515 ...(chunk.parentToolCallId !== undefined && {
516 parentToolCallId: chunk.parentToolCallId,
517 }),
518 ...(chunk.metadata !== undefined && { metadata: chunk.metadata }),
519 processor: new StreamProcessor({
520 subagentRunId: id,
521 initialMessages: modelMessagesToUIMessages(initial),
522 }),
523 status: 'running',
524 // No stored base means the cut point is unknown. Keep every message
525 // that is already stored. `0` would drop them on the next continue.
526 base:
527 resumes && marker.base !== undefined ? marker.base : stored.length,
528 // A nested child belongs to the thread of the child that started it.
529 parentThreadId: ownerThread({
530 threadId: input.threadId,
531 subagentRunId: chunk.parentSubagentRunId ?? input.subagentRunId,
532 }),
533 ...(prompt !== undefined && { prompt }),
534 })
535 }
536 if (record && record.status !== 'running') {
537 await stores.runs?.update(id, { status: 'running' })
538 }
539 // The parent child shows this one as a nested card.
540 if (chunk.parentSubagentRunId !== undefined) {
541 children.get(chunk.parentSubagentRunId)?.processor.processChunk(chunk)
542 }
543 await saveChild(id)
544 const note = children.get(id)
545 if (stores.sessions && note) await indexChild(stores.sessions, id, note)
546 }
547​
548 // One index entry per child, in the tenant of the recorder. A write
549 // replaces the whole entry, so keep the fields that other writers set, like
550 // a title. `upsertIf` writes only over the entry that was read, and a
551 // conflict reads again, so a change from another host is not lost. The
552 // child has the `harness` name of its parent entry, so a list filtered by
553 // it shows it. It has no members: access to a child goes
554 // through its top-level thread. Best-effort: the index is a side store, so
555 // a failed write never fails the run.
556 async function indexChild(
557 sessions: SessionIndexStore,
558 subagentRunId: string,
559 note: ChildNote,
560 ) {
561 const tenant =
562 stores.tenantId === undefined ? {} : { tenantId: stores.tenantId }
563 const threadId = childStoreId(subagentRunId)
564 try {
565 const parent = await sessions.get({
566 ...tenant,
567 threadId: note.parentThreadId,
568 })
569 for (let attempt = 0; attempt < 5; attempt += 1) {
570 const current = await sessions.getVersioned({ ...tenant, threadId })
571 const now = Date.now()
572 const written = await sessions.upsertIf({
573 entry: {
574 members: [],
575 ...current?.entry,
576 ...tenant,
577 threadId,
578 parentThreadId: note.parentThreadId,
579 ...(note.parentToolCallId !== undefined && {
580 parentToolCallId: note.parentToolCallId,
581 }),
582 ...(parent?.harness !== undefined && { harness: parent.harness }),
583 createdAt: current?.entry.createdAt ?? now,
584 updatedAt: now,
585 },
586 revision: current?.revision ?? null,
587 })
588 if (written.ok) return
589 }
590 console.warn(
591 `[ai-persistence] session index entry '${threadId}' changed on another host 5 times in a row`,
592 )
593 } catch (error) {
594 console.warn(
595 `[ai-persistence] session index write failed for '${threadId}'`,
596 error,
597 )
598 }
599 }
600​
601 /**
602 * The stored transcript of a child, for a call that continues it by
603 * `sessionId`. It starts with the task of the first call as a user message.
604 * `undefined` when `caller` did not start a child with this id. While the
605 * child waits on an interrupt, it is the transcript from before that call:
606 * the resume adds the newer messages of the child itself.
607 */
608 async function loadChild(
609 subagentRunId: string,
610 caller: { threadId: string; subagentRunId?: string },
611 ) {
612 const stored = await loadMessages(childStoreId(subagentRunId))
613 const marker = storedMarker(stored)
614 // The id can come from a prompt injection. Never load the child of an
615 // other thread.
616 if (marker.parentThreadId !== ownerThread(caller)) return undefined
617 const messages = withoutPlaceholder(stored)
618 const info = storedSubagentInfo(stored)
619 const waits = info?.status === 'suspended'
620 const transcript =
621 waits && marker.base !== undefined
622 ? messages.slice(0, marker.base)
623 : messages
624 // The agent the child ran under. Only that agent can continue it.
625 return {
626 messages: [...taskOf(subagentRunId, marker.prompt), ...transcript],
627 ...(info !== undefined && { agent: info.name }),
628 // A resume reads the waiting call from here, not from the client card.
629 ...(waits && {
630 pending: messages.slice(marker.base ?? 0),
631 interruptIds: info.interruptIds ?? [],
632 }),
633 ...(info?.parentToolCallId !== undefined && {
634 parentToolCallId: info.parentToolCallId,
635 }),
636 }
637 }
638​
639 async function settleChild(
640 chunk: Extract<
641 StreamChunk,
642 { type: 'SUBAGENT_FINISHED' | 'SUBAGENT_ERROR' }
643 >,
644 ) {
645 const id = chunk.subagentRunId
646 const note = children.get(id)
647 if (!note) return
648 try {
649 await writeSettled(note, id, chunk)
650 } finally {
651 // A routed child stays until its run ends: the parent message reads its
652 // text. Nested children and children started by a tool call go now.
653 if (
654 note.parentSubagentRunId !== undefined ||
655 note.parentToolCallId !== undefined
656 ) {
657 children.delete(id)
658 }
659 }
660 }
661​
662 async function writeSettled(
663 note: ChildNote,
664 id: string,
665 chunk: Extract<
666 StreamChunk,
667 { type: 'SUBAGENT_FINISHED' | 'SUBAGENT_ERROR' }
668 >,
669 ) {
670 note.processor.finalizeStream()
671 if (note.parentSubagentRunId !== undefined) {
672 children.get(note.parentSubagentRunId)?.processor.processChunk(chunk)
673 }
674 if (chunk.type === 'SUBAGENT_ERROR') {
675 const stopped = chunk.message === 'Stopped'
676 note.status = 'error'
677 note.error = {
678 message: chunk.message,
679 ...(chunk.code !== undefined && { code: chunk.code }),
680 }
681 await saveChild(id)
682 await stores.runs?.update(id, {
683 status: stopped ? 'aborted' : 'failed',
684 finishedAt: Date.now(),
685 ...(!stopped ? { error: { message: chunk.message } } : {}),
686 })
687 return
688 }
689 if (chunk.outcome?.type === 'suspended') {
690 note.status = 'suspended'
691 note.interruptIds = chunk.outcome.interruptIds ?? []
692 await saveChild(id)
693 await stores.runs?.update(id, { status: 'interrupted' })
694 return
695 }
696 note.status = 'finished'
697 await saveChild(id)
698 await stores.runs?.update(id, {
699 status: 'completed',
700 finishedAt: Date.now(),
701 })
702 }
703​
704 async function commitAnswers(runId: string) {
705 const entries = answered.get(runId) ?? []
706 answered.delete(runId)
707 for (const entry of entries) {
708 if (entry.status === 'cancelled') {
709 await stores.interrupts?.cancel(entry.interruptId)
710 } else {
711 await stores.interrupts?.resolve(entry.interruptId, entry.payload)
712 }
713 }
714 }
715​
716 /** The notes a run fed. */
717 function notesOf(runId: string) {
718 return [...children].filter(([, note]) => note.runId === runId)
719 }
720​
721 function forget(runId: string) {
722 for (const [id] of notesOf(runId)) children.delete(id)
723 parentSavedAt.delete(runId)
724 }
725​
726 async function settleOpenChildren(
727 runId: string,
728 status: 'completed' | 'failed' | 'aborted',
729 error?: { message: string },
730 ) {
731 for (const [subagentRunId] of notesOf(runId)) {
732 await saveChild(subagentRunId)
733 const current = await stores.runs?.get(subagentRunId)
734 if (current && current.status !== 'running') continue
735 await stores.runs?.update(subagentRunId, {
736 status,
737 finishedAt: Date.now(),
738 ...(error ? { error } : {}),
739 })
740 }
741 }
742​
743 /** Write the parent messages of this thread's routed children. */
744 async function saveParents(threadId: string) {
745 const runIds = new Set(
746 [...children.values()]
747 .filter((note) => note.threadId === threadId)
748 .map((note) => note.parentRunId),
749 )
750 for (const runId of runIds) await saveParent(threadId, runId)
751 }
752​
753 return {
754 loadChild,
755​
756 async start(input: {
757 threadId: string
758 runId: string
759 messages: ReadonlyArray<UIMessage | ModelMessage>
760 resume?: ReadonlyArray<RunAgentResumeItem>
761 }) {
762 await stores.runs?.createOrResume({
763 runId: input.runId,
764 threadId: input.threadId,
765 startedAt: Date.now(),
766 })
767 if (input.resume?.length) answered.set(input.runId, [...input.resume])
768 const incoming = convertMessagesToModelMessages([...input.messages])
769 const stored = await loadMessages(input.threadId)
770 const merged = mergeStoredMessages(stored, incoming)
771 await stores.messages.saveThread(
772 input.threadId,
773 keepSubagentRunIds(stored, merged),
774 )
775 },
776​
777 async chunk(input: {
778 threadId: string
779 runId: string
780 /** Set when the chat that streams this chunk is a child itself. */
781 subagentRunId?: string
782 chunk: StreamChunk
783 }) {
784 const chunk = input.chunk
785 if (chunk.type === 'TOOL_CALL_START') {
786 calls.set(chunk.toolCallId, {
787 name: chunk.toolCallName,
788 args: '',
789 runId: input.runId,
790 })
791 }
792 if (chunk.type === 'TOOL_CALL_ARGS') {
793 const call = calls.get(chunk.toolCallId)
794 if (call) call.args += chunk.delta
795 }
796 if (chunk.type === 'TOOL_CALL_RESULT') calls.delete(chunk.toolCallId)
797 if (chunk.type === 'SUBAGENT_STARTED') {
798 await startChild(input, chunk)
799 return
800 }
801 if (
802 chunk.type === 'SUBAGENT_FINISHED' ||
803 chunk.type === 'SUBAGENT_ERROR'
804 ) {
805 await settleChild(chunk)
806 await saveParents(input.threadId)
807 return
808 }
809 const subagentRunId = readSubagentRunId(chunk)
810 if (!subagentRunId) return
811 const notes = lineage(subagentRunId)
812 if (notes.length === 0) return
813 for (const note of notes) note.processor.processChunk(chunk)
814 // A streaming child writes at most once per interval. Its terminal
815 // event and the run's end always write.
816 const now = Date.now()
817 const note = notes[0]
818 if (note && now - note.savedAt >= intervalMs) {
819 await saveChild(subagentRunId)
820 }
821 if (
822 chunk.type === 'TEXT_MESSAGE_CONTENT' &&
823 now - (parentSavedAt.get(input.runId) ?? 0) >= intervalMs
824 ) {
825 parentSavedAt.set(input.runId, now)
826 await saveParents(input.threadId)
827 }
828 },
829​
830 async suspend(input: {
831 threadId: string
832 runId: string
833 interrupts: ReadonlyArray<Interrupt>
834 }) {
835 await commitAnswers(input.runId)
836 await saveParents(input.threadId)
837 for (const [subagentRunId] of notesOf(input.runId)) {
838 await saveChild(subagentRunId)
839 }
840 for (const interrupt of input.interrupts) {
841 await stores.interrupts?.create({
842 interruptId: interrupt.id,
843 runId: input.runId,
844 threadId: input.threadId,
845 requestedAt: Date.now(),
846 payload: { ...interrupt },
847 })
848 }
849 await stores.runs?.update(input.runId, { status: 'interrupted' })
850 forget(input.runId)
851 },
852​
853 async finish(input: { threadId: string; runId: string }) {
854 dropCalls(input.runId)
855 await commitAnswers(input.runId)
856 await saveParents(input.threadId)
857 await settleOpenChildren(input.runId, 'completed')
858 await stores.runs?.update(input.runId, {
859 status: 'completed',
860 finishedAt: Date.now(),
861 })
862 forget(input.runId)
863 },
864​
865 async abort(input: { threadId: string; runId: string; error?: unknown }) {
866 dropCalls(input.runId)
867 const aborted =
868 input.error instanceof Error && input.error.name === 'AbortError'
869 const message =
870 input.error instanceof Error ? input.error.message : 'Run failed'
871 await settleOpenChildren(
872 input.runId,
873 aborted ? 'aborted' : 'failed',
874 aborted ? undefined : { message },
875 )
876 await saveParents(input.threadId)
877 await stores.runs?.update(input.runId, {
878 status: aborted ? 'aborted' : 'failed',
879 finishedAt: Date.now(),
880 ...(!aborted ? { error: { message } } : {}),
881 })
882 answered.delete(input.runId)
883 forget(input.runId)
884 },
885 }