@capybara-hq/kernel 0.1.0-rc.90 → 0.1.0-rc.91

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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;
@@ -53,11 +53,13 @@ export interface RenderedResult {
53
53
  isError: boolean;
54
54
  }
55
55
  /**
56
- * 管线第 5 阶段(渲染):文本块按行拼接;图片 → `[image <mimeType>, <n> bytes]`(M3 不把图片回传模型);
57
- * `resource_link` → `[resource <uri>]`;未知块 → `[unsupported content <type>]`。
58
- * 畸形结果(不是对象、content 不是数组)给出说明并标为错误,不抛错(Review Focus 5)。
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
  */
@@ -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
- * 管线第 5 阶段(渲染):文本块按行拼接;图片 → `[image <mimeType>, <n> bytes]`(M3 不把图片回传模型);
155
- * `resource_link` → `[resource <uri>]`;未知块 → `[unsupported content <type>]`。
156
- * 畸形结果(不是对象、content 不是数组)给出说明并标为错误,不抛错(Review Focus 5)。
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 (type === "image" && typeof b.data === "string") {
173
+ else if (isToolImageBlock(block) && typeof b.data === "string") {
176
174
  const mime = typeof b.mimeType === "string" ? b.mimeType : "unknown";
177
- parts.push(`[image ${mime}, ${base64Bytes(b.data)} bytes]`);
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}]`);
@@ -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`,工具全部发送)
@@ -12,6 +12,7 @@ import { Inject, Injectable, Optional } from "@nestjs/common";
12
12
  import { sql } from "kysely";
13
13
  import { backgroundMaxSeconds } from "../background/launch.js";
14
14
  import { ConversationApprovalProfile } from "../conversations/approval-profile.js";
15
+ import { AttachmentsService } from "../conversations/attachments.service.js";
15
16
  import { EventLog } from "../conversations/event-log.js";
16
17
  import { COMMAND_ASK_MAX_CHARS, COMMAND_ASK_TEXT_MAX_CHARS, ToolViewSchema, } from "../conversations/events.js";
17
18
  import { ConversationDevices } from "../devices/conversation-devices.js";
@@ -74,6 +75,7 @@ import { QuestionsService, } from "./questions.service.js";
74
75
  import { redactDeep, redactorFor } from "./redact.js";
75
76
  import { ToolRegistry, } from "./registry.js";
76
77
  import { runResourceTool } from "./resources.js";
78
+ import { storeResultImages } from "./result-images.js";
77
79
  import { ToolAskReview } from "./tool-review.js";
78
80
  import { validateInput } from "./validate.js";
79
81
  // ---- 模型可见文案(英文) ----
@@ -413,11 +415,12 @@ function withNotes(result, notes) {
413
415
  };
414
416
  }
415
417
  /** A network ask's kept display fields, written with its result when the ask settles. */
