@capybara-hq/kernel 0.1.0-rc.90 → 0.1.0-rc.91
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.js +3 -3
- package/dist/conversations/attachments.service.d.ts +3 -0
- package/dist/conversations/attachments.service.js +4 -1
- package/dist/conversations/events.js +6 -4
- package/dist/conversations/model-image.d.ts +6 -0
- package/dist/conversations/model-image.js +10 -1
- package/dist/runtime/context/build.d.ts +15 -8
- package/dist/runtime/context/build.js +20 -14
- package/dist/tools/approvals.service.d.ts +3 -1
- package/dist/tools/builtins/conversation-files.d.ts +11 -5
- package/dist/tools/builtins/conversation-files.js +62 -5
- package/dist/tools/builtins/image/generate.js +1 -1
- package/dist/tools/builtins/sandbox/deliver.d.ts +2 -0
- package/dist/tools/builtins/sandbox/deliver.js +100 -34
- package/dist/tools/builtins/sandbox/read.js +7 -0
- package/dist/tools/outputs.d.ts +6 -4
- package/dist/tools/outputs.js +11 -12
- package/dist/tools/pipeline.d.ts +92 -3
- package/dist/tools/pipeline.js +40 -5
- package/dist/tools/result-images.d.ts +91 -0
- package/dist/tools/result-images.js +195 -0
- package/package.json +2 -2
package/bootstrap.json
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"schemaVersion": 1,
|
|
4
4
|
"marketplace": {
|
|
5
5
|
"url": "https://github.com/capybara-hq/plugins.git",
|
|
6
|
-
"commit": "
|
|
6
|
+
"commit": "44fa9a1384c92d8016c54dae17d36fb9d464c9e5"
|
|
7
7
|
},
|
|
8
8
|
"plugins": [
|
|
9
9
|
{
|
|
@@ -90,16 +90,16 @@
|
|
|
90
90
|
"name": "device-docker",
|
|
91
91
|
"source": "npm",
|
|
92
92
|
"npm": "@capybara-hq/plugin-device-docker",
|
|
93
|
-
"version": "0.1.0-rc.
|
|
94
|
-
"integrity": "sha512-
|
|
93
|
+
"version": "0.1.0-rc.30",
|
|
94
|
+
"integrity": "sha512-bhqSRr6r9gNI7aKYE0ANf3xeCYYIKCOFlvOZZLyM83AzaTn4A2K7zgbgZQZAGgs9b5M3cZhlemjVTAChBPZGuw==",
|
|
95
95
|
"required": false
|
|
96
96
|
},
|
|
97
97
|
{
|
|
98
98
|
"name": "device-local",
|
|
99
99
|
"source": "npm",
|
|
100
100
|
"npm": "@capybara-hq/plugin-device-local",
|
|
101
|
-
"version": "0.1.0-rc.
|
|
102
|
-
"integrity": "sha512-
|
|
101
|
+
"version": "0.1.0-rc.11",
|
|
102
|
+
"integrity": "sha512-ZxWxrGjPjNpJtwH/2oK58itxfPFRi5CQQFbMe8VPyfYaEdfyPT8ZlOjgocdz/F8hR9jeu+E2VPgOmh7uMeBo/w==",
|
|
103
103
|
"required": false,
|
|
104
104
|
"scope": "all"
|
|
105
105
|
},
|
|
@@ -208,7 +208,7 @@ export declare function headsToResolve(entries: readonly MarketplaceEntry[], imp
|
|
|
208
208
|
/** The host versions (an entry's `minKernel` is judged against them). */
|
|
209
209
|
export declare const HOST_VERSIONS: {
|
|
210
210
|
readonly kernel: string;
|
|
211
|
-
readonly sdk: "0.1.0-rc.
|
|
211
|
+
readonly sdk: "0.1.0-rc.73";
|
|
212
212
|
};
|
|
213
213
|
/** Whether this deployment satisfies the entry's `minKernel`. */
|
|
214
214
|
export declare const entryCompatible: (e: Pick<MarketplaceEntry, "minKernel">) => boolean;
|
package/dist/config/schema.js
CHANGED
|
@@ -1230,7 +1230,7 @@ export const KernelConfigSchema = z.strictObject({
|
|
|
1230
1230
|
.default(6)
|
|
1231
1231
|
.meta(meta({
|
|
1232
1232
|
hot: true,
|
|
1233
|
-
description: "Most images Read
|
|
1233
|
+
description: "Most stored tool-result images (Read images and images other tools returned) shown to the model in one request; older ones are replaced with a placeholder",
|
|
1234
1234
|
})),
|
|
1235
1235
|
readMaxBytesPerConversation: z
|
|
1236
1236
|
.number()
|
|
@@ -1240,7 +1240,7 @@ export const KernelConfigSchema = z.strictObject({
|
|
|
1240
1240
|
.default(536_870_912)
|
|
1241
1241
|
.meta(meta({
|
|
1242
1242
|
hot: true,
|
|
1243
|
-
description: "Most bytes of
|
|
1243
|
+
description: "Most bytes of stored tool-result image copies (Read images and images other tools returned) for one conversation; past it an image is not stored and does not stay in the history; 0 stores none",
|
|
1244
1244
|
})),
|
|
1245
1245
|
readPurgeAfterHours: z
|
|
1246
1246
|
.number()
|
|
@@ -1250,7 +1250,7 @@ export const KernelConfigSchema = z.strictObject({
|
|
|
1250
1250
|
.default(24)
|
|
1251
1251
|
.meta(meta({
|
|
1252
1252
|
hot: true,
|
|
1253
|
-
description: "Hours after a conversation is deleted before its
|
|
1253
|
+
description: "Hours after a conversation is deleted before its stored tool-result image copies are purged (row and object)",
|
|
1254
1254
|
})),
|
|
1255
1255
|
})
|
|
1256
1256
|
// 单个附件不能大于单次请求的预算:否则它永远被省略(最新的附件总能放进请求)
|
|
@@ -210,6 +210,9 @@ export declare class AttachmentsService {
|
|
|
210
210
|
* 下载地址(预签名,{@link ATTACHMENT_DOWNLOAD_TTL_SECONDS} 秒):已绑定的附件要求能访问其会话,
|
|
211
211
|
* 未绑定的只有上传者;否则 `attachment.not_found`。只有图片与 PDF 以 `inline` 打开,其余一律 `attachment`
|
|
212
212
|
* (即使存储里的类型被改成 text/html 也不会在页面里渲染);响应类型按 finalize 核对过的类型返回。
|
|
213
|
+
* A `read` copy (an image a tool showed the agent) is served the same way to whoever can open its
|
|
214
|
+
* conversation, so the web can show it on the call's row (tool result images design §4); it is
|
|
215
|
+
* still never listed (lists and the device's attachments stay `chat` only).
|
|
213
216
|
*/
|
|
214
217
|
downloadUrl(orgId: string, accountId: string, id: string): Promise<string>;
|
|
215
218
|
/**
|
|
@@ -423,6 +423,9 @@ let AttachmentsService = class AttachmentsService {
|
|
|
423
423
|
* 下载地址(预签名,{@link ATTACHMENT_DOWNLOAD_TTL_SECONDS} 秒):已绑定的附件要求能访问其会话,
|
|
424
424
|
* 未绑定的只有上传者;否则 `attachment.not_found`。只有图片与 PDF 以 `inline` 打开,其余一律 `attachment`
|
|
425
425
|
* (即使存储里的类型被改成 text/html 也不会在页面里渲染);响应类型按 finalize 核对过的类型返回。
|
|
426
|
+
* A `read` copy (an image a tool showed the agent) is served the same way to whoever can open its
|
|
427
|
+
* conversation, so the web can show it on the call's row (tool result images design §4); it is
|
|
428
|
+
* still never listed (lists and the device's attachments stay `chat` only).
|
|
426
429
|
*/
|
|
427
430
|
async downloadUrl(orgId, accountId, id) {
|
|
428
431
|
this.storage.assertAvailable();
|
|
@@ -440,7 +443,7 @@ let AttachmentsService = class AttachmentsService {
|
|
|
440
443
|
.where("id", "=", id)
|
|
441
444
|
.where("org_id", "=", orgId)
|
|
442
445
|
.where("status", "=", "ready")
|
|
443
|
-
.where("purpose", "
|
|
446
|
+
.where("purpose", "in", ["chat", "read"])
|
|
444
447
|
.executeTakeFirst();
|
|
445
448
|
if (!row)
|
|
446
449
|
throw notFound();
|
|
@@ -1297,10 +1297,12 @@ export const ConversationEventSchema = z.discriminatedUnion("type", [
|
|
|
1297
1297
|
})
|
|
1298
1298
|
.optional(),
|
|
1299
1299
|
/**
|
|
1300
|
-
* The images
|
|
1301
|
-
*
|
|
1302
|
-
*
|
|
1303
|
-
*
|
|
1300
|
+
* The images stored for the call: the builtin Read's copy (vision-read design §1.2) and the
|
|
1301
|
+
* image blocks of any tool's result, which the pipeline stores itself (tool result images
|
|
1302
|
+
* design §2); `read` attachments bound to this conversation, one per image. A tool never
|
|
1303
|
+
* names an attachment here. Model-visible: request building renders each after the step's
|
|
1304
|
+
* tool results (`Image from <toolKey> (file_id <id>):` and the image, or the no-vision
|
|
1305
|
+
* text), inside the Read-image window. The web shows them on the call's row.
|
|
1304
1306
|
*/
|
|
1305
1307
|
media: z
|
|
1306
1308
|
.array(z.object({
|
|
@@ -7,6 +7,12 @@ import type { MediaBytes } from "../runtime/context/build.js";
|
|
|
7
7
|
export declare const MODEL_IMAGE_MAX_EDGE = 2048;
|
|
8
8
|
/** An image at most this large and within {@link MODEL_IMAGE_MAX_EDGE} is sent unchanged. */
|
|
9
9
|
export declare const MODEL_IMAGE_KEEP_BYTES = 1048576;
|
|
10
|
+
/**
|
|
11
|
+
* The most pixels {@link fitImageForModel} decodes; a larger image is sent unchanged (and a
|
|
12
|
+
* provider that rejects it is handled by `media_excluded`). Above the tool-result and thumbnail
|
|
13
|
+
* bound (40 megapixels) so a large camera photo a person uploads is still scaled.
|
|
14
|
+
*/
|
|
15
|
+
export declare const MODEL_IMAGE_MAX_INPUT_PIXELS = 100000000;
|
|
10
16
|
/**
|
|
11
17
|
* The copy of an image a model request carries. Images over {@link MODEL_IMAGE_KEEP_BYTES} or
|
|
12
18
|
* larger than {@link MODEL_IMAGE_MAX_EDGE} on an edge are scaled to fit that edge (never enlarged)
|
|
@@ -7,6 +7,12 @@ import sharp from "sharp";
|
|
|
7
7
|
export const MODEL_IMAGE_MAX_EDGE = 2048;
|
|
8
8
|
/** An image at most this large and within {@link MODEL_IMAGE_MAX_EDGE} is sent unchanged. */
|
|
9
9
|
export const MODEL_IMAGE_KEEP_BYTES = 1_048_576;
|
|
10
|
+
/**
|
|
11
|
+
* The most pixels {@link fitImageForModel} decodes; a larger image is sent unchanged (and a
|
|
12
|
+
* provider that rejects it is handled by `media_excluded`). Above the tool-result and thumbnail
|
|
13
|
+
* bound (40 megapixels) so a large camera photo a person uploads is still scaled.
|
|
14
|
+
*/
|
|
15
|
+
export const MODEL_IMAGE_MAX_INPUT_PIXELS = 100_000_000;
|
|
10
16
|
/** Quality of the re-encoded copy (JPEG, or WebP for an image with transparent pixels). */
|
|
11
17
|
const QUALITY = 85;
|
|
12
18
|
/** Types {@link fitImageForModel} re-encodes; others (GIF, which may be animated) pass through. */
|
|
@@ -23,7 +29,10 @@ export async function fitImageForModel(media) {
|
|
|
23
29
|
if (!RESIZABLE.has(media.mediaType))
|
|
24
30
|
return media;
|
|
25
31
|
try {
|
|
26
|
-
const image = sharp(media.data, {
|
|
32
|
+
const image = sharp(media.data, {
|
|
33
|
+
failOn: "error",
|
|
34
|
+
limitInputPixels: MODEL_IMAGE_MAX_INPUT_PIXELS,
|
|
35
|
+
});
|
|
27
36
|
const meta = await image.metadata();
|
|
28
37
|
if (media.data.byteLength <= MODEL_IMAGE_KEEP_BYTES &&
|
|
29
38
|
Math.max(meta.width, meta.height) <= MODEL_IMAGE_MAX_EDGE) {
|
|
@@ -164,7 +164,10 @@ export declare const PDF_BYTES_PER_PAGE_ESTIMATE: number;
|
|
|
164
164
|
export declare function pdfTokens(size: number, pages: number | null): number;
|
|
165
165
|
/** 日志里(按 zod 推导的形状)的内容块。 */
|
|
166
166
|
type LogBlock = EventPayload<"user_message">["content"][number];
|
|
167
|
-
/**
|
|
167
|
+
/**
|
|
168
|
+
* One stored image of a tool result (`tool_result.media`): the builtin Read's copy (vision-read
|
|
169
|
+
* design §1.2) or an image block of any tool's result (tool result images design §2).
|
|
170
|
+
*/
|
|
168
171
|
export type ReadMedia = NonNullable<EventPayload<"tool_result">["media"]>[number];
|
|
169
172
|
/**
|
|
170
173
|
* The Read-image window with chunked eviction (vision-read design §1.4): walks the images from Read
|
|
@@ -245,15 +248,19 @@ export declare const mediaTooManyImagesText: (name: string) => string;
|
|
|
245
248
|
export declare const mediaTooManyPagesText: (name: string) => string;
|
|
246
249
|
/** An attachment the provider rejected, never sent again (model-facing, English). */
|
|
247
250
|
export declare const mediaRejectedText: (name: string) => string;
|
|
248
|
-
/** The label before an image from Read (model-facing, vision-read design §1.4). */
|
|
249
|
-
export declare const readImageLabelText: (id: string) => string;
|
|
250
251
|
/**
|
|
251
|
-
*
|
|
252
|
-
*
|
|
252
|
+
* The label before an image of a tool result (model-facing; vision-read design §1.4, tool result
|
|
253
|
+
* images design §3): the tool's key, e.g. `Image from Read (file_id <id>):`.
|
|
254
|
+
*/
|
|
255
|
+
export declare const readImageLabelText: (toolKey: string, id: string) => string;
|
|
256
|
+
/**
|
|
257
|
+
* An image of a tool result for a model without vision (static, so history stays append-only):
|
|
258
|
+
* it says the image was not shown. After `Read`, whose result already carries any vision model's
|
|
259
|
+
* answer, nothing more; after another tool, how the image can still be read.
|
|
253
260
|
*/
|
|
254
|
-
export declare const
|
|
255
|
-
/** An image
|
|
256
|
-
export declare const readImageNotIncludedText: (id: string) => string;
|
|
261
|
+
export declare const readImageNoVisionText: (toolKey: string, id: string) => string;
|
|
262
|
+
/** An image of a tool result the Read-image window left out of this request. */
|
|
263
|
+
export declare const readImageNotIncludedText: (toolKey: string, id: string) => string;
|
|
257
264
|
/**
|
|
258
265
|
* A reference line (model-facing English, one text block, §5.2): the file's name and media type, its
|
|
259
266
|
* size, the unsigned object URI, and how to get the bytes — `FetchAttachment` copies the file into the
|
|
@@ -294,15 +294,21 @@ export const mediaTooManyImagesText = (name) => `[Attachment ${quoted(name)} omi
|
|
|
294
294
|
export const mediaTooManyPagesText = (name) => `[Attachment ${quoted(name)} has too many pages for this model.]`;
|
|
295
295
|
/** An attachment the provider rejected, never sent again (model-facing, English). */
|
|
296
296
|
export const mediaRejectedText = (name) => `[Attachment ${quoted(name)} was rejected by the model provider.]`;
|
|
297
|
-
/** The label before an image from Read (model-facing, vision-read design §1.4). */
|
|
298
|
-
export const readImageLabelText = (id) => `Image from Read (file_id ${id}):`;
|
|
299
297
|
/**
|
|
300
|
-
*
|
|
301
|
-
*
|
|
298
|
+
* The label before an image of a tool result (model-facing; vision-read design §1.4, tool result
|
|
299
|
+
* images design §3): the tool's key, e.g. `Image from Read (file_id <id>):`.
|
|
302
300
|
*/
|
|
303
|
-
export const
|
|
304
|
-
/**
|
|
305
|
-
|
|
301
|
+
export const readImageLabelText = (toolKey, id) => `Image from ${toolKey} (file_id ${id}):`;
|
|
302
|
+
/**
|
|
303
|
+
* An image of a tool result for a model without vision (static, so history stays append-only):
|
|
304
|
+
* it says the image was not shown. After `Read`, whose result already carries any vision model's
|
|
305
|
+
* answer, nothing more; after another tool, how the image can still be read.
|
|
306
|
+
*/
|
|
307
|
+
export const readImageNoVisionText = (toolKey, id) => toolKey === "Read"
|
|
308
|
+
? "[Not shown to you: this model cannot view images.]"
|
|
309
|
+
: `[Not shown to you: this model cannot view images. If Read is available to you, Read with file_id ${id} sends it to the organization's vision model, if one is set.]`;
|
|
310
|
+
/** An image of a tool result the Read-image window left out of this request. */
|
|
311
|
+
export const readImageNotIncludedText = (toolKey, id) => `[Image from ${toolKey} (file_id ${id}) not included in this request.]`;
|
|
306
312
|
/**
|
|
307
313
|
* The usual file extension per content type: the label of a `file` block logged without a name (every
|
|
308
314
|
* accepted type, so the reference line always names something a person could recognise).
|
|
@@ -343,7 +349,7 @@ export const attachmentReferenceText = (input) => {
|
|
|
343
349
|
};
|
|
344
350
|
function placeholder(b, name) {
|
|
345
351
|
if (b.type === "image") {
|
|
346
|
-
return `[Attached image ${quoted(name)} — this model cannot view images. Read with file_id ${b.source.attachmentId} sends it to the organization's vision model, if one is set.]`;
|
|
352
|
+
return `[Attached image ${quoted(name)} — this model cannot view images. If Read is available to you, Read with file_id ${b.source.attachmentId} sends it to the organization's vision model, if one is set.]`;
|
|
347
353
|
}
|
|
348
354
|
return `[Attached document ${quoted(name)} — this model cannot read ${b.mediaType === "application/pdf" ? "PDF documents" : "documents"}.]`;
|
|
349
355
|
}
|
|
@@ -762,7 +768,7 @@ export function buildModelRequest(input) {
|
|
|
762
768
|
* label: the image (through {@link resolveMedia}, so the cap, the budget and `media_excluded`
|
|
763
769
|
* apply), the static text for a model without vision, or the window's "not included" text.
|
|
764
770
|
*/
|
|
765
|
-
const readBlocks = (media) => media.flatMap((m) => {
|
|
771
|
+
const readBlocks = (toolKey, media) => media.flatMap((m) => {
|
|
766
772
|
const id = m.attachmentId;
|
|
767
773
|
const note = (text, outcome) => {
|
|
768
774
|
if (!mediaOutcomes.has(id))
|
|
@@ -771,14 +777,14 @@ export function buildModelRequest(input) {
|
|
|
771
777
|
};
|
|
772
778
|
if (!model.capabilities.vision) {
|
|
773
779
|
return [
|
|
774
|
-
{ type: "text", text: readImageLabelText(id) },
|
|
775
|
-
...note(
|
|
780
|
+
{ type: "text", text: readImageLabelText(toolKey, id) },
|
|
781
|
+
...note(readImageNoVisionText(toolKey, id), "placeholder_unsupported"),
|
|
776
782
|
];
|
|
777
783
|
}
|
|
778
784
|
if (mediaCtx.plan.notIncluded.has(id)) {
|
|
779
|
-
return note(readImageNotIncludedText(id), "not_included");
|
|
785
|
+
return note(readImageNotIncludedText(toolKey, id), "not_included");
|
|
780
786
|
}
|
|
781
|
-
return [{ type: "text", text: readImageLabelText(id) }, ...blocksOf([readBlock(m)])];
|
|
787
|
+
return [{ type: "text", text: readImageLabelText(toolKey, id) }, ...blocksOf([readBlock(m)])];
|
|
782
788
|
});
|
|
783
789
|
/** Whether the request renders an image from Read (the window is then recorded). */
|
|
784
790
|
let hasReadImages = false;
|
|
@@ -891,7 +897,7 @@ export function buildModelRequest(input) {
|
|
|
891
897
|
});
|
|
892
898
|
if (r.media !== undefined && r.media.length > 0) {
|
|
893
899
|
hasReadImages = true;
|
|
894
|
-
images.push(...readBlocks(r.media));
|
|
900
|
+
images.push(...readBlocks(r.toolKey, r.media));
|
|
895
901
|
}
|
|
896
902
|
}
|
|
897
903
|
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { type LocalizedName, type ToolDisplay } from "@capybara-hq/plugin-sdk";
|
|
2
2
|
import { EventLog } from "../conversations/event-log.js";
|
|
3
|
-
import { type ReviewRecord, type ToolView } from "../conversations/events.js";
|
|
3
|
+
import { type EventPayload, type ReviewRecord, type ToolView } from "../conversations/events.js";
|
|
4
4
|
import { ConversationLeakCheck } from "../conversations/leak-check.js";
|
|
5
5
|
import { DevicesService } from "../devices/devices.service.js";
|
|
6
6
|
import { type PersonRef } from "../identity/account-avatar.js";
|
|
@@ -43,6 +43,8 @@ export interface KeptToolResult {
|
|
|
43
43
|
contentTypes?: string[];
|
|
44
44
|
display?: ToolDisplay;
|
|
45
45
|
view?: ToolView;
|
|
46
|
+
/** The stored images of the result (`tool_result.media`), written with it when the ask settles. */
|
|
47
|
+
media?: NonNullable<EventPayload<"tool_result">["media"]>;
|
|
46
48
|
/** The command review's decision, kept with the result (display only). */
|
|
47
49
|
review?: ReviewRecord;
|
|
48
50
|
/**
|
|
@@ -5,6 +5,11 @@ import type { StorageService } from "../../storage/storage.service.js";
|
|
|
5
5
|
export interface ConversationFile {
|
|
6
6
|
kind: "attachment" | "artifact";
|
|
7
7
|
id: string;
|
|
8
|
+
/**
|
|
9
|
+
* For a `read` copy (an image a tool showed the agent), the conversation it is bound to: a
|
|
10
|
+
* `Read` of a copy that is already the calling conversation's needs no new copy.
|
|
11
|
+
*/
|
|
12
|
+
readCopyOf?: string;
|
|
8
13
|
name: string;
|
|
9
14
|
contentType: string;
|
|
10
15
|
size: number;
|
|
@@ -25,11 +30,12 @@ export interface ConversationFileDeps {
|
|
|
25
30
|
storage: Pick<StorageService, "kernel">;
|
|
26
31
|
}
|
|
27
32
|
/**
|
|
28
|
-
* A file of the conversation by id, always inside `orgId`: an attachment
|
|
29
|
-
*
|
|
30
|
-
*
|
|
31
|
-
*
|
|
32
|
-
*
|
|
33
|
+
* A file of the conversation by id, always inside `orgId`: an attachment (a `chat` attachment or
|
|
34
|
+
* a `read` copy: this lookup is the model's, vision-read design §1.1) or an `artifact_created`
|
|
35
|
+
* event of the conversation, of its root, or of a sub-agent conversation below the conversation
|
|
36
|
+
* (so a parent reaches an image its sub-agent's tool returned; tool result images design §5).
|
|
37
|
+
* Anything else (a sibling's or another tree's, another org's, a missing object, an id that is
|
|
38
|
+
* not a UUID) is `null`. Storage errors are thrown as they are. `signal` aborts the storage reads.
|
|
33
39
|
*/
|
|
34
40
|
export declare function findConversationFile(deps: ConversationFileDeps, q: {
|
|
35
41
|
orgId: string;
|
|
@@ -34,18 +34,74 @@ async function bytesOf(body, maxBytes) {
|
|
|
34
34
|
}
|
|
35
35
|
return out;
|
|
36
36
|
}
|
|
37
|
+
/** How many parent links {@link isBelow} follows at most (the tree reads' bound). */
|
|
38
|
+
const TREE_MAX_LEVELS = 16;
|
|
37
39
|
/**
|
|
38
|
-
*
|
|
39
|
-
*
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
40
|
+
* Whether `candidate` is a sub-agent conversation below `ancestor` (its child, grandchild …),
|
|
41
|
+
* walking `parent_conversation_id` inside `orgId`, at most {@link TREE_MAX_LEVELS} links.
|
|
42
|
+
*/
|
|
43
|
+
async function isBelow(db, orgId, candidate, ancestor) {
|
|
44
|
+
let at = candidate;
|
|
45
|
+
for (let i = 0; i < TREE_MAX_LEVELS && at !== null; i++) {
|
|
46
|
+
const row = await db
|
|
47
|
+
.selectFrom("conversations")
|
|
48
|
+
.select("parent_conversation_id")
|
|
49
|
+
.where("id", "=", at)
|
|
50
|
+
.where("org_id", "=", orgId)
|
|
51
|
+
.executeTakeFirst();
|
|
52
|
+
at = row?.parent_conversation_id ?? null;
|
|
53
|
+
if (at === ancestor)
|
|
54
|
+
return true;
|
|
55
|
+
}
|
|
56
|
+
return false;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* The conversation an attachment (`chat` or `read`, ready) or artifact with this id belongs to,
|
|
60
|
+
* in `orgId`; null when there is none.
|
|
61
|
+
*/
|
|
62
|
+
async function ownerOf(db, orgId, id) {
|
|
63
|
+
const att = await db
|
|
64
|
+
.selectFrom("attachments")
|
|
65
|
+
.select(["conversation_id", "purpose"])
|
|
66
|
+
.where("id", "=", id)
|
|
67
|
+
.where("org_id", "=", orgId)
|
|
68
|
+
.where("status", "=", "ready")
|
|
69
|
+
.where("purpose", "in", ["chat", "read"])
|
|
70
|
+
.executeTakeFirst();
|
|
71
|
+
if (att?.conversation_id)
|
|
72
|
+
return { conversationId: att.conversation_id, purpose: att.purpose };
|
|
73
|
+
const ev = await db
|
|
74
|
+
.selectFrom("conversation_events as e")
|
|
75
|
+
.innerJoin("conversations as c", "c.id", "e.conversation_id")
|
|
76
|
+
.select("e.conversation_id")
|
|
77
|
+
.where("c.org_id", "=", orgId)
|
|
78
|
+
.where("e.type", "=", "artifact_created")
|
|
79
|
+
.where(sql `e.payload->>'artifactId'`, "=", id)
|
|
80
|
+
.limit(1)
|
|
81
|
+
.executeTakeFirst();
|
|
82
|
+
return ev ? { conversationId: ev.conversation_id, purpose: "artifact" } : null;
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* A file of the conversation by id, always inside `orgId`: an attachment (a `chat` attachment or
|
|
86
|
+
* a `read` copy: this lookup is the model's, vision-read design §1.1) or an `artifact_created`
|
|
87
|
+
* event of the conversation, of its root, or of a sub-agent conversation below the conversation
|
|
88
|
+
* (so a parent reaches an image its sub-agent's tool returned; tool result images design §5).
|
|
89
|
+
* Anything else (a sibling's or another tree's, another org's, a missing object, an id that is
|
|
90
|
+
* not a UUID) is `null`. Storage errors are thrown as they are. `signal` aborts the storage reads.
|
|
43
91
|
*/
|
|
44
92
|
export async function findConversationFile(deps, q) {
|
|
45
93
|
if (!UUID.test(q.id))
|
|
46
94
|
return null;
|
|
47
95
|
const id = q.id.toLowerCase();
|
|
48
96
|
const conversations = [...new Set([q.conversationId, q.rootConversationId])];
|
|
97
|
+
// a file of a sub-agent below the calling conversation joins the lookup
|
|
98
|
+
const found = await ownerOf(deps.db, q.orgId, id);
|
|
99
|
+
const owner = found?.conversationId;
|
|
100
|
+
if (owner !== undefined &&
|
|
101
|
+
!conversations.includes(owner) &&
|
|
102
|
+
(await isBelow(deps.db, q.orgId, owner, q.conversationId))) {
|
|
103
|
+
conversations.push(owner);
|
|
104
|
+
}
|
|
49
105
|
for (const conversationId of conversations) {
|
|
50
106
|
const opened = await deps.attachments.openForConversation(q.orgId, conversationId, id, {
|
|
51
107
|
purposes: ["chat", "read"],
|
|
@@ -57,6 +113,7 @@ export async function findConversationFile(deps, q) {
|
|
|
57
113
|
return {
|
|
58
114
|
kind: "attachment",
|
|
59
115
|
id,
|
|
116
|
+
...(found?.purpose === "read" && owner === conversationId && { readCopyOf: conversationId }),
|
|
60
117
|
name: opened.name,
|
|
61
118
|
contentType: opened.contentType,
|
|
62
119
|
size: opened.size,
|
|
@@ -585,7 +585,7 @@ function resultText(prepared, stored, files, revisedPrompt, deviceLine) {
|
|
|
585
585
|
}
|
|
586
586
|
const first = stored[0];
|
|
587
587
|
if (first !== undefined) {
|
|
588
|
-
lines.push(`The images are not shown to you; Read with file_id ${first.repeatOf?.artifactId ?? first.artifactId} returns one.`);
|
|
588
|
+
lines.push(`The images are not shown to you; if Read is available to you, Read with file_id ${first.repeatOf?.artifactId ?? first.artifactId} returns one.`);
|
|
589
589
|
}
|
|
590
590
|
if (deviceLine !== null)
|
|
591
591
|
lines.push(deviceLine);
|
|
@@ -2,5 +2,7 @@ import type { BuiltinTool } from "../../registry.js";
|
|
|
2
2
|
import { type SandboxToolDeps } from "./common.js";
|
|
3
3
|
/** The content type of a file name by its extension (Deliver, skill files); unknown: octet-stream. */
|
|
4
4
|
export declare function contentTypeFor(name: string): string;
|
|
5
|
+
/** Neither or both of `file_path` and `file_id`. */
|
|
6
|
+
export declare const DELIVER_ONE_SOURCE_TEXT = "Pass exactly one of file_path (a path on the device) and file_id (an attachment or artifact id).";
|
|
5
7
|
/** 内置工具 `Deliver`:把沙箱里的文件存进对象存储,写 `artifact_created`,用户可下载。 */
|
|
6
8
|
export declare function sandboxDeliverTool(deps: SandboxToolDeps): BuiltinTool;
|
|
@@ -1,34 +1,42 @@
|
|
|
1
|
-
import { MEDIA_NAME_MAX_CHARS, ToolError } from "@capybara-hq/plugin-sdk";
|
|
1
|
+
import { MEDIA_NAME_MAX_CHARS, ToolError, } from "@capybara-hq/plugin-sdk";
|
|
2
2
|
import { isValidArtifactName } from "../../../conversations/events.js";
|
|
3
|
+
import { ApiError } from "../../../errors.js";
|
|
3
4
|
import { NO_STORAGE, NO_STORAGE_REASON, REPEAT_TEXT, storeArtifacts, } from "../artifacts.js";
|
|
4
|
-
import {
|
|
5
|
+
import { findConversationFile } from "../conversation-files.js";
|
|
6
|
+
import { checkPathShape, checkToolPath, clip, display, inToolSandbox, sandboxBaseTimeoutMs, sandboxConversationOf, unavailableWhenNoSandbox, withNotices, } from "./common.js";
|
|
5
7
|
const SPEC = {
|
|
6
8
|
name: "Deliver",
|
|
7
9
|
// Display only (the tool row; not in the fingerprint, never sent to the model).
|
|
8
|
-
keyArgs: ["file_path"],
|
|
9
|
-
description: "Deliver a file
|
|
10
|
-
"
|
|
11
|
-
"
|
|
12
|
-
"
|
|
13
|
-
"
|
|
14
|
-
"
|
|
15
|
-
"
|
|
10
|
+
keyArgs: ["file_path", "file_id"],
|
|
11
|
+
description: "Deliver a file to the user as a downloadable artifact. Use it when the user should receive a " +
|
|
12
|
+
"file you produced (a report, chart, spreadsheet, archive and so on); files that stay on the " +
|
|
13
|
+
"device are not visible to the user, and images in tool results are shown to you, not " +
|
|
14
|
+
"delivered to the user. Pass file_path for a file on the device, or file_id for an attachment " +
|
|
15
|
+
"or artifact of this conversation, such as the file_id an image in a tool result names (needs " +
|
|
16
|
+
"no device). Each call delivers only that one file, so a directory must first be packed into " +
|
|
17
|
+
"one archive. The file size is limited (100 MB by default). Do not use it for intermediate " +
|
|
18
|
+
"files the user does not need. An HTML file is shown on its own: files it references by " +
|
|
19
|
+
"relative path are not delivered with it, so inline or embed them.",
|
|
16
20
|
inputSchema: {
|
|
17
21
|
type: "object",
|
|
18
22
|
properties: {
|
|
19
23
|
file_path: {
|
|
20
24
|
type: "string",
|
|
21
25
|
minLength: 1,
|
|
22
|
-
description: "Absolute path of the file
|
|
26
|
+
description: "Absolute path of the file on the device, e.g. out/report.pdf in the workspace directory.",
|
|
27
|
+
},
|
|
28
|
+
file_id: {
|
|
29
|
+
type: "string",
|
|
30
|
+
minLength: 1,
|
|
31
|
+
description: "Instead of file_path: an attachment or artifact id of this conversation, e.g. the file_id of an image in a tool result.",
|
|
23
32
|
},
|
|
24
33
|
name: {
|
|
25
34
|
type: "string",
|
|
26
35
|
minLength: 1,
|
|
27
36
|
maxLength: MEDIA_NAME_MAX_CHARS,
|
|
28
|
-
description: 'File name shown to the user, e.g. "Q3 report.pdf". Default: the file name in file_path.',
|
|
37
|
+
description: 'File name shown to the user, e.g. "Q3 report.pdf". Default: the file name in file_path, or the stored name of file_id.',
|
|
29
38
|
},
|
|
30
39
|
},
|
|
31
|
-
required: ["file_path"],
|
|
32
40
|
additionalProperties: false,
|
|
33
41
|
},
|
|
34
42
|
};
|
|
@@ -82,6 +90,10 @@ export function contentTypeFor(name) {
|
|
|
82
90
|
const notFound = (path) => `File not found: ${clip(path, 200)}. Check the path with Glob.`;
|
|
83
91
|
const isDirectory = (path) => `${clip(path, 200)} is a directory; pass one file (pack the directory into one archive first).`;
|
|
84
92
|
const tooLarge = (path, size, max) => `File ${clip(path, 200)} is ${size} bytes, over the delivery limit of ${max} bytes; compress or split it with Bash and retry.`;
|
|
93
|
+
/** Neither or both of `file_path` and `file_id`. */
|
|
94
|
+
export const DELIVER_ONE_SOURCE_TEXT = "Pass exactly one of file_path (a path on the device) and file_id (an attachment or artifact id).";
|
|
95
|
+
/** A `file_id` that is no file of this conversation or its root. */
|
|
96
|
+
const unknownFileId = (id) => `file_id ${clip(id, 100)} is not an attachment or artifact of this conversation; pass the id of one.`;
|
|
85
97
|
const BAD_NAME = "name must not contain control characters, / or \\; pass a plain file name such as report.pdf.";
|
|
86
98
|
/** 默认产物名:路径的文件名部分,过长时保留末尾(扩展名)截到 255 个 UTF-16 单元以内。 */
|
|
87
99
|
function defaultName(path) {
|
|
@@ -100,9 +112,16 @@ export function sandboxDeliverTool(deps) {
|
|
|
100
112
|
return {
|
|
101
113
|
spec: SPEC,
|
|
102
114
|
defaultPolicy: "allow",
|
|
103
|
-
//
|
|
104
|
-
|
|
105
|
-
|
|
115
|
+
// nothing is delivered without an object store; without a usable device only file_id is
|
|
116
|
+
// (listed when the conversation's files can be read by id)
|
|
117
|
+
unavailable: async (ctx) => {
|
|
118
|
+
if (!deps.storage.available) {
|
|
119
|
+
return (await unavailableWhenNoSandbox(deps)(ctx)) ?? NO_STORAGE_REASON;
|
|
120
|
+
}
|
|
121
|
+
if (deps.read !== undefined)
|
|
122
|
+
return null;
|
|
123
|
+
return unavailableWhenNoSandbox(deps)(ctx);
|
|
124
|
+
},
|
|
106
125
|
timeoutMs: () => 2 * sandboxBaseTimeoutMs(deps.config.get()),
|
|
107
126
|
async run(input, ctx) {
|
|
108
127
|
// 存储在调用前就核对:不为一个交付不了的文件去 stat / 读沙箱
|
|
@@ -114,13 +133,19 @@ export function sandboxDeliverTool(deps) {
|
|
|
114
133
|
throw new ToolError(BAD_NAME);
|
|
115
134
|
}
|
|
116
135
|
const max = deps.config.get().sandbox.deliverMaxBytes;
|
|
117
|
-
|
|
136
|
+
const { file_path: filePath, file_id: fileId } = input;
|
|
137
|
+
if ((filePath === undefined) === (fileId === undefined)) {
|
|
138
|
+
throw new ToolError(DELIVER_ONE_SOURCE_TEXT);
|
|
139
|
+
}
|
|
140
|
+
if (fileId !== undefined)
|
|
141
|
+
return deliverById(deps, ctx, fileId, given, max);
|
|
142
|
+
checkPathShape(filePath, "file_path");
|
|
118
143
|
let path = "";
|
|
119
144
|
const { value: data, notices } = await inToolSandbox(deps, ctx, async (s) => {
|
|
120
145
|
const { h, p, signal } = s;
|
|
121
146
|
// bounded as the other file tools are: the admitted scope (a project file outside the
|
|
122
147
|
// workspace too)
|
|
123
|
-
path = checkToolPath(
|
|
148
|
+
path = checkToolPath(filePath, "file_path");
|
|
124
149
|
const st = await p.stat(h, path, signal);
|
|
125
150
|
if (st === null)
|
|
126
151
|
throw new ToolError(notFound(path));
|
|
@@ -137,23 +162,64 @@ export function sandboxDeliverTool(deps) {
|
|
|
137
162
|
return got.data;
|
|
138
163
|
});
|
|
139
164
|
const name = given ?? defaultName(path);
|
|
140
|
-
// uploaded outside the device lock: the device is not held meanwhile
|
|
141
165
|
const contentType = contentTypeFor(name);
|
|
142
|
-
|
|
143
|
-
{ name, contentType, data, sourcePath: path },
|
|
144
|
-
]);
|
|
145
|
-
const { artifactId, repeatOf } = stored;
|
|
146
|
-
if (repeatOf !== undefined) {
|
|
147
|
-
return {
|
|
148
|
-
content: [{ type: "text", text: withNotices(notices, REPEAT_TEXT(name, repeatOf)) }],
|
|
149
|
-
display: display(`已交付过(内容相同)${clip(name, 160)}`, `Already delivered (same content): ${clip(name, 160)}`),
|
|
150
|
-
};
|
|
151
|
-
}
|
|
152
|
-
const text = `Delivered ${name} (${data.byteLength} bytes, ${contentType}) to the user as artifact ${artifactId}; the user can download it from the conversation.`;
|
|
153
|
-
return {
|
|
154
|
-
content: [{ type: "text", text: withNotices(notices, text) }],
|
|
155
|
-
display: display(`交付文件 ${clip(name, 180)}`, `Delivered ${clip(name, 180)}`),
|
|
156
|
-
};
|
|
166
|
+
return deliverBytes(deps, ctx, { name, contentType, data, sourcePath: path }, notices);
|
|
157
167
|
},
|
|
158
168
|
};
|
|
159
169
|
}
|
|
170
|
+
/**
|
|
171
|
+
* A `file_id` delivery: the file of the conversation or its root (an attachment, a `read` copy
|
|
172
|
+
* such as a tool result's image, or an artifact) read from the object store, no device; the
|
|
173
|
+
* artifact's source path is `file_id/<id>`.
|
|
174
|
+
*/
|
|
175
|
+
async function deliverById(deps, ctx, id, given, max) {
|
|
176
|
+
if (deps.read === undefined)
|
|
177
|
+
throw new ToolError(NO_STORAGE);
|
|
178
|
+
let found;
|
|
179
|
+
try {
|
|
180
|
+
found = await findConversationFile(deps.read.files, {
|
|
181
|
+
orgId: ctx.orgId,
|
|
182
|
+
conversationId: ctx.conversationId,
|
|
183
|
+
rootConversationId: sandboxConversationOf(ctx),
|
|
184
|
+
id,
|
|
185
|
+
maxBytes: max + 1,
|
|
186
|
+
signal: ctx.signal,
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
catch (e) {
|
|
190
|
+
if (e instanceof ApiError && e.code === "storage.unavailable")
|
|
191
|
+
throw new ToolError(NO_STORAGE);
|
|
192
|
+
throw e;
|
|
193
|
+
}
|
|
194
|
+
if (found === null)
|
|
195
|
+
throw new ToolError(unknownFileId(id));
|
|
196
|
+
const name = given ?? (isValidArtifactName(found.name) ? found.name : defaultName(found.name));
|
|
197
|
+
if (found.size > max) {
|
|
198
|
+
await found.discard();
|
|
199
|
+
throw new ToolError(tooLarge(name, found.size, max));
|
|
200
|
+
}
|
|
201
|
+
const data = await found.open({ maxBytes: max + 1 });
|
|
202
|
+
if (data.byteLength > max)
|
|
203
|
+
throw new ToolError(tooLarge(name, data.byteLength, max));
|
|
204
|
+
ctx.signal.throwIfAborted();
|
|
205
|
+
const contentType = given === undefined && found.contentType ? found.contentType : contentTypeFor(name);
|
|
206
|
+
return deliverBytes(deps, ctx, { name, contentType, data, sourcePath: `file_id/${found.id}` }, []);
|
|
207
|
+
}
|
|
208
|
+
/** Stores one file as an artifact and answers with what the user received (or the repeat). */
|
|
209
|
+
async function deliverBytes(deps, ctx, file, notices) {
|
|
210
|
+
const { name, contentType, data } = file;
|
|
211
|
+
// uploaded outside the device lock: the device is not held meanwhile
|
|
212
|
+
const [stored] = await storeArtifacts(deps, ctx, [file]);
|
|
213
|
+
const { artifactId, repeatOf } = stored;
|
|
214
|
+
if (repeatOf !== undefined) {
|
|
215
|
+
return {
|
|
216
|
+
content: [{ type: "text", text: withNotices(notices, REPEAT_TEXT(name, repeatOf)) }],
|
|
217
|
+
display: display(`已交付过(内容相同)${clip(name, 160)}`, `Already delivered (same content): ${clip(name, 160)}`),
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
const text = `Delivered ${name} (${data.byteLength} bytes, ${contentType}) to the user as artifact ${artifactId}; the user can download it from the conversation.`;
|
|
221
|
+
return {
|
|
222
|
+
content: [{ type: "text", text: withNotices(notices, text) }],
|
|
223
|
+
display: display(`交付文件 ${clip(name, 180)}`, `Delivered ${clip(name, 180)}`),
|
|
224
|
+
};
|
|
225
|
+
}
|