@sixb/agent 0.1.0 → 0.2.1
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.
- package/dist/agent-prompt.d.ts +34 -28
- package/dist/agent-prompt.d.ts.map +1 -1
- package/dist/artifacts/publish-tool.d.ts +1 -1
- package/dist/attachments.d.ts +42 -1
- package/dist/attachments.d.ts.map +1 -1
- package/dist/child-files.d.ts +0 -5
- package/dist/child-files.d.ts.map +1 -1
- package/dist/computer-runner.d.ts +16 -7
- package/dist/computer-runner.d.ts.map +1 -1
- package/dist/context-budget.d.ts +23 -17
- package/dist/context-budget.d.ts.map +1 -1
- package/dist/context-compaction.d.ts +118 -18
- package/dist/context-compaction.d.ts.map +1 -1
- package/dist/context-guard.d.ts +69 -0
- package/dist/context-guard.d.ts.map +1 -0
- package/dist/conversation-messages.d.ts +33 -0
- package/dist/conversation-messages.d.ts.map +1 -0
- package/dist/execution-plan.d.ts +5 -1
- package/dist/execution-plan.d.ts.map +1 -1
- package/dist/failure.d.ts.map +1 -1
- package/dist/index.js +4916 -2697
- package/dist/index.js.map +41 -34
- package/dist/inline-images.d.ts +28 -0
- package/dist/inline-images.d.ts.map +1 -0
- package/dist/message-authors.d.ts +4 -4
- package/dist/message-authors.d.ts.map +1 -1
- package/dist/message-times.d.ts +4 -3
- package/dist/message-times.d.ts.map +1 -1
- package/dist/model-adapters.d.ts +6 -2
- package/dist/model-adapters.d.ts.map +1 -1
- package/dist/prompt-cache.d.ts +28 -0
- package/dist/prompt-cache.d.ts.map +1 -0
- package/dist/run-agent-turn.d.ts +33 -3
- package/dist/run-agent-turn.d.ts.map +1 -1
- package/dist/run-child.d.ts.map +1 -1
- package/dist/run-conversation-turn.d.ts.map +1 -1
- package/dist/run-environment.d.ts +35 -5
- package/dist/run-environment.d.ts.map +1 -1
- package/dist/run-files-lock.d.ts +16 -0
- package/dist/run-files-lock.d.ts.map +1 -0
- package/dist/run-subagent.d.ts +15 -1
- package/dist/run-subagent.d.ts.map +1 -1
- package/dist/run-workflow-agent-node.d.ts +5 -0
- package/dist/run-workflow-agent-node.d.ts.map +1 -1
- package/dist/sandbox-api-context.d.ts.map +1 -1
- package/dist/subagent-context.d.ts +50 -0
- package/dist/subagent-context.d.ts.map +1 -0
- package/dist/subagent-continuation.d.ts +10 -4
- package/dist/subagent-continuation.d.ts.map +1 -1
- package/dist/subagent-tools.d.ts +11 -0
- package/dist/subagent-tools.d.ts.map +1 -1
- package/dist/thread-context.d.ts +7 -2
- package/dist/thread-context.d.ts.map +1 -1
- package/dist/tools/bash.d.ts +8 -0
- package/dist/tools/bash.d.ts.map +1 -1
- package/dist/tools/model-spec.d.ts +7 -2
- package/dist/tools/model-spec.d.ts.map +1 -1
- package/dist/tools/result-media.d.ts +53 -10
- package/dist/tools/result-media.d.ts.map +1 -1
- package/dist/tools/result-output.d.ts +1 -1
- package/dist/tools/result-output.d.ts.map +1 -1
- package/dist/tools/tool-outputs.d.ts +63 -0
- package/dist/tools/tool-outputs.d.ts.map +1 -0
- package/dist/types.d.ts +9 -2
- package/dist/types.d.ts.map +1 -1
- package/package.json +4 -4
- package/src/agent-prompt.ts +178 -76
- package/src/attachments.ts +275 -84
- package/src/child-files.ts +1 -6
- package/src/computer-runner.ts +75 -23
- package/src/context-budget.ts +110 -94
- package/src/context-compaction.ts +1007 -187
- package/src/context-guard.ts +826 -0
- package/src/conversation-messages.ts +86 -0
- package/src/execution-plan.ts +22 -2
- package/src/failure.ts +11 -0
- package/src/inline-images.ts +69 -0
- package/src/message-authors.ts +5 -5
- package/src/message-times.ts +8 -5
- package/src/model-adapters.ts +59 -13
- package/src/prompt-cache.ts +40 -0
- package/src/run-agent-turn.ts +234 -72
- package/src/run-child.ts +30 -5
- package/src/run-conversation-turn.ts +16 -1
- package/src/run-environment.ts +553 -106
- package/src/run-files-lock.ts +118 -0
- package/src/run-subagent.ts +132 -46
- package/src/run-workflow-agent-node.ts +84 -10
- package/src/sandbox-api-context.ts +3 -0
- package/src/skills/sixb-artifacts/canvas.md +1 -1
- package/src/skills/sixb-artifacts/page.md +1 -1
- package/src/skills/sixb-artifacts/slides.md +1 -1
- package/src/subagent-context.ts +182 -0
- package/src/subagent-continuation.ts +11 -6
- package/src/subagent-tools.ts +73 -11
- package/src/thread-context.ts +9 -3
- package/src/tools/bash.ts +17 -1
- package/src/tools/model-spec.ts +9 -4
- package/src/tools/result-media.ts +286 -82
- package/src/tools/result-output.ts +4 -2
- package/src/tools/tool-outputs.ts +464 -0
- package/src/types.ts +14 -2
|
@@ -0,0 +1,464 @@
|
|
|
1
|
+
import { createHash } from "node:crypto"
|
|
2
|
+
import { posix } from "node:path"
|
|
3
|
+
import type { AgentToolResult } from "@sixb/core"
|
|
4
|
+
import {
|
|
5
|
+
AGENT_FILE_MAX_BYTES,
|
|
6
|
+
AGENT_TOOL_OUTPUTS_DIRECTORY,
|
|
7
|
+
type AgentRunFileStore,
|
|
8
|
+
type AgentToolCallFile,
|
|
9
|
+
agentToolOutputPath,
|
|
10
|
+
isAgentToolOutputFile,
|
|
11
|
+
isAgentToolResult,
|
|
12
|
+
} from "@sixb/core/internal/agents"
|
|
13
|
+
import {
|
|
14
|
+
assertJsonValue,
|
|
15
|
+
type JsonValue,
|
|
16
|
+
type ModelTool,
|
|
17
|
+
type ModelToolExecutionContext,
|
|
18
|
+
type ModelToolOutput,
|
|
19
|
+
} from "@sixb/core/models"
|
|
20
|
+
import type { AgentMessageRecord } from "@sixb/core/storage"
|
|
21
|
+
import { listSandboxFiles } from "../sandbox-files"
|
|
22
|
+
import { type AgentSandboxHandle, contextPath } from "../sandbox-handle"
|
|
23
|
+
import { BASH_TOOL_SPEC, keptCommandOutput } from "./bash"
|
|
24
|
+
import { READ_TOOL_SPEC } from "./read"
|
|
25
|
+
import { AgentFileBudget } from "./tool-files"
|
|
26
|
+
import { VIEW_FILE_TOOL_SPEC } from "./view-file"
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Past this, a tool's output reaches the model as a preview, and the whole of it as a file in the
|
|
30
|
+
* sandbox that the agent reads in pieces or searches: one result then never takes more than a few
|
|
31
|
+
* KB of the context, and nothing past a cap is lost.
|
|
32
|
+
*/
|
|
33
|
+
export const TOOL_OUTPUT_FILE_MIN_BYTES = 30 * 1024
|
|
34
|
+
|
|
35
|
+
/** Where saved outputs go, in the context directory: `$SIXB_TOOL_OUTPUTS_DIR`. */
|
|
36
|
+
export const TOOL_OUTPUTS_DIRECTORY = AGENT_TOOL_OUTPUTS_DIRECTORY
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* The preview: the head, where a listing or a document starts, and the tail, where a command's
|
|
40
|
+
* log ends with its errors and its verdict.
|
|
41
|
+
*/
|
|
42
|
+
const PREVIEW_HEAD_BYTES = 1_536
|
|
43
|
+
const PREVIEW_TAIL_BYTES = 512
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* What one run may save, apart from the run's file budget that published artifacts and
|
|
47
|
+
* file-returning tools take: saving gives way first, its outputs left to the copy their message
|
|
48
|
+
* keeps. Identical outputs count once.
|
|
49
|
+
*/
|
|
50
|
+
export const TOOL_OUTPUTS_MAX_BYTES = 64 * 1024 * 1024
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* What a run writes again of the outputs its history saved, newest first: a blank sandbox, or a
|
|
54
|
+
* computer's, starts without them.
|
|
55
|
+
*/
|
|
56
|
+
const RESTORED_OUTPUTS_MAX_BYTES = 32 * 1024 * 1024
|
|
57
|
+
|
|
58
|
+
/** How many stored outputs a run reads at once to write them back. */
|
|
59
|
+
const RESTORED_OUTPUTS_CONCURRENCY = 4
|
|
60
|
+
|
|
61
|
+
/** Past this many files in the sandbox's directory, the rest are written back whether held. */
|
|
62
|
+
const LISTED_OUTPUTS_MAX_FILES = 1_000
|
|
63
|
+
const LIST_TIMEOUT_MS = 30_000
|
|
64
|
+
|
|
65
|
+
/** The readers: they page through files themselves, so their output is never saved to another. */
|
|
66
|
+
const FILE_READERS: ReadonlySet<string> = new Set([READ_TOOL_SPEC.name, VIEW_FILE_TOOL_SPEC.name])
|
|
67
|
+
|
|
68
|
+
const NOTICE_TAG = "tool_output_file"
|
|
69
|
+
const NOTICE_OPENING = new RegExp(`^<${NOTICE_TAG} sandboxPath="([^"]*)"`)
|
|
70
|
+
|
|
71
|
+
/** A saved output, between its call's execution and the preview the model reads of it. */
|
|
72
|
+
interface SavedCall {
|
|
73
|
+
readonly file: AgentToolCallFile
|
|
74
|
+
readonly sandboxPath: string
|
|
75
|
+
contents?: string
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* The run's tools, each saving an output too large for the context: stored as a file of its run,
|
|
80
|
+
* like a tool's own files, and copied into the sandbox at `tool-outputs/<call id>-<digest>.txt`.
|
|
81
|
+
* The model reads a preview with that path; the call's message part keeps a bounded copy of the
|
|
82
|
+
* output and the stored file as its `outputFile` ({@link fileOf}), which every later run writes
|
|
83
|
+
* back ({@link restoreSavedToolOutputs}). Saving that fails leaves the output as the part keeps it.
|
|
84
|
+
*/
|
|
85
|
+
export class ToolOutputFiles {
|
|
86
|
+
readonly #saved = new Map<string, SavedCall>()
|
|
87
|
+
readonly #budget: AgentFileBudget
|
|
88
|
+
|
|
89
|
+
constructor(
|
|
90
|
+
private readonly input: {
|
|
91
|
+
readonly sandbox: () => Promise<AgentSandboxHandle>
|
|
92
|
+
readonly blobStorage: Pick<AgentRunFileStore, "put">
|
|
93
|
+
/** Test seam; production holds {@link TOOL_OUTPUTS_MAX_BYTES}, never the run's own budget. */
|
|
94
|
+
readonly budget?: AgentFileBudget
|
|
95
|
+
}
|
|
96
|
+
) {
|
|
97
|
+
this.#budget = input.budget ?? new AgentFileBudget(TOOL_OUTPUTS_MAX_BYTES)
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
wrap(tools: readonly ModelTool[]): ModelTool[] {
|
|
101
|
+
return tools.map((tool) => (FILE_READERS.has(tool.name) ? tool : this.saving(tool)))
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** The stored file of a call whose output was saved, for its message part. */
|
|
105
|
+
fileOf(toolCallId: string): AgentToolCallFile | undefined {
|
|
106
|
+
return this.#saved.get(toolCallId)?.file
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
private saving(tool: ModelTool): ModelTool {
|
|
110
|
+
const project = (output: JsonValue, context: ModelToolExecutionContext) =>
|
|
111
|
+
tool.toModelOutput ? tool.toModelOutput(output, context) : defaultModelOutput(output)
|
|
112
|
+
|
|
113
|
+
return {
|
|
114
|
+
...tool,
|
|
115
|
+
execute: async (input, context) => {
|
|
116
|
+
const output = await tool.execute(input, context)
|
|
117
|
+
const contents = savedOutputText(tool.name, output)
|
|
118
|
+
if (contents === undefined) return output
|
|
119
|
+
|
|
120
|
+
try {
|
|
121
|
+
this.#saved.set(context.toolCallId, await this.save(tool.name, contents, context))
|
|
122
|
+
} catch (error) {
|
|
123
|
+
context.signal.throwIfAborted()
|
|
124
|
+
console.warn(
|
|
125
|
+
`[SixbAgent] Could not save a ${tool.name} output to a file, so the model reads what its message keeps:`,
|
|
126
|
+
error
|
|
127
|
+
)
|
|
128
|
+
}
|
|
129
|
+
return keptOutput(tool.name, output)
|
|
130
|
+
},
|
|
131
|
+
toModelOutput: async (output, context) => {
|
|
132
|
+
const saved = this.#saved.get(context.toolCallId)
|
|
133
|
+
if (saved?.contents === undefined) return project(output, context)
|
|
134
|
+
|
|
135
|
+
const notice = toolOutputNotice({
|
|
136
|
+
toolName: tool.name,
|
|
137
|
+
output,
|
|
138
|
+
path: saved.sandboxPath,
|
|
139
|
+
contents: saved.contents,
|
|
140
|
+
})
|
|
141
|
+
saved.contents = undefined
|
|
142
|
+
if (!isAgentToolResult(output)) return { type: "text", value: notice }
|
|
143
|
+
|
|
144
|
+
// A file-aware result keeps its files, which its tool projects after the notice.
|
|
145
|
+
const noticed: unknown = withText(output, notice)
|
|
146
|
+
assertJsonValue(noticed)
|
|
147
|
+
return project(noticed, context)
|
|
148
|
+
},
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
private async save(
|
|
153
|
+
toolName: string,
|
|
154
|
+
contents: string,
|
|
155
|
+
context: ModelToolExecutionContext
|
|
156
|
+
): Promise<SavedCall> {
|
|
157
|
+
const bytes = new TextEncoder().encode(contents)
|
|
158
|
+
if (bytes.byteLength > AGENT_FILE_MAX_BYTES) {
|
|
159
|
+
throw new Error(`the output exceeds the ${AGENT_FILE_MAX_BYTES}-byte file limit`)
|
|
160
|
+
}
|
|
161
|
+
const sha256 = createHash("sha256").update(bytes).digest("hex")
|
|
162
|
+
this.#budget.holdContent(`sha256:${sha256}`, bytes.byteLength, toolName)
|
|
163
|
+
|
|
164
|
+
try {
|
|
165
|
+
const path = agentToolOutputPath(context.toolCallId, sha256)
|
|
166
|
+
const fileRef = await this.input.blobStorage.put({
|
|
167
|
+
body: bytes,
|
|
168
|
+
expectedSizeBytes: bytes.byteLength,
|
|
169
|
+
signal: context.signal,
|
|
170
|
+
fileName: posix.basename(path),
|
|
171
|
+
mediaType: "text/plain",
|
|
172
|
+
})
|
|
173
|
+
|
|
174
|
+
const handle = await this.input.sandbox()
|
|
175
|
+
context.signal.throwIfAborted()
|
|
176
|
+
const sandboxPath = posix.join(handle.contextDirectory, path)
|
|
177
|
+
await handle.sandbox.writeFiles([
|
|
178
|
+
{ path: posix.resolve(handle.sandbox.workingDirectory, sandboxPath), contents: bytes },
|
|
179
|
+
])
|
|
180
|
+
return { file: { fileRef, path }, sandboxPath, contents }
|
|
181
|
+
} catch (error) {
|
|
182
|
+
this.#budget.releaseContent(`sha256:${sha256}`)
|
|
183
|
+
throw error
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* The outputs a history saved, to write back: the newest within
|
|
190
|
+
* {@link RESTORED_OUTPUTS_MAX_BYTES}, by the size they declare, listed oldest first so that a
|
|
191
|
+
* later one at the same path is written last. Only a file of the shape the harness names is: the
|
|
192
|
+
* stored messages are a runner's, or a fork's copy of them.
|
|
193
|
+
*/
|
|
194
|
+
export function savedToolOutputFiles(messages: readonly AgentMessageRecord[]): AgentToolCallFile[] {
|
|
195
|
+
const files: AgentToolCallFile[] = []
|
|
196
|
+
let bytes = 0
|
|
197
|
+
|
|
198
|
+
newest: for (const message of [...messages].reverse()) {
|
|
199
|
+
for (const part of [...message.parts].reverse()) {
|
|
200
|
+
if (part.type !== "tool-call" || part.state !== "output-available") continue
|
|
201
|
+
if (!isAgentToolOutputFile(part.outputFile)) continue
|
|
202
|
+
|
|
203
|
+
bytes += part.outputFile.fileRef.sizeBytes
|
|
204
|
+
if (bytes > RESTORED_OUTPUTS_MAX_BYTES) break newest
|
|
205
|
+
files.push(part.outputFile)
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
return files.reverse()
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/**
|
|
212
|
+
* Write the saved outputs back into a run's sandbox: those it does not hold already, as a
|
|
213
|
+
* workspace that persists does, read from the store a few at a time, oldest first. A file is read
|
|
214
|
+
* no further than the size it declares, so the bytes read stay within what
|
|
215
|
+
* {@link savedToolOutputFiles} counted; one that cannot be read, or holds more, is left out.
|
|
216
|
+
*/
|
|
217
|
+
export async function restoreSavedToolOutputs(input: {
|
|
218
|
+
readonly handle: AgentSandboxHandle
|
|
219
|
+
readonly files: readonly AgentToolCallFile[]
|
|
220
|
+
readonly blobStorage: Pick<AgentRunFileStore, "open">
|
|
221
|
+
readonly signal: AbortSignal
|
|
222
|
+
}): Promise<void> {
|
|
223
|
+
const { handle, signal } = input
|
|
224
|
+
if (input.files.length === 0) return
|
|
225
|
+
|
|
226
|
+
const directory = contextPath(handle, TOOL_OUTPUTS_DIRECTORY)
|
|
227
|
+
const listing = await listSandboxFiles(handle, {
|
|
228
|
+
directory,
|
|
229
|
+
maxFiles: LISTED_OUTPUTS_MAX_FILES,
|
|
230
|
+
signal,
|
|
231
|
+
timeoutMs: LIST_TIMEOUT_MS,
|
|
232
|
+
})
|
|
233
|
+
const held = new Map(listing.files.map((file) => [file.relativePath, file.sizeBytes]))
|
|
234
|
+
const missing = input.files.filter(
|
|
235
|
+
(file) => held.get(posix.basename(file.path)) !== file.fileRef.sizeBytes
|
|
236
|
+
)
|
|
237
|
+
|
|
238
|
+
const read: (Uint8Array | undefined)[] = new Array(missing.length)
|
|
239
|
+
let next = 0
|
|
240
|
+
const reader = async () => {
|
|
241
|
+
while (next < missing.length) {
|
|
242
|
+
const index = next++
|
|
243
|
+
const file = missing[index]
|
|
244
|
+
if (file) read[index] = await readSavedFile(input.blobStorage, file, signal)
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
await Promise.all(Array.from({ length: RESTORED_OUTPUTS_CONCURRENCY }, reader))
|
|
248
|
+
|
|
249
|
+
signal.throwIfAborted()
|
|
250
|
+
const records = missing.flatMap((file, index) => {
|
|
251
|
+
const contents = read[index]
|
|
252
|
+
return contents ? [{ path: posix.join(directory, posix.basename(file.path)), contents }] : []
|
|
253
|
+
})
|
|
254
|
+
if (records.length > 0) await handle.sandbox.writeFiles(records)
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/** A stored output's bytes, read no further than its declared size; undefined when it differs. */
|
|
258
|
+
async function readSavedFile(
|
|
259
|
+
blobStorage: Pick<AgentRunFileStore, "open">,
|
|
260
|
+
file: AgentToolCallFile,
|
|
261
|
+
signal: AbortSignal
|
|
262
|
+
): Promise<Uint8Array | undefined> {
|
|
263
|
+
const maxBytes = file.fileRef.sizeBytes
|
|
264
|
+
try {
|
|
265
|
+
const reader = (await blobStorage.open(file.fileRef.blobId)).getReader()
|
|
266
|
+
const bytes = new Uint8Array(maxBytes)
|
|
267
|
+
let length = 0
|
|
268
|
+
try {
|
|
269
|
+
while (true) {
|
|
270
|
+
signal.throwIfAborted()
|
|
271
|
+
const { done, value } = await reader.read()
|
|
272
|
+
if (done) break
|
|
273
|
+
if (length + value.byteLength > maxBytes) {
|
|
274
|
+
throw new Error(`it holds more than the ${maxBytes} bytes it declares`)
|
|
275
|
+
}
|
|
276
|
+
bytes.set(value, length)
|
|
277
|
+
length += value.byteLength
|
|
278
|
+
}
|
|
279
|
+
} finally {
|
|
280
|
+
await reader.cancel().catch(() => {})
|
|
281
|
+
}
|
|
282
|
+
if (length !== maxBytes) throw new Error(`it holds ${length} bytes, not ${maxBytes}`)
|
|
283
|
+
return bytes
|
|
284
|
+
} catch (error) {
|
|
285
|
+
signal.throwIfAborted()
|
|
286
|
+
console.warn(`[SixbAgent] Could not write back the saved tool output ${file.path}:`, error)
|
|
287
|
+
return undefined
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/** The path a tool result's text names when it is the preview of a saved output. */
|
|
292
|
+
export function savedToolOutputPath(text: string): string | undefined {
|
|
293
|
+
return NOTICE_OPENING.exec(text)?.[1]
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/** The file an output too large for the context is saved to, or undefined when it fits. */
|
|
297
|
+
function savedOutputText(toolName: string, output: JsonValue): string | undefined {
|
|
298
|
+
if (modelFacingBytes(output) <= TOOL_OUTPUT_FILE_MIN_BYTES) return undefined
|
|
299
|
+
|
|
300
|
+
const text = outputText(toolName, output)
|
|
301
|
+
return text.endsWith("\n") ? text : `${text}\n`
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/**
|
|
305
|
+
* What the message part keeps of a saved output: a command's streams bounded, as the app shows
|
|
306
|
+
* them. Any other tool's output is its author's contract, saved and streamed as it returned it.
|
|
307
|
+
*/
|
|
308
|
+
function keptOutput(toolName: string, output: JsonValue): JsonValue {
|
|
309
|
+
if (toolName !== BASH_TOOL_SPEC.name || !isCommandOutput(output)) return output
|
|
310
|
+
|
|
311
|
+
const kept: unknown = keptCommandOutput(output)
|
|
312
|
+
assertJsonValue(kept)
|
|
313
|
+
return kept
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
/**
|
|
317
|
+
* What the model would read of an output: a file-aware result's text (its files reach the model
|
|
318
|
+
* on their own), a string, or the JSON it prints.
|
|
319
|
+
*/
|
|
320
|
+
function modelFacingBytes(output: JsonValue): number {
|
|
321
|
+
if (isAgentToolResult(output)) return utf8Bytes(resultText(output))
|
|
322
|
+
if (typeof output === "string") return utf8Bytes(output)
|
|
323
|
+
return utf8Bytes(JSON.stringify(output))
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/**
|
|
327
|
+
* An output as a file the agent reads by lines and searches: a command's streams as it printed
|
|
328
|
+
* them, text as is, JSON indented. Compact JSON is indented, or one long line would be all the
|
|
329
|
+
* read tool sees of it.
|
|
330
|
+
*/
|
|
331
|
+
function outputText(toolName: string, output: JsonValue): string {
|
|
332
|
+
if (toolName === BASH_TOOL_SPEC.name && isCommandOutput(output)) {
|
|
333
|
+
const stdout = indentedJsonText(output.stdout)
|
|
334
|
+
return output.stderr ? `${stdout}\n--- stderr ---\n${output.stderr}` : stdout
|
|
335
|
+
}
|
|
336
|
+
if (isAgentToolResult(output)) return indentedJsonText(resultText(output))
|
|
337
|
+
if (typeof output === "string") return indentedJsonText(output)
|
|
338
|
+
|
|
339
|
+
return JSON.stringify(output, null, 2)
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
/**
|
|
343
|
+
* What the model reads in place of an output saved to a file: where it is, how large, how to read
|
|
344
|
+
* it, and a preview.
|
|
345
|
+
*/
|
|
346
|
+
function toolOutputNotice(input: {
|
|
347
|
+
readonly toolName: string
|
|
348
|
+
readonly output: JsonValue
|
|
349
|
+
readonly path: string
|
|
350
|
+
readonly contents: string
|
|
351
|
+
}): string {
|
|
352
|
+
const bytes = Buffer.from(input.contents)
|
|
353
|
+
const headEnd = previewHeadEnd(bytes, PREVIEW_HEAD_BYTES)
|
|
354
|
+
const tailStart = previewTailStart(bytes, PREVIEW_TAIL_BYTES)
|
|
355
|
+
// The file ends with a newline, which the closing tag's own line stands for.
|
|
356
|
+
const tail =
|
|
357
|
+
tailStart > headEnd ? bytes.subarray(tailStart).toString("utf8").replace(/\n$/, "") : undefined
|
|
358
|
+
const exit =
|
|
359
|
+
input.toolName === BASH_TOOL_SPEC.name && isCommandOutput(input.output)
|
|
360
|
+
? [`Exit code: ${input.output.exitCode}${input.output.timedOut ? " (timed out)" : ""}.`]
|
|
361
|
+
: []
|
|
362
|
+
const lines = input.contents.split("\n").length - 1
|
|
363
|
+
|
|
364
|
+
return [
|
|
365
|
+
`<${NOTICE_TAG} sandboxPath="${input.path}" sizeBytes="${bytes.byteLength}" lines="${lines}">`,
|
|
366
|
+
"This output is too large for the context: the whole of it is in this file. Read it in pieces with the read tool (offset, limit), or search it with grep.",
|
|
367
|
+
...exit,
|
|
368
|
+
"",
|
|
369
|
+
`First ${headEnd.toLocaleString("en-US")} bytes:`,
|
|
370
|
+
bytes.subarray(0, headEnd).toString("utf8"),
|
|
371
|
+
...(tail === undefined
|
|
372
|
+
? []
|
|
373
|
+
: [
|
|
374
|
+
`[… ${(tailStart - headEnd).toLocaleString("en-US")} bytes …]`,
|
|
375
|
+
`Last ${(bytes.byteLength - tailStart).toLocaleString("en-US")} bytes:`,
|
|
376
|
+
tail,
|
|
377
|
+
]),
|
|
378
|
+
`</${NOTICE_TAG}>`,
|
|
379
|
+
].join("\n")
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
/** Where the first `maxBytes` end, at a line's end when one is in their second half. */
|
|
383
|
+
function previewHeadEnd(bytes: Buffer, maxBytes: number): number {
|
|
384
|
+
if (bytes.byteLength <= maxBytes) return bytes.byteLength
|
|
385
|
+
|
|
386
|
+
let end = maxBytes
|
|
387
|
+
// Never inside a character: back to the start of the one the cut falls in.
|
|
388
|
+
while (end > 0 && isContinuationByte(bytes[end])) end -= 1
|
|
389
|
+
const newline = bytes.lastIndexOf(10, end - 1)
|
|
390
|
+
return newline > end / 2 ? newline : end
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
/** Where the last `maxBytes` start, at a line's start when one is in their first half. */
|
|
394
|
+
function previewTailStart(bytes: Buffer, maxBytes: number): number {
|
|
395
|
+
if (bytes.byteLength <= maxBytes) return 0
|
|
396
|
+
|
|
397
|
+
let start = bytes.byteLength - maxBytes
|
|
398
|
+
while (start < bytes.byteLength && isContinuationByte(bytes[start])) start += 1
|
|
399
|
+
const newline = bytes.indexOf(10, start)
|
|
400
|
+
return newline !== -1 && newline < start + maxBytes / 2 ? newline + 1 : start
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
function isContinuationByte(byte: number | undefined): boolean {
|
|
404
|
+
return byte !== undefined && (byte & 0xc0) === 0x80
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
function defaultModelOutput(output: JsonValue): ModelToolOutput {
|
|
408
|
+
return typeof output === "string"
|
|
409
|
+
? { type: "text", value: output }
|
|
410
|
+
: { type: "json", value: output }
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
/** A file-aware result with its text replaced by `text`, its files kept. */
|
|
414
|
+
function withText(output: AgentToolResult, text: string): AgentToolResult {
|
|
415
|
+
return {
|
|
416
|
+
kind: "agentToolResult",
|
|
417
|
+
content: [{ type: "text", text }, ...output.content.filter((part) => part.type === "file")],
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
function resultText(output: AgentToolResult): string {
|
|
422
|
+
return output.content.flatMap((part) => (part.type === "text" ? [part.text] : [])).join("\n")
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
/**
|
|
426
|
+
* A compact JSON document indented, else the text as it is. Only one that prints back as it came:
|
|
427
|
+
* an integer past 2^53 or an escape would otherwise read another value or other bytes in the file.
|
|
428
|
+
*/
|
|
429
|
+
function indentedJsonText(text: string): string {
|
|
430
|
+
const trimmed = text.trim()
|
|
431
|
+
if (!trimmed.startsWith("{") && !trimmed.startsWith("[")) return text
|
|
432
|
+
|
|
433
|
+
let value: unknown
|
|
434
|
+
try {
|
|
435
|
+
value = JSON.parse(trimmed)
|
|
436
|
+
} catch {
|
|
437
|
+
return text
|
|
438
|
+
}
|
|
439
|
+
return JSON.stringify(value) === trimmed ? JSON.stringify(value, null, 2) : text
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
interface CommandOutput {
|
|
443
|
+
readonly exitCode: number
|
|
444
|
+
readonly stdout: string
|
|
445
|
+
readonly stderr: string
|
|
446
|
+
readonly durationMs: number
|
|
447
|
+
readonly timedOut?: boolean
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
function isCommandOutput(output: JsonValue): output is JsonValue & CommandOutput {
|
|
451
|
+
return (
|
|
452
|
+
typeof output === "object" &&
|
|
453
|
+
output !== null &&
|
|
454
|
+
!Array.isArray(output) &&
|
|
455
|
+
typeof output.exitCode === "number" &&
|
|
456
|
+
typeof output.stdout === "string" &&
|
|
457
|
+
typeof output.stderr === "string" &&
|
|
458
|
+
typeof output.durationMs === "number"
|
|
459
|
+
)
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
function utf8Bytes(text: string): number {
|
|
463
|
+
return Buffer.byteLength(text, "utf8")
|
|
464
|
+
}
|
package/src/types.ts
CHANGED
|
@@ -1,5 +1,10 @@
|
|
|
1
1
|
import type { AuthorizablePrincipal } from "@sixb/core"
|
|
2
|
-
import type {
|
|
2
|
+
import type {
|
|
3
|
+
AgentRunFileStore,
|
|
4
|
+
AgentSystemPromptSize,
|
|
5
|
+
AgentToolCallFile,
|
|
6
|
+
RunModelLoopInput,
|
|
7
|
+
} from "@sixb/core/internal/agents"
|
|
3
8
|
import type { ModelTool } from "@sixb/core/models"
|
|
4
9
|
import type { PreparedAgentAttachmentContext } from "./attachments"
|
|
5
10
|
import type { AgentRequester } from "./requester"
|
|
@@ -47,11 +52,18 @@ export interface AgentTurnContext {
|
|
|
47
52
|
/** The Sixb API the run's commands call, when this turn was created through a run environment. */
|
|
48
53
|
readonly apiBaseUrl?: string
|
|
49
54
|
readonly tools: readonly ModelTool[]
|
|
55
|
+
/** The stored file of a call whose output was too large for the context, for its message. */
|
|
56
|
+
readonly outputFileOf?: (toolCallId: string) => AgentToolCallFile | undefined
|
|
50
57
|
readonly prepareStep?: RunModelLoopInput["prepareStep"]
|
|
51
58
|
/** Complete worker-owned system prompt, derived from the mode and provisioned runtime. */
|
|
52
59
|
readonly systemPrompt: string
|
|
53
|
-
/**
|
|
60
|
+
/** The same prompt with each section's bytes, for each step to record what its request sent. */
|
|
61
|
+
readonly systemPromptSize?: AgentSystemPromptSize
|
|
62
|
+
/** Where the run's context files are, as the agent names them: its reads of them are named. */
|
|
63
|
+
readonly contextDirectory?: string
|
|
64
|
+
/** Time zone and locale of runs that captured none, used to date their user messages. */
|
|
54
65
|
readonly projectTimeZone: string
|
|
66
|
+
readonly projectLocale: string
|
|
55
67
|
/** Prepared by the run's environment, which materializes the files in its context directory. */
|
|
56
68
|
readonly attachmentContext?: PreparedAgentAttachmentContext
|
|
57
69
|
/**
|