@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,51 @@
1
+ import {
2
+ AgentExecutionLostError,
3
+ type AgentRunSession,
4
+ AgentTurnInterruptedError,
5
+ } from "@sixb/core/internal/agents"
6
+ import type { AgentRunRecord, AppendAgentMessageInput } from "@sixb/core/storage"
7
+ import { type AgentRunFailure, toAgentExecutionFailure } from "./failure"
8
+
9
+ /**
10
+ * End a run that failed or stopped, with what it did kept in the same transaction. Returns
11
+ * nothing when the run is no longer this session's; throws {@link AgentFinalizationError} when
12
+ * storage stays unavailable, so the job is redelivered rather than acknowledged.
13
+ */
14
+ export async function recordFate(
15
+ session: AgentRunSession,
16
+ status: "failed" | "cancelled",
17
+ error: unknown,
18
+ messages?: readonly AppendAgentMessageInput[]
19
+ ): Promise<{ readonly run: AgentRunRecord; readonly failure: AgentRunFailure } | undefined> {
20
+ const { run } = session
21
+ const completedAt = new Date()
22
+ const failure = toAgentExecutionFailure(error, {
23
+ status,
24
+ at: completedAt,
25
+ details: agentRunFailureDetails(run),
26
+ })
27
+ try {
28
+ const finalized = await session.finish(
29
+ {
30
+ status,
31
+ error: failure,
32
+ completedAt,
33
+ ...(error instanceof AgentTurnInterruptedError
34
+ ? { finishReason: "interrupted" as const }
35
+ : {}),
36
+ },
37
+ messages
38
+ )
39
+ return { run: finalized, failure }
40
+ } catch (finishError) {
41
+ if (finishError instanceof AgentExecutionLostError) return undefined
42
+ throw finishError
43
+ }
44
+ }
45
+
46
+ /** What a run's failure names: its run, and its thread or its parent. */
47
+ export function agentRunFailureDetails(run: AgentRunRecord): Readonly<Record<string, string>> {
48
+ return run.kind === "conversation"
49
+ ? { runId: run.id, threadId: run.threadId }
50
+ : { parentRunId: run.parentRunId, runId: run.id }
51
+ }
@@ -0,0 +1,118 @@
1
+ import { link, readFile, rm, writeFile } from "node:fs/promises"
2
+ import { delay } from "./abort"
3
+
4
+ /** How often a run waiting for a thread's files directory looks again. */
5
+ const POLL_MS = 100
6
+
7
+ /**
8
+ * How long a run waits for a live holder before it takes the directory over. Only one run of a
9
+ * thread is active at a time, so a holder still alive after its run ended is releasing (seconds)
10
+ * or stopping on a lost lease (its next renewal, within seconds); past this, its process id was
11
+ * reused, or it hangs.
12
+ */
13
+ const TAKEOVER_MS = 60_000
14
+
15
+ /** Who holds a thread's files directory, as its lock file says. */
16
+ interface Holder {
17
+ readonly pid: number
18
+ readonly runId: string
19
+ }
20
+
21
+ /**
22
+ * Hold a thread's files directory for one run, across every process on the computer: each `sixb`
23
+ * opened in the folder shares the directory, and the next turn of a thread can start in another
24
+ * one while the last turn's release still removes the directory. The lock is a file beside the
25
+ * directory, created exclusively and naming its holder; one whose process is gone is stale, and
26
+ * taken over. Resolves with the release, which removes the lock only while it is still this run's.
27
+ *
28
+ * Only one run of a thread is active at a time, so no two runs take a stale lock over at once.
29
+ */
30
+ export async function holdRunFiles(input: {
31
+ /** The thread's files directory. */
32
+ readonly directory: string
33
+ readonly runId: string
34
+ readonly signal: AbortSignal
35
+ }): Promise<() => Promise<void>> {
36
+ const lock = `${input.directory}.lock`
37
+ const own = JSON.stringify({ pid: process.pid, runId: input.runId } satisfies Holder)
38
+ const deadline = Date.now() + TAKEOVER_MS
39
+
40
+ for (;;) {
41
+ if (await create(lock, own, input.runId)) break
42
+
43
+ const holder = await readHolder(lock)
44
+ // Released between the two reads: try again at once.
45
+ if (holder === null) continue
46
+
47
+ if (holder === undefined || !alive(holder.pid) || Date.now() >= deadline) {
48
+ if (holder && alive(holder.pid)) {
49
+ console.warn(
50
+ `[SixbAgent] Run '${input.runId}' takes over ${input.directory} from run '${holder.runId}' (process ${holder.pid}), which did not give it back in time.`
51
+ )
52
+ }
53
+ await rm(lock, { force: true })
54
+ continue
55
+ }
56
+
57
+ await delay(POLL_MS, input.signal)
58
+ }
59
+
60
+ return async () => {
61
+ if ((await readFile(lock, "utf8").catch(() => null)) === own) await rm(lock, { force: true })
62
+ }
63
+ }
64
+
65
+ /**
66
+ * Create the lock file, unless one exists. Linked from a file already written, so no reader ever
67
+ * finds it empty.
68
+ */
69
+ async function create(lock: string, contents: string, runId: string): Promise<boolean> {
70
+ const written = `${lock}.${process.pid}.${runId}`
71
+ await writeFile(written, contents)
72
+ try {
73
+ await link(written, lock)
74
+ return true
75
+ } catch (error) {
76
+ if (errorCode(error) === "EEXIST") return false
77
+ throw error
78
+ } finally {
79
+ await rm(written, { force: true })
80
+ }
81
+ }
82
+
83
+ /** The lock's holder; null once it is gone, undefined when it names none a run can wait for. */
84
+ async function readHolder(lock: string): Promise<Holder | null | undefined> {
85
+ let text: string
86
+ try {
87
+ text = await readFile(lock, "utf8")
88
+ } catch (error) {
89
+ if (errorCode(error) === "ENOENT") return null
90
+ throw error
91
+ }
92
+
93
+ try {
94
+ const parsed: unknown = JSON.parse(text)
95
+ if (typeof parsed !== "object" || parsed === null) return undefined
96
+
97
+ const { pid, runId } = parsed as Record<string, unknown>
98
+ return Number.isSafeInteger(pid) && typeof runId === "string"
99
+ ? { pid: pid as number, runId }
100
+ : undefined
101
+ } catch {
102
+ return undefined
103
+ }
104
+ }
105
+
106
+ /** Whether a process runs: one owned by another user still does. */
107
+ function alive(pid: number): boolean {
108
+ try {
109
+ process.kill(pid, 0)
110
+ return true
111
+ } catch (error) {
112
+ return errorCode(error) === "EPERM"
113
+ }
114
+ }
115
+
116
+ function errorCode(error: unknown): string | undefined {
117
+ return error instanceof Error && "code" in error ? String(error.code) : undefined
118
+ }
@@ -0,0 +1,63 @@
1
+ import type { Sandbox } from "@sixb/core"
2
+ import type { AgentWorkspacePromptContext } from "./agent-prompt"
3
+
4
+ /**
5
+ * Where a provider's sandbox keeps a run's files: in its working directory, which a Git checkout
6
+ * excludes (see `prepareWorkspaceRunFiles`).
7
+ */
8
+ export { SANDBOX_CONTEXT_DIRECTORY } from "@sixb/core/internal/agents"
9
+
10
+ /** The sandbox a run works in, with what the system prompt may say about it. */
11
+ export interface AcquiredRunSandbox {
12
+ readonly sandbox: Sandbox
13
+ /** The workspace's environment; provisioning adds the run's. */
14
+ readonly env?: Readonly<Record<string, string>>
15
+ /** Facts about a prepared workspace; absent for a blank sandbox. */
16
+ readonly promptContext?: AgentWorkspacePromptContext
17
+ /** When the workspace was recreated and its earlier files were lost. */
18
+ readonly resetAt?: string
19
+ }
20
+
21
+ /**
22
+ * How one run obtains its sandbox and gives it back. Every run kind goes through this lifecycle,
23
+ * with one of two behaviors:
24
+ *
25
+ * - ephemeral (`ephemeralRunSandbox`): created for this run, blank or prepared from a recipe, and
26
+ * destroyed when the run releases it;
27
+ * - persistent (`persistentRunSandbox`): a thread's workspace, resumed for this run and saved by
28
+ * `beforeFinalize`. It has no `release`: only a sub-agent run that ends without pausing
29
+ * destroys it.
30
+ *
31
+ * Acquisition may happen before `acquire()`: a thread's workspace is acquired before compaction,
32
+ * so `acquire()` only hands it over. Preservation belongs to `beforeFinalize`, never `release`.
33
+ */
34
+ export interface RunSandbox {
35
+ /**
36
+ * Whether the first model call waits for acquisition. A workspace the prompt describes must
37
+ * exist first; a blank sandbox boots concurrently and tools wait for it only when used.
38
+ */
39
+ readonly waitBeforeModel: boolean
40
+ /**
41
+ * Where the run's files go, known before acquisition so the prompt can name them. As the agent
42
+ * names it: relative to the working directory, or absolute.
43
+ */
44
+ readonly contextDirectory: string
45
+ /** Called once, when the run environment starts. */
46
+ acquire(): Promise<AcquiredRunSandbox>
47
+ /**
48
+ * Give back an acquired sandbox, after the run or a failed provisioning. Absent when the run
49
+ * has nothing to give back, so teardown never waits on it.
50
+ */
51
+ release?(acquired: AcquiredRunSandbox): Promise<void>
52
+ /** Confirm preservation before the run's terminal write. Idempotent: the first call decides. */
53
+ beforeFinalize?(options?: BeforeFinalizeOptions): Promise<void>
54
+ }
55
+
56
+ /** How a run's end leaves its thread's workspace. */
57
+ export interface BeforeFinalizeOptions {
58
+ /**
59
+ * The run leaves nothing its thread goes on from, as a sub-agent run that answered, failed or
60
+ * was stopped: destroy its workspace instead of saving it.
61
+ */
62
+ readonly discard?: boolean
63
+ }
@@ -0,0 +1,433 @@
1
+ import type { AgentMessagePart } from "@sixb/core"
2
+ import {
3
+ type AgentContextBudget,
4
+ type AgentRunSession,
5
+ createAgentMessageId,
6
+ type PausableModelLoopResult,
7
+ runModelLoop,
8
+ toModelMessages,
9
+ } from "@sixb/core/internal/agents"
10
+ import { createSixbError, withFailureMessage } from "@sixb/core/internal/errors"
11
+ import type { ModelMessage, ModelStep } from "@sixb/core/models"
12
+ import {
13
+ type AgentRunFinishReason,
14
+ type AgentThreadRecord,
15
+ type AppendAgentMessageInput,
16
+ coerceAgentRunFinishReason,
17
+ type SubagentRunRecord,
18
+ } from "@sixb/core/storage"
19
+ import { renderCurrentTime, sentSettings } from "./agent-prompt"
20
+ import { unansweredQuestion } from "./ask-parent-tool"
21
+ import { storeChildOutputs } from "./child-files"
22
+ import { createAgentContextGuard } from "./context-guard"
23
+ import { throwIfExecutionLost } from "./errors"
24
+ import type { ResolvedAgentExecutionPlan } from "./execution-plan"
25
+ import {
26
+ type AgentToolOutputFileOf,
27
+ agentTraceFromModelSteps,
28
+ agentTraceFromPartialModelLoop,
29
+ } from "./model-adapters"
30
+ import { markReducedSteps } from "./run-agent-turn"
31
+ import type { SubagentAgentExecutionEnvironment } from "./run-environment"
32
+ import { monitorSandboxReadiness } from "./sandbox-readiness"
33
+ import {
34
+ type SubagentThreadContext,
35
+ subagentContextFailure,
36
+ subagentModelMessages,
37
+ subagentPromptCaching,
38
+ } from "./subagent-context"
39
+ import type { SubagentHistory } from "./subagent-continuation"
40
+ import type { SubagentDelivery, SubagentInbox } from "./subagent-inbox"
41
+ import type { AgentTurnRuntime } from "./turn-runtime"
42
+ import type { AgentRunFiles, AgentTurnContext } from "./types"
43
+
44
+ /**
45
+ * What a child did so far, kept in its thread however its run ends: a failed or stopped child
46
+ * keeps it as an interrupted turn does. Its steps, and each message its parent sent it where it
47
+ * read it.
48
+ */
49
+ export interface SubagentWork {
50
+ messages?: readonly AppendAgentMessageInput[]
51
+ }
52
+
53
+ /**
54
+ * Run one child in its thread. Its request is the thread's messages, the task dated at the thread's
55
+ * creation; what it did is the thread's next message, written with its finish. A held call stops it
56
+ * after that step: it pauses, and its thread's next run continues it once the call is decided.
57
+ */
58
+ export async function runSubagent(input: {
59
+ readonly context: AgentTurnContext
60
+ readonly plan: ResolvedAgentExecutionPlan
61
+ /**
62
+ * The limits every call of the child keeps under, what its environment's preflight left of its
63
+ * thread, and how it compacts that thread from within.
64
+ */
65
+ readonly contextLimits: {
66
+ readonly budget: AgentContextBudget
67
+ readonly thread: SubagentThreadContext
68
+ readonly compactInRun?: SubagentAgentExecutionEnvironment["compactInRun"]
69
+ readonly bytesPerToken?: number
70
+ /** What the child's latest counted call measured (see prepareAgentModel). */
71
+ readonly measuredBytesPerToken?: () => number | undefined
72
+ }
73
+ readonly run: SubagentRunRecord
74
+ /** The child's session: its finish is fenced by the run's execution token. */
75
+ readonly session: AgentRunSession
76
+ /** The child's own thread, and what its runs before this one left there. */
77
+ readonly thread: AgentThreadRecord
78
+ readonly history: SubagentHistory
79
+ /** Created by the worker before the run's tools, which share its signal and accounting. */
80
+ readonly runtime: AgentTurnRuntime
81
+ /** Filled once the model loop returns, for the worker to keep when the run fails afterwards. */
82
+ readonly work?: SubagentWork
83
+ /** Where it finds the files its parent handed over, and leaves the ones it returns. */
84
+ readonly runFiles: AgentRunFiles
85
+ /**
86
+ * What its parent sends it while it runs, read before its next step, and the questions it asks,
87
+ * through the inbox's `ask_parent` among its tools.
88
+ */
89
+ readonly inbox: SubagentInbox
90
+ }): Promise<SubagentRunRecord> {
91
+ const { context, plan, run, thread, runtime, inbox } = input
92
+ const { budget, compactInRun, bytesPerToken, measuredBytesPerToken } = input.contextLimits
93
+ const caching = subagentPromptCaching({
94
+ projectId: context.id,
95
+ thread,
96
+ run,
97
+ history: input.history,
98
+ })
99
+ const createdAt = renderCurrentTime(
100
+ thread.createdAt,
101
+ sentSettings(plan, { timeZone: context.projectTimeZone, locale: context.projectLocale })
102
+ )
103
+ const messages: ModelMessage[] = [
104
+ { role: "system", content: context.systemPrompt },
105
+ ...subagentModelMessages({
106
+ thread: input.contextLimits.thread,
107
+ ...(context.attachmentContext ? { attachmentContext: context.attachmentContext } : {}),
108
+ createdAt,
109
+ }),
110
+ ]
111
+ const guard = createAgentContextGuard({
112
+ budget,
113
+ tools: context.tools.map((tool) => ({
114
+ name: tool.name,
115
+ description: tool.description,
116
+ inputSchema: tool.inputSchema,
117
+ })),
118
+ ...(bytesPerToken === undefined ? {} : { bytesPerToken }),
119
+ ...(measuredBytesPerToken === undefined ? {} : { measuredBytesPerToken }),
120
+ ...(compactInRun
121
+ ? {
122
+ compact: async (compacting) => {
123
+ const request = await compactInRun(compacting)
124
+ return (
125
+ request && [
126
+ { role: "system" as const, content: request.systemPrompt },
127
+ ...request.messages,
128
+ ]
129
+ )
130
+ },
131
+ }
132
+ : {}),
133
+ })
134
+ const sandboxReadiness = monitorSandboxReadiness(context.sandboxReady)
135
+ const abortSignal = AbortSignal.any([runtime.signal, sandboxReadiness.signal])
136
+ let chunkIndex = 0
137
+ const generation = await runModelLoop({
138
+ model: plan.model,
139
+ messages,
140
+ tools: context.tools,
141
+ ...(plan.reasoning === undefined ? {} : { reasoning: plan.reasoning }),
142
+ ...(plan.maxSteps === undefined ? {} : { maxSteps: plan.maxSteps }),
143
+ caching,
144
+ // A message from the parent comes after the step that was running when it arrived, and stays
145
+ // in the history of every later step. The guard weighs the step before it: what it compacts
146
+ // is the history the run started from, never what the parent sent it since.
147
+ prepareStep: async (step) => {
148
+ const prepared = await context.prepareStep?.(step)
149
+ const guarded = await guard.prepareStep({
150
+ ...step,
151
+ messages: prepared?.messages ?? step.messages,
152
+ })
153
+ const mail = await inbox.take(step.stepIndex)
154
+ // The guard's request, when it reduced the one prepared, and the room its answer has.
155
+ if (!mail) return { ...prepared, ...guarded }
156
+
157
+ return {
158
+ ...guarded,
159
+ messages: [
160
+ ...(guarded?.messages ?? prepared?.messages ?? step.messages),
161
+ ...toModelMessages([mail]),
162
+ ],
163
+ }
164
+ },
165
+ recoverStep: guard.recoverStep,
166
+ // One that arrives as the child answers is read too: it writes its result again, after it.
167
+ beforeComplete: async (_step, stepIndex) => {
168
+ const mail = await inbox.take(stepIndex + 1, { afterAnswer: true })
169
+ return mail ? toModelMessages([mail]) : undefined
170
+ },
171
+ signal: abortSignal,
172
+ onEvent: (chunk) =>
173
+ input.session.events.publishUiChunk({ run, chunkIndex: chunkIndex++, chunk }),
174
+ // The approval records decide, never the prompt or the tool output: a held call stops the
175
+ // child after that step, whatever its model would do next. So does a question its parent's
176
+ // turn ended without answering.
177
+ pauseAfterStep: async () =>
178
+ inbox.deferred !== undefined || (await input.session.heldCalls.holdsRun()),
179
+ }).catch((error: unknown) => {
180
+ throw subagentContextFailure(error, run) ?? error
181
+ })
182
+ const work = subagentWorkMessages(
183
+ generation,
184
+ run,
185
+ inbox.deliveries,
186
+ guard.reducedFromStep(),
187
+ context.outputFileOf
188
+ )
189
+ if (input.work) input.work.messages = work
190
+
191
+ return settleSubagent({
192
+ ...input,
193
+ generation,
194
+ work,
195
+ abortSignal,
196
+ sandboxReadiness,
197
+ lastMessageAt: inbox.deliveries.at(-1)?.afterSteps ?? 0,
198
+ })
199
+ }
200
+
201
+ /** End a child whose model loop returned: paused on its held calls, answered, or failed. */
202
+ async function settleSubagent(
203
+ input: Omit<Parameters<typeof finishSubagent>[0], "finishReason" | "text"> & {
204
+ readonly generation: PausableModelLoopResult
205
+ readonly sandboxReadiness: ReturnType<typeof monitorSandboxReadiness>
206
+ /** After how many steps it read its parent's last message. */
207
+ readonly lastMessageAt: number
208
+ }
209
+ ): Promise<SubagentRunRecord> {
210
+ const { generation, run } = input
211
+ assertSubagentCanFinalize(input)
212
+ if (generation.status === "aborted")
213
+ throw new DOMException("Subagent stream was aborted.", "AbortError")
214
+
215
+ // A call held after its last step, by a command left running in the sandbox, pauses it too. A
216
+ // held call wins over a question: only a decision continues it, and it can ask again then.
217
+ const asked = input.inbox.deferred !== undefined
218
+ const held =
219
+ (generation.status === "paused" && !asked) || (await input.session.heldCalls.holdsRun())
220
+ if (held) {
221
+ // Its question then goes unanswered: the decision continues it.
222
+ const work = asked ? unansweredQuestion(input.work) : input.work
223
+ return finishSubagent({ ...input, work, finishReason: "awaiting_approval" })
224
+ }
225
+ if (generation.status === "paused" || asked) {
226
+ return finishSubagent({ ...input, finishReason: "awaiting_answer" })
227
+ }
228
+
229
+ // Nobody watches a child: its limit ends it, and its parent decides what next. What it wrote
230
+ // stays in its thread, and its parent's wait reads the last of it.
231
+ if (generation.stepLimitReached) {
232
+ const steps = generation.steps.length
233
+ const remedy = "Spawn it again with a narrower task, or do the rest yourself."
234
+ throw withFailureMessage(
235
+ createSixbError(
236
+ "agent.step_limit_reached",
237
+ `[SixbAgent] Subagent run '${run.id}' stopped after ${steps} steps before finishing its task. ${remedy}`,
238
+ { details: { parentRunId: run.parentRunId, runId: run.id } }
239
+ ),
240
+ `The subagent stopped after ${steps} steps before finishing its task. ${remedy}`
241
+ )
242
+ }
243
+
244
+ // The parent would read a cut-short answer as complete: it gets the cause instead.
245
+ if (generation.finishReason === "length") {
246
+ const remedy = "Spawn it again with lower reasoning or a narrower task."
247
+ throw withFailureMessage(
248
+ createSixbError(
249
+ "agent.execution_failed",
250
+ `[SixbAgent] Subagent run '${run.id}' reached the model's output limit before finishing its answer. ${remedy}`,
251
+ { details: { parentRunId: run.parentRunId, runId: run.id } }
252
+ ),
253
+ `The subagent's model reached its output limit before finishing its answer. ${remedy}`
254
+ )
255
+ }
256
+ return finishSubagent({
257
+ ...input,
258
+ text: subagentResult(generation.steps, run, input.lastMessageAt),
259
+ finishReason: coerceAgentRunFinishReason(generation.finishReason) ?? "unknown",
260
+ })
261
+ }
262
+
263
+ /**
264
+ * Keep the child's outcome: its answer, what it wrote under `out/`, and what it did as its thread's
265
+ * next message. A paused child keeps its files too, for the run that continues it; `wait_agent`
266
+ * hands over only a finished child's, as an unfinished one's would pass for complete. Its `out/`
267
+ * is stored even when its workspace is kept: a continuation that finds it lost gets it back.
268
+ */
269
+ async function finishSubagent(input: {
270
+ readonly context: AgentTurnContext
271
+ readonly plan: ResolvedAgentExecutionPlan
272
+ readonly run: SubagentRunRecord
273
+ readonly runtime: AgentTurnRuntime
274
+ readonly runFiles: AgentRunFiles
275
+ readonly session: AgentRunSession
276
+ readonly abortSignal: AbortSignal
277
+ readonly finishReason: AgentRunFinishReason
278
+ readonly work: readonly AppendAgentMessageInput[]
279
+ readonly inbox: SubagentInbox
280
+ /** None yet for a paused child. */
281
+ readonly text?: string
282
+ }): Promise<SubagentRunRecord> {
283
+ const { context, run } = input
284
+ const outputs = await storeChildOutputs({
285
+ files: input.runFiles,
286
+ handed: run.spec.files ?? [],
287
+ signal: input.abortSignal,
288
+ })
289
+ input.runtime.assertCanContinue()
290
+
291
+ // Before the terminal write, and after out/ was read: a paused child's workspace is kept for
292
+ // the run that continues it, and one that answered goes.
293
+ const paused =
294
+ input.finishReason === "awaiting_approval" || input.finishReason === "awaiting_answer"
295
+ // A paused child stops reading here: what came and it never read goes on with the run that
296
+ // continues it, as that run's first message.
297
+ const unread = paused ? input.inbox.close() : []
298
+ await context.beforeFinalize?.({ discard: !paused })
299
+ input.runtime.assertCanContinue()
300
+
301
+ const finalized = await input.session.finish(
302
+ {
303
+ status: "succeeded",
304
+ modelId: input.plan.model.modelId,
305
+ finishReason: input.finishReason,
306
+ result: {
307
+ text: input.text ?? "",
308
+ ...(outputs.files.length > 0 ? { files: outputs.files } : {}),
309
+ ...(outputs.error === undefined ? {} : { filesError: outputs.error }),
310
+ ...(unread.length > 0 ? { unread } : {}),
311
+ },
312
+ },
313
+ input.work
314
+ )
315
+ if (finalized.kind !== "subagent") {
316
+ throw new Error(`[SixbAgent] Subagent run '${run.id}' changed kind during finalization.`)
317
+ }
318
+ await input.session.events.publishRunFinished(finalized)
319
+ return finalized
320
+ }
321
+
322
+ /**
323
+ * What a child run did, as the messages its thread keeps: its steps, the one cut short included,
324
+ * and each message its parent sent it, where it read it. Each has the run's id.
325
+ */
326
+ function subagentWorkMessages(
327
+ generation: PausableModelLoopResult,
328
+ run: SubagentRunRecord,
329
+ deliveries: readonly SubagentDelivery[],
330
+ /** The first step whose request the guard reduced: it and those after it are marked so. */
331
+ reducedFromStep: number | undefined,
332
+ outputFileOf: AgentToolOutputFileOf | undefined
333
+ ): readonly AppendAgentMessageInput[] {
334
+ const details = { threadId: run.threadId, runId: run.id }
335
+ const messages: AppendAgentMessageInput[] = []
336
+ const push = (role: "user" | "assistant", parts: readonly AgentMessagePart[]) => {
337
+ messages.push({
338
+ id: createAgentMessageId(),
339
+ projectId: run.projectId,
340
+ threadId: run.threadId,
341
+ runId: run.id,
342
+ role,
343
+ parts,
344
+ })
345
+ }
346
+ // Steps from `from` on, the ones whose request was reduced marked so.
347
+ const pushSteps = (parts: readonly AgentMessagePart[], from: number) => {
348
+ const marked = markReducedSteps(
349
+ parts,
350
+ reducedFromStep === undefined ? undefined : reducedFromStep - from
351
+ )
352
+ if (marked.some((part) => part.type !== "step-start")) push("assistant", marked)
353
+ }
354
+
355
+ let from = 0
356
+ for (const delivery of deliveries) {
357
+ pushSteps(
358
+ agentTraceFromModelSteps(
359
+ generation.steps.slice(from, delivery.afterSteps),
360
+ details,
361
+ outputFileOf
362
+ ),
363
+ from
364
+ )
365
+ push("user", delivery.parts)
366
+ from = delivery.afterSteps
367
+ }
368
+
369
+ const rest = generation.steps.slice(from)
370
+ pushSteps(
371
+ generation.status === "aborted"
372
+ ? agentTraceFromPartialModelLoop(rest, generation.partialContent, details, outputFileOf)
373
+ : agentTraceFromModelSteps(rest, details, outputFileOf),
374
+ from
375
+ )
376
+ return messages
377
+ }
378
+
379
+ function assertSubagentCanFinalize(input: {
380
+ readonly runtime: AgentTurnRuntime
381
+ readonly sandboxReadiness: ReturnType<typeof monitorSandboxReadiness>
382
+ }): void {
383
+ throwIfExecutionLost(input.runtime.sourceSignal)
384
+ input.sandboxReadiness.throwIfFailed()
385
+ input.runtime.assertCanContinue()
386
+ }
387
+
388
+ /** The child's answer, or a failure that tells the parent what to do about none. */
389
+ function subagentResult(
390
+ steps: readonly ModelStep[],
391
+ run: SubagentRunRecord,
392
+ lastMessageAt: number
393
+ ): string {
394
+ const text = subagentAnswer(steps, lastMessageAt)
395
+ if (!text) {
396
+ const remedy = "Spawn it again with a task that says what its answer must contain."
397
+ throw withFailureMessage(
398
+ createSixbError(
399
+ "agent.execution_failed",
400
+ `[SixbAgent] Subagent run '${run.id}' finished without an answer. ${remedy}`,
401
+ { details: { parentRunId: run.parentRunId, runId: run.id } }
402
+ ),
403
+ `The subagent finished without an answer. ${remedy}`
404
+ )
405
+ }
406
+ return text
407
+ }
408
+
409
+ /**
410
+ * What the child answers: the text it wrote once its last local tool returned, through any provider
411
+ * continuation, and after the last message its parent sent it (read after `lastMessageAt` steps),
412
+ * which an answer written before it no longer answers. Without any, the last text it wrote, such
413
+ * as an answer it gave before a final tool call. Narration written before earlier tool calls never
414
+ * reaches the parent.
415
+ */
416
+ export function subagentAnswer(steps: readonly ModelStep[], lastMessageAt = 0): string {
417
+ const ranLocalTools = steps.map((step) =>
418
+ step.content.some((part) => part.type === "tool-call" && part.providerExecuted !== true)
419
+ )
420
+ const answer = textOf(steps.slice(Math.max(ranLocalTools.lastIndexOf(true) + 1, lastMessageAt)))
421
+ if (answer) return answer
422
+
423
+ const written = steps.map((step) => textOf([step])).filter(Boolean)
424
+ return written.at(-1) ?? ""
425
+ }
426
+
427
+ function textOf(steps: readonly ModelStep[]): string {
428
+ return steps
429
+ .flatMap((step) => step.content)
430
+ .flatMap((part) => (part.type === "text" ? [part.text] : []))
431
+ .join("\n")
432
+ .trim()
433
+ }