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

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 (189) hide show
  1. package/dist/admin/admin.schemas.d.ts +3 -0
  2. package/dist/catalog/marketplaces.service.d.ts +1 -1
  3. package/dist/channels/channels.module.js +4 -3
  4. package/dist/channels/file-delivery.d.ts +26 -11
  5. package/dist/channels/file-delivery.js +32 -11
  6. package/dist/channels/outbound.d.ts +3 -3
  7. package/dist/channels/outbound.js +15 -13
  8. package/dist/config/schema.d.ts +3 -0
  9. package/dist/config/schema.js +12 -0
  10. package/dist/conversations/artifacts.d.ts +20 -17
  11. package/dist/conversations/artifacts.js +30 -37
  12. package/dist/conversations/attachments.controller.d.ts +6 -19
  13. package/dist/conversations/attachments.controller.js +8 -59
  14. package/dist/conversations/attachments.service.d.ts +30 -74
  15. package/dist/conversations/attachments.service.js +51 -193
  16. package/dist/conversations/conversations.module.js +4 -0
  17. package/dist/conversations/conversations.service.d.ts +10 -9
  18. package/dist/conversations/conversations.service.js +28 -11
  19. package/dist/conversations/event-log.d.ts +1 -0
  20. package/dist/conversations/events.d.ts +49 -27
  21. package/dist/conversations/events.js +54 -7
  22. package/dist/conversations/files.d.ts +66 -64
  23. package/dist/conversations/files.js +127 -147
  24. package/dist/conversations/prompt-suggestion-request.js +2 -1
  25. package/dist/conversations/prompt-suggestions.d.ts +3 -3
  26. package/dist/conversations/prompt-suggestions.js +11 -10
  27. package/dist/conversations/queue.service.js +7 -2
  28. package/dist/ctx/create-ctx.d.ts +3 -1
  29. package/dist/ctx/create-ctx.js +19 -1
  30. package/dist/db/kernel-schema.d.ts +80 -2
  31. package/dist/errors.d.ts +19 -0
  32. package/dist/errors.js +19 -0
  33. package/dist/evals/canonical-json.d.ts +7 -0
  34. package/dist/evals/canonical-json.js +21 -0
  35. package/dist/evals/reconstruct.js +13 -1
  36. package/dist/evals/recorded-tools.d.ts +0 -2
  37. package/dist/evals/recorded-tools.js +1 -16
  38. package/dist/evals/snapshot.d.ts +26 -3
  39. package/dist/evals/snapshot.js +110 -57
  40. package/dist/evals/worker.d.ts +4 -3
  41. package/dist/evals/worker.js +8 -4
  42. package/dist/extensions/host.d.ts +3 -1
  43. package/dist/extensions/host.js +2 -0
  44. package/dist/extensions/instance.d.ts +3 -1
  45. package/dist/extensions/instance.js +4 -0
  46. package/dist/extensions/ledger.d.ts +1 -1
  47. package/dist/files/blob-objects.d.ts +124 -0
  48. package/dist/files/blob-objects.js +341 -0
  49. package/dist/files/blob-sweep.job.d.ts +122 -0
  50. package/dist/files/blob-sweep.job.js +389 -0
  51. package/dist/files/blobs.service.d.ts +135 -0
  52. package/dist/files/blobs.service.js +300 -0
  53. package/dist/files/conversation-media.d.ts +41 -0
  54. package/dist/files/conversation-media.js +124 -0
  55. package/dist/files/deliveries.d.ts +64 -0
  56. package/dist/files/deliveries.js +156 -0
  57. package/dist/files/deliveries.module.d.ts +6 -0
  58. package/dist/files/deliveries.module.js +24 -0
  59. package/dist/files/draft-cleanup.job.d.ts +26 -0
  60. package/dist/files/draft-cleanup.job.js +93 -0
  61. package/dist/files/files.module.d.ts +1 -1
  62. package/dist/files/files.module.js +3 -2
  63. package/dist/files/hash-job.d.ts +127 -0
  64. package/dist/files/hash-job.js +447 -0
  65. package/dist/files/library-backfill.d.ts +63 -0
  66. package/dist/files/library-backfill.js +143 -0
  67. package/dist/files/library-files.service.d.ts +255 -0
  68. package/dist/files/library-files.service.js +883 -0
  69. package/dist/files/library-jobs.module.d.ts +8 -0
  70. package/dist/files/library-jobs.module.js +27 -0
  71. package/dist/files/library-query.d.ts +127 -0
  72. package/dist/files/library-query.js +322 -0
  73. package/dist/files/library-read.module.d.ts +9 -0
  74. package/dist/files/library-read.module.js +30 -0
  75. package/dist/files/library.controller.d.ts +77 -0
  76. package/dist/files/library.controller.js +235 -0
  77. package/dist/files/library.module.d.ts +9 -0
  78. package/dist/files/library.module.js +29 -0
  79. package/dist/files/library.schemas.d.ts +46 -0
  80. package/dist/files/library.schemas.js +49 -0
  81. package/dist/files/previewers.controller.d.ts +20 -0
  82. package/dist/files/previewers.controller.js +47 -0
  83. package/dist/files/previewers.d.ts +25 -11
  84. package/dist/files/previewers.js +43 -27
  85. package/dist/files/referenced-files.d.ts +150 -0
  86. package/dist/files/referenced-files.js +234 -0
  87. package/dist/html/html-document.controller.d.ts +8 -1
  88. package/dist/html/html-document.controller.js +19 -1
  89. package/dist/html/html-document.service.d.ts +19 -4
  90. package/dist/html/html-document.service.js +43 -22
  91. package/dist/html/html-token.d.ts +10 -1
  92. package/dist/html/html-token.js +14 -0
  93. package/dist/html/html.module.js +8 -1
  94. package/dist/http/api.module.js +5 -0
  95. package/dist/identity/settings.d.ts +26 -0
  96. package/dist/identity/settings.js +33 -2
  97. package/dist/infra/outbox/registry.d.ts +82 -0
  98. package/dist/infra/outbox/registry.js +74 -2
  99. package/dist/infra/throttler/named-throttlers.d.ts +2 -0
  100. package/dist/infra/throttler/named-throttlers.js +14 -0
  101. package/dist/lifecycle/kernel-lifecycle.js +6 -0
  102. package/dist/models/purposes.js +1 -1
  103. package/dist/orgs/offboarding.js +1 -1
  104. package/dist/orgs/settings.service.d.ts +48 -2
  105. package/dist/orgs/settings.service.js +63 -3
  106. package/dist/platform/exclusions.js +45 -8
  107. package/dist/platform/file-ref.d.ts +18 -3
  108. package/dist/platform/file-ref.js +22 -11
  109. package/dist/platform/operation.js +4 -0
  110. package/dist/platform/ops/admin.ops.js +5 -2
  111. package/dist/platform/ops/files.ops.d.ts +18 -0
  112. package/dist/platform/ops/files.ops.js +267 -0
  113. package/dist/platform/ops/org-settings.ops.js +6 -2
  114. package/dist/platform/ops/orgs.ops.js +1 -0
  115. package/dist/platform/ops/shares.ops.js +2 -2
  116. package/dist/platform/platform-ops.module.d.ts +2 -1
  117. package/dist/platform/platform-ops.module.js +5 -0
  118. package/dist/platform/route-schemas.js +3 -0
  119. package/dist/roles/worker.module.js +15 -1
  120. package/dist/runtime/compaction-settings.service.d.ts +13 -1
  121. package/dist/runtime/compaction-settings.service.js +16 -1
  122. package/dist/runtime/compaction.service.d.ts +3 -1
  123. package/dist/runtime/compaction.service.js +3 -1
  124. package/dist/runtime/context/build.d.ts +18 -1
  125. package/dist/runtime/context/build.js +19 -8
  126. package/dist/runtime/context/cache-expiry.d.ts +31 -0
  127. package/dist/runtime/context/cache-expiry.js +60 -0
  128. package/dist/runtime/context/cache-ttl.d.ts +18 -0
  129. package/dist/runtime/context/cache-ttl.js +30 -0
  130. package/dist/runtime/context/compaction.d.ts +9 -2
  131. package/dist/runtime/context/compaction.js +50 -17
  132. package/dist/runtime/context/in-context-compaction.d.ts +156 -0
  133. package/dist/runtime/context/in-context-compaction.js +310 -0
  134. package/dist/runtime/hook-calls.d.ts +2 -1
  135. package/dist/runtime/hook-calls.js +5 -2
  136. package/dist/runtime/maintenance.d.ts +10 -2
  137. package/dist/runtime/maintenance.js +48 -8
  138. package/dist/runtime/model-call.d.ts +34 -5
  139. package/dist/runtime/model-call.js +207 -22
  140. package/dist/runtime/providers.js +11 -1
  141. package/dist/runtime/run-steps.d.ts +4 -2
  142. package/dist/runtime/run-steps.js +10 -5
  143. package/dist/runtime/runtime.module.js +3 -0
  144. package/dist/shares/liveness.d.ts +26 -12
  145. package/dist/shares/liveness.js +79 -20
  146. package/dist/shares/revoke.d.ts +16 -11
  147. package/dist/shares/revoke.js +18 -14
  148. package/dist/shares/share-objects.d.ts +16 -21
  149. package/dist/shares/share-objects.js +25 -55
  150. package/dist/shares/share-open.service.d.ts +8 -4
  151. package/dist/shares/share-open.service.js +14 -11
  152. package/dist/shares/shares.controller.d.ts +16 -5
  153. package/dist/shares/shares.controller.js +39 -5
  154. package/dist/shares/shares.module.d.ts +4 -4
  155. package/dist/shares/shares.module.js +7 -6
  156. package/dist/shares/shares.schemas.d.ts +4 -0
  157. package/dist/shares/shares.schemas.js +2 -0
  158. package/dist/shares/shares.service.d.ts +93 -54
  159. package/dist/shares/shares.service.js +292 -131
  160. package/dist/shares/sweep.job.d.ts +18 -39
  161. package/dist/shares/sweep.job.js +47 -206
  162. package/dist/tools/builtins/artifacts.d.ts +21 -13
  163. package/dist/tools/builtins/artifacts.js +81 -51
  164. package/dist/tools/builtins/builtin-tools.d.ts +7 -1
  165. package/dist/tools/builtins/builtin-tools.js +17 -6
  166. package/dist/tools/builtins/conversation-files.d.ts +23 -13
  167. package/dist/tools/builtins/conversation-files.js +62 -83
  168. package/dist/tools/builtins/image/generate.d.ts +7 -1
  169. package/dist/tools/builtins/image/generate.js +1 -1
  170. package/dist/tools/builtins/platform.js +1 -0
  171. package/dist/tools/builtins/sandbox/common.d.ts +6 -2
  172. package/dist/tools/builtins/sandbox/deliver.js +6 -7
  173. package/dist/tools/builtins/sandbox/fetch-attachment.d.ts +6 -5
  174. package/dist/tools/builtins/sandbox/fetch-attachment.js +19 -12
  175. package/dist/tools/tools.module.js +6 -0
  176. package/dist/ui/call-extension.d.ts +6 -4
  177. package/dist/ui/call-extension.js +5 -4
  178. package/dist/ui/embed-token.js +6 -3
  179. package/dist/ui/registry.d.ts +21 -5
  180. package/dist/ui/registry.js +24 -6
  181. package/dist/ui/ui.schemas.d.ts +22 -0
  182. package/dist/ui/ui.schemas.js +22 -4
  183. package/dist/ui/views.controller.d.ts +13 -3
  184. package/dist/ui/views.controller.js +33 -2
  185. package/dist/ui/views.d.ts +29 -1
  186. package/dist/ui/views.js +131 -7
  187. package/package.json +3 -3
  188. package/src/migrations/0190_file_library.sql +285 -0
  189. package/src/migrations/0191_file_library_copy.sql +4 -0
