@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
@@ -15,6 +15,7 @@ import type { FileCardDetail } from "../platform/file-ref.js";
15
15
  import { type PersonFieldSpec } from "../platform/person-fields.js";
16
16
  import { SealedInputs } from "../platform/sealed-inputs.js";
17
17
  import { RunResume } from "../runtime/run-jobs.js";
18
+ import { LoopbackGrants } from "../sandbox/loopback-grants.js";
18
19
  import { PermissionAuthorityLock } from "../sandbox/permission-authority-lock.js";
19
20
  import { PermissionCallGrants } from "../sandbox/permission-call-grants.js";
20
21
  import type { PermissionCandidate, PermissionEscalation, PermissionExpansion } from "../sandbox/permission-call-types.js";
@@ -108,14 +109,33 @@ export interface ServiceNetworkAskDetail extends NetworkAskDetailBase {
108
109
  /** The call's attempt (`tool_call_started`) that asked: the re-run takes the next one. */
109
110
  attempt: number;
110
111
  }
111
- /** A network ask's `detail`: a command's or a device service's. */
112
- export type NetworkAskDetail = CommandNetworkAskDetail | ServiceNetworkAskDetail;
112
+ /**
113
+ * A device service's loopback port ask (browser loopback port grants): an extension declaring
114
+ * `permissions.deviceAccess.loopbackPorts` whose service was refused a local port of the person's
115
+ * own device. It offers only `session` (a grant held by the conversation's root for 24 hours);
116
+ * approved, the grant is written in the decision's transaction and the call runs again, otherwise
117
+ * its kept result is written with the outcome's note. `service` names the extension whose service
118
+ * asked, `url` the page it was loading when known; `database` marks a well-known database port.
119
+ */
120
+ export interface LoopbackAskDetail extends Omit<NetworkAskDetailBase, "appliesAt" | "grantedHosts" | "outcome"> {
121
+ kind: "loopback";
122
+ service: string;
123
+ url: string | null;
124
+ port: number;
125
+ database: boolean;
126
+ /** The call's attempt (`tool_call_started`) that asked: the re-run takes the next one. */
127
+ attempt: number;
128
+ /** What took effect once approved: the root conversation's grant. */
129
+ outcome?: "session";
130
+ }
131
+ /** A network ask's `detail`: a command's, a device service's, or a loopback port's. */
132
+ export type NetworkAskDetail = CommandNetworkAskDetail | ServiceNetworkAskDetail | LoopbackAskDetail;
113
133
  /** `Omit` over each member of a union. */
114
134
  type OmitEach<T, K extends PropertyKey> = T extends unknown ? Omit<T, K> : never;
115
135
  /** A network ask's detail as the API shows it: without the kept call result. */
116
136
  export type NetworkAskView = OmitEach<NetworkAskDetail, "result">;
117
- /** The hosts a network ask asked about, whichever kind it is. */
118
- export declare function networkAskHosts(detail: Pick<NetworkAskDetail, "hosts" | "kind">): string[];
137
+ /** The hosts a network ask asked about, whichever kind it is (a loopback port ask: none). */
138
+ export declare function networkAskHosts(detail: Pick<CommandNetworkAskDetail, "hosts" | "kind"> | Pick<ServiceNetworkAskDetail, "hosts" | "kind"> | Pick<LoopbackAskDetail, "kind">): string[];
119
139
  /**
120
140
  * A git push ask's `detail` (sandbox git credentials spec §7): the host, the repository
121
141
  * (`<owner>/<repo>`, normalized) and the refs of the push the gateway held, the command that ran
@@ -416,7 +436,7 @@ export interface NetworkAskInput {
416
436
  requestedFor: string;
417
437
  /** The tool key the ask is recorded under: the call's (`Bash` for a command). */
418
438
  toolKey: string;
419
- detail: OmitEach<NetworkAskDetail, "grantedHosts" | "outcome">;
439
+ detail: OmitEach<CommandNetworkAskDetail | ServiceNetworkAskDetail, "grantedHosts" | "outcome">;
420
440
  /**
421
441
  * What the device's provider enforces (device-provider spec §6.3, `networkAskOffer`): `once` (a
422
442
  * run grant) only with per-operation hosts, `always` (add to the device's own list) only when
@@ -424,6 +444,10 @@ export interface NetworkAskInput {
424
444
  */
425
445
  scopes: ("once" | "always")[];
426
446
  }
447
+ /** A new loopback port ask, made by the tool pipeline ({@link ApprovalsService.requestLoopback}). */
448
+ export type LoopbackAskInput = Omit<NetworkAskInput, "detail" | "scopes"> & {
449
+ detail: LoopbackAskDetail;
450
+ };
427
451
  /** The tool key a git ask is recorded under (the push ran in a `Bash` command). */
428
452
  export declare const GIT_ASK_TOOL_KEY = "Bash";
