@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,540 @@
1
+ import { createHash } from "node:crypto"
2
+ import { posix } from "node:path"
3
+ import type { FileRef } from "@sixb/core"
4
+ import { AgentToolPublicError } from "@sixb/core"
5
+ import type { AgentRunFileStore } from "@sixb/core/internal/agents"
6
+ import { inferFileMediaType } from "@sixb/core/internal/blob-storage"
7
+ import type { SubagentRunFile } from "@sixb/core/storage"
8
+ import { NEVER_ABORTED_SIGNAL, waitForAbort } from "./abort"
9
+ import { readBlob } from "./artifacts/materialize"
10
+ import {
11
+ formatBytes,
12
+ type PreparedAgentAttachmentContext,
13
+ SANDBOX_ATTACHMENT_LIMITS,
14
+ } from "./attachments"
15
+ import {
16
+ listSandboxFiles,
17
+ readSandboxFile,
18
+ resolveSandboxEntry,
19
+ resolveSandboxPath,
20
+ type SandboxFileEntry,
21
+ SandboxFileError,
22
+ type SandboxFileListing,
23
+ sandboxRoots,
24
+ } from "./sandbox-files"
25
+ import { type AgentSandboxHandle, contextPath } from "./sandbox-handle"
26
+ import { AgentFileBudget } from "./tools/tool-files"
27
+ import type { AgentRunFiles } from "./types"
28
+
29
+ // A parent Agent hands its child files from its sandbox, and gets back what the child wrote under
30
+ // `out/`. Both go through blob storage: the parent stores what it hands over in the child's spec,
31
+ // the child stores its outputs in its result, and each side copies them into its own sandbox.
32
+
33
+ /** Where a child writes the files its parent gets back, relative to its working directory. */
34
+ const CHILD_OUTPUT_DIRECTORY = "out"
35
+
36
+ /**
37
+ * Where a parent finds them, a directory per spawn key, in the context directory. They last for
38
+ * the turn, like the run's attachments and artifacts.
39
+ */
40
+ export const CHILD_FILES_DIRECTORY = "children"
41
+
42
+ /** What a run installs in its context directory that holds files worth handing over. */
43
+ const HANDED_RUN_DIRECTORIES = ["attachments", "artifacts", "tool-files", CHILD_FILES_DIRECTORY]
44
+ const SANDBOX_TIMEOUT_MS = 30_000
45
+ const { maxFiles, fileMaxBytes, totalMaxBytes } = SANDBOX_ATTACHMENT_LIMITS
46
+
47
+ /**
48
+ * Whether `path` is in the run's context directory, both relative to the working directory. A
49
+ * context directory outside the working directory holds no such path.
50
+ */
51
+ function isRunFile(path: string, contextDirectory: string): boolean {
52
+ return path === contextDirectory || path.startsWith(`${contextDirectory}/`)
53
+ }
54
+
55
+ /** A file a child returned, copied into its parent's sandbox for the turn. */
56
+ export interface InstalledChildFile extends SubagentRunFile {
57
+ /** As the agent names it: relative to the working directory, or absolute. */
58
+ readonly sandboxPath: string
59
+ }
60
+
61
+ /** A file a parent hands its child, checked but not read yet. */
62
+ export interface HandedSource {
63
+ /** Where the child finds it: the path the parent named, relative to the working directory. */
64
+ readonly path: string
65
+ /** Where it really is, every symbolic link followed. */
66
+ readonly absolutePath: string
67
+ readonly sizeBytes?: number
68
+ }
69
+
70
+ /**
71
+ * Check the files and directories a parent hands its child, without reading them. Refused when a
72
+ * path is missing or a link, leaves the working directory or really is the run's own context, or
73
+ * when the files pass the attachment limits.
74
+ */
75
+ export async function listHandedSources(input: {
76
+ readonly files: AgentRunFiles
77
+ readonly paths: readonly string[]
78
+ readonly signal: AbortSignal
79
+ }): Promise<readonly HandedSource[]> {
80
+ const handle = await input.files.sandbox()
81
+ input.signal.throwIfAborted()
82
+
83
+ // The working directory may itself be reached through a link: compare real paths with its own,
84
+ // and with the context directory's when that lies elsewhere.
85
+ const realRoots: string[] = []
86
+ for (const root of sandboxRoots(handle)) {
87
+ const entry = await resolveSandboxEntry(handle, {
88
+ path: root,
89
+ signal: input.signal,
90
+ timeoutMs: SANDBOX_TIMEOUT_MS,
91
+ })
92
+ realRoots.push(entry.kind === "directory" ? entry.realPath : root)
93
+ }
94
+
95
+ const sources = new Map<string, HandedSource>()
96
+ for (const path of input.paths) {
97
+ for (const source of await handedSourcesAt(handle, realRoots, path, input.signal)) {
98
+ sources.set(source.path, source)
99
+ }
100
+ }
101
+ if (sources.size > maxFiles) {
102
+ throw handOffError(
103
+ `${sources.size} files; a child receives at most ${maxFiles}. Hand over fewer files or a smaller directory`
104
+ )
105
+ }
106
+ assertWithinTotal([...sources.values()].reduce((sum, source) => sum + (source.sizeBytes ?? 0), 0))
107
+ return [...sources.values()]
108
+ }
109
+
110
+ /**
111
+ * Read and store the files a parent hands its child once it will be admitted, one at a time,
112
+ * against the parent's run budget: `release` them when it is not.
113
+ */
114
+ export async function storeHandedFiles(input: {
115
+ readonly files: AgentRunFiles
116
+ readonly sources: readonly HandedSource[]
117
+ readonly signal: AbortSignal
118
+ }): Promise<{ readonly files: readonly SubagentRunFile[]; release(): void }> {
119
+ const reservation = input.files.budget.reserve(0, "spawn_agent")
120
+ try {
121
+ const stored: SubagentRunFile[] = []
122
+ await readHandedSources(input, async (source, bytes) => {
123
+ const fileRef = await storeFile(input.files, reservation, bytes, source.path, input.signal)
124
+ stored.push({ path: source.path, fileRef })
125
+ })
126
+ return { files: stored, release: () => reservation.release() }
127
+ } catch (error) {
128
+ reservation.release()
129
+ throw error
130
+ }
131
+ }
132
+
133
+ /** The references the files would be stored under, read one at a time and stored nowhere. */
134
+ export async function handedFileRefs(input: {
135
+ readonly files: AgentRunFiles
136
+ readonly sources: readonly HandedSource[]
137
+ readonly signal: AbortSignal
138
+ }): Promise<readonly SubagentRunFile[]> {
139
+ const refs: SubagentRunFile[] = []
140
+ await readHandedSources(input, async (source, bytes) => {
141
+ refs.push({ path: source.path, fileRef: contentFileRef(bytes, source.path) })
142
+ })
143
+ return refs
144
+ }
145
+
146
+ async function readHandedSources(
147
+ input: {
148
+ readonly files: AgentRunFiles
149
+ readonly sources: readonly HandedSource[]
150
+ readonly signal: AbortSignal
151
+ },
152
+ use: (source: HandedSource, bytes: Uint8Array) => Promise<void>
153
+ ): Promise<void> {
154
+ const handle = await input.files.sandbox()
155
+ let totalBytes = 0
156
+ for (const source of input.sources) {
157
+ if (source.sizeBytes !== undefined && source.sizeBytes > fileMaxBytes) {
158
+ throw fileTooLarge(source.path)
159
+ }
160
+
161
+ const bytes = await readSandboxFile(handle, {
162
+ path: source.absolutePath,
163
+ maxBytes: fileMaxBytes,
164
+ signal: input.signal,
165
+ timeoutMs: SANDBOX_TIMEOUT_MS,
166
+ }).catch((error: unknown) => {
167
+ throw toHandOffError(error, source.path)
168
+ })
169
+ if (bytes.byteLength > fileMaxBytes) throw fileTooLarge(source.path)
170
+
171
+ totalBytes += bytes.byteLength
172
+ assertWithinTotal(totalBytes)
173
+ await use(source, bytes)
174
+ }
175
+ }
176
+
177
+ /**
178
+ * The child's side: the files its parent handed over, at the same paths in its sandbox, listed in
179
+ * `$SIXB_ATTACHMENTS` and readable with `view_file`.
180
+ */
181
+ export async function prepareHandedFiles(input: {
182
+ readonly projectId: string
183
+ readonly parentRunId: string
184
+ readonly files: readonly SubagentRunFile[]
185
+ /**
186
+ * The files are in the sandbox already, as a resumed workspace kept them: listed, not copied,
187
+ * so what the child changed in them stays. Those in the context directory are copied again:
188
+ * every run starts without it.
189
+ */
190
+ readonly inSandbox?: boolean
191
+ /** The child's context directory, relative to its working directory or absolute. */
192
+ readonly contextDirectory: string
193
+ readonly blobStorage: AgentRunFileStore
194
+ readonly signal?: AbortSignal
195
+ }): Promise<PreparedAgentAttachmentContext> {
196
+ const signal = input.signal ?? NEVER_ABORTED_SIGNAL
197
+ const sandboxFiles: PreparedAgentAttachmentContext["sandboxFiles"][number][] = []
198
+
199
+ const copied = input.inSandbox
200
+ ? input.files.filter((file) => isRunFile(file.path, input.contextDirectory))
201
+ : input.files
202
+ for (const { path, fileRef } of copied) {
203
+ const stat = await waitForAbort(input.blobStorage.stat(fileRef.blobId), signal)
204
+ if (stat?.digest !== fileRef.digest) {
205
+ throw new Error(
206
+ `[SixbAgent] '${path}', handed over by parent run '${input.parentRunId}', is no longer in blob storage.`
207
+ )
208
+ }
209
+ sandboxFiles.push({
210
+ key: path,
211
+ path,
212
+ bytes: await readBlob(input.blobStorage, fileRef.blobId, signal),
213
+ fileRef,
214
+ })
215
+ }
216
+
217
+ return {
218
+ entries: [],
219
+ promptTextByPartKey: new Map(),
220
+ modelFileDataByPartKey: new Map(),
221
+ sandboxFiles,
222
+ manifestJson: JSON.stringify(
223
+ {
224
+ projectId: input.projectId,
225
+ parentRunId: input.parentRunId,
226
+ attachments: input.files.map(({ path, fileRef }) => ({
227
+ key: path,
228
+ fileName: posix.basename(path),
229
+ ...(fileRef.mediaType === undefined ? {} : { mediaType: fileRef.mediaType }),
230
+ sizeBytes: fileRef.sizeBytes,
231
+ digest: fileRef.digest,
232
+ sandboxPath: path,
233
+ source: "parent",
234
+ })),
235
+ },
236
+ null,
237
+ 2
238
+ ),
239
+ }
240
+ }
241
+
242
+ /**
243
+ * Store what a child that finished wrote under `out/`, by path relative to it, against a budget of
244
+ * their own: what the child published does not count. A file its parent handed over there and the
245
+ * child left unchanged does not come back. Past the attachment limits, none comes back and `error`
246
+ * says why, so the child's answer still does.
247
+ */
248
+ export async function storeChildOutputs(input: {
249
+ readonly files: AgentRunFiles
250
+ readonly handed: readonly SubagentRunFile[]
251
+ readonly signal: AbortSignal
252
+ }): Promise<{ readonly files: readonly SubagentRunFile[]; readonly error?: string }> {
253
+ const { signal } = input
254
+ const handle = await input.files.sandbox()
255
+ const directory = posix.join(handle.sandbox.workingDirectory, CHILD_OUTPUT_DIRECTORY)
256
+ const listing = await listSandboxFiles(handle, {
257
+ directory,
258
+ maxFiles: maxFiles + input.handed.length + 1,
259
+ signal,
260
+ timeoutMs: SANDBOX_TIMEOUT_MS,
261
+ })
262
+
263
+ // A file of the size of one handed over at its path may be that file: only its bytes tell.
264
+ const handed = new Map(input.handed.map((file) => [file.path, file.fileRef]))
265
+ const handedAt = (path: string) => handed.get(posix.join(CHILD_OUTPUT_DIRECTORY, path))
266
+ const maybeHanded = (file: SandboxFileEntry) =>
267
+ handedAt(file.relativePath)?.sizeBytes === file.sizeBytes
268
+
269
+ // Checked before reading anything: these files come back whatever their bytes.
270
+ const tooMany = outputLimitError(
271
+ listing.files.filter((file) => !maybeHanded(file)),
272
+ listing.truncated
273
+ )
274
+ if (tooMany) return { files: [], error: tooMany }
275
+
276
+ const kept: { readonly entry: SandboxFileEntry; readonly bytes: Uint8Array }[] = []
277
+ for (const entry of listing.files) {
278
+ let bytes: Uint8Array
279
+ try {
280
+ bytes = await readSandboxFile(handle, {
281
+ path: posix.join(directory, entry.relativePath),
282
+ maxBytes: fileMaxBytes,
283
+ signal,
284
+ timeoutMs: SANDBOX_TIMEOUT_MS,
285
+ })
286
+ } catch (error) {
287
+ if (!(error instanceof SandboxFileError)) throw error
288
+ return { files: [], error: outputError(`'out/${entry.relativePath}': ${error.message}`) }
289
+ }
290
+ if (handedAt(entry.relativePath)?.digest === `sha256:${sha256(bytes)}`) continue
291
+
292
+ kept.push({ entry: { relativePath: entry.relativePath, sizeBytes: bytes.byteLength }, bytes })
293
+ }
294
+ const pastLimits = outputLimitError(kept.map((file) => file.entry))
295
+ if (pastLimits) return { files: [], error: pastLimits }
296
+
297
+ // The child's outputs have a budget of their own, within the limits checked above.
298
+ const reservation = new AgentFileBudget(totalMaxBytes).reserve(0, "out/")
299
+ const files: SubagentRunFile[] = []
300
+ for (const { entry, bytes } of kept) {
301
+ files.push({
302
+ path: entry.relativePath,
303
+ fileRef: await storeFile(input.files, reservation, bytes, entry.relativePath, signal),
304
+ })
305
+ }
306
+ return { files }
307
+ }
308
+
309
+ /**
310
+ * The parent's side: copy what a child wrote under `out/` into the parent's sandbox for the turn,
311
+ * under `children/<key>/` in its context directory. Each file's reference names it by that path,
312
+ * as its `logicalPath`, and by a name no other file of the child shares, so a later turn tells
313
+ * them apart in `$SIXB_ATTACHMENTS`.
314
+ */
315
+ export async function installChildOutputs(input: {
316
+ readonly files: AgentRunFiles
317
+ readonly key: string
318
+ readonly outputs: readonly SubagentRunFile[]
319
+ readonly signal: AbortSignal
320
+ }): Promise<readonly InstalledChildFile[]> {
321
+ const { signal } = input
322
+ const handle = await input.files.sandbox()
323
+ const childDirectory = childDirectoryName(input.key)
324
+ const directory = posix.join(handle.contextDirectory, CHILD_FILES_DIRECTORY, childDirectory)
325
+
326
+ const installed: InstalledChildFile[] = []
327
+ const names = new Set<string>()
328
+ for (const { path, fileRef } of input.outputs) {
329
+ // One file at a time: a child's files can hold 100 MB.
330
+ const contents = await readBlob(input.files.blobStorage, fileRef.blobId, signal)
331
+ signal.throwIfAborted()
332
+ await handle.sandbox.writeFiles([
333
+ { path: posix.resolve(handle.sandbox.workingDirectory, directory, path), contents },
334
+ ])
335
+
336
+ const name = `${childDirectory}-${path.split("/").join("-")}`
337
+ let fileName = name
338
+ for (let copy = 2; names.has(fileName); copy += 1) fileName = `${copy}-${name}`
339
+ names.add(fileName)
340
+ installed.push({
341
+ path,
342
+ fileRef: { ...fileRef, fileName, logicalPath: posix.join(childDirectory, path) },
343
+ sandboxPath: posix.join(directory, path),
344
+ })
345
+ }
346
+ return installed
347
+ }
348
+
349
+ /** A spawn key as one path segment; one that needs changing gets a hash, so two never collide. */
350
+ function childDirectoryName(key: string): string {
351
+ if (/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(key)) return key
352
+
353
+ const safe = key.replace(/[^A-Za-z0-9._-]/g, "_").replace(/^[._-]+/, "")
354
+ return `${safe.slice(0, 96) || "child"}-${sha256(new TextEncoder().encode(key)).slice(0, 8)}`
355
+ }
356
+
357
+ async function handedSourcesAt(
358
+ handle: AgentSandboxHandle,
359
+ realRoots: readonly string[],
360
+ path: string,
361
+ signal: AbortSignal
362
+ ): Promise<readonly HandedSource[]> {
363
+ const [root = "/", context] = sandboxRoots(handle)
364
+ let requested: string
365
+ try {
366
+ requested = resolveSandboxPath(handle, path)
367
+ } catch (error) {
368
+ throw toHandOffError(error, path)
369
+ }
370
+ // A run file in a context directory outside the working directory reaches the child at its path
371
+ // in that directory, such as `attachments/report.pdf`.
372
+ const fromContext = context !== undefined && requested.startsWith(`${context}/`)
373
+ const childPath = posix.relative(fromContext ? context : root, requested)
374
+ const realRoot = (fromContext ? realRoots[1] : realRoots[0]) ?? root
375
+
376
+ // What the path really is decides what it may hand over: a link must not reach the run context.
377
+ const entry = await resolveSandboxEntry(handle, {
378
+ path: requested,
379
+ signal,
380
+ timeoutMs: SANDBOX_TIMEOUT_MS,
381
+ }).catch((error: unknown) => {
382
+ throw toHandOffError(error, path)
383
+ })
384
+ if (entry.kind === "missing") throw handOffError(`'${path}': it does not exist`)
385
+ if (entry.kind === "link") throw handOffError(`'${path}': it is a symbolic link`)
386
+ const realPath = posix.relative(realRoot, entry.realPath)
387
+ if (realPath === "" || realPath.startsWith("../") || realPath === "..") {
388
+ throw handOffError(
389
+ fromContext
390
+ ? `'${path}': it leads outside the run's context directory`
391
+ : `'${path}': it leads outside the sandbox working directory`
392
+ )
393
+ }
394
+ if (fromContext) assertHandableRunFile(handle, realPath, path)
395
+ else assertHandable(handle, realPath, path)
396
+
397
+ if (entry.kind === "file") {
398
+ return [{ path: childPath, absolutePath: entry.realPath }]
399
+ }
400
+
401
+ let listing: SandboxFileListing
402
+ try {
403
+ listing = await listSandboxFiles(handle, {
404
+ directory: entry.realPath,
405
+ maxFiles: maxFiles + 1,
406
+ signal,
407
+ timeoutMs: SANDBOX_TIMEOUT_MS,
408
+ })
409
+ } catch (error) {
410
+ throw toHandOffError(error, path)
411
+ }
412
+ if (listing.truncated) {
413
+ throw handOffError(
414
+ `'${path}': it holds more than ${maxFiles} files; a child receives at most ${maxFiles}`
415
+ )
416
+ }
417
+ if (listing.files.length === 0) throw handOffError(`'${path}': it is an empty directory`)
418
+
419
+ // A listing reaches no file through a link, so each file is where it is listed.
420
+ return listing.files.map((file) => ({
421
+ path: posix.join(childPath, file.relativePath),
422
+ absolutePath: posix.join(entry.realPath, file.relativePath),
423
+ sizeBytes: file.sizeBytes,
424
+ }))
425
+ }
426
+
427
+ /**
428
+ * Hands over nothing of the run's context directory but its files: the context holds the run's
429
+ * API address. Checked where a path really is; a copy the Agent makes with `cp` is not.
430
+ */
431
+ function assertHandable(handle: AgentSandboxHandle, relativePath: string, requested: string): void {
432
+ const contextDirectory = posix.relative(
433
+ posix.resolve(handle.sandbox.workingDirectory),
434
+ contextPath(handle)
435
+ )
436
+ if (!isRunFile(relativePath, contextDirectory)) return
437
+ assertHandableRunFile(handle, posix.relative(contextDirectory, relativePath), requested)
438
+ }
439
+
440
+ /** A path in the context directory, relative to it: only the files the run was given or made. */
441
+ function assertHandableRunFile(
442
+ handle: AgentSandboxHandle,
443
+ relativePath: string,
444
+ requested: string
445
+ ): void {
446
+ if (HANDED_RUN_DIRECTORIES.some((directory) => `${relativePath}/`.startsWith(`${directory}/`))) {
447
+ return
448
+ }
449
+
450
+ throw handOffError(
451
+ `'${requested}': it is part of the run context Sixb installs under ${handle.contextDirectory}. Hand over files from your working directory, $SIXB_ATTACHMENT_DIR, $SIXB_ARTIFACTS_DIR or ${posix.join(handle.contextDirectory, CHILD_FILES_DIRECTORY)}`
452
+ )
453
+ }
454
+
455
+ async function storeFile(
456
+ files: AgentRunFiles,
457
+ reservation: ReturnType<AgentFileBudget["reserve"]>,
458
+ bytes: Uint8Array,
459
+ path: string,
460
+ signal: AbortSignal
461
+ ): Promise<FileRef> {
462
+ // Blob storage keeps identical bytes once: a file handed to several children counts once.
463
+ const expected = contentFileRef(bytes, path)
464
+ reservation.addContent(sha256(bytes), bytes.byteLength)
465
+ const stored = await files.blobStorage.put({
466
+ body: bytes,
467
+ expectedSizeBytes: bytes.byteLength,
468
+ signal,
469
+ ...(expected.fileName === undefined ? {} : { fileName: expected.fileName }),
470
+ ...(expected.mediaType === undefined ? {} : { mediaType: expected.mediaType }),
471
+ })
472
+ if (stored.blobId !== expected.blobId) {
473
+ throw new Error(`[SixbAgent] Blob storage stored '${path}' under another id.`)
474
+ }
475
+ return stored
476
+ }
477
+
478
+ /** The reference blob storage gives these bytes, named after `path`: its id is their SHA-256. */
479
+ function contentFileRef(bytes: Uint8Array, path: string): FileRef {
480
+ const hex = sha256(bytes)
481
+ const fileName = posix.basename(path)
482
+ return {
483
+ blobId: `blob_${hex}`,
484
+ digest: `sha256:${hex}`,
485
+ sizeBytes: bytes.byteLength,
486
+ fileName,
487
+ mediaType: inferFileMediaType(fileName, bytes),
488
+ }
489
+ }
490
+
491
+ function assertWithinTotal(totalBytes: number): void {
492
+ if (totalBytes <= totalMaxBytes) return
493
+
494
+ const limit = formatBytes(totalMaxBytes)
495
+ throw handOffError(`more than ${limit}; a child receives at most ${limit} in all`)
496
+ }
497
+
498
+ function fileTooLarge(path: string): AgentToolPublicError {
499
+ return handOffError(
500
+ `'${path}': it holds more than ${formatBytes(fileMaxBytes)}, the most a file handed to a child may hold`
501
+ )
502
+ }
503
+
504
+ function toHandOffError(error: unknown, path: string): unknown {
505
+ if (!(error instanceof SandboxFileError)) return error
506
+ if (error.reason === "too_large") return fileTooLarge(path)
507
+ return handOffError(`'${path}': ${error.message}`)
508
+ }
509
+
510
+ function handOffError(problem: string): AgentToolPublicError {
511
+ return new AgentToolPublicError(`[SixbAgent] spawn_agent cannot hand over ${problem}.`)
512
+ }
513
+
514
+ /** Why the files a child left in `out/` do not come back, or nothing when they do. */
515
+ function outputLimitError(
516
+ files: readonly SandboxFileEntry[],
517
+ truncated = false
518
+ ): string | undefined {
519
+ if (truncated || files.length > maxFiles) {
520
+ return outputError(`It left more than ${maxFiles} files in out/`)
521
+ }
522
+ const tooLarge = files.find((file) => file.sizeBytes > fileMaxBytes)
523
+ if (tooLarge) {
524
+ return outputError(
525
+ `'out/${tooLarge.relativePath}' holds more than ${formatBytes(fileMaxBytes)}`
526
+ )
527
+ }
528
+ if (files.reduce((sum, file) => sum + file.sizeBytes, 0) > totalMaxBytes) {
529
+ return outputError(`Its files in out/ hold more than ${formatBytes(totalMaxBytes)} in all`)
530
+ }
531
+ return undefined
532
+ }
533
+
534
+ function outputError(problem: string): string {
535
+ return `${problem}, so none of its files came back: at most ${maxFiles} files of ${formatBytes(fileMaxBytes)}, ${formatBytes(totalMaxBytes)} in all, do. To get them, spawn it again with a task that writes fewer or smaller files to out/, or that publishes them.`
536
+ }
537
+
538
+ function sha256(bytes: Uint8Array): string {
539
+ return createHash("sha256").update(bytes).digest("hex")
540
+ }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * A question a child asked: the id of its mail and what it asks. A child paused on it keeps both in
3
+ * its thread, the text as its `ask_parent` call's input and the id in that call's output.
4
+ */
5
+ export interface QuestionRef {
6
+ readonly id: string
7
+ readonly text: string
8
+ }
9
+
10
+ /** A question a child of the turn asked. */
11
+ export interface ChildQuestion extends QuestionRef {
12
+ /** The child that asked it, waiting for the answer. */
13
+ readonly runId: string
14
+ }
15
+
16
+ /**
17
+ * What the Agent reads for its children's questions it has not seen yet, or, `earlier`, for the
18
+ * children of earlier turns paused on theirs. The children's text is escaped: it must not close the
19
+ * block or pass for one of Sixb's own.
20
+ */
21
+ export function renderChildQuestions(
22
+ questions: readonly (QuestionRef & { readonly key: string })[],
23
+ options: { readonly earlier?: boolean } = {}
24
+ ): string {
25
+ const [tag, lead] = options.earlier
26
+ ? [
27
+ "sixb_waiting_children",
28
+ "These sub-agents of earlier turns paused on a question. Once you have an answer, send it with message_agent and the key: the sub-agent continues where it stopped.",
29
+ ]
30
+ : [
31
+ "sixb_child_questions",
32
+ "Your sub-agents ask you, and wait for your answer. Answer each with message_agent and its key, or ask the user when only they can answer.",
33
+ ]
34
+ const lines = questions.map(
35
+ (question) => `- ${escapeText(question.key)} asks: ${escapeText(question.text)}`
36
+ )
37
+ return [`<${tag}>`, lead, ...lines, `</${tag}>`].join("\n")
38
+ }
39
+
40
+ function escapeText(value: string): string {
41
+ return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;")
42
+ }