@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.js CHANGED
@@ -464,13 +464,77 @@ var init_scores = __esm({
464
464
  }
465
465
  });
466
466
 
467
+ // src/worlds/personalToken.ts
468
+ 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;
469
+ var init_personalToken = __esm({
470
+ "src/worlds/personalToken.ts"() {
471
+ "use strict";
472
+ TOKEN_NOT_PERSONAL = "GATEWAY_TOKEN takes a personal access token: pat_ followed by letters and digits only.";
473
+ TOKEN_NEEDS_PROJECT = "GATEWAY_TOKEN acts in the project GATEWAY_PROJECT_ID names: set it to the official project's id (letters, digits, - and _).";
474
+ TOKEN_NEEDS_HOST = "GATEWAY_TOKEN goes only to the host GATEWAY_HOST names: set GATEWAY_HOST.";
475
+ 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.";
476
+ 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.";
477
+ 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).";
478
+ TOKEN_KEYS_ONLY = "Task-run tracing exports with a project key pair (GATEWAY_PUBLIC_KEY / GATEWAY_SECRET_KEY), not GATEWAY_TOKEN.";
479
+ PERSONAL = /^pat_[A-Za-z0-9]+$/;
480
+ PROJECT = /^[A-Za-z0-9_-]+$/;
481
+ ENV_KEYS = ["GATEWAY_PUBLIC_KEY", "GATEWAY_SECRET_KEY", "GATEWAY_API_KEY"];
482
+ PersonalTokenRefused = class extends Error {
483
+ };
484
+ bare = (host) => host.replace(/\/+$/, "");
485
+ PersonalToken = class _PersonalToken {
486
+ constructor(value, project, host) {
487
+ this.value = value;
488
+ this.project = project;
489
+ this.host = host;
490
+ }
491
+ value;
492
+ project;
493
+ host;
494
+ static fromEnv(env, request = {}) {
495
+ const value = env.GATEWAY_TOKEN;
496
+ if (!value) return null;
497
+ if (request.keys || ENV_KEYS.some((name) => env[name])) throw new PersonalTokenRefused(TOKEN_BESIDE_KEYS);
498
+ const host = bare(env.GATEWAY_HOST ?? "");
499
+ if (!host) throw new PersonalTokenRefused(TOKEN_NEEDS_HOST);
500
+ if (request.host && bare(request.host) !== host) throw new PersonalTokenRefused(TOKEN_OTHER_HOST);
501
+ if (!PERSONAL.test(value)) throw new PersonalTokenRefused(TOKEN_NOT_PERSONAL);
502
+ const project = env.GATEWAY_PROJECT_ID ?? "";
503
+ if (!PROJECT.test(project)) throw new PersonalTokenRefused(TOKEN_NEEDS_PROJECT);
504
+ return new _PersonalToken(value, project, host);
505
+ }
506
+ toJSON() {
507
+ return { project: this.project, host: this.host };
508
+ }
509
+ [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
510
+ return `PersonalToken { project: ${this.project}, host: ${this.host} }`;
511
+ }
512
+ static scrubbed(env) {
513
+ return Object.fromEntries(Object.entries(env).filter(([key2]) => key2 !== "GATEWAY_TOKEN"));
514
+ }
515
+ };
516
+ }
517
+ });
518
+
467
519
  // src/worlds/platformEndpoint.ts
468
520
  function platformEndpoint(options) {
521
+ if (options.token)
522
+ return {
523
+ host: (options.host ?? options.token.host).replace(/\/+$/, ""),
524
+ publicKey: options.publicKey ?? "",
525
+ secretKey: options.secretKey ?? "",
526
+ token: options.token
527
+ };
528
+ const token = PersonalToken.fromEnv(process.env, {
529
+ host: options.host,
530
+ keys: Boolean(options.publicKey || options.secretKey)
531
+ });
532
+ if (token) return { host: token.host, publicKey: "", secretKey: "", token };
533
+ const host = (options.host ?? process.env.GATEWAY_HOST ?? DEFAULT_HOST).replace(/\/+$/, "");
469
534
  const publicKey = options.publicKey ?? process.env.GATEWAY_PUBLIC_KEY;
470
535
  const secretKey = options.secretKey ?? process.env.GATEWAY_SECRET_KEY;
471
536
  if (!publicKey || !secretKey) return null;
472
- const host = options.host ?? process.env.GATEWAY_HOST ?? DEFAULT_HOST;
473
- return { host: host.replace(/\/+$/, ""), publicKey, secretKey };
537
+ return { host, publicKey, secretKey };
474
538
  }
