@sixb/agent 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (219) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +31 -2
  3. package/dist/abort.d.ts +6 -0
  4. package/dist/abort.d.ts.map +1 -0
  5. package/dist/agent-prompt.d.ts +120 -0
  6. package/dist/agent-prompt.d.ts.map +1 -0
  7. package/dist/agent-runtime/errors.d.ts +13 -0
  8. package/dist/agent-runtime/errors.d.ts.map +1 -0
  9. package/dist/agent-runtime/preflight.d.ts +18 -0
  10. package/dist/agent-runtime/preflight.d.ts.map +1 -0
  11. package/dist/agent-runtime/profile.d.ts +14 -0
  12. package/dist/agent-runtime/profile.d.ts.map +1 -0
  13. package/dist/artifacts/layout-check/layout-check.d.ts +87 -0
  14. package/dist/artifacts/layout-check/layout-check.d.ts.map +1 -0
  15. package/dist/artifacts/materialize.d.ts +115 -0
  16. package/dist/artifacts/materialize.d.ts.map +1 -0
  17. package/dist/artifacts/publish-tool.d.ts +86 -0
  18. package/dist/artifacts/publish-tool.d.ts.map +1 -0
  19. package/dist/ask-parent-tool.d.ts +36 -0
  20. package/dist/ask-parent-tool.d.ts.map +1 -0
  21. package/dist/attachments.d.ts +68 -0
  22. package/dist/attachments.d.ts.map +1 -0
  23. package/dist/child-files.d.ts +96 -0
  24. package/dist/child-files.d.ts.map +1 -0
  25. package/dist/child-questions.d.ts +24 -0
  26. package/dist/child-questions.d.ts.map +1 -0
  27. package/dist/computer-runner.d.ts +65 -0
  28. package/dist/computer-runner.d.ts.map +1 -0
  29. package/dist/context-budget.d.ts +28 -0
  30. package/dist/context-budget.d.ts.map +1 -0
  31. package/dist/context-compaction.d.ts +48 -0
  32. package/dist/context-compaction.d.ts.map +1 -0
  33. package/dist/conversation-memory.d.ts +21 -0
  34. package/dist/conversation-memory.d.ts.map +1 -0
  35. package/dist/errors.d.ts +46 -0
  36. package/dist/errors.d.ts.map +1 -0
  37. package/dist/execution-plan.d.ts +34 -0
  38. package/dist/execution-plan.d.ts.map +1 -0
  39. package/dist/failure.d.ts +14 -0
  40. package/dist/failure.d.ts.map +1 -0
  41. package/dist/family-mailbox.d.ts +60 -0
  42. package/dist/family-mailbox.d.ts.map +1 -0
  43. package/dist/file-ref.d.ts +6 -0
  44. package/dist/file-ref.d.ts.map +1 -0
  45. package/dist/image-attachments.d.ts +34 -0
  46. package/dist/image-attachments.d.ts.map +1 -0
  47. package/dist/index.d.ts +35 -0
  48. package/dist/index.d.ts.map +1 -0
  49. package/dist/index.js +12168 -0
  50. package/dist/index.js.map +65 -0
  51. package/dist/message-authors.d.ts +34 -0
  52. package/dist/message-authors.d.ts.map +1 -0
  53. package/dist/message-times.d.ts +8 -0
  54. package/dist/message-times.d.ts.map +1 -0
  55. package/dist/model-adapters.d.ts +55 -0
  56. package/dist/model-adapters.d.ts.map +1 -0
  57. package/dist/model-lines.d.ts +16 -0
  58. package/dist/model-lines.d.ts.map +1 -0
  59. package/dist/requester.d.ts +15 -0
  60. package/dist/requester.d.ts.map +1 -0
  61. package/dist/run-agent-turn.d.ts +63 -0
  62. package/dist/run-agent-turn.d.ts.map +1 -0
  63. package/dist/run-child.d.ts +77 -0
  64. package/dist/run-child.d.ts.map +1 -0
  65. package/dist/run-conversation-turn.d.ts +42 -0
  66. package/dist/run-conversation-turn.d.ts.map +1 -0
  67. package/dist/run-credential.d.ts +22 -0
  68. package/dist/run-credential.d.ts.map +1 -0
  69. package/dist/run-environment.d.ts +115 -0
  70. package/dist/run-environment.d.ts.map +1 -0
  71. package/dist/run-fate.d.ts +15 -0
  72. package/dist/run-fate.d.ts.map +1 -0
  73. package/dist/run-sandbox.d.ts +60 -0
  74. package/dist/run-sandbox.d.ts.map +1 -0
  75. package/dist/run-subagent.d.ts +51 -0
  76. package/dist/run-subagent.d.ts.map +1 -0
  77. package/dist/run-workflow-agent-node.d.ts +41 -0
  78. package/dist/run-workflow-agent-node.d.ts.map +1 -0
  79. package/dist/sandbox-api-context.d.ts +34 -0
  80. package/dist/sandbox-api-context.d.ts.map +1 -0
  81. package/dist/sandbox-file-registry.d.ts +9 -0
  82. package/dist/sandbox-file-registry.d.ts.map +1 -0
  83. package/dist/sandbox-files.d.ts +71 -0
  84. package/dist/sandbox-files.d.ts.map +1 -0
  85. package/dist/sandbox-handle.d.ts +15 -0
  86. package/dist/sandbox-handle.d.ts.map +1 -0
  87. package/dist/sandbox-readiness.d.ts +8 -0
  88. package/dist/sandbox-readiness.d.ts.map +1 -0
  89. package/dist/skills/built-in.d.ts +15 -0
  90. package/dist/skills/built-in.d.ts.map +1 -0
  91. package/dist/subagent-continuation.d.ts +27 -0
  92. package/dist/subagent-continuation.d.ts.map +1 -0
  93. package/dist/subagent-inbox.d.ts +53 -0
  94. package/dist/subagent-inbox.d.ts.map +1 -0
  95. package/dist/subagent-tools.d.ts +282 -0
  96. package/dist/subagent-tools.d.ts.map +1 -0
  97. package/dist/thread-context.d.ts +12 -0
  98. package/dist/thread-context.d.ts.map +1 -0
  99. package/dist/tools/attachments.d.ts +11 -0
  100. package/dist/tools/attachments.d.ts.map +1 -0
  101. package/dist/tools/bash.d.ts +60 -0
  102. package/dist/tools/bash.d.ts.map +1 -0
  103. package/dist/tools/model-spec.d.ts +4 -0
  104. package/dist/tools/model-spec.d.ts.map +1 -0
  105. package/dist/tools/read.d.ts +43 -0
  106. package/dist/tools/read.d.ts.map +1 -0
  107. package/dist/tools/result-media.d.ts +22 -0
  108. package/dist/tools/result-media.d.ts.map +1 -0
  109. package/dist/tools/result-output.d.ts +18 -0
  110. package/dist/tools/result-output.d.ts.map +1 -0
  111. package/dist/tools/tool-files.d.ts +59 -0
  112. package/dist/tools/tool-files.d.ts.map +1 -0
  113. package/dist/tools/view-file.d.ts +40 -0
  114. package/dist/tools/view-file.d.ts.map +1 -0
  115. package/dist/tsconfig.json +5 -0
  116. package/dist/turn-runtime.d.ts +19 -0
  117. package/dist/turn-runtime.d.ts.map +1 -0
  118. package/dist/types.d.ts +76 -0
  119. package/dist/types.d.ts.map +1 -0
  120. package/dist/workflow-input-attachments.d.ts +18 -0
  121. package/dist/workflow-input-attachments.d.ts.map +1 -0
  122. package/package.json +59 -4
  123. package/src/abort.ts +40 -0
  124. package/src/agent-prompt.ts +758 -0
  125. package/src/agent-runtime/errors.ts +44 -0
  126. package/src/agent-runtime/preflight.ts +314 -0
  127. package/src/agent-runtime/profile.ts +23 -0
  128. package/src/artifacts/layout-check/check.cjs +478 -0
  129. package/src/artifacts/layout-check/layout-check.ts +460 -0
  130. package/src/artifacts/materialize.ts +380 -0
  131. package/src/artifacts/publish-tool.ts +700 -0
  132. package/src/ask-parent-tool.ts +100 -0
  133. package/src/attachments.ts +850 -0
  134. package/src/child-files.ts +540 -0
  135. package/src/child-questions.ts +42 -0
  136. package/src/computer-runner.ts +284 -0
  137. package/src/context-budget.ts +161 -0
  138. package/src/context-compaction.ts +529 -0
  139. package/src/conversation-memory.ts +45 -0
  140. package/src/errors.ts +85 -0
  141. package/src/execution-plan.ts +50 -0
  142. package/src/failure.ts +71 -0
  143. package/src/family-mailbox.ts +189 -0
  144. package/src/file-ref.ts +18 -0
  145. package/src/image-attachments.ts +322 -0
  146. package/src/index.ts +54 -0
  147. package/src/message-authors.ts +77 -0
  148. package/src/message-times.ts +21 -0
  149. package/src/model-adapters.ts +227 -0
  150. package/src/model-lines.ts +28 -0
  151. package/src/requester.ts +21 -0
  152. package/src/run-agent-turn.ts +347 -0
  153. package/src/run-child.ts +319 -0
  154. package/src/run-conversation-turn.ts +257 -0
  155. package/src/run-credential.ts +55 -0
  156. package/src/run-environment.ts +769 -0
  157. package/src/run-fate.ts +51 -0
  158. package/src/run-sandbox.ts +63 -0
  159. package/src/run-subagent.ts +347 -0
  160. package/src/run-workflow-agent-node.ts +270 -0
  161. package/src/sandbox-api-context.ts +234 -0
  162. package/src/sandbox-file-registry.ts +26 -0
  163. package/src/sandbox-files.ts +326 -0
  164. package/src/sandbox-handle.ts +19 -0
  165. package/src/sandbox-readiness.ts +22 -0
  166. package/src/skills/built-in.ts +183 -0
  167. package/src/skills/sixb-artifacts/SKILL.md +95 -0
  168. package/src/skills/sixb-artifacts/canvas.md +104 -0
  169. package/src/skills/sixb-artifacts/document.md +63 -0
  170. package/src/skills/sixb-artifacts/examples/canvas/onboarding-flow/boards/first-job.html +42 -0
  171. package/src/skills/sixb-artifacts/examples/canvas/onboarding-flow/boards/region.html +29 -0
  172. package/src/skills/sixb-artifacts/examples/canvas/onboarding-flow/boards/shared.css +35 -0
  173. package/src/skills/sixb-artifacts/examples/canvas/onboarding-flow/boards/welcome.html +31 -0
  174. package/src/skills/sixb-artifacts/examples/canvas/onboarding-flow/canvas.json +107 -0
  175. package/src/skills/sixb-artifacts/examples/canvas/retro/canvas.json +158 -0
  176. package/src/skills/sixb-artifacts/examples/document/incident-report/document.md +35 -0
  177. package/src/skills/sixb-artifacts/examples/document/operations-review/document.md +41 -0
  178. package/src/skills/sixb-artifacts/examples/document/operations-review/figures/restorations.svg +1 -0
  179. package/src/skills/sixb-artifacts/examples/page/collections-desk/index.html +169 -0
  180. package/src/skills/sixb-artifacts/examples/page/collections-desk/queries/overdue.json +13 -0
  181. package/src/skills/sixb-artifacts/examples/page/dispatch-board/data/dispatch.json +234 -0
  182. package/src/skills/sixb-artifacts/examples/page/dispatch-board/index.html +245 -0
  183. package/src/skills/sixb-artifacts/examples/page/fleet-planner/data/plan.json +53 -0
  184. package/src/skills/sixb-artifacts/examples/page/fleet-planner/index.html +462 -0
  185. package/src/skills/sixb-artifacts/examples/page/service-explorer/data/service.json +276 -0
  186. package/src/skills/sixb-artifacts/examples/page/service-explorer/index.html +549 -0
  187. package/src/skills/sixb-artifacts/examples/sheet/overdue-invoices/queries/overdue.json +13 -0
  188. package/src/skills/sixb-artifacts/examples/sheet/overdue-invoices/workbook.json +30 -0
  189. package/src/skills/sixb-artifacts/examples/sheet/parts-inventory/sheets/Inventory.csv +13 -0
  190. package/src/skills/sixb-artifacts/examples/sheet/parts-inventory/sheets/Spend.csv +6 -0
  191. package/src/skills/sixb-artifacts/examples/sheet/parts-inventory/workbook.json +47 -0
  192. package/src/skills/sixb-artifacts/examples/sheet/service-metrics/sheets/Quarters.csv +5 -0
  193. package/src/skills/sixb-artifacts/examples/sheet/service-metrics/sheets/Regions.csv +5 -0
  194. package/src/skills/sixb-artifacts/examples/sheet/service-metrics/workbook.json +78 -0
  195. package/src/skills/sixb-artifacts/examples/slides/launch-plan/index.html +63 -0
  196. package/src/skills/sixb-artifacts/examples/slides/q3-review/index.html +133 -0
  197. package/src/skills/sixb-artifacts/file.md +17 -0
  198. package/src/skills/sixb-artifacts/page.md +215 -0
  199. package/src/skills/sixb-artifacts/queries.md +66 -0
  200. package/src/skills/sixb-artifacts/references.md +68 -0
  201. package/src/skills/sixb-artifacts/sheet.md +223 -0
  202. package/src/skills/sixb-artifacts/slides.md +137 -0
  203. package/src/skills/sixb-memory/SKILL.md +68 -0
  204. package/src/skills/text-assets.d.ts +25 -0
  205. package/src/subagent-continuation.ts +51 -0
  206. package/src/subagent-inbox.ts +101 -0
  207. package/src/subagent-tools.ts +1609 -0
  208. package/src/thread-context.ts +25 -0
  209. package/src/tools/attachments.ts +28 -0
  210. package/src/tools/bash.ts +217 -0
  211. package/src/tools/model-spec.ts +22 -0
  212. package/src/tools/read.ts +262 -0
  213. package/src/tools/result-media.ts +147 -0
  214. package/src/tools/result-output.ts +44 -0
  215. package/src/tools/tool-files.ts +204 -0
  216. package/src/tools/view-file.ts +155 -0
  217. package/src/turn-runtime.ts +33 -0
  218. package/src/types.ts +79 -0
  219. package/src/workflow-input-attachments.ts +140 -0