429
453
  /**
@@ -491,6 +515,8 @@ export declare class ApprovalsService {
491
515
  private readonly devices;
492
516
  private readonly permissionLocks?;
493
517
  private readonly permissionGrants?;
518
+ /** A loopback port ask's approval writes the root conversation's grant (absent: refused). */
519
+ private readonly loopback?;
494
520
  constructor(db: KernelDb, config: Pick<KernelConfigService, "get">, eventLog: Pick<EventLog, "appendIn" | "notify">, events: Pick<KernelEvents, "emit">, txHost: TransactionHost, automations: Pick<AutomationStore, "addGrant">,
495
521
  /** A trial approval is kept only for a tool the task may hold as a grant (its agent's tools). */
496
522
  registry: Pick<ToolRegistry, "forAgent">,
@@ -505,7 +531,9 @@ export declare class ApprovalsService {
505
531
  /** A person's entered values are sealed in the decision's transaction (§4.3). */
506
532
  sealed: Pick<SealedInputs, "sealIn">,
507
533
  /** A network ask's "add to this device's list" writes the device's own network list. */
508
- devices: Pick<DevicesService, "lockNetworkAddSubject" | "addNetworkHostsIn">, permissionLocks?: PermissionAuthorityLock | undefined, permissionGrants?: PermissionCallGrants | undefined);
534
+ devices: Pick<DevicesService, "lockNetworkAddSubject" | "addNetworkHostsIn">, permissionLocks?: PermissionAuthorityLock | undefined, permissionGrants?: PermissionCallGrants | undefined,
535
+ /** A loopback port ask's approval writes the root conversation's grant (absent: refused). */
536
+ loopback?: Pick<LoopbackGrants, "grantIn" | "refusalNow" | "liveLockedIn"> | undefined);
509
537
  /**
510
538
  * 新建 pending 审批(`expires_at` = 现在 + `tools.approvalTimeoutHours`)并写 `approval_requested`,同一事务。
511
539
  * 按 (run_id, call_id, attempt) 幂等:已存在则返回已有记录(不覆盖),事件按 `approval_requested:<approvalId>` 幂等。
@@ -531,6 +559,14 @@ export declare class ApprovalsService {
531
559
  * approval of the call follows it). One per call: a second request returns the first.
532
560
  */
533
561
  requestNetwork(input: NetworkAskInput): Promise<ApprovalRecord>;
562
+ /**
563
+ * A loopback port ask (browser loopback port grants): a pending approval of kind `network` for
564
+ * the device owner, offering only `session`, expiring like a tool approval, and its
565
+ * `approval_requested` (the call's tool key, the display-only `loopback`: service, port and
566
+ * whether it is a database port; no `network` field), in one transaction. One per call: a
567
+ * second request returns the first (whatever its kind).
568
+ */
569
+ requestLoopback(input: LoopbackAskInput): Promise<ApprovalRecord>;
534
570
  private requestNetworkIn;
535
571
  /**
536
572
  * A git push ask (sandbox git credentials spec §7): a pending approval of kind `git` for the
@@ -576,6 +612,46 @@ export declare class ApprovalsService {
576
612
  * resumes the run in its transaction and is announced after the commit.
577
613
  */
578
614
  private decideNetwork;
