@withgateway/sdk 0.6.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 (119) 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 +5019 -1599
  10. package/dist/cli.js.map +1 -1
  11. package/dist/cli.mjs +5003 -1584
  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 +371 -102
  16. package/dist/files/index.js.map +1 -1
  17. package/dist/files/index.mjs +371 -102
  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-LA-PMRJT.d.ts → index-DIN14Lhg.d.ts} +1 -1
  24. package/dist/{index-Di9nNqOY.d.mts → index-DuB-eQ0Z.d.mts} +1 -1
  25. package/dist/index.d.mts +7 -4
  26. package/dist/index.d.ts +7 -4
  27. package/dist/index.js +2689 -401
  28. package/dist/index.js.map +1 -1
  29. package/dist/index.mjs +2650 -394
  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/traces/index.d.mts +3 -1
  34. package/dist/traces/index.d.ts +3 -1
  35. package/dist/traces/index.js +371 -102
  36. package/dist/traces/index.js.map +1 -1
  37. package/dist/traces/index.mjs +371 -102
  38. package/dist/traces/index.mjs.map +1 -1
  39. package/dist/tracing/index.d.mts +3 -2
  40. package/dist/tracing/index.d.ts +3 -2
  41. package/dist/tracing/index.js +257 -16
  42. package/dist/tracing/index.js.map +1 -1
  43. package/dist/tracing/index.mjs +257 -16
  44. package/dist/tracing/index.mjs.map +1 -1
  45. package/dist/transport-CpRe7zgd.d.mts +123 -0
  46. package/dist/transport-CpRe7zgd.d.ts +123 -0
  47. package/dist/worlds/index.d.mts +1983 -1745
  48. package/dist/worlds/index.d.ts +1983 -1745
  49. package/dist/worlds/index.js +1295 -226
  50. package/dist/worlds/index.js.map +1 -1
  51. package/dist/worlds/index.mjs +1290 -222
  52. package/dist/worlds/index.mjs.map +1 -1
  53. package/package.json +6 -1
  54. package/runtime/gatewaysdk/environment/bundle_manifest.py +243 -0
  55. package/runtime/gatewaysdk/environment/schema/__main__.py +2 -2
  56. package/runtime/gatewaysdk/environment/schema/_slack_fidelity.py +8 -23
  57. package/runtime/gatewaysdk/environment/schema/api.py +3 -4
  58. package/runtime/gatewaysdk/environment/schema/assertions.py +7 -1
  59. package/runtime/gatewaysdk/environment/schema/bundle_runtime.py +1 -0
  60. package/runtime/gatewaysdk/environment/schema/call_log.py +20 -0
  61. package/runtime/gatewaysdk/environment/schema/database/base.py +2 -2
  62. package/runtime/gatewaysdk/environment/schema/host.py +74 -11
  63. package/runtime/gatewaysdk/environment/schema/host_browser.py +48 -0
  64. package/runtime/gatewaysdk/environment/schema/host_control.py +33 -2
  65. package/runtime/gatewaysdk/environment/schema/host_handoff.py +4 -1
  66. package/runtime/gatewaysdk/environment/schema/host_requests.py +14 -0
  67. package/runtime/gatewaysdk/environment/schema/host_session.py +13 -2
  68. package/runtime/gatewaysdk/environment/schema/host_surfaces.py +6 -0
  69. package/runtime/gatewaysdk/environment/schema/host_versions.py +96 -19
  70. package/runtime/gatewaysdk/environment/schema/journal.py +7 -2
  71. package/runtime/gatewaysdk/environment/schema/local.py +32 -7
  72. package/runtime/gatewaysdk/environment/schema/page_checks.py +123 -0
  73. package/runtime/gatewaysdk/environment/schema/platform.py +23 -267
  74. package/runtime/gatewaysdk/environment/schema/platform_templates.py +332 -0
  75. package/runtime/gatewaysdk/environment/schema/request_ledger.py +4 -1
  76. package/runtime/gatewaysdk/environment/schema/run_parameters.py +25 -0
  77. package/runtime/gatewaysdk/environment/schema/runtime.py +43 -5
  78. package/runtime/gatewaysdk/environment/schema/scaffold.py +367 -217
  79. package/runtime/gatewaysdk/environment/schema/session_files.py +13 -2
  80. package/runtime/gatewaysdk/environment/schema/skills/benchmarks-getting-started/SKILL.md +1 -1
  81. package/runtime/gatewaysdk/environment/schema/skills/connector-schema-authoring/SKILL.md +1 -2
  82. package/runtime/gatewaysdk/environment/schema/skills/world-data-ingestion/SKILL.md +4 -2
  83. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/SKILL.md +7 -7
  84. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/cli-mcp-map.md +32 -2
  85. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/gotchas.md +6 -6
  86. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/journal-checks.md +17 -2
  87. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/new-world-sandbox.md +1 -1
  88. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/ui-map.md +3 -2
  89. package/runtime/gatewaysdk/environment/schema/slack.py +55 -10
  90. package/runtime/gatewaysdk/environment/schema/snapshot.py +28 -2
  91. package/runtime/gatewaysdk/environment/schema/tasks.py +25 -2
  92. package/runtime/gatewaysdk/environment/schema/template_record.py +131 -0
  93. package/runtime/gatewaysdk/environment/schema/tools_world.py +7 -5
  94. package/runtime/gatewaysdk/environment/schema/ui.py +54 -33
  95. package/runtime/gatewaysdk/environment/schema/ui_interactions.py +419 -0
  96. package/runtime/gatewaysdk/environment/schema/ui_recorder.js +895 -0
  97. package/runtime/gatewaysdk/environment/schema/ui_replay.py +366 -0
  98. package/runtime/gatewaysdk/environment/schema/ui_replay_record.LICENSE +25 -0
  99. package/runtime/gatewaysdk/environment/schema/ui_replay_record.js +109 -0
  100. package/runtime/gatewaysdk/environment/schema/validation.py +10 -1
  101. package/runtime/gatewaysdk/environment/schema/worker.py +5 -1
  102. package/runtime/gatewaysdk/environment/schema/workers.py +8 -1
  103. package/runtime/gatewaysdk/environment/schema/world_host.py +44 -15
  104. package/runtime/gatewaysdk/environment/secret_values.py +1 -1
  105. package/runtime/gatewaysdk/environment/world.py +34 -43
  106. package/runtime/gatewaysdk/environment/world_session_contract.py +7 -34
  107. package/skills/benchmarks-getting-started/SKILL.md +1 -1
  108. package/skills/connector-schema-authoring/SKILL.md +1 -2
  109. package/skills/connector-schema-authoring/connector-worlds.md +2 -2
  110. package/skills/connector-schema-authoring/world-schema.md +29 -23
  111. package/skills/world-data-ingestion/SKILL.md +4 -2
  112. package/skills/worlds-getting-started/SKILL.md +7 -7
  113. package/skills/worlds-getting-started/references/cli-mcp-map.md +32 -2
  114. package/skills/worlds-getting-started/references/gotchas.md +6 -6
  115. package/skills/worlds-getting-started/references/journal-checks.md +17 -2
  116. package/skills/worlds-getting-started/references/new-world-sandbox.md +1 -1
  117. package/skills/worlds-getting-started/references/ui-map.md +3 -2
  118. package/dist/media-BIApiPzS.d.mts +0 -102
  119. package/dist/media-BIApiPzS.d.ts +0 -102
package/dist/index.mjs CHANGED
@@ -450,13 +450,77 @@ var init_scores = __esm({
450
450
  }
451
451
  });
452
452
 
453
+ // src/worlds/personalToken.ts
454
+ var TOKEN_NOT_PERSONAL, TOKEN_NEEDS_PROJECT, TOKEN_NEEDS_HOST, TOKEN_OTHER_HOST, TOKEN_BESIDE_KEYS, TOKEN_FILING, TOKEN_KEYS_ONLY, PERSONAL, PROJECT, ENV_KEYS, PersonalTokenRefused, bare, PersonalToken;
455
+ var init_personalToken = __esm({
456
+ "src/worlds/personalToken.ts"() {
457
+ "use strict";
458
+ TOKEN_NOT_PERSONAL = "GATEWAY_TOKEN takes a personal access token: pat_ followed by letters and digits only.";
459
+ TOKEN_NEEDS_PROJECT = "GATEWAY_TOKEN acts in the project GATEWAY_PROJECT_ID names: set it to the official project's id (letters, digits, - and _).";
460
+ TOKEN_NEEDS_HOST = "GATEWAY_TOKEN goes only to the host GATEWAY_HOST names: set GATEWAY_HOST.";
461
+ TOKEN_OTHER_HOST = "GATEWAY_TOKEN goes only to the host GATEWAY_HOST names, and this call names another host: point the call at GATEWAY_HOST or unset GATEWAY_TOKEN.";
462
+ TOKEN_BESIDE_KEYS = "GATEWAY_TOKEN is set beside a project key (GATEWAY_PUBLIC_KEY, GATEWAY_SECRET_KEY, GATEWAY_API_KEY or a key passed in): unset one of them. Neither replaces the other.";
463
+ TOKEN_FILING = "Filing an evaluation takes your project's key pair, not GATEWAY_TOKEN: unset it (an official world runs once copied into your own project).";
464
+ TOKEN_KEYS_ONLY = "Task-run tracing exports with a project key pair (GATEWAY_PUBLIC_KEY / GATEWAY_SECRET_KEY), not GATEWAY_TOKEN.";
465
+ PERSONAL = /^pat_[A-Za-z0-9]+$/;
466
+ PROJECT = /^[A-Za-z0-9_-]+$/;
467
+ ENV_KEYS = ["GATEWAY_PUBLIC_KEY", "GATEWAY_SECRET_KEY", "GATEWAY_API_KEY"];
468
+ PersonalTokenRefused = class extends Error {
469
+ };
470
+ bare = (host) => host.replace(/\/+$/, "");
471
+ PersonalToken = class _PersonalToken {
472
+ constructor(value, project, host) {
473
+ this.value = value;
474
+ this.project = project;
475
+ this.host = host;
476
+ }
477
+ value;
478
+ project;
479
+ host;
480
+ static fromEnv(env, request = {}) {
481
+ const value = env.GATEWAY_TOKEN;
482
+ if (!value) return null;
483
+ if (request.keys || ENV_KEYS.some((name) => env[name])) throw new PersonalTokenRefused(TOKEN_BESIDE_KEYS);
484
+ const host = bare(env.GATEWAY_HOST ?? "");
485
+ if (!host) throw new PersonalTokenRefused(TOKEN_NEEDS_HOST);
486
+ if (request.host && bare(request.host) !== host) throw new PersonalTokenRefused(TOKEN_OTHER_HOST);
487
+ if (!PERSONAL.test(value)) throw new PersonalTokenRefused(TOKEN_NOT_PERSONAL);
488
+ const project = env.GATEWAY_PROJECT_ID ?? "";
489
+ if (!PROJECT.test(project)) throw new PersonalTokenRefused(TOKEN_NEEDS_PROJECT);
490
+ return new _PersonalToken(value, project, host);
491
+ }
492
+ toJSON() {
493
+ return { project: this.project, host: this.host };
494
+ }
495
+ [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
496
+ return `PersonalToken { project: ${this.project}, host: ${this.host} }`;
497
+ }
498
+ static scrubbed(env) {
499
+ return Object.fromEntries(Object.entries(env).filter(([key2]) => key2 !== "GATEWAY_TOKEN"));
500
+ }
501
+ };
502
+ }
503
+ });
504
+
453
505
  // src/worlds/platformEndpoint.ts
454
506
  function platformEndpoint(options) {
507
+ if (options.token)
508
+ return {
509
+ host: (options.host ?? options.token.host).replace(/\/+$/, ""),
510
+ publicKey: options.publicKey ?? "",
511
+ secretKey: options.secretKey ?? "",
512
+ token: options.token
513
+ };
514
+ const token = PersonalToken.fromEnv(process.env, {
515
+ host: options.host,
516
+ keys: Boolean(options.publicKey || options.secretKey)
517
+ });
518
+ if (token) return { host: token.host, publicKey: "", secretKey: "", token };
519
+ const host = (options.host ?? process.env.GATEWAY_HOST ?? DEFAULT_HOST).replace(/\/+$/, "");
455
520
  const publicKey = options.publicKey ?? process.env.GATEWAY_PUBLIC_KEY;
456
521
  const secretKey = options.secretKey ?? process.env.GATEWAY_SECRET_KEY;
457
522
  if (!publicKey || !secretKey) return null;
458
- const host = options.host ?? process.env.GATEWAY_HOST ?? DEFAULT_HOST;
459
- return { host: host.replace(/\/+$/, ""), publicKey, secretKey };
523
+ return { host, publicKey, secretKey };
460
524
  }