@@ -0,0 +1,347 @@
1
+ import type { AgentMessage, AgentMessagePart } from "@sixb/core"
2
+ import {
3
+ type AgentRunSession,
4
+ createAgentMessageId,
5
+ type PausableModelLoopResult,
6
+ runModelLoop,
7
+ toModelMessages,
8
+ } from "@sixb/core/internal/agents"
9
+ import { isAbortError } from "@sixb/core/internal/workers"
10
+ import {
11
+ type AgentRunDiagnostic,
12
+ type AgentRunFinishReason,
13
+ type AgentRunRecord,
14
+ type ConversationAgentRunRecord,
15
+ coerceAgentRunFinishReason,
16
+ } from "@sixb/core/storage"
17
+ import { attachmentKey, toolResultAttachmentKey } from "./attachments"
18
+ import { throwIfExecutionLost } from "./errors"
19
+ import type { ResolvedAgentExecutionPlan } from "./execution-plan"
20
+ import { type ConversationReaders, conversationAuthors } from "./message-authors"
21
+ import { userMessageTimes } from "./message-times"
22
+ import { agentTraceFromModelSteps, agentTraceFromPartialModelLoop } from "./model-adapters"
23
+ import { monitorSandboxReadiness } from "./sandbox-readiness"
24
+ import type { LoadedAgentThreadModelContext } from "./thread-context"
25
+ import { type AgentTurnRuntime, createAgentTurnRuntime } from "./turn-runtime"
26
+ import type { AgentTurnContext } from "./types"
27
+
28
+ export interface RunAgentTurnInput {
29
+ /** The worker's stable execution context (storage, tools and stream sink). */
30
+ readonly context: AgentTurnContext
31
+ readonly plan: ResolvedAgentExecutionPlan
32
+ /** The run this delivery reserved or reclaimed with its execution token. */
33
+ readonly run: ConversationAgentRunRecord
34
+ /** The run's session: its finish, and every other write, are fenced by its execution token. */
35
+ readonly session: AgentRunSession
36
+ /** The worker's shutdown signal. */
37
+ readonly signal: AbortSignal
38
+ /**
39
+ * The worker's own stop, when `signal` also carries a user cancel. A turn it ends first is
40
+ * recorded with `finishReason: "interrupted"` so the user can resume it.
41
+ */
42
+ readonly stopSignal?: AbortSignal
43
+ /** Shared with preflight when this turn performed compaction. */
44
+ readonly runtime?: AgentTurnRuntime
45
+ /** The thread and who can read it now; without it the model is told nothing of its people. */
46
+ readonly conversation?: ConversationReaders
47
+ /** The history the turn runs on: as it started, or as its compaction left it. */
48
+ readonly threadContext: LoadedAgentThreadModelContext
49
+ /** What the turn's children ask it, and the work it waits for, when it can delegate. */
50
+ readonly children?: TurnChildren
51
+ }
52
+
53
+ /**
54
+ * How a turn hears the questions its children ask, leaves them waiting when it ends, and waits for
55
+ * those still at work when it pauses.
56
+ */
57
+ export interface TurnChildren {
58
+ /** Read after the conversation: children of earlier turns still waiting on their question. */
59
+ readonly waiting?: string
60
+ /** The questions the model has not read yet, read in one more step when it answers. */
61
+ unread(): Promise<string | undefined>
62
+ /**
63
+ * Before the turn records its end: each child still waiting on its question pauses on it, and
64
+ * the turn waits until it has. Only then can its end cancel the others.
65
+ */
66
+ defer(signal: AbortSignal): Promise<void>
67
+ /**
68
+ * Before a pausing turn records its end: wait until none of its children is at work. Its end
69
+ * cancels those still at work; one that holds a call pauses by itself.
70
+ */
71
+ settle(signal: AbortSignal): Promise<void>
72
+ }
73
+
74
+ /** Drive one provider-neutral model/tool turn to completion and persist it. */
75
+ export async function runAgentTurn(input: RunAgentTurnInput): Promise<AgentRunRecord> {
76
+ const { context, plan, run, signal } = input
77
+ const { id: projectId, tools } = context
78
+ const runId = run.id
79
+
80
+ const { threadContext } = input
81
+ const { attachmentContext } = context
82
+ const sentTimes = userMessageTimes(threadContext.history, context.projectTimeZone)
83
+ const authors = input.conversation
84
+ ? conversationAuthors({
85
+ conversation: input.conversation,
86
+ messages: threadContext.retainedMessages,
87
+ })
88
+ : undefined
89
+ const newestUserMessageId = threadContext.retainedMessages
90
+ .filter((message) => message.role === "user")
91
+ .at(-1)?.id
92
+
93
+ const modelMessages = toModelMessages(threadContext.modelMessages, {
94
+ // Who takes part, then when, then who wrote it: `<sixb_author>` stays the message's last tag.
95
+ userMessageSuffix: (message) => {
96
+ if (!message.id) return undefined
97
+
98
+ const closing = [
99
+ message.id === newestUserMessageId ? authors?.section : undefined,
100
+ sentTimes.get(message.id),
101
+ authors?.byMessageId.get(message.id),
102
+ ]
103
+ return closing.filter(Boolean).join("\n") || undefined
104
+ },
105
+ fileText: ({ message, partIndex }) =>
106
+ message.id
107
+ ? attachmentContext?.promptTextByPartKey.get(attachmentKey(message.id, partIndex))
108
+ : undefined,
109
+ fileData: ({ message, partIndex }) =>
110
+ message.id
111
+ ? attachmentContext?.modelFileDataByPartKey.get(attachmentKey(message.id, partIndex))
112
+ : undefined,
113
+ toolResultFileText: ({ message, partIndex, contentIndex }) =>
114
+ message.id
115
+ ? attachmentContext?.promptTextByPartKey.get(
116
+ toolResultAttachmentKey(message.id, partIndex, contentIndex)
117
+ )
118
+ : undefined,
119
+ })
120
+
121
+ const sandboxReadiness = monitorSandboxReadiness(context.sandboxReady)
122
+ // Preflight and the answer share one signal. Direct callers own their runtime.
123
+ const ownsRuntime = input.runtime === undefined
124
+ const runtime = input.runtime ?? createAgentTurnRuntime({ signal })
125
+ const abortSignal = AbortSignal.any([
126
+ runtime.signal,
127
+ sandboxReadiness.signal,
128
+ ...(context.environmentFailureSignal ? [context.environmentFailureSignal] : []),
129
+ ])
130
+ let interruptedParts: readonly AgentMessagePart[] | undefined
131
+ const stopReason = () =>
132
+ stoppedByWorker(signal, input.stopSignal) ? { finishReason: "interrupted" as const } : {}
133
+
134
+ const finalizeIfInterrupted = async (error?: unknown): Promise<AgentRunRecord | null> => {
135
+ throwIfExecutionLost(runtime.sourceSignal)
136
+ sandboxReadiness.throwIfFailed()
137
+ context.environmentFailureSignal?.throwIfAborted()
138
+ if (!abortSignal.aborted && (error === undefined || !isAbortError(error))) return null
139
+ return finalizeInterruptedTurn({
140
+ session: input.session,
141
+ context,
142
+ run,
143
+ modelId: plan.model.modelId,
144
+ ...stopReason(),
145
+ parts: interruptedParts,
146
+ })
147
+ }
148
+
149
+ try {
150
+ let chunkIndex = 0
151
+ let result: PausableModelLoopResult
152
+ try {
153
+ result = await runModelLoop({
154
+ model: plan.model,
155
+ messages: [
156
+ {
157
+ role: "system",
158
+ content: context.systemPrompt,
159
+ },
160
+ ...modelMessages,
161
+ ...(input.children?.waiting
162
+ ? [
163
+ {
164
+ role: "user" as const,
165
+ content: [{ type: "text" as const, text: input.children.waiting }],
166
+ },
167
+ ]
168
+ : []),
169
+ ],
170
+ tools,
171
+ ...(plan.reasoning === undefined ? {} : { reasoning: plan.reasoning }),
172
+ ...(context.prepareStep === undefined ? {} : { prepareStep: context.prepareStep }),
173
+ // A child's question the model has not read comes before its answer ends the turn.
174
+ ...(input.children === undefined
175
+ ? {}
176
+ : {
177
+ beforeComplete: async () => {
178
+ const unread = await input.children?.unread()
179
+ return unread
180
+ ? [{ role: "user", content: [{ type: "text", text: unread }] }]
181
+ : undefined
182
+ },
183
+ }),
184
+ signal: abortSignal,
185
+ onEvent: async (chunk) => {
186
+ await input.session.events.publishUiChunk({ run, chunkIndex: chunkIndex++, chunk })
187
+ },
188
+ // The approval records decide, never the tool output: the model can send a command's
189
+ // output elsewhere, or print one of its own. A held call waits for the children still
190
+ // at work: pausing ends the turn, and that would cancel them.
191
+ pauseAfterStep: () => input.session.heldCalls.pausesAfterStep(),
192
+ })
193
+ } catch (error) {
194
+ const interrupted = await finalizeIfInterrupted(error)
195
+ if (interrupted) return interrupted
196
+ throw error
197
+ }
198
+
199
+ interruptedParts =
200
+ result.status === "aborted"
201
+ ? agentTraceFromPartialModelLoop(result.steps, result.partialContent, {
202
+ threadId: run.threadId,
203
+ runId,
204
+ })
205
+ : agentTraceFromModelSteps(result.steps, { threadId: run.threadId, runId })
206
+
207
+ const interruptedAfterModel = await finalizeIfInterrupted()
208
+ if (interruptedAfterModel) return interruptedAfterModel
209
+ if (result.status === "aborted") {
210
+ return finalizeInterruptedTurn({
211
+ session: input.session,
212
+ context,
213
+ run,
214
+ modelId: plan.model.modelId,
215
+ ...stopReason(),
216
+ parts: interruptedParts,
217
+ })
218
+ }
219
+
220
+ // A child waiting on its question pauses on it while the turn still runs: a waiting child
221
+ // would hold the wait below forever, and the turn's end cancels the children still at work.
222
+ await input.children?.defer(abortSignal)
223
+
224
+ // A call held after the last step that ran tools, by a command left running in the sandbox or
225
+ // by a child, pauses the turn too. Its end cancels the children still at work, so it first
226
+ // waits for them: one that holds a call pauses by itself instead of being stopped.
227
+ if (result.status === "paused" || (await input.session.heldCalls.holdsRun())) {
228
+ await input.children?.settle(abortSignal)
229
+ }
230
+ const interruptedWhileWaiting = await finalizeIfInterrupted()
231
+ if (interruptedWhileWaiting) return interruptedWhileWaiting
232
+
233
+ const finishReason =
234
+ result.status === "paused" || (await input.session.heldCalls.holdsRun())
235
+ ? "awaiting_approval"
236
+ : (coerceAgentRunFinishReason(result.finishReason) ?? "unknown")
237
+ const assistant: AgentMessage = { role: "assistant", parts: interruptedParts }
238
+ const diagnostics = [outputLimitDiagnostic(finishReason)].filter(
239
+ (diagnostic) => diagnostic !== undefined
240
+ )
241
+ const assistantMessageId = createAgentMessageId()
242
+
243
+ const interruptedBeforeCommit = await finalizeIfInterrupted()
244
+ if (interruptedBeforeCommit) return interruptedBeforeCommit
245
+
246
+ await context.beforeFinalize?.()
247
+ const finalizedRun = await input.session.finish(
248
+ {
249
+ status: "succeeded",
250
+ modelId: plan.model.modelId,
251
+ finishReason,
252
+ ...(diagnostics.length === 0 ? {} : { diagnostics }),
253
+ },
254
+ [
255
+ {
256
+ id: assistantMessageId,
257
+ projectId,
258
+ threadId: run.threadId,
259
+ runId,
260
+ role: assistant.role,
261
+ parts: assistant.parts,
262
+ ...(context.authorPrincipal === undefined
263
+ ? {}
264
+ : { authorPrincipal: context.authorPrincipal }),
265
+ },
266
+ ]
267
+ )
268
+
269
+ await input.session.events.publishMessageFinalized({ run, messageId: assistantMessageId })
270
+ await input.session.events.publishRunFinished(finalizedRun)
271
+ return finalizedRun
272
+ } finally {
273
+ if (ownsRuntime) runtime.dispose()
274
+ }
275
+ }
276
+
277
+ /**
278
+ * Whether the turn holds a call for its requester, as `runs.finish` checks before it pauses: one
279
+ * waiting, or decided and not reported to the model yet, its children's included.
280
+ */
281
+
282
+ /**
283
+ * Whether the worker's stop, rather than the user's, ended the turn. Whichever fired first wins:
284
+ * the combined turn signal carries the reason of the first source that aborted it.
285
+ */
286
+ export function stoppedByWorker(turnSignal: AbortSignal, stopSignal?: AbortSignal): boolean {
287
+ return stopSignal?.aborted === true && turnSignal.reason === stopSignal.reason
288
+ }
289
+
290
+ /**
291
+ * An answer the output limit cut short keeps what the model produced, reasoning included, and says
292
+ * so through a diagnostic, which chats render in the reader's language. Its unfinished tool calls
293
+ * were dropped unexecuted.
294
+ */
295
+ function outputLimitDiagnostic(finishReason: AgentRunFinishReason): AgentRunDiagnostic | undefined {
296
+ if (finishReason !== "length") return undefined
297
+ return {
298
+ code: "output_limit_reached",
299
+ severity: "warning",
300
+ scope: "run",
301
+ message: "The model reached its output limit before finishing the answer.",
302
+ }
303
+ }
304
+
305
+ /** Persist a cancelled turn, retaining coherent partial content when any was produced. */
306
+ async function finalizeInterruptedTurn(input: {
307
+ readonly session: AgentRunSession
308
+ readonly context: AgentTurnContext
309
+ readonly run: ConversationAgentRunRecord
310
+ readonly modelId?: string
311
+ readonly finishReason?: "interrupted"
312
+ readonly parts?: readonly AgentMessagePart[]
313
+ }): Promise<AgentRunRecord> {
314
+ const { session, context, run, modelId, finishReason } = input
315
+ const parts = input.parts?.some((part) => part.type !== "step-start") ? input.parts : undefined
316
+
317
+ await context.beforeFinalize?.()
318
+
319
+ const outcome = {
320
+ status: "cancelled" as const,
321
+ ...(modelId === undefined ? {} : { modelId }),
322
+ ...(finishReason === undefined ? {} : { finishReason }),
323
+ }
324
+ if (!parts) {
325
+ const finalizedRun = await session.finish(outcome)
326
+ await session.events.publishRunFinished(finalizedRun)
327
+ return finalizedRun
328
+ }
329
+
330
+ const assistantMessageId = createAgentMessageId()
331
+ const finalizedRun = await session.finish(outcome, [
332
+ {
333
+ id: assistantMessageId,
334
+ projectId: run.projectId,
335
+ threadId: run.threadId,
336
+ runId: run.id,
337
+ role: "assistant",
338
+ parts,
339
+ ...(context.authorPrincipal === undefined
340
+ ? {}
341
+ : { authorPrincipal: context.authorPrincipal }),
342
+ },
343
+ ])
344
+ await session.events.publishMessageFinalized({ run, messageId: assistantMessageId })
345
+ await session.events.publishRunFinished(finalizedRun)
346
+ return finalizedRun
347
+ }
@@ -0,0 +1,319 @@
1
+ import {
2
+ AgentExecutionLostError,
3
+ AgentFinalizationError,
4
+ type AgentRunSession,
5
+ interruptedError,
6
+ } from "@sixb/core/internal/agents"
7
+ import { createSixbError } from "@sixb/core/internal/errors"
8
+ import { ModelUsageRecordingError } from "@sixb/core/internal/model-execution"
9
+ import { isAbortError } from "@sixb/core/internal/workers"
10
+ import type {
11
+ AgentRunRecord,
12
+ AgentThreadRecord,
13
+ ExecutionRecord,
14
+ SubagentRunRecord,
15
+ } from "@sixb/core/storage"
16
+ import { createAskParentTool } from "./ask-parent-tool"
17
+ import { prepareAgentModel } from "./context-budget"
18
+ import { isLostExecution } from "./errors"
19
+ import { resolveRunPlan } from "./execution-plan"
20
+ import type { AgentRunFailure } from "./failure"
21
+ import type { FamilyMailbox } from "./family-mailbox"
22
+ import { agentRequester } from "./requester"
23
+ import { stoppedByWorker } from "./run-agent-turn"
24
+ import {
25
+ type AgentExecutionEnvironment,
26
+ createSubagentEnvironment,
27
+ type OpenRunSandbox,
28
+ } from "./run-environment"
29
+ import { agentRunFailureDetails, recordFate } from "./run-fate"
30
+ import { runSubagent, type SubagentWork } from "./run-subagent"
31
+ import { SubagentInbox } from "./subagent-inbox"
32
+ import { type AgentTurnRuntime, createAgentTurnRuntime } from "./turn-runtime"
33
+ import type { AgentExecutionContext, AgentRunSettings } from "./types"
34
+
35
+ // The children a turn spawns, run beside it in its runner: the worker, or a runner on a computer.
36
+ // The runner keeps what is its own: how a child is claimed, and where its sandbox comes from.
37
+
38
+ /** What a runner lends the children it runs. */
39
+ export interface ChildRunnerHost {
40
+ /** What every run of the project shares. */
41
+ readonly settings: AgentRunSettings
42
+ /** How many children run here at once, across every turn; the rest wait their turn queued. */
43
+ readonly capacity: number
44
+ /**
45
+ * Claim a queued child, retrying while `stop` holds: nothing redelivers a child, and its parent
46
+ * waits on it. Null when it can't be claimed, such as once its parent ended.
47
+ */
48
+ claim(
49
+ run: SubagentRunRecord,
50
+ claim: { readonly leaseExpiresAt: string; readonly stop: AbortSignal }
51
+ ): Promise<AgentRunSession<SubagentRunRecord> | null>
52
+ /** The sandbox the child works in, opened when it first needs one. */
53
+ openSandbox(child: {
54
+ readonly session: AgentRunSession<SubagentRunRecord>
55
+ readonly context: AgentExecutionContext
56
+ readonly execution: ExecutionRecord
57
+ readonly thread: AgentThreadRecord
58
+ }): OpenRunSandbox
59
+ /** A sandbox teardown that outlives the child: the runner waits for it before it stops. */
60
+ onDetachedTeardown(teardown: Promise<void>): void
61
+ /** A child that failed: the runner reports it, once its end is recorded. */
62
+ reportFailure?(error: unknown, run: AgentRunRecord, failure: AgentRunFailure): void
63
+ /** Runs the child's preparation, which calls no model. Runs it once when absent. */
64
+ prepare?<T>(prepare: () => Promise<T>, signal: AbortSignal): Promise<T>
65
+ }
66
+
67
+ /** What a child runs under: its parent turn's. */
68
+ export interface ChildParent {
69
+ /** The runner's own stop: its process stopping, or its hold on the parent lost. */
70
+ readonly signal: AbortSignal
71
+ /** When the parent's lease runs out, which the child is claimed until. */
72
+ leaseExpiresAt(): string
73
+ /** Holds the child's lease beside its parent's, from now until the returned release. */
74
+ holdLease(session: AgentRunSession<SubagentRunRecord>): Promise<() => void>
75
+ /** The turn's mailbox, through which they talk. */
76
+ readonly family: FamilyMailbox
77
+ }
78
+
79
+ interface RunningChild {
80
+ readonly parentRunId: string
81
+ /** Aborted when the parent's turn ends while the child still runs. */
82
+ readonly ended: AbortController
83
+ readonly done: Promise<void>
84
+ }
85
+
86
+ /**
87
+ * Runs the children of a runner's turns. A child holds its own run, session, token and sandbox,
88
+ * but no lease of its own: its parent's renewals renew it, and a runner that stops takes its
89
+ * children with it. A child left running once its parent ended is ended when its lease lapses.
90
+ */
91
+ export class ChildRunner {
92
+ /** Children running here, by run id: a child already running is never started twice. */
93
+ private readonly running = new Map<string, RunningChild>()
94
+ /** Children holding one of the runner's slots, and those waiting for one, first come first. */
95
+ private active = 0
96
+ private readonly waiting: (() => void)[] = []
97
+
98
+ constructor(private readonly host: ChildRunnerHost) {}
99
+
100
+ /** Run a child, in this process. It records the child's fate itself and never rejects. */
101
+ start(run: SubagentRunRecord, parent: ChildParent): void {
102
+ if (this.running.has(run.id)) return
103
+ const ended = new AbortController()
104
+ const done = this.run(run, parent, ended.signal).catch((error: unknown) => {
105
+ console.error(`[SixbAgent] Subagent run '${run.id}' failed outside its run.`, error)
106
+ })
107
+ this.running.set(run.id, { parentRunId: run.parentRunId, ended, done })
108
+ void done.finally(() => {
109
+ this.running.delete(run.id)
110
+ // Ended, paused or never claimed: the turn's waits read why.
111
+ parent.family.finished(run.id)
112
+ })
113
+ }
114
+
115
+ /**
116
+ * Stop a parent's children still running here, and wait for them to record it. The parent's
117
+ * lease, which renews theirs, must hold until this returns.
118
+ */
119
+ async stopChildrenOf(parentRunId: string): Promise<void> {
120
+ const children = [...this.running.values()].filter((child) => child.parentRunId === parentRunId)
121
+ for (const child of children) {
122
+ child.ended.abort(new DOMException("The parent Agent run has ended.", "AbortError"))
123
+ }
124
+ await Promise.allSettled(children.map((child) => child.done))
125
+ }
126
+
127
+ /** Wait for every child running here, for a runner that stops. */
128
+ async drain(): Promise<void> {
129
+ await Promise.allSettled([...this.running.values()].map((child) => child.done))
130
+ }
131
+
132
+ private async run(
133
+ queuedRun: SubagentRunRecord,
134
+ parent: ChildParent,
135
+ parentEnded: AbortSignal
136
+ ): Promise<void> {
137
+ const stopped = AbortSignal.any([parent.signal, parentEnded])
138
+ if (!(await this.takeSlot(stopped))) return
139
+ try {
140
+ const session = await this.host.claim(queuedRun, {
141
+ leaseExpiresAt: parent.leaseExpiresAt(),
142
+ stop: stopped,
143
+ })
144
+ if (session) await this.runClaimed(session, parent, stopped)
145
+ } finally {
146
+ this.releaseSlot()
147
+ }
148
+ }
149
+
150
+ /** Wait for one of the runner's child slots: false once the child stops first. */
151
+ private takeSlot(stopped: AbortSignal): Promise<boolean> {
152
+ if (stopped.aborted) return Promise.resolve(false)
153
+ if (this.active < this.host.capacity) {
154
+ this.active += 1
155
+ return Promise.resolve(true)
156
+ }
157
+ return new Promise((resolve) => {
158
+ const granted = (): void => {
159
+ stopped.removeEventListener("abort", gaveUp)
160
+ resolve(true)
161
+ }
162
+ const gaveUp = (): void => {
163
+ this.waiting.splice(this.waiting.indexOf(granted), 1)
164
+ resolve(false)
165
+ }
166
+ this.waiting.push(granted)
167
+ stopped.addEventListener("abort", gaveUp, { once: true })
168
+ })
169
+ }
170
+
171
+ /** A slot a child let go of passes to the child waiting longest. */
172
+ private releaseSlot(): void {
173
+ const next = this.waiting.shift()
174
+ if (next) next()
175
+ else this.active -= 1
176
+ }
177
+
178
+ private async runClaimed(
179
+ session: AgentRunSession<SubagentRunRecord>,
180
+ parent: ChildParent,
181
+ stopped: AbortSignal
182
+ ): Promise<void> {
183
+ const { signal } = parent
184
+ const run = session.run
185
+ // A child stops with its parent: cancelling the parent cancels it.
186
+ const turnSignal = AbortSignal.any([stopped, session.cancelled])
187
+ let environment: AgentExecutionEnvironment | null = null
188
+ let runtime: AgentTurnRuntime | null = null
189
+ let releaseLease: (() => void) | undefined
190
+ const work: SubagentWork = {}
191
+
192
+ try {
193
+ releaseLease = await parent.holdLease(session)
194
+ const prepare = () => this.prepare(session)
195
+ const prepared = await (this.host.prepare
196
+ ? this.host.prepare(prepare, turnSignal)
197
+ : prepare())
198
+ const { context, execution, thread, conversation, plan, history } = prepared
199
+ await session.events.publishStarted(run)
200
+ runtime = createAgentTurnRuntime({ signal: turnSignal })
201
+ // A message its parent sent while it was queued is read at its first step. What a paused run
202
+ // it continues never read is in its trigger already.
203
+ const inbox = new SubagentInbox(parent.family.child(run.id), run)
204
+ environment = await createSubagentEnvironment({
205
+ session,
206
+ openSandbox: this.host.openSandbox({ session, context, execution, thread }),
207
+ context,
208
+ plan,
209
+ run,
210
+ thread,
211
+ conversation,
212
+ frameworkTools: [createAskParentTool(inbox)],
213
+ ...(execution.requestedBy === undefined ? {} : { requestedBy: execution.requestedBy }),
214
+ history,
215
+ signal: runtime.signal,
216
+ onDetachedTeardown: (teardown) => this.host.onDetachedTeardown(teardown),
217
+ })
218
+ await runSubagent({
219
+ history,
220
+ inbox,
221
+ context: environment.turnContext,
222
+ plan,
223
+ run,
224
+ session,
225
+ thread,
226
+ runtime,
227
+ work,
228
+ runFiles: environment.runFiles,
229
+ })
230
+ } catch (error) {
231
+ if (isLostExecution(error, signal)) return
232
+ // Its end could not be recorded: it stays running until its lease lapses, and is then ended
233
+ // as interrupted.
234
+ if (error instanceof AgentFinalizationError) {
235
+ console.error(error.message, error.cause)
236
+ return
237
+ }
238
+ // A child run that fails or is stopped leaves its workspace mid-work: it goes, and a later
239
+ // continuation of the thread starts again from the handed files and out/. The run's own
240
+ // error is the one recorded, a save that failed included.
241
+ try {
242
+ await environment?.beforeFinalize({ discard: true })
243
+ } catch (saveError) {
244
+ if (saveError instanceof AgentExecutionLostError) return
245
+ }
246
+ const aborted =
247
+ !(error instanceof ModelUsageRecordingError) &&
248
+ (stopped.aborted || session.cancelled.aborted || isAbortError(error))
249
+ // A runner that stops takes its turns' children with it, and nothing replays them.
250
+ const interrupted = aborted && stoppedByWorker(turnSignal, signal)
251
+ const finalized = await recordFate(
252
+ session,
253
+ aborted ? "cancelled" : "failed",
254
+ interrupted ? interruptedError(run) : error,
255
+ work.messages
256
+ )
257
+ if (finalized) {
258
+ if (finalized.run.status === "failed") {
259
+ this.host.reportFailure?.(error, finalized.run, finalized.failure)
260
+ }
261
+ await session.events.publishRunFinished(finalized.run)
262
+ }
263
+ } finally {
264
+ releaseLease?.()
265
+ await session.close()
266
+ runtime?.dispose()
267
+ await environment?.dispose()
268
+ }
269
+ }
270
+
271
+ /** Everything a child needs before its first model call, read through its session. */
272
+ private async prepare(session: AgentRunSession<SubagentRunRecord>) {
273
+ const { run } = session
274
+ const child = await session.context()
275
+ if (child.kind !== "subagent") throw new Error(`[SixbAgent] Run '${run.id}' changed kind.`)
276
+ const { parent, execution, thread } = child
277
+ if (!parent || parent.kind !== "conversation" || !isActiveRun(parent)) {
278
+ throw new DOMException("The parent Agent run is no longer active.", "AbortError")
279
+ }
280
+ if (
281
+ !execution ||
282
+ execution.source.type !== "execution" ||
283
+ execution.source.executionId !== parent.executionId
284
+ ) {
285
+ throw createSixbError(
286
+ "internal.unexpected",
287
+ `[SixbAgent] Subagent run '${run.id}' has invalid execution lineage.`,
288
+ {
289
+ details: { parentRunId: run.parentRunId, runId: run.id, executionId: run.executionId },
290
+ }
291
+ )
292
+ }
293
+ // The child works in its own thread, and publishes into its conversation's gallery.
294
+ if (!thread) {
295
+ throw createSixbError(
296
+ "internal.unexpected",
297
+ `[SixbAgent] Subagent run '${run.id}' references missing thread '${run.threadId}'.`,
298
+ { details: agentRunFailureDetails(run) }
299
+ )
300
+ }
301
+ const runPlan = await session.plan()
302
+ const configured = resolveRunPlan(runPlan, {
303
+ model: await session.models.language(runPlan.model),
304
+ })
305
+ const plan = Object.freeze({ ...configured, model: prepareAgentModel(configured).model })
306
+ const requester = agentRequester(execution.requestedBy, child.names)
307
+ const context: AgentExecutionContext = {
308
+ ...this.host.settings,
309
+ ...(requester === undefined ? {} : { requester }),
310
+ blobStorage: session.files,
311
+ }
312
+ const history = { messages: child.messages, ...(child.paused ? { paused: child.paused } : {}) }
313
+ return { context, execution, thread, conversation: child.conversation, plan, history }
314
+ }
315
+ }
316
+
317
+ function isActiveRun(run: AgentRunRecord): boolean {
318
+ return run.status === "queued" || run.status === "running"
319
+ }