@capybara-hq/kernel 0.1.0-rc.113 → 0.1.0-rc.115

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 (96) hide show
  1. package/bootstrap.json +7 -7
  2. package/dist/admin/admin.schemas.d.ts +1 -0
  3. package/dist/catalog/marketplaces.service.d.ts +1 -1
  4. package/dist/channels/actions.js +2 -0
  5. package/dist/channels/cards.d.ts +4 -3
  6. package/dist/channels/cards.js +18 -3
  7. package/dist/channels/phrases.d.ts +15 -0
  8. package/dist/channels/phrases.js +9 -0
  9. package/dist/conversations/conversations.service.js +7 -0
  10. package/dist/conversations/events.d.ts +21 -0
  11. package/dist/conversations/events.js +35 -3
  12. package/dist/ctx/create-ctx.d.ts +1 -1
  13. package/dist/ctx/create-ctx.js +6 -1
  14. package/dist/db/kernel-schema.d.ts +29 -0
  15. package/dist/device-access/device-access.service.d.ts +74 -3
  16. package/dist/device-access/device-access.service.js +221 -7
  17. package/dist/devices/devices.service.js +3 -0
  18. package/dist/errors.d.ts +6 -0
  19. package/dist/errors.js +6 -0
  20. package/dist/extensions/permission-set.d.ts +11 -1
  21. package/dist/extensions/permission-set.js +15 -1
  22. package/dist/extensions/permission-view.d.ts +3 -2
  23. package/dist/extensions/permission-view.js +15 -2
  24. package/dist/identity/settings.d.ts +5 -0
  25. package/dist/identity/settings.js +4 -0
  26. package/dist/infra/outbox/registry.d.ts +14 -0
  27. package/dist/infra/outbox/registry.js +14 -0
  28. package/dist/models/purposes.js +5 -0
  29. package/dist/orgs/offboarding.js +5 -1
  30. package/dist/orgs/settings.service.d.ts +2 -0
  31. package/dist/platform/ops/org-settings.ops.js +1 -1
  32. package/dist/roles/worker.module.js +3 -0
  33. package/dist/runtime/compaction-model.d.ts +57 -0
  34. package/dist/runtime/compaction-model.js +87 -0
  35. package/dist/runtime/compaction.service.d.ts +23 -8
  36. package/dist/runtime/compaction.service.js +15 -10
  37. package/dist/runtime/context/compaction.d.ts +19 -2
  38. package/dist/runtime/context/compaction.js +23 -2
  39. package/dist/runtime/context/idle-compaction-rules.d.ts +17 -2
  40. package/dist/runtime/context/idle-compaction-rules.js +20 -5
  41. package/dist/runtime/idle-arm.d.ts +12 -2
  42. package/dist/runtime/idle-arm.js +66 -18
  43. package/dist/runtime/idle-compaction-jobs.d.ts +24 -3
  44. package/dist/runtime/idle-compaction.d.ts +11 -3
  45. package/dist/runtime/idle-compaction.js +61 -30
  46. package/dist/runtime/maintenance.d.ts +4 -2
  47. package/dist/runtime/maintenance.js +14 -4
  48. package/dist/runtime/model-call.d.ts +52 -16
  49. package/dist/runtime/model-call.js +71 -24
  50. package/dist/runtime/run-finish.d.ts +12 -3
  51. package/dist/runtime/run-finish.js +14 -7
  52. package/dist/runtime/run-queue.d.ts +5 -2
  53. package/dist/runtime/run-queue.js +7 -4
  54. package/dist/runtime/run-steps.d.ts +4 -1
  55. package/dist/runtime/run-steps.js +9 -2
  56. package/dist/runtime/run-worker.js +4 -2
  57. package/dist/runtime/runtime.module.js +3 -0
  58. package/dist/sandbox/device-sandbox.d.ts +12 -0
  59. package/dist/sandbox/device-sandbox.js +2 -0
  60. package/dist/sandbox/device-services.d.ts +42 -2
  61. package/dist/sandbox/device-services.js +74 -14
  62. package/dist/sandbox/loopback-expiry.job.d.ts +21 -0
  63. package/dist/sandbox/loopback-expiry.job.js +50 -0
  64. package/dist/sandbox/loopback-grant-records.d.ts +143 -0
  65. package/dist/sandbox/loopback-grant-records.js +239 -0
  66. package/dist/sandbox/loopback-grants.d.ts +119 -0
  67. package/dist/sandbox/loopback-grants.js +454 -0
  68. package/dist/sandbox/loopback-live-ports.d.ts +12 -0
  69. package/dist/sandbox/loopback-live-ports.js +43 -0
  70. package/dist/sandbox/permission-call-types.d.ts +3 -2
  71. package/dist/sandbox/permission-ceiling-writes.js +13 -1
  72. package/dist/sandbox/permission-facts.d.ts +4 -0
  73. package/dist/sandbox/permission-facts.js +4 -0
  74. package/dist/sandbox/review/classifier.d.ts +26 -4
  75. package/dist/sandbox/review/classifier.js +31 -4
  76. package/dist/sandbox/review/index.d.ts +3 -3
  77. package/dist/sandbox/review/index.js +2 -2
  78. package/dist/sandbox/review/permission-candidate.d.ts +5 -4
  79. package/dist/sandbox/review/permission-candidate.js +6 -5
  80. package/dist/sandbox/review/review.service.d.ts +69 -0
  81. package/dist/sandbox/review/review.service.js +117 -0
  82. package/dist/sandbox/sandbox.module.d.ts +1 -1
  83. package/dist/sandbox/sandbox.module.js +13 -2
  84. package/dist/tools/approvals.service.d.ts +82 -6
  85. package/dist/tools/approvals.service.js +233 -11
  86. package/dist/tools/call-scope.d.ts +9 -1
  87. package/dist/tools/loopback-asks.d.ts +52 -0
  88. package/dist/tools/loopback-asks.js +70 -0
  89. package/dist/tools/network-asks.d.ts +2 -1
  90. package/dist/tools/network-asks.js +10 -5
  91. package/dist/tools/pipeline.d.ts +59 -3
  92. package/dist/tools/pipeline.js +403 -40
  93. package/dist/tools/tools.module.js +3 -0
  94. package/package.json +2 -2
  95. package/src/migrations/0199_device_loopback_grants.sql +59 -0
  96. package/src/migrations/0200_runs_idle_mode.sql +4 -0
