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

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 (65) hide show
  1. package/dist/catalog/marketplaces.service.d.ts +1 -1
  2. package/dist/channels/actions.js +2 -0
  3. package/dist/channels/cards.d.ts +4 -3
  4. package/dist/channels/cards.js +18 -3
  5. package/dist/channels/phrases.d.ts +15 -0
  6. package/dist/channels/phrases.js +9 -0
  7. package/dist/conversations/conversations.service.js +7 -0
  8. package/dist/conversations/events.d.ts +13 -0
  9. package/dist/conversations/events.js +24 -3
  10. package/dist/ctx/create-ctx.d.ts +1 -1
  11. package/dist/ctx/create-ctx.js +6 -1
  12. package/dist/db/kernel-schema.d.ts +26 -0
  13. package/dist/device-access/device-access.service.d.ts +74 -3
  14. package/dist/device-access/device-access.service.js +221 -7
  15. package/dist/devices/devices.service.js +3 -0
  16. package/dist/errors.d.ts +6 -0
  17. package/dist/errors.js +6 -0
  18. package/dist/extensions/permission-set.d.ts +11 -1
  19. package/dist/extensions/permission-set.js +15 -1
  20. package/dist/extensions/permission-view.d.ts +3 -2
  21. package/dist/extensions/permission-view.js +15 -2
  22. package/dist/infra/outbox/registry.d.ts +14 -0
  23. package/dist/infra/outbox/registry.js +14 -0
  24. package/dist/orgs/offboarding.js +5 -1
  25. package/dist/roles/worker.module.js +3 -0
  26. package/dist/runtime/maintenance.d.ts +4 -2
  27. package/dist/runtime/maintenance.js +14 -4
  28. package/dist/sandbox/device-sandbox.d.ts +12 -0
  29. package/dist/sandbox/device-sandbox.js +2 -0
  30. package/dist/sandbox/device-services.d.ts +42 -2
  31. package/dist/sandbox/device-services.js +74 -14
  32. package/dist/sandbox/loopback-expiry.job.d.ts +21 -0
  33. package/dist/sandbox/loopback-expiry.job.js +50 -0
  34. package/dist/sandbox/loopback-grant-records.d.ts +143 -0
  35. package/dist/sandbox/loopback-grant-records.js +239 -0
  36. package/dist/sandbox/loopback-grants.d.ts +119 -0
  37. package/dist/sandbox/loopback-grants.js +454 -0
  38. package/dist/sandbox/loopback-live-ports.d.ts +12 -0
  39. package/dist/sandbox/loopback-live-ports.js +43 -0
  40. package/dist/sandbox/permission-call-types.d.ts +3 -2
  41. package/dist/sandbox/permission-ceiling-writes.js +13 -1
  42. package/dist/sandbox/permission-facts.d.ts +4 -0
  43. package/dist/sandbox/permission-facts.js +4 -0
  44. package/dist/sandbox/review/classifier.d.ts +26 -4
  45. package/dist/sandbox/review/classifier.js +31 -4
  46. package/dist/sandbox/review/index.d.ts +3 -3
  47. package/dist/sandbox/review/index.js +2 -2
  48. package/dist/sandbox/review/permission-candidate.d.ts +5 -4
  49. package/dist/sandbox/review/permission-candidate.js +6 -5
  50. package/dist/sandbox/review/review.service.d.ts +69 -0
  51. package/dist/sandbox/review/review.service.js +117 -0
  52. package/dist/sandbox/sandbox.module.d.ts +1 -1
  53. package/dist/sandbox/sandbox.module.js +13 -2
  54. package/dist/tools/approvals.service.d.ts +82 -6
  55. package/dist/tools/approvals.service.js +233 -11
  56. package/dist/tools/call-scope.d.ts +9 -1
  57. package/dist/tools/loopback-asks.d.ts +52 -0
  58. package/dist/tools/loopback-asks.js +70 -0
  59. package/dist/tools/network-asks.d.ts +2 -1
  60. package/dist/tools/network-asks.js +10 -5
  61. package/dist/tools/pipeline.d.ts +59 -3
  62. package/dist/tools/pipeline.js +403 -40
  63. package/dist/tools/tools.module.js +3 -0
  64. package/package.json +2 -2
  65. package/src/migrations/0199_device_loopback_grants.sql +59 -0
