@capybara-hq/kernel 0.1.0-rc.106 → 0.1.0-rc.108

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 (190) hide show
  1. package/bootstrap.json +13 -13
  2. package/dist/admin/admin.schemas.d.ts +3 -0
  3. package/dist/catalog/marketplaces.service.d.ts +1 -1
  4. package/dist/channels/channels.module.js +4 -3
  5. package/dist/channels/file-delivery.d.ts +26 -11
  6. package/dist/channels/file-delivery.js +32 -11
  7. package/dist/channels/outbound.d.ts +3 -3
  8. package/dist/channels/outbound.js +15 -13
  9. package/dist/config/schema.d.ts +3 -0
  10. package/dist/config/schema.js +12 -0
  11. package/dist/conversations/artifacts.d.ts +20 -17
  12. package/dist/conversations/artifacts.js +30 -37
  13. package/dist/conversations/attachments.controller.d.ts +6 -19
  14. package/dist/conversations/attachments.controller.js +8 -59
  15. package/dist/conversations/attachments.service.d.ts +30 -74
  16. package/dist/conversations/attachments.service.js +51 -193
  17. package/dist/conversations/conversations.module.js +4 -0
  18. package/dist/conversations/conversations.service.d.ts +10 -9
  19. package/dist/conversations/conversations.service.js +28 -11
  20. package/dist/conversations/event-log.d.ts +1 -0
  21. package/dist/conversations/events.d.ts +49 -27
  22. package/dist/conversations/events.js +54 -7
  23. package/dist/conversations/files.d.ts +66 -64
  24. package/dist/conversations/files.js +127 -147
  25. package/dist/conversations/prompt-suggestion-request.js +2 -1
  26. package/dist/conversations/prompt-suggestions.d.ts +3 -3
  27. package/dist/conversations/prompt-suggestions.js +11 -10
  28. package/dist/conversations/queue.service.js +7 -2
  29. package/dist/ctx/create-ctx.d.ts +3 -1
  30. package/dist/ctx/create-ctx.js +19 -1
  31. package/dist/db/kernel-schema.d.ts +80 -2
  32. package/dist/errors.d.ts +19 -0
  33. package/dist/errors.js +19 -0
  34. package/dist/evals/canonical-json.d.ts +7 -0
  35. package/dist/evals/canonical-json.js +21 -0
  36. package/dist/evals/reconstruct.js +13 -1
  37. package/dist/evals/recorded-tools.d.ts +0 -2
  38. package/dist/evals/recorded-tools.js +1 -16
  39. package/dist/evals/snapshot.d.ts +26 -3
  40. package/dist/evals/snapshot.js +110 -57
  41. package/dist/evals/worker.d.ts +4 -3
  42. package/dist/evals/worker.js +8 -4
  43. package/dist/extensions/host.d.ts +3 -1
  44. package/dist/extensions/host.js +2 -0
  45. package/dist/extensions/instance.d.ts +3 -1
  46. package/dist/extensions/instance.js +4 -0
  47. package/dist/extensions/ledger.d.ts +1 -1
  48. package/dist/files/blob-objects.d.ts +124 -0
  49. package/dist/files/blob-objects.js +341 -0
  50. package/dist/files/blob-sweep.job.d.ts +122 -0
  51. package/dist/files/blob-sweep.job.js +389 -0
  52. package/dist/files/blobs.service.d.ts +135 -0
  53. package/dist/files/blobs.service.js +300 -0
  54. package/dist/files/conversation-media.d.ts +41 -0
  55. package/dist/files/conversation-media.js +124 -0
  56. package/dist/files/deliveries.d.ts +64 -0
  57. package/dist/files/deliveries.js +156 -0
  58. package/dist/files/deliveries.module.d.ts +6 -0
  59. package/dist/files/deliveries.module.js +24 -0
  60. package/dist/files/draft-cleanup.job.d.ts +26 -0
  61. package/dist/files/draft-cleanup.job.js +93 -0
  62. package/dist/files/files.module.d.ts +1 -1
  63. package/dist/files/files.module.js +3 -2
  64. package/dist/files/hash-job.d.ts +127 -0
  65. package/dist/files/hash-job.js +447 -0
  66. package/dist/files/library-backfill.d.ts +63 -0
  67. package/dist/files/library-backfill.js +143 -0
  68. package/dist/files/library-files.service.d.ts +255 -0
  69. package/dist/files/library-files.service.js +883 -0
  70. package/dist/files/library-jobs.module.d.ts +8 -0
  71. package/dist/files/library-jobs.module.js +27 -0
  72. package/dist/files/library-query.d.ts +127 -0
  73. package/dist/files/library-query.js +322 -0
  74. package/dist/files/library-read.module.d.ts +9 -0
  75. package/dist/files/library-read.module.js +30 -0
  76. package/dist/files/library.controller.d.ts +77 -0
  77. package/dist/files/library.controller.js +235 -0
  78. package/dist/files/library.module.d.ts +9 -0
  79. package/dist/files/library.module.js +29 -0
  80. package/dist/files/library.schemas.d.ts +46 -0
  81. package/dist/files/library.schemas.js +49 -0
  82. package/dist/files/previewers.controller.d.ts +20 -0
  83. package/dist/files/previewers.controller.js +47 -0
  84. package/dist/files/previewers.d.ts +25 -11
  85. package/dist/files/previewers.js +43 -27
  86. package/dist/files/referenced-files.d.ts +150 -0
  87. package/dist/files/referenced-files.js +234 -0
  88. package/dist/html/html-document.controller.d.ts +8 -1
  89. package/dist/html/html-document.controller.js +19 -1
  90. package/dist/html/html-document.service.d.ts +19 -4
  91. package/dist/html/html-document.service.js +43 -22
  92. package/dist/html/html-token.d.ts +10 -1
  93. package/dist/html/html-token.js +14 -0
  94. package/dist/html/html.module.js +8 -1
  95. package/dist/http/api.module.js +5 -0
  96. package/dist/identity/settings.d.ts +26 -0
  97. package/dist/identity/settings.js +33 -2
  98. package/dist/infra/outbox/registry.d.ts +82 -0
  99. package/dist/infra/outbox/registry.js +74 -2
  100. package/dist/infra/throttler/named-throttlers.d.ts +2 -0
  101. package/dist/infra/throttler/named-throttlers.js +14 -0
  102. package/dist/lifecycle/kernel-lifecycle.js +6 -0
  103. package/dist/models/purposes.js +1 -1
  104. package/dist/orgs/offboarding.js +1 -1
  105. package/dist/orgs/settings.service.d.ts +48 -2
  106. package/dist/orgs/settings.service.js +63 -3
  107. package/dist/platform/exclusions.js +45 -8
  108. package/dist/platform/file-ref.d.ts +18 -3
  109. package/dist/platform/file-ref.js +22 -11
  110. package/dist/platform/operation.js +4 -0
  111. package/dist/platform/ops/admin.ops.js +5 -2
  112. package/dist/platform/ops/files.ops.d.ts +18 -0
  113. package/dist/platform/ops/files.ops.js +267 -0
  114. package/dist/platform/ops/org-settings.ops.js +6 -2
  115. package/dist/platform/ops/orgs.ops.js +1 -0
  116. package/dist/platform/ops/shares.ops.js +2 -2
  117. package/dist/platform/platform-ops.module.d.ts +2 -1
  118. package/dist/platform/platform-ops.module.js +5 -0
  119. package/dist/platform/route-schemas.js +3 -0
  120. package/dist/roles/worker.module.js +15 -1
  121. package/dist/runtime/compaction-settings.service.d.ts +13 -1
  122. package/dist/runtime/compaction-settings.service.js +16 -1
  123. package/dist/runtime/compaction.service.d.ts +3 -1
  124. package/dist/runtime/compaction.service.js +3 -1
  125. package/dist/runtime/context/build.d.ts +18 -1
  126. package/dist/runtime/context/build.js +19 -8
  127. package/dist/runtime/context/cache-expiry.d.ts +31 -0
  128. package/dist/runtime/context/cache-expiry.js +60 -0
  129. package/dist/runtime/context/cache-ttl.d.ts +18 -0
  130. package/dist/runtime/context/cache-ttl.js +30 -0
  131. package/dist/runtime/context/compaction.d.ts +9 -2
  132. package/dist/runtime/context/compaction.js +50 -17
  133. package/dist/runtime/context/in-context-compaction.d.ts +156 -0
  134. package/dist/runtime/context/in-context-compaction.js +310 -0
  135. package/dist/runtime/hook-calls.d.ts +2 -1
  136. package/dist/runtime/hook-calls.js +5 -2
  137. package/dist/runtime/maintenance.d.ts +10 -2
  138. package/dist/runtime/maintenance.js +48 -8
  139. package/dist/runtime/model-call.d.ts +34 -5
  140. package/dist/runtime/model-call.js +207 -22
  141. package/dist/runtime/providers.js +11 -1
  142. package/dist/runtime/run-steps.d.ts +4 -2
  143. package/dist/runtime/run-steps.js +10 -5
  144. package/dist/runtime/runtime.module.js +3 -0
  145. package/dist/shares/liveness.d.ts +26 -12
  146. package/dist/shares/liveness.js +79 -20
  147. package/dist/shares/revoke.d.ts +16 -11
  148. package/dist/shares/revoke.js +18 -14
  149. package/dist/shares/share-objects.d.ts +16 -21
  150. package/dist/shares/share-objects.js +25 -55
  151. package/dist/shares/share-open.service.d.ts +8 -4
  152. package/dist/shares/share-open.service.js +14 -11
  153. package/dist/shares/shares.controller.d.ts +16 -5
  154. package/dist/shares/shares.controller.js +39 -5
  155. package/dist/shares/shares.module.d.ts +4 -4
  156. package/dist/shares/shares.module.js +7 -6
  157. package/dist/shares/shares.schemas.d.ts +4 -0
  158. package/dist/shares/shares.schemas.js +2 -0
  159. package/dist/shares/shares.service.d.ts +93 -54
  160. package/dist/shares/shares.service.js +292 -131
  161. package/dist/shares/sweep.job.d.ts +18 -39
  162. package/dist/shares/sweep.job.js +47 -206
  163. package/dist/tools/builtins/artifacts.d.ts +21 -13
  164. package/dist/tools/builtins/artifacts.js +81 -51
  165. package/dist/tools/builtins/builtin-tools.d.ts +7 -1
  166. package/dist/tools/builtins/builtin-tools.js +17 -6
  167. package/dist/tools/builtins/conversation-files.d.ts +23 -13
  168. package/dist/tools/builtins/conversation-files.js +62 -83
  169. package/dist/tools/builtins/image/generate.d.ts +7 -1
  170. package/dist/tools/builtins/image/generate.js +1 -1
  171. package/dist/tools/builtins/platform.js +1 -0
  172. package/dist/tools/builtins/sandbox/common.d.ts +6 -2
  173. package/dist/tools/builtins/sandbox/deliver.js +6 -7
  174. package/dist/tools/builtins/sandbox/fetch-attachment.d.ts +6 -5
  175. package/dist/tools/builtins/sandbox/fetch-attachment.js +19 -12
  176. package/dist/tools/tools.module.js +6 -0
  177. package/dist/ui/call-extension.d.ts +6 -4
  178. package/dist/ui/call-extension.js +5 -4
  179. package/dist/ui/embed-token.js +6 -3
  180. package/dist/ui/registry.d.ts +21 -5
  181. package/dist/ui/registry.js +24 -6
  182. package/dist/ui/ui.schemas.d.ts +22 -0
  183. package/dist/ui/ui.schemas.js +22 -4
  184. package/dist/ui/views.controller.d.ts +13 -3
  185. package/dist/ui/views.controller.js +33 -2
  186. package/dist/ui/views.d.ts +29 -1
  187. package/dist/ui/views.js +131 -7
  188. package/package.json +3 -3
  189. package/src/migrations/0190_file_library.sql +285 -0
  190. package/src/migrations/0191_file_library_copy.sql +4 -0