@@ -8,9 +8,10 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
8
  return function (target, key) { decorator(target, key, paramIndex); }
9
9
  };
10
10
  import { randomBytes } from "node:crypto";
11
- import { DEVICE_SERVICE_ROLL_CHECK, DeviceAccessError, deviceServiceFilesDigest, deviceServiceId, parseRollCheck, parseToolKey, ToolError, } from "@capybara-hq/plugin-sdk";
11
+ import { DEVICE_SERVICE_ROLL_CHECK, DeviceAccessError, deviceServiceFilesDigest, deviceServiceId, isLoopbackGrantHost, parseRollCheck, parseToolKey, ToolError, } from "@capybara-hq/plugin-sdk";
12
12
  import { Inject, Injectable } from "@nestjs/common";
13
13
  import { sql } from "kysely";
14
+ import { unattendedRunOf } from "../automations/unattended.js";
14
15
  import { DeviceAccess } from "../devices/access.js";
15
16
  import { ConversationDevices } from "../devices/conversation-devices.js";
16
17
  import { DevicesService } from "../devices/devices.service.js";
@@ -20,11 +21,16 @@ import { ExtensionRegistry } from "../extensions/registry.js";
20
21
  import { audit } from "../identity/audit.js";
21
22
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
22
23
  import { KernelDb } from "../infra/database/kernel-db.js";
24
+ import { TransactionHost } from "../infra/database/transaction-host.js";
25
+ import { Transactional } from "../infra/database/transactional.decorator.js";
23
26
  import { KERNEL_LOGGER, REDIS } from "../infra/tokens.js";
27
+ import { currentExecutionClaim } from "../runtime/run-execution.js";
24
28
  import { rootConversationOf } from "../runtime/subagents/child.js";
25
29
  import { assertServiceSpec, DeviceServices } from "../sandbox/device-services.js";
30
+ import { isDatabasePort, LoopbackGrants, } from "../sandbox/loopback-grants.js";
26
31
  import { DeviceProviders } from "../sandbox/providers.js";
27
- import { CommandReviewService } from "../sandbox/review/review.service.js";
32
+ import { CommandReviewService, LOOPBACK_UNATTENDED_WHY } from "../sandbox/review/review.service.js";
33
+ import { ApprovalsService } from "../tools/approvals.service.js";
28
34
  import { mapSandboxError } from "../tools/builtins/sandbox/common.js";
29
35
  import { attachCallScope, callScopeOf, serviceHostKey, strongerLayer, whileDeviceStarting, } from "../tools/call-scope.js";
30
36
  import { QuestionsService } from "../tools/questions.service.js";
