@capybara-hq/kernel 0.1.0-rc.90 → 0.1.0-rc.92
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.d.ts +11 -0
- package/dist/conversations/events.js +12 -4
- package/dist/conversations/model-image.d.ts +6 -0
- package/dist/conversations/model-image.js +10 -1
- package/dist/device-access/device-access.service.d.ts +19 -4
- package/dist/device-access/device-access.service.js +40 -7
- package/dist/device-access/viewer.d.ts +4 -1
- package/dist/device-access/viewer.js +16 -3
- 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 +44 -6
- package/dist/tools/result-images.d.ts +91 -0
- package/dist/tools/result-images.js +195 -0
- package/package.json +3 -3
|
@@ -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
|
+
}
|
|
@@ -255,6 +255,8 @@ async function readById(deps, ctx, input, id) {
|
|
|
255
255
|
data: data.subarray(0, READ_MAX_BYTES),
|
|
256
256
|
size: Math.max(found.size, data.byteLength),
|
|
257
257
|
truncated: found.size > READ_MAX_BYTES || data.byteLength > READ_MAX_BYTES,
|
|
258
|
+
// already a stored copy of this conversation: a model without vision needs no second one
|
|
259
|
+
...(found.readCopyOf === ctx.conversationId && { storedAs: found.id }),
|
|
258
260
|
});
|
|
259
261
|
return {
|
|
260
262
|
...out,
|
|
@@ -313,6 +315,11 @@ async function readImage(read, ctx, input, file, image) {
|
|
|
313
315
|
answer = fallbackAnswerText(got.provider, got.model, got.text);
|
|
314
316
|
}
|
|
315
317
|
const withAnswer = (text) => (answer === null ? text : `${text}\n\n${answer}`);
|
|
318
|
+
if (answer !== null && file.storedAs !== undefined) {
|
|
319
|
+
return {
|
|
320
|
+
text: withAnswer(readImageText(file.name, image.mediaType, size, image, file.storedAs)),
|
|
321
|
+
};
|
|
322
|
+
}
|
|
316
323
|
// storeRead takes no signal: an aborted call stores nothing
|
|
317
324
|
ctx.signal.throwIfAborted();
|
|
318
325
|
let stored;
|
package/dist/tools/outputs.d.ts
CHANGED
|
@@ -53,11 +53,13 @@ export interface RenderedResult {
|
|
|
53
53
|
isError: boolean;
|
|
54
54
|
}
|
|
55
55
|
/**
|
|
56
|
-
*
|
|
57
|
-
* `
|
|
58
|
-
*
|
|
56
|
+
* Pipeline stage 5 (render): text blocks joined by lines; the n-th image block → `imageTexts[n]`
|
|
57
|
+
* (the stored copy or why it was not stored, `storeResultImages`), else a "not stored, so not
|
|
58
|
+
* shown" line; `resource_link` → `[resource <uri>]`; an unknown block →
|
|
59
|
+
* `[unsupported content <type>]`. A malformed result (not an object, content not an array) gets an
|
|
60
|
+
* explanation and is marked an error, never thrown (Review Focus 5).
|
|
59
61
|
*/
|
|
60
|
-
export declare function renderResult(result: unknown): RenderedResult;
|
|
62
|
+
export declare function renderResult(result: unknown, imageTexts?: readonly string[]): RenderedResult;
|
|
61
63
|
/**
|
|
62
64
|
* 管线第 5 阶段(转存):超过 `spillChars` 的文本存为输出存档,模型只见前 `previewChars` 个字符与截断说明。
|
|
63
65
|
*/
|
package/dist/tools/outputs.js
CHANGED
|
@@ -14,6 +14,7 @@ import { sql } from "kysely";
|
|
|
14
14
|
import { KernelConfigService } from "../infra/config/kernel-config.service.js";
|
|
15
15
|
import { KernelDb } from "../infra/database/kernel-db.js";
|
|
16
16
|
import { asPlatform } from "../infra/database/org-scope.js";
|
|
17
|
+
import { base64Bytes, isToolImageBlock, resultImageNotStoredText } from "./result-images.js";
|
|
17
18
|
/** 文本行数(按 `\n` 切分;空串算 1 行,与按行分页读取一致)。 */
|
|
18
19
|
export function countLines(s) {
|
|
19
20
|
let n = 1;
|
|
@@ -142,20 +143,16 @@ export async function resolveOutputRefs(input, load) {
|
|
|
142
143
|
};
|
|
143
144
|
return walk(input);
|
|
144
145
|
}
|
|
145
|
-
/** base64 数据解码后的字节数。 */
|
|
146
|
-
function base64Bytes(data) {
|
|
147
|
-
const s = data.replace(/\s/g, "");
|
|
148
|
-
const pad = s.endsWith("==") ? 2 : s.endsWith("=") ? 1 : 0;
|
|
149
|
-
return Math.max(0, Math.floor((s.length * 3) / 4) - pad);
|
|
150
|
-
}
|
|
151
146
|
/** 空结果的文本(模型可见,英文;部分供应商不接受空的 tool_result)。 */
|
|
152
147
|
const NO_OUTPUT = "(no output)";
|
|
153
148
|
/**
|
|
154
|
-
*
|
|
155
|
-
* `
|
|
156
|
-
*
|
|
149
|
+
* Pipeline stage 5 (render): text blocks joined by lines; the n-th image block → `imageTexts[n]`
|
|
150
|
+
* (the stored copy or why it was not stored, `storeResultImages`), else a "not stored, so not
|
|
151
|
+
* shown" line; `resource_link` → `[resource <uri>]`; an unknown block →
|
|
152
|
+
* `[unsupported content <type>]`. A malformed result (not an object, content not an array) gets an
|
|
153
|
+
* explanation and is marked an error, never thrown (Review Focus 5).
|
|
157
154
|
*/
|
|
158
|
-
export function renderResult(result) {
|
|
155
|
+
export function renderResult(result, imageTexts) {
|
|
159
156
|
if (!isPlainObject(result) || !Array.isArray(result.content)) {
|
|
160
157
|
return {
|
|
161
158
|
text: "The tool returned a malformed result (expected an object with a content array).",
|
|
@@ -165,6 +162,7 @@ export function renderResult(result) {
|
|
|
165
162
|
}
|
|
166
163
|
const parts = [];
|
|
167
164
|
const types = [];
|
|
165
|
+
let image = 0;
|
|
168
166
|
for (const block of result.content) {
|
|
169
167
|
const b = isPlainObject(block) ? block : {};
|
|
170
168
|
const type = typeof b.type === "string" ? b.type : "unknown";
|
|
@@ -172,9 +170,10 @@ export function renderResult(result) {
|
|
|
172
170
|
types.push(type);
|
|
173
171
|
if (type === "text" && typeof b.text === "string")
|
|
174
172
|
parts.push(b.text);
|
|
175
|
-
else if (
|
|
173
|
+
else if (isToolImageBlock(block) && typeof b.data === "string") {
|
|
176
174
|
const mime = typeof b.mimeType === "string" ? b.mimeType : "unknown";
|
|
177
|
-
parts.push(
|
|
175
|
+
parts.push(imageTexts?.[image] ?? resultImageNotStoredText(mime, base64Bytes(b.data)));
|
|
176
|
+
image++;
|
|
178
177
|
}
|
|
179
178
|
else if (type === "resource_link" && typeof b.uri === "string") {
|
|
180
179
|
parts.push(`[resource ${b.uri}]`);
|
package/dist/tools/pipeline.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import { type ConversationSource, type FormAnswer, type InputForm, type Logger } from "@capybara-hq/plugin-sdk";
|
|
1
|
+
import { type ConversationSource, type FormAnswer, type InputForm, type Logger, type ToolDisplay } from "@capybara-hq/plugin-sdk";
|
|
2
2
|
import type { AgentDefinition } from "../agents/definition.js";
|
|
3
3
|
import { ConversationApprovalProfile } from "../conversations/approval-profile.js";
|
|
4
|
+
import { AttachmentsService } from "../conversations/attachments.service.js";
|
|
4
5
|
import { EventLog } from "../conversations/event-log.js";
|
|
5
6
|
import { type ReviewRecord } from "../conversations/events.js";
|
|
6
7
|
import type { KernelSchemaDb } from "../db/kernel-schema.js";
|
|
@@ -25,7 +26,7 @@ import { PermissionCallGrants } from "../sandbox/permission-call-grants.js";
|
|
|
25
26
|
import { type CommandReview } from "../sandbox/review/index.js";
|
|
26
27
|
import { SandboxService } from "../sandbox/sandbox.service.js";
|
|
27
28
|
import { type UnattendedRun } from "../schedules/unattended.js";
|
|
28
|
-
import { ApprovalsService } from "./approvals.service.js";
|
|
29
|
+
import { ApprovalsService, type NetworkAskDetail } from "./approvals.service.js";
|
|
29
30
|
import { Breaker } from "./breaker.js";
|
|
30
31
|
import { Credentials } from "./credentials.js";
|
|
31
32
|
import { ToolDrift } from "./drift.js";
|
|
@@ -411,6 +412,78 @@ export declare const permissionCheckFailedText: (why: string) => string;
|
|
|
411
412
|
* run), the same for every `InputRequired` round of the call.
|
|
412
413
|
*/
|
|
413
414
|
export declare const toolIdempotencyKey: (conversationId: string, runId: string, callId: string) => string;
|
|
415
|
+
/** A network ask's kept display fields, written with its result when the ask settles. */
|
|
416
|
+
export declare const keptExtras: (kept: NetworkAskDetail["result"] | undefined) => {
|
|
417
|
+
outputId?: string;
|
|
418
|
+
contentTypes?: string[];
|
|
419
|
+
display?: ToolDisplay;
|
|
420
|
+
view?: {
|
|
421
|
+
kind: "command";
|
|
422
|
+
description?: string | undefined;
|
|
423
|
+
exitCode: number | null;
|
|
424
|
+
timedOut: boolean;
|
|
425
|
+
} | {
|
|
426
|
+
kind: "edit";
|
|
427
|
+
path: string;
|
|
428
|
+
created: boolean;
|
|
429
|
+
added: number;
|
|
430
|
+
removed: number;
|
|
431
|
+
truncated: boolean;
|
|
432
|
+
file?: {
|
|
433
|
+
path: string;
|
|
434
|
+
size: number;
|
|
435
|
+
sha256: string;
|
|
436
|
+
} | undefined;
|
|
437
|
+
hunks: {
|
|
438
|
+
oldStart: number;
|
|
439
|
+
newStart: number;
|
|
440
|
+
lines: {
|
|
441
|
+
kind: "add" | "ctx" | "del";
|
|
442
|
+
text: string;
|
|
443
|
+
}[];
|
|
444
|
+
}[];
|
|
445
|
+
} | {
|
|
446
|
+
kind: "read";
|
|
447
|
+
path: string;
|
|
448
|
+
fromLine?: number | undefined;
|
|
449
|
+
toLine?: number | undefined;
|
|
450
|
+
file?: {
|
|
451
|
+
path: string;
|
|
452
|
+
size: number;
|
|
453
|
+
sha256: string;
|
|
454
|
+
} | undefined;
|
|
455
|
+
} | {
|
|
456
|
+
kind: "guard";
|
|
457
|
+
reason: "modified" | "not_read";
|
|
458
|
+
} | {
|
|
459
|
+
kind: "not_loaded";
|
|
460
|
+
} | {
|
|
461
|
+
kind: "launch_unconfirmed";
|
|
462
|
+
taskId: string;
|
|
463
|
+
} | {
|
|
464
|
+
kind: "reveal";
|
|
465
|
+
reveal: "initial_password" | "invitation_link";
|
|
466
|
+
} | {
|
|
467
|
+
kind: "handoff";
|
|
468
|
+
title: {
|
|
469
|
+
zh: string;
|
|
470
|
+
en: string;
|
|
471
|
+
};
|
|
472
|
+
target: {
|
|
473
|
+
type: "link";
|
|
474
|
+
url: string;
|
|
475
|
+
} | {
|
|
476
|
+
type: "connect";
|
|
477
|
+
connectorId: string;
|
|
478
|
+
};
|
|
479
|
+
};
|
|
480
|
+
media?: {
|
|
481
|
+
attachmentId: string;
|
|
482
|
+
name: string;
|
|
483
|
+
mediaType: string;
|
|
484
|
+
size: number;
|
|
485
|
+
}[];
|
|
486
|
+
};
|
|
414
487
|
/**
|
|
415
488
|
* 工具执行管线(spec 5.4 / 6.2):每个阶段是独立函数——
|
|
416
489
|
* `resolveOutputRefs` → `validateInput` → `decidePolicy` → `execute`(超时、熔断)→ `renderResult` / `spillIfLarge`
|
|
@@ -435,6 +508,11 @@ export declare class ToolPipeline {
|
|
|
435
508
|
private readonly approvalProfile?;
|
|
436
509
|
/** The review model's judgment of an ask under Approve for me (R3); absent: every ask asks. */
|
|
437
510
|
private readonly toolReview?;
|
|
511
|
+
/**
|
|
512
|
+
* Stores the images a tool result carries as `read` copies of the calling conversation (tool
|
|
513
|
+
* result images design §2); absent (hand-built pipelines): images are named as not stored.
|
|
514
|
+
*/
|
|
515
|
+
private readonly resultImages?;
|
|
438
516
|
private readonly decide;
|
|
439
517
|
private readonly deps;
|
|
440
518
|
constructor(kdb: KernelDb, eventLog: EventLog,
|
|
@@ -460,7 +538,12 @@ export declare class ToolPipeline {
|
|
|
460
538
|
*/
|
|
461
539
|
approvalProfile?: Pick<ConversationApprovalProfile, "resolve"> | undefined,
|
|
462
540
|
/** The review model's judgment of an ask under Approve for me (R3); absent: every ask asks. */
|
|
463
|
-
toolReview?: ToolAskReviewer | undefined
|
|
541
|
+
toolReview?: ToolAskReviewer | undefined,
|
|
542
|
+
/**
|
|
543
|
+
* Stores the images a tool result carries as `read` copies of the calling conversation (tool
|
|
544
|
+
* result images design §2); absent (hand-built pipelines): images are named as not stored.
|
|
545
|
+
*/
|
|
546
|
+
resultImages?: Pick<AttachmentsService, "storeRead"> | undefined);
|
|
464
547
|
/**
|
|
465
548
|
* tools 节点:按顺序处理本步 assistant 消息里的全部 `tool_call`,每个调用都以一条 `tool_result` 结束
|
|
466
549
|
* (之后才回到 prepare 构建下一次请求,保持「已记录调用、未记录结果之间不构建请求」的不变式)。
|
|
@@ -566,6 +649,12 @@ export declare class ToolPipeline {
|
|
|
566
649
|
private ownDeviceReport;
|
|
567
650
|
/** Appends a sub-agent's connect card to its root conversation ({@link rootSurfaceOf}). */
|
|
568
651
|
private surfaceConnectInRoot;
|
|
652
|
+
/**
|
|
653
|
+
* How a call's result images are stored: a `read` copy bound to the calling conversation (a
|
|
654
|
+
* sub-agent's own, never its root), owned by the run's trigger account; absent without the
|
|
655
|
+
* attachments service.
|
|
656
|
+
*/
|
|
657
|
+
private storeResultImage;
|
|
569
658
|
/**
|
|
570
659
|
* 发出本步调用的请求里带了完整定义的工具 key:本步最后一次尝试的 `model_call.request.tools`
|
|
571
660
|
* (`assistant_message` 来自最后一次尝试)。该请求不在 ToolSearch 模式(没有 `catalog`,工具全部发送)
|