@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,351 @@
1
+ import type { FileRef, JsonValue } from "@sixb/core"
2
+ import type {
3
+ AgentRunFileStore,
4
+ PrepareModelStepInput,
5
+ PrepareModelStepResult,
6
+ } from "@sixb/core/internal/agents"
7
+ import { agentMessageSteps, isAgentToolResult } from "@sixb/core/internal/agents"
8
+ import type { ModelFilePart, ModelMessage, ModelTextPart } from "@sixb/core/models"
9
+ import type { AgentMessageRecord } from "@sixb/core/storage"
10
+ import {
11
+ type AttachmentImageOutcome,
12
+ type AttachmentImageProjection,
13
+ attachmentKey,
14
+ modelSupportsInlineImages,
15
+ type PendingAttachmentImage,
16
+ type PreparedAgentAttachmentContext,
17
+ prepareAgentToolFileProjection,
18
+ settleAttachmentImages,
19
+ } from "../attachments"
20
+ import { fileContentKey } from "../file-ref"
21
+ import { type InlineImageBudget, projectInOrder } from "../inline-images"
22
+ import { type AgentToolModelOutput, agentToolResultToModelOutput } from "./result-output"
23
+
24
+ const TOOL_RESULT_IMAGE_OMISSION_NOTE =
25
+ "[Image is not embedded in the tool-result message; Sixb supplies it as a separate model input when the selected model supports images.]"
26
+
27
+ /** Whether the images a tool's results return reach the model after its step. */
28
+ export type SuppliesToolFiles = (toolName: string) => boolean
29
+
30
+ /** An image a step's tool returned, not projected yet. */
31
+ interface ToolFileCandidate {
32
+ readonly toolCallId: string
33
+ readonly fileRef: FileRef
34
+ }
35
+
36
+ /** One tool call's durable result, as the step that ran it produced it. */
37
+ interface StepToolResult {
38
+ readonly toolCallId: string
39
+ readonly toolName: string
40
+ readonly output: JsonValue | undefined
41
+ }
42
+
43
+ interface ToolFileProjectionInput {
44
+ readonly blobStorage: AgentRunFileStore
45
+ readonly signal: AbortSignal
46
+ /** Test seam; production uses the bounded attachment projector. */
47
+ readonly projectFile?: typeof prepareAgentToolFileProjection
48
+ }
49
+
50
+ /** What became of a step's image: inline, left out by the budget, or no image to project. */
51
+ type ToolFileDecision =
52
+ | { readonly kind: "inline"; readonly toolCallId: string; readonly file: ModelFilePart }
53
+ | { readonly kind: "budget"; readonly toolCallId: string; readonly name: string }
54
+ | { readonly kind: "none" }
55
+
56
+ /**
57
+ * Move tool-created images into a user message after their step without changing their durable
58
+ * result. The message is derived from the step's results alone, so a later turn derives the same
59
+ * one from the stored trace ({@link replayToolFiles}) and its request keeps the prefix. Its images
60
+ * take what the request's inline image budget has left, after the history's.
61
+ */
62
+ export class AgentToolResultMediaBridge {
63
+ constructor(
64
+ private readonly input: Omit<ToolFileProjectionInput, "signal"> & {
65
+ readonly suppliesToolFiles: SuppliesToolFiles
66
+ readonly inlineImages: InlineImageBudget
67
+ readonly sandboxPathForFileRef?: (
68
+ fileRef: FileRef
69
+ ) => string | undefined | Promise<string | undefined>
70
+ }
71
+ ) {}
72
+
73
+ async toModelOutput(input: {
74
+ readonly output: JsonValue
75
+ readonly signal: AbortSignal
76
+ }): Promise<AgentToolModelOutput> {
77
+ input.signal.throwIfAborted()
78
+ return agentToolResultToModelOutput({
79
+ output: input.output,
80
+ blobStorage: this.input.blobStorage,
81
+ signal: input.signal,
82
+ ...(this.input.sandboxPathForFileRef === undefined
83
+ ? {}
84
+ : { sandboxPathForFileRef: this.input.sandboxPathForFileRef }),
85
+ imageOmissionNote: TOOL_RESULT_IMAGE_OMISSION_NOTE,
86
+ })
87
+ }
88
+
89
+ readonly prepareStep = async ({
90
+ stepIndex,
91
+ messages,
92
+ model,
93
+ signal,
94
+ }: PrepareModelStepInput): Promise<PrepareModelStepResult | undefined> => {
95
+ // Only after a step this loop ran: a replayed history holds its own steps' messages already,
96
+ // and a retried request keeps the one it added.
97
+ const results = messages.at(-1)
98
+ if (stepIndex === 0 || results?.role !== "tool" || !modelSupportsInlineImages(model)) {
99
+ return undefined
100
+ }
101
+
102
+ signal.throwIfAborted()
103
+ const candidates = toolFileCandidates(
104
+ results.content.map((part) => ({
105
+ toolCallId: part.toolCallId,
106
+ toolName: part.toolName,
107
+ output:
108
+ part.originalOutput ??
109
+ (part.output.type === "text" || part.output.type === "json"
110
+ ? part.output.value
111
+ : undefined),
112
+ })),
113
+ this.input.suppliesToolFiles
114
+ )
115
+
116
+ const decisions: ToolFileDecision[] = []
117
+ await projectInOrder({
118
+ items: candidates,
119
+ budget: this.input.inlineImages,
120
+ project: (candidate) => projectToolFile(candidate, { ...this.input, signal }),
121
+ decide: (candidate, file) =>
122
+ decisions.push(decideToolFile(candidate, file, this.input.inlineImages)),
123
+ })
124
+
125
+ const message = toolFilesMessage(decisions)
126
+ return message ? { messages: [...messages, message] } : undefined
127
+ }
128
+ }
129
+
130
+ /** The key of a stored step's tool-files message: its message and its first local tool call. */
131
+ export function toolFilesStepKey(messageId: string, partIndex: number): string {
132
+ return `${messageId}:${partIndex}`
133
+ }
134
+
135
+ /**
136
+ * The images each stored step's tools returned, by {@link toolFilesStepKey}, not projected yet:
137
+ * {@link allocateInlineImages} projects them as far as the request's budget goes.
138
+ */
139
+ export function replayToolFiles(input: {
140
+ readonly messages: readonly AgentMessageRecord[]
141
+ readonly suppliesToolFiles: SuppliesToolFiles
142
+ readonly supportsImages: boolean
143
+ }): ReadonlyMap<string, readonly ToolFileCandidate[]> {
144
+ const replayed = new Map<string, readonly ToolFileCandidate[]>()
145
+ if (!input.supportsImages) return replayed
146
+
147
+ for (const message of input.messages) {
148
+ if (message.role !== "assistant") continue
149
+
150
+ for (const step of agentMessageSteps(message)) {
151
+ const first = step.localToolCalls[0]
152
+ if (!first) continue
153
+
154
+ const candidates = toolFileCandidates(
155
+ step.localToolCalls.map(({ part }) => ({
156
+ toolCallId: part.toolCallId,
157
+ toolName: part.toolName,
158
+ output: part.state === "output-available" ? part.output : undefined,
159
+ })),
160
+ input.suppliesToolFiles
161
+ )
162
+ if (candidates.length > 0) {
163
+ replayed.set(toolFilesStepKey(message.id, first.partIndex), candidates)
164
+ }
165
+ }
166
+ }
167
+ return replayed
168
+ }
169
+
170
+ /**
171
+ * Spend the request's inline image budget on the history, in thread order, oldest first: each user
172
+ * message's attachments, then the images after each step of the turn that answered it. Images are
173
+ * projected only while the budget is open, a few at a time; what does not fit reads as metadata.
174
+ * The run's own steps then take what is left, in the order a later replay walks them, so every
175
+ * turn takes the same decisions. Images are never stored: their bytes are projected again from
176
+ * their blobs, which is deterministic.
177
+ */
178
+ export async function allocateInlineImages(
179
+ input: ToolFileProjectionInput & {
180
+ readonly messages: readonly AgentMessageRecord[]
181
+ readonly attachments: PreparedAgentAttachmentContext
182
+ readonly toolFiles: ReadonlyMap<string, readonly ToolFileCandidate[]>
183
+ readonly budget: InlineImageBudget
184
+ }
185
+ ): Promise<PreparedAgentAttachmentContext> {
186
+ const { attachments, budget } = input
187
+ type Item =
188
+ | { readonly kind: "attachment"; readonly key: string; readonly image: PendingAttachmentImage }
189
+ | { readonly kind: "tool"; readonly step: string; readonly candidate: ToolFileCandidate }
190
+
191
+ const items: Item[] = []
192
+ for (const message of input.messages) {
193
+ if (message.role === "user") {
194
+ message.parts.forEach((_part, partIndex) => {
195
+ const key = attachmentKey(message.id, partIndex)
196
+ const image = attachments.pendingImages?.get(key)
197
+ if (image) items.push({ kind: "attachment", key, image })
198
+ })
199
+ continue
200
+ }
201
+
202
+ for (const step of agentMessageSteps(message)) {
203
+ const first = step.localToolCalls[0]
204
+ if (!first) continue
205
+
206
+ const key = toolFilesStepKey(message.id, first.partIndex)
207
+ for (const candidate of input.toolFiles.get(key) ?? []) {
208
+ items.push({ kind: "tool", step: key, candidate })
209
+ }
210
+ }
211
+ }
212
+
213
+ const outcomes = new Map<string, AttachmentImageOutcome>()
214
+ const decisionsByStep = new Map<string, ToolFileDecision[]>()
215
+ await projectInOrder({
216
+ items,
217
+ budget,
218
+ project: async (item) =>
219
+ item.kind === "attachment"
220
+ ? { attachment: await item.image.project(input.signal) }
221
+ : { tool: await projectToolFile(item.candidate, input) },
222
+ decide: (item, projected) => {
223
+ if (item.kind === "attachment") {
224
+ outcomes.set(item.key, decideAttachment(projected?.attachment, budget))
225
+ return
226
+ }
227
+
228
+ const decisions = decisionsByStep.get(item.step) ?? []
229
+ decisions.push(decideToolFile(item.candidate, projected?.tool, budget))
230
+ decisionsByStep.set(item.step, decisions)
231
+ },
232
+ })
233
+
234
+ const toolFilesByStep = new Map<string, ModelMessage>()
235
+ for (const [step, decisions] of decisionsByStep) {
236
+ const message = toolFilesMessage(decisions)
237
+ if (message) toolFilesByStep.set(step, message)
238
+ }
239
+ return { ...settleAttachmentImages(attachments, outcomes), toolFilesByStep }
240
+ }
241
+
242
+ /** An attachment's image fate: inline while it fits, metadata once the budget closed. */
243
+ function decideAttachment(
244
+ projection: AttachmentImageProjection | undefined,
245
+ budget: InlineImageBudget
246
+ ): AttachmentImageOutcome {
247
+ // One projected ahead of the budget's closing reads as one never projected.
248
+ if (budget.closed || !projection) return { kind: "budget" }
249
+ if (projection.kind !== "inline") return projection
250
+ return budget.take(projection.data.data) ? projection : { kind: "budget" }
251
+ }
252
+
253
+ /** A tool image's fate: inline while it fits, named once the budget closed. */
254
+ function decideToolFile(
255
+ candidate: ToolFileCandidate,
256
+ file: ModelFilePart | undefined,
257
+ budget: InlineImageBudget
258
+ ): ToolFileDecision {
259
+ const name = candidate.fileRef.fileName ?? "image"
260
+ if (budget.closed) return { kind: "budget", toolCallId: candidate.toolCallId, name }
261
+ if (!file) return { kind: "none" }
262
+ return budget.take(file.data)
263
+ ? { kind: "inline", toolCallId: candidate.toolCallId, file }
264
+ : { kind: "budget", toolCallId: candidate.toolCallId, name }
265
+ }
266
+
267
+ /** The image files a step's results returned, once each, in the order of the step's calls. */
268
+ function toolFileCandidates(
269
+ results: readonly StepToolResult[],
270
+ suppliesToolFiles: SuppliesToolFiles
271
+ ): ToolFileCandidate[] {
272
+ const seen = new Set<string>()
273
+ const candidates: ToolFileCandidate[] = []
274
+ for (const result of results) {
275
+ if (!suppliesToolFiles(result.toolName) || !isAgentToolResult(result.output)) continue
276
+
277
+ for (const contentPart of result.output.content) {
278
+ if (contentPart.type !== "file" || !isImageFile(contentPart.fileRef)) continue
279
+
280
+ const identity = fileContentKey(contentPart.fileRef)
281
+ if (seen.has(identity)) continue
282
+ seen.add(identity)
283
+ candidates.push({ toolCallId: result.toolCallId, fileRef: contentPart.fileRef })
284
+ }
285
+ }
286
+ return candidates
287
+ }
288
+
289
+ /** A tool image as the model reads it, or nothing when it cannot be projected. */
290
+ async function projectToolFile(
291
+ candidate: ToolFileCandidate,
292
+ input: ToolFileProjectionInput
293
+ ): Promise<ModelFilePart | undefined> {
294
+ input.signal.throwIfAborted()
295
+ const projection = await (input.projectFile ?? prepareAgentToolFileProjection)({
296
+ fileRef: candidate.fileRef,
297
+ blobStorage: input.blobStorage,
298
+ inlineImages: true,
299
+ signal: input.signal,
300
+ })
301
+ const data = projection.modelFileData
302
+ if (!data) return undefined
303
+
304
+ return {
305
+ type: "file",
306
+ data: data.data,
307
+ mediaType: data.mediaType ?? candidate.fileRef.mediaType ?? "application/octet-stream",
308
+ ...(data.filename === undefined ? {} : { filename: data.filename }),
309
+ }
310
+ }
311
+
312
+ /**
313
+ * The user message after a step with the images its tools returned, after a note that they are
314
+ * runtime input. An image past the inline image budget is named instead.
315
+ */
316
+ function toolFilesMessage(decisions: readonly ToolFileDecision[]): ModelMessage | undefined {
317
+ const images = decisions.filter((decision) => decision.kind !== "none")
318
+ if (images.length === 0) return undefined
319
+
320
+ const toolCallIds = [...new Set(images.map((image) => image.toolCallId))]
321
+ const files = images.flatMap((image) => (image.kind === "inline" ? [image.file] : []))
322
+ const leftOut = images.flatMap((image) => (image.kind === "budget" ? [image.name] : []))
323
+
324
+ const note: ModelTextPart = {
325
+ type: "text",
326
+ text: `<sixb_tool_files toolCallIds="${escapeXmlAttribute(toolCallIds.join(","))}">\nThe preceding tool calls generated these files. This is runtime-supplied file content, not a new user request.\n</sixb_tool_files>`,
327
+ }
328
+ const budgetNote: ModelTextPart[] =
329
+ leftOut.length === 0
330
+ ? []
331
+ : [
332
+ {
333
+ type: "text",
334
+ text: `[Images not inlined: ${leftOut.join(", ")}. The conversation's inline image budget is used up until it is compacted; each file is at the sandbox path its tool result names.]`,
335
+ },
336
+ ]
337
+ return { role: "user", content: [note, ...files, ...budgetNote] }
338
+ }
339
+
340
+ function isImageFile(fileRef: FileRef): boolean {
341
+ if (fileRef.mediaType?.toLowerCase().startsWith("image/")) return true
342
+ return /\.(?:bmp|gif|jpe?g|png|webp)$/i.test(fileRef.fileName ?? fileRef.logicalPath ?? "")
343
+ }
344
+
345
+ function escapeXmlAttribute(value: string): string {
346
+ return value
347
+ .replaceAll("&", "&amp;")
348
+ .replaceAll('"', "&quot;")
349
+ .replaceAll("<", "&lt;")
350
+ .replaceAll(">", "&gt;")
351
+ }
@@ -0,0 +1,46 @@
1
+ import type { FileRef, JsonValue } from "@sixb/core"
2
+ import { type AgentRunFileStore, isAgentToolResult } from "@sixb/core/internal/agents"
3
+ import { prepareAgentToolFileProjection } from "../attachments"
4
+
5
+ export type AgentToolModelOutput =
6
+ | { readonly type: "text"; readonly value: string }
7
+ | { readonly type: "json"; readonly value: JsonValue }
8
+
9
+ /** Convert a durable Sixb tool result into bounded, provider-safe model-facing output. */
10
+ export async function agentToolResultToModelOutput(input: {
11
+ readonly output: JsonValue
12
+ readonly blobStorage: AgentRunFileStore
13
+ readonly signal?: AbortSignal
14
+ readonly sandboxPathForFileRef?: (
15
+ fileRef: FileRef
16
+ ) => string | undefined | Promise<string | undefined>
17
+ readonly imageOmissionNote?: string
18
+ }): Promise<AgentToolModelOutput> {
19
+ if (!isAgentToolResult(input.output)) {
20
+ return typeof input.output === "string"
21
+ ? { type: "text", value: input.output }
22
+ : { type: "json", value: input.output }
23
+ }
24
+
25
+ const text: string[] = []
26
+ for (const contentPart of input.output.content) {
27
+ if (contentPart.type === "text") {
28
+ text.push(contentPart.text)
29
+ continue
30
+ }
31
+
32
+ const sandboxPath = await input.sandboxPathForFileRef?.(contentPart.fileRef)
33
+ const projection = await prepareAgentToolFileProjection({
34
+ fileRef: contentPart.fileRef,
35
+ blobStorage: input.blobStorage,
36
+ inlineImages: false,
37
+ ...(input.signal === undefined ? {} : { signal: input.signal }),
38
+ ...(sandboxPath === undefined ? {} : { sandboxPath }),
39
+ ...(input.imageOmissionNote === undefined
40
+ ? {}
41
+ : { imageOmissionNote: input.imageOmissionNote }),
42
+ })
43
+ text.push(projection.promptText)
44
+ }
45
+ return { type: "text", value: text.join("\n") }
46
+ }
@@ -0,0 +1,204 @@
1
+ import { posix } from "node:path"
2
+ import type { AgentToolFile, AgentToolFilePutInput, AgentToolFiles } from "@sixb/core"
3
+ import { AgentToolPublicError } from "@sixb/core"
4
+ import {
5
+ AGENT_FILE_MAX_BYTES,
6
+ type AgentRunFileStore,
7
+ type AgentToolCallFile,
8
+ storeAgentToolFile,
9
+ } from "@sixb/core/internal/agents"
10
+ import type { AgentSandboxHandle } from "../sandbox-handle"
11
+
12
+ export { AGENT_FILE_MAX_BYTES }
13
+ const DEFAULT_RUN_MAX_BYTES = 100 * 1024 * 1024
14
+
15
+ interface CreateAgentToolFilesInput {
16
+ readonly toolName: string
17
+ readonly toolCallId: string
18
+ readonly signal: AbortSignal
19
+ readonly blobStorage: AgentRunFileStore
20
+ readonly resolveSandbox: () => Promise<AgentSandboxHandle>
21
+ readonly onPublished?: (file: AgentToolFile) => void
22
+ /** Shared across every tool call in one run so parallel publishers cannot oversubscribe it. */
23
+ readonly budget?: AgentFileBudget
24
+ /** Test seam; production allows {@link AGENT_FILE_MAX_BYTES}. */
25
+ readonly fileMaxBytes?: number
26
+ }
27
+
28
+ /** Atomic byte budget shared by every file publisher in one agent run. */
29
+ export class AgentFileBudget {
30
+ #reservedBytes = 0
31
+ /**
32
+ * Content held by reservations, by digest. Blob storage keeps identical bytes once, so content a
33
+ * run stores again, such as the unchanged files of an artifact's next version, counts once.
34
+ */
35
+ readonly #contents = new Map<string, { readonly sizeBytes: number; holders: number }>()
36
+
37
+ constructor(readonly maxBytes = DEFAULT_RUN_MAX_BYTES) {
38
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 0) {
39
+ throw new Error("[SixbAgent] Agent file budget must be a safe non-negative integer.")
40
+ }
41
+ }
42
+
43
+ get reservedBytes(): number {
44
+ return this.#reservedBytes
45
+ }
46
+
47
+ reserve(bytes: number, toolName: string): AgentFileReservation {
48
+ if (!Number.isSafeInteger(bytes) || bytes < 0) {
49
+ throw new Error("[SixbAgent] Agent file reservation must be a safe non-negative integer.")
50
+ }
51
+ this.add(bytes, toolName)
52
+ return new AgentFileReservation(this, bytes, toolName)
53
+ }
54
+
55
+ add(bytes: number, toolName: string): void {
56
+ if (this.#reservedBytes + bytes > this.maxBytes) {
57
+ throw toolFileError(toolName, `files exceed the ${this.maxBytes}-byte run limit`)
58
+ }
59
+ this.#reservedBytes += bytes
60
+ }
61
+
62
+ release(bytes: number): void {
63
+ this.#reservedBytes -= bytes
64
+ }
65
+
66
+ /** Counts content's bytes when no reservation holds the same digest yet, and nothing after. */
67
+ holdContent(digest: string, sizeBytes: number, toolName: string): void {
68
+ const held = this.#contents.get(digest)
69
+ if (held) {
70
+ held.holders += 1
71
+ return
72
+ }
73
+ this.add(sizeBytes, toolName)
74
+ this.#contents.set(digest, { sizeBytes, holders: 1 })
75
+ }
76
+
77
+ releaseContent(digest: string): void {
78
+ const held = this.#contents.get(digest)
79
+ if (!held) return
80
+ held.holders -= 1
81
+ if (held.holders > 0) return
82
+ this.#contents.delete(digest)
83
+ this.release(held.sizeBytes)
84
+ }
85
+ }
86
+
87
+ class AgentFileReservation {
88
+ #bytes: number
89
+ readonly #contents: string[] = []
90
+ #released = false
91
+
92
+ constructor(
93
+ private readonly budget: AgentFileBudget,
94
+ bytes: number,
95
+ private readonly toolName: string
96
+ ) {
97
+ this.#bytes = bytes
98
+ }
99
+
100
+ add(bytes: number): void {
101
+ this.budget.add(bytes, this.toolName)
102
+ this.#bytes += bytes
103
+ }
104
+
105
+ /** Reserves bytes whose SHA-256 is `digest`, unless the run already counts the same content. */
106
+ addContent(digest: string, sizeBytes: number): void {
107
+ this.budget.holdContent(digest, sizeBytes, this.toolName)
108
+ this.#contents.push(digest)
109
+ }
110
+
111
+ release(): void {
112
+ if (this.#released) return
113
+ this.#released = true
114
+ this.budget.release(this.#bytes)
115
+ for (const digest of this.#contents) this.budget.releaseContent(digest)
116
+ }
117
+ }
118
+
119
+ /**
120
+ * The file publisher of one of the harness's own tool calls: each file is stored as a project
121
+ * tool's is, counted against the run's budget, and copied into the sandbox at its path.
122
+ */
123
+ export function createAgentToolFiles(input: CreateAgentToolFilesInput): AgentToolFiles {
124
+ const budget = input.budget ?? new AgentFileBudget()
125
+
126
+ return Object.freeze({
127
+ async put(fileInput: AgentToolFilePutInput) {
128
+ const reservation = budget.reserve(0, input.toolName)
129
+ let published = false
130
+ try {
131
+ const stored = await storeAgentToolFile({
132
+ toolName: input.toolName,
133
+ toolCallId: input.toolCallId,
134
+ file: fileInput,
135
+ store: input.blobStorage,
136
+ signal: input.signal,
137
+ onBytes: (sizeBytes) => reservation.add(sizeBytes),
138
+ ...(input.fileMaxBytes === undefined ? {} : { fileMaxBytes: input.fileMaxBytes }),
139
+ })
140
+ const file = await copyToSandbox(input, stored, stored.bytes)
141
+ published = true
142
+ return file
143
+ } finally {
144
+ if (!published) reservation.release()
145
+ }
146
+ },
147
+ })
148
+ }
149
+
150
+ /**
151
+ * Copy the files a project tool stored into the sandbox, at the paths it was told, each counted
152
+ * against the run's budget as the harness's own tools' files are. The call stored no more than the
153
+ * budget had left when it started.
154
+ */
155
+ export async function installAgentToolFiles(input: {
156
+ readonly toolName: string
157
+ readonly files: readonly AgentToolCallFile[]
158
+ readonly blobStorage: AgentRunFileStore
159
+ readonly resolveSandbox: () => Promise<AgentSandboxHandle>
160
+ readonly budget: AgentFileBudget
161
+ readonly signal: AbortSignal
162
+ readonly onPublished?: (file: AgentToolFile) => void
163
+ }): Promise<void> {
164
+ for (const file of input.files) {
165
+ input.signal.throwIfAborted()
166
+ const reservation = input.budget.reserve(0, input.toolName)
167
+ try {
168
+ reservation.add(file.fileRef.sizeBytes)
169
+ const bytes = new Uint8Array(
170
+ await new Response(await input.blobStorage.open(file.fileRef.blobId)).arrayBuffer()
171
+ )
172
+ await copyToSandbox(input, file, bytes)
173
+ } catch (error) {
174
+ reservation.release()
175
+ throw error
176
+ }
177
+ }
178
+ }
179
+
180
+ async function copyToSandbox(
181
+ input: {
182
+ readonly resolveSandbox: () => Promise<AgentSandboxHandle>
183
+ readonly signal: AbortSignal
184
+ readonly onPublished?: (file: AgentToolFile) => void
185
+ },
186
+ stored: AgentToolCallFile,
187
+ bytes: Uint8Array
188
+ ): Promise<AgentToolFile> {
189
+ const handle = await input.resolveSandbox()
190
+ input.signal.throwIfAborted()
191
+ const path = posix.join(handle.contextDirectory, stored.path)
192
+ await handle.sandbox.writeFiles([{ path, contents: bytes }])
193
+ input.signal.throwIfAborted()
194
+ const file = {
195
+ fileRef: stored.fileRef,
196
+ sandboxPath: posix.resolve(handle.sandbox.workingDirectory, path),
197
+ }
198
+ input.onPublished?.(file)
199
+ return file
200
+ }
201
+
202
+ function toolFileError(toolName: string, message: string): AgentToolPublicError {
203
+ return new AgentToolPublicError(`[SixbAgent] Agent tool '${toolName}' ${message}.`)
204
+ }