@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,31 @@
1
+ import {
2
+ type AgentThreadModelContextMessage,
3
+ type AgentTurnHistory,
4
+ projectAgentThreadModelContext,
5
+ } from "@sixb/core/internal/agents"
6
+ import type { AgentContextCheckpointRecord, AgentMessageRecord } from "@sixb/core/storage"
7
+
8
+ export interface LoadedAgentThreadModelContext {
9
+ readonly checkpoint: AgentContextCheckpointRecord | null
10
+ readonly retainedMessages: readonly AgentMessageRecord[]
11
+ readonly modelMessages: readonly AgentThreadModelContextMessage[]
12
+ /** The history it was built from, as the session answered it. */
13
+ readonly history: AgentTurnHistory
14
+ }
15
+
16
+ /**
17
+ * The retained tail with its checkpoint, projected for the model. A child's run reads its thread
18
+ * without `historyReadable`: `sixb history` prints only a conversation's.
19
+ */
20
+ export function agentThreadModelContext(
21
+ history: AgentTurnHistory,
22
+ options: { readonly historyReadable?: boolean } = {}
23
+ ): LoadedAgentThreadModelContext {
24
+ const { checkpoint, messages } = history
25
+ return {
26
+ checkpoint,
27
+ retainedMessages: messages,
28
+ modelMessages: projectAgentThreadModelContext({ checkpoint, messages, ...options }),
29
+ history,
30
+ }
31
+ }
@@ -0,0 +1,28 @@
1
+ import { type AgentToolAttachments, AgentToolPublicError } from "@sixb/core"
2
+ import type { AgentRunFileStore } from "@sixb/core/internal/agents"
3
+ import { openFileRef } from "@sixb/core/internal/blob-storage"
4
+ import type { WorkflowIOSnapshot } from "@sixb/core/internal/workflows"
5
+ import { workflowInputFileRefs } from "../workflow-input-attachments"
6
+
7
+ type AttachmentBlobStorage = Pick<AgentRunFileStore, "stat" | "open">
8
+
9
+ /** A workflow AI task's attachments: the files of its input, by their path such as `input.pdf`. */
10
+ export function workflowInputToolAttachments(input: {
11
+ readonly input: WorkflowIOSnapshot
12
+ readonly blobStorage: AttachmentBlobStorage
13
+ }): AgentToolAttachments {
14
+ const fileRefs = new Map(workflowInputFileRefs(input.input).map((ref) => [ref.path, ref.fileRef]))
15
+ return {
16
+ async open(key) {
17
+ const fileRef = fileRefs.get(key)
18
+ if (!fileRef) throw unknownAttachment(key)
19
+ return openFileRef(input.blobStorage, fileRef)
20
+ },
21
+ }
22
+ }
23
+
24
+ function unknownAttachment(key: string): AgentToolPublicError {
25
+ return new AgentToolPublicError(
26
+ `[SixbAgent] '${key}' is not an attachment of this run. Pass a key listed in $SIXB_ATTACHMENTS.`
27
+ )
28
+ }
@@ -0,0 +1,233 @@
1
+ import type { CommandResult } from "@sixb/core"
2
+ import type { JsonObject, JsonValue, ModelTool } from "@sixb/core/models"
3
+ import type { AgentSandboxHandle } from "../sandbox-handle"
4
+
5
+ const DEFAULT_COMMAND_TIMEOUT_MS = 30_000
6
+ const MAX_COMMAND_TIMEOUT_MS = 120_000
7
+ const DEFAULT_MAX_OUTPUT_CHARS = 20_000
8
+
9
+ export const BASH_TOOL_SPEC = {
10
+ name: "bash",
11
+ description: "Run a Bash command in the agent run sandbox.",
12
+ inputSchema: {
13
+ type: "object",
14
+ properties: {
15
+ command: { type: "string" },
16
+ cwd: {
17
+ type: "string",
18
+ description:
19
+ "Directory to run the command in. Defaults to the sandbox workspace. Accepts absolute paths or paths relative to the workspace.",
20
+ },
21
+ timeoutMs: { type: "number" },
22
+ },
23
+ required: ["command"],
24
+ additionalProperties: false,
25
+ } satisfies JsonObject,
26
+ } as const
27
+
28
+ interface BashToolInput {
29
+ readonly command: string
30
+ readonly cwd?: string
31
+ readonly timeoutMs?: number
32
+ }
33
+
34
+ export interface BashToolOutput extends CommandResult {
35
+ readonly stdoutTruncated: boolean
36
+ readonly stderrTruncated: boolean
37
+ }
38
+
39
+ /**
40
+ * Build the bash tool from a resolver that yields the sandbox on demand. The
41
+ * resolver is awaited on the first command, not at tool-construction time, so
42
+ * sandbox creation can run concurrently with the model's first response instead
43
+ * of blocking the turn. A resolver rejection surfaces as a failed command.
44
+ *
45
+ * Its output holds the command's streams whole: the run's tools save an output too large for the
46
+ * context to a file and keep {@link keptCommandOutput} of it (see tool-outputs.ts).
47
+ */
48
+ export function createBashTool(
49
+ resolveSandbox: () => Promise<AgentSandboxHandle>
50
+ ): ModelTool<BashToolInput> {
51
+ return {
52
+ ...BASH_TOOL_SPEC,
53
+ parseInput: parseBashToolInput,
54
+ async execute(input, { signal }): Promise<JsonValue> {
55
+ const { sandbox, env } = await resolveSandbox()
56
+ const result = await sandbox.runCommand("bash", ["-lc", input.command], {
57
+ cwd: input.cwd,
58
+ env,
59
+ timeout: normalizeTimeout(input.timeoutMs),
60
+ signal,
61
+ })
62
+ const output: BashToolOutput = {
63
+ ...result,
64
+ stdoutTruncated: false,
65
+ stderrTruncated: false,
66
+ }
67
+ return output as unknown as JsonValue
68
+ },
69
+ errorText: () => "The command failed.",
70
+ }
71
+ }
72
+
73
+ function parseBashToolInput(value: unknown): BashToolInput {
74
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
75
+ throw new TypeError("Bash tool input must be an object.")
76
+ }
77
+ const input = value as Record<string, unknown>
78
+ if (typeof input.command !== "string" || input.command.length === 0) {
79
+ throw new TypeError("Bash tool input.command must be a non-empty string.")
80
+ }
81
+ if (input.cwd !== undefined && typeof input.cwd !== "string") {
82
+ throw new TypeError("Bash tool input.cwd must be a string when provided.")
83
+ }
84
+ if (input.timeoutMs !== undefined && typeof input.timeoutMs !== "number") {
85
+ throw new TypeError("Bash tool input.timeoutMs must be a number when provided.")
86
+ }
87
+ for (const key of Object.keys(input)) {
88
+ if (key !== "command" && key !== "cwd" && key !== "timeoutMs") {
89
+ throw new TypeError(`Bash tool input contains unknown property '${key}'.`)
90
+ }
91
+ }
92
+ return {
93
+ command: input.command,
94
+ ...(input.cwd === undefined ? {} : { cwd: input.cwd }),
95
+ ...(input.timeoutMs === undefined ? {} : { timeoutMs: input.timeoutMs }),
96
+ }
97
+ }
98
+
99
+ function normalizeTimeout(timeoutMs: number | undefined): number {
100
+ if (timeoutMs === undefined || !Number.isFinite(timeoutMs) || timeoutMs <= 0) {
101
+ return DEFAULT_COMMAND_TIMEOUT_MS
102
+ }
103
+ return Math.min(Math.floor(timeoutMs), MAX_COMMAND_TIMEOUT_MS)
104
+ }
105
+
106
+ /**
107
+ * What a command's message part keeps of an output saved to a file: each stream within
108
+ * 20,000 characters, as the app, the TUI and `sixb history` show it.
109
+ */
110
+ export function keptCommandOutput(output: CommandResult): BashToolOutput {
111
+ return truncateCommandResult(output)
112
+ }
113
+
114
+ function truncateCommandResult(result: CommandResult): BashToolOutput {
115
+ // stdout is usually a Sixb API JSON response: compact it (and, if still oversized, keep a valid
116
+ // structural prefix) so both the model and the chat UI receive parseable JSON rather than a body
117
+ // cut mid-structure. stderr is diagnostics, so it just gets a lossless-in-the-middle text trim.
118
+ const stdout = compressStdout(result.stdout, DEFAULT_MAX_OUTPUT_CHARS)
119
+ const stderr = truncateText(result.stderr, DEFAULT_MAX_OUTPUT_CHARS)
120
+ return {
121
+ ...result,
122
+ stdout: stdout.text,
123
+ stderr: stderr.text,
124
+ stdoutTruncated: stdout.truncated,
125
+ stderrTruncated: stderr.truncated,
126
+ }
127
+ }
128
+
129
+ interface TruncateResult {
130
+ readonly text: string
131
+ readonly truncated: boolean
132
+ }
133
+
134
+ /**
135
+ * Fit a command's stdout under `maxChars`, preferring to keep it valid JSON.
136
+ *
137
+ * The agent's commands (and any `jq` pretty-printing it adds) mostly produce JSON API responses. We
138
+ * compress in the order the field recommends — reformat first, drop data only if we must:
139
+ * 1. Under budget already → leave it untouched.
140
+ * 2. Valid JSON → re-serialize compact; whitespace alone often brings it under budget with zero
141
+ * data loss (compact JSON is also fewer tokens and no worse for model comprehension).
142
+ * 3. Still oversized JSON array → keep the largest whole-element prefix that fits, as a bare array
143
+ * (same shape the caller expects, still valid JSON, just fewer rows).
144
+ * 4. Oversized JSON object → return a valid JSON preview that tells the agent to narrow the call.
145
+ * 5. Oversized non-JSON → middle-truncate the text.
146
+ */
147
+ export function compressStdout(text: string, maxChars: number): TruncateResult {
148
+ if (text.length <= maxChars) return { text, truncated: false }
149
+
150
+ const json = tryParseJsonDocument(text)
151
+ if (json !== undefined) {
152
+ const compact = JSON.stringify(json)
153
+ if (compact.length <= maxChars) return { text: compact, truncated: false }
154
+ if (Array.isArray(json)) return { text: fitJsonArrayPrefix(json, maxChars), truncated: true }
155
+ if (typeof json === "object" && json !== null) {
156
+ return { text: fitJsonObjectPreview(json, compact, maxChars), truncated: true }
157
+ }
158
+ return truncateText(compact, maxChars)
159
+ }
160
+
161
+ return truncateText(text, maxChars)
162
+ }
163
+
164
+ /** A parseable diagnostic plus as much leading source JSON as the budget allows. */
165
+ function fitJsonObjectPreview(value: object, compact: string, maxChars: number): string {
166
+ const base = {
167
+ _sixbOutputTruncated: true,
168
+ message:
169
+ "Command output exceeded the tool limit; rerun with a smaller limit or narrower query.",
170
+ topLevelKeys: Object.keys(value).slice(0, 50),
171
+ preview: "",
172
+ }
173
+ if (JSON.stringify(base).length > maxChars) {
174
+ const minimal = JSON.stringify({ _sixbOutputTruncated: true })
175
+ return minimal.length <= maxChars ? minimal : "{}"
176
+ }
177
+
178
+ let low = 0
179
+ let high = compact.length
180
+ let best = ""
181
+ while (low <= high) {
182
+ const length = (low + high) >> 1
183
+ const candidate = JSON.stringify({ ...base, preview: compact.slice(0, length) })
184
+ if (candidate.length <= maxChars) {
185
+ best = candidate
186
+ low = length + 1
187
+ } else {
188
+ high = length - 1
189
+ }
190
+ }
191
+ return best || JSON.stringify(base)
192
+ }
193
+
194
+ /** The largest whole-element prefix of `items` whose compact JSON fits under `maxChars`. */
195
+ function fitJsonArrayPrefix(items: readonly unknown[], maxChars: number): string {
196
+ let low = 0
197
+ let high = items.length
198
+ let best = 0
199
+ while (low <= high) {
200
+ const mid = (low + high) >> 1
201
+ if (JSON.stringify(items.slice(0, mid)).length <= maxChars) {
202
+ best = mid
203
+ low = mid + 1
204
+ } else {
205
+ high = mid - 1
206
+ }
207
+ }
208
+ return JSON.stringify(items.slice(0, best))
209
+ }
210
+
211
+ /** JSON.parse, but only for object/array documents — never a bare number/string/bool. */
212
+ function tryParseJsonDocument(text: string): unknown {
213
+ const trimmed = text.trim()
214
+ if (!trimmed.startsWith("{") && !trimmed.startsWith("[")) return undefined
215
+ try {
216
+ return JSON.parse(trimmed)
217
+ } catch {
218
+ return undefined
219
+ }
220
+ }
221
+
222
+ /** Keep the head and tail, dropping the middle — so trailing errors and exit lines survive. */
223
+ function truncateText(text: string, maxChars: number): TruncateResult {
224
+ if (text.length <= maxChars) return { text, truncated: false }
225
+ const marker = `\n…[SixbAgent] output truncated to ${maxChars} characters]…\n`
226
+ const budget = Math.max(0, maxChars - marker.length)
227
+ const head = Math.ceil(budget / 2)
228
+ const tail = budget - head
229
+ return {
230
+ text: text.slice(0, head) + marker + (tail > 0 ? text.slice(text.length - tail) : ""),
231
+ truncated: true,
232
+ }
233
+ }
@@ -0,0 +1,27 @@
1
+ import type { AgentToolSpec } from "@sixb/core/internal/agents"
2
+ import {
3
+ PUBLISH_ARTIFACT_TOOL_SPEC,
4
+ PUBLISH_ARTIFACT_VERSION_TOOL_SPEC,
5
+ } from "../artifacts/publish-tool"
6
+ import { BASH_TOOL_SPEC } from "./bash"
7
+ import { READ_TOOL_SPEC } from "./read"
8
+ import { VIEW_FILE_TOOL_SPEC } from "./view-file"
9
+
10
+ /**
11
+ * Describe exactly the tools a conversational model receives, in its order, without starting its
12
+ * sandbox. A conversation publishes artifacts once its run executes in a thread.
13
+ */
14
+ export function agentModelToolSpecs(
15
+ projectTools: readonly AgentToolSpec[],
16
+ options: { readonly publishes?: boolean } = {}
17
+ ): readonly AgentToolSpec[] {
18
+ return [
19
+ ...projectTools,
20
+ VIEW_FILE_TOOL_SPEC,
21
+ READ_TOOL_SPEC,
22
+ BASH_TOOL_SPEC,
23
+ ...(options.publishes === false
24
+ ? []
25
+ : [PUBLISH_ARTIFACT_TOOL_SPEC, PUBLISH_ARTIFACT_VERSION_TOOL_SPEC]),
26
+ ]
27
+ }
@@ -0,0 +1,262 @@
1
+ import { posix } from "node:path"
2
+ import { AgentToolPublicError, type CommandResult } from "@sixb/core"
3
+ import type { JsonObject, JsonValue, ModelTool } from "@sixb/core/models"
4
+ import { AgentToolExecutionError } from "../errors"
5
+ import { agentToolErrorText } from "../model-adapters"
6
+ import { type AgentSandboxHandle, contextPath } from "../sandbox-handle"
7
+
8
+ const DEFAULT_LIMIT = 2_000
9
+ const MAX_BYTES = 50 * 1024
10
+ const PROBE_BYTES = MAX_BYTES + 5
11
+ const READ_TIMEOUT_MS = 30_000
12
+
13
+ export const READ_TOOL_SPEC = {
14
+ name: "read",
15
+ description:
16
+ "Read a UTF-8 text file relative to the sandbox working directory. Returns at most 2,000 lines or 50 KiB and includes nextOffset when more content remains. Prefer this over bash for reading files.",
17
+ inputSchema: {
18
+ type: "object",
19
+ properties: {
20
+ path: {
21
+ type: "string",
22
+ description:
23
+ "Path relative to the working directory, or an absolute path in the run's context directory.",
24
+ },
25
+ offset: { type: "integer", minimum: 1, description: "One-based start line. Default: 1." },
26
+ limit: {
27
+ type: "integer",
28
+ minimum: 1,
29
+ description: "Requested line count. Default and maximum: 2,000.",
30
+ },
31
+ },
32
+ required: ["path"],
33
+ additionalProperties: false,
34
+ } satisfies JsonObject,
35
+ } as const
36
+
37
+ export interface ReadToolInput {
38
+ readonly path: string
39
+ readonly offset?: number
40
+ readonly limit?: number
41
+ }
42
+
43
+ export interface ReadToolOutput {
44
+ readonly path: string
45
+ readonly content: string
46
+ readonly startLine: number
47
+ readonly endLine: number
48
+ readonly truncated: boolean
49
+ readonly nextOffset?: number
50
+ }
51
+
52
+ /** Build the bounded UTF-8 file reader from the run's lazy sandbox resolver. */
53
+ export function createReadTool(
54
+ resolveSandbox: () => Promise<AgentSandboxHandle>
55
+ ): ModelTool<ReadToolInput> {
56
+ return {
57
+ ...READ_TOOL_SPEC,
58
+ parseInput: parseReadToolInput,
59
+ async execute(input, { signal }): Promise<JsonValue> {
60
+ const path = normalizePath(input.path)
61
+ const offset = positiveInteger(input.offset, 1, "offset")
62
+ const limit = Math.min(positiveInteger(input.limit, DEFAULT_LIMIT, "limit"), DEFAULT_LIMIT)
63
+
64
+ let result: CommandResult
65
+ try {
66
+ const handle = await resolveSandbox()
67
+ const { sandbox, env } = handle
68
+ result = await sandbox.runCommand(
69
+ "bash",
70
+ [
71
+ "-c",
72
+ READ_SCRIPT,
73
+ "sixb-read",
74
+ path,
75
+ String(offset),
76
+ String(limit),
77
+ String(PROBE_BYTES),
78
+ contextPath(handle),
79
+ ],
80
+ {
81
+ cwd: sandbox.workingDirectory,
82
+ env,
83
+ timeout: READ_TIMEOUT_MS,
84
+ signal,
85
+ }
86
+ )
87
+ } catch (error) {
88
+ signal.throwIfAborted()
89
+ throw new AgentToolExecutionError("read", { cause: error })
90
+ }
91
+
92
+ signal.throwIfAborted()
93
+ if (result.exitCode !== 0) throwReadError(path, result.exitCode, result.stderr)
94
+
95
+ const page = paginate(decodeBase64(result.stdout), path, offset, limit)
96
+ const endLine = offset + page.lineCount - 1
97
+ return {
98
+ path,
99
+ content: page.content,
100
+ startLine: offset,
101
+ endLine,
102
+ truncated: page.truncated,
103
+ ...(page.truncated ? { nextOffset: endLine + 1 } : {}),
104
+ } as JsonValue
105
+ },
106
+ errorText: agentToolErrorText,
107
+ }
108
+ }
109
+
110
+ function parseReadToolInput(value: unknown): ReadToolInput {
111
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
112
+ throw publicError("input must be an object.")
113
+ }
114
+ const input = value as Record<string, unknown>
115
+ for (const key of Object.keys(input)) {
116
+ if (key !== "path" && key !== "offset" && key !== "limit") {
117
+ throw publicError(`input contains unknown property '${key}'.`)
118
+ }
119
+ }
120
+ const path = normalizePath(input.path)
121
+ const offset = input.offset === undefined ? undefined : positiveInteger(input.offset, 1, "offset")
122
+ const limit = input.limit === undefined ? undefined : positiveInteger(input.limit, 1, "limit")
123
+ return {
124
+ path,
125
+ ...(offset === undefined ? {} : { offset }),
126
+ ...(limit === undefined ? {} : { limit }),
127
+ }
128
+ }
129
+
130
+ /** The sandbox checks where a path really leads: here only its form. */
131
+ function normalizePath(value: unknown): string {
132
+ if (typeof value !== "string" || !value || value.includes("\0")) {
133
+ throw publicError("path must be a non-empty path.")
134
+ }
135
+ return posix.normalize(value)
136
+ }
137
+
138
+ function positiveInteger(value: unknown, fallback: number, field: string): number {
139
+ if (value === undefined) return fallback
140
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 1) {
141
+ throw publicError(`${field} must be a positive integer.`)
142
+ }
143
+ return value
144
+ }
145
+
146
+ function decodeBase64(value: string): Uint8Array {
147
+ const encoded = value.replace(/[\t\n\r ]/g, "")
148
+ if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(encoded)) {
149
+ throw new AgentToolExecutionError("read", { cause: new Error("Invalid sandbox output.") })
150
+ }
151
+ const bytes = Buffer.from(encoded, "base64")
152
+ if (bytes.byteLength > PROBE_BYTES) {
153
+ throw new AgentToolExecutionError("read", { cause: new Error("Oversized sandbox output.") })
154
+ }
155
+ return bytes
156
+ }
157
+
158
+ function paginate(
159
+ bytes: Uint8Array,
160
+ path: string,
161
+ offset: number,
162
+ limit: number
163
+ ): { readonly content: string; readonly lineCount: number; readonly truncated: boolean } {
164
+ if (bytes.byteLength === 0) {
165
+ if (offset > 1) throw publicError(`offset ${offset} is beyond the end of '${path}'.`)
166
+ return { content: "", lineCount: 1, truncated: false }
167
+ }
168
+ if (bytes.includes(0)) throw publicError(`'${path}' is binary, not UTF-8 text.`)
169
+
170
+ let cursor = 0
171
+ let lineCount = 0
172
+ let selectedEnd = 0
173
+ let truncated = false
174
+
175
+ while (cursor < bytes.byteLength) {
176
+ if (lineCount === limit) {
177
+ truncated = true
178
+ break
179
+ }
180
+ const newline = bytes.indexOf(10, cursor)
181
+ if (newline === -1) {
182
+ if (bytes.byteLength === PROBE_BYTES || bytes.byteLength > MAX_BYTES) {
183
+ truncated = true
184
+ break
185
+ }
186
+ lineCount += 1
187
+ selectedEnd = bytes.byteLength
188
+ cursor = bytes.byteLength
189
+ break
190
+ }
191
+ if (newline > MAX_BYTES) {
192
+ truncated = true
193
+ break
194
+ }
195
+ lineCount += 1
196
+ selectedEnd = newline
197
+ cursor = newline + 1
198
+ }
199
+
200
+ if (cursor < bytes.byteLength) truncated = true
201
+ if (lineCount === 0) {
202
+ throw publicError(`line ${offset} of '${path}' exceeds the 50 KiB read limit.`)
203
+ }
204
+
205
+ let content: string
206
+ try {
207
+ content = new TextDecoder("utf-8", { fatal: true }).decode(bytes.subarray(0, selectedEnd))
208
+ } catch {
209
+ throw publicError(`'${path}' is binary, not UTF-8 text.`)
210
+ }
211
+ return { content, lineCount, truncated }
212
+ }
213
+
214
+ function throwReadError(path: string, exitCode: number, stderr: string): never {
215
+ if (exitCode === 10) throw publicError(`'${path}' does not exist or cannot be resolved.`)
216
+ if (exitCode === 11)
217
+ throw publicError(
218
+ `'${path}' resolves outside the working directory and the run's context directory.`
219
+ )
220
+ if (exitCode === 12) throw publicError(`'${path}' is a directory, not a file.`)
221
+ if (exitCode === 13) throw publicError(`'${path}' is not a regular file.`)
222
+ if (exitCode === 14) throw publicError(`'${path}' is not readable.`)
223
+ const missingCommand = READ_COMMAND_BY_EXIT_CODE[exitCode]
224
+ if (missingCommand) {
225
+ throw publicError(`is unavailable because the sandbox image is missing '${missingCommand}'.`)
226
+ }
227
+ throw new AgentToolExecutionError("read", {
228
+ cause: new Error(stderr.trim() || `Sandbox read exited with code ${exitCode}.`),
229
+ })
230
+ }
231
+
232
+ function publicError(message: string): AgentToolPublicError {
233
+ return new AgentToolPublicError(`[SixbAgent] read ${message}`)
234
+ }
235
+
236
+ const READ_SCRIPT = `set -u
237
+ realpath_bin="$(command -v realpath)" || exit 15
238
+ tail_bin="$(command -v tail)" || exit 16
239
+ head_bin="$(command -v head)" || exit 17
240
+ base64_bin="$(command -v base64)" || exit 18
241
+ root="$(pwd -P)"
242
+ context="$root"
243
+ if [ -d "$5" ]; then context="$(cd -P -- "$5" && pwd)"; fi
244
+ case "$1" in /*) requested="$1" ;; *) requested="$root/$1" ;; esac
245
+ target="$("$realpath_bin" "$requested")" || exit 10
246
+ case "$target" in "$root"|"$root"/*|"$context"/*) ;; *) exit 11 ;; esac
247
+ [ -e "$target" ] || exit 10
248
+ [ ! -d "$target" ] || exit 12
249
+ [ -f "$target" ] || exit 13
250
+ [ -r "$target" ] || exit 14
251
+ export LC_ALL=C
252
+ "$tail_bin" -n "+$2" -- "$target" | "$head_bin" -n "$(($3 + 1))" | "$head_bin" -c "$4" | "$base64_bin"
253
+ for status in "\${PIPESTATUS[@]}"; do
254
+ case "$status" in 0|141) ;; *) exit 19 ;; esac
255
+ done`
256
+
257
+ const READ_COMMAND_BY_EXIT_CODE: Readonly<Record<number, string>> = {
258
+ 15: "realpath",
259
+ 16: "tail",
260
+ 17: "head",
261
+ 18: "base64",
262
+ }