@@ -8,7 +8,6 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
8
  return function (target, key) { decorator(target, key, paramIndex); }
9
9
  };
10
10
  import { randomUUID } from "node:crypto";
11
- import { MEDIA_LIMITS } from "@capybara-hq/plugin-sdk";
12
11
  import { Inject, Injectable } from "@nestjs/common";
13
12
  import { sql } from "kysely";
14
13
  import { ApiError } from "../errors.js";
@@ -23,7 +22,7 @@ import { LockedCron } from "../infra/schedule/locked-cron.decorator.js";
23
22
  import { KERNEL_LOGGER } from "../infra/tokens.js";
24
23
  import { StorageService } from "../storage/storage.service.js";
25
24
  import { ConversationAccess } from "./access.js";
26
- import { acceptedContent, isImageContentType, isMediaContentType } from "./media-types.js";
25
+ import { isImageContentType } from "./media-types.js";
27
26
  import { fitImageForModel, MODEL_IMAGE_CACHE_SECONDS, modelImageKey, parseModelImage, serializeModelImage, } from "./model-image.js";
28
27
  /** 预签名上传的有效期(秒)。尽量短:表单在有效期内可被再次使用(内容替换由 etag 核对兜底)。 */
29
28
  export const ATTACHMENT_UPLOAD_TTL_SECONDS = 300;