461
525
  function requirePlatformEndpoint(options) {
462
526
  const endpoint = platformEndpoint(options);
@@ -467,11 +531,74 @@ var DEFAULT_HOST, GATEWAY_KEYS_MISSING;
467
531
  var init_platformEndpoint = __esm({
468
532
  "src/worlds/platformEndpoint.ts"() {
469
533
  "use strict";
534
+ init_personalToken();
470
535
  DEFAULT_HOST = "https://withgateway.ai";
471
536
  GATEWAY_KEYS_MISSING = "Gateway keys missing: set GATEWAY_PUBLIC_KEY / GATEWAY_SECRET_KEY (or pass publicKey/secretKey).";
472
537
  }
473
538
  });
474
539
 
540
+ // src/worlds/apiError.ts
541
+ function edgeAnswer(text2, status) {
542
+ if (status !== void 0 && status >= 500) return EDGE_ANSWERS[status] ?? EDGE_FAILURE;
543
+ return /^\s*</.test(text2) ? EDGE_PAGE : null;
544
+ }
545
+ function parseErrorBody(text2, status) {
546
+ const raw = { detail: text2.slice(0, DETAIL_LIMIT), code: null };
547
+ let parsed;
548
+ try {
549
+ parsed = JSON.parse(text2);
550
+ } catch {
551
+ return { detail: (edgeAnswer(text2, status) ?? text2).slice(0, DETAIL_LIMIT), code: null };
552
+ }
553
+ if (parsed === null || typeof parsed !== "object") return raw;
554
+ const { message, code, error } = parsed;
555
+ const stableCode = typeof code === "string" ? code : null;
556
+ if (typeof message !== "string") return { ...raw, code: stableCode };
557
+ const fields = invalidFields(error);
558
+ const said = fields ? `${message}: ${fields}` : message;
559
+ if (stableCode === null) return { detail: said.slice(0, DETAIL_LIMIT), code: null };
560
+ return {
561
+ detail: `${said} (${stableCode})`.slice(0, DETAIL_LIMIT),
562
+ code: stableCode
563
+ };
564
+ }
565
+ function invalidFields(error) {
566
+ const issues = Array.isArray(error) ? error : [];
567
+ return issues.filter(
568
+ (issue) => issue !== null && typeof issue === "object" && typeof issue.message === "string"
569
+ ).map((issue) => {
570
+ const path17 = Array.isArray(issue.path) ? issue.path.map(String).join(".") : "";
571
+ return path17 ? `${path17}: ${issue.message}` : issue.message;
572
+ }).join("; ");
573
+ }
574
+ var ApiError, DETAIL_LIMIT, EDGE_ANSWERS, EDGE_FAILURE, EDGE_PAGE;
575
+ var init_apiError = __esm({
576
+ "src/worlds/apiError.ts"() {
577
+ "use strict";
578
+ ApiError = class extends Error {
579
+ constructor(status, method, path17, text2) {
580
+ const parsed = parseErrorBody(text2, status);
581
+ super(`${method} ${path17} -> ${status}: ${parsed.detail}`);
582
+ this.status = status;
583
+ this.text = text2;
584
+ this.name = "ApiError";
585
+ this.code = parsed.code;
586
+ }
587
+ status;
588
+ text;
589
+ code;
590
+ };
591
+ DETAIL_LIMIT = 600;
592
+ EDGE_ANSWERS = {
593
+ 502: "Bad Gateway from the load balancer in front of the platform, not the platform's answer: the web server dropped the connection or restarted mid-request. Retry; if it repeats, the platform is restarting or overloaded.",
594
+ 503: "Service Unavailable from the load balancer in front of the platform, not the platform's answer: no web server was ready to take the request (a deploy or a restart). Retry in a minute.",
595
+ 504: "Gateway Time-out from the load balancer in front of the platform, not the platform's answer: the request sent nothing back within the load balancer's idle timeout (60 s unless the deployment raises it: Helm ingress.idleTimeoutSeconds) and was cut there, though the platform may still be running it. Check what it changed before you retry."
596
+ };
597
+ EDGE_FAILURE = "The platform failed without its JSON error body: a proxy in front of it answered, or the server stopped before its error handler ran. Retry; if it repeats, report the request and the time.";
598
+ EDGE_PAGE = "An HTML page answered instead of the platform's JSON: a proxy in front of the platform, or the configured host is not the platform.";
599
+ }
600
+ });
601
+
475
602
  // src/worlds/transport.ts
476
603
  function platformTimeoutMs(env = process.env) {
477
604
  const raw = env[PLATFORM_TIMEOUT_ENV];
@@ -480,10 +607,20 @@ function platformTimeoutMs(env = process.env) {
480
607
  if (Number.isInteger(value) && value > 0) return value;
481
608
  throw new Error(`${PLATFORM_TIMEOUT_ENV} must be a positive whole number of milliseconds, not \`${raw}\`.`);
482
609
  }
483
- var PLATFORM_TIMEOUT_ENV, PLATFORM_TIMEOUT_DEFAULT_MS, CHECK_HOST, RETRY, FETCH_LIMIT, CAUSES, UNKNOWN_CAUSE, TransportCause, UnreachableError, sleep2, RetryPolicy, Attempt, PlatformTransport;
610
+ function platformAuthorization(endpoint, url) {
611
+ const { token } = endpoint;
612
+ if (!token)
613
+ return { authorization: "Basic " + Buffer.from(`${endpoint.publicKey}:${endpoint.secretKey}`).toString("base64") };
614
+ if (endpoint.publicKey || endpoint.secretKey) throw new PersonalTokenRefused(TOKEN_BESIDE_KEYS);
615
+ if (!url.startsWith(`${token.host}/`)) throw new PersonalTokenRefused(TOKEN_OTHER_HOST);
616
+ return { authorization: `Bearer ${token.value}`, "x-gateway-project": token.project };
617
+ }
618
+ var PLATFORM_TIMEOUT_ENV, PLATFORM_TIMEOUT_DEFAULT_MS, CHECK_HOST, RETRY, FETCH_LIMIT, CAUSES, UNKNOWN_CAUSE, TransportCause, UnreachableError, sleep2, RetryPolicy, Attempt, PLATFORM_STREAM_IDLE_MS, REFUSAL_TEXT_LIMIT, KEYED_REDIRECTS, PlatformTransport, StreamWatch, PlatformStream;
484
619
  var init_transport = __esm({
485
620
  "src/worlds/transport.ts"() {
486
621
  "use strict";
622
+ init_apiError();
623
+ init_personalToken();
487
624
  PLATFORM_TIMEOUT_ENV = "GATEWAY_TIMEOUT_MS";
488
625
  PLATFORM_TIMEOUT_DEFAULT_MS = 12e4;
489
626
  CHECK_HOST = "Check GATEWAY_HOST (or --host) points at a running platform, then retry.";
@@ -523,6 +660,13 @@ var init_transport = __esm({
523
660
  `Retry; if the platform is slow, raise ${PLATFORM_TIMEOUT_ENV} (milliseconds per request).`
524
661
  );
525
662
  }
663
+ static idle(idleMs) {
664
+ return new _TransportCause(
665
+ `no data for ${idleMs / 1e3}s`,
666
+ null,
667
+ "The stream resumes from its last event; if it repeats, check the network between here and the platform."
668
+ );
669
+ }
526
670
  static of(error) {
527
671
  const cause = error instanceof Error && error.cause instanceof Error ? error.cause : void 0;
528
672
  const code = cause && "code" in cause && typeof cause.code === "string" ? cause.code : null;
@@ -598,45 +742,277 @@ var init_transport = __esm({
598
742
  throw this.error;
599
743
  }
600
744
  };
745
+ PLATFORM_STREAM_IDLE_MS = 6e4;
746
+ REFUSAL_TEXT_LIMIT = 64 * 1024;
747
+ KEYED_REDIRECTS = "manual";
601
748
  PlatformTransport = class {
749
+ #endpoint;
750
+ #timeoutMs;
602
751
  constructor(endpoint, timeoutMs = platformTimeoutMs()) {
603
- this.endpoint = endpoint;
604
- this.timeoutMs = timeoutMs;
752
+ this.#endpoint = endpoint;
753
+ this.#timeoutMs = timeoutMs;
605
754
  }
606
- endpoint;
607
- timeoutMs;
608
755
  /** A request that legitimately takes longer (a sandbox exec, a world create) waits its own budget; every other one waits the default. */
609
756
  budget(ownMs) {
610
- return Math.max(ownMs ?? 0, this.timeoutMs);
757
+ return Math.max(ownMs ?? 0, this.#timeoutMs);
611
758
  }
759
+ /** One request; the caller's `signal` aborts it in flight and throws the signal's reason, never an `UnreachableError`. */
612
760
  async send(method, route2, body, opts = {}) {
613
761
  const timeoutMs = this.budget(opts.timeoutMs);
614
- return (opts.retry ?? RetryPolicy.NONE).run(() => this.once(method, route2, body, timeoutMs));
762
+ return (opts.retry ?? RetryPolicy.NONE).run(() => this.once(method, route2, body, timeoutMs, opts.signal));
763
+ }
764
+ /** `send`, then the 2xx body as JSON; any other answer throws `ApiError` with its status and stable `code`. */
765
+ async json(method, route2, body, opts = {}) {
766
+ const reply = await this.send(method, route2, body, opts);
767
+ if (!reply.ok) throw new ApiError(reply.status, method, route2, reply.text);
768
+ return JSON.parse(reply.text);
769
+ }
770
+ /** The streaming twin of `send` for a `GET` event stream: nothing is buffered, `after` travels as `Last-Event-ID`, and each wait for the platform (the headers, every chunk) may last `idleMs` (default 60 s) instead of the request budget. */
771
+ async stream(route2, opts = {}) {
772
+ const watch = new StreamWatch(opts.signal, opts.idleMs ?? PLATFORM_STREAM_IDLE_MS, this.#endpoint.host, route2);
773
+ const headers = this.headers(route2, "text/event-stream", opts.after ? { "last-event-id": opts.after } : {});
774
+ try {
775
+ const response = await watch.within(
776
+ () => fetch(this.url(route2), { method: "GET", headers, signal: watch.signal, redirect: KEYED_REDIRECTS })
777
+ );
778
+ return new PlatformStream(response, watch);
779
+ } catch (error) {
780
+ watch.close();
781
+ throw error;
782
+ }
783
+ }
784
+ url(route2) {
785
+ return `${this.#endpoint.host}${route2}`;
786
+ }
787
+ headers(route2, accept, extra = {}) {
788
+ return {
789
+ "content-type": "application/json",
790
+ accept,
791
+ ...platformAuthorization(this.#endpoint, this.url(route2)),
792
+ ...extra
793
+ };
615
794
  }
616
- async once(method, route2, body, timeoutMs) {
795
+ async once(method, route2, body, timeoutMs, caller) {
796
+ if (caller?.aborted) throw caller.reason;
617
797
  const payload = body === void 0 ? {} : { body: JSON.stringify(body) };
798
+ const headers = this.headers(route2, "application/json");
618
799
  const controller = new AbortController();
619
800
  const timer = setTimeout(() => controller.abort(), timeoutMs);
801
+ const relay = () => controller.abort(caller?.reason);
802
+ caller?.addEventListener("abort", relay, { once: true });
620
803
  try {
621
- const res = await fetch(`${this.endpoint.host}${route2}`, {
804
+ const res = await fetch(this.url(route2), {
622
805
  method,
623
- headers: {
624
- "content-type": "application/json",
625
- accept: "application/json",
626
- authorization: "Basic " + Buffer.from(`${this.endpoint.publicKey}:${this.endpoint.secretKey}`).toString("base64")
627
- },
806
+ headers,
628
807
  ...payload,
629
- signal: controller.signal
808
+ signal: controller.signal,
809
+ redirect: KEYED_REDIRECTS
630
810
  });
631
811
  return { status: res.status, ok: res.ok, text: await res.text() };
632
812
  } catch (error) {
813
+ if (caller?.aborted) throw caller.reason;
633
814
  const cause = controller.signal.aborted ? TransportCause.timeout(timeoutMs) : TransportCause.of(error);
634
- throw new UnreachableError(this.endpoint.host, method, route2, cause);
815
+ throw new UnreachableError(this.#endpoint.host, method, route2, cause);
635
816
  } finally {
636
817
  clearTimeout(timer);
818
+ caller?.removeEventListener("abort", relay);
637
819
  }
638
820
  }
639
821
  };
822
+ StreamWatch = class {
823
+ constructor(caller, idleMs, host, route2) {
824
+ this.idleMs = idleMs;
825
+ this.host = host;
826
+ this.route = route2;
827
+ this.#caller = caller;
828
+ caller?.addEventListener("abort", this.#relay, { once: true });
829
+ if (caller?.aborted) this.#relay();
830
+ }
831
+ idleMs;
832
+ host;
833
+ route;
834
+ #controller = new AbortController();
835
+ #caller;
836
+ #relay = () => this.#controller.abort(this.#caller?.reason);
837
+ #idled = false;
838
+ get signal() {
839
+ return this.#controller.signal;
840
+ }
841
+ async within(wait) {
842
+ const timer = setTimeout(() => this.idle(), this.idleMs);
843
+ try {
844
+ return await wait();
845
+ } catch (error) {
846
+ throw this.failure(error);
847
+ } finally {
848
+ clearTimeout(timer);
849
+ }
850
+ }
851
+ close() {
852
+ this.#caller?.removeEventListener("abort", this.#relay);
853
+ this.#controller.abort();
854
+ }
855
+ idle() {
856
+ this.#idled = true;
857
+ this.#controller.abort();
858
+ }
859
+ failure(error) {
860
+ if (this.#caller?.aborted) return this.#caller.reason;
861
+ const cause = this.#idled ? TransportCause.idle(this.idleMs) : TransportCause.of(error);
862
+ return new UnreachableError(this.host, "GET", this.route, cause);
863
+ }
864
+ };
865
+ PlatformStream = class {
866
+ #response;
867
+ #watch;
868
+ constructor(response, watch) {
869
+ this.#response = response;
870
+ this.#watch = watch;
871
+ }
872
+ get status() {
873
+ return this.#response.status;
874
+ }
875
+ get ok() {
876
+ return this.#response.ok;
877
+ }
878
+ /** The body as text, for a refusal: at most the first 64 KiB of characters; closes the stream. */
879
+ async text() {
880
+ const decoder = new TextDecoder();
881
+ let text2 = "";
882
+ for await (const chunk of this.chunks()) {
883
+ text2 += decoder.decode(chunk, { stream: true });
884
+ if (text2.length >= REFUSAL_TEXT_LIMIT) return text2.slice(0, REFUSAL_TEXT_LIMIT);
885
+ }
886
+ return text2 + decoder.decode();
887
+ }
888
+ /** The body's bytes as they arrive; the idle budget runs only while waiting for the platform, never while the caller holds a chunk. */
889
+ async *chunks() {
890
+ const reader = this.#response.body?.getReader();
891
+ try {
892
+ for (; ; ) {
893
+ const next = reader ? await this.#watch.within(() => reader.read()) : { done: true };
894
+ if (next.done) return;
895
+ yield next.value;
896
+ }
897
+ } finally {
898
+ this.close();
899
+ }
900
+ }
901
+ close() {
902
+ this.#watch.close();
903
+ }
904
+ };
905
+ }
906
+ });
907
+
908
+ // src/worlds/credentialField.ts
909
+ function isCredentialField(described) {
910
+ const words2 = described.replace(SPACES, " ").replace(/^ | $/g, "");
911
+ return SECRET_FIELD.some((prefix) => words2.startsWith(prefix)) || SECRET_KEY.test(words2);
912
+ }
913
+ function credentialTexts(pairs) {
914
+ return pairs.filter(([, text2]) => text2 !== null && text2 !== void 0).filter(([described]) => isCredentialField(String(described))).map(([, text2]) => String(text2));
915
+ }
916
+ function isTextField(described) {
917
+ return described !== "" && !NOT_TEXT.some((prefix) => described.startsWith(prefix));
918
+ }
919
+ function redactActionArgs(action, args) {
920
+ const secretField = action === "browser_type" && SECRET_KEY.test(String(args.selector ?? ""));
921
+ return Object.fromEntries(
922
+ Object.entries(args).map(([key2, value]) => [
923
+ key2,
924
+ redactedArg(key2, value, secretField)
925
+ ])
926
+ );
927
+ }
928
+ function redactedArg(key2, value, secretField) {
929
+ if (value === null || value === void 0) return null;
930
+ if (typeof value === "boolean" || typeof value === "number") return value;
931
+ if (typeof value !== "string") return "[omitted]";
932
+ if (SECRET_KEY.test(key2) || SECRET_VALUE.test(value) || secretField && key2 === "text")
933
+ return "[redacted]";
934
+ return value.length <= EVENT_MAX_STRING ? value : value.slice(0, EVENT_MAX_STRING) + "\u2026";
935
+ }
936
+ var SECRET_KEY, DESCRIBE_FIELD_JS, FIELD_VALUE_JS, FIELDS, SHORTEST_WITHHELD, WITHHELD_TEXT, SPACES, LINE_BREAK, TRIM, describeField, readFieldValue, readEditables, UNREADABLE, SECRET_FIELD, NOT_TEXT, escapeRegExp, urlForms, forms, CredentialText, EVENT_MAX_STRING, SECRET_VALUE;
937
+ var init_credentialField = __esm({
938
+ "src/worlds/credentialField.ts"() {
939
+ "use strict";
940
+ SECRET_KEY = /pass(word|wd|code|phrase)|pass(?![a-z])|secret|token(?!s)|(api|private)[-_ ]?key|authorization|cookie|one[-_ ]?time[-_ ]?(code|password)|(verification|security|recovery|backup)[-_ ]?codes?|security[-_ ]?answers?|social[-_ ]?security|(card|account|routing)[-_ ]?(number|no\b)|cc-(number|csc|exp)|(^|[-_ #.\["'=(])(otp|totp|mfa|2fa|pin|cvv|cvc|ssn|iban)([-_ \]"'):.,*]|$)/i;
941
+ DESCRIBE_FIELD_JS = "(e) => { if (!e) return ''; if (e.tagName === 'IFRAME' || e.tagName === 'FRAME') return 'frame'; const root = e.getRootNode(); const byIds = (at) => (at.getAttribute('aria-labelledby') || '').split(/\\s+/).map((id) => (id && root.getElementById ? root.getElementById(id) : null)).map((label) => (label ? label.textContent : '')).join(' '); const labels = e.labels ? [...e.labels].map((label) => label.textContent) : []; const context = []; for (let at = e.parentElement; at; at = at.parentElement) { const legend = at.tagName === 'FIELDSET' ? at.querySelector('legend') : null; context.push(at.getAttribute('aria-label'), byIds(at), legend ? legend.textContent : ''); } const names = [e.getAttribute('aria-label'), byIds(e), ...labels, e.getAttribute('placeholder'), e.getAttribute('title'), ...context]; if (e.tagName === 'SELECT') return ['select', e.name, e.id, ...names].filter(Boolean).join(' '); if (!(e.tagName === 'INPUT' || e.tagName === 'TEXTAREA' || e.isContentEditable)) return 'opaque'; return [e.type, e.name, e.id, e.getAttribute('autocomplete'), ...names].filter(Boolean).join(' '); }";
942
+ FIELD_VALUE_JS = "(e) => { if (e.tagName === 'SELECT') return [...e.selectedOptions].map((o) => o.text).join('\\n'); if (e.tagName === 'INPUT' || e.tagName === 'TEXTAREA') return e.value; return e.isContentEditable ? e.innerText : null; }";
943
+ FIELDS = "input:not([type=button]):not([type=submit]):not([type=reset]):not([type=image]):not([type=checkbox]):not([type=radio]):not([type=file]), textarea, select, [contenteditable]:not([contenteditable=false])";
944
+ SHORTEST_WITHHELD = 4;
945
+ WITHHELD_TEXT = "[redacted]";
946
+ SPACES = /[ \t\n\r\f\v]+/g;
947
+ LINE_BREAK = /\r\n|\r|\n/;
948
+ TRIM = /^[ \t\n\r\f\v]+|[ \t\n\r\f\v]+$/g;
949
+ describeField = new Function(
950
+ "e",
951
+ `return (${DESCRIBE_FIELD_JS})(e);`
952
+ );
953
+ readFieldValue = new Function(
954
+ "e",
955
+ `return (${FIELD_VALUE_JS})(e);`
956
+ );
957
+ readEditables = new Function(
958
+ "elements",
959
+ `return elements.map((e) => [(${DESCRIBE_FIELD_JS})(e), (${FIELD_VALUE_JS})(e)]);`
960
+ );
961
+ UNREADABLE = "unreadable";
962
+ SECRET_FIELD = ["password", "frame", "opaque", UNREADABLE];
963
+ NOT_TEXT = ["opaque", "frame", "select"];
964
+ escapeRegExp = (text2) => text2.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
965
+ urlForms = (text2) => {
966
+ let component;
967
+ try {
968
+ component = encodeURIComponent(text2);
969
+ } catch {
970
+ return [];
971
+ }
972
+ const form = component.replace(
973
+ /[!'()~]/g,
974
+ (c) => "%" + c.charCodeAt(0).toString(16).toUpperCase()
975
+ ).replace(/%20/g, "+");
976
+ return [component, component.replace(/%20/g, "+"), form];
977
+ };
978
+ forms = (text2) => {
979
+ const written = [
980
+ text2,
981
+ text2.replace(SPACES, " "),
982
+ JSON.stringify(text2).slice(1, -1)
983
+ ];
984
+ return [
985
+ ...written,
986
+ ...written.map((form) => form.replaceAll("'", "''")),
987
+ ...urlForms(text2)
988
+ ];
989
+ };
990
+ CredentialText = class {
991
+ pattern;
992
+ constructor(secrets) {
993
+ const texts = secrets.map((secret) => String(secret).replace(TRIM, ""));
994
+ const lines = texts.flatMap(
995
+ (text2) => text2.split(LINE_BREAK).map((line) => line.replace(TRIM, ""))
996
+ );
997
+ const whole = new Set(
998
+ [...texts, ...lines].filter(
999
+ (text2) => [...text2].length >= SHORTEST_WITHHELD
1000
+ )
1001
+ );
1002
+ const withheld = [
1003
+ ...new Set([...whole].flatMap((text2) => forms(text2)))
1004
+ ].sort((a, b) => b.length - a.length);
1005
+ this.pattern = withheld.length === 0 ? null : new RegExp(
1006
+ `(?<![A-Za-z0-9])(?:${withheld.map(escapeRegExp).join("|")})(?![A-Za-z0-9])`,
1007
+ "g"
1008
+ );
1009
+ }
1010
+ withhold(text2) {
1011
+ return this.pattern === null ? text2 : text2.replace(this.pattern, WITHHELD_TEXT);
1012
+ }
1013
+ };
1014
+ EVENT_MAX_STRING = 500;
1015
+ SECRET_VALUE = /^((sk|pk|ghp|xox[abp])[-_][-_A-Za-z0-9]{8,}|AKIA[0-9A-Z]{12,}|Bearer [-_.A-Za-z0-9]{8,})/;
640
1016
  }
641
1017
  });
642
1018
 
@@ -653,6 +1029,25 @@ function isBrowserGone(error) {
653
1029
  if (PAGE_NETWORK_ERROR.test(message)) return false;
654
1030
  return BROWSER_GONE_PATTERNS.some((p) => p.test(message));
655
1031
  }
1032
+ function scrubError(error, scrub) {
1033
+ const seen = /* @__PURE__ */ new Set();
1034
+ let at = error;
1035
+ while (at instanceof Error && !seen.has(at)) {
1036
+ seen.add(at);
1037
+ at.message = scrub(at.message);
1038
+ at.stack = at.stack && scrub(at.stack);
1039
+ scrubOwnText(at, scrub);
1040
+ at = at.cause;
1041
+ }
1042
+ }
1043
+ function scrubOwnText(error, scrub) {
1044
+ for (const key2 of Object.keys(error)) {
1045
+ const value = error[key2];
1046
+ if (typeof value === "string") error[key2] = scrub(value);
1047
+ if (Array.isArray(value) && value.every((item) => typeof item === "string"))
1048
+ error[key2] = value.map((item) => scrub(item));
1049
+ }
1050
+ }
656
1051
  function refusalIsTransient(error) {
657
1052
  const { status, code } = error;
658
1053
  if (typeof status !== "number") return true;
@@ -689,11 +1084,17 @@ var init_browserReconnect = __esm({
689
1084
  ].sort((a, b) => b.length - a.length);
690
1085
  }
691
1086
  scrub(text2) {
692
- const bare = this.secrets.reduce(
1087
+ const bare2 = this.secrets.reduce(
693
1088
  (out, secret) => out.split(secret).join(REDACTED),
694
1089
  text2
695
1090
  );
696
- return bare.replace(TOKEN_QUERY_VALUE, `$1${REDACTED}`);
1091
+ return bare2.replace(TOKEN_QUERY_VALUE, `$1${REDACTED}`);
1092
+ }
1093
+ /** Scrub `error` and the errors it was raised from, in place: the message,
1094
+ * the stack and every other own text property, Playwright's `log` call log
1095
+ * included. */
1096
+ scrubError(error) {
1097
+ scrubError(error, (text2) => this.scrub(text2));
697
1098
  }
698
1099
  };
699
1100
  BrowserReconnected = class extends Error {
@@ -845,22 +1246,6 @@ function capabilityLabel(url) {
845
1246
  }
846
1247
  return CAPABILITY_HOST.exec(host)?.[1] ?? null;
847
1248
  }
848
- function redactActionArgs(action, args) {
849
- const secretField = action === "browser_type" && SECRET_KEY.test(String(args.selector ?? ""));
850
- const out = {};
851
- for (const [key2, value] of Object.entries(args)) {
852
- if (value === null || value === void 0) out[key2] = null;
853
- else if (typeof value === "boolean" || typeof value === "number")
854
- out[key2] = value;
855
- else if (typeof value === "string") {
856
- if (SECRET_KEY.test(key2) || SECRET_VALUE.test(value) || secretField && key2 === "text")
857
- out[key2] = "[redacted]";
858
- else
859
- out[key2] = value.length <= EVENT_MAX_STRING ? value : value.slice(0, EVENT_MAX_STRING) + "\u2026";
860
- } else out[key2] = "[omitted]";
861
- }
862
- return out;
863
- }
864
1249
  async function loadPlaywright() {
865
1250
  try {
866
1251
  const name = "playwright";
@@ -922,62 +1307,14 @@ async function openBrowser(surfaces, opts = {}) {
922
1307
  scrubber
923
1308
  );
924
1309
  }
925
- function computerUseToolkit(browser, opts = {}) {
926
- const maxText = opts.maxText ?? 2e4;
927
- const observe2 = async (selector = "body") => {
928
- const text2 = await browser.text(selector);
929
- return {
930
- url: browser.url,
931
- title: await browser.title(),
932
- text: text2.slice(0, maxText),
933
- truncated: text2.length > maxText
934
- };
935
- };
936
- const impls = {
937
- browser_goto: async (a) => {
938
- await browser.goto(typeof a.path === "string" ? a.path : void 0);
939
- return observe2();
940
- },
941
- browser_click: async (a) => {
942
- await browser.click(str(a.selector, ""));
943
- return observe2();
944
- },
945
- browser_type: async (a) => {
946
- await browser.type(str(a.selector, ""), String(a.text ?? ""));
947
- return { ok: true, url: browser.url };
948
- },
949
- browser_press: async (a) => {
950
- await browser.press(str(a.key, "Enter"));
951
- return observe2();
952
- },
953
- browser_scroll: async (a) => {
954
- await browser.scroll(typeof a.dy === "number" ? a.dy : 600);
955
- return { ok: true, url: browser.url };
956
- },
957
- browser_screenshot: async (a) => ({
958
- image_base64: await browser.screenshotBase64(a.full_page === true),
959
- url: browser.url
960
- }),
961
- browser_read: async (a) => observe2(str(a.selector, "body")),
962
- browser_back: async () => {
963
- await browser.back();
964
- return observe2();
965
- }
966
- };
967
- const specs = COMPUTER_USE_SPECS.map((s) => ({ ...s }));
968
- return {
969
- schemas: specs.map((spec) => schemaFromSignature(spec)),
970
- impls,
971
- specs
972
- };
973
- }
974
- var SURFACE_KINDS, PLATFORM_SESSION_HEADER, SESSION_AUTH_MODES, BROWSER_TIERS, DEFAULT_VIEWPORT, SETTLE_TIMEOUT_MS, SETTLE_QUIET_MS, SETTLE_POLL_MS, EVENT_BATCH_SIZE, EVENT_FLUSH_INTERVAL_MS, EVENT_MAX_RETRIES, EVENT_SCREENSHOT_QUALITY, EVENT_MAX_STRING, SECRET_KEY, SECRET_VALUE, WorldSurfaceUnavailable, UI_TOKEN_QUERY, CAPABILITY_HOST, BrowserActionRecorder, WorldBrowser, COMPUTER_USE_SPECS, str;
1310
+ var SURFACE_KINDS, FIELD_PROBE_TIMEOUT_MS, PLATFORM_SESSION_HEADER, SESSION_AUTH_MODES, BROWSER_TIERS, DEFAULT_VIEWPORT, SETTLE_TIMEOUT_MS, SETTLE_QUIET_MS, SETTLE_POLL_MS, EVENT_BATCH_SIZE, EVENT_FLUSH_INTERVAL_MS, EVENT_MAX_RETRIES, EVENT_SCREENSHOT_QUALITY, WorldSurfaceUnavailable, UI_TOKEN_QUERY, CAPABILITY_HOST, BrowserActionRecorder, WorldBrowser;
975
1311
  var init_browser = __esm({
976
1312
  "src/worlds/browser.ts"() {
977
1313
  "use strict";
978
- init_session2();
1314
+ init_credentialField();
979
1315
  init_browserReconnect();
980
1316
  SURFACE_KINDS = ["tools", "api", "ui", "browser"];
1317
+ FIELD_PROBE_TIMEOUT_MS = 2e3;
981
1318
  PLATFORM_SESSION_HEADER = "X-World-Session";
982
1319
  SESSION_AUTH_MODES = ["vendor", "open"];
983
1320
  BROWSER_TIERS = ["standard", "premium"];
@@ -989,9 +1326,6 @@ var init_browser = __esm({
989
1326
  EVENT_FLUSH_INTERVAL_MS = 1e3;
990
1327
  EVENT_MAX_RETRIES = 3;
991
1328
  EVENT_SCREENSHOT_QUALITY = 60;
992
- EVENT_MAX_STRING = 500;
993
- SECRET_KEY = /pass(word|wd)?|secret|token|api[-_]?key|authorization|cookie|(^|[-_ #.\["'=])(otp|pin|cvv|ssn)([-_ \]"']|$)/i;
994
- SECRET_VALUE = /^((sk|pk|ghp|xox[abp])[-_][-_A-Za-z0-9]{8,}|AKIA[0-9A-Z]{12,}|Bearer [-_.A-Za-z0-9]{8,})/;
995
1329
  WorldSurfaceUnavailable = class extends Error {
996
1330
  constructor(surface, reason) {
997
1331
  super(`World surface '${surface}' is unavailable: ${reason}`);
@@ -1114,6 +1448,8 @@ var init_browser = __esm({
1114
1448
  recorder;
1115
1449
  reconnector;
1116
1450
  scrubber;
1451
+ typed = [];
1452
+ typedText = new CredentialText([]);
1117
1453
  current;
1118
1454
  inflight = 0;
1119
1455
  lastNetwork = Date.now();
@@ -1127,10 +1463,20 @@ var init_browser = __esm({
1127
1463
  get agentId() {
1128
1464
  return this.recorder?.agentId ?? null;
1129
1465
  }
1130
- /** `text` with this session's credentials (UI token, browser address) removed. */
1466
+ /** `text` with this session's credentials (UI token, browser address) and
1467
+ * the credentials typed into it removed. */
1131
1468
  scrub(text2) {
1469
+ return this.typedText.withhold(this.scrubber.scrub(text2));
1470
+ }
1471
+ /** `text` with this session's credentials removed and nothing else
1472
+ * changed: for text that is compared and never leaves the process. */
1473
+ scrubSession(text2) {
1132
1474
  return this.scrubber.scrub(text2);
1133
1475
  }
1476
+ /** Every credential typed into this browser by `type`. */
1477
+ get typedCredentials() {
1478
+ return [...this.typed];
1479
+ }
1134
1480
  watchNetwork(page) {
1135
1481
  page.on("request", () => {
1136
1482
  this.inflight += 1;
@@ -1174,7 +1520,7 @@ var init_browser = __esm({
1174
1520
  async recover(reconnector, cause) {
1175
1521
  const started = Date.now();
1176
1522
  const message = cause instanceof Error ? cause.message : String(cause);
1177
- const args = { cause: this.scrubber.scrub(message).slice(0, 200) };
1523
+ const args = { cause: this.scrub(message).slice(0, 200) };
1178
1524
  let result;
1179
1525
  try {
1180
1526
  result = await reconnector.recover(cause, (c) => this.adopt(c));
@@ -1209,7 +1555,9 @@ var init_browser = __esm({
1209
1555
  }
1210
1556
  /** Run one action and report it: the event carries what was asked,
1211
1557
  * whether it worked, and the screen after — for failures too, so a
1212
- * reviewer sees what the agent saw when the selector did not match. */
1558
+ * reviewer sees what the agent saw when the selector did not match. The
1559
+ * error it throws keeps no session credential and no credential typed into
1560
+ * this browser, which Playwright's call log would quote. */
1213
1561
  async act(action, args, fn, onLoss = "report") {
1214
1562
  const started = Date.now();
1215
1563
  try {
@@ -1217,6 +1565,7 @@ var init_browser = __esm({
1217
1565
  await this.report(action, args, started, null);
1218
1566
  return result;
1219
1567
  } catch (error) {
1568
+ this.scrubError(error);
1220
1569
  await this.report(action, args, started, error);
1221
1570
  throw error;
1222
1571
  }
@@ -1225,7 +1574,7 @@ var init_browser = __esm({
1225
1574
  async report(action, args, started, failure) {
1226
1575
  const recorder = this.recorder;
1227
1576
  if (!recorder) return;
1228
- const error = failure === null ? null : this.scrubber.scrub(
1577
+ const error = failure === null ? null : this.scrub(
1229
1578
  failure instanceof Error ? `${failure.name}: ${failure.message}` : String(failure)
1230
1579
  ).slice(0, 4e3);
1231
1580
  recorder.record({
@@ -1238,7 +1587,7 @@ var init_browser = __esm({
1238
1587
  Object.fromEntries(
1239
1588
  Object.entries(args).map(([key2, value]) => [
1240
1589
  key2,
1241
- typeof value === "string" ? this.scrubber.scrub(value) : value
1590
+ typeof value === "string" ? this.scrub(value) : value
1242
1591
  ])
1243
1592
  )
1244
1593
  ),
@@ -1257,8 +1606,8 @@ var init_browser = __esm({
1257
1606
  screenshot: null
1258
1607
  };
1259
1608
  try {
1260
- out.url = this.scrubber.scrub(this.page.url());
1261
- out.title = this.scrubber.scrub(await this.page.title());
1609
+ out.url = this.scrub(this.page.url());
1610
+ out.title = this.scrub(await this.page.title());
1262
1611
  const jpeg = await this.page.screenshot({
1263
1612
  type: "jpeg",
1264
1613
  quality: EVENT_SCREENSHOT_QUALITY
@@ -1295,7 +1644,7 @@ var init_browser = __esm({
1295
1644
  async () => {
1296
1645
  await this.page.goto(target, { waitUntil: "load" });
1297
1646
  await this.settle();
1298
- return this.page.url();
1647
+ return this.url;
1299
1648
  },
1300
1649
  // Navigating again lands on the same page: safe to replay.
1301
1650
  "retry"
@@ -1305,7 +1654,7 @@ var init_browser = __esm({
1305
1654
  return this.act("browser_back", {}, async () => {
1306
1655
  await this.page.goBack({ waitUntil: "load" });
1307
1656
  await this.settle();
1308
- return this.page.url();
1657
+ return this.url;
1309
1658
  });
1310
1659
  }
1311
1660
  /** Wait for the page to finish reacting to an action. `load` alone is not
@@ -1324,19 +1673,54 @@ var init_browser = __esm({
1324
1673
  await this.page.waitForTimeout(SETTLE_POLL_MS);
1325
1674
  }
1326
1675
  }
1327
- async click(selector) {
1676
+ async click(selector, opts = {}) {
1328
1677
  await this.act("browser_click", { selector }, async () => {
1329
- await this.page.click(selector);
1678
+ await this.page.click(selector, { timeout: opts.timeoutMs });
1330
1679
  await this.settle();
1331
1680
  });
1332
1681
  }
1333
- async type(selector, text2) {
1682
+ /** Replace the field's value with `text`. `opts.credential` is whether the
1683
+ * field takes one, when the caller already probed it; a credential is
1684
+ * withheld from the event and from any error. */
1685
+ async type(selector, text2, opts = {}) {
1686
+ const secret = opts.credential ?? await this.credentialField(selector);
1687
+ if (secret) this.typed.push(text2);
1688
+ this.typedText = new CredentialText(this.typed);
1334
1689
  await this.act(
1335
1690
  "browser_type",
1336
- { selector, text: text2 },
1337
- () => this.page.fill(selector, text2)
1691
+ { selector, text: secret ? "[redacted]" : text2 },
1692
+ () => this.page.fill(selector, text2, { timeout: opts.timeoutMs })
1338
1693
  );
1339
1694
  }
1695
+ /** `DESCRIBE_FIELD_JS` of the element `selector` finds, or `UNREADABLE`. */
1696
+ async describeField(selector) {
1697
+ try {
1698
+ const described = await this.page.locator(selector).evaluate(describeField, void 0, { timeout: FIELD_PROBE_TIMEOUT_MS });
1699
+ return String(described ?? "");
1700
+ } catch {
1701
+ return UNREADABLE;
1702
+ }
1703
+ }
1704
+ /** Whether the field `selector` finds takes a credential; one it cannot
1705
+ * read counts. */
1706
+ async credentialField(selector) {
1707
+ return isCredentialField(await this.describeField(selector));
1708
+ }
1709
+ /** What the field `selector` finds holds (`FIELD_VALUE_JS`), or null when
1710
+ * it cannot be read. */
1711
+ async fieldValue(selector) {
1712
+ try {
1713
+ const value = await this.page.locator(selector).evaluate(readFieldValue, void 0, { timeout: FIELD_PROBE_TIMEOUT_MS });
1714
+ return value === null || value === void 0 ? null : String(value);
1715
+ } catch {
1716
+ return null;
1717
+ }
1718
+ }
1719
+ /** Take this session's credentials out of `error` and the errors it came
1720
+ * from, in place. */
1721
+ scrubError(error) {
1722
+ scrubError(error, (text2) => this.scrub(text2));
1723
+ }
1340
1724
  async press(key2) {
1341
1725
  await this.act("browser_press", { key: key2 }, async () => {
1342
1726
  await this.page.keyboard.press(key2);
@@ -1359,14 +1743,39 @@ var init_browser = __esm({
1359
1743
  async screenshotBase64(fullPage = false) {
1360
1744
  return (await this.screenshot(fullPage)).toString("base64");
1361
1745
  }
1746
+ /** The visible text of `selector`'s element, without what any field on the
1747
+ * page that takes a credential holds. */
1362
1748
  async text(selector = "body") {
1363
- return this.resilient(() => this.page.innerText(selector), "retry");
1749
+ const withheld = new CredentialText(await this.credentialTexts());
1750
+ return withheld.withhold(
1751
+ await this.resilient(() => this.page.innerText(selector), "retry")
1752
+ );
1753
+ }
1754
+ /** What each field on the page that takes a credential holds: an input's
1755
+ * or textarea's value, a select's chosen option, a contenteditable's text. */
1756
+ async credentialTexts() {
1757
+ return this.resilient(async () => {
1758
+ const pairs = await this.page.locator(FIELDS).evaluateAll(readEditables);
1759
+ return credentialTexts(pairs);
1760
+ }, "retry");
1761
+ }
1762
+ /** Wait until the element `selector` finds could be clicked, without
1763
+ * clicking it. */
1764
+ async actionable(selector) {
1765
+ await this.resilient(() => this.page.locator(selector).click({ trial: true }), "retry");
1766
+ }
1767
+ async ariaSnapshot() {
1768
+ return this.resilient(async () => {
1769
+ if (!this.page.ariaSnapshot)
1770
+ throw new TypeError("this Playwright has no page.ariaSnapshot");
1771
+ return this.page.ariaSnapshot({ mode: "ai" });
1772
+ }, "retry");
1364
1773
  }
1365
1774
  async html() {
1366
1775
  return this.resilient(() => this.page.content(), "retry");
1367
1776
  }
1368
1777
  get url() {
1369
- return this.page.url();
1778
+ return withoutUiToken(this.page.url());
1370
1779
  }
1371
1780
  async title() {
1372
1781
  return this.resilient(() => this.page.title(), "retry");
@@ -1379,21 +1788,504 @@ var init_browser = __esm({
1379
1788
  }
1380
1789
  }
1381
1790
  };
1791
+ }
1792
+ });
1793
+
1794
+ // src/worlds/pageState.ts
1795
+ function selectorRef(selector) {
1796
+ if (selector.includes("aria-ref"))
1797
+ throw new PageStateError(
1798
+ "aria-ref selectors are not taken: pass ref=\u2026 from browser_snapshot"
1799
+ );
1800
+ return REF_SELECTOR.exec(selector.replace(/^ +| +$/g, ""))?.[1] ?? null;
1801
+ }
1802
+ var DEFAULT_MAX_CHARS, REF_ACT_TIMEOUT_MS, STEADY_READS, NEEDS_PLAYWRIGHT, CHANGED, LINE_KEY, ATTRIBUTES, FOCUS, STATES, ROLE, REF, REF_SELECTOR, EDITABLE_ROLES, VALUE_KEYS, WITHHELD, PageStateError, AriaLine, Touched, sameLines, deeper, PageState, PageObserver;
1803
+ var init_pageState = __esm({
1804
+ "src/worlds/pageState.ts"() {
1805
+ "use strict";
1806
+ init_credentialField();
1807
+ DEFAULT_MAX_CHARS = 2e4;
1808
+ REF_ACT_TIMEOUT_MS = 2e3;
1809
+ STEADY_READS = 4;
1810
+ NEEDS_PLAYWRIGHT = "browser_snapshot needs Playwright 1.59 or newer (npm install playwright@latest)";
1811
+ CHANGED = "the page changed since the last browser_snapshot: take a new one (a page that never holds still can be driven with text= or CSS selectors)";
1812
+ LINE_KEY = /^ *- ('(?:[^']|'')*'|.*?)(:(?: .*)?)?$/s;
1813
+ ATTRIBUTES = /(?: \[[^[\]]*\])*$/;
1814
+ FOCUS = / \[active\]/g;
1815
+ STATES = / \[(?:checked(?:=mixed)?|expanded|pressed(?:=mixed)?|selected)\]/g;
1816
+ ROLE = /^[a-z]+/;
1817
+ REF = /\[ref=((?:f[0-9]+)?e[0-9]+)\]/g;
1818
+ REF_SELECTOR = /^ref=((?:f[0-9]+)?e[0-9]+)$/;
1819
+ EDITABLE_ROLES = /* @__PURE__ */ new Set([
1820
+ "textbox",
1821
+ "searchbox",
1822
+ "combobox",
1823
+ "spinbutton",
1824
+ "slider"
1825
+ ]);
1826
+ VALUE_KEYS = /* @__PURE__ */ new Set(["text", "/placeholder"]);
1827
+ WITHHELD = ": [redacted]";
1828
+ PageStateError = class extends Error {
1829
+ name = "PageStateError";
1830
+ };
1831
+ AriaLine = class _AriaLine {
1832
+ constructor(text2, indent, key2 = "", attributes = "", rest = "") {
1833
+ this.text = text2;
1834
+ this.indent = indent;
1835
+ this.key = key2;
1836
+ this.attributes = attributes;
1837
+ this.rest = rest;
1838
+ }
1839
+ text;
1840
+ indent;
1841
+ key;
1842
+ attributes;
1843
+ rest;
1844
+ static parse(text2) {
1845
+ const indent = text2.length - text2.replace(/^ +/, "").length;
1846
+ const found = LINE_KEY.exec(text2);
1847
+ if (!found) return new _AriaLine(text2, indent);
1848
+ const key2 = found[1].startsWith("'") ? found[1].slice(1, -1).replaceAll("''", "'") : found[1];
1849
+ return new _AriaLine(
1850
+ text2,
1851
+ indent,
1852
+ key2,
1853
+ ATTRIBUTES.exec(key2)?.[0] ?? "",
1854
+ found[2] ?? ""
1855
+ );
1856
+ }
1857
+ static parseAll(aria) {
1858
+ return aria === "" ? [] : aria.split("\n").map((text2) => _AriaLine.parse(text2));
1859
+ }
1860
+ get refs() {
1861
+ return [...this.attributes.matchAll(REF)].map((ref) => ref[1]);
1862
+ }
1863
+ get disabled() {
1864
+ return this.attributes.includes("[disabled]");
1865
+ }
1866
+ get editable() {
1867
+ const role = ROLE.exec(this.key)?.[0];
1868
+ return role !== void 0 && EDITABLE_ROLES.has(role);
1869
+ }
1870
+ /** A value line: a field's text, or the placeholder it shows. */
1871
+ get value() {
1872
+ return VALUE_KEYS.has(this.key);
1873
+ }
1874
+ get states() {
1875
+ return this.attributes.match(STATES) ?? [];
1876
+ }
1877
+ get namedLikeCredential() {
1878
+ return SECRET_KEY.test(
1879
+ this.key.slice(0, this.key.length - this.attributes.length)
1880
+ );
1881
+ }
1882
+ /** Whether every value in and under this line is withheld. A field is,
1883
+ * when it is named like a credential or sits in something that is, has no
1884
+ * ref to probe, or `describe` reads it as a credential field. Any other
1885
+ * line is, when it is named like a credential and holds typed text (a
1886
+ * contenteditable), or has no ref to tell. */
1887
+ async credentialField(describe2, withinCredential) {
1888
+ if (this.editable)
1889
+ return this.credentialFieldInput(describe2, withinCredential);
1890
+ if (!this.namedLikeCredential) return false;
1891
+ if (this.refs.length === 0) return true;
1892
+ return isTextField(await describe2(this.refs[0]));
1893
+ }
1894
+ async credentialFieldInput(describe2, withinCredential) {
1895
+ if (withinCredential || this.namedLikeCredential) return true;
1896
+ if (this.refs.length === 0) return true;
1897
+ return isCredentialField(await describe2(this.refs[0]));
1898
+ }
1899
+ /** The line as shown: `withholding` applied to its text, while its refs and
1900
+ * states are still read from the attribute run Playwright wrote, so a
1901
+ * withheld name cannot join that run. */
1902
+ withheldBy(withhold) {
1903
+ return new _AriaLine(
1904
+ this.withholding(withhold),
1905
+ this.indent,
1906
+ this.key,
1907
+ this.attributes,
1908
+ this.rest
1909
+ );
1910
+ }
1911
+ /** The line with `withhold` applied to its name and value, its attribute
1912
+ * run (refs, states, levels) as Playwright wrote it. */
1913
+ withholding(withhold) {
1914
+ const at = this.attributes ? this.text.lastIndexOf(
1915
+ this.attributes,
1916
+ this.text.length - this.rest.length - this.attributes.length
1917
+ ) : -1;
1918
+ if (at < 0) return withhold(this.text);
1919
+ const end = at + this.attributes.length;
1920
+ return withhold(this.text.slice(0, at)) + this.attributes + withhold(this.text.slice(end));
1921
+ }
1922
+ /** The line with its own value replaced, keeping the key as Playwright
1923
+ * wrote it. */
1924
+ get withheld() {
1925
+ if (this.key === "/placeholder" || !this.rest.startsWith(": "))
1926
+ return this.text;
1927
+ return this.text.slice(0, this.text.length - this.rest.length) + WITHHELD;
1928
+ }
1929
+ };
1930
+ Touched = class _Touched {
1931
+ constructor(clicked = /* @__PURE__ */ new Map(), typed = /* @__PURE__ */ new Map()) {
1932
+ this.clicked = clicked;
1933
+ this.typed = typed;
1934
+ }
1935
+ clicked;
1936
+ typed;
1937
+ afterClick(ref, states) {
1938
+ return new _Touched(new Map([...this.clicked, [ref, states]]), this.typed);
1939
+ }
1940
+ afterTyping(ref, text2) {
1941
+ return new _Touched(this.clicked, new Map([...this.typed, [ref, text2]]));
1942
+ }
1943
+ /** The snapshot's lines as the page should now read them. */
1944
+ expected(lines) {
1945
+ return this.compared(lines, (line) => this.leftByClick(line));
1946
+ }
1947
+ /** A fresh read's lines, in the same form. */
1948
+ actual(lines) {
1949
+ return this.compared(lines, (line) => line.states);
1950
+ }
1951
+ compared(lines, states) {
1952
+ const out = [];
1953
+ let typedAt = null;
1954
+ for (const line of lines) {
1955
+ if (typedAt !== null && line.indent > typedAt && line.value) continue;
1956
+ typedAt = this.isTyped(line) ? line.indent : null;
1957
+ out.push(this.comparedLine(line, states(line)));
1958
+ }
1959
+ return out;
1960
+ }
1961
+ isTyped(line) {
1962
+ return line.refs.some((ref) => this.typed.has(ref));
1963
+ }
1964
+ clickedRef(line) {
1965
+ return line.refs.find((ref) => this.clicked.has(ref));
1966
+ }
1967
+ leftByClick(line) {
1968
+ const ref = this.clickedRef(line);
1969
+ return ref === void 0 ? line.states : this.clicked.get(ref);
1970
+ }
1971
+ comparedLine(line, states) {
1972
+ if (this.isTyped(line))
1973
+ return (" ".repeat(line.indent) + "- " + line.key).replace(FOCUS, "");
1974
+ if (this.clickedRef(line) !== void 0)
1975
+ return line.text.replace(FOCUS, "").replace(STATES, "") + states.join("");
1976
+ return line.text.replace(FOCUS, "");
1977
+ }
1978
+ };
1979
+ sameLines = (a, b) => a.length === b.length && a.every((line, at) => line === b[at]);
1980
+ deeper = (line, below) => below !== null && line.indent > below ? below : null;
1981
+ PageState = class _PageState {
1982
+ constructor(url, title, snapshot, refs, disabled, truncated, credentials = /* @__PURE__ */ new Set()) {
1983
+ this.url = url;
1984
+ this.title = title;
1985
+ this.snapshot = snapshot;
1986
+ this.refs = refs;
1987
+ this.disabled = disabled;
1988
+ this.truncated = truncated;
1989
+ this.credentials = credentials;
1990
+ }
1991
+ url;
1992
+ title;
1993
+ snapshot;
1994
+ refs;
1995
+ disabled;
1996
+ truncated;
1997
+ credentials;
1998
+ static parse(aria, opts) {
1999
+ return _PageState.ofLines(AriaLine.parseAll(aria), opts);
2000
+ }
2001
+ static ofLines(lines, opts) {
2002
+ const maxChars = opts.maxChars ?? DEFAULT_MAX_CHARS;
2003
+ const shown = [];
2004
+ let size = 0;
2005
+ for (const line of lines) {
2006
+ const width = [...line.text].length + 1;
2007
+ if (size + width > maxChars) break;
2008
+ size += width;
2009
+ shown.push(line);
2010
+ }
2011
+ return new _PageState(
2012
+ opts.url,
2013
+ opts.title,
2014
+ shown.map((line) => line.text).join("\n"),
2015
+ new Set(shown.flatMap((line) => line.refs)),
2016
+ new Set(
2017
+ shown.filter((line) => line.disabled).flatMap((line) => line.refs)
2018
+ ),
2019
+ shown.length < lines.length,
2020
+ opts.credentials ?? /* @__PURE__ */ new Set()
2021
+ );
2022
+ }
2023
+ /** `aria` with credential values withheld: every value in and under a
2024
+ * credential field (see `AriaLine.credentialField`; `describe` is
2025
+ * `DESCRIBE_FIELD_JS` of a ref's element), the placeholder aside, and the
2026
+ * value of any line named like a credential. Names, roles and refs stay. */
2027
+ static async redacted(aria, describe2) {
2028
+ const out = [];
2029
+ const withheld = [];
2030
+ let withheldBelow = null;
2031
+ let credentialBelow = null;
2032
+ for (const line of AriaLine.parseAll(aria)) {
2033
+ withheldBelow = deeper(line, withheldBelow);
2034
+ credentialBelow = deeper(line, credentialBelow);
2035
+ if (withheldBelow === null && await line.credentialField(describe2, credentialBelow !== null))
2036
+ withheldBelow = line.indent;
2037
+ if (credentialBelow === null && line.namedLikeCredential)
2038
+ credentialBelow = line.indent;
2039
+ const hidden = withheldBelow !== null || line.namedLikeCredential;
2040
+ out.push(hidden ? line.withheld : line.text);
2041
+ if (hidden) withheld.push(...line.refs);
2042
+ }
2043
+ return { snapshot: out.join("\n"), withheld: new Set(withheld) };
2044
+ }
2045
+ target(ref) {
2046
+ if (!this.refs.has(ref))
2047
+ throw new PageStateError(
2048
+ `ref=${ref} is not in the last browser_snapshot: take a new one`
2049
+ );
2050
+ if (this.disabled.has(ref))
2051
+ throw new PageStateError(`ref=${ref} is disabled`);
2052
+ return `aria-ref=${ref}`;
2053
+ }
2054
+ observation() {
2055
+ return {
2056
+ url: this.url,
2057
+ title: this.title,
2058
+ snapshot: this.snapshot,
2059
+ truncated: this.truncated
2060
+ };
2061
+ }
2062
+ };
2063
+ PageObserver = class {
2064
+ constructor(browser, maxChars = DEFAULT_MAX_CHARS) {
2065
+ this.browser = browser;
2066
+ this.maxChars = maxChars;
2067
+ }
2068
+ browser;
2069
+ maxChars;
2070
+ last = null;
2071
+ seen = [];
2072
+ seenUrl = "";
2073
+ touched = new Touched();
2074
+ turn = Promise.resolve();
2075
+ async snapshot() {
2076
+ return this.inTurn(() => this.takeSnapshot());
2077
+ }
2078
+ async click(selector) {
2079
+ return this.inTurn(() => this.clickOnce(selector));
2080
+ }
2081
+ async type(selector, text2) {
2082
+ return this.inTurn(() => this.typeOnce(selector, text2));
2083
+ }
2084
+ /** One call at a time, so a tool call a model made in parallel cannot act
2085
+ * between another's checks and its action. */
2086
+ inTurn(fn) {
2087
+ const run = this.turn.then(fn, fn);
2088
+ this.turn = run.catch(() => void 0);
2089
+ return run;
2090
+ }
2091
+ async takeSnapshot() {
2092
+ const aria = this.browser.scrubSession(await this.steady());
2093
+ const shown = await PageState.redacted(
2094
+ aria,
2095
+ (ref) => this.browser.describeField(`aria-ref=${ref}`)
2096
+ );
2097
+ const secrets = new CredentialText([
2098
+ ...await this.withheldValues(shown),
2099
+ ...await this.browser.credentialTexts(),
2100
+ ...this.browser.typedCredentials
2101
+ ]);
2102
+ const lines = AriaLine.parseAll(shown.snapshot).map(
2103
+ (line) => line.withheldBy((text2) => secrets.withhold(text2))
2104
+ );
2105
+ this.last = PageState.ofLines(lines, {
2106
+ url: this.url(),
2107
+ title: this.browser.scrub(await this.browser.title()),
2108
+ maxChars: this.maxChars,
2109
+ credentials: shown.withheld
2110
+ });
2111
+ this.seen = AriaLine.parseAll(aria);
2112
+ this.seenUrl = this.browser.scrubSession(this.browser.url);
2113
+ this.touched = new Touched();
2114
+ return this.last;
2115
+ }
2116
+ /** The values of the fields the redaction withheld: a page may repeat them
2117
+ * in another line's name (a row or cell named from its content, a label
2118
+ * that wraps the field). */
2119
+ async withheldValues(shown) {
2120
+ const refs = AriaLine.parseAll(shown.snapshot).filter((line) => line.editable).flatMap((line) => line.refs).filter((ref) => shown.withheld.has(ref));
2121
+ const values = [];
2122
+ for (const ref of refs)
2123
+ values.push(await this.browser.fieldValue(`aria-ref=${ref}`) ?? "");
2124
+ return values;
2125
+ }
2126
+ async clickOnce(selector) {
2127
+ const ref = selectorRef(selector);
2128
+ if (ref === null) return this.browser.click(selector);
2129
+ const [, target] = this.target(ref);
2130
+ await this.ready(target);
2131
+ await this.browser.click(target, { timeoutMs: REF_ACT_TIMEOUT_MS });
2132
+ const left = (await this.now()).find((line) => line.refs.includes(ref));
2133
+ if (left) this.touched = this.touched.afterClick(ref, left.states);
2134
+ }
2135
+ async typeOnce(selector, text2) {
2136
+ const ref = selectorRef(selector);
2137
+ if (ref === null) return this.browser.type(selector, text2);
2138
+ const [last, target] = this.target(ref);
2139
+ const credential = last.credentials.has(ref) || await this.browser.credentialField(target);
2140
+ await this.ready(target);
2141
+ await this.browser.type(target, text2, {
2142
+ timeoutMs: REF_ACT_TIMEOUT_MS,
2143
+ credential
2144
+ });
2145
+ this.touched = this.touched.afterTyping(ref, text2);
2146
+ }
2147
+ target(ref) {
2148
+ if (this.last === null)
2149
+ throw new PageStateError(
2150
+ "ref=\u2026 selectors come from browser_snapshot: take one first"
2151
+ );
2152
+ return [this.last, this.last.target(ref)];
2153
+ }
2154
+ async ready(target) {
2155
+ await this.still();
2156
+ await this.browser.actionable(target);
2157
+ await this.still();
2158
+ }
2159
+ /** A page still rendering when it is read would refuse the model's next
2160
+ * ref, so the snapshot it is shown is one that read the same before and
2161
+ * after the page settled again. */
2162
+ async steady() {
2163
+ const untouched = new Touched();
2164
+ let aria = await this.read();
2165
+ for (let read = 1; read < STEADY_READS; read++) {
2166
+ await this.browser.settle();
2167
+ const again = await this.read();
2168
+ if (sameLines(
2169
+ untouched.actual(AriaLine.parseAll(again)),
2170
+ untouched.actual(AriaLine.parseAll(aria))
2171
+ ))
2172
+ return again;
2173
+ aria = again;
2174
+ }
2175
+ return aria;
2176
+ }
2177
+ async read() {
2178
+ try {
2179
+ return await this.browser.ariaSnapshot();
2180
+ } catch (error) {
2181
+ if (error instanceof TypeError)
2182
+ throw new PageStateError(NEEDS_PLAYWRIGHT);
2183
+ throw error;
2184
+ }
2185
+ }
2186
+ url() {
2187
+ return this.browser.scrub(this.browser.url);
2188
+ }
2189
+ async now() {
2190
+ return AriaLine.parseAll(this.browser.scrubSession(await this.read()));
2191
+ }
2192
+ async still() {
2193
+ if (this.browser.scrubSession(this.browser.url) !== this.seenUrl || !sameLines(
2194
+ this.touched.actual(await this.now()),
2195
+ this.touched.expected(this.seen)
2196
+ ))
2197
+ throw new PageStateError(CHANGED);
2198
+ for (const [ref, text2] of this.touched.typed)
2199
+ if (await this.browser.fieldValue(`aria-ref=${ref}`) !== text2)
2200
+ throw new PageStateError(CHANGED);
2201
+ }
2202
+ };
2203
+ }
2204
+ });
2205
+
2206
+ // src/worlds/browserTools.ts
2207
+ function computerUseToolkit(browser, opts = {}) {
2208
+ const maxText = opts.maxText ?? DEFAULT_MAX_CHARS;
2209
+ const pages = new PageObserver(browser, maxText);
2210
+ const observe2 = async (selector = "body") => {
2211
+ const text2 = browser.scrub(await browser.text(selector));
2212
+ return {
2213
+ url: browser.scrub(browser.url),
2214
+ title: browser.scrub(await browser.title()),
2215
+ text: text2.slice(0, maxText),
2216
+ truncated: text2.length > maxText
2217
+ };
2218
+ };
2219
+ const impls = {
2220
+ browser_goto: async (a) => {
2221
+ await browser.goto(typeof a.path === "string" ? a.path : void 0);
2222
+ return observe2();
2223
+ },
2224
+ browser_snapshot: async () => (await pages.snapshot()).observation(),
2225
+ browser_click: async (a) => {
2226
+ await pages.click(str(a.selector, ""));
2227
+ return observe2();
2228
+ },
2229
+ browser_type: async (a) => {
2230
+ await pages.type(str(a.selector, ""), String(a.text ?? ""));
2231
+ return { ok: true, url: browser.scrub(browser.url) };
2232
+ },
2233
+ browser_press: async (a) => {
2234
+ await browser.press(str(a.key, "Enter"));
2235
+ return observe2();
2236
+ },
2237
+ browser_scroll: async (a) => {
2238
+ await browser.scroll(typeof a.dy === "number" ? a.dy : 600);
2239
+ return { ok: true, url: browser.scrub(browser.url) };
2240
+ },
2241
+ browser_screenshot: async (a) => ({
2242
+ image_base64: await browser.screenshotBase64(a.full_page === true),
2243
+ url: browser.scrub(browser.url)
2244
+ }),
2245
+ browser_read: async (a) => observe2(str(a.selector, "body")),
2246
+ browser_back: async () => {
2247
+ await browser.back();
2248
+ return observe2();
2249
+ }
2250
+ };
2251
+ const specs = COMPUTER_USE_SPECS.map((s) => ({ ...s }));
2252
+ return {
2253
+ schemas: specs.map((spec) => schemaFromSignature(spec)),
2254
+ impls: Object.fromEntries(
2255
+ Object.entries(impls).map(([name, impl]) => [
2256
+ name,
2257
+ scrubbingErrors(browser, impl)
2258
+ ])
2259
+ ),
2260
+ specs
2261
+ };
2262
+ }
2263
+ var COMPUTER_USE_SPECS, scrubbingErrors, str;
2264
+ var init_browserTools = __esm({
2265
+ "src/worlds/browserTools.ts"() {
2266
+ "use strict";
2267
+ init_pageState();
2268
+ init_session2();
1382
2269
  COMPUTER_USE_SPECS = [
1383
2270
  {
1384
2271
  name: "browser_goto",
1385
2272
  signature: "browser_goto(path=None)",
1386
2273
  doc: "Open a page of the world's UI. `path` is a UI path like /customers, a full URL, or omitted for the entry page. Returns the URL and page text."
1387
2274
  },
2275
+ {
2276
+ name: "browser_snapshot",
2277
+ signature: "browser_snapshot()",
2278
+ doc: "The page as an accessibility tree, one line per element with its role, name and [ref=e3]. To act on an element, pass `ref=e3` as the selector of browser_click or browser_type. Returns {url, title, snapshot, truncated}."
2279
+ },
1388
2280
  {
1389
2281
  name: "browser_click",
1390
2282
  signature: "browser_click(selector)",
1391
- doc: "Click an element by Playwright selector (CSS, `text=Refund`, `role=button[name=Save]`). Returns the page text after the click."
2283
+ doc: "Click an element by `ref=e3` from the last browser_snapshot, or by Playwright selector (CSS, `text=Refund`, `role=button[name=Save]`). Returns the page text after the click."
1392
2284
  },
1393
2285
  {
1394
2286
  name: "browser_type",
1395
2287
  signature: "browser_type(selector, text)",
1396
- doc: "Replace the value of an input/textarea found by selector with `text`."
2288
+ doc: "Replace the value of an input/textarea, found by `ref=e3` or by selector, with `text`."
1397
2289
  },
1398
2290
  {
1399
2291
  name: "browser_press",
@@ -1421,6 +2313,14 @@ var init_browser = __esm({
1421
2313
  doc: "Go back one page in history."
1422
2314
  }
1423
2315
  ];
2316
+ scrubbingErrors = (browser, impl) => async (args) => {
2317
+ try {
2318
+ return await impl(args);
2319
+ } catch (error) {
2320
+ browser.scrubError(error);
2321
+ throw error;
2322
+ }
2323
+ };
1424
2324
  str = (v, fallback) => typeof v === "string" && v.length > 0 ? v : fallback;
1425
2325
  }
1426
2326
  });
@@ -1565,13 +2465,12 @@ function isNativePage(page) {
1565
2465
  const mouse = candidate?.mouse;
1566
2466
  return typeof candidate?.context === "function" && NATIVE_METHODS.every((m) => typeof mouse?.[m] === "function");
1567
2467
  }
1568
- var FOCUSED_FIELD_JS, SECRET_FOCUS, DRAG_STEPS, PNG_SIGNATURE, NATIVE_METHODS, Screen;
2468
+ var FOCUSED_FIELD_JS, DRAG_STEPS, PNG_SIGNATURE, NATIVE_METHODS, Screen;
1569
2469
  var init_screen = __esm({
1570
2470
  "src/worlds/nativeComputer/screen.ts"() {
1571
2471
  "use strict";
1572
- init_browser();
1573
- FOCUSED_FIELD_JS = "(() => { let e = document.activeElement; const inner = (el) => (el.shadowRoot && el.shadowRoot.activeElement) || (el.contentDocument && el.contentDocument.activeElement); while (e && inner(e)) e = inner(e); if (!e) return ''; if (e.tagName === 'IFRAME' || e.tagName === 'FRAME') return 'frame'; if (!(e.tagName === 'INPUT' || e.tagName === 'TEXTAREA' || e.isContentEditable)) return 'opaque'; return [e.type, e.name, e.id, e.getAttribute('autocomplete')].filter(Boolean).join(' '); })()";
1574
- SECRET_FOCUS = ["password", "frame", "opaque"];
2472
+ init_credentialField();
2473
+ FOCUSED_FIELD_JS = `(() => { let e = document.activeElement; const inner = (el) => (el.shadowRoot && el.shadowRoot.activeElement) || (el.contentDocument && el.contentDocument.activeElement); while (e && inner(e)) e = inner(e); return (${DESCRIBE_FIELD_JS})(e); })()`;
1575
2474
  DRAG_STEPS = 5;
1576
2475
  PNG_SIGNATURE = Buffer.from([
1577
2476
  137,
@@ -1662,7 +2561,7 @@ var init_screen = __esm({
1662
2561
  } catch {
1663
2562
  return true;
1664
2563
  }
1665
- return SECRET_FOCUS.some((prefix) => described.startsWith(prefix)) || SECRET_KEY.test(described);
2564
+ return isCredentialField(described);
1666
2565
  }
1667
2566
  /** CDP renders a clip at the page's device pixel ratio as well as its
1668
2567
  * `scale` (a Retina host doubles it), so a capture of the wrong width
@@ -2840,7 +3739,7 @@ var init_requestLedger = __esm({
2840
3739
  "use strict";
2841
3740
  init_worlds();
2842
3741
  init_sessionContract();
2843
- WORLD_REQUEST_VIAS = ["api", "ui", "tool", "webhook"];
3742
+ WORLD_REQUEST_VIAS = ["api", "ui", "tool", "webhook", "page"];
2844
3743
  WorldRequestFilterError = class extends Error {
2845
3744
  };
2846
3745
  NOT_RECORDED = "This session's engine records no requests; only hosted World Host sessions do.";
@@ -3349,7 +4248,8 @@ async function openSession(slugOrRef, taskOrOpts = {}, positionalOpts = {}) {
3349
4248
  ...opts.reuseWarm === void 0 ? {} : { reuseWarm: opts.reuseWarm },
3350
4249
  ...opts.surfaces?.length ? { surfaces: opts.surfaces } : {},
3351
4250
  ...opts.browserTier === void 0 ? {} : { browserTier: opts.browserTier },
3352
- ...opts.auth === void 0 ? {} : { auth: opts.auth }
4251
+ ...opts.auth === void 0 ? {} : { auth: opts.auth },
4252
+ ...opts.worldState === void 0 ? {} : { worldState: opts.worldState }
3353
4253
  }
3354
4254
  );
3355
4255
  return new WorldSession(state2.sessionId, state2, options);
@@ -3436,6 +4336,7 @@ var init_session2 = __esm({
3436
4336
  "use strict";
3437
4337
  init_worlds();
3438
4338
  init_browser();
4339
+ init_browserTools();
3439
4340
  init_nativeComputer();
3440
4341
  init_sessionContract();
3441
4342
  init_toolSchema();
@@ -3501,6 +4402,9 @@ var init_session2 = __esm({
3501
4402
  get versionId() {
3502
4403
  return this.current.versionId;
3503
4404
  }
4405
+ get worldState() {
4406
+ return this.current.worldState ?? null;
4407
+ }
3504
4408
  /** Whether the session answered ready as of the last state read (the open,
3505
4409
  * a `status()`, or the poll inside `ready()`); no request is made. */
3506
4410
  get isReady() {
@@ -3870,6 +4774,7 @@ var init_session2 = __esm({
3870
4774
  "surfaces",
3871
4775
  "browserTier",
3872
4776
  "auth",
4777
+ "worldState",
3873
4778
  "options"
3874
4779
  ]);
3875
4780
  isOpenSessionOptions = (value) => typeof value === "object" && value !== null && Object.keys(value).every((key2) => OPEN_SESSION_OPTION_KEYS.has(key2));
@@ -4113,7 +5018,8 @@ async function openTask(ref, opts = {}) {
4113
5018
  task,
4114
5019
  ...opts.reuseWarm === void 0 ? {} : { reuseWarm: opts.reuseWarm },
4115
5020
  ...opts.surfaces?.length ? { surfaces: opts.surfaces } : {},
4116
- ...opts.browserTier === void 0 ? {} : { browserTier: opts.browserTier }
5021
+ ...opts.browserTier === void 0 ? {} : { browserTier: opts.browserTier },
5022
+ ...opts.worldStates === void 0 ? {} : { worldStates: opts.worldStates }
4117
5023
  }
4118
5024
  );
4119
5025
  return fromResponse(answer, options);
@@ -4371,16 +5277,22 @@ var init_evals = __esm({
4371
5277
  "src/worlds/evals.ts"() {
4372
5278
  "use strict";
4373
5279
  init_worlds();
5280
+ init_personalToken();
5281
+ init_platformEndpoint();
4374
5282
  init_transport();
4375
5283
  EVALUATIONS = "/api/public/benchmark-containers/evaluations";
4376
- GatewayEvalsClient = class {
5284
+ GatewayEvalsClient = class _GatewayEvalsClient {
4377
5285
  constructor(options = {}, retry = RetryPolicy.FILING) {
4378
5286
  this.options = options;
4379
5287
  this.retry = retry;
5288
+ _GatewayEvalsClient.refuseToken(options);
4380
5289
  }
4381
5290
  options;
4382
5291
  retry;
4383
5292
  keyed = /* @__PURE__ */ new Set();
5293
+ static refuseToken(options) {
5294
+ if (platformEndpoint(options)?.token) throw new PersonalTokenRefused(TOKEN_FILING);
5295
+ }
4384
5296
  async createEvaluation(versionId, opts = {}) {
4385
5297
  const body = { versionId };
4386
5298
  if (opts.model !== void 0) body.model = opts.model;
@@ -5063,7 +5975,7 @@ var require_package = __commonJS({
5063
5975
  "package.json"(exports, module) {
5064
5976
  module.exports = {
5065
5977
  name: "@withgateway/sdk",
5066
- version: "0.6.0",
5978
+ version: "0.9.1",
5067
5979
  description: "Gateway SDK for TypeScript - A/B experiments, tracing, and observability",
5068
5980
  main: "./dist/index.js",
5069
5981
  module: "./dist/index.mjs",
@@ -5144,6 +6056,11 @@ var require_package = __commonJS({
5144
6056
  import: "./dist/hooks/index.mjs",
5145
6057
  require: "./dist/hooks/index.js"
5146
6058
  },
6059
+ "./agents": {
6060
+ types: "./dist/agents/index.d.ts",
6061
+ import: "./dist/agents/index.mjs",
6062
+ require: "./dist/agents/index.js"
6063
+ },
5147
6064
  "./cli": {
5148
6065
  types: "./dist/cli.d.ts",
5149
6066
  import: "./dist/cli.mjs",
@@ -5839,6 +6756,7 @@ var init_taskTracing = __esm({
5839
6756
  "use strict";
5840
6757
  init_prerequisites();
5841
6758
  init_platformEndpoint();
6759
+ init_personalToken();
5842
6760
  HOST_WITH_AUTHORITY = /^[a-z][a-z0-9+.-]*:\/\/[^/\\?#@\s]+(\/|$)/i;
5843
6761
  TRACING_HELD_ELSEWHERE = "Tracing in this process already sends spans to another destination or with other keys (an earlier run, or the agent's own tracing.init()), so this run's spans would not reach its own project.";
5844
6762
  TaskTracing = class _TaskTracing {
@@ -5850,8 +6768,9 @@ var init_taskTracing = __esm({
5850
6768
  static target = null;
5851
6769
  async start(requested, options) {
5852
6770
  if (!requested) return false;
5853
- const endpoint = platformEndpoint(options);
6771
+ let endpoint = null;
5854
6772
  try {
6773
+ endpoint = platformEndpoint(options);
5855
6774
  await this.initOnce(_TaskTracing.config(endpoint));
5856
6775
  return true;
5857
6776
  } catch (error) {
@@ -5873,6 +6792,7 @@ var init_taskTracing = __esm({
5873
6792
  }
5874
6793
  static config(endpoint) {
5875
6794
  if (!endpoint) throw new Error(GATEWAY_KEYS_MISSING);
6795
+ if (endpoint.token) throw new Error(TOKEN_KEYS_ONLY);
5876
6796
  return { ...endpoint, endpoint: _TaskTracing.destination(endpoint) };
5877
6797
  }
5878
6798
  // B1: a saved login's keys go to their own host only. The redirect is compared as text, never parsed:
@@ -5903,7 +6823,9 @@ Pass --no-trace (trace: false) to run untraced without this warning.`
5903
6823
  static reason(error, endpoint) {
5904
6824
  if (OpenTelemetryMissing.explains(error)) return new OpenTelemetryMissing().message;
5905
6825
  const message = error instanceof Error ? error.message : String(error);
5906
- const keys = endpoint ? [endpoint.publicKey, endpoint.secretKey] : [];
6826
+ const keys = [endpoint?.publicKey, endpoint?.secretKey, endpoint?.token?.value].filter(
6827
+ (key2) => Boolean(key2)
6828
+ );
5907
6829
  return keys.reduce((text2, key2) => text2.split(key2).join("[redacted]"), message);
5908
6830
  }
5909
6831
  };
@@ -5950,13 +6872,15 @@ async function refuseUnreadTools(live) {
5950
6872
  }
5951
6873
  }
5952
6874
  async function runTask(ref, agent, opts) {
5953
- const runId = `wtr-${randomBytes(6).toString("hex")}`;
5954
6875
  const options = opts.options ?? {};
6876
+ if (opts.file !== false) GatewayEvalsClient.refuseToken(options);
6877
+ const runId = `wtr-${randomBytes(6).toString("hex")}`;
5955
6878
  const opening = new TaskOpening(
5956
6879
  openTask(ref, {
5957
6880
  surfaces: opts.surfaces,
5958
6881
  reuseWarm: opts.reuseWarm,
5959
6882
  browserTier: opts.browserTier,
6883
+ worldStates: opts.worldStates,
5960
6884
  options
5961
6885
  }).then(async (live) => {
5962
6886
  await refuseUnreadTools(live);
@@ -6236,6 +7160,7 @@ var init_checkoutProvenance = __esm({
6236
7160
  // src/worlds/setRun.ts
6237
7161
  async function runSet(datasetId, agent, opts) {
6238
7162
  const options = opts.options ?? {};
7163
+ GatewayEvalsClient.refuseToken(options);
6239
7164
  const git = opts.git === void 0 ? CheckoutProvenance.read() : opts.git;
6240
7165
  const opened = await apiRequest(options, "POST", SET_RUNS, {
6241
7166
  datasetId,
@@ -6251,6 +7176,7 @@ var init_setRun = __esm({
6251
7176
  "use strict";
6252
7177
  init_worlds();
6253
7178
  init_checkoutProvenance();
7179
+ init_evals();
6254
7180
  init_runSignals();
6255
7181
  init_taskRun();
6256
7182
  SET_RUNS = "/api/public/set-runs";
@@ -6638,19 +7564,20 @@ var init_checkoutTarget = __esm({
6638
7564
  import { createHash as createHash4 } from "crypto";
6639
7565
  import * as fs3 from "fs";
6640
7566
  import * as path4 from "path";
6641
- var WORLD_MANIFEST, API_BUNDLE_MANIFEST, BUNDLED_WORLD_PREFIX, CONNECTOR_SPEC, PYPROJECT, BENCHMARK_CONFIG, WORLD_SCHEMA_MARKERS, WORLD_ROOT_MARKERS, BROAD_ROOT_MARKERS, SKIPPED_DIRS, V1_DEP, V1_IMPORT, V1_TASKSET, HARBOR_TASK, skippedDir, byCodePoint, WorldDir;
7567
+ var WORLD_MANIFEST, API_BUNDLE_MANIFEST, BUNDLE_MANIFEST, BUNDLED_WORLD_PREFIX, CONNECTOR_SPEC, PYPROJECT, BENCHMARK_CONFIG, WORLD_SCHEMA_MARKERS, WORLD_ROOT_MARKERS, BROAD_ROOT_MARKERS, SKIPPED_DIRS, V1_DEP, V1_IMPORT, V1_TASKSET, HARBOR_TASK, skippedDir, byCodePoint, WorldDir;
6642
7568
  var init_worldDir = __esm({
6643
7569
  "src/worlds/worldDir.ts"() {
6644
7570
  "use strict";
6645
7571
  WORLD_MANIFEST = "gateway-env.toml";
6646
7572
  API_BUNDLE_MANIFEST = "gateway-api-world.toml";
7573
+ BUNDLE_MANIFEST = "gateway-bundle.toml";
6647
7574
  BUNDLED_WORLD_PREFIX = "server/world/";
6648
7575
  CONNECTOR_SPEC = "connector.toml";
6649
7576
  PYPROJECT = "pyproject.toml";
6650
7577
  BENCHMARK_CONFIG = "benchmark.json";
6651
7578
  WORLD_SCHEMA_MARKERS = ["schema/world.json", "schema/runtime.json", "schema/lock.json"];
6652
7579
  WORLD_ROOT_MARKERS = [CONNECTOR_SPEC, ...WORLD_SCHEMA_MARKERS];
6653
- BROAD_ROOT_MARKERS = [WORLD_MANIFEST, API_BUNDLE_MANIFEST, BENCHMARK_CONFIG];
7580
+ BROAD_ROOT_MARKERS = [WORLD_MANIFEST, API_BUNDLE_MANIFEST, BENCHMARK_CONFIG, BUNDLE_MANIFEST];
6654
7581
  SKIPPED_DIRS = /* @__PURE__ */ new Set(["dist", "build", "outputs", "__pycache__", "node_modules"]);
6655
7582
  V1_DEP = /["']verifiers\s*(?:\[[^\]]*\])?\s*(?:>=|~=|==|>)\s*(?:0\.(?:[2-9]\d*|[1-9]\d+)|[1-9]\d*)/;
6656
7583
  V1_IMPORT = /^\s*(?:from\s+verifiers\.v1\s+import\b|from\s+verifiers\s+import\s+v1\b|import\s+verifiers\.v1\b)/m;
@@ -6671,7 +7598,6 @@ var init_worldDir = __esm({
6671
7598
  const bundled = present(API_BUNDLE_MANIFEST) && WORLD_ROOT_MARKERS.some((m) => present(BUNDLED_WORLD_PREFIX + m));
6672
7599
  return new _WorldDir(dir, bundled ? BUNDLED_WORLD_PREFIX : "");
6673
7600
  }
6674
- // ── Files ──────────────────────────────────────────────────────────────
6675
7601
  has(rel) {
6676
7602
  return fs3.existsSync(path4.join(this.dir, rel));
6677
7603
  }
@@ -6682,15 +7608,9 @@ var init_worldDir = __esm({
6682
7608
  return null;
6683
7609
  }
6684
7610
  }
6685
- /** A path under the authored world's root. */
6686
7611
  worldPath(rel) {
6687
7612
  return this.worldRoot + rel;
6688
7613
  }
6689
- /** Every regular file the archive rules keep (`_archive.py`: no hidden,
6690
- * dist, build, outputs, pycache, node_modules or egg-info directories), as
6691
- * sorted relpaths. Root files enter only when a Gateway manifest or
6692
- * benchmark.json widens the root, or they are README.md, pyproject.toml or
6693
- * Python. */
6694
7614
  get archivePaths() {
6695
7615
  if (this.pathsMemo) return this.pathsMemo;
6696
7616
  const broad = BROAD_ROOT_MARKERS.some((m) => this.has(m));
@@ -6709,11 +7629,6 @@ var init_worldDir = __esm({
6709
7629
  walk("");
6710
7630
  return this.pathsMemo = out.sort(byCodePoint);
6711
7631
  }
6712
- /** What the archive rules leave out, collapsed to the entry that decided
6713
- * it: a pruned directory counts its files once, a dropped root file is
6714
- * named. Dot entries (`.git/`, `.gateway/`, `.gitignore`) are the one
6715
- * universal convention and stay unreported. `push` prints the rest so
6716
- * nothing disappears silently. */
6717
7632
  get exclusions() {
6718
7633
  const kept = new Set(this.archivePaths);
6719
7634
  const out = [];
@@ -6736,14 +7651,11 @@ var init_worldDir = __esm({
6736
7651
  }
6737
7652
  return out;
6738
7653
  }
6739
- /** A root `.gitignore` is present: the Python SDK honours it when
6740
- * collecting, this package does not reimplement gitignore. */
7654
+ /** The Python SDK honours a root `.gitignore` when collecting; this package does not reimplement gitignore. */
6741
7655
  get hasRootGitignore() {
6742
7656
  return this.has(".gitignore");
6743
7657
  }
6744
- /** SHA-256 over `utf8("file:" + relpath)` + bytes per archive path in
6745
- * sorted order: the version's identity, byte-compatible with
6746
- * `_archive.compute_content_hash` and Prime Intellect. */
7658
+ /** The version's identity, byte-compatible with the Python SDK's `compute_content_hash` and Prime Intellect's hub. */
6747
7659
  get contentHash() {
6748
7660
  const hasher = createHash4("sha256");
6749
7661
  for (const rel of this.archivePaths) {
@@ -6752,18 +7664,18 @@ var init_worldDir = __esm({
6752
7664
  }
6753
7665
  return hasher.digest("hex");
6754
7666
  }
6755
- // ── Markers ────────────────────────────────────────────────────────────
6756
7667
  get isApiBundle() {
6757
7668
  return this.has(API_BUNDLE_MANIFEST);
6758
7669
  }
7670
+ get isWorldBundle() {
7671
+ return this.has(BUNDLE_MANIFEST);
7672
+ }
6759
7673
  get hasManifest() {
6760
7674
  return this.has(this.worldPath(WORLD_MANIFEST));
6761
7675
  }
6762
7676
  get hasSchemaMarker() {
6763
7677
  return WORLD_SCHEMA_MARKERS.some((m) => this.has(this.worldPath(m)));
6764
7678
  }
6765
- /** Harbor task dirs, relative to the tree: `tasks/<name>` when a `tasks/`
6766
- * dir holds them, else the root `<name>` dirs. */
6767
7679
  taskDirs() {
6768
7680
  const names = /* @__PURE__ */ new Set();
6769
7681
  for (const rel of this.archivePaths) {
@@ -6773,8 +7685,6 @@ var init_worldDir = __esm({
6773
7685
  const under = [...names].filter((n) => n.startsWith("tasks/"));
6774
7686
  return (under.length ? under : [...names]).sort();
6775
7687
  }
6776
- /** The Python package of a verifiers tree (`<pkg>/__init__.py` or
6777
- * `src/<pkg>/__init__.py`), or null. */
6778
7688
  pythonPackage() {
6779
7689
  if (!this.has(PYPROJECT)) return null;
6780
7690
  for (const base of ["", "src/"]) {
@@ -6786,8 +7696,6 @@ var init_worldDir = __esm({
6786
7696
  }
6787
7697
  return null;
6788
7698
  }
6789
- /** The package targets the `verifiers.v1` API: read from the root
6790
- * pyproject and every archived Python module. */
6791
7699
  get isVerifiersV1() {
6792
7700
  for (const rel of this.archivePaths) {
6793
7701
  if (rel !== PYPROJECT && !rel.endsWith(".py")) continue;
@@ -6798,11 +7706,9 @@ var init_worldDir = __esm({
6798
7706
  }
6799
7707
  return false;
6800
7708
  }
6801
- // ── The answer ─────────────────────────────────────────────────────────
6802
- /** The runner's kind (`detect_env_kind`): api / mock-tools win over
6803
- * everything, a harbor task tree next, then the verifiers API version. */
6804
7709
  get kind() {
6805
7710
  if (this.isApiBundle) return "api";
7711
+ if (this.isWorldBundle) return "bundle";
6806
7712
  if (this.has(WORLD_MANIFEST)) return "mock-tools";
6807
7713
  if (this.taskDirs().length) return "harbor";
6808
7714
  return this.isVerifiersV1 ? "verifiers-v1" : "verifiers";
@@ -7144,8 +8050,7 @@ async function push(dir, opts = {}) {
7144
8050
  const metadata = {
7145
8051
  ...opts.name !== void 0 ? { name: opts.name } : {},
7146
8052
  ...opts.description !== void 0 ? { description: opts.description } : {},
7147
- ...opts.tags !== void 0 ? { tags: opts.tags } : {},
7148
- ...opts.visibility ? { visibility: opts.visibility } : {}
8053
+ ...opts.tags !== void 0 ? { tags: opts.tags } : {}
7149
8054
  };
7150
8055
  const resolve11 = await apiRequest(
7151
8056
  options,
@@ -7673,7 +8578,7 @@ var init_sandbox = __esm({
7673
8578
  /**
7674
8579
  * `{ slug, ref? }` opens a READY version; `{ new, from }` opens a sandbox on
7675
8580
  * a world that does not exist yet (409 `world_exists` if the slug is taken,
7676
- * 400 naming the shipped templates if `from` is unknown). Its first commit
8581
+ * 400 naming the official templates if `from` is unknown). Its first commit
7677
8582
  * creates the world on `main`.
7678
8583
  */
7679
8584
  open(target) {
@@ -8318,6 +9223,7 @@ var CliError;
8318
9223
  var init_router = __esm({
8319
9224
  "src/cli/router.ts"() {
8320
9225
  "use strict";
9226
+ init_personalToken();
8321
9227
  CliError = class extends Error {
8322
9228
  constructor(message, exitCode = 2) {
8323
9229
  super(message);
@@ -8332,18 +9238,62 @@ var init_router = __esm({
8332
9238
  import * as fs6 from "fs";
8333
9239
  import * as os from "os";
8334
9240
  import * as path7 from "path";
9241
+ function configPath() {
9242
+ return path7.join(process.env.GATEWAY_CONFIG_DIR || path7.join(os.homedir(), ".gateway"), "config.json");
9243
+ }
9244
+ function readConfig() {
9245
+ let stored;
9246
+ try {
9247
+ stored = JSON.parse(fs6.readFileSync(configPath(), "utf8"));
9248
+ } catch {
9249
+ return {};
9250
+ }
9251
+ const record = stored ?? {};
9252
+ return Object.fromEntries(STORED_FIELDS.filter((f) => typeof record[f] === "string").map((f) => [f, record[f]]));
9253
+ }
9254
+ function personalToken(request = {}) {
9255
+ try {
9256
+ return PersonalToken.fromEnv(process.env, request);
9257
+ } catch (error) {
9258
+ if (error instanceof PersonalTokenRefused) throw new CliError(error.message);
9259
+ throw error;
9260
+ }
9261
+ }
9262
+ function resolveCredentials(hostFlag, secretKeyFlag) {
9263
+ const token = personalToken({ host: hostFlag || void 0, keys: Boolean(secretKeyFlag) });
9264
+ if (token) return { host: token.host, publicKey: "", secretKey: "", token };
9265
+ const stored = readConfig();
9266
+ const explicitHost = (hostFlag || process.env.GATEWAY_HOST || "").replace(/\/+$/, "");
9267
+ const host = explicitHost || (stored.host ?? "").replace(/\/+$/, "");
9268
+ if (!host)
9269
+ throw new CredentialsMissing(
9270
+ "Host not configured. Pass --host, set GATEWAY_HOST, or run `gateway auth login`."
9271
+ );
9272
+ const login = host === (stored.host ?? "").replace(/\/+$/, "") ? stored : {};
9273
+ const publicKey = process.env.GATEWAY_PUBLIC_KEY || login.public_key || "";
9274
+ const secretKey = secretKeyFlag || process.env.GATEWAY_SECRET_KEY || process.env.GATEWAY_API_KEY || login.api_key || "";
9275
+ if (!publicKey || !secretKey)
9276
+ throw new CredentialsMissing(
9277
+ "API key not configured. Set GATEWAY_PUBLIC_KEY and GATEWAY_SECRET_KEY, or run `gateway auth login`."
9278
+ );
9279
+ return { host, publicKey, secretKey };
9280
+ }
8335
9281
  async function api(creds, method, route2, body, init3 = {}) {
8336
9282
  const reply = await new PlatformTransport(creds).send(method, route2, body, init3);
8337
9283
  if (!reply.ok) throw new ApiError2(reply.status, method, route2, reply.text);
8338
9284
  return reply.text ? JSON.parse(reply.text) : {};
8339
9285
  }
8340
- var ApiError2;
9286
+ var STORED_FIELDS, CredentialsMissing, ApiError2;
8341
9287
  var init_config = __esm({
8342
9288
  "src/cli/config.ts"() {
8343
9289
  "use strict";
8344
9290
  init_router();
8345
9291
  init_worlds();
9292
+ init_personalToken();
8346
9293
  init_transport();
9294
+ STORED_FIELDS = ["host", "public_key", "api_key"];
9295
+ CredentialsMissing = class extends CliError {
9296
+ };
8347
9297
  ApiError2 = class extends CliError {
8348
9298
  constructor(status, method, route2, text2) {
8349
9299
  const body = parseErrorBody(text2, status);
@@ -8363,8 +9313,37 @@ var init_config = __esm({
8363
9313
  }
8364
9314
  });
8365
9315
 
9316
+ // src/worlds/isolatedPython.ts
9317
+ import { spawnSync } from "child_process";
9318
+ function isolatedPython(python, args, timeout) {
9319
+ return spawnSync(python, ["-I", ...args], { encoding: "utf8", timeout, env: PersonalToken.scrubbed(process.env) });
9320
+ }
9321
+ var init_isolatedPython = __esm({
9322
+ "src/worlds/isolatedPython.ts"() {
9323
+ "use strict";
9324
+ init_personalToken();
9325
+ }
9326
+ });
9327
+
8366
9328
  // src/cli/runtime/local.ts
8367
- import { spawn, spawnSync } from "child_process";
9329
+ var local_exports = {};
9330
+ __export(local_exports, {
9331
+ MIN_PYTHON_LABEL: () => MIN_PYTHON_LABEL,
9332
+ assertPortFree: () => assertPortFree,
9333
+ credentialsForRuntime: () => credentialsForRuntime,
9334
+ findPython: () => findPython,
9335
+ localBridge: () => localBridge,
9336
+ localModule: () => localModule,
9337
+ localPythonHasYaml: () => localPythonHasYaml,
9338
+ localRuntime: () => localRuntime,
9339
+ localRuntimeReason: () => localRuntimeReason,
9340
+ portOwner: () => portOwner,
9341
+ pythonAdvice: () => pythonAdvice,
9342
+ resetPythonCache: () => resetPythonCache,
9343
+ runtimeMode: () => runtimeMode,
9344
+ runtimeRoot: () => runtimeRoot
9345
+ });
9346
+ import { spawn, spawnSync as spawnSync2 } from "child_process";
8368
9347
  import * as fs7 from "fs";
8369
9348
  import * as net from "net";
8370
9349
  import * as path8 from "path";
@@ -8404,12 +9383,12 @@ function runtimeRoot() {
8404
9383
  return root;
8405
9384
  return null;
8406
9385
  }
9386
+ function resetPythonCache() {
9387
+ pythonCache = void 0;
9388
+ pythonProbes = [];
9389
+ }
8407
9390
  function probeVersion(name) {
8408
- const probe = spawnSync(
8409
- name,
8410
- ["-c", "import sys;print(sys.version_info[0],sys.version_info[1])"],
8411
- { encoding: "utf8", timeout: 1e4 }
8412
- );
9391
+ const probe = isolatedPython(name, ["-c", "import sys;print(sys.version_info[0],sys.version_info[1])"], 1e4);
8413
9392
  if (probe.status !== 0) return null;
8414
9393
  const [major, minor] = probe.stdout.trim().split(/\s+/).map(Number);
8415
9394
  return Number.isInteger(major) && Number.isInteger(minor) ? `${major}.${minor}` : null;
@@ -8419,7 +9398,7 @@ function atLeastMinimum(version) {
8419
9398
  return major > MIN_PYTHON[0] || major === MIN_PYTHON[0] && minor >= MIN_PYTHON[1];
8420
9399
  }
8421
9400
  function uvPython() {
8422
- const found = spawnSync("uv", UV_FIND, { encoding: "utf8", timeout: 1e4 });
9401
+ const found = spawnSync2("uv", UV_FIND, { encoding: "utf8", timeout: 1e4, env: PersonalToken.scrubbed(process.env) });
8423
9402
  if (found.status !== 0) return null;
8424
9403
  const line = found.stdout.trim().split(/\r?\n/)[0] ?? "";
8425
9404
  return line || null;
@@ -8478,7 +9457,7 @@ function localRuntime() {
8478
9457
  return { python, root };
8479
9458
  }
8480
9459
  function localPythonHasYaml(python) {
8481
- return spawnSync(python, ["-c", "import yaml"], { timeout: 1e4 }).status === 0;
9460
+ return isolatedPython(python, ["-c", "import yaml"], 1e4).status === 0;
8482
9461
  }
8483
9462
  async function localBridge(request, local, opts = {}) {
8484
9463
  const input = JSON.stringify(request);
@@ -8539,12 +9518,88 @@ async function localBridge(request, local, opts = {}) {
8539
9518
  child.stdin.end(input);
8540
9519
  });
8541
9520
  }
8542
- var MIN_PYTHON, MIN_PYTHON_LABEL, DIAGNOSTIC_TAIL, FORWARDED_ENV, BRIDGE_BOOTSTRAP, pythonCache, pythonProbes, PYTHON_CANDIDATES, UV_FIND;
9521
+ function portOwner(port) {
9522
+ const found = spawnSync2("lsof", ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN", "-Fpc"], {
9523
+ encoding: "utf8",
9524
+ timeout: 5e3
9525
+ });
9526
+ if (found.error || found.status !== 0) return null;
9527
+ let pid = null;
9528
+ let command2 = null;
9529
+ for (const line of found.stdout.split("\n")) {
9530
+ if (line.startsWith("p") && pid === null) pid = line.slice(1);
9531
+ else if (line.startsWith("c") && pid !== null && command2 === null) command2 = line.slice(1);
9532
+ }
9533
+ if (pid === null) return null;
9534
+ return `pid ${pid}${command2 ? ` (${command2})` : ""}`;
9535
+ }
9536
+ async function assertPortFree(port, host = "127.0.0.1") {
9537
+ const taken = await new Promise((resolve11) => {
9538
+ const probe = net.createServer();
9539
+ probe.once("error", () => resolve11(true));
9540
+ probe.listen(port, host, () => probe.close(() => resolve11(false)));
9541
+ });
9542
+ if (!taken) return;
9543
+ const owner = portOwner(port);
9544
+ throw new CliError(
9545
+ `port ${port} on ${host} is already in use${owner ? ` by ${owner}` : ""}; nothing was served there \u2014 pass another --port, or stop that server first`,
9546
+ 1
9547
+ );
9548
+ }
9549
+ async function localModule(argv, local, opts = {}) {
9550
+ return await new Promise((resolve11, reject) => {
9551
+ const child = spawn(
9552
+ local.python,
9553
+ ["-B", "-c", MODULE_BOOTSTRAP, local.root, ...argv],
9554
+ {
9555
+ stdio: "inherit",
9556
+ cwd: opts.cwd,
9557
+ env: { ...PersonalToken.scrubbed(process.env), ...opts.env }
9558
+ }
9559
+ );
9560
+ const forward = (signal) => () => {
9561
+ if (child.exitCode === null && child.signalCode === null) child.kill(signal);
9562
+ };
9563
+ const handlers = [
9564
+ ["SIGINT", forward("SIGINT")],
9565
+ ["SIGTERM", forward("SIGTERM")],
9566
+ ["SIGHUP", forward("SIGHUP")]
9567
+ ];
9568
+ for (const [signal, handler] of handlers) process.on(signal, handler);
9569
+ const release = () => {
9570
+ for (const [signal, handler] of handlers) process.off(signal, handler);
9571
+ };
9572
+ child.on("error", (error) => {
9573
+ release();
9574
+ reject(
9575
+ new CliError(
9576
+ `local runtime could not start (${local.python}): ${error.message}`,
9577
+ 1
9578
+ )
9579
+ );
9580
+ });
9581
+ child.on("close", (code, signal) => {
9582
+ release();
9583
+ resolve11(code ?? (signal ? 130 : 1));
9584
+ });
9585
+ });
9586
+ }
9587
+ function credentialsForRuntime(hostFlag) {
9588
+ try {
9589
+ return resolveCredentials(hostFlag);
9590
+ } catch (error) {
9591
+ if (error instanceof CliError && localRuntime()) return null;
9592
+ throw error;
9593
+ }
9594
+ }
9595
+ var MIN_PYTHON, MIN_PYTHON_LABEL, DIAGNOSTIC_TAIL, FORWARDED_ENV, BRIDGE_BOOTSTRAP, MODULE_BOOTSTRAP, pythonCache, pythonProbes, PYTHON_CANDIDATES, UV_FIND;
8543
9596
  var init_local = __esm({
8544
9597
  "src/cli/runtime/local.ts"() {
8545
9598
  "use strict";
8546
9599
  init_router();
8547
9600
  init_config();
9601
+ init_isolatedPython();
9602
+ init_personalToken();
8548
9603
  MIN_PYTHON = [3, 12];
8549
9604
  MIN_PYTHON_LABEL = MIN_PYTHON.join(".");
8550
9605
  DIAGNOSTIC_TAIL = 600;
@@ -8555,6 +9610,13 @@ package=types.ModuleType('gatewaysdk')
8555
9610
  package.__path__=[os.path.join(root,'gatewaysdk')]
8556
9611
  sys.modules['gatewaysdk']=package
8557
9612
  runpy.run_module('gatewaysdk.environment.schema.platform',run_name='__main__')`;
9613
+ MODULE_BOOTSTRAP = `import sys,runpy,types,os
9614
+ root=sys.argv[1]
9615
+ package=types.ModuleType('gatewaysdk')
9616
+ package.__path__=[os.path.join(root,'gatewaysdk')]
9617
+ sys.modules['gatewaysdk']=package
9618
+ sys.argv=['gateway worlds']+sys.argv[2:]
9619
+ runpy.run_module('gatewaysdk.environment.schema',run_name='__main__')`;
8558
9620
  pythonProbes = [];
8559
9621
  PYTHON_CANDIDATES = [
8560
9622
  "python3.13",
@@ -9606,9 +10668,9 @@ async function emit(sink, record) {
9606
10668
  }
9607
10669
  throw new TypeError("sink must be an array, a file path, or a function");
9608
10670
  }
9609
- function captureToolCalls(tools, sink, opts = {}) {
10671
+ function captureToolCalls(tools2, sink, opts = {}) {
9610
10672
  const wrapped = /* @__PURE__ */ Object.create(null);
9611
- for (const [name, fn] of Object.entries(tools)) {
10673
+ for (const [name, fn] of Object.entries(tools2)) {
9612
10674
  wrapped[name] = async (args = {}) => {
9613
10675
  const record = { tool: name, args, at: (/* @__PURE__ */ new Date()).toISOString() };
9614
10676
  if (opts.session) record.session = opts.session;
@@ -9664,14 +10726,23 @@ function toolCallsFromObservations(observations, opts = {}) {
9664
10726
  }
9665
10727
  return out;
9666
10728
  }
10729
+ async function runtimeEndpoint(options) {
10730
+ try {
10731
+ return platformEndpoint(options);
10732
+ } catch (error) {
10733
+ const { localRuntime: localRuntime2 } = await Promise.resolve().then(() => (init_local(), local_exports));
10734
+ if (error instanceof PersonalTokenRefused && localRuntime2()) return null;
10735
+ throw error;
10736
+ }
10737
+ }
9667
10738
  async function ingest(world, records, options = {}) {
9668
10739
  const { ingestLocalToolCalls: ingestLocalToolCalls2, importLocalWorldData: importLocalWorldData2, checkLocalWorldData: checkLocalWorldData2 } = await Promise.resolve().then(() => (init_data(), data_exports));
9669
10740
  if (options.transform !== void 0 && options.map !== void 0) throw new Error("records go through one of transform, map");
9670
10741
  const redact = options.redact ?? "off";
9671
10742
  const mode = options.mode ?? "append";
9672
10743
  const dryRun = Boolean(options.dryRun);
9673
- const creds = platformEndpoint(options);
9674
10744
  const local = fs12.existsSync(world) && fs12.statSync(world).isDirectory();
10745
+ const creds = local ? await runtimeEndpoint(options) : platformEndpoint(options);
9675
10746
  const map = options.map === void 0 ? void 0 : options.map;
9676
10747
  let rows = null;
9677
10748
  let stderr = "";
@@ -9769,6 +10840,7 @@ var init_ingest = __esm({
9769
10840
  "use strict";
9770
10841
  init_worlds();
9771
10842
  init_platformEndpoint();
10843
+ init_personalToken();
9772
10844
  isObject2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
9773
10845
  isoOf = (value) => value instanceof Date ? value.toISOString() : typeof value === "string" ? value : void 0;
9774
10846
  }
@@ -9826,6 +10898,38 @@ var init_editSessions = __esm({
9826
10898
  }
9827
10899
  });
9828
10900
 
10901
+ // src/worlds/states.ts
10902
+ var WORLDS3, refQuery, WorldStateClient;
10903
+ var init_states = __esm({
10904
+ "src/worlds/states.ts"() {
10905
+ "use strict";
10906
+ init_worlds();
10907
+ WORLDS3 = "/api/public/worlds";
10908
+ refQuery = (ref) => ref ? `?${new URLSearchParams({ ref })}` : "";
10909
+ WorldStateClient = class {
10910
+ constructor(options = {}) {
10911
+ this.options = options;
10912
+ }
10913
+ options;
10914
+ list(slug) {
10915
+ return apiRequest(this.options, "GET", `${WORLDS3}/${encodeURIComponent(slug)}/states`);
10916
+ }
10917
+ show(slug, name, ref) {
10918
+ return apiRequest(this.options, "GET", `${WORLDS3}/${encodeURIComponent(slug)}/states/${encodeURIComponent(name)}` + refQuery(ref));
10919
+ }
10920
+ create(slug, input) {
10921
+ return apiRequest(this.options, "POST", `${WORLDS3}/${encodeURIComponent(slug)}/states`, input);
10922
+ }
10923
+ delete(slug, name) {
10924
+ return apiRequest(this.options, "DELETE", `${WORLDS3}/${encodeURIComponent(slug)}/states/${encodeURIComponent(name)}`);
10925
+ }
10926
+ pull(slug, name, ref) {
10927
+ return apiRequest(this.options, "GET", `${WORLDS3}/${encodeURIComponent(slug)}/states/${encodeURIComponent(name)}/pull` + refQuery(ref));
10928
+ }
10929
+ };
10930
+ }
10931
+ });
10932
+
9829
10933
  // src/worlds/dryRun.ts
9830
10934
  var DRY_RUN_KIND, DRY_RUN_AGENT, STATUS_WAIT_CAP_SECONDS, cid, HostedDryRunClient, DryRunOutcome;
9831
10935
  var init_dryRun = __esm({
@@ -9959,9 +11063,14 @@ __export(worlds_exports, {
9959
11063
  OpenAIComputer: () => OpenAIComputer,
9960
11064
  OpenAIPreviewComputer: () => OpenAIPreviewComputer,
9961
11065
  PLATFORM_SESSION_HEADER: () => PLATFORM_SESSION_HEADER,
11066
+ PLATFORM_STREAM_IDLE_MS: () => PLATFORM_STREAM_IDLE_MS,
9962
11067
  PLATFORM_TIMEOUT_DEFAULT_MS: () => PLATFORM_TIMEOUT_DEFAULT_MS,
9963
11068
  PLATFORM_TIMEOUT_ENV: () => PLATFORM_TIMEOUT_ENV,
11069
+ PageObserver: () => PageObserver,
11070
+ PageState: () => PageState,
11071
+ PageStateError: () => PageStateError,
9964
11072
  PendingSafetyChecks: () => PendingSafetyChecks,
11073
+ PlatformStream: () => PlatformStream,
9965
11074
  PlatformTransport: () => PlatformTransport,
9966
11075
  PushSlugConflict: () => PushSlugConflict,
9967
11076
  RECOVER_BUDGET_MS: () => RECOVER_BUDGET_MS,
@@ -10014,6 +11123,7 @@ __export(worlds_exports, {
10014
11123
  WorldSessionOpenFailed: () => WorldSessionOpenFailed,
10015
11124
  WorldSessionTimeout: () => WorldSessionTimeout,
10016
11125
  WorldSet: () => WorldSet,
11126
+ WorldStateClient: () => WorldStateClient,
10017
11127
  WorldSurfaceUnavailable: () => WorldSurfaceUnavailable,
10018
11128
  WorldTask: () => WorldTask,
10019
11129
  WorldToolsUnread: () => WorldToolsUnread,
@@ -10081,6 +11191,7 @@ __export(worlds_exports, {
10081
11191
  parseToolCallRecord: () => parseToolCallRecord,
10082
11192
  parseTransform: () => parseTransform,
10083
11193
  parseWorldTaskRefs: () => parseWorldTaskRefs,
11194
+ platformAuthorization: () => platformAuthorization,
10084
11195
  platformTimeoutMs: () => platformTimeoutMs,
10085
11196
  playwrightKey: () => playwrightKey,
10086
11197
  preserveForm: () => preserveForm,
@@ -10107,6 +11218,7 @@ __export(worlds_exports, {
10107
11218
  runSet: () => runSet,
10108
11219
  runTask: () => runTask,
10109
11220
  schemaFromSignature: () => schemaFromSignature,
11221
+ scrubError: () => scrubError,
10110
11222
  serializeCallBody: () => serializeCallBody,
10111
11223
  sessionToolObservations: () => sessionToolObservations,
10112
11224
  setEnvSecret: () => setEnvSecret,
@@ -10134,43 +11246,8 @@ __export(worlds_exports, {
10134
11246
  worldRequestsUnrecorded: () => worldRequestsUnrecorded,
10135
11247
  writeLocalMeta: () => writeLocalMeta
10136
11248
  });
10137
- function edgeAnswer(text2, status) {
10138
- if (status !== void 0 && status >= 500) return EDGE_ANSWERS[status] ?? EDGE_FAILURE;
10139
- return /^\s*</.test(text2) ? EDGE_PAGE : null;
10140
- }
10141
- function parseErrorBody(text2, status) {
10142
- const raw = { detail: text2.slice(0, DETAIL_LIMIT), code: null };
10143
- let parsed;
10144
- try {
10145
- parsed = JSON.parse(text2);
10146
- } catch {
10147
- return { detail: (edgeAnswer(text2, status) ?? text2).slice(0, DETAIL_LIMIT), code: null };
10148
- }
10149
- if (parsed === null || typeof parsed !== "object") return raw;
10150
- const { message, code, error } = parsed;
10151
- const stableCode = typeof code === "string" ? code : null;
10152
- if (typeof message !== "string") return { ...raw, code: stableCode };
10153
- const fields = invalidFields(error);
10154
- const said = fields ? `${message}: ${fields}` : message;
10155
- if (stableCode === null) return { detail: said.slice(0, DETAIL_LIMIT), code: null };
10156
- return {
10157
- detail: `${said} (${stableCode})`.slice(0, DETAIL_LIMIT),
10158
- code: stableCode
10159
- };
10160
- }
10161
- function invalidFields(error) {
10162
- const issues = Array.isArray(error) ? error : [];
10163
- return issues.filter(
10164
- (issue) => issue !== null && typeof issue === "object" && typeof issue.message === "string"
10165
- ).map((issue) => {
10166
- const path17 = Array.isArray(issue.path) ? issue.path.map(String).join(".") : "";
10167
- return path17 ? `${path17}: ${issue.message}` : issue.message;
10168
- }).join("; ");
10169
- }
10170
11249
  async function apiRequest(options, method, path17, body, init3 = {}) {
10171
- const reply = await new PlatformTransport(requirePlatformEndpoint(options)).send(method, path17, body, init3);
10172
- if (!reply.ok) throw new ApiError(reply.status, method, path17, reply.text);
10173
- return JSON.parse(reply.text);
11250
+ return new PlatformTransport(requirePlatformEndpoint(options)).json(method, path17, body, init3);
10174
11251
  }
10175
11252
  async function setEnvSecret(slug, key2, value, options = {}) {
10176
11253
  return apiRequest(
@@ -10345,12 +11422,13 @@ async function resolveWorld(slugRef, slug, ref, pin, options) {
10345
11422
  }
10346
11423
  return world;
10347
11424
  }
10348
- var ApiError, DETAIL_LIMIT, EDGE_ANSWERS, EDGE_FAILURE, EDGE_PAGE, WorldTask, WorldSet;
11425
+ var WorldTask, WorldSet;
10349
11426
  var init_worlds = __esm({
10350
11427
  "src/worlds/index.ts"() {
10351
11428
  "use strict";
10352
11429
  init_platformEndpoint();
10353
11430
  init_transport();
11431
+ init_apiError();
10354
11432
  init_transport();
10355
11433
  init_session2();
10356
11434
  init_grade();
@@ -10365,6 +11443,8 @@ var init_worlds = __esm({
10365
11443
  init_checkoutProvenance();
10366
11444
  init_evals();
10367
11445
  init_browser();
11446
+ init_browserTools();
11447
+ init_pageState();
10368
11448
  init_surfaceDescriptor();
10369
11449
  init_requestLog();
10370
11450
  init_requestLedger();
@@ -10376,34 +11456,14 @@ var init_worlds = __esm({
10376
11456
  init_describe();
10377
11457
  init_redaction();
10378
11458
  init_transforms();
10379
- init_query();
10380
- init_migrate();
10381
- init_ingest();
10382
- init_sandbox();
10383
- init_editSessions();
10384
- init_dryRun();
10385
- init_worldNotice();
10386
- ApiError = class extends Error {
10387
- constructor(status, method, path17, text2) {
10388
- const parsed = parseErrorBody(text2, status);
10389
- super(`${method} ${path17} -> ${status}: ${parsed.detail}`);
10390
- this.status = status;
10391
- this.text = text2;
10392
- this.name = "ApiError";
10393
- this.code = parsed.code;
10394
- }
10395
- status;
10396
- text;
10397
- code;
10398
- };
10399
- DETAIL_LIMIT = 600;
10400
- EDGE_ANSWERS = {
10401
- 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.",
10402
- 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.",
10403
- 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."
10404
- };
10405
- 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.";
10406
- EDGE_PAGE = "An HTML page answered instead of the platform's JSON: a proxy in front of the platform, or the configured host is not the platform.";
11459
+ init_query();
11460
+ init_migrate();
11461
+ init_ingest();
11462
+ init_sandbox();
11463
+ init_editSessions();
11464
+ init_states();
11465
+ init_dryRun();
11466
+ init_worldNotice();
10407
11467
  WorldTask = class {
10408
11468
  constructor(world, name, variant) {
10409
11469
  this.world = world;
@@ -12864,6 +13924,961 @@ init_scores();
12864
13924
  init_worlds();
12865
13925
  init_session2();
12866
13926
 
13927
+ // src/agents/agent.ts
13928
+ init_apiError();
13929
+
13930
+ // src/agents/patch.ts
13931
+ var list = (value) => Array.isArray(value) ? value : [value];
13932
+ function grantOf(input) {
13933
+ if (typeof input === "string") return { server: input };
13934
+ return input.only ? { server: input.server, only: [...input.only].sort() } : { server: input.server };
13935
+ }
13936
+ var AgentPatch = class _AgentPatch {
13937
+ constructor(json) {
13938
+ this.json = json;
13939
+ }
13940
+ json;
13941
+ static update(fields) {
13942
+ const set = Object.fromEntries(Object.entries(fields).filter(([, value]) => value !== void 0));
13943
+ return new _AgentPatch({ set });
13944
+ }
13945
+ static attach(grants) {
13946
+ return new _AgentPatch({ attach: list(grants).map(grantOf) });
13947
+ }
13948
+ static detach(servers) {
13949
+ return new _AgentPatch({ detach: [...list(servers)] });
13950
+ }
13951
+ toJSON() {
13952
+ return structuredClone(this.json);
13953
+ }
13954
+ };
13955
+
13956
+ // src/agents/agent.ts
13957
+ var AgentVersionConflictError = class extends ApiError {
13958
+ currentVersionId;
13959
+ constructor(status, method, path17, text2) {
13960
+ super(status, method, path17, text2);
13961
+ this.name = "AgentVersionConflictError";
13962
+ this.currentVersionId = currentVersionOf(text2);
13963
+ }
13964
+ };
13965
+ function currentVersionOf(text2) {
13966
+ try {
13967
+ const id = JSON.parse(text2).currentVersionId;
13968
+ return typeof id === "string" ? id : null;
13969
+ } catch {
13970
+ return null;
13971
+ }
13972
+ }
13973
+ var AgentTools = class {
13974
+ constructor(agent) {
13975
+ this.agent = agent;
13976
+ }
13977
+ agent;
13978
+ /** Grant servers: one already attached keeps its place and takes the new grant. */
13979
+ attach(grants, options = {}) {
13980
+ return this.agent.edit(AgentPatch.attach(grants), options);
13981
+ }
13982
+ /** Remove servers; one that is not attached changes nothing. */
13983
+ detach(servers, options = {}) {
13984
+ return this.agent.edit(AgentPatch.detach(servers), options);
13985
+ }
13986
+ };
13987
+ var AgentThreads = class {
13988
+ constructor(threads, name) {
13989
+ this.threads = threads;
13990
+ this.name = name;
13991
+ }
13992
+ threads;
13993
+ name;
13994
+ create(options = {}) {
13995
+ return this.threads.create({ ...options, agent: this.name });
13996
+ }
13997
+ };
13998
+ var Agent = class {
13999
+ #agents;
14000
+ #record;
14001
+ tools;
14002
+ threads;
14003
+ constructor(agents, record, threads) {
14004
+ this.#agents = agents;
14005
+ this.#record = liveOf(record);
14006
+ this.tools = new AgentTools(this);
14007
+ this.threads = new AgentThreads(threads, record.name);
14008
+ }
14009
+ get name() {
14010
+ return this.#record.name;
14011
+ }
14012
+ /** The version edits apply to: the one `production` runs (else, never deployed, the newest). */
14013
+ get versionId() {
14014
+ return this.#record.versionId;
14015
+ }
14016
+ get version() {
14017
+ return this.#record.version;
14018
+ }
14019
+ get buildHash() {
14020
+ return this.#record.buildHash;
14021
+ }
14022
+ get deployed() {
14023
+ return this.#record.deployed;
14024
+ }
14025
+ get definition() {
14026
+ return structuredClone(this.#record.definition);
14027
+ }
14028
+ /** Change fields: a new version, live unless `deploy: false`; a change to the values it already has writes nothing. */
14029
+ update(fields, options = {}) {
14030
+ return this.edit(AgentPatch.update(fields), options);
14031
+ }
14032
+ /** Apply one patch made of `AgentPatch.update`, `.attach` or `.detach`. */
14033
+ async edit(patch, options = {}) {
14034
+ const result = await this.#agents.edit(this.name, patch, { ...options, from: this.versionId });
14035
+ if (result.deployed || !this.deployed) this.#record = liveOf(result);
14036
+ return result;
14037
+ }
14038
+ /** Move `production` to one of this agent's versions (an earlier one, or one staged with `deploy: false`); `force` crosses a breaking tool change. */
14039
+ async rollback(versionId, options = {}) {
14040
+ this.#record = liveOf(await this.#agents.rollback(this.name, versionId, { ...options, from: this.versionId }));
14041
+ return this.toJSON();
14042
+ }
14043
+ /** Every version, newest first, with whether it is live and its changes against the version before it. */
14044
+ versions() {
14045
+ return this.#agents.history(this.name);
14046
+ }
14047
+ /** Read the live version again, after a conflict or someone else's change. */
14048
+ async refresh() {
14049
+ this.#record = liveOf(await this.#agents.live(this.name));
14050
+ return this;
14051
+ }
14052
+ /** Start a thread with this agent and send it `input`: the run uses the version `production` runs now (or `version`). */
14053
+ async run(input, options = {}) {
14054
+ const { version, ...thread } = options;
14055
+ return (await this.threads.create(thread)).send(input, { version });
14056
+ }
14057
+ toJSON() {
14058
+ return { ...this.#record, definition: this.definition };
14059
+ }
14060
+ };
14061
+ function liveOf(record) {
14062
+ const { name, versionId, version, buildHash, deployed, definition: definition2 } = record;
14063
+ return { name, versionId, version, buildHash, deployed, definition: definition2 };
14064
+ }
14065
+
14066
+ // src/agents/definition.ts
14067
+ var NAME_PATTERN = /^[a-z0-9][a-z0-9-]{0,62}$/;
14068
+ var DEFAULT_MODEL = "claude-opus-5";
14069
+ var DEFAULT_MAX_TURNS = 50;
14070
+ var INSTRUCTIONS = { min: 1, max: 65536 };
14071
+ var MAX_TURNS = { min: 1, max: 200 };
14072
+ var DEFINITION_FIELDS = /* @__PURE__ */ new Set([
14073
+ "name",
14074
+ "instructions",
14075
+ "model",
14076
+ "effort",
14077
+ "maxTurns",
14078
+ "tools"
14079
+ ]);
14080
+ var GRANT_FIELDS = /* @__PURE__ */ new Set(["server", "only"]);
14081
+ var AgentDefinitionError = class extends Error {
14082
+ constructor(issues) {
14083
+ super(`Invalid agent definition: ${issues.map((issue) => `${pathText(issue.path)}: ${issue.message}`).join("; ")}`);
14084
+ this.issues = issues;
14085
+ this.name = "AgentDefinitionError";
14086
+ }
14087
+ issues;
14088
+ };
14089
+ var AgentDefinition = class _AgentDefinition {
14090
+ name;
14091
+ instructions;
14092
+ model;
14093
+ effort;
14094
+ maxTurns;
14095
+ tools;
14096
+ constructor(spec) {
14097
+ this.name = spec.name;
14098
+ this.instructions = spec.instructions;
14099
+ this.model = spec.model;
14100
+ this.effort = spec.effort;
14101
+ this.maxTurns = spec.maxTurns;
14102
+ this.tools = Object.freeze(spec.tools.map(freezeGrant));
14103
+ Object.freeze(this);
14104
+ }
14105
+ /** Validate and normalize any value (a parsed JSON file included); throws `AgentDefinitionError` listing every broken rule. */
14106
+ static from(input) {
14107
+ return new _AgentDefinition(DefinitionReader.read(input));
14108
+ }
14109
+ /** The normalized definition: defaults filled, tool shorthands expanded, `only` sorted, `effort` present only when set. */
14110
+ toJSON() {
14111
+ return {
14112
+ name: this.name,
14113
+ instructions: this.instructions,
14114
+ model: this.model,
14115
+ ...this.effort === void 0 ? {} : { effort: this.effort },
14116
+ maxTurns: this.maxTurns,
14117
+ tools: this.tools.map(
14118
+ (grant2) => grant2.only ? { server: grant2.server, only: [...grant2.only] } : { server: grant2.server }
14119
+ )
14120
+ };
14121
+ }
14122
+ };
14123
+ function defineAgent(input) {
14124
+ return AgentDefinition.from(input);
14125
+ }
14126
+ function freezeGrant(grant2) {
14127
+ const only = grant2.only ? { only: Object.freeze([...grant2.only]) } : {};
14128
+ return Object.freeze({ server: grant2.server, ...only });
14129
+ }
14130
+ function pathText(path17) {
14131
+ return path17.length === 0 ? "definition" : path17.join(".");
14132
+ }
14133
+ function isRecord2(value) {
14134
+ return typeof value === "object" && value !== null && !Array.isArray(value);
14135
+ }
14136
+ function isString(value) {
14137
+ return value !== null;
14138
+ }
14139
+ var DefinitionReader = class _DefinitionReader {
14140
+ #issues = [];
14141
+ static read(input) {
14142
+ const reader = new _DefinitionReader();
14143
+ const spec = reader.spec(input);
14144
+ if (!spec || reader.#issues.length > 0) throw new AgentDefinitionError(reader.#issues);
14145
+ return spec;
14146
+ }
14147
+ spec(input) {
14148
+ if (!isRecord2(input)) return this.refuse([], "invalid_type", "a definition is an object", null);
14149
+ this.unknownFields(input, DEFINITION_FIELDS, []);
14150
+ const effort = this.optionalString(input.effort, ["effort"]);
14151
+ return {
14152
+ name: this.name(input.name),
14153
+ instructions: this.instructions(input.instructions),
14154
+ model: this.optionalString(input.model, ["model"]) ?? DEFAULT_MODEL,
14155
+ ...effort === void 0 ? {} : { effort },
14156
+ maxTurns: this.maxTurns(input.maxTurns),
14157
+ tools: this.tools(input.tools)
14158
+ };
14159
+ }
14160
+ name(value) {
14161
+ const name = this.string(value, ["name"]);
14162
+ if (name !== null && !NAME_PATTERN.test(name))
14163
+ this.issue(["name"], "invalid_name", "lowercase letters, digits and dashes, 1-63 long, not starting with a dash");
14164
+ return name ?? "";
14165
+ }
14166
+ instructions(value) {
14167
+ const instructions = this.string(value, ["instructions"]);
14168
+ if (instructions !== null) this.bounded(instructions.length, INSTRUCTIONS, ["instructions"], "characters");
14169
+ return instructions ?? "";
14170
+ }
14171
+ maxTurns(value) {
14172
+ if (value === void 0) return DEFAULT_MAX_TURNS;
14173
+ if (typeof value !== "number" || !Number.isInteger(value))
14174
+ return this.refuse(["maxTurns"], "invalid_type", "a whole number", DEFAULT_MAX_TURNS);
14175
+ this.bounded(value, MAX_TURNS, ["maxTurns"], "turns");
14176
+ return value;
14177
+ }
14178
+ tools(value) {
14179
+ if (value === void 0) return [];
14180
+ if (!Array.isArray(value)) return this.refuse(["tools"], "invalid_type", "a list of tools", []);
14181
+ const grants = value.map((entry, index2) => this.grant(entry, ["tools", index2]));
14182
+ this.noRepeats(
14183
+ grants.map((grant2) => grant2?.server ?? null),
14184
+ (index2) => ["tools", index2, "server"],
14185
+ "duplicate_tool_server",
14186
+ "this server is already granted"
14187
+ );
14188
+ return grants.filter((grant2) => grant2 !== null);
14189
+ }
14190
+ grant(entry, path17) {
14191
+ if (typeof entry === "string") return { server: entry };
14192
+ if (!isRecord2(entry)) return this.refuse(path17, "invalid_type", "a server name or { server, only }", null);
14193
+ this.unknownFields(entry, GRANT_FIELDS, path17);
14194
+ const server = this.string(entry.server, [...path17, "server"]);
14195
+ if (server === null) return null;
14196
+ return entry.only === void 0 ? { server } : { server, only: this.only(entry.only, [...path17, "only"]) };
14197
+ }
14198
+ only(value, path17) {
14199
+ if (!Array.isArray(value)) return this.refuse(path17, "invalid_type", "a list of tool names", []);
14200
+ if (value.length === 0)
14201
+ this.issue(path17, "too_small", "names at least one tool; leave `only` out to grant the whole server");
14202
+ const names = value.map((name, index2) => this.string(name, [...path17, index2]));
14203
+ this.noRepeats(names, (index2) => [...path17, index2], "duplicate_tool", "this tool is already named");
14204
+ return names.filter(isString).sort();
14205
+ }
14206
+ string(value, path17) {
14207
+ if (typeof value === "string") return value;
14208
+ return this.refuse(path17, "invalid_type", "a string", null);
14209
+ }
14210
+ optionalString(value, path17) {
14211
+ if (value === void 0) return void 0;
14212
+ return this.string(value, path17) ?? void 0;
14213
+ }
14214
+ bounded(value, bounds, path17, unit) {
14215
+ if (value < bounds.min) this.issue(path17, "too_small", `at least ${bounds.min} ${unit}`);
14216
+ if (value > bounds.max) this.issue(path17, "too_large", `at most ${bounds.max} ${unit}`);
14217
+ }
14218
+ unknownFields(record, known, path17) {
14219
+ for (const [key2, value] of Object.entries(record)) {
14220
+ if (value !== void 0 && !known.has(key2))
14221
+ this.issue([...path17, key2], "unknown_field", "not a field of an agent definition");
14222
+ }
14223
+ }
14224
+ noRepeats(values, pathOf, code, message) {
14225
+ const seen = /* @__PURE__ */ new Set();
14226
+ values.forEach((value, index2) => {
14227
+ if (value === null) return;
14228
+ if (seen.has(value)) this.issue(pathOf(index2), code, message);
14229
+ seen.add(value);
14230
+ });
14231
+ }
14232
+ issue(path17, code, message) {
14233
+ this.#issues.push({ path: path17, code, message });
14234
+ }
14235
+ refuse(path17, code, message, fallback) {
14236
+ this.issue(path17, code, message);
14237
+ return fallback;
14238
+ }
14239
+ };
14240
+
14241
+ // src/agents/index.ts
14242
+ init_apiError();
14243
+ init_transport();
14244
+
14245
+ // src/agents/agents.ts
14246
+ init_apiError();
14247
+
14248
+ // src/agents/segment.ts
14249
+ function segment(id) {
14250
+ if (id === "" || id === "." || id === "..") throw new TypeError(`not an id: "${id}"`);
14251
+ return encodeURIComponent(id);
14252
+ }
14253
+
14254
+ // src/agents/agents.ts
14255
+ var PRODUCTION = "production";
14256
+ var PAGE_SIZE = 100;
14257
+ var buildRoute = (buildId) => `/api/public/agent-builds/${segment(buildId)}`;
14258
+ var AgentVersionNotFoundError = class extends Error {
14259
+ constructor(agent, versionId) {
14260
+ super(`${versionId} is not a version of ${agent}; nothing was deployed.`);
14261
+ this.agent = agent;
14262
+ this.versionId = versionId;
14263
+ this.name = "AgentVersionNotFoundError";
14264
+ }
14265
+ agent;
14266
+ versionId;
14267
+ code = "version_not_found";
14268
+ };
14269
+ var Agents = class {
14270
+ #transport;
14271
+ #threads;
14272
+ constructor(transport, threads) {
14273
+ this.#transport = transport;
14274
+ this.#threads = threads;
14275
+ }
14276
+ /** Create an agent, live in one call: version 1, deployed. A definition `defineAgent` would refuse throws `AgentDefinitionError` before anything is sent; a name the project already holds is 409 `agent_exists`. */
14277
+ async create(input) {
14278
+ const { name, ...definition2 } = AgentDefinition.from(input).toJSON();
14279
+ const record = await this.#transport.json(
14280
+ "POST",
14281
+ `/api/public/agent-builds/definitions/${segment(name)}`,
14282
+ definition2
14283
+ );
14284
+ return new Agent(this, record, this.#threads);
14285
+ }
14286
+ /** The live agent named `name`, to edit or run; 404 `agent_not_found` when the project has none. */
14287
+ async get(name) {
14288
+ return new Agent(this, await this.live(name), this.#threads);
14289
+ }
14290
+ /** The version of `name` that edits apply to: the one `production` runs, else the newest. */
14291
+ live(name) {
14292
+ return this.#transport.json("GET", `/api/public/agent-builds/definitions/${segment(name)}`);
14293
+ }
14294
+ /** Apply one patch to `name` as a new version, live unless `deploy: false`. With `from`, a version that is no longer the live one is refused (`AgentVersionConflictError`) and nothing is written. */
14295
+ edit(name, patch, options = {}) {
14296
+ const body = { patch: patch.toJSON(), from: options.from, deploy: options.deploy ?? true };
14297
+ return this.conflictAware("POST", `/api/public/agent-builds/definitions/${segment(name)}/versions`, body);
14298
+ }
14299
+ /** Move `production` of `name` to one of its versions, with the audit row; `force` crosses a breaking tool change. */
14300
+ rollback(name, versionId, options = {}) {
14301
+ const body = { versionId, from: options.from, force: options.force ?? false };
14302
+ return this.conflictAware("POST", `/api/public/agent-builds/definitions/${segment(name)}/rollback`, body);
14303
+ }
14304
+ /** Every version of the live agent `name`, newest first, each with `isDeployed` and its changes against the one before; a version written while the pages are read never repeats one. */
14305
+ async history(name) {
14306
+ const versions = /* @__PURE__ */ new Map();
14307
+ for (let page = 1, pages = 1; page <= pages; page += 1) {
14308
+ const query = new URLSearchParams({ page: String(page), limit: String(PAGE_SIZE) });
14309
+ const reply = await this.#transport.json(
14310
+ "GET",
14311
+ `/api/public/agent-builds/definitions/${segment(name)}/versions?${query}`
14312
+ );
14313
+ for (const version of reply.data) if (!versions.has(version.id)) versions.set(version.id, version);
14314
+ pages = reply.meta.totalPages;
14315
+ }
14316
+ return [...versions.values()];
14317
+ }
14318
+ /** Push a definition: a new version, or the identical one already pushed (`created: false`); the platform derives its `buildHash`. With `deploy`, `production` moves to it; when that move is refused the version still exists, and pushing again returns it. */
14319
+ async push(definition2, options = {}) {
14320
+ const body = { definition: definition2.toJSON(), attribution: options.attribution };
14321
+ const version = await this.#transport.json("POST", "/api/public/agent-builds/definitions", body);
14322
+ if (!options.deploy) return version;
14323
+ await this.move(version.id, false);
14324
+ return { ...version, deployed: true, labels: [.../* @__PURE__ */ new Set([...version.labels, PRODUCTION])] };
14325
+ }
14326
+ /** Move `production` to `versionId`, after checking it is a defined version of `name` (an observed build of that name is not one). Rolling back is deploying an older version; `force` crosses a breaking tool change. */
14327
+ async deploy(name, versionId, options = {}) {
14328
+ const versions = await this.versions(name);
14329
+ if (!versions.some((version) => version.id === versionId && version.kind === "defined"))
14330
+ throw new AgentVersionNotFoundError(name, versionId);
14331
+ return this.move(versionId, options.force ?? false);
14332
+ }
14333
+ /** Every version of `name`, newest first. */
14334
+ async versions(name) {
14335
+ const builds = [];
14336
+ for (let page = 1, pages = 1; page <= pages; page += 1) {
14337
+ const query = new URLSearchParams({ agentId: name, page: String(page), limit: String(PAGE_SIZE) });
14338
+ const reply = await this.#transport.json("GET", `/api/public/agent-builds?${query}`);
14339
+ builds.push(...reply.data);
14340
+ pages = reply.meta.totalPages;
14341
+ }
14342
+ return builds;
14343
+ }
14344
+ async conflictAware(method, path17, body) {
14345
+ try {
14346
+ return await this.#transport.json(method, path17, body);
14347
+ } catch (error) {
14348
+ if (error instanceof ApiError && error.code === "agent_version_conflict")
14349
+ throw new AgentVersionConflictError(error.status, method, path17, error.text);
14350
+ throw error;
14351
+ }
14352
+ }
14353
+ async move(versionId, force) {
14354
+ const body = { label: PRODUCTION, source: "api", force };
14355
+ const moved = await this.#transport.json("POST", `${buildRoute(versionId)}/labels`, body);
14356
+ return {
14357
+ agentId: moved.agentId,
14358
+ label: moved.label,
14359
+ versionId,
14360
+ fromBuildHash: moved.fromBuild,
14361
+ toBuildHash: moved.toBuild
14362
+ };
14363
+ }
14364
+ };
14365
+
14366
+ // src/agents/gateway.ts
14367
+ init_platformEndpoint();
14368
+ init_transport();
14369
+
14370
+ // src/agents/run.ts
14371
+ init_apiError();
14372
+ init_transport();
14373
+
14374
+ // src/agents/sse.ts
14375
+ var EventStreamError = class extends Error {
14376
+ constructor(code, message) {
14377
+ super(message);
14378
+ this.code = code;
14379
+ this.name = "EventStreamError";
14380
+ }
14381
+ code;
14382
+ };
14383
+ var SseLimits = class _SseLimits {
14384
+ constructor(maxLineLength, maxEventLength) {
14385
+ this.maxLineLength = maxLineLength;
14386
+ this.maxEventLength = maxEventLength;
14387
+ }
14388
+ maxLineLength;
14389
+ maxEventLength;
14390
+ static DEFAULT = new _SseLimits(4 * 1024 * 1024, 4 * 1024 * 1024);
14391
+ };
14392
+ var EventBlock = class {
14393
+ constructor(id, limits) {
14394
+ this.id = id;
14395
+ this.limits = limits;
14396
+ }
14397
+ id;
14398
+ limits;
14399
+ #data = [];
14400
+ #length = 0;
14401
+ #type = "";
14402
+ addData(value) {
14403
+ this.#length += value.length + 1;
14404
+ if (this.#length > this.limits.maxEventLength)
14405
+ throw new EventStreamError("event_too_large", `an event passed ${this.limits.maxEventLength} characters`);
14406
+ this.#data.push(value);
14407
+ }
14408
+ setType(value) {
14409
+ this.#type = value;
14410
+ }
14411
+ setId(value) {
14412
+ if (!value.includes("\0")) this.id = value;
14413
+ }
14414
+ message() {
14415
+ if (this.#data.length === 0) return null;
14416
+ return { event: this.#type || "message", data: this.#data.join("\n"), lastEventId: this.id || null };
14417
+ }
14418
+ };
14419
+ var FIELDS2 = /* @__PURE__ */ new Map([
14420
+ ["data", (block, value) => block.addData(value)],
14421
+ ["event", (block, value) => block.setType(value)],
14422
+ ["id", (block, value) => block.setId(value)]
14423
+ ]);
14424
+ var SseParser = class {
14425
+ #decoder = new TextDecoder();
14426
+ #lineEnd = /[\r\n]/g;
14427
+ #limits;
14428
+ #pending = "";
14429
+ #afterCarriageReturn = false;
14430
+ #lastEventId;
14431
+ #block;
14432
+ constructor(lastEventId = null, limits = SseLimits.DEFAULT) {
14433
+ this.#limits = limits;
14434
+ this.#lastEventId = lastEventId ?? "";
14435
+ this.#block = new EventBlock(this.#lastEventId, limits);
14436
+ }
14437
+ /** The id a reconnect sends as `Last-Event-ID`: the last one set before a dispatched event, or null. */
14438
+ get lastEventId() {
14439
+ return this.#lastEventId || null;
14440
+ }
14441
+ /** Feed the next bytes; returns the events they completed, in order. */
14442
+ push(chunk) {
14443
+ const messages = [];
14444
+ for (const line of this.lines(this.#decoder.decode(chunk, { stream: true }))) {
14445
+ const message = this.line(line);
14446
+ if (message) messages.push(message);
14447
+ }
14448
+ return messages;
14449
+ }
14450
+ lines(text2) {
14451
+ const scanFrom = this.#pending.length;
14452
+ this.#pending += this.skipLineFeed(text2);
14453
+ const lines = [];
14454
+ let start = 0;
14455
+ this.#lineEnd.lastIndex = scanFrom;
14456
+ for (let end = this.#lineEnd.exec(this.#pending); end; end = this.#lineEnd.exec(this.#pending)) {
14457
+ lines.push(this.capped(this.#pending.slice(start, end.index)));
14458
+ start = this.lineEnd(end.index);
14459
+ this.#lineEnd.lastIndex = start;
14460
+ }
14461
+ this.#pending = this.capped(this.#pending.slice(start));
14462
+ return lines;
14463
+ }
14464
+ lineEnd(index2) {
14465
+ const crlf = this.#pending.startsWith("\r\n", index2);
14466
+ this.#afterCarriageReturn = this.#pending[index2] === "\r" && index2 + 1 === this.#pending.length;
14467
+ return index2 + (crlf ? 2 : 1);
14468
+ }
14469
+ skipLineFeed(text2) {
14470
+ if (!this.#afterCarriageReturn || text2 === "") return text2;
14471
+ this.#afterCarriageReturn = false;
14472
+ return text2.startsWith("\n") ? text2.slice(1) : text2;
14473
+ }
14474
+ capped(line) {
14475
+ if (line.length > this.#limits.maxLineLength)
14476
+ throw new EventStreamError("line_too_large", `a line passed ${this.#limits.maxLineLength} characters`);
14477
+ return line;
14478
+ }
14479
+ line(line) {
14480
+ if (line === "") return this.dispatch();
14481
+ if (line.startsWith(":")) return null;
14482
+ const colon = line.indexOf(":");
14483
+ const field2 = colon === -1 ? line : line.slice(0, colon);
14484
+ const value = colon === -1 ? "" : line.slice(colon + 1).replace(/^ /, "");
14485
+ FIELDS2.get(field2)?.(this.#block, value);
14486
+ return null;
14487
+ }
14488
+ dispatch() {
14489
+ const message = this.#block.message();
14490
+ this.#lastEventId = this.#block.id;
14491
+ this.#block = new EventBlock(this.#lastEventId, this.#limits);
14492
+ return message;
14493
+ }
14494
+ };
14495
+
14496
+ // src/agents/run.ts
14497
+ var SYSTEM_CLOCK = Object.freeze({
14498
+ now: () => Date.now(),
14499
+ sleep: (ms, signal) => new Promise((resolve11, reject) => {
14500
+ if (signal?.aborted) return reject(signal.reason);
14501
+ const abort = () => {
14502
+ clearTimeout(timer);
14503
+ reject(signal?.reason);
14504
+ };
14505
+ const timer = setTimeout(() => {
14506
+ signal?.removeEventListener("abort", abort);
14507
+ resolve11();
14508
+ }, ms);
14509
+ signal?.addEventListener("abort", abort, { once: true });
14510
+ })
14511
+ });
14512
+ var ReconnectPolicy = class _ReconnectPolicy {
14513
+ constructor(delaysMs, idleMs) {
14514
+ this.delaysMs = delaysMs;
14515
+ this.idleMs = idleMs;
14516
+ }
14517
+ delaysMs;
14518
+ idleMs;
14519
+ static DEFAULT = new _ReconnectPolicy([250, 500, 1e3, 2e3, 4e3], PLATFORM_STREAM_IDLE_MS);
14520
+ };
14521
+ var STOPS = {
14522
+ "run.started": "continues",
14523
+ "step.attempt": "continues",
14524
+ "message.delta": "continues",
14525
+ "step.completed": "continues",
14526
+ "tool.started": "continues",
14527
+ "tool.completed": "continues",
14528
+ "run.error": "continues",
14529
+ "action.required": "waits",
14530
+ "run.completed": "ends",
14531
+ "run.failed": "ends",
14532
+ "run.cancelled": "ends"
14533
+ };
14534
+ var FINISHED = /* @__PURE__ */ new Set(["completed", "failed", "cancelled"]);
14535
+ var REFRESH_RETRIES = 3;
14536
+ var STREAM_REFUSALS_RETRIED = /* @__PURE__ */ new Set(["too_many_streams"]);
14537
+ var runRoute = (threadId, runId) => `/api/public/threads/${segment(threadId)}/runs/${segment(runId)}`;
14538
+ function readEvent(message) {
14539
+ if (!Object.hasOwn(STOPS, message.event)) return null;
14540
+ const data = parseJson2(message.data);
14541
+ if (typeof data !== "object" || data === null || data.type !== message.event)
14542
+ throw new EventStreamError("malformed_event", `a ${message.event} event whose data is not that event's JSON`);
14543
+ return data;
14544
+ }
14545
+ function retried(refusal) {
14546
+ return RetryPolicy.TRANSIENT_STATUSES.has(refusal.status) || STREAM_REFUSALS_RETRIED.has(refusal.code ?? "");
14547
+ }
14548
+ function parseJson2(text2) {
14549
+ try {
14550
+ return JSON.parse(text2);
14551
+ } catch {
14552
+ return void 0;
14553
+ }
14554
+ }
14555
+ var Connection = class {
14556
+ constructor(openedAt) {
14557
+ this.openedAt = openedAt;
14558
+ }
14559
+ openedAt;
14560
+ #delivered = false;
14561
+ #closedCleanly = false;
14562
+ #stop = "continues";
14563
+ #why = "the stream closed before the run ended";
14564
+ get ended() {
14565
+ return this.#stop === "ends";
14566
+ }
14567
+ // The door closes after action.required only while the run waits; when more events follow, that wait was answered.
14568
+ get stopped() {
14569
+ return this.#stop !== "continues";
14570
+ }
14571
+ get why() {
14572
+ return this.#why;
14573
+ }
14574
+ delivered() {
14575
+ this.#delivered = true;
14576
+ }
14577
+ at(stop) {
14578
+ this.#stop = stop;
14579
+ }
14580
+ closedCleanly() {
14581
+ this.#closedCleanly = true;
14582
+ }
14583
+ refused(status) {
14584
+ this.#why = `the platform answered ${status}`;
14585
+ }
14586
+ dropped(error) {
14587
+ if (!(error instanceof UnreachableError)) throw error;
14588
+ this.#why = error.message;
14589
+ }
14590
+ // A silence cut, a drop or a refused status never counts as working, however long it took: only an event, or the
14591
+ // platform's own clean close of a stream that lived the idle budget (its lifetime close), starts the count again.
14592
+ working(now, idleMs) {
14593
+ return this.#delivered || this.#closedCleanly && now - this.openedAt >= idleMs;
14594
+ }
14595
+ };
14596
+ var Reconnects = class {
14597
+ constructor(policy, clock, route2) {
14598
+ this.policy = policy;
14599
+ this.clock = clock;
14600
+ this.route = route2;
14601
+ }
14602
+ policy;
14603
+ clock;
14604
+ route;
14605
+ #inARow = 0;
14606
+ async after(connection, signal) {
14607
+ this.#inARow = connection.working(this.clock.now(), this.policy.idleMs) ? 1 : this.#inARow + 1;
14608
+ const delayMs = this.policy.delaysMs[this.#inARow - 1];
14609
+ if (delayMs === void 0)
14610
+ throw new EventStreamError(
14611
+ "reconnects_exhausted",
14612
+ `GET ${this.route}: no working stream after ${this.policy.delaysMs.length} reconnects in a row; last: ${connection.why}`
14613
+ );
14614
+ await this.clock.sleep(delayMs, signal);
14615
+ }
14616
+ };
14617
+ var AgentRun = class {
14618
+ #transport;
14619
+ #clock;
14620
+ #reconnect;
14621
+ #snapshot;
14622
+ #cursor = null;
14623
+ #ending = null;
14624
+ constructor(transport, run, options = {}) {
14625
+ this.#transport = transport;
14626
+ this.#snapshot = run;
14627
+ this.#clock = options.clock ?? SYSTEM_CLOCK;
14628
+ this.#reconnect = options.reconnect ?? ReconnectPolicy.DEFAULT;
14629
+ }
14630
+ get id() {
14631
+ return this.#snapshot.id;
14632
+ }
14633
+ get threadId() {
14634
+ return this.#snapshot.threadId;
14635
+ }
14636
+ /** The run as last read from the platform. */
14637
+ get snapshot() {
14638
+ return this.#snapshot;
14639
+ }
14640
+ /** The id of the last event delivered by any reader; pass it as `after` to resume this run's events elsewhere. */
14641
+ get cursor() {
14642
+ return this.#cursor;
14643
+ }
14644
+ /**
14645
+ * The run's events from `after` (default: where the last `events()` stopped, else the start). A dropped connection, a
14646
+ * silence past the idle budget (60 s), a 502/503/504, a 429 `too_many_streams` or the platform closing the stream
14647
+ * reconnects with `Last-Event-ID`,
14648
+ * so each event arrives once; after 5 reconnects in a row with no event delivered (a clean close after at least the idle
14649
+ * budget also counts as working) it throws `EventStreamError`. Ends after `run.completed`, `run.failed` (`not_found` when
14650
+ * the run no longer exists) or `run.cancelled`, and at an `action.required` the platform ends the stream on (the run waits
14651
+ * for a person); an `action.required` followed by more events was a wait already answered, and the events go on. A key
14652
+ * holds at most 64 open streams: past that the platform answers 429 `too_many_streams`, which counts against the same
14653
+ * five reconnects.
14654
+ */
14655
+ async *events(options = {}) {
14656
+ const position = { cursor: options.after === void 0 ? this.#cursor : options.after };
14657
+ this.#ending = null;
14658
+ const reconnects = new Reconnects(this.#reconnect, this.#clock, `${runRoute(this.threadId, this.id)}/events`);
14659
+ for (; ; ) {
14660
+ const connection = new Connection(this.#clock.now());
14661
+ yield* this.connect(position, connection, options.signal);
14662
+ if (connection.stopped) return;
14663
+ await reconnects.after(connection, options.signal);
14664
+ }
14665
+ }
14666
+ /** The run once it has finished, or once it waits for a person (`status: "requires_action"` with its `action`). Throws `EventStreamError` `run_not_finished` when the stream ended the run and the platform still reads it as active after the reconnect delays, and the platform's 404 `ApiError` (`not_found`) for a run that no longer exists. */
14667
+ async wait(options = {}) {
14668
+ const polls = this.#reconnect.delaysMs[Symbol.iterator]();
14669
+ let run = this.#ending === null ? this.#snapshot : await this.refresh(options);
14670
+ while (!this.settled(run)) {
14671
+ await this.advance(polls, options.signal);
14672
+ run = await this.refresh(options);
14673
+ }
14674
+ return run;
14675
+ }
14676
+ /** The run as the platform reads it now; a gateway 5xx or a dropped connection is retried with the first reconnect delays. `signal` aborts the request and its retry waits. */
14677
+ async refresh(options = {}) {
14678
+ const { signal } = options;
14679
+ const retry = new RetryPolicy(
14680
+ this.#reconnect.delaysMs.slice(0, REFRESH_RETRIES),
14681
+ (ms) => this.#clock.sleep(ms, signal)
14682
+ );
14683
+ return this.take(
14684
+ await this.#transport.json("GET", `${runRoute(this.threadId, this.id)}`, void 0, { retry, signal })
14685
+ );
14686
+ }
14687
+ /** Stop the run; a run already finished answers with its status. */
14688
+ async cancel(options = {}) {
14689
+ const { signal } = options;
14690
+ return this.take(
14691
+ await this.#transport.json("POST", `${runRoute(this.threadId, this.id)}/cancel`, {}, { signal })
14692
+ );
14693
+ }
14694
+ /** Answer the question the run waits on; the run is queued again and `events()` continues from where it stopped. */
14695
+ async resolve(answer, options = {}) {
14696
+ const body = { actionId: answer.actionId, answer: answer.answer };
14697
+ const { signal } = options;
14698
+ const run = await this.#transport.json("POST", `${runRoute(this.threadId, this.id)}/resolve`, body, {
14699
+ signal
14700
+ });
14701
+ this.#ending = null;
14702
+ return this.take(run);
14703
+ }
14704
+ settled(run) {
14705
+ return FINISHED.has(run.status) || this.#ending === "action.required" && run.status === "requires_action";
14706
+ }
14707
+ async advance(polls, signal) {
14708
+ if (this.#ending !== null && this.#ending !== "action.required") return this.pause(polls, signal);
14709
+ const before = this.#cursor;
14710
+ for await (const event of this.events({ signal })) void event;
14711
+ if (this.#ending === "action.required" && this.#cursor === before) await this.pause(polls, signal);
14712
+ }
14713
+ async pause(polls, signal) {
14714
+ const delay = polls.next();
14715
+ if (delay.done)
14716
+ throw new EventStreamError(
14717
+ "run_not_finished",
14718
+ `${runRoute(this.threadId, this.id)}: the stream ended the run with ${this.#ending}, and the platform still reads it as ${this.#snapshot.status}`
14719
+ );
14720
+ await this.#clock.sleep(delay.value, signal);
14721
+ }
14722
+ take(run) {
14723
+ this.#snapshot = run;
14724
+ return run;
14725
+ }
14726
+ async *connect(position, connection, signal) {
14727
+ const stream = await this.open(position, connection, signal);
14728
+ if (!stream) return;
14729
+ try {
14730
+ yield* this.read(stream, position, connection);
14731
+ connection.closedCleanly();
14732
+ } catch (error) {
14733
+ connection.dropped(error);
14734
+ } finally {
14735
+ stream.close();
14736
+ }
14737
+ }
14738
+ async open(position, connection, signal) {
14739
+ const route2 = `${runRoute(this.threadId, this.id)}/events`;
14740
+ try {
14741
+ const stream = await this.#transport.stream(route2, {
14742
+ after: position.cursor,
14743
+ signal,
14744
+ idleMs: this.#reconnect.idleMs
14745
+ });
14746
+ return await this.accepted(stream, route2, connection);
14747
+ } catch (error) {
14748
+ connection.dropped(error);
14749
+ return null;
14750
+ }
14751
+ }
14752
+ async accepted(stream, route2, connection) {
14753
+ if (stream.ok) return stream;
14754
+ const refusal = new ApiError(stream.status, "GET", route2, await stream.text());
14755
+ if (!retried(refusal)) throw refusal;
14756
+ connection.refused(stream.status);
14757
+ return null;
14758
+ }
14759
+ async *read(stream, position, connection) {
14760
+ const parser = new SseParser(position.cursor);
14761
+ for await (const chunk of stream.chunks()) {
14762
+ for (const message of parser.push(chunk)) {
14763
+ const event = readEvent(message);
14764
+ this.moveTo(position, message.lastEventId);
14765
+ if (!event) continue;
14766
+ connection.delivered();
14767
+ this.note(event, connection);
14768
+ yield event;
14769
+ if (connection.ended) return;
14770
+ }
14771
+ this.moveTo(position, parser.lastEventId);
14772
+ }
14773
+ }
14774
+ // Each events() call resumes from its own position, so two readers of one run never skip or repeat each other's events.
14775
+ moveTo(position, cursor) {
14776
+ position.cursor = cursor;
14777
+ this.#cursor = cursor;
14778
+ }
14779
+ note(event, connection) {
14780
+ const stop = STOPS[event.type];
14781
+ this.#ending = stop === "continues" ? null : event.type;
14782
+ connection.at(stop);
14783
+ }
14784
+ };
14785
+
14786
+ // src/agents/threads.ts
14787
+ var threadRoute = (threadId) => `/api/public/threads/${segment(threadId)}`;
14788
+ var Thread = class {
14789
+ #transport;
14790
+ #runs;
14791
+ id;
14792
+ agent;
14793
+ title;
14794
+ autonomy;
14795
+ activeRun;
14796
+ createdAt;
14797
+ /** Granted tools this key cannot activate; only on the thread `create` returns. */
14798
+ warnings;
14799
+ constructor(transport, record, runs = {}) {
14800
+ this.#transport = transport;
14801
+ this.#runs = runs;
14802
+ this.id = record.id;
14803
+ this.agent = record.agent;
14804
+ this.title = record.title;
14805
+ this.autonomy = Object.freeze({ ...record.autonomy });
14806
+ this.activeRun = record.activeRun ? Object.freeze({ ...record.activeRun }) : null;
14807
+ this.createdAt = record.createdAt;
14808
+ this.warnings = Object.freeze([...record.warnings ?? []]);
14809
+ }
14810
+ /** Start a run on the agent's deployed version (or `version`); refused with 409 `thread_busy` while another run is active. */
14811
+ async send(input, options = {}) {
14812
+ const body = { input, version: options.version, multitask: options.multitask };
14813
+ const run = await this.#transport.json("POST", `${threadRoute(this.id)}/runs`, body);
14814
+ return new AgentRun(this.#transport, run, this.#runs);
14815
+ }
14816
+ /** A run of this thread by id, as it is now. */
14817
+ async run(runId) {
14818
+ const run = await this.#transport.json("GET", `${threadRoute(this.id)}/runs/${segment(runId)}`);
14819
+ return new AgentRun(this.#transport, run, this.#runs);
14820
+ }
14821
+ };
14822
+ var Threads = class {
14823
+ #transport;
14824
+ #runs;
14825
+ constructor(transport, runs = {}) {
14826
+ this.#transport = transport;
14827
+ this.#runs = runs;
14828
+ }
14829
+ /** A thread for a deployed agent; `allowSelfSchedule` or `allowSubagents` set to `true` is refused (400 `autonomy_unsupported`). */
14830
+ async create(options) {
14831
+ const agent = typeof options.agent === "string" ? options.agent : options.agent.name;
14832
+ const body = { agent, title: options.title, autonomy: options.autonomy };
14833
+ const record = await this.#transport.json("POST", "/api/public/threads", body);
14834
+ return new Thread(this.#transport, record, this.#runs);
14835
+ }
14836
+ async get(threadId) {
14837
+ const record = await this.#transport.json("GET", `${threadRoute(threadId)}`);
14838
+ return new Thread(this.#transport, record, this.#runs);
14839
+ }
14840
+ };
14841
+
14842
+ // src/agents/gateway.ts
14843
+ var Gateway = class {
14844
+ agents;
14845
+ threads;
14846
+ constructor(options = {}) {
14847
+ const transport = options.transport ?? new PlatformTransport(requirePlatformEndpoint(options));
14848
+ this.threads = new Threads(transport, { clock: options.clock, reconnect: options.reconnect });
14849
+ this.agents = new Agents(transport, this.threads);
14850
+ Object.freeze(this);
14851
+ }
14852
+ };
14853
+
14854
+ // src/agents/tools.ts
14855
+ var AGENT_MODELS = ["claude-opus-5", "claude-sonnet-5"];
14856
+ var AGENT_EFFORTS = ["low", "medium", "high", "xhigh"];
14857
+ var TOOL_SERVERS = {
14858
+ docs: ["search_docs"],
14859
+ drive: ["get_drive_file", "list_drive_files", "save_drive_file"],
14860
+ sandbox: [
14861
+ "copy_file",
14862
+ "execute_python",
14863
+ "grep_files",
14864
+ "ingest_sessions_to_sandbox",
14865
+ "list_files",
14866
+ "query_json",
14867
+ "read_file",
14868
+ "run_bash",
14869
+ "run_gateway_cli",
14870
+ "write_file"
14871
+ ],
14872
+ web: ["download_url_to_drive", "fetch_url"]
14873
+ };
14874
+ var grant = (server) => (options = {}) => options.only ? { server, only: [...options.only] } : { server };
14875
+ var tools = Object.freeze({
14876
+ sandbox: grant("sandbox"),
14877
+ drive: grant("drive"),
14878
+ web: grant("web"),
14879
+ docs: grant("docs")
14880
+ });
14881
+
12867
14882
  // src/files/index.ts
12868
14883
  var files_exports = {};
12869
14884
  __export(files_exports, {
@@ -13228,7 +15243,7 @@ __export(hooks_exports, {
13228
15243
  normalizeEvent: () => normalizeEvent,
13229
15244
  pageTitle: () => pageTitle,
13230
15245
  parseHookConfig: () => parseHookConfig,
13231
- parseJson: () => parseJson2,
15246
+ parseJson: () => parseJson3,
13232
15247
  parseMatcher: () => parseMatcher,
13233
15248
  parseRegex: () => parseRegex,
13234
15249
  parseStdout: () => parseStdout,
@@ -13706,7 +15721,7 @@ function emailPairs(real, fake) {
13706
15721
  }
13707
15722
  function phoneForms(number) {
13708
15723
  const digits = number.replace(/\D/g, "");
13709
- const forms = [
15724
+ const forms2 = [
13710
15725
  ["raw", number],
13711
15726
  ["digits", digits],
13712
15727
  ["plus", `+${digits}`]
@@ -13717,7 +15732,7 @@ function phoneForms(number) {
13717
15732
  const c = digits.slice(-4);
13718
15733
  const country = digits.slice(0, -10);
13719
15734
  const prefix = country ? `+${country} ` : "";
13720
- forms.push(
15735
+ forms2.push(
13721
15736
  ["spaced", `${prefix}${a} ${b} ${c}`],
13722
15737
  ["dashed", `${prefix}${a}-${b}-${c}`],
13723
15738
  ["paren", `${prefix}(${a}) ${b}-${c}`],
@@ -13727,7 +15742,7 @@ function phoneForms(number) {
13727
15742
  ["local_paren", `(${a}) ${b}-${c}`]
13728
15743
  );
13729
15744
  }
13730
- return forms;
15745
+ return forms2;
13731
15746
  }
13732
15747
  function phonePairs(real, fake) {
13733
15748
  const fakeForms = new Map(phoneForms(fake));
@@ -14459,172 +16474,382 @@ function mirrorHandle(handle, identity) {
14459
16474
  import * as fs14 from "fs";
14460
16475
 
14461
16476
  // src/cli/platform/worldData/toml.ts
16477
+ var TomlDateTime = class {
16478
+ constructor(text2) {
16479
+ this.text = text2;
16480
+ }
16481
+ text;
16482
+ toString() {
16483
+ return this.text;
16484
+ }
16485
+ };
14462
16486
  var TomlError = class extends Error {
14463
16487
  };
14464
16488
  function parseToml(text2) {
14465
- const root = {};
14466
- let current = root;
14467
- const lines = joinContinuations(text2);
14468
- for (const [number, rawLine] of lines.entries()) {
14469
- const line = stripComment(rawLine).trim();
14470
- if (!line) continue;
14471
- const arrayTable = /^\[\[\s*([^\]]+?)\s*\]\]$/.exec(line);
14472
- if (arrayTable) {
14473
- const parent = tableAt(root, keyPath(arrayTable[1]).slice(0, -1));
14474
- const name = keyPath(arrayTable[1]).at(-1);
14475
- const list = parent[name] ??= [];
14476
- if (!Array.isArray(list)) throw new TomlError(`line ${number + 1}: ${name} is not an array of tables`);
14477
- current = {};
14478
- list.push(current);
14479
- continue;
14480
- }
14481
- const table2 = /^\[\s*([^\]]+?)\s*\]$/.exec(line);
14482
- if (table2) {
14483
- current = tableAt(root, keyPath(table2[1]));
14484
- continue;
16489
+ return new TomlReader(text2).read();
16490
+ }
16491
+ var BARE_KEY = /^[A-Za-z0-9_-]+$/;
16492
+ var CONTROL = /[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/;
16493
+ var COMMENT_CONTROL = /[\x00-\x08\x0a-\x1f\x7f]/;
16494
+ var DEC_INT = /^[+-]?(?:0|[1-9](?:_?\d)*)$/;
16495
+ var RADIX_INT = [
16496
+ [/^0x[0-9A-Fa-f](?:_?[0-9A-Fa-f])*$/, 16],
16497
+ [/^0o[0-7](?:_?[0-7])*$/, 8],
16498
+ [/^0b[01](?:_?[01])*$/, 2]
16499
+ ];
16500
+ var FLOAT = /^[+-]?(?:0|[1-9](?:_?\d)*)(?:\.\d(?:_?\d)*)?(?:[eE][+-]?\d(?:_?\d)*)?$/;
16501
+ var SPECIAL_FLOAT = /^([+-]?)(inf|nan)$/;
16502
+ var DATE_TIME = /^(\d{4})-(\d{2})-(\d{2})(?:[Tt ](\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:[Zz]|[+-](\d{2}):(\d{2}))?)?/;
16503
+ var LOCAL_TIME = /^(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?/;
16504
+ var INLINE = /* @__PURE__ */ new WeakSet();
16505
+ var newTable = () => /* @__PURE__ */ Object.create(null);
16506
+ var own = (table2, key2) => Object.prototype.hasOwnProperty.call(table2, key2) ? table2[key2] : void 0;
16507
+ var isTomlTable = (value) => value !== void 0 && typeof value === "object" && Object.getPrototypeOf(value) === null;
16508
+ var stripBlank = (text2) => text2.replace(/^[ \t]+|[ \t]+$/g, "");
16509
+ var TomlReader = class {
16510
+ constructor(text2) {
16511
+ this.text = text2;
16512
+ }
16513
+ text;
16514
+ root = newTable();
16515
+ current = this.root;
16516
+ defined = /* @__PURE__ */ new WeakSet();
16517
+ byHeader = /* @__PURE__ */ new WeakSet();
16518
+ byDottedKey = /* @__PURE__ */ new WeakSet();
16519
+ tableArrays = /* @__PURE__ */ new WeakSet();
16520
+ read() {
16521
+ for (const { text: text2, line } of logicalLines(this.text)) this.statement(stripBlank(text2), line);
16522
+ return this.root;
16523
+ }
16524
+ statement(text2, line) {
16525
+ if (!text2) return;
16526
+ const arrayTable = /^\[\[[ \t]*(.+?)[ \t]*\]\]$/.exec(text2);
16527
+ if (arrayTable) return this.arrayTable(keyPath(arrayTable[1], line), line);
16528
+ const header = /^\[[ \t]*(.+?)[ \t]*\]$/.exec(text2);
16529
+ if (header) return this.header(keyPath(header[1], line), line);
16530
+ const eq = outsideQuotes(text2, "=");
16531
+ if (eq === -1) throw new TomlError(`line ${line}: expected key = value`);
16532
+ const path17 = keyPath(text2.slice(0, eq), line);
16533
+ const [value, rest] = readValue(text2.slice(eq + 1), line);
16534
+ if (stripBlank(rest)) throw new TomlError(`line ${line}: unexpected text after value`);
16535
+ assign(this.descend(this.current, path17.slice(0, -1), line, "key"), path17, value, line);
16536
+ }
16537
+ header(path17, line) {
16538
+ const parent = this.descend(this.root, path17.slice(0, -1), line, "header");
16539
+ const name = path17.at(-1);
16540
+ const table2 = own(parent, name) ?? newTable();
16541
+ const fresh = isTomlTable(table2) && !INLINE.has(table2) && !this.byDottedKey.has(table2) && !this.defined.has(table2);
16542
+ if (!fresh) throw new TomlError(`line ${line}: [${path17.join(".")}] is defined twice`);
16543
+ parent[name] = table2;
16544
+ this.open(table2);
16545
+ }
16546
+ arrayTable(path17, line) {
16547
+ const parent = this.descend(this.root, path17.slice(0, -1), line, "header");
16548
+ const name = path17.at(-1);
16549
+ const existing = own(parent, name);
16550
+ if (existing !== void 0 && !(Array.isArray(existing) && this.tableArrays.has(existing)))
16551
+ throw new TomlError(`line ${line}: ${path17.join(".")} is not an array of tables`);
16552
+ const list2 = existing ?? [];
16553
+ this.tableArrays.add(list2);
16554
+ parent[name] = list2;
16555
+ const table2 = newTable();
16556
+ list2.push(table2);
16557
+ this.open(table2);
16558
+ }
16559
+ open(table2) {
16560
+ this.defined.add(table2);
16561
+ this.byHeader.add(table2);
16562
+ this.current = table2;
16563
+ }
16564
+ descend(from, parts2, line, via) {
16565
+ let node = from;
16566
+ for (const part of parts2) {
16567
+ const next = own(node, part);
16568
+ node = next === void 0 ? this.make(node, part, via) : this.enter(next, part, line, via);
14485
16569
  }
14486
- const eq = line.indexOf("=");
14487
- if (eq === -1) throw new TomlError(`line ${number + 1}: expected key = value`);
14488
- const key2 = unquoteKey(line.slice(0, eq).trim());
14489
- const [value, rest] = readValue(line.slice(eq + 1).trim(), number + 1);
14490
- if (rest.trim()) throw new TomlError(`line ${number + 1}: unexpected text after value`);
14491
- current[key2] = value;
16570
+ return node;
14492
16571
  }
14493
- return root;
14494
- }
14495
- function keyPath(header) {
14496
- return header.split(".").map((part) => unquoteKey(part.trim()));
14497
- }
14498
- function unquoteKey(key2) {
14499
- if (key2.startsWith('"') && key2.endsWith('"') || key2.startsWith("'") && key2.endsWith("'")) return key2.slice(1, -1);
14500
- return key2;
16572
+ make(parent, part, via) {
16573
+ const table2 = newTable();
16574
+ (via === "header" ? this.byHeader : this.byDottedKey).add(table2);
16575
+ parent[part] = table2;
16576
+ return table2;
16577
+ }
16578
+ enter(value, part, line, via) {
16579
+ const target = via === "header" && Array.isArray(value) && this.tableArrays.has(value) ? value.at(-1) : value;
16580
+ const open = isTomlTable(target) && !INLINE.has(target) && !(via === "key" && this.defined.has(target));
16581
+ if (!open) throw new TomlError(`line ${line}: ${part} is already defined and cannot be extended here`);
16582
+ if (via === "key") this.byDottedKey.add(target);
16583
+ return target;
16584
+ }
16585
+ };
16586
+ function assign(table2, path17, value, line) {
16587
+ const key2 = path17.at(-1);
16588
+ if (own(table2, key2) !== void 0) throw new TomlError(`line ${line}: key ${path17.join(".")} is defined twice`);
16589
+ table2[key2] = value;
14501
16590
  }
14502
- function tableAt(root, parts2) {
14503
- let node = root;
16591
+ function inlineAt(table2, parts2, line) {
16592
+ let node = table2;
14504
16593
  for (const part of parts2) {
14505
- const next = node[part] ??= {};
14506
- if (Array.isArray(next)) {
14507
- const last = next[next.length - 1];
14508
- if (!last || typeof last !== "object" || Array.isArray(last)) throw new TomlError(`${part} is not a table`);
14509
- node = last;
14510
- } else if (typeof next !== "object") throw new TomlError(`${part} is not a table`);
14511
- else node = next;
16594
+ const next = own(node, part) ?? newTable();
16595
+ if (!isTomlTable(next) || INLINE.has(next))
16596
+ throw new TomlError(`line ${line}: ${part} is already defined and cannot be extended here`);
16597
+ node[part] = next;
16598
+ node = next;
14512
16599
  }
14513
16600
  return node;
14514
16601
  }
14515
- function joinContinuations(text2) {
14516
- const out = [];
14517
- let pending = "";
14518
- let depth = 0;
14519
- for (const physical of text2.split(/\r?\n/)) {
14520
- const raw = stripComment(physical);
14521
- const line = pending ? pending + "\n" + raw : raw;
14522
- depth = bracketDepth(line);
14523
- if (depth > 0) {
14524
- pending = line;
14525
- continue;
14526
- }
14527
- pending = "";
14528
- out.push(line);
16602
+ function keyPath(text2, line) {
16603
+ const parts2 = [];
16604
+ let rest = text2;
16605
+ for (; ; ) {
16606
+ const dot = outsideQuotes(rest, ".");
16607
+ parts2.push(readKey(stripBlank(dot === -1 ? rest : rest.slice(0, dot)), line));
16608
+ if (dot === -1) return parts2;
16609
+ rest = rest.slice(dot + 1);
14529
16610
  }
14530
- if (pending) out.push(pending);
14531
- return out;
14532
16611
  }
14533
- function bracketDepth(line) {
14534
- let depth = 0;
14535
- let quote = null;
14536
- for (let i = 0; i < line.length; i++) {
14537
- const c = line[i];
14538
- if (quote) {
14539
- if (c === "\\" && quote === '"') i++;
14540
- else if (c === quote) quote = null;
14541
- continue;
14542
- }
14543
- if (c === '"' || c === "'") quote = c;
14544
- else if (c === "[" || c === "{") depth++;
14545
- else if (c === "]" || c === "}") depth--;
14546
- }
14547
- return depth;
16612
+ function readKey(part, line) {
16613
+ const quote = openingQuote(part, 0);
16614
+ if (quote === null && BARE_KEY.test(part)) return part;
16615
+ const read = quote?.length === 1 ? readString(part, line) : null;
16616
+ if (!read || read[1] !== "") throw new TomlError(`line ${line}: \`${part}\` is not a key; quote it`);
16617
+ return read[0];
14548
16618
  }
14549
- function stripComment(line) {
16619
+ function outsideQuotes(text2, char) {
14550
16620
  let quote = null;
14551
- for (let i = 0; i < line.length; i++) {
14552
- const c = line[i];
16621
+ for (let i = 0; i < text2.length; i++) {
16622
+ const c = text2[i];
14553
16623
  if (quote) {
14554
16624
  if (c === "\\" && quote === '"') i++;
14555
16625
  else if (c === quote) quote = null;
14556
16626
  continue;
14557
16627
  }
14558
16628
  if (c === '"' || c === "'") quote = c;
14559
- else if (c === "#") return line.slice(0, i);
16629
+ else if (c === char) return i;
16630
+ }
16631
+ return -1;
16632
+ }
16633
+ function openingQuote(text2, i) {
16634
+ const c = text2[i];
16635
+ if (c !== '"' && c !== "'") return null;
16636
+ return text2.startsWith(c.repeat(3), i) ? c.repeat(3) : c;
16637
+ }
16638
+ function quoteRun(text2, i, quote, line) {
16639
+ let run = 0;
16640
+ while (text2[i + run] === quote) run++;
16641
+ if (run > 5) throw new TomlError(`line ${line}: too many quotes close a multi-line string`);
16642
+ return run;
16643
+ }
16644
+ var LogicalLines = class {
16645
+ constructor(text2) {
16646
+ this.text = text2;
16647
+ }
16648
+ text;
16649
+ out = [];
16650
+ brackets = [];
16651
+ buffer = "";
16652
+ start = 1;
16653
+ line = 1;
16654
+ quote = null;
16655
+ i = 0;
16656
+ split() {
16657
+ if (this.text.startsWith("\uFEFF")) throw new TomlError("line 1: a byte order mark is not TOML");
16658
+ for (; this.i < this.text.length; this.i++) this.step(this.text[this.i]);
16659
+ if (this.quote) throw new TomlError(`line ${this.start}: unterminated string`);
16660
+ if (this.brackets.length > 0) throw new TomlError(`line ${this.start}: a bracket or brace is never closed`);
16661
+ this.out.push({ text: this.buffer, line: this.start });
16662
+ return this.out;
16663
+ }
16664
+ step(c) {
16665
+ if (c === "\n") this.line++;
16666
+ if (this.quote) return this.inString(c, this.quote);
16667
+ if (c === "#") return this.skipComment();
16668
+ const opened = openingQuote(this.text, this.i);
16669
+ if (opened) return this.openString(opened);
16670
+ this.outside(c);
16671
+ }
16672
+ inString(c, quote) {
16673
+ if (c === "\n" && quote.length === 1) throw new TomlError(`line ${this.line - 1}: unterminated string`);
16674
+ if (c === "\\" && quote.startsWith('"')) return this.escape();
16675
+ if (this.text.startsWith(quote, this.i)) return this.closeString(quote);
16676
+ this.buffer += c;
16677
+ }
16678
+ escape() {
16679
+ const next = this.text[this.i + 1] ?? "";
16680
+ this.buffer += "\\" + next;
16681
+ if (next === "\n") this.line++;
16682
+ this.i++;
16683
+ }
16684
+ openString(opened) {
16685
+ this.quote = opened;
16686
+ this.buffer += opened;
16687
+ this.i += opened.length - 1;
16688
+ }
16689
+ closeString(quote) {
16690
+ const run = quote.length === 3 ? quoteRun(this.text, this.i, quote[0], this.line) : 1;
16691
+ this.buffer += this.text.slice(this.i, this.i + run);
16692
+ this.i += run - 1;
16693
+ this.quote = null;
16694
+ }
16695
+ skipComment() {
16696
+ for (; this.i + 1 < this.text.length && this.text[this.i + 1] !== "\n"; this.i++)
16697
+ this.commentCharacter(this.text[this.i + 1]);
16698
+ }
16699
+ commentCharacter(c) {
16700
+ const lineEnd = c === "\r" && this.text[this.i + 2] === "\n";
16701
+ if (!lineEnd && COMMENT_CONTROL.test(c))
16702
+ throw new TomlError(`line ${this.line}: a comment holds a control character`);
16703
+ }
16704
+ outside(c) {
16705
+ if (c === "[" || c === "{") this.brackets.push(c);
16706
+ if (c === "]" || c === "}") this.brackets.pop();
16707
+ if (c === "\n" && this.brackets.at(-1) === "{")
16708
+ throw new TomlError(`line ${this.line - 1}: an inline table must be on one line`);
16709
+ if (c === "\n" && this.brackets.length === 0) return this.endLine();
16710
+ this.buffer += c;
16711
+ }
16712
+ endLine() {
16713
+ this.out.push({ text: this.buffer.replace(/\r$/, ""), line: this.start });
16714
+ this.buffer = "";
16715
+ this.start = this.line;
14560
16716
  }
14561
- return line;
14562
- }
14563
- function readValue(text2, line) {
14564
- const s = text2.trimStart();
14565
- if (s.startsWith('"')) {
14566
- let out = "";
14567
- for (let i = 1; i < s.length; i++) {
14568
- const c = s[i];
14569
- if (c === "\\") {
14570
- const e = s[++i];
14571
- const map = { n: "\n", t: " ", r: "\r", '"': '"', "\\": "\\", b: "\b", f: "\f" };
14572
- if (e === "u" || e === "U") {
14573
- const width = e === "u" ? 4 : 8;
14574
- out += String.fromCodePoint(parseInt(s.slice(i + 1, i + 1 + width), 16));
14575
- i += width;
14576
- } else if (e !== void 0 && e in map) out += map[e];
14577
- else throw new TomlError(`line ${line}: unsupported escape \\${e ?? ""}`);
14578
- continue;
14579
- }
14580
- if (c === '"') return [out, s.slice(i + 1)];
16717
+ };
16718
+ function logicalLines(text2) {
16719
+ return new LogicalLines(text2).split();
16720
+ }
16721
+ var ESCAPES = { n: "\n", t: " ", r: "\r", '"': '"', "\\": "\\", b: "\b", f: "\f" };
16722
+ function unicodeEscape(body, at, width, line) {
16723
+ const digits = body.slice(at, at + width);
16724
+ const code = /^[0-9A-Fa-f]+$/.test(digits) && digits.length === width ? parseInt(digits, 16) : -1;
16725
+ const scalar = code >= 0 && code <= 1114111 && (code < 55296 || code > 57343);
16726
+ if (!scalar) throw new TomlError(`line ${line}: \\${width === 4 ? "u" : "U"}${digits} is not a Unicode scalar value`);
16727
+ return String.fromCodePoint(code);
16728
+ }
16729
+ function decodeBasic(body, line, multiline) {
16730
+ let out = "";
16731
+ for (let i = 0; i < body.length; i++) {
16732
+ const c = body[i];
16733
+ if (c !== "\\") {
14581
16734
  out += c;
16735
+ continue;
14582
16736
  }
14583
- throw new TomlError(`line ${line}: unterminated string`);
14584
- }
14585
- if (s.startsWith("'")) {
14586
- const end = s.indexOf("'", 1);
14587
- if (end === -1) throw new TomlError(`line ${line}: unterminated string`);
14588
- return [s.slice(1, end), s.slice(end + 1)];
14589
- }
14590
- if (s.startsWith("[")) {
14591
- const items = [];
14592
- let rest2 = s.slice(1);
14593
- for (; ; ) {
14594
- rest2 = rest2.replace(/^[\s\n]+/, "");
14595
- if (rest2.startsWith("]")) return [items, rest2.slice(1)];
14596
- const [item, after] = readValue(rest2, line);
14597
- items.push(item);
14598
- rest2 = after.replace(/^[\s\n]+/, "");
14599
- if (rest2.startsWith(",")) rest2 = rest2.slice(1);
14600
- else if (!rest2.startsWith("]")) throw new TomlError(`line ${line}: expected , or ] in array`);
16737
+ const e = body[++i];
16738
+ if (multiline && /^[ \t]*\r?\n/.test(body.slice(i))) {
16739
+ while (i + 1 < body.length && /[ \t\r\n]/.test(body[i + 1])) i++;
16740
+ continue;
14601
16741
  }
16742
+ if (e === "u" || e === "U") {
16743
+ const width = e === "u" ? 4 : 8;
16744
+ out += unicodeEscape(body, i + 1, width, line);
16745
+ i += width;
16746
+ } else if (e !== void 0 && e in ESCAPES) out += ESCAPES[e];
16747
+ else throw new TomlError(`line ${line}: unsupported escape \\${e ?? ""}`);
14602
16748
  }
14603
- if (s.startsWith("{")) {
14604
- const table2 = {};
14605
- let rest2 = s.slice(1);
14606
- for (; ; ) {
14607
- rest2 = rest2.replace(/^[\s\n]+/, "");
14608
- if (rest2.startsWith("}")) return [table2, rest2.slice(1)];
14609
- const eq = rest2.indexOf("=");
14610
- if (eq === -1) throw new TomlError(`line ${line}: expected key = value in inline table`);
14611
- const key2 = unquoteKey(rest2.slice(0, eq).trim());
14612
- const [value, after] = readValue(rest2.slice(eq + 1), line);
14613
- table2[key2] = value;
14614
- rest2 = after.replace(/^[\s\n]+/, "");
14615
- if (rest2.startsWith(",")) rest2 = rest2.slice(1);
14616
- else if (!rest2.startsWith("}")) throw new TomlError(`line ${line}: expected , or } in inline table`);
16749
+ return out;
16750
+ }
16751
+ function checkControls(body, line, multiline) {
16752
+ const broken = CONTROL.test(body) || (multiline ? /\r(?!\n)/.test(body) : /[\r\n]/.test(body));
16753
+ if (broken) throw new TomlError(`line ${line}: a string holds a control character`);
16754
+ }
16755
+ function readString(s, line) {
16756
+ const quote = openingQuote(s, 0);
16757
+ if (!quote) return null;
16758
+ let end = quote.length;
16759
+ for (; end < s.length; end++) {
16760
+ if (quote.startsWith('"') && s[end] === "\\") {
16761
+ end++;
16762
+ continue;
14617
16763
  }
16764
+ if (s.startsWith(quote, end)) break;
16765
+ }
16766
+ if (end >= s.length) throw new TomlError(`line ${line}: unterminated string`);
16767
+ if (quote.length === 3) end += quoteRun(s, end, quote[0], line) - 3;
16768
+ const raw = s.slice(quote.length, end);
16769
+ const multiline = quote.length === 3;
16770
+ const body = multiline ? raw.replace(/^\r?\n/, "") : raw;
16771
+ checkControls(body, line, multiline);
16772
+ const text2 = quote.startsWith('"') ? decodeBasic(body, line, multiline) : body;
16773
+ return [text2, s.slice(end + quote.length)];
16774
+ }
16775
+ function readArray(s, line) {
16776
+ const items = [];
16777
+ let rest = s.slice(1);
16778
+ for (; ; ) {
16779
+ rest = rest.replace(/^[ \t\r\n]+/, "");
16780
+ if (rest.startsWith("]")) return [items, rest.slice(1)];
16781
+ const [item, after] = readValue(rest, line);
16782
+ items.push(item);
16783
+ rest = after.replace(/^[ \t\r\n]+/, "");
16784
+ if (rest.startsWith(",")) rest = rest.slice(1);
16785
+ else if (!rest.startsWith("]")) throw new TomlError(`line ${line}: expected , or ] in array`);
16786
+ }
16787
+ }
16788
+ function readInlineTable(s, line) {
16789
+ const table2 = newTable();
16790
+ let rest = s.slice(1).replace(/^[ \t]+/, "");
16791
+ if (rest.startsWith("}")) {
16792
+ INLINE.add(table2);
16793
+ return [table2, rest.slice(1)];
14618
16794
  }
14619
- const scalar = /^([^,\]}\s]+)/.exec(s);
16795
+ for (; ; ) {
16796
+ const eq = outsideQuotes(rest, "=");
16797
+ if (eq === -1) throw new TomlError(`line ${line}: expected key = value in inline table`);
16798
+ const path17 = keyPath(rest.slice(0, eq), line);
16799
+ const [value, after] = readValue(rest.slice(eq + 1), line);
16800
+ assign(inlineAt(table2, path17.slice(0, -1), line), path17, value, line);
16801
+ rest = after.replace(/^[ \t]+/, "");
16802
+ if (rest.startsWith("}")) {
16803
+ INLINE.add(table2);
16804
+ return [table2, rest.slice(1)];
16805
+ }
16806
+ if (!rest.startsWith(",")) throw new TomlError(`line ${line}: expected , or } in inline table`);
16807
+ rest = rest.slice(1).replace(/^[ \t]+/, "");
16808
+ if (rest.startsWith("}")) throw new TomlError(`line ${line}: an inline table takes no trailing comma`);
16809
+ }
16810
+ }
16811
+ function inRange(value, low, high) {
16812
+ return value === void 0 || Number(value) >= low && Number(value) <= high;
16813
+ }
16814
+ function readDateTime(s, line) {
16815
+ const full = DATE_TIME.exec(s);
16816
+ const time = full ? null : LOCAL_TIME.exec(s);
16817
+ const match = full ?? time;
16818
+ if (!match) return null;
16819
+ const [y, mo, d, h, mi, se, oh, om] = full ? full.slice(1) : [void 0, void 0, void 0, ...time.slice(1)];
16820
+ const day = y === void 0 ? null : new Date(Date.UTC(Number(y), Number(mo) - 1, Number(d)));
16821
+ const dateOk = day === null || day.getUTCMonth() === Number(mo) - 1 && day.getUTCDate() === Number(d);
16822
+ const timeOk = inRange(h, 0, 23) && inRange(mi, 0, 59) && inRange(se, 0, 59) && inRange(oh, 0, 23) && inRange(om, 0, 59);
16823
+ if (!dateOk || !timeOk) throw new TomlError(`line ${line}: ${match[0]} is not a valid date or time`);
16824
+ return [new TomlDateTime(match[0]), s.slice(match[0].length)];
16825
+ }
16826
+ function readNumber(token) {
16827
+ const plain = token.replace(/_/g, "");
16828
+ if (DEC_INT.test(token)) return Number(plain);
16829
+ for (const [pattern, radix] of RADIX_INT) if (pattern.test(token)) return parseInt(plain.slice(2), radix);
16830
+ if (FLOAT.test(token) && /[.eE]/.test(token)) return Number(plain);
16831
+ const special = SPECIAL_FLOAT.exec(token);
16832
+ if (!special) return null;
16833
+ if (special[2] === "nan") return NaN;
16834
+ return special[1] === "-" ? -Infinity : Infinity;
16835
+ }
16836
+ function readValue(text2, line) {
16837
+ const s = text2.replace(/^[ \t]+/, "");
16838
+ const string = readString(s, line);
16839
+ if (string) return string;
16840
+ if (s.startsWith("[")) return readArray(s, line);
16841
+ if (s.startsWith("{")) return readInlineTable(s, line);
16842
+ const date = readDateTime(s, line);
16843
+ if (date) return date;
16844
+ const scalar = /^([^,\]}\s#]+)/.exec(s);
14620
16845
  if (!scalar) throw new TomlError(`line ${line}: expected a value`);
14621
16846
  const token = scalar[1];
14622
16847
  const rest = s.slice(token.length);
14623
16848
  if (token === "true") return [true, rest];
14624
16849
  if (token === "false") return [false, rest];
14625
- if (/^[+-]?\d[\d_]*$/.test(token)) return [Number(token.replace(/_/g, "")), rest];
14626
- if (/^[+-]?(\d[\d_]*)?\.?\d[\d_]*([eE][+-]?\d+)?$/.test(token)) return [Number(token.replace(/_/g, "")), rest];
14627
- throw new TomlError(`line ${line}: unsupported value ${token}`);
16850
+ const number = readNumber(token);
16851
+ if (number === null) throw new TomlError(`line ${line}: unsupported value ${token}`);
16852
+ return [number, rest];
14628
16853
  }
14629
16854
 
14630
16855
  // src/hooks/events.ts
@@ -15037,15 +17262,15 @@ function parseLive(raw, toolsRaw) {
15037
17262
  );
15038
17263
  if (!isObject4(toolsRaw))
15039
17264
  throw new HookConfigError("`tools` must be a table of [tools.<name>]");
15040
- const tools = {};
17265
+ const tools2 = {};
15041
17266
  for (const [name, spec] of Object.entries(toolsRaw))
15042
- tools[name] = parseTool(name, spec, allowed);
17267
+ tools2[name] = parseTool(name, spec, allowed);
15043
17268
  return {
15044
17269
  ...typeof raw.record === "string" && raw.record ? { record: raw.record } : {},
15045
17270
  ...typeof raw.replay === "string" && raw.replay ? { replay: raw.replay } : {},
15046
17271
  allowedEnv: allowed,
15047
17272
  timeout,
15048
- tools
17273
+ tools: tools2
15049
17274
  };
15050
17275
  }
15051
17276
  function parseTool(name, raw, allowedEnv) {
@@ -15327,7 +17552,7 @@ function loadHookConfig(file) {
15327
17552
  }
15328
17553
  return parseHookConfig(data, file);
15329
17554
  }
15330
- var isObject4 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
17555
+ var isObject4 = (v) => typeof v === "object" && v !== null && [null, Object.prototype].includes(Object.getPrototypeOf(v));
15331
17556
  function parseHookConfig(data, source) {
15332
17557
  const where = source ?? "config";
15333
17558
  if (!isObject4(data))
@@ -15349,12 +17574,12 @@ function parseHookConfig(data, source) {
15349
17574
  throw new HookConfigError(
15350
17575
  `hooks.${rawEvent}: unknown event; expected one of ${EVENTS.join(", ")} (or PreToolUse, PostToolUse, Stop)`
15351
17576
  );
15352
- const list = isObject4(rawRules) ? [rawRules] : rawRules;
15353
- if (!Array.isArray(list))
17577
+ const list2 = isObject4(rawRules) ? [rawRules] : rawRules;
17578
+ if (!Array.isArray(list2))
15354
17579
  throw new HookConfigError(
15355
17580
  `hooks.${rawEvent}: expected an array of rules ([[hooks.${rawEvent}]])`
15356
17581
  );
15357
- list.forEach(
17582
+ list2.forEach(
15358
17583
  (raw, index2) => rules.push(parseRule(event, raw, `hooks.${rawEvent}[${index2}]`))
15359
17584
  );
15360
17585
  }
@@ -15474,12 +17699,12 @@ function parseRule(event, raw, position) {
15474
17699
  );
15475
17700
  }
15476
17701
  const handlersRaw = raw.handlers ?? raw.hooks;
15477
- const list = isObject4(handlersRaw) ? [handlersRaw] : handlersRaw;
15478
- if (!Array.isArray(list) || !list.length)
17702
+ const list2 = isObject4(handlersRaw) ? [handlersRaw] : handlersRaw;
17703
+ if (!Array.isArray(list2) || !list2.length)
15479
17704
  throw new HookConfigError(
15480
17705
  `${position}.handlers: expected a non-empty array of handler tables`
15481
17706
  );
15482
- const handlers = list.map(
17707
+ const handlers = list2.map(
15483
17708
  (h, i) => parseHandler(event, h, `${position}.handlers[${i}]`)
15484
17709
  );
15485
17710
  const rewriters = handlers.filter(isRewriter);
@@ -16339,8 +18564,8 @@ var pyQuote2 = (value) => encodeURIComponent(value).replace(
16339
18564
  /[!'()*]/g,
16340
18565
  (c) => "%" + c.charCodeAt(0).toString(16).toUpperCase()
16341
18566
  );
16342
- function jsonPath(node, pathText) {
16343
- const steps = pathText.trim().split(/\.|(?=\[)/).filter((s) => s && s !== "$");
18567
+ function jsonPath(node, pathText2) {
18568
+ const steps = pathText2.trim().split(/\.|(?=\[)/).filter((s) => s && s !== "$");
16344
18569
  let current = node;
16345
18570
  for (const step of steps) {
16346
18571
  const index2 = /^\[(\*|\d+)\]$/.exec(step);
@@ -16446,7 +18671,7 @@ function mapFields(items, fields, stripHtml) {
16446
18671
  );
16447
18672
  });
16448
18673
  }
16449
- function parseJson2(body, options) {
18674
+ function parseJson3(body, options) {
16450
18675
  let data;
16451
18676
  try {
16452
18677
  data = JSON.parse(body);
@@ -16614,7 +18839,7 @@ var HttpTool = class _HttpTool {
16614
18839
  }
16615
18840
  this.checkFailIf(response.status, body, url);
16616
18841
  if (o.parse === "json")
16617
- return applyLimit(parseJson2(body, o), o.limit, values);
18842
+ return applyLimit(parseJson3(body, o), o.limit, values);
16618
18843
  return applyLimit(parseRegex(body, o), o.limit, values);
16619
18844
  }
16620
18845
  /** `fail_if`: a body that matches is a refusal from the provider (a bot challenge,
@@ -16669,8 +18894,8 @@ function readConnection(root) {
16669
18894
  };
16670
18895
  }
16671
18896
  return {
16672
- slug: connector.slug ?? path15.basename(root),
16673
- baseUrl: (connector.base_url ?? "").replace(/\/+$/, ""),
18897
+ slug: typeof connector.slug === "string" ? connector.slug : path15.basename(root),
18898
+ baseUrl: (typeof connector.base_url === "string" ? connector.base_url : "").replace(/\/+$/, ""),
16674
18899
  scheme: carrier.scheme,
16675
18900
  carrier,
16676
18901
  ...typeof auth.secret_env === "string" ? { secretEnv: auth.secret_env } : {},
@@ -16771,7 +18996,7 @@ var ConnectorTool = class {
16771
18996
  throw new TypeError(
16772
18997
  `${this.spec.name}: missing path argument(s) ${missing.join(", ")}`
16773
18998
  );
16774
- const pathText = this.operation.path.replace(
18999
+ const pathText2 = this.operation.path.replace(
16775
19000
  /\{([A-Za-z_][A-Za-z0-9_]*)\}/g,
16776
19001
  (_, name) => pyQuote2(String(values[name]))
16777
19002
  );
@@ -16787,7 +19012,7 @@ var ConnectorTool = class {
16787
19012
  const carried2 = carryCredential(c.carrier, await this.credential() ?? "");
16788
19013
  Object.assign(headers, carried2.headers);
16789
19014
  for (const [key2, value] of carried2.query) query.append(key2, value);
16790
- const url = c.baseUrl + pathText + (query.toString() ? `?${query.toString()}` : "");
19015
+ const url = c.baseUrl + pathText2 + (query.toString() ? `?${query.toString()}` : "");
16791
19016
  const response = await fetch(url, {
16792
19017
  method: this.operation.method,
16793
19018
  headers,
@@ -16802,7 +19027,7 @@ var ConnectorTool = class {
16802
19027
  }
16803
19028
  if (response.status >= 400)
16804
19029
  throw new LiveToolError(
16805
- `${this.spec.name}: ${c.baseUrl}${pathText} answered HTTP ${response.status}: ${text2.slice(0, 200)}`
19030
+ `${this.spec.name}: ${c.baseUrl}${pathText2} answered HTTP ${response.status}: ${text2.slice(0, 200)}`
16806
19031
  );
16807
19032
  if (this.operation.results && isObject5(body)) {
16808
19033
  const selected = jsonPath(body, this.operation.results);
@@ -16918,12 +19143,12 @@ var LiveTools = class _LiveTools {
16918
19143
  raw = {};
16919
19144
  inside;
16920
19145
  static async create(run, live, baseDir) {
16921
- const tools = new _LiveTools(run, live);
19146
+ const tools2 = new _LiveTools(run, live);
16922
19147
  for (const [name, spec] of Object.entries(live.tools)) {
16923
- tools.built[name] = await buildTool(spec, live, baseDir);
16924
- tools.raw[name] = tools.replay ? tools.replay.tool(spec) : tools.built[name];
19148
+ tools2.built[name] = await buildTool(spec, live, baseDir);
19149
+ tools2.raw[name] = tools2.replay ? tools2.replay.tool(spec) : tools2.built[name];
16925
19150
  }
16926
- return tools;
19151
+ return tools2;
16927
19152
  }
16928
19153
  /** The tools of a hooks file for an existing run: the file read, `{run_id}` /
16929
19154
  * `{run_dir}` in its `[live]` paths filled from the run (`runDir` overrides the
@@ -17613,9 +19838,9 @@ var HookRun = class _HookRun {
17613
19838
  * and is re-thrown (same class with the rewritten message). `additional_context`
17614
19839
  * from the handlers is delivered with the result (see `withContext`).
17615
19840
  */
17616
- wrapTools(tools, opts = {}) {
19841
+ wrapTools(tools2, opts = {}) {
17617
19842
  const wrapped = /* @__PURE__ */ Object.create(null);
17618
- for (const [name, fn] of Object.entries(tools)) {
19843
+ for (const [name, fn] of Object.entries(tools2)) {
17619
19844
  wrapped[name] = async (args = {}) => {
17620
19845
  let real;
17621
19846
  let context4;
@@ -18257,8 +20482,20 @@ var tracing = {
18257
20482
  };
18258
20483
  export {
18259
20484
  ACTION_NAMES,
20485
+ AGENT_EFFORTS,
18260
20486
  AGENT_ID_KEY,
20487
+ AGENT_MODELS,
18261
20488
  ActionTracer,
20489
+ Agent,
20490
+ AgentDefinition,
20491
+ AgentDefinitionError,
20492
+ AgentPatch,
20493
+ AgentRun,
20494
+ AgentThreads,
20495
+ AgentTools,
20496
+ AgentVersionConflictError,
20497
+ AgentVersionNotFoundError,
20498
+ Agents,
18262
20499
  AnthropicComputer,
18263
20500
  AnthropicComputer20251124,
18264
20501
  ApiError,
@@ -18291,9 +20528,11 @@ export {
18291
20528
  EXPERIMENT_ATTRIBUTES,
18292
20529
  EXPLORATORY_TASK,
18293
20530
  EXPLORATORY_TASK_SOURCE,
20531
+ EventStreamError,
18294
20532
  ExperimentClient,
18295
20533
  ExperimentSpanProcessor,
18296
20534
  ExposureLogger,
20535
+ Gateway,
18297
20536
  GatewayContext,
18298
20537
  GatewayContextConflictError,
18299
20538
  GatewayContextError,
@@ -18317,12 +20556,17 @@ export {
18317
20556
  OpenAIComputer,
18318
20557
  OpenAIPreviewComputer,
18319
20558
  PLATFORM_SESSION_HEADER,
20559
+ PLATFORM_STREAM_IDLE_MS,
18320
20560
  PLATFORM_TIMEOUT_DEFAULT_MS,
18321
20561
  PLATFORM_TIMEOUT_ENV,
20562
+ PageObserver,
20563
+ PageState,
20564
+ PageStateError,
18322
20565
  PendingSafetyChecks,
18323
20566
  Persona,
18324
20567
  PersonaError,
18325
20568
  PersonasClient,
20569
+ PlatformStream,
18326
20570
  PlatformTransport,
18327
20571
  PushSlugConflict,
18328
20572
  RECOVER_BUDGET_MS,
@@ -18330,6 +20574,7 @@ export {
18330
20574
  REQUESTS_NOT_RECORDED,
18331
20575
  REQUEST_BODY_CAPTURE_BYTES,
18332
20576
  REQUEST_LOG_PAGE_MAX,
20577
+ ReconnectPolicy,
18333
20578
  ReplayCase,
18334
20579
  ReplayCheck,
18335
20580
  ReplayError,
@@ -18354,6 +20599,7 @@ export {
18354
20599
  SUCCESS_METRIC_NAME_KEY,
18355
20600
  SUCCESS_SIGNAL_KEY,
18356
20601
  SURFACE_KINDS,
20602
+ SYSTEM_CLOCK,
18357
20603
  Score,
18358
20604
  ScoreError,
18359
20605
  ScoresClient,
@@ -18362,13 +20608,18 @@ export {
18362
20608
  SessionLoadError,
18363
20609
  SessionRecording,
18364
20610
  SessionTrace,
20611
+ SseLimits,
20612
+ SseParser,
18365
20613
  StubMissError,
18366
20614
  TOOL_CONTRACT_UNREAD,
20615
+ TOOL_SERVERS,
18367
20616
  TRANSFORMS,
18368
20617
  TaskEditClient,
18369
20618
  TaskGrades,
18370
20619
  TaskRun,
18371
20620
  TaskSessions,
20621
+ Thread,
20622
+ Threads,
18372
20623
  ToolStubRegistry,
18373
20624
  TraceDiff,
18374
20625
  TransportCause,
@@ -18394,6 +20645,7 @@ export {
18394
20645
  WorldSessionOpenFailed,
18395
20646
  WorldSessionTimeout,
18396
20647
  WorldSet,
20648
+ WorldStateClient,
18397
20649
  WorldSurfaceUnavailable,
18398
20650
  WorldTask,
18399
20651
  WorldToolsUnread,
@@ -18431,6 +20683,7 @@ export {
18431
20683
  createRef,
18432
20684
  createTask,
18433
20685
  currentTraceId,
20686
+ defineAgent,
18434
20687
  defineTool,
18435
20688
  deleteEnvSecret,
18436
20689
  deleteTask,
@@ -18486,6 +20739,7 @@ export {
18486
20739
  parseTransform,
18487
20740
  parseWorldTaskRefs,
18488
20741
  personas,
20742
+ platformAuthorization,
18489
20743
  platformTimeoutMs,
18490
20744
  playwrightKey,
18491
20745
  preserveForm,
@@ -18522,6 +20776,7 @@ export {
18522
20776
  runWithExperimentContext,
18523
20777
  schemaFromSignature,
18524
20778
  scores,
20779
+ scrubError,
18525
20780
  serializeCallBody,
18526
20781
  sessionObservationFromApi,
18527
20782
  sessionToolObservations,
@@ -18542,6 +20797,7 @@ export {
18542
20797
  taskRunFailure,
18543
20798
  toolCallRecordsIn,
18544
20799
  toolCallsFromObservations,
20800
+ tools,
18545
20801
  traces_exports as traces,
18546
20802
  tracing,
18547
20803
  uiEntryUrl,