@sixb/agent 0.0.0-stage → 0.2.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 (240) 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 +126 -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 +109 -0
  22. package/dist/attachments.d.ts.map +1 -0
  23. package/dist/child-files.d.ts +91 -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 +74 -0
  28. package/dist/computer-runner.d.ts.map +1 -0
  29. package/dist/context-budget.d.ts +34 -0
  30. package/dist/context-budget.d.ts.map +1 -0
  31. package/dist/context-compaction.d.ts +148 -0
  32. package/dist/context-compaction.d.ts.map +1 -0
  33. package/dist/context-guard.d.ts +69 -0
  34. package/dist/context-guard.d.ts.map +1 -0
  35. package/dist/conversation-memory.d.ts +21 -0
  36. package/dist/conversation-memory.d.ts.map +1 -0
  37. package/dist/conversation-messages.d.ts +33 -0
  38. package/dist/conversation-messages.d.ts.map +1 -0
  39. package/dist/errors.d.ts +46 -0
  40. package/dist/errors.d.ts.map +1 -0
  41. package/dist/execution-plan.d.ts +38 -0
  42. package/dist/execution-plan.d.ts.map +1 -0
  43. package/dist/failure.d.ts +14 -0
  44. package/dist/failure.d.ts.map +1 -0
  45. package/dist/family-mailbox.d.ts +60 -0
  46. package/dist/family-mailbox.d.ts.map +1 -0
  47. package/dist/file-ref.d.ts +6 -0
  48. package/dist/file-ref.d.ts.map +1 -0
  49. package/dist/image-attachments.d.ts +34 -0
  50. package/dist/image-attachments.d.ts.map +1 -0
  51. package/dist/index.d.ts +35 -0
  52. package/dist/index.d.ts.map +1 -0
  53. package/dist/index.js +14387 -0
  54. package/dist/index.js.map +72 -0
  55. package/dist/inline-images.d.ts +28 -0
  56. package/dist/inline-images.d.ts.map +1 -0
  57. package/dist/message-authors.d.ts +34 -0
  58. package/dist/message-authors.d.ts.map +1 -0
  59. package/dist/message-times.d.ts +9 -0
  60. package/dist/message-times.d.ts.map +1 -0
  61. package/dist/model-adapters.d.ts +59 -0
  62. package/dist/model-adapters.d.ts.map +1 -0
  63. package/dist/model-lines.d.ts +16 -0
  64. package/dist/model-lines.d.ts.map +1 -0
  65. package/dist/prompt-cache.d.ts +28 -0
  66. package/dist/prompt-cache.d.ts.map +1 -0
  67. package/dist/requester.d.ts +15 -0
  68. package/dist/requester.d.ts.map +1 -0
  69. package/dist/run-agent-turn.d.ts +93 -0
  70. package/dist/run-agent-turn.d.ts.map +1 -0
  71. package/dist/run-child.d.ts +77 -0
  72. package/dist/run-child.d.ts.map +1 -0
  73. package/dist/run-conversation-turn.d.ts +42 -0
  74. package/dist/run-conversation-turn.d.ts.map +1 -0
  75. package/dist/run-credential.d.ts +22 -0
  76. package/dist/run-credential.d.ts.map +1 -0
  77. package/dist/run-environment.d.ts +145 -0
  78. package/dist/run-environment.d.ts.map +1 -0
  79. package/dist/run-fate.d.ts +15 -0
  80. package/dist/run-fate.d.ts.map +1 -0
  81. package/dist/run-files-lock.d.ts +16 -0
  82. package/dist/run-files-lock.d.ts.map +1 -0
  83. package/dist/run-sandbox.d.ts +60 -0
  84. package/dist/run-sandbox.d.ts.map +1 -0
  85. package/dist/run-subagent.d.ts +65 -0
  86. package/dist/run-subagent.d.ts.map +1 -0
  87. package/dist/run-workflow-agent-node.d.ts +46 -0
  88. package/dist/run-workflow-agent-node.d.ts.map +1 -0
  89. package/dist/sandbox-api-context.d.ts +34 -0
  90. package/dist/sandbox-api-context.d.ts.map +1 -0
  91. package/dist/sandbox-file-registry.d.ts +9 -0
  92. package/dist/sandbox-file-registry.d.ts.map +1 -0
  93. package/dist/sandbox-files.d.ts +71 -0
  94. package/dist/sandbox-files.d.ts.map +1 -0
  95. package/dist/sandbox-handle.d.ts +15 -0
  96. package/dist/sandbox-handle.d.ts.map +1 -0
  97. package/dist/sandbox-readiness.d.ts +8 -0
  98. package/dist/sandbox-readiness.d.ts.map +1 -0
  99. package/dist/skills/built-in.d.ts +15 -0
  100. package/dist/skills/built-in.d.ts.map +1 -0
  101. package/dist/subagent-context.d.ts +50 -0
  102. package/dist/subagent-context.d.ts.map +1 -0
  103. package/dist/subagent-continuation.d.ts +33 -0
  104. package/dist/subagent-continuation.d.ts.map +1 -0
  105. package/dist/subagent-inbox.d.ts +53 -0
  106. package/dist/subagent-inbox.d.ts.map +1 -0
  107. package/dist/subagent-tools.d.ts +293 -0
  108. package/dist/subagent-tools.d.ts.map +1 -0
  109. package/dist/thread-context.d.ts +17 -0
  110. package/dist/thread-context.d.ts.map +1 -0
  111. package/dist/tools/attachments.d.ts +11 -0
  112. package/dist/tools/attachments.d.ts.map +1 -0
  113. package/dist/tools/bash.d.ts +68 -0
  114. package/dist/tools/bash.d.ts.map +1 -0
  115. package/dist/tools/model-spec.d.ts +9 -0
  116. package/dist/tools/model-spec.d.ts.map +1 -0
  117. package/dist/tools/read.d.ts +43 -0
  118. package/dist/tools/read.d.ts.map +1 -0
  119. package/dist/tools/result-media.d.ts +65 -0
  120. package/dist/tools/result-media.d.ts.map +1 -0
  121. package/dist/tools/result-output.d.ts +18 -0
  122. package/dist/tools/result-output.d.ts.map +1 -0
  123. package/dist/tools/tool-files.d.ts +59 -0
  124. package/dist/tools/tool-files.d.ts.map +1 -0
  125. package/dist/tools/tool-outputs.d.ts +63 -0
  126. package/dist/tools/tool-outputs.d.ts.map +1 -0
  127. package/dist/tools/view-file.d.ts +40 -0
  128. package/dist/tools/view-file.d.ts.map +1 -0
  129. package/dist/tsconfig.json +5 -0
  130. package/dist/turn-runtime.d.ts +19 -0
  131. package/dist/turn-runtime.d.ts.map +1 -0
  132. package/dist/types.d.ts +83 -0
  133. package/dist/types.d.ts.map +1 -0
  134. package/dist/workflow-input-attachments.d.ts +18 -0
  135. package/dist/workflow-input-attachments.d.ts.map +1 -0
  136. package/package.json +59 -4
  137. package/src/abort.ts +40 -0
  138. package/src/agent-prompt.ts +860 -0
  139. package/src/agent-runtime/errors.ts +44 -0
  140. package/src/agent-runtime/preflight.ts +314 -0
  141. package/src/agent-runtime/profile.ts +23 -0
  142. package/src/artifacts/layout-check/check.cjs +478 -0
  143. package/src/artifacts/layout-check/layout-check.ts +460 -0
  144. package/src/artifacts/materialize.ts +380 -0
  145. package/src/artifacts/publish-tool.ts +700 -0
  146. package/src/ask-parent-tool.ts +100 -0
  147. package/src/attachments.ts +1041 -0
  148. package/src/child-files.ts +535 -0
  149. package/src/child-questions.ts +42 -0
  150. package/src/computer-runner.ts +336 -0
  151. package/src/context-budget.ts +177 -0
  152. package/src/context-compaction.ts +1349 -0
  153. package/src/context-guard.ts +826 -0
  154. package/src/conversation-memory.ts +45 -0
  155. package/src/conversation-messages.ts +86 -0
  156. package/src/errors.ts +85 -0
  157. package/src/execution-plan.ts +70 -0
  158. package/src/failure.ts +82 -0
  159. package/src/family-mailbox.ts +189 -0
  160. package/src/file-ref.ts +18 -0
  161. package/src/image-attachments.ts +322 -0
  162. package/src/index.ts +54 -0
  163. package/src/inline-images.ts +69 -0
  164. package/src/message-authors.ts +77 -0
  165. package/src/message-times.ts +24 -0
  166. package/src/model-adapters.ts +273 -0
  167. package/src/model-lines.ts +28 -0
  168. package/src/prompt-cache.ts +40 -0
  169. package/src/requester.ts +21 -0
  170. package/src/run-agent-turn.ts +509 -0
  171. package/src/run-child.ts +344 -0
  172. package/src/run-conversation-turn.ts +272 -0
  173. package/src/run-credential.ts +55 -0
  174. package/src/run-environment.ts +1216 -0
  175. package/src/run-fate.ts +51 -0
  176. package/src/run-files-lock.ts +118 -0
  177. package/src/run-sandbox.ts +63 -0
  178. package/src/run-subagent.ts +433 -0
  179. package/src/run-workflow-agent-node.ts +344 -0
  180. package/src/sandbox-api-context.ts +237 -0
  181. package/src/sandbox-file-registry.ts +26 -0
  182. package/src/sandbox-files.ts +326 -0
  183. package/src/sandbox-handle.ts +19 -0
  184. package/src/sandbox-readiness.ts +22 -0
  185. package/src/skills/built-in.ts +183 -0
  186. package/src/skills/sixb-artifacts/SKILL.md +95 -0
  187. package/src/skills/sixb-artifacts/canvas.md +104 -0
  188. package/src/skills/sixb-artifacts/document.md +63 -0
  189. package/src/skills/sixb-artifacts/examples/canvas/onboarding-flow/boards/first-job.html +42 -0
  190. package/src/skills/sixb-artifacts/examples/canvas/onboarding-flow/boards/region.html +29 -0
  191. package/src/skills/sixb-artifacts/examples/canvas/onboarding-flow/boards/shared.css +35 -0
  192. package/src/skills/sixb-artifacts/examples/canvas/onboarding-flow/boards/welcome.html +31 -0
  193. package/src/skills/sixb-artifacts/examples/canvas/onboarding-flow/canvas.json +107 -0
  194. package/src/skills/sixb-artifacts/examples/canvas/retro/canvas.json +158 -0
  195. package/src/skills/sixb-artifacts/examples/document/incident-report/document.md +35 -0
  196. package/src/skills/sixb-artifacts/examples/document/operations-review/document.md +41 -0
  197. package/src/skills/sixb-artifacts/examples/document/operations-review/figures/restorations.svg +1 -0
  198. package/src/skills/sixb-artifacts/examples/page/collections-desk/index.html +169 -0
  199. package/src/skills/sixb-artifacts/examples/page/collections-desk/queries/overdue.json +13 -0
  200. package/src/skills/sixb-artifacts/examples/page/dispatch-board/data/dispatch.json +234 -0
  201. package/src/skills/sixb-artifacts/examples/page/dispatch-board/index.html +245 -0
  202. package/src/skills/sixb-artifacts/examples/page/fleet-planner/data/plan.json +53 -0
  203. package/src/skills/sixb-artifacts/examples/page/fleet-planner/index.html +462 -0
  204. package/src/skills/sixb-artifacts/examples/page/service-explorer/data/service.json +276 -0
  205. package/src/skills/sixb-artifacts/examples/page/service-explorer/index.html +549 -0
  206. package/src/skills/sixb-artifacts/examples/sheet/overdue-invoices/queries/overdue.json +13 -0
  207. package/src/skills/sixb-artifacts/examples/sheet/overdue-invoices/workbook.json +30 -0
  208. package/src/skills/sixb-artifacts/examples/sheet/parts-inventory/sheets/Inventory.csv +13 -0
  209. package/src/skills/sixb-artifacts/examples/sheet/parts-inventory/sheets/Spend.csv +6 -0
  210. package/src/skills/sixb-artifacts/examples/sheet/parts-inventory/workbook.json +47 -0
  211. package/src/skills/sixb-artifacts/examples/sheet/service-metrics/sheets/Quarters.csv +5 -0
  212. package/src/skills/sixb-artifacts/examples/sheet/service-metrics/sheets/Regions.csv +5 -0
  213. package/src/skills/sixb-artifacts/examples/sheet/service-metrics/workbook.json +78 -0
  214. package/src/skills/sixb-artifacts/examples/slides/launch-plan/index.html +63 -0
  215. package/src/skills/sixb-artifacts/examples/slides/q3-review/index.html +133 -0
  216. package/src/skills/sixb-artifacts/file.md +17 -0
  217. package/src/skills/sixb-artifacts/page.md +215 -0
  218. package/src/skills/sixb-artifacts/queries.md +66 -0
  219. package/src/skills/sixb-artifacts/references.md +68 -0
  220. package/src/skills/sixb-artifacts/sheet.md +223 -0
  221. package/src/skills/sixb-artifacts/slides.md +137 -0
  222. package/src/skills/sixb-memory/SKILL.md +68 -0
  223. package/src/skills/text-assets.d.ts +25 -0
  224. package/src/subagent-context.ts +182 -0
  225. package/src/subagent-continuation.ts +56 -0
  226. package/src/subagent-inbox.ts +101 -0
  227. package/src/subagent-tools.ts +1671 -0
  228. package/src/thread-context.ts +31 -0
  229. package/src/tools/attachments.ts +28 -0
  230. package/src/tools/bash.ts +233 -0
  231. package/src/tools/model-spec.ts +27 -0
  232. package/src/tools/read.ts +262 -0
  233. package/src/tools/result-media.ts +351 -0
  234. package/src/tools/result-output.ts +46 -0
  235. package/src/tools/tool-files.ts +204 -0
  236. package/src/tools/tool-outputs.ts +464 -0
  237. package/src/tools/view-file.ts +155 -0
  238. package/src/turn-runtime.ts +33 -0
  239. package/src/types.ts +91 -0
  240. package/src/workflow-input-attachments.ts +140 -0
