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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bootstrap.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "schemaVersion": 1,
4
4
  "marketplace": {
5
5
  "url": "https://github.com/capybara-hq/plugins.git",
6
- "commit": "d03e463a0339d42f42ec591cd44eea7d96436d06"
6
+ "commit": "44fa9a1384c92d8016c54dae17d36fb9d464c9e5"
7
7
  },
8
8
  "plugins": [
9
9
  {
@@ -90,16 +90,16 @@
90
90
  "name": "device-docker",
91
91
  "source": "npm",
92
92
  "npm": "@capybara-hq/plugin-device-docker",
93
- "version": "0.1.0-rc.29",
94
- "integrity": "sha512-TGdSjzofH1KNP8t0fgzFqd7Jf19nrDSJ+l+G+0oLc36PI3GGk2pzp97m9K1XfAlaIWrABghZytjE3myCXpvdBw==",
93
+ "version": "0.1.0-rc.30",
94
+ "integrity": "sha512-bhqSRr6r9gNI7aKYE0ANf3xeCYYIKCOFlvOZZLyM83AzaTn4A2K7zgbgZQZAGgs9b5M3cZhlemjVTAChBPZGuw==",
95
95
  "required": false
96
96
  },
97
97
  {
98
98
  "name": "device-local",
99
99
  "source": "npm",
100
100
  "npm": "@capybara-hq/plugin-device-local",
101
- "version": "0.1.0-rc.10",
102
- "integrity": "sha512-f33WI+WifA/5jNjsWiuuPsrvRR/TD3qizXY2GkW4IVKZGHuMoznoxQu+znEYjsQl7b0ZxuuBzcTgHI9oGIFhRg==",
101
+ "version": "0.1.0-rc.11",
102
+ "integrity": "sha512-ZxWxrGjPjNpJtwH/2oK58itxfPFRi5CQQFbMe8VPyfYaEdfyPT8ZlOjgocdz/F8hR9jeu+E2VPgOmh7uMeBo/w==",
103
103
  "required": false,
104
104
  "scope": "all"
105
105
  },
@@ -208,7 +208,7 @@ export declare function headsToResolve(entries: readonly MarketplaceEntry[], imp
208
208
  /** The host versions (an entry's `minKernel` is judged against them). */
209
209
  export declare const HOST_VERSIONS: {
210
210
  readonly kernel: string;
211
- readonly sdk: "0.1.0-rc.72";
211
+ readonly sdk: "0.1.0-rc.75";
212
212
  };
213
213
  /** Whether this deployment satisfies the entry's `minKernel`. */
214
214
  export declare const entryCompatible: (e: Pick<MarketplaceEntry, "minKernel">) => boolean;
@@ -1230,7 +1230,7 @@ export const KernelConfigSchema = z.strictObject({
1230
1230
  .default(6)
1231
1231
  .meta(meta({
1232
1232
  hot: true,
1233
- description: "Most images Read may show the model in one request; older Read images are replaced with a placeholder",
1233
+ description: "Most stored tool-result images (Read images and images other tools returned) shown to the model in one request; older ones are replaced with a placeholder",
1234
1234
  })),
1235
1235
  readMaxBytesPerConversation: z
1236
1236
  .number()
@@ -1240,7 +1240,7 @@ export const KernelConfigSchema = z.strictObject({
1240
1240
  .default(536_870_912)
1241
1241
  .meta(meta({
1242
1242
  hot: true,
1243
- description: "Most bytes of Read image copies stored for one conversation; past it a Read image is not stored and does not stay in the history; 0 stores none",
1243
+ description: "Most bytes of stored tool-result image copies (Read images and images other tools returned) for one conversation; past it an image is not stored and does not stay in the history; 0 stores none",
1244
1244
  })),
1245
1245
  readPurgeAfterHours: z
1246
1246
  .number()
@@ -1250,7 +1250,7 @@ export const KernelConfigSchema = z.strictObject({
1250
1250
  .default(24)
1251
1251
  .meta(meta({
1252
1252
  hot: true,
1253
- description: "Hours after a conversation is deleted before its Read image copies are purged (row and object)",
1253
+ description: "Hours after a conversation is deleted before its stored tool-result image copies are purged (row and object)",
1254
1254
  })),
1255
1255
  })
1256
1256
  // 单个附件不能大于单次请求的预算:否则它永远被省略(最新的附件总能放进请求)
@@ -210,6 +210,9 @@ export declare class AttachmentsService {
210
210
  * 下载地址(预签名,{@link ATTACHMENT_DOWNLOAD_TTL_SECONDS} 秒):已绑定的附件要求能访问其会话,
211
211
  * 未绑定的只有上传者;否则 `attachment.not_found`。只有图片与 PDF 以 `inline` 打开,其余一律 `attachment`
212
212
  * (即使存储里的类型被改成 text/html 也不会在页面里渲染);响应类型按 finalize 核对过的类型返回。
213
+ * A `read` copy (an image a tool showed the agent) is served the same way to whoever can open its
214
+ * conversation, so the web can show it on the call's row (tool result images design §4); it is
215
+ * still never listed (lists and the device's attachments stay `chat` only).
213
216
  */
214
217
  downloadUrl(orgId: string, accountId: string, id: string): Promise<string>;
215
218
  /**
@@ -423,6 +423,9 @@ let AttachmentsService = class AttachmentsService {
423
423
  * 下载地址(预签名,{@link ATTACHMENT_DOWNLOAD_TTL_SECONDS} 秒):已绑定的附件要求能访问其会话,
424
424
  * 未绑定的只有上传者;否则 `attachment.not_found`。只有图片与 PDF 以 `inline` 打开,其余一律 `attachment`
425
425
  * (即使存储里的类型被改成 text/html 也不会在页面里渲染);响应类型按 finalize 核对过的类型返回。
426
+ * A `read` copy (an image a tool showed the agent) is served the same way to whoever can open its
427
+ * conversation, so the web can show it on the call's row (tool result images design §4); it is
428
+ * still never listed (lists and the device's attachments stay `chat` only).
426
429
  */
427
430
  async downloadUrl(orgId, accountId, id) {
428
431
  this.storage.assertAvailable();
@@ -440,7 +443,7 @@ let AttachmentsService = class AttachmentsService {
440
443
  .where("id", "=", id)
441
444
  .where("org_id", "=", orgId)
442
445
  .where("status", "=", "ready")
443
- .where("purpose", "=", "chat")
446
+ .where("purpose", "in", ["chat", "read"])
444
447
  .executeTakeFirst();
445
448
  if (!row)
446
449
  throw notFound();
@@ -1617,6 +1617,10 @@ export declare const ConversationEventSchema: z.ZodDiscriminatedUnion<[z.ZodObje
1617
1617
  en: z.ZodString;
1618
1618
  }, z.core.$strip>]>;
1619
1619
  url: z.ZodOptional<z.ZodString>;
1620
+ body: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
1621
+ zh: z.ZodString;
1622
+ en: z.ZodString;
1623
+ }, z.core.$strip>]>>;
1620
1624
  fields: z.ZodArray<z.ZodObject<{
1621
1625
  key: z.ZodString;
1622
1626
  label: z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
@@ -1631,6 +1635,13 @@ export declare const ConversationEventSchema: z.ZodDiscriminatedUnion<[z.ZodObje
1631
1635
  multiSelect: z.ZodOptional<z.ZodBoolean>;
1632
1636
  allowOther: z.ZodOptional<z.ZodBoolean>;
1633
1637
  required: z.ZodOptional<z.ZodBoolean>;
1638
+ choices: z.ZodOptional<z.ZodArray<z.ZodObject<{
1639
+ value: z.ZodUnion<readonly [z.ZodString, z.ZodBoolean]>;
1640
+ label: z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
1641
+ zh: z.ZodString;
1642
+ en: z.ZodString;
1643
+ }, z.core.$strip>]>;
1644
+ }, z.core.$strip>>>;
1634
1645
  }, z.core.$strip>>;
1635
1646
  }, z.core.$strip>;
1636
1647
  expiresAt: z.ZodString;
@@ -671,6 +671,8 @@ const InputFormSchema = z.object({
671
671
  title: FormTextSchema,
672
672
  /** 需要用户在浏览器里打开的外部页面(MCP URL 模式的 elicitation)。较早的事件没有。 */
673
673
  url: z.string().optional(),
674
+ /** Longer text under the title (`InputForm.body`). Older events have none. */
675
+ body: FormTextSchema.optional(),
674
676
  fields: z.array(z.object({
675
677
  key: z.string(),
676
678
  label: FormTextSchema,
@@ -679,6 +681,10 @@ const InputFormSchema = z.object({
679
681
  multiSelect: z.boolean().optional(),
680
682
  allowOther: z.boolean().optional(),
681
683
  required: z.boolean().optional(),
684
+ /** The field's buttons (`InputForm` `choices`). Older events have none. */
685
+ choices: z
686
+ .array(z.object({ value: z.union([z.string(), z.boolean()]), label: FormTextSchema }))
687
+ .optional(),
682
688
  })),
683
689
  });
684
690
  /** 表单答案(plugin-sdk 的 `FormAnswer`)。 */
@@ -1297,10 +1303,12 @@ export const ConversationEventSchema = z.discriminatedUnion("type", [
1297
1303
  })
1298
1304
  .optional(),
1299
1305
  /**
1300
- * The images the builtin Read stored for the call (vision-read design §1.2): `read`
1301
- * attachments bound to this conversation, one per image. Model-visible: request building
1302
- * renders each after the step's tool results (`Image from Read (file_id <id>):` and the image,
1303
- * or the no-vision text), inside the Read-image window. Only the builtin Read sets it.
1306
+ * The images stored for the call: the builtin Read's copy (vision-read design §1.2) and the
1307
+ * image blocks of any tool's result, which the pipeline stores itself (tool result images
1308
+ * design §2); `read` attachments bound to this conversation, one per image. A tool never
1309
+ * names an attachment here. Model-visible: request building renders each after the step's
1310
+ * tool results (`Image from <toolKey> (file_id <id>):` and the image, or the no-vision
1311
+ * text), inside the Read-image window. The web shows them on the call's row.
1304
1312
  */
1305
1313
  media: z
1306
1314
  .array(z.object({
@@ -7,6 +7,12 @@ import type { MediaBytes } from "../runtime/context/build.js";
7
7
  export declare const MODEL_IMAGE_MAX_EDGE = 2048;
8
8
  /** An image at most this large and within {@link MODEL_IMAGE_MAX_EDGE} is sent unchanged. */
9
9
  export declare const MODEL_IMAGE_KEEP_BYTES = 1048576;
10
+ /**
11
+ * The most pixels {@link fitImageForModel} decodes; a larger image is sent unchanged (and a
12
+ * provider that rejects it is handled by `media_excluded`). Above the tool-result and thumbnail
13
+ * bound (40 megapixels) so a large camera photo a person uploads is still scaled.
14
+ */
15
+ export declare const MODEL_IMAGE_MAX_INPUT_PIXELS = 100000000;
10
16
  /**
11
17
  * The copy of an image a model request carries. Images over {@link MODEL_IMAGE_KEEP_BYTES} or
12
18
  * larger than {@link MODEL_IMAGE_MAX_EDGE} on an edge are scaled to fit that edge (never enlarged)
@@ -7,6 +7,12 @@ import sharp from "sharp";
7
7
  export const MODEL_IMAGE_MAX_EDGE = 2048;
8
8
  /** An image at most this large and within {@link MODEL_IMAGE_MAX_EDGE} is sent unchanged. */
9
9
  export const MODEL_IMAGE_KEEP_BYTES = 1_048_576;
10
+ /**
11
+ * The most pixels {@link fitImageForModel} decodes; a larger image is sent unchanged (and a
12
+ * provider that rejects it is handled by `media_excluded`). Above the tool-result and thumbnail
13
+ * bound (40 megapixels) so a large camera photo a person uploads is still scaled.
14
+ */
15
+ export const MODEL_IMAGE_MAX_INPUT_PIXELS = 100_000_000;
10
16
  /** Quality of the re-encoded copy (JPEG, or WebP for an image with transparent pixels). */
11
17
  const QUALITY = 85;
12
18
  /** Types {@link fitImageForModel} re-encodes; others (GIF, which may be animated) pass through. */
@@ -23,7 +29,10 @@ export async function fitImageForModel(media) {
23
29
  if (!RESIZABLE.has(media.mediaType))
24
30
  return media;
25
31
  try {
26
- const image = sharp(media.data, { failOn: "error" });
32
+ const image = sharp(media.data, {
33
+ failOn: "error",
34
+ limitInputPixels: MODEL_IMAGE_MAX_INPUT_PIXELS,
35
+ });
27
36
  const meta = await image.metadata();
28
37
  if (media.data.byteLength <= MODEL_IMAGE_KEEP_BYTES &&
29
38
  Math.max(meta.width, meta.height) <= MODEL_IMAGE_MAX_EDGE) {
@@ -21,6 +21,11 @@ export interface DeviceStreamTicket {
21
21
  orgId: string;
22
22
  accountId: string;
23
23
  conversationId: string;
24
+ /**
25
+ * The root of `conversationId`'s tree at mint (itself outside sub-agents): the viewer context
26
+ * the kernel writes first on the service stream names it.
27
+ */
28
+ rootConversationId: string;
24
29
  deviceId: string;
25
30
  providerName: string;
26
31
  service: string;
@@ -103,7 +108,7 @@ export declare class DeviceAccessService {
103
108
  /**
104
109
  * Whether a taken viewer ticket's record still stands when its viewer opens (the checks of
105
110
  * {@link mintTicket} again, binding nothing): the conversation live and owned by the record's
106
- * account, its device still the record's device on the record's provider and the account's
111
+ * account, its current tree root the record's root, its device still the record's device on the record's provider and the account's
107
112
  * own, the record's extension still enabled in the org and its approved manifest as loaded now
108
113
  * (not the record's copy) still declaring the service in `permissions.deviceAccess.services`.
109
114
  * False when any of that no longer holds; other failures (the database) are thrown.
@@ -125,14 +130,24 @@ export declare class DeviceAccessService {
125
130
  hosts: string[];
126
131
  }): Promise<void>;
127
132
  /**
128
- * Answers the pending question of tool call `callId` in the conversation with `{ done }`, under
129
- * the questions' own rules (only the run's starter answers, the form validates the answer); only
130
- * a question one of this extension's tools raised.
133
+ * Answers the pending question of tool call `callId` in conversation `handoffConversationId`
134
+ * with `{ done }`, under the questions' own rules (only the run's starter answers, the form
135
+ * validates the answer); only a question one of this extension's tools raised, and only in the
136
+ * scope conversation or one of its sub-agent descendants (the root's panel answers a
137
+ * sub-agent's handoff; a call id is unique only within a run). Anything else is
138
+ * `question.not_found`, without telling whether such a question exists elsewhere.
131
139
  */
132
140
  answerHandoff(caller: DeviceAccessCaller, scope: DeviceAccessScope & {
133
141
  callId: string;
142
+ handoffConversationId: string;
134
143
  done: boolean;
135
144
  }): Promise<void>;
145
+ /**
146
+ * Whether `id` is `ancestorId` itself or a live conversation below it: walks `id`'s parent links
147
+ * up, every row in org `orgId` and not deleted, at most 16 levels (far above
148
+ * `subagents.maxDepth`'s bound of 5, so a corrupt parent chain cannot loop forever).
149
+ */
150
+ private isSelfOrDescendant;
136
151
  /** The use of the call's device (bound now when the conversation has none yet, as tools do). */
137
152
  private callUse;
138
153
  /**
@@ -274,6 +274,7 @@ let DeviceAccessService = class DeviceAccessService {
274
274
  orgId: d.orgId,
275
275
  accountId: scope.accountId,
276
276
  conversationId: d.conversationId,
277
+ rootConversationId: d.rootConversationId,
277
278
  deviceId: d.deviceId,
278
279
  providerName: d.provider,
279
280
  service,
@@ -295,7 +296,7 @@ let DeviceAccessService = class DeviceAccessService {
295
296
  /**
296
297
  * Whether a taken viewer ticket's record still stands when its viewer opens (the checks of
297
298
  * {@link mintTicket} again, binding nothing): the conversation live and owned by the record's
298
- * account, its device still the record's device on the record's provider and the account's
299
+ * account, its current tree root the record's root, its device still the record's device on the record's provider and the account's
299
300
  * own, the record's extension still enabled in the org and its approved manifest as loaded now
300
301
  * (not the record's copy) still declaring the service in `permissions.deviceAccess.services`.
301
302
  * False when any of that no longer holds; other failures (the database) are thrown.
@@ -315,7 +316,10 @@ let DeviceAccessService = class DeviceAccessService {
315
316
  return "revoked";
316
317
  try {
317
318
  const d = await this.scopedDevice({ extension: t.extension, services: [t.service] }, { orgId: t.orgId, accountId: t.accountId, conversationId: t.conversationId });
318
- return d.orgId === t.orgId && d.deviceId === t.deviceId && d.provider === t.providerName
319
+ return d.orgId === t.orgId &&
320
+ d.rootConversationId === t.rootConversationId &&
321
+ d.deviceId === t.deviceId &&
322
+ d.provider === t.providerName
319
323
  ? "stands"
320
324
  : "revoked";
321
325
  }
@@ -358,29 +362,58 @@ let DeviceAccessService = class DeviceAccessService {
358
362
  }
359
363
  }
360
364
  /**
361
- * Answers the pending question of tool call `callId` in the conversation with `{ done }`, under
362
- * the questions' own rules (only the run's starter answers, the form validates the answer); only
363
- * a question one of this extension's tools raised.
365
+ * Answers the pending question of tool call `callId` in conversation `handoffConversationId`
366
+ * with `{ done }`, under the questions' own rules (only the run's starter answers, the form
367
+ * validates the answer); only a question one of this extension's tools raised, and only in the
368
+ * scope conversation or one of its sub-agent descendants (the root's panel answers a
369
+ * sub-agent's handoff; a call id is unique only within a run). Anything else is
370
+ * `question.not_found`, without telling whether such a question exists elsewhere.
364
371
  */
365
372
  async answerHandoff(caller, scope) {
366
373
  const d = await this.scopedDevice(caller, scope);
374
+ const notFound = () => new ApiError("question.not_found", `No pending question of tool call ${scope.callId} in this conversation`);
375
+ if (!(await this.isSelfOrDescendant(d.orgId, d.conversationId, scope.handoffConversationId)))
376
+ throw notFound();
367
377
  const q = await this.db
368
378
  .selectFrom("questions")
369
379
  .select(["id", "spec"])
370
380
  .where("org_id", "=", d.orgId)
371
- .where("conversation_id", "=", d.conversationId)
381
+ .where("conversation_id", "=", scope.handoffConversationId)
372
382
  .where("call_id", "=", scope.callId)
373
383
  .where("status", "=", "pending")
374
384
  .orderBy("created_at", "desc")
375
385
  .executeTakeFirst();
376
386
  if (q === undefined)
377
- throw new ApiError("question.not_found", `No pending question of tool call ${scope.callId} in this conversation`);
387
+ throw notFound();
378
388
  const key = q.spec?.toolKey;
379
389
  const parsed = typeof key === "string" ? parseToolKey(key) : null;
380
390
  if (parsed?.kind !== "extension" || parsed.plugin !== caller.extension)
381
391
  throw new ApiError("question.not_found", `No pending question of tool call ${scope.callId} of ${caller.extension} in this conversation`);
382
392
  await this.questions.answer(q.id, scope.accountId, { done: scope.done }, d.orgId);
383
393
  }
394
+ /**
395
+ * Whether `id` is `ancestorId` itself or a live conversation below it: walks `id`'s parent links
396
+ * up, every row in org `orgId` and not deleted, at most 16 levels (far above
397
+ * `subagents.maxDepth`'s bound of 5, so a corrupt parent chain cannot loop forever).
398
+ */
399
+ async isSelfOrDescendant(orgId, ancestorId, id) {
400
+ let current = id;
401
+ for (let i = 0; i <= 16; i++) {
402
+ if (current === ancestorId)
403
+ return true;
404
+ const row = await this.db
405
+ .selectFrom("conversations")
406
+ .select("parent_conversation_id")
407
+ .where("id", "=", current)
408
+ .where("org_id", "=", orgId)
409
+ .where("deleted_at", "is", null)
410
+ .executeTakeFirst();
411
+ if (!row?.parent_conversation_id)
412
+ return false;
413
+ current = row.parent_conversation_id;
414
+ }
415
+ return false;
416
+ }
384
417
  /** The use of the call's device (bound now when the conversation has none yet, as tools do). */
385
418
  async callUse(call, rootConversationId, scope) {
386
419
  const conv = await this.db
@@ -151,7 +151,10 @@ export declare function parseTicketRecord(raw: unknown): DeviceStreamTicket | nu
151
151
  * The viewer endpoint (browser use spec §6.2, served on the gateway role by `viewer-routes.ts`):
152
152
  * `GET /device/stream?ticket=` takes the single-use viewer ticket
153
153
  * (`DeviceAccessService.takeTicket`) and pipes the device service's stream to the browser, bytes
154
- * unchanged both ways. Where the stream opens:
154
+ * unchanged both ways, after one message of its own: the first stream message the service gets is
155
+ * the viewer context (`encodeViewerContext`: the record's conversation and its root, from the
156
+ * ticket record only), written where the stream opens and before any of the browser's messages
157
+ * (queued by its {@link WsEnd} meanwhile). Where the stream opens:
155
158
  *
156
159
  * - A device whose provider declares `permissions.dialIn` (a local device) streams only from the
157
160
  * gateway replica holding its machine's socket. Any other replica hops once: a `ws` connection
@@ -8,7 +8,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
8
  return function (target, key) { decorator(target, key, paramIndex); }
9
9
  };
10
10
  import { createHmac, timingSafeEqual } from "node:crypto";
11
- import { DeviceAccessError, deviceServiceId, isDeviceOfflineError, } from "@capybara-hq/plugin-sdk";
11
+ import { DeviceAccessError, deviceServiceId, encodeViewerContext, isDeviceOfflineError, } from "@capybara-hq/plugin-sdk";
12
12
  import { Inject, Injectable } from "@nestjs/common";
13
13
  import WebSocket, {} from "ws";
14
14
  import { DialInGateway } from "../dial-in/gateway.js";
@@ -354,6 +354,7 @@ export function parseTicketRecord(raw) {
354
354
  "orgId",
355
355
  "accountId",
356
356
  "conversationId",
357
+ "rootConversationId",
357
358
  "deviceId",
358
359
  "providerName",
359
360
  "service",
@@ -366,6 +367,7 @@ export function parseTicketRecord(raw) {
366
367
  orgId: r.orgId,
367
368
  accountId: r.accountId,
368
369
  conversationId: r.conversationId,
370
+ rootConversationId: r.rootConversationId,
369
371
  deviceId: r.deviceId,
370
372
  providerName: r.providerName,
371
373
  service: r.service,
@@ -376,7 +378,10 @@ export function parseTicketRecord(raw) {
376
378
  * The viewer endpoint (browser use spec §6.2, served on the gateway role by `viewer-routes.ts`):
377
379
  * `GET /device/stream?ticket=` takes the single-use viewer ticket
378
380
  * (`DeviceAccessService.takeTicket`) and pipes the device service's stream to the browser, bytes
379
- * unchanged both ways. Where the stream opens:
381
+ * unchanged both ways, after one message of its own: the first stream message the service gets is
382
+ * the viewer context (`encodeViewerContext`: the record's conversation and its root, from the
383
+ * ticket record only), written where the stream opens and before any of the browser's messages
384
+ * (queued by its {@link WsEnd} meanwhile). Where the stream opens:
380
385
  *
381
386
  * - A device whose provider declares `permissions.dialIn` (a local device) streams only from the
382
387
  * gateway replica holding its machine's socket. Any other replica hops once: a `ws` connection
@@ -746,7 +751,15 @@ let DeviceStreamViewers = class DeviceStreamViewers {
746
751
  });
747
752
  viewed = true;
748
753
  void pump(stream.messages, end);
749
- const inbound = pump(end.messages, stream);
754
+ // the first stream message is the kernel's viewer context, from the ticket record only; the
755
+ // panel's messages (queued by `end` meanwhile) follow it
756
+ const inbound = stream
757
+ .send(encodeViewerContext({
758
+ kind: "viewer",
759
+ conversationId: record.conversationId,
760
+ rootConversationId: record.rootConversationId,
761
+ }))
762
+ .then(() => pump(end.messages, stream), (failed) => ({ failed: failed ?? new Error("send failed") }));
750
763
  const settled = await Promise.race([
751
764
  end.closed.then(() => ({ side: "viewer" })),
752
765
  stream.closed.then((c) => ({ side: "stream", reason: c.reason })),
@@ -164,7 +164,10 @@ export declare const PDF_BYTES_PER_PAGE_ESTIMATE: number;
164
164
  export declare function pdfTokens(size: number, pages: number | null): number;
165
165
  /** 日志里(按 zod 推导的形状)的内容块。 */
166
166
  type LogBlock = EventPayload<"user_message">["content"][number];
167
- /** One image the builtin Read stored (`tool_result.media`, vision-read design §1.2). */
167
+ /**
168
+ * One stored image of a tool result (`tool_result.media`): the builtin Read's copy (vision-read
169
+ * design §1.2) or an image block of any tool's result (tool result images design §2).
170
+ */
168
171
  export type ReadMedia = NonNullable<EventPayload<"tool_result">["media"]>[number];
169
172
  /**
170
173
  * The Read-image window with chunked eviction (vision-read design §1.4): walks the images from Read
@@ -245,15 +248,19 @@ export declare const mediaTooManyImagesText: (name: string) => string;
245
248
  export declare const mediaTooManyPagesText: (name: string) => string;
246
249
  /** An attachment the provider rejected, never sent again (model-facing, English). */
247
250
  export declare const mediaRejectedText: (name: string) => string;
248
- /** The label before an image from Read (model-facing, vision-read design §1.4). */
249
- export declare const readImageLabelText: (id: string) => string;
250
251
  /**
251
- * An image from Read for a model without vision (static, so history stays append-only; any
252
- * fallback answer is already in the tool result).
252
+ * The label before an image of a tool result (model-facing; vision-read design §1.4, tool result
253
+ * images design §3): the tool's key, e.g. `Image from Read (file_id <id>):`.
254
+ */
255
+ export declare const readImageLabelText: (toolKey: string, id: string) => string;
256
+ /**
257
+ * An image of a tool result for a model without vision (static, so history stays append-only):
258
+ * it says the image was not shown. After `Read`, whose result already carries any vision model's
259
+ * answer, nothing more; after another tool, how the image can still be read.
253
260
  */
254
- export declare const READ_IMAGE_NO_VISION_TEXT = "[This model cannot view images.]";
255
- /** An image from Read the Read-image window left out of this request. */
256
- export declare const readImageNotIncludedText: (id: string) => string;
261
+ export declare const readImageNoVisionText: (toolKey: string, id: string) => string;
262
+ /** An image of a tool result the Read-image window left out of this request. */
263
+ export declare const readImageNotIncludedText: (toolKey: string, id: string) => string;
257
264
  /**
258
265
  * A reference line (model-facing English, one text block, §5.2): the file's name and media type, its
259
266
  * size, the unsigned object URI, and how to get the bytes — `FetchAttachment` copies the file into the
@@ -294,15 +294,21 @@ export const mediaTooManyImagesText = (name) => `[Attachment ${quoted(name)} omi
294
294
  export const mediaTooManyPagesText = (name) => `[Attachment ${quoted(name)} has too many pages for this model.]`;
295
295
  /** An attachment the provider rejected, never sent again (model-facing, English). */
296
296
  export const mediaRejectedText = (name) => `[Attachment ${quoted(name)} was rejected by the model provider.]`;
297
- /** The label before an image from Read (model-facing, vision-read design §1.4). */
298
- export const readImageLabelText = (id) => `Image from Read (file_id ${id}):`;
299
297
  /**
300
- * An image from Read for a model without vision (static, so history stays append-only; any
301
- * fallback answer is already in the tool result).
298
+ * The label before an image of a tool result (model-facing; vision-read design §1.4, tool result
299
+ * images design §3): the tool's key, e.g. `Image from Read (file_id <id>):`.
302
300
  */
303
- export const READ_IMAGE_NO_VISION_TEXT = "[This model cannot view images.]";
304
- /** An image from Read the Read-image window left out of this request. */
305
- export const readImageNotIncludedText = (id) => `[Image from Read (file_id ${id}) not included in this request.]`;
301
+ export const readImageLabelText = (toolKey, id) => `Image from ${toolKey} (file_id ${id}):`;
302
+ /**
303
+ * An image of a tool result for a model without vision (static, so history stays append-only):
304
+ * it says the image was not shown. After `Read`, whose result already carries any vision model's
305
+ * answer, nothing more; after another tool, how the image can still be read.
306
+ */
307
+ export const readImageNoVisionText = (toolKey, id) => toolKey === "Read"
308
+ ? "[Not shown to you: this model cannot view images.]"
309
+ : `[Not shown to you: this model cannot view images. If Read is available to you, Read with file_id ${id} sends it to the organization's vision model, if one is set.]`;
310
+ /** An image of a tool result the Read-image window left out of this request. */
311
+ export const readImageNotIncludedText = (toolKey, id) => `[Image from ${toolKey} (file_id ${id}) not included in this request.]`;
306
312
  /**
307
313
  * The usual file extension per content type: the label of a `file` block logged without a name (every
308
314
  * accepted type, so the reference line always names something a person could recognise).
@@ -343,7 +349,7 @@ export const attachmentReferenceText = (input) => {
343
349
  };
344
350
  function placeholder(b, name) {
345
351
  if (b.type === "image") {
346
- return `[Attached image ${quoted(name)} — this model cannot view images. Read with file_id ${b.source.attachmentId} sends it to the organization's vision model, if one is set.]`;
352
+ return `[Attached image ${quoted(name)} — this model cannot view images. If Read is available to you, Read with file_id ${b.source.attachmentId} sends it to the organization's vision model, if one is set.]`;
347
353
  }
348
354
  return `[Attached document ${quoted(name)} — this model cannot read ${b.mediaType === "application/pdf" ? "PDF documents" : "documents"}.]`;
349
355
  }
@@ -762,7 +768,7 @@ export function buildModelRequest(input) {
762
768
  * label: the image (through {@link resolveMedia}, so the cap, the budget and `media_excluded`
763
769
  * apply), the static text for a model without vision, or the window's "not included" text.
764
770
  */
765
- const readBlocks = (media) => media.flatMap((m) => {
771
+ const readBlocks = (toolKey, media) => media.flatMap((m) => {
766
772
  const id = m.attachmentId;
767
773
  const note = (text, outcome) => {
768
774
  if (!mediaOutcomes.has(id))
@@ -771,14 +777,14 @@ export function buildModelRequest(input) {
771
777
  };
772
778
  if (!model.capabilities.vision) {
773
779
  return [
774
- { type: "text", text: readImageLabelText(id) },
775
- ...note(READ_IMAGE_NO_VISION_TEXT, "placeholder_unsupported"),
780
+ { type: "text", text: readImageLabelText(toolKey, id) },
781
+ ...note(readImageNoVisionText(toolKey, id), "placeholder_unsupported"),
776
782
  ];
777
783
  }
778
784
  if (mediaCtx.plan.notIncluded.has(id)) {
779
- return note(readImageNotIncludedText(id), "not_included");
785
+ return note(readImageNotIncludedText(toolKey, id), "not_included");
780
786
  }
781
- return [{ type: "text", text: readImageLabelText(id) }, ...blocksOf([readBlock(m)])];
787
+ return [{ type: "text", text: readImageLabelText(toolKey, id) }, ...blocksOf([readBlock(m)])];
782
788
  });
783
789
  /** Whether the request renders an image from Read (the window is then recorded). */
784
790
  let hasReadImages = false;
@@ -891,7 +897,7 @@ export function buildModelRequest(input) {
891
897
  });
892
898
  if (r.media !== undefined && r.media.length > 0) {
893
899
  hasReadImages = true;
894
- images.push(...readBlocks(r.media));
900
+ images.push(...readBlocks(r.toolKey, r.media));
895
901
  }
896
902
  }
897
903
  }
@@ -1,6 +1,6 @@
1
1
  import { type LocalizedName, type ToolDisplay } from "@capybara-hq/plugin-sdk";
2
2
  import { EventLog } from "../conversations/event-log.js";
3
- import { type ReviewRecord, type ToolView } from "../conversations/events.js";
3
+ import { type EventPayload, type ReviewRecord, type ToolView } from "../conversations/events.js";
4
4
  import { ConversationLeakCheck } from "../conversations/leak-check.js";
5
5
  import { DevicesService } from "../devices/devices.service.js";
6
6
  import { type PersonRef } from "../identity/account-avatar.js";
@@ -43,6 +43,8 @@ export interface KeptToolResult {
43
43
  contentTypes?: string[];
44
44
  display?: ToolDisplay;
45
45
  view?: ToolView;
46
+ /** The stored images of the result (`tool_result.media`), written with it when the ask settles. */
47
+ media?: NonNullable<EventPayload<"tool_result">["media"]>;
46
48
  /** The command review's decision, kept with the result (display only). */
47
49
  review?: ReviewRecord;
48
50
  /**
@@ -5,6 +5,11 @@ import type { StorageService } from "../../storage/storage.service.js";
5
5
  export interface ConversationFile {
6
6
  kind: "attachment" | "artifact";
7
7
  id: string;
8
+ /**
9
+ * For a `read` copy (an image a tool showed the agent), the conversation it is bound to: a
10
+ * `Read` of a copy that is already the calling conversation's needs no new copy.
11
+ */
12
+ readCopyOf?: string;
8
13
  name: string;
9
14
  contentType: string;
10
15
  size: number;
@@ -25,11 +30,12 @@ export interface ConversationFileDeps {
25
30
  storage: Pick<StorageService, "kernel">;
26
31
  }
27
32
  /**
28
- * A file of the conversation by id, always inside `orgId`: an attachment 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
+ * A file of the conversation by id, always inside `orgId`: an attachment (a `chat` attachment or
34
+ * a `read` copy: this lookup is the model's, vision-read design §1.1) or an `artifact_created`
35
+ * event of the conversation, of its root, or of a sub-agent conversation below the conversation
36
+ * (so a parent reaches an image its sub-agent's tool returned; tool result images design §5).
37
+ * Anything else (a sibling's or another tree's, another org's, a missing object, an id that is
38
+ * not a UUID) is `null`. Storage errors are thrown as they are. `signal` aborts the storage reads.
33
39
  */
34
40
  export declare function findConversationFile(deps: ConversationFileDeps, q: {
35
41
  orgId: string;