@sixb/agent 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- 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 +120 -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 +68 -0
- package/dist/attachments.d.ts.map +1 -0
- package/dist/child-files.d.ts +96 -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 +65 -0
- package/dist/computer-runner.d.ts.map +1 -0
- package/dist/context-budget.d.ts +28 -0
- package/dist/context-budget.d.ts.map +1 -0
- package/dist/context-compaction.d.ts +48 -0
- package/dist/context-compaction.d.ts.map +1 -0
- package/dist/conversation-memory.d.ts +21 -0
- package/dist/conversation-memory.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 +34 -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 +12168 -0
- package/dist/index.js.map +65 -0
- package/dist/message-authors.d.ts +34 -0
- package/dist/message-authors.d.ts.map +1 -0
- package/dist/message-times.d.ts +8 -0
- package/dist/message-times.d.ts.map +1 -0
- package/dist/model-adapters.d.ts +55 -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/requester.d.ts +15 -0
- package/dist/requester.d.ts.map +1 -0
- package/dist/run-agent-turn.d.ts +63 -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 +115 -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-sandbox.d.ts +60 -0
- package/dist/run-sandbox.d.ts.map +1 -0
- package/dist/run-subagent.d.ts +51 -0
- package/dist/run-subagent.d.ts.map +1 -0
- package/dist/run-workflow-agent-node.d.ts +41 -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-continuation.d.ts +27 -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 +282 -0
- package/dist/subagent-tools.d.ts.map +1 -0
- package/dist/thread-context.d.ts +12 -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 +60 -0
- package/dist/tools/bash.d.ts.map +1 -0
- package/dist/tools/model-spec.d.ts +4 -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 +22 -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/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 +76 -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 +758 -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 +850 -0
- package/src/child-files.ts +540 -0
- package/src/child-questions.ts +42 -0
- package/src/computer-runner.ts +284 -0
- package/src/context-budget.ts +161 -0
- package/src/context-compaction.ts +529 -0
- package/src/conversation-memory.ts +45 -0
- package/src/errors.ts +85 -0
- package/src/execution-plan.ts +50 -0
- package/src/failure.ts +71 -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/message-authors.ts +77 -0
- package/src/message-times.ts +21 -0
- package/src/model-adapters.ts +227 -0
- package/src/model-lines.ts +28 -0
- package/src/requester.ts +21 -0
- package/src/run-agent-turn.ts +347 -0
- package/src/run-child.ts +319 -0
- package/src/run-conversation-turn.ts +257 -0
- package/src/run-credential.ts +55 -0
- package/src/run-environment.ts +769 -0
- package/src/run-fate.ts +51 -0
- package/src/run-sandbox.ts +63 -0
- package/src/run-subagent.ts +347 -0
- package/src/run-workflow-agent-node.ts +270 -0
- package/src/sandbox-api-context.ts +234 -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-continuation.ts +51 -0
- package/src/subagent-inbox.ts +101 -0
- package/src/subagent-tools.ts +1609 -0
- package/src/thread-context.ts +25 -0
- package/src/tools/attachments.ts +28 -0
- package/src/tools/bash.ts +217 -0
- package/src/tools/model-spec.ts +22 -0
- package/src/tools/read.ts +262 -0
- package/src/tools/result-media.ts +147 -0
- package/src/tools/result-output.ts +44 -0
- package/src/tools/tool-files.ts +204 -0
- package/src/tools/view-file.ts +155 -0
- package/src/turn-runtime.ts +33 -0
- package/src/types.ts +79 -0
- package/src/workflow-input-attachments.ts +140 -0
|
@@ -0,0 +1,850 @@
|
|
|
1
|
+
import { posix } from "node:path"
|
|
2
|
+
import type { AgentFileDataProjection, BlobInfo, FileRef } from "@sixb/core"
|
|
3
|
+
import { type AgentRunFileStore, listMessageAttachments } from "@sixb/core/internal/agents"
|
|
4
|
+
import type { LanguageModel } from "@sixb/core/models"
|
|
5
|
+
import type { AgentMessageRecord } from "@sixb/core/storage"
|
|
6
|
+
import { NEVER_ABORTED_SIGNAL, waitForAbort } from "./abort"
|
|
7
|
+
import { type AgentAttachmentLimits, processAgentImageAttachment } from "./image-attachments"
|
|
8
|
+
|
|
9
|
+
const DEFAULT_AGENT_ATTACHMENT_LIMITS: AgentAttachmentLimits = {
|
|
10
|
+
textInlineMaxBytes: 50 * 1024,
|
|
11
|
+
textInlineMaxLines: 2_000,
|
|
12
|
+
imageMaxWidth: 2_000,
|
|
13
|
+
imageMaxHeight: 2_000,
|
|
14
|
+
imageMaxBase64Bytes: 4.5 * 1024 * 1024,
|
|
15
|
+
imageJpegQualities: [80, 85, 70, 55, 40],
|
|
16
|
+
imageMaxPixels: 4096 * 4096,
|
|
17
|
+
sandboxFileMaxBytes: 25 * 1024 * 1024,
|
|
18
|
+
sandboxTotalMaxBytes: 100 * 1024 * 1024,
|
|
19
|
+
}
|
|
20
|
+
const TEXT_INLINE_TOTAL_MAX_BYTES = 200 * 1024
|
|
21
|
+
const MAX_ASSISTANT_ATTACHMENTS = 50
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* How many files, and bytes, a sandbox receives of a run's attachments: also what a parent Agent
|
|
25
|
+
* and its child hand each other.
|
|
26
|
+
*/
|
|
27
|
+
export const SANDBOX_ATTACHMENT_LIMITS = {
|
|
28
|
+
maxFiles: MAX_ASSISTANT_ATTACHMENTS,
|
|
29
|
+
fileMaxBytes: DEFAULT_AGENT_ATTACHMENT_LIMITS.sandboxFileMaxBytes,
|
|
30
|
+
totalMaxBytes: DEFAULT_AGENT_ATTACHMENT_LIMITS.sandboxTotalMaxBytes,
|
|
31
|
+
} as const
|
|
32
|
+
|
|
33
|
+
export interface PreparedAgentAttachmentContext {
|
|
34
|
+
readonly entries: readonly PreparedAgentAttachment[]
|
|
35
|
+
readonly promptTextByPartKey: ReadonlyMap<string, string>
|
|
36
|
+
readonly modelFileDataByPartKey: ReadonlyMap<string, AgentFileDataProjection>
|
|
37
|
+
readonly sandboxFiles: readonly PreparedSandboxAttachmentFile[]
|
|
38
|
+
readonly manifestJson: string
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export interface PreparedAgentAttachment {
|
|
42
|
+
readonly key: string
|
|
43
|
+
readonly messageId: string
|
|
44
|
+
readonly partIndex: number
|
|
45
|
+
readonly fileRef: FileRef
|
|
46
|
+
readonly fileName: string
|
|
47
|
+
readonly mediaType: string
|
|
48
|
+
readonly sizeBytes: number
|
|
49
|
+
readonly contentPath: string
|
|
50
|
+
readonly contentUrl: string
|
|
51
|
+
readonly sandboxPath?: string
|
|
52
|
+
readonly inlineDisposition: "image" | "text" | "metadata-only" | "omitted"
|
|
53
|
+
readonly notes: readonly string[]
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export interface PreparedSandboxAttachmentFile {
|
|
57
|
+
readonly key: string
|
|
58
|
+
readonly path: string
|
|
59
|
+
readonly bytes: Uint8Array
|
|
60
|
+
readonly fileRef: FileRef
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export interface PreparedAgentToolFileProjection {
|
|
64
|
+
readonly promptText: string
|
|
65
|
+
readonly modelFileData?: AgentFileDataProjection
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
interface AttachmentWorkItem {
|
|
69
|
+
readonly message: AgentMessageRecord
|
|
70
|
+
readonly fileRef: FileRef
|
|
71
|
+
readonly partIndex: number
|
|
72
|
+
readonly key: string
|
|
73
|
+
readonly contentPath: string
|
|
74
|
+
readonly sandboxName: string
|
|
75
|
+
readonly inlineContent: boolean
|
|
76
|
+
readonly origin: "message-file" | "tool-result-file"
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export async function prepareAgentAttachments(input: {
|
|
80
|
+
readonly projectId: string
|
|
81
|
+
readonly threadId: string
|
|
82
|
+
readonly messages: readonly AgentMessageRecord[]
|
|
83
|
+
readonly blobStorage: AgentRunFileStore
|
|
84
|
+
readonly apiBaseUrl: string
|
|
85
|
+
/** Where the run's files go: attachments are materialized in it. */
|
|
86
|
+
readonly contextDirectory: string
|
|
87
|
+
readonly inlineImages: boolean
|
|
88
|
+
readonly signal?: AbortSignal
|
|
89
|
+
}): Promise<PreparedAgentAttachmentContext> {
|
|
90
|
+
const promptTextByPartKey = new Map<string, string>()
|
|
91
|
+
const modelFileDataByPartKey = new Map<string, AgentFileDataProjection>()
|
|
92
|
+
const sandboxFiles: PreparedSandboxAttachmentFile[] = []
|
|
93
|
+
const entries: PreparedAgentAttachment[] = []
|
|
94
|
+
let sandboxBytes = 0
|
|
95
|
+
let textInlineBytes = 0
|
|
96
|
+
|
|
97
|
+
for (const item of fileWorkItems(input.messages)) {
|
|
98
|
+
input.signal?.throwIfAborted()
|
|
99
|
+
const prepared = await prepareOneAttachment({
|
|
100
|
+
...input,
|
|
101
|
+
item,
|
|
102
|
+
sandboxBytes,
|
|
103
|
+
textInlineBytes,
|
|
104
|
+
})
|
|
105
|
+
sandboxBytes += prepared.sandboxBytesAdded
|
|
106
|
+
textInlineBytes += prepared.textInlineBytesAdded
|
|
107
|
+
entries.push(prepared.entry)
|
|
108
|
+
promptTextByPartKey.set(prepared.entry.key, prepared.promptText)
|
|
109
|
+
if (prepared.modelFileData) {
|
|
110
|
+
modelFileDataByPartKey.set(prepared.entry.key, prepared.modelFileData)
|
|
111
|
+
}
|
|
112
|
+
if (prepared.sandboxFile) {
|
|
113
|
+
sandboxFiles.push(prepared.sandboxFile)
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
return {
|
|
118
|
+
entries,
|
|
119
|
+
promptTextByPartKey,
|
|
120
|
+
modelFileDataByPartKey,
|
|
121
|
+
sandboxFiles,
|
|
122
|
+
manifestJson: JSON.stringify(
|
|
123
|
+
{
|
|
124
|
+
projectId: input.projectId,
|
|
125
|
+
threadId: input.threadId,
|
|
126
|
+
attachments: entries.map((entry) => manifestEntry(entry)),
|
|
127
|
+
},
|
|
128
|
+
null,
|
|
129
|
+
2
|
|
130
|
+
),
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** Build the bounded, ephemeral projection of a tool-created file for the next model step. */
|
|
135
|
+
export async function prepareAgentToolFileProjection(input: {
|
|
136
|
+
readonly fileRef: FileRef
|
|
137
|
+
readonly blobStorage: AgentRunFileStore
|
|
138
|
+
readonly inlineImages: boolean
|
|
139
|
+
readonly signal?: AbortSignal
|
|
140
|
+
readonly sandboxPath?: string
|
|
141
|
+
readonly imageOmissionNote?: string
|
|
142
|
+
}): Promise<PreparedAgentToolFileProjection> {
|
|
143
|
+
const { fileRef } = input
|
|
144
|
+
const signal = input.signal ?? NEVER_ABORTED_SIGNAL
|
|
145
|
+
signal.throwIfAborted()
|
|
146
|
+
const fileName = fileNameFor(fileRef)
|
|
147
|
+
const mediaType = normalizedMediaType(fileRef.mediaType) ?? "application/octet-stream"
|
|
148
|
+
const notes: string[] = []
|
|
149
|
+
let textExcerpt: string | undefined
|
|
150
|
+
let modelFileData: AgentFileDataProjection | undefined
|
|
151
|
+
|
|
152
|
+
const stat = await safeBlobStat(input.blobStorage, fileRef, notes, signal)
|
|
153
|
+
if (!stat) {
|
|
154
|
+
notes.push("[File omitted: blob content is not available or no longer matches this FileRef.]")
|
|
155
|
+
} else {
|
|
156
|
+
const shouldReadForText = shouldAttemptTextInline(mediaType, fileName, stat.sizeBytes)
|
|
157
|
+
const shouldReadForImage = input.inlineImages && shouldAttemptImageInline(mediaType, fileName)
|
|
158
|
+
const readLimit = shouldReadForText
|
|
159
|
+
? DEFAULT_AGENT_ATTACHMENT_LIMITS.textInlineMaxBytes + 4
|
|
160
|
+
: shouldReadForImage
|
|
161
|
+
? DEFAULT_AGENT_ATTACHMENT_LIMITS.sandboxFileMaxBytes
|
|
162
|
+
: 0
|
|
163
|
+
|
|
164
|
+
if (readLimit > 0) {
|
|
165
|
+
const read = await readBlobBytes(input.blobStorage, fileRef.blobId, readLimit, signal, {
|
|
166
|
+
allowPrefix: shouldReadForText,
|
|
167
|
+
})
|
|
168
|
+
if (read.ok) {
|
|
169
|
+
const text = shouldReadForText
|
|
170
|
+
? maybeTextExcerpt(read.bytes, mediaType, fileName, stat.sizeBytes, readLimit - 4)
|
|
171
|
+
: undefined
|
|
172
|
+
if (text) {
|
|
173
|
+
textExcerpt = text.text
|
|
174
|
+
if (text.truncated) {
|
|
175
|
+
notes.push("[Text file truncated for model input.]")
|
|
176
|
+
}
|
|
177
|
+
} else if (shouldReadForImage) {
|
|
178
|
+
const image = await maybeImageData({
|
|
179
|
+
bytes: read.bytes,
|
|
180
|
+
mediaType,
|
|
181
|
+
fileName,
|
|
182
|
+
inlineImages: true,
|
|
183
|
+
hasImageHint: true,
|
|
184
|
+
signal,
|
|
185
|
+
})
|
|
186
|
+
if (image?.ok) {
|
|
187
|
+
notes.push(...image.notes)
|
|
188
|
+
modelFileData = {
|
|
189
|
+
data: image.dataUrl,
|
|
190
|
+
mediaType: image.mediaType,
|
|
191
|
+
filename: fileName,
|
|
192
|
+
}
|
|
193
|
+
} else if (image) {
|
|
194
|
+
notes.push(...image.notes)
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
} else if (read.reason === "too_large") {
|
|
198
|
+
notes.push("[File not projected inline: file exceeds the attachment read limit.]")
|
|
199
|
+
} else {
|
|
200
|
+
notes.push(`[File not projected inline: ${read.reason}.]`)
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
if (!input.inlineImages && hasImageHint(mediaType, fileName)) {
|
|
205
|
+
notes.push(
|
|
206
|
+
input.imageOmissionNote ??
|
|
207
|
+
"[Image not inlined: the selected model does not advertise image input support.]"
|
|
208
|
+
)
|
|
209
|
+
}
|
|
210
|
+
if (!textExcerpt && !modelFileData && notes.length === 0) {
|
|
211
|
+
notes.push("[File contents are available through its sandbox path.]")
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
const body = [
|
|
216
|
+
...notes,
|
|
217
|
+
...(textExcerpt === undefined ? [] : ["<content>", textExcerpt, "</content>"]),
|
|
218
|
+
].join("\n")
|
|
219
|
+
const sandboxPathAttribute =
|
|
220
|
+
input.sandboxPath === undefined ? "" : ` sandboxPath="${escapeXmlAttribute(input.sandboxPath)}"`
|
|
221
|
+
const promptText = `<tool_file name="${escapeXmlAttribute(fileName)}" mediaType="${escapeXmlAttribute(
|
|
222
|
+
mediaType
|
|
223
|
+
)}" sizeBytes="${fileRef.sizeBytes}"${sandboxPathAttribute}>\n${body}\n</tool_file>`
|
|
224
|
+
return {
|
|
225
|
+
promptText,
|
|
226
|
+
...(modelFileData === undefined ? {} : { modelFileData }),
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
function fileWorkItems(messages: readonly AgentMessageRecord[]): AttachmentWorkItem[] {
|
|
231
|
+
const items: AttachmentWorkItem[] = []
|
|
232
|
+
const currentUserMessageId = latestUserMessageId(messages)
|
|
233
|
+
for (const message of messages) {
|
|
234
|
+
for (const file of listMessageAttachments(message)) {
|
|
235
|
+
items.push({
|
|
236
|
+
message,
|
|
237
|
+
...file,
|
|
238
|
+
inlineContent:
|
|
239
|
+
file.origin === "message-file" &&
|
|
240
|
+
message.role === "user" &&
|
|
241
|
+
message.id === currentUserMessageId,
|
|
242
|
+
})
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
const retainedAssistantKeys = new Set(
|
|
247
|
+
items
|
|
248
|
+
.filter((item) => item.message.role === "assistant")
|
|
249
|
+
.slice(-MAX_ASSISTANT_ATTACHMENTS)
|
|
250
|
+
.map((item) => item.key)
|
|
251
|
+
)
|
|
252
|
+
return items.filter(
|
|
253
|
+
(item) => item.message.role !== "assistant" || retainedAssistantKeys.has(item.key)
|
|
254
|
+
)
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
function latestUserMessageId(messages: readonly AgentMessageRecord[]): string | undefined {
|
|
258
|
+
for (let index = messages.length - 1; index >= 0; index -= 1) {
|
|
259
|
+
const message = messages[index]
|
|
260
|
+
if (message?.role === "user") return message.id
|
|
261
|
+
}
|
|
262
|
+
return undefined
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
async function prepareOneAttachment(input: {
|
|
266
|
+
readonly projectId: string
|
|
267
|
+
readonly threadId: string
|
|
268
|
+
readonly item: AttachmentWorkItem
|
|
269
|
+
readonly blobStorage: AgentRunFileStore
|
|
270
|
+
readonly apiBaseUrl: string
|
|
271
|
+
readonly contextDirectory: string
|
|
272
|
+
readonly inlineImages: boolean
|
|
273
|
+
readonly sandboxBytes: number
|
|
274
|
+
readonly textInlineBytes: number
|
|
275
|
+
readonly signal?: AbortSignal
|
|
276
|
+
}): Promise<{
|
|
277
|
+
readonly entry: PreparedAgentAttachment
|
|
278
|
+
readonly promptText: string
|
|
279
|
+
readonly modelFileData?: AgentFileDataProjection
|
|
280
|
+
readonly sandboxFile?: PreparedSandboxAttachmentFile
|
|
281
|
+
readonly sandboxBytesAdded: number
|
|
282
|
+
readonly textInlineBytesAdded: number
|
|
283
|
+
}> {
|
|
284
|
+
const { item } = input
|
|
285
|
+
const signal = input.signal ?? NEVER_ABORTED_SIGNAL
|
|
286
|
+
signal.throwIfAborted()
|
|
287
|
+
const key = item.key
|
|
288
|
+
const fileRef = item.fileRef
|
|
289
|
+
const fileName = fileNameFor(fileRef)
|
|
290
|
+
const mediaType = normalizedMediaType(fileRef.mediaType) ?? "application/octet-stream"
|
|
291
|
+
const contentPath = item.contentPath
|
|
292
|
+
const contentUrl = attachmentContentUrl({
|
|
293
|
+
apiBaseUrl: input.apiBaseUrl,
|
|
294
|
+
threadId: input.threadId,
|
|
295
|
+
messageId: item.message.id,
|
|
296
|
+
contentPath,
|
|
297
|
+
})
|
|
298
|
+
const notes: string[] = []
|
|
299
|
+
let bytes: Uint8Array | undefined
|
|
300
|
+
let inlineDisposition: PreparedAgentAttachment["inlineDisposition"] = "metadata-only"
|
|
301
|
+
let sandboxPath: string | undefined
|
|
302
|
+
let sandboxFile: PreparedSandboxAttachmentFile | undefined
|
|
303
|
+
let sandboxBytesAdded = 0
|
|
304
|
+
let textExcerpt: string | undefined
|
|
305
|
+
let textInlineBytesAdded = 0
|
|
306
|
+
let modelFileData: AgentFileDataProjection | undefined
|
|
307
|
+
|
|
308
|
+
const stat = await safeBlobStat(input.blobStorage, fileRef, notes, signal)
|
|
309
|
+
if (!stat) {
|
|
310
|
+
inlineDisposition = "omitted"
|
|
311
|
+
notes.push("[File omitted: blob content is not available or no longer matches this FileRef.]")
|
|
312
|
+
} else {
|
|
313
|
+
const canMaterializeFile = stat.sizeBytes <= DEFAULT_AGENT_ATTACHMENT_LIMITS.sandboxFileMaxBytes
|
|
314
|
+
const canMaterializeTotal =
|
|
315
|
+
input.sandboxBytes + stat.sizeBytes <= DEFAULT_AGENT_ATTACHMENT_LIMITS.sandboxTotalMaxBytes
|
|
316
|
+
const mayInlineContent = item.inlineContent
|
|
317
|
+
const remainingTextBytes = Math.max(0, TEXT_INLINE_TOTAL_MAX_BYTES - input.textInlineBytes)
|
|
318
|
+
const shouldReadForText =
|
|
319
|
+
mayInlineContent &&
|
|
320
|
+
remainingTextBytes > 0 &&
|
|
321
|
+
shouldAttemptTextInline(mediaType, fileName, stat.sizeBytes)
|
|
322
|
+
const shouldReadForImage =
|
|
323
|
+
mayInlineContent && input.inlineImages && shouldAttemptImageInline(mediaType, fileName)
|
|
324
|
+
const needsFullBytes = canMaterializeFile && canMaterializeTotal
|
|
325
|
+
const readLimit = needsFullBytes
|
|
326
|
+
? stat.sizeBytes
|
|
327
|
+
: shouldReadForText
|
|
328
|
+
? Math.min(DEFAULT_AGENT_ATTACHMENT_LIMITS.textInlineMaxBytes, remainingTextBytes) + 4
|
|
329
|
+
: shouldReadForImage
|
|
330
|
+
? DEFAULT_AGENT_ATTACHMENT_LIMITS.sandboxFileMaxBytes
|
|
331
|
+
: 0
|
|
332
|
+
|
|
333
|
+
if (needsFullBytes || readLimit > 0) {
|
|
334
|
+
const read = await readBlobBytes(input.blobStorage, fileRef.blobId, readLimit, signal, {
|
|
335
|
+
allowPrefix: shouldReadForText && !needsFullBytes,
|
|
336
|
+
})
|
|
337
|
+
if (read.ok) {
|
|
338
|
+
bytes = read.bytes
|
|
339
|
+
} else if (read.reason === "too_large") {
|
|
340
|
+
notes.push("[File not read inline: file exceeds the attachment read limit.]")
|
|
341
|
+
} else {
|
|
342
|
+
notes.push(`[File not read inline: ${read.reason}.]`)
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
if (bytes && needsFullBytes && bytes.byteLength === stat.sizeBytes) {
|
|
347
|
+
sandboxPath = sandboxAttachmentPath(
|
|
348
|
+
input.contextDirectory,
|
|
349
|
+
item.message.id,
|
|
350
|
+
item.sandboxName,
|
|
351
|
+
fileName
|
|
352
|
+
)
|
|
353
|
+
sandboxFile = { key, path: sandboxPath, bytes, fileRef }
|
|
354
|
+
sandboxBytesAdded = stat.sizeBytes
|
|
355
|
+
} else if (!canMaterializeFile) {
|
|
356
|
+
notes.push("[File not materialized in sandbox: file exceeds the per-file sandbox limit.]")
|
|
357
|
+
} else if (!canMaterializeTotal) {
|
|
358
|
+
notes.push("[File not materialized in sandbox: attachment sandbox budget exhausted.]")
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
if (bytes) {
|
|
362
|
+
const text =
|
|
363
|
+
mayInlineContent && remainingTextBytes > 0
|
|
364
|
+
? maybeTextExcerpt(bytes, mediaType, fileName, stat.sizeBytes, remainingTextBytes)
|
|
365
|
+
: undefined
|
|
366
|
+
if (text) {
|
|
367
|
+
textExcerpt = text.text
|
|
368
|
+
textInlineBytesAdded = Buffer.byteLength(text.text, "utf-8")
|
|
369
|
+
inlineDisposition = "text"
|
|
370
|
+
if (text.truncated) {
|
|
371
|
+
notes.push(
|
|
372
|
+
`[Text attachment truncated: showing first ${text.linesShown} line(s) within ${formatBytes(
|
|
373
|
+
Math.min(DEFAULT_AGENT_ATTACHMENT_LIMITS.textInlineMaxBytes, remainingTextBytes)
|
|
374
|
+
)}. Full file is available through the sandbox path or content URL.]`
|
|
375
|
+
)
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
if (!textExcerpt) {
|
|
380
|
+
const image = await maybeImageData({
|
|
381
|
+
bytes,
|
|
382
|
+
mediaType,
|
|
383
|
+
fileName,
|
|
384
|
+
inlineImages: mayInlineContent && input.inlineImages,
|
|
385
|
+
hasImageHint: hasImageHint(mediaType, fileName),
|
|
386
|
+
signal,
|
|
387
|
+
})
|
|
388
|
+
if (image) {
|
|
389
|
+
if (image.ok) {
|
|
390
|
+
inlineDisposition = "image"
|
|
391
|
+
notes.push(...image.notes)
|
|
392
|
+
modelFileData = {
|
|
393
|
+
data: image.dataUrl,
|
|
394
|
+
mediaType: image.mediaType,
|
|
395
|
+
filename: fileName,
|
|
396
|
+
}
|
|
397
|
+
} else if (image.notes.length > 0) {
|
|
398
|
+
notes.push(...image.notes)
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
} else if (hasImageHint(mediaType, fileName)) {
|
|
402
|
+
notes.push("[Image not inlined: attachment was treated as text based on its content.]")
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
if (mayInlineContent && !input.inlineImages && hasImageHint(mediaType, fileName)) {
|
|
407
|
+
notes.push("[Image not inlined: the selected model does not advertise image input support.]")
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
if (inlineDisposition === "metadata-only" && notes.length === 0) {
|
|
411
|
+
notes.push(
|
|
412
|
+
!item.inlineContent
|
|
413
|
+
? "[Historical file kept as metadata: use view_file with the sandbox path when its contents are needed.]"
|
|
414
|
+
: remainingTextBytes === 0 && shouldAttemptTextInline(mediaType, fileName, stat.sizeBytes)
|
|
415
|
+
? "[File not inlined: the attachment text budget is exhausted; use the sandbox path or content URL.]"
|
|
416
|
+
: "[File not inlined: available through the sandbox path or content URL.]"
|
|
417
|
+
)
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
const entry: PreparedAgentAttachment = {
|
|
422
|
+
key,
|
|
423
|
+
messageId: item.message.id,
|
|
424
|
+
partIndex: item.partIndex,
|
|
425
|
+
fileRef,
|
|
426
|
+
fileName,
|
|
427
|
+
mediaType,
|
|
428
|
+
sizeBytes: fileRef.sizeBytes,
|
|
429
|
+
contentPath,
|
|
430
|
+
contentUrl,
|
|
431
|
+
...(sandboxPath === undefined ? {} : { sandboxPath }),
|
|
432
|
+
inlineDisposition,
|
|
433
|
+
notes,
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
return {
|
|
437
|
+
entry,
|
|
438
|
+
promptText: attachmentPromptText(entry, textExcerpt),
|
|
439
|
+
...(modelFileData === undefined ? {} : { modelFileData }),
|
|
440
|
+
...(sandboxFile === undefined ? {} : { sandboxFile }),
|
|
441
|
+
sandboxBytesAdded,
|
|
442
|
+
textInlineBytesAdded,
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
async function safeBlobStat(
|
|
447
|
+
blobStorage: AgentRunFileStore,
|
|
448
|
+
fileRef: FileRef,
|
|
449
|
+
notes: string[],
|
|
450
|
+
signal: AbortSignal
|
|
451
|
+
): Promise<BlobInfo | null> {
|
|
452
|
+
signal.throwIfAborted()
|
|
453
|
+
let stat: BlobInfo | null
|
|
454
|
+
try {
|
|
455
|
+
stat = await waitForAbort(blobStorage.stat(fileRef.blobId), signal)
|
|
456
|
+
} catch (error) {
|
|
457
|
+
signal.throwIfAborted()
|
|
458
|
+
console.error("[SixbAgent] Failed to inspect an attachment blob.", error)
|
|
459
|
+
notes.push("[File omitted: blob storage metadata is unavailable.]")
|
|
460
|
+
return null
|
|
461
|
+
}
|
|
462
|
+
if (!stat || !blobMatchesFileRef(stat, fileRef)) {
|
|
463
|
+
return null
|
|
464
|
+
}
|
|
465
|
+
return stat
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
function blobMatchesFileRef(stat: BlobInfo, fileRef: FileRef): boolean {
|
|
469
|
+
return (
|
|
470
|
+
stat.blobId === fileRef.blobId &&
|
|
471
|
+
stat.digest === fileRef.digest &&
|
|
472
|
+
stat.sizeBytes === fileRef.sizeBytes
|
|
473
|
+
)
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
async function readBlobBytes(
|
|
477
|
+
blobStorage: AgentRunFileStore,
|
|
478
|
+
blobId: string,
|
|
479
|
+
maxBytes: number,
|
|
480
|
+
signal: AbortSignal,
|
|
481
|
+
options: { readonly allowPrefix?: boolean } = {}
|
|
482
|
+
): Promise<
|
|
483
|
+
| { readonly ok: true; readonly bytes: Uint8Array }
|
|
484
|
+
| { readonly ok: false; readonly reason: string }
|
|
485
|
+
> {
|
|
486
|
+
signal.throwIfAborted()
|
|
487
|
+
let stream: ReadableStream<Uint8Array>
|
|
488
|
+
try {
|
|
489
|
+
stream = await waitForAbort(blobStorage.open(blobId), signal)
|
|
490
|
+
} catch (error) {
|
|
491
|
+
signal.throwIfAborted()
|
|
492
|
+
console.error("[SixbAgent] Failed to open an attachment blob.", error)
|
|
493
|
+
return { ok: false, reason: "blob content is unavailable" }
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
const reader = stream.getReader()
|
|
497
|
+
const chunks: Uint8Array[] = []
|
|
498
|
+
let total = 0
|
|
499
|
+
const cancelOnAbort = () => {
|
|
500
|
+
void reader.cancel(signal.reason)
|
|
501
|
+
}
|
|
502
|
+
signal.addEventListener("abort", cancelOnAbort, { once: true })
|
|
503
|
+
// A cancel between the open and the listener fires no event.
|
|
504
|
+
if (signal.aborted) cancelOnAbort()
|
|
505
|
+
try {
|
|
506
|
+
for (;;) {
|
|
507
|
+
const { done, value } = await reader.read()
|
|
508
|
+
signal.throwIfAborted()
|
|
509
|
+
if (done) break
|
|
510
|
+
const remaining = maxBytes - total
|
|
511
|
+
if (value.byteLength > remaining) {
|
|
512
|
+
if (options.allowPrefix) {
|
|
513
|
+
if (remaining > 0) chunks.push(value.subarray(0, remaining))
|
|
514
|
+
total = maxBytes
|
|
515
|
+
await reader.cancel().catch(() => {})
|
|
516
|
+
break
|
|
517
|
+
}
|
|
518
|
+
await reader.cancel().catch(() => {})
|
|
519
|
+
return { ok: false, reason: "too_large" }
|
|
520
|
+
}
|
|
521
|
+
total += value.byteLength
|
|
522
|
+
chunks.push(value)
|
|
523
|
+
}
|
|
524
|
+
} finally {
|
|
525
|
+
signal.removeEventListener("abort", cancelOnAbort)
|
|
526
|
+
reader.releaseLock()
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
const result = new Uint8Array(total)
|
|
530
|
+
let offset = 0
|
|
531
|
+
for (const chunk of chunks) {
|
|
532
|
+
result.set(chunk, offset)
|
|
533
|
+
offset += chunk.byteLength
|
|
534
|
+
}
|
|
535
|
+
return { ok: true, bytes: result }
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
function shouldAttemptTextInline(mediaType: string, fileName: string, sizeBytes: number): boolean {
|
|
539
|
+
return (
|
|
540
|
+
sizeBytes <= DEFAULT_AGENT_ATTACHMENT_LIMITS.sandboxFileMaxBytes &&
|
|
541
|
+
(isTextMediaType(mediaType) || looksLikeTextFileName(fileName))
|
|
542
|
+
)
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
function shouldAttemptImageInline(mediaType: string, fileName: string): boolean {
|
|
546
|
+
return hasImageHint(mediaType, fileName)
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
function maybeTextExcerpt(
|
|
550
|
+
bytes: Uint8Array,
|
|
551
|
+
mediaType: string,
|
|
552
|
+
fileName: string,
|
|
553
|
+
sizeBytes: number,
|
|
554
|
+
maxBytes: number
|
|
555
|
+
): { readonly text: string; readonly truncated: boolean; readonly linesShown: number } | undefined {
|
|
556
|
+
const declaredText = isTextMediaType(mediaType) || looksLikeTextFileName(fileName)
|
|
557
|
+
if (!declaredText && !looksLikeUtf8Text(bytes)) {
|
|
558
|
+
return undefined
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
let text: string
|
|
562
|
+
try {
|
|
563
|
+
text = new TextDecoder("utf-8", { fatal: !declaredText }).decode(
|
|
564
|
+
bytes.subarray(0, Math.min(bytes.byteLength, maxBytes + 4))
|
|
565
|
+
)
|
|
566
|
+
} catch {
|
|
567
|
+
return undefined
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
const truncated = truncateText(text, {
|
|
571
|
+
...DEFAULT_AGENT_ATTACHMENT_LIMITS,
|
|
572
|
+
textInlineMaxBytes: Math.min(DEFAULT_AGENT_ATTACHMENT_LIMITS.textInlineMaxBytes, maxBytes),
|
|
573
|
+
})
|
|
574
|
+
return {
|
|
575
|
+
text: truncated.text,
|
|
576
|
+
truncated: truncated.truncated || sizeBytes > bytes.byteLength,
|
|
577
|
+
linesShown: truncated.linesShown,
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
function truncateText(
|
|
582
|
+
value: string,
|
|
583
|
+
limits: AgentAttachmentLimits
|
|
584
|
+
): { readonly text: string; readonly truncated: boolean; readonly linesShown: number } {
|
|
585
|
+
const lines = value.split("\n")
|
|
586
|
+
const out: string[] = []
|
|
587
|
+
let bytes = 0
|
|
588
|
+
let truncated = false
|
|
589
|
+
|
|
590
|
+
for (const line of lines) {
|
|
591
|
+
if (out.length >= limits.textInlineMaxLines) {
|
|
592
|
+
truncated = true
|
|
593
|
+
break
|
|
594
|
+
}
|
|
595
|
+
const separatorBytes = out.length === 0 ? 0 : 1
|
|
596
|
+
const lineBytes = Buffer.byteLength(line, "utf-8") + separatorBytes
|
|
597
|
+
if (bytes + lineBytes > limits.textInlineMaxBytes) {
|
|
598
|
+
truncated = true
|
|
599
|
+
break
|
|
600
|
+
}
|
|
601
|
+
out.push(line)
|
|
602
|
+
bytes += lineBytes
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
return { text: out.join("\n"), truncated, linesShown: out.length }
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
function looksLikeUtf8Text(bytes: Uint8Array): boolean {
|
|
609
|
+
if (bytes.length === 0) {
|
|
610
|
+
return true
|
|
611
|
+
}
|
|
612
|
+
try {
|
|
613
|
+
new TextDecoder("utf-8", { fatal: true }).decode(bytes)
|
|
614
|
+
} catch {
|
|
615
|
+
return false
|
|
616
|
+
}
|
|
617
|
+
const sampleLength = Math.min(bytes.length, 1024)
|
|
618
|
+
let control = 0
|
|
619
|
+
for (let index = 0; index < sampleLength; index += 1) {
|
|
620
|
+
const byte = bytes[index]
|
|
621
|
+
if (byte !== 9 && byte !== 10 && byte !== 13 && byte < 32) {
|
|
622
|
+
control += 1
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
return control / sampleLength < 0.02
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
async function maybeImageData(input: {
|
|
629
|
+
readonly bytes: Uint8Array
|
|
630
|
+
readonly mediaType: string
|
|
631
|
+
readonly fileName: string
|
|
632
|
+
readonly inlineImages: boolean
|
|
633
|
+
readonly hasImageHint: boolean
|
|
634
|
+
readonly signal: AbortSignal
|
|
635
|
+
}): Promise<
|
|
636
|
+
| {
|
|
637
|
+
readonly ok: true
|
|
638
|
+
readonly dataUrl: URL
|
|
639
|
+
readonly mediaType: string
|
|
640
|
+
readonly notes: readonly string[]
|
|
641
|
+
}
|
|
642
|
+
| { readonly ok: false; readonly notes: readonly string[] }
|
|
643
|
+
| undefined
|
|
644
|
+
> {
|
|
645
|
+
if (!input.inlineImages) {
|
|
646
|
+
return undefined
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
input.signal.throwIfAborted()
|
|
650
|
+
const image = await processAgentImageAttachment({
|
|
651
|
+
bytes: input.bytes,
|
|
652
|
+
declaredMediaType: input.mediaType,
|
|
653
|
+
fileName: input.fileName,
|
|
654
|
+
limits: DEFAULT_AGENT_ATTACHMENT_LIMITS,
|
|
655
|
+
signal: input.signal,
|
|
656
|
+
})
|
|
657
|
+
input.signal.throwIfAborted()
|
|
658
|
+
if (!image.ok) {
|
|
659
|
+
return input.hasImageHint ? { ok: false, notes: image.notes } : undefined
|
|
660
|
+
}
|
|
661
|
+
return {
|
|
662
|
+
ok: true,
|
|
663
|
+
dataUrl: image.dataUrl,
|
|
664
|
+
mediaType: image.mediaType,
|
|
665
|
+
notes: image.notes,
|
|
666
|
+
}
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
export function modelSupportsInlineImages(model: LanguageModel): boolean {
|
|
670
|
+
const { inputMediaTypes } = model.definition.capabilities
|
|
671
|
+
return (
|
|
672
|
+
inputMediaTypes === "any" ||
|
|
673
|
+
inputMediaTypes?.some((mediaType) => mediaType.toLowerCase().startsWith("image/")) === true
|
|
674
|
+
)
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
function attachmentPromptText(
|
|
678
|
+
entry: PreparedAgentAttachment,
|
|
679
|
+
textExcerpt: string | undefined
|
|
680
|
+
): string {
|
|
681
|
+
const attrs = [
|
|
682
|
+
`key="${escapeXmlAttribute(entry.key)}"`,
|
|
683
|
+
`messageId="${escapeXmlAttribute(entry.messageId)}"`,
|
|
684
|
+
`partIndex="${entry.partIndex}"`,
|
|
685
|
+
`name="${escapeXmlAttribute(entry.fileName)}"`,
|
|
686
|
+
`mediaType="${escapeXmlAttribute(entry.mediaType)}"`,
|
|
687
|
+
`sizeBytes="${entry.sizeBytes}"`,
|
|
688
|
+
...(entry.fileRef.logicalPath
|
|
689
|
+
? [`logicalPath="${escapeXmlAttribute(entry.fileRef.logicalPath)}"`]
|
|
690
|
+
: []),
|
|
691
|
+
`contentUrl="${escapeXmlAttribute(entry.contentUrl)}"`,
|
|
692
|
+
...(entry.sandboxPath ? [`sandboxPath="${escapeXmlAttribute(entry.sandboxPath)}"`] : []),
|
|
693
|
+
].join(" ")
|
|
694
|
+
const body = [
|
|
695
|
+
...entry.notes,
|
|
696
|
+
...(textExcerpt === undefined ? [] : ["<content>", textExcerpt, "</content>"]),
|
|
697
|
+
].join("\n")
|
|
698
|
+
return `<attachment ${attrs}>\n${body}\n</attachment>`
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
function manifestEntry(entry: PreparedAgentAttachment) {
|
|
702
|
+
return {
|
|
703
|
+
key: entry.key,
|
|
704
|
+
messageId: entry.messageId,
|
|
705
|
+
partIndex: entry.partIndex,
|
|
706
|
+
fileName: entry.fileName,
|
|
707
|
+
mediaType: entry.mediaType,
|
|
708
|
+
sizeBytes: entry.sizeBytes,
|
|
709
|
+
...(entry.fileRef.logicalPath ? { logicalPath: entry.fileRef.logicalPath } : {}),
|
|
710
|
+
digest: entry.fileRef.digest,
|
|
711
|
+
contentPath: entry.contentPath,
|
|
712
|
+
contentUrl: entry.contentUrl,
|
|
713
|
+
...(entry.sandboxPath === undefined ? {} : { sandboxPath: entry.sandboxPath }),
|
|
714
|
+
inlineDisposition: entry.inlineDisposition,
|
|
715
|
+
notes: entry.notes,
|
|
716
|
+
}
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
function attachmentContentUrl(input: {
|
|
720
|
+
readonly apiBaseUrl: string
|
|
721
|
+
readonly threadId: string
|
|
722
|
+
readonly messageId: string
|
|
723
|
+
readonly contentPath: string
|
|
724
|
+
}): string {
|
|
725
|
+
const base = input.apiBaseUrl.replace(/\/+$/, "")
|
|
726
|
+
return `${base}/api/agent-threads/${encodeURIComponent(
|
|
727
|
+
input.threadId
|
|
728
|
+
)}/messages/${encodeURIComponent(input.messageId)}/files/content?path=${encodeURIComponent(
|
|
729
|
+
input.contentPath
|
|
730
|
+
)}`
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
function sandboxAttachmentPath(
|
|
734
|
+
contextDirectory: string,
|
|
735
|
+
messageId: string,
|
|
736
|
+
sandboxName: string,
|
|
737
|
+
fileName: string
|
|
738
|
+
): string {
|
|
739
|
+
return posix.join(
|
|
740
|
+
contextDirectory,
|
|
741
|
+
"attachments",
|
|
742
|
+
safePathSegment(messageId),
|
|
743
|
+
`${safePathSegment(sandboxName)}-${safeFileName(fileName)}`
|
|
744
|
+
)
|
|
745
|
+
}
|
|
746
|
+
|
|
747
|
+
function fileNameFor(fileRef: FileRef): string {
|
|
748
|
+
const fromFileName = lastPathSegment(fileRef.fileName)
|
|
749
|
+
if (fromFileName) return fromFileName
|
|
750
|
+
const fromLogicalPath = lastPathSegment(fileRef.logicalPath)
|
|
751
|
+
return fromLogicalPath || `${fileRef.blobId}.bin`
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
function lastPathSegment(value: string | undefined): string | undefined {
|
|
755
|
+
const segment = value?.split(/[\\/]/).filter(Boolean).at(-1)?.trim()
|
|
756
|
+
return segment || undefined
|
|
757
|
+
}
|
|
758
|
+
|
|
759
|
+
function safeFileName(value: string): string {
|
|
760
|
+
const cleaned = value
|
|
761
|
+
.normalize("NFKC")
|
|
762
|
+
.replace(/[\u0000-\u001f\u007f]/g, "_")
|
|
763
|
+
.replace(/[\\/]/g, "_")
|
|
764
|
+
.replace(/^\.+$/, "_")
|
|
765
|
+
.slice(0, 120)
|
|
766
|
+
return cleaned || "attachment.bin"
|
|
767
|
+
}
|
|
768
|
+
|
|
769
|
+
function safePathSegment(value: string): string {
|
|
770
|
+
return safeFileName(value).replace(/[^A-Za-z0-9._-]/g, "_") || "message"
|
|
771
|
+
}
|
|
772
|
+
|
|
773
|
+
function normalizedMediaType(value: string | undefined): string | undefined {
|
|
774
|
+
const normalized = value?.split(";")[0]?.trim().toLowerCase()
|
|
775
|
+
return normalized || undefined
|
|
776
|
+
}
|
|
777
|
+
|
|
778
|
+
function isTextMediaType(mediaType: string): boolean {
|
|
779
|
+
return (
|
|
780
|
+
mediaType.startsWith("text/") ||
|
|
781
|
+
mediaType === "application/json" ||
|
|
782
|
+
mediaType === "application/xml" ||
|
|
783
|
+
mediaType === "application/yaml" ||
|
|
784
|
+
mediaType === "application/x-yaml" ||
|
|
785
|
+
mediaType === "application/javascript" ||
|
|
786
|
+
mediaType === "application/typescript" ||
|
|
787
|
+
mediaType === "application/csv"
|
|
788
|
+
)
|
|
789
|
+
}
|
|
790
|
+
|
|
791
|
+
function looksLikeTextFileName(fileName: string): boolean {
|
|
792
|
+
const lower = fileName.toLowerCase()
|
|
793
|
+
return [
|
|
794
|
+
".txt",
|
|
795
|
+
".md",
|
|
796
|
+
".markdown",
|
|
797
|
+
".json",
|
|
798
|
+
".jsonl",
|
|
799
|
+
".csv",
|
|
800
|
+
".ts",
|
|
801
|
+
".tsx",
|
|
802
|
+
".js",
|
|
803
|
+
".jsx",
|
|
804
|
+
".mjs",
|
|
805
|
+
".cjs",
|
|
806
|
+
".yml",
|
|
807
|
+
".yaml",
|
|
808
|
+
".xml",
|
|
809
|
+
".html",
|
|
810
|
+
".css",
|
|
811
|
+
".scss",
|
|
812
|
+
".log",
|
|
813
|
+
].some((extension) => lower.endsWith(extension))
|
|
814
|
+
}
|
|
815
|
+
|
|
816
|
+
function hasImageHint(mediaType: string, fileName: string): boolean {
|
|
817
|
+
return isImageMediaType(mediaType) || looksLikeImageFileName(fileName)
|
|
818
|
+
}
|
|
819
|
+
|
|
820
|
+
function isImageMediaType(mediaType: string): boolean {
|
|
821
|
+
return mediaType.startsWith("image/")
|
|
822
|
+
}
|
|
823
|
+
|
|
824
|
+
function looksLikeImageFileName(fileName: string): boolean {
|
|
825
|
+
const lower = fileName.toLowerCase()
|
|
826
|
+
return [".png", ".jpg", ".jpeg", ".webp", ".gif", ".bmp"].some((extension) =>
|
|
827
|
+
lower.endsWith(extension)
|
|
828
|
+
)
|
|
829
|
+
}
|
|
830
|
+
|
|
831
|
+
function escapeXmlAttribute(value: string): string {
|
|
832
|
+
return value
|
|
833
|
+
.replace(/&/g, "&")
|
|
834
|
+
.replace(/"/g, """)
|
|
835
|
+
.replace(/</g, "<")
|
|
836
|
+
.replace(/>/g, ">")
|
|
837
|
+
}
|
|
838
|
+
|
|
839
|
+
export function formatBytes(bytes: number): string {
|
|
840
|
+
if (bytes < 1024) return `${bytes}B`
|
|
841
|
+
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)}KB`
|
|
842
|
+
return `${(bytes / (1024 * 1024)).toFixed(1)}MB`
|
|
843
|
+
}
|
|
844
|
+
|
|
845
|
+
export {
|
|
846
|
+
attachmentKey,
|
|
847
|
+
attachmentKeyMessageId,
|
|
848
|
+
findMessageAttachment,
|
|
849
|
+
toolResultAttachmentKey,
|
|
850
|
+
} from "@sixb/core/internal/agents"
|