@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
@@ -1,4 +1,4 @@
1
- import { type CompactForm, type FormAnswer, type Logger, type UiActionResult, type UiContribution, type UiIcon, type UiSlotId, type UiView } from "@capybara-hq/plugin-sdk";
1
+ import { type CompactForm, type FormAnswer, type JsonValue, type Logger, type UiActionResult, type UiContribution, type UiIcon, type UiPageFrame, type UiPageNav, type UiSlotId, type UiView } from "@capybara-hq/plugin-sdk";
2
2
  import { ConversationsService } from "../conversations/conversations.service.js";
3
3
  import type { KernelSchemaDb } from "../db/kernel-schema.js";
4
4
  import { EffectiveConfigs } from "../extensions/effective-config.js";
@@ -9,6 +9,8 @@ import { type OrgRole } from "../orgs/roles.js";
9
9
  export { callExtension } from "./call-extension.js";
10
10
  /** 插件 render / action 的时限(spec §4.2:慢的插件只让那个标签失败)。 */
11
11
  export declare const UI_CALL_TIMEOUT_MS = 5000;
12
+ /** The time limit of a component query (plugin full pages spec §4.1). */
13
+ export declare const UI_QUERY_TIMEOUT_MS = 10000;
12
14
  /** 列出贡献接口的一项。 */