@@ -10,7 +10,6 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
10
10
  import { FILE_PREVIEW_EXTENSION_POINT, previewerAccepts, validateUiView, } from "@capybara-hq/plugin-sdk";
11
11
  import { Inject, Injectable, Optional } from "@nestjs/common";
12
12
  import { sql } from "kysely";
13
- import { attachmentContentMatches } from "../conversations/attachments.service.js";
14
13
  import { ConversationFiles } from "../conversations/files.js";
15
14
  import { ApiError } from "../errors.js";
16
15
  import { EffectiveConfigs } from "../extensions/effective-config.js";
@@ -24,6 +23,8 @@ import { KERNEL_LOGGER } from "../infra/tokens.js";
24
23
  import { SkillFiles } from "../skills/skill-files.js";
25
24
  import { StorageService } from "../storage/storage.service.js";
26
25
  import { callExtension } from "../ui/call-extension.js";
26
+ import { BlobsService } from "./blobs.service.js";
27
+ import { LibraryQuery } from "./library-query.js";
27
28
  /** Time limit of a previewer's render (UI refresh spec §5.3: 10 s on the conversation page). */
28
29
  export const FILE_PREVIEW_TIMEOUT_MS = 10_000;
29
30
  const notFound = () => new ApiError("ui.not_found", "Previewer not found");
