@sixb/agent 0.0.0-stage → 0.1.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 (219) 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 +120 -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 +68 -0
  22. package/dist/attachments.d.ts.map +1 -0
  23. package/dist/child-files.d.ts +96 -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 +65 -0
  28. package/dist/computer-runner.d.ts.map +1 -0
  29. package/dist/context-budget.d.ts +28 -0
  30. package/dist/context-budget.d.ts.map +1 -0
  31. package/dist/context-compaction.d.ts +48 -0
  32. package/dist/context-compaction.d.ts.map +1 -0
  33. package/dist/conversation-memory.d.ts +21 -0
  34. package/dist/conversation-memory.d.ts.map +1 -0
  35. package/dist/errors.d.ts +46 -0
  36. package/dist/errors.d.ts.map +1 -0
  37. package/dist/execution-plan.d.ts +34 -0
  38. package/dist/execution-plan.d.ts.map +1 -0
  39. package/dist/failure.d.ts +14 -0
  40. package/dist/failure.d.ts.map +1 -0
  41. package/dist/family-mailbox.d.ts +60 -0
  42. package/dist/family-mailbox.d.ts.map +1 -0
  43. package/dist/file-ref.d.ts +6 -0
  44. package/dist/file-ref.d.ts.map +1 -0
  45. package/dist/image-attachments.d.ts +34 -0
  46. package/dist/image-attachments.d.ts.map +1 -0
  47. package/dist/index.d.ts +35 -0
  48. package/dist/index.d.ts.map +1 -0
  49. package/dist/index.js +12168 -0
  50. package/dist/index.js.map +65 -0
  51. package/dist/message-authors.d.ts +34 -0
  52. package/dist/message-authors.d.ts.map +1 -0
  53. package/dist/message-times.d.ts +8 -0
  54. package/dist/message-times.d.ts.map +1 -0
  55. package/dist/model-adapters.d.ts +55 -0
  56. package/dist/model-adapters.d.ts.map +1 -0
  57. package/dist/model-lines.d.ts +16 -0
  58. package/dist/model-lines.d.ts.map +1 -0
  59. package/dist/requester.d.ts +15 -0
  60. package/dist/requester.d.ts.map +1 -0
  61. package/dist/run-agent-turn.d.ts +63 -0
  62. package/dist/run-agent-turn.d.ts.map +1 -0
  63. package/dist/run-child.d.ts +77 -0
  64. package/dist/run-child.d.ts.map +1 -0
  65. package/dist/run-conversation-turn.d.ts +42 -0
  66. package/dist/run-conversation-turn.d.ts.map +1 -0
  67. package/dist/run-credential.d.ts +22 -0
  68. package/dist/run-credential.d.ts.map +1 -0
  69. package/dist/run-environment.d.ts +115 -0
  70. package/dist/run-environment.d.ts.map +1 -0
  71. package/dist/run-fate.d.ts +15 -0
  72. package/dist/run-fate.d.ts.map +1 -0
  73. package/dist/run-sandbox.d.ts +60 -0
  74. package/dist/run-sandbox.d.ts.map +1 -0
  75. package/dist/run-subagent.d.ts +51 -0
  76. package/dist/run-subagent.d.ts.map +1 -0
  77. package/dist/run-workflow-agent-node.d.ts +41 -0
  78. package/dist/run-workflow-agent-node.d.ts.map +1 -0
  79. package/dist/sandbox-api-context.d.ts +34 -0
  80. package/dist/sandbox-api-context.d.ts.map +1 -0
  81. package/dist/sandbox-file-registry.d.ts +9 -0
  82. package/dist/sandbox-file-registry.d.ts.map +1 -0
  83. package/dist/sandbox-files.d.ts +71 -0
  84. package/dist/sandbox-files.d.ts.map +1 -0
  85. package/dist/sandbox-handle.d.ts +15 -0
  86. package/dist/sandbox-handle.d.ts.map +1 -0
  87. package/dist/sandbox-readiness.d.ts +8 -0
  88. package/dist/sandbox-readiness.d.ts.map +1 -0
  89. package/dist/skills/built-in.d.ts +15 -0
  90. package/dist/skills/built-in.d.ts.map +1 -0
  91. package/dist/subagent-continuation.d.ts +27 -0
  92. package/dist/subagent-continuation.d.ts.map +1 -0
  93. package/dist/subagent-inbox.d.ts +53 -0
  94. package/dist/subagent-inbox.d.ts.map +1 -0
  95. package/dist/subagent-tools.d.ts +282 -0
  96. package/dist/subagent-tools.d.ts.map +1 -0
  97. package/dist/thread-context.d.ts +12 -0
  98. package/dist/thread-context.d.ts.map +1 -0
  99. package/dist/tools/attachments.d.ts +11 -0
  100. package/dist/tools/attachments.d.ts.map +1 -0
  101. package/dist/tools/bash.d.ts +60 -0
  102. package/dist/tools/bash.d.ts.map +1 -0
  103. package/dist/tools/model-spec.d.ts +4 -0
  104. package/dist/tools/model-spec.d.ts.map +1 -0
  105. package/dist/tools/read.d.ts +43 -0
  106. package/dist/tools/read.d.ts.map +1 -0
  107. package/dist/tools/result-media.d.ts +22 -0
  108. package/dist/tools/result-media.d.ts.map +1 -0
  109. package/dist/tools/result-output.d.ts +18 -0
  110. package/dist/tools/result-output.d.ts.map +1 -0
  111. package/dist/tools/tool-files.d.ts +59 -0
  112. package/dist/tools/tool-files.d.ts.map +1 -0
  113. package/dist/tools/view-file.d.ts +40 -0
  114. package/dist/tools/view-file.d.ts.map +1 -0
  115. package/dist/tsconfig.json +5 -0
  116. package/dist/turn-runtime.d.ts +19 -0
  117. package/dist/turn-runtime.d.ts.map +1 -0
  118. package/dist/types.d.ts +76 -0
  119. package/dist/types.d.ts.map +1 -0
  120. package/dist/workflow-input-attachments.d.ts +18 -0
  121. package/dist/workflow-input-attachments.d.ts.map +1 -0
  122. package/package.json +59 -4
  123. package/src/abort.ts +40 -0
  124. package/src/agent-prompt.ts +758 -0
  125. package/src/agent-runtime/errors.ts +44 -0
  126. package/src/agent-runtime/preflight.ts +314 -0
  127. package/src/agent-runtime/profile.ts +23 -0
  128. package/src/artifacts/layout-check/check.cjs +478 -0
  129. package/src/artifacts/layout-check/layout-check.ts +460 -0
  130. package/src/artifacts/materialize.ts +380 -0
  131. package/src/artifacts/publish-tool.ts +700 -0
  132. package/src/ask-parent-tool.ts +100 -0
  133. package/src/attachments.ts +850 -0
  134. package/src/child-files.ts +540 -0
  135. package/src/child-questions.ts +42 -0
  136. package/src/computer-runner.ts +284 -0
  137. package/src/context-budget.ts +161 -0
  138. package/src/context-compaction.ts +529 -0
  139. package/src/conversation-memory.ts +45 -0
  140. package/src/errors.ts +85 -0
  141. package/src/execution-plan.ts +50 -0
  142. package/src/failure.ts +71 -0
  143. package/src/family-mailbox.ts +189 -0
  144. package/src/file-ref.ts +18 -0
  145. package/src/image-attachments.ts +322 -0
  146. package/src/index.ts +54 -0
  147. package/src/message-authors.ts +77 -0
  148. package/src/message-times.ts +21 -0
  149. package/src/model-adapters.ts +227 -0
  150. package/src/model-lines.ts +28 -0
  151. package/src/requester.ts +21 -0
  152. package/src/run-agent-turn.ts +347 -0
  153. package/src/run-child.ts +319 -0
  154. package/src/run-conversation-turn.ts +257 -0
  155. package/src/run-credential.ts +55 -0
  156. package/src/run-environment.ts +769 -0
  157. package/src/run-fate.ts +51 -0
  158. package/src/run-sandbox.ts +63 -0
  159. package/src/run-subagent.ts +347 -0
  160. package/src/run-workflow-agent-node.ts +270 -0
  161. package/src/sandbox-api-context.ts +234 -0
  162. package/src/sandbox-file-registry.ts +26 -0
  163. package/src/sandbox-files.ts +326 -0
  164. package/src/sandbox-handle.ts +19 -0
  165. package/src/sandbox-readiness.ts +22 -0
  166. package/src/skills/built-in.ts +183 -0
  167. package/src/skills/sixb-artifacts/SKILL.md +95 -0
  168. package/src/skills/sixb-artifacts/canvas.md +104 -0
  169. package/src/skills/sixb-artifacts/document.md +63 -0
  170. package/src/skills/sixb-artifacts/examples/canvas/onboarding-flow/boards/first-job.html +42 -0
  171. package/src/skills/sixb-artifacts/examples/canvas/onboarding-flow/boards/region.html +29 -0
  172. package/src/skills/sixb-artifacts/examples/canvas/onboarding-flow/boards/shared.css +35 -0
  173. package/src/skills/sixb-artifacts/examples/canvas/onboarding-flow/boards/welcome.html +31 -0
  174. package/src/skills/sixb-artifacts/examples/canvas/onboarding-flow/canvas.json +107 -0
  175. package/src/skills/sixb-artifacts/examples/canvas/retro/canvas.json +158 -0
  176. package/src/skills/sixb-artifacts/examples/document/incident-report/document.md +35 -0
  177. package/src/skills/sixb-artifacts/examples/document/operations-review/document.md +41 -0
  178. package/src/skills/sixb-artifacts/examples/document/operations-review/figures/restorations.svg +1 -0
  179. package/src/skills/sixb-artifacts/examples/page/collections-desk/index.html +169 -0
  180. package/src/skills/sixb-artifacts/examples/page/collections-desk/queries/overdue.json +13 -0
  181. package/src/skills/sixb-artifacts/examples/page/dispatch-board/data/dispatch.json +234 -0
  182. package/src/skills/sixb-artifacts/examples/page/dispatch-board/index.html +245 -0
  183. package/src/skills/sixb-artifacts/examples/page/fleet-planner/data/plan.json +53 -0
  184. package/src/skills/sixb-artifacts/examples/page/fleet-planner/index.html +462 -0
  185. package/src/skills/sixb-artifacts/examples/page/service-explorer/data/service.json +276 -0
  186. package/src/skills/sixb-artifacts/examples/page/service-explorer/index.html +549 -0
  187. package/src/skills/sixb-artifacts/examples/sheet/overdue-invoices/queries/overdue.json +13 -0
  188. package/src/skills/sixb-artifacts/examples/sheet/overdue-invoices/workbook.json +30 -0
  189. package/src/skills/sixb-artifacts/examples/sheet/parts-inventory/sheets/Inventory.csv +13 -0
  190. package/src/skills/sixb-artifacts/examples/sheet/parts-inventory/sheets/Spend.csv +6 -0
  191. package/src/skills/sixb-artifacts/examples/sheet/parts-inventory/workbook.json +47 -0
  192. package/src/skills/sixb-artifacts/examples/sheet/service-metrics/sheets/Quarters.csv +5 -0
  193. package/src/skills/sixb-artifacts/examples/sheet/service-metrics/sheets/Regions.csv +5 -0
  194. package/src/skills/sixb-artifacts/examples/sheet/service-metrics/workbook.json +78 -0
  195. package/src/skills/sixb-artifacts/examples/slides/launch-plan/index.html +63 -0
  196. package/src/skills/sixb-artifacts/examples/slides/q3-review/index.html +133 -0
  197. package/src/skills/sixb-artifacts/file.md +17 -0
  198. package/src/skills/sixb-artifacts/page.md +215 -0
  199. package/src/skills/sixb-artifacts/queries.md +66 -0
  200. package/src/skills/sixb-artifacts/references.md +68 -0
  201. package/src/skills/sixb-artifacts/sheet.md +223 -0
  202. package/src/skills/sixb-artifacts/slides.md +137 -0
  203. package/src/skills/sixb-memory/SKILL.md +68 -0
  204. package/src/skills/text-assets.d.ts +25 -0
  205. package/src/subagent-continuation.ts +51 -0
  206. package/src/subagent-inbox.ts +101 -0
  207. package/src/subagent-tools.ts +1609 -0
  208. package/src/thread-context.ts +25 -0
  209. package/src/tools/attachments.ts +28 -0
  210. package/src/tools/bash.ts +217 -0
  211. package/src/tools/model-spec.ts +22 -0
  212. package/src/tools/read.ts +262 -0
  213. package/src/tools/result-media.ts +147 -0
  214. package/src/tools/result-output.ts +44 -0
  215. package/src/tools/tool-files.ts +204 -0
  216. package/src/tools/view-file.ts +155 -0
  217. package/src/turn-runtime.ts +33 -0
  218. package/src/types.ts +79 -0
  219. package/src/workflow-input-attachments.ts +140 -0
