@capybara-hq/kernel 0.1.0-rc.84 → 0.1.0-rc.86

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 (157) hide show
  1. package/dist/admin/admin.module.js +5 -0
  2. package/dist/admin/health.service.d.ts +2 -2
  3. package/dist/admin/health.service.js +10 -2
  4. package/dist/catalog/admin-catalog.controller.d.ts +2 -1
  5. package/dist/catalog/admin-catalog.controller.js +2 -1
  6. package/dist/catalog/catalog-content.d.ts +5 -15
  7. package/dist/catalog/catalog-content.js +5 -56
  8. package/dist/catalog/catalog-scope.service.d.ts +3 -3
  9. package/dist/catalog/catalog-scope.service.js +4 -3
  10. package/dist/catalog/catalog.module.d.ts +3 -1
  11. package/dist/catalog/catalog.module.js +14 -1
  12. package/dist/catalog/component-scope.service.d.ts +6 -1
  13. package/dist/catalog/component-scope.service.js +16 -2
  14. package/dist/catalog/job-ids.d.ts +29 -0
  15. package/dist/catalog/job-ids.js +29 -0
  16. package/dist/catalog/jobs.d.ts +12 -3
  17. package/dist/catalog/jobs.js +28 -7
  18. package/dist/catalog/marketplaces.service.d.ts +1 -1
  19. package/dist/catalog/org-catalog.controller.d.ts +2 -30
  20. package/dist/catalog/org-catalog.controller.js +3 -29
  21. package/dist/catalog/org-catalog.schemas.d.ts +9 -46
  22. package/dist/catalog/org-catalog.schemas.js +9 -23
  23. package/dist/catalog/org-catalog.service.js +14 -23
  24. package/dist/catalog/plugin-import.d.ts +21 -0
  25. package/dist/catalog/plugin-import.js +33 -3
  26. package/dist/catalog/plugin-install.d.ts +69 -76
  27. package/dist/catalog/plugin-install.js +156 -234
  28. package/dist/catalog/plugin-upgrade.d.ts +71 -11
  29. package/dist/catalog/plugin-upgrade.js +222 -43
  30. package/dist/catalog/scope-sync.d.ts +22 -20
  31. package/dist/catalog/scope-sync.js +57 -42
  32. package/dist/catalog/template-connector-ensure.d.ts +100 -0
  33. package/dist/catalog/template-connector-ensure.js +285 -0
  34. package/dist/catalog/template-connector-jobs.d.ts +28 -0
  35. package/dist/catalog/template-connector-jobs.js +54 -0
  36. package/dist/catalog/template-connector-reconcile.d.ts +44 -0
  37. package/dist/catalog/template-connector-reconcile.js +114 -0
  38. package/dist/catalog/template-connectors.processor.d.ts +32 -0
  39. package/dist/catalog/template-connectors.processor.js +101 -0
  40. package/dist/channels/cards.d.ts +7 -3
  41. package/dist/channels/cards.js +9 -4
  42. package/dist/channels/phrases.d.ts +10 -0
  43. package/dist/channels/phrases.js +10 -0
  44. package/dist/config/docs.js +1 -1
  45. package/dist/config/schema.d.ts +3 -0
  46. package/dist/config/schema.js +18 -12
  47. package/dist/ctx/create-ctx.d.ts +10 -1
  48. package/dist/ctx/create-ctx.js +42 -2
  49. package/dist/db/kernel-schema.d.ts +2 -1
  50. package/dist/device-access/device-access.module.d.ts +7 -0
  51. package/dist/device-access/device-access.module.js +41 -0
  52. package/dist/device-access/device-access.service.d.ts +142 -0
  53. package/dist/device-access/device-access.service.js +464 -0
  54. package/dist/device-access/token.d.ts +6 -0
  55. package/dist/device-access/token.js +6 -0
  56. package/dist/device-access/viewer-routes.d.ts +45 -0
  57. package/dist/device-access/viewer-routes.js +81 -0
  58. package/dist/device-access/viewer.d.ts +244 -0
  59. package/dist/device-access/viewer.js +844 -0
  60. package/dist/dial-in/access.d.ts +19 -0
  61. package/dist/dial-in/access.js +23 -0
  62. package/dist/dial-in/gateway.d.ts +48 -6
  63. package/dist/dial-in/gateway.js +145 -10
  64. package/dist/dial-in/keys.d.ts +7 -0
  65. package/dist/dial-in/keys.js +7 -0
  66. package/dist/dial-in/routes.d.ts +11 -3
  67. package/dist/dial-in/routes.js +15 -4
  68. package/dist/dial-in/streams.d.ts +58 -0
  69. package/dist/dial-in/streams.js +283 -0
  70. package/dist/errors.d.ts +2 -0
  71. package/dist/errors.js +2 -0
  72. package/dist/extensions/host.d.ts +13 -1
  73. package/dist/extensions/host.js +20 -1
  74. package/dist/extensions/org-config.d.ts +6 -1
  75. package/dist/extensions/org-config.js +15 -2
  76. package/dist/extensions/permission-set.d.ts +15 -1
  77. package/dist/extensions/permission-set.js +13 -1
  78. package/dist/extensions/permission-view.d.ts +6 -4
  79. package/dist/extensions/permission-view.js +6 -1
  80. package/dist/git/gateway.js +3 -1
  81. package/dist/http/error.filter.js +2 -0
  82. package/dist/http/gateway-routes.d.ts +8 -4
  83. package/dist/http/gateway-routes.js +4 -3
  84. package/dist/infra/lock/lock.service.d.ts +5 -1
  85. package/dist/infra/lock/lock.service.js +10 -4
  86. package/dist/infra/outbox/registry.d.ts +28 -0
  87. package/dist/infra/outbox/registry.js +33 -0
  88. package/dist/infra/queue/queue-names.d.ts +1 -1
  89. package/dist/infra/queue/queue-names.js +2 -0
  90. package/dist/infra/throttler/named-throttlers.d.ts +3 -0
  91. package/dist/infra/throttler/named-throttlers.js +16 -0
  92. package/dist/kernel.module.js +3 -0
  93. package/dist/lifecycle/kernel-lifecycle.d.ts +8 -1
  94. package/dist/lifecycle/kernel-lifecycle.js +37 -11
  95. package/dist/orgs/org-owner.d.ts +7 -0
  96. package/dist/orgs/org-owner.js +16 -0
  97. package/dist/platform/operation.d.ts +3 -4
  98. package/dist/platform/ops/connectors.ops.js +8 -1
  99. package/dist/platform/ops/org-plugins.ops.d.ts +0 -9
  100. package/dist/platform/ops/org-plugins.ops.js +18 -235
  101. package/dist/platform/ops/plugins.ops.d.ts +0 -1
  102. package/dist/platform/ops/plugins.ops.js +3 -31
  103. package/dist/roles/gateway-role.d.ts +13 -6
  104. package/dist/roles/gateway-role.js +27 -9
  105. package/dist/roles/gateway.module.d.ts +2 -1
  106. package/dist/roles/gateway.module.js +13 -3
  107. package/dist/roles/worker-role.d.ts +9 -4
  108. package/dist/roles/worker-role.js +18 -5
  109. package/dist/roles/worker.module.d.ts +1 -1
  110. package/dist/roles/worker.module.js +8 -1
  111. package/dist/sandbox/device-services.d.ts +62 -0
  112. package/dist/sandbox/device-services.js +183 -0
  113. package/dist/sandbox/leases.d.ts +18 -1
  114. package/dist/sandbox/leases.js +75 -1
  115. package/dist/sandbox/network-grants.js +5 -2
  116. package/dist/sandbox/sandbox.module.d.ts +2 -1
  117. package/dist/sandbox/sandbox.module.js +5 -2
  118. package/dist/sandbox/sandbox.service.d.ts +44 -1
  119. package/dist/sandbox/sandbox.service.js +142 -5
  120. package/dist/setup/setup-guides.service.d.ts +9 -1
  121. package/dist/setup/setup-guides.service.js +38 -8
  122. package/dist/tools/admin-connectors.d.ts +3 -2
  123. package/dist/tools/admin-connectors.js +5 -4
  124. package/dist/tools/approvals.service.d.ts +45 -20
  125. package/dist/tools/approvals.service.js +19 -9
  126. package/dist/tools/call-scope.d.ts +60 -0
  127. package/dist/tools/call-scope.js +23 -0
  128. package/dist/tools/connector-setup.d.ts +28 -0
  129. package/dist/tools/connector-setup.js +33 -0
  130. package/dist/tools/connector-tools-jobs.d.ts +35 -0
  131. package/dist/tools/connector-tools-jobs.js +40 -0
  132. package/dist/tools/connector-tools.processor.d.ts +32 -0
  133. package/dist/tools/connector-tools.processor.js +97 -0
  134. package/dist/tools/connectors.controller.d.ts +1 -0
  135. package/dist/tools/connectors.schemas.d.ts +1 -0
  136. package/dist/tools/connectors.schemas.js +5 -0
  137. package/dist/tools/connectors.service.d.ts +138 -14
  138. package/dist/tools/connectors.service.js +410 -50
  139. package/dist/tools/credentials.d.ts +35 -0
  140. package/dist/tools/credentials.js +89 -1
  141. package/dist/tools/drift.d.ts +5 -0
  142. package/dist/tools/drift.js +21 -2
  143. package/dist/tools/editable-endpoint.d.ts +23 -0
  144. package/dist/tools/editable-endpoint.js +92 -0
  145. package/dist/tools/network-asks.d.ts +13 -0
  146. package/dist/tools/network-asks.js +26 -2
  147. package/dist/tools/oauth/flow.d.ts +1 -1
  148. package/dist/tools/oauth/flow.js +3 -2
  149. package/dist/tools/pipeline.d.ts +30 -1
  150. package/dist/tools/pipeline.js +299 -59
  151. package/dist/tools/questions.service.d.ts +24 -3
  152. package/dist/tools/questions.service.js +3 -1
  153. package/dist/tools/registry.d.ts +14 -2
  154. package/dist/tools/registry.js +27 -6
  155. package/dist/tools/tools.module.js +4 -0
  156. package/package.json +3 -3
  157. package/src/migrations/0183_connectors_created_by_nullable.sql +5 -0
