@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
@@ -39,16 +39,17 @@ import { rootSurfaceOf } from "../runtime/subagents/child.js";
39
39
  import { SubagentMessages } from "../runtime/subagents/messages.js";
40
40
  import { pairStoppedForks } from "../runtime/subagents/skill-fork.js";
41
41
  import { SubagentsService } from "../runtime/subagents/subagents.service.js";
42
+ import { LoopbackGrants, LoopbackLimitError, loopbackRefusal, } from "../sandbox/loopback-grants.js";
42
43
  import { orgHostOutsideCeiling } from "../sandbox/modes.js";
43
44
  import { NetworkGrants } from "../sandbox/network-grants.js";
44
45
  import { SandboxOperationAuthority } from "../sandbox/operation-authority.js";
45
46
  import { PermissionAuthorityLock } from "../sandbox/permission-authority-lock.js";
46
47
  import { PermissionAutoGrants } from "../sandbox/permission-auto-grants.js";
47
48
  import { PermissionCallGrants } from "../sandbox/permission-call-grants.js";
48
- import { permissionScopeHash } from "../sandbox/permission-facts.js";
49
+ import { PermissionFacts, permissionScopeHash } from "../sandbox/permission-facts.js";
49
50
  import { isSessionGrantableRule, } from "../sandbox/review/index.js";
50
51
  import { approverForCrossing, buildPermissionCandidate, crossingOfCandidate, ESCALATION_RETRY_HINT, ESCALATION_UNATTENDED_WHY, escalationRefusedText, isEscalatedCall, } from "../sandbox/review/permission-candidate.js";
51
- import { CommandReviewService } from "../sandbox/review/review.service.js";
52
+ import { CommandReviewService, LOOPBACK_FULL_ACCESS_REASON, } from "../sandbox/review/review.service.js";
52
53
  import { SandboxService } from "../sandbox/sandbox.service.js";
53
54
  import { skillLoadOfferedIn } from "../skills/catalog.js";
54
55
  import { ApprovalsService, } from "./approvals.service.js";
@@ -62,12 +63,13 @@ import { DEVICE_CODE_PATTERN, deviceCodeIdemKey, GITHUB_DEVICE_LOGIN_URL, } from
62
63
  import { DEVICE_OF_ANOTHER_ACCOUNT_TEXT } from "./builtins/sandbox/device-owner.js";
63
64
  import { SendMessageInput } from "./builtins/send-message.js";
64
65
  import { isAlwaysLoaded, notLoadedText } from "./builtins/tool-search.js";
65
- import { attachCallScope, mergeServiceHosts, stillStartingUnsent, } from "./call-scope.js";
66
+ import { attachCallScope, mergeServiceHosts, serviceHostKey, stillStartingUnsent, } from "./call-scope.js";
66
67
  import { canonicalJson } from "./canonical-json.js";
67
68
  import { CredentialMissing, Credentials } from "./credentials.js";
68
69
  import { ToolDrift } from "./drift.js";
69
70
  import { ElicitationSession } from "./elicitation.js";
70
- import { addressEscalationHint, blockedEventHosts, clipKept, denialHintFor, deviceAskTerms, NETWORK_ASK_KEPT_MAX_BYTES, networkBlockedIdemKey, planNetworkAsk, serviceAskedNote, serviceAskTerms, settledNetworkNotes, withNetworkNotes, } from "./network-asks.js";
71
+ import { loopbackGrantedNote, loopbackNotAppliedNote, loopbackPendingNote, loopbackReviewDeniedNote, planLoopbackAsk, } from "./loopback-asks.js";
72
+ import { addressEscalationHint, blockedEventHosts, clipKept, denialHintFor, deviceAskTerms, MAX_NETWORK_ASKS_PER_RUN, NETWORK_ASK_KEPT_MAX_BYTES, networkBlockedIdemKey, otherAskPendingNote, planNetworkAsk, serviceAskedNote, serviceAskTerms, settledNetworkNotes, tooManyNote, withNetworkNotes, } from "./network-asks.js";
71
73
  import { OrgToolSwitches, toolTurnedOffReason } from "./org-tool-switches.js";
72
74
  import { renderResult, resolveOutputRefs, spillIfLarge, ToolOutputs } from "./outputs.js";
73
75
  import { createDecidePolicy } from "./policy.js";
@@ -500,6 +502,7 @@ function withBlocked(outcome, scope) {
500
502
  deviceId: blocked.deviceId,
501
503
  hosts: [...blocked.hosts].map(([host, layer]) => ({ host, layer })),
502
504
  url: blocked.url,
505
+ ...(blocked.loopback !== null && { loopback: { ...blocked.loopback } }),
503
506
  },
504
507
  }),
505
508
  // a device service launch's review (ctx.deviceAccess), recorded with the call's result
@@ -531,12 +534,26 @@ function carriedOf(rounds) {
531
534
  * another kernel version) is dropped.
