@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.
- package/LICENSE +21 -0
- package/README.md +31 -2
- package/dist/abort.d.ts +6 -0
- package/dist/abort.d.ts.map +1 -0
- package/dist/agent-prompt.d.ts +126 -0
- package/dist/agent-prompt.d.ts.map +1 -0
- package/dist/agent-runtime/errors.d.ts +13 -0
- package/dist/agent-runtime/errors.d.ts.map +1 -0
- package/dist/agent-runtime/preflight.d.ts +18 -0
- package/dist/agent-runtime/preflight.d.ts.map +1 -0
- package/dist/agent-runtime/profile.d.ts +14 -0
- package/dist/agent-runtime/profile.d.ts.map +1 -0
- package/dist/artifacts/layout-check/layout-check.d.ts +87 -0
- package/dist/artifacts/layout-check/layout-check.d.ts.map +1 -0
- package/dist/artifacts/materialize.d.ts +115 -0
- package/dist/artifacts/materialize.d.ts.map +1 -0
- package/dist/artifacts/publish-tool.d.ts +86 -0
- package/dist/artifacts/publish-tool.d.ts.map +1 -0
- package/dist/ask-parent-tool.d.ts +36 -0
- package/dist/ask-parent-tool.d.ts.map +1 -0
- package/dist/attachments.d.ts +109 -0
- package/dist/attachments.d.ts.map +1 -0
- package/dist/child-files.d.ts +91 -0
- package/dist/child-files.d.ts.map +1 -0
- package/dist/child-questions.d.ts +24 -0
- package/dist/child-questions.d.ts.map +1 -0
- package/dist/computer-runner.d.ts +74 -0
- package/dist/computer-runner.d.ts.map +1 -0
- package/dist/context-budget.d.ts +34 -0
- package/dist/context-budget.d.ts.map +1 -0
- package/dist/context-compaction.d.ts +148 -0
- package/dist/context-compaction.d.ts.map +1 -0
- package/dist/context-guard.d.ts +69 -0
- package/dist/context-guard.d.ts.map +1 -0
- package/dist/conversation-memory.d.ts +21 -0
- package/dist/conversation-memory.d.ts.map +1 -0
- package/dist/conversation-messages.d.ts +33 -0
- package/dist/conversation-messages.d.ts.map +1 -0
- package/dist/errors.d.ts +46 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/execution-plan.d.ts +38 -0
- package/dist/execution-plan.d.ts.map +1 -0
- package/dist/failure.d.ts +14 -0
- package/dist/failure.d.ts.map +1 -0
- package/dist/family-mailbox.d.ts +60 -0
- package/dist/family-mailbox.d.ts.map +1 -0
- package/dist/file-ref.d.ts +6 -0
- package/dist/file-ref.d.ts.map +1 -0
- package/dist/image-attachments.d.ts +34 -0
- package/dist/image-attachments.d.ts.map +1 -0
- package/dist/index.d.ts +35 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +14387 -0
- package/dist/index.js.map +72 -0
- package/dist/inline-images.d.ts +28 -0
- package/dist/inline-images.d.ts.map +1 -0
- package/dist/message-authors.d.ts +34 -0
- package/dist/message-authors.d.ts.map +1 -0
- package/dist/message-times.d.ts +9 -0
- package/dist/message-times.d.ts.map +1 -0
- package/dist/model-adapters.d.ts +59 -0
- package/dist/model-adapters.d.ts.map +1 -0
- package/dist/model-lines.d.ts +16 -0
- package/dist/model-lines.d.ts.map +1 -0
- package/dist/prompt-cache.d.ts +28 -0
- package/dist/prompt-cache.d.ts.map +1 -0
- package/dist/requester.d.ts +15 -0
- package/dist/requester.d.ts.map +1 -0
- package/dist/run-agent-turn.d.ts +93 -0
- package/dist/run-agent-turn.d.ts.map +1 -0
- package/dist/run-child.d.ts +77 -0
- package/dist/run-child.d.ts.map +1 -0
- package/dist/run-conversation-turn.d.ts +42 -0
- package/dist/run-conversation-turn.d.ts.map +1 -0
- package/dist/run-credential.d.ts +22 -0
- package/dist/run-credential.d.ts.map +1 -0
- package/dist/run-environment.d.ts +145 -0
- package/dist/run-environment.d.ts.map +1 -0
- package/dist/run-fate.d.ts +15 -0
- package/dist/run-fate.d.ts.map +1 -0
- package/dist/run-files-lock.d.ts +16 -0
- package/dist/run-files-lock.d.ts.map +1 -0
- package/dist/run-sandbox.d.ts +60 -0
- package/dist/run-sandbox.d.ts.map +1 -0
- package/dist/run-subagent.d.ts +65 -0
- package/dist/run-subagent.d.ts.map +1 -0
- package/dist/run-workflow-agent-node.d.ts +46 -0
- package/dist/run-workflow-agent-node.d.ts.map +1 -0
- package/dist/sandbox-api-context.d.ts +34 -0
- package/dist/sandbox-api-context.d.ts.map +1 -0
- package/dist/sandbox-file-registry.d.ts +9 -0
- package/dist/sandbox-file-registry.d.ts.map +1 -0
- package/dist/sandbox-files.d.ts +71 -0
- package/dist/sandbox-files.d.ts.map +1 -0
- package/dist/sandbox-handle.d.ts +15 -0
- package/dist/sandbox-handle.d.ts.map +1 -0
- package/dist/sandbox-readiness.d.ts +8 -0
- package/dist/sandbox-readiness.d.ts.map +1 -0
- package/dist/skills/built-in.d.ts +15 -0
- package/dist/skills/built-in.d.ts.map +1 -0
- package/dist/subagent-context.d.ts +50 -0
- package/dist/subagent-context.d.ts.map +1 -0
- package/dist/subagent-continuation.d.ts +33 -0
- package/dist/subagent-continuation.d.ts.map +1 -0
- package/dist/subagent-inbox.d.ts +53 -0
- package/dist/subagent-inbox.d.ts.map +1 -0
- package/dist/subagent-tools.d.ts +293 -0
- package/dist/subagent-tools.d.ts.map +1 -0
- package/dist/thread-context.d.ts +17 -0
- package/dist/thread-context.d.ts.map +1 -0
- package/dist/tools/attachments.d.ts +11 -0
- package/dist/tools/attachments.d.ts.map +1 -0
- package/dist/tools/bash.d.ts +68 -0
- package/dist/tools/bash.d.ts.map +1 -0
- package/dist/tools/model-spec.d.ts +9 -0
- package/dist/tools/model-spec.d.ts.map +1 -0
- package/dist/tools/read.d.ts +43 -0
- package/dist/tools/read.d.ts.map +1 -0
- package/dist/tools/result-media.d.ts +65 -0
- package/dist/tools/result-media.d.ts.map +1 -0
- package/dist/tools/result-output.d.ts +18 -0
- package/dist/tools/result-output.d.ts.map +1 -0
- package/dist/tools/tool-files.d.ts +59 -0
- package/dist/tools/tool-files.d.ts.map +1 -0
- package/dist/tools/tool-outputs.d.ts +63 -0
- package/dist/tools/tool-outputs.d.ts.map +1 -0
- package/dist/tools/view-file.d.ts +40 -0
- package/dist/tools/view-file.d.ts.map +1 -0
- package/dist/tsconfig.json +5 -0
- package/dist/turn-runtime.d.ts +19 -0
- package/dist/turn-runtime.d.ts.map +1 -0
- package/dist/types.d.ts +83 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/workflow-input-attachments.d.ts +18 -0
- package/dist/workflow-input-attachments.d.ts.map +1 -0
- package/package.json +59 -4
- package/src/abort.ts +40 -0
- package/src/agent-prompt.ts +860 -0
- package/src/agent-runtime/errors.ts +44 -0
- package/src/agent-runtime/preflight.ts +314 -0
- package/src/agent-runtime/profile.ts +23 -0
- package/src/artifacts/layout-check/check.cjs +478 -0
- package/src/artifacts/layout-check/layout-check.ts +460 -0
- package/src/artifacts/materialize.ts +380 -0
- package/src/artifacts/publish-tool.ts +700 -0
- package/src/ask-parent-tool.ts +100 -0
- package/src/attachments.ts +1041 -0
- package/src/child-files.ts +535 -0
- package/src/child-questions.ts +42 -0
- package/src/computer-runner.ts +336 -0
- package/src/context-budget.ts +177 -0
- package/src/context-compaction.ts +1349 -0
- package/src/context-guard.ts +826 -0
- package/src/conversation-memory.ts +45 -0
- package/src/conversation-messages.ts +86 -0
- package/src/errors.ts +85 -0
- package/src/execution-plan.ts +70 -0
- package/src/failure.ts +82 -0
- package/src/family-mailbox.ts +189 -0
- package/src/file-ref.ts +18 -0
- package/src/image-attachments.ts +322 -0
- package/src/index.ts +54 -0
- package/src/inline-images.ts +69 -0
- package/src/message-authors.ts +77 -0
- package/src/message-times.ts +24 -0
- package/src/model-adapters.ts +273 -0
- package/src/model-lines.ts +28 -0
- package/src/prompt-cache.ts +40 -0
- package/src/requester.ts +21 -0
- package/src/run-agent-turn.ts +509 -0
- package/src/run-child.ts +344 -0
- package/src/run-conversation-turn.ts +272 -0
- package/src/run-credential.ts +55 -0
- package/src/run-environment.ts +1216 -0
- package/src/run-fate.ts +51 -0
- package/src/run-files-lock.ts +118 -0
- package/src/run-sandbox.ts +63 -0
- package/src/run-subagent.ts +433 -0
- package/src/run-workflow-agent-node.ts +344 -0
- package/src/sandbox-api-context.ts +237 -0
- package/src/sandbox-file-registry.ts +26 -0
- package/src/sandbox-files.ts +326 -0
- package/src/sandbox-handle.ts +19 -0
- package/src/sandbox-readiness.ts +22 -0
- package/src/skills/built-in.ts +183 -0
- package/src/skills/sixb-artifacts/SKILL.md +95 -0
- package/src/skills/sixb-artifacts/canvas.md +104 -0
- package/src/skills/sixb-artifacts/document.md +63 -0
- package/src/skills/sixb-artifacts/examples/canvas/onboarding-flow/boards/first-job.html +42 -0
- package/src/skills/sixb-artifacts/examples/canvas/onboarding-flow/boards/region.html +29 -0
- package/src/skills/sixb-artifacts/examples/canvas/onboarding-flow/boards/shared.css +35 -0
- package/src/skills/sixb-artifacts/examples/canvas/onboarding-flow/boards/welcome.html +31 -0
- package/src/skills/sixb-artifacts/examples/canvas/onboarding-flow/canvas.json +107 -0
- package/src/skills/sixb-artifacts/examples/canvas/retro/canvas.json +158 -0
- package/src/skills/sixb-artifacts/examples/document/incident-report/document.md +35 -0
- package/src/skills/sixb-artifacts/examples/document/operations-review/document.md +41 -0
- package/src/skills/sixb-artifacts/examples/document/operations-review/figures/restorations.svg +1 -0
- package/src/skills/sixb-artifacts/examples/page/collections-desk/index.html +169 -0
- package/src/skills/sixb-artifacts/examples/page/collections-desk/queries/overdue.json +13 -0
- package/src/skills/sixb-artifacts/examples/page/dispatch-board/data/dispatch.json +234 -0
- package/src/skills/sixb-artifacts/examples/page/dispatch-board/index.html +245 -0
- package/src/skills/sixb-artifacts/examples/page/fleet-planner/data/plan.json +53 -0
- package/src/skills/sixb-artifacts/examples/page/fleet-planner/index.html +462 -0
- package/src/skills/sixb-artifacts/examples/page/service-explorer/data/service.json +276 -0
- package/src/skills/sixb-artifacts/examples/page/service-explorer/index.html +549 -0
- package/src/skills/sixb-artifacts/examples/sheet/overdue-invoices/queries/overdue.json +13 -0
- package/src/skills/sixb-artifacts/examples/sheet/overdue-invoices/workbook.json +30 -0
- package/src/skills/sixb-artifacts/examples/sheet/parts-inventory/sheets/Inventory.csv +13 -0
- package/src/skills/sixb-artifacts/examples/sheet/parts-inventory/sheets/Spend.csv +6 -0
- package/src/skills/sixb-artifacts/examples/sheet/parts-inventory/workbook.json +47 -0
- package/src/skills/sixb-artifacts/examples/sheet/service-metrics/sheets/Quarters.csv +5 -0
- package/src/skills/sixb-artifacts/examples/sheet/service-metrics/sheets/Regions.csv +5 -0
- package/src/skills/sixb-artifacts/examples/sheet/service-metrics/workbook.json +78 -0
- package/src/skills/sixb-artifacts/examples/slides/launch-plan/index.html +63 -0
- package/src/skills/sixb-artifacts/examples/slides/q3-review/index.html +133 -0
- package/src/skills/sixb-artifacts/file.md +17 -0
- package/src/skills/sixb-artifacts/page.md +215 -0
- package/src/skills/sixb-artifacts/queries.md +66 -0
- package/src/skills/sixb-artifacts/references.md +68 -0
- package/src/skills/sixb-artifacts/sheet.md +223 -0
- package/src/skills/sixb-artifacts/slides.md +137 -0
- package/src/skills/sixb-memory/SKILL.md +68 -0
- package/src/skills/text-assets.d.ts +25 -0
- package/src/subagent-context.ts +182 -0
- package/src/subagent-continuation.ts +56 -0
- package/src/subagent-inbox.ts +101 -0
- package/src/subagent-tools.ts +1671 -0
- package/src/thread-context.ts +31 -0
- package/src/tools/attachments.ts +28 -0
- package/src/tools/bash.ts +233 -0
- package/src/tools/model-spec.ts +27 -0
- package/src/tools/read.ts +262 -0
- package/src/tools/result-media.ts +351 -0
- package/src/tools/result-output.ts +46 -0
- package/src/tools/tool-files.ts +204 -0
- package/src/tools/tool-outputs.ts +464 -0
- package/src/tools/view-file.ts +155 -0
- package/src/turn-runtime.ts +33 -0
- package/src/types.ts +91 -0
- package/src/workflow-input-attachments.ts +140 -0
|
@@ -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
|
+
}
|
|
@@ -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
|
+
}
|