@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,380 @@
1
+ import { posix } from "node:path"
2
+ import type { Sandbox, SandboxFileRecord } from "@sixb/core"
3
+ import { formatArtifactAddress } from "@sixb/core/artifacts"
4
+ import type { AgentRunArtifacts, AgentRunFileStore } from "@sixb/core/internal/agents"
5
+ import type { ArtifactOutline, ArtifactRecord, ArtifactVersionRecord } from "@sixb/core/storage"
6
+ import { NEVER_ABORTED_SIGNAL, waitForAbort } from "../abort"
7
+
8
+ /** How many of the thread's artifacts are installed, newest first, and how many bytes in all. */
9
+ const MATERIALIZE_MAX_ARTIFACTS = 50
10
+ const MATERIALIZE_MAX_BYTES = 50 * 1024 * 1024
11
+ const REMOVE_TIMEOUT_MS = 30_000
12
+
13
+ export interface MaterializedArtifacts {
14
+ /** Files to write, at paths relative to the sandbox working directory or absolute. */
15
+ readonly files: readonly SandboxFileRecord[]
16
+ readonly manifestJson: string
17
+ }
18
+
19
+ /** One file of a version just published, with the bytes it holds. */
20
+ export interface PublishedArtifactFile {
21
+ readonly path: string
22
+ readonly bytes: Uint8Array
23
+ }
24
+
25
+ interface ManifestEntry {
26
+ readonly id: string
27
+ readonly kind: string
28
+ readonly title: string
29
+ readonly version: number
30
+ /** The artifact's address: an artifact that shows it follows its latest version. */
31
+ readonly address: string
32
+ /** The same at this version, which never changes: a reply shows what its words describe. */
33
+ readonly pinned: string
34
+ /**
35
+ * Addresses of its parts: a document's sections, a sheet's sheets and charts, a deck's slides, a
36
+ * canvas's boards and sections.
37
+ */
38
+ readonly parts?: readonly {
39
+ readonly address: string
40
+ readonly pinned: string
41
+ readonly name: string
42
+ }[]
43
+ /** Where the version's files are, as the agent names it; absent when not installed. */
44
+ readonly directory?: string
45
+ readonly files: readonly string[]
46
+ /**
47
+ * The latest version was published outside this conversation: a person's edit in the app,
48
+ * another conversation, or the project's code. The next version starts from it and keeps its
49
+ * changes.
50
+ */
51
+ readonly edited?: true
52
+ }
53
+
54
+ /**
55
+ * The conversation's artifacts as the run's sandbox holds them: the latest version of each under
56
+ * `<directory>/<id>/`, listed in the manifest, newest first. A publish replaces its artifact's copy
57
+ * and entry, so both stay the latest version for the rest of the run: revising from the copy never
58
+ * starts from the version before. A publish refused because the artifact moved on installs the
59
+ * version it moved to.
60
+ */
61
+ export class InstalledArtifacts implements MaterializedArtifacts {
62
+ #entries: readonly ManifestEntry[]
63
+ /** The installed copies' sizes, by artifact id. */
64
+ readonly #installed: Map<string, number>
65
+ #updates: Promise<void> = Promise.resolve()
66
+
67
+ constructor(
68
+ private readonly layout: {
69
+ /** As the agent names it, like the manifest. */
70
+ readonly directory: string
71
+ readonly manifestPath: string
72
+ readonly maxBytes: number
73
+ },
74
+ entries: readonly ManifestEntry[],
75
+ installed: Map<string, number>,
76
+ readonly files: readonly SandboxFileRecord[]
77
+ ) {
78
+ this.#entries = entries
79
+ this.#installed = installed
80
+ }
81
+
82
+ get manifestJson(): string {
83
+ return JSON.stringify({ artifacts: this.#entries }, null, 2)
84
+ }
85
+
86
+ /** The version the manifest lists for an artifact: the one its copy holds. */
87
+ versionOf(artifactId: string): number | undefined {
88
+ return this.#entries.find((entry) => entry.id === artifactId)?.version
89
+ }
90
+
91
+ /**
92
+ * Install the version just published in place of the artifact's copy, and list it first. One
93
+ * update runs at a time, so parallel publishes never write an older manifest over a newer one.
94
+ */
95
+ replace(
96
+ sandbox: Sandbox,
97
+ published: { readonly artifact: ArtifactRecord; readonly version: ArtifactVersionRecord },
98
+ files: readonly PublishedArtifactFile[],
99
+ signal: AbortSignal,
100
+ options: { readonly edited?: boolean } = {}
101
+ ): Promise<void> {
102
+ const update = this.#updates.then(() =>
103
+ this.#replace(sandbox, published, files, signal, options)
104
+ )
105
+ this.#updates = update.catch(() => {})
106
+ return update
107
+ }
108
+
109
+ async #replace(
110
+ sandbox: Sandbox,
111
+ {
112
+ artifact,
113
+ version,
114
+ }: { readonly artifact: ArtifactRecord; readonly version: ArtifactVersionRecord },
115
+ files: readonly PublishedArtifactFile[],
116
+ signal: AbortSignal,
117
+ options: { readonly edited?: boolean }
118
+ ): Promise<void> {
119
+ const { directory: root, manifestPath, maxBytes } = this.layout
120
+ const directory = posix.join(root, artifact.id)
121
+ const inSandbox = (path: string) => posix.resolve(sandbox.workingDirectory, path)
122
+ const sizeBytes = files.reduce((sum, file) => sum + file.bytes.byteLength, 0)
123
+ let othersBytes = 0
124
+ for (const [id, bytes] of this.#installed) if (id !== artifact.id) othersBytes += bytes
125
+ const install = othersBytes + sizeBytes <= maxBytes
126
+
127
+ // A version's directory holds exactly that version: files an older one had must not linger.
128
+ const removed = await sandbox.runCommand("bash", ["-c", 'rm -rf -- "$SIXB_ARTIFACT_COPY"'], {
129
+ env: { SIXB_ARTIFACT_COPY: inSandbox(directory) },
130
+ timeout: REMOVE_TIMEOUT_MS,
131
+ signal,
132
+ })
133
+ if (removed.exitCode !== 0 || removed.timedOut) {
134
+ throw new Error(
135
+ `[SixbAgent] Could not remove ${directory}: ${removed.stderr.trim() || `exit ${removed.exitCode}`}`
136
+ )
137
+ }
138
+ if (install) this.#installed.set(artifact.id, sizeBytes)
139
+ else this.#installed.delete(artifact.id)
140
+ this.#entries = [
141
+ manifestEntry(artifact, version, install ? directory : undefined, options),
142
+ ...this.#entries.filter((entry) => entry.id !== artifact.id),
143
+ ]
144
+ await sandbox.writeFiles([
145
+ ...(install
146
+ ? files.map((file) => ({
147
+ path: inSandbox(posix.join(directory, file.path)),
148
+ contents: file.bytes,
149
+ }))
150
+ : []),
151
+ { path: inSandbox(manifestPath), contents: this.manifestJson },
152
+ ])
153
+ }
154
+ }
155
+
156
+ /** What a turn reads of its conversation's artifacts, as its requester, through its session. */
157
+ export type TurnArtifacts = Pick<AgentRunArtifacts, "getVersion" | "list" | "listVersions">
158
+
159
+ /**
160
+ * The latest version of each artifact the conversation shares, installed under `<directory>/<id>/`
161
+ * and listed in a manifest, so the Agent edits what was published rather than whatever an older
162
+ * workspace still holds. Read as the turn's requester, it holds nothing they cannot read. Newest
163
+ * first; artifacts past the byte budget, or whose files cannot be read, are listed without their
164
+ * files.
165
+ */
166
+ export async function materializeThreadArtifacts(input: {
167
+ /** The conversation's thread, whose artifacts a copy published elsewhere is edited from. */
168
+ readonly threadId: string
169
+ readonly artifacts: TurnArtifacts
170
+ readonly blobStorage: AgentRunFileStore
171
+ /** As the agent names it: relative to the working directory, or absolute. */
172
+ readonly directory: string
173
+ /** Where the manifest is written, named the same way. */
174
+ readonly manifestPath: string
175
+ /** A cancelled run stops downloading. */
176
+ readonly signal?: AbortSignal
177
+ /** Test seam; production installs up to 50 MB. */
178
+ readonly maxBytes?: number
179
+ }): Promise<InstalledArtifacts> {
180
+ const signal = input.signal ?? NEVER_ABORTED_SIGNAL
181
+ const maxBytes = input.maxBytes ?? MATERIALIZE_MAX_BYTES
182
+ const entries: ManifestEntry[] = []
183
+ const files: SandboxFileRecord[] = []
184
+ const installed = new Map<string, number>()
185
+ const artifacts = await input.artifacts.list({ limit: MATERIALIZE_MAX_ARTIFACTS })
186
+ let installedBytes = 0
187
+ for (const artifact of artifacts) {
188
+ signal.throwIfAborted()
189
+ const version = await input.artifacts.getVersion(artifact.id, artifact.latestVersion)
190
+ if (!version) continue
191
+ const sizeBytes = version.files.reduce((sum, file) => sum + file.file.sizeBytes, 0)
192
+ const directory = posix.join(input.directory, artifact.id)
193
+ let install = installedBytes + sizeBytes <= maxBytes
194
+ if (install) {
195
+ try {
196
+ const copy: SandboxFileRecord[] = []
197
+ for (const file of version.files) {
198
+ copy.push({
199
+ path: posix.join(directory, file.path),
200
+ contents: await readBlob(input.blobStorage, file.file.blobId, signal),
201
+ })
202
+ }
203
+ files.push(...copy)
204
+ installedBytes += sizeBytes
205
+ installed.set(artifact.id, sizeBytes)
206
+ } catch (error) {
207
+ signal.throwIfAborted()
208
+ // One unreadable blob must not cost every later run of the thread its sandbox.
209
+ console.warn(
210
+ `[SixbAgent] Could not install version ${version.version} of artifact '${artifact.id}':`,
211
+ error
212
+ )
213
+ install = false
214
+ }
215
+ }
216
+ entries.push(
217
+ manifestEntry(artifact, version, install ? directory : undefined, {
218
+ edited: version.origin?.threadId !== input.threadId,
219
+ })
220
+ )
221
+ }
222
+ return new InstalledArtifacts(
223
+ { directory: input.directory, manifestPath: input.manifestPath, maxBytes },
224
+ entries,
225
+ installed,
226
+ files
227
+ )
228
+ }
229
+
230
+ /**
231
+ * Install the latest version of each thread artifact one of `runIds` published a version of, in
232
+ * place of the copy the run holds: a parent turn sees what its children published like its own,
233
+ * whoever published since. One that cannot be installed does not stop the others; the error at the
234
+ * end names each.
235
+ */
236
+ export async function installArtifactsPublishedBy(input: {
237
+ readonly installed: InstalledArtifacts
238
+ readonly artifacts: TurnArtifacts
239
+ readonly blobStorage: AgentRunFileStore
240
+ readonly sandbox: Sandbox
241
+ readonly runIds: readonly string[]
242
+ readonly signal: AbortSignal
243
+ }): Promise<void> {
244
+ const runIds = new Set(input.runIds)
245
+ const artifacts = await input.artifacts.list({ limit: MATERIALIZE_MAX_ARTIFACTS })
246
+
247
+ const failed: string[] = []
248
+ // Oldest first: each install lists its artifact first, so the newest ends up first.
249
+ for (const artifact of [...artifacts].reverse()) {
250
+ input.signal.throwIfAborted()
251
+ if (input.installed.versionOf(artifact.id) === artifact.latestVersion) continue
252
+
253
+ try {
254
+ const versions = await input.artifacts.listVersions(artifact.id, {
255
+ limit: artifact.latestVersion,
256
+ })
257
+ const published = versions?.versions.some(
258
+ (version) => version.origin !== undefined && runIds.has(version.origin.runId)
259
+ )
260
+ if (!published) continue
261
+
262
+ const version = await input.artifacts.getVersion(artifact.id, artifact.latestVersion)
263
+ if (!version) continue
264
+ const files = await readArtifactVersionFiles(input.blobStorage, version, input.signal)
265
+ await input.installed.replace(input.sandbox, { artifact, version }, files, input.signal)
266
+ } catch (error) {
267
+ input.signal.throwIfAborted()
268
+ console.warn(`[SixbAgent] Could not install artifact '${artifact.id}':`, error)
269
+ failed.push(artifact.id)
270
+ }
271
+ }
272
+ if (failed.length > 0) {
273
+ throw new Error(`[SixbAgent] Could not install artifacts ${failed.join(", ")}.`)
274
+ }
275
+ }
276
+
277
+ function manifestEntry(
278
+ artifact: Pick<ArtifactRecord, "id" | "kind">,
279
+ version: ArtifactVersionRecord,
280
+ directory: string | undefined,
281
+ { edited = false }: { readonly edited?: boolean } = {}
282
+ ): ManifestEntry {
283
+ return {
284
+ id: artifact.id,
285
+ kind: artifact.kind,
286
+ title: version.title,
287
+ version: version.version,
288
+ address: formatArtifactAddress({ artifactId: artifact.id }),
289
+ pinned: formatArtifactAddress({ artifactId: artifact.id, version: version.version }),
290
+ ...partsOf(artifact.id, version.version, version.outline),
291
+ ...(directory === undefined ? {} : { directory }),
292
+ files: version.files.map((file) => file.path),
293
+ ...(edited ? { edited: true as const } : {}),
294
+ }
295
+ }
296
+
297
+ /**
298
+ * The parts an address can name, each with its address written out, so the Agent copies an
299
+ * address instead of working out a heading's slug.
300
+ */
301
+ function partsOf(
302
+ artifactId: string,
303
+ version: number,
304
+ outline: ArtifactOutline
305
+ ): { readonly parts?: ManifestEntry["parts"] } {
306
+ const part = (name: string, label: string) => ({
307
+ address: formatArtifactAddress({ artifactId, part: name }),
308
+ pinned: formatArtifactAddress({ artifactId, version, part: name }),
309
+ name: label,
310
+ })
311
+ const parts =
312
+ outline.kind === "document"
313
+ ? outline.headings
314
+ .filter((heading) => heading.depth <= 3)
315
+ .map((heading) => part(heading.slug, heading.text))
316
+ : outline.kind === "sheet"
317
+ ? [
318
+ ...outline.sheets.map((sheet) =>
319
+ part(
320
+ sheet.name,
321
+ // A live sheet's rows are each reader's, read by its query: it has no count.
322
+ `Sheet ${sheet.name}: ${sheet.query === undefined ? `${sheet.rows} rows` : `live rows of query ${sheet.query}`}; columns ${sheet.columns.join(", ")}`
323
+ )
324
+ ),
325
+ ...outline.charts.map((chart) => part(`chart=${chart}`, `Chart ${chart}`)),
326
+ ]
327
+ : outline.kind === "slides"
328
+ ? outline.slides.map((slide, index) =>
329
+ part(String(index + 1), `Slide ${index + 1}${slide.title ? `: ${slide.title}` : ""}`)
330
+ )
331
+ : outline.kind === "canvas"
332
+ ? outline.items.map((item) =>
333
+ part(
334
+ item.id,
335
+ `${item.type === "board" ? "Board" : "Section"} ${item.id}${item.title ? `: ${item.title}` : ""}`
336
+ )
337
+ )
338
+ : []
339
+ return parts.length > 0 ? { parts } : {}
340
+ }
341
+
342
+ /** A version's files with the bytes each holds. Reading stops when the run is cancelled. */
343
+ export async function readArtifactVersionFiles(
344
+ blobStorage: AgentRunFileStore,
345
+ version: ArtifactVersionRecord,
346
+ signal: AbortSignal
347
+ ): Promise<PublishedArtifactFile[]> {
348
+ const files: PublishedArtifactFile[] = []
349
+
350
+ for (const file of version.files) {
351
+ files.push({ path: file.path, bytes: await readBlob(blobStorage, file.file.blobId, signal) })
352
+ }
353
+
354
+ return files
355
+ }
356
+
357
+ /** A blob's bytes. Reading stops when the run is cancelled. */
358
+ export async function readBlob(
359
+ blobStorage: AgentRunFileStore,
360
+ blobId: string,
361
+ signal: AbortSignal
362
+ ): Promise<Uint8Array> {
363
+ const reader = (await waitForAbort(blobStorage.open(blobId), signal)).getReader()
364
+ const cancel = () => void reader.cancel(signal.reason).catch(() => {})
365
+ signal.addEventListener("abort", cancel, { once: true })
366
+ // A cancel between the open and the listener fires no event.
367
+ if (signal.aborted) cancel()
368
+ try {
369
+ const chunks: Uint8Array[] = []
370
+ for (;;) {
371
+ const { done, value } = await reader.read()
372
+ signal.throwIfAborted()
373
+ if (done) return Buffer.concat(chunks)
374
+ chunks.push(value)
375
+ }
376
+ } finally {
377
+ signal.removeEventListener("abort", cancel)
378
+ reader.releaseLock()
379
+ }
380
+ }