@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,322 @@
1
+ export interface AgentAttachmentLimits {
2
+ readonly textInlineMaxBytes: number
3
+ readonly textInlineMaxLines: number
4
+ readonly imageMaxWidth: number
5
+ readonly imageMaxHeight: number
6
+ readonly imageMaxBase64Bytes: number
7
+ readonly imageJpegQualities: readonly number[]
8
+ readonly imageMaxPixels: number
9
+ readonly sandboxFileMaxBytes: number
10
+ readonly sandboxTotalMaxBytes: number
11
+ }
12
+
13
+ export type ProcessedAgentImage =
14
+ | {
15
+ readonly ok: true
16
+ readonly dataUrl: URL
17
+ readonly mediaType: "image/png" | "image/jpeg" | "image/webp" | "image/gif"
18
+ readonly width: number
19
+ readonly height: number
20
+ readonly originalWidth: number
21
+ readonly originalHeight: number
22
+ readonly wasResized: boolean
23
+ readonly notes: readonly string[]
24
+ }
25
+ | {
26
+ readonly ok: false
27
+ readonly reason: string
28
+ readonly notes: readonly string[]
29
+ }
30
+
31
+ interface ImageMetadata {
32
+ readonly width: number
33
+ readonly height: number
34
+ readonly format: string
35
+ }
36
+
37
+ interface ImageCandidate {
38
+ readonly base64: string
39
+ readonly mediaType: "image/png" | "image/jpeg" | "image/webp" | "image/gif"
40
+ readonly encodedSize: number
41
+ readonly width: number
42
+ readonly height: number
43
+ readonly convertedFrom?: string
44
+ }
45
+
46
+ const BUN_FORMAT_TO_MEDIA_TYPE: Readonly<Record<string, ImageCandidate["mediaType"]>> = {
47
+ jpeg: "image/jpeg",
48
+ jpg: "image/jpeg",
49
+ png: "image/png",
50
+ webp: "image/webp",
51
+ gif: "image/gif",
52
+ }
53
+
54
+ export async function processAgentImageAttachment(input: {
55
+ readonly bytes: Uint8Array
56
+ readonly declaredMediaType?: string
57
+ readonly fileName?: string
58
+ readonly limits: AgentAttachmentLimits
59
+ readonly signal?: AbortSignal
60
+ }): Promise<ProcessedAgentImage> {
61
+ const { bytes, limits } = input
62
+ input.signal?.throwIfAborted()
63
+ if (typeof Bun.Image !== "function") {
64
+ return {
65
+ ok: false,
66
+ reason: "Bun.Image is unavailable in this runtime",
67
+ notes: ["[Image not inlined: this Bun runtime does not provide image processing.]"],
68
+ }
69
+ }
70
+
71
+ let metadata: ImageMetadata
72
+ try {
73
+ metadata = await readImageMetadata(bytes, limits)
74
+ input.signal?.throwIfAborted()
75
+ } catch (error) {
76
+ input.signal?.throwIfAborted()
77
+ return {
78
+ ok: false,
79
+ reason: imageErrorMessage(error),
80
+ notes: ["[Image omitted: could not be decoded as a supported image format.]"],
81
+ }
82
+ }
83
+
84
+ const originalMediaType =
85
+ mediaTypeForFormat(metadata.format) ?? normalizedMediaType(input.declaredMediaType)
86
+ if (!originalMediaType) {
87
+ return {
88
+ ok: false,
89
+ reason: `unsupported image format '${metadata.format}'`,
90
+ notes: ["[Image omitted: unsupported image format.]"],
91
+ }
92
+ }
93
+
94
+ const candidates: ImageCandidate[] = []
95
+ const originalBase64Size = base64EncodedSize(bytes.byteLength)
96
+ const withinDimensions =
97
+ metadata.width <= limits.imageMaxWidth && metadata.height <= limits.imageMaxHeight
98
+ if (
99
+ withinDimensions &&
100
+ originalBase64Size < limits.imageMaxBase64Bytes &&
101
+ originalMediaType !== "image/bmp"
102
+ ) {
103
+ const originalCandidate = originalCandidateFor(bytes, metadata, originalMediaType)
104
+ if (originalCandidate) {
105
+ return processedImageFromCandidate(originalCandidate, metadata)
106
+ }
107
+ }
108
+
109
+ candidates.push(
110
+ ...(await encodedCandidates(bytes, metadata, originalMediaType, limits, input.signal))
111
+ )
112
+ input.signal?.throwIfAborted()
113
+ const winner = candidates
114
+ .filter((candidate) => candidate.encodedSize < limits.imageMaxBase64Bytes)
115
+ .sort((left, right) => left.encodedSize - right.encodedSize)[0]
116
+
117
+ if (!winner) {
118
+ return {
119
+ ok: false,
120
+ reason: "inline image size limit exceeded",
121
+ notes: ["[Image omitted: could not be resized below the inline image size limit.]"],
122
+ }
123
+ }
124
+
125
+ return processedImageFromCandidate(winner, metadata)
126
+ }
127
+
128
+ async function readImageMetadata(
129
+ bytes: Uint8Array,
130
+ limits: AgentAttachmentLimits
131
+ ): Promise<ImageMetadata> {
132
+ const metadata = await new Bun.Image(bytes, {
133
+ maxPixels: limits.imageMaxPixels,
134
+ autoOrient: true,
135
+ }).metadata()
136
+ return {
137
+ width: metadata.width,
138
+ height: metadata.height,
139
+ format: metadata.format,
140
+ }
141
+ }
142
+
143
+ function originalCandidateFor(
144
+ bytes: Uint8Array,
145
+ metadata: ImageMetadata,
146
+ mediaType: string
147
+ ): ImageCandidate | undefined {
148
+ if (!isSupportedInlineImageMediaType(mediaType)) {
149
+ return undefined
150
+ }
151
+ return {
152
+ base64: Buffer.from(bytes).toString("base64"),
153
+ mediaType,
154
+ encodedSize: base64EncodedSize(bytes.byteLength),
155
+ width: metadata.width,
156
+ height: metadata.height,
157
+ }
158
+ }
159
+
160
+ async function encodedCandidates(
161
+ bytes: Uint8Array,
162
+ metadata: ImageMetadata,
163
+ originalMediaType: string,
164
+ limits: AgentAttachmentLimits,
165
+ signal?: AbortSignal
166
+ ): Promise<ImageCandidate[]> {
167
+ const result: ImageCandidate[] = []
168
+ const resized = () =>
169
+ new Bun.Image(bytes, { maxPixels: limits.imageMaxPixels, autoOrient: true }).resize(
170
+ limits.imageMaxWidth,
171
+ limits.imageMaxHeight,
172
+ { fit: "inside", withoutEnlargement: true, filter: "lanczos3" }
173
+ )
174
+
175
+ try {
176
+ signal?.throwIfAborted()
177
+ const pngBytes = await resized().png().bytes()
178
+ signal?.throwIfAborted()
179
+ result.push(
180
+ await candidateFromEncodedBytes({
181
+ bytes: pngBytes,
182
+ mediaType: "image/png",
183
+ originalMediaType,
184
+ fallbackWidth: Math.min(metadata.width, limits.imageMaxWidth),
185
+ fallbackHeight: Math.min(metadata.height, limits.imageMaxHeight),
186
+ limits,
187
+ })
188
+ )
189
+ } catch {
190
+ signal?.throwIfAborted()
191
+ // Keep trying JPEG candidates below. The caller reports omission if none fit.
192
+ }
193
+
194
+ for (const quality of limits.imageJpegQualities) {
195
+ try {
196
+ signal?.throwIfAborted()
197
+ const jpegBytes = await resized().jpeg({ quality }).bytes()
198
+ signal?.throwIfAborted()
199
+ result.push(
200
+ await candidateFromEncodedBytes({
201
+ bytes: jpegBytes,
202
+ mediaType: "image/jpeg",
203
+ originalMediaType,
204
+ fallbackWidth: Math.min(metadata.width, limits.imageMaxWidth),
205
+ fallbackHeight: Math.min(metadata.height, limits.imageMaxHeight),
206
+ limits,
207
+ })
208
+ )
209
+ } catch {
210
+ signal?.throwIfAborted()
211
+ // Try the next quality; some source formats/platforms may reject a candidate.
212
+ }
213
+ }
214
+
215
+ return result
216
+ }
217
+
218
+ async function candidateFromEncodedBytes(input: {
219
+ readonly bytes: Uint8Array
220
+ readonly mediaType: "image/png" | "image/jpeg"
221
+ readonly originalMediaType: string
222
+ readonly fallbackWidth: number
223
+ readonly fallbackHeight: number
224
+ readonly limits: AgentAttachmentLimits
225
+ }): Promise<ImageCandidate> {
226
+ const metadata = await readImageMetadata(input.bytes, input.limits).catch(() => ({
227
+ width: input.fallbackWidth,
228
+ height: input.fallbackHeight,
229
+ format: input.mediaType.split("/")[1] ?? "",
230
+ }))
231
+ return {
232
+ base64: Buffer.from(input.bytes).toString("base64"),
233
+ mediaType: input.mediaType,
234
+ encodedSize: base64EncodedSize(input.bytes.byteLength),
235
+ width: metadata.width,
236
+ height: metadata.height,
237
+ ...(input.originalMediaType === input.mediaType
238
+ ? {}
239
+ : { convertedFrom: input.originalMediaType }),
240
+ }
241
+ }
242
+
243
+ function processedImageFromCandidate(
244
+ candidate: ImageCandidate,
245
+ original: ImageMetadata
246
+ ): Extract<ProcessedAgentImage, { readonly ok: true }> {
247
+ const notes = imageNotes({
248
+ from: candidate.convertedFrom,
249
+ to: candidate.mediaType,
250
+ originalWidth: original.width,
251
+ originalHeight: original.height,
252
+ width: candidate.width,
253
+ height: candidate.height,
254
+ })
255
+
256
+ return {
257
+ ok: true,
258
+ dataUrl: new URL(`data:${candidate.mediaType};base64,${candidate.base64}`),
259
+ mediaType: candidate.mediaType,
260
+ width: candidate.width,
261
+ height: candidate.height,
262
+ originalWidth: original.width,
263
+ originalHeight: original.height,
264
+ wasResized: candidate.width !== original.width || candidate.height !== original.height,
265
+ notes,
266
+ }
267
+ }
268
+
269
+ function base64EncodedSize(byteLength: number): number {
270
+ return Math.ceil(byteLength / 3) * 4
271
+ }
272
+
273
+ function mediaTypeForFormat(format: string): ImageCandidate["mediaType"] | "image/bmp" | undefined {
274
+ const normalized = format.trim().toLowerCase()
275
+ if (normalized === "bmp") {
276
+ return "image/bmp"
277
+ }
278
+ return BUN_FORMAT_TO_MEDIA_TYPE[normalized]
279
+ }
280
+
281
+ function normalizedMediaType(value: string | undefined): string | undefined {
282
+ const normalized = value?.split(";")[0]?.trim().toLowerCase()
283
+ return normalized || undefined
284
+ }
285
+
286
+ function isSupportedInlineImageMediaType(
287
+ mediaType: string
288
+ ): mediaType is ImageCandidate["mediaType"] {
289
+ return (
290
+ mediaType === "image/png" ||
291
+ mediaType === "image/jpeg" ||
292
+ mediaType === "image/webp" ||
293
+ mediaType === "image/gif"
294
+ )
295
+ }
296
+
297
+ function imageNotes(input: {
298
+ readonly from: string | undefined
299
+ readonly to: string
300
+ readonly originalWidth: number
301
+ readonly originalHeight: number
302
+ readonly width: number
303
+ readonly height: number
304
+ }): string[] {
305
+ const notes: string[] = []
306
+ if (input.from && input.from !== input.to) {
307
+ notes.push(`[Image converted from ${input.from} to ${input.to}.]`)
308
+ }
309
+ if (input.width !== input.originalWidth || input.height !== input.originalHeight) {
310
+ notes.push(
311
+ `[Image resized from ${input.originalWidth}x${input.originalHeight} to ${input.width}x${input.height}.]`
312
+ )
313
+ }
314
+ return notes
315
+ }
316
+
317
+ function imageErrorMessage(error: unknown): string {
318
+ if (error instanceof Error) {
319
+ return error.message
320
+ }
321
+ return String(error)
322
+ }
package/src/index.ts ADDED
@@ -0,0 +1,54 @@
1
+ export { waitForAbort } from "./abort"
2
+ export type { AgentWorkspacePromptContext } from "./agent-prompt"
3
+ export { createAskParentTool } from "./ask-parent-tool"
4
+ export {
5
+ ComputerRunner,
6
+ type ComputerRunnerOptions,
7
+ type OpenComputerSandbox,
8
+ } from "./computer-runner"
9
+ export { prepareAgentModel } from "./context-budget"
10
+ export {
11
+ AgentEnvironmentSaveError,
12
+ AgentRequesterLeftThreadError,
13
+ isLostExecution,
14
+ } from "./errors"
15
+ export { type ResolvedAgentExecutionPlan, resolveRunPlan } from "./execution-plan"
16
+ export type { AgentRunFailure } from "./failure"
17
+ export { toAgentExecutionFailure, toAgentRunFailure } from "./failure"
18
+ export type { FamilyMailbox } from "./family-mailbox"
19
+ export type { ConversationReaders } from "./message-authors"
20
+ export type { AgentToolCaller } from "./model-adapters"
21
+ export { agentRequester } from "./requester"
22
+ export { runAgentTurn, stoppedByWorker } from "./run-agent-turn"
23
+ export { type ChildParent, ChildRunner, type ChildRunnerHost } from "./run-child"
24
+ export { type ConversationTurnRunner, runConversationTurn } from "./run-conversation-turn"
25
+ export { runApiCredential, runTokenFor } from "./run-credential"
26
+ export type {
27
+ AgentExecutionEnvironment,
28
+ ConversationAgentExecutionEnvironment,
29
+ OpenedRunSandbox,
30
+ OpenRunSandbox,
31
+ } from "./run-environment"
32
+ export {
33
+ createConversationAgentEnvironment,
34
+ createSubagentEnvironment,
35
+ createWorkflowAgentNodeEnvironment,
36
+ } from "./run-environment"
37
+ export { agentRunFailureDetails, recordFate } from "./run-fate"
38
+ export type { AcquiredRunSandbox, BeforeFinalizeOptions, RunSandbox } from "./run-sandbox"
39
+ export { SANDBOX_CONTEXT_DIRECTORY } from "./run-sandbox"
40
+ export type { SubagentWork } from "./run-subagent"
41
+ export { runSubagent } from "./run-subagent"
42
+ export type { WorkflowAgentFailurePhase } from "./run-workflow-agent-node"
43
+ export { runWorkflowAgentNode, WorkflowAgentNodeExecutionError } from "./run-workflow-agent-node"
44
+ export { withBuiltInSkills } from "./skills/built-in"
45
+ export { SubagentInbox } from "./subagent-inbox"
46
+ export type { TurnDelegation } from "./subagent-tools"
47
+ export { SubagentCoordinator } from "./subagent-tools"
48
+ export { workflowInputToolAttachments } from "./tools/attachments"
49
+ export type { AgentTurnRuntime } from "./turn-runtime"
50
+ export { createAgentTurnRuntime } from "./turn-runtime"
51
+ export type {
52
+ AgentExecutionContext,
53
+ AgentRunSettings,
54
+ } from "./types"
@@ -0,0 +1,69 @@
1
+ import { AGENT_INLINE_IMAGE_LIMITS } from "@sixb/core/internal/agents"
2
+
3
+ /** What a request says in place of an attachment's image the budget left out. */
4
+ export const INLINE_IMAGE_BUDGET_NOTE =
5
+ "[Image not inlined: the conversation's inline image budget is used up until it is compacted; the file is available through the sandbox path or content URL.]"
6
+
7
+ /** How many images a request projects at once while the budget decides them in order. */
8
+ const PROJECTION_CONCURRENCY = 4
9
+
10
+ /**
11
+ * What one request has left of {@link AGENT_INLINE_IMAGE_LIMITS}. A run takes from it in thread
12
+ * order, oldest first: the history's attachments and tool images, then the images its own steps
13
+ * return. The first image that does not fit closes it, so nothing after it is projected at all. A
14
+ * replay walks the same order: an image that fitted keeps its inline data until compaction, and one
15
+ * that did not stays metadata from its own turn on.
16
+ */
17
+ export class InlineImageBudget {
18
+ #bytes = 0
19
+ #images = 0
20
+ #closed = false
21
+
22
+ /** Whether no further image can go inline in this request. */
23
+ get closed(): boolean {
24
+ return this.#closed
25
+ }
26
+
27
+ /** Count the image in when it fits what is left; one that does not closes the budget. */
28
+ take(data: URL): boolean {
29
+ const bytes = data.href.length
30
+ this.#closed ||=
31
+ this.#images >= AGENT_INLINE_IMAGE_LIMITS.maxImages ||
32
+ this.#bytes + bytes > AGENT_INLINE_IMAGE_LIMITS.maxBytes
33
+ if (this.#closed) return false
34
+
35
+ this.#bytes += bytes
36
+ this.#images += 1
37
+ return true
38
+ }
39
+ }
40
+
41
+ /**
42
+ * Project images and let the budget decide each, in their order: a few run ahead at once, while
43
+ * every decision waits for the ones before it. Once the budget closes, the rest are never projected:
44
+ * `decide` gets `undefined` for them.
45
+ */
46
+ export async function projectInOrder<TItem, TProjection>(input: {
47
+ readonly items: readonly TItem[]
48
+ readonly budget: InlineImageBudget
49
+ readonly project: (item: TItem) => Promise<TProjection>
50
+ readonly decide: (item: TItem, projection: TProjection | undefined) => void
51
+ }): Promise<void> {
52
+ const { items, budget } = input
53
+ const projections: Promise<TProjection>[] = []
54
+
55
+ for (const [index, item] of items.entries()) {
56
+ if (budget.closed) {
57
+ input.decide(item, undefined)
58
+ continue
59
+ }
60
+
61
+ while (projections.length < Math.min(items.length, index + PROJECTION_CONCURRENCY)) {
62
+ const projection = input.project(items[projections.length] as TItem)
63
+ // Awaited in order below; one the budget no longer needs must not go unhandled.
64
+ projection.catch(() => {})
65
+ projections.push(projection)
66
+ }
67
+ input.decide(item, await projections[index])
68
+ }
69
+ }
@@ -0,0 +1,77 @@
1
+ import { type Principal, principalsEqual, type UserPrincipal } from "@sixb/core"
2
+ import type { AgentMessageRecord, AgentThreadRecord } from "@sixb/core/storage"
3
+ import {
4
+ type ConversationPerson,
5
+ renderConversationPeople,
6
+ renderMessageAuthor,
7
+ } from "./agent-prompt"
8
+
9
+ /** What the model reads of who writes in a conversation. Nothing of it is stored or shown. */
10
+ export interface ConversationAuthors {
11
+ /** Who takes part, for the system prompt; absent in a one-person conversation. */
12
+ readonly section?: string
13
+ /** The `<sixb_author>` closing each retained user message, by message id. */
14
+ readonly byMessageId: ReadonlyMap<string, string>
15
+ }
16
+
17
+ const ALONE: ConversationAuthors = { byMessageId: new Map() }
18
+
19
+ /**
20
+ * A thread with the participants who can read it now: the people the model is told about, with
21
+ * their display names as the turn read them (`AgentTurnContext.readers` and `names`).
22
+ */
23
+ export interface ConversationReaders {
24
+ readonly thread: AgentThreadRecord
25
+ readonly participants: readonly UserPrincipal[]
26
+ readonly names: Readonly<Record<string, string>>
27
+ }
28
+
29
+ /**
30
+ * Who wrote each retained user message, when the thread has participants or several people wrote
31
+ * in it; nothing in a conversation its owner holds alone, so its messages do not change.
32
+ *
33
+ * Each message's author derives from stored data, so a turn replays the bytes the previous one
34
+ * sent. They change only when someone renames their account. The section naming who takes part
35
+ * goes in the system prompt, the same whoever sends the turn: it changes when someone joins or
36
+ * leaves, or is renamed.
37
+ */
38
+ export function conversationAuthors(input: {
39
+ readonly conversation: ConversationReaders
40
+ readonly messages: readonly AgentMessageRecord[]
41
+ }): ConversationAuthors {
42
+ const { thread, participants, names } = input.conversation
43
+
44
+ const authored = input.messages.filter(
45
+ (message): message is AgentMessageRecord & { authorPrincipal: Principal } =>
46
+ message.role === "user" && message.authorPrincipal !== undefined
47
+ )
48
+ const owner = thread.ownerPrincipal
49
+ const someoneElseWrote = authored.some(
50
+ (message) => !principalsEqual(message.authorPrincipal, owner)
51
+ )
52
+ if (participants.length === 0 && !someoneElseWrote) return ALONE
53
+
54
+ // Each user goes by their display name; anyone else, or a user without one, by their id.
55
+ const personOf = (principal: Principal): ConversationPerson => {
56
+ const name = principal.type === "user" ? names[`user:${principal.id}`] : undefined
57
+ return name ? { id: principal.id, name } : { id: principal.id }
58
+ }
59
+
60
+ return {
61
+ section: renderConversationPeople({
62
+ owner: personOf(owner),
63
+ participants: participants.map(personOf),
64
+ }),
65
+ byMessageId: new Map(
66
+ authored.map((message) => [
67
+ message.id,
68
+ renderMessageAuthor(personOf(message.authorPrincipal)),
69
+ ])
70
+ ),
71
+ }
72
+ }
73
+
74
+ /** What the authors add to the user messages, for the model input's token estimate. */
75
+ export function conversationAuthorsText(authors: ConversationAuthors): string {
76
+ return [...authors.byMessageId.values()].join("\n")
77
+ }
@@ -0,0 +1,24 @@
1
+ import type { AgentTurnHistory } from "@sixb/core/internal/agents"
2
+ import { renderCurrentTime, type SentSettings } from "./agent-prompt"
3
+
4
+ /**
5
+ * The `<sixb_current_time>` closing each retained user message: when it was sent, in the time zone
6
+ * and locale of the run that answered it (the project's when that run captured none). Stored data
7
+ * only, so every later run replays the same bytes and the history stays a cacheable prefix.
8
+ */
9
+ export function userMessageTimes(
10
+ history: AgentTurnHistory,
11
+ project: SentSettings
12
+ ): ReadonlyMap<string, string> {
13
+ return new Map(
14
+ history.messages
15
+ .filter((message) => message.role === "user")
16
+ .map((message) => [
17
+ message.id,
18
+ renderCurrentTime(message.createdAt, {
19
+ timeZone: history.sentTimeZones[message.id] ?? project.timeZone,
20
+ locale: history.sentLocales?.[message.id] ?? project.locale,
21
+ }),
22
+ ])
23
+ )
24
+ }