@withgateway/sdk 0.4.0 → 0.9.1

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/agents/index.d.mts +573 -0
  2. package/dist/agents/index.d.ts +573 -0
  3. package/dist/agents/index.js +1443 -0
  4. package/dist/agents/index.js.map +1 -0
  5. package/dist/agents/index.mjs +1394 -0
  6. package/dist/agents/index.mjs.map +1 -0
  7. package/dist/apiError-DHpfbmdx.d.mts +17 -0
  8. package/dist/apiError-DHpfbmdx.d.ts +17 -0
  9. package/dist/cli.js +5655 -1890
  10. package/dist/cli.js.map +1 -1
  11. package/dist/cli.mjs +5769 -2005
  12. package/dist/cli.mjs.map +1 -1
  13. package/dist/files/index.d.mts +3 -1
  14. package/dist/files/index.d.ts +3 -1
  15. package/dist/files/index.js +418 -120
  16. package/dist/files/index.js.map +1 -1
  17. package/dist/files/index.mjs +418 -120
  18. package/dist/files/index.mjs.map +1 -1
  19. package/dist/hooks/index.js +346 -136
  20. package/dist/hooks/index.js.map +1 -1
  21. package/dist/hooks/index.mjs +346 -136
  22. package/dist/hooks/index.mjs.map +1 -1
  23. package/dist/{index-DUHmS74p.d.ts → index-DIN14Lhg.d.ts} +27 -4
  24. package/dist/{index-mJhG3vZU.d.mts → index-DuB-eQ0Z.d.mts} +27 -4
  25. package/dist/index.d.mts +7 -4
  26. package/dist/index.d.ts +7 -4
  27. package/dist/index.js +2862 -438
  28. package/dist/index.js.map +1 -1
  29. package/dist/index.mjs +2820 -431
  30. package/dist/index.mjs.map +1 -1
  31. package/dist/media-CQUC7TkS.d.mts +39 -0
  32. package/dist/media-DQnBloaX.d.ts +39 -0
  33. package/dist/replay/index.d.mts +1 -1
  34. package/dist/replay/index.d.ts +1 -1
  35. package/dist/replay/index.js.map +1 -1
  36. package/dist/replay/index.mjs.map +1 -1
  37. package/dist/traces/index.d.mts +3 -1
  38. package/dist/traces/index.d.ts +3 -1
  39. package/dist/traces/index.js +418 -120
  40. package/dist/traces/index.js.map +1 -1
  41. package/dist/traces/index.mjs +418 -120
  42. package/dist/traces/index.mjs.map +1 -1
  43. package/dist/tracing/index.d.mts +3 -2
  44. package/dist/tracing/index.d.ts +3 -2
  45. package/dist/tracing/index.js +257 -16
  46. package/dist/tracing/index.js.map +1 -1
  47. package/dist/tracing/index.mjs +257 -16
  48. package/dist/tracing/index.mjs.map +1 -1
  49. package/dist/transport-CpRe7zgd.d.mts +123 -0
  50. package/dist/transport-CpRe7zgd.d.ts +123 -0
  51. package/dist/worlds/index.d.mts +2086 -1749
  52. package/dist/worlds/index.d.ts +2086 -1749
  53. package/dist/worlds/index.js +1471 -269
  54. package/dist/worlds/index.js.map +1 -1
  55. package/dist/worlds/index.mjs +1466 -265
  56. package/dist/worlds/index.mjs.map +1 -1
  57. package/package.json +6 -1
  58. package/runtime/gatewaysdk/environment/_bundle.py +4 -6
  59. package/runtime/gatewaysdk/environment/_world.py +24 -1
  60. package/runtime/gatewaysdk/environment/bundle_manifest.py +243 -0
  61. package/runtime/gatewaysdk/environment/runtime.py +45 -2
  62. package/runtime/gatewaysdk/environment/schema/__main__.py +2 -2
  63. package/runtime/gatewaysdk/environment/schema/_slack_fidelity.py +8 -23
  64. package/runtime/gatewaysdk/environment/schema/api.py +27 -7
  65. package/runtime/gatewaysdk/environment/schema/assertions.py +7 -1
  66. package/runtime/gatewaysdk/environment/schema/bundle_runtime.py +2 -0
  67. package/runtime/gatewaysdk/environment/schema/call_capture.py +13 -1
  68. package/runtime/gatewaysdk/environment/schema/call_log.py +66 -0
  69. package/runtime/gatewaysdk/environment/schema/call_redaction.py +6 -0
  70. package/runtime/gatewaysdk/environment/schema/compiler.py +4 -1
  71. package/runtime/gatewaysdk/environment/schema/conform.py +32 -8
  72. package/runtime/gatewaysdk/environment/schema/connector.py +5 -0
  73. package/runtime/gatewaysdk/environment/schema/connectors/custom/handlers.py +2 -1
  74. package/runtime/gatewaysdk/environment/schema/connectors/github/api/handlers.py +217 -58
  75. package/runtime/gatewaysdk/environment/schema/connectors/github/connector.toml +9 -19
  76. package/runtime/gatewaysdk/environment/schema/connectors/github/scenarios/default/seed/github_webhooks.json +10 -2
  77. package/runtime/gatewaysdk/environment/schema/connectors/github/tests/webhooks.json +47 -0
  78. package/runtime/gatewaysdk/environment/schema/connectors/github/world.json +21 -0
  79. package/runtime/gatewaysdk/environment/schema/connectors/jamf/api/handlers.py +185 -18
  80. package/runtime/gatewaysdk/environment/schema/connectors/jamf/connector.toml +29 -14
  81. package/runtime/gatewaysdk/environment/schema/connectors/jamf/provenance.json +43 -12
  82. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scenarios/default/seed/jamf_webhooks.json +2 -2
  83. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scope.toml +4 -17
  84. package/runtime/gatewaysdk/environment/schema/connectors/jamf/tests/webhooks.json +107 -0
  85. package/runtime/gatewaysdk/environment/schema/connectors/jamf/vendor-openapi.json +1 -1
  86. package/runtime/gatewaysdk/environment/schema/connectors/linear/api/handlers.py +85 -1
  87. package/runtime/gatewaysdk/environment/schema/connectors/linear/connector.toml +19 -31
  88. package/runtime/gatewaysdk/environment/schema/connectors/linear/provenance.json +18 -8
  89. package/runtime/gatewaysdk/environment/schema/connectors/linear/scenarios/default/seed/webhooks.json +19 -3
  90. package/runtime/gatewaysdk/environment/schema/connectors/linear/tests/test_webhooks.py +71 -0
  91. package/runtime/gatewaysdk/environment/schema/database/base.py +2 -2
  92. package/runtime/gatewaysdk/environment/schema/database/guard.py +2 -1
  93. package/runtime/gatewaysdk/environment/schema/handler_errors.py +27 -1
  94. package/runtime/gatewaysdk/environment/schema/host.py +74 -11
  95. package/runtime/gatewaysdk/environment/schema/host_browser.py +48 -0
  96. package/runtime/gatewaysdk/environment/schema/host_control.py +33 -2
  97. package/runtime/gatewaysdk/environment/schema/host_handoff.py +4 -1
  98. package/runtime/gatewaysdk/environment/schema/host_requests.py +14 -0
  99. package/runtime/gatewaysdk/environment/schema/host_session.py +13 -2
  100. package/runtime/gatewaysdk/environment/schema/host_surfaces.py +6 -0
  101. package/runtime/gatewaysdk/environment/schema/host_versions.py +96 -19
  102. package/runtime/gatewaysdk/environment/schema/journal.py +10 -4
  103. package/runtime/gatewaysdk/environment/schema/local.py +33 -7
  104. package/runtime/gatewaysdk/environment/schema/openapi_schemas.py +20 -5
  105. package/runtime/gatewaysdk/environment/schema/page_checks.py +123 -0
  106. package/runtime/gatewaysdk/environment/schema/platform.py +33 -480
  107. package/runtime/gatewaysdk/environment/schema/platform_templates.py +332 -0
  108. package/runtime/gatewaysdk/environment/schema/request_ledger.py +4 -1
  109. package/runtime/gatewaysdk/environment/schema/run_parameters.py +25 -0
  110. package/runtime/gatewaysdk/environment/schema/runtime.py +49 -4
  111. package/runtime/gatewaysdk/environment/schema/scaffold.py +369 -218
  112. package/runtime/gatewaysdk/environment/schema/session_files.py +13 -2
  113. package/runtime/gatewaysdk/environment/schema/skills/benchmarks-getting-started/SKILL.md +1 -1
  114. package/runtime/gatewaysdk/environment/schema/skills/connector-schema-authoring/CONNECTORS.md +3 -3
  115. package/runtime/gatewaysdk/environment/schema/skills/connector-schema-authoring/SKILL.md +20 -24
  116. package/runtime/gatewaysdk/environment/schema/skills/world-data-ingestion/SKILL.md +11 -11
  117. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/SKILL.md +9 -9
  118. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/cli-mcp-map.md +45 -12
  119. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/gotchas.md +40 -9
  120. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/journal-checks.md +17 -2
  121. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/new-world-sandbox.md +1 -1
  122. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/ui-map.md +3 -2
  123. package/runtime/gatewaysdk/environment/schema/slack.py +55 -10
  124. package/runtime/gatewaysdk/environment/schema/snapshot.py +30 -4
  125. package/runtime/gatewaysdk/environment/schema/tasks.py +25 -2
  126. package/runtime/gatewaysdk/environment/schema/template_record.py +131 -0
  127. package/runtime/gatewaysdk/environment/schema/tools_world.py +26 -5
  128. package/runtime/gatewaysdk/environment/schema/ui.py +54 -33
  129. package/runtime/gatewaysdk/environment/schema/ui_interactions.py +419 -0
  130. package/runtime/gatewaysdk/environment/schema/ui_recorder.js +895 -0
  131. package/runtime/gatewaysdk/environment/schema/ui_replay.py +366 -0
  132. package/runtime/gatewaysdk/environment/schema/ui_replay_record.LICENSE +25 -0
  133. package/runtime/gatewaysdk/environment/schema/ui_replay_record.js +109 -0
  134. package/runtime/gatewaysdk/environment/schema/validation.py +10 -1
  135. package/runtime/gatewaysdk/environment/schema/verbs.py +6 -0
  136. package/runtime/gatewaysdk/environment/schema/webhooks.py +687 -0
  137. package/runtime/gatewaysdk/environment/schema/worker.py +5 -1
  138. package/runtime/gatewaysdk/environment/schema/workers.py +8 -1
  139. package/runtime/gatewaysdk/environment/schema/world_host.py +64 -18
  140. package/runtime/gatewaysdk/environment/schema/world_tests.py +74 -0
  141. package/runtime/gatewaysdk/environment/secret_values.py +1 -1
  142. package/runtime/gatewaysdk/environment/world.py +34 -43
  143. package/runtime/gatewaysdk/environment/world_session_contract.py +7 -34
  144. package/skills/benchmarks-getting-started/SKILL.md +1 -1
  145. package/skills/connector-schema-authoring/CONNECTORS.md +3 -3
  146. package/skills/connector-schema-authoring/SKILL.md +20 -24
  147. package/skills/connector-schema-authoring/connector-worlds.md +155 -13
  148. package/skills/connector-schema-authoring/world-schema.md +36 -29
  149. package/skills/world-data-ingestion/SKILL.md +11 -11
  150. package/skills/worlds-getting-started/SKILL.md +9 -9
  151. package/skills/worlds-getting-started/references/cli-mcp-map.md +45 -12
  152. package/skills/worlds-getting-started/references/gotchas.md +40 -9
  153. package/skills/worlds-getting-started/references/journal-checks.md +17 -2
  154. package/skills/worlds-getting-started/references/new-world-sandbox.md +1 -1
  155. package/skills/worlds-getting-started/references/ui-map.md +3 -2
  156. package/dist/media-BIApiPzS.d.mts +0 -102
  157. package/dist/media-BIApiPzS.d.ts +0 -102
package/dist/index.mjs CHANGED
@@ -450,13 +450,77 @@ var init_scores = __esm({
450
450
  }
451
451
  });
452
452
 
453
+ // src/worlds/personalToken.ts
454
+ var TOKEN_NOT_PERSONAL, TOKEN_NEEDS_PROJECT, TOKEN_NEEDS_HOST, TOKEN_OTHER_HOST, TOKEN_BESIDE_KEYS, TOKEN_FILING, TOKEN_KEYS_ONLY, PERSONAL, PROJECT, ENV_KEYS, PersonalTokenRefused, bare, PersonalToken;
455
+ var init_personalToken = __esm({
456
+ "src/worlds/personalToken.ts"() {
457
+ "use strict";
458
+ TOKEN_NOT_PERSONAL = "GATEWAY_TOKEN takes a personal access token: pat_ followed by letters and digits only.";
459
+ TOKEN_NEEDS_PROJECT = "GATEWAY_TOKEN acts in the project GATEWAY_PROJECT_ID names: set it to the official project's id (letters, digits, - and _).";
460
+ TOKEN_NEEDS_HOST = "GATEWAY_TOKEN goes only to the host GATEWAY_HOST names: set GATEWAY_HOST.";
461
+ TOKEN_OTHER_HOST = "GATEWAY_TOKEN goes only to the host GATEWAY_HOST names, and this call names another host: point the call at GATEWAY_HOST or unset GATEWAY_TOKEN.";
462
+ TOKEN_BESIDE_KEYS = "GATEWAY_TOKEN is set beside a project key (GATEWAY_PUBLIC_KEY, GATEWAY_SECRET_KEY, GATEWAY_API_KEY or a key passed in): unset one of them. Neither replaces the other.";
463
+ TOKEN_FILING = "Filing an evaluation takes your project's key pair, not GATEWAY_TOKEN: unset it (an official world runs once copied into your own project).";
464
+ TOKEN_KEYS_ONLY = "Task-run tracing exports with a project key pair (GATEWAY_PUBLIC_KEY / GATEWAY_SECRET_KEY), not GATEWAY_TOKEN.";
465
+ PERSONAL = /^pat_[A-Za-z0-9]+$/;
466
+ PROJECT = /^[A-Za-z0-9_-]+$/;
467
+ ENV_KEYS = ["GATEWAY_PUBLIC_KEY", "GATEWAY_SECRET_KEY", "GATEWAY_API_KEY"];
468
+ PersonalTokenRefused = class extends Error {
469
+ };
470
+ bare = (host) => host.replace(/\/+$/, "");
471
+ PersonalToken = class _PersonalToken {
472
+ constructor(value, project, host) {
473
+ this.value = value;
474
+ this.project = project;
475
+ this.host = host;
476
+ }
477
+ value;
478
+ project;
479
+ host;
480
+ static fromEnv(env, request = {}) {
481
+ const value = env.GATEWAY_TOKEN;
482
+ if (!value) return null;
483
+ if (request.keys || ENV_KEYS.some((name) => env[name])) throw new PersonalTokenRefused(TOKEN_BESIDE_KEYS);
484
+ const host = bare(env.GATEWAY_HOST ?? "");
485
+ if (!host) throw new PersonalTokenRefused(TOKEN_NEEDS_HOST);
486
+ if (request.host && bare(request.host) !== host) throw new PersonalTokenRefused(TOKEN_OTHER_HOST);
487
+ if (!PERSONAL.test(value)) throw new PersonalTokenRefused(TOKEN_NOT_PERSONAL);
488
+ const project = env.GATEWAY_PROJECT_ID ?? "";
489
+ if (!PROJECT.test(project)) throw new PersonalTokenRefused(TOKEN_NEEDS_PROJECT);
490
+ return new _PersonalToken(value, project, host);
491
+ }
492
+ toJSON() {
493
+ return { project: this.project, host: this.host };
494
+ }
495
+ [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
496
+ return `PersonalToken { project: ${this.project}, host: ${this.host} }`;
497
+ }
498
+ static scrubbed(env) {
499
+ return Object.fromEntries(Object.entries(env).filter(([key2]) => key2 !== "GATEWAY_TOKEN"));
500
+ }
501
+ };
502
+ }
503
+ });
504
+
453
505
  // src/worlds/platformEndpoint.ts
454
506
  function platformEndpoint(options) {
507
+ if (options.token)
508
+ return {
509
+ host: (options.host ?? options.token.host).replace(/\/+$/, ""),
510
+ publicKey: options.publicKey ?? "",
511
+ secretKey: options.secretKey ?? "",
512
+ token: options.token
513
+ };
514
+ const token = PersonalToken.fromEnv(process.env, {
515
+ host: options.host,
516
+ keys: Boolean(options.publicKey || options.secretKey)
517
+ });
518
+ if (token) return { host: token.host, publicKey: "", secretKey: "", token };
519
+ const host = (options.host ?? process.env.GATEWAY_HOST ?? DEFAULT_HOST).replace(/\/+$/, "");
455
520
  const publicKey = options.publicKey ?? process.env.GATEWAY_PUBLIC_KEY;
456
521
  const secretKey = options.secretKey ?? process.env.GATEWAY_SECRET_KEY;
457
522
  if (!publicKey || !secretKey) return null;
458
- const host = options.host ?? process.env.GATEWAY_HOST ?? DEFAULT_HOST;
459
- return { host: host.replace(/\/+$/, ""), publicKey, secretKey };
523
+ return { host, publicKey, secretKey };
460
524
  }