@@ -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). */
@@ -4,6 +4,7 @@ import { NETWORK_ASK_MAX_HOSTS, NETWORK_HOST_MAX_CHARS } from "../conversations/
4
4
  import { coversHost } from "../sandbox/modes.js";
5
5
  import { ESCALATION_UNATTENDED_WHY } from "../sandbox/review/permission-candidate.js";
6
6
  import { NETWORK_ASK_CANCELLED_NOTE, networkAskHosts, } from "./approvals.service.js";
7
+ import { settledLoopbackNotes } from "./loopback-asks.js";
7
8
  /**
8
9
  * Network asks in the tool pipeline (network ask-to-allow spec §6.2, §6.6–§6.9, §8.3): what a
9
10
  * command's reported refusals turn into (an ask to the device owner, or notes written at once) and
@@ -359,18 +360,22 @@ const NO_OFFER_WHY = "the device's owner changes the device's network on its pag
359
360
  * The note of a settled network ask (spec §6.6): one line per outcome. An approval allows
360
361
  * `detail.grantedHosts` for the run (`once`) or added them to the device's own list (`always`,
361
362
  * applying at `detail.appliesAt`) and declines the hosts left unchecked; `hours` is the ask's own
362
- * wait (created to expiry). Null while it is pending.
363
+ * wait (created to expiry). Null while it is pending. A loopback port ask's notes are
364
+ * {@link settledLoopbackNotes}.
363
365
  */