13
15
  export interface UiContributionItem {
14
16
  plugin: string;
@@ -25,6 +27,10 @@ export interface UiContributionItem {
25
27
  icon: UiIcon;
26
28
  /** The form on a compact screen: the slot's, narrowed by the contribution's (spec §5.6). */
27
29
  compact: CompactForm;
30
+ /** `org.page` component only, when the manifest names it: who draws the page frame. */
31
+ frame?: UiPageFrame;
32
+ /** `org.page` component only, when the manifest names it: the suggested navigation section. */
33
+ nav?: UiPageNav;
28
34
  }
29
35
  /** A list slot of an arrangement listing: where its entry comes from and its items in order. */
30
36
  export interface UiArrangementListSlot {
@@ -189,6 +195,14 @@ export declare class UiViews {
189
195
  * else is 404.
190
196
  */
191
197
  private skillFileEmbed;
198
+ /**
199
+ * A `file.preview` embed for one of the caller's own library files (file library spec §6; no
200
+ * conversation or agent): the caller's role may use agents (`agents.use`) and the slot, the
201
+ * contribution is a loaded `file.preview` embed of an extension enabled in the org, and an
202
+ * enabled previewer of that extension with `embed: <this contribution>` takes the file (another
203
+ * account's file throws 404 `file.not_found`); anything else is 404.
204
+ */
205
+ private libraryFileEmbed;
192
206
  /**
193
207
  * The path of a loaded `file.preview` embed contribution (a share page's embed previewer, file
194
208
  * sharing spec §7), else 404 `ui.not_found`. Whether the previewer takes the share's snapshot
@@ -203,6 +217,20 @@ export declare class UiViews {
203
217
  payload?: unknown;
204
218
  answer?: FormAnswer;
205
219
  }): Promise<UiActionResult>;
220
+ /**
221
+ * Runs a component's named query (`ctx.ui.query`, plugin full pages spec §4.1): the same gate
222
+ * and args as the component's view, plus `{ query, params, signal }`. Not offered (or no
223
+ * handler) is 404 `ui.query_not_found`; params over `UI_LIMITS.componentQueryParamsBytes` 413
224
+ * `ui.query_params_too_large`; 10 s 504 `ui.query_timeout`; a throw 502 `ui.query_failed`; a
225
+ * result that is not JSON or over `UI_LIMITS.componentQueryBytes` 502
226
+ * `ui.query_result_too_large`.
227
+ */
228
+ query(t: UiOrgTarget, input: {
229
+ query: string;
230
+ params?: unknown;
231
+ }): Promise<{
232
+ data: JsonValue;
233
+ }>;
206
234
  /** Ids of the extension's live `panel` contributions. */
207
235
  private panels;
208
236
  /**
package/dist/ui/views.js CHANGED
@@ -7,7 +7,7 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
7
7
  var __param = (this && this.__param) || function (paramIndex, decorator) {
8
8
  return function (target, key) { decorator(target, key, paramIndex); }
9
9
  };
10
- import { effectiveCompact, UI_ARRANGEABLE_SLOTS, validateUiView, } from "@capybara-hq/plugin-sdk";
10
+ import { effectiveCompact, UI_ARRANGEABLE_SLOTS, UI_LIMITS, validateUiView, } from "@capybara-hq/plugin-sdk";
11
11
  import { Inject, Injectable } from "@nestjs/common";
12
12
  import { sql } from "kysely";
13
13
  import { isAgentVisibleIn } from "../agents/agent-lookup.js";
@@ -24,9 +24,12 @@ import { readOrgSettings } from "../orgs/settings.service.js";
24
24
  import { arrange, arrangeBySlot, effectiveEntry, isSingle, keyOf, ORG_ARRANGEABLE, orderItems, resolveSingleSlot, storedUse, } from "./arrangement.js";
25
25
  import { callExtension } from "./call-extension.js";
26
26
  import { canUseSlot, UUID_RE } from "./registry.js";
27
+ import { jsonBytes } from "./ui.schemas.js";
27
28
  export { callExtension } from "./call-extension.js";
28
29
  /** 插件 render / action 的时限(spec §4.2:慢的插件只让那个标签失败)。 */
29
30
  export const UI_CALL_TIMEOUT_MS = 5_000;
31
+ /** The time limit of a component query (plugin full pages spec §4.1). */
32
+ export const UI_QUERY_TIMEOUT_MS = 10_000;
30
33
  /** The log field naming where a target is: its org, or the platform scope. */
31
34
  const whereOf = (t) => t.scope === "platform" ? { scope: "platform" } : { orgId: t.orgId };
32
35
  /**
@@ -93,6 +96,8 @@ function listed(entries) {
93
96
  ...(c.kind === "embed" && c.path !== undefined && { path: c.path }),
94
97
  icon: c.icon ?? "puzzle",
95
98
  compact: effectiveCompact(s.compact, c.compact),
99
+ ...(c.frame !== undefined && { frame: c.frame }),
100
+ ...(c.nav !== undefined && { nav: c.nav }),
96
101
  }));
97
102
  }
98
103
  /** The candidates of a single slot in an arrangement listing. */
@@ -112,13 +117,24 @@ const TOAST_MAX = 500;
112
117
  const MAX_LOGGED_PROBLEMS = 10;
113
118
  const notFound = () => new ApiError("ui.not_found", "UI contribution not found");
114
119
  const isObj = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
120
+ /** At most this many query names in an action result's `invalidate`. */
121
+ const INVALIDATE_MAX = 50;
115
122
  /**
116
- * 校验动作结果,返回问题列表(空 = 合法)。A new `view` may carry `data` only for a component
123
+ * Checks an action result and returns its problems (empty = valid). A new `view` may carry
124
+ * `data`, and `invalidate` (query names the host refetches) is read, only for a component
117
125
  * (`component`).
118
126
  */
119
127
  function actionResultProblems(r, component) {
120
128
  if (!isObj(r))
121
129
  return ["action result must be an object"];
130
+ if (component && r.invalidate !== undefined) {
131
+ const inv = r.invalidate;
132
+ if (!Array.isArray(inv) ||
133
+ inv.length > INVALIDATE_MAX ||
134
+ !inv.every((q) => typeof q === "string" && q !== "" && q.length <= 200)) {
135
+ return [`invalidate must be at most ${INVALIDATE_MAX} query names of 1-200 characters`];
136
+ }
137
+ }
122
138
  if (r.view !== undefined)
123
139
  return validateUiView(r.view, { component }).map((p) => `view: ${p}`);
124
140
  if (r.toast === undefined)
@@ -277,6 +293,12 @@ let UiViews = class UiViews {
277
293
  const { fileId: f, skillFile, ...org } = t;
278
294
  if (skillFile !== undefined)
279
295
  return this.skillFileEmbed({ ...org, skillFile }, f);
296
+ if (f !== undefined && org.conversationId === undefined) {
297
+ if (org.agentId !== undefined) {
298
+ throw new ApiError("validation_failed", "fileId is not allowed with agentId");
299
+ }
300
+ return this.libraryFileEmbed(org, f);
301
+ }
280
302
  fileId = f;
281
303
  target = { ...org, locale: "en" };
282
304
  }
@@ -354,6 +376,39 @@ let UiViews = class UiViews {
354
376
  throw notFound();
355
377
  return { plugin: t.plugin, contribution: t.id, path, skillFile: file };
356
378
  }
379
+ /**
380
+ * A `file.preview` embed for one of the caller's own library files (file library spec §6; no
381
+ * conversation or agent): the caller's role may use agents (`agents.use`) and the slot, the
382
+ * contribution is a loaded `file.preview` embed of an extension enabled in the org, and an
383
+ * enabled previewer of that extension with `embed: <this contribution>` takes the file (another
384
+ * account's file throws 404 `file.not_found`); anything else is 404.
385
+ */
386
+ async libraryFileEmbed(t, fileId) {
387
+ const entry = this.d.host
388
+ .uiContributions()
389
+ .find((c) => c.plugin === t.plugin &&
390
+ c.contribution.id === t.id &&
391
+ c.contribution.kind === "embed" &&
392
+ c.slot.id === "file.preview");
393
+ const path = entry?.contribution.path;
394
+ if (entry === undefined || path === undefined)
395
+ throw notFound();
396
+ if (!canUseSlot(entry.slot, t.role) || !can(t.role, "agents.use"))
397
+ throw notFound();
398
+ if (!(await this.d.enabledPlugins(t.orgId)).has(t.plugin))
399
+ throw notFound();
400
+ const allowed = this.d.previewEmbedAllowed !== undefined &&
401
+ (await this.d.previewEmbedAllowed({
402
+ orgId: t.orgId,
403
+ accountId: t.accountId,
404
+ fileId,
405
+ plugin: t.plugin,
406
+ contribution: t.id,
407
+ }));
408
+ if (!allowed)
409
+ throw notFound();
410
+ return { plugin: t.plugin, contribution: t.id, path, fileId };
411
+ }
357
412
  /**
358
413
  * The path of a loaded `file.preview` embed contribution (a share page's embed previewer, file
359
414
  * sharing spec §7), else 404 `ui.not_found`. Whether the previewer takes the share's snapshot
@@ -383,6 +438,12 @@ let UiViews = class UiViews {
383
438
  /** 执行动作:调用插件 `action`(视图里的按钮 / 表单提交),校验返回的提示或新视图。 */
384
439
  async act(t, input) {
385
440
  const { entry, args } = await this.resolve(t, "action");
441
+ // a component's action takes a form-sized payload; a view's button keeps the view limit
442
+ if (entry.contribution.kind !== "component" &&
443
+ input.payload !== undefined &&
444
+ jsonBytes(input.payload) > UI_LIMITS.payloadBytes) {
445
+ throw new ApiError("validation_failed", `payload must be at most ${UI_LIMITS.payloadBytes} bytes as JSON`);
446
+ }
386
447
  const action = entry.action;
387
448
  const r = await this.call(t, "action", (signal) => action({
388
449
  ...args,
@@ -391,11 +452,74 @@ let UiViews = class UiViews {
391
452
  ...(input.payload !== undefined && { payload: input.payload }),
392
453
  ...(input.answer !== undefined && { answer: input.answer }),
393
454
  }));
394
- this.check(t, "action", actionResultProblems(r, entry.contribution.kind === "component"));
455
+ const component = entry.contribution.kind === "component";
456
+ this.check(t, "action", actionResultProblems(r, component));
395
457
  const res = r;
396
- if (res.view !== undefined)
397
- return { view: dropForeignOpens(res.view, this.panels(t.plugin)) };
398
- return res.toast !== undefined ? { toast: { zh: res.toast.zh, en: res.toast.en } } : {};
458
+ // the query names to refetch: a component's only (plugin full pages spec §4.1)
459
+ const inv = component && res.invalidate !== undefined ? { invalidate: [...res.invalidate] } : {};
460
+ if (res.view !== undefined) {
461
+ return { view: dropForeignOpens(res.view, this.panels(t.plugin)), ...inv };
462
+ }
463
+ return res.toast !== undefined
464
+ ? { toast: { zh: res.toast.zh, en: res.toast.en }, ...inv }
465
+ : inv;
466
+ }
467
+ /**
468
+ * Runs a component's named query (`ctx.ui.query`, plugin full pages spec §4.1): the same gate
469
+ * and args as the component's view, plus `{ query, params, signal }`. Not offered (or no
470
+ * handler) is 404 `ui.query_not_found`; params over `UI_LIMITS.componentQueryParamsBytes` 413
471
+ * `ui.query_params_too_large`; 10 s 504 `ui.query_timeout`; a throw 502 `ui.query_failed`; a
472
+ * result that is not JSON or over `UI_LIMITS.componentQueryBytes` 502
473
+ * `ui.query_result_too_large`.
474
+ */
475
+ async query(t, input) {
476
+ let resolved;
477
+ try {
478
+ resolved = await this.resolve(t, "query");
479
+ }
480
+ catch (e) {
481
+ if (e instanceof ApiError && e.code === "ui.not_found") {
482
+ throw new ApiError("ui.query_not_found", "UI component query not found");
483
+ }
484
+ throw e;
485
+ }
486
+ const params = (input.params ?? null);
487
+ if (jsonBytes(params) > UI_LIMITS.componentQueryParamsBytes) {
488
+ throw new ApiError("ui.query_params_too_large", `params must be at most ${UI_LIMITS.componentQueryParamsBytes} bytes as JSON`);
489
+ }
490
+ const handler = resolved.entry.query;
491
+ // an org target always resolves to org args
492
+ const args = resolved.args;
493
+ const data = await callExtension({
494
+ log: this.d.log,
495
+ plugin: t.plugin,
496
+ what: "query",
497
+ fields: { plugin: t.plugin, contribution: t.id, query: input.query, orgId: t.orgId },
498
+ timeoutMs: UI_QUERY_TIMEOUT_MS,
499
+ failCode: "ui.query_failed",
500
+ timeoutCode: "ui.query_timeout",
501
+ failMessage: `Plugin ${t.plugin} failed to answer query ${input.query} of ${t.id}`,
502
+ fn: (signal) => handler({ ...args, query: input.query, params, signal }),
503
+ });
504
+ let json;
505
+ try {
506
+ json = JSON.stringify(data);
507
+ }
508
+ catch {
509
+ json = undefined;
510
+ }
511
+ const bytes = json === undefined ? undefined : Buffer.byteLength(json, "utf8");
512
+ if (bytes === undefined || bytes > UI_LIMITS.componentQueryBytes) {
513
+ this.d.log.warn("plugin ui query returned a result that is not JSON or too large", {
514
+ plugin: t.plugin,
515
+ contribution: t.id,
516
+ query: input.query,
517
+ orgId: t.orgId,
518
+ ...(bytes !== undefined && { bytes }),
519
+ });
520
+ throw new ApiError("ui.query_result_too_large", `Plugin ${t.plugin} returned a query result that is not JSON of at most ${UI_LIMITS.componentQueryBytes} bytes`);
521
+ }
522
+ return { data };
399
523
  }
400
524
  /** Ids of the extension's live `panel` contributions. */
401
525
  panels(plugin) {
@@ -421,7 +545,7 @@ let UiViews = class UiViews {
421
545
  c.contribution.id === t.id &&
422
546
  (need === "embed"
423
547
  ? c.contribution.kind === "embed"
424
- : // a view, or a component's server view (served like a view of its slot)
548
+ : // a view, or a component's server view or query (served like a view of its slot)
425
549
  (c.contribution.kind === "view" || c.contribution.kind === "component") &&
426
550
  c[need] !== undefined));
427
551
  if (t.scope === "platform") {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capybara-hq/kernel",
3
- "version": "0.1.0-rc.106",
3
+ "version": "0.1.0-rc.108",
4
4
  "description": "Capybara kernel: config, database, plugin host and HTTP API of the Capybara agent platform",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -66,7 +66,7 @@
66
66
  "yaml": "^2.9.1",
67
67
  "yauzl": "3.4.0",
68
68
  "zod": "^4.6.7",
69
- "@capybara-hq/plugin-sdk": "^0.1.0-rc.85"
69
+ "@capybara-hq/plugin-sdk": "^0.1.0-rc.86"
70
70
  },
71
71
  "devDependencies": {
72
72
  "@langchain/langgraph-checkpoint-validation": "^1.2.0",
@@ -75,7 +75,7 @@
75
75
  "@types/ws": "^8.18.2",
76
76
  "@types/yauzl": "3.4.0",
77
77
  "ws": "^8.22.0",
78
- "@capybara-hq/testing": "0.1.0-rc.47"
78
+ "@capybara-hq/testing": "0.1.0-rc.48"
79
79
  },
80
80
  "scripts": {
81
81
  "build": "tsc -b"
@@ -0,0 +1,285 @@
1
+ -- File library (docs/superpowers/specs/2026-11-27-file-library-design.md §1, §9): bytes become
2
+ -- per-org content-addressed blobs, files become account-owned rows, conversations refer to files.
3
+ -- This is the expand step: the tables, the `file_shares` columns and the copy function. A later
4
+ -- contract migration drops `file_shares.object_key` and the chat purpose of `attachments`.
5
+ --
6
+ -- The data copy is the function `file_library_copy(since)` defined here, run by
7
+ -- 0191_file_library_copy.sql in its own transaction (so this file's DDL locks are not held while
8
+ -- it scans). It copies chat attachments, `artifact_created` artifacts and share snapshots with
9
+ -- preserved ids (every logged ref resolves on the first request after the deploy), restricted to
10
+ -- source rows created at or after `since` ('-infinity' = everything), and catches up the rows old
11
+ -- code changed after an earlier copy (a draft now bound, an upload now finalized, a share whose
12
+ -- snapshot generation moved on). During a rolling deploy old replicas keep writing the old tables,
13
+ -- so the kernel calls it again from a one-off catch-up job after the rolling window, before the
14
+ -- hashing job merges any blob (a share repointed to a merged blob would otherwise look like a moved
15
+ -- snapshot generation and be pointed back at the deleted duplicate). It is idempotent: every
16
+ -- insert is ON CONFLICT DO NOTHING, every update guarded.
17
+ --
18
+ -- `file_shares.object_key` is kept as is (old replicas still read it for liveness and the share
19
+ -- sweep); `blob_id` is the new reference.
20
+ --
21
+ -- Search: pg_trgm is not assumed present, so name search is a `lower(name)` index (prefix queries)
22
+ -- plus `position(lower($q) in lower(name)) > 0` over one account's ready rows, bounded by the
23
+ -- library index.
24
+
25
+ -- The bytes. `object_key` is relative to `kernel/<org>/`: new blobs `blobs/<blobId>` (every one
26
+ -- written by the kernel: a delivery, or a finalized upload's verified copy); migrated blobs keep
27
+ -- their old key. `sha256` is null while `pending` and for a migrated blob the hashing job has not
28
+ -- reached yet. `dedup_after`: from when another account's upload may resolve to this blob (now()
29
+ -- for kernel-written blobs). `gone`: the hashing job found the object missing.
30
+ CREATE TABLE IF NOT EXISTS blobs (
31
+ id text PRIMARY KEY,
32
+ org_id text NOT NULL REFERENCES orgs(id) ON DELETE CASCADE,
33
+ sha256 text CHECK (sha256 ~ '^[0-9a-f]{64}$'),
34
+ size bigint NOT NULL CHECK (size >= 0),
35
+ etag text,
36
+ object_key text NOT NULL,
37
+ status text NOT NULL CHECK (status IN ('pending', 'ready', 'deleting', 'gone')),
38
+ dedup_after timestamptz NOT NULL DEFAULT now(),
39
+ created_at timestamptz NOT NULL DEFAULT now()
40
+ );
41
+ CREATE UNIQUE INDEX IF NOT EXISTS blobs_org_sha256_key ON blobs (org_id, sha256)
42
+ WHERE sha256 IS NOT NULL;
43
+ -- one blob per object
44
+ CREATE UNIQUE INDEX IF NOT EXISTS blobs_org_object_key ON blobs (org_id, object_key);
45
+ -- the hashing job's cursor
46
+ CREATE INDEX IF NOT EXISTS blobs_unhashed_idx ON blobs (org_id, id) WHERE sha256 IS NULL;
47
+ -- the sweep: pending intents and deletions under way
48
+ CREATE INDEX IF NOT EXISTS blobs_status_idx ON blobs (status, created_at) WHERE status <> 'ready';
49
+
50
+ -- What a person sees. `blob_id` is null while `uploading` (and may be once `deleted`);
51
+ -- `staging_key` is the staging object of a migrated `uploading` row (its old `attachments/<id>`
52
+ -- key; null for new rows, which stage at `uploads/<id>`). `agent_id` has no foreign key: agents can
53
+ -- be deleted, the library keeps the id as a label. `expires_at` applies to `uploading` / `draft`.
54
+ -- `sha256`: an upload's declared hash at create, the verified one from finalize on (null for
55
+ -- deliveries and migrated rows); `upload_purpose`: where an upload was started (null otherwise).
56
+ -- `ref_key` / `ref_etag`: the object key and etag of the blob the file was first stored on, kept
57
+ -- when the file later moves to another blob (a hashing merge) so the unsigned reference and etag
58
+ -- the model saw stay the same in later requests and replays. With `ref_key` set, `ref_etag` is
59
+ -- taken as recorded (null: none); with no `ref_key`, the blob's own key and etag.
60
+ CREATE TABLE IF NOT EXISTS files (
61
+ id text PRIMARY KEY,
62
+ org_id text NOT NULL REFERENCES orgs(id) ON DELETE CASCADE,
63
+ account_id text NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
64
+ blob_id text REFERENCES blobs(id),
65
+ name text NOT NULL,
66
+ content_type text NOT NULL,
67
+ size bigint NOT NULL,
68
+ pages integer,
69
+ origin text NOT NULL CHECK (origin IN ('upload', 'delivered', 'generated')),
70
+ status text NOT NULL CHECK (status IN ('uploading', 'draft', 'ready', 'deleted')),
71
+ agent_id text,
72
+ source_conversation_id text REFERENCES conversations(id) ON DELETE SET NULL,
73
+ source_path text,
74
+ staging_key text,
75
+ sha256 text CHECK (sha256 ~ '^[0-9a-f]{64}$'),
76
+ upload_purpose text CHECK (upload_purpose IN ('composer', 'library')),
77
+ ref_key text,
78
+ ref_etag text,
79
+ expires_at timestamptz,
80
+ created_at timestamptz NOT NULL DEFAULT now(),
81
+ deleted_at timestamptz,
82
+ CONSTRAINT files_blob_check CHECK (status IN ('uploading', 'deleted') OR blob_id IS NOT NULL)
83
+ );
84
+ CREATE INDEX IF NOT EXISTS files_library_idx ON files (org_id, account_id, created_at DESC, id DESC)
85
+ WHERE status = 'ready';
86
+ CREATE INDEX IF NOT EXISTS files_blob_idx ON files (blob_id);
87
+ -- the instant path of an upload: the caller's own files with these bytes
88
+ CREATE INDEX IF NOT EXISTS files_account_sha256_idx ON files (org_id, account_id, sha256)
89
+ WHERE sha256 IS NOT NULL;
90
+ CREATE INDEX IF NOT EXISTS files_expiry_idx ON files (expires_at)
91
+ WHERE status IN ('uploading', 'draft');
92
+ CREATE INDEX IF NOT EXISTS files_deleted_idx ON files (deleted_at) WHERE status = 'deleted';
93
+ CREATE INDEX IF NOT EXISTS files_source_idx ON files (source_conversation_id, source_path);
94
+ CREATE INDEX IF NOT EXISTS files_name_lower_idx
95
+ ON files (org_id, account_id, lower(name) text_pattern_ops) WHERE status = 'ready';
96
+
97
+ -- Which conversation refers to which file: `attached` (sent in a message) or `delivered`;
98
+ -- `first_seq` is the event that first referred to it (null when not known).
99
+ CREATE TABLE IF NOT EXISTS conversation_files (
100
+ conversation_id text NOT NULL REFERENCES conversations(id) ON DELETE CASCADE,
101
+ file_id text NOT NULL REFERENCES files(id) ON DELETE CASCADE,
102
+ org_id text NOT NULL REFERENCES orgs(id) ON DELETE CASCADE,
103
+ role text NOT NULL CHECK (role IN ('attached', 'delivered')),
104
+ first_seq bigint,
105
+ created_at timestamptz NOT NULL DEFAULT now(),
106
+ PRIMARY KEY (conversation_id, file_id)
107
+ );
108
+ CREATE INDEX IF NOT EXISTS conversation_files_file_idx ON conversation_files (file_id);
109
+
110
+ -- Shares point at blobs; a library share has no conversation.
111
+ ALTER TABLE file_shares ADD COLUMN IF NOT EXISTS blob_id text REFERENCES blobs(id);
112
+ ALTER TABLE file_shares ADD COLUMN IF NOT EXISTS source_file_id text
113
+ REFERENCES files(id) ON DELETE SET NULL;
114
+ ALTER TABLE file_shares ALTER COLUMN conversation_id DROP NOT NULL;
115
+ -- capybara:allow-destructive replaced by a wider check right below (adds 'file_deleted')
116
+ ALTER TABLE file_shares DROP CONSTRAINT IF EXISTS file_shares_revoke_reason_check;
117
+ ALTER TABLE file_shares ADD CONSTRAINT file_shares_revoke_reason_check CHECK (revoke_reason IN
118
+ ('creator', 'admin', 'conversation_deleted', 'member_offboarded', 'creator_lost_access',
119
+ 'file_deleted'));
120
+ CREATE INDEX IF NOT EXISTS file_shares_blob_idx ON file_shares (blob_id) WHERE blob_id IS NOT NULL;
121
+ CREATE INDEX IF NOT EXISTS file_shares_source_file_idx ON file_shares (source_file_id);
122
+
123
+ DROP POLICY IF EXISTS org_scope ON blobs;
124
+ CREATE POLICY org_scope ON blobs USING (rls_admits(org_id)) WITH CHECK (rls_admits(org_id));
125
+ DROP POLICY IF EXISTS org_scope ON files;
126
+ CREATE POLICY org_scope ON files USING (rls_admits(org_id)) WITH CHECK (rls_admits(org_id));
127
+ DROP POLICY IF EXISTS org_scope ON conversation_files;
128
+ CREATE POLICY org_scope ON conversation_files USING (rls_admits(org_id))
129
+ WITH CHECK (rls_admits(org_id));
130
+
131
+ -- The data copy (see the header). A migrated blob's id is derived from its org and key,
132
+ -- md5('blob:' || org_id || '/' || object_key)::uuid; inserts that reference a blob resolve it by
133
+ -- (org_id, object_key), so a blob written by new code under the same key is reused. Migrated blobs
134
+ -- are `ready` with `sha256` null (the hashing job fills it or merges duplicates).
135
+ CREATE OR REPLACE FUNCTION file_library_copy(since timestamptz) RETURNS void
136
+ LANGUAGE plpgsql
137
+ SET search_path TO capybara, public
138
+ AS $$
139
+ BEGIN
140
+ -- 1. Chat attachments. A blob for every ready one in range, and for those whose migrated
141
+ -- `uploading` file waits for them (finalized by old code after an earlier copy).
142
+ INSERT INTO blobs (id, org_id, sha256, size, etag, object_key, status, dedup_after, created_at)
143
+ SELECT md5('blob:' || a.org_id || '/' || a.object_key)::uuid::text, a.org_id, NULL, a.size,
144
+ a.etag, a.object_key, 'ready', now(), a.created_at
145
+ FROM attachments a
146
+ WHERE a.purpose = 'chat' AND a.status = 'ready'
147
+ AND (a.created_at >= since
148
+ OR EXISTS (SELECT 1 FROM files f WHERE f.id = a.id AND f.status = 'uploading'))
149
+ ON CONFLICT DO NOTHING;
150
+
151
+ -- ready + bound → `ready`; ready + unbound → `draft` (keeps `expires_at`); pending →
152
+ -- `uploading` without a blob, its old key kept as `staging_key`
153
+ INSERT INTO files (id, org_id, account_id, blob_id, name, content_type, size, pages, origin,
154
+ status, agent_id, source_conversation_id, source_path, staging_key,
155
+ ref_key, ref_etag, expires_at, created_at)
156
+ SELECT a.id, a.org_id, a.account_id, b.id, a.name, a.content_type, a.size, a.pages, 'upload',
157
+ CASE WHEN a.status = 'pending' THEN 'uploading'
158
+ WHEN a.conversation_id IS NULL THEN 'draft'
159
+ ELSE 'ready' END,
160
+ NULL, a.conversation_id, NULL,
161
+ CASE WHEN a.status = 'pending' THEN a.object_key END,
162
+ b.object_key, b.etag,
163
+ CASE WHEN a.status = 'pending' OR a.conversation_id IS NULL THEN a.expires_at END,
164
+ a.created_at
165
+ FROM attachments a
166
+ LEFT JOIN blobs b ON a.status = 'ready' AND b.org_id = a.org_id AND b.object_key = a.object_key
167
+ WHERE a.purpose = 'chat' AND a.status IN ('ready', 'pending') AND a.created_at >= since
168
+ ON CONFLICT DO NOTHING;
169
+
170
+ -- catch-up: an `uploading` file whose attachment old code finalized
171
+ UPDATE files f
172
+ SET blob_id = b.id,
173
+ ref_key = b.object_key,
174
+ ref_etag = b.etag,
175
+ status = CASE WHEN a.conversation_id IS NULL THEN 'draft' ELSE 'ready' END,
176
+ size = a.size,
177
+ pages = a.pages,
178
+ staging_key = NULL,
179
+ source_conversation_id = a.conversation_id,
180
+ expires_at = CASE WHEN a.conversation_id IS NULL THEN a.expires_at END
181
+ FROM attachments a
182
+ JOIN blobs b ON b.org_id = a.org_id AND b.object_key = a.object_key
183
+ WHERE f.id = a.id AND f.org_id = a.org_id AND f.status = 'uploading' AND f.origin = 'upload'
184
+ AND a.purpose = 'chat' AND a.status = 'ready';
185
+
186
+ -- catch-up: a `draft` file whose attachment old code bound to a message
187
+ UPDATE files f
188
+ SET status = 'ready', expires_at = NULL, source_conversation_id = a.conversation_id
189
+ FROM attachments a
190
+ WHERE f.id = a.id AND f.org_id = a.org_id AND f.status = 'draft' AND f.origin = 'upload'
191
+ AND a.purpose = 'chat' AND a.status = 'ready' AND a.conversation_id IS NOT NULL;
192
+
193
+ -- every bound attachment whose ready file is not referenced yet; `first_seq` is the first
194
+ -- user_message whose content names it (a message still queued has none yet)
195
+ INSERT INTO conversation_files (conversation_id, file_id, org_id, role, first_seq, created_at)
196
+ SELECT a.conversation_id, a.id, a.org_id, 'attached', m.seq, a.created_at
197
+ FROM attachments a
198
+ JOIN files f ON f.id = a.id AND f.org_id = a.org_id AND f.status = 'ready'
199
+ LEFT JOIN LATERAL (
200
+ SELECT e.seq FROM conversation_events e
201
+ WHERE e.conversation_id = a.conversation_id AND e.type = 'user_message'
202
+ AND jsonb_path_exists(e.payload,
203
+ '$.content[*].source ? (@.attachmentId == $id || @.fileId == $id)',
204
+ jsonb_build_object('id', a.id))
205
+ ORDER BY e.seq LIMIT 1
206
+ ) m ON true
207
+ WHERE a.purpose = 'chat' AND a.status = 'ready' AND a.conversation_id IS NOT NULL
208
+ AND NOT EXISTS (SELECT 1 FROM conversation_files cf
209
+ WHERE cf.conversation_id = a.conversation_id AND cf.file_id = a.id)
210
+ ON CONFLICT DO NOTHING;
211
+
212
+ -- 2. Delivered artifacts in range: one file per artifact id (its earliest event), owned by its
213
+ -- conversation's owner, deleted conversations included (files stay); every conversation that
214
+ -- logged the id refers to it from its first such event. One statement, so the events are
215
+ -- scanned once (the foreign keys of the sibling inserts are checked at the statement's end).
216
+ WITH ev AS MATERIALIZED (
217
+ SELECT e.conversation_id, e.seq, e.created_at, c.org_id, c.account_id, c.agent_id,
218
+ e.payload->>'artifactId' AS id, e.payload->>'objectKey' AS object_key,
219
+ e.payload->>'name' AS name, e.payload->>'contentType' AS content_type,
220
+ (e.payload->>'size')::bigint AS size, e.payload->>'sourcePath' AS source_path
221
+ FROM conversation_events e
222
+ JOIN conversations c ON c.id = e.conversation_id
223
+ WHERE e.type = 'artifact_created' AND e.created_at >= since
224
+ AND e.payload->>'artifactId' IS NOT NULL AND e.payload->>'objectKey' IS NOT NULL
225
+ AND e.payload->>'name' IS NOT NULL AND e.payload->>'contentType' IS NOT NULL
226
+ AND e.payload->>'size' IS NOT NULL
227
+ ),
228
+ x AS (
229
+ SELECT DISTINCT ON (id) * FROM ev ORDER BY id, created_at, seq
230
+ ),
231
+ new_blobs AS (
232
+ INSERT INTO blobs (id, org_id, sha256, size, etag, object_key, status, dedup_after,
233
+ created_at)
234
+ SELECT DISTINCT ON (org_id, object_key)
235
+ md5('blob:' || org_id || '/' || object_key)::uuid::text, org_id, NULL, size, NULL,
236
+ object_key, 'ready', now(), created_at
237
+ FROM x ORDER BY org_id, object_key, created_at
238
+ ON CONFLICT DO NOTHING
239
+ RETURNING id, org_id, object_key
240
+ ),
241
+ all_blobs AS (
242
+ SELECT id, org_id, object_key FROM new_blobs
243
+ UNION ALL
244
+ SELECT b.id, b.org_id, b.object_key FROM blobs b
245
+ WHERE EXISTS (SELECT 1 FROM x WHERE x.org_id = b.org_id AND x.object_key = b.object_key)
246
+ ),
247
+ new_files AS (
248
+ INSERT INTO files (id, org_id, account_id, blob_id, name, content_type, size, origin, status,
249
+ agent_id, source_conversation_id, source_path, ref_key, created_at)
250
+ SELECT x.id, x.org_id, x.account_id, ab.id, x.name, x.content_type, x.size,
251
+ CASE WHEN x.source_path LIKE 'generated/%' THEN 'generated' ELSE 'delivered' END,
252
+ 'ready', x.agent_id, x.conversation_id, x.source_path, ab.object_key, x.created_at
253
+ FROM x JOIN all_blobs ab ON ab.org_id = x.org_id AND ab.object_key = x.object_key
254
+ ON CONFLICT DO NOTHING
255
+ RETURNING id
256
+ )
257
+ INSERT INTO conversation_files (conversation_id, file_id, org_id, role, first_seq, created_at)
258
+ SELECT ev.conversation_id, ev.id, ev.org_id, 'delivered', min(ev.seq), min(ev.created_at)
259
+ FROM ev
260
+ WHERE EXISTS (SELECT 1 FROM new_files nf WHERE nf.id = ev.id)
261
+ OR EXISTS (SELECT 1 FROM files f WHERE f.id = ev.id AND f.org_id = ev.org_id)
262
+ GROUP BY ev.conversation_id, ev.id, ev.org_id
263
+ ON CONFLICT DO NOTHING;
264
+
265
+ -- 3. Shares: each snapshot object becomes a blob the share points at; also when old code moved
266
+ -- the share to a new snapshot generation after an earlier copy. `source_file_id` names the file
267
+ -- when one has the share's `file_id`. `object_key` stays (old replicas read it).
268
+ INSERT INTO blobs (id, org_id, sha256, size, etag, object_key, status, dedup_after, created_at)
269
+ SELECT md5('blob:' || s.org_id || '/' || s.object_key)::uuid::text, s.org_id, NULL, s.size,
270
+ NULL, s.object_key, 'ready', now(), s.created_at
271
+ FROM file_shares s
272
+ LEFT JOIN blobs cur ON cur.id = s.blob_id
273
+ WHERE s.object_key IS NOT NULL AND s.updated_at >= since
274
+ AND cur.object_key IS DISTINCT FROM s.object_key
275
+ ON CONFLICT DO NOTHING;
276
+
277
+ UPDATE file_shares s
278
+ SET blob_id = b.id,
279
+ source_file_id = coalesce(s.source_file_id,
280
+ (SELECT f.id FROM files f WHERE f.id = s.file_id AND f.org_id = s.org_id))
281
+ FROM blobs b
282
+ WHERE b.org_id = s.org_id AND b.object_key = s.object_key AND s.updated_at >= since
283
+ AND s.blob_id IS DISTINCT FROM b.id;
284
+ END
285
+ $$;
@@ -0,0 +1,4 @@
1
+ -- File library data copy (0190_file_library.sql header): copies every existing chat attachment,
2
+ -- delivered artifact and share snapshot, in its own transaction so 0190's DDL locks are not held
3
+ -- while it scans.
4
+ SELECT file_library_copy('-infinity');