@capybara-hq/kernel 0.1.0-rc.85 → 0.1.0-rc.87

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 (71) hide show
  1. package/bootstrap.json +5 -5
  2. package/dist/catalog/marketplaces.service.d.ts +1 -1
  3. package/dist/channels/cards.d.ts +7 -3
  4. package/dist/channels/cards.js +9 -4
  5. package/dist/channels/phrases.d.ts +10 -0
  6. package/dist/channels/phrases.js +10 -0
  7. package/dist/config/docs.js +1 -1
  8. package/dist/config/schema.d.ts +3 -0
  9. package/dist/config/schema.js +18 -12
  10. package/dist/ctx/create-ctx.d.ts +10 -1
  11. package/dist/ctx/create-ctx.js +42 -2
  12. package/dist/device-access/device-access.module.d.ts +7 -0
  13. package/dist/device-access/device-access.module.js +41 -0
  14. package/dist/device-access/device-access.service.d.ts +142 -0
  15. package/dist/device-access/device-access.service.js +464 -0
  16. package/dist/device-access/token.d.ts +6 -0
  17. package/dist/device-access/token.js +6 -0
  18. package/dist/device-access/viewer-routes.d.ts +45 -0
  19. package/dist/device-access/viewer-routes.js +81 -0
  20. package/dist/device-access/viewer.d.ts +244 -0
  21. package/dist/device-access/viewer.js +844 -0
  22. package/dist/dial-in/access.d.ts +19 -0
  23. package/dist/dial-in/access.js +23 -0
  24. package/dist/dial-in/gateway.d.ts +48 -6
  25. package/dist/dial-in/gateway.js +145 -10
  26. package/dist/dial-in/keys.d.ts +7 -0
  27. package/dist/dial-in/keys.js +7 -0
  28. package/dist/dial-in/routes.d.ts +11 -3
  29. package/dist/dial-in/routes.js +15 -4
  30. package/dist/dial-in/streams.d.ts +58 -0
  31. package/dist/dial-in/streams.js +283 -0
  32. package/dist/errors.d.ts +2 -0
  33. package/dist/errors.js +2 -0
  34. package/dist/extensions/host.d.ts +13 -1
  35. package/dist/extensions/host.js +20 -1
  36. package/dist/extensions/permission-set.d.ts +15 -1
  37. package/dist/extensions/permission-set.js +13 -1
  38. package/dist/extensions/permission-view.d.ts +6 -4
  39. package/dist/extensions/permission-view.js +6 -1
  40. package/dist/http/error.filter.js +2 -0
  41. package/dist/http/gateway-routes.d.ts +8 -4
  42. package/dist/http/gateway-routes.js +4 -3
  43. package/dist/infra/lock/lock.service.d.ts +5 -1
  44. package/dist/infra/lock/lock.service.js +10 -4
  45. package/dist/infra/throttler/named-throttlers.d.ts +3 -0
  46. package/dist/infra/throttler/named-throttlers.js +16 -0
  47. package/dist/kernel.module.js +3 -0
  48. package/dist/roles/gateway-role.d.ts +13 -6
  49. package/dist/roles/gateway-role.js +27 -9
  50. package/dist/roles/gateway.module.d.ts +2 -1
  51. package/dist/roles/gateway.module.js +13 -3
  52. package/dist/sandbox/device-services.d.ts +62 -0
  53. package/dist/sandbox/device-services.js +183 -0
  54. package/dist/sandbox/leases.d.ts +18 -1
  55. package/dist/sandbox/leases.js +75 -1
  56. package/dist/sandbox/network-grants.js +5 -2
  57. package/dist/sandbox/sandbox.module.d.ts +2 -1
  58. package/dist/sandbox/sandbox.module.js +5 -2
  59. package/dist/sandbox/sandbox.service.d.ts +44 -1
  60. package/dist/sandbox/sandbox.service.js +142 -5
  61. package/dist/tools/approvals.service.d.ts +45 -20
  62. package/dist/tools/approvals.service.js +19 -9
  63. package/dist/tools/call-scope.d.ts +60 -0
  64. package/dist/tools/call-scope.js +23 -0
  65. package/dist/tools/network-asks.d.ts +13 -0
  66. package/dist/tools/network-asks.js +26 -2
  67. package/dist/tools/pipeline.d.ts +30 -1
  68. package/dist/tools/pipeline.js +285 -54
  69. package/dist/tools/questions.service.d.ts +24 -3
  70. package/dist/tools/questions.service.js +3 -1
  71. package/package.json +3 -3
