@capybara-hq/kernel 0.1.0-rc.131 → 0.1.0-rc.133

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 (155) hide show
  1. package/bootstrap.json +5 -5
  2. package/dist/admin/admin.module.js +3 -0
  3. package/dist/admin/admin.schemas.d.ts +4 -0
  4. package/dist/admin/health.service.d.ts +2 -2
  5. package/dist/admin/health.service.js +6 -2
  6. package/dist/admin/setup.service.js +6 -1
  7. package/dist/agents/agents.controller.js +3 -2
  8. package/dist/agents/agents.service.d.ts +2 -0
  9. package/dist/agents/agents.service.js +7 -0
  10. package/dist/catalog/catalog.service.d.ts +2 -0
  11. package/dist/catalog/catalog.service.js +28 -5
  12. package/dist/catalog/marketplace-fetch.d.ts +2 -0
  13. package/dist/catalog/marketplace-fetch.js +15 -0
  14. package/dist/catalog/marketplaces.service.d.ts +4 -4
  15. package/dist/catalog/marketplaces.service.js +3 -2
  16. package/dist/catalog/owned-items.d.ts +2 -0
  17. package/dist/catalog/owned-items.js +30 -31
  18. package/dist/catalog/ownership.js +40 -38
  19. package/dist/catalog/plugin-import.d.ts +6 -5
  20. package/dist/catalog/plugin-import.js +69 -16
  21. package/dist/catalog/plugin-upgrade.d.ts +8 -0
  22. package/dist/catalog/plugin-upgrade.js +95 -7
  23. package/dist/catalog/publisher-policy.d.ts +9 -0
  24. package/dist/catalog/publisher-policy.js +12 -0
  25. package/dist/catalog/unshare.js +66 -58
  26. package/dist/client/client-access.service.js +5 -3
  27. package/dist/config/schema.d.ts +1 -0
  28. package/dist/config/schema.js +9 -1
  29. package/dist/conversations/conversations.controller.js +4 -14
  30. package/dist/conversations/conversations.service.d.ts +14 -0
  31. package/dist/conversations/conversations.service.js +20 -2
  32. package/dist/ctx/create-ctx.d.ts +14 -4
  33. package/dist/ctx/create-ctx.js +131 -59
  34. package/dist/ctx/queue.js +7 -4
  35. package/dist/db/extension-db.d.ts +30 -0
  36. package/dist/db/extension-db.js +91 -0
  37. package/dist/db/extension-rls-predicate.d.ts +1 -0
  38. package/dist/db/extension-rls-predicate.js +8 -0
  39. package/dist/db/extension-schema-transfer.d.ts +6 -0
  40. package/dist/db/extension-schema-transfer.js +141 -0
  41. package/dist/db/kernel-schema.d.ts +50 -4
  42. package/dist/db/migrator.d.ts +6 -0
  43. package/dist/db/migrator.js +35 -7
  44. package/dist/db/pool.d.ts +6 -2
  45. package/dist/db/pool.js +37 -2
  46. package/dist/db/sql-statements.d.ts +3 -0
  47. package/dist/db/sql-statements.js +15 -5
  48. package/dist/device-access/device-access.module.js +12 -2
  49. package/dist/device-access/device-access.service.d.ts +30 -2
  50. package/dist/device-access/device-access.service.js +38 -4
  51. package/dist/device-access/host-gate.d.ts +45 -0
  52. package/dist/device-access/host-gate.js +92 -0
  53. package/dist/device-access/host-service-stop-sweep.d.ts +33 -0
  54. package/dist/device-access/host-service-stop-sweep.js +112 -0
  55. package/dist/device-access/host-service-stop.d.ts +78 -0
  56. package/dist/device-access/host-service-stop.js +144 -0
  57. package/dist/device-access/host-services.d.ts +211 -0
  58. package/dist/device-access/host-services.js +803 -0
  59. package/dist/device-access/person-handles.d.ts +10 -0
  60. package/dist/device-access/person-handles.js +25 -0
  61. package/dist/device-access/service-events.d.ts +199 -0
  62. package/dist/device-access/service-events.js +704 -0
  63. package/dist/device-access/token.d.ts +5 -0
  64. package/dist/device-access/token.js +5 -0
  65. package/dist/devices/devices.service.js +3 -0
  66. package/dist/dial-in/access.d.ts +5 -5
  67. package/dist/dial-in/access.js +19 -12
  68. package/dist/dial-in/gateway.js +6 -2
  69. package/dist/dial-in/machines.d.ts +9 -2
  70. package/dist/dial-in/machines.js +27 -4
  71. package/dist/erasure/device-cleanup.js +12 -0
  72. package/dist/erasure/org-catalog.js +2 -2
  73. package/dist/erasure/org-rules.js +9 -0
  74. package/dist/errors.d.ts +2 -0
  75. package/dist/errors.js +2 -0
  76. package/dist/extensions/admin-ops.d.ts +3 -1
  77. package/dist/extensions/admin-ops.js +19 -9
  78. package/dist/extensions/deployed-snapshots.d.ts +4 -1
  79. package/dist/extensions/deployed-snapshots.js +7 -2
  80. package/dist/extensions/extensions.module.js +3 -0
  81. package/dist/extensions/host.d.ts +11 -3
  82. package/dist/extensions/host.js +40 -8
  83. package/dist/extensions/instance.d.ts +6 -0
  84. package/dist/extensions/instance.js +7 -1
  85. package/dist/extensions/ledger.d.ts +1 -1
  86. package/dist/extensions/lifecycle-hooks.js +3 -3
  87. package/dist/extensions/migrate-lock.d.ts +4 -1
  88. package/dist/extensions/migrate-lock.js +19 -2
  89. package/dist/extensions/org-config.js +6 -1
  90. package/dist/extensions/permission-set.d.ts +7 -0
  91. package/dist/extensions/permission-set.js +10 -0
  92. package/dist/extensions/permission-view.d.ts +1 -1
  93. package/dist/extensions/permission-view.js +10 -1
  94. package/dist/git/tickets.js +32 -27
  95. package/dist/http/app.js +5 -3
  96. package/dist/identity/accounts.d.ts +6 -1
  97. package/dist/identity/accounts.js +11 -2
  98. package/dist/identity/api-tokens.js +7 -6
  99. package/dist/identity/settings.d.ts +9 -1
  100. package/dist/identity/settings.js +16 -1
  101. package/dist/inbox/org-notices.js +3 -2
  102. package/dist/index.d.ts +1 -0
  103. package/dist/index.js +1 -0
  104. package/dist/infra/database/scoped-dialect.d.ts +3 -2
  105. package/dist/infra/database/scoped-dialect.js +260 -72
  106. package/dist/infra/database/startup-activation-transaction.d.ts +2 -0
  107. package/dist/infra/database/startup-activation-transaction.js +3 -2
  108. package/dist/infra/outbox/registry.d.ts +28 -14
  109. package/dist/infra/outbox/registry.js +30 -15
  110. package/dist/infra/queue/queue-names.d.ts +1 -1
  111. package/dist/infra/queue/queue-names.js +1 -0
  112. package/dist/infra/queue/run-job.d.ts +4 -1
  113. package/dist/infra/queue/run-job.js +10 -2
  114. package/dist/kernel.js +4 -0
  115. package/dist/kernel.module.js +3 -0
  116. package/dist/lifecycle/kernel-lifecycle.d.ts +3 -1
  117. package/dist/lifecycle/kernel-lifecycle.js +26 -21
  118. package/dist/orgs/offboarding.js +18 -9
  119. package/dist/orgs/settings.service.js +3 -0
  120. package/dist/packages/npm-publish-keys.json +27 -0
  121. package/dist/packages/official-publisher.d.ts +19 -0
  122. package/dist/packages/official-publisher.js +152 -0
  123. package/dist/packages/provenance.d.ts +7 -0
  124. package/dist/packages/provenance.js +22 -19
  125. package/dist/packages/sigstore-trusted-root.json +126 -0
  126. package/dist/platform/ops/admin.ops.js +2 -1
  127. package/dist/platform/ops/orgs.ops.js +1 -0
  128. package/dist/roles/worker-role.d.ts +6 -3
  129. package/dist/roles/worker-role.js +12 -4
  130. package/dist/roles/worker.module.js +7 -6
  131. package/dist/runtime/maintenance.d.ts +5 -4
  132. package/dist/runtime/maintenance.js +16 -13
  133. package/dist/sandbox/device-reports.d.ts +4 -4
  134. package/dist/sandbox/device-reports.js +40 -30
  135. package/dist/sandbox/device-services.d.ts +2 -1
  136. package/dist/sandbox/device-services.js +5 -1
  137. package/dist/sandbox/permission-ceiling-writes.d.ts +8 -0
  138. package/dist/sandbox/permission-ceiling-writes.js +21 -0
  139. package/dist/sandbox/permission-config-publication.js +5 -1
  140. package/dist/themes/theme-state.js +24 -13
  141. package/dist/tools/call-scope.d.ts +6 -0
  142. package/dist/tools/call-scope.js +22 -0
  143. package/dist/tools/registry.js +20 -2
  144. package/dist/ui/views.js +36 -8
  145. package/package.json +9 -4
  146. package/src/migrations/0219_event_org_constraint_check.sql +29 -0
  147. package/src/migrations/0220_require_event_org.sql +18 -0
  148. package/src/migrations/0221_drop_connector_declaration_policy.sql +2 -0
  149. package/src/migrations/0222_device_host_services.sql +27 -0
  150. package/src/migrations/0223_device_service_events.sql +54 -0
  151. package/src/migrations/0224_cache_conversation_rls_settings.sql +33 -0
  152. package/dist/conversations/event-org-backfill.d.ts +0 -111
  153. package/dist/conversations/event-org-backfill.js +0 -264
  154. package/dist/conversations/event-org-backfill.module.d.ts +0 -3
  155. package/dist/conversations/event-org-backfill.module.js +0 -18
