@capybara-hq/kernel 0.1.0-rc.74 → 0.1.0-rc.76

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 (94) hide show
  1. package/bootstrap.json +3 -3
  2. package/dist/agents/readiness.controller.d.ts +4 -3
  3. package/dist/agents/readiness.controller.js +4 -3
  4. package/dist/agents/readiness.service.d.ts +44 -11
  5. package/dist/agents/readiness.service.js +59 -16
  6. package/dist/catalog/catalog-import.module.d.ts +1 -1
  7. package/dist/catalog/catalog-import.module.js +1 -1
  8. package/dist/catalog/cli.d.ts +9 -2
  9. package/dist/catalog/cli.js +10 -4
  10. package/dist/catalog/marketplaces.service.d.ts +1 -1
  11. package/dist/catalog/plugin-upgrade.d.ts +4 -2
  12. package/dist/catalog/plugin-upgrade.js +9 -3
  13. package/dist/db/kernel-schema.d.ts +5 -0
  14. package/dist/devices/device-projects.service.d.ts +3 -12
  15. package/dist/devices/device-projects.service.js +20 -63
  16. package/dist/devices/devices.service.d.ts +15 -12
  17. package/dist/devices/devices.service.js +25 -19
  18. package/dist/dial-in/machines.d.ts +3 -15
  19. package/dist/dial-in/machines.js +4 -60
  20. package/dist/extensions/bootstrap.d.ts +17 -3
  21. package/dist/extensions/bootstrap.js +56 -14
  22. package/dist/http/meta.controller.d.ts +0 -1
  23. package/dist/http/meta.controller.js +2 -6
  24. package/dist/lifecycle/kernel-lifecycle.d.ts +3 -1
  25. package/dist/lifecycle/kernel-lifecycle.js +16 -11
  26. package/dist/overrides.d.ts +0 -5
  27. package/dist/overrides.js +0 -2
  28. package/dist/platform/file-ref.d.ts +6 -5
  29. package/dist/platform/ops/agent-skills.ops.js +1 -1
  30. package/dist/platform/ops/agents.ops.js +1 -1
  31. package/dist/runtime/model-call.d.ts +2 -2
  32. package/dist/runtime/project/knowledge.d.ts +1 -1
  33. package/dist/runtime/project/knowledge.js +1 -1
  34. package/dist/runtime/project/knowledge.service.d.ts +5 -11
  35. package/dist/runtime/project/knowledge.service.js +12 -23
  36. package/dist/runtime/providers.d.ts +34 -1
  37. package/dist/runtime/providers.js +56 -7
  38. package/dist/runtime/run-steps.d.ts +4 -6
  39. package/dist/runtime/run-steps.js +7 -15
  40. package/dist/runtime/runtime.module.js +1 -1
  41. package/dist/sandbox/device-sandbox.d.ts +16 -2
  42. package/dist/sandbox/device-sandbox.js +13 -5
  43. package/dist/sandbox/held-operations.d.ts +2 -5
  44. package/dist/sandbox/held-operations.js +0 -14
  45. package/dist/sandbox/managed-device-context.d.ts +1 -1
  46. package/dist/sandbox/managed-device-context.js +1 -1
  47. package/dist/sandbox/operation-authority.js +3 -1
  48. package/dist/sandbox/permission-authority-lock.d.ts +6 -0
  49. package/dist/sandbox/permission-authority-lock.js +14 -0
  50. package/dist/sandbox/permission-context-types.d.ts +0 -11
  51. package/dist/sandbox/permission-context-types.js +0 -13
  52. package/dist/sandbox/permission-facts.d.ts +4 -0
  53. package/dist/sandbox/permission-facts.js +6 -1
  54. package/dist/sandbox/providers.d.ts +5 -0
  55. package/dist/sandbox/providers.js +1 -1
  56. package/dist/sandbox/review/permission-candidate.d.ts +12 -7
  57. package/dist/sandbox/review/permission-candidate.js +28 -7
  58. package/dist/sandbox/sandbox-file-reader.d.ts +7 -12
  59. package/dist/sandbox/sandbox-file-reader.js +12 -29
  60. package/dist/sandbox/sandbox.service.d.ts +53 -32
  61. package/dist/sandbox/sandbox.service.js +217 -141
  62. package/dist/sandbox/use-context.d.ts +4 -1
  63. package/dist/setup/setup-guides.service.d.ts +1 -2
  64. package/dist/setup/setup-guides.service.js +1 -4
  65. package/dist/shares/sweep.job.d.ts +2 -0
  66. package/dist/shares/sweep.job.js +3 -1
  67. package/dist/skills/invoke.d.ts +13 -35
  68. package/dist/skills/invoke.js +23 -162
  69. package/dist/tools/builtins/builtin-tools.d.ts +2 -11
  70. package/dist/tools/builtins/builtin-tools.js +5 -23
  71. package/dist/tools/builtins/image/generate.js +2 -2
  72. package/dist/tools/builtins/sandbox/common.d.ts +32 -80
  73. package/dist/tools/builtins/sandbox/common.js +61 -173
  74. package/dist/tools/builtins/sandbox/deliver.js +2 -2
  75. package/dist/tools/builtins/sandbox/device-owner.d.ts +4 -5
  76. package/dist/tools/builtins/sandbox/device-owner.js +5 -6
  77. package/dist/tools/builtins/sandbox/fetch-attachment.js +2 -2
  78. package/dist/tools/builtins/sandbox/glob.js +1 -1
  79. package/dist/tools/builtins/sandbox/grep.js +1 -1
  80. package/dist/tools/builtins/sandbox/index.d.ts +2 -2
  81. package/dist/tools/builtins/sandbox/index.js +2 -2
  82. package/dist/tools/builtins/sandbox/read.js +1 -1
  83. package/dist/tools/builtins/sandbox/task-output.d.ts +3 -3
  84. package/dist/tools/builtins/sandbox/task-output.js +4 -4
  85. package/dist/tools/builtins/sandbox/task-stop.js +1 -1
  86. package/dist/tools/builtins/skill-load.js +2 -2
  87. package/dist/tools/connectors.service.d.ts +4 -2
  88. package/dist/tools/connectors.service.js +15 -3
  89. package/dist/tools/pipeline.d.ts +0 -2
  90. package/dist/tools/pipeline.js +7 -14
  91. package/dist/tools/tools.module.js +1 -1
  92. package/package.json +2 -2
  93. package/src/migrations/0179_device_report_limit_text.sql +28 -0
  94. package/src/migrations/0180_device_instance_abandoned.sql +6 -0