@@ -7,7 +7,7 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
7
7
  var __param = (this && this.__param) || function (paramIndex, decorator) {
8
8
  return function (target, key) { decorator(target, key, paramIndex); }
9
9
  };
10
- import { ToolError, validateInputForm, validateToolDisplay, } from "@capybara-hq/plugin-sdk";
10
+ import { DeviceAccessError, ToolError, validateInputForm, validateToolDisplay, } from "@capybara-hq/plugin-sdk";
11
11
  import { Inject, Injectable, Optional } from "@nestjs/common";
12
12
  import { sql } from "kysely";
13
13
  import { backgroundMaxSeconds } from "../background/launch.js";
@@ -61,15 +61,16 @@ import { DEVICE_CODE_PATTERN, deviceCodeIdemKey, GITHUB_DEVICE_LOGIN_URL, } from
61
61
  import { DEVICE_OF_ANOTHER_ACCOUNT_TEXT } from "./builtins/sandbox/device-owner.js";
62
62
  import { SendMessageInput } from "./builtins/send-message.js";
63
63
  import { isAlwaysLoaded, notLoadedText } from "./builtins/tool-search.js";
64
+ import { attachCallScope } from "./call-scope.js";
64
65
  import { canonicalJson } from "./canonical-json.js";
65
66
  import { CredentialMissing, Credentials } from "./credentials.js";
66
67
  import { ToolDrift } from "./drift.js";