475
539
  function requirePlatformEndpoint(options) {
476
540
  const endpoint = platformEndpoint(options);
@@ -481,11 +545,74 @@ var DEFAULT_HOST, GATEWAY_KEYS_MISSING;
481
545
  var init_platformEndpoint = __esm({
482
546
  "src/worlds/platformEndpoint.ts"() {
483
547
  "use strict";
548
+ init_personalToken();
484
549
  DEFAULT_HOST = "https://withgateway.ai";
485
550
  GATEWAY_KEYS_MISSING = "Gateway keys missing: set GATEWAY_PUBLIC_KEY / GATEWAY_SECRET_KEY (or pass publicKey/secretKey).";
486
551
  }
487
552
  });
488
553
 
554
+ // src/worlds/apiError.ts
555
+ function edgeAnswer(text2, status) {
556
+ if (status !== void 0 && status >= 500) return EDGE_ANSWERS[status] ?? EDGE_FAILURE;
557
+ return /^\s*</.test(text2) ? EDGE_PAGE : null;
558
+ }
559
+ function parseErrorBody(text2, status) {
560
+ const raw = { detail: text2.slice(0, DETAIL_LIMIT), code: null };
561
+ let parsed;
562
+ try {
563
+ parsed = JSON.parse(text2);
564
+ } catch {
565
+ return { detail: (edgeAnswer(text2, status) ?? text2).slice(0, DETAIL_LIMIT), code: null };
566
+ }
567
+ if (parsed === null || typeof parsed !== "object") return raw;
568
+ const { message, code, error } = parsed;
569
+ const stableCode = typeof code === "string" ? code : null;
570
+ if (typeof message !== "string") return { ...raw, code: stableCode };
571
+ const fields = invalidFields(error);
572
+ const said = fields ? `${message}: ${fields}` : message;
573
+ if (stableCode === null) return { detail: said.slice(0, DETAIL_LIMIT), code: null };
574
+ return {
575
+ detail: `${said} (${stableCode})`.slice(0, DETAIL_LIMIT),
576
+ code: stableCode
577
+ };
578
+ }
579
+ function invalidFields(error) {
580
+ const issues = Array.isArray(error) ? error : [];
581
+ return issues.filter(
582
+ (issue) => issue !== null && typeof issue === "object" && typeof issue.message === "string"
583
+ ).map((issue) => {
584
+ const path17 = Array.isArray(issue.path) ? issue.path.map(String).join(".") : "";
585
+ return path17 ? `${path17}: ${issue.message}` : issue.message;
586
+ }).join("; ");
587
+ }
588
+ var ApiError, DETAIL_LIMIT, EDGE_ANSWERS, EDGE_FAILURE, EDGE_PAGE;
589
+ var init_apiError = __esm({
590
+ "src/worlds/apiError.ts"() {
591
+ "use strict";
592
+ ApiError = class extends Error {
593
+ constructor(status, method, path17, text2) {
594
+ const parsed = parseErrorBody(text2, status);
595
+ super(`${method} ${path17} -> ${status}: ${parsed.detail}`);
596
+ this.status = status;
597
+ this.text = text2;
598
+ this.name = "ApiError";
599
+ this.code = parsed.code;
600
+ }
601
+ status;
602
+ text;
603
+ code;
604
+ };
605
+ DETAIL_LIMIT = 600;
606
+ EDGE_ANSWERS = {
607
+ 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.",
608
+ 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.",
609
+ 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."
610
+ };
611
+ 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.";
612
+ 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.";
613
+ }
614
+ });
615
+
489
616
  // src/worlds/transport.ts
490
617
  function platformTimeoutMs(env = process.env) {
491
618
  const raw = env[PLATFORM_TIMEOUT_ENV];
@@ -494,10 +621,20 @@ function platformTimeoutMs(env = process.env) {
494
621
  if (Number.isInteger(value) && value > 0) return value;
495
622
  throw new Error(`${PLATFORM_TIMEOUT_ENV} must be a positive whole number of milliseconds, not \`${raw}\`.`);
496
623
  }
497
- var PLATFORM_TIMEOUT_ENV, PLATFORM_TIMEOUT_DEFAULT_MS, CHECK_HOST, RETRY, FETCH_LIMIT, CAUSES, UNKNOWN_CAUSE, TransportCause, UnreachableError, sleep2, RetryPolicy, Attempt, PlatformTransport;
624
+ function platformAuthorization(endpoint, url) {
625
+ const { token } = endpoint;
626
+ if (!token)
627
+ return { authorization: "Basic " + Buffer.from(`${endpoint.publicKey}:${endpoint.secretKey}`).toString("base64") };
628
+ if (endpoint.publicKey || endpoint.secretKey) throw new PersonalTokenRefused(TOKEN_BESIDE_KEYS);
629
+ if (!url.startsWith(`${token.host}/`)) throw new PersonalTokenRefused(TOKEN_OTHER_HOST);
630
+ return { authorization: `Bearer ${token.value}`, "x-gateway-project": token.project };
631
+ }
632
+ 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;
498
633
  var init_transport = __esm({
499
634
  "src/worlds/transport.ts"() {
500
635
  "use strict";
636
+ init_apiError();
637
+ init_personalToken();
501
638
  PLATFORM_TIMEOUT_ENV = "GATEWAY_TIMEOUT_MS";
502
639
  PLATFORM_TIMEOUT_DEFAULT_MS = 12e4;
503
640
  CHECK_HOST = "Check GATEWAY_HOST (or --host) points at a running platform, then retry.";
@@ -537,6 +674,13 @@ var init_transport = __esm({
537
674
  `Retry; if the platform is slow, raise ${PLATFORM_TIMEOUT_ENV} (milliseconds per request).`
538
675
  );
539
676
  }
677
+ static idle(idleMs) {
678
+ return new _TransportCause(
679
+ `no data for ${idleMs / 1e3}s`,
680
+ null,
681
+ "The stream resumes from its last event; if it repeats, check the network between here and the platform."
682
+ );
683
+ }
540
684
  static of(error) {
541
685
  const cause = error instanceof Error && error.cause instanceof Error ? error.cause : void 0;
542
686
  const code = cause && "code" in cause && typeof cause.code === "string" ? cause.code : null;
@@ -549,11 +693,11 @@ var init_transport = __esm({
549
693
  }
550
694
  };
551
695
  UnreachableError = class extends Error {
552
- constructor(host, method, route, failure) {
553
- super(`${method} ${route}: no answer from ${host}: ${failure.describe()}. ${failure.next}`);
696
+ constructor(host, method, route2, failure) {
697
+ super(`${method} ${route2}: no answer from ${host}: ${failure.describe()}. ${failure.next}`);
554
698
  this.host = host;
555
699
  this.method = method;
556
- this.route = route;
700
+ this.route = route2;
557
701
  this.failure = failure;
558
702
  this.name = "UnreachableError";
559
703
  }
@@ -612,48 +756,280 @@ var init_transport = __esm({
612
756
  throw this.error;
613
757
  }
614
758
  };
759
+ PLATFORM_STREAM_IDLE_MS = 6e4;
760
+ REFUSAL_TEXT_LIMIT = 64 * 1024;
761
+ KEYED_REDIRECTS = "manual";
615
762
  PlatformTransport = class {
763
+ #endpoint;
764
+ #timeoutMs;
616
765
  constructor(endpoint, timeoutMs = platformTimeoutMs()) {
617
- this.endpoint = endpoint;
618
- this.timeoutMs = timeoutMs;
766
+ this.#endpoint = endpoint;
767
+ this.#timeoutMs = timeoutMs;
619
768
  }
620
- endpoint;
621
- timeoutMs;
622
769
  /** A request that legitimately takes longer (a sandbox exec, a world create) waits its own budget; every other one waits the default. */
623
770
  budget(ownMs) {
624
- return Math.max(ownMs ?? 0, this.timeoutMs);
771
+ return Math.max(ownMs ?? 0, this.#timeoutMs);
625
772
  }
626
- async send(method, route, body, opts = {}) {
773
+ /** One request; the caller's `signal` aborts it in flight and throws the signal's reason, never an `UnreachableError`. */
774
+ async send(method, route2, body, opts = {}) {
627
775
  const timeoutMs = this.budget(opts.timeoutMs);
628
- return (opts.retry ?? RetryPolicy.NONE).run(() => this.once(method, route, body, timeoutMs));
776
+ return (opts.retry ?? RetryPolicy.NONE).run(() => this.once(method, route2, body, timeoutMs, opts.signal));
777
+ }
778
+ /** `send`, then the 2xx body as JSON; any other answer throws `ApiError` with its status and stable `code`. */
779
+ async json(method, route2, body, opts = {}) {
780
+ const reply = await this.send(method, route2, body, opts);
781
+ if (!reply.ok) throw new ApiError(reply.status, method, route2, reply.text);
782
+ return JSON.parse(reply.text);
783
+ }
784
+ /** 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. */
785
+ async stream(route2, opts = {}) {
786
+ const watch = new StreamWatch(opts.signal, opts.idleMs ?? PLATFORM_STREAM_IDLE_MS, this.#endpoint.host, route2);
787
+ const headers = this.headers(route2, "text/event-stream", opts.after ? { "last-event-id": opts.after } : {});
788
+ try {
789
+ const response = await watch.within(
790
+ () => fetch(this.url(route2), { method: "GET", headers, signal: watch.signal, redirect: KEYED_REDIRECTS })
791
+ );
792
+ return new PlatformStream(response, watch);
793
+ } catch (error) {
794
+ watch.close();
795
+ throw error;
796
+ }
629
797
  }
630
- async once(method, route, body, timeoutMs) {
798
+ url(route2) {
799
+ return `${this.#endpoint.host}${route2}`;
800
+ }
801
+ headers(route2, accept, extra = {}) {
802
+ return {
803
+ "content-type": "application/json",
804
+ accept,
805
+ ...platformAuthorization(this.#endpoint, this.url(route2)),
806
+ ...extra
807
+ };
808
+ }
809
+ async once(method, route2, body, timeoutMs, caller) {
810
+ if (caller?.aborted) throw caller.reason;
631
811
  const payload = body === void 0 ? {} : { body: JSON.stringify(body) };
812
+ const headers = this.headers(route2, "application/json");
632
813
  const controller = new AbortController();
633
814
  const timer = setTimeout(() => controller.abort(), timeoutMs);
815
+ const relay = () => controller.abort(caller?.reason);
816
+ caller?.addEventListener("abort", relay, { once: true });
634
817
  try {
635
- const res = await fetch(`${this.endpoint.host}${route}`, {
818
+ const res = await fetch(this.url(route2), {
636
819
  method,
637
- headers: {
638
- "content-type": "application/json",
639
- accept: "application/json",
640
- authorization: "Basic " + Buffer.from(`${this.endpoint.publicKey}:${this.endpoint.secretKey}`).toString("base64")
641
- },
820
+ headers,
642
821
  ...payload,
643
- signal: controller.signal
822
+ signal: controller.signal,
823
+ redirect: KEYED_REDIRECTS
644
824
  });
645
825
  return { status: res.status, ok: res.ok, text: await res.text() };
646
826
  } catch (error) {
827
+ if (caller?.aborted) throw caller.reason;
647
828
  const cause = controller.signal.aborted ? TransportCause.timeout(timeoutMs) : TransportCause.of(error);
648
- throw new UnreachableError(this.endpoint.host, method, route, cause);
829
+ throw new UnreachableError(this.#endpoint.host, method, route2, cause);
649
830
  } finally {
650
831
  clearTimeout(timer);
832
+ caller?.removeEventListener("abort", relay);
833
+ }
834
+ }
835
+ };
836
+ StreamWatch = class {
837
+ constructor(caller, idleMs, host, route2) {
838
+ this.idleMs = idleMs;
839
+ this.host = host;
840
+ this.route = route2;
841
+ this.#caller = caller;
842
+ caller?.addEventListener("abort", this.#relay, { once: true });
843
+ if (caller?.aborted) this.#relay();
844
+ }
845
+ idleMs;
846
+ host;
847
+ route;
848
+ #controller = new AbortController();
849
+ #caller;
850
+ #relay = () => this.#controller.abort(this.#caller?.reason);
851
+ #idled = false;
852
+ get signal() {
853
+ return this.#controller.signal;
854
+ }
855
+ async within(wait) {
856
+ const timer = setTimeout(() => this.idle(), this.idleMs);
857
+ try {
858
+ return await wait();
859
+ } catch (error) {
860
+ throw this.failure(error);
861
+ } finally {
862
+ clearTimeout(timer);
863
+ }
864
+ }
865
+ close() {
866
+ this.#caller?.removeEventListener("abort", this.#relay);
867
+ this.#controller.abort();
868
+ }
869
+ idle() {
870
+ this.#idled = true;
871
+ this.#controller.abort();
872
+ }
873
+ failure(error) {
874
+ if (this.#caller?.aborted) return this.#caller.reason;
875
+ const cause = this.#idled ? TransportCause.idle(this.idleMs) : TransportCause.of(error);
876
+ return new UnreachableError(this.host, "GET", this.route, cause);
877
+ }
878
+ };
879
+ PlatformStream = class {
880
+ #response;
881
+ #watch;
882
+ constructor(response, watch) {
883
+ this.#response = response;
884
+ this.#watch = watch;
885
+ }
886
+ get status() {
887
+ return this.#response.status;
888
+ }
889
+ get ok() {
890
+ return this.#response.ok;
891
+ }
892
+ /** The body as text, for a refusal: at most the first 64 KiB of characters; closes the stream. */
893
+ async text() {
894
+ const decoder = new TextDecoder();
895
+ let text2 = "";
896
+ for await (const chunk of this.chunks()) {
897
+ text2 += decoder.decode(chunk, { stream: true });
898
+ if (text2.length >= REFUSAL_TEXT_LIMIT) return text2.slice(0, REFUSAL_TEXT_LIMIT);
899
+ }
900
+ return text2 + decoder.decode();
901
+ }
902
+ /** The body's bytes as they arrive; the idle budget runs only while waiting for the platform, never while the caller holds a chunk. */
903
+ async *chunks() {
904
+ const reader = this.#response.body?.getReader();
905
+ try {
906
+ for (; ; ) {
907
+ const next = reader ? await this.#watch.within(() => reader.read()) : { done: true };
908
+ if (next.done) return;
909
+ yield next.value;
910
+ }
911
+ } finally {
912
+ this.close();
651
913
  }
652
914
  }
915
+ close() {
916
+ this.#watch.close();
917
+ }
653
918
  };
654
919
  }
655
920
  });
656
921
 
922
+ // src/worlds/credentialField.ts
923
+ function isCredentialField(described) {
924
+ const words2 = described.replace(SPACES, " ").replace(/^ | $/g, "");
925
+ return SECRET_FIELD.some((prefix) => words2.startsWith(prefix)) || SECRET_KEY.test(words2);
926
+ }
927
+ function credentialTexts(pairs) {
928
+ return pairs.filter(([, text2]) => text2 !== null && text2 !== void 0).filter(([described]) => isCredentialField(String(described))).map(([, text2]) => String(text2));
929
+ }
930
+ function isTextField(described) {
931
+ return described !== "" && !NOT_TEXT.some((prefix) => described.startsWith(prefix));
932
+ }
933
+ function redactActionArgs(action, args) {
934
+ const secretField = action === "browser_type" && SECRET_KEY.test(String(args.selector ?? ""));
935
+ return Object.fromEntries(
936
+ Object.entries(args).map(([key2, value]) => [
937
+ key2,
938
+ redactedArg(key2, value, secretField)
939
+ ])
940
+ );
941
+ }
942
+ function redactedArg(key2, value, secretField) {
943
+ if (value === null || value === void 0) return null;
944
+ if (typeof value === "boolean" || typeof value === "number") return value;
945
+ if (typeof value !== "string") return "[omitted]";
946
+ if (SECRET_KEY.test(key2) || SECRET_VALUE.test(value) || secretField && key2 === "text")
947
+ return "[redacted]";
948
+ return value.length <= EVENT_MAX_STRING ? value : value.slice(0, EVENT_MAX_STRING) + "\u2026";
949
+ }
950
+ 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;
951
+ var init_credentialField = __esm({
952
+ "src/worlds/credentialField.ts"() {
953
+ "use strict";
954
+ 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;
955
+ 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(' '); }";
956
+ 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; }";
957
+ 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])";
958
+ SHORTEST_WITHHELD = 4;
959
+ WITHHELD_TEXT = "[redacted]";
960
+ SPACES = /[ \t\n\r\f\v]+/g;
961
+ LINE_BREAK = /\r\n|\r|\n/;
962
+ TRIM = /^[ \t\n\r\f\v]+|[ \t\n\r\f\v]+$/g;
963
+ describeField = new Function(
964
+ "e",
965
+ `return (${DESCRIBE_FIELD_JS})(e);`
966
+ );
967
+ readFieldValue = new Function(
968
+ "e",
969
+ `return (${FIELD_VALUE_JS})(e);`
970
+ );
971
+ readEditables = new Function(
972
+ "elements",
973
+ `return elements.map((e) => [(${DESCRIBE_FIELD_JS})(e), (${FIELD_VALUE_JS})(e)]);`
974
+ );
975
+ UNREADABLE = "unreadable";
976
+ SECRET_FIELD = ["password", "frame", "opaque", UNREADABLE];
977
+ NOT_TEXT = ["opaque", "frame", "select"];
978
+ escapeRegExp = (text2) => text2.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
979
+ urlForms = (text2) => {
980
+ let component;
981
+ try {
982
+ component = encodeURIComponent(text2);
983
+ } catch {
984
+ return [];
985
+ }
986
+ const form = component.replace(
987
+ /[!'()~]/g,
988
+ (c) => "%" + c.charCodeAt(0).toString(16).toUpperCase()
989
+ ).replace(/%20/g, "+");
990
+ return [component, component.replace(/%20/g, "+"), form];
991
+ };
992
+ forms = (text2) => {
993
+ const written = [
994
+ text2,
995
+ text2.replace(SPACES, " "),
996
+ JSON.stringify(text2).slice(1, -1)
997
+ ];
998
+ return [
999
+ ...written,
1000
+ ...written.map((form) => form.replaceAll("'", "''")),
1001
+ ...urlForms(text2)
1002
+ ];
1003
+ };
1004
+ CredentialText = class {
1005
+ pattern;
1006
+ constructor(secrets) {
1007
+ const texts = secrets.map((secret) => String(secret).replace(TRIM, ""));
1008
+ const lines = texts.flatMap(
1009
+ (text2) => text2.split(LINE_BREAK).map((line) => line.replace(TRIM, ""))
1010
+ );
1011
+ const whole = new Set(
1012
+ [...texts, ...lines].filter(
1013
+ (text2) => [...text2].length >= SHORTEST_WITHHELD
1014
+ )
1015
+ );
1016
+ const withheld = [
1017
+ ...new Set([...whole].flatMap((text2) => forms(text2)))
1018
+ ].sort((a, b) => b.length - a.length);
1019
+ this.pattern = withheld.length === 0 ? null : new RegExp(
1020
+ `(?<![A-Za-z0-9])(?:${withheld.map(escapeRegExp).join("|")})(?![A-Za-z0-9])`,
1021
+ "g"
1022
+ );
1023
+ }
1024
+ withhold(text2) {
1025
+ return this.pattern === null ? text2 : text2.replace(this.pattern, WITHHELD_TEXT);
1026
+ }
1027
+ };
1028
+ EVENT_MAX_STRING = 500;
1029
+ SECRET_VALUE = /^((sk|pk|ghp|xox[abp])[-_][-_A-Za-z0-9]{8,}|AKIA[0-9A-Z]{12,}|Bearer [-_.A-Za-z0-9]{8,})/;
1030
+ }
1031
+ });
1032
+
657
1033
  // src/worlds/browserReconnect.ts
658
1034
  async function closeConnection(c) {
659
1035
  await c.context.close();
@@ -667,6 +1043,25 @@ function isBrowserGone(error) {
667
1043
  if (PAGE_NETWORK_ERROR.test(message)) return false;
668
1044
  return BROWSER_GONE_PATTERNS.some((p) => p.test(message));
669
1045
  }
1046
+ function scrubError(error, scrub) {
1047
+ const seen = /* @__PURE__ */ new Set();
1048
+ let at = error;
1049
+ while (at instanceof Error && !seen.has(at)) {
1050
+ seen.add(at);
1051
+ at.message = scrub(at.message);
1052
+ at.stack = at.stack && scrub(at.stack);
1053
+ scrubOwnText(at, scrub);
1054
+ at = at.cause;
1055
+ }
1056
+ }
1057
+ function scrubOwnText(error, scrub) {
1058
+ for (const key2 of Object.keys(error)) {
1059
+ const value = error[key2];
1060
+ if (typeof value === "string") error[key2] = scrub(value);
1061
+ if (Array.isArray(value) && value.every((item) => typeof item === "string"))
1062
+ error[key2] = value.map((item) => scrub(item));
1063
+ }
1064
+ }
670
1065
  function refusalIsTransient(error) {
671
1066
  const { status, code } = error;
672
1067
  if (typeof status !== "number") return true;
@@ -703,11 +1098,17 @@ var init_browserReconnect = __esm({
703
1098
  ].sort((a, b) => b.length - a.length);
704
1099
  }
705
1100
  scrub(text2) {
706
- const bare = this.secrets.reduce(
1101
+ const bare2 = this.secrets.reduce(
707
1102
  (out, secret) => out.split(secret).join(REDACTED),
708
1103
  text2
709
1104
  );
710
- return bare.replace(TOKEN_QUERY_VALUE, `$1${REDACTED}`);
1105
+ return bare2.replace(TOKEN_QUERY_VALUE, `$1${REDACTED}`);
1106
+ }
1107
+ /** Scrub `error` and the errors it was raised from, in place: the message,
1108
+ * the stack and every other own text property, Playwright's `log` call log
1109
+ * included. */
1110
+ scrubError(error) {
1111
+ scrubError(error, (text2) => this.scrub(text2));
711
1112
  }
712
1113
  };
713
1114
  BrowserReconnected = class extends Error {
@@ -859,22 +1260,6 @@ function capabilityLabel(url) {
859
1260
  }
860
1261
  return CAPABILITY_HOST.exec(host)?.[1] ?? null;
861
1262
  }
862
- function redactActionArgs(action, args) {
863
- const secretField = action === "browser_type" && SECRET_KEY.test(String(args.selector ?? ""));
864
- const out = {};
865
- for (const [key2, value] of Object.entries(args)) {
866
- if (value === null || value === void 0) out[key2] = null;
867
- else if (typeof value === "boolean" || typeof value === "number")
868
- out[key2] = value;
869
- else if (typeof value === "string") {
870
- if (SECRET_KEY.test(key2) || SECRET_VALUE.test(value) || secretField && key2 === "text")
871
- out[key2] = "[redacted]";
872
- else
873
- out[key2] = value.length <= EVENT_MAX_STRING ? value : value.slice(0, EVENT_MAX_STRING) + "\u2026";
874
- } else out[key2] = "[omitted]";
875
- }
876
- return out;
877
- }
878
1263
  async function loadPlaywright() {
879
1264
  try {
880
1265
  const name = "playwright";
@@ -936,62 +1321,14 @@ async function openBrowser(surfaces, opts = {}) {
936
1321
  scrubber
937
1322
  );
938
1323
  }
939
- function computerUseToolkit(browser, opts = {}) {
940
- const maxText = opts.maxText ?? 2e4;
941
- const observe2 = async (selector = "body") => {
942
- const text2 = await browser.text(selector);
943
- return {
944
- url: browser.url,
945
- title: await browser.title(),
946
- text: text2.slice(0, maxText),
947
- truncated: text2.length > maxText
948
- };
949
- };
950
- const impls = {
951
- browser_goto: async (a) => {
952
- await browser.goto(typeof a.path === "string" ? a.path : void 0);
953
- return observe2();
954
- },
955
- browser_click: async (a) => {
956
- await browser.click(str(a.selector, ""));
957
- return observe2();
958
- },
959
- browser_type: async (a) => {
960
- await browser.type(str(a.selector, ""), String(a.text ?? ""));
961
- return { ok: true, url: browser.url };
962
- },
963
- browser_press: async (a) => {
964
- await browser.press(str(a.key, "Enter"));
965
- return observe2();
966
- },
967
- browser_scroll: async (a) => {
968
- await browser.scroll(typeof a.dy === "number" ? a.dy : 600);
969
- return { ok: true, url: browser.url };
970
- },
971
- browser_screenshot: async (a) => ({
972
- image_base64: await browser.screenshotBase64(a.full_page === true),
973
- url: browser.url
974
- }),
975
- browser_read: async (a) => observe2(str(a.selector, "body")),
976
- browser_back: async () => {
977
- await browser.back();
978
- return observe2();
979
- }
980
- };
981
- const specs = COMPUTER_USE_SPECS.map((s) => ({ ...s }));
982
- return {
983
- schemas: specs.map((spec) => schemaFromSignature(spec)),
984
- impls,
985
- specs
986
- };
987
- }
988
- 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;
1324
+ 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;
989
1325
  var init_browser = __esm({
990
1326
  "src/worlds/browser.ts"() {
991
1327
  "use strict";
992
- init_session2();
1328
+ init_credentialField();
993
1329
  init_browserReconnect();
994
1330
  SURFACE_KINDS = ["tools", "api", "ui", "browser"];
1331
+ FIELD_PROBE_TIMEOUT_MS = 2e3;
995
1332
  PLATFORM_SESSION_HEADER = "X-World-Session";
996
1333
  SESSION_AUTH_MODES = ["vendor", "open"];
997
1334
  BROWSER_TIERS = ["standard", "premium"];
@@ -1003,9 +1340,6 @@ var init_browser = __esm({
1003
1340
  EVENT_FLUSH_INTERVAL_MS = 1e3;
1004
1341
  EVENT_MAX_RETRIES = 3;
1005
1342
  EVENT_SCREENSHOT_QUALITY = 60;
1006
- EVENT_MAX_STRING = 500;
1007
- SECRET_KEY = /pass(word|wd)?|secret|token|api[-_]?key|authorization|cookie|(^|[-_ #.\["'=])(otp|pin|cvv|ssn)([-_ \]"']|$)/i;
1008
- SECRET_VALUE = /^((sk|pk|ghp|xox[abp])[-_][-_A-Za-z0-9]{8,}|AKIA[0-9A-Z]{12,}|Bearer [-_.A-Za-z0-9]{8,})/;
1009
1343
  WorldSurfaceUnavailable = class extends Error {
1010
1344
  constructor(surface, reason) {
1011
1345
  super(`World surface '${surface}' is unavailable: ${reason}`);
@@ -1128,6 +1462,8 @@ var init_browser = __esm({
1128
1462
  recorder;
1129
1463
  reconnector;
1130
1464
  scrubber;
1465
+ typed = [];
1466
+ typedText = new CredentialText([]);
1131
1467
  current;
1132
1468
  inflight = 0;
1133
1469
  lastNetwork = Date.now();
@@ -1141,10 +1477,20 @@ var init_browser = __esm({
1141
1477
  get agentId() {
1142
1478
  return this.recorder?.agentId ?? null;
1143
1479
  }
1144
- /** `text` with this session's credentials (UI token, browser address) removed. */
1480
+ /** `text` with this session's credentials (UI token, browser address) and
1481
+ * the credentials typed into it removed. */
1145
1482
  scrub(text2) {
1483
+ return this.typedText.withhold(this.scrubber.scrub(text2));
1484
+ }
1485
+ /** `text` with this session's credentials removed and nothing else
1486
+ * changed: for text that is compared and never leaves the process. */
1487
+ scrubSession(text2) {
1146
1488
  return this.scrubber.scrub(text2);
1147
1489
  }
1490
+ /** Every credential typed into this browser by `type`. */
1491
+ get typedCredentials() {
1492
+ return [...this.typed];
1493
+ }
1148
1494
  watchNetwork(page) {
1149
1495
  page.on("request", () => {
1150
1496
  this.inflight += 1;
@@ -1188,7 +1534,7 @@ var init_browser = __esm({
1188
1534
  async recover(reconnector, cause) {
1189
1535
  const started = Date.now();
1190
1536
  const message = cause instanceof Error ? cause.message : String(cause);
1191
- const args = { cause: this.scrubber.scrub(message).slice(0, 200) };
1537
+ const args = { cause: this.scrub(message).slice(0, 200) };
1192
1538
  let result;
1193
1539
  try {
1194
1540
  result = await reconnector.recover(cause, (c) => this.adopt(c));
@@ -1223,7 +1569,9 @@ var init_browser = __esm({
1223
1569
  }
1224
1570
  /** Run one action and report it: the event carries what was asked,
1225
1571
  * whether it worked, and the screen after — for failures too, so a
1226
- * reviewer sees what the agent saw when the selector did not match. */
1572
+ * reviewer sees what the agent saw when the selector did not match. The
1573
+ * error it throws keeps no session credential and no credential typed into
1574
+ * this browser, which Playwright's call log would quote. */
1227
1575
  async act(action, args, fn, onLoss = "report") {
1228
1576
  const started = Date.now();
1229
1577
  try {
@@ -1231,6 +1579,7 @@ var init_browser = __esm({
1231
1579
  await this.report(action, args, started, null);
1232
1580
  return result;
1233
1581
  } catch (error) {
1582
+ this.scrubError(error);
1234
1583
  await this.report(action, args, started, error);
1235
1584
  throw error;
1236
1585
  }
@@ -1239,7 +1588,7 @@ var init_browser = __esm({
1239
1588
  async report(action, args, started, failure) {
1240
1589
  const recorder = this.recorder;
1241
1590
  if (!recorder) return;
1242
- const error = failure === null ? null : this.scrubber.scrub(
1591
+ const error = failure === null ? null : this.scrub(
1243
1592
  failure instanceof Error ? `${failure.name}: ${failure.message}` : String(failure)
1244
1593
  ).slice(0, 4e3);
1245
1594
  recorder.record({
@@ -1252,7 +1601,7 @@ var init_browser = __esm({
1252
1601
  Object.fromEntries(
1253
1602
  Object.entries(args).map(([key2, value]) => [
1254
1603
  key2,
1255
- typeof value === "string" ? this.scrubber.scrub(value) : value
1604
+ typeof value === "string" ? this.scrub(value) : value
1256
1605
  ])
1257
1606
  )
1258
1607
  ),
@@ -1271,8 +1620,8 @@ var init_browser = __esm({
1271
1620
  screenshot: null
1272
1621
  };
1273
1622
  try {
1274
- out.url = this.scrubber.scrub(this.page.url());
1275
- out.title = this.scrubber.scrub(await this.page.title());
1623
+ out.url = this.scrub(this.page.url());
1624
+ out.title = this.scrub(await this.page.title());
1276
1625
  const jpeg = await this.page.screenshot({
1277
1626
  type: "jpeg",
1278
1627
  quality: EVENT_SCREENSHOT_QUALITY
@@ -1309,7 +1658,7 @@ var init_browser = __esm({
1309
1658
  async () => {
1310
1659
  await this.page.goto(target, { waitUntil: "load" });
1311
1660
  await this.settle();
1312
- return this.page.url();
1661
+ return this.url;
1313
1662
  },
1314
1663
  // Navigating again lands on the same page: safe to replay.
1315
1664
  "retry"
@@ -1319,7 +1668,7 @@ var init_browser = __esm({
1319
1668
  return this.act("browser_back", {}, async () => {
1320
1669
  await this.page.goBack({ waitUntil: "load" });
1321
1670
  await this.settle();
1322
- return this.page.url();
1671
+ return this.url;
1323
1672
  });
1324
1673
  }
1325
1674
  /** Wait for the page to finish reacting to an action. `load` alone is not
@@ -1338,19 +1687,54 @@ var init_browser = __esm({
1338
1687
  await this.page.waitForTimeout(SETTLE_POLL_MS);
1339
1688
  }
1340
1689
  }
1341
- async click(selector) {
1690
+ async click(selector, opts = {}) {
1342
1691
  await this.act("browser_click", { selector }, async () => {
1343
- await this.page.click(selector);
1692
+ await this.page.click(selector, { timeout: opts.timeoutMs });
1344
1693
  await this.settle();
1345
1694
  });
1346
1695
  }
1347
- async type(selector, text2) {
1696
+ /** Replace the field's value with `text`. `opts.credential` is whether the
1697
+ * field takes one, when the caller already probed it; a credential is
1698
+ * withheld from the event and from any error. */
1699
+ async type(selector, text2, opts = {}) {
1700
+ const secret = opts.credential ?? await this.credentialField(selector);
1701
+ if (secret) this.typed.push(text2);
1702
+ this.typedText = new CredentialText(this.typed);
1348
1703
  await this.act(
1349
1704
  "browser_type",
1350
- { selector, text: text2 },
1351
- () => this.page.fill(selector, text2)
1705
+ { selector, text: secret ? "[redacted]" : text2 },
1706
+ () => this.page.fill(selector, text2, { timeout: opts.timeoutMs })
1352
1707
  );
1353
1708
  }
1709
+ /** `DESCRIBE_FIELD_JS` of the element `selector` finds, or `UNREADABLE`. */
1710
+ async describeField(selector) {
1711
+ try {
1712
+ const described = await this.page.locator(selector).evaluate(describeField, void 0, { timeout: FIELD_PROBE_TIMEOUT_MS });
1713
+ return String(described ?? "");
1714
+ } catch {
1715
+ return UNREADABLE;
1716
+ }
1717
+ }
1718
+ /** Whether the field `selector` finds takes a credential; one it cannot
1719
+ * read counts. */
1720
+ async credentialField(selector) {
1721
+ return isCredentialField(await this.describeField(selector));
1722
+ }
1723
+ /** What the field `selector` finds holds (`FIELD_VALUE_JS`), or null when
1724
+ * it cannot be read. */
1725
+ async fieldValue(selector) {
1726
+ try {
1727
+ const value = await this.page.locator(selector).evaluate(readFieldValue, void 0, { timeout: FIELD_PROBE_TIMEOUT_MS });
1728
+ return value === null || value === void 0 ? null : String(value);
1729
+ } catch {
1730
+ return null;
1731
+ }
1732
+ }
1733
+ /** Take this session's credentials out of `error` and the errors it came
1734
+ * from, in place. */
1735
+ scrubError(error) {
1736
+ scrubError(error, (text2) => this.scrub(text2));
1737
+ }
1354
1738
  async press(key2) {
1355
1739
  await this.act("browser_press", { key: key2 }, async () => {
1356
1740
  await this.page.keyboard.press(key2);
@@ -1373,14 +1757,39 @@ var init_browser = __esm({
1373
1757
  async screenshotBase64(fullPage = false) {
1374
1758
  return (await this.screenshot(fullPage)).toString("base64");
1375
1759
  }
1760
+ /** The visible text of `selector`'s element, without what any field on the
1761
+ * page that takes a credential holds. */
1376
1762
  async text(selector = "body") {
1377
- return this.resilient(() => this.page.innerText(selector), "retry");
1763
+ const withheld = new CredentialText(await this.credentialTexts());
1764
+ return withheld.withhold(
1765
+ await this.resilient(() => this.page.innerText(selector), "retry")
1766
+ );
1767
+ }
1768
+ /** What each field on the page that takes a credential holds: an input's
1769
+ * or textarea's value, a select's chosen option, a contenteditable's text. */
1770
+ async credentialTexts() {
1771
+ return this.resilient(async () => {
1772
+ const pairs = await this.page.locator(FIELDS).evaluateAll(readEditables);
1773
+ return credentialTexts(pairs);
1774
+ }, "retry");
1775
+ }
1776
+ /** Wait until the element `selector` finds could be clicked, without
1777
+ * clicking it. */
1778
+ async actionable(selector) {
1779
+ await this.resilient(() => this.page.locator(selector).click({ trial: true }), "retry");
1780
+ }
1781
+ async ariaSnapshot() {
1782
+ return this.resilient(async () => {
1783
+ if (!this.page.ariaSnapshot)
1784
+ throw new TypeError("this Playwright has no page.ariaSnapshot");
1785
+ return this.page.ariaSnapshot({ mode: "ai" });
1786
+ }, "retry");
1378
1787
  }
1379
1788
  async html() {
1380
1789
  return this.resilient(() => this.page.content(), "retry");
1381
1790
  }
1382
1791
  get url() {
1383
- return this.page.url();
1792
+ return withoutUiToken(this.page.url());
1384
1793
  }
1385
1794
  async title() {
1386
1795
  return this.resilient(() => this.page.title(), "retry");
@@ -1393,21 +1802,504 @@ var init_browser = __esm({
1393
1802
  }
1394
1803
  }
1395
1804
  };
1805
+ }
1806
+ });
1807
+
1808
+ // src/worlds/pageState.ts
1809
+ function selectorRef(selector) {
1810
+ if (selector.includes("aria-ref"))
1811
+ throw new PageStateError(
1812
+ "aria-ref selectors are not taken: pass ref=\u2026 from browser_snapshot"
1813
+ );
1814
+ return REF_SELECTOR.exec(selector.replace(/^ +| +$/g, ""))?.[1] ?? null;
1815
+ }
1816
+ 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;
1817
+ var init_pageState = __esm({
1818
+ "src/worlds/pageState.ts"() {
1819
+ "use strict";
1820
+ init_credentialField();
1821
+ DEFAULT_MAX_CHARS = 2e4;
1822
+ REF_ACT_TIMEOUT_MS = 2e3;
1823
+ STEADY_READS = 4;
1824
+ NEEDS_PLAYWRIGHT = "browser_snapshot needs Playwright 1.59 or newer (npm install playwright@latest)";
1825
+ 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)";
1826
+ LINE_KEY = /^ *- ('(?:[^']|'')*'|.*?)(:(?: .*)?)?$/s;
1827
+ ATTRIBUTES = /(?: \[[^[\]]*\])*$/;
1828
+ FOCUS = / \[active\]/g;
1829
+ STATES = / \[(?:checked(?:=mixed)?|expanded|pressed(?:=mixed)?|selected)\]/g;
1830
+ ROLE = /^[a-z]+/;
1831
+ REF = /\[ref=((?:f[0-9]+)?e[0-9]+)\]/g;
1832
+ REF_SELECTOR = /^ref=((?:f[0-9]+)?e[0-9]+)$/;
1833
+ EDITABLE_ROLES = /* @__PURE__ */ new Set([
1834
+ "textbox",
1835
+ "searchbox",
1836
+ "combobox",
1837
+ "spinbutton",
1838
+ "slider"
1839
+ ]);
1840
+ VALUE_KEYS = /* @__PURE__ */ new Set(["text", "/placeholder"]);
1841
+ WITHHELD = ": [redacted]";
1842
+ PageStateError = class extends Error {
1843
+ name = "PageStateError";
1844
+ };
1845
+ AriaLine = class _AriaLine {
1846
+ constructor(text2, indent, key2 = "", attributes = "", rest = "") {
1847
+ this.text = text2;
1848
+ this.indent = indent;
1849
+ this.key = key2;
1850
+ this.attributes = attributes;
1851
+ this.rest = rest;
1852
+ }
1853
+ text;
1854
+ indent;
1855
+ key;
1856
+ attributes;
1857
+ rest;
1858
+ static parse(text2) {
1859
+ const indent = text2.length - text2.replace(/^ +/, "").length;
1860
+ const found = LINE_KEY.exec(text2);
1861
+ if (!found) return new _AriaLine(text2, indent);
1862
+ const key2 = found[1].startsWith("'") ? found[1].slice(1, -1).replaceAll("''", "'") : found[1];
1863
+ return new _AriaLine(
1864
+ text2,
1865
+ indent,
1866
+ key2,
1867
+ ATTRIBUTES.exec(key2)?.[0] ?? "",
1868
+ found[2] ?? ""
1869
+ );
1870
+ }
1871
+ static parseAll(aria) {
1872
+ return aria === "" ? [] : aria.split("\n").map((text2) => _AriaLine.parse(text2));
1873
+ }
1874
+ get refs() {
1875
+ return [...this.attributes.matchAll(REF)].map((ref) => ref[1]);
1876
+ }
1877
+ get disabled() {
1878
+ return this.attributes.includes("[disabled]");
1879
+ }
1880
+ get editable() {
1881
+ const role = ROLE.exec(this.key)?.[0];
1882
+ return role !== void 0 && EDITABLE_ROLES.has(role);
1883
+ }
1884
+ /** A value line: a field's text, or the placeholder it shows. */
1885
+ get value() {
1886
+ return VALUE_KEYS.has(this.key);
1887
+ }
1888
+ get states() {
1889
+ return this.attributes.match(STATES) ?? [];
1890
+ }
1891
+ get namedLikeCredential() {
1892
+ return SECRET_KEY.test(
1893
+ this.key.slice(0, this.key.length - this.attributes.length)
1894
+ );
1895
+ }
1896
+ /** Whether every value in and under this line is withheld. A field is,
1897
+ * when it is named like a credential or sits in something that is, has no
1898
+ * ref to probe, or `describe` reads it as a credential field. Any other
1899
+ * line is, when it is named like a credential and holds typed text (a
1900
+ * contenteditable), or has no ref to tell. */
1901
+ async credentialField(describe2, withinCredential) {
1902
+ if (this.editable)
1903
+ return this.credentialFieldInput(describe2, withinCredential);
1904
+ if (!this.namedLikeCredential) return false;
1905
+ if (this.refs.length === 0) return true;
1906
+ return isTextField(await describe2(this.refs[0]));
1907
+ }
1908
+ async credentialFieldInput(describe2, withinCredential) {
1909
+ if (withinCredential || this.namedLikeCredential) return true;
1910
+ if (this.refs.length === 0) return true;
1911
+ return isCredentialField(await describe2(this.refs[0]));
1912
+ }
1913
+ /** The line as shown: `withholding` applied to its text, while its refs and
1914
+ * states are still read from the attribute run Playwright wrote, so a
1915
+ * withheld name cannot join that run. */
1916
+ withheldBy(withhold) {
1917
+ return new _AriaLine(
1918
+ this.withholding(withhold),
1919
+ this.indent,
1920
+ this.key,
1921
+ this.attributes,
1922
+ this.rest
1923
+ );
1924
+ }
1925
+ /** The line with `withhold` applied to its name and value, its attribute
1926
+ * run (refs, states, levels) as Playwright wrote it. */
1927
+ withholding(withhold) {
1928
+ const at = this.attributes ? this.text.lastIndexOf(
1929
+ this.attributes,
1930
+ this.text.length - this.rest.length - this.attributes.length
1931
+ ) : -1;
1932
+ if (at < 0) return withhold(this.text);
1933
+ const end = at + this.attributes.length;
1934
+ return withhold(this.text.slice(0, at)) + this.attributes + withhold(this.text.slice(end));
1935
+ }
1936
+ /** The line with its own value replaced, keeping the key as Playwright
1937
+ * wrote it. */
1938
+ get withheld() {
1939
+ if (this.key === "/placeholder" || !this.rest.startsWith(": "))
1940
+ return this.text;
1941
+ return this.text.slice(0, this.text.length - this.rest.length) + WITHHELD;
1942
+ }
1943
+ };
1944
+ Touched = class _Touched {
1945
+ constructor(clicked = /* @__PURE__ */ new Map(), typed = /* @__PURE__ */ new Map()) {
1946
+ this.clicked = clicked;
1947
+ this.typed = typed;
1948
+ }
1949
+ clicked;
1950
+ typed;
1951
+ afterClick(ref, states) {
1952
+ return new _Touched(new Map([...this.clicked, [ref, states]]), this.typed);
1953
+ }
1954
+ afterTyping(ref, text2) {
1955
+ return new _Touched(this.clicked, new Map([...this.typed, [ref, text2]]));
1956
+ }
1957
+ /** The snapshot's lines as the page should now read them. */
1958
+ expected(lines) {
1959
+ return this.compared(lines, (line) => this.leftByClick(line));
1960
+ }
1961
+ /** A fresh read's lines, in the same form. */
1962
+ actual(lines) {
1963
+ return this.compared(lines, (line) => line.states);
1964
+ }
1965
+ compared(lines, states) {
1966
+ const out = [];
1967
+ let typedAt = null;
1968
+ for (const line of lines) {
1969
+ if (typedAt !== null && line.indent > typedAt && line.value) continue;
1970
+ typedAt = this.isTyped(line) ? line.indent : null;
1971
+ out.push(this.comparedLine(line, states(line)));
1972
+ }
1973
+ return out;
1974
+ }
1975
+ isTyped(line) {
1976
+ return line.refs.some((ref) => this.typed.has(ref));
1977
+ }
1978
+ clickedRef(line) {
1979
+ return line.refs.find((ref) => this.clicked.has(ref));
1980
+ }
1981
+ leftByClick(line) {
1982
+ const ref = this.clickedRef(line);
1983
+ return ref === void 0 ? line.states : this.clicked.get(ref);
1984
+ }
1985
+ comparedLine(line, states) {
1986
+ if (this.isTyped(line))
1987
+ return (" ".repeat(line.indent) + "- " + line.key).replace(FOCUS, "");
1988
+ if (this.clickedRef(line) !== void 0)
1989
+ return line.text.replace(FOCUS, "").replace(STATES, "") + states.join("");
1990
+ return line.text.replace(FOCUS, "");
1991
+ }
1992
+ };
1993
+ sameLines = (a, b) => a.length === b.length && a.every((line, at) => line === b[at]);
1994
+ deeper = (line, below) => below !== null && line.indent > below ? below : null;
1995
+ PageState = class _PageState {
1996
+ constructor(url, title, snapshot, refs, disabled, truncated, credentials = /* @__PURE__ */ new Set()) {
1997
+ this.url = url;
1998
+ this.title = title;
1999
+ this.snapshot = snapshot;
2000
+ this.refs = refs;
2001
+ this.disabled = disabled;
2002
+ this.truncated = truncated;
2003
+ this.credentials = credentials;
2004
+ }
2005
+ url;
2006
+ title;
2007
+ snapshot;
2008
+ refs;
2009
+ disabled;
2010
+ truncated;
2011
+ credentials;
2012
+ static parse(aria, opts) {
2013
+ return _PageState.ofLines(AriaLine.parseAll(aria), opts);
2014
+ }
2015
+ static ofLines(lines, opts) {
2016
+ const maxChars = opts.maxChars ?? DEFAULT_MAX_CHARS;
2017
+ const shown = [];
2018
+ let size = 0;
2019
+ for (const line of lines) {
2020
+ const width = [...line.text].length + 1;
2021
+ if (size + width > maxChars) break;
2022
+ size += width;
2023
+ shown.push(line);
2024
+ }
2025
+ return new _PageState(
2026
+ opts.url,
2027
+ opts.title,
2028
+ shown.map((line) => line.text).join("\n"),
2029
+ new Set(shown.flatMap((line) => line.refs)),
2030
+ new Set(
2031
+ shown.filter((line) => line.disabled).flatMap((line) => line.refs)
2032
+ ),
2033
+ shown.length < lines.length,
2034
+ opts.credentials ?? /* @__PURE__ */ new Set()
2035
+ );
2036
+ }
2037
+ /** `aria` with credential values withheld: every value in and under a
2038
+ * credential field (see `AriaLine.credentialField`; `describe` is
2039
+ * `DESCRIBE_FIELD_JS` of a ref's element), the placeholder aside, and the
2040
+ * value of any line named like a credential. Names, roles and refs stay. */
2041
+ static async redacted(aria, describe2) {
2042
+ const out = [];
2043
+ const withheld = [];
2044
+ let withheldBelow = null;
2045
+ let credentialBelow = null;
2046
+ for (const line of AriaLine.parseAll(aria)) {
2047
+ withheldBelow = deeper(line, withheldBelow);
2048
+ credentialBelow = deeper(line, credentialBelow);
2049
+ if (withheldBelow === null && await line.credentialField(describe2, credentialBelow !== null))
2050
+ withheldBelow = line.indent;
2051
+ if (credentialBelow === null && line.namedLikeCredential)
2052
+ credentialBelow = line.indent;
2053
+ const hidden = withheldBelow !== null || line.namedLikeCredential;
2054
+ out.push(hidden ? line.withheld : line.text);
2055
+ if (hidden) withheld.push(...line.refs);
2056
+ }
2057
+ return { snapshot: out.join("\n"), withheld: new Set(withheld) };
2058
+ }
2059
+ target(ref) {
2060
+ if (!this.refs.has(ref))
2061
+ throw new PageStateError(
2062
+ `ref=${ref} is not in the last browser_snapshot: take a new one`
2063
+ );
2064
+ if (this.disabled.has(ref))
2065
+ throw new PageStateError(`ref=${ref} is disabled`);
2066
+ return `aria-ref=${ref}`;
2067
+ }
2068
+ observation() {
2069
+ return {
2070
+ url: this.url,
2071
+ title: this.title,
2072
+ snapshot: this.snapshot,
2073
+ truncated: this.truncated
2074
+ };
2075
+ }
2076
+ };
2077
+ PageObserver = class {
2078
+ constructor(browser, maxChars = DEFAULT_MAX_CHARS) {
2079
+ this.browser = browser;
2080
+ this.maxChars = maxChars;
2081
+ }
2082
+ browser;
2083
+ maxChars;
2084
+ last = null;
2085
+ seen = [];
2086
+ seenUrl = "";
2087
+ touched = new Touched();
2088
+ turn = Promise.resolve();
2089
+ async snapshot() {
2090
+ return this.inTurn(() => this.takeSnapshot());
2091
+ }
2092
+ async click(selector) {
2093
+ return this.inTurn(() => this.clickOnce(selector));
2094
+ }
2095
+ async type(selector, text2) {
2096
+ return this.inTurn(() => this.typeOnce(selector, text2));
2097
+ }
2098
+ /** One call at a time, so a tool call a model made in parallel cannot act
2099
+ * between another's checks and its action. */
2100
+ inTurn(fn) {
2101
+ const run = this.turn.then(fn, fn);
2102
+ this.turn = run.catch(() => void 0);
2103
+ return run;
2104
+ }
2105
+ async takeSnapshot() {
2106
+ const aria = this.browser.scrubSession(await this.steady());
2107
+ const shown = await PageState.redacted(
2108
+ aria,
2109
+ (ref) => this.browser.describeField(`aria-ref=${ref}`)
2110
+ );
2111
+ const secrets = new CredentialText([
2112
+ ...await this.withheldValues(shown),
2113
+ ...await this.browser.credentialTexts(),
2114
+ ...this.browser.typedCredentials
2115
+ ]);
2116
+ const lines = AriaLine.parseAll(shown.snapshot).map(
2117
+ (line) => line.withheldBy((text2) => secrets.withhold(text2))
2118
+ );
2119
+ this.last = PageState.ofLines(lines, {
2120
+ url: this.url(),
2121
+ title: this.browser.scrub(await this.browser.title()),
2122
+ maxChars: this.maxChars,
2123
+ credentials: shown.withheld
2124
+ });
2125
+ this.seen = AriaLine.parseAll(aria);
2126
+ this.seenUrl = this.browser.scrubSession(this.browser.url);
2127
+ this.touched = new Touched();
2128
+ return this.last;
2129
+ }
2130
+ /** The values of the fields the redaction withheld: a page may repeat them
2131
+ * in another line's name (a row or cell named from its content, a label
2132
+ * that wraps the field). */
2133
+ async withheldValues(shown) {
2134
+ const refs = AriaLine.parseAll(shown.snapshot).filter((line) => line.editable).flatMap((line) => line.refs).filter((ref) => shown.withheld.has(ref));
2135
+ const values = [];
2136
+ for (const ref of refs)
2137
+ values.push(await this.browser.fieldValue(`aria-ref=${ref}`) ?? "");
2138
+ return values;
2139
+ }
2140
+ async clickOnce(selector) {
2141
+ const ref = selectorRef(selector);
2142
+ if (ref === null) return this.browser.click(selector);
2143
+ const [, target] = this.target(ref);
2144
+ await this.ready(target);
2145
+ await this.browser.click(target, { timeoutMs: REF_ACT_TIMEOUT_MS });
2146
+ const left = (await this.now()).find((line) => line.refs.includes(ref));
2147
+ if (left) this.touched = this.touched.afterClick(ref, left.states);
2148
+ }
2149
+ async typeOnce(selector, text2) {
2150
+ const ref = selectorRef(selector);
2151
+ if (ref === null) return this.browser.type(selector, text2);
2152
+ const [last, target] = this.target(ref);
2153
+ const credential = last.credentials.has(ref) || await this.browser.credentialField(target);
2154
+ await this.ready(target);
2155
+ await this.browser.type(target, text2, {
2156
+ timeoutMs: REF_ACT_TIMEOUT_MS,
2157
+ credential
2158
+ });
2159
+ this.touched = this.touched.afterTyping(ref, text2);
2160
+ }
2161
+ target(ref) {
2162
+ if (this.last === null)
2163
+ throw new PageStateError(
2164
+ "ref=\u2026 selectors come from browser_snapshot: take one first"
2165
+ );
2166
+ return [this.last, this.last.target(ref)];
2167
+ }
2168
+ async ready(target) {
2169
+ await this.still();
2170
+ await this.browser.actionable(target);
2171
+ await this.still();
2172
+ }
2173
+ /** A page still rendering when it is read would refuse the model's next
2174
+ * ref, so the snapshot it is shown is one that read the same before and
2175
+ * after the page settled again. */
2176
+ async steady() {
2177
+ const untouched = new Touched();
2178
+ let aria = await this.read();
2179
+ for (let read = 1; read < STEADY_READS; read++) {
2180
+ await this.browser.settle();
2181
+ const again = await this.read();
2182
+ if (sameLines(
2183
+ untouched.actual(AriaLine.parseAll(again)),
2184
+ untouched.actual(AriaLine.parseAll(aria))
2185
+ ))
2186
+ return again;
2187
+ aria = again;
2188
+ }
2189
+ return aria;
2190
+ }
2191
+ async read() {
2192
+ try {
2193
+ return await this.browser.ariaSnapshot();
2194
+ } catch (error) {
2195
+ if (error instanceof TypeError)
2196
+ throw new PageStateError(NEEDS_PLAYWRIGHT);
2197
+ throw error;
2198
+ }
2199
+ }
2200
+ url() {
2201
+ return this.browser.scrub(this.browser.url);
2202
+ }
2203
+ async now() {
2204
+ return AriaLine.parseAll(this.browser.scrubSession(await this.read()));
2205
+ }
2206
+ async still() {
2207
+ if (this.browser.scrubSession(this.browser.url) !== this.seenUrl || !sameLines(
2208
+ this.touched.actual(await this.now()),
2209
+ this.touched.expected(this.seen)
2210
+ ))
2211
+ throw new PageStateError(CHANGED);
2212
+ for (const [ref, text2] of this.touched.typed)
2213
+ if (await this.browser.fieldValue(`aria-ref=${ref}`) !== text2)
2214
+ throw new PageStateError(CHANGED);
2215
+ }
2216
+ };
2217
+ }
2218
+ });
2219
+
2220
+ // src/worlds/browserTools.ts
2221
+ function computerUseToolkit(browser, opts = {}) {
2222
+ const maxText = opts.maxText ?? DEFAULT_MAX_CHARS;
2223
+ const pages = new PageObserver(browser, maxText);
2224
+ const observe2 = async (selector = "body") => {
2225
+ const text2 = browser.scrub(await browser.text(selector));
2226
+ return {
2227
+ url: browser.scrub(browser.url),
2228
+ title: browser.scrub(await browser.title()),
2229
+ text: text2.slice(0, maxText),
2230
+ truncated: text2.length > maxText
2231
+ };
2232
+ };
2233
+ const impls = {
2234
+ browser_goto: async (a) => {
2235
+ await browser.goto(typeof a.path === "string" ? a.path : void 0);
2236
+ return observe2();
2237
+ },
2238
+ browser_snapshot: async () => (await pages.snapshot()).observation(),
2239
+ browser_click: async (a) => {
2240
+ await pages.click(str(a.selector, ""));
2241
+ return observe2();
2242
+ },
2243
+ browser_type: async (a) => {
2244
+ await pages.type(str(a.selector, ""), String(a.text ?? ""));
2245
+ return { ok: true, url: browser.scrub(browser.url) };
2246
+ },
2247
+ browser_press: async (a) => {
2248
+ await browser.press(str(a.key, "Enter"));
2249
+ return observe2();
2250
+ },
2251
+ browser_scroll: async (a) => {
2252
+ await browser.scroll(typeof a.dy === "number" ? a.dy : 600);
2253
+ return { ok: true, url: browser.scrub(browser.url) };
2254
+ },
2255
+ browser_screenshot: async (a) => ({
2256
+ image_base64: await browser.screenshotBase64(a.full_page === true),
2257
+ url: browser.scrub(browser.url)
2258
+ }),
2259
+ browser_read: async (a) => observe2(str(a.selector, "body")),
2260
+ browser_back: async () => {
2261
+ await browser.back();
2262
+ return observe2();
2263
+ }
2264
+ };
2265
+ const specs = COMPUTER_USE_SPECS.map((s) => ({ ...s }));
2266
+ return {
2267
+ schemas: specs.map((spec) => schemaFromSignature(spec)),
2268
+ impls: Object.fromEntries(
2269
+ Object.entries(impls).map(([name, impl]) => [
2270
+ name,
2271
+ scrubbingErrors(browser, impl)
2272
+ ])
2273
+ ),
2274
+ specs
2275
+ };
2276
+ }
2277
+ var COMPUTER_USE_SPECS, scrubbingErrors, str;
2278
+ var init_browserTools = __esm({
2279
+ "src/worlds/browserTools.ts"() {
2280
+ "use strict";
2281
+ init_pageState();
2282
+ init_session2();
1396
2283
  COMPUTER_USE_SPECS = [
1397
2284
  {
1398
2285
  name: "browser_goto",
1399
2286
  signature: "browser_goto(path=None)",
1400
2287
  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."
1401
2288
  },
2289
+ {
2290
+ name: "browser_snapshot",
2291
+ signature: "browser_snapshot()",
2292
+ 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}."
2293
+ },
1402
2294
  {
1403
2295
  name: "browser_click",
1404
2296
  signature: "browser_click(selector)",
1405
- doc: "Click an element by Playwright selector (CSS, `text=Refund`, `role=button[name=Save]`). Returns the page text after the click."
2297
+ 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."
1406
2298
  },
1407
2299
  {
1408
2300
  name: "browser_type",
1409
2301
  signature: "browser_type(selector, text)",
1410
- doc: "Replace the value of an input/textarea found by selector with `text`."
2302
+ doc: "Replace the value of an input/textarea, found by `ref=e3` or by selector, with `text`."
1411
2303
  },
1412
2304
  {
1413
2305
  name: "browser_press",
@@ -1435,6 +2327,14 @@ var init_browser = __esm({
1435
2327
  doc: "Go back one page in history."
1436
2328
  }
1437
2329
  ];
2330
+ scrubbingErrors = (browser, impl) => async (args) => {
2331
+ try {
2332
+ return await impl(args);
2333
+ } catch (error) {
2334
+ browser.scrubError(error);
2335
+ throw error;
2336
+ }
2337
+ };
1438
2338
  str = (v, fallback) => typeof v === "string" && v.length > 0 ? v : fallback;
1439
2339
  }
1440
2340
  });
@@ -1579,13 +2479,12 @@ function isNativePage(page) {
1579
2479
  const mouse = candidate?.mouse;
1580
2480
  return typeof candidate?.context === "function" && NATIVE_METHODS.every((m) => typeof mouse?.[m] === "function");
1581
2481
  }
1582
- var FOCUSED_FIELD_JS, SECRET_FOCUS, DRAG_STEPS, PNG_SIGNATURE, NATIVE_METHODS, Screen;
2482
+ var FOCUSED_FIELD_JS, DRAG_STEPS, PNG_SIGNATURE, NATIVE_METHODS, Screen;
1583
2483
  var init_screen = __esm({
1584
2484
  "src/worlds/nativeComputer/screen.ts"() {
1585
2485
  "use strict";
1586
- init_browser();
1587
- 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(' '); })()";
1588
- SECRET_FOCUS = ["password", "frame", "opaque"];
2486
+ init_credentialField();
2487
+ 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); })()`;
1589
2488
  DRAG_STEPS = 5;
1590
2489
  PNG_SIGNATURE = Buffer.from([
1591
2490
  137,
@@ -1676,7 +2575,7 @@ var init_screen = __esm({
1676
2575
  } catch {
1677
2576
  return true;
1678
2577
  }
1679
- return SECRET_FOCUS.some((prefix) => described.startsWith(prefix)) || SECRET_KEY.test(described);
2578
+ return isCredentialField(described);
1680
2579
  }
1681
2580
  /** CDP renders a clip at the page's device pixel ratio as well as its
1682
2581
  * `scale` (a Retina host doubles it), so a capture of the wrong width
@@ -1907,11 +2806,11 @@ var init_media = __esm({
1907
2806
  status
1908
2807
  );
1909
2808
  }
1910
- async send(method, route, body) {
1911
- const reply = await this.transport.send(method, route, body);
2809
+ async send(method, route2, body) {
2810
+ const reply = await this.transport.send(method, route2, body);
1912
2811
  if (!reply.ok)
1913
2812
  throw new MediaUploadError(
1914
- `${method} ${route} -> ${reply.status}`,
2813
+ `${method} ${route2} -> ${reply.status}`,
1915
2814
  reply.status
1916
2815
  );
1917
2816
  return reply.text ? JSON.parse(reply.text) : {};
@@ -2264,7 +3163,7 @@ function click(button, count) {
2264
3163
  modifiers: modifierChord(raw.text)
2265
3164
  });
2266
3165
  }
2267
- var SCROLL_STEP_PX, NOT_EXECUTED, MAX_ERROR2, SCROLL_DIRECTIONS, MEMBERS, AnthropicComputer, AnthropicComputer20251124;
3166
+ var SCROLL_STEP_PX, NOT_EXECUTED, MAX_ERROR2, SCROLL_DIRECTIONS, IMAGE_PARTS, MEMBERS, AnthropicComputer, AnthropicComputer20251124;
2268
3167
  var init_anthropic = __esm({
2269
3168
  "src/worlds/nativeComputer/anthropic.ts"() {
2270
3169
  "use strict";
@@ -2280,6 +3179,14 @@ var init_anthropic = __esm({
2280
3179
  left: [-1, 0],
2281
3180
  right: [1, 0]
2282
3181
  };
3182
+ IMAGE_PARTS = {
3183
+ 6: (data) => ({ type: "image-data", data, mediaType: "image/png" }),
3184
+ 7: (data) => ({
3185
+ type: "file",
3186
+ mediaType: "image/png",
3187
+ data: { type: "data", data }
3188
+ })
3189
+ };
2283
3190
  MEMBERS = {
2284
3191
  screenshot: () => new ComputerAction("screenshot"),
2285
3192
  zoom: (raw) => new ComputerAction("zoom", {
@@ -2389,15 +3296,17 @@ var init_anthropic = __esm({
2389
3296
  ];
2390
3297
  return [{ type: "text", text: result.text ?? "OK" }];
2391
3298
  }
2392
- /** For `anthropic.tools.computerToolset_20260801({ ...computer.aiSdk() })`
2393
- * (or `computer_20251124` with the legacy kind): `execute` runs one action
2394
- * and returns `{ type: "image", data }` or text; `toModelOutput` turns that
2395
- * into the tool result. Calls run one at a time, and once a call fails the
3299
+ /** For `anthropic.tools.computerToolset_20260801(computer.aiSdk({ version: 7 }))`
3300
+ * (AI SDK 7 only), or `computer_20251124` with the legacy kind (AI SDK 6
3301
+ * and 7): `execute` runs one action and returns `{ type: "image", data }` or
3302
+ * text; `toModelOutput` turns that into the tool result in the part shape
3303
+ * of `options.version`. Calls run one at a time, and once a call fails the
2396
3304
  * rest of that step's calls answer as not executed. */
2397
- aiSdk() {
3305
+ aiSdk(options = {}) {
3306
+ const imagePart = _AnthropicComputer.imagePart(options);
2398
3307
  let failedStep;
2399
- const execute = (input, options) => this.serial(async () => {
2400
- const step = options?.messages?.length;
3308
+ const execute = (input, options2) => this.serial(async () => {
3309
+ const step = options2?.messages?.length;
2401
3310
  if (step !== void 0 && step === failedStep)
2402
3311
  throw new Error(NOT_EXECUTED);
2403
3312
  try {
@@ -2409,7 +3318,7 @@ var init_anthropic = __esm({
2409
3318
  });
2410
3319
  return {
2411
3320
  execute,
2412
- toModelOutput: ({ output }) => _AnthropicComputer.aiSdkModelOutput(output)
3321
+ toModelOutput: ({ output }) => _AnthropicComputer.modelOutput(output, imagePart)
2413
3322
  };
2414
3323
  }
2415
3324
  static aiSdkOutput(result) {
@@ -2417,16 +3326,26 @@ var init_anthropic = __esm({
2417
3326
  return { type: "image", data: result.image.toString("base64") };
2418
3327
  return result.text ?? "OK";
2419
3328
  }
2420
- /** `image-data` is what AI SDK 6's Anthropic provider turns into an image
2421
- * block; AI SDK 7 still accepts it (and converts it to a `file` part). */
2422
- static aiSdkModelOutput(output) {
3329
+ /** A screenshot as the image part of AI SDK `options.version`:
3330
+ * `image-data` for 6 (the default), `file` with `{ type: "data", data }`
3331
+ * for 7. */
3332
+ static aiSdkModelOutput(output, options = {}) {
3333
+ return _AnthropicComputer.modelOutput(
3334
+ output,
3335
+ _AnthropicComputer.imagePart(options)
3336
+ );
3337
+ }
3338
+ static imagePart({
3339
+ version = 6
3340
+ }) {
3341
+ if (Object.hasOwn(IMAGE_PARTS, version)) return IMAGE_PARTS[version];
3342
+ throw new Error(
3343
+ `unsupported AI SDK version ${version}; choose ${Object.keys(IMAGE_PARTS).join(" or ")}`
3344
+ );
3345
+ }
3346
+ static modelOutput(output, imagePart) {
2423
3347
  if (typeof output === "string") return { type: "text", value: output };
2424
- return {
2425
- type: "content",
2426
- value: [
2427
- { type: "image-data", data: output.data, mediaType: "image/png" }
2428
- ]
2429
- };
3348
+ return { type: "content", value: [imagePart(output.data)] };
2430
3349
  }
2431
3350
  envelope(block, content, isError = false) {
2432
3351
  return {
@@ -2834,7 +3753,7 @@ var init_requestLedger = __esm({
2834
3753
  "use strict";
2835
3754
  init_worlds();
2836
3755
  init_sessionContract();
2837
- WORLD_REQUEST_VIAS = ["api", "ui", "tool"];
3756
+ WORLD_REQUEST_VIAS = ["api", "ui", "tool", "webhook", "page"];
2838
3757
  WorldRequestFilterError = class extends Error {
2839
3758
  };
2840
3759
  NOT_RECORDED = "This session's engine records no requests; only hosted World Host sessions do.";
@@ -3342,7 +4261,8 @@ async function openSession(slugOrRef, taskOrOpts = {}, positionalOpts = {}) {
3342
4261
  ...opts.reuseWarm === void 0 ? {} : { reuseWarm: opts.reuseWarm },
3343
4262
  ...opts.surfaces?.length ? { surfaces: opts.surfaces } : {},
3344
4263
  ...opts.browserTier === void 0 ? {} : { browserTier: opts.browserTier },
3345
- ...opts.auth === void 0 ? {} : { auth: opts.auth }
4264
+ ...opts.auth === void 0 ? {} : { auth: opts.auth },
4265
+ ...opts.worldState === void 0 ? {} : { worldState: opts.worldState }
3346
4266
  }
3347
4267
  );
3348
4268
  return new WorldSession(state2.sessionId, state2, options);
@@ -3430,6 +4350,7 @@ var init_session2 = __esm({
3430
4350
  import_node_crypto2 = require("crypto");
3431
4351
  init_worlds();
3432
4352
  init_browser();
4353
+ init_browserTools();
3433
4354
  init_nativeComputer();
3434
4355
  init_sessionContract();
3435
4356
  init_toolSchema();
@@ -3495,6 +4416,9 @@ var init_session2 = __esm({
3495
4416
  get versionId() {
3496
4417
  return this.current.versionId;
3497
4418
  }
4419
+ get worldState() {
4420
+ return this.current.worldState ?? null;
4421
+ }
3498
4422
  /** Whether the session answered ready as of the last state read (the open,
3499
4423
  * a `status()`, or the poll inside `ready()`); no request is made. */
3500
4424
  get isReady() {
@@ -3766,13 +4690,13 @@ var init_session2 = __esm({
3766
4690
  WorldRequestQuery.parse({ cursor: opts.cursor, limit: opts.limit ?? REQUEST_LOG_PAGE_MAX })
3767
4691
  );
3768
4692
  }
3769
- page(route, limit, cursor) {
4693
+ page(route2, limit, cursor) {
3770
4694
  const query = new URLSearchParams({ limit: String(limit) });
3771
4695
  if (cursor) query.set("cursor", cursor);
3772
4696
  return apiRequest(
3773
4697
  this.options,
3774
4698
  "GET",
3775
- `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/${route}?${query.toString()}`
4699
+ `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/${route2}?${query.toString()}`
3776
4700
  );
3777
4701
  }
3778
4702
  /** The session's call log, oldest first: every tool call, seed, reset,
@@ -3864,6 +4788,7 @@ var init_session2 = __esm({
3864
4788
  "surfaces",
3865
4789
  "browserTier",
3866
4790
  "auth",
4791
+ "worldState",
3867
4792
  "options"
3868
4793
  ]);
3869
4794
  isOpenSessionOptions = (value) => typeof value === "object" && value !== null && Object.keys(value).every((key2) => OPEN_SESSION_OPTION_KEYS.has(key2));
@@ -4107,7 +5032,8 @@ async function openTask(ref, opts = {}) {
4107
5032
  task,
4108
5033
  ...opts.reuseWarm === void 0 ? {} : { reuseWarm: opts.reuseWarm },
4109
5034
  ...opts.surfaces?.length ? { surfaces: opts.surfaces } : {},
4110
- ...opts.browserTier === void 0 ? {} : { browserTier: opts.browserTier }
5035
+ ...opts.browserTier === void 0 ? {} : { browserTier: opts.browserTier },
5036
+ ...opts.worldStates === void 0 ? {} : { worldStates: opts.worldStates }
4111
5037
  }
4112
5038
  );
4113
5039
  return fromResponse(answer, options);
@@ -4365,16 +5291,22 @@ var init_evals = __esm({
4365
5291
  "src/worlds/evals.ts"() {
4366
5292
  "use strict";
4367
5293
  init_worlds();
5294
+ init_personalToken();
5295
+ init_platformEndpoint();
4368
5296
  init_transport();
4369
5297
  EVALUATIONS = "/api/public/benchmark-containers/evaluations";
4370
- GatewayEvalsClient = class {
5298
+ GatewayEvalsClient = class _GatewayEvalsClient {
4371
5299
  constructor(options = {}, retry = RetryPolicy.FILING) {
4372
5300
  this.options = options;
4373
5301
  this.retry = retry;
5302
+ _GatewayEvalsClient.refuseToken(options);
4374
5303
  }
4375
5304
  options;
4376
5305
  retry;
4377
5306
  keyed = /* @__PURE__ */ new Set();
5307
+ static refuseToken(options) {
5308
+ if (platformEndpoint(options)?.token) throw new PersonalTokenRefused(TOKEN_FILING);
5309
+ }
4378
5310
  async createEvaluation(versionId, opts = {}) {
4379
5311
  const body = { versionId };
4380
5312
  if (opts.model !== void 0) body.model = opts.model;
@@ -5057,7 +5989,7 @@ var require_package = __commonJS({
5057
5989
  "package.json"(exports2, module2) {
5058
5990
  module2.exports = {
5059
5991
  name: "@withgateway/sdk",
5060
- version: "0.4.0",
5992
+ version: "0.9.1",
5061
5993
  description: "Gateway SDK for TypeScript - A/B experiments, tracing, and observability",
5062
5994
  main: "./dist/index.js",
5063
5995
  module: "./dist/index.mjs",
@@ -5138,6 +6070,11 @@ var require_package = __commonJS({
5138
6070
  import: "./dist/hooks/index.mjs",
5139
6071
  require: "./dist/hooks/index.js"
5140
6072
  },
6073
+ "./agents": {
6074
+ types: "./dist/agents/index.d.ts",
6075
+ import: "./dist/agents/index.mjs",
6076
+ require: "./dist/agents/index.js"
6077
+ },
5141
6078
  "./cli": {
5142
6079
  types: "./dist/cli.d.ts",
5143
6080
  import: "./dist/cli.mjs",
@@ -5833,6 +6770,7 @@ var init_taskTracing = __esm({
5833
6770
  "use strict";
5834
6771
  init_prerequisites();
5835
6772
  init_platformEndpoint();
6773
+ init_personalToken();
5836
6774
  HOST_WITH_AUTHORITY = /^[a-z][a-z0-9+.-]*:\/\/[^/\\?#@\s]+(\/|$)/i;
5837
6775
  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.";
5838
6776
  TaskTracing = class _TaskTracing {
@@ -5844,8 +6782,9 @@ var init_taskTracing = __esm({
5844
6782
  static target = null;
5845
6783
  async start(requested, options) {
5846
6784
  if (!requested) return false;
5847
- const endpoint = platformEndpoint(options);
6785
+ let endpoint = null;
5848
6786
  try {
6787
+ endpoint = platformEndpoint(options);
5849
6788
  await this.initOnce(_TaskTracing.config(endpoint));
5850
6789
  return true;
5851
6790
  } catch (error) {
@@ -5867,6 +6806,7 @@ var init_taskTracing = __esm({
5867
6806
  }
5868
6807
  static config(endpoint) {
5869
6808
  if (!endpoint) throw new Error(GATEWAY_KEYS_MISSING);
6809
+ if (endpoint.token) throw new Error(TOKEN_KEYS_ONLY);
5870
6810
  return { ...endpoint, endpoint: _TaskTracing.destination(endpoint) };
5871
6811
  }
5872
6812
  // B1: a saved login's keys go to their own host only. The redirect is compared as text, never parsed:
@@ -5897,7 +6837,9 @@ Pass --no-trace (trace: false) to run untraced without this warning.`
5897
6837
  static reason(error, endpoint) {
5898
6838
  if (OpenTelemetryMissing.explains(error)) return new OpenTelemetryMissing().message;
5899
6839
  const message = error instanceof Error ? error.message : String(error);
5900
- const keys = endpoint ? [endpoint.publicKey, endpoint.secretKey] : [];
6840
+ const keys = [endpoint?.publicKey, endpoint?.secretKey, endpoint?.token?.value].filter(
6841
+ (key2) => Boolean(key2)
6842
+ );
5901
6843
  return keys.reduce((text2, key2) => text2.split(key2).join("[redacted]"), message);
5902
6844
  }
5903
6845
  };
@@ -5942,13 +6884,15 @@ async function refuseUnreadTools(live) {
5942
6884
  }
5943
6885
  }
5944
6886
  async function runTask(ref, agent, opts) {
5945
- const runId = `wtr-${(0, import_node_crypto4.randomBytes)(6).toString("hex")}`;
5946
6887
  const options = opts.options ?? {};
6888
+ if (opts.file !== false) GatewayEvalsClient.refuseToken(options);
6889
+ const runId = `wtr-${(0, import_node_crypto4.randomBytes)(6).toString("hex")}`;
5947
6890
  const opening = new TaskOpening(
5948
6891
  openTask(ref, {
5949
6892
  surfaces: opts.surfaces,
5950
6893
  reuseWarm: opts.reuseWarm,
5951
6894
  browserTier: opts.browserTier,
6895
+ worldStates: opts.worldStates,
5952
6896
  options
5953
6897
  }).then(async (live) => {
5954
6898
  await refuseUnreadTools(live);
@@ -6230,6 +7174,7 @@ var init_checkoutProvenance = __esm({
6230
7174
  // src/worlds/setRun.ts
6231
7175
  async function runSet(datasetId, agent, opts) {
6232
7176
  const options = opts.options ?? {};
7177
+ GatewayEvalsClient.refuseToken(options);
6233
7178
  const git = opts.git === void 0 ? CheckoutProvenance.read() : opts.git;
6234
7179
  const opened = await apiRequest(options, "POST", SET_RUNS, {
6235
7180
  datasetId,
@@ -6245,6 +7190,7 @@ var init_setRun = __esm({
6245
7190
  "use strict";
6246
7191
  init_worlds();
6247
7192
  init_checkoutProvenance();
7193
+ init_evals();
6248
7194
  init_runSignals();
6249
7195
  init_taskRun();
6250
7196
  SET_RUNS = "/api/public/set-runs";
@@ -6419,6 +7365,112 @@ var init_requestLog = __esm({
6419
7365
  }
6420
7366
  });
6421
7367
 
7368
+ // src/worlds/webhooks.ts
7369
+ async function listWebhooks(options, sessionId, page = {}) {
7370
+ const query = new URLSearchParams({
7371
+ after: String(page.after ?? 0),
7372
+ limit: String(page.limit ?? WORLD_WEBHOOK_PAGE_MAX),
7373
+ tail: String(page.tail ?? false)
7374
+ });
7375
+ if (page.epoch) query.set("epoch", page.epoch);
7376
+ return apiRequest(options, "GET", `${route(sessionId)}?${query.toString()}`);
7377
+ }
7378
+ var WORLD_WEBHOOK_PAGE_MAX, FORWARD_TIMEOUT_MS, ERROR_CHARS, route, WorldWebhookForwarder;
7379
+ var init_webhooks = __esm({
7380
+ "src/worlds/webhooks.ts"() {
7381
+ "use strict";
7382
+ init_worlds();
7383
+ WORLD_WEBHOOK_PAGE_MAX = 100;
7384
+ FORWARD_TIMEOUT_MS = 1e4;
7385
+ ERROR_CHARS = 500;
7386
+ route = (sessionId) => `/api/public/world-sessions/${encodeURIComponent(sessionId)}/webhooks`;
7387
+ WorldWebhookForwarder = class {
7388
+ constructor(options, sessionId, forwardTo, opts = {}) {
7389
+ this.options = options;
7390
+ this.sessionId = sessionId;
7391
+ this.forwardTo = forwardTo;
7392
+ this.send = opts.fetch ?? fetch;
7393
+ }
7394
+ options;
7395
+ sessionId;
7396
+ forwardTo;
7397
+ after = 0;
7398
+ epoch = null;
7399
+ answers = [];
7400
+ send;
7401
+ get cursor() {
7402
+ return this.after;
7403
+ }
7404
+ /** Where forwarding begins: the deliveries the session still holds (`replay`), or only those it sends from now. */
7405
+ async start(replay2) {
7406
+ if (replay2) return null;
7407
+ const page = await this.poll([], { tail: true, limit: 1 });
7408
+ this.follow(page);
7409
+ return page;
7410
+ }
7411
+ /** One poll: the answers held so far sent, the next page forwarded. A poll that fails keeps its answers for the next. */
7412
+ async round() {
7413
+ const page = await this.withAnswers((answers) => this.poll(answers));
7414
+ const forwarded = [];
7415
+ for (const delivery of page.deliveries) {
7416
+ const answer = await this.forward(delivery);
7417
+ this.answers.push(answer);
7418
+ forwarded.push({ delivery, answer });
7419
+ }
7420
+ this.follow(page);
7421
+ return { page, forwarded };
7422
+ }
7423
+ /** Sends the answers still held; the cursor stays, so a delivery this poll returns is forwarded by the next round. */
7424
+ async settle() {
7425
+ if (this.answers.length === 0) return 0;
7426
+ const page = await this.withAnswers((answers) => this.poll(answers, { limit: 1 }));
7427
+ return page.answered;
7428
+ }
7429
+ follow(page) {
7430
+ this.after = page.next;
7431
+ this.epoch = page.epoch;
7432
+ }
7433
+ async withAnswers(poll) {
7434
+ const answers = this.answers.splice(0, WORLD_WEBHOOK_PAGE_MAX);
7435
+ try {
7436
+ return await poll(answers);
7437
+ } catch (error) {
7438
+ this.answers.unshift(...answers);
7439
+ throw error;
7440
+ }
7441
+ }
7442
+ poll(answers, opts = {}) {
7443
+ return apiRequest(this.options, "POST", route(this.sessionId), {
7444
+ after: this.after,
7445
+ epoch: this.epoch,
7446
+ tail: opts.tail ?? false,
7447
+ limit: opts.limit ?? WORLD_WEBHOOK_PAGE_MAX,
7448
+ subscriptions: false,
7449
+ answers
7450
+ });
7451
+ }
7452
+ async forward(delivery) {
7453
+ const started = Date.now();
7454
+ try {
7455
+ const reply = await this.send(this.forwardTo, {
7456
+ method: "POST",
7457
+ headers: delivery.headers,
7458
+ body: delivery.payload,
7459
+ redirect: "manual",
7460
+ signal: AbortSignal.timeout(FORWARD_TIMEOUT_MS)
7461
+ });
7462
+ await reply.arrayBuffer().catch(() => void 0);
7463
+ if (reply.status < 100 || reply.status > 599) throw new Error("the receiver answered an invalid HTTP status");
7464
+ return { id: delivery.id, status: reply.status, durationMs: Date.now() - started, error: null };
7465
+ } catch (error) {
7466
+ const message = error instanceof Error ? error.message : String(error);
7467
+ return { id: delivery.id, status: 0, durationMs: Date.now() - started, error: message.slice(0, ERROR_CHARS) };
7468
+ }
7469
+ }
7470
+ };
7471
+ }
7472
+ });
7473
+
6422
7474
  // src/worlds/checkoutTarget.ts
6423
7475
  var fs2, path3, CheckoutRefusedError, NAMED_EDITS, CheckoutTarget;
6424
7476
  var init_checkoutTarget = __esm({
@@ -6523,7 +7575,7 @@ var init_checkoutTarget = __esm({
6523
7575
  });
6524
7576
 
6525
7577
  // src/worlds/worldDir.ts
6526
- var import_node_crypto5, fs3, path4, 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;
7578
+ var import_node_crypto5, fs3, path4, 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;
6527
7579
  var init_worldDir = __esm({
6528
7580
  "src/worlds/worldDir.ts"() {
6529
7581
  "use strict";
@@ -6532,13 +7584,14 @@ var init_worldDir = __esm({
6532
7584
  path4 = __toESM(require("path"));
6533
7585
  WORLD_MANIFEST = "gateway-env.toml";
6534
7586
  API_BUNDLE_MANIFEST = "gateway-api-world.toml";
7587
+ BUNDLE_MANIFEST = "gateway-bundle.toml";
6535
7588
  BUNDLED_WORLD_PREFIX = "server/world/";
6536
7589
  CONNECTOR_SPEC = "connector.toml";
6537
7590
  PYPROJECT = "pyproject.toml";
6538
7591
  BENCHMARK_CONFIG = "benchmark.json";
6539
7592
  WORLD_SCHEMA_MARKERS = ["schema/world.json", "schema/runtime.json", "schema/lock.json"];
6540
7593
  WORLD_ROOT_MARKERS = [CONNECTOR_SPEC, ...WORLD_SCHEMA_MARKERS];
6541
- BROAD_ROOT_MARKERS = [WORLD_MANIFEST, API_BUNDLE_MANIFEST, BENCHMARK_CONFIG];
7594
+ BROAD_ROOT_MARKERS = [WORLD_MANIFEST, API_BUNDLE_MANIFEST, BENCHMARK_CONFIG, BUNDLE_MANIFEST];
6542
7595
  SKIPPED_DIRS = /* @__PURE__ */ new Set(["dist", "build", "outputs", "__pycache__", "node_modules"]);
6543
7596
  V1_DEP = /["']verifiers\s*(?:\[[^\]]*\])?\s*(?:>=|~=|==|>)\s*(?:0\.(?:[2-9]\d*|[1-9]\d+)|[1-9]\d*)/;
6544
7597
  V1_IMPORT = /^\s*(?:from\s+verifiers\.v1\s+import\b|from\s+verifiers\s+import\s+v1\b|import\s+verifiers\.v1\b)/m;
@@ -6559,7 +7612,6 @@ var init_worldDir = __esm({
6559
7612
  const bundled = present(API_BUNDLE_MANIFEST) && WORLD_ROOT_MARKERS.some((m) => present(BUNDLED_WORLD_PREFIX + m));
6560
7613
  return new _WorldDir(dir, bundled ? BUNDLED_WORLD_PREFIX : "");
6561
7614
  }
6562
- // ── Files ──────────────────────────────────────────────────────────────
6563
7615
  has(rel) {
6564
7616
  return fs3.existsSync(path4.join(this.dir, rel));
6565
7617
  }
@@ -6570,15 +7622,9 @@ var init_worldDir = __esm({
6570
7622
  return null;
6571
7623
  }
6572
7624
  }
6573
- /** A path under the authored world's root. */
6574
7625
  worldPath(rel) {
6575
7626
  return this.worldRoot + rel;
6576
7627
  }
6577
- /** Every regular file the archive rules keep (`_archive.py`: no hidden,
6578
- * dist, build, outputs, pycache, node_modules or egg-info directories), as
6579
- * sorted relpaths. Root files enter only when a Gateway manifest or
6580
- * benchmark.json widens the root, or they are README.md, pyproject.toml or
6581
- * Python. */
6582
7628
  get archivePaths() {
6583
7629
  if (this.pathsMemo) return this.pathsMemo;
6584
7630
  const broad = BROAD_ROOT_MARKERS.some((m) => this.has(m));
@@ -6597,11 +7643,6 @@ var init_worldDir = __esm({
6597
7643
  walk("");
6598
7644
  return this.pathsMemo = out.sort(byCodePoint);
6599
7645
  }
6600
- /** What the archive rules leave out, collapsed to the entry that decided
6601
- * it: a pruned directory counts its files once, a dropped root file is
6602
- * named. Dot entries (`.git/`, `.gateway/`, `.gitignore`) are the one
6603
- * universal convention and stay unreported. `push` prints the rest so
6604
- * nothing disappears silently. */
6605
7646
  get exclusions() {
6606
7647
  const kept = new Set(this.archivePaths);
6607
7648
  const out = [];
@@ -6624,14 +7665,11 @@ var init_worldDir = __esm({
6624
7665
  }
6625
7666
  return out;
6626
7667
  }
6627
- /** A root `.gitignore` is present: the Python SDK honours it when
6628
- * collecting, this package does not reimplement gitignore. */
7668
+ /** The Python SDK honours a root `.gitignore` when collecting; this package does not reimplement gitignore. */
6629
7669
  get hasRootGitignore() {
6630
7670
  return this.has(".gitignore");
6631
7671
  }
6632
- /** SHA-256 over `utf8("file:" + relpath)` + bytes per archive path in
6633
- * sorted order: the version's identity, byte-compatible with
6634
- * `_archive.compute_content_hash` and Prime Intellect. */
7672
+ /** The version's identity, byte-compatible with the Python SDK's `compute_content_hash` and Prime Intellect's hub. */
6635
7673
  get contentHash() {
6636
7674
  const hasher = (0, import_node_crypto5.createHash)("sha256");
6637
7675
  for (const rel of this.archivePaths) {
@@ -6640,18 +7678,18 @@ var init_worldDir = __esm({
6640
7678
  }
6641
7679
  return hasher.digest("hex");
6642
7680
  }
6643
- // ── Markers ────────────────────────────────────────────────────────────
6644
7681
  get isApiBundle() {
6645
7682
  return this.has(API_BUNDLE_MANIFEST);
6646
7683
  }
7684
+ get isWorldBundle() {
7685
+ return this.has(BUNDLE_MANIFEST);
7686
+ }
6647
7687
  get hasManifest() {
6648
7688
  return this.has(this.worldPath(WORLD_MANIFEST));
6649
7689
  }
6650
7690
  get hasSchemaMarker() {
6651
7691
  return WORLD_SCHEMA_MARKERS.some((m) => this.has(this.worldPath(m)));
6652
7692
  }
6653
- /** Harbor task dirs, relative to the tree: `tasks/<name>` when a `tasks/`
6654
- * dir holds them, else the root `<name>` dirs. */
6655
7693
  taskDirs() {
6656
7694
  const names = /* @__PURE__ */ new Set();
6657
7695
  for (const rel of this.archivePaths) {
@@ -6661,8 +7699,6 @@ var init_worldDir = __esm({
6661
7699
  const under = [...names].filter((n) => n.startsWith("tasks/"));
6662
7700
  return (under.length ? under : [...names]).sort();
6663
7701
  }
6664
- /** The Python package of a verifiers tree (`<pkg>/__init__.py` or
6665
- * `src/<pkg>/__init__.py`), or null. */
6666
7702
  pythonPackage() {
6667
7703
  if (!this.has(PYPROJECT)) return null;
6668
7704
  for (const base of ["", "src/"]) {
@@ -6674,8 +7710,6 @@ var init_worldDir = __esm({
6674
7710
  }
6675
7711
  return null;
6676
7712
  }
6677
- /** The package targets the `verifiers.v1` API: read from the root
6678
- * pyproject and every archived Python module. */
6679
7713
  get isVerifiersV1() {
6680
7714
  for (const rel of this.archivePaths) {
6681
7715
  if (rel !== PYPROJECT && !rel.endsWith(".py")) continue;
@@ -6686,11 +7720,9 @@ var init_worldDir = __esm({
6686
7720
  }
6687
7721
  return false;
6688
7722
  }
6689
- // ── The answer ─────────────────────────────────────────────────────────
6690
- /** The runner's kind (`detect_env_kind`): api / mock-tools win over
6691
- * everything, a harbor task tree next, then the verifiers API version. */
6692
7723
  get kind() {
6693
7724
  if (this.isApiBundle) return "api";
7725
+ if (this.isWorldBundle) return "bundle";
6694
7726
  if (this.has(WORLD_MANIFEST)) return "mock-tools";
6695
7727
  if (this.taskDirs().length) return "harbor";
6696
7728
  return this.isVerifiersV1 ? "verifiers-v1" : "verifiers";
@@ -7028,8 +8060,7 @@ async function push(dir, opts = {}) {
7028
8060
  const metadata = {
7029
8061
  ...opts.name !== void 0 ? { name: opts.name } : {},
7030
8062
  ...opts.description !== void 0 ? { description: opts.description } : {},
7031
- ...opts.tags !== void 0 ? { tags: opts.tags } : {},
7032
- ...opts.visibility ? { visibility: opts.visibility } : {}
8063
+ ...opts.tags !== void 0 ? { tags: opts.tags } : {}
7033
8064
  };
7034
8065
  const resolve11 = await apiRequest(
7035
8066
  options,
@@ -7561,7 +8592,7 @@ var init_sandbox = __esm({
7561
8592
  /**
7562
8593
  * `{ slug, ref? }` opens a READY version; `{ new, from }` opens a sandbox on
7563
8594
  * a world that does not exist yet (409 `world_exists` if the slug is taken,
7564
- * 400 naming the shipped templates if `from` is unknown). Its first commit
8595
+ * 400 naming the official templates if `from` is unknown). Its first commit
7565
8596
  * creates the world on `main`.
7566
8597
  */
7567
8598
  open(target) {
@@ -8206,6 +9237,7 @@ var CliError;
8206
9237
  var init_router = __esm({
8207
9238
  "src/cli/router.ts"() {
8208
9239
  "use strict";
9240
+ init_personalToken();
8209
9241
  CliError = class extends Error {
8210
9242
  constructor(message, exitCode = 2) {
8211
9243
  super(message);
@@ -8217,12 +9249,52 @@ var init_router = __esm({
8217
9249
  });
8218
9250
 
8219
9251
  // src/cli/config.ts
8220
- async function api(creds, method, route, body, init3 = {}) {
8221
- const reply = await new PlatformTransport(creds).send(method, route, body, init3);
8222
- if (!reply.ok) throw new ApiError2(reply.status, method, route, reply.text);
9252
+ function configPath() {
9253
+ return path7.join(process.env.GATEWAY_CONFIG_DIR || path7.join(os.homedir(), ".gateway"), "config.json");
9254
+ }
9255
+ function readConfig() {
9256
+ let stored;
9257
+ try {
9258
+ stored = JSON.parse(fs6.readFileSync(configPath(), "utf8"));
9259
+ } catch {
9260
+ return {};
9261
+ }
9262
+ const record = stored ?? {};
9263
+ return Object.fromEntries(STORED_FIELDS.filter((f) => typeof record[f] === "string").map((f) => [f, record[f]]));
9264
+ }
9265
+ function personalToken(request = {}) {
9266
+ try {
9267
+ return PersonalToken.fromEnv(process.env, request);
9268
+ } catch (error) {
9269
+ if (error instanceof PersonalTokenRefused) throw new CliError(error.message);
9270
+ throw error;
9271
+ }
9272
+ }
9273
+ function resolveCredentials(hostFlag, secretKeyFlag) {
9274
+ const token = personalToken({ host: hostFlag || void 0, keys: Boolean(secretKeyFlag) });
9275
+ if (token) return { host: token.host, publicKey: "", secretKey: "", token };
9276
+ const stored = readConfig();
9277
+ const explicitHost = (hostFlag || process.env.GATEWAY_HOST || "").replace(/\/+$/, "");
9278
+ const host = explicitHost || (stored.host ?? "").replace(/\/+$/, "");
9279
+ if (!host)
9280
+ throw new CredentialsMissing(
9281
+ "Host not configured. Pass --host, set GATEWAY_HOST, or run `gateway auth login`."
9282
+ );
9283
+ const login = host === (stored.host ?? "").replace(/\/+$/, "") ? stored : {};
9284
+ const publicKey = process.env.GATEWAY_PUBLIC_KEY || login.public_key || "";
9285
+ const secretKey = secretKeyFlag || process.env.GATEWAY_SECRET_KEY || process.env.GATEWAY_API_KEY || login.api_key || "";
9286
+ if (!publicKey || !secretKey)
9287
+ throw new CredentialsMissing(
9288
+ "API key not configured. Set GATEWAY_PUBLIC_KEY and GATEWAY_SECRET_KEY, or run `gateway auth login`."
9289
+ );
9290
+ return { host, publicKey, secretKey };
9291
+ }
9292
+ async function api(creds, method, route2, body, init3 = {}) {
9293
+ const reply = await new PlatformTransport(creds).send(method, route2, body, init3);
9294
+ if (!reply.ok) throw new ApiError2(reply.status, method, route2, reply.text);
8223
9295
  return reply.text ? JSON.parse(reply.text) : {};
8224
9296
  }
8225
- var fs6, os, path7, ApiError2;
9297
+ var fs6, os, path7, STORED_FIELDS, CredentialsMissing, ApiError2;
8226
9298
  var init_config = __esm({
8227
9299
  "src/cli/config.ts"() {
8228
9300
  "use strict";
@@ -8231,14 +9303,18 @@ var init_config = __esm({
8231
9303
  path7 = __toESM(require("path"));
8232
9304
  init_router();
8233
9305
  init_worlds();
9306
+ init_personalToken();
8234
9307
  init_transport();
9308
+ STORED_FIELDS = ["host", "public_key", "api_key"];
9309
+ CredentialsMissing = class extends CliError {
9310
+ };
8235
9311
  ApiError2 = class extends CliError {
8236
- constructor(status, method, route, text2) {
9312
+ constructor(status, method, route2, text2) {
8237
9313
  const body = parseErrorBody(text2, status);
8238
- super(`${method} ${route} -> ${status}: ${body.detail}`, 1);
9314
+ super(`${method} ${route2} -> ${status}: ${body.detail}`, 1);
8239
9315
  this.status = status;
8240
9316
  this.method = method;
8241
- this.route = route;
9317
+ this.route = route2;
8242
9318
  this.text = text2;
8243
9319
  this.code = body.code;
8244
9320
  }
@@ -8251,7 +9327,37 @@ var init_config = __esm({
8251
9327
  }
8252
9328
  });
8253
9329
 
9330
+ // src/worlds/isolatedPython.ts
9331
+ function isolatedPython(python, args, timeout) {
9332
+ return (0, import_node_child_process2.spawnSync)(python, ["-I", ...args], { encoding: "utf8", timeout, env: PersonalToken.scrubbed(process.env) });
9333
+ }
9334
+ var import_node_child_process2;
9335
+ var init_isolatedPython = __esm({
9336
+ "src/worlds/isolatedPython.ts"() {
9337
+ "use strict";
9338
+ import_node_child_process2 = require("child_process");
9339
+ init_personalToken();
9340
+ }
9341
+ });
9342
+
8254
9343
  // src/cli/runtime/local.ts
9344
+ var local_exports = {};
9345
+ __export(local_exports, {
9346
+ MIN_PYTHON_LABEL: () => MIN_PYTHON_LABEL,
9347
+ assertPortFree: () => assertPortFree,
9348
+ credentialsForRuntime: () => credentialsForRuntime,
9349
+ findPython: () => findPython,
9350
+ localBridge: () => localBridge,
9351
+ localModule: () => localModule,
9352
+ localPythonHasYaml: () => localPythonHasYaml,
9353
+ localRuntime: () => localRuntime,
9354
+ localRuntimeReason: () => localRuntimeReason,
9355
+ portOwner: () => portOwner,
9356
+ pythonAdvice: () => pythonAdvice,
9357
+ resetPythonCache: () => resetPythonCache,
9358
+ runtimeMode: () => runtimeMode,
9359
+ runtimeRoot: () => runtimeRoot
9360
+ });
8255
9361
  function forwardedEnv() {
8256
9362
  return Object.fromEntries(
8257
9363
  FORWARDED_ENV.flatMap((name) => {
@@ -8288,12 +9394,12 @@ function runtimeRoot() {
8288
9394
  return root;
8289
9395
  return null;
8290
9396
  }
9397
+ function resetPythonCache() {
9398
+ pythonCache = void 0;
9399
+ pythonProbes = [];
9400
+ }
8291
9401
  function probeVersion(name) {
8292
- const probe = (0, import_node_child_process2.spawnSync)(
8293
- name,
8294
- ["-c", "import sys;print(sys.version_info[0],sys.version_info[1])"],
8295
- { encoding: "utf8", timeout: 1e4 }
8296
- );
9402
+ const probe = isolatedPython(name, ["-c", "import sys;print(sys.version_info[0],sys.version_info[1])"], 1e4);
8297
9403
  if (probe.status !== 0) return null;
8298
9404
  const [major, minor] = probe.stdout.trim().split(/\s+/).map(Number);
8299
9405
  return Number.isInteger(major) && Number.isInteger(minor) ? `${major}.${minor}` : null;
@@ -8303,7 +9409,7 @@ function atLeastMinimum(version) {
8303
9409
  return major > MIN_PYTHON[0] || major === MIN_PYTHON[0] && minor >= MIN_PYTHON[1];
8304
9410
  }
8305
9411
  function uvPython() {
8306
- const found = (0, import_node_child_process2.spawnSync)("uv", UV_FIND, { encoding: "utf8", timeout: 1e4 });
9412
+ const found = (0, import_node_child_process3.spawnSync)("uv", UV_FIND, { encoding: "utf8", timeout: 1e4, env: PersonalToken.scrubbed(process.env) });
8307
9413
  if (found.status !== 0) return null;
8308
9414
  const line = found.stdout.trim().split(/\r?\n/)[0] ?? "";
8309
9415
  return line || null;
@@ -8362,12 +9468,12 @@ function localRuntime() {
8362
9468
  return { python, root };
8363
9469
  }
8364
9470
  function localPythonHasYaml(python) {
8365
- return (0, import_node_child_process2.spawnSync)(python, ["-c", "import yaml"], { timeout: 1e4 }).status === 0;
9471
+ return isolatedPython(python, ["-c", "import yaml"], 1e4).status === 0;
8366
9472
  }
8367
9473
  async function localBridge(request, local, opts = {}) {
8368
9474
  const input = JSON.stringify(request);
8369
9475
  return await new Promise((resolve11, reject) => {
8370
- const child = (0, import_node_child_process2.spawn)(
9476
+ const child = (0, import_node_child_process3.spawn)(
8371
9477
  local.python,
8372
9478
  ["-I", "-B", "-c", BRIDGE_BOOTSTRAP, local.root],
8373
9479
  {
@@ -8423,16 +9529,92 @@ async function localBridge(request, local, opts = {}) {
8423
9529
  child.stdin.end(input);
8424
9530
  });
8425
9531
  }
8426
- var import_node_child_process2, fs7, net, path8, MIN_PYTHON, MIN_PYTHON_LABEL, DIAGNOSTIC_TAIL, FORWARDED_ENV, BRIDGE_BOOTSTRAP, pythonCache, pythonProbes, PYTHON_CANDIDATES, UV_FIND;
9532
+ function portOwner(port) {
9533
+ const found = (0, import_node_child_process3.spawnSync)("lsof", ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN", "-Fpc"], {
9534
+ encoding: "utf8",
9535
+ timeout: 5e3
9536
+ });
9537
+ if (found.error || found.status !== 0) return null;
9538
+ let pid = null;
9539
+ let command2 = null;
9540
+ for (const line of found.stdout.split("\n")) {
9541
+ if (line.startsWith("p") && pid === null) pid = line.slice(1);
9542
+ else if (line.startsWith("c") && pid !== null && command2 === null) command2 = line.slice(1);
9543
+ }
9544
+ if (pid === null) return null;
9545
+ return `pid ${pid}${command2 ? ` (${command2})` : ""}`;
9546
+ }
9547
+ async function assertPortFree(port, host = "127.0.0.1") {
9548
+ const taken = await new Promise((resolve11) => {
9549
+ const probe = net.createServer();
9550
+ probe.once("error", () => resolve11(true));
9551
+ probe.listen(port, host, () => probe.close(() => resolve11(false)));
9552
+ });
9553
+ if (!taken) return;
9554
+ const owner = portOwner(port);
9555
+ throw new CliError(
9556
+ `port ${port} on ${host} is already in use${owner ? ` by ${owner}` : ""}; nothing was served there \u2014 pass another --port, or stop that server first`,
9557
+ 1
9558
+ );
9559
+ }
9560
+ async function localModule(argv, local, opts = {}) {
9561
+ return await new Promise((resolve11, reject) => {
9562
+ const child = (0, import_node_child_process3.spawn)(
9563
+ local.python,
9564
+ ["-B", "-c", MODULE_BOOTSTRAP, local.root, ...argv],
9565
+ {
9566
+ stdio: "inherit",
9567
+ cwd: opts.cwd,
9568
+ env: { ...PersonalToken.scrubbed(process.env), ...opts.env }
9569
+ }
9570
+ );
9571
+ const forward = (signal) => () => {
9572
+ if (child.exitCode === null && child.signalCode === null) child.kill(signal);
9573
+ };
9574
+ const handlers = [
9575
+ ["SIGINT", forward("SIGINT")],
9576
+ ["SIGTERM", forward("SIGTERM")],
9577
+ ["SIGHUP", forward("SIGHUP")]
9578
+ ];
9579
+ for (const [signal, handler] of handlers) process.on(signal, handler);
9580
+ const release = () => {
9581
+ for (const [signal, handler] of handlers) process.off(signal, handler);
9582
+ };
9583
+ child.on("error", (error) => {
9584
+ release();
9585
+ reject(
9586
+ new CliError(
9587
+ `local runtime could not start (${local.python}): ${error.message}`,
9588
+ 1
9589
+ )
9590
+ );
9591
+ });
9592
+ child.on("close", (code, signal) => {
9593
+ release();
9594
+ resolve11(code ?? (signal ? 130 : 1));
9595
+ });
9596
+ });
9597
+ }
9598
+ function credentialsForRuntime(hostFlag) {
9599
+ try {
9600
+ return resolveCredentials(hostFlag);
9601
+ } catch (error) {
9602
+ if (error instanceof CliError && localRuntime()) return null;
9603
+ throw error;
9604
+ }
9605
+ }
9606
+ var import_node_child_process3, fs7, net, path8, MIN_PYTHON, MIN_PYTHON_LABEL, DIAGNOSTIC_TAIL, FORWARDED_ENV, BRIDGE_BOOTSTRAP, MODULE_BOOTSTRAP, pythonCache, pythonProbes, PYTHON_CANDIDATES, UV_FIND;
8427
9607
  var init_local = __esm({
8428
9608
  "src/cli/runtime/local.ts"() {
8429
9609
  "use strict";
8430
- import_node_child_process2 = require("child_process");
9610
+ import_node_child_process3 = require("child_process");
8431
9611
  fs7 = __toESM(require("fs"));
8432
9612
  net = __toESM(require("net"));
8433
9613
  path8 = __toESM(require("path"));
8434
9614
  init_router();
8435
9615
  init_config();
9616
+ init_isolatedPython();
9617
+ init_personalToken();
8436
9618
  MIN_PYTHON = [3, 12];
8437
9619
  MIN_PYTHON_LABEL = MIN_PYTHON.join(".");
8438
9620
  DIAGNOSTIC_TAIL = 600;
@@ -8443,6 +9625,13 @@ package=types.ModuleType('gatewaysdk')
8443
9625
  package.__path__=[os.path.join(root,'gatewaysdk')]
8444
9626
  sys.modules['gatewaysdk']=package
8445
9627
  runpy.run_module('gatewaysdk.environment.schema.platform',run_name='__main__')`;
9628
+ MODULE_BOOTSTRAP = `import sys,runpy,types,os
9629
+ root=sys.argv[1]
9630
+ package=types.ModuleType('gatewaysdk')
9631
+ package.__path__=[os.path.join(root,'gatewaysdk')]
9632
+ sys.modules['gatewaysdk']=package
9633
+ sys.argv=['gateway worlds']+sys.argv[2:]
9634
+ runpy.run_module('gatewaysdk.environment.schema',run_name='__main__')`;
8446
9635
  pythonProbes = [];
8447
9636
  PYTHON_CANDIDATES = [
8448
9637
  "python3.13",
@@ -8589,8 +9778,8 @@ async function runtime(creds, request, opts = {}) {
8589
9778
  throw new CliError(
8590
9779
  "This needs the schema runtime (the CLI bundles it) or platform credentials (`gateway auth login`). " + localRuntimeReason()
8591
9780
  );
8592
- const route = "/api/public/worlds/runtime";
8593
- const res = await new PlatformTransport(creds).send("POST", route, request, {
9781
+ const route2 = "/api/public/worlds/runtime";
9782
+ const res = await new PlatformTransport(creds).send("POST", route2, request, {
8594
9783
  timeoutMs: opts.timeoutMs ?? RUNTIME_TIMEOUT_MS
8595
9784
  });
8596
9785
  let payload = null;
@@ -8602,8 +9791,8 @@ async function runtime(creds, request, opts = {}) {
8602
9791
  const detail = detailFrom(payload);
8603
9792
  if (detail) throw new BridgeRejected(detail);
8604
9793
  if (!res.ok)
8605
- throw new CliError(`POST ${route} (${request.command}) -> ${res.status}: ${res.text.slice(0, 600)}`, 1);
8606
- if (payload === null) throw new CliError(`POST ${route} (${request.command}) returned non-JSON`, 1);
9794
+ throw new CliError(`POST ${route2} (${request.command}) -> ${res.status}: ${res.text.slice(0, 600)}`, 1);
9795
+ if (payload === null) throw new CliError(`POST ${route2} (${request.command}) returned non-JSON`, 1);
8607
9796
  return payload;
8608
9797
  }
8609
9798
  var fs8, path9, MAX_WORLD_FILES, RUNTIME_TIMEOUT_MS, SKIP_DIRS, BridgeRejected, YAML_NAME, YAML_NEEDS_PYYAML, YAML_NOT_ON_PLATFORM, RuntimeRoute;
@@ -8938,7 +10127,7 @@ async function runTransform(script, records, opts = {}) {
8938
10127
  const { file, args } = command(resolved, scratch);
8939
10128
  const env = Object.fromEntries(Object.entries(process.env).filter(([key2]) => !SCRUBBED.test(key2)));
8940
10129
  const done = await new Promise((resolve11, reject) => {
8941
- const child = (0, import_node_child_process3.spawn)(file, args, { cwd: path11.dirname(resolved), env, stdio: ["pipe", "pipe", "pipe"] });
10130
+ const child = (0, import_node_child_process4.spawn)(file, args, { cwd: path11.dirname(resolved), env, stdio: ["pipe", "pipe", "pipe"] });
8942
10131
  let stdout = "";
8943
10132
  let stderr = "";
8944
10133
  let timedOut = false;
@@ -8976,11 +10165,11 @@ async function transformRecords(transform, records, opts = {}) {
8976
10165
  if (typeof transform === "function") return { rows: checkRows(await transform(records), "transform(records)"), stderr: "" };
8977
10166
  return runTransform(transform, records, opts);
8978
10167
  }
8979
- var import_node_child_process3, fs10, os2, path11, import_node_module, import_meta, DEFAULT_TRANSFORM_TIMEOUT_MS, NODE_SUFFIXES, PYTHON_SUFFIXES, SCRUBBED, PY_WRAPPER, NODE_WRAPPER, isObject, tail;
10168
+ var import_node_child_process4, fs10, os2, path11, import_node_module, import_meta, DEFAULT_TRANSFORM_TIMEOUT_MS, NODE_SUFFIXES, PYTHON_SUFFIXES, SCRUBBED, PY_WRAPPER, NODE_WRAPPER, isObject, tail;
8980
10169
  var init_transform = __esm({
8981
10170
  "src/cli/platform/worldData/transform.ts"() {
8982
10171
  "use strict";
8983
- import_node_child_process3 = require("child_process");
10172
+ import_node_child_process4 = require("child_process");
8984
10173
  fs10 = __toESM(require("fs"));
8985
10174
  os2 = __toESM(require("os"));
8986
10175
  path11 = __toESM(require("path"));
@@ -9493,9 +10682,9 @@ async function emit(sink, record) {
9493
10682
  }
9494
10683
  throw new TypeError("sink must be an array, a file path, or a function");
9495
10684
  }
9496
- function captureToolCalls(tools, sink, opts = {}) {
10685
+ function captureToolCalls(tools2, sink, opts = {}) {
9497
10686
  const wrapped = /* @__PURE__ */ Object.create(null);
9498
- for (const [name, fn] of Object.entries(tools)) {
10687
+ for (const [name, fn] of Object.entries(tools2)) {
9499
10688
  wrapped[name] = async (args = {}) => {
9500
10689
  const record = { tool: name, args, at: (/* @__PURE__ */ new Date()).toISOString() };
9501
10690
  if (opts.session) record.session = opts.session;
@@ -9551,14 +10740,23 @@ function toolCallsFromObservations(observations, opts = {}) {
9551
10740
  }
9552
10741
  return out;
9553
10742
  }
10743
+ async function runtimeEndpoint(options) {
10744
+ try {
10745
+ return platformEndpoint(options);
10746
+ } catch (error) {
10747
+ const { localRuntime: localRuntime2 } = await Promise.resolve().then(() => (init_local(), local_exports));
10748
+ if (error instanceof PersonalTokenRefused && localRuntime2()) return null;
10749
+ throw error;
10750
+ }
10751
+ }
9554
10752
  async function ingest(world, records, options = {}) {
9555
10753
  const { ingestLocalToolCalls: ingestLocalToolCalls2, importLocalWorldData: importLocalWorldData2, checkLocalWorldData: checkLocalWorldData2 } = await Promise.resolve().then(() => (init_data(), data_exports));
9556
10754
  if (options.transform !== void 0 && options.map !== void 0) throw new Error("records go through one of transform, map");
9557
10755
  const redact = options.redact ?? "off";
9558
10756
  const mode = options.mode ?? "append";
9559
10757
  const dryRun = Boolean(options.dryRun);
9560
- const creds = platformEndpoint(options);
9561
10758
  const local = fs12.existsSync(world) && fs12.statSync(world).isDirectory();
10759
+ const creds = local ? await runtimeEndpoint(options) : platformEndpoint(options);
9562
10760
  const map = options.map === void 0 ? void 0 : options.map;
9563
10761
  let rows = null;
9564
10762
  let stderr = "";
@@ -9659,6 +10857,7 @@ var init_ingest = __esm({
9659
10857
  path12 = __toESM(require("path"));
9660
10858
  init_worlds();
9661
10859
  init_platformEndpoint();
10860
+ init_personalToken();
9662
10861
  isObject2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
9663
10862
  isoOf = (value) => value instanceof Date ? value.toISOString() : typeof value === "string" ? value : void 0;
9664
10863
  }
@@ -9716,6 +10915,38 @@ var init_editSessions = __esm({
9716
10915
  }
9717
10916
  });
9718
10917
 
10918
+ // src/worlds/states.ts
10919
+ var WORLDS3, refQuery, WorldStateClient;
10920
+ var init_states = __esm({
10921
+ "src/worlds/states.ts"() {
10922
+ "use strict";
10923
+ init_worlds();
10924
+ WORLDS3 = "/api/public/worlds";
10925
+ refQuery = (ref) => ref ? `?${new URLSearchParams({ ref })}` : "";
10926
+ WorldStateClient = class {
10927
+ constructor(options = {}) {
10928
+ this.options = options;
10929
+ }
10930
+ options;
10931
+ list(slug) {
10932
+ return apiRequest(this.options, "GET", `${WORLDS3}/${encodeURIComponent(slug)}/states`);
10933
+ }
10934
+ show(slug, name, ref) {
10935
+ return apiRequest(this.options, "GET", `${WORLDS3}/${encodeURIComponent(slug)}/states/${encodeURIComponent(name)}` + refQuery(ref));
10936
+ }
10937
+ create(slug, input) {
10938
+ return apiRequest(this.options, "POST", `${WORLDS3}/${encodeURIComponent(slug)}/states`, input);
10939
+ }
10940
+ delete(slug, name) {
10941
+ return apiRequest(this.options, "DELETE", `${WORLDS3}/${encodeURIComponent(slug)}/states/${encodeURIComponent(name)}`);
10942
+ }
10943
+ pull(slug, name, ref) {
10944
+ return apiRequest(this.options, "GET", `${WORLDS3}/${encodeURIComponent(slug)}/states/${encodeURIComponent(name)}/pull` + refQuery(ref));
10945
+ }
10946
+ };
10947
+ }
10948
+ });
10949
+
9719
10950
  // src/worlds/dryRun.ts
9720
10951
  var DRY_RUN_KIND, DRY_RUN_AGENT, STATUS_WAIT_CAP_SECONDS, cid, HostedDryRunClient, DryRunOutcome;
9721
10952
  var init_dryRun = __esm({
@@ -9849,9 +11080,14 @@ __export(worlds_exports, {
9849
11080
  OpenAIComputer: () => OpenAIComputer,
9850
11081
  OpenAIPreviewComputer: () => OpenAIPreviewComputer,
9851
11082
  PLATFORM_SESSION_HEADER: () => PLATFORM_SESSION_HEADER,
11083
+ PLATFORM_STREAM_IDLE_MS: () => PLATFORM_STREAM_IDLE_MS,
9852
11084
  PLATFORM_TIMEOUT_DEFAULT_MS: () => PLATFORM_TIMEOUT_DEFAULT_MS,
9853
11085
  PLATFORM_TIMEOUT_ENV: () => PLATFORM_TIMEOUT_ENV,
11086
+ PageObserver: () => PageObserver,
11087
+ PageState: () => PageState,
11088
+ PageStateError: () => PageStateError,
9854
11089
  PendingSafetyChecks: () => PendingSafetyChecks,
11090
+ PlatformStream: () => PlatformStream,
9855
11091
  PlatformTransport: () => PlatformTransport,
9856
11092
  PushSlugConflict: () => PushSlugConflict,
9857
11093
  RECOVER_BUDGET_MS: () => RECOVER_BUDGET_MS,
@@ -9888,6 +11124,7 @@ __export(worlds_exports, {
9888
11124
  VERIFIER_REWARD_PREFIX: () => VERIFIER_REWARD_PREFIX,
9889
11125
  WHITESPACE: () => WHITESPACE,
9890
11126
  WORLD_REQUEST_VIAS: () => WORLD_REQUEST_VIAS,
11127
+ WORLD_WEBHOOK_PAGE_MAX: () => WORLD_WEBHOOK_PAGE_MAX,
9891
11128
  WorldBrowser: () => WorldBrowser,
9892
11129
  WorldCallTooLarge: () => WorldCallTooLarge,
9893
11130
  WorldEditClient: () => WorldEditClient,
@@ -9903,9 +11140,11 @@ __export(worlds_exports, {
9903
11140
  WorldSessionOpenFailed: () => WorldSessionOpenFailed,
9904
11141
  WorldSessionTimeout: () => WorldSessionTimeout,
9905
11142
  WorldSet: () => WorldSet,
11143
+ WorldStateClient: () => WorldStateClient,
9906
11144
  WorldSurfaceUnavailable: () => WorldSurfaceUnavailable,
9907
11145
  WorldTask: () => WorldTask,
9908
11146
  WorldToolsUnread: () => WorldToolsUnread,
11147
+ WorldWebhookForwarder: () => WorldWebhookForwarder,
9909
11148
  WriteTreeFilter: () => WriteTreeFilter,
9910
11149
  aggregateTaskGrade: () => aggregateTaskGrade,
9911
11150
  apiRequest: () => apiRequest,
@@ -9953,6 +11192,7 @@ __export(worlds_exports, {
9953
11192
  listSessions: () => listSessions,
9954
11193
  listTaskSessions: () => listTaskSessions,
9955
11194
  listTasks: () => listTasks,
11195
+ listWebhooks: () => listWebhooks,
9956
11196
  localTreeState: () => localTreeState,
9957
11197
  messageOf: () => messageOf,
9958
11198
  migrateProjectWorlds: () => migrateProjectWorlds,
@@ -9968,6 +11208,7 @@ __export(worlds_exports, {
9968
11208
  parseToolCallRecord: () => parseToolCallRecord,
9969
11209
  parseTransform: () => parseTransform,
9970
11210
  parseWorldTaskRefs: () => parseWorldTaskRefs,
11211
+ platformAuthorization: () => platformAuthorization,
9971
11212
  platformTimeoutMs: () => platformTimeoutMs,
9972
11213
  playwrightKey: () => playwrightKey,
9973
11214
  preserveForm: () => preserveForm,
@@ -9994,6 +11235,7 @@ __export(worlds_exports, {
9994
11235
  runSet: () => runSet,
9995
11236
  runTask: () => runTask,
9996
11237
  schemaFromSignature: () => schemaFromSignature,
11238
+ scrubError: () => scrubError,
9997
11239
  serializeCallBody: () => serializeCallBody,
9998
11240
  sessionToolObservations: () => sessionToolObservations,
9999
11241
  setEnvSecret: () => setEnvSecret,
@@ -10021,43 +11263,8 @@ __export(worlds_exports, {
10021
11263
  worldRequestsUnrecorded: () => worldRequestsUnrecorded,
10022
11264
  writeLocalMeta: () => writeLocalMeta
10023
11265
  });
10024
- function edgeAnswer(text2, status) {
10025
- if (status !== void 0 && status >= 500) return EDGE_ANSWERS[status] ?? EDGE_FAILURE;
10026
- return /^\s*</.test(text2) ? EDGE_PAGE : null;
10027
- }
10028
- function parseErrorBody(text2, status) {
10029
- const raw = { detail: text2.slice(0, DETAIL_LIMIT), code: null };
10030
- let parsed;
10031
- try {
10032
- parsed = JSON.parse(text2);
10033
- } catch {
10034
- return { detail: (edgeAnswer(text2, status) ?? text2).slice(0, DETAIL_LIMIT), code: null };
10035
- }
10036
- if (parsed === null || typeof parsed !== "object") return raw;
10037
- const { message, code, error } = parsed;
10038
- const stableCode = typeof code === "string" ? code : null;
10039
- if (typeof message !== "string") return { ...raw, code: stableCode };
10040
- const fields = invalidFields(error);
10041
- const said = fields ? `${message}: ${fields}` : message;
10042
- if (stableCode === null) return { detail: said.slice(0, DETAIL_LIMIT), code: null };
10043
- return {
10044
- detail: `${said} (${stableCode})`.slice(0, DETAIL_LIMIT),
10045
- code: stableCode
10046
- };
10047
- }
10048
- function invalidFields(error) {
10049
- const issues = Array.isArray(error) ? error : [];
10050
- return issues.filter(
10051
- (issue) => issue !== null && typeof issue === "object" && typeof issue.message === "string"
10052
- ).map((issue) => {
10053
- const path17 = Array.isArray(issue.path) ? issue.path.map(String).join(".") : "";
10054
- return path17 ? `${path17}: ${issue.message}` : issue.message;
10055
- }).join("; ");
10056
- }
10057
11266
  async function apiRequest(options, method, path17, body, init3 = {}) {
10058
- const reply = await new PlatformTransport(requirePlatformEndpoint(options)).send(method, path17, body, init3);
10059
- if (!reply.ok) throw new ApiError(reply.status, method, path17, reply.text);
10060
- return JSON.parse(reply.text);
11267
+ return new PlatformTransport(requirePlatformEndpoint(options)).json(method, path17, body, init3);
10061
11268
  }
10062
11269
  async function setEnvSecret(slug, key2, value, options = {}) {
10063
11270
  return apiRequest(
@@ -10232,12 +11439,13 @@ async function resolveWorld(slugRef, slug, ref, pin, options) {
10232
11439
  }
10233
11440
  return world;
10234
11441
  }
10235
- var ApiError, DETAIL_LIMIT, EDGE_ANSWERS, EDGE_FAILURE, EDGE_PAGE, WorldTask, WorldSet;
11442
+ var WorldTask, WorldSet;
10236
11443
  var init_worlds = __esm({
10237
11444
  "src/worlds/index.ts"() {
10238
11445
  "use strict";
10239
11446
  init_platformEndpoint();
10240
11447
  init_transport();
11448
+ init_apiError();
10241
11449
  init_transport();
10242
11450
  init_session2();
10243
11451
  init_grade();
@@ -10252,9 +11460,12 @@ var init_worlds = __esm({
10252
11460
  init_checkoutProvenance();
10253
11461
  init_evals();
10254
11462
  init_browser();
11463
+ init_browserTools();
11464
+ init_pageState();
10255
11465
  init_surfaceDescriptor();
10256
11466
  init_requestLog();
10257
11467
  init_requestLedger();
11468
+ init_webhooks();
10258
11469
  init_browserReconnect();
10259
11470
  init_nativeComputer();
10260
11471
  init_hub();
@@ -10262,34 +11473,14 @@ var init_worlds = __esm({
10262
11473
  init_describe();
10263
11474
  init_redaction();
10264
11475
  init_transforms();
10265
- init_query();
10266
- init_migrate();
10267
- init_ingest();
10268
- init_sandbox();
10269
- init_editSessions();
10270
- init_dryRun();
10271
- init_worldNotice();
10272
- ApiError = class extends Error {
10273
- constructor(status, method, path17, text2) {
10274
- const parsed = parseErrorBody(text2, status);
10275
- super(`${method} ${path17} -> ${status}: ${parsed.detail}`);
10276
- this.status = status;
10277
- this.text = text2;
10278
- this.name = "ApiError";
10279
- this.code = parsed.code;
10280
- }
10281
- status;
10282
- text;
10283
- code;
10284
- };
10285
- DETAIL_LIMIT = 600;
10286
- EDGE_ANSWERS = {
10287
- 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.",
10288
- 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.",
10289
- 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."
10290
- };
10291
- 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.";
10292
- 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.";
11476
+ init_query();
11477
+ init_migrate();
11478
+ init_ingest();
11479
+ init_sandbox();
11480
+ init_editSessions();
11481
+ init_states();
11482
+ init_dryRun();
11483
+ init_worldNotice();
10293
11484
  WorldTask = class {
10294
11485
  constructor(world, name, variant) {
10295
11486
  this.world = world;
@@ -10360,8 +11551,20 @@ var init_worlds = __esm({
10360
11551
  var src_exports = {};
10361
11552
  __export(src_exports, {
10362
11553
  ACTION_NAMES: () => ACTION_NAMES,
11554
+ AGENT_EFFORTS: () => AGENT_EFFORTS,
10363
11555
  AGENT_ID_KEY: () => AGENT_ID_KEY,
11556
+ AGENT_MODELS: () => AGENT_MODELS,
10364
11557
  ActionTracer: () => ActionTracer,
11558
+ Agent: () => Agent,
11559
+ AgentDefinition: () => AgentDefinition,
11560
+ AgentDefinitionError: () => AgentDefinitionError,
11561
+ AgentPatch: () => AgentPatch,
11562
+ AgentRun: () => AgentRun,
11563
+ AgentThreads: () => AgentThreads,
11564
+ AgentTools: () => AgentTools,
11565
+ AgentVersionConflictError: () => AgentVersionConflictError,
11566
+ AgentVersionNotFoundError: () => AgentVersionNotFoundError,
11567
+ Agents: () => Agents,
10365
11568
  AnthropicComputer: () => AnthropicComputer,
10366
11569
  AnthropicComputer20251124: () => AnthropicComputer20251124,
10367
11570
  ApiError: () => ApiError,
@@ -10394,9 +11597,11 @@ __export(src_exports, {
10394
11597
  EXPERIMENT_ATTRIBUTES: () => EXPERIMENT_ATTRIBUTES,
10395
11598
  EXPLORATORY_TASK: () => EXPLORATORY_TASK,
10396
11599
  EXPLORATORY_TASK_SOURCE: () => EXPLORATORY_TASK_SOURCE,
11600
+ EventStreamError: () => EventStreamError,
10397
11601
  ExperimentClient: () => ExperimentClient,
10398
11602
  ExperimentSpanProcessor: () => ExperimentSpanProcessor,
10399
11603
  ExposureLogger: () => ExposureLogger,
11604
+ Gateway: () => Gateway,
10400
11605
  GatewayContext: () => GatewayContext,
10401
11606
  GatewayContextConflictError: () => GatewayContextConflictError,
10402
11607
  GatewayContextError: () => GatewayContextError,
@@ -10420,12 +11625,17 @@ __export(src_exports, {
10420
11625
  OpenAIComputer: () => OpenAIComputer,
10421
11626
  OpenAIPreviewComputer: () => OpenAIPreviewComputer,
10422
11627
  PLATFORM_SESSION_HEADER: () => PLATFORM_SESSION_HEADER,
11628
+ PLATFORM_STREAM_IDLE_MS: () => PLATFORM_STREAM_IDLE_MS,
10423
11629
  PLATFORM_TIMEOUT_DEFAULT_MS: () => PLATFORM_TIMEOUT_DEFAULT_MS,
10424
11630
  PLATFORM_TIMEOUT_ENV: () => PLATFORM_TIMEOUT_ENV,
11631
+ PageObserver: () => PageObserver,
11632
+ PageState: () => PageState,
11633
+ PageStateError: () => PageStateError,
10425
11634
  PendingSafetyChecks: () => PendingSafetyChecks,
10426
11635
  Persona: () => Persona,
10427
11636
  PersonaError: () => PersonaError,
10428
11637
  PersonasClient: () => PersonasClient,
11638
+ PlatformStream: () => PlatformStream,
10429
11639
  PlatformTransport: () => PlatformTransport,
10430
11640
  PushSlugConflict: () => PushSlugConflict,
10431
11641
  RECOVER_BUDGET_MS: () => RECOVER_BUDGET_MS,
@@ -10433,6 +11643,7 @@ __export(src_exports, {
10433
11643
  REQUESTS_NOT_RECORDED: () => REQUESTS_NOT_RECORDED,
10434
11644
  REQUEST_BODY_CAPTURE_BYTES: () => REQUEST_BODY_CAPTURE_BYTES,
10435
11645
  REQUEST_LOG_PAGE_MAX: () => REQUEST_LOG_PAGE_MAX,
11646
+ ReconnectPolicy: () => ReconnectPolicy,
10436
11647
  ReplayCase: () => ReplayCase,
10437
11648
  ReplayCheck: () => ReplayCheck,
10438
11649
  ReplayError: () => ReplayError,
@@ -10457,6 +11668,7 @@ __export(src_exports, {
10457
11668
  SUCCESS_METRIC_NAME_KEY: () => SUCCESS_METRIC_NAME_KEY,
10458
11669
  SUCCESS_SIGNAL_KEY: () => SUCCESS_SIGNAL_KEY,
10459
11670
  SURFACE_KINDS: () => SURFACE_KINDS,
11671
+ SYSTEM_CLOCK: () => SYSTEM_CLOCK,
10460
11672
  Score: () => Score,
10461
11673
  ScoreError: () => ScoreError,
10462
11674
  ScoresClient: () => ScoresClient,
@@ -10465,13 +11677,18 @@ __export(src_exports, {
10465
11677
  SessionLoadError: () => SessionLoadError,
10466
11678
  SessionRecording: () => SessionRecording,
10467
11679
  SessionTrace: () => SessionTrace,
11680
+ SseLimits: () => SseLimits,
11681
+ SseParser: () => SseParser,
10468
11682
  StubMissError: () => StubMissError,
10469
11683
  TOOL_CONTRACT_UNREAD: () => TOOL_CONTRACT_UNREAD,
11684
+ TOOL_SERVERS: () => TOOL_SERVERS,
10470
11685
  TRANSFORMS: () => TRANSFORMS,
10471
11686
  TaskEditClient: () => TaskEditClient,
10472
11687
  TaskGrades: () => TaskGrades,
10473
11688
  TaskRun: () => TaskRun,
10474
11689
  TaskSessions: () => TaskSessions,
11690
+ Thread: () => Thread,
11691
+ Threads: () => Threads,
10475
11692
  ToolStubRegistry: () => ToolStubRegistry,
10476
11693
  TraceDiff: () => TraceDiff,
10477
11694
  TransportCause: () => TransportCause,
@@ -10481,6 +11698,7 @@ __export(src_exports, {
10481
11698
  VERIFIER_REWARD_PREFIX: () => VERIFIER_REWARD_PREFIX,
10482
11699
  WHITESPACE: () => WHITESPACE,
10483
11700
  WORLD_REQUEST_VIAS: () => WORLD_REQUEST_VIAS,
11701
+ WORLD_WEBHOOK_PAGE_MAX: () => WORLD_WEBHOOK_PAGE_MAX,
10484
11702
  WorldBrowser: () => WorldBrowser,
10485
11703
  WorldCallTooLarge: () => WorldCallTooLarge,
10486
11704
  WorldEditClient: () => WorldEditClient,
@@ -10496,9 +11714,11 @@ __export(src_exports, {
10496
11714
  WorldSessionOpenFailed: () => WorldSessionOpenFailed,
10497
11715
  WorldSessionTimeout: () => WorldSessionTimeout,
10498
11716
  WorldSet: () => WorldSet,
11717
+ WorldStateClient: () => WorldStateClient,
10499
11718
  WorldSurfaceUnavailable: () => WorldSurfaceUnavailable,
10500
11719
  WorldTask: () => WorldTask,
10501
11720
  WorldToolsUnread: () => WorldToolsUnread,
11721
+ WorldWebhookForwarder: () => WorldWebhookForwarder,
10502
11722
  WriteTreeFilter: () => WriteTreeFilter,
10503
11723
  addExperimentAttributes: () => addExperimentAttributes,
10504
11724
  aggregateTaskGrade: () => aggregateTaskGrade,
@@ -10532,6 +11752,7 @@ __export(src_exports, {
10532
11752
  createRef: () => createRef,
10533
11753
  createTask: () => createTask,
10534
11754
  currentTraceId: () => currentTraceId,
11755
+ defineAgent: () => defineAgent,
10535
11756
  defineTool: () => defineTool,
10536
11757
  deleteEnvSecret: () => deleteEnvSecret,
10537
11758
  deleteTask: () => deleteTask,
@@ -10568,6 +11789,7 @@ __export(src_exports, {
10568
11789
  listSessions: () => listSessions,
10569
11790
  listTaskSessions: () => listTaskSessions,
10570
11791
  listTasks: () => listTasks,
11792
+ listWebhooks: () => listWebhooks,
10571
11793
  loadSession: () => loadSession,
10572
11794
  localTreeState: () => localTreeState,
10573
11795
  memory: () => memory,
@@ -10586,6 +11808,7 @@ __export(src_exports, {
10586
11808
  parseTransform: () => parseTransform,
10587
11809
  parseWorldTaskRefs: () => parseWorldTaskRefs,
10588
11810
  personas: () => personas,
11811
+ platformAuthorization: () => platformAuthorization,
10589
11812
  platformTimeoutMs: () => platformTimeoutMs,
10590
11813
  playwrightKey: () => playwrightKey,
10591
11814
  preserveForm: () => preserveForm,
@@ -10622,6 +11845,7 @@ __export(src_exports, {
10622
11845
  runWithExperimentContext: () => runWithExperimentContext,
10623
11846
  schemaFromSignature: () => schemaFromSignature,
10624
11847
  scores: () => scores,
11848
+ scrubError: () => scrubError,
10625
11849
  serializeCallBody: () => serializeCallBody,
10626
11850
  sessionObservationFromApi: () => sessionObservationFromApi,
10627
11851
  sessionToolObservations: () => sessionToolObservations,
@@ -10642,6 +11866,7 @@ __export(src_exports, {
10642
11866
  taskRunFailure: () => taskRunFailure,
10643
11867
  toolCallRecordsIn: () => toolCallRecordsIn,
10644
11868
  toolCallsFromObservations: () => toolCallsFromObservations,
11869
+ tools: () => tools,
10645
11870
  traces: () => traces_exports,
10646
11871
  tracing: () => tracing,
10647
11872
  uiEntryUrl: () => uiEntryUrl,
@@ -13053,6 +14278,961 @@ init_scores();
13053
14278
  init_worlds();
13054
14279
  init_session2();
13055
14280
 
14281
+ // src/agents/agent.ts
14282
+ init_apiError();
14283
+
14284
+ // src/agents/patch.ts
14285
+ var list = (value) => Array.isArray(value) ? value : [value];
14286
+ function grantOf(input) {
14287
+ if (typeof input === "string") return { server: input };
14288
+ return input.only ? { server: input.server, only: [...input.only].sort() } : { server: input.server };
14289
+ }
14290
+ var AgentPatch = class _AgentPatch {
14291
+ constructor(json) {
14292
+ this.json = json;
14293
+ }
14294
+ json;
14295
+ static update(fields) {
14296
+ const set = Object.fromEntries(Object.entries(fields).filter(([, value]) => value !== void 0));
14297
+ return new _AgentPatch({ set });
14298
+ }
14299
+ static attach(grants) {
14300
+ return new _AgentPatch({ attach: list(grants).map(grantOf) });
14301
+ }
14302
+ static detach(servers) {
14303
+ return new _AgentPatch({ detach: [...list(servers)] });
14304
+ }
14305
+ toJSON() {
14306
+ return structuredClone(this.json);
14307
+ }
14308
+ };
14309
+
14310
+ // src/agents/agent.ts
14311
+ var AgentVersionConflictError = class extends ApiError {
14312
+ currentVersionId;
14313
+ constructor(status, method, path17, text2) {
14314
+ super(status, method, path17, text2);
14315
+ this.name = "AgentVersionConflictError";
14316
+ this.currentVersionId = currentVersionOf(text2);
14317
+ }
14318
+ };
14319
+ function currentVersionOf(text2) {
14320
+ try {
14321
+ const id = JSON.parse(text2).currentVersionId;
14322
+ return typeof id === "string" ? id : null;
14323
+ } catch {
14324
+ return null;
14325
+ }
14326
+ }
14327
+ var AgentTools = class {
14328
+ constructor(agent) {
14329
+ this.agent = agent;
14330
+ }
14331
+ agent;
14332
+ /** Grant servers: one already attached keeps its place and takes the new grant. */
14333
+ attach(grants, options = {}) {
14334
+ return this.agent.edit(AgentPatch.attach(grants), options);
14335
+ }
14336
+ /** Remove servers; one that is not attached changes nothing. */
14337
+ detach(servers, options = {}) {
14338
+ return this.agent.edit(AgentPatch.detach(servers), options);
14339
+ }
14340
+ };
14341
+ var AgentThreads = class {
14342
+ constructor(threads, name) {
14343
+ this.threads = threads;
14344
+ this.name = name;
14345
+ }
14346
+ threads;
14347
+ name;
14348
+ create(options = {}) {
14349
+ return this.threads.create({ ...options, agent: this.name });
14350
+ }
14351
+ };
14352
+ var Agent = class {
14353
+ #agents;
14354
+ #record;
14355
+ tools;
14356
+ threads;
14357
+ constructor(agents, record, threads) {
14358
+ this.#agents = agents;
14359
+ this.#record = liveOf(record);
14360
+ this.tools = new AgentTools(this);
14361
+ this.threads = new AgentThreads(threads, record.name);
14362
+ }
14363
+ get name() {
14364
+ return this.#record.name;
14365
+ }
14366
+ /** The version edits apply to: the one `production` runs (else, never deployed, the newest). */
14367
+ get versionId() {
14368
+ return this.#record.versionId;
14369
+ }
14370
+ get version() {
14371
+ return this.#record.version;
14372
+ }
14373
+ get buildHash() {
14374
+ return this.#record.buildHash;
14375
+ }
14376
+ get deployed() {
14377
+ return this.#record.deployed;
14378
+ }
14379
+ get definition() {
14380
+ return structuredClone(this.#record.definition);
14381
+ }
14382
+ /** Change fields: a new version, live unless `deploy: false`; a change to the values it already has writes nothing. */
14383
+ update(fields, options = {}) {
14384
+ return this.edit(AgentPatch.update(fields), options);
14385
+ }
14386
+ /** Apply one patch made of `AgentPatch.update`, `.attach` or `.detach`. */
14387
+ async edit(patch, options = {}) {
14388
+ const result = await this.#agents.edit(this.name, patch, { ...options, from: this.versionId });
14389
+ if (result.deployed || !this.deployed) this.#record = liveOf(result);
14390
+ return result;
14391
+ }
14392
+ /** Move `production` to one of this agent's versions (an earlier one, or one staged with `deploy: false`); `force` crosses a breaking tool change. */
14393
+ async rollback(versionId, options = {}) {
14394
+ this.#record = liveOf(await this.#agents.rollback(this.name, versionId, { ...options, from: this.versionId }));
14395
+ return this.toJSON();
14396
+ }
14397
+ /** Every version, newest first, with whether it is live and its changes against the version before it. */
14398
+ versions() {
14399
+ return this.#agents.history(this.name);
14400
+ }
14401
+ /** Read the live version again, after a conflict or someone else's change. */
14402
+ async refresh() {
14403
+ this.#record = liveOf(await this.#agents.live(this.name));
14404
+ return this;
14405
+ }
14406
+ /** Start a thread with this agent and send it `input`: the run uses the version `production` runs now (or `version`). */
14407
+ async run(input, options = {}) {
14408
+ const { version, ...thread } = options;
14409
+ return (await this.threads.create(thread)).send(input, { version });
14410
+ }
14411
+ toJSON() {
14412
+ return { ...this.#record, definition: this.definition };
14413
+ }
14414
+ };
14415
+ function liveOf(record) {
14416
+ const { name, versionId, version, buildHash, deployed, definition: definition2 } = record;
14417
+ return { name, versionId, version, buildHash, deployed, definition: definition2 };
14418
+ }
14419
+
14420
+ // src/agents/definition.ts
14421
+ var NAME_PATTERN = /^[a-z0-9][a-z0-9-]{0,62}$/;
14422
+ var DEFAULT_MODEL = "claude-opus-5";
14423
+ var DEFAULT_MAX_TURNS = 50;
14424
+ var INSTRUCTIONS = { min: 1, max: 65536 };
14425
+ var MAX_TURNS = { min: 1, max: 200 };
14426
+ var DEFINITION_FIELDS = /* @__PURE__ */ new Set([
14427
+ "name",
14428
+ "instructions",
14429
+ "model",
14430
+ "effort",
14431
+ "maxTurns",
14432
+ "tools"
14433
+ ]);
14434
+ var GRANT_FIELDS = /* @__PURE__ */ new Set(["server", "only"]);
14435
+ var AgentDefinitionError = class extends Error {
14436
+ constructor(issues) {
14437
+ super(`Invalid agent definition: ${issues.map((issue) => `${pathText(issue.path)}: ${issue.message}`).join("; ")}`);
14438
+ this.issues = issues;
14439
+ this.name = "AgentDefinitionError";
14440
+ }
14441
+ issues;
14442
+ };
14443
+ var AgentDefinition = class _AgentDefinition {
14444
+ name;
14445
+ instructions;
14446
+ model;
14447
+ effort;
14448
+ maxTurns;
14449
+ tools;
14450
+ constructor(spec) {
14451
+ this.name = spec.name;
14452
+ this.instructions = spec.instructions;
14453
+ this.model = spec.model;
14454
+ this.effort = spec.effort;
14455
+ this.maxTurns = spec.maxTurns;
14456
+ this.tools = Object.freeze(spec.tools.map(freezeGrant));
14457
+ Object.freeze(this);
14458
+ }
14459
+ /** Validate and normalize any value (a parsed JSON file included); throws `AgentDefinitionError` listing every broken rule. */
14460
+ static from(input) {
14461
+ return new _AgentDefinition(DefinitionReader.read(input));
14462
+ }
14463
+ /** The normalized definition: defaults filled, tool shorthands expanded, `only` sorted, `effort` present only when set. */
14464
+ toJSON() {
14465
+ return {
14466
+ name: this.name,
14467
+ instructions: this.instructions,
14468
+ model: this.model,
14469
+ ...this.effort === void 0 ? {} : { effort: this.effort },
14470
+ maxTurns: this.maxTurns,
14471
+ tools: this.tools.map(
14472
+ (grant2) => grant2.only ? { server: grant2.server, only: [...grant2.only] } : { server: grant2.server }
14473
+ )
14474
+ };
14475
+ }
14476
+ };
14477
+ function defineAgent(input) {
14478
+ return AgentDefinition.from(input);
14479
+ }
14480
+ function freezeGrant(grant2) {
14481
+ const only = grant2.only ? { only: Object.freeze([...grant2.only]) } : {};
14482
+ return Object.freeze({ server: grant2.server, ...only });
14483
+ }
14484
+ function pathText(path17) {
14485
+ return path17.length === 0 ? "definition" : path17.join(".");
14486
+ }
14487
+ function isRecord2(value) {
14488
+ return typeof value === "object" && value !== null && !Array.isArray(value);
14489
+ }
14490
+ function isString(value) {
14491
+ return value !== null;
14492
+ }
14493
+ var DefinitionReader = class _DefinitionReader {
14494
+ #issues = [];
14495
+ static read(input) {
14496
+ const reader = new _DefinitionReader();
14497
+ const spec = reader.spec(input);
14498
+ if (!spec || reader.#issues.length > 0) throw new AgentDefinitionError(reader.#issues);
14499
+ return spec;
14500
+ }
14501
+ spec(input) {
14502
+ if (!isRecord2(input)) return this.refuse([], "invalid_type", "a definition is an object", null);
14503
+ this.unknownFields(input, DEFINITION_FIELDS, []);
14504
+ const effort = this.optionalString(input.effort, ["effort"]);
14505
+ return {
14506
+ name: this.name(input.name),
14507
+ instructions: this.instructions(input.instructions),
14508
+ model: this.optionalString(input.model, ["model"]) ?? DEFAULT_MODEL,
14509
+ ...effort === void 0 ? {} : { effort },
14510
+ maxTurns: this.maxTurns(input.maxTurns),
14511
+ tools: this.tools(input.tools)
14512
+ };
14513
+ }
14514
+ name(value) {
14515
+ const name = this.string(value, ["name"]);
14516
+ if (name !== null && !NAME_PATTERN.test(name))
14517
+ this.issue(["name"], "invalid_name", "lowercase letters, digits and dashes, 1-63 long, not starting with a dash");
14518
+ return name ?? "";
14519
+ }
14520
+ instructions(value) {
14521
+ const instructions = this.string(value, ["instructions"]);
14522
+ if (instructions !== null) this.bounded(instructions.length, INSTRUCTIONS, ["instructions"], "characters");
14523
+ return instructions ?? "";
14524
+ }
14525
+ maxTurns(value) {
14526
+ if (value === void 0) return DEFAULT_MAX_TURNS;
14527
+ if (typeof value !== "number" || !Number.isInteger(value))
14528
+ return this.refuse(["maxTurns"], "invalid_type", "a whole number", DEFAULT_MAX_TURNS);
14529
+ this.bounded(value, MAX_TURNS, ["maxTurns"], "turns");
14530
+ return value;
14531
+ }
14532
+ tools(value) {
14533
+ if (value === void 0) return [];
14534
+ if (!Array.isArray(value)) return this.refuse(["tools"], "invalid_type", "a list of tools", []);
14535
+ const grants = value.map((entry, index2) => this.grant(entry, ["tools", index2]));
14536
+ this.noRepeats(
14537
+ grants.map((grant2) => grant2?.server ?? null),
14538
+ (index2) => ["tools", index2, "server"],
14539
+ "duplicate_tool_server",
14540
+ "this server is already granted"
14541
+ );
14542
+ return grants.filter((grant2) => grant2 !== null);
14543
+ }
14544
+ grant(entry, path17) {
14545
+ if (typeof entry === "string") return { server: entry };
14546
+ if (!isRecord2(entry)) return this.refuse(path17, "invalid_type", "a server name or { server, only }", null);
14547
+ this.unknownFields(entry, GRANT_FIELDS, path17);
14548
+ const server = this.string(entry.server, [...path17, "server"]);
14549
+ if (server === null) return null;
14550
+ return entry.only === void 0 ? { server } : { server, only: this.only(entry.only, [...path17, "only"]) };
14551
+ }
14552
+ only(value, path17) {
14553
+ if (!Array.isArray(value)) return this.refuse(path17, "invalid_type", "a list of tool names", []);
14554
+ if (value.length === 0)
14555
+ this.issue(path17, "too_small", "names at least one tool; leave `only` out to grant the whole server");
14556
+ const names = value.map((name, index2) => this.string(name, [...path17, index2]));
14557
+ this.noRepeats(names, (index2) => [...path17, index2], "duplicate_tool", "this tool is already named");
14558
+ return names.filter(isString).sort();
14559
+ }
14560
+ string(value, path17) {
14561
+ if (typeof value === "string") return value;
14562
+ return this.refuse(path17, "invalid_type", "a string", null);
14563
+ }
14564
+ optionalString(value, path17) {
14565
+ if (value === void 0) return void 0;
14566
+ return this.string(value, path17) ?? void 0;
14567
+ }
14568
+ bounded(value, bounds, path17, unit) {
14569
+ if (value < bounds.min) this.issue(path17, "too_small", `at least ${bounds.min} ${unit}`);
14570
+ if (value > bounds.max) this.issue(path17, "too_large", `at most ${bounds.max} ${unit}`);
14571
+ }
14572
+ unknownFields(record, known, path17) {
14573
+ for (const [key2, value] of Object.entries(record)) {
14574
+ if (value !== void 0 && !known.has(key2))
14575
+ this.issue([...path17, key2], "unknown_field", "not a field of an agent definition");
14576
+ }
14577
+ }
14578
+ noRepeats(values, pathOf, code, message) {
14579
+ const seen = /* @__PURE__ */ new Set();
14580
+ values.forEach((value, index2) => {
14581
+ if (value === null) return;
14582
+ if (seen.has(value)) this.issue(pathOf(index2), code, message);
14583
+ seen.add(value);
14584
+ });
14585
+ }
14586
+ issue(path17, code, message) {
14587
+ this.#issues.push({ path: path17, code, message });
14588
+ }
14589
+ refuse(path17, code, message, fallback) {
14590
+ this.issue(path17, code, message);
14591
+ return fallback;
14592
+ }
14593
+ };
14594
+
14595
+ // src/agents/index.ts
14596
+ init_apiError();
14597
+ init_transport();
14598
+
14599
+ // src/agents/agents.ts
14600
+ init_apiError();
14601
+
14602
+ // src/agents/segment.ts
14603
+ function segment(id) {
14604
+ if (id === "" || id === "." || id === "..") throw new TypeError(`not an id: "${id}"`);
14605
+ return encodeURIComponent(id);
14606
+ }
14607
+
14608
+ // src/agents/agents.ts
14609
+ var PRODUCTION = "production";
14610
+ var PAGE_SIZE = 100;
14611
+ var buildRoute = (buildId) => `/api/public/agent-builds/${segment(buildId)}`;
14612
+ var AgentVersionNotFoundError = class extends Error {
14613
+ constructor(agent, versionId) {
14614
+ super(`${versionId} is not a version of ${agent}; nothing was deployed.`);
14615
+ this.agent = agent;
14616
+ this.versionId = versionId;
14617
+ this.name = "AgentVersionNotFoundError";
14618
+ }
14619
+ agent;
14620
+ versionId;
14621
+ code = "version_not_found";
14622
+ };
14623
+ var Agents = class {
14624
+ #transport;
14625
+ #threads;
14626
+ constructor(transport, threads) {
14627
+ this.#transport = transport;
14628
+ this.#threads = threads;
14629
+ }
14630
+ /** 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`. */
14631
+ async create(input) {
14632
+ const { name, ...definition2 } = AgentDefinition.from(input).toJSON();
14633
+ const record = await this.#transport.json(
14634
+ "POST",
14635
+ `/api/public/agent-builds/definitions/${segment(name)}`,
14636
+ definition2
14637
+ );
14638
+ return new Agent(this, record, this.#threads);
14639
+ }
14640
+ /** The live agent named `name`, to edit or run; 404 `agent_not_found` when the project has none. */
14641
+ async get(name) {
14642
+ return new Agent(this, await this.live(name), this.#threads);
14643
+ }
14644
+ /** The version of `name` that edits apply to: the one `production` runs, else the newest. */
14645
+ live(name) {
14646
+ return this.#transport.json("GET", `/api/public/agent-builds/definitions/${segment(name)}`);
14647
+ }
14648
+ /** 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. */
14649
+ edit(name, patch, options = {}) {
14650
+ const body = { patch: patch.toJSON(), from: options.from, deploy: options.deploy ?? true };
14651
+ return this.conflictAware("POST", `/api/public/agent-builds/definitions/${segment(name)}/versions`, body);
14652
+ }
14653
+ /** Move `production` of `name` to one of its versions, with the audit row; `force` crosses a breaking tool change. */
14654
+ rollback(name, versionId, options = {}) {
14655
+ const body = { versionId, from: options.from, force: options.force ?? false };
14656
+ return this.conflictAware("POST", `/api/public/agent-builds/definitions/${segment(name)}/rollback`, body);
14657
+ }
14658
+ /** 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. */
14659
+ async history(name) {
14660
+ const versions = /* @__PURE__ */ new Map();
14661
+ for (let page = 1, pages = 1; page <= pages; page += 1) {
14662
+ const query = new URLSearchParams({ page: String(page), limit: String(PAGE_SIZE) });
14663
+ const reply = await this.#transport.json(
14664
+ "GET",
14665
+ `/api/public/agent-builds/definitions/${segment(name)}/versions?${query}`
14666
+ );
14667
+ for (const version of reply.data) if (!versions.has(version.id)) versions.set(version.id, version);
14668
+ pages = reply.meta.totalPages;
14669
+ }
14670
+ return [...versions.values()];
14671
+ }
14672
+ /** 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. */
14673
+ async push(definition2, options = {}) {
14674
+ const body = { definition: definition2.toJSON(), attribution: options.attribution };
14675
+ const version = await this.#transport.json("POST", "/api/public/agent-builds/definitions", body);
14676
+ if (!options.deploy) return version;
14677
+ await this.move(version.id, false);
14678
+ return { ...version, deployed: true, labels: [.../* @__PURE__ */ new Set([...version.labels, PRODUCTION])] };
14679
+ }
14680
+ /** 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. */
14681
+ async deploy(name, versionId, options = {}) {
14682
+ const versions = await this.versions(name);
14683
+ if (!versions.some((version) => version.id === versionId && version.kind === "defined"))
14684
+ throw new AgentVersionNotFoundError(name, versionId);
14685
+ return this.move(versionId, options.force ?? false);
14686
+ }
14687
+ /** Every version of `name`, newest first. */
14688
+ async versions(name) {
14689
+ const builds = [];
14690
+ for (let page = 1, pages = 1; page <= pages; page += 1) {
14691
+ const query = new URLSearchParams({ agentId: name, page: String(page), limit: String(PAGE_SIZE) });
14692
+ const reply = await this.#transport.json("GET", `/api/public/agent-builds?${query}`);
14693
+ builds.push(...reply.data);
14694
+ pages = reply.meta.totalPages;
14695
+ }
14696
+ return builds;
14697
+ }
14698
+ async conflictAware(method, path17, body) {
14699
+ try {
14700
+ return await this.#transport.json(method, path17, body);
14701
+ } catch (error) {
14702
+ if (error instanceof ApiError && error.code === "agent_version_conflict")
14703
+ throw new AgentVersionConflictError(error.status, method, path17, error.text);
14704
+ throw error;
14705
+ }
14706
+ }
14707
+ async move(versionId, force) {
14708
+ const body = { label: PRODUCTION, source: "api", force };
14709
+ const moved = await this.#transport.json("POST", `${buildRoute(versionId)}/labels`, body);
14710
+ return {
14711
+ agentId: moved.agentId,
14712
+ label: moved.label,
14713
+ versionId,
14714
+ fromBuildHash: moved.fromBuild,
14715
+ toBuildHash: moved.toBuild
14716
+ };
14717
+ }
14718
+ };
14719
+
14720
+ // src/agents/gateway.ts
14721
+ init_platformEndpoint();
14722
+ init_transport();
14723
+
14724
+ // src/agents/run.ts
14725
+ init_apiError();
14726
+ init_transport();
14727
+
14728
+ // src/agents/sse.ts
14729
+ var EventStreamError = class extends Error {
14730
+ constructor(code, message) {
14731
+ super(message);
14732
+ this.code = code;
14733
+ this.name = "EventStreamError";
14734
+ }
14735
+ code;
14736
+ };
14737
+ var SseLimits = class _SseLimits {
14738
+ constructor(maxLineLength, maxEventLength) {
14739
+ this.maxLineLength = maxLineLength;
14740
+ this.maxEventLength = maxEventLength;
14741
+ }
14742
+ maxLineLength;
14743
+ maxEventLength;
14744
+ static DEFAULT = new _SseLimits(4 * 1024 * 1024, 4 * 1024 * 1024);
14745
+ };
14746
+ var EventBlock = class {
14747
+ constructor(id, limits) {
14748
+ this.id = id;
14749
+ this.limits = limits;
14750
+ }
14751
+ id;
14752
+ limits;
14753
+ #data = [];
14754
+ #length = 0;
14755
+ #type = "";
14756
+ addData(value) {
14757
+ this.#length += value.length + 1;
14758
+ if (this.#length > this.limits.maxEventLength)
14759
+ throw new EventStreamError("event_too_large", `an event passed ${this.limits.maxEventLength} characters`);
14760
+ this.#data.push(value);
14761
+ }
14762
+ setType(value) {
14763
+ this.#type = value;
14764
+ }
14765
+ setId(value) {
14766
+ if (!value.includes("\0")) this.id = value;
14767
+ }
14768
+ message() {
14769
+ if (this.#data.length === 0) return null;
14770
+ return { event: this.#type || "message", data: this.#data.join("\n"), lastEventId: this.id || null };
14771
+ }
14772
+ };
14773
+ var FIELDS2 = /* @__PURE__ */ new Map([
14774
+ ["data", (block, value) => block.addData(value)],
14775
+ ["event", (block, value) => block.setType(value)],
14776
+ ["id", (block, value) => block.setId(value)]
14777
+ ]);
14778
+ var SseParser = class {
14779
+ #decoder = new TextDecoder();
14780
+ #lineEnd = /[\r\n]/g;
14781
+ #limits;
14782
+ #pending = "";
14783
+ #afterCarriageReturn = false;
14784
+ #lastEventId;
14785
+ #block;
14786
+ constructor(lastEventId = null, limits = SseLimits.DEFAULT) {
14787
+ this.#limits = limits;
14788
+ this.#lastEventId = lastEventId ?? "";
14789
+ this.#block = new EventBlock(this.#lastEventId, limits);
14790
+ }
14791
+ /** The id a reconnect sends as `Last-Event-ID`: the last one set before a dispatched event, or null. */
14792
+ get lastEventId() {
14793
+ return this.#lastEventId || null;
14794
+ }
14795
+ /** Feed the next bytes; returns the events they completed, in order. */
14796
+ push(chunk) {
14797
+ const messages = [];
14798
+ for (const line of this.lines(this.#decoder.decode(chunk, { stream: true }))) {
14799
+ const message = this.line(line);
14800
+ if (message) messages.push(message);
14801
+ }
14802
+ return messages;
14803
+ }
14804
+ lines(text2) {
14805
+ const scanFrom = this.#pending.length;
14806
+ this.#pending += this.skipLineFeed(text2);
14807
+ const lines = [];
14808
+ let start = 0;
14809
+ this.#lineEnd.lastIndex = scanFrom;
14810
+ for (let end = this.#lineEnd.exec(this.#pending); end; end = this.#lineEnd.exec(this.#pending)) {
14811
+ lines.push(this.capped(this.#pending.slice(start, end.index)));
14812
+ start = this.lineEnd(end.index);
14813
+ this.#lineEnd.lastIndex = start;
14814
+ }
14815
+ this.#pending = this.capped(this.#pending.slice(start));
14816
+ return lines;
14817
+ }
14818
+ lineEnd(index2) {
14819
+ const crlf = this.#pending.startsWith("\r\n", index2);
14820
+ this.#afterCarriageReturn = this.#pending[index2] === "\r" && index2 + 1 === this.#pending.length;
14821
+ return index2 + (crlf ? 2 : 1);
14822
+ }
14823
+ skipLineFeed(text2) {
14824
+ if (!this.#afterCarriageReturn || text2 === "") return text2;
14825
+ this.#afterCarriageReturn = false;
14826
+ return text2.startsWith("\n") ? text2.slice(1) : text2;
14827
+ }
14828
+ capped(line) {
14829
+ if (line.length > this.#limits.maxLineLength)
14830
+ throw new EventStreamError("line_too_large", `a line passed ${this.#limits.maxLineLength} characters`);
14831
+ return line;
14832
+ }
14833
+ line(line) {
14834
+ if (line === "") return this.dispatch();
14835
+ if (line.startsWith(":")) return null;
14836
+ const colon = line.indexOf(":");
14837
+ const field2 = colon === -1 ? line : line.slice(0, colon);
14838
+ const value = colon === -1 ? "" : line.slice(colon + 1).replace(/^ /, "");
14839
+ FIELDS2.get(field2)?.(this.#block, value);
14840
+ return null;
14841
+ }
14842
+ dispatch() {
14843
+ const message = this.#block.message();
14844
+ this.#lastEventId = this.#block.id;
14845
+ this.#block = new EventBlock(this.#lastEventId, this.#limits);
14846
+ return message;
14847
+ }
14848
+ };
14849
+
14850
+ // src/agents/run.ts
14851
+ var SYSTEM_CLOCK = Object.freeze({
14852
+ now: () => Date.now(),
14853
+ sleep: (ms, signal) => new Promise((resolve11, reject) => {
14854
+ if (signal?.aborted) return reject(signal.reason);
14855
+ const abort = () => {
14856
+ clearTimeout(timer);
14857
+ reject(signal?.reason);
14858
+ };
14859
+ const timer = setTimeout(() => {
14860
+ signal?.removeEventListener("abort", abort);
14861
+ resolve11();
14862
+ }, ms);
14863
+ signal?.addEventListener("abort", abort, { once: true });
14864
+ })
14865
+ });
14866
+ var ReconnectPolicy = class _ReconnectPolicy {
14867
+ constructor(delaysMs, idleMs) {
14868
+ this.delaysMs = delaysMs;
14869
+ this.idleMs = idleMs;
14870
+ }
14871
+ delaysMs;
14872
+ idleMs;
14873
+ static DEFAULT = new _ReconnectPolicy([250, 500, 1e3, 2e3, 4e3], PLATFORM_STREAM_IDLE_MS);
14874
+ };
14875
+ var STOPS = {
14876
+ "run.started": "continues",
14877
+ "step.attempt": "continues",
14878
+ "message.delta": "continues",
14879
+ "step.completed": "continues",
14880
+ "tool.started": "continues",
14881
+ "tool.completed": "continues",
14882
+ "run.error": "continues",
14883
+ "action.required": "waits",
14884
+ "run.completed": "ends",
14885
+ "run.failed": "ends",
14886
+ "run.cancelled": "ends"
14887
+ };
14888
+ var FINISHED = /* @__PURE__ */ new Set(["completed", "failed", "cancelled"]);
14889
+ var REFRESH_RETRIES = 3;
14890
+ var STREAM_REFUSALS_RETRIED = /* @__PURE__ */ new Set(["too_many_streams"]);
14891
+ var runRoute = (threadId, runId) => `/api/public/threads/${segment(threadId)}/runs/${segment(runId)}`;
14892
+ function readEvent(message) {
14893
+ if (!Object.hasOwn(STOPS, message.event)) return null;
14894
+ const data = parseJson2(message.data);
14895
+ if (typeof data !== "object" || data === null || data.type !== message.event)
14896
+ throw new EventStreamError("malformed_event", `a ${message.event} event whose data is not that event's JSON`);
14897
+ return data;
14898
+ }
14899
+ function retried(refusal) {
14900
+ return RetryPolicy.TRANSIENT_STATUSES.has(refusal.status) || STREAM_REFUSALS_RETRIED.has(refusal.code ?? "");
14901
+ }
14902
+ function parseJson2(text2) {
14903
+ try {
14904
+ return JSON.parse(text2);
14905
+ } catch {
14906
+ return void 0;
14907
+ }
14908
+ }
14909
+ var Connection = class {
14910
+ constructor(openedAt) {
14911
+ this.openedAt = openedAt;
14912
+ }
14913
+ openedAt;
14914
+ #delivered = false;
14915
+ #closedCleanly = false;
14916
+ #stop = "continues";
14917
+ #why = "the stream closed before the run ended";
14918
+ get ended() {
14919
+ return this.#stop === "ends";
14920
+ }
14921
+ // The door closes after action.required only while the run waits; when more events follow, that wait was answered.
14922
+ get stopped() {
14923
+ return this.#stop !== "continues";
14924
+ }
14925
+ get why() {
14926
+ return this.#why;
14927
+ }
14928
+ delivered() {
14929
+ this.#delivered = true;
14930
+ }
14931
+ at(stop) {
14932
+ this.#stop = stop;
14933
+ }
14934
+ closedCleanly() {
14935
+ this.#closedCleanly = true;
14936
+ }
14937
+ refused(status) {
14938
+ this.#why = `the platform answered ${status}`;
14939
+ }
14940
+ dropped(error) {
14941
+ if (!(error instanceof UnreachableError)) throw error;
14942
+ this.#why = error.message;
14943
+ }
14944
+ // A silence cut, a drop or a refused status never counts as working, however long it took: only an event, or the
14945
+ // platform's own clean close of a stream that lived the idle budget (its lifetime close), starts the count again.
14946
+ working(now, idleMs) {
14947
+ return this.#delivered || this.#closedCleanly && now - this.openedAt >= idleMs;
14948
+ }
14949
+ };
14950
+ var Reconnects = class {
14951
+ constructor(policy, clock, route2) {
14952
+ this.policy = policy;
14953
+ this.clock = clock;
14954
+ this.route = route2;
14955
+ }
14956
+ policy;
14957
+ clock;
14958
+ route;
14959
+ #inARow = 0;
14960
+ async after(connection, signal) {
14961
+ this.#inARow = connection.working(this.clock.now(), this.policy.idleMs) ? 1 : this.#inARow + 1;
14962
+ const delayMs = this.policy.delaysMs[this.#inARow - 1];
14963
+ if (delayMs === void 0)
14964
+ throw new EventStreamError(
14965
+ "reconnects_exhausted",
14966
+ `GET ${this.route}: no working stream after ${this.policy.delaysMs.length} reconnects in a row; last: ${connection.why}`
14967
+ );
14968
+ await this.clock.sleep(delayMs, signal);
14969
+ }
14970
+ };
14971
+ var AgentRun = class {
14972
+ #transport;
14973
+ #clock;
14974
+ #reconnect;
14975
+ #snapshot;
14976
+ #cursor = null;
14977
+ #ending = null;
14978
+ constructor(transport, run, options = {}) {
14979
+ this.#transport = transport;
14980
+ this.#snapshot = run;
14981
+ this.#clock = options.clock ?? SYSTEM_CLOCK;
14982
+ this.#reconnect = options.reconnect ?? ReconnectPolicy.DEFAULT;
14983
+ }
14984
+ get id() {
14985
+ return this.#snapshot.id;
14986
+ }
14987
+ get threadId() {
14988
+ return this.#snapshot.threadId;
14989
+ }
14990
+ /** The run as last read from the platform. */
14991
+ get snapshot() {
14992
+ return this.#snapshot;
14993
+ }
14994
+ /** The id of the last event delivered by any reader; pass it as `after` to resume this run's events elsewhere. */
14995
+ get cursor() {
14996
+ return this.#cursor;
14997
+ }
14998
+ /**
14999
+ * The run's events from `after` (default: where the last `events()` stopped, else the start). A dropped connection, a
15000
+ * silence past the idle budget (60 s), a 502/503/504, a 429 `too_many_streams` or the platform closing the stream
15001
+ * reconnects with `Last-Event-ID`,
15002
+ * so each event arrives once; after 5 reconnects in a row with no event delivered (a clean close after at least the idle
15003
+ * budget also counts as working) it throws `EventStreamError`. Ends after `run.completed`, `run.failed` (`not_found` when
15004
+ * the run no longer exists) or `run.cancelled`, and at an `action.required` the platform ends the stream on (the run waits
15005
+ * for a person); an `action.required` followed by more events was a wait already answered, and the events go on. A key
15006
+ * holds at most 64 open streams: past that the platform answers 429 `too_many_streams`, which counts against the same
15007
+ * five reconnects.
15008
+ */
15009
+ async *events(options = {}) {
15010
+ const position = { cursor: options.after === void 0 ? this.#cursor : options.after };
15011
+ this.#ending = null;
15012
+ const reconnects = new Reconnects(this.#reconnect, this.#clock, `${runRoute(this.threadId, this.id)}/events`);
15013
+ for (; ; ) {
15014
+ const connection = new Connection(this.#clock.now());
15015
+ yield* this.connect(position, connection, options.signal);
15016
+ if (connection.stopped) return;
15017
+ await reconnects.after(connection, options.signal);
15018
+ }
15019
+ }
15020
+ /** 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. */
15021
+ async wait(options = {}) {
15022
+ const polls = this.#reconnect.delaysMs[Symbol.iterator]();
15023
+ let run = this.#ending === null ? this.#snapshot : await this.refresh(options);
15024
+ while (!this.settled(run)) {
15025
+ await this.advance(polls, options.signal);
15026
+ run = await this.refresh(options);
15027
+ }
15028
+ return run;
15029
+ }
15030
+ /** 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. */
15031
+ async refresh(options = {}) {
15032
+ const { signal } = options;
15033
+ const retry = new RetryPolicy(
15034
+ this.#reconnect.delaysMs.slice(0, REFRESH_RETRIES),
15035
+ (ms) => this.#clock.sleep(ms, signal)
15036
+ );
15037
+ return this.take(
15038
+ await this.#transport.json("GET", `${runRoute(this.threadId, this.id)}`, void 0, { retry, signal })
15039
+ );
15040
+ }
15041
+ /** Stop the run; a run already finished answers with its status. */
15042
+ async cancel(options = {}) {
15043
+ const { signal } = options;
15044
+ return this.take(
15045
+ await this.#transport.json("POST", `${runRoute(this.threadId, this.id)}/cancel`, {}, { signal })
15046
+ );
15047
+ }
15048
+ /** Answer the question the run waits on; the run is queued again and `events()` continues from where it stopped. */
15049
+ async resolve(answer, options = {}) {
15050
+ const body = { actionId: answer.actionId, answer: answer.answer };
15051
+ const { signal } = options;
15052
+ const run = await this.#transport.json("POST", `${runRoute(this.threadId, this.id)}/resolve`, body, {
15053
+ signal
15054
+ });
15055
+ this.#ending = null;
15056
+ return this.take(run);
15057
+ }
15058
+ settled(run) {
15059
+ return FINISHED.has(run.status) || this.#ending === "action.required" && run.status === "requires_action";
15060
+ }
15061
+ async advance(polls, signal) {
15062
+ if (this.#ending !== null && this.#ending !== "action.required") return this.pause(polls, signal);
15063
+ const before = this.#cursor;
15064
+ for await (const event of this.events({ signal })) void event;
15065
+ if (this.#ending === "action.required" && this.#cursor === before) await this.pause(polls, signal);
15066
+ }
15067
+ async pause(polls, signal) {
15068
+ const delay = polls.next();
15069
+ if (delay.done)
15070
+ throw new EventStreamError(
15071
+ "run_not_finished",
15072
+ `${runRoute(this.threadId, this.id)}: the stream ended the run with ${this.#ending}, and the platform still reads it as ${this.#snapshot.status}`
15073
+ );
15074
+ await this.#clock.sleep(delay.value, signal);
15075
+ }
15076
+ take(run) {
15077
+ this.#snapshot = run;
15078
+ return run;
15079
+ }
15080
+ async *connect(position, connection, signal) {
15081
+ const stream = await this.open(position, connection, signal);
15082
+ if (!stream) return;
15083
+ try {
15084
+ yield* this.read(stream, position, connection);
15085
+ connection.closedCleanly();
15086
+ } catch (error) {
15087
+ connection.dropped(error);
15088
+ } finally {
15089
+ stream.close();
15090
+ }
15091
+ }
15092
+ async open(position, connection, signal) {
15093
+ const route2 = `${runRoute(this.threadId, this.id)}/events`;
15094
+ try {
15095
+ const stream = await this.#transport.stream(route2, {
15096
+ after: position.cursor,
15097
+ signal,
15098
+ idleMs: this.#reconnect.idleMs
15099
+ });
15100
+ return await this.accepted(stream, route2, connection);
15101
+ } catch (error) {
15102
+ connection.dropped(error);
15103
+ return null;
15104
+ }
15105
+ }
15106
+ async accepted(stream, route2, connection) {
15107
+ if (stream.ok) return stream;
15108
+ const refusal = new ApiError(stream.status, "GET", route2, await stream.text());
15109
+ if (!retried(refusal)) throw refusal;
15110
+ connection.refused(stream.status);
15111
+ return null;
15112
+ }
15113
+ async *read(stream, position, connection) {
15114
+ const parser = new SseParser(position.cursor);
15115
+ for await (const chunk of stream.chunks()) {
15116
+ for (const message of parser.push(chunk)) {
15117
+ const event = readEvent(message);
15118
+ this.moveTo(position, message.lastEventId);
15119
+ if (!event) continue;
15120
+ connection.delivered();
15121
+ this.note(event, connection);
15122
+ yield event;
15123
+ if (connection.ended) return;
15124
+ }
15125
+ this.moveTo(position, parser.lastEventId);
15126
+ }
15127
+ }
15128
+ // Each events() call resumes from its own position, so two readers of one run never skip or repeat each other's events.
15129
+ moveTo(position, cursor) {
15130
+ position.cursor = cursor;
15131
+ this.#cursor = cursor;
15132
+ }
15133
+ note(event, connection) {
15134
+ const stop = STOPS[event.type];
15135
+ this.#ending = stop === "continues" ? null : event.type;
15136
+ connection.at(stop);
15137
+ }
15138
+ };
15139
+
15140
+ // src/agents/threads.ts
15141
+ var threadRoute = (threadId) => `/api/public/threads/${segment(threadId)}`;
15142
+ var Thread = class {
15143
+ #transport;
15144
+ #runs;
15145
+ id;
15146
+ agent;
15147
+ title;
15148
+ autonomy;
15149
+ activeRun;
15150
+ createdAt;
15151
+ /** Granted tools this key cannot activate; only on the thread `create` returns. */
15152
+ warnings;
15153
+ constructor(transport, record, runs = {}) {
15154
+ this.#transport = transport;
15155
+ this.#runs = runs;
15156
+ this.id = record.id;
15157
+ this.agent = record.agent;
15158
+ this.title = record.title;
15159
+ this.autonomy = Object.freeze({ ...record.autonomy });
15160
+ this.activeRun = record.activeRun ? Object.freeze({ ...record.activeRun }) : null;
15161
+ this.createdAt = record.createdAt;
15162
+ this.warnings = Object.freeze([...record.warnings ?? []]);
15163
+ }
15164
+ /** Start a run on the agent's deployed version (or `version`); refused with 409 `thread_busy` while another run is active. */
15165
+ async send(input, options = {}) {
15166
+ const body = { input, version: options.version, multitask: options.multitask };
15167
+ const run = await this.#transport.json("POST", `${threadRoute(this.id)}/runs`, body);
15168
+ return new AgentRun(this.#transport, run, this.#runs);
15169
+ }
15170
+ /** A run of this thread by id, as it is now. */
15171
+ async run(runId) {
15172
+ const run = await this.#transport.json("GET", `${threadRoute(this.id)}/runs/${segment(runId)}`);
15173
+ return new AgentRun(this.#transport, run, this.#runs);
15174
+ }
15175
+ };
15176
+ var Threads = class {
15177
+ #transport;
15178
+ #runs;
15179
+ constructor(transport, runs = {}) {
15180
+ this.#transport = transport;
15181
+ this.#runs = runs;
15182
+ }
15183
+ /** A thread for a deployed agent; `allowSelfSchedule` or `allowSubagents` set to `true` is refused (400 `autonomy_unsupported`). */
15184
+ async create(options) {
15185
+ const agent = typeof options.agent === "string" ? options.agent : options.agent.name;
15186
+ const body = { agent, title: options.title, autonomy: options.autonomy };
15187
+ const record = await this.#transport.json("POST", "/api/public/threads", body);
15188
+ return new Thread(this.#transport, record, this.#runs);
15189
+ }
15190
+ async get(threadId) {
15191
+ const record = await this.#transport.json("GET", `${threadRoute(threadId)}`);
15192
+ return new Thread(this.#transport, record, this.#runs);
15193
+ }
15194
+ };
15195
+
15196
+ // src/agents/gateway.ts
15197
+ var Gateway = class {
15198
+ agents;
15199
+ threads;
15200
+ constructor(options = {}) {
15201
+ const transport = options.transport ?? new PlatformTransport(requirePlatformEndpoint(options));
15202
+ this.threads = new Threads(transport, { clock: options.clock, reconnect: options.reconnect });
15203
+ this.agents = new Agents(transport, this.threads);
15204
+ Object.freeze(this);
15205
+ }
15206
+ };
15207
+
15208
+ // src/agents/tools.ts
15209
+ var AGENT_MODELS = ["claude-opus-5", "claude-sonnet-5"];
15210
+ var AGENT_EFFORTS = ["low", "medium", "high", "xhigh"];
15211
+ var TOOL_SERVERS = {
15212
+ docs: ["search_docs"],
15213
+ drive: ["get_drive_file", "list_drive_files", "save_drive_file"],
15214
+ sandbox: [
15215
+ "copy_file",
15216
+ "execute_python",
15217
+ "grep_files",
15218
+ "ingest_sessions_to_sandbox",
15219
+ "list_files",
15220
+ "query_json",
15221
+ "read_file",
15222
+ "run_bash",
15223
+ "run_gateway_cli",
15224
+ "write_file"
15225
+ ],
15226
+ web: ["download_url_to_drive", "fetch_url"]
15227
+ };
15228
+ var grant = (server) => (options = {}) => options.only ? { server, only: [...options.only] } : { server };
15229
+ var tools = Object.freeze({
15230
+ sandbox: grant("sandbox"),
15231
+ drive: grant("drive"),
15232
+ web: grant("web"),
15233
+ docs: grant("docs")
15234
+ });
15235
+
13056
15236
  // src/files/index.ts
13057
15237
  var files_exports = {};
13058
15238
  __export(files_exports, {
@@ -13417,7 +15597,7 @@ __export(hooks_exports, {
13417
15597
  normalizeEvent: () => normalizeEvent,
13418
15598
  pageTitle: () => pageTitle,
13419
15599
  parseHookConfig: () => parseHookConfig,
13420
- parseJson: () => parseJson2,
15600
+ parseJson: () => parseJson3,
13421
15601
  parseMatcher: () => parseMatcher,
13422
15602
  parseRegex: () => parseRegex,
13423
15603
  parseStdout: () => parseStdout,
@@ -13895,7 +16075,7 @@ function emailPairs(real, fake) {
13895
16075
  }
13896
16076
  function phoneForms(number) {
13897
16077
  const digits = number.replace(/\D/g, "");
13898
- const forms = [
16078
+ const forms2 = [
13899
16079
  ["raw", number],
13900
16080
  ["digits", digits],
13901
16081
  ["plus", `+${digits}`]
@@ -13906,7 +16086,7 @@ function phoneForms(number) {
13906
16086
  const c = digits.slice(-4);
13907
16087
  const country = digits.slice(0, -10);
13908
16088
  const prefix = country ? `+${country} ` : "";
13909
- forms.push(
16089
+ forms2.push(
13910
16090
  ["spaced", `${prefix}${a} ${b} ${c}`],
13911
16091
  ["dashed", `${prefix}${a}-${b}-${c}`],
13912
16092
  ["paren", `${prefix}(${a}) ${b}-${c}`],
@@ -13916,7 +16096,7 @@ function phoneForms(number) {
13916
16096
  ["local_paren", `(${a}) ${b}-${c}`]
13917
16097
  );
13918
16098
  }
13919
- return forms;
16099
+ return forms2;
13920
16100
  }
13921
16101
  function phonePairs(real, fake) {
13922
16102
  const fakeForms = new Map(phoneForms(fake));
@@ -14648,172 +16828,382 @@ function mirrorHandle(handle, identity) {
14648
16828
  var fs14 = __toESM(require("fs"));
14649
16829
 
14650
16830
  // src/cli/platform/worldData/toml.ts
16831
+ var TomlDateTime = class {
16832
+ constructor(text2) {
16833
+ this.text = text2;
16834
+ }
16835
+ text;
16836
+ toString() {
16837
+ return this.text;
16838
+ }
16839
+ };
14651
16840
  var TomlError = class extends Error {
14652
16841
  };
14653
16842
  function parseToml(text2) {
14654
- const root = {};
14655
- let current = root;
14656
- const lines = joinContinuations(text2);
14657
- for (const [number, rawLine] of lines.entries()) {
14658
- const line = stripComment(rawLine).trim();
14659
- if (!line) continue;
14660
- const arrayTable = /^\[\[\s*([^\]]+?)\s*\]\]$/.exec(line);
14661
- if (arrayTable) {
14662
- const parent = tableAt(root, keyPath(arrayTable[1]).slice(0, -1));
14663
- const name = keyPath(arrayTable[1]).at(-1);
14664
- const list = parent[name] ??= [];
14665
- if (!Array.isArray(list)) throw new TomlError(`line ${number + 1}: ${name} is not an array of tables`);
14666
- current = {};
14667
- list.push(current);
14668
- continue;
14669
- }
14670
- const table2 = /^\[\s*([^\]]+?)\s*\]$/.exec(line);
14671
- if (table2) {
14672
- current = tableAt(root, keyPath(table2[1]));
14673
- continue;
16843
+ return new TomlReader(text2).read();
16844
+ }
16845
+ var BARE_KEY = /^[A-Za-z0-9_-]+$/;
16846
+ var CONTROL = /[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/;
16847
+ var COMMENT_CONTROL = /[\x00-\x08\x0a-\x1f\x7f]/;
16848
+ var DEC_INT = /^[+-]?(?:0|[1-9](?:_?\d)*)$/;
16849
+ var RADIX_INT = [
16850
+ [/^0x[0-9A-Fa-f](?:_?[0-9A-Fa-f])*$/, 16],
16851
+ [/^0o[0-7](?:_?[0-7])*$/, 8],
16852
+ [/^0b[01](?:_?[01])*$/, 2]
16853
+ ];
16854
+ var FLOAT = /^[+-]?(?:0|[1-9](?:_?\d)*)(?:\.\d(?:_?\d)*)?(?:[eE][+-]?\d(?:_?\d)*)?$/;
16855
+ var SPECIAL_FLOAT = /^([+-]?)(inf|nan)$/;
16856
+ var DATE_TIME = /^(\d{4})-(\d{2})-(\d{2})(?:[Tt ](\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:[Zz]|[+-](\d{2}):(\d{2}))?)?/;
16857
+ var LOCAL_TIME = /^(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?/;
16858
+ var INLINE = /* @__PURE__ */ new WeakSet();
16859
+ var newTable = () => /* @__PURE__ */ Object.create(null);
16860
+ var own = (table2, key2) => Object.prototype.hasOwnProperty.call(table2, key2) ? table2[key2] : void 0;
16861
+ var isTomlTable = (value) => value !== void 0 && typeof value === "object" && Object.getPrototypeOf(value) === null;
16862
+ var stripBlank = (text2) => text2.replace(/^[ \t]+|[ \t]+$/g, "");
16863
+ var TomlReader = class {
16864
+ constructor(text2) {
16865
+ this.text = text2;
16866
+ }
16867
+ text;
16868
+ root = newTable();
16869
+ current = this.root;
16870
+ defined = /* @__PURE__ */ new WeakSet();
16871
+ byHeader = /* @__PURE__ */ new WeakSet();
16872
+ byDottedKey = /* @__PURE__ */ new WeakSet();
16873
+ tableArrays = /* @__PURE__ */ new WeakSet();
16874
+ read() {
16875
+ for (const { text: text2, line } of logicalLines(this.text)) this.statement(stripBlank(text2), line);
16876
+ return this.root;
16877
+ }
16878
+ statement(text2, line) {
16879
+ if (!text2) return;
16880
+ const arrayTable = /^\[\[[ \t]*(.+?)[ \t]*\]\]$/.exec(text2);
16881
+ if (arrayTable) return this.arrayTable(keyPath(arrayTable[1], line), line);
16882
+ const header = /^\[[ \t]*(.+?)[ \t]*\]$/.exec(text2);
16883
+ if (header) return this.header(keyPath(header[1], line), line);
16884
+ const eq = outsideQuotes(text2, "=");
16885
+ if (eq === -1) throw new TomlError(`line ${line}: expected key = value`);
16886
+ const path17 = keyPath(text2.slice(0, eq), line);
16887
+ const [value, rest] = readValue(text2.slice(eq + 1), line);
16888
+ if (stripBlank(rest)) throw new TomlError(`line ${line}: unexpected text after value`);
16889
+ assign(this.descend(this.current, path17.slice(0, -1), line, "key"), path17, value, line);
16890
+ }
16891
+ header(path17, line) {
16892
+ const parent = this.descend(this.root, path17.slice(0, -1), line, "header");
16893
+ const name = path17.at(-1);
16894
+ const table2 = own(parent, name) ?? newTable();
16895
+ const fresh = isTomlTable(table2) && !INLINE.has(table2) && !this.byDottedKey.has(table2) && !this.defined.has(table2);
16896
+ if (!fresh) throw new TomlError(`line ${line}: [${path17.join(".")}] is defined twice`);
16897
+ parent[name] = table2;
16898
+ this.open(table2);
16899
+ }
16900
+ arrayTable(path17, line) {
16901
+ const parent = this.descend(this.root, path17.slice(0, -1), line, "header");
16902
+ const name = path17.at(-1);
16903
+ const existing = own(parent, name);
16904
+ if (existing !== void 0 && !(Array.isArray(existing) && this.tableArrays.has(existing)))
16905
+ throw new TomlError(`line ${line}: ${path17.join(".")} is not an array of tables`);
16906
+ const list2 = existing ?? [];
16907
+ this.tableArrays.add(list2);
16908
+ parent[name] = list2;
16909
+ const table2 = newTable();
16910
+ list2.push(table2);
16911
+ this.open(table2);
16912
+ }
16913
+ open(table2) {
16914
+ this.defined.add(table2);
16915
+ this.byHeader.add(table2);
16916
+ this.current = table2;
16917
+ }
16918
+ descend(from, parts2, line, via) {
16919
+ let node = from;
16920
+ for (const part of parts2) {
16921
+ const next = own(node, part);
16922
+ node = next === void 0 ? this.make(node, part, via) : this.enter(next, part, line, via);
14674
16923
  }
14675
- const eq = line.indexOf("=");
14676
- if (eq === -1) throw new TomlError(`line ${number + 1}: expected key = value`);
14677
- const key2 = unquoteKey(line.slice(0, eq).trim());
14678
- const [value, rest] = readValue(line.slice(eq + 1).trim(), number + 1);
14679
- if (rest.trim()) throw new TomlError(`line ${number + 1}: unexpected text after value`);
14680
- current[key2] = value;
16924
+ return node;
14681
16925
  }
14682
- return root;
14683
- }
14684
- function keyPath(header) {
14685
- return header.split(".").map((part) => unquoteKey(part.trim()));
14686
- }
14687
- function unquoteKey(key2) {
14688
- if (key2.startsWith('"') && key2.endsWith('"') || key2.startsWith("'") && key2.endsWith("'")) return key2.slice(1, -1);
14689
- return key2;
16926
+ make(parent, part, via) {
16927
+ const table2 = newTable();
16928
+ (via === "header" ? this.byHeader : this.byDottedKey).add(table2);
16929
+ parent[part] = table2;
16930
+ return table2;
16931
+ }
16932
+ enter(value, part, line, via) {
16933
+ const target = via === "header" && Array.isArray(value) && this.tableArrays.has(value) ? value.at(-1) : value;
16934
+ const open = isTomlTable(target) && !INLINE.has(target) && !(via === "key" && this.defined.has(target));
16935
+ if (!open) throw new TomlError(`line ${line}: ${part} is already defined and cannot be extended here`);
16936
+ if (via === "key") this.byDottedKey.add(target);
16937
+ return target;
16938
+ }
16939
+ };
16940
+ function assign(table2, path17, value, line) {
16941
+ const key2 = path17.at(-1);
16942
+ if (own(table2, key2) !== void 0) throw new TomlError(`line ${line}: key ${path17.join(".")} is defined twice`);
16943
+ table2[key2] = value;
14690
16944
  }
14691
- function tableAt(root, parts2) {
14692
- let node = root;
16945
+ function inlineAt(table2, parts2, line) {
16946
+ let node = table2;
14693
16947
  for (const part of parts2) {
14694
- const next = node[part] ??= {};
14695
- if (Array.isArray(next)) {
14696
- const last = next[next.length - 1];
14697
- if (!last || typeof last !== "object" || Array.isArray(last)) throw new TomlError(`${part} is not a table`);
14698
- node = last;
14699
- } else if (typeof next !== "object") throw new TomlError(`${part} is not a table`);
14700
- else node = next;
16948
+ const next = own(node, part) ?? newTable();
16949
+ if (!isTomlTable(next) || INLINE.has(next))
16950
+ throw new TomlError(`line ${line}: ${part} is already defined and cannot be extended here`);
16951
+ node[part] = next;
16952
+ node = next;
14701
16953
  }
14702
16954
  return node;
14703
16955
  }
14704
- function joinContinuations(text2) {
14705
- const out = [];
14706
- let pending = "";
14707
- let depth = 0;
14708
- for (const physical of text2.split(/\r?\n/)) {
14709
- const raw = stripComment(physical);
14710
- const line = pending ? pending + "\n" + raw : raw;
14711
- depth = bracketDepth(line);
14712
- if (depth > 0) {
14713
- pending = line;
14714
- continue;
14715
- }
14716
- pending = "";
14717
- out.push(line);
16956
+ function keyPath(text2, line) {
16957
+ const parts2 = [];
16958
+ let rest = text2;
16959
+ for (; ; ) {
16960
+ const dot = outsideQuotes(rest, ".");
16961
+ parts2.push(readKey(stripBlank(dot === -1 ? rest : rest.slice(0, dot)), line));
16962
+ if (dot === -1) return parts2;
16963
+ rest = rest.slice(dot + 1);
14718
16964
  }
14719
- if (pending) out.push(pending);
14720
- return out;
14721
16965
  }
14722
- function bracketDepth(line) {
14723
- let depth = 0;
14724
- let quote = null;
14725
- for (let i = 0; i < line.length; i++) {
14726
- const c = line[i];
14727
- if (quote) {
14728
- if (c === "\\" && quote === '"') i++;
14729
- else if (c === quote) quote = null;
14730
- continue;
14731
- }
14732
- if (c === '"' || c === "'") quote = c;
14733
- else if (c === "[" || c === "{") depth++;
14734
- else if (c === "]" || c === "}") depth--;
14735
- }
14736
- return depth;
16966
+ function readKey(part, line) {
16967
+ const quote = openingQuote(part, 0);
16968
+ if (quote === null && BARE_KEY.test(part)) return part;
16969
+ const read = quote?.length === 1 ? readString(part, line) : null;
16970
+ if (!read || read[1] !== "") throw new TomlError(`line ${line}: \`${part}\` is not a key; quote it`);
16971
+ return read[0];
14737
16972
  }
14738
- function stripComment(line) {
16973
+ function outsideQuotes(text2, char) {
14739
16974
  let quote = null;
14740
- for (let i = 0; i < line.length; i++) {
14741
- const c = line[i];
16975
+ for (let i = 0; i < text2.length; i++) {
16976
+ const c = text2[i];
14742
16977
  if (quote) {
14743
16978
  if (c === "\\" && quote === '"') i++;
14744
16979
  else if (c === quote) quote = null;
14745
16980
  continue;
14746
16981
  }
14747
16982
  if (c === '"' || c === "'") quote = c;
14748
- else if (c === "#") return line.slice(0, i);
16983
+ else if (c === char) return i;
16984
+ }
16985
+ return -1;
16986
+ }
16987
+ function openingQuote(text2, i) {
16988
+ const c = text2[i];
16989
+ if (c !== '"' && c !== "'") return null;
16990
+ return text2.startsWith(c.repeat(3), i) ? c.repeat(3) : c;
16991
+ }
16992
+ function quoteRun(text2, i, quote, line) {
16993
+ let run = 0;
16994
+ while (text2[i + run] === quote) run++;
16995
+ if (run > 5) throw new TomlError(`line ${line}: too many quotes close a multi-line string`);
16996
+ return run;
16997
+ }
16998
+ var LogicalLines = class {
16999
+ constructor(text2) {
17000
+ this.text = text2;
17001
+ }
17002
+ text;
17003
+ out = [];
17004
+ brackets = [];
17005
+ buffer = "";
17006
+ start = 1;
17007
+ line = 1;
17008
+ quote = null;
17009
+ i = 0;
17010
+ split() {
17011
+ if (this.text.startsWith("\uFEFF")) throw new TomlError("line 1: a byte order mark is not TOML");
17012
+ for (; this.i < this.text.length; this.i++) this.step(this.text[this.i]);
17013
+ if (this.quote) throw new TomlError(`line ${this.start}: unterminated string`);
17014
+ if (this.brackets.length > 0) throw new TomlError(`line ${this.start}: a bracket or brace is never closed`);
17015
+ this.out.push({ text: this.buffer, line: this.start });
17016
+ return this.out;
17017
+ }
17018
+ step(c) {
17019
+ if (c === "\n") this.line++;
17020
+ if (this.quote) return this.inString(c, this.quote);
17021
+ if (c === "#") return this.skipComment();
17022
+ const opened = openingQuote(this.text, this.i);
17023
+ if (opened) return this.openString(opened);
17024
+ this.outside(c);
17025
+ }
17026
+ inString(c, quote) {
17027
+ if (c === "\n" && quote.length === 1) throw new TomlError(`line ${this.line - 1}: unterminated string`);
17028
+ if (c === "\\" && quote.startsWith('"')) return this.escape();
17029
+ if (this.text.startsWith(quote, this.i)) return this.closeString(quote);
17030
+ this.buffer += c;
17031
+ }
17032
+ escape() {
17033
+ const next = this.text[this.i + 1] ?? "";
17034
+ this.buffer += "\\" + next;
17035
+ if (next === "\n") this.line++;
17036
+ this.i++;
17037
+ }
17038
+ openString(opened) {
17039
+ this.quote = opened;
17040
+ this.buffer += opened;
17041
+ this.i += opened.length - 1;
17042
+ }
17043
+ closeString(quote) {
17044
+ const run = quote.length === 3 ? quoteRun(this.text, this.i, quote[0], this.line) : 1;
17045
+ this.buffer += this.text.slice(this.i, this.i + run);
17046
+ this.i += run - 1;
17047
+ this.quote = null;
17048
+ }
17049
+ skipComment() {
17050
+ for (; this.i + 1 < this.text.length && this.text[this.i + 1] !== "\n"; this.i++)
17051
+ this.commentCharacter(this.text[this.i + 1]);
17052
+ }
17053
+ commentCharacter(c) {
17054
+ const lineEnd = c === "\r" && this.text[this.i + 2] === "\n";
17055
+ if (!lineEnd && COMMENT_CONTROL.test(c))
17056
+ throw new TomlError(`line ${this.line}: a comment holds a control character`);
17057
+ }
17058
+ outside(c) {
17059
+ if (c === "[" || c === "{") this.brackets.push(c);
17060
+ if (c === "]" || c === "}") this.brackets.pop();
17061
+ if (c === "\n" && this.brackets.at(-1) === "{")
17062
+ throw new TomlError(`line ${this.line - 1}: an inline table must be on one line`);
17063
+ if (c === "\n" && this.brackets.length === 0) return this.endLine();
17064
+ this.buffer += c;
17065
+ }
17066
+ endLine() {
17067
+ this.out.push({ text: this.buffer.replace(/\r$/, ""), line: this.start });
17068
+ this.buffer = "";
17069
+ this.start = this.line;
14749
17070
  }
14750
- return line;
14751
- }
14752
- function readValue(text2, line) {
14753
- const s = text2.trimStart();
14754
- if (s.startsWith('"')) {
14755
- let out = "";
14756
- for (let i = 1; i < s.length; i++) {
14757
- const c = s[i];
14758
- if (c === "\\") {
14759
- const e = s[++i];
14760
- const map = { n: "\n", t: " ", r: "\r", '"': '"', "\\": "\\", b: "\b", f: "\f" };
14761
- if (e === "u" || e === "U") {
14762
- const width = e === "u" ? 4 : 8;
14763
- out += String.fromCodePoint(parseInt(s.slice(i + 1, i + 1 + width), 16));
14764
- i += width;
14765
- } else if (e !== void 0 && e in map) out += map[e];
14766
- else throw new TomlError(`line ${line}: unsupported escape \\${e ?? ""}`);
14767
- continue;
14768
- }
14769
- if (c === '"') return [out, s.slice(i + 1)];
17071
+ };
17072
+ function logicalLines(text2) {
17073
+ return new LogicalLines(text2).split();
17074
+ }
17075
+ var ESCAPES = { n: "\n", t: " ", r: "\r", '"': '"', "\\": "\\", b: "\b", f: "\f" };
17076
+ function unicodeEscape(body, at, width, line) {
17077
+ const digits = body.slice(at, at + width);
17078
+ const code = /^[0-9A-Fa-f]+$/.test(digits) && digits.length === width ? parseInt(digits, 16) : -1;
17079
+ const scalar = code >= 0 && code <= 1114111 && (code < 55296 || code > 57343);
17080
+ if (!scalar) throw new TomlError(`line ${line}: \\${width === 4 ? "u" : "U"}${digits} is not a Unicode scalar value`);
17081
+ return String.fromCodePoint(code);
17082
+ }
17083
+ function decodeBasic(body, line, multiline) {
17084
+ let out = "";
17085
+ for (let i = 0; i < body.length; i++) {
17086
+ const c = body[i];
17087
+ if (c !== "\\") {
14770
17088
  out += c;
17089
+ continue;
14771
17090
  }
14772
- throw new TomlError(`line ${line}: unterminated string`);
14773
- }
14774
- if (s.startsWith("'")) {
14775
- const end = s.indexOf("'", 1);
14776
- if (end === -1) throw new TomlError(`line ${line}: unterminated string`);
14777
- return [s.slice(1, end), s.slice(end + 1)];
14778
- }
14779
- if (s.startsWith("[")) {
14780
- const items = [];
14781
- let rest2 = s.slice(1);
14782
- for (; ; ) {
14783
- rest2 = rest2.replace(/^[\s\n]+/, "");
14784
- if (rest2.startsWith("]")) return [items, rest2.slice(1)];
14785
- const [item, after] = readValue(rest2, line);
14786
- items.push(item);
14787
- rest2 = after.replace(/^[\s\n]+/, "");
14788
- if (rest2.startsWith(",")) rest2 = rest2.slice(1);
14789
- else if (!rest2.startsWith("]")) throw new TomlError(`line ${line}: expected , or ] in array`);
17091
+ const e = body[++i];
17092
+ if (multiline && /^[ \t]*\r?\n/.test(body.slice(i))) {
17093
+ while (i + 1 < body.length && /[ \t\r\n]/.test(body[i + 1])) i++;
17094
+ continue;
14790
17095
  }
17096
+ if (e === "u" || e === "U") {
17097
+ const width = e === "u" ? 4 : 8;
17098
+ out += unicodeEscape(body, i + 1, width, line);
17099
+ i += width;
17100
+ } else if (e !== void 0 && e in ESCAPES) out += ESCAPES[e];
17101
+ else throw new TomlError(`line ${line}: unsupported escape \\${e ?? ""}`);
14791
17102
  }
14792
- if (s.startsWith("{")) {
14793
- const table2 = {};
14794
- let rest2 = s.slice(1);
14795
- for (; ; ) {
14796
- rest2 = rest2.replace(/^[\s\n]+/, "");
14797
- if (rest2.startsWith("}")) return [table2, rest2.slice(1)];
14798
- const eq = rest2.indexOf("=");
14799
- if (eq === -1) throw new TomlError(`line ${line}: expected key = value in inline table`);
14800
- const key2 = unquoteKey(rest2.slice(0, eq).trim());
14801
- const [value, after] = readValue(rest2.slice(eq + 1), line);
14802
- table2[key2] = value;
14803
- rest2 = after.replace(/^[\s\n]+/, "");
14804
- if (rest2.startsWith(",")) rest2 = rest2.slice(1);
14805
- else if (!rest2.startsWith("}")) throw new TomlError(`line ${line}: expected , or } in inline table`);
17103
+ return out;
17104
+ }
17105
+ function checkControls(body, line, multiline) {
17106
+ const broken = CONTROL.test(body) || (multiline ? /\r(?!\n)/.test(body) : /[\r\n]/.test(body));
17107
+ if (broken) throw new TomlError(`line ${line}: a string holds a control character`);
17108
+ }
17109
+ function readString(s, line) {
17110
+ const quote = openingQuote(s, 0);
17111
+ if (!quote) return null;
17112
+ let end = quote.length;
17113
+ for (; end < s.length; end++) {
17114
+ if (quote.startsWith('"') && s[end] === "\\") {
17115
+ end++;
17116
+ continue;
14806
17117
  }
17118
+ if (s.startsWith(quote, end)) break;
17119
+ }
17120
+ if (end >= s.length) throw new TomlError(`line ${line}: unterminated string`);
17121
+ if (quote.length === 3) end += quoteRun(s, end, quote[0], line) - 3;
17122
+ const raw = s.slice(quote.length, end);
17123
+ const multiline = quote.length === 3;
17124
+ const body = multiline ? raw.replace(/^\r?\n/, "") : raw;
17125
+ checkControls(body, line, multiline);
17126
+ const text2 = quote.startsWith('"') ? decodeBasic(body, line, multiline) : body;
17127
+ return [text2, s.slice(end + quote.length)];
17128
+ }
17129
+ function readArray(s, line) {
17130
+ const items = [];
17131
+ let rest = s.slice(1);
17132
+ for (; ; ) {
17133
+ rest = rest.replace(/^[ \t\r\n]+/, "");
17134
+ if (rest.startsWith("]")) return [items, rest.slice(1)];
17135
+ const [item, after] = readValue(rest, line);
17136
+ items.push(item);
17137
+ rest = after.replace(/^[ \t\r\n]+/, "");
17138
+ if (rest.startsWith(",")) rest = rest.slice(1);
17139
+ else if (!rest.startsWith("]")) throw new TomlError(`line ${line}: expected , or ] in array`);
17140
+ }
17141
+ }
17142
+ function readInlineTable(s, line) {
17143
+ const table2 = newTable();
17144
+ let rest = s.slice(1).replace(/^[ \t]+/, "");
17145
+ if (rest.startsWith("}")) {
17146
+ INLINE.add(table2);
17147
+ return [table2, rest.slice(1)];
14807
17148
  }
14808
- const scalar = /^([^,\]}\s]+)/.exec(s);
17149
+ for (; ; ) {
17150
+ const eq = outsideQuotes(rest, "=");
17151
+ if (eq === -1) throw new TomlError(`line ${line}: expected key = value in inline table`);
17152
+ const path17 = keyPath(rest.slice(0, eq), line);
17153
+ const [value, after] = readValue(rest.slice(eq + 1), line);
17154
+ assign(inlineAt(table2, path17.slice(0, -1), line), path17, value, line);
17155
+ rest = after.replace(/^[ \t]+/, "");
17156
+ if (rest.startsWith("}")) {
17157
+ INLINE.add(table2);
17158
+ return [table2, rest.slice(1)];
17159
+ }
17160
+ if (!rest.startsWith(",")) throw new TomlError(`line ${line}: expected , or } in inline table`);
17161
+ rest = rest.slice(1).replace(/^[ \t]+/, "");
17162
+ if (rest.startsWith("}")) throw new TomlError(`line ${line}: an inline table takes no trailing comma`);
17163
+ }
17164
+ }
17165
+ function inRange(value, low, high) {
17166
+ return value === void 0 || Number(value) >= low && Number(value) <= high;
17167
+ }
17168
+ function readDateTime(s, line) {
17169
+ const full = DATE_TIME.exec(s);
17170
+ const time = full ? null : LOCAL_TIME.exec(s);
17171
+ const match = full ?? time;
17172
+ if (!match) return null;
17173
+ const [y, mo, d, h, mi, se, oh, om] = full ? full.slice(1) : [void 0, void 0, void 0, ...time.slice(1)];
17174
+ const day = y === void 0 ? null : new Date(Date.UTC(Number(y), Number(mo) - 1, Number(d)));
17175
+ const dateOk = day === null || day.getUTCMonth() === Number(mo) - 1 && day.getUTCDate() === Number(d);
17176
+ const timeOk = inRange(h, 0, 23) && inRange(mi, 0, 59) && inRange(se, 0, 59) && inRange(oh, 0, 23) && inRange(om, 0, 59);
17177
+ if (!dateOk || !timeOk) throw new TomlError(`line ${line}: ${match[0]} is not a valid date or time`);
17178
+ return [new TomlDateTime(match[0]), s.slice(match[0].length)];
17179
+ }
17180
+ function readNumber(token) {
17181
+ const plain = token.replace(/_/g, "");
17182
+ if (DEC_INT.test(token)) return Number(plain);
17183
+ for (const [pattern, radix] of RADIX_INT) if (pattern.test(token)) return parseInt(plain.slice(2), radix);
17184
+ if (FLOAT.test(token) && /[.eE]/.test(token)) return Number(plain);
17185
+ const special = SPECIAL_FLOAT.exec(token);
17186
+ if (!special) return null;
17187
+ if (special[2] === "nan") return NaN;
17188
+ return special[1] === "-" ? -Infinity : Infinity;
17189
+ }
17190
+ function readValue(text2, line) {
17191
+ const s = text2.replace(/^[ \t]+/, "");
17192
+ const string = readString(s, line);
17193
+ if (string) return string;
17194
+ if (s.startsWith("[")) return readArray(s, line);
17195
+ if (s.startsWith("{")) return readInlineTable(s, line);
17196
+ const date = readDateTime(s, line);
17197
+ if (date) return date;
17198
+ const scalar = /^([^,\]}\s#]+)/.exec(s);
14809
17199
  if (!scalar) throw new TomlError(`line ${line}: expected a value`);
14810
17200
  const token = scalar[1];
14811
17201
  const rest = s.slice(token.length);
14812
17202
  if (token === "true") return [true, rest];
14813
17203
  if (token === "false") return [false, rest];
14814
- if (/^[+-]?\d[\d_]*$/.test(token)) return [Number(token.replace(/_/g, "")), rest];
14815
- if (/^[+-]?(\d[\d_]*)?\.?\d[\d_]*([eE][+-]?\d+)?$/.test(token)) return [Number(token.replace(/_/g, "")), rest];
14816
- throw new TomlError(`line ${line}: unsupported value ${token}`);
17204
+ const number = readNumber(token);
17205
+ if (number === null) throw new TomlError(`line ${line}: unsupported value ${token}`);
17206
+ return [number, rest];
14817
17207
  }
14818
17208
 
14819
17209
  // src/hooks/events.ts
@@ -15226,15 +17616,15 @@ function parseLive(raw, toolsRaw) {
15226
17616
  );
15227
17617
  if (!isObject4(toolsRaw))
15228
17618
  throw new HookConfigError("`tools` must be a table of [tools.<name>]");
15229
- const tools = {};
17619
+ const tools2 = {};
15230
17620
  for (const [name, spec] of Object.entries(toolsRaw))
15231
- tools[name] = parseTool(name, spec, allowed);
17621
+ tools2[name] = parseTool(name, spec, allowed);
15232
17622
  return {
15233
17623
  ...typeof raw.record === "string" && raw.record ? { record: raw.record } : {},
15234
17624
  ...typeof raw.replay === "string" && raw.replay ? { replay: raw.replay } : {},
15235
17625
  allowedEnv: allowed,
15236
17626
  timeout,
15237
- tools
17627
+ tools: tools2
15238
17628
  };
15239
17629
  }
15240
17630
  function parseTool(name, raw, allowedEnv) {
@@ -15516,7 +17906,7 @@ function loadHookConfig(file) {
15516
17906
  }
15517
17907
  return parseHookConfig(data, file);
15518
17908
  }
15519
- var isObject4 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
17909
+ var isObject4 = (v) => typeof v === "object" && v !== null && [null, Object.prototype].includes(Object.getPrototypeOf(v));
15520
17910
  function parseHookConfig(data, source) {
15521
17911
  const where = source ?? "config";
15522
17912
  if (!isObject4(data))
@@ -15538,12 +17928,12 @@ function parseHookConfig(data, source) {
15538
17928
  throw new HookConfigError(
15539
17929
  `hooks.${rawEvent}: unknown event; expected one of ${EVENTS.join(", ")} (or PreToolUse, PostToolUse, Stop)`
15540
17930
  );
15541
- const list = isObject4(rawRules) ? [rawRules] : rawRules;
15542
- if (!Array.isArray(list))
17931
+ const list2 = isObject4(rawRules) ? [rawRules] : rawRules;
17932
+ if (!Array.isArray(list2))
15543
17933
  throw new HookConfigError(
15544
17934
  `hooks.${rawEvent}: expected an array of rules ([[hooks.${rawEvent}]])`
15545
17935
  );
15546
- list.forEach(
17936
+ list2.forEach(
15547
17937
  (raw, index2) => rules.push(parseRule(event, raw, `hooks.${rawEvent}[${index2}]`))
15548
17938
  );
15549
17939
  }
@@ -15663,12 +18053,12 @@ function parseRule(event, raw, position) {
15663
18053
  );
15664
18054
  }
15665
18055
  const handlersRaw = raw.handlers ?? raw.hooks;
15666
- const list = isObject4(handlersRaw) ? [handlersRaw] : handlersRaw;
15667
- if (!Array.isArray(list) || !list.length)
18056
+ const list2 = isObject4(handlersRaw) ? [handlersRaw] : handlersRaw;
18057
+ if (!Array.isArray(list2) || !list2.length)
15668
18058
  throw new HookConfigError(
15669
18059
  `${position}.handlers: expected a non-empty array of handler tables`
15670
18060
  );
15671
- const handlers = list.map(
18061
+ const handlers = list2.map(
15672
18062
  (h, i) => parseHandler(event, h, `${position}.handlers[${i}]`)
15673
18063
  );
15674
18064
  const rewriters = handlers.filter(isRewriter);
@@ -15879,7 +18269,7 @@ function parseHandler(event, raw, position) {
15879
18269
  }
15880
18270
 
15881
18271
  // src/hooks/handlers.ts
15882
- var import_node_child_process4 = require("child_process");
18272
+ var import_node_child_process5 = require("child_process");
15883
18273
  var fs15 = __toESM(require("fs"));
15884
18274
  var path14 = __toESM(require("path"));
15885
18275
  var import_node_url = require("url");
@@ -15915,11 +18305,11 @@ var CommandHandler = class {
15915
18305
  return new Promise((resolve11, reject) => {
15916
18306
  let child;
15917
18307
  try {
15918
- child = exec ? (0, import_node_child_process4.spawn)(this.command, this.opts.args, {
18308
+ child = exec ? (0, import_node_child_process5.spawn)(this.command, this.opts.args, {
15919
18309
  cwd: this.opts.cwd,
15920
18310
  env: this.opts.env ?? process.env,
15921
18311
  stdio: ["pipe", "pipe", "pipe"]
15922
- }) : (0, import_node_child_process4.spawn)(this.command, {
18312
+ }) : (0, import_node_child_process5.spawn)(this.command, {
15923
18313
  shell: true,
15924
18314
  cwd: this.opts.cwd,
15925
18315
  env: this.opts.env ?? process.env,
@@ -16528,8 +18918,8 @@ var pyQuote2 = (value) => encodeURIComponent(value).replace(
16528
18918
  /[!'()*]/g,
16529
18919
  (c) => "%" + c.charCodeAt(0).toString(16).toUpperCase()
16530
18920
  );
16531
- function jsonPath(node, pathText) {
16532
- const steps = pathText.trim().split(/\.|(?=\[)/).filter((s) => s && s !== "$");
18921
+ function jsonPath(node, pathText2) {
18922
+ const steps = pathText2.trim().split(/\.|(?=\[)/).filter((s) => s && s !== "$");
16533
18923
  let current = node;
16534
18924
  for (const step of steps) {
16535
18925
  const index2 = /^\[(\*|\d+)\]$/.exec(step);
@@ -16635,7 +19025,7 @@ function mapFields(items, fields, stripHtml) {
16635
19025
  );
16636
19026
  });
16637
19027
  }
16638
- function parseJson2(body, options) {
19028
+ function parseJson3(body, options) {
16639
19029
  let data;
16640
19030
  try {
16641
19031
  data = JSON.parse(body);
@@ -16803,7 +19193,7 @@ var HttpTool = class _HttpTool {
16803
19193
  }
16804
19194
  this.checkFailIf(response.status, body, url);
16805
19195
  if (o.parse === "json")
16806
- return applyLimit(parseJson2(body, o), o.limit, values);
19196
+ return applyLimit(parseJson3(body, o), o.limit, values);
16807
19197
  return applyLimit(parseRegex(body, o), o.limit, values);
16808
19198
  }
16809
19199
  /** `fail_if`: a body that matches is a refusal from the provider (a bot challenge,
@@ -16858,8 +19248,8 @@ function readConnection(root) {
16858
19248
  };
16859
19249
  }
16860
19250
  return {
16861
- slug: connector.slug ?? path15.basename(root),
16862
- baseUrl: (connector.base_url ?? "").replace(/\/+$/, ""),
19251
+ slug: typeof connector.slug === "string" ? connector.slug : path15.basename(root),
19252
+ baseUrl: (typeof connector.base_url === "string" ? connector.base_url : "").replace(/\/+$/, ""),
16863
19253
  scheme: carrier.scheme,
16864
19254
  carrier,
16865
19255
  ...typeof auth.secret_env === "string" ? { secretEnv: auth.secret_env } : {},
@@ -16960,7 +19350,7 @@ var ConnectorTool = class {
16960
19350
  throw new TypeError(
16961
19351
  `${this.spec.name}: missing path argument(s) ${missing.join(", ")}`
16962
19352
  );
16963
- const pathText = this.operation.path.replace(
19353
+ const pathText2 = this.operation.path.replace(
16964
19354
  /\{([A-Za-z_][A-Za-z0-9_]*)\}/g,
16965
19355
  (_, name) => pyQuote2(String(values[name]))
16966
19356
  );
@@ -16976,7 +19366,7 @@ var ConnectorTool = class {
16976
19366
  const carried2 = carryCredential(c.carrier, await this.credential() ?? "");
16977
19367
  Object.assign(headers, carried2.headers);
16978
19368
  for (const [key2, value] of carried2.query) query.append(key2, value);
16979
- const url = c.baseUrl + pathText + (query.toString() ? `?${query.toString()}` : "");
19369
+ const url = c.baseUrl + pathText2 + (query.toString() ? `?${query.toString()}` : "");
16980
19370
  const response = await fetch(url, {
16981
19371
  method: this.operation.method,
16982
19372
  headers,
@@ -16991,7 +19381,7 @@ var ConnectorTool = class {
16991
19381
  }
16992
19382
  if (response.status >= 400)
16993
19383
  throw new LiveToolError(
16994
- `${this.spec.name}: ${c.baseUrl}${pathText} answered HTTP ${response.status}: ${text2.slice(0, 200)}`
19384
+ `${this.spec.name}: ${c.baseUrl}${pathText2} answered HTTP ${response.status}: ${text2.slice(0, 200)}`
16995
19385
  );
16996
19386
  if (this.operation.results && isObject5(body)) {
16997
19387
  const selected = jsonPath(body, this.operation.results);
@@ -17107,12 +19497,12 @@ var LiveTools = class _LiveTools {
17107
19497
  raw = {};
17108
19498
  inside;
17109
19499
  static async create(run, live, baseDir) {
17110
- const tools = new _LiveTools(run, live);
19500
+ const tools2 = new _LiveTools(run, live);
17111
19501
  for (const [name, spec] of Object.entries(live.tools)) {
17112
- tools.built[name] = await buildTool(spec, live, baseDir);
17113
- tools.raw[name] = tools.replay ? tools.replay.tool(spec) : tools.built[name];
19502
+ tools2.built[name] = await buildTool(spec, live, baseDir);
19503
+ tools2.raw[name] = tools2.replay ? tools2.replay.tool(spec) : tools2.built[name];
17114
19504
  }
17115
- return tools;
19505
+ return tools2;
17116
19506
  }
17117
19507
  /** The tools of a hooks file for an existing run: the file read, `{run_id}` /
17118
19508
  * `{run_dir}` in its `[live]` paths filled from the run (`runDir` overrides the
@@ -17802,9 +20192,9 @@ var HookRun = class _HookRun {
17802
20192
  * and is re-thrown (same class with the rewritten message). `additional_context`
17803
20193
  * from the handlers is delivered with the result (see `withContext`).
17804
20194
  */
17805
- wrapTools(tools, opts = {}) {
20195
+ wrapTools(tools2, opts = {}) {
17806
20196
  const wrapped = /* @__PURE__ */ Object.create(null);
17807
- for (const [name, fn] of Object.entries(tools)) {
20197
+ for (const [name, fn] of Object.entries(tools2)) {
17808
20198
  wrapped[name] = async (args = {}) => {
17809
20199
  let real;
17810
20200
  let context4;
@@ -18443,8 +20833,20 @@ var tracing = {
18443
20833
  // Annotate the CommonJS export names for ESM import in node:
18444
20834
  0 && (module.exports = {
18445
20835
  ACTION_NAMES,
20836
+ AGENT_EFFORTS,
18446
20837
  AGENT_ID_KEY,
20838
+ AGENT_MODELS,
18447
20839
  ActionTracer,
20840
+ Agent,
20841
+ AgentDefinition,
20842
+ AgentDefinitionError,
20843
+ AgentPatch,
20844
+ AgentRun,
20845
+ AgentThreads,
20846
+ AgentTools,
20847
+ AgentVersionConflictError,
20848
+ AgentVersionNotFoundError,
20849
+ Agents,
18448
20850
  AnthropicComputer,
18449
20851
  AnthropicComputer20251124,
18450
20852
  ApiError,
@@ -18477,9 +20879,11 @@ var tracing = {
18477
20879
  EXPERIMENT_ATTRIBUTES,
18478
20880
  EXPLORATORY_TASK,
18479
20881
  EXPLORATORY_TASK_SOURCE,
20882
+ EventStreamError,
18480
20883
  ExperimentClient,
18481
20884
  ExperimentSpanProcessor,
18482
20885
  ExposureLogger,
20886
+ Gateway,
18483
20887
  GatewayContext,
18484
20888
  GatewayContextConflictError,
18485
20889
  GatewayContextError,
@@ -18503,12 +20907,17 @@ var tracing = {
18503
20907
  OpenAIComputer,
18504
20908
  OpenAIPreviewComputer,
18505
20909
  PLATFORM_SESSION_HEADER,
20910
+ PLATFORM_STREAM_IDLE_MS,
18506
20911
  PLATFORM_TIMEOUT_DEFAULT_MS,
18507
20912
  PLATFORM_TIMEOUT_ENV,
20913
+ PageObserver,
20914
+ PageState,
20915
+ PageStateError,
18508
20916
  PendingSafetyChecks,
18509
20917
  Persona,
18510
20918
  PersonaError,
18511
20919
  PersonasClient,
20920
+ PlatformStream,
18512
20921
  PlatformTransport,
18513
20922
  PushSlugConflict,
18514
20923
  RECOVER_BUDGET_MS,
@@ -18516,6 +20925,7 @@ var tracing = {
18516
20925
  REQUESTS_NOT_RECORDED,
18517
20926
  REQUEST_BODY_CAPTURE_BYTES,
18518
20927
  REQUEST_LOG_PAGE_MAX,
20928
+ ReconnectPolicy,
18519
20929
  ReplayCase,
18520
20930
  ReplayCheck,
18521
20931
  ReplayError,
@@ -18540,6 +20950,7 @@ var tracing = {
18540
20950
  SUCCESS_METRIC_NAME_KEY,
18541
20951
  SUCCESS_SIGNAL_KEY,
18542
20952
  SURFACE_KINDS,
20953
+ SYSTEM_CLOCK,
18543
20954
  Score,
18544
20955
  ScoreError,
18545
20956
  ScoresClient,
@@ -18548,13 +20959,18 @@ var tracing = {
18548
20959
  SessionLoadError,
18549
20960
  SessionRecording,
18550
20961
  SessionTrace,
20962
+ SseLimits,
20963
+ SseParser,
18551
20964
  StubMissError,
18552
20965
  TOOL_CONTRACT_UNREAD,
20966
+ TOOL_SERVERS,
18553
20967
  TRANSFORMS,
18554
20968
  TaskEditClient,
18555
20969
  TaskGrades,
18556
20970
  TaskRun,
18557
20971
  TaskSessions,
20972
+ Thread,
20973
+ Threads,
18558
20974
  ToolStubRegistry,
18559
20975
  TraceDiff,
18560
20976
  TransportCause,
@@ -18564,6 +20980,7 @@ var tracing = {
18564
20980
  VERIFIER_REWARD_PREFIX,
18565
20981
  WHITESPACE,
18566
20982
  WORLD_REQUEST_VIAS,
20983
+ WORLD_WEBHOOK_PAGE_MAX,
18567
20984
  WorldBrowser,
18568
20985
  WorldCallTooLarge,
18569
20986
  WorldEditClient,
@@ -18579,9 +20996,11 @@ var tracing = {
18579
20996
  WorldSessionOpenFailed,
18580
20997
  WorldSessionTimeout,
18581
20998
  WorldSet,
20999
+ WorldStateClient,
18582
21000
  WorldSurfaceUnavailable,
18583
21001
  WorldTask,
18584
21002
  WorldToolsUnread,
21003
+ WorldWebhookForwarder,
18585
21004
  WriteTreeFilter,
18586
21005
  addExperimentAttributes,
18587
21006
  aggregateTaskGrade,
@@ -18615,6 +21034,7 @@ var tracing = {
18615
21034
  createRef,
18616
21035
  createTask,
18617
21036
  currentTraceId,
21037
+ defineAgent,
18618
21038
  defineTool,
18619
21039
  deleteEnvSecret,
18620
21040
  deleteTask,
@@ -18651,6 +21071,7 @@ var tracing = {
18651
21071
  listSessions,
18652
21072
  listTaskSessions,
18653
21073
  listTasks,
21074
+ listWebhooks,
18654
21075
  loadSession,
18655
21076
  localTreeState,
18656
21077
  memory,
@@ -18669,6 +21090,7 @@ var tracing = {
18669
21090
  parseTransform,
18670
21091
  parseWorldTaskRefs,
18671
21092
  personas,
21093
+ platformAuthorization,
18672
21094
  platformTimeoutMs,
18673
21095
  playwrightKey,
18674
21096
  preserveForm,
@@ -18705,6 +21127,7 @@ var tracing = {
18705
21127
  runWithExperimentContext,
18706
21128
  schemaFromSignature,
18707
21129
  scores,
21130
+ scrubError,
18708
21131
  serializeCallBody,
18709
21132
  sessionObservationFromApi,
18710
21133
  sessionToolObservations,
@@ -18725,6 +21148,7 @@ var tracing = {
18725
21148
  taskRunFailure,
18726
21149
  toolCallRecordsIn,
18727
21150
  toolCallsFromObservations,
21151
+ tools,
18728
21152
  traces,
18729
21153
  tracing,
18730
21154
  uiEntryUrl,