@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,14 +10,14 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
10
10
  import { Readable } from "node:stream";
11
11
  import { FILE_PREVIEW_MAX_BYTES } from "@capybara-hq/plugin-sdk";
12
12
  import { Inject, Injectable, Optional } from "@nestjs/common";
13
- import { attachmentContentMatches } from "../conversations/attachments.service.js";
14
13
  import { ConversationFiles } from "../conversations/files.js";
15
14
  import { ApiError } from "../errors.js";
15
+ import { BlobsService } from "../files/blobs.service.js";
16
+ import { LibraryQuery } from "../files/library-query.js";
16
17
  import { KernelDb } from "../infra/database/kernel-db.js";
17
18
  import { KERNEL_LOGGER } from "../infra/tokens.js";
18
19
  import { ShareLiveness } from "../shares/liveness.js";
19
20
  import { readHtmlCdnAllowlist } from "../shares/settings.js";
20
- import { StorageService } from "../storage/storage.service.js";
21
21
  import { htmlDocumentCsp } from "./csp.js";
22
22
  import { HTML_TOKEN_TTL_SECONDS, HtmlTokens } from "./html-token.js";
23
23
  import { htmlContentType, isHtmlType } from "./html-type.js";
@@ -29,7 +29,8 @@ const notPreviewable = (message) => new ApiError("conversation.artifact_not_prev
29
29
  * mints a short-lived document token for one version of an HTML file ({@link mint}); the public
30
30
  * route serves it ({@link serve}) under the sandbox CSP after re-checking, live, what the token
31
31
  * names: the owner can still read the file (`ConversationFiles.file`: membership, active account,
32
- * conversation and agent not deleted; an upload's object still the one finalize checked), or the
32
+ * conversation and agent not deleted; the file not deleted and its blob still the recorded bytes;
33
+ * a library file: `LibraryQuery.live`, still the account's and not deleted), or the
33
34
  * share is still live at that generation (`ShareLiveness.byId`). The bytes are streamed by the
34
35
  * kernel as stored; never a presigned URL on the app origin. HTML larger than
35
36
  * `FILE_PREVIEW_MAX_BYTES` is never rendered.
@@ -37,15 +38,21 @@ const notPreviewable = (message) => new ApiError("conversation.artifact_not_prev
37
38
  let HtmlDocumentService = class HtmlDocumentService {
38
39
  db;
39
40
  files;
41
+ library;
40
42
  liveness;
41
- storage;
43
+ blobs;
42
44
  tokens;
43
45
  log;
44
- constructor(db, files, liveness, storage, tokens, log) {
46
+ constructor(db, files,
47
+ /** The account's own library files (the Files page). */
48
+ library, liveness,
49
+ /** A conversation file's or a share's bytes, through its blob. */
50
+ blobs, tokens, log) {
45
51
  this.db = db;
46
52
  this.files = files;
53
+ this.library = library;
47
54
  this.liveness = liveness;
48
- this.storage = storage;
55
+ this.blobs = blobs;
49
56
  this.tokens = tokens;
50
57
  this.log = log;
51
58
  }
@@ -73,6 +80,22 @@ let HtmlDocumentService = class HtmlDocumentService {
73
80
  });
74
81
  return { path: `/api/v1/html/${token}`, expiresIn: HTML_TOKEN_TTL_SECONDS };
75
82
  }
83
+ /**
84
+ * A document token for one of the caller's library files (the Files page; file library spec
85
+ * §6): another account's, unknown or deleted → `file.not_found`; bytes gone → `file.deleted`;
86
+ * not HTML, or larger than `FILE_PREVIEW_MAX_BYTES` → `conversation.artifact_not_previewable`.
87
+ */
88
+ async mintLibrary(orgId, accountId, fileId) {
89
+ const f = await this.library.live(orgId, accountId, fileId);
90
+ if (!isHtmlType(f.name, f.contentType)) {
91
+ throw notPreviewable("Only HTML files render as documents; download this file instead");
92
+ }
93
+ if (f.size > FILE_PREVIEW_MAX_BYTES) {
94
+ throw notPreviewable("This HTML file is too large to render; download it instead");
95
+ }
96
+ const { token } = this.tokens.issue({ kind: "library", orgId, fileId: f.id, accountId });
97
+ return { path: `/api/v1/html/${token}`, expiresIn: HTML_TOKEN_TTL_SECONDS };
98
+ }
76
99
  /**
77
100
  * Serves the document verified claims name with the spec §4 headers, the CSP built from the CDN
78
101
  * allowlist read now. Any live check failing → 404 `not_found`.
@@ -83,11 +106,10 @@ let HtmlDocumentService = class HtmlDocumentService {
83
106
  throw htmlNotFound();
84
107
  // read before the object is opened, so no stream is held across this query
85
108
  const allowlist = await readHtmlCdnAllowlist(this.db.db, this.log);
86
- const got = await this.storage.kernel(source.orgId).get(source.objectKey);
109
+ const got = await this.blobs.open(source.orgId, source.blob);
87
110
  if (!got)
88
111
  throw htmlNotFound();
89
- if (got.head.size > FILE_PREVIEW_MAX_BYTES ||
90
- (source.recorded && !attachmentContentMatches(source.recorded, got.head))) {
112
+ if (got.head.size > FILE_PREVIEW_MAX_BYTES) {
91
113
  await got.body.cancel().catch(() => { });
92
114
  throw htmlNotFound();
93
115
  }
@@ -108,11 +130,14 @@ let HtmlDocumentService = class HtmlDocumentService {
108
130
  if (s === null || !isHtmlType(s.name, s.contentType) || s.size > FILE_PREVIEW_MAX_BYTES) {
109
131
  return null;
110
132
  }
111
- return { orgId: s.orgId, objectKey: s.objectKey, contentType: s.contentType };
133
+ return { orgId: s.orgId, contentType: s.contentType, blob: s.blob };
112
134
  }
113
135
  let f;
114
136
  try {
115
- f = await this.files.file(claims.orgId, claims.conversationId, claims.accountId, claims.fileId);
137
+ f =
138
+ claims.kind === "library"
139
+ ? await this.library.live(claims.orgId, claims.accountId, claims.fileId)
140
+ : await this.files.file(claims.orgId, claims.conversationId, claims.accountId, claims.fileId);
116
141
  }
117
142
  catch (e) {
118
143
  // the owner lost access, the file is unknown or the upload changed: all the same 404
@@ -122,22 +147,18 @@ let HtmlDocumentService = class HtmlDocumentService {
122
147
  }
123
148
  if (!isHtmlType(f.name, f.contentType) || f.size > FILE_PREVIEW_MAX_BYTES)
124
149
  return null;
125
- return {
126
- orgId: claims.orgId,
127
- objectKey: f.objectKey,
128
- contentType: f.contentType,
129
- recorded: f.recorded,
130
- };
150
+ return { orgId: claims.orgId, contentType: f.contentType, blob: f.blob };
131
151
  }
132
152
  };
133
153
  HtmlDocumentService = __decorate([
134
154
  Injectable(),
135
155
  __param(0, Inject(KernelDb)),
136
156
  __param(1, Inject(ConversationFiles)),
137
- __param(2, Inject(ShareLiveness)),
138
- __param(3, Inject(StorageService)),
139
- __param(4, Inject(HtmlTokens)),
140
- __param(5, Optional()),
141
- __param(5, Inject(KERNEL_LOGGER))
157
+ __param(2, Inject(LibraryQuery)),
158
+ __param(3, Inject(ShareLiveness)),
159
+ __param(4, Inject(BlobsService)),
160
+ __param(5, Inject(HtmlTokens)),
161
+ __param(6, Optional()),
162
+ __param(6, Inject(KERNEL_LOGGER))
142
163
  ], HtmlDocumentService);
143
164
  export { HtmlDocumentService };
@@ -7,7 +7,8 @@ export declare const HTML_TOKEN_TTL_SECONDS = 300;
7
7
  export declare const HTML_TOKEN_SKEW_SECONDS = 30;
8
8
  /**
9
9
  * What a document token names (file sharing spec §4): one version of a conversation file for its
10
- * owner (the right panel), or one generation of a share (the share page). Re-checked live on use.
10
+ * owner (the right panel), one of the account's library files (`library`, the Files page; file
11
+ * library spec §6), or one generation of a share (the share page). Re-checked live on use.
11
12
  */
12
13
  export type HtmlClaims = {
13
14
  kind: "file";
@@ -16,6 +17,12 @@ export type HtmlClaims = {
16
17
  fileId: string;
17
18
  accountId: string;
18
19
  exp: number;
20
+ } | {
21
+ kind: "library";
22
+ orgId: string;
23
+ fileId: string;
24
+ accountId: string;
25
+ exp: number;
19
26
  } | {
20
27
  kind: "share";
21
28
  shareId: string;
@@ -25,6 +32,8 @@ export type HtmlClaims = {
25
32
  /** Claims before issuing (the token's expiry is set by {@link HtmlTokens.issue}). */
26
33
  export type HtmlClaimsInput = Omit<Extract<HtmlClaims, {
27
34
  kind: "file";
35
+ }>, "exp"> | Omit<Extract<HtmlClaims, {
36
+ kind: "library";
28
37
  }>, "exp"> | Omit<Extract<HtmlClaims, {
29
38
  kind: "share";
30
39
  }>, "exp">;
@@ -20,6 +20,7 @@ const TOKEN_MAX = 2048;
20
20
  const MAC_LEN = 32;
21
21
  const B64URL = /^[A-Za-z0-9_-]+$/;
22
22
  const FILE_KEYS = ["kind", "orgId", "conversationId", "fileId", "accountId", "exp"];
23
+ const LIBRARY_KEYS = ["kind", "orgId", "fileId", "accountId", "exp"];
23
24
  const SHARE_KEYS = ["kind", "shareId", "generation", "exp"];
24
25
  const isId = (v) => typeof v === "string" && v !== "" && v.length <= 100;
25
26
  /** Strict base64url: the alphabet only, no padding, the canonical encoding of its bytes. */
@@ -55,6 +56,19 @@ function parseClaims(v) {
55
56
  exp: c.exp,
56
57
  };
57
58
  }
59
+ if (c.kind === "library") {
60
+ if (!sameKeys(c, LIBRARY_KEYS))
61
+ return null;
62
+ if (!isId(c.orgId) || !isId(c.fileId) || !isId(c.accountId))
63
+ return null;
64
+ return {
65
+ kind: "library",
66
+ orgId: c.orgId,
67
+ fileId: c.fileId,
68
+ accountId: c.accountId,
69
+ exp: c.exp,
70
+ };
71
+ }
58
72
  if (c.kind === "share") {
59
73
  if (!sameKeys(c, SHARE_KEYS) || !isId(c.shareId))
60
74
  return null;
@@ -6,6 +6,7 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
6
6
  };
7
7
  import { Module } from "@nestjs/common";
8
8
  import { ConversationsModule } from "../conversations/conversations.module.js";
9
+ import { LibraryReadModule } from "../files/library-read.module.js";
9
10
  import { ShareLivenessModule } from "../shares/liveness.js";
10
11
  import { StorageModule } from "../storage/storage.module.js";
11
12
  import { HtmlDocumentService } from "./html-document.service.js";
@@ -18,7 +19,13 @@ let HtmlModule = class HtmlModule {
18
19
  };
19
20
  HtmlModule = __decorate([
20
21
  Module({
21
- imports: [ConversationsModule, ShareLivenessModule, StorageModule, HtmlTokensModule],
22
+ imports: [
23
+ ConversationsModule,
24
+ LibraryReadModule,
25
+ ShareLivenessModule,
26
+ StorageModule,
27
+ HtmlTokensModule,
28
+ ],
22
29
  providers: [HtmlDocumentService],
23
30
  exports: [HtmlDocumentService, HtmlTokensModule],
24
31
  })
@@ -56,6 +56,8 @@ import { TrajectoryController } from "../evals/trajectory.controller.js";
56
56
  import { ExtensionsModule } from "../extensions/extensions.module.js";
57
57
  import { ExtensionPointDefaultsController } from "../extensions/point-defaults.controller.js";
58
58
  import { FilesModule } from "../files/files.module.js";
59
+ import { LibraryFilesController } from "../files/library.controller.js";
60
+ import { LibraryReadModule } from "../files/library-read.module.js";
59
61
  import { FilePreviewersController } from "../files/previewers.controller.js";
60
62
  import { GitModule } from "../git/git.module.js";
61
63
  import { HandoffController } from "../handoff/handoff.controller.js";
@@ -163,6 +165,7 @@ const CONTROLLERS = [
163
165
  DevicesController,
164
166
  AutomationsController,
165
167
  AttachmentsController,
168
+ LibraryFilesController,
166
169
  SkillsController,
167
170
  SkillChangesController,
168
171
  AgentSkillsController,
@@ -253,6 +256,8 @@ ApiModule = __decorate([
253
256
  ChannelsModule,
254
257
  EvalsModule,
255
258
  FilesModule,
259
+ // the person's files: uploads, drafts, blobs
260
+ LibraryReadModule,
256
261
  UiModule,
257
262
  InboxModule,
258
263
  ThemesModule,
@@ -119,6 +119,24 @@ export type CompactionSettingsPatch = z.infer<typeof COMPACTION_SETTINGS_PARTIAL
119
119
  * the rest follow the platform's settings, which are themselves the built-in defaults when unset.
120
120
  */
121
121
  export declare function effectiveCompactionSettings(platform: CompactionSettings, org: CompactionSettingsPatch | undefined): CompactionSettings;
122
+ /**
123
+ * Prompt cache settings (idle compaction spec): `longTtl` asks the model call for the longer
124
+ * cache tier, which costs more per write and keeps a conversation's prefix warm longer.
125
+ */
126
+ export declare const PROMPT_CACHE_SETTINGS: z.ZodObject<{
127
+ longTtl: z.ZodDefault<z.ZodBoolean>;
128
+ }, z.core.$strip>;
129
+ export type PromptCacheSettings = z.infer<typeof PROMPT_CACHE_SETTINGS>;
130
+ /** The partial form the platform and org patches carry: only the given fields. */
131
+ export declare const PROMPT_CACHE_SETTINGS_PARTIAL: z.ZodObject<{
132
+ longTtl: z.ZodOptional<z.ZodBoolean>;
133
+ }, z.core.$strip>;
134
+ /** The strict request-body form: a misspelled field is a 400, not a silent no-op. */
135
+ export declare const PROMPT_CACHE_SETTINGS_PATCH: z.ZodObject<{
136
+ longTtl: z.ZodOptional<z.ZodBoolean>;
137
+ }, z.core.$strict>;
138
+ /** The prompt cache settings in effect for an organization: its override over the platform. */
139
+ export declare function effectivePromptCacheSettings(platform: PromptCacheSettings, org: z.infer<typeof PROMPT_CACHE_SETTINGS_PARTIAL> | undefined): PromptCacheSettings;
122
140
  export declare const DEPLOYMENT_SETTINGS: z.ZodObject<{
123
141
  orgCreation: z.ZodDefault<z.ZodEnum<{
124
142
  anyone: "anyone";
@@ -160,6 +178,9 @@ export declare const DEPLOYMENT_SETTINGS: z.ZodObject<{
160
178
  reserveTokens: z.ZodDefault<z.ZodNumber>;
161
179
  maxOutputTokens: z.ZodDefault<z.ZodNumber>;
162
180
  }, z.core.$strip>>;
181
+ promptCache: z.ZodPrefault<z.ZodObject<{
182
+ longTtl: z.ZodDefault<z.ZodBoolean>;
183
+ }, z.core.$strip>>;
163
184
  htmlRenderCdnAllowlist: z.ZodDefault<z.ZodArray<z.ZodType<string, unknown, z.core.$ZodTypeInternals<string, unknown>>>>;
164
185
  }, z.core.$strip>;
165
186
  export type DeploymentSettings = z.infer<typeof DEPLOYMENT_SETTINGS>;
@@ -264,6 +285,9 @@ export declare const DEPLOYMENT_SETTINGS_PATCH: z.ZodObject<{
264
285
  reserveTokens: z.ZodOptional<z.ZodNumber>;
265
286
  maxOutputTokens: z.ZodOptional<z.ZodNumber>;
266
287
  }, z.core.$strict>>;
288
+ promptCache: z.ZodOptional<z.ZodObject<{
289
+ longTtl: z.ZodOptional<z.ZodBoolean>;
290
+ }, z.core.$strict>>;
267
291
  externalSharing: z.ZodOptional<z.ZodNullable<z.ZodEnum<{
268
292
  allow: "allow";
269
293
  deny: "deny";
@@ -293,6 +317,8 @@ export declare function readSubagentLimitOverride(db: KernelSchemaDb, orgId: str
293
317
  * defaults, as {@link SettingsService.get} reads them.
294
318
  */
295
319
  export declare function readPlatformCompactionSettings(db: KernelSchemaDb): Promise<CompactionSettings>;
320
+ /** The platform's prompt cache settings, read live from PG (what an org that follows gets). */
321
+ export declare function readPlatformPromptCacheSettings(db: KernelSchemaDb): Promise<PromptCacheSettings>;
296
322
  /**
297
323
  * When orgs may not create their own connectors / skills (deployment setting `customConnectors` /
298
324
  * `customSkills` is `deny`, C22) throws `catalog.custom_disabled`: install from the platform
@@ -173,6 +173,19 @@ export function effectiveCompactionSettings(platform, org) {
173
173
  maxOutputTokens: org?.maxOutputTokens ?? platform.maxOutputTokens,
174
174
  };
175
175
  }
176
+ /**
177
+ * Prompt cache settings (idle compaction spec): `longTtl` asks the model call for the longer
178
+ * cache tier, which costs more per write and keeps a conversation's prefix warm longer.
179
+ */
180
+ export const PROMPT_CACHE_SETTINGS = z.object({ longTtl: z.boolean().default(false) });
181
+ /** The partial form the platform and org patches carry: only the given fields. */
182
+ export const PROMPT_CACHE_SETTINGS_PARTIAL = z.object({ longTtl: z.boolean() }).partial();
183
+ /** The strict request-body form: a misspelled field is a 400, not a silent no-op. */
184
+ export const PROMPT_CACHE_SETTINGS_PATCH = PROMPT_CACHE_SETTINGS_PARTIAL.strict();
185
+ /** The prompt cache settings in effect for an organization: its override over the platform. */
186
+ export function effectivePromptCacheSettings(platform, org) {
187
+ return { longTtl: org?.longTtl ?? platform.longTtl };
188
+ }
176
189
  export const DEPLOYMENT_SETTINGS = z.object({
177
190
  orgCreation: z.enum(["anyone", "super_admin"]).default("anyone"),
178
191
  /** 按组织覆盖运行并发上限(orgId → 上限);未列出的组织用 `runtime.orgConcurrency`。 */
@@ -213,6 +226,8 @@ export const DEPLOYMENT_SETTINGS = z.object({
213
226
  * values; an organization may override any field in its own settings.
214
227
  */
215
228
  compaction: COMPACTION_SETTINGS.prefault({}),
229
+ /** Prompt cache tier (idle compaction spec): the platform default; an org may override it. */
230
+ promptCache: PROMPT_CACHE_SETTINGS.prefault({}),
216
231
  /**
217
232
  * The CDN origins a rendered HTML file may load scripts, styles, fonts and images from (file
218
233
  * sharing spec §4): `https://` origins only; applies to the next document load. No org level.
@@ -324,6 +339,8 @@ export const DEPLOYMENT_SETTINGS_PATCH = z
324
339
  * one, fields left out keep their value.
325
340
  */
326
341
  compaction: COMPACTION_SETTINGS_PATCH.optional(),
342
+ /** Prompt cache settings: each given field replaces the stored one. */
343
+ promptCache: PROMPT_CACHE_SETTINGS_PATCH.optional(),
327
344
  /**
328
345
  * The platform's external sharing switch (file sharing spec §8): allow or deny; null clears it
329
346
  * (back to the default, deny). A value set in the startup config is read-only (409
@@ -398,6 +415,16 @@ export async function readPlatformCompactionSettings(db) {
398
415
  const parsed = COMPACTION_SETTINGS.safeParse(row?.value ?? {});
399
416
  return parsed.success ? parsed.data : DEFAULTS.compaction;
400
417
  }
418
+ /** The platform's prompt cache settings, read live from PG (what an org that follows gets). */
419
+ export async function readPlatformPromptCacheSettings(db) {
420
+ const row = await db
421
+ .selectFrom("deployment_settings")
422
+ .select("value")
423
+ .where("key", "=", "promptCache")
424
+ .executeTakeFirst();
425
+ const parsed = PROMPT_CACHE_SETTINGS.safeParse(row?.value ?? {});
426
+ return parsed.success ? parsed.data : DEFAULTS.promptCache;
427
+ }
401
428
  /**
402
429
  * When orgs may not create their own connectors / skills (deployment setting `customConnectors` /
403
430
  * `customSkills` is `deny`, C22) throws `catalog.custom_disabled`: install from the platform
@@ -819,13 +846,14 @@ let SettingsService = class SettingsService {
819
846
  }
820
847
  next.uiTheme = { id: patch.uiTheme.id };
821
848
  }
822
- const { runConcurrencyOverrides: runPatch, sandboxLimitOverrides: sandboxPatch, subagentLimitOverrides: subagentPatch, uiArrangement: arrangementPatch, clientExtensions: clientPatch, compaction: compactionPatch, } = patch;
849
+ const { runConcurrencyOverrides: runPatch, sandboxLimitOverrides: sandboxPatch, subagentLimitOverrides: subagentPatch, uiArrangement: arrangementPatch, clientExtensions: clientPatch, compaction: compactionPatch, promptCache: promptCachePatch, } = patch;
823
850
  if (runPatch !== undefined ||
824
851
  sandboxPatch !== undefined ||
825
852
  subagentPatch !== undefined ||
826
853
  arrangementPatch !== undefined ||
827
854
  clientPatch !== undefined ||
828
- compactionPatch !== undefined) {
855
+ compactionPatch !== undefined ||
856
+ promptCachePatch !== undefined) {
829
857
  const current = await this.get();
830
858
  if (clientPatch !== undefined) {
831
859
  next.clientExtensions = {
@@ -844,6 +872,9 @@ let SettingsService = class SettingsService {
844
872
  maxOutputTokens: compactionPatch.maxOutputTokens ?? current.compaction.maxOutputTokens,
845
873
  };
846
874
  }
875
+ if (promptCachePatch !== undefined) {
876
+ next.promptCache = { longTtl: promptCachePatch.longTtl ?? current.promptCache.longTtl };
877
+ }
847
878
  if (arrangementPatch !== undefined) {
848
879
  next.uiArrangement = mergeArrangement(current.uiArrangement, arrangementPatch);
849
880
  }
@@ -59,6 +59,88 @@ export declare const OUTBOX_JOBS: {
59
59
  readonly removeOnComplete: true;
60
60
  };
61
61
  };
62
+ readonly "blob-delete": {
63
+ readonly queue: "cap-kernel-maintenance";
64
+ readonly idempotent: "Deletes the object and row only of a blob still in deleting status that no file or share points at; deleting a missing object is a no-op";
65
+ readonly processedIn: "packages/kernel/src/runtime/maintenance.ts";
66
+ readonly opts: {
67
+ readonly attempts: 10;
68
+ readonly backoff: {
69
+ readonly type: "exponential";
70
+ readonly delay: 5000;
71
+ };
72
+ readonly removeOnComplete: true;
73
+ readonly removeOnFail: true;
74
+ };
75
+ };
76
+ readonly "file-library-hash": {
77
+ readonly queue: "cap-kernel-maintenance";
78
+ readonly idempotent: "Owes each org's first hashing batch under a deterministic id; a second run owes the same ids, deduplicated";
79
+ readonly processedIn: "packages/kernel/src/runtime/maintenance.ts";
80
+ readonly opts: {
81
+ readonly attempts: 5;
82
+ readonly backoff: {
83
+ readonly type: "exponential";
84
+ readonly delay: 5000;
85
+ };
86
+ readonly removeOnComplete: true;
87
+ readonly removeOnFail: true;
88
+ };
89
+ };
90
+ readonly "file-library-hash-org": {
91
+ readonly queue: "cap-kernel-maintenance";
92
+ readonly idempotent: "Holds the org's hashing lock and re-checks each blob under its row lock and the hash's lock; a blob already hashed or merged is skipped";
93
+ readonly processedIn: "packages/kernel/src/runtime/maintenance.ts";
94
+ readonly opts: {
95
+ readonly attempts: 5;
96
+ readonly backoff: {
97
+ readonly type: "exponential";
98
+ readonly delay: 5000;
99
+ };
100
+ readonly removeOnComplete: true;
101
+ readonly removeOnFail: true;
102
+ };
103
+ };
104
+ readonly "file-library-backfill": {
105
+ readonly queue: "cap-kernel-maintenance";
106
+ readonly idempotent: "Does nothing once the settled marker exists; the copy itself is idempotent and writes the marker in its own transaction";
107
+ readonly processedIn: "packages/kernel/src/runtime/maintenance.ts";
108
+ readonly opts: {
109
+ readonly attempts: 5;
110
+ readonly backoff: {
111
+ readonly type: "exponential";
112
+ readonly delay: 30000;
113
+ };
114
+ readonly removeOnComplete: true;
115
+ readonly removeOnFail: true;
116
+ };
117
+ };
118
+ readonly "file-release": {
119
+ readonly queue: "cap-kernel-maintenance";
120
+ readonly idempotent: "Re-reads the deleted file under its row lock and releases its blob only while nothing else points at it, or deletes its own staging key; a second run finds nothing to do";
121
+ readonly processedIn: "packages/kernel/src/runtime/maintenance.ts";
122
+ readonly opts: {
123
+ readonly attempts: 10;
124
+ readonly backoff: {
125
+ readonly type: "exponential";
126
+ readonly delay: 5000;
127
+ };
128
+ readonly removeOnComplete: true;
129
+ };
130
+ };
131
+ readonly "file-staging-delete": {
132
+ readonly queue: "cap-kernel-maintenance";
133
+ readonly idempotent: "Deletes the file's own staging key only when the file is no longer uploading and no blob names that key; deleting a missing object is a no-op";
134
+ readonly processedIn: "packages/kernel/src/runtime/maintenance.ts";
135
+ readonly opts: {
136
+ readonly attempts: 10;
137
+ readonly backoff: {
138
+ readonly type: "exponential";
139
+ readonly delay: 5000;
140
+ };
141
+ readonly removeOnComplete: true;
142
+ };
143
+ };
62
144
  readonly "platform-icon-delete": {
63
145
  readonly queue: "cap-kernel-maintenance";
64
146
  readonly idempotent: "Deletes one icon object only when the purpose's row does not name it, under the purpose's lock; deleting a missing object is a no-op";
@@ -44,14 +44,86 @@ export const OUTBOX_JOBS = {
44
44
  removeOnFail: true,
45
45
  },
46
46
  },
47
- // `shares/share-objects.ts` SHARE_OBJECT_DELETE_JOB: owed by a share's refresh (the previous
48
- // generation) and revoke (the current one), under `shareObjectDeleteJobId` (file sharing spec §2)
47
+ // `shares/share-objects.ts` SHARE_OBJECT_DELETE_JOB: owed before the file library by a share's
48
+ // refresh and revoke (`shareObjectDeleteJobId`); no longer owed, handled for rows owed before the
49
+ // deploy (a key a blob uses is never deleted)
49
50
  "share-object-delete": {
50
51
  queue: "cap-kernel-maintenance",
51
52
  idempotent: "Deletes one object key; deleting a missing object is a no-op",
52
53
  processedIn: "packages/kernel/src/runtime/maintenance.ts",
53
54
  opts: { attempts: 10, backoff: { type: "exponential", delay: 5000 }, removeOnComplete: true },
54
55
  },
56
+ // `files/blob-objects.ts` BLOB_DELETE_JOB: owed with a blob turned `deleting` (an upload dropped
57
+ // before use whose own blob nothing else points at; the blob sweep; a hashing merge's
58
+ // duplicate), under `blobDeleteJobId`
59
+ "blob-delete": {
60
+ queue: "cap-kernel-maintenance",
61
+ idempotent: "Deletes the object and row only of a blob still in deleting status that no file or share points at; deleting a missing object is a no-op",
62
+ processedIn: "packages/kernel/src/runtime/maintenance.ts",
63
+ // removed on failure too: the blob sweep owes a stale deletion again under the same id
64
+ opts: {
65
+ attempts: 10,
66
+ backoff: { type: "exponential", delay: 5000 },
67
+ removeOnComplete: true,
68
+ removeOnFail: true,
69
+ },
70
+ },
71
+ // `files/hash-job.ts` FILE_LIBRARY_HASH_JOB: the hashing dispatcher, owed by the hourly kickoff
72
+ // under its own name as id
73
+ "file-library-hash": {
74
+ queue: "cap-kernel-maintenance",
75
+ idempotent: "Owes each org's first hashing batch under a deterministic id; a second run owes the same ids, deduplicated",
76
+ processedIn: "packages/kernel/src/runtime/maintenance.ts",
77
+ // removed either way, so the next kickoff can owe it again
78
+ opts: {
79
+ attempts: 5,
80
+ backoff: { type: "exponential", delay: 5000 },
81
+ removeOnComplete: true,
82
+ removeOnFail: true,
83
+ },
84
+ },
85
+ // `files/hash-job.ts` FILE_LIBRARY_HASH_ORG_JOB: one org's hashing batch, owed by the dispatcher
86
+ // and by the previous batch, under `fileLibraryHashOrgJobId`
87
+ "file-library-hash-org": {
88
+ queue: "cap-kernel-maintenance",
89
+ idempotent: "Holds the org's hashing lock and re-checks each blob under its row lock and the hash's lock; a blob already hashed or merged is skipped",
90
+ processedIn: "packages/kernel/src/runtime/maintenance.ts",
91
+ opts: {
92
+ attempts: 5,
93
+ backoff: { type: "exponential", delay: 5000 },
94
+ removeOnComplete: true,
95
+ removeOnFail: true,
96
+ },
97
+ },
98
+ // `files/library-backfill.ts` FILE_LIBRARY_BACKFILL_JOB: the one-off catch-up copy, owed by the
99
+ // kickoff until it settled, under its own name as id
100
+ "file-library-backfill": {
101
+ queue: "cap-kernel-maintenance",
102
+ idempotent: "Does nothing once the settled marker exists; the copy itself is idempotent and writes the marker in its own transaction",
103
+ processedIn: "packages/kernel/src/runtime/maintenance.ts",
104
+ opts: {
105
+ attempts: 5,
106
+ backoff: { type: "exponential", delay: 30000 },
107
+ removeOnComplete: true,
108
+ removeOnFail: true,
109
+ },
110
+ },
111
+ // `files/blob-objects.ts` FILE_RELEASE_JOB: owed, deferred, by every discard and draft cleanup
112
+ // of an upload, under `fileReleaseJobId`
113
+ "file-release": {
114
+ queue: "cap-kernel-maintenance",
115
+ idempotent: "Re-reads the deleted file under its row lock and releases its blob only while nothing else points at it, or deletes its own staging key; a second run finds nothing to do",
116
+ processedIn: "packages/kernel/src/runtime/maintenance.ts",
117
+ opts: { attempts: 10, backoff: { type: "exponential", delay: 5000 }, removeOnComplete: true },
118
+ },
119
+ // `files/blob-objects.ts` FILE_STAGING_DELETE_JOB: owed by a finalize that reused another blob, a
120
+ // discard and the draft cleanup, under `fileStagingDeleteJobId`
121
+ "file-staging-delete": {
122
+ queue: "cap-kernel-maintenance",
123
+ idempotent: "Deletes the file's own staging key only when the file is no longer uploading and no blob names that key; deleting a missing object is a no-op",
124
+ processedIn: "packages/kernel/src/runtime/maintenance.ts",
125
+ opts: { attempts: 10, backoff: { type: "exponential", delay: 5000 }, removeOnComplete: true },
126
+ },
55
127
  // `themes/platform-icon-objects.ts` PLATFORM_ICON_DELETE_JOB: owed by an icon upload (its own
56
128
  // object's delayed orphan check), a replace and a clear (the object the row stopped naming)
57
129
  "platform-icon-delete": {
@@ -38,6 +38,8 @@ export interface NamedThrottler {
38
38
  * and `device-token-ip` with `@Throttled` (every request counts; neither checks a guessable
39
39
  * credential: the device code is 32 random bytes). `POST /api/v1/app-auth/token` opts in to
40
40
  * `app-auth-token-ip` the same way (the one-time code is 32 random bytes).
41
+ * `POST /api/v1/orgs/:orgId/files/:id/finalize` opts in to `file-finalize` (60 per minute per
42
+ * account: each finalize reads a whole upload and copies it).
41
43
  * `POST …/guides/:guideId/checks/:checkId/run` opts in to `setup-check` (setup guides v2 §10.3: each run may call a third party).
42
44
  *
43
45
  * `device-stream-ip` is not a Nest route limit either: the gateway's raw viewer route
@@ -39,6 +39,8 @@ const LOGIN_MSG = "Too many failed login attempts; try again later";
39
39
  * and `device-token-ip` with `@Throttled` (every request counts; neither checks a guessable
40
40
  * credential: the device code is 32 random bytes). `POST /api/v1/app-auth/token` opts in to
41
41
  * `app-auth-token-ip` the same way (the one-time code is 32 random bytes).
42
+ * `POST /api/v1/orgs/:orgId/files/:id/finalize` opts in to `file-finalize` (60 per minute per
43
+ * account: each finalize reads a whole upload and copies it).
42
44
  * `POST …/guides/:guideId/checks/:checkId/run` opts in to `setup-check` (setup guides v2 §10.3: each run may call a third party).
43
45
  *
44
46
  * `device-stream-ip` is not a Nest route limit either: the gateway's raw viewer route
@@ -239,6 +241,18 @@ export const NAMED_THROTTLERS = [
239
241
  message: "Too many share link requests; try again later",
240
242
  getTracker: ip,
241
243
  },
244
+ // file upload finalizes per signed-in person (file library spec §3): 60 a minute, every request
245
+ // counts (@Throttled); each one reads a whole upload into memory and copies it
246
+ {
247
+ name: "file-finalize",
248
+ group: "file-finalize",
249
+ onSuccess: "clear",
250
+ limit: 60,
251
+ ttl: 60_000,
252
+ message: "Too many file uploads finished at once; try again in a minute",
253
+ code: "rate_limited",
254
+ getTracker: (req) => sha256(principalAccountId(req)),
255
+ },
242
256
  ];
243
257
  /** The storage key of a named throttler's counter for a tracker (shared by the guard and success paths). */
244
258
  export const throttlerKey = (name, tracker) => sha256(`${name}:${tracker}`);
@@ -334,6 +334,12 @@ let KernelLifecycle = class KernelLifecycle {
334
334
  if (bootstrapAgain && opts.bootstrap !== undefined) {
335
335
  await this.runBootstrap(opts.bootstrap.dir, true);
336
336
  this.checkpoint();
337
+ // The second pass installs its extensions through the lifecycle ops, which only publish
338
+ // `kernel.plugins.changed`: this replica would load them whenever the message arrives. The
339
+ // start loads them itself before it goes on (the template connectors plan against them) and
340
+ // serves (an org's first request sees the builtin plugin's tools)
341
+ await this.extensionLifecycle.reconcile("bootstrap");
342
+ this.checkpoint();
337
343
  }
338
344
  // The one-off reconciliation of template connectors (plugin pages spec §7): once the
339
345
  // extensions loaded (it plans connectors against their connector extensions) and the bootstrap
@@ -424,7 +424,7 @@ let ModelPurposesService = class ModelPurposesService {
424
424
  try {
425
425
  const out = await consumeModelStream(provider, request, idleMs, signal, (ev) => {
426
426
  chars += deltaChars(ev);
427
- });
427
+ }, this.log);
428
428
  return {
429
429
  content: out.content,
430
430
  stopReason: out.stopReason,
@@ -322,7 +322,7 @@ let Offboarding = class Offboarding {
322
322
  .where("account_id", "=", accountId)
323
323
  .execute();
324
324
  // after the conversations above (the share rows come last, as in every other share write)
325
- const sharesRevoked = await revokeSharesIn(this.db.db, this.outbox, { orgId, createdBy: accountId }, "member_offboarded");
325
+ const sharesRevoked = await revokeSharesIn(this.db.db, { orgId, createdBy: accountId }, "member_offboarded");
326
326
  await audit(this.db.db, {
327
327
  ...(actor.actorAccountId !== undefined && { actorAccountId: actor.actorAccountId }),
328
328
  ...(actor.actorTokenId !== undefined && { actorTokenId: actor.actorTokenId }),