67
68
  import { ElicitationSession } from "./elicitation.js";
68
- import { addressEscalationHint, blockedEventHosts, clipKept, deviceAskTerms, NETWORK_ASK_KEPT_MAX_BYTES, networkBlockedIdemKey, planNetworkAsk, settledNetworkNotes, withNetworkNotes, } from "./network-asks.js";
69
+ import { addressEscalationHint, blockedEventHosts, clipKept, deviceAskTerms, NETWORK_ASK_KEPT_MAX_BYTES, networkBlockedIdemKey, planNetworkAsk, serviceAskedNote, serviceAskTerms, settledNetworkNotes, withNetworkNotes, } from "./network-asks.js";
69
70
  import { OrgToolSwitches, toolTurnedOffReason } from "./org-tool-switches.js";
70
71
  import { renderResult, resolveOutputRefs, spillIfLarge, ToolOutputs } from "./outputs.js";
71
72
  import { createDecidePolicy } from "./policy.js";
72
- import { QuestionsService } from "./questions.service.js";
73
+ import { QuestionsService, } from "./questions.service.js";
73
74
  import { redactDeep, redactorFor } from "./redact.js";
74
75
  import { ToolRegistry, } from "./registry.js";
75
76
  import { runResourceTool } from "./resources.js";
@@ -207,7 +208,11 @@ export const hookDeniedText = (plugin, reason) => `Tool call blocked by the "${p
207
208
  const invalidFormText = (key, problems) => `Tool ${key} returned an invalid input form: ${problems.join("; ")}.`;
208
209
  const stateTooLargeText = (key) => `Tool ${key} returned input state larger than ${MAX_INPUT_STATE_BYTES / 1024} KB.`;
209
210
  const personalMissingText = (connectorName) => `The user has not connected ${connectorName}. A connect card was shown; ask the user to connect, then retry.`;
210
- const orgMissingText = (connectorName) => `${connectorName} has no organization credential configured; ask an organization admin to set it up.`;
211
+ /**
212
+ * A connector lacking its org input (`needs_config`, plugin pages spec §5.2.1): `Credentials`
213
+ * throws an org `CredentialMissing` before any credential is presented, so the call never opens.
214
+ */
215
+ const ORG_MISSING_TEXT = "This connector needs to be configured by an organization admin before it can be used.";
211
216
  /** Optional provider: the pipeline's {@link ToolPipelineHooks} (tests). */
212
217
  export const TOOL_PIPELINE_HOOKS = Symbol("TOOL_PIPELINE_HOOKS");
213
218
  /** Review usage and hooks retain the same tree ancestry on both review routes. */
@@ -408,6 +413,86 @@ const keptExtras = (kept) => ({
408
413
  ...(kept?.display !== undefined && { display: kept.display }),
409
414
  ...(kept?.view !== undefined && { view: kept.view }),
410
415
  });
416
+ function withBlocked(outcome, scope) {
417
+ if (outcome.kind === "connection_required")
418
+ return outcome;
419
+ const blocked = scope?.blocked;
420
+ const review = scope?.review ?? null;
421
+ return {
422
+ ...outcome,
423
+ ...(blocked != null &&
424
+ blocked.hosts.size > 0 && {
425
+ blocked: { deviceId: blocked.deviceId, hosts: [...blocked.hosts], url: blocked.url },
426
+ }),
427
+ // a device service launch's review (ctx.deviceAccess), recorded with the call's result
428
+ ...(review !== null && { review }),
429
+ };
430
+ }
431
+ /**
432
+ * What a call's earlier input rounds carried for its result ({@link QuestionCarried}): the latest
433
+ * launch review, and every refused host (the latest device and page) in one report.
434
+ */
435
+ function carriedOf(rounds) {
436
+ let review;
437
+ let blocked;
438
+ for (const r of rounds) {
439
+ if (r.carried?.review !== undefined)
440
+ review = r.carried.review;
441
+ const b = r.carried?.blocked;
442
+ if (b !== undefined)
443
+ blocked = mergeBlocked(blocked, b);
444
+ }
445
+ return {
446
+ ...(review !== undefined && { review }),
447
+ ...(blocked !== undefined && { blocked }),
448
+ };
449
+ }
450
+ /** Two refused-host reports of one call as one: the hosts of both, the later device and page. */
451
+ function mergeBlocked(a, b) {
452
+ if (a === undefined)
453
+ return { ...b, hosts: [...b.hosts] };
454
+ return {
455
+ deviceId: b.deviceId ?? a.deviceId,
456
+ hosts: [...new Set([...a.hosts, ...b.hosts])],
457
+ url: b.url ?? a.url,
458
+ };
459
+ }
460
+ /**
461
+ * The outcome with what earlier input rounds carried: their launch review when this round
462
+ * reviewed none, their refused hosts merged before this round's.
463
+ */
464
+ function withCarried(outcome, carried) {
465
+ if (outcome.kind === "connection_required")
466
+ return outcome;
467
+ if (carried.review === undefined && carried.blocked === undefined)
468
+ return outcome;
469
+ const blocked = carried.blocked === undefined
470
+ ? outcome.blocked
471
+ : outcome.blocked === undefined
472
+ ? carried.blocked
473
+ : mergeBlocked(carried.blocked, outcome.blocked);
474
+ const review = outcome.review ?? carried.review;
475
+ return {
476
+ ...outcome,
477
+ ...(blocked !== undefined && { blocked }),
478
+ ...(review !== undefined && { review }),
479
+ };
480
+ }
481
+ /**
482
+ * The attempt of a device service's call whose network ask was approved (the person added its
483
+ * hosts to the device's list, browser use spec §7.1) with hosts in force from the next command:
484
+ * the call runs again in the next attempt. Null for any other ask, or none.
485
+ */
486
+ function serviceRerunAfter(ask) {
487
+ const d = ask?.detail;
488
+ if (ask?.status !== "approved" || ask.scope !== "always" || d?.kind !== "service")
489
+ return null;
490
+ // hosts that apply only at the device's next use or after a files reset are not in force for
491
+ // a re-run now: the kept result is written with the outcome's note instead, as for a command
492
+ if (d.appliesAt !== "next-command")
493
+ return null;
494
+ return d.attempt;
495
+ }
411
496
  /** A builtin result's kernel-internal network report (see `BuiltinResult.networkReport`). */
412
497
  function networkReportOf(result) {
413
498
  const r = result?.networkReport;
@@ -645,33 +730,58 @@ let ToolPipeline = class ToolPipeline {
645
730
  await this.writeResult(ctx, call.id, last.toolKey, skippedResult(last.toolKey));
646
731
  return undefined;
647
732
  }
648
- const attempt = rounds.length + 1;
649
- const started = await this.deps.eventLog.findByIdem(ctx.conversationId, idem.started(ctx.runId, call.id, attempt));
733
+ let attempt = rounds.length + 1;
734
+ // a device service's call that ran again after its network ask took one attempt more (browser
735
+ // use spec §7.1): input rounds the re-run asked come after it
736
+ if (rounds.length > 0) {
737
+ const asked = serviceRerunAfter(await this.deps.approvals.networkForCall(ctx.runId, call.id));
738
+ if (asked !== null && attempt > asked)
739
+ attempt += 1;
740
+ }
741
+ const resume = last
742
+ ? { state: last.state, answer: last.status === "answered" ? last.answer : null }
743
+ : undefined;
744
+ let started = await this.deps.eventLog.findByIdem(ctx.conversationId, idem.started(ctx.runId, call.id, attempt));
650
745
  if (started?.type === "tool_call_started") {
651
746
  // a command that ran and was refused a network host waits for the device owner (network
652
747
  // ask-to-allow spec §6.2, P-D2): pending → wait on; settled → its kept result and the
653
- // outcome's note (the command is never run again; its tool.called was audited when it ran)
748
+ // outcome's note (the command is never run again; its tool.called was audited when it ran).
749
+ // A device service's ask (browser use spec §7.1) belongs to the attempt that asked; once
750
+ // the person added its hosts to the device's list the call runs again in the next attempt
654
751
  const ask = await this.deps.approvals.networkForCall(ctx.runId, call.id);
655
- if (ask !== null) {
752
+ const askedHere = ask !== null && (ask.detail?.kind !== "service" || ask.detail.attempt === attempt);
753
+ if (ask !== null && askedHere) {
656
754
  const notes = settledNetworkNotes(ask, approvalHours(ask));
657
755
  if (notes === null)
658
756
  return approvalWait(ask);
659
- const kept = ask.detail?.result;
660
- // the device code the command printed is carried in the kept result: write its
661
- // display-only event here too (a crash before the ask's first write, or an older kept
662
- // result; the event's ids and the per-conversation code check keep it to one)
663
- const keptCode = validLoginCode(kept?.loginCode);
664
- const pre = keptCode !== undefined &&
665
- !(await this.deps.eventLog.deviceCodeShown(ctx.conversationId, keptCode.code))
666
- ? [deviceCodeEvent(ctx.runId, ctx.step, call.id, keptCode)]
667
- : [];
668
- await this.writeResult(ctx, call.id, call.name, {
669
- ...keptExtras(kept),
670
- content: withNetworkNotes(kept?.content ?? UNKNOWN_RESULT_TEXT, notes),
671
- isError: kept?.isError ?? true,
672
- ...(kept?.review !== undefined && { review: kept.review }),
673
- }, pre);
674
- return undefined;
757
+ if (serviceRerunAfter(ask) === null) {
758
+ const kept = ask.detail?.result;
759
+ // the device code the command printed is carried in the kept result: write its
760
+ // display-only event here too (a crash before the ask's first write, or an older kept
761
+ // result; the event's ids and the per-conversation code check keep it to one)
762
+ const keptCode = validLoginCode(kept?.loginCode);
763
+ const pre = keptCode !== undefined &&
764
+ !(await this.deps.eventLog.deviceCodeShown(ctx.conversationId, keptCode.code))
765
+ ? [deviceCodeEvent(ctx.runId, ctx.step, call.id, keptCode)]
766
+ : [];
767
+ await this.writeResult(ctx, call.id, call.name, {
768
+ ...keptExtras(kept),
769
+ content: withNetworkNotes(kept?.content ?? UNKNOWN_RESULT_TEXT, notes),
770
+ isError: kept?.isError ?? true,
771
+ ...(kept?.review !== undefined && { review: kept.review }),
772
+ }, pre);
773
+ return undefined;
774
+ }
775
+ const rerun = await this.deps.eventLog.findByIdem(ctx.conversationId, idem.started(ctx.runId, call.id, attempt + 1));
776
+ if (rerun?.type !== "tool_call_started") {
777
+ // the asked hosts are settled: only an earlier round's launch review is carried
778
+ const { review: carriedReview } = carriedOf(rounds);
779
+ return this.runCall(ctx, call, await resolve(), attempt + 1, resume, {
780
+ ...(carriedReview !== undefined && { review: carriedReview }),
781
+ });
782
+ }
783
+ // the re-run started and its result was lost: the result is unknown, as below
784
+ started = rerun;
675
785
  }
676
786
  // 确实开始执行过:照样审计 tool.called(耗时未知);放行依据只认批准了所执行定义的审批记录
677
787
  const key = started.payload.toolKey;
@@ -711,12 +821,11 @@ let ToolPipeline = class ToolPipeline {
711
821
  });
712
822
  return undefined;
713
823
  }
714
- const resume = last
715
- ? { state: last.state, answer: last.status === "answered" ? last.answer : null }
716
- : undefined;
717
- return this.runCall(ctx, call, await resolve(), attempt, resume);
824
+ return this.runCall(ctx, call, await resolve(), attempt, resume, carriedOf(rounds));
718
825
  }
719
- async runCall(ctx, call, resolved, attempt, resume) {
826
+ async runCall(ctx, call, resolved, attempt, resume,
827
+ /** What earlier input rounds of the call collected for its result ({@link carriedOf}). */
828
+ carried = {}) {
720
829
  // the command review's record for this call's result (absent: not reviewed, or no device)
721
830
  let review;
722
831
  const fail = async (content, key = call.name, view) => {
@@ -730,8 +839,11 @@ let ToolPipeline = class ToolPipeline {
730
839
  };
731
840
  const tool = resolved.tools.find((t) => t.key === call.name);
732
841
  if (!tool) {
842
+ // a hidden `<prefix>__*` ref covers every tool of that source (a disabled or needs_config
843
+ // connector), so a call of one of them gets the reason, not "unknown tool"
844
+ const covers = (ref) => ref === call.name || (ref.endsWith("__*") && call.name.startsWith(ref.slice(0, -1)));
733
845
  const why = resolved.unavailable.find((u) => u.ref === call.name) ??
734
- resolved.hidden?.find((u) => u.ref === call.name);
846
+ resolved.hidden?.find((u) => covers(u.ref));
735
847
  if (why)
736
848
  return fail(unavailableText(call.name, why.reason));
737
849
  let keys = resolved.tools.map((t) => t.key);
@@ -1105,6 +1217,12 @@ let ToolPipeline = class ToolPipeline {
1105
1217
  secureInputId);
1106
1218
  const durationMs = Date.now() - t0;
1107
1219
  await this.deps.hooks?.afterExecute?.(ctx.runId, call.id);
1220
+ // what earlier input rounds collected: a launch reviewed in a round that asked, the hosts a
1221
+ // service reported refused there (this round, a resume, finds the service running)
1222
+ outcome = withCarried(outcome, carried);
1223
+ // a device service launch's review during the call (ctx.deviceAccess, the call scope)
1224
+ if (review === undefined && outcome.kind !== "connection_required")
1225
+ review = outcome.review;
1108
1226
  // the record says a call ran outside the sandbox only when admission gave it that scope
1109
1227
  if (review !== undefined && isEscalatedCall(tool.key, input)) {
1110
1228
  const { sandbox: _asked, ...rest } = review;
@@ -1115,7 +1233,12 @@ let ToolPipeline = class ToolPipeline {
1115
1233
  // scheduled tasks spec §7, `fail` mode: no one answers an input request or connects an app
1116
1234
  if (unattendedFails(ctx.unattended) && ctx.unattended != null) {
1117
1235
  if (outcome.kind === "input_required") {
1118
- outcome = { kind: "error", message: UNATTENDED_QUESTION_ERROR };
1236
+ outcome = {
1237
+ kind: "error",
1238
+ message: UNATTENDED_QUESTION_ERROR,
1239
+ ...(outcome.blocked !== undefined && { blocked: outcome.blocked }),
1240
+ ...(outcome.review !== undefined && { review: outcome.review }),
1241
+ };
1119
1242
  }
1120
1243
  else if (outcome.kind === "connection_required") {
1121
1244
  await appendMissingGrant(this.deps.db, ctx.unattended.taskRunId, connectionGrantKey(outcome.connectorSlug));
@@ -1126,7 +1249,12 @@ let ToolPipeline = class ToolPipeline {
1126
1249
  const asked = await this.askInput(ctx, call.id, tool.key, attempt, outcome);
1127
1250
  if (typeof asked !== "string")
1128
1251
  return asked;
1129
- outcome = { kind: "error", message: asked };
1252
+ outcome = {
1253
+ kind: "error",
1254
+ message: asked,
1255
+ ...(outcome.blocked !== undefined && { blocked: outcome.blocked }),
1256
+ ...(outcome.review !== undefined && { review: outcome.review }),
1257
+ };
1130
1258
  }
1131
1259
  const rendered = outcome.kind === "result"
1132
1260
  ? renderResult(outcome.result)
@@ -1200,9 +1328,24 @@ let ToolPipeline = class ToolPipeline {
1200
1328
  // a foreground command refused network hosts (network ask-to-allow spec §6.2): display-only
1201
1329
  // `network_blocked` before the result, then an ask to the device owner (the run waits; the
1202
1330
  // result is written when the ask settles) or notes after the output
1203
- const report = outcome.kind === "result" && tool.source.kind === "builtin"
1331
+ const commandReport = outcome.kind === "result" && tool.source.kind === "builtin"
1204
1332
  ? networkReportOf(outcome.result)
1205
1333
  : undefined;
1334
+ // a device service's refusals reported in the call scope (browser use spec §7.1), any source:
1335
+ // asked as "always" only, the call runs again once approved
1336
+ // a report about another device than the conversation's is ignored: only the device the call
1337
+ // works in may be asked about, and only its owner
1338
+ const scoped = commandReport === undefined && (outcome.kind === "result" || outcome.kind === "error")
1339
+ ? await this.ownDeviceReport(ctx, outKey, outcome.blocked)
1340
+ : undefined;
1341
+ const report = commandReport ??
1342
+ (scoped === undefined
1343
+ ? undefined
1344
+ : {
1345
+ deviceId: scoped.deviceId,
1346
+ // a service reports host names only: the event carries the HTTPS port
1347
+ blocked: scoped.hosts.map((host) => ({ host, port: 443, layer: "device" })),
1348
+ });
1206
1349
  let content = spilled.content;
1207
1350
  if (report !== undefined) {
1208
1351
  const handled = await this.networkBlocked(ctx, call.id, outKey, input, report, pre, callAudit, {
@@ -1217,7 +1360,13 @@ let ToolPipeline = class ToolPipeline {
1217
1360
  // carried into the kept result so a resumed run writes the event too (it was written
1218
1361
  // with `network_blocked` below when the ask was created)
1219
1362
  ...(loginCode !== undefined && { loginCode }),
1220
- }, reviewedRoots.escalation, reviewedRoots.escalationRefusal);
1363
+ }, reviewedRoots.escalation, reviewedRoots.escalationRefusal, scoped === undefined
1364
+ ? undefined
1365
+ : {
1366
+ name: tool.source.kind === "plugin" ? tool.source.plugin : tool.key,
1367
+ attempt,
1368
+ url: scoped.url,
1369
+ });
1221
1370
  if (handled.kind === "wait") {
1222
1371
  if (hooks && hookBase) {
1223
1372
  fireObserve(hooks, "tool.postExecute", { ...hookBase, isError: rendered.isError, content: handled.content, durationMs }, ctx.signal, this.deps.log);
@@ -2024,7 +2173,12 @@ let ToolPipeline = class ToolPipeline {
2024
2173
  /** Admission's verdict for this call: `available` when it may run outside the sandbox. */
2025
2174
  escalation,
2026
2175
  /** Why this call could not run outside the sandbox here (absent when it could). */
2027
- escalationRefusal) {
2176
+ escalationRefusal,
2177
+ /**
2178
+ * A device service's refusals (browser use spec §7.1): the extension whose service asked and
2179
+ * the call's attempt. Only "always" is offered; once approved the call runs again.
2180
+ */
2181
+ service) {
2028
2182
  const hosts = blockedEventHosts(report.blocked);
2029
2183
  if (hosts.length === 0)
2030
2184
  return { kind: "write", event: null, notes: [] };
@@ -2051,13 +2205,16 @@ let ToolPipeline = class ToolPipeline {
2051
2205
  const plan = planNetworkAsk(hosts, run, {
2052
2206
  unattended: ctx.unattended,
2053
2207
  outsideCeiling: (h) => orgHostOutsideCeiling(limits, h),
2054
- ...(sandbox !== undefined && {
2055
- ...deviceAskTerms(sandbox),
2056
- // the hint follows admission's verdict for this call (never a recomputation), and only
2057
- // the open network makes a private address the one thing escalation adds
2058
- escalation: addressEscalationHint(escalation, sandbox.box.networkMode),
2059
- }),
2060
- ...(escalationRefusal !== undefined && { escalationRefusal }),
2208
+ ...(sandbox !== undefined &&
2209
+ (service !== undefined
2210
+ ? serviceAskTerms(sandbox)
2211
+ : {
2212
+ ...deviceAskTerms(sandbox),
2213
+ // the hint follows admission's verdict for this call (never a recomputation), and
2214
+ // only the open network makes a private address the one thing escalation adds
2215
+ escalation: addressEscalationHint(escalation, sandbox.box.networkMode),
2216
+ })),
2217
+ ...(service === undefined && escalationRefusal !== undefined && { escalationRefusal }),
2061
2218
  });
2062
2219
  if (ctx.unattended != null) {
2063
2220
  for (const key of plan.missingGrants) {
@@ -2067,6 +2224,16 @@ let ToolPipeline = class ToolPipeline {
2067
2224
  const offer = plan.offer;
2068
2225
  if (plan.ask.length === 0 || offer === undefined)
2069
2226
  return { kind: "write", event, notes: plan.notes };
2227
+ // one ask per call: a service call that ran again after its ask is not asked again; only a
2228
+ // would-be ask is replaced, the plan's other notes (a host on the list, not yet applied) stay
2229
+ if (service !== undefined &&
2230
+ (await this.deps.approvals.networkForCall(ctx.runId, callId)) !== null) {
2231
+ return {
2232
+ kind: "write",
2233
+ event,
2234
+ notes: [...plan.notes, serviceAskedNote(plan.ask.map((h) => h.host))],
2235
+ };
2236
+ }
2070
2237
  // the device's owner is the only person who may decide (spec §5.2)
2071
2238
  const owner = await this.deps.db
2072
2239
  .selectFrom("devices")
@@ -2107,18 +2274,57 @@ let ToolPipeline = class ToolPipeline {
2107
2274
  step: ctx.step,
2108
2275
  callId,
2109
2276
  requestedFor: owner.owner_account_id,
2110
- detail: {
2111
- deviceId: report.deviceId,
2112
- hosts: plan.ask,
2113
- command: typeof given.command === "string" ? clipText(given.command, 2000) : "",
2114
- description: typeof given.description === "string" ? given.description : null,
2115
- appliesAt: offer.appliesAt,
2116
- result: kept,
2117
- },
2277
+ toolKey,
2278
+ detail: service === undefined
2279
+ ? {
2280
+ kind: "command",
2281
+ deviceId: report.deviceId,
2282
+ hosts: plan.ask,
2283
+ command: typeof given.command === "string" ? clipText(given.command, 2000) : "",
2284
+ description: typeof given.description === "string" ? given.description : null,
2285
+ appliesAt: offer.appliesAt,
2286
+ result: kept,
2287
+ }
2288
+ : {
2289
+ kind: "service",
2290
+ deviceId: report.deviceId,
2291
+ service: service.name,
2292
+ url: service.url,
2293
+ hosts: plan.ask.map((h) => h.host),
2294
+ attempt: service.attempt,
2295
+ appliesAt: offer.appliesAt,
2296
+ result: kept,
2297
+ },
2118
2298
  scopes: offer.scopes,
2119
2299
  });
2120
2300
  return { kind: "wait", wait: approvalWait(ask), content: kept.content };
2121
2301
  }
2302
+ /**
2303
+ * A device service's report (the call scope, browser use spec §7.1) on the device the call's
2304
+ * conversation works in (the root conversation's for a sub-agent, as the sandbox tools resolve
2305
+ * it): a report that names no device is about that one; a report naming another device id (the
2306
+ * conversation moved to another device during the call) is ignored with a warning, never asked
2307
+ * about.
2308
+ */
2309
+ async ownDeviceReport(ctx, toolKey, blocked) {
2310
+ if (blocked === undefined)
2311
+ return undefined;
2312
+ const conv = await this.deps.db
2313
+ .selectFrom("conversations")
2314
+ .select("device_id")
2315
+ .where("id", "=", ctx.parent?.rootConversationId ?? ctx.conversationId)
2316
+ .where("org_id", "=", ctx.orgId)
2317
+ .executeTakeFirst();
2318
+ const deviceId = conv?.device_id ?? null;
2319
+ if (deviceId !== null && (blocked.deviceId === null || blocked.deviceId === deviceId))
2320
+ return { ...blocked, deviceId };
2321
+ this.deps.log.warn("ignored refused hosts reported for another device than the call's", {
2322
+ runId: ctx.runId,
2323
+ toolKey,
2324
+ deviceId: blocked.deviceId,
2325
+ });
2326
+ return undefined;
2327
+ }
2122
2328
  /** Appends a sub-agent's connect card to its root conversation ({@link rootSurfaceOf}). */
2123
2329
  async surfaceConnectInRoot(ctx, parent, callId, toolKey) {
2124
2330
  const target = await rootSurfaceOf(this.deps.db, ctx.conversationId, ctx.runId, parent);
@@ -2272,6 +2478,13 @@ let ToolPipeline = class ToolPipeline {
2272
2478
  toolKey,
2273
2479
  form: req.form,
2274
2480
  state: JSON.parse(stateJson),
2481
+ // kept for the call's result, which a later round writes
2482
+ ...((req.review !== undefined || req.blocked !== undefined) && {
2483
+ carried: {
2484
+ ...(req.review !== undefined && { review: req.review }),
2485
+ ...(req.blocked !== undefined && { blocked: req.blocked }),
2486
+ },
2487
+ }),
2275
2488
  });
2276
2489
  return inputWait(q);
2277
2490
  }
@@ -2353,6 +2566,7 @@ let ToolPipeline = class ToolPipeline {
2353
2566
  };
2354
2567
  // 内置工具可按输入给自己的时限(沙箱 bash 按命令超时加余量);缺省 tools.timeoutMs
2355
2568
  const timeoutMs = tool.timeoutMs?.(input) ?? this.config.get().tools.timeoutMs;
2569
+ let scope;
2356
2570
  try {
2357
2571
  // a plugin tool runs with the extension's effective config for the org, never without it
2358
2572
  // (layering spec A §6): one read per call, cached by EffectiveConfigs
@@ -2374,20 +2588,41 @@ let ToolPipeline = class ToolPipeline {
2374
2588
  const r = await this.bounded(ctx.signal, async (signal) => {
2375
2589
  await this.txHost.run(async () => { });
2376
2590
  signal.throwIfAborted();
2377
- return handler(input, { ...base, ...config, signal });
2591
+ // the call scope lives on this call's own context object (never a module map)
2592
+ const call = { ...base, ...config, signal };
2593
+ scope = attachCallScope(call, {
2594
+ runId: ctx.runId,
2595
+ step: ctx.step,
2596
+ rootConversationId: ctx.parent?.rootConversationId ?? ctx.conversationId,
2597
+ unattended: ctx.unattended != null,
2598
+ agentVersion: ctx.agentVersion,
2599
+ ...(ctx.conversationKind !== undefined && { conversationKind: ctx.conversationKind }),
2600
+ ...(ctx.parent !== undefined && {
2601
+ parent: {
2602
+ conversationId: ctx.parent.conversationId,
2603
+ runId: ctx.parent.runId,
2604
+ callId: ctx.parent.callId,
2605
+ ...(ctx.parent.budgetRunId !== undefined && {
2606
+ budgetRunId: ctx.parent.budgetRunId,
2607
+ }),
2608
+ },
2609
+ }),
2610
+ });
2611
+ return handler(input, call);
2378
2612
  }, undefined, timeoutMs);
2379
2613
  if (r === "timeout") {
2380
- return { kind: "error", message: timeoutText(tool.key, timeoutMs) };
2614
+ return withBlocked({ kind: "error", message: timeoutText(tool.key, timeoutMs) }, scope);
2381
2615
  }
2616
+ // a launch reviewed before the call stopped or asked is kept with its result
2382
2617
  if (r === "aborted")
2383
- return { kind: "error", message: RUN_STOPPED_DURING_TEXT };
2618
+ return withBlocked({ kind: "error", message: RUN_STOPPED_DURING_TEXT }, scope);
2384
2619
  if (isInputRequired(r.value)) {
2385
- return { kind: "input_required", form: r.value.form, state: r.value.state ?? null };
2620
+ return withBlocked({ kind: "input_required", form: r.value.form, state: r.value.state ?? null }, scope);
2386
2621
  }
2387
- return { kind: "result", result: r.value };
2622
+ return withBlocked({ kind: "result", result: r.value }, scope);
2388
2623
  }
2389
2624
  catch (e) {
2390
- return this.thrown(tool.key, e);
2625
+ return withBlocked(this.thrown(tool.key, e), scope);
2391
2626
  }
2392
2627
  }
2393
2628
  async executeConnector(tool, source, input, ctx, resume) {
@@ -2477,15 +2712,17 @@ let ToolPipeline = class ToolPipeline {
2477
2712
  connectorSlug: app.slug,
2478
2713
  message: personalMissingText(app.name),
2479
2714
  }
2480
- : { kind: "error", message: orgMissingText(app.name) };
2481
- // 先取一次凭据:缺凭据在打开会话之前就确定,不依赖连接器把 CredentialMissing 原样抛出。
2715
+ : { kind: "error", message: ORG_MISSING_TEXT };
2716
+ // Read the credential once first: a missing one (or a needs_config connector) is settled before
2717
+ // any session opens, without relying on the connector to rethrow CredentialMissing.
2482
2718
  try {
2483
2719
  await getAuth();
2484
2720
  }
2485
2721
  catch (e) {
2486
2722
  if (e instanceof CredentialMissing)
2487
2723
  return missing(e);
2488
- // 取 token 时授权服务器暂时不可用(OAuth):给模型可执行的说明,不让整轮失败
2724
+ // the authorization server is briefly unavailable for the token (OAuth): an actionable
2725
+ // message for the model instead of failing the whole turn
2489
2726
  if (e instanceof ToolError)
2490
2727
  return { kind: "error", message: e.message };
2491
2728
  throw e;
@@ -2567,6 +2804,9 @@ let ToolPipeline = class ToolPipeline {
2567
2804
  thrown(key, e) {
2568
2805
  if (e instanceof ToolError)
2569
2806
  return { kind: "error", message: e.message };
2807
+ // a ctx.deviceAccess refusal the handler let through: its message is actionable English
2808
+ if (e instanceof DeviceAccessError)
2809
+ return { kind: "error", message: e.message };
2570
2810
  // an extension tool's ctx.models.embed denied by a policy hook (spec B §5.4): the model sees the
2571
2811
  // deny text (sanitized reason), as for a denied tool call, not a generic failure
2572
2812
  if (e instanceof ApiError && e.code === "model.hook_denied") {
@@ -1,5 +1,6 @@
1
1
  import { type FormAnswer, type InputForm } from "@capybara-hq/plugin-sdk";
2
2
  import { EventLog } from "../conversations/event-log.js";
3
+ import type { ReviewRecord } from "../conversations/events.js";
3
4
  import { type PersonRef } from "../identity/account-avatar.js";
4
5
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
5
6
  import { KernelDb } from "../infra/database/kernel-db.js";
@@ -7,6 +8,20 @@ import { TransactionHost } from "../infra/database/transaction-host.js";
7
8
  import { KernelEvents } from "../infra/events/kernel-events.js";
8
9
  import { RunResume } from "../runtime/run-jobs.js";
9
10
  export type QuestionStatus = "pending" | "answered" | "skipped" | "expired" | "cancelled";
11
+ /**
12
+ * What the round that asked collected for the call's result and is not the tool's own state: a
13
+ * device service launch's review record and the hosts a device service reported refused
14
+ * (`ctx.deviceAccess`, the call scope). A later round (the resume, which starts nothing) writes
15
+ * the result with them, so they are not lost with the round that asked.
16
+ */
17
+ export interface QuestionCarried {
18
+ review?: ReviewRecord;
19
+ blocked?: {
20
+ deviceId: string | null;
21
+ hosts: string[];
22
+ url: string | null;
23
+ };
24
+ }
10
25
  /** 一条输入请求(`AskUserQuestion`、插件工具的 `input_required`、MCP elicitation 共用)。 */
11
26
  export interface QuestionRecord {
12
27
  id: string;
@@ -20,6 +35,8 @@ export interface QuestionRecord {
20
35
  step: number;
21
36
  form: InputForm;
22
37
  state: unknown;
38
+ /** {@link QuestionCarried}, when the round that asked collected any. */
39
+ carried?: QuestionCarried;
23
40
  status: QuestionStatus;
24
41
  answer: FormAnswer | null;
25
42
  answeredBy: string | null;
@@ -38,9 +55,13 @@ export interface QuestionAskInput {
38
55
  toolKey: string;
39
56
  form: InputForm;
40
57
  state: unknown;
58
+ carried?: QuestionCarried;
41
59
  }
42
- /** 网页读取输入请求的视图(不含插件 state:那是工具内部的续跑数据)。 */
43
- export type QuestionView = Omit<QuestionRecord, "state"> & {
60
+ /**
61
+ * The web's view of an input request: without the plugin's state (the tool's own resume data)
62
+ * and without what the round carried for the call's result ({@link QuestionCarried}).
63
+ */
64
+ export type QuestionView = Omit<QuestionRecord, "state" | "carried"> & {
44
65
  /** Who answered (next to `answeredBy`); null while open or when the account is gone. */
45
66
  answeredByPerson: PersonRef | null;
46
67
  };
@@ -78,7 +99,7 @@ export declare class QuestionsService {
78
99
  */
79
100
  get(orgId: string, questionId: string, accountId: string): Promise<QuestionView>;
80
101
  /** The web's view of a question: no plugin state, plus the answerer as a person. */
81
- view({ state: _state, ...rest }: QuestionRecord): Promise<QuestionView>;
102
+ view({ state: _state, carried: _carried, ...rest }: QuestionRecord): Promise<QuestionView>;
82
103
  /** 某个调用的全部输入请求(按轮次升序)。 */
83
104
  forCall(runId: string, callId: string): Promise<QuestionRecord[]>;
84
105
  /**
@@ -36,6 +36,7 @@ function toRecord(r) {
36
36
  step: spec.step,
37
37
  form: spec.form,
38
38
  state: spec.state ?? null,
39
+ ...(spec.carried !== undefined && { carried: spec.carried }),
39
40
  status: r.status,
40
41
  answer: (r.answer ?? null),
41
42
  answeredBy: r.answered_by,
@@ -89,6 +90,7 @@ let QuestionsService = class QuestionsService {
89
90
  state: input.state ?? null,
90
91
  toolKey: input.toolKey,
91
92
  step: input.step,
93
+ ...(input.carried !== undefined && { carried: input.carried }),
92
94
  };
93
95
  const t = this.db.db;
94
96
  await t
@@ -152,7 +154,7 @@ let QuestionsService = class QuestionsService {
152
154
  return this.view(toRecord(row));
153
155
  }
154
156
  /** The web's view of a question: no plugin state, plus the answerer as a person. */
155
- async view({ state: _state, ...rest }) {
157
+ async view({ state: _state, carried: _carried, ...rest }) {
156
158
  const answeredByPerson = rest.answeredBy === null
157
159
  ? null
158
160
  : ((await loadPeople(this.db.db, [rest.answeredBy])).get(rest.answeredBy) ?? null);