@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,1041 @@
1
+ import { posix } from "node:path"
2
+ import type { AgentFileDataProjection, BlobInfo, FileRef } from "@sixb/core"
3
+ import {
4
+ type AgentRunFileStore,
5
+ agentToolFilePath,
6
+ listMessageAttachments,
7
+ } from "@sixb/core/internal/agents"
8
+ import type { LanguageModel, ModelMessage } from "@sixb/core/models"
9
+ import type { AgentMessageRecord } from "@sixb/core/storage"
10
+ import { NEVER_ABORTED_SIGNAL, waitForAbort } from "./abort"
11
+ import { fileRefKey } from "./file-ref"
12
+ import { type AgentAttachmentLimits, processAgentImageAttachment } from "./image-attachments"
13
+ import { INLINE_IMAGE_BUDGET_NOTE } from "./inline-images"
14
+
15
+ const DEFAULT_AGENT_ATTACHMENT_LIMITS: AgentAttachmentLimits = {
16
+ textInlineMaxBytes: 50 * 1024,
17
+ textInlineMaxLines: 2_000,
18
+ imageMaxWidth: 2_000,
19
+ imageMaxHeight: 2_000,
20
+ imageMaxBase64Bytes: 4.5 * 1024 * 1024,
21
+ imageJpegQualities: [80, 85, 70, 55, 40],
22
+ imageMaxPixels: 4096 * 4096,
23
+ sandboxFileMaxBytes: 25 * 1024 * 1024,
24
+ sandboxTotalMaxBytes: 100 * 1024 * 1024,
25
+ }
26
+ const TEXT_INLINE_TOTAL_MAX_BYTES = 200 * 1024
27
+ const MAX_ASSISTANT_ATTACHMENTS = 50
28
+
29
+ /**
30
+ * Where a parent finds what its children wrote to `out/`, a directory per spawn key, in the context
31
+ * directory: `wait_agent` copies them there, and later turns materialize them there again.
32
+ */
33
+ export const CHILD_FILES_DIRECTORY = "children"
34
+ const WAIT_AGENT_TOOL = "wait_agent"
35
+
36
+ /**
37
+ * How many files, and bytes, a sandbox receives of a run's attachments: also what a parent Agent
38
+ * and its child hand each other.
39
+ */
40
+ export const SANDBOX_ATTACHMENT_LIMITS = {
41
+ maxFiles: MAX_ASSISTANT_ATTACHMENTS,
42
+ fileMaxBytes: DEFAULT_AGENT_ATTACHMENT_LIMITS.sandboxFileMaxBytes,
43
+ totalMaxBytes: DEFAULT_AGENT_ATTACHMENT_LIMITS.sandboxTotalMaxBytes,
44
+ } as const
45
+
46
+ export interface PreparedAgentAttachmentContext {
47
+ readonly entries: readonly PreparedAgentAttachment[]
48
+ readonly promptTextByPartKey: ReadonlyMap<string, string>
49
+ readonly modelFileDataByPartKey: ReadonlyMap<string, AgentFileDataProjection>
50
+ readonly sandboxFiles: readonly PreparedSandboxAttachmentFile[]
51
+ readonly manifestJson: string
52
+ /** The images each stored step's tools returned, as the model read them after that step. */
53
+ readonly toolFilesByStep?: ReadonlyMap<string, ModelMessage>
54
+ /**
55
+ * The user attachments the request may inline as images, projected only once the request's
56
+ * inline image budget decides them ({@link settleAttachmentImages}). Until then each reads as
57
+ * the budget had no room for it.
58
+ */
59
+ readonly pendingImages?: ReadonlyMap<string, PendingAttachmentImage>
60
+ }
61
+
62
+ /** What projecting an attachment as an image gave: its inline data, or why there is none. */
63
+ export type AttachmentImageProjection =
64
+ | {
65
+ readonly kind: "inline"
66
+ readonly data: AgentFileDataProjection
67
+ readonly notes: readonly string[]
68
+ }
69
+ | { readonly kind: "not-inlined"; readonly notes: readonly string[] }
70
+
71
+ /** An image's fate in the request: projected, or left out because the budget was used up. */
72
+ export type AttachmentImageOutcome = AttachmentImageProjection | { readonly kind: "budget" }
73
+
74
+ /** A user attachment the request may inline as an image, decoded and encoded only on demand. */
75
+ export interface PendingAttachmentImage {
76
+ project(signal: AbortSignal): Promise<AttachmentImageProjection>
77
+ /** The attachment as the request reads it once its image's fate is known. */
78
+ settle(outcome: AttachmentImageOutcome): {
79
+ readonly entry: PreparedAgentAttachment
80
+ readonly promptText: string
81
+ readonly modelFileData?: AgentFileDataProjection
82
+ }
83
+ }
84
+
85
+ export interface PreparedAgentAttachment {
86
+ readonly key: string
87
+ readonly messageId: string
88
+ readonly partIndex: number
89
+ readonly fileRef: FileRef
90
+ readonly fileName: string
91
+ readonly mediaType: string
92
+ readonly sizeBytes: number
93
+ readonly contentPath: string
94
+ readonly contentUrl: string
95
+ readonly sandboxPath?: string
96
+ readonly inlineDisposition: "image" | "text" | "metadata-only" | "omitted"
97
+ readonly notes: readonly string[]
98
+ }
99
+
100
+ export interface PreparedSandboxAttachmentFile {
101
+ readonly key: string
102
+ readonly path: string
103
+ readonly bytes: Uint8Array
104
+ readonly fileRef: FileRef
105
+ }
106
+
107
+ export interface PreparedAgentToolFileProjection {
108
+ readonly promptText: string
109
+ readonly modelFileData?: AgentFileDataProjection
110
+ }
111
+
112
+ interface AttachmentWorkItem {
113
+ readonly message: AgentMessageRecord
114
+ readonly fileRef: FileRef
115
+ readonly partIndex: number
116
+ readonly key: string
117
+ readonly contentPath: string
118
+ readonly sandboxName: string
119
+ readonly inlineContent: boolean
120
+ readonly origin: "message-file" | "tool-result-file"
121
+ /** For a tool-result file, the call that returned it. */
122
+ readonly toolCall?: { readonly toolName: string; readonly toolCallId: string }
123
+ }
124
+
125
+ export async function prepareAgentAttachments(input: {
126
+ readonly projectId: string
127
+ readonly threadId: string
128
+ readonly messages: readonly AgentMessageRecord[]
129
+ readonly blobStorage: AgentRunFileStore
130
+ readonly apiBaseUrl: string
131
+ /** Where the run's files go: attachments are materialized in it. */
132
+ readonly contextDirectory: string
133
+ readonly inlineImages: boolean
134
+ readonly signal?: AbortSignal
135
+ }): Promise<PreparedAgentAttachmentContext> {
136
+ const promptTextByPartKey = new Map<string, string>()
137
+ const modelFileDataByPartKey = new Map<string, AgentFileDataProjection>()
138
+ const sandboxFiles: PreparedSandboxAttachmentFile[] = []
139
+ const entries: { readonly order: number; readonly entry: PreparedAgentAttachment }[] = []
140
+ const materialized = new Map<string, string>()
141
+ const textInlineBytesByMessage = new Map<string, number>()
142
+ const pendingImages = new Map<string, PendingAttachmentImage>()
143
+ let sandboxBytes = 0
144
+
145
+ // The user's files take the sandbox budget first, in message order: what a user message reads
146
+ // then depends only on the messages before it, never on the tool files the window keeps.
147
+ const items = fileWorkItems(input.messages).map((item, order) => ({ item, order }))
148
+ const userFirst = [
149
+ ...items.filter(({ item }) => item.message.role === "user"),
150
+ ...items.filter(({ item }) => item.message.role !== "user"),
151
+ ]
152
+
153
+ for (const { item, order } of userFirst) {
154
+ input.signal?.throwIfAborted()
155
+ const prepared = await prepareOneAttachment({
156
+ ...input,
157
+ item,
158
+ sandboxBytes,
159
+ textInlineBytes: textInlineBytesByMessage.get(item.message.id) ?? 0,
160
+ materialized,
161
+ })
162
+ sandboxBytes += prepared.sandboxBytesAdded
163
+ textInlineBytesByMessage.set(
164
+ item.message.id,
165
+ (textInlineBytesByMessage.get(item.message.id) ?? 0) + prepared.textInlineBytesAdded
166
+ )
167
+ entries.push({ order, entry: prepared.entry })
168
+ promptTextByPartKey.set(prepared.entry.key, prepared.promptText)
169
+ if (prepared.modelFileData) {
170
+ modelFileDataByPartKey.set(prepared.entry.key, prepared.modelFileData)
171
+ }
172
+ if (prepared.sandboxFile) {
173
+ sandboxFiles.push(prepared.sandboxFile)
174
+ materialized.set(fileRefKey(prepared.sandboxFile.fileRef), prepared.sandboxFile.path)
175
+ }
176
+ if (prepared.pendingImage) pendingImages.set(prepared.entry.key, prepared.pendingImage)
177
+ }
178
+
179
+ const ordered = entries.sort((left, right) => left.order - right.order).map(({ entry }) => entry)
180
+ return {
181
+ entries: ordered,
182
+ promptTextByPartKey,
183
+ modelFileDataByPartKey,
184
+ sandboxFiles,
185
+ ...(pendingImages.size === 0 ? {} : { pendingImages }),
186
+ manifestJson: JSON.stringify(
187
+ {
188
+ projectId: input.projectId,
189
+ threadId: input.threadId,
190
+ attachments: ordered.map((entry) => manifestEntry(entry)),
191
+ },
192
+ null,
193
+ 2
194
+ ),
195
+ }
196
+ }
197
+
198
+ /** Build the bounded, ephemeral projection of a tool-created file for the next model step. */
199
+ export async function prepareAgentToolFileProjection(input: {
200
+ readonly fileRef: FileRef
201
+ readonly blobStorage: AgentRunFileStore
202
+ readonly inlineImages: boolean
203
+ readonly signal?: AbortSignal
204
+ readonly sandboxPath?: string
205
+ readonly imageOmissionNote?: string
206
+ }): Promise<PreparedAgentToolFileProjection> {
207
+ const { fileRef } = input
208
+ const signal = input.signal ?? NEVER_ABORTED_SIGNAL
209
+ signal.throwIfAborted()
210
+ const fileName = fileNameFor(fileRef)
211
+ const mediaType = normalizedMediaType(fileRef.mediaType) ?? "application/octet-stream"
212
+ const notes: string[] = []
213
+ let textExcerpt: string | undefined
214
+ let modelFileData: AgentFileDataProjection | undefined
215
+
216
+ const stat = await safeBlobStat(input.blobStorage, fileRef, notes, signal)
217
+ if (!stat) {
218
+ notes.push("[File omitted: blob content is not available or no longer matches this FileRef.]")
219
+ } else {
220
+ const shouldReadForText = shouldAttemptTextInline(mediaType, fileName, stat.sizeBytes)
221
+ const shouldReadForImage = input.inlineImages && shouldAttemptImageInline(mediaType, fileName)
222
+ const readLimit = shouldReadForText
223
+ ? DEFAULT_AGENT_ATTACHMENT_LIMITS.textInlineMaxBytes + 4
224
+ : shouldReadForImage
225
+ ? DEFAULT_AGENT_ATTACHMENT_LIMITS.sandboxFileMaxBytes
226
+ : 0
227
+
228
+ if (readLimit > 0) {
229
+ const read = await readBlobBytes(input.blobStorage, fileRef.blobId, readLimit, signal, {
230
+ allowPrefix: shouldReadForText,
231
+ })
232
+ if (read.ok) {
233
+ const text = shouldReadForText
234
+ ? maybeTextExcerpt(read.bytes, mediaType, fileName, stat.sizeBytes, readLimit - 4)
235
+ : undefined
236
+ if (text) {
237
+ textExcerpt = text.text
238
+ if (text.truncated) {
239
+ notes.push("[Text file truncated for model input.]")
240
+ }
241
+ } else if (shouldReadForImage) {
242
+ const image = await maybeImageData({
243
+ bytes: read.bytes,
244
+ mediaType,
245
+ fileName,
246
+ inlineImages: true,
247
+ hasImageHint: true,
248
+ signal,
249
+ })
250
+ if (image?.ok) {
251
+ notes.push(...image.notes)
252
+ modelFileData = {
253
+ data: image.dataUrl,
254
+ mediaType: image.mediaType,
255
+ filename: fileName,
256
+ }
257
+ } else if (image) {
258
+ notes.push(...image.notes)
259
+ }
260
+ }
261
+ } else if (read.reason === "too_large") {
262
+ notes.push("[File not projected inline: file exceeds the attachment read limit.]")
263
+ } else {
264
+ notes.push(`[File not projected inline: ${read.reason}.]`)
265
+ }
266
+ }
267
+
268
+ if (!input.inlineImages && hasImageHint(mediaType, fileName)) {
269
+ notes.push(
270
+ input.imageOmissionNote ??
271
+ "[Image not inlined: the selected model does not advertise image input support.]"
272
+ )
273
+ }
274
+ if (!textExcerpt && !modelFileData && notes.length === 0) {
275
+ notes.push("[File contents are available through its sandbox path.]")
276
+ }
277
+ }
278
+
279
+ const body = [
280
+ ...notes,
281
+ ...(textExcerpt === undefined ? [] : ["<content>", textExcerpt, "</content>"]),
282
+ ].join("\n")
283
+ const sandboxPathAttribute =
284
+ input.sandboxPath === undefined ? "" : ` sandboxPath="${escapeXmlAttribute(input.sandboxPath)}"`
285
+ const promptText = `<tool_file name="${escapeXmlAttribute(fileName)}" mediaType="${escapeXmlAttribute(
286
+ mediaType
287
+ )}" sizeBytes="${fileRef.sizeBytes}"${sandboxPathAttribute}>\n${body}\n</tool_file>`
288
+ return {
289
+ promptText,
290
+ ...(modelFileData === undefined ? {} : { modelFileData }),
291
+ }
292
+ }
293
+
294
+ /**
295
+ * Every retained user message keeps its files inline, as its own turn read them, until compaction
296
+ * summarizes it: later turns then send the same bytes. Tool files are metadata in the manifest; the
297
+ * model reads what their call's output showed.
298
+ */
299
+ function fileWorkItems(messages: readonly AgentMessageRecord[]): AttachmentWorkItem[] {
300
+ const items: AttachmentWorkItem[] = []
301
+ for (const message of messages) {
302
+ for (const file of listMessageAttachments(message)) {
303
+ const part = message.parts[file.partIndex]
304
+ items.push({
305
+ message,
306
+ ...file,
307
+ inlineContent: file.origin === "message-file" && message.role === "user",
308
+ ...(file.origin === "tool-result-file" && part?.type === "tool-call"
309
+ ? { toolCall: { toolName: part.toolName, toolCallId: part.toolCallId } }
310
+ : {}),
311
+ })
312
+ }
313
+ }
314
+
315
+ const retainedAssistantKeys = new Set(
316
+ items
317
+ .filter((item) => item.message.role === "assistant")
318
+ .slice(-MAX_ASSISTANT_ATTACHMENTS)
319
+ .map((item) => item.key)
320
+ )
321
+ return items.filter(
322
+ (item) => item.message.role !== "assistant" || retainedAssistantKeys.has(item.key)
323
+ )
324
+ }
325
+
326
+ async function prepareOneAttachment(input: {
327
+ readonly projectId: string
328
+ readonly threadId: string
329
+ readonly item: AttachmentWorkItem
330
+ readonly blobStorage: AgentRunFileStore
331
+ readonly apiBaseUrl: string
332
+ readonly contextDirectory: string
333
+ readonly inlineImages: boolean
334
+ readonly sandboxBytes: number
335
+ /** What the message's earlier files took of its inline text budget. */
336
+ readonly textInlineBytes: number
337
+ /** Where the files already prepared went in the sandbox, by file. */
338
+ readonly materialized: ReadonlyMap<string, string>
339
+ readonly signal?: AbortSignal
340
+ }): Promise<{
341
+ readonly entry: PreparedAgentAttachment
342
+ readonly promptText: string
343
+ readonly modelFileData?: AgentFileDataProjection
344
+ readonly sandboxFile?: PreparedSandboxAttachmentFile
345
+ readonly pendingImage?: PendingAttachmentImage
346
+ readonly sandboxBytesAdded: number
347
+ readonly textInlineBytesAdded: number
348
+ }> {
349
+ const { item } = input
350
+ const signal = input.signal ?? NEVER_ABORTED_SIGNAL
351
+ signal.throwIfAborted()
352
+ const key = item.key
353
+ const fileRef = item.fileRef
354
+ const fileName = fileNameFor(fileRef)
355
+ const mediaType = normalizedMediaType(fileRef.mediaType) ?? "application/octet-stream"
356
+ const contentPath = item.contentPath
357
+ const contentUrl = attachmentContentUrl({
358
+ apiBaseUrl: input.apiBaseUrl,
359
+ threadId: input.threadId,
360
+ messageId: item.message.id,
361
+ contentPath,
362
+ })
363
+ const notes: string[] = []
364
+ let bytes: Uint8Array | undefined
365
+ let inlineDisposition: PreparedAgentAttachment["inlineDisposition"] = "metadata-only"
366
+ let sandboxPath: string | undefined
367
+ let sandboxFile: PreparedSandboxAttachmentFile | undefined
368
+ let sandboxBytesAdded = 0
369
+ let textExcerpt: string | undefined
370
+ let textInlineBytesAdded = 0
371
+ let projectImage: ((signal: AbortSignal) => Promise<AttachmentImageProjection>) | undefined
372
+ let metadataNote: string | undefined
373
+
374
+ const stat = await safeBlobStat(input.blobStorage, fileRef, notes, signal)
375
+ if (!stat) {
376
+ inlineDisposition = "omitted"
377
+ notes.push("[File omitted: blob content is not available or no longer matches this FileRef.]")
378
+ } else {
379
+ const canMaterializeFile = stat.sizeBytes <= DEFAULT_AGENT_ATTACHMENT_LIMITS.sandboxFileMaxBytes
380
+ const canMaterializeTotal =
381
+ input.sandboxBytes + stat.sizeBytes <= DEFAULT_AGENT_ATTACHMENT_LIMITS.sandboxTotalMaxBytes
382
+ const mayInlineContent = item.inlineContent
383
+ const remainingTextBytes = Math.max(0, TEXT_INLINE_TOTAL_MAX_BYTES - input.textInlineBytes)
384
+ const shouldReadForText =
385
+ mayInlineContent &&
386
+ remainingTextBytes > 0 &&
387
+ shouldAttemptTextInline(mediaType, fileName, stat.sizeBytes)
388
+ // A tool can return a file the sandbox holds already, such as an attachment view_file showed:
389
+ // its output named that path, and the file stays there once.
390
+ const alreadyAt =
391
+ item.origin === "tool-result-file" ? input.materialized.get(fileRefKey(fileRef)) : undefined
392
+ const needsFullBytes = alreadyAt === undefined && canMaterializeFile && canMaterializeTotal
393
+ const readLimit = needsFullBytes
394
+ ? stat.sizeBytes
395
+ : shouldReadForText
396
+ ? Math.min(DEFAULT_AGENT_ATTACHMENT_LIMITS.textInlineMaxBytes, remainingTextBytes) + 4
397
+ : 0
398
+
399
+ if (needsFullBytes || readLimit > 0) {
400
+ const read = await readBlobBytes(input.blobStorage, fileRef.blobId, readLimit, signal, {
401
+ allowPrefix: shouldReadForText && !needsFullBytes,
402
+ })
403
+ if (read.ok) {
404
+ bytes = read.bytes
405
+ } else if (read.reason === "too_large") {
406
+ notes.push("[File not read inline: file exceeds the attachment read limit.]")
407
+ } else {
408
+ notes.push(`[File not read inline: ${read.reason}.]`)
409
+ }
410
+ }
411
+
412
+ if (alreadyAt !== undefined) {
413
+ sandboxPath = alreadyAt
414
+ } else if (bytes && needsFullBytes && bytes.byteLength === stat.sizeBytes) {
415
+ sandboxPath =
416
+ toolResultSandboxPath(input.contextDirectory, item) ??
417
+ sandboxAttachmentPath(input.contextDirectory, item.message.id, item.sandboxName, fileName)
418
+ sandboxFile = { key, path: sandboxPath, bytes, fileRef }
419
+ sandboxBytesAdded = stat.sizeBytes
420
+ } else if (!canMaterializeFile) {
421
+ notes.push("[File not materialized in sandbox: file exceeds the per-file sandbox limit.]")
422
+ } else if (!canMaterializeTotal) {
423
+ notes.push("[File not materialized in sandbox: attachment sandbox budget exhausted.]")
424
+ }
425
+
426
+ if (bytes) {
427
+ const text =
428
+ mayInlineContent && remainingTextBytes > 0
429
+ ? maybeTextExcerpt(bytes, mediaType, fileName, stat.sizeBytes, remainingTextBytes)
430
+ : undefined
431
+ if (text) {
432
+ textExcerpt = text.text
433
+ textInlineBytesAdded = Buffer.byteLength(text.text, "utf-8")
434
+ inlineDisposition = "text"
435
+ if (text.truncated) {
436
+ notes.push(
437
+ `[Text attachment truncated: showing first ${text.linesShown} line(s) within ${formatBytes(
438
+ Math.min(DEFAULT_AGENT_ATTACHMENT_LIMITS.textInlineMaxBytes, remainingTextBytes)
439
+ )}. Full file is available through the sandbox path or content URL.]`
440
+ )
441
+ }
442
+ }
443
+
444
+ if (textExcerpt && hasImageHint(mediaType, fileName)) {
445
+ notes.push("[Image not inlined: attachment was treated as text based on its content.]")
446
+ }
447
+ }
448
+
449
+ // An image is decoded and encoded only once the request's inline image budget has room for
450
+ // it: see settleAttachmentImages.
451
+ const fullBytes = bytes?.byteLength === stat.sizeBytes ? bytes : undefined
452
+ if (!textExcerpt && mayInlineContent && input.inlineImages) {
453
+ projectImage = (projectSignal) =>
454
+ projectAttachmentImage({
455
+ ...input,
456
+ fileRef,
457
+ fileName,
458
+ mediaType,
459
+ ...(fullBytes === undefined ? {} : { bytes: fullBytes }),
460
+ signal: projectSignal,
461
+ })
462
+ }
463
+
464
+ if (mayInlineContent && !input.inlineImages && hasImageHint(mediaType, fileName)) {
465
+ notes.push("[Image not inlined: the selected model does not advertise image input support.]")
466
+ }
467
+
468
+ metadataNote = !item.inlineContent
469
+ ? "[Historical file kept as metadata: use view_file with the sandbox path when its contents are needed.]"
470
+ : remainingTextBytes === 0 && shouldAttemptTextInline(mediaType, fileName, stat.sizeBytes)
471
+ ? "[File not inlined: the attachment text budget is exhausted; use the sandbox path or content URL.]"
472
+ : "[File not inlined: available through the sandbox path or content URL.]"
473
+ }
474
+
475
+ const attachment = (
476
+ imageNotes: readonly string[],
477
+ image?: AgentFileDataProjection
478
+ ): { readonly entry: PreparedAgentAttachment; readonly promptText: string } => {
479
+ const disposition = image ? "image" : inlineDisposition
480
+ const allNotes = [...notes, ...imageNotes]
481
+ if (disposition === "metadata-only" && allNotes.length === 0 && metadataNote) {
482
+ allNotes.push(metadataNote)
483
+ }
484
+
485
+ const entry: PreparedAgentAttachment = {
486
+ key,
487
+ messageId: item.message.id,
488
+ partIndex: item.partIndex,
489
+ fileRef,
490
+ fileName,
491
+ mediaType,
492
+ sizeBytes: fileRef.sizeBytes,
493
+ contentPath,
494
+ contentUrl,
495
+ ...(sandboxPath === undefined ? {} : { sandboxPath }),
496
+ inlineDisposition: disposition,
497
+ notes: allNotes,
498
+ }
499
+ return { entry, promptText: attachmentPromptText(entry, textExcerpt) }
500
+ }
501
+
502
+ const imageHint = hasImageHint(mediaType, fileName)
503
+ const pendingImage: PendingAttachmentImage | undefined = projectImage && {
504
+ project: projectImage,
505
+ settle: (outcome) => {
506
+ if (outcome.kind === "inline") {
507
+ return { ...attachment(outcome.notes, outcome.data), modelFileData: outcome.data }
508
+ }
509
+ if (outcome.kind === "not-inlined") return attachment(outcome.notes)
510
+ return attachment(imageHint ? [INLINE_IMAGE_BUDGET_NOTE] : [])
511
+ },
512
+ }
513
+
514
+ return {
515
+ ...(pendingImage ? pendingImage.settle({ kind: "budget" }) : attachment([])),
516
+ ...(sandboxFile === undefined ? {} : { sandboxFile }),
517
+ ...(pendingImage === undefined ? {} : { pendingImage }),
518
+ sandboxBytesAdded,
519
+ textInlineBytesAdded,
520
+ }
521
+ }
522
+
523
+ /**
524
+ * Decode and encode a user attachment as the request inlines an image, from the bytes already read
525
+ * for the sandbox or from its blob. A file whose bytes are no image is not inlined, without a note
526
+ * unless it was named as one.
527
+ */
528
+ async function projectAttachmentImage(input: {
529
+ readonly blobStorage: AgentRunFileStore
530
+ readonly fileRef: FileRef
531
+ readonly fileName: string
532
+ readonly mediaType: string
533
+ readonly bytes?: Uint8Array
534
+ readonly signal: AbortSignal
535
+ }): Promise<AttachmentImageProjection> {
536
+ let bytes = input.bytes
537
+ if (!bytes) {
538
+ const read = await readBlobBytes(
539
+ input.blobStorage,
540
+ input.fileRef.blobId,
541
+ DEFAULT_AGENT_ATTACHMENT_LIMITS.sandboxFileMaxBytes,
542
+ input.signal
543
+ )
544
+ if (!read.ok) {
545
+ return {
546
+ kind: "not-inlined",
547
+ notes: [
548
+ read.reason === "too_large"
549
+ ? "[File not read inline: file exceeds the attachment read limit.]"
550
+ : `[File not read inline: ${read.reason}.]`,
551
+ ],
552
+ }
553
+ }
554
+ bytes = read.bytes
555
+ }
556
+
557
+ const image = await maybeImageData({
558
+ bytes,
559
+ mediaType: input.mediaType,
560
+ fileName: input.fileName,
561
+ inlineImages: true,
562
+ hasImageHint: hasImageHint(input.mediaType, input.fileName),
563
+ signal: input.signal,
564
+ })
565
+ if (!image) return { kind: "not-inlined", notes: [] }
566
+ if (!image.ok) return { kind: "not-inlined", notes: image.notes }
567
+ return {
568
+ kind: "inline",
569
+ data: { data: image.dataUrl, mediaType: image.mediaType, filename: input.fileName },
570
+ notes: image.notes,
571
+ }
572
+ }
573
+
574
+ async function safeBlobStat(
575
+ blobStorage: AgentRunFileStore,
576
+ fileRef: FileRef,
577
+ notes: string[],
578
+ signal: AbortSignal
579
+ ): Promise<BlobInfo | null> {
580
+ signal.throwIfAborted()
581
+ let stat: BlobInfo | null
582
+ try {
583
+ stat = await waitForAbort(blobStorage.stat(fileRef.blobId), signal)
584
+ } catch (error) {
585
+ signal.throwIfAborted()
586
+ console.error("[SixbAgent] Failed to inspect an attachment blob.", error)
587
+ notes.push("[File omitted: blob storage metadata is unavailable.]")
588
+ return null
589
+ }
590
+ if (!stat || !blobMatchesFileRef(stat, fileRef)) {
591
+ return null
592
+ }
593
+ return stat
594
+ }
595
+
596
+ function blobMatchesFileRef(stat: BlobInfo, fileRef: FileRef): boolean {
597
+ return (
598
+ stat.blobId === fileRef.blobId &&
599
+ stat.digest === fileRef.digest &&
600
+ stat.sizeBytes === fileRef.sizeBytes
601
+ )
602
+ }
603
+
604
+ async function readBlobBytes(
605
+ blobStorage: AgentRunFileStore,
606
+ blobId: string,
607
+ maxBytes: number,
608
+ signal: AbortSignal,
609
+ options: { readonly allowPrefix?: boolean } = {}
610
+ ): Promise<
611
+ | { readonly ok: true; readonly bytes: Uint8Array }
612
+ | { readonly ok: false; readonly reason: string }
613
+ > {
614
+ signal.throwIfAborted()
615
+ let stream: ReadableStream<Uint8Array>
616
+ try {
617
+ stream = await waitForAbort(blobStorage.open(blobId), signal)
618
+ } catch (error) {
619
+ signal.throwIfAborted()
620
+ console.error("[SixbAgent] Failed to open an attachment blob.", error)
621
+ return { ok: false, reason: "blob content is unavailable" }
622
+ }
623
+
624
+ const reader = stream.getReader()
625
+ const chunks: Uint8Array[] = []
626
+ let total = 0
627
+ const cancelOnAbort = () => {
628
+ void reader.cancel(signal.reason)
629
+ }
630
+ signal.addEventListener("abort", cancelOnAbort, { once: true })
631
+ // A cancel between the open and the listener fires no event.
632
+ if (signal.aborted) cancelOnAbort()
633
+ try {
634
+ for (;;) {
635
+ const { done, value } = await reader.read()
636
+ signal.throwIfAborted()
637
+ if (done) break
638
+ const remaining = maxBytes - total
639
+ if (value.byteLength > remaining) {
640
+ if (options.allowPrefix) {
641
+ if (remaining > 0) chunks.push(value.subarray(0, remaining))
642
+ total = maxBytes
643
+ await reader.cancel().catch(() => {})
644
+ break
645
+ }
646
+ await reader.cancel().catch(() => {})
647
+ return { ok: false, reason: "too_large" }
648
+ }
649
+ total += value.byteLength
650
+ chunks.push(value)
651
+ }
652
+ } finally {
653
+ signal.removeEventListener("abort", cancelOnAbort)
654
+ reader.releaseLock()
655
+ }
656
+
657
+ const result = new Uint8Array(total)
658
+ let offset = 0
659
+ for (const chunk of chunks) {
660
+ result.set(chunk, offset)
661
+ offset += chunk.byteLength
662
+ }
663
+ return { ok: true, bytes: result }
664
+ }
665
+
666
+ function shouldAttemptTextInline(mediaType: string, fileName: string, sizeBytes: number): boolean {
667
+ return (
668
+ sizeBytes <= DEFAULT_AGENT_ATTACHMENT_LIMITS.sandboxFileMaxBytes &&
669
+ (isTextMediaType(mediaType) || looksLikeTextFileName(fileName))
670
+ )
671
+ }
672
+
673
+ function shouldAttemptImageInline(mediaType: string, fileName: string): boolean {
674
+ return hasImageHint(mediaType, fileName)
675
+ }
676
+
677
+ function maybeTextExcerpt(
678
+ bytes: Uint8Array,
679
+ mediaType: string,
680
+ fileName: string,
681
+ sizeBytes: number,
682
+ maxBytes: number
683
+ ): { readonly text: string; readonly truncated: boolean; readonly linesShown: number } | undefined {
684
+ const declaredText = isTextMediaType(mediaType) || looksLikeTextFileName(fileName)
685
+ if (!declaredText && !looksLikeUtf8Text(bytes)) {
686
+ return undefined
687
+ }
688
+
689
+ let text: string
690
+ try {
691
+ text = new TextDecoder("utf-8", { fatal: !declaredText }).decode(
692
+ bytes.subarray(0, Math.min(bytes.byteLength, maxBytes + 4))
693
+ )
694
+ } catch {
695
+ return undefined
696
+ }
697
+
698
+ const truncated = truncateText(text, {
699
+ ...DEFAULT_AGENT_ATTACHMENT_LIMITS,
700
+ textInlineMaxBytes: Math.min(DEFAULT_AGENT_ATTACHMENT_LIMITS.textInlineMaxBytes, maxBytes),
701
+ })
702
+ return {
703
+ text: truncated.text,
704
+ truncated: truncated.truncated || sizeBytes > bytes.byteLength,
705
+ linesShown: truncated.linesShown,
706
+ }
707
+ }
708
+
709
+ function truncateText(
710
+ value: string,
711
+ limits: AgentAttachmentLimits
712
+ ): { readonly text: string; readonly truncated: boolean; readonly linesShown: number } {
713
+ const lines = value.split("\n")
714
+ const out: string[] = []
715
+ let bytes = 0
716
+ let truncated = false
717
+
718
+ for (const line of lines) {
719
+ if (out.length >= limits.textInlineMaxLines) {
720
+ truncated = true
721
+ break
722
+ }
723
+ const separatorBytes = out.length === 0 ? 0 : 1
724
+ const lineBytes = Buffer.byteLength(line, "utf-8") + separatorBytes
725
+ if (bytes + lineBytes > limits.textInlineMaxBytes) {
726
+ truncated = true
727
+ break
728
+ }
729
+ out.push(line)
730
+ bytes += lineBytes
731
+ }
732
+
733
+ return { text: out.join("\n"), truncated, linesShown: out.length }
734
+ }
735
+
736
+ function looksLikeUtf8Text(bytes: Uint8Array): boolean {
737
+ if (bytes.length === 0) {
738
+ return true
739
+ }
740
+ try {
741
+ new TextDecoder("utf-8", { fatal: true }).decode(bytes)
742
+ } catch {
743
+ return false
744
+ }
745
+ const sampleLength = Math.min(bytes.length, 1024)
746
+ let control = 0
747
+ for (let index = 0; index < sampleLength; index += 1) {
748
+ const byte = bytes[index]
749
+ if (byte !== 9 && byte !== 10 && byte !== 13 && byte < 32) {
750
+ control += 1
751
+ }
752
+ }
753
+ return control / sampleLength < 0.02
754
+ }
755
+
756
+ async function maybeImageData(input: {
757
+ readonly bytes: Uint8Array
758
+ readonly mediaType: string
759
+ readonly fileName: string
760
+ readonly inlineImages: boolean
761
+ readonly hasImageHint: boolean
762
+ readonly signal: AbortSignal
763
+ }): Promise<
764
+ | {
765
+ readonly ok: true
766
+ readonly dataUrl: URL
767
+ readonly mediaType: string
768
+ readonly notes: readonly string[]
769
+ }
770
+ | { readonly ok: false; readonly notes: readonly string[] }
771
+ | undefined
772
+ > {
773
+ if (!input.inlineImages) {
774
+ return undefined
775
+ }
776
+
777
+ input.signal.throwIfAborted()
778
+ const image = await processAgentImageAttachment({
779
+ bytes: input.bytes,
780
+ declaredMediaType: input.mediaType,
781
+ fileName: input.fileName,
782
+ limits: DEFAULT_AGENT_ATTACHMENT_LIMITS,
783
+ signal: input.signal,
784
+ })
785
+ input.signal.throwIfAborted()
786
+ if (!image.ok) {
787
+ return input.hasImageHint ? { ok: false, notes: image.notes } : undefined
788
+ }
789
+ return {
790
+ ok: true,
791
+ dataUrl: image.dataUrl,
792
+ mediaType: image.mediaType,
793
+ notes: image.notes,
794
+ }
795
+ }
796
+
797
+ export function modelSupportsInlineImages(model: LanguageModel): boolean {
798
+ const { inputMediaTypes } = model.definition.capabilities
799
+ return (
800
+ inputMediaTypes === "any" ||
801
+ inputMediaTypes?.some((mediaType) => mediaType.toLowerCase().startsWith("image/")) === true
802
+ )
803
+ }
804
+
805
+ /**
806
+ * The context once the request's inline image budget decided its pending images: each reads inline,
807
+ * or as metadata with the note that says why, in the prompt and in the manifest.
808
+ */
809
+ export function settleAttachmentImages(
810
+ context: PreparedAgentAttachmentContext,
811
+ outcomes: ReadonlyMap<string, AttachmentImageOutcome>
812
+ ): PreparedAgentAttachmentContext {
813
+ const { pendingImages, ...settled } = context
814
+ if (!pendingImages) return context
815
+
816
+ const promptTextByPartKey = new Map(context.promptTextByPartKey)
817
+ const modelFileDataByPartKey = new Map(context.modelFileDataByPartKey)
818
+ const entries = context.entries.map((entry) => {
819
+ const pending = pendingImages.get(entry.key)
820
+ if (!pending) return entry
821
+
822
+ const attachment = pending.settle(outcomes.get(entry.key) ?? { kind: "budget" })
823
+ promptTextByPartKey.set(entry.key, attachment.promptText)
824
+ if (attachment.modelFileData) modelFileDataByPartKey.set(entry.key, attachment.modelFileData)
825
+ return attachment.entry
826
+ })
827
+
828
+ const manifest = JSON.parse(context.manifestJson) as Record<string, unknown>
829
+ return {
830
+ ...settled,
831
+ entries,
832
+ promptTextByPartKey,
833
+ modelFileDataByPartKey,
834
+ manifestJson: JSON.stringify(
835
+ { ...manifest, attachments: entries.map((entry) => manifestEntry(entry)) },
836
+ null,
837
+ 2
838
+ ),
839
+ }
840
+ }
841
+
842
+ function attachmentPromptText(
843
+ entry: PreparedAgentAttachment,
844
+ textExcerpt: string | undefined
845
+ ): string {
846
+ const attrs = [
847
+ `key="${escapeXmlAttribute(entry.key)}"`,
848
+ `messageId="${escapeXmlAttribute(entry.messageId)}"`,
849
+ `partIndex="${entry.partIndex}"`,
850
+ `name="${escapeXmlAttribute(entry.fileName)}"`,
851
+ `mediaType="${escapeXmlAttribute(entry.mediaType)}"`,
852
+ `sizeBytes="${entry.sizeBytes}"`,
853
+ ...(entry.fileRef.logicalPath
854
+ ? [`logicalPath="${escapeXmlAttribute(entry.fileRef.logicalPath)}"`]
855
+ : []),
856
+ `contentUrl="${escapeXmlAttribute(entry.contentUrl)}"`,
857
+ ...(entry.sandboxPath ? [`sandboxPath="${escapeXmlAttribute(entry.sandboxPath)}"`] : []),
858
+ ].join(" ")
859
+ const body = [
860
+ ...entry.notes,
861
+ ...(textExcerpt === undefined ? [] : ["<content>", textExcerpt, "</content>"]),
862
+ ].join("\n")
863
+ return `<attachment ${attrs}>\n${body}\n</attachment>`
864
+ }
865
+
866
+ function manifestEntry(entry: PreparedAgentAttachment) {
867
+ return {
868
+ key: entry.key,
869
+ messageId: entry.messageId,
870
+ partIndex: entry.partIndex,
871
+ fileName: entry.fileName,
872
+ mediaType: entry.mediaType,
873
+ sizeBytes: entry.sizeBytes,
874
+ ...(entry.fileRef.logicalPath ? { logicalPath: entry.fileRef.logicalPath } : {}),
875
+ digest: entry.fileRef.digest,
876
+ contentPath: entry.contentPath,
877
+ contentUrl: entry.contentUrl,
878
+ ...(entry.sandboxPath === undefined ? {} : { sandboxPath: entry.sandboxPath }),
879
+ inlineDisposition: entry.inlineDisposition,
880
+ notes: entry.notes,
881
+ }
882
+ }
883
+
884
+ function attachmentContentUrl(input: {
885
+ readonly apiBaseUrl: string
886
+ readonly threadId: string
887
+ readonly messageId: string
888
+ readonly contentPath: string
889
+ }): string {
890
+ const base = input.apiBaseUrl.replace(/\/+$/, "")
891
+ return `${base}/api/agent-threads/${encodeURIComponent(
892
+ input.threadId
893
+ )}/messages/${encodeURIComponent(input.messageId)}/files/content?path=${encodeURIComponent(
894
+ input.contentPath
895
+ )}`
896
+ }
897
+
898
+ function sandboxAttachmentPath(
899
+ contextDirectory: string,
900
+ messageId: string,
901
+ sandboxName: string,
902
+ fileName: string
903
+ ): string {
904
+ return posix.join(
905
+ contextDirectory,
906
+ "attachments",
907
+ safePathSegment(messageId),
908
+ `${safePathSegment(sandboxName)}-${safeFileName(fileName)}`
909
+ )
910
+ }
911
+
912
+ /**
913
+ * Where the call that returned a tool file put it in the sandbox, as its output showed: a later
914
+ * turn materializes it there again, so the replayed output still names a file that exists.
915
+ * `wait_agent` copies a child's file under `children/<key>/`, its `logicalPath`; a tool that
916
+ * stored a file put it at its call's tool-file path.
917
+ */
918
+ function toolResultSandboxPath(
919
+ contextDirectory: string,
920
+ item: AttachmentWorkItem
921
+ ): string | undefined {
922
+ const { toolCall, fileRef } = item
923
+ if (!toolCall) return undefined
924
+
925
+ if (toolCall.toolName === WAIT_AGENT_TOOL) {
926
+ const path =
927
+ fileRef.logicalPath === undefined ? undefined : posix.normalize(fileRef.logicalPath)
928
+ if (!path || path.startsWith("/") || path === ".." || path.startsWith("../")) return undefined
929
+ return posix.join(contextDirectory, CHILD_FILES_DIRECTORY, path)
930
+ }
931
+
932
+ const name = fileRef.fileName
933
+ if (!name || name === "." || name === ".." || /[\\/\u0000-\u001f\u007f]/.test(name))
934
+ return undefined
935
+ return posix.join(contextDirectory, agentToolFilePath(toolCall.toolCallId, fileRef, name))
936
+ }
937
+
938
+ function fileNameFor(fileRef: FileRef): string {
939
+ const fromFileName = lastPathSegment(fileRef.fileName)
940
+ if (fromFileName) return fromFileName
941
+ const fromLogicalPath = lastPathSegment(fileRef.logicalPath)
942
+ return fromLogicalPath || `${fileRef.blobId}.bin`
943
+ }
944
+
945
+ function lastPathSegment(value: string | undefined): string | undefined {
946
+ const segment = value?.split(/[\\/]/).filter(Boolean).at(-1)?.trim()
947
+ return segment || undefined
948
+ }
949
+
950
+ function safeFileName(value: string): string {
951
+ const cleaned = value
952
+ .normalize("NFKC")
953
+ .replace(/[\u0000-\u001f\u007f]/g, "_")
954
+ .replace(/[\\/]/g, "_")
955
+ .replace(/^\.+$/, "_")
956
+ .slice(0, 120)
957
+ return cleaned || "attachment.bin"
958
+ }
959
+
960
+ function safePathSegment(value: string): string {
961
+ return safeFileName(value).replace(/[^A-Za-z0-9._-]/g, "_") || "message"
962
+ }
963
+
964
+ function normalizedMediaType(value: string | undefined): string | undefined {
965
+ const normalized = value?.split(";")[0]?.trim().toLowerCase()
966
+ return normalized || undefined
967
+ }
968
+
969
+ function isTextMediaType(mediaType: string): boolean {
970
+ return (
971
+ mediaType.startsWith("text/") ||
972
+ mediaType === "application/json" ||
973
+ mediaType === "application/xml" ||
974
+ mediaType === "application/yaml" ||
975
+ mediaType === "application/x-yaml" ||
976
+ mediaType === "application/javascript" ||
977
+ mediaType === "application/typescript" ||
978
+ mediaType === "application/csv"
979
+ )
980
+ }
981
+
982
+ function looksLikeTextFileName(fileName: string): boolean {
983
+ const lower = fileName.toLowerCase()
984
+ return [
985
+ ".txt",
986
+ ".md",
987
+ ".markdown",
988
+ ".json",
989
+ ".jsonl",
990
+ ".csv",
991
+ ".ts",
992
+ ".tsx",
993
+ ".js",
994
+ ".jsx",
995
+ ".mjs",
996
+ ".cjs",
997
+ ".yml",
998
+ ".yaml",
999
+ ".xml",
1000
+ ".html",
1001
+ ".css",
1002
+ ".scss",
1003
+ ".log",
1004
+ ].some((extension) => lower.endsWith(extension))
1005
+ }
1006
+
1007
+ function hasImageHint(mediaType: string, fileName: string): boolean {
1008
+ return isImageMediaType(mediaType) || looksLikeImageFileName(fileName)
1009
+ }
1010
+
1011
+ function isImageMediaType(mediaType: string): boolean {
1012
+ return mediaType.startsWith("image/")
1013
+ }
1014
+
1015
+ function looksLikeImageFileName(fileName: string): boolean {
1016
+ const lower = fileName.toLowerCase()
1017
+ return [".png", ".jpg", ".jpeg", ".webp", ".gif", ".bmp"].some((extension) =>
1018
+ lower.endsWith(extension)
1019
+ )
1020
+ }
1021
+
1022
+ function escapeXmlAttribute(value: string): string {
1023
+ return value
1024
+ .replace(/&/g, "&amp;")
1025
+ .replace(/"/g, "&quot;")
1026
+ .replace(/</g, "&lt;")
1027
+ .replace(/>/g, "&gt;")
1028
+ }
1029
+
1030
+ export function formatBytes(bytes: number): string {
1031
+ if (bytes < 1024) return `${bytes}B`
1032
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)}KB`
1033
+ return `${(bytes / (1024 * 1024)).toFixed(1)}MB`
1034
+ }
1035
+
1036
+ export {
1037
+ attachmentKey,
1038
+ attachmentKeyMessageId,
1039
+ findMessageAttachment,
1040
+ toolResultAttachmentKey,
1041
+ } from "@sixb/core/internal/agents"