@@ -0,0 +1,147 @@
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 { isAgentToolResult } from "@sixb/core/internal/agents"
8
+ import { modelSupportsInlineImages, prepareAgentToolFileProjection } from "../attachments"
9
+ import { fileContentKey } from "../file-ref"
10
+ import { type AgentToolModelOutput, agentToolResultToModelOutput } from "./result-output"
11
+
12
+ const TOOL_RESULT_IMAGE_OMISSION_NOTE =
13
+ "[Image is not embedded in the tool-result message; Sixb supplies it as a separate model input when the selected model supports images.]"
14
+
15
+ interface PendingToolFile {
16
+ readonly fileRef: FileRef
17
+ readonly signal: AbortSignal
18
+ readonly toolCallId: string
19
+ }
20
+
21
+ /** Move tool-created images into an ephemeral user message without changing their durable result. */
22
+ export class AgentToolResultMediaBridge {
23
+ readonly #pending: PendingToolFile[] = []
24
+
25
+ constructor(
26
+ private readonly input: {
27
+ readonly blobStorage: AgentRunFileStore
28
+ readonly sandboxPathForFileRef?: (fileRef: FileRef) => string | undefined
29
+ /** Test seam; production uses the bounded attachment projector. */
30
+ readonly projectFile?: typeof prepareAgentToolFileProjection
31
+ }
32
+ ) {}
33
+
34
+ async toModelOutput(input: {
35
+ readonly output: JsonValue
36
+ readonly signal: AbortSignal
37
+ readonly toolCallId: string
38
+ }): Promise<AgentToolModelOutput> {
39
+ input.signal.throwIfAborted()
40
+ const output = await agentToolResultToModelOutput({
41
+ output: input.output,
42
+ blobStorage: this.input.blobStorage,
43
+ signal: input.signal,
44
+ ...(this.input.sandboxPathForFileRef === undefined
45
+ ? {}
46
+ : { sandboxPathForFileRef: this.input.sandboxPathForFileRef }),
47
+ imageOmissionNote: TOOL_RESULT_IMAGE_OMISSION_NOTE,
48
+ })
49
+
50
+ if (isAgentToolResult(input.output)) {
51
+ for (const contentPart of input.output.content) {
52
+ if (contentPart.type === "file" && isImageFile(contentPart.fileRef)) {
53
+ this.#pending.push({
54
+ fileRef: contentPart.fileRef,
55
+ signal: input.signal,
56
+ toolCallId: input.toolCallId,
57
+ })
58
+ }
59
+ }
60
+ }
61
+ return output
62
+ }
63
+
64
+ readonly prepareStep = async ({
65
+ messages,
66
+ model,
67
+ signal: stepSignal,
68
+ }: PrepareModelStepInput): Promise<PrepareModelStepResult | undefined> => {
69
+ if (this.#pending.length === 0) return undefined
70
+
71
+ const pending = this.#pending.slice()
72
+ const signal = combinedSignal(pending, stepSignal)
73
+ signal.throwIfAborted()
74
+ const supportsImages = modelSupportsInlineImages(model)
75
+ if (!supportsImages) {
76
+ this.#pending.splice(0, pending.length)
77
+ return undefined
78
+ }
79
+
80
+ const seen = new Set<string>()
81
+ const content: Array<
82
+ | { readonly type: "text"; readonly text: string }
83
+ | {
84
+ readonly type: "file"
85
+ readonly data: URL
86
+ readonly mediaType: string
87
+ readonly filename?: string
88
+ }
89
+ > = []
90
+ const toolCallIds: string[] = []
91
+ for (const item of pending) {
92
+ item.signal.throwIfAborted()
93
+ const identity = fileContentKey(item.fileRef)
94
+ if (seen.has(identity)) continue
95
+ seen.add(identity)
96
+
97
+ const sandboxPath = this.input.sandboxPathForFileRef?.(item.fileRef)
98
+ const projection = await (this.input.projectFile ?? prepareAgentToolFileProjection)({
99
+ fileRef: item.fileRef,
100
+ blobStorage: this.input.blobStorage,
101
+ inlineImages: true,
102
+ signal: item.signal,
103
+ ...(sandboxPath === undefined ? {} : { sandboxPath }),
104
+ })
105
+ if (!projection.modelFileData) continue
106
+
107
+ toolCallIds.push(item.toolCallId)
108
+ content.push({
109
+ type: "file",
110
+ data: projection.modelFileData.data,
111
+ mediaType:
112
+ projection.modelFileData.mediaType ??
113
+ item.fileRef.mediaType ??
114
+ "application/octet-stream",
115
+ ...(projection.modelFileData.filename === undefined
116
+ ? {}
117
+ : { filename: projection.modelFileData.filename }),
118
+ })
119
+ }
120
+
121
+ this.#pending.splice(0, pending.length)
122
+ if (content.length === 0) return undefined
123
+ content.unshift({
124
+ type: "text",
125
+ 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>`,
126
+ })
127
+ return { messages: [...messages, { role: "user", content }] }
128
+ }
129
+ }
130
+
131
+ function combinedSignal(pending: readonly PendingToolFile[], stepSignal: AbortSignal): AbortSignal {
132
+ const signals = [...new Set([stepSignal, ...pending.map((item) => item.signal)])]
133
+ return signals.length === 1 ? stepSignal : AbortSignal.any(signals)
134
+ }
135
+
136
+ function isImageFile(fileRef: FileRef): boolean {
137
+ if (fileRef.mediaType?.toLowerCase().startsWith("image/")) return true
138
+ return /\.(?:bmp|gif|jpe?g|png|webp)$/i.test(fileRef.fileName ?? fileRef.logicalPath ?? "")
139
+ }
140
+
141
+ function escapeXmlAttribute(value: string): string {
142
+ return value
143
+ .replaceAll("&", "&amp;")
144
+ .replaceAll('"', "&quot;")
145
+ .replaceAll("<", "&lt;")
146
+ .replaceAll(">", "&gt;")
147
+ }
@@ -0,0 +1,44 @@
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?: (fileRef: FileRef) => string | undefined
15
+ readonly imageOmissionNote?: string
16
+ }): Promise<AgentToolModelOutput> {
17
+ if (!isAgentToolResult(input.output)) {
18
+ return typeof input.output === "string"
19
+ ? { type: "text", value: input.output }
20
+ : { type: "json", value: input.output }
21
+ }
22
+
23
+ const text: string[] = []
24
+ for (const contentPart of input.output.content) {
25
+ if (contentPart.type === "text") {
26
+ text.push(contentPart.text)
27
+ continue
28
+ }
29
+
30
+ const sandboxPath = input.sandboxPathForFileRef?.(contentPart.fileRef)
31
+ const projection = await prepareAgentToolFileProjection({
32
+ fileRef: contentPart.fileRef,
33
+ blobStorage: input.blobStorage,
34
+ inlineImages: false,
35
+ ...(input.signal === undefined ? {} : { signal: input.signal }),
36
+ ...(sandboxPath === undefined ? {} : { sandboxPath }),
37
+ ...(input.imageOmissionNote === undefined
38
+ ? {}
39
+ : { imageOmissionNote: input.imageOmissionNote }),
40
+ })
41
+ text.push(projection.promptText)
42
+ }
43
+ return { type: "text", value: text.join("\n") }
44
+ }
@@ -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
+ }
@@ -0,0 +1,155 @@
1
+ import { posix } from "node:path"
2
+ import type { AgentToolFiles, FileRef, JsonValue } from "@sixb/core"
3
+ import { AgentToolPublicError } from "@sixb/core"
4
+ import { inferFileMediaType } from "@sixb/core/internal/blob-storage"
5
+ import type { JsonObject, ModelTool } from "@sixb/core/models"
6
+ import type { PreparedAgentAttachmentContext } from "../attachments"
7
+ import { agentToolErrorText } from "../model-adapters"
8
+ import type { AgentSandboxFileRegistry } from "../sandbox-file-registry"
9
+ import { readSandboxFile, resolveSandboxPath, SandboxFileError } from "../sandbox-files"
10
+ import type { AgentSandboxHandle } from "../sandbox-handle"
11
+ import type { AgentToolModelOutput } from "./result-output"
12
+ import { AGENT_FILE_MAX_BYTES } from "./tool-files"
13
+
14
+ const VIEW_FILE_TIMEOUT_MS = 30_000
15
+
16
+ export const VIEW_FILE_TOOL_SPEC = {
17
+ name: "view_file",
18
+ description:
19
+ "Inspect a file in the current run sandbox. Use this for historical attachments and files created by bash. Paths must stay inside the working directory or the run's context directory. Images are prepared for visual input when supported; other formats return bounded text or metadata.",
20
+ inputSchema: {
21
+ type: "object",
22
+ properties: { path: { type: "string", minLength: 1 } },
23
+ required: ["path"],
24
+ additionalProperties: false,
25
+ } satisfies JsonObject,
26
+ } as const
27
+
28
+ interface ViewFileInput {
29
+ readonly path: string
30
+ }
31
+
32
+ export function createViewFileTool(input: {
33
+ readonly resolveSandbox: () => Promise<AgentSandboxHandle>
34
+ readonly attachments: PreparedAgentAttachmentContext
35
+ readonly registry: AgentSandboxFileRegistry
36
+ readonly filesForToolCall: (options: {
37
+ readonly toolCallId: string
38
+ readonly signal: AbortSignal
39
+ }) => AgentToolFiles
40
+ readonly toolResultToModelOutput: (input: {
41
+ readonly output: JsonValue
42
+ readonly signal: AbortSignal
43
+ readonly toolCallId: string
44
+ }) => AgentToolModelOutput | Promise<AgentToolModelOutput>
45
+ }): ModelTool<ViewFileInput> {
46
+ return {
47
+ ...VIEW_FILE_TOOL_SPEC,
48
+ parseInput: parseViewFileInput,
49
+ async execute({ path }, { signal, toolCallId }): Promise<JsonValue> {
50
+ signal.throwIfAborted()
51
+ const handle = await input.resolveSandbox()
52
+ let absolutePath: string
53
+ try {
54
+ absolutePath = resolveSandboxPath(handle, path)
55
+ } catch (error) {
56
+ throw toViewFileError(error)
57
+ }
58
+ const knownFileRef =
59
+ input.registry.get(absolutePath) ??
60
+ preparedFileRefAtPath(input.attachments, handle.sandbox.workingDirectory, absolutePath)
61
+
62
+ let fileRef: FileRef
63
+ if (knownFileRef) {
64
+ fileRef = knownFileRef
65
+ } else {
66
+ const bytes = await readSandboxFile(handle, {
67
+ path: absolutePath,
68
+ maxBytes: AGENT_FILE_MAX_BYTES,
69
+ signal,
70
+ timeoutMs: VIEW_FILE_TIMEOUT_MS,
71
+ }).catch((error: unknown) => {
72
+ throw toViewFileError(error)
73
+ })
74
+ const fileName = safePublishedFileName(posix.basename(absolutePath))
75
+ const file = await input.filesForToolCall({ toolCallId, signal }).put({
76
+ body: bytes,
77
+ fileName,
78
+ mediaType: inferFileMediaType(fileName, bytes),
79
+ })
80
+ fileRef = file.fileRef
81
+ }
82
+
83
+ // Prepared attachments and files tools stored are immutable snapshots and can be reused.
84
+ // Arbitrary bash paths stay mutable, so do not cache their published snapshot at the source
85
+ // path; a later view_file call must read the path again.
86
+ if (knownFileRef) input.registry.register(absolutePath, fileRef)
87
+ return richViewFileResult(fileRef)
88
+ },
89
+ toModelOutput(output, { toolCallId, signal }) {
90
+ return input.toolResultToModelOutput({ output, toolCallId, signal })
91
+ },
92
+ errorText: agentToolErrorText,
93
+ }
94
+ }
95
+
96
+ function parseViewFileInput(value: unknown): ViewFileInput {
97
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
98
+ throw viewFileError("input must be an object")
99
+ }
100
+ const input = value as Record<string, unknown>
101
+ if (Object.keys(input).some((key) => key !== "path")) {
102
+ throw viewFileError("input contains an unknown property")
103
+ }
104
+ if (typeof input.path !== "string") throw viewFileError("path must be a string")
105
+ return { path: input.path }
106
+ }
107
+
108
+ function preparedFileRefAtPath(
109
+ attachments: PreparedAgentAttachmentContext,
110
+ workingDirectory: string,
111
+ absolutePath: string
112
+ ): FileRef | undefined {
113
+ for (const file of attachments.sandboxFiles) {
114
+ if (posix.resolve(workingDirectory, file.path) === absolutePath) {
115
+ return file.fileRef
116
+ }
117
+ }
118
+ return undefined
119
+ }
120
+
121
+ function richViewFileResult(fileRef: FileRef): JsonValue {
122
+ const mediaType = fileRef.mediaType ?? "application/octet-stream"
123
+ const fileName = fileRef.fileName ?? "file"
124
+ const description = mediaType.startsWith("image/")
125
+ ? `Prepared image '${fileName}' for inspection.`
126
+ : `Prepared file '${fileName}' (${mediaType}) for inspection.`
127
+ return {
128
+ kind: "agentToolResult",
129
+ content: [
130
+ {
131
+ type: "text",
132
+ text: `${description} Size: ${fileRef.sizeBytes} bytes.`,
133
+ },
134
+ { type: "file", fileRef: { ...fileRef } },
135
+ ],
136
+ }
137
+ }
138
+
139
+ function safePublishedFileName(value: string): string {
140
+ const safe = value
141
+ .normalize("NFKC")
142
+ .replace(/[\u0000-\u001f\u007f]/g, "_")
143
+ .replace(/[\\/]/g, "_")
144
+ .slice(0, 120)
145
+ return safe && safe !== "." && safe !== ".." ? safe : "viewed-file.bin"
146
+ }
147
+
148
+ /** A sandbox file refusal becomes the message the Agent sees; anything else passes through. */
149
+ function toViewFileError(error: unknown): unknown {
150
+ return error instanceof SandboxFileError ? viewFileError(error.message) : error
151
+ }
152
+
153
+ function viewFileError(message: string): AgentToolPublicError {
154
+ return new AgentToolPublicError(`[SixbAgent] view_file ${message}.`)
155
+ }
@@ -0,0 +1,33 @@
1
+ import { throwIfExecutionLost } from "./errors"
2
+
3
+ export interface AgentTurnRuntime {
4
+ /** Worker shutdown, queue-lease loss, and user cancellation. */
5
+ readonly sourceSignal: AbortSignal
6
+ /** The run's signal: `sourceSignal`, and the run's end. */
7
+ readonly signal: AbortSignal
8
+ /** Surface lost ownership or cancellation before another durable action. */
9
+ readonly assertCanContinue: () => void
10
+ /** End the run: aborts `signal`, so a tool call that outlived it stops calling models. */
11
+ dispose(): void
12
+ }
13
+
14
+ /**
15
+ * The run's signal, shared by its compaction and its answer. A run has no time or step limit: it
16
+ * ends when the model answers, when it is cancelled, or when its runner loses it. Its model records
17
+ * each call itself, so a call that could not be admitted or recorded fails where it was made.
18
+ */
19
+ export function createAgentTurnRuntime(input: { readonly signal: AbortSignal }): AgentTurnRuntime {
20
+ const ended = new AbortController()
21
+
22
+ return {
23
+ sourceSignal: input.signal,
24
+ signal: AbortSignal.any([input.signal, ended.signal]),
25
+ assertCanContinue() {
26
+ throwIfExecutionLost(input.signal)
27
+ input.signal.throwIfAborted()
28
+ },
29
+ dispose() {
30
+ ended.abort(new DOMException("The Agent run has ended.", "AbortError"))
31
+ },
32
+ }
33
+ }
package/src/types.ts ADDED
@@ -0,0 +1,79 @@
1
+ import type { AuthorizablePrincipal } from "@sixb/core"
2
+ import type { AgentRunFileStore, RunModelLoopInput } from "@sixb/core/internal/agents"
3
+ import type { ModelTool } from "@sixb/core/models"
4
+ import type { PreparedAgentAttachmentContext } from "./attachments"
5
+ import type { AgentRequester } from "./requester"
6
+ import type { BeforeFinalizeOptions } from "./run-sandbox"
7
+ import type { AgentSandboxHandle } from "./sandbox-handle"
8
+ import type { AgentFileBudget } from "./tools/tool-files"
9
+
10
+ /**
11
+ * What every run of a project shares, whichever runner runs it: its settings. A run reaches the
12
+ * project through its session, never through storage, the project's SDK or its definitions.
13
+ */
14
+ export interface AgentRunSettings {
15
+ /** The project id. */
16
+ readonly id: string
17
+ /** The Sixb API origin the run's commands call, through their environment's credentialed address. */
18
+ readonly apiBaseUrl: string
19
+ /** How many children one conversation turn may have queued or running at once. */
20
+ readonly subagentConcurrencyPerRun: number
21
+ /** Whether a child keeps its workspace between runs: its environment can be resumed. */
22
+ readonly keepsChildWorkspaces: boolean
23
+ /** Project locale and time zone, for runs that do not carry the requester's own. */
24
+ readonly locale: string
25
+ readonly timeZone: string
26
+ }
27
+
28
+ /** A run's settings, with who it works for and where its files are stored. */
29
+ export interface AgentExecutionContext extends AgentRunSettings {
30
+ readonly authorPrincipal?: AuthorizablePrincipal
31
+ /**
32
+ * Who the run works for; absent when no principal started its chain of executions, or in a
33
+ * shared thread, where each user message names its author instead.
34
+ */
35
+ readonly requester?: AgentRequester
36
+ readonly blobStorage: AgentRunFileStore
37
+ }
38
+
39
+ export interface AgentTurnContext {
40
+ /** Environment-owned failure (for example lost source credentials), not user cancellation. */
41
+ readonly environmentFailureSignal?: AbortSignal
42
+ /** Persistent environments must confirm cleanup/save before any terminal write. */
43
+ readonly beforeFinalize?: (options?: BeforeFinalizeOptions) => Promise<void>
44
+ readonly id: string
45
+ readonly authorPrincipal?: AuthorizablePrincipal
46
+ readonly blobStorage: AgentRunFileStore
47
+ /** The Sixb API the run's commands call, when this turn was created through a run environment. */
48
+ readonly apiBaseUrl?: string
49
+ readonly tools: readonly ModelTool[]
50
+ readonly prepareStep?: RunModelLoopInput["prepareStep"]
51
+ /** Complete worker-owned system prompt, derived from the mode and provisioned runtime. */
52
+ readonly systemPrompt: string
53
+ /** Time zone of runs that captured none, used to date their user messages. */
54
+ readonly projectTimeZone: string
55
+ /** Prepared by the run's environment, which materializes the files in its context directory. */
56
+ readonly attachmentContext?: PreparedAgentAttachmentContext
57
+ /**
58
+ * The concurrently provisioning sandbox, exposed so the turn can fail if it rejects. Resolved
59
+ * value is irrelevant here (the sandbox tools consume the handle); only its rejection matters.
60
+ */
61
+ readonly sandboxReady?: Promise<AgentSandboxHandle>
62
+ }
63
+
64
+ /**
65
+ * A run's sandbox and its stored files, as its framework tools use them: a parent hands files to
66
+ * its children and gets theirs back, a child returns what it wrote.
67
+ */
68
+ export interface AgentRunFiles {
69
+ sandbox(): Promise<AgentSandboxHandle>
70
+ readonly blobStorage: AgentRunFileStore
71
+ /** Shared with every other file the run stores. */
72
+ readonly budget: AgentFileBudget
73
+ /**
74
+ * Install the latest version of each artifact these runs published in the thread in the run's
75
+ * `$SIXB_ARTIFACTS`; nothing for a run that installs no artifacts. Throws, naming them, when
76
+ * some could not be installed.
77
+ */
78
+ installArtifactsFrom(runIds: readonly string[], signal: AbortSignal): Promise<void>
79
+ }