@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
@@ -0,0 +1,8 @@
1
+ /**
2
+ * The file library's background jobs that the maintenance queue runs: the one-off catch-up copy
3
+ * ({@link FileLibraryBackfill}) and the hashing of migrated blobs ({@link FileLibraryHashJob}).
4
+ * Imported by the worker role only (`MaintenanceModule`, `WorkerModule`), which also provides
5
+ * their kickoff and the daily blob sweep.
6
+ */
7
+ export declare class FileLibraryJobsModule {
8
+ }
@@ -0,0 +1,27 @@
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
+ import { Module } from "@nestjs/common";
8
+ import { StorageModule } from "../storage/storage.module.js";
9
+ import { FileLibraryHashJob } from "./hash-job.js";
10
+ import { LibraryFilesModule } from "./library.module.js";
11
+ import { FileLibraryBackfill } from "./library-backfill.js";
12
+ /**
13
+ * The file library's background jobs that the maintenance queue runs: the one-off catch-up copy
14
+ * ({@link FileLibraryBackfill}) and the hashing of migrated blobs ({@link FileLibraryHashJob}).
15
+ * Imported by the worker role only (`MaintenanceModule`, `WorkerModule`), which also provides
16
+ * their kickoff and the daily blob sweep.
17
+ */
18
+ let FileLibraryJobsModule = class FileLibraryJobsModule {
19
+ };
20
+ FileLibraryJobsModule = __decorate([
21
+ Module({
22
+ imports: [StorageModule, LibraryFilesModule],
23
+ providers: [FileLibraryBackfill, FileLibraryHashJob],
24
+ exports: [FileLibraryBackfill, FileLibraryHashJob],
25
+ })
26
+ ], FileLibraryJobsModule);
27
+ export { FileLibraryJobsModule };
@@ -0,0 +1,127 @@
1
+ import { type FileContent } from "../conversations/files.js";
2
+ import type { FileOrigin } 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 BlobRef, BlobsService } from "./blobs.service.js";
6
+ import type { LIBRARY_ORIGINS, LIBRARY_TYPES } from "./library.schemas.js";
7
+ import { ReferencedFiles } from "./referenced-files.js";
8
+ /** A conversation as the library shows it: the owner's own, `deleted` once they deleted it. */
9
+ export interface LibraryConversation {
10
+ id: string;
11
+ title: string | null;
12
+ deleted: boolean;
13
+ }
14
+ /** One entry of the library list (`GET /files`): a file, or the newest version of a delivery. */
15
+ export interface LibraryFileView {
16
+ id: string;
17
+ name: string;
18
+ contentType: string;
19
+ size: number;
20
+ origin: FileOrigin;
21
+ /** The agent that delivered or generated it; null for an upload. */
22
+ agentId: string | null;
23
+ /** That agent's current name, when it can be read. */
24
+ agentName?: string;
25
+ /** Where it was delivered, or first sent; null when not known (or not the caller's). */
26
+ sourceConversation: LibraryConversation | null;
27
+ /** The ready versions of its delivery group (1 for an upload). */
28
+ versions: number;
29
+ createdAt: Date;
30
+ /** The built-in preview kind (`image`, `text`), null otherwise. */
31
+ previewable: "image" | "text" | null;
32
+ }
33
+ /** `GET /files/:id`: the view, the owner's conversations referring to it and its versions. */
34
+ export interface LibraryFileDetails {
35
+ file: LibraryFileView;
36
+ conversations: LibraryConversation[];
37
+ /** Newest first, at most {@link FILE_VERSIONS_MAX}. */
38
+ versions: {
39
+ id: string;
40
+ size: number;
41
+ createdAt: Date;
42
+ }[];
43
+ }
44
+ /** `GET /files/usage`: the caller's ready files and the bytes of the distinct blobs they use. */
45
+ export interface LibraryUsage {
46
+ bytes: number;
47
+ files: number;
48
+ }
49
+ /** A library file whose bytes can be read now, for the kernel only (the key never leaves it). */
50
+ export interface LiveLibraryFile {
51
+ id: string;
52
+ name: string;
53
+ contentType: string;
54
+ size: number;
55
+ blob: BlobRef;
56
+ }
57
+ export type LibraryOriginFilter = (typeof LIBRARY_ORIGINS)[number];
58
+ export type LibraryTypeFilter = (typeof LIBRARY_TYPES)[number];
59
+ /** `GET /files`' filters and page. */
60
+ export interface LibraryListOptions {
61
+ origin?: LibraryOriginFilter;
62
+ agentId?: string;
63
+ type?: LibraryTypeFilter;
64
+ q?: string;
65
+ limit: number;
66
+ cursor?: string;
67
+ }
68
+ /**
69
+ * The read side of the Files page (file library spec §6, §8): the caller's own files only (a file
70
+ * is visible to its owner alone), never another account's, whatever the org shares in blobs.
71
+ * Bytes are read through the file's blob with its size and etag checked, never an event's key.
72
+ * Read on every request; no process state.
73
+ */
74
+ export declare class LibraryQuery {
75
+ private readonly db;
76
+ private readonly files;
77
+ private readonly blobs;
78
+ private readonly storage;
79
+ constructor(db: KernelDb, files: Pick<ReferencedFiles, "owned">, blobs: Pick<BlobsService, "open" | "head">, storage: Pick<StorageService, "kernel">);
80
+ /**
81
+ * The views of the account's ready files of one org, newest first, deliveries of one source path
82
+ * in one conversation collapsed to the newest with their `versions` count. `where` filters the
83
+ * newest version (the entry); `limit` caps the rows.
84
+ */
85
+ private views;
86
+ /**
87
+ * `GET /files`: one page of the account's library (see {@link views}). `q` matches a
88
+ * case-insensitive substring of the name; `next` is the cursor of the following page, null on
89
+ * the last. A cursor this route did not hand out → 400 `validation_failed`.
90
+ */
91
+ list(orgId: string, accountId: string, opts: LibraryListOptions): Promise<{
92
+ files: LibraryFileView[];
93
+ next: string | null;
94
+ }>;
95
+ /** `GET /files/usage` (file library spec §8): other accounts' use of a blob never shows. */
96
+ usage(orgId: string, accountId: string): Promise<LibraryUsage>;
97
+ /**
98
+ * `GET /files/:id`: one of the account's ready files (any version of a delivery) with the
99
+ * owner's conversations referring to it (oldest reference first) and the ready versions of its
100
+ * group. Another account's, deleted or unknown → `file.not_found`.
101
+ */
102
+ details(orgId: string, accountId: string, fileId: string): Promise<LibraryFileDetails>;
103
+ /** The view of one ready file of the account (not collapsed: the file itself). */
104
+ private viewOfFile;
105
+ /**
106
+ * One of the account's files whose bytes can be read now (`ready`, or a `draft` of the
107
+ * composer: `ReferencedFiles.owned`), its blob ready and its stored object still the recorded
108
+ * bytes. Another account's, unknown or deleted → `file.not_found`; bytes gone → `file.deleted`.
109
+ */
110
+ live(orgId: string, accountId: string, fileId: string): Promise<LiveLibraryFile>;
111
+ /**
112
+ * The first `limit` bytes of a text file (the conversation route's twin): not text, or NUL
113
+ * bytes in what was read → `conversation.artifact_not_previewable`; a cut never splits a UTF-8
114
+ * character.
115
+ */
116
+ content(orgId: string, accountId: string, fileId: string, limit: number): Promise<FileContent>;
117
+ /**
118
+ * A presigned address of the file's bytes (the artifact download's twin): `attachment` with the
119
+ * file's name and type; `inline` only for bitmaps.
120
+ */
121
+ downloadUrl(orgId: string, accountId: string, fileId: string, opts?: {
122
+ inline?: boolean;
123
+ }): Promise<{
124
+ url: string;
125
+ name: string;
126
+ }>;
127
+ }
@@ -0,0 +1,322 @@
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 { ARTIFACT_DOWNLOAD_TTL_SECONDS, isInlineArtifactType, isTextArtifactType, } from "../conversations/artifacts.js";
13
+ import { FILE_CONTENT_MAX_BYTES, FILE_VERSIONS_MAX, previewKind, readPrefix, trimUtf8, } from "../conversations/files.js";
14
+ import { ApiError } from "../errors.js";
15
+ import { KernelDb } from "../infra/database/kernel-db.js";
16
+ import { StorageService } from "../storage/storage.service.js";
17
+ import { UUID_RE } from "../ui/registry.js";
18
+ import { BlobsService } from "./blobs.service.js";
19
+ import { ReferencedFiles } from "./referenced-files.js";
20
+ const notFound = () => new ApiError("file.not_found", "File not found");
21
+ const gone = () => new ApiError("file.deleted", "The file is no longer available");
22
+ const badCursor = () => new ApiError("validation_failed", "Request validation failed", [
23
+ { path: "cursor", message: "Pass the next value of the previous page" },
24
+ ]);
25
+ /** The content type without parameters, lower case (SQL). */
26
+ const baseType = sql `lower(btrim(split_part(f.content_type, ';', 1)))`;
27
+ /**
28
+ * The family `GET /files?type=` filters by: `image/*`; PDF and office documents; `text/*` and the
29
+ * text formats the previews read; everything else.
30
+ */
31
+ const typeFamily = sql `CASE
32
+ WHEN ${baseType} LIKE 'image/%' THEN 'image'
33
+ WHEN ${baseType} IN ('application/pdf', 'application/msword', 'application/rtf')
34
+ OR ${baseType} LIKE 'application/vnd.openxmlformats-officedocument.%'
35
+ OR ${baseType} LIKE 'application/vnd.ms-%'
36
+ OR ${baseType} LIKE 'application/vnd.oasis.opendocument.%' THEN 'document'
37
+ WHEN ${baseType} LIKE 'text/%'
38
+ OR ${baseType} IN ('application/json', 'application/xml', 'application/yaml', 'application/sql')
39
+ THEN 'text'
40
+ ELSE 'other' END`;
41
+ /**
42
+ * The version group of a file: the deliveries of one source path in one conversation share it;
43
+ * anything else (an upload, a delivery whose conversation is not known) is its own group.
44
+ */
45
+ const groupKey = sql `CASE
46
+ WHEN f.origin <> 'upload' AND f.source_path IS NOT NULL AND f.source_conversation_id IS NOT NULL
47
+ THEN f.source_conversation_id || chr(10) || f.source_path
48
+ ELSE f.id END`;
49
+ /** A cursor's time: UTC, microseconds (PG's precision; a JS `Date` would lose them). */
50
+ const CURSOR_TIME_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{6}$/;
51
+ const encodeCursor = (createdKey, id) => Buffer.from(JSON.stringify([createdKey, id]), "utf8").toString("base64url");
52
+ function decodeCursor(cursor) {
53
+ let parsed;
54
+ try {
55
+ parsed = JSON.parse(Buffer.from(cursor, "base64url").toString("utf8"));
56
+ }
57
+ catch {
58
+ throw badCursor();
59
+ }
60
+ if (!Array.isArray(parsed) || parsed.length !== 2)
61
+ throw badCursor();
62
+ const [createdKey, id] = parsed;
63
+ if (typeof createdKey !== "string" || !CURSOR_TIME_RE.test(createdKey))
64
+ throw badCursor();
65
+ if (typeof id !== "string" || id === "" || id.length > 100)
66
+ throw badCursor();
67
+ return { createdKey, id };
68
+ }
69
+ const viewOf = (r) => ({
70
+ id: r.id,
71
+ name: r.name,
72
+ contentType: r.content_type,
73
+ size: Number(r.size),
74
+ origin: r.origin,
75
+ agentId: r.agent_id,
76
+ ...(r.agent_name !== null && { agentName: r.agent_name }),
77
+ sourceConversation: r.conv_id === null
78
+ ? null
79
+ : { id: r.conv_id, title: r.conv_title, deleted: r.conv_deleted === true },
80
+ versions: Number(r.versions),
81
+ createdAt: r.created_at,
82
+ previewable: previewKind(r.content_type),
83
+ });
84
+ /**
85
+ * The read side of the Files page (file library spec §6, §8): the caller's own files only (a file
86
+ * is visible to its owner alone), never another account's, whatever the org shares in blobs.
87
+ * Bytes are read through the file's blob with its size and etag checked, never an event's key.
88
+ * Read on every request; no process state.
89
+ */
90
+ let LibraryQuery = class LibraryQuery {
91
+ db;
92
+ files;
93
+ blobs;
94
+ storage;
95
+ constructor(db, files, blobs, storage) {
96
+ this.db = db;
97
+ this.files = files;
98
+ this.blobs = blobs;
99
+ this.storage = storage;
100
+ }
101
+ /**
102
+ * The views of the account's ready files of one org, newest first, deliveries of one source path
103
+ * in one conversation collapsed to the newest with their `versions` count. `where` filters the
104
+ * newest version (the entry); `limit` caps the rows.
105
+ */
106
+ async views(orgId, accountId, where, limit) {
107
+ // the filters (q, type, cursor, ...) apply after the window on purpose: the versions of one
108
+ // path may have different names or types, and the entry is always the group's newest version
109
+ const conditions = [sql `m.rank = 1`, ...where];
110
+ const rows = await sql `
111
+ WITH mine AS (
112
+ SELECT f.id, f.name, f.content_type, f.size, f.origin, f.agent_id,
113
+ f.source_conversation_id, f.created_at, ${typeFamily} AS family,
114
+ row_number() OVER (PARTITION BY ${groupKey} ORDER BY f.created_at DESC, f.id DESC) AS rank,
115
+ count(*) OVER (PARTITION BY ${groupKey}) AS versions
116
+ FROM capybara.files f
117
+ WHERE f.org_id = ${orgId} AND f.account_id = ${accountId} AND f.status = 'ready'
118
+ )
119
+ SELECT m.id, m.name, m.content_type, m.size, m.origin, m.agent_id, m.created_at, m.versions,
120
+ to_char(m.created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US') AS created_key,
121
+ c.id AS conv_id, c.title AS conv_title, (c.deleted_at IS NOT NULL) AS conv_deleted,
122
+ (SELECT v.definition->>'name' FROM capybara.agents a
123
+ JOIN capybara.agent_versions v ON v.agent_id = a.id AND v.version = a.current_version
124
+ WHERE a.id = m.agent_id AND a.org_id = ${orgId}) AS agent_name
125
+ FROM mine m
126
+ LEFT JOIN capybara.conversations c ON c.id = m.source_conversation_id
127
+ AND c.org_id = ${orgId} AND c.account_id = ${accountId}
128
+ WHERE ${sql.join(conditions, sql ` AND `)}
129
+ ORDER BY m.created_at DESC, m.id DESC
130
+ LIMIT ${limit}`.execute(this.db.db);
131
+ return rows.rows;
132
+ }
133
+ /**
134
+ * `GET /files`: one page of the account's library (see {@link views}). `q` matches a
135
+ * case-insensitive substring of the name; `next` is the cursor of the following page, null on
136
+ * the last. A cursor this route did not hand out → 400 `validation_failed`.
137
+ */
138
+ async list(orgId, accountId, opts) {
139
+ const where = [];
140
+ if (opts.origin !== undefined)
141
+ where.push(sql `m.origin = ${opts.origin}`);
142
+ if (opts.agentId !== undefined)
143
+ where.push(sql `m.agent_id = ${opts.agentId}`);
144
+ if (opts.type !== undefined)
145
+ where.push(sql `m.family = ${opts.type}`);
146
+ if (opts.q !== undefined)
147
+ where.push(sql `position(lower(${opts.q}) in lower(m.name)) > 0`);
148
+ if (opts.cursor !== undefined) {
149
+ const c = decodeCursor(opts.cursor);
150
+ where.push(sql `(m.created_at, m.id) < (${c.createdKey}::timestamp AT TIME ZONE 'UTC', ${c.id})`);
151
+ }
152
+ const rows = await this.views(orgId, accountId, where, opts.limit + 1);
153
+ const page = rows.slice(0, opts.limit);
154
+ const last = page.at(-1);
155
+ return {
156
+ files: page.map(viewOf),
157
+ next: rows.length > opts.limit && last ? encodeCursor(last.created_key, last.id) : null,
158
+ };
159
+ }
160
+ /** `GET /files/usage` (file library spec §8): other accounts' use of a blob never shows. */
161
+ async usage(orgId, accountId) {
162
+ const r = await sql `
163
+ SELECT
164
+ (SELECT count(*) FROM capybara.files f
165
+ WHERE f.org_id = ${orgId} AND f.account_id = ${accountId} AND f.status = 'ready') AS files,
166
+ (SELECT sum(b.size) FROM capybara.blobs b
167
+ WHERE b.org_id = ${orgId} AND b.id IN (
168
+ SELECT f.blob_id FROM capybara.files f
169
+ WHERE f.org_id = ${orgId} AND f.account_id = ${accountId} AND f.status = 'ready'
170
+ )) AS bytes`.execute(this.db.db);
171
+ const row = r.rows[0];
172
+ return { files: Number(row?.files ?? 0), bytes: Number(row?.bytes ?? 0) };
173
+ }
174
+ /**
175
+ * `GET /files/:id`: one of the account's ready files (any version of a delivery) with the
176
+ * owner's conversations referring to it (oldest reference first) and the ready versions of its
177
+ * group. Another account's, deleted or unknown → `file.not_found`.
178
+ */
179
+ async details(orgId, accountId, fileId) {
180
+ if (!UUID_RE.test(fileId))
181
+ throw notFound();
182
+ const row = await this.db.db
183
+ .selectFrom("files")
184
+ .select(["id", "origin", "source_conversation_id", "source_path", "size", "created_at"])
185
+ .where("org_id", "=", orgId)
186
+ .where("account_id", "=", accountId)
187
+ .where("id", "=", fileId)
188
+ .where("status", "=", "ready")
189
+ .executeTakeFirst();
190
+ if (!row)
191
+ throw notFound();
192
+ const grouped = row.origin !== "upload" && row.source_path !== null && row.source_conversation_id !== null;
193
+ const group = () => this.db.db
194
+ .selectFrom("files")
195
+ .where("org_id", "=", orgId)
196
+ .where("account_id", "=", accountId)
197
+ .where("status", "=", "ready")
198
+ .where("origin", "<>", "upload")
199
+ .where("source_conversation_id", "=", row.source_conversation_id)
200
+ .where("source_path", "=", row.source_path);
201
+ // the count is over every ready version (as the list counts), the listed ones are capped
202
+ const count = grouped
203
+ ? Number((await group()
204
+ .select((eb) => eb.fn.countAll().as("n"))
205
+ .executeTakeFirst())?.n ?? 1)
206
+ : 1;
207
+ const versions = grouped
208
+ ? (await group()
209
+ .select(["id", "size", "created_at"])
210
+ .orderBy("created_at", "desc")
211
+ .orderBy("id", "desc")
212
+ .limit(FILE_VERSIONS_MAX)
213
+ .execute()).map((v) => ({ id: v.id, size: Number(v.size), createdAt: v.created_at }))
214
+ : [{ id: row.id, size: Number(row.size), createdAt: row.created_at }];
215
+ const [view] = await this.viewOfFile(orgId, accountId, fileId);
216
+ if (!view)
217
+ throw notFound();
218
+ const conversations = await this.db.db
219
+ .selectFrom("conversation_files as cf")
220
+ .innerJoin("conversations as c", (j) => j.onRef("c.id", "=", "cf.conversation_id").on("c.org_id", "=", orgId))
221
+ .select(["c.id", "c.title", "c.deleted_at"])
222
+ .where("cf.org_id", "=", orgId)
223
+ .where("cf.file_id", "=", fileId)
224
+ .where("c.account_id", "=", accountId)
225
+ .orderBy("cf.created_at")
226
+ .orderBy("c.id")
227
+ .execute();
228
+ return {
229
+ file: { ...view, versions: count },
230
+ conversations: conversations.map((c) => ({
231
+ id: c.id,
232
+ title: c.title,
233
+ deleted: c.deleted_at !== null,
234
+ })),
235
+ versions,
236
+ };
237
+ }
238
+ /** The view of one ready file of the account (not collapsed: the file itself). */
239
+ async viewOfFile(orgId, accountId, fileId) {
240
+ const rows = await sql `
241
+ SELECT f.id, f.name, f.content_type, f.size, f.origin, f.agent_id, f.created_at,
242
+ 1 AS versions, c.id AS conv_id, c.title AS conv_title,
243
+ (c.deleted_at IS NOT NULL) AS conv_deleted,
244
+ (SELECT v.definition->>'name' FROM capybara.agents a
245
+ JOIN capybara.agent_versions v ON v.agent_id = a.id AND v.version = a.current_version
246
+ WHERE a.id = f.agent_id AND a.org_id = ${orgId}) AS agent_name
247
+ FROM capybara.files f
248
+ LEFT JOIN capybara.conversations c ON c.id = f.source_conversation_id
249
+ AND c.org_id = ${orgId} AND c.account_id = ${accountId}
250
+ WHERE f.org_id = ${orgId} AND f.account_id = ${accountId} AND f.id = ${fileId}
251
+ AND f.status = 'ready'`.execute(this.db.db);
252
+ return rows.rows.map(viewOf);
253
+ }
254
+ /**
255
+ * One of the account's files whose bytes can be read now (`ready`, or a `draft` of the
256
+ * composer: `ReferencedFiles.owned`), its blob ready and its stored object still the recorded
257
+ * bytes. Another account's, unknown or deleted → `file.not_found`; bytes gone → `file.deleted`.
258
+ */
259
+ async live(orgId, accountId, fileId) {
260
+ if (!UUID_RE.test(fileId))
261
+ throw notFound();
262
+ const f = await this.files.owned(orgId, accountId, fileId);
263
+ if (f.blob === null || f.blob.status !== "ready")
264
+ throw gone();
265
+ const blob = {
266
+ id: f.blob.id,
267
+ objectKey: f.blob.objectKey,
268
+ size: f.blob.size,
269
+ etag: f.blob.etag,
270
+ };
271
+ if ((await this.blobs.head(orgId, blob)) === null)
272
+ throw gone();
273
+ return { id: f.id, name: f.name, contentType: f.contentType, size: f.size, blob };
274
+ }
275
+ /**
276
+ * The first `limit` bytes of a text file (the conversation route's twin): not text, or NUL
277
+ * bytes in what was read → `conversation.artifact_not_previewable`; a cut never splits a UTF-8
278
+ * character.
279
+ */
280
+ async content(orgId, accountId, fileId, limit) {
281
+ const f = await this.live(orgId, accountId, fileId);
282
+ if (!isTextArtifactType(f.contentType)) {
283
+ throw new ApiError("conversation.artifact_not_previewable", "Only text files have content");
284
+ }
285
+ const max = Math.min(limit, FILE_CONTENT_MAX_BYTES);
286
+ const got = await this.blobs.open(orgId, f.blob, { range: { start: 0, end: max - 1 } });
287
+ if (!got)
288
+ throw gone();
289
+ let body = await readPrefix(got.body, max);
290
+ if (body.includes(0)) {
291
+ throw new ApiError("conversation.artifact_not_previewable", "This file contains binary data and has no text content");
292
+ }
293
+ const truncated = got.head.size > body.byteLength;
294
+ if (truncated)
295
+ body = trimUtf8(body);
296
+ const base = (f.contentType.split(";")[0] ?? "").trim().toLowerCase();
297
+ return { body, contentType: "text/plain; charset=utf-8", originalType: base, truncated };
298
+ }
299
+ /**
300
+ * A presigned address of the file's bytes (the artifact download's twin): `attachment` with the
301
+ * file's name and type; `inline` only for bitmaps.
302
+ */
303
+ async downloadUrl(orgId, accountId, fileId, opts = {}) {
304
+ const f = await this.live(orgId, accountId, fileId);
305
+ const inline = opts.inline === true && isInlineArtifactType(f.contentType);
306
+ const url = await this.storage.kernel(orgId).presignGet(f.blob.objectKey, {
307
+ ttlSeconds: ARTIFACT_DOWNLOAD_TTL_SECONDS,
308
+ downloadName: f.name,
309
+ disposition: inline ? "inline" : "attachment",
310
+ responseContentType: f.contentType,
311
+ });
312
+ return { url, name: f.name };
313
+ }
314
+ };
315
+ LibraryQuery = __decorate([
316
+ Injectable(),
317
+ __param(0, Inject(KernelDb)),
318
+ __param(1, Inject(ReferencedFiles)),
319
+ __param(2, Inject(BlobsService)),
320
+ __param(3, Inject(StorageService))
321
+ ], LibraryQuery);
322
+ export { LibraryQuery };
@@ -0,0 +1,9 @@
1
+ /**
2
+ * How conversations read the file library (file library spec §2, §5): the files a conversation
3
+ * refers to ({@link ReferencedFiles}) and the media request building resolves refs with
4
+ * ({@link ConversationMedia}), and the Files page's reads ({@link LibraryQuery}). Re-exports
5
+ * {@link LibraryFilesModule} (the send path attaches files through it). Its own module (no
6
+ * conversations dependency) so conversations, the runtime and the tools can use it.
7
+ */
8
+ export declare class LibraryReadModule {
9
+ }
@@ -0,0 +1,30 @@
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
+ import { Module } from "@nestjs/common";
8
+ import { AttachmentsModule } from "../conversations/attachments.module.js";
9
+ import { StorageModule } from "../storage/storage.module.js";
10
+ import { ConversationMedia } from "./conversation-media.js";
11
+ import { LibraryFilesModule } from "./library.module.js";
12
+ import { LibraryQuery } from "./library-query.js";
13
+ import { ReferencedFiles } from "./referenced-files.js";
14
+ /**
15
+ * How conversations read the file library (file library spec §2, §5): the files a conversation
16
+ * refers to ({@link ReferencedFiles}) and the media request building resolves refs with
17
+ * ({@link ConversationMedia}), and the Files page's reads ({@link LibraryQuery}). Re-exports
18
+ * {@link LibraryFilesModule} (the send path attaches files through it). Its own module (no
19
+ * conversations dependency) so conversations, the runtime and the tools can use it.
20
+ */
21
+ let LibraryReadModule = class LibraryReadModule {
22
+ };
23
+ LibraryReadModule = __decorate([
24
+ Module({
25
+ imports: [StorageModule, LibraryFilesModule, AttachmentsModule],
26
+ providers: [ReferencedFiles, ConversationMedia, LibraryQuery],
27
+ exports: [ReferencedFiles, ConversationMedia, LibraryQuery, LibraryFilesModule],
28
+ })
29
+ ], LibraryReadModule);
30
+ export { LibraryReadModule };
@@ -0,0 +1,77 @@
1
+ import type { FastifyReply } from "fastify";
2
+ import { z } from "zod";
3
+ import { type Principal } from "../identity/principal.js";
4
+ import { type OrgContext } from "../orgs/org.guard.js";
5
+ import { FileCreateBody, FileIdParams, LibraryListQuery } from "./library.schemas.js";
6
+ import { type CreatedFile, type FileLimits, type FileView, LibraryFilesService } from "./library-files.service.js";
7
+ import { type LibraryFileDetails, type LibraryFileView, LibraryQuery, type LibraryUsage } from "./library-query.js";
8
+ declare const ContentQuery: z.ZodObject<{
9
+ limit: z.ZodDefault<z.ZodCoercedNumber<unknown>>;
10
+ }, z.core.$strip>;
11
+ /**
12
+ * `inline=1`: open inline (bitmaps only); `as=url`: answer `{ url }` instead of redirecting. Not
13
+ * strict: the web adds a cache-busting `retry=1` when it reloads a failed image.
14
+ */
15
+ declare const DownloadQuery: z.ZodObject<{
16
+ inline: z.ZodOptional<z.ZodEnum<{
17
+ 0: "0";
18
+ 1: "1";
19
+ }>>;
20
+ as: z.ZodOptional<z.ZodEnum<{
21
+ url: "url";
22
+ }>>;
23
+ }, z.core.$strip>;
24
+ /**
25
+ * The person's files (`/api/v1/orgs/:orgId/files`, `agents.use`, people only; file library spec
26
+ * §3):
27
+ * 1. `POST /` with `{ name, contentType, size, sha256, purpose }` → 201 `{ file, upload,
28
+ * expiresAt }`: `upload` is a presigned form (`method` `POST`: the `fields` first, the `file`
29
+ * last), or null when the caller already holds these bytes (the file exists at once);
30
+ * 2. the browser sends the bytes to the store;
31
+ * 3. `POST /:id/finalize` → `{ id, name, contentType, size, status }`;
32
+ * 4. a message names the id in `files`.
33
+ * Finalize is limited to 60 a minute per person (429 `rate_limited`). `DELETE /:id/draft` (204)
34
+ * drops a composer upload before it is sent; `GET /limits` answers the types, sizes, files per
35
+ * message, the media budget per request and whether storage is available (no object store
36
+ * needed). Without an object store the upload routes answer 503 `storage.unavailable`.
37
+ *
38
+ * The library (file library spec §6, §8; the caller's own files only: another account's file is
39
+ * 404 `file.not_found` on every route; `Cache-Control: private, no-store`):
40
+ * - `GET /?origin=&agentId=&type=&q=&limit=&cursor=` → `{ files, next }`: ready files newest first,
41
+ * the deliveries of one source path in one conversation collapsed to the newest with `versions`;
42
+ * `q` a case-insensitive substring of the name (the composer's `@` search);
43
+ * - `GET /usage` → `{ bytes, files }`; `GET /:id` → `{ file, conversations, versions }`;
44
+ * - `GET /:id/content?limit=` and `GET /:id/download?as=url&inline=1`: the conversation-scoped
45
+ * routes' twins (same headers; the download a 302 with `private, max-age=60`);
46
+ * - `DELETE /:id` (204): the file is deleted and its shares revoked.
47
+ */
48
+ export declare class LibraryFilesController {
49
+ private readonly files;
50
+ private readonly library;
51
+ constructor(files: LibraryFilesService, library: LibraryQuery);
52
+ limits(principal: Principal): FileLimits;
53
+ create(principal: Principal, org: OrgContext, body: z.infer<typeof FileCreateBody>): Promise<CreatedFile>;
54
+ finalize(principal: Principal, org: OrgContext, id: string): Promise<FileView>;
55
+ discard(principal: Principal, org: OrgContext, id: string): Promise<void>;
56
+ list(principal: Principal, org: OrgContext, q: z.infer<typeof LibraryListQuery>): Promise<{
57
+ files: LibraryFileView[];
58
+ next: string | null;
59
+ }>;
60
+ usage(principal: Principal, org: OrgContext): Promise<LibraryUsage>;
61
+ details(principal: Principal, org: OrgContext, params: z.infer<typeof FileIdParams>): Promise<LibraryFileDetails>;
62
+ /**
63
+ * The first `limit` bytes (≤ 1 MiB) of a text file, always as `text/plain; charset=utf-8` with
64
+ * the stored type in `X-Content-Original-Type` (sandboxed, never sniffed);
65
+ * `X-Content-Truncated: true` when cut. Not text → 400 `conversation.artifact_not_previewable`;
66
+ * bytes gone → 410 `file.deleted`.
67
+ */
68
+ content(principal: Principal, org: OrgContext, params: z.infer<typeof FileIdParams>, q: z.infer<typeof ContentQuery>, reply: FastifyReply): Promise<void>;
69
+ /**
70
+ * A 302 to the presigned address of the file's bytes (`attachment` with its name; `inline=1`
71
+ * only for bitmaps), `Cache-Control: private, max-age=60`; `as=url` answers `{ url }` instead
72
+ * (never cached).
73
+ */
74
+ download(principal: Principal, org: OrgContext, params: z.infer<typeof FileIdParams>, q: z.infer<typeof DownloadQuery>, reply: FastifyReply): Promise<void>;
75
+ remove(principal: Principal, org: OrgContext, params: z.infer<typeof FileIdParams>): Promise<void>;
76
+ }
77
+ export {};