@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
@@ -111,20 +111,6 @@ export declare const OUTBOX_JOBS: {
111
111
  readonly removeOnFail: true;
112
112
  };
113
113
  };
114
- readonly "conversation-events-org-backfill": {
115
- readonly queue: "cap-kernel-maintenance";
116
- readonly idempotent: "Locks up to 5,000 NULL org_id rows after its (conversation_id, seq) cursor with FOR UPDATE SKIP LOCKED and fills each from its conversation's org_id; rows already filled are skipped and the next batch is owed atomically under a deterministic cursor job id";
117
- readonly processedIn: "packages/kernel/src/runtime/maintenance.ts";
118
- readonly opts: {
119
- readonly attempts: 5;
120
- readonly backoff: {
121
- readonly type: "exponential";
122
- readonly delay: 5000;
123
- };
124
- readonly removeOnComplete: true;
125
- readonly removeOnFail: true;
126
- };
127
- };
128
114
  readonly "file-release": {
129
115
  readonly queue: "cap-kernel-maintenance";
130
116
  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";
@@ -584,6 +570,34 @@ export declare const OUTBOX_JOBS: {
584
570
  readonly removeOnFail: true;
585
571
  };
586
572
  };
573
+ readonly "device-host-services-stop": {
574
+ readonly queue: "cap-kernel-maintenance";
575
+ readonly idempotent: "Stops the extension's host services on the devices that started one; stopping a service that is not running is a no-op";
576
+ readonly processedIn: "packages/kernel/src/runtime/maintenance.ts";
577
+ readonly opts: {
578
+ readonly attempts: 10;
579
+ readonly backoff: {
580
+ readonly type: "exponential";
581
+ readonly delay: 5000;
582
+ };
583
+ readonly removeOnComplete: true;
584
+ readonly removeOnFail: true;
585
+ };
586
+ };
587
+ readonly "device-service-events": {
588
+ readonly queue: "cap-device-service-events";
589
+ readonly idempotent: "the delivery takes the service's lock and hands on only rows not yet marked delivered, in seq order, marking each once its handler resolved; a repeat finds them delivered (handlers get each event at least once)";
590
+ readonly processedIn: "packages/kernel/src/device-access/service-events.ts";
591
+ readonly opts: {
592
+ readonly attempts: 10;
593
+ readonly backoff: {
594
+ readonly type: "exponential";
595
+ readonly delay: 2000;
596
+ };
597
+ readonly removeOnComplete: true;
598
+ readonly removeOnFail: true;
599
+ };
600
+ };
587
601
  readonly "hook-run-lifecycle": {
588
602
  readonly queue: "cap-kernel-lifecycle";
589
603
  readonly idempotent: "the `run.lifecycle` handler sets a display state keyed by the run and phase (the SDK contract: handlers are idempotent); the job id is deterministic per run, phase and wait";
@@ -98,21 +98,6 @@ export const OUTBOX_JOBS = {
98
98
  removeOnFail: true,
99
99
  },
100
100
  },
101
- // `conversations/event-org-backfill.ts` EVENT_ORG_BACKFILL_JOB: batched backfill of
102
- // `conversation_events.org_id` from `conversations`, owed by the periodic kickoff under
103
- // `eventOrgBackfillJobId(null)` and chained per 5,000-row batch under `eventOrgBackfillJobId(last)`
104
- "conversation-events-org-backfill": {
105
- queue: "cap-kernel-maintenance",
106
- idempotent: "Locks up to 5,000 NULL org_id rows after its (conversation_id, seq) cursor with FOR UPDATE SKIP LOCKED and fills each from its conversation's org_id; rows already filled are skipped and the next batch is owed atomically under a deterministic cursor job id",
107
- processedIn: "packages/kernel/src/runtime/maintenance.ts",
108
- // removed either way, so a later kickoff during a rolling deploy can owe the first batch again
109
- opts: {
110
- attempts: 5,
111
- backoff: { type: "exponential", delay: 5_000 },
112
- removeOnComplete: true,
113
- removeOnFail: true,
114
- },
115
- },
116
101
  // `files/blob-objects.ts` FILE_RELEASE_JOB: owed, deferred, by every discard and draft cleanup
117
102
  // of an upload, under `fileReleaseJobId`
118
103
  "file-release": {
@@ -527,6 +512,36 @@ export const OUTBOX_JOBS = {
527
512
  removeOnFail: true,
528
513
  },
529
514
  },
