@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
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": "84a5307e2757bd4fc1f9f11b43be456b63f0f9c7"
6
+ "commit": "fa745394ab347eeb1d59d2ba185328c2088a7e8b"
7
7
  },
8
8
  "plugins": [
9
9
  {
@@ -58,8 +58,8 @@
58
58
  "name": "ark",
59
59
  "source": "npm",
60
60
  "npm": "@capybara-hq/plugin-ark",
61
- "version": "0.1.0-rc.10",
62
- "integrity": "sha512-8SRYcBBb/wROJX8ByBisL/SKNg7z4RvWFq8X7L+944QBzSed4YHwNATLRDTL4pW1l6VIC2rr+0DeSBCjmsF4Qw==",
61
+ "version": "0.1.0-rc.11",
62
+ "integrity": "sha512-rE0tPudbL0AjY9f6cTdM0wSFtyhWsKOaEFy6GOZ79wISw9F5Y0ap3RVaiaeW9c0lZPxKdhqIzi18xARu/A1jVQ==",
63
63
  "required": false
64
64
  },
65
65
  {
@@ -106,8 +106,8 @@
106
106
  "name": "skills-core",
107
107
  "source": "npm",
108
108
  "npm": "@capybara-hq/plugin-skills-core",
109
- "version": "0.1.0-rc.1",
110
- "integrity": "sha512-eIad/YOTGMAjOQPEVrN6jfq/WHhpJUn5FifbELnFmRij1yo+mI4b/5/72DZ0cjsRXFWhUODen2IPmhYH/YZqWQ==",
109
+ "version": "0.1.0-rc.2",
110
+ "integrity": "sha512-I0jlrKU+bqiGRW65jVLftT2S5Oa4QVaG1hDr6+1TT8gtAMjOkl87lNNrWJFHeOvp1bJBbx6ccLGffSUVesHqlA==",
111
111
  "required": false,
112
112
  "builtin": true
113
113
  },
@@ -188,7 +188,7 @@ export declare function headsToResolve(entries: readonly MarketplaceEntry[], imp
188
188
  /** The host versions (an entry's `minKernel` is judged against them). */
189
189
  export declare const HOST_VERSIONS: {
190
190
  readonly kernel: string;
191
- readonly sdk: "0.1.0-rc.36";
191
+ readonly sdk: "0.1.0-rc.37";
192
192
  };
193
193
  /** Whether this deployment satisfies the entry's `minKernel`. */
194
194
  export declare const entryCompatible: (e: Pick<MarketplaceEntry, "minKernel">) => boolean;
@@ -191,6 +191,9 @@ export declare const KernelConfigSchema: z.ZodObject<{
191
191
  maxPerMessage: z.ZodDefault<z.ZodNumber>;
192
192
  unboundTtlHours: z.ZodDefault<z.ZodNumber>;
193
193
  requestMediaBytes: z.ZodDefault<z.ZodNumber>;
194
+ readImagesPerRequest: z.ZodDefault<z.ZodNumber>;
195
+ readMaxBytesPerConversation: z.ZodDefault<z.ZodNumber>;
196
+ readPurgeAfterHours: z.ZodDefault<z.ZodNumber>;
194
197
  }, z.core.$strict>>;
195
198
  sharing: z.ZodPrefault<z.ZodObject<{
196
199
  external: z.ZodOptional<z.ZodEnum<{
@@ -293,6 +296,9 @@ export declare const KernelConfigSchema: z.ZodObject<{
293
296
  imageTimeoutMs: z.ZodDefault<z.ZodNumber>;
294
297
  imageMaxPerCall: z.ZodDefault<z.ZodNumber>;
295
298
  imagePromptMaxChars: z.ZodDefault<z.ZodNumber>;
299
+ imageStandardPixels: z.ZodDefault<z.ZodNumber>;
300
+ visionTimeoutMs: z.ZodDefault<z.ZodNumber>;
301
+ visionMaxOutputTokens: z.ZodDefault<z.ZodNumber>;
296
302
  }, z.core.$strict>>;
297
303
  hooks: z.ZodPrefault<z.ZodObject<{
298
304
  timeoutMs: z.ZodDefault<z.ZodNumber>;
@@ -1151,6 +1151,36 @@ export const KernelConfigSchema = z.strictObject({
1151
1151
  .meta(meta({
1152
1152
  description: "Budget of raw attachment bytes in one model request; the newest attachments are kept and older ones are replaced with a placeholder. At most 24 MiB: base64 inflates it by about 4/3, and common providers cap a request at 32 MB",
1153
1153
  })),
1154
+ readImagesPerRequest: z
1155
+ .number()
1156
+ .int()
1157
+ .min(2)
1158
+ .max(20)
1159
+ .default(6)
1160
+ .meta(meta({
1161
+ hot: true,
1162
+ description: "Most images Read may show the model in one request; older Read images are replaced with a placeholder",
1163
+ })),
1164
+ readMaxBytesPerConversation: z
1165
+ .number()
1166
+ .int()
1167
+ .min(0)
1168
+ .max(17_179_869_184)
1169
+ .default(536_870_912)
1170
+ .meta(meta({
1171
+ hot: true,
1172
+ 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",
1173
+ })),
1174
+ readPurgeAfterHours: z
1175
+ .number()
1176
+ .int()
1177
+ .min(1)
1178
+ .max(720)
1179
+ .default(24)
1180
+ .meta(meta({
1181
+ hot: true,
1182
+ description: "Hours after a conversation is deleted before its Read image copies are purged (row and object)",
1183
+ })),
1154
1184
  })
1155
1185
  // 单个附件不能大于单次请求的预算:否则它永远被省略(最新的附件总能放进请求)
1156
1186
  .refine((c) => c.maxBytes <= c.requestMediaBytes, {
@@ -1742,6 +1772,36 @@ export const KernelConfigSchema = z.strictObject({
1742
1772
  hot: true,
1743
1773
  description: "Longest prompt, in characters (code points), an image generation call accepts; longer is a validation error",
1744
1774
  })),
1775
+ imageStandardPixels: z
1776
+ .number()
1777
+ .int()
1778
+ .min(262_144)
1779
+ .max(16_777_216)
1780
+ .default(1_048_576)
1781
+ .meta(meta({
1782
+ hot: true,
1783
+ description: "Target pixel area (width times height) of a standard-resolution GenerateImage size: the model's size closest to it for the requested shape",
1784
+ })),
1785
+ visionTimeoutMs: z
1786
+ .number()
1787
+ .int()
1788
+ .min(5_000)
1789
+ .max(600_000)
1790
+ .default(120_000)
1791
+ .meta(meta({
1792
+ hot: true,
1793
+ description: "Milliseconds a vision model call for Read may take before it is aborted",
1794
+ })),
1795
+ visionMaxOutputTokens: z
1796
+ .number()
1797
+ .int()
1798
+ .min(100)
1799
+ .max(16_000)
1800
+ .default(2_000)
1801
+ .meta(meta({
1802
+ hot: true,
1803
+ description: "Most tokens a vision model may answer with when it reads an image for Read",
1804
+ })),
1745
1805
  })
1746
1806
  .prefault({}),
1747
1807
  hooks: z
@@ -45,6 +45,17 @@ export declare const AGENT_AVATAR_DOWNLOAD_TTL_SECONDS = 300;
45
45
  export declare const skillFilesPrefix: (uploadId: string) => string;
46
46
  /** 周期任务:每小时清理过期未绑定的附件(`@LockedCron`)。 */
47
47
  export declare const ATTACHMENT_CLEANUP_JOB = "attachment-cleanup";
48
+ /** The hourly purge of `read` copies whose conversation was deleted long enough ago. */
49
+ export declare const ATTACHMENT_READ_PURGE_JOB = "attachments-read-purge";
50
+ /** {@link AttachmentsService.storeRead}'s result: the bound copy, or refused by the cap. */
51
+ export type StoreReadResult = {
52
+ ok: true;
53
+ attachmentId: string;
54
+ size: number;
55
+ } | {
56
+ ok: false;
57
+ reason: "cap";
58
+ };
48
59
  /** 附件元数据(finalize 的返回)。 */
49
60
  export interface AttachmentView {
50
61
  id: string;
@@ -172,9 +183,11 @@ export declare class AttachmentsService {
172
183
  /**
173
184
  * The ready `chat` attachments bound to the conversation in this org (never another purpose, a
174
185
  * pending or an unbound upload), oldest first by upload time, then id; with `id`, only that one.
175
- * Nothing here checks who reads them: callers check the conversation's access first.
186
+ * Nothing here checks who reads them: callers check the conversation's access first. `purposes`
187
+ * widens it for a model-facing lookup only (`read` copies; vision-read design §1.1): every
188
+ * person- or device-facing caller keeps the default.
176
189
  */
177
- boundRows(orgId: string, conversationId: string, id?: string): Promise<BoundAttachment[]>;
190
+ boundRows(orgId: string, conversationId: string, id?: string, purposes?: readonly ("chat" | "read")[]): Promise<BoundAttachment[]>;
178
191
  /**
179
192
  * {@link attachmentContentMatches} for a bound attachment's stored object (`null`: gone), with
180
193
  * the warning logged when the content was replaced after finalize.
@@ -190,7 +203,16 @@ export declare class AttachmentsService {
190
203
  * 读取一个绑定在该会话、已 ready 的附件(沙箱同步等内核内部用途):没有行、未绑定到该会话、对象已不在、
191
204
  * 大小或 etag 与 finalize 时不符 → null。其余错误(存储不可用等)照常抛出。调用方负责读完或取消 `body`。
192
205
  */
193
- openForConversation(orgId: string, conversationId: string, attachmentId: string): Promise<OpenedAttachment | null>;
206
+ openForConversation(orgId: string, conversationId: string, attachmentId: string, opts?: {
207
+ /**
208
+ * Also `read` copies (the model-facing file lookup only, vision-read design §1.1); the
209
+ * default is `chat` attachments, which is all a person or a device may see.
210
+ */
211
+ purposes?: readonly ("chat" | "read")[];
212
+ /** Read at most this many bytes (a range read; a store that ignores it serves the whole). */
213
+ maxBytes?: number;
214
+ signal?: AbortSignal;
215
+ }): Promise<OpenedAttachment | null>;
194
216
  /**
195
217
  * 发消息时在调用方事务里绑定附件(行锁),返回写进 user_message 的媒体块(`ref`,按 ids 顺序):
196
218
  * - 超过 `attachments.maxPerMessage`、或同一个 id 出现多次 → `validation_failed`;
@@ -203,14 +225,18 @@ export declare class AttachmentsService {
203
225
  /** 下载 / 取字节时核对 etag:finalize 记下的与当前对象的不一致 → 内容被替换(记 warn)。没有记录时不核对。 */
204
226
  private sameContent;
205
227
  /**
206
- * 构建模型请求时查附件行的声明信息(只含绑定在该会话、已 ready 的):大小、PDF 页数,以及对象的无签名引用
207
- * (`ObjectStore.uri`,存储没有时退回 `capybara://attachments/<id>`)。没有行的不在结果里;查询失败照常抛出。
228
+ * The recorded facts request building needs about attachments (only ready `chat` or `read` rows
229
+ * bound to this conversation): size, PDF page count, and the object's unsigned reference
230
+ * (`ObjectStore.uri`, falling back to `capybara://attachments/<id>`). An id with no row is left
231
+ * out; a failed query throws.
208
232
  */
209
233
  mediaInfo(orgId: string, conversationId: string, ids: readonly string[]): Promise<Map<string, MediaInfo>>;
210
234
  /**
211
- * 构建模型请求时取附件字节:只取绑定在该会话、已 ready 的附件。只有「确定不存在」才为 null:没有行、对象已不在、
212
- * 大小或 etag 与 finalize 时不符(内容被替换,记 warn)。其余错误(存储不可用、网络错误)一律抛出(Ruling M4),
213
- * 由调用方按可重试处理,不会变成占位。`caps` 里的附件只按范围读开头若干字节(`text/*` 封顶,更后面的不取)。
235
+ * The bytes request building sends, only of ready `chat` or `read` rows bound to this
236
+ * conversation. Null only when certainly gone: no row, the object missing, or its size or etag
237
+ * not the recorded one (content replaced, logged as a warning). Every other error (storage
238
+ * unavailable, network) throws (Ruling M4) for the caller to treat as retryable, never a
239
+ * placeholder. An id in `caps` is read by range up to that many leading bytes (the `text/*` cap).
214
240
  */
215
241
  fetchMedia(orgId: string, conversationId: string, ids: readonly string[], caps?: ReadonlyMap<string, number>): Promise<Map<string, MediaBytes | null>>;
216
242
  /**
@@ -245,6 +271,43 @@ export declare class AttachmentsService {
245
271
  * to `agentId`; `null` when there is none or its object is gone or no longer the finalized one.
246
272
  */
247
273
  agentAvatarUrl(orgId: string, agentId: string, id: string): Promise<string | null>;
274
+ /**
275
+ * Stores the copy of an image the builtin Read read, bound to the calling conversation (never its
276
+ * root), intent first so a crash leaves nothing unowned (vision-read design §1.3):
277
+ * 1. the per-conversation cap `attachments.readMaxBytesPerConversation` (the sizes of the
278
+ * conversation's `read` rows plus this one; 0 refuses always) → `{ ok: false, reason: "cap" }`,
279
+ * nothing stored. Concurrent calls may pass it together: a soft cap;
280
+ * 2. the row, unbound, `pending`, expiring after `attachments.unboundTtlHours`, so
281
+ * {@link deleteExpired} collects it after a crash; with no `accountId` (a run nobody started)
282
+ * it is the conversation owner's;
283
+ * 3. the object under `read-images/<id>` (a failed put throws and leaves the row to expire);
284
+ * 4. one transaction binding it: the conversation, `ready`, no expiry, the stored size and etag.
285
+ * No object store → `storage.unavailable`. A conversation not in the org → an error, nothing stored.
286
+ */
287
+ storeRead(orgId: string, conversationId: string, accountId: string | null, file: {
288
+ name: string;
289
+ contentType: string;
290
+ data: Uint8Array;
291
+ }): Promise<StoreReadResult>;
292
+ /**
293
+ * Step 2 of {@link storeRead}: the unbound intent row, in its own transaction so it is committed
294
+ * before the put even when the caller holds one (a rollback must never leave an object with no
295
+ * row). The INSERT ... SELECT proves the conversation is in the org; with no `accountId` the row
296
+ * is the conversation owner's.
297
+ */
298
+ private insertReadIntent;
299
+ /** Step 4 of {@link storeRead}: binds the unbound row in one transaction. */
300
+ private bindRead;
301
+ /**
302
+ * Purges the `read` copies of conversations deleted more than `attachments.readPurgeAfterHours`
303
+ * ago (read at run time), and of the sub-agent conversations below them (a sub-agent
304
+ * conversation keeps `deleted_at` null when its root is deleted): claims up to
305
+ * {@link READ_PURGE_BATCH} rows at a time as `deleting` (`FOR UPDATE SKIP LOCKED`, so concurrent
306
+ * runs never share a row), deletes each object, then the row. A row whose object delete fails stays `deleting` and is claimed again on the next run.
307
+ * Chat attachments of deleted conversations are not touched. Does nothing without an object
308
+ * store. Returns the number of rows deleted.
309
+ */
310
+ purgeRead(): Promise<number>;
248
311
  /**
249
312
  * 删除过期(`expires_at < now()`)且从未绑定到会话的附件:先把行认领为 `deleting`(`FOR UPDATE SKIP LOCKED`,
250
313
  * 多副本并发时互不重复),再删对象、删行。删对象失败的行保持 `deleting`,下次运行重试。
@@ -254,11 +317,16 @@ export declare class AttachmentsService {
254
317
  */
255
318
  deleteExpired(): Promise<number>;
256
319
  }
257
- /** The hourly cleanup of expired unbound attachments, once per tick across replicas. */
320
+ /**
321
+ * The hourly attachment jobs, each once per tick across replicas (provided only under
322
+ * `WorkerModule`): the cleanup of expired unbound attachments and the purge of `read` copies of
323
+ * deleted conversations.
324
+ */
258
325
  export declare class AttachmentCleanupJob {
259
326
  private readonly attachments;
260
327
  readonly lockService: LockService;
261
328
  readonly log: KernelLogger;
262
- constructor(attachments: Pick<AttachmentsService, "deleteExpired">, lockService: LockService, log: KernelLogger);
329
+ constructor(attachments: Pick<AttachmentsService, "deleteExpired" | "purgeRead">, lockService: LockService, log: KernelLogger);
263
330
  run(): Promise<void>;
331
+ purgeRead(): Promise<void>;
264
332
  }
@@ -60,6 +60,15 @@ export const skillFilesPrefix = (uploadId) => `skills/${uploadId}/`;
60
60
  export const ATTACHMENT_CLEANUP_JOB = "attachment-cleanup";
61
61
  /** 每批认领的行数。 */
62
62
  const CLEANUP_BATCH = 100;
63
+ /** The hourly purge of `read` copies whose conversation was deleted long enough ago. */
64
+ export const ATTACHMENT_READ_PURGE_JOB = "attachments-read-purge";
65
+ /** Rows one claim of the read purge takes. */
66
+ const READ_PURGE_BATCH = 500;
67
+ /**
68
+ * How many sub-agent levels below a deleted conversation the read purge walks (the bound of
69
+ * `conversations/tree.ts`: far above `subagents.maxDepth`, so a corrupt chain cannot loop).
70
+ */
71
+ const READ_PURGE_TREE_LEVELS = 16;
63
72
  /** finalize 时读取开头多少字节核对文件签名。 */
64
73
  const SNIFF_BYTES = 1024;
65
74
  /**
@@ -70,14 +79,24 @@ export function attachmentContentMatches(recorded, head) {
70
79
  return head.size === recorded.size && (recorded.etag === null || recorded.etag === head.etag);
71
80
  }
72
81
  const notFound = () => new ApiError("attachment.not_found", "Attachment not found");
82
+ /**
83
+ * The purposes request building reads bytes of: chat attachments and the `read` copies of the
84
+ * builtin Read. Every other lookup (listing, sandbox sync, download, binding) stays `chat` only.
85
+ */
86
+ const MEDIA_PURPOSES = ["chat", "read"];
73
87
  /** 去掉参数、转小写:`Text/Plain; charset=utf-8` → `text/plain`。 */
74
88
  export const normalizeContentType = (ct) => (ct.split(";")[0] ?? "").trim().toLowerCase();
75
- /** 对象键:只用附件 id,用户的文件名不进键。技能包另放 `skill-packages/<id>`。 */
89
+ /**
90
+ * The object key: the attachment id only (the user's file name never goes into a key), under one
91
+ * prefix per purpose.
92
+ */
76
93
  const objectKey = (id, purpose = "chat") => purpose === "chat"
77
94
  ? `attachments/${id}`
78
95
  : purpose === "agent-avatar"
79
96
  ? `agent-avatars/${id}`
80
- : `skill-packages/${id}`;
97
+ : purpose === "read"
98
+ ? `read-images/${id}`
99
+ : `skill-packages/${id}`;
81
100
  const startsWith = (b, sig, at = 0) => sig.every((x, i) => b[at + i] === x);
82
101
  const ascii = (s) => [...s].map((c) => c.charCodeAt(0));
83
102
  /**
@@ -251,6 +270,8 @@ let AttachmentsService = class AttachmentsService {
251
270
  .where("org_id", "=", orgId)
252
271
  .where("account_id", "=", accountId)
253
272
  .where("status", "in", ["pending", "ready"])
273
+ // read copies are the kernel's own (storeRead binds them); nobody finalizes them
274
+ .where("purpose", "<>", "read")
254
275
  .executeTakeFirst();
255
276
  if (!row)
256
277
  throw notFound();
@@ -347,15 +368,17 @@ let AttachmentsService = class AttachmentsService {
347
368
  /**
348
369
  * The ready `chat` attachments bound to the conversation in this org (never another purpose, a
349
370
  * pending or an unbound upload), oldest first by upload time, then id; with `id`, only that one.
350
- * Nothing here checks who reads them: callers check the conversation's access first.
371
+ * Nothing here checks who reads them: callers check the conversation's access first. `purposes`
372
+ * widens it for a model-facing lookup only (`read` copies; vision-read design §1.1): every
373
+ * person- or device-facing caller keeps the default.
351
374
  */
352
- async boundRows(orgId, conversationId, id) {
375
+ async boundRows(orgId, conversationId, id, purposes = ["chat"]) {
353
376
  let q = this.db
354
377
  .selectFrom("attachments")
355
378
  .select(["id", "name", "content_type", "size", "object_key", "etag", "created_at"])
356
379
  .where("org_id", "=", orgId)
357
380
  .where("conversation_id", "=", conversationId)
358
- .where("purpose", "=", "chat")
381
+ .where("purpose", "in", [...purposes])
359
382
  .where("status", "=", "ready");
360
383
  if (id !== undefined)
361
384
  q = q.where("id", "=", id);
@@ -389,11 +412,16 @@ let AttachmentsService = class AttachmentsService {
389
412
  * 读取一个绑定在该会话、已 ready 的附件(沙箱同步等内核内部用途):没有行、未绑定到该会话、对象已不在、
390
413
  * 大小或 etag 与 finalize 时不符 → null。其余错误(存储不可用等)照常抛出。调用方负责读完或取消 `body`。
391
414
  */
392
- async openForConversation(orgId, conversationId, attachmentId) {
393
- const [row] = await this.boundRows(orgId, conversationId, attachmentId);
415
+ async openForConversation(orgId, conversationId, attachmentId, opts = {}) {
416
+ const [row] = await this.boundRows(orgId, conversationId, attachmentId, opts.purposes);
394
417
  if (!row)
395
418
  return null;
396
- const got = await this.storage.kernel(orgId).get(row.objectKey);
419
+ const got = await this.storage.kernel(orgId).get(row.objectKey, {
420
+ ...(opts.signal !== undefined && { signal: opts.signal }),
421
+ // only a larger object is ranged (a range on an empty object is unsatisfiable)
422
+ ...(opts.maxBytes !== undefined &&
423
+ row.size > opts.maxBytes && { range: { start: 0, end: opts.maxBytes - 1 } }),
424
+ });
397
425
  if (!got)
398
426
  return null;
399
427
  if (!this.storedMatches(row, got.head, { orgId, conversationId })) {
@@ -507,8 +535,10 @@ let AttachmentsService = class AttachmentsService {
507
535
  return false;
508
536
  }
509
537
  /**
510
- * 构建模型请求时查附件行的声明信息(只含绑定在该会话、已 ready 的):大小、PDF 页数,以及对象的无签名引用
511
- * (`ObjectStore.uri`,存储没有时退回 `capybara://attachments/<id>`)。没有行的不在结果里;查询失败照常抛出。
538
+ * The recorded facts request building needs about attachments (only ready `chat` or `read` rows
539
+ * bound to this conversation): size, PDF page count, and the object's unsigned reference
540
+ * (`ObjectStore.uri`, falling back to `capybara://attachments/<id>`). An id with no row is left
541
+ * out; a failed query throws.
512
542
  */
513
543
  async mediaInfo(orgId, conversationId, ids) {
514
544
  if (ids.length === 0)
@@ -518,7 +548,7 @@ let AttachmentsService = class AttachmentsService {
518
548
  .select(["id", "size", "pages", "etag", "object_key"])
519
549
  .where("org_id", "=", orgId)
520
550
  .where("conversation_id", "=", conversationId)
521
- .where("purpose", "=", "chat")
551
+ .where("purpose", "in", MEDIA_PURPOSES)
522
552
  .where("status", "=", "ready")
523
553
  .where("id", "in", [...ids])
524
554
  .execute();
@@ -534,9 +564,11 @@ let AttachmentsService = class AttachmentsService {
534
564
  ]));
535
565
  }
536
566
  /**
537
- * 构建模型请求时取附件字节:只取绑定在该会话、已 ready 的附件。只有「确定不存在」才为 null:没有行、对象已不在、
538
- * 大小或 etag 与 finalize 时不符(内容被替换,记 warn)。其余错误(存储不可用、网络错误)一律抛出(Ruling M4),
539
- * 由调用方按可重试处理,不会变成占位。`caps` 里的附件只按范围读开头若干字节(`text/*` 封顶,更后面的不取)。
567
+ * The bytes request building sends, only of ready `chat` or `read` rows bound to this
568
+ * conversation. Null only when certainly gone: no row, the object missing, or its size or etag
569
+ * not the recorded one (content replaced, logged as a warning). Every other error (storage
570
+ * unavailable, network) throws (Ruling M4) for the caller to treat as retryable, never a
571
+ * placeholder. An id in `caps` is read by range up to that many leading bytes (the `text/*` cap).
540
572
  */
541
573
  async fetchMedia(orgId, conversationId, ids, caps) {
542
574
  const out = new Map();
@@ -547,7 +579,7 @@ let AttachmentsService = class AttachmentsService {
547
579
  .select(["id", "content_type", "object_key", "size", "etag"])
548
580
  .where("org_id", "=", orgId)
549
581
  .where("conversation_id", "=", conversationId)
550
- .where("purpose", "=", "chat")
582
+ .where("purpose", "in", MEDIA_PURPOSES)
551
583
  .where("status", "=", "ready")
552
584
  .where("id", "in", [...ids])
553
585
  .execute();
@@ -733,6 +765,173 @@ let AttachmentsService = class AttachmentsService {
733
765
  responseContentType: row.content_type,
734
766
  });
735
767
  }
768
+ /**
769
+ * Stores the copy of an image the builtin Read read, bound to the calling conversation (never its
770
+ * root), intent first so a crash leaves nothing unowned (vision-read design §1.3):
771
+ * 1. the per-conversation cap `attachments.readMaxBytesPerConversation` (the sizes of the
772
+ * conversation's `read` rows plus this one; 0 refuses always) → `{ ok: false, reason: "cap" }`,
773
+ * nothing stored. Concurrent calls may pass it together: a soft cap;
774
+ * 2. the row, unbound, `pending`, expiring after `attachments.unboundTtlHours`, so
775
+ * {@link deleteExpired} collects it after a crash; with no `accountId` (a run nobody started)
776
+ * it is the conversation owner's;
777
+ * 3. the object under `read-images/<id>` (a failed put throws and leaves the row to expire);
778
+ * 4. one transaction binding it: the conversation, `ready`, no expiry, the stored size and etag.
779
+ * No object store → `storage.unavailable`. A conversation not in the org → an error, nothing stored.
780
+ */
781
+ async storeRead(orgId, conversationId, accountId, file) {
782
+ this.storage.assertAvailable();
783
+ const size = file.data.byteLength;
784
+ const cap = this.config.get().attachments.readMaxBytesPerConversation;
785
+ if (cap === 0)
786
+ return { ok: false, reason: "cap" };
787
+ const used = await this.db
788
+ .selectFrom("attachments")
789
+ .select(sql `coalesce(sum(size), 0)`.as("n"))
790
+ .where("org_id", "=", orgId)
791
+ .where("conversation_id", "=", conversationId)
792
+ .where("purpose", "=", "read")
793
+ .executeTakeFirst();
794
+ if (Number(used?.n ?? 0) + size > cap)
795
+ return { ok: false, reason: "cap" };
796
+ const id = randomUUID();
797
+ const key = objectKey(id, "read");
798
+ const contentType = normalizeContentType(file.contentType);
799
+ await this.insertReadIntent(orgId, conversationId, accountId, {
800
+ id,
801
+ key,
802
+ name: file.name,
803
+ contentType,
804
+ size,
805
+ });
806
+ const head = await this.storage
807
+ .kernel(orgId)
808
+ .put(key, file.data, { contentType: contentType || "application/octet-stream" });
809
+ await this.bindRead(id, conversationId, head.size, head.etag ?? null);
810
+ return { ok: true, attachmentId: id, size: head.size };
811
+ }
812
+ /**
813
+ * Step 2 of {@link storeRead}: the unbound intent row, in its own transaction so it is committed
814
+ * before the put even when the caller holds one (a rollback must never leave an object with no
815
+ * row). The INSERT ... SELECT proves the conversation is in the org; with no `accountId` the row
816
+ * is the conversation owner's.
817
+ */
818
+ async insertReadIntent(orgId, conversationId, accountId, r) {
819
+ const { unboundTtlHours } = this.config.get().attachments;
820
+ const inserted = await this.db.db
821
+ .insertInto("attachments")
822
+ .columns([
823
+ "id",
824
+ "org_id",
825
+ "account_id",
826
+ "name",
827
+ "content_type",
828
+ "size",
829
+ "object_key",
830
+ "status",
831
+ "purpose",
832
+ "expires_at",
833
+ ])
834
+ .expression((eb) => eb
835
+ .selectFrom("conversations")
836
+ .select([
837
+ sql.val(r.id).as("id"),
838
+ "org_id",
839
+ accountId === null ? "account_id" : sql.val(accountId).as("account_id"),
840
+ sql.val(r.name).as("name"),
841
+ sql.val(r.contentType).as("content_type"),
842
+ sql.val(r.size).as("size"),
843
+ sql.val(r.key).as("object_key"),
844
+ sql.lit("pending").as("status"),
845
+ sql.lit("read").as("purpose"),
846
+ sql `now() + make_interval(hours => ${unboundTtlHours})`.as("expires_at"),
847
+ ])
848
+ .where("id", "=", conversationId)
849
+ .where("org_id", "=", orgId))
850
+ .executeTakeFirst();
851
+ if (Number(inserted.numInsertedOrUpdatedRows ?? 0) !== 1) {
852
+ throw new Error(`conversation ${conversationId} not found in org ${orgId}`);
853
+ }
854
+ }
855
+ /** Step 4 of {@link storeRead}: binds the unbound row in one transaction. */
856
+ async bindRead(id, conversationId, size, etag) {
857
+ const bound = await this.db.db
858
+ .updateTable("attachments")
859
+ .set({ conversation_id: conversationId, status: "ready", expires_at: null, size, etag })
860
+ .where("id", "=", id)
861
+ .where("purpose", "=", "read")
862
+ .where("status", "=", "pending")
863
+ .where("conversation_id", "is", null)
864
+ .executeTakeFirst();
865
+ if (Number(bound.numUpdatedRows) !== 1) {
866
+ throw new Error(`read attachment ${id} is no longer pending; cannot bind it`);
867
+ }
868
+ }
869
+ /**
870
+ * Purges the `read` copies of conversations deleted more than `attachments.readPurgeAfterHours`
871
+ * ago (read at run time), and of the sub-agent conversations below them (a sub-agent
872
+ * conversation keeps `deleted_at` null when its root is deleted): claims up to
873
+ * {@link READ_PURGE_BATCH} rows at a time as `deleting` (`FOR UPDATE SKIP LOCKED`, so concurrent
874
+ * runs never share a row), deletes each object, then the row. A row whose object delete fails stays `deleting` and is claimed again on the next run.
875
+ * Chat attachments of deleted conversations are not touched. Does nothing without an object
876
+ * store. Returns the number of rows deleted.
877
+ */
878
+ async purgeRead() {
879
+ if (!this.storage.available)
880
+ return 0;
881
+ const hours = this.config.get().attachments.readPurgeAfterHours;
882
+ let deleted = 0;
883
+ const failed = [];
884
+ for (;;) {
885
+ const claimed = await this.db
886
+ .updateTable("attachments")
887
+ .set({ status: "deleting" })
888
+ .where("id", "in", this.db
889
+ .selectFrom("attachments")
890
+ .select("id")
891
+ .where("purpose", "=", "read")
892
+ .where("conversation_id", "in", sql `(
893
+ WITH RECURSIVE gone(id, level) AS (
894
+ SELECT c.id, 0 FROM capybara.conversations c
895
+ WHERE c.deleted_at < now() - make_interval(hours => ${hours})
896
+ UNION ALL
897
+ SELECT c.id, g.level + 1
898
+ FROM capybara.conversations c JOIN gone g ON c.parent_conversation_id = g.id
899
+ WHERE c.kind = 'subagent' AND g.level < ${READ_PURGE_TREE_LEVELS}
900
+ )
901
+ SELECT id FROM gone
902
+ )`)
903
+ .$if(failed.length > 0, (q) => q.where("id", "not in", failed))
904
+ .orderBy("created_at")
905
+ .limit(READ_PURGE_BATCH)
906
+ .forUpdate()
907
+ .skipLocked())
908
+ .returning(["id", "org_id", "object_key"])
909
+ .execute();
910
+ if (claimed.length === 0)
911
+ return deleted;
912
+ for (const r of claimed) {
913
+ try {
914
+ await this.storage.kernel(r.org_id).delete(r.object_key);
915
+ await this.db
916
+ .deleteFrom("attachments")
917
+ .where("id", "=", r.id)
918
+ .where("purpose", "=", "read")
919
+ .execute();
920
+ deleted++;
921
+ }
922
+ catch (err) {
923
+ failed.push(r.id);
924
+ this.log.warn("cannot purge read attachment; will retry", {
925
+ orgId: r.org_id,
926
+ attachmentId: r.id,
927
+ err,
928
+ });
929
+ }
930
+ }
931
+ if (claimed.length < READ_PURGE_BATCH)
932
+ return deleted;
933
+ }
934
+ }
736
935
  /**
737
936
  * 删除过期(`expires_at < now()`)且从未绑定到会话的附件:先把行认领为 `deleting`(`FOR UPDATE SKIP LOCKED`,
738
937
  * 多副本并发时互不重复),再删对象、删行。删对象失败的行保持 `deleting`,下次运行重试。
@@ -808,6 +1007,12 @@ __decorate([
808
1007
  __decorate([
809
1008
  Transactional({ propagation: "mandatory" })
810
1009
  ], AttachmentsService.prototype, "consumeAgentAvatar", null);
1010
+ __decorate([
1011
+ Transactional({ propagation: "requires_new" })
1012
+ ], AttachmentsService.prototype, "insertReadIntent", null);
1013
+ __decorate([
1014
+ Transactional()
1015
+ ], AttachmentsService.prototype, "bindRead", null);
811
1016
  AttachmentsService = __decorate([
812
1017
  Injectable(),
813
1018
  __param(0, Inject(KernelDb)),
@@ -818,7 +1023,11 @@ AttachmentsService = __decorate([
818
1023
  __param(5, Inject(TransactionHost))
819
1024
  ], AttachmentsService);
820
1025
  export { AttachmentsService };
821
- /** The hourly cleanup of expired unbound attachments, once per tick across replicas. */
1026
+ /**
1027
+ * The hourly attachment jobs, each once per tick across replicas (provided only under
1028
+ * `WorkerModule`): the cleanup of expired unbound attachments and the purge of `read` copies of
1029
+ * deleted conversations.
1030
+ */
822
1031
  let AttachmentCleanupJob = class AttachmentCleanupJob {
823
1032
  attachments;
824
1033
  lockService;
@@ -833,10 +1042,18 @@ let AttachmentCleanupJob = class AttachmentCleanupJob {
833
1042
  if (n > 0)
834
1043
  this.log.info("expired attachments deleted", { count: n });
835
1044
  }
1045
+ async purgeRead() {
1046
+ const n = await this.attachments.purgeRead();
1047
+ if (n > 0)
1048
+ this.log.info("read attachments of deleted conversations purged", { count: n });
1049
+ }
836
1050
  };
837
1051
  __decorate([
838
1052
  LockedCron("0 * * * *", { name: ATTACHMENT_CLEANUP_JOB })
839
1053
  ], AttachmentCleanupJob.prototype, "run", null);
1054
+ __decorate([
1055
+ LockedCron("0 * * * *", { name: ATTACHMENT_READ_PURGE_JOB })
1056
+ ], AttachmentCleanupJob.prototype, "purgeRead", null);
840
1057
  AttachmentCleanupJob = __decorate([
841
1058
  Injectable(),
842
1059
  __param(0, Inject(AttachmentsService)),
@@ -824,6 +824,7 @@ export declare const ConversationEventSchema: z.ZodDiscriminatedUnion<[z.ZodObje
824
824
  bytes: "bytes";
825
825
  excluded: "excluded";
826
826
  inline: "inline";
827
+ not_included: "not_included";
827
828
  omitted: "omitted";
828
829
  placeholder_unsupported: "placeholder_unsupported";
829
830
  reference: "reference";
@@ -835,6 +836,7 @@ export declare const ConversationEventSchema: z.ZodDiscriminatedUnion<[z.ZodObje
835
836
  etag: z.ZodOptional<z.ZodString>;
836
837
  }, z.core.$strip>>>;
837
838
  mediaBudgetBytes: z.ZodOptional<z.ZodNumber>;
839
+ readImagesPerRequest: z.ZodOptional<z.ZodNumber>;
838
840
  fit: z.ZodOptional<z.ZodObject<{
839
841
  droppedMessageIndexes: z.ZodArray<z.ZodNumber>;
840
842
  truncated: z.ZodArray<z.ZodObject<{
@@ -944,6 +946,7 @@ export declare const ConversationEventSchema: z.ZodDiscriminatedUnion<[z.ZodObje
944
946
  review: "review";
945
947
  suggestion: "suggestion";
946
948
  title: "title";
949
+ vision: "vision";
947
950
  web_fetch: "web_fetch";
948
951
  }>>;
949
952
  chunk: z.ZodOptional<z.ZodNumber>;
@@ -1191,6 +1194,12 @@ export declare const ConversationEventSchema: z.ZodDiscriminatedUnion<[z.ZodObje
1191
1194
  view: z.ZodString;
1192
1195
  key: z.ZodOptional<z.ZodString>;
1193
1196
  }, z.core.$strip>>;
1197
+ media: z.ZodOptional<z.ZodArray<z.ZodObject<{
1198
+ attachmentId: z.ZodString & z.ZodType<string, string, z.core.$ZodTypeInternals<string, string>>;
1199
+ name: z.ZodString;
1200
+ mediaType: z.ZodString;
1201
+ size: z.ZodNumber;
1202
+ }, z.core.$strip>>>;
1194
1203
  }, z.core.$strip>;
1195
1204
  }, z.core.$strip>, z.ZodObject<{
1196
1205
  type: z.ZodLiteral<"connection_required">;