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

subagent-runs.ts

775 lines25.3 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 } 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 `prompt` of an agent tool call, if any. */
75function promptOf(call: { args: string } | undefined) {
76 if (call === undefined) return undefined
77 let args: unknown
78 try {
79 args = JSON.parse(call.args)
80 } catch {
81 return undefined
82 }
83 const prompt =
84 args !== null && typeof args === 'object'
85 ? Reflect.get(args, 'prompt')
86 : undefined
87 return typeof prompt === 'string' ? prompt : undefined
89​
90function readSubagentRunId(chunk: StreamChunk) {
91 if (!('subagentRunId' in chunk)) return
92 const id = chunk.subagentRunId
93 return typeof id === 'string' && id !== '' ? id : undefined
95​
96function assistantId(runId: string) {
97 return subagentHostMessageId(runId)
99​
100function messageText(message: ModelMessage) {
101 return typeof message.content === 'string' ? message.content : ''
103​
104function readModelRunId(message: ModelMessage) {
105 const metadata = message.metadata
106 if (metadata == null || typeof metadata !== 'object') return
107 if (!('tanstack' in metadata)) return
108 const tanstack = metadata.tanstack
109 if (tanstack == null || typeof tanstack !== 'object') return
110 if (!('runId' in tanstack)) return
111 const runId = tanstack.runId
112 return typeof runId === 'string' && runId !== '' ? runId : undefined
114​
115function withRunId(message: ModelMessage, runId: string): ModelMessage {
116 const metadata = message.metadata
117 const tanstack =
118 metadata != null &&
119 typeof metadata === 'object' &&
120 'tanstack' in metadata &&
121 metadata.tanstack != null &&
122 typeof metadata.tanstack === 'object'
123 ? metadata.tanstack
124 : {}
125 return {
126 ...message,
127 metadata: {
128 ...metadata,
129 tanstack: { ...tanstack, runId },
130 },
131 }
133​
134function sameChildText(stored: string, incoming: string) {
135 if (stored === '' || incoming === '') return false
136 if (stored === incoming) return true
137 const blocks = stored.split('\n\n').filter((block) => block.includes(':\n'))
138 if (blocks.length === 0) return false
139 return blocks.every((block) => incoming.includes(block))
141​
142// A live client mints its own assistant id. The stored row uses
143// `assistant:${runId}`. When the client sends the turn again, copy `runId`
144// onto the new row so the cards still rebuild.
145function keepSubagentRunIds(
146 stored: ReadonlyArray<ModelMessage>,
147 merged: Array<ModelMessage>,
148) {
149 const dropped = stored.filter((message) => {
150 const runId = readModelRunId(message)
151 if (runId === undefined) return false
152 return !merged.some(
153 (item) => item.id !== undefined && item.id === message.id,
154 )
155 })
156 // The user message before a message, as the turn it answers.
157 const turnOf = (list: ReadonlyArray<ModelMessage>, index: number) =>
158 list.slice(0, index).findLast((message) => message.role === 'user')?.id
159 const used = new Set<number>()
160 for (const previous of dropped) {
161 const runId = readModelRunId(previous)
162 if (runId === undefined) continue
163 if (merged.some((message) => readModelRunId(message) === runId)) continue
164 const previousText = messageText(previous)
165 const previousTurn = turnOf(stored, stored.indexOf(previous))
166 const index = merged.findIndex((message, messageIndex) => {
167 if (used.has(messageIndex)) return false
168 if (message.role !== 'assistant') return false
169 if (readModelRunId(message) !== undefined) return false
170 // No child text yet (a child waits for approval): match the first
171 // assistant reply to the same user message.
172 if (previousText === '') {
173 return (
174 previousTurn !== undefined &&
175 turnOf(merged, messageIndex) === previousTurn &&
176 merged[messageIndex - 1]?.role === 'user'
177 )
178 }
179 return sameChildText(previousText, messageText(message))
180 })
181 if (index === -1) continue
182 const host = merged[index]
183 if (!host) continue
184 used.add(index)
185 merged[index] = withRunId(host, runId)
186 }
187 return merged
189function childText(messages: ReadonlyArray<UIMessage>) {
190 return messages
191 .flatMap((message) =>
192 message.role === 'assistant'
193 ? message.parts.flatMap((part) =>
194 part.type === 'text' && part.content.trim() !== ''
195 ? [part.content.trim()]
196 : [],
197 )
198 : [],
199 )
200 .join('\n\n')
202​
203// Nested children have their own run and transcript. Leave their cards out
204// of this child's transcript, so a rebuilt card does not show them twice.
205function withoutCards(messages: ReadonlyArray<UIMessage>): Array<UIMessage> {
206 return messages.map((message) => ({
207 ...message,
208 parts: message.parts.filter((part) => part.type !== 'subagent'),
209 }))
211​
212/**
213 * Card data for a stored child transcript. It rides on the first message, in
214 * `metadata.tanstack.subagent`, the same shape the wire uses.
215 */
216export function storedSubagentInfo(
217 messages: ReadonlyArray<ModelMessage>,
218): SubagentWireInfo | undefined {
219 // Same validation as the wire path. Malformed stored data reads as absent.
220 return wireSubagentInfo(messages[0])
222​
223/** A stored child transcript without its card-only placeholder. */
224function withoutPlaceholder(messages: ReadonlyArray<ModelMessage>) {
225 return messages.filter(
226 (message) => storedSubagentInfo([message])?.placeholder !== true,
227 )
229​
230type ChildNote = {
231 name: string
232 /** The thread and run that feed this note now. */
233 threadId: string
234 runId: string
235 /** Last transcript write, for the write interval. */
236 savedAt: number
237 /** The run that started this child. A resume keeps it. */
238 parentRunId: string
239 parentSubagentRunId?: string
240 parentToolCallId?: string
241 processor: StreamProcessor
242 status: SubagentStatus
243 interruptIds?: Array<string>
244 error?: { message: string; code?: string }
245 metadata?: Record<string, unknown>
246 /** Stored messages from before the current call. A resume keeps it. */
247 base: number
248 /** The thread that started this child. */
249 parentThreadId: string
250 /** The task of the first call. */
251 prompt?: string
253​
254export function createSubagentRunRecorder(stores: {
255 messages: MessageStore
256 runs?: RunStore
257 interrupts?: InterruptStore
258 /** Minimum milliseconds between writes while a child streams. */
259 intervalMs?: number
260}) {
261 // One recorder serves every run of a middleware instance. Notes leave the
262 // map when their child or their run ends.
263 const children = new Map<string, ChildNote>()
264 const intervalMs = stores.intervalMs ?? 1000
265 // Resume entries each run answers. Committed when the run finishes or
266 // suspends. Dropped on abort.
267 const answered = new Map<string, Array<RunAgentResumeItem>>()
268 const parentSavedAt = new Map<string, number>()
269 // Name and arguments of each open tool call, by id. A child that a call
270 // starts reads its task from here. The run's end drops the calls that are
271 // still open.
272 const calls = new Map<string, { name: string; args: string; runId: string }>()
273​
274 /** Drop the open tool calls of a run that ended. */
275 function dropCalls(runId: string) {
276 for (const [id, call] of calls) if (call.runId === runId) calls.delete(id)
277 }
278​
279 async function loadMessages(threadId: string) {
280 return stores.messages.loadThread(threadId)
281 }
282​
283 // The child and its ancestors, nearest first. Each keeps its own stream.
284 function lineage(subagentRunId: string) {
285 const notes: Array<ChildNote> = []
286 let id: string | undefined = subagentRunId
287 for (let depth = 0; id !== undefined && depth < 64; depth++) {
288 const note = children.get(id)
289 if (!note) break
290 notes.push(note)
291 id = note.parentSubagentRunId
292 }
293 return notes
294 }
295​
296 async function saveChild(subagentRunId: string) {
297 const note = children.get(subagentRunId)
298 if (!note) return
299 note.savedAt = Date.now()
300 const info: SubagentWireInfo = {
301 name: note.name,
302 status: note.status,
303 ...(note.parentSubagentRunId !== undefined && {
304 parentSubagentRunId: note.parentSubagentRunId,
305 }),
306 ...(note.parentToolCallId !== undefined && {
307 parentToolCallId: note.parentToolCallId,
308 }),
309 ...(note.interruptIds !== undefined && {
310 interruptIds: note.interruptIds,
311 }),
312 ...(note.error !== undefined && { error: note.error }),
313 ...(note.metadata !== undefined && { metadata: note.metadata }),
314 }
315 const transcript = convertMessagesToModelMessages(
316 withoutCards(note.processor.getMessages()),
317 )
318 const marker = {
319 [CHILD_KEY]: {
320 base: note.base,
321 parentThreadId: note.parentThreadId,
322 ...(note.prompt !== undefined && { prompt: note.prompt }),
323 },
324 }
325 const [first, ...rest] = transcript
326 const head: ModelMessage = first
327 ? {
328 ...first,
329 metadata: { ...withSubagentInfo(first.metadata, info), ...marker },
330 }
331 : {
332 id: `child:${subagentRunId}`,
333 role: 'assistant',
334 content: '',
335 metadata: {
336 ...withSubagentInfo(undefined, { ...info, placeholder: true }),
337 ...marker,
338 },
339 }
340 await stores.messages.saveThread(childStoreId(subagentRunId), [
341 head,
342 ...rest,
343 ])
344 }
345​
346 // The parent message for a routed run holds the children's text. It exists
347 // even before any child writes text, so a reload can show a waiting card.
348 async function saveParent(threadId: string, runId: string) {
349 const notes = [...children.values()].filter(
350 (note) =>
351 note.parentRunId === runId &&
352 note.parentSubagentRunId === undefined &&
353 note.parentToolCallId === undefined,
354 )
355 if (notes.length === 0) return
356 const content = notes
357 .map((note) => {
358 const text = childText(note.processor.getMessages())
359 return text === '' ? '' : `${note.name}:\n${text}`
360 })
361 .filter((block) => block !== '')
362 .join('\n\n')
363 const stored = await loadMessages(threadId)
364 // A resume updates the message of the run that started the child.
365 const index = stored.findIndex(
366 (message) => readModelRunId(message) === runId,
367 )
368 const host = stored[index]
369 if (host) {
370 const next = [...stored]
371 next[index] = { ...host, content }
372 await stores.messages.saveThread(threadId, next)
373 return
374 }
375 const assistant: ModelMessage = {
376 id: assistantId(runId),
377 role: 'assistant',
378 content,
379 metadata: { tanstack: { runId } },
380 }
381 await stores.messages.saveThread(threadId, [...stored, assistant])
382 }
383​
384 async function startChild(
385 input: { threadId: string; runId: string; subagentRunId?: string },
386 chunk: Extract<StreamChunk, { type: 'SUBAGENT_STARTED' }>,
387 ) {
388 const id = chunk.subagentRunId
389 const call =
390 chunk.parentToolCallId === undefined
391 ? undefined
392 : calls.get(chunk.parentToolCallId)
393 if (chunk.parentToolCallId !== undefined) {
394 calls.delete(chunk.parentToolCallId)
395 }
396 const record = await stores.runs?.createOrResume({
397 runId: id,
398 threadId: childStoreId(id),
399 startedAt: Date.now(),
400 parentRunId: chunk.parentSubagentRunId ?? input.runId,
401 subagentRunId: id,
402 name: chunk.name,
403 })
404 const existing = children.get(id)
405 if (existing) {
406 existing.threadId = input.threadId
407 existing.runId = input.runId
408 existing.status = 'running'
409 delete existing.interruptIds
410 if (chunk.metadata !== undefined) existing.metadata = chunk.metadata
411 } else {
412 // A resume or a continue goes on from the stored transcript.
413 const raw = await loadMessages(childStoreId(id))
414 const stored = withoutPlaceholder(raw)
415 const marker = storedMarker(raw)
416 // A resume keeps the base of the call it resumes. A new call starts
417 // after the whole stored transcript.
418 const resumes = storedSubagentInfo(raw)?.status === 'suspended'
419 // An agent with `inputSchema` has its checked input on the card. An
420 // agent without one gets the `prompt` of the call as a user message.
421 const checked = subagentInputOf(chunk.metadata)
422 // Only the first call gives the task. A later call keeps it.
423 const prompt =
424 raw.length > 0
425 ? marker.prompt
426 : checked === undefined
427 ? promptOf(call)
428 : JSON.stringify(checked)
429 // Core does not stream that user message, so store it here.
430 const followUp =
431 raw.length > 0 && !resumes && checked === undefined
432 ? promptOf(call)
433 : undefined
434 const initial: Array<ModelMessage> =
435 followUp === undefined
436 ? stored
437 : [
438 ...stored,
439 {
440 id: `${childStoreId(id)}:prompt:${stored.length}`,
441 role: 'user',
442 content: followUp,
443 },
444 ]
445 children.set(id, {
446 name: chunk.name,
447 threadId: input.threadId,
448 runId: input.runId,
449 savedAt: 0,
450 parentRunId:
451 record?.parentRunId ?? chunk.parentSubagentRunId ?? input.runId,
452 ...(chunk.parentSubagentRunId !== undefined && {
453 parentSubagentRunId: chunk.parentSubagentRunId,
454 }),
455 ...(chunk.parentToolCallId !== undefined && {
456 parentToolCallId: chunk.parentToolCallId,
457 }),
458 ...(chunk.metadata !== undefined && { metadata: chunk.metadata }),
459 processor: new StreamProcessor({
460 subagentRunId: id,
461 initialMessages: modelMessagesToUIMessages(initial),
462 }),
463 status: 'running',
464 // No stored base means the cut point is unknown. Keep every message
465 // that is already stored. `0` would drop them on the next continue.
466 base:
467 resumes && marker.base !== undefined ? marker.base : stored.length,
468 // A nested child belongs to the thread of the child that started it.
469 parentThreadId: ownerThread({
470 threadId: input.threadId,
471 subagentRunId: chunk.parentSubagentRunId ?? input.subagentRunId,
472 }),
473 ...(prompt !== undefined && { prompt }),
474 })
475 }
476 if (record && record.status !== 'running') {
477 await stores.runs?.update(id, { status: 'running' })
478 }
479 // The parent child shows this one as a nested card.
480 if (chunk.parentSubagentRunId !== undefined) {
481 children.get(chunk.parentSubagentRunId)?.processor.processChunk(chunk)
482 }
483 await saveChild(id)
484 }
485​
486 /**
487 * The stored transcript of a child, for a call that continues it by
488 * `sessionId`. It starts with the task of the first call as a user message.
489 * `undefined` when `caller` did not start a child with this id. While the
490 * child waits on an interrupt, it is the transcript from before that call:
491 * the resume adds the newer messages of the child itself.
492 */
493 async function loadChild(
494 subagentRunId: string,
495 caller: { threadId: string; subagentRunId?: string },
496 ) {
497 const stored = await loadMessages(childStoreId(subagentRunId))
498 const marker = storedMarker(stored)
499 // The id can come from a prompt injection. Never load the child of an
500 // other thread.
501 if (marker.parentThreadId !== ownerThread(caller)) return undefined
502 const messages = withoutPlaceholder(stored)
503 const info = storedSubagentInfo(stored)
504 const waits = info?.status === 'suspended'
505 const transcript =
506 waits && marker.base !== undefined
507 ? messages.slice(0, marker.base)
508 : messages
509 const task: Array<ModelMessage> =
510 marker.prompt === undefined
511 ? []
512 : [
513 {
514 id: `${childStoreId(subagentRunId)}:prompt`,
515 role: 'user',
516 content: marker.prompt,
517 },
518 ]
519 // The agent the child ran under. Only that agent can continue it.
520 return {
521 messages: [...task, ...transcript],
522 ...(info !== undefined && { agent: info.name }),
523 // A resume reads the waiting call from here, not from the client card.
524 ...(waits && { pending: messages.slice(marker.base ?? 0) }),
525 }
526 }
527​
528 async function settleChild(
529 chunk: Extract<
530 StreamChunk,
531 { type: 'SUBAGENT_FINISHED' | 'SUBAGENT_ERROR' }
532 >,
533 ) {
534 const id = chunk.subagentRunId
535 const note = children.get(id)
536 if (!note) return
537 try {
538 await writeSettled(note, id, chunk)
539 } finally {
540 // A routed child stays until its run ends: the parent message reads its
541 // text. Nested children and children started by a tool call go now.
542 if (
543 note.parentSubagentRunId !== undefined ||
544 note.parentToolCallId !== undefined
545 ) {
546 children.delete(id)
547 }
548 }
549 }
550​
551 async function writeSettled(
552 note: ChildNote,
553 id: string,
554 chunk: Extract<
555 StreamChunk,
556 { type: 'SUBAGENT_FINISHED' | 'SUBAGENT_ERROR' }
557 >,
558 ) {
559 note.processor.finalizeStream()
560 if (note.parentSubagentRunId !== undefined) {
561 children.get(note.parentSubagentRunId)?.processor.processChunk(chunk)
562 }
563 if (chunk.type === 'SUBAGENT_ERROR') {
564 const stopped = chunk.message === 'Stopped'
565 note.status = 'error'
566 note.error = {
567 message: chunk.message,
568 ...(chunk.code !== undefined && { code: chunk.code }),
569 }
570 await saveChild(id)
571 await stores.runs?.update(id, {
572 status: stopped ? 'aborted' : 'failed',
573 finishedAt: Date.now(),
574 ...(!stopped ? { error: { message: chunk.message } } : {}),
575 })
576 return
577 }
578 if (chunk.outcome?.type === 'suspended') {
579 note.status = 'suspended'
580 note.interruptIds = chunk.outcome.interruptIds ?? []
581 await saveChild(id)
582 await stores.runs?.update(id, { status: 'interrupted' })
583 return
584 }
585 note.status = 'finished'
586 await saveChild(id)
587 await stores.runs?.update(id, {
588 status: 'completed',
589 finishedAt: Date.now(),
590 })
591 }
592​
593 async function commitAnswers(runId: string) {
594 const entries = answered.get(runId) ?? []
595 answered.delete(runId)
596 for (const entry of entries) {
597 if (entry.status === 'cancelled') {
598 await stores.interrupts?.cancel(entry.interruptId)
599 } else {
600 await stores.interrupts?.resolve(entry.interruptId, entry.payload)
601 }
602 }
603 }
604​
605 /** The notes a run fed. */
606 function notesOf(runId: string) {
607 return [...children].filter(([, note]) => note.runId === runId)
608 }
609​
610 function forget(runId: string) {
611 for (const [id] of notesOf(runId)) children.delete(id)
612 parentSavedAt.delete(runId)
613 }
614​
615 async function settleOpenChildren(
616 runId: string,
617 status: 'completed' | 'failed' | 'aborted',
618 error?: { message: string },
619 ) {
620 for (const [subagentRunId] of notesOf(runId)) {
621 await saveChild(subagentRunId)
622 const current = await stores.runs?.get(subagentRunId)
623 if (current && current.status !== 'running') continue
624 await stores.runs?.update(subagentRunId, {
625 status,
626 finishedAt: Date.now(),
627 ...(error ? { error } : {}),
628 })
629 }
630 }
631​
632 /** Write the parent messages of this thread's routed children. */
633 async function saveParents(threadId: string) {
634 const runIds = new Set(
635 [...children.values()]
636 .filter((note) => note.threadId === threadId)
637 .map((note) => note.parentRunId),
638 )
639 for (const runId of runIds) await saveParent(threadId, runId)
640 }
641​
642 return {
643 loadChild,
644​
645 async start(input: {
646 threadId: string
647 runId: string
648 messages: ReadonlyArray<UIMessage | ModelMessage>
649 resume?: ReadonlyArray<RunAgentResumeItem>
650 }) {
651 await stores.runs?.createOrResume({
652 runId: input.runId,
653 threadId: input.threadId,
654 startedAt: Date.now(),
655 })
656 if (input.resume?.length) answered.set(input.runId, [...input.resume])
657 const incoming = convertMessagesToModelMessages([...input.messages])
658 const stored = await loadMessages(input.threadId)
659 const merged = mergeStoredMessages(stored, incoming)
660 await stores.messages.saveThread(
661 input.threadId,
662 keepSubagentRunIds(stored, merged),
663 )
664 },
665​
666 async chunk(input: {
667 threadId: string
668 runId: string
669 /** Set when the chat that streams this chunk is a child itself. */
670 subagentRunId?: string
671 chunk: StreamChunk
672 }) {
673 const chunk = input.chunk
674 if (chunk.type === 'TOOL_CALL_START') {
675 calls.set(chunk.toolCallId, {
676 name: chunk.toolCallName,
677 args: '',
678 runId: input.runId,
679 })
680 }
681 if (chunk.type === 'TOOL_CALL_ARGS') {
682 const call = calls.get(chunk.toolCallId)
683 if (call) call.args += chunk.delta
684 }
685 if (chunk.type === 'TOOL_CALL_RESULT') calls.delete(chunk.toolCallId)
686 if (chunk.type === 'SUBAGENT_STARTED') {
687 await startChild(input, chunk)
688 return
689 }
690 if (
691 chunk.type === 'SUBAGENT_FINISHED' ||
692 chunk.type === 'SUBAGENT_ERROR'
693 ) {
694 await settleChild(chunk)
695 await saveParents(input.threadId)
696 return
697 }
698 const subagentRunId = readSubagentRunId(chunk)
699 if (!subagentRunId) return
700 const notes = lineage(subagentRunId)
701 if (notes.length === 0) return
702 for (const note of notes) note.processor.processChunk(chunk)
703 // A streaming child writes at most once per interval. Its terminal
704 // event and the run's end always write.
705 const now = Date.now()
706 const note = notes[0]
707 if (note && now - note.savedAt >= intervalMs) {
708 await saveChild(subagentRunId)
709 }
710 if (
711 chunk.type === 'TEXT_MESSAGE_CONTENT' &&
712 now - (parentSavedAt.get(input.runId) ?? 0) >= intervalMs
713 ) {
714 parentSavedAt.set(input.runId, now)
715 await saveParents(input.threadId)
716 }
717 },
718​
719 async suspend(input: {
720 threadId: string
721 runId: string
722 interrupts: ReadonlyArray<Interrupt>
723 }) {
724 await commitAnswers(input.runId)
725 await saveParents(input.threadId)
726 for (const [subagentRunId] of notesOf(input.runId)) {
727 await saveChild(subagentRunId)
728 }
729 for (const interrupt of input.interrupts) {
730 await stores.interrupts?.create({
731 interruptId: interrupt.id,
732 runId: input.runId,
733 threadId: input.threadId,
734 requestedAt: Date.now(),
735 payload: { ...interrupt },
736 })
737 }
738 await stores.runs?.update(input.runId, { status: 'interrupted' })
739 forget(input.runId)
740 },
741​
742 async finish(input: { threadId: string; runId: string }) {
743 dropCalls(input.runId)
744 await commitAnswers(input.runId)
745 await saveParents(input.threadId)
746 await settleOpenChildren(input.runId, 'completed')
747 await stores.runs?.update(input.runId, {
748 status: 'completed',
749 finishedAt: Date.now(),
750 })
751 forget(input.runId)
752 },
753​
754 async abort(input: { threadId: string; runId: string; error?: unknown }) {
755 dropCalls(input.runId)
756 const aborted =
757 input.error instanceof Error && input.error.name === 'AbortError'
758 const message =
759 input.error instanceof Error ? input.error.message : 'Run failed'
760 await settleOpenChildren(
761 input.runId,
762 aborted ? 'aborted' : 'failed',
763 aborted ? undefined : { message },
764 )
765 await saveParents(input.threadId)
766 await stores.runs?.update(input.runId, {
767 status: aborted ? 'aborted' : 'failed',
768 finishedAt: Date.now(),
769 ...(!aborted ? { error: { message } } : {}),
770 })
771 answered.delete(input.runId)
772 forget(input.runId)
773 },
774 }