@@ -3,7 +3,7 @@ import { NETWORK_ASK_MAX_HOSTS, NETWORK_HOST_MAX_CHARS } from "../conversations/
3
3
  import { coversHost } from "../sandbox/modes.js";
4
4
  import { ESCALATION_UNATTENDED_WHY } from "../sandbox/review/permission-candidate.js";
5
5
  import { networkGrantKey, unattendedFails, unattendedRules, } from "../schedules/unattended.js";
6
- import { NETWORK_ASK_CANCELLED_NOTE, } from "./approvals.service.js";
6
+ import { NETWORK_ASK_CANCELLED_NOTE, networkAskHosts, } from "./approvals.service.js";
7
7
  /**
8
8
  * Network asks in the tool pipeline (network ask-to-allow spec §6.2, §6.6–§6.9, §8.3): what a
9
9
  * command's reported refusals turn into (an ask to the device owner, or notes written at once) and
@@ -84,6 +84,25 @@ export function deviceAskTerms(f) {
84
84
  offer: (hosts) => networkAskOffer({ perOperationHosts }, f.limitsApplyAt, f.ownList && hosts.length > 0 && hosts.every((h) => f.listAddRefusal(h) === null)),
85
85
  };
86
86
  }
87
+ /**
88
+ * The ask terms for a device service's refusals (browser use spec §7.1): a long-lived service is
89
+ * reached only through the device's own list, never a per-exec run grant, so a host is offered
90
+ * only `always` and refused when the list cannot take it (`listAddRefusal`: beyond the org's or
91
+ * platform's hosts, or a device with no list of its own); a host the list already holds waits for
92
+ * it to apply ({@link deviceAskTerms}' `onList`).
93
+ */
94
+ export function serviceAskTerms(f) {
95
+ const terms = deviceAskTerms(f);
96
+ return {
97
+ refusal: f.listAddRefusal,
98
+ onList: terms.onList,
99
+ deviceBlocks: () => false,
100
+ offer: (hosts) => {
101
+ const o = terms.offer(hosts);
102
+ return o?.scopes.includes("always") ? { scopes: ["always"], appliesAt: o.appliesAt } : null;
103
+ },
104
+ };
105
+ }
87
106
  /** When a host added to the device's list applies, as the model reads it. */