@@ -357,18 +357,21 @@ export declare class DevicesService {
357
357
  */
358
358
  lockNetworkAddSubject(orgId: string, accountId: string, deviceId: string): Promise<void>;
359
359
  /**
360
- * Adds `hosts` to one of the person's devices' own network list: a network approval decided
361
- * "add to this device's list" (`via`: where it was decided). In a caller's transaction (the
362
- * approval decision's) it joins it and requires the device's permission write lock already held
363
- * there ({@link lockNetworkAddSubject} in the caller's ordered prelude; else it throws before
364
- * writing); with no transaction it takes that prelude itself ({@link withOrderedLocks}). It
365
- * takes no distributed lock. The write is a network change like `PATCH` ({@link networkLocked}:
366
- * audited `device.network_changed` from → to, listed as a recent change, the device epoch bumped
367
- * and the instance marked for its next use). Refuses with `device.network_not_allowed`, writing
368
- * nothing, unless the stored network is `allowlist` with a host list of its own (a device
369
- * following its org's hosts already allows every host its list could name) and every host may
370
- * join that list (`deviceListAddRefusal`). Hosts its list already covers change nothing; own
371
- * hosts the org's hosts no longer cover (in effect nowhere) leave the list with the addition.
360
+ * Adds `hosts` to one of the person's devices' own network list: a network approval decided "add
361
+ * to this device's list" (`via`: where it was decided). In a caller's transaction (the approval
362
+ * decision's) it joins it and requires the authority locks of that prelude already held there
363
+ * (platform and org shared, the device exclusive: {@link lockNetworkAddSubject} in the caller's
364
+ * ordered prelude; else it throws before locking or writing anything; the membership and device
365
+ * rows are locked again in the body); with no transaction it takes that prelude itself
366
+ * ({@link withOrderedLocks}). It takes no distributed lock. The write is a network change like `PATCH`
367
+ * ({@link networkLocked}: audited `device.network_changed` from → to, listed as a recent change,
368
+ * the device epoch bumped and the instance marked for its next use). Refuses with
369
+ * `device.network_not_allowed`, writing nothing, unless the stored network is `allowlist` with a
370
+ * host list of its own (a device following its org's hosts already allows every host its list
371
+ * could name) and every host may join that list (`deviceListAddRefusal`); its detail `reason`
372
+ * says which (`network_closed`, `follows_org`, `host_not_addable`), for the decision's copy.
373
+ * Hosts its list already covers change nothing; own hosts the org's hosts no longer cover (in
374
+ * effect nowhere) leave the list with the addition.
372
375
  */
373
376
  addNetworkHostsIn(orgId: string, accountId: string, deviceId: string, hosts: string[], via: "web" | "im"): Promise<void>;
374
377
  /** {@link addNetworkHostsIn} under the locks of its prelude (naming them again re-checks). */
@@ -25,10 +25,10 @@ import { assertNotSharedAdmission, currentStore, TransactionHost, withOrderedLoc
25
25
  import { Transactional } from "../infra/database/transactional.decorator.js";
26
26
  import { OutboxService } from "../infra/outbox/outbox.service.js";
27
27
  import { DeviceReports } from "../sandbox/device-reports.js";
28
- import { hostGrantable } from "../sandbox/device-sandbox.js";
28
+ import { deviceSideLayer, hostGrantable } from "../sandbox/device-sandbox.js";
29
29
  import { oweDeviceDestroy, SandboxJobs } from "../sandbox/jobs.js";
30
30
  import { coversHost } from "../sandbox/modes.js";
31
- import { assertAuthorityHeld } from "../sandbox/permission-authority-lock.js";
31
+ import { assertAuthorityWriteHeld } from "../sandbox/permission-authority-lock.js";
32
32
  import { hostsNarrowed, needsOpenNetwork, PermissionCeilingWrites, } from "../sandbox/permission-ceiling-writes.js";
33
33
  import { ownNetwork, PermissionFacts } from "../sandbox/permission-facts.js";
34
34
  import { DeviceProviders, servesDialIn } from "../sandbox/providers.js";
@@ -439,7 +439,7 @@ let DevicesService = class DevicesService {
439
439
  }),
440
440
  ]);
441
441
  if (to.mode === "open" && next.box.networkMode !== "open")