615
+ /**
616
+ * A loopback port ask's decision (browser loopback port grants), under {@link decideNetwork}'s
617
+ * lock and checks (the device owner, a signed-in session, still pending): an approval takes
618
+ * scope `session` and no hosts. The device's ceilings are read again first; refused, the ask
619
+ * stays pending (`approval.loopback_unavailable`). The grant
620
+ * (`LoopbackGrants.grantIn`, source `human`, the call and the attempt that asked) is written in
621
+ * the decision's transaction before its conversation, approval and run rows: the grant reads the
622
+ * root conversation `FOR SHARE` and a conversation's deletion locks its runs after its own row.
623
+ */
624
+ private decideLoopback;
625
+ /**
626
+ * The owner granted a port from the browser panel (`ctx.deviceAccess.grantLoopbackPort`): the
627
+ * pending loopback asks for that port of the same device service in the same conversation tree
628
+ * are approved as the owner's decision (the grant they find is the panel's), so their calls run
629
+ * again now instead of waiting for the approval timeout, and only while the panel's grant is
630
+ * still live (a revoke in the meantime wins). An ask decided meanwhile, or one the owner may no
631
+ * longer decide, is left as it is; any other failure leaves that ask pending and is returned (the
632
+ * caller logs it), and the others are still settled.
633
+ */
634
+ settleLoopbackAsks(orgId: string, accountId: string, key: {
635
+ deviceId: string;
636
+ serviceId: string;
637
+ rootConversationId: string;
638
+ port: number;
639
+ }): Promise<{
640
+ approved: number;
641
+ failed: {
642
+ approvalId: string;
643
+ err: unknown;
644
+ }[];
645
+ }>;
646
+ /**
647
+ * A loopback port ask's approval in one transaction: the tree's root conversation row first
648
+ * (`FOR NO KEY UPDATE`, the order a run's fence takes it in), then the grant, then the decision.
649
+ * Taking the root before the grant's `FOR SHARE` read and its (device, service) lock keeps one
650
+ * lock order with a concurrent panel grant (root share, then that lock): without it the
651
+ * decision held the root shared, the panel waited on the service lock, and the decision's
652
+ * append then waited to update the root behind the panel's share (a deadlock).
653
+ */
654
+ private decideLoopbackIn;
579
655
  /**
580
656
  * A git push ask's decision (sandbox git credentials spec §7): only the asked actor
581
657
  * (`requested_for`) decides, in a signed-in session (a personal access token is refused, as for
@@ -38,6 +38,7 @@ import { checkPersonValue } from "../platform/person-fields.js";
38
38
  import { SealedInputs } from "../platform/sealed-inputs.js";
39
39
  import { RunResume } from "../runtime/run-jobs.js";
40
40
  import { rootConversationOf } from "../runtime/subagents/child.js";
41
+ import { LoopbackGrants, LoopbackLimitError } from "../sandbox/loopback-grants.js";
41
42
  import { PermissionAuthorityLock } from "../sandbox/permission-authority-lock.js";
42
43
  import { PermissionCallGrants } from "../sandbox/permission-call-grants.js";
43
44
  import { isSessionGrantableRule } from "../sandbox/review/types.js";
@@ -48,8 +49,10 @@ import { ToolRegistry } from "./registry.js";
48
49
  export { APPROVAL_DENY_REASON_MAX_CHARS } from "../conversations/events.js";
49
50
  /** `list` 一次最多返回的审批数(收件箱据此判断这个来源是否取满)。 */
50
51
  export const APPROVALS_LIST_MAX = 100;