532
535
  */
533
536
  function mergeBlocked(a, b) {
537
+ const loopback = validLoopback(b.loopback) ?? validLoopback(a?.loopback);
534
538
  return {
535
539
  deviceId: b.deviceId ?? a?.deviceId ?? null,
536
540
  hosts: mergeServiceHosts(validServiceHosts(a?.hosts), validServiceHosts(b.hosts)),
537
541
  url: b.url ?? a?.url ?? null,
542
+ ...(loopback !== undefined && { loopback }),
538
543
  };
539
544
  }
545
+ /** A well-formed loopback refusal ({@link ServiceBlocked.loopback}); a malformed one is dropped. */
546
+ function validLoopback(l) {
547
+ const v = l;
548
+ return v != null &&
549
+ typeof v.serviceId === "string" &&
550
+ typeof v.host === "string" &&
551
+ Number.isInteger(v.port) &&
552
+ v.port >= 1 &&
553
+ v.port <= 65535
554
+ ? { serviceId: v.serviceId, host: v.host, port: v.port }
555
+ : undefined;
556
+ }
540
557
  /** The well-formed entries of a refused-host list ({@link ServiceBlocked.hosts}). */
541
558
  function validServiceHosts(hosts) {
542
559
  if (!Array.isArray(hosts))
@@ -583,6 +600,27 @@ function serviceRerunAfter(ask) {
583
600
  return null;
584
601
  return d.attempt;
585
602
  }
603
+ /**
604
+ * The attempt of an approved loopback port ask: the call runs again after it whatever became of
605
+ * the grant (the approval is the person's decision; a grant the panel made first, or one that
606
+ * ended since, leaves the re-run to meet the port as it is and report it).
607
+ */
608
+ function loopbackAskRerunAfter(ask) {
609
+ const d = ask?.detail;
610
+ return ask?.status === "approved" && d?.kind === "loopback" ? d.attempt : null;
611
+ }
612
+ /**
613
+ * Every attempt after which the call ran again: a device service's approved network ask
614
+ * ({@link serviceRerunAfter}), an approved loopback port ask ({@link loopbackAskRerunAfter}), or
615
+ * the call's live loopback port grant (Full access or the review model granted the port to the
616
+ * attempt that was refused it).
617
+ */
618
+ function rerunPoints(ask, grant) {
619
+ const points = [serviceRerunAfter(ask), loopbackAskRerunAfter(ask), grant?.attempt ?? null];
620
+ return new Set(points.filter((p) => p !== null));
621
+ }
622
+ /** An ask whose approval runs the call again: it belongs to the attempt that asked. */
623
+ const asksPerAttempt = (ask) => ask.detail?.kind === "service" || ask.detail?.kind === "loopback";
586
624
  /** A builtin result's kernel-internal network report (see `BuiltinResult.networkReport`). */
587
625
  function networkReportOf(result) {
588
626
  const r = result?.networkReport;
@@ -668,6 +706,8 @@ let ToolPipeline = class ToolPipeline {
668
706
  approvalProfile;
669
707
  toolReview;
670
708
  resultImages;
709
+ loopbackGrants;
710
+ permissionFacts;
671
711
  decide;
672
712
  deps;
673
713
  constructor(kdb, eventLog,
@@ -696,7 +736,14 @@ let ToolPipeline = class ToolPipeline {
696
736
  * Stores the images a tool result carries as `read` copies of the calling conversation (tool
697
737
  * result images design §2); absent (hand-built pipelines): images are named as not stored.
698
738
  */
699
- resultImages) {
739
+ resultImages,
740
+ /**
741
+ * A device service's loopback port grants (browser loopback port grants); absent (hand-built
742
+ * pipelines): a loopback refusal keeps the address note.
743
+ */
744
+ loopbackGrants,
745
+ /** The device's sandbox and its provider's support a loopback grant is checked against. */
746
+ permissionFacts) {
700
747
  this.config = config;
701
748
  this.txHost = txHost;
702
749
  this.permissionAuthority = permissionAuthority;
@@ -707,6 +754,8 @@ let ToolPipeline = class ToolPipeline {
707
754
  this.approvalProfile = approvalProfile;
708
755
  this.toolReview = toolReview;
709
756
  this.resultImages = resultImages;
757
+ this.loopbackGrants = loopbackGrants;
758
+ this.permissionFacts = permissionFacts;
710
759
  this.deps = {
711
760
  // the builtins that enter a device on the managed operation route (common.ts
712
761
  // `inToolSandbox`, `inSandboxPreparation`): their review is the permission review, whose
@@ -853,13 +902,18 @@ let ToolPipeline = class ToolPipeline {
853
902
  });
854
903
  return undefined;
855
904
  }
905
+ // the call's network ask (one per call) and its live loopback port grant
906
+ const ask = await this.deps.approvals.networkForCall(ctx.runId, call.id);
907
+ const grant = await this.loopbackGrantOf(ctx.runId, call.id);
856
908
  let attempt = rounds.length + 1;
857
- // a device service's call that ran again after its network ask took one attempt more (browser
858
- // use spec §7.1): input rounds the re-run asked come after it
909
+ // each time the call ran again (after its network ask, browser use spec §7.1, or a loopback
910
+ // grant or ask) took one attempt more: input rounds asked after a re-run come after it, so
911
+ // every re-run point the count has passed adds one, in order
912
+ const reruns = rerunPoints(ask, grant);
859
913
  if (rounds.length > 0) {
860
- const asked = serviceRerunAfter(await this.deps.approvals.networkForCall(ctx.runId, call.id));
861
- if (asked !== null && attempt > asked)
862
- attempt += 1;
914
+ for (const p of [...reruns].sort((a, b) => a - b))
915
+ if (attempt > p)
916
+ attempt += 1;
863
917
  }
864
918
  const resume = last
865
919
  ? {
@@ -869,19 +923,39 @@ let ToolPipeline = class ToolPipeline {
869
923
  }
870
924
  : undefined;
871
925
  let started = await this.deps.eventLog.findByIdem(ctx.conversationId, idem.started(ctx.runId, call.id, attempt));
926
+ // a call that ran again (after a loopback grant or an approved ask) is looked at in its latest
927
+ // attempt: a re-run that asked a network ask of its own resumes from that ask
928
+ while (started?.type === "tool_call_started" && reruns.has(attempt)) {
929
+ const next = await this.deps.eventLog.findByIdem(ctx.conversationId, idem.started(ctx.runId, call.id, attempt + 1));
930
+ if (next?.type !== "tool_call_started")
931
+ break;
932
+ attempt += 1;
933
+ started = next;
934
+ }
872
935
  if (started?.type === "tool_call_started") {
873
936
  // a command that ran and was refused a network host waits for the device owner (network
874
937
  // ask-to-allow spec §6.2, P-D2): pending → wait on; settled → its kept result and the
875
938
  // outcome's note (the command is never run again; its tool.called was audited when it ran).
876
939
  // A device service's ask (browser use spec §7.1) belongs to the attempt that asked; once
877
940
  // the person added its hosts to the device's list the call runs again in the next attempt
878
- const ask = await this.deps.approvals.networkForCall(ctx.runId, call.id);
879
- const askedHere = ask !== null && (ask.detail?.kind !== "service" || ask.detail.attempt === attempt);
880
- if (ask !== null && askedHere) {
881
- const notes = settledNetworkNotes(ask, approvalHours(ask));
941
+ // A loopback port ask (browser loopback port grants) too; a port that Full access or the
942
+ // review model granted to this attempt has no ask: its grant row names the attempt, so the
943
+ // call runs again in the next one, also after a crash between the grant and the re-run
944
+ const askedHere = ask !== null &&
945
+ (!asksPerAttempt(ask) ||
946
+ ask.detail?.attempt === attempt);
947
+ const grantedHere = !askedHere && grant !== null && grant.attempt === attempt;
948
+ if (askedHere || grantedHere) {
949
+ const notes = askedHere && ask !== null
950
+ ? settledNetworkNotes(ask, approvalHours(ask))
951
+ : [loopbackGrantedNote(grant.port)];
882
952
  if (notes === null)
883
953
  return approvalWait(ask);
884
- if (serviceRerunAfter(ask) === null) {
954
+ const rerunsHere = !askedHere ||
955
+ serviceRerunAfter(ask) !== null ||
956
+ loopbackAskRerunAfter(ask) !== null ||
957
+ grant?.attempt === attempt;
958
+ if (askedHere && ask !== null && !rerunsHere) {
885
959
  const kept = ask.detail?.result;
886
960
  // the device code the command printed is carried in the kept result: write its
887
961
  // display-only event here too (a crash before the ask's first write, or an older kept
@@ -901,11 +975,11 @@ let ToolPipeline = class ToolPipeline {
901
975
  }
902
976
  const rerun = await this.deps.eventLog.findByIdem(ctx.conversationId, idem.started(ctx.runId, call.id, attempt + 1));
903
977
  if (rerun?.type !== "tool_call_started") {
904
- // the asked hosts are settled: only an earlier round's launch review is carried
978
+ // the asked hosts are settled: only an earlier round's launch review is carried; a
979
+ // granted loopback port's note goes with the re-run's result
905
980
  const { review: carriedReview } = carriedOf(rounds);
906
- return this.runCall(ctx, call, await resolve(), attempt + 1, resume, {
907
- ...(carriedReview !== undefined && { review: carriedReview }),
908
- });
981
+ const loopback = !askedHere || ask?.detail?.kind === "loopback";
982
+ return this.runCall(ctx, call, await resolve(), attempt + 1, resume, { ...(carriedReview !== undefined && { review: carriedReview }) }, loopback ? { notes, loopbackRerun: true } : {});
909
983
  }
910
984
  // the re-run started and its result was lost: the result is unknown, as below
911
985
  started = rerun;
@@ -952,7 +1026,12 @@ let ToolPipeline = class ToolPipeline {
952
1026
  }
953
1027
  async runCall(ctx, call, resolved, attempt, resume,
954
1028
  /** What earlier input rounds of the call collected for its result ({@link carriedOf}). */
955
- carried = {}) {
1029
+ carried = {},
1030
+ /**
1031
+ * A re-run after a granted loopback port: the notes written after its result, and that it is
1032
+ * the re-run (a port still refused is not asked about again in it).
1033
+ */
1034
+ rerun = {}) {
956
1035
  // the command review's record for this call's result (absent: not reviewed, or no device)
957
1036
  let review;
958
1037
  const fail = async (content, key = call.name, view) => {
@@ -1495,8 +1574,47 @@ let ToolPipeline = class ToolPipeline {
1495
1574
  const scoped = commandReport === undefined && (outcome.kind === "result" || outcome.kind === "error")
1496
1575
  ? await this.ownDeviceReport(ctx, outKey, outcome.blocked)
1497
1576
  : undefined;
1577
+ // the formatted result and its display-only fields, kept by an ask until it settles
1578
+ const keptResult = {
1579
+ text: rendered.text,
1580
+ content: spilled.content,
1581
+ isError: rendered.isError,
1582
+ ...(spilled.outputId !== undefined && { outputId: spilled.outputId }),
1583
+ ...(rendered.contentTypes.length > 0 && { contentTypes: rendered.contentTypes }),
1584
+ ...(display !== undefined && { display }),
1585
+ ...(view !== undefined && { view }),
1586
+ ...(media !== undefined && { media }),
1587
+ ...(review !== undefined && { review }),
1588
+ // carried into the kept result so a resumed run writes the event too (it was written
1589
+ // with `network_blocked` below when the ask was created)
1590
+ ...(loginCode !== undefined && { loginCode }),
1591
+ ...(denialHint !== undefined && { denialHint }),
1592
+ };
1593
+ // a device service's loopback refusal (browser loopback port grants), decided before the other
1594
+ // hosts: the conversation's permission profile grants the port (the call runs again now),
1595
+ // the run waits for the device owner, or a note says why the port stays closed; its host is
1596
+ // then not one of the address hosts below
1597
+ let serviceHosts = scoped?.hosts;
1598
+ let loopbackNotes = [];
1599
+ if (scoped?.loopback !== undefined) {
1600
+ const lb = scoped.loopback;
1601
+ const handled = await this.loopbackBlocked(ctx, call, tool, input, outKey, { deviceId: scoped.deviceId, loopback: lb, url: scoped.url }, attempt, keptResult, rerun.loopbackRerun === true, pre, callAudit);
1602
+ if (handled.kind !== "none") {
1603
+ serviceHosts = scoped.hosts.filter((h) => serviceHostKey(h.host) !== serviceHostKey(lb.host));
1604
+ if (handled.kind === "wait") {
1605
+ if (hooks && hookBase) {
1606
+ fireObserve(hooks, "tool.postExecute", { ...hookBase, isError: rendered.isError, content: handled.content, durationMs }, ctx.signal, this.deps.log);
1607
+ }
1608
+ return handled.wait;
1609
+ }
1610
+ if (handled.kind === "rerun") {
1611
+ return this.runCall(ctx, call, resolved, attempt + 1, resume, { ...(carried.review !== undefined && { review: carried.review }) }, { notes: handled.notes, loopbackRerun: true });
1612
+ }
1613
+ loopbackNotes = handled.notes;
1614
+ }
1615
+ }
1498
1616
  const report = commandReport ??
1499
- (scoped === undefined
1617
+ (scoped === undefined || serviceHosts === undefined || serviceHosts.length === 0
1500
1618
  ? undefined
1501
1619
  : {
1502
1620
  deviceId: scoped.deviceId,
@@ -1504,25 +1622,13 @@ let ToolPipeline = class ToolPipeline {
1504
1622
  // port. The layer is the service's word: it only chooses the note or the ask, and the
1505
1623
  // plan still refuses to ask about a host the device list cannot take (an IP literal
1506
1624
  // or other invalid name is always `address`)
1507
- blocked: scoped.hosts.map(({ host, layer }) => ({ host, port: 443, layer })),
1625
+ blocked: serviceHosts.map(({ host, layer }) => ({ host, port: 443, layer })),
1508
1626
  });
1509
1627
  let content = spilled.content;
1510
1628
  if (report !== undefined) {
1511
- const handled = await this.networkBlocked(ctx, call.id, outKey, input, report, pre, callAudit, {
1512
- text: rendered.text,
1513
- content: spilled.content,
1514
- isError: rendered.isError,
1515
- ...(spilled.outputId !== undefined && { outputId: spilled.outputId }),
1516
- ...(rendered.contentTypes.length > 0 && { contentTypes: rendered.contentTypes }),
1517
- ...(display !== undefined && { display }),
1518
- ...(view !== undefined && { view }),
1519
- ...(media !== undefined && { media }),
1520
- ...(review !== undefined && { review }),
1521
- // carried into the kept result so a resumed run writes the event too (it was written
1522
- // with `network_blocked` below when the ask was created)
1523
- ...(loginCode !== undefined && { loginCode }),
1524
- ...(denialHint !== undefined && { denialHint }),
1525
- }, reviewedRoots.escalation, reviewedRoots.escalationRefusal, scoped === undefined
1629
+ const handled = await this.networkBlocked(ctx, call.id, outKey, input, report, pre, callAudit, loopbackNotes.length === 0
1630
+ ? keptResult
1631
+ : { ...keptResult, content: withNetworkNotes(keptResult.content, loopbackNotes) }, reviewedRoots.escalation, reviewedRoots.escalationRefusal, scoped === undefined
1526
1632
  ? undefined
1527
1633
  : {
1528
1634
  name: tool.source.kind === "plugin" ? tool.source.plugin : tool.key,
@@ -1537,10 +1643,12 @@ let ToolPipeline = class ToolPipeline {
1537
1643
  }
1538
1644
  if (handled.event !== null)
1539
1645
  pre.push(handled.event);
1540
- content = withNetworkNotes(content + denialHintFor(denialHint, handled.addressNote), handled.notes);
1646
+ content = withNetworkNotes(withNetworkNotes(content, loopbackNotes) + denialHintFor(denialHint, handled.addressNote), handled.notes);
1541
1647
  }
1542
1648
  else
1543
- content += denialHintFor(denialHint, undefined);
1649
+ content = withNetworkNotes(content, loopbackNotes) + denialHintFor(denialHint, undefined);
1650
+ // a re-run after a granted loopback port: its note after the result
1651
+ content = withNetworkNotes(content, rerun.notes ?? []);
1544
1652
  await this.writeResult(ctx, call.id, outKey, {
1545
1653
  content,
1546
1654
  isError: rendered.isError,
@@ -2468,6 +2576,251 @@ let ToolPipeline = class ToolPipeline {
2468
2576
  });
2469
2577
  return { kind: "wait", wait: approvalWait(ask), content: kept.content };
2470
2578
  }
2579
+ /** The call's live loopback port grant (null: none, ended, or no grants service). */
2580
+ async loopbackGrantOf(runId, callId) {
2581
+ return (await this.loopbackGrants?.forCall(runId, callId)) ?? null;
2582
+ }
2583
+ /**
2584
+ * A device service's loopback refusal (browser loopback port grants): the port of the person's
2585
+ * own device a service of an extension declaring `permissions.deviceAccess.loopbackPorts` was
2586
+ * refused. Refused by the device's ceilings, its provider or an unattended run → a note
2587
+ * (`write`). A live grant the service had not applied yet → the call runs again, once. Else the
2588
+ * conversation's permission profile decides (`approverForCrossing`, crossing `loopback-port`):
2589
+ * Full access grants it, the review model reviews it (allow grants, deny is a note, an unsure
2590
+ * answer asks), the person is asked (the run waits, the result kept in the ask). A grant is
2591
+ * written with its `permission_reviewed`, the call's display events and its `tool.called` in one
2592
+ * transaction, naming this attempt: the call then runs again in the next one (`rerun`), also
2593
+ * after a crash. `none`: not decidable here (no device of the call's account, a hand-built
2594
+ * pipeline, no facts): the host stays an address host with its note.
2595
+ */
2596
+ async loopbackBlocked(ctx, call, tool, input, toolKey, report, attempt, kept, rerunning, pre, callAudit) {
2597
+ const grants = this.loopbackGrants;
2598
+ const sandboxFacts = this.permissionFacts;
2599
+ const authority = this.permissionAuthority;
2600
+ const devices = this.deps.devices;
2601
+ if (!grants || !sandboxFacts || !authority || !devices)
2602
+ return { kind: "none" };
2603
+ // only the device the call works in, and only its owner's own run
2604
+ const device = await devices.reviewFacts(ctx.orgId, ctx.parent?.rootConversationId ?? ctx.conversationId, ctx.conversationId);
2605
+ if (!device || device.deviceId !== report.deviceId || device.ownerAccountId !== ctx.accountId)
2606
+ return { kind: "none" };
2607
+ const use = {
2608
+ orgId: ctx.orgId,
2609
+ deviceId: device.deviceId,
2610
+ holderConversationId: ctx.conversationId,
2611
+ actor: { accountId: ctx.accountId, conversationId: ctx.conversationId, runId: ctx.runId },
2612
+ };
2613
+ let facts;
2614
+ try {
2615
+ facts = await authority.previewCall(use, { runId: ctx.runId, callId: call.id }, ctx.signal);
2616
+ }
2617
+ catch (err) {
2618
+ ctx.signal.throwIfAborted();
2619
+ this.deps.log.warn("cannot read the facts of a loopback refusal; noted as an address", {
2620
+ runId: ctx.runId,
2621
+ callId: call.id,
2622
+ err,
2623
+ });
2624
+ return { kind: "none" };
2625
+ }
2626
+ const { serviceId, host, port } = report.loopback;
2627
+ const hp = host.includes(":") ? `[${host}]:${port}` : `${host}:${port}`;
2628
+ // the effective profile's facts: an unattended run's escalation refusal names it
2629
+ const sandbox = await sandboxFacts.deviceSandboxFacts(ctx.orgId, device.deviceId);
2630
+ const plan = planLoopbackAsk({ host, port }, loopbackRefusal(sandbox.box, sandbox.support, facts.escalationRefusal), facts.escalationRefusal == null);
2631
+ if (plan.kind === "none")
2632
+ return { kind: "none" };
2633
+ // refused before the live grants are read: an unattended run is never approved by a grant
2634
+ // the person made earlier in the tree (no grant, no rerun). The device's carve-out stays the
2635
+ // union of the service's live grants; refusing an unattended tab is the browser's check
2636
+ if (plan.kind === "refused")
2637
+ return { kind: "write", notes: [plan.note] };
2638
+ const key = {
2639
+ orgId: ctx.orgId,
2640
+ deviceId: device.deviceId,
2641
+ serviceId,
2642
+ rootConversationId: facts.rootConversationId,
2643
+ port,
2644
+ };
2645
+ const live = await grants.liveForRoot(ctx.orgId, device.deviceId, serviceId, facts.rootConversationId);
2646
+ if (live.some((g) => g.port === port)) {
2647
+ // granted already (the panel, an earlier call): the service had not applied it yet, so the
2648
+ // call runs again once; refused again (or granted to this call), its result stands
2649
+ if (rerunning || (await grants.forCall(ctx.runId, call.id)) !== null)
2650
+ return { kind: "write", notes: [loopbackNotAppliedNote(port)] };
2651
+ await this.writeResultIn(ctx, call.id, toolKey, kept, [...pre], callAudit, []);
2652
+ return { kind: "rerun", notes: [] };
2653
+ }
2654
+ // a call that ran again after its grant is not decided again (the port was closed meanwhile)
2655
+ if (rerunning)
2656
+ return { kind: "write", notes: [serviceAskedNote([hp])] };
2657
+ const binding = {
2658
+ orgId: facts.orgId,
2659
+ rootConversationId: facts.rootConversationId,
2660
+ conversationId: facts.conversationId,
2661
+ deviceId: facts.deviceId,
2662
+ accountId: facts.accountId,
2663
+ runId: facts.runId,
2664
+ callId: facts.callId,
2665
+ toolKey: tool.key,
2666
+ specHash: tool.specHash,
2667
+ callInputHash: permissionScopeHash(call.input),
2668
+ resolvedInputHash: permissionScopeHash(input),
2669
+ profile: facts.profile,
2670
+ profileRevision: facts.profileRevision,
2671
+ scopeRevision: facts.scopeRevision,
2672
+ authorityRevision: facts.authorityRevision,
2673
+ };
2674
+ const reviewed = (outcome, reason, decisionSource) => {
2675
+ const candidate = {
2676
+ binding,
2677
+ permissionScope: { writeDirectories: [], hosts: [] },
2678
+ scopeKind: "loopback-port",
2679
+ loopback: { service: serviceId, port },
2680
+ };
2681
+ return {
2682
+ type: "permission_reviewed",
2683
+ runId: ctx.runId,
2684
+ idemKey: `permission_reviewed:loopback:${ctx.runId}:${call.id}:${attempt}`,
2685
+ payload: {
2686
+ ...candidate,
2687
+ candidateHash: permissionScopeHash(candidate),
2688
+ outcome,
2689
+ reason,
2690
+ decisionSource,
2691
+ crossing: "loopback-port",
2692
+ },
2693
+ };
2694
+ };
2695
+ const grant = async (source, reason, decisionSource = source) => {
2696
+ try {
2697
+ await this.grantLoopbackIn(ctx, call.id, toolKey, kept, key, { runId: ctx.runId, callId: call.id, attempt }, source, [reviewed("allow", reason, decisionSource), ...pre], callAudit);
2698
+ }
2699
+ catch (e) {
2700
+ // the service holds the most ports it may: the note says so, nothing was granted
2701
+ if (e instanceof LoopbackLimitError)
2702
+ return {
2703
+ kind: "write",
2704
+ notes: [`[network] ${hp} is a local port on the device. ${e.message}`],
2705
+ };
2706
+ throw e;
2707
+ }
2708
+ return { kind: "rerun", notes: [loopbackGrantedNote(port)] };
2709
+ };
2710
+ const approver = approverForCrossing({
2711
+ profile: facts.profile,
2712
+ crossing: "loopback-port",
2713
+ subAgent: ctx.parent !== undefined,
2714
+ });
2715
+ if (approver === "none")
2716
+ return grant("full-access", LOOPBACK_FULL_ACCESS_REASON);
2717
+ if (approver === "review-model" && this.deps.review?.reviewLoopbackPort) {
2718
+ const verdict = await this.deps.review.reviewLoopbackPort({
2719
+ orgId: ctx.orgId,
2720
+ conversationId: ctx.conversationId,
2721
+ runId: ctx.runId,
2722
+ step: ctx.step,
2723
+ callId: call.id,
2724
+ signal: ctx.signal,
2725
+ accountId: ctx.accountId,
2726
+ agentId: ctx.agentId,
2727
+ agentVersion: ctx.agentVersion,
2728
+ conversationKind: ctx.conversationKind,
2729
+ ...reviewParentOf(ctx.parent),
2730
+ profile: facts.profile,
2731
+ attended: !facts.unattended,
2732
+ refusal: null,
2733
+ service: serviceId,
2734
+ port,
2735
+ url: report.url,
2736
+ database: plan.database,
2737
+ });
2738
+ const source = verdict.by === "classifier" ? "review-model" : "rule";
2739
+ // the review path's grant; its record names who allowed it (a rule allows only under Full
2740
+ // access, decided above, so a rule's allow here is not expected but recorded as one)
2741
+ if (verdict.decision === "allow")
2742
+ return grant("review-model", verdict.reason, source);
2743
+ if (verdict.decision === "deny") {
2744
+ await this.recordLoopbackReview(ctx, reviewed("deny", verdict.reason, source));
2745
+ return { kind: "write", notes: [loopbackReviewDeniedNote(port, verdict.reason)] };
2746
+ }
2747
+ await this.recordLoopbackReview(ctx, reviewed("ask", verdict.reason, source));
2748
+ }
2749
+ // the person: the device's owner, within the run's network asks; one ask per call (a call
2750
+ // that ran again after its network ask is not asked again)
2751
+ if ((await this.deps.approvals.networkForCall(ctx.runId, call.id)) !== null)
2752
+ return { kind: "write", notes: [serviceAskedNote([hp])] };
2753
+ const run = await this.deps.network?.grants.runState(ctx.runId, device.deviceId);
2754
+ if (run?.pending === true)
2755
+ return { kind: "write", notes: [otherAskPendingNote([hp])] };
2756
+ if ((run?.asks ?? 0) >= MAX_NETWORK_ASKS_PER_RUN)
2757
+ return { kind: "write", notes: [tooManyNote([hp])] };
2758
+ const { content, outputId } = await this.keptContent(ctx, call.id, kept);
2759
+ const { text: _text, denialHint: _hint, ...rest } = kept;
2760
+ const result = {
2761
+ ...rest,
2762
+ content: clipKept(content),
2763
+ ...(outputId !== undefined && { outputId }),
2764
+ };
2765
+ // the service's call ran: its display-only events and tool.called now, the result once the
2766
+ // ask settles
2767
+ const written = await this.writeResultIn(ctx, call.id, toolKey, kept, [...pre], callAudit, []);
2768
+ if (written.length > 0)
2769
+ await this.deps.eventLog.notify(ctx.conversationId, Math.max(...written.map((e) => e.seq)));
2770
+ const ask = await this.deps.approvals.requestLoopback({
2771
+ orgId: ctx.orgId,
2772
+ conversationId: ctx.conversationId,
2773
+ runId: ctx.runId,
2774
+ step: ctx.step,
2775
+ callId: call.id,
2776
+ requestedFor: device.ownerAccountId,
2777
+ toolKey,
2778
+ detail: {
2779
+ kind: "loopback",
2780
+ deviceId: device.deviceId,
2781
+ service: serviceId,
2782
+ url: report.url,
2783
+ port,
2784
+ database: plan.database,
2785
+ attempt,
2786
+ result,
2787
+ },
2788
+ });
2789
+ return { kind: "wait", wait: approvalWait(ask), content: loopbackPendingNote(host, port) };
2790
+ }
2791
+ /**
2792
+ * A loopback port grant to this call's attempt and what goes with it, in one transaction: the
2793
+ * grant first (it reads the root conversation `FOR SHARE`, before the conversation row the
2794
+ * appends lock), then `permission_reviewed`, the call's display-only events and its
2795
+ * `tool.called`. The call then runs again in the next attempt.
2796
+ */
2797
+ async grantLoopbackIn(ctx, callId, toolKey, r, key, call, source, events, callAudit) {
2798
+ const grants = this.loopbackGrants;
2799
+ if (!grants)
2800
+ throw new Error("Loopback grants are unavailable");
2801
+ await grants.grantIn(key, { source, actorAccountId: null, call });
2802
+ await this.writeResultIn(ctx, callId, toolKey, r, events, callAudit, []);
2803
+ }
2804
+ /** A review model's loopback verdict that grants nothing (a deny, an unsure answer). */
2805
+ async recordLoopbackReview(ctx, event) {
2806
+ await this.deps.eventLog.appendIn(ctx.conversationId, [event]);
2807
+ }
2808
+ /**
2809
+ * A kept result's content within what an ask keeps: output under the spill threshold but over
2810
+ * {@link NETWORK_ASK_KEPT_MAX_BYTES} is archived after all.
2811
+ */
2812
+ async keptContent(ctx, callId, result) {
2813
+ const { content, outputId } = result;
2814
+ if (Buffer.byteLength(content, "utf8") <= NETWORK_ASK_KEPT_MAX_BYTES || outputId !== undefined)
2815
+ return { content, outputId };
2816
+ const spilled = await spillIfLarge(result.text, { spillChars: 0, previewChars: this.config.get().tools.outputPreviewChars }, (c) => this.deps.outputs.save({
2817
+ orgId: ctx.orgId,
2818
+ conversationId: ctx.conversationId,
2819
+ callId,
2820
+ content: c,
2821
+ }));
2822
+ return { content: spilled.content, outputId: spilled.outputId };
2823
+ }
2471
2824
  /**
2472
2825
  * A device service's report (the call scope, browser use spec §7.1) on the device the call's
2473
2826
  * conversation works in (the root conversation's for a sub-agent, as the sandbox tools resolve
@@ -3294,6 +3647,12 @@ __decorate([
3294
3647
  __decorate([
3295
3648
  Transactional()
3296
3649
  ], ToolPipeline.prototype, "recordPermissionReview", null);
3650
+ __decorate([
3651
+ Transactional()
3652
+ ], ToolPipeline.prototype, "grantLoopbackIn", null);
3653
+ __decorate([
3654
+ Transactional()
3655
+ ], ToolPipeline.prototype, "recordLoopbackReview", null);
3297
3656
  __decorate([
3298
3657
  Transactional()
3299
3658
  ], ToolPipeline.prototype, "writeResultIn", null);
@@ -3339,6 +3698,10 @@ ToolPipeline = __decorate([
3339
3698
  __param(27, Optional()),
3340
3699
  __param(27, Inject(ToolAskReview)),
3341
3700
  __param(28, Optional()),
3342
- __param(28, Inject(AttachmentsService))
3701
+ __param(28, Inject(AttachmentsService)),
3702
+ __param(29, Optional()),
3703
+ __param(29, Inject(LoopbackGrants)),
3704
+ __param(30, Optional()),
3705
+ __param(30, Inject(PermissionFacts))
3343
3706
  ], ToolPipeline);
3344
3707
  export { ToolPipeline };
@@ -31,6 +31,7 @@ import { NetworkGrantsModule } from "../sandbox/network-grants.module.js";
31
31
  import { OperationAuthorityModule } from "../sandbox/operation-authority.module.js";
32
32
  import { PermissionAuthorityModule } from "../sandbox/permission-authority.module.js";
33
33
  import { PermissionCallGrantsModule } from "../sandbox/permission-call-grants.module.js";
34
+ import { PermissionFactsModule } from "../sandbox/permission-facts.module.js";
34
35
  import { SandboxModule } from "../sandbox/sandbox.module.js";
35
36
  import { SkillsModule } from "../skills/skills.module.js";
36
37
  import { StorageModule } from "../storage/storage.module.js";
@@ -73,6 +74,8 @@ ToolsModule = __decorate([
73
74
  PermissionCallGrantsModule,
74
75
  PermissionAuthorityModule,
75
76
  OperationAuthorityModule,
77
+ // the device's sandbox and provider support a loopback port grant is checked against
78
+ PermissionFactsModule,
76
79
  EventLogModule,
77
80
  // the profile that decides an ask addressed to the conversation's person (the profile step)
78
81
  ConversationApprovalProfileModule,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capybara-hq/kernel",
3
- "version": "0.1.0-rc.113",
3
+ "version": "0.1.0-rc.114",
4
4
  "description": "Capybara kernel: config, database, plugin host and HTTP API of the Capybara agent platform",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -66,7 +66,7 @@
66
66
  "yaml": "^2.9.1",
67
67
  "yauzl": "3.4.0",
68
68
  "zod": "^4.6.7",
69
- "@capybara-hq/plugin-sdk": "^0.1.0-rc.89"
69
+ "@capybara-hq/plugin-sdk": "^0.1.0-rc.90"
70
70
  },
71
71
  "devDependencies": {
72
72
  "@langchain/langgraph-checkpoint-validation": "^1.2.0",