515
+ // `device-access/host-service-stop.ts` HOST_SERVICES_STOP_JOB: owed by the transaction that
516
+ // switches an extension off in an org (`OrgExtensionConfigs`) or on the deployment
517
+ // (`ExtensionAdminOps`), under `hostServicesStopJobId` (local agents spec, call 5)
518
+ "device-host-services-stop": {
519
+ queue: "cap-kernel-maintenance",
520
+ idempotent: "Stops the extension's host services on the devices that started one; stopping a service that is not running is a no-op",
521
+ processedIn: "packages/kernel/src/runtime/maintenance.ts",
522
+ opts: {
523
+ attempts: 10,
524
+ backoff: { type: "exponential", delay: 5_000 },
525
+ removeOnComplete: true,
526
+ removeOnFail: true,
527
+ },
528
+ },
529
+ // `device-access/service-events.ts` SERVICE_EVENTS_JOB: owed by the transaction that stores a
530
+ // device service event (`ServiceEvents.record`, local agents spec Part 1), under
531
+ // `serviceEventsJobId` (one per event)
532
+ "device-service-events": {
533
+ queue: "cap-device-service-events",
534
+ idempotent: "the delivery takes the service's lock and hands on only rows not yet marked delivered, in seq order, marking each once its handler resolved; a repeat finds them delivered (handlers get each event at least once)",
535
+ processedIn: "packages/kernel/src/device-access/service-events.ts",
536
+ // 10 attempts from 2 s, doubling (about 17 min in all); removed once done, so the same event
537
+ // reported again owes a job that is not deduped away
538
+ opts: {
539
+ attempts: 10,
540
+ backoff: { type: "exponential", delay: 2_000 },
541
+ removeOnComplete: true,
542
+ removeOnFail: true,
543
+ },
544
+ },
530
545
  // `extensions/run-lifecycle-owe.ts` RUN_LIFECYCLE_JOB: owed by the transaction that starts a
531
546
  // run, suspends it on a person, resumes it, ends it (finished, failed, aborted) or declines,
532
547
  // expires or gives up on directed work, once per phase of a run (and wait) and plugin
@@ -4,5 +4,5 @@
4
4
  * (admin/health.service.ts) lists the same names from the feature constants;
5
5
  * test/infra/queue-names.test.ts keeps the two equal.
6
6
  */
7
- export declare const KERNEL_QUEUES: readonly ["cap-kernel-runs", "cap-kernel-subagent-runs", "cap-kernel-channels", "cap-kernel-maintenance", "cap-kernel-tool-watch", "cap-kernel-plugin-scope", "cap-kernel-titles", "cap-kernel-suggestions", "cap-kernel-usage-report", "cap-kernel-evals", "cap-kernel-lifecycle", "cap-push-deliver", "cap-connector-tools", "cap-template-connectors"];
7
+ export declare const KERNEL_QUEUES: readonly ["cap-kernel-runs", "cap-kernel-subagent-runs", "cap-kernel-channels", "cap-kernel-maintenance", "cap-kernel-tool-watch", "cap-kernel-plugin-scope", "cap-kernel-titles", "cap-kernel-suggestions", "cap-kernel-usage-report", "cap-kernel-evals", "cap-kernel-lifecycle", "cap-push-deliver", "cap-connector-tools", "cap-template-connectors", "cap-device-service-events"];
8
8
  export type KernelQueueName = (typeof KERNEL_QUEUES)[number];
@@ -19,4 +19,5 @@ export const KERNEL_QUEUES = [
19
19
  "cap-push-deliver",
20
20
  "cap-connector-tools",
21
21
  "cap-template-connectors",
22
+ "cap-device-service-events",
22
23
  ];
@@ -1,4 +1,5 @@
1
1
  import { type ContextJob } from "../../log-context.js";
2
+ import { type OrgScope } from "../database/org-scope.js";
2
3
  /**
3
4
  * The wrapper every queue processor runs its job in: a fresh async context (no transaction of
4
5
  * whoever enqueued the job or started the worker is visible), `queue` / `jobId` / `runId` in the
@@ -6,7 +7,8 @@ import { type ContextJob } from "../../log-context.js";
6
7
  * §5.3, §10) is the job's org when its data carries a string `orgId`; else the platform scope when
7
8
  * the queue's work is deployment-wide (`opts.platform`, the reason); else none, never inherited
8
9
  * from whoever started the worker (a missing org fails closed once RLS is enforced, and the
9
- * unscoped-query check reports it).
10
+ * unscoped-query check reports it). An explicit `opts.scope` overrides payload inference, with
11
+ * `null` selecting no scope.
10
12
  *
11
13
  * ```ts
12
14
  * @Processor("cap-kernel-titles")
@@ -19,4 +21,5 @@ import { type ContextJob } from "../../log-context.js";
19
21
  */
20
22
  export declare function runJob<T>(queue: string, job: ContextJob, fn: () => Promise<T>, opts?: {
21
23
  platform?: string;
24
+ scope?: OrgScope | null;
22
25
  }): Promise<T>;
@@ -8,7 +8,8 @@ import { runOutsideTransaction } from "../database/transaction-host.js";
8
8
  * §5.3, §10) is the job's org when its data carries a string `orgId`; else the platform scope when
9
9
  * the queue's work is deployment-wide (`opts.platform`, the reason); else none, never inherited
10
10
  * from whoever started the worker (a missing org fails closed once RLS is enforced, and the
11
- * unscoped-query check reports it).
11
+ * unscoped-query check reports it). An explicit `opts.scope` overrides payload inference, with
12
+ * `null` selecting no scope.
12
13
  *