442
- throw new ApiError("device.network_not_allowed", `The open network is not allowed for this device: ${networkLayerText(next.box.layer.network)} limits it to ${next.box.networkCeiling === "none" ? "no network" : "the allowlist"}`);
442
+ throw new ApiError("device.network_not_allowed", `The open network is not allowed for this device: ${networkLayerText(next.box.layer.network)} limits it to ${next.box.networkCeiling === "none" ? "no network" : "the allowlist"}${deviceSideLayer(next.box.layer.network) && next.changeHint ? ` (to change this, as the device's provider says: ${next.changeHint.trim().replace(/\.$/, "")})` : ""}`);
443
443
  // a device's own list only narrows its org's hosts, whatever the network in effect now
444
444
  const outside = to.hosts.filter((h) => !next.orgHosts.some((p) => coversHost(p.toLowerCase(), h)));
445
445
  if (outside.length > 0)
@@ -504,22 +504,26 @@ let DevicesService = class DevicesService {
504
504
  await this.lockNetworkSubject(orgId, accountId, deviceId);
505
505
  }
506
506
  /**
507
- * Adds `hosts` to one of the person's devices' own network list: a network approval decided
508
- * "add to this device's list" (`via`: where it was decided). In a caller's transaction (the
509
- * approval decision's) it joins it and requires the device's permission write lock already held
510
- * there ({@link lockNetworkAddSubject} in the caller's ordered prelude; else it throws before
511
- * writing); with no transaction it takes that prelude itself ({@link withOrderedLocks}). It
512
- * takes no distributed lock. The write is a network change like `PATCH` ({@link networkLocked}:
513
- * audited `device.network_changed` from → to, listed as a recent change, the device epoch bumped
514
- * and the instance marked for its next use). Refuses with `device.network_not_allowed`, writing
515
- * nothing, unless the stored network is `allowlist` with a host list of its own (a device
516
- * following its org's hosts already allows every host its list could name) and every host may
517
- * join that list (`deviceListAddRefusal`). Hosts its list already covers change nothing; own
518
- * hosts the org's hosts no longer cover (in effect nowhere) leave the list with the addition.
507
+ * Adds `hosts` to one of the person's devices' own network list: a network approval decided "add
508
+ * to this device's list" (`via`: where it was decided). In a caller's transaction (the approval
509
+ * decision's) it joins it and requires the authority locks of that prelude already held there
510
+ * (platform and org shared, the device exclusive: {@link lockNetworkAddSubject} in the caller's
511
+ * ordered prelude; else it throws before locking or writing anything; the membership and device
512
+ * rows are locked again in the body); with no transaction it takes that prelude itself
513
+ * ({@link withOrderedLocks}). It takes no distributed lock. The write is a network change like `PATCH`
514
+ * ({@link networkLocked}: audited `device.network_changed` from → to, listed as a recent change,
515
+ * the device epoch bumped and the instance marked for its next use). Refuses with
516
+ * `device.network_not_allowed`, writing nothing, unless the stored network is `allowlist` with a
517
+ * host list of its own (a device following its org's hosts already allows every host its list
518
+ * could name) and every host may join that list (`deviceListAddRefusal`); its detail `reason`
519
+ * says which (`network_closed`, `follows_org`, `host_not_addable`), for the decision's copy.
520
+ * Hosts its list already covers change nothing; own hosts the org's hosts no longer cover (in
521
+ * effect nowhere) leave the list with the addition.
519
522
  */
520
523
  async addNetworkHostsIn(orgId, accountId, deviceId, hosts, via) {
521
524
  if (currentStore() !== undefined) {
522
- assertAuthorityHeld("device", deviceId, true);
525
+ // every authority level the prelude takes: platform and org shared, the device exclusive
526
+ assertAuthorityWriteHeld({ orgId, deviceId }, "device");
523
527
  await this.addNetworkHostsLocked(orgId, accountId, deviceId, hosts, via);
524
528
  return;
525
529
  }
@@ -536,9 +540,9 @@ let DevicesService = class DevicesService {
536
540
  .executeTakeFirstOrThrow();
537
541
  const own = ownNetwork(row);
538
542
  if (own.networkMode === "none")
539
- throw new ApiError("device.network_not_allowed", "Network access is turned off for this device's sandbox; its owner changes that on the device page");
543
+ throw new ApiError("device.network_not_allowed", "Network access is turned off for this device's sandbox; its owner changes that on the device page", [{ reason: "network_closed" }]);
540
544
  if (own.networkMode !== "allowlist" || own.networkHosts.length === 0)
541
- throw new ApiError("device.network_not_allowed", "This device has no host list of its own: it follows its organization's hosts, which already include every host its list could name; an organization admin adds another host to the organization's device network list");
545
+ throw new ApiError("device.network_not_allowed", "This device has no host list of its own: it follows its organization's hosts, which already include every host its list could name; an organization admin adds another host to the organization's device network list", [{ reason: "follows_org" }]);
542
546
  const wanted = [...new Set(hosts.map((h) => h.toLowerCase()))];
543
547
  for (const host of wanted) {
544
548
  const invalid = validateAllowHost(host);
@@ -551,7 +555,7 @@ let DevicesService = class DevicesService {
551
555
  for (const host of wanted) {
552
556
  const why = facts.listAddRefusal(host);
553
557
  if (why !== null)
554
- throw new ApiError("device.network_not_allowed", `${host} cannot be added to this device's network list: ${why}`);
558
+ throw new ApiError("device.network_not_allowed", `${host} cannot be added to this device's network list: ${why}`, [{ reason: "host_not_addable" }]);
555
559
  }
556
560
  const covers = (list, h) => list.some((p) => coversHost(p.toLowerCase(), h));
557
561
  // own hosts the org dropped since are in effect nowhere: they would refuse the new list
@@ -1143,6 +1147,8 @@ function networkLayerText(layer) {
1143
1147
  return "the organization (an org admin)";
1144
1148
  case "provider":
1145
1149
  return "its sandbox provider";
1150
+ case "owner":
1151
+ return "the owner of the machine it runs on";
1146
1152
  default:
1147
1153
  return "its owner";
1148
1154
  }
@@ -3,7 +3,6 @@ import { KernelDb } from "../infra/database/kernel-db.js";
3
3
  import { TransactionHost } from "../infra/database/transaction-host.js";
4
4
  import type { KernelLogger } from "../log.js";
5
5
  import { PermissionCeilingWrites } from "../sandbox/permission-ceiling-writes.js";
6
- import { DeviceProviders } from "../sandbox/providers.js";
7
6
  import { DialInRelay } from "./relay.js";
8
7
  /** The machine credential's prefix (`cap_dev_` plus 32 random bytes, base64url). */
9
8
  export declare const MACHINE_CREDENTIAL_PREFIX = "cap_dev_";
@@ -57,8 +56,7 @@ export declare class DialInMachines {
57
56
  private readonly bus;
58
57
  private readonly log;
59
58
  private readonly ceilings;
60
- private readonly providers;
61
- constructor(db: KernelDb, txHost: TransactionHost, relay: Pick<DialInRelay, "stop">, bus: ExtensionContext["bus"], log: Pick<KernelLogger, "warn">, ceilings: PermissionCeilingWrites, providers: Pick<DeviceProviders, "forDevice">);
59
+ constructor(db: KernelDb, txHost: TransactionHost, relay: Pick<DialInRelay, "stop">, bus: ExtensionContext["bus"], log: Pick<KernelLogger, "warn">, ceilings: PermissionCeilingWrites);
62
60
  /**
63
61
  * A new machine for the device and its credential (returned once). Revokes the
64
62
  * device's active machine first. Joins the caller's transaction (the device confirmation),
@@ -113,19 +111,11 @@ export declare class DialInMachines {
113
111
  }): Promise<void>;
114
112
  /** Marks the machine seen (a ping); writes at most once every 60 seconds. */
115
113
  touch(machineId: string): Promise<void>;
116
- /**
117
- * Disconnects the machine of one of the person's own live dial-in devices, whatever its
118
- * provider: revokes it and audits `device.machine_revoked`. No route calls it (the device page
119
- * no longer disconnects a machine; deleting the device revokes it, {@link revokeActive}); the
120
- * kernel tests revoke a connected machine with it. Anyone else's device, a cloud one or a
121
- * missing one → `device.not_found`; no machine connected is a no-op.
122
- */
123
- revoke(orgId: string, accountId: string, deviceId: string, actorTokenId?: string): Promise<void>;
124
114
  /**
125
115
  * Revokes the device's active machine, if any, in the caller's transaction, and after the
126
116
  * commit tells it to stop (not when `replaced`) and closes its connection for `reason`. Returns
127
- * the revoked machine's id. Used by {@link issue} (`replaced`), {@link revoke} (`revoked`) and
128
- * the device's deletion (`deleted`).
117
+ * the revoked machine's id. Used by {@link issue} (`replaced`) and the device's deletion
118
+ * (`deleted`).
129
119
  */
130
120
  revokeActive(deviceId: string, reason: MachineRevocationReason): Promise<string | null>;
131
121
  /**
@@ -133,8 +123,6 @@ export declare class DialInMachines {
133
123
  * same post-commit disconnect as a replacement (no stop frame). True when it was active.
134
124
  */
135
125
  revokeMachine(machineId: string): Promise<boolean>;
136
- /** Whether a machine ever signed in to the device (revoked or not). */
137
- private everSignedIn;
138
126
  /** The device's active machine, or null. */
139
127
  activeFor(deviceId: string): Promise<ActiveMachine | null>;
140
128
  /**
@@ -11,8 +11,6 @@ import { randomBytes } from "node:crypto";
11
11
  import { isDeviceBootId } from "@capybara-hq/plugin-sdk/device-protocol";
12
12
  import { Inject, Injectable } from "@nestjs/common";
13
13
  import { sql } from "kysely";
14
- import { deviceNotFound } from "../devices/errors.js";
15
- import { audit } from "../identity/audit.js";
16
14
  import { sha256Hex } from "../identity/hash.js";
17
15
  import { afterCommit } from "../infra/database/after-commit.js";
18
16
  import { KernelDb } from "../infra/database/kernel-db.js";
@@ -20,7 +18,6 @@ import { TransactionHost } from "../infra/database/transaction-host.js";
20
18
  import { Transactional } from "../infra/database/transactional.decorator.js";
21
19
  import { KERNEL_BUS, KERNEL_LOGGER } from "../infra/tokens.js";
22
20
  import { PermissionCeilingWrites } from "../sandbox/permission-ceiling-writes.js";
23
- import { DeviceProviders, servesDialIn } from "../sandbox/providers.js";
24
21
  import { deviceRevokedTopic } from "./keys.js";
25
22
  import { DialInRelay } from "./relay.js";
26
23
  /** The machine credential's prefix (`cap_dev_` plus 32 random bytes, base64url). */
@@ -44,15 +41,13 @@ let DialInMachines = class DialInMachines {
44
41
  bus;
45
42
  log;
46
43
  ceilings;
47
- providers;
48
- constructor(db, txHost, relay, bus, log, ceilings, providers) {
44
+ constructor(db, txHost, relay, bus, log, ceilings) {
49
45
  this.db = db;
50
46
  this.txHost = txHost;
51
47
  this.relay = relay;
52
48
  this.bus = bus;
53
49
  this.log = log;
54
50
  this.ceilings = ceilings;
55
- this.providers = providers;
56
51
  }
57
52
  /**
58
53
  * A new machine for the device and its credential (returned once). Revokes the
@@ -196,48 +191,11 @@ let DialInMachines = class DialInMachines {
196
191
  ]))
197
192
  .execute();
198
193
  }
199
- /**
200
- * Disconnects the machine of one of the person's own live dial-in devices, whatever its
201
- * provider: revokes it and audits `device.machine_revoked`. No route calls it (the device page
202
- * no longer disconnects a machine; deleting the device revokes it, {@link revokeActive}); the
203
- * kernel tests revoke a connected machine with it. Anyone else's device, a cloud one or a
204
- * missing one → `device.not_found`; no machine connected is a no-op.
205
- */
206
- async revoke(orgId, accountId, deviceId, actorTokenId) {
207
- const env = await this.db
208
- .selectFrom("devices")
209
- .select(["id", "provider"])
210
- .where("id", "=", deviceId)
211
- .where("org_id", "=", orgId)
212
- .where("owner_kind", "=", "personal")
213
- .where("owner_account_id", "=", accountId)
214
- .where("deleted_at", "is", null)
215
- .forNoKeyUpdate()
216
- .executeTakeFirst();
217
- if (!env)
218
- throw deviceNotFound();
219
- // a dial-in device: its provider serves the dial-in channel, or a machine signed in to it
220
- // (its provider may be unloaded here, and the person disconnects anyway)
221
- const p = this.providers.forDevice(env.provider);
222
- if (!(p !== undefined && servesDialIn(p)) && !(await this.everSignedIn(deviceId)))
223
- throw deviceNotFound();
224
- const machineId = await this.revokeActive(deviceId, "revoked");
225
- if (machineId === null)
226
- return;
227
- await audit(this.db.db, {
228
- actorAccountId: accountId,
229
- ...(actorTokenId !== undefined && { actorTokenId }),
230
- orgId,
231
- action: "device.machine_revoked",
232
- target: deviceId,
233
- detail: { machineId },
234
- });
235
- }
236
194
  /**
237
195
  * Revokes the device's active machine, if any, in the caller's transaction, and after the
238
196
  * commit tells it to stop (not when `replaced`) and closes its connection for `reason`. Returns
239
- * the revoked machine's id. Used by {@link issue} (`replaced`), {@link revoke} (`revoked`) and
240
- * the device's deletion (`deleted`).
197
+ * the revoked machine's id. Used by {@link issue} (`replaced`) and the device's deletion
198
+ * (`deleted`).
241
199
  */
242
200
  async revokeActive(deviceId, reason) {
243
201
  const device = await this.db
@@ -287,16 +245,6 @@ let DialInMachines = class DialInMachines {
287
245
  afterCommit(() => this.disconnect(deviceId, machineId, "revoked", { stop: false }));
288
246
  return true;
289
247
  }
290
- /** Whether a machine ever signed in to the device (revoked or not). */
291
- async everSignedIn(deviceId) {
292
- const row = await this.db
293
- .selectFrom("device_machines")
294
- .select("id")
295
- .where("device_id", "=", deviceId)
296
- .limit(1)
297
- .executeTakeFirst();
298
- return row !== undefined;
299
- }
300
248
  /** The device's active machine, or null. */
301
249
  async activeFor(deviceId) {
302
250
  const r = await this.db
@@ -358,9 +306,6 @@ __decorate([
358
306
  __decorate([
359
307
  Transactional()
360
308
  ], DialInMachines.prototype, "recordConnect", null);
361
- __decorate([
362
- Transactional()
363
- ], DialInMachines.prototype, "revoke", null);
364
309
  __decorate([
365
310
  Transactional()
366
311
  ], DialInMachines.prototype, "revokeActive", null);
@@ -374,8 +319,7 @@ DialInMachines = __decorate([
374
319
  __param(2, Inject(DialInRelay)),
375
320
  __param(3, Inject(KERNEL_BUS)),
376
321
  __param(4, Inject(KERNEL_LOGGER)),
377
- __param(5, Inject(PermissionCeilingWrites)),
378
- __param(6, Inject(DeviceProviders))
322
+ __param(5, Inject(PermissionCeilingWrites))
379
323
  ], DialInMachines);
380
324
  export { DialInMachines };
381
325
  /** Two machine rows (or a login) name the same machine: same name, OS and arch. */
@@ -1,4 +1,5 @@
1
1
  import { type PluginImport } from "../catalog/plugin-import.js";
2
+ import type { PlatformPluginUpdater } from "../catalog/plugin-upgrade.js";
2
3
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
3
4
  import { KernelDb } from "../infra/database/kernel-db.js";
4
5
  import { TransactionHost } from "../infra/database/transaction-host.js";
@@ -148,6 +149,11 @@ export declare const BOOTSTRAP_LOCK_TTL_MS = 120000;
148
149
  export declare const BOOTSTRAP_LOCK_TTL: unique symbol;
149
150
  /** What a run imports a declarative entry or an entry's catalog version with. */
150
151
  export type BootstrapImports = Pick<PluginImport, "prepare" | "prepareGit" | "confirm">;
152
+ /**
153
+ * What a run moves the platform to a raised pin of a plugin without an extension with (the
154
+ * platform plugin update, acting as the kernel).
155
+ */
156
+ export type BootstrapUpdater = Pick<PlatformPluginUpdater, "preview" | "update">;
151
157
  export declare class BootstrapService {
152
158
  private readonly kdb;
153
159
  readonly txHost: TransactionHost;
@@ -221,6 +227,8 @@ export declare class BootstrapService {
221
227
  packages?: ReadonlyMap<string, Uint8Array>;
222
228
  /** The plugin import a declarative entry (or an entry's catalog version) goes through. */
223
229
  imports: BootstrapImports;
230
+ /** The platform update a raised pin of a declarative entry goes through. */
231
+ updater: BootstrapUpdater;
224
232
  }): Promise<BootstrapResult>;
225
233
  /**
226
234
  * A pin whose plugin name an org holds (a live org-owned catalog item): the bootstrap takes no
@@ -247,8 +255,11 @@ export declare class BootstrapService {
247
255
  /** The entry names the last completed run handled (undefined before any run completed). */
248
256
  private lastRunNames;
249
257
  private entry;
250
- /** Whether a live (not deleted) platform catalog item has this name. */
251
- private hasLiveItem;
258
+ /**
259
+ * The live (not deleted) platform catalog item of this name: its platform version (the one orgs
260
+ * install, else its latest) and where that version came from. undefined: no such item.
261
+ */
262
+ private platformVersion;
252
263
  /**
253
264
  * The catalog item of a bootstrap entry follows `required` / `builtin`: such an entry is builtin,
254
265
  * offered to every org (scope `all`, which an org admin cannot switch off) and not disabled
@@ -272,7 +283,10 @@ export declare class BootstrapService {
272
283
  private gitPlugin;
273
284
  /** Stages a git entry from its files as an admin git import would (translation included). */
274
285
  private prepareGitEntry;
275
- /** A declarative plugin: catalog only. Returns false when that version is already imported. */
286
+ /**
287
+ * A declarative plugin: catalog only. Returns false when that version is already imported.
288
+ * `updateFollows`: a platform update to this version follows (it owes the scope sync).
289
+ */
276
290
  private importOnly;
277
291
  /**
278
292
  * Imports, approves, installs and enables (one review; its confirm deploys the extension). When
@@ -244,7 +244,7 @@ let BootstrapService = class BootstrapService {
244
244
  const fetchErr = fetchFailed.get(e.name);
245
245
  if (fetchErr !== undefined)
246
246
  throw fetchErr;
247
- const r = await this.entry(e, files.get(e.name), handled, o.imports, {
247
+ const r = await this.entry(e, files.get(e.name), handled, o, {
248
248
  manifest: o.manifest,
249
249
  tree: gitTrees.get(e.name),
250
250
  });
@@ -370,7 +370,7 @@ let BootstrapService = class BootstrapService {
370
370
  return undefined;
371
371
  return new Set(results.filter((r) => r.action !== "required_cleared").map((r) => r.name));
372
372
  }
373
- async entry(e, bytes, handled, imports,
373
+ async entry(e, bytes, handled, { imports, updater },
374
374
  /** For a git entry: the manifest (its marketplaces) and the tree oid when read from git now. */
375
375
  at) {
376
376
  let plugin;
@@ -432,9 +432,31 @@ let BootstrapService = class BootstrapService {
432
432
  const builtin = e.required || e.builtin === true;
433
433
  if (!plugin.extension) {
434
434
  await this.markBuiltin(e.name, builtin);
435
- if (!isNew && !(builtin && !(await this.hasLiveItem(e.name)))) {
436
- return { name: e.name, action: "kept", version: e.version };
435
+ const live = await this.platformVersion(e.name);
436
+ if (live !== undefined) {
437
+ // As the extension path does: a version the bootstrap put there is raised to the pin; one
438
+ // the super admin moved to (another source, or a higher version) stays
439
+ if (live.source !== "bootstrap" || !isLower(live.version, e.version)) {
440
+ return { name: e.name, action: "kept", version: live.version };
441
+ }
442
+ if (live.disabled) {
443
+ // The update refuses a disabled item: the version waits in the catalog, and the super
444
+ // admin applies it once they enable the plugin
445
+ await this.importOnly(e, bytes, source, imports, git);
446
+ this.log.info("bootstrap: the plugin is disabled on the deployment; the pinned version is imported, not applied", { plugin: e.name, version: e.version, current: live.version });
447
+ return { name: e.name, action: "kept", version: live.version };
448
+ }
449
+ await this.importOnly(e, bytes, source, imports, git, true);
450
+ const preview = await updater.preview(live.itemId, e.version);
451
+ await updater.update(null, live.itemId, {
452
+ version: e.version,
453
+ diffHash: preview.diffHash,
454
+ });
455
+ return { name: e.name, action: "upgraded", version: e.version };
437
456
  }
457
+ // A builtin entry a super admin removed is put back; an optional one stays out (Ruling 5)
458
+ if (!isNew && !builtin)
459
+ return { name: e.name, action: "kept", version: e.version };
438
460
  const imported = await this.importOnly(e, bytes, source, imports, git);
439
461
  await this.markBuiltin(e.name, builtin);
440
462
  return { name: e.name, action: imported ? "imported" : "kept", version: e.version };
@@ -489,16 +511,32 @@ let BootstrapService = class BootstrapService {
489
511
  await this.markBuiltin(e.name, builtin);
490
512
  return leftDisabled === undefined ? result : { ...result, leftDisabled };
491
513
  }
492
- /** Whether a live (not deleted) platform catalog item has this name. */
493
- async hasLiveItem(name) {
514
+ /**
515
+ * The live (not deleted) platform catalog item of this name: its platform version (the one orgs
516
+ * install, else its latest) and where that version came from. undefined: no such item.
517
+ */
518
+ async platformVersion(name) {
494
519
  const row = await this.db
495
- .selectFrom("catalog_items")
496
- .select("id")
497
- .where("name", "=", name)
498
- .where("owner_org_id", "is", null)
499
- .where("deleted_at", "is", null)
520
+ .selectFrom("catalog_items as i")
521
+ .leftJoin("catalog_item_versions as v", (j) => j
522
+ .onRef("v.item_id", "=", "i.id")
523
+ .on("v.version", "=", sql `coalesce(i.platform_synced_version, i.latest_version)`))
524
+ .select([
525
+ "i.id",
526
+ sql `coalesce(i.platform_synced_version, i.latest_version)`.as("version"),
527
+ "v.source",
528
+ "i.disabled",
529
+ ])
530
+ .where("i.name", "=", name)
531
+ .where("i.owner_org_id", "is", null)
532
+ .where("i.deleted_at", "is", null)
500
533
  .executeTakeFirst();
501
- return row !== undefined;
534
+ return (row && {
535
+ itemId: row.id,
536
+ version: row.version,
537
+ source: row.source ?? null,
538
+ disabled: row.disabled,
539
+ });
502
540
  }
503
541
  /**
504
542
  * The catalog item of a bootstrap entry follows `required` / `builtin`: such an entry is builtin,
@@ -585,8 +623,11 @@ let BootstrapService = class BootstrapService {
585
623
  }
586
624
  return staged;
587
625
  }
588
- /** A declarative plugin: catalog only. Returns false when that version is already imported. */
589
- async importOnly(e, bytes, source, imports, git) {
626
+ /**
627
+ * A declarative plugin: catalog only. Returns false when that version is already imported.
628
+ * `updateFollows`: a platform update to this version follows (it owes the scope sync).
629
+ */
630
+ async importOnly(e, bytes, source, imports, git, updateFollows = false) {
590
631
  try {
591
632
  const { stagingId, review } = git !== undefined
592
633
  ? await this.prepareGitEntry(e, git, source, imports)
@@ -594,6 +635,7 @@ let BootstrapService = class BootstrapService {
594
635
  await imports.confirm(null, stagingId, {
595
636
  reviewHash: review.reviewHash,
596
637
  scope: e.scope ?? "optional",
638
+ ...(updateFollows && { updateFollows: true }),
597
639
  });
598
640
  return true;
599
641
  }
@@ -19,7 +19,6 @@ export declare const MetaResponseSchema: z.ZodObject<{
19
19
  }, z.core.$strip>;
20
20
  }, z.core.$strip>;
21
21
  features: z.ZodObject<{
22
- localDevices: z.ZodBoolean;
23
22
  appSignIn: z.ZodBoolean;
24
23
  push: z.ZodArray<z.ZodObject<{
25
24
  appId: z.ZodString;
@@ -27,13 +27,11 @@ export const MetaResponseSchema = z.object({
27
27
  protocols: z.object({
28
28
  /**
29
29
  * The `capybara-device` protocol majors the loaded dial-in providers speak (their
30
- * `permissions.dialIn.protocol`); without any, the SDK's major, and `localDevices` is false.
30
+ * `permissions.dialIn.protocol`); without any, the SDK's major.
31
31
  */
32
32
  device: z.object({ min: z.number().int(), max: z.number().int() }),
33
33
  }),
34
34
  features: z.object({
35
- /** A dial-in provider speaking `capybara-device/<major>` (device-local) is loaded. */
36
- localDevices: z.boolean(),
37
35
  appSignIn: z.boolean(),
38
36
  /** App ids a push provider covers with the providers that do; `[]` without `http.publicUrl`. */
39
37
  push: z.array(z.object({ appId: z.string(), providers: z.array(z.string()) })),
@@ -77,8 +75,7 @@ let MetaController = class MetaController {
77
75
  this.iconUrl("favicon"),
78
76
  ]);
79
77
  const appSignIn = Boolean(config.http.publicUrl);
80
- // Local devices exist only while a dial-in provider speaking capybara-device is loaded
81
- // (device-local); the shells offer "connect this machine" only then.
78
+ // The capybara-device majors the loaded dial-in providers (device-local) speak.
82
79
  const devices = deviceProtocolRange(this.dialIn.loaded().map((p) => p.protocol));
83
80
  return {
84
81
  name: config.platform.name ?? null,
@@ -88,7 +85,6 @@ let MetaController = class MetaController {
88
85
  device: devices ?? { min: DEVICE_PROTOCOL_VERSION, max: DEVICE_PROTOCOL_VERSION },
89
86
  },
90
87
  features: {
91
- localDevices: devices !== null,
92
88
  // The authorize route answers app_auth.unavailable without http.publicUrl.
93
89
  appSignIn,
94
90
  // A push message carries the deployment origin, which needs http.publicUrl.
@@ -5,6 +5,7 @@ import { type Kysely } from "kysely";
5
5
  import type { KernelAppOptions } from "../app.js";
6
6
  import { MarketplacesService } from "../catalog/marketplaces.service.js";
7
7
  import { PluginImport } from "../catalog/plugin-import.js";
8
+ import { PlatformPluginUpdater } from "../catalog/plugin-upgrade.js";
8
9
  import { ChannelJobs } from "../channels/jobs.js";
9
10
  import { ChannelOutbound } from "../channels/outbound.js";
10
11
  import { PromptSuggestionQueue } from "../conversations/prompt-suggestions.js";
@@ -84,6 +85,7 @@ export declare class KernelLifecycle implements OnApplicationBootstrap, BeforeAp
84
85
  private readonly bootstrapDefaults;
85
86
  private readonly marketplaces;
86
87
  private readonly pluginImport;
88
+ private readonly pluginUpdater;
87
89
  private readonly bus;
88
90
  private readonly usageReport;
89
91
  private readonly titles;
@@ -109,7 +111,7 @@ export declare class KernelLifecycle implements OnApplicationBootstrap, BeforeAp
109
111
  private bootstrapPackages;
110
112
  /** The merged bootstrap manifest, read once per start. */
111
113
  private mergedManifest;
112
- 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, bus: Pick<ExtensionContext["bus"], "publish" | "subscribe">, usageReport: UsageReporter, titles: TitleQueue, suggestions: PromptSuggestionQueue, channelJobs: ChannelJobs, channelOutbound: ChannelOutbound, presence: ReplicaPresence, worker?: WorkerRole | undefined, gateway?: GatewayRole | undefined);
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);
113
115
  /** The kernel HTTP application (set up by `buildKernelApp` before `init()`). */
114
116
  get http(): KernelHttpApp;
115
117
  attachHttp(http: KernelHttpApp): void;
@@ -12,6 +12,7 @@ import { Inject, Injectable, Optional, } from "@nestjs/common";
12
12
  import { sql } from "kysely";
13
13
  import { MarketplacesService } from "../catalog/marketplaces.service.js";
14
14
  import { PluginImport } from "../catalog/plugin-import.js";
15
+ import { PlatformPluginUpdater } from "../catalog/plugin-upgrade.js";
15
16
  import { ChannelJobs } from "../channels/jobs.js";
16
17
  import { ChannelOutbound } from "../channels/outbound.js";
17
18
  import { PromptSuggestionQueue } from "../conversations/prompt-suggestions.js";
@@ -105,6 +106,7 @@ let KernelLifecycle = class KernelLifecycle {
105
106
  bootstrapDefaults;
106
107
  marketplaces;
107
108
  pluginImport;
109
+ pluginUpdater;
108
110
  bus;
109
111
  usageReport;
110
112
  titles;
@@ -132,7 +134,7 @@ let KernelLifecycle = class KernelLifecycle {
132
134
  mergedManifest;
133
135
  constructor(permissionConfig, accounts, configService, log, options,
134
136
  // biome-ignore lint/suspicious/noExplicitAny: the pool carries no schema types
135
- pool, redis, kdb, shutdown, host, registry, installs, blobs, extensionLifecycle, replicaStatus, bootstrap, bootstrapDefaults, marketplaces, pluginImport, bus,
137
+ pool, redis, kdb, shutdown, host, registry, installs, blobs, extensionLifecycle, replicaStatus, bootstrap, bootstrapDefaults, marketplaces, pluginImport, pluginUpdater, bus,
136
138
  // the producers closed on every role (their consumers are the worker role's)
137
139
  usageReport, titles, suggestions, channelJobs, channelOutbound,
138
140
  // this process's presence beat, on every role (admin overview spec §5.1)
@@ -159,6 +161,7 @@ let KernelLifecycle = class KernelLifecycle {
159
161
  this.bootstrapDefaults = bootstrapDefaults;
160
162
  this.marketplaces = marketplaces;
161
163
  this.pluginImport = pluginImport;
164
+ this.pluginUpdater = pluginUpdater;
162
165
  this.bus = bus;
163
166
  this.usageReport = usageReport;
164
167
  this.titles = titles;
@@ -387,6 +390,7 @@ let KernelLifecycle = class KernelLifecycle {
387
390
  await bootstrap.run({
388
391
  manifest,
389
392
  imports: this.pluginImport,
393
+ updater: this.pluginUpdater,
390
394
  ...(dir !== undefined && { dir }),
391
395
  signal: this.shutdown.signal,
392
396
  ...(this.bootstrapCarry !== undefined && { carry: this.bootstrapCarry }),
@@ -557,16 +561,17 @@ KernelLifecycle = __decorate([
557
561
  __param(16, Inject(BootstrapDefaultsService)),
558
562
  __param(17, Inject(MarketplacesService)),
559
563
  __param(18, Inject(PluginImport)),
560
- __param(19, Inject(KERNEL_BUS)),
561
- __param(20, Inject(UsageReporter)),
562
- __param(21, Inject(TitleQueue)),
563
- __param(22, Inject(PromptSuggestionQueue)),
564
- __param(23, Inject(ChannelJobs)),
565
- __param(24, Inject(ChannelOutbound)),
566
- __param(25, Inject(ReplicaPresence)),
567
- __param(26, Optional()),
568
- __param(26, Inject(WorkerRole)),
564
+ __param(19, Inject(PlatformPluginUpdater)),
565
+ __param(20, Inject(KERNEL_BUS)),
566
+ __param(21, Inject(UsageReporter)),
567
+ __param(22, Inject(TitleQueue)),
568
+ __param(23, Inject(PromptSuggestionQueue)),
569
+ __param(24, Inject(ChannelJobs)),
570
+ __param(25, Inject(ChannelOutbound)),
571
+ __param(26, Inject(ReplicaPresence)),
569
572
  __param(27, Optional()),
570
- __param(27, Inject(GatewayRole))
573
+ __param(27, Inject(WorkerRole)),
574
+ __param(28, Optional()),
575
+ __param(28, Inject(GatewayRole))
571
576
  ], KernelLifecycle);
572
577
  export { KernelLifecycle };
@@ -28,7 +28,6 @@ import { RUN_HOOKS, type RunHooks } from "./runtime/run-worker.js";
28
28
  import { SUBAGENT_MESSAGES_HOOKS, type SubagentMessagesHooks } from "./runtime/subagents/messages.js";
29
29
  import { SANDBOX_LEASE_TIMINGS, type SandboxLeaseTimings } from "./sandbox/leases.js";
30
30
  import { PERMISSION_AUTO_GRANT_HOOKS, type PermissionAutoGrantHooks } from "./sandbox/permission-auto-grants.js";
31
- import { PERMISSION_CONTEXT_ACTIVATION } from "./sandbox/permission-context-types.js";
32
31
  import { SETUP_CHECK_TIMEOUT } from "./setup/setup-checks.service.js";
33
32
  import { TOOL_PIPELINE_HOOKS, type ToolPipelineHooks } from "./tools/pipeline.js";
34
33
  import { EMBED_TOKEN_CLOCK } from "./ui/embed-token.js";
@@ -68,9 +67,6 @@ import { EMBED_TOKEN_CLOCK } from "./ui/embed-token.js";
68
67
  * - `EXTENSION_NET_SEAMS`: `ctx.net`'s DNS and dispatcher (a hostname resolving to a private address
69
68
  * served by a loopback fake);
70
69
  * - `APP_INTERCEPTOR`: one more global interceptor (a probe of the matched routes);
71
- * - `PERMISSION_CONTEXT_ACTIVATION`: the recorded permission context producers (the request
72
- * boundary and the managed device context writer); production leaves them on, and a test may
73
- * turn them off to exercise the dormant state;
74
70
  * - `PERMISSION_AUTO_GRANT_HOOKS`: a barrier after a Full access auto-grant's precheck (two
75
71
  * replicas racing the same crossing).
76
72
  */
@@ -104,7 +100,6 @@ interface KernelSeams {
104
100
  [PLUGIN_PUBLIC_WRITE_LIMIT]: number;
105
101
  [EXTENSION_NET_SEAMS]: ExtensionNetSeams;
106
102
  [APP_INTERCEPTOR]: NestInterceptor;
107
- [PERMISSION_CONTEXT_ACTIVATION]: boolean;
108
103
  [PERMISSION_AUTO_GRANT_HOOKS]: PermissionAutoGrantHooks;
109
104
  }
110
105
  /**