@capybara-hq/kernel 0.1.0-rc.50 → 0.1.0-rc.52

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/bootstrap.json +5 -5
  2. package/dist/catalog/marketplaces.service.d.ts +1 -1
  3. package/dist/config/schema.d.ts +6 -0
  4. package/dist/config/schema.js +60 -0
  5. package/dist/conversations/attachments.service.d.ts +78 -10
  6. package/dist/conversations/attachments.service.js +233 -16
  7. package/dist/conversations/events.d.ts +9 -0
  8. package/dist/conversations/events.js +26 -3
  9. package/dist/db/kernel-schema.d.ts +5 -2
  10. package/dist/evals/reconstruct.d.ts +6 -1
  11. package/dist/evals/reconstruct.js +8 -4
  12. package/dist/evals/recorded-tools.d.ts +7 -0
  13. package/dist/evals/recorded-tools.js +2 -0
  14. package/dist/infra/config/kernel-config.service.js +8 -0
  15. package/dist/media/image-header.d.ts +10 -0
  16. package/dist/media/image-header.js +87 -0
  17. package/dist/models/images.d.ts +2 -0
  18. package/dist/models/images.js +6 -4
  19. package/dist/models/purposes.d.ts +17 -57
  20. package/dist/models/purposes.js +25 -4
  21. package/dist/runtime/context/build.d.ts +73 -28
  22. package/dist/runtime/context/build.js +179 -33
  23. package/dist/runtime/model-call.js +16 -10
  24. package/dist/runtime/usage-report.d.ts +3 -2
  25. package/dist/runtime/usage-report.js +3 -2
  26. package/dist/tools/builtins/builtin-tools.d.ts +8 -1
  27. package/dist/tools/builtins/builtin-tools.js +54 -3
  28. package/dist/tools/builtins/conversation-files.d.ts +42 -0
  29. package/dist/tools/builtins/conversation-files.js +105 -0
  30. package/dist/tools/builtins/image/generate.d.ts +3 -3
  31. package/dist/tools/builtins/image/generate.js +63 -71
  32. package/dist/tools/builtins/image/size.d.ts +12 -0
  33. package/dist/tools/builtins/image/size.js +36 -0
  34. package/dist/tools/builtins/sandbox/common.d.ts +7 -0
  35. package/dist/tools/builtins/sandbox/read.d.ts +53 -2
  36. package/dist/tools/builtins/sandbox/read.js +260 -51
  37. package/dist/tools/builtins/size-text.d.ts +2 -0
  38. package/dist/tools/builtins/size-text.js +8 -0
  39. package/dist/tools/builtins/vision/read-image.d.ts +59 -0
  40. package/dist/tools/builtins/vision/read-image.js +220 -0
  41. package/dist/tools/pipeline.js +22 -3
  42. package/dist/tools/registry.d.ts +9 -1
  43. package/package.json +3 -3
  44. package/src/migrations/0163_read_attachments.sql +10 -0
@@ -16,6 +16,7 @@ import { AttachmentsService } from "../../conversations/attachments.service.js";
16
16
  import { EventLog } from "../../conversations/event-log.js";
17
17
  import { conversationAncestors } from "../../conversations/tree.js";
18
18
  import { ConversationDevices } from "../../devices/conversation-devices.js";
19
+ import { ApiError } from "../../errors.js";
19
20
  import { ExtensionHost } from "../../extensions/host.js";
20
21
  import { ExtensionPointDefaults } from "../../extensions/point-defaults.js";
21
22
  import { KernelConfigService } from "../../infra/config/kernel-config.service.js";
@@ -27,7 +28,7 @@ import { readOrgSettings } from "../../orgs/settings.service.js";
27
28
  import { PlatformActor } from "../../platform/actor.js";
28
29
  import { AgentDocs } from "../../platform/agent-docs.js";
29
30
  import { PlatformOperations } from "../../platform/registry.js";
30
- import { ProviderRegistry } from "../../runtime/providers.js";
31
+ import { ProviderListError, ProviderRegistry } from "../../runtime/providers.js";
31
32
  import { conversationTimeZone, RUN_CONTEXT_CLOCK } from "../../runtime/run-context.service.js";
32
33
  import { StepLog } from "../../runtime/step-log.js";
33
34
  import { ManagedDeviceContextRecorder, } from "../../sandbox/managed-device-context.js";
