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

subagent-runs.ts

773 lines25.1 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 }
524 }
525​
526 async function settleChild(
527 chunk: Extract<
528 StreamChunk,
529 { type: 'SUBAGENT_FINISHED' | 'SUBAGENT_ERROR' }
530 >,
531 ) {
532 const id = chunk.subagentRunId
533 const note = children.get(id)
534 if (!note) return
535 try {
536 await writeSettled(note, id, chunk)
537 } finally {
538 // A routed child stays until its run ends: the parent message reads its
539 // text. Nested children and children started by a tool call go now.
540 if (
541 note.parentSubagentRunId !== undefined ||
542 note.parentToolCallId !== undefined
543 ) {
544 children.delete(id)
545 }
546 }
547 }
548​
549 async function writeSettled(
550 note: ChildNote,
551 id: string,
552 chunk: Extract<
553 StreamChunk,
554 { type: 'SUBAGENT_FINISHED' | 'SUBAGENT_ERROR' }
555 >,
556 ) {
557 note.processor.finalizeStream()
558 if (note.parentSubagentRunId !== undefined) {
559 children.get(note.parentSubagentRunId)?.processor.processChunk(chunk)
560 }
561 if (chunk.type === 'SUBAGENT_ERROR') {
562 const stopped = chunk.message === 'Stopped'
563 note.status = 'error'
564 note.error = {
565 message: chunk.message,
566 ...(chunk.code !== undefined && { code: chunk.code }),
567 }
568 await saveChild(id)
569 await stores.runs?.update(id, {
570 status: stopped ? 'aborted' : 'failed',
571 finishedAt: Date.now(),
572 ...(!stopped ? { error: { message: chunk.message } } : {}),
573 })
574 return
575 }
576 if (chunk.outcome?.type === 'suspended') {
577 note.status = 'suspended'
578 note.interruptIds = chunk.outcome.interruptIds ?? []
579 await saveChild(id)
580 await stores.runs?.update(id, { status: 'interrupted' })
581 return
582 }
583 note.status = 'finished'
584 await saveChild(id)
585 await stores.runs?.update(id, {
586 status: 'completed',
587 finishedAt: Date.now(),
588 })
589 }
590​
591 async function commitAnswers(runId: string) {
592 const entries = answered.get(runId) ?? []
593 answered.delete(runId)
594 for (const entry of entries) {
595 if (entry.status === 'cancelled') {
596 await stores.interrupts?.cancel(entry.interruptId)
597 } else {
598 await stores.interrupts?.resolve(entry.interruptId, entry.payload)
599 }
600 }
601 }
602​
603 /** The notes a run fed. */
604 function notesOf(runId: string) {
605 return [...children].filter(([, note]) => note.runId === runId)
606 }
607​
608 function forget(runId: string) {
609 for (const [id] of notesOf(runId)) children.delete(id)
610 parentSavedAt.delete(runId)
611 }
612​
613 async function settleOpenChildren(
614 runId: string,
615 status: 'completed' | 'failed' | 'aborted',
616 error?: { message: string },
617 ) {
618 for (const [subagentRunId] of notesOf(runId)) {
619 await saveChild(subagentRunId)
620 const current = await stores.runs?.get(subagentRunId)
621 if (current && current.status !== 'running') continue
622 await stores.runs?.update(subagentRunId, {
623 status,
624 finishedAt: Date.now(),
625 ...(error ? { error } : {}),
626 })
627 }
628 }
629​
630 /** Write the parent messages of this thread's routed children. */
631 async function saveParents(threadId: string) {
632 const runIds = new Set(
633 [...children.values()]
634 .filter((note) => note.threadId === threadId)
635 .map((note) => note.parentRunId),
636 )
637 for (const runId of runIds) await saveParent(threadId, runId)
638 }
639​
640 return {
641 loadChild,
642​
643 async start(input: {
644 threadId: string
645 runId: string
646 messages: ReadonlyArray<UIMessage | ModelMessage>
647 resume?: ReadonlyArray<RunAgentResumeItem>
648 }) {
649 await stores.runs?.createOrResume({
650 runId: input.runId,
651 threadId: input.threadId,
652 startedAt: Date.now(),
653 })
654 if (input.resume?.length) answered.set(input.runId, [...input.resume])
655 const incoming = convertMessagesToModelMessages([...input.messages])
656 const stored = await loadMessages(input.threadId)
657 const merged = mergeStoredMessages(stored, incoming)
658 await stores.messages.saveThread(
659 input.threadId,
660 keepSubagentRunIds(stored, merged),
661 )
662 },
663​
664 async chunk(input: {
665 threadId: string
666 runId: string
667 /** Set when the chat that streams this chunk is a child itself. */
668 subagentRunId?: string
669 chunk: StreamChunk
670 }) {
671 const chunk = input.chunk
672 if (chunk.type === 'TOOL_CALL_START') {
673 calls.set(chunk.toolCallId, {
674 name: chunk.toolCallName,
675 args: '',
676 runId: input.runId,
677 })
678 }
679 if (chunk.type === 'TOOL_CALL_ARGS') {
680 const call = calls.get(chunk.toolCallId)
681 if (call) call.args += chunk.delta
682 }
683 if (chunk.type === 'TOOL_CALL_RESULT') calls.delete(chunk.toolCallId)
684 if (chunk.type === 'SUBAGENT_STARTED') {
685 await startChild(input, chunk)
686 return
687 }
688 if (
689 chunk.type === 'SUBAGENT_FINISHED' ||
690 chunk.type === 'SUBAGENT_ERROR'
691 ) {
692 await settleChild(chunk)
693 await saveParents(input.threadId)
694 return
695 }
696 const subagentRunId = readSubagentRunId(chunk)
697 if (!subagentRunId) return
698 const notes = lineage(subagentRunId)
699 if (notes.length === 0) return
700 for (const note of notes) note.processor.processChunk(chunk)
701 // A streaming child writes at most once per interval. Its terminal
702 // event and the run's end always write.
703 const now = Date.now()
704 const note = notes[0]
705 if (note && now - note.savedAt >= intervalMs) {
706 await saveChild(subagentRunId)
707 }
708 if (
709 chunk.type === 'TEXT_MESSAGE_CONTENT' &&
710 now - (parentSavedAt.get(input.runId) ?? 0) >= intervalMs
711 ) {
712 parentSavedAt.set(input.runId, now)
713 await saveParents(input.threadId)
714 }
715 },
716​
717 async suspend(input: {
718 threadId: string
719 runId: string
720 interrupts: ReadonlyArray<Interrupt>
721 }) {
722 await commitAnswers(input.runId)
723 await saveParents(input.threadId)
724 for (const [subagentRunId] of notesOf(input.runId)) {
725 await saveChild(subagentRunId)
726 }
727 for (const interrupt of input.interrupts) {
728 await stores.interrupts?.create({
729 interruptId: interrupt.id,
730 runId: input.runId,
731 threadId: input.threadId,
732 requestedAt: Date.now(),
733 payload: { ...interrupt },
734 })
735 }
736 await stores.runs?.update(input.runId, { status: 'interrupted' })
737 forget(input.runId)
738 },
739​
740 async finish(input: { threadId: string; runId: string }) {
741 dropCalls(input.runId)
742 await commitAnswers(input.runId)
743 await saveParents(input.threadId)
744 await settleOpenChildren(input.runId, 'completed')
745 await stores.runs?.update(input.runId, {
746 status: 'completed',
747 finishedAt: Date.now(),
748 })
749 forget(input.runId)
750 },
751​
752 async abort(input: { threadId: string; runId: string; error?: unknown }) {
753 dropCalls(input.runId)
754 const aborted =
755 input.error instanceof Error && input.error.name === 'AbortError'
756 const message =
757 input.error instanceof Error ? input.error.message : 'Run failed'
758 await settleOpenChildren(
759 input.runId,
760 aborted ? 'aborted' : 'failed',
761 aborted ? undefined : { message },
762 )
763 await saveParents(input.threadId)
764 await stores.runs?.update(input.runId, {
765 status: aborted ? 'aborted' : 'failed',
766 finishedAt: Date.now(),
767 ...(!aborted ? { error: { message } } : {}),
768 })
769 answered.delete(input.runId)
770 forget(input.runId)
771 },
772 }