@@ -64,7 +64,8 @@ export declare class DeviceServices {
64
64
  * Starts the service in the device, or finds it running (the provider keeps a running one).
65
65
  * With `ifRunning` it never starts one: a stopped service answers its `stopped` status, and the
66
66
  * provider gets only the name ({@link nameOnlySpec}), as with every ifRunning ensure. A spec
67
- * breaking {@link serviceSpecIssue} is refused before the device is touched.
67
+ * breaking {@link serviceSpecIssue}, or a host spec (`host` set: `host_not_declared`), is refused
68
+ * before the device is touched.
68
69
  */
69
70
  ensure(use: SandboxUseContext, spec: DeviceServiceSpec, signal: AbortSignal, opts?: {
70
71
  ifRunning?: boolean;
@@ -113,10 +113,14 @@ let DeviceServices = class DeviceServices {
113
113
  * Starts the service in the device, or finds it running (the provider keeps a running one).
114
114
  * With `ifRunning` it never starts one: a stopped service answers its `stopped` status, and the
115
115
  * provider gets only the name ({@link nameOnlySpec}), as with every ifRunning ensure. A spec
116
- * breaking {@link serviceSpecIssue} is refused before the device is touched.
116
+ * breaking {@link serviceSpecIssue}, or a host spec (`host` set: `host_not_declared`), is refused
117
+ * before the device is touched.
117
118
  */
118
119
  async ensure(use, spec, signal, opts = {}) {
119
120
  assertServiceSpec(spec);
121
+ // a host service starts only through its own admission (`HostServiceAccess`), never here
122
+ if (spec.host !== undefined)
123
+ throw new DeviceAccessError("host_not_declared", `The device service spec ${spec.name} sets host: a host service starts only through ensureHostService.`);
120
124
  return this.sandbox.withDeviceServices(use, requireServices, (h, p, sig) => {
121
125
  const ensure = p.ensureService;
122
126
  // read under the use and the set lock, so a grant committed before it is in the set
@@ -22,6 +22,14 @@ export declare class PermissionCeilingWrites {
22
22
  /** The platform writer excludes every descendant; only these environments changed Full reach. */
23
23
  invalidateDeviceConsentUnderPlatform(deviceIds: readonly string[], platformProfiles?: readonly PermissionProfile[]): Promise<void>;
24
24
  publishLocked(subject: AuthoritySubject, level: "platform" | "org" | "device" | "root", revoke?: boolean | ((scope: SandboxOperationScope | SandboxBrowseScope, row: Selectable<SandboxOperationIntentsTable>) => boolean), invalidateFullConsent?: boolean, refreshStartedServices?: boolean, platformProfiles?: readonly PermissionProfile[]): Promise<void>;
25
+ /**
26
+ * The host gate closed under the subject (local agents spec, call 1: a platform or org project
27
+ * reach cap narrowed below `machine`, or running outside the sandbox switched off there): every
28
+ * host service under it, a whole-machine escalation, is owed a stop in the writer's transaction,
29
+ * under the writer's exclusive lock of its level. The host gate refuses new ones once it
30
+ * commits, and its admission reads under the shared authority locks (`HostServiceGate.admit`).
31
+ */
32
+ oweHostServiceStopsLocked(subject: AuthoritySubject, level: "platform" | "org"): Promise<void>;
25
33
  /** Full access consent only grows where the org inherits the widened platform reach. */
26
34
  invalidateProjectReachWideningLocked(before: DeviceProjectReach, after: DeviceProjectReach, platformProfiles?: readonly PermissionProfile[]): Promise<void>;
27
35
  /** Selected profiles removed by an org or platform ceiling reset before the writer commits. */
@@ -10,6 +10,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
10
10
  import { narrowerProjectReach, } from "@capybara-hq/plugin-sdk";
11
11
  import { Inject, Injectable, Optional } from "@nestjs/common";
12
12
  import { sql } from "kysely";
13
+ import { oweHostServicesStop } from "../device-access/host-service-stop.js";
13
14
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
14
15
  import { KernelDb } from "../infra/database/kernel-db.js";
15
16
  import { asPlatform } from "../infra/database/org-scope.js";
@@ -122,6 +123,11 @@ let PermissionCeilingWrites = class PermissionCeilingWrites {
122
123
  rootConversationId: subject.rootConversationId,
123
124
  }),
124
125
  }, `c${level}-${id}-${epoch}`, refreshStartedServices);
126
+ // a project reach narrowed at the platform or the org (the writers pass it as
127
+ // `refreshStartedServices`) leaves it below `machine` for every device under the subject,
128
+ // which closes the host gate there
129
+ if (refreshStartedServices && (level === "platform" || level === "org"))
130
+ await this.oweHostServiceStopsLocked(subject, level);
125
131
  if (!revoke)
126
132
  return;
127
133
  // Acknowledged background starts stay revocable by every actual revoking writer (deletion is
@@ -170,6 +176,18 @@ let PermissionCeilingWrites = class PermissionCeilingWrites {
170
176
  });
171
177
  }
172
178
  }
179
+ /**
180
+ * The host gate closed under the subject (local agents spec, call 1: a platform or org project
181
+ * reach cap narrowed below `machine`, or running outside the sandbox switched off there): every
182
+ * host service under it, a whole-machine escalation, is owed a stop in the writer's transaction,
183
+ * under the writer's exclusive lock of its level. The host gate refuses new ones once it
184
+ * commits, and its admission reads under the shared authority locks (`HostServiceGate.admit`).
185
+ */
186
+ async oweHostServiceStopsLocked(subject, level) {
187
+ const orgId = level === "org" ? required(subject.orgId) : undefined;
188
+ this.locks.assertHeld(level, orgId ?? "platform", true);
189
+ await oweHostServicesStop(this.db.db, this.outbox, orgId === undefined ? {} : { orgId });
190
+ }
173
191
  /** Full access consent only grows where the org inherits the widened platform reach. */
174
192
  async invalidateProjectReachWideningLocked(before, after, platformProfiles) {
175
193
  if (narrowerProjectReach(before, after) === after)
@@ -293,6 +311,9 @@ __decorate([
293
311
  __decorate([
294
312
  Transactional({ propagation: "mandatory" })
295
313
  ], PermissionCeilingWrites.prototype, "publishLocked", null);
314
+ __decorate([
315
+ Transactional({ propagation: "mandatory" })
316
+ ], PermissionCeilingWrites.prototype, "oweHostServiceStopsLocked", null);
296
317
  __decorate([
297
318
  Transactional({ propagation: "mandatory" })
298
319
  ], PermissionCeilingWrites.prototype, "invalidateProjectReachWideningLocked", null);
@@ -159,10 +159,11 @@ let PermissionConfigPublication = class PermissionConfigPublication {
159
159
  const projection = permissionConfigProjection(this.config.get());
160
160
  const initialize = () => this.initializeLocked(projection, options.activation);
161
161
  if (options.startup) {
162
- const { url, connectTimeoutMs } = this.config.get().db;
162
+ const { url, connectTimeoutMs, rls } = this.config.get().db;
163
163
  return this.txHost.runStartupActivation(initialize, {
164
164
  connectionString: url,
165
165
  connectTimeoutMs,
166
+ rls,
166
167
  ...options.startup,
167
168
  });
168
169
  }
@@ -315,6 +316,9 @@ let PermissionConfigPublication = class PermissionConfigPublication {
315
316
  },
316
317
  // only a widening resets Full consent: a narrowing keeps what the consent covered
317
318
  (beforeMode === "off" && nextMode === "allowed") || networkWidened || hostsWidened, reachTightened, nextView.allowedProfiles.value);
319
+ // running outside the sandbox switched off closes the host gate on every device
320
+ if (beforeMode !== "off" && nextMode === "off")
321
+ await this.ceilings.oweHostServiceStopsLocked({}, "platform");
318
322
  if (beforeReach !== nextReach && !reachTightened)
319
323
  await this.ceilings.invalidateProjectReachWideningLocked(beforeReach, nextReach, nextView.allowedProfiles.value);
320
324
  return "activated";
@@ -3,8 +3,9 @@
3
3
  // transaction's connection when there is one): the settings writers (deployment, org, person) and
4
4
  // `ThemesService` decide with the same predicates.
5
5
  import { BUILTIN_AVATAR_PRESET_IDS, isThemeAssetPath, mergeThemeSchemes, } from "@capybara-hq/plugin-sdk";
6
- import { componentOn, listedIn, loadComponents, loadScopeState, pluginFactsOf, switchOf, } from "../catalog/component-state.js";
6
+ import { componentOn, listedIn, loadComponents, loadScopeState, platformBuiltin, pluginFactsOf, switchOf, } from "../catalog/component-state.js";
7
7
  import { ApiError } from "../errors.js";
8
+ import { asPlatform, withOrgScope } from "../infra/database/org-scope.js";
8
9
  import { packagePath } from "../packages/tgz.js";
9
10
  import { THEME_PRESET_KEY_RE } from "./avatar-preset-key.js";
10
11
  /** The schemes in the order they are listed. */
@@ -161,10 +162,9 @@ export async function themesOnIn(db, orgId) {
161
162
  * plugin live and not disabled, and its effective scope `all` (its own, or its plugin's when it
162
163
  * follows; a builtin plugin is `all`).
163
164
  */
164
- function platformDefaultEligible(st, c) {
165
+ function platformDefaultEligible(c, p) {
165
166
  if (c.ownerOrgId !== null || c.disabled)
166
167
  return false;
167
- const p = c.itemId === null ? undefined : st.plugins.get(c.itemId);
168
168
  if (c.itemId !== null && (p === undefined || p.disabled))
169
169
  return false;
170
170
  if (c.scopeMode === "own")
@@ -176,8 +176,17 @@ export async function eligiblePlatformDefault(db, id) {
176
176
  const [c] = await loadComponents(db, "theme", { ids: [id] });
177
177
  if (!c)
178
178
  return null;
179
- const st = await loadScopeState(db, "theme", [c]);
180
- return platformDefaultEligible(st, c) ? c : null;
179
+ // The public theme read needs only catalog metadata. Per-org availability is checked on writes.
180
+ const item = c.itemId === null
181
+ ? undefined
182
+ : await db
183
+ .selectFrom("catalog_items")
184
+ .select(["scope", "builtin", "disabled", "owner_org_id"])
185
+ .where("id", "=", c.itemId)
186
+ .where("deleted_at", "is", null)
187
+ .executeTakeFirst();
188
+ const plugin = item && { ...item, builtin: platformBuiltin(item) };
189
+ return platformDefaultEligible(c, plugin) ? c : null;
181
190
  }
182
191
  /**
183
192
  * 400 `theme.not_available`: theme `id` cannot be chosen where it was set; `orgs`: the live orgs
@@ -220,7 +229,8 @@ export async function lockThemeShared(db, id) {
220
229
  export async function assertPlatformDefaultEligible(db, id) {
221
230
  const [c] = await loadComponents(db, "theme", { ids: [id] });
222
231
  const st = c && (await loadScopeState(db, "theme", [c]));
223
- if (!c || !st || !platformDefaultEligible(st, c)) {
232
+ const plugin = c?.itemId == null ? undefined : st?.plugins.get(c.itemId);
233
+ if (!c || !st || !platformDefaultEligible(c, plugin)) {
224
234
  throw themeNotAvailable(id, "as the platform default (a platform theme whose scope is all)");
225
235
  }
226
236
  const orgs = await db
@@ -254,18 +264,19 @@ export async function themeOnIn(db, orgId, id) {
254
264
  }
255
265
  /** Whether theme `id` is on in at least one of the person's live orgs. */
256
266
  export async function themeOnForAccount(db, accountId, id) {
257
- const orgs = await db
267
+ // org-filter: deployment-wide lookup of the authenticated account's live memberships.
268
+ const orgs = await asPlatform("Resolve the account's orgs for a personal theme", () => db
258
269
  .selectFrom("memberships as m")
259
270
  .innerJoin("orgs as o", "o.id", "m.org_id")
260
271
  .select("m.org_id")
261
272
  .where("m.account_id", "=", accountId)
262
273
  .where("o.deleted_at", "is", null)
263
- .execute();
264
- const [c] = await loadComponents(db, "theme", { ids: [id] });
265
- if (!c || orgs.length === 0)
266
- return false;
267
- const st = await loadScopeState(db, "theme", [c]);
268
- return orgs.some((o) => onIn(st, c, o.org_id));
274
+ .execute());
275
+ for (const { org_id: orgId } of orgs) {
276
+ if (await withOrgScope(orgId, () => themeOnIn(db, orgId, id)))
277
+ return true;
278
+ }
279
+ return false;
269
280
  }
270
281
  /**
271
282
  * Refuses (400 `theme.not_available`) a person's pick that is on in none of their live orgs (the
@@ -92,6 +92,12 @@ export declare function attachCallScope(ctx: ToolCallContext, facts?: CallFacts,
92
92
  }): CallScope;
93
93
  /** The call's scope, or null for a context the pipeline did not make (no scope attached). */
94
94
  export declare function callScopeOf(ctx: ToolCallContext): CallScope | null;
95
+ /** Marks `ctx` live while the kernel runs its handler ({@link isLiveCall}). */
96
+ export declare function markCallLive(ctx: ToolCallContext): void;
97
+ /** Ends the live mark of `ctx`: its handler settled, or the kernel gave up on it. */
98
+ export declare function endCall(ctx: ToolCallContext): void;
99
+ /** Whether `ctx` is a call context the kernel issued and whose handler is running now. */
100
+ export declare function isLiveCall(ctx: unknown): boolean;
95
101
  /**
96
102
  * Runs `fn` as a device start of the call ({@link CallScope.starting}); a context without a scope
97
103
  * runs it as it is.
@@ -28,6 +28,28 @@ export function attachCallScope(ctx, facts, opts = {}) {
28
28
  export function callScopeOf(ctx) {
29
29
  return ctx[CALL_SCOPE] ?? null;
30
30
  }
31
+ /**
32
+ * The tool call contexts whose extension handler (or watcher) the kernel is running now: the tool
33
+ * registry marks the very object it passes to the extension before the call and ends the mark
34
+ * when the handler settles or the kernel gives up on it (its signal aborts); each watcher run of a
35
+ * watched wait gets its own mark the same way. A
36
+ * copy of a context (`{ ...call }`), one kept past its handler, or one built from strings is not
37
+ * live. Host device services admit a tool scope only for a live call. A `WeakSet` keyed by the
38
+ * object: per call and per process, like the scope itself.
39
+ */
40
+ const liveCalls = new WeakSet();
41
+ /** Marks `ctx` live while the kernel runs its handler ({@link isLiveCall}). */
42
+ export function markCallLive(ctx) {
43
+ liveCalls.add(ctx);
44
+ }
45
+ /** Ends the live mark of `ctx`: its handler settled, or the kernel gave up on it. */
46
+ export function endCall(ctx) {
47
+ liveCalls.delete(ctx);
48
+ }
49
+ /** Whether `ctx` is a call context the kernel issued and whose handler is running now. */
50
+ export function isLiveCall(ctx) {
51
+ return typeof ctx === "object" && ctx !== null && liveCalls.has(ctx);
52
+ }
31
53
  /**
32
54
  * Runs `fn` as a device start of the call ({@link CallScope.starting}); a context without a scope
33
55
  * runs it as it is.
@@ -24,6 +24,7 @@ import { resolveRoster } from "../runtime/subagents/roster.js";
24
24
  import { AGENT_BUILTIN_NAMES, AGENT_TOOL, BASH_COMPANION_TOOLS, BUILTIN, SEND_MESSAGE, SKILL_LOAD, SUBAGENT_HANDBACK, TOOL_SEARCH, } from "./builtin-names.js";
25
25
  import { agentToolSpec } from "./builtins/agent.js";
26
26
  import { BuiltinTools } from "./builtins/builtin-tools.js";
27
+ import { endCall, markCallLive } from "./call-scope.js";
27
28
  import { canonicalJson } from "./canonical-json.js";
28
29
  import { connectorSetups } from "./connector-setup.js";
29
30
  import { Credentials } from "./credentials.js";
@@ -201,7 +202,7 @@ let ToolRegistry = class ToolRegistry {
201
202
  .find((x) => x.plugin === source.plugin && x.spec.name === source.name);
202
203
  if (!t)
203
204
  return undefined;
204
- return (input, ctx) => t.inflight.run(ctx.signal, (signal) => t.handler(input, { ...ctx, signal }));
205
+ return (input, ctx) => t.inflight.run(ctx.signal, (signal) => whileLive({ ...ctx, signal }, (call) => t.handler(input, call)));
205
206
  }
206
207
  return undefined;
207
208
  }
@@ -219,7 +220,7 @@ let ToolRegistry = class ToolRegistry {
219
220
  const watch = t?.watch;
220
221
  if (t === undefined || watch === undefined)
221
222
  return undefined;
222
- return (ctx) => t.inflight.run(ctx.signal, (signal) => watch({ ...ctx, signal }));
223
+ return (ctx) => t.inflight.run(ctx.signal, (signal) => whileLive({ ...ctx, signal }, (call) => watch(call)));
223
224
  }
224
225
  /** The registered builtin tools' specs (display metadata for `tools/info.ts`). */
225
226
  builtinSpecs() {
@@ -688,3 +689,20 @@ export function filterSubagentTools(tools, filter) {
688
689
  const keep = (key) => !deny.has(key) && (allow === null || allow.has(key));
689
690
  return tools.filter((t) => (companions.has(t.key) ? keep(BUILTIN.Bash) : keep(t.key)));
690
691
  }
692
+ /**
693
+ * Runs an extension's handler (or watcher) with `call` live ({@link markCallLive}): the very
694
+ * object the extension receives, until the handler settles or the kernel gives up on it (its
695
+ * signal aborts, as on a timeout or a stop).
696
+ */
697
+ async function whileLive(call, fn) {
698
+ markCallLive(call);
699
+ const end = () => endCall(call);
700
+ call.signal.addEventListener("abort", end, { once: true });
701
+ try {
702
+ return await fn(call);
703
+ }
704
+ finally {
705
+ call.signal.removeEventListener("abort", end);
706
+ endCall(call);
707
+ }
708
+ }
package/dist/ui/views.js CHANGED
@@ -12,6 +12,7 @@ import { Inject, Injectable } from "@nestjs/common";
12
12
  import { sql } from "kysely";
13
13
  import { isAgentVisibleIn } from "../agents/agent-lookup.js";
14
14
  import { ConversationsService } from "../conversations/conversations.service.js";
15
+ import { issuePersonHandle, revokePersonHandle } from "../device-access/person-handles.js";
15
16
  import { ApiError } from "../errors.js";
16
17
  import { EffectiveConfigs, NEEDS_CONFIG_REASON } from "../extensions/effective-config.js";
17
18
  import { ExtensionHost } from "../extensions/host.js";
@@ -446,13 +447,23 @@ let UiViews = class UiViews {
446
447
  throw new ApiError("validation_failed", `payload must be at most ${UI_LIMITS.payloadBytes} bytes as JSON`);
447
448
  }
448
449
  const action = entry.action;
449
- const r = await this.call(t, "action", (signal) => action({
450
- ...args,
451
- signal,
452
- actionId: input.actionId,
453
- ...(input.payload !== undefined && { payload: input.payload }),
454
- ...(input.answer !== undefined && { answer: input.answer }),
455
- }));
450
+ // an org action runs for its person: a kernel-issued handle, live only while it runs
451
+ const person = args.scope === "platform" ? undefined : issuePersonHandle(args.orgId, args.accountId);
452
+ let r;
453
+ try {
454
+ r = await this.call(t, "action", (signal) => action({
455
+ ...args,
456
+ signal,
457
+ actionId: input.actionId,
458
+ ...(person !== undefined && { person }),
459
+ ...(input.payload !== undefined && { payload: input.payload }),
460
+ ...(input.answer !== undefined && { answer: input.answer }),
461
+ }));
462
+ }
463
+ finally {
464
+ if (person !== undefined)
465
+ revokePersonHandle(person);
466
+ }
456
467
  const component = entry.contribution.kind === "component";
457
468
  this.check(t, "action", actionResultProblems(r, component));
458
469
  const res = r;
@@ -499,7 +510,24 @@ let UiViews = class UiViews {
499
510
  failCode: "ui.query_failed",
500
511
  timeoutCode: "ui.query_timeout",
501
512
  failMessage: `Plugin ${t.plugin} failed to answer query ${input.query} of ${t.id}`,
502
- fn: (signal) => handler({ ...resolved.args, query: input.query, params, signal }),
513
+ fn: async (signal) => {
514
+ const a = resolved.args;
515
+ // an org query runs for its person: a kernel-issued handle, live only while it runs
516
+ const person = a.scope === "platform" ? undefined : issuePersonHandle(a.orgId, a.accountId);
517
+ try {
518
+ return await handler({
519
+ ...a,
520
+ query: input.query,
521
+ params,
522
+ signal,
523
+ ...(person !== undefined && { person }),
524
+ });
525
+ }
526
+ finally {
527
+ if (person !== undefined)
528
+ revokePersonHandle(person);
529
+ }
530
+ },
503
531
  });
504
532
  let json;
505
533
  try {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capybara-hq/kernel",
3
- "version": "0.1.0-rc.131",
3
+ "version": "0.1.0-rc.133",
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": {
@@ -11,7 +11,7 @@
11
11
  "homepage": "https://github.com/capybara-hq/core/tree/main/packages/kernel#readme",
12
12
  "type": "module",
13
13
  "engines": {
14
- "node": ">=24"
14
+ "node": "^24.15.0 || >=26.0.0"
15
15
  },
16
16
  "main": "./dist/index.js",
17
17
  "types": "./dist/index.d.ts",
@@ -45,6 +45,9 @@
45
45
  "@nestjs/terminus": "12.1.0",
46
46
  "@nestjs/throttler": "6.7.1",
47
47
  "@opentelemetry/api": "1.9.1",
48
+ "@sigstore/bundle": "^5.0.1",
49
+ "@sigstore/protobuf-specs": "^0.5.2",
50
+ "@sigstore/verify": "^4.1.4",
48
51
  "ajv": "^8.20.0",
49
52
  "bullmq": "^6.3.15",
50
53
  "cron": "4.4.0",
@@ -67,17 +70,19 @@
67
70
  "yaml": "^2.9.1",
68
71
  "yauzl": "3.4.0",
69
72
  "zod": "^4.6.7",
70
- "@capybara-hq/plugin-sdk": "^0.1.0-rc.97"
73
+ "@capybara-hq/plugin-sdk": "^0.1.0-rc.98"
71
74
  },
72
75
  "devDependencies": {
73
76
  "@langchain/langgraph-checkpoint-validation": "^1.2.0",
74
77
  "@opentelemetry/sdk-metrics": "2.12.0",
75
78
  "@types/pg": "^8.23.1",
79
+ "@types/pg-cursor": "^2.7.2",
76
80
  "@types/semver": "^7.8.0",
77
81
  "@types/ws": "^8.18.2",
78
82
  "@types/yauzl": "3.4.0",
83
+ "pg-cursor": "^2.22.1",
79
84
  "ws": "^8.22.0",
80
- "@capybara-hq/testing": "0.1.0-rc.53"
85
+ "@capybara-hq/testing": "0.1.0-rc.54"
81
86
  },
82
87
  "scripts": {
83
88
  "build": "tsc -b"
@@ -0,0 +1,29 @@
1
+ -- Run after the 0215 writers have fully rolled out and the event backfill has finished.
2
+ -- capybara:allow-destructive report a pending backfill and add the temporary check once; no data is changed
3
+ DO $$
4
+ BEGIN
5
+ IF EXISTS (SELECT 1 FROM conversation_events WHERE org_id IS NULL) THEN
6
+ RAISE EXCEPTION 'conversation_events still contains NULL org_id values. Wait for EventOrgBackfillJob to finish on the previous release before rerunning the migration.';
7
+ END IF;
8
+ END
9
+ $$;
10
+
11
+ -- Validate under SHARE UPDATE EXCLUSIVE before adding the check takes ACCESS EXCLUSIVE.
12
+ ALTER TABLE conversation_events VALIDATE CONSTRAINT conversation_events_conversation_org_fkey;
13
+
14
+ -- capybara:allow-destructive add the temporary check idempotently after validating the foreign key
15
+ DO $$
16
+ BEGIN
17
+ IF NOT EXISTS (
18
+ SELECT 1 FROM pg_attribute
19
+ WHERE attrelid = 'conversation_events'::regclass AND attname = 'org_id' AND attnotnull
20
+ ) AND NOT EXISTS (
21
+ SELECT 1 FROM pg_constraint
22
+ WHERE conrelid = 'conversation_events'::regclass
23
+ AND conname = 'conversation_events_org_id_present'
24
+ ) THEN
25
+ ALTER TABLE conversation_events
26
+ ADD CONSTRAINT conversation_events_org_id_present CHECK (org_id IS NOT NULL) NOT VALID;
27
+ END IF;
28
+ END
29
+ $$;
@@ -0,0 +1,18 @@
1
+ -- Migration 0219 committed the temporary CHECK. Validate it under SHARE UPDATE EXCLUSIVE
2
+ -- so the scan permits ordinary reads and writes.
3
+ -- capybara:allow-destructive skip check validation on reapplication after the temporary check was removed
4
+ DO $$
5
+ BEGIN
6
+ IF NOT EXISTS (
7
+ SELECT 1 FROM pg_attribute
8
+ WHERE attrelid = 'conversation_events'::regclass AND attname = 'org_id' AND attnotnull
9
+ ) THEN
10
+ ALTER TABLE conversation_events VALIDATE CONSTRAINT conversation_events_org_id_present;
11
+ END IF;
12
+ END
13
+ $$;
14
+
15
+ -- The validated CHECK proves there are no NULLs, so SET NOT NULL takes ACCESS EXCLUSIVE
16
+ -- without scanning the table. Drop the check in a separate statement to preserve that proof.
17
+ ALTER TABLE conversation_events ALTER COLUMN org_id SET NOT NULL;
18
+ ALTER TABLE conversation_events DROP CONSTRAINT IF EXISTS conversation_events_org_id_present;
@@ -0,0 +1,2 @@
1
+ -- capybara:allow-destructive migration 0213 moved connector defaults into default_policy; replicas that read declaration_policy have drained (#1246)
2
+ ALTER TABLE connector_tools DROP COLUMN IF EXISTS declaration_policy;
@@ -0,0 +1,27 @@
1
+ -- Host device services running, or being started, on a person's personal machine (local agents
2
+ -- spec, Part 1): one row per (device, extension, service), written before the machine is asked to
3
+ -- start it (intent first) and deleted once a stop is confirmed. stop_owed_at marks a stop the
4
+ -- kernel owes (the extension was switched off, the host gate closed, or the device or its person
5
+ -- went): kept until the machine confirms the stop, so a machine offline at the time gets it when
6
+ -- it connects again.
7
+ CREATE TABLE IF NOT EXISTS device_host_services (
8
+ org_id text NOT NULL REFERENCES orgs(id) ON DELETE CASCADE,
9
+ device_id text NOT NULL REFERENCES devices(id) ON DELETE CASCADE,
10
+ extension text NOT NULL,
11
+ service text NOT NULL,
12
+ digest text,
13
+ started_at timestamptz,
14
+ stop_owed_at timestamptz,
15
+ created_at timestamptz NOT NULL DEFAULT now(),
16
+ PRIMARY KEY (device_id, extension, service)
17
+ );
18
+
19
+ CREATE INDEX IF NOT EXISTS device_host_services_extension_idx
20
+ ON device_host_services (extension, org_id);
21
+
22
+ CREATE INDEX IF NOT EXISTS device_host_services_owed_idx
23
+ ON device_host_services (device_id)
24
+ WHERE stop_owed_at IS NOT NULL;
25
+
26
+ DROP POLICY IF EXISTS org_scope ON device_host_services;
27
+ CREATE POLICY org_scope ON device_host_services USING (rls_admits(org_id)) WITH CHECK (rls_admits(org_id));
@@ -0,0 +1,54 @@
1
+ -- Device service events (local agents spec, Part 1): an event a host service on a personal
2
+ -- machine emitted, stored when its provider reports it (`ctx.devices.serviceEvent`) and delivered
3
+ -- to the extension's `ctx.deviceAccess.onServiceEvent` handler by an outbox-owed queue job, at
4
+ -- least once, in seq order per (device, extension, service). The seq is the device's numbering
5
+ -- (from 1, per device and service); a second report of the same seq is the same row. delivered_at is set once the handler resolved
6
+ -- (or the event was dropped); delivered rows are deleted after 7 days by a sweep. stalled_at notes
7
+ -- that the sweep found the event first in line and undelivered for too long and owed its delivery
8
+ -- again (logged once per stall).
9
+ CREATE TABLE IF NOT EXISTS device_service_events (
10
+ org_id text NOT NULL REFERENCES orgs(id) ON DELETE CASCADE,
11
+ device_id text NOT NULL REFERENCES devices(id) ON DELETE CASCADE,
12
+ extension text NOT NULL,
13
+ service text NOT NULL,
14
+ seq bigint NOT NULL,
15
+ body bytea NOT NULL,
16
+ created_at timestamptz NOT NULL DEFAULT now(),
17
+ delivered_at timestamptz,
18
+ stalled_at timestamptz,
19
+ PRIMARY KEY (device_id, extension, service, seq)
20
+ );
21
+
22
+ -- the deliveries' read: a service's undelivered events in seq order
23
+ CREATE INDEX IF NOT EXISTS device_service_events_undelivered_idx
24
+ ON device_service_events (device_id, extension, service, seq)
25
+ WHERE delivered_at IS NULL;
26
+
27
+ -- the stall scan: undelivered events by age
28
+ CREATE INDEX IF NOT EXISTS device_service_events_stall_idx
29
+ ON device_service_events (created_at)
30
+ WHERE delivered_at IS NULL;
31
+
32
+ -- the sweep: delivered events by age
33
+ CREATE INDEX IF NOT EXISTS device_service_events_delivered_idx
34
+ ON device_service_events (delivered_at)
35
+ WHERE delivered_at IS NOT NULL;
36
+
37
+ DROP POLICY IF EXISTS org_scope ON device_service_events;
38
+ CREATE POLICY org_scope ON device_service_events USING (rls_admits(org_id)) WITH CHECK (rls_admits(org_id));
39
+
40
+ -- The delivery cursor of each (device, extension, service): the last seq delivered (seqs start at 1
41
+ -- and rise by 1, numbered by the device), moved with GREATEST in the transaction that marks an
42
+ -- event delivered. Never swept: one row per service on a device, so a quiet service keeps its place.
43
+ CREATE TABLE IF NOT EXISTS device_service_event_cursors (
44
+ org_id text NOT NULL REFERENCES orgs(id) ON DELETE CASCADE,
45
+ device_id text NOT NULL REFERENCES devices(id) ON DELETE CASCADE,
46
+ extension text NOT NULL,
47
+ service text NOT NULL,
48
+ delivered_seq bigint NOT NULL,
49
+ updated_at timestamptz NOT NULL DEFAULT now(),
50
+ PRIMARY KEY (device_id, extension, service)
51
+ );
52
+
53
+ DROP POLICY IF EXISTS org_scope ON device_service_event_cursors;
54
+ CREATE POLICY org_scope ON device_service_event_cursors USING (rls_admits(org_id)) WITH CHECK (rls_admits(org_id));
@@ -0,0 +1,33 @@
1
+ -- Factor the 0182 predicate so policies can read the settings once per statement.
2
+ CREATE OR REPLACE FUNCTION rls_scope_unrestricted() RETURNS boolean
3
+ LANGUAGE sql STABLE PARALLEL SAFE AS $$
4
+ SELECT coalesce(pg_catalog.current_setting('capybara.rls', true), '') <> 'enforce'
5
+ OR pg_catalog.current_setting('capybara.scope', true) = 'platform'
6
+ $$;
7
+
8
+ CREATE OR REPLACE FUNCTION rls_admits(row_org text, unrestricted boolean, scope_org text)
9
+ RETURNS boolean LANGUAGE sql STABLE PARALLEL SAFE AS $$
10
+ SELECT unrestricted OR row_org = scope_org
11
+ $$;
12
+
13
+ CREATE OR REPLACE FUNCTION rls_admits(row_org text) RETURNS boolean
14
+ LANGUAGE sql STABLE PARALLEL SAFE AS $$
15
+ SELECT capybara.rls_admits(row_org, capybara.rls_scope_unrestricted(),
16
+ pg_catalog.current_setting('capybara.org_id', true))
17
+ $$;
18
+
19
+ -- The uncorrelated settings reads stay in the policy so PostgreSQL can inline the predicate
20
+ -- and evaluate the setting lookups as InitPlans. ALTER POLICY does not scan the table.
21
+ SET LOCAL lock_timeout = '2s';
22
+
23
+ ALTER POLICY org_scope ON conversations
24
+ USING (rls_admits(org_id, (SELECT rls_scope_unrestricted()),
25
+ (SELECT pg_catalog.current_setting('capybara.org_id', true))))
26
+ WITH CHECK (rls_admits(org_id, (SELECT rls_scope_unrestricted()),
27
+ (SELECT pg_catalog.current_setting('capybara.org_id', true))));
28
+
29
+ ALTER POLICY org_scope ON conversation_events
30
+ USING (rls_admits(org_id, (SELECT rls_scope_unrestricted()),
31
+ (SELECT pg_catalog.current_setting('capybara.org_id', true))))
32
+ WITH CHECK (rls_admits(org_id, (SELECT rls_scope_unrestricted()),
33
+ (SELECT pg_catalog.current_setting('capybara.org_id', true))));