51
- /** The hosts a network ask asked about, whichever kind it is. */
52
+ /** The hosts a network ask asked about, whichever kind it is (a loopback port ask: none). */
52
53
  export function networkAskHosts(detail) {
54
+ if (detail.kind === "loopback")
55
+ return [];
53
56
  return detail.kind === "service"
54
57
  ? [...detail.hosts]
55
58
  : detail.hosts.map((h) => h.host);
@@ -228,6 +231,7 @@ let ApprovalsService = class ApprovalsService {
228
231
  devices;
229
232
  permissionLocks;
230
233
  permissionGrants;
234
+ loopback;
231
235
  constructor(db, config, eventLog, events, txHost, automations,
232
236
  /** A trial approval is kept only for a tool the task may hold as a grant (its agent's tools). */
233
237
  registry,
@@ -242,7 +246,9 @@ let ApprovalsService = class ApprovalsService {
242
246
  /** A person's entered values are sealed in the decision's transaction (§4.3). */
243
247
  sealed,
244
248
  /** A network ask's "add to this device's list" writes the device's own network list. */
245
- devices, permissionLocks, permissionGrants) {
249
+ devices, permissionLocks, permissionGrants,
250
+ /** A loopback port ask's approval writes the root conversation's grant (absent: refused). */
251
+ loopback) {
246
252
  this.db = db;
247
253
  this.config = config;
248
254
  this.eventLog = eventLog;
@@ -258,6 +264,7 @@ let ApprovalsService = class ApprovalsService {
258
264
  this.devices = devices;
259
265
  this.permissionLocks = permissionLocks;
260
266
  this.permissionGrants = permissionGrants;
267
+ this.loopback = loopback;
261
268
  }
262
269
  /**
263
270
  * 新建 pending 审批(`expires_at` = 现在 + `tools.approvalTimeoutHours`)并写 `approval_requested`,同一事务。
@@ -463,6 +470,28 @@ let ApprovalsService = class ApprovalsService {
463
470
  await this.eventLog.notify(record.conversationId, toSeq);
464
471
  return record;
465
472
  }
473
+ /**
474
+ * A loopback port ask (browser loopback port grants): a pending approval of kind `network` for
475
+ * the device owner, offering only `session`, expiring like a tool approval, and its
476
+ * `approval_requested` (the call's tool key, the display-only `loopback`: service, port and
477
+ * whether it is a database port; no `network` field), in one transaction. One per call: a
478
+ * second request returns the first (whatever its kind).
479
+ */
480
+ async requestLoopback(input) {
481
+ const d = input.detail;
482
+ if (d.kind !== "loopback")
483
+ throw new Error("a loopback port ask has a loopback detail");
484
+ if (!(Number.isInteger(d.port) && d.port >= 1 && d.port <= 65535))
485
+ throw new Error("a loopback port ask names a port from 1 to 65535");
486
+ if (input.toolKey.length === 0)
487
+ throw new Error("a loopback port ask names its call's tool key");
488
+ if (!(Number.isInteger(d.attempt) && d.attempt >= 1))
489
+ throw new Error("a loopback port ask names the attempt that asked");
490
+ const { record, toSeq } = await this.requestNetworkIn({ ...input, scopes: ["session"] });
491
+ if (toSeq !== null)
492
+ await this.eventLog.notify(record.conversationId, toSeq);
493
+ return record;
494
+ }
466
495
  async requestNetworkIn(input) {
467
496
  const hours = this.config.get().tools.approvalTimeoutHours;
468
497
  const t = this.db.db;
@@ -525,7 +554,15 @@ let ApprovalsService = class ApprovalsService {
525
554
  approvalId: rec.id,
526
555
  toolKey: rec.toolKey,
527
556
  expiresAt: rec.expiresAt,
528
- network: { hosts: networkAskHosts(input.detail) },
557
+ ...(input.detail.kind === "loopback"
558
+ ? {
559
+ loopback: {
560
+ service: input.detail.service,
561
+ port: input.detail.port,
562
+ database: input.detail.database,
563
+ },
564
+ }
565
+ : { network: { hosts: networkAskHosts(input.detail) } }),
529
566
  requestedFor: rec.requestedFor,
530
567
  approverRole: null,
531
568
  },
@@ -895,7 +932,9 @@ let ApprovalsService = class ApprovalsService {
895
932
  * approval and run rows; this method's distributed lock stays outside it. Every decision
896
933
  * resumes the run in its transaction and is announced after the commit.
897
934
  */
898
- async decideNetwork(orgId, id, accountId, body, actorTokenId, via) {
935
+ async decideNetwork(orgId, id, accountId, body, actorTokenId, via,
936
+ /** A panel grant settling the ask: approve only while that grant is still live. */
937
+ opts = {}) {
899
938
  const row = await this.db
900
939
  .selectFrom("approvals")
901
940
  .selectAll()
@@ -933,6 +972,8 @@ let ApprovalsService = class ApprovalsService {
933
972
  }
934
973
  if (row.expired)
935
974
  throw new ApiError("approval.already_decided", "Approval has expired");
975
+ if (detail.kind === "loopback")
976
+ return this.decideLoopback(orgId, ask, detail, accountId, body, via, opts.panelGrantOnly);
936
977
  const asked = [...new Set(networkAskHosts(detail))];
937
978
  let network;
938
979
  if (body.decision === "approve") {
@@ -983,6 +1024,155 @@ let ApprovalsService = class ApprovalsService {
983
1024
  await this.announceDecided(decided.record, decided.toSeq);
984
1025
  return decided.record;
985
1026
  }
1027
+ /**
1028
+ * A loopback port ask's decision (browser loopback port grants), under {@link decideNetwork}'s
1029
+ * lock and checks (the device owner, a signed-in session, still pending): an approval takes
1030
+ * scope `session` and no hosts. The device's ceilings are read again first; refused, the ask
1031
+ * stays pending (`approval.loopback_unavailable`). The grant
1032
+ * (`LoopbackGrants.grantIn`, source `human`, the call and the attempt that asked) is written in
1033
+ * the decision's transaction before its conversation, approval and run rows: the grant reads the
1034
+ * root conversation `FOR SHARE` and a conversation's deletion locks its runs after its own row.
1035
+ */
1036
+ async decideLoopback(orgId, ask, detail, accountId, body, via,
1037
+ /**
1038
+ * Settled by the owner's panel grant: the grant is that live row (read `FOR SHARE` in the
1039
+ * decision's transaction), never a new one; a grant revoked meanwhile refuses the approval.
1040
+ */
1041
+ panelGrantOnly = false) {
1042
+ if (body.hosts !== undefined) {
1043
+ throw new ApiError("validation_failed", "A loopback port ask takes no hosts", [
1044
+ { path: "hosts", message: "A loopback port ask takes no hosts" },
1045
+ ]);
1046
+ }
1047
+ const id = ask.id;
1048
+ if (body.decision !== "approve") {
1049
+ const network = { wanted: [], granted: [], outcome: null, via };
1050
+ const decided = await this.decideIn(orgId, id, accountId, body, undefined, network);
1051
+ await this.announceDecided(decided.record, decided.toSeq);
1052
+ return decided.record;
1053
+ }
1054
+ const scope = body.scope ?? "session";
1055
+ if (scope !== "session" || !ask.scopes.includes("session")) {
1056
+ throw new ApiError("approval.scope_not_allowed", `Scope "${scope}" is not allowed for this approval; allowed: ${ask.scopes.join(", ")}`);
1057
+ }
1058
+ const loopback = this.loopback;
1059
+ if (loopback === undefined)
1060
+ throw new Error("Loopback grants are unavailable");
1061
+ const why = await loopback.refusalNow(orgId, detail.deviceId);
1062
+ if (why !== null) {
1063
+ throw new ApiError("approval.loopback_unavailable", `Port ${detail.port} on the device cannot be opened to the browser now: ${why}.`);
1064
+ }
1065
+ const conv = await this.db
1066
+ .selectFrom("conversations")
1067
+ .select("parent_conversation_id")
1068
+ .where("id", "=", ask.conversationId)
1069
+ .where("org_id", "=", orgId)
1070
+ .executeTakeFirst();
1071
+ if (!conv)
1072
+ throw notFound();
1073
+ const rootConversationId = conv.parent_conversation_id === null
1074
+ ? ask.conversationId
1075
+ : await rootConversationOf(this.db.db, conv.parent_conversation_id);
1076
+ const network = { wanted: [], granted: [], outcome: "session", via };
1077
+ const decided = await this.decideLoopbackIn(orgId, id, accountId, body, network, rootConversationId, async () => {
1078
+ const key = {
1079
+ orgId,
1080
+ deviceId: detail.deviceId,
1081
+ serviceId: detail.service,
1082
+ rootConversationId,
1083
+ port: detail.port,
1084
+ };
1085
+ if (panelGrantOnly) {
1086
+ if ((await loopback.liveLockedIn(key)) === null)
1087
+ throw new ApiError("approval.loopback_unavailable", `The grant of port ${detail.port} on the device ended before this approval was settled.`);
1088
+ return;
1089
+ }
1090
+ await loopback.grantIn(key, {
1091
+ source: "human",
1092
+ actorAccountId: accountId,
1093
+ approvalId: id,
1094
+ call: { runId: ask.runId, callId: ask.callId, attempt: detail.attempt },
1095
+ });
1096
+ });
1097
+ await this.announceDecided(decided.record, decided.toSeq);
1098
+ return decided.record;
1099
+ }
1100
+ /**
1101
+ * The owner granted a port from the browser panel (`ctx.deviceAccess.grantLoopbackPort`): the
1102
+ * pending loopback asks for that port of the same device service in the same conversation tree
1103
+ * are approved as the owner's decision (the grant they find is the panel's), so their calls run
1104
+ * again now instead of waiting for the approval timeout, and only while the panel's grant is
1105
+ * still live (a revoke in the meantime wins). An ask decided meanwhile, or one the owner may no
1106
+ * longer decide, is left as it is; any other failure leaves that ask pending and is returned (the
1107
+ * caller logs it), and the others are still settled.
1108
+ */
1109
+ async settleLoopbackAsks(orgId, accountId, key) {
1110
+ const rows = await this.db
1111
+ .selectFrom("approvals")
1112
+ .innerJoin("conversations", "conversations.id", "approvals.conversation_id")
1113
+ .select(["approvals.id", "approvals.conversation_id", "conversations.parent_conversation_id"])
1114
+ .where("approvals.org_id", "=", orgId)
1115
+ .where("approvals.kind", "=", "network")
1116
+ .where("approvals.status", "=", "pending")
1117
+ .where("approvals.requested_for", "=", accountId)
1118
+ .where(sql `approvals.detail->>'kind'`, "=", "loopback")
1119
+ .where(sql `approvals.detail->>'deviceId'`, "=", key.deviceId)
1120
+ .where(sql `approvals.detail->>'service'`, "=", key.serviceId)
1121
+ .where(sql `approvals.detail->>'port'`, "=", String(key.port))
1122
+ .execute();
1123
+ let approved = 0;
1124
+ const failed = [];
1125
+ for (const r of rows) {
1126
+ try {
1127
+ const root = r.parent_conversation_id === null
1128
+ ? r.conversation_id
1129
+ : await rootConversationOf(this.db.db, r.parent_conversation_id);
1130
+ if (root !== key.rootConversationId)
1131
+ continue;
1132
+ await this.decideNetwork(orgId, r.id, accountId, { decision: "approve", scope: "session" }, undefined, "web", { panelGrantOnly: true });
1133
+ approved += 1;
1134
+ }
1135
+ catch (e) {
1136
+ if (e instanceof ApiError &&
1137
+ ["approval.already_decided", "approval.not_found", "approval.not_yours"].includes(e.code))
1138
+ continue;
1139
+ failed.push({ approvalId: r.id, err: e });
1140
+ }
1141
+ }
1142
+ return { approved, failed };
1143
+ }
1144
+ /**
1145
+ * A loopback port ask's approval in one transaction: the tree's root conversation row first
1146
+ * (`FOR NO KEY UPDATE`, the order a run's fence takes it in), then the grant, then the decision.
1147
+ * Taking the root before the grant's `FOR SHARE` read and its (device, service) lock keeps one
1148
+ * lock order with a concurrent panel grant (root share, then that lock): without it the
1149
+ * decision held the root shared, the panel waited on the service lock, and the decision's
1150
+ * append then waited to update the root behind the panel's share (a deadlock).
1151
+ */
1152
+ async decideLoopbackIn(orgId, id, accountId, body, network, rootConversationId, grant) {
1153
+ await this.db.db
1154
+ .selectFrom("conversations")
1155
+ .select("id")
1156
+ .where("id", "=", rootConversationId)
1157
+ .where("org_id", "=", orgId)
1158
+ .forNoKeyUpdate()
1159
+ .execute();
1160
+ try {
1161
+ await grant();
1162
+ }
1163
+ catch (e) {
1164
+ // the conversation was deleted meanwhile
1165
+ if (e instanceof ApiError && e.code === "conversation.not_found")
1166
+ throw notFound();
1167
+ if (e instanceof LoopbackLimitError)
1168
+ throw new ApiError("approval.loopback_unavailable", e.message);
1169
+ throw e;
1170
+ }
1171
+ const o = await this.decideTx(orgId, id, accountId, body, undefined, network);
1172
+ if ("leaked" in o)
1173
+ throw new Error(`approval ${id}: a leak outcome outside a secure input`);
1174
+ return o;
1175
+ }
986
1176
  /**
987
1177
  * A git push ask's decision (sandbox git credentials spec §7): only the asked actor
988
1178
  * (`requested_for`) decides, in a signed-in session (a personal access token is refused, as for
@@ -1285,12 +1475,14 @@ let ApprovalsService = class ApprovalsService {
1285
1475
  deny_reason: reason ?? null,
1286
1476
  ...(network?.outcome != null &&
1287
1477
  before.detail !== null && {
1288
- // what took effect; run grants read grantedHosts
1289
- detail: JSON.stringify({
1290
- ...before.detail,
1291
- grantedHosts: network.granted,
1292
- outcome: network.outcome,
1293
- }),
1478
+ // what took effect; run grants read grantedHosts (a loopback port ask: its grant row)
1479
+ detail: JSON.stringify((before.detail.kind === "loopback"
1480
+ ? { ...before.detail, outcome: "session" }
1481
+ : {
1482
+ ...before.detail,
1483
+ grantedHosts: network.granted,
1484
+ outcome: network.outcome === "always" ? "always" : "once",
1485
+ })),
1294
1486
  }),
1295
1487
  ...(git?.outcome != null &&
1296
1488
  before.git !== null && {
@@ -1393,6 +1585,31 @@ let ApprovalsService = class ApprovalsService {
1393
1585
  },
1394
1586
  },
1395
1587
  ]);
1588
+ if (network !== undefined && before.detail?.kind === "loopback") {
1589
+ // an approval's grant audited itself (`device.loopback_granted`, with this approval's id)
1590
+ if (!approved) {
1591
+ await audit(t, {
1592
+ actorAccountId: accountId,
1593
+ orgId,
1594
+ action: "device.network_denied",
1595
+ target: before.detail.deviceId,
1596
+ detail: {
1597
+ approvalId: id,
1598
+ deviceId: before.detail.deviceId,
1599
+ serviceId: before.detail.service,
1600
+ port: before.detail.port,
1601
+ outcome: "denied",
1602
+ by: accountId,
1603
+ via: network.via,
1604
+ conversationId: before.conversationId,
1605
+ runId: before.runId,
1606
+ ...(reason !== undefined && { reason }),
1607
+ },
1608
+ });
1609
+ }
1610
+ await this.resumes.resumeIn(before.runId, id);
1611
+ return { record: toRecord(updated), toSeq: Math.max(...written.map((e) => e.seq)) };
1612
+ }
1396
1613
  if (network !== undefined && before.detail !== null) {
1397
1614
  const asked = [...new Set(networkAskHosts(before.detail))];
1398
1615
  const refused = asked.filter((h) => !network.wanted.includes(h));
@@ -2146,6 +2363,9 @@ __decorate([
2146
2363
  __decorate([
2147
2364
  WithLock({ key: "network-ask-#{1}", ttl: 60_000, waitTimeout: 45_000 })
2148
2365
  ], ApprovalsService.prototype, "decideNetwork", null);
2366
+ __decorate([
2367
+ Transactional({ propagation: "requires_new" })
2368
+ ], ApprovalsService.prototype, "decideLoopbackIn", null);
2149
2369
  __decorate([
2150
2370
  Transactional({ propagation: "requires_new" })
2151
2371
  ], ApprovalsService.prototype, "decideIn", null);
@@ -2200,6 +2420,8 @@ ApprovalsService = __decorate([
2200
2420
  __param(13, Optional()),
2201
2421
  __param(13, Inject(PermissionAuthorityLock)),
2202
2422
  __param(14, Optional()),
2203
- __param(14, Inject(PermissionCallGrants))
2423
+ __param(14, Inject(PermissionCallGrants)),
2424
+ __param(15, Optional()),
2425
+ __param(15, Inject(LoopbackGrants))
2204
2426
  ], ApprovalsService);
2205
2427
  export { ApprovalsService };
@@ -53,12 +53,20 @@ export interface CallScope {
53
53
  * ({@link strongerLayer}); null when nothing was reported. `deviceId` is the device this call's
54
54
  * own `ctx.deviceAccess` calls resolved, or null when the call made none (the pipeline then asks
55
55
  * about the device the call's conversation works in); `url` is the page the refusals came from,
56
- * when the service said.
56
+ * when the service said. `loopback` is the call's first loopback refusal of an extension that
57
+ * declares `permissions.deviceAccess.loopbackPorts` (its host is in `hosts` too, as an address
58
+ * host): the service it came from (`<extension>.<name>`), the host as reported and the port;
59
+ * null when there was none.
57
60
  */
58
61
  blocked: {
59
62
  deviceId: string | null;
60
63
  hosts: Map<string, NetworkBlockLayer>;
61
64
  url: string | null;
65
+ loopback: {
66
+ serviceId: string;
67
+ host: string;
68
+ port: number;
69
+ } | null;
62
70
  } | null;
63
71
  /**
64
72
  * How many device starts of this call are in progress now (`ctx.deviceAccess.ensureService`:
@@ -0,0 +1,52 @@
1
+ import { type ApprovalRecord } from "./approvals.service.js";
2
+ /** What a reported loopback refusal becomes. */
3
+ export type LoopbackPlan =
4
+ /** No loopback entry in the report. */
5
+ {
6
+ kind: "none";
7
+ }
8
+ /** The device's ceilings or its provider refuse a loopback grant now: the note says why. */
9
+ | {
10
+ kind: "refused";
11
+ note: string;
12
+ }
13
+ /** The permission profile decides: grant at once, the review model, or the person. */
14
+ | {
15
+ kind: "decide";
16
+ port: number;
17
+ host: string;
18
+ database: boolean;
19
+ };
20
+ /**
21
+ * The plan for a call's loopback refusal: `refusal` is why a grant is refused now
22
+ * (`loopbackRefusal`), null when grantable; `escalationAvailable` whether a command of this call
23
+ * could run outside the sandbox (the refusal note then names that remedy).
24
+ */
25
+ export declare function planLoopbackAsk(entry: {
26
+ host: string;
27
+ port: number;
28
+ } | null, refusal: string | null, escalationAvailable: boolean): LoopbackPlan;
29
+ /** Asked: the run waits for the device owner's answer (the call's kept result is written then). */
30
+ export declare const loopbackPendingNote: (host: string, port: number) => string;
31
+ /** Granted (by Full access, the review model or the person): the call ran again. */
32
+ export declare const loopbackGrantedNote: (port: number) => string;
33
+ /**
34
+ * Granted, yet the device service still refused the port: it had not applied the grant yet (a
35
+ * service applies a changed set of ports when it restarts).
36
+ */
37
+ export declare const loopbackNotAppliedNote: (port: number) => string;
38
+ /** Not asked: the ceilings or the provider refuse a loopback grant now. */
39
+ export declare const loopbackRefusedNote: (host: string, port: number, why: string, escalationAvailable: boolean) => string;
40
+ /** Asked and declined by the person. */
41
+ export declare const loopbackDeniedNote: (port: number, reason?: string | null) => string;
42
+ /** Asked, no answer within the approval timeout. */
43
+ export declare const loopbackExpiredNote: (port: number, hours: number) => string;
44
+ /** Declined by the review model (Approve for me, or a Full access sub-agent). */
45
+ export declare const loopbackReviewDeniedNote: (port: number, reason: string) => string;
46
+ /** Asked, the person sent a message instead of answering. */
47
+ export declare const loopbackSkippedNote: (port: number) => string;
48
+ /**
49
+ * The notes of a settled loopback ask (one line per outcome); `hours` is the ask's own wait
50
+ * (created to expiry). Null while it is pending.
51
+ */
52
+ export declare function settledLoopbackNotes(a: ApprovalRecord, hours: number): string[] | null;
@@ -0,0 +1,70 @@
1
+ import { isDatabasePort } from "../sandbox/loopback-grant-records.js";
2
+ import { NETWORK_ASK_CANCELLED_NOTE, } from "./approvals.service.js";
3
+ /**
4
+ * Loopback port asks in the tool pipeline (browser loopback port grants): what a device service's
5
+ * reported loopback refusal turns into (a decision by the conversation's permission profile, or a
6
+ * refusal note written at once) and the model-visible notes. Pure: the pipeline reads the facts,
7
+ * writes the grant and the events.
8
+ */
9
+ /** `host:port`, an IPv6 literal in brackets. */
10
+ const hostPort = (h, p) => (h.includes(":") ? `[${h}]:${p}` : `${h}:${p}`);
11
+ /**
12
+ * The plan for a call's loopback refusal: `refusal` is why a grant is refused now
13
+ * (`loopbackRefusal`), null when grantable; `escalationAvailable` whether a command of this call
14
+ * could run outside the sandbox (the refusal note then names that remedy).
15
+ */
16
+ export function planLoopbackAsk(entry, refusal, escalationAvailable) {
17
+ if (entry === null)
18
+ return { kind: "none" };
19
+ if (refusal !== null)
20
+ return {
21
+ kind: "refused",
22
+ note: loopbackRefusedNote(entry.host, entry.port, refusal, escalationAvailable),
23
+ };
24
+ return {
25
+ kind: "decide",
26
+ port: entry.port,
27
+ host: entry.host,
28
+ database: isDatabasePort(entry.port),
29
+ };
30
+ }
31
+ /** Asked: the run waits for the device owner's answer (the call's kept result is written then). */
32
+ export const loopbackPendingNote = (host, port) => `[network] ${hostPort(host, port)} is a local port on the device. The browser reaches local ports only after the port is approved for this conversation; an approval was requested.`;
33
+ /** Granted (by Full access, the review model or the person): the call ran again. */
34
+ export const loopbackGrantedNote = (port) => `Port ${port} on the device was approved for this conversation.`;
35
+ /**
36
+ * Granted, yet the device service still refused the port: it had not applied the grant yet (a
37
+ * service applies a changed set of ports when it restarts).
38
+ */
39
+ export const loopbackNotAppliedNote = (port) => `[network] Port ${port} on the device is approved for this conversation, but the device service had not applied it yet; it applies when the service restarts. Call the tool again to reach it.`;
40
+ /** Not asked: the ceilings or the provider refuse a loopback grant now. */
41
+ export const loopbackRefusedNote = (host, port, why, escalationAvailable) => `[network] ${hostPort(host, port)} is a local port on the device. Local ports stay closed to the browser because ${why}.${escalationAvailable ? ' A command run outside the sandbox (Bash with sandbox: "escalated") still reaches it.' : ""}`;
42
+ /** Asked and declined by the person. */
43
+ export const loopbackDeniedNote = (port, reason) => `[network] Port ${port} on the device was not approved for this conversation, so the browser cannot reach it.${reason ? ` Reason: ${reason}` : ""}`;
44
+ /** Asked, no answer within the approval timeout. */
45
+ export const loopbackExpiredNote = (port, hours) => `[network] The approval for port ${port} on the device expired after ${hours} hours without an answer, so the browser cannot reach it.`;
46
+ /** Declined by the review model (Approve for me, or a Full access sub-agent). */
47
+ export const loopbackReviewDeniedNote = (port, reason) => `[network] The review declined port ${port} on the device for this conversation: ${reason}`;
48
+ /** Asked, the person sent a message instead of answering. */
49
+ export const loopbackSkippedNote = (port) => `[network] The user sent a message instead of answering, so the browser cannot reach port ${port} on the device.`;
50
+ /**
51
+ * The notes of a settled loopback ask (one line per outcome); `hours` is the ask's own wait
52
+ * (created to expiry). Null while it is pending.
53
+ */
54
+ export function settledLoopbackNotes(a, hours) {
55
+ const port = a.detail?.port ?? 0;
56
+ switch (a.status) {
57
+ case "approved":
58
+ return [loopbackGrantedNote(port)];
59
+ case "denied":
60
+ return [loopbackDeniedNote(port, a.denyReason)];
61
+ case "expired":
62
+ return [loopbackExpiredNote(port, hours)];
63
+ case "skipped":
64
+ return [loopbackSkippedNote(port)];
65
+ case "cancelled":
66
+ return [NETWORK_ASK_CANCELLED_NOTE];
67
+ default:
68
+ return null;
69
+ }
70
+ }
@@ -258,7 +258,8 @@ export declare function planNetworkAsk(blocked: readonly NetworkBlockedHost[], r
258
258
  * The note of a settled network ask (spec §6.6): one line per outcome. An approval allows
259
259
  * `detail.grantedHosts` for the run (`once`) or added them to the device's own list (`always`,
260
260
  * applying at `detail.appliesAt`) and declines the hosts left unchecked; `hours` is the ask's own
261
- * wait (created to expiry). Null while it is pending.
261
+ * wait (created to expiry). Null while it is pending. A loopback port ask's notes are
262
+ * {@link settledLoopbackNotes}.
262
263
  */
263
264
  export declare function settledNetworkNotes(a: ApprovalRecord, hours: number): string[] | null;
264
265
  /** `text` followed by `notes` after a blank line (unchanged without notes). */