@withgateway/sdk 0.2.6 → 0.2.9

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 (110) hide show
  1. package/README.md +24 -8
  2. package/dist/cli.js +15468 -11263
  3. package/dist/cli.js.map +1 -1
  4. package/dist/cli.mjs +15233 -11028
  5. package/dist/cli.mjs.map +1 -1
  6. package/dist/files/index.d.mts +1 -1
  7. package/dist/files/index.d.ts +1 -1
  8. package/dist/files/index.js +291 -40
  9. package/dist/files/index.js.map +1 -1
  10. package/dist/files/index.mjs +284 -37
  11. package/dist/files/index.mjs.map +1 -1
  12. package/dist/hooks/index.d.mts +1 -1
  13. package/dist/hooks/index.d.ts +1 -1
  14. package/dist/hooks/index.js +203 -47
  15. package/dist/hooks/index.js.map +1 -1
  16. package/dist/hooks/index.mjs +198 -42
  17. package/dist/hooks/index.mjs.map +1 -1
  18. package/dist/{index-BaKu5ZSU.d.mts → index-C3UzD0G3.d.mts} +75 -1
  19. package/dist/{index-BaKu5ZSU.d.ts → index-C3UzD0G3.d.ts} +75 -1
  20. package/dist/{index-CLkMr6VG.d.ts → index-D-_4Ibcn.d.ts} +36 -4
  21. package/dist/{index-CdbmO4aX.d.mts → index-FfK4Nump.d.mts} +36 -4
  22. package/dist/index.d.mts +3 -3
  23. package/dist/index.d.ts +3 -3
  24. package/dist/index.js +2149 -615
  25. package/dist/index.js.map +1 -1
  26. package/dist/index.mjs +2053 -566
  27. package/dist/index.mjs.map +1 -1
  28. package/dist/traces/index.js +268 -31
  29. package/dist/traces/index.js.map +1 -1
  30. package/dist/traces/index.mjs +262 -28
  31. package/dist/traces/index.mjs.map +1 -1
  32. package/dist/tracing/index.js +19 -11
  33. package/dist/tracing/index.js.map +1 -1
  34. package/dist/tracing/index.mjs +19 -11
  35. package/dist/tracing/index.mjs.map +1 -1
  36. package/dist/worlds/index.d.mts +886 -117
  37. package/dist/worlds/index.d.ts +886 -117
  38. package/dist/worlds/index.js +1770 -452
  39. package/dist/worlds/index.js.map +1 -1
  40. package/dist/worlds/index.mjs +1752 -434
  41. package/dist/worlds/index.mjs.map +1 -1
  42. package/package.json +14 -10
  43. package/runtime/gatewaysdk/environment/_toml.py +3 -10
  44. package/runtime/gatewaysdk/environment/_world.py +95 -28
  45. package/runtime/gatewaysdk/environment/runtime.py +10 -6
  46. package/runtime/gatewaysdk/environment/schema/__main__.py +35 -0
  47. package/runtime/gatewaysdk/environment/schema/api.py +19 -23
  48. package/runtime/gatewaysdk/environment/schema/batch.py +68 -14
  49. package/runtime/gatewaysdk/environment/schema/bundle_runtime.py +4 -2
  50. package/runtime/gatewaysdk/environment/schema/cast.py +264 -0
  51. package/runtime/gatewaysdk/environment/schema/compiler.py +35 -1
  52. package/runtime/gatewaysdk/environment/schema/conform.py +28 -10
  53. package/runtime/gatewaysdk/environment/schema/connector.py +59 -14
  54. package/runtime/gatewaysdk/environment/schema/connectors/custom/handlers.py +38 -1
  55. package/runtime/gatewaysdk/environment/schema/connectors/google-drive/readers/merge.toml +3 -1
  56. package/runtime/gatewaysdk/environment/schema/credentials.py +20 -0
  57. package/runtime/gatewaysdk/environment/schema/csv_rows.py +117 -0
  58. package/runtime/gatewaysdk/environment/schema/cycles.py +121 -0
  59. package/runtime/gatewaysdk/environment/schema/data.py +21 -5
  60. package/runtime/gatewaysdk/environment/schema/grading.py +95 -13
  61. package/runtime/gatewaysdk/environment/schema/handler_errors.py +44 -0
  62. package/runtime/gatewaysdk/environment/schema/handler_scan.py +175 -0
  63. package/runtime/gatewaysdk/environment/schema/host.py +68 -115
  64. package/runtime/gatewaysdk/environment/schema/host_requests.py +78 -0
  65. package/runtime/gatewaysdk/environment/schema/host_surfaces.py +12 -0
  66. package/runtime/gatewaysdk/environment/schema/ingest.py +5 -18
  67. package/runtime/gatewaysdk/environment/schema/local.py +7 -10
  68. package/runtime/gatewaysdk/environment/schema/openapi_document.py +322 -0
  69. package/runtime/gatewaysdk/environment/schema/openapi_import.py +382 -0
  70. package/runtime/gatewaysdk/environment/schema/openapi_routes.py +441 -0
  71. package/runtime/gatewaysdk/environment/schema/openapi_schemas.py +629 -0
  72. package/runtime/gatewaysdk/environment/schema/openapi_source.py +210 -0
  73. package/runtime/gatewaysdk/environment/schema/platform.py +110 -299
  74. package/runtime/gatewaysdk/environment/schema/platform_import.py +182 -0
  75. package/runtime/gatewaysdk/environment/schema/platform_query.py +95 -0
  76. package/runtime/gatewaysdk/environment/schema/route_bindings.py +176 -0
  77. package/runtime/gatewaysdk/environment/schema/runtime.py +56 -7
  78. package/runtime/gatewaysdk/environment/schema/scaffold.py +64 -5
  79. package/runtime/gatewaysdk/environment/schema/skills/benchmarks-getting-started/SKILL.md +70 -22
  80. package/runtime/gatewaysdk/environment/schema/skills/connector-schema-authoring/SKILL.md +54 -4
  81. package/runtime/gatewaysdk/environment/schema/skills/hooks-getting-started/SKILL.md +27 -2
  82. package/runtime/gatewaysdk/environment/schema/skills/world-data-ingestion/ROWS.md +62 -0
  83. package/runtime/gatewaysdk/environment/schema/skills/world-data-ingestion/SKILL.md +91 -54
  84. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/SKILL.md +146 -146
  85. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/cli-mcp-map.md +11 -7
  86. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/gotchas.md +30 -0
  87. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/new-world-sandbox.md +43 -0
  88. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/openapi-import.md +90 -0
  89. package/runtime/gatewaysdk/environment/schema/store.py +15 -6
  90. package/runtime/gatewaysdk/environment/schema/store_contract.py +119 -0
  91. package/runtime/gatewaysdk/environment/schema/tasks.py +121 -32
  92. package/runtime/gatewaysdk/environment/schema/tools_world.py +32 -10
  93. package/runtime/gatewaysdk/environment/schema/tree_import.py +228 -0
  94. package/runtime/gatewaysdk/environment/schema/ui.py +18 -2
  95. package/runtime/gatewaysdk/environment/schema/validation.py +35 -0
  96. package/runtime/gatewaysdk/environment/schema/verbs.py +8 -2
  97. package/runtime/gatewaysdk/environment/world.py +42 -3
  98. package/runtime/gatewaysdk/environment/world_session_contract.py +57 -0
  99. package/skills/benchmarks-getting-started/SKILL.md +70 -22
  100. package/skills/connector-schema-authoring/SKILL.md +54 -4
  101. package/skills/connector-schema-authoring/connector-worlds.md +21 -7
  102. package/skills/connector-schema-authoring/world-schema.md +144 -83
  103. package/skills/hooks-getting-started/SKILL.md +27 -2
  104. package/skills/world-data-ingestion/ROWS.md +62 -0
  105. package/skills/world-data-ingestion/SKILL.md +91 -54
  106. package/skills/worlds-getting-started/SKILL.md +146 -146
  107. package/skills/worlds-getting-started/references/cli-mcp-map.md +11 -7
  108. package/skills/worlds-getting-started/references/gotchas.md +30 -0
  109. package/skills/worlds-getting-started/references/new-world-sandbox.md +43 -0
  110. package/skills/worlds-getting-started/references/openapi-import.md +90 -0
package/dist/index.js CHANGED
@@ -5,11 +5,20 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
6
  var __getProtoOf = Object.getPrototypeOf;