@@ -101,7 +102,7 @@ let PreviewerRegistry = class PreviewerRegistry {
101
102
  txHost;
102
103
  timeoutMs;
103
104
  d;
104
- constructor(kdb, host, files, skillFiles, storage, effective, log, txHost, timeoutMs = FILE_PREVIEW_TIMEOUT_MS) {
105
+ constructor(kdb, host, files, library, blobs, skillFiles, storage, effective, log, txHost, timeoutMs = FILE_PREVIEW_TIMEOUT_MS) {
105
106
  this.txHost = txHost;
106
107
  this.timeoutMs = timeoutMs;
107
108
  this.d = {
@@ -111,6 +112,8 @@ let PreviewerRegistry = class PreviewerRegistry {
111
112
  host,
112
113
  enabledPlugins: (orgId) => host.enabledPlugins(orgId),
113
114
  files,
115
+ library,
116
+ blobs,
114
117
  skillFiles,
115
118
  storage,
116
119
  effective,
@@ -213,9 +216,22 @@ let PreviewerRegistry = class PreviewerRegistry {
213
216
  detail: { items, ...auditDetail },
214
217
  });
215
218
  }
216
- /** Previewers that take this file (viewer must read the conversation), in the org's order. */
219
+ /**
220
+ * The file a conversation or library previewer reads: with `conversationId`, a file of that
221
+ * conversation (the viewer must read it; `ConversationFiles.file`); without, one of the viewer's
222
+ * own library files (`LibraryQuery.live`: 404 `file.not_found` for anyone else's).
223
+ */
224
+ async fileFor(orgId, conversationId, viewer, fileId) {
225
+ return conversationId === undefined
226
+ ? this.d.library.live(orgId, viewer, fileId)
227
+ : this.d.files.file(orgId, conversationId, viewer, fileId);
228
+ }
229
+ /**
230
+ * Previewers that take this file, in the org's order: a file of the conversation (the viewer
231
+ * must read it), or without `conversationId` one of the viewer's library files.
232
+ */
217
233
  async forFile(orgId, conversationId, viewer, fileId) {
218
- const file = await this.d.files.file(orgId, conversationId, viewer, fileId);
234
+ const file = await this.fileFor(orgId, conversationId, viewer, fileId);
219
235
  return (await this.accepting(orgId, file)).map(item);
220
236
  }
221
237
  /**
@@ -247,28 +263,25 @@ let PreviewerRegistry = class PreviewerRegistry {
247
263
  });
248
264
  }
249
265
  /**
250
- * Renders a view previewer for one file: 404 `ui.not_found` when it does not take the file (or is
251
- * disabled, not enabled, an embed); the render's errors as for plugin views (504 / 502).
266
+ * Renders a view previewer for one file (of a conversation, or without `conversationId` of the
267
+ * viewer's library; args `source: "conversation"` then carry no `conversationId`): 404
268
+ * `ui.not_found` when it does not take the file (or is disabled, not enabled, an embed); the
269
+ * render's errors as for plugin views (504 / 502).
252
270
  */
253
271
  async render(t) {
254
- const file = await this.d.files.file(t.orgId, t.conversationId, t.accountId, t.fileId);
272
+ const file = await this.fileFor(t.orgId, t.conversationId, t.accountId, t.fileId);
255
273
  const l = await this.viewPreviewer(t.orgId, file, t.plugin, t.id);
256
- const store = this.d.storage.kernel(t.orgId);
257
274
  return this.renderWith(l, t, {
258
275
  source: "conversation",
259
276
  orgId: t.orgId,
260
277
  accountId: t.accountId,
261
- conversationId: t.conversationId,
278
+ ...(t.conversationId !== undefined && { conversationId: t.conversationId }),
262
279
  file: { id: file.id, name: file.name, contentType: file.contentType, size: file.size },
263
280
  }, async (signal) => {
264
- const got = await store.get(file.objectKey, { signal });
281
+ // the file's blob, still the recorded bytes (a replaced object is not the file any more)
282
+ const got = await this.d.blobs.open(t.orgId, file.blob, { signal });
265
283
  if (!got)
266
284
  throw new Error("the file is no longer available");
267
- // an attachment replaced since it was checked is not the file any more
268
- if (file.recorded && !attachmentContentMatches(file.recorded, got.head)) {
269
- await got.body.cancel().catch(() => { });
270
- throw new Error("the file is no longer available");
271
- }
272
285
  return got.body;
273
286
  });
274
287
  }
@@ -284,7 +297,6 @@ let PreviewerRegistry = class PreviewerRegistry {
284
297
  */
285
298
  async renderShare(t) {
286
299
  const l = await this.viewPreviewer(t.orgId, t.file, t.plugin, t.id);
287
- const store = this.d.storage.kernel(t.orgId);
288
300
  return this.renderWith(l, t, {
289
301
  source: "share",
290
302
  orgId: t.orgId,
@@ -296,7 +308,8 @@ let PreviewerRegistry = class PreviewerRegistry {
296
308
  size: t.file.size,
297
309
  },
298
310
  }, async (signal) => {
299
- const got = await store.get(t.file.objectKey, { signal });
311
+ // the share's blob, still the recorded bytes
312
+ const got = await this.d.blobs.open(t.orgId, t.file.blob, { signal });
300
313
  if (!got)
301
314
  throw new Error("the file is no longer available");
302
315
  return got.body;
@@ -455,11 +468,12 @@ let PreviewerRegistry = class PreviewerRegistry {
455
468
  }
456
469
  /**
457
470
  * Whether an embed token for a `file.preview` contribution may be issued for this file: the
458
- * viewer reads the conversation, the file is in it, and an enabled previewer of that extension
459
- * with `embed: contribution` takes it. Conversation / file not found throws 404.
471
+ * viewer reads the conversation and the file is in it (without `conversationId`: the file is
472
+ * one of the viewer's own library files), and an enabled previewer of that extension with
473
+ * `embed: contribution` takes it. Conversation / file not found throws 404.
460
474
  */
461
475
  async embedAllowed(t) {
462
- const file = await this.d.files.file(t.orgId, t.conversationId, t.accountId, t.fileId);
476
+ const file = await this.fileFor(t.orgId, t.conversationId, t.accountId, t.fileId);
463
477
  return (await this.accepting(t.orgId, file)).some((l) => l.plugin === t.plugin && l.previewer.embed === t.contribution);
464
478
  }
465
479
  };
@@ -471,12 +485,14 @@ PreviewerRegistry = __decorate([
471
485
  __param(0, Inject(KernelDb)),
472
486
  __param(1, Inject(ExtensionHost)),
473
487
  __param(2, Inject(ConversationFiles)),
474
- __param(3, Inject(SkillFiles)),
475
- __param(4, Inject(StorageService)),
476
- __param(5, Inject(EffectiveConfigs)),
477
- __param(6, Inject(KERNEL_LOGGER)),
478
- __param(7, Inject(TransactionHost)),
479
- __param(8, Optional()),
480
- __param(8, Inject(FILE_PREVIEW_TIMEOUT))
488
+ __param(3, Inject(LibraryQuery)),
489
+ __param(4, Inject(BlobsService)),
490
+ __param(5, Inject(SkillFiles)),
491
+ __param(6, Inject(StorageService)),
492
+ __param(7, Inject(EffectiveConfigs)),
493
+ __param(8, Inject(KERNEL_LOGGER)),
494
+ __param(9, Inject(TransactionHost)),
495
+ __param(10, Optional()),
496
+ __param(10, Inject(FILE_PREVIEW_TIMEOUT))
481
497
  ], PreviewerRegistry);
482
498
  export { PreviewerRegistry };
@@ -0,0 +1,150 @@
1
+ import type { ObjectHead } from "@capybara-hq/plugin-sdk";
2
+ import type { FileOrigin, FileStatus } from "../db/kernel-schema.js";
3
+ import { KernelDb } from "../infra/database/kernel-db.js";
4
+ import { StorageService } from "../storage/storage.service.js";
5
+ import { type BlobRow, BlobsService } from "./blobs.service.js";
6
+ /** A library file row (file library spec §1). */
7
+ export interface LibraryFile {
8
+ id: string;
9
+ orgId: string;
10
+ accountId: string;
11
+ blobId: string | null;
12
+ name: string;
13
+ contentType: string;
14
+ size: number;
15
+ pages: number | null;
16
+ origin: FileOrigin;
17
+ status: FileStatus;
18
+ agentId: string | null;
19
+ sourceConversationId: string | null;
20
+ sourcePath: string | null;
21
+ /**
22
+ * The key and etag of the blob the file was first stored on (`files.ref_key` / `ref_etag`): the
23
+ * model-visible reference ({@link ReferencedFiles.modelRef}) stays the same when the file moves
24
+ * to another blob. Null key: the blob's own.
25
+ */
26
+ refKey: string | null;
27
+ refEtag: string | null;
28
+ createdAt: Date;
29
+ deletedAt: Date | null;
30
+ }
31
+ /**
32
+ * A file one conversation refers to (`conversation_files`), with its blob (null when the file has
33
+ * none any more). One entry per conversation and file: a file referred to by two conversations of
34
+ * a set appears twice.
35
+ */
36
+ export interface FileReference extends LibraryFile {
37
+ blob: BlobRow | null;
38
+ /** The conversation that refers to the file. */
39
+ conversationId: string;
40
+ role: "attached" | "delivered";
41
+ /** The event that first referred to it; null when not known (migrated rows, queued messages). */
42
+ firstSeq: number | null;
43
+ /** When the conversation started referring to it. */
44
+ referencedAt: Date;
45
+ }
46
+ /** A {@link FileReference} whose file is `ready` and whose blob is `ready`. */
47
+ export type ReferencedFile = FileReference & {
48
+ blob: BlobRow;
49
+ };
50
+ /** A file sent into the conversation (`FetchAttachment`'s list). */
51
+ export interface AttachedFile {
52
+ id: string;
53
+ name: string;
54
+ /** Whether it can be copied now (not deleted, its blob ready); names are assigned over all. */
55
+ available: boolean;
56
+ /** The unsigned reference the model saw in a reference line ({@link ReferencedFiles.uri}). */
57
+ uri: string;
58
+ }
59
+ /** {@link ReferencedFiles.openForConversation}'s result. */
60
+ export interface OpenedFile {
61
+ name: string;
62
+ contentType: string;
63
+ size: number;
64
+ body: ReadableStream<Uint8Array>;
65
+ }
66
+ /** Whether a reference can be read: the file `ready` and its blob `ready`. */
67
+ export declare const isLive: (f: FileReference) => f is ReferencedFile;
68
+ /**
69
+ * The read side of the file library for conversations (file library spec §2, §5): which files a
70
+ * set of conversations refers to (`conversation_files` → `files` → `blobs`), and their bytes
71
+ * through {@link BlobsService} (size and etag checked; never an event's `objectKey`). A file
72
+ * reaches a conversation, its model or its device only through such a reference: a library file
73
+ * the person never attached is not found here. Callers check who may read the conversations
74
+ * first. No process state.
75
+ */
76
+ export declare class ReferencedFiles {
77
+ private readonly db;
78
+ private readonly storage;
79
+ private readonly blobs;
80
+ constructor(db: KernelDb, storage: Pick<StorageService, "kernel">, blobs: Pick<BlobsService, "open" | "head">);
81
+ /** The file and blob columns, the blob's prefixed with `b_`. */
82
+ private fileQuery;
83
+ /**
84
+ * Every reference of the conversations (any file status, any blob state: a deleted file stays
85
+ * listed so the conversation can show it as no longer available), oldest reference first, then
86
+ * the file id; with `ids`, only those files; with `role`, only that role.
87
+ */
88
+ references(orgId: string, conversationIds: readonly string[], opts?: {
89
+ ids?: readonly string[];
90
+ role?: FileReference["role"];
91
+ }): Promise<FileReference[]>;
92
+ /**
93
+ * The files any of the conversations refers to that can be read now (the file `ready`, its blob
94
+ * `ready`), as {@link references} orders them; with `ids`, only those files.
95
+ */
96
+ referenced(orgId: string, conversationIds: readonly string[], ids?: readonly string[]): Promise<ReferencedFile[]>;
97
+ /**
98
+ * One of the account's files that the account may use (file library spec §2): `ready`, or a
99
+ * `draft` (the composer's own upload, not sent yet), with its blob; another account's, an unknown
100
+ * id, an upload not finalized or a deleted file → `file.not_found`.
101
+ */
102
+ owned(orgId: string, accountId: string, fileId: string): Promise<LibraryFile & {
103
+ blob: BlobRow | null;
104
+ }>;
105
+ /**
106
+ * What the model sees of a file's bytes, pinned to the blob the file was first stored on so a
107
+ * later move to another blob (a hashing merge) changes no model-visible text and no replay etag:
108
+ * `uri`, the store's unsigned reference of that key (else `capybara://attachments/<fileId>`, the
109
+ * form logs already hold), and `etag` (with `refKey` set, `refEtag` as recorded; else the
110
+ * blob's). Byte reads still check the current blob's own size and etag.
111
+ */
112
+ modelRef(orgId: string, f: Pick<LibraryFile, "id" | "refKey" | "refEtag"> & {
113
+ blob: Pick<BlobRow, "objectKey" | "etag">;
114
+ }): {
115
+ uri: string;
116
+ etag: string | null;
117
+ };
118
+ /**
119
+ * The live files of id `fileId` that sub-agent conversations below `ancestorId` refer to (its
120
+ * children, grandchildren …, at most {@link TREE_LEVELS} levels and {@link BELOW_LIMIT}
121
+ * referring conversations): one query over the parent index joined to the references.
122
+ */
123
+ referencedBelow(orgId: string, ancestorId: string, fileId: string): Promise<ReferencedFile[]>;
124
+ /** A live file's bytes ({@link BlobsService.open}): null when the blob is certainly gone. */
125
+ open(orgId: string, f: ReferencedFile, opts?: {
126
+ range?: {
127
+ start: number;
128
+ end?: number;
129
+ };
130
+ signal?: AbortSignal;
131
+ }): Promise<{
132
+ head: ObjectHead;
133
+ body: ReadableStream<Uint8Array>;
134
+ } | null>;
135
+ /** A live file's stored head ({@link BlobsService.head}): null when gone or replaced. */
136
+ head(orgId: string, f: ReferencedFile): Promise<ObjectHead | null>;
137
+ /**
138
+ * The files sent into the conversation (`FetchAttachment`): its `attached` references, oldest
139
+ * reference first, then the id (a later attachment never moves an earlier one), each marked
140
+ * `available` when it can be copied now. The copy assigns names over the whole list, so a file
141
+ * deleted later never renames another.
142
+ */
143
+ listForConversation(orgId: string, conversationId: string): Promise<AttachedFile[]>;
144
+ /**
145
+ * Opens one file sent into the conversation ({@link listForConversation}); null when it is not
146
+ * one of them any more or its bytes are gone. Other errors (storage unavailable) throw. The
147
+ * caller reads or cancels `body`.
148
+ */
149
+ openForConversation(orgId: string, conversationId: string, fileId: string): Promise<OpenedFile | null>;
150
+ }
@@ -0,0 +1,234 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
+ return function (target, key) { decorator(target, key, paramIndex); }
9
+ };
10
+ import { Inject, Injectable } from "@nestjs/common";
11
+ import { sql } from "kysely";
12
+ import { ApiError } from "../errors.js";
13
+ import { KernelDb } from "../infra/database/kernel-db.js";
14
+ import { StorageService } from "../storage/storage.service.js";
15
+ import { BlobsService } from "./blobs.service.js";
16
+ /** Whether a reference can be read: the file `ready` and its blob `ready`. */
17
+ export const isLive = (f) => f.status === "ready" && f.blob !== null && f.blob.status === "ready";
18
+ const notFound = () => new ApiError("file.not_found", "File not found");
19
+ /** How many sub-agent levels {@link ReferencedFiles.referencedBelow} walks (the tree reads' bound). */
20
+ const TREE_LEVELS = 16;
21
+ /** The most referring sub-agent conversations {@link ReferencedFiles.referencedBelow} reads. */
22
+ const BELOW_LIMIT = 32;
23
+ const toFile = (r) => ({
24
+ id: r.id,
25
+ orgId: r.org_id,
26
+ accountId: r.account_id,
27
+ blobId: r.blob_id,
28
+ name: r.name,
29
+ contentType: r.content_type,
30
+ size: Number(r.size),
31
+ pages: r.pages,
32
+ origin: r.origin,
33
+ status: r.status,
34
+ agentId: r.agent_id,
35
+ sourceConversationId: r.source_conversation_id,
36
+ sourcePath: r.source_path,
37
+ refKey: r.ref_key,
38
+ refEtag: r.ref_etag,
39
+ createdAt: r.created_at,
40
+ deletedAt: r.deleted_at,
41
+ blob: r.b_id === null
42
+ ? null
43
+ : {
44
+ id: r.b_id,
45
+ orgId: r.org_id,
46
+ sha256: r.b_sha256,
47
+ size: Number(r.b_size),
48
+ etag: r.b_etag,
49
+ objectKey: r.b_object_key,
50
+ status: r.b_status,
51
+ },
52
+ });
53
+ /**
54
+ * The read side of the file library for conversations (file library spec §2, §5): which files a
55
+ * set of conversations refers to (`conversation_files` → `files` → `blobs`), and their bytes
56
+ * through {@link BlobsService} (size and etag checked; never an event's `objectKey`). A file
57
+ * reaches a conversation, its model or its device only through such a reference: a library file
58
+ * the person never attached is not found here. Callers check who may read the conversations
59
+ * first. No process state.
60
+ */
61
+ let ReferencedFiles = class ReferencedFiles {
62
+ db;
63
+ storage;
64
+ blobs;
65
+ constructor(db, storage, blobs) {
66
+ this.db = db;
67
+ this.storage = storage;
68
+ this.blobs = blobs;
69
+ }
70
+ /** The file and blob columns, the blob's prefixed with `b_`. */
71
+ fileQuery(orgId) {
72
+ return this.db
73
+ .selectFrom("files as f")
74
+ .leftJoin("blobs as b", (j) => j.onRef("b.id", "=", "f.blob_id").on("b.org_id", "=", orgId))
75
+ .select([
76
+ "f.id",
77
+ "f.org_id",
78
+ "f.account_id",
79
+ "f.blob_id",
80
+ "f.name",
81
+ "f.content_type",
82
+ "f.size",
83
+ "f.pages",
84
+ "f.origin",
85
+ "f.status",
86
+ "f.agent_id",
87
+ "f.source_conversation_id",
88
+ "f.source_path",
89
+ "f.ref_key",
90
+ "f.ref_etag",
91
+ "f.created_at",
92
+ "f.deleted_at",
93
+ "b.id as b_id",
94
+ "b.sha256 as b_sha256",
95
+ "b.size as b_size",
96
+ "b.etag as b_etag",
97
+ "b.object_key as b_object_key",
98
+ "b.status as b_status",
99
+ ])
100
+ .where("f.org_id", "=", orgId);
101
+ }
102
+ /**
103
+ * Every reference of the conversations (any file status, any blob state: a deleted file stays
104
+ * listed so the conversation can show it as no longer available), oldest reference first, then
105
+ * the file id; with `ids`, only those files; with `role`, only that role.
106
+ */
107
+ async references(orgId, conversationIds, opts = {}) {
108
+ if (conversationIds.length === 0 || opts.ids?.length === 0)
109
+ return [];
110
+ let q = this.fileQuery(orgId)
111
+ .innerJoin("conversation_files as cf", (j) => j.onRef("cf.file_id", "=", "f.id").on("cf.org_id", "=", orgId))
112
+ .select(["cf.conversation_id", "cf.role", "cf.first_seq", "cf.created_at as referenced_at"])
113
+ .where("cf.conversation_id", "in", [...new Set(conversationIds)]);
114
+ if (opts.ids !== undefined)
115
+ q = q.where("f.id", "in", [...new Set(opts.ids)]);
116
+ if (opts.role !== undefined)
117
+ q = q.where("cf.role", "=", opts.role);
118
+ const rows = await q.orderBy("cf.created_at").orderBy("f.id").execute();
119
+ return rows.map((r) => ({
120
+ ...toFile(r),
121
+ conversationId: r.conversation_id,
122
+ role: r.role,
123
+ firstSeq: r.first_seq === null ? null : Number(r.first_seq),
124
+ referencedAt: r.referenced_at,
125
+ }));
126
+ }
127
+ /**
128
+ * The files any of the conversations refers to that can be read now (the file `ready`, its blob
129
+ * `ready`), as {@link references} orders them; with `ids`, only those files.
130
+ */
131
+ async referenced(orgId, conversationIds, ids) {
132
+ const refs = await this.references(orgId, conversationIds, ids === undefined ? {} : { ids });
133
+ return refs.filter(isLive);
134
+ }
135
+ /**
136
+ * One of the account's files that the account may use (file library spec §2): `ready`, or a
137
+ * `draft` (the composer's own upload, not sent yet), with its blob; another account's, an unknown
138
+ * id, an upload not finalized or a deleted file → `file.not_found`.
139
+ */
140
+ async owned(orgId, accountId, fileId) {
141
+ const row = await this.fileQuery(orgId)
142
+ .where("f.id", "=", fileId)
143
+ .where("f.account_id", "=", accountId)
144
+ .where("f.status", "in", ["ready", "draft"])
145
+ .executeTakeFirst();
146
+ if (!row)
147
+ throw notFound();
148
+ return toFile(row);
149
+ }
150
+ /**
151
+ * What the model sees of a file's bytes, pinned to the blob the file was first stored on so a
152
+ * later move to another blob (a hashing merge) changes no model-visible text and no replay etag:
153
+ * `uri`, the store's unsigned reference of that key (else `capybara://attachments/<fileId>`, the
154
+ * form logs already hold), and `etag` (with `refKey` set, `refEtag` as recorded; else the
155
+ * blob's). Byte reads still check the current blob's own size and etag.
156
+ */
157
+ modelRef(orgId, f) {
158
+ const key = f.refKey ?? f.blob.objectKey;
159
+ return {
160
+ uri: this.storage.kernel(orgId).uri?.(key) ?? `capybara://attachments/${f.id}`,
161
+ etag: f.refKey !== null ? f.refEtag : f.blob.etag,
162
+ };
163
+ }
164
+ /**
165
+ * The live files of id `fileId` that sub-agent conversations below `ancestorId` refer to (its
166
+ * children, grandchildren …, at most {@link TREE_LEVELS} levels and {@link BELOW_LIMIT}
167
+ * referring conversations): one query over the parent index joined to the references.
168
+ */
169
+ async referencedBelow(orgId, ancestorId, fileId) {
170
+ const below = await sql `
171
+ WITH RECURSIVE tree(id, level) AS (
172
+ SELECT c.id, 1 FROM capybara.conversations c
173
+ WHERE c.parent_conversation_id = ${ancestorId} AND c.org_id = ${orgId}
174
+ AND c.kind = 'subagent'
175
+ UNION ALL
176
+ SELECT c.id, t.level + 1
177
+ FROM capybara.conversations c JOIN tree t ON c.parent_conversation_id = t.id
178
+ WHERE c.org_id = ${orgId} AND c.kind = 'subagent' AND t.level < ${TREE_LEVELS}
179
+ )
180
+ SELECT cf.conversation_id FROM capybara.conversation_files cf
181
+ JOIN tree t ON t.id = cf.conversation_id
182
+ WHERE cf.org_id = ${orgId} AND cf.file_id = ${fileId}
183
+ LIMIT ${BELOW_LIMIT}`.execute(this.db.db);
184
+ if (below.rows.length === 0)
185
+ return [];
186
+ return this.referenced(orgId, below.rows.map((r) => r.conversation_id), [fileId]);
187
+ }
188
+ /** A live file's bytes ({@link BlobsService.open}): null when the blob is certainly gone. */
189
+ open(orgId, f, opts = {}) {
190
+ return this.blobs.open(orgId, f.blob, opts);
191
+ }
192
+ /** A live file's stored head ({@link BlobsService.head}): null when gone or replaced. */
193
+ head(orgId, f) {
194
+ return this.blobs.head(orgId, f.blob);
195
+ }
196
+ /**
197
+ * The files sent into the conversation (`FetchAttachment`): its `attached` references, oldest
198
+ * reference first, then the id (a later attachment never moves an earlier one), each marked
199
+ * `available` when it can be copied now. The copy assigns names over the whole list, so a file
200
+ * deleted later never renames another.
201
+ */
202
+ async listForConversation(orgId, conversationId) {
203
+ const refs = await this.references(orgId, [conversationId], { role: "attached" });
204
+ return refs.map((f) => ({
205
+ id: f.id,
206
+ name: f.name,
207
+ available: isLive(f),
208
+ uri: f.blob
209
+ ? this.modelRef(orgId, { ...f, blob: f.blob }).uri
210
+ : `capybara://attachments/${f.id}`,
211
+ }));
212
+ }
213
+ /**
214
+ * Opens one file sent into the conversation ({@link listForConversation}); null when it is not
215
+ * one of them any more or its bytes are gone. Other errors (storage unavailable) throw. The
216
+ * caller reads or cancels `body`.
217
+ */
218
+ async openForConversation(orgId, conversationId, fileId) {
219
+ const [f] = (await this.references(orgId, [conversationId], { ids: [fileId], role: "attached" })).filter(isLive);
220
+ if (!f)
221
+ return null;
222
+ const got = await this.open(orgId, f);
223
+ if (!got)
224
+ return null;
225
+ return { name: f.name, contentType: f.contentType, size: f.size, body: got.body };
226
+ }
227
+ };
228
+ ReferencedFiles = __decorate([
229
+ Injectable(),
230
+ __param(0, Inject(KernelDb)),
231
+ __param(1, Inject(StorageService)),
232
+ __param(2, Inject(BlobsService))
233
+ ], ReferencedFiles);
234
+ export { ReferencedFiles };
@@ -9,9 +9,14 @@ export declare const HtmlTokenParams: z.ZodObject<{
9
9
  id: z.ZodString;
10
10
  fileId: z.ZodString;
11
11
  }, z.core.$strip>;
12
+ /** `POST …/files/:id/html-token` (a library file). */
13
+ export declare const LibraryHtmlTokenParams: z.ZodObject<{
14
+ id: z.ZodString;
15
+ }, z.core.$strip>;
12
16
  /**
13
17
  * The HTML document (file sharing spec §4): the right panel mints a document token for one
14
- * version of the caller's HTML file (`agents.use`, the conversation's owner), then frames
18
+ * version of the caller's HTML file (`agents.use`, the conversation's owner; the Files page the
19
+ * same for one of the caller's library files, `POST …/files/:id/html-token`), then frames
15
20
  * `/api/v1/html/<token>`. The document route is public: the token is the authority, checked and
16
21
  * then re-checked live by {@link HtmlDocumentService.serve}.
17
22
  */
@@ -21,6 +26,8 @@ export declare class HtmlDocumentController {
21
26
  constructor(documents: HtmlDocumentService, tokens: HtmlTokens);
22
27
  /** A document token: 200 `{ path, expiresIn }`. */
23
28
  mint(principal: Principal, org: OrgContext, params: z.infer<typeof HtmlTokenParams>): Promise<HtmlTokenResponse>;
29
+ /** A document token for a library file: 200 `{ path, expiresIn }`. */
30
+ mintLibrary(principal: Principal, org: OrgContext, params: z.infer<typeof LibraryHtmlTokenParams>): Promise<HtmlTokenResponse>;
24
31
  /**
25
32
  * The document a token names (`/api/v1/html/<token>`), under the sandbox CSP. A bad or expired
26
33
  * token, or a live check failing, is 404 `not_found` (one answer for every refusal). A wildcard
@@ -20,11 +20,16 @@ export const HtmlTokenParams = z.object({
20
20
  id: z.string().min(1).max(100),
21
21
  fileId: z.string().min(1).max(100),
22
22
  });
23
+ /** `POST …/files/:id/html-token` (a library file). */
24
+ export const LibraryHtmlTokenParams = z.object({ id: z.string().min(1).max(100) });
23
25
  class HtmlTokenParamsDto extends createZodDto(HtmlTokenParams, "HtmlTokenParams") {
24
26
  }
27
+ class LibraryHtmlTokenParamsDto extends createZodDto(LibraryHtmlTokenParams, "LibraryHtmlTokenParams") {
28
+ }
25
29
  /**
26
30
  * The HTML document (file sharing spec §4): the right panel mints a document token for one
27
- * version of the caller's HTML file (`agents.use`, the conversation's owner), then frames
31
+ * version of the caller's HTML file (`agents.use`, the conversation's owner; the Files page the
32
+ * same for one of the caller's library files, `POST …/files/:id/html-token`), then frames
28
33
  * `/api/v1/html/<token>`. The document route is public: the token is the authority, checked and
29
34
  * then re-checked live by {@link HtmlDocumentService.serve}.
30
35
  */
@@ -40,6 +45,11 @@ let HtmlDocumentController = class HtmlDocumentController {
40
45
  const p = requireUser(principal);
41
46
  return this.documents.mint(org.orgId, params.id, p.account.id, params.fileId);
42
47
  }
48
+ /** A document token for a library file: 200 `{ path, expiresIn }`. */
49
+ async mintLibrary(principal, org, params) {
50
+ const p = requireUser(principal);
51
+ return this.documents.mintLibrary(org.orgId, p.account.id, params.id);
52
+ }
43
53
  /**
44
54
  * The document a token names (`/api/v1/html/<token>`), under the sandbox CSP. A bad or expired
45
55
  * token, or a live check failing, is 404 `not_found` (one answer for every refusal). A wildcard
@@ -61,6 +71,14 @@ __decorate([
61
71
  __param(1, CurrentOrg()),
62
72
  __param(2, ZParam(HtmlTokenParamsDto))
63
73
  ], HtmlDocumentController.prototype, "mint", null);
74
+ __decorate([
75
+ Post("orgs/:orgId/files/:id/html-token"),
76
+ HttpCode(200),
77
+ OrgAction("agents.use"),
78
+ __param(0, CurrentPrincipal()),
79
+ __param(1, CurrentOrg()),
80
+ __param(2, ZParam(LibraryHtmlTokenParamsDto))
81
+ ], HtmlDocumentController.prototype, "mintLibrary", null);
64
82
  __decorate([
65
83
  Public(),
66
84
  Get("html/*"),
@@ -1,10 +1,11 @@
1
1
  import type { FastifyReply } from "fastify";
2
2
  import { ConversationFiles } from "../conversations/files.js";
3
3
  import { ApiError } from "../errors.js";
4
+ import { BlobsService } from "../files/blobs.service.js";
5
+ import { LibraryQuery } from "../files/library-query.js";
4
6
  import { KernelDb } from "../infra/database/kernel-db.js";
5
7
  import type { KernelLogger } from "../log.js";
6
8
  import { ShareLiveness } from "../shares/liveness.js";
7
- import { StorageService } from "../storage/storage.service.js";
8
9
  import { type HtmlClaims, HtmlTokens } from "./html-token.js";
9
10
  /** What `POST …/html-token` returns: `path` loads the document once within `expiresIn` seconds. */
10
11
  export interface HtmlTokenResponse {
@@ -18,7 +19,8 @@ export declare const htmlNotFound: () => ApiError;
18
19
  * mints a short-lived document token for one version of an HTML file ({@link mint}); the public
19
20
  * route serves it ({@link serve}) under the sandbox CSP after re-checking, live, what the token
20
21
  * names: the owner can still read the file (`ConversationFiles.file`: membership, active account,
21
- * conversation and agent not deleted; an upload's object still the one finalize checked), or the
22
+ * conversation and agent not deleted; the file not deleted and its blob still the recorded bytes;
23
+ * a library file: `LibraryQuery.live`, still the account's and not deleted), or the
22
24
  * share is still live at that generation (`ShareLiveness.byId`). The bytes are streamed by the
23
25
  * kernel as stored; never a presigned URL on the app origin. HTML larger than
24
26
  * `FILE_PREVIEW_MAX_BYTES` is never rendered.
@@ -26,11 +28,18 @@ export declare const htmlNotFound: () => ApiError;
26
28
  export declare class HtmlDocumentService {
27
29
  private readonly db;
28
30
  private readonly files;
31
+ /** The account's own library files (the Files page). */
32
+ private readonly library;
29
33
  private readonly liveness;
30
- private readonly storage;
34
+ /** A conversation file's or a share's bytes, through its blob. */
35
+ private readonly blobs;
31
36
  private readonly tokens;
32
37
  private readonly log?;
33
- constructor(db: KernelDb, files: Pick<ConversationFiles, "file">, liveness: Pick<ShareLiveness, "byId">, storage: Pick<StorageService, "kernel">, tokens: HtmlTokens, log?: KernelLogger | undefined);
38
+ constructor(db: KernelDb, files: Pick<ConversationFiles, "file">,
39
+ /** The account's own library files (the Files page). */
40
+ library: Pick<LibraryQuery, "live">, liveness: Pick<ShareLiveness, "byId">,
41
+ /** A conversation file's or a share's bytes, through its blob. */
42
+ blobs: Pick<BlobsService, "open">, tokens: HtmlTokens, log?: KernelLogger | undefined);
34
43
  /**
35
44
  * A document token for one version of the caller's conversation file (a delivered version or an
36
45
  * upload). Not the owner → `conversation.not_found`; unknown file →
@@ -39,6 +48,12 @@ export declare class HtmlDocumentService {
39
48
  * `conversation.artifact_not_previewable`.
40
49
  */
41
50
  mint(orgId: string, conversationId: string, accountId: string, fileId: string): Promise<HtmlTokenResponse>;
51
+ /**
52
+ * A document token for one of the caller's library files (the Files page; file library spec
53
+ * §6): another account's, unknown or deleted → `file.not_found`; bytes gone → `file.deleted`;
54
+ * not HTML, or larger than `FILE_PREVIEW_MAX_BYTES` → `conversation.artifact_not_previewable`.
55
+ */
56
+ mintLibrary(orgId: string, accountId: string, fileId: string): Promise<HtmlTokenResponse>;
42
57
  /**
43
58
  * Serves the document verified claims name with the spec §4 headers, the CSP built from the CDN
44
59
  * allowlist read now. Any live check failing → 404 `not_found`.