461
525
  function requirePlatformEndpoint(options) {
462
526
  const endpoint = platformEndpoint(options);
@@ -467,11 +531,74 @@ var DEFAULT_HOST, GATEWAY_KEYS_MISSING;
467
531
  var init_platformEndpoint = __esm({
468
532
  "src/worlds/platformEndpoint.ts"() {
469
533
  "use strict";
534
+ init_personalToken();
470
535
  DEFAULT_HOST = "https://withgateway.ai";
471
536
  GATEWAY_KEYS_MISSING = "Gateway keys missing: set GATEWAY_PUBLIC_KEY / GATEWAY_SECRET_KEY (or pass publicKey/secretKey).";
472
537
  }
473
538
  });
474
539
 
540
+ // src/worlds/apiError.ts
541
+ function edgeAnswer(text2, status) {
542
+ if (status !== void 0 && status >= 500) return EDGE_ANSWERS[status] ?? EDGE_FAILURE;
543
+ return /^\s*</.test(text2) ? EDGE_PAGE : null;
544
+ }
545
+ function parseErrorBody(text2, status) {
546
+ const raw = { detail: text2.slice(0, DETAIL_LIMIT), code: null };
547
+ let parsed;
548
+ try {
549
+ parsed = JSON.parse(text2);
550
+ } catch {
551
+ return { detail: (edgeAnswer(text2, status) ?? text2).slice(0, DETAIL_LIMIT), code: null };
552
+ }
553
+ if (parsed === null || typeof parsed !== "object") return raw;
554
+ const { message, code, error } = parsed;
555
+ const stableCode = typeof code === "string" ? code : null;
556
+ if (typeof message !== "string") return { ...raw, code: stableCode };
557
+ const fields = invalidFields(error);
558
+ const said = fields ? `${message}: ${fields}` : message;
559
+ if (stableCode === null) return { detail: said.slice(0, DETAIL_LIMIT), code: null };
560
+ return {
561
+ detail: `${said} (${stableCode})`.slice(0, DETAIL_LIMIT),
562
+ code: stableCode
563
+ };
564
+ }
565
+ function invalidFields(error) {
566
+ const issues = Array.isArray(error) ? error : [];
567
+ return issues.filter(
568
+ (issue) => issue !== null && typeof issue === "object" && typeof issue.message === "string"
569
+ ).map((issue) => {
570
+ const path17 = Array.isArray(issue.path) ? issue.path.map(String).join(".") : "";
571
+ return path17 ? `${path17}: ${issue.message}` : issue.message;
572
+ }).join("; ");
573
+ }
574
+ var ApiError, DETAIL_LIMIT, EDGE_ANSWERS, EDGE_FAILURE, EDGE_PAGE;
575
+ var init_apiError = __esm({
576
+ "src/worlds/apiError.ts"() {
577
+ "use strict";
578
+ ApiError = class extends Error {
579
+ constructor(status, method, path17, text2) {
580
+ const parsed = parseErrorBody(text2, status);
581
+ super(`${method} ${path17} -> ${status}: ${parsed.detail}`);
582
+ this.status = status;
583
+ this.text = text2;
584
+ this.name = "ApiError";
585
+ this.code = parsed.code;
586
+ }
587
+ status;
588
+ text;
589
+ code;
590
+ };
591
+ DETAIL_LIMIT = 600;
592
+ EDGE_ANSWERS = {
593
+ 502: "Bad Gateway from the load balancer in front of the platform, not the platform's answer: the web server dropped the connection or restarted mid-request. Retry; if it repeats, the platform is restarting or overloaded.",
594
+ 503: "Service Unavailable from the load balancer in front of the platform, not the platform's answer: no web server was ready to take the request (a deploy or a restart). Retry in a minute.",
595
+ 504: "Gateway Time-out from the load balancer in front of the platform, not the platform's answer: the request sent nothing back within the load balancer's idle timeout (60 s unless the deployment raises it: Helm ingress.idleTimeoutSeconds) and was cut there, though the platform may still be running it. Check what it changed before you retry."
596
+ };
597
+ EDGE_FAILURE = "The platform failed without its JSON error body: a proxy in front of it answered, or the server stopped before its error handler ran. Retry; if it repeats, report the request and the time.";
598
+ EDGE_PAGE = "An HTML page answered instead of the platform's JSON: a proxy in front of the platform, or the configured host is not the platform.";
599
+ }
600
+ });
601
+
475
602
  // src/worlds/transport.ts
476
603
  function platformTimeoutMs(env = process.env) {
477
604
  const raw = env[PLATFORM_TIMEOUT_ENV];
@@ -480,10 +607,20 @@ function platformTimeoutMs(env = process.env) {
480
607
  if (Number.isInteger(value) && value > 0) return value;
481
608
  throw new Error(`${PLATFORM_TIMEOUT_ENV} must be a positive whole number of milliseconds, not \`${raw}\`.`);
482
609
  }
483
- var PLATFORM_TIMEOUT_ENV, PLATFORM_TIMEOUT_DEFAULT_MS, CHECK_HOST, RETRY, FETCH_LIMIT, CAUSES, UNKNOWN_CAUSE, TransportCause, UnreachableError, sleep2, RetryPolicy, Attempt, PlatformTransport;
610
+ function platformAuthorization(endpoint, url) {
611
+ const { token } = endpoint;
612
+ if (!token)
613
+ return { authorization: "Basic " + Buffer.from(`${endpoint.publicKey}:${endpoint.secretKey}`).toString("base64") };
614
+ if (endpoint.publicKey || endpoint.secretKey) throw new PersonalTokenRefused(TOKEN_BESIDE_KEYS);
615
+ if (!url.startsWith(`${token.host}/`)) throw new PersonalTokenRefused(TOKEN_OTHER_HOST);
616
+ return { authorization: `Bearer ${token.value}`, "x-gateway-project": token.project };
617
+ }
618
+ var PLATFORM_TIMEOUT_ENV, PLATFORM_TIMEOUT_DEFAULT_MS, CHECK_HOST, RETRY, FETCH_LIMIT, CAUSES, UNKNOWN_CAUSE, TransportCause, UnreachableError, sleep2, RetryPolicy, Attempt, PLATFORM_STREAM_IDLE_MS, REFUSAL_TEXT_LIMIT, KEYED_REDIRECTS, PlatformTransport, StreamWatch, PlatformStream;
484
619
  var init_transport = __esm({
485
620
  "src/worlds/transport.ts"() {
486
621
  "use strict";
622
+ init_apiError();
623
+ init_personalToken();
487
624
  PLATFORM_TIMEOUT_ENV = "GATEWAY_TIMEOUT_MS";
488
625
  PLATFORM_TIMEOUT_DEFAULT_MS = 12e4;
489
626
  CHECK_HOST = "Check GATEWAY_HOST (or --host) points at a running platform, then retry.";
@@ -523,6 +660,13 @@ var init_transport = __esm({
523
660
  `Retry; if the platform is slow, raise ${PLATFORM_TIMEOUT_ENV} (milliseconds per request).`
524
661
  );
525
662
  }
663
+ static idle(idleMs) {
664
+ return new _TransportCause(
665
+ `no data for ${idleMs / 1e3}s`,
666
+ null,
667
+ "The stream resumes from its last event; if it repeats, check the network between here and the platform."
668
+ );
669
+ }
526
670
  static of(error) {
527
671
  const cause = error instanceof Error && error.cause instanceof Error ? error.cause : void 0;
528
672
  const code = cause && "code" in cause && typeof cause.code === "string" ? cause.code : null;
@@ -535,11 +679,11 @@ var init_transport = __esm({
535
679
  }
536
680
  };
537
681
  UnreachableError = class extends Error {
538
- constructor(host, method, route, failure) {
539
- super(`${method} ${route}: no answer from ${host}: ${failure.describe()}. ${failure.next}`);
682
+ constructor(host, method, route2, failure) {
683
+ super(`${method} ${route2}: no answer from ${host}: ${failure.describe()}. ${failure.next}`);
540
684
  this.host = host;
541
685
  this.method = method;
542
- this.route = route;
686
+ this.route = route2;
543
687
  this.failure = failure;
544
688
  this.name = "UnreachableError";
545
689
  }
@@ -598,45 +742,277 @@ var init_transport = __esm({
598
742
  throw this.error;
599
743
  }
600
744
  };
745
+ PLATFORM_STREAM_IDLE_MS = 6e4;
746
+ REFUSAL_TEXT_LIMIT = 64 * 1024;
747
+ KEYED_REDIRECTS = "manual";
601
748
  PlatformTransport = class {
749
+ #endpoint;
750
+ #timeoutMs;
602
751
  constructor(endpoint, timeoutMs = platformTimeoutMs()) {
603
- this.endpoint = endpoint;
604
- this.timeoutMs = timeoutMs;
752
+ this.#endpoint = endpoint;
753
+ this.#timeoutMs = timeoutMs;
605
754
  }
606
- endpoint;
607
- timeoutMs;
608
755
  /** A request that legitimately takes longer (a sandbox exec, a world create) waits its own budget; every other one waits the default. */
609
756
  budget(ownMs) {
610
- return Math.max(ownMs ?? 0, this.timeoutMs);
757
+ return Math.max(ownMs ?? 0, this.#timeoutMs);
611
758
  }
612
- async send(method, route, body, opts = {}) {
759
+ /** One request; the caller's `signal` aborts it in flight and throws the signal's reason, never an `UnreachableError`. */
760
+ async send(method, route2, body, opts = {}) {
613
761
  const timeoutMs = this.budget(opts.timeoutMs);
614
- return (opts.retry ?? RetryPolicy.NONE).run(() => this.once(method, route, body, timeoutMs));
762
+ return (opts.retry ?? RetryPolicy.NONE).run(() => this.once(method, route2, body, timeoutMs, opts.signal));
763
+ }
764
+ /** `send`, then the 2xx body as JSON; any other answer throws `ApiError` with its status and stable `code`. */
765
+ async json(method, route2, body, opts = {}) {
766
+ const reply = await this.send(method, route2, body, opts);
767
+ if (!reply.ok) throw new ApiError(reply.status, method, route2, reply.text);
768
+ return JSON.parse(reply.text);
769
+ }
770
+ /** The streaming twin of `send` for a `GET` event stream: nothing is buffered, `after` travels as `Last-Event-ID`, and each wait for the platform (the headers, every chunk) may last `idleMs` (default 60 s) instead of the request budget. */
771
+ async stream(route2, opts = {}) {
772
+ const watch = new StreamWatch(opts.signal, opts.idleMs ?? PLATFORM_STREAM_IDLE_MS, this.#endpoint.host, route2);
773
+ const headers = this.headers(route2, "text/event-stream", opts.after ? { "last-event-id": opts.after } : {});
774
+ try {
775
+ const response = await watch.within(
776
+ () => fetch(this.url(route2), { method: "GET", headers, signal: watch.signal, redirect: KEYED_REDIRECTS })
777
+ );
778
+ return new PlatformStream(response, watch);
779
+ } catch (error) {
780
+ watch.close();
781
+ throw error;
782
+ }
783
+ }
784
+ url(route2) {
785
+ return `${this.#endpoint.host}${route2}`;
786
+ }
787
+ headers(route2, accept, extra = {}) {
788
+ return {
789
+ "content-type": "application/json",
790
+ accept,
791
+ ...platformAuthorization(this.#endpoint, this.url(route2)),
792
+ ...extra
793
+ };
615
794
  }
616
- async once(method, route, body, timeoutMs) {
795
+ async once(method, route2, body, timeoutMs, caller) {
796
+ if (caller?.aborted) throw caller.reason;
617
797
  const payload = body === void 0 ? {} : { body: JSON.stringify(body) };
798
+ const headers = this.headers(route2, "application/json");
618
799
  const controller = new AbortController();
619
800
  const timer = setTimeout(() => controller.abort(), timeoutMs);
801
+ const relay = () => controller.abort(caller?.reason);
802
+ caller?.addEventListener("abort", relay, { once: true });
620
803
  try {
621
- const res = await fetch(`${this.endpoint.host}${route}`, {
804
+ const res = await fetch(this.url(route2), {
622
805
  method,
623
- headers: {
624
- "content-type": "application/json",
625
- accept: "application/json",
626
- authorization: "Basic " + Buffer.from(`${this.endpoint.publicKey}:${this.endpoint.secretKey}`).toString("base64")
627
- },
806
+ headers,
628
807
  ...payload,
629
- signal: controller.signal
808
+ signal: controller.signal,
809
+ redirect: KEYED_REDIRECTS
630
810
  });
631
811
  return { status: res.status, ok: res.ok, text: await res.text() };
632
812
  } catch (error) {
813
+ if (caller?.aborted) throw caller.reason;
633
814
  const cause = controller.signal.aborted ? TransportCause.timeout(timeoutMs) : TransportCause.of(error);
634
- throw new UnreachableError(this.endpoint.host, method, route, cause);
815
+ throw new UnreachableError(this.#endpoint.host, method, route2, cause);
635
816
  } finally {
636
817
  clearTimeout(timer);
818
+ caller?.removeEventListener("abort", relay);
637
819
  }
638
820
  }
639
821
  };
822
+ StreamWatch = class {
823
+ constructor(caller, idleMs, host, route2) {
824
+ this.idleMs = idleMs;
825
+ this.host = host;
826
+ this.route = route2;
827
+ this.#caller = caller;
828
+ caller?.addEventListener("abort", this.#relay, { once: true });
829
+ if (caller?.aborted) this.#relay();
830
+ }
831
+ idleMs;
832
+ host;
833
+ route;
834
+ #controller = new AbortController();
835
+ #caller;
836
+ #relay = () => this.#controller.abort(this.#caller?.reason);
837
+ #idled = false;
838
+ get signal() {
839
+ return this.#controller.signal;
840
+ }
841
+ async within(wait) {
842
+ const timer = setTimeout(() => this.idle(), this.idleMs);
843
+ try {
844
+ return await wait();
845
+ } catch (error) {
846
+ throw this.failure(error);
847
+ } finally {
848
+ clearTimeout(timer);
849
+ }
850
+ }
851
+ close() {
852
+ this.#caller?.removeEventListener("abort", this.#relay);
853
+ this.#controller.abort();
854
+ }
855
+ idle() {
856
+ this.#idled = true;
857
+ this.#controller.abort();
858
+ }
859
+ failure(error) {
860
+ if (this.#caller?.aborted) return this.#caller.reason;
861
+ const cause = this.#idled ? TransportCause.idle(this.idleMs) : TransportCause.of(error);
862
+ return new UnreachableError(this.host, "GET", this.route, cause);
863
+ }
864
+ };
865
+ PlatformStream = class {
866
+ #response;
867
+ #watch;
868
+ constructor(response, watch) {
869
+ this.#response = response;
870
+ this.#watch = watch;
871
+ }
872
+ get status() {
873
+ return this.#response.status;
874
+ }
875
+ get ok() {
876
+ return this.#response.ok;
877
+ }
878
+ /** The body as text, for a refusal: at most the first 64 KiB of characters; closes the stream. */
879
+ async text() {
880
+ const decoder = new TextDecoder();
881
+ let text2 = "";
882
+ for await (const chunk of this.chunks()) {
883
+ text2 += decoder.decode(chunk, { stream: true });
884
+ if (text2.length >= REFUSAL_TEXT_LIMIT) return text2.slice(0, REFUSAL_TEXT_LIMIT);
885
+ }
886
+ return text2 + decoder.decode();
887
+ }
888
+ /** The body's bytes as they arrive; the idle budget runs only while waiting for the platform, never while the caller holds a chunk. */
889
+ async *chunks() {
890
+ const reader = this.#response.body?.getReader();
891
+ try {
892
+ for (; ; ) {
893
+ const next = reader ? await this.#watch.within(() => reader.read()) : { done: true };
894
+ if (next.done) return;
895
+ yield next.value;
896
+ }
897
+ } finally {
898
+ this.close();
899
+ }
900
+ }
901
+ close() {
902
+ this.#watch.close();
903
+ }
904
+ };
905
+ }
906
+ });
907
+
908
+ // src/worlds/credentialField.ts
909
+ function isCredentialField(described) {
910
+ const words2 = described.replace(SPACES, " ").replace(/^ | $/g, "");
911
+ return SECRET_FIELD.some((prefix) => words2.startsWith(prefix)) || SECRET_KEY.test(words2);
912
+ }
913
+ function credentialTexts(pairs) {
914
+ return pairs.filter(([, text2]) => text2 !== null && text2 !== void 0).filter(([described]) => isCredentialField(String(described))).map(([, text2]) => String(text2));
915
+ }
916
+ function isTextField(described) {
917
+ return described !== "" && !NOT_TEXT.some((prefix) => described.startsWith(prefix));
918
+ }
919
+ function redactActionArgs(action, args) {
920
+ const secretField = action === "browser_type" && SECRET_KEY.test(String(args.selector ?? ""));
921
+ return Object.fromEntries(
922
+ Object.entries(args).map(([key2, value]) => [
923
+ key2,
924
+ redactedArg(key2, value, secretField)
925
+ ])
926
+ );
927
+ }
928
+ function redactedArg(key2, value, secretField) {
929
+ if (value === null || value === void 0) return null;
930
+ if (typeof value === "boolean" || typeof value === "number") return value;
931
+ if (typeof value !== "string") return "[omitted]";
932
+ if (SECRET_KEY.test(key2) || SECRET_VALUE.test(value) || secretField && key2 === "text")
933
+ return "[redacted]";
934
+ return value.length <= EVENT_MAX_STRING ? value : value.slice(0, EVENT_MAX_STRING) + "\u2026";
935
+ }
936
+ var SECRET_KEY, DESCRIBE_FIELD_JS, FIELD_VALUE_JS, FIELDS, SHORTEST_WITHHELD, WITHHELD_TEXT, SPACES, LINE_BREAK, TRIM, describeField, readFieldValue, readEditables, UNREADABLE, SECRET_FIELD, NOT_TEXT, escapeRegExp, urlForms, forms, CredentialText, EVENT_MAX_STRING, SECRET_VALUE;
937
+ var init_credentialField = __esm({
938
+ "src/worlds/credentialField.ts"() {
939
+ "use strict";
940
+ SECRET_KEY = /pass(word|wd|code|phrase)|pass(?![a-z])|secret|token(?!s)|(api|private)[-_ ]?key|authorization|cookie|one[-_ ]?time[-_ ]?(code|password)|(verification|security|recovery|backup)[-_ ]?codes?|security[-_ ]?answers?|social[-_ ]?security|(card|account|routing)[-_ ]?(number|no\b)|cc-(number|csc|exp)|(^|[-_ #.\["'=(])(otp|totp|mfa|2fa|pin|cvv|cvc|ssn|iban)([-_ \]"'):.,*]|$)/i;
941
+ DESCRIBE_FIELD_JS = "(e) => { if (!e) return ''; if (e.tagName === 'IFRAME' || e.tagName === 'FRAME') return 'frame'; const root = e.getRootNode(); const byIds = (at) => (at.getAttribute('aria-labelledby') || '').split(/\\s+/).map((id) => (id && root.getElementById ? root.getElementById(id) : null)).map((label) => (label ? label.textContent : '')).join(' '); const labels = e.labels ? [...e.labels].map((label) => label.textContent) : []; const context = []; for (let at = e.parentElement; at; at = at.parentElement) { const legend = at.tagName === 'FIELDSET' ? at.querySelector('legend') : null; context.push(at.getAttribute('aria-label'), byIds(at), legend ? legend.textContent : ''); } const names = [e.getAttribute('aria-label'), byIds(e), ...labels, e.getAttribute('placeholder'), e.getAttribute('title'), ...context]; if (e.tagName === 'SELECT') return ['select', e.name, e.id, ...names].filter(Boolean).join(' '); if (!(e.tagName === 'INPUT' || e.tagName === 'TEXTAREA' || e.isContentEditable)) return 'opaque'; return [e.type, e.name, e.id, e.getAttribute('autocomplete'), ...names].filter(Boolean).join(' '); }";
942
+ FIELD_VALUE_JS = "(e) => { if (e.tagName === 'SELECT') return [...e.selectedOptions].map((o) => o.text).join('\\n'); if (e.tagName === 'INPUT' || e.tagName === 'TEXTAREA') return e.value; return e.isContentEditable ? e.innerText : null; }";
943
+ FIELDS = "input:not([type=button]):not([type=submit]):not([type=reset]):not([type=image]):not([type=checkbox]):not([type=radio]):not([type=file]), textarea, select, [contenteditable]:not([contenteditable=false])";
944
+ SHORTEST_WITHHELD = 4;
945
+ WITHHELD_TEXT = "[redacted]";
946
+ SPACES = /[ \t\n\r\f\v]+/g;
947
+ LINE_BREAK = /\r\n|\r|\n/;
948
+ TRIM = /^[ \t\n\r\f\v]+|[ \t\n\r\f\v]+$/g;
949
+ describeField = new Function(
950
+ "e",
951
+ `return (${DESCRIBE_FIELD_JS})(e);`
952
+ );
953
+ readFieldValue = new Function(
954
+ "e",
955
+ `return (${FIELD_VALUE_JS})(e);`
956
+ );
957
+ readEditables = new Function(
958
+ "elements",
959
+ `return elements.map((e) => [(${DESCRIBE_FIELD_JS})(e), (${FIELD_VALUE_JS})(e)]);`
960
+ );
961
+ UNREADABLE = "unreadable";
962
+ SECRET_FIELD = ["password", "frame", "opaque", UNREADABLE];
963
+ NOT_TEXT = ["opaque", "frame", "select"];
964
+ escapeRegExp = (text2) => text2.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
965
+ urlForms = (text2) => {
966
+ let component;
967
+ try {
968
+ component = encodeURIComponent(text2);
969
+ } catch {
970
+ return [];
971
+ }
972
+ const form = component.replace(
973
+ /[!'()~]/g,
974
+ (c) => "%" + c.charCodeAt(0).toString(16).toUpperCase()
975
+ ).replace(/%20/g, "+");
976
+ return [component, component.replace(/%20/g, "+"), form];
977
+ };
978
+ forms = (text2) => {
979
+ const written = [
980
+ text2,
981
+ text2.replace(SPACES, " "),
982
+ JSON.stringify(text2).slice(1, -1)
983
+ ];
984
+ return [
985
+ ...written,
986
+ ...written.map((form) => form.replaceAll("'", "''")),
987
+ ...urlForms(text2)
988
+ ];
989
+ };
990
+ CredentialText = class {
991
+ pattern;
992
+ constructor(secrets) {
993
+ const texts = secrets.map((secret) => String(secret).replace(TRIM, ""));
994
+ const lines = texts.flatMap(
995
+ (text2) => text2.split(LINE_BREAK).map((line) => line.replace(TRIM, ""))
996
+ );
997
+ const whole = new Set(
998
+ [...texts, ...lines].filter(
999
+ (text2) => [...text2].length >= SHORTEST_WITHHELD
1000
+ )
1001
+ );
1002
+ const withheld = [
1003
+ ...new Set([...whole].flatMap((text2) => forms(text2)))
1004
+ ].sort((a, b) => b.length - a.length);
1005
+ this.pattern = withheld.length === 0 ? null : new RegExp(
1006
+ `(?<![A-Za-z0-9])(?:${withheld.map(escapeRegExp).join("|")})(?![A-Za-z0-9])`,
1007
+ "g"
1008
+ );
1009
+ }
1010
+ withhold(text2) {
1011
+ return this.pattern === null ? text2 : text2.replace(this.pattern, WITHHELD_TEXT);
1012
+ }
1013
+ };
1014
+ EVENT_MAX_STRING = 500;
1015
+ SECRET_VALUE = /^((sk|pk|ghp|xox[abp])[-_][-_A-Za-z0-9]{8,}|AKIA[0-9A-Z]{12,}|Bearer [-_.A-Za-z0-9]{8,})/;
640
1016
  }
641
1017
  });
642
1018
 
@@ -653,6 +1029,25 @@ function isBrowserGone(error) {
653
1029
  if (PAGE_NETWORK_ERROR.test(message)) return false;
654
1030
  return BROWSER_GONE_PATTERNS.some((p) => p.test(message));
655
1031
  }
1032
+ function scrubError(error, scrub) {
1033
+ const seen = /* @__PURE__ */ new Set();
1034
+ let at = error;
1035
+ while (at instanceof Error && !seen.has(at)) {
1036
+ seen.add(at);
1037
+ at.message = scrub(at.message);
1038
+ at.stack = at.stack && scrub(at.stack);
1039
+ scrubOwnText(at, scrub);
1040
+ at = at.cause;
1041
+ }
1042
+ }
1043
+ function scrubOwnText(error, scrub) {
1044
+ for (const key2 of Object.keys(error)) {
1045
+ const value = error[key2];
1046
+ if (typeof value === "string") error[key2] = scrub(value);
1047
+ if (Array.isArray(value) && value.every((item) => typeof item === "string"))
1048
+ error[key2] = value.map((item) => scrub(item));
1049
+ }
1050
+ }
656
1051
  function refusalIsTransient(error) {
657
1052
  const { status, code } = error;
658
1053
  if (typeof status !== "number") return true;
@@ -689,11 +1084,17 @@ var init_browserReconnect = __esm({
689
1084
  ].sort((a, b) => b.length - a.length);
690
1085
  }
691
1086
  scrub(text2) {
692
- const bare = this.secrets.reduce(
1087
+ const bare2 = this.secrets.reduce(
693
1088
  (out, secret) => out.split(secret).join(REDACTED),
694
1089
  text2
695
1090
  );
696
- return bare.replace(TOKEN_QUERY_VALUE, `$1${REDACTED}`);
1091
+ return bare2.replace(TOKEN_QUERY_VALUE, `$1${REDACTED}`);
1092
+ }
1093
+ /** Scrub `error` and the errors it was raised from, in place: the message,
1094
+ * the stack and every other own text property, Playwright's `log` call log
1095
+ * included. */
1096
+ scrubError(error) {
1097
+ scrubError(error, (text2) => this.scrub(text2));
697
1098
  }
698
1099
  };
699
1100
  BrowserReconnected = class extends Error {
@@ -845,22 +1246,6 @@ function capabilityLabel(url) {
845
1246
  }
846
1247
  return CAPABILITY_HOST.exec(host)?.[1] ?? null;
847
1248
  }
848
- function redactActionArgs(action, args) {
849
- const secretField = action === "browser_type" && SECRET_KEY.test(String(args.selector ?? ""));
850
- const out = {};
851
- for (const [key2, value] of Object.entries(args)) {
852
- if (value === null || value === void 0) out[key2] = null;
853
- else if (typeof value === "boolean" || typeof value === "number")
854
- out[key2] = value;
855
- else if (typeof value === "string") {
856
- if (SECRET_KEY.test(key2) || SECRET_VALUE.test(value) || secretField && key2 === "text")
857
- out[key2] = "[redacted]";
858
- else
859
- out[key2] = value.length <= EVENT_MAX_STRING ? value : value.slice(0, EVENT_MAX_STRING) + "\u2026";
860
- } else out[key2] = "[omitted]";
861
- }
862
- return out;
863
- }
864
1249
  async function loadPlaywright() {
865
1250
  try {
866
1251
  const name = "playwright";
@@ -922,62 +1307,14 @@ async function openBrowser(surfaces, opts = {}) {
922
1307
  scrubber
923
1308
  );
924
1309
  }
925
- function computerUseToolkit(browser, opts = {}) {
926
- const maxText = opts.maxText ?? 2e4;
927
- const observe2 = async (selector = "body") => {
928
- const text2 = await browser.text(selector);
929
- return {
930
- url: browser.url,
931
- title: await browser.title(),
932
- text: text2.slice(0, maxText),
933
- truncated: text2.length > maxText
934
- };
935
- };
936
- const impls = {
937
- browser_goto: async (a) => {
938
- await browser.goto(typeof a.path === "string" ? a.path : void 0);
939
- return observe2();
940
- },
941
- browser_click: async (a) => {
942
- await browser.click(str(a.selector, ""));
943
- return observe2();
944
- },
945
- browser_type: async (a) => {
946
- await browser.type(str(a.selector, ""), String(a.text ?? ""));
947
- return { ok: true, url: browser.url };
948
- },
949
- browser_press: async (a) => {
950
- await browser.press(str(a.key, "Enter"));
951
- return observe2();
952
- },
953
- browser_scroll: async (a) => {
954
- await browser.scroll(typeof a.dy === "number" ? a.dy : 600);
955
- return { ok: true, url: browser.url };
956
- },
957
- browser_screenshot: async (a) => ({
958
- image_base64: await browser.screenshotBase64(a.full_page === true),
959
- url: browser.url
960
- }),
961
- browser_read: async (a) => observe2(str(a.selector, "body")),
962
- browser_back: async () => {
963
- await browser.back();
964
- return observe2();
965
- }
966
- };
967
- const specs = COMPUTER_USE_SPECS.map((s) => ({ ...s }));
968
- return {
969
- schemas: specs.map((spec) => schemaFromSignature(spec)),
970
- impls,
971
- specs
972
- };
973
- }
974
- var SURFACE_KINDS, PLATFORM_SESSION_HEADER, SESSION_AUTH_MODES, BROWSER_TIERS, DEFAULT_VIEWPORT, SETTLE_TIMEOUT_MS, SETTLE_QUIET_MS, SETTLE_POLL_MS, EVENT_BATCH_SIZE, EVENT_FLUSH_INTERVAL_MS, EVENT_MAX_RETRIES, EVENT_SCREENSHOT_QUALITY, EVENT_MAX_STRING, SECRET_KEY, SECRET_VALUE, WorldSurfaceUnavailable, UI_TOKEN_QUERY, CAPABILITY_HOST, BrowserActionRecorder, WorldBrowser, COMPUTER_USE_SPECS, str;
1310
+ var SURFACE_KINDS, FIELD_PROBE_TIMEOUT_MS, PLATFORM_SESSION_HEADER, SESSION_AUTH_MODES, BROWSER_TIERS, DEFAULT_VIEWPORT, SETTLE_TIMEOUT_MS, SETTLE_QUIET_MS, SETTLE_POLL_MS, EVENT_BATCH_SIZE, EVENT_FLUSH_INTERVAL_MS, EVENT_MAX_RETRIES, EVENT_SCREENSHOT_QUALITY, WorldSurfaceUnavailable, UI_TOKEN_QUERY, CAPABILITY_HOST, BrowserActionRecorder, WorldBrowser;
975
1311
  var init_browser = __esm({
976
1312
  "src/worlds/browser.ts"() {
977
1313
  "use strict";
978
- init_session2();
1314
+ init_credentialField();
979
1315
  init_browserReconnect();
980
1316
  SURFACE_KINDS = ["tools", "api", "ui", "browser"];
1317
+ FIELD_PROBE_TIMEOUT_MS = 2e3;
981
1318
  PLATFORM_SESSION_HEADER = "X-World-Session";
982
1319
  SESSION_AUTH_MODES = ["vendor", "open"];
983
1320
  BROWSER_TIERS = ["standard", "premium"];
@@ -989,9 +1326,6 @@ var init_browser = __esm({
989
1326
  EVENT_FLUSH_INTERVAL_MS = 1e3;
990
1327
  EVENT_MAX_RETRIES = 3;
991
1328
  EVENT_SCREENSHOT_QUALITY = 60;
992
- EVENT_MAX_STRING = 500;
993
- SECRET_KEY = /pass(word|wd)?|secret|token|api[-_]?key|authorization|cookie|(^|[-_ #.\["'=])(otp|pin|cvv|ssn)([-_ \]"']|$)/i;
994
- SECRET_VALUE = /^((sk|pk|ghp|xox[abp])[-_][-_A-Za-z0-9]{8,}|AKIA[0-9A-Z]{12,}|Bearer [-_.A-Za-z0-9]{8,})/;
995
1329
  WorldSurfaceUnavailable = class extends Error {
996
1330
  constructor(surface, reason) {
997
1331
  super(`World surface '${surface}' is unavailable: ${reason}`);
@@ -1114,6 +1448,8 @@ var init_browser = __esm({
1114
1448
  recorder;
1115
1449
  reconnector;
1116
1450
  scrubber;
1451
+ typed = [];
1452
+ typedText = new CredentialText([]);
1117
1453
  current;
1118
1454
  inflight = 0;
1119
1455
  lastNetwork = Date.now();
@@ -1127,10 +1463,20 @@ var init_browser = __esm({
1127
1463
  get agentId() {
1128
1464
  return this.recorder?.agentId ?? null;
1129
1465
  }
1130
- /** `text` with this session's credentials (UI token, browser address) removed. */
1466
+ /** `text` with this session's credentials (UI token, browser address) and
1467
+ * the credentials typed into it removed. */
1131
1468
  scrub(text2) {
1469
+ return this.typedText.withhold(this.scrubber.scrub(text2));
1470
+ }
1471
+ /** `text` with this session's credentials removed and nothing else
1472
+ * changed: for text that is compared and never leaves the process. */
1473
+ scrubSession(text2) {
1132
1474
  return this.scrubber.scrub(text2);
1133
1475
  }
1476
+ /** Every credential typed into this browser by `type`. */
1477
+ get typedCredentials() {
1478
+ return [...this.typed];
1479
+ }
1134
1480
  watchNetwork(page) {
1135
1481
  page.on("request", () => {
1136
1482
  this.inflight += 1;
@@ -1174,7 +1520,7 @@ var init_browser = __esm({
1174
1520
  async recover(reconnector, cause) {
1175
1521
  const started = Date.now();
1176
1522
  const message = cause instanceof Error ? cause.message : String(cause);
1177
- const args = { cause: this.scrubber.scrub(message).slice(0, 200) };
1523
+ const args = { cause: this.scrub(message).slice(0, 200) };
1178
1524
  let result;
1179
1525
  try {
1180
1526
  result = await reconnector.recover(cause, (c) => this.adopt(c));
@@ -1209,7 +1555,9 @@ var init_browser = __esm({
1209
1555
  }
1210
1556
  /** Run one action and report it: the event carries what was asked,
1211
1557
  * whether it worked, and the screen after — for failures too, so a
1212
- * reviewer sees what the agent saw when the selector did not match. */
1558
+ * reviewer sees what the agent saw when the selector did not match. The
1559
+ * error it throws keeps no session credential and no credential typed into
1560
+ * this browser, which Playwright's call log would quote. */
1213
1561
  async act(action, args, fn, onLoss = "report") {
1214
1562
  const started = Date.now();
1215
1563
  try {
@@ -1217,6 +1565,7 @@ var init_browser = __esm({
1217
1565
  await this.report(action, args, started, null);
1218
1566
  return result;
1219
1567
  } catch (error) {
1568
+ this.scrubError(error);
1220
1569
  await this.report(action, args, started, error);
1221
1570
  throw error;
1222
1571
  }
@@ -1225,7 +1574,7 @@ var init_browser = __esm({
1225
1574
  async report(action, args, started, failure) {
1226
1575
  const recorder = this.recorder;
1227
1576
  if (!recorder) return;
1228
- const error = failure === null ? null : this.scrubber.scrub(
1577
+ const error = failure === null ? null : this.scrub(
1229
1578
  failure instanceof Error ? `${failure.name}: ${failure.message}` : String(failure)
1230
1579
  ).slice(0, 4e3);
1231
1580
  recorder.record({
@@ -1238,7 +1587,7 @@ var init_browser = __esm({
1238
1587
  Object.fromEntries(
1239
1588
  Object.entries(args).map(([key2, value]) => [
1240
1589
  key2,
1241
- typeof value === "string" ? this.scrubber.scrub(value) : value
1590
+ typeof value === "string" ? this.scrub(value) : value
1242
1591
  ])
1243
1592
  )
1244
1593
  ),
@@ -1257,8 +1606,8 @@ var init_browser = __esm({
1257
1606
  screenshot: null
1258
1607
  };
1259
1608
  try {
1260
- out.url = this.scrubber.scrub(this.page.url());
1261
- out.title = this.scrubber.scrub(await this.page.title());
1609
+ out.url = this.scrub(this.page.url());
1610
+ out.title = this.scrub(await this.page.title());
1262
1611
  const jpeg = await this.page.screenshot({
1263
1612
  type: "jpeg",
1264
1613
  quality: EVENT_SCREENSHOT_QUALITY
@@ -1295,7 +1644,7 @@ var init_browser = __esm({
1295
1644
  async () => {
1296
1645
  await this.page.goto(target, { waitUntil: "load" });
1297
1646
  await this.settle();
1298
- return this.page.url();
1647
+ return this.url;
1299
1648
  },
1300
1649
  // Navigating again lands on the same page: safe to replay.
1301
1650
  "retry"
@@ -1305,7 +1654,7 @@ var init_browser = __esm({
1305
1654
  return this.act("browser_back", {}, async () => {
1306
1655
  await this.page.goBack({ waitUntil: "load" });
1307
1656
  await this.settle();
1308
- return this.page.url();
1657
+ return this.url;
1309
1658
  });
1310
1659
  }
1311
1660
  /** Wait for the page to finish reacting to an action. `load` alone is not
@@ -1324,19 +1673,54 @@ var init_browser = __esm({
1324
1673
  await this.page.waitForTimeout(SETTLE_POLL_MS);
1325
1674
  }
1326
1675
  }
1327
- async click(selector) {
1676
+ async click(selector, opts = {}) {
1328
1677
  await this.act("browser_click", { selector }, async () => {
1329
- await this.page.click(selector);
1678
+ await this.page.click(selector, { timeout: opts.timeoutMs });
1330
1679
  await this.settle();
1331
1680
  });
1332
1681
  }
1333
- async type(selector, text2) {
1682
+ /** Replace the field's value with `text`. `opts.credential` is whether the
1683
+ * field takes one, when the caller already probed it; a credential is
1684
+ * withheld from the event and from any error. */
1685
+ async type(selector, text2, opts = {}) {
1686
+ const secret = opts.credential ?? await this.credentialField(selector);
1687
+ if (secret) this.typed.push(text2);
1688
+ this.typedText = new CredentialText(this.typed);
1334
1689
  await this.act(
1335
1690
  "browser_type",
1336
- { selector, text: text2 },
1337
- () => this.page.fill(selector, text2)
1691
+ { selector, text: secret ? "[redacted]" : text2 },
1692
+ () => this.page.fill(selector, text2, { timeout: opts.timeoutMs })
1338
1693
  );
1339
1694
  }
1695
+ /** `DESCRIBE_FIELD_JS` of the element `selector` finds, or `UNREADABLE`. */
1696
+ async describeField(selector) {
1697
+ try {
1698
+ const described = await this.page.locator(selector).evaluate(describeField, void 0, { timeout: FIELD_PROBE_TIMEOUT_MS });
1699
+ return String(described ?? "");
1700
+ } catch {
1701
+ return UNREADABLE;
1702
+ }
1703
+ }
1704
+ /** Whether the field `selector` finds takes a credential; one it cannot
1705
+ * read counts. */
1706
+ async credentialField(selector) {
1707
+ return isCredentialField(await this.describeField(selector));
1708
+ }
1709
+ /** What the field `selector` finds holds (`FIELD_VALUE_JS`), or null when
1710
+ * it cannot be read. */
1711
+ async fieldValue(selector) {
1712
+ try {
1713
+ const value = await this.page.locator(selector).evaluate(readFieldValue, void 0, { timeout: FIELD_PROBE_TIMEOUT_MS });
1714
+ return value === null || value === void 0 ? null : String(value);
1715
+ } catch {
1716
+ return null;
1717
+ }
1718
+ }
1719
+ /** Take this session's credentials out of `error` and the errors it came
1720
+ * from, in place. */
1721
+ scrubError(error) {
1722
+ scrubError(error, (text2) => this.scrub(text2));
1723
+ }
1340
1724
  async press(key2) {
1341
1725
  await this.act("browser_press", { key: key2 }, async () => {
1342
1726
  await this.page.keyboard.press(key2);
@@ -1359,14 +1743,39 @@ var init_browser = __esm({
1359
1743
  async screenshotBase64(fullPage = false) {
1360
1744
  return (await this.screenshot(fullPage)).toString("base64");
1361
1745
  }
1746
+ /** The visible text of `selector`'s element, without what any field on the
1747
+ * page that takes a credential holds. */
1362
1748
  async text(selector = "body") {
1363
- return this.resilient(() => this.page.innerText(selector), "retry");
1749
+ const withheld = new CredentialText(await this.credentialTexts());
1750
+ return withheld.withhold(
1751
+ await this.resilient(() => this.page.innerText(selector), "retry")
1752
+ );
1753
+ }
1754
+ /** What each field on the page that takes a credential holds: an input's
1755
+ * or textarea's value, a select's chosen option, a contenteditable's text. */
1756
+ async credentialTexts() {
1757
+ return this.resilient(async () => {
1758
+ const pairs = await this.page.locator(FIELDS).evaluateAll(readEditables);
1759
+ return credentialTexts(pairs);
1760
+ }, "retry");
1761
+ }
1762
+ /** Wait until the element `selector` finds could be clicked, without
1763
+ * clicking it. */
1764
+ async actionable(selector) {
1765
+ await this.resilient(() => this.page.locator(selector).click({ trial: true }), "retry");
1766
+ }
1767
+ async ariaSnapshot() {
1768
+ return this.resilient(async () => {
1769
+ if (!this.page.ariaSnapshot)
1770
+ throw new TypeError("this Playwright has no page.ariaSnapshot");
1771
+ return this.page.ariaSnapshot({ mode: "ai" });
1772
+ }, "retry");
1364
1773
  }
1365
1774
  async html() {
1366
1775
  return this.resilient(() => this.page.content(), "retry");
1367
1776
  }
1368
1777
  get url() {
1369
- return this.page.url();
1778
+ return withoutUiToken(this.page.url());
1370
1779
  }
1371
1780
  async title() {
1372
1781
  return this.resilient(() => this.page.title(), "retry");
@@ -1379,21 +1788,504 @@ var init_browser = __esm({
1379
1788
  }
1380
1789
  }
1381
1790
  };
1791
+ }
1792
+ });
1793
+
1794
+ // src/worlds/pageState.ts
1795
+ function selectorRef(selector) {
1796
+ if (selector.includes("aria-ref"))
1797
+ throw new PageStateError(
1798
+ "aria-ref selectors are not taken: pass ref=\u2026 from browser_snapshot"
1799
+ );
1800
+ return REF_SELECTOR.exec(selector.replace(/^ +| +$/g, ""))?.[1] ?? null;
1801
+ }
1802
+ var DEFAULT_MAX_CHARS, REF_ACT_TIMEOUT_MS, STEADY_READS, NEEDS_PLAYWRIGHT, CHANGED, LINE_KEY, ATTRIBUTES, FOCUS, STATES, ROLE, REF, REF_SELECTOR, EDITABLE_ROLES, VALUE_KEYS, WITHHELD, PageStateError, AriaLine, Touched, sameLines, deeper, PageState, PageObserver;
1803
+ var init_pageState = __esm({
1804
+ "src/worlds/pageState.ts"() {
1805
+ "use strict";
1806
+ init_credentialField();
1807
+ DEFAULT_MAX_CHARS = 2e4;
1808
+ REF_ACT_TIMEOUT_MS = 2e3;
1809
+ STEADY_READS = 4;
1810
+ NEEDS_PLAYWRIGHT = "browser_snapshot needs Playwright 1.59 or newer (npm install playwright@latest)";
1811
+ CHANGED = "the page changed since the last browser_snapshot: take a new one (a page that never holds still can be driven with text= or CSS selectors)";
1812
+ LINE_KEY = /^ *- ('(?:[^']|'')*'|.*?)(:(?: .*)?)?$/s;
1813
+ ATTRIBUTES = /(?: \[[^[\]]*\])*$/;
1814
+ FOCUS = / \[active\]/g;
1815
+ STATES = / \[(?:checked(?:=mixed)?|expanded|pressed(?:=mixed)?|selected)\]/g;
1816
+ ROLE = /^[a-z]+/;
1817
+ REF = /\[ref=((?:f[0-9]+)?e[0-9]+)\]/g;
1818
+ REF_SELECTOR = /^ref=((?:f[0-9]+)?e[0-9]+)$/;
1819
+ EDITABLE_ROLES = /* @__PURE__ */ new Set([
1820
+ "textbox",
1821
+ "searchbox",
1822
+ "combobox",
1823
+ "spinbutton",
1824
+ "slider"
1825
+ ]);
1826
+ VALUE_KEYS = /* @__PURE__ */ new Set(["text", "/placeholder"]);
1827
+ WITHHELD = ": [redacted]";
1828
+ PageStateError = class extends Error {
1829
+ name = "PageStateError";
1830
+ };
1831
+ AriaLine = class _AriaLine {
1832
+ constructor(text2, indent, key2 = "", attributes = "", rest = "") {
1833
+ this.text = text2;
1834
+ this.indent = indent;
1835
+ this.key = key2;
1836
+ this.attributes = attributes;
1837
+ this.rest = rest;
1838
+ }
1839
+ text;
1840
+ indent;
1841
+ key;
1842
+ attributes;
1843
+ rest;
1844
+ static parse(text2) {
1845
+ const indent = text2.length - text2.replace(/^ +/, "").length;
1846
+ const found = LINE_KEY.exec(text2);
1847
+ if (!found) return new _AriaLine(text2, indent);
1848
+ const key2 = found[1].startsWith("'") ? found[1].slice(1, -1).replaceAll("''", "'") : found[1];
1849
+ return new _AriaLine(
1850
+ text2,
1851
+ indent,
1852
+ key2,
1853
+ ATTRIBUTES.exec(key2)?.[0] ?? "",
1854
+ found[2] ?? ""
1855
+ );
1856
+ }
1857
+ static parseAll(aria) {
1858
+ return aria === "" ? [] : aria.split("\n").map((text2) => _AriaLine.parse(text2));
1859
+ }
1860
+ get refs() {
1861
+ return [...this.attributes.matchAll(REF)].map((ref) => ref[1]);
1862
+ }
1863
+ get disabled() {
1864
+ return this.attributes.includes("[disabled]");
1865
+ }
1866
+ get editable() {
1867
+ const role = ROLE.exec(this.key)?.[0];
1868
+ return role !== void 0 && EDITABLE_ROLES.has(role);
1869
+ }
1870
+ /** A value line: a field's text, or the placeholder it shows. */
1871
+ get value() {
1872
+ return VALUE_KEYS.has(this.key);
1873
+ }
1874
+ get states() {
1875
+ return this.attributes.match(STATES) ?? [];
1876
+ }
1877
+ get namedLikeCredential() {
1878
+ return SECRET_KEY.test(
1879
+ this.key.slice(0, this.key.length - this.attributes.length)
1880
+ );
1881
+ }
1882
+ /** Whether every value in and under this line is withheld. A field is,
1883
+ * when it is named like a credential or sits in something that is, has no
1884
+ * ref to probe, or `describe` reads it as a credential field. Any other
1885
+ * line is, when it is named like a credential and holds typed text (a
1886
+ * contenteditable), or has no ref to tell. */
1887
+ async credentialField(describe2, withinCredential) {
1888
+ if (this.editable)
1889
+ return this.credentialFieldInput(describe2, withinCredential);
1890
+ if (!this.namedLikeCredential) return false;
1891
+ if (this.refs.length === 0) return true;
1892
+ return isTextField(await describe2(this.refs[0]));
1893
+ }
1894
+ async credentialFieldInput(describe2, withinCredential) {
1895
+ if (withinCredential || this.namedLikeCredential) return true;
1896
+ if (this.refs.length === 0) return true;
1897
+ return isCredentialField(await describe2(this.refs[0]));
1898
+ }
1899
+ /** The line as shown: `withholding` applied to its text, while its refs and
1900
+ * states are still read from the attribute run Playwright wrote, so a
1901
+ * withheld name cannot join that run. */
1902
+ withheldBy(withhold) {
1903
+ return new _AriaLine(
1904
+ this.withholding(withhold),
1905
+ this.indent,
1906
+ this.key,
1907
+ this.attributes,
1908
+ this.rest
1909
+ );
1910
+ }
1911
+ /** The line with `withhold` applied to its name and value, its attribute
1912
+ * run (refs, states, levels) as Playwright wrote it. */
1913
+ withholding(withhold) {
1914
+ const at = this.attributes ? this.text.lastIndexOf(
1915
+ this.attributes,
1916
+ this.text.length - this.rest.length - this.attributes.length
1917
+ ) : -1;
1918
+ if (at < 0) return withhold(this.text);
1919
+ const end = at + this.attributes.length;
1920
+ return withhold(this.text.slice(0, at)) + this.attributes + withhold(this.text.slice(end));
1921
+ }
1922
+ /** The line with its own value replaced, keeping the key as Playwright
1923
+ * wrote it. */
1924
+ get withheld() {
1925
+ if (this.key === "/placeholder" || !this.rest.startsWith(": "))
1926
+ return this.text;
1927
+ return this.text.slice(0, this.text.length - this.rest.length) + WITHHELD;
1928
+ }
1929
+ };
1930
+ Touched = class _Touched {
1931
+ constructor(clicked = /* @__PURE__ */ new Map(), typed = /* @__PURE__ */ new Map()) {
1932
+ this.clicked = clicked;
1933
+ this.typed = typed;
1934
+ }
1935
+ clicked;
1936
+ typed;
1937
+ afterClick(ref, states) {
1938
+ return new _Touched(new Map([...this.clicked, [ref, states]]), this.typed);
1939
+ }
1940
+ afterTyping(ref, text2) {
1941
+ return new _Touched(this.clicked, new Map([...this.typed, [ref, text2]]));
1942
+ }
1943
+ /** The snapshot's lines as the page should now read them. */
1944
+ expected(lines) {
1945
+ return this.compared(lines, (line) => this.leftByClick(line));
1946
+ }
1947
+ /** A fresh read's lines, in the same form. */
1948
+ actual(lines) {
1949
+ return this.compared(lines, (line) => line.states);
1950
+ }
1951
+ compared(lines, states) {
1952
+ const out = [];
1953
+ let typedAt = null;
1954
+ for (const line of lines) {
1955
+ if (typedAt !== null && line.indent > typedAt && line.value) continue;
1956
+ typedAt = this.isTyped(line) ? line.indent : null;
1957
+ out.push(this.comparedLine(line, states(line)));
1958
+ }
1959
+ return out;
1960
+ }
1961
+ isTyped(line) {
1962
+ return line.refs.some((ref) => this.typed.has(ref));
1963
+ }
1964
+ clickedRef(line) {
1965
+ return line.refs.find((ref) => this.clicked.has(ref));
1966
+ }
1967
+ leftByClick(line) {
1968
+ const ref = this.clickedRef(line);
1969
+ return ref === void 0 ? line.states : this.clicked.get(ref);
1970
+ }
1971
+ comparedLine(line, states) {
1972
+ if (this.isTyped(line))
1973
+ return (" ".repeat(line.indent) + "- " + line.key).replace(FOCUS, "");
1974
+ if (this.clickedRef(line) !== void 0)
1975
+ return line.text.replace(FOCUS, "").replace(STATES, "") + states.join("");
1976
+ return line.text.replace(FOCUS, "");
1977
+ }
1978
+ };
1979
+ sameLines = (a, b) => a.length === b.length && a.every((line, at) => line === b[at]);
1980
+ deeper = (line, below) => below !== null && line.indent > below ? below : null;
1981
+ PageState = class _PageState {
1982
+ constructor(url, title, snapshot, refs, disabled, truncated, credentials = /* @__PURE__ */ new Set()) {
1983
+ this.url = url;
1984
+ this.title = title;
1985
+ this.snapshot = snapshot;
1986
+ this.refs = refs;
1987
+ this.disabled = disabled;
1988
+ this.truncated = truncated;
1989
+ this.credentials = credentials;
1990
+ }
1991
+ url;
1992
+ title;
1993
+ snapshot;
1994
+ refs;
1995
+ disabled;
1996
+ truncated;
1997
+ credentials;
1998
+ static parse(aria, opts) {
1999
+ return _PageState.ofLines(AriaLine.parseAll(aria), opts);
2000
+ }
2001
+ static ofLines(lines, opts) {
2002
+ const maxChars = opts.maxChars ?? DEFAULT_MAX_CHARS;
2003
+ const shown = [];
2004
+ let size = 0;
2005
+ for (const line of lines) {
2006
+ const width = [...line.text].length + 1;
2007
+ if (size + width > maxChars) break;
2008
+ size += width;
2009
+ shown.push(line);
2010
+ }
2011
+ return new _PageState(
2012
+ opts.url,
2013
+ opts.title,
2014
+ shown.map((line) => line.text).join("\n"),
2015
+ new Set(shown.flatMap((line) => line.refs)),
2016
+ new Set(
2017
+ shown.filter((line) => line.disabled).flatMap((line) => line.refs)
2018
+ ),
2019
+ shown.length < lines.length,
2020
+ opts.credentials ?? /* @__PURE__ */ new Set()
2021
+ );
2022
+ }
2023
+ /** `aria` with credential values withheld: every value in and under a
2024
+ * credential field (see `AriaLine.credentialField`; `describe` is
2025
+ * `DESCRIBE_FIELD_JS` of a ref's element), the placeholder aside, and the
2026
+ * value of any line named like a credential. Names, roles and refs stay. */
2027
+ static async redacted(aria, describe2) {
2028
+ const out = [];
2029
+ const withheld = [];
2030
+ let withheldBelow = null;
2031
+ let credentialBelow = null;
2032
+ for (const line of AriaLine.parseAll(aria)) {
2033
+ withheldBelow = deeper(line, withheldBelow);
2034
+ credentialBelow = deeper(line, credentialBelow);
2035
+ if (withheldBelow === null && await line.credentialField(describe2, credentialBelow !== null))
2036
+ withheldBelow = line.indent;
2037
+ if (credentialBelow === null && line.namedLikeCredential)
2038
+ credentialBelow = line.indent;
2039
+ const hidden = withheldBelow !== null || line.namedLikeCredential;
2040
+ out.push(hidden ? line.withheld : line.text);
2041
+ if (hidden) withheld.push(...line.refs);
2042
+ }
2043
+ return { snapshot: out.join("\n"), withheld: new Set(withheld) };
2044
+ }
2045
+ target(ref) {
2046
+ if (!this.refs.has(ref))
2047
+ throw new PageStateError(
2048
+ `ref=${ref} is not in the last browser_snapshot: take a new one`
2049
+ );
2050
+ if (this.disabled.has(ref))
2051
+ throw new PageStateError(`ref=${ref} is disabled`);
2052
+ return `aria-ref=${ref}`;
2053
+ }
2054
+ observation() {
2055
+ return {
2056
+ url: this.url,
2057
+ title: this.title,
2058
+ snapshot: this.snapshot,
2059
+ truncated: this.truncated
2060
+ };
2061
+ }
2062
+ };
2063
+ PageObserver = class {
2064
+ constructor(browser, maxChars = DEFAULT_MAX_CHARS) {
2065
+ this.browser = browser;
2066
+ this.maxChars = maxChars;
2067
+ }
2068
+ browser;
2069
+ maxChars;
2070
+ last = null;
2071
+ seen = [];
2072
+ seenUrl = "";
2073
+ touched = new Touched();
2074
+ turn = Promise.resolve();
2075
+ async snapshot() {
2076
+ return this.inTurn(() => this.takeSnapshot());
2077
+ }
2078
+ async click(selector) {
2079
+ return this.inTurn(() => this.clickOnce(selector));
2080
+ }
2081
+ async type(selector, text2) {
2082
+ return this.inTurn(() => this.typeOnce(selector, text2));
2083
+ }
2084
+ /** One call at a time, so a tool call a model made in parallel cannot act
2085
+ * between another's checks and its action. */
2086
+ inTurn(fn) {
2087
+ const run = this.turn.then(fn, fn);
2088
+ this.turn = run.catch(() => void 0);
2089
+ return run;
2090
+ }
2091
+ async takeSnapshot() {
2092
+ const aria = this.browser.scrubSession(await this.steady());
2093
+ const shown = await PageState.redacted(
2094
+ aria,
2095
+ (ref) => this.browser.describeField(`aria-ref=${ref}`)
2096
+ );
2097
+ const secrets = new CredentialText([
2098
+ ...await this.withheldValues(shown),
2099
+ ...await this.browser.credentialTexts(),
2100
+ ...this.browser.typedCredentials
2101
+ ]);
2102
+ const lines = AriaLine.parseAll(shown.snapshot).map(
2103
+ (line) => line.withheldBy((text2) => secrets.withhold(text2))
2104
+ );
2105
+ this.last = PageState.ofLines(lines, {
2106
+ url: this.url(),
2107
+ title: this.browser.scrub(await this.browser.title()),
2108
+ maxChars: this.maxChars,
2109
+ credentials: shown.withheld
2110
+ });
2111
+ this.seen = AriaLine.parseAll(aria);
2112
+ this.seenUrl = this.browser.scrubSession(this.browser.url);
2113
+ this.touched = new Touched();
2114
+ return this.last;
2115
+ }
2116
+ /** The values of the fields the redaction withheld: a page may repeat them
2117
+ * in another line's name (a row or cell named from its content, a label
2118
+ * that wraps the field). */
2119
+ async withheldValues(shown) {
2120
+ const refs = AriaLine.parseAll(shown.snapshot).filter((line) => line.editable).flatMap((line) => line.refs).filter((ref) => shown.withheld.has(ref));
2121
+ const values = [];
2122
+ for (const ref of refs)
2123
+ values.push(await this.browser.fieldValue(`aria-ref=${ref}`) ?? "");
2124
+ return values;
2125
+ }
2126
+ async clickOnce(selector) {
2127
+ const ref = selectorRef(selector);
2128
+ if (ref === null) return this.browser.click(selector);
2129
+ const [, target] = this.target(ref);
2130
+ await this.ready(target);
2131
+ await this.browser.click(target, { timeoutMs: REF_ACT_TIMEOUT_MS });
2132
+ const left = (await this.now()).find((line) => line.refs.includes(ref));
2133
+ if (left) this.touched = this.touched.afterClick(ref, left.states);
2134
+ }
2135
+ async typeOnce(selector, text2) {
2136
+ const ref = selectorRef(selector);
2137
+ if (ref === null) return this.browser.type(selector, text2);
2138
+ const [last, target] = this.target(ref);
2139
+ const credential = last.credentials.has(ref) || await this.browser.credentialField(target);
2140
+ await this.ready(target);
2141
+ await this.browser.type(target, text2, {
2142
+ timeoutMs: REF_ACT_TIMEOUT_MS,
2143
+ credential
2144
+ });
2145
+ this.touched = this.touched.afterTyping(ref, text2);
2146
+ }
2147
+ target(ref) {
2148
+ if (this.last === null)
2149
+ throw new PageStateError(
2150
+ "ref=\u2026 selectors come from browser_snapshot: take one first"
2151
+ );
2152
+ return [this.last, this.last.target(ref)];
2153
+ }
2154
+ async ready(target) {
2155
+ await this.still();
2156
+ await this.browser.actionable(target);
2157
+ await this.still();
2158
+ }
2159
+ /** A page still rendering when it is read would refuse the model's next
2160
+ * ref, so the snapshot it is shown is one that read the same before and
2161
+ * after the page settled again. */
2162
+ async steady() {
2163
+ const untouched = new Touched();
2164
+ let aria = await this.read();
2165
+ for (let read = 1; read < STEADY_READS; read++) {
2166
+ await this.browser.settle();
2167
+ const again = await this.read();
2168
+ if (sameLines(
2169
+ untouched.actual(AriaLine.parseAll(again)),
2170
+ untouched.actual(AriaLine.parseAll(aria))
2171
+ ))
2172
+ return again;
2173
+ aria = again;
2174
+ }
2175
+ return aria;
2176
+ }
2177
+ async read() {
2178
+ try {
2179
+ return await this.browser.ariaSnapshot();
2180
+ } catch (error) {
2181
+ if (error instanceof TypeError)
2182
+ throw new PageStateError(NEEDS_PLAYWRIGHT);
2183
+ throw error;
2184
+ }
2185
+ }
2186
+ url() {
2187
+ return this.browser.scrub(this.browser.url);
2188
+ }
2189
+ async now() {
2190
+ return AriaLine.parseAll(this.browser.scrubSession(await this.read()));
2191
+ }
2192
+ async still() {
2193
+ if (this.browser.scrubSession(this.browser.url) !== this.seenUrl || !sameLines(
2194
+ this.touched.actual(await this.now()),
2195
+ this.touched.expected(this.seen)
2196
+ ))
2197
+ throw new PageStateError(CHANGED);
2198
+ for (const [ref, text2] of this.touched.typed)
2199
+ if (await this.browser.fieldValue(`aria-ref=${ref}`) !== text2)
2200
+ throw new PageStateError(CHANGED);
2201
+ }
2202
+ };
2203
+ }
2204
+ });
2205
+
2206
+ // src/worlds/browserTools.ts
2207
+ function computerUseToolkit(browser, opts = {}) {
2208
+ const maxText = opts.maxText ?? DEFAULT_MAX_CHARS;
2209
+ const pages = new PageObserver(browser, maxText);
2210
+ const observe2 = async (selector = "body") => {
2211
+ const text2 = browser.scrub(await browser.text(selector));
2212
+ return {
2213
+ url: browser.scrub(browser.url),
2214
+ title: browser.scrub(await browser.title()),
2215
+ text: text2.slice(0, maxText),
2216
+ truncated: text2.length > maxText
2217
+ };
2218
+ };
2219
+ const impls = {
2220
+ browser_goto: async (a) => {
2221
+ await browser.goto(typeof a.path === "string" ? a.path : void 0);
2222
+ return observe2();
2223
+ },
2224
+ browser_snapshot: async () => (await pages.snapshot()).observation(),
2225
+ browser_click: async (a) => {
2226
+ await pages.click(str(a.selector, ""));
2227
+ return observe2();
2228
+ },
2229
+ browser_type: async (a) => {
2230
+ await pages.type(str(a.selector, ""), String(a.text ?? ""));
2231
+ return { ok: true, url: browser.scrub(browser.url) };
2232
+ },
2233
+ browser_press: async (a) => {
2234
+ await browser.press(str(a.key, "Enter"));
2235
+ return observe2();
2236
+ },
2237
+ browser_scroll: async (a) => {
2238
+ await browser.scroll(typeof a.dy === "number" ? a.dy : 600);
2239
+ return { ok: true, url: browser.scrub(browser.url) };
2240
+ },
2241
+ browser_screenshot: async (a) => ({
2242
+ image_base64: await browser.screenshotBase64(a.full_page === true),
2243
+ url: browser.scrub(browser.url)
2244
+ }),
2245
+ browser_read: async (a) => observe2(str(a.selector, "body")),
2246
+ browser_back: async () => {
2247
+ await browser.back();
2248
+ return observe2();
2249
+ }
2250
+ };
2251
+ const specs = COMPUTER_USE_SPECS.map((s) => ({ ...s }));
2252
+ return {
2253
+ schemas: specs.map((spec) => schemaFromSignature(spec)),
2254
+ impls: Object.fromEntries(
2255
+ Object.entries(impls).map(([name, impl]) => [
2256
+ name,
2257
+ scrubbingErrors(browser, impl)
2258
+ ])
2259
+ ),
2260
+ specs
2261
+ };
2262
+ }
2263
+ var COMPUTER_USE_SPECS, scrubbingErrors, str;
2264
+ var init_browserTools = __esm({
2265
+ "src/worlds/browserTools.ts"() {
2266
+ "use strict";
2267
+ init_pageState();
2268
+ init_session2();
1382
2269
  COMPUTER_USE_SPECS = [
1383
2270
  {
1384
2271
  name: "browser_goto",
1385
2272
  signature: "browser_goto(path=None)",
1386
2273
  doc: "Open a page of the world's UI. `path` is a UI path like /customers, a full URL, or omitted for the entry page. Returns the URL and page text."
1387
2274
  },
2275
+ {
2276
+ name: "browser_snapshot",
2277
+ signature: "browser_snapshot()",
2278
+ doc: "The page as an accessibility tree, one line per element with its role, name and [ref=e3]. To act on an element, pass `ref=e3` as the selector of browser_click or browser_type. Returns {url, title, snapshot, truncated}."
2279
+ },
1388
2280
  {
1389
2281
  name: "browser_click",
1390
2282
  signature: "browser_click(selector)",
1391
- doc: "Click an element by Playwright selector (CSS, `text=Refund`, `role=button[name=Save]`). Returns the page text after the click."
2283
+ doc: "Click an element by `ref=e3` from the last browser_snapshot, or by Playwright selector (CSS, `text=Refund`, `role=button[name=Save]`). Returns the page text after the click."
1392
2284
  },
1393
2285
  {
1394
2286
  name: "browser_type",
1395
2287
  signature: "browser_type(selector, text)",
1396
- doc: "Replace the value of an input/textarea found by selector with `text`."
2288
+ doc: "Replace the value of an input/textarea, found by `ref=e3` or by selector, with `text`."
1397
2289
  },
1398
2290
  {
1399
2291
  name: "browser_press",
@@ -1421,6 +2313,14 @@ var init_browser = __esm({
1421
2313
  doc: "Go back one page in history."
1422
2314
  }
1423
2315
  ];
2316
+ scrubbingErrors = (browser, impl) => async (args) => {
2317
+ try {
2318
+ return await impl(args);
2319
+ } catch (error) {
2320
+ browser.scrubError(error);
2321
+ throw error;
2322
+ }
2323
+ };
1424
2324
  str = (v, fallback) => typeof v === "string" && v.length > 0 ? v : fallback;
1425
2325
  }
1426
2326
  });
@@ -1565,13 +2465,12 @@ function isNativePage(page) {
1565
2465
  const mouse = candidate?.mouse;
1566
2466
  return typeof candidate?.context === "function" && NATIVE_METHODS.every((m) => typeof mouse?.[m] === "function");
1567
2467
  }
1568
- var FOCUSED_FIELD_JS, SECRET_FOCUS, DRAG_STEPS, PNG_SIGNATURE, NATIVE_METHODS, Screen;
2468
+ var FOCUSED_FIELD_JS, DRAG_STEPS, PNG_SIGNATURE, NATIVE_METHODS, Screen;
1569
2469
  var init_screen = __esm({
1570
2470
  "src/worlds/nativeComputer/screen.ts"() {
1571
2471
  "use strict";
1572
- init_browser();
1573
- FOCUSED_FIELD_JS = "(() => { let e = document.activeElement; const inner = (el) => (el.shadowRoot && el.shadowRoot.activeElement) || (el.contentDocument && el.contentDocument.activeElement); while (e && inner(e)) e = inner(e); if (!e) return ''; if (e.tagName === 'IFRAME' || e.tagName === 'FRAME') return 'frame'; if (!(e.tagName === 'INPUT' || e.tagName === 'TEXTAREA' || e.isContentEditable)) return 'opaque'; return [e.type, e.name, e.id, e.getAttribute('autocomplete')].filter(Boolean).join(' '); })()";
1574
- SECRET_FOCUS = ["password", "frame", "opaque"];
2472
+ init_credentialField();
2473
+ FOCUSED_FIELD_JS = `(() => { let e = document.activeElement; const inner = (el) => (el.shadowRoot && el.shadowRoot.activeElement) || (el.contentDocument && el.contentDocument.activeElement); while (e && inner(e)) e = inner(e); return (${DESCRIBE_FIELD_JS})(e); })()`;
1575
2474
  DRAG_STEPS = 5;
1576
2475
  PNG_SIGNATURE = Buffer.from([
1577
2476
  137,
@@ -1662,7 +2561,7 @@ var init_screen = __esm({
1662
2561
  } catch {
1663
2562
  return true;
1664
2563
  }
1665
- return SECRET_FOCUS.some((prefix) => described.startsWith(prefix)) || SECRET_KEY.test(described);
2564
+ return isCredentialField(described);
1666
2565
  }
1667
2566
  /** CDP renders a clip at the page's device pixel ratio as well as its
1668
2567
  * `scale` (a Retina host doubles it), so a capture of the wrong width
@@ -1893,11 +2792,11 @@ var init_media = __esm({
1893
2792
  status
1894
2793
  );
1895
2794
  }
1896
- async send(method, route, body) {
1897
- const reply = await this.transport.send(method, route, body);
2795
+ async send(method, route2, body) {
2796
+ const reply = await this.transport.send(method, route2, body);
1898
2797
  if (!reply.ok)
1899
2798
  throw new MediaUploadError(
1900
- `${method} ${route} -> ${reply.status}`,
2799
+ `${method} ${route2} -> ${reply.status}`,
1901
2800
  reply.status
1902
2801
  );
1903
2802
  return reply.text ? JSON.parse(reply.text) : {};
@@ -2250,7 +3149,7 @@ function click(button, count) {
2250
3149
  modifiers: modifierChord(raw.text)
2251
3150
  });
2252
3151
  }
2253
- var SCROLL_STEP_PX, NOT_EXECUTED, MAX_ERROR2, SCROLL_DIRECTIONS, MEMBERS, AnthropicComputer, AnthropicComputer20251124;
3152
+ var SCROLL_STEP_PX, NOT_EXECUTED, MAX_ERROR2, SCROLL_DIRECTIONS, IMAGE_PARTS, MEMBERS, AnthropicComputer, AnthropicComputer20251124;
2254
3153
  var init_anthropic = __esm({
2255
3154
  "src/worlds/nativeComputer/anthropic.ts"() {
2256
3155
  "use strict";
@@ -2266,6 +3165,14 @@ var init_anthropic = __esm({
2266
3165
  left: [-1, 0],
2267
3166
  right: [1, 0]
2268
3167
  };
3168
+ IMAGE_PARTS = {
3169
+ 6: (data) => ({ type: "image-data", data, mediaType: "image/png" }),
3170
+ 7: (data) => ({
3171
+ type: "file",
3172
+ mediaType: "image/png",
3173
+ data: { type: "data", data }
3174
+ })
3175
+ };
2269
3176
  MEMBERS = {
2270
3177
  screenshot: () => new ComputerAction("screenshot"),
2271
3178
  zoom: (raw) => new ComputerAction("zoom", {
@@ -2375,15 +3282,17 @@ var init_anthropic = __esm({
2375
3282
  ];
2376
3283
  return [{ type: "text", text: result.text ?? "OK" }];
2377
3284
  }
2378
- /** For `anthropic.tools.computerToolset_20260801({ ...computer.aiSdk() })`
2379
- * (or `computer_20251124` with the legacy kind): `execute` runs one action
2380
- * and returns `{ type: "image", data }` or text; `toModelOutput` turns that
2381
- * into the tool result. Calls run one at a time, and once a call fails the
3285
+ /** For `anthropic.tools.computerToolset_20260801(computer.aiSdk({ version: 7 }))`
3286
+ * (AI SDK 7 only), or `computer_20251124` with the legacy kind (AI SDK 6
3287
+ * and 7): `execute` runs one action and returns `{ type: "image", data }` or
3288
+ * text; `toModelOutput` turns that into the tool result in the part shape
3289
+ * of `options.version`. Calls run one at a time, and once a call fails the
2382
3290
  * rest of that step's calls answer as not executed. */
2383
- aiSdk() {
3291
+ aiSdk(options = {}) {
3292
+ const imagePart = _AnthropicComputer.imagePart(options);
2384
3293
  let failedStep;
2385
- const execute = (input, options) => this.serial(async () => {
2386
- const step = options?.messages?.length;
3294
+ const execute = (input, options2) => this.serial(async () => {
3295
+ const step = options2?.messages?.length;
2387
3296
  if (step !== void 0 && step === failedStep)
2388
3297
  throw new Error(NOT_EXECUTED);
2389
3298
  try {
@@ -2395,7 +3304,7 @@ var init_anthropic = __esm({
2395
3304
  });
2396
3305
  return {
2397
3306
  execute,
2398
- toModelOutput: ({ output }) => _AnthropicComputer.aiSdkModelOutput(output)
3307
+ toModelOutput: ({ output }) => _AnthropicComputer.modelOutput(output, imagePart)
2399
3308
  };
2400
3309
  }
2401
3310
  static aiSdkOutput(result) {
@@ -2403,16 +3312,26 @@ var init_anthropic = __esm({
2403
3312
  return { type: "image", data: result.image.toString("base64") };
2404
3313
  return result.text ?? "OK";
2405
3314
  }
2406
- /** `image-data` is what AI SDK 6's Anthropic provider turns into an image
2407
- * block; AI SDK 7 still accepts it (and converts it to a `file` part). */
2408
- static aiSdkModelOutput(output) {
3315
+ /** A screenshot as the image part of AI SDK `options.version`:
3316
+ * `image-data` for 6 (the default), `file` with `{ type: "data", data }`
3317
+ * for 7. */
3318
+ static aiSdkModelOutput(output, options = {}) {
3319
+ return _AnthropicComputer.modelOutput(
3320
+ output,
3321
+ _AnthropicComputer.imagePart(options)
3322
+ );
3323
+ }
3324
+ static imagePart({
3325
+ version = 6
3326
+ }) {
3327
+ if (Object.hasOwn(IMAGE_PARTS, version)) return IMAGE_PARTS[version];
3328
+ throw new Error(
3329
+ `unsupported AI SDK version ${version}; choose ${Object.keys(IMAGE_PARTS).join(" or ")}`
3330
+ );
3331
+ }
3332
+ static modelOutput(output, imagePart) {
2409
3333
  if (typeof output === "string") return { type: "text", value: output };
2410
- return {
2411
- type: "content",
2412
- value: [
2413
- { type: "image-data", data: output.data, mediaType: "image/png" }
2414
- ]
2415
- };
3334
+ return { type: "content", value: [imagePart(output.data)] };
2416
3335
  }
2417
3336
  envelope(block, content, isError = false) {
2418
3337
  return {
@@ -2820,7 +3739,7 @@ var init_requestLedger = __esm({
2820
3739
  "use strict";
2821
3740
  init_worlds();
2822
3741
  init_sessionContract();
2823
- WORLD_REQUEST_VIAS = ["api", "ui", "tool"];
3742
+ WORLD_REQUEST_VIAS = ["api", "ui", "tool", "webhook", "page"];
2824
3743
  WorldRequestFilterError = class extends Error {
2825
3744
  };
2826
3745
  NOT_RECORDED = "This session's engine records no requests; only hosted World Host sessions do.";
@@ -3329,7 +4248,8 @@ async function openSession(slugOrRef, taskOrOpts = {}, positionalOpts = {}) {
3329
4248
  ...opts.reuseWarm === void 0 ? {} : { reuseWarm: opts.reuseWarm },
3330
4249
  ...opts.surfaces?.length ? { surfaces: opts.surfaces } : {},
3331
4250
  ...opts.browserTier === void 0 ? {} : { browserTier: opts.browserTier },
3332
- ...opts.auth === void 0 ? {} : { auth: opts.auth }
4251
+ ...opts.auth === void 0 ? {} : { auth: opts.auth },
4252
+ ...opts.worldState === void 0 ? {} : { worldState: opts.worldState }
3333
4253
  }
3334
4254
  );
3335
4255
  return new WorldSession(state2.sessionId, state2, options);
@@ -3416,6 +4336,7 @@ var init_session2 = __esm({
3416
4336
  "use strict";
3417
4337
  init_worlds();
3418
4338
  init_browser();
4339
+ init_browserTools();
3419
4340
  init_nativeComputer();
3420
4341
  init_sessionContract();
3421
4342
  init_toolSchema();
@@ -3481,6 +4402,9 @@ var init_session2 = __esm({
3481
4402
  get versionId() {
3482
4403
  return this.current.versionId;
3483
4404
  }
4405
+ get worldState() {
4406
+ return this.current.worldState ?? null;
4407
+ }
3484
4408
  /** Whether the session answered ready as of the last state read (the open,
3485
4409
  * a `status()`, or the poll inside `ready()`); no request is made. */
3486
4410
  get isReady() {
@@ -3752,13 +4676,13 @@ var init_session2 = __esm({
3752
4676
  WorldRequestQuery.parse({ cursor: opts.cursor, limit: opts.limit ?? REQUEST_LOG_PAGE_MAX })
3753
4677
  );
3754
4678
  }
3755
- page(route, limit, cursor) {
4679
+ page(route2, limit, cursor) {
3756
4680
  const query = new URLSearchParams({ limit: String(limit) });
3757
4681
  if (cursor) query.set("cursor", cursor);
3758
4682
  return apiRequest(
3759
4683
  this.options,
3760
4684
  "GET",
3761
- `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/${route}?${query.toString()}`
4685
+ `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/${route2}?${query.toString()}`
3762
4686
  );
3763
4687
  }
3764
4688
  /** The session's call log, oldest first: every tool call, seed, reset,
@@ -3850,6 +4774,7 @@ var init_session2 = __esm({
3850
4774
  "surfaces",
3851
4775
  "browserTier",
3852
4776
  "auth",
4777
+ "worldState",
3853
4778
  "options"
3854
4779
  ]);
3855
4780
  isOpenSessionOptions = (value) => typeof value === "object" && value !== null && Object.keys(value).every((key2) => OPEN_SESSION_OPTION_KEYS.has(key2));
@@ -4093,7 +5018,8 @@ async function openTask(ref, opts = {}) {
4093
5018
  task,
4094
5019
  ...opts.reuseWarm === void 0 ? {} : { reuseWarm: opts.reuseWarm },
4095
5020
  ...opts.surfaces?.length ? { surfaces: opts.surfaces } : {},
4096
- ...opts.browserTier === void 0 ? {} : { browserTier: opts.browserTier }
5021
+ ...opts.browserTier === void 0 ? {} : { browserTier: opts.browserTier },
5022
+ ...opts.worldStates === void 0 ? {} : { worldStates: opts.worldStates }
4097
5023
  }
4098
5024
  );
4099
5025
  return fromResponse(answer, options);
@@ -4351,16 +5277,22 @@ var init_evals = __esm({
4351
5277
  "src/worlds/evals.ts"() {
4352
5278
  "use strict";
4353
5279
  init_worlds();
5280
+ init_personalToken();
5281
+ init_platformEndpoint();
4354
5282
  init_transport();
4355
5283
  EVALUATIONS = "/api/public/benchmark-containers/evaluations";
4356
- GatewayEvalsClient = class {
5284
+ GatewayEvalsClient = class _GatewayEvalsClient {
4357
5285
  constructor(options = {}, retry = RetryPolicy.FILING) {
4358
5286
  this.options = options;
4359
5287
  this.retry = retry;
5288
+ _GatewayEvalsClient.refuseToken(options);
4360
5289
  }
4361
5290
  options;
4362
5291
  retry;
4363
5292
  keyed = /* @__PURE__ */ new Set();
5293
+ static refuseToken(options) {
5294
+ if (platformEndpoint(options)?.token) throw new PersonalTokenRefused(TOKEN_FILING);
5295
+ }
4364
5296
  async createEvaluation(versionId, opts = {}) {
4365
5297
  const body = { versionId };
4366
5298
  if (opts.model !== void 0) body.model = opts.model;
@@ -5043,7 +5975,7 @@ var require_package = __commonJS({
5043
5975
  "package.json"(exports, module) {
5044
5976
  module.exports = {
5045
5977
  name: "@withgateway/sdk",
5046
- version: "0.4.0",
5978
+ version: "0.9.1",
5047
5979
  description: "Gateway SDK for TypeScript - A/B experiments, tracing, and observability",
5048
5980
  main: "./dist/index.js",
5049
5981
  module: "./dist/index.mjs",
@@ -5124,6 +6056,11 @@ var require_package = __commonJS({
5124
6056
  import: "./dist/hooks/index.mjs",
5125
6057
  require: "./dist/hooks/index.js"
5126
6058
  },
6059
+ "./agents": {
6060
+ types: "./dist/agents/index.d.ts",
6061
+ import: "./dist/agents/index.mjs",
6062
+ require: "./dist/agents/index.js"
6063
+ },
5127
6064
  "./cli": {
5128
6065
  types: "./dist/cli.d.ts",
5129
6066
  import: "./dist/cli.mjs",
@@ -5819,6 +6756,7 @@ var init_taskTracing = __esm({
5819
6756
  "use strict";
5820
6757
  init_prerequisites();
5821
6758
  init_platformEndpoint();
6759
+ init_personalToken();
5822
6760
  HOST_WITH_AUTHORITY = /^[a-z][a-z0-9+.-]*:\/\/[^/\\?#@\s]+(\/|$)/i;
5823
6761
  TRACING_HELD_ELSEWHERE = "Tracing in this process already sends spans to another destination or with other keys (an earlier run, or the agent's own tracing.init()), so this run's spans would not reach its own project.";
5824
6762
  TaskTracing = class _TaskTracing {
@@ -5830,8 +6768,9 @@ var init_taskTracing = __esm({
5830
6768
  static target = null;
5831
6769
  async start(requested, options) {
5832
6770
  if (!requested) return false;
5833
- const endpoint = platformEndpoint(options);
6771
+ let endpoint = null;
5834
6772
  try {
6773
+ endpoint = platformEndpoint(options);
5835
6774
  await this.initOnce(_TaskTracing.config(endpoint));
5836
6775
  return true;
5837
6776
  } catch (error) {
@@ -5853,6 +6792,7 @@ var init_taskTracing = __esm({
5853
6792
  }
5854
6793
  static config(endpoint) {
5855
6794
  if (!endpoint) throw new Error(GATEWAY_KEYS_MISSING);
6795
+ if (endpoint.token) throw new Error(TOKEN_KEYS_ONLY);
5856
6796
  return { ...endpoint, endpoint: _TaskTracing.destination(endpoint) };
5857
6797
  }
5858
6798
  // B1: a saved login's keys go to their own host only. The redirect is compared as text, never parsed:
@@ -5883,7 +6823,9 @@ Pass --no-trace (trace: false) to run untraced without this warning.`
5883
6823
  static reason(error, endpoint) {
5884
6824
  if (OpenTelemetryMissing.explains(error)) return new OpenTelemetryMissing().message;
5885
6825
  const message = error instanceof Error ? error.message : String(error);
5886
- const keys = endpoint ? [endpoint.publicKey, endpoint.secretKey] : [];
6826
+ const keys = [endpoint?.publicKey, endpoint?.secretKey, endpoint?.token?.value].filter(
6827
+ (key2) => Boolean(key2)
6828
+ );
5887
6829
  return keys.reduce((text2, key2) => text2.split(key2).join("[redacted]"), message);
5888
6830
  }
5889
6831
  };
@@ -5930,13 +6872,15 @@ async function refuseUnreadTools(live) {
5930
6872
  }
5931
6873
  }
5932
6874
  async function runTask(ref, agent, opts) {
5933
- const runId = `wtr-${randomBytes(6).toString("hex")}`;
5934
6875
  const options = opts.options ?? {};
6876
+ if (opts.file !== false) GatewayEvalsClient.refuseToken(options);
6877
+ const runId = `wtr-${randomBytes(6).toString("hex")}`;
5935
6878
  const opening = new TaskOpening(
5936
6879
  openTask(ref, {
5937
6880
  surfaces: opts.surfaces,
5938
6881
  reuseWarm: opts.reuseWarm,
5939
6882
  browserTier: opts.browserTier,
6883
+ worldStates: opts.worldStates,
5940
6884
  options
5941
6885
  }).then(async (live) => {
5942
6886
  await refuseUnreadTools(live);
@@ -6216,6 +7160,7 @@ var init_checkoutProvenance = __esm({
6216
7160
  // src/worlds/setRun.ts
6217
7161
  async function runSet(datasetId, agent, opts) {
6218
7162
  const options = opts.options ?? {};
7163
+ GatewayEvalsClient.refuseToken(options);
6219
7164
  const git = opts.git === void 0 ? CheckoutProvenance.read() : opts.git;
6220
7165
  const opened = await apiRequest(options, "POST", SET_RUNS, {
6221
7166
  datasetId,
@@ -6231,6 +7176,7 @@ var init_setRun = __esm({
6231
7176
  "use strict";
6232
7177
  init_worlds();
6233
7178
  init_checkoutProvenance();
7179
+ init_evals();
6234
7180
  init_runSignals();
6235
7181
  init_taskRun();
6236
7182
  SET_RUNS = "/api/public/set-runs";
@@ -6405,6 +7351,112 @@ var init_requestLog = __esm({
6405
7351
  }
6406
7352
  });
6407
7353
 
7354
+ // src/worlds/webhooks.ts
7355
+ async function listWebhooks(options, sessionId, page = {}) {
7356
+ const query = new URLSearchParams({
7357
+ after: String(page.after ?? 0),
7358
+ limit: String(page.limit ?? WORLD_WEBHOOK_PAGE_MAX),
7359
+ tail: String(page.tail ?? false)
7360
+ });
7361
+ if (page.epoch) query.set("epoch", page.epoch);
7362
+ return apiRequest(options, "GET", `${route(sessionId)}?${query.toString()}`);
7363
+ }
7364
+ var WORLD_WEBHOOK_PAGE_MAX, FORWARD_TIMEOUT_MS, ERROR_CHARS, route, WorldWebhookForwarder;
7365
+ var init_webhooks = __esm({
7366
+ "src/worlds/webhooks.ts"() {
7367
+ "use strict";
7368
+ init_worlds();
7369
+ WORLD_WEBHOOK_PAGE_MAX = 100;
7370
+ FORWARD_TIMEOUT_MS = 1e4;
7371
+ ERROR_CHARS = 500;
7372
+ route = (sessionId) => `/api/public/world-sessions/${encodeURIComponent(sessionId)}/webhooks`;
7373
+ WorldWebhookForwarder = class {
7374
+ constructor(options, sessionId, forwardTo, opts = {}) {
7375
+ this.options = options;
7376
+ this.sessionId = sessionId;
7377
+ this.forwardTo = forwardTo;
7378
+ this.send = opts.fetch ?? fetch;
7379
+ }
7380
+ options;
7381
+ sessionId;
7382
+ forwardTo;
7383
+ after = 0;
7384
+ epoch = null;
7385
+ answers = [];
7386
+ send;
7387
+ get cursor() {
7388
+ return this.after;
7389
+ }
7390
+ /** Where forwarding begins: the deliveries the session still holds (`replay`), or only those it sends from now. */
7391
+ async start(replay2) {
7392
+ if (replay2) return null;
7393
+ const page = await this.poll([], { tail: true, limit: 1 });
7394
+ this.follow(page);
7395
+ return page;
7396
+ }
7397
+ /** One poll: the answers held so far sent, the next page forwarded. A poll that fails keeps its answers for the next. */
7398
+ async round() {
7399
+ const page = await this.withAnswers((answers) => this.poll(answers));
7400
+ const forwarded = [];
7401
+ for (const delivery of page.deliveries) {
7402
+ const answer = await this.forward(delivery);
7403
+ this.answers.push(answer);
7404
+ forwarded.push({ delivery, answer });
7405
+ }
7406
+ this.follow(page);
7407
+ return { page, forwarded };
7408
+ }
7409
+ /** Sends the answers still held; the cursor stays, so a delivery this poll returns is forwarded by the next round. */
7410
+ async settle() {
7411
+ if (this.answers.length === 0) return 0;
7412
+ const page = await this.withAnswers((answers) => this.poll(answers, { limit: 1 }));
7413
+ return page.answered;
7414
+ }
7415
+ follow(page) {
7416
+ this.after = page.next;
7417
+ this.epoch = page.epoch;
7418
+ }
7419
+ async withAnswers(poll) {
7420
+ const answers = this.answers.splice(0, WORLD_WEBHOOK_PAGE_MAX);
7421
+ try {
7422
+ return await poll(answers);
7423
+ } catch (error) {
7424
+ this.answers.unshift(...answers);
7425
+ throw error;
7426
+ }
7427
+ }
7428
+ poll(answers, opts = {}) {
7429
+ return apiRequest(this.options, "POST", route(this.sessionId), {
7430
+ after: this.after,
7431
+ epoch: this.epoch,
7432
+ tail: opts.tail ?? false,
7433
+ limit: opts.limit ?? WORLD_WEBHOOK_PAGE_MAX,
7434
+ subscriptions: false,
7435
+ answers
7436
+ });
7437
+ }
7438
+ async forward(delivery) {
7439
+ const started = Date.now();
7440
+ try {
7441
+ const reply = await this.send(this.forwardTo, {
7442
+ method: "POST",
7443
+ headers: delivery.headers,
7444
+ body: delivery.payload,
7445
+ redirect: "manual",
7446
+ signal: AbortSignal.timeout(FORWARD_TIMEOUT_MS)
7447
+ });
7448
+ await reply.arrayBuffer().catch(() => void 0);
7449
+ if (reply.status < 100 || reply.status > 599) throw new Error("the receiver answered an invalid HTTP status");
7450
+ return { id: delivery.id, status: reply.status, durationMs: Date.now() - started, error: null };
7451
+ } catch (error) {
7452
+ const message = error instanceof Error ? error.message : String(error);
7453
+ return { id: delivery.id, status: 0, durationMs: Date.now() - started, error: message.slice(0, ERROR_CHARS) };
7454
+ }
7455
+ }
7456
+ };
7457
+ }
7458
+ });
7459
+
6408
7460
  // src/worlds/checkoutTarget.ts
6409
7461
  import * as fs2 from "fs";
6410
7462
  import * as path3 from "path";
@@ -6512,19 +7564,20 @@ var init_checkoutTarget = __esm({
6512
7564
  import { createHash as createHash4 } from "crypto";
6513
7565
  import * as fs3 from "fs";
6514
7566
  import * as path4 from "path";
6515
- var WORLD_MANIFEST, API_BUNDLE_MANIFEST, BUNDLED_WORLD_PREFIX, CONNECTOR_SPEC, PYPROJECT, BENCHMARK_CONFIG, WORLD_SCHEMA_MARKERS, WORLD_ROOT_MARKERS, BROAD_ROOT_MARKERS, SKIPPED_DIRS, V1_DEP, V1_IMPORT, V1_TASKSET, HARBOR_TASK, skippedDir, byCodePoint, WorldDir;
7567
+ var WORLD_MANIFEST, API_BUNDLE_MANIFEST, BUNDLE_MANIFEST, BUNDLED_WORLD_PREFIX, CONNECTOR_SPEC, PYPROJECT, BENCHMARK_CONFIG, WORLD_SCHEMA_MARKERS, WORLD_ROOT_MARKERS, BROAD_ROOT_MARKERS, SKIPPED_DIRS, V1_DEP, V1_IMPORT, V1_TASKSET, HARBOR_TASK, skippedDir, byCodePoint, WorldDir;
6516
7568
  var init_worldDir = __esm({
6517
7569
  "src/worlds/worldDir.ts"() {
6518
7570
  "use strict";
6519
7571
  WORLD_MANIFEST = "gateway-env.toml";
6520
7572
  API_BUNDLE_MANIFEST = "gateway-api-world.toml";
7573
+ BUNDLE_MANIFEST = "gateway-bundle.toml";
6521
7574
  BUNDLED_WORLD_PREFIX = "server/world/";
6522
7575
  CONNECTOR_SPEC = "connector.toml";
6523
7576
  PYPROJECT = "pyproject.toml";
6524
7577
  BENCHMARK_CONFIG = "benchmark.json";
6525
7578
  WORLD_SCHEMA_MARKERS = ["schema/world.json", "schema/runtime.json", "schema/lock.json"];
6526
7579
  WORLD_ROOT_MARKERS = [CONNECTOR_SPEC, ...WORLD_SCHEMA_MARKERS];
6527
- BROAD_ROOT_MARKERS = [WORLD_MANIFEST, API_BUNDLE_MANIFEST, BENCHMARK_CONFIG];
7580
+ BROAD_ROOT_MARKERS = [WORLD_MANIFEST, API_BUNDLE_MANIFEST, BENCHMARK_CONFIG, BUNDLE_MANIFEST];
6528
7581
  SKIPPED_DIRS = /* @__PURE__ */ new Set(["dist", "build", "outputs", "__pycache__", "node_modules"]);
6529
7582
  V1_DEP = /["']verifiers\s*(?:\[[^\]]*\])?\s*(?:>=|~=|==|>)\s*(?:0\.(?:[2-9]\d*|[1-9]\d+)|[1-9]\d*)/;
6530
7583
  V1_IMPORT = /^\s*(?:from\s+verifiers\.v1\s+import\b|from\s+verifiers\s+import\s+v1\b|import\s+verifiers\.v1\b)/m;
@@ -6545,7 +7598,6 @@ var init_worldDir = __esm({
6545
7598
  const bundled = present(API_BUNDLE_MANIFEST) && WORLD_ROOT_MARKERS.some((m) => present(BUNDLED_WORLD_PREFIX + m));
6546
7599
  return new _WorldDir(dir, bundled ? BUNDLED_WORLD_PREFIX : "");
6547
7600
  }
6548
- // ── Files ──────────────────────────────────────────────────────────────
6549
7601
  has(rel) {
6550
7602
  return fs3.existsSync(path4.join(this.dir, rel));
6551
7603
  }
@@ -6556,15 +7608,9 @@ var init_worldDir = __esm({
6556
7608
  return null;
6557
7609
  }
6558
7610
  }
6559
- /** A path under the authored world's root. */
6560
7611
  worldPath(rel) {
6561
7612
  return this.worldRoot + rel;
6562
7613
  }
6563
- /** Every regular file the archive rules keep (`_archive.py`: no hidden,
6564
- * dist, build, outputs, pycache, node_modules or egg-info directories), as
6565
- * sorted relpaths. Root files enter only when a Gateway manifest or
6566
- * benchmark.json widens the root, or they are README.md, pyproject.toml or
6567
- * Python. */
6568
7614
  get archivePaths() {
6569
7615
  if (this.pathsMemo) return this.pathsMemo;
6570
7616
  const broad = BROAD_ROOT_MARKERS.some((m) => this.has(m));
@@ -6583,11 +7629,6 @@ var init_worldDir = __esm({
6583
7629
  walk("");
6584
7630
  return this.pathsMemo = out.sort(byCodePoint);
6585
7631
  }
6586
- /** What the archive rules leave out, collapsed to the entry that decided
6587
- * it: a pruned directory counts its files once, a dropped root file is
6588
- * named. Dot entries (`.git/`, `.gateway/`, `.gitignore`) are the one
6589
- * universal convention and stay unreported. `push` prints the rest so
6590
- * nothing disappears silently. */
6591
7632
  get exclusions() {
6592
7633
  const kept = new Set(this.archivePaths);
6593
7634
  const out = [];
@@ -6610,14 +7651,11 @@ var init_worldDir = __esm({
6610
7651
  }
6611
7652
  return out;
6612
7653
  }
6613
- /** A root `.gitignore` is present: the Python SDK honours it when
6614
- * collecting, this package does not reimplement gitignore. */
7654
+ /** The Python SDK honours a root `.gitignore` when collecting; this package does not reimplement gitignore. */
6615
7655
  get hasRootGitignore() {
6616
7656
  return this.has(".gitignore");
6617
7657
  }
6618
- /** SHA-256 over `utf8("file:" + relpath)` + bytes per archive path in
6619
- * sorted order: the version's identity, byte-compatible with
6620
- * `_archive.compute_content_hash` and Prime Intellect. */
7658
+ /** The version's identity, byte-compatible with the Python SDK's `compute_content_hash` and Prime Intellect's hub. */
6621
7659
  get contentHash() {
6622
7660
  const hasher = createHash4("sha256");
6623
7661
  for (const rel of this.archivePaths) {
@@ -6626,18 +7664,18 @@ var init_worldDir = __esm({
6626
7664
  }
6627
7665
  return hasher.digest("hex");
6628
7666
  }
6629
- // ── Markers ────────────────────────────────────────────────────────────
6630
7667
  get isApiBundle() {
6631
7668
  return this.has(API_BUNDLE_MANIFEST);
6632
7669
  }
7670
+ get isWorldBundle() {
7671
+ return this.has(BUNDLE_MANIFEST);
7672
+ }
6633
7673
  get hasManifest() {
6634
7674
  return this.has(this.worldPath(WORLD_MANIFEST));
6635
7675
  }
6636
7676
  get hasSchemaMarker() {
6637
7677
  return WORLD_SCHEMA_MARKERS.some((m) => this.has(this.worldPath(m)));
6638
7678
  }
6639
- /** Harbor task dirs, relative to the tree: `tasks/<name>` when a `tasks/`
6640
- * dir holds them, else the root `<name>` dirs. */
6641
7679
  taskDirs() {
6642
7680
  const names = /* @__PURE__ */ new Set();
6643
7681
  for (const rel of this.archivePaths) {
@@ -6647,8 +7685,6 @@ var init_worldDir = __esm({
6647
7685
  const under = [...names].filter((n) => n.startsWith("tasks/"));
6648
7686
  return (under.length ? under : [...names]).sort();
6649
7687
  }
6650
- /** The Python package of a verifiers tree (`<pkg>/__init__.py` or
6651
- * `src/<pkg>/__init__.py`), or null. */
6652
7688
  pythonPackage() {
6653
7689
  if (!this.has(PYPROJECT)) return null;
6654
7690
  for (const base of ["", "src/"]) {
@@ -6660,8 +7696,6 @@ var init_worldDir = __esm({
6660
7696
  }
6661
7697
  return null;
6662
7698
  }
6663
- /** The package targets the `verifiers.v1` API: read from the root
6664
- * pyproject and every archived Python module. */
6665
7699
  get isVerifiersV1() {
6666
7700
  for (const rel of this.archivePaths) {
6667
7701
  if (rel !== PYPROJECT && !rel.endsWith(".py")) continue;
@@ -6672,11 +7706,9 @@ var init_worldDir = __esm({
6672
7706
  }
6673
7707
  return false;
6674
7708
  }
6675
- // ── The answer ─────────────────────────────────────────────────────────
6676
- /** The runner's kind (`detect_env_kind`): api / mock-tools win over
6677
- * everything, a harbor task tree next, then the verifiers API version. */
6678
7709
  get kind() {
6679
7710
  if (this.isApiBundle) return "api";
7711
+ if (this.isWorldBundle) return "bundle";
6680
7712
  if (this.has(WORLD_MANIFEST)) return "mock-tools";
6681
7713
  if (this.taskDirs().length) return "harbor";
6682
7714
  return this.isVerifiersV1 ? "verifiers-v1" : "verifiers";
@@ -7018,8 +8050,7 @@ async function push(dir, opts = {}) {
7018
8050
  const metadata = {
7019
8051
  ...opts.name !== void 0 ? { name: opts.name } : {},
7020
8052
  ...opts.description !== void 0 ? { description: opts.description } : {},
7021
- ...opts.tags !== void 0 ? { tags: opts.tags } : {},
7022
- ...opts.visibility ? { visibility: opts.visibility } : {}
8053
+ ...opts.tags !== void 0 ? { tags: opts.tags } : {}
7023
8054
  };
7024
8055
  const resolve11 = await apiRequest(
7025
8056
  options,
@@ -7547,7 +8578,7 @@ var init_sandbox = __esm({
7547
8578
  /**
7548
8579
  * `{ slug, ref? }` opens a READY version; `{ new, from }` opens a sandbox on
7549
8580
  * a world that does not exist yet (409 `world_exists` if the slug is taken,
7550
- * 400 naming the shipped templates if `from` is unknown). Its first commit
8581
+ * 400 naming the official templates if `from` is unknown). Its first commit
7551
8582
  * creates the world on `main`.
7552
8583
  */
7553
8584
  open(target) {
@@ -8192,6 +9223,7 @@ var CliError;
8192
9223
  var init_router = __esm({
8193
9224
  "src/cli/router.ts"() {
8194
9225
  "use strict";
9226
+ init_personalToken();
8195
9227
  CliError = class extends Error {
8196
9228
  constructor(message, exitCode = 2) {
8197
9229
  super(message);
@@ -8206,25 +9238,69 @@ var init_router = __esm({
8206
9238
  import * as fs6 from "fs";
8207
9239
  import * as os from "os";
8208
9240
  import * as path7 from "path";
8209
- async function api(creds, method, route, body, init3 = {}) {
8210
- const reply = await new PlatformTransport(creds).send(method, route, body, init3);
8211
- if (!reply.ok) throw new ApiError2(reply.status, method, route, reply.text);
9241
+ function configPath() {
9242
+ return path7.join(process.env.GATEWAY_CONFIG_DIR || path7.join(os.homedir(), ".gateway"), "config.json");
9243
+ }
9244
+ function readConfig() {
9245
+ let stored;
9246
+ try {
9247
+ stored = JSON.parse(fs6.readFileSync(configPath(), "utf8"));
9248
+ } catch {
9249
+ return {};
9250
+ }
9251
+ const record = stored ?? {};
9252
+ return Object.fromEntries(STORED_FIELDS.filter((f) => typeof record[f] === "string").map((f) => [f, record[f]]));
9253
+ }
9254
+ function personalToken(request = {}) {
9255
+ try {
9256
+ return PersonalToken.fromEnv(process.env, request);
9257
+ } catch (error) {
9258
+ if (error instanceof PersonalTokenRefused) throw new CliError(error.message);
9259
+ throw error;
9260
+ }
9261
+ }
9262
+ function resolveCredentials(hostFlag, secretKeyFlag) {
9263
+ const token = personalToken({ host: hostFlag || void 0, keys: Boolean(secretKeyFlag) });
9264
+ if (token) return { host: token.host, publicKey: "", secretKey: "", token };
9265
+ const stored = readConfig();
9266
+ const explicitHost = (hostFlag || process.env.GATEWAY_HOST || "").replace(/\/+$/, "");
9267
+ const host = explicitHost || (stored.host ?? "").replace(/\/+$/, "");
9268
+ if (!host)
9269
+ throw new CredentialsMissing(
9270
+ "Host not configured. Pass --host, set GATEWAY_HOST, or run `gateway auth login`."
9271
+ );
9272
+ const login = host === (stored.host ?? "").replace(/\/+$/, "") ? stored : {};
9273
+ const publicKey = process.env.GATEWAY_PUBLIC_KEY || login.public_key || "";
9274
+ const secretKey = secretKeyFlag || process.env.GATEWAY_SECRET_KEY || process.env.GATEWAY_API_KEY || login.api_key || "";
9275
+ if (!publicKey || !secretKey)
9276
+ throw new CredentialsMissing(
9277
+ "API key not configured. Set GATEWAY_PUBLIC_KEY and GATEWAY_SECRET_KEY, or run `gateway auth login`."
9278
+ );
9279
+ return { host, publicKey, secretKey };
9280
+ }
9281
+ async function api(creds, method, route2, body, init3 = {}) {
9282
+ const reply = await new PlatformTransport(creds).send(method, route2, body, init3);
9283
+ if (!reply.ok) throw new ApiError2(reply.status, method, route2, reply.text);
8212
9284
  return reply.text ? JSON.parse(reply.text) : {};
8213
9285
  }
8214
- var ApiError2;
9286
+ var STORED_FIELDS, CredentialsMissing, ApiError2;
8215
9287
  var init_config = __esm({
8216
9288
  "src/cli/config.ts"() {
8217
9289
  "use strict";
8218
9290
  init_router();
8219
9291
  init_worlds();
9292
+ init_personalToken();
8220
9293
  init_transport();
9294
+ STORED_FIELDS = ["host", "public_key", "api_key"];
9295
+ CredentialsMissing = class extends CliError {
9296
+ };
8221
9297
  ApiError2 = class extends CliError {
8222
- constructor(status, method, route, text2) {
9298
+ constructor(status, method, route2, text2) {
8223
9299
  const body = parseErrorBody(text2, status);
8224
- super(`${method} ${route} -> ${status}: ${body.detail}`, 1);
9300
+ super(`${method} ${route2} -> ${status}: ${body.detail}`, 1);
8225
9301
  this.status = status;
8226
9302
  this.method = method;
8227
- this.route = route;
9303
+ this.route = route2;
8228
9304
  this.text = text2;
8229
9305
  this.code = body.code;
8230
9306
  }
@@ -8237,8 +9313,37 @@ var init_config = __esm({
8237
9313
  }
8238
9314
  });
8239
9315
 
9316
+ // src/worlds/isolatedPython.ts
9317
+ import { spawnSync } from "child_process";
9318
+ function isolatedPython(python, args, timeout) {
9319
+ return spawnSync(python, ["-I", ...args], { encoding: "utf8", timeout, env: PersonalToken.scrubbed(process.env) });
9320
+ }
9321
+ var init_isolatedPython = __esm({
9322
+ "src/worlds/isolatedPython.ts"() {
9323
+ "use strict";
9324
+ init_personalToken();
9325
+ }
9326
+ });
9327
+
8240
9328
  // src/cli/runtime/local.ts
8241
- import { spawn, spawnSync } from "child_process";
9329
+ var local_exports = {};
9330
+ __export(local_exports, {
9331
+ MIN_PYTHON_LABEL: () => MIN_PYTHON_LABEL,
9332
+ assertPortFree: () => assertPortFree,
9333
+ credentialsForRuntime: () => credentialsForRuntime,
9334
+ findPython: () => findPython,
9335
+ localBridge: () => localBridge,
9336
+ localModule: () => localModule,
9337
+ localPythonHasYaml: () => localPythonHasYaml,
9338
+ localRuntime: () => localRuntime,
9339
+ localRuntimeReason: () => localRuntimeReason,
9340
+ portOwner: () => portOwner,
9341
+ pythonAdvice: () => pythonAdvice,
9342
+ resetPythonCache: () => resetPythonCache,
9343
+ runtimeMode: () => runtimeMode,
9344
+ runtimeRoot: () => runtimeRoot
9345
+ });
9346
+ import { spawn, spawnSync as spawnSync2 } from "child_process";
8242
9347
  import * as fs7 from "fs";
8243
9348
  import * as net from "net";
8244
9349
  import * as path8 from "path";
@@ -8278,12 +9383,12 @@ function runtimeRoot() {
8278
9383
  return root;
8279
9384
  return null;
8280
9385
  }
9386
+ function resetPythonCache() {
9387
+ pythonCache = void 0;
9388
+ pythonProbes = [];
9389
+ }
8281
9390
  function probeVersion(name) {
8282
- const probe = spawnSync(
8283
- name,
8284
- ["-c", "import sys;print(sys.version_info[0],sys.version_info[1])"],
8285
- { encoding: "utf8", timeout: 1e4 }
8286
- );
9391
+ const probe = isolatedPython(name, ["-c", "import sys;print(sys.version_info[0],sys.version_info[1])"], 1e4);
8287
9392
  if (probe.status !== 0) return null;
8288
9393
  const [major, minor] = probe.stdout.trim().split(/\s+/).map(Number);
8289
9394
  return Number.isInteger(major) && Number.isInteger(minor) ? `${major}.${minor}` : null;
@@ -8293,7 +9398,7 @@ function atLeastMinimum(version) {
8293
9398
  return major > MIN_PYTHON[0] || major === MIN_PYTHON[0] && minor >= MIN_PYTHON[1];
8294
9399
  }
8295
9400
  function uvPython() {
8296
- const found = spawnSync("uv", UV_FIND, { encoding: "utf8", timeout: 1e4 });
9401
+ const found = spawnSync2("uv", UV_FIND, { encoding: "utf8", timeout: 1e4, env: PersonalToken.scrubbed(process.env) });
8297
9402
  if (found.status !== 0) return null;
8298
9403
  const line = found.stdout.trim().split(/\r?\n/)[0] ?? "";
8299
9404
  return line || null;
@@ -8352,7 +9457,7 @@ function localRuntime() {
8352
9457
  return { python, root };
8353
9458
  }
8354
9459
  function localPythonHasYaml(python) {
8355
- return spawnSync(python, ["-c", "import yaml"], { timeout: 1e4 }).status === 0;
9460
+ return isolatedPython(python, ["-c", "import yaml"], 1e4).status === 0;
8356
9461
  }
8357
9462
  async function localBridge(request, local, opts = {}) {
8358
9463
  const input = JSON.stringify(request);
@@ -8413,12 +9518,88 @@ async function localBridge(request, local, opts = {}) {
8413
9518
  child.stdin.end(input);
8414
9519
  });
8415
9520
  }
8416
- var MIN_PYTHON, MIN_PYTHON_LABEL, DIAGNOSTIC_TAIL, FORWARDED_ENV, BRIDGE_BOOTSTRAP, pythonCache, pythonProbes, PYTHON_CANDIDATES, UV_FIND;
9521
+ function portOwner(port) {
9522
+ const found = spawnSync2("lsof", ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN", "-Fpc"], {
9523
+ encoding: "utf8",
9524
+ timeout: 5e3
9525
+ });
9526
+ if (found.error || found.status !== 0) return null;
9527
+ let pid = null;
9528
+ let command2 = null;
9529
+ for (const line of found.stdout.split("\n")) {
9530
+ if (line.startsWith("p") && pid === null) pid = line.slice(1);
9531
+ else if (line.startsWith("c") && pid !== null && command2 === null) command2 = line.slice(1);
9532
+ }
9533
+ if (pid === null) return null;
9534
+ return `pid ${pid}${command2 ? ` (${command2})` : ""}`;
9535
+ }
9536
+ async function assertPortFree(port, host = "127.0.0.1") {
9537
+ const taken = await new Promise((resolve11) => {
9538
+ const probe = net.createServer();
9539
+ probe.once("error", () => resolve11(true));
9540
+ probe.listen(port, host, () => probe.close(() => resolve11(false)));
9541
+ });
9542
+ if (!taken) return;
9543
+ const owner = portOwner(port);
9544
+ throw new CliError(
9545
+ `port ${port} on ${host} is already in use${owner ? ` by ${owner}` : ""}; nothing was served there \u2014 pass another --port, or stop that server first`,
9546
+ 1
9547
+ );
9548
+ }
9549
+ async function localModule(argv, local, opts = {}) {
9550
+ return await new Promise((resolve11, reject) => {
9551
+ const child = spawn(
9552
+ local.python,
9553
+ ["-B", "-c", MODULE_BOOTSTRAP, local.root, ...argv],
9554
+ {
9555
+ stdio: "inherit",
9556
+ cwd: opts.cwd,
9557
+ env: { ...PersonalToken.scrubbed(process.env), ...opts.env }
9558
+ }
9559
+ );
9560
+ const forward = (signal) => () => {
9561
+ if (child.exitCode === null && child.signalCode === null) child.kill(signal);
9562
+ };
9563
+ const handlers = [
9564
+ ["SIGINT", forward("SIGINT")],
9565
+ ["SIGTERM", forward("SIGTERM")],
9566
+ ["SIGHUP", forward("SIGHUP")]
9567
+ ];
9568
+ for (const [signal, handler] of handlers) process.on(signal, handler);
9569
+ const release = () => {
9570
+ for (const [signal, handler] of handlers) process.off(signal, handler);
9571
+ };
9572
+ child.on("error", (error) => {
9573
+ release();
9574
+ reject(
9575
+ new CliError(
9576
+ `local runtime could not start (${local.python}): ${error.message}`,
9577
+ 1
9578
+ )
9579
+ );
9580
+ });
9581
+ child.on("close", (code, signal) => {
9582
+ release();
9583
+ resolve11(code ?? (signal ? 130 : 1));
9584
+ });
9585
+ });
9586
+ }
9587
+ function credentialsForRuntime(hostFlag) {
9588
+ try {
9589
+ return resolveCredentials(hostFlag);
9590
+ } catch (error) {
9591
+ if (error instanceof CliError && localRuntime()) return null;
9592
+ throw error;
9593
+ }
9594
+ }
9595
+ var MIN_PYTHON, MIN_PYTHON_LABEL, DIAGNOSTIC_TAIL, FORWARDED_ENV, BRIDGE_BOOTSTRAP, MODULE_BOOTSTRAP, pythonCache, pythonProbes, PYTHON_CANDIDATES, UV_FIND;
8417
9596
  var init_local = __esm({
8418
9597
  "src/cli/runtime/local.ts"() {
8419
9598
  "use strict";
8420
9599
  init_router();
8421
9600
  init_config();
9601
+ init_isolatedPython();
9602
+ init_personalToken();
8422
9603
  MIN_PYTHON = [3, 12];
8423
9604
  MIN_PYTHON_LABEL = MIN_PYTHON.join(".");
8424
9605
  DIAGNOSTIC_TAIL = 600;
@@ -8429,6 +9610,13 @@ package=types.ModuleType('gatewaysdk')
8429
9610
  package.__path__=[os.path.join(root,'gatewaysdk')]
8430
9611
  sys.modules['gatewaysdk']=package
8431
9612
  runpy.run_module('gatewaysdk.environment.schema.platform',run_name='__main__')`;
9613
+ MODULE_BOOTSTRAP = `import sys,runpy,types,os
9614
+ root=sys.argv[1]
9615
+ package=types.ModuleType('gatewaysdk')
9616
+ package.__path__=[os.path.join(root,'gatewaysdk')]
9617
+ sys.modules['gatewaysdk']=package
9618
+ sys.argv=['gateway worlds']+sys.argv[2:]
9619
+ runpy.run_module('gatewaysdk.environment.schema',run_name='__main__')`;
8432
9620
  pythonProbes = [];
8433
9621
  PYTHON_CANDIDATES = [
8434
9622
  "python3.13",
@@ -8577,8 +9765,8 @@ async function runtime(creds, request, opts = {}) {
8577
9765
  throw new CliError(
8578
9766
  "This needs the schema runtime (the CLI bundles it) or platform credentials (`gateway auth login`). " + localRuntimeReason()
8579
9767
  );
8580
- const route = "/api/public/worlds/runtime";
8581
- const res = await new PlatformTransport(creds).send("POST", route, request, {
9768
+ const route2 = "/api/public/worlds/runtime";
9769
+ const res = await new PlatformTransport(creds).send("POST", route2, request, {
8582
9770
  timeoutMs: opts.timeoutMs ?? RUNTIME_TIMEOUT_MS
8583
9771
  });
8584
9772
  let payload = null;
@@ -8590,8 +9778,8 @@ async function runtime(creds, request, opts = {}) {
8590
9778
  const detail = detailFrom(payload);
8591
9779
  if (detail) throw new BridgeRejected(detail);
8592
9780
  if (!res.ok)
8593
- throw new CliError(`POST ${route} (${request.command}) -> ${res.status}: ${res.text.slice(0, 600)}`, 1);
8594
- if (payload === null) throw new CliError(`POST ${route} (${request.command}) returned non-JSON`, 1);
9781
+ throw new CliError(`POST ${route2} (${request.command}) -> ${res.status}: ${res.text.slice(0, 600)}`, 1);
9782
+ if (payload === null) throw new CliError(`POST ${route2} (${request.command}) returned non-JSON`, 1);
8595
9783
  return payload;
8596
9784
  }
8597
9785
  var MAX_WORLD_FILES, RUNTIME_TIMEOUT_MS, SKIP_DIRS, BridgeRejected, YAML_NAME, YAML_NEEDS_PYYAML, YAML_NOT_ON_PLATFORM, RuntimeRoute;
@@ -9480,9 +10668,9 @@ async function emit(sink, record) {
9480
10668
  }
9481
10669
  throw new TypeError("sink must be an array, a file path, or a function");
9482
10670
  }
9483
- function captureToolCalls(tools, sink, opts = {}) {
10671
+ function captureToolCalls(tools2, sink, opts = {}) {
9484
10672
  const wrapped = /* @__PURE__ */ Object.create(null);
9485
- for (const [name, fn] of Object.entries(tools)) {
10673
+ for (const [name, fn] of Object.entries(tools2)) {
9486
10674
  wrapped[name] = async (args = {}) => {
9487
10675
  const record = { tool: name, args, at: (/* @__PURE__ */ new Date()).toISOString() };
9488
10676
  if (opts.session) record.session = opts.session;
@@ -9538,14 +10726,23 @@ function toolCallsFromObservations(observations, opts = {}) {
9538
10726
  }
9539
10727
  return out;
9540
10728
  }
10729
+ async function runtimeEndpoint(options) {
10730
+ try {
10731
+ return platformEndpoint(options);
10732
+ } catch (error) {
10733
+ const { localRuntime: localRuntime2 } = await Promise.resolve().then(() => (init_local(), local_exports));
10734
+ if (error instanceof PersonalTokenRefused && localRuntime2()) return null;
10735
+ throw error;
10736
+ }
10737
+ }
9541
10738
  async function ingest(world, records, options = {}) {
9542
10739
  const { ingestLocalToolCalls: ingestLocalToolCalls2, importLocalWorldData: importLocalWorldData2, checkLocalWorldData: checkLocalWorldData2 } = await Promise.resolve().then(() => (init_data(), data_exports));
9543
10740
  if (options.transform !== void 0 && options.map !== void 0) throw new Error("records go through one of transform, map");
9544
10741
  const redact = options.redact ?? "off";
9545
10742
  const mode = options.mode ?? "append";
9546
10743
  const dryRun = Boolean(options.dryRun);
9547
- const creds = platformEndpoint(options);
9548
10744
  const local = fs12.existsSync(world) && fs12.statSync(world).isDirectory();
10745
+ const creds = local ? await runtimeEndpoint(options) : platformEndpoint(options);
9549
10746
  const map = options.map === void 0 ? void 0 : options.map;
9550
10747
  let rows = null;
9551
10748
  let stderr = "";
@@ -9643,6 +10840,7 @@ var init_ingest = __esm({
9643
10840
  "use strict";
9644
10841
  init_worlds();
9645
10842
  init_platformEndpoint();
10843
+ init_personalToken();
9646
10844
  isObject2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
9647
10845
  isoOf = (value) => value instanceof Date ? value.toISOString() : typeof value === "string" ? value : void 0;
9648
10846
  }
@@ -9700,6 +10898,38 @@ var init_editSessions = __esm({
9700
10898
  }
9701
10899
  });
9702
10900
 
10901
+ // src/worlds/states.ts
10902
+ var WORLDS3, refQuery, WorldStateClient;
10903
+ var init_states = __esm({
10904
+ "src/worlds/states.ts"() {
10905
+ "use strict";
10906
+ init_worlds();
10907
+ WORLDS3 = "/api/public/worlds";
10908
+ refQuery = (ref) => ref ? `?${new URLSearchParams({ ref })}` : "";
10909
+ WorldStateClient = class {
10910
+ constructor(options = {}) {
10911
+ this.options = options;
10912
+ }
10913
+ options;
10914
+ list(slug) {
10915
+ return apiRequest(this.options, "GET", `${WORLDS3}/${encodeURIComponent(slug)}/states`);
10916
+ }
10917
+ show(slug, name, ref) {
10918
+ return apiRequest(this.options, "GET", `${WORLDS3}/${encodeURIComponent(slug)}/states/${encodeURIComponent(name)}` + refQuery(ref));
10919
+ }
10920
+ create(slug, input) {
10921
+ return apiRequest(this.options, "POST", `${WORLDS3}/${encodeURIComponent(slug)}/states`, input);
10922
+ }
10923
+ delete(slug, name) {
10924
+ return apiRequest(this.options, "DELETE", `${WORLDS3}/${encodeURIComponent(slug)}/states/${encodeURIComponent(name)}`);
10925
+ }
10926
+ pull(slug, name, ref) {
10927
+ return apiRequest(this.options, "GET", `${WORLDS3}/${encodeURIComponent(slug)}/states/${encodeURIComponent(name)}/pull` + refQuery(ref));
10928
+ }
10929
+ };
10930
+ }
10931
+ });
10932
+
9703
10933
  // src/worlds/dryRun.ts
9704
10934
  var DRY_RUN_KIND, DRY_RUN_AGENT, STATUS_WAIT_CAP_SECONDS, cid, HostedDryRunClient, DryRunOutcome;
9705
10935
  var init_dryRun = __esm({
@@ -9833,9 +11063,14 @@ __export(worlds_exports, {
9833
11063
  OpenAIComputer: () => OpenAIComputer,
9834
11064
  OpenAIPreviewComputer: () => OpenAIPreviewComputer,
9835
11065
  PLATFORM_SESSION_HEADER: () => PLATFORM_SESSION_HEADER,
11066
+ PLATFORM_STREAM_IDLE_MS: () => PLATFORM_STREAM_IDLE_MS,
9836
11067
  PLATFORM_TIMEOUT_DEFAULT_MS: () => PLATFORM_TIMEOUT_DEFAULT_MS,
9837
11068
  PLATFORM_TIMEOUT_ENV: () => PLATFORM_TIMEOUT_ENV,
11069
+ PageObserver: () => PageObserver,
11070
+ PageState: () => PageState,
11071
+ PageStateError: () => PageStateError,
9838
11072
  PendingSafetyChecks: () => PendingSafetyChecks,
11073
+ PlatformStream: () => PlatformStream,
9839
11074
  PlatformTransport: () => PlatformTransport,
9840
11075
  PushSlugConflict: () => PushSlugConflict,
9841
11076
  RECOVER_BUDGET_MS: () => RECOVER_BUDGET_MS,
@@ -9872,6 +11107,7 @@ __export(worlds_exports, {
9872
11107
  VERIFIER_REWARD_PREFIX: () => VERIFIER_REWARD_PREFIX,
9873
11108
  WHITESPACE: () => WHITESPACE,
9874
11109
  WORLD_REQUEST_VIAS: () => WORLD_REQUEST_VIAS,
11110
+ WORLD_WEBHOOK_PAGE_MAX: () => WORLD_WEBHOOK_PAGE_MAX,
9875
11111
  WorldBrowser: () => WorldBrowser,
9876
11112
  WorldCallTooLarge: () => WorldCallTooLarge,
9877
11113
  WorldEditClient: () => WorldEditClient,
@@ -9887,9 +11123,11 @@ __export(worlds_exports, {
9887
11123
  WorldSessionOpenFailed: () => WorldSessionOpenFailed,
9888
11124
  WorldSessionTimeout: () => WorldSessionTimeout,
9889
11125
  WorldSet: () => WorldSet,
11126
+ WorldStateClient: () => WorldStateClient,
9890
11127
  WorldSurfaceUnavailable: () => WorldSurfaceUnavailable,
9891
11128
  WorldTask: () => WorldTask,
9892
11129
  WorldToolsUnread: () => WorldToolsUnread,
11130
+ WorldWebhookForwarder: () => WorldWebhookForwarder,
9893
11131
  WriteTreeFilter: () => WriteTreeFilter,
9894
11132
  aggregateTaskGrade: () => aggregateTaskGrade,
9895
11133
  apiRequest: () => apiRequest,
@@ -9937,6 +11175,7 @@ __export(worlds_exports, {
9937
11175
  listSessions: () => listSessions,
9938
11176
  listTaskSessions: () => listTaskSessions,
9939
11177
  listTasks: () => listTasks,
11178
+ listWebhooks: () => listWebhooks,
9940
11179
  localTreeState: () => localTreeState,
9941
11180
  messageOf: () => messageOf,
9942
11181
  migrateProjectWorlds: () => migrateProjectWorlds,
@@ -9952,6 +11191,7 @@ __export(worlds_exports, {
9952
11191
  parseToolCallRecord: () => parseToolCallRecord,
9953
11192
  parseTransform: () => parseTransform,
9954
11193
  parseWorldTaskRefs: () => parseWorldTaskRefs,
11194
+ platformAuthorization: () => platformAuthorization,
9955
11195
  platformTimeoutMs: () => platformTimeoutMs,
9956
11196
  playwrightKey: () => playwrightKey,
9957
11197
  preserveForm: () => preserveForm,
@@ -9978,6 +11218,7 @@ __export(worlds_exports, {
9978
11218
  runSet: () => runSet,
9979
11219
  runTask: () => runTask,
9980
11220
  schemaFromSignature: () => schemaFromSignature,
11221
+ scrubError: () => scrubError,
9981
11222
  serializeCallBody: () => serializeCallBody,
9982
11223
  sessionToolObservations: () => sessionToolObservations,
9983
11224
  setEnvSecret: () => setEnvSecret,
@@ -10005,43 +11246,8 @@ __export(worlds_exports, {
10005
11246
  worldRequestsUnrecorded: () => worldRequestsUnrecorded,
10006
11247
  writeLocalMeta: () => writeLocalMeta
10007
11248
  });
10008
- function edgeAnswer(text2, status) {
10009
- if (status !== void 0 && status >= 500) return EDGE_ANSWERS[status] ?? EDGE_FAILURE;
10010
- return /^\s*</.test(text2) ? EDGE_PAGE : null;
10011
- }
10012
- function parseErrorBody(text2, status) {
10013
- const raw = { detail: text2.slice(0, DETAIL_LIMIT), code: null };
10014
- let parsed;
10015
- try {
10016
- parsed = JSON.parse(text2);
10017
- } catch {
10018
- return { detail: (edgeAnswer(text2, status) ?? text2).slice(0, DETAIL_LIMIT), code: null };
10019
- }
10020
- if (parsed === null || typeof parsed !== "object") return raw;
10021
- const { message, code, error } = parsed;
10022
- const stableCode = typeof code === "string" ? code : null;
10023
- if (typeof message !== "string") return { ...raw, code: stableCode };
10024
- const fields = invalidFields(error);
10025
- const said = fields ? `${message}: ${fields}` : message;
10026
- if (stableCode === null) return { detail: said.slice(0, DETAIL_LIMIT), code: null };
10027
- return {
10028
- detail: `${said} (${stableCode})`.slice(0, DETAIL_LIMIT),
10029
- code: stableCode
10030
- };
10031
- }
10032
- function invalidFields(error) {
10033
- const issues = Array.isArray(error) ? error : [];
10034
- return issues.filter(
10035
- (issue) => issue !== null && typeof issue === "object" && typeof issue.message === "string"
10036
- ).map((issue) => {
10037
- const path17 = Array.isArray(issue.path) ? issue.path.map(String).join(".") : "";
10038
- return path17 ? `${path17}: ${issue.message}` : issue.message;
10039
- }).join("; ");
10040
- }
10041
11249
  async function apiRequest(options, method, path17, body, init3 = {}) {
10042
- const reply = await new PlatformTransport(requirePlatformEndpoint(options)).send(method, path17, body, init3);
10043
- if (!reply.ok) throw new ApiError(reply.status, method, path17, reply.text);
10044
- return JSON.parse(reply.text);
11250
+ return new PlatformTransport(requirePlatformEndpoint(options)).json(method, path17, body, init3);
10045
11251
  }
10046
11252
  async function setEnvSecret(slug, key2, value, options = {}) {
10047
11253
  return apiRequest(
@@ -10216,12 +11422,13 @@ async function resolveWorld(slugRef, slug, ref, pin, options) {
10216
11422
  }
10217
11423
  return world;
10218
11424
  }
10219
- var ApiError, DETAIL_LIMIT, EDGE_ANSWERS, EDGE_FAILURE, EDGE_PAGE, WorldTask, WorldSet;
11425
+ var WorldTask, WorldSet;
10220
11426
  var init_worlds = __esm({
10221
11427
  "src/worlds/index.ts"() {
10222
11428
  "use strict";
10223
11429
  init_platformEndpoint();
10224
11430
  init_transport();
11431
+ init_apiError();
10225
11432
  init_transport();
10226
11433
  init_session2();
10227
11434
  init_grade();
@@ -10236,9 +11443,12 @@ var init_worlds = __esm({
10236
11443
  init_checkoutProvenance();
10237
11444
  init_evals();
10238
11445
  init_browser();
11446
+ init_browserTools();
11447
+ init_pageState();
10239
11448
  init_surfaceDescriptor();
10240
11449
  init_requestLog();
10241
11450
  init_requestLedger();
11451
+ init_webhooks();
10242
11452
  init_browserReconnect();
10243
11453
  init_nativeComputer();
10244
11454
  init_hub();
@@ -10246,34 +11456,14 @@ var init_worlds = __esm({
10246
11456
  init_describe();
10247
11457
  init_redaction();
10248
11458
  init_transforms();
10249
- init_query();
10250
- init_migrate();
10251
- init_ingest();
10252
- init_sandbox();
10253
- init_editSessions();
10254
- init_dryRun();
10255
- init_worldNotice();
10256
- ApiError = class extends Error {
10257
- constructor(status, method, path17, text2) {
10258
- const parsed = parseErrorBody(text2, status);
10259
- super(`${method} ${path17} -> ${status}: ${parsed.detail}`);
10260
- this.status = status;
10261
- this.text = text2;
10262
- this.name = "ApiError";
10263
- this.code = parsed.code;
10264
- }
10265
- status;
10266
- text;
10267
- code;
10268
- };
10269
- DETAIL_LIMIT = 600;
10270
- EDGE_ANSWERS = {
10271
- 502: "Bad Gateway from the load balancer in front of the platform, not the platform's answer: the web server dropped the connection or restarted mid-request. Retry; if it repeats, the platform is restarting or overloaded.",
10272
- 503: "Service Unavailable from the load balancer in front of the platform, not the platform's answer: no web server was ready to take the request (a deploy or a restart). Retry in a minute.",
10273
- 504: "Gateway Time-out from the load balancer in front of the platform, not the platform's answer: the request sent nothing back within the load balancer's idle timeout (60 s unless the deployment raises it: Helm ingress.idleTimeoutSeconds) and was cut there, though the platform may still be running it. Check what it changed before you retry."
10274
- };
10275
- EDGE_FAILURE = "The platform failed without its JSON error body: a proxy in front of it answered, or the server stopped before its error handler ran. Retry; if it repeats, report the request and the time.";
10276
- EDGE_PAGE = "An HTML page answered instead of the platform's JSON: a proxy in front of the platform, or the configured host is not the platform.";
11459
+ init_query();
11460
+ init_migrate();
11461
+ init_ingest();
11462
+ init_sandbox();
11463
+ init_editSessions();
11464
+ init_states();
11465
+ init_dryRun();
11466
+ init_worldNotice();
10277
11467
  WorldTask = class {
10278
11468
  constructor(world, name, variant) {
10279
11469
  this.world = world;
@@ -12734,6 +13924,961 @@ init_scores();
12734
13924
  init_worlds();
12735
13925
  init_session2();
12736
13926
 
13927
+ // src/agents/agent.ts
13928
+ init_apiError();
13929
+
13930
+ // src/agents/patch.ts
13931
+ var list = (value) => Array.isArray(value) ? value : [value];
13932
+ function grantOf(input) {
13933
+ if (typeof input === "string") return { server: input };
13934
+ return input.only ? { server: input.server, only: [...input.only].sort() } : { server: input.server };
13935
+ }
13936
+ var AgentPatch = class _AgentPatch {
13937
+ constructor(json) {
13938
+ this.json = json;
13939
+ }
13940
+ json;
13941
+ static update(fields) {
13942
+ const set = Object.fromEntries(Object.entries(fields).filter(([, value]) => value !== void 0));
13943
+ return new _AgentPatch({ set });
13944
+ }
13945
+ static attach(grants) {
13946
+ return new _AgentPatch({ attach: list(grants).map(grantOf) });
13947
+ }
13948
+ static detach(servers) {
13949
+ return new _AgentPatch({ detach: [...list(servers)] });
13950
+ }
13951
+ toJSON() {
13952
+ return structuredClone(this.json);
13953
+ }
13954
+ };
13955
+
13956
+ // src/agents/agent.ts
13957
+ var AgentVersionConflictError = class extends ApiError {
13958
+ currentVersionId;
13959
+ constructor(status, method, path17, text2) {
13960
+ super(status, method, path17, text2);
13961
+ this.name = "AgentVersionConflictError";
13962
+ this.currentVersionId = currentVersionOf(text2);
13963
+ }
13964
+ };
13965
+ function currentVersionOf(text2) {
13966
+ try {
13967
+ const id = JSON.parse(text2).currentVersionId;
13968
+ return typeof id === "string" ? id : null;
13969
+ } catch {
13970
+ return null;
13971
+ }
13972
+ }
13973
+ var AgentTools = class {
13974
+ constructor(agent) {
13975
+ this.agent = agent;
13976
+ }
13977
+ agent;
13978
+ /** Grant servers: one already attached keeps its place and takes the new grant. */
13979
+ attach(grants, options = {}) {
13980
+ return this.agent.edit(AgentPatch.attach(grants), options);
13981
+ }
13982
+ /** Remove servers; one that is not attached changes nothing. */
13983
+ detach(servers, options = {}) {
13984
+ return this.agent.edit(AgentPatch.detach(servers), options);
13985
+ }
13986
+ };
13987
+ var AgentThreads = class {
13988
+ constructor(threads, name) {
13989
+ this.threads = threads;
13990
+ this.name = name;
13991
+ }
13992
+ threads;
13993
+ name;
13994
+ create(options = {}) {
13995
+ return this.threads.create({ ...options, agent: this.name });
13996
+ }
13997
+ };
13998
+ var Agent = class {
13999
+ #agents;
14000
+ #record;
14001
+ tools;
14002
+ threads;
14003
+ constructor(agents, record, threads) {
14004
+ this.#agents = agents;
14005
+ this.#record = liveOf(record);
14006
+ this.tools = new AgentTools(this);
14007
+ this.threads = new AgentThreads(threads, record.name);
14008
+ }
14009
+ get name() {
14010
+ return this.#record.name;
14011
+ }
14012
+ /** The version edits apply to: the one `production` runs (else, never deployed, the newest). */
14013
+ get versionId() {
14014
+ return this.#record.versionId;
14015
+ }
14016
+ get version() {
14017
+ return this.#record.version;
14018
+ }
14019
+ get buildHash() {
14020
+ return this.#record.buildHash;
14021
+ }
14022
+ get deployed() {
14023
+ return this.#record.deployed;
14024
+ }
14025
+ get definition() {
14026
+ return structuredClone(this.#record.definition);
14027
+ }
14028
+ /** Change fields: a new version, live unless `deploy: false`; a change to the values it already has writes nothing. */
14029
+ update(fields, options = {}) {
14030
+ return this.edit(AgentPatch.update(fields), options);
14031
+ }
14032
+ /** Apply one patch made of `AgentPatch.update`, `.attach` or `.detach`. */
14033
+ async edit(patch, options = {}) {
14034
+ const result = await this.#agents.edit(this.name, patch, { ...options, from: this.versionId });
14035
+ if (result.deployed || !this.deployed) this.#record = liveOf(result);
14036
+ return result;
14037
+ }
14038
+ /** Move `production` to one of this agent's versions (an earlier one, or one staged with `deploy: false`); `force` crosses a breaking tool change. */
14039
+ async rollback(versionId, options = {}) {
14040
+ this.#record = liveOf(await this.#agents.rollback(this.name, versionId, { ...options, from: this.versionId }));
14041
+ return this.toJSON();
14042
+ }
14043
+ /** Every version, newest first, with whether it is live and its changes against the version before it. */
14044
+ versions() {
14045
+ return this.#agents.history(this.name);
14046
+ }
14047
+ /** Read the live version again, after a conflict or someone else's change. */
14048
+ async refresh() {
14049
+ this.#record = liveOf(await this.#agents.live(this.name));
14050
+ return this;
14051
+ }
14052
+ /** Start a thread with this agent and send it `input`: the run uses the version `production` runs now (or `version`). */
14053
+ async run(input, options = {}) {
14054
+ const { version, ...thread } = options;
14055
+ return (await this.threads.create(thread)).send(input, { version });
14056
+ }
14057
+ toJSON() {
14058
+ return { ...this.#record, definition: this.definition };
14059
+ }
14060
+ };
14061
+ function liveOf(record) {
14062
+ const { name, versionId, version, buildHash, deployed, definition: definition2 } = record;
14063
+ return { name, versionId, version, buildHash, deployed, definition: definition2 };
14064
+ }
14065
+
14066
+ // src/agents/definition.ts
14067
+ var NAME_PATTERN = /^[a-z0-9][a-z0-9-]{0,62}$/;
14068
+ var DEFAULT_MODEL = "claude-opus-5";
14069
+ var DEFAULT_MAX_TURNS = 50;
14070
+ var INSTRUCTIONS = { min: 1, max: 65536 };
14071
+ var MAX_TURNS = { min: 1, max: 200 };
14072
+ var DEFINITION_FIELDS = /* @__PURE__ */ new Set([
14073
+ "name",
14074
+ "instructions",
14075
+ "model",
14076
+ "effort",
14077
+ "maxTurns",
14078
+ "tools"
14079
+ ]);
14080
+ var GRANT_FIELDS = /* @__PURE__ */ new Set(["server", "only"]);
14081
+ var AgentDefinitionError = class extends Error {
14082
+ constructor(issues) {
14083
+ super(`Invalid agent definition: ${issues.map((issue) => `${pathText(issue.path)}: ${issue.message}`).join("; ")}`);
14084
+ this.issues = issues;
14085
+ this.name = "AgentDefinitionError";
14086
+ }
14087
+ issues;
14088
+ };
14089
+ var AgentDefinition = class _AgentDefinition {
14090
+ name;
14091
+ instructions;
14092
+ model;
14093
+ effort;
14094
+ maxTurns;
14095
+ tools;
14096
+ constructor(spec) {
14097
+ this.name = spec.name;
14098
+ this.instructions = spec.instructions;
14099
+ this.model = spec.model;
14100
+ this.effort = spec.effort;
14101
+ this.maxTurns = spec.maxTurns;
14102
+ this.tools = Object.freeze(spec.tools.map(freezeGrant));
14103
+ Object.freeze(this);
14104
+ }
14105
+ /** Validate and normalize any value (a parsed JSON file included); throws `AgentDefinitionError` listing every broken rule. */
14106
+ static from(input) {
14107
+ return new _AgentDefinition(DefinitionReader.read(input));
14108
+ }
14109
+ /** The normalized definition: defaults filled, tool shorthands expanded, `only` sorted, `effort` present only when set. */
14110
+ toJSON() {
14111
+ return {
14112
+ name: this.name,
14113
+ instructions: this.instructions,
14114
+ model: this.model,
14115
+ ...this.effort === void 0 ? {} : { effort: this.effort },
14116
+ maxTurns: this.maxTurns,
14117
+ tools: this.tools.map(
14118
+ (grant2) => grant2.only ? { server: grant2.server, only: [...grant2.only] } : { server: grant2.server }
14119
+ )
14120
+ };
14121
+ }
14122
+ };
14123
+ function defineAgent(input) {
14124
+ return AgentDefinition.from(input);
14125
+ }
14126
+ function freezeGrant(grant2) {
14127
+ const only = grant2.only ? { only: Object.freeze([...grant2.only]) } : {};
14128
+ return Object.freeze({ server: grant2.server, ...only });
14129
+ }
14130
+ function pathText(path17) {
14131
+ return path17.length === 0 ? "definition" : path17.join(".");
14132
+ }
14133
+ function isRecord2(value) {
14134
+ return typeof value === "object" && value !== null && !Array.isArray(value);
14135
+ }
14136
+ function isString(value) {
14137
+ return value !== null;
14138
+ }
14139
+ var DefinitionReader = class _DefinitionReader {
14140
+ #issues = [];
14141
+ static read(input) {
14142
+ const reader = new _DefinitionReader();
14143
+ const spec = reader.spec(input);
14144
+ if (!spec || reader.#issues.length > 0) throw new AgentDefinitionError(reader.#issues);
14145
+ return spec;
14146
+ }
14147
+ spec(input) {
14148
+ if (!isRecord2(input)) return this.refuse([], "invalid_type", "a definition is an object", null);
14149
+ this.unknownFields(input, DEFINITION_FIELDS, []);
14150
+ const effort = this.optionalString(input.effort, ["effort"]);
14151
+ return {
14152
+ name: this.name(input.name),
14153
+ instructions: this.instructions(input.instructions),
14154
+ model: this.optionalString(input.model, ["model"]) ?? DEFAULT_MODEL,
14155
+ ...effort === void 0 ? {} : { effort },
14156
+ maxTurns: this.maxTurns(input.maxTurns),
14157
+ tools: this.tools(input.tools)
14158
+ };
14159
+ }
14160
+ name(value) {
14161
+ const name = this.string(value, ["name"]);
14162
+ if (name !== null && !NAME_PATTERN.test(name))
14163
+ this.issue(["name"], "invalid_name", "lowercase letters, digits and dashes, 1-63 long, not starting with a dash");
14164
+ return name ?? "";
14165
+ }
14166
+ instructions(value) {
14167
+ const instructions = this.string(value, ["instructions"]);
14168
+ if (instructions !== null) this.bounded(instructions.length, INSTRUCTIONS, ["instructions"], "characters");
14169
+ return instructions ?? "";
14170
+ }
14171
+ maxTurns(value) {
14172
+ if (value === void 0) return DEFAULT_MAX_TURNS;
14173
+ if (typeof value !== "number" || !Number.isInteger(value))
14174
+ return this.refuse(["maxTurns"], "invalid_type", "a whole number", DEFAULT_MAX_TURNS);
14175
+ this.bounded(value, MAX_TURNS, ["maxTurns"], "turns");
14176
+ return value;
14177
+ }
14178
+ tools(value) {
14179
+ if (value === void 0) return [];
14180
+ if (!Array.isArray(value)) return this.refuse(["tools"], "invalid_type", "a list of tools", []);
14181
+ const grants = value.map((entry, index2) => this.grant(entry, ["tools", index2]));
14182
+ this.noRepeats(
14183
+ grants.map((grant2) => grant2?.server ?? null),
14184
+ (index2) => ["tools", index2, "server"],
14185
+ "duplicate_tool_server",
14186
+ "this server is already granted"
14187
+ );
14188
+ return grants.filter((grant2) => grant2 !== null);
14189
+ }
14190
+ grant(entry, path17) {
14191
+ if (typeof entry === "string") return { server: entry };
14192
+ if (!isRecord2(entry)) return this.refuse(path17, "invalid_type", "a server name or { server, only }", null);
14193
+ this.unknownFields(entry, GRANT_FIELDS, path17);
14194
+ const server = this.string(entry.server, [...path17, "server"]);
14195
+ if (server === null) return null;
14196
+ return entry.only === void 0 ? { server } : { server, only: this.only(entry.only, [...path17, "only"]) };
14197
+ }
14198
+ only(value, path17) {
14199
+ if (!Array.isArray(value)) return this.refuse(path17, "invalid_type", "a list of tool names", []);
14200
+ if (value.length === 0)
14201
+ this.issue(path17, "too_small", "names at least one tool; leave `only` out to grant the whole server");
14202
+ const names = value.map((name, index2) => this.string(name, [...path17, index2]));
14203
+ this.noRepeats(names, (index2) => [...path17, index2], "duplicate_tool", "this tool is already named");
14204
+ return names.filter(isString).sort();
14205
+ }
14206
+ string(value, path17) {
14207
+ if (typeof value === "string") return value;
14208
+ return this.refuse(path17, "invalid_type", "a string", null);
14209
+ }
14210
+ optionalString(value, path17) {
14211
+ if (value === void 0) return void 0;
14212
+ return this.string(value, path17) ?? void 0;
14213
+ }
14214
+ bounded(value, bounds, path17, unit) {
14215
+ if (value < bounds.min) this.issue(path17, "too_small", `at least ${bounds.min} ${unit}`);
14216
+ if (value > bounds.max) this.issue(path17, "too_large", `at most ${bounds.max} ${unit}`);
14217
+ }
14218
+ unknownFields(record, known, path17) {
14219
+ for (const [key2, value] of Object.entries(record)) {
14220
+ if (value !== void 0 && !known.has(key2))
14221
+ this.issue([...path17, key2], "unknown_field", "not a field of an agent definition");
14222
+ }
14223
+ }
14224
+ noRepeats(values, pathOf, code, message) {
14225
+ const seen = /* @__PURE__ */ new Set();
14226
+ values.forEach((value, index2) => {
14227
+ if (value === null) return;
14228
+ if (seen.has(value)) this.issue(pathOf(index2), code, message);
14229
+ seen.add(value);
14230
+ });
14231
+ }
14232
+ issue(path17, code, message) {
14233
+ this.#issues.push({ path: path17, code, message });
14234
+ }
14235
+ refuse(path17, code, message, fallback) {
14236
+ this.issue(path17, code, message);
14237
+ return fallback;
14238
+ }
14239
+ };
14240
+
14241
+ // src/agents/index.ts
14242
+ init_apiError();
14243
+ init_transport();
14244
+
14245
+ // src/agents/agents.ts
14246
+ init_apiError();
14247
+
14248
+ // src/agents/segment.ts
14249
+ function segment(id) {
14250
+ if (id === "" || id === "." || id === "..") throw new TypeError(`not an id: "${id}"`);
14251
+ return encodeURIComponent(id);
14252
+ }
14253
+
14254
+ // src/agents/agents.ts
14255
+ var PRODUCTION = "production";
14256
+ var PAGE_SIZE = 100;
14257
+ var buildRoute = (buildId) => `/api/public/agent-builds/${segment(buildId)}`;
14258
+ var AgentVersionNotFoundError = class extends Error {
14259
+ constructor(agent, versionId) {
14260
+ super(`${versionId} is not a version of ${agent}; nothing was deployed.`);
14261
+ this.agent = agent;
14262
+ this.versionId = versionId;
14263
+ this.name = "AgentVersionNotFoundError";
14264
+ }
14265
+ agent;
14266
+ versionId;
14267
+ code = "version_not_found";
14268
+ };
14269
+ var Agents = class {
14270
+ #transport;
14271
+ #threads;
14272
+ constructor(transport, threads) {
14273
+ this.#transport = transport;
14274
+ this.#threads = threads;
14275
+ }
14276
+ /** Create an agent, live in one call: version 1, deployed. A definition `defineAgent` would refuse throws `AgentDefinitionError` before anything is sent; a name the project already holds is 409 `agent_exists`. */
14277
+ async create(input) {
14278
+ const { name, ...definition2 } = AgentDefinition.from(input).toJSON();
14279
+ const record = await this.#transport.json(
14280
+ "POST",
14281
+ `/api/public/agent-builds/definitions/${segment(name)}`,
14282
+ definition2
14283
+ );
14284
+ return new Agent(this, record, this.#threads);
14285
+ }
14286
+ /** The live agent named `name`, to edit or run; 404 `agent_not_found` when the project has none. */
14287
+ async get(name) {
14288
+ return new Agent(this, await this.live(name), this.#threads);
14289
+ }
14290
+ /** The version of `name` that edits apply to: the one `production` runs, else the newest. */
14291
+ live(name) {
14292
+ return this.#transport.json("GET", `/api/public/agent-builds/definitions/${segment(name)}`);
14293
+ }
14294
+ /** Apply one patch to `name` as a new version, live unless `deploy: false`. With `from`, a version that is no longer the live one is refused (`AgentVersionConflictError`) and nothing is written. */
14295
+ edit(name, patch, options = {}) {
14296
+ const body = { patch: patch.toJSON(), from: options.from, deploy: options.deploy ?? true };
14297
+ return this.conflictAware("POST", `/api/public/agent-builds/definitions/${segment(name)}/versions`, body);
14298
+ }
14299
+ /** Move `production` of `name` to one of its versions, with the audit row; `force` crosses a breaking tool change. */
14300
+ rollback(name, versionId, options = {}) {
14301
+ const body = { versionId, from: options.from, force: options.force ?? false };
14302
+ return this.conflictAware("POST", `/api/public/agent-builds/definitions/${segment(name)}/rollback`, body);
14303
+ }
14304
+ /** Every version of the live agent `name`, newest first, each with `isDeployed` and its changes against the one before; a version written while the pages are read never repeats one. */
14305
+ async history(name) {
14306
+ const versions = /* @__PURE__ */ new Map();
14307
+ for (let page = 1, pages = 1; page <= pages; page += 1) {
14308
+ const query = new URLSearchParams({ page: String(page), limit: String(PAGE_SIZE) });
14309
+ const reply = await this.#transport.json(
14310
+ "GET",
14311
+ `/api/public/agent-builds/definitions/${segment(name)}/versions?${query}`
14312
+ );
14313
+ for (const version of reply.data) if (!versions.has(version.id)) versions.set(version.id, version);
14314
+ pages = reply.meta.totalPages;
14315
+ }
14316
+ return [...versions.values()];
14317
+ }
14318
+ /** Push a definition: a new version, or the identical one already pushed (`created: false`); the platform derives its `buildHash`. With `deploy`, `production` moves to it; when that move is refused the version still exists, and pushing again returns it. */
14319
+ async push(definition2, options = {}) {
14320
+ const body = { definition: definition2.toJSON(), attribution: options.attribution };
14321
+ const version = await this.#transport.json("POST", "/api/public/agent-builds/definitions", body);
14322
+ if (!options.deploy) return version;
14323
+ await this.move(version.id, false);
14324
+ return { ...version, deployed: true, labels: [.../* @__PURE__ */ new Set([...version.labels, PRODUCTION])] };
14325
+ }
14326
+ /** Move `production` to `versionId`, after checking it is a defined version of `name` (an observed build of that name is not one). Rolling back is deploying an older version; `force` crosses a breaking tool change. */
14327
+ async deploy(name, versionId, options = {}) {
14328
+ const versions = await this.versions(name);
14329
+ if (!versions.some((version) => version.id === versionId && version.kind === "defined"))
14330
+ throw new AgentVersionNotFoundError(name, versionId);
14331
+ return this.move(versionId, options.force ?? false);
14332
+ }
14333
+ /** Every version of `name`, newest first. */
14334
+ async versions(name) {
14335
+ const builds = [];
14336
+ for (let page = 1, pages = 1; page <= pages; page += 1) {
14337
+ const query = new URLSearchParams({ agentId: name, page: String(page), limit: String(PAGE_SIZE) });
14338
+ const reply = await this.#transport.json("GET", `/api/public/agent-builds?${query}`);
14339
+ builds.push(...reply.data);
14340
+ pages = reply.meta.totalPages;
14341
+ }
14342
+ return builds;
14343
+ }
14344
+ async conflictAware(method, path17, body) {
14345
+ try {
14346
+ return await this.#transport.json(method, path17, body);
14347
+ } catch (error) {
14348
+ if (error instanceof ApiError && error.code === "agent_version_conflict")
14349
+ throw new AgentVersionConflictError(error.status, method, path17, error.text);
14350
+ throw error;
14351
+ }
14352
+ }
14353
+ async move(versionId, force) {
14354
+ const body = { label: PRODUCTION, source: "api", force };
14355
+ const moved = await this.#transport.json("POST", `${buildRoute(versionId)}/labels`, body);
14356
+ return {
14357
+ agentId: moved.agentId,
14358
+ label: moved.label,
14359
+ versionId,
14360
+ fromBuildHash: moved.fromBuild,
14361
+ toBuildHash: moved.toBuild
14362
+ };
14363
+ }
14364
+ };
14365
+
14366
+ // src/agents/gateway.ts
14367
+ init_platformEndpoint();
14368
+ init_transport();
14369
+
14370
+ // src/agents/run.ts
14371
+ init_apiError();
14372
+ init_transport();
14373
+
14374
+ // src/agents/sse.ts
14375
+ var EventStreamError = class extends Error {
14376
+ constructor(code, message) {
14377
+ super(message);
14378
+ this.code = code;
14379
+ this.name = "EventStreamError";
14380
+ }
14381
+ code;
14382
+ };
14383
+ var SseLimits = class _SseLimits {
14384
+ constructor(maxLineLength, maxEventLength) {
14385
+ this.maxLineLength = maxLineLength;
14386
+ this.maxEventLength = maxEventLength;
14387
+ }
14388
+ maxLineLength;
14389
+ maxEventLength;
14390
+ static DEFAULT = new _SseLimits(4 * 1024 * 1024, 4 * 1024 * 1024);
14391
+ };
14392
+ var EventBlock = class {
14393
+ constructor(id, limits) {
14394
+ this.id = id;
14395
+ this.limits = limits;
14396
+ }
14397
+ id;
14398
+ limits;
14399
+ #data = [];
14400
+ #length = 0;
14401
+ #type = "";
14402
+ addData(value) {
14403
+ this.#length += value.length + 1;
14404
+ if (this.#length > this.limits.maxEventLength)
14405
+ throw new EventStreamError("event_too_large", `an event passed ${this.limits.maxEventLength} characters`);
14406
+ this.#data.push(value);
14407
+ }
14408
+ setType(value) {
14409
+ this.#type = value;
14410
+ }
14411
+ setId(value) {
14412
+ if (!value.includes("\0")) this.id = value;
14413
+ }
14414
+ message() {
14415
+ if (this.#data.length === 0) return null;
14416
+ return { event: this.#type || "message", data: this.#data.join("\n"), lastEventId: this.id || null };
14417
+ }
14418
+ };
14419
+ var FIELDS2 = /* @__PURE__ */ new Map([
14420
+ ["data", (block, value) => block.addData(value)],
14421
+ ["event", (block, value) => block.setType(value)],
14422
+ ["id", (block, value) => block.setId(value)]
14423
+ ]);
14424
+ var SseParser = class {
14425
+ #decoder = new TextDecoder();
14426
+ #lineEnd = /[\r\n]/g;
14427
+ #limits;
14428
+ #pending = "";
14429
+ #afterCarriageReturn = false;
14430
+ #lastEventId;
14431
+ #block;
14432
+ constructor(lastEventId = null, limits = SseLimits.DEFAULT) {
14433
+ this.#limits = limits;
14434
+ this.#lastEventId = lastEventId ?? "";
14435
+ this.#block = new EventBlock(this.#lastEventId, limits);
14436
+ }
14437
+ /** The id a reconnect sends as `Last-Event-ID`: the last one set before a dispatched event, or null. */
14438
+ get lastEventId() {
14439
+ return this.#lastEventId || null;
14440
+ }
14441
+ /** Feed the next bytes; returns the events they completed, in order. */
14442
+ push(chunk) {
14443
+ const messages = [];
14444
+ for (const line of this.lines(this.#decoder.decode(chunk, { stream: true }))) {
14445
+ const message = this.line(line);
14446
+ if (message) messages.push(message);
14447
+ }
14448
+ return messages;
14449
+ }
14450
+ lines(text2) {
14451
+ const scanFrom = this.#pending.length;
14452
+ this.#pending += this.skipLineFeed(text2);
14453
+ const lines = [];
14454
+ let start = 0;
14455
+ this.#lineEnd.lastIndex = scanFrom;
14456
+ for (let end = this.#lineEnd.exec(this.#pending); end; end = this.#lineEnd.exec(this.#pending)) {
14457
+ lines.push(this.capped(this.#pending.slice(start, end.index)));
14458
+ start = this.lineEnd(end.index);
14459
+ this.#lineEnd.lastIndex = start;
14460
+ }
14461
+ this.#pending = this.capped(this.#pending.slice(start));
14462
+ return lines;
14463
+ }
14464
+ lineEnd(index2) {
14465
+ const crlf = this.#pending.startsWith("\r\n", index2);
14466
+ this.#afterCarriageReturn = this.#pending[index2] === "\r" && index2 + 1 === this.#pending.length;
14467
+ return index2 + (crlf ? 2 : 1);
14468
+ }
14469
+ skipLineFeed(text2) {
14470
+ if (!this.#afterCarriageReturn || text2 === "") return text2;
14471
+ this.#afterCarriageReturn = false;
14472
+ return text2.startsWith("\n") ? text2.slice(1) : text2;
14473
+ }
14474
+ capped(line) {
14475
+ if (line.length > this.#limits.maxLineLength)
14476
+ throw new EventStreamError("line_too_large", `a line passed ${this.#limits.maxLineLength} characters`);
14477
+ return line;
14478
+ }
14479
+ line(line) {
14480
+ if (line === "") return this.dispatch();
14481
+ if (line.startsWith(":")) return null;
14482
+ const colon = line.indexOf(":");
14483
+ const field2 = colon === -1 ? line : line.slice(0, colon);
14484
+ const value = colon === -1 ? "" : line.slice(colon + 1).replace(/^ /, "");
14485
+ FIELDS2.get(field2)?.(this.#block, value);
14486
+ return null;
14487
+ }
14488
+ dispatch() {
14489
+ const message = this.#block.message();
14490
+ this.#lastEventId = this.#block.id;
14491
+ this.#block = new EventBlock(this.#lastEventId, this.#limits);
14492
+ return message;
14493
+ }
14494
+ };
14495
+
14496
+ // src/agents/run.ts
14497
+ var SYSTEM_CLOCK = Object.freeze({
14498
+ now: () => Date.now(),
14499
+ sleep: (ms, signal) => new Promise((resolve11, reject) => {
14500
+ if (signal?.aborted) return reject(signal.reason);
14501
+ const abort = () => {
14502
+ clearTimeout(timer);
14503
+ reject(signal?.reason);
14504
+ };
14505
+ const timer = setTimeout(() => {
14506
+ signal?.removeEventListener("abort", abort);
14507
+ resolve11();
14508
+ }, ms);
14509
+ signal?.addEventListener("abort", abort, { once: true });
14510
+ })
14511
+ });
14512
+ var ReconnectPolicy = class _ReconnectPolicy {
14513
+ constructor(delaysMs, idleMs) {
14514
+ this.delaysMs = delaysMs;
14515
+ this.idleMs = idleMs;
14516
+ }
14517
+ delaysMs;
14518
+ idleMs;
14519
+ static DEFAULT = new _ReconnectPolicy([250, 500, 1e3, 2e3, 4e3], PLATFORM_STREAM_IDLE_MS);
14520
+ };
14521
+ var STOPS = {
14522
+ "run.started": "continues",
14523
+ "step.attempt": "continues",
14524
+ "message.delta": "continues",
14525
+ "step.completed": "continues",
14526
+ "tool.started": "continues",
14527
+ "tool.completed": "continues",
14528
+ "run.error": "continues",
14529
+ "action.required": "waits",
14530
+ "run.completed": "ends",
14531
+ "run.failed": "ends",
14532
+ "run.cancelled": "ends"
14533
+ };
14534
+ var FINISHED = /* @__PURE__ */ new Set(["completed", "failed", "cancelled"]);
14535
+ var REFRESH_RETRIES = 3;
14536
+ var STREAM_REFUSALS_RETRIED = /* @__PURE__ */ new Set(["too_many_streams"]);
14537
+ var runRoute = (threadId, runId) => `/api/public/threads/${segment(threadId)}/runs/${segment(runId)}`;
14538
+ function readEvent(message) {
14539
+ if (!Object.hasOwn(STOPS, message.event)) return null;
14540
+ const data = parseJson2(message.data);
14541
+ if (typeof data !== "object" || data === null || data.type !== message.event)
14542
+ throw new EventStreamError("malformed_event", `a ${message.event} event whose data is not that event's JSON`);
14543
+ return data;
14544
+ }
14545
+ function retried(refusal) {
14546
+ return RetryPolicy.TRANSIENT_STATUSES.has(refusal.status) || STREAM_REFUSALS_RETRIED.has(refusal.code ?? "");
14547
+ }
14548
+ function parseJson2(text2) {
14549
+ try {
14550
+ return JSON.parse(text2);
14551
+ } catch {
14552
+ return void 0;
14553
+ }
14554
+ }
14555
+ var Connection = class {
14556
+ constructor(openedAt) {
14557
+ this.openedAt = openedAt;
14558
+ }
14559
+ openedAt;
14560
+ #delivered = false;
14561
+ #closedCleanly = false;
14562
+ #stop = "continues";
14563
+ #why = "the stream closed before the run ended";
14564
+ get ended() {
14565
+ return this.#stop === "ends";
14566
+ }
14567
+ // The door closes after action.required only while the run waits; when more events follow, that wait was answered.
14568
+ get stopped() {
14569
+ return this.#stop !== "continues";
14570
+ }
14571
+ get why() {
14572
+ return this.#why;
14573
+ }
14574
+ delivered() {
14575
+ this.#delivered = true;
14576
+ }
14577
+ at(stop) {
14578
+ this.#stop = stop;
14579
+ }
14580
+ closedCleanly() {
14581
+ this.#closedCleanly = true;
14582
+ }
14583
+ refused(status) {
14584
+ this.#why = `the platform answered ${status}`;
14585
+ }
14586
+ dropped(error) {
14587
+ if (!(error instanceof UnreachableError)) throw error;
14588
+ this.#why = error.message;
14589
+ }
14590
+ // A silence cut, a drop or a refused status never counts as working, however long it took: only an event, or the
14591
+ // platform's own clean close of a stream that lived the idle budget (its lifetime close), starts the count again.
14592
+ working(now, idleMs) {
14593
+ return this.#delivered || this.#closedCleanly && now - this.openedAt >= idleMs;
14594
+ }
14595
+ };
14596
+ var Reconnects = class {
14597
+ constructor(policy, clock, route2) {
14598
+ this.policy = policy;
14599
+ this.clock = clock;
14600
+ this.route = route2;
14601
+ }
14602
+ policy;
14603
+ clock;
14604
+ route;
14605
+ #inARow = 0;
14606
+ async after(connection, signal) {
14607
+ this.#inARow = connection.working(this.clock.now(), this.policy.idleMs) ? 1 : this.#inARow + 1;
14608
+ const delayMs = this.policy.delaysMs[this.#inARow - 1];
14609
+ if (delayMs === void 0)
14610
+ throw new EventStreamError(
14611
+ "reconnects_exhausted",
14612
+ `GET ${this.route}: no working stream after ${this.policy.delaysMs.length} reconnects in a row; last: ${connection.why}`
14613
+ );
14614
+ await this.clock.sleep(delayMs, signal);
14615
+ }
14616
+ };
14617
+ var AgentRun = class {
14618
+ #transport;
14619
+ #clock;
14620
+ #reconnect;
14621
+ #snapshot;
14622
+ #cursor = null;
14623
+ #ending = null;
14624
+ constructor(transport, run, options = {}) {
14625
+ this.#transport = transport;
14626
+ this.#snapshot = run;
14627
+ this.#clock = options.clock ?? SYSTEM_CLOCK;
14628
+ this.#reconnect = options.reconnect ?? ReconnectPolicy.DEFAULT;
14629
+ }
14630
+ get id() {
14631
+ return this.#snapshot.id;
14632
+ }
14633
+ get threadId() {
14634
+ return this.#snapshot.threadId;
14635
+ }
14636
+ /** The run as last read from the platform. */
14637
+ get snapshot() {
14638
+ return this.#snapshot;
14639
+ }
14640
+ /** The id of the last event delivered by any reader; pass it as `after` to resume this run's events elsewhere. */
14641
+ get cursor() {
14642
+ return this.#cursor;
14643
+ }
14644
+ /**
14645
+ * The run's events from `after` (default: where the last `events()` stopped, else the start). A dropped connection, a
14646
+ * silence past the idle budget (60 s), a 502/503/504, a 429 `too_many_streams` or the platform closing the stream
14647
+ * reconnects with `Last-Event-ID`,
14648
+ * so each event arrives once; after 5 reconnects in a row with no event delivered (a clean close after at least the idle
14649
+ * budget also counts as working) it throws `EventStreamError`. Ends after `run.completed`, `run.failed` (`not_found` when
14650
+ * the run no longer exists) or `run.cancelled`, and at an `action.required` the platform ends the stream on (the run waits
14651
+ * for a person); an `action.required` followed by more events was a wait already answered, and the events go on. A key
14652
+ * holds at most 64 open streams: past that the platform answers 429 `too_many_streams`, which counts against the same
14653
+ * five reconnects.
14654
+ */
14655
+ async *events(options = {}) {
14656
+ const position = { cursor: options.after === void 0 ? this.#cursor : options.after };
14657
+ this.#ending = null;
14658
+ const reconnects = new Reconnects(this.#reconnect, this.#clock, `${runRoute(this.threadId, this.id)}/events`);
14659
+ for (; ; ) {
14660
+ const connection = new Connection(this.#clock.now());
14661
+ yield* this.connect(position, connection, options.signal);
14662
+ if (connection.stopped) return;
14663
+ await reconnects.after(connection, options.signal);
14664
+ }
14665
+ }
14666
+ /** The run once it has finished, or once it waits for a person (`status: "requires_action"` with its `action`). Throws `EventStreamError` `run_not_finished` when the stream ended the run and the platform still reads it as active after the reconnect delays, and the platform's 404 `ApiError` (`not_found`) for a run that no longer exists. */
14667
+ async wait(options = {}) {
14668
+ const polls = this.#reconnect.delaysMs[Symbol.iterator]();
14669
+ let run = this.#ending === null ? this.#snapshot : await this.refresh(options);
14670
+ while (!this.settled(run)) {
14671
+ await this.advance(polls, options.signal);
14672
+ run = await this.refresh(options);
14673
+ }
14674
+ return run;
14675
+ }
14676
+ /** The run as the platform reads it now; a gateway 5xx or a dropped connection is retried with the first reconnect delays. `signal` aborts the request and its retry waits. */
14677
+ async refresh(options = {}) {
14678
+ const { signal } = options;
14679
+ const retry = new RetryPolicy(
14680
+ this.#reconnect.delaysMs.slice(0, REFRESH_RETRIES),
14681
+ (ms) => this.#clock.sleep(ms, signal)
14682
+ );
14683
+ return this.take(
14684
+ await this.#transport.json("GET", `${runRoute(this.threadId, this.id)}`, void 0, { retry, signal })
14685
+ );
14686
+ }
14687
+ /** Stop the run; a run already finished answers with its status. */
14688
+ async cancel(options = {}) {
14689
+ const { signal } = options;
14690
+ return this.take(
14691
+ await this.#transport.json("POST", `${runRoute(this.threadId, this.id)}/cancel`, {}, { signal })
14692
+ );
14693
+ }
14694
+ /** Answer the question the run waits on; the run is queued again and `events()` continues from where it stopped. */
14695
+ async resolve(answer, options = {}) {
14696
+ const body = { actionId: answer.actionId, answer: answer.answer };
14697
+ const { signal } = options;
14698
+ const run = await this.#transport.json("POST", `${runRoute(this.threadId, this.id)}/resolve`, body, {
14699
+ signal
14700
+ });
14701
+ this.#ending = null;
14702
+ return this.take(run);
14703
+ }
14704
+ settled(run) {
14705
+ return FINISHED.has(run.status) || this.#ending === "action.required" && run.status === "requires_action";
14706
+ }
14707
+ async advance(polls, signal) {
14708
+ if (this.#ending !== null && this.#ending !== "action.required") return this.pause(polls, signal);
14709
+ const before = this.#cursor;
14710
+ for await (const event of this.events({ signal })) void event;
14711
+ if (this.#ending === "action.required" && this.#cursor === before) await this.pause(polls, signal);
14712
+ }
14713
+ async pause(polls, signal) {
14714
+ const delay = polls.next();
14715
+ if (delay.done)
14716
+ throw new EventStreamError(
14717
+ "run_not_finished",
14718
+ `${runRoute(this.threadId, this.id)}: the stream ended the run with ${this.#ending}, and the platform still reads it as ${this.#snapshot.status}`
14719
+ );
14720
+ await this.#clock.sleep(delay.value, signal);
14721
+ }
14722
+ take(run) {
14723
+ this.#snapshot = run;
14724
+ return run;
14725
+ }
14726
+ async *connect(position, connection, signal) {
14727
+ const stream = await this.open(position, connection, signal);
14728
+ if (!stream) return;
14729
+ try {
14730
+ yield* this.read(stream, position, connection);
14731
+ connection.closedCleanly();
14732
+ } catch (error) {
14733
+ connection.dropped(error);
14734
+ } finally {
14735
+ stream.close();
14736
+ }
14737
+ }
14738
+ async open(position, connection, signal) {
14739
+ const route2 = `${runRoute(this.threadId, this.id)}/events`;
14740
+ try {
14741
+ const stream = await this.#transport.stream(route2, {
14742
+ after: position.cursor,
14743
+ signal,
14744
+ idleMs: this.#reconnect.idleMs
14745
+ });
14746
+ return await this.accepted(stream, route2, connection);
14747
+ } catch (error) {
14748
+ connection.dropped(error);
14749
+ return null;
14750
+ }
14751
+ }
14752
+ async accepted(stream, route2, connection) {
14753
+ if (stream.ok) return stream;
14754
+ const refusal = new ApiError(stream.status, "GET", route2, await stream.text());
14755
+ if (!retried(refusal)) throw refusal;
14756
+ connection.refused(stream.status);
14757
+ return null;
14758
+ }
14759
+ async *read(stream, position, connection) {
14760
+ const parser = new SseParser(position.cursor);
14761
+ for await (const chunk of stream.chunks()) {
14762
+ for (const message of parser.push(chunk)) {
14763
+ const event = readEvent(message);
14764
+ this.moveTo(position, message.lastEventId);
14765
+ if (!event) continue;
14766
+ connection.delivered();
14767
+ this.note(event, connection);
14768
+ yield event;
14769
+ if (connection.ended) return;
14770
+ }
14771
+ this.moveTo(position, parser.lastEventId);
14772
+ }
14773
+ }
14774
+ // Each events() call resumes from its own position, so two readers of one run never skip or repeat each other's events.
14775
+ moveTo(position, cursor) {
14776
+ position.cursor = cursor;
14777
+ this.#cursor = cursor;
14778
+ }
14779
+ note(event, connection) {
14780
+ const stop = STOPS[event.type];
14781
+ this.#ending = stop === "continues" ? null : event.type;
14782
+ connection.at(stop);
14783
+ }
14784
+ };
14785
+
14786
+ // src/agents/threads.ts
14787
+ var threadRoute = (threadId) => `/api/public/threads/${segment(threadId)}`;
14788
+ var Thread = class {
14789
+ #transport;
14790
+ #runs;
14791
+ id;
14792
+ agent;
14793
+ title;
14794
+ autonomy;
14795
+ activeRun;
14796
+ createdAt;
14797
+ /** Granted tools this key cannot activate; only on the thread `create` returns. */
14798
+ warnings;
14799
+ constructor(transport, record, runs = {}) {
14800
+ this.#transport = transport;
14801
+ this.#runs = runs;
14802
+ this.id = record.id;
14803
+ this.agent = record.agent;
14804
+ this.title = record.title;
14805
+ this.autonomy = Object.freeze({ ...record.autonomy });
14806
+ this.activeRun = record.activeRun ? Object.freeze({ ...record.activeRun }) : null;
14807
+ this.createdAt = record.createdAt;
14808
+ this.warnings = Object.freeze([...record.warnings ?? []]);
14809
+ }
14810
+ /** Start a run on the agent's deployed version (or `version`); refused with 409 `thread_busy` while another run is active. */
14811
+ async send(input, options = {}) {
14812
+ const body = { input, version: options.version, multitask: options.multitask };
14813
+ const run = await this.#transport.json("POST", `${threadRoute(this.id)}/runs`, body);
14814
+ return new AgentRun(this.#transport, run, this.#runs);
14815
+ }
14816
+ /** A run of this thread by id, as it is now. */
14817
+ async run(runId) {
14818
+ const run = await this.#transport.json("GET", `${threadRoute(this.id)}/runs/${segment(runId)}`);
14819
+ return new AgentRun(this.#transport, run, this.#runs);
14820
+ }
14821
+ };
14822
+ var Threads = class {
14823
+ #transport;
14824
+ #runs;
14825
+ constructor(transport, runs = {}) {
14826
+ this.#transport = transport;
14827
+ this.#runs = runs;
14828
+ }
14829
+ /** A thread for a deployed agent; `allowSelfSchedule` or `allowSubagents` set to `true` is refused (400 `autonomy_unsupported`). */
14830
+ async create(options) {
14831
+ const agent = typeof options.agent === "string" ? options.agent : options.agent.name;
14832
+ const body = { agent, title: options.title, autonomy: options.autonomy };
14833
+ const record = await this.#transport.json("POST", "/api/public/threads", body);
14834
+ return new Thread(this.#transport, record, this.#runs);
14835
+ }
14836
+ async get(threadId) {
14837
+ const record = await this.#transport.json("GET", `${threadRoute(threadId)}`);
14838
+ return new Thread(this.#transport, record, this.#runs);
14839
+ }
14840
+ };
14841
+
14842
+ // src/agents/gateway.ts
14843
+ var Gateway = class {
14844
+ agents;
14845
+ threads;
14846
+ constructor(options = {}) {
14847
+ const transport = options.transport ?? new PlatformTransport(requirePlatformEndpoint(options));
14848
+ this.threads = new Threads(transport, { clock: options.clock, reconnect: options.reconnect });
14849
+ this.agents = new Agents(transport, this.threads);
14850
+ Object.freeze(this);
14851
+ }
14852
+ };
14853
+
14854
+ // src/agents/tools.ts
14855
+ var AGENT_MODELS = ["claude-opus-5", "claude-sonnet-5"];
14856
+ var AGENT_EFFORTS = ["low", "medium", "high", "xhigh"];
14857
+ var TOOL_SERVERS = {
14858
+ docs: ["search_docs"],
14859
+ drive: ["get_drive_file", "list_drive_files", "save_drive_file"],
14860
+ sandbox: [
14861
+ "copy_file",
14862
+ "execute_python",
14863
+ "grep_files",
14864
+ "ingest_sessions_to_sandbox",
14865
+ "list_files",
14866
+ "query_json",
14867
+ "read_file",
14868
+ "run_bash",
14869
+ "run_gateway_cli",
14870
+ "write_file"
14871
+ ],
14872
+ web: ["download_url_to_drive", "fetch_url"]
14873
+ };
14874
+ var grant = (server) => (options = {}) => options.only ? { server, only: [...options.only] } : { server };
14875
+ var tools = Object.freeze({
14876
+ sandbox: grant("sandbox"),
14877
+ drive: grant("drive"),
14878
+ web: grant("web"),
14879
+ docs: grant("docs")
14880
+ });
14881
+
12737
14882
  // src/files/index.ts
12738
14883
  var files_exports = {};
12739
14884
  __export(files_exports, {
@@ -13098,7 +15243,7 @@ __export(hooks_exports, {
13098
15243
  normalizeEvent: () => normalizeEvent,
13099
15244
  pageTitle: () => pageTitle,
13100
15245
  parseHookConfig: () => parseHookConfig,
13101
- parseJson: () => parseJson2,
15246
+ parseJson: () => parseJson3,
13102
15247
  parseMatcher: () => parseMatcher,
13103
15248
  parseRegex: () => parseRegex,
13104
15249
  parseStdout: () => parseStdout,
@@ -13576,7 +15721,7 @@ function emailPairs(real, fake) {
13576
15721
  }
13577
15722
  function phoneForms(number) {
13578
15723
  const digits = number.replace(/\D/g, "");
13579
- const forms = [
15724
+ const forms2 = [
13580
15725
  ["raw", number],
13581
15726
  ["digits", digits],
13582
15727
  ["plus", `+${digits}`]
@@ -13587,7 +15732,7 @@ function phoneForms(number) {
13587
15732
  const c = digits.slice(-4);
13588
15733
  const country = digits.slice(0, -10);
13589
15734
  const prefix = country ? `+${country} ` : "";
13590
- forms.push(
15735
+ forms2.push(
13591
15736
  ["spaced", `${prefix}${a} ${b} ${c}`],
13592
15737
  ["dashed", `${prefix}${a}-${b}-${c}`],
13593
15738
  ["paren", `${prefix}(${a}) ${b}-${c}`],
@@ -13597,7 +15742,7 @@ function phoneForms(number) {
13597
15742
  ["local_paren", `(${a}) ${b}-${c}`]
13598
15743
  );
13599
15744
  }
13600
- return forms;
15745
+ return forms2;
13601
15746
  }
13602
15747
  function phonePairs(real, fake) {
13603
15748
  const fakeForms = new Map(phoneForms(fake));
@@ -14329,172 +16474,382 @@ function mirrorHandle(handle, identity) {
14329
16474
  import * as fs14 from "fs";
14330
16475
 
14331
16476
  // src/cli/platform/worldData/toml.ts
16477
+ var TomlDateTime = class {
16478
+ constructor(text2) {
16479
+ this.text = text2;
16480
+ }
16481
+ text;
16482
+ toString() {
16483
+ return this.text;
16484
+ }
16485
+ };
14332
16486
  var TomlError = class extends Error {
14333
16487
  };
14334
16488
  function parseToml(text2) {
14335
- const root = {};
14336
- let current = root;
14337
- const lines = joinContinuations(text2);
14338
- for (const [number, rawLine] of lines.entries()) {
14339
- const line = stripComment(rawLine).trim();
14340
- if (!line) continue;
14341
- const arrayTable = /^\[\[\s*([^\]]+?)\s*\]\]$/.exec(line);
14342
- if (arrayTable) {
14343
- const parent = tableAt(root, keyPath(arrayTable[1]).slice(0, -1));
14344
- const name = keyPath(arrayTable[1]).at(-1);
14345
- const list = parent[name] ??= [];
14346
- if (!Array.isArray(list)) throw new TomlError(`line ${number + 1}: ${name} is not an array of tables`);
14347
- current = {};
14348
- list.push(current);
14349
- continue;
14350
- }
14351
- const table2 = /^\[\s*([^\]]+?)\s*\]$/.exec(line);
14352
- if (table2) {
14353
- current = tableAt(root, keyPath(table2[1]));
14354
- continue;
16489
+ return new TomlReader(text2).read();
16490
+ }
16491
+ var BARE_KEY = /^[A-Za-z0-9_-]+$/;
16492
+ var CONTROL = /[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/;
16493
+ var COMMENT_CONTROL = /[\x00-\x08\x0a-\x1f\x7f]/;
16494
+ var DEC_INT = /^[+-]?(?:0|[1-9](?:_?\d)*)$/;
16495
+ var RADIX_INT = [
16496
+ [/^0x[0-9A-Fa-f](?:_?[0-9A-Fa-f])*$/, 16],
16497
+ [/^0o[0-7](?:_?[0-7])*$/, 8],
16498
+ [/^0b[01](?:_?[01])*$/, 2]
16499
+ ];
16500
+ var FLOAT = /^[+-]?(?:0|[1-9](?:_?\d)*)(?:\.\d(?:_?\d)*)?(?:[eE][+-]?\d(?:_?\d)*)?$/;
16501
+ var SPECIAL_FLOAT = /^([+-]?)(inf|nan)$/;
16502
+ var DATE_TIME = /^(\d{4})-(\d{2})-(\d{2})(?:[Tt ](\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:[Zz]|[+-](\d{2}):(\d{2}))?)?/;
16503
+ var LOCAL_TIME = /^(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?/;
16504
+ var INLINE = /* @__PURE__ */ new WeakSet();
16505
+ var newTable = () => /* @__PURE__ */ Object.create(null);
16506
+ var own = (table2, key2) => Object.prototype.hasOwnProperty.call(table2, key2) ? table2[key2] : void 0;
16507
+ var isTomlTable = (value) => value !== void 0 && typeof value === "object" && Object.getPrototypeOf(value) === null;
16508
+ var stripBlank = (text2) => text2.replace(/^[ \t]+|[ \t]+$/g, "");
16509
+ var TomlReader = class {
16510
+ constructor(text2) {
16511
+ this.text = text2;
16512
+ }
16513
+ text;
16514
+ root = newTable();
16515
+ current = this.root;
16516
+ defined = /* @__PURE__ */ new WeakSet();
16517
+ byHeader = /* @__PURE__ */ new WeakSet();
16518
+ byDottedKey = /* @__PURE__ */ new WeakSet();
16519
+ tableArrays = /* @__PURE__ */ new WeakSet();
16520
+ read() {
16521
+ for (const { text: text2, line } of logicalLines(this.text)) this.statement(stripBlank(text2), line);
16522
+ return this.root;
16523
+ }
16524
+ statement(text2, line) {
16525
+ if (!text2) return;
16526
+ const arrayTable = /^\[\[[ \t]*(.+?)[ \t]*\]\]$/.exec(text2);
16527
+ if (arrayTable) return this.arrayTable(keyPath(arrayTable[1], line), line);
16528
+ const header = /^\[[ \t]*(.+?)[ \t]*\]$/.exec(text2);
16529
+ if (header) return this.header(keyPath(header[1], line), line);
16530
+ const eq = outsideQuotes(text2, "=");
16531
+ if (eq === -1) throw new TomlError(`line ${line}: expected key = value`);
16532
+ const path17 = keyPath(text2.slice(0, eq), line);
16533
+ const [value, rest] = readValue(text2.slice(eq + 1), line);
16534
+ if (stripBlank(rest)) throw new TomlError(`line ${line}: unexpected text after value`);
16535
+ assign(this.descend(this.current, path17.slice(0, -1), line, "key"), path17, value, line);
16536
+ }
16537
+ header(path17, line) {
16538
+ const parent = this.descend(this.root, path17.slice(0, -1), line, "header");
16539
+ const name = path17.at(-1);
16540
+ const table2 = own(parent, name) ?? newTable();
16541
+ const fresh = isTomlTable(table2) && !INLINE.has(table2) && !this.byDottedKey.has(table2) && !this.defined.has(table2);
16542
+ if (!fresh) throw new TomlError(`line ${line}: [${path17.join(".")}] is defined twice`);
16543
+ parent[name] = table2;
16544
+ this.open(table2);
16545
+ }
16546
+ arrayTable(path17, line) {
16547
+ const parent = this.descend(this.root, path17.slice(0, -1), line, "header");
16548
+ const name = path17.at(-1);
16549
+ const existing = own(parent, name);
16550
+ if (existing !== void 0 && !(Array.isArray(existing) && this.tableArrays.has(existing)))
16551
+ throw new TomlError(`line ${line}: ${path17.join(".")} is not an array of tables`);
16552
+ const list2 = existing ?? [];
16553
+ this.tableArrays.add(list2);
16554
+ parent[name] = list2;
16555
+ const table2 = newTable();
16556
+ list2.push(table2);
16557
+ this.open(table2);
16558
+ }
16559
+ open(table2) {
16560
+ this.defined.add(table2);
16561
+ this.byHeader.add(table2);
16562
+ this.current = table2;
16563
+ }
16564
+ descend(from, parts2, line, via) {
16565
+ let node = from;
16566
+ for (const part of parts2) {
16567
+ const next = own(node, part);
16568
+ node = next === void 0 ? this.make(node, part, via) : this.enter(next, part, line, via);
14355
16569
  }
14356
- const eq = line.indexOf("=");
14357
- if (eq === -1) throw new TomlError(`line ${number + 1}: expected key = value`);
14358
- const key2 = unquoteKey(line.slice(0, eq).trim());
14359
- const [value, rest] = readValue(line.slice(eq + 1).trim(), number + 1);
14360
- if (rest.trim()) throw new TomlError(`line ${number + 1}: unexpected text after value`);
14361
- current[key2] = value;
16570
+ return node;
14362
16571
  }
14363
- return root;
14364
- }
14365
- function keyPath(header) {
14366
- return header.split(".").map((part) => unquoteKey(part.trim()));
14367
- }
14368
- function unquoteKey(key2) {
14369
- if (key2.startsWith('"') && key2.endsWith('"') || key2.startsWith("'") && key2.endsWith("'")) return key2.slice(1, -1);
14370
- return key2;
16572
+ make(parent, part, via) {
16573
+ const table2 = newTable();
16574
+ (via === "header" ? this.byHeader : this.byDottedKey).add(table2);
16575
+ parent[part] = table2;
16576
+ return table2;
16577
+ }
16578
+ enter(value, part, line, via) {
16579
+ const target = via === "header" && Array.isArray(value) && this.tableArrays.has(value) ? value.at(-1) : value;
16580
+ const open = isTomlTable(target) && !INLINE.has(target) && !(via === "key" && this.defined.has(target));
16581
+ if (!open) throw new TomlError(`line ${line}: ${part} is already defined and cannot be extended here`);
16582
+ if (via === "key") this.byDottedKey.add(target);
16583
+ return target;
16584
+ }
16585
+ };
16586
+ function assign(table2, path17, value, line) {
16587
+ const key2 = path17.at(-1);
16588
+ if (own(table2, key2) !== void 0) throw new TomlError(`line ${line}: key ${path17.join(".")} is defined twice`);
16589
+ table2[key2] = value;
14371
16590
  }
14372
- function tableAt(root, parts2) {
14373
- let node = root;
16591
+ function inlineAt(table2, parts2, line) {
16592
+ let node = table2;
14374
16593
  for (const part of parts2) {
14375
- const next = node[part] ??= {};
14376
- if (Array.isArray(next)) {
14377
- const last = next[next.length - 1];
14378
- if (!last || typeof last !== "object" || Array.isArray(last)) throw new TomlError(`${part} is not a table`);
14379
- node = last;
14380
- } else if (typeof next !== "object") throw new TomlError(`${part} is not a table`);
14381
- else node = next;
16594
+ const next = own(node, part) ?? newTable();
16595
+ if (!isTomlTable(next) || INLINE.has(next))
16596
+ throw new TomlError(`line ${line}: ${part} is already defined and cannot be extended here`);
16597
+ node[part] = next;
16598
+ node = next;
14382
16599
  }
14383
16600
  return node;
14384
16601
  }
14385
- function joinContinuations(text2) {
14386
- const out = [];
14387
- let pending = "";
14388
- let depth = 0;
14389
- for (const physical of text2.split(/\r?\n/)) {
14390
- const raw = stripComment(physical);
14391
- const line = pending ? pending + "\n" + raw : raw;
14392
- depth = bracketDepth(line);
14393
- if (depth > 0) {
14394
- pending = line;
14395
- continue;
14396
- }
14397
- pending = "";
14398
- out.push(line);
16602
+ function keyPath(text2, line) {
16603
+ const parts2 = [];
16604
+ let rest = text2;
16605
+ for (; ; ) {
16606
+ const dot = outsideQuotes(rest, ".");
16607
+ parts2.push(readKey(stripBlank(dot === -1 ? rest : rest.slice(0, dot)), line));
16608
+ if (dot === -1) return parts2;
16609
+ rest = rest.slice(dot + 1);
14399
16610
  }
14400
- if (pending) out.push(pending);
14401
- return out;
14402
16611
  }
14403
- function bracketDepth(line) {
14404
- let depth = 0;
14405
- let quote = null;
14406
- for (let i = 0; i < line.length; i++) {
14407
- const c = line[i];
14408
- if (quote) {
14409
- if (c === "\\" && quote === '"') i++;
14410
- else if (c === quote) quote = null;
14411
- continue;
14412
- }
14413
- if (c === '"' || c === "'") quote = c;
14414
- else if (c === "[" || c === "{") depth++;
14415
- else if (c === "]" || c === "}") depth--;
14416
- }
14417
- return depth;
16612
+ function readKey(part, line) {
16613
+ const quote = openingQuote(part, 0);
16614
+ if (quote === null && BARE_KEY.test(part)) return part;
16615
+ const read = quote?.length === 1 ? readString(part, line) : null;
16616
+ if (!read || read[1] !== "") throw new TomlError(`line ${line}: \`${part}\` is not a key; quote it`);
16617
+ return read[0];
14418
16618
  }
14419
- function stripComment(line) {
16619
+ function outsideQuotes(text2, char) {
14420
16620
  let quote = null;
14421
- for (let i = 0; i < line.length; i++) {
14422
- const c = line[i];
16621
+ for (let i = 0; i < text2.length; i++) {
16622
+ const c = text2[i];
14423
16623
  if (quote) {
14424
16624
  if (c === "\\" && quote === '"') i++;
14425
16625
  else if (c === quote) quote = null;
14426
16626
  continue;
14427
16627
  }
14428
16628
  if (c === '"' || c === "'") quote = c;
14429
- else if (c === "#") return line.slice(0, i);
16629
+ else if (c === char) return i;
16630
+ }
16631
+ return -1;
16632
+ }
16633
+ function openingQuote(text2, i) {
16634
+ const c = text2[i];
16635
+ if (c !== '"' && c !== "'") return null;
16636
+ return text2.startsWith(c.repeat(3), i) ? c.repeat(3) : c;
16637
+ }
16638
+ function quoteRun(text2, i, quote, line) {
16639
+ let run = 0;
16640
+ while (text2[i + run] === quote) run++;
16641
+ if (run > 5) throw new TomlError(`line ${line}: too many quotes close a multi-line string`);
16642
+ return run;
16643
+ }
16644
+ var LogicalLines = class {
16645
+ constructor(text2) {
16646
+ this.text = text2;
16647
+ }
16648
+ text;
16649
+ out = [];
16650
+ brackets = [];
16651
+ buffer = "";
16652
+ start = 1;
16653
+ line = 1;
16654
+ quote = null;
16655
+ i = 0;
16656
+ split() {
16657
+ if (this.text.startsWith("\uFEFF")) throw new TomlError("line 1: a byte order mark is not TOML");
16658
+ for (; this.i < this.text.length; this.i++) this.step(this.text[this.i]);
16659
+ if (this.quote) throw new TomlError(`line ${this.start}: unterminated string`);
16660
+ if (this.brackets.length > 0) throw new TomlError(`line ${this.start}: a bracket or brace is never closed`);
16661
+ this.out.push({ text: this.buffer, line: this.start });
16662
+ return this.out;
16663
+ }
16664
+ step(c) {
16665
+ if (c === "\n") this.line++;
16666
+ if (this.quote) return this.inString(c, this.quote);
16667
+ if (c === "#") return this.skipComment();
16668
+ const opened = openingQuote(this.text, this.i);
16669
+ if (opened) return this.openString(opened);
16670
+ this.outside(c);
16671
+ }
16672
+ inString(c, quote) {
16673
+ if (c === "\n" && quote.length === 1) throw new TomlError(`line ${this.line - 1}: unterminated string`);
16674
+ if (c === "\\" && quote.startsWith('"')) return this.escape();
16675
+ if (this.text.startsWith(quote, this.i)) return this.closeString(quote);
16676
+ this.buffer += c;
16677
+ }
16678
+ escape() {
16679
+ const next = this.text[this.i + 1] ?? "";
16680
+ this.buffer += "\\" + next;
16681
+ if (next === "\n") this.line++;
16682
+ this.i++;
16683
+ }
16684
+ openString(opened) {
16685
+ this.quote = opened;
16686
+ this.buffer += opened;
16687
+ this.i += opened.length - 1;
16688
+ }
16689
+ closeString(quote) {
16690
+ const run = quote.length === 3 ? quoteRun(this.text, this.i, quote[0], this.line) : 1;
16691
+ this.buffer += this.text.slice(this.i, this.i + run);
16692
+ this.i += run - 1;
16693
+ this.quote = null;
16694
+ }
16695
+ skipComment() {
16696
+ for (; this.i + 1 < this.text.length && this.text[this.i + 1] !== "\n"; this.i++)
16697
+ this.commentCharacter(this.text[this.i + 1]);
16698
+ }
16699
+ commentCharacter(c) {
16700
+ const lineEnd = c === "\r" && this.text[this.i + 2] === "\n";
16701
+ if (!lineEnd && COMMENT_CONTROL.test(c))
16702
+ throw new TomlError(`line ${this.line}: a comment holds a control character`);
16703
+ }
16704
+ outside(c) {
16705
+ if (c === "[" || c === "{") this.brackets.push(c);
16706
+ if (c === "]" || c === "}") this.brackets.pop();
16707
+ if (c === "\n" && this.brackets.at(-1) === "{")
16708
+ throw new TomlError(`line ${this.line - 1}: an inline table must be on one line`);
16709
+ if (c === "\n" && this.brackets.length === 0) return this.endLine();
16710
+ this.buffer += c;
16711
+ }
16712
+ endLine() {
16713
+ this.out.push({ text: this.buffer.replace(/\r$/, ""), line: this.start });
16714
+ this.buffer = "";
16715
+ this.start = this.line;
14430
16716
  }
14431
- return line;
14432
- }
14433
- function readValue(text2, line) {
14434
- const s = text2.trimStart();
14435
- if (s.startsWith('"')) {
14436
- let out = "";
14437
- for (let i = 1; i < s.length; i++) {
14438
- const c = s[i];
14439
- if (c === "\\") {
14440
- const e = s[++i];
14441
- const map = { n: "\n", t: " ", r: "\r", '"': '"', "\\": "\\", b: "\b", f: "\f" };
14442
- if (e === "u" || e === "U") {
14443
- const width = e === "u" ? 4 : 8;
14444
- out += String.fromCodePoint(parseInt(s.slice(i + 1, i + 1 + width), 16));
14445
- i += width;
14446
- } else if (e !== void 0 && e in map) out += map[e];
14447
- else throw new TomlError(`line ${line}: unsupported escape \\${e ?? ""}`);
14448
- continue;
14449
- }
14450
- if (c === '"') return [out, s.slice(i + 1)];
16717
+ };
16718
+ function logicalLines(text2) {
16719
+ return new LogicalLines(text2).split();
16720
+ }
16721
+ var ESCAPES = { n: "\n", t: " ", r: "\r", '"': '"', "\\": "\\", b: "\b", f: "\f" };
16722
+ function unicodeEscape(body, at, width, line) {
16723
+ const digits = body.slice(at, at + width);
16724
+ const code = /^[0-9A-Fa-f]+$/.test(digits) && digits.length === width ? parseInt(digits, 16) : -1;
16725
+ const scalar = code >= 0 && code <= 1114111 && (code < 55296 || code > 57343);
16726
+ if (!scalar) throw new TomlError(`line ${line}: \\${width === 4 ? "u" : "U"}${digits} is not a Unicode scalar value`);
16727
+ return String.fromCodePoint(code);
16728
+ }
16729
+ function decodeBasic(body, line, multiline) {
16730
+ let out = "";
16731
+ for (let i = 0; i < body.length; i++) {
16732
+ const c = body[i];
16733
+ if (c !== "\\") {
14451
16734
  out += c;
16735
+ continue;
14452
16736
  }
14453
- throw new TomlError(`line ${line}: unterminated string`);
14454
- }
14455
- if (s.startsWith("'")) {
14456
- const end = s.indexOf("'", 1);
14457
- if (end === -1) throw new TomlError(`line ${line}: unterminated string`);
14458
- return [s.slice(1, end), s.slice(end + 1)];
14459
- }
14460
- if (s.startsWith("[")) {
14461
- const items = [];
14462
- let rest2 = s.slice(1);
14463
- for (; ; ) {
14464
- rest2 = rest2.replace(/^[\s\n]+/, "");
14465
- if (rest2.startsWith("]")) return [items, rest2.slice(1)];
14466
- const [item, after] = readValue(rest2, line);
14467
- items.push(item);
14468
- rest2 = after.replace(/^[\s\n]+/, "");
14469
- if (rest2.startsWith(",")) rest2 = rest2.slice(1);
14470
- else if (!rest2.startsWith("]")) throw new TomlError(`line ${line}: expected , or ] in array`);
16737
+ const e = body[++i];
16738
+ if (multiline && /^[ \t]*\r?\n/.test(body.slice(i))) {
16739
+ while (i + 1 < body.length && /[ \t\r\n]/.test(body[i + 1])) i++;
16740
+ continue;
14471
16741
  }
16742
+ if (e === "u" || e === "U") {
16743
+ const width = e === "u" ? 4 : 8;
16744
+ out += unicodeEscape(body, i + 1, width, line);
16745
+ i += width;
16746
+ } else if (e !== void 0 && e in ESCAPES) out += ESCAPES[e];
16747
+ else throw new TomlError(`line ${line}: unsupported escape \\${e ?? ""}`);
14472
16748
  }
14473
- if (s.startsWith("{")) {
14474
- const table2 = {};
14475
- let rest2 = s.slice(1);
14476
- for (; ; ) {
14477
- rest2 = rest2.replace(/^[\s\n]+/, "");
14478
- if (rest2.startsWith("}")) return [table2, rest2.slice(1)];
14479
- const eq = rest2.indexOf("=");
14480
- if (eq === -1) throw new TomlError(`line ${line}: expected key = value in inline table`);
14481
- const key2 = unquoteKey(rest2.slice(0, eq).trim());
14482
- const [value, after] = readValue(rest2.slice(eq + 1), line);
14483
- table2[key2] = value;
14484
- rest2 = after.replace(/^[\s\n]+/, "");
14485
- if (rest2.startsWith(",")) rest2 = rest2.slice(1);
14486
- else if (!rest2.startsWith("}")) throw new TomlError(`line ${line}: expected , or } in inline table`);
16749
+ return out;
16750
+ }
16751
+ function checkControls(body, line, multiline) {
16752
+ const broken = CONTROL.test(body) || (multiline ? /\r(?!\n)/.test(body) : /[\r\n]/.test(body));
16753
+ if (broken) throw new TomlError(`line ${line}: a string holds a control character`);
16754
+ }
16755
+ function readString(s, line) {
16756
+ const quote = openingQuote(s, 0);
16757
+ if (!quote) return null;
16758
+ let end = quote.length;
16759
+ for (; end < s.length; end++) {
16760
+ if (quote.startsWith('"') && s[end] === "\\") {
16761
+ end++;
16762
+ continue;
14487
16763
  }
16764
+ if (s.startsWith(quote, end)) break;
16765
+ }
16766
+ if (end >= s.length) throw new TomlError(`line ${line}: unterminated string`);
16767
+ if (quote.length === 3) end += quoteRun(s, end, quote[0], line) - 3;
16768
+ const raw = s.slice(quote.length, end);
16769
+ const multiline = quote.length === 3;
16770
+ const body = multiline ? raw.replace(/^\r?\n/, "") : raw;
16771
+ checkControls(body, line, multiline);
16772
+ const text2 = quote.startsWith('"') ? decodeBasic(body, line, multiline) : body;
16773
+ return [text2, s.slice(end + quote.length)];
16774
+ }
16775
+ function readArray(s, line) {
16776
+ const items = [];
16777
+ let rest = s.slice(1);
16778
+ for (; ; ) {
16779
+ rest = rest.replace(/^[ \t\r\n]+/, "");
16780
+ if (rest.startsWith("]")) return [items, rest.slice(1)];
16781
+ const [item, after] = readValue(rest, line);
16782
+ items.push(item);
16783
+ rest = after.replace(/^[ \t\r\n]+/, "");
16784
+ if (rest.startsWith(",")) rest = rest.slice(1);
16785
+ else if (!rest.startsWith("]")) throw new TomlError(`line ${line}: expected , or ] in array`);
16786
+ }
16787
+ }
16788
+ function readInlineTable(s, line) {
16789
+ const table2 = newTable();
16790
+ let rest = s.slice(1).replace(/^[ \t]+/, "");
16791
+ if (rest.startsWith("}")) {
16792
+ INLINE.add(table2);
16793
+ return [table2, rest.slice(1)];
14488
16794
  }
14489
- const scalar = /^([^,\]}\s]+)/.exec(s);
16795
+ for (; ; ) {
16796
+ const eq = outsideQuotes(rest, "=");
16797
+ if (eq === -1) throw new TomlError(`line ${line}: expected key = value in inline table`);
16798
+ const path17 = keyPath(rest.slice(0, eq), line);
16799
+ const [value, after] = readValue(rest.slice(eq + 1), line);
16800
+ assign(inlineAt(table2, path17.slice(0, -1), line), path17, value, line);
16801
+ rest = after.replace(/^[ \t]+/, "");
16802
+ if (rest.startsWith("}")) {
16803
+ INLINE.add(table2);
16804
+ return [table2, rest.slice(1)];
16805
+ }
16806
+ if (!rest.startsWith(",")) throw new TomlError(`line ${line}: expected , or } in inline table`);
16807
+ rest = rest.slice(1).replace(/^[ \t]+/, "");
16808
+ if (rest.startsWith("}")) throw new TomlError(`line ${line}: an inline table takes no trailing comma`);
16809
+ }
16810
+ }
16811
+ function inRange(value, low, high) {
16812
+ return value === void 0 || Number(value) >= low && Number(value) <= high;
16813
+ }
16814
+ function readDateTime(s, line) {
16815
+ const full = DATE_TIME.exec(s);
16816
+ const time = full ? null : LOCAL_TIME.exec(s);
16817
+ const match = full ?? time;
16818
+ if (!match) return null;
16819
+ const [y, mo, d, h, mi, se, oh, om] = full ? full.slice(1) : [void 0, void 0, void 0, ...time.slice(1)];
16820
+ const day = y === void 0 ? null : new Date(Date.UTC(Number(y), Number(mo) - 1, Number(d)));
16821
+ const dateOk = day === null || day.getUTCMonth() === Number(mo) - 1 && day.getUTCDate() === Number(d);
16822
+ const timeOk = inRange(h, 0, 23) && inRange(mi, 0, 59) && inRange(se, 0, 59) && inRange(oh, 0, 23) && inRange(om, 0, 59);
16823
+ if (!dateOk || !timeOk) throw new TomlError(`line ${line}: ${match[0]} is not a valid date or time`);
16824
+ return [new TomlDateTime(match[0]), s.slice(match[0].length)];
16825
+ }
16826
+ function readNumber(token) {
16827
+ const plain = token.replace(/_/g, "");
16828
+ if (DEC_INT.test(token)) return Number(plain);
16829
+ for (const [pattern, radix] of RADIX_INT) if (pattern.test(token)) return parseInt(plain.slice(2), radix);
16830
+ if (FLOAT.test(token) && /[.eE]/.test(token)) return Number(plain);
16831
+ const special = SPECIAL_FLOAT.exec(token);
16832
+ if (!special) return null;
16833
+ if (special[2] === "nan") return NaN;
16834
+ return special[1] === "-" ? -Infinity : Infinity;
16835
+ }
16836
+ function readValue(text2, line) {
16837
+ const s = text2.replace(/^[ \t]+/, "");
16838
+ const string = readString(s, line);
16839
+ if (string) return string;
16840
+ if (s.startsWith("[")) return readArray(s, line);
16841
+ if (s.startsWith("{")) return readInlineTable(s, line);
16842
+ const date = readDateTime(s, line);
16843
+ if (date) return date;
16844
+ const scalar = /^([^,\]}\s#]+)/.exec(s);
14490
16845
  if (!scalar) throw new TomlError(`line ${line}: expected a value`);
14491
16846
  const token = scalar[1];
14492
16847
  const rest = s.slice(token.length);
14493
16848
  if (token === "true") return [true, rest];
14494
16849
  if (token === "false") return [false, rest];
14495
- if (/^[+-]?\d[\d_]*$/.test(token)) return [Number(token.replace(/_/g, "")), rest];
14496
- if (/^[+-]?(\d[\d_]*)?\.?\d[\d_]*([eE][+-]?\d+)?$/.test(token)) return [Number(token.replace(/_/g, "")), rest];
14497
- throw new TomlError(`line ${line}: unsupported value ${token}`);
16850
+ const number = readNumber(token);
16851
+ if (number === null) throw new TomlError(`line ${line}: unsupported value ${token}`);
16852
+ return [number, rest];
14498
16853
  }
14499
16854
 
14500
16855
  // src/hooks/events.ts
@@ -14907,15 +17262,15 @@ function parseLive(raw, toolsRaw) {
14907
17262
  );
14908
17263
  if (!isObject4(toolsRaw))
14909
17264
  throw new HookConfigError("`tools` must be a table of [tools.<name>]");
14910
- const tools = {};
17265
+ const tools2 = {};
14911
17266
  for (const [name, spec] of Object.entries(toolsRaw))
14912
- tools[name] = parseTool(name, spec, allowed);
17267
+ tools2[name] = parseTool(name, spec, allowed);
14913
17268
  return {
14914
17269
  ...typeof raw.record === "string" && raw.record ? { record: raw.record } : {},
14915
17270
  ...typeof raw.replay === "string" && raw.replay ? { replay: raw.replay } : {},
14916
17271
  allowedEnv: allowed,
14917
17272
  timeout,
14918
- tools
17273
+ tools: tools2
14919
17274
  };
14920
17275
  }
14921
17276
  function parseTool(name, raw, allowedEnv) {
@@ -15197,7 +17552,7 @@ function loadHookConfig(file) {
15197
17552
  }
15198
17553
  return parseHookConfig(data, file);
15199
17554
  }
15200
- var isObject4 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
17555
+ var isObject4 = (v) => typeof v === "object" && v !== null && [null, Object.prototype].includes(Object.getPrototypeOf(v));
15201
17556
  function parseHookConfig(data, source) {
15202
17557
  const where = source ?? "config";
15203
17558
  if (!isObject4(data))
@@ -15219,12 +17574,12 @@ function parseHookConfig(data, source) {
15219
17574
  throw new HookConfigError(
15220
17575
  `hooks.${rawEvent}: unknown event; expected one of ${EVENTS.join(", ")} (or PreToolUse, PostToolUse, Stop)`
15221
17576
  );
15222
- const list = isObject4(rawRules) ? [rawRules] : rawRules;
15223
- if (!Array.isArray(list))
17577
+ const list2 = isObject4(rawRules) ? [rawRules] : rawRules;
17578
+ if (!Array.isArray(list2))
15224
17579
  throw new HookConfigError(
15225
17580
  `hooks.${rawEvent}: expected an array of rules ([[hooks.${rawEvent}]])`
15226
17581
  );
15227
- list.forEach(
17582
+ list2.forEach(
15228
17583
  (raw, index2) => rules.push(parseRule(event, raw, `hooks.${rawEvent}[${index2}]`))
15229
17584
  );
15230
17585
  }
@@ -15344,12 +17699,12 @@ function parseRule(event, raw, position) {
15344
17699
  );
15345
17700
  }
15346
17701
  const handlersRaw = raw.handlers ?? raw.hooks;
15347
- const list = isObject4(handlersRaw) ? [handlersRaw] : handlersRaw;
15348
- if (!Array.isArray(list) || !list.length)
17702
+ const list2 = isObject4(handlersRaw) ? [handlersRaw] : handlersRaw;
17703
+ if (!Array.isArray(list2) || !list2.length)
15349
17704
  throw new HookConfigError(
15350
17705
  `${position}.handlers: expected a non-empty array of handler tables`
15351
17706
  );
15352
- const handlers = list.map(
17707
+ const handlers = list2.map(
15353
17708
  (h, i) => parseHandler(event, h, `${position}.handlers[${i}]`)
15354
17709
  );
15355
17710
  const rewriters = handlers.filter(isRewriter);
@@ -16209,8 +18564,8 @@ var pyQuote2 = (value) => encodeURIComponent(value).replace(
16209
18564
  /[!'()*]/g,
16210
18565
  (c) => "%" + c.charCodeAt(0).toString(16).toUpperCase()
16211
18566
  );
16212
- function jsonPath(node, pathText) {
16213
- const steps = pathText.trim().split(/\.|(?=\[)/).filter((s) => s && s !== "$");
18567
+ function jsonPath(node, pathText2) {
18568
+ const steps = pathText2.trim().split(/\.|(?=\[)/).filter((s) => s && s !== "$");
16214
18569
  let current = node;
16215
18570
  for (const step of steps) {
16216
18571
  const index2 = /^\[(\*|\d+)\]$/.exec(step);
@@ -16316,7 +18671,7 @@ function mapFields(items, fields, stripHtml) {
16316
18671
  );
16317
18672
  });
16318
18673
  }
16319
- function parseJson2(body, options) {
18674
+ function parseJson3(body, options) {
16320
18675
  let data;
16321
18676
  try {
16322
18677
  data = JSON.parse(body);
@@ -16484,7 +18839,7 @@ var HttpTool = class _HttpTool {
16484
18839
  }
16485
18840
  this.checkFailIf(response.status, body, url);
16486
18841
  if (o.parse === "json")
16487
- return applyLimit(parseJson2(body, o), o.limit, values);
18842
+ return applyLimit(parseJson3(body, o), o.limit, values);
16488
18843
  return applyLimit(parseRegex(body, o), o.limit, values);
16489
18844
  }
16490
18845
  /** `fail_if`: a body that matches is a refusal from the provider (a bot challenge,
@@ -16539,8 +18894,8 @@ function readConnection(root) {
16539
18894
  };
16540
18895
  }
16541
18896
  return {
16542
- slug: connector.slug ?? path15.basename(root),
16543
- baseUrl: (connector.base_url ?? "").replace(/\/+$/, ""),
18897
+ slug: typeof connector.slug === "string" ? connector.slug : path15.basename(root),
18898
+ baseUrl: (typeof connector.base_url === "string" ? connector.base_url : "").replace(/\/+$/, ""),
16544
18899
  scheme: carrier.scheme,
16545
18900
  carrier,
16546
18901
  ...typeof auth.secret_env === "string" ? { secretEnv: auth.secret_env } : {},
@@ -16641,7 +18996,7 @@ var ConnectorTool = class {
16641
18996
  throw new TypeError(
16642
18997
  `${this.spec.name}: missing path argument(s) ${missing.join(", ")}`
16643
18998
  );
16644
- const pathText = this.operation.path.replace(
18999
+ const pathText2 = this.operation.path.replace(
16645
19000
  /\{([A-Za-z_][A-Za-z0-9_]*)\}/g,
16646
19001
  (_, name) => pyQuote2(String(values[name]))
16647
19002
  );
@@ -16657,7 +19012,7 @@ var ConnectorTool = class {
16657
19012
  const carried2 = carryCredential(c.carrier, await this.credential() ?? "");
16658
19013
  Object.assign(headers, carried2.headers);
16659
19014
  for (const [key2, value] of carried2.query) query.append(key2, value);
16660
- const url = c.baseUrl + pathText + (query.toString() ? `?${query.toString()}` : "");
19015
+ const url = c.baseUrl + pathText2 + (query.toString() ? `?${query.toString()}` : "");
16661
19016
  const response = await fetch(url, {
16662
19017
  method: this.operation.method,
16663
19018
  headers,
@@ -16672,7 +19027,7 @@ var ConnectorTool = class {
16672
19027
  }
16673
19028
  if (response.status >= 400)
16674
19029
  throw new LiveToolError(
16675
- `${this.spec.name}: ${c.baseUrl}${pathText} answered HTTP ${response.status}: ${text2.slice(0, 200)}`
19030
+ `${this.spec.name}: ${c.baseUrl}${pathText2} answered HTTP ${response.status}: ${text2.slice(0, 200)}`
16676
19031
  );
16677
19032
  if (this.operation.results && isObject5(body)) {
16678
19033
  const selected = jsonPath(body, this.operation.results);
@@ -16788,12 +19143,12 @@ var LiveTools = class _LiveTools {
16788
19143
  raw = {};
16789
19144
  inside;
16790
19145
  static async create(run, live, baseDir) {
16791
- const tools = new _LiveTools(run, live);
19146
+ const tools2 = new _LiveTools(run, live);
16792
19147
  for (const [name, spec] of Object.entries(live.tools)) {
16793
- tools.built[name] = await buildTool(spec, live, baseDir);
16794
- tools.raw[name] = tools.replay ? tools.replay.tool(spec) : tools.built[name];
19148
+ tools2.built[name] = await buildTool(spec, live, baseDir);
19149
+ tools2.raw[name] = tools2.replay ? tools2.replay.tool(spec) : tools2.built[name];
16795
19150
  }
16796
- return tools;
19151
+ return tools2;
16797
19152
  }
16798
19153
  /** The tools of a hooks file for an existing run: the file read, `{run_id}` /
16799
19154
  * `{run_dir}` in its `[live]` paths filled from the run (`runDir` overrides the
@@ -17483,9 +19838,9 @@ var HookRun = class _HookRun {
17483
19838
  * and is re-thrown (same class with the rewritten message). `additional_context`
17484
19839
  * from the handlers is delivered with the result (see `withContext`).
17485
19840
  */
17486
- wrapTools(tools, opts = {}) {
19841
+ wrapTools(tools2, opts = {}) {
17487
19842
  const wrapped = /* @__PURE__ */ Object.create(null);
17488
- for (const [name, fn] of Object.entries(tools)) {
19843
+ for (const [name, fn] of Object.entries(tools2)) {
17489
19844
  wrapped[name] = async (args = {}) => {
17490
19845
  let real;
17491
19846
  let context4;
@@ -18127,8 +20482,20 @@ var tracing = {
18127
20482
  };
18128
20483
  export {
18129
20484
  ACTION_NAMES,
20485
+ AGENT_EFFORTS,
18130
20486
  AGENT_ID_KEY,
20487
+ AGENT_MODELS,
18131
20488
  ActionTracer,
20489
+ Agent,
20490
+ AgentDefinition,
20491
+ AgentDefinitionError,
20492
+ AgentPatch,
20493
+ AgentRun,
20494
+ AgentThreads,
20495
+ AgentTools,
20496
+ AgentVersionConflictError,
20497
+ AgentVersionNotFoundError,
20498
+ Agents,
18132
20499
  AnthropicComputer,
18133
20500
  AnthropicComputer20251124,
18134
20501
  ApiError,
@@ -18161,9 +20528,11 @@ export {
18161
20528
  EXPERIMENT_ATTRIBUTES,
18162
20529
  EXPLORATORY_TASK,
18163
20530
  EXPLORATORY_TASK_SOURCE,
20531
+ EventStreamError,
18164
20532
  ExperimentClient,
18165
20533
  ExperimentSpanProcessor,
18166
20534
  ExposureLogger,
20535
+ Gateway,
18167
20536
  GatewayContext,
18168
20537
  GatewayContextConflictError,
18169
20538
  GatewayContextError,
@@ -18187,12 +20556,17 @@ export {
18187
20556
  OpenAIComputer,
18188
20557
  OpenAIPreviewComputer,
18189
20558
  PLATFORM_SESSION_HEADER,
20559
+ PLATFORM_STREAM_IDLE_MS,
18190
20560
  PLATFORM_TIMEOUT_DEFAULT_MS,
18191
20561
  PLATFORM_TIMEOUT_ENV,
20562
+ PageObserver,
20563
+ PageState,
20564
+ PageStateError,
18192
20565
  PendingSafetyChecks,
18193
20566
  Persona,
18194
20567
  PersonaError,
18195
20568
  PersonasClient,
20569
+ PlatformStream,
18196
20570
  PlatformTransport,
18197
20571
  PushSlugConflict,
18198
20572
  RECOVER_BUDGET_MS,
@@ -18200,6 +20574,7 @@ export {
18200
20574
  REQUESTS_NOT_RECORDED,
18201
20575
  REQUEST_BODY_CAPTURE_BYTES,
18202
20576
  REQUEST_LOG_PAGE_MAX,
20577
+ ReconnectPolicy,
18203
20578
  ReplayCase,
18204
20579
  ReplayCheck,
18205
20580
  ReplayError,
@@ -18224,6 +20599,7 @@ export {
18224
20599
  SUCCESS_METRIC_NAME_KEY,
18225
20600
  SUCCESS_SIGNAL_KEY,
18226
20601
  SURFACE_KINDS,
20602
+ SYSTEM_CLOCK,
18227
20603
  Score,
18228
20604
  ScoreError,
18229
20605
  ScoresClient,
@@ -18232,13 +20608,18 @@ export {
18232
20608
  SessionLoadError,
18233
20609
  SessionRecording,
18234
20610
  SessionTrace,
20611
+ SseLimits,
20612
+ SseParser,
18235
20613
  StubMissError,
18236
20614
  TOOL_CONTRACT_UNREAD,
20615
+ TOOL_SERVERS,
18237
20616
  TRANSFORMS,
18238
20617
  TaskEditClient,
18239
20618
  TaskGrades,
18240
20619
  TaskRun,
18241
20620
  TaskSessions,
20621
+ Thread,
20622
+ Threads,
18242
20623
  ToolStubRegistry,
18243
20624
  TraceDiff,
18244
20625
  TransportCause,
@@ -18248,6 +20629,7 @@ export {
18248
20629
  VERIFIER_REWARD_PREFIX,
18249
20630
  WHITESPACE,
18250
20631
  WORLD_REQUEST_VIAS,
20632
+ WORLD_WEBHOOK_PAGE_MAX,
18251
20633
  WorldBrowser,
18252
20634
  WorldCallTooLarge,
18253
20635
  WorldEditClient,
@@ -18263,9 +20645,11 @@ export {
18263
20645
  WorldSessionOpenFailed,
18264
20646
  WorldSessionTimeout,
18265
20647
  WorldSet,
20648
+ WorldStateClient,
18266
20649
  WorldSurfaceUnavailable,
18267
20650
  WorldTask,
18268
20651
  WorldToolsUnread,
20652
+ WorldWebhookForwarder,
18269
20653
  WriteTreeFilter,
18270
20654
  addExperimentAttributes,
18271
20655
  aggregateTaskGrade,
@@ -18299,6 +20683,7 @@ export {
18299
20683
  createRef,
18300
20684
  createTask,
18301
20685
  currentTraceId,
20686
+ defineAgent,
18302
20687
  defineTool,
18303
20688
  deleteEnvSecret,
18304
20689
  deleteTask,
@@ -18335,6 +20720,7 @@ export {
18335
20720
  listSessions,
18336
20721
  listTaskSessions,
18337
20722
  listTasks,
20723
+ listWebhooks,
18338
20724
  loadSession,
18339
20725
  localTreeState,
18340
20726
  memory,
@@ -18353,6 +20739,7 @@ export {
18353
20739
  parseTransform,
18354
20740
  parseWorldTaskRefs,
18355
20741
  personas,
20742
+ platformAuthorization,
18356
20743
  platformTimeoutMs,
18357
20744
  playwrightKey,
18358
20745
  preserveForm,
@@ -18389,6 +20776,7 @@ export {
18389
20776
  runWithExperimentContext,
18390
20777
  schemaFromSignature,
18391
20778
  scores,
20779
+ scrubError,
18392
20780
  serializeCallBody,
18393
20781
  sessionObservationFromApi,
18394
20782
  sessionToolObservations,
@@ -18409,6 +20797,7 @@ export {
18409
20797
  taskRunFailure,
18410
20798
  toolCallRecordsIn,
18411
20799
  toolCallsFromObservations,
20800
+ tools,
18412
20801
  traces_exports as traces,
18413
20802
  tracing,
18414
20803
  uiEntryUrl,