@@ -31,8 +30,6 @@ export const ATTACHMENT_UPLOAD_TTL_SECONDS = 300;
31
30
  export const ATTACHMENT_DOWNLOAD_TTL_SECONDS = 300;
32
31
  /** 下载 302 的 `Cache-Control: private, max-age=…`(秒):同一页面里缩略图可复用跳转地址。 */
33
32
  export const ATTACHMENT_DOWNLOAD_CACHE_SECONDS = 60;
34
- /** 同一账号在一个组织里最多的未 finalize 附件数(超过 → 429 `attachment.too_many_pending`)。 */
35
- export const MAX_PENDING_ATTACHMENTS = 50;
36
33
  /** 技能包 zip 的内容类型(上传时一律按它签名,finalize 时核对 zip 文件头)。 */
37
34
  export const SKILL_PACKAGE_CONTENT_TYPE = "application/zip";
38
35
  /** 技能包 zip 的大小上限(字节)。 */
@@ -83,23 +80,22 @@ export function attachmentContentMatches(recorded, head) {
83
80
  }
84
81
  const notFound = () => new ApiError("attachment.not_found", "Attachment not found");
85
82
  /**
86
- * The purposes request building reads bytes of: chat attachments and the `read` copies of the
87
- * builtin Read. Every other lookup (listing, sandbox sync, download, binding) stays `chat` only.
83
+ * The one purpose conversations read here: the `read` copies of the builtin Read and of tool
84
+ * result images. A person's files (the `chat` rows the file library migrated) are read through the
85
+ * library (`ReferencedFiles`), never here.
88
86
  */
89
- const MEDIA_PURPOSES = ["chat", "read"];
87
+ const READ_PURPOSE = "read";
90
88
  /** 去掉参数、转小写:`Text/Plain; charset=utf-8` → `text/plain`。 */
91
89
  export const normalizeContentType = (ct) => (ct.split(";")[0] ?? "").trim().toLowerCase();
92
90
  /**
93
91
  * The object key: the attachment id only (the user's file name never goes into a key), under one
94
- * prefix per purpose.
92
+ * prefix per purpose this service still writes (legacy `chat` rows are the file library's).
95
93
  */
96
- const objectKey = (id, purpose = "chat") => purpose === "chat"
97
- ? `attachments/${id}`
98
- : purpose === "agent-avatar"
99
- ? `agent-avatars/${id}`
100
- : purpose === "read"
101
- ? `read-images/${id}`
102
- : `skill-packages/${id}`;
94
+ const objectKey = (id, purpose) => purpose === "agent-avatar"
95
+ ? `agent-avatars/${id}`
96
+ : purpose === "read"
97
+ ? `read-images/${id}`
98
+ : `skill-packages/${id}`;
103
99
  const startsWith = (b, sig, at = 0) => sig.every((x, i) => b[at + i] === x);
104
100
  const ascii = (s) => [...s].map((c) => c.charCodeAt(0));
105
101
  /**
@@ -143,9 +139,11 @@ async function readAll(body) {
143
139
  return new Uint8Array(await new Response(body).arrayBuffer());
144
140
  }
145
141
  /**
146
- * 对话附件(M5 T3):登记 → 浏览器按预签名直传对象存储 → finalize 核对 → 发消息时绑定到会话。
147
- * 字节只在对象存储(`kernel/<orgId>/attachments/<id>`),日志里只有引用;构建模型请求时经 {@link fetchMedia} 取字节。
148
- * 无进程内状态,可多副本共用。
142
+ * Uploads that are not a person's files (agent avatars, skill packages: register → the browser
143
+ * uploads with the presigned form → finalize checks) and the `read` copies of images the agent was
144
+ * shown (bound to their conversation; request building reads them through {@link fetchMedia}). A
145
+ * person's files are the file library's (`LibraryFilesService`, `ReferencedFiles`). Bytes live only
146
+ * in the object store; logs hold refs. No process state.
149
147
  */