364
366
  export function settledNetworkNotes(a, hours) {
365
- const asked = a.detail === null ? [] : networkAskHosts(a.detail);
367
+ if (a.detail?.kind === "loopback")
368
+ return settledLoopbackNotes(a, hours);
369
+ const detail = a.detail;
370
+ const asked = detail === null ? [] : networkAskHosts(detail);
366
371
  switch (a.status) {
367
372
  case "approved": {
368
- const granted = a.detail?.grantedHosts ?? asked;
373
+ const granted = detail?.grantedHosts ?? asked;
369
374
  const rest = asked.filter((h) => !granted.includes(h));
370
375
  const notes = [];
371
376
  if (granted.length > 0) {
372
- notes.push(a.scope === "always" && a.detail !== null
373
- ? addedToDeviceNote(granted, a.detail.appliesAt)
377
+ notes.push(a.scope === "always" && detail !== null
378
+ ? addedToDeviceNote(granted, detail.appliesAt)
374
379
  : allowedOnceNote(granted));
375
380
  }
376
381
  if (rest.length > 0)
@@ -19,11 +19,13 @@ import { type SubagentParent, type WaitingFor } from "../runtime/loop.js";
19
19
  import type { DispatchArgs, DispatchOutcome } from "../runtime/subagents/dispatch.js";
20
20
  import { SubagentMessages } from "../runtime/subagents/messages.js";
21
21
  import { SubagentsService } from "../runtime/subagents/subagents.service.js";
22
+ import { LoopbackGrants } from "../sandbox/loopback-grants.js";
22
23
  import { type NetworkRunState } from "../sandbox/network-grants.js";
23
24
  import { SandboxOperationAuthority } from "../sandbox/operation-authority.js";
24
25
  import { PermissionAuthorityLock } from "../sandbox/permission-authority-lock.js";
25
26
  import { PermissionAutoGrants } from "../sandbox/permission-auto-grants.js";
26
27
  import { PermissionCallGrants } from "../sandbox/permission-call-grants.js";
28
+ import { PermissionFacts } from "../sandbox/permission-facts.js";
27
29
  import { type CommandReview } from "../sandbox/review/index.js";
28
30
  import { SandboxService } from "../sandbox/sandbox.service.js";
29
31
  import { ApprovalsService, type NetworkAskDetail } from "./approvals.service.js";
@@ -243,7 +245,7 @@ interface PipelineDeps {
243
245
  readonly breaker: Pick<Breaker, "check" | "failure" | "success">;
244
246
  readonly outputs: Pick<ToolOutputs, "save" | "load">;
245
247
  /** 策略为 `ask` 时建审批;续跑时读该调用的审批结果。 A refused network host: a network ask. */
246
- readonly approvals: Pick<ApprovalsService, "request" | "forCall" | "networkForCall" | "requestNetwork" | "commandForCall" | "requestCommand" | "requestSecureInput" | "secureInputForCall">;
248
+ readonly approvals: Pick<ApprovalsService, "request" | "forCall" | "networkForCall" | "requestNetwork" | "requestLoopback" | "commandForCall" | "requestCommand" | "requestSecureInput" | "secureInputForCall">;
247
249
  /** 处理函数返回 `input_required` 时建输入请求;续跑时读该调用的各轮输入请求。 */
248
250
  readonly questions: Pick<QuestionsService, "ask" | "forCall">;
249
251
  readonly log: Logger;
@@ -382,6 +384,16 @@ export interface ServiceBlocked {
382
384
  hosts: ServiceBlockedHost[];
383
385
  /** The page the refusals came from, when the service said. */
384
386
  url: string | null;
387
+ /**
388
+ * The call's loopback refusal of an extension declaring `permissions.deviceAccess.loopbackPorts`
389
+ * (`CallScope.blocked.loopback`): the service (`<extension>.<name>`), the host and the port. Its
390
+ * host is in `hosts` too, as an address host. Absent: none.
391
+ */
392
+ loopback?: {
393
+ serviceId: string;
394
+ host: string;
395
+ port: number;
396
+ };
385
397
  }
386
398
  export type ExecOutcome =
387
399
  /** 工具返回了结果(可能是工具自己报告的错误,或畸形结果,由渲染阶段处理)。 */
@@ -586,13 +598,20 @@ export declare class ToolPipeline {
586
598
  * result images design §2); absent (hand-built pipelines): images are named as not stored.
587
599
  */
588
600
  private readonly resultImages?;
601
+ /**
602
+ * A device service's loopback port grants (browser loopback port grants); absent (hand-built
603
+ * pipelines): a loopback refusal keeps the address note.
604
+ */
605
+ private readonly loopbackGrants?;
606
+ /** The device's sandbox and its provider's support a loopback grant is checked against. */
607
+ private readonly permissionFacts?;
589
608
  private readonly decide;
590
609
  private readonly deps;
591
610
  constructor(kdb: KernelDb, eventLog: EventLog,
592
611
  /** The `Agent` tool's sub-agent dispatch; absent (tests): `Agent` calls are refused. */
593
612
  subagents: Pick<SubagentsService, "dispatch"> | undefined,
594
613
  /** The message tools between agents; absent (tests): their calls are refused. */
595
- messages: Pick<SubagentMessages, "toChild" | "toParent"> | undefined, registry: Pick<ToolRegistry, "forAgent" | "findConnector" | "handler" | "watcher">, credentials: Pick<Credentials, "injection" | "onUnauthorized">, breaker: Pick<Breaker, "check" | "failure" | "success">, outputs: Pick<ToolOutputs, "save" | "load">, approvals: Pick<ApprovalsService, "request" | "forCall" | "networkForCall" | "requestNetwork" | "commandForCall" | "requestCommand" | "requestSecureInput" | "secureInputForCall">, questions: Pick<QuestionsService, "ask" | "forCall">, config: Pick<KernelConfigService, "get">, log: Logger & Partial<Pick<KernelLogger, "debug">>,
614
+ messages: Pick<SubagentMessages, "toChild" | "toParent"> | undefined, registry: Pick<ToolRegistry, "forAgent" | "findConnector" | "handler" | "watcher">, credentials: Pick<Credentials, "injection" | "onUnauthorized">, breaker: Pick<Breaker, "check" | "failure" | "success">, outputs: Pick<ToolOutputs, "save" | "load">, approvals: Pick<ApprovalsService, "request" | "forCall" | "networkForCall" | "requestNetwork" | "requestLoopback" | "commandForCall" | "requestCommand" | "requestSecureInput" | "secureInputForCall">, questions: Pick<QuestionsService, "ask" | "forCall">, config: Pick<KernelConfigService, "get">, log: Logger & Partial<Pick<KernelLogger, "debug">>,
596
615
  /** Plugin hooks and inline ui contributions; absent (tests): no hooks, cards dropped. */
597
616
  host: Pick<ExtensionHost, "hooks" | "current"> | undefined, drift: Pick<ToolDrift, "onToolsChanged"> | undefined, effective: Pick<EffectiveConfigs, "get">, switches: Pick<OrgToolSwitches, "isToolOff">, txHost: TransactionHost, hooks?: ToolPipelineHooks, networkGrants?: {
598
617
  runState(runId: string, deviceId?: string): Promise<NetworkRunState>;
@@ -616,7 +635,14 @@ export declare class ToolPipeline {
616
635
  * Stores the images a tool result carries as `read` copies of the calling conversation (tool
617
636
  * result images design §2); absent (hand-built pipelines): images are named as not stored.
618
637
  */
619
- resultImages?: Pick<AttachmentsService, "storeRead"> | undefined);
638
+ resultImages?: Pick<AttachmentsService, "storeRead"> | undefined,
639
+ /**
640
+ * A device service's loopback port grants (browser loopback port grants); absent (hand-built
641
+ * pipelines): a loopback refusal keeps the address note.
642
+ */
643
+ loopbackGrants?: Pick<LoopbackGrants, "grantIn" | "forCall" | "liveForRoot"> | undefined,
644
+ /** The device's sandbox and its provider's support a loopback grant is checked against. */
645
+ permissionFacts?: Pick<PermissionFacts, "deviceSandboxFacts"> | undefined);
620
646
  /**
621
647
  * tools 节点:按顺序处理本步 assistant 消息里的全部 `tool_call`,每个调用都以一条 `tool_result` 结束
622
648
  * (之后才回到 prepare 构建下一次请求,保持「已记录调用、未记录结果之间不构建请求」的不变式)。
@@ -712,6 +738,36 @@ export declare class ToolPipeline {
712
738
  * settles (P-D2).
713
739
  */
714
740
  private networkBlocked;
741
+ /** The call's live loopback port grant (null: none, ended, or no grants service). */
742
+ private loopbackGrantOf;
743
+ /**
744
+ * A device service's loopback refusal (browser loopback port grants): the port of the person's
745
+ * own device a service of an extension declaring `permissions.deviceAccess.loopbackPorts` was
746
+ * refused. Refused by the device's ceilings, its provider or an unattended run → a note
747
+ * (`write`). A live grant the service had not applied yet → the call runs again, once. Else the
748
+ * conversation's permission profile decides (`approverForCrossing`, crossing `loopback-port`):
749
+ * Full access grants it, the review model reviews it (allow grants, deny is a note, an unsure
750
+ * answer asks), the person is asked (the run waits, the result kept in the ask). A grant is
751
+ * written with its `permission_reviewed`, the call's display events and its `tool.called` in one
752
+ * transaction, naming this attempt: the call then runs again in the next one (`rerun`), also
753
+ * after a crash. `none`: not decidable here (no device of the call's account, a hand-built
754
+ * pipeline, no facts): the host stays an address host with its note.
755
+ */
756
+ private loopbackBlocked;
757
+ /**
758
+ * A loopback port grant to this call's attempt and what goes with it, in one transaction: the
759
+ * grant first (it reads the root conversation `FOR SHARE`, before the conversation row the
760
+ * appends lock), then `permission_reviewed`, the call's display-only events and its
761
+ * `tool.called`. The call then runs again in the next attempt.
762
+ */
763
+ private grantLoopbackIn;
764
+ /** A review model's loopback verdict that grants nothing (a deny, an unsure answer). */
765
+ private recordLoopbackReview;
766
+ /**
767
+ * A kept result's content within what an ask keeps: output under the spill threshold but over
768
+ * {@link NETWORK_ASK_KEPT_MAX_BYTES} is archived after all.
769
+ */
770
+ private keptContent;
715
771
  /**
716
772
  * A device service's report (the call scope, browser use spec §7.1) on the device the call's
717
773
  * conversation works in (the root conversation's for a sub-agent, as the sandbox tools resolve