@capybara-hq/kernel 0.1.0-rc.50 → 0.1.0-rc.52
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/bootstrap.json +5 -5
- package/dist/catalog/marketplaces.service.d.ts +1 -1
- package/dist/config/schema.d.ts +6 -0
- package/dist/config/schema.js +60 -0
- package/dist/conversations/attachments.service.d.ts +78 -10
- package/dist/conversations/attachments.service.js +233 -16
- package/dist/conversations/events.d.ts +9 -0
- package/dist/conversations/events.js +26 -3
- package/dist/db/kernel-schema.d.ts +5 -2
- package/dist/evals/reconstruct.d.ts +6 -1
- package/dist/evals/reconstruct.js +8 -4
- package/dist/evals/recorded-tools.d.ts +7 -0
- package/dist/evals/recorded-tools.js +2 -0
- package/dist/infra/config/kernel-config.service.js +8 -0
- package/dist/media/image-header.d.ts +10 -0
- package/dist/media/image-header.js +87 -0
- package/dist/models/images.d.ts +2 -0
- package/dist/models/images.js +6 -4
- package/dist/models/purposes.d.ts +17 -57
- package/dist/models/purposes.js +25 -4
- package/dist/runtime/context/build.d.ts +73 -28
- package/dist/runtime/context/build.js +179 -33
- package/dist/runtime/model-call.js +16 -10
- package/dist/runtime/usage-report.d.ts +3 -2
- package/dist/runtime/usage-report.js +3 -2
- package/dist/tools/builtins/builtin-tools.d.ts +8 -1
- package/dist/tools/builtins/builtin-tools.js +54 -3
- package/dist/tools/builtins/conversation-files.d.ts +42 -0
- package/dist/tools/builtins/conversation-files.js +105 -0
- package/dist/tools/builtins/image/generate.d.ts +3 -3
- package/dist/tools/builtins/image/generate.js +63 -71
- package/dist/tools/builtins/image/size.d.ts +12 -0
- package/dist/tools/builtins/image/size.js +36 -0
- package/dist/tools/builtins/sandbox/common.d.ts +7 -0
- package/dist/tools/builtins/sandbox/read.d.ts +53 -2
- package/dist/tools/builtins/sandbox/read.js +260 -51
- package/dist/tools/builtins/size-text.d.ts +2 -0
- package/dist/tools/builtins/size-text.js +8 -0
- package/dist/tools/builtins/vision/read-image.d.ts +59 -0
- package/dist/tools/builtins/vision/read-image.js +220 -0
- package/dist/tools/pipeline.js +22 -3
- package/dist/tools/registry.d.ts +9 -1
- package/package.json +3 -3
- package/src/migrations/0163_read_attachments.sql +10 -0
|
@@ -1,6 +1,12 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { posix } from "node:path";
|
|
2
|
+
import { IMAGE_MEDIA_TYPES, MEDIA_LIMITS, ToolError } from "@capybara-hq/plugin-sdk";
|
|
3
|
+
import { ApiError } from "../../../errors.js";
|
|
4
|
+
import { sniffImage } from "../../../media/image-header.js";
|
|
2
5
|
import { viewPath } from "../../view.js";
|
|
3
|
-
import {
|
|
6
|
+
import { findConversationFile, } from "../conversation-files.js";
|
|
7
|
+
import { sizeText } from "../size-text.js";
|
|
8
|
+
import { readImageWithVisionModel } from "../vision/read-image.js";
|
|
9
|
+
import { checkFilePathShape, checkToolPath, clip, display, inToolSandbox, looksBinary, resolveToolPath, sandboxBaseTimeoutMs, sandboxConversationOf, sandboxUsable, unavailableWhenNoSandbox, withNotices, } from "./common.js";
|
|
4
10
|
import { normalizeSandboxPath, recordedFile } from "./file-state.js";
|
|
5
11
|
/** 不给 `limit` 时一次读的行数。 */
|
|
6
12
|
const DEFAULT_LIMIT = 2000;
|
|
@@ -11,43 +17,84 @@ export const READ_MAX_BYTES = 10 * 1024 * 1024;
|
|
|
11
17
|
const SPEC = {
|
|
12
18
|
name: "Read",
|
|
13
19
|
// Display only (the tool row; not in the fingerprint, never sent to the model).
|
|
14
|
-
keyArgs: ["file_path"],
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
"
|
|
18
|
-
"
|
|
19
|
-
"
|
|
20
|
-
"
|
|
21
|
-
"
|
|
22
|
-
"
|
|
23
|
-
"
|
|
20
|
+
keyArgs: ["file_path", "file_id"],
|
|
21
|
+
// vision-read design §1.5, verbatim
|
|
22
|
+
description: "Read a file and return it to you. Text files come back with line numbers; pass offset and limit " +
|
|
23
|
+
"for part of a long file. Images (PNG, JPEG, GIF, WebP up to 5 MB) are shown to you; if this " +
|
|
24
|
+
"model cannot view images, the organization's vision model reads the image and answers prompt, " +
|
|
25
|
+
"which is a billed model call. Images read are stored with the conversation. Other binary files " +
|
|
26
|
+
"are not shown; use Bash. file_path is an absolute path on the device (under the workspace, " +
|
|
27
|
+
"skills or temporary directory; anywhere in auto mode); file_id is an attachment or artifact id " +
|
|
28
|
+
"of this conversation and needs no device. Do not use it to list directories; use Glob instead. " +
|
|
29
|
+
"Read a file before you write it: Write and Edit fail on a file you have not read, or one changed " +
|
|
30
|
+
"since you read it.",
|
|
24
31
|
inputSchema: {
|
|
25
32
|
type: "object",
|
|
26
33
|
properties: {
|
|
27
34
|
file_path: {
|
|
28
35
|
type: "string",
|
|
29
36
|
minLength: 1,
|
|
30
|
-
description: "Absolute path of the file, e.g. src/main.py in the workspace directory.",
|
|
37
|
+
description: "Absolute path of the file on the device, e.g. src/main.py in the workspace directory.",
|
|
38
|
+
},
|
|
39
|
+
file_id: {
|
|
40
|
+
type: "string",
|
|
41
|
+
minLength: 1,
|
|
42
|
+
description: "Id of an attachment or artifact of this conversation (instead of file_path).",
|
|
31
43
|
},
|
|
32
44
|
offset: {
|
|
33
45
|
type: "integer",
|
|
34
46
|
minimum: 1,
|
|
35
|
-
description: "First line to read (1-based). Default 1.",
|
|
47
|
+
description: "First line to read (1-based), text files only. Default 1.",
|
|
36
48
|
},
|
|
37
49
|
limit: {
|
|
38
50
|
type: "integer",
|
|
39
51
|
minimum: 1,
|
|
40
|
-
description: `Maximum number of lines to read. Default ${DEFAULT_LIMIT}.`,
|
|
52
|
+
description: `Maximum number of lines to read, text files only. Default ${DEFAULT_LIMIT}.`,
|
|
53
|
+
},
|
|
54
|
+
prompt: {
|
|
55
|
+
type: "string",
|
|
56
|
+
minLength: 1,
|
|
57
|
+
description: "What to look for in an image; used only when the organization's vision model reads it for you.",
|
|
41
58
|
},
|
|
42
59
|
},
|
|
43
|
-
required: ["file_path"],
|
|
44
60
|
additionalProperties: false,
|
|
45
61
|
},
|
|
46
62
|
annotations: { readOnlyHint: true },
|
|
47
63
|
};
|
|
64
|
+
/** The `Read` description (vision-read design §1.5; verbatim). */
|
|
65
|
+
export const READ_DESCRIPTION = SPEC.description;
|
|
48
66
|
const notFound = (path) => `File not found: ${clip(path, 200)}. Check the path with Glob.`;
|
|
49
67
|
const isDirectory = (path) => `${clip(path, 200)} is a directory; use Glob to list its files.`;
|
|
50
68
|
const pastEnd = (offset, total) => `offset ${offset} is past the end of the file (${total} lines); pass an offset of at most ${total}.`;
|
|
69
|
+
/** Neither or both of `file_path` and `file_id` (spec §1.1). */
|
|
70
|
+
export const READ_ONE_SOURCE_TEXT = "Pass exactly one of file_path (a path on the device) and file_id (an attachment or artifact id).";
|
|
71
|
+
/** A `file_path` read without a usable device (spec §1.1; verbatim). */
|
|
72
|
+
export const READ_NO_DEVICE_TEXT = "This agent has no device; pass file_id to read an attachment or artifact.";
|
|
73
|
+
/** A `file_id` that is no file of this conversation or its root. */
|
|
74
|
+
export const unknownFileIdText = (id) => `file_id ${clip(id, 100)} is not an attachment or artifact of this conversation; pass the id of one.`;
|
|
75
|
+
/** A `file_id` read in a deployment without an object store. */
|
|
76
|
+
export const READ_NO_STORAGE_TEXT = "File storage is not configured in this deployment, so file_id cannot be read; pass file_path to read a file on the device.";
|
|
77
|
+
/** An image over `MEDIA_LIMITS.imageBytes` (spec §1.2; verbatim). */
|
|
78
|
+
export const tooLargeText = (name, size) => `Image ${name} is ${sizeText(size)}; the limit is 5 MB. Make a smaller copy and Read it.`;
|
|
79
|
+
/** A PDF (sniffed `%PDF-`; spec §1.5; verbatim). */
|
|
80
|
+
export const pdfText = (size) => `PDF document (${sizeText(size)}). Read does not parse PDFs; images it reads are shown, so pages rendered as images can be read.`;
|
|
81
|
+
/** Any other binary file (unchanged). */
|
|
82
|
+
const binaryText = (size) => `Binary file (${size} bytes); use Bash to inspect it.`;
|
|
83
|
+
/** The first line of an image result (spec §1.2; verbatim). */
|
|
84
|
+
export const readImageText = (name, mediaType, size, dims, attachmentId) => `Read image ${name} (${mediaType}, ${sizeText(size)}${dimsText(dims)}; file_id ${attachmentId}).`;
|
|
85
|
+
/** The fallback answer paragraph (spec §1.2; verbatim). */
|
|
86
|
+
export const fallbackAnswerText = (provider, model, answer) => `${provider}/${model} read the image for you (this model cannot view images):\n${answer}`;
|
|
87
|
+
/** An image read but not stored: the per-conversation cap, or no object store. */
|
|
88
|
+
export const notStoredText = (name, mediaType, size, dims, reason) => `Read image ${name} (${mediaType}, ${sizeText(size)}${dimsText(dims)}). ${reason === "cap"
|
|
89
|
+
? "This conversation reached its limit for stored images"
|
|
90
|
+
: "File storage is not configured in this deployment"}, so the image is not stored: it is not shown and will not stay in the history.`;
|
|
91
|
+
const dimsText = (d) => d.width !== undefined && d.height !== undefined ? `, ${d.width}×${d.height}` : "";
|
|
92
|
+
/** The file names a raster image Read can show by its extension (an SVG is text). */
|
|
93
|
+
const IMAGE_EXTENSION = /\.(png|jpe?g|gif|webp)$/i;
|
|
94
|
+
/** A content type of one of the raster images Read can show (`image/svg+xml` is not one). */
|
|
95
|
+
const isRasterType = (contentType) => IMAGE_MEDIA_TYPES.includes(contentType.split(";")[0]?.trim().toLowerCase() ?? "");
|
|
96
|
+
const PDF_MAGIC = [0x25, 0x50, 0x44, 0x46, 0x2d];
|
|
97
|
+
const isPdf = (data) => PDF_MAGIC.every((b, i) => data[i] === b);
|
|
51
98
|
/** The file's lines (a final newline does not start another line). */
|
|
52
99
|
function fileLines(text) {
|
|
53
100
|
const lines = text.split("\n");
|
|
@@ -75,60 +122,222 @@ export function numberLines(text, offset, limit) {
|
|
|
75
122
|
}
|
|
76
123
|
return out.join("\n");
|
|
77
124
|
}
|
|
78
|
-
/**
|
|
125
|
+
/**
|
|
126
|
+
* The builtin `Read` (read-only; never asks, even when the org's sandbox tool policy is ask): a
|
|
127
|
+
* text file with line numbers, an image shown to the model (or read by the `vision` purpose for a
|
|
128
|
+
* model that cannot view images) and stored with the conversation, a PDF or other binary file
|
|
129
|
+
* named only. `file_path` reads the device; `file_id` an attachment or artifact of the
|
|
130
|
+
* conversation or its root, never entering the device. Listed when a device is usable or (with
|
|
131
|
+
* `deps.read`) an object store is there.
|
|
132
|
+
*/
|
|
79
133
|
export function sandboxReadTool(deps) {
|
|
134
|
+
const sandboxUnavailable = unavailableWhenNoSandbox(deps);
|
|
80
135
|
return {
|
|
81
136
|
spec: SPEC,
|
|
82
137
|
defaultPolicy: "allow",
|
|
83
|
-
unavailable:
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
138
|
+
unavailable: async (scope) => {
|
|
139
|
+
const reason = await sandboxUnavailable(scope);
|
|
140
|
+
if (reason === null)
|
|
141
|
+
return null;
|
|
142
|
+
return deps.read !== undefined && deps.storage.available === true ? null : reason;
|
|
143
|
+
},
|
|
144
|
+
timeoutMs: () => {
|
|
145
|
+
const cfg = deps.config.get();
|
|
146
|
+
return Math.max(sandboxBaseTimeoutMs(cfg), cfg.models.visionTimeoutMs + 10_000);
|
|
147
|
+
},
|
|
148
|
+
async run(raw, ctx) {
|
|
149
|
+
const input = raw;
|
|
150
|
+
if ((input.file_path === undefined) === (input.file_id === undefined)) {
|
|
151
|
+
throw new ToolError(READ_ONE_SOURCE_TEXT);
|
|
152
|
+
}
|
|
153
|
+
if (input.file_id !== undefined)
|
|
154
|
+
return readById(deps, ctx, input, input.file_id);
|
|
155
|
+
const filePath = input.file_path;
|
|
156
|
+
checkFilePathShape(filePath);
|
|
157
|
+
if (!(await sandboxUsable(deps, ctx.orgId, sandboxConversationOf(ctx)))) {
|
|
158
|
+
throw new ToolError(READ_NO_DEVICE_TEXT);
|
|
159
|
+
}
|
|
88
160
|
let path = "";
|
|
89
161
|
const { value, notices } = await inToolSandbox(deps, ctx, async (s) => {
|
|
90
162
|
const { h, p, signal } = s;
|
|
91
|
-
path = checkToolPath(resolveToolPath(
|
|
163
|
+
path = checkToolPath(resolveToolPath(filePath, s), s, "file_path");
|
|
92
164
|
const st = await p.stat(h, path, signal);
|
|
93
165
|
if (st === null)
|
|
94
166
|
throw new ToolError(notFound(path));
|
|
95
167
|
if (st.isDir)
|
|
96
168
|
throw new ToolError(isDirectory(path));
|
|
169
|
+
// read as before (up to the cap) so the file state is recorded for the read-before-write
|
|
170
|
+
// guard even when the image is too large to show (readImage gives the too-large text)
|
|
97
171
|
const got = await p.readFile(h, path, { maxBytes: READ_MAX_BYTES, signal });
|
|
98
172
|
if (got === null)
|
|
99
173
|
throw new ToolError(notFound(path));
|
|
100
174
|
return { ...got, size: st.size };
|
|
101
175
|
});
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
toLine: Math.min(fileLines(decoded).length, offset - 1 + limit),
|
|
117
|
-
};
|
|
118
|
-
if (value.truncated) {
|
|
119
|
-
text += `\n[Only the first ${READ_MAX_BYTES} bytes of this ${value.size}-byte file were read; use Bash to read the rest.]`;
|
|
120
|
-
}
|
|
121
|
-
}
|
|
176
|
+
const name = posix.basename(path);
|
|
177
|
+
const summary = { display: display(`读取 ${clip(path, 180)}`, `Read ${clip(path, 180)}`) };
|
|
178
|
+
const view = (range) => ({
|
|
179
|
+
kind: "read",
|
|
180
|
+
path: viewPath(path),
|
|
181
|
+
...range,
|
|
182
|
+
file: recordedFile(normalizeSandboxPath(path), value.data, value.size),
|
|
183
|
+
});
|
|
184
|
+
const out = await readContent(deps, ctx, input, {
|
|
185
|
+
name,
|
|
186
|
+
data: value.data,
|
|
187
|
+
size: value.size,
|
|
188
|
+
truncated: value.truncated,
|
|
189
|
+
});
|
|
122
190
|
return {
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
path: viewPath(path),
|
|
128
|
-
...range,
|
|
129
|
-
file: recordedFile(normalizeSandboxPath(path), value.data, value.size),
|
|
130
|
-
},
|
|
191
|
+
...out,
|
|
192
|
+
content: [{ type: "text", text: withNotices(notices, out.text) }],
|
|
193
|
+
...summary,
|
|
194
|
+
view: view(out.range),
|
|
131
195
|
};
|
|
132
196
|
},
|
|
133
197
|
};
|
|
134
198
|
}
|
|
199
|
+
/**
|
|
200
|
+
* A `file_id` read: the file of the conversation or its root, read from the object store (no
|
|
201
|
+
* device). It does not feed the read-before-write guard.
|
|
202
|
+
*/
|
|
203
|
+
async function readById(deps, ctx, input, id) {
|
|
204
|
+
const read = deps.read;
|
|
205
|
+
if (read === undefined)
|
|
206
|
+
throw new ToolError(READ_NO_STORAGE_TEXT);
|
|
207
|
+
let found;
|
|
208
|
+
try {
|
|
209
|
+
found = await findConversationFile(read.files, {
|
|
210
|
+
orgId: ctx.orgId,
|
|
211
|
+
conversationId: ctx.conversationId,
|
|
212
|
+
rootConversationId: sandboxConversationOf(ctx),
|
|
213
|
+
id,
|
|
214
|
+
// one byte past the cap tells a truncated read
|
|
215
|
+
maxBytes: READ_MAX_BYTES + 1,
|
|
216
|
+
signal: ctx.signal,
|
|
217
|
+
});
|
|
218
|
+
}
|
|
219
|
+
catch (e) {
|
|
220
|
+
if (e instanceof ApiError && e.code === "storage.unavailable") {
|
|
221
|
+
throw new ToolError(READ_NO_STORAGE_TEXT);
|
|
222
|
+
}
|
|
223
|
+
throw e;
|
|
224
|
+
}
|
|
225
|
+
if (found === null)
|
|
226
|
+
throw new ToolError(unknownFileIdText(id));
|
|
227
|
+
const summary = {
|
|
228
|
+
display: display(`读取 ${clip(found.name, 180)}`, `Read ${clip(found.name, 180)}`),
|
|
229
|
+
};
|
|
230
|
+
const imageLike = IMAGE_EXTENSION.test(found.name) || isRasterType(found.contentType);
|
|
231
|
+
if (found.size > MEDIA_LIMITS.imageBytes && imageLike) {
|
|
232
|
+
await found.discard();
|
|
233
|
+
return {
|
|
234
|
+
content: [{ type: "text", text: tooLargeText(found.name, found.size) }],
|
|
235
|
+
...summary,
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
let data;
|
|
239
|
+
try {
|
|
240
|
+
// never more than the cap (an image: its limit), plus one byte that tells a truncated read
|
|
241
|
+
data = await found.open({
|
|
242
|
+
maxBytes: (imageLike ? MEDIA_LIMITS.imageBytes : READ_MAX_BYTES) + 1,
|
|
243
|
+
});
|
|
244
|
+
}
|
|
245
|
+
catch (e) {
|
|
246
|
+
await found.discard();
|
|
247
|
+
throw e;
|
|
248
|
+
}
|
|
249
|
+
ctx.signal.throwIfAborted();
|
|
250
|
+
const out = await readContent(deps, ctx, input, {
|
|
251
|
+
name: found.name,
|
|
252
|
+
data: data.subarray(0, READ_MAX_BYTES),
|
|
253
|
+
size: Math.max(found.size, data.byteLength),
|
|
254
|
+
truncated: found.size > READ_MAX_BYTES || data.byteLength > READ_MAX_BYTES,
|
|
255
|
+
});
|
|
256
|
+
return {
|
|
257
|
+
...out,
|
|
258
|
+
content: [{ type: "text", text: out.text }],
|
|
259
|
+
...summary,
|
|
260
|
+
view: { kind: "read", path: viewPath(found.name), ...out.range },
|
|
261
|
+
};
|
|
262
|
+
}
|
|
263
|
+
/**
|
|
264
|
+
* The answer for read bytes (spec §1.2, in order): an image (too large, then shown or read by the
|
|
265
|
+
* vision purpose, then stored), a PDF, another binary file, or numbered text lines.
|
|
266
|
+
*/
|
|
267
|
+
async function readContent(deps, ctx, input, file) {
|
|
268
|
+
const { offset = 1, limit = DEFAULT_LIMIT } = input;
|
|
269
|
+
const image = deps.read === undefined ? null : sniffImage(file.data);
|
|
270
|
+
if (image !== null && deps.read !== undefined) {
|
|
271
|
+
return { ...(await readImage(deps.read, ctx, input, file, image)), range: {} };
|
|
272
|
+
}
|
|
273
|
+
if (looksBinary(file.data)) {
|
|
274
|
+
return { text: isPdf(file.data) ? pdfText(file.size) : binaryText(file.size), range: {} };
|
|
275
|
+
}
|
|
276
|
+
if (file.data.byteLength === 0)
|
|
277
|
+
return { text: "(empty file)", range: {} };
|
|
278
|
+
const decoded = new TextDecoder().decode(file.data);
|
|
279
|
+
let text = numberLines(decoded, offset, limit);
|
|
280
|
+
if (file.truncated) {
|
|
281
|
+
text += `\n[Only the first ${READ_MAX_BYTES} bytes of this ${file.size}-byte file were read; use Bash to read the rest.]`;
|
|
282
|
+
}
|
|
283
|
+
return {
|
|
284
|
+
text,
|
|
285
|
+
// display only: the line range shown on the row
|
|
286
|
+
range: { fromLine: offset, toLine: Math.min(fileLines(decoded).length, offset - 1 + limit) },
|
|
287
|
+
};
|
|
288
|
+
}
|
|
289
|
+
/**
|
|
290
|
+
* An image (spec §1.2): over the limit gives the too-large text; a chat model that cannot view
|
|
291
|
+
* images gets the `vision` purpose's answer first (its errors are the call's, nothing stored);
|
|
292
|
+
* then the copy is stored on the calling conversation (never the root), outside any transaction,
|
|
293
|
+
* and named in `media`. Past the per-conversation cap, or with no object store, nothing is stored
|
|
294
|
+
* and the result carries no `media`.
|
|
295
|
+
*/
|
|
296
|
+
async function readImage(read, ctx, input, file, image) {
|
|
297
|
+
if (file.truncated || file.data.byteLength > MEDIA_LIMITS.imageBytes) {
|
|
298
|
+
return { text: tooLargeText(file.name, file.size) };
|
|
299
|
+
}
|
|
300
|
+
const size = file.data.byteLength;
|
|
301
|
+
let answer = null;
|
|
302
|
+
if (!(await read.chatModelSeesImages(ctx))) {
|
|
303
|
+
const got = await readImageWithVisionModel(read.vision, ctx, {
|
|
304
|
+
name: file.name,
|
|
305
|
+
mediaType: image.mediaType,
|
|
306
|
+
data: file.data,
|
|
307
|
+
...(input.prompt !== undefined && { prompt: input.prompt }),
|
|
308
|
+
signal: ctx.signal,
|
|
309
|
+
});
|
|
310
|
+
answer = fallbackAnswerText(got.provider, got.model, got.text);
|
|
311
|
+
}
|
|
312
|
+
const withAnswer = (text) => (answer === null ? text : `${text}\n\n${answer}`);
|
|
313
|
+
// storeRead takes no signal: an aborted call stores nothing
|
|
314
|
+
ctx.signal.throwIfAborted();
|
|
315
|
+
let stored;
|
|
316
|
+
try {
|
|
317
|
+
stored = await read.reads.storeRead(ctx.orgId, ctx.conversationId, ctx.accountId || null, {
|
|
318
|
+
name: file.name,
|
|
319
|
+
contentType: image.mediaType,
|
|
320
|
+
data: file.data,
|
|
321
|
+
});
|
|
322
|
+
}
|
|
323
|
+
catch (e) {
|
|
324
|
+
if (!(e instanceof ApiError && e.code === "storage.unavailable"))
|
|
325
|
+
throw e;
|
|
326
|
+
stored = "storage";
|
|
327
|
+
}
|
|
328
|
+
if (stored === "storage" || !stored.ok) {
|
|
329
|
+
const reason = stored === "storage" ? "storage" : "cap";
|
|
330
|
+
return { text: withAnswer(notStoredText(file.name, image.mediaType, size, image, reason)) };
|
|
331
|
+
}
|
|
332
|
+
return {
|
|
333
|
+
text: withAnswer(readImageText(file.name, image.mediaType, stored.size, image, stored.attachmentId)),
|
|
334
|
+
media: [
|
|
335
|
+
{
|
|
336
|
+
attachmentId: stored.attachmentId,
|
|
337
|
+
name: file.name,
|
|
338
|
+
mediaType: image.mediaType,
|
|
339
|
+
size: stored.size,
|
|
340
|
+
},
|
|
341
|
+
],
|
|
342
|
+
};
|
|
343
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/** A byte count as a tool result shows it: `B` below 1 KB, else `KB` / `MB` with one decimal. */
|
|
2
|
+
export function sizeText(bytes) {
|
|
3
|
+
if (bytes < 1024)
|
|
4
|
+
return `${bytes} B`;
|
|
5
|
+
if (bytes < 1_048_576)
|
|
6
|
+
return `${(bytes / 1024).toFixed(1)} KB`;
|
|
7
|
+
return `${(bytes / 1_048_576).toFixed(1)} MB`;
|
|
8
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { type Logger } from "@capybara-hq/plugin-sdk";
|
|
2
|
+
import type { EventLog } from "../../../conversations/event-log.js";
|
|
3
|
+
import type { KernelConfigService } from "../../../infra/config/kernel-config.service.js";
|
|
4
|
+
import { type ModelPurposesService } from "../../../models/purposes.js";
|
|
5
|
+
import { type HookRunner } from "../../../runtime/hook-calls.js";
|
|
6
|
+
import type { StepLog } from "../../../runtime/step-log.js";
|
|
7
|
+
import type { BuiltinCallContext } from "../../registry.js";
|
|
8
|
+
/**
|
|
9
|
+
* The vision read (vision read spec §2.3): an image read for a model that cannot view images goes
|
|
10
|
+
* to the org's `vision` purpose model, and only its answer comes back. It follows the `WebFetch`
|
|
11
|
+
* extraction call (`web/extract.ts`) step by step: one call, no tools, a fixed system prompt, one
|
|
12
|
+
* user message (the prompt text and one image block with the in-memory bytes), output capped at
|
|
13
|
+
* `min(models.visionMaxOutputTokens, the target's limit)`, aborted after `models.visionTimeoutMs`
|
|
14
|
+
* or with the caller's signal. It fires `model.request` (`purpose: "vision"`; a policy denial is
|
|
15
|
+
* recorded like any hook denial and becomes the tool error {@link VISION_DENIED_TEXT}) and
|
|
16
|
+
* `model.response`; its tokens are a `usage` event with `purpose: "vision"` and the call id,
|
|
17
|
+
* reported in the same transaction and counted on the parent run of a sub-agent. A sent call that
|
|
18
|
+
* fails logs its estimated usage. The purpose has no fallback: unmapped, or mapped to a model the
|
|
19
|
+
* org cannot use or that cannot view images, is the tool error {@link NO_VISION_MODEL_TEXT}.
|
|
20
|
+
*/
|
|
21
|
+
/** The system prompt of the vision call (model-facing, English; a core constant). */
|
|
22
|
+
export declare const VISION_SYSTEM_PROMPT: string;
|
|
23
|
+
/** The prompt of the call when the caller gives none. */
|
|
24
|
+
export declare const VISION_DEFAULT_PROMPT = "Describe the image, including any text in it.";
|
|
25
|
+
/** The tool error when the org has no usable vision model (spec §1.2; verbatim). */
|
|
26
|
+
export declare const NO_VISION_MODEL_TEXT: string;
|
|
27
|
+
/** The tool error when the vision call fails. */
|
|
28
|
+
export declare const VISION_READ_FAILED_TEXT = "The vision model could not read the image.";
|
|
29
|
+
/** The tool error when a `model.request` policy hook denies the vision call. */
|
|
30
|
+
export declare const VISION_DENIED_TEXT = "An org policy hook denied the call that would read this image with the vision model.";
|
|
31
|
+
/** What {@link readImageWithVisionModel} needs (the shapes `web/extract.ts` takes). */
|
|
32
|
+
export interface VisionReadDeps {
|
|
33
|
+
purposes: Pick<ModelPurposesService, "chat">;
|
|
34
|
+
eventLog: Pick<EventLog, "notify" | "latestOfType">;
|
|
35
|
+
stepLog: Pick<StepLog, "appendCounted" | "appendReported" | "appendAudited">;
|
|
36
|
+
config: Pick<KernelConfigService, "get">;
|
|
37
|
+
log: Pick<Logger, "warn">;
|
|
38
|
+
/** Extension hooks (absent: none fire). */
|
|
39
|
+
hooks?: HookRunner | undefined;
|
|
40
|
+
}
|
|
41
|
+
/** The image to read and the caller's request about it. */
|
|
42
|
+
export interface VisionReadImage {
|
|
43
|
+
name: string;
|
|
44
|
+
mediaType: string;
|
|
45
|
+
data: Uint8Array;
|
|
46
|
+
/** The question about the image (absent or blank: {@link VISION_DEFAULT_PROMPT}). */
|
|
47
|
+
prompt?: string;
|
|
48
|
+
signal: AbortSignal;
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Reads `img` with one call on the `vision` purpose (see the module comment). Returns the answer
|
|
52
|
+
* and the model that gave it; throws a {@link ToolError} when no vision model is usable, on a
|
|
53
|
+
* denial or on a failure.
|
|
54
|
+
*/
|
|
55
|
+
export declare function readImageWithVisionModel(deps: VisionReadDeps, ctx: BuiltinCallContext, img: VisionReadImage): Promise<{
|
|
56
|
+
text: string;
|
|
57
|
+
provider: string;
|
|
58
|
+
model: string;
|
|
59
|
+
}>;
|