7
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __esm = (fn, res) => function __init() {
9
- return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
8
+ var __esm = (fn, res, err) => function __init() {
9
+ if (err) throw err[0];
10
+ try {
11
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
12
+ } catch (e) {
13
+ throw err = [e], e;
14
+ }
10
15
  };
11
16
  var __commonJS = (cb, mod) => function __require() {
12
- return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
17
+ try {
18
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
19
+ } catch (e) {
20
+ throw mod = 0, e;
21
+ }
13
22
  };
14
23
  var __export = (target, all) => {
15
24
  for (var name in all)
@@ -195,10 +204,10 @@ var init_users = __esm({
195
204
  totalItems: Number(meta.totalItems ?? rows.length)
196
205
  };
197
206
  }
198
- async requestJson(method, path14, payload) {
207
+ async requestJson(method, path16, payload) {
199
208
  let response;
200
209
  try {
201
- response = await fetch(`${this.host}${path14}`, {
210
+ response = await fetch(`${this.host}${path16}`, {
202
211
  method,
203
212
  headers: {
204
213
  Authorization: this.authHeader(),
@@ -209,17 +218,17 @@ var init_users = __esm({
209
218
  });
210
219
  } catch (error) {
211
220
  throw new UserProfileError(
212
- `${method} ${path14} failed: ${error instanceof Error ? error.message : String(error)}`,
221
+ `${method} ${path16} failed: ${error instanceof Error ? error.message : String(error)}`,
213
222
  { cause: error }
214
223
  );
215
224
  }
216
225
  const text2 = await response.text();
217
226
  if (!response.ok) {
218
227
  throw new UserProfileError(
219
- `${method} ${path14} failed (${response.status}): ${text2.slice(0, 500)}`
228
+ `${method} ${path16} failed (${response.status}): ${text2.slice(0, 500)}`
220
229
  );
221
230
  }
222
- this.log("%s %s -> %s", method, path14, response.status);
231
+ this.log("%s %s -> %s", method, path16, response.status);
223
232
  return safeJson4(text2);
224
233
  }
225
234
  authHeader() {
@@ -408,10 +417,10 @@ var init_scores = __esm({
408
417
  metadata: signalMetadata
409
418
  });
410
419
  }
411
- async request(method, path14, payload) {
420
+ async request(method, path16, payload) {
412
421
  let response;
413
422
  try {
414
- response = await fetch(`${this.host}${path14}`, {
423
+ response = await fetch(`${this.host}${path16}`, {
415
424
  method,
416
425
  headers: {
417
426
  Authorization: this.authHeader(),
@@ -422,17 +431,17 @@ var init_scores = __esm({
422
431
  });
423
432
  } catch (error) {
424
433
  throw new ScoreError(
425
- `${method} ${path14} failed: ${error instanceof Error ? error.message : String(error)}`,
434
+ `${method} ${path16} failed: ${error instanceof Error ? error.message : String(error)}`,
426
435
  { cause: error }
427
436
  );
428
437
  }
429
438
  const text2 = await response.text();
430
439
  if (!response.ok) {
431
440
  throw new ScoreError(
432
- `${method} ${path14} failed (${response.status}): ${text2.slice(0, 500)}`
441
+ `${method} ${path16} failed (${response.status}): ${text2.slice(0, 500)}`
433
442
  );
434
443
  }
435
- this.log("%s %s -> %s", method, path14, response.status);
444
+ this.log("%s %s -> %s", method, path16, response.status);
436
445
  }
437
446
  authHeader() {
438
447
  return `Basic ${Buffer.from(`${this.publicKey}:${this.secretKey}`).toString(
@@ -455,7 +464,275 @@ var init_scores = __esm({
455
464
  }
456
465
  });
457
466
 
467
+ // src/worlds/transport.ts
468
+ function platformTimeoutMs(env = process.env) {
469
+ const raw = env[PLATFORM_TIMEOUT_ENV];
470
+ if (raw === void 0 || raw === "") return PLATFORM_TIMEOUT_DEFAULT_MS;
471
+ const value = Number(raw);
472
+ if (Number.isInteger(value) && value > 0) return value;
473
+ throw new Error(`${PLATFORM_TIMEOUT_ENV} must be a positive whole number of milliseconds, not \`${raw}\`.`);
474
+ }
475
+ var PLATFORM_TIMEOUT_ENV, PLATFORM_TIMEOUT_DEFAULT_MS, CHECK_HOST, RETRY, CAUSES, UNKNOWN_CAUSE, TransportCause, UnreachableError, PlatformTransport;
476
+ var init_transport = __esm({
477
+ "src/worlds/transport.ts"() {
478
+ "use strict";
479
+ PLATFORM_TIMEOUT_ENV = "GATEWAY_TIMEOUT_MS";
480
+ PLATFORM_TIMEOUT_DEFAULT_MS = 12e4;
481
+ CHECK_HOST = "Check GATEWAY_HOST (or --host) points at a running platform, then retry.";
482
+ RETRY = "Retry; if it repeats, check the network between here and the platform.";
483
+ CAUSES = {
484
+ ECONNREFUSED: { reason: "connection refused", next: CHECK_HOST },
485
+ ENOTFOUND: { reason: "DNS lookup failed", next: CHECK_HOST },
486
+ EAI_AGAIN: { reason: "DNS lookup failed", next: CHECK_HOST },
487
+ ETIMEDOUT: { reason: "connect timed out", next: CHECK_HOST },
488
+ UND_ERR_CONNECT_TIMEOUT: { reason: "connect timed out", next: CHECK_HOST },
489
+ EHOSTUNREACH: { reason: "host unreachable", next: CHECK_HOST },
490
+ ENETUNREACH: { reason: "network unreachable", next: RETRY },
491
+ ECONNRESET: { reason: "connection dropped", next: RETRY },
492
+ UND_ERR_SOCKET: { reason: "connection dropped", next: RETRY },
493
+ EPIPE: { reason: "connection dropped", next: RETRY }
494
+ };
495
+ UNKNOWN_CAUSE = { reason: "network error", next: CHECK_HOST };
496
+ TransportCause = class _TransportCause {
497
+ constructor(reason, detail, next) {
498
+ this.reason = reason;
499
+ this.detail = detail;
500
+ this.next = next;
501
+ }
502
+ reason;
503
+ detail;
504
+ next;
505
+ static timeout(timeoutMs) {
506
+ return new _TransportCause(
507
+ `timed out after ${timeoutMs / 1e3}s`,
508
+ null,
509
+ `Retry; if the platform is slow, raise ${PLATFORM_TIMEOUT_ENV} (milliseconds per request).`
510
+ );
511
+ }
512
+ static of(error) {
513
+ const cause = error instanceof Error && error.cause instanceof Error ? error.cause : void 0;
514
+ const code = cause && "code" in cause && typeof cause.code === "string" ? cause.code : null;
515
+ const message = cause?.message ?? (error instanceof Error ? error.message : String(error));
516
+ const known = code && CAUSES[code] || UNKNOWN_CAUSE;
517
+ return new _TransportCause(known.reason, code ? `${code}: ${message}` : message, known.next);
518
+ }
519
+ describe() {
520
+ return this.detail === null ? this.reason : `${this.reason} (${this.detail})`;
521
+ }
522
+ };
523
+ UnreachableError = class extends Error {
524
+ constructor(host, method, route, failure) {
525
+ super(`${method} ${route}: no answer from ${host}: ${failure.describe()}. ${failure.next}`);
526
+ this.host = host;
527
+ this.method = method;
528
+ this.route = route;
529
+ this.failure = failure;
530
+ this.name = "UnreachableError";
531
+ }
532
+ host;
533
+ method;
534
+ route;
535
+ failure;
536
+ };
537
+ PlatformTransport = class {
538
+ constructor(endpoint, timeoutMs = platformTimeoutMs()) {
539
+ this.endpoint = endpoint;
540
+ this.timeoutMs = timeoutMs;
541
+ }
542
+ endpoint;
543
+ timeoutMs;
544
+ /** A request that legitimately takes longer (a sandbox exec, a world create) waits its own budget; every other one waits the default. */
545
+ budget(ownMs) {
546
+ return Math.max(ownMs ?? 0, this.timeoutMs);
547
+ }
548
+ async send(method, route, body, opts = {}) {
549
+ const timeoutMs = this.budget(opts.timeoutMs);
550
+ const payload = body === void 0 ? {} : { body: JSON.stringify(body) };
551
+ const controller = new AbortController();
552
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
553
+ try {
554
+ const res = await fetch(`${this.endpoint.host}${route}`, {
555
+ method,
556
+ headers: {
557
+ "content-type": "application/json",
558
+ accept: "application/json",
559
+ authorization: "Basic " + Buffer.from(`${this.endpoint.publicKey}:${this.endpoint.secretKey}`).toString("base64")
560
+ },
561
+ ...payload,
562
+ signal: controller.signal
563
+ });
564
+ return { status: res.status, ok: res.ok, text: await res.text() };
565
+ } catch (error) {
566
+ const cause = controller.signal.aborted ? TransportCause.timeout(timeoutMs) : TransportCause.of(error);
567
+ throw new UnreachableError(this.endpoint.host, method, route, cause);
568
+ } finally {
569
+ clearTimeout(timer);
570
+ }
571
+ }
572
+ };
573
+ }
574
+ });
575
+
576
+ // src/worlds/browserReconnect.ts
577
+ async function closeConnection(c) {
578
+ await c.context.close();
579
+ await c.browser.close();
580
+ }
581
+ async function releaseConnection(c) {
582
+ await closeConnection(c).catch(() => void 0);
583
+ }
584
+ function isBrowserGone(error) {
585
+ const message = error instanceof Error ? error.message : String(error);
586
+ if (PAGE_NETWORK_ERROR.test(message)) return false;
587
+ return BROWSER_GONE_PATTERNS.some((p) => p.test(message));
588
+ }
589
+ function refusalIsTransient(error) {
590
+ const { status, code } = error;
591
+ if (typeof status !== "number") return true;
592
+ if (status >= 500) return true;
593
+ return status === 400 && code === "browser_capacity";
594
+ }
595
+ function describe(error) {
596
+ return error instanceof Error ? error.message : String(error);
597
+ }
598
+ var RECOVER_BUDGET_MS, BACKOFF_BASE_MS, BACKOFF_CAP_MS, BROWSER_GONE_PATTERNS, PAGE_NETWORK_ERROR, REDACTED, TOKEN_QUERY_VALUE, SecretScrubber, BrowserReconnected, BrowserUnrecoverable, BrowserReconnector;
599
+ var init_browserReconnect = __esm({
600
+ "src/worlds/browserReconnect.ts"() {
601
+ "use strict";
602
+ RECOVER_BUDGET_MS = 9e4;
603
+ BACKOFF_BASE_MS = 1e3;
604
+ BACKOFF_CAP_MS = 5e3;
605
+ BROWSER_GONE_PATTERNS = [
606
+ /target page, context or browser has been closed/i,
607
+ /\bbrowser has been (closed|disconnected)\b/i,
608
+ /\bbrowser (has )?disconnected\b/i,
609
+ /\btarget closed\b/i,
610
+ /\bwebsocket is not open\b/i,
611
+ /\bconnection closed\b/i
612
+ ];
613
+ PAGE_NETWORK_ERROR = /net::ERR_/i;
614
+ REDACTED = "<redacted>";
615
+ TOKEN_QUERY_VALUE = /([?&]token=)[^&#\s"')]*/gi;
616
+ SecretScrubber = class {
617
+ secrets;
618
+ constructor(secrets) {
619
+ const known = secrets.filter((s) => Boolean(s));
620
+ this.secrets = [
621
+ .../* @__PURE__ */ new Set([...known, ...known.map((s) => encodeURIComponent(s))])
622
+ ].sort((a, b) => b.length - a.length);
623
+ }
624
+ scrub(text2) {
625
+ const bare = this.secrets.reduce(
626
+ (out, secret) => out.split(secret).join(REDACTED),
627
+ text2
628
+ );
629
+ return bare.replace(TOKEN_QUERY_VALUE, `$1${REDACTED}`);
630
+ }
631
+ };
632
+ BrowserReconnected = class extends Error {
633
+ constructor(outcome, restoredUrl, cause) {
634
+ super(
635
+ `the browser was lost mid-action and reconnected (${outcome}); ` + (restoredUrl ? `the page was reopened at ${restoredUrl}. ` : "it is on a blank page. ") + "The action may or may not have taken effect \u2014 look at the page before acting again.",
636
+ { cause }
637
+ );
638
+ this.outcome = outcome;
639
+ this.restoredUrl = restoredUrl;
640
+ this.name = "BrowserReconnected";
641
+ }
642
+ outcome;
643
+ restoredUrl;
644
+ };
645
+ BrowserUnrecoverable = class extends Error {
646
+ constructor(message, cause) {
647
+ super(message, { cause });
648
+ this.name = "BrowserUnrecoverable";
649
+ }
650
+ };
651
+ BrowserReconnector = class {
652
+ constructor(repair, connect, opts = {}) {
653
+ this.repair = repair;
654
+ this.connect = connect;
655
+ this.sleep = opts.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
656
+ this.now = opts.now ?? Date.now;
657
+ this.budgetMs = opts.budgetMs ?? RECOVER_BUDGET_MS;
658
+ this.scrub = opts.scrub ?? ((text2) => text2);
659
+ }
660
+ repair;
661
+ connect;
662
+ sleep;
663
+ now;
664
+ scrub;
665
+ budgetMs;
666
+ /**
667
+ * Repair, reconnect and `restore` until it works or the budget runs out.
668
+ * `restore` receives each new connection (the owner adopts it and reopens
669
+ * its page); a restore that fails counts as a failed reconnect, because the
670
+ * browser may have died again. A repair the platform refuses for good
671
+ * rethrows `cause` untouched.
672
+ */
673
+ async recover(cause, restore) {
674
+ const deadline = this.now() + this.budgetMs;
675
+ let reason = describe(cause);
676
+ for (let attempt = 1; ; attempt++) {
677
+ const step = await this.attempt(restore);
678
+ if (step.kind === "recovered")
679
+ return { outcome: step.outcome, attempts: attempt };
680
+ if (step.kind === "stop") throw cause;
681
+ reason = step.reason;
682
+ const remaining = deadline - this.now();
683
+ if (remaining <= 0) break;
684
+ const backoff = Math.min(
685
+ BACKOFF_BASE_MS * 2 ** (attempt - 1),
686
+ BACKOFF_CAP_MS
687
+ );
688
+ await this.sleep(Math.min(step.waitMs ?? backoff, remaining));
689
+ }
690
+ throw new BrowserUnrecoverable(
691
+ `the session's browser could not be recovered within ${Math.round(this.budgetMs / 1e3)}s: ${this.scrub(reason)}`,
692
+ cause
693
+ );
694
+ }
695
+ async attempt(restore) {
696
+ let answer;
697
+ try {
698
+ answer = await this.repair();
699
+ } catch (error) {
700
+ if (!refusalIsTransient(error)) return { kind: "stop" };
701
+ return {
702
+ kind: "wait",
703
+ reason: `repair failed: ${describe(error)}`,
704
+ waitMs: null
705
+ };
706
+ }
707
+ const outcome = answer.outcome;
708
+ if (outcome === "starting")
709
+ return {
710
+ kind: "wait",
711
+ reason: "a new browser is still starting",
712
+ waitMs: answer.retryAfterMs
713
+ };
714
+ try {
715
+ await restore(await this.connect());
716
+ } catch (error) {
717
+ return {
718
+ kind: "wait",
719
+ reason: `reconnect failed: ${describe(error)}`,
720
+ waitMs: null
721
+ };
722
+ }
723
+ return { kind: "recovered", outcome };
724
+ }
725
+ };
726
+ }
727
+ });
728
+
458
729
  // src/worlds/browser.ts
730
+ function assertBrowserTier(value) {
731
+ if (BROWSER_TIERS.includes(value)) return;
732
+ throw new Error(
733
+ `Unknown browser tier: ${String(value)}; choose from ${BROWSER_TIERS.join(", ")}`
734
+ );
735
+ }
459
736
  function surfaceKinds(s) {
460
737
  const kinds = ["tools"];
461
738
  if (s.api) kinds.push("api");
@@ -463,9 +740,9 @@ function surfaceKinds(s) {
463
740
  if (s.browser) kinds.push("browser");
464
741
  return kinds;
465
742
  }
466
- function uiUrl(ui, path14) {
743
+ function uiUrl(ui, path16) {
467
744
  const base = ui.url.replace(/\/+$/, "");
468
- const rel = path14.startsWith("/") ? path14 : `/${path14}`;
745
+ const rel = path16.startsWith("/") ? path16 : `/${path16}`;
469
746
  if (!ui.token) return base + rel;
470
747
  const [beforeHash, hash] = splitHash(rel);
471
748
  const joiner = beforeHash.includes("?") ? "&" : "?";
@@ -531,19 +808,34 @@ async function openBrowser(surfaces, opts = {}) {
531
808
  const mode = resolveBrowserMode(surfaces, opts.mode ?? "auto");
532
809
  const pw = opts.playwright ?? await loadPlaywright();
533
810
  const viewport = surfaces.browser?.viewport ?? DEFAULT_VIEWPORT;
534
- const browser = mode === "hosted" ? surfaces.browser.protocol === "playwright" ? await pw.chromium.connect(surfaces.browser.wsUrl) : await pw.chromium.connectOverCDP(surfaces.browser.wsUrl) : await pw.chromium.launch({ headless: opts.headless ?? true });
535
- const context4 = await browser.newContext({ viewport });
536
- const page = await context4.newPage();
811
+ const attach = async () => {
812
+ const browser = mode === "hosted" ? surfaces.browser.protocol === "playwright" ? await pw.chromium.connect(surfaces.browser.wsUrl) : await pw.chromium.connectOverCDP(surfaces.browser.wsUrl) : await pw.chromium.launch({ headless: opts.headless ?? true });
813
+ const context4 = await browser.newContext({ viewport });
814
+ return { browser, context: context4, page: await context4.newPage() };
815
+ };
816
+ let live = await attach();
817
+ const reattach = async () => {
818
+ const fresh = await attach();
819
+ await releaseConnection(live);
820
+ live = fresh;
821
+ return fresh;
822
+ };
823
+ const scrubber = new SecretScrubber([
824
+ surfaces.browser?.wsUrl,
825
+ surfaces.ui?.token
826
+ ]);
827
+ const reconnector = mode === "hosted" && surfaces.browser.protocol === "cdp" && opts.repair ? new BrowserReconnector(opts.repair, reattach, {
828
+ scrub: (text2) => scrubber.scrub(text2)
829
+ }) : null;
537
830
  return new WorldBrowser(
538
- page,
831
+ live.page,
539
832
  surfaces.ui,
540
833
  mode,
541
- async () => {
542
- await context4.close();
543
- await browser.close();
544
- },
834
+ () => closeConnection(live),
545
835
  viewport,
546
- opts.recorder ?? null
836
+ opts.recorder ?? null,
837
+ reconnector,
838
+ scrubber
547
839
  );
548
840
  }
549
841
  function computerUseToolkit(browser, opts = {}) {
@@ -595,12 +887,14 @@ function computerUseToolkit(browser, opts = {}) {
595
887
  specs
596
888
  };
597
889
  }
598
- var SURFACE_KINDS, 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, BrowserActionRecorder, WorldBrowser, COMPUTER_USE_SPECS, str;
890
+ var SURFACE_KINDS, 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, BrowserActionRecorder, WorldBrowser, COMPUTER_USE_SPECS, str;
599
891
  var init_browser = __esm({
600
892
  "src/worlds/browser.ts"() {
601
893
  "use strict";
602
894
  init_session();
895
+ init_browserReconnect();
603
896
  SURFACE_KINDS = ["tools", "api", "ui", "browser"];
897
+ BROWSER_TIERS = ["standard", "premium"];
604
898
  DEFAULT_VIEWPORT = { width: 1280, height: 800 };
605
899
  SETTLE_TIMEOUT_MS = 5e3;
606
900
  SETTLE_QUIET_MS = 150;
@@ -617,6 +911,7 @@ var init_browser = __esm({
617
911
  super(`World surface '${surface}' is unavailable: ${reason}`);
618
912
  this.surface = surface;
619
913
  }
914
+ surface;
620
915
  };
621
916
  UI_TOKEN_QUERY = "token";
622
917
  BrowserActionRecorder = class {
@@ -625,6 +920,9 @@ var init_browser = __esm({
625
920
  this.agentId = agentId;
626
921
  this.opts = opts;
627
922
  }
923
+ post;
924
+ agentId;
925
+ opts;
628
926
  seq = 0;
629
927
  base = null;
630
928
  queue = [];
@@ -638,8 +936,8 @@ var init_browser = __esm({
638
936
  }
639
937
  resolveBase() {
640
938
  if (this.base === null) {
641
- const resolve10 = this.opts.resumeFrom ?? (async () => 0);
642
- this.base = resolve10().then((n) => {
939
+ const resolve11 = this.opts.resumeFrom ?? (async () => 0);
940
+ this.base = resolve11().then((n) => {
643
941
  if (!Number.isInteger(n) || n < 0)
644
942
  throw new Error(
645
943
  `browser event base seq must be a non-negative integer, got ${String(n)}`
@@ -708,13 +1006,38 @@ var init_browser = __esm({
708
1006
  }
709
1007
  };
710
1008
  WorldBrowser = class {
711
- constructor(page, ui, mode, teardown, viewport = DEFAULT_VIEWPORT, recorder = null) {
712
- this.page = page;
1009
+ constructor(page, ui, mode, teardown, viewport = DEFAULT_VIEWPORT, recorder = null, reconnector = null, scrubber = new SecretScrubber([ui?.token])) {
713
1010
  this.ui = ui;
714
1011
  this.mode = mode;
715
1012
  this.teardown = teardown;
716
1013
  this.viewport = viewport;
717
1014
  this.recorder = recorder;
1015
+ this.reconnector = reconnector;
1016
+ this.scrubber = scrubber;
1017
+ this.current = page;
1018
+ this.watchNetwork(page);
1019
+ }
1020
+ ui;
1021
+ mode;
1022
+ teardown;
1023
+ viewport;
1024
+ recorder;
1025
+ reconnector;
1026
+ scrubber;
1027
+ current;
1028
+ inflight = 0;
1029
+ lastNetwork = Date.now();
1030
+ /** Where the page last was after an action, token stripped: what a
1031
+ * reconnect reopens. Null until the page has left `about:blank`. */
1032
+ lastUrl = null;
1033
+ /** The live Playwright page; a new object after a reconnect. */
1034
+ get page() {
1035
+ return this.current;
1036
+ }
1037
+ get agentId() {
1038
+ return this.recorder?.agentId ?? null;
1039
+ }
1040
+ watchNetwork(page) {
718
1041
  page.on("request", () => {
719
1042
  this.inflight += 1;
720
1043
  this.lastNetwork = Date.now();
@@ -726,42 +1049,105 @@ var init_browser = __esm({
726
1049
  page.on("requestfinished", done);
727
1050
  page.on("requestfailed", done);
728
1051
  }
729
- inflight = 0;
730
- lastNetwork = Date.now();
731
- get agentId() {
732
- return this.recorder?.agentId ?? null;
1052
+ /** Run `fn` against the page. If it fails because the browser is gone,
1053
+ * recover; then `retry` runs it ONCE more and `report` throws
1054
+ * `BrowserReconnected` instead of replaying it. Any other error, and a
1055
+ * second loss during the retry, propagate unchanged. */
1056
+ async resilient(fn, onLoss) {
1057
+ try {
1058
+ return this.remember(await fn());
1059
+ } catch (error) {
1060
+ if (!this.reconnector || !isBrowserGone(error)) throw error;
1061
+ const recovered = await this.recover(this.reconnector, error);
1062
+ if (onLoss === "report")
1063
+ throw new BrowserReconnected(
1064
+ recovered.outcome,
1065
+ recovered.restoredUrl,
1066
+ error
1067
+ );
1068
+ }
1069
+ return this.remember(await fn());
1070
+ }
1071
+ remember(result) {
1072
+ this.lastUrl = this.openedUrl() ?? this.lastUrl;
1073
+ return result;
1074
+ }
1075
+ /** The page's URL less its token; null while it is blank. */
1076
+ openedUrl() {
1077
+ const url = this.page.url();
1078
+ return url && url !== "about:blank" ? withoutUiToken(url) : null;
1079
+ }
1080
+ async recover(reconnector, cause) {
1081
+ const started = Date.now();
1082
+ const message = cause instanceof Error ? cause.message : String(cause);
1083
+ const args = { cause: this.scrubber.scrub(message).slice(0, 200) };
1084
+ let result;
1085
+ try {
1086
+ result = await reconnector.recover(cause, (c) => this.adopt(c));
1087
+ } catch (error) {
1088
+ await this.report("browser_reconnect", args, started, error);
1089
+ throw error;
1090
+ }
1091
+ const restoredUrl = this.openedUrl();
1092
+ await this.report(
1093
+ "browser_reconnect",
1094
+ { ...args, ...result, restoredUrl },
1095
+ started,
1096
+ null
1097
+ );
1098
+ return { ...result, restoredUrl };
1099
+ }
1100
+ /** Take over a new connection's page and reopen the page the agent was on
1101
+ * (`openBrowser` owns the connection itself). A new browser has no session
1102
+ * cookie, so a World Host UI is first loaded with its token, exactly as
1103
+ * `goto()` loads the entry page. */
1104
+ async adopt(connection) {
1105
+ this.current = connection.page;
1106
+ this.inflight = 0;
1107
+ this.watchNetwork(connection.page);
1108
+ const last = this.lastUrl;
1109
+ if (!last) return;
1110
+ if (this.ui?.token)
1111
+ await this.page.goto(uiEntryUrl(this.ui), { waitUntil: "load" });
1112
+ if (withoutUiToken(this.page.url()) !== last)
1113
+ await this.page.goto(last, { waitUntil: "load" });
1114
+ await this.settle();
733
1115
  }
734
1116
  /** Run one action and report it: the event carries what was asked,
735
1117
  * whether it worked, and the screen after — for failures too, so a
736
1118
  * reviewer sees what the agent saw when the selector did not match. */
737
- async act(action, args, fn) {
738
- const recorder = this.recorder;
739
- if (!recorder) return fn();
1119
+ async act(action, args, fn, onLoss = "report") {
740
1120
  const started = Date.now();
741
- let ok = true;
742
- let error = null;
743
1121
  try {
744
- return await fn();
745
- } catch (err) {
746
- ok = false;
747
- error = (err instanceof Error ? `${err.name}: ${err.message}` : String(err)).slice(0, 4e3);
748
- throw err;
749
- } finally {
750
- recorder.record({
751
- agentId: recorder.agentId,
752
- seq: recorder.nextSeq(),
753
- ts: (/* @__PURE__ */ new Date()).toISOString(),
754
- action,
755
- args: redactActionArgs(action, args),
756
- ok,
757
- error,
758
- durationMs: Date.now() - started,
759
- mode: this.mode,
760
- viewport: { ...this.viewport },
761
- ...await this.observeForEvent()
762
- });
1122
+ const result = await this.resilient(fn, onLoss);
1123
+ await this.report(action, args, started, null);
1124
+ return result;
1125
+ } catch (error) {
1126
+ await this.report(action, args, started, error);
1127
+ throw error;
763
1128
  }
764
1129
  }
1130
+ /** One event on the recorder, if there is one; `failure` null means ok. */
1131
+ async report(action, args, started, failure) {
1132
+ const recorder = this.recorder;
1133
+ if (!recorder) return;
1134
+ const error = failure === null ? null : this.scrubber.scrub(
1135
+ failure instanceof Error ? `${failure.name}: ${failure.message}` : String(failure)
1136
+ ).slice(0, 4e3);
1137
+ recorder.record({
1138
+ agentId: recorder.agentId,
1139
+ seq: recorder.nextSeq(),
1140
+ ts: (/* @__PURE__ */ new Date()).toISOString(),
1141
+ action,
1142
+ args: redactActionArgs(action, args),
1143
+ ok: failure === null,
1144
+ error,
1145
+ durationMs: Date.now() - started,
1146
+ mode: this.mode,
1147
+ viewport: { ...this.viewport },
1148
+ ...await this.observeForEvent()
1149
+ });
1150
+ }
765
1151
  async observeForEvent() {
766
1152
  const out = {
767
1153
  url: null,
@@ -808,7 +1194,9 @@ var init_browser = __esm({
808
1194
  await this.page.goto(target, { waitUntil: "load" });
809
1195
  await this.settle();
810
1196
  return this.page.url();
811
- }
1197
+ },
1198
+ // Navigating again lands on the same page: safe to replay.
1199
+ "retry"
812
1200
  );
813
1201
  }
814
1202
  async back() {
@@ -861,22 +1249,25 @@ var init_browser = __esm({
861
1249
  );
862
1250
  }
863
1251
  async screenshot(fullPage = false) {
864
- return this.page.screenshot({ type: "png", fullPage });
1252
+ return this.resilient(
1253
+ () => this.page.screenshot({ type: "png", fullPage }),
1254
+ "retry"
1255
+ );
865
1256
  }
866
1257
  async screenshotBase64(fullPage = false) {
867
1258
  return (await this.screenshot(fullPage)).toString("base64");
868
1259
  }
869
1260
  async text(selector = "body") {
870
- return this.page.innerText(selector);
1261
+ return this.resilient(() => this.page.innerText(selector), "retry");
871
1262
  }
872
1263
  async html() {
873
- return this.page.content();
1264
+ return this.resilient(() => this.page.content(), "retry");
874
1265
  }
875
1266
  get url() {
876
1267
  return this.page.url();
877
1268
  }
878
1269
  async title() {
879
- return this.page.title();
1270
+ return this.resilient(() => this.page.title(), "retry");
880
1271
  }
881
1272
  async close() {
882
1273
  try {
@@ -932,6 +1323,82 @@ var init_browser = __esm({
932
1323
  }
933
1324
  });
934
1325
 
1326
+ // src/worlds/sessionContract.ts
1327
+ function serializeCallBody(body) {
1328
+ const text2 = JSON.stringify(body);
1329
+ const size = Buffer.byteLength(text2, "utf8");
1330
+ if (size > CALL_BODY_LIMIT_BYTES) throw new WorldCallTooLarge(size);
1331
+ return text2;
1332
+ }
1333
+ function idleWarning(idleExpiresAt, now = /* @__PURE__ */ new Date()) {
1334
+ if (!idleExpiresAt) return null;
1335
+ const leftMs = new Date(idleExpiresAt).getTime() - now.getTime();
1336
+ if (leftMs >= IDLE_WARNING_MINUTES * 6e4) return null;
1337
+ const minutes = Math.max(0, Math.floor(leftMs / 6e4));
1338
+ return `warning: session expires in ${minutes}m (idle TTL); call a tool to extend it or \`gateway worlds session pin\` to keep it`;
1339
+ }
1340
+ var CALL_BODY_LIMIT_BYTES, CALL_BODY_LIMIT_LABEL, IDLE_WARNING_MINUTES, EXPLORATORY_TASK, EXPLORATORY_TASK_SOURCE, NO_GRADER_REASON, WorldCallTooLarge;
1341
+ var init_sessionContract = __esm({
1342
+ "src/worlds/sessionContract.ts"() {
1343
+ "use strict";
1344
+ CALL_BODY_LIMIT_BYTES = 4 * 1024 * 1024;
1345
+ CALL_BODY_LIMIT_LABEL = "4mb";
1346
+ IDLE_WARNING_MINUTES = 5;
1347
+ EXPLORATORY_TASK = Object.freeze({
1348
+ instruction: "exploratory session"
1349
+ });
1350
+ EXPLORATORY_TASK_SOURCE = "none";
1351
+ NO_GRADER_REASON = "no grader";
1352
+ WorldCallTooLarge = class extends Error {
1353
+ constructor(size, limitBytes = CALL_BODY_LIMIT_BYTES, limit = CALL_BODY_LIMIT_LABEL) {
1354
+ super(
1355
+ `call body is ${size} bytes; the platform accepts at most ${limit} (${limitBytes} bytes)`
1356
+ );
1357
+ this.size = size;
1358
+ this.limitBytes = limitBytes;
1359
+ this.limit = limit;
1360
+ this.name = "WorldCallTooLarge";
1361
+ }
1362
+ size;
1363
+ limitBytes;
1364
+ limit;
1365
+ code = "payload_too_large";
1366
+ /** The structured refusal the CLIs print. */
1367
+ toJSON() {
1368
+ return {
1369
+ status: "error",
1370
+ code: this.code,
1371
+ limit: this.limit,
1372
+ size: this.size
1373
+ };
1374
+ }
1375
+ };
1376
+ }
1377
+ });
1378
+
1379
+ // src/worlds/taskRef.ts
1380
+ var isTaskIdRef, isTaskSpec, taskLabel, assertTaskRef;
1381
+ var init_taskRef = __esm({
1382
+ "src/worlds/taskRef.ts"() {
1383
+ "use strict";
1384
+ isTaskIdRef = (task) => typeof task === "object" && task !== null && "id" in task;
1385
+ isTaskSpec = (task) => typeof task === "object" && task !== null && "instruction" in task;
1386
+ taskLabel = (task, info) => {
1387
+ if (typeof task === "string") return task;
1388
+ if (isTaskIdRef(task)) return info?.name ?? task.id;
1389
+ if (task.name) return task.name;
1390
+ return info?.hash ? `inline:${info.hash.slice(0, 12)}` : "inline";
1391
+ };
1392
+ assertTaskRef = (task) => {
1393
+ const malformed = task === null || typeof task === "string" && !task || isTaskIdRef(task) && !task.id || isTaskSpec(task) && !task.instruction || typeof task === "object" && !isTaskIdRef(task) && !isTaskSpec(task);
1394
+ if (malformed)
1395
+ throw new Error(
1396
+ "openSession needs a task: a bundled task name, a stored task { id, version? } or { instruction, seed?, grader?, metadata? } \u2014 or none at all for an exploratory session"
1397
+ );
1398
+ };
1399
+ }
1400
+ });
1401
+
935
1402
  // src/worlds/session.ts
936
1403
  var session_exports = {};
937
1404
  __export(session_exports, {
@@ -947,6 +1414,34 @@ __export(session_exports, {
947
1414
  schemaFromSignature: () => schemaFromSignature,
948
1415
  taskLabel: () => taskLabel
949
1416
  });
1417
+ function numericGrade(record) {
1418
+ const rewards = {};
1419
+ const nested = record.rewards;
1420
+ if (nested && typeof nested === "object") {
1421
+ for (const [key2, value] of Object.entries(nested)) {
1422
+ if (typeof value === "number") rewards[key2] = value;
1423
+ }
1424
+ }
1425
+ for (const [key2, value] of Object.entries(record)) {
1426
+ if (key2 !== "reward" && typeof value === "number") rewards[key2] = value;
1427
+ }
1428
+ return {
1429
+ reward: typeof record.reward === "number" ? record.reward : null,
1430
+ rewards
1431
+ };
1432
+ }
1433
+ function verifierGrades(value) {
1434
+ if (!value || typeof value !== "object") return void 0;
1435
+ const out = {};
1436
+ for (const [name, grade] of Object.entries(value)) {
1437
+ const record = grade && typeof grade === "object" ? grade : {};
1438
+ out[name] = {
1439
+ ...numericGrade(record),
1440
+ ...typeof record.error === "string" ? { error: record.error } : {}
1441
+ };
1442
+ }
1443
+ return out;
1444
+ }
950
1445
  function schemaFromSignature(spec) {
951
1446
  if (spec.inputSchema)
952
1447
  return {
@@ -1006,12 +1501,9 @@ async function attachSession(sessionId, options = {}) {
1006
1501
  );
1007
1502
  return new WorldSession(sessionId, state2, options);
1008
1503
  }
1009
- async function openSession(slugOrRef, taskOrOpts, positionalOpts = {}) {
1010
- const { task, ...opts } = typeof taskOrOpts === "object" && "task" in taskOrOpts ? taskOrOpts : { task: taskOrOpts, ...positionalOpts };
1011
- if (task === void 0 || task === null || typeof task === "string" && !task || isTaskIdRef(task) && !task.id || isTaskSpec(task) && !task.instruction || typeof task === "object" && !isTaskIdRef(task) && !isTaskSpec(task))
1012
- throw new Error(
1013
- "openSession needs a task: a bundled task name, a stored task { id, version? } or { instruction, seed?, grader?, metadata? }"
1014
- );
1504
+ async function openSession(slugOrRef, taskOrOpts = {}, positionalOpts = {}) {
1505
+ const { task, ...opts } = isOpenSessionOptions(taskOrOpts) ? taskOrOpts : { task: taskOrOpts, ...positionalOpts };
1506
+ if (task !== void 0) assertTaskRef(task);
1015
1507
  const options = opts.options ?? {};
1016
1508
  const unknown = (opts.surfaces ?? []).filter(
1017
1509
  (s) => !SURFACE_KINDS.includes(s)
@@ -1020,6 +1512,7 @@ async function openSession(slugOrRef, taskOrOpts, positionalOpts = {}) {
1020
1512
  throw new Error(
1021
1513
  `Unknown world surfaces: ${unknown.join(", ")}; choose from ${SURFACE_KINDS.join(", ")}`
1022
1514
  );
1515
+ if (opts.browserTier !== void 0) assertBrowserTier(opts.browserTier);
1023
1516
  const at = slugOrRef.indexOf("@");
1024
1517
  const slug = at === -1 ? slugOrRef : slugOrRef.slice(0, at);
1025
1518
  const ref = at === -1 ? "" : slugOrRef.slice(at + 1);
@@ -1029,9 +1522,10 @@ async function openSession(slugOrRef, taskOrOpts, positionalOpts = {}) {
1029
1522
  "/api/public/world-sessions",
1030
1523
  {
1031
1524
  ...opts.versionId ? { versionId: opts.versionId } : { slug, ...ref && { ref } },
1032
- task,
1525
+ ...task === void 0 ? {} : { task },
1033
1526
  ...opts.reuseWarm === void 0 ? {} : { reuseWarm: opts.reuseWarm },
1034
- ...opts.surfaces?.length ? { surfaces: opts.surfaces } : {}
1527
+ ...opts.surfaces?.length ? { surfaces: opts.surfaces } : {},
1528
+ ...opts.browserTier === void 0 ? {} : { browserTier: opts.browserTier }
1035
1529
  }
1036
1530
  );
1037
1531
  return new WorldSession(state2.sessionId, state2, options);
@@ -1107,21 +1601,16 @@ async function runSessions(opts) {
1107
1601
  passed: failed === 0 && (opts.failUnder === void 0 || mean >= opts.failUnder)
1108
1602
  };
1109
1603
  }
1110
- var import_node_crypto, isTaskIdRef, isTaskSpec, taskLabel, READY_TIMEOUT_MS, READY_POLL_MS, CALL_TIMEOUT_MS, CALL_POLL_MS, JUDGED_GRADE_TIMEOUT_MS, JUDGED_GRADE_POLL_MS, EXPORT_PAGE, sleep2, modelToolName, WorldSessionTimeout, WorldSessionCallError, WorldSession;
1604
+ var import_node_crypto, READY_TIMEOUT_MS, READY_POLL_MS, CALL_TIMEOUT_MS, CALL_POLL_MS, JUDGED_GRADE_TIMEOUT_MS, JUDGED_GRADE_POLL_MS, EXPORT_PAGE, sleep2, modelToolName, WorldSessionTimeout, WorldSessionCallError, WorldSession, OPEN_SESSION_OPTION_KEYS, isOpenSessionOptions;
1111
1605
  var init_session = __esm({
1112
1606
  "src/worlds/session.ts"() {
1113
1607
  "use strict";
1114
1608
  import_node_crypto = require("crypto");
1115
1609
  init_worlds();
1116
1610
  init_browser();
1117
- isTaskIdRef = (task) => typeof task === "object" && task !== null && "id" in task;
1118
- isTaskSpec = (task) => typeof task === "object" && task !== null && "instruction" in task;
1119
- taskLabel = (task, info) => {
1120
- if (typeof task === "string") return task;
1121
- if (isTaskIdRef(task)) return info?.name ?? task.id;
1122
- if (task.name) return task.name;
1123
- return info?.hash ? `inline:${info.hash.slice(0, 12)}` : "inline";
1124
- };
1611
+ init_sessionContract();
1612
+ init_taskRef();
1613
+ init_taskRef();
1125
1614
  READY_TIMEOUT_MS = 10 * 6e4;
1126
1615
  READY_POLL_MS = 2e3;
1127
1616
  CALL_TIMEOUT_MS = 3 * 6e4;
@@ -1141,16 +1630,25 @@ var init_session = __esm({
1141
1630
  this.current = current;
1142
1631
  this.options = options;
1143
1632
  }
1633
+ sessionId;
1634
+ current;
1635
+ options;
1144
1636
  /** The task's display name: a bundled scenario's, or the inline spec's
1145
- * `name` (null when the spec was unnamed). Same as `taskName`. */
1146
- get task() {
1147
- return this.current.taskName;
1148
- }
1149
- /** The task's display name: a bundled scenario's, or the inline spec's
1150
- * `name` (null when the spec was unnamed). */
1637
+ * `name` (null when the spec was unnamed). `task` is the same. */
1151
1638
  get taskName() {
1152
1639
  return this.current.taskName;
1153
1640
  }
1641
+ get task() {
1642
+ return this.taskName;
1643
+ }
1644
+ /** `{idleExpiresAt, pinned}` as of the last state read: when the fleet
1645
+ * reaps the session (null once pinned), and whether it is pinned. */
1646
+ get idle() {
1647
+ return {
1648
+ idleExpiresAt: this.current.idleExpiresAt ?? null,
1649
+ pinned: this.current.pinned ?? false
1650
+ };
1651
+ }
1154
1652
  /** The platform's notices about the world this session runs on (empty
1155
1653
  * for a schema world). Printed by the CLI on stderr at open. */
1156
1654
  get deprecations() {
@@ -1224,23 +1722,37 @@ var init_session = __esm({
1224
1722
  const { agentId, record = true, ...rest } = opts;
1225
1723
  return openBrowser(await this.surfaces(), {
1226
1724
  ...rest,
1227
- recorder: record ? this.browserRecorder(agentId) : null
1725
+ recorder: record ? this.browserRecorder(agentId) : null,
1726
+ repair: () => this.repairBrowser()
1228
1727
  });
1229
1728
  }
1729
+ /** Ask the platform to make this session's hosted browser reachable again
1730
+ * after its connection dropped: `healthy` (reconnect now), `replaced` (a new,
1731
+ * blank browser behind the same wsUrl; reconnect and reopen your page) or
1732
+ * `starting` (ask again in `retryAfterMs`). `browser()` does this on its
1733
+ * own; call it when you drive your own Playwright against `wsUrl`. */
1734
+ async repairBrowser() {
1735
+ return apiRequest(
1736
+ this.options,
1737
+ "POST",
1738
+ `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/browser-repair`,
1739
+ {}
1740
+ );
1741
+ }
1230
1742
  /** The reporter `browser()` uses; exposed for a page you drive yourself. */
1231
1743
  browserRecorder(agentId) {
1232
- const path14 = `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/browser-events`;
1744
+ const path16 = `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/browser-events`;
1233
1745
  const id = agentId ?? process.env.GATEWAY_AGENT_ID ?? `agent-${(0, import_node_crypto.randomUUID)().replace(/-/g, "").slice(0, 8)}`;
1234
1746
  return new BrowserActionRecorder(
1235
1747
  async (events) => {
1236
- await apiRequest(this.options, "POST", path14, { events });
1748
+ await apiRequest(this.options, "POST", path16, { events });
1237
1749
  },
1238
1750
  id,
1239
1751
  {
1240
1752
  // Continue this agent's timeline where the platform has it, so the
1241
1753
  // same id reopened later never re-numbers from zero.
1242
1754
  resumeFrom: async () => {
1243
- const summary = await apiRequest(this.options, "GET", path14);
1755
+ const summary = await apiRequest(this.options, "GET", path16);
1244
1756
  return summary.agents.find((a) => a.agentId === id)?.nextSeq ?? 0;
1245
1757
  }
1246
1758
  }
@@ -1288,6 +1800,7 @@ var init_session = __esm({
1288
1800
  }
1289
1801
  /** Enqueue one interaction and wait for the container's answer. */
1290
1802
  async exchange(body, timeoutMs) {
1803
+ serializeCallBody(body);
1291
1804
  const enqueued = await apiRequest(
1292
1805
  this.options,
1293
1806
  "POST",
@@ -1359,26 +1872,25 @@ var init_session = __esm({
1359
1872
  * the judge's budget (15 min) instead of a call's. `timeoutMs` overrides
1360
1873
  * either. `report` is the agent's own account of what it did and found,
1361
1874
  * handed to the judge as its claim beside the evidence (the state and the
1362
- * calls); assertions and python graders ignore it. */
1875
+ * calls); assertions and python graders ignore it. `worlds` names the
1876
+ * task's other sessions by alias (`{alias: sessionId}`): the platform
1877
+ * reads each one's evidence and hands it to the cross-world verifiers
1878
+ * anchored on this session, whose grades come back under `verifiers`. */
1363
1879
  async grade(opts = {}) {
1364
1880
  const raw = await this.exchange(
1365
- opts.report !== void 0 ? { kind: "grade", report: opts.report } : { kind: "grade" },
1881
+ {
1882
+ kind: "grade",
1883
+ ...opts.report !== void 0 ? { report: opts.report } : {},
1884
+ ...opts.worlds && Object.keys(opts.worlds).length > 0 ? { worlds: opts.worlds } : {}
1885
+ },
1366
1886
  opts.timeoutMs
1367
1887
  );
1368
1888
  const record = raw && typeof raw === "object" ? raw : {};
1369
- const rewards = {};
1370
- const nested = record.rewards;
1371
- if (nested && typeof nested === "object") {
1372
- for (const [key2, value] of Object.entries(nested)) {
1373
- if (typeof value === "number") rewards[key2] = value;
1374
- }
1375
- }
1376
- for (const [key2, value] of Object.entries(record)) {
1377
- if (key2 !== "reward" && typeof value === "number") rewards[key2] = value;
1378
- }
1889
+ const verifiers = verifierGrades(record.verifiers);
1379
1890
  return {
1380
- reward: typeof record.reward === "number" ? record.reward : null,
1381
- rewards,
1891
+ ...numericGrade(record),
1892
+ ...typeof record.reason === "string" ? { reason: record.reason } : {},
1893
+ ...verifiers ? { verifiers } : {},
1382
1894
  raw
1383
1895
  };
1384
1896
  }
@@ -1485,6 +1997,46 @@ var init_session = __esm({
1485
1997
  );
1486
1998
  }
1487
1999
  };
2000
+ OPEN_SESSION_OPTION_KEYS = /* @__PURE__ */ new Set([
2001
+ "task",
2002
+ "versionId",
2003
+ "reuseWarm",
2004
+ "surfaces",
2005
+ "browserTier",
2006
+ "options"
2007
+ ]);
2008
+ isOpenSessionOptions = (value) => typeof value === "object" && value !== null && Object.keys(value).every((key2) => OPEN_SESSION_OPTION_KEYS.has(key2));
2009
+ }
2010
+ });
2011
+
2012
+ // src/worlds/sessionList.ts
2013
+ async function listSessions(filter = {}, options = {}) {
2014
+ const params = new URLSearchParams();
2015
+ if (filter.state) params.set("state", filter.state);
2016
+ if (filter.slug) params.set("slug", filter.slug);
2017
+ if (filter.limit !== void 0) params.set("limit", String(filter.limit));
2018
+ const qs3 = params.toString();
2019
+ const res = await apiRequest(
2020
+ options,
2021
+ "GET",
2022
+ `/api/public/world-sessions${qs3 ? `?${qs3}` : ""}`
2023
+ );
2024
+ return res.sessions;
2025
+ }
2026
+ var SESSION_STATES;
2027
+ var init_sessionList = __esm({
2028
+ "src/worlds/sessionList.ts"() {
2029
+ "use strict";
2030
+ init_worlds();
2031
+ SESSION_STATES = [
2032
+ "PROVISIONING",
2033
+ "RUNNING",
2034
+ "IDLE",
2035
+ "STOPPING",
2036
+ "STOPPED",
2037
+ "FAILED",
2038
+ "LOST"
2039
+ ];
1488
2040
  }
1489
2041
  });
1490
2042
 
@@ -1570,16 +2122,23 @@ function aggregateTaskGrade(worlds) {
1570
2122
  const rewards = {};
1571
2123
  const ungraded = [];
1572
2124
  const graded = [];
1573
- for (const [alias, grade] of Object.entries(worlds)) {
2125
+ const verifiers = {};
2126
+ const fold = (key2, grade) => {
1574
2127
  if (typeof grade.reward === "number") {
1575
- rewards[alias] = grade.reward;
2128
+ rewards[key2] = grade.reward;
1576
2129
  graded.push(grade.reward);
1577
- } else ungraded.push(alias);
1578
- for (const [key2, value] of Object.entries(grade.rewards))
1579
- rewards[`${alias}.${key2}`] = value;
2130
+ } else ungraded.push(key2);
2131
+ for (const [name, value] of Object.entries(grade.rewards))
2132
+ rewards[`${key2}.${name}`] = value;
2133
+ };
2134
+ for (const [alias, grade] of Object.entries(worlds)) {
2135
+ fold(alias, grade);
2136
+ Object.assign(verifiers, grade.verifiers ?? {});
1580
2137
  }
2138
+ for (const [name, grade] of Object.entries(verifiers))
2139
+ fold(`${VERIFIER_REWARD_PREFIX}${name}`, grade);
1581
2140
  const reward = graded.length > 0 ? graded.reduce((a, b) => a + b, 0) / graded.length : null;
1582
- return { reward, rewards, worlds, ungraded };
2141
+ return { reward, rewards, worlds, ungraded, verifiers };
1583
2142
  }
1584
2143
  function fromResponse(answer, options) {
1585
2144
  const sessions2 = {};
@@ -1612,6 +2171,7 @@ async function openTask(ref, opts = {}) {
1612
2171
  throw new Error(
1613
2172
  "openTask needs a spec that names its worlds; a single-world spec opens with openSession"
1614
2173
  );
2174
+ if (opts.browserTier !== void 0) assertBrowserTier(opts.browserTier);
1615
2175
  const answer = await apiRequest(
1616
2176
  options,
1617
2177
  "POST",
@@ -1619,7 +2179,8 @@ async function openTask(ref, opts = {}) {
1619
2179
  {
1620
2180
  task,
1621
2181
  ...opts.reuseWarm === void 0 ? {} : { reuseWarm: opts.reuseWarm },
1622
- ...opts.surfaces?.length ? { surfaces: opts.surfaces } : {}
2182
+ ...opts.surfaces?.length ? { surfaces: opts.surfaces } : {},
2183
+ ...opts.browserTier === void 0 ? {} : { browserTier: opts.browserTier }
1623
2184
  }
1624
2185
  );
1625
2186
  return fromResponse(answer, options);
@@ -1695,7 +2256,7 @@ async function attachManifest(manifest, options = {}) {
1695
2256
  function isTaskManifest(value) {
1696
2257
  return typeof value === "object" && value !== null && !Array.isArray(value) && typeof value.sessions === "object" && value.sessions !== null && !("instruction" in value && "worlds" in value);
1697
2258
  }
1698
- var TASK_SESSIONS, manifestSession, TaskSessions;
2259
+ var TASK_SESSIONS, VERIFIER_REWARD_PREFIX, manifestSession, TaskSessions;
1699
2260
  var init_taskSessions = __esm({
1700
2261
  "src/worlds/taskSessions.ts"() {
1701
2262
  "use strict";
@@ -1703,6 +2264,7 @@ var init_taskSessions = __esm({
1703
2264
  init_browser();
1704
2265
  init_session();
1705
2266
  TASK_SESSIONS = "/api/public/world-task-sessions";
2267
+ VERIFIER_REWARD_PREFIX = "x.";
1706
2268
  manifestSession = (s, state2, world) => ({
1707
2269
  slug: world.slug,
1708
2270
  ref: world.ref,
@@ -1733,6 +2295,13 @@ var init_taskSessions = __esm({
1733
2295
  this.worlds = worlds;
1734
2296
  this.hash = hash;
1735
2297
  }
2298
+ taskId;
2299
+ taskVersion;
2300
+ name;
2301
+ instruction;
2302
+ sessions;
2303
+ worlds;
2304
+ hash;
1736
2305
  /** This alias's `{slug, ref}` as recorded at open/attach — the world a
1737
2306
  * `TaskRun` filing needs to name, without exposing the whole map. */
1738
2307
  worldRef(alias) {
@@ -1792,10 +2361,20 @@ var init_taskSessions = __esm({
1792
2361
  }
1793
2362
  /** Grade every world and aggregate — see `TaskGrade`. One `report` (the
1794
2363
  * agent's own account of the whole investigation) goes to every world's
1795
- * judge; a world graded by assertions or python ignores it. */
2364
+ * judge; a world graded by assertions or python ignores it. Each grade
2365
+ * names the task's other sessions by alias, so the cross-world verifiers
2366
+ * anchored on that world can read them. */
1796
2367
  async grade(opts = {}) {
1797
2368
  return aggregateTaskGrade(
1798
- await this.each((session) => session.grade(opts))
2369
+ await this.each(
2370
+ (session, alias) => session.grade({ ...opts, worlds: this.otherSessions(alias) })
2371
+ )
2372
+ );
2373
+ }
2374
+ /** The task's other sessions by alias: what a grade names. */
2375
+ otherSessions(alias) {
2376
+ return Object.fromEntries(
2377
+ Object.entries(this.sessions).filter(([other]) => other !== alias).map(([other, session]) => [other, session.sessionId])
1799
2378
  );
1800
2379
  }
1801
2380
  /** Every world's call log, keyed by alias. */
@@ -1841,10 +2420,11 @@ var init_evals = __esm({
1841
2420
  constructor(options = {}) {
1842
2421
  this.options = options;
1843
2422
  }
1844
- /** Anchor a new evaluation to `versionId`; returns its id. */
2423
+ options;
1845
2424
  async createEvaluation(versionId, opts = {}) {
1846
2425
  const body = { versionId };
1847
2426
  if (opts.model !== void 0) body.model = opts.model;
2427
+ if (opts.runId !== void 0) body.runId = opts.runId;
1848
2428
  if (opts.rolloutsPerExample !== void 0)
1849
2429
  body.rolloutsPerExample = opts.rolloutsPerExample;
1850
2430
  if (opts.metadata !== void 0) body.metadata = opts.metadata;
@@ -1856,7 +2436,6 @@ var init_evals = __esm({
1856
2436
  );
1857
2437
  return answer.evaluationId;
1858
2438
  }
1859
- /** Push one batch of samples; returns how many the platform inserted. */
1860
2439
  async pushSamples(evaluationId, samples) {
1861
2440
  const answer = await apiRequest(
1862
2441
  this.options,
@@ -1866,7 +2445,6 @@ var init_evals = __esm({
1866
2445
  );
1867
2446
  return answer.inserted ?? samples.length;
1868
2447
  }
1869
- /** Close the evaluation out; returns its final status. */
1870
2448
  async finalizeEvaluation(evaluationId, opts = {}) {
1871
2449
  const body = {
1872
2450
  status: opts.status ?? "COMPLETED"
@@ -1968,9 +2546,9 @@ function getAmbientSessionId() {
1968
2546
  return currentSessionStorage.getStore();
1969
2547
  }
1970
2548
  function withSession(sessionId, fn) {
1971
- return new Promise((resolve10, reject) => {
2549
+ return new Promise((resolve11, reject) => {
1972
2550
  currentSessionStorage.run(sessionId, () => {
1973
- Promise.resolve().then(fn).then(resolve10, reject);
2551
+ Promise.resolve().then(fn).then(resolve11, reject);
1974
2552
  });
1975
2553
  });
1976
2554
  }
@@ -2003,7 +2581,7 @@ var require_package = __commonJS({
2003
2581
  "package.json"(exports2, module2) {
2004
2582
  module2.exports = {
2005
2583
  name: "@withgateway/sdk",
2006
- version: "0.2.6",
2584
+ version: "0.2.9",
2007
2585
  description: "Gateway SDK for TypeScript - A/B experiments, tracing, and observability",
2008
2586
  main: "./dist/index.js",
2009
2587
  module: "./dist/index.mjs",
@@ -2158,16 +2736,16 @@ var require_package = __commonJS({
2158
2736
  }
2159
2737
  },
2160
2738
  optionalDependencies: {
2161
- "@arizeai/openinference-instrumentation-anthropic": "^0.1.15",
2162
- "@arizeai/openinference-instrumentation-openai": "^4.1.5"
2739
+ "@arizeai/openinference-instrumentation-anthropic": "^0.2.8",
2740
+ "@arizeai/openinference-instrumentation-openai": "^4.2.7"
2163
2741
  },
2164
2742
  devDependencies: {
2165
- "@anthropic-ai/sdk": "^0.79.0",
2743
+ "@anthropic-ai/sdk": "^0.91.1",
2166
2744
  "@opentelemetry/api": "^1.9.0",
2167
- "@opentelemetry/exporter-trace-otlp-http": "^0.212.0",
2168
- "@opentelemetry/resources": "^2.6.0",
2169
- "@opentelemetry/sdk-trace-base": "^1.30.1",
2170
- "@opentelemetry/sdk-trace-node": "^2.6.0",
2745
+ "@opentelemetry/exporter-trace-otlp-http": "^0.222.0",
2746
+ "@opentelemetry/resources": "^2.11.0",
2747
+ "@opentelemetry/sdk-trace-base": "^2.11.0",
2748
+ "@opentelemetry/sdk-trace-node": "^2.11.0",
2171
2749
  "@opentelemetry/semantic-conventions": "^1.40.0",
2172
2750
  "@types/node": "^20.0.0",
2173
2751
  openai: "^4.70.0",
@@ -2180,7 +2758,9 @@ var require_package = __commonJS({
2180
2758
  protobufjs: "^8.4.1",
2181
2759
  "vite@6": "^6.4.3",
2182
2760
  postcss: "^8.5.18",
2183
- "picomatch@4": "^4.0.4"
2761
+ "picomatch@4": "^4.0.4",
2762
+ nanoid: ">=3.3.18",
2763
+ esbuild: ">=0.28.1"
2184
2764
  },
2185
2765
  pnpm: {
2186
2766
  overrides: {
@@ -2188,7 +2768,9 @@ var require_package = __commonJS({
2188
2768
  vitest: "^3.2.6",
2189
2769
  "vite@6": "^6.4.3",
2190
2770
  postcss: "^8.5.18",
2191
- "picomatch@4": "^4.0.4"
2771
+ "picomatch@4": "^4.0.4",
2772
+ nanoid: ">=3.3.18",
2773
+ esbuild: ">=0.28.1"
2192
2774
  }
2193
2775
  },
2194
2776
  bin: {
@@ -2791,7 +3373,7 @@ function worldRef(live, alias) {
2791
3373
  sessionId: session.sessionId
2792
3374
  };
2793
3375
  }
2794
- async function fileTaskRun(live, runId, model, report, grade, agentError, traced, runDir, options) {
3376
+ async function fileTaskRun(live, runId, model, report, grade, agentError, traced, runDir, options, setRunId) {
2795
3377
  const aliases = live.aliases;
2796
3378
  const anchor = aliases[0];
2797
3379
  const worldsMeta = Object.fromEntries(
@@ -2803,6 +3385,7 @@ async function fileTaskRun(live, runId, model, report, grade, agentError, traced
2803
3385
  {
2804
3386
  model,
2805
3387
  rolloutsPerExample: 1,
3388
+ ...setRunId ? { runId: setRunId } : {},
2806
3389
  metadata: {
2807
3390
  source: "worlds-task-run",
2808
3391
  task: {
@@ -2885,6 +3468,7 @@ async function runTask(ref, agent, opts) {
2885
3468
  const live = await openTask(ref, {
2886
3469
  surfaces: opts.surfaces,
2887
3470
  reuseWarm: opts.reuseWarm,
3471
+ browserTier: opts.browserTier,
2888
3472
  options
2889
3473
  });
2890
3474
  const started = Date.now();
@@ -2920,6 +3504,8 @@ async function runTask(ref, agent, opts) {
2920
3504
  const message = (error instanceof Error ? error.message : String(error)) || "Unknown error";
2921
3505
  agentError = message.slice(0, 2e3);
2922
3506
  }
3507
+ if (traced)
3508
+ await Promise.resolve().then(() => (init_init(), init_exports)).then((tracing2) => tracing2.flush()).catch(() => void 0);
2923
3509
  const grade = report !== null ? await live.grade({ report }) : await live.grade();
2924
3510
  fs.writeFileSync(
2925
3511
  path.join(runDir, "manifest.json"),
@@ -2960,7 +3546,8 @@ async function runTask(ref, agent, opts) {
2960
3546
  agentError,
2961
3547
  traced,
2962
3548
  runDir,
2963
- options
3549
+ options,
3550
+ opts.setRunId
2964
3551
  );
2965
3552
  summary.filed = true;
2966
3553
  }
@@ -2997,8 +3584,12 @@ var init_taskRun = __esm({
2997
3584
  this.sessions = sessions2;
2998
3585
  this.manifest = manifest;
2999
3586
  }
3587
+ runId;
3588
+ instruction;
3589
+ model;
3590
+ sessions;
3591
+ manifest;
3000
3592
  notes = {};
3001
- /** The alias's session, or a clear error naming the aliases there are. */
3002
3593
  session(alias) {
3003
3594
  const session = this.sessions[alias];
3004
3595
  if (!session)
@@ -3007,8 +3598,7 @@ var init_taskRun = __esm({
3007
3598
  );
3008
3599
  return session;
3009
3600
  }
3010
- /** `alias`'s HTTP API. Raises the same error the session itself would
3011
- * when it was not opened with `surfaces: ["api"]`. */
3601
+ /** Raises when the session was not opened with `surfaces: ["api"]`. */
3012
3602
  async api(alias) {
3013
3603
  const surfaces = await this.session(alias).surfaces();
3014
3604
  if (!surfaces.api)
@@ -3018,10 +3608,7 @@ var init_taskRun = __esm({
3018
3608
  );
3019
3609
  return { url: surfaces.api.url, token: surfaces.api.token };
3020
3610
  }
3021
- /** Every world's tools merged into one toolkit, each name prefixed
3022
- * `<alias>.<tool>` so a model can tell which world a call goes to. A
3023
- * world that exposes no tools contributes nothing — there is nothing to
3024
- * merge. */
3611
+ /** Each tool is prefixed `<alias>.<tool>` so a model can tell which world a call goes to. */
3025
3612
  async toolkit() {
3026
3613
  const schemas = [];
3027
3614
  const impls = {};
@@ -3046,8 +3633,7 @@ var init_taskRun = __esm({
3046
3633
  }
3047
3634
  return { schemas, impls, specs };
3048
3635
  }
3049
- /** Log arbitrary notes into this run's `run.json` (merged; a later call
3050
- * overrides a key an earlier one set). */
3636
+ /** Merged into `run.json` under `notes`; a later call overrides an earlier key. */
3051
3637
  record(notes) {
3052
3638
  Object.assign(this.notes, notes);
3053
3639
  }
@@ -3057,23 +3643,263 @@ var init_taskRun = __esm({
3057
3643
  }
3058
3644
  });
3059
3645
 
3646
+ // src/worlds/checkoutProvenance.ts
3647
+ var import_node_child_process, CheckoutProvenance;
3648
+ var init_checkoutProvenance = __esm({
3649
+ "src/worlds/checkoutProvenance.ts"() {
3650
+ "use strict";
3651
+ import_node_child_process = require("child_process");
3652
+ CheckoutProvenance = class _CheckoutProvenance {
3653
+ constructor(cwd, env) {
3654
+ this.cwd = cwd;
3655
+ this.env = env;
3656
+ }
3657
+ cwd;
3658
+ env;
3659
+ static read(cwd = process.cwd(), env = process.env) {
3660
+ return new _CheckoutProvenance(cwd, env).checkout();
3661
+ }
3662
+ checkout() {
3663
+ const commit = this.git("rev-parse", "HEAD");
3664
+ if (!commit) return this.withPr({});
3665
+ const branch = this.env.GITHUB_HEAD_REF || this.git("rev-parse", "--abbrev-ref", "HEAD");
3666
+ const remote = this.git("config", "--get", "remote.origin.url");
3667
+ return this.withPr({
3668
+ commit,
3669
+ ...branch && branch !== "HEAD" ? { branch } : {},
3670
+ ...remote ? { repoUrl: _CheckoutProvenance.withoutCredentials(remote) } : {}
3671
+ });
3672
+ }
3673
+ /** Security: credentials are stripped; scp-style `git@host:org/repo` has none and is kept. */
3674
+ static withoutCredentials(url) {
3675
+ return url.replace(/^([a-z][a-z0-9+.-]*:\/\/)[^@/]+@/i, "$1");
3676
+ }
3677
+ withPr(checkout) {
3678
+ const pr = this.pullRequest();
3679
+ return pr ? { ...checkout, pr } : checkout;
3680
+ }
3681
+ pullRequest() {
3682
+ const url = this.env.GATEWAY_PR_URL;
3683
+ const fromUrl = url ? /\/pull\/(\d+)/.exec(url)?.[1] : void 0;
3684
+ if (url && fromUrl)
3685
+ return {
3686
+ number: Number(fromUrl),
3687
+ url,
3688
+ ...this.env.GATEWAY_PR_TITLE ? { title: this.env.GATEWAY_PR_TITLE } : {}
3689
+ };
3690
+ const number = /^refs\/pull\/(\d+)\//.exec(this.env.GITHUB_REF ?? "")?.[1];
3691
+ const server = this.env.GITHUB_SERVER_URL;
3692
+ const repo = this.env.GITHUB_REPOSITORY;
3693
+ if (!number || !server || !repo) return void 0;
3694
+ return { number: Number(number), url: `${server}/${repo}/pull/${number}` };
3695
+ }
3696
+ git(...args) {
3697
+ try {
3698
+ const out = (0, import_node_child_process.execFileSync)("git", args, {
3699
+ cwd: this.cwd,
3700
+ stdio: ["ignore", "pipe", "ignore"],
3701
+ timeout: 5e3
3702
+ }).toString().trim();
3703
+ return out || void 0;
3704
+ } catch {
3705
+ return void 0;
3706
+ }
3707
+ }
3708
+ };
3709
+ }
3710
+ });
3711
+
3712
+ // src/worlds/setRun.ts
3713
+ async function runSet(datasetId, agent, opts) {
3714
+ const options = opts.options ?? {};
3715
+ const git = opts.git === void 0 ? CheckoutProvenance.read() : opts.git;
3716
+ const opened = await apiRequest(options, "POST", SET_RUNS, {
3717
+ datasetId,
3718
+ model: opts.model,
3719
+ source: opts.source ?? "sdk",
3720
+ ...git && Object.keys(git).length ? { git } : {}
3721
+ });
3722
+ const close = (status) => apiRequest(
3723
+ options,
3724
+ "POST",
3725
+ `${SET_RUNS}/${encodeURIComponent(opened.id)}/close`,
3726
+ { status }
3727
+ );
3728
+ const onInterrupt = () => {
3729
+ void close("failed").finally(() => process.exit(130));
3730
+ };
3731
+ process.once("SIGINT", onInterrupt);
3732
+ const planned = await runPlannedTasks(opened, agent, opts, options).finally(
3733
+ () => process.off("SIGINT", onInterrupt)
3734
+ );
3735
+ const { tasks, failed } = planned;
3736
+ const requested = failed ? "failed" : "completed";
3737
+ const setRun = await close(requested);
3738
+ return {
3739
+ setRun,
3740
+ tasks,
3741
+ failed: failed || setRun.status !== "completed",
3742
+ closedAsRequested: setRun.status === requested
3743
+ };
3744
+ }
3745
+ async function runPlannedTasks(opened, agent, opts, options) {
3746
+ const tasks = [];
3747
+ let failed = false;
3748
+ for (const task of opened.tasks) {
3749
+ try {
3750
+ const summary = await runTask(task.worldTaskId, agent, {
3751
+ model: opts.model,
3752
+ surfaces: opts.surfaces,
3753
+ browserTier: opts.browserTier,
3754
+ outDir: opts.outDir,
3755
+ trace: opts.trace,
3756
+ setRunId: opened.id,
3757
+ options
3758
+ });
3759
+ tasks.push(summary);
3760
+ failed ||= summary.agentError !== null;
3761
+ opts.onTask?.(summary);
3762
+ } catch (error) {
3763
+ failed = true;
3764
+ const message = error instanceof Error ? error.message : String(error);
3765
+ process.stderr.write(`task ${task.name} could not run: ${message}
3766
+ `);
3767
+ }
3768
+ }
3769
+ return { tasks, failed };
3770
+ }
3771
+ var SET_RUNS;
3772
+ var init_setRun = __esm({
3773
+ "src/worlds/setRun.ts"() {
3774
+ "use strict";
3775
+ init_worlds();
3776
+ init_checkoutProvenance();
3777
+ init_taskRun();
3778
+ SET_RUNS = "/api/public/set-runs";
3779
+ }
3780
+ });
3781
+
3782
+ // src/worlds/checkoutTarget.ts
3783
+ var fs2, path2, CheckoutRefusedError, NAMED_EDITS, CheckoutTarget;
3784
+ var init_checkoutTarget = __esm({
3785
+ "src/worlds/checkoutTarget.ts"() {
3786
+ "use strict";
3787
+ fs2 = __toESM(require("fs"));
3788
+ path2 = __toESM(require("path"));
3789
+ CheckoutRefusedError = class extends Error {
3790
+ constructor(message) {
3791
+ super(`checkout refused: ${message}`);
3792
+ this.name = "CheckoutRefusedError";
3793
+ }
3794
+ };
3795
+ NAMED_EDITS = 3;
3796
+ CheckoutTarget = class _CheckoutTarget {
3797
+ constructor(dir, replaces) {
3798
+ this.dir = dir;
3799
+ this.replaces = replaces;
3800
+ }
3801
+ dir;
3802
+ replaces;
3803
+ static resolve(slug, target, opts) {
3804
+ if (target === void 0) return _CheckoutTarget.fresh(slug, opts.cwd);
3805
+ return _CheckoutTarget.explicit(
3806
+ _CheckoutTarget.confined(target, opts.cwd),
3807
+ slug,
3808
+ opts
3809
+ );
3810
+ }
3811
+ /** The absolute destination; a relative target may not resolve above `cwd`. */
3812
+ static confined(target, cwd) {
3813
+ const dir = path2.resolve(cwd, target);
3814
+ if (path2.isAbsolute(target)) return dir;
3815
+ const rel = path2.relative(cwd, dir);
3816
+ if (rel === "" || !rel.startsWith("..") && !path2.isAbsolute(rel))
3817
+ return dir;
3818
+ throw new CheckoutRefusedError(
3819
+ `--target ${target} resolves outside the current directory (${cwd}) \u2014 run from that directory, or pass an absolute path`
3820
+ );
3821
+ }
3822
+ static fresh(slug, cwd) {
3823
+ const base = path2.join(cwd, slug);
3824
+ let dir = base;
3825
+ let i = 1;
3826
+ while (fs2.existsSync(dir)) dir = `${base}-${i++}`;
3827
+ return new _CheckoutTarget(dir, []);
3828
+ }
3829
+ static explicit(dir, slug, opts) {
3830
+ if (!fs2.existsSync(dir)) return new _CheckoutTarget(dir, []);
3831
+ if (!fs2.statSync(dir).isDirectory())
3832
+ throw new CheckoutRefusedError(`${dir} is a file`);
3833
+ if (fs2.readdirSync(dir).length === 0) return new _CheckoutTarget(dir, []);
3834
+ const state2 = opts.state(dir);
3835
+ const refusal = _CheckoutTarget.refusal(dir, slug, state2);
3836
+ if (refusal === null || opts.force)
3837
+ return new _CheckoutTarget(dir, _CheckoutTarget.tracked(state2));
3838
+ throw new CheckoutRefusedError(refusal);
3839
+ }
3840
+ /** Base files plus local edits — everything the archive would see in the old
3841
+ * checkout. `.env-metadata.json` is local input: a key that would leave the
3842
+ * checkout (`../x`, `/etc/x`) is dropped, never removed. */
3843
+ static tracked(state2) {
3844
+ if (!state2.meta?.baseFiles) return [];
3845
+ return [
3846
+ .../* @__PURE__ */ new Set([...Object.keys(state2.meta.baseFiles), ...state2.dirty])
3847
+ ].filter(_CheckoutTarget.confinedRel).sort();
3848
+ }
3849
+ static confinedRel(rel) {
3850
+ if (rel === "" || path2.isAbsolute(rel)) return false;
3851
+ return !rel.split(/[\\/]/).includes("..");
3852
+ }
3853
+ /** Why `dir` cannot be overwritten, or null when it is a clean checkout of `slug`. */
3854
+ static refusal(dir, slug, state2) {
3855
+ if (!state2.meta?.baseFiles)
3856
+ return `${dir} is not empty and is not a checkout of "${slug}" \u2014 pick an empty --target, or pass --force to overwrite it`;
3857
+ if (state2.meta.slug !== void 0 && state2.meta.slug !== slug)
3858
+ return `${dir} tracks "${state2.meta.slug}", not "${slug}" \u2014 pick another --target, or pass --force to replace it`;
3859
+ if (state2.clean) return null;
3860
+ const n = state2.dirty.length;
3861
+ const named = state2.dirty.slice(0, NAMED_EDITS).join(", ");
3862
+ const more = n > NAMED_EDITS ? `, +${n - NAMED_EDITS} more` : "";
3863
+ return `${dir} has ${n} local edit${n === 1 ? "" : "s"} not pushed (${named}${more}) \u2014 push or propose them first, or pass --force to discard them`;
3864
+ }
3865
+ /** Remove the replaced checkout's files (and the dirs they leave empty). */
3866
+ clear() {
3867
+ for (const rel of this.replaces) {
3868
+ const abs = path2.join(this.dir, rel);
3869
+ fs2.rmSync(abs, { force: true });
3870
+ this.pruneEmptyParents(path2.dirname(abs));
3871
+ }
3872
+ }
3873
+ pruneEmptyParents(from) {
3874
+ let cur = from;
3875
+ while (cur !== this.dir && cur.startsWith(this.dir)) {
3876
+ if (fs2.existsSync(cur) && fs2.readdirSync(cur).length > 0) return;
3877
+ fs2.rmSync(cur, { recursive: true, force: true });
3878
+ cur = path2.dirname(cur);
3879
+ }
3880
+ }
3881
+ };
3882
+ }
3883
+ });
3884
+
3060
3885
  // src/worlds/worldDir.ts
3061
- var import_node_crypto4, fs2, path2, WORLD_MANIFEST, API_BUNDLE_MANIFEST, BUNDLED_WORLD_PREFIX, CONNECTOR_SPEC, PYPROJECT, WORLD_SCHEMA_MARKERS, WORLD_ROOT_MARKERS, BROAD_ROOT_MARKERS, SKIPPED_DIRS, V1_DEP, V1_IMPORT, V1_TASKSET, HARBOR_TASK, skippedDir, byCodePoint, WorldDir;
3886
+ var import_node_crypto4, fs3, path3, 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;
3062
3887
  var init_worldDir = __esm({
3063
3888
  "src/worlds/worldDir.ts"() {
3064
3889
  "use strict";
3065
3890
  import_node_crypto4 = require("crypto");
3066
- fs2 = __toESM(require("fs"));
3067
- path2 = __toESM(require("path"));
3891
+ fs3 = __toESM(require("fs"));
3892
+ path3 = __toESM(require("path"));
3068
3893
  WORLD_MANIFEST = "gateway-env.toml";
3069
3894
  API_BUNDLE_MANIFEST = "gateway-api-world.toml";
3070
3895
  BUNDLED_WORLD_PREFIX = "server/world/";
3071
3896
  CONNECTOR_SPEC = "connector.toml";
3072
3897
  PYPROJECT = "pyproject.toml";
3898
+ BENCHMARK_CONFIG = "benchmark.json";
3073
3899
  WORLD_SCHEMA_MARKERS = ["schema/world.json", "schema/runtime.json", "schema/lock.json"];
3074
3900
  WORLD_ROOT_MARKERS = [CONNECTOR_SPEC, ...WORLD_SCHEMA_MARKERS];
3075
- BROAD_ROOT_MARKERS = [WORLD_MANIFEST, API_BUNDLE_MANIFEST];
3076
- SKIPPED_DIRS = /* @__PURE__ */ new Set(["dist", "build", "outputs", "__pycache__"]);
3901
+ BROAD_ROOT_MARKERS = [WORLD_MANIFEST, API_BUNDLE_MANIFEST, BENCHMARK_CONFIG];
3902
+ SKIPPED_DIRS = /* @__PURE__ */ new Set(["dist", "build", "outputs", "__pycache__", "node_modules"]);
3077
3903
  V1_DEP = /["']verifiers\s*(?:\[[^\]]*\])?\s*(?:>=|~=|==|>)\s*(?:0\.(?:[2-9]\d*|[1-9]\d+)|[1-9]\d*)/;
3078
3904
  V1_IMPORT = /^\s*(?:from\s+verifiers\.v1\s+import\b|from\s+verifiers\s+import\s+v1\b|import\s+verifiers\.v1\b)/m;
3079
3905
  V1_TASKSET = /class\s+\w+\s*\(\s*(?:(?:vf|v1|verifiers(?:\.v1)?)\.)?Taskset\s*[,)]/;
@@ -3085,19 +3911,21 @@ var init_worldDir = __esm({
3085
3911
  this.dir = dir;
3086
3912
  this.worldRoot = worldRoot;
3087
3913
  }
3914
+ dir;
3915
+ worldRoot;
3088
3916
  pathsMemo;
3089
3917
  static open(dir) {
3090
- const present = (rel) => fs2.existsSync(path2.join(dir, rel));
3918
+ const present = (rel) => fs3.existsSync(path3.join(dir, rel));
3091
3919
  const bundled = present(API_BUNDLE_MANIFEST) && WORLD_ROOT_MARKERS.some((m) => present(BUNDLED_WORLD_PREFIX + m));
3092
3920
  return new _WorldDir(dir, bundled ? BUNDLED_WORLD_PREFIX : "");
3093
3921
  }
3094
3922
  // ── Files ──────────────────────────────────────────────────────────────
3095
3923
  has(rel) {
3096
- return fs2.existsSync(path2.join(this.dir, rel));
3924
+ return fs3.existsSync(path3.join(this.dir, rel));
3097
3925
  }
3098
3926
  text(rel) {
3099
3927
  try {
3100
- return fs2.readFileSync(path2.join(this.dir, rel), "utf-8");
3928
+ return fs3.readFileSync(path3.join(this.dir, rel), "utf-8");
3101
3929
  } catch {
3102
3930
  return null;
3103
3931
  }
@@ -3107,20 +3935,21 @@ var init_worldDir = __esm({
3107
3935
  return this.worldRoot + rel;
3108
3936
  }
3109
3937
  /** Every regular file the archive rules keep (`_archive.py`: no hidden,
3110
- * dist, build, outputs, pycache or egg-info directories), as sorted
3111
- * relpaths. Root files enter only when a Gateway manifest widens the root
3112
- * or they are README.md, pyproject.toml or Python. */
3938
+ * dist, build, outputs, pycache, node_modules or egg-info directories), as
3939
+ * sorted relpaths. Root files enter only when a Gateway manifest or
3940
+ * benchmark.json widens the root, or they are README.md, pyproject.toml or
3941
+ * Python. */
3113
3942
  get archivePaths() {
3114
3943
  if (this.pathsMemo) return this.pathsMemo;
3115
3944
  const broad = BROAD_ROOT_MARKERS.some((m) => this.has(m));
3116
3945
  const out = [];
3117
3946
  const walk = (rel) => {
3118
- for (const entry of fs2.readdirSync(rel ? path2.join(this.dir, rel) : this.dir, { withFileTypes: true })) {
3947
+ for (const entry of fs3.readdirSync(rel ? path3.join(this.dir, rel) : this.dir, { withFileTypes: true })) {
3119
3948
  const child = rel ? `${rel}/${entry.name}` : entry.name;
3120
3949
  if (entry.isDirectory()) {
3121
3950
  if (!skippedDir(entry.name)) walk(child);
3122
3951
  } else if (entry.isFile() && !entry.name.startsWith(".")) {
3123
- const rootKept = broad || ["README.md", PYPROJECT].includes(entry.name) || entry.name.endsWith(".py");
3952
+ const rootKept = broad || ["README.md", PYPROJECT, ...BROAD_ROOT_MARKERS].includes(entry.name) || entry.name.endsWith(".py");
3124
3953
  if (rel || rootKept) out.push(child);
3125
3954
  }
3126
3955
  }
@@ -3128,6 +3957,33 @@ var init_worldDir = __esm({
3128
3957
  walk("");
3129
3958
  return this.pathsMemo = out.sort(byCodePoint);
3130
3959
  }
3960
+ /** What the archive rules leave out, collapsed to the entry that decided
3961
+ * it: a pruned directory counts its files once, a dropped root file is
3962
+ * named. Dot entries (`.git/`, `.gateway/`, `.gitignore`) are the one
3963
+ * universal convention and stay unreported. `push` prints the rest so
3964
+ * nothing disappears silently. */
3965
+ get exclusions() {
3966
+ const kept = new Set(this.archivePaths);
3967
+ const out = [];
3968
+ const filesUnder = (rel) => fs3.readdirSync(path3.join(this.dir, rel), { withFileTypes: true }).flatMap((entry) => {
3969
+ const child = `${rel}/${entry.name}`;
3970
+ if (entry.isDirectory()) return filesUnder(child);
3971
+ return entry.isFile() ? [child] : [];
3972
+ });
3973
+ for (const entry of fs3.readdirSync(this.dir, { withFileTypes: true }).sort((a, b) => byCodePoint(a.name, b.name))) {
3974
+ if (entry.name.startsWith(".")) continue;
3975
+ if (entry.isDirectory()) {
3976
+ const all = filesUnder(entry.name);
3977
+ const missing = all.filter((rel) => !kept.has(rel));
3978
+ if (missing.length === 0) continue;
3979
+ const whole = missing.length === all.length;
3980
+ out.push(...whole ? [{ path: `${entry.name}/`, files: missing.length }] : missing.map((p) => ({ path: p, files: 1 })));
3981
+ continue;
3982
+ }
3983
+ if (!kept.has(entry.name)) out.push({ path: entry.name, files: 1 });
3984
+ }
3985
+ return out;
3986
+ }
3131
3987
  /** A root `.gitignore` is present: the Python SDK honours it when
3132
3988
  * collecting, this package does not reimplement gitignore. */
3133
3989
  get hasRootGitignore() {
@@ -3140,7 +3996,7 @@ var init_worldDir = __esm({
3140
3996
  const hasher = (0, import_node_crypto4.createHash)("sha256");
3141
3997
  for (const rel of this.archivePaths) {
3142
3998
  hasher.update(Buffer.from(`file:${rel}`, "utf-8"));
3143
- hasher.update(fs2.readFileSync(path2.join(this.dir, rel)));
3999
+ hasher.update(fs3.readFileSync(path3.join(this.dir, rel)));
3144
4000
  }
3145
4001
  return hasher.digest("hex");
3146
4002
  }
@@ -3203,14 +4059,121 @@ var init_worldDir = __esm({
3203
4059
  }
3204
4060
  });
3205
4061
 
4062
+ // src/worlds/tar.ts
4063
+ function archiveMode(mode) {
4064
+ return (mode & 73) !== 0 ? TAR_EXEC_MODE : TAR_FILE_MODE;
4065
+ }
4066
+ function field(header, start, end) {
4067
+ return header.subarray(start, end).toString("utf-8").replace(/\0.*$/, "");
4068
+ }
4069
+ function octalField(header, start, end) {
4070
+ return parseInt(field(header, start, end).trim(), 8);
4071
+ }
4072
+ function paxPath(body) {
4073
+ let off = 0;
4074
+ let found = null;
4075
+ while (off < body.length) {
4076
+ const sp = body.indexOf(32, off);
4077
+ if (sp === -1) break;
4078
+ const len = parseInt(body.subarray(off, sp).toString("ascii"), 10);
4079
+ if (!Number.isFinite(len) || len <= 0) break;
4080
+ const record = body.subarray(sp + 1, off + len);
4081
+ const eq = record.indexOf(61);
4082
+ const key2 = eq === -1 ? "" : record.subarray(0, eq).toString("utf-8");
4083
+ if (key2 === "path")
4084
+ found = record.subarray(eq + 1).toString("utf-8").replace(/\n$/, "");
4085
+ off += len;
4086
+ }
4087
+ return found;
4088
+ }
4089
+ var fs4, path4, import_node_zlib, TAR_FILE_MODE, TAR_EXEC_MODE, TarArchive;
4090
+ var init_tar = __esm({
4091
+ "src/worlds/tar.ts"() {
4092
+ "use strict";
4093
+ fs4 = __toESM(require("fs"));
4094
+ path4 = __toESM(require("path"));
4095
+ import_node_zlib = require("zlib");
4096
+ TAR_FILE_MODE = 420;
4097
+ TAR_EXEC_MODE = 493;
4098
+ TarArchive = class _TarArchive {
4099
+ constructor(tar) {
4100
+ this.tar = tar;
4101
+ }
4102
+ tar;
4103
+ static fromGzip(bundle) {
4104
+ return new _TarArchive((0, import_node_zlib.gunzipSync)(bundle));
4105
+ }
4106
+ static fromTar(tar) {
4107
+ return new _TarArchive(tar);
4108
+ }
4109
+ /** Every member, names fully resolved; metadata members are consumed. */
4110
+ *members() {
4111
+ const tar = this.tar;
4112
+ let offset = 0;
4113
+ let pendingName = null;
4114
+ while (offset + 512 <= tar.length) {
4115
+ const header = tar.subarray(offset, offset + 512);
4116
+ offset += 512;
4117
+ if (header.every((b) => b === 0)) break;
4118
+ const size = octalField(header, 124, 136) || 0;
4119
+ const mode = octalField(header, 100, 108) || TAR_FILE_MODE;
4120
+ const typeflag = String.fromCharCode(header[156] ?? 0);
4121
+ const bytes = tar.subarray(offset, offset + size);
4122
+ offset += Math.ceil(size / 512) * 512;
4123
+ if (typeflag === "L") {
4124
+ pendingName = bytes.toString("utf-8").replace(/\0.*$/, "");
4125
+ continue;
4126
+ }
4127
+ if (typeflag === "x") {
4128
+ pendingName = paxPath(bytes) ?? pendingName;
4129
+ continue;
4130
+ }
4131
+ if (typeflag === "K" || typeflag === "g") continue;
4132
+ const name = pendingName ?? _TarArchive.ustarName(header);
4133
+ pendingName = null;
4134
+ yield { name: name.replace(/^\.\//, ""), bytes, typeflag, mode };
4135
+ }
4136
+ }
4137
+ static ustarName(header) {
4138
+ const name = field(header, 0, 100);
4139
+ const magic = header.subarray(257, 262).toString("ascii");
4140
+ const prefix = magic === "ustar" ? field(header, 345, 500) : "";
4141
+ return prefix ? `${prefix}/${name}` : name;
4142
+ }
4143
+ /** Regular files only, confined to `dir` (absolute or `..` names are
4144
+ * skipped, never written). Returns the number of files written. */
4145
+ extractTo(dir) {
4146
+ let written = 0;
4147
+ for (const member of this.members()) {
4148
+ if (member.typeflag !== "0" && member.typeflag !== "\0") continue;
4149
+ if (!_TarArchive.isConfined(member.name)) continue;
4150
+ const target = path4.join(dir, member.name);
4151
+ fs4.mkdirSync(path4.dirname(target), { recursive: true });
4152
+ const mode = archiveMode(member.mode);
4153
+ fs4.writeFileSync(target, member.bytes, { mode });
4154
+ fs4.chmodSync(target, mode);
4155
+ written++;
4156
+ }
4157
+ return written;
4158
+ }
4159
+ static isConfined(name) {
4160
+ if (name === "" || name.startsWith("/")) return false;
4161
+ return !name.split("/").includes("..");
4162
+ }
4163
+ };
4164
+ }
4165
+ });
4166
+
3206
4167
  // src/worlds/hub.ts
3207
4168
  var hub_exports = {};
3208
4169
  __export(hub_exports, {
3209
4170
  DEFAULT_BRANCH: () => DEFAULT_BRANCH,
4171
+ DetachedPushError: () => DetachedPushError,
3210
4172
  PushSlugConflict: () => PushSlugConflict,
3211
4173
  archiveMode: () => archiveMode,
3212
4174
  buildFileManifest: () => buildFileManifest,
3213
4175
  buildSourceTarball: () => buildSourceTarball,
4176
+ checkoutIdentity: () => checkoutIdentity,
3214
4177
  collectArchiveRelPaths: () => collectArchiveRelPaths,
3215
4178
  computeContentHash: () => computeContentHash,
3216
4179
  createRef: () => createRef,
@@ -3219,6 +4182,7 @@ __export(hub_exports, {
3219
4182
  propose: () => propose,
3220
4183
  pull: () => pull,
3221
4184
  push: () => push,
4185
+ pushBranch: () => pushBranch,
3222
4186
  pushSlug: () => pushSlug,
3223
4187
  readLocalMeta: () => readLocalMeta,
3224
4188
  resolvePushSlug: () => resolvePushSlug,
@@ -3244,9 +4208,6 @@ function octal(value, length) {
3244
4208
  "ascii"
3245
4209
  );
3246
4210
  }
3247
- function archiveMode(mode) {
3248
- return (mode & 73) !== 0 ? EXEC_MODE : FILE_MODE;
3249
- }
3250
4211
  function tarHeader(name, size, mode = FILE_MODE) {
3251
4212
  const header = Buffer.alloc(512);
3252
4213
  header.write(name, 0, 100, "utf-8");
@@ -3290,21 +4251,21 @@ function tarMember(name, payload, mode) {
3290
4251
  function buildSourceTarball(dir) {
3291
4252
  const parts2 = [];
3292
4253
  for (const relPath of collectArchiveRelPaths(dir)) {
3293
- const abs = path3.join(dir, relPath);
4254
+ const abs = path5.join(dir, relPath);
3294
4255
  parts2.push(
3295
4256
  ...tarMember(
3296
4257
  relPath,
3297
- fs3.readFileSync(abs),
3298
- archiveMode(fs3.statSync(abs).mode)
4258
+ fs5.readFileSync(abs),
4259
+ archiveMode(fs5.statSync(abs).mode)
3299
4260
  )
3300
4261
  );
3301
4262
  }
3302
4263
  parts2.push(Buffer.alloc(1024));
3303
- return (0, import_node_zlib.gzipSync)(Buffer.concat(parts2), { level: 9 });
4264
+ return (0, import_node_zlib2.gzipSync)(Buffer.concat(parts2), { level: 9 });
3304
4265
  }
3305
4266
  function readLocalMeta(dir) {
3306
4267
  try {
3307
- const raw = fs3.readFileSync(path3.join(dir, META_RELPATH), "utf-8");
4268
+ const raw = fs5.readFileSync(path5.join(dir, META_RELPATH), "utf-8");
3308
4269
  const parsed = JSON.parse(raw);
3309
4270
  return parsed && typeof parsed === "object" ? parsed : null;
3310
4271
  } catch {
@@ -3327,16 +4288,16 @@ function resolvePushSlug(dir, opts = {}) {
3327
4288
  }
3328
4289
  const first = declared[0];
3329
4290
  if (first) return { ...base, slug: first.slug, source: first.source };
3330
- return { ...base, slug: path3.basename(path3.resolve(dir)), source: "directory name" };
4291
+ return { ...base, slug: path5.basename(path5.resolve(dir)), source: "directory name" };
3331
4292
  }
3332
4293
  function writeLocalMeta(dir, meta) {
3333
- fs3.mkdirSync(path3.join(dir, ".gateway"), { recursive: true });
3334
- fs3.writeFileSync(path3.join(dir, META_RELPATH), JSON.stringify(meta, null, 2));
4294
+ fs5.mkdirSync(path5.join(dir, ".gateway"), { recursive: true });
4295
+ fs5.writeFileSync(path5.join(dir, META_RELPATH), JSON.stringify(meta, null, 2));
3335
4296
  }
3336
4297
  function snapshotTreeHashes(dir) {
3337
4298
  const out = {};
3338
4299
  for (const relPath of collectArchiveRelPaths(dir)) {
3339
- out[relPath] = (0, import_node_crypto5.createHash)("sha256").update(fs3.readFileSync(path3.join(dir, relPath))).digest("hex");
4300
+ out[relPath] = (0, import_node_crypto5.createHash)("sha256").update(fs5.readFileSync(path5.join(dir, relPath))).digest("hex");
3340
4301
  }
3341
4302
  return out;
3342
4303
  }
@@ -3354,7 +4315,7 @@ function localTreeState(dir) {
3354
4315
  }
3355
4316
  function readPyproject(dir) {
3356
4317
  try {
3357
- const text2 = fs3.readFileSync(path3.join(dir, "pyproject.toml"), "utf-8");
4318
+ const text2 = fs5.readFileSync(path5.join(dir, "pyproject.toml"), "utf-8");
3358
4319
  const section = /\[project\]([\s\S]*?)(\n\[|$)/.exec(text2)?.[1] ?? "";
3359
4320
  const name = /\bname\s*=\s*"([^"]+)"/.exec(section)?.[1];
3360
4321
  const version = /\bversion\s*=\s*"([^"]+)"/.exec(section)?.[1];
@@ -3377,7 +4338,7 @@ function readWorldContractVersion(dir) {
3377
4338
  }
3378
4339
  function buildFileManifest(dir) {
3379
4340
  return collectArchiveRelPaths(dir).map((relPath) => {
3380
- const payload = fs3.readFileSync(path3.join(dir, relPath));
4341
+ const payload = fs5.readFileSync(path5.join(dir, relPath));
3381
4342
  return {
3382
4343
  path: relPath,
3383
4344
  isDirectory: false,
@@ -3401,30 +4362,36 @@ async function putObject(url, data, shaB64) {
3401
4362
  );
3402
4363
  }
3403
4364
  }
4365
+ function pushBranch(dir, localMeta, explicit) {
4366
+ if (explicit) return explicit;
4367
+ if (typeof localMeta.tag === "string" && localMeta.tag) throw new DetachedPushError(dir, localMeta.tag);
4368
+ return localMeta.branch ?? DEFAULT_BRANCH;
4369
+ }
3404
4370
  async function push(dir, opts = {}) {
3405
4371
  const options = opts.options ?? {};
3406
- if (!fs3.statSync(dir).isDirectory())
4372
+ if (!fs5.statSync(dir).isDirectory())
3407
4373
  throw new Error(`Not a directory: ${dir}`);
3408
4374
  const localMeta = readLocalMeta(dir) ?? {};
3409
- const branch = opts.branch ?? localMeta.branch ?? DEFAULT_BRANCH;
4375
+ const branch = pushBranch(dir, localMeta, opts.branch);
3410
4376
  const baseVersionId = opts.baseVersionId ?? localMeta.versionId ?? null;
4377
+ const world = WorldDir.open(dir);
3411
4378
  const fileManifest = buildFileManifest(dir);
3412
4379
  if (fileManifest.length === 0)
3413
4380
  throw new Error(
3414
4381
  `Nothing to push: ${dir} has no files the archive rules keep (a world root marker, README.md, pyproject.toml, *.py, or any file below a subdirectory).`
3415
4382
  );
3416
- const contentHash = computeContentHash(dir);
4383
+ const contentHash = world.contentHash;
3417
4384
  const pyproject = readPyproject(dir);
3418
4385
  const contractVersion = pyproject.version ? void 0 : readWorldContractVersion(dir).version;
3419
4386
  if (contractVersion) pyproject.version = contractVersion;
3420
- const slug = opts.slug ?? localMeta.slug ?? pyproject.name ?? path3.basename(path3.resolve(dir));
4387
+ const slug = opts.slug ?? localMeta.slug ?? pyproject.name ?? path5.basename(path5.resolve(dir));
3421
4388
  const metadata = {
3422
4389
  ...opts.name !== void 0 ? { name: opts.name } : {},
3423
4390
  ...opts.description !== void 0 ? { description: opts.description } : {},
3424
4391
  ...opts.tags !== void 0 ? { tags: opts.tags } : {},
3425
4392
  ...opts.visibility ? { visibility: opts.visibility } : {}
3426
4393
  };
3427
- const resolve10 = await apiRequest(
4394
+ const resolve11 = await apiRequest(
3428
4395
  options,
3429
4396
  "POST",
3430
4397
  "/api/public/benchmark-containers/resolve",
@@ -3433,7 +4400,7 @@ async function push(dir, opts = {}) {
3433
4400
  const tarball = buildSourceTarball(dir);
3434
4401
  const bundleSha256 = sha256b64(tarball);
3435
4402
  const version = await apiRequest(options, "POST", "/api/public/benchmark-containers/versions", {
3436
- containerId: resolve10.containerId,
4403
+ containerId: resolve11.containerId,
3437
4404
  contentHash,
3438
4405
  bundleSha256,
3439
4406
  bundleSizeBytes: tarball.length,
@@ -3472,56 +4439,36 @@ async function push(dir, opts = {}) {
3472
4439
  baseFiles: snapshotTreeHashes(dir)
3473
4440
  });
3474
4441
  return {
3475
- containerId: resolve10.containerId,
4442
+ containerId: resolve11.containerId,
3476
4443
  slug,
3477
4444
  versionId: version.versionId,
3478
4445
  contentHash,
3479
4446
  branch: final.branch ?? branch,
3480
4447
  state: final.state ?? null,
3481
- alreadyUploaded: Boolean(version.alreadyUploaded)
4448
+ alreadyUploaded: Boolean(version.alreadyUploaded),
4449
+ editSessionId: final.editSessionId ?? null,
4450
+ filesKept: fileManifest.length,
4451
+ excluded: world.exclusions
3482
4452
  };
3483
4453
  }
3484
4454
  function extractBundle(bundle, dir) {
3485
- const tar = (0, import_node_zlib.gunzipSync)(bundle);
3486
- let offset = 0;
3487
- let longName = null;
3488
- let written = 0;
3489
- while (offset + 512 <= tar.length) {
3490
- const header = tar.subarray(offset, offset + 512);
3491
- offset += 512;
3492
- if (header.every((b) => b === 0)) break;
3493
- const rawName = header.subarray(0, 100).toString("utf-8").replace(/\0.*$/, "");
3494
- const size = parseInt(
3495
- header.subarray(124, 136).toString("ascii").replace(/\0.*$/, "").trim(),
3496
- 8
3497
- ) || 0;
3498
- const mode = parseInt(
3499
- header.subarray(100, 108).toString("ascii").replace(/\0.*$/, "").trim(),
3500
- 8
3501
- ) || FILE_MODE;
3502
- const typeflag = header.subarray(156, 157).toString("ascii");
3503
- const body = tar.subarray(offset, offset + size);
3504
- offset += size + (size % 512 === 0 ? 0 : 512 - size % 512);
3505
- if (typeflag === "L") {
3506
- longName = body.toString("utf-8").replace(/\0.*$/, "");
3507
- continue;
3508
- }
3509
- const name = (longName ?? rawName).replace(/^\.\//, "");
3510
- longName = null;
3511
- if (typeflag !== "0" && typeflag !== "") continue;
3512
- if (name.startsWith("/") || name.split("/").includes("..")) continue;
3513
- const target = path3.join(dir, name);
3514
- fs3.mkdirSync(path3.dirname(target), { recursive: true });
3515
- fs3.writeFileSync(target, body, { mode: archiveMode(mode) });
3516
- fs3.chmodSync(target, archiveMode(mode));
3517
- written++;
3518
- }
3519
- return written;
4455
+ return TarArchive.fromGzip(bundle).extractTo(dir);
3520
4456
  }
3521
- async function pull(slugRef, target, options = {}) {
4457
+ function checkoutIdentity(ref, resolved) {
4458
+ if (resolved.tag) return { tag: resolved.tag };
4459
+ if (resolved.branch) return { branch: resolved.branch };
4460
+ const pinned = ref === "latest" || /^\d|^[0-9a-f]{8,}$/.test(ref);
4461
+ return { branch: pinned ? DEFAULT_BRANCH : ref };
4462
+ }
4463
+ async function pull(slugRef, target, options = {}, opts = {}) {
3522
4464
  const at = slugRef.indexOf("@");
3523
4465
  const slug = at === -1 ? slugRef : slugRef.slice(0, at);
3524
4466
  const ref = at === -1 ? "latest" : slugRef.slice(at + 1);
4467
+ const landing = CheckoutTarget.resolve(slug, target, {
4468
+ cwd: process.cwd(),
4469
+ force: opts.force ?? false,
4470
+ state: localTreeState
4471
+ });
3525
4472
  const details = await apiRequest(options, "POST", "/api/public/benchmark-containers/resolve-version", {
3526
4473
  slug,
3527
4474
  ref
@@ -3529,13 +4476,6 @@ async function pull(slugRef, target, options = {}) {
3529
4476
  if (!details.downloadUrl) {
3530
4477
  throw new Error(`${slug}@${ref} resolved but has no uploaded bundle`);
3531
4478
  }
3532
- let dir = target ?? path3.join(process.cwd(), slug);
3533
- if (!target) {
3534
- let i = 1;
3535
- const base = dir;
3536
- while (fs3.existsSync(dir)) dir = `${base}-${i++}`;
3537
- }
3538
- fs3.mkdirSync(dir, { recursive: true });
3539
4479
  const resp = await fetch(details.downloadUrl);
3540
4480
  if (!resp.ok) throw new Error(`bundle download -> ${resp.status}`);
3541
4481
  const bundle = Buffer.from(await resp.arrayBuffer());
@@ -3544,12 +4484,14 @@ async function pull(slugRef, target, options = {}) {
3544
4484
  `bundle integrity check failed for ${slug}@${ref}: downloaded sha256 != recorded bundleSha256`
3545
4485
  );
3546
4486
  }
4487
+ const dir = landing.dir;
4488
+ fs5.mkdirSync(dir, { recursive: true });
4489
+ landing.clear();
3547
4490
  const files = extractBundle(bundle, dir);
3548
- const branch = ref === "latest" || /^\d|^[0-9a-f]{8,}$/.test(ref) ? DEFAULT_BRANCH : ref;
3549
4491
  writeLocalMeta(dir, {
3550
4492
  slug,
3551
4493
  ref,
3552
- branch,
4494
+ ...checkoutIdentity(ref, details),
3553
4495
  versionId: details.versionId,
3554
4496
  contentHash: details.contentHash,
3555
4497
  semanticVersion: details.semanticVersion ?? void 0,
@@ -3568,13 +4510,13 @@ async function propose(dir, opts) {
3568
4510
  if (state2.clean)
3569
4511
  throw new Error("Nothing to propose \u2014 the tree matches its base.");
3570
4512
  const changes = state2.dirty.map((relPath) => {
3571
- const abs = path3.join(dir, relPath);
3572
- if (!fs3.existsSync(abs))
4513
+ const abs = path5.join(dir, relPath);
4514
+ if (!fs5.existsSync(abs))
3573
4515
  return { path: relPath, action: "delete" };
3574
4516
  return {
3575
4517
  path: relPath,
3576
4518
  action: "write",
3577
- newContent: fs3.readFileSync(abs, "utf-8")
4519
+ newContent: fs5.readFileSync(abs, "utf-8")
3578
4520
  };
3579
4521
  });
3580
4522
  const res = await apiRequest(
@@ -3600,20 +4542,21 @@ async function createRef(slug, name, kind, versionId, options = {}) {
3600
4542
  ...versionId ? { versionId } : {}
3601
4543
  });
3602
4544
  }
3603
- var import_node_crypto5, import_node_zlib, fs3, path3, DEFAULT_BRANCH, META_RELPATH, FILE_MODE, EXEC_MODE, MINTED_SUFFIX, PushSlugConflict, sha256b64;
4545
+ var import_node_crypto5, import_node_zlib2, fs5, path5, DEFAULT_BRANCH, META_RELPATH, FILE_MODE, MINTED_SUFFIX, PushSlugConflict, sha256b64, DetachedPushError;
3604
4546
  var init_hub = __esm({
3605
4547
  "src/worlds/hub.ts"() {
3606
4548
  "use strict";
3607
4549
  import_node_crypto5 = require("crypto");
3608
- import_node_zlib = require("zlib");
3609
- fs3 = __toESM(require("fs"));
3610
- path3 = __toESM(require("path"));
4550
+ import_node_zlib2 = require("zlib");
4551
+ fs5 = __toESM(require("fs"));
4552
+ path5 = __toESM(require("path"));
3611
4553
  init_worlds();
4554
+ init_checkoutTarget();
3612
4555
  init_worldDir();
4556
+ init_tar();
3613
4557
  DEFAULT_BRANCH = "main";
3614
- META_RELPATH = path3.join(".gateway", ".env-metadata.json");
3615
- FILE_MODE = 420;
3616
- EXEC_MODE = 493;
4558
+ META_RELPATH = path5.join(".gateway", ".env-metadata.json");
4559
+ FILE_MODE = TAR_FILE_MODE;
3617
4560
  MINTED_SUFFIX = /^-\d+$/;
3618
4561
  PushSlugConflict = class extends Error {
3619
4562
  constructor(dir, tracked, declared) {
@@ -3625,8 +4568,19 @@ var init_hub = __esm({
3625
4568
  this.declared = declared;
3626
4569
  this.name = "PushSlugConflict";
3627
4570
  }
4571
+ dir;
4572
+ tracked;
4573
+ declared;
3628
4574
  };
3629
4575
  sha256b64 = (data) => (0, import_node_crypto5.createHash)("sha256").update(data).digest("base64");
4576
+ DetachedPushError = class extends Error {
4577
+ constructor(dir, tag) {
4578
+ super(
4579
+ `push refused: ${dir} is a checkout of tag "${tag}" (tags are immutable). Nothing was pushed. Pass --branch <name> to land these files on a branch, or checkout a branch first.`
4580
+ );
4581
+ this.name = "DetachedPushError";
4582
+ }
4583
+ };
3630
4584
  }
3631
4585
  });
3632
4586
 
@@ -3783,52 +4737,170 @@ async function validateWorld(dir, opts) {
3783
4737
  else if (report.score < minScore)
3784
4738
  failure = `score ${fmtScore(report.score)} < ${minScore}`;
3785
4739
  }
3786
- } catch (error) {
3787
- failure = error instanceof Error ? error.message : String(error);
3788
- }
3789
- runs.push({ model: run.model, runId: run.runId, report, failure });
3790
- }
3791
- const base = {
3792
- ok: runs.length > 0 && runs.every((r) => r.failure === null),
3793
- slug: pushed.slug,
3794
- branch,
3795
- versionId: pushed.versionId,
3796
- contentHash: pushed.contentHash,
3797
- runConfig: { id: runConfig.id, name: runConfig.name },
3798
- runs
3799
- };
3800
- return {
3801
- ...base,
3802
- markdown: buildMarkdown(base, minScore, {
3803
- repoUrl: provenance.repoUrl,
3804
- commit: provenance.commit
3805
- })
3806
- };
3807
- }
3808
- var init_validate = __esm({
3809
- "src/worlds/validate.ts"() {
3810
- "use strict";
3811
- init_worlds();
3812
- init_hub();
4740
+ } catch (error) {
4741
+ failure = error instanceof Error ? error.message : String(error);
4742
+ }
4743
+ runs.push({ model: run.model, runId: run.runId, report, failure });
4744
+ }
4745
+ const base = {
4746
+ ok: runs.length > 0 && runs.every((r) => r.failure === null),
4747
+ slug: pushed.slug,
4748
+ branch,
4749
+ versionId: pushed.versionId,
4750
+ contentHash: pushed.contentHash,
4751
+ runConfig: { id: runConfig.id, name: runConfig.name },
4752
+ runs
4753
+ };
4754
+ return {
4755
+ ...base,
4756
+ markdown: buildMarkdown(base, minScore, {
4757
+ repoUrl: provenance.repoUrl,
4758
+ commit: provenance.commit
4759
+ })
4760
+ };
4761
+ }
4762
+ var init_validate = __esm({
4763
+ "src/worlds/validate.ts"() {
4764
+ "use strict";
4765
+ init_worlds();
4766
+ init_hub();
4767
+ }
4768
+ });
4769
+
4770
+ // src/worlds/sandbox.ts
4771
+ function parseSlugRef(slugRef) {
4772
+ const at = slugRef.indexOf("@");
4773
+ if (at === -1) return { slug: slugRef };
4774
+ return { slug: slugRef.slice(0, at), ref: slugRef.slice(at + 1) };
4775
+ }
4776
+ function rebaseConflicts(error) {
4777
+ if (!(error instanceof ApiError) || error.status !== 409) return null;
4778
+ let body;
4779
+ try {
4780
+ body = JSON.parse(error.text);
4781
+ } catch {
4782
+ return null;
4783
+ }
4784
+ const conflicts = body?.conflicts;
4785
+ if (!Array.isArray(conflicts)) return null;
4786
+ return conflicts.filter(isConflictPath).map(({ path: path16, reason }) => ({ path: path16, reason }));
4787
+ }
4788
+ function isConflictPath(value) {
4789
+ const entry = value;
4790
+ return typeof entry?.path === "string" && typeof entry.reason === "string";
4791
+ }
4792
+ function uncommittedPaths(error) {
4793
+ if (!(error instanceof ApiError) || error.status !== 409 || error.code !== "sandbox_uncommitted") return null;
4794
+ let body;
4795
+ try {
4796
+ body = JSON.parse(error.text);
4797
+ } catch {
4798
+ return null;
4799
+ }
4800
+ const uncommitted = body?.uncommitted;
4801
+ if (!Array.isArray(uncommitted)) return null;
4802
+ return uncommitted.filter((p) => typeof p === "string");
4803
+ }
4804
+ function listQuery(filter) {
4805
+ const params = new URLSearchParams();
4806
+ if (filter.status) params.set("status", filter.status);
4807
+ if (filter.slug) params.set("slug", filter.slug);
4808
+ if (filter.limit !== void 0) params.set("limit", String(filter.limit));
4809
+ const qs3 = params.toString();
4810
+ return qs3 ? `?${qs3}` : "";
4811
+ }
4812
+ var isSandboxImportPending, sid, SANDBOXES, SANDBOX_REQUEST_TIMEOUT_MS, WorldSandboxClient;
4813
+ var init_sandbox = __esm({
4814
+ "src/worlds/sandbox.ts"() {
4815
+ "use strict";
4816
+ init_worlds();
4817
+ isSandboxImportPending = (answer) => !("versionId" in answer);
4818
+ sid = encodeURIComponent;
4819
+ SANDBOXES = "/api/public/benchmark-containers/sandboxes";
4820
+ SANDBOX_REQUEST_TIMEOUT_MS = 66e4;
4821
+ WorldSandboxClient = class {
4822
+ constructor(options = {}) {
4823
+ this.options = options;
4824
+ }
4825
+ options;
4826
+ request(method, path16, body) {
4827
+ return apiRequest(this.options, method, path16, body, {
4828
+ timeoutMs: SANDBOX_REQUEST_TIMEOUT_MS
4829
+ });
4830
+ }
4831
+ /**
4832
+ * `{ slug, ref? }` opens a READY version; `{ new, from }` opens a sandbox on
4833
+ * a world that does not exist yet (409 `world_exists` if the slug is taken,
4834
+ * 400 naming the shipped templates if `from` is unknown). Its first commit
4835
+ * creates the world on `main`.
4836
+ */
4837
+ open(target) {
4838
+ return this.request("POST", `${SANDBOXES}`, target);
4839
+ }
4840
+ status(sandboxId) {
4841
+ return this.request("GET", `${SANDBOXES}/${sid(sandboxId)}`);
4842
+ }
4843
+ /** The project's sandboxes, newest first — how an agent finds one it left open. */
4844
+ async list(filter = {}) {
4845
+ const res = await this.request("GET", `${SANDBOXES}${listQuery(filter)}`);
4846
+ return res.sandboxes;
4847
+ }
4848
+ async read(sandboxId, filePath) {
4849
+ const res = await this.request(
4850
+ "GET",
4851
+ `${SANDBOXES}/${sid(sandboxId)}/file?path=${encodeURIComponent(filePath)}`
4852
+ );
4853
+ return { path: res.path, size: res.size, bytes: Buffer.from(res.contentBase64, "base64") };
4854
+ }
4855
+ write(sandboxId, filePath, bytes) {
4856
+ return this.request("PUT", `${SANDBOXES}/${sid(sandboxId)}/file`, {
4857
+ path: filePath,
4858
+ contentBase64: bytes.toString("base64")
4859
+ });
4860
+ }
4861
+ exec(sandboxId, input) {
4862
+ return this.request("POST", `${SANDBOXES}/${sid(sandboxId)}/exec`, input);
4863
+ }
4864
+ check(sandboxId) {
4865
+ return this.request("POST", `${SANDBOXES}/${sid(sandboxId)}/check`, {});
4866
+ }
4867
+ /** With `rebase`, a moved base is replayed onto; a 409 then names the conflicting paths (`rebaseConflicts`). */
4868
+ commit(sandboxId, input) {
4869
+ const { rebase, ...rest } = input;
4870
+ return this.request("POST", `${SANDBOXES}/${sid(sandboxId)}/commit`, rebase ? { ...rest, rebase: true } : rest);
4871
+ }
4872
+ /**
4873
+ * A rows file already in the sandbox tree into the PLATFORM world the
4874
+ * sandbox was opened on (201 with the version, 202 with the batch to poll,
4875
+ * 400 naming a refused row). Not `commit`: a commit versions the source
4876
+ * tree and never carries data.
4877
+ */
4878
+ importData(sandboxId, input) {
4879
+ return this.request("POST", `${SANDBOXES}/${sid(sandboxId)}/import`, input);
4880
+ }
4881
+ /** Uncommitted work is a 409 (`uncommittedPaths`) unless `force` discards it. */
4882
+ close(sandboxId, opts = {}) {
4883
+ return this.request("DELETE", `${SANDBOXES}/${sid(sandboxId)}`, opts.force ? { force: true } : void 0);
4884
+ }
4885
+ };
3813
4886
  }
3814
4887
  });
3815
4888
 
3816
4889
  // src/worlds/describe.ts
3817
- async function describeWorld(slug, options = {}) {
3818
- if (slug.includes("@"))
3819
- throw new Error(
3820
- `describeWorld reads a world's head version: pass the slug without @ref (got ${slug})`
3821
- );
4890
+ async function describeWorld(slugRef, options = {}) {
4891
+ const { slug, ref } = parseSlugRef(slugRef);
4892
+ const query = ref === void 0 ? "" : `?ref=${encodeURIComponent(ref)}`;
3822
4893
  return apiRequest(
3823
4894
  options,
3824
4895
  "GET",
3825
- `/api/public/worlds/${encodeURIComponent(slug)}`
4896
+ `/api/public/worlds/${encodeURIComponent(slug)}${query}`
3826
4897
  );
3827
4898
  }
3828
4899
  var init_describe = __esm({
3829
4900
  "src/worlds/describe.ts"() {
3830
4901
  "use strict";
3831
4902
  init_worlds();
4903
+ init_sandbox();
3832
4904
  }
3833
4905
  });
3834
4906
 
@@ -3933,6 +5005,7 @@ var init_json = __esm({
3933
5005
  constructor(text2) {
3934
5006
  this.text = text2;
3935
5007
  }
5008
+ text;
3936
5009
  /** A float in Python's eyes: a fraction, an exponent, or a non-finite literal. */
3937
5010
  get isFloat() {
3938
5011
  return /[.eE]/.test(this.text) || /[nN]/.test(this.text);
@@ -3947,6 +5020,7 @@ var init_json = __esm({
3947
5020
  constructor(s) {
3948
5021
  this.s = s;
3949
5022
  }
5023
+ s;
3950
5024
  i = 0;
3951
5025
  skipWs() {
3952
5026
  const s = this.s;
@@ -4226,24 +5300,24 @@ function roundForm(plaintext, decimals) {
4226
5300
  if (typeof plaintext === "string" || isInt(plaintext) || !Number.isFinite(plaintext)) return plaintext;
4227
5301
  return pyRound(new JsonNumber(pyFloatRepr(plaintext)), decimals).value;
4228
5302
  }
4229
- function redactionOf(redact, field) {
5303
+ function redactionOf(redact, field2) {
4230
5304
  if (!redact) return null;
4231
- const named = (names) => (names ?? []).some((name) => name === field || name.slice(name.lastIndexOf(".") + 1) === field);
5305
+ const named = (names) => (names ?? []).some((name) => name === field2 || name.slice(name.lastIndexOf(".") + 1) === field2);
4232
5306
  if (named(redact.drop)) return "drop";
4233
5307
  if (named(redact.hash)) return "hash";
4234
5308
  if (named(redact.preserve)) return "preserve";
4235
- const decimals = redact.round?.[field];
5309
+ const decimals = redact.round?.[field2];
4236
5310
  if (typeof decimals === "number") return `round:${decimals}`;
4237
5311
  return null;
4238
5312
  }
4239
- function storedForms(world, field, plaintext, transform) {
5313
+ function storedForms(world, field2, plaintext, transform) {
4240
5314
  if (transform?.length) plaintext = applyTransforms(plaintext, transform);
4241
- const policy = redactionOf(world.redact, field);
5315
+ const policy = redactionOf(world.redact, field2);
4242
5316
  const salt = world.redact?.slug ?? world.slug;
4243
5317
  if (policy === "drop") return [];
4244
5318
  if (policy === "hash") return [hashForm(salt, plaintext)];
4245
5319
  if (policy === "preserve") return [preserveForm(salt, plaintext)];
4246
- if (policy !== null) return [roundForm(plaintext, world.redact.round[field])];
5320
+ if (policy !== null) return [roundForm(plaintext, world.redact.round[field2])];
4247
5321
  return [plaintext];
4248
5322
  }
4249
5323
  var import_node_crypto7, isInt;
@@ -4329,71 +5403,42 @@ var init_router = __esm({
4329
5403
  super(message);
4330
5404
  this.exitCode = exitCode;
4331
5405
  }
5406
+ exitCode;
4332
5407
  };
4333
5408
  }
4334
5409
  });
4335
5410
 
4336
5411
  // src/cli/config.ts
4337
- function transportDetail(error, timeoutMs) {
4338
- if (error instanceof Error && error.name === "AbortError") return `timed out after ${Math.round(timeoutMs / 1e3)}s`;
4339
- const cause = error instanceof Error && error.cause instanceof Error ? error.cause : void 0;
4340
- const code = cause && "code" in cause && typeof cause.code === "string" ? `${cause.code}: ` : "";
4341
- const message = cause?.message ?? (error instanceof Error ? error.message : String(error));
4342
- return `${code}${message}`;
4343
- }
4344
5412
  async function api(creds, method, route, body, init3 = {}) {
4345
- const controller = new AbortController();
4346
- const timeoutMs = init3.timeoutMs ?? 12e4;
4347
- const timer = setTimeout(() => controller.abort(), timeoutMs);
4348
- let res;
4349
- try {
4350
- res = await fetch(`${creds.host}${route}`, {
4351
- method,
4352
- headers: {
4353
- "content-type": "application/json",
4354
- accept: "application/json",
4355
- authorization: "Basic " + Buffer.from(`${creds.publicKey}:${creds.secretKey}`).toString("base64")
4356
- },
4357
- ...body === void 0 ? {} : { body: JSON.stringify(body) },
4358
- signal: controller.signal
4359
- });
4360
- } catch (error) {
4361
- clearTimeout(timer);
4362
- throw new UnreachableError(creds.host, method, route, transportDetail(error, timeoutMs));
4363
- }
4364
- try {
4365
- const text2 = await res.text();
4366
- if (!res.ok) throw new ApiError(res.status, method, route, text2);
4367
- return text2 ? JSON.parse(text2) : {};
4368
- } finally {
4369
- clearTimeout(timer);
4370
- }
5413
+ const reply = await new PlatformTransport(creds).send(method, route, body, init3);
5414
+ if (!reply.ok) throw new ApiError2(reply.status, method, route, reply.text);
5415
+ return reply.text ? JSON.parse(reply.text) : {};
4371
5416
  }
4372
- var fs4, os, path4, ApiError, UnreachableError;
5417
+ var fs6, os, path6, ApiError2;
4373
5418
  var init_config = __esm({
4374
5419
  "src/cli/config.ts"() {
4375
5420
  "use strict";
4376
- fs4 = __toESM(require("fs"));
5421
+ fs6 = __toESM(require("fs"));
4377
5422
  os = __toESM(require("os"));
4378
- path4 = __toESM(require("path"));
5423
+ path6 = __toESM(require("path"));
4379
5424
  init_router();
4380
- ApiError = class extends CliError {
5425
+ init_worlds();
5426
+ init_transport();
5427
+ ApiError2 = class extends CliError {
4381
5428
  constructor(status, method, route, text2) {
4382
- super(`${method} ${route} -> ${status}: ${text2.slice(0, 600)}`, 1);
5429
+ const body = parseErrorBody(text2);
5430
+ super(`${method} ${route} -> ${status}: ${body.detail}`, 1);
4383
5431
  this.status = status;
4384
5432
  this.method = method;
4385
5433
  this.route = route;
4386
5434
  this.text = text2;
5435
+ this.code = body.code;
4387
5436
  }
4388
- };
4389
- UnreachableError = class extends CliError {
4390
- constructor(host, method, route, detail) {
4391
- super(`${method} ${route}: no answer from ${host} (${detail}). Check the host and the network, then retry.`, 1);
4392
- this.host = host;
4393
- this.method = method;
4394
- this.route = route;
4395
- this.detail = detail;
4396
- }
5437
+ status;
5438
+ method;
5439
+ route;
5440
+ text;
5441
+ code;
4397
5442
  };
4398
5443
  }
4399
5444
  });
@@ -4413,22 +5458,22 @@ function runtimeRoot() {
4413
5458
  const candidates = [];
4414
5459
  if (process.env.GATEWAY_RUNTIME_PATH)
4415
5460
  candidates.push(process.env.GATEWAY_RUNTIME_PATH);
4416
- const entry = process.argv[1] && fs5.existsSync(process.argv[1]) ? path5.dirname(fs5.realpathSync(process.argv[1])) : null;
5461
+ const entry = process.argv[1] && fs7.existsSync(process.argv[1]) ? path7.dirname(fs7.realpathSync(process.argv[1])) : null;
4417
5462
  if (entry) {
4418
- candidates.push(path5.resolve(entry, "..", "runtime"));
4419
- candidates.push(path5.resolve(entry, "..", "..", "runtime"));
4420
- candidates.push(path5.resolve(entry, "..", "..", "sdk", "src"));
5463
+ candidates.push(path7.resolve(entry, "..", "runtime"));
5464
+ candidates.push(path7.resolve(entry, "..", "..", "runtime"));
5465
+ candidates.push(path7.resolve(entry, "..", "..", "sdk", "src"));
4421
5466
  }
4422
- candidates.push(path5.resolve(process.cwd(), "runtime"));
5467
+ candidates.push(path7.resolve(process.cwd(), "runtime"));
4423
5468
  for (const root of candidates)
4424
- if (fs5.existsSync(
4425
- path5.join(root, "gatewaysdk", "environment", "schema", "platform.py")
5469
+ if (fs7.existsSync(
5470
+ path7.join(root, "gatewaysdk", "environment", "schema", "platform.py")
4426
5471
  ))
4427
5472
  return root;
4428
5473
  return null;
4429
5474
  }
4430
5475
  function probeVersion(name) {
4431
- const probe = (0, import_node_child_process.spawnSync)(
5476
+ const probe = (0, import_node_child_process2.spawnSync)(
4432
5477
  name,
4433
5478
  ["-c", "import sys;print(sys.version_info[0],sys.version_info[1])"],
4434
5479
  { encoding: "utf8", timeout: 1e4 }
@@ -4442,7 +5487,7 @@ function atLeastMinimum(version) {
4442
5487
  return major > MIN_PYTHON[0] || major === MIN_PYTHON[0] && minor >= MIN_PYTHON[1];
4443
5488
  }
4444
5489
  function uvPython() {
4445
- const found = (0, import_node_child_process.spawnSync)("uv", UV_FIND, { encoding: "utf8", timeout: 1e4 });
5490
+ const found = (0, import_node_child_process2.spawnSync)("uv", UV_FIND, { encoding: "utf8", timeout: 1e4 });
4446
5491
  if (found.status !== 0) return null;
4447
5492
  const line = found.stdout.trim().split(/\r?\n/)[0] ?? "";
4448
5493
  return line || null;
@@ -4501,12 +5546,12 @@ function localRuntime() {
4501
5546
  return { python, root };
4502
5547
  }
4503
5548
  function localPythonHasYaml(python) {
4504
- return (0, import_node_child_process.spawnSync)(python, ["-c", "import yaml"], { timeout: 1e4 }).status === 0;
5549
+ return (0, import_node_child_process2.spawnSync)(python, ["-c", "import yaml"], { timeout: 1e4 }).status === 0;
4505
5550
  }
4506
5551
  async function localBridge(request, local, opts = {}) {
4507
5552
  const input = JSON.stringify(request);
4508
- return await new Promise((resolve10, reject) => {
4509
- const child = (0, import_node_child_process.spawn)(
5553
+ return await new Promise((resolve11, reject) => {
5554
+ const child = (0, import_node_child_process2.spawn)(
4510
5555
  local.python,
4511
5556
  ["-I", "-B", "-c", BRIDGE_BOOTSTRAP, local.root],
4512
5557
  {
@@ -4550,7 +5595,7 @@ async function localBridge(request, local, opts = {}) {
4550
5595
  payload = null;
4551
5596
  }
4552
5597
  if (payload && typeof payload === "object") {
4553
- resolve10(payload);
5598
+ resolve11(payload);
4554
5599
  return;
4555
5600
  }
4556
5601
  reject(
@@ -4563,17 +5608,17 @@ async function localBridge(request, local, opts = {}) {
4563
5608
  child.stdin.end(input);
4564
5609
  });
4565
5610
  }
4566
- var import_node_child_process, fs5, net, path5, MIN_PYTHON, DIAGNOSTIC_TAIL, BRIDGE_BOOTSTRAP, pythonCache, pythonProbes, PYTHON_CANDIDATES, UV_FIND;
5611
+ var import_node_child_process2, fs7, net, path7, MIN_PYTHON, DIAGNOSTIC_TAIL, BRIDGE_BOOTSTRAP, pythonCache, pythonProbes, PYTHON_CANDIDATES, UV_FIND;
4567
5612
  var init_local = __esm({
4568
5613
  "src/cli/runtime/local.ts"() {
4569
5614
  "use strict";
4570
- import_node_child_process = require("child_process");
4571
- fs5 = __toESM(require("fs"));
5615
+ import_node_child_process2 = require("child_process");
5616
+ fs7 = __toESM(require("fs"));
4572
5617
  net = __toESM(require("net"));
4573
- path5 = __toESM(require("path"));
5618
+ path7 = __toESM(require("path"));
4574
5619
  init_router();
4575
5620
  init_config();
4576
- MIN_PYTHON = [3, 11];
5621
+ MIN_PYTHON = [3, 12];
4577
5622
  DIAGNOSTIC_TAIL = 600;
4578
5623
  BRIDGE_BOOTSTRAP = `import sys,runpy,types,os
4579
5624
  root=sys.argv[1]
@@ -4585,7 +5630,6 @@ runpy.run_module('gatewaysdk.environment.schema.platform',run_name='__main__')`;
4585
5630
  PYTHON_CANDIDATES = [
4586
5631
  "python3.13",
4587
5632
  "python3.12",
4588
- "python3.11",
4589
5633
  "python3",
4590
5634
  "python"
4591
5635
  ];
@@ -4598,12 +5642,12 @@ function isBuildOutput(relPath) {
4598
5642
  return BUILD_OUTPUT.test(relPath);
4599
5643
  }
4600
5644
  function readWorldFiles(dir, opts = {}) {
4601
- if (!fs6.existsSync(dir) || !fs6.statSync(dir).isDirectory())
5645
+ if (!fs8.existsSync(dir) || !fs8.statSync(dir).isDirectory())
4602
5646
  throw new CliError(`Not a directory: ${dir}`);
4603
5647
  const out = [];
4604
5648
  const walk = (rel) => {
4605
- const abs = rel ? path6.join(dir, rel) : dir;
4606
- const entries = fs6.readdirSync(abs, { withFileTypes: true });
5649
+ const abs = rel ? path8.join(dir, rel) : dir;
5650
+ const entries = fs8.readdirSync(abs, { withFileTypes: true });
4607
5651
  entries.sort((a, b) => a.name.localeCompare(b.name));
4608
5652
  for (const entry of entries) {
4609
5653
  const childRel = rel ? `${rel}/${entry.name}` : entry.name;
@@ -4613,7 +5657,7 @@ function readWorldFiles(dir, opts = {}) {
4613
5657
  if (!opts.buildOutputs && isBuildOutput(childRel)) continue;
4614
5658
  out.push({
4615
5659
  path: childRel,
4616
- content: fs6.readFileSync(path6.join(dir, childRel)).toString("base64")
5660
+ content: fs8.readFileSync(path8.join(dir, childRel)).toString("base64")
4617
5661
  });
4618
5662
  }
4619
5663
  }
@@ -4627,20 +5671,22 @@ function assertSafeRelPath(rel) {
4627
5671
  throw new CliError(`The runtime returned an unsafe file path: ${rel}`, 1);
4628
5672
  }
4629
5673
  function writeWorldFiles(dir, files, opts = {}) {
5674
+ if (files.length > MAX_WORLD_FILES)
5675
+ throw new CliError(`The runtime returned ${files.length} files, over the ${MAX_WORLD_FILES} limit`, 1);
4630
5676
  for (const file of files) assertSafeRelPath(file.path);
4631
- if (opts.clean && fs6.existsSync(dir)) {
5677
+ if (opts.clean && fs8.existsSync(dir)) {
4632
5678
  const keep = new Set(files.map((f) => f.path));
4633
5679
  for (const existing of readWorldFiles(dir)) {
4634
- if (!keep.has(existing.path)) fs6.rmSync(path6.join(dir, existing.path));
5680
+ if (!keep.has(existing.path)) fs8.rmSync(path8.join(dir, existing.path));
4635
5681
  }
4636
5682
  pruneEmptyDirs(dir);
4637
5683
  }
4638
- fs6.mkdirSync(dir, { recursive: true });
5684
+ fs8.mkdirSync(dir, { recursive: true });
4639
5685
  const written = [];
4640
5686
  for (const file of files) {
4641
- const target = path6.join(dir, file.path);
4642
- fs6.mkdirSync(path6.dirname(target), { recursive: true });
4643
- fs6.writeFileSync(target, Buffer.from(file.content, "base64"));
5687
+ const target = path8.join(dir, file.path);
5688
+ fs8.mkdirSync(path8.dirname(target), { recursive: true });
5689
+ fs8.writeFileSync(target, Buffer.from(file.content, "base64"));
4644
5690
  written.push(file.path);
4645
5691
  }
4646
5692
  return written;
@@ -4648,14 +5694,14 @@ function writeWorldFiles(dir, files, opts = {}) {
4648
5694
  function pruneEmptyDirs(root) {
4649
5695
  const walk = (abs) => {
4650
5696
  let empty = true;
4651
- for (const entry of fs6.readdirSync(abs, { withFileTypes: true })) {
4652
- const child = path6.join(abs, entry.name);
5697
+ for (const entry of fs8.readdirSync(abs, { withFileTypes: true })) {
5698
+ const child = path8.join(abs, entry.name);
4653
5699
  if (entry.isDirectory()) {
4654
5700
  if (SKIP_DIRS.has(entry.name)) {
4655
5701
  empty = false;
4656
5702
  continue;
4657
5703
  }
4658
- if (walk(child)) fs6.rmdirSync(child);
5704
+ if (walk(child)) fs8.rmdirSync(child);
4659
5705
  else empty = false;
4660
5706
  } else empty = false;
4661
5707
  }
@@ -4675,58 +5721,61 @@ function detailFrom(payload) {
4675
5721
  if (typeof detail.code !== "string" || typeof detail.message !== "string") return null;
4676
5722
  return detail;
4677
5723
  }
5724
+ function isYamlSource(name, base64) {
5725
+ if (name.endsWith(".json")) return false;
5726
+ if (YAML_NAME.test(name)) return true;
5727
+ const head = Buffer.from(base64.slice(0, 256), "base64").toString("utf8").trimStart();
5728
+ return !["{", "["].includes(head[0] ?? "");
5729
+ }
5730
+ function yamlDocument(request) {
5731
+ if (request.command === "init-openapi")
5732
+ return isYamlSource(String(request.source ?? ""), String(request.document ?? ""));
5733
+ return request.command === "conform" && Array.isArray(request.openapi) && request.openapi.some((doc) => YAML_NAME.test(doc.path ?? ""));
5734
+ }
5735
+ function runsLocally(request) {
5736
+ const local = localRuntime();
5737
+ return local !== null && !(yamlDocument(request) && !localPythonHasYaml(local.python));
5738
+ }
4678
5739
  async function runtime(creds, request, opts = {}) {
4679
5740
  const local = localRuntime();
4680
- const yamlSpec = request.command === "conform" && Array.isArray(request.openapi) && request.openapi.some((doc) => /\.ya?ml$/i.test(doc.path ?? ""));
4681
- if (local && !(yamlSpec && !localPythonHasYaml(local.python))) {
4682
- const payload = await localBridge(request, local, opts);
4683
- const detail = detailFrom(payload);
4684
- if (detail) throw new BridgeRejected(detail);
4685
- return payload;
5741
+ if (local && runsLocally(request)) {
5742
+ const payload2 = await localBridge(request, local, opts);
5743
+ const detail2 = detailFrom(payload2);
5744
+ if (detail2) throw new BridgeRejected(detail2);
5745
+ return payload2;
4686
5746
  }
4687
5747
  if (!creds)
4688
5748
  throw new CliError(
4689
5749
  "This needs the schema runtime (the CLI bundles it) or platform credentials (`gateway auth login`). " + localRuntimeReason()
4690
5750
  );
4691
- const controller = new AbortController();
4692
- const timer = setTimeout(() => controller.abort(), opts.timeoutMs ?? 18e4);
4693
5751
  const route = "/api/public/worlds/runtime";
5752
+ const res = await new PlatformTransport(creds).send("POST", route, request, {
5753
+ timeoutMs: opts.timeoutMs ?? RUNTIME_TIMEOUT_MS
5754
+ });
5755
+ let payload = null;
4694
5756
  try {
4695
- const res = await fetch(`${creds.host}${route}`, {
4696
- method: "POST",
4697
- headers: {
4698
- "content-type": "application/json",
4699
- accept: "application/json",
4700
- authorization: "Basic " + Buffer.from(`${creds.publicKey}:${creds.secretKey}`).toString("base64")
4701
- },
4702
- body: JSON.stringify(request),
4703
- signal: controller.signal
4704
- });
4705
- const text2 = await res.text();
4706
- let payload = null;
4707
- try {
4708
- payload = text2 ? JSON.parse(text2) : {};
4709
- } catch {
4710
- payload = null;
4711
- }
4712
- const detail = detailFrom(payload);
4713
- if (detail) throw new BridgeRejected(detail);
4714
- if (!res.ok)
4715
- throw new CliError(`POST ${route} (${request.command}) -> ${res.status}: ${text2.slice(0, 600)}`, 1);
4716
- if (payload === null) throw new CliError(`POST ${route} (${request.command}) returned non-JSON`, 1);
4717
- return payload;
4718
- } finally {
4719
- clearTimeout(timer);
5757
+ payload = res.text ? JSON.parse(res.text) : {};
5758
+ } catch {
5759
+ payload = null;
4720
5760
  }
5761
+ const detail = detailFrom(payload);
5762
+ if (detail) throw new BridgeRejected(detail);
5763
+ if (!res.ok)
5764
+ throw new CliError(`POST ${route} (${request.command}) -> ${res.status}: ${res.text.slice(0, 600)}`, 1);
5765
+ if (payload === null) throw new CliError(`POST ${route} (${request.command}) returned non-JSON`, 1);
5766
+ return payload;
4721
5767
  }
4722
- var fs6, path6, SKIP_DIRS, BUILD_OUTPUT, BridgeRejected;
5768
+ var fs8, path8, MAX_WORLD_FILES, RUNTIME_TIMEOUT_MS, SKIP_DIRS, BUILD_OUTPUT, BridgeRejected, YAML_NAME;
4723
5769
  var init_client = __esm({
4724
5770
  "src/cli/runtime/client.ts"() {
4725
5771
  "use strict";
4726
- fs6 = __toESM(require("fs"));
4727
- path6 = __toESM(require("path"));
5772
+ fs8 = __toESM(require("fs"));
5773
+ path8 = __toESM(require("path"));
4728
5774
  init_router();
4729
5775
  init_local();
5776
+ init_transport();
5777
+ MAX_WORLD_FILES = 2e3;
5778
+ RUNTIME_TIMEOUT_MS = 18e4;
4730
5779
  SKIP_DIRS = /* @__PURE__ */ new Set(["__pycache__", ".git", "node_modules", ".gateway"]);
4731
5780
  BUILD_OUTPUT = /(^|\/)state\.(sqlite|json)$/;
4732
5781
  BridgeRejected = class extends CliError {
@@ -4734,7 +5783,9 @@ var init_client = __esm({
4734
5783
  super(formatBridgeError(detail), 1);
4735
5784
  this.detail = detail;
4736
5785
  }
5786
+ detail;
4737
5787
  };
5788
+ YAML_NAME = /\.ya?ml$/i;
4738
5789
  }
4739
5790
  });
4740
5791
 
@@ -4742,8 +5793,10 @@ var init_client = __esm({
4742
5793
  var data_exports = {};
4743
5794
  __export(data_exports, {
4744
5795
  checkLocalWorldData: () => checkLocalWorldData,
5796
+ chunkLocalWorldFiles: () => chunkLocalWorldFiles,
4745
5797
  dropBuildOutputs: () => dropBuildOutputs,
4746
5798
  importLocalWorldData: () => importLocalWorldData,
5799
+ importLocalWorldFiles: () => importLocalWorldFiles,
4747
5800
  ingestLocalToolCalls: () => ingestLocalToolCalls,
4748
5801
  queryLocalWorldData: () => queryLocalWorldData,
4749
5802
  queryLocalWorldDataAcross: () => queryLocalWorldDataAcross,
@@ -4770,11 +5823,57 @@ async function importLocalWorldData(dir, rows, opts, creds) {
4770
5823
  } : {}
4771
5824
  };
4772
5825
  }
5826
+ async function importLocalWorldFiles(dir, sources, opts) {
5827
+ const local = localRuntime();
5828
+ if (!local)
5829
+ throw new CliError(
5830
+ `Rows files stream into a directory through the bundled runtime on this machine, and none can run: ${localRuntimeReason()}`,
5831
+ 1
5832
+ );
5833
+ const res = await runtime(null, {
5834
+ command: "import-files",
5835
+ world: path9.resolve(dir),
5836
+ sources: sources.map((source) => path9.resolve(source)),
5837
+ mode: opts.mode ?? "append",
5838
+ ...opts.entity ? { entity: opts.entity } : {},
5839
+ ...opts.delimiter ? { delimiter: opts.delimiter } : {},
5840
+ ...opts.merge && opts.merge !== "upsert" ? { merge: opts.merge } : {},
5841
+ ...opts.redact && opts.redact !== "off" ? { redact: opts.redact } : {},
5842
+ ...opts.dryRun ? { dry_run: true } : {}
5843
+ });
5844
+ return {
5845
+ kind: res.kind ?? "unknown",
5846
+ entity_counts: res.entity_counts ?? {},
5847
+ changed: Boolean(res.changed),
5848
+ rows: res.rows ?? 0,
5849
+ ...res.proof ? { proof: res.proof } : {},
5850
+ ...res.deferred ? { deferred: res.deferred } : {}
5851
+ };
5852
+ }
5853
+ async function chunkLocalWorldFiles(dir, sources, out, opts) {
5854
+ const local = localRuntime();
5855
+ if (!local)
5856
+ throw new CliError(
5857
+ `Rows files are cut into chunks by the bundled runtime on this machine, and none can run: ${localRuntimeReason()}`,
5858
+ 1
5859
+ );
5860
+ const res = await runtime(null, {
5861
+ command: "chunk-files",
5862
+ world: path9.resolve(dir),
5863
+ sources: sources.map((source) => path9.resolve(source)),
5864
+ out: path9.resolve(out),
5865
+ ...opts.entity ? { entity: opts.entity } : {},
5866
+ ...opts.delimiter ? { delimiter: opts.delimiter } : {},
5867
+ ...opts.chunkBytes ? { chunk_bytes: opts.chunkBytes } : {},
5868
+ ...opts.chunkRows ? { chunk_rows: opts.chunkRows } : {}
5869
+ });
5870
+ return { rows: res.rows ?? 0, chunks: res.chunks ?? [] };
5871
+ }
4773
5872
  function dropBuildOutputs(dir) {
4774
5873
  const dropped = [];
4775
5874
  for (const file of readWorldFiles(dir, { buildOutputs: true })) {
4776
5875
  if (!BUILD_OUTPUT2.test(file.path)) continue;
4777
- fs7.rmSync(path7.join(dir, file.path), { force: true });
5876
+ fs9.rmSync(path9.join(dir, file.path), { force: true });
4778
5877
  dropped.push(file.path);
4779
5878
  }
4780
5879
  return dropped;
@@ -4841,7 +5940,7 @@ async function queryLocalWorldDataAcross(dir, entity, where, opts) {
4841
5940
  const payload = await localBridge(
4842
5941
  {
4843
5942
  command: "query",
4844
- world: path7.resolve(dir),
5943
+ world: path9.resolve(dir),
4845
5944
  entity,
4846
5945
  across: true,
4847
5946
  ...opts.compare ? { compare: true } : {},
@@ -4888,12 +5987,12 @@ async function ingestLocalToolCalls(dir, records, opts, creds) {
4888
5987
  ...res.batch !== void 0 ? { batch: res.batch } : {}
4889
5988
  };
4890
5989
  }
4891
- var fs7, path7, BUILD_OUTPUT2;
5990
+ var fs9, path9, BUILD_OUTPUT2;
4892
5991
  var init_data = __esm({
4893
5992
  "src/cli/runtime/data.ts"() {
4894
5993
  "use strict";
4895
- fs7 = __toESM(require("fs"));
4896
- path7 = __toESM(require("path"));
5994
+ fs9 = __toESM(require("fs"));
5995
+ path9 = __toESM(require("path"));
4897
5996
  init_router();
4898
5997
  init_client();
4899
5998
  init_local();
@@ -4936,27 +6035,27 @@ function typescriptPrefix() {
4936
6035
  }
4937
6036
  }
4938
6037
  function command(script, wrapperDir) {
4939
- const suffix = path8.extname(script).toLowerCase();
6038
+ const suffix = path10.extname(script).toLowerCase();
4940
6039
  if (PYTHON_SUFFIXES.includes(suffix)) return { file: process.env.GATEWAY_PYTHON || "python3", args: ["-c", PY_WRAPPER, script] };
4941
6040
  if (NODE_SUFFIXES.includes(suffix)) {
4942
- const wrapper = path8.join(wrapperDir, "transform-wrapper.mjs");
4943
- fs8.writeFileSync(wrapper, NODE_WRAPPER);
6041
+ const wrapper = path10.join(wrapperDir, "transform-wrapper.mjs");
6042
+ fs10.writeFileSync(wrapper, NODE_WRAPPER);
4944
6043
  const flags = suffix === ".ts" || suffix === ".mts" ? typescriptPrefix() : [];
4945
6044
  return { file: process.env.GATEWAY_NODE || process.execPath, args: [...flags, wrapper, script] };
4946
6045
  }
4947
- throw new CliError(`${path8.basename(script)}: a transform script is .py, .ts, .mjs, .js or .cjs`, 1);
6046
+ throw new CliError(`${path10.basename(script)}: a transform script is .py, .ts, .mjs, .js or .cjs`, 1);
4948
6047
  }
4949
6048
  async function runTransform(script, records, opts = {}) {
4950
- if (!fs8.existsSync(script) || !fs8.statSync(script).isFile()) throw new CliError(`no transform script at ${script}`, 1);
4951
- const resolved = path8.resolve(script);
4952
- const name = path8.basename(script);
6049
+ if (!fs10.existsSync(script) || !fs10.statSync(script).isFile()) throw new CliError(`no transform script at ${script}`, 1);
6050
+ const resolved = path10.resolve(script);
6051
+ const name = path10.basename(script);
4953
6052
  const timeoutMs = opts.timeoutMs ?? DEFAULT_TRANSFORM_TIMEOUT_MS;
4954
- const scratch = fs8.mkdtempSync(path8.join(os2.tmpdir(), "gateway-transform-"));
6053
+ const scratch = fs10.mkdtempSync(path10.join(os2.tmpdir(), "gateway-transform-"));
4955
6054
  try {
4956
6055
  const { file, args } = command(resolved, scratch);
4957
6056
  const env = Object.fromEntries(Object.entries(process.env).filter(([key2]) => !SCRUBBED.test(key2)));
4958
- const done = await new Promise((resolve10, reject) => {
4959
- const child = (0, import_node_child_process2.spawn)(file, args, { cwd: path8.dirname(resolved), env, stdio: ["pipe", "pipe", "pipe"] });
6057
+ const done = await new Promise((resolve11, reject) => {
6058
+ const child = (0, import_node_child_process3.spawn)(file, args, { cwd: path10.dirname(resolved), env, stdio: ["pipe", "pipe", "pipe"] });
4960
6059
  let stdout = "";
4961
6060
  let stderr = "";
4962
6061
  let timedOut = false;
@@ -4972,7 +6071,7 @@ async function runTransform(script, records, opts = {}) {
4972
6071
  });
4973
6072
  child.on("close", (code) => {
4974
6073
  clearTimeout(timer);
4975
- resolve10({ code, stdout, stderr, timedOut });
6074
+ resolve11({ code, stdout, stderr, timedOut });
4976
6075
  });
4977
6076
  child.stdin.on("error", () => void 0);
4978
6077
  child.stdin.end(records.map((record) => JSON.stringify(record) + "\n").join(""));
@@ -4987,21 +6086,21 @@ async function runTransform(script, records, opts = {}) {
4987
6086
  }
4988
6087
  return { rows: checkRows(value, name), stderr: done.stderr };
4989
6088
  } finally {
4990
- fs8.rmSync(scratch, { recursive: true, force: true });
6089
+ fs10.rmSync(scratch, { recursive: true, force: true });
4991
6090
  }
4992
6091
  }
4993
6092
  async function transformRecords(transform, records, opts = {}) {
4994
6093
  if (typeof transform === "function") return { rows: checkRows(await transform(records), "transform(records)"), stderr: "" };
4995
6094
  return runTransform(transform, records, opts);
4996
6095
  }
4997
- var import_node_child_process2, fs8, os2, path8, import_node_module, import_meta, DEFAULT_TRANSFORM_TIMEOUT_MS, NODE_SUFFIXES, PYTHON_SUFFIXES, SCRUBBED, PY_WRAPPER, NODE_WRAPPER, isObject, tail;
6096
+ var import_node_child_process3, fs10, os2, path10, import_node_module, import_meta, DEFAULT_TRANSFORM_TIMEOUT_MS, NODE_SUFFIXES, PYTHON_SUFFIXES, SCRUBBED, PY_WRAPPER, NODE_WRAPPER, isObject, tail;
4998
6097
  var init_transform = __esm({
4999
6098
  "src/cli/platform/worldData/transform.ts"() {
5000
6099
  "use strict";
5001
- import_node_child_process2 = require("child_process");
5002
- fs8 = __toESM(require("fs"));
6100
+ import_node_child_process3 = require("child_process");
6101
+ fs10 = __toESM(require("fs"));
5003
6102
  os2 = __toESM(require("os"));
5004
- path8 = __toESM(require("path"));
6103
+ path10 = __toESM(require("path"));
5005
6104
  import_node_module = require("module");
5006
6105
  init_router();
5007
6106
  import_meta = {};
@@ -5140,12 +6239,12 @@ function phaseLine(status) {
5140
6239
  const phase = status.progress?.phase;
5141
6240
  return phase ? `${status.state} (${phase})` : status.state;
5142
6241
  }
5143
- var import_node_crypto8, fs9, TERMINAL_STATES, sleepMs, WorldDataApi;
6242
+ var import_node_crypto8, fs11, TERMINAL_STATES, sleepMs, WorldDataApi;
5144
6243
  var init_batches = __esm({
5145
6244
  "src/cli/platform/worldData/batches.ts"() {
5146
6245
  "use strict";
5147
6246
  import_node_crypto8 = require("crypto");
5148
- fs9 = __toESM(require("fs"));
6247
+ fs11 = __toESM(require("fs"));
5149
6248
  init_config();
5150
6249
  init_router();
5151
6250
  TERMINAL_STATES = /* @__PURE__ */ new Set([
@@ -5154,7 +6253,7 @@ var init_batches = __esm({
5154
6253
  "published",
5155
6254
  "failed"
5156
6255
  ]);
5157
- sleepMs = (ms) => new Promise((resolve10) => setTimeout(resolve10, ms));
6256
+ sleepMs = (ms) => new Promise((resolve11) => setTimeout(resolve11, ms));
5158
6257
  WorldDataApi = class {
5159
6258
  constructor(creds, slug, sleep3 = sleepMs) {
5160
6259
  this.creds = creds;
@@ -5162,6 +6261,9 @@ var init_batches = __esm({
5162
6261
  this.sleep = sleep3;
5163
6262
  this.base = `/api/public/worlds/${encodeURIComponent(slug)}/data`;
5164
6263
  }
6264
+ creds;
6265
+ slug;
6266
+ sleep;
5165
6267
  base;
5166
6268
  open(body) {
5167
6269
  return api(this.creds, "POST", `${this.base}/batches`, body);
@@ -5360,7 +6462,7 @@ function gzipDeterministic(raw, opts = {}) {
5360
6462
  level === 9 ? 2 : level === 1 ? 4 : 0,
5361
6463
  255
5362
6464
  ]);
5363
- const body = (0, import_node_zlib2.deflateRawSync)(raw, { level });
6465
+ const body = (0, import_node_zlib3.deflateRawSync)(raw, { level });
5364
6466
  const trailer = Buffer.alloc(8);
5365
6467
  trailer.writeUInt32LE(crc32(raw), 0);
5366
6468
  trailer.writeUInt32LE(raw.length >>> 0, 4);
@@ -5380,12 +6482,12 @@ function crc32(data) {
5380
6482
  crc = table[(crc ^ data[i]) & 255] ^ crc >>> 8;
5381
6483
  return (crc ^ 4294967295) >>> 0;
5382
6484
  }
5383
- var import_node_crypto9, import_node_zlib2, DEFAULT_CHUNK_BYTES, GZIP_LEVEL, chunkName, table;
6485
+ var import_node_crypto9, import_node_zlib3, DEFAULT_CHUNK_BYTES, GZIP_LEVEL, chunkName, table;
5384
6486
  var init_chunker = __esm({
5385
6487
  "src/cli/platform/worldData/chunker.ts"() {
5386
6488
  "use strict";
5387
6489
  import_node_crypto9 = require("crypto");
5388
- import_node_zlib2 = require("zlib");
6490
+ import_node_zlib3 = require("zlib");
5389
6491
  init_json();
5390
6492
  DEFAULT_CHUNK_BYTES = 64 * 1024 * 1024;
5391
6493
  GZIP_LEVEL = 9;
@@ -5457,7 +6559,7 @@ function parseToolCallRecord(raw) {
5457
6559
  }
5458
6560
  function readToolCallRecords(paths) {
5459
6561
  const records = [];
5460
- for (const file of paths) records.push(...toolCallRecordsIn(fs10.readFileSync(file, "utf8"), file));
6562
+ for (const file of paths) records.push(...toolCallRecordsIn(fs12.readFileSync(file, "utf8"), file));
5461
6563
  return records;
5462
6564
  }
5463
6565
  function toolCallRecordsIn(text2, where) {
@@ -5493,7 +6595,7 @@ async function emit(sink, record) {
5493
6595
  return;
5494
6596
  }
5495
6597
  if (typeof sink === "string") {
5496
- fs10.appendFileSync(sink, JSON.stringify(record) + "\n");
6598
+ fs12.appendFileSync(sink, JSON.stringify(record) + "\n");
5497
6599
  return;
5498
6600
  }
5499
6601
  if (typeof sink === "function") {
@@ -5573,7 +6675,7 @@ async function ingest(world, records, options = {}) {
5573
6675
  const mode = options.mode ?? "append";
5574
6676
  const dryRun = Boolean(options.dryRun);
5575
6677
  const creds = credentialsOf(options);
5576
- const local = fs10.existsSync(world) && fs10.statSync(world).isDirectory();
6678
+ const local = fs12.existsSync(world) && fs12.statSync(world).isDirectory();
5577
6679
  const map = options.map === void 0 ? void 0 : options.map;
5578
6680
  let rows = null;
5579
6681
  let stderr = "";
@@ -5589,9 +6691,9 @@ async function ingest(world, records, options = {}) {
5589
6691
  if (!creds) throw new Error("Gateway keys missing: set GATEWAY_PUBLIC_KEY / GATEWAY_SECRET_KEY (or pass publicKey/secretKey).");
5590
6692
  const { pull: pull2 } = await Promise.resolve().then(() => (init_hub(), hub_exports));
5591
6693
  const slug = world.split("@", 1)[0];
5592
- const scratch = fs10.mkdtempSync(path9.join(os3.tmpdir(), "gateway-ingest-"));
6694
+ const scratch = fs12.mkdtempSync(path11.join(os3.tmpdir(), "gateway-ingest-"));
5593
6695
  try {
5594
- const pulled = await pull2(world, path9.join(scratch, slug), options);
6696
+ const pulled = await pull2(world, path11.join(scratch, slug), options);
5595
6697
  let report;
5596
6698
  let projected;
5597
6699
  if (rows === null) {
@@ -5612,7 +6714,7 @@ async function ingest(world, records, options = {}) {
5612
6714
  if (status.entityCounts) report.entityCounts = status.entityCounts;
5613
6715
  return report;
5614
6716
  } finally {
5615
- fs10.rmSync(scratch, { recursive: true, force: true });
6717
+ fs12.rmSync(scratch, { recursive: true, force: true });
5616
6718
  }
5617
6719
  }
5618
6720
  async function ingestToolCalls(world, records, options = {}) {
@@ -5665,66 +6767,139 @@ async function sessionToolObservations(sessionId, options = {}) {
5665
6767
  for (const observation of trace5.observations ?? []) out.push({ traceId: trace5.id ?? null, ...observation });
5666
6768
  return out;
5667
6769
  }
5668
- var fs10, os3, path9, isObject2, isoOf;
6770
+ var fs12, os3, path11, isObject2, isoOf;
5669
6771
  var init_ingest = __esm({
5670
6772
  "src/worlds/ingest.ts"() {
5671
6773
  "use strict";
5672
- fs10 = __toESM(require("fs"));
6774
+ fs12 = __toESM(require("fs"));
5673
6775
  os3 = __toESM(require("os"));
5674
- path9 = __toESM(require("path"));
6776
+ path11 = __toESM(require("path"));
5675
6777
  init_worlds();
5676
6778
  isObject2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
5677
6779
  isoOf = (value) => value instanceof Date ? value.toISOString() : typeof value === "string" ? value : void 0;
5678
6780
  }
5679
6781
  });
5680
6782
 
5681
- // src/worlds/sandbox.ts
5682
- function parseSlugRef(slugRef) {
5683
- const at = slugRef.indexOf("@");
5684
- if (at === -1) return { slug: slugRef };
5685
- return { slug: slugRef.slice(0, at), ref: slugRef.slice(at + 1) };
5686
- }
5687
- var sid, WorldSandboxClient;
5688
- var init_sandbox = __esm({
5689
- "src/worlds/sandbox.ts"() {
6783
+ // src/worlds/editSessions.ts
6784
+ var WORLDS, WorldEditClient;
6785
+ var init_editSessions = __esm({
6786
+ "src/worlds/editSessions.ts"() {
5690
6787
  "use strict";
5691
6788
  init_worlds();
5692
- sid = encodeURIComponent;
5693
- WorldSandboxClient = class {
6789
+ WORLDS = "/api/public/worlds";
6790
+ WorldEditClient = class {
5694
6791
  constructor(options = {}) {
5695
6792
  this.options = options;
5696
6793
  }
5697
- open(target) {
5698
- return apiRequest(this.options, "POST", "/api/public/benchmark-containers/sandboxes", target);
6794
+ options;
6795
+ /** The credential's current session and the world's newest-first sessions. */
6796
+ list(slug, query = {}) {
6797
+ const qs3 = new URLSearchParams();
6798
+ if (query.status) qs3.set("status", query.status);
6799
+ if (query.limit !== void 0) qs3.set("limit", String(query.limit));
6800
+ const suffix = qs3.size ? `?${qs3.toString()}` : "";
6801
+ return apiRequest(this.options, "GET", `${WORLDS}/${encodeURIComponent(slug)}/edits${suffix}`);
5699
6802
  }
5700
- status(sandboxId) {
5701
- return apiRequest(this.options, "GET", `/api/public/benchmark-containers/sandboxes/${sid(sandboxId)}`);
6803
+ /** Seal a session into a version on main (the credential's current one when `sessionId` is omitted). */
6804
+ close(slug, input = {}) {
6805
+ return apiRequest(this.options, "POST", `${WORLDS}/${encodeURIComponent(slug)}/edits/close`, input);
5702
6806
  }
5703
- async read(sandboxId, filePath) {
5704
- const res = await apiRequest(
6807
+ /** Drop the session's private branch without making a version. */
6808
+ discard(slug, input = {}) {
6809
+ return apiRequest(this.options, "POST", `${WORLDS}/${encodeURIComponent(slug)}/edits/discard`, input);
6810
+ }
6811
+ /** Undo a sealed session (source and data) as a new sealed session. */
6812
+ rollback(slug, input) {
6813
+ return apiRequest(this.options, "POST", `${WORLDS}/${encodeURIComponent(slug)}/edits/rollback`, input);
6814
+ }
6815
+ };
6816
+ }
6817
+ });
6818
+
6819
+ // src/worlds/dryRun.ts
6820
+ var DRY_RUN_KIND, DRY_RUN_AGENT, STATUS_WAIT_CAP_SECONDS, cid, HostedDryRunClient, DryRunOutcome;
6821
+ var init_dryRun = __esm({
6822
+ "src/worlds/dryRun.ts"() {
6823
+ "use strict";
6824
+ init_worlds();
6825
+ DRY_RUN_KIND = "dry-run";
6826
+ DRY_RUN_AGENT = "oracle";
6827
+ STATUS_WAIT_CAP_SECONDS = 50;
6828
+ cid = (id) => `/api/public/environments/${encodeURIComponent(id)}`;
6829
+ HostedDryRunClient = class {
6830
+ constructor(options = {}) {
6831
+ this.options = options;
6832
+ }
6833
+ options;
6834
+ /** Dispatch ONE oracle job for `task` on `containerId` (a container id, not a slug); pins `versionId` when given. */
6835
+ dispatch(target) {
6836
+ return apiRequest(
5705
6837
  this.options,
5706
- "GET",
5707
- `/api/public/benchmark-containers/sandboxes/${sid(sandboxId)}/file?path=${encodeURIComponent(filePath)}`
6838
+ "POST",
6839
+ `${cid(target.containerId)}/dry-run`,
6840
+ {
6841
+ task: target.task,
6842
+ ...target.versionId ? { versionId: target.versionId } : {}
6843
+ }
5708
6844
  );
5709
- return { path: res.path, size: res.size, bytes: Buffer.from(res.contentBase64, "base64") };
5710
- }
5711
- write(sandboxId, filePath, bytes) {
5712
- return apiRequest(this.options, "PUT", `/api/public/benchmark-containers/sandboxes/${sid(sandboxId)}/file`, {
5713
- path: filePath,
5714
- contentBase64: bytes.toString("base64")
5715
- });
5716
6845
  }
5717
- exec(sandboxId, input) {
5718
- return apiRequest(this.options, "POST", `/api/public/benchmark-containers/sandboxes/${sid(sandboxId)}/exec`, input);
6846
+ /** One status read, blocking server-side for up to `waitSeconds` (capped). */
6847
+ status(runId, waitSeconds = 0) {
6848
+ const wait = Math.max(
6849
+ 0,
6850
+ Math.min(Math.floor(waitSeconds), STATUS_WAIT_CAP_SECONDS)
6851
+ );
6852
+ const suffix = wait ? `?waitSeconds=${wait}` : "";
6853
+ return apiRequest(
6854
+ this.options,
6855
+ "GET",
6856
+ `/api/public/environments/runs/${encodeURIComponent(runId)}${suffix}`
6857
+ );
5719
6858
  }
5720
- check(sandboxId) {
5721
- return apiRequest(this.options, "POST", `/api/public/benchmark-containers/sandboxes/${sid(sandboxId)}/check`, {});
6859
+ /** Poll until the run settles or `timeoutSeconds` pass; the last verdict either way. */
6860
+ async settle(runId, opts) {
6861
+ const now = opts.now ?? Date.now;
6862
+ const sleep3 = opts.sleep ?? ((ms) => new Promise((resolve11) => setTimeout(resolve11, ms)));
6863
+ const deadline = now() + opts.timeoutSeconds * 1e3;
6864
+ for (; ; ) {
6865
+ const budget = Math.floor(
6866
+ Math.min(45, Math.max(0, (deadline - now()) / 1e3))
6867
+ );
6868
+ const asked = now();
6869
+ const verdict = await this.status(runId, budget);
6870
+ if (verdict.settled || now() >= deadline) return verdict;
6871
+ opts.onProgress?.(verdict);
6872
+ if (now() - asked < 1e3) await sleep3(1e3);
6873
+ }
5722
6874
  }
5723
- commit(sandboxId, input) {
5724
- return apiRequest(this.options, "POST", `/api/public/benchmark-containers/sandboxes/${sid(sandboxId)}/commit`, input);
6875
+ };
6876
+ DryRunOutcome = class {
6877
+ constructor(verdict) {
6878
+ this.verdict = verdict;
6879
+ }
6880
+ verdict;
6881
+ get settlement() {
6882
+ return this.verdict.dryRun?.settlement ?? null;
6883
+ }
6884
+ /** Why the dry run did not pass, or null when it did. */
6885
+ reason() {
6886
+ if (!this.verdict.settled) return `still running after the wait`;
6887
+ const settlement = this.settlement;
6888
+ if (!settlement)
6889
+ return `the runner filed no settlement (${this.verdict.status})`;
6890
+ const lastErrorLine = settlement.errorTail?.trim().split("\n").at(-1) || null;
6891
+ if (settlement.exitCode !== null && settlement.exitCode !== 0)
6892
+ return `the runner failed (exit ${settlement.exitCode}): ${lastErrorLine ?? "harbor exited non-zero"}`;
6893
+ if (settlement.reward === null && lastErrorLine)
6894
+ return `the runner failed (exit ?): ${lastErrorLine}`;
6895
+ if (settlement.reward === null)
6896
+ return "ungraded: the grader ran but wrote no reward";
6897
+ if (settlement.reward !== 1)
6898
+ return `the reference solution scored ${settlement.reward}, not 1.0`;
6899
+ return null;
5725
6900
  }
5726
- close(sandboxId) {
5727
- return apiRequest(this.options, "DELETE", `/api/public/benchmark-containers/sandboxes/${sid(sandboxId)}`);
6901
+ passed() {
6902
+ return this.reason() === null;
5728
6903
  }
5729
6904
  };
5730
6905
  }
@@ -5733,23 +6908,53 @@ var init_sandbox = __esm({
5733
6908
  // src/worlds/index.ts
5734
6909
  var worlds_exports = {};
5735
6910
  __export(worlds_exports, {
5736
- ApiError: () => ApiError2,
6911
+ ApiError: () => ApiError,
6912
+ BROWSER_GONE_PATTERNS: () => BROWSER_GONE_PATTERNS,
6913
+ BROWSER_TIERS: () => BROWSER_TIERS,
5737
6914
  BrowserActionRecorder: () => BrowserActionRecorder,
6915
+ BrowserReconnected: () => BrowserReconnected,
6916
+ BrowserReconnector: () => BrowserReconnector,
6917
+ BrowserUnrecoverable: () => BrowserUnrecoverable,
6918
+ CALL_BODY_LIMIT_BYTES: () => CALL_BODY_LIMIT_BYTES,
6919
+ CALL_BODY_LIMIT_LABEL: () => CALL_BODY_LIMIT_LABEL,
5738
6920
  COMPUTER_USE_SPECS: () => COMPUTER_USE_SPECS,
6921
+ CheckoutProvenance: () => CheckoutProvenance,
5739
6922
  DEFAULT_BRANCH: () => DEFAULT_BRANCH,
5740
6923
  DEFAULT_VIEWPORT: () => DEFAULT_VIEWPORT,
6924
+ DRY_RUN_AGENT: () => DRY_RUN_AGENT,
6925
+ DRY_RUN_KIND: () => DRY_RUN_KIND,
6926
+ DetachedPushError: () => DetachedPushError,
6927
+ DryRunOutcome: () => DryRunOutcome,
5741
6928
  EVENT_BATCH_SIZE: () => EVENT_BATCH_SIZE,
5742
6929
  EVENT_FLUSH_INTERVAL_MS: () => EVENT_FLUSH_INTERVAL_MS,
5743
6930
  EVENT_MAX_RETRIES: () => EVENT_MAX_RETRIES,
6931
+ EXPLORATORY_TASK: () => EXPLORATORY_TASK,
6932
+ EXPLORATORY_TASK_SOURCE: () => EXPLORATORY_TASK_SOURCE,
5744
6933
  GatewayEvalsClient: () => GatewayEvalsClient,
6934
+ HostedDryRunClient: () => HostedDryRunClient,
6935
+ IDLE_WARNING_MINUTES: () => IDLE_WARNING_MINUTES,
6936
+ NO_GRADER_REASON: () => NO_GRADER_REASON,
6937
+ PLATFORM_TIMEOUT_DEFAULT_MS: () => PLATFORM_TIMEOUT_DEFAULT_MS,
6938
+ PLATFORM_TIMEOUT_ENV: () => PLATFORM_TIMEOUT_ENV,
6939
+ PlatformTransport: () => PlatformTransport,
5745
6940
  PushSlugConflict: () => PushSlugConflict,
6941
+ RECOVER_BUDGET_MS: () => RECOVER_BUDGET_MS,
6942
+ SANDBOX_REQUEST_TIMEOUT_MS: () => SANDBOX_REQUEST_TIMEOUT_MS,
6943
+ SESSION_STATES: () => SESSION_STATES,
6944
+ STATUS_WAIT_CAP_SECONDS: () => STATUS_WAIT_CAP_SECONDS,
5746
6945
  STRIP_PREFIX: () => STRIP_PREFIX,
5747
6946
  SURFACE_KINDS: () => SURFACE_KINDS,
6947
+ SecretScrubber: () => SecretScrubber,
5748
6948
  TRANSFORMS: () => TRANSFORMS,
5749
6949
  TaskRun: () => TaskRun,
5750
6950
  TaskSessions: () => TaskSessions,
6951
+ TransportCause: () => TransportCause,
6952
+ UnreachableError: () => UnreachableError,
6953
+ VERIFIER_REWARD_PREFIX: () => VERIFIER_REWARD_PREFIX,
5751
6954
  WHITESPACE: () => WHITESPACE,
5752
6955
  WorldBrowser: () => WorldBrowser,
6956
+ WorldCallTooLarge: () => WorldCallTooLarge,
6957
+ WorldEditClient: () => WorldEditClient,
5753
6958
  WorldSandboxClient: () => WorldSandboxClient,
5754
6959
  WorldSession: () => WorldSession,
5755
6960
  WorldSessionCallError: () => WorldSessionCallError,
@@ -5761,12 +6966,16 @@ __export(worlds_exports, {
5761
6966
  apiRequest: () => apiRequest,
5762
6967
  applyTransforms: () => applyTransforms,
5763
6968
  archiveMode: () => archiveMode,
6969
+ assertBrowserTier: () => assertBrowserTier,
6970
+ assertTaskRef: () => assertTaskRef,
5764
6971
  attachManifest: () => attachManifest,
5765
6972
  attachSession: () => attachSession,
5766
6973
  attachTask: () => attachTask,
5767
6974
  buildFileManifest: () => buildFileManifest,
5768
6975
  buildSourceTarball: () => buildSourceTarball,
5769
6976
  captureToolCalls: () => captureToolCalls,
6977
+ checkoutIdentity: () => checkoutIdentity,
6978
+ closeConnection: () => closeConnection,
5770
6979
  collectArchiveRelPaths: () => collectArchiveRelPaths,
5771
6980
  computeContentHash: () => computeContentHash,
5772
6981
  computerUseToolkit: () => computerUseToolkit,
@@ -5780,13 +6989,18 @@ __export(worlds_exports, {
5780
6989
  getRun: () => getRun,
5781
6990
  getTask: () => getTask,
5782
6991
  hashForm: () => hashForm,
6992
+ idleWarning: () => idleWarning,
5783
6993
  ingest: () => ingest,
5784
6994
  ingestToolCalls: () => ingestToolCalls,
6995
+ isBrowserGone: () => isBrowserGone,
6996
+ isSandboxImportPending: () => isSandboxImportPending,
5785
6997
  isTaskIdRef: () => isTaskIdRef,
5786
6998
  isTaskManifest: () => isTaskManifest,
5787
6999
  isTaskSpec: () => isTaskSpec,
5788
7000
  listEnvSecretKeys: () => listEnvSecretKeys,
5789
7001
  listRunConfigs: () => listRunConfigs,
7002
+ listRuns: () => listRuns,
7003
+ listSessions: () => listSessions,
5790
7004
  listTaskSessions: () => listTaskSessions,
5791
7005
  listTasks: () => listTasks,
5792
7006
  localTreeState: () => localTreeState,
@@ -5798,28 +7012,35 @@ __export(worlds_exports, {
5798
7012
  openTask: () => openTask,
5799
7013
  openWorld: () => openWorld,
5800
7014
  openWorldVersion: () => openWorldVersion,
7015
+ parseErrorBody: () => parseErrorBody,
5801
7016
  parseSlugRef: () => parseSlugRef,
5802
7017
  parseToolCallRecord: () => parseToolCallRecord,
5803
7018
  parseTransform: () => parseTransform,
5804
7019
  parseWorldTaskRefs: () => parseWorldTaskRefs,
7020
+ platformTimeoutMs: () => platformTimeoutMs,
5805
7021
  preserveForm: () => preserveForm,
5806
7022
  propose: () => propose,
5807
7023
  pull: () => pull,
5808
7024
  push: () => push,
7025
+ pushBranch: () => pushBranch,
5809
7026
  pushSlug: () => pushSlug,
5810
7027
  pyText: () => pyText,
5811
7028
  queryRows: () => queryRows,
5812
7029
  queryRowsSearch: () => queryRowsSearch,
5813
7030
  readLocalMeta: () => readLocalMeta,
5814
7031
  readToolCallRecords: () => readToolCallRecords,
7032
+ rebaseConflicts: () => rebaseConflicts,
5815
7033
  redactActionArgs: () => redactActionArgs,
5816
7034
  redactionOf: () => redactionOf,
7035
+ releaseConnection: () => releaseConnection,
5817
7036
  resolveBrowserMode: () => resolveBrowserMode,
5818
7037
  resolvePushSlug: () => resolvePushSlug,
5819
7038
  roundForm: () => roundForm,
5820
7039
  runSessions: () => runSessions,
7040
+ runSet: () => runSet,
5821
7041
  runTask: () => runTask,
5822
7042
  schemaFromSignature: () => schemaFromSignature,
7043
+ serializeCallBody: () => serializeCallBody,
5823
7044
  sessionToolObservations: () => sessionToolObservations,
5824
7045
  setEnvSecret: () => setEnvSecret,
5825
7046
  shapeText: () => shapeText,
@@ -5831,6 +7052,7 @@ __export(worlds_exports, {
5831
7052
  toolCallsFromObservations: () => toolCallsFromObservations,
5832
7053
  uiEntryUrl: () => uiEntryUrl,
5833
7054
  uiUrl: () => uiUrl,
7055
+ uncommittedPaths: () => uncommittedPaths,
5834
7056
  updateTask: () => updateTask,
5835
7057
  upsertRunConfig: () => upsertRunConfig,
5836
7058
  validateTask: () => validateTask,
@@ -5850,19 +7072,29 @@ function resolveEnv(options) {
5850
7072
  }
5851
7073
  return { host: host.replace(/\/+$/, ""), publicKey, secretKey };
5852
7074
  }
5853
- async function apiRequest(options, method, path14, body) {
5854
- const { host, publicKey, secretKey } = resolveEnv(options);
5855
- const res = await fetch(`${host}${path14}`, {
5856
- method,
5857
- headers: {
5858
- "content-type": "application/json",
5859
- authorization: "Basic " + Buffer.from(`${publicKey}:${secretKey}`).toString("base64")
5860
- },
5861
- ...body === void 0 ? {} : { body: JSON.stringify(body) }
5862
- });
5863
- const text2 = await res.text();
5864
- if (!res.ok) throw new ApiError2(res.status, method, path14, text2.slice(0, 400));
5865
- return JSON.parse(text2);
7075
+ function parseErrorBody(text2, limit = 600) {
7076
+ const raw = { detail: text2.slice(0, limit), code: null };
7077
+ let parsed;
7078
+ try {
7079
+ parsed = JSON.parse(text2);
7080
+ } catch {
7081
+ return raw;
7082
+ }
7083
+ if (parsed === null || typeof parsed !== "object") return raw;
7084
+ const { message, code } = parsed;
7085
+ const stableCode = typeof code === "string" ? code : null;
7086
+ if (typeof message !== "string") return { ...raw, code: stableCode };
7087
+ if (stableCode === null)
7088
+ return { detail: message.slice(0, limit), code: null };
7089
+ return {
7090
+ detail: `${message} (${stableCode})`.slice(0, limit),
7091
+ code: stableCode
7092
+ };
7093
+ }
7094
+ async function apiRequest(options, method, path16, body, init3 = {}) {
7095
+ const reply = await new PlatformTransport(resolveEnv(options)).send(method, path16, body, init3);
7096
+ if (!reply.ok) throw new ApiError(reply.status, method, path16, reply.text);
7097
+ return JSON.parse(reply.text);
5866
7098
  }
5867
7099
  async function setEnvSecret(slug, key2, value, options = {}) {
5868
7100
  return apiRequest(
@@ -5932,6 +7164,19 @@ async function getRun(runId, options = {}) {
5932
7164
  `/api/public/benchmark-containers/runs/${encodeURIComponent(runId)}`
5933
7165
  );
5934
7166
  }
7167
+ async function listRuns(filter = {}, options = {}) {
7168
+ const params = new URLSearchParams();
7169
+ if (filter.slug) params.set("slug", filter.slug);
7170
+ if (filter.status) params.set("status", filter.status);
7171
+ if (filter.limit !== void 0) params.set("limit", String(filter.limit));
7172
+ const qs3 = params.toString();
7173
+ const res = await apiRequest(
7174
+ options,
7175
+ "GET",
7176
+ `/api/public/benchmark-containers/runs${qs3 ? `?${qs3}` : ""}`
7177
+ );
7178
+ return res.runs;
7179
+ }
5935
7180
  async function waitForRun(runId, opts = {}) {
5936
7181
  const deadline = Date.now() + (opts.timeoutMinutes ?? 45) * 6e4;
5937
7182
  for (; ; ) {
@@ -5943,7 +7188,7 @@ async function waitForRun(runId, opts = {}) {
5943
7188
  );
5944
7189
  opts.onTick?.(run);
5945
7190
  await new Promise(
5946
- (resolve10) => setTimeout(resolve10, (opts.intervalSeconds ?? 20) * 1e3)
7191
+ (resolve11) => setTimeout(resolve11, (opts.intervalSeconds ?? 20) * 1e3)
5947
7192
  );
5948
7193
  }
5949
7194
  }
@@ -5966,8 +7211,8 @@ function detectProvenance() {
5966
7211
  }
5967
7212
  if (!out.branch || !out.commit) {
5968
7213
  try {
5969
- const { execFileSync } = require("child_process");
5970
- const git = (args) => execFileSync("git", args, {
7214
+ const { execFileSync: execFileSync2 } = require("child_process");
7215
+ const git = (args) => execFileSync2("git", args, {
5971
7216
  encoding: "utf-8",
5972
7217
  stdio: ["ignore", "pipe", "ignore"]
5973
7218
  }).toString().trim();
@@ -6025,16 +7270,24 @@ async function resolveWorld(slugRef, slug, ref, pin, options) {
6025
7270
  }
6026
7271
  return world;
6027
7272
  }
6028
- var ApiError2, WorldTask, WorldSet;
7273
+ var ApiError, WorldTask, WorldSet;
6029
7274
  var init_worlds = __esm({
6030
7275
  "src/worlds/index.ts"() {
6031
7276
  "use strict";
7277
+ init_transport();
7278
+ init_transport();
6032
7279
  init_session();
7280
+ init_sessionList();
7281
+ init_sessionContract();
7282
+ init_taskRef();
6033
7283
  init_tasks();
6034
7284
  init_taskSessions();
6035
7285
  init_taskRun();
7286
+ init_setRun();
7287
+ init_checkoutProvenance();
6036
7288
  init_evals();
6037
7289
  init_browser();
7290
+ init_browserReconnect();
6038
7291
  init_hub();
6039
7292
  init_validate();
6040
7293
  init_describe();
@@ -6044,12 +7297,20 @@ var init_worlds = __esm({
6044
7297
  init_migrate();
6045
7298
  init_ingest();
6046
7299
  init_sandbox();
6047
- ApiError2 = class extends Error {
6048
- constructor(status, method, path14, body) {
6049
- super(`${method} ${path14} -> ${status}: ${body}`);
7300
+ init_editSessions();
7301
+ init_dryRun();
7302
+ ApiError = class extends Error {
7303
+ constructor(status, method, path16, text2) {
7304
+ const parsed = parseErrorBody(text2);
7305
+ super(`${method} ${path16} -> ${status}: ${parsed.detail}`);
6050
7306
  this.status = status;
7307
+ this.text = text2;
6051
7308
  this.name = "ApiError";
7309
+ this.code = parsed.code;
6052
7310
  }
7311
+ status;
7312
+ text;
7313
+ code;
6053
7314
  };
6054
7315
  WorldTask = class {
6055
7316
  constructor(world, name, variant) {
@@ -6057,6 +7318,9 @@ var init_worlds = __esm({
6057
7318
  this.name = name;
6058
7319
  this.variant = variant;
6059
7320
  }
7321
+ world;
7322
+ name;
7323
+ variant;
6060
7324
  };
6061
7325
  WorldSet = class {
6062
7326
  constructor(slugRef, slug, ref, version, tasks, options) {
@@ -6067,6 +7331,12 @@ var init_worlds = __esm({
6067
7331
  this.tasks = tasks;
6068
7332
  this.options = options;
6069
7333
  }
7334
+ slugRef;
7335
+ slug;
7336
+ ref;
7337
+ version;
7338
+ tasks;
7339
+ options;
6070
7340
  task(variant) {
6071
7341
  const hit = this.tasks.find(
6072
7342
  (t) => t.variant === variant || t.name.includes(variant)
@@ -6090,6 +7360,7 @@ var init_worlds = __esm({
6090
7360
  versionId: this.version.versionId,
6091
7361
  reuseWarm: opts.reuseWarm,
6092
7362
  surfaces: opts.surfaces,
7363
+ browserTier: opts.browserTier,
6093
7364
  options: this.options
6094
7365
  });
6095
7366
  }
@@ -6120,13 +7391,25 @@ var init_worlds = __esm({
6120
7391
  var src_exports = {};
6121
7392
  __export(src_exports, {
6122
7393
  AGENT_ID_KEY: () => AGENT_ID_KEY,
6123
- ApiError: () => ApiError2,
7394
+ ApiError: () => ApiError,
7395
+ BROWSER_GONE_PATTERNS: () => BROWSER_GONE_PATTERNS,
7396
+ BROWSER_TIERS: () => BROWSER_TIERS,
6124
7397
  BrowserActionRecorder: () => BrowserActionRecorder,
7398
+ BrowserReconnected: () => BrowserReconnected,
7399
+ BrowserReconnector: () => BrowserReconnector,
7400
+ BrowserUnrecoverable: () => BrowserUnrecoverable,
7401
+ CALL_BODY_LIMIT_BYTES: () => CALL_BODY_LIMIT_BYTES,
7402
+ CALL_BODY_LIMIT_LABEL: () => CALL_BODY_LIMIT_LABEL,
6125
7403
  COMPUTER_USE_SPECS: () => COMPUTER_USE_SPECS,
7404
+ CheckoutProvenance: () => CheckoutProvenance,
6126
7405
  DEFAULT_BRANCH: () => DEFAULT_BRANCH,
6127
7406
  DEFAULT_TIMEOUT_SECONDS: () => DEFAULT_TIMEOUT_SECONDS,
6128
7407
  DEFAULT_VIEWPORT: () => DEFAULT_VIEWPORT,
7408
+ DRY_RUN_AGENT: () => DRY_RUN_AGENT,
7409
+ DRY_RUN_KIND: () => DRY_RUN_KIND,
7410
+ DetachedPushError: () => DetachedPushError,
6129
7411
  DriftError: () => DriftError,
7412
+ DryRunOutcome: () => DryRunOutcome,
6130
7413
  ENV_GATEWAY_HOST: () => ENV_GATEWAY_HOST,
6131
7414
  ENV_GATEWAY_PUBLIC_KEY: () => ENV_GATEWAY_PUBLIC_KEY,
6132
7415
  ENV_GATEWAY_SECRET_KEY: () => ENV_GATEWAY_SECRET_KEY,
@@ -6134,6 +7417,8 @@ __export(src_exports, {
6134
7417
  EVENT_FLUSH_INTERVAL_MS: () => EVENT_FLUSH_INTERVAL_MS,
6135
7418
  EVENT_MAX_RETRIES: () => EVENT_MAX_RETRIES,
6136
7419
  EXPERIMENT_ATTRIBUTES: () => EXPERIMENT_ATTRIBUTES,
7420
+ EXPLORATORY_TASK: () => EXPLORATORY_TASK,
7421
+ EXPLORATORY_TASK_SOURCE: () => EXPLORATORY_TASK_SOURCE,
6137
7422
  ExperimentClient: () => ExperimentClient,
6138
7423
  ExperimentSpanProcessor: () => ExperimentSpanProcessor,
6139
7424
  ExposureLogger: () => ExposureLogger,
@@ -6148,10 +7433,17 @@ __export(src_exports, {
6148
7433
  GatewaySecurityError: () => GatewaySecurityError,
6149
7434
  GatewayToolApprovalRequiredError: () => GatewayToolApprovalRequiredError,
6150
7435
  GatewayToolBlockedError: () => GatewayToolBlockedError,
7436
+ HostedDryRunClient: () => HostedDryRunClient,
7437
+ IDLE_WARNING_MINUTES: () => IDLE_WARNING_MINUTES,
7438
+ NO_GRADER_REASON: () => NO_GRADER_REASON,
7439
+ PLATFORM_TIMEOUT_DEFAULT_MS: () => PLATFORM_TIMEOUT_DEFAULT_MS,
7440
+ PLATFORM_TIMEOUT_ENV: () => PLATFORM_TIMEOUT_ENV,
6151
7441
  Persona: () => Persona,
6152
7442
  PersonaError: () => PersonaError,
6153
7443
  PersonasClient: () => PersonasClient,
7444
+ PlatformTransport: () => PlatformTransport,
6154
7445
  PushSlugConflict: () => PushSlugConflict,
7446
+ RECOVER_BUDGET_MS: () => RECOVER_BUDGET_MS,
6155
7447
  REPLAY_ENVIRONMENT: () => REPLAY_ENVIRONMENT,
6156
7448
  ReplayCase: () => ReplayCase,
6157
7449
  ReplayCheck: () => ReplayCheck,
@@ -6159,12 +7451,16 @@ __export(src_exports, {
6159
7451
  ReplayReport: () => ReplayReport,
6160
7452
  ReplaySuite: () => ReplaySuite,
6161
7453
  ReplayTask: () => ReplayTask,
7454
+ SANDBOX_REQUEST_TIMEOUT_MS: () => SANDBOX_REQUEST_TIMEOUT_MS,
7455
+ SESSION_STATES: () => SESSION_STATES,
7456
+ STATUS_WAIT_CAP_SECONDS: () => STATUS_WAIT_CAP_SECONDS,
6162
7457
  STRIP_PREFIX: () => STRIP_PREFIX,
6163
7458
  SUCCESS_METRIC_NAME_KEY: () => SUCCESS_METRIC_NAME_KEY,
6164
7459
  SUCCESS_SIGNAL_KEY: () => SUCCESS_SIGNAL_KEY,
6165
7460
  SURFACE_KINDS: () => SURFACE_KINDS,
6166
7461
  ScoreError: () => ScoreError,
6167
7462
  ScoresClient: () => ScoresClient,
7463
+ SecretScrubber: () => SecretScrubber,
6168
7464
  SessionLoadError: () => SessionLoadError,
6169
7465
  SessionRecording: () => SessionRecording,
6170
7466
  SessionTrace: () => SessionTrace,
@@ -6174,10 +7470,15 @@ __export(src_exports, {
6174
7470
  TaskSessions: () => TaskSessions,
6175
7471
  ToolStubRegistry: () => ToolStubRegistry,
6176
7472
  TraceDiff: () => TraceDiff,
7473
+ TransportCause: () => TransportCause,
7474
+ UnreachableError: () => UnreachableError,
6177
7475
  UserProfileError: () => UserProfileError,
6178
7476
  UsersClient: () => UsersClient,
7477
+ VERIFIER_REWARD_PREFIX: () => VERIFIER_REWARD_PREFIX,
6179
7478
  WHITESPACE: () => WHITESPACE,
6180
7479
  WorldBrowser: () => WorldBrowser,
7480
+ WorldCallTooLarge: () => WorldCallTooLarge,
7481
+ WorldEditClient: () => WorldEditClient,
6181
7482
  WorldSandboxClient: () => WorldSandboxClient,
6182
7483
  WorldSession: () => WorldSession,
6183
7484
  WorldSessionCallError: () => WorldSessionCallError,
@@ -6191,6 +7492,8 @@ __export(src_exports, {
6191
7492
  applyTransforms: () => applyTransforms,
6192
7493
  archiveMode: () => archiveMode,
6193
7494
  assembleManifest: () => assembleManifest,
7495
+ assertBrowserTier: () => assertBrowserTier,
7496
+ assertTaskRef: () => assertTaskRef,
6194
7497
  assignVariant: () => assignVariant,
6195
7498
  attachManifest: () => attachManifest,
6196
7499
  attachSession: () => attachSession,
@@ -6200,7 +7503,9 @@ __export(src_exports, {
6200
7503
  buildSourceTarball: () => buildSourceTarball,
6201
7504
  canonicalJson: () => canonicalJson,
6202
7505
  captureToolCalls: () => captureToolCalls,
7506
+ checkoutIdentity: () => checkoutIdentity,
6203
7507
  clearExperimentContext: () => clearExperimentContext,
7508
+ closeConnection: () => closeConnection,
6204
7509
  collectArchiveRelPaths: () => collectArchiveRelPaths,
6205
7510
  computeBuildHash: () => computeBuildHash,
6206
7511
  computeContentHash: () => computeContentHash,
@@ -6230,13 +7535,18 @@ __export(src_exports, {
6230
7535
  hashForm: () => hashForm,
6231
7536
  hooks: () => hooks_exports,
6232
7537
  identify: () => identify,
7538
+ idleWarning: () => idleWarning,
6233
7539
  ingest: () => ingest,
6234
7540
  ingestToolCalls: () => ingestToolCalls,
7541
+ isBrowserGone: () => isBrowserGone,
7542
+ isSandboxImportPending: () => isSandboxImportPending,
6235
7543
  isTaskIdRef: () => isTaskIdRef,
6236
7544
  isTaskManifest: () => isTaskManifest,
6237
7545
  isTaskSpec: () => isTaskSpec,
6238
7546
  listEnvSecretKeys: () => listEnvSecretKeys,
6239
7547
  listRunConfigs: () => listRunConfigs,
7548
+ listRuns: () => listRuns,
7549
+ listSessions: () => listSessions,
6240
7550
  listTaskSessions: () => listTaskSessions,
6241
7551
  listTasks: () => listTasks,
6242
7552
  loadSession: () => loadSession,
@@ -6250,26 +7560,31 @@ __export(src_exports, {
6250
7560
  openTask: () => openTask,
6251
7561
  openWorld: () => openWorld,
6252
7562
  openWorldVersion: () => openWorldVersion,
7563
+ parseErrorBody: () => parseErrorBody,
6253
7564
  parseSlugRef: () => parseSlugRef,
6254
7565
  parseToolCallRecord: () => parseToolCallRecord,
6255
7566
  parseTransform: () => parseTransform,
6256
7567
  parseWorldTaskRefs: () => parseWorldTaskRefs,
6257
7568
  personas: () => personas,
7569
+ platformTimeoutMs: () => platformTimeoutMs,
6258
7570
  preserveForm: () => preserveForm,
6259
7571
  propose: () => propose,
6260
7572
  pull: () => pull,
6261
7573
  push: () => push,
7574
+ pushBranch: () => pushBranch,
6262
7575
  pushSlug: () => pushSlug,
6263
7576
  pyText: () => pyText,
6264
7577
  queryRows: () => queryRows,
6265
7578
  queryRowsSearch: () => queryRowsSearch,
6266
7579
  readLocalMeta: () => readLocalMeta,
6267
7580
  readToolCallRecords: () => readToolCallRecords,
7581
+ rebaseConflicts: () => rebaseConflicts,
6268
7582
  redactActionArgs: () => redactActionArgs,
6269
7583
  redactionOf: () => redactionOf,
6270
7584
  registerArtifact: () => registerArtifact,
6271
7585
  registerPrompt: () => registerPrompt,
6272
7586
  registerSkill: () => registerSkill,
7587
+ releaseConnection: () => releaseConnection,
6273
7588
  renderAgentSystem: () => renderAgentSystem,
6274
7589
  replay: () => replay,
6275
7590
  resetBuildRegistry: () => resetBuildRegistry,
@@ -6278,11 +7593,13 @@ __export(src_exports, {
6278
7593
  resolveUserId: () => resolveUserId,
6279
7594
  roundForm: () => roundForm,
6280
7595
  runSessions: () => runSessions,
7596
+ runSet: () => runSet,
6281
7597
  runSuite: () => runSuite,
6282
7598
  runTask: () => runTask,
6283
7599
  runWithExperimentContext: () => runWithExperimentContext,
6284
7600
  schemaFromSignature: () => schemaFromSignature,
6285
7601
  scores: () => scores,
7602
+ serializeCallBody: () => serializeCallBody,
6286
7603
  sessionObservationFromApi: () => sessionObservationFromApi,
6287
7604
  sessionToolObservations: () => sessionToolObservations,
6288
7605
  sessions: () => sessions,
@@ -6301,6 +7618,7 @@ __export(src_exports, {
6301
7618
  tracing: () => tracing,
6302
7619
  uiEntryUrl: () => uiEntryUrl,
6303
7620
  uiUrl: () => uiUrl,
7621
+ uncommittedPaths: () => uncommittedPaths,
6304
7622
  updateTask: () => updateTask,
6305
7623
  upsertRunConfig: () => upsertRunConfig,
6306
7624
  users: () => users,
@@ -6882,8 +8200,8 @@ var GatewayContext = class _GatewayContext {
6882
8200
  }
6883
8201
  return resolved;
6884
8202
  }
6885
- async requestJson(method, path14, payload) {
6886
- const response = await fetch(`${this.host}${path14}`, {
8203
+ async requestJson(method, path16, payload) {
8204
+ const response = await fetch(`${this.host}${path16}`, {
6887
8205
  method,
6888
8206
  headers: {
6889
8207
  Authorization: this.authHeader(),
@@ -6894,7 +8212,7 @@ var GatewayContext = class _GatewayContext {
6894
8212
  const text2 = await response.text();
6895
8213
  const body = text2 ? safeJson(text2) : {};
6896
8214
  if (!response.ok) {
6897
- const message = typeof body.message === "string" ? body.message : `Gateway API ${response.status} on ${path14}`;
8215
+ const message = typeof body.message === "string" ? body.message : `Gateway API ${response.status} on ${path16}`;
6898
8216
  if (response.status === 409) {
6899
8217
  throw new GatewayContextConflictError(
6900
8218
  message,
@@ -6903,7 +8221,7 @@ var GatewayContext = class _GatewayContext {
6903
8221
  }
6904
8222
  throw new GatewayContextError(message);
6905
8223
  }
6906
- this.log("%s %s -> %s", method, path14, response.status);
8224
+ this.log("%s %s -> %s", method, path16, response.status);
6907
8225
  return body;
6908
8226
  }
6909
8227
  authHeader() {
@@ -7010,11 +8328,11 @@ function primaryPathForKind(kind, snapshot) {
7010
8328
  const preferred = kind === "agent" ? "AGENTS.md" : kind === "prompt" ? "PROMPT.md" : kind === "skill" ? "SKILL.md" : "MEMORY.md";
7011
8329
  if (readFile(snapshot, preferred)) return preferred;
7012
8330
  return Object.entries(snapshot.files).find(
7013
- ([path14, entry]) => entry.type === "file" && path14.endsWith(".md")
8331
+ ([path16, entry]) => entry.type === "file" && path16.endsWith(".md")
7014
8332
  )?.[0] ?? null;
7015
8333
  }
7016
- function parseJsonFile(snapshot, path14) {
7017
- const content = readFile(snapshot, path14);
8334
+ function parseJsonFile(snapshot, path16) {
8335
+ const content = readFile(snapshot, path16);
7018
8336
  if (!content) return {};
7019
8337
  try {
7020
8338
  const parsed = JSON.parse(content);
@@ -7023,8 +8341,8 @@ function parseJsonFile(snapshot, path14) {
7023
8341
  return {};
7024
8342
  }
7025
8343
  }
7026
- function readFile(snapshot, path14) {
7027
- const entry = snapshot.files[path14];
8344
+ function readFile(snapshot, path16) {
8345
+ const entry = snapshot.files[path16];
7028
8346
  return entry?.type === "file" ? entry.content : null;
7029
8347
  }
7030
8348
  function provenanceFor(snapshot, label) {
@@ -7126,16 +8444,16 @@ var GatewayMemory = class _GatewayMemory {
7126
8444
  `/api/public/context/memory/${encodeIdentifier2(identifier)}${suffix}`
7127
8445
  );
7128
8446
  }
7129
- async read(target, path14, options = {}) {
8447
+ async read(target, path16, options = {}) {
7130
8448
  const snapshot = typeof target === "string" ? await this.pull(target, options) : target;
7131
- const file = snapshot.files[path14];
8449
+ const file = snapshot.files[path16];
7132
8450
  return file?.type === "file" ? file.content : null;
7133
8451
  }
7134
- async write(target, path14, content, options = {}) {
8452
+ async write(target, path16, content, options = {}) {
7135
8453
  const snapshot = typeof target === "string" ? await this.pull(target) : target;
7136
8454
  return this.push(snapshot.repo.repoHandle, {
7137
8455
  files: {
7138
- [path14]: {
8456
+ [path16]: {
7139
8457
  content,
7140
8458
  ...options.mimeType ? { mimeType: options.mimeType } : {}
7141
8459
  }
@@ -7145,10 +8463,10 @@ var GatewayMemory = class _GatewayMemory {
7145
8463
  ...runtimeContextPayload2(options)
7146
8464
  });
7147
8465
  }
7148
- async delete(target, path14, options = {}) {
8466
+ async delete(target, path16, options = {}) {
7149
8467
  const snapshot = typeof target === "string" ? await this.pull(target) : target;
7150
8468
  return this.push(snapshot.repo.repoHandle, {
7151
- files: { [path14]: null },
8469
+ files: { [path16]: null },
7152
8470
  parentCommit: options.parentCommit ?? snapshot.commit.commitHash,
7153
8471
  message: options.message,
7154
8472
  ...runtimeContextPayload2(options)
@@ -7161,8 +8479,8 @@ var GatewayMemory = class _GatewayMemory {
7161
8479
  payload
7162
8480
  );
7163
8481
  }
7164
- async requestJson(method, path14, payload) {
7165
- const response = await fetch(`${this.host}${path14}`, {
8482
+ async requestJson(method, path16, payload) {
8483
+ const response = await fetch(`${this.host}${path16}`, {
7166
8484
  method,
7167
8485
  headers: {
7168
8486
  Authorization: this.authHeader(),
@@ -7173,7 +8491,7 @@ var GatewayMemory = class _GatewayMemory {
7173
8491
  const text2 = await response.text();
7174
8492
  const body = text2 ? safeJson2(text2) : {};
7175
8493
  if (!response.ok) {
7176
- const message = typeof body.message === "string" ? body.message : `Gateway API ${response.status} on ${path14}`;
8494
+ const message = typeof body.message === "string" ? body.message : `Gateway API ${response.status} on ${path16}`;
7177
8495
  if (response.status === 409) {
7178
8496
  throw new GatewayMemoryConflictError(
7179
8497
  message,
@@ -7182,7 +8500,7 @@ var GatewayMemory = class _GatewayMemory {
7182
8500
  }
7183
8501
  throw new GatewayMemoryError(message);
7184
8502
  }
7185
- this.log("%s %s -> %s", method, path14, response.status);
8503
+ this.log("%s %s -> %s", method, path16, response.status);
7186
8504
  return body;
7187
8505
  }
7188
8506
  authHeader() {
@@ -7344,10 +8662,10 @@ var PersonasClient = class _PersonasClient {
7344
8662
  done: Boolean(payload.done)
7345
8663
  };
7346
8664
  }
7347
- async requestJson(method, path14, payload) {
8665
+ async requestJson(method, path16, payload) {
7348
8666
  let response;
7349
8667
  try {
7350
- response = await fetch(`${this.host}${path14}`, {
8668
+ response = await fetch(`${this.host}${path16}`, {
7351
8669
  method,
7352
8670
  headers: {
7353
8671
  Authorization: this.authHeader(),
@@ -7358,7 +8676,7 @@ var PersonasClient = class _PersonasClient {
7358
8676
  });
7359
8677
  } catch (error) {
7360
8678
  const reason = error instanceof Error ? error.message : String(error);
7361
- throw new PersonaError(`${method} ${path14} failed: ${reason}`, {
8679
+ throw new PersonaError(`${method} ${path16} failed: ${reason}`, {
7362
8680
  cause: error
7363
8681
  });
7364
8682
  }
@@ -7366,10 +8684,10 @@ var PersonasClient = class _PersonasClient {
7366
8684
  if (!response.ok) {
7367
8685
  const detail = text2.slice(0, 500);
7368
8686
  throw new PersonaError(
7369
- `${method} ${path14} failed (${response.status}): ${detail}`
8687
+ `${method} ${path16} failed (${response.status}): ${detail}`
7370
8688
  );
7371
8689
  }
7372
- this.log("%s %s -> %s", method, path14, response.status);
8690
+ this.log("%s %s -> %s", method, path16, response.status);
7373
8691
  return safeJson3(text2);
7374
8692
  }
7375
8693
  authHeader() {
@@ -7594,10 +8912,10 @@ var SessionRecording = class _SessionRecording {
7594
8912
  };
7595
8913
  }
7596
8914
  /** Dump the full session as a JSON fixture (for regression tests). */
7597
- toFixture(path14) {
7598
- (0, import_node_fs.mkdirSync)((0, import_node_path.dirname)(path14), { recursive: true });
7599
- (0, import_node_fs.writeFileSync)(path14, JSON.stringify(this.toJSON(), null, 2), "utf-8");
7600
- return path14;
8915
+ toFixture(path16) {
8916
+ (0, import_node_fs.mkdirSync)((0, import_node_path.dirname)(path16), { recursive: true });
8917
+ (0, import_node_fs.writeFileSync)(path16, JSON.stringify(this.toJSON(), null, 2), "utf-8");
8918
+ return path16;
7601
8919
  }
7602
8920
  static fromApi(raw) {
7603
8921
  return new _SessionRecording({
@@ -8432,7 +9750,7 @@ function randomHex() {
8432
9750
  return crypto.randomUUID().replace(/-/g, "");
8433
9751
  }
8434
9752
  function sleep(ms) {
8435
- return new Promise((resolve10) => setTimeout(resolve10, ms));
9753
+ return new Promise((resolve11) => setTimeout(resolve11, ms));
8436
9754
  }
8437
9755
  var replay = {
8438
9756
  suite,
@@ -8519,7 +9837,7 @@ var GatewaySecurity = class _GatewaySecurity {
8519
9837
  const descriptors = entries.map(
8520
9838
  ([key2, tool]) => this.describeTool(key2, tool, options)
8521
9839
  );
8522
- const resolve10 = await this.resolveToolset({
9840
+ const resolve11 = await this.resolveToolset({
8523
9841
  agent: this.agent,
8524
9842
  toolsetId: options.toolsetId,
8525
9843
  toolsetName: options.toolsetName,
@@ -8529,8 +9847,8 @@ var GatewaySecurity = class _GatewaySecurity {
8529
9847
  });
8530
9848
  const securedEntries = entries.flatMap(([key2, tool]) => {
8531
9849
  const descriptor = descriptors.find((item) => item.name === key2);
8532
- if (!this.shouldExposeTool(resolve10, descriptor.id)) {
8533
- this.log("Hiding tool %s in %s mode", descriptor.id, resolve10.mode);
9850
+ if (!this.shouldExposeTool(resolve11, descriptor.id)) {
9851
+ this.log("Hiding tool %s in %s mode", descriptor.id, resolve11.mode);
8534
9852
  return [];
8535
9853
  }
8536
9854
  return [
@@ -8540,7 +9858,7 @@ var GatewaySecurity = class _GatewaySecurity {
8540
9858
  toolId: descriptor.id,
8541
9859
  toolsetId: options.toolsetId,
8542
9860
  context: this.normalizeContext(options.context),
8543
- resolve: resolve10
9861
+ resolve: resolve11
8544
9862
  })
8545
9863
  ]
8546
9864
  ];
@@ -8628,8 +9946,8 @@ var GatewaySecurity = class _GatewaySecurity {
8628
9946
  );
8629
9947
  }
8630
9948
  }
8631
- async postJson(path14, payload) {
8632
- const response = await fetch(`${this.host}${path14}`, {
9949
+ async postJson(path16, payload) {
9950
+ const response = await fetch(`${this.host}${path16}`, {
8633
9951
  method: "POST",
8634
9952
  headers: {
8635
9953
  Authorization: this.authHeader(),
@@ -8640,7 +9958,7 @@ var GatewaySecurity = class _GatewaySecurity {
8640
9958
  if (!response.ok) {
8641
9959
  const body = await response.text();
8642
9960
  throw new GatewaySecurityError(
8643
- `Gateway API ${response.status} on ${path14}: ${body || response.statusText}`
9961
+ `Gateway API ${response.status} on ${path16}: ${body || response.statusText}`
8644
9962
  );
8645
9963
  }
8646
9964
  return await response.json();
@@ -8655,9 +9973,9 @@ var GatewaySecurity = class _GatewaySecurity {
8655
9973
  metadata: options.toolMetadata?.[key2] ?? {}
8656
9974
  };
8657
9975
  }
8658
- shouldExposeTool(resolve10, toolId) {
8659
- if (resolve10.mode === "observe") return true;
8660
- if (resolve10.blockedToolIds.includes(toolId)) return false;
9976
+ shouldExposeTool(resolve11, toolId) {
9977
+ if (resolve11.mode === "observe") return true;
9978
+ if (resolve11.blockedToolIds.includes(toolId)) return false;
8661
9979
  return true;
8662
9980
  }
8663
9981
  normalizeContext(context4) {
@@ -8716,6 +10034,7 @@ __export(files_exports, {
8716
10034
  deleteFile: () => deleteFile,
8717
10035
  downloadFile: () => downloadFile,
8718
10036
  drivePath: () => drivePath,
10037
+ fetchToDrive: () => fetchToDrive,
8719
10038
  getFile: () => getFile,
8720
10039
  isDriveRef: () => isDriveRef,
8721
10040
  iterateFiles: () => iterateFiles,
@@ -8730,8 +10049,8 @@ __export(files_exports, {
8730
10049
  uploadFile: () => uploadFile
8731
10050
  });
8732
10051
  var import_node_crypto10 = require("crypto");
8733
- var fs11 = __toESM(require("fs"));
8734
- var path10 = __toESM(require("path"));
10052
+ var fs13 = __toESM(require("fs"));
10053
+ var path12 = __toESM(require("path"));
8735
10054
  var import_node_stream = require("stream");
8736
10055
  var import_promises = require("stream/promises");
8737
10056
  init_worlds();
@@ -8772,17 +10091,20 @@ async function openDownload(url) {
8772
10091
  if (!res.ok || !res.body) throw new Error(`download failed: storage answered HTTP ${res.status}`);
8773
10092
  return res;
8774
10093
  }
8775
- async function readFile2(options = {}, filePath) {
10094
+ async function readFile2(options = {}, filePath, limits = {}) {
8776
10095
  const file = await getFile(options, filePath);
10096
+ const size = file.sizeBytes ?? 0;
10097
+ if (limits.maxBytes !== void 0 && size > limits.maxBytes)
10098
+ throw new Error(`${filePath} is ${size} bytes, over the ${limits.maxBytes}-byte limit`);
8777
10099
  const res = await openDownload(file.url);
8778
10100
  return Buffer.from(await res.arrayBuffer());
8779
10101
  }
8780
10102
  async function downloadFile(options = {}, filePath, outPath, onProgress) {
8781
10103
  const file = await getFile(options, filePath);
8782
10104
  const res = await openDownload(file.url);
8783
- fs11.mkdirSync(path10.dirname(path10.resolve(outPath)), { recursive: true });
10105
+ fs13.mkdirSync(path12.dirname(path12.resolve(outPath)), { recursive: true });
8784
10106
  const source = import_node_stream.Readable.fromWeb(res.body);
8785
- await (0, import_promises.pipeline)(source, counting((n) => onProgress?.(n, file.sizeBytes)), fs11.createWriteStream(outPath));
10107
+ await (0, import_promises.pipeline)(source, counting((n) => onProgress?.(n, file.sizeBytes)), fs13.createWriteStream(outPath));
8786
10108
  return { ...file, out: outPath };
8787
10109
  }
8788
10110
  async function requestUpload(options = {}, body) {
@@ -8793,7 +10115,7 @@ async function confirmUpload(options = {}, fileId, ok = true) {
8793
10115
  }
8794
10116
  async function sha256Base64(localPath) {
8795
10117
  const hash = (0, import_node_crypto10.createHash)("sha256");
8796
- for await (const chunk of fs11.createReadStream(localPath)) hash.update(chunk);
10118
+ for await (const chunk of fs13.createReadStream(localPath)) hash.update(chunk);
8797
10119
  return hash.digest("base64");
8798
10120
  }
8799
10121
  var CONTENT_TYPES = {
@@ -8829,7 +10151,7 @@ var CONTENT_TYPES = {
8829
10151
  ".mp4": "video/mp4"
8830
10152
  };
8831
10153
  function contentTypeFor(name) {
8832
- return CONTENT_TYPES[path10.extname(name).toLowerCase()] ?? "application/octet-stream";
10154
+ return CONTENT_TYPES[path12.extname(name).toLowerCase()] ?? "application/octet-stream";
8833
10155
  }
8834
10156
  function counting(report) {
8835
10157
  let seen = 0;
@@ -8856,7 +10178,7 @@ async function putPresigned(uploadUrl, body, headers) {
8856
10178
  if (!res.ok) throw new Error(`upload failed: storage answered HTTP ${res.status}: ${(await res.text()).slice(0, 300)}`);
8857
10179
  }
8858
10180
  async function uploadFile(options = {}, localPath, targetPath, upload = {}) {
8859
- const stat = fs11.statSync(localPath);
10181
+ const stat = fs13.statSync(localPath);
8860
10182
  if (!stat.isFile()) throw new Error(`${localPath} is not a file`);
8861
10183
  if (stat.size === 0) throw new Error(`${localPath} is empty; the drive refuses zero-byte uploads`);
8862
10184
  const contentType = upload.contentType ?? contentTypeFor(localPath);
@@ -8864,7 +10186,7 @@ async function uploadFile(options = {}, localPath, targetPath, upload = {}) {
8864
10186
  const target = drivePath(targetPath);
8865
10187
  const granted = await requestUpload(options, { path: target, contentLength: stat.size, contentType, sha256: sha2562, ...upload.overwrite ? { overwrite: true } : {} });
8866
10188
  try {
8867
- const stream = fs11.createReadStream(localPath).pipe(counting((n) => upload.onProgress?.(n, stat.size)));
10189
+ const stream = fs13.createReadStream(localPath).pipe(counting((n) => upload.onProgress?.(n, stat.size)));
8868
10190
  await putPresigned(granted.uploadUrl, import_node_stream.Readable.toWeb(stream), { contentType, contentLength: stat.size, sha256: sha2562 });
8869
10191
  } catch (error) {
8870
10192
  await confirmUpload(options, granted.fileId, false).catch(() => void 0);
@@ -8894,6 +10216,15 @@ async function deleteFile(options = {}, filePath) {
8894
10216
  async function moveFile(options = {}, fromPath, toPath) {
8895
10217
  return apiRequest(options, "POST", `${BASE}/move`, { fromPath: drivePath(fromPath), toPath: drivePath(toPath) });
8896
10218
  }
10219
+ async function fetchToDrive(options = {}, url, targetPath, fetchOptions = {}) {
10220
+ return apiRequest(options, "POST", `${BASE}/fetch`, {
10221
+ url,
10222
+ path: drivePath(targetPath),
10223
+ ...fetchOptions.headers?.length ? { headers: fetchOptions.headers } : {},
10224
+ ...fetchOptions.contentType ? { contentType: fetchOptions.contentType } : {},
10225
+ ...fetchOptions.overwrite ? { overwrite: true } : {}
10226
+ });
10227
+ }
8897
10228
  async function createFolder(options = {}, folderPath) {
8898
10229
  return apiRequest(options, "POST", `${BASE}/folders`, { path: drivePath(folderPath) });
8899
10230
  }
@@ -8915,7 +10246,7 @@ __export(traces_exports, {
8915
10246
  iterateSessions: () => iterateSessions,
8916
10247
  iterateTraces: () => iterateTraces,
8917
10248
  listObservations: () => listObservations,
8918
- listSessions: () => listSessions,
10249
+ listSessions: () => listSessions2,
8919
10250
  listTraces: () => listTraces
8920
10251
  });
8921
10252
  init_worlds();
@@ -8946,11 +10277,11 @@ async function listObservations(options = {}, filters = {}, page = {}) {
8946
10277
  async function* iterateObservations(options = {}, filters = {}, limits = {}) {
8947
10278
  yield* paged((page) => listObservations(options, filters, { page, limit: PAGE_LIMIT2 }), limits.max);
8948
10279
  }
8949
- async function listSessions(options = {}, filters = {}, page = {}) {
10280
+ async function listSessions2(options = {}, filters = {}, page = {}) {
8950
10281
  return apiRequest(options, "GET", `/api/public/sessions${qs2({ ...filters, page: page.page ?? 1, limit: page.limit ?? 50 })}`);
8951
10282
  }
8952
10283
  async function* iterateSessions(options = {}, filters = {}, limits = {}) {
8953
- yield* paged((page) => listSessions(options, filters, { page, limit: PAGE_LIMIT2 }), limits.max);
10284
+ yield* paged((page) => listSessions2(options, filters, { page, limit: PAGE_LIMIT2 }), limits.max);
8954
10285
  }
8955
10286
  async function getSession(options = {}, sessionId, detail = {}) {
8956
10287
  return apiRequest(options, "GET", `/api/public/sessions/${encodeURIComponent(sessionId)}${qs2({ includeIO: detail.includeIO ? "true" : void 0 })}`);
@@ -9120,8 +10451,45 @@ function swapValue(text2, needle, replacement) {
9120
10451
  );
9121
10452
  }
9122
10453
 
9123
- // src/hooks/alias.ts
10454
+ // src/hooks/standInDigits.ts
9124
10455
  var import_node_crypto11 = require("crypto");
10456
+ function standInDigits(realDigits, identityName) {
10457
+ if (!realDigits) return "";
10458
+ const digest = (0, import_node_crypto11.createHash)("sha256").update(`${identityName}:${realDigits}`).digest("hex");
10459
+ let digits = "";
10460
+ for (let i = 0; i < realDigits.length; i++)
10461
+ digits += String(parseInt(digest[i % digest.length], 16) % 10);
10462
+ if (digits !== realDigits) return digits;
10463
+ return String((Number(digits[0]) + 1) % 10) + digits.slice(1);
10464
+ }
10465
+
10466
+ // src/hooks/declared.ts
10467
+ var DeclaredStandIn = class _DeclaredStandIn {
10468
+ alias;
10469
+ variants;
10470
+ constructor(alias, variants = []) {
10471
+ this.alias = typeof alias === "string" && alias.trim() ? alias.trim() : null;
10472
+ this.variants = Array.isArray(variants) ? variants.filter(
10473
+ (v) => typeof v === "string" && v.trim() !== ""
10474
+ ) : [];
10475
+ }
10476
+ static of(entity) {
10477
+ return new _DeclaredStandIn(entity.alias, entity.variants ?? []);
10478
+ }
10479
+ get declared() {
10480
+ return this.alias !== null || this.variants.length > 0;
10481
+ }
10482
+ /** The pairings for `display`: the real value's forms, then every extra spelling in the
10483
+ * same forms, each mapped onto the stand-in. */
10484
+ pairs(real, display, build) {
10485
+ const out = [...build(real, display)];
10486
+ for (const spelling of this.variants) out.push(...build(spelling, display));
10487
+ return out;
10488
+ }
10489
+ };
10490
+
10491
+ // src/hooks/alias.ts
10492
+ var import_node_crypto12 = require("crypto");
9125
10493
  var GIVEN = [
9126
10494
  "John",
9127
10495
  "Mary",
@@ -9312,7 +10680,7 @@ function findKind(kind, text2) {
9312
10680
  return out;
9313
10681
  }
9314
10682
  function newRunKey() {
9315
- return (0, import_node_crypto11.randomBytes)(32).toString("hex");
10683
+ return (0, import_node_crypto12.randomBytes)(32).toString("hex");
9316
10684
  }
9317
10685
  function canonical(kind, value) {
9318
10686
  const text2 = String(value).normalize("NFKC").trim();
@@ -9369,7 +10737,7 @@ function explodeIp(text2) {
9369
10737
  return groups.map((g) => g.padStart(4, "0")).join(":") + zone;
9370
10738
  }
9371
10739
  function index(runKey, kind, value, salt = "") {
9372
- const digest = (0, import_node_crypto11.createHmac)("sha256", Buffer.from(runKey, "hex")).update(`${kind}:${value}:${salt}`, "utf8").digest();
10740
+ const digest = (0, import_node_crypto12.createHmac)("sha256", Buffer.from(runKey, "hex")).update(`${kind}:${value}:${salt}`, "utf8").digest();
9373
10741
  return digest.readBigUInt64BE(0);
9374
10742
  }
9375
10743
  var pick = (pool, n) => pool[Number(n % BigInt(pool.length))];
@@ -9554,6 +10922,14 @@ function genericPairs(real, fake) {
9554
10922
  }
9555
10923
  return dedupe(out);
9556
10924
  }
10925
+ function pairBuilder(kind) {
10926
+ const builders = {
10927
+ person_name: namePairs,
10928
+ email: emailPairs,
10929
+ phone: phonePairs
10930
+ };
10931
+ return builders[kind] ?? genericPairs;
10932
+ }
9557
10933
  function dedupe(pairs) {
9558
10934
  const seen = /* @__PURE__ */ new Set();
9559
10935
  const out = [];
@@ -9565,7 +10941,12 @@ function dedupe(pairs) {
9565
10941
  }
9566
10942
  return out.sort((a, b) => b[0].length - a[0].length);
9567
10943
  }
10944
+ function isSubject(alias) {
10945
+ return alias.provenance === "seed";
10946
+ }
9568
10947
  var fullName = (identity) => `${identity.given} ${identity.surname}`;
10948
+ var DeclaredOnlyError = class extends Error {
10949
+ };
9569
10950
  var AliasMap = class _AliasMap {
9570
10951
  constructor(runKey, slugs = [], options = {}) {
9571
10952
  this.runKey = runKey;
@@ -9575,7 +10956,14 @@ var AliasMap = class _AliasMap {
9575
10956
  this.publicLayerWins = options.publicLayerWins ?? true;
9576
10957
  this.publicMailboxDomains = options.publicMailboxDomains ?? null;
9577
10958
  this.mintInbound = options.mintInbound ?? [];
10959
+ this.declaredOnly = options.declaredOnly ?? false;
10960
+ if (this.declaredOnly && this.mintInbound.length)
10961
+ throw new DeclaredOnlyError(
10962
+ "declared_only and mint_inbound cannot both be set: nothing is minted on sight"
10963
+ );
9578
10964
  }
10965
+ runKey;
10966
+ slugs;
9579
10967
  aliases = /* @__PURE__ */ new Map();
9580
10968
  identities = /* @__PURE__ */ new Map();
9581
10969
  taken = /* @__PURE__ */ new Set();
@@ -9583,6 +10971,9 @@ var AliasMap = class _AliasMap {
9583
10971
  aliasDigests = /* @__PURE__ */ new Set();
9584
10972
  leaksIn = [];
9585
10973
  leaksOut = [];
10974
+ /** As `leaksIn` / `leaksOut`, for values minted on sight: counted, never a failure. */
10975
+ bystandersIn = [];
10976
+ bystandersOut = [];
9586
10977
  unresolvedOut = [];
9587
10978
  /** Every value minted on sight: `{where, kind, alias}`. */
9588
10979
  found = [];
@@ -9606,6 +10997,20 @@ var AliasMap = class _AliasMap {
9606
10997
  * subject. Off (the default) such a value reaches the agent as it is — the seed
9607
10998
  * list is the whole map. */
9608
10999
  mintInbound;
11000
+ /** Every private seed must carry its own `alias`; a seed without one is refused instead
11001
+ * of getting a generated persona, and nothing is minted on arrival. */
11002
+ declaredOnly;
11003
+ /** `declaredOnly`: refuse a private value that would need a generated persona. */
11004
+ requireDeclared(kind, provenance, declared) {
11005
+ if (!this.declaredOnly || declared?.alias) return;
11006
+ if (provenance === "seed")
11007
+ throw new DeclaredOnlyError(
11008
+ `declared_only: the seed of kind '${kind}' carries no \`alias\`; give every private seed its stand-in or turn declared_only off`
11009
+ );
11010
+ throw new DeclaredOnlyError(
11011
+ `declared_only: a value of kind '${kind}' arrived unseeded and nothing may be minted on sight; seed it with an \`alias\`, or turn declared_only off`
11012
+ );
11013
+ }
9609
11014
  mailboxDomains() {
9610
11015
  if (this.publicMailboxDomains === null) return PUBLIC_MAILBOX_DOMAINS;
9611
11016
  return new Set(this.publicMailboxDomains.map((d) => d.toLowerCase()));
@@ -9675,8 +11080,14 @@ var AliasMap = class _AliasMap {
9675
11080
  return alias2;
9676
11081
  }
9677
11082
  const identityKey = opts.identityKey ?? `${kind}:${canon}`;
11083
+ this.requireDeclared(kind, provenance, opts.declared);
9678
11084
  const identity = this.identityFor(identityKey);
9679
- const [display, variants] = this.derive(kind, real, identity);
11085
+ const [display, variants] = this.derive(
11086
+ kind,
11087
+ real,
11088
+ identity,
11089
+ opts.declared ?? new DeclaredStandIn()
11090
+ );
9680
11091
  const alias = {
9681
11092
  kind,
9682
11093
  canonical: canon,
@@ -9799,7 +11210,15 @@ var AliasMap = class _AliasMap {
9799
11210
  }
9800
11211
  return out;
9801
11212
  }
9802
- derive(kind, real, identity) {
11213
+ /** The stand-in and its pairings. A declared stand-in replaces the generated one; the
11214
+ * kind's own pair builder runs over it and over every declared spelling. */
11215
+ derive(kind, real, identity, declared) {
11216
+ const [display, variants] = this.generated(kind, real, identity);
11217
+ if (!declared.declared) return [display, variants];
11218
+ const chosen = declared.alias ?? display;
11219
+ return [chosen, dedupe(declared.pairs(real, chosen, pairBuilder(kind)))];
11220
+ }
11221
+ generated(kind, real, identity) {
9803
11222
  if (kind === "person_name") {
9804
11223
  const display2 = fullName(identity);
9805
11224
  return [display2, namePairs(real, display2)];
@@ -9852,7 +11271,7 @@ var AliasMap = class _AliasMap {
9852
11271
  const existing = this.aliases.get(key2);
9853
11272
  if (existing) return existing.display;
9854
11273
  if (this.aliasDigests.has(digest.toLowerCase())) return digest;
9855
- const standIn = "sha256:" + (0, import_node_crypto11.createHmac)("sha256", Buffer.from(this.runKey, "hex")).update(digest, "utf8").digest("hex");
11274
+ const standIn = "sha256:" + (0, import_node_crypto12.createHmac)("sha256", Buffer.from(this.runKey, "hex")).update(digest, "utf8").digest("hex");
9856
11275
  this.aliasDigests.add(standIn.toLowerCase());
9857
11276
  const alias = {
9858
11277
  kind: "digest",
@@ -9886,13 +11305,14 @@ var AliasMap = class _AliasMap {
9886
11305
  for (const entity of entities) {
9887
11306
  const alias = this.mint(entity.type, entity.value, {
9888
11307
  identityKey: entity.identity,
9889
- role: entity.role ?? "private"
11308
+ role: entity.role ?? "private",
11309
+ declared: DeclaredStandIn.of(entity)
9890
11310
  });
9891
11311
  if (alias.role === "private") {
9892
11312
  for (const slug of this.slugs) {
9893
- const standIn = "sha256:" + (0, import_node_crypto11.createHash)("sha256").update(`${slug}:${canonical(alias.kind, alias.display)}`, "utf8").digest("hex");
11313
+ const standIn = "sha256:" + (0, import_node_crypto12.createHash)("sha256").update(`${slug}:${canonical(alias.kind, alias.display)}`, "utf8").digest("hex");
9894
11314
  alias.variants.push([
9895
- "sha256:" + (0, import_node_crypto11.createHash)("sha256").update(`${slug}:${alias.canonical}`, "utf8").digest("hex"),
11315
+ "sha256:" + (0, import_node_crypto12.createHash)("sha256").update(`${slug}:${alias.canonical}`, "utf8").digest("hex"),
9896
11316
  standIn
9897
11317
  ]);
9898
11318
  this.aliasDigests.add(standIn.toLowerCase());
@@ -10014,45 +11434,51 @@ var AliasMap = class _AliasMap {
10014
11434
  /** Requirement 3: count what slipped, do not assume nothing did. The scan is
10015
11435
  * case-folded with whitespace collapsed and walks EVERY variant of every alias,
10016
11436
  * not only the pairs the rewriter used. */
10017
- meter(text2, where) {
10018
- const haystack = folded(text2);
11437
+ /** Every private alias with a real variant of 4+ characters in the folded text,
11438
+ * case subjects first. */
11439
+ surviving(haystack) {
10019
11440
  const pub = this.publicFolded();
11441
+ const found = [];
10020
11442
  for (const alias of this.aliases.values()) {
10021
11443
  if (alias.role === "public") continue;
10022
- for (const [real] of alias.variants) {
10023
- if (real.length >= 4 && !pub.has(folded(real)) && haystack.includes(folded(real))) {
10024
- this.leaksIn.push({
10025
- where,
10026
- kind: alias.kind,
10027
- variant: shorten(real),
10028
- alias: alias.display
10029
- });
10030
- return;
10031
- }
10032
- }
11444
+ const variant = alias.variants.find(
11445
+ ([real]) => real.length >= 4 && !pub.has(folded(real)) && haystack.includes(folded(real))
11446
+ );
11447
+ if (variant !== void 0) found.push([alias, variant[0]]);
10033
11448
  }
11449
+ return [
11450
+ ...found.filter(([a]) => isSubject(a)),
11451
+ ...found.filter(([a]) => !isSubject(a))
11452
+ ];
11453
+ }
11454
+ /** A leak is about a CASE SUBJECT (a seeded entity); a value that only arrived in a
11455
+ * result and was given a stand-in on sight is a bystander, counted apart. */
11456
+ meter(text2, where) {
11457
+ const hit = this.surviving(folded(text2))[0];
11458
+ if (hit === void 0) return;
11459
+ const [alias, real] = hit;
11460
+ const rows = isSubject(alias) ? this.leaksIn : this.bystandersIn;
11461
+ rows.push({
11462
+ where,
11463
+ kind: alias.kind,
11464
+ variant: shorten(real),
11465
+ alias: alias.display
11466
+ });
10034
11467
  }
10035
- /** Requirement 4: the report and the artifacts must contain no real value. */
11468
+ /** Requirement 4: the report and the artifacts must contain no real value OF A CASE
11469
+ * SUBJECT. Bystanders are counted, never returned. */
10036
11470
  scanOutgoing(text2, where) {
10037
- const hits = [];
10038
- const haystack = typeof text2 === "string" ? folded(text2) : "";
10039
- const pub = this.publicFolded();
10040
- for (const alias of this.aliases.values()) {
10041
- if (alias.role === "public") continue;
10042
- for (const [real] of alias.variants) {
10043
- if (real.length >= 4 && !pub.has(folded(real)) && haystack.includes(folded(real))) {
10044
- hits.push({
10045
- check: "leak_outbound",
10046
- where,
10047
- kind: alias.kind,
10048
- alias: alias.display,
10049
- variant: shorten(real)
10050
- });
10051
- break;
10052
- }
10053
- }
10054
- }
11471
+ const found = this.surviving(typeof text2 === "string" ? folded(text2) : "");
11472
+ const row = ([alias, real]) => ({
11473
+ check: "leak_outbound",
11474
+ where,
11475
+ kind: alias.kind,
11476
+ alias: alias.display,
11477
+ variant: shorten(real)
11478
+ });
11479
+ const hits = found.filter(([a]) => isSubject(a)).map(row);
10055
11480
  this.leaksOut.push(...hits);
11481
+ this.bystandersOut.push(...found.filter(([a]) => !isSubject(a)).map(row));
10056
11482
  return hits;
10057
11483
  }
10058
11484
  // ------------------------------------------------------------ reporting
@@ -10149,6 +11575,8 @@ var AliasMap = class _AliasMap {
10149
11575
  leak_through_inbound_detail: this.leaksIn.slice(0, 50),
10150
11576
  leaks_outbound: this.leaksOut.length,
10151
11577
  leaks_outbound_detail: this.leaksOut.slice(0, 50),
11578
+ bystander_leak_through_inbound: this.bystandersIn.length,
11579
+ bystander_leaks_outbound: this.bystandersOut.length,
10152
11580
  unresolved_aliases_outbound: this.unresolvedOut.length,
10153
11581
  unresolved_detail: this.unresolvedOut.slice(0, 50),
10154
11582
  found_inbound: this.found.length,
@@ -10175,8 +11603,9 @@ function mirrorHandle(handle, identity) {
10175
11603
  const surname = identity.surname.toLowerCase();
10176
11604
  const text2 = handle.toLowerCase();
10177
11605
  const digits = /\d+$/.exec(text2);
10178
- const suffix = digits ? digits[0] : "";
10179
- const body = text2.slice(0, text2.length - suffix.length);
11606
+ const realSuffix = digits ? digits[0] : "";
11607
+ const body = text2.slice(0, text2.length - realSuffix.length);
11608
+ const suffix = standInDigits(realSuffix, `${given} ${surname}`);
10180
11609
  for (const separator of [".", "_", "-"]) {
10181
11610
  if (body.includes(separator))
10182
11611
  return `${given}${separator}${surname}${suffix}`;
@@ -10187,7 +11616,7 @@ function mirrorHandle(handle, identity) {
10187
11616
  }
10188
11617
 
10189
11618
  // src/hooks/config.ts
10190
- var fs12 = __toESM(require("fs"));
11619
+ var fs14 = __toESM(require("fs"));
10191
11620
 
10192
11621
  // src/cli/platform/worldData/toml.ts
10193
11622
  var TomlError = class extends Error {
@@ -10424,6 +11853,11 @@ var HookDenied = class extends Error {
10424
11853
  this.handler = handler;
10425
11854
  this.name = "HookDenied";
10426
11855
  }
11856
+ event;
11857
+ toolName;
11858
+ reason;
11859
+ findings;
11860
+ handler;
10427
11861
  };
10428
11862
  var HookError = class extends Error {
10429
11863
  constructor(event, toolName, handler, detail) {
@@ -10434,6 +11868,10 @@ var HookError = class extends Error {
10434
11868
  this.detail = detail;
10435
11869
  this.name = "HookError";
10436
11870
  }
11871
+ event;
11872
+ toolName;
11873
+ handler;
11874
+ detail;
10437
11875
  };
10438
11876
  var isObject3 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
10439
11877
  function resultFromJson(raw, handler = "handler") {
@@ -10535,9 +11973,9 @@ function alternatives(raw) {
10535
11973
  if (!parts2.length || parts2.includes("*")) return [];
10536
11974
  return parts2;
10537
11975
  }
10538
- function hasPath(node, path14) {
11976
+ function hasPath(node, path16) {
10539
11977
  let current = node;
10540
- for (const part of path14.split(".")) {
11978
+ for (const part of path16.split(".")) {
10541
11979
  if (current && typeof current === "object" && !Array.isArray(current) && part in current) {
10542
11980
  current = current[part];
10543
11981
  continue;
@@ -10578,7 +12016,7 @@ function matches(m, event) {
10578
12016
  if (m.args.length) {
10579
12017
  const haystacks = event.event === "pre_request" || event.event === "post_response" ? [event.request?.query, event.request?.body] : [event.toolInput];
10580
12018
  const present = haystacks.filter((h) => h !== void 0 && h !== null);
10581
- if (!m.args.every((path14) => present.some((h) => hasPath(h, path14))))
12019
+ if (!m.args.every((path16) => present.some((h) => hasPath(h, path16))))
10582
12020
  return false;
10583
12021
  }
10584
12022
  return true;
@@ -10978,6 +12416,7 @@ var emptyConfig = () => ({
10978
12416
  aliasPublicLayerWins: true,
10979
12417
  aliasPublicMailboxDomains: null,
10980
12418
  aliasMintInbound: [],
12419
+ aliasDeclaredOnly: false,
10981
12420
  aliasLegend: null,
10982
12421
  vendors: {},
10983
12422
  live: emptyLive()
@@ -11021,9 +12460,9 @@ function vendorOf(config, toolName) {
11021
12460
  return void 0;
11022
12461
  }
11023
12462
  function loadHookConfig(file) {
11024
- if (!fs12.existsSync(file) || !fs12.statSync(file).isFile())
12463
+ if (!fs14.existsSync(file) || !fs14.statSync(file).isFile())
11025
12464
  throw new HookConfigError(`${file}: no such file`);
11026
- const text2 = fs12.readFileSync(file, "utf8");
12465
+ const text2 = fs14.readFileSync(file, "utf8");
11027
12466
  if (file.toLowerCase().endsWith(".json")) {
11028
12467
  let data2;
11029
12468
  try {
@@ -11090,7 +12529,8 @@ function parseHookConfig(data, source) {
11090
12529
  "public_layer_wins",
11091
12530
  "public_mailbox_domains",
11092
12531
  "mint_inbound",
11093
- "legend"
12532
+ "legend",
12533
+ "declared_only"
11094
12534
  ].includes(k)
11095
12535
  );
11096
12536
  if (unknownAlias.length)
@@ -11117,6 +12557,13 @@ function parseHookConfig(data, source) {
11117
12557
  throw new HookConfigError(
11118
12558
  `alias.mint_inbound: ${badKinds.join(", ")} cannot be found by a pattern; only ${INBOUND_KINDS.join(", ")} can (a name or a handle is seeded, never guessed)`
11119
12559
  );
12560
+ const declaredOnly = alias.declared_only ?? false;
12561
+ if (typeof declaredOnly !== "boolean")
12562
+ throw new HookConfigError("alias.declared_only must be true or false");
12563
+ if (declaredOnly && mintInboundRaw.length)
12564
+ throw new HookConfigError(
12565
+ "alias.declared_only and alias.mint_inbound cannot both be set: nothing is minted on sight"
12566
+ );
11120
12567
  const legendPath = alias.legend ?? null;
11121
12568
  if (legendPath !== null && (typeof legendPath !== "string" || !legendPath.trim()))
11122
12569
  throw new HookConfigError(
@@ -11149,6 +12596,7 @@ function parseHookConfig(data, source) {
11149
12596
  aliasPublicLayerWins: publicLayerWins,
11150
12597
  aliasPublicMailboxDomains: mailbox,
11151
12598
  aliasMintInbound: mintInboundRaw,
12599
+ aliasDeclaredOnly: declaredOnly,
11152
12600
  aliasLegend: legendPath,
11153
12601
  vendors,
11154
12602
  live: parseLive(data.live ?? {}, data.tools ?? {}),
@@ -11402,9 +12850,9 @@ function parseHandler(event, raw, position) {
11402
12850
  }
11403
12851
 
11404
12852
  // src/hooks/handlers.ts
11405
- var import_node_child_process3 = require("child_process");
11406
- var fs13 = __toESM(require("fs"));
11407
- var path11 = __toESM(require("path"));
12853
+ var import_node_child_process4 = require("child_process");
12854
+ var fs15 = __toESM(require("fs"));
12855
+ var path13 = __toESM(require("path"));
11408
12856
  var import_node_url = require("url");
11409
12857
  function parseStdout(text2, handler) {
11410
12858
  const stripped = text2.trim();
@@ -11427,20 +12875,22 @@ var CommandHandler = class {
11427
12875
  this.command = command2;
11428
12876
  this.opts = opts;
11429
12877
  }
12878
+ command;
12879
+ opts;
11430
12880
  describe() {
11431
12881
  return `command ${this.command}${this.opts.args?.length ? " " + this.opts.args.join(" ") : ""}`;
11432
12882
  }
11433
12883
  run(event) {
11434
12884
  const input = JSON.stringify(eventToJson(event));
11435
12885
  const exec = this.opts.args !== void 0;
11436
- return new Promise((resolve10, reject) => {
12886
+ return new Promise((resolve11, reject) => {
11437
12887
  let child;
11438
12888
  try {
11439
- child = exec ? (0, import_node_child_process3.spawn)(this.command, this.opts.args, {
12889
+ child = exec ? (0, import_node_child_process4.spawn)(this.command, this.opts.args, {
11440
12890
  cwd: this.opts.cwd,
11441
12891
  env: this.opts.env ?? process.env,
11442
12892
  stdio: ["pipe", "pipe", "pipe"]
11443
- }) : (0, import_node_child_process3.spawn)(this.command, {
12893
+ }) : (0, import_node_child_process4.spawn)(this.command, {
11444
12894
  shell: true,
11445
12895
  cwd: this.opts.cwd,
11446
12896
  env: this.opts.env ?? process.env,
@@ -11494,7 +12944,7 @@ var CommandHandler = class {
11494
12944
  return;
11495
12945
  }
11496
12946
  try {
11497
- resolve10(
12947
+ resolve11(
11498
12948
  parseStdout(Buffer.concat(out).toString("utf8"), this.describe())
11499
12949
  );
11500
12950
  } catch (error) {
@@ -11529,6 +12979,8 @@ var HttpHandler = class {
11529
12979
  this.url = url;
11530
12980
  this.opts = opts;
11531
12981
  }
12982
+ url;
12983
+ opts;
11532
12984
  describe() {
11533
12985
  return `http ${this.url}`;
11534
12986
  }
@@ -11565,6 +13017,7 @@ var DenyHandler = class {
11565
13017
  constructor(reason = "denied by rule") {
11566
13018
  this.reason = reason;
11567
13019
  }
13020
+ reason;
11568
13021
  describe() {
11569
13022
  return `deny: ${this.reason}`;
11570
13023
  }
@@ -11577,6 +13030,8 @@ var RecordHandler = class {
11577
13030
  this.sink = sink;
11578
13031
  this.opts = opts;
11579
13032
  }
13033
+ sink;
13034
+ opts;
11580
13035
  describe() {
11581
13036
  return `record -> ${typeof this.sink === "string" ? this.sink : typeof this.sink === "function" ? "callback" : "array"}`;
11582
13037
  }
@@ -11598,8 +13053,8 @@ var RecordHandler = class {
11598
13053
  record.source = this.opts.source ?? null;
11599
13054
  if (Array.isArray(this.sink)) this.sink.push(record);
11600
13055
  else if (typeof this.sink === "string") {
11601
- fs13.mkdirSync(path11.dirname(this.sink), { recursive: true });
11602
- fs13.appendFileSync(this.sink, JSON.stringify(record) + "\n");
13056
+ fs15.mkdirSync(path13.dirname(this.sink), { recursive: true });
13057
+ fs15.appendFileSync(this.sink, JSON.stringify(record) + "\n");
11603
13058
  } else await this.sink(record);
11604
13059
  return allow();
11605
13060
  }
@@ -11613,6 +13068,7 @@ var RedactHandler = class {
11613
13068
  this.patterns = (opts.patterns ?? []).map((p) => new RegExp(p, "g"));
11614
13069
  this.token = opts.token ?? "[redacted {kind}]";
11615
13070
  }
13071
+ aliases;
11616
13072
  kinds;
11617
13073
  /** Literal strings (a name, a company, a phrase) removed wherever they appear, any
11618
13074
  * case — the arbitrary half of redaction; `patterns` is the shaped half. */
@@ -11673,6 +13129,8 @@ var AliasHandler = class {
11673
13129
  this.aliases = aliases;
11674
13130
  this.opts = opts;
11675
13131
  }
13132
+ aliases;
13133
+ opts;
11676
13134
  describe() {
11677
13135
  if (this.opts.check) return `alias check=${this.opts.check}`;
11678
13136
  return this.opts.direction ? `alias direction=${this.opts.direction}` : "alias";
@@ -11793,6 +13251,8 @@ var FunctionHandler = class {
11793
13251
  this.fn = fn;
11794
13252
  this.name = name;
11795
13253
  }
13254
+ fn;
13255
+ name;
11796
13256
  describe() {
11797
13257
  return `callable ${this.name}`;
11798
13258
  }
@@ -11804,7 +13264,7 @@ async function importCallable(target, cwd) {
11804
13264
  const hash = target.lastIndexOf("#");
11805
13265
  const modulePath = target.slice(0, hash);
11806
13266
  const exportName = target.slice(hash + 1) || "default";
11807
- const resolved = modulePath.startsWith(".") || path11.isAbsolute(modulePath) ? (0, import_node_url.pathToFileURL)(path11.resolve(cwd, modulePath)).href : modulePath;
13267
+ const resolved = modulePath.startsWith(".") || path13.isAbsolute(modulePath) ? (0, import_node_url.pathToFileURL)(path13.resolve(cwd, modulePath)).href : modulePath;
11808
13268
  let module2;
11809
13269
  try {
11810
13270
  module2 = await import(resolved);
@@ -11867,8 +13327,8 @@ async function buildHandler(spec, aliases, opts) {
11867
13327
  }
11868
13328
 
11869
13329
  // src/hooks/live.ts
11870
- var fs14 = __toESM(require("fs"));
11871
- var path12 = __toESM(require("path"));
13330
+ var fs16 = __toESM(require("fs"));
13331
+ var path14 = __toESM(require("path"));
11872
13332
  var USER_AGENT = "gateway-hooks/1 (+https://withgateway.ai)";
11873
13333
  var TAGS = /<(script|style)[^>]*>.*?<\/\1>/gis;
11874
13334
  var STRIP = /<[^>]+>/g;
@@ -11888,7 +13348,7 @@ var Pacer = class {
11888
13348
  /** Waits until the interval since the tool's last call has passed; resolves to the
11889
13349
  * seconds waited. `sleep`/`clock` are injectable for tests. */
11890
13350
  async wait(name, intervalMs, opts = {}) {
11891
- const sleep3 = opts.sleep ?? ((seconds) => new Promise((resolve10) => setTimeout(resolve10, seconds * 1e3)));
13351
+ const sleep3 = opts.sleep ?? ((seconds) => new Promise((resolve11) => setTimeout(resolve11, seconds * 1e3)));
11892
13352
  const clock = opts.clock ?? (() => Date.now() / 1e3);
11893
13353
  const now = clock();
11894
13354
  const due = (this.last.get(name) ?? -Infinity) + intervalMs / 1e3;
@@ -12119,6 +13579,8 @@ var HttpTool = class _HttpTool {
12119
13579
  this.spec = spec;
12120
13580
  this.live = live;
12121
13581
  }
13582
+ spec;
13583
+ live;
12122
13584
  /** Shared across tools: the pace is per tool name, not per HttpTool instance. */
12123
13585
  static pacer = new Pacer();
12124
13586
  /** The status of the most recent answer, for the recording line. */
@@ -12215,6 +13677,8 @@ var CallableTool = class _CallableTool {
12215
13677
  this.spec = spec;
12216
13678
  this.fn = fn;
12217
13679
  }
13680
+ spec;
13681
+ fn;
12218
13682
  static async create(spec, cwd) {
12219
13683
  const fn = await importCallable(spec.options.callable, cwd);
12220
13684
  return new _CallableTool(
@@ -12232,9 +13696,9 @@ var CallableTool = class _CallableTool {
12232
13696
  }
12233
13697
  };
12234
13698
  function readConnection(root) {
12235
- const file = path12.join(root, "connector.toml");
12236
- if (!fs14.existsSync(file)) throw new Error(`no connector.toml at ${root}`);
12237
- const raw = parseToml(fs14.readFileSync(file, "utf8"));
13699
+ const file = path14.join(root, "connector.toml");
13700
+ if (!fs16.existsSync(file)) throw new Error(`no connector.toml at ${root}`);
13701
+ const raw = parseToml(fs16.readFileSync(file, "utf8"));
12238
13702
  const connector = raw.connector ?? {};
12239
13703
  const auth = raw.auth ?? {};
12240
13704
  const operations = {};
@@ -12248,7 +13712,7 @@ function readConnection(root) {
12248
13712
  };
12249
13713
  }
12250
13714
  return {
12251
- slug: connector.slug ?? path12.basename(root),
13715
+ slug: connector.slug ?? path14.basename(root),
12252
13716
  baseUrl: (connector.base_url ?? "").replace(/\/+$/, ""),
12253
13717
  scheme: auth.scheme ?? "none",
12254
13718
  ...typeof auth.name === "string" ? { authName: auth.name } : {},
@@ -12265,8 +13729,8 @@ var ConnectorTool = class {
12265
13729
  this.spec = spec;
12266
13730
  this.live = live;
12267
13731
  let location = spec.options.connector;
12268
- if (!path12.isAbsolute(location)) location = path12.resolve(baseDir, location);
12269
- const root = fs14.existsSync(location) && fs14.statSync(location).isFile() ? path12.dirname(location) : location;
13732
+ if (!path14.isAbsolute(location)) location = path14.resolve(baseDir, location);
13733
+ const root = fs16.existsSync(location) && fs16.statSync(location).isFile() ? path14.dirname(location) : location;
12270
13734
  try {
12271
13735
  this.connection = readConnection(root);
12272
13736
  } catch (error) {
@@ -12289,6 +13753,8 @@ var ConnectorTool = class {
12289
13753
  );
12290
13754
  }
12291
13755
  }
13756
+ spec;
13757
+ live;
12292
13758
  connection;
12293
13759
  operation;
12294
13760
  get placeholders() {
@@ -12419,17 +13885,18 @@ var Recorder = class {
12419
13885
  constructor(file) {
12420
13886
  this.file = file;
12421
13887
  }
13888
+ file;
12422
13889
  write(line) {
12423
- fs14.mkdirSync(path12.dirname(this.file), { recursive: true });
12424
- fs14.appendFileSync(this.file, canonical2(line) + "\n");
13890
+ fs16.mkdirSync(path14.dirname(this.file), { recursive: true });
13891
+ fs16.appendFileSync(this.file, canonical2(line) + "\n");
12425
13892
  }
12426
13893
  };
12427
13894
  var Replay = class {
12428
13895
  constructor(file) {
12429
13896
  this.file = file;
12430
- if (!fs14.existsSync(file))
13897
+ if (!fs16.existsSync(file))
12431
13898
  throw new LiveToolError(`replay: no recording at ${file}`);
12432
- fs14.readFileSync(file, "utf8").split(/\r?\n/).forEach((raw, index2) => {
13899
+ fs16.readFileSync(file, "utf8").split(/\r?\n/).forEach((raw, index2) => {
12433
13900
  if (!raw.trim()) return;
12434
13901
  let line;
12435
13902
  try {
@@ -12449,6 +13916,7 @@ var Replay = class {
12449
13916
  );
12450
13917
  });
12451
13918
  }
13919
+ file;
12452
13920
  answers = /* @__PURE__ */ new Map();
12453
13921
  tool(spec) {
12454
13922
  const answers = this.answers;
@@ -12489,6 +13957,8 @@ var LiveTools = class _LiveTools {
12489
13957
  if (live.replay) this.replay = new Replay(live.replay);
12490
13958
  if (live.record) this.recorder = new Recorder(live.record);
12491
13959
  }
13960
+ run;
13961
+ live;
12492
13962
  replay;
12493
13963
  recorder;
12494
13964
  built = {};
@@ -12513,7 +13983,7 @@ var LiveTools = class _LiveTools {
12513
13983
  ...config.live.record ? { record: interpolatePath(config.live.record, run.runId, directory) } : {},
12514
13984
  ...config.live.replay ? { replay: interpolatePath(config.live.replay, run.runId, directory) } : {}
12515
13985
  };
12516
- return _LiveTools.create(run, live, path12.dirname(path12.resolve(file)));
13986
+ return _LiveTools.create(run, live, path14.dirname(path14.resolve(file)));
12517
13987
  }
12518
13988
  /** The declared tools for a model. `openai`: `{type: "function", function: {name,
12519
13989
  * description, parameters}}`; `anthropic`: `{name, description, input_schema}`. */
@@ -12640,6 +14110,9 @@ var Identifier = class {
12640
14110
  this.value = value;
12641
14111
  this.source = source;
12642
14112
  }
14113
+ kind;
14114
+ value;
14115
+ source;
12643
14116
  get key() {
12644
14117
  return folded(this.value);
12645
14118
  }
@@ -12673,6 +14146,7 @@ var FieldSource = class extends IdentifierSource {
12673
14146
  super();
12674
14147
  this.fieldKinds = fieldKinds;
12675
14148
  }
14149
+ fieldKinds;
12676
14150
  name = "fields";
12677
14151
  kindsFor(tool) {
12678
14152
  return { ...this.fieldKinds[ANY_TOOL] ?? {}, ...this.fieldKinds[tool] ?? {} };
@@ -12712,6 +14186,7 @@ var IdentifierCensus = class {
12712
14186
  constructor(sources) {
12713
14187
  this.sources = sources;
12714
14188
  }
14189
+ sources;
12715
14190
  get detectors() {
12716
14191
  return this.sources.map((source) => source.name);
12717
14192
  }
@@ -12750,6 +14225,12 @@ var AuditReport = class {
12750
14225
  this.leakedIdentifiers = leakedIdentifiers;
12751
14226
  this.cleanTexts = cleanTexts;
12752
14227
  }
14228
+ findings;
14229
+ census;
14230
+ detectors;
14231
+ recordsScanned;
14232
+ leakedIdentifiers;
14233
+ cleanTexts;
12753
14234
  get ok() {
12754
14235
  return this.findings.length === 0;
12755
14236
  }
@@ -12793,6 +14274,7 @@ var RedactionAudit = class _RedactionAudit {
12793
14274
  constructor(census) {
12794
14275
  this.census = census;
12795
14276
  }
14277
+ census;
12796
14278
  /** The standard audit: the run's legend, declared field kinds, pattern finders. */
12797
14279
  static forRun(options) {
12798
14280
  return new _RedactionAudit(
@@ -12826,9 +14308,9 @@ var RedactionAudit = class _RedactionAudit {
12826
14308
  };
12827
14309
 
12828
14310
  // src/hooks/run.ts
12829
- var import_node_crypto12 = require("crypto");
12830
- var fs15 = __toESM(require("fs"));
12831
- var path13 = __toESM(require("path"));
14311
+ var import_node_crypto13 = require("crypto");
14312
+ var fs17 = __toESM(require("fs"));
14313
+ var path15 = __toESM(require("path"));
12832
14314
  var BLOCKING_EVENTS = [
12833
14315
  "pre_tool_call",
12834
14316
  "pre_request",
@@ -12870,20 +14352,21 @@ var HookRun = class _HookRun {
12870
14352
  source;
12871
14353
  constructor(config, options) {
12872
14354
  this.config = config;
12873
- this.runId = options.runId ?? `run-${(0, import_node_crypto12.randomBytes)(6).toString("hex")}`;
14355
+ this.runId = options.runId ?? `run-${(0, import_node_crypto13.randomBytes)(6).toString("hex")}`;
12874
14356
  this.runKey = options.runKey ?? newRunKey();
12875
14357
  this.alias = new AliasMap(this.runKey, options.slugs ?? config.aliasSlugs, {
12876
14358
  publicLayerWins: config.aliasPublicLayerWins,
12877
14359
  publicMailboxDomains: config.aliasPublicMailboxDomains,
12878
- mintInbound: options.mintInbound ?? config.aliasMintInbound
14360
+ mintInbound: options.mintInbound ?? config.aliasMintInbound,
14361
+ declaredOnly: options.declaredOnly ?? config.aliasDeclaredOnly
12879
14362
  });
12880
14363
  this.cwd = options.cwd ?? process.cwd();
12881
- this.runDir = options.runDir ?? path13.join(this.cwd, "runs", this.runId);
14364
+ this.runDir = options.runDir ?? path15.join(this.cwd, "runs", this.runId);
12882
14365
  const chosen = options.legend !== void 0 ? options.legend : config.aliasLegend;
12883
- this.legendPath = chosen ? path13.resolve(this.cwd, interpolatePath(chosen, this.runId, this.runDir)) : null;
14366
+ this.legendPath = chosen ? path15.resolve(this.cwd, interpolatePath(chosen, this.runId, this.runDir)) : null;
12884
14367
  this.sessionId = options.session;
12885
14368
  this.source = options.source;
12886
- this.configDir = config.source ? path13.dirname(path13.resolve(config.source)) : this.cwd;
14369
+ this.configDir = config.source ? path15.dirname(path15.resolve(config.source)) : this.cwd;
12887
14370
  }
12888
14371
  /** Build from a parsed config (an object in the file's shape, or a `HookConfig`);
12889
14372
  * handlers are constructed now, so a callable that does not import fails here. */
@@ -13293,8 +14776,8 @@ var HookRun = class _HookRun {
13293
14776
  throw new Error(
13294
14777
  "no legend path: set [alias] legend, pass legend to the run, or give a path"
13295
14778
  );
13296
- fs15.mkdirSync(path13.dirname(target), { recursive: true });
13297
- fs15.writeFileSync(target, JSON.stringify(this.legend(), null, 2) + "\n");
14779
+ fs17.mkdirSync(path15.dirname(target), { recursive: true });
14780
+ fs17.writeFileSync(target, JSON.stringify(this.legend(), null, 2) + "\n");
13298
14781
  return target;
13299
14782
  }
13300
14783
  writeLegendIfConfigured() {
@@ -13353,6 +14836,10 @@ var HookedSession = class {
13353
14836
  this.vendor = vendor;
13354
14837
  this.requestFn = requestFn;
13355
14838
  }
14839
+ run;
14840
+ inner;
14841
+ vendor;
14842
+ requestFn;
13356
14843
  async call(tool, args = {}, ...rest) {
13357
14844
  const [real, context4] = await this.run.beforeCall(
13358
14845
  tool,
@@ -13386,14 +14873,14 @@ var HookedSession = class {
13386
14873
  * `apiHeaders()`), `pre_request` before it and `post_response` after. Returns
13387
14874
  * `{status, body, headers}`; a 4xx/5xx is returned, not thrown, so the agent sees
13388
14875
  * the vendor's own error shape (rewritten like any result). */
13389
- async request(method, path14, opts = {}) {
14876
+ async request(method, path16, opts = {}) {
13390
14877
  if (!this.inner.api && !this.requestFn)
13391
14878
  throw new Error(
13392
14879
  "this session has no api surface (pass requestFn for a transport of your own)"
13393
14880
  );
13394
14881
  let request = {
13395
14882
  method: method.toUpperCase(),
13396
- path: path14,
14883
+ path: path16,
13397
14884
  query: { ...opts.query ?? {} },
13398
14885
  body: opts.body ?? null
13399
14886
  };
@@ -13620,8 +15107,8 @@ var USAGE_ATTRIBUTES = [
13620
15107
  function setUsageAttributes(span, usage) {
13621
15108
  if (!usage || typeof usage !== "object") return;
13622
15109
  const u = usage;
13623
- for (const [field, attribute] of USAGE_ATTRIBUTES) {
13624
- const value = u[field];
15110
+ for (const [field2, attribute] of USAGE_ATTRIBUTES) {
15111
+ const value = u[field2];
13625
15112
  if (typeof value === "number" && Number.isFinite(value))
13626
15113
  span.setAttribute(attribute, value);
13627
15114
  }
@@ -13801,12 +15288,24 @@ var tracing = {
13801
15288
  0 && (module.exports = {
13802
15289
  AGENT_ID_KEY,
13803
15290
  ApiError,
15291
+ BROWSER_GONE_PATTERNS,
15292
+ BROWSER_TIERS,
13804
15293
  BrowserActionRecorder,
15294
+ BrowserReconnected,
15295
+ BrowserReconnector,
15296
+ BrowserUnrecoverable,
15297
+ CALL_BODY_LIMIT_BYTES,
15298
+ CALL_BODY_LIMIT_LABEL,
13805
15299
  COMPUTER_USE_SPECS,
15300
+ CheckoutProvenance,
13806
15301
  DEFAULT_BRANCH,
13807
15302
  DEFAULT_TIMEOUT_SECONDS,
13808
15303
  DEFAULT_VIEWPORT,
15304
+ DRY_RUN_AGENT,
15305
+ DRY_RUN_KIND,
15306
+ DetachedPushError,
13809
15307
  DriftError,
15308
+ DryRunOutcome,
13810
15309
  ENV_GATEWAY_HOST,
13811
15310
  ENV_GATEWAY_PUBLIC_KEY,
13812
15311
  ENV_GATEWAY_SECRET_KEY,
@@ -13814,6 +15313,8 @@ var tracing = {
13814
15313
  EVENT_FLUSH_INTERVAL_MS,
13815
15314
  EVENT_MAX_RETRIES,
13816
15315
  EXPERIMENT_ATTRIBUTES,
15316
+ EXPLORATORY_TASK,
15317
+ EXPLORATORY_TASK_SOURCE,
13817
15318
  ExperimentClient,
13818
15319
  ExperimentSpanProcessor,
13819
15320
  ExposureLogger,
@@ -13828,10 +15329,17 @@ var tracing = {
13828
15329
  GatewaySecurityError,
13829
15330
  GatewayToolApprovalRequiredError,
13830
15331
  GatewayToolBlockedError,
15332
+ HostedDryRunClient,
15333
+ IDLE_WARNING_MINUTES,
15334
+ NO_GRADER_REASON,
15335
+ PLATFORM_TIMEOUT_DEFAULT_MS,
15336
+ PLATFORM_TIMEOUT_ENV,
13831
15337
  Persona,
13832
15338
  PersonaError,
13833
15339
  PersonasClient,
15340
+ PlatformTransport,
13834
15341
  PushSlugConflict,
15342
+ RECOVER_BUDGET_MS,
13835
15343
  REPLAY_ENVIRONMENT,
13836
15344
  ReplayCase,
13837
15345
  ReplayCheck,
@@ -13839,12 +15347,16 @@ var tracing = {
13839
15347
  ReplayReport,
13840
15348
  ReplaySuite,
13841
15349
  ReplayTask,
15350
+ SANDBOX_REQUEST_TIMEOUT_MS,
15351
+ SESSION_STATES,
15352
+ STATUS_WAIT_CAP_SECONDS,
13842
15353
  STRIP_PREFIX,
13843
15354
  SUCCESS_METRIC_NAME_KEY,
13844
15355
  SUCCESS_SIGNAL_KEY,
13845
15356
  SURFACE_KINDS,
13846
15357
  ScoreError,
13847
15358
  ScoresClient,
15359
+ SecretScrubber,
13848
15360
  SessionLoadError,
13849
15361
  SessionRecording,
13850
15362
  SessionTrace,
@@ -13854,10 +15366,15 @@ var tracing = {
13854
15366
  TaskSessions,
13855
15367
  ToolStubRegistry,
13856
15368
  TraceDiff,
15369
+ TransportCause,
15370
+ UnreachableError,
13857
15371
  UserProfileError,
13858
15372
  UsersClient,
15373
+ VERIFIER_REWARD_PREFIX,
13859
15374
  WHITESPACE,
13860
15375
  WorldBrowser,
15376
+ WorldCallTooLarge,
15377
+ WorldEditClient,
13861
15378
  WorldSandboxClient,
13862
15379
  WorldSession,
13863
15380
  WorldSessionCallError,
@@ -13871,6 +15388,8 @@ var tracing = {
13871
15388
  applyTransforms,
13872
15389
  archiveMode,
13873
15390
  assembleManifest,
15391
+ assertBrowserTier,
15392
+ assertTaskRef,
13874
15393
  assignVariant,
13875
15394
  attachManifest,
13876
15395
  attachSession,
@@ -13880,7 +15399,9 @@ var tracing = {
13880
15399
  buildSourceTarball,
13881
15400
  canonicalJson,
13882
15401
  captureToolCalls,
15402
+ checkoutIdentity,
13883
15403
  clearExperimentContext,
15404
+ closeConnection,
13884
15405
  collectArchiveRelPaths,
13885
15406
  computeBuildHash,
13886
15407
  computeContentHash,
@@ -13910,13 +15431,18 @@ var tracing = {
13910
15431
  hashForm,
13911
15432
  hooks,
13912
15433
  identify,
15434
+ idleWarning,
13913
15435
  ingest,
13914
15436
  ingestToolCalls,
15437
+ isBrowserGone,
15438
+ isSandboxImportPending,
13915
15439
  isTaskIdRef,
13916
15440
  isTaskManifest,
13917
15441
  isTaskSpec,
13918
15442
  listEnvSecretKeys,
13919
15443
  listRunConfigs,
15444
+ listRuns,
15445
+ listSessions,
13920
15446
  listTaskSessions,
13921
15447
  listTasks,
13922
15448
  loadSession,
@@ -13930,26 +15456,31 @@ var tracing = {
13930
15456
  openTask,
13931
15457
  openWorld,
13932
15458
  openWorldVersion,
15459
+ parseErrorBody,
13933
15460
  parseSlugRef,
13934
15461
  parseToolCallRecord,
13935
15462
  parseTransform,
13936
15463
  parseWorldTaskRefs,
13937
15464
  personas,
15465
+ platformTimeoutMs,
13938
15466
  preserveForm,
13939
15467
  propose,
13940
15468
  pull,
13941
15469
  push,
15470
+ pushBranch,
13942
15471
  pushSlug,
13943
15472
  pyText,
13944
15473
  queryRows,
13945
15474
  queryRowsSearch,
13946
15475
  readLocalMeta,
13947
15476
  readToolCallRecords,
15477
+ rebaseConflicts,
13948
15478
  redactActionArgs,
13949
15479
  redactionOf,
13950
15480
  registerArtifact,
13951
15481
  registerPrompt,
13952
15482
  registerSkill,
15483
+ releaseConnection,
13953
15484
  renderAgentSystem,
13954
15485
  replay,
13955
15486
  resetBuildRegistry,
@@ -13958,11 +15489,13 @@ var tracing = {
13958
15489
  resolveUserId,
13959
15490
  roundForm,
13960
15491
  runSessions,
15492
+ runSet,
13961
15493
  runSuite,
13962
15494
  runTask,
13963
15495
  runWithExperimentContext,
13964
15496
  schemaFromSignature,
13965
15497
  scores,
15498
+ serializeCallBody,
13966
15499
  sessionObservationFromApi,
13967
15500
  sessionToolObservations,
13968
15501
  sessions,
@@ -13981,6 +15514,7 @@ var tracing = {
13981
15514
  tracing,
13982
15515
  uiEntryUrl,
13983
15516
  uiUrl,
15517
+ uncommittedPaths,
13984
15518
  updateTask,
13985
15519
  upsertRunConfig,
13986
15520
  users,