13
14
  * ```ts
14
15
  * @Processor("cap-kernel-titles")
@@ -20,9 +21,16 @@ import { runOutsideTransaction } from "../database/transaction-host.js";
20
21
  * ```
21
22
  */
22
23
  export function runJob(queue, job, fn, opts = {}) {
23
- const orgId = job.data?.orgId;
24
24
  const run = () => withJobContext(queue, job, fn);
25
25
  return runOutsideTransaction(() => {
26
+ if (opts.scope !== undefined) {
27
+ if (opts.scope?.kind === "org")
28
+ return withOrgScope(opts.scope.orgId, run);
29
+ if (opts.scope?.kind === "platform")
30
+ return asPlatform(opts.scope.reason, run);
31
+ return withoutOrgScope(run);
32
+ }
33
+ const orgId = job.data?.orgId;
26
34
  if (typeof orgId === "string" && orgId !== "")
27
35
  return withOrgScope(orgId, run);
28
36
  if (opts.platform !== undefined)
package/dist/kernel.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { fileURLToPath } from "node:url";
2
+ import { extensionDbIdentity } from "./db/extension-db.js";
2
3
  import { canMigrateKernel, migrate, verifyMigrations } from "./db/migrator.js";
3
4
  import { createDb } from "./db/pool.js";
4
5
  import { ExtensionHost } from "./extensions/host.js";
@@ -49,6 +50,9 @@ export async function migrateAll(config, opts = {}) {
49
50
  });
50
51
  const plugins = await ExtensionHost.migrateOnly(config.extensions, {
51
52
  dbUrl: config.db.url,
53
+ ...(config.db.extensionsUrl !== undefined && {
54
+ extensionIdentity: extensionDbIdentity(config.db),
55
+ }),
52
56
  connectTimeoutMs,
53
57
  autoApprove: config.extensionPermissions.autoApprove,
54
58
  ...(opts.resolveFrom !== undefined && { resolveFrom: opts.resolveFrom }),
@@ -14,6 +14,7 @@ import { ClientModule } from "./client/client.module.js";
14
14
  import { PromptSuggestionsModule } from "./conversations/prompt-suggestions.js";
15
15
  import { TitlesModule } from "./conversations/titles.js";
16
16
  import { ExtensionDeviceAccessModule } from "./device-access/device-access.module.js";
17
+ import { DeviceServiceEventsModule } from "./device-access/service-events.js";
17
18
  import { BootstrapDefaultsService } from "./extensions/bootstrap-defaults.js";
18
19
  import { ExtensionsModule } from "./extensions/extensions.module.js";
19
20
  import { ApiModule } from "./http/api.module.js";
@@ -134,6 +135,8 @@ let KernelModule = KernelModule_1 = class KernelModule {
134
135
  ClientModule,
135
136
  // ctx.deviceAccess: extensions' device services (the host finds it at the time of use)
136
137
  ExtensionDeviceAccessModule,
138
+ // ctx.devices.serviceEvent: host service events (the host finds it at the time of use)
139
+ DeviceServiceEventsModule,
137
140
  // ctx.triggers: the events extensions emit (the host finds it at the time of use)
138
141
  TriggerEventsModule,
139
142
  // ctx.inbox: personal inbox items extensions post (the host finds it at the time of use)
@@ -10,6 +10,7 @@ import { ChannelJobs } from "../channels/jobs.js";
10
10
  import { ChannelOutbound } from "../channels/outbound.js";
11
11
  import { PromptSuggestionQueue } from "../conversations/prompt-suggestions.js";
12
12
  import { TitleQueue } from "../conversations/titles.js";
13
+ import { type ExtensionDbIdentity } from "../db/extension-db.js";
13
14
  import { ExtensionBlobs } from "../extensions/blobs.js";
14
15
  import { BootstrapService } from "../extensions/bootstrap.js";
15
16
  import { BootstrapDefaultsService } from "../extensions/bootstrap-defaults.js";
@@ -76,6 +77,7 @@ export declare class KernelLifecycle implements OnApplicationBootstrap, BeforeAp
76
77
  private readonly kdb;
77
78
  private readonly shutdown;
78
79
  private readonly host;
80
+ private readonly extensionDbIdentity;
79
81
  private readonly registry;
80
82
  private readonly installs;
81
83
  private readonly blobs;
@@ -111,7 +113,7 @@ export declare class KernelLifecycle implements OnApplicationBootstrap, BeforeAp
111
113
  private bootstrapPackages;
112
114
  /** The merged bootstrap manifest, read once per start. */
113
115
  private mergedManifest;
114
- constructor(permissionConfig: PermissionConfigPublication, accounts: AccountsService, configService: KernelConfigService, log: KernelLogger, options: KernelAppOptions, pool: Kysely<any>, redis: Redis, kdb: KernelDb, shutdown: GracefulShutdown, host: ExtensionHost, registry: ExtensionRegistry, installs: ExtensionInstalls, blobs: ExtensionBlobs, extensionLifecycle: ExtensionLifecycle, replicaStatus: ReplicaStatusStore, bootstrap: BootstrapService, bootstrapDefaults: BootstrapDefaultsService, marketplaces: MarketplacesService, pluginImport: PluginImport, pluginUpdater: PlatformPluginUpdater, bus: Pick<ExtensionContext["bus"], "publish" | "subscribe">, usageReport: UsageReporter, titles: TitleQueue, suggestions: PromptSuggestionQueue, channelJobs: ChannelJobs, channelOutbound: ChannelOutbound, presence: ReplicaPresence, worker?: WorkerRole | undefined, gateway?: GatewayRole | undefined);
116
+ constructor(permissionConfig: PermissionConfigPublication, accounts: AccountsService, configService: KernelConfigService, log: KernelLogger, options: KernelAppOptions, pool: Kysely<any>, redis: Redis, kdb: KernelDb, shutdown: GracefulShutdown, host: ExtensionHost, extensionDbIdentity: ExtensionDbIdentity, registry: ExtensionRegistry, installs: ExtensionInstalls, blobs: ExtensionBlobs, extensionLifecycle: ExtensionLifecycle, replicaStatus: ReplicaStatusStore, bootstrap: BootstrapService, bootstrapDefaults: BootstrapDefaultsService, marketplaces: MarketplacesService, pluginImport: PluginImport, pluginUpdater: PlatformPluginUpdater, bus: Pick<ExtensionContext["bus"], "publish" | "subscribe">, usageReport: UsageReporter, titles: TitleQueue, suggestions: PromptSuggestionQueue, channelJobs: ChannelJobs, channelOutbound: ChannelOutbound, presence: ReplicaPresence, worker?: WorkerRole | undefined, gateway?: GatewayRole | undefined);
115
117
  /** The kernel HTTP application (set up by `buildKernelApp` before `init()`). */
116
118
  get http(): KernelHttpApp;
117
119
  attachHttp(http: KernelHttpApp): void;
@@ -17,6 +17,7 @@ import { ChannelJobs } from "../channels/jobs.js";
17
17
  import { ChannelOutbound } from "../channels/outbound.js";
18
18
  import { PromptSuggestionQueue } from "../conversations/prompt-suggestions.js";
19
19
  import { TitleQueue } from "../conversations/titles.js";
20
+ import { ConfiguredExtensionDbIdentity } from "../db/extension-db.js";
20
21
  import { ExtensionBlobs } from "../extensions/blobs.js";
21
22
  import { BootstrapFailedError, BootstrapService, } from "../extensions/bootstrap.js";
22
23
  import { BootstrapDefaultsService } from "../extensions/bootstrap-defaults.js";
@@ -98,6 +99,7 @@ let KernelLifecycle = class KernelLifecycle {
98
99
  kdb;
99
100
  shutdown;
100
101
  host;
102
+ extensionDbIdentity;
101
103
  registry;
102
104
  installs;
103
105
  blobs;
@@ -135,7 +137,7 @@ let KernelLifecycle = class KernelLifecycle {
135
137
  mergedManifest;
136
138
  constructor(permissionConfig, accounts, configService, log, options,
137
139
  // biome-ignore lint/suspicious/noExplicitAny: the pool carries no schema types
138
- pool, redis, kdb, shutdown, host, registry, installs, blobs, extensionLifecycle, replicaStatus, bootstrap, bootstrapDefaults, marketplaces, pluginImport, pluginUpdater, bus,
140
+ pool, redis, kdb, shutdown, host, extensionDbIdentity, registry, installs, blobs, extensionLifecycle, replicaStatus, bootstrap, bootstrapDefaults, marketplaces, pluginImport, pluginUpdater, bus,
139
141
  // the producers closed on every role (their consumers are the worker role's)
140
142
  usageReport, titles, suggestions, channelJobs, channelOutbound,
141
143
  // this process's presence beat, on every role (admin overview spec §5.1)
@@ -153,6 +155,7 @@ let KernelLifecycle = class KernelLifecycle {
153
155
  this.kdb = kdb;
154
156
  this.shutdown = shutdown;
155
157
  this.host = host;
158
+ this.extensionDbIdentity = extensionDbIdentity;
156
159
  this.registry = registry;
157
160
  this.installs = installs;
158
161
  this.blobs = blobs;
@@ -294,6 +297,7 @@ let KernelLifecycle = class KernelLifecycle {
294
297
  : ensureMigrated({
295
298
  db: this.kdb.db,
296
299
  dbUrl: config.db.url,
300
+ extensionDb: this.extensionDbIdentity.resolve(d.name),
297
301
  connectTimeoutMs: config.db.connectTimeoutMs,
298
302
  bus: this.bus,
299
303
  log: this.log,
@@ -572,26 +576,27 @@ KernelLifecycle = __decorate([
572
576
  __param(7, Inject(KernelDb)),
573
577
  __param(8, Inject(GracefulShutdown)),
574
578
  __param(9, Inject(ExtensionHost)),
575
- __param(10, Inject(ExtensionRegistry)),
576
- __param(11, Inject(ExtensionInstalls)),
577
- __param(12, Inject(ExtensionBlobs)),
578
- __param(13, Inject(ExtensionLifecycle)),
579
- __param(14, Inject(ReplicaStatusStore)),
580
- __param(15, Inject(BootstrapService)),
581
- __param(16, Inject(BootstrapDefaultsService)),
582
- __param(17, Inject(MarketplacesService)),
583
- __param(18, Inject(PluginImport)),
584
- __param(19, Inject(PlatformPluginUpdater)),
585
- __param(20, Inject(KERNEL_BUS)),
586
- __param(21, Inject(UsageReporter)),
587
- __param(22, Inject(TitleQueue)),
588
- __param(23, Inject(PromptSuggestionQueue)),
589
- __param(24, Inject(ChannelJobs)),
590
- __param(25, Inject(ChannelOutbound)),
591
- __param(26, Inject(ReplicaPresence)),
592
- __param(27, Optional()),
593
- __param(27, Inject(WorkerRole)),
579
+ __param(10, Inject(ConfiguredExtensionDbIdentity)),
580
+ __param(11, Inject(ExtensionRegistry)),
581
+ __param(12, Inject(ExtensionInstalls)),
582
+ __param(13, Inject(ExtensionBlobs)),
583
+ __param(14, Inject(ExtensionLifecycle)),
584
+ __param(15, Inject(ReplicaStatusStore)),
585
+ __param(16, Inject(BootstrapService)),
586
+ __param(17, Inject(BootstrapDefaultsService)),
587
+ __param(18, Inject(MarketplacesService)),
588
+ __param(19, Inject(PluginImport)),
589
+ __param(20, Inject(PlatformPluginUpdater)),
590
+ __param(21, Inject(KERNEL_BUS)),
591
+ __param(22, Inject(UsageReporter)),
592
+ __param(23, Inject(TitleQueue)),
593
+ __param(24, Inject(PromptSuggestionQueue)),
594
+ __param(25, Inject(ChannelJobs)),
595
+ __param(26, Inject(ChannelOutbound)),
596
+ __param(27, Inject(ReplicaPresence)),
594
597
  __param(28, Optional()),
595
- __param(28, Inject(GatewayRole))
598
+ __param(28, Inject(WorkerRole)),
599
+ __param(29, Optional()),
600
+ __param(29, Inject(GatewayRole))
596
601
  ], KernelLifecycle);
597
602
  export { KernelLifecycle };
@@ -13,6 +13,7 @@ import { sql } from "kysely";
13
13
  import { retargetSetupRequests } from "../agents/pending-connector-requests.js";
14
14
  import { EventLog } from "../conversations/event-log.js";
15
15
  import { lockConversationTrees } from "../conversations/tree.js";
16
+ import { oweHostServicesStopOnDevices } from "../device-access/host-service-stop.js";
16
17
  import { revokeSiteGrantsOfDevice } from "../device-access/site-grants.js";
17
18
  import { ApiError } from "../errors.js";
18
19
  import { enabledExtensionsQuery } from "../extensions/enabled.js";
@@ -21,6 +22,7 @@ import { ExtensionRegistry } from "../extensions/registry.js";
21
22
  import { audit } from "../identity/audit.js";
22
23
  import { SessionService } from "../identity/sessions.js";
23
24
  import { KernelDb } from "../infra/database/kernel-db.js";
25
+ import { asPlatform } from "../infra/database/org-scope.js";
24
26
  import { TransactionHost } from "../infra/database/transaction-host.js";
25
27
  import { Transactional } from "../infra/database/transactional.decorator.js";
26
28
  import { OutboxService } from "../infra/outbox/outbox.service.js";
@@ -199,16 +201,18 @@ let Offboarding = class Offboarding {
199
201
  .returning("id")
200
202
  .execute()
201
203
  : [];
202
- // org-filter: removal revokes the person's personal tokens account-wide on purpose (comment above)
203
204
  const tokens = revoke
204
- ? await this.db
205
- .updateTable("api_tokens")
206
- .set({ revoked_at: sql `now()` })
207
- .where("kind", "=", "personal")
208
- .where("account_id", "=", accountId)
209
- .where("revoked_at", "is", null)
210
- .returning("id")
211
- .execute()
205
+ ? await asPlatform("Revoke account-wide personal tokens after member removal", () => {
206
+ // org-filter: personal tokens belong to the account and have a null org_id.
207
+ return this.db
208
+ .updateTable("api_tokens")
209
+ .set({ revoked_at: sql `now()` })
210
+ .where("kind", "=", "personal")
211
+ .where("account_id", "=", accountId)
212
+ .where("revoked_at", "is", null)
213
+ .returning("id")
214
+ .execute();
215
+ })
212
216
  : [];
213
217
  // a registration follows its session (push plan decision 3)
214
218
  await deletePushRegistrationsForSessions(this.db.db, sessions.map((r) => r.id));
@@ -320,6 +324,11 @@ let Offboarding = class Offboarding {
320
324
  await revokeLoopbackGrantsOfDevice(this.db.db, this.outbox, { orgId, deviceId: d.id });
321
325
  await revokeSiteGrantsOfDevice(this.db.db, { orgId, deviceId: d.id });
322
326
  }
327
+ // the person's host services in the org end with their devices (local agents spec, call 5)
328
+ await oweHostServicesStopOnDevices(this.db.db, this.outbox, {
329
+ orgId,
330
+ deviceIds: devices.map((d) => d.id),
331
+ });
323
332
  await this.db
324
333
  .deleteFrom("device_defaults")
325
334
  .where("org_id", "=", orgId)
@@ -940,6 +940,9 @@ let OrgSettingsService = class OrgSettingsService {
940
940
  return after.outsideSandbox === "off";
941
941
  return hostsNarrowed(scope, row, orgHosts, (host) => hostGrantable(grantCeiling, host));
942
942
  }, resetConsent);
943
+ // running outside the sandbox switched off closes the host gate on the org's devices
944
+ if (effOutside(before) === "allowed" && effOutside(reread) === "off")
945
+ await this.ceilings.oweHostServiceStopsLocked({ orgId }, "org");
943
946
  }
944
947
  return after;
945
948
  }
@@ -0,0 +1,27 @@
1
+ {
2
+ "keys": [
3
+ {
4
+ "keyId": "SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA",
5
+ "keyUsage": "npm:attestations",
6
+ "publicKey": {
7
+ "rawBytes": "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE1Olb3zMAFFxXKHiIkQO5cJ3Yhl5i6UPp+IhuteBJbuHcA5UogKo0EWtlWwW6KSaKoTNEYL7JlCQiVnkhBktUgg==",
8
+ "keyDetails": "PKIX_ECDSA_P256_SHA_256",
9
+ "validFor": {
10
+ "start": "2022-12-01T00:00:00.000Z",
11
+ "end": "2025-01-29T00:00:00.000Z"
12
+ }
13
+ }
14
+ },
15
+ {
16
+ "keyId": "SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U",
17
+ "keyUsage": "npm:attestations",
18
+ "publicKey": {
19
+ "rawBytes": "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEY6Ya7W++7aUPzvMTrezH6Ycx3c+HOKYCcNGybJZSCJq/fd7Qa8uuAKtdIkUQtQiEKERhAmE5lMMJhP8OkDOa2g==",
20
+ "keyDetails": "PKIX_ECDSA_P256_SHA_256",
21
+ "validFor": {
22
+ "start": "2025-01-13T00:00:00.000Z"
23
+ }
24
+ }
25
+ }
26
+ ]
27
+ }
@@ -0,0 +1,19 @@
1
+ import type { NpmFetchConfig } from "./npm.js";
2
+ import { type Provenance } from "./provenance.js";
3
+ declare const POLICY_VERSION = 1;
4
+ export interface OfficialNpmRevision {
5
+ name: string;
6
+ version: string;
7
+ /** SHA-512 already checked against the fetched artifact bytes. */
8
+ integrity: string;
9
+ }
10
+ export interface OfficialPublisherProof extends Provenance {
11
+ revision: OfficialNpmRevision;
12
+ evidenceDigest: string;
13
+ policyVersion: typeof POLICY_VERSION;
14
+ }
15
+ /** Checks both signatures, transparency evidence and publisher identity with the bundled roots. */
16
+ export declare function verifyOfficialPublisher(body: unknown, revision: OfficialNpmRevision): OfficialPublisherProof;
17
+ /** Uses the same bounded registry client as the review's display-only provenance. */
18
+ export declare function fetchOfficialPublisher(cfg: NpmFetchConfig, revision: OfficialNpmRevision, signal?: AbortSignal): Promise<OfficialPublisherProof>;
19
+ export {};
@@ -0,0 +1,152 @@
1
+ import { createHash } from "node:crypto";
2
+ import { bundleFromJSON } from "@sigstore/bundle";
3
+ import { PublicKey, TrustedRoot } from "@sigstore/protobuf-specs";
4
+ import { toSignedEntity, toTrustMaterial, Verifier } from "@sigstore/verify";
5
+ import { z } from "zod";
6
+ import { canonicalJson } from "../tools/canonical-json.js";
7
+ import npmPublishKeys from "./npm-publish-keys.json" with { type: "json" };
8
+ import { fetchNpmAttestations, PROVENANCE_TIMEOUT_MS, SLSA_PROVENANCE_V1, sha512Hex, } from "./provenance.js";
9
+ import trustedRoot from "./sigstore-trusted-root.json" with { type: "json" };
10
+ const NPM_PUBLISH = "https://github.com/npm/attestation/tree/main/specs/publish/v0.1";
11
+ const REGISTRY = "https://registry.npmjs.org";
12
+ const REPOSITORY = "https://github.com/capybara-hq/plugins";
13
+ const REPOSITORY_ID = "1436732755";
14
+ const OWNER_ID = "343699164";
15
+ const WORKFLOW = ".github/workflows/release.yml";
16
+ const MAIN_REF = "refs/heads/main";
17
+ const WORKFLOW_IDENTITY = [REPOSITORY, "/", WORKFLOW, "@", MAIN_REF].join("");
18
+ const GITHUB_ISSUER = "https://token.actions.githubusercontent.com";
19
+ const BUILD_TYPE = "https://slsa-framework.github.io/github-actions-buildtypes/workflow/v1";
20
+ const POLICY_VERSION = 1;
21
+ // These two files are Sigstore production TUF targets: trusted_root.json and
22
+ // registry.npmjs.org/keys.json (publish keys only). Refresh them from the authenticated
23
+ // TUF repository during review. Verification receives no trust material from the registry.
24
+ const verifier = new Verifier(toTrustMaterial(TrustedRoot.fromJSON(trustedRoot), Object.fromEntries(npmPublishKeys.keys.map((key) => [key.keyId, PublicKey.fromJSON(key.publicKey)]))));
25
+ const attestationsSchema = z.object({
26
+ attestations: z.array(z.object({ predicateType: z.string(), bundle: z.unknown() })).max(16),
27
+ });
28
+ const statementSchema = z.object({
29
+ _type: z.enum(["https://in-toto.io/Statement/v1", "https://in-toto.io/Statement/v0.1"]),
30
+ predicateType: z.string(),
31
+ subject: z
32
+ .array(z.object({ name: z.string(), digest: z.object({ sha512: z.string() }) }))
33
+ .length(1),
34
+ predicate: z.unknown(),
35
+ });
36
+ const buildSchema = z.object({
37
+ buildDefinition: z.object({
38
+ buildType: z.literal(BUILD_TYPE),
39
+ externalParameters: z.object({
40
+ workflow: z.object({
41
+ repository: z.literal(REPOSITORY),
42
+ path: z.literal(WORKFLOW),
43
+ ref: z.literal(MAIN_REF),
44
+ }),
45
+ }),
46
+ internalParameters: z.object({
47
+ github: z.object({
48
+ repository_id: z.literal(REPOSITORY_ID),
49
+ repository_owner_id: z.literal(OWNER_ID),
50
+ }),
51
+ }),
52
+ resolvedDependencies: z
53
+ .array(z.object({ digest: z.object({ gitCommit: z.string().regex(/^[0-9a-f]{40}$/) }) }))
54
+ .min(1),
55
+ }),
56
+ });
57
+ const publishSchema = z.object({
58
+ name: z.string(),
59
+ version: z.string(),
60
+ registry: z.literal(REGISTRY),
61
+ });
62
+ function checkEnvelope(raw, type, revision) {
63
+ const bundle = bundleFromJSON(raw);
64
+ if (bundle.content.$case !== "dsseEnvelope" ||
65
+ bundle.content.dsseEnvelope.payloadType !== "application/vnd.in-toto+json") {
66
+ throw new Error("Expected an in-toto DSSE bundle");
67
+ }
68
+ const entity = toSignedEntity(bundle);
69
+ if (!entity.tlogEntries.some((entry) => entry.inclusionProof !== undefined)) {
70
+ throw new Error("The attestation has no transparency log inclusion proof");
71
+ }
72
+ const statement = statementSchema.parse(JSON.parse(bundle.content.dsseEnvelope.payload.toString("utf8")));
73
+ const [subject] = statement.subject;
74
+ const digest = sha512Hex(revision.integrity);
75
+ const packageUrl = ["pkg:npm/", revision.name.replace(/^@/, "%40"), "@", revision.version].join("");
76
+ if (!digest ||
77
+ statement.predicateType !== type ||
78
+ (type === SLSA_PROVENANCE_V1 && statement._type !== "https://in-toto.io/Statement/v1") ||
79
+ subject?.name !== packageUrl ||
80
+ subject.digest.sha512 !== digest) {
81
+ throw new Error("The attestation does not match this package, version and SHA-512");
82
+ }
83
+ return { entity, predicate: statement.predicate };
84
+ }
85
+ function verifyBuildSigner(entity) {
86
+ if (entity.key.$case !== "certificate") {
87
+ throw new Error("The build attestation has no signing certificate");
88
+ }
89
+ const cert = entity.key.certificate;
90
+ const signer = verifier.verify(entity, { extensions: { issuer: GITHUB_ISSUER } });
91
+ // Fulcio extensions sign these GitHub OIDC claims independently of the predicate.
92
+ const claim = (oid) => cert.extension(`1.3.6.1.4.1.57264.1.${oid}`)?.valueObj.subs[0]?.value.toString("utf8");
93
+ if (claim(14) !== MAIN_REF || !claim(9)?.endsWith(`/${WORKFLOW}@${MAIN_REF}`)) {
94
+ throw new Error("The signing certificate does not match the official release workflow or main ref");
95
+ }
96
+ if (signer.identity?.subjectAlternativeName !== WORKFLOW_IDENTITY ||
97
+ claim(9) !== WORKFLOW_IDENTITY ||
98
+ claim(12) !== REPOSITORY ||
99
+ claim(15) !== REPOSITORY_ID ||
100
+ claim(17) !== OWNER_ID) {
101
+ throw new Error("The signing certificate does not match the official repository identity");
102
+ }
103
+ const commit = claim(13);
104
+ if (!commit)
105
+ throw new Error("The signing certificate names no source commit");
106
+ return commit;
107
+ }
108
+ /** Checks both signatures, transparency evidence and publisher identity with the bundled roots. */
109
+ export function verifyOfficialPublisher(body, revision) {
110
+ const { attestations } = attestationsSchema.parse(body);
111
+ const [publish, ...duplicatePublish] = attestations.filter((a) => a.predicateType === NPM_PUBLISH);
112
+ const [build, ...duplicateBuild] = attestations.filter((a) => a.predicateType === SLSA_PROVENANCE_V1);
113
+ if (!publish || !build || duplicatePublish.length || duplicateBuild.length) {
114
+ throw new Error("Expected one registry publish attestation and one workflow attestation");
115
+ }
116
+ const published = checkEnvelope(publish.bundle, NPM_PUBLISH, revision);
117
+ if (published.entity.key.$case !== "public-key") {
118
+ throw new Error("The publish attestation must be signed by an npm registry key");
119
+ }
120
+ const info = publishSchema.parse(published.predicate);
121
+ if (info.name !== revision.name || info.version !== revision.version) {
122
+ throw new Error("The npm registry attested a different package revision");
123
+ }
124
+ verifier.verify(published.entity);
125
+ const built = checkEnvelope(build.bundle, SLSA_PROVENANCE_V1, revision);
126
+ const commit = verifyBuildSigner(built.entity);
127
+ const [source] = buildSchema.parse(built.predicate).buildDefinition.resolvedDependencies;
128
+ if (source?.digest.gitCommit !== commit) {
129
+ throw new Error("The signing certificate does not match the build's source commit");
130
+ }
131
+ if (!/^@capybara-hq\/plugin-[a-z0-9][a-z0-9-]*$/.test(revision.name)) {
132
+ throw new Error("An official plugin must belong to the Capybara npm namespace");
133
+ }
134
+ return {
135
+ checked: true,
136
+ revision,
137
+ repository: REPOSITORY,
138
+ commit,
139
+ workflow: WORKFLOW,
140
+ buildType: BUILD_TYPE,
141
+ evidenceDigest: createHash("sha256")
142
+ .update(canonicalJson([publish.bundle, build.bundle]))
143
+ .digest("hex"),
144
+ policyVersion: POLICY_VERSION,
145
+ };
146
+ }
147
+ /** Uses the same bounded registry client as the review's display-only provenance. */
148
+ export async function fetchOfficialPublisher(cfg, revision, signal) {
149
+ const timeout = AbortSignal.timeout(PROVENANCE_TIMEOUT_MS);
150
+ const attestations = await fetchNpmAttestations(cfg, revision.name, revision.version, signal ? AbortSignal.any([signal, timeout]) : timeout);
151
+ return verifyOfficialPublisher(attestations, revision);
152
+ }
@@ -21,17 +21,22 @@ export interface Provenance {
21
21
  workflow: string;
22
22
  /** The SLSA build type (which CI system's build definition). */
23
23
  buildType: string;
24
+ /** Present only when the official publisher attestations were verified. */
25
+ evidenceDigest?: string;
24
26
  }
25
27
  /** Provenance was not checked (no attestation, offline, or an answer that could not be read). */
26
28
  export interface ProvenanceNotChecked {
27
29
  checked: false;
28
30
  reason: string;
31
+ reasonCode?: "official_pin_only";
29
32
  }
30
33
  export type ProvenanceResult = Provenance | ProvenanceNotChecked;
31
34
  /** The predicate type of an SLSA v1 provenance statement. */
32
35
  export declare const SLSA_PROVENANCE_V1 = "https://slsa.dev/provenance/v1";
33
36
  /** Provenance must not hold up an import: a slow registry gives "not checked". */
34
37
  export declare const PROVENANCE_TIMEOUT_MS = 15000;
38
+ /** The hex sha512 of a `sha512-<base64>` integrity (undefined for anything else). */
39
+ export declare function sha512Hex(integrity: string): string | undefined;
35
40
  /**
36
41
  * Reads the SLSA provenance of `name@version` from the configured registry. `integrity` (the
37
42
  * tarball's `sha512-…`, when known) must be among the statement's subject digests, so a statement
@@ -40,6 +45,8 @@ export declare const PROVENANCE_TIMEOUT_MS = 15000;
40
45
  export declare function fetchProvenance(cfg: NpmFetchConfig, name: string, version: string, signal: AbortSignal, opts?: {
41
46
  integrity?: string;
42
47
  }): Promise<ProvenanceResult>;
48
+ /** Fetches bounded attestation evidence without accepting it as publisher proof. */
49
+ export declare function fetchNpmAttestations(cfg: NpmFetchConfig, name: string, version: string, signal: AbortSignal): Promise<unknown>;
43
50
  /**
44
51
  * Parses an attestations answer (`{ attestations: [{ predicateType, bundle: { dsseEnvelope } }] }`).
45
52
  * Exported for tests.