@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.mjs CHANGED
@@ -8,11 +8,20 @@ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require
8
8
  if (typeof require !== "undefined") return require.apply(this, arguments);
9
9
  throw Error('Dynamic require of "' + x + '" is not supported');
10
10
  });
11
- var __esm = (fn, res) => function __init() {
12
- return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
11
+ var __esm = (fn, res, err) => function __init() {
12
+ if (err) throw err[0];
13
+ try {
14
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
15
+ } catch (e) {
16
+ throw err = [e], e;
17
+ }
13
18
  };
14
19
  var __commonJS = (cb, mod) => function __require2() {
15
- return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
20
+ try {
21
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
22
+ } catch (e) {
23
+ throw mod = 0, e;
24
+ }
16
25
  };
17
26
  var __export = (target, all) => {
18
27
  for (var name in all)
@@ -181,10 +190,10 @@ var init_users = __esm({
181
190
  totalItems: Number(meta.totalItems ?? rows.length)
182
191
  };
183
192
  }
184
- async requestJson(method, path14, payload) {
193
+ async requestJson(method, path16, payload) {
185
194
  let response;
186
195
  try {
187
- response = await fetch(`${this.host}${path14}`, {
196
+ response = await fetch(`${this.host}${path16}`, {
188
197
  method,
189
198
  headers: {
190
199
  Authorization: this.authHeader(),
@@ -195,17 +204,17 @@ var init_users = __esm({
195
204
  });
196
205
  } catch (error) {
197
206
  throw new UserProfileError(
198
- `${method} ${path14} failed: ${error instanceof Error ? error.message : String(error)}`,
207
+ `${method} ${path16} failed: ${error instanceof Error ? error.message : String(error)}`,
199
208
  { cause: error }
200
209
  );
201
210
  }
202
211
  const text2 = await response.text();
203
212
  if (!response.ok) {
204
213
  throw new UserProfileError(
205
- `${method} ${path14} failed (${response.status}): ${text2.slice(0, 500)}`
214
+ `${method} ${path16} failed (${response.status}): ${text2.slice(0, 500)}`
206
215
  );
207
216
  }
208
- this.log("%s %s -> %s", method, path14, response.status);
217
+ this.log("%s %s -> %s", method, path16, response.status);
209
218
  return safeJson4(text2);
210
219
  }
211
220
  authHeader() {
@@ -394,10 +403,10 @@ var init_scores = __esm({
394
403
  metadata: signalMetadata
395
404
  });
396
405
  }
397
- async request(method, path14, payload) {
406
+ async request(method, path16, payload) {
398
407
  let response;
399
408
  try {
400
- response = await fetch(`${this.host}${path14}`, {
409
+ response = await fetch(`${this.host}${path16}`, {
401
410
  method,
402
411
  headers: {
403
412
  Authorization: this.authHeader(),
@@ -408,17 +417,17 @@ var init_scores = __esm({
408
417
  });
409
418
  } catch (error) {
410
419
  throw new ScoreError(
411
- `${method} ${path14} failed: ${error instanceof Error ? error.message : String(error)}`,
420
+ `${method} ${path16} failed: ${error instanceof Error ? error.message : String(error)}`,
412
421
  { cause: error }
413
422
  );
414
423
  }
415
424
  const text2 = await response.text();
416
425
  if (!response.ok) {
417
426
  throw new ScoreError(
418
- `${method} ${path14} failed (${response.status}): ${text2.slice(0, 500)}`
427
+ `${method} ${path16} failed (${response.status}): ${text2.slice(0, 500)}`
419
428
  );
420
429
  }
421
- this.log("%s %s -> %s", method, path14, response.status);
430
+ this.log("%s %s -> %s", method, path16, response.status);
422
431
  }
423
432
  authHeader() {
424
433
  return `Basic ${Buffer.from(`${this.publicKey}:${this.secretKey}`).toString(
@@ -441,7 +450,275 @@ var init_scores = __esm({
441
450
  }
442
451
  });
443
452
 
453
+ // src/worlds/transport.ts
454
+ function platformTimeoutMs(env = process.env) {
455
+ const raw = env[PLATFORM_TIMEOUT_ENV];
456
+ if (raw === void 0 || raw === "") return PLATFORM_TIMEOUT_DEFAULT_MS;
457
+ const value = Number(raw);
458
+ if (Number.isInteger(value) && value > 0) return value;
459
+ throw new Error(`${PLATFORM_TIMEOUT_ENV} must be a positive whole number of milliseconds, not \`${raw}\`.`);
460
+ }
461
+ var PLATFORM_TIMEOUT_ENV, PLATFORM_TIMEOUT_DEFAULT_MS, CHECK_HOST, RETRY, CAUSES, UNKNOWN_CAUSE, TransportCause, UnreachableError, PlatformTransport;
462
+ var init_transport = __esm({
463
+ "src/worlds/transport.ts"() {
464
+ "use strict";
465
+ PLATFORM_TIMEOUT_ENV = "GATEWAY_TIMEOUT_MS";
466
+ PLATFORM_TIMEOUT_DEFAULT_MS = 12e4;
467
+ CHECK_HOST = "Check GATEWAY_HOST (or --host) points at a running platform, then retry.";
468
+ RETRY = "Retry; if it repeats, check the network between here and the platform.";
469
+ CAUSES = {
470
+ ECONNREFUSED: { reason: "connection refused", next: CHECK_HOST },
471
+ ENOTFOUND: { reason: "DNS lookup failed", next: CHECK_HOST },
472
+ EAI_AGAIN: { reason: "DNS lookup failed", next: CHECK_HOST },
473
+ ETIMEDOUT: { reason: "connect timed out", next: CHECK_HOST },
474
+ UND_ERR_CONNECT_TIMEOUT: { reason: "connect timed out", next: CHECK_HOST },
475
+ EHOSTUNREACH: { reason: "host unreachable", next: CHECK_HOST },
476
+ ENETUNREACH: { reason: "network unreachable", next: RETRY },
477
+ ECONNRESET: { reason: "connection dropped", next: RETRY },
478
+ UND_ERR_SOCKET: { reason: "connection dropped", next: RETRY },
479
+ EPIPE: { reason: "connection dropped", next: RETRY }
480
+ };
481
+ UNKNOWN_CAUSE = { reason: "network error", next: CHECK_HOST };
482
+ TransportCause = class _TransportCause {
483
+ constructor(reason, detail, next) {
484
+ this.reason = reason;
485
+ this.detail = detail;
486
+ this.next = next;
487
+ }
488
+ reason;
489
+ detail;
490
+ next;
491
+ static timeout(timeoutMs) {
492
+ return new _TransportCause(
493
+ `timed out after ${timeoutMs / 1e3}s`,
494
+ null,
495
+ `Retry; if the platform is slow, raise ${PLATFORM_TIMEOUT_ENV} (milliseconds per request).`
496
+ );
497
+ }
498
+ static of(error) {
499
+ const cause = error instanceof Error && error.cause instanceof Error ? error.cause : void 0;
500
+ const code = cause && "code" in cause && typeof cause.code === "string" ? cause.code : null;
501
+ const message = cause?.message ?? (error instanceof Error ? error.message : String(error));
502
+ const known = code && CAUSES[code] || UNKNOWN_CAUSE;
503
+ return new _TransportCause(known.reason, code ? `${code}: ${message}` : message, known.next);
504
+ }
505
+ describe() {
506
+ return this.detail === null ? this.reason : `${this.reason} (${this.detail})`;
507
+ }
508
+ };
509
+ UnreachableError = class extends Error {
510
+ constructor(host, method, route, failure) {
511
+ super(`${method} ${route}: no answer from ${host}: ${failure.describe()}. ${failure.next}`);
512
+ this.host = host;
513
+ this.method = method;
514
+ this.route = route;
515
+ this.failure = failure;
516
+ this.name = "UnreachableError";
517
+ }
518
+ host;
519
+ method;
520
+ route;
521
+ failure;
522
+ };
523
+ PlatformTransport = class {
524
+ constructor(endpoint, timeoutMs = platformTimeoutMs()) {
525
+ this.endpoint = endpoint;
526
+ this.timeoutMs = timeoutMs;
527
+ }
528
+ endpoint;
529
+ timeoutMs;
530
+ /** A request that legitimately takes longer (a sandbox exec, a world create) waits its own budget; every other one waits the default. */
531
+ budget(ownMs) {
532
+ return Math.max(ownMs ?? 0, this.timeoutMs);
533
+ }
534
+ async send(method, route, body, opts = {}) {
535
+ const timeoutMs = this.budget(opts.timeoutMs);
536
+ const payload = body === void 0 ? {} : { body: JSON.stringify(body) };
537
+ const controller = new AbortController();
538
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
539
+ try {
540
+ const res = await fetch(`${this.endpoint.host}${route}`, {
541
+ method,
542
+ headers: {
543
+ "content-type": "application/json",
544
+ accept: "application/json",
545
+ authorization: "Basic " + Buffer.from(`${this.endpoint.publicKey}:${this.endpoint.secretKey}`).toString("base64")
546
+ },
547
+ ...payload,
548
+ signal: controller.signal
549
+ });
550
+ return { status: res.status, ok: res.ok, text: await res.text() };
551
+ } catch (error) {
552
+ const cause = controller.signal.aborted ? TransportCause.timeout(timeoutMs) : TransportCause.of(error);
553
+ throw new UnreachableError(this.endpoint.host, method, route, cause);
554
+ } finally {
555
+ clearTimeout(timer);
556
+ }
557
+ }
558
+ };
559
+ }
560
+ });
561
+
562
+ // src/worlds/browserReconnect.ts
563
+ async function closeConnection(c) {
564
+ await c.context.close();
565
+ await c.browser.close();
566
+ }
567
+ async function releaseConnection(c) {
568
+ await closeConnection(c).catch(() => void 0);
569
+ }
570
+ function isBrowserGone(error) {
571
+ const message = error instanceof Error ? error.message : String(error);
572
+ if (PAGE_NETWORK_ERROR.test(message)) return false;
573
+ return BROWSER_GONE_PATTERNS.some((p) => p.test(message));
574
+ }
575
+ function refusalIsTransient(error) {
576
+ const { status, code } = error;
577
+ if (typeof status !== "number") return true;
578
+ if (status >= 500) return true;
579
+ return status === 400 && code === "browser_capacity";
580
+ }
581
+ function describe(error) {
582
+ return error instanceof Error ? error.message : String(error);
583
+ }
584
+ var RECOVER_BUDGET_MS, BACKOFF_BASE_MS, BACKOFF_CAP_MS, BROWSER_GONE_PATTERNS, PAGE_NETWORK_ERROR, REDACTED, TOKEN_QUERY_VALUE, SecretScrubber, BrowserReconnected, BrowserUnrecoverable, BrowserReconnector;
585
+ var init_browserReconnect = __esm({
586
+ "src/worlds/browserReconnect.ts"() {
587
+ "use strict";
588
+ RECOVER_BUDGET_MS = 9e4;
589
+ BACKOFF_BASE_MS = 1e3;
590
+ BACKOFF_CAP_MS = 5e3;
591
+ BROWSER_GONE_PATTERNS = [
592
+ /target page, context or browser has been closed/i,
593
+ /\bbrowser has been (closed|disconnected)\b/i,
594
+ /\bbrowser (has )?disconnected\b/i,
595
+ /\btarget closed\b/i,
596
+ /\bwebsocket is not open\b/i,
597
+ /\bconnection closed\b/i
598
+ ];
599
+ PAGE_NETWORK_ERROR = /net::ERR_/i;
600
+ REDACTED = "<redacted>";
601
+ TOKEN_QUERY_VALUE = /([?&]token=)[^&#\s"')]*/gi;
602
+ SecretScrubber = class {
603
+ secrets;
604
+ constructor(secrets) {
605
+ const known = secrets.filter((s) => Boolean(s));
606
+ this.secrets = [
607
+ .../* @__PURE__ */ new Set([...known, ...known.map((s) => encodeURIComponent(s))])
608
+ ].sort((a, b) => b.length - a.length);
609
+ }
610
+ scrub(text2) {
611
+ const bare = this.secrets.reduce(
612
+ (out, secret) => out.split(secret).join(REDACTED),
613
+ text2
614
+ );
615
+ return bare.replace(TOKEN_QUERY_VALUE, `$1${REDACTED}`);
616
+ }
617
+ };
618
+ BrowserReconnected = class extends Error {
619
+ constructor(outcome, restoredUrl, cause) {
620
+ super(
621
+ `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.",
622
+ { cause }
623
+ );
624
+ this.outcome = outcome;
625
+ this.restoredUrl = restoredUrl;
626
+ this.name = "BrowserReconnected";
627
+ }
628
+ outcome;
629
+ restoredUrl;
630
+ };
631
+ BrowserUnrecoverable = class extends Error {
632
+ constructor(message, cause) {
633
+ super(message, { cause });
634
+ this.name = "BrowserUnrecoverable";
635
+ }
636
+ };
637
+ BrowserReconnector = class {
638
+ constructor(repair, connect, opts = {}) {
639
+ this.repair = repair;
640
+ this.connect = connect;
641
+ this.sleep = opts.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
642
+ this.now = opts.now ?? Date.now;
643
+ this.budgetMs = opts.budgetMs ?? RECOVER_BUDGET_MS;
644
+ this.scrub = opts.scrub ?? ((text2) => text2);
645
+ }
646
+ repair;
647
+ connect;
648
+ sleep;
649
+ now;
650
+ scrub;
651
+ budgetMs;
652
+ /**
653
+ * Repair, reconnect and `restore` until it works or the budget runs out.
654
+ * `restore` receives each new connection (the owner adopts it and reopens
655
+ * its page); a restore that fails counts as a failed reconnect, because the
656
+ * browser may have died again. A repair the platform refuses for good
657
+ * rethrows `cause` untouched.
658
+ */
659
+ async recover(cause, restore) {
660
+ const deadline = this.now() + this.budgetMs;
661
+ let reason = describe(cause);
662
+ for (let attempt = 1; ; attempt++) {
663
+ const step = await this.attempt(restore);
664
+ if (step.kind === "recovered")
665
+ return { outcome: step.outcome, attempts: attempt };
666
+ if (step.kind === "stop") throw cause;
667
+ reason = step.reason;
668
+ const remaining = deadline - this.now();
669
+ if (remaining <= 0) break;
670
+ const backoff = Math.min(
671
+ BACKOFF_BASE_MS * 2 ** (attempt - 1),
672
+ BACKOFF_CAP_MS
673
+ );
674
+ await this.sleep(Math.min(step.waitMs ?? backoff, remaining));
675
+ }
676
+ throw new BrowserUnrecoverable(
677
+ `the session's browser could not be recovered within ${Math.round(this.budgetMs / 1e3)}s: ${this.scrub(reason)}`,
678
+ cause
679
+ );
680
+ }
681
+ async attempt(restore) {
682
+ let answer;
683
+ try {
684
+ answer = await this.repair();
685
+ } catch (error) {
686
+ if (!refusalIsTransient(error)) return { kind: "stop" };
687
+ return {
688
+ kind: "wait",
689
+ reason: `repair failed: ${describe(error)}`,
690
+ waitMs: null
691
+ };
692
+ }
693
+ const outcome = answer.outcome;
694
+ if (outcome === "starting")
695
+ return {
696
+ kind: "wait",
697
+ reason: "a new browser is still starting",
698
+ waitMs: answer.retryAfterMs
699
+ };
700
+ try {
701
+ await restore(await this.connect());
702
+ } catch (error) {
703
+ return {
704
+ kind: "wait",
705
+ reason: `reconnect failed: ${describe(error)}`,
706
+ waitMs: null
707
+ };
708
+ }
709
+ return { kind: "recovered", outcome };
710
+ }
711
+ };
712
+ }
713
+ });
714
+
444
715
  // src/worlds/browser.ts
716
+ function assertBrowserTier(value) {
717
+ if (BROWSER_TIERS.includes(value)) return;
718
+ throw new Error(
719
+ `Unknown browser tier: ${String(value)}; choose from ${BROWSER_TIERS.join(", ")}`
720
+ );
721
+ }
445
722
  function surfaceKinds(s) {
446
723
  const kinds = ["tools"];
447
724
  if (s.api) kinds.push("api");
@@ -449,9 +726,9 @@ function surfaceKinds(s) {
449
726
  if (s.browser) kinds.push("browser");
450
727
  return kinds;
451
728
  }
452
- function uiUrl(ui, path14) {
729
+ function uiUrl(ui, path16) {
453
730
  const base = ui.url.replace(/\/+$/, "");
454
- const rel = path14.startsWith("/") ? path14 : `/${path14}`;
731
+ const rel = path16.startsWith("/") ? path16 : `/${path16}`;
455
732
  if (!ui.token) return base + rel;
456
733
  const [beforeHash, hash] = splitHash(rel);
457
734
  const joiner = beforeHash.includes("?") ? "&" : "?";
@@ -517,19 +794,34 @@ async function openBrowser(surfaces, opts = {}) {
517
794
  const mode = resolveBrowserMode(surfaces, opts.mode ?? "auto");
518
795
  const pw = opts.playwright ?? await loadPlaywright();
519
796
  const viewport = surfaces.browser?.viewport ?? DEFAULT_VIEWPORT;
520
- 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 });
521
- const context4 = await browser.newContext({ viewport });
522
- const page = await context4.newPage();
797
+ const attach = async () => {
798
+ 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 });
799
+ const context4 = await browser.newContext({ viewport });
800
+ return { browser, context: context4, page: await context4.newPage() };
801
+ };
802
+ let live = await attach();
803
+ const reattach = async () => {
804
+ const fresh = await attach();
805
+ await releaseConnection(live);
806
+ live = fresh;
807
+ return fresh;
808
+ };
809
+ const scrubber = new SecretScrubber([
810
+ surfaces.browser?.wsUrl,
811
+ surfaces.ui?.token
812
+ ]);
813
+ const reconnector = mode === "hosted" && surfaces.browser.protocol === "cdp" && opts.repair ? new BrowserReconnector(opts.repair, reattach, {
814
+ scrub: (text2) => scrubber.scrub(text2)
815
+ }) : null;
523
816
  return new WorldBrowser(
524
- page,
817
+ live.page,
525
818
  surfaces.ui,
526
819
  mode,
527
- async () => {
528
- await context4.close();
529
- await browser.close();
530
- },
820
+ () => closeConnection(live),
531
821
  viewport,
532
- opts.recorder ?? null
822
+ opts.recorder ?? null,
823
+ reconnector,
824
+ scrubber
533
825
  );
534
826
  }
535
827
  function computerUseToolkit(browser, opts = {}) {
@@ -581,12 +873,14 @@ function computerUseToolkit(browser, opts = {}) {
581
873
  specs
582
874
  };
583
875
  }
584
- 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;
876
+ 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;
585
877
  var init_browser = __esm({
586
878
  "src/worlds/browser.ts"() {
587
879
  "use strict";
588
880
  init_session();
881
+ init_browserReconnect();
589
882
  SURFACE_KINDS = ["tools", "api", "ui", "browser"];
883
+ BROWSER_TIERS = ["standard", "premium"];
590
884
  DEFAULT_VIEWPORT = { width: 1280, height: 800 };
591
885
  SETTLE_TIMEOUT_MS = 5e3;
592
886
  SETTLE_QUIET_MS = 150;
@@ -603,6 +897,7 @@ var init_browser = __esm({
603
897
  super(`World surface '${surface}' is unavailable: ${reason}`);
604
898
  this.surface = surface;
605
899
  }
900
+ surface;
606
901
  };
607
902
  UI_TOKEN_QUERY = "token";
608
903
  BrowserActionRecorder = class {
@@ -611,6 +906,9 @@ var init_browser = __esm({
611
906
  this.agentId = agentId;
612
907
  this.opts = opts;
613
908
  }
909
+ post;
910
+ agentId;
911
+ opts;
614
912
  seq = 0;
615
913
  base = null;
616
914
  queue = [];
@@ -624,8 +922,8 @@ var init_browser = __esm({
624
922
  }
625
923
  resolveBase() {
626
924
  if (this.base === null) {
627
- const resolve10 = this.opts.resumeFrom ?? (async () => 0);
628
- this.base = resolve10().then((n) => {
925
+ const resolve11 = this.opts.resumeFrom ?? (async () => 0);
926
+ this.base = resolve11().then((n) => {
629
927
  if (!Number.isInteger(n) || n < 0)
630
928
  throw new Error(
631
929
  `browser event base seq must be a non-negative integer, got ${String(n)}`
@@ -694,13 +992,38 @@ var init_browser = __esm({
694
992
  }
695
993
  };
696
994
  WorldBrowser = class {
697
- constructor(page, ui, mode, teardown, viewport = DEFAULT_VIEWPORT, recorder = null) {
698
- this.page = page;
995
+ constructor(page, ui, mode, teardown, viewport = DEFAULT_VIEWPORT, recorder = null, reconnector = null, scrubber = new SecretScrubber([ui?.token])) {
699
996
  this.ui = ui;
700
997
  this.mode = mode;
701
998
  this.teardown = teardown;
702
999
  this.viewport = viewport;
703
1000
  this.recorder = recorder;
1001
+ this.reconnector = reconnector;
1002
+ this.scrubber = scrubber;
1003
+ this.current = page;
1004
+ this.watchNetwork(page);
1005
+ }
1006
+ ui;
1007
+ mode;
1008
+ teardown;
1009
+ viewport;
1010
+ recorder;
1011
+ reconnector;
1012
+ scrubber;
1013
+ current;
1014
+ inflight = 0;
1015
+ lastNetwork = Date.now();
1016
+ /** Where the page last was after an action, token stripped: what a
1017
+ * reconnect reopens. Null until the page has left `about:blank`. */
1018
+ lastUrl = null;
1019
+ /** The live Playwright page; a new object after a reconnect. */
1020
+ get page() {
1021
+ return this.current;
1022
+ }
1023
+ get agentId() {
1024
+ return this.recorder?.agentId ?? null;
1025
+ }
1026
+ watchNetwork(page) {
704
1027
  page.on("request", () => {
705
1028
  this.inflight += 1;
706
1029
  this.lastNetwork = Date.now();
@@ -712,42 +1035,105 @@ var init_browser = __esm({
712
1035
  page.on("requestfinished", done);
713
1036
  page.on("requestfailed", done);
714
1037
  }
715
- inflight = 0;
716
- lastNetwork = Date.now();
717
- get agentId() {
718
- return this.recorder?.agentId ?? null;
1038
+ /** Run `fn` against the page. If it fails because the browser is gone,
1039
+ * recover; then `retry` runs it ONCE more and `report` throws
1040
+ * `BrowserReconnected` instead of replaying it. Any other error, and a
1041
+ * second loss during the retry, propagate unchanged. */
1042
+ async resilient(fn, onLoss) {
1043
+ try {
1044
+ return this.remember(await fn());
1045
+ } catch (error) {
1046
+ if (!this.reconnector || !isBrowserGone(error)) throw error;
1047
+ const recovered = await this.recover(this.reconnector, error);
1048
+ if (onLoss === "report")
1049
+ throw new BrowserReconnected(
1050
+ recovered.outcome,
1051
+ recovered.restoredUrl,
1052
+ error
1053
+ );
1054
+ }
1055
+ return this.remember(await fn());
1056
+ }
1057
+ remember(result) {
1058
+ this.lastUrl = this.openedUrl() ?? this.lastUrl;
1059
+ return result;
1060
+ }
1061
+ /** The page's URL less its token; null while it is blank. */
1062
+ openedUrl() {
1063
+ const url = this.page.url();
1064
+ return url && url !== "about:blank" ? withoutUiToken(url) : null;
1065
+ }
1066
+ async recover(reconnector, cause) {
1067
+ const started = Date.now();
1068
+ const message = cause instanceof Error ? cause.message : String(cause);
1069
+ const args = { cause: this.scrubber.scrub(message).slice(0, 200) };
1070
+ let result;
1071
+ try {
1072
+ result = await reconnector.recover(cause, (c) => this.adopt(c));
1073
+ } catch (error) {
1074
+ await this.report("browser_reconnect", args, started, error);
1075
+ throw error;
1076
+ }
1077
+ const restoredUrl = this.openedUrl();
1078
+ await this.report(
1079
+ "browser_reconnect",
1080
+ { ...args, ...result, restoredUrl },
1081
+ started,
1082
+ null
1083
+ );
1084
+ return { ...result, restoredUrl };
1085
+ }
1086
+ /** Take over a new connection's page and reopen the page the agent was on
1087
+ * (`openBrowser` owns the connection itself). A new browser has no session
1088
+ * cookie, so a World Host UI is first loaded with its token, exactly as
1089
+ * `goto()` loads the entry page. */
1090
+ async adopt(connection) {
1091
+ this.current = connection.page;
1092
+ this.inflight = 0;
1093
+ this.watchNetwork(connection.page);
1094
+ const last = this.lastUrl;
1095
+ if (!last) return;
1096
+ if (this.ui?.token)
1097
+ await this.page.goto(uiEntryUrl(this.ui), { waitUntil: "load" });
1098
+ if (withoutUiToken(this.page.url()) !== last)
1099
+ await this.page.goto(last, { waitUntil: "load" });
1100
+ await this.settle();
719
1101
  }
720
1102
  /** Run one action and report it: the event carries what was asked,
721
1103
  * whether it worked, and the screen after — for failures too, so a
722
1104
  * reviewer sees what the agent saw when the selector did not match. */
723
- async act(action, args, fn) {
724
- const recorder = this.recorder;
725
- if (!recorder) return fn();
1105
+ async act(action, args, fn, onLoss = "report") {
726
1106
  const started = Date.now();
727
- let ok = true;
728
- let error = null;
729
1107
  try {
730
- return await fn();
731
- } catch (err) {
732
- ok = false;
733
- error = (err instanceof Error ? `${err.name}: ${err.message}` : String(err)).slice(0, 4e3);
734
- throw err;
735
- } finally {
736
- recorder.record({
737
- agentId: recorder.agentId,
738
- seq: recorder.nextSeq(),
739
- ts: (/* @__PURE__ */ new Date()).toISOString(),
740
- action,
741
- args: redactActionArgs(action, args),
742
- ok,
743
- error,
744
- durationMs: Date.now() - started,
745
- mode: this.mode,
746
- viewport: { ...this.viewport },
747
- ...await this.observeForEvent()
748
- });
1108
+ const result = await this.resilient(fn, onLoss);
1109
+ await this.report(action, args, started, null);
1110
+ return result;
1111
+ } catch (error) {
1112
+ await this.report(action, args, started, error);
1113
+ throw error;
749
1114
  }
750
1115
  }
1116
+ /** One event on the recorder, if there is one; `failure` null means ok. */
1117
+ async report(action, args, started, failure) {
1118
+ const recorder = this.recorder;
1119
+ if (!recorder) return;
1120
+ const error = failure === null ? null : this.scrubber.scrub(
1121
+ failure instanceof Error ? `${failure.name}: ${failure.message}` : String(failure)
1122
+ ).slice(0, 4e3);
1123
+ recorder.record({
1124
+ agentId: recorder.agentId,
1125
+ seq: recorder.nextSeq(),
1126
+ ts: (/* @__PURE__ */ new Date()).toISOString(),
1127
+ action,
1128
+ args: redactActionArgs(action, args),
1129
+ ok: failure === null,
1130
+ error,
1131
+ durationMs: Date.now() - started,
1132
+ mode: this.mode,
1133
+ viewport: { ...this.viewport },
1134
+ ...await this.observeForEvent()
1135
+ });
1136
+ }
751
1137
  async observeForEvent() {
752
1138
  const out = {
753
1139
  url: null,
@@ -794,7 +1180,9 @@ var init_browser = __esm({
794
1180
  await this.page.goto(target, { waitUntil: "load" });
795
1181
  await this.settle();
796
1182
  return this.page.url();
797
- }
1183
+ },
1184
+ // Navigating again lands on the same page: safe to replay.
1185
+ "retry"
798
1186
  );
799
1187
  }
800
1188
  async back() {
@@ -847,22 +1235,25 @@ var init_browser = __esm({
847
1235
  );
848
1236
  }
849
1237
  async screenshot(fullPage = false) {
850
- return this.page.screenshot({ type: "png", fullPage });
1238
+ return this.resilient(
1239
+ () => this.page.screenshot({ type: "png", fullPage }),
1240
+ "retry"
1241
+ );
851
1242
  }
852
1243
  async screenshotBase64(fullPage = false) {
853
1244
  return (await this.screenshot(fullPage)).toString("base64");
854
1245
  }
855
1246
  async text(selector = "body") {
856
- return this.page.innerText(selector);
1247
+ return this.resilient(() => this.page.innerText(selector), "retry");
857
1248
  }
858
1249
  async html() {
859
- return this.page.content();
1250
+ return this.resilient(() => this.page.content(), "retry");
860
1251
  }
861
1252
  get url() {
862
1253
  return this.page.url();
863
1254
  }
864
1255
  async title() {
865
- return this.page.title();
1256
+ return this.resilient(() => this.page.title(), "retry");
866
1257
  }
867
1258
  async close() {
868
1259
  try {
@@ -918,6 +1309,82 @@ var init_browser = __esm({
918
1309
  }
919
1310
  });
920
1311
 
1312
+ // src/worlds/sessionContract.ts
1313
+ function serializeCallBody(body) {
1314
+ const text2 = JSON.stringify(body);
1315
+ const size = Buffer.byteLength(text2, "utf8");
1316
+ if (size > CALL_BODY_LIMIT_BYTES) throw new WorldCallTooLarge(size);
1317
+ return text2;
1318
+ }
1319
+ function idleWarning(idleExpiresAt, now = /* @__PURE__ */ new Date()) {
1320
+ if (!idleExpiresAt) return null;
1321
+ const leftMs = new Date(idleExpiresAt).getTime() - now.getTime();
1322
+ if (leftMs >= IDLE_WARNING_MINUTES * 6e4) return null;
1323
+ const minutes = Math.max(0, Math.floor(leftMs / 6e4));
1324
+ return `warning: session expires in ${minutes}m (idle TTL); call a tool to extend it or \`gateway worlds session pin\` to keep it`;
1325
+ }
1326
+ var CALL_BODY_LIMIT_BYTES, CALL_BODY_LIMIT_LABEL, IDLE_WARNING_MINUTES, EXPLORATORY_TASK, EXPLORATORY_TASK_SOURCE, NO_GRADER_REASON, WorldCallTooLarge;
1327
+ var init_sessionContract = __esm({
1328
+ "src/worlds/sessionContract.ts"() {
1329
+ "use strict";
1330
+ CALL_BODY_LIMIT_BYTES = 4 * 1024 * 1024;
1331
+ CALL_BODY_LIMIT_LABEL = "4mb";
1332
+ IDLE_WARNING_MINUTES = 5;
1333
+ EXPLORATORY_TASK = Object.freeze({
1334
+ instruction: "exploratory session"
1335
+ });
1336
+ EXPLORATORY_TASK_SOURCE = "none";
1337
+ NO_GRADER_REASON = "no grader";
1338
+ WorldCallTooLarge = class extends Error {
1339
+ constructor(size, limitBytes = CALL_BODY_LIMIT_BYTES, limit = CALL_BODY_LIMIT_LABEL) {
1340
+ super(
1341
+ `call body is ${size} bytes; the platform accepts at most ${limit} (${limitBytes} bytes)`
1342
+ );
1343
+ this.size = size;
1344
+ this.limitBytes = limitBytes;
1345
+ this.limit = limit;
1346
+ this.name = "WorldCallTooLarge";
1347
+ }
1348
+ size;
1349
+ limitBytes;
1350
+ limit;
1351
+ code = "payload_too_large";
1352
+ /** The structured refusal the CLIs print. */
1353
+ toJSON() {
1354
+ return {
1355
+ status: "error",
1356
+ code: this.code,
1357
+ limit: this.limit,
1358
+ size: this.size
1359
+ };
1360
+ }
1361
+ };
1362
+ }
1363
+ });
1364
+
1365
+ // src/worlds/taskRef.ts
1366
+ var isTaskIdRef, isTaskSpec, taskLabel, assertTaskRef;
1367
+ var init_taskRef = __esm({
1368
+ "src/worlds/taskRef.ts"() {
1369
+ "use strict";
1370
+ isTaskIdRef = (task) => typeof task === "object" && task !== null && "id" in task;
1371
+ isTaskSpec = (task) => typeof task === "object" && task !== null && "instruction" in task;
1372
+ taskLabel = (task, info) => {
1373
+ if (typeof task === "string") return task;
1374
+ if (isTaskIdRef(task)) return info?.name ?? task.id;
1375
+ if (task.name) return task.name;
1376
+ return info?.hash ? `inline:${info.hash.slice(0, 12)}` : "inline";
1377
+ };
1378
+ assertTaskRef = (task) => {
1379
+ const malformed = task === null || typeof task === "string" && !task || isTaskIdRef(task) && !task.id || isTaskSpec(task) && !task.instruction || typeof task === "object" && !isTaskIdRef(task) && !isTaskSpec(task);
1380
+ if (malformed)
1381
+ throw new Error(
1382
+ "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"
1383
+ );
1384
+ };
1385
+ }
1386
+ });
1387
+
921
1388
  // src/worlds/session.ts
922
1389
  var session_exports = {};
923
1390
  __export(session_exports, {
@@ -934,6 +1401,34 @@ __export(session_exports, {
934
1401
  taskLabel: () => taskLabel
935
1402
  });
936
1403
  import { randomUUID } from "crypto";
1404
+ function numericGrade(record) {
1405
+ const rewards = {};
1406
+ const nested = record.rewards;
1407
+ if (nested && typeof nested === "object") {
1408
+ for (const [key2, value] of Object.entries(nested)) {
1409
+ if (typeof value === "number") rewards[key2] = value;
1410
+ }
1411
+ }
1412
+ for (const [key2, value] of Object.entries(record)) {
1413
+ if (key2 !== "reward" && typeof value === "number") rewards[key2] = value;
1414
+ }
1415
+ return {
1416
+ reward: typeof record.reward === "number" ? record.reward : null,
1417
+ rewards
1418
+ };
1419
+ }
1420
+ function verifierGrades(value) {
1421
+ if (!value || typeof value !== "object") return void 0;
1422
+ const out = {};
1423
+ for (const [name, grade] of Object.entries(value)) {
1424
+ const record = grade && typeof grade === "object" ? grade : {};
1425
+ out[name] = {
1426
+ ...numericGrade(record),
1427
+ ...typeof record.error === "string" ? { error: record.error } : {}
1428
+ };
1429
+ }
1430
+ return out;
1431
+ }
937
1432
  function schemaFromSignature(spec) {
938
1433
  if (spec.inputSchema)
939
1434
  return {
@@ -993,12 +1488,9 @@ async function attachSession(sessionId, options = {}) {
993
1488
  );
994
1489
  return new WorldSession(sessionId, state2, options);
995
1490
  }
996
- async function openSession(slugOrRef, taskOrOpts, positionalOpts = {}) {
997
- const { task, ...opts } = typeof taskOrOpts === "object" && "task" in taskOrOpts ? taskOrOpts : { task: taskOrOpts, ...positionalOpts };
998
- 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))
999
- throw new Error(
1000
- "openSession needs a task: a bundled task name, a stored task { id, version? } or { instruction, seed?, grader?, metadata? }"
1001
- );
1491
+ async function openSession(slugOrRef, taskOrOpts = {}, positionalOpts = {}) {
1492
+ const { task, ...opts } = isOpenSessionOptions(taskOrOpts) ? taskOrOpts : { task: taskOrOpts, ...positionalOpts };
1493
+ if (task !== void 0) assertTaskRef(task);
1002
1494
  const options = opts.options ?? {};
1003
1495
  const unknown = (opts.surfaces ?? []).filter(
1004
1496
  (s) => !SURFACE_KINDS.includes(s)
@@ -1007,6 +1499,7 @@ async function openSession(slugOrRef, taskOrOpts, positionalOpts = {}) {
1007
1499
  throw new Error(
1008
1500
  `Unknown world surfaces: ${unknown.join(", ")}; choose from ${SURFACE_KINDS.join(", ")}`
1009
1501
  );
1502
+ if (opts.browserTier !== void 0) assertBrowserTier(opts.browserTier);
1010
1503
  const at = slugOrRef.indexOf("@");
1011
1504
  const slug = at === -1 ? slugOrRef : slugOrRef.slice(0, at);
1012
1505
  const ref = at === -1 ? "" : slugOrRef.slice(at + 1);
@@ -1016,9 +1509,10 @@ async function openSession(slugOrRef, taskOrOpts, positionalOpts = {}) {
1016
1509
  "/api/public/world-sessions",
1017
1510
  {
1018
1511
  ...opts.versionId ? { versionId: opts.versionId } : { slug, ...ref && { ref } },
1019
- task,
1512
+ ...task === void 0 ? {} : { task },
1020
1513
  ...opts.reuseWarm === void 0 ? {} : { reuseWarm: opts.reuseWarm },
1021
- ...opts.surfaces?.length ? { surfaces: opts.surfaces } : {}
1514
+ ...opts.surfaces?.length ? { surfaces: opts.surfaces } : {},
1515
+ ...opts.browserTier === void 0 ? {} : { browserTier: opts.browserTier }
1022
1516
  }
1023
1517
  );
1024
1518
  return new WorldSession(state2.sessionId, state2, options);
@@ -1094,20 +1588,15 @@ async function runSessions(opts) {
1094
1588
  passed: failed === 0 && (opts.failUnder === void 0 || mean >= opts.failUnder)
1095
1589
  };
1096
1590
  }
1097
- var 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;
1591
+ var 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;
1098
1592
  var init_session = __esm({
1099
1593
  "src/worlds/session.ts"() {
1100
1594
  "use strict";
1101
1595
  init_worlds();
1102
1596
  init_browser();
1103
- isTaskIdRef = (task) => typeof task === "object" && task !== null && "id" in task;
1104
- isTaskSpec = (task) => typeof task === "object" && task !== null && "instruction" in task;
1105
- taskLabel = (task, info) => {
1106
- if (typeof task === "string") return task;
1107
- if (isTaskIdRef(task)) return info?.name ?? task.id;
1108
- if (task.name) return task.name;
1109
- return info?.hash ? `inline:${info.hash.slice(0, 12)}` : "inline";
1110
- };
1597
+ init_sessionContract();
1598
+ init_taskRef();
1599
+ init_taskRef();
1111
1600
  READY_TIMEOUT_MS = 10 * 6e4;
1112
1601
  READY_POLL_MS = 2e3;
1113
1602
  CALL_TIMEOUT_MS = 3 * 6e4;
@@ -1127,16 +1616,25 @@ var init_session = __esm({
1127
1616
  this.current = current;
1128
1617
  this.options = options;
1129
1618
  }
1619
+ sessionId;
1620
+ current;
1621
+ options;
1130
1622
  /** The task's display name: a bundled scenario's, or the inline spec's
1131
- * `name` (null when the spec was unnamed). Same as `taskName`. */
1132
- get task() {
1133
- return this.current.taskName;
1134
- }
1135
- /** The task's display name: a bundled scenario's, or the inline spec's
1136
- * `name` (null when the spec was unnamed). */
1623
+ * `name` (null when the spec was unnamed). `task` is the same. */
1137
1624
  get taskName() {
1138
1625
  return this.current.taskName;
1139
1626
  }
1627
+ get task() {
1628
+ return this.taskName;
1629
+ }
1630
+ /** `{idleExpiresAt, pinned}` as of the last state read: when the fleet
1631
+ * reaps the session (null once pinned), and whether it is pinned. */
1632
+ get idle() {
1633
+ return {
1634
+ idleExpiresAt: this.current.idleExpiresAt ?? null,
1635
+ pinned: this.current.pinned ?? false
1636
+ };
1637
+ }
1140
1638
  /** The platform's notices about the world this session runs on (empty
1141
1639
  * for a schema world). Printed by the CLI on stderr at open. */
1142
1640
  get deprecations() {
@@ -1210,23 +1708,37 @@ var init_session = __esm({
1210
1708
  const { agentId, record = true, ...rest } = opts;
1211
1709
  return openBrowser(await this.surfaces(), {
1212
1710
  ...rest,
1213
- recorder: record ? this.browserRecorder(agentId) : null
1711
+ recorder: record ? this.browserRecorder(agentId) : null,
1712
+ repair: () => this.repairBrowser()
1214
1713
  });
1215
1714
  }
1715
+ /** Ask the platform to make this session's hosted browser reachable again
1716
+ * after its connection dropped: `healthy` (reconnect now), `replaced` (a new,
1717
+ * blank browser behind the same wsUrl; reconnect and reopen your page) or
1718
+ * `starting` (ask again in `retryAfterMs`). `browser()` does this on its
1719
+ * own; call it when you drive your own Playwright against `wsUrl`. */
1720
+ async repairBrowser() {
1721
+ return apiRequest(
1722
+ this.options,
1723
+ "POST",
1724
+ `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/browser-repair`,
1725
+ {}
1726
+ );
1727
+ }
1216
1728
  /** The reporter `browser()` uses; exposed for a page you drive yourself. */
1217
1729
  browserRecorder(agentId) {
1218
- const path14 = `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/browser-events`;
1730
+ const path16 = `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/browser-events`;
1219
1731
  const id = agentId ?? process.env.GATEWAY_AGENT_ID ?? `agent-${randomUUID().replace(/-/g, "").slice(0, 8)}`;
1220
1732
  return new BrowserActionRecorder(
1221
1733
  async (events) => {
1222
- await apiRequest(this.options, "POST", path14, { events });
1734
+ await apiRequest(this.options, "POST", path16, { events });
1223
1735
  },
1224
1736
  id,
1225
1737
  {
1226
1738
  // Continue this agent's timeline where the platform has it, so the
1227
1739
  // same id reopened later never re-numbers from zero.
1228
1740
  resumeFrom: async () => {
1229
- const summary = await apiRequest(this.options, "GET", path14);
1741
+ const summary = await apiRequest(this.options, "GET", path16);
1230
1742
  return summary.agents.find((a) => a.agentId === id)?.nextSeq ?? 0;
1231
1743
  }
1232
1744
  }
@@ -1274,6 +1786,7 @@ var init_session = __esm({
1274
1786
  }
1275
1787
  /** Enqueue one interaction and wait for the container's answer. */
1276
1788
  async exchange(body, timeoutMs) {
1789
+ serializeCallBody(body);
1277
1790
  const enqueued = await apiRequest(
1278
1791
  this.options,
1279
1792
  "POST",
@@ -1345,26 +1858,25 @@ var init_session = __esm({
1345
1858
  * the judge's budget (15 min) instead of a call's. `timeoutMs` overrides
1346
1859
  * either. `report` is the agent's own account of what it did and found,
1347
1860
  * handed to the judge as its claim beside the evidence (the state and the
1348
- * calls); assertions and python graders ignore it. */
1861
+ * calls); assertions and python graders ignore it. `worlds` names the
1862
+ * task's other sessions by alias (`{alias: sessionId}`): the platform
1863
+ * reads each one's evidence and hands it to the cross-world verifiers
1864
+ * anchored on this session, whose grades come back under `verifiers`. */
1349
1865
  async grade(opts = {}) {
1350
1866
  const raw = await this.exchange(
1351
- opts.report !== void 0 ? { kind: "grade", report: opts.report } : { kind: "grade" },
1867
+ {
1868
+ kind: "grade",
1869
+ ...opts.report !== void 0 ? { report: opts.report } : {},
1870
+ ...opts.worlds && Object.keys(opts.worlds).length > 0 ? { worlds: opts.worlds } : {}
1871
+ },
1352
1872
  opts.timeoutMs
1353
1873
  );
1354
1874
  const record = raw && typeof raw === "object" ? raw : {};
1355
- const rewards = {};
1356
- const nested = record.rewards;
1357
- if (nested && typeof nested === "object") {
1358
- for (const [key2, value] of Object.entries(nested)) {
1359
- if (typeof value === "number") rewards[key2] = value;
1360
- }
1361
- }
1362
- for (const [key2, value] of Object.entries(record)) {
1363
- if (key2 !== "reward" && typeof value === "number") rewards[key2] = value;
1364
- }
1875
+ const verifiers = verifierGrades(record.verifiers);
1365
1876
  return {
1366
- reward: typeof record.reward === "number" ? record.reward : null,
1367
- rewards,
1877
+ ...numericGrade(record),
1878
+ ...typeof record.reason === "string" ? { reason: record.reason } : {},
1879
+ ...verifiers ? { verifiers } : {},
1368
1880
  raw
1369
1881
  };
1370
1882
  }
@@ -1471,6 +1983,46 @@ var init_session = __esm({
1471
1983
  );
1472
1984
  }
1473
1985
  };
1986
+ OPEN_SESSION_OPTION_KEYS = /* @__PURE__ */ new Set([
1987
+ "task",
1988
+ "versionId",
1989
+ "reuseWarm",
1990
+ "surfaces",
1991
+ "browserTier",
1992
+ "options"
1993
+ ]);
1994
+ isOpenSessionOptions = (value) => typeof value === "object" && value !== null && Object.keys(value).every((key2) => OPEN_SESSION_OPTION_KEYS.has(key2));
1995
+ }
1996
+ });
1997
+
1998
+ // src/worlds/sessionList.ts
1999
+ async function listSessions(filter = {}, options = {}) {
2000
+ const params = new URLSearchParams();
2001
+ if (filter.state) params.set("state", filter.state);
2002
+ if (filter.slug) params.set("slug", filter.slug);
2003
+ if (filter.limit !== void 0) params.set("limit", String(filter.limit));
2004
+ const qs3 = params.toString();
2005
+ const res = await apiRequest(
2006
+ options,
2007
+ "GET",
2008
+ `/api/public/world-sessions${qs3 ? `?${qs3}` : ""}`
2009
+ );
2010
+ return res.sessions;
2011
+ }
2012
+ var SESSION_STATES;
2013
+ var init_sessionList = __esm({
2014
+ "src/worlds/sessionList.ts"() {
2015
+ "use strict";
2016
+ init_worlds();
2017
+ SESSION_STATES = [
2018
+ "PROVISIONING",
2019
+ "RUNNING",
2020
+ "IDLE",
2021
+ "STOPPING",
2022
+ "STOPPED",
2023
+ "FAILED",
2024
+ "LOST"
2025
+ ];
1474
2026
  }
1475
2027
  });
1476
2028
 
@@ -1556,16 +2108,23 @@ function aggregateTaskGrade(worlds) {
1556
2108
  const rewards = {};
1557
2109
  const ungraded = [];
1558
2110
  const graded = [];
1559
- for (const [alias, grade] of Object.entries(worlds)) {
2111
+ const verifiers = {};
2112
+ const fold = (key2, grade) => {
1560
2113
  if (typeof grade.reward === "number") {
1561
- rewards[alias] = grade.reward;
2114
+ rewards[key2] = grade.reward;
1562
2115
  graded.push(grade.reward);
1563
- } else ungraded.push(alias);
1564
- for (const [key2, value] of Object.entries(grade.rewards))
1565
- rewards[`${alias}.${key2}`] = value;
2116
+ } else ungraded.push(key2);
2117
+ for (const [name, value] of Object.entries(grade.rewards))
2118
+ rewards[`${key2}.${name}`] = value;
2119
+ };
2120
+ for (const [alias, grade] of Object.entries(worlds)) {
2121
+ fold(alias, grade);
2122
+ Object.assign(verifiers, grade.verifiers ?? {});
1566
2123
  }
2124
+ for (const [name, grade] of Object.entries(verifiers))
2125
+ fold(`${VERIFIER_REWARD_PREFIX}${name}`, grade);
1567
2126
  const reward = graded.length > 0 ? graded.reduce((a, b) => a + b, 0) / graded.length : null;
1568
- return { reward, rewards, worlds, ungraded };
2127
+ return { reward, rewards, worlds, ungraded, verifiers };
1569
2128
  }
1570
2129
  function fromResponse(answer, options) {
1571
2130
  const sessions2 = {};
@@ -1598,6 +2157,7 @@ async function openTask(ref, opts = {}) {
1598
2157
  throw new Error(
1599
2158
  "openTask needs a spec that names its worlds; a single-world spec opens with openSession"
1600
2159
  );
2160
+ if (opts.browserTier !== void 0) assertBrowserTier(opts.browserTier);
1601
2161
  const answer = await apiRequest(
1602
2162
  options,
1603
2163
  "POST",
@@ -1605,7 +2165,8 @@ async function openTask(ref, opts = {}) {
1605
2165
  {
1606
2166
  task,
1607
2167
  ...opts.reuseWarm === void 0 ? {} : { reuseWarm: opts.reuseWarm },
1608
- ...opts.surfaces?.length ? { surfaces: opts.surfaces } : {}
2168
+ ...opts.surfaces?.length ? { surfaces: opts.surfaces } : {},
2169
+ ...opts.browserTier === void 0 ? {} : { browserTier: opts.browserTier }
1609
2170
  }
1610
2171
  );
1611
2172
  return fromResponse(answer, options);
@@ -1681,7 +2242,7 @@ async function attachManifest(manifest, options = {}) {
1681
2242
  function isTaskManifest(value) {
1682
2243
  return typeof value === "object" && value !== null && !Array.isArray(value) && typeof value.sessions === "object" && value.sessions !== null && !("instruction" in value && "worlds" in value);
1683
2244
  }
1684
- var TASK_SESSIONS, manifestSession, TaskSessions;
2245
+ var TASK_SESSIONS, VERIFIER_REWARD_PREFIX, manifestSession, TaskSessions;
1685
2246
  var init_taskSessions = __esm({
1686
2247
  "src/worlds/taskSessions.ts"() {
1687
2248
  "use strict";
@@ -1689,6 +2250,7 @@ var init_taskSessions = __esm({
1689
2250
  init_browser();
1690
2251
  init_session();
1691
2252
  TASK_SESSIONS = "/api/public/world-task-sessions";
2253
+ VERIFIER_REWARD_PREFIX = "x.";
1692
2254
  manifestSession = (s, state2, world) => ({
1693
2255
  slug: world.slug,
1694
2256
  ref: world.ref,
@@ -1719,6 +2281,13 @@ var init_taskSessions = __esm({
1719
2281
  this.worlds = worlds;
1720
2282
  this.hash = hash;
1721
2283
  }
2284
+ taskId;
2285
+ taskVersion;
2286
+ name;
2287
+ instruction;
2288
+ sessions;
2289
+ worlds;
2290
+ hash;
1722
2291
  /** This alias's `{slug, ref}` as recorded at open/attach — the world a
1723
2292
  * `TaskRun` filing needs to name, without exposing the whole map. */
1724
2293
  worldRef(alias) {
@@ -1778,10 +2347,20 @@ var init_taskSessions = __esm({
1778
2347
  }
1779
2348
  /** Grade every world and aggregate — see `TaskGrade`. One `report` (the
1780
2349
  * agent's own account of the whole investigation) goes to every world's
1781
- * judge; a world graded by assertions or python ignores it. */
2350
+ * judge; a world graded by assertions or python ignores it. Each grade
2351
+ * names the task's other sessions by alias, so the cross-world verifiers
2352
+ * anchored on that world can read them. */
1782
2353
  async grade(opts = {}) {
1783
2354
  return aggregateTaskGrade(
1784
- await this.each((session) => session.grade(opts))
2355
+ await this.each(
2356
+ (session, alias) => session.grade({ ...opts, worlds: this.otherSessions(alias) })
2357
+ )
2358
+ );
2359
+ }
2360
+ /** The task's other sessions by alias: what a grade names. */
2361
+ otherSessions(alias) {
2362
+ return Object.fromEntries(
2363
+ Object.entries(this.sessions).filter(([other]) => other !== alias).map(([other, session]) => [other, session.sessionId])
1785
2364
  );
1786
2365
  }
1787
2366
  /** Every world's call log, keyed by alias. */
@@ -1827,10 +2406,11 @@ var init_evals = __esm({
1827
2406
  constructor(options = {}) {
1828
2407
  this.options = options;
1829
2408
  }
1830
- /** Anchor a new evaluation to `versionId`; returns its id. */
2409
+ options;
1831
2410
  async createEvaluation(versionId, opts = {}) {
1832
2411
  const body = { versionId };
1833
2412
  if (opts.model !== void 0) body.model = opts.model;
2413
+ if (opts.runId !== void 0) body.runId = opts.runId;
1834
2414
  if (opts.rolloutsPerExample !== void 0)
1835
2415
  body.rolloutsPerExample = opts.rolloutsPerExample;
1836
2416
  if (opts.metadata !== void 0) body.metadata = opts.metadata;
@@ -1842,7 +2422,6 @@ var init_evals = __esm({
1842
2422
  );
1843
2423
  return answer.evaluationId;
1844
2424
  }
1845
- /** Push one batch of samples; returns how many the platform inserted. */
1846
2425
  async pushSamples(evaluationId, samples) {
1847
2426
  const answer = await apiRequest(
1848
2427
  this.options,
@@ -1852,7 +2431,6 @@ var init_evals = __esm({
1852
2431
  );
1853
2432
  return answer.inserted ?? samples.length;
1854
2433
  }
1855
- /** Close the evaluation out; returns its final status. */
1856
2434
  async finalizeEvaluation(evaluationId, opts = {}) {
1857
2435
  const body = {
1858
2436
  status: opts.status ?? "COMPLETED"
@@ -1955,9 +2533,9 @@ function getAmbientSessionId() {
1955
2533
  return currentSessionStorage.getStore();
1956
2534
  }
1957
2535
  function withSession(sessionId, fn) {
1958
- return new Promise((resolve10, reject) => {
2536
+ return new Promise((resolve11, reject) => {
1959
2537
  currentSessionStorage.run(sessionId, () => {
1960
- Promise.resolve().then(fn).then(resolve10, reject);
2538
+ Promise.resolve().then(fn).then(resolve11, reject);
1961
2539
  });
1962
2540
  });
1963
2541
  }
@@ -1989,7 +2567,7 @@ var require_package = __commonJS({
1989
2567
  "package.json"(exports, module) {
1990
2568
  module.exports = {
1991
2569
  name: "@withgateway/sdk",
1992
- version: "0.2.6",
2570
+ version: "0.2.9",
1993
2571
  description: "Gateway SDK for TypeScript - A/B experiments, tracing, and observability",
1994
2572
  main: "./dist/index.js",
1995
2573
  module: "./dist/index.mjs",
@@ -2144,16 +2722,16 @@ var require_package = __commonJS({
2144
2722
  }
2145
2723
  },
2146
2724
  optionalDependencies: {
2147
- "@arizeai/openinference-instrumentation-anthropic": "^0.1.15",
2148
- "@arizeai/openinference-instrumentation-openai": "^4.1.5"
2725
+ "@arizeai/openinference-instrumentation-anthropic": "^0.2.8",
2726
+ "@arizeai/openinference-instrumentation-openai": "^4.2.7"
2149
2727
  },
2150
2728
  devDependencies: {
2151
- "@anthropic-ai/sdk": "^0.79.0",
2729
+ "@anthropic-ai/sdk": "^0.91.1",
2152
2730
  "@opentelemetry/api": "^1.9.0",
2153
- "@opentelemetry/exporter-trace-otlp-http": "^0.212.0",
2154
- "@opentelemetry/resources": "^2.6.0",
2155
- "@opentelemetry/sdk-trace-base": "^1.30.1",
2156
- "@opentelemetry/sdk-trace-node": "^2.6.0",
2731
+ "@opentelemetry/exporter-trace-otlp-http": "^0.222.0",
2732
+ "@opentelemetry/resources": "^2.11.0",
2733
+ "@opentelemetry/sdk-trace-base": "^2.11.0",
2734
+ "@opentelemetry/sdk-trace-node": "^2.11.0",
2157
2735
  "@opentelemetry/semantic-conventions": "^1.40.0",
2158
2736
  "@types/node": "^20.0.0",
2159
2737
  openai: "^4.70.0",
@@ -2166,7 +2744,9 @@ var require_package = __commonJS({
2166
2744
  protobufjs: "^8.4.1",
2167
2745
  "vite@6": "^6.4.3",
2168
2746
  postcss: "^8.5.18",
2169
- "picomatch@4": "^4.0.4"
2747
+ "picomatch@4": "^4.0.4",
2748
+ nanoid: ">=3.3.18",
2749
+ esbuild: ">=0.28.1"
2170
2750
  },
2171
2751
  pnpm: {
2172
2752
  overrides: {
@@ -2174,7 +2754,9 @@ var require_package = __commonJS({
2174
2754
  vitest: "^3.2.6",
2175
2755
  "vite@6": "^6.4.3",
2176
2756
  postcss: "^8.5.18",
2177
- "picomatch@4": "^4.0.4"
2757
+ "picomatch@4": "^4.0.4",
2758
+ nanoid: ">=3.3.18",
2759
+ esbuild: ">=0.28.1"
2178
2760
  }
2179
2761
  },
2180
2762
  bin: {
@@ -2780,7 +3362,7 @@ function worldRef(live, alias) {
2780
3362
  sessionId: session.sessionId
2781
3363
  };
2782
3364
  }
2783
- async function fileTaskRun(live, runId, model, report, grade, agentError, traced, runDir, options) {
3365
+ async function fileTaskRun(live, runId, model, report, grade, agentError, traced, runDir, options, setRunId) {
2784
3366
  const aliases = live.aliases;
2785
3367
  const anchor = aliases[0];
2786
3368
  const worldsMeta = Object.fromEntries(
@@ -2792,6 +3374,7 @@ async function fileTaskRun(live, runId, model, report, grade, agentError, traced
2792
3374
  {
2793
3375
  model,
2794
3376
  rolloutsPerExample: 1,
3377
+ ...setRunId ? { runId: setRunId } : {},
2795
3378
  metadata: {
2796
3379
  source: "worlds-task-run",
2797
3380
  task: {
@@ -2874,6 +3457,7 @@ async function runTask(ref, agent, opts) {
2874
3457
  const live = await openTask(ref, {
2875
3458
  surfaces: opts.surfaces,
2876
3459
  reuseWarm: opts.reuseWarm,
3460
+ browserTier: opts.browserTier,
2877
3461
  options
2878
3462
  });
2879
3463
  const started = Date.now();
@@ -2909,6 +3493,8 @@ async function runTask(ref, agent, opts) {
2909
3493
  const message = (error instanceof Error ? error.message : String(error)) || "Unknown error";
2910
3494
  agentError = message.slice(0, 2e3);
2911
3495
  }
3496
+ if (traced)
3497
+ await Promise.resolve().then(() => (init_init(), init_exports)).then((tracing2) => tracing2.flush()).catch(() => void 0);
2912
3498
  const grade = report !== null ? await live.grade({ report }) : await live.grade();
2913
3499
  fs.writeFileSync(
2914
3500
  path.join(runDir, "manifest.json"),
@@ -2949,7 +3535,8 @@ async function runTask(ref, agent, opts) {
2949
3535
  agentError,
2950
3536
  traced,
2951
3537
  runDir,
2952
- options
3538
+ options,
3539
+ opts.setRunId
2953
3540
  );
2954
3541
  summary.filed = true;
2955
3542
  }
@@ -2983,8 +3570,12 @@ var init_taskRun = __esm({
2983
3570
  this.sessions = sessions2;
2984
3571
  this.manifest = manifest;
2985
3572
  }
3573
+ runId;
3574
+ instruction;
3575
+ model;
3576
+ sessions;
3577
+ manifest;
2986
3578
  notes = {};
2987
- /** The alias's session, or a clear error naming the aliases there are. */
2988
3579
  session(alias) {
2989
3580
  const session = this.sessions[alias];
2990
3581
  if (!session)
@@ -2993,8 +3584,7 @@ var init_taskRun = __esm({
2993
3584
  );
2994
3585
  return session;
2995
3586
  }
2996
- /** `alias`'s HTTP API. Raises the same error the session itself would
2997
- * when it was not opened with `surfaces: ["api"]`. */
3587
+ /** Raises when the session was not opened with `surfaces: ["api"]`. */
2998
3588
  async api(alias) {
2999
3589
  const surfaces = await this.session(alias).surfaces();
3000
3590
  if (!surfaces.api)
@@ -3004,10 +3594,7 @@ var init_taskRun = __esm({
3004
3594
  );
3005
3595
  return { url: surfaces.api.url, token: surfaces.api.token };
3006
3596
  }
3007
- /** Every world's tools merged into one toolkit, each name prefixed
3008
- * `<alias>.<tool>` so a model can tell which world a call goes to. A
3009
- * world that exposes no tools contributes nothing — there is nothing to
3010
- * merge. */
3597
+ /** Each tool is prefixed `<alias>.<tool>` so a model can tell which world a call goes to. */
3011
3598
  async toolkit() {
3012
3599
  const schemas = [];
3013
3600
  const impls = {};
@@ -3032,8 +3619,7 @@ var init_taskRun = __esm({
3032
3619
  }
3033
3620
  return { schemas, impls, specs };
3034
3621
  }
3035
- /** Log arbitrary notes into this run's `run.json` (merged; a later call
3036
- * overrides a key an earlier one set). */
3622
+ /** Merged into `run.json` under `notes`; a later call overrides an earlier key. */
3037
3623
  record(notes) {
3038
3624
  Object.assign(this.notes, notes);
3039
3625
  }
@@ -3043,11 +3629,250 @@ var init_taskRun = __esm({
3043
3629
  }
3044
3630
  });
3045
3631
 
3046
- // src/worlds/worldDir.ts
3047
- import { createHash as createHash3 } from "crypto";
3632
+ // src/worlds/checkoutProvenance.ts
3633
+ import { execFileSync } from "child_process";
3634
+ var CheckoutProvenance;
3635
+ var init_checkoutProvenance = __esm({
3636
+ "src/worlds/checkoutProvenance.ts"() {
3637
+ "use strict";
3638
+ CheckoutProvenance = class _CheckoutProvenance {
3639
+ constructor(cwd, env) {
3640
+ this.cwd = cwd;
3641
+ this.env = env;
3642
+ }
3643
+ cwd;
3644
+ env;
3645
+ static read(cwd = process.cwd(), env = process.env) {
3646
+ return new _CheckoutProvenance(cwd, env).checkout();
3647
+ }
3648
+ checkout() {
3649
+ const commit = this.git("rev-parse", "HEAD");
3650
+ if (!commit) return this.withPr({});
3651
+ const branch = this.env.GITHUB_HEAD_REF || this.git("rev-parse", "--abbrev-ref", "HEAD");
3652
+ const remote = this.git("config", "--get", "remote.origin.url");
3653
+ return this.withPr({
3654
+ commit,
3655
+ ...branch && branch !== "HEAD" ? { branch } : {},
3656
+ ...remote ? { repoUrl: _CheckoutProvenance.withoutCredentials(remote) } : {}
3657
+ });
3658
+ }
3659
+ /** Security: credentials are stripped; scp-style `git@host:org/repo` has none and is kept. */
3660
+ static withoutCredentials(url) {
3661
+ return url.replace(/^([a-z][a-z0-9+.-]*:\/\/)[^@/]+@/i, "$1");
3662
+ }
3663
+ withPr(checkout) {
3664
+ const pr = this.pullRequest();
3665
+ return pr ? { ...checkout, pr } : checkout;
3666
+ }
3667
+ pullRequest() {
3668
+ const url = this.env.GATEWAY_PR_URL;
3669
+ const fromUrl = url ? /\/pull\/(\d+)/.exec(url)?.[1] : void 0;
3670
+ if (url && fromUrl)
3671
+ return {
3672
+ number: Number(fromUrl),
3673
+ url,
3674
+ ...this.env.GATEWAY_PR_TITLE ? { title: this.env.GATEWAY_PR_TITLE } : {}
3675
+ };
3676
+ const number = /^refs\/pull\/(\d+)\//.exec(this.env.GITHUB_REF ?? "")?.[1];
3677
+ const server = this.env.GITHUB_SERVER_URL;
3678
+ const repo = this.env.GITHUB_REPOSITORY;
3679
+ if (!number || !server || !repo) return void 0;
3680
+ return { number: Number(number), url: `${server}/${repo}/pull/${number}` };
3681
+ }
3682
+ git(...args) {
3683
+ try {
3684
+ const out = execFileSync("git", args, {
3685
+ cwd: this.cwd,
3686
+ stdio: ["ignore", "pipe", "ignore"],
3687
+ timeout: 5e3
3688
+ }).toString().trim();
3689
+ return out || void 0;
3690
+ } catch {
3691
+ return void 0;
3692
+ }
3693
+ }
3694
+ };
3695
+ }
3696
+ });
3697
+
3698
+ // src/worlds/setRun.ts
3699
+ async function runSet(datasetId, agent, opts) {
3700
+ const options = opts.options ?? {};
3701
+ const git = opts.git === void 0 ? CheckoutProvenance.read() : opts.git;
3702
+ const opened = await apiRequest(options, "POST", SET_RUNS, {
3703
+ datasetId,
3704
+ model: opts.model,
3705
+ source: opts.source ?? "sdk",
3706
+ ...git && Object.keys(git).length ? { git } : {}
3707
+ });
3708
+ const close = (status) => apiRequest(
3709
+ options,
3710
+ "POST",
3711
+ `${SET_RUNS}/${encodeURIComponent(opened.id)}/close`,
3712
+ { status }
3713
+ );
3714
+ const onInterrupt = () => {
3715
+ void close("failed").finally(() => process.exit(130));
3716
+ };
3717
+ process.once("SIGINT", onInterrupt);
3718
+ const planned = await runPlannedTasks(opened, agent, opts, options).finally(
3719
+ () => process.off("SIGINT", onInterrupt)
3720
+ );
3721
+ const { tasks, failed } = planned;
3722
+ const requested = failed ? "failed" : "completed";
3723
+ const setRun = await close(requested);
3724
+ return {
3725
+ setRun,
3726
+ tasks,
3727
+ failed: failed || setRun.status !== "completed",
3728
+ closedAsRequested: setRun.status === requested
3729
+ };
3730
+ }
3731
+ async function runPlannedTasks(opened, agent, opts, options) {
3732
+ const tasks = [];
3733
+ let failed = false;
3734
+ for (const task of opened.tasks) {
3735
+ try {
3736
+ const summary = await runTask(task.worldTaskId, agent, {
3737
+ model: opts.model,
3738
+ surfaces: opts.surfaces,
3739
+ browserTier: opts.browserTier,
3740
+ outDir: opts.outDir,
3741
+ trace: opts.trace,
3742
+ setRunId: opened.id,
3743
+ options
3744
+ });
3745
+ tasks.push(summary);
3746
+ failed ||= summary.agentError !== null;
3747
+ opts.onTask?.(summary);
3748
+ } catch (error) {
3749
+ failed = true;
3750
+ const message = error instanceof Error ? error.message : String(error);
3751
+ process.stderr.write(`task ${task.name} could not run: ${message}
3752
+ `);
3753
+ }
3754
+ }
3755
+ return { tasks, failed };
3756
+ }
3757
+ var SET_RUNS;
3758
+ var init_setRun = __esm({
3759
+ "src/worlds/setRun.ts"() {
3760
+ "use strict";
3761
+ init_worlds();
3762
+ init_checkoutProvenance();
3763
+ init_taskRun();
3764
+ SET_RUNS = "/api/public/set-runs";
3765
+ }
3766
+ });
3767
+
3768
+ // src/worlds/checkoutTarget.ts
3048
3769
  import * as fs2 from "fs";
3049
3770
  import * as path2 from "path";
3050
- var 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;
3771
+ var CheckoutRefusedError, NAMED_EDITS, CheckoutTarget;
3772
+ var init_checkoutTarget = __esm({
3773
+ "src/worlds/checkoutTarget.ts"() {
3774
+ "use strict";
3775
+ CheckoutRefusedError = class extends Error {
3776
+ constructor(message) {
3777
+ super(`checkout refused: ${message}`);
3778
+ this.name = "CheckoutRefusedError";
3779
+ }
3780
+ };
3781
+ NAMED_EDITS = 3;
3782
+ CheckoutTarget = class _CheckoutTarget {
3783
+ constructor(dir, replaces) {
3784
+ this.dir = dir;
3785
+ this.replaces = replaces;
3786
+ }
3787
+ dir;
3788
+ replaces;
3789
+ static resolve(slug, target, opts) {
3790
+ if (target === void 0) return _CheckoutTarget.fresh(slug, opts.cwd);
3791
+ return _CheckoutTarget.explicit(
3792
+ _CheckoutTarget.confined(target, opts.cwd),
3793
+ slug,
3794
+ opts
3795
+ );
3796
+ }
3797
+ /** The absolute destination; a relative target may not resolve above `cwd`. */
3798
+ static confined(target, cwd) {
3799
+ const dir = path2.resolve(cwd, target);
3800
+ if (path2.isAbsolute(target)) return dir;
3801
+ const rel = path2.relative(cwd, dir);
3802
+ if (rel === "" || !rel.startsWith("..") && !path2.isAbsolute(rel))
3803
+ return dir;
3804
+ throw new CheckoutRefusedError(
3805
+ `--target ${target} resolves outside the current directory (${cwd}) \u2014 run from that directory, or pass an absolute path`
3806
+ );
3807
+ }
3808
+ static fresh(slug, cwd) {
3809
+ const base = path2.join(cwd, slug);
3810
+ let dir = base;
3811
+ let i = 1;
3812
+ while (fs2.existsSync(dir)) dir = `${base}-${i++}`;
3813
+ return new _CheckoutTarget(dir, []);
3814
+ }
3815
+ static explicit(dir, slug, opts) {
3816
+ if (!fs2.existsSync(dir)) return new _CheckoutTarget(dir, []);
3817
+ if (!fs2.statSync(dir).isDirectory())
3818
+ throw new CheckoutRefusedError(`${dir} is a file`);
3819
+ if (fs2.readdirSync(dir).length === 0) return new _CheckoutTarget(dir, []);
3820
+ const state2 = opts.state(dir);
3821
+ const refusal = _CheckoutTarget.refusal(dir, slug, state2);
3822
+ if (refusal === null || opts.force)
3823
+ return new _CheckoutTarget(dir, _CheckoutTarget.tracked(state2));
3824
+ throw new CheckoutRefusedError(refusal);
3825
+ }
3826
+ /** Base files plus local edits — everything the archive would see in the old
3827
+ * checkout. `.env-metadata.json` is local input: a key that would leave the
3828
+ * checkout (`../x`, `/etc/x`) is dropped, never removed. */
3829
+ static tracked(state2) {
3830
+ if (!state2.meta?.baseFiles) return [];
3831
+ return [
3832
+ .../* @__PURE__ */ new Set([...Object.keys(state2.meta.baseFiles), ...state2.dirty])
3833
+ ].filter(_CheckoutTarget.confinedRel).sort();
3834
+ }
3835
+ static confinedRel(rel) {
3836
+ if (rel === "" || path2.isAbsolute(rel)) return false;
3837
+ return !rel.split(/[\\/]/).includes("..");
3838
+ }
3839
+ /** Why `dir` cannot be overwritten, or null when it is a clean checkout of `slug`. */
3840
+ static refusal(dir, slug, state2) {
3841
+ if (!state2.meta?.baseFiles)
3842
+ return `${dir} is not empty and is not a checkout of "${slug}" \u2014 pick an empty --target, or pass --force to overwrite it`;
3843
+ if (state2.meta.slug !== void 0 && state2.meta.slug !== slug)
3844
+ return `${dir} tracks "${state2.meta.slug}", not "${slug}" \u2014 pick another --target, or pass --force to replace it`;
3845
+ if (state2.clean) return null;
3846
+ const n = state2.dirty.length;
3847
+ const named = state2.dirty.slice(0, NAMED_EDITS).join(", ");
3848
+ const more = n > NAMED_EDITS ? `, +${n - NAMED_EDITS} more` : "";
3849
+ 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`;
3850
+ }
3851
+ /** Remove the replaced checkout's files (and the dirs they leave empty). */
3852
+ clear() {
3853
+ for (const rel of this.replaces) {
3854
+ const abs = path2.join(this.dir, rel);
3855
+ fs2.rmSync(abs, { force: true });
3856
+ this.pruneEmptyParents(path2.dirname(abs));
3857
+ }
3858
+ }
3859
+ pruneEmptyParents(from) {
3860
+ let cur = from;
3861
+ while (cur !== this.dir && cur.startsWith(this.dir)) {
3862
+ if (fs2.existsSync(cur) && fs2.readdirSync(cur).length > 0) return;
3863
+ fs2.rmSync(cur, { recursive: true, force: true });
3864
+ cur = path2.dirname(cur);
3865
+ }
3866
+ }
3867
+ };
3868
+ }
3869
+ });
3870
+
3871
+ // src/worlds/worldDir.ts
3872
+ import { createHash as createHash3 } from "crypto";
3873
+ import * as fs3 from "fs";
3874
+ import * as path3 from "path";
3875
+ var WORLD_MANIFEST, API_BUNDLE_MANIFEST, BUNDLED_WORLD_PREFIX, CONNECTOR_SPEC, PYPROJECT, BENCHMARK_CONFIG, WORLD_SCHEMA_MARKERS, WORLD_ROOT_MARKERS, BROAD_ROOT_MARKERS, SKIPPED_DIRS, V1_DEP, V1_IMPORT, V1_TASKSET, HARBOR_TASK, skippedDir, byCodePoint, WorldDir;
3051
3876
  var init_worldDir = __esm({
3052
3877
  "src/worlds/worldDir.ts"() {
3053
3878
  "use strict";
@@ -3056,10 +3881,11 @@ var init_worldDir = __esm({
3056
3881
  BUNDLED_WORLD_PREFIX = "server/world/";
3057
3882
  CONNECTOR_SPEC = "connector.toml";
3058
3883
  PYPROJECT = "pyproject.toml";
3884
+ BENCHMARK_CONFIG = "benchmark.json";
3059
3885
  WORLD_SCHEMA_MARKERS = ["schema/world.json", "schema/runtime.json", "schema/lock.json"];
3060
3886
  WORLD_ROOT_MARKERS = [CONNECTOR_SPEC, ...WORLD_SCHEMA_MARKERS];
3061
- BROAD_ROOT_MARKERS = [WORLD_MANIFEST, API_BUNDLE_MANIFEST];
3062
- SKIPPED_DIRS = /* @__PURE__ */ new Set(["dist", "build", "outputs", "__pycache__"]);
3887
+ BROAD_ROOT_MARKERS = [WORLD_MANIFEST, API_BUNDLE_MANIFEST, BENCHMARK_CONFIG];
3888
+ SKIPPED_DIRS = /* @__PURE__ */ new Set(["dist", "build", "outputs", "__pycache__", "node_modules"]);
3063
3889
  V1_DEP = /["']verifiers\s*(?:\[[^\]]*\])?\s*(?:>=|~=|==|>)\s*(?:0\.(?:[2-9]\d*|[1-9]\d+)|[1-9]\d*)/;
3064
3890
  V1_IMPORT = /^\s*(?:from\s+verifiers\.v1\s+import\b|from\s+verifiers\s+import\s+v1\b|import\s+verifiers\.v1\b)/m;
3065
3891
  V1_TASKSET = /class\s+\w+\s*\(\s*(?:(?:vf|v1|verifiers(?:\.v1)?)\.)?Taskset\s*[,)]/;
@@ -3071,19 +3897,21 @@ var init_worldDir = __esm({
3071
3897
  this.dir = dir;
3072
3898
  this.worldRoot = worldRoot;
3073
3899
  }
3900
+ dir;
3901
+ worldRoot;
3074
3902
  pathsMemo;
3075
3903
  static open(dir) {
3076
- const present = (rel) => fs2.existsSync(path2.join(dir, rel));
3904
+ const present = (rel) => fs3.existsSync(path3.join(dir, rel));
3077
3905
  const bundled = present(API_BUNDLE_MANIFEST) && WORLD_ROOT_MARKERS.some((m) => present(BUNDLED_WORLD_PREFIX + m));
3078
3906
  return new _WorldDir(dir, bundled ? BUNDLED_WORLD_PREFIX : "");
3079
3907
  }
3080
3908
  // ── Files ──────────────────────────────────────────────────────────────
3081
3909
  has(rel) {
3082
- return fs2.existsSync(path2.join(this.dir, rel));
3910
+ return fs3.existsSync(path3.join(this.dir, rel));
3083
3911
  }
3084
3912
  text(rel) {
3085
3913
  try {
3086
- return fs2.readFileSync(path2.join(this.dir, rel), "utf-8");
3914
+ return fs3.readFileSync(path3.join(this.dir, rel), "utf-8");
3087
3915
  } catch {
3088
3916
  return null;
3089
3917
  }
@@ -3093,20 +3921,21 @@ var init_worldDir = __esm({
3093
3921
  return this.worldRoot + rel;
3094
3922
  }
3095
3923
  /** Every regular file the archive rules keep (`_archive.py`: no hidden,
3096
- * dist, build, outputs, pycache or egg-info directories), as sorted
3097
- * relpaths. Root files enter only when a Gateway manifest widens the root
3098
- * or they are README.md, pyproject.toml or Python. */
3924
+ * dist, build, outputs, pycache, node_modules or egg-info directories), as
3925
+ * sorted relpaths. Root files enter only when a Gateway manifest or
3926
+ * benchmark.json widens the root, or they are README.md, pyproject.toml or
3927
+ * Python. */
3099
3928
  get archivePaths() {
3100
3929
  if (this.pathsMemo) return this.pathsMemo;
3101
3930
  const broad = BROAD_ROOT_MARKERS.some((m) => this.has(m));
3102
3931
  const out = [];
3103
3932
  const walk = (rel) => {
3104
- for (const entry of fs2.readdirSync(rel ? path2.join(this.dir, rel) : this.dir, { withFileTypes: true })) {
3933
+ for (const entry of fs3.readdirSync(rel ? path3.join(this.dir, rel) : this.dir, { withFileTypes: true })) {
3105
3934
  const child = rel ? `${rel}/${entry.name}` : entry.name;
3106
3935
  if (entry.isDirectory()) {
3107
3936
  if (!skippedDir(entry.name)) walk(child);
3108
3937
  } else if (entry.isFile() && !entry.name.startsWith(".")) {
3109
- const rootKept = broad || ["README.md", PYPROJECT].includes(entry.name) || entry.name.endsWith(".py");
3938
+ const rootKept = broad || ["README.md", PYPROJECT, ...BROAD_ROOT_MARKERS].includes(entry.name) || entry.name.endsWith(".py");
3110
3939
  if (rel || rootKept) out.push(child);
3111
3940
  }
3112
3941
  }
@@ -3114,6 +3943,33 @@ var init_worldDir = __esm({
3114
3943
  walk("");
3115
3944
  return this.pathsMemo = out.sort(byCodePoint);
3116
3945
  }
3946
+ /** What the archive rules leave out, collapsed to the entry that decided
3947
+ * it: a pruned directory counts its files once, a dropped root file is
3948
+ * named. Dot entries (`.git/`, `.gateway/`, `.gitignore`) are the one
3949
+ * universal convention and stay unreported. `push` prints the rest so
3950
+ * nothing disappears silently. */
3951
+ get exclusions() {
3952
+ const kept = new Set(this.archivePaths);
3953
+ const out = [];
3954
+ const filesUnder = (rel) => fs3.readdirSync(path3.join(this.dir, rel), { withFileTypes: true }).flatMap((entry) => {
3955
+ const child = `${rel}/${entry.name}`;
3956
+ if (entry.isDirectory()) return filesUnder(child);
3957
+ return entry.isFile() ? [child] : [];
3958
+ });
3959
+ for (const entry of fs3.readdirSync(this.dir, { withFileTypes: true }).sort((a, b) => byCodePoint(a.name, b.name))) {
3960
+ if (entry.name.startsWith(".")) continue;
3961
+ if (entry.isDirectory()) {
3962
+ const all = filesUnder(entry.name);
3963
+ const missing = all.filter((rel) => !kept.has(rel));
3964
+ if (missing.length === 0) continue;
3965
+ const whole = missing.length === all.length;
3966
+ out.push(...whole ? [{ path: `${entry.name}/`, files: missing.length }] : missing.map((p) => ({ path: p, files: 1 })));
3967
+ continue;
3968
+ }
3969
+ if (!kept.has(entry.name)) out.push({ path: entry.name, files: 1 });
3970
+ }
3971
+ return out;
3972
+ }
3117
3973
  /** A root `.gitignore` is present: the Python SDK honours it when
3118
3974
  * collecting, this package does not reimplement gitignore. */
3119
3975
  get hasRootGitignore() {
@@ -3126,7 +3982,7 @@ var init_worldDir = __esm({
3126
3982
  const hasher = createHash3("sha256");
3127
3983
  for (const rel of this.archivePaths) {
3128
3984
  hasher.update(Buffer.from(`file:${rel}`, "utf-8"));
3129
- hasher.update(fs2.readFileSync(path2.join(this.dir, rel)));
3985
+ hasher.update(fs3.readFileSync(path3.join(this.dir, rel)));
3130
3986
  }
3131
3987
  return hasher.digest("hex");
3132
3988
  }
@@ -3189,14 +4045,121 @@ var init_worldDir = __esm({
3189
4045
  }
3190
4046
  });
3191
4047
 
4048
+ // src/worlds/tar.ts
4049
+ import * as fs4 from "fs";
4050
+ import * as path4 from "path";
4051
+ import { gunzipSync } from "zlib";
4052
+ function archiveMode(mode) {
4053
+ return (mode & 73) !== 0 ? TAR_EXEC_MODE : TAR_FILE_MODE;
4054
+ }
4055
+ function field(header, start, end) {
4056
+ return header.subarray(start, end).toString("utf-8").replace(/\0.*$/, "");
4057
+ }
4058
+ function octalField(header, start, end) {
4059
+ return parseInt(field(header, start, end).trim(), 8);
4060
+ }
4061
+ function paxPath(body) {
4062
+ let off = 0;
4063
+ let found = null;
4064
+ while (off < body.length) {
4065
+ const sp = body.indexOf(32, off);
4066
+ if (sp === -1) break;
4067
+ const len = parseInt(body.subarray(off, sp).toString("ascii"), 10);
4068
+ if (!Number.isFinite(len) || len <= 0) break;
4069
+ const record = body.subarray(sp + 1, off + len);
4070
+ const eq = record.indexOf(61);
4071
+ const key2 = eq === -1 ? "" : record.subarray(0, eq).toString("utf-8");
4072
+ if (key2 === "path")
4073
+ found = record.subarray(eq + 1).toString("utf-8").replace(/\n$/, "");
4074
+ off += len;
4075
+ }
4076
+ return found;
4077
+ }
4078
+ var TAR_FILE_MODE, TAR_EXEC_MODE, TarArchive;
4079
+ var init_tar = __esm({
4080
+ "src/worlds/tar.ts"() {
4081
+ "use strict";
4082
+ TAR_FILE_MODE = 420;
4083
+ TAR_EXEC_MODE = 493;
4084
+ TarArchive = class _TarArchive {
4085
+ constructor(tar) {
4086
+ this.tar = tar;
4087
+ }
4088
+ tar;
4089
+ static fromGzip(bundle) {
4090
+ return new _TarArchive(gunzipSync(bundle));
4091
+ }
4092
+ static fromTar(tar) {
4093
+ return new _TarArchive(tar);
4094
+ }
4095
+ /** Every member, names fully resolved; metadata members are consumed. */
4096
+ *members() {
4097
+ const tar = this.tar;
4098
+ let offset = 0;
4099
+ let pendingName = null;
4100
+ while (offset + 512 <= tar.length) {
4101
+ const header = tar.subarray(offset, offset + 512);
4102
+ offset += 512;
4103
+ if (header.every((b) => b === 0)) break;
4104
+ const size = octalField(header, 124, 136) || 0;
4105
+ const mode = octalField(header, 100, 108) || TAR_FILE_MODE;
4106
+ const typeflag = String.fromCharCode(header[156] ?? 0);
4107
+ const bytes = tar.subarray(offset, offset + size);
4108
+ offset += Math.ceil(size / 512) * 512;
4109
+ if (typeflag === "L") {
4110
+ pendingName = bytes.toString("utf-8").replace(/\0.*$/, "");
4111
+ continue;
4112
+ }
4113
+ if (typeflag === "x") {
4114
+ pendingName = paxPath(bytes) ?? pendingName;
4115
+ continue;
4116
+ }
4117
+ if (typeflag === "K" || typeflag === "g") continue;
4118
+ const name = pendingName ?? _TarArchive.ustarName(header);
4119
+ pendingName = null;
4120
+ yield { name: name.replace(/^\.\//, ""), bytes, typeflag, mode };
4121
+ }
4122
+ }
4123
+ static ustarName(header) {
4124
+ const name = field(header, 0, 100);
4125
+ const magic = header.subarray(257, 262).toString("ascii");
4126
+ const prefix = magic === "ustar" ? field(header, 345, 500) : "";
4127
+ return prefix ? `${prefix}/${name}` : name;
4128
+ }
4129
+ /** Regular files only, confined to `dir` (absolute or `..` names are
4130
+ * skipped, never written). Returns the number of files written. */
4131
+ extractTo(dir) {
4132
+ let written = 0;
4133
+ for (const member of this.members()) {
4134
+ if (member.typeflag !== "0" && member.typeflag !== "\0") continue;
4135
+ if (!_TarArchive.isConfined(member.name)) continue;
4136
+ const target = path4.join(dir, member.name);
4137
+ fs4.mkdirSync(path4.dirname(target), { recursive: true });
4138
+ const mode = archiveMode(member.mode);
4139
+ fs4.writeFileSync(target, member.bytes, { mode });
4140
+ fs4.chmodSync(target, mode);
4141
+ written++;
4142
+ }
4143
+ return written;
4144
+ }
4145
+ static isConfined(name) {
4146
+ if (name === "" || name.startsWith("/")) return false;
4147
+ return !name.split("/").includes("..");
4148
+ }
4149
+ };
4150
+ }
4151
+ });
4152
+
3192
4153
  // src/worlds/hub.ts
3193
4154
  var hub_exports = {};
3194
4155
  __export(hub_exports, {
3195
4156
  DEFAULT_BRANCH: () => DEFAULT_BRANCH,
4157
+ DetachedPushError: () => DetachedPushError,
3196
4158
  PushSlugConflict: () => PushSlugConflict,
3197
4159
  archiveMode: () => archiveMode,
3198
4160
  buildFileManifest: () => buildFileManifest,
3199
4161
  buildSourceTarball: () => buildSourceTarball,
4162
+ checkoutIdentity: () => checkoutIdentity,
3200
4163
  collectArchiveRelPaths: () => collectArchiveRelPaths,
3201
4164
  computeContentHash: () => computeContentHash,
3202
4165
  createRef: () => createRef,
@@ -3205,6 +4168,7 @@ __export(hub_exports, {
3205
4168
  propose: () => propose,
3206
4169
  pull: () => pull,
3207
4170
  push: () => push,
4171
+ pushBranch: () => pushBranch,
3208
4172
  pushSlug: () => pushSlug,
3209
4173
  readLocalMeta: () => readLocalMeta,
3210
4174
  resolvePushSlug: () => resolvePushSlug,
@@ -3212,9 +4176,9 @@ __export(hub_exports, {
3212
4176
  writeLocalMeta: () => writeLocalMeta
3213
4177
  });
3214
4178
  import { createHash as createHash4 } from "crypto";
3215
- import { gzipSync, gunzipSync } from "zlib";
3216
- import * as fs3 from "fs";
3217
- import * as path3 from "path";
4179
+ import { gzipSync } from "zlib";
4180
+ import * as fs5 from "fs";
4181
+ import * as path5 from "path";
3218
4182
  function collectArchiveRelPaths(dir) {
3219
4183
  const world = WorldDir.open(dir);
3220
4184
  if (world.hasRootGitignore) {
@@ -3234,9 +4198,6 @@ function octal(value, length) {
3234
4198
  "ascii"
3235
4199
  );
3236
4200
  }
3237
- function archiveMode(mode) {
3238
- return (mode & 73) !== 0 ? EXEC_MODE : FILE_MODE;
3239
- }
3240
4201
  function tarHeader(name, size, mode = FILE_MODE) {
3241
4202
  const header = Buffer.alloc(512);
3242
4203
  header.write(name, 0, 100, "utf-8");
@@ -3280,12 +4241,12 @@ function tarMember(name, payload, mode) {
3280
4241
  function buildSourceTarball(dir) {
3281
4242
  const parts2 = [];
3282
4243
  for (const relPath of collectArchiveRelPaths(dir)) {
3283
- const abs = path3.join(dir, relPath);
4244
+ const abs = path5.join(dir, relPath);
3284
4245
  parts2.push(
3285
4246
  ...tarMember(
3286
4247
  relPath,
3287
- fs3.readFileSync(abs),
3288
- archiveMode(fs3.statSync(abs).mode)
4248
+ fs5.readFileSync(abs),
4249
+ archiveMode(fs5.statSync(abs).mode)
3289
4250
  )
3290
4251
  );
3291
4252
  }
@@ -3294,7 +4255,7 @@ function buildSourceTarball(dir) {
3294
4255
  }
3295
4256
  function readLocalMeta(dir) {
3296
4257
  try {
3297
- const raw = fs3.readFileSync(path3.join(dir, META_RELPATH), "utf-8");
4258
+ const raw = fs5.readFileSync(path5.join(dir, META_RELPATH), "utf-8");
3298
4259
  const parsed = JSON.parse(raw);
3299
4260
  return parsed && typeof parsed === "object" ? parsed : null;
3300
4261
  } catch {
@@ -3317,16 +4278,16 @@ function resolvePushSlug(dir, opts = {}) {
3317
4278
  }
3318
4279
  const first = declared[0];
3319
4280
  if (first) return { ...base, slug: first.slug, source: first.source };
3320
- return { ...base, slug: path3.basename(path3.resolve(dir)), source: "directory name" };
4281
+ return { ...base, slug: path5.basename(path5.resolve(dir)), source: "directory name" };
3321
4282
  }
3322
4283
  function writeLocalMeta(dir, meta) {
3323
- fs3.mkdirSync(path3.join(dir, ".gateway"), { recursive: true });
3324
- fs3.writeFileSync(path3.join(dir, META_RELPATH), JSON.stringify(meta, null, 2));
4284
+ fs5.mkdirSync(path5.join(dir, ".gateway"), { recursive: true });
4285
+ fs5.writeFileSync(path5.join(dir, META_RELPATH), JSON.stringify(meta, null, 2));
3325
4286
  }
3326
4287
  function snapshotTreeHashes(dir) {
3327
4288
  const out = {};
3328
4289
  for (const relPath of collectArchiveRelPaths(dir)) {
3329
- out[relPath] = createHash4("sha256").update(fs3.readFileSync(path3.join(dir, relPath))).digest("hex");
4290
+ out[relPath] = createHash4("sha256").update(fs5.readFileSync(path5.join(dir, relPath))).digest("hex");
3330
4291
  }
3331
4292
  return out;
3332
4293
  }
@@ -3344,7 +4305,7 @@ function localTreeState(dir) {
3344
4305
  }
3345
4306
  function readPyproject(dir) {
3346
4307
  try {
3347
- const text2 = fs3.readFileSync(path3.join(dir, "pyproject.toml"), "utf-8");
4308
+ const text2 = fs5.readFileSync(path5.join(dir, "pyproject.toml"), "utf-8");
3348
4309
  const section = /\[project\]([\s\S]*?)(\n\[|$)/.exec(text2)?.[1] ?? "";
3349
4310
  const name = /\bname\s*=\s*"([^"]+)"/.exec(section)?.[1];
3350
4311
  const version = /\bversion\s*=\s*"([^"]+)"/.exec(section)?.[1];
@@ -3367,7 +4328,7 @@ function readWorldContractVersion(dir) {
3367
4328
  }
3368
4329
  function buildFileManifest(dir) {
3369
4330
  return collectArchiveRelPaths(dir).map((relPath) => {
3370
- const payload = fs3.readFileSync(path3.join(dir, relPath));
4331
+ const payload = fs5.readFileSync(path5.join(dir, relPath));
3371
4332
  return {
3372
4333
  path: relPath,
3373
4334
  isDirectory: false,
@@ -3391,30 +4352,36 @@ async function putObject(url, data, shaB64) {
3391
4352
  );
3392
4353
  }
3393
4354
  }
4355
+ function pushBranch(dir, localMeta, explicit) {
4356
+ if (explicit) return explicit;
4357
+ if (typeof localMeta.tag === "string" && localMeta.tag) throw new DetachedPushError(dir, localMeta.tag);
4358
+ return localMeta.branch ?? DEFAULT_BRANCH;
4359
+ }
3394
4360
  async function push(dir, opts = {}) {
3395
4361
  const options = opts.options ?? {};
3396
- if (!fs3.statSync(dir).isDirectory())
4362
+ if (!fs5.statSync(dir).isDirectory())
3397
4363
  throw new Error(`Not a directory: ${dir}`);
3398
4364
  const localMeta = readLocalMeta(dir) ?? {};
3399
- const branch = opts.branch ?? localMeta.branch ?? DEFAULT_BRANCH;
4365
+ const branch = pushBranch(dir, localMeta, opts.branch);
3400
4366
  const baseVersionId = opts.baseVersionId ?? localMeta.versionId ?? null;
4367
+ const world = WorldDir.open(dir);
3401
4368
  const fileManifest = buildFileManifest(dir);
3402
4369
  if (fileManifest.length === 0)
3403
4370
  throw new Error(
3404
4371
  `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).`
3405
4372
  );
3406
- const contentHash = computeContentHash(dir);
4373
+ const contentHash = world.contentHash;
3407
4374
  const pyproject = readPyproject(dir);
3408
4375
  const contractVersion = pyproject.version ? void 0 : readWorldContractVersion(dir).version;
3409
4376
  if (contractVersion) pyproject.version = contractVersion;
3410
- const slug = opts.slug ?? localMeta.slug ?? pyproject.name ?? path3.basename(path3.resolve(dir));
4377
+ const slug = opts.slug ?? localMeta.slug ?? pyproject.name ?? path5.basename(path5.resolve(dir));
3411
4378
  const metadata = {
3412
4379
  ...opts.name !== void 0 ? { name: opts.name } : {},
3413
4380
  ...opts.description !== void 0 ? { description: opts.description } : {},
3414
4381
  ...opts.tags !== void 0 ? { tags: opts.tags } : {},
3415
4382
  ...opts.visibility ? { visibility: opts.visibility } : {}
3416
4383
  };
3417
- const resolve10 = await apiRequest(
4384
+ const resolve11 = await apiRequest(
3418
4385
  options,
3419
4386
  "POST",
3420
4387
  "/api/public/benchmark-containers/resolve",
@@ -3423,7 +4390,7 @@ async function push(dir, opts = {}) {
3423
4390
  const tarball = buildSourceTarball(dir);
3424
4391
  const bundleSha256 = sha256b64(tarball);
3425
4392
  const version = await apiRequest(options, "POST", "/api/public/benchmark-containers/versions", {
3426
- containerId: resolve10.containerId,
4393
+ containerId: resolve11.containerId,
3427
4394
  contentHash,
3428
4395
  bundleSha256,
3429
4396
  bundleSizeBytes: tarball.length,
@@ -3462,56 +4429,36 @@ async function push(dir, opts = {}) {
3462
4429
  baseFiles: snapshotTreeHashes(dir)
3463
4430
  });
3464
4431
  return {
3465
- containerId: resolve10.containerId,
4432
+ containerId: resolve11.containerId,
3466
4433
  slug,
3467
4434
  versionId: version.versionId,
3468
4435
  contentHash,
3469
4436
  branch: final.branch ?? branch,
3470
4437
  state: final.state ?? null,
3471
- alreadyUploaded: Boolean(version.alreadyUploaded)
4438
+ alreadyUploaded: Boolean(version.alreadyUploaded),
4439
+ editSessionId: final.editSessionId ?? null,
4440
+ filesKept: fileManifest.length,
4441
+ excluded: world.exclusions
3472
4442
  };
3473
4443
  }
3474
4444
  function extractBundle(bundle, dir) {
3475
- const tar = gunzipSync(bundle);
3476
- let offset = 0;
3477
- let longName = null;
3478
- let written = 0;
3479
- while (offset + 512 <= tar.length) {
3480
- const header = tar.subarray(offset, offset + 512);
3481
- offset += 512;
3482
- if (header.every((b) => b === 0)) break;
3483
- const rawName = header.subarray(0, 100).toString("utf-8").replace(/\0.*$/, "");
3484
- const size = parseInt(
3485
- header.subarray(124, 136).toString("ascii").replace(/\0.*$/, "").trim(),
3486
- 8
3487
- ) || 0;
3488
- const mode = parseInt(
3489
- header.subarray(100, 108).toString("ascii").replace(/\0.*$/, "").trim(),
3490
- 8
3491
- ) || FILE_MODE;
3492
- const typeflag = header.subarray(156, 157).toString("ascii");
3493
- const body = tar.subarray(offset, offset + size);
3494
- offset += size + (size % 512 === 0 ? 0 : 512 - size % 512);
3495
- if (typeflag === "L") {
3496
- longName = body.toString("utf-8").replace(/\0.*$/, "");
3497
- continue;
3498
- }
3499
- const name = (longName ?? rawName).replace(/^\.\//, "");
3500
- longName = null;
3501
- if (typeflag !== "0" && typeflag !== "") continue;
3502
- if (name.startsWith("/") || name.split("/").includes("..")) continue;
3503
- const target = path3.join(dir, name);
3504
- fs3.mkdirSync(path3.dirname(target), { recursive: true });
3505
- fs3.writeFileSync(target, body, { mode: archiveMode(mode) });
3506
- fs3.chmodSync(target, archiveMode(mode));
3507
- written++;
3508
- }
3509
- return written;
4445
+ return TarArchive.fromGzip(bundle).extractTo(dir);
4446
+ }
4447
+ function checkoutIdentity(ref, resolved) {
4448
+ if (resolved.tag) return { tag: resolved.tag };
4449
+ if (resolved.branch) return { branch: resolved.branch };
4450
+ const pinned = ref === "latest" || /^\d|^[0-9a-f]{8,}$/.test(ref);
4451
+ return { branch: pinned ? DEFAULT_BRANCH : ref };
3510
4452
  }
3511
- async function pull(slugRef, target, options = {}) {
4453
+ async function pull(slugRef, target, options = {}, opts = {}) {
3512
4454
  const at = slugRef.indexOf("@");
3513
4455
  const slug = at === -1 ? slugRef : slugRef.slice(0, at);
3514
4456
  const ref = at === -1 ? "latest" : slugRef.slice(at + 1);
4457
+ const landing = CheckoutTarget.resolve(slug, target, {
4458
+ cwd: process.cwd(),
4459
+ force: opts.force ?? false,
4460
+ state: localTreeState
4461
+ });
3515
4462
  const details = await apiRequest(options, "POST", "/api/public/benchmark-containers/resolve-version", {
3516
4463
  slug,
3517
4464
  ref
@@ -3519,13 +4466,6 @@ async function pull(slugRef, target, options = {}) {
3519
4466
  if (!details.downloadUrl) {
3520
4467
  throw new Error(`${slug}@${ref} resolved but has no uploaded bundle`);
3521
4468
  }
3522
- let dir = target ?? path3.join(process.cwd(), slug);
3523
- if (!target) {
3524
- let i = 1;
3525
- const base = dir;
3526
- while (fs3.existsSync(dir)) dir = `${base}-${i++}`;
3527
- }
3528
- fs3.mkdirSync(dir, { recursive: true });
3529
4469
  const resp = await fetch(details.downloadUrl);
3530
4470
  if (!resp.ok) throw new Error(`bundle download -> ${resp.status}`);
3531
4471
  const bundle = Buffer.from(await resp.arrayBuffer());
@@ -3534,12 +4474,14 @@ async function pull(slugRef, target, options = {}) {
3534
4474
  `bundle integrity check failed for ${slug}@${ref}: downloaded sha256 != recorded bundleSha256`
3535
4475
  );
3536
4476
  }
4477
+ const dir = landing.dir;
4478
+ fs5.mkdirSync(dir, { recursive: true });
4479
+ landing.clear();
3537
4480
  const files = extractBundle(bundle, dir);
3538
- const branch = ref === "latest" || /^\d|^[0-9a-f]{8,}$/.test(ref) ? DEFAULT_BRANCH : ref;
3539
4481
  writeLocalMeta(dir, {
3540
4482
  slug,
3541
4483
  ref,
3542
- branch,
4484
+ ...checkoutIdentity(ref, details),
3543
4485
  versionId: details.versionId,
3544
4486
  contentHash: details.contentHash,
3545
4487
  semanticVersion: details.semanticVersion ?? void 0,
@@ -3558,13 +4500,13 @@ async function propose(dir, opts) {
3558
4500
  if (state2.clean)
3559
4501
  throw new Error("Nothing to propose \u2014 the tree matches its base.");
3560
4502
  const changes = state2.dirty.map((relPath) => {
3561
- const abs = path3.join(dir, relPath);
3562
- if (!fs3.existsSync(abs))
4503
+ const abs = path5.join(dir, relPath);
4504
+ if (!fs5.existsSync(abs))
3563
4505
  return { path: relPath, action: "delete" };
3564
4506
  return {
3565
4507
  path: relPath,
3566
4508
  action: "write",
3567
- newContent: fs3.readFileSync(abs, "utf-8")
4509
+ newContent: fs5.readFileSync(abs, "utf-8")
3568
4510
  };
3569
4511
  });
3570
4512
  const res = await apiRequest(
@@ -3590,16 +4532,17 @@ async function createRef(slug, name, kind, versionId, options = {}) {
3590
4532
  ...versionId ? { versionId } : {}
3591
4533
  });
3592
4534
  }
3593
- var DEFAULT_BRANCH, META_RELPATH, FILE_MODE, EXEC_MODE, MINTED_SUFFIX, PushSlugConflict, sha256b64;
4535
+ var DEFAULT_BRANCH, META_RELPATH, FILE_MODE, MINTED_SUFFIX, PushSlugConflict, sha256b64, DetachedPushError;
3594
4536
  var init_hub = __esm({
3595
4537
  "src/worlds/hub.ts"() {
3596
4538
  "use strict";
3597
4539
  init_worlds();
4540
+ init_checkoutTarget();
3598
4541
  init_worldDir();
4542
+ init_tar();
3599
4543
  DEFAULT_BRANCH = "main";
3600
- META_RELPATH = path3.join(".gateway", ".env-metadata.json");
3601
- FILE_MODE = 420;
3602
- EXEC_MODE = 493;
4544
+ META_RELPATH = path5.join(".gateway", ".env-metadata.json");
4545
+ FILE_MODE = TAR_FILE_MODE;
3603
4546
  MINTED_SUFFIX = /^-\d+$/;
3604
4547
  PushSlugConflict = class extends Error {
3605
4548
  constructor(dir, tracked, declared) {
@@ -3611,8 +4554,19 @@ var init_hub = __esm({
3611
4554
  this.declared = declared;
3612
4555
  this.name = "PushSlugConflict";
3613
4556
  }
4557
+ dir;
4558
+ tracked;
4559
+ declared;
3614
4560
  };
3615
4561
  sha256b64 = (data) => createHash4("sha256").update(data).digest("base64");
4562
+ DetachedPushError = class extends Error {
4563
+ constructor(dir, tag) {
4564
+ super(
4565
+ `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.`
4566
+ );
4567
+ this.name = "DetachedPushError";
4568
+ }
4569
+ };
3616
4570
  }
3617
4571
  });
3618
4572
 
@@ -3795,26 +4749,144 @@ var init_validate = __esm({
3795
4749
  "src/worlds/validate.ts"() {
3796
4750
  "use strict";
3797
4751
  init_worlds();
3798
- init_hub();
4752
+ init_hub();
4753
+ }
4754
+ });
4755
+
4756
+ // src/worlds/sandbox.ts
4757
+ function parseSlugRef(slugRef) {
4758
+ const at = slugRef.indexOf("@");
4759
+ if (at === -1) return { slug: slugRef };
4760
+ return { slug: slugRef.slice(0, at), ref: slugRef.slice(at + 1) };
4761
+ }
4762
+ function rebaseConflicts(error) {
4763
+ if (!(error instanceof ApiError) || error.status !== 409) return null;
4764
+ let body;
4765
+ try {
4766
+ body = JSON.parse(error.text);
4767
+ } catch {
4768
+ return null;
4769
+ }
4770
+ const conflicts = body?.conflicts;
4771
+ if (!Array.isArray(conflicts)) return null;
4772
+ return conflicts.filter(isConflictPath).map(({ path: path16, reason }) => ({ path: path16, reason }));
4773
+ }
4774
+ function isConflictPath(value) {
4775
+ const entry = value;
4776
+ return typeof entry?.path === "string" && typeof entry.reason === "string";
4777
+ }
4778
+ function uncommittedPaths(error) {
4779
+ if (!(error instanceof ApiError) || error.status !== 409 || error.code !== "sandbox_uncommitted") return null;
4780
+ let body;
4781
+ try {
4782
+ body = JSON.parse(error.text);
4783
+ } catch {
4784
+ return null;
4785
+ }
4786
+ const uncommitted = body?.uncommitted;
4787
+ if (!Array.isArray(uncommitted)) return null;
4788
+ return uncommitted.filter((p) => typeof p === "string");
4789
+ }
4790
+ function listQuery(filter) {
4791
+ const params = new URLSearchParams();
4792
+ if (filter.status) params.set("status", filter.status);
4793
+ if (filter.slug) params.set("slug", filter.slug);
4794
+ if (filter.limit !== void 0) params.set("limit", String(filter.limit));
4795
+ const qs3 = params.toString();
4796
+ return qs3 ? `?${qs3}` : "";
4797
+ }
4798
+ var isSandboxImportPending, sid, SANDBOXES, SANDBOX_REQUEST_TIMEOUT_MS, WorldSandboxClient;
4799
+ var init_sandbox = __esm({
4800
+ "src/worlds/sandbox.ts"() {
4801
+ "use strict";
4802
+ init_worlds();
4803
+ isSandboxImportPending = (answer) => !("versionId" in answer);
4804
+ sid = encodeURIComponent;
4805
+ SANDBOXES = "/api/public/benchmark-containers/sandboxes";
4806
+ SANDBOX_REQUEST_TIMEOUT_MS = 66e4;
4807
+ WorldSandboxClient = class {
4808
+ constructor(options = {}) {
4809
+ this.options = options;
4810
+ }
4811
+ options;
4812
+ request(method, path16, body) {
4813
+ return apiRequest(this.options, method, path16, body, {
4814
+ timeoutMs: SANDBOX_REQUEST_TIMEOUT_MS
4815
+ });
4816
+ }
4817
+ /**
4818
+ * `{ slug, ref? }` opens a READY version; `{ new, from }` opens a sandbox on
4819
+ * a world that does not exist yet (409 `world_exists` if the slug is taken,
4820
+ * 400 naming the shipped templates if `from` is unknown). Its first commit
4821
+ * creates the world on `main`.
4822
+ */
4823
+ open(target) {
4824
+ return this.request("POST", `${SANDBOXES}`, target);
4825
+ }
4826
+ status(sandboxId) {
4827
+ return this.request("GET", `${SANDBOXES}/${sid(sandboxId)}`);
4828
+ }
4829
+ /** The project's sandboxes, newest first — how an agent finds one it left open. */
4830
+ async list(filter = {}) {
4831
+ const res = await this.request("GET", `${SANDBOXES}${listQuery(filter)}`);
4832
+ return res.sandboxes;
4833
+ }
4834
+ async read(sandboxId, filePath) {
4835
+ const res = await this.request(
4836
+ "GET",
4837
+ `${SANDBOXES}/${sid(sandboxId)}/file?path=${encodeURIComponent(filePath)}`
4838
+ );
4839
+ return { path: res.path, size: res.size, bytes: Buffer.from(res.contentBase64, "base64") };
4840
+ }
4841
+ write(sandboxId, filePath, bytes) {
4842
+ return this.request("PUT", `${SANDBOXES}/${sid(sandboxId)}/file`, {
4843
+ path: filePath,
4844
+ contentBase64: bytes.toString("base64")
4845
+ });
4846
+ }
4847
+ exec(sandboxId, input) {
4848
+ return this.request("POST", `${SANDBOXES}/${sid(sandboxId)}/exec`, input);
4849
+ }
4850
+ check(sandboxId) {
4851
+ return this.request("POST", `${SANDBOXES}/${sid(sandboxId)}/check`, {});
4852
+ }
4853
+ /** With `rebase`, a moved base is replayed onto; a 409 then names the conflicting paths (`rebaseConflicts`). */
4854
+ commit(sandboxId, input) {
4855
+ const { rebase, ...rest } = input;
4856
+ return this.request("POST", `${SANDBOXES}/${sid(sandboxId)}/commit`, rebase ? { ...rest, rebase: true } : rest);
4857
+ }
4858
+ /**
4859
+ * A rows file already in the sandbox tree into the PLATFORM world the
4860
+ * sandbox was opened on (201 with the version, 202 with the batch to poll,
4861
+ * 400 naming a refused row). Not `commit`: a commit versions the source
4862
+ * tree and never carries data.
4863
+ */
4864
+ importData(sandboxId, input) {
4865
+ return this.request("POST", `${SANDBOXES}/${sid(sandboxId)}/import`, input);
4866
+ }
4867
+ /** Uncommitted work is a 409 (`uncommittedPaths`) unless `force` discards it. */
4868
+ close(sandboxId, opts = {}) {
4869
+ return this.request("DELETE", `${SANDBOXES}/${sid(sandboxId)}`, opts.force ? { force: true } : void 0);
4870
+ }
4871
+ };
3799
4872
  }
3800
4873
  });
3801
4874
 
3802
4875
  // src/worlds/describe.ts
3803
- async function describeWorld(slug, options = {}) {
3804
- if (slug.includes("@"))
3805
- throw new Error(
3806
- `describeWorld reads a world's head version: pass the slug without @ref (got ${slug})`
3807
- );
4876
+ async function describeWorld(slugRef, options = {}) {
4877
+ const { slug, ref } = parseSlugRef(slugRef);
4878
+ const query = ref === void 0 ? "" : `?ref=${encodeURIComponent(ref)}`;
3808
4879
  return apiRequest(
3809
4880
  options,
3810
4881
  "GET",
3811
- `/api/public/worlds/${encodeURIComponent(slug)}`
4882
+ `/api/public/worlds/${encodeURIComponent(slug)}${query}`
3812
4883
  );
3813
4884
  }
3814
4885
  var init_describe = __esm({
3815
4886
  "src/worlds/describe.ts"() {
3816
4887
  "use strict";
3817
4888
  init_worlds();
4889
+ init_sandbox();
3818
4890
  }
3819
4891
  });
3820
4892
 
@@ -3919,6 +4991,7 @@ var init_json = __esm({
3919
4991
  constructor(text2) {
3920
4992
  this.text = text2;
3921
4993
  }
4994
+ text;
3922
4995
  /** A float in Python's eyes: a fraction, an exponent, or a non-finite literal. */
3923
4996
  get isFloat() {
3924
4997
  return /[.eE]/.test(this.text) || /[nN]/.test(this.text);
@@ -3933,6 +5006,7 @@ var init_json = __esm({
3933
5006
  constructor(s) {
3934
5007
  this.s = s;
3935
5008
  }
5009
+ s;
3936
5010
  i = 0;
3937
5011
  skipWs() {
3938
5012
  const s = this.s;
@@ -4213,24 +5287,24 @@ function roundForm(plaintext, decimals) {
4213
5287
  if (typeof plaintext === "string" || isInt(plaintext) || !Number.isFinite(plaintext)) return plaintext;
4214
5288
  return pyRound(new JsonNumber(pyFloatRepr(plaintext)), decimals).value;
4215
5289
  }
4216
- function redactionOf(redact, field) {
5290
+ function redactionOf(redact, field2) {
4217
5291
  if (!redact) return null;
4218
- const named = (names) => (names ?? []).some((name) => name === field || name.slice(name.lastIndexOf(".") + 1) === field);
5292
+ const named = (names) => (names ?? []).some((name) => name === field2 || name.slice(name.lastIndexOf(".") + 1) === field2);
4219
5293
  if (named(redact.drop)) return "drop";
4220
5294
  if (named(redact.hash)) return "hash";
4221
5295
  if (named(redact.preserve)) return "preserve";
4222
- const decimals = redact.round?.[field];
5296
+ const decimals = redact.round?.[field2];
4223
5297
  if (typeof decimals === "number") return `round:${decimals}`;
4224
5298
  return null;
4225
5299
  }
4226
- function storedForms(world, field, plaintext, transform) {
5300
+ function storedForms(world, field2, plaintext, transform) {
4227
5301
  if (transform?.length) plaintext = applyTransforms(plaintext, transform);
4228
- const policy = redactionOf(world.redact, field);
5302
+ const policy = redactionOf(world.redact, field2);
4229
5303
  const salt = world.redact?.slug ?? world.slug;
4230
5304
  if (policy === "drop") return [];
4231
5305
  if (policy === "hash") return [hashForm(salt, plaintext)];
4232
5306
  if (policy === "preserve") return [preserveForm(salt, plaintext)];
4233
- if (policy !== null) return [roundForm(plaintext, world.redact.round[field])];
5307
+ if (policy !== null) return [roundForm(plaintext, world.redact.round[field2])];
4234
5308
  return [plaintext];
4235
5309
  }
4236
5310
  var isInt;
@@ -4315,80 +5389,51 @@ var init_router = __esm({
4315
5389
  super(message);
4316
5390
  this.exitCode = exitCode;
4317
5391
  }
5392
+ exitCode;
4318
5393
  };
4319
5394
  }
4320
5395
  });
4321
5396
 
4322
5397
  // src/cli/config.ts
4323
- import * as fs4 from "fs";
5398
+ import * as fs6 from "fs";
4324
5399
  import * as os from "os";
4325
- import * as path4 from "path";
4326
- function transportDetail(error, timeoutMs) {
4327
- if (error instanceof Error && error.name === "AbortError") return `timed out after ${Math.round(timeoutMs / 1e3)}s`;
4328
- const cause = error instanceof Error && error.cause instanceof Error ? error.cause : void 0;
4329
- const code = cause && "code" in cause && typeof cause.code === "string" ? `${cause.code}: ` : "";
4330
- const message = cause?.message ?? (error instanceof Error ? error.message : String(error));
4331
- return `${code}${message}`;
4332
- }
5400
+ import * as path6 from "path";
4333
5401
  async function api(creds, method, route, body, init3 = {}) {
4334
- const controller = new AbortController();
4335
- const timeoutMs = init3.timeoutMs ?? 12e4;
4336
- const timer = setTimeout(() => controller.abort(), timeoutMs);
4337
- let res;
4338
- try {
4339
- res = await fetch(`${creds.host}${route}`, {
4340
- method,
4341
- headers: {
4342
- "content-type": "application/json",
4343
- accept: "application/json",
4344
- authorization: "Basic " + Buffer.from(`${creds.publicKey}:${creds.secretKey}`).toString("base64")
4345
- },
4346
- ...body === void 0 ? {} : { body: JSON.stringify(body) },
4347
- signal: controller.signal
4348
- });
4349
- } catch (error) {
4350
- clearTimeout(timer);
4351
- throw new UnreachableError(creds.host, method, route, transportDetail(error, timeoutMs));
4352
- }
4353
- try {
4354
- const text2 = await res.text();
4355
- if (!res.ok) throw new ApiError(res.status, method, route, text2);
4356
- return text2 ? JSON.parse(text2) : {};
4357
- } finally {
4358
- clearTimeout(timer);
4359
- }
5402
+ const reply = await new PlatformTransport(creds).send(method, route, body, init3);
5403
+ if (!reply.ok) throw new ApiError2(reply.status, method, route, reply.text);
5404
+ return reply.text ? JSON.parse(reply.text) : {};
4360
5405
  }
4361
- var ApiError, UnreachableError;
5406
+ var ApiError2;
4362
5407
  var init_config = __esm({
4363
5408
  "src/cli/config.ts"() {
4364
5409
  "use strict";
4365
5410
  init_router();
4366
- ApiError = class extends CliError {
5411
+ init_worlds();
5412
+ init_transport();
5413
+ ApiError2 = class extends CliError {
4367
5414
  constructor(status, method, route, text2) {
4368
- super(`${method} ${route} -> ${status}: ${text2.slice(0, 600)}`, 1);
5415
+ const body = parseErrorBody(text2);
5416
+ super(`${method} ${route} -> ${status}: ${body.detail}`, 1);
4369
5417
  this.status = status;
4370
5418
  this.method = method;
4371
5419
  this.route = route;
4372
5420
  this.text = text2;
5421
+ this.code = body.code;
4373
5422
  }
4374
- };
4375
- UnreachableError = class extends CliError {
4376
- constructor(host, method, route, detail) {
4377
- super(`${method} ${route}: no answer from ${host} (${detail}). Check the host and the network, then retry.`, 1);
4378
- this.host = host;
4379
- this.method = method;
4380
- this.route = route;
4381
- this.detail = detail;
4382
- }
5423
+ status;
5424
+ method;
5425
+ route;
5426
+ text;
5427
+ code;
4383
5428
  };
4384
5429
  }
4385
5430
  });
4386
5431
 
4387
5432
  // src/cli/runtime/local.ts
4388
5433
  import { spawn, spawnSync } from "child_process";
4389
- import * as fs5 from "fs";
5434
+ import * as fs7 from "fs";
4390
5435
  import * as net from "net";
4391
- import * as path5 from "path";
5436
+ import * as path7 from "path";
4392
5437
  function tailOf(output) {
4393
5438
  return output.length > DIAGNOSTIC_TAIL ? `\u2026${output.slice(-DIAGNOSTIC_TAIL)}` : output;
4394
5439
  }
@@ -4403,16 +5448,16 @@ function runtimeRoot() {
4403
5448
  const candidates = [];
4404
5449
  if (process.env.GATEWAY_RUNTIME_PATH)
4405
5450
  candidates.push(process.env.GATEWAY_RUNTIME_PATH);
4406
- const entry = process.argv[1] && fs5.existsSync(process.argv[1]) ? path5.dirname(fs5.realpathSync(process.argv[1])) : null;
5451
+ const entry = process.argv[1] && fs7.existsSync(process.argv[1]) ? path7.dirname(fs7.realpathSync(process.argv[1])) : null;
4407
5452
  if (entry) {
4408
- candidates.push(path5.resolve(entry, "..", "runtime"));
4409
- candidates.push(path5.resolve(entry, "..", "..", "runtime"));
4410
- candidates.push(path5.resolve(entry, "..", "..", "sdk", "src"));
5453
+ candidates.push(path7.resolve(entry, "..", "runtime"));
5454
+ candidates.push(path7.resolve(entry, "..", "..", "runtime"));
5455
+ candidates.push(path7.resolve(entry, "..", "..", "sdk", "src"));
4411
5456
  }
4412
- candidates.push(path5.resolve(process.cwd(), "runtime"));
5457
+ candidates.push(path7.resolve(process.cwd(), "runtime"));
4413
5458
  for (const root of candidates)
4414
- if (fs5.existsSync(
4415
- path5.join(root, "gatewaysdk", "environment", "schema", "platform.py")
5459
+ if (fs7.existsSync(
5460
+ path7.join(root, "gatewaysdk", "environment", "schema", "platform.py")
4416
5461
  ))
4417
5462
  return root;
4418
5463
  return null;
@@ -4495,7 +5540,7 @@ function localPythonHasYaml(python) {
4495
5540
  }
4496
5541
  async function localBridge(request, local, opts = {}) {
4497
5542
  const input = JSON.stringify(request);
4498
- return await new Promise((resolve10, reject) => {
5543
+ return await new Promise((resolve11, reject) => {
4499
5544
  const child = spawn(
4500
5545
  local.python,
4501
5546
  ["-I", "-B", "-c", BRIDGE_BOOTSTRAP, local.root],
@@ -4540,7 +5585,7 @@ async function localBridge(request, local, opts = {}) {
4540
5585
  payload = null;
4541
5586
  }
4542
5587
  if (payload && typeof payload === "object") {
4543
- resolve10(payload);
5588
+ resolve11(payload);
4544
5589
  return;
4545
5590
  }
4546
5591
  reject(
@@ -4559,7 +5604,7 @@ var init_local = __esm({
4559
5604
  "use strict";
4560
5605
  init_router();
4561
5606
  init_config();
4562
- MIN_PYTHON = [3, 11];
5607
+ MIN_PYTHON = [3, 12];
4563
5608
  DIAGNOSTIC_TAIL = 600;
4564
5609
  BRIDGE_BOOTSTRAP = `import sys,runpy,types,os
4565
5610
  root=sys.argv[1]
@@ -4571,7 +5616,6 @@ runpy.run_module('gatewaysdk.environment.schema.platform',run_name='__main__')`;
4571
5616
  PYTHON_CANDIDATES = [
4572
5617
  "python3.13",
4573
5618
  "python3.12",
4574
- "python3.11",
4575
5619
  "python3",
4576
5620
  "python"
4577
5621
  ];
@@ -4580,18 +5624,18 @@ runpy.run_module('gatewaysdk.environment.schema.platform',run_name='__main__')`;
4580
5624
  });
4581
5625
 
4582
5626
  // src/cli/runtime/client.ts
4583
- import * as fs6 from "fs";
4584
- import * as path6 from "path";
5627
+ import * as fs8 from "fs";
5628
+ import * as path8 from "path";
4585
5629
  function isBuildOutput(relPath) {
4586
5630
  return BUILD_OUTPUT.test(relPath);
4587
5631
  }
4588
5632
  function readWorldFiles(dir, opts = {}) {
4589
- if (!fs6.existsSync(dir) || !fs6.statSync(dir).isDirectory())
5633
+ if (!fs8.existsSync(dir) || !fs8.statSync(dir).isDirectory())
4590
5634
  throw new CliError(`Not a directory: ${dir}`);
4591
5635
  const out = [];
4592
5636
  const walk = (rel) => {
4593
- const abs = rel ? path6.join(dir, rel) : dir;
4594
- const entries = fs6.readdirSync(abs, { withFileTypes: true });
5637
+ const abs = rel ? path8.join(dir, rel) : dir;
5638
+ const entries = fs8.readdirSync(abs, { withFileTypes: true });
4595
5639
  entries.sort((a, b) => a.name.localeCompare(b.name));
4596
5640
  for (const entry of entries) {
4597
5641
  const childRel = rel ? `${rel}/${entry.name}` : entry.name;
@@ -4601,7 +5645,7 @@ function readWorldFiles(dir, opts = {}) {
4601
5645
  if (!opts.buildOutputs && isBuildOutput(childRel)) continue;
4602
5646
  out.push({
4603
5647
  path: childRel,
4604
- content: fs6.readFileSync(path6.join(dir, childRel)).toString("base64")
5648
+ content: fs8.readFileSync(path8.join(dir, childRel)).toString("base64")
4605
5649
  });
4606
5650
  }
4607
5651
  }
@@ -4615,20 +5659,22 @@ function assertSafeRelPath(rel) {
4615
5659
  throw new CliError(`The runtime returned an unsafe file path: ${rel}`, 1);
4616
5660
  }
4617
5661
  function writeWorldFiles(dir, files, opts = {}) {
5662
+ if (files.length > MAX_WORLD_FILES)
5663
+ throw new CliError(`The runtime returned ${files.length} files, over the ${MAX_WORLD_FILES} limit`, 1);
4618
5664
  for (const file of files) assertSafeRelPath(file.path);
4619
- if (opts.clean && fs6.existsSync(dir)) {
5665
+ if (opts.clean && fs8.existsSync(dir)) {
4620
5666
  const keep = new Set(files.map((f) => f.path));
4621
5667
  for (const existing of readWorldFiles(dir)) {
4622
- if (!keep.has(existing.path)) fs6.rmSync(path6.join(dir, existing.path));
5668
+ if (!keep.has(existing.path)) fs8.rmSync(path8.join(dir, existing.path));
4623
5669
  }
4624
5670
  pruneEmptyDirs(dir);
4625
5671
  }
4626
- fs6.mkdirSync(dir, { recursive: true });
5672
+ fs8.mkdirSync(dir, { recursive: true });
4627
5673
  const written = [];
4628
5674
  for (const file of files) {
4629
- const target = path6.join(dir, file.path);
4630
- fs6.mkdirSync(path6.dirname(target), { recursive: true });
4631
- fs6.writeFileSync(target, Buffer.from(file.content, "base64"));
5675
+ const target = path8.join(dir, file.path);
5676
+ fs8.mkdirSync(path8.dirname(target), { recursive: true });
5677
+ fs8.writeFileSync(target, Buffer.from(file.content, "base64"));
4632
5678
  written.push(file.path);
4633
5679
  }
4634
5680
  return written;
@@ -4636,14 +5682,14 @@ function writeWorldFiles(dir, files, opts = {}) {
4636
5682
  function pruneEmptyDirs(root) {
4637
5683
  const walk = (abs) => {
4638
5684
  let empty = true;
4639
- for (const entry of fs6.readdirSync(abs, { withFileTypes: true })) {
4640
- const child = path6.join(abs, entry.name);
5685
+ for (const entry of fs8.readdirSync(abs, { withFileTypes: true })) {
5686
+ const child = path8.join(abs, entry.name);
4641
5687
  if (entry.isDirectory()) {
4642
5688
  if (SKIP_DIRS.has(entry.name)) {
4643
5689
  empty = false;
4644
5690
  continue;
4645
5691
  }
4646
- if (walk(child)) fs6.rmdirSync(child);
5692
+ if (walk(child)) fs8.rmdirSync(child);
4647
5693
  else empty = false;
4648
5694
  } else empty = false;
4649
5695
  }
@@ -4663,56 +5709,59 @@ function detailFrom(payload) {
4663
5709
  if (typeof detail.code !== "string" || typeof detail.message !== "string") return null;
4664
5710
  return detail;
4665
5711
  }
5712
+ function isYamlSource(name, base64) {
5713
+ if (name.endsWith(".json")) return false;
5714
+ if (YAML_NAME.test(name)) return true;
5715
+ const head = Buffer.from(base64.slice(0, 256), "base64").toString("utf8").trimStart();
5716
+ return !["{", "["].includes(head[0] ?? "");
5717
+ }
5718
+ function yamlDocument(request) {
5719
+ if (request.command === "init-openapi")
5720
+ return isYamlSource(String(request.source ?? ""), String(request.document ?? ""));
5721
+ return request.command === "conform" && Array.isArray(request.openapi) && request.openapi.some((doc) => YAML_NAME.test(doc.path ?? ""));
5722
+ }
5723
+ function runsLocally(request) {
5724
+ const local = localRuntime();
5725
+ return local !== null && !(yamlDocument(request) && !localPythonHasYaml(local.python));
5726
+ }
4666
5727
  async function runtime(creds, request, opts = {}) {
4667
5728
  const local = localRuntime();
4668
- const yamlSpec = request.command === "conform" && Array.isArray(request.openapi) && request.openapi.some((doc) => /\.ya?ml$/i.test(doc.path ?? ""));
4669
- if (local && !(yamlSpec && !localPythonHasYaml(local.python))) {
4670
- const payload = await localBridge(request, local, opts);
4671
- const detail = detailFrom(payload);
4672
- if (detail) throw new BridgeRejected(detail);
4673
- return payload;
5729
+ if (local && runsLocally(request)) {
5730
+ const payload2 = await localBridge(request, local, opts);
5731
+ const detail2 = detailFrom(payload2);
5732
+ if (detail2) throw new BridgeRejected(detail2);
5733
+ return payload2;
4674
5734
  }
4675
5735
  if (!creds)
4676
5736
  throw new CliError(
4677
5737
  "This needs the schema runtime (the CLI bundles it) or platform credentials (`gateway auth login`). " + localRuntimeReason()
4678
5738
  );
4679
- const controller = new AbortController();
4680
- const timer = setTimeout(() => controller.abort(), opts.timeoutMs ?? 18e4);
4681
5739
  const route = "/api/public/worlds/runtime";
5740
+ const res = await new PlatformTransport(creds).send("POST", route, request, {
5741
+ timeoutMs: opts.timeoutMs ?? RUNTIME_TIMEOUT_MS
5742
+ });
5743
+ let payload = null;
4682
5744
  try {
4683
- const res = await fetch(`${creds.host}${route}`, {
4684
- method: "POST",
4685
- headers: {
4686
- "content-type": "application/json",
4687
- accept: "application/json",
4688
- authorization: "Basic " + Buffer.from(`${creds.publicKey}:${creds.secretKey}`).toString("base64")
4689
- },
4690
- body: JSON.stringify(request),
4691
- signal: controller.signal
4692
- });
4693
- const text2 = await res.text();
4694
- let payload = null;
4695
- try {
4696
- payload = text2 ? JSON.parse(text2) : {};
4697
- } catch {
4698
- payload = null;
4699
- }
4700
- const detail = detailFrom(payload);
4701
- if (detail) throw new BridgeRejected(detail);
4702
- if (!res.ok)
4703
- throw new CliError(`POST ${route} (${request.command}) -> ${res.status}: ${text2.slice(0, 600)}`, 1);
4704
- if (payload === null) throw new CliError(`POST ${route} (${request.command}) returned non-JSON`, 1);
4705
- return payload;
4706
- } finally {
4707
- clearTimeout(timer);
5745
+ payload = res.text ? JSON.parse(res.text) : {};
5746
+ } catch {
5747
+ payload = null;
4708
5748
  }
5749
+ const detail = detailFrom(payload);
5750
+ if (detail) throw new BridgeRejected(detail);
5751
+ if (!res.ok)
5752
+ throw new CliError(`POST ${route} (${request.command}) -> ${res.status}: ${res.text.slice(0, 600)}`, 1);
5753
+ if (payload === null) throw new CliError(`POST ${route} (${request.command}) returned non-JSON`, 1);
5754
+ return payload;
4709
5755
  }
4710
- var SKIP_DIRS, BUILD_OUTPUT, BridgeRejected;
5756
+ var MAX_WORLD_FILES, RUNTIME_TIMEOUT_MS, SKIP_DIRS, BUILD_OUTPUT, BridgeRejected, YAML_NAME;
4711
5757
  var init_client = __esm({
4712
5758
  "src/cli/runtime/client.ts"() {
4713
5759
  "use strict";
4714
5760
  init_router();
4715
5761
  init_local();
5762
+ init_transport();
5763
+ MAX_WORLD_FILES = 2e3;
5764
+ RUNTIME_TIMEOUT_MS = 18e4;
4716
5765
  SKIP_DIRS = /* @__PURE__ */ new Set(["__pycache__", ".git", "node_modules", ".gateway"]);
4717
5766
  BUILD_OUTPUT = /(^|\/)state\.(sqlite|json)$/;
4718
5767
  BridgeRejected = class extends CliError {
@@ -4720,7 +5769,9 @@ var init_client = __esm({
4720
5769
  super(formatBridgeError(detail), 1);
4721
5770
  this.detail = detail;
4722
5771
  }
5772
+ detail;
4723
5773
  };
5774
+ YAML_NAME = /\.ya?ml$/i;
4724
5775
  }
4725
5776
  });
4726
5777
 
@@ -4728,15 +5779,17 @@ var init_client = __esm({
4728
5779
  var data_exports = {};
4729
5780
  __export(data_exports, {
4730
5781
  checkLocalWorldData: () => checkLocalWorldData,
5782
+ chunkLocalWorldFiles: () => chunkLocalWorldFiles,
4731
5783
  dropBuildOutputs: () => dropBuildOutputs,
4732
5784
  importLocalWorldData: () => importLocalWorldData,
5785
+ importLocalWorldFiles: () => importLocalWorldFiles,
4733
5786
  ingestLocalToolCalls: () => ingestLocalToolCalls,
4734
5787
  queryLocalWorldData: () => queryLocalWorldData,
4735
5788
  queryLocalWorldDataAcross: () => queryLocalWorldDataAcross,
4736
5789
  showLocalWorldData: () => showLocalWorldData
4737
5790
  });
4738
- import * as fs7 from "fs";
4739
- import * as path7 from "path";
5791
+ import * as fs9 from "fs";
5792
+ import * as path9 from "path";
4740
5793
  async function importLocalWorldData(dir, rows, opts, creds) {
4741
5794
  const res = await runtime(creds, {
4742
5795
  command: "import-data",
@@ -4758,11 +5811,57 @@ async function importLocalWorldData(dir, rows, opts, creds) {
4758
5811
  } : {}
4759
5812
  };
4760
5813
  }
5814
+ async function importLocalWorldFiles(dir, sources, opts) {
5815
+ const local = localRuntime();
5816
+ if (!local)
5817
+ throw new CliError(
5818
+ `Rows files stream into a directory through the bundled runtime on this machine, and none can run: ${localRuntimeReason()}`,
5819
+ 1
5820
+ );
5821
+ const res = await runtime(null, {
5822
+ command: "import-files",
5823
+ world: path9.resolve(dir),
5824
+ sources: sources.map((source) => path9.resolve(source)),
5825
+ mode: opts.mode ?? "append",
5826
+ ...opts.entity ? { entity: opts.entity } : {},
5827
+ ...opts.delimiter ? { delimiter: opts.delimiter } : {},
5828
+ ...opts.merge && opts.merge !== "upsert" ? { merge: opts.merge } : {},
5829
+ ...opts.redact && opts.redact !== "off" ? { redact: opts.redact } : {},
5830
+ ...opts.dryRun ? { dry_run: true } : {}
5831
+ });
5832
+ return {
5833
+ kind: res.kind ?? "unknown",
5834
+ entity_counts: res.entity_counts ?? {},
5835
+ changed: Boolean(res.changed),
5836
+ rows: res.rows ?? 0,
5837
+ ...res.proof ? { proof: res.proof } : {},
5838
+ ...res.deferred ? { deferred: res.deferred } : {}
5839
+ };
5840
+ }
5841
+ async function chunkLocalWorldFiles(dir, sources, out, opts) {
5842
+ const local = localRuntime();
5843
+ if (!local)
5844
+ throw new CliError(
5845
+ `Rows files are cut into chunks by the bundled runtime on this machine, and none can run: ${localRuntimeReason()}`,
5846
+ 1
5847
+ );
5848
+ const res = await runtime(null, {
5849
+ command: "chunk-files",
5850
+ world: path9.resolve(dir),
5851
+ sources: sources.map((source) => path9.resolve(source)),
5852
+ out: path9.resolve(out),
5853
+ ...opts.entity ? { entity: opts.entity } : {},
5854
+ ...opts.delimiter ? { delimiter: opts.delimiter } : {},
5855
+ ...opts.chunkBytes ? { chunk_bytes: opts.chunkBytes } : {},
5856
+ ...opts.chunkRows ? { chunk_rows: opts.chunkRows } : {}
5857
+ });
5858
+ return { rows: res.rows ?? 0, chunks: res.chunks ?? [] };
5859
+ }
4761
5860
  function dropBuildOutputs(dir) {
4762
5861
  const dropped = [];
4763
5862
  for (const file of readWorldFiles(dir, { buildOutputs: true })) {
4764
5863
  if (!BUILD_OUTPUT2.test(file.path)) continue;
4765
- fs7.rmSync(path7.join(dir, file.path), { force: true });
5864
+ fs9.rmSync(path9.join(dir, file.path), { force: true });
4766
5865
  dropped.push(file.path);
4767
5866
  }
4768
5867
  return dropped;
@@ -4829,7 +5928,7 @@ async function queryLocalWorldDataAcross(dir, entity, where, opts) {
4829
5928
  const payload = await localBridge(
4830
5929
  {
4831
5930
  command: "query",
4832
- world: path7.resolve(dir),
5931
+ world: path9.resolve(dir),
4833
5932
  entity,
4834
5933
  across: true,
4835
5934
  ...opts.compare ? { compare: true } : {},
@@ -4900,9 +5999,9 @@ __export(transform_exports, {
4900
5999
  transformRecords: () => transformRecords
4901
6000
  });
4902
6001
  import { spawn as spawn2 } from "child_process";
4903
- import * as fs8 from "fs";
6002
+ import * as fs10 from "fs";
4904
6003
  import * as os2 from "os";
4905
- import * as path8 from "path";
6004
+ import * as path10 from "path";
4906
6005
  import { createRequire } from "module";
4907
6006
  function checkRows(value, where) {
4908
6007
  if (!isObject(value)) throw new CliError(`${where} must return {entity: [rows]}; got ${value === null ? "null" : Array.isArray(value) ? "an array" : typeof value}`, 1);
@@ -4927,27 +6026,27 @@ function typescriptPrefix() {
4927
6026
  }
4928
6027
  }
4929
6028
  function command(script, wrapperDir) {
4930
- const suffix = path8.extname(script).toLowerCase();
6029
+ const suffix = path10.extname(script).toLowerCase();
4931
6030
  if (PYTHON_SUFFIXES.includes(suffix)) return { file: process.env.GATEWAY_PYTHON || "python3", args: ["-c", PY_WRAPPER, script] };
4932
6031
  if (NODE_SUFFIXES.includes(suffix)) {
4933
- const wrapper = path8.join(wrapperDir, "transform-wrapper.mjs");
4934
- fs8.writeFileSync(wrapper, NODE_WRAPPER);
6032
+ const wrapper = path10.join(wrapperDir, "transform-wrapper.mjs");
6033
+ fs10.writeFileSync(wrapper, NODE_WRAPPER);
4935
6034
  const flags = suffix === ".ts" || suffix === ".mts" ? typescriptPrefix() : [];
4936
6035
  return { file: process.env.GATEWAY_NODE || process.execPath, args: [...flags, wrapper, script] };
4937
6036
  }
4938
- throw new CliError(`${path8.basename(script)}: a transform script is .py, .ts, .mjs, .js or .cjs`, 1);
6037
+ throw new CliError(`${path10.basename(script)}: a transform script is .py, .ts, .mjs, .js or .cjs`, 1);
4939
6038
  }
4940
6039
  async function runTransform(script, records, opts = {}) {
4941
- if (!fs8.existsSync(script) || !fs8.statSync(script).isFile()) throw new CliError(`no transform script at ${script}`, 1);
4942
- const resolved = path8.resolve(script);
4943
- const name = path8.basename(script);
6040
+ if (!fs10.existsSync(script) || !fs10.statSync(script).isFile()) throw new CliError(`no transform script at ${script}`, 1);
6041
+ const resolved = path10.resolve(script);
6042
+ const name = path10.basename(script);
4944
6043
  const timeoutMs = opts.timeoutMs ?? DEFAULT_TRANSFORM_TIMEOUT_MS;
4945
- const scratch = fs8.mkdtempSync(path8.join(os2.tmpdir(), "gateway-transform-"));
6044
+ const scratch = fs10.mkdtempSync(path10.join(os2.tmpdir(), "gateway-transform-"));
4946
6045
  try {
4947
6046
  const { file, args } = command(resolved, scratch);
4948
6047
  const env = Object.fromEntries(Object.entries(process.env).filter(([key2]) => !SCRUBBED.test(key2)));
4949
- const done = await new Promise((resolve10, reject) => {
4950
- const child = spawn2(file, args, { cwd: path8.dirname(resolved), env, stdio: ["pipe", "pipe", "pipe"] });
6048
+ const done = await new Promise((resolve11, reject) => {
6049
+ const child = spawn2(file, args, { cwd: path10.dirname(resolved), env, stdio: ["pipe", "pipe", "pipe"] });
4951
6050
  let stdout = "";
4952
6051
  let stderr = "";
4953
6052
  let timedOut = false;
@@ -4963,7 +6062,7 @@ async function runTransform(script, records, opts = {}) {
4963
6062
  });
4964
6063
  child.on("close", (code) => {
4965
6064
  clearTimeout(timer);
4966
- resolve10({ code, stdout, stderr, timedOut });
6065
+ resolve11({ code, stdout, stderr, timedOut });
4967
6066
  });
4968
6067
  child.stdin.on("error", () => void 0);
4969
6068
  child.stdin.end(records.map((record) => JSON.stringify(record) + "\n").join(""));
@@ -4978,7 +6077,7 @@ async function runTransform(script, records, opts = {}) {
4978
6077
  }
4979
6078
  return { rows: checkRows(value, name), stderr: done.stderr };
4980
6079
  } finally {
4981
- fs8.rmSync(scratch, { recursive: true, force: true });
6080
+ fs10.rmSync(scratch, { recursive: true, force: true });
4982
6081
  }
4983
6082
  }
4984
6083
  async function transformRecords(transform, records, opts = {}) {
@@ -5071,7 +6170,7 @@ if (fn) {
5071
6170
 
5072
6171
  // src/cli/platform/worldData/batches.ts
5073
6172
  import { createHash as createHash7 } from "crypto";
5074
- import * as fs9 from "fs";
6173
+ import * as fs11 from "fs";
5075
6174
  function isSettled(status) {
5076
6175
  if (!TERMINAL_STATES.has(status.state)) return false;
5077
6176
  if (status.state !== "applied") return true;
@@ -5139,7 +6238,7 @@ var init_batches = __esm({
5139
6238
  "published",
5140
6239
  "failed"
5141
6240
  ]);
5142
- sleepMs = (ms) => new Promise((resolve10) => setTimeout(resolve10, ms));
6241
+ sleepMs = (ms) => new Promise((resolve11) => setTimeout(resolve11, ms));
5143
6242
  WorldDataApi = class {
5144
6243
  constructor(creds, slug, sleep3 = sleepMs) {
5145
6244
  this.creds = creds;
@@ -5147,6 +6246,9 @@ var init_batches = __esm({
5147
6246
  this.sleep = sleep3;
5148
6247
  this.base = `/api/public/worlds/${encodeURIComponent(slug)}/data`;
5149
6248
  }
6249
+ creds;
6250
+ slug;
6251
+ sleep;
5150
6252
  base;
5151
6253
  open(body) {
5152
6254
  return api(this.creds, "POST", `${this.base}/batches`, body);
@@ -5422,9 +6524,9 @@ var init_push = __esm({
5422
6524
  });
5423
6525
 
5424
6526
  // src/worlds/ingest.ts
5425
- import * as fs10 from "fs";
6527
+ import * as fs12 from "fs";
5426
6528
  import * as os3 from "os";
5427
- import * as path9 from "path";
6529
+ import * as path11 from "path";
5428
6530
  function parseToolCallRecord(raw) {
5429
6531
  const none = { record: null, skip: null };
5430
6532
  if (!isObject2(raw)) return { ...none, refusal: "record is not an object" };
@@ -5445,7 +6547,7 @@ function parseToolCallRecord(raw) {
5445
6547
  }
5446
6548
  function readToolCallRecords(paths) {
5447
6549
  const records = [];
5448
- for (const file of paths) records.push(...toolCallRecordsIn(fs10.readFileSync(file, "utf8"), file));
6550
+ for (const file of paths) records.push(...toolCallRecordsIn(fs12.readFileSync(file, "utf8"), file));
5449
6551
  return records;
5450
6552
  }
5451
6553
  function toolCallRecordsIn(text2, where) {
@@ -5481,7 +6583,7 @@ async function emit(sink, record) {
5481
6583
  return;
5482
6584
  }
5483
6585
  if (typeof sink === "string") {
5484
- fs10.appendFileSync(sink, JSON.stringify(record) + "\n");
6586
+ fs12.appendFileSync(sink, JSON.stringify(record) + "\n");
5485
6587
  return;
5486
6588
  }
5487
6589
  if (typeof sink === "function") {
@@ -5561,7 +6663,7 @@ async function ingest(world, records, options = {}) {
5561
6663
  const mode = options.mode ?? "append";
5562
6664
  const dryRun = Boolean(options.dryRun);
5563
6665
  const creds = credentialsOf(options);
5564
- const local = fs10.existsSync(world) && fs10.statSync(world).isDirectory();
6666
+ const local = fs12.existsSync(world) && fs12.statSync(world).isDirectory();
5565
6667
  const map = options.map === void 0 ? void 0 : options.map;
5566
6668
  let rows = null;
5567
6669
  let stderr = "";
@@ -5577,9 +6679,9 @@ async function ingest(world, records, options = {}) {
5577
6679
  if (!creds) throw new Error("Gateway keys missing: set GATEWAY_PUBLIC_KEY / GATEWAY_SECRET_KEY (or pass publicKey/secretKey).");
5578
6680
  const { pull: pull2 } = await Promise.resolve().then(() => (init_hub(), hub_exports));
5579
6681
  const slug = world.split("@", 1)[0];
5580
- const scratch = fs10.mkdtempSync(path9.join(os3.tmpdir(), "gateway-ingest-"));
6682
+ const scratch = fs12.mkdtempSync(path11.join(os3.tmpdir(), "gateway-ingest-"));
5581
6683
  try {
5582
- const pulled = await pull2(world, path9.join(scratch, slug), options);
6684
+ const pulled = await pull2(world, path11.join(scratch, slug), options);
5583
6685
  let report;
5584
6686
  let projected;
5585
6687
  if (rows === null) {
@@ -5600,7 +6702,7 @@ async function ingest(world, records, options = {}) {
5600
6702
  if (status.entityCounts) report.entityCounts = status.entityCounts;
5601
6703
  return report;
5602
6704
  } finally {
5603
- fs10.rmSync(scratch, { recursive: true, force: true });
6705
+ fs12.rmSync(scratch, { recursive: true, force: true });
5604
6706
  }
5605
6707
  }
5606
6708
  async function ingestToolCalls(world, records, options = {}) {
@@ -5663,53 +6765,126 @@ var init_ingest = __esm({
5663
6765
  }
5664
6766
  });
5665
6767
 
5666
- // src/worlds/sandbox.ts
5667
- function parseSlugRef(slugRef) {
5668
- const at = slugRef.indexOf("@");
5669
- if (at === -1) return { slug: slugRef };
5670
- return { slug: slugRef.slice(0, at), ref: slugRef.slice(at + 1) };
5671
- }
5672
- var sid, WorldSandboxClient;
5673
- var init_sandbox = __esm({
5674
- "src/worlds/sandbox.ts"() {
6768
+ // src/worlds/editSessions.ts
6769
+ var WORLDS, WorldEditClient;
6770
+ var init_editSessions = __esm({
6771
+ "src/worlds/editSessions.ts"() {
5675
6772
  "use strict";
5676
6773
  init_worlds();
5677
- sid = encodeURIComponent;
5678
- WorldSandboxClient = class {
6774
+ WORLDS = "/api/public/worlds";
6775
+ WorldEditClient = class {
5679
6776
  constructor(options = {}) {
5680
6777
  this.options = options;
5681
6778
  }
5682
- open(target) {
5683
- return apiRequest(this.options, "POST", "/api/public/benchmark-containers/sandboxes", target);
6779
+ options;
6780
+ /** The credential's current session and the world's newest-first sessions. */
6781
+ list(slug, query = {}) {
6782
+ const qs3 = new URLSearchParams();
6783
+ if (query.status) qs3.set("status", query.status);
6784
+ if (query.limit !== void 0) qs3.set("limit", String(query.limit));
6785
+ const suffix = qs3.size ? `?${qs3.toString()}` : "";
6786
+ return apiRequest(this.options, "GET", `${WORLDS}/${encodeURIComponent(slug)}/edits${suffix}`);
5684
6787
  }
5685
- status(sandboxId) {
5686
- return apiRequest(this.options, "GET", `/api/public/benchmark-containers/sandboxes/${sid(sandboxId)}`);
6788
+ /** Seal a session into a version on main (the credential's current one when `sessionId` is omitted). */
6789
+ close(slug, input = {}) {
6790
+ return apiRequest(this.options, "POST", `${WORLDS}/${encodeURIComponent(slug)}/edits/close`, input);
5687
6791
  }
5688
- async read(sandboxId, filePath) {
5689
- const res = await apiRequest(
6792
+ /** Drop the session's private branch without making a version. */
6793
+ discard(slug, input = {}) {
6794
+ return apiRequest(this.options, "POST", `${WORLDS}/${encodeURIComponent(slug)}/edits/discard`, input);
6795
+ }
6796
+ /** Undo a sealed session (source and data) as a new sealed session. */
6797
+ rollback(slug, input) {
6798
+ return apiRequest(this.options, "POST", `${WORLDS}/${encodeURIComponent(slug)}/edits/rollback`, input);
6799
+ }
6800
+ };
6801
+ }
6802
+ });
6803
+
6804
+ // src/worlds/dryRun.ts
6805
+ var DRY_RUN_KIND, DRY_RUN_AGENT, STATUS_WAIT_CAP_SECONDS, cid, HostedDryRunClient, DryRunOutcome;
6806
+ var init_dryRun = __esm({
6807
+ "src/worlds/dryRun.ts"() {
6808
+ "use strict";
6809
+ init_worlds();
6810
+ DRY_RUN_KIND = "dry-run";
6811
+ DRY_RUN_AGENT = "oracle";
6812
+ STATUS_WAIT_CAP_SECONDS = 50;
6813
+ cid = (id) => `/api/public/environments/${encodeURIComponent(id)}`;
6814
+ HostedDryRunClient = class {
6815
+ constructor(options = {}) {
6816
+ this.options = options;
6817
+ }
6818
+ options;
6819
+ /** Dispatch ONE oracle job for `task` on `containerId` (a container id, not a slug); pins `versionId` when given. */
6820
+ dispatch(target) {
6821
+ return apiRequest(
5690
6822
  this.options,
5691
- "GET",
5692
- `/api/public/benchmark-containers/sandboxes/${sid(sandboxId)}/file?path=${encodeURIComponent(filePath)}`
6823
+ "POST",
6824
+ `${cid(target.containerId)}/dry-run`,
6825
+ {
6826
+ task: target.task,
6827
+ ...target.versionId ? { versionId: target.versionId } : {}
6828
+ }
5693
6829
  );
5694
- return { path: res.path, size: res.size, bytes: Buffer.from(res.contentBase64, "base64") };
5695
- }
5696
- write(sandboxId, filePath, bytes) {
5697
- return apiRequest(this.options, "PUT", `/api/public/benchmark-containers/sandboxes/${sid(sandboxId)}/file`, {
5698
- path: filePath,
5699
- contentBase64: bytes.toString("base64")
5700
- });
5701
6830
  }
5702
- exec(sandboxId, input) {
5703
- return apiRequest(this.options, "POST", `/api/public/benchmark-containers/sandboxes/${sid(sandboxId)}/exec`, input);
6831
+ /** One status read, blocking server-side for up to `waitSeconds` (capped). */
6832
+ status(runId, waitSeconds = 0) {
6833
+ const wait = Math.max(
6834
+ 0,
6835
+ Math.min(Math.floor(waitSeconds), STATUS_WAIT_CAP_SECONDS)
6836
+ );
6837
+ const suffix = wait ? `?waitSeconds=${wait}` : "";
6838
+ return apiRequest(
6839
+ this.options,
6840
+ "GET",
6841
+ `/api/public/environments/runs/${encodeURIComponent(runId)}${suffix}`
6842
+ );
5704
6843
  }
5705
- check(sandboxId) {
5706
- return apiRequest(this.options, "POST", `/api/public/benchmark-containers/sandboxes/${sid(sandboxId)}/check`, {});
6844
+ /** Poll until the run settles or `timeoutSeconds` pass; the last verdict either way. */
6845
+ async settle(runId, opts) {
6846
+ const now = opts.now ?? Date.now;
6847
+ const sleep3 = opts.sleep ?? ((ms) => new Promise((resolve11) => setTimeout(resolve11, ms)));
6848
+ const deadline = now() + opts.timeoutSeconds * 1e3;
6849
+ for (; ; ) {
6850
+ const budget = Math.floor(
6851
+ Math.min(45, Math.max(0, (deadline - now()) / 1e3))
6852
+ );
6853
+ const asked = now();
6854
+ const verdict = await this.status(runId, budget);
6855
+ if (verdict.settled || now() >= deadline) return verdict;
6856
+ opts.onProgress?.(verdict);
6857
+ if (now() - asked < 1e3) await sleep3(1e3);
6858
+ }
5707
6859
  }
5708
- commit(sandboxId, input) {
5709
- return apiRequest(this.options, "POST", `/api/public/benchmark-containers/sandboxes/${sid(sandboxId)}/commit`, input);
6860
+ };
6861
+ DryRunOutcome = class {
6862
+ constructor(verdict) {
6863
+ this.verdict = verdict;
6864
+ }
6865
+ verdict;
6866
+ get settlement() {
6867
+ return this.verdict.dryRun?.settlement ?? null;
6868
+ }
6869
+ /** Why the dry run did not pass, or null when it did. */
6870
+ reason() {
6871
+ if (!this.verdict.settled) return `still running after the wait`;
6872
+ const settlement = this.settlement;
6873
+ if (!settlement)
6874
+ return `the runner filed no settlement (${this.verdict.status})`;
6875
+ const lastErrorLine = settlement.errorTail?.trim().split("\n").at(-1) || null;
6876
+ if (settlement.exitCode !== null && settlement.exitCode !== 0)
6877
+ return `the runner failed (exit ${settlement.exitCode}): ${lastErrorLine ?? "harbor exited non-zero"}`;
6878
+ if (settlement.reward === null && lastErrorLine)
6879
+ return `the runner failed (exit ?): ${lastErrorLine}`;
6880
+ if (settlement.reward === null)
6881
+ return "ungraded: the grader ran but wrote no reward";
6882
+ if (settlement.reward !== 1)
6883
+ return `the reference solution scored ${settlement.reward}, not 1.0`;
6884
+ return null;
5710
6885
  }
5711
- close(sandboxId) {
5712
- return apiRequest(this.options, "DELETE", `/api/public/benchmark-containers/sandboxes/${sid(sandboxId)}`);
6886
+ passed() {
6887
+ return this.reason() === null;
5713
6888
  }
5714
6889
  };
5715
6890
  }
@@ -5718,23 +6893,53 @@ var init_sandbox = __esm({
5718
6893
  // src/worlds/index.ts
5719
6894
  var worlds_exports = {};
5720
6895
  __export(worlds_exports, {
5721
- ApiError: () => ApiError2,
6896
+ ApiError: () => ApiError,
6897
+ BROWSER_GONE_PATTERNS: () => BROWSER_GONE_PATTERNS,
6898
+ BROWSER_TIERS: () => BROWSER_TIERS,
5722
6899
  BrowserActionRecorder: () => BrowserActionRecorder,
6900
+ BrowserReconnected: () => BrowserReconnected,
6901
+ BrowserReconnector: () => BrowserReconnector,
6902
+ BrowserUnrecoverable: () => BrowserUnrecoverable,
6903
+ CALL_BODY_LIMIT_BYTES: () => CALL_BODY_LIMIT_BYTES,
6904
+ CALL_BODY_LIMIT_LABEL: () => CALL_BODY_LIMIT_LABEL,
5723
6905
  COMPUTER_USE_SPECS: () => COMPUTER_USE_SPECS,
6906
+ CheckoutProvenance: () => CheckoutProvenance,
5724
6907
  DEFAULT_BRANCH: () => DEFAULT_BRANCH,
5725
6908
  DEFAULT_VIEWPORT: () => DEFAULT_VIEWPORT,
6909
+ DRY_RUN_AGENT: () => DRY_RUN_AGENT,
6910
+ DRY_RUN_KIND: () => DRY_RUN_KIND,
6911
+ DetachedPushError: () => DetachedPushError,
6912
+ DryRunOutcome: () => DryRunOutcome,
5726
6913
  EVENT_BATCH_SIZE: () => EVENT_BATCH_SIZE,
5727
6914
  EVENT_FLUSH_INTERVAL_MS: () => EVENT_FLUSH_INTERVAL_MS,
5728
6915
  EVENT_MAX_RETRIES: () => EVENT_MAX_RETRIES,
6916
+ EXPLORATORY_TASK: () => EXPLORATORY_TASK,
6917
+ EXPLORATORY_TASK_SOURCE: () => EXPLORATORY_TASK_SOURCE,
5729
6918
  GatewayEvalsClient: () => GatewayEvalsClient,
6919
+ HostedDryRunClient: () => HostedDryRunClient,
6920
+ IDLE_WARNING_MINUTES: () => IDLE_WARNING_MINUTES,
6921
+ NO_GRADER_REASON: () => NO_GRADER_REASON,
6922
+ PLATFORM_TIMEOUT_DEFAULT_MS: () => PLATFORM_TIMEOUT_DEFAULT_MS,
6923
+ PLATFORM_TIMEOUT_ENV: () => PLATFORM_TIMEOUT_ENV,
6924
+ PlatformTransport: () => PlatformTransport,
5730
6925
  PushSlugConflict: () => PushSlugConflict,
6926
+ RECOVER_BUDGET_MS: () => RECOVER_BUDGET_MS,
6927
+ SANDBOX_REQUEST_TIMEOUT_MS: () => SANDBOX_REQUEST_TIMEOUT_MS,
6928
+ SESSION_STATES: () => SESSION_STATES,
6929
+ STATUS_WAIT_CAP_SECONDS: () => STATUS_WAIT_CAP_SECONDS,
5731
6930
  STRIP_PREFIX: () => STRIP_PREFIX,
5732
6931
  SURFACE_KINDS: () => SURFACE_KINDS,
6932
+ SecretScrubber: () => SecretScrubber,
5733
6933
  TRANSFORMS: () => TRANSFORMS,
5734
6934
  TaskRun: () => TaskRun,
5735
6935
  TaskSessions: () => TaskSessions,
6936
+ TransportCause: () => TransportCause,
6937
+ UnreachableError: () => UnreachableError,
6938
+ VERIFIER_REWARD_PREFIX: () => VERIFIER_REWARD_PREFIX,
5736
6939
  WHITESPACE: () => WHITESPACE,
5737
6940
  WorldBrowser: () => WorldBrowser,
6941
+ WorldCallTooLarge: () => WorldCallTooLarge,
6942
+ WorldEditClient: () => WorldEditClient,
5738
6943
  WorldSandboxClient: () => WorldSandboxClient,
5739
6944
  WorldSession: () => WorldSession,
5740
6945
  WorldSessionCallError: () => WorldSessionCallError,
@@ -5746,12 +6951,16 @@ __export(worlds_exports, {
5746
6951
  apiRequest: () => apiRequest,
5747
6952
  applyTransforms: () => applyTransforms,
5748
6953
  archiveMode: () => archiveMode,
6954
+ assertBrowserTier: () => assertBrowserTier,
6955
+ assertTaskRef: () => assertTaskRef,
5749
6956
  attachManifest: () => attachManifest,
5750
6957
  attachSession: () => attachSession,
5751
6958
  attachTask: () => attachTask,
5752
6959
  buildFileManifest: () => buildFileManifest,
5753
6960
  buildSourceTarball: () => buildSourceTarball,
5754
6961
  captureToolCalls: () => captureToolCalls,
6962
+ checkoutIdentity: () => checkoutIdentity,
6963
+ closeConnection: () => closeConnection,
5755
6964
  collectArchiveRelPaths: () => collectArchiveRelPaths,
5756
6965
  computeContentHash: () => computeContentHash,
5757
6966
  computerUseToolkit: () => computerUseToolkit,
@@ -5765,13 +6974,18 @@ __export(worlds_exports, {
5765
6974
  getRun: () => getRun,
5766
6975
  getTask: () => getTask,
5767
6976
  hashForm: () => hashForm,
6977
+ idleWarning: () => idleWarning,
5768
6978
  ingest: () => ingest,
5769
6979
  ingestToolCalls: () => ingestToolCalls,
6980
+ isBrowserGone: () => isBrowserGone,
6981
+ isSandboxImportPending: () => isSandboxImportPending,
5770
6982
  isTaskIdRef: () => isTaskIdRef,
5771
6983
  isTaskManifest: () => isTaskManifest,
5772
6984
  isTaskSpec: () => isTaskSpec,
5773
6985
  listEnvSecretKeys: () => listEnvSecretKeys,
5774
6986
  listRunConfigs: () => listRunConfigs,
6987
+ listRuns: () => listRuns,
6988
+ listSessions: () => listSessions,
5775
6989
  listTaskSessions: () => listTaskSessions,
5776
6990
  listTasks: () => listTasks,
5777
6991
  localTreeState: () => localTreeState,
@@ -5783,28 +6997,35 @@ __export(worlds_exports, {
5783
6997
  openTask: () => openTask,
5784
6998
  openWorld: () => openWorld,
5785
6999
  openWorldVersion: () => openWorldVersion,
7000
+ parseErrorBody: () => parseErrorBody,
5786
7001
  parseSlugRef: () => parseSlugRef,
5787
7002
  parseToolCallRecord: () => parseToolCallRecord,
5788
7003
  parseTransform: () => parseTransform,
5789
7004
  parseWorldTaskRefs: () => parseWorldTaskRefs,
7005
+ platformTimeoutMs: () => platformTimeoutMs,
5790
7006
  preserveForm: () => preserveForm,
5791
7007
  propose: () => propose,
5792
7008
  pull: () => pull,
5793
7009
  push: () => push,
7010
+ pushBranch: () => pushBranch,
5794
7011
  pushSlug: () => pushSlug,
5795
7012
  pyText: () => pyText,
5796
7013
  queryRows: () => queryRows,
5797
7014
  queryRowsSearch: () => queryRowsSearch,
5798
7015
  readLocalMeta: () => readLocalMeta,
5799
7016
  readToolCallRecords: () => readToolCallRecords,
7017
+ rebaseConflicts: () => rebaseConflicts,
5800
7018
  redactActionArgs: () => redactActionArgs,
5801
7019
  redactionOf: () => redactionOf,
7020
+ releaseConnection: () => releaseConnection,
5802
7021
  resolveBrowserMode: () => resolveBrowserMode,
5803
7022
  resolvePushSlug: () => resolvePushSlug,
5804
7023
  roundForm: () => roundForm,
5805
7024
  runSessions: () => runSessions,
7025
+ runSet: () => runSet,
5806
7026
  runTask: () => runTask,
5807
7027
  schemaFromSignature: () => schemaFromSignature,
7028
+ serializeCallBody: () => serializeCallBody,
5808
7029
  sessionToolObservations: () => sessionToolObservations,
5809
7030
  setEnvSecret: () => setEnvSecret,
5810
7031
  shapeText: () => shapeText,
@@ -5816,6 +7037,7 @@ __export(worlds_exports, {
5816
7037
  toolCallsFromObservations: () => toolCallsFromObservations,
5817
7038
  uiEntryUrl: () => uiEntryUrl,
5818
7039
  uiUrl: () => uiUrl,
7040
+ uncommittedPaths: () => uncommittedPaths,
5819
7041
  updateTask: () => updateTask,
5820
7042
  upsertRunConfig: () => upsertRunConfig,
5821
7043
  validateTask: () => validateTask,
@@ -5835,19 +7057,29 @@ function resolveEnv(options) {
5835
7057
  }
5836
7058
  return { host: host.replace(/\/+$/, ""), publicKey, secretKey };
5837
7059
  }
5838
- async function apiRequest(options, method, path14, body) {
5839
- const { host, publicKey, secretKey } = resolveEnv(options);
5840
- const res = await fetch(`${host}${path14}`, {
5841
- method,
5842
- headers: {
5843
- "content-type": "application/json",
5844
- authorization: "Basic " + Buffer.from(`${publicKey}:${secretKey}`).toString("base64")
5845
- },
5846
- ...body === void 0 ? {} : { body: JSON.stringify(body) }
5847
- });
5848
- const text2 = await res.text();
5849
- if (!res.ok) throw new ApiError2(res.status, method, path14, text2.slice(0, 400));
5850
- return JSON.parse(text2);
7060
+ function parseErrorBody(text2, limit = 600) {
7061
+ const raw = { detail: text2.slice(0, limit), code: null };
7062
+ let parsed;
7063
+ try {
7064
+ parsed = JSON.parse(text2);
7065
+ } catch {
7066
+ return raw;
7067
+ }
7068
+ if (parsed === null || typeof parsed !== "object") return raw;
7069
+ const { message, code } = parsed;
7070
+ const stableCode = typeof code === "string" ? code : null;
7071
+ if (typeof message !== "string") return { ...raw, code: stableCode };
7072
+ if (stableCode === null)
7073
+ return { detail: message.slice(0, limit), code: null };
7074
+ return {
7075
+ detail: `${message} (${stableCode})`.slice(0, limit),
7076
+ code: stableCode
7077
+ };
7078
+ }
7079
+ async function apiRequest(options, method, path16, body, init3 = {}) {
7080
+ const reply = await new PlatformTransport(resolveEnv(options)).send(method, path16, body, init3);
7081
+ if (!reply.ok) throw new ApiError(reply.status, method, path16, reply.text);
7082
+ return JSON.parse(reply.text);
5851
7083
  }
5852
7084
  async function setEnvSecret(slug, key2, value, options = {}) {
5853
7085
  return apiRequest(
@@ -5917,6 +7149,19 @@ async function getRun(runId, options = {}) {
5917
7149
  `/api/public/benchmark-containers/runs/${encodeURIComponent(runId)}`
5918
7150
  );
5919
7151
  }
7152
+ async function listRuns(filter = {}, options = {}) {
7153
+ const params = new URLSearchParams();
7154
+ if (filter.slug) params.set("slug", filter.slug);
7155
+ if (filter.status) params.set("status", filter.status);
7156
+ if (filter.limit !== void 0) params.set("limit", String(filter.limit));
7157
+ const qs3 = params.toString();
7158
+ const res = await apiRequest(
7159
+ options,
7160
+ "GET",
7161
+ `/api/public/benchmark-containers/runs${qs3 ? `?${qs3}` : ""}`
7162
+ );
7163
+ return res.runs;
7164
+ }
5920
7165
  async function waitForRun(runId, opts = {}) {
5921
7166
  const deadline = Date.now() + (opts.timeoutMinutes ?? 45) * 6e4;
5922
7167
  for (; ; ) {
@@ -5928,7 +7173,7 @@ async function waitForRun(runId, opts = {}) {
5928
7173
  );
5929
7174
  opts.onTick?.(run);
5930
7175
  await new Promise(
5931
- (resolve10) => setTimeout(resolve10, (opts.intervalSeconds ?? 20) * 1e3)
7176
+ (resolve11) => setTimeout(resolve11, (opts.intervalSeconds ?? 20) * 1e3)
5932
7177
  );
5933
7178
  }
5934
7179
  }
@@ -5951,8 +7196,8 @@ function detectProvenance() {
5951
7196
  }
5952
7197
  if (!out.branch || !out.commit) {
5953
7198
  try {
5954
- const { execFileSync } = __require("child_process");
5955
- const git = (args) => execFileSync("git", args, {
7199
+ const { execFileSync: execFileSync2 } = __require("child_process");
7200
+ const git = (args) => execFileSync2("git", args, {
5956
7201
  encoding: "utf-8",
5957
7202
  stdio: ["ignore", "pipe", "ignore"]
5958
7203
  }).toString().trim();
@@ -6010,16 +7255,24 @@ async function resolveWorld(slugRef, slug, ref, pin, options) {
6010
7255
  }
6011
7256
  return world;
6012
7257
  }
6013
- var ApiError2, WorldTask, WorldSet;
7258
+ var ApiError, WorldTask, WorldSet;
6014
7259
  var init_worlds = __esm({
6015
7260
  "src/worlds/index.ts"() {
6016
7261
  "use strict";
7262
+ init_transport();
7263
+ init_transport();
6017
7264
  init_session();
7265
+ init_sessionList();
7266
+ init_sessionContract();
7267
+ init_taskRef();
6018
7268
  init_tasks();
6019
7269
  init_taskSessions();
6020
7270
  init_taskRun();
7271
+ init_setRun();
7272
+ init_checkoutProvenance();
6021
7273
  init_evals();
6022
7274
  init_browser();
7275
+ init_browserReconnect();
6023
7276
  init_hub();
6024
7277
  init_validate();
6025
7278
  init_describe();
@@ -6029,12 +7282,20 @@ var init_worlds = __esm({
6029
7282
  init_migrate();
6030
7283
  init_ingest();
6031
7284
  init_sandbox();
6032
- ApiError2 = class extends Error {
6033
- constructor(status, method, path14, body) {
6034
- super(`${method} ${path14} -> ${status}: ${body}`);
7285
+ init_editSessions();
7286
+ init_dryRun();
7287
+ ApiError = class extends Error {
7288
+ constructor(status, method, path16, text2) {
7289
+ const parsed = parseErrorBody(text2);
7290
+ super(`${method} ${path16} -> ${status}: ${parsed.detail}`);
6035
7291
  this.status = status;
7292
+ this.text = text2;
6036
7293
  this.name = "ApiError";
7294
+ this.code = parsed.code;
6037
7295
  }
7296
+ status;
7297
+ text;
7298
+ code;
6038
7299
  };
6039
7300
  WorldTask = class {
6040
7301
  constructor(world, name, variant) {
@@ -6042,6 +7303,9 @@ var init_worlds = __esm({
6042
7303
  this.name = name;
6043
7304
  this.variant = variant;
6044
7305
  }
7306
+ world;
7307
+ name;
7308
+ variant;
6045
7309
  };
6046
7310
  WorldSet = class {
6047
7311
  constructor(slugRef, slug, ref, version, tasks, options) {
@@ -6052,6 +7316,12 @@ var init_worlds = __esm({
6052
7316
  this.tasks = tasks;
6053
7317
  this.options = options;
6054
7318
  }
7319
+ slugRef;
7320
+ slug;
7321
+ ref;
7322
+ version;
7323
+ tasks;
7324
+ options;
6055
7325
  task(variant) {
6056
7326
  const hit = this.tasks.find(
6057
7327
  (t) => t.variant === variant || t.name.includes(variant)
@@ -6075,6 +7345,7 @@ var init_worlds = __esm({
6075
7345
  versionId: this.version.versionId,
6076
7346
  reuseWarm: opts.reuseWarm,
6077
7347
  surfaces: opts.surfaces,
7348
+ browserTier: opts.browserTier,
6078
7349
  options: this.options
6079
7350
  });
6080
7351
  }
@@ -6671,8 +7942,8 @@ var GatewayContext = class _GatewayContext {
6671
7942
  }
6672
7943
  return resolved;
6673
7944
  }
6674
- async requestJson(method, path14, payload) {
6675
- const response = await fetch(`${this.host}${path14}`, {
7945
+ async requestJson(method, path16, payload) {
7946
+ const response = await fetch(`${this.host}${path16}`, {
6676
7947
  method,
6677
7948
  headers: {
6678
7949
  Authorization: this.authHeader(),
@@ -6683,7 +7954,7 @@ var GatewayContext = class _GatewayContext {
6683
7954
  const text2 = await response.text();
6684
7955
  const body = text2 ? safeJson(text2) : {};
6685
7956
  if (!response.ok) {
6686
- const message = typeof body.message === "string" ? body.message : `Gateway API ${response.status} on ${path14}`;
7957
+ const message = typeof body.message === "string" ? body.message : `Gateway API ${response.status} on ${path16}`;
6687
7958
  if (response.status === 409) {
6688
7959
  throw new GatewayContextConflictError(
6689
7960
  message,
@@ -6692,7 +7963,7 @@ var GatewayContext = class _GatewayContext {
6692
7963
  }
6693
7964
  throw new GatewayContextError(message);
6694
7965
  }
6695
- this.log("%s %s -> %s", method, path14, response.status);
7966
+ this.log("%s %s -> %s", method, path16, response.status);
6696
7967
  return body;
6697
7968
  }
6698
7969
  authHeader() {
@@ -6799,11 +8070,11 @@ function primaryPathForKind(kind, snapshot) {
6799
8070
  const preferred = kind === "agent" ? "AGENTS.md" : kind === "prompt" ? "PROMPT.md" : kind === "skill" ? "SKILL.md" : "MEMORY.md";
6800
8071
  if (readFile(snapshot, preferred)) return preferred;
6801
8072
  return Object.entries(snapshot.files).find(
6802
- ([path14, entry]) => entry.type === "file" && path14.endsWith(".md")
8073
+ ([path16, entry]) => entry.type === "file" && path16.endsWith(".md")
6803
8074
  )?.[0] ?? null;
6804
8075
  }
6805
- function parseJsonFile(snapshot, path14) {
6806
- const content = readFile(snapshot, path14);
8076
+ function parseJsonFile(snapshot, path16) {
8077
+ const content = readFile(snapshot, path16);
6807
8078
  if (!content) return {};
6808
8079
  try {
6809
8080
  const parsed = JSON.parse(content);
@@ -6812,8 +8083,8 @@ function parseJsonFile(snapshot, path14) {
6812
8083
  return {};
6813
8084
  }
6814
8085
  }
6815
- function readFile(snapshot, path14) {
6816
- const entry = snapshot.files[path14];
8086
+ function readFile(snapshot, path16) {
8087
+ const entry = snapshot.files[path16];
6817
8088
  return entry?.type === "file" ? entry.content : null;
6818
8089
  }
6819
8090
  function provenanceFor(snapshot, label) {
@@ -6915,16 +8186,16 @@ var GatewayMemory = class _GatewayMemory {
6915
8186
  `/api/public/context/memory/${encodeIdentifier2(identifier)}${suffix}`
6916
8187
  );
6917
8188
  }
6918
- async read(target, path14, options = {}) {
8189
+ async read(target, path16, options = {}) {
6919
8190
  const snapshot = typeof target === "string" ? await this.pull(target, options) : target;
6920
- const file = snapshot.files[path14];
8191
+ const file = snapshot.files[path16];
6921
8192
  return file?.type === "file" ? file.content : null;
6922
8193
  }
6923
- async write(target, path14, content, options = {}) {
8194
+ async write(target, path16, content, options = {}) {
6924
8195
  const snapshot = typeof target === "string" ? await this.pull(target) : target;
6925
8196
  return this.push(snapshot.repo.repoHandle, {
6926
8197
  files: {
6927
- [path14]: {
8198
+ [path16]: {
6928
8199
  content,
6929
8200
  ...options.mimeType ? { mimeType: options.mimeType } : {}
6930
8201
  }
@@ -6934,10 +8205,10 @@ var GatewayMemory = class _GatewayMemory {
6934
8205
  ...runtimeContextPayload2(options)
6935
8206
  });
6936
8207
  }
6937
- async delete(target, path14, options = {}) {
8208
+ async delete(target, path16, options = {}) {
6938
8209
  const snapshot = typeof target === "string" ? await this.pull(target) : target;
6939
8210
  return this.push(snapshot.repo.repoHandle, {
6940
- files: { [path14]: null },
8211
+ files: { [path16]: null },
6941
8212
  parentCommit: options.parentCommit ?? snapshot.commit.commitHash,
6942
8213
  message: options.message,
6943
8214
  ...runtimeContextPayload2(options)
@@ -6950,8 +8221,8 @@ var GatewayMemory = class _GatewayMemory {
6950
8221
  payload
6951
8222
  );
6952
8223
  }
6953
- async requestJson(method, path14, payload) {
6954
- const response = await fetch(`${this.host}${path14}`, {
8224
+ async requestJson(method, path16, payload) {
8225
+ const response = await fetch(`${this.host}${path16}`, {
6955
8226
  method,
6956
8227
  headers: {
6957
8228
  Authorization: this.authHeader(),
@@ -6962,7 +8233,7 @@ var GatewayMemory = class _GatewayMemory {
6962
8233
  const text2 = await response.text();
6963
8234
  const body = text2 ? safeJson2(text2) : {};
6964
8235
  if (!response.ok) {
6965
- const message = typeof body.message === "string" ? body.message : `Gateway API ${response.status} on ${path14}`;
8236
+ const message = typeof body.message === "string" ? body.message : `Gateway API ${response.status} on ${path16}`;
6966
8237
  if (response.status === 409) {
6967
8238
  throw new GatewayMemoryConflictError(
6968
8239
  message,
@@ -6971,7 +8242,7 @@ var GatewayMemory = class _GatewayMemory {
6971
8242
  }
6972
8243
  throw new GatewayMemoryError(message);
6973
8244
  }
6974
- this.log("%s %s -> %s", method, path14, response.status);
8245
+ this.log("%s %s -> %s", method, path16, response.status);
6975
8246
  return body;
6976
8247
  }
6977
8248
  authHeader() {
@@ -7133,10 +8404,10 @@ var PersonasClient = class _PersonasClient {
7133
8404
  done: Boolean(payload.done)
7134
8405
  };
7135
8406
  }
7136
- async requestJson(method, path14, payload) {
8407
+ async requestJson(method, path16, payload) {
7137
8408
  let response;
7138
8409
  try {
7139
- response = await fetch(`${this.host}${path14}`, {
8410
+ response = await fetch(`${this.host}${path16}`, {
7140
8411
  method,
7141
8412
  headers: {
7142
8413
  Authorization: this.authHeader(),
@@ -7147,7 +8418,7 @@ var PersonasClient = class _PersonasClient {
7147
8418
  });
7148
8419
  } catch (error) {
7149
8420
  const reason = error instanceof Error ? error.message : String(error);
7150
- throw new PersonaError(`${method} ${path14} failed: ${reason}`, {
8421
+ throw new PersonaError(`${method} ${path16} failed: ${reason}`, {
7151
8422
  cause: error
7152
8423
  });
7153
8424
  }
@@ -7155,10 +8426,10 @@ var PersonasClient = class _PersonasClient {
7155
8426
  if (!response.ok) {
7156
8427
  const detail = text2.slice(0, 500);
7157
8428
  throw new PersonaError(
7158
- `${method} ${path14} failed (${response.status}): ${detail}`
8429
+ `${method} ${path16} failed (${response.status}): ${detail}`
7159
8430
  );
7160
8431
  }
7161
- this.log("%s %s -> %s", method, path14, response.status);
8432
+ this.log("%s %s -> %s", method, path16, response.status);
7162
8433
  return safeJson3(text2);
7163
8434
  }
7164
8435
  authHeader() {
@@ -7383,10 +8654,10 @@ var SessionRecording = class _SessionRecording {
7383
8654
  };
7384
8655
  }
7385
8656
  /** Dump the full session as a JSON fixture (for regression tests). */
7386
- toFixture(path14) {
7387
- mkdirSync(dirname(path14), { recursive: true });
7388
- writeFileSync(path14, JSON.stringify(this.toJSON(), null, 2), "utf-8");
7389
- return path14;
8657
+ toFixture(path16) {
8658
+ mkdirSync(dirname(path16), { recursive: true });
8659
+ writeFileSync(path16, JSON.stringify(this.toJSON(), null, 2), "utf-8");
8660
+ return path16;
7390
8661
  }
7391
8662
  static fromApi(raw) {
7392
8663
  return new _SessionRecording({
@@ -8221,7 +9492,7 @@ function randomHex() {
8221
9492
  return crypto.randomUUID().replace(/-/g, "");
8222
9493
  }
8223
9494
  function sleep(ms) {
8224
- return new Promise((resolve10) => setTimeout(resolve10, ms));
9495
+ return new Promise((resolve11) => setTimeout(resolve11, ms));
8225
9496
  }
8226
9497
  var replay = {
8227
9498
  suite,
@@ -8308,7 +9579,7 @@ var GatewaySecurity = class _GatewaySecurity {
8308
9579
  const descriptors = entries.map(
8309
9580
  ([key2, tool]) => this.describeTool(key2, tool, options)
8310
9581
  );
8311
- const resolve10 = await this.resolveToolset({
9582
+ const resolve11 = await this.resolveToolset({
8312
9583
  agent: this.agent,
8313
9584
  toolsetId: options.toolsetId,
8314
9585
  toolsetName: options.toolsetName,
@@ -8318,8 +9589,8 @@ var GatewaySecurity = class _GatewaySecurity {
8318
9589
  });
8319
9590
  const securedEntries = entries.flatMap(([key2, tool]) => {
8320
9591
  const descriptor = descriptors.find((item) => item.name === key2);
8321
- if (!this.shouldExposeTool(resolve10, descriptor.id)) {
8322
- this.log("Hiding tool %s in %s mode", descriptor.id, resolve10.mode);
9592
+ if (!this.shouldExposeTool(resolve11, descriptor.id)) {
9593
+ this.log("Hiding tool %s in %s mode", descriptor.id, resolve11.mode);
8323
9594
  return [];
8324
9595
  }
8325
9596
  return [
@@ -8329,7 +9600,7 @@ var GatewaySecurity = class _GatewaySecurity {
8329
9600
  toolId: descriptor.id,
8330
9601
  toolsetId: options.toolsetId,
8331
9602
  context: this.normalizeContext(options.context),
8332
- resolve: resolve10
9603
+ resolve: resolve11
8333
9604
  })
8334
9605
  ]
8335
9606
  ];
@@ -8417,8 +9688,8 @@ var GatewaySecurity = class _GatewaySecurity {
8417
9688
  );
8418
9689
  }
8419
9690
  }
8420
- async postJson(path14, payload) {
8421
- const response = await fetch(`${this.host}${path14}`, {
9691
+ async postJson(path16, payload) {
9692
+ const response = await fetch(`${this.host}${path16}`, {
8422
9693
  method: "POST",
8423
9694
  headers: {
8424
9695
  Authorization: this.authHeader(),
@@ -8429,7 +9700,7 @@ var GatewaySecurity = class _GatewaySecurity {
8429
9700
  if (!response.ok) {
8430
9701
  const body = await response.text();
8431
9702
  throw new GatewaySecurityError(
8432
- `Gateway API ${response.status} on ${path14}: ${body || response.statusText}`
9703
+ `Gateway API ${response.status} on ${path16}: ${body || response.statusText}`
8433
9704
  );
8434
9705
  }
8435
9706
  return await response.json();
@@ -8444,9 +9715,9 @@ var GatewaySecurity = class _GatewaySecurity {
8444
9715
  metadata: options.toolMetadata?.[key2] ?? {}
8445
9716
  };
8446
9717
  }
8447
- shouldExposeTool(resolve10, toolId) {
8448
- if (resolve10.mode === "observe") return true;
8449
- if (resolve10.blockedToolIds.includes(toolId)) return false;
9718
+ shouldExposeTool(resolve11, toolId) {
9719
+ if (resolve11.mode === "observe") return true;
9720
+ if (resolve11.blockedToolIds.includes(toolId)) return false;
8450
9721
  return true;
8451
9722
  }
8452
9723
  normalizeContext(context4) {
@@ -8505,6 +9776,7 @@ __export(files_exports, {
8505
9776
  deleteFile: () => deleteFile,
8506
9777
  downloadFile: () => downloadFile,
8507
9778
  drivePath: () => drivePath,
9779
+ fetchToDrive: () => fetchToDrive,
8508
9780
  getFile: () => getFile,
8509
9781
  isDriveRef: () => isDriveRef,
8510
9782
  iterateFiles: () => iterateFiles,
@@ -8520,8 +9792,8 @@ __export(files_exports, {
8520
9792
  });
8521
9793
  init_worlds();
8522
9794
  import { createHash as createHash9 } from "crypto";
8523
- import * as fs11 from "fs";
8524
- import * as path10 from "path";
9795
+ import * as fs13 from "fs";
9796
+ import * as path12 from "path";
8525
9797
  import { Readable, Transform } from "stream";
8526
9798
  import { pipeline } from "stream/promises";
8527
9799
  var DRIVE_PREFIX = "drive:";
@@ -8561,17 +9833,20 @@ async function openDownload(url) {
8561
9833
  if (!res.ok || !res.body) throw new Error(`download failed: storage answered HTTP ${res.status}`);
8562
9834
  return res;
8563
9835
  }
8564
- async function readFile2(options = {}, filePath) {
9836
+ async function readFile2(options = {}, filePath, limits = {}) {
8565
9837
  const file = await getFile(options, filePath);
9838
+ const size = file.sizeBytes ?? 0;
9839
+ if (limits.maxBytes !== void 0 && size > limits.maxBytes)
9840
+ throw new Error(`${filePath} is ${size} bytes, over the ${limits.maxBytes}-byte limit`);
8566
9841
  const res = await openDownload(file.url);
8567
9842
  return Buffer.from(await res.arrayBuffer());
8568
9843
  }
8569
9844
  async function downloadFile(options = {}, filePath, outPath, onProgress) {
8570
9845
  const file = await getFile(options, filePath);
8571
9846
  const res = await openDownload(file.url);
8572
- fs11.mkdirSync(path10.dirname(path10.resolve(outPath)), { recursive: true });
9847
+ fs13.mkdirSync(path12.dirname(path12.resolve(outPath)), { recursive: true });
8573
9848
  const source = Readable.fromWeb(res.body);
8574
- await pipeline(source, counting((n) => onProgress?.(n, file.sizeBytes)), fs11.createWriteStream(outPath));
9849
+ await pipeline(source, counting((n) => onProgress?.(n, file.sizeBytes)), fs13.createWriteStream(outPath));
8575
9850
  return { ...file, out: outPath };
8576
9851
  }
8577
9852
  async function requestUpload(options = {}, body) {
@@ -8582,7 +9857,7 @@ async function confirmUpload(options = {}, fileId, ok = true) {
8582
9857
  }
8583
9858
  async function sha256Base64(localPath) {
8584
9859
  const hash = createHash9("sha256");
8585
- for await (const chunk of fs11.createReadStream(localPath)) hash.update(chunk);
9860
+ for await (const chunk of fs13.createReadStream(localPath)) hash.update(chunk);
8586
9861
  return hash.digest("base64");
8587
9862
  }
8588
9863
  var CONTENT_TYPES = {
@@ -8618,7 +9893,7 @@ var CONTENT_TYPES = {
8618
9893
  ".mp4": "video/mp4"
8619
9894
  };
8620
9895
  function contentTypeFor(name) {
8621
- return CONTENT_TYPES[path10.extname(name).toLowerCase()] ?? "application/octet-stream";
9896
+ return CONTENT_TYPES[path12.extname(name).toLowerCase()] ?? "application/octet-stream";
8622
9897
  }
8623
9898
  function counting(report) {
8624
9899
  let seen = 0;
@@ -8645,7 +9920,7 @@ async function putPresigned(uploadUrl, body, headers) {
8645
9920
  if (!res.ok) throw new Error(`upload failed: storage answered HTTP ${res.status}: ${(await res.text()).slice(0, 300)}`);
8646
9921
  }
8647
9922
  async function uploadFile(options = {}, localPath, targetPath, upload = {}) {
8648
- const stat = fs11.statSync(localPath);
9923
+ const stat = fs13.statSync(localPath);
8649
9924
  if (!stat.isFile()) throw new Error(`${localPath} is not a file`);
8650
9925
  if (stat.size === 0) throw new Error(`${localPath} is empty; the drive refuses zero-byte uploads`);
8651
9926
  const contentType = upload.contentType ?? contentTypeFor(localPath);
@@ -8653,7 +9928,7 @@ async function uploadFile(options = {}, localPath, targetPath, upload = {}) {
8653
9928
  const target = drivePath(targetPath);
8654
9929
  const granted = await requestUpload(options, { path: target, contentLength: stat.size, contentType, sha256: sha2562, ...upload.overwrite ? { overwrite: true } : {} });
8655
9930
  try {
8656
- const stream = fs11.createReadStream(localPath).pipe(counting((n) => upload.onProgress?.(n, stat.size)));
9931
+ const stream = fs13.createReadStream(localPath).pipe(counting((n) => upload.onProgress?.(n, stat.size)));
8657
9932
  await putPresigned(granted.uploadUrl, Readable.toWeb(stream), { contentType, contentLength: stat.size, sha256: sha2562 });
8658
9933
  } catch (error) {
8659
9934
  await confirmUpload(options, granted.fileId, false).catch(() => void 0);
@@ -8683,6 +9958,15 @@ async function deleteFile(options = {}, filePath) {
8683
9958
  async function moveFile(options = {}, fromPath, toPath) {
8684
9959
  return apiRequest(options, "POST", `${BASE}/move`, { fromPath: drivePath(fromPath), toPath: drivePath(toPath) });
8685
9960
  }
9961
+ async function fetchToDrive(options = {}, url, targetPath, fetchOptions = {}) {
9962
+ return apiRequest(options, "POST", `${BASE}/fetch`, {
9963
+ url,
9964
+ path: drivePath(targetPath),
9965
+ ...fetchOptions.headers?.length ? { headers: fetchOptions.headers } : {},
9966
+ ...fetchOptions.contentType ? { contentType: fetchOptions.contentType } : {},
9967
+ ...fetchOptions.overwrite ? { overwrite: true } : {}
9968
+ });
9969
+ }
8686
9970
  async function createFolder(options = {}, folderPath) {
8687
9971
  return apiRequest(options, "POST", `${BASE}/folders`, { path: drivePath(folderPath) });
8688
9972
  }
@@ -8704,7 +9988,7 @@ __export(traces_exports, {
8704
9988
  iterateSessions: () => iterateSessions,
8705
9989
  iterateTraces: () => iterateTraces,
8706
9990
  listObservations: () => listObservations,
8707
- listSessions: () => listSessions,
9991
+ listSessions: () => listSessions2,
8708
9992
  listTraces: () => listTraces
8709
9993
  });
8710
9994
  init_worlds();
@@ -8735,11 +10019,11 @@ async function listObservations(options = {}, filters = {}, page = {}) {
8735
10019
  async function* iterateObservations(options = {}, filters = {}, limits = {}) {
8736
10020
  yield* paged((page) => listObservations(options, filters, { page, limit: PAGE_LIMIT2 }), limits.max);
8737
10021
  }
8738
- async function listSessions(options = {}, filters = {}, page = {}) {
10022
+ async function listSessions2(options = {}, filters = {}, page = {}) {
8739
10023
  return apiRequest(options, "GET", `/api/public/sessions${qs2({ ...filters, page: page.page ?? 1, limit: page.limit ?? 50 })}`);
8740
10024
  }
8741
10025
  async function* iterateSessions(options = {}, filters = {}, limits = {}) {
8742
- yield* paged((page) => listSessions(options, filters, { page, limit: PAGE_LIMIT2 }), limits.max);
10026
+ yield* paged((page) => listSessions2(options, filters, { page, limit: PAGE_LIMIT2 }), limits.max);
8743
10027
  }
8744
10028
  async function getSession(options = {}, sessionId, detail = {}) {
8745
10029
  return apiRequest(options, "GET", `/api/public/sessions/${encodeURIComponent(sessionId)}${qs2({ includeIO: detail.includeIO ? "true" : void 0 })}`);
@@ -8909,8 +10193,45 @@ function swapValue(text2, needle, replacement) {
8909
10193
  );
8910
10194
  }
8911
10195
 
10196
+ // src/hooks/standInDigits.ts
10197
+ import { createHash as createHash10 } from "crypto";
10198
+ function standInDigits(realDigits, identityName) {
10199
+ if (!realDigits) return "";
10200
+ const digest = createHash10("sha256").update(`${identityName}:${realDigits}`).digest("hex");
10201
+ let digits = "";
10202
+ for (let i = 0; i < realDigits.length; i++)
10203
+ digits += String(parseInt(digest[i % digest.length], 16) % 10);
10204
+ if (digits !== realDigits) return digits;
10205
+ return String((Number(digits[0]) + 1) % 10) + digits.slice(1);
10206
+ }
10207
+
10208
+ // src/hooks/declared.ts
10209
+ var DeclaredStandIn = class _DeclaredStandIn {
10210
+ alias;
10211
+ variants;
10212
+ constructor(alias, variants = []) {
10213
+ this.alias = typeof alias === "string" && alias.trim() ? alias.trim() : null;
10214
+ this.variants = Array.isArray(variants) ? variants.filter(
10215
+ (v) => typeof v === "string" && v.trim() !== ""
10216
+ ) : [];
10217
+ }
10218
+ static of(entity) {
10219
+ return new _DeclaredStandIn(entity.alias, entity.variants ?? []);
10220
+ }
10221
+ get declared() {
10222
+ return this.alias !== null || this.variants.length > 0;
10223
+ }
10224
+ /** The pairings for `display`: the real value's forms, then every extra spelling in the
10225
+ * same forms, each mapped onto the stand-in. */
10226
+ pairs(real, display, build) {
10227
+ const out = [...build(real, display)];
10228
+ for (const spelling of this.variants) out.push(...build(spelling, display));
10229
+ return out;
10230
+ }
10231
+ };
10232
+
8912
10233
  // src/hooks/alias.ts
8913
- import { createHash as createHash10, createHmac, randomBytes as randomBytes2 } from "crypto";
10234
+ import { createHash as createHash11, createHmac, randomBytes as randomBytes2 } from "crypto";
8914
10235
  var GIVEN = [
8915
10236
  "John",
8916
10237
  "Mary",
@@ -9343,6 +10664,14 @@ function genericPairs(real, fake) {
9343
10664
  }
9344
10665
  return dedupe(out);
9345
10666
  }
10667
+ function pairBuilder(kind) {
10668
+ const builders = {
10669
+ person_name: namePairs,
10670
+ email: emailPairs,
10671
+ phone: phonePairs
10672
+ };
10673
+ return builders[kind] ?? genericPairs;
10674
+ }
9346
10675
  function dedupe(pairs) {
9347
10676
  const seen = /* @__PURE__ */ new Set();
9348
10677
  const out = [];
@@ -9354,7 +10683,12 @@ function dedupe(pairs) {
9354
10683
  }
9355
10684
  return out.sort((a, b) => b[0].length - a[0].length);
9356
10685
  }
10686
+ function isSubject(alias) {
10687
+ return alias.provenance === "seed";
10688
+ }
9357
10689
  var fullName = (identity) => `${identity.given} ${identity.surname}`;
10690
+ var DeclaredOnlyError = class extends Error {
10691
+ };
9358
10692
  var AliasMap = class _AliasMap {
9359
10693
  constructor(runKey, slugs = [], options = {}) {
9360
10694
  this.runKey = runKey;
@@ -9364,7 +10698,14 @@ var AliasMap = class _AliasMap {
9364
10698
  this.publicLayerWins = options.publicLayerWins ?? true;
9365
10699
  this.publicMailboxDomains = options.publicMailboxDomains ?? null;
9366
10700
  this.mintInbound = options.mintInbound ?? [];
10701
+ this.declaredOnly = options.declaredOnly ?? false;
10702
+ if (this.declaredOnly && this.mintInbound.length)
10703
+ throw new DeclaredOnlyError(
10704
+ "declared_only and mint_inbound cannot both be set: nothing is minted on sight"
10705
+ );
9367
10706
  }
10707
+ runKey;
10708
+ slugs;
9368
10709
  aliases = /* @__PURE__ */ new Map();
9369
10710
  identities = /* @__PURE__ */ new Map();
9370
10711
  taken = /* @__PURE__ */ new Set();
@@ -9372,6 +10713,9 @@ var AliasMap = class _AliasMap {
9372
10713
  aliasDigests = /* @__PURE__ */ new Set();
9373
10714
  leaksIn = [];
9374
10715
  leaksOut = [];
10716
+ /** As `leaksIn` / `leaksOut`, for values minted on sight: counted, never a failure. */
10717
+ bystandersIn = [];
10718
+ bystandersOut = [];
9375
10719
  unresolvedOut = [];
9376
10720
  /** Every value minted on sight: `{where, kind, alias}`. */
9377
10721
  found = [];
@@ -9395,6 +10739,20 @@ var AliasMap = class _AliasMap {
9395
10739
  * subject. Off (the default) such a value reaches the agent as it is — the seed
9396
10740
  * list is the whole map. */
9397
10741
  mintInbound;
10742
+ /** Every private seed must carry its own `alias`; a seed without one is refused instead
10743
+ * of getting a generated persona, and nothing is minted on arrival. */
10744
+ declaredOnly;
10745
+ /** `declaredOnly`: refuse a private value that would need a generated persona. */
10746
+ requireDeclared(kind, provenance, declared) {
10747
+ if (!this.declaredOnly || declared?.alias) return;
10748
+ if (provenance === "seed")
10749
+ throw new DeclaredOnlyError(
10750
+ `declared_only: the seed of kind '${kind}' carries no \`alias\`; give every private seed its stand-in or turn declared_only off`
10751
+ );
10752
+ throw new DeclaredOnlyError(
10753
+ `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`
10754
+ );
10755
+ }
9398
10756
  mailboxDomains() {
9399
10757
  if (this.publicMailboxDomains === null) return PUBLIC_MAILBOX_DOMAINS;
9400
10758
  return new Set(this.publicMailboxDomains.map((d) => d.toLowerCase()));
@@ -9464,8 +10822,14 @@ var AliasMap = class _AliasMap {
9464
10822
  return alias2;
9465
10823
  }
9466
10824
  const identityKey = opts.identityKey ?? `${kind}:${canon}`;
10825
+ this.requireDeclared(kind, provenance, opts.declared);
9467
10826
  const identity = this.identityFor(identityKey);
9468
- const [display, variants] = this.derive(kind, real, identity);
10827
+ const [display, variants] = this.derive(
10828
+ kind,
10829
+ real,
10830
+ identity,
10831
+ opts.declared ?? new DeclaredStandIn()
10832
+ );
9469
10833
  const alias = {
9470
10834
  kind,
9471
10835
  canonical: canon,
@@ -9588,7 +10952,15 @@ var AliasMap = class _AliasMap {
9588
10952
  }
9589
10953
  return out;
9590
10954
  }
9591
- derive(kind, real, identity) {
10955
+ /** The stand-in and its pairings. A declared stand-in replaces the generated one; the
10956
+ * kind's own pair builder runs over it and over every declared spelling. */
10957
+ derive(kind, real, identity, declared) {
10958
+ const [display, variants] = this.generated(kind, real, identity);
10959
+ if (!declared.declared) return [display, variants];
10960
+ const chosen = declared.alias ?? display;
10961
+ return [chosen, dedupe(declared.pairs(real, chosen, pairBuilder(kind)))];
10962
+ }
10963
+ generated(kind, real, identity) {
9592
10964
  if (kind === "person_name") {
9593
10965
  const display2 = fullName(identity);
9594
10966
  return [display2, namePairs(real, display2)];
@@ -9675,13 +11047,14 @@ var AliasMap = class _AliasMap {
9675
11047
  for (const entity of entities) {
9676
11048
  const alias = this.mint(entity.type, entity.value, {
9677
11049
  identityKey: entity.identity,
9678
- role: entity.role ?? "private"
11050
+ role: entity.role ?? "private",
11051
+ declared: DeclaredStandIn.of(entity)
9679
11052
  });
9680
11053
  if (alias.role === "private") {
9681
11054
  for (const slug of this.slugs) {
9682
- const standIn = "sha256:" + createHash10("sha256").update(`${slug}:${canonical(alias.kind, alias.display)}`, "utf8").digest("hex");
11055
+ const standIn = "sha256:" + createHash11("sha256").update(`${slug}:${canonical(alias.kind, alias.display)}`, "utf8").digest("hex");
9683
11056
  alias.variants.push([
9684
- "sha256:" + createHash10("sha256").update(`${slug}:${alias.canonical}`, "utf8").digest("hex"),
11057
+ "sha256:" + createHash11("sha256").update(`${slug}:${alias.canonical}`, "utf8").digest("hex"),
9685
11058
  standIn
9686
11059
  ]);
9687
11060
  this.aliasDigests.add(standIn.toLowerCase());
@@ -9803,45 +11176,51 @@ var AliasMap = class _AliasMap {
9803
11176
  /** Requirement 3: count what slipped, do not assume nothing did. The scan is
9804
11177
  * case-folded with whitespace collapsed and walks EVERY variant of every alias,
9805
11178
  * not only the pairs the rewriter used. */
9806
- meter(text2, where) {
9807
- const haystack = folded(text2);
11179
+ /** Every private alias with a real variant of 4+ characters in the folded text,
11180
+ * case subjects first. */
11181
+ surviving(haystack) {
9808
11182
  const pub = this.publicFolded();
11183
+ const found = [];
9809
11184
  for (const alias of this.aliases.values()) {
9810
11185
  if (alias.role === "public") continue;
9811
- for (const [real] of alias.variants) {
9812
- if (real.length >= 4 && !pub.has(folded(real)) && haystack.includes(folded(real))) {
9813
- this.leaksIn.push({
9814
- where,
9815
- kind: alias.kind,
9816
- variant: shorten(real),
9817
- alias: alias.display
9818
- });
9819
- return;
9820
- }
9821
- }
11186
+ const variant = alias.variants.find(
11187
+ ([real]) => real.length >= 4 && !pub.has(folded(real)) && haystack.includes(folded(real))
11188
+ );
11189
+ if (variant !== void 0) found.push([alias, variant[0]]);
9822
11190
  }
11191
+ return [
11192
+ ...found.filter(([a]) => isSubject(a)),
11193
+ ...found.filter(([a]) => !isSubject(a))
11194
+ ];
9823
11195
  }
9824
- /** Requirement 4: the report and the artifacts must contain no real value. */
11196
+ /** A leak is about a CASE SUBJECT (a seeded entity); a value that only arrived in a
11197
+ * result and was given a stand-in on sight is a bystander, counted apart. */
11198
+ meter(text2, where) {
11199
+ const hit = this.surviving(folded(text2))[0];
11200
+ if (hit === void 0) return;
11201
+ const [alias, real] = hit;
11202
+ const rows = isSubject(alias) ? this.leaksIn : this.bystandersIn;
11203
+ rows.push({
11204
+ where,
11205
+ kind: alias.kind,
11206
+ variant: shorten(real),
11207
+ alias: alias.display
11208
+ });
11209
+ }
11210
+ /** Requirement 4: the report and the artifacts must contain no real value OF A CASE
11211
+ * SUBJECT. Bystanders are counted, never returned. */
9825
11212
  scanOutgoing(text2, where) {
9826
- const hits = [];
9827
- const haystack = typeof text2 === "string" ? folded(text2) : "";
9828
- const pub = this.publicFolded();
9829
- for (const alias of this.aliases.values()) {
9830
- if (alias.role === "public") continue;
9831
- for (const [real] of alias.variants) {
9832
- if (real.length >= 4 && !pub.has(folded(real)) && haystack.includes(folded(real))) {
9833
- hits.push({
9834
- check: "leak_outbound",
9835
- where,
9836
- kind: alias.kind,
9837
- alias: alias.display,
9838
- variant: shorten(real)
9839
- });
9840
- break;
9841
- }
9842
- }
9843
- }
11213
+ const found = this.surviving(typeof text2 === "string" ? folded(text2) : "");
11214
+ const row = ([alias, real]) => ({
11215
+ check: "leak_outbound",
11216
+ where,
11217
+ kind: alias.kind,
11218
+ alias: alias.display,
11219
+ variant: shorten(real)
11220
+ });
11221
+ const hits = found.filter(([a]) => isSubject(a)).map(row);
9844
11222
  this.leaksOut.push(...hits);
11223
+ this.bystandersOut.push(...found.filter(([a]) => !isSubject(a)).map(row));
9845
11224
  return hits;
9846
11225
  }
9847
11226
  // ------------------------------------------------------------ reporting
@@ -9938,6 +11317,8 @@ var AliasMap = class _AliasMap {
9938
11317
  leak_through_inbound_detail: this.leaksIn.slice(0, 50),
9939
11318
  leaks_outbound: this.leaksOut.length,
9940
11319
  leaks_outbound_detail: this.leaksOut.slice(0, 50),
11320
+ bystander_leak_through_inbound: this.bystandersIn.length,
11321
+ bystander_leaks_outbound: this.bystandersOut.length,
9941
11322
  unresolved_aliases_outbound: this.unresolvedOut.length,
9942
11323
  unresolved_detail: this.unresolvedOut.slice(0, 50),
9943
11324
  found_inbound: this.found.length,
@@ -9964,8 +11345,9 @@ function mirrorHandle(handle, identity) {
9964
11345
  const surname = identity.surname.toLowerCase();
9965
11346
  const text2 = handle.toLowerCase();
9966
11347
  const digits = /\d+$/.exec(text2);
9967
- const suffix = digits ? digits[0] : "";
9968
- const body = text2.slice(0, text2.length - suffix.length);
11348
+ const realSuffix = digits ? digits[0] : "";
11349
+ const body = text2.slice(0, text2.length - realSuffix.length);
11350
+ const suffix = standInDigits(realSuffix, `${given} ${surname}`);
9969
11351
  for (const separator of [".", "_", "-"]) {
9970
11352
  if (body.includes(separator))
9971
11353
  return `${given}${separator}${surname}${suffix}`;
@@ -9976,7 +11358,7 @@ function mirrorHandle(handle, identity) {
9976
11358
  }
9977
11359
 
9978
11360
  // src/hooks/config.ts
9979
- import * as fs12 from "fs";
11361
+ import * as fs14 from "fs";
9980
11362
 
9981
11363
  // src/cli/platform/worldData/toml.ts
9982
11364
  var TomlError = class extends Error {
@@ -10213,6 +11595,11 @@ var HookDenied = class extends Error {
10213
11595
  this.handler = handler;
10214
11596
  this.name = "HookDenied";
10215
11597
  }
11598
+ event;
11599
+ toolName;
11600
+ reason;
11601
+ findings;
11602
+ handler;
10216
11603
  };
10217
11604
  var HookError = class extends Error {
10218
11605
  constructor(event, toolName, handler, detail) {
@@ -10223,6 +11610,10 @@ var HookError = class extends Error {
10223
11610
  this.detail = detail;
10224
11611
  this.name = "HookError";
10225
11612
  }
11613
+ event;
11614
+ toolName;
11615
+ handler;
11616
+ detail;
10226
11617
  };
10227
11618
  var isObject3 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
10228
11619
  function resultFromJson(raw, handler = "handler") {
@@ -10324,9 +11715,9 @@ function alternatives(raw) {
10324
11715
  if (!parts2.length || parts2.includes("*")) return [];
10325
11716
  return parts2;
10326
11717
  }
10327
- function hasPath(node, path14) {
11718
+ function hasPath(node, path16) {
10328
11719
  let current = node;
10329
- for (const part of path14.split(".")) {
11720
+ for (const part of path16.split(".")) {
10330
11721
  if (current && typeof current === "object" && !Array.isArray(current) && part in current) {
10331
11722
  current = current[part];
10332
11723
  continue;
@@ -10367,7 +11758,7 @@ function matches(m, event) {
10367
11758
  if (m.args.length) {
10368
11759
  const haystacks = event.event === "pre_request" || event.event === "post_response" ? [event.request?.query, event.request?.body] : [event.toolInput];
10369
11760
  const present = haystacks.filter((h) => h !== void 0 && h !== null);
10370
- if (!m.args.every((path14) => present.some((h) => hasPath(h, path14))))
11761
+ if (!m.args.every((path16) => present.some((h) => hasPath(h, path16))))
10371
11762
  return false;
10372
11763
  }
10373
11764
  return true;
@@ -10767,6 +12158,7 @@ var emptyConfig = () => ({
10767
12158
  aliasPublicLayerWins: true,
10768
12159
  aliasPublicMailboxDomains: null,
10769
12160
  aliasMintInbound: [],
12161
+ aliasDeclaredOnly: false,
10770
12162
  aliasLegend: null,
10771
12163
  vendors: {},
10772
12164
  live: emptyLive()
@@ -10810,9 +12202,9 @@ function vendorOf(config, toolName) {
10810
12202
  return void 0;
10811
12203
  }
10812
12204
  function loadHookConfig(file) {
10813
- if (!fs12.existsSync(file) || !fs12.statSync(file).isFile())
12205
+ if (!fs14.existsSync(file) || !fs14.statSync(file).isFile())
10814
12206
  throw new HookConfigError(`${file}: no such file`);
10815
- const text2 = fs12.readFileSync(file, "utf8");
12207
+ const text2 = fs14.readFileSync(file, "utf8");
10816
12208
  if (file.toLowerCase().endsWith(".json")) {
10817
12209
  let data2;
10818
12210
  try {
@@ -10879,7 +12271,8 @@ function parseHookConfig(data, source) {
10879
12271
  "public_layer_wins",
10880
12272
  "public_mailbox_domains",
10881
12273
  "mint_inbound",
10882
- "legend"
12274
+ "legend",
12275
+ "declared_only"
10883
12276
  ].includes(k)
10884
12277
  );
10885
12278
  if (unknownAlias.length)
@@ -10906,6 +12299,13 @@ function parseHookConfig(data, source) {
10906
12299
  throw new HookConfigError(
10907
12300
  `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)`
10908
12301
  );
12302
+ const declaredOnly = alias.declared_only ?? false;
12303
+ if (typeof declaredOnly !== "boolean")
12304
+ throw new HookConfigError("alias.declared_only must be true or false");
12305
+ if (declaredOnly && mintInboundRaw.length)
12306
+ throw new HookConfigError(
12307
+ "alias.declared_only and alias.mint_inbound cannot both be set: nothing is minted on sight"
12308
+ );
10909
12309
  const legendPath = alias.legend ?? null;
10910
12310
  if (legendPath !== null && (typeof legendPath !== "string" || !legendPath.trim()))
10911
12311
  throw new HookConfigError(
@@ -10938,6 +12338,7 @@ function parseHookConfig(data, source) {
10938
12338
  aliasPublicLayerWins: publicLayerWins,
10939
12339
  aliasPublicMailboxDomains: mailbox,
10940
12340
  aliasMintInbound: mintInboundRaw,
12341
+ aliasDeclaredOnly: declaredOnly,
10941
12342
  aliasLegend: legendPath,
10942
12343
  vendors,
10943
12344
  live: parseLive(data.live ?? {}, data.tools ?? {}),
@@ -11192,8 +12593,8 @@ function parseHandler(event, raw, position) {
11192
12593
 
11193
12594
  // src/hooks/handlers.ts
11194
12595
  import { spawn as spawn3 } from "child_process";
11195
- import * as fs13 from "fs";
11196
- import * as path11 from "path";
12596
+ import * as fs15 from "fs";
12597
+ import * as path13 from "path";
11197
12598
  import { pathToFileURL } from "url";
11198
12599
  function parseStdout(text2, handler) {
11199
12600
  const stripped = text2.trim();
@@ -11216,13 +12617,15 @@ var CommandHandler = class {
11216
12617
  this.command = command2;
11217
12618
  this.opts = opts;
11218
12619
  }
12620
+ command;
12621
+ opts;
11219
12622
  describe() {
11220
12623
  return `command ${this.command}${this.opts.args?.length ? " " + this.opts.args.join(" ") : ""}`;
11221
12624
  }
11222
12625
  run(event) {
11223
12626
  const input = JSON.stringify(eventToJson(event));
11224
12627
  const exec = this.opts.args !== void 0;
11225
- return new Promise((resolve10, reject) => {
12628
+ return new Promise((resolve11, reject) => {
11226
12629
  let child;
11227
12630
  try {
11228
12631
  child = exec ? spawn3(this.command, this.opts.args, {
@@ -11283,7 +12686,7 @@ var CommandHandler = class {
11283
12686
  return;
11284
12687
  }
11285
12688
  try {
11286
- resolve10(
12689
+ resolve11(
11287
12690
  parseStdout(Buffer.concat(out).toString("utf8"), this.describe())
11288
12691
  );
11289
12692
  } catch (error) {
@@ -11318,6 +12721,8 @@ var HttpHandler = class {
11318
12721
  this.url = url;
11319
12722
  this.opts = opts;
11320
12723
  }
12724
+ url;
12725
+ opts;
11321
12726
  describe() {
11322
12727
  return `http ${this.url}`;
11323
12728
  }
@@ -11354,6 +12759,7 @@ var DenyHandler = class {
11354
12759
  constructor(reason = "denied by rule") {
11355
12760
  this.reason = reason;
11356
12761
  }
12762
+ reason;
11357
12763
  describe() {
11358
12764
  return `deny: ${this.reason}`;
11359
12765
  }
@@ -11366,6 +12772,8 @@ var RecordHandler = class {
11366
12772
  this.sink = sink;
11367
12773
  this.opts = opts;
11368
12774
  }
12775
+ sink;
12776
+ opts;
11369
12777
  describe() {
11370
12778
  return `record -> ${typeof this.sink === "string" ? this.sink : typeof this.sink === "function" ? "callback" : "array"}`;
11371
12779
  }
@@ -11387,8 +12795,8 @@ var RecordHandler = class {
11387
12795
  record.source = this.opts.source ?? null;
11388
12796
  if (Array.isArray(this.sink)) this.sink.push(record);
11389
12797
  else if (typeof this.sink === "string") {
11390
- fs13.mkdirSync(path11.dirname(this.sink), { recursive: true });
11391
- fs13.appendFileSync(this.sink, JSON.stringify(record) + "\n");
12798
+ fs15.mkdirSync(path13.dirname(this.sink), { recursive: true });
12799
+ fs15.appendFileSync(this.sink, JSON.stringify(record) + "\n");
11392
12800
  } else await this.sink(record);
11393
12801
  return allow();
11394
12802
  }
@@ -11402,6 +12810,7 @@ var RedactHandler = class {
11402
12810
  this.patterns = (opts.patterns ?? []).map((p) => new RegExp(p, "g"));
11403
12811
  this.token = opts.token ?? "[redacted {kind}]";
11404
12812
  }
12813
+ aliases;
11405
12814
  kinds;
11406
12815
  /** Literal strings (a name, a company, a phrase) removed wherever they appear, any
11407
12816
  * case — the arbitrary half of redaction; `patterns` is the shaped half. */
@@ -11462,6 +12871,8 @@ var AliasHandler = class {
11462
12871
  this.aliases = aliases;
11463
12872
  this.opts = opts;
11464
12873
  }
12874
+ aliases;
12875
+ opts;
11465
12876
  describe() {
11466
12877
  if (this.opts.check) return `alias check=${this.opts.check}`;
11467
12878
  return this.opts.direction ? `alias direction=${this.opts.direction}` : "alias";
@@ -11582,6 +12993,8 @@ var FunctionHandler = class {
11582
12993
  this.fn = fn;
11583
12994
  this.name = name;
11584
12995
  }
12996
+ fn;
12997
+ name;
11585
12998
  describe() {
11586
12999
  return `callable ${this.name}`;
11587
13000
  }
@@ -11593,7 +13006,7 @@ async function importCallable(target, cwd) {
11593
13006
  const hash = target.lastIndexOf("#");
11594
13007
  const modulePath = target.slice(0, hash);
11595
13008
  const exportName = target.slice(hash + 1) || "default";
11596
- const resolved = modulePath.startsWith(".") || path11.isAbsolute(modulePath) ? pathToFileURL(path11.resolve(cwd, modulePath)).href : modulePath;
13009
+ const resolved = modulePath.startsWith(".") || path13.isAbsolute(modulePath) ? pathToFileURL(path13.resolve(cwd, modulePath)).href : modulePath;
11597
13010
  let module;
11598
13011
  try {
11599
13012
  module = await import(resolved);
@@ -11656,8 +13069,8 @@ async function buildHandler(spec, aliases, opts) {
11656
13069
  }
11657
13070
 
11658
13071
  // src/hooks/live.ts
11659
- import * as fs14 from "fs";
11660
- import * as path12 from "path";
13072
+ import * as fs16 from "fs";
13073
+ import * as path14 from "path";
11661
13074
  var USER_AGENT = "gateway-hooks/1 (+https://withgateway.ai)";
11662
13075
  var TAGS = /<(script|style)[^>]*>.*?<\/\1>/gis;
11663
13076
  var STRIP = /<[^>]+>/g;
@@ -11677,7 +13090,7 @@ var Pacer = class {
11677
13090
  /** Waits until the interval since the tool's last call has passed; resolves to the
11678
13091
  * seconds waited. `sleep`/`clock` are injectable for tests. */
11679
13092
  async wait(name, intervalMs, opts = {}) {
11680
- const sleep3 = opts.sleep ?? ((seconds) => new Promise((resolve10) => setTimeout(resolve10, seconds * 1e3)));
13093
+ const sleep3 = opts.sleep ?? ((seconds) => new Promise((resolve11) => setTimeout(resolve11, seconds * 1e3)));
11681
13094
  const clock = opts.clock ?? (() => Date.now() / 1e3);
11682
13095
  const now = clock();
11683
13096
  const due = (this.last.get(name) ?? -Infinity) + intervalMs / 1e3;
@@ -11908,6 +13321,8 @@ var HttpTool = class _HttpTool {
11908
13321
  this.spec = spec;
11909
13322
  this.live = live;
11910
13323
  }
13324
+ spec;
13325
+ live;
11911
13326
  /** Shared across tools: the pace is per tool name, not per HttpTool instance. */
11912
13327
  static pacer = new Pacer();
11913
13328
  /** The status of the most recent answer, for the recording line. */
@@ -12004,6 +13419,8 @@ var CallableTool = class _CallableTool {
12004
13419
  this.spec = spec;
12005
13420
  this.fn = fn;
12006
13421
  }
13422
+ spec;
13423
+ fn;
12007
13424
  static async create(spec, cwd) {
12008
13425
  const fn = await importCallable(spec.options.callable, cwd);
12009
13426
  return new _CallableTool(
@@ -12021,9 +13438,9 @@ var CallableTool = class _CallableTool {
12021
13438
  }
12022
13439
  };
12023
13440
  function readConnection(root) {
12024
- const file = path12.join(root, "connector.toml");
12025
- if (!fs14.existsSync(file)) throw new Error(`no connector.toml at ${root}`);
12026
- const raw = parseToml(fs14.readFileSync(file, "utf8"));
13441
+ const file = path14.join(root, "connector.toml");
13442
+ if (!fs16.existsSync(file)) throw new Error(`no connector.toml at ${root}`);
13443
+ const raw = parseToml(fs16.readFileSync(file, "utf8"));
12027
13444
  const connector = raw.connector ?? {};
12028
13445
  const auth = raw.auth ?? {};
12029
13446
  const operations = {};
@@ -12037,7 +13454,7 @@ function readConnection(root) {
12037
13454
  };
12038
13455
  }
12039
13456
  return {
12040
- slug: connector.slug ?? path12.basename(root),
13457
+ slug: connector.slug ?? path14.basename(root),
12041
13458
  baseUrl: (connector.base_url ?? "").replace(/\/+$/, ""),
12042
13459
  scheme: auth.scheme ?? "none",
12043
13460
  ...typeof auth.name === "string" ? { authName: auth.name } : {},
@@ -12054,8 +13471,8 @@ var ConnectorTool = class {
12054
13471
  this.spec = spec;
12055
13472
  this.live = live;
12056
13473
  let location = spec.options.connector;
12057
- if (!path12.isAbsolute(location)) location = path12.resolve(baseDir, location);
12058
- const root = fs14.existsSync(location) && fs14.statSync(location).isFile() ? path12.dirname(location) : location;
13474
+ if (!path14.isAbsolute(location)) location = path14.resolve(baseDir, location);
13475
+ const root = fs16.existsSync(location) && fs16.statSync(location).isFile() ? path14.dirname(location) : location;
12059
13476
  try {
12060
13477
  this.connection = readConnection(root);
12061
13478
  } catch (error) {
@@ -12078,6 +13495,8 @@ var ConnectorTool = class {
12078
13495
  );
12079
13496
  }
12080
13497
  }
13498
+ spec;
13499
+ live;
12081
13500
  connection;
12082
13501
  operation;
12083
13502
  get placeholders() {
@@ -12208,17 +13627,18 @@ var Recorder = class {
12208
13627
  constructor(file) {
12209
13628
  this.file = file;
12210
13629
  }
13630
+ file;
12211
13631
  write(line) {
12212
- fs14.mkdirSync(path12.dirname(this.file), { recursive: true });
12213
- fs14.appendFileSync(this.file, canonical2(line) + "\n");
13632
+ fs16.mkdirSync(path14.dirname(this.file), { recursive: true });
13633
+ fs16.appendFileSync(this.file, canonical2(line) + "\n");
12214
13634
  }
12215
13635
  };
12216
13636
  var Replay = class {
12217
13637
  constructor(file) {
12218
13638
  this.file = file;
12219
- if (!fs14.existsSync(file))
13639
+ if (!fs16.existsSync(file))
12220
13640
  throw new LiveToolError(`replay: no recording at ${file}`);
12221
- fs14.readFileSync(file, "utf8").split(/\r?\n/).forEach((raw, index2) => {
13641
+ fs16.readFileSync(file, "utf8").split(/\r?\n/).forEach((raw, index2) => {
12222
13642
  if (!raw.trim()) return;
12223
13643
  let line;
12224
13644
  try {
@@ -12238,6 +13658,7 @@ var Replay = class {
12238
13658
  );
12239
13659
  });
12240
13660
  }
13661
+ file;
12241
13662
  answers = /* @__PURE__ */ new Map();
12242
13663
  tool(spec) {
12243
13664
  const answers = this.answers;
@@ -12278,6 +13699,8 @@ var LiveTools = class _LiveTools {
12278
13699
  if (live.replay) this.replay = new Replay(live.replay);
12279
13700
  if (live.record) this.recorder = new Recorder(live.record);
12280
13701
  }
13702
+ run;
13703
+ live;
12281
13704
  replay;
12282
13705
  recorder;
12283
13706
  built = {};
@@ -12302,7 +13725,7 @@ var LiveTools = class _LiveTools {
12302
13725
  ...config.live.record ? { record: interpolatePath(config.live.record, run.runId, directory) } : {},
12303
13726
  ...config.live.replay ? { replay: interpolatePath(config.live.replay, run.runId, directory) } : {}
12304
13727
  };
12305
- return _LiveTools.create(run, live, path12.dirname(path12.resolve(file)));
13728
+ return _LiveTools.create(run, live, path14.dirname(path14.resolve(file)));
12306
13729
  }
12307
13730
  /** The declared tools for a model. `openai`: `{type: "function", function: {name,
12308
13731
  * description, parameters}}`; `anthropic`: `{name, description, input_schema}`. */
@@ -12429,6 +13852,9 @@ var Identifier = class {
12429
13852
  this.value = value;
12430
13853
  this.source = source;
12431
13854
  }
13855
+ kind;
13856
+ value;
13857
+ source;
12432
13858
  get key() {
12433
13859
  return folded(this.value);
12434
13860
  }
@@ -12462,6 +13888,7 @@ var FieldSource = class extends IdentifierSource {
12462
13888
  super();
12463
13889
  this.fieldKinds = fieldKinds;
12464
13890
  }
13891
+ fieldKinds;
12465
13892
  name = "fields";
12466
13893
  kindsFor(tool) {
12467
13894
  return { ...this.fieldKinds[ANY_TOOL] ?? {}, ...this.fieldKinds[tool] ?? {} };
@@ -12501,6 +13928,7 @@ var IdentifierCensus = class {
12501
13928
  constructor(sources) {
12502
13929
  this.sources = sources;
12503
13930
  }
13931
+ sources;
12504
13932
  get detectors() {
12505
13933
  return this.sources.map((source) => source.name);
12506
13934
  }
@@ -12539,6 +13967,12 @@ var AuditReport = class {
12539
13967
  this.leakedIdentifiers = leakedIdentifiers;
12540
13968
  this.cleanTexts = cleanTexts;
12541
13969
  }
13970
+ findings;
13971
+ census;
13972
+ detectors;
13973
+ recordsScanned;
13974
+ leakedIdentifiers;
13975
+ cleanTexts;
12542
13976
  get ok() {
12543
13977
  return this.findings.length === 0;
12544
13978
  }
@@ -12582,6 +14016,7 @@ var RedactionAudit = class _RedactionAudit {
12582
14016
  constructor(census) {
12583
14017
  this.census = census;
12584
14018
  }
14019
+ census;
12585
14020
  /** The standard audit: the run's legend, declared field kinds, pattern finders. */
12586
14021
  static forRun(options) {
12587
14022
  return new _RedactionAudit(
@@ -12616,8 +14051,8 @@ var RedactionAudit = class _RedactionAudit {
12616
14051
 
12617
14052
  // src/hooks/run.ts
12618
14053
  import { randomBytes as randomBytes3 } from "crypto";
12619
- import * as fs15 from "fs";
12620
- import * as path13 from "path";
14054
+ import * as fs17 from "fs";
14055
+ import * as path15 from "path";
12621
14056
  var BLOCKING_EVENTS = [
12622
14057
  "pre_tool_call",
12623
14058
  "pre_request",
@@ -12664,15 +14099,16 @@ var HookRun = class _HookRun {
12664
14099
  this.alias = new AliasMap(this.runKey, options.slugs ?? config.aliasSlugs, {
12665
14100
  publicLayerWins: config.aliasPublicLayerWins,
12666
14101
  publicMailboxDomains: config.aliasPublicMailboxDomains,
12667
- mintInbound: options.mintInbound ?? config.aliasMintInbound
14102
+ mintInbound: options.mintInbound ?? config.aliasMintInbound,
14103
+ declaredOnly: options.declaredOnly ?? config.aliasDeclaredOnly
12668
14104
  });
12669
14105
  this.cwd = options.cwd ?? process.cwd();
12670
- this.runDir = options.runDir ?? path13.join(this.cwd, "runs", this.runId);
14106
+ this.runDir = options.runDir ?? path15.join(this.cwd, "runs", this.runId);
12671
14107
  const chosen = options.legend !== void 0 ? options.legend : config.aliasLegend;
12672
- this.legendPath = chosen ? path13.resolve(this.cwd, interpolatePath(chosen, this.runId, this.runDir)) : null;
14108
+ this.legendPath = chosen ? path15.resolve(this.cwd, interpolatePath(chosen, this.runId, this.runDir)) : null;
12673
14109
  this.sessionId = options.session;
12674
14110
  this.source = options.source;
12675
- this.configDir = config.source ? path13.dirname(path13.resolve(config.source)) : this.cwd;
14111
+ this.configDir = config.source ? path15.dirname(path15.resolve(config.source)) : this.cwd;
12676
14112
  }
12677
14113
  /** Build from a parsed config (an object in the file's shape, or a `HookConfig`);
12678
14114
  * handlers are constructed now, so a callable that does not import fails here. */
@@ -13082,8 +14518,8 @@ var HookRun = class _HookRun {
13082
14518
  throw new Error(
13083
14519
  "no legend path: set [alias] legend, pass legend to the run, or give a path"
13084
14520
  );
13085
- fs15.mkdirSync(path13.dirname(target), { recursive: true });
13086
- fs15.writeFileSync(target, JSON.stringify(this.legend(), null, 2) + "\n");
14521
+ fs17.mkdirSync(path15.dirname(target), { recursive: true });
14522
+ fs17.writeFileSync(target, JSON.stringify(this.legend(), null, 2) + "\n");
13087
14523
  return target;
13088
14524
  }
13089
14525
  writeLegendIfConfigured() {
@@ -13142,6 +14578,10 @@ var HookedSession = class {
13142
14578
  this.vendor = vendor;
13143
14579
  this.requestFn = requestFn;
13144
14580
  }
14581
+ run;
14582
+ inner;
14583
+ vendor;
14584
+ requestFn;
13145
14585
  async call(tool, args = {}, ...rest) {
13146
14586
  const [real, context4] = await this.run.beforeCall(
13147
14587
  tool,
@@ -13175,14 +14615,14 @@ var HookedSession = class {
13175
14615
  * `apiHeaders()`), `pre_request` before it and `post_response` after. Returns
13176
14616
  * `{status, body, headers}`; a 4xx/5xx is returned, not thrown, so the agent sees
13177
14617
  * the vendor's own error shape (rewritten like any result). */
13178
- async request(method, path14, opts = {}) {
14618
+ async request(method, path16, opts = {}) {
13179
14619
  if (!this.inner.api && !this.requestFn)
13180
14620
  throw new Error(
13181
14621
  "this session has no api surface (pass requestFn for a transport of your own)"
13182
14622
  );
13183
14623
  let request = {
13184
14624
  method: method.toUpperCase(),
13185
- path: path14,
14625
+ path: path16,
13186
14626
  query: { ...opts.query ?? {} },
13187
14627
  body: opts.body ?? null
13188
14628
  };
@@ -13413,8 +14853,8 @@ var USAGE_ATTRIBUTES = [
13413
14853
  function setUsageAttributes(span, usage) {
13414
14854
  if (!usage || typeof usage !== "object") return;
13415
14855
  const u = usage;
13416
- for (const [field, attribute] of USAGE_ATTRIBUTES) {
13417
- const value = u[field];
14856
+ for (const [field2, attribute] of USAGE_ATTRIBUTES) {
14857
+ const value = u[field2];
13418
14858
  if (typeof value === "number" && Number.isFinite(value))
13419
14859
  span.setAttribute(attribute, value);
13420
14860
  }
@@ -13592,13 +15032,25 @@ var tracing = {
13592
15032
  };
13593
15033
  export {
13594
15034
  AGENT_ID_KEY,
13595
- ApiError2 as ApiError,
15035
+ ApiError,
15036
+ BROWSER_GONE_PATTERNS,
15037
+ BROWSER_TIERS,
13596
15038
  BrowserActionRecorder,
15039
+ BrowserReconnected,
15040
+ BrowserReconnector,
15041
+ BrowserUnrecoverable,
15042
+ CALL_BODY_LIMIT_BYTES,
15043
+ CALL_BODY_LIMIT_LABEL,
13597
15044
  COMPUTER_USE_SPECS,
15045
+ CheckoutProvenance,
13598
15046
  DEFAULT_BRANCH,
13599
15047
  DEFAULT_TIMEOUT_SECONDS,
13600
15048
  DEFAULT_VIEWPORT,
15049
+ DRY_RUN_AGENT,
15050
+ DRY_RUN_KIND,
15051
+ DetachedPushError,
13601
15052
  DriftError,
15053
+ DryRunOutcome,
13602
15054
  ENV_GATEWAY_HOST,
13603
15055
  ENV_GATEWAY_PUBLIC_KEY,
13604
15056
  ENV_GATEWAY_SECRET_KEY,
@@ -13606,6 +15058,8 @@ export {
13606
15058
  EVENT_FLUSH_INTERVAL_MS,
13607
15059
  EVENT_MAX_RETRIES,
13608
15060
  EXPERIMENT_ATTRIBUTES,
15061
+ EXPLORATORY_TASK,
15062
+ EXPLORATORY_TASK_SOURCE,
13609
15063
  ExperimentClient,
13610
15064
  ExperimentSpanProcessor,
13611
15065
  ExposureLogger,
@@ -13620,10 +15074,17 @@ export {
13620
15074
  GatewaySecurityError,
13621
15075
  GatewayToolApprovalRequiredError,
13622
15076
  GatewayToolBlockedError,
15077
+ HostedDryRunClient,
15078
+ IDLE_WARNING_MINUTES,
15079
+ NO_GRADER_REASON,
15080
+ PLATFORM_TIMEOUT_DEFAULT_MS,
15081
+ PLATFORM_TIMEOUT_ENV,
13623
15082
  Persona,
13624
15083
  PersonaError,
13625
15084
  PersonasClient,
15085
+ PlatformTransport,
13626
15086
  PushSlugConflict,
15087
+ RECOVER_BUDGET_MS,
13627
15088
  REPLAY_ENVIRONMENT,
13628
15089
  ReplayCase,
13629
15090
  ReplayCheck,
@@ -13631,12 +15092,16 @@ export {
13631
15092
  ReplayReport,
13632
15093
  ReplaySuite,
13633
15094
  ReplayTask,
15095
+ SANDBOX_REQUEST_TIMEOUT_MS,
15096
+ SESSION_STATES,
15097
+ STATUS_WAIT_CAP_SECONDS,
13634
15098
  STRIP_PREFIX,
13635
15099
  SUCCESS_METRIC_NAME_KEY,
13636
15100
  SUCCESS_SIGNAL_KEY,
13637
15101
  SURFACE_KINDS,
13638
15102
  ScoreError,
13639
15103
  ScoresClient,
15104
+ SecretScrubber,
13640
15105
  SessionLoadError,
13641
15106
  SessionRecording,
13642
15107
  SessionTrace,
@@ -13646,10 +15111,15 @@ export {
13646
15111
  TaskSessions,
13647
15112
  ToolStubRegistry,
13648
15113
  TraceDiff,
15114
+ TransportCause,
15115
+ UnreachableError,
13649
15116
  UserProfileError,
13650
15117
  UsersClient,
15118
+ VERIFIER_REWARD_PREFIX,
13651
15119
  WHITESPACE,
13652
15120
  WorldBrowser,
15121
+ WorldCallTooLarge,
15122
+ WorldEditClient,
13653
15123
  WorldSandboxClient,
13654
15124
  WorldSession,
13655
15125
  WorldSessionCallError,
@@ -13663,6 +15133,8 @@ export {
13663
15133
  applyTransforms,
13664
15134
  archiveMode,
13665
15135
  assembleManifest,
15136
+ assertBrowserTier,
15137
+ assertTaskRef,
13666
15138
  assignVariant,
13667
15139
  attachManifest,
13668
15140
  attachSession,
@@ -13672,7 +15144,9 @@ export {
13672
15144
  buildSourceTarball,
13673
15145
  canonicalJson,
13674
15146
  captureToolCalls,
15147
+ checkoutIdentity,
13675
15148
  clearExperimentContext,
15149
+ closeConnection,
13676
15150
  collectArchiveRelPaths,
13677
15151
  computeBuildHash,
13678
15152
  computeContentHash,
@@ -13702,13 +15176,18 @@ export {
13702
15176
  hashForm,
13703
15177
  hooks_exports as hooks,
13704
15178
  identify,
15179
+ idleWarning,
13705
15180
  ingest,
13706
15181
  ingestToolCalls,
15182
+ isBrowserGone,
15183
+ isSandboxImportPending,
13707
15184
  isTaskIdRef,
13708
15185
  isTaskManifest,
13709
15186
  isTaskSpec,
13710
15187
  listEnvSecretKeys,
13711
15188
  listRunConfigs,
15189
+ listRuns,
15190
+ listSessions,
13712
15191
  listTaskSessions,
13713
15192
  listTasks,
13714
15193
  loadSession,
@@ -13722,26 +15201,31 @@ export {
13722
15201
  openTask,
13723
15202
  openWorld,
13724
15203
  openWorldVersion,
15204
+ parseErrorBody,
13725
15205
  parseSlugRef,
13726
15206
  parseToolCallRecord,
13727
15207
  parseTransform,
13728
15208
  parseWorldTaskRefs,
13729
15209
  personas,
15210
+ platformTimeoutMs,
13730
15211
  preserveForm,
13731
15212
  propose,
13732
15213
  pull,
13733
15214
  push,
15215
+ pushBranch,
13734
15216
  pushSlug,
13735
15217
  pyText,
13736
15218
  queryRows,
13737
15219
  queryRowsSearch,
13738
15220
  readLocalMeta,
13739
15221
  readToolCallRecords,
15222
+ rebaseConflicts,
13740
15223
  redactActionArgs,
13741
15224
  redactionOf,
13742
15225
  registerArtifact,
13743
15226
  registerPrompt,
13744
15227
  registerSkill,
15228
+ releaseConnection,
13745
15229
  renderAgentSystem,
13746
15230
  replay,
13747
15231
  resetBuildRegistry,
@@ -13750,11 +15234,13 @@ export {
13750
15234
  resolveUserId,
13751
15235
  roundForm,
13752
15236
  runSessions,
15237
+ runSet,
13753
15238
  runSuite,
13754
15239
  runTask,
13755
15240
  runWithExperimentContext,
13756
15241
  schemaFromSignature,
13757
15242
  scores,
15243
+ serializeCallBody,
13758
15244
  sessionObservationFromApi,
13759
15245
  sessionToolObservations,
13760
15246
  sessions,
@@ -13773,6 +15259,7 @@ export {
13773
15259
  tracing,
13774
15260
  uiEntryUrl,
13775
15261
  uiUrl,
15262
+ uncommittedPaths,
13776
15263
  updateTask,
13777
15264
  upsertRunConfig,
13778
15265
  users,