150
148
  let AttachmentsService = class AttachmentsService {
151
149
  db;
@@ -168,31 +166,14 @@ let AttachmentsService = class AttachmentsService {
168
166
  this.txHost = txHost;
169
167
  this.cache = cache;
170
168
  }
171
- /** 单个附件的大小上限:配置的 `maxBytes`,图片再受 `MEDIA_LIMITS.imageBytes` 限制。 */
172
- limitFor(contentType) {
173
- const { maxBytes } = this.config.get().attachments;
174
- return Math.min(maxBytes, isImageContentType(contentType) ? MEDIA_LIMITS.imageBytes : MEDIA_LIMITS.documentBytes);
175
- }
176
- /** 当前配置下的上限(不需要对象存储)。 */
177
- limits() {
178
- const cfg = this.config.get().attachments;
179
- return {
180
- types: [...cfg.allowedTypes],
181
- extensions: [...cfg.allowedExtensions],
182
- maxBytes: Math.min(cfg.maxBytes, MEDIA_LIMITS.documentBytes),
183
- imageMaxBytes: Math.min(cfg.maxBytes, MEDIA_LIMITS.imageBytes),
184
- maxPerMessage: cfg.maxPerMessage,
185
- requestMediaBytes: cfg.requestMediaBytes,
186
- available: this.storage.available,
187
- };
188
- }
189
169
  /**
190
- * 登记一个附件(`pending`)并返回预签名上传:存储端按声明的大小与类型限制上传。
191
- * 类型不在 `attachments.allowedTypes` → `attachment.type_not_allowed`;超过上限 → `attachment.too_large`;
192
- * 该账号在组织里已有 {@link MAX_PENDING_ATTACHMENTS} 个未 finalize 的附件 → `attachment.too_many_pending`
193
- * (软上限:并发登记可能略超);没有对象存储 → `storage.unavailable`。
170
+ * Registers an agent avatar or skill package upload (`pending`) and returns its presigned form;
171
+ * the store enforces the declared size and type. A type or size the purpose does not take →
172
+ * `attachment.type_not_allowed` / `attachment.too_large`; too many unfinished uploads of the
173
+ * purpose → `attachment.too_many_pending` (a soft cap); no object store → `storage.unavailable`.
174
+ * A person's files go through the file library (`LibraryFilesService`), never here.
194
175
  */
195
- async create(orgId, accountId, input, purpose = "chat") {
176
+ async create(orgId, accountId, input, purpose) {
196
177
  this.storage.assertAvailable();
197
178
  const { contentType, ttlHours } = await this.admit(orgId, accountId, purpose, input, false);
198
179
  const id = randomUUID();
@@ -230,22 +211,14 @@ let AttachmentsService = class AttachmentsService {
230
211
  * not stay pending).
231
212
  */
232
213
  async admit(orgId, accountId, purpose, input, countStored) {
233
- const cfg = this.config.get().attachments;
234
214
  const contentType = normalizeContentType(input.contentType);
235
215
  const skill = purpose === "skill-package";
236
- const avatar = purpose === "agent-avatar";
237
216
  if (skill
238
217
  ? contentType !== SKILL_PACKAGE_CONTENT_TYPE
239
- : avatar
240
- ? !AGENT_AVATAR_CONTENT_TYPES.includes(contentType)
241
- : !cfg.allowedTypes.includes(contentType)) {
218
+ : !AGENT_AVATAR_CONTENT_TYPES.includes(contentType)) {
242
219
  throw new ApiError("attachment.type_not_allowed", `Attachment type ${JSON.stringify(contentType)} is not allowed`);
243
220
  }
244
- const limit = skill
245
- ? SKILL_PACKAGE_UPLOAD_MAX_BYTES
246
- : avatar
247
- ? AGENT_AVATAR_MAX_BYTES
248
- : this.limitFor(contentType);
221
+ const limit = skill ? SKILL_PACKAGE_UPLOAD_MAX_BYTES : AGENT_AVATAR_MAX_BYTES;
249
222
  if (input.size > limit) {
250
223
  throw new ApiError("attachment.too_large", `Attachment is ${input.size} bytes, over the limit of ${limit} bytes`);
251
224
  }
@@ -266,19 +239,11 @@ let AttachmentsService = class AttachmentsService {
266
239
  ])
267
240
  : eb("status", "=", "pending"))
268
241
  .executeTakeFirst();
269
- const maxPending = skill
270
- ? MAX_PENDING_SKILL_PACKAGES
271
- : avatar
272
- ? MAX_PENDING_AGENT_AVATARS
273
- : MAX_PENDING_ATTACHMENTS;
242
+ const maxPending = skill ? MAX_PENDING_SKILL_PACKAGES : MAX_PENDING_AGENT_AVATARS;
274
243
  if (Number(pending?.n ?? 0) >= maxPending) {
275
244
  throw new ApiError("attachment.too_many_pending", `Too many unfinished uploads (at most ${maxPending}); finish or wait for them first`);
276
245
  }
277
- const ttlHours = skill
278
- ? SKILL_PACKAGE_TTL_HOURS
279
- : avatar
280
- ? AGENT_AVATAR_TTL_HOURS
281
- : cfg.unboundTtlHours;
246
+ const ttlHours = skill ? SKILL_PACKAGE_TTL_HOURS : AGENT_AVATAR_TTL_HOURS;
282
247
  return { contentType, ttlHours };
283
248
  }
284
249
  /**
@@ -372,8 +337,9 @@ let AttachmentsService = class AttachmentsService {
372
337
  .where("org_id", "=", orgId)
373
338
  .where("account_id", "=", accountId)
374
339
  .where("status", "in", ["pending", "ready"])
375
- // read copies are the kernel's own (storeRead binds them); nobody finalizes them
376
- .where("purpose", "<>", "read")
340
+ // read copies are the kernel's own (storeRead binds them); a person's files are finalized
341
+ // by the file library
342
+ .where("purpose", "in", ["agent-avatar", "skill-package"])
377
343
  .executeTakeFirst();
378
344
  if (!row)
379
345
  throw notFound();
@@ -420,12 +386,11 @@ let AttachmentsService = class AttachmentsService {
420
386
  return view;
421
387
  }
422
388
  /**
423
- * 下载地址(预签名,{@link ATTACHMENT_DOWNLOAD_TTL_SECONDS} 秒):已绑定的附件要求能访问其会话,
424
- * 未绑定的只有上传者;否则 `attachment.not_found`。只有图片与 PDF 以 `inline` 打开,其余一律 `attachment`
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).
389
+ * The download address (presigned, {@link ATTACHMENT_DOWNLOAD_TTL_SECONDS} seconds) of a `read`
390
+ * copy (an image a tool showed the agent), for whoever can open its conversation, so the web can
391
+ * show it on the call's row (tool result images design §4); anything else →
392
+ * `attachment.not_found` (a person's files are downloaded through the file library). Only images
393
+ * and PDFs open `inline`; the response type is the recorded one.
429
394
  */
430
395
  async downloadUrl(orgId, accountId, id) {
431
396
  this.storage.assertAvailable();
@@ -443,7 +408,7 @@ let AttachmentsService = class AttachmentsService {
443
408
  .where("id", "=", id)
444
409
  .where("org_id", "=", orgId)
445
410
  .where("status", "=", "ready")
446
- .where("purpose", "in", ["chat", "read"])
411
+ .where("purpose", "=", READ_PURPOSE)
447
412
  .executeTakeFirst();
448
413
  if (!row)
449
414
  throw notFound();
@@ -466,25 +431,17 @@ let AttachmentsService = class AttachmentsService {
466
431
  });
467
432
  }
468
433
  /**
469
- * 绑定在该会话、已 ready 的附件(id 与原始文件名),按上传时间、id 排序(沙箱同步按这个顺序分配文件名)。
434
+ * The ready `read` copies bound to the conversation in this org (vision-read design §1.1), oldest
435
+ * first, then id; with `id`, only that one. Nothing here checks who reads them: callers check the
436
+ * conversation's access first.
470
437
  */
471
- async listForConversation(orgId, conversationId) {
472
- return (await this.boundRows(orgId, conversationId)).map((r) => ({ id: r.id, name: r.name }));
473
- }
474
- /**
475
- * The ready `chat` attachments bound to the conversation in this org (never another purpose, a
476
- * pending or an unbound upload), oldest first by upload time, then id; with `id`, only that one.
477
- * Nothing here checks who reads them: callers check the conversation's access first. `purposes`
478
- * widens it for a model-facing lookup only (`read` copies; vision-read design §1.1): every
479
- * person- or device-facing caller keeps the default.
480
- */
481
- async boundRows(orgId, conversationId, id, purposes = ["chat"]) {
438
+ async boundRows(orgId, conversationId, id) {
482
439
  let q = this.db
483
440
  .selectFrom("attachments")
484
441
  .select(["id", "name", "content_type", "size", "object_key", "etag", "created_at"])
485
442
  .where("org_id", "=", orgId)
486
443
  .where("conversation_id", "=", conversationId)
487
- .where("purpose", "in", [...purposes])
444
+ .where("purpose", "=", READ_PURPOSE)
488
445
  .where("status", "=", "ready");
489
446
  if (id !== undefined)
490
447
  q = q.where("id", "=", id);
@@ -515,11 +472,12 @@ let AttachmentsService = class AttachmentsService {
515
472
  return false;
516
473
  }
517
474
  /**
518
- * 读取一个绑定在该会话、已 ready 的附件(沙箱同步等内核内部用途):没有行、未绑定到该会话、对象已不在、
519
- * 大小或 etag 与 finalize 时不符 → null。其余错误(存储不可用等)照常抛出。调用方负责读完或取消 `body`。
475
+ * Opens a ready `read` copy bound to the conversation (the model-facing file lookup): no row, not
476
+ * bound to it, the object gone, or its size or etag not the recorded one → null. Other errors
477
+ * (storage unavailable) throw. The caller reads or cancels `body`.
520
478
  */
521
479
  async openForConversation(orgId, conversationId, attachmentId, opts = {}) {
522
- const [row] = await this.boundRows(orgId, conversationId, attachmentId, opts.purposes);
480
+ const [row] = await this.boundRows(orgId, conversationId, attachmentId);
523
481
  if (!row)
524
482
  return null;
525
483
  const got = await this.storage.kernel(orgId).get(row.objectKey, {
@@ -536,104 +494,6 @@ let AttachmentsService = class AttachmentsService {
536
494
  }
537
495
  return { name: row.name, contentType: row.contentType, size: row.size, body: got.body };
538
496
  }
539
- /**
540
- * 发消息时在调用方事务里绑定附件(行锁),返回写进 user_message 的媒体块(`ref`,按 ids 顺序):
541
- * - 超过 `attachments.maxPerMessage`、或同一个 id 出现多次 → `validation_failed`;
542
- * - 不存在、不是发送者上传的、已绑定到别的会话、未绑定且已过期 → `attachment.not_found`;
543
- * - 还没 finalize → `attachment.not_ready`。
544
- * 后两种的 details 为 `[{ path: "files", message, attachmentId }]`,网页据此标出对应条目。
545
- * 已绑定到本会话的(重试)照常返回块。
546
- */
547
- async bindForMessage(orgId, conversationId, accountId, ids) {
548
- const unique = [...new Set(ids)];
549
- const max = this.config.get().attachments.maxPerMessage;
550
- if (ids.length > max) {
551
- throw new ApiError("validation_failed", "Request validation failed", [
552
- { path: "files", message: `At most ${max} files per message` },
553
- ]);
554
- }
555
- if (unique.length !== ids.length) {
556
- throw new ApiError("validation_failed", "Request validation failed", [
557
- { path: "files", message: "Each file may appear only once per message" },
558
- ]);
559
- }
560
- if (unique.length === 0)
561
- return [];
562
- const trx = this.db.db;
563
- const rows = await trx
564
- .selectFrom("attachments")
565
- .select([
566
- "id",
567
- "account_id",
568
- "conversation_id",
569
- "name",
570
- "content_type",
571
- "size",
572
- "status",
573
- sql `expires_at IS NOT NULL AND expires_at <= now()`.as("expired"),
574
- ])
575
- .where("org_id", "=", orgId)
576
- .where("id", "in", unique)
577
- // 技能包上传不能当附件发出(当作不存在)
578
- .where("purpose", "=", "chat")
579
- .orderBy("id")
580
- .forUpdate()
581
- .execute();
582
- const byId = new Map(rows.map((r) => [r.id, r]));
583
- const blocks = [];
584
- const toBind = [];
585
- for (const id of unique) {
586
- const r = byId.get(id);
587
- if (!r ||
588
- r.account_id !== accountId ||
589
- r.status === "deleting" ||
590
- (r.conversation_id !== null && r.conversation_id !== conversationId) ||
591
- (r.conversation_id === null && r.expired)) {
592
- const message = `Attachment ${id} not found, expired, or already used in another conversation`;
593
- throw new ApiError("attachment.not_found", message, [
594
- { path: "files", message, attachmentId: id },
595
- ]);
596
- }
597
- if (r.status !== "ready") {
598
- const message = `Attachment ${id} has not been finalized`;
599
- throw new ApiError("attachment.not_ready", message, [
600
- { path: "files", message, attachmentId: id },
601
- ]);
602
- }
603
- if (r.conversation_id === null)
604
- toBind.push(id);
605
- const source = { kind: "ref", attachmentId: id };
606
- const size = Number(r.size);
607
- // The model reads images, PDFs and text files itself; every other accepted type becomes a
608
- // `file` block the model only gets a reference to (the bytes stay in the object store).
609
- blocks.push(isImageContentType(r.content_type)
610
- ? {
611
- type: "image",
612
- mediaType: r.content_type,
613
- source,
614
- name: r.name,
615
- size,
616
- }
617
- : isMediaContentType(r.content_type)
618
- ? {
619
- type: "document",
620
- mediaType: r.content_type,
621
- source,
622
- name: r.name,
623
- size,
624
- }
625
- : { type: "file", mediaType: r.content_type, source, name: r.name, size });
626
- }
627
- if (toBind.length > 0) {
628
- await trx
629
- .updateTable("attachments")
630
- .set({ conversation_id: conversationId, expires_at: null })
631
- .where("id", "in", toBind)
632
- .where("org_id", "=", orgId)
633
- .execute();
634
- }
635
- return blocks;
636
- }
637
497
  /** 下载 / 取字节时核对 etag:finalize 记下的与当前对象的不一致 → 内容被替换(记 warn)。没有记录时不核对。 */
638
498
  sameContent(recorded, current, where) {
639
499
  if (recorded === null || recorded === (current ?? null))
@@ -642,8 +502,8 @@ let AttachmentsService = class AttachmentsService {
642
502
  return false;
643
503
  }
644
504
  /**
645
- * The recorded facts request building needs about attachments (only ready `chat` or `read` rows
646
- * bound to this conversation): size, PDF page count, and the object's unsigned reference
505
+ * The recorded facts request building needs about `read` copies (only ready rows bound to this
506
+ * conversation; `ConversationMedia` asks here for the refs that are not library files): size, PDF page count, and the object's unsigned reference
647
507
  * (`ObjectStore.uri`, falling back to `capybara://attachments/<id>`). An id with no row is left
648
508
  * out; a failed query throws.
649
509
  */
@@ -655,7 +515,7 @@ let AttachmentsService = class AttachmentsService {
655
515
  .select(["id", "size", "pages", "etag", "object_key"])
656
516
  .where("org_id", "=", orgId)
657
517
  .where("conversation_id", "=", conversationId)
658
- .where("purpose", "in", MEDIA_PURPOSES)
518
+ .where("purpose", "=", READ_PURPOSE)
659
519
  .where("status", "=", "ready")
660
520
  .where("id", "in", [...ids])
661
521
  .execute();
@@ -671,8 +531,7 @@ let AttachmentsService = class AttachmentsService {
671
531
  ]));
672
532
  }
673
533
  /**
674
- * The bytes request building sends, only of ready `chat` or `read` rows bound to this
675
- * conversation. Null only when certainly gone: no row, the object missing, or its size or etag
534
+ * The bytes request building sends, only of ready `read` copies bound to this conversation. Null only when certainly gone: no row, the object missing, or its size or etag
676
535
  * not the recorded one (content replaced, logged as a warning). Every other error (storage
677
536
  * unavailable, network) throws (Ruling M4) for the caller to treat as retryable, never a
678
537
  * placeholder. An id in `caps` is read by range up to that many leading bytes (the `text/*` cap).
@@ -689,7 +548,7 @@ let AttachmentsService = class AttachmentsService {
689
548
  .select(["id", "content_type", "object_key", "size", "etag"])
690
549
  .where("org_id", "=", orgId)
691
550
  .where("conversation_id", "=", conversationId)
692
- .where("purpose", "in", MEDIA_PURPOSES)
551
+ .where("purpose", "=", READ_PURPOSE)
693
552
  .where("status", "=", "ready")
694
553
  .where("id", "in", [...ids])
695
554
  .execute();
@@ -1102,6 +961,8 @@ let AttachmentsService = class AttachmentsService {
1102
961
  .selectFrom("attachments")
1103
962
  .select("id")
1104
963
  .where("conversation_id", "is", null)
964
+ // chat rows are the file library's now (a migrated draft's object is a blob's)
965
+ .where("purpose", "<>", "chat")
1105
966
  .where("expires_at", "<", sql `now()`)
1106
967
  .$if(failed.length > 0, (q) => q.where("id", "not in", failed))
1107
968
  .orderBy("expires_at")
@@ -1158,9 +1019,6 @@ __decorate([
1158
1019
  __decorate([
1159
1020
  Transactional({ propagation: "requires_new" })
1160
1021
  ], AttachmentsService.prototype, "insertUploadIntent", null);
1161
- __decorate([
1162
- Transactional({ propagation: "mandatory" })
1163
- ], AttachmentsService.prototype, "bindForMessage", null);
1164
1022
  __decorate([
1165
1023
  Transactional({ propagation: "mandatory" })
1166
1024
  ], AttachmentsService.prototype, "consumeSkillPackage", null);
@@ -8,6 +8,7 @@ import { Module } from "@nestjs/common";
8
8
  import { AgentLookupModule } from "../agents/agent-lookup.js";
9
9
  import { BackgroundModule } from "../background/background.module.js";
10
10
  import { DevicesModule } from "../devices/devices.module.js";
11
+ import { LibraryReadModule } from "../files/library-read.module.js";
11
12
  import { ProvidersModule } from "../runtime/providers.js";
12
13
  import { RuntimeModule } from "../runtime/runtime.module.js";
13
14
  import { OperationAuthorityModule } from "../sandbox/operation-authority.module.js";
@@ -46,6 +47,8 @@ ConversationsModule = __decorate([
46
47
  EventLogModule,
47
48
  ConversationAccessModule,
48
49
  AttachmentsModule,
50
+ // the files messages attach and the conversation's files read (file library)
51
+ LibraryReadModule,
49
52
  AgentLookupModule,
50
53
  StorageModule,
51
54
  SkillsModule,
@@ -75,6 +78,7 @@ ConversationsModule = __decorate([
75
78
  EventLogModule,
76
79
  ConversationAccessModule,
77
80
  AttachmentsModule,
81
+ LibraryReadModule,
78
82
  ConversationsService,
79
83
  ConversationQueue,
80
84
  ConversationOutputs,
@@ -7,6 +7,7 @@ import type { ConversationSubject, TitleSource } from "../db/kernel-schema.js";
7
7
  import { ConversationDevices, type NewConversationDevice } from "../devices/conversation-devices.js";
8
8
  import { DeviceProjectFilesService } from "../devices/device-project-files.service.js";
9
9
  import { DeviceProjectsService } from "../devices/device-projects.service.js";
10
+ import { LibraryFilesService } from "../files/library-files.service.js";
10
11
  import { type PersonRef } from "../identity/account-avatar.js";
11
12
  import { KernelDb } from "../infra/database/kernel-db.js";
12
13
  import { TransactionHost } from "../infra/database/transaction-host.js";
@@ -21,9 +22,8 @@ import { ConnectorContent } from "../tools/connector-content.js";
21
22
  import { type QuestionRecord, QuestionsService } from "../tools/questions.service.js";
22
23
  import { ConversationAccess } from "./access.js";
23
24
  import { type AgentTreeNode } from "./agent-tree.js";
24
- import { AttachmentsService } from "./attachments.service.js";
25
25
  import { EventLog } from "./event-log.js";
26
- import type { ConversationEvent, LogContentBlock } from "./events.js";
26
+ import { type ConversationEvent, type LogContentBlock } from "./events.js";
27
27
  import { type ImSenderContext } from "./message-context.js";
28
28
  import type { PermissionSelection } from "./permission-profiles.schemas.js";
29
29
  import { PermissionProfilesService } from "./permission-profiles.service.js";
@@ -349,8 +349,8 @@ export declare class ConversationsService {
349
349
  private readonly providers;
350
350
  /** Reads `@` resources with the sender's credentials. */
351
351
  private readonly content;
352
- /** Binds uploaded files to the conversation in the message's transaction. */
353
- private readonly attachments;
352
+ /** Attaches the sender's library files to the conversation in the message's transaction. */
353
+ private readonly libraryFiles;
354
354
  /** Renders a person's skill invocation (phase D). */
355
355
  private readonly invoker;
356
356
  /** Stops a deleted conversation's background tasks. */
@@ -377,8 +377,8 @@ export declare class ConversationsService {
377
377
  providers: Pick<ProviderRegistry, "resolve">,
378
378
  /** Reads `@` resources with the sender's credentials. */
379
379
  content: Pick<ConnectorContent, "resolveAttachments">,
380
- /** Binds uploaded files to the conversation in the message's transaction. */
381
- attachments: Pick<AttachmentsService, "bindForMessage">,
380
+ /** Attaches the sender's library files to the conversation in the message's transaction. */
381
+ libraryFiles: Pick<LibraryFilesService, "attachForMessage">,
382
382
  /** Renders a person's skill invocation (phase D). */
383
383
  invoker: Pick<SkillInvoker, "prepare">,
384
384
  /** Stops a deleted conversation's background tasks. */
@@ -691,9 +691,10 @@ export declare class ConversationsService {
691
691
  /** {@link resolveExtra}'s project file check: the normalized paths and the root, or none. */
692
692
  private checkProjectFiles;
693
693
  /**
694
- * Binds uploaded files inside the message's (or queue item's) transaction; none → no blocks.
695
- * The bound files join the conversation's files, so open pages read the list again after the
696
- * commit (`changed: files`, a hint).
694
+ * Attaches the sender's library files inside the message's (or queue item's) transaction
695
+ * (`LibraryFilesService.attachForMessage`: drafts become ready, the conversation refers to each);
696
+ * none → no blocks. The files join the conversation's files, so open pages read the list again
697
+ * after the commit (`changed: files`, a hint).
697
698
  */
698
699
  bindIn(orgId: string, conversationId: string, accountId: string, files: readonly string[]): Promise<LogContentBlock[]>;
699
700
  private userMessage;
@@ -20,6 +20,7 @@ import { DeviceProjectsService } from "../devices/device-projects.service.js";
20
20
  import { projectFilePath } from "../devices/project-paths.js";
21
21
  import { clipped } from "../devices/project-rules.js";
22
22
  import { ApiError } from "../errors.js";
23
+ import { LibraryFilesService } from "../files/library-files.service.js";
23
24
  import { loadPeople } from "../identity/account-avatar.js";
24
25
  import { afterCommit } from "../infra/database/after-commit.js";
25
26
  import { KernelDb } from "../infra/database/kernel-db.js";
@@ -40,9 +41,9 @@ import { ConnectorContent } from "../tools/connector-content.js";
40
41
  import { QuestionsService } from "../tools/questions.service.js";
41
42
  import { ConversationAccess, parentReachable } from "./access.js";
42
43
  import { readAgentTree } from "./agent-tree.js";
43
- import { AttachmentsService } from "./attachments.service.js";
44
44
  import { EventLog } from "./event-log.js";
45
45
  import { peopleOfEvents } from "./event-people.js";
46
+ import { refFileId } from "./events.js";
46
47
  import { userMessageIdemKey } from "./idem-keys.js";
47
48
  import { readMessageContext, } from "./message-context.js";
48
49
  import { PermissionProfilesService } from "./permission-profiles.service.js";
@@ -203,7 +204,7 @@ let ConversationsService = class ConversationsService {
203
204
  runs;
204
205
  providers;
205
206
  content;
206
- attachments;
207
+ libraryFiles;
207
208
  invoker;
208
209
  deletion;
209
210
  devices;
@@ -222,8 +223,8 @@ let ConversationsService = class ConversationsService {
222
223
  providers,
223
224
  /** Reads `@` resources with the sender's credentials. */
224
225
  content,
225
- /** Binds uploaded files to the conversation in the message's transaction. */
226
- attachments,
226
+ /** Attaches the sender's library files to the conversation in the message's transaction. */
227
+ libraryFiles,
227
228
  /** Renders a person's skill invocation (phase D). */
228
229
  invoker,
229
230
  /** Stops a deleted conversation's background tasks. */
@@ -248,7 +249,7 @@ let ConversationsService = class ConversationsService {
248
249
  this.runs = runs;
249
250
  this.providers = providers;
250
251
  this.content = content;
251
- this.attachments = attachments;
252
+ this.libraryFiles = libraryFiles;
252
253
  this.invoker = invoker;
253
254
  this.deletion = deletion;
254
255
  this.devices = devices;
@@ -586,7 +587,7 @@ let ConversationsService = class ConversationsService {
586
587
  await unbindConversation(this.db.db, conversationId);
587
588
  // its shares stop with it and their snapshots are owed for deletion (file sharing spec §9);
588
589
  // a share being created waits on the row lock above (`FOR SHARE`) and then finds it deleted
589
- await revokeSharesIn(this.db.db, this.outbox, { conversationId }, "conversation_deleted");
590
+ await revokeSharesIn(this.db.db, { conversationId }, "conversation_deleted");
590
591
  // the device's services (the browser's tabs) forget the conversation: the notice is owed here
591
592
  // and delivered by the worker, an offline device's once it is back (close tabs on delete §4)
592
593
  if (subject.deviceId)
@@ -1209,6 +1210,21 @@ let ConversationsService = class ConversationsService {
1209
1210
  // happen (the process died) or fail (transactional outbox spec §6)
1210
1211
  if (fresh.at(-1) === true)
1211
1212
  await this.runs.oweEnsureRun(conversationId, message.seq, orgId);
1213
+ // the files this message attached were first referred to by it (a queued message's files keep
1214
+ // a null `first_seq`: they were attached when queued, before the message had a seq)
1215
+ const fileIds = blocks.flatMap((b) => (b.type === "image" || b.type === "document" || b.type === "file") && b.source.kind === "ref"
1216
+ ? [refFileId(b.source)]
1217
+ : []);
1218
+ if (fileIds.length > 0) {
1219
+ await this.db.db
1220
+ .updateTable("conversation_files")
1221
+ .set({ first_seq: message.seq })
1222
+ .where("org_id", "=", orgId)
1223
+ .where("conversation_id", "=", conversationId)
1224
+ .where("file_id", "in", fileIds)
1225
+ .where("first_seq", "is", null)
1226
+ .execute();
1227
+ }
1212
1228
  const skips = fresh.at(-1) === true
1213
1229
  ? await this.skipWaitsIn(conversationId, accountId, message.seq)
1214
1230
  : { skipped: NO_REPLY_SKIPS, toSeq: null };
@@ -1307,14 +1323,15 @@ let ConversationsService = class ConversationsService {
1307
1323
  return { paths, root: project.path };
1308
1324
  }
1309
1325
  /**
1310
- * Binds uploaded files inside the message's (or queue item's) transaction; none → no blocks.
1311
- * The bound files join the conversation's files, so open pages read the list again after the
1312
- * commit (`changed: files`, a hint).
1326
+ * Attaches the sender's library files inside the message's (or queue item's) transaction
1327
+ * (`LibraryFilesService.attachForMessage`: drafts become ready, the conversation refers to each);
1328
+ * none → no blocks. The files join the conversation's files, so open pages read the list again
1329
+ * after the commit (`changed: files`, a hint).
1313
1330
  */
1314
1331
  async bindIn(orgId, conversationId, accountId, files) {
1315
1332
  if (files.length === 0)
1316
1333
  return [];
1317
- const blocks = await this.attachments.bindForMessage(orgId, conversationId, accountId, files);
1334
+ const blocks = await this.libraryFiles.attachForMessage(orgId, conversationId, accountId, files);
1318
1335
  afterCommit(() => this.eventLog.publishChanged(conversationId, "files"));
1319
1336
  return blocks;
1320
1337
  }
@@ -1518,7 +1535,7 @@ ConversationsService = __decorate([
1518
1535
  __param(5, Inject(RunControlService)),
1519
1536
  __param(6, Inject(ProviderRegistry)),
1520
1537
  __param(7, Inject(ConnectorContent)),
1521
- __param(8, Inject(AttachmentsService)),
1538
+ __param(8, Inject(LibraryFilesService)),
1522
1539
  __param(9, Inject(SkillInvoker)),
1523
1540
  __param(10, Inject(RunDeletion)),
1524
1541
  __param(11, Inject(ConversationDevices)),
@@ -72,6 +72,7 @@ export type ConversationBusMessage = {
72
72
  kind: "ui";
73
73
  plugin: string;
74
74
  contribution: string;
75
+ queries?: true;
75
76
  } | {
76
77
  kind: "changed";
77
78
  what: ConversationChange;