@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,700 @@
1
+ import { createHash } from "node:crypto"
2
+ import { posix } from "node:path"
3
+ import {
4
+ AgentToolPublicError,
5
+ type ArtifactKind,
6
+ ArtifactRequestError,
7
+ AuthorizationError,
8
+ type JsonValue,
9
+ ObjectQueryExecutionError,
10
+ type Principal,
11
+ principalsEqual,
12
+ } from "@sixb/core"
13
+ import { ARTIFACT_KINDS, ARTIFACT_THEME_FILE, parseArtifactTheme } from "@sixb/core/artifacts"
14
+ import {
15
+ AgentExecutionLostError,
16
+ type AgentRunArtifacts,
17
+ type AgentRunFileStore,
18
+ } from "@sixb/core/internal/agents"
19
+ import { frameLayout, serializeArtifactQueryResult } from "@sixb/core/internal/artifacts/frames"
20
+ import {
21
+ ARTIFACT_LIMITS,
22
+ artifactQueryName,
23
+ isArtifactId,
24
+ type PublishedArtifact,
25
+ } from "@sixb/core/internal/artifacts/publish"
26
+ import { inferFileMediaType } from "@sixb/core/internal/blob-storage"
27
+ import type { JsonObject, ModelTool } from "@sixb/core/models"
28
+ import type { ArtifactFile, ArtifactRecord } from "@sixb/core/storage"
29
+ import { agentToolErrorText } from "../model-adapters"
30
+ import {
31
+ listSandboxFiles,
32
+ readSandboxFile,
33
+ resolveSandboxPath,
34
+ SandboxFileError,
35
+ } from "../sandbox-files"
36
+ import type { AgentSandboxHandle } from "../sandbox-handle"
37
+ import type { AgentFileBudget } from "../tools/tool-files"
38
+ import {
39
+ type CheckedQuery,
40
+ checkLayout,
41
+ type LayoutCheck,
42
+ type LayoutWarning,
43
+ } from "./layout-check/layout-check"
44
+ import {
45
+ type InstalledArtifacts,
46
+ type PublishedArtifactFile,
47
+ readArtifactVersionFiles,
48
+ } from "./materialize"
49
+
50
+ const CREATE_TOOL = "publish_artifact"
51
+ const VERSION_TOOL = "publish_artifact_version"
52
+ type PublishToolName = typeof CREATE_TOOL | typeof VERSION_TOOL
53
+ const SANDBOX_TIMEOUT_MS = 30_000
54
+ /** The kinds the Agent can create today; each lands with its validator, renderer, and skill. */
55
+ const PUBLISHABLE_KINDS = ARTIFACT_KINDS
56
+ type PublishableKind = ArtifactKind
57
+
58
+ // Creating and revising are two tools, and every argument of each is required and meaningful. A
59
+ // mode carried by an optional or null argument is where models differ: some fill every field, some
60
+ // send "null" or "" for nothing. Every model picks a tool by name. With all properties required
61
+ // and no length or pattern keywords, every model adapter can also send both schemas as strict.
62
+ const PATH_PROPERTY = {
63
+ type: "string",
64
+ description: "A file or a directory in the sandbox, relative to the working directory.",
65
+ } as const
66
+ const TITLE_PROPERTY = {
67
+ type: "string",
68
+ description: `Plain text of at most ${ARTIFACT_LIMITS.maxTitleLength} characters naming the deliverable.`,
69
+ } as const
70
+
71
+ export const PUBLISH_ARTIFACT_TOOL_SPEC = {
72
+ name: CREATE_TOOL,
73
+ description:
74
+ "Publish a new artifact from a file or directory in the sandbox: a deliverable the user opens beside the conversation. Read the sixb-artifacts skill before the first publish. To change an artifact you already published, use publish_artifact_version. Returns the artifact's id and version; a refusal says what to fix.",
75
+ inputSchema: {
76
+ type: "object",
77
+ properties: {
78
+ path: PATH_PROPERTY,
79
+ kind: { type: "string", enum: [...PUBLISHABLE_KINDS] },
80
+ title: TITLE_PROPERTY,
81
+ },
82
+ required: ["path", "kind", "title"],
83
+ additionalProperties: false,
84
+ } satisfies JsonObject,
85
+ } as const
86
+
87
+ export const PUBLISH_ARTIFACT_VERSION_TOOL_SPEC = {
88
+ name: VERSION_TOOL,
89
+ description:
90
+ "Publish the next version of an artifact you published, from a file or directory in the sandbox. It keeps its kind, and its earlier versions stay readable. $SIXB_ARTIFACTS lists this conversation's artifacts, each with its latest version under $SIXB_ARTIFACTS_DIR/<id>/. Returns the new version; a refusal says what to fix.",
91
+ inputSchema: {
92
+ type: "object",
93
+ properties: {
94
+ id: { type: "string", description: "The artifact's id, such as art_k3m9q2x7tp." },
95
+ path: PATH_PROPERTY,
96
+ title: TITLE_PROPERTY,
97
+ },
98
+ required: ["id", "path", "title"],
99
+ additionalProperties: false,
100
+ } satisfies JsonObject,
101
+ } as const
102
+
103
+ export interface PublishArtifactToolInput {
104
+ readonly path: string
105
+ readonly kind: PublishableKind
106
+ readonly title: string
107
+ }
108
+
109
+ export interface PublishArtifactVersionToolInput {
110
+ readonly id: string
111
+ readonly path: string
112
+ readonly title: string
113
+ }
114
+
115
+ interface PublishToolsInput {
116
+ /** The run's artifacts, through its session: what it reads as its requester, and publishes. */
117
+ readonly artifacts: AgentRunArtifacts
118
+ /** The conversation the run publishes into, and its owner, who owns what the Agent creates. */
119
+ readonly threadId: string
120
+ readonly owner: Principal
121
+ /** Where the version's files are stored before it is published. */
122
+ readonly blobStorage: AgentRunFileStore
123
+ /** Shared with every other file the run stores. */
124
+ readonly budget: AgentFileBudget
125
+ readonly resolveSandbox: () => Promise<AgentSandboxHandle>
126
+ /** The conversation's artifacts in the sandbox, which each publish keeps current. */
127
+ readonly installed: Promise<InstalledArtifacts>
128
+ }
129
+
130
+ /**
131
+ * `publish_artifact` and `publish_artifact_version`: each reads a file or a directory from the
132
+ * sandbox, stores its bytes, and publishes them through the run's session, which applies a run's
133
+ * rules (see `AgentRunArtifacts.publish`). The version exists when the tool returns, so the
134
+ * conversation shows it mid-turn and a cancelled run keeps it.
135
+ */
136
+ export function createPublishArtifactTools(
137
+ input: PublishToolsInput
138
+ ): readonly [ModelTool<PublishArtifactToolInput>, ModelTool<PublishArtifactVersionToolInput>] {
139
+ return [
140
+ {
141
+ ...PUBLISH_ARTIFACT_TOOL_SPEC,
142
+ parseInput: parsePublishArtifactInput,
143
+ execute: (request, { signal }) =>
144
+ publish(input, CREATE_TOOL, { ...request, target: { kind: request.kind } }, signal),
145
+ toModelOutput: (output) => ({ type: "text", value: publishSummary(output, CREATE_TOOL) }),
146
+ errorText: (error) => publishErrorText(error, CREATE_TOOL),
147
+ },
148
+ {
149
+ ...PUBLISH_ARTIFACT_VERSION_TOOL_SPEC,
150
+ parseInput: parsePublishArtifactVersionInput,
151
+ execute: (request, { signal }) =>
152
+ publish(input, VERSION_TOOL, { ...request, target: { artifactId: request.id } }, signal),
153
+ toModelOutput: (output) => ({ type: "text", value: publishSummary(output, VERSION_TOOL) }),
154
+ errorText: (error) => publishErrorText(error, VERSION_TOOL),
155
+ },
156
+ ]
157
+ }
158
+
159
+ /** A run that lost its conversation stores nothing, and the trace says so instead of "an error". */
160
+ function publishErrorText(error: unknown, tool: PublishToolName): string {
161
+ return error instanceof AgentExecutionLostError
162
+ ? publishError(tool, "this run no longer holds its conversation, so nothing was published")
163
+ .message
164
+ : agentToolErrorText(error)
165
+ }
166
+
167
+ interface PublishRequest {
168
+ readonly path: string
169
+ readonly title: string
170
+ /** A new artifact of this kind, or the next version of this artifact. */
171
+ readonly target: { readonly kind: PublishableKind } | { readonly artifactId: string }
172
+ }
173
+
174
+ async function publish(
175
+ input: PublishToolsInput,
176
+ tool: PublishToolName,
177
+ request: PublishRequest,
178
+ signal: AbortSignal
179
+ ): Promise<JsonValue> {
180
+ signal.throwIfAborted()
181
+ const kind: ArtifactKind =
182
+ "kind" in request.target
183
+ ? request.target.kind
184
+ : (await updatableArtifact(input, request.target.artifactId, tool)).kind
185
+ const handle = await input.resolveSandbox()
186
+ const sources = await listSources(handle, request.path, kind, tool, signal)
187
+
188
+ // A version of an installed artifact is made from its copy: publishing past the version the copy
189
+ // holds would drop whatever was published since.
190
+ const installed = await input.installed
191
+ const baseVersion =
192
+ "artifactId" in request.target ? installed.versionOf(request.target.artifactId) : undefined
193
+
194
+ const totalBytes = sources.reduce((sum, source) => sum + source.sizeBytes, 0)
195
+ if (totalBytes > ARTIFACT_LIMITS.maxVersionBytes) {
196
+ throw publishError(
197
+ tool,
198
+ `the files hold ${totalBytes} bytes; a version may hold at most ${ARTIFACT_LIMITS.maxVersionBytes}`
199
+ )
200
+ }
201
+ const reservation = input.budget.reserve(0, tool)
202
+ const contents: PublishedArtifactFile[] = []
203
+ let published: PublishedArtifact
204
+ try {
205
+ const files: ArtifactFile[] = []
206
+ for (const source of sources) {
207
+ const bytes =
208
+ source.bytes ??
209
+ (await readSandboxFile(handle, {
210
+ path: source.absolutePath,
211
+ maxBytes: ARTIFACT_LIMITS.maxFileBytes,
212
+ signal,
213
+ timeoutMs: SANDBOX_TIMEOUT_MS,
214
+ }).catch((error: unknown) => {
215
+ throw toPublishError(error, tool, source.path)
216
+ }))
217
+ if (bytes.byteLength !== source.sizeBytes) {
218
+ throw publishError(tool, `'${source.path}' changed while it was being read; publish again`)
219
+ }
220
+ // Blob storage keeps identical bytes once, so a file the run already stored, such as one a
221
+ // next version keeps, costs the budget nothing again.
222
+ reservation.addContent(createHash("sha256").update(bytes).digest("hex"), bytes.byteLength)
223
+ const fileName = posix.basename(source.path)
224
+ const fileRef = await input.blobStorage.put({
225
+ body: bytes,
226
+ expectedSizeBytes: bytes.byteLength,
227
+ signal,
228
+ fileName,
229
+ mediaType: inferFileMediaType(fileName, bytes),
230
+ })
231
+ files.push({ path: source.path, file: fileRef })
232
+ contents.push({ path: source.path, bytes })
233
+ }
234
+ signal.throwIfAborted()
235
+
236
+ published = await input.artifacts.publish({
237
+ ...("artifactId" in request.target
238
+ ? {
239
+ artifactId: request.target.artifactId,
240
+ ...(baseVersion === undefined ? {} : { baseVersion }),
241
+ }
242
+ : { kind }),
243
+ title: request.title,
244
+ files,
245
+ })
246
+ } catch (error) {
247
+ // Nothing was published, so the bytes do not count against the run.
248
+ reservation.release()
249
+
250
+ if (
251
+ error instanceof ArtifactRequestError &&
252
+ error.code === "artifact_moved" &&
253
+ "artifactId" in request.target &&
254
+ baseVersion !== undefined
255
+ ) {
256
+ throw await artifactMoved(
257
+ input,
258
+ { installed, handle },
259
+ { artifactId: request.target.artifactId, baseVersion },
260
+ signal
261
+ )
262
+ }
263
+
264
+ if (
265
+ error instanceof ArtifactRequestError &&
266
+ UNREACHABLE.has(error.code) &&
267
+ "artifactId" in request.target
268
+ ) {
269
+ throw noArtifact(tool, request.target.artifactId)
270
+ }
271
+
272
+ throw toPublishError(error, tool)
273
+ }
274
+
275
+ // The version exists by now: nothing below may read as a failed publish, which the Agent would
276
+ // publish again.
277
+ try {
278
+ // Revising from $SIXB_ARTIFACTS_DIR must start from this version, not the one before.
279
+ await installed.replace(handle.sandbox, published, contents, signal)
280
+ } catch (error) {
281
+ if (signal.aborted) throw error
282
+ console.warn(
283
+ `[SixbAgent] Could not install version ${published.version.version} of artifact '${published.artifact.id}':`,
284
+ error
285
+ )
286
+ }
287
+ // A published deck, page, or canvas is laid out in the sandbox's browser, so the Agent sees what
288
+ // the reader will, and fixes it in its next version.
289
+ const layout = frameLayout(kind)
290
+ const { outline, entry } = published.version
291
+ const root = layout ? sources.find((source) => source.path === entry) : undefined
292
+ const bytesOf = (path: string) => contents.find((file) => file.path === path)?.bytes
293
+ const themeFile = contents.find((file) => file.path === ARTIFACT_THEME_FILE)
294
+ // Publishing has read it already: a version with a theme.json it refused is not here.
295
+ const theme = themeFile ? parseArtifactTheme(new TextDecoder().decode(themeFile.bytes)) : null
296
+ // What the check opens: a canvas's boards, each at its own size, or the entry.
297
+ const pages =
298
+ outline.kind === "canvas"
299
+ ? {
300
+ layout: "canvas" as const,
301
+ boards: outline.items.flatMap((item) => {
302
+ const html = item.type === "board" ? bytesOf(item.file) : undefined
303
+ return item.type === "board" && html
304
+ ? [{ id: item.id, file: item.file, w: item.w, h: item.h, html }]
305
+ : []
306
+ }),
307
+ }
308
+ : layout && bytesOf(entry)
309
+ ? { layout, entry: bytesOf(entry) as Uint8Array }
310
+ : null
311
+ let check: LayoutCheck | undefined
312
+ let queries: CheckedQueries = { answers: {}, warnings: [] }
313
+ if (root && pages && (pages.layout !== "canvas" || pages.boards.length > 0)) {
314
+ queries = await checkedQueries(input.artifacts, published)
315
+ signal.throwIfAborted()
316
+ try {
317
+ check = await checkLayout({
318
+ handle,
319
+ ...pages,
320
+ directory: posix.dirname(root.absolutePath),
321
+ files: contents.map((file) => file.path),
322
+ name: `${published.artifact.id}-v${published.version.version}`,
323
+ ...(theme && "theme" in theme ? { theme: theme.theme } : {}),
324
+ queries: queries.answers,
325
+ signal,
326
+ })
327
+ } catch (error) {
328
+ if (signal.aborted) throw error
329
+ console.warn("[SixbAgent] The layout check failed:", error)
330
+ check = { status: "skipped", reason: "the check failed in the sandbox" }
331
+ }
332
+ }
333
+ return {
334
+ artifactId: published.artifact.id,
335
+ version: published.version.version,
336
+ kind: published.artifact.kind,
337
+ title: published.version.title,
338
+ warnings: [
339
+ ...published.warnings,
340
+ ...queries.warnings,
341
+ ...(check?.status === "checked" ? check.warnings : []),
342
+ ].map(({ code, message, part }) => ({
343
+ code,
344
+ message,
345
+ ...(part === undefined ? {} : { part }),
346
+ })),
347
+ ...(check === undefined
348
+ ? {}
349
+ : {
350
+ layoutCheck:
351
+ check.status === "checked"
352
+ ? { screenshots: [...check.screenshots] }
353
+ : { skipped: check.reason },
354
+ }),
355
+ }
356
+ }
357
+
358
+ interface CheckedQueries {
359
+ readonly answers: Readonly<Record<string, CheckedQuery>>
360
+ readonly warnings: readonly LayoutWarning[]
361
+ }
362
+
363
+ /**
364
+ * The version's queries, run as the requester, for the check to open the page with the rows a
365
+ * reader like them gets: each as the API serializes it, since the page reads that JSON in the app.
366
+ * Publishing checked each one as the requester, but what they may read can change before it runs,
367
+ * and running can fail where checking could not: such a query is a warning, as the version exists.
368
+ */
369
+ async function checkedQueries(
370
+ reader: Pick<AgentRunArtifacts, "query">,
371
+ published: PublishedArtifact
372
+ ): Promise<CheckedQueries> {
373
+ const { artifact, version } = published
374
+ const names = version.files.flatMap((file) => {
375
+ const name = artifactQueryName(file.path)
376
+ return name === undefined ? [] : [name]
377
+ })
378
+
379
+ const answers = await Promise.all(
380
+ names.map(async (name): Promise<readonly [string, CheckedQuery]> => {
381
+ try {
382
+ const result = await reader.query(artifact.id, name, { version: version.version })
383
+ if (!result) throw new Error(`[SixbAgent] Version ${version.version} is missing.`)
384
+
385
+ return [name, { result: serializeArtifactQueryResult(result) }]
386
+ } catch (error) {
387
+ return [name, { error: queryErrorText(error) }]
388
+ }
389
+ })
390
+ )
391
+
392
+ return {
393
+ answers: Object.fromEntries(answers),
394
+ warnings: answers.flatMap(([name, answer]) =>
395
+ "error" in answer
396
+ ? [
397
+ {
398
+ code: "query_failed",
399
+ message: `Query '${name}' failed when the check ran it as you: ${answer.error.replace(/^\[Sixb\] /, "")} The page was checked with sixb.query("${name}") rejecting, as it does for every reader it fails for.`,
400
+ },
401
+ ]
402
+ : []
403
+ ),
404
+ }
405
+ }
406
+
407
+ /** A refusal in the words the API gives a reader; anything else stays internal. */
408
+ function queryErrorText(error: unknown): string {
409
+ if (
410
+ error instanceof ArtifactRequestError ||
411
+ error instanceof AuthorizationError ||
412
+ error instanceof ObjectQueryExecutionError
413
+ ) {
414
+ return /[.!?]$/.test(error.message) ? error.message : `${error.message}.`
415
+ }
416
+
417
+ console.warn("[SixbAgent] A query of the published version did not run:", error)
418
+ return "[Sixb] The query could not be read."
419
+ }
420
+
421
+ /** How storing refuses an artifact the requester may not publish to: as if it did not exist. */
422
+ const UNREACHABLE: ReadonlySet<string> = new Set(["artifact_not_found", "not_shared", "read_only"])
423
+
424
+ /**
425
+ * The artifact to publish a version of: one the requester owns, or one this conversation shares
426
+ * that they take part in. Another is refused as if it did not exist, even one they could update
427
+ * from another conversation: publishing here would share it in this one.
428
+ */
429
+ async function updatableArtifact(
430
+ input: PublishToolsInput,
431
+ artifactId: string,
432
+ tool: PublishToolName
433
+ ): Promise<ArtifactRecord> {
434
+ const artifact = await input.artifacts.updatable(artifactId)
435
+ if (!artifact) throw noArtifact(tool, artifactId)
436
+ return artifact
437
+ }
438
+
439
+ function noArtifact(tool: PublishToolName, artifactId: string): AgentToolPublicError {
440
+ return publishError(
441
+ tool,
442
+ `there is no artifact '${artifactId}'. $SIXB_ARTIFACTS lists this conversation's artifacts; to create a new one, call ${CREATE_TOOL}`
443
+ )
444
+ }
445
+
446
+ /**
447
+ * The refusal for a version made from a copy the artifact has moved past, such as a person saving
448
+ * in the app while the run works. The version it moved to replaces the copy, so the Agent starts
449
+ * again from it instead of publishing over it.
450
+ */
451
+ async function artifactMoved(
452
+ input: PublishToolsInput,
453
+ {
454
+ installed,
455
+ handle,
456
+ }: { readonly installed: InstalledArtifacts; readonly handle: AgentSandboxHandle },
457
+ { artifactId, baseVersion }: { readonly artifactId: string; readonly baseVersion: number },
458
+ signal: AbortSignal
459
+ ): Promise<AgentToolPublicError> {
460
+ // Read as the requester: whatever moved it, it is a version they can read.
461
+ const artifact = await updatableArtifact(input, artifactId, VERSION_TOOL)
462
+ const latest = await input.artifacts.getVersion(artifactId, artifact.latestVersion)
463
+ if (!latest) {
464
+ throw new Error(`[SixbAgent] Version ${artifact.latestVersion} of '${artifactId}' is missing.`)
465
+ }
466
+
467
+ const author = principalsEqual(latest.author, input.owner)
468
+ ? "its owner"
469
+ : `${latest.author.type} '${latest.author.id}'`
470
+ const where =
471
+ latest.origin === undefined
472
+ ? `by ${author} outside a conversation, such as in the app`
473
+ : latest.origin.threadId === input.threadId
474
+ ? "earlier in this conversation"
475
+ : `by ${author} in another conversation`
476
+ const moved = `artifact '${artifactId}' moved on from version ${baseVersion}, which you started from: version ${latest.version} was published ${where}, so nothing was published`
477
+
478
+ try {
479
+ const files = await readArtifactVersionFiles(input.blobStorage, latest, signal)
480
+ await installed.replace(handle.sandbox, { artifact, version: latest }, files, signal, {
481
+ edited: latest.origin?.threadId !== input.threadId,
482
+ })
483
+ } catch (error) {
484
+ if (signal.aborted) throw error
485
+ console.warn(
486
+ `[SixbAgent] Could not install version ${latest.version} of artifact '${artifactId}':`,
487
+ error
488
+ )
489
+ return publishError(
490
+ VERSION_TOOL,
491
+ `${moved}. Version ${latest.version} could not be installed in the sandbox, so tell the user you could not build on it`
492
+ )
493
+ }
494
+
495
+ return publishError(
496
+ VERSION_TOOL,
497
+ `${moved}. $SIXB_ARTIFACTS lists version ${latest.version}, installed under $SIXB_ARTIFACTS_DIR/${artifactId}/: start again from it as it is, keep its changes, make yours again, and publish`
498
+ )
499
+ }
500
+
501
+ interface PublishSource {
502
+ /** The file's path in the artifact. */
503
+ readonly path: string
504
+ readonly absolutePath: string
505
+ readonly sizeBytes: number
506
+ /** Already read: a single file is read once, while the path is checked. */
507
+ readonly bytes?: Uint8Array
508
+ }
509
+
510
+ /**
511
+ * A directory publishes every file under it at its relative path, skipping names that start with
512
+ * a dot. A single file publishes alone: a document's Markdown as `document.md`, any other file
513
+ * under its own name.
514
+ */
515
+ async function listSources(
516
+ handle: AgentSandboxHandle,
517
+ path: string,
518
+ kind: ArtifactKind,
519
+ tool: PublishToolName,
520
+ signal: AbortSignal
521
+ ): Promise<PublishSource[]> {
522
+ let absolutePath: string
523
+ try {
524
+ absolutePath = resolveSandboxPath(handle, path)
525
+ } catch (error) {
526
+ throw toPublishError(error, tool)
527
+ }
528
+ const listing = await listSandboxFiles(handle, {
529
+ directory: absolutePath,
530
+ maxFiles: ARTIFACT_LIMITS.maxFiles * 2,
531
+ signal,
532
+ timeoutMs: SANDBOX_TIMEOUT_MS,
533
+ }).catch((error: unknown) => {
534
+ throw toPublishError(error, tool)
535
+ })
536
+
537
+ if (listing.files.length === 0 && !listing.truncated) {
538
+ if (listing.directory) throw publishError(tool, `'${path}' is an empty directory`)
539
+ // A missing path lists nothing as well; reading it says which.
540
+ const bytes = await readSandboxFile(handle, {
541
+ path: absolutePath,
542
+ maxBytes: ARTIFACT_LIMITS.maxFileBytes,
543
+ signal,
544
+ timeoutMs: SANDBOX_TIMEOUT_MS,
545
+ }).catch((error: unknown) => {
546
+ throw toPublishError(error, tool, path)
547
+ })
548
+ return [
549
+ {
550
+ path: kind === "document" ? "document.md" : posix.basename(absolutePath),
551
+ absolutePath,
552
+ sizeBytes: bytes.byteLength,
553
+ bytes,
554
+ },
555
+ ]
556
+ }
557
+
558
+ const files = listing.files.filter(
559
+ (file) => !file.relativePath.split("/").some((segment) => segment.startsWith("."))
560
+ )
561
+ if (listing.truncated || files.length > ARTIFACT_LIMITS.maxFiles) {
562
+ throw publishError(
563
+ tool,
564
+ `'${path}' holds more than ${ARTIFACT_LIMITS.maxFiles} files; a version may hold at most ${ARTIFACT_LIMITS.maxFiles}`
565
+ )
566
+ }
567
+ if (files.length === 0) throw publishError(tool, `'${path}' holds no files to publish`)
568
+ for (const file of files) {
569
+ if (file.sizeBytes > ARTIFACT_LIMITS.maxFileBytes) {
570
+ throw publishError(
571
+ tool,
572
+ `'${file.relativePath}' is ${file.sizeBytes} bytes; a file may be at most ${ARTIFACT_LIMITS.maxFileBytes}`
573
+ )
574
+ }
575
+ }
576
+ return files.map((file) => ({
577
+ path: file.relativePath,
578
+ absolutePath: posix.join(absolutePath, file.relativePath),
579
+ sizeBytes: file.sizeBytes,
580
+ }))
581
+ }
582
+
583
+ function publishSummary(output: JsonValue, tool: PublishToolName): string {
584
+ if (typeof output !== "object" || output === null || Array.isArray(output)) {
585
+ return JSON.stringify(output)
586
+ }
587
+ const lines = [
588
+ `Published "${String(output.title)}" as artifact ${String(output.artifactId)}, version ${String(output.version)}.`,
589
+ ]
590
+ if (tool === CREATE_TOOL) {
591
+ lines.push(`To change it, publish its next version with ${VERSION_TOOL} and this id.`)
592
+ }
593
+ const warnings = Array.isArray(output.warnings) ? output.warnings : []
594
+ for (const warning of warnings) {
595
+ if (typeof warning === "object" && warning !== null && !Array.isArray(warning)) {
596
+ lines.push(
597
+ `Warning${warning.part ? ` (${String(warning.part)})` : ""}: ${String(warning.message)}`
598
+ )
599
+ }
600
+ }
601
+ const check = output.layoutCheck
602
+ if (typeof check === "object" && check !== null && !Array.isArray(check)) {
603
+ const screenshots = Array.isArray(check.screenshots) ? check.screenshots.map(String) : []
604
+ const kind = output.kind
605
+ if (typeof check.skipped === "string") {
606
+ lines.push(
607
+ `The layout check did not run: ${check.skipped}. ${
608
+ kind === "page"
609
+ ? "Read index.html and its scripts closely."
610
+ : kind === "canvas"
611
+ ? "Read each board's HTML closely."
612
+ : "Read index.html slide by slide."
613
+ }`
614
+ )
615
+ } else if (screenshots.length > 0) {
616
+ const directory = posix.dirname(screenshots[0] ?? "")
617
+ lines.push(
618
+ kind === "page"
619
+ ? `Layout check: the page as the reader sees it, in light mode or the mode its theme.json pins, is ${directory}/desktop.png at 1280px and ${directory}/phone.png at 390px, each its top 4000px. Open them with view_file, fix what the warnings name, and publish the next version.`
620
+ : kind === "canvas"
621
+ ? `Layout check: each board as the reader sees it, at its own size, in light mode or the mode its theme.json pins, is ${directory}/<id>.png (${screenshots.length} boards). Open them with view_file, fix what the warnings name, and publish the next version.`
622
+ : `Layout check: each slide as the reader sees it, in light mode or the mode its theme.json pins, is ${directory}/slide-NN.png (${screenshots.length} slides). Open them with view_file, fix what the warnings name, and publish the next version.`
623
+ )
624
+ }
625
+ }
626
+ return lines.join("\n")
627
+ }
628
+
629
+ function parsePublishArtifactInput(value: unknown): PublishArtifactToolInput {
630
+ const input = inputObject(value, CREATE_TOOL, ["path", "kind", "title"])
631
+ if (!PUBLISHABLE_KINDS.includes(input.kind as PublishableKind)) {
632
+ throw publishError(CREATE_TOOL, `kind must be one of ${PUBLISHABLE_KINDS.join(", ")}`)
633
+ }
634
+ return {
635
+ path: pathInput(input.path, CREATE_TOOL),
636
+ kind: input.kind as PublishableKind,
637
+ title: titleInput(input.title, CREATE_TOOL),
638
+ }
639
+ }
640
+
641
+ function parsePublishArtifactVersionInput(value: unknown): PublishArtifactVersionToolInput {
642
+ const input = inputObject(value, VERSION_TOOL, ["id", "path", "title"])
643
+ const id = typeof input.id === "string" ? input.id.trim() : ""
644
+ if (!isArtifactId(id)) {
645
+ throw publishError(
646
+ VERSION_TOOL,
647
+ `id must be an artifact id such as art_k3m9q2x7tp. $SIXB_ARTIFACTS lists this conversation's artifacts; to create a new one, call ${CREATE_TOOL}`
648
+ )
649
+ }
650
+ return {
651
+ id,
652
+ path: pathInput(input.path, VERSION_TOOL),
653
+ title: titleInput(input.title, VERSION_TOOL),
654
+ }
655
+ }
656
+
657
+ function inputObject(
658
+ value: unknown,
659
+ tool: PublishToolName,
660
+ keys: readonly string[]
661
+ ): Record<string, unknown> {
662
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
663
+ throw publishError(tool, "input must be an object")
664
+ }
665
+ const input = value as Record<string, unknown>
666
+ const unknownKey = Object.keys(input).find((key) => !keys.includes(key))
667
+ if (unknownKey) throw publishError(tool, `input has an unknown property '${unknownKey}'`)
668
+ return input
669
+ }
670
+
671
+ function pathInput(value: unknown, tool: PublishToolName): string {
672
+ if (typeof value !== "string" || value.trim().length === 0) {
673
+ throw publishError(tool, "path must be a file or directory in the sandbox")
674
+ }
675
+ return value
676
+ }
677
+
678
+ function titleInput(value: unknown, tool: PublishToolName): string {
679
+ if (typeof value !== "string") throw publishError(tool, "title must be text")
680
+ return value
681
+ }
682
+
683
+ /** Refusals the Agent can act on become its error text; anything else stays internal. */
684
+ function toPublishError(error: unknown, tool: PublishToolName, path?: string): unknown {
685
+ if (error instanceof SandboxFileError) {
686
+ if (error.reason === "not_found" && path !== undefined) {
687
+ return publishError(tool, `there is no file or directory at '${path}'`)
688
+ }
689
+ return publishError(tool, path === undefined ? error.message : `'${path}': ${error.message}`)
690
+ }
691
+ if (error instanceof ArtifactRequestError) {
692
+ return publishError(tool, error.message.replace(/^\[Sixb\] /, ""))
693
+ }
694
+ return error
695
+ }
696
+
697
+ function publishError(tool: PublishToolName, message: string): AgentToolPublicError {
698
+ const sentence = /[.!?]$/.test(message) ? message : `${message}.`
699
+ return new AgentToolPublicError(`[SixbAgent] ${tool} refused: ${sentence}`)
700
+ }