@@ -76,6 +77,21 @@ let BuiltinTools = class BuiltinTools {
76
77
  // dormant: the builtins keep the legacy route until the paired activation turns the gate on;
77
78
  // then every builtin entering a device (the skill tool too) takes the managed route
78
79
  const managed = managedSandboxDeps(managedDeviceContext, activation);
80
+ // `Read` beyond the device (vision-read design §1): files by id, the vision read with its
81
+ // hooks (as the WebFetch extraction), the stored copies and the chat model's capabilities
82
+ const vision = { purposes, eventLog, stepLog, config, log, hooks: host?.hooks };
83
+ const read = {
84
+ files: {
85
+ get db() {
86
+ return db.db;
87
+ },
88
+ attachments,
89
+ storage,
90
+ },
91
+ reads: attachments,
92
+ vision,
93
+ chatModelSeesImages: (ctx) => chatModelSeesImages(db, providers, ctx),
94
+ };
79
95
  const sandboxDeps = {
80
96
  sandbox,
81
97
  devices,
@@ -91,6 +107,7 @@ let BuiltinTools = class BuiltinTools {
91
107
  config,
92
108
  log,
93
109
  ...managed,
110
+ read,
94
111
  };
95
112
  this.tools = [
96
113
  askUserTool({ config }),
@@ -123,7 +140,7 @@ let BuiltinTools = class BuiltinTools {
123
140
  points,
124
141
  config,
125
142
  cache: webPages,
126
- extract: (ctx, page, prompt) => extractAnswer({ purposes, eventLog, stepLog, config, log, hooks: host?.hooks }, ctx, page, prompt),
143
+ extract: (ctx, page, prompt) => extractAnswer(vision, ctx, page, prompt),
127
144
  }),
128
145
  // images from the org's `image` purpose model, delivered as artifacts (image generation
129
146
  // spec §5.3); written into the device too with `file_path`
@@ -137,7 +154,7 @@ let BuiltinTools = class BuiltinTools {
137
154
  config,
138
155
  log,
139
156
  hooks: host?.hooks,
140
- db: () => db.db,
157
+ db,
141
158
  attachments,
142
159
  sandbox: sandboxDeps,
143
160
  }),
@@ -215,3 +232,37 @@ export function managedSandboxDeps(recorder, activation) {
215
232
  return {};
216
233
  return { managedDeviceContext: recorder, managedDeviceContextRequired: true };
217
234
  }
235
+ /**
236
+ * Whether "the chat model" of a `Read` call can view images (vision-read design §1.2): the model
237
+ * of the latest `model_call` of the call's run (a fallback step's model when the step fell back),
238
+ * its capabilities from the model list cache. A run with no model call yet, or a model the org can
239
+ * no longer resolve, counts as one that cannot: the vision purpose reads the image then.
240
+ */
241
+ export async function chatModelSeesImages(db, providers, ctx) {
242
+ if (ctx.runId === undefined)
243
+ return false;
244
+ const row = await db.db
245
+ .selectFrom("conversation_events")
246
+ .select("payload")
247
+ .where("conversation_id", "=", ctx.conversationId)
248
+ .where("run_id", "=", ctx.runId)
249
+ .where("type", "=", "model_call")
250
+ .orderBy("seq", "desc")
251
+ .limit(1)
252
+ .executeTakeFirst();
253
+ if (!row)
254
+ return false;
255
+ const call = row.payload;
256
+ try {
257
+ const { info } = await providers.resolve(ctx.orgId, {
258
+ provider: call.provider,
259
+ model: call.model,
260
+ });
261
+ return info.capabilities.vision;
262
+ }
263
+ catch (e) {
264
+ if (e instanceof ApiError || e instanceof ProviderListError)
265
+ return false;
266
+ throw e;
267
+ }
268
+ }
@@ -0,0 +1,42 @@
1
+ import type { AttachmentsService } from "../../conversations/attachments.service.js";
2
+ import type { KernelDb } from "../../infra/database/kernel-db.js";
3
+ import type { StorageService } from "../../storage/storage.service.js";
4
+ /** An id of the conversation's files: an attachment or an artifact (generated or delivered). */
5
+ export interface ConversationFile {
6
+ kind: "attachment" | "artifact";
7
+ id: string;
8
+ name: string;
9
+ contentType: string;
10
+ size: number;
11
+ /**
12
+ * Reads the bytes, at most `maxBytes` of them when given (the head of a larger file: an
13
+ * attachment's stream is cancelled there, an artifact is read with a range). Call it, or
14
+ * {@link discard}, exactly once: an attachment holds its stream.
15
+ */
16
+ open(opts?: {
17
+ maxBytes?: number;
18
+ }): Promise<Uint8Array>;
19
+ /** Releases the file without reading it (a refusal before the bytes are needed). */
20
+ discard(): Promise<void>;
21
+ }
22
+ export interface ConversationFileDeps {
23
+ db: Pick<KernelDb, "selectFrom">;
24
+ attachments: Pick<AttachmentsService, "openForConversation">;
25
+ storage: Pick<StorageService, "kernel">;
26
+ }
27
+ /**
28
+ * A file of the conversation by id, always inside `orgId`: an attachment bound to the
29
+ * conversation or to its root (a `chat` attachment or a `read` copy: this lookup is the model's,
30
+ * vision-read design §1.1), else an `artifact_created` event of either. Anything else (another
31
+ * conversation or org, a missing object, an id that is not a UUID) is `null`. Storage errors are
32
+ * thrown as they are. `signal` aborts the storage reads.
33
+ */
34
+ export declare function findConversationFile(deps: ConversationFileDeps, q: {
35
+ orgId: string;
36
+ conversationId: string;
37
+ rootConversationId: string;
38
+ id: string;
39
+ /** The most bytes {@link ConversationFile.open} may be asked for (an attachment's range). */
40
+ maxBytes?: number;
41
+ signal?: AbortSignal;
42
+ }): Promise<ConversationFile | null>;
@@ -0,0 +1,105 @@
1
+ import { sql } from "kysely";
2
+ /** Lower-case or upper-case UUIDs: attachment and artifact ids. */
3
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
4
+ /**
5
+ * The bytes of `body`, at most `maxBytes` (the stream is cancelled once that many are read: a
6
+ * store that ignores a range still sends no more than one chunk past it).
7
+ */
8
+ async function bytesOf(body, maxBytes) {
9
+ if (maxBytes === undefined)
10
+ return new Uint8Array(await new Response(body).arrayBuffer());
11
+ const reader = body.getReader();
12
+ const chunks = [];
13
+ let n = 0;
14
+ try {
15
+ while (n < maxBytes) {
16
+ const { done, value } = await reader.read();
17
+ if (done)
18
+ break;
19
+ chunks.push(value);
20
+ n += value.byteLength;
21
+ }
22
+ }
23
+ finally {
24
+ await reader.cancel().catch(() => { });
25
+ }
26
+ const out = new Uint8Array(Math.min(n, maxBytes));
27
+ let at = 0;
28
+ for (const c of chunks) {
29
+ const part = c.subarray(0, out.length - at);
30
+ out.set(part, at);
31
+ at += part.length;
32
+ if (at === out.length)
33
+ break;
34
+ }
35
+ return out;
36
+ }
37
+ /**
38
+ * A file of the conversation by id, always inside `orgId`: an attachment bound to the
39
+ * conversation or to its root (a `chat` attachment or a `read` copy: this lookup is the model's,
40
+ * vision-read design §1.1), else an `artifact_created` event of either. Anything else (another
41
+ * conversation or org, a missing object, an id that is not a UUID) is `null`. Storage errors are
42
+ * thrown as they are. `signal` aborts the storage reads.
43
+ */
44
+ export async function findConversationFile(deps, q) {
45
+ if (!UUID.test(q.id))
46
+ return null;
47
+ const id = q.id.toLowerCase();
48
+ const conversations = [...new Set([q.conversationId, q.rootConversationId])];
49
+ for (const conversationId of conversations) {
50
+ const opened = await deps.attachments.openForConversation(q.orgId, conversationId, id, {
51
+ purposes: ["chat", "read"],
52
+ ...(q.maxBytes !== undefined && { maxBytes: q.maxBytes }),
53
+ ...(q.signal !== undefined && { signal: q.signal }),
54
+ });
55
+ if (opened === null)
56
+ continue;
57
+ return {
58
+ kind: "attachment",
59
+ id,
60
+ name: opened.name,
61
+ contentType: opened.contentType,
62
+ size: opened.size,
63
+ // the one storage read of the lookup: its stream is read by open() or cancelled by discard()
64
+ open: (opts) => bytesOf(opened.body, opts?.maxBytes),
65
+ discard: () => opened.body.cancel().catch(() => { }),
66
+ };
67
+ }
68
+ const row = await deps.db
69
+ .selectFrom("conversation_events as e")
70
+ .innerJoin("conversations as c", "c.id", "e.conversation_id")
71
+ .select("e.payload")
72
+ .where("c.org_id", "=", q.orgId)
73
+ .where("e.conversation_id", "in", conversations)
74
+ .where("e.type", "=", "artifact_created")
75
+ .where(sql `e.payload->>'artifactId'`, "=", id)
76
+ .limit(1)
77
+ .executeTakeFirst();
78
+ if (!row)
79
+ return null;
80
+ const a = row.payload;
81
+ const store = deps.storage.kernel(q.orgId);
82
+ const head = await store.head(a.objectKey);
83
+ if (head === null)
84
+ return null;
85
+ return {
86
+ kind: "artifact",
87
+ id,
88
+ name: a.name,
89
+ contentType: a.contentType,
90
+ size: head.size,
91
+ async open(opts) {
92
+ const max = opts?.maxBytes;
93
+ // only a larger object is ranged (a range on an empty object is unsatisfiable)
94
+ const ranged = max !== undefined && head.size > max;
95
+ const got = await store.get(a.objectKey, {
96
+ ...(q.signal !== undefined && { signal: q.signal }),
97
+ ...(ranged && { range: { start: 0, end: max - 1 } }),
98
+ });
99
+ if (got === null)
100
+ throw new Error(`artifact ${id} is no longer available`);
101
+ return bytesOf(got.body, max);
102
+ },
103
+ discard: async () => { },
104
+ };
105
+ }
@@ -1,8 +1,8 @@
1
1
  import { type ImageMediaType, type Logger, type ToolSpec } from "@capybara-hq/plugin-sdk";
2
2
  import type { AttachmentsService } from "../../../conversations/attachments.service.js";
3
3
  import type { EventLog } from "../../../conversations/event-log.js";
4
- import type { KernelSchemaDb } from "../../../db/kernel-schema.js";
5
4
  import type { KernelConfigService } from "../../../infra/config/kernel-config.service.js";
5
+ import type { KernelDb } from "../../../infra/database/kernel-db.js";
6
6
  import { type ImageInputCaps } from "../../../models/image-usable.js";
7
7
  import { type ModelImages } from "../../../models/images.js";
8
8
  import type { ModelPurposesService } from "../../../models/purposes.js";
@@ -13,7 +13,7 @@ import type { StorageService } from "../../../storage/storage.service.js";
13
13
  import type { BuiltinTool } from "../../registry.js";
14
14
  import { type SandboxToolDeps } from "../sandbox/common.js";
15
15
  /** The listed spec for an org whose image model accepts `caps` (pure; `n` and references drop or cap). */
16
- export declare function generateImageSpec(caps: ImageInputCaps): ToolSpec;
16
+ export declare function generateImageSpec(caps: ImageInputCaps, standardPixels: number): ToolSpec;
17
17
  export declare const GENERATE_IMAGE_SPEC: ToolSpec;
18
18
  /** Why the tool is not listed: the org's `image` purpose has no usable model (spec §5.3). */
19
19
  export declare const NO_IMAGE_MODEL_REASON = "No image model is configured for this organization";
@@ -37,7 +37,7 @@ export interface GenerateImageDeps {
37
37
  /** Extension hooks (absent: none fire). */
38
38
  hooks?: HookRunner | undefined;
39
39
  /** The artifact lookup of `reference_images`. */
40
- db: () => KernelSchemaDb;
40
+ db: Pick<KernelDb, "selectFrom">;
41
41
  attachments: Pick<AttachmentsService, "openForConversation">;
42
42
  /** The device copy of `file_path` (the sandbox tools' own dependencies). */
43
43
  sandbox: SandboxToolDeps;
@@ -1,5 +1,4 @@
1
1
  import { IMAGE_ASPECT_RATIOS, IMAGE_MEDIA_TYPES, isModelError, MEDIA_LIMITS, ToolError, } from "@capybara-hq/plugin-sdk";
2
- import { sql } from "kysely";
3
2
  import { isValidArtifactName } from "../../../conversations/events.js";
4
3
  import { ApiError } from "../../../errors.js";
5
4
  import { IMAGE_PURPOSE, imagePurposeState, } from "../../../models/image-usable.js";
@@ -8,10 +7,13 @@ import { hookDeniedAudit, hookDeniedEvent, hookScope, } from "../../../runtime/h
8
7
  import { appendCounted } from "../../../runtime/model-call.js";
9
8
  import { ProviderListError } from "../../../runtime/providers.js";
10
9
  import { NO_STORAGE, NO_STORAGE_REASON, REPEAT_CLAUSE, storeArtifacts, } from "../artifacts.js";
10
+ import { findConversationFile } from "../conversation-files.js";
11
11
  import { checkFilePathShape, checkToolWritable, clip, display, inToolSandbox, sandboxConversationOf, sandboxUsable, withNotices, withPathLease, } from "../sandbox/common.js";
12
12
  import { assertReadAndUnchanged, FileGuardError, fileStateOf } from "../sandbox/file-state.js";
13
13
  import { READ_MAX_BYTES } from "../sandbox/read.js";
14
+ import { sizeText } from "../size-text.js";
14
15
  import { generateImagePaths } from "./paths.js";
16
+ import { pickStandardSize } from "./size.js";
15
17
  /** The model purpose the tool calls (image generation spec §5.4; no fallback). */
16
18
  const PURPOSE = IMAGE_PURPOSE;
17
19
  /** The most reference images one call names (the schema's `maxItems`). */
@@ -21,10 +23,13 @@ const MAX_IMAGES = 4;
21
23
  /** The longest base name (`name`). */
22
24
  const NAME_MAX_CHARS = 100;
23
25
  /** The listed spec for an org whose image model accepts `caps` (pure; `n` and references drop or cap). */
24
- export function generateImageSpec(caps) {
26
+ export function generateImageSpec(caps, standardPixels) {
25
27
  const base = GENERATE_IMAGE_SPEC;
26
- const { n, reference_images, ...rest } = base.inputSchema.properties;
27
- const properties = { ...rest };
28
+ const { n, reference_images, resolution, ...rest } = base.inputSchema.properties;
29
+ const properties = {
30
+ ...rest,
31
+ resolution: { ...resolution, description: resolutionDescription(standardPixels) },
32
+ };
28
33
  if (caps.maxImages > 1)
29
34
  properties.n = { ...n, maximum: caps.maxImages };
30
35
  if (caps.maxReferenceImages > 0) {
@@ -45,7 +50,9 @@ export function generateImageSpec(caps) {
45
50
  * The description sentence about reference images (spelled out in the description below); dropped
46
51
  * with the `reference_images` field. `generateImageSpec` fails loudly if the two drift apart.
47
52
  */
48
- const REFERENCE_SENTENCE = "Optionally pass reference images (attachment or earlier generated image ids) to guide the result. ";
53
+ const REFERENCE_SENTENCE = "Pass reference images (ids of images in this conversation) to keep a subject or style consistent with them, or to edit one. ";
54
+ /** The `resolution` description with the configured target area in megapixels. */
55
+ const resolutionDescription = (standardPixels) => `standard: the size closest to about ${(standardPixels / 1_000_000).toFixed(1)} megapixels for this shape; high: the model's largest size for this shape. Default: standard.`;
49
56
  export const GENERATE_IMAGE_SPEC = {
50
57
  name: "GenerateImage",
51
58
  // Display only (the tool row; not in the fingerprint, never sent to the model).
@@ -54,7 +61,7 @@ export const GENERATE_IMAGE_SPEC = {
54
61
  "the user in the conversation. Write a specific prompt: subject, composition, style, lighting, " +
55
62
  "any text that must appear. " +
56
63
  // REFERENCE_SENTENCE, spelled out: the tool-description check reads string literals only
57
- "Optionally pass reference images (attachment or earlier generated image ids) to guide the result. " +
64
+ "Pass reference images (ids of images in this conversation) to keep a subject or style consistent with them, or to edit one. " +
58
65
  "Each call costs money: generate only what the user asked for.",
59
66
  inputSchema: {
60
67
  type: "object",
@@ -67,7 +74,13 @@ export const GENERATE_IMAGE_SPEC = {
67
74
  aspect_ratio: {
68
75
  type: "string",
69
76
  enum: [...IMAGE_ASPECT_RATIOS],
70
- description: "Shape of the images; the closest size the model supports is used. Default: the model's default size.",
77
+ description: "Shape of the images; the closest size the model supports is used. Default: the shape of the model's default size.",
78
+ },
79
+ resolution: {
80
+ type: "string",
81
+ enum: ["standard", "high"],
82
+ // the listed spec replaces this with the configured megapixels (generateImageSpec)
83
+ description: "standard: a mid-sized image for this shape; high: the model's largest size for this shape. Default: standard.",
71
84
  },
72
85
  n: {
73
86
  type: "integer",
@@ -79,7 +92,7 @@ export const GENERATE_IMAGE_SPEC = {
79
92
  type: "array",
80
93
  maxItems: MAX_REFERENCES,
81
94
  items: { type: "string", minLength: 1 },
82
- description: "Ids of images that guide the result: attachment ids of this conversation, or artifact ids of images generated earlier in it.",
95
+ description: "Ids of images in this conversation that guide the result: attachment ids or artifact ids (generated or delivered images).",
83
96
  },
84
97
  name: {
85
98
  type: "string",
@@ -108,7 +121,7 @@ const refusedText = (message) => `The image model refused this prompt: ${message
108
121
  const failedText = (message) => `Image generation failed: ${message}. Retry once, or continue without the image.`;
109
122
  /** A refused argument (the request building's text names it and the allowed values). */
110
123
  const invalidText = (message) => `${message}; fix the argument and retry.`;
111
- 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.`;
124
+ const unknownReferenceText = (k) => `reference_images[${k}] is not an image attachment or artifact of this conversation; pass the id of one.`;
112
125
  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.`;
113
126
  const BAD_NAME = "name must not contain control characters, / or \\; pass a plain base name such as poster.";
114
127
  const BLANK_NAME = 'name must not be blank; pass a short file name such as "poster", or omit it.';
@@ -125,8 +138,6 @@ const modifiedText = (path) => `${clip(path, 200)} has changed since this conver
125
138
  const vanishedText = (path) => `${clip(path, 200)} disappeared while it was being written; retry the call.`;
126
139
  /** The device line of a call whose conversation has no device to write to. */
127
140
  export const NO_DEVICE_LINE = "Not written to the device: this conversation has no device.";
128
- /** Lower-case UUIDs: attachment and artifact ids. */
129
- const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
130
141
  /** The file extension of each image media type. */
131
142
  const EXTENSIONS = {
132
143
  "image/png": "png",
@@ -160,7 +171,9 @@ export function generateImageTool(deps) {
160
171
  // the counts the org's image model accepts (on a race to unusable: the static spec)
161
172
  specFor: async (scope) => {
162
173
  const state = await imagePurposeState(deps, scope.orgId, scope.memo);
163
- return state.usable === "usable" ? generateImageSpec(state) : GENERATE_IMAGE_SPEC;
174
+ return state.usable === "usable"
175
+ ? generateImageSpec(state, deps.config.get().models.imageStandardPixels)
176
+ : GENERATE_IMAGE_SPEC;
164
177
  },
165
178
  timeoutMs: () => deps.config.get().models.imageTimeoutMs + 60_000,
166
179
  async run(raw, ctx) {
@@ -181,6 +194,13 @@ export function generateImageTool(deps) {
181
194
  ...(input.n !== undefined && { n: input.n }),
182
195
  };
183
196
  // the cheap checks (prompt, count, size, the model) before any reference is read
197
+ // the size of the tool: the kernel's standard size for the shape, or the largest (spec §3.3)
198
+ const standardPixels = deps.config.get().models.imageStandardPixels;
199
+ call.chooseSize = (info) => pickStandardSize(info, {
200
+ aspectRatio: input.aspect_ratio,
201
+ resolution: input.resolution ?? "standard",
202
+ standardPixels,
203
+ });
184
204
  let prepared = await prepare(deps, ctx, call);
185
205
  const refs = input.reference_images ?? [];
186
206
  if (refs.length > prepared.info.maxReferenceImages) {
@@ -265,66 +285,42 @@ function toolErrorOf(e) {
265
285
  return null;
266
286
  }
267
287
  /**
268
- * Reads the reference images as bytes, each an id of the conversation: an attachment of the
269
- * conversation whose device the call uses (a sub-agent: its root's, as `FetchAttachment`
270
- * resolves), else an `artifact_created` of the calling conversation or its root. Anything else
271
- * names its index; a file that is not an image within `MEDIA_LIMITS.imageBytes` is refused before
272
- * it is read.
288
+ * Reads the reference images as bytes, each an id of the conversation: an attachment or an
289
+ * `artifact_created` of the calling conversation or its root ({@link findConversationFile}).
290
+ * Anything else names its index; a file that is not an image within `MEDIA_LIMITS.imageBytes` is
291
+ * refused before it is read.
273
292
  */
274
293
  async function resolveReferences(deps, ctx, ids) {
275
294
  const root = sandboxConversationOf(ctx);
276
295
  const out = [];
277
296
  for (const [k, id] of ids.entries()) {
278
- if (!UUID.test(id))
279
- throw new ToolError(unknownReferenceText(k));
280
- const found = await openReference(deps, ctx, root, id.toLowerCase());
281
- if (found === null)
282
- throw new ToolError(unknownReferenceText(k));
283
- const mediaType = found.contentType.split(";")[0]?.trim().toLowerCase() ?? "";
284
- if (!IMAGE_MEDIA_TYPES.includes(mediaType) ||
285
- found.size > MEDIA_LIMITS.imageBytes) {
286
- await found.body.cancel().catch(() => { });
287
- throw new ToolError(badReferenceText(k));
297
+ try {
298
+ const found = await findConversationFile({ db: deps.db, attachments: deps.attachments, storage: deps.storage }, { orgId: ctx.orgId, conversationId: ctx.conversationId, rootConversationId: root, id });
299
+ if (found === null)
300
+ throw new ToolError(unknownReferenceText(k));
301
+ const mediaType = found.contentType.split(";")[0]?.trim().toLowerCase() ?? "";
302
+ if (!IMAGE_MEDIA_TYPES.includes(mediaType) ||
303
+ found.size > MEDIA_LIMITS.imageBytes) {
304
+ await found.discard();
305
+ throw new ToolError(badReferenceText(k));
306
+ }
307
+ const bytes = await found.open();
308
+ if (bytes.byteLength > MEDIA_LIMITS.imageBytes)
309
+ throw new ToolError(badReferenceText(k));
310
+ out.push({
311
+ mediaType: mediaType,
312
+ data: Buffer.from(bytes).toString("base64"),
313
+ });
314
+ }
315
+ catch (e) {
316
+ if (e instanceof ApiError && e.code === "storage.unavailable") {
317
+ throw new ToolError(NO_STORAGE);
318
+ }
319
+ throw e;
288
320
  }
289
- const bytes = new Uint8Array(await new Response(found.body).arrayBuffer());
290
- if (bytes.byteLength > MEDIA_LIMITS.imageBytes)
291
- throw new ToolError(badReferenceText(k));
292
- out.push({
293
- mediaType: mediaType,
294
- data: Buffer.from(bytes).toString("base64"),
295
- });
296
321
  }
297
322
  return out;
298
323
  }
299
- /** One reference by id: its declared type and size and its bytes, or null when it is not one. */
300
- async function openReference(deps, ctx, root, id) {
301
- try {
302
- const attachment = await deps.attachments.openForConversation(ctx.orgId, root, id);
303
- if (attachment !== null)
304
- return attachment;
305
- const row = await deps
306
- .db()
307
- .selectFrom("conversation_events")
308
- .select("payload")
309
- .where("conversation_id", "in", [...new Set([ctx.conversationId, root])])
310
- .where("type", "=", "artifact_created")
311
- .where(sql `payload->>'artifactId'`, "=", id)
312
- .limit(1)
313
- .executeTakeFirst();
314
- if (!row)
315
- return null;
316
- const a = row.payload;
317
- const got = await deps.storage.kernel(ctx.orgId).get(a.objectKey);
318
- if (got === null)
319
- return null;
320
- return { contentType: a.contentType, size: got.head.size, body: got.body };
321
- }
322
- catch (e) {
323
- if (e instanceof ApiError && e.code === "storage.unavailable")
324
- throw new ToolError(NO_STORAGE);
325
- throw e;
326
- }
327
- }
328
324
  /**
329
325
  * Runs the prepared call (the hooks fire for a `chat` or `subagent` conversation only). A policy
330
326
  * denial is recorded (`hook_denied` with its audit row) and becomes the denial tool error.
@@ -556,14 +552,6 @@ async function hasDevice(sb, orgId, conv) {
556
552
  return true;
557
553
  }
558
554
  }
559
- /** A byte count as the result shows it. */
560
- function sizeText(bytes) {
561
- if (bytes < 1024)
562
- return `${bytes} B`;
563
- if (bytes < 1_048_576)
564
- return `${(bytes / 1024).toFixed(1)} KB`;
565
- return `${(bytes / 1_048_576).toFixed(1)} MB`;
566
- }
567
555
  /** The model-visible result (spec §5.3): what was generated, delivered or repeated, billing, the device copy. */
568
556
  function resultText(prepared, stored, files, revisedPrompt, deviceLine) {
569
557
  const n = stored.length;
@@ -585,6 +573,10 @@ function resultText(prepared, stored, files, revisedPrompt, deviceLine) {
585
573
  if (typeof revisedPrompt === "string" && revisedPrompt !== "") {
586
574
  lines.push(`Revised prompt: ${revisedPrompt}`);
587
575
  }
576
+ const first = stored[0];
577
+ if (first !== undefined) {
578
+ lines.push(`The images are not shown to you; Read with file_id ${first.repeatOf?.artifactId ?? first.artifactId} returns one.`);
579
+ }
588
580
  if (deviceLine !== null)
589
581
  lines.push(deviceLine);
590
582
  return lines.join("\n");
@@ -0,0 +1,12 @@
1
+ import type { ImageAspectRatio, ImageSize, ModelImageGenerationInfo } from "@capybara-hq/plugin-sdk";
2
+ /**
3
+ * The output size `GenerateImage` asks for (vision-read spec §3.3). The shape is `aspectRatio`,
4
+ * or the ratio of the model's default size; the candidates are the sizes of the closest shape.
5
+ * `standard` takes the candidate whose area is closest to `standardPixels` (a tie: the smaller
6
+ * one); `high` takes the largest candidate. A model with one size gives that size.
7
+ */
8
+ export declare function pickStandardSize(info: ModelImageGenerationInfo, q: {
9
+ aspectRatio?: ImageAspectRatio | undefined;
10
+ resolution: "standard" | "high";
11
+ standardPixels: number;
12
+ }): ImageSize;
@@ -0,0 +1,36 @@
1
+ /** Log-ratio differences closer than this are the same shape. */
2
+ const SHAPE_EPSILON = 1e-9;
3
+ const area = (s) => s.width * s.height;
4
+ /**
5
+ * The output size `GenerateImage` asks for (vision-read spec §3.3). The shape is `aspectRatio`,
6
+ * or the ratio of the model's default size; the candidates are the sizes of the closest shape.
7
+ * `standard` takes the candidate whose area is closest to `standardPixels` (a tie: the smaller
8
+ * one); `high` takes the largest candidate. A model with one size gives that size.
9
+ */
10
+ export function pickStandardSize(info, q) {
11
+ let target;
12
+ if (q.aspectRatio !== undefined) {
13
+ const [rw, rh] = q.aspectRatio.split(":").map(Number);
14
+ target = Math.log(rw / rh);
15
+ }
16
+ else {
17
+ target = Math.log(info.defaultSize.width / info.defaultSize.height);
18
+ }
19
+ const diff = (s) => Math.abs(Math.log(s.width / s.height) - target);
20
+ const best = Math.min(...info.sizes.map(diff));
21
+ const candidates = info.sizes.filter((s) => diff(s) - best <= SHAPE_EPSILON);
22
+ let pick = candidates[0] ?? info.defaultSize;
23
+ for (const s of candidates) {
24
+ if (q.resolution === "high") {
25
+ if (area(s) > area(pick))
26
+ pick = s;
27
+ }
28
+ else {
29
+ const d = Math.abs(area(s) - q.standardPixels);
30
+ const pd = Math.abs(area(pick) - q.standardPixels);
31
+ if (d < pd || (d === pd && area(s) < area(pick)))
32
+ pick = s;
33
+ }
34
+ }
35
+ return pick;
36
+ }
@@ -15,6 +15,7 @@ import type { HeldDeviceContextEvidence } from "../../../sandbox/permission-cont
15
15
  import { type HeldProvider, type SandboxService } from "../../../sandbox/sandbox.service.js";
16
16
  import type { StorageService } from "../../../storage/storage.service.js";
17
17
  import type { BuiltinCallContext, ToolListingScope } from "../../registry.js";
18
+ import type { ReadFileDeps } from "./read.js";
18
19
  /** 沙箱工具的依赖(都按调用时取,多副本下无进程内状态)。 */
19
20
  export interface SandboxToolDeps {
20
21
  /**
@@ -71,6 +72,12 @@ export interface SandboxToolDeps {
71
72
  * {@link managedDeviceContext} and refuses before entering without it.
72
73
  */
73
74
  managedDeviceContextRequired?: boolean;
75
+ /**
76
+ * `Read` beyond the device (vision-read design §1): reads by `file_id`, images shown or read by
77
+ * the vision purpose, their stored copies. Absent in test stubs: `Read` then reads the device
78
+ * only, and an image is reported as a binary file.
79
+ */
80
+ read?: ReadFileDeps;
74
81
  }
75
82
  /**
76
83
  * The sandbox a callback gets: the instance handle, the provider (every `exec` carries the
@@ -1,8 +1,59 @@
1
- import type { BuiltinTool } from "../../registry.js";
1
+ import type { AttachmentsService } from "../../../conversations/attachments.service.js";
2
+ import type { BuiltinCallContext, BuiltinTool } from "../../registry.js";
3
+ import { type ConversationFileDeps } from "../conversation-files.js";
4
+ import { type VisionReadDeps } from "../vision/read-image.js";
2
5
  import { type SandboxToolDeps } from "./common.js";
3
6
  /** 最多读出的字节数(更大的文件只读开头,并说明用 Bash 读其余部分)。 */
4
7
  export declare const READ_MAX_BYTES: number;
8
+ /** The `Read` description (vision-read design §1.5; verbatim). */
9
+ export declare const READ_DESCRIPTION: string;
10
+ /** Neither or both of `file_path` and `file_id` (spec §1.1). */
11
+ export declare const READ_ONE_SOURCE_TEXT = "Pass exactly one of file_path (a path on the device) and file_id (an attachment or artifact id).";
12
+ /** A `file_path` read without a usable device (spec §1.1; verbatim). */
13
+ export declare const READ_NO_DEVICE_TEXT = "This agent has no device; pass file_id to read an attachment or artifact.";
14
+ /** A `file_id` that is no file of this conversation or its root. */
15
+ export declare const unknownFileIdText: (id: string) => string;
16
+ /** A `file_id` read in a deployment without an object store. */
17
+ export declare const READ_NO_STORAGE_TEXT = "File storage is not configured in this deployment, so file_id cannot be read; pass file_path to read a file on the device.";
18
+ /** An image over `MEDIA_LIMITS.imageBytes` (spec §1.2; verbatim). */
19
+ export declare const tooLargeText: (name: string, size: number) => string;
20
+ /** A PDF (sniffed `%PDF-`; spec §1.5; verbatim). */
21
+ export declare const pdfText: (size: number) => string;
22
+ /** The first line of an image result (spec §1.2; verbatim). */
23
+ export declare const readImageText: (name: string, mediaType: string, size: number, dims: {
24
+ width?: number;
25
+ height?: number;
26
+ }, attachmentId: string) => string;
27
+ /** The fallback answer paragraph (spec §1.2; verbatim). */
28
+ export declare const fallbackAnswerText: (provider: string, model: string, answer: string) => string;
29
+ /** An image read but not stored: the per-conversation cap, or no object store. */
30
+ export declare const notStoredText: (name: string, mediaType: string, size: number, dims: {
31
+ width?: number;
32
+ height?: number;
33
+ }, reason: "cap" | "storage") => string;
5
34
  /** 按行编号显示 `[offset, offset + limit)`(1 起),结尾注明还有多少行。 */
6
35
  export declare function numberLines(text: string, offset: number, limit: number): string;
7
- /** 内置工具 `Read`:读沙箱里的文本文件(只读,组织策略为 ask 时也不审批)。 */
36
+ /**
37
+ * What `Read` needs beyond the device (vision-read design §1): the conversation's files by id
38
+ * ({@link findConversationFile}), the stored copy of an image (`storeRead`), the vision read for a
39
+ * model that cannot view images, and whether the model of the step that issued the call can.
40
+ */
41
+ export interface ReadFileDeps {
42
+ files: ConversationFileDeps;
43
+ reads: Pick<AttachmentsService, "storeRead">;
44
+ vision: VisionReadDeps;
45
+ /**
46
+ * Whether "the chat model" can view images: the model of the latest `model_call` of the call's
47
+ * run, its capabilities from the model list cache.
48
+ */
49
+ chatModelSeesImages(ctx: BuiltinCallContext): Promise<boolean>;
50
+ }
51
+ /**
52
+ * The builtin `Read` (read-only; never asks, even when the org's sandbox tool policy is ask): a
53
+ * text file with line numbers, an image shown to the model (or read by the `vision` purpose for a
54
+ * model that cannot view images) and stored with the conversation, a PDF or other binary file
55
+ * named only. `file_path` reads the device; `file_id` an attachment or artifact of the
56
+ * conversation or its root, never entering the device. Listed when a device is usable or (with
57
+ * `deps.read`) an object store is there.
58
+ */
8
59
  export declare function sandboxReadTool(deps: SandboxToolDeps): BuiltinTool;