416
- const keptExtras = (kept) => ({
418
+ export const keptExtras = (kept) => ({
417
419
  ...(kept?.outputId !== undefined && { outputId: kept.outputId }),
418
420
  ...(kept?.contentTypes !== undefined && { contentTypes: kept.contentTypes }),
419
421
  ...(kept?.display !== undefined && { display: kept.display }),
420
422
  ...(kept?.view !== undefined && { view: kept.view }),
423
+ ...(kept?.media !== undefined && { media: kept.media }),
421
424
  });
422
425
  function withBlocked(outcome, scope) {
423
426
  if (outcome.kind === "connection_required")
@@ -574,6 +577,7 @@ let ToolPipeline = class ToolPipeline {
574
577
  sandboxes;
575
578
  approvalProfile;
576
579
  toolReview;
580
+ resultImages;
577
581
  decide;
578
582
  deps;
579
583
  constructor(kdb, eventLog,
@@ -597,7 +601,12 @@ let ToolPipeline = class ToolPipeline {
597
601
  */
598
602
  approvalProfile,
599
603
  /** The review model's judgment of an ask under Approve for me (R3); absent: every ask asks. */
600
- toolReview) {
604
+ toolReview,
605
+ /**
606
+ * Stores the images a tool result carries as `read` copies of the calling conversation (tool
607
+ * result images design §2); absent (hand-built pipelines): images are named as not stored.
608
+ */
609
+ resultImages) {
601
610
  this.config = config;
602
611
  this.txHost = txHost;
603
612
  this.permissionAuthority = permissionAuthority;
@@ -607,6 +616,7 @@ let ToolPipeline = class ToolPipeline {
607
616
  this.sandboxes = sandboxes;
608
617
  this.approvalProfile = approvalProfile;
609
618
  this.toolReview = toolReview;
619
+ this.resultImages = resultImages;
610
620
  this.deps = {
611
621
  // the builtins that enter a device on the managed operation route (common.ts
612
622
  // `inToolSandbox`, `inSandboxPreparation`): their review is the permission review, whose
@@ -1272,8 +1282,17 @@ let ToolPipeline = class ToolPipeline {
1272
1282
  ...(outcome.review !== undefined && { review: outcome.review }),
1273
1283
  };
1274
1284
  }
1285
+ // the images of the result (any tool): stored as `read` copies of the calling conversation,
1286
+ // named in the text and in `tool_result.media`, so a model with vision sees them after the
1287
+ // step's results and the person sees them on the call's row (tool result images design §2)
1288
+ const images = outcome.kind === "result"
1289
+ ? await storeResultImages(outcome.result, tool.key, this.storeResultImage(ctx), (err) => this.deps.log.warn("cannot store an image of a tool result", {
1290
+ toolKey: tool.key,
1291
+ error: err instanceof Error ? err.message : String(err),
1292
+ }), ctx.signal)
1293
+ : undefined;
1275
1294
  const rendered = outcome.kind === "result"
1276
- ? renderResult(outcome.result)
1295
+ ? renderResult(outcome.result, images?.texts)
1277
1296
  : { text: outcome.message, contentTypes: [], isError: true };
1278
1297
  // the tools a builtin (ToolSearch) reports as loaded: only keys available in this step and not
1279
1298
  // builtin, written to tool_result (the log is the source of truth)
@@ -1282,9 +1301,11 @@ let ToolPipeline = class ToolPipeline {
1282
1301
  : [];
1283
1302
  // the images the builtin Read stored for the call (vision-read design §1.2): builtins only,
1284
1303
  // so a plugin can never name an attachment for request building
1285
- const media = outcome.kind === "result" && tool.source.kind === "builtin"
1304
+ const builtinMedia = outcome.kind === "result" && tool.source.kind === "builtin"
1286
1305
  ? mediaFrom(outcome.result)
1287
1306
  : undefined;
1307
+ const allMedia = [...(builtinMedia ?? []), ...(images?.media ?? [])];
1308
+ const media = allMedia.length > 0 ? allMedia : undefined;
1288
1309
  // 显示摘要:只认插件 / 内置工具与内核的 resources 工具给的(连接器结果来自外部服务,不采信),
1289
1310
  // 校验不过就丢弃并告警
1290
1311
  const display = outcome.kind === "result" && (tool.source.kind !== "connector" || tool.source.resources)
@@ -1372,6 +1393,7 @@ let ToolPipeline = class ToolPipeline {
1372
1393
  ...(rendered.contentTypes.length > 0 && { contentTypes: rendered.contentTypes }),
1373
1394
  ...(display !== undefined && { display }),
1374
1395
  ...(view !== undefined && { view }),
1396
+ ...(media !== undefined && { media }),
1375
1397
  ...(review !== undefined && { review }),
1376
1398
  // carried into the kept result so a resumed run writes the event too (it was written
1377
1399
  // with `network_blocked` below when the ask was created)
@@ -2361,6 +2383,17 @@ let ToolPipeline = class ToolPipeline {
2361
2383
  },
2362
2384
  ]);
2363
2385
  }
2386
+ /**
2387
+ * How a call's result images are stored: a `read` copy bound to the calling conversation (a
2388
+ * sub-agent's own, never its root), owned by the run's trigger account; absent without the
2389
+ * attachments service.
2390
+ */
2391
+ storeResultImage(ctx) {
2392
+ const attachments = this.resultImages;
2393
+ if (attachments === undefined)
2394
+ return undefined;
2395
+ return (file) => attachments.storeRead(ctx.orgId, ctx.conversationId, ctx.accountId || null, file);
2396
+ }
2364
2397
  /**
2365
2398
  * 发出本步调用的请求里带了完整定义的工具 key:本步最后一次尝试的 `model_call.request.tools`
2366
2399
  * (`assistant_message` 来自最后一次尝试)。该请求不在 ToolSearch 模式(没有 `catalog`,工具全部发送)
@@ -3099,6 +3132,8 @@ ToolPipeline = __decorate([
3099
3132
  __param(26, Optional()),
3100
3133
  __param(26, Inject(ConversationApprovalProfile)),
3101
3134
  __param(27, Optional()),
3102
- __param(27, Inject(ToolAskReview))
3135
+ __param(27, Inject(ToolAskReview)),
3136
+ __param(28, Optional()),
3137
+ __param(28, Inject(AttachmentsService))
3103
3138
  ], ToolPipeline);
3104
3139
  export { ToolPipeline };
@@ -0,0 +1,91 @@
1
+ import type { ToolResultMedia } from "./registry.js";
2
+ /**
3
+ * Images in tool results (tool result images design §2): the pipeline stores every image block a
4
+ * tool returns as a `read` copy of the calling conversation and names it in `tool_result.media`,
5
+ * so request building shows it to a model with vision after the step's tool results, exactly as
6
+ * an image the builtin `Read` read. The tool never names an attachment: the kernel stores the
7
+ * bytes it was given and records the ids itself.
8
+ */
9
+ /** The most image blocks of one tool result that are stored; the rest are named as not stored. */
10
+ export declare const RESULT_IMAGES_MAX = 10;
11
+ /**
12
+ * The most pixels an image from a tool result may have: an external server can send a small,
13
+ * highly compressible file that decodes to gigabytes. The same bound as the kernel's thumbnails
14
+ * (`THUMBNAIL_MAX_INPUT_PIXELS`).
15
+ */
16
+ export declare const RESULT_IMAGE_MAX_PIXELS = 40000000;
17
+ /**
18
+ * Stores one image as a `read` copy of the calling conversation (`AttachmentsService.storeRead`
19
+ * bound to it): the copy, or refused by the per-conversation cap. Throws `storage.unavailable`
20
+ * without an object store.
21
+ */
22
+ export type StoreResultImage = (file: {
23
+ name: string;
24
+ contentType: string;
25
+ data: Uint8Array;
26
+ }) => Promise<{
27
+ ok: true;
28
+ attachmentId: string;
29
+ size: number;
30
+ } | {
31
+ ok: false;
32
+ reason: "cap";
33
+ }>;
34
+ /** Why an image block was not stored (each one is said in the result text). */
35
+ export type NotStoredReason = "type" | "size" | "pixels" | "unreadable" | "count" | "cap" | "storage" | "stopped" | "error";
36
+ /** The per-block texts (in image order) and the stored copies of one tool result. */
37
+ export interface ResultImages {
38
+ /** One text per image block, in order: what the model reads in place of the block. */
39
+ texts: string[];
40
+ /** The stored copies, in order; absent when none was stored. */
41
+ media?: ToolResultMedia[];
42
+ }
43
+ /**
44
+ * The name of a stored image: the tool's own name (the last `__` segment of its key), `-<n>` from
45
+ * the second image of a result on, and the extension of its sniffed type.
46
+ */
47
+ export declare function resultImageName(toolKey: string, index: number, mediaType: string): string;
48
+ /** A stored image in the result text (model-visible): its type, size, pixels and file_id. */
49
+ export declare const resultImageText: (mediaType: string, size: number, dims: {
50
+ width?: number;
51
+ height?: number;
52
+ }, attachmentId: string) => string;
53
+ /**
54
+ * An image block that was not stored (model-visible): it is neither shown to the model nor kept
55
+ * in the history, and the text says so, so a model never takes the line for an image it saw.
56
+ * Without a reason (a pipeline with no image store wired in) it says only that.
57
+ */
58
+ export declare const resultImageNotStoredText: (mediaType: string, size: number, reason?: NotStoredReason) => string;
59
+ /** The decoded size of base64 data, without decoding it. */
60
+ export declare function base64Bytes(data: string): number;
61
+ /**
62
+ * An image block of a tool result: `{ type: "image", data: <base64 string>, mimeType? }`. The one
63
+ * test {@link storeResultImages} and `renderResult` both use, so the n-th text always belongs to
64
+ * the n-th image block.
65
+ */
66
+ export declare function isToolImageBlock(b: unknown): b is {
67
+ type: "image";
68
+ data: string;
69
+ mimeType?: unknown;
70
+ };
71
+ /**
72
+ * Whether the bytes decode as a whole image within {@link RESULT_IMAGE_MAX_PIXELS}: `pixels` when
73
+ * the header's size is missing or over the bound, `unreadable` when decoding fails (a truncated
74
+ * or corrupt body after valid magic bytes), else null. Decodes once, shrunk, so the cost is bounded
75
+ * by the pixel limit.
76
+ */
77
+ export declare function checkResultImage(data: Uint8Array): Promise<"pixels" | "unreadable" | null>;
78
+ /**
79
+ * Stores the image blocks of a tool result (`{ content: [...] }`, blocks matching
80
+ * {@link isToolImageBlock}), in order and one at a time, and returns the text for each block and
81
+ * the stored copies; `undefined` when the result has no image block. A block is stored when it is
82
+ * among the first {@link RESULT_IMAGES_MAX} and at most `MEDIA_LIMITS.imageBytes` (both checked
83
+ * before decoding), its bytes sniff as PNG, JPEG, GIF or WebP, and it decodes as a whole image
84
+ * within {@link RESULT_IMAGE_MAX_PIXELS}; `store` absent or throwing `storage.unavailable` means no
85
+ * object store; any other error is passed to `onError` and the block is not stored (the call's
86
+ * result is still written). `signal` (the run's) is checked before each image: once the run is
87
+ * stopped, nothing more is stored and the remaining images read "not stored" (the tool's own result
88
+ * is still written). A copy stored before a crash that keeps the result from being written stays bound
89
+ * and unreferenced until the conversation's purge (the same window as `Read`'s copies).
90
+ */
91
+ export declare function storeResultImages(result: unknown, toolKey: string, store: StoreResultImage | undefined, onError?: (err: unknown) => void, signal?: AbortSignal): Promise<ResultImages | undefined>;
@@ -0,0 +1,195 @@
1
+ import { MEDIA_LIMITS } from "@capybara-hq/plugin-sdk";
2
+ import sharp from "sharp";
3
+ import { sniffImage } from "../media/image-header.js";
4
+ import { sizeText } from "./builtins/size-text.js";
5
+ /**
6
+ * Images in tool results (tool result images design §2): the pipeline stores every image block a
7
+ * tool returns as a `read` copy of the calling conversation and names it in `tool_result.media`,
8
+ * so request building shows it to a model with vision after the step's tool results, exactly as
9
+ * an image the builtin `Read` read. The tool never names an attachment: the kernel stores the
10
+ * bytes it was given and records the ids itself.
11
+ */
12
+ /** The most image blocks of one tool result that are stored; the rest are named as not stored. */
13
+ export const RESULT_IMAGES_MAX = 10;
14
+ /**
15
+ * The most pixels an image from a tool result may have: an external server can send a small,
16
+ * highly compressible file that decodes to gigabytes. The same bound as the kernel's thumbnails
17
+ * (`THUMBNAIL_MAX_INPUT_PIXELS`).
18
+ */
19
+ export const RESULT_IMAGE_MAX_PIXELS = 40_000_000;
20
+ /** base64 characters decoded to sniff a block's type without decoding it (a 64-byte head). */
21
+ const SNIFF_BASE64_CHARS = 88;
22
+ const EXTENSIONS = {
23
+ "image/png": "png",
24
+ "image/jpeg": "jpg",
25
+ "image/gif": "gif",
26
+ "image/webp": "webp",
27
+ };
28
+ /**
29
+ * The name of a stored image: the tool's own name (the last `__` segment of its key), `-<n>` from
30
+ * the second image of a result on, and the extension of its sniffed type.
31
+ */
32
+ export function resultImageName(toolKey, index, mediaType) {
33
+ const at = toolKey.lastIndexOf("__");
34
+ const base = (at === -1 ? toolKey : toolKey.slice(at + 2)) || "image";
35
+ const ext = EXTENSIONS[mediaType] ?? "img";
36
+ return `${base.slice(0, 200)}${index === 0 ? "" : `-${index + 1}`}.${ext}`;
37
+ }
38
+ const dimsText = (d) => d.width !== undefined && d.height !== undefined ? `, ${d.width}×${d.height}` : "";
39
+ /** A stored image in the result text (model-visible): its type, size, pixels and file_id. */
40
+ export const resultImageText = (mediaType, size, dims, attachmentId) => `[Image (${mediaType}, ${sizeText(size)}${dimsText(dims)}), file_id ${attachmentId}]`;
41
+ const REASON_TEXT = {
42
+ type: "only PNG, JPEG, GIF and WebP images are stored.",
43
+ size: "it is over the 5 MB image limit.",
44
+ pixels: `its pixel size is missing or over the limit of ${RESULT_IMAGE_MAX_PIXELS / 1_000_000} megapixels.`,
45
+ unreadable: "it could not be decoded as a whole image.",
46
+ count: `a tool result stores at most ${RESULT_IMAGES_MAX} images.`,
47
+ cap: "this conversation reached its limit for stored images.",
48
+ storage: "file storage is not configured in this deployment.",
49
+ stopped: "the run was stopped while its images were stored.",
50
+ error: "storing it failed.",
51
+ };
52
+ /**
53
+ * An image block that was not stored (model-visible): it is neither shown to the model nor kept
54
+ * in the history, and the text says so, so a model never takes the line for an image it saw.
55
+ * Without a reason (a pipeline with no image store wired in) it says only that.
56
+ */
57
+ export const resultImageNotStoredText = (mediaType, size, reason) => `[Image (${clipType(mediaType)}, ${sizeText(size)}) not stored, so not shown${reason === undefined ? "." : `: ${REASON_TEXT[reason]}`}]`;
58
+ /** A declared media type as the text shows it (the tool's string, bounded). */
59
+ const clipType = (t) => (t.length > 100 ? `${t.slice(0, 100)}…` : t);
60
+ /** base64 data decoded (Node accepts and skips characters outside the alphabet). */
61
+ const decode = (data) => new Uint8Array(Buffer.from(data, "base64"));
62
+ /** The decoded size of base64 data, without decoding it. */
63
+ export function base64Bytes(data) {
64
+ const s = data.replace(/\s/g, "");
65
+ const pad = s.endsWith("==") ? 2 : s.endsWith("=") ? 1 : 0;
66
+ return Math.max(0, Math.floor((s.length * 3) / 4) - pad);
67
+ }
68
+ /**
69
+ * An image block of a tool result: `{ type: "image", data: <base64 string>, mimeType? }`. The one
70
+ * test {@link storeResultImages} and `renderResult` both use, so the n-th text always belongs to
71
+ * the n-th image block.
72
+ */
73
+ export function isToolImageBlock(b) {
74
+ return (typeof b === "object" &&
75
+ b !== null &&
76
+ !Array.isArray(b) &&
77
+ b.type === "image" &&
78
+ typeof b.data === "string");
79
+ }
80
+ /**
81
+ * Whether the bytes decode as a whole image within {@link RESULT_IMAGE_MAX_PIXELS}: `pixels` when
82
+ * the header's size is missing or over the bound, `unreadable` when decoding fails (a truncated
83
+ * or corrupt body after valid magic bytes), else null. Decodes once, shrunk, so the cost is bounded
84
+ * by the pixel limit.
85
+ */
86
+ export async function checkResultImage(data) {
87
+ let width;
88
+ let height;
89
+ try {
90
+ ({ width, height } = await sharp(data, { limitInputPixels: false }).metadata());
91
+ }
92
+ catch {
93
+ return "unreadable";
94
+ }
95
+ if (!width || !height || width * height > RESULT_IMAGE_MAX_PIXELS)
96
+ return "pixels";
97
+ try {
98
+ await sharp(data, { failOn: "truncated", limitInputPixels: RESULT_IMAGE_MAX_PIXELS })
99
+ .resize(64, 64, { fit: "inside" })
100
+ .toBuffer();
101
+ }
102
+ catch {
103
+ return "unreadable";
104
+ }
105
+ return null;
106
+ }
107
+ const isApiStorageUnavailable = (e) => typeof e === "object" && e !== null && e.code === "storage.unavailable";
108
+ /**
109
+ * Stores the image blocks of a tool result (`{ content: [...] }`, blocks matching
110
+ * {@link isToolImageBlock}), in order and one at a time, and returns the text for each block and
111
+ * the stored copies; `undefined` when the result has no image block. A block is stored when it is
112
+ * among the first {@link RESULT_IMAGES_MAX} and at most `MEDIA_LIMITS.imageBytes` (both checked
113
+ * before decoding), its bytes sniff as PNG, JPEG, GIF or WebP, and it decodes as a whole image
114
+ * within {@link RESULT_IMAGE_MAX_PIXELS}; `store` absent or throwing `storage.unavailable` means no
115
+ * object store; any other error is passed to `onError` and the block is not stored (the call's
116
+ * result is still written). `signal` (the run's) is checked before each image: once the run is
117
+ * stopped, nothing more is stored and the remaining images read "not stored" (the tool's own result
118
+ * is still written). A copy stored before a crash that keeps the result from being written stays bound
119
+ * and unreferenced until the conversation's purge (the same window as `Read`'s copies).
120
+ */
121
+ export async function storeResultImages(result, toolKey, store, onError, signal) {
122
+ const content = result?.content;
123
+ if (!Array.isArray(content))
124
+ return undefined;
125
+ const blocks = content.filter(isToolImageBlock);
126
+ if (blocks.length === 0)
127
+ return undefined;
128
+ const texts = [];
129
+ const media = [];
130
+ let noStorage = store === undefined;
131
+ for (const [i, b] of blocks.entries()) {
132
+ const declared = typeof b.mimeType === "string" ? b.mimeType : "unknown";
133
+ const declaredSize = base64Bytes(b.data);
134
+ const notStored = (reason, size = declaredSize) => texts.push(resultImageNotStoredText(declared, size, reason));
135
+ if (i >= RESULT_IMAGES_MAX) {
136
+ notStored("count");
137
+ continue;
138
+ }
139
+ if (declaredSize > MEDIA_LIMITS.imageBytes) {
140
+ notStored("size");
141
+ continue;
142
+ }
143
+ if (noStorage || store === undefined) {
144
+ // the head is enough to tell an image from another type, so that reason still wins
145
+ notStored(sniffImage(decode(b.data.slice(0, SNIFF_BASE64_CHARS))) === null ? "type" : "storage");
146
+ continue;
147
+ }
148
+ if (signal?.aborted) {
149
+ notStored("stopped");
150
+ continue;
151
+ }
152
+ const data = decode(b.data);
153
+ const size = data.byteLength;
154
+ const sniffed = sniffImage(data);
155
+ if (sniffed === null) {
156
+ notStored("type", size);
157
+ continue;
158
+ }
159
+ const bad = await checkResultImage(data);
160
+ if (bad !== null) {
161
+ notStored(bad, size);
162
+ continue;
163
+ }
164
+ if (signal?.aborted) {
165
+ notStored("stopped", size);
166
+ continue;
167
+ }
168
+ const name = resultImageName(toolKey, media.length, sniffed.mediaType);
169
+ try {
170
+ const stored = await store({ name, contentType: sniffed.mediaType, data });
171
+ if (!stored.ok) {
172
+ notStored("cap", size);
173
+ continue;
174
+ }
175
+ media.push({
176
+ attachmentId: stored.attachmentId,
177
+ name,
178
+ mediaType: sniffed.mediaType,
179
+ size: stored.size,
180
+ });
181
+ texts.push(resultImageText(sniffed.mediaType, stored.size, sniffed, stored.attachmentId));
182
+ }
183
+ catch (e) {
184
+ if (isApiStorageUnavailable(e)) {
185
+ noStorage = true;
186
+ notStored("storage", size);
187
+ }
188
+ else {
189
+ onError?.(e);
190
+ notStored("error", size);
191
+ }
192
+ }
193
+ }
194
+ return { texts, ...(media.length > 0 && { media }) };
195
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capybara-hq/kernel",
3
- "version": "0.1.0-rc.90",
3
+ "version": "0.1.0-rc.91",
4
4
  "description": "Capybara kernel: config, database, plugin host and HTTP API of the Capybara agent platform",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -66,7 +66,7 @@
66
66
  "yaml": "^2.9.1",
67
67
  "yauzl": "3.4.0",
68
68
  "zod": "^4.6.7",
69
- "@capybara-hq/plugin-sdk": "^0.1.0-rc.72"
69
+ "@capybara-hq/plugin-sdk": "^0.1.0-rc.73"
70
70
  },
71
71
  "devDependencies": {
72
72
  "@langchain/langgraph-checkpoint-validation": "^1.2.0",