@@ -0,0 +1,344 @@
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, budget, history } = prepared
199
+ const { measuredBytesPerToken } = prepared
200
+ await session.events.publishStarted(run)
201
+ runtime = createAgentTurnRuntime({ signal: turnSignal })
202
+ // A message its parent sent while it was queued is read at its first step. What a paused run
203
+ // it continues never read is in its trigger already.
204
+ const inbox = new SubagentInbox(parent.family.child(run.id), run)
205
+ const childEnvironment = await createSubagentEnvironment({
206
+ session,
207
+ openSandbox: this.host.openSandbox({ session, context, execution, thread }),
208
+ context,
209
+ plan,
210
+ run,
211
+ thread,
212
+ conversation,
213
+ frameworkTools: [createAskParentTool(inbox)],
214
+ ...(execution.requestedBy === undefined ? {} : { requestedBy: execution.requestedBy }),
215
+ history,
216
+ signal: runtime.signal,
217
+ onDetachedTeardown: (teardown) => this.host.onDetachedTeardown(teardown),
218
+ preflight: { budget, runtime },
219
+ })
220
+ environment = childEnvironment
221
+ const { compactInRun, bytesPerToken } = childEnvironment
222
+ await runSubagent({
223
+ history,
224
+ inbox,
225
+ context: environment.turnContext,
226
+ plan,
227
+ contextLimits: {
228
+ budget,
229
+ measuredBytesPerToken,
230
+ thread: childEnvironment.thread,
231
+ ...(compactInRun ? { compactInRun } : {}),
232
+ ...(bytesPerToken === undefined ? {} : { bytesPerToken }),
233
+ },
234
+ run,
235
+ session,
236
+ thread,
237
+ runtime,
238
+ work,
239
+ runFiles: environment.runFiles,
240
+ })
241
+ } catch (error) {
242
+ if (isLostExecution(error, signal)) return
243
+ // Its end could not be recorded: it stays running until its lease lapses, and is then ended
244
+ // as interrupted.
245
+ if (error instanceof AgentFinalizationError) {
246
+ console.error(error.message, error.cause)
247
+ return
248
+ }
249
+ // A child run that fails or is stopped leaves its workspace mid-work: it goes, and a later
250
+ // continuation of the thread starts again from the handed files and out/. The run's own
251
+ // error is the one recorded, a save that failed included.
252
+ try {
253
+ await environment?.beforeFinalize({ discard: true })
254
+ } catch (saveError) {
255
+ if (saveError instanceof AgentExecutionLostError) return
256
+ }
257
+ const aborted =
258
+ !(error instanceof ModelUsageRecordingError) &&
259
+ (stopped.aborted || session.cancelled.aborted || isAbortError(error))
260
+ // A runner that stops takes its turns' children with it, and nothing replays them.
261
+ const interrupted = aborted && stoppedByWorker(turnSignal, signal)
262
+ const finalized = await recordFate(
263
+ session,
264
+ aborted ? "cancelled" : "failed",
265
+ interrupted ? interruptedError(run) : error,
266
+ work.messages
267
+ )
268
+ if (finalized) {
269
+ if (finalized.run.status === "failed") {
270
+ this.host.reportFailure?.(error, finalized.run, finalized.failure)
271
+ }
272
+ await session.events.publishRunFinished(finalized.run)
273
+ }
274
+ } finally {
275
+ releaseLease?.()
276
+ await session.close()
277
+ runtime?.dispose()
278
+ await environment?.dispose()
279
+ }
280
+ }
281
+
282
+ /** Everything a child needs before its first model call, read through its session. */
283
+ private async prepare(session: AgentRunSession<SubagentRunRecord>) {
284
+ const { run } = session
285
+ const child = await session.context()
286
+ if (child.kind !== "subagent") throw new Error(`[SixbAgent] Run '${run.id}' changed kind.`)
287
+ const { parent, execution, thread } = child
288
+ if (!parent || parent.kind !== "conversation" || !isActiveRun(parent)) {
289
+ throw new DOMException("The parent Agent run is no longer active.", "AbortError")
290
+ }
291
+ if (
292
+ !execution ||
293
+ execution.source.type !== "execution" ||
294
+ execution.source.executionId !== parent.executionId
295
+ ) {
296
+ throw createSixbError(
297
+ "internal.unexpected",
298
+ `[SixbAgent] Subagent run '${run.id}' has invalid execution lineage.`,
299
+ {
300
+ details: { parentRunId: run.parentRunId, runId: run.id, executionId: run.executionId },
301
+ }
302
+ )
303
+ }
304
+ // The child works in its own thread, and publishes into its conversation's gallery.
305
+ if (!thread) {
306
+ throw createSixbError(
307
+ "internal.unexpected",
308
+ `[SixbAgent] Subagent run '${run.id}' references missing thread '${run.threadId}'.`,
309
+ { details: agentRunFailureDetails(run) }
310
+ )
311
+ }
312
+ const runPlan = await session.plan()
313
+ const configured = resolveRunPlan(runPlan, {
314
+ model: await session.models.language(runPlan.model),
315
+ })
316
+ const { model, budget, measuredBytesPerToken } = prepareAgentModel(configured)
317
+ const plan = Object.freeze({ ...configured, model })
318
+ const requester = agentRequester(execution.requestedBy, child.names)
319
+ const context: AgentExecutionContext = {
320
+ ...this.host.settings,
321
+ ...(requester === undefined ? {} : { requester }),
322
+ blobStorage: session.files,
323
+ }
324
+ const history = {
325
+ ...child.history,
326
+ ...(child.task ? { task: child.task } : {}),
327
+ ...(child.paused ? { paused: child.paused } : {}),
328
+ }
329
+ return {
330
+ context,
331
+ execution,
332
+ thread,
333
+ conversation: child.conversation,
334
+ plan,
335
+ budget,
336
+ measuredBytesPerToken,
337
+ history,
338
+ }
339
+ }
340
+ }
341
+
342
+ function isActiveRun(run: AgentRunRecord): boolean {
343
+ return run.status === "queued" || run.status === "running"
344
+ }
@@ -0,0 +1,272 @@
1
+ import { principalsEqual } from "@sixb/core"
2
+ import {
3
+ AgentExecutionLostError,
4
+ AgentFinalizationError,
5
+ type AgentRunSession,
6
+ AgentTurnInterruptedError,
7
+ } from "@sixb/core/internal/agents"
8
+ import { createSixbError } from "@sixb/core/internal/errors"
9
+ import { ModelUsageRecordingError } from "@sixb/core/internal/model-execution"
10
+ import { isAbortError } from "@sixb/core/internal/workers"
11
+ import type {
12
+ AgentRunRecord,
13
+ AgentThreadParticipantRecord,
14
+ AgentThreadRecord,
15
+ AppendAgentMessageInput,
16
+ ConversationAgentRunRecord,
17
+ ExecutionRecord,
18
+ SubagentRunRecord,
19
+ } from "@sixb/core/storage"
20
+ import { prepareAgentModel } from "./context-budget"
21
+ import { AgentEnvironmentSaveError, AgentRequesterLeftThreadError, isLostExecution } from "./errors"
22
+ import { resolveRunPlan } from "./execution-plan"
23
+ import type { AgentRunFailure } from "./failure"
24
+ import type { FamilyMailbox } from "./family-mailbox"
25
+ import { agentRequester } from "./requester"
26
+ import { runAgentTurn, stoppedByWorker } from "./run-agent-turn"
27
+ import {
28
+ type ConversationAgentExecutionEnvironment,
29
+ createConversationAgentEnvironment,
30
+ type OpenRunSandbox,
31
+ } from "./run-environment"
32
+ import { recordFate } from "./run-fate"
33
+ import { SubagentCoordinator } from "./subagent-tools"
34
+ import { type AgentTurnRuntime, createAgentTurnRuntime } from "./turn-runtime"
35
+ import type { AgentExecutionContext, AgentRunSettings } from "./types"
36
+
37
+ // A conversation turn, from its claimed session to its end, whichever runner runs it: the worker,
38
+ // under a queue delivery, or a runner on a computer, over HTTP. The runner keeps what is its own:
39
+ // how it holds the run, where the turn's sandbox comes from, and where its children run.
40
+
41
+ /** What a runner lends the turns it runs. */
42
+ export interface ConversationTurnRunner {
43
+ /** What every run of the project shares. */
44
+ readonly settings: AgentRunSettings
45
+ /** The sandbox the turn works in, opened when it first needs one. */
46
+ openSandbox(turn: {
47
+ readonly session: AgentRunSession<ConversationAgentRunRecord>
48
+ readonly context: AgentExecutionContext
49
+ readonly execution: ExecutionRecord
50
+ readonly thread: AgentThreadRecord | null
51
+ }): OpenRunSandbox
52
+ /** Run a child the turn spawned or continues, beside the turn, on the turn's mailbox. */
53
+ startChild(run: SubagentRunRecord, family: FamilyMailbox): void
54
+ /** A sandbox teardown that outlives the turn: the runner waits for it before it stops. */
55
+ onDetachedTeardown(teardown: Promise<void>): void
56
+ /** A turn that failed: the runner reports it, once its end is recorded. */
57
+ reportFailure?(error: unknown, run: AgentRunRecord, failure: AgentRunFailure): void
58
+ /**
59
+ * Runs the turn's preparation, which reads and resolves and calls no model: the worker retries a
60
+ * storage blip in place. Runs it once when absent.
61
+ */
62
+ prepare?<T>(prepare: () => Promise<T>): Promise<T>
63
+ }
64
+
65
+ /**
66
+ * Run a claimed conversation turn and record how it ended. Returns once its end is recorded, or
67
+ * at once when its runner lost the run. Throws {@link AgentFinalizationError} when its end could
68
+ * not be recorded, and rethrows its failure when `signal` stopped it, for the runner to release
69
+ * the run rather than call it done.
70
+ */
71
+ export async function runConversationTurn(input: {
72
+ readonly session: AgentRunSession<ConversationAgentRunRecord>
73
+ readonly runner: ConversationTurnRunner
74
+ /** The runner's own stop: its process stopping, or its hold on the run lost. */
75
+ readonly signal: AbortSignal
76
+ }): Promise<void> {
77
+ const { session, runner, signal } = input
78
+ const { run } = session
79
+ let environment: ConversationAgentExecutionEnvironment | null = null
80
+ let runtime: AgentTurnRuntime | null = null
81
+ let delegation: SubagentCoordinator | undefined
82
+ // The answer so far: a turn that fails keeps the steps it completed.
83
+ let work: AppendAgentMessageInput | undefined
84
+ // A user cancel joins the turn's abort sources, so it stops the model stream as a shutdown does.
85
+ const turnSignal = AbortSignal.any([signal, session.cancelled])
86
+
87
+ try {
88
+ const prepare = () => prepareConversationTurn(session, runner.settings)
89
+ const prepared = await (runner.prepare ? runner.prepare(prepare) : prepare())
90
+ const plan = Object.freeze({ ...prepared.plan, model: prepared.model.model })
91
+
92
+ await session.events.publishStarted(run)
93
+ runtime = createAgentTurnRuntime({ signal: turnSignal })
94
+ delegation = new SubagentCoordinator(
95
+ prepared.delegation,
96
+ runner.settings,
97
+ run,
98
+ session,
99
+ (child, family) => runner.startChild(child, family)
100
+ )
101
+ const frameworkTools = await delegation.createTools()
102
+ environment = await createConversationAgentEnvironment({
103
+ session,
104
+ frameworkTools,
105
+ thread: prepared.thread,
106
+ ...(prepared.execution.requestedBy === undefined
107
+ ? {}
108
+ : { requestedBy: prepared.execution.requestedBy }),
109
+ ...(prepared.conversation === undefined ? {} : { conversation: prepared.conversation }),
110
+ shared: prepared.shared,
111
+ openSandbox: runner.openSandbox({
112
+ session,
113
+ context: prepared.context,
114
+ execution: prepared.execution,
115
+ thread: prepared.thread,
116
+ }),
117
+ preflight: { budget: prepared.model.budget, runtime },
118
+ context: prepared.context,
119
+ plan,
120
+ run,
121
+ history: prepared.history,
122
+ signal: runtime.signal,
123
+ onDetachedTeardown: (teardown) => runner.onDetachedTeardown(teardown),
124
+ })
125
+ delegation.attach(environment.runFiles)
126
+ // A resumed turn's paused children go on first, as the model reads that they do.
127
+ await delegation.continuePausedChildren(runtime.signal)
128
+ runtime.assertCanContinue()
129
+ await runAgentTurn({
130
+ context: environment.turnContext,
131
+ plan,
132
+ run,
133
+ session,
134
+ ...(prepared.conversation === undefined ? {} : { conversation: prepared.conversation }),
135
+ signal: turnSignal,
136
+ stopSignal: signal,
137
+ runtime,
138
+ threadContext: environment.threadContext,
139
+ children: await delegation.turnChildren(),
140
+ contextLimits: {
141
+ budget: prepared.model.budget,
142
+ measuredBytesPerToken: prepared.model.measuredBytesPerToken,
143
+ ...(environment.compactInTurn ? { compactInTurn: environment.compactInTurn } : {}),
144
+ ...(environment.bytesPerToken === undefined
145
+ ? {}
146
+ : { bytesPerToken: environment.bytesPerToken }),
147
+ },
148
+ onWork: (message) => {
149
+ work = message
150
+ },
151
+ })
152
+ } catch (caughtError) {
153
+ let error = caughtError
154
+ let environmentSaveFailed = error instanceof AgentEnvironmentSaveError
155
+ // Its runner lost the run: touch nothing; whoever holds it now ends it.
156
+ if (isLostExecution(error, signal)) return
157
+ // It ended, but its end could not be recorded (storage down): its runner tries again.
158
+ if (error instanceof AgentFinalizationError) throw error
159
+ if (environment) {
160
+ try {
161
+ await environment.beforeFinalize()
162
+ } catch (saveError) {
163
+ if (saveError instanceof AgentExecutionLostError) return
164
+ error = saveError
165
+ environmentSaveFailed = true
166
+ }
167
+ }
168
+ // A user cancel is read off its own signal, so it records `cancelled` however the aborted
169
+ // stream surfaced. `recordFate` retries a blip, and throws AgentFinalizationError past it.
170
+ const aborted =
171
+ error instanceof AgentRequesterLeftThreadError ||
172
+ (!environmentSaveFailed &&
173
+ !(error instanceof ModelUsageRecordingError) &&
174
+ (signal.aborted || session.cancelled.aborted || isAbortError(error)))
175
+ // A runner that stops, unlike a user cancel, leaves the user something to resume.
176
+ const interrupted = aborted && stoppedByWorker(turnSignal, signal)
177
+ const finalized = await recordFate(
178
+ session,
179
+ aborted ? "cancelled" : "failed",
180
+ interrupted ? new AgentTurnInterruptedError(run.id) : error,
181
+ !aborted && work ? [work] : undefined
182
+ )
183
+ if (finalized) {
184
+ if (finalized.run.status === "failed") {
185
+ runner.reportFailure?.(error, finalized.run, finalized.failure)
186
+ }
187
+ await session.events.publishRunFinished(finalized.run)
188
+ }
189
+ // Its runner stopped: it releases the run rather than calls it done.
190
+ if (signal.aborted) throw error
191
+ } finally {
192
+ delegation?.close()
193
+ runtime?.dispose()
194
+ await environment?.dispose()
195
+ }
196
+ }
197
+
198
+ /** Everything a turn needs before its first model call, read through its session. */
199
+ async function prepareConversationTurn(
200
+ session: AgentRunSession<ConversationAgentRunRecord>,
201
+ settings: AgentRunSettings
202
+ ) {
203
+ const { run } = session
204
+ const turn = await session.context()
205
+ const { thread, execution, participants } = turn
206
+ const runPlan = await session.plan()
207
+ const plan = resolveRunPlan(runPlan, { model: await session.models.language(runPlan.model) })
208
+ // A turn's plan always carries it; only a child's goes without.
209
+ if (!runPlan.delegation) {
210
+ throw createSixbError(
211
+ "internal.unexpected",
212
+ `[SixbAgent] Agent run '${run.id}' has no models to delegate to.`
213
+ )
214
+ }
215
+ if (!execution) {
216
+ throw createSixbError(
217
+ "internal.unexpected",
218
+ `[SixbAgent] Agent run '${run.id}' references missing execution '${run.executionId}'.`,
219
+ { details: { runId: run.id, threadId: run.threadId, executionId: run.executionId } }
220
+ )
221
+ }
222
+ assertRequesterTakesPart(run, thread, participants, execution)
223
+
224
+ const conversation = thread
225
+ ? { thread, participants: turn.readers, names: turn.names }
226
+ : undefined
227
+ // The rule run tokens apply to memory: someone who loses access may regain it, and read back
228
+ // whatever memory the thread held meanwhile.
229
+ const shared = participants.length > 0
230
+ // A shared thread's system prompt names nobody, so it stays the same whoever sends the turn.
231
+ const requester =
232
+ (conversation?.participants.length ?? 0) > 0
233
+ ? undefined
234
+ : agentRequester(execution.requestedBy, turn.names)
235
+ const context: AgentExecutionContext = {
236
+ ...settings,
237
+ ...(requester === undefined ? {} : { requester }),
238
+ blobStorage: session.files,
239
+ }
240
+ return {
241
+ thread,
242
+ ...(conversation === undefined ? {} : { conversation }),
243
+ shared,
244
+ plan,
245
+ delegation: {
246
+ models: runPlan.delegation,
247
+ toolNames: runPlan.tools.map((tool) => tool.name),
248
+ },
249
+ execution,
250
+ context,
251
+ model: prepareAgentModel(plan),
252
+ history: turn.history,
253
+ }
254
+ }
255
+
256
+ /**
257
+ * A shared thread's turn waits queued: its requester may leave the thread, or be removed, before
258
+ * it starts. Such a turn never reaches the model. One already running when they leave finishes,
259
+ * as it already read the thread.
260
+ */
261
+ function assertRequesterTakesPart(
262
+ run: ConversationAgentRunRecord,
263
+ thread: AgentThreadRecord | null,
264
+ participants: readonly AgentThreadParticipantRecord[],
265
+ execution: ExecutionRecord
266
+ ): void {
267
+ const requester = execution.requestedBy
268
+ if (!thread || !requester || principalsEqual(requester, thread.ownerPrincipal)) return
269
+ if (participants.some((participant) => principalsEqual(participant.principal, requester))) return
270
+
271
+ throw new AgentRequesterLeftThreadError(run.id)
272
+ }
@@ -0,0 +1,55 @@
1
+ import type { SandboxRequestCredential } from "@sixb/core"
2
+ import { createAgentRunnerToken, createAgentRunToken } from "@sixb/core/internal/agents"
3
+
4
+ /** The token the run's commands call the API with, valid while this execution owns the run. */
5
+ export function runTokenFor(input: {
6
+ readonly projectId: string
7
+ readonly runId: string
8
+ readonly executionToken?: string
9
+ }): string {
10
+ if (!input.executionToken) {
11
+ throw new Error(
12
+ `[SixbAgent] Agent execution '${input.runId}' must hold an execution token before it gets a run token.`
13
+ )
14
+ }
15
+ return createAgentRunToken({
16
+ projectId: input.projectId,
17
+ runId: input.runId,
18
+ executionToken: input.executionToken,
19
+ })
20
+ }
21
+
22
+ /**
23
+ * The token a runner over HTTP reaches its run's session with. It is the runner's alone: the run's
24
+ * commands get the run token, which the session refuses.
25
+ */
26
+ export function runnerTokenFor(input: {
27
+ readonly projectId: string
28
+ readonly runId: string
29
+ readonly executionToken?: string
30
+ }): string {
31
+ if (!input.executionToken) {
32
+ throw new Error(
33
+ `[SixbAgent] Agent execution '${input.runId}' must hold an execution token before it gets a runner token.`
34
+ )
35
+ }
36
+ return createAgentRunnerToken({
37
+ projectId: input.projectId,
38
+ runId: input.runId,
39
+ executionToken: input.executionToken,
40
+ })
41
+ }
42
+
43
+ /**
44
+ * The run token as a request credential: on a provider that adds credentials outside the guest,
45
+ * every call to the API under `apiBaseUrl` gets it, and the run's commands never hold it.
46
+ */
47
+ export function runApiCredential(apiBaseUrl: string, runToken: string): SandboxRequestCredential {
48
+ const url = new URL(apiBaseUrl)
49
+ return {
50
+ origin: url.origin,
51
+ path: { prefix: `${url.pathname.replace(/\/+$/, "")}/api/` },
52
+ method: ["GET", "POST", "PUT", "PATCH", "DELETE"],
53
+ headers: { Authorization: `Bearer ${runToken}` },
54
+ }
55
+ }