88
107
  const APPLIES_TEXT = {
89
108
  "next-command": "from the next command",
@@ -97,6 +116,11 @@ export const allowedOnceNote = (hosts) => `${blockedLead(hosts)} The user allowe
97
116
  * apply at `appliesAt`, never to the command that asked, which is not run again.
98
117
  */
99
118
  export const addedToDeviceNote = (hosts, appliesAt) => `${blockedLead(hosts)} The person added ${list(hosts)} to this device's network list; it applies ${APPLIES_TEXT[appliesAt]}. This command is not run again.`;
119
+ /**
120
+ * Not asked: a device service's call that already asked once (it ran again after the person added
121
+ * hosts to the device's list, browser use spec §7.1) was refused more hosts; one ask per call.
122
+ */
123
+ export const serviceAskedNote = (hosts) => `${blockedLead(hosts)} This call already asked for network access once; call the tool again to ask for ${pron(hosts)}.`;
100
124
  /**
101
125
  * Not asked: the device's network settings already allow the host (its own list, added by an
102
126
  * earlier answer or on the device page, or the org's hosts it follows), but its sandbox has not
@@ -319,7 +343,7 @@ const NO_OFFER_WHY = "the device's owner changes the device's network on its pag
319
343
  * wait (created to expiry). Null while it is pending.
320
344
  */
321
345
  export function settledNetworkNotes(a, hours) {
322
- const asked = (a.detail?.hosts ?? []).map((h) => h.host);
346
+ const asked = a.detail === null ? [] : networkAskHosts(a.detail);
323
347
  switch (a.status) {
324
348
  case "approved": {
325
349
  const granted = a.detail?.grantedHosts ?? asked;
@@ -2,6 +2,7 @@ import { type ConversationSource, type FormAnswer, type InputForm, type Logger }
2
2
  import type { AgentDefinition } from "../agents/definition.js";
3
3
  import { ConversationApprovalProfile } from "../conversations/approval-profile.js";
4
4
  import { EventLog } from "../conversations/event-log.js";
5
+ import { type ReviewRecord } from "../conversations/events.js";
5
6
  import type { KernelSchemaDb } from "../db/kernel-schema.js";
6
7
  import { ConversationDevices } from "../devices/conversation-devices.js";
7
8
  import { EffectiveConfigs } from "../extensions/effective-config.js";
@@ -340,22 +341,42 @@ export type ToolResume = {
340
341
  answer: FormAnswer | null;
341
342
  };
342
343
  /** 执行阶段的结果。 */
344
+ /**
345
+ * Hosts a device service reported refused during a handler's call (the call scope, browser use
346
+ * spec §7.1): the pipeline asks the device owner about them after the call.
347
+ */
348
+ export interface ServiceBlocked {
349
+ /** The device the call's `ctx.deviceAccess` calls resolved; null: the conversation's device. */
350
+ deviceId: string | null;
351
+ hosts: string[];
352
+ /** The page the refusals came from, when the service said. */
353
+ url: string | null;
354
+ }
343
355
  export type ExecOutcome =
344
356
  /** 工具返回了结果(可能是工具自己报告的错误,或畸形结果,由渲染阶段处理)。 */
345
357
  {
346
358
  kind: "result";
347
359
  result: unknown;
360
+ blocked?: ServiceBlocked;
361
+ review?: ReviewRecord;
348
362
  }
349
- /** 处理函数需要用户输入(表单尚未校验)。 */
363
+ /**
364
+ * The handler needs the user's input (the form is not validated yet). `review` and `blocked`:
365
+ * what the round collected before it asked ({@link withBlocked}), kept for the call's result.
366
+ */
350
367
  | {
351
368
  kind: "input_required";
352
369
  form: InputForm;
353
370
  state: unknown;
371
+ blocked?: ServiceBlocked;
372
+ review?: ReviewRecord;
354
373
  }
355
374
  /** 执行失败(超时、抛错、熔断、中止等),message 给模型看。 */
356
375
  | {
357
376
  kind: "error";
358
377
  message: string;
378
+ blocked?: ServiceBlocked;
379
+ review?: ReviewRecord;
359
380
  }
360
381
  /** 发起人未连接个人凭据:除错误结果外再写 `connection_required`。 */
361
382
  | {
@@ -522,6 +543,14 @@ export declare class ToolPipeline {
522
543
  * settles (P-D2).
523
544
  */
524
545
  private networkBlocked;
546
+ /**
547
+ * A device service's report (the call scope, browser use spec §7.1) on the device the call's
548
+ * conversation works in (the root conversation's for a sub-agent, as the sandbox tools resolve
549
+ * it): a report that names no device is about that one; a report naming another device id (the
550
+ * conversation moved to another device during the call) is ignored with a warning, never asked
551
+ * about.
552
+ */
553
+ private ownDeviceReport;
525
554
  /** Appends a sub-agent's connect card to its root conversation ({@link rootSurfaceOf}). */
526
555
  private surfaceConnectInRoot;
527
556
  /**
@@ -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";
@@ -412,6 +413,86 @@ const keptExtras = (kept) => ({
412
413
  ...(kept?.display !== undefined && { display: kept.display }),
413
414
  ...(kept?.view !== undefined && { view: kept.view }),
414
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
+ }
415
496
  /** A builtin result's kernel-internal network report (see `BuiltinResult.networkReport`). */
416
497
  function networkReportOf(result) {
417
498
  const r = result?.networkReport;
@@ -649,33 +730,58 @@ let ToolPipeline = class ToolPipeline {
649
730
  await this.writeResult(ctx, call.id, last.toolKey, skippedResult(last.toolKey));
650
731
  return undefined;
651
732
  }
652
- const attempt = rounds.length + 1;
653
- 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));
654
745
  if (started?.type === "tool_call_started") {
655
746
  // a command that ran and was refused a network host waits for the device owner (network
656
747
  // ask-to-allow spec §6.2, P-D2): pending → wait on; settled → its kept result and the
657
- // 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
658
751
  const ask = await this.deps.approvals.networkForCall(ctx.runId, call.id);
659
- if (ask !== null) {
752
+ const askedHere = ask !== null && (ask.detail?.kind !== "service" || ask.detail.attempt === attempt);
753
+ if (ask !== null && askedHere) {
660
754
  const notes = settledNetworkNotes(ask, approvalHours(ask));
661
755
  if (notes === null)
662
756
  return approvalWait(ask);
663
- const kept = ask.detail?.result;
664
- // the device code the command printed is carried in the kept result: write its
665
- // display-only event here too (a crash before the ask's first write, or an older kept
666
- // result; the event's ids and the per-conversation code check keep it to one)
667
- const keptCode = validLoginCode(kept?.loginCode);
668
- const pre = keptCode !== undefined &&
669
- !(await this.deps.eventLog.deviceCodeShown(ctx.conversationId, keptCode.code))
670
- ? [deviceCodeEvent(ctx.runId, ctx.step, call.id, keptCode)]
671
- : [];
672
- await this.writeResult(ctx, call.id, call.name, {
673
- ...keptExtras(kept),
674
- content: withNetworkNotes(kept?.content ?? UNKNOWN_RESULT_TEXT, notes),
675
- isError: kept?.isError ?? true,
676
- ...(kept?.review !== undefined && { review: kept.review }),
677
- }, pre);
678
- 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;
679
785
  }
680
786
  // 确实开始执行过:照样审计 tool.called(耗时未知);放行依据只认批准了所执行定义的审批记录
681
787
  const key = started.payload.toolKey;
@@ -715,12 +821,11 @@ let ToolPipeline = class ToolPipeline {
715
821
  });
716
822
  return undefined;
717
823
  }
718
- const resume = last
719
- ? { state: last.state, answer: last.status === "answered" ? last.answer : null }
720
- : undefined;
721
- return this.runCall(ctx, call, await resolve(), attempt, resume);
824
+ return this.runCall(ctx, call, await resolve(), attempt, resume, carriedOf(rounds));
722
825
  }
723
- 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 = {}) {
724
829
  // the command review's record for this call's result (absent: not reviewed, or no device)
725
830
  let review;
726
831
  const fail = async (content, key = call.name, view) => {
@@ -1112,6 +1217,12 @@ let ToolPipeline = class ToolPipeline {
1112
1217
  secureInputId);
1113
1218
  const durationMs = Date.now() - t0;
1114
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;
1115
1226
  // the record says a call ran outside the sandbox only when admission gave it that scope
1116
1227
  if (review !== undefined && isEscalatedCall(tool.key, input)) {
1117
1228
  const { sandbox: _asked, ...rest } = review;
@@ -1122,7 +1233,12 @@ let ToolPipeline = class ToolPipeline {
1122
1233
  // scheduled tasks spec §7, `fail` mode: no one answers an input request or connects an app
1123
1234
  if (unattendedFails(ctx.unattended) && ctx.unattended != null) {
1124
1235
  if (outcome.kind === "input_required") {
1125
- 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
+ };
1126
1242
  }
1127
1243
  else if (outcome.kind === "connection_required") {
1128
1244
  await appendMissingGrant(this.deps.db, ctx.unattended.taskRunId, connectionGrantKey(outcome.connectorSlug));
@@ -1133,7 +1249,12 @@ let ToolPipeline = class ToolPipeline {
1133
1249
  const asked = await this.askInput(ctx, call.id, tool.key, attempt, outcome);
1134
1250
  if (typeof asked !== "string")
1135
1251
  return asked;
1136
- 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
+ };
1137
1258
  }
1138
1259
  const rendered = outcome.kind === "result"
1139
1260
  ? renderResult(outcome.result)
@@ -1207,9 +1328,24 @@ let ToolPipeline = class ToolPipeline {
1207
1328
  // a foreground command refused network hosts (network ask-to-allow spec §6.2): display-only
1208
1329
  // `network_blocked` before the result, then an ask to the device owner (the run waits; the
1209
1330
  // result is written when the ask settles) or notes after the output
1210
- const report = outcome.kind === "result" && tool.source.kind === "builtin"
1331
+ const commandReport = outcome.kind === "result" && tool.source.kind === "builtin"
1211
1332
  ? networkReportOf(outcome.result)
1212
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
+ });
1213
1349
  let content = spilled.content;
1214
1350
  if (report !== undefined) {
1215
1351
  const handled = await this.networkBlocked(ctx, call.id, outKey, input, report, pre, callAudit, {
@@ -1224,7 +1360,13 @@ let ToolPipeline = class ToolPipeline {
1224
1360
  // carried into the kept result so a resumed run writes the event too (it was written
1225
1361
  // with `network_blocked` below when the ask was created)
1226
1362
  ...(loginCode !== undefined && { loginCode }),
1227
- }, 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
+ });
1228
1370
  if (handled.kind === "wait") {
1229
1371
  if (hooks && hookBase) {
1230
1372
  fireObserve(hooks, "tool.postExecute", { ...hookBase, isError: rendered.isError, content: handled.content, durationMs }, ctx.signal, this.deps.log);
@@ -2031,7 +2173,12 @@ let ToolPipeline = class ToolPipeline {
2031
2173
  /** Admission's verdict for this call: `available` when it may run outside the sandbox. */
2032
2174
  escalation,
2033
2175
  /** Why this call could not run outside the sandbox here (absent when it could). */
2034
- 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) {
2035
2182
  const hosts = blockedEventHosts(report.blocked);
2036
2183
  if (hosts.length === 0)
2037
2184
  return { kind: "write", event: null, notes: [] };
@@ -2058,13 +2205,16 @@ let ToolPipeline = class ToolPipeline {
2058
2205
  const plan = planNetworkAsk(hosts, run, {
2059
2206
  unattended: ctx.unattended,
2060
2207
  outsideCeiling: (h) => orgHostOutsideCeiling(limits, h),
2061
- ...(sandbox !== undefined && {
2062
- ...deviceAskTerms(sandbox),
2063
- // the hint follows admission's verdict for this call (never a recomputation), and only
2064
- // the open network makes a private address the one thing escalation adds
2065
- escalation: addressEscalationHint(escalation, sandbox.box.networkMode),
2066
- }),
2067
- ...(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 }),
2068
2218
  });
2069
2219
  if (ctx.unattended != null) {
2070
2220
  for (const key of plan.missingGrants) {
@@ -2074,6 +2224,16 @@ let ToolPipeline = class ToolPipeline {
2074
2224
  const offer = plan.offer;
2075
2225
  if (plan.ask.length === 0 || offer === undefined)
2076
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
+ }
2077
2237
  // the device's owner is the only person who may decide (spec §5.2)
2078
2238
  const owner = await this.deps.db
2079
2239
  .selectFrom("devices")
@@ -2114,18 +2274,57 @@ let ToolPipeline = class ToolPipeline {
2114
2274
  step: ctx.step,
2115
2275
  callId,
2116
2276
  requestedFor: owner.owner_account_id,
2117
- detail: {
2118
- deviceId: report.deviceId,
2119
- hosts: plan.ask,
2120
- command: typeof given.command === "string" ? clipText(given.command, 2000) : "",
2121
- description: typeof given.description === "string" ? given.description : null,
2122
- appliesAt: offer.appliesAt,
2123
- result: kept,
2124
- },
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
+ },
2125
2298
  scopes: offer.scopes,
2126
2299
  });
2127
2300
  return { kind: "wait", wait: approvalWait(ask), content: kept.content };
2128
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
+ }
2129
2328
  /** Appends a sub-agent's connect card to its root conversation ({@link rootSurfaceOf}). */
2130
2329
  async surfaceConnectInRoot(ctx, parent, callId, toolKey) {
2131
2330
  const target = await rootSurfaceOf(this.deps.db, ctx.conversationId, ctx.runId, parent);
@@ -2279,6 +2478,13 @@ let ToolPipeline = class ToolPipeline {
2279
2478
  toolKey,
2280
2479
  form: req.form,
2281
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
+ }),
2282
2488
  });
2283
2489
  return inputWait(q);
2284
2490
  }
@@ -2360,6 +2566,7 @@ let ToolPipeline = class ToolPipeline {
2360
2566
  };
2361
2567
  // 内置工具可按输入给自己的时限(沙箱 bash 按命令超时加余量);缺省 tools.timeoutMs
2362
2568
  const timeoutMs = tool.timeoutMs?.(input) ?? this.config.get().tools.timeoutMs;
2569
+ let scope;
2363
2570
  try {
2364
2571
  // a plugin tool runs with the extension's effective config for the org, never without it
2365
2572
  // (layering spec A §6): one read per call, cached by EffectiveConfigs
@@ -2381,20 +2588,41 @@ let ToolPipeline = class ToolPipeline {
2381
2588
  const r = await this.bounded(ctx.signal, async (signal) => {
2382
2589
  await this.txHost.run(async () => { });
2383
2590
  signal.throwIfAborted();
2384
- 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);
2385
2612
  }, undefined, timeoutMs);
2386
2613
  if (r === "timeout") {
2387
- return { kind: "error", message: timeoutText(tool.key, timeoutMs) };
2614
+ return withBlocked({ kind: "error", message: timeoutText(tool.key, timeoutMs) }, scope);
2388
2615
  }
2616
+ // a launch reviewed before the call stopped or asked is kept with its result
2389
2617
  if (r === "aborted")
2390
- return { kind: "error", message: RUN_STOPPED_DURING_TEXT };
2618
+ return withBlocked({ kind: "error", message: RUN_STOPPED_DURING_TEXT }, scope);
2391
2619
  if (isInputRequired(r.value)) {
2392
- 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);
2393
2621
  }
2394
- return { kind: "result", result: r.value };
2622
+ return withBlocked({ kind: "result", result: r.value }, scope);
2395
2623
  }
2396
2624
  catch (e) {
2397
- return this.thrown(tool.key, e);
2625
+ return withBlocked(this.thrown(tool.key, e), scope);
2398
2626
  }
2399
2627
  }
2400
2628
  async executeConnector(tool, source, input, ctx, resume) {
@@ -2576,6 +2804,9 @@ let ToolPipeline = class ToolPipeline {
2576
2804
  thrown(key, e) {
2577
2805
  if (e instanceof ToolError)
2578
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 };
2579
2810
  // an extension tool's ctx.models.embed denied by a policy hook (spec B §5.4): the model sees the
2580
2811
  // deny text (sanitized reason), as for a denied tool call, not a generic failure
2581
2812
  if (e instanceof ApiError && e.code === "model.hook_denied") {