@@ -104,7 +110,12 @@ let DeviceAccessService = class DeviceAccessService {
104
110
  providers;
105
111
  log;
106
112
  registry;
107
- constructor(kdb, redis, config, services, review, devices, access, deviceWrites, questions, providers, log, registry) {
113
+ txHost;
114
+ loopback;
115
+ approvals;
116
+ constructor(kdb, redis, config, services, review, devices, access, deviceWrites, questions, providers, log, registry, txHost, loopback,
117
+ /** A panel grant settles the agent's pending ask for the same port. */
118
+ approvals) {
108
119
  this.kdb = kdb;
109
120
  this.redis = redis;
110
121
  this.config = config;
@@ -117,6 +128,9 @@ let DeviceAccessService = class DeviceAccessService {
117
128
  this.providers = providers;
118
129
  this.log = log;
119
130
  this.registry = registry;
131
+ this.txHost = txHost;
132
+ this.loopback = loopback;
133
+ this.approvals = approvals;
120
134
  }
121
135
  get db() {
122
136
  return this.kdb.db;
@@ -392,8 +406,15 @@ let DeviceAccessService = class DeviceAccessService {
392
406
  * once the handler returns) on the device this call's own `ctx.deviceAccess` calls resolved, if
393
407
  * any. A malformed entry (not a non-empty host with a known layer) is dropped; a host reported
394
408
  * again keeps its most restrictive layer, so a later report never makes it grantable.
409
+ *
410
+ * A loopback refusal (layer `address`, class `loopback`, a loopback grant host, an integer port
411
+ * in 1–65535) of an extension declaring `permissions.deviceAccess.loopbackPorts` also lands as
412
+ * the scope's `loopback` entry (the first such entry of the call wins), naming the service it
413
+ * came from: `opts.service` when declared, else the extension's only declared service; with no
414
+ * such service it does not. Every other port and class is dropped: the entry is an address host
415
+ * like any other.
395
416
  */
396
- reportBlockedHosts(call, hosts, opts) {
417
+ reportBlockedHosts(caller, call, hosts, opts) {
397
418
  assertCallOwner(call);
398
419
  const scope = callScopeOf(call) ?? attachCallScope(call);
399
420
  // a watcher's reports reach no call result: the resumed handler reports what it sees
@@ -408,7 +429,7 @@ let DeviceAccessService = class DeviceAccessService {
408
429
  return;
409
430
  const url = typeof opts?.url === "string" && opts.url.length > 0 ? opts.url : null;
410
431
  if (scope.blocked === null)
411
- scope.blocked = { deviceId: scope.device, hosts: new Map(), url };
432
+ scope.blocked = { deviceId: scope.device, hosts: new Map(), url, loopback: null };
412
433
  else if (url !== null)
413
434
  scope.blocked.url = url;
414
435
  const seen = scope.blocked.hosts;
@@ -417,6 +438,175 @@ let DeviceAccessService = class DeviceAccessService {
417
438
  const had = seen.get(key);
418
439
  seen.set(key, had === undefined ? h.layer : strongerLayer(had, h.layer));
419
440
  }
441
+ if (scope.blocked.loopback !== null || !caller.loopbackPorts)
442
+ return;
443
+ const service = reportedService(caller, opts?.service);
444
+ if (service === null)
445
+ return;
446
+ const entry = valid.find((h) => h.layer === "address" &&
447
+ h.class === "loopback" &&
448
+ isLoopbackGrantHost(h.host) &&
449
+ Number.isInteger(h.port) &&
450
+ h.port >= 1 &&
451
+ h.port <= 65535);
452
+ if (entry === undefined)
453
+ return;
454
+ scope.blocked.loopback = {
455
+ serviceId: deviceServiceId(caller.extension, service),
456
+ host: entry.host,
457
+ port: entry.port,
458
+ };
459
+ }
460
+ /**
461
+ * Grants the scope conversation's root a local port of its device for one service (the owner's
462
+ * click in the panel, source `owner-panel`): owner only, refused with `loopback_unavailable`
463
+ * when the device's outside-sandbox ceilings or its provider do not allow it now
464
+ * (`loopbackRefusal`). The record is written in its own transaction
465
+ * (`LoopbackGrants.grantIn`, which owes the refresh); the running service then gets the live set
466
+ * at once, best effort (the owed refresh job is the backstop).
467
+ */
468
+ async grantLoopbackPort(caller, scope) {
469
+ const { d, key } = await this.loopbackKey(caller, scope, scope.port);
470
+ const unavailable = (why) => new DeviceAccessError("loopback_unavailable", `Port ${scope.port} on the device cannot be opened to the device service ${scope.service}: ${why}.`);
471
+ // a panel click never happens inside a run's execution: a tool step granting itself a port
472
+ // as the owner's panel is refused (its refusal reported with reportBlockedHosts asks instead)
473
+ if (currentExecutionClaim() !== undefined)
474
+ throw unavailable("a tool call cannot grant a local port as the owner's panel; report the refused port with ctx.deviceAccess.reportBlockedHosts so the conversation's permission profile decides");
475
+ // the kernel's own record of the tree's origin: an automation's conversation, or a run of an
476
+ // automation active in it now, has no one to grant a port (the ask's unattended refusal)
477
+ if (await this.unattendedTree(d))
478
+ throw unavailable(LOOPBACK_UNATTENDED_WHY);
479
+ // the ceilings previewCall gives an attended call, read before the grant's transaction
480
+ // (`LoopbackGrants.refusalNow`: a ceiling switched off meanwhile is revoked by the refresh)
481
+ const why = await this.loopback.refusalNow(d.orgId, d.deviceId);
482
+ if (why !== null)
483
+ throw unavailable(why);
484
+ let row;
485
+ try {
486
+ row = await this.grantInTx(key, scope.accountId);
487
+ }
488
+ catch (e) {
489
+ // the conversation was deleted meanwhile
490
+ if (e instanceof ApiError && e.code === "conversation.not_found")
491
+ throw new DeviceAccessError("no_device", "The conversation does not exist.", { cause: e });
492
+ throw e;
493
+ }
494
+ await this.refreshLoopback(d, key.serviceId);
495
+ // the agent's pending ask for the same port is the owner's decision now: its call runs again
496
+ try {
497
+ const { failed } = await this.approvals.settleLoopbackAsks(d.orgId, scope.accountId, key);
498
+ for (const f of failed)
499
+ this.log.warn("a pending loopback ask not settled after a panel grant", {
500
+ deviceId: d.deviceId,
501
+ serviceId: key.serviceId,
502
+ approvalId: f.approvalId,
503
+ err: f.err,
504
+ });
505
+ }
506
+ catch (err) {
507
+ this.log.warn("pending loopback asks not settled after a panel grant", {
508
+ deviceId: d.deviceId,
509
+ serviceId: key.serviceId,
510
+ err,
511
+ });
512
+ }
513
+ return viewOf(row);
514
+ }
515
+ /**
516
+ * Revokes the scope conversation root's grant of the port to the service (owner only); nothing
517
+ * to revoke succeeds. The running service then gets the live set at once, best effort (the
518
+ * owed refresh job is the backstop).
519
+ */
520
+ async revokeLoopbackPort(caller, scope) {
521
+ const { d, key } = await this.loopbackKey(caller, scope, scope.port);
522
+ if (await this.loopback.revoke(key, scope.accountId))
523
+ await this.refreshLoopback(d, key.serviceId);
524
+ }
525
+ /**
526
+ * The live grants of the service held by the scope conversation's root (owner only), by port.
527
+ * None while the tree is unattended ({@link unattendedTree}): a grant the person made is never an
528
+ * unattended run's, so the browser's per-tab check refuses that tab (the grants stay live).
529
+ */
530
+ async loopbackPorts(caller, scope) {
531
+ const { d, key } = await this.loopbackKey(caller, scope, null);
532
+ if (await this.unattendedTree(d))
533
+ return [];
534
+ const rows = await this.loopback.liveForRoot(d.orgId, d.deviceId, key.serviceId, d.rootConversationId);
535
+ return rows.map(viewOf);
536
+ }
537
+ /**
538
+ * The checks every loopback call makes (the extension declares loopback ports and the service,
539
+ * the port is one, the account owns the conversation and its personal device) and the grant key
540
+ * under the conversation's root (`port` 0 for a listing).
541
+ */
542
+ async loopbackKey(caller, scope, port) {
543
+ if (!caller.loopbackPorts)
544
+ throw new DeviceAccessError("loopback_not_declared", "This extension does not declare permissions.deviceAccess.loopbackPorts.");
545
+ assertDeclared(caller, scope.service);
546
+ if (port !== null && !(Number.isInteger(port) && port >= 1 && port <= 65535))
547
+ throw new DeviceAccessError("invalid_request", `${String(port)} is not a port: a loopback port is an integer from 1 to 65535.`);
548
+ const d = await this.scopedDevice(caller, scope);
549
+ return {
550
+ d,
551
+ key: {
552
+ orgId: d.orgId,
553
+ deviceId: d.deviceId,
554
+ serviceId: deviceServiceId(caller.extension, scope.service),
555
+ rootConversationId: d.rootConversationId,
556
+ port: port ?? 0,
557
+ },
558
+ };
559
+ }
560
+ /**
561
+ * Whether the scope's tree is unattended now, by the kernel's own records: its root is an
562
+ * automation's conversation (`automation_id`), or a run of the scope conversation or its root
563
+ * that has not ended serves an automation run with no person joined (`unattendedRunOf`; a trial
564
+ * run is attended).
565
+ */
566
+ async unattendedTree(d) {
567
+ const root = await this.db
568
+ .selectFrom("conversations")
569
+ .select("automation_id")
570
+ .where("id", "=", d.rootConversationId)
571
+ .where("org_id", "=", d.orgId)
572
+ .executeTakeFirst();
573
+ if (root?.automation_id != null)
574
+ return true;
575
+ const runs = await this.db
576
+ .selectFrom("runs as r")
577
+ .innerJoin("conversations as c", "c.id", "r.conversation_id")
578
+ .select("r.id")
579
+ .where("c.org_id", "=", d.orgId)
580
+ .where("r.conversation_id", "in", [d.conversationId, d.rootConversationId])
581
+ .where("r.status", "in", ["queued", "running", "waiting"])
582
+ .where("r.automation_run_id", "is not", null)
583
+ .execute();
584
+ for (const r of runs) {
585
+ const run = await unattendedRunOf(this.db, this.config, d.orgId, r.id);
586
+ if (run !== null && !run.trial)
587
+ return true;
588
+ }
589
+ return false;
590
+ }
591
+ /**
592
+ * The grant in a transaction of its own. `grantIn` locks the root conversation first, so nothing
593
+ * here locks rows the conversation deletion path locks after the conversation.
594
+ */
595
+ grantInTx(key, accountId) {
596
+ return this.loopback.grantIn(key, { source: "owner-panel", actorAccountId: accountId });
597
+ }
598
+ /** Sends the service's live set now when it runs (best effort, logged on failure). */
599
+ async refreshLoopback(d, serviceId) {
600
+ try {
601
+ await this.services.refreshLoopback(d.orgId, d.deviceId, serviceId, AbortSignal.timeout(REFRESH_TIMEOUT_MS));
602
+ }
603
+ catch (err) {
604
+ this.log.warn("device service not refreshed after a loopback grant change", {
605
+ deviceId: d.deviceId,
606
+ serviceId,
607
+ err,
608
+ });
609
+ }
420
610
  }
421
611
  /** A single-use viewer ticket for the service (the person's panel opens `url`). */
422
612
  async streamTicket(caller, scope) {
@@ -480,7 +670,7 @@ let DeviceAccessService = class DeviceAccessService {
480
670
  if (!declared.includes(t.service))
481
671
  return "revoked";
482
672
  try {
483
- const d = await this.scopedDevice({ extension: t.extension, services: [t.service] }, { orgId: t.orgId, accountId: t.accountId, conversationId: t.conversationId });
673
+ const d = await this.scopedDevice({ extension: t.extension, services: [t.service], loopbackPorts: false }, { orgId: t.orgId, accountId: t.accountId, conversationId: t.conversationId });
484
674
  return d.orgId === t.orgId &&
485
675
  d.rootConversationId === t.rootConversationId &&
486
676
  d.deviceId === t.deviceId &&
@@ -665,6 +855,9 @@ let DeviceAccessService = class DeviceAccessService {
665
855
  return rootConversationOf(this.db, conversationId);
666
856
  }
667
857
  };
858
+ __decorate([
859
+ Transactional()
860
+ ], DeviceAccessService.prototype, "grantInTx", null);
668
861
  DeviceAccessService = __decorate([
669
862
  Injectable(),
670
863
  __param(0, Inject(KernelDb)),
@@ -678,9 +871,30 @@ DeviceAccessService = __decorate([
678
871
  __param(8, Inject(QuestionsService)),
679
872
  __param(9, Inject(DeviceProviders)),
680
873
  __param(10, Inject(KERNEL_LOGGER)),
681
- __param(11, Inject(ExtensionRegistry))
874
+ __param(11, Inject(ExtensionRegistry)),
875
+ __param(12, Inject(TransactionHost)),
876
+ __param(13, Inject(LoopbackGrants)),
877
+ __param(14, Inject(ApprovalsService))
682
878
  ], DeviceAccessService);
683
879
  export { DeviceAccessService };
880
+ /** A grant record as the extension sees it. */
881
+ function viewOf(row) {
882
+ return {
883
+ port: row.port,
884
+ source: row.source,
885
+ expiresAt: row.expiresAt,
886
+ database: isDatabasePort(row.port),
887
+ };
888
+ }
889
+ /**
890
+ * The declared service a report came from: `named` when the caller declares it, the caller's only
891
+ * service when it names none, else null.
892
+ */
893
+ function reportedService(caller, named) {
894
+ if (named !== undefined)
895
+ return caller.services.includes(named) ? named : null;
896
+ return caller.services.length === 1 ? caller.services[0] : null;
897
+ }
684
898
  /** A provider's status under the extension's own service name (the provider names the id). */
685
899
  function asNamed(status, name) {
686
900
  return { ...status, name };
@@ -27,6 +27,7 @@ import { OutboxService } from "../infra/outbox/outbox.service.js";
27
27
  import { DeviceReports } from "../sandbox/device-reports.js";
28
28
  import { deviceSideLayer, hostGrantable } from "../sandbox/device-sandbox.js";
29
29
  import { oweDeviceDestroy, SandboxJobs } from "../sandbox/jobs.js";
30
+ import { revokeLoopbackGrantsOfDevice } from "../sandbox/loopback-grant-records.js";
30
31
  import { coversHost } from "../sandbox/modes.js";
31
32
  import { assertAuthorityWriteHeld } from "../sandbox/permission-authority-lock.js";
32
33
  import { hostsNarrowed, needsOpenNetwork, PermissionCeilingWrites, } from "../sandbox/permission-ceiling-writes.js";
@@ -671,6 +672,8 @@ let DevicesService = class DevicesService {
671
672
  .where("device_id", "=", id)
672
673
  .execute();
673
674
  await this.machines.revokeActive(id, "deleted");
675
+ // its loopback port grants end with it (browser loopback port grants design §4)
676
+ await revokeLoopbackGrantsOfDevice(this.db.db, this.outbox, { orgId, deviceId: id });
674
677
  await audit(this.db.db, {
675
678
  actorAccountId: accountId,
676
679
  ...(actorTokenId !== undefined && { actorTokenId }),
package/dist/errors.d.ts CHANGED
@@ -440,6 +440,12 @@ export declare const ERROR_CODES: {
440
440
  readonly "approval.input_leaked": 422;
441
441
  /** Inputs for an approval that asks for none, or for a path it does not ask for. */
442
442
  readonly "approval.inputs_not_expected": 400;
443
+ /**
444
+ * A loopback port ask approved while the device can no longer open a local port to the browser
445
+ * (its outside-sandbox setting, its runtime or its provider), or the service already has the
446
+ * most local ports open: the ask stays pending.
447
+ */
448
+ readonly "approval.loopback_unavailable": 409;
443
449
  readonly "question.not_found": 404;
444
450
  readonly "question.already_answered": 409;
445
451
  readonly "tool_output.not_found": 404;
package/dist/errors.js CHANGED
@@ -440,6 +440,12 @@ export const ERROR_CODES = {
440
440
  "approval.input_leaked": 422,
441
441
  /** Inputs for an approval that asks for none, or for a path it does not ask for. */
442
442
  "approval.inputs_not_expected": 400,
443
+ /**
444
+ * A loopback port ask approved while the device can no longer open a local port to the browser
445
+ * (its outside-sandbox setting, its runtime or its provider), or the service already has the
446
+ * most local ports open: the ask stays pending.
447
+ */
448
+ "approval.loopback_unavailable": 409,
443
449
  "question.not_found": 404,
444
450
  "question.already_answered": 409,
445
451
  "tool_output.not_found": 404,
@@ -73,10 +73,13 @@ export interface PermissionSet {
73
73
  /**
74
74
  * The device services the extension runs in conversations' devices
75
75
  * (`permissions.deviceAccess`, browser use spec §7): one blocking key per service. Absent when
76
- * not declared (and in older snapshots).
76
+ * not declared (and in older snapshots). `loopbackPorts` (browser loopback port grants design):
77
+ * its services may be granted local ports of the device, one blocking key; present only when
78
+ * declared true.
77
79
  */
78
80
  deviceAccess?: {
79
81
  services: string[];
82
+ loopbackPorts?: true;
80
83
  };
81
84
  /**
82
85
  * The event types the extension may emit (`permissions.triggers.emit`, collaboration spec
@@ -152,6 +155,7 @@ export declare function buildPermissionSet(input: {
152
155
  * `permissions.http.<access>:<METHOD> <path>` (`permissions.http.public:POST /events`),
153
156
  * `ui.view:tasks`, `ui.embed:board`, `permissions.client`, `ui.component:hud`,
154
157
  * `permissions.dialin:capybara-device/6`, `permissions.deviceaccess:browser`,
158
+ * `permissions.deviceaccess.loopbackports`,
155
159
  * `permissions.triggers:item.created`, `permissions.inbox`.
156
160
  * Tolerates old snapshots missing fields (read as empty), so format changes never throw.
157
161
  */
@@ -177,6 +181,12 @@ export declare const DIAL_IN_KEY_PREFIX = "permissions.dialin:";
177
181
  * catalog permission keys require (`PERMISSION_KEY_RE`).
178
182
  */
179
183
  export declare const DEVICE_ACCESS_KEY_PREFIX = "permissions.deviceaccess:";
184
+ /**
185
+ * Permission key of loopback port grants (`permissions.deviceAccess.loopbackPorts: true`, browser
186
+ * loopback port grants design): sensitive and blocking, so an approved extension never gains it on
187
+ * upgrade without approval again. Recorded only when declared.
188
+ */
189
+ export declare const DEVICE_LOOPBACK_PORTS_KEY = "permissions.deviceaccess.loopbackports";
180
190
  /**
181
191
  * Key prefix of an event type the extension emits (`permissions.triggers.emit`): blocking, not
182
192
  * sensitive (an event only reaches automations an org built on it, collaboration spec §4.2).
@@ -119,7 +119,12 @@ export function buildPermissionSet(input) {
119
119
  ...(p.dialIn ? { dialIn: { protocol: p.dialIn.protocol } } : {}),
120
120
  // only when declared, likewise
121
121
  ...(p.deviceAccess
122
- ? { deviceAccess: { services: sortedUnique(p.deviceAccess.services) } }
122
+ ? {
123
+ deviceAccess: {
124
+ services: sortedUnique(p.deviceAccess.services),
125
+ ...(p.deviceAccess.loopbackPorts === true && { loopbackPorts: true }),
126
+ },
127
+ }
123
128
  : {}),
124
129
  // only when declared, likewise
125
130
  ...(p.triggers ? { triggers: { emit: sortedUnique(p.triggers.emit) } } : {}),
@@ -138,6 +143,7 @@ export function buildPermissionSet(input) {
138
143
  * `permissions.http.<access>:<METHOD> <path>` (`permissions.http.public:POST /events`),
139
144
  * `ui.view:tasks`, `ui.embed:board`, `permissions.client`, `ui.component:hud`,
140
145
  * `permissions.dialin:capybara-device/6`, `permissions.deviceaccess:browser`,
146
+ * `permissions.deviceaccess.loopbackports`,
141
147
  * `permissions.triggers:item.created`, `permissions.inbox`.
142
148
  * Tolerates old snapshots missing fields (read as empty), so format changes never throw.
143
149
  */
@@ -189,6 +195,8 @@ export function permissionKeys(set) {
189
195
  keys.push(`${DIAL_IN_KEY_PREFIX}${p.dialIn.protocol}`);
190
196
  for (const svc of p.deviceAccess?.services ?? [])
191
197
  keys.push(`${DEVICE_ACCESS_KEY_PREFIX}${svc}`);
198
+ if (p.deviceAccess?.loopbackPorts === true)
199
+ keys.push(DEVICE_LOOPBACK_PORTS_KEY);
192
200
  for (const t of p.triggers?.emit ?? [])
193
201
  keys.push(`${TRIGGERS_KEY_PREFIX}${t}`);
194
202
  if (p.inbox === true)
@@ -224,6 +232,12 @@ export const DIAL_IN_KEY_PREFIX = "permissions.dialin:";
224
232
  * catalog permission keys require (`PERMISSION_KEY_RE`).
225
233
  */
226
234
  export const DEVICE_ACCESS_KEY_PREFIX = "permissions.deviceaccess:";
235
+ /**
236
+ * Permission key of loopback port grants (`permissions.deviceAccess.loopbackPorts: true`, browser
237
+ * loopback port grants design): sensitive and blocking, so an approved extension never gains it on
238
+ * upgrade without approval again. Recorded only when declared.
239
+ */
240
+ export const DEVICE_LOOPBACK_PORTS_KEY = "permissions.deviceaccess.loopbackports";
227
241
  /**
228
242
  * Key prefix of an event type the extension emits (`permissions.triggers.emit`): blocking, not
229
243
  * sensitive (an event only reaches automations an org built on it, collaboration spec §4.2).
@@ -29,11 +29,12 @@ export interface PermissionGroup {
29
29
  * Sensitive reason codes (the UI translates them by code): secrets, public routes, embed routes,
30
30
  * tools, hooks, embedded apps, client code and client components (client extensions spec §5.4: code that runs with
31
31
  * full trust in members' browsers), device services (`device_access`: long-lived processes in
32
- * conversations' devices), and sensitive extension points
32
+ * conversations' devices), loopback port grants (`device_loopback_ports`: its device services may
33
+ * reach local ports of the person's device), and sensitive extension points
33
34
  * ({@link SENSITIVE_EXTENSION_POINTS}; the code is the extension point name without `@<major>`, with
34
35
  * `-` replaced by `_`).
35
36
  */
36
- export type SensitiveReason = "secrets" | "public_routes" | "embed_routes" | "tools" | "hooks" | "ui_embed" | "client_code" | "ui_component" | "channel" | "directory" | "identity_source" | "device_provider" | "object_store" | "context" | "push_provider" | "device_access" | "migration_warnings";
37
+ export type SensitiveReason = "secrets" | "public_routes" | "embed_routes" | "tools" | "hooks" | "ui_embed" | "client_code" | "ui_component" | "channel" | "directory" | "identity_source" | "device_provider" | "object_store" | "context" | "push_provider" | "device_access" | "device_loopback_ports" | "migration_warnings";
37
38
  /** 权限清单里的一项(分组里的一项,或 `added` 里的一个权限键)。 */
38
39
  export interface PermissionItem {
39
40
  value: string;
@@ -1,7 +1,7 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { pluginSchemaName } from "../ctx/create-ctx.js";
3
3
  import { isDestructiveSql, splitSqlStatements } from "../db/sql-statements.js";
4
- import { AGENTS_KEY, CLIENT_KEY, CONVERSATIONS_KEY, DEVICE_ACCESS_KEY_PREFIX, DIAL_IN_KEY_PREFIX, INBOX_KEY, PEOPLE_KEY, permissionKeys, TRIGGERS_KEY_PREFIX, UI_COMPONENT_KEY_PREFIX, WARNINGS_KEY_PREFIX, } from "./permission-set.js";
4
+ import { AGENTS_KEY, CLIENT_KEY, CONVERSATIONS_KEY, DEVICE_ACCESS_KEY_PREFIX, DEVICE_LOOPBACK_PORTS_KEY, DIAL_IN_KEY_PREFIX, INBOX_KEY, PEOPLE_KEY, permissionKeys, TRIGGERS_KEY_PREFIX, UI_COMPONENT_KEY_PREFIX, WARNINGS_KEY_PREFIX, } from "./permission-set.js";
5
5
  /**
6
6
  * Review digest: the first 16 hex digits of `sha256(permissionKeys(set).join("\n"))`; with migration
7
7
  * warnings their digest (kind, file, line and statement) is folded in, without warnings it equals the
@@ -40,6 +40,8 @@ export const SENSITIVE_EXTENSION_POINTS = [
40
40
  ];
41
41
  /** The one item of the "client" group (client extensions spec §5.4). */
42
42
  const CLIENT_ITEM = "client code";
43
+ /** The "deviceAccess" group's item of loopback port grants (`permissions.deviceAccess.loopbackPorts`). */
44
+ const LOOPBACK_PORTS_ITEM = "local ports on the device (loopback)";
43
45
  /** The one item of the "inbox" group (collaboration spec §4.9). */
44
46
  const INBOX_ITEM = "personal inbox items";
45
47
  /** The items of the read-only org fact groups. */
@@ -85,6 +87,8 @@ function itemReason(category, item) {
85
87
  return "ui_embed";
86
88
  return undefined;
87
89
  }
90
+ if (category === "deviceAccess" && item === LOOPBACK_PORTS_ITEM)
91
+ return "device_loopback_ports";
88
92
  return ALWAYS_SENSITIVE.has(category) ? CATEGORY_REASON[category] : undefined;
89
93
  }
90
94
  /** Routes of the `http` group: member and admin (the kernel authenticates a person). */
@@ -103,6 +107,8 @@ function keyItem(key) {
103
107
  return { category: "client", item: CLIENT_ITEM };
104
108
  if (key === INBOX_KEY)
105
109
  return { category: "inbox", item: INBOX_ITEM };
110
+ if (key === DEVICE_LOOPBACK_PORTS_KEY)
111
+ return { category: "deviceAccess", item: LOOPBACK_PORTS_ITEM };
106
112
  if (key === AGENTS_KEY)
107
113
  return { category: "agents", item: AGENTS_ITEM };
108
114
  if (key === CONVERSATIONS_KEY)
@@ -202,7 +208,14 @@ export function permissionGroups(set) {
202
208
  // machines that connect to the deployment for this provider's devices, speaking its protocol
203
209
  { category: "dialIn", items: p.dialIn ? [p.dialIn.protocol] : [] },
204
210
  // long-lived services the extension runs in conversations' devices
205
- { category: "deviceAccess", items: p.deviceAccess?.services ?? [] },
211
+ // and, when declared, local ports of the device its services may be granted
212
+ {
213
+ category: "deviceAccess",
214
+ items: [
215
+ ...(p.deviceAccess?.services ?? []),
216
+ ...(p.deviceAccess?.loopbackPorts === true ? [LOOPBACK_PORTS_ITEM] : []),
217
+ ],
218
+ },
206
219
  // the event types it emits for the orgs' event automations (not sensitive)
207
220
  { category: "triggers", items: p.triggers?.emit ?? [] },
208
221
  // personal inbox items for the orgs' members (not sensitive)
@@ -90,6 +90,7 @@ export declare const COMPACTION_SETTINGS: z.ZodObject<{
90
90
  idleEnabled: z.ZodDefault<z.ZodBoolean>;
91
91
  idleMinTokensFloor: z.ZodDefault<z.ZodNumber>;
92
92
  idleMinWindowRatio: z.ZodDefault<z.ZodNumber>;
93
+ idleDelayMinutes: z.ZodDefault<z.ZodNumber>;
93
94
  }, z.core.$strip>;
94
95
  export type CompactionSettings = z.infer<typeof COMPACTION_SETTINGS>;
95
96
  /**
@@ -106,6 +107,7 @@ export declare const COMPACTION_SETTINGS_PARTIAL: z.ZodObject<{
106
107
  idleEnabled: z.ZodOptional<z.ZodBoolean>;
107
108
  idleMinTokensFloor: z.ZodOptional<z.ZodNumber>;
108
109
  idleMinWindowRatio: z.ZodOptional<z.ZodNumber>;
110
+ idleDelayMinutes: z.ZodOptional<z.ZodNumber>;
109
111
  }, z.core.$strip>;
110
112
  /**
111
113
  * The patch form both settings writers take: the partial form above, strict, so a misspelled
@@ -121,6 +123,7 @@ export declare const COMPACTION_SETTINGS_PATCH: z.ZodObject<{
121
123
  idleEnabled: z.ZodOptional<z.ZodBoolean>;
122
124
  idleMinTokensFloor: z.ZodOptional<z.ZodNumber>;
123
125
  idleMinWindowRatio: z.ZodOptional<z.ZodNumber>;
126
+ idleDelayMinutes: z.ZodOptional<z.ZodNumber>;
124
127
  }, z.core.$strict>;
125
128
  export type CompactionSettingsPatch = z.infer<typeof COMPACTION_SETTINGS_PARTIAL>;
126
129
  /**
@@ -189,6 +192,7 @@ export declare const DEPLOYMENT_SETTINGS: z.ZodObject<{
189
192
  idleEnabled: z.ZodDefault<z.ZodBoolean>;
190
193
  idleMinTokensFloor: z.ZodDefault<z.ZodNumber>;
191
194
  idleMinWindowRatio: z.ZodDefault<z.ZodNumber>;
195
+ idleDelayMinutes: z.ZodDefault<z.ZodNumber>;
192
196
  }, z.core.$strip>>;
193
197
  promptCache: z.ZodPrefault<z.ZodObject<{
194
198
  longTtl: z.ZodDefault<z.ZodBoolean>;
@@ -299,6 +303,7 @@ export declare const DEPLOYMENT_SETTINGS_PATCH: z.ZodObject<{
299
303
  idleEnabled: z.ZodOptional<z.ZodBoolean>;
300
304
  idleMinTokensFloor: z.ZodOptional<z.ZodNumber>;
301
305
  idleMinWindowRatio: z.ZodOptional<z.ZodNumber>;
306
+ idleDelayMinutes: z.ZodOptional<z.ZodNumber>;
302
307
  }, z.core.$strict>>;
303
308
  promptCache: z.ZodOptional<z.ZodObject<{
304
309
  longTtl: z.ZodOptional<z.ZodBoolean>;
@@ -137,6 +137,7 @@ const COMPACTION_FIELDS = {
137
137
  idleEnabled: z.boolean(),
138
138
  idleMinTokensFloor: z.number().int().min(50_000).max(2_000_000),
139
139
  idleMinWindowRatio: z.number().min(0.1).max(0.9),
140
+ idleDelayMinutes: z.number().int().min(5).max(1440),
140
141
  };
141
142
  /**
142
143
  * Conversation compaction (context compaction spec §4.8): the platform's defaults and the bounds
@@ -153,6 +154,7 @@ export const COMPACTION_SETTINGS = z.object({
153
154
  idleEnabled: COMPACTION_FIELDS.idleEnabled.default(true),
154
155
  idleMinTokensFloor: COMPACTION_FIELDS.idleMinTokensFloor.default(200_000),
155
156
  idleMinWindowRatio: COMPACTION_FIELDS.idleMinWindowRatio.default(0.3),
157
+ idleDelayMinutes: COMPACTION_FIELDS.idleDelayMinutes.default(30),
156
158
  });
157
159
  /**
158
160
  * The partial form the platform and org patches carry: only the given fields, validated against
@@ -180,6 +182,7 @@ export function effectiveCompactionSettings(platform, org) {
180
182
  idleEnabled: org?.idleEnabled ?? platform.idleEnabled,
181
183
  idleMinTokensFloor: org?.idleMinTokensFloor ?? platform.idleMinTokensFloor,
182
184
  idleMinWindowRatio: org?.idleMinWindowRatio ?? platform.idleMinWindowRatio,
185
+ idleDelayMinutes: org?.idleDelayMinutes ?? platform.idleDelayMinutes,
183
186
  };
184
187
  }
185
188
  /**
@@ -882,6 +885,7 @@ let SettingsService = class SettingsService {
882
885
  idleEnabled: compactionPatch.idleEnabled ?? current.compaction.idleEnabled,
883
886
  idleMinTokensFloor: compactionPatch.idleMinTokensFloor ?? current.compaction.idleMinTokensFloor,
884
887
  idleMinWindowRatio: compactionPatch.idleMinWindowRatio ?? current.compaction.idleMinWindowRatio,
888
+ idleDelayMinutes: compactionPatch.idleDelayMinutes ?? current.compaction.idleDelayMinutes,
885
889
  };
886
890
  }
887
891
  if (promptCachePatch !== undefined) {
@@ -574,6 +574,20 @@ export declare const OUTBOX_JOBS: {
574
574
  readonly removeOnFail: true;
575
575
  };
576
576
  };
577
+ readonly "device-loopback-refresh": {
578
+ readonly queue: "cap-kernel-maintenance";
579
+ readonly idempotent: "the refresh sends the whole live set to an ifRunning ensure; a repeat sends the same set and the machine keeps the service";
580
+ readonly processedIn: "packages/kernel/src/runtime/maintenance.ts";
581
+ readonly opts: {
582
+ readonly attempts: 3;
583
+ readonly backoff: {
584
+ readonly type: "exponential";
585
+ readonly delay: 5000;
586
+ };
587
+ readonly removeOnComplete: true;
588
+ readonly removeOnFail: true;
589
+ };
590
+ };
577
591
  readonly "hook-run-lifecycle": {
578
592
  readonly queue: "cap-kernel-lifecycle";
579
593
  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";
@@ -523,6 +523,20 @@ export const OUTBOX_JOBS = {
523
523
  processedIn: "packages/kernel/src/runtime/maintenance.ts",
524
524
  opts: { attempts: 1, removeOnComplete: true, removeOnFail: true },
525
525
  },
526
+ // `sandbox/loopback-grants.ts` LOOPBACK_REFRESH_JOB: owed by a loopback grant, a revoke, the
527
+ // expiry pass, a root's deletion and every revoking ceiling publication, per (device, service),
528
+ // under `loopbackRefreshJobId` (browser loopback port grants design §4)
529
+ "device-loopback-refresh": {
530
+ queue: "cap-kernel-maintenance",
531
+ idempotent: "the refresh sends the whole live set to an ifRunning ensure; a repeat sends the same set and the machine keeps the service",
532
+ processedIn: "packages/kernel/src/runtime/maintenance.ts",
533
+ opts: {
534
+ attempts: 3,
535
+ backoff: { type: "exponential", delay: 5_000 },
536
+ removeOnComplete: true,
537
+ removeOnFail: true,
538
+ },
539
+ },
526
540
  // `extensions/run-lifecycle-owe.ts` RUN_LIFECYCLE_JOB: owed by the transaction that starts a
527
541
  // run, suspends it on a person, resumes it, ends it (finished, failed, aborted) or declines,
528
542
  // expires or gives up on directed work, once per phase of a run (and wait) and plugin
@@ -46,6 +46,11 @@ export const KERNEL_PURPOSES = [
46
46
  * current chat model (a sub-agent's call: the sub-agent's).
47
47
  */
48
48
  { purpose: "web_fetch", kind: "chat", label: { zh: "网页提取", en: "Web page extraction" } },
49
+ /**
50
+ * The compaction summarizer (compaction model spec); unmapped → the model whose next request the
51
+ * summary serves (the conversation's model, or the overflowed rung on the reactive path).
52
+ */
53
+ { purpose: "compaction", kind: "chat", label: { zh: "摘要压缩", en: "Compaction" } },
49
54
  {
50
55
  purpose: "subagent_fast",
51
56
  kind: "chat",
@@ -28,6 +28,7 @@ import { deletePushRegistrationsForSessions } from "../push/registration-cleanup
28
28
  import { MAINTENANCE_QUEUE_NAME } from "../runtime/maintenance-queue.js";
29
29
  import { RunControl } from "../runtime/run-control.js";
30
30
  import { oweDeviceDestroy } from "../sandbox/jobs.js";
31
+ import { revokeLoopbackGrantsOfDevice } from "../sandbox/loopback-grant-records.js";
31
32
  import { PermissionCeilingWrites } from "../sandbox/permission-ceiling-writes.js";
32
33
  import { revokeSharesIn } from "../shares/revoke.js";
33
34
  import { ApprovalsService } from "../tools/approvals.service.js";
@@ -314,8 +315,11 @@ let Offboarding = class Offboarding {
314
315
  .where("deleted_at", "is", null)
315
316
  .returning("id")
316
317
  .execute();
317
- for (const d of devices)
318
+ for (const d of devices) {
318
319
  await oweDeviceDestroy(this.outbox, d.id, orgId);
320
+ // its loopback port grants end with it (browser loopback port grants design §4)
321
+ await revokeLoopbackGrantsOfDevice(this.db.db, this.outbox, { orgId, deviceId: d.id });
322
+ }
319
323
  await this.db
320
324
  .deleteFrom("device_defaults")
321
325
  .where("org_id", "=", orgId)