@capybara-hq/kernel 0.1.0-rc.42 → 0.1.0-rc.44
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/dist/catalog/marketplaces.service.d.ts +1 -1
- package/dist/catalog/scope-sync.d.ts +3 -2
- package/dist/catalog/scope-sync.js +3 -2
- package/dist/client/client-access.service.js +4 -4
- package/dist/config/schema.d.ts +3 -0
- package/dist/config/schema.js +30 -0
- package/dist/conversations/events.d.ts +3 -0
- package/dist/conversations/events.js +7 -3
- package/dist/ctx/create-ctx.d.ts +13 -6
- package/dist/ctx/create-ctx.js +21 -5
- package/dist/db/kernel-schema.d.ts +10 -0
- package/dist/extensions/enabled.d.ts +24 -4
- package/dist/extensions/enabled.js +47 -10
- package/dist/extensions/host.d.ts +7 -3
- package/dist/extensions/host.js +13 -8
- package/dist/extensions/org-config.d.ts +5 -2
- package/dist/extensions/org-config.js +32 -22
- package/dist/infra/config/kernel-config.service.js +4 -0
- package/dist/models/enablement.d.ts +1 -1
- package/dist/models/enablement.js +1 -1
- package/dist/models/image-usable.d.ts +22 -0
- package/dist/models/image-usable.js +29 -0
- package/dist/models/images.d.ts +125 -0
- package/dist/models/images.js +440 -0
- package/dist/models/models.module.d.ts +3 -2
- package/dist/models/models.module.js +16 -5
- package/dist/models/org-models.schemas.js +1 -0
- package/dist/models/purposes.controller.d.ts +7 -0
- package/dist/models/purposes.controller.js +9 -0
- package/dist/models/purposes.d.ts +28 -3
- package/dist/models/purposes.js +40 -13
- package/dist/platform/ops/models.ops.js +10 -0
- package/dist/runtime/hook-calls.d.ts +11 -1
- package/dist/runtime/hook-calls.js +24 -1
- package/dist/runtime/providers.d.ts +10 -6
- package/dist/runtime/providers.js +23 -4
- package/dist/runtime/usage-report.d.ts +10 -6
- package/dist/runtime/usage-report.js +31 -11
- package/dist/sandbox/review/permission-candidate.js +22 -6
- package/dist/sandbox/review/review.service.d.ts +1 -1
- package/dist/sandbox/review/review.service.js +43 -12
- package/dist/tools/builtin-names.d.ts +3 -1
- package/dist/tools/builtin-names.js +5 -1
- package/dist/tools/builtins/artifacts.d.ts +43 -0
- package/dist/tools/builtins/artifacts.js +67 -0
- package/dist/tools/builtins/builtin-tools.d.ts +4 -0
- package/dist/tools/builtins/builtin-tools.js +28 -5
- package/dist/tools/builtins/image/generate.d.ts +59 -0
- package/dist/tools/builtins/image/generate.js +535 -0
- package/dist/tools/builtins/image/index.d.ts +2 -0
- package/dist/tools/builtins/image/index.js +2 -0
- package/dist/tools/builtins/image/paths.d.ts +12 -0
- package/dist/tools/builtins/image/paths.js +26 -0
- package/dist/tools/builtins/sandbox/deliver.js +7 -49
- package/dist/tools/pipeline.js +15 -7
- package/dist/tools/registry.d.ts +2 -2
- package/dist/tools/registry.js +2 -2
- package/dist/tools/tools.module.js +3 -0
- package/package.json +4 -4
- package/src/migrations/0160_model_usage_image_kind.sql +10 -0
|
@@ -0,0 +1,535 @@
|
|
|
1
|
+
import { IMAGE_ASPECT_RATIOS, IMAGE_MEDIA_TYPES, isModelError, MEDIA_LIMITS, ToolError, } from "@capybara-hq/plugin-sdk";
|
|
2
|
+
import { sql } from "kysely";
|
|
3
|
+
import { isValidArtifactName } from "../../../conversations/events.js";
|
|
4
|
+
import { ApiError } from "../../../errors.js";
|
|
5
|
+
import { IMAGE_PURPOSE, imagePurposeUsable } from "../../../models/image-usable.js";
|
|
6
|
+
import { billedImages, ImageCallDenied, } from "../../../models/images.js";
|
|
7
|
+
import { hookDeniedAudit, hookDeniedEvent, hookScope, } from "../../../runtime/hook-calls.js";
|
|
8
|
+
import { appendCounted } from "../../../runtime/model-call.js";
|
|
9
|
+
import { ProviderListError } from "../../../runtime/providers.js";
|
|
10
|
+
import { NO_STORAGE, NO_STORAGE_REASON, storeArtifacts, } from "../artifacts.js";
|
|
11
|
+
import { checkFilePathShape, checkToolWritable, clip, display, inToolSandbox, sandboxConversationOf, sandboxUsable, withNotices, withPathLease, } from "../sandbox/common.js";
|
|
12
|
+
import { assertReadAndUnchanged, FileGuardError, fileStateOf } from "../sandbox/file-state.js";
|
|
13
|
+
import { READ_MAX_BYTES } from "../sandbox/read.js";
|
|
14
|
+
import { generateImagePaths } from "./paths.js";
|
|
15
|
+
/** The model purpose the tool calls (image generation spec §5.4; no fallback). */
|
|
16
|
+
const PURPOSE = IMAGE_PURPOSE;
|
|
17
|
+
/** The most reference images one call names (the schema's `maxItems`). */
|
|
18
|
+
const MAX_REFERENCES = 4;
|
|
19
|
+
/** The most images one call asks for (the schema's maximum; the kernel cap may be lower). */
|
|
20
|
+
const MAX_IMAGES = 4;
|
|
21
|
+
/** The longest base name (`name`). */
|
|
22
|
+
const NAME_MAX_CHARS = 100;
|
|
23
|
+
export const GENERATE_IMAGE_SPEC = {
|
|
24
|
+
name: "GenerateImage",
|
|
25
|
+
// Display only (the tool row; not in the fingerprint, never sent to the model).
|
|
26
|
+
keyArgs: ["prompt"],
|
|
27
|
+
description: "Generate images from a text prompt with this organization's image model, and deliver them to " +
|
|
28
|
+
"the user in the conversation. Write a specific prompt: subject, composition, style, lighting, " +
|
|
29
|
+
"any text that must appear. Optionally pass reference images (attachment or earlier generated " +
|
|
30
|
+
"image ids) to guide the result. Each call costs money: generate only what the user asked for.",
|
|
31
|
+
inputSchema: {
|
|
32
|
+
type: "object",
|
|
33
|
+
properties: {
|
|
34
|
+
prompt: {
|
|
35
|
+
type: "string",
|
|
36
|
+
minLength: 1,
|
|
37
|
+
description: "What to draw: subject, composition, style, lighting, any text to include.",
|
|
38
|
+
},
|
|
39
|
+
aspect_ratio: {
|
|
40
|
+
type: "string",
|
|
41
|
+
enum: [...IMAGE_ASPECT_RATIOS],
|
|
42
|
+
description: "Shape of the images; the closest size the model supports is used. Default: the model's default size.",
|
|
43
|
+
},
|
|
44
|
+
n: {
|
|
45
|
+
type: "integer",
|
|
46
|
+
minimum: 1,
|
|
47
|
+
maximum: MAX_IMAGES,
|
|
48
|
+
description: "How many images to generate (default 1).",
|
|
49
|
+
},
|
|
50
|
+
reference_images: {
|
|
51
|
+
type: "array",
|
|
52
|
+
maxItems: MAX_REFERENCES,
|
|
53
|
+
items: { type: "string", minLength: 1 },
|
|
54
|
+
description: "Ids of images that guide the result: attachment ids of this conversation, or artifact ids of images generated earlier in it.",
|
|
55
|
+
},
|
|
56
|
+
name: {
|
|
57
|
+
type: "string",
|
|
58
|
+
minLength: 1,
|
|
59
|
+
maxLength: NAME_MAX_CHARS,
|
|
60
|
+
pattern: "^[^/\\\\]+$",
|
|
61
|
+
description: 'Base file name shown to the user, without extension, e.g. "poster" (gives poster-1.png, poster-2.png). Default: image.',
|
|
62
|
+
},
|
|
63
|
+
file_path: {
|
|
64
|
+
type: "string",
|
|
65
|
+
minLength: 1,
|
|
66
|
+
description: "Also write the images into the device at this path, e.g. out/poster.png in the workspace directory; several images get -1, -2 suffixes before the extension.",
|
|
67
|
+
},
|
|
68
|
+
},
|
|
69
|
+
required: ["prompt"],
|
|
70
|
+
additionalProperties: false,
|
|
71
|
+
},
|
|
72
|
+
};
|
|
73
|
+
/** Why the tool is not listed: the org's `image` purpose has no usable model (spec §5.3). */
|
|
74
|
+
export const NO_IMAGE_MODEL_REASON = "No image model is configured for this organization";
|
|
75
|
+
/** The tool error when the purpose's model went away after the listing. */
|
|
76
|
+
export const NO_IMAGE_MODEL_TEXT = `${NO_IMAGE_MODEL_REASON}; ask an org admin to set a model for the image purpose, or continue without the image.`;
|
|
77
|
+
/** The tool error when a `model.request` policy hook denies the call. */
|
|
78
|
+
export const GENERATE_IMAGE_DENIED_TEXT = "An org policy blocked this image request; continue without it or ask the user.";
|
|
79
|
+
const refusedText = (message) => `The image model refused this prompt: ${message}. Rephrase it or ask the user.`;
|
|
80
|
+
const failedText = (message) => `Image generation failed: ${message}. Retry once, or continue without the image.`;
|
|
81
|
+
/** A refused argument (the request building's text names it and the allowed values). */
|
|
82
|
+
const invalidText = (message) => `${message}; fix the argument and retry.`;
|
|
83
|
+
const unknownReferenceText = (k) => `reference_images[${k}] is not an attachment or generated image of this conversation; pass an attachment id or the artifact id of an image generated earlier in it.`;
|
|
84
|
+
const badReferenceText = (k) => `reference_images[${k}] is not a PNG, JPEG, GIF or WebP image up to ${MEDIA_LIMITS.imageBytes / 1_048_576} MB; pass another image, or call without it.`;
|
|
85
|
+
const BAD_NAME = "name must not contain control characters, / or \\; pass a plain base name such as poster.";
|
|
86
|
+
const BLANK_NAME = 'name must not be blank; pass a short file name such as "poster", or omit it.';
|
|
87
|
+
/** The request building's refusal of too many references (checked before any is read). */
|
|
88
|
+
const tooManyReferencesText = (max) => invalidText(max === 0
|
|
89
|
+
? "this model takes no reference images"
|
|
90
|
+
: `this model takes at most ${max} reference images`);
|
|
91
|
+
/** Why a device write failed for a reason the device did not explain (its error stays in the log). */
|
|
92
|
+
const copyFailedText = (path) => `the device could not write ${clip(path, 200)}; retry the call, or pass another file_path.`;
|
|
93
|
+
/** `Write`'s refusals of a target, worded for `file_path` (the images are already delivered). */
|
|
94
|
+
const isDirectoryText = (path) => `${clip(path, 200)} is a directory; pass the path of a file inside it as file_path.`;
|
|
95
|
+
const notReadText = (path) => `${clip(path, 200)} already exists and this conversation has not read it; Read it first to replace it, or pass another file_path.`;
|
|
96
|
+
const modifiedText = (path) => `${clip(path, 200)} has changed since this conversation read it; Read it again to replace it, or pass another file_path.`;
|
|
97
|
+
const vanishedText = (path) => `${clip(path, 200)} disappeared while it was being written; retry the call.`;
|
|
98
|
+
/** The device line of a call whose conversation has no device to write to. */
|
|
99
|
+
export const NO_DEVICE_LINE = "Not written to the device: this conversation has no device.";
|
|
100
|
+
/** Lower-case UUIDs: attachment and artifact ids. */
|
|
101
|
+
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
102
|
+
/** The file extension of each image media type. */
|
|
103
|
+
const EXTENSIONS = {
|
|
104
|
+
"image/png": "png",
|
|
105
|
+
"image/jpeg": "jpg",
|
|
106
|
+
"image/gif": "gif",
|
|
107
|
+
"image/webp": "webp",
|
|
108
|
+
};
|
|
109
|
+
/**
|
|
110
|
+
* The builtin `GenerateImage` (image generation spec §5.3): generates images with the org's
|
|
111
|
+
* `image` purpose model ({@link ModelImages}), stores them as artifacts of the conversation as
|
|
112
|
+
* `Deliver` stores a file (all or none, {@link storeArtifacts}), records the call's `usage` event
|
|
113
|
+
* (purpose `image`, the call id, `outputImages`) and, with `file_path`, also writes the images
|
|
114
|
+
* into the device through `Write`'s path checks (the command review covers such a call as a
|
|
115
|
+
* write). Listed only while the purpose resolves to a callable image model and an object store
|
|
116
|
+
* is there. A `model.request` policy denial is logged as any hook denial and sends nothing; a
|
|
117
|
+
* refusal or a failure is an actionable tool error, never retried. The model sees only the result
|
|
118
|
+
* text, so replays never call an image model.
|
|
119
|
+
*/
|
|
120
|
+
export function generateImageTool(deps) {
|
|
121
|
+
return {
|
|
122
|
+
spec: GENERATE_IMAGE_SPEC,
|
|
123
|
+
// the admins mapped a model to the purpose on purpose: that is the opt-in (spec §5.3)
|
|
124
|
+
defaultPolicy: "allow",
|
|
125
|
+
// the predicate the agent form's purpose availability reads too (one rule, no drift)
|
|
126
|
+
unavailable: async (scope) => {
|
|
127
|
+
const usable = await imagePurposeUsable(deps, scope.orgId);
|
|
128
|
+
if (usable === "no-model")
|
|
129
|
+
return NO_IMAGE_MODEL_REASON;
|
|
130
|
+
return usable === "no-storage" ? NO_STORAGE_REASON : null;
|
|
131
|
+
},
|
|
132
|
+
timeoutMs: () => deps.config.get().models.imageTimeoutMs + 60_000,
|
|
133
|
+
async run(raw, ctx) {
|
|
134
|
+
const input = raw;
|
|
135
|
+
if (!deps.storage.available)
|
|
136
|
+
throw new ToolError(NO_STORAGE);
|
|
137
|
+
const base = input.name?.trim();
|
|
138
|
+
if (base === "")
|
|
139
|
+
throw new ToolError(BLANK_NAME);
|
|
140
|
+
if (base !== undefined && (!isValidArtifactName(base) || /[/\\]/.test(base))) {
|
|
141
|
+
throw new ToolError(BAD_NAME);
|
|
142
|
+
}
|
|
143
|
+
if (input.file_path !== undefined)
|
|
144
|
+
checkFilePathShape(input.file_path);
|
|
145
|
+
const call = {
|
|
146
|
+
prompt: input.prompt,
|
|
147
|
+
...(input.aspect_ratio !== undefined && { aspectRatio: input.aspect_ratio }),
|
|
148
|
+
...(input.n !== undefined && { n: input.n }),
|
|
149
|
+
};
|
|
150
|
+
// the cheap checks (prompt, count, size, the model) before any reference is read
|
|
151
|
+
let prepared = await prepare(deps, ctx, call);
|
|
152
|
+
const refs = input.reference_images ?? [];
|
|
153
|
+
if (refs.length > prepared.info.maxReferenceImages) {
|
|
154
|
+
throw new ToolError(tooManyReferencesText(prepared.info.maxReferenceImages));
|
|
155
|
+
}
|
|
156
|
+
if (refs.length > 0) {
|
|
157
|
+
// the bytes are checked (type, size) and sent by the request building
|
|
158
|
+
const referenceImages = await resolveReferences(deps, ctx, refs);
|
|
159
|
+
prepared = await prepare(deps, ctx, { ...call, referenceImages });
|
|
160
|
+
}
|
|
161
|
+
const result = await generate(deps, ctx, prepared);
|
|
162
|
+
// a valid answer is billed whatever happens to its images afterwards (ruling R11)
|
|
163
|
+
await logUsage(deps, ctx, prepared, result);
|
|
164
|
+
// images a late answer carries after an abort are dropped: nothing is stored
|
|
165
|
+
ctx.signal.throwIfAborted();
|
|
166
|
+
const max = deps.config.get().sandbox.deliverMaxBytes;
|
|
167
|
+
const files = result.images.map((img, i) => {
|
|
168
|
+
const data = Buffer.from(img.data, "base64");
|
|
169
|
+
if (data.byteLength > max) {
|
|
170
|
+
// a server failure of the call (spec §6), with no partial delivery: nothing is stored
|
|
171
|
+
throw new ToolError(failedText(`the model returned an image of ${data.byteLength} bytes, over the artifact limit of ${max} bytes`));
|
|
172
|
+
}
|
|
173
|
+
const ext = EXTENSIONS[img.mediaType];
|
|
174
|
+
const stem = base ?? "image";
|
|
175
|
+
return {
|
|
176
|
+
name: result.images.length === 1 ? `${stem}.${ext}` : `${stem}-${i + 1}.${ext}`,
|
|
177
|
+
contentType: img.mediaType,
|
|
178
|
+
data: new Uint8Array(data.buffer, data.byteOffset, data.byteLength),
|
|
179
|
+
};
|
|
180
|
+
});
|
|
181
|
+
// each call's images are their own files, never versions of an earlier call's (R13)
|
|
182
|
+
const stored = await storeArtifacts(deps, ctx, files.map((f) => ({ ...f, sourcePath: `generated/${ctx.callId}/${f.name}` })));
|
|
183
|
+
let deviceLine = null;
|
|
184
|
+
let notices = [];
|
|
185
|
+
if (input.file_path !== undefined) {
|
|
186
|
+
const copied = await copyToDevice(deps, ctx, input.file_path, files);
|
|
187
|
+
deviceLine = copied.line;
|
|
188
|
+
notices = copied.notices;
|
|
189
|
+
}
|
|
190
|
+
const text = resultText(prepared, stored, files, result.revisedPrompt, deviceLine);
|
|
191
|
+
return {
|
|
192
|
+
content: [{ type: "text", text: withNotices(notices, text) }],
|
|
193
|
+
display: display(`生成图片 ${clip(input.prompt, 160)}`, `Generated images: ${clip(input.prompt, 160)}`),
|
|
194
|
+
};
|
|
195
|
+
},
|
|
196
|
+
};
|
|
197
|
+
}
|
|
198
|
+
/** {@link ModelImages.prepare} with its refusals as tool errors. */
|
|
199
|
+
async function prepare(deps, ctx, call) {
|
|
200
|
+
try {
|
|
201
|
+
return await deps.images.prepare(ctx.orgId, PURPOSE, call);
|
|
202
|
+
}
|
|
203
|
+
catch (e) {
|
|
204
|
+
throw toolErrorOf(e) ?? e;
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
/**
|
|
208
|
+
* The tool error of a refusal of the image call, or null for an error the pipeline reports
|
|
209
|
+
* itself (an abort, a kernel fault).
|
|
210
|
+
*/
|
|
211
|
+
function toolErrorOf(e) {
|
|
212
|
+
if (e instanceof ToolError)
|
|
213
|
+
return e;
|
|
214
|
+
if (e instanceof ApiError) {
|
|
215
|
+
if (e.code === "validation_failed")
|
|
216
|
+
return new ToolError(invalidText(e.message));
|
|
217
|
+
// a transient list error of the provider: the call may succeed on a retry
|
|
218
|
+
if (e instanceof ProviderListError)
|
|
219
|
+
return new ToolError(failedText(e.message));
|
|
220
|
+
if (e.code === "model.unconfigured" || e.code === "agent.model_unavailable") {
|
|
221
|
+
return new ToolError(NO_IMAGE_MODEL_TEXT);
|
|
222
|
+
}
|
|
223
|
+
return null;
|
|
224
|
+
}
|
|
225
|
+
if (isModelError(e) && e.kind === "refusal")
|
|
226
|
+
return new ToolError(refusedText(e.message));
|
|
227
|
+
if (isModelError(e))
|
|
228
|
+
return new ToolError(failedText(e.message));
|
|
229
|
+
return null;
|
|
230
|
+
}
|
|
231
|
+
/**
|
|
232
|
+
* Reads the reference images as bytes, each an id of the conversation: an attachment of the
|
|
233
|
+
* conversation whose device the call uses (a sub-agent: its root's, as `FetchAttachment`
|
|
234
|
+
* resolves), else an `artifact_created` of the calling conversation or its root. Anything else
|
|
235
|
+
* names its index; a file that is not an image within `MEDIA_LIMITS.imageBytes` is refused before
|
|
236
|
+
* it is read.
|
|
237
|
+
*/
|
|
238
|
+
async function resolveReferences(deps, ctx, ids) {
|
|
239
|
+
const root = sandboxConversationOf(ctx);
|
|
240
|
+
const out = [];
|
|
241
|
+
for (const [k, id] of ids.entries()) {
|
|
242
|
+
if (!UUID.test(id))
|
|
243
|
+
throw new ToolError(unknownReferenceText(k));
|
|
244
|
+
const found = await openReference(deps, ctx, root, id.toLowerCase());
|
|
245
|
+
if (found === null)
|
|
246
|
+
throw new ToolError(unknownReferenceText(k));
|
|
247
|
+
const mediaType = found.contentType.split(";")[0]?.trim().toLowerCase() ?? "";
|
|
248
|
+
if (!IMAGE_MEDIA_TYPES.includes(mediaType) ||
|
|
249
|
+
found.size > MEDIA_LIMITS.imageBytes) {
|
|
250
|
+
await found.body.cancel().catch(() => { });
|
|
251
|
+
throw new ToolError(badReferenceText(k));
|
|
252
|
+
}
|
|
253
|
+
const bytes = new Uint8Array(await new Response(found.body).arrayBuffer());
|
|
254
|
+
if (bytes.byteLength > MEDIA_LIMITS.imageBytes)
|
|
255
|
+
throw new ToolError(badReferenceText(k));
|
|
256
|
+
out.push({
|
|
257
|
+
mediaType: mediaType,
|
|
258
|
+
data: Buffer.from(bytes).toString("base64"),
|
|
259
|
+
});
|
|
260
|
+
}
|
|
261
|
+
return out;
|
|
262
|
+
}
|
|
263
|
+
/** One reference by id: its declared type and size and its bytes, or null when it is not one. */
|
|
264
|
+
async function openReference(deps, ctx, root, id) {
|
|
265
|
+
try {
|
|
266
|
+
const attachment = await deps.attachments.openForConversation(ctx.orgId, root, id);
|
|
267
|
+
if (attachment !== null)
|
|
268
|
+
return attachment;
|
|
269
|
+
const row = await deps
|
|
270
|
+
.db()
|
|
271
|
+
.selectFrom("conversation_events")
|
|
272
|
+
.select("payload")
|
|
273
|
+
.where("conversation_id", "in", [...new Set([ctx.conversationId, root])])
|
|
274
|
+
.where("type", "=", "artifact_created")
|
|
275
|
+
.where(sql `payload->>'artifactId'`, "=", id)
|
|
276
|
+
.limit(1)
|
|
277
|
+
.executeTakeFirst();
|
|
278
|
+
if (!row)
|
|
279
|
+
return null;
|
|
280
|
+
const a = row.payload;
|
|
281
|
+
const got = await deps.storage.kernel(ctx.orgId).get(a.objectKey);
|
|
282
|
+
if (got === null)
|
|
283
|
+
return null;
|
|
284
|
+
return { contentType: a.contentType, size: got.head.size, body: got.body };
|
|
285
|
+
}
|
|
286
|
+
catch (e) {
|
|
287
|
+
if (e instanceof ApiError && e.code === "storage.unavailable")
|
|
288
|
+
throw new ToolError(NO_STORAGE);
|
|
289
|
+
throw e;
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
/**
|
|
293
|
+
* Runs the prepared call (the hooks fire for a `chat` or `subagent` conversation only). A policy
|
|
294
|
+
* denial is recorded (`hook_denied` with its audit row) and becomes the denial tool error.
|
|
295
|
+
*/
|
|
296
|
+
async function generate(deps, ctx, prepared) {
|
|
297
|
+
const runId = ctx.runId ?? "";
|
|
298
|
+
const scope = hookScope(deps.hooks, {
|
|
299
|
+
...(ctx.conversationKind !== undefined && { conversationKind: ctx.conversationKind }),
|
|
300
|
+
orgId: ctx.orgId,
|
|
301
|
+
accountId: ctx.accountId,
|
|
302
|
+
agentId: ctx.agentId,
|
|
303
|
+
agentVersion: ctx.agentVersion ?? 1,
|
|
304
|
+
conversationId: ctx.conversationId,
|
|
305
|
+
runId,
|
|
306
|
+
parent: ctx.parent,
|
|
307
|
+
});
|
|
308
|
+
try {
|
|
309
|
+
return await deps.images.run(ctx.orgId, prepared, {
|
|
310
|
+
kind: "conversation",
|
|
311
|
+
// without a scope no hook fires (the runner is not passed), so the fields are unused
|
|
312
|
+
scope: scope ?? {
|
|
313
|
+
orgId: ctx.orgId,
|
|
314
|
+
accountId: ctx.accountId,
|
|
315
|
+
agentId: ctx.agentId,
|
|
316
|
+
agentVersion: ctx.agentVersion ?? 1,
|
|
317
|
+
conversationId: ctx.conversationId,
|
|
318
|
+
runId,
|
|
319
|
+
},
|
|
320
|
+
step: ctx.step ?? 0,
|
|
321
|
+
callId: ctx.callId,
|
|
322
|
+
}, ctx.signal, scope ? deps.hooks : undefined);
|
|
323
|
+
}
|
|
324
|
+
catch (e) {
|
|
325
|
+
if (e instanceof ImageCallDenied) {
|
|
326
|
+
await recordDenial(deps, ctx, runId, e.verdict);
|
|
327
|
+
throw new ToolError(GENERATE_IMAGE_DENIED_TEXT);
|
|
328
|
+
}
|
|
329
|
+
// an abort is the pipeline's (the run stopped or the call timed out)
|
|
330
|
+
if (ctx.signal.aborted)
|
|
331
|
+
throw e;
|
|
332
|
+
const mapped = toolErrorOf(e);
|
|
333
|
+
if (mapped === null)
|
|
334
|
+
throw e;
|
|
335
|
+
deps.log.warn("GenerateImage call failed", {
|
|
336
|
+
conversationId: ctx.conversationId,
|
|
337
|
+
callId: ctx.callId,
|
|
338
|
+
err: e,
|
|
339
|
+
});
|
|
340
|
+
throw mapped;
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
/**
|
|
344
|
+
* Appends the call's `usage` event (the tool call's run and step, `callId`, `outputImages`;
|
|
345
|
+
* idempotent per call) and owes its `usage.report` delivery in the same transaction; a
|
|
346
|
+
* sub-agent's call also counts on its budget run ({@link appendCounted}).
|
|
347
|
+
*/
|
|
348
|
+
async function logUsage(deps, ctx, prepared, result) {
|
|
349
|
+
const runId = ctx.runId ?? "";
|
|
350
|
+
const event = {
|
|
351
|
+
type: "usage",
|
|
352
|
+
...(runId !== "" && { runId }),
|
|
353
|
+
idemKey: `usage_image:${runId}:${ctx.callId}`,
|
|
354
|
+
payload: {
|
|
355
|
+
step: ctx.step ?? 0,
|
|
356
|
+
provider: prepared.ref.provider,
|
|
357
|
+
model: prepared.ref.model,
|
|
358
|
+
inputTokens: result.usage.inputTokens,
|
|
359
|
+
outputTokens: result.usage.outputTokens,
|
|
360
|
+
cacheReadTokens: result.usage.cacheReadTokens,
|
|
361
|
+
cacheWriteTokens: result.usage.cacheWriteTokens,
|
|
362
|
+
outputImages: billedImages(result),
|
|
363
|
+
purpose: PURPOSE,
|
|
364
|
+
callId: ctx.callId,
|
|
365
|
+
},
|
|
366
|
+
};
|
|
367
|
+
await appendCounted(deps, {
|
|
368
|
+
conversationId: ctx.conversationId,
|
|
369
|
+
parentRunId: ctx.parentRunId,
|
|
370
|
+
budgetRunId: ctx.budgetRunId,
|
|
371
|
+
}, [event]);
|
|
372
|
+
}
|
|
373
|
+
/**
|
|
374
|
+
* Records a `model.request` denial of the call: the `hook_denied` event (the tool call's step and
|
|
375
|
+
* `callId`) with its `hook.denied` audit row (`detail.purpose: "image"`), in one transaction.
|
|
376
|
+
*/
|
|
377
|
+
async function recordDenial(deps, ctx, runId, verdict) {
|
|
378
|
+
const site = {
|
|
379
|
+
orgId: ctx.orgId,
|
|
380
|
+
conversationId: ctx.conversationId,
|
|
381
|
+
runId,
|
|
382
|
+
accountId: ctx.accountId,
|
|
383
|
+
agentId: ctx.agentId,
|
|
384
|
+
idemKey: `hook_denied_image:${runId}:${ctx.callId}`,
|
|
385
|
+
};
|
|
386
|
+
const event = hookDeniedEvent(site, "model.request", verdict, {
|
|
387
|
+
step: ctx.step ?? 0,
|
|
388
|
+
attempt: 1,
|
|
389
|
+
callId: ctx.callId,
|
|
390
|
+
});
|
|
391
|
+
const entry = hookDeniedAudit(site, event.payload, verdict);
|
|
392
|
+
entry.detail = { ...entry.detail, purpose: PURPOSE };
|
|
393
|
+
deps.log.warn("GenerateImage blocked by a policy hook", {
|
|
394
|
+
conversationId: ctx.conversationId,
|
|
395
|
+
callId: ctx.callId,
|
|
396
|
+
plugin: verdict.plugin,
|
|
397
|
+
cause: verdict.cause,
|
|
398
|
+
});
|
|
399
|
+
const written = await deps.stepLog.appendAudited(ctx.conversationId, [event], entry);
|
|
400
|
+
if (written.length > 0) {
|
|
401
|
+
await deps.eventLog.notify(ctx.conversationId, Math.max(...written.map((e) => e.seq)));
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
/**
|
|
405
|
+
* Writes the images into the call's device at `filePath` (several: `-1`, `-2`… before the
|
|
406
|
+
* extension, {@link generateImagePaths}) with `Write`'s checks (spec §5.3): the device entry every
|
|
407
|
+
* builtin takes ({@link inToolSandbox}: the managed route and its marked device paths once
|
|
408
|
+
* activated), each path checked as `Write` checks it, and under its path lease a directory refused
|
|
409
|
+
* and an existing file replaced only when this conversation read it and it is unchanged
|
|
410
|
+
* ({@link assertReadAndUnchanged}). The images are already delivered, so a copy that cannot be made
|
|
411
|
+
* is a line of the result, not a tool error: no device, or the reason the copy stopped, after the
|
|
412
|
+
* paths written before it. A path whose extension does not match the image's media type names the
|
|
413
|
+
* type ({@link deviceEntry}). An abort still ends the call.
|
|
414
|
+
*/
|
|
415
|
+
async function copyToDevice(deps, ctx, filePath, files) {
|
|
416
|
+
const sb = deps.sandbox;
|
|
417
|
+
const conv = sandboxConversationOf(ctx);
|
|
418
|
+
if (!(await hasDevice(sb, ctx.orgId, conv)))
|
|
419
|
+
return { line: NO_DEVICE_LINE, notices: [] };
|
|
420
|
+
const targets = generateImagePaths({ file_path: filePath, n: files.length });
|
|
421
|
+
// the paths written so far (a rebuilt instance runs the copy again from the start)
|
|
422
|
+
let written = [];
|
|
423
|
+
let current = targets[0];
|
|
424
|
+
try {
|
|
425
|
+
const { notices } = await inToolSandbox(sb, ctx, async (s) => {
|
|
426
|
+
written = [];
|
|
427
|
+
for (const [i, f] of files.entries()) {
|
|
428
|
+
current = targets[i];
|
|
429
|
+
const path = checkToolWritable(current, s);
|
|
430
|
+
current = path;
|
|
431
|
+
// stat, read the existing file, write: one holder at a time per file (as `Write`)
|
|
432
|
+
await withPathLease(sb, { deviceId: s.deviceId }, path, s.signal, async (signal) => {
|
|
433
|
+
const st = await s.p.stat(s.h, path, signal);
|
|
434
|
+
if (st?.isDir)
|
|
435
|
+
throw new ToolError(isDirectoryText(path));
|
|
436
|
+
if (st !== null) {
|
|
437
|
+
const got = await s.p.readFile(s.h, path, { maxBytes: READ_MAX_BYTES, signal });
|
|
438
|
+
if (got === null)
|
|
439
|
+
throw new ToolError(vanishedText(path));
|
|
440
|
+
try {
|
|
441
|
+
await assertReadAndUnchanged(sb, ctx.conversationId, path, fileStateOf(got.data, st.size));
|
|
442
|
+
}
|
|
443
|
+
catch (e) {
|
|
444
|
+
if (!(e instanceof FileGuardError))
|
|
445
|
+
throw e;
|
|
446
|
+
if (e.reason === "not_read")
|
|
447
|
+
throw new ToolError(notReadText(path));
|
|
448
|
+
throw new ToolError(modifiedText(path));
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
await s.p.writeFile(s.h, path, f.data, signal);
|
|
452
|
+
});
|
|
453
|
+
written.push(deviceEntry(path, f.contentType));
|
|
454
|
+
}
|
|
455
|
+
});
|
|
456
|
+
return { line: `Written to the device: ${written.join(", ")}`, notices };
|
|
457
|
+
}
|
|
458
|
+
catch (e) {
|
|
459
|
+
if (ctx.signal.aborted)
|
|
460
|
+
throw e;
|
|
461
|
+
// a device's own error is not shown to the model (it may name provider internals)
|
|
462
|
+
if (!(e instanceof ToolError)) {
|
|
463
|
+
deps.log.warn("GenerateImage device copy failed", {
|
|
464
|
+
conversationId: ctx.conversationId,
|
|
465
|
+
callId: ctx.callId,
|
|
466
|
+
err: e,
|
|
467
|
+
});
|
|
468
|
+
}
|
|
469
|
+
const failed = `Not written to the device: ${e instanceof ToolError ? e.message : copyFailedText(current)}`;
|
|
470
|
+
// a partial copy says which files are there before the failure
|
|
471
|
+
return {
|
|
472
|
+
line: written.length === 0 ? failed : `Written to the device: ${written.join(", ")}\n${failed}`,
|
|
473
|
+
notices: [],
|
|
474
|
+
};
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
/**
|
|
478
|
+
* A written path as the device line names it: the path, followed by the image's media type when
|
|
479
|
+
* the path's extension is not one of that type's (`out/a.jpg (image/png)`), so the model knows
|
|
480
|
+
* what the file holds whatever it was called.
|
|
481
|
+
*/
|
|
482
|
+
export function deviceEntry(path, mediaType) {
|
|
483
|
+
const name = path.slice(path.lastIndexOf("/") + 1);
|
|
484
|
+
const dot = name.lastIndexOf(".");
|
|
485
|
+
const ext = dot > 0 ? name.slice(dot + 1).toLowerCase() : "";
|
|
486
|
+
return MEDIA_EXTENSIONS[mediaType].includes(ext) ? path : `${path} (${mediaType})`;
|
|
487
|
+
}
|
|
488
|
+
/** The extensions that name each image media type ({@link deviceEntry}). */
|
|
489
|
+
const MEDIA_EXTENSIONS = {
|
|
490
|
+
"image/png": ["png"],
|
|
491
|
+
"image/jpeg": ["jpg", "jpeg"],
|
|
492
|
+
"image/gif": ["gif"],
|
|
493
|
+
"image/webp": ["webp"],
|
|
494
|
+
};
|
|
495
|
+
/**
|
|
496
|
+
* Whether the conversation tree has a device to write to: a provider it can run on, and a device
|
|
497
|
+
* its owner has (an anonymous IM sender or a deployment without a cloud provider has none).
|
|
498
|
+
*/
|
|
499
|
+
async function hasDevice(sb, orgId, conv) {
|
|
500
|
+
if (!(await sandboxUsable(sb, orgId, conv)))
|
|
501
|
+
return false;
|
|
502
|
+
try {
|
|
503
|
+
await sb.devices.forTool(orgId, conv);
|
|
504
|
+
return true;
|
|
505
|
+
}
|
|
506
|
+
catch (e) {
|
|
507
|
+
if (e instanceof ApiError && e.code === "sandbox.unavailable")
|
|
508
|
+
return false;
|
|
509
|
+
// any other refusal (a gone or forbidden device) is reported by the copy itself
|
|
510
|
+
return true;
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
/** A byte count as the result shows it. */
|
|
514
|
+
function sizeText(bytes) {
|
|
515
|
+
if (bytes < 1024)
|
|
516
|
+
return `${bytes} B`;
|
|
517
|
+
if (bytes < 1_048_576)
|
|
518
|
+
return `${(bytes / 1024).toFixed(1)} KB`;
|
|
519
|
+
return `${(bytes / 1_048_576).toFixed(1)} MB`;
|
|
520
|
+
}
|
|
521
|
+
/** The model-visible result (spec §5.3): what was generated, where it went, the revised prompt. */
|
|
522
|
+
function resultText(prepared, stored, files, revisedPrompt, deviceLine) {
|
|
523
|
+
const n = stored.length;
|
|
524
|
+
const { width, height } = prepared.request.size;
|
|
525
|
+
const lines = [
|
|
526
|
+
`Generated ${n} ${n === 1 ? "image" : "images"} with ${prepared.ref.provider}/${prepared.ref.model} at ${width}x${height} and delivered ${n === 1 ? "it" : "them"} to the user:`,
|
|
527
|
+
...stored.map((a, i) => `- ${a.name} (artifact ${a.artifactId}, ${files[i]?.contentType ?? ""}, ${sizeText(a.size)})`),
|
|
528
|
+
];
|
|
529
|
+
if (typeof revisedPrompt === "string" && revisedPrompt !== "") {
|
|
530
|
+
lines.push(`Revised prompt: ${revisedPrompt}`);
|
|
531
|
+
}
|
|
532
|
+
if (deviceLine !== null)
|
|
533
|
+
lines.push(deviceLine);
|
|
534
|
+
return lines.join("\n");
|
|
535
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The device paths a `GenerateImage` call writes (image generation spec §5.3), shared by the tool
|
|
3
|
+
* and the command review so the review judges exactly the files the tool writes.
|
|
4
|
+
*/
|
|
5
|
+
/** `path` with `-<i>` before the extension of its last segment (or at its end without one). */
|
|
6
|
+
export declare function suffixedPath(path: string, i: number): string;
|
|
7
|
+
/**
|
|
8
|
+
* The paths a `GenerateImage` input writes into the device, in image order: none without
|
|
9
|
+
* `file_path`, `file_path` itself for one image, `-1`, `-2`… before the extension for several
|
|
10
|
+
* ({@link suffixedPath}). `n` absent or not a whole number above 1 is one image.
|
|
11
|
+
*/
|
|
12
|
+
export declare function generateImagePaths(input: unknown): string[];
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The device paths a `GenerateImage` call writes (image generation spec §5.3), shared by the tool
|
|
3
|
+
* and the command review so the review judges exactly the files the tool writes.
|
|
4
|
+
*/
|
|
5
|
+
/** `path` with `-<i>` before the extension of its last segment (or at its end without one). */
|
|
6
|
+
export function suffixedPath(path, i) {
|
|
7
|
+
const slash = path.lastIndexOf("/");
|
|
8
|
+
const dot = path.lastIndexOf(".");
|
|
9
|
+
// a dot that starts the file name (`.env`) is not an extension
|
|
10
|
+
if (dot <= slash + 1)
|
|
11
|
+
return `${path}-${i}`;
|
|
12
|
+
return `${path.slice(0, dot)}-${i}${path.slice(dot)}`;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* The paths a `GenerateImage` input writes into the device, in image order: none without
|
|
16
|
+
* `file_path`, `file_path` itself for one image, `-1`, `-2`… before the extension for several
|
|
17
|
+
* ({@link suffixedPath}). `n` absent or not a whole number above 1 is one image.
|
|
18
|
+
*/
|
|
19
|
+
export function generateImagePaths(input) {
|
|
20
|
+
const o = (input ?? {});
|
|
21
|
+
if (typeof o.file_path !== "string")
|
|
22
|
+
return [];
|
|
23
|
+
const n = typeof o.n === "number" && Number.isInteger(o.n) && o.n > 1 ? o.n : 1;
|
|
24
|
+
const path = o.file_path;
|
|
25
|
+
return n === 1 ? [path] : Array.from({ length: n }, (_, i) => suffixedPath(path, i + 1));
|
|
26
|
+
}
|
|
@@ -1,7 +1,6 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { ExtensionPointUnavailableError, MEDIA_NAME_MAX_CHARS, ToolError, } from "@capybara-hq/plugin-sdk";
|
|
1
|
+
import { MEDIA_NAME_MAX_CHARS, ToolError } from "@capybara-hq/plugin-sdk";
|
|
3
2
|
import { isValidArtifactName } from "../../../conversations/events.js";
|
|
4
|
-
import {
|
|
3
|
+
import { NO_STORAGE, NO_STORAGE_REASON, storeArtifacts } from "../artifacts.js";
|
|
5
4
|
import { checkPath, checkPathShape, clip, display, inToolSandbox, sandboxBaseTimeoutMs, unavailableWhenNoSandbox, withNotices, } from "./common.js";
|
|
6
5
|
const SPEC = {
|
|
7
6
|
name: "Deliver",
|
|
@@ -87,9 +86,6 @@ function defaultName(path) {
|
|
|
87
86
|
}
|
|
88
87
|
return isValidArtifactName(out) ? out : "artifact";
|
|
89
88
|
}
|
|
90
|
-
const NO_STORAGE = "File storage is not configured in this deployment, so files cannot be delivered; ask an administrator, or provide the result in your reply instead.";
|
|
91
|
-
/** 「工具不可用」提醒里的原因(内核在后面补句号)。 */
|
|
92
|
-
const NO_STORAGE_REASON = NO_STORAGE.slice(0, -1);
|
|
93
89
|
/** 内置工具 `Deliver`:把沙箱里的文件存进对象存储,写 `artifact_created`,用户可下载。 */
|
|
94
90
|
export function sandboxDeliverTool(deps) {
|
|
95
91
|
return {
|
|
@@ -129,50 +125,12 @@ export function sandboxDeliverTool(deps) {
|
|
|
129
125
|
return got.data;
|
|
130
126
|
});
|
|
131
127
|
const name = given ?? defaultName(path);
|
|
132
|
-
//
|
|
133
|
-
const artifactId = randomUUID();
|
|
134
|
-
const objectKey = `artifacts/${ctx.conversationId}/${artifactId}`;
|
|
128
|
+
// uploaded outside the device lock: the device is not held meanwhile
|
|
135
129
|
const contentType = contentTypeFor(name);
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
signal: ctx.signal,
|
|
141
|
-
});
|
|
142
|
-
}
|
|
143
|
-
catch (e) {
|
|
144
|
-
if ((e instanceof ApiError && e.code === "storage.unavailable") ||
|
|
145
|
-
e instanceof ExtensionPointUnavailableError) {
|
|
146
|
-
throw new ToolError(NO_STORAGE);
|
|
147
|
-
}
|
|
148
|
-
throw e;
|
|
149
|
-
}
|
|
150
|
-
try {
|
|
151
|
-
await deps.eventLog.append(ctx.conversationId, [
|
|
152
|
-
{
|
|
153
|
-
type: "artifact_created",
|
|
154
|
-
...(ctx.runId !== undefined && { runId: ctx.runId }),
|
|
155
|
-
payload: {
|
|
156
|
-
artifactId,
|
|
157
|
-
name,
|
|
158
|
-
contentType,
|
|
159
|
-
size: data.byteLength,
|
|
160
|
-
objectKey,
|
|
161
|
-
sourcePath: path,
|
|
162
|
-
callId: ctx.callId,
|
|
163
|
-
},
|
|
164
|
-
},
|
|
165
|
-
]);
|
|
166
|
-
}
|
|
167
|
-
catch (e) {
|
|
168
|
-
// 事件没写进去:对象没人引用,尽力删掉
|
|
169
|
-
await deps.storage
|
|
170
|
-
.kernel(ctx.orgId)
|
|
171
|
-
.delete(objectKey)
|
|
172
|
-
.catch(() => { });
|
|
173
|
-
throw e;
|
|
174
|
-
}
|
|
175
|
-
await deps.eventLog.publishChanged?.(ctx.conversationId, "files");
|
|
130
|
+
const [stored] = await storeArtifacts(deps, ctx, [
|
|
131
|
+
{ name, contentType, data, sourcePath: path },
|
|
132
|
+
]);
|
|
133
|
+
const artifactId = stored.artifactId;
|
|
176
134
|
const text = `Delivered ${name} (${data.byteLength} bytes, ${contentType}) to the user as artifact ${artifactId}; the user can download it from the conversation.`;
|
|
177
135
|
return {
|
|
178
136
|
content: [{ type: "text", text: withNotices(notices, text) }],
|