@withgateway/sdk 0.3.3 → 0.4.0

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 (123) hide show
  1. package/README.md +4 -3
  2. package/dist/cli.js +2221 -962
  3. package/dist/cli.js.map +1 -1
  4. package/dist/cli.mjs +2212 -953
  5. package/dist/cli.mjs.map +1 -1
  6. package/dist/files/index.js +81 -19
  7. package/dist/files/index.js.map +1 -1
  8. package/dist/files/index.mjs +79 -17
  9. package/dist/files/index.mjs.map +1 -1
  10. package/dist/hooks/index.d.mts +1 -1
  11. package/dist/hooks/index.d.ts +1 -1
  12. package/dist/hooks/index.js +124 -11
  13. package/dist/hooks/index.js.map +1 -1
  14. package/dist/hooks/index.mjs +124 -11
  15. package/dist/hooks/index.mjs.map +1 -1
  16. package/dist/{index-C3UzD0G3.d.mts → index-CDPQBsU5.d.mts} +19 -3
  17. package/dist/{index-C3UzD0G3.d.ts → index-CDPQBsU5.d.ts} +19 -3
  18. package/dist/index.d.mts +2 -2
  19. package/dist/index.d.ts +2 -2
  20. package/dist/index.js +903 -221
  21. package/dist/index.js.map +1 -1
  22. package/dist/index.mjs +868 -212
  23. package/dist/index.mjs.map +1 -1
  24. package/dist/traces/index.js +78 -16
  25. package/dist/traces/index.js.map +1 -1
  26. package/dist/traces/index.mjs +76 -14
  27. package/dist/traces/index.mjs.map +1 -1
  28. package/dist/tracing/index.js +7 -1
  29. package/dist/tracing/index.js.map +1 -1
  30. package/dist/tracing/index.mjs +7 -1
  31. package/dist/tracing/index.mjs.map +1 -1
  32. package/dist/worlds/index.d.mts +692 -410
  33. package/dist/worlds/index.d.ts +692 -410
  34. package/dist/worlds/index.js +740 -197
  35. package/dist/worlds/index.js.map +1 -1
  36. package/dist/worlds/index.mjs +736 -193
  37. package/dist/worlds/index.mjs.map +1 -1
  38. package/package.json +1 -1
  39. package/runtime/gatewaysdk/environment/_materialize.py +5 -25
  40. package/runtime/gatewaysdk/environment/_world.py +58 -65
  41. package/runtime/gatewaysdk/environment/backing.py +20 -24
  42. package/runtime/gatewaysdk/environment/core.py +1 -16
  43. package/runtime/gatewaysdk/environment/legacy_sqlite.py +14 -27
  44. package/runtime/gatewaysdk/environment/schema/admission.py +174 -0
  45. package/runtime/gatewaysdk/environment/schema/api.py +174 -471
  46. package/runtime/gatewaysdk/environment/schema/assertions.py +458 -0
  47. package/runtime/gatewaysdk/environment/schema/batch.py +3 -3
  48. package/runtime/gatewaysdk/environment/schema/cache_layout.py +5 -0
  49. package/runtime/gatewaysdk/environment/schema/call_capture.py +309 -0
  50. package/runtime/gatewaysdk/environment/schema/call_log.py +230 -18
  51. package/runtime/gatewaysdk/environment/schema/call_redaction.py +201 -19
  52. package/runtime/gatewaysdk/environment/schema/cast.py +15 -35
  53. package/runtime/gatewaysdk/environment/schema/conform.py +6 -27
  54. package/runtime/gatewaysdk/environment/schema/connector.py +89 -152
  55. package/runtime/gatewaysdk/environment/schema/connectors/confluence/connector.toml +1 -12
  56. package/runtime/gatewaysdk/environment/schema/connectors/github/connector.toml +1 -0
  57. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/connector.toml +2 -5
  58. package/runtime/gatewaysdk/environment/schema/cors.py +54 -0
  59. package/runtime/gatewaysdk/environment/schema/credentials.py +313 -8
  60. package/runtime/gatewaysdk/environment/schema/data.py +14 -13
  61. package/runtime/gatewaysdk/environment/schema/database/base.py +106 -165
  62. package/runtime/gatewaysdk/environment/schema/database/guard.py +43 -36
  63. package/runtime/gatewaysdk/environment/schema/database/reads.py +169 -0
  64. package/runtime/gatewaysdk/environment/schema/database/sqlite.py +57 -31
  65. package/runtime/gatewaysdk/environment/schema/declared_routes.py +210 -0
  66. package/runtime/gatewaysdk/environment/schema/door.py +899 -0
  67. package/runtime/gatewaysdk/environment/schema/envelope.py +86 -28
  68. package/runtime/gatewaysdk/environment/schema/grading.py +58 -86
  69. package/runtime/gatewaysdk/environment/schema/handler_errors.py +25 -4
  70. package/runtime/gatewaysdk/environment/schema/host.py +229 -1695
  71. package/runtime/gatewaysdk/environment/schema/host_control.py +144 -0
  72. package/runtime/gatewaysdk/environment/schema/host_handoff.py +370 -0
  73. package/runtime/gatewaysdk/environment/schema/host_loops.py +97 -0
  74. package/runtime/gatewaysdk/environment/schema/host_owners.py +121 -0
  75. package/runtime/gatewaysdk/environment/schema/host_proxy.py +111 -0
  76. package/runtime/gatewaysdk/environment/schema/host_requests.py +6 -0
  77. package/runtime/gatewaysdk/environment/schema/host_session.py +126 -0
  78. package/runtime/gatewaysdk/environment/schema/host_surfaces.py +79 -21
  79. package/runtime/gatewaysdk/environment/schema/host_transfers.py +127 -0
  80. package/runtime/gatewaysdk/environment/schema/host_versions.py +242 -0
  81. package/runtime/gatewaysdk/environment/schema/host_workers.py +577 -0
  82. package/runtime/gatewaysdk/environment/schema/journal.py +437 -0
  83. package/runtime/gatewaysdk/environment/schema/ledger_spill.py +828 -0
  84. package/runtime/gatewaysdk/environment/schema/local.py +31 -116
  85. package/runtime/gatewaysdk/environment/schema/platform.py +15 -17
  86. package/runtime/gatewaysdk/environment/schema/request_body.py +238 -0
  87. package/runtime/gatewaysdk/environment/schema/request_ledger.py +958 -0
  88. package/runtime/gatewaysdk/environment/schema/route_bindings.py +25 -3
  89. package/runtime/gatewaysdk/environment/schema/route_miss.py +54 -0
  90. package/runtime/gatewaysdk/environment/schema/runtime.py +129 -176
  91. package/runtime/gatewaysdk/environment/schema/session_files.py +133 -24
  92. package/runtime/gatewaysdk/environment/schema/session_move.py +275 -0
  93. package/runtime/gatewaysdk/environment/schema/skills/agents/connector-template-author.md +5 -1
  94. package/runtime/gatewaysdk/environment/schema/skills/benchmarks-getting-started/SKILL.md +8 -9
  95. package/runtime/gatewaysdk/environment/schema/skills/connector-schema-authoring/SKILL.md +31 -6
  96. package/runtime/gatewaysdk/environment/schema/skills/world-data-ingestion/ROWS.md +12 -8
  97. package/runtime/gatewaysdk/environment/schema/skills/world-data-ingestion/SKILL.md +13 -13
  98. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/SKILL.md +23 -23
  99. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/cli-mcp-map.md +11 -6
  100. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/gotchas.md +35 -2
  101. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/journal-checks.md +182 -0
  102. package/runtime/gatewaysdk/environment/schema/snapshot.py +149 -29
  103. package/runtime/gatewaysdk/environment/schema/spill_files.py +228 -0
  104. package/runtime/gatewaysdk/environment/schema/tasks.py +229 -323
  105. package/runtime/gatewaysdk/environment/schema/tools_world.py +84 -203
  106. package/runtime/gatewaysdk/environment/schema/validation.py +69 -1
  107. package/runtime/gatewaysdk/environment/schema/verbs.py +32 -36
  108. package/runtime/gatewaysdk/environment/schema/worker.py +6 -4
  109. package/runtime/gatewaysdk/environment/schema/workers.py +203 -39
  110. package/runtime/gatewaysdk/environment/schema/world_host.py +953 -0
  111. package/runtime/gatewaysdk/environment/schema/world_tests.py +9 -11
  112. package/runtime/gatewaysdk/environment/world.py +1 -1
  113. package/runtime/gatewaysdk/environment/world_session_contract.py +14 -0
  114. package/skills/agents/connector-template-author.md +5 -1
  115. package/skills/benchmarks-getting-started/SKILL.md +8 -9
  116. package/skills/connector-schema-authoring/SKILL.md +31 -6
  117. package/skills/connector-schema-authoring/connector-worlds.md +129 -7
  118. package/skills/world-data-ingestion/ROWS.md +12 -8
  119. package/skills/world-data-ingestion/SKILL.md +13 -13
  120. package/skills/worlds-getting-started/SKILL.md +23 -23
  121. package/skills/worlds-getting-started/references/cli-mcp-map.md +11 -6
  122. package/skills/worlds-getting-started/references/gotchas.md +35 -2
  123. package/skills/worlds-getting-started/references/journal-checks.md +182 -0
package/dist/index.mjs CHANGED
@@ -480,7 +480,7 @@ function platformTimeoutMs(env = process.env) {
480
480
  if (Number.isInteger(value) && value > 0) return value;
481
481
  throw new Error(`${PLATFORM_TIMEOUT_ENV} must be a positive whole number of milliseconds, not \`${raw}\`.`);
482
482
  }
483
- var PLATFORM_TIMEOUT_ENV, PLATFORM_TIMEOUT_DEFAULT_MS, CHECK_HOST, RETRY, CAUSES, UNKNOWN_CAUSE, TransportCause, UnreachableError, sleep2, RetryPolicy, Attempt, PlatformTransport;
483
+ var PLATFORM_TIMEOUT_ENV, PLATFORM_TIMEOUT_DEFAULT_MS, CHECK_HOST, RETRY, FETCH_LIMIT, CAUSES, UNKNOWN_CAUSE, TransportCause, UnreachableError, sleep2, RetryPolicy, Attempt, PlatformTransport;
484
484
  var init_transport = __esm({
485
485
  "src/worlds/transport.ts"() {
486
486
  "use strict";
@@ -488,7 +488,13 @@ var init_transport = __esm({
488
488
  PLATFORM_TIMEOUT_DEFAULT_MS = 12e4;
489
489
  CHECK_HOST = "Check GATEWAY_HOST (or --host) points at a running platform, then retry.";
490
490
  RETRY = "Retry; if it repeats, check the network between here and the platform.";
491
+ FETCH_LIMIT = {
492
+ reason: "Node's fetch stopped waiting after 300 s",
493
+ next: "The platform may still be running it: check what it changed before you retry."
494
+ };
491
495
  CAUSES = {
496
+ UND_ERR_HEADERS_TIMEOUT: FETCH_LIMIT,
497
+ UND_ERR_BODY_TIMEOUT: FETCH_LIMIT,
492
498
  ECONNREFUSED: { reason: "connection refused", next: CHECK_HOST },
493
499
  ENOTFOUND: { reason: "DNS lookup failed", next: CHECK_HOST },
494
500
  EAI_AGAIN: { reason: "DNS lookup failed", next: CHECK_HOST },
@@ -788,6 +794,12 @@ var init_browserReconnect = __esm({
788
794
  });
789
795
 
790
796
  // src/worlds/browser.ts
797
+ function assertSessionAuthMode(value) {
798
+ if (SESSION_AUTH_MODES.includes(value)) return;
799
+ throw new Error(
800
+ `Unknown session auth: ${String(value)}; choose from ${SESSION_AUTH_MODES.join(", ")}`
801
+ );
802
+ }
791
803
  function assertBrowserTier(value) {
792
804
  if (BROWSER_TIERS.includes(value)) return;
793
805
  throw new Error(
@@ -824,6 +836,15 @@ function splitHash(url) {
824
836
  const h = url.indexOf("#");
825
837
  return h < 0 ? [url, ""] : [url.slice(0, h), url.slice(h)];
826
838
  }
839
+ function capabilityLabel(url) {
840
+ let host = "";
841
+ try {
842
+ host = url ? new URL(url).hostname : "";
843
+ } catch {
844
+ return null;
845
+ }
846
+ return CAPABILITY_HOST.exec(host)?.[1] ?? null;
847
+ }
827
848
  function redactActionArgs(action, args) {
828
849
  const secretField = action === "browser_type" && SECRET_KEY.test(String(args.selector ?? ""));
829
850
  const out = {};
@@ -883,7 +904,9 @@ async function openBrowser(surfaces, opts = {}) {
883
904
  };
884
905
  const scrubber = new SecretScrubber([
885
906
  surfaces.browser?.wsUrl,
886
- surfaces.ui?.token
907
+ surfaces.ui?.token,
908
+ capabilityLabel(surfaces.ui?.url),
909
+ capabilityLabel(surfaces.api?.url)
887
910
  ]);
888
911
  const reconnector = mode === "hosted" && surfaces.browser.protocol === "cdp" && opts.repair ? new BrowserReconnector(opts.repair, reattach, {
889
912
  scrub: (text2) => scrubber.scrub(text2)
@@ -948,13 +971,15 @@ function computerUseToolkit(browser, opts = {}) {
948
971
  specs
949
972
  };
950
973
  }
951
- 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;
974
+ var SURFACE_KINDS, PLATFORM_SESSION_HEADER, SESSION_AUTH_MODES, BROWSER_TIERS, DEFAULT_VIEWPORT, SETTLE_TIMEOUT_MS, SETTLE_QUIET_MS, SETTLE_POLL_MS, EVENT_BATCH_SIZE, EVENT_FLUSH_INTERVAL_MS, EVENT_MAX_RETRIES, EVENT_SCREENSHOT_QUALITY, EVENT_MAX_STRING, SECRET_KEY, SECRET_VALUE, WorldSurfaceUnavailable, UI_TOKEN_QUERY, CAPABILITY_HOST, BrowserActionRecorder, WorldBrowser, COMPUTER_USE_SPECS, str;
952
975
  var init_browser = __esm({
953
976
  "src/worlds/browser.ts"() {
954
977
  "use strict";
955
978
  init_session2();
956
979
  init_browserReconnect();
957
980
  SURFACE_KINDS = ["tools", "api", "ui", "browser"];
981
+ PLATFORM_SESSION_HEADER = "X-World-Session";
982
+ SESSION_AUTH_MODES = ["vendor", "open"];
958
983
  BROWSER_TIERS = ["standard", "premium"];
959
984
  DEFAULT_VIEWPORT = { width: 1280, height: 800 };
960
985
  SETTLE_TIMEOUT_MS = 5e3;
@@ -975,6 +1000,7 @@ var init_browser = __esm({
975
1000
  surface;
976
1001
  };
977
1002
  UI_TOKEN_QUERY = "token";
1003
+ CAPABILITY_HOST = /^o-[a-z0-9]+-([a-z2-7]{26})(?:-api)?\./;
978
1004
  BrowserActionRecorder = class {
979
1005
  constructor(post, agentId, opts = {}) {
980
1006
  this.post = post;
@@ -1067,7 +1093,10 @@ var init_browser = __esm({
1067
1093
  }
1068
1094
  };
1069
1095
  WorldBrowser = class {
1070
- constructor(page, ui, mode, teardown, viewport = DEFAULT_VIEWPORT, recorder = null, reconnector = null, scrubber = new SecretScrubber([ui?.token])) {
1096
+ constructor(page, ui, mode, teardown, viewport = DEFAULT_VIEWPORT, recorder = null, reconnector = null, scrubber = new SecretScrubber([
1097
+ ui?.token,
1098
+ capabilityLabel(ui?.url)
1099
+ ])) {
1071
1100
  this.ui = ui;
1072
1101
  this.mode = mode;
1073
1102
  this.teardown = teardown;
@@ -1204,7 +1233,15 @@ var init_browser = __esm({
1204
1233
  seq: recorder.nextSeq(),
1205
1234
  ts: (/* @__PURE__ */ new Date()).toISOString(),
1206
1235
  action,
1207
- args: redactActionArgs(action, args),
1236
+ args: redactActionArgs(
1237
+ action,
1238
+ Object.fromEntries(
1239
+ Object.entries(args).map(([key2, value]) => [
1240
+ key2,
1241
+ typeof value === "string" ? this.scrubber.scrub(value) : value
1242
+ ])
1243
+ )
1244
+ ),
1208
1245
  ok: failure === null,
1209
1246
  error,
1210
1247
  durationMs: Date.now() - started,
@@ -1220,8 +1257,8 @@ var init_browser = __esm({
1220
1257
  screenshot: null
1221
1258
  };
1222
1259
  try {
1223
- out.url = this.page.url();
1224
- out.title = await this.page.title();
1260
+ out.url = this.scrubber.scrub(this.page.url());
1261
+ out.title = this.scrubber.scrub(await this.page.title());
1225
1262
  const jpeg = await this.page.screenshot({
1226
1263
  type: "jpeg",
1227
1264
  quality: EVENT_SCREENSHOT_QUALITY
@@ -2665,13 +2702,16 @@ function idleWarning(idleExpiresAt, now = /* @__PURE__ */ new Date()) {
2665
2702
  const minutes = Math.max(0, Math.floor(leftMs / 6e4));
2666
2703
  return `warning: session expires in ${minutes}m (idle TTL); call a tool to extend it or \`gateway worlds session pin\` to keep it`;
2667
2704
  }
2668
- var CALL_BODY_LIMIT_BYTES, CALL_BODY_LIMIT_LABEL, IDLE_WARNING_MINUTES, EXPLORATORY_TASK, EXPLORATORY_TASK_SOURCE, NO_GRADER_REASON, WorldCallTooLarge, stillStartingHint;
2705
+ var CALL_BODY_LIMIT_BYTES, CALL_BODY_LIMIT_LABEL, IDLE_WARNING_MINUTES, REQUEST_LOG_PAGE_MAX, REQUEST_BODY_CAPTURE_BYTES, REQUESTS_NOT_RECORDED, EXPLORATORY_TASK, EXPLORATORY_TASK_SOURCE, NO_GRADER_REASON, WorldCallTooLarge, stillStartingHint;
2669
2706
  var init_sessionContract = __esm({
2670
2707
  "src/worlds/sessionContract.ts"() {
2671
2708
  "use strict";
2672
2709
  CALL_BODY_LIMIT_BYTES = 4 * 1024 * 1024;
2673
2710
  CALL_BODY_LIMIT_LABEL = "4mb";
2674
2711
  IDLE_WARNING_MINUTES = 5;
2712
+ REQUEST_LOG_PAGE_MAX = 200;
2713
+ REQUEST_BODY_CAPTURE_BYTES = 64 * 1024;
2714
+ REQUESTS_NOT_RECORDED = "requests_not_recorded";
2675
2715
  EXPLORATORY_TASK = Object.freeze({
2676
2716
  instruction: "exploratory session"
2677
2717
  });
@@ -2705,6 +2745,217 @@ var init_sessionContract = __esm({
2705
2745
  }
2706
2746
  });
2707
2747
 
2748
+ // src/worlds/toolSchema.ts
2749
+ function schemaFromSignature(spec) {
2750
+ if (spec.inputSchema)
2751
+ return {
2752
+ type: "function",
2753
+ function: {
2754
+ name: modelToolName(spec.name),
2755
+ description: spec.doc ?? spec.name,
2756
+ parameters: spec.inputSchema
2757
+ }
2758
+ };
2759
+ const inside = /\(([\s\S]*)\)\s*$/.exec(spec.signature.trim())?.[1] ?? "";
2760
+ const properties = {};
2761
+ const required2 = [];
2762
+ const params = [];
2763
+ let depth = 0;
2764
+ let current = "";
2765
+ for (const ch of inside) {
2766
+ if ("([{".includes(ch)) depth++;
2767
+ if (")]}".includes(ch)) depth--;
2768
+ if (ch === "," && depth === 0) {
2769
+ params.push(current);
2770
+ current = "";
2771
+ } else current += ch;
2772
+ }
2773
+ if (current.trim()) params.push(current);
2774
+ for (const raw of params) {
2775
+ const param = raw.trim();
2776
+ if (!param || param.startsWith("*") || param === "self") continue;
2777
+ const eq = param.indexOf("=");
2778
+ const name = (eq === -1 ? param : param.slice(0, eq)).split(":")[0].trim();
2779
+ if (!name) continue;
2780
+ if (eq === -1) {
2781
+ properties[name] = { type: "string" };
2782
+ required2.push(name);
2783
+ continue;
2784
+ }
2785
+ const value = param.slice(eq + 1).trim();
2786
+ if (/^-?\d+(\.\d+)?$/.test(value)) properties[name] = { type: "number" };
2787
+ else if (value === "True" || value === "False")
2788
+ properties[name] = { type: "boolean" };
2789
+ else properties[name] = { type: "string" };
2790
+ }
2791
+ return {
2792
+ type: "function",
2793
+ function: {
2794
+ name: modelToolName(spec.name),
2795
+ description: spec.doc ?? spec.name,
2796
+ parameters: { type: "object", properties, required: required2 }
2797
+ }
2798
+ };
2799
+ }
2800
+ var modelToolName;
2801
+ var init_toolSchema = __esm({
2802
+ "src/worlds/toolSchema.ts"() {
2803
+ "use strict";
2804
+ modelToolName = (name) => name.replace(/[^A-Za-z0-9_-]/g, "_").slice(0, 64) || "tool";
2805
+ }
2806
+ });
2807
+
2808
+ // src/worlds/requestLedger.ts
2809
+ function platformMessage(text2) {
2810
+ try {
2811
+ const { message } = JSON.parse(text2);
2812
+ return typeof message === "string" ? message : null;
2813
+ } catch {
2814
+ return null;
2815
+ }
2816
+ }
2817
+ var WORLD_REQUEST_VIAS, WorldRequestFilterError, NOT_RECORDED, WorldRequestsNotRecorded, STATUS, INSTANT, WORLDS, SESSIONS, Instant, WorldRequestQuery, WorldRequestLedger;
2818
+ var init_requestLedger = __esm({
2819
+ "src/worlds/requestLedger.ts"() {
2820
+ "use strict";
2821
+ init_worlds();
2822
+ init_sessionContract();
2823
+ WORLD_REQUEST_VIAS = ["api", "ui", "tool"];
2824
+ WorldRequestFilterError = class extends Error {
2825
+ };
2826
+ NOT_RECORDED = "This session's engine records no requests; only hosted World Host sessions do.";
2827
+ WorldRequestsNotRecorded = class _WorldRequestsNotRecorded extends Error {
2828
+ static from(error) {
2829
+ if (!(error instanceof ApiError) || error.code !== REQUESTS_NOT_RECORDED) return error;
2830
+ return new _WorldRequestsNotRecorded(platformMessage(error.text) || NOT_RECORDED);
2831
+ }
2832
+ static async mapped(read) {
2833
+ try {
2834
+ return await read;
2835
+ } catch (error) {
2836
+ throw _WorldRequestsNotRecorded.from(error);
2837
+ }
2838
+ }
2839
+ };
2840
+ STATUS = /^(?:[1-5]\d\d|[1-5]xx)$/;
2841
+ INSTANT = /^(\d{4})-(\d{2})-(\d{2})(?:T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{1,3}))?)?(Z|[+-]\d{2}:\d{2})?)?$/;
2842
+ WORLDS = "/api/public/worlds";
2843
+ SESSIONS = "/api/public/world-sessions";
2844
+ Instant = class _Instant {
2845
+ static parse(flag, raw) {
2846
+ const match = INSTANT.exec(raw);
2847
+ const millis = match ? _Instant.fromParts(match) : null;
2848
+ if (millis === null)
2849
+ throw new WorldRequestFilterError(
2850
+ `--${flag} must be an ISO 8601 date or time (2026-10-05, 2026-10-05T14:30:00Z), not \`${raw}\`.`
2851
+ );
2852
+ return millis;
2853
+ }
2854
+ static fromParts(match) {
2855
+ const [year, month, day, hour, minute, second] = [1, 2, 3, 4, 5, 6].map((i) => Number(match[i] ?? 0));
2856
+ const offset = _Instant.offsetMinutes(match[8]);
2857
+ if (offset === null || year < 1 || hour > 23 || minute > 59 || second > 59) return null;
2858
+ const date = /* @__PURE__ */ new Date(0);
2859
+ date.setUTCFullYear(year, month - 1, day);
2860
+ if (date.getUTCFullYear() !== year || date.getUTCMonth() !== month - 1 || date.getUTCDate() !== day) return null;
2861
+ date.setUTCHours(hour, minute, second, Number((match[7] ?? "").padEnd(3, "0")));
2862
+ const utc = date.getTime() - offset * 6e4;
2863
+ const utcYear = new Date(utc).getUTCFullYear();
2864
+ return utcYear < 1 || utcYear > 9999 ? null : utc;
2865
+ }
2866
+ static offsetMinutes(zone) {
2867
+ if (zone === void 0 || zone === "Z") return 0;
2868
+ const hours = Number(zone.slice(1, 3));
2869
+ const minutes = Number(zone.slice(4, 6));
2870
+ if (hours > 23 || minutes > 59) return null;
2871
+ return (zone.startsWith("-") ? -1 : 1) * (hours * 60 + minutes);
2872
+ }
2873
+ };
2874
+ WorldRequestQuery = class _WorldRequestQuery {
2875
+ constructor(entries) {
2876
+ this.entries = entries;
2877
+ }
2878
+ entries;
2879
+ static parse(filter = {}) {
2880
+ const via = _WorldRequestQuery.via(filter.via);
2881
+ const status = _WorldRequestQuery.status(filter.status);
2882
+ const since = filter.since === void 0 ? void 0 : Instant.parse("since", filter.since);
2883
+ const until = filter.until === void 0 ? void 0 : Instant.parse("until", filter.until);
2884
+ if (since !== void 0 && until !== void 0 && since > until)
2885
+ throw new WorldRequestFilterError("--since must not be after --until.");
2886
+ const values = [
2887
+ ["session", filter.session],
2888
+ ["version", filter.version],
2889
+ ["via", via],
2890
+ ["operation", filter.operation],
2891
+ ["status", status],
2892
+ ["since", since === void 0 ? void 0 : new Date(since).toISOString()],
2893
+ ["until", until === void 0 ? void 0 : new Date(until).toISOString()],
2894
+ ["limit", filter.limit === void 0 ? void 0 : String(filter.limit)],
2895
+ ["cursor", filter.cursor]
2896
+ ];
2897
+ return new _WorldRequestQuery(values.filter((entry) => entry[1] !== void 0));
2898
+ }
2899
+ static via(value) {
2900
+ if (value === void 0) return void 0;
2901
+ const lower = value.toLowerCase();
2902
+ if (WORLD_REQUEST_VIAS.includes(lower)) return lower;
2903
+ throw new WorldRequestFilterError(`--via must be one of ${WORLD_REQUEST_VIAS.join(", ")}, not \`${value}\`.`);
2904
+ }
2905
+ static status(value) {
2906
+ if (value === void 0) return void 0;
2907
+ const lower = value.toLowerCase();
2908
+ if (STATUS.test(lower)) return lower;
2909
+ throw new WorldRequestFilterError(`--status must be a code (200) or a class (2xx), not \`${value}\`.`);
2910
+ }
2911
+ get filtered() {
2912
+ return this.entries.some(([key2]) => key2 !== "limit");
2913
+ }
2914
+ params() {
2915
+ return this.entries.map(([key2, value]) => [key2, value]);
2916
+ }
2917
+ search() {
2918
+ return this.entries.length ? `?${new URLSearchParams(this.entries).toString()}` : "";
2919
+ }
2920
+ };
2921
+ WorldRequestLedger = class {
2922
+ constructor(options = {}) {
2923
+ this.options = options;
2924
+ }
2925
+ options;
2926
+ /** A page of the world's requests, newest first; `nextCursor` reads the page after it. Narrowed to a session
2927
+ * whose engine records none: `WorldRequestsNotRecorded`. */
2928
+ list(slug, query = WorldRequestQuery.parse()) {
2929
+ return WorldRequestsNotRecorded.mapped(
2930
+ apiRequest(
2931
+ this.options,
2932
+ "GET",
2933
+ `${WORLDS}/${encodeURIComponent(slug)}/requests${query.search()}`
2934
+ )
2935
+ );
2936
+ }
2937
+ /** One of the world's requests, with its headers and bodies. */
2938
+ get(slug, requestId) {
2939
+ return apiRequest(
2940
+ this.options,
2941
+ "GET",
2942
+ `${WORLDS}/${encodeURIComponent(slug)}/requests/${encodeURIComponent(requestId)}`
2943
+ );
2944
+ }
2945
+ /** A page of one session's requests, newest first; `WorldRequestsNotRecorded` when its engine records none. */
2946
+ forSession(sessionId, query = WorldRequestQuery.parse()) {
2947
+ return WorldRequestsNotRecorded.mapped(
2948
+ apiRequest(
2949
+ this.options,
2950
+ "GET",
2951
+ `${SESSIONS}/${encodeURIComponent(sessionId)}/requests${query.search()}`
2952
+ )
2953
+ );
2954
+ }
2955
+ };
2956
+ }
2957
+ });
2958
+
2708
2959
  // src/worlds/sessionReadiness.ts
2709
2960
  var READY_TIMEOUT_MS, READY_POLL_MS, sleep3, WorldSessionTimeout, WorldSessionCallError, WorldSessionOpenFailed, ENDED, SessionReadiness;
2710
2961
  var init_sessionReadiness = __esm({
@@ -3044,57 +3295,6 @@ __export(session_exports2, {
3044
3295
  taskLabel: () => taskLabel
3045
3296
  });
3046
3297
  import { randomUUID } from "crypto";
3047
- function schemaFromSignature(spec) {
3048
- if (spec.inputSchema)
3049
- return {
3050
- type: "function",
3051
- function: {
3052
- name: modelToolName(spec.name),
3053
- description: spec.doc ?? spec.name,
3054
- parameters: spec.inputSchema
3055
- }
3056
- };
3057
- const inside = /\(([\s\S]*)\)\s*$/.exec(spec.signature.trim())?.[1] ?? "";
3058
- const properties = {};
3059
- const required2 = [];
3060
- const params = [];
3061
- let depth = 0;
3062
- let current = "";
3063
- for (const ch of inside) {
3064
- if ("([{".includes(ch)) depth++;
3065
- if (")]}".includes(ch)) depth--;
3066
- if (ch === "," && depth === 0) {
3067
- params.push(current);
3068
- current = "";
3069
- } else current += ch;
3070
- }
3071
- if (current.trim()) params.push(current);
3072
- for (const raw of params) {
3073
- const param = raw.trim();
3074
- if (!param || param.startsWith("*") || param === "self") continue;
3075
- const eq = param.indexOf("=");
3076
- const name = (eq === -1 ? param : param.slice(0, eq)).split(":")[0].trim();
3077
- if (!name) continue;
3078
- if (eq === -1) {
3079
- properties[name] = { type: "string" };
3080
- required2.push(name);
3081
- continue;
3082
- }
3083
- const value = param.slice(eq + 1).trim();
3084
- if (/^-?\d+(\.\d+)?$/.test(value)) properties[name] = { type: "number" };
3085
- else if (value === "True" || value === "False")
3086
- properties[name] = { type: "boolean" };
3087
- else properties[name] = { type: "string" };
3088
- }
3089
- return {
3090
- type: "function",
3091
- function: {
3092
- name: modelToolName(spec.name),
3093
- description: spec.doc ?? spec.name,
3094
- parameters: { type: "object", properties, required: required2 }
3095
- }
3096
- };
3097
- }
3098
3298
  async function attachSession(sessionId, options = {}) {
3099
3299
  const state2 = await apiRequest(
3100
3300
  options,
@@ -3115,6 +3315,7 @@ async function openSession(slugOrRef, taskOrOpts = {}, positionalOpts = {}) {
3115
3315
  `Unknown world surfaces: ${unknown.join(", ")}; choose from ${SURFACE_KINDS.join(", ")}`
3116
3316
  );
3117
3317
  if (opts.browserTier !== void 0) assertBrowserTier(opts.browserTier);
3318
+ if (opts.auth !== void 0) assertSessionAuthMode(opts.auth);
3118
3319
  const at = slugOrRef.indexOf("@");
3119
3320
  const slug = at === -1 ? slugOrRef : slugOrRef.slice(0, at);
3120
3321
  const ref = at === -1 ? "" : slugOrRef.slice(at + 1);
@@ -3127,7 +3328,8 @@ async function openSession(slugOrRef, taskOrOpts = {}, positionalOpts = {}) {
3127
3328
  ...task === void 0 ? {} : { task },
3128
3329
  ...opts.reuseWarm === void 0 ? {} : { reuseWarm: opts.reuseWarm },
3129
3330
  ...opts.surfaces?.length ? { surfaces: opts.surfaces } : {},
3130
- ...opts.browserTier === void 0 ? {} : { browserTier: opts.browserTier }
3331
+ ...opts.browserTier === void 0 ? {} : { browserTier: opts.browserTier },
3332
+ ...opts.auth === void 0 ? {} : { auth: opts.auth }
3131
3333
  }
3132
3334
  );
3133
3335
  return new WorldSession(state2.sessionId, state2, options);
@@ -3208,7 +3410,7 @@ async function runSessions(opts) {
3208
3410
  passed: failed === 0 && (opts.failUnder === void 0 || mean >= opts.failUnder)
3209
3411
  };
3210
3412
  }
3211
- var CALL_TIMEOUT_MS, CALL_POLL_MS, JUDGED_GRADE_TIMEOUT_MS, JUDGED_GRADE_POLL_MS, EXPORT_PAGE, sleep4, modelToolName, WorldSession, OPEN_SESSION_OPTION_KEYS, isOpenSessionOptions;
3413
+ var CALL_TIMEOUT_MS, CALL_POLL_MS, JUDGED_GRADE_TIMEOUT_MS, JUDGED_GRADE_POLL_MS, EXPORT_PAGE, sleep4, WorldSession, OPEN_SESSION_OPTION_KEYS, isOpenSessionOptions;
3212
3414
  var init_session2 = __esm({
3213
3415
  "src/worlds/session.ts"() {
3214
3416
  "use strict";
@@ -3216,6 +3418,8 @@ var init_session2 = __esm({
3216
3418
  init_browser();
3217
3419
  init_nativeComputer();
3218
3420
  init_sessionContract();
3421
+ init_toolSchema();
3422
+ init_requestLedger();
3219
3423
  init_sessionReadiness();
3220
3424
  init_session();
3221
3425
  init_taskRef();
@@ -3229,7 +3433,6 @@ var init_session2 = __esm({
3229
3433
  JUDGED_GRADE_POLL_MS = 2e3;
3230
3434
  EXPORT_PAGE = 500;
3231
3435
  sleep4 = (ms) => new Promise((r) => setTimeout(r, ms));
3232
- modelToolName = (name) => name.replace(/[^A-Za-z0-9_-]/g, "_").slice(0, 64) || "tool";
3233
3436
  WorldSession = class {
3234
3437
  constructor(sessionId, current, options) {
3235
3438
  this.sessionId = sessionId;
@@ -3299,12 +3502,12 @@ var init_session2 = __esm({
3299
3502
  );
3300
3503
  return api2.url;
3301
3504
  }
3302
- /** Headers every request to `api()` needs. A World Host session gates its
3303
- * api surface on a per-session token; a pod or hosted twin answers with the
3304
- * world's own declared auth and this is `{}`. */
3505
+ /** Headers every request to `api()` needs: a World Host session's token in the
3506
+ * platform's `X-World-Session` header, which every world takes; `{}` for a pod
3507
+ * or hosted twin, which answers with the world's own declared auth. */
3305
3508
  async apiHeaders() {
3306
3509
  const { api: api2 } = await this.surfaces();
3307
- return api2?.token ? { Authorization: `Bearer ${api2.token}` } : {};
3510
+ return api2?.token ? { [PLATFORM_SESSION_HEADER]: api2.token } : {};
3308
3511
  }
3309
3512
  /** URL of the world's UI entry page for this session. */
3310
3513
  async ui() {
@@ -3375,11 +3578,28 @@ var init_session2 = __esm({
3375
3578
  }
3376
3579
  /** The session's latest platform state (one request, no waiting). */
3377
3580
  async status() {
3581
+ return this.refresh(
3582
+ await apiRequest(
3583
+ this.options,
3584
+ "GET",
3585
+ `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}`
3586
+ )
3587
+ );
3588
+ }
3589
+ /** The world started over under the same id, URLs and token, on what its pin (or `version`, which becomes
3590
+ * its pin) resolves to now: base data plus the task's seed. A grade then reads only the new world's requests. */
3591
+ async restart(opts = {}) {
3378
3592
  const fresh = await apiRequest(
3379
3593
  this.options,
3380
- "GET",
3381
- `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}`
3594
+ "POST",
3595
+ `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/restart`,
3596
+ opts.version ? { version: opts.version } : {}
3382
3597
  );
3598
+ this.refresh(fresh);
3599
+ return fresh;
3600
+ }
3601
+ // A status read carries neither the objective nor the open's notices; keep the ones we opened with.
3602
+ refresh(fresh) {
3383
3603
  this.current = {
3384
3604
  instruction: this.current.instruction,
3385
3605
  tools: this.current.tools,
@@ -3414,7 +3634,7 @@ var init_session2 = __esm({
3414
3634
  const { callId } = enqueued;
3415
3635
  const judged = enqueued.pending === true;
3416
3636
  const budgetMs = timeoutMs ?? (judged ? JUDGED_GRADE_TIMEOUT_MS : CALL_TIMEOUT_MS);
3417
- const pollMs2 = judged ? JUDGED_GRADE_POLL_MS : CALL_POLL_MS;
3637
+ const pollMs = judged ? JUDGED_GRADE_POLL_MS : CALL_POLL_MS;
3418
3638
  const deadline = Date.now() + budgetMs;
3419
3639
  for (; ; ) {
3420
3640
  const call = await apiRequest(
@@ -3430,7 +3650,7 @@ var init_session2 = __esm({
3430
3650
  throw new WorldSessionTimeout(
3431
3651
  judged ? `Grade ${callId} still ${call.state} after ${Math.round(budgetMs / 1e3)}s \u2014 the judge has not answered; the platform finalizes the call on its own, read it back with export().` : `Call ${callId} still ${call.state} after ${Math.round(budgetMs / 1e3)}s \u2014 the container may have died.`
3432
3652
  );
3433
- await sleep4(pollMs2);
3653
+ await sleep4(pollMs);
3434
3654
  }
3435
3655
  }
3436
3656
  /**
@@ -3523,19 +3743,31 @@ var init_session2 = __esm({
3523
3743
  async reset(opts = {}) {
3524
3744
  await this.exchange({ kind: "reset" }, opts.timeoutMs);
3525
3745
  }
3746
+ /** One page of the session's entries in its world's request ledger, newest
3747
+ * first and without bodies: at most `limit` after `cursor` (the last page's
3748
+ * `nextCursor`). Reading it records nothing in the session. */
3749
+ async requests(opts = {}) {
3750
+ return new WorldRequestLedger(this.options).forSession(
3751
+ this.sessionId,
3752
+ WorldRequestQuery.parse({ cursor: opts.cursor, limit: opts.limit ?? REQUEST_LOG_PAGE_MAX })
3753
+ );
3754
+ }
3755
+ page(route, limit, cursor) {
3756
+ const query = new URLSearchParams({ limit: String(limit) });
3757
+ if (cursor) query.set("cursor", cursor);
3758
+ return apiRequest(
3759
+ this.options,
3760
+ "GET",
3761
+ `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/${route}?${query.toString()}`
3762
+ );
3763
+ }
3526
3764
  /** The session's call log, oldest first: every tool call, seed, reset,
3527
3765
  * grade with its result — the record of the episode. */
3528
3766
  async export() {
3529
3767
  const calls = [];
3530
3768
  let cursor;
3531
3769
  do {
3532
- const params = new URLSearchParams({ limit: String(EXPORT_PAGE) });
3533
- if (cursor) params.set("cursor", cursor);
3534
- const page = await apiRequest(
3535
- this.options,
3536
- "GET",
3537
- `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/calls?${params.toString()}`
3538
- );
3770
+ const page = await this.page("calls", EXPORT_PAGE, cursor);
3539
3771
  for (const call of page.calls) {
3540
3772
  calls.push({
3541
3773
  seq: Number(call.seq),
@@ -3617,6 +3849,7 @@ var init_session2 = __esm({
3617
3849
  "reuseWarm",
3618
3850
  "surfaces",
3619
3851
  "browserTier",
3852
+ "auth",
3620
3853
  "options"
3621
3854
  ]);
3622
3855
  isOpenSessionOptions = (value) => typeof value === "object" && value !== null && Object.keys(value).every((key2) => OPEN_SESSION_OPTION_KEYS.has(key2));
@@ -3731,11 +3964,50 @@ var init_tasks = __esm({
3731
3964
  }
3732
3965
  });
3733
3966
 
3967
+ // src/worlds/taskGrades.ts
3968
+ var TASKS2, compact2, TaskGrades;
3969
+ var init_taskGrades = __esm({
3970
+ "src/worlds/taskGrades.ts"() {
3971
+ "use strict";
3972
+ init_worlds();
3973
+ TASKS2 = "/api/public/world-tasks";
3974
+ compact2 = (body) => Object.fromEntries(Object.entries(body).filter(([, v]) => v !== void 0));
3975
+ TaskGrades = class {
3976
+ constructor(options = {}) {
3977
+ this.options = options;
3978
+ }
3979
+ options;
3980
+ try(sessionId, target) {
3981
+ return apiRequest(
3982
+ this.options,
3983
+ "POST",
3984
+ `${TASKS2}/try`,
3985
+ compact2({ sessionId, ...target })
3986
+ );
3987
+ }
3988
+ regrade(taskId, scope = {}) {
3989
+ return apiRequest(
3990
+ this.options,
3991
+ "POST",
3992
+ `${TASKS2}/${encodeURIComponent(taskId)}/regrade`,
3993
+ compact2({ ...scope })
3994
+ );
3995
+ }
3996
+ };
3997
+ }
3998
+ });
3999
+
3734
4000
  // src/worlds/surfaceDescriptor.ts
3735
4001
  function surfaceDescriptor(s) {
3736
4002
  return {
3737
4003
  surfaces: surfaceKinds(s),
3738
- ...s.api ? { api: { url: s.api.url, ...s.api.token ? { token: s.api.token } : {} } } : {},
4004
+ ...s.api ? {
4005
+ api: {
4006
+ url: s.api.url,
4007
+ ...s.api.token ? { token: s.api.token } : {},
4008
+ ...s.api.auth ? { auth: s.api.auth } : {}
4009
+ }
4010
+ } : {},
3739
4011
  ...s.ui ? { ui: { url: s.ui.url, entry: uiEntryUrl(s.ui), apiPath: s.ui.apiPath ?? null } } : {},
3740
4012
  ...s.browser ? {
3741
4013
  browser: {
@@ -3785,8 +4057,7 @@ function fromResponse(answer, options) {
3785
4057
  sessions2[alias] = new WorldSession(state2.sessionId, state2, options);
3786
4058
  worlds[alias] = {
3787
4059
  slug: state2.slug,
3788
- ref: state2.ref,
3789
- private: state2.private ?? null
4060
+ ref: state2.ref
3790
4061
  };
3791
4062
  }
3792
4063
  return new TaskSessions(
@@ -3861,7 +4132,6 @@ async function attachTask(taskId, options = {}) {
3861
4132
  {
3862
4133
  slug: row.slug ?? "",
3863
4134
  ref: null,
3864
- private: null,
3865
4135
  versionId: row.versionId,
3866
4136
  sessionId: row.sessionId,
3867
4137
  ready: row.ready,
@@ -3891,7 +4161,7 @@ async function attachManifest(manifest, options = {}) {
3891
4161
  Object.fromEntries(
3892
4162
  Object.entries(manifest.sessions).map(([alias, entry]) => [
3893
4163
  alias,
3894
- { slug: entry.slug, ref: entry.ref, private: entry.private ?? null }
4164
+ { slug: entry.slug, ref: entry.ref }
3895
4165
  ])
3896
4166
  )
3897
4167
  );
@@ -3913,7 +4183,6 @@ var init_taskSessions = __esm({
3913
4183
  manifestSession = (s, state2, world) => ({
3914
4184
  slug: world.slug,
3915
4185
  ref: world.ref,
3916
- private: world.private,
3917
4186
  versionId: state2.versionId,
3918
4187
  sessionId: state2.sessionId,
3919
4188
  ready: state2.ready,
@@ -3970,7 +4239,7 @@ var init_taskSessions = __esm({
3970
4239
  /** This alias's world as recorded at open/attach — what a `TaskRun`
3971
4240
  * filing needs to name, without exposing the whole map. */
3972
4241
  worldRef(alias) {
3973
- return this.worlds[alias] ?? { slug: "", ref: null, private: null };
4242
+ return this.worlds[alias] ?? { slug: "", ref: null };
3974
4243
  }
3975
4244
  /** The aliases, in the spec's order. */
3976
4245
  get aliases() {
@@ -4295,16 +4564,12 @@ var init_taskRunOutcome = __esm({
4295
4564
  evaluationId;
4296
4565
  evaluationStatus = null;
4297
4566
  started = Date.now();
4298
- /** The run stopped short of a grade; the first reason stands. */
4299
4567
  stopped(error) {
4300
4568
  this.runError ??= messageOf(error).slice(0, 2e3);
4301
4569
  }
4302
4570
  agentRaised(error) {
4303
4571
  this.agentError = messageOf(error).slice(0, 2e3);
4304
4572
  }
4305
- /** Every reason the run failed, on one line: the evaluation's
4306
- * `metrics.error`. A run that never reached a grade has failed whatever
4307
- * its reasons say. */
4308
4573
  failure() {
4309
4574
  const reasons = [
4310
4575
  this.agentError === null ? null : `agent raised: ${this.agentError}`,
@@ -4400,6 +4665,7 @@ var init_taskRunOutcome = __esm({
4400
4665
  ])
4401
4666
  ),
4402
4667
  ungraded: this.grade?.ungraded ?? live.aliases,
4668
+ verifierVersion: live.taskVersion,
4403
4669
  traced: this.traced,
4404
4670
  runDir: this.runDir,
4405
4671
  ...this.agentError ? { agentError: this.agentError } : {},
@@ -4777,7 +5043,7 @@ var require_package = __commonJS({
4777
5043
  "package.json"(exports, module) {
4778
5044
  module.exports = {
4779
5045
  name: "@withgateway/sdk",
4780
- version: "0.3.3",
5046
+ version: "0.4.0",
4781
5047
  description: "Gateway SDK for TypeScript - A/B experiments, tracing, and observability",
4782
5048
  main: "./dist/index.js",
4783
5049
  module: "./dist/index.mjs",
@@ -6056,45 +6322,83 @@ var init_setRun = __esm({
6056
6322
  });
6057
6323
 
6058
6324
  // src/worlds/requestLog.ts
6059
- var WorldRequestLog;
6325
+ function worldRequestsUnrecorded(counts) {
6326
+ const parts2 = UNRECORDED.map(([field2, one, many]) => [counted(counts[field2]), one, many]).filter(([count]) => count > 0).map(([count, one, many]) => (count === 1 ? one : many).replace("{n}", String(count)));
6327
+ return parts2.length > 0 ? `Not recorded: ${parts2.join(", ")}` : null;
6328
+ }
6329
+ function counted(value) {
6330
+ return typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : 0;
6331
+ }
6332
+ var UNRECORDED, WorldRequestLog;
6060
6333
  var init_requestLog = __esm({
6061
6334
  "src/worlds/requestLog.ts"() {
6062
6335
  "use strict";
6336
+ init_requestLedger();
6337
+ UNRECORDED = [
6338
+ ["lost", "{n} request", "{n} requests"],
6339
+ ["shed", "{n} request's headers and bodies", "{n} requests' headers and bodies"],
6340
+ ["hostsLost", "the requests {n} lost host held", "the requests {n} lost hosts held"]
6341
+ ];
6063
6342
  WorldRequestLog = class _WorldRequestLog {
6064
- constructor(requests) {
6343
+ constructor(requests, notRecorded = null, unrecorded = null) {
6065
6344
  this.requests = requests;
6345
+ this.notRecorded = notRecorded;
6346
+ this.unrecorded = unrecorded;
6066
6347
  }
6067
6348
  requests;
6068
- static async read(session) {
6069
- const state2 = await session.state();
6070
- const calls = state2?.calls;
6071
- if (!Array.isArray(calls)) return null;
6072
- return new _WorldRequestLog(calls.filter((c) => typeof c === "object" && c !== null));
6073
- }
6074
- /** How many older requests the world no longer keeps (its log is bounded): the gap
6075
- * before the first entry it still holds. */
6076
- get dropped() {
6077
- const first = Number(this.requests[0]?.seq) || 1;
6078
- return Math.max(0, first - 1);
6079
- }
6080
- /** Each request in the shape of a ledger line, `kind: "request"`, so one JSONL
6081
- * file holds both. */
6349
+ notRecorded;
6350
+ unrecorded;
6351
+ /** Every entry the ledger holds for the session, oldest first, and the line for what it did not record;
6352
+ * for a session the World Host did not serve, none, and `notRecorded` says why. */
6353
+ static async load(session) {
6354
+ try {
6355
+ return await _WorldRequestLog.pages(session);
6356
+ } catch (error) {
6357
+ const refused = WorldRequestsNotRecorded.from(error);
6358
+ if (!(refused instanceof WorldRequestsNotRecorded)) throw error;
6359
+ return new _WorldRequestLog([], refused.message);
6360
+ }
6361
+ }
6362
+ static async pages(session) {
6363
+ const requests = [];
6364
+ let cursor;
6365
+ for (; ; ) {
6366
+ const page = await session.requests(cursor ? { cursor } : {});
6367
+ requests.push(...page.requests);
6368
+ if (!page.nextCursor || page.requests.length === 0)
6369
+ return new _WorldRequestLog(requests.reverse(), null, worldRequestsUnrecorded(page));
6370
+ cursor = page.nextCursor;
6371
+ }
6372
+ }
6373
+ /** Each entry in the shape of a ledger line, `kind: "request"`, so one JSONL
6374
+ * file holds both: `args` what was asked, `result` what came back under the
6375
+ * entry's `requestId`. */
6082
6376
  asCalls() {
6083
6377
  return this.requests.map((r) => ({
6084
- seq: Number(r.seq) || 0,
6378
+ seq: r.seq,
6085
6379
  kind: "request",
6086
- tool: r.operation ?? null,
6380
+ tool: r.operation,
6087
6381
  args: {
6088
- method: r.method ?? null,
6089
- path: r.path ?? null,
6090
- args: r.args ?? null,
6091
- query: r.query ?? null,
6092
- body: r.body ?? null,
6093
- via: r.via ?? null
6382
+ method: r.method,
6383
+ path: r.path,
6384
+ query: r.query,
6385
+ via: r.via,
6386
+ contentType: r.request.contentType,
6387
+ bodyBytes: r.request.bodyBytes,
6388
+ truncated: r.request.truncated
6389
+ },
6390
+ result: {
6391
+ requestId: r.id,
6392
+ status: r.response.status,
6393
+ rows: r.rows,
6394
+ found: r.found,
6395
+ durationMs: r.durationMs,
6396
+ contentType: r.response.contentType,
6397
+ bodyBytes: r.response.bodyBytes,
6398
+ truncated: r.response.truncated
6094
6399
  },
6095
- result: { status: r.status ?? null, rows: r.rows ?? null, found: r.found ?? null },
6096
6400
  error: null,
6097
- completedAt: r.at ?? null
6401
+ completedAt: r.at
6098
6402
  }));
6099
6403
  }
6100
6404
  };
@@ -6789,7 +7093,8 @@ function checkoutIdentity(ref, resolved) {
6789
7093
  async function pull(slugRef, target, options = {}, opts = {}) {
6790
7094
  const at = slugRef.indexOf("@");
6791
7095
  const slug = at === -1 ? slugRef : slugRef.slice(0, at);
6792
- const ref = at === -1 ? "latest" : slugRef.slice(at + 1);
7096
+ const asked = at === -1 ? void 0 : slugRef.slice(at + 1);
7097
+ const ref = asked ?? "latest";
6793
7098
  const landing = CheckoutTarget.resolve(slug, target, {
6794
7099
  cwd: process.cwd(),
6795
7100
  force: opts.force ?? false,
@@ -6797,7 +7102,7 @@ async function pull(slugRef, target, options = {}, opts = {}) {
6797
7102
  });
6798
7103
  const details = await apiRequest(options, "POST", "/api/public/benchmark-containers/resolve-version", {
6799
7104
  slug,
6800
- ref
7105
+ ...asked ? { ref: asked } : {}
6801
7106
  });
6802
7107
  if (!details.downloadUrl) {
6803
7108
  throw new Error(`${slug}@${ref} resolved but has no uploaded bundle`);
@@ -6983,7 +7288,7 @@ async function validateWorld(dir, opts) {
6983
7288
  options,
6984
7289
  "POST",
6985
7290
  "/api/public/benchmark-containers/resolve-version",
6986
- { slug, ref: branch }
7291
+ { slug, ...branch === DEFAULT_BRANCH ? {} : { ref: branch } }
6987
7292
  );
6988
7293
  tipVersionId = tip.versionId ?? null;
6989
7294
  } catch {
@@ -7090,11 +7395,16 @@ var init_validate = __esm({
7090
7395
  });
7091
7396
 
7092
7397
  // src/worlds/sandbox.ts
7398
+ import { createHash as createHash6, randomUUID as randomUUID2 } from "crypto";
7093
7399
  function parseSlugRef(slugRef) {
7094
7400
  const at = slugRef.indexOf("@");
7095
7401
  if (at === -1) return { slug: slugRef };
7096
7402
  return { slug: slugRef.slice(0, at), ref: slugRef.slice(at + 1) };
7097
7403
  }
7404
+ function nameGlob(pattern) {
7405
+ const literal = (part) => part.replace(/[.+?^${}()|[\]\\]/g, "\\$&");
7406
+ return new RegExp(`^${pattern.split("*").map(literal).join(".*")}$`);
7407
+ }
7098
7408
  function rebaseConflicts(error) {
7099
7409
  if (!(error instanceof ApiError) || error.status !== 409) return null;
7100
7410
  let body;
@@ -7112,7 +7422,8 @@ function isConflictPath(value) {
7112
7422
  return typeof entry?.path === "string" && typeof entry.reason === "string";
7113
7423
  }
7114
7424
  function uncommittedPaths(error) {
7115
- if (!(error instanceof ApiError) || error.status !== 409 || error.code !== "sandbox_uncommitted") return null;
7425
+ if (!(error instanceof ApiError) || error.status !== 409 || error.code !== "sandbox_uncommitted")
7426
+ return null;
7116
7427
  let body;
7117
7428
  try {
7118
7429
  body = JSON.parse(error.text);
@@ -7123,6 +7434,53 @@ function uncommittedPaths(error) {
7123
7434
  if (!Array.isArray(uncommitted)) return null;
7124
7435
  return uncommitted.filter((p) => typeof p === "string");
7125
7436
  }
7437
+ function carriedWarnings(error) {
7438
+ const kept = typeof error === "object" && error !== null ? carried.get(error) ?? [] : [];
7439
+ const shown = error instanceof Error ? error.message : "";
7440
+ return unique([...kept, ...bodyWarnings(error)]).filter((warning) => !shown.includes(warning));
7441
+ }
7442
+ function carrying(error, warnings) {
7443
+ if (warnings.length > 0 && typeof error === "object" && error !== null)
7444
+ carried.set(error, unique([...carried.get(error) ?? [], ...warnings]));
7445
+ return error;
7446
+ }
7447
+ function unique(warnings) {
7448
+ return [...new Set(warnings)];
7449
+ }
7450
+ function bodyWarnings(error) {
7451
+ if (!(error instanceof ApiError)) return [];
7452
+ let body;
7453
+ try {
7454
+ body = JSON.parse(error.text);
7455
+ } catch {
7456
+ return [];
7457
+ }
7458
+ const warnings = body?.warnings;
7459
+ if (!Array.isArray(warnings)) return [];
7460
+ return warnings.filter((w) => typeof w === "string");
7461
+ }
7462
+ function deferredWarnings(error) {
7463
+ if (!(error instanceof ApiError) || error.status !== 409 || error.code !== "sandbox_exec_deferred") return null;
7464
+ return bodyWarnings(error);
7465
+ }
7466
+ function rowsRefusal(error) {
7467
+ if (!(error instanceof ApiError) || error.status !== 400 || error.code !== "rows_refused") return null;
7468
+ let body;
7469
+ try {
7470
+ body = JSON.parse(error.text);
7471
+ } catch {
7472
+ return null;
7473
+ }
7474
+ const { message, batchId, refusalCount, refusals, reportUrl } = body;
7475
+ if (typeof batchId !== "string" || typeof refusalCount !== "number" || !Array.isArray(refusals)) return null;
7476
+ return {
7477
+ message: typeof message === "string" ? message : "",
7478
+ batchId,
7479
+ refusalCount,
7480
+ refusals: refusals.filter((r) => typeof r === "object" && r !== null),
7481
+ reportUrl: typeof reportUrl === "string" ? reportUrl : null
7482
+ };
7483
+ }
7126
7484
  function listQuery(filter) {
7127
7485
  const params = new URLSearchParams();
7128
7486
  if (filter.status) params.set("status", filter.status);
@@ -7131,15 +7489,51 @@ function listQuery(filter) {
7131
7489
  const qs3 = params.toString();
7132
7490
  return qs3 ? `?${qs3}` : "";
7133
7491
  }
7134
- var isSandboxImportPending, sid, SANDBOXES, SANDBOX_REQUEST_TIMEOUT_MS, WorldSandboxClient;
7492
+ var isSandboxCommitPending, isSandboxImportPending, sid, SANDBOXES, SANDBOX_REQUEST_TIMEOUT_MS, SANDBOX_WRITE_CHUNK_BYTES, SANDBOX_FILE_MAX_BYTES, SANDBOX_WRITE_SKIPPED, WriteTreeFilter, SANDBOX_EXEC_WAIT_MS, SANDBOX_EXEC_TIMEOUT_MAX_S, SANDBOX_EXEC_REPORT_MARGIN_MS, SANDBOX_EXEC_START_ATTEMPTS, carried, WorldSandboxClient;
7135
7493
  var init_sandbox = __esm({
7136
7494
  "src/worlds/sandbox.ts"() {
7137
7495
  "use strict";
7138
7496
  init_worlds();
7497
+ isSandboxCommitPending = (answer) => !("versionId" in answer);
7139
7498
  isSandboxImportPending = (answer) => !("versionId" in answer);
7140
7499
  sid = encodeURIComponent;
7141
7500
  SANDBOXES = "/api/public/benchmark-containers/sandboxes";
7142
- SANDBOX_REQUEST_TIMEOUT_MS = 66e4;
7501
+ SANDBOX_REQUEST_TIMEOUT_MS = 29e4;
7502
+ SANDBOX_WRITE_CHUNK_BYTES = 4 * 1024 * 1024;
7503
+ SANDBOX_FILE_MAX_BYTES = 256 * 1024 * 1024;
7504
+ SANDBOX_WRITE_SKIPPED = [
7505
+ ".git/",
7506
+ ".gateway/",
7507
+ "scratch/",
7508
+ ".scratch/",
7509
+ "__pycache__/",
7510
+ "*.pyc",
7511
+ ".pytest_cache/",
7512
+ ".mypy_cache/",
7513
+ ".ruff_cache/",
7514
+ "node_modules/",
7515
+ ".venv/",
7516
+ "venv/",
7517
+ ".DS_Store",
7518
+ "*.swp"
7519
+ ];
7520
+ WriteTreeFilter = class {
7521
+ directories = new Set(
7522
+ SANDBOX_WRITE_SKIPPED.filter((pattern) => pattern.endsWith("/")).map((pattern) => pattern.slice(0, -1))
7523
+ );
7524
+ files = SANDBOX_WRITE_SKIPPED.filter((pattern) => !pattern.endsWith("/")).map(nameGlob);
7525
+ skipsDirectory(name) {
7526
+ return this.directories.has(name);
7527
+ }
7528
+ skipsFile(name) {
7529
+ return this.files.some((glob) => glob.test(name));
7530
+ }
7531
+ };
7532
+ SANDBOX_EXEC_WAIT_MS = 4e4;
7533
+ SANDBOX_EXEC_TIMEOUT_MAX_S = 600;
7534
+ SANDBOX_EXEC_REPORT_MARGIN_MS = 35e3;
7535
+ SANDBOX_EXEC_START_ATTEMPTS = 3;
7536
+ carried = /* @__PURE__ */ new WeakMap();
7143
7537
  WorldSandboxClient = class {
7144
7538
  constructor(options = {}) {
7145
7539
  this.options = options;
@@ -7164,7 +7558,10 @@ var init_sandbox = __esm({
7164
7558
  }
7165
7559
  /** The project's sandboxes, newest first — how an agent finds one it left open. */
7166
7560
  async list(filter = {}) {
7167
- const res = await this.request("GET", `${SANDBOXES}${listQuery(filter)}`);
7561
+ const res = await this.request(
7562
+ "GET",
7563
+ `${SANDBOXES}${listQuery(filter)}`
7564
+ );
7168
7565
  return res.sandboxes;
7169
7566
  }
7170
7567
  async read(sandboxId, filePath) {
@@ -7172,16 +7569,72 @@ var init_sandbox = __esm({
7172
7569
  "GET",
7173
7570
  `${SANDBOXES}/${sid(sandboxId)}/file?path=${encodeURIComponent(filePath)}`
7174
7571
  );
7175
- return { path: res.path, size: res.size, bytes: Buffer.from(res.contentBase64, "base64") };
7572
+ return {
7573
+ path: res.path,
7574
+ size: res.size,
7575
+ bytes: Buffer.from(res.contentBase64, "base64")
7576
+ };
7176
7577
  }
7177
- write(sandboxId, filePath, bytes) {
7178
- return this.request("PUT", `${SANDBOXES}/${sid(sandboxId)}/file`, {
7179
- path: filePath,
7180
- contentBase64: bytes.toString("base64")
7181
- });
7578
+ /** A file past one chunk goes up in parts under one upload id; the platform lands it whole once the last part's
7579
+ * size and SHA-256 check out. */
7580
+ async write(sandboxId, filePath, bytes) {
7581
+ if (bytes.length <= SANDBOX_WRITE_CHUNK_BYTES)
7582
+ return this.putFile(sandboxId, { path: filePath, contentBase64: bytes.toString("base64") });
7583
+ const whole = { upload: randomUUID2(), size: bytes.length, sha256: createHash6("sha256").update(bytes).digest("hex") };
7584
+ let answer = { path: filePath, received: 0 };
7585
+ for (let offset = 0; offset < bytes.length; offset += SANDBOX_WRITE_CHUNK_BYTES) {
7586
+ const part = bytes.subarray(offset, offset + SANDBOX_WRITE_CHUNK_BYTES);
7587
+ answer = await this.putFile(sandboxId, {
7588
+ path: filePath,
7589
+ contentBase64: part.toString("base64"),
7590
+ ...whole,
7591
+ offset,
7592
+ last: offset + part.length === bytes.length
7593
+ });
7594
+ }
7595
+ return answer;
7596
+ }
7597
+ putFile(sandboxId, body) {
7598
+ return this.request("PUT", `${SANDBOXES}/${sid(sandboxId)}/file`, body);
7599
+ }
7600
+ /** Runs as a job on the platform: a command that outlasts one request is waited on again until its result. */
7601
+ async exec(sandboxId, input) {
7602
+ const budgetMs = (input.timeoutMs ?? SANDBOX_EXEC_TIMEOUT_MAX_S * 1e3) + SANDBOX_EXEC_REPORT_MARGIN_MS;
7603
+ let answer = await this.startExec(sandboxId, { ...input, waitMs: SANDBOX_EXEC_WAIT_MS });
7604
+ const deadline = Date.now() + budgetMs;
7605
+ const warnings = [...answer.warnings ?? []];
7606
+ try {
7607
+ while ("state" in answer) {
7608
+ if (Date.now() >= deadline)
7609
+ throw new Error(
7610
+ `exec ${answer.execId} in sandbox ${sandboxId} has not reported back within ${budgetMs / 1e3} s, past its timeout: the sandbox may have restarted. Check the sandbox's status, then run the command again.`
7611
+ );
7612
+ answer = await this.execStep(sandboxId, { execId: answer.execId, waitMs: SANDBOX_EXEC_WAIT_MS });
7613
+ warnings.push(...answer.warnings ?? []);
7614
+ }
7615
+ } catch (error) {
7616
+ throw carrying(error, warnings);
7617
+ }
7618
+ return { ...answer, warnings };
7619
+ }
7620
+ // A deferred start ran nothing (the platform was still getting the sandbox ready), so starting again is safe. What
7621
+ // getting ready found rides on the deferral alone (no later call reports it), so it is kept for the answer, or for
7622
+ // the error when a later attempt fails.
7623
+ async startExec(sandboxId, body) {
7624
+ const kept = [];
7625
+ for (let attempt = 1; ; attempt += 1) {
7626
+ try {
7627
+ const answer = await this.execStep(sandboxId, body);
7628
+ return { ...answer, warnings: unique([...kept, ...answer.warnings ?? []]) };
7629
+ } catch (error) {
7630
+ const warnings = deferredWarnings(error);
7631
+ if (warnings === null || attempt === SANDBOX_EXEC_START_ATTEMPTS) throw carrying(error, kept);
7632
+ kept.push(...warnings);
7633
+ }
7634
+ }
7182
7635
  }
7183
- exec(sandboxId, input) {
7184
- return this.request("POST", `${SANDBOXES}/${sid(sandboxId)}/exec`, input);
7636
+ execStep(sandboxId, body) {
7637
+ return this.request("POST", `${SANDBOXES}/${sid(sandboxId)}/exec`, body);
7185
7638
  }
7186
7639
  check(sandboxId) {
7187
7640
  return this.request("POST", `${SANDBOXES}/${sid(sandboxId)}/check`, {});
@@ -7189,7 +7642,11 @@ var init_sandbox = __esm({
7189
7642
  /** With `rebase`, a moved base is replayed onto; a 409 then names the conflicting paths (`rebaseConflicts`). */
7190
7643
  commit(sandboxId, input) {
7191
7644
  const { rebase, ...rest } = input;
7192
- return this.request("POST", `${SANDBOXES}/${sid(sandboxId)}/commit`, rebase ? { ...rest, rebase: true } : rest);
7645
+ return this.request(
7646
+ "POST",
7647
+ `${SANDBOXES}/${sid(sandboxId)}/commit`,
7648
+ rebase ? { ...rest, rebase: true } : rest
7649
+ );
7193
7650
  }
7194
7651
  /**
7195
7652
  * A rows file already in the sandbox tree into the PLATFORM world the
@@ -7202,7 +7659,11 @@ var init_sandbox = __esm({
7202
7659
  }
7203
7660
  /** Uncommitted work is a 409 (`uncommittedPaths`) unless `force` discards it. */
7204
7661
  close(sandboxId, opts = {}) {
7205
- return this.request("DELETE", `${SANDBOXES}/${sid(sandboxId)}`, opts.force ? { force: true } : void 0);
7662
+ return this.request(
7663
+ "DELETE",
7664
+ `${SANDBOXES}/${sid(sandboxId)}`,
7665
+ opts.force ? { force: true } : void 0
7666
+ );
7206
7667
  }
7207
7668
  };
7208
7669
  }
@@ -7521,7 +7982,7 @@ var init_json = __esm({
7521
7982
  });
7522
7983
 
7523
7984
  // src/worlds/transforms.ts
7524
- import { createHash as createHash6 } from "crypto";
7985
+ import { createHash as createHash7 } from "crypto";
7525
7986
  function parseTransform(name) {
7526
7987
  const simple = Object.prototype.hasOwnProperty.call(SIMPLE, name) ? SIMPLE[name] : void 0;
7527
7988
  if (simple) return simple;
@@ -7559,7 +8020,7 @@ var init_transforms = __esm({
7559
8020
  return at === -1 ? "" : value.slice(at + 1).toLowerCase();
7560
8021
  };
7561
8022
  stripPrefix = (prefix) => (value) => value.startsWith(prefix) ? value.slice(prefix.length) : value;
7562
- hex = (algorithm, value) => createHash6(algorithm).update(value, "utf8").digest("hex");
8023
+ hex = (algorithm, value) => createHash7(algorithm).update(value, "utf8").digest("hex");
7563
8024
  SIMPLE = {
7564
8025
  lower: (value) => value.toLowerCase(),
7565
8026
  upper: (value) => value.toUpperCase(),
@@ -7583,7 +8044,7 @@ var init_transforms = __esm({
7583
8044
  });
7584
8045
 
7585
8046
  // src/worlds/redaction.ts
7586
- import { createHash as createHash7 } from "crypto";
8047
+ import { createHash as createHash8 } from "crypto";
7587
8048
  function pyText(value) {
7588
8049
  if (typeof value === "string") return value;
7589
8050
  if (Number.isInteger(value)) return String(value);
@@ -7592,7 +8053,7 @@ function pyText(value) {
7592
8053
  return pyFloatRepr(value);
7593
8054
  }
7594
8055
  function hashForm(slug, plaintext) {
7595
- return "sha256:" + createHash7("sha256").update(`${slug}:${pyText(plaintext)}`, "utf8").digest("hex");
8056
+ return "sha256:" + createHash8("sha256").update(`${slug}:${pyText(plaintext)}`, "utf8").digest("hex");
7596
8057
  }
7597
8058
  function preserveForm(slug, plaintext) {
7598
8059
  const kind = typeof plaintext === "string" ? "str" : isInt(plaintext) ? "int" : "float";
@@ -7601,12 +8062,12 @@ function preserveForm(slug, plaintext) {
7601
8062
  }
7602
8063
  function shapeText(slug, text2, kind) {
7603
8064
  const seed = Buffer.from(`${slug}:${text2}`, "utf8");
7604
- let digest = createHash7("sha256").update(seed).digest();
8065
+ let digest = createHash8("sha256").update(seed).digest();
7605
8066
  let cursor = 0;
7606
8067
  const out = [];
7607
8068
  for (const char of text2) {
7608
8069
  if (cursor === digest.length) {
7609
- digest = createHash7("sha256").update(Buffer.concat([digest, seed])).digest();
8070
+ digest = createHash8("sha256").update(Buffer.concat([digest, seed])).digest();
7610
8071
  cursor = 0;
7611
8072
  }
7612
8073
  const byte = digest[cursor];
@@ -7759,7 +8220,7 @@ var init_config = __esm({
7759
8220
  init_transport();
7760
8221
  ApiError2 = class extends CliError {
7761
8222
  constructor(status, method, route, text2) {
7762
- const body = parseErrorBody(text2);
8223
+ const body = parseErrorBody(text2, status);
7763
8224
  super(`${method} ${route} -> ${status}: ${body.detail}`, 1);
7764
8225
  this.status = status;
7765
8226
  this.method = method;
@@ -7781,6 +8242,14 @@ import { spawn, spawnSync } from "child_process";
7781
8242
  import * as fs7 from "fs";
7782
8243
  import * as net from "net";
7783
8244
  import * as path8 from "path";
8245
+ function forwardedEnv() {
8246
+ return Object.fromEntries(
8247
+ FORWARDED_ENV.flatMap((name) => {
8248
+ const value = process.env[name];
8249
+ return value ? [[name, value]] : [];
8250
+ })
8251
+ );
8252
+ }
7784
8253
  function tailOf(output) {
7785
8254
  return output.length > DIAGNOSTIC_TAIL ? `\u2026${output.slice(-DIAGNOSTIC_TAIL)}` : output;
7786
8255
  }
@@ -7898,7 +8367,7 @@ async function localBridge(request, local, opts = {}) {
7898
8367
  PATH: process.env.PATH ?? "",
7899
8368
  HOME: process.env.HOME ?? "",
7900
8369
  TMPDIR: process.env.TMPDIR ?? "",
7901
- ...process.env.VIRTUAL_ENV ? { VIRTUAL_ENV: process.env.VIRTUAL_ENV } : {},
8370
+ ...forwardedEnv(),
7902
8371
  GATEWAY_RUNTIME_EXECUTE: "1"
7903
8372
  }
7904
8373
  }
@@ -7944,7 +8413,7 @@ async function localBridge(request, local, opts = {}) {
7944
8413
  child.stdin.end(input);
7945
8414
  });
7946
8415
  }
7947
- var MIN_PYTHON, MIN_PYTHON_LABEL, DIAGNOSTIC_TAIL, BRIDGE_BOOTSTRAP, pythonCache, pythonProbes, PYTHON_CANDIDATES, UV_FIND;
8416
+ var MIN_PYTHON, MIN_PYTHON_LABEL, DIAGNOSTIC_TAIL, FORWARDED_ENV, BRIDGE_BOOTSTRAP, pythonCache, pythonProbes, PYTHON_CANDIDATES, UV_FIND;
7948
8417
  var init_local = __esm({
7949
8418
  "src/cli/runtime/local.ts"() {
7950
8419
  "use strict";
@@ -7953,6 +8422,7 @@ var init_local = __esm({
7953
8422
  MIN_PYTHON = [3, 12];
7954
8423
  MIN_PYTHON_LABEL = MIN_PYTHON.join(".");
7955
8424
  DIAGNOSTIC_TAIL = 600;
8425
+ FORWARDED_ENV = ["VIRTUAL_ENV", "GATEWAY_SNAPSHOT_STORE"];
7956
8426
  BRIDGE_BOOTSTRAP = `import sys,runpy,types,os
7957
8427
  root=sys.argv[1]
7958
8428
  package=types.ModuleType('gatewaysdk')
@@ -8581,18 +9051,22 @@ if (fn) {
8581
9051
  });
8582
9052
 
8583
9053
  // src/cli/platform/worldData/batches.ts
8584
- import { createHash as createHash8 } from "crypto";
9054
+ import { createHash as createHash9 } from "crypto";
8585
9055
  import * as fs11 from "fs";
8586
9056
  function isSettled(status) {
8587
9057
  if (!TERMINAL_STATES.has(status.state)) return false;
8588
9058
  if (status.state !== "applied") return true;
8589
9059
  return status.dryRun === true || status.publish !== "now" || !status.snapshotId;
8590
9060
  }
9061
+ function worldDataPollMs() {
9062
+ const raw = Number(process.env.GATEWAY_WORLD_DATA_POLL_MS ?? 1e3);
9063
+ return Number.isFinite(raw) && raw >= 0 ? raw : 1e3;
9064
+ }
8591
9065
  function uploadHeadersFor(gz) {
8592
9066
  return {
8593
9067
  "content-type": "application/gzip",
8594
9068
  "content-length": String(gz.length),
8595
- "x-amz-checksum-sha256": createHash8("sha256").update(gz).digest("base64")
9069
+ "x-amz-checksum-sha256": createHash9("sha256").update(gz).digest("base64")
8596
9070
  };
8597
9071
  }
8598
9072
  async function forEachLimited(items, limit, fn) {
@@ -8630,6 +9104,8 @@ async function waitForBatch(client2, batchId, opts = {}) {
8630
9104
  last = phase;
8631
9105
  }
8632
9106
  if (isSettled(status)) return status;
9107
+ if (opts.deadlineMs !== void 0 && (opts.now ?? Date.now)() >= opts.deadlineMs)
9108
+ return status;
8633
9109
  await sleep5(delay);
8634
9110
  delay = Math.min(1e4, Math.round(delay * 1.5));
8635
9111
  }
@@ -8679,11 +9155,6 @@ var init_batches = __esm({
8679
9155
  }
8680
9156
  );
8681
9157
  }
8682
- /**
8683
- * Stage a project-drive rows file as one chunk, on the platform: the server
8684
- * streams it out of drive storage into chunk storage and answers with the
8685
- * digest and gzipped size it derived. No bytes pass through this process.
8686
- */
8687
9158
  async stageDrive(batchId, chunk) {
8688
9159
  const staged = await api(this.creds, "POST", `${this.base}/batches/${batchId}/chunks`, {
8689
9160
  ordinal: chunk.ordinal,
@@ -8737,11 +9208,6 @@ var init_batches = __esm({
8737
9208
  message ? { message } : {}
8738
9209
  );
8739
9210
  }
8740
- /**
8741
- * PUT the gzipped chunk to its presigned URL with exactly the headers the
8742
- * URL was signed for (the platform's `uploadHeaders`; the same three when it
8743
- * sends none), with backoff on a dropped connection or a 5xx.
8744
- */
8745
9211
  async put(uploadUrl, gz, signed) {
8746
9212
  const headers = signed ?? uploadHeadersFor(gz);
8747
9213
  const delays = [500, 1500, 4e3];
@@ -8768,7 +9234,6 @@ var init_batches = __esm({
8768
9234
  await this.sleep(delays[attempt]);
8769
9235
  }
8770
9236
  }
8771
- /** Register, upload unless the server already holds the content, confirm. */
8772
9237
  async upload(batchId, chunk) {
8773
9238
  const registered = await this.register(batchId, chunk);
8774
9239
  if (!registered.uploaded) {
@@ -8795,7 +9260,7 @@ var init_batches = __esm({
8795
9260
  });
8796
9261
 
8797
9262
  // src/cli/platform/worldData/chunker.ts
8798
- import { createHash as createHash9 } from "crypto";
9263
+ import { createHash as createHash10 } from "crypto";
8799
9264
  import { deflateRawSync } from "zlib";
8800
9265
  function chunkLine(row, declared) {
8801
9266
  if (declared !== null) return dumps(row.row) + "\n";
@@ -8836,12 +9301,12 @@ function finishChunk(ordinal, raw, rows, entity, firstRow = 0) {
8836
9301
  const gz = gzipDeterministic(raw, { name: chunkName(ordinal) });
8837
9302
  return {
8838
9303
  ordinal,
8839
- digest: createHash9("sha256").update(gz).digest("hex"),
9304
+ digest: createHash10("sha256").update(gz).digest("hex"),
8840
9305
  bytes: gz.length,
8841
9306
  rows,
8842
9307
  entity,
8843
9308
  rawBytes: raw.length,
8844
- contentSha256: createHash9("sha256").update(raw).digest("hex"),
9309
+ contentSha256: createHash10("sha256").update(raw).digest("hex"),
8845
9310
  firstRow,
8846
9311
  gz
8847
9312
  };
@@ -8909,22 +9374,33 @@ async function pushRows(creds, slug, rows, opts = {}) {
8909
9374
  publish: opts.publish ?? "now",
8910
9375
  ...opts.message ? { message: opts.message } : {}
8911
9376
  });
8912
- if (!opened.batchId) throw new Error("the platform opened no batch (no batchId in the answer)");
9377
+ if (!opened.batchId)
9378
+ throw new Error("the platform opened no batch (no batchId in the answer)");
8913
9379
  const tagged = (async function* () {
8914
9380
  for (const [entity, listed] of Object.entries(rows))
8915
9381
  for (let index2 = 0; index2 < listed.length; index2++)
8916
- yield { entity, row: parseJson(JSON.stringify(listed[index2])), where: `${entity}[${index2}]` };
9382
+ yield {
9383
+ entity,
9384
+ row: parseJson(JSON.stringify(listed[index2])),
9385
+ where: `${entity}[${index2}]`
9386
+ };
8917
9387
  })();
8918
- const chunks = buildChunks(tagged, { chunkBytes: opts.chunkBytes ?? DEFAULT_CHUNK_BYTES, chunkRows: null, entity: null });
8919
- await forEachLimited(chunks, Math.max(1, opts.parallel ?? 4), async (chunk) => {
8920
- await client2.upload(opened.batchId, chunk);
9388
+ const chunks = buildChunks(tagged, {
9389
+ chunkBytes: opts.chunkBytes ?? DEFAULT_CHUNK_BYTES,
9390
+ chunkRows: null,
9391
+ entity: null
8921
9392
  });
9393
+ await forEachLimited(
9394
+ chunks,
9395
+ Math.max(1, opts.parallel ?? 4),
9396
+ async (chunk) => {
9397
+ await client2.upload(opened.batchId, chunk);
9398
+ }
9399
+ );
8922
9400
  await client2.complete(opened.batchId);
8923
- return waitForBatch(client2, opened.batchId, { initialDelayMs: pollMs() });
8924
- }
8925
- function pollMs() {
8926
- const raw = Number(process.env.GATEWAY_WORLD_DATA_POLL_MS ?? 1e3);
8927
- return Number.isFinite(raw) && raw >= 0 ? raw : 1e3;
9401
+ return waitForBatch(client2, opened.batchId, {
9402
+ initialDelayMs: worldDataPollMs()
9403
+ });
8928
9404
  }
8929
9405
  var init_push = __esm({
8930
9406
  "src/cli/platform/worldData/push.ts"() {
@@ -9173,12 +9649,12 @@ var init_ingest = __esm({
9173
9649
  });
9174
9650
 
9175
9651
  // src/worlds/editSessions.ts
9176
- var WORLDS, WorldEditClient, TASK_EDITS, TaskEditClient;
9652
+ var WORLDS2, WorldEditClient, TASK_EDITS, TaskEditClient;
9177
9653
  var init_editSessions = __esm({
9178
9654
  "src/worlds/editSessions.ts"() {
9179
9655
  "use strict";
9180
9656
  init_worlds();
9181
- WORLDS = "/api/public/worlds";
9657
+ WORLDS2 = "/api/public/worlds";
9182
9658
  WorldEditClient = class {
9183
9659
  constructor(options = {}) {
9184
9660
  this.options = options;
@@ -9190,19 +9666,19 @@ var init_editSessions = __esm({
9190
9666
  if (query.status) qs3.set("status", query.status);
9191
9667
  if (query.limit !== void 0) qs3.set("limit", String(query.limit));
9192
9668
  const suffix = qs3.size ? `?${qs3.toString()}` : "";
9193
- return apiRequest(this.options, "GET", `${WORLDS}/${encodeURIComponent(slug)}/edits${suffix}`);
9669
+ return apiRequest(this.options, "GET", `${WORLDS2}/${encodeURIComponent(slug)}/edits${suffix}`);
9194
9670
  }
9195
9671
  /** Seal a session into a version on main (the credential's current one when `sessionId` is omitted). */
9196
9672
  close(slug, input = {}) {
9197
- return apiRequest(this.options, "POST", `${WORLDS}/${encodeURIComponent(slug)}/edits/close`, input);
9673
+ return apiRequest(this.options, "POST", `${WORLDS2}/${encodeURIComponent(slug)}/edits/close`, input);
9198
9674
  }
9199
9675
  /** Drop the session's private branch without making a version. */
9200
9676
  discard(slug, input = {}) {
9201
- return apiRequest(this.options, "POST", `${WORLDS}/${encodeURIComponent(slug)}/edits/discard`, input);
9677
+ return apiRequest(this.options, "POST", `${WORLDS2}/${encodeURIComponent(slug)}/edits/discard`, input);
9202
9678
  }
9203
9679
  /** Undo a sealed session (source and data) as a new sealed session. */
9204
9680
  rollback(slug, input) {
9205
- return apiRequest(this.options, "POST", `${WORLDS}/${encodeURIComponent(slug)}/edits/rollback`, input);
9681
+ return apiRequest(this.options, "POST", `${WORLDS2}/${encodeURIComponent(slug)}/edits/rollback`, input);
9206
9682
  }
9207
9683
  };
9208
9684
  TASK_EDITS = "/api/public/world-task-edits";
@@ -9356,15 +9832,27 @@ __export(worlds_exports, {
9356
9832
  NativeComputer: () => NativeComputer,
9357
9833
  OpenAIComputer: () => OpenAIComputer,
9358
9834
  OpenAIPreviewComputer: () => OpenAIPreviewComputer,
9835
+ PLATFORM_SESSION_HEADER: () => PLATFORM_SESSION_HEADER,
9359
9836
  PLATFORM_TIMEOUT_DEFAULT_MS: () => PLATFORM_TIMEOUT_DEFAULT_MS,
9360
9837
  PLATFORM_TIMEOUT_ENV: () => PLATFORM_TIMEOUT_ENV,
9361
9838
  PendingSafetyChecks: () => PendingSafetyChecks,
9362
9839
  PlatformTransport: () => PlatformTransport,
9363
9840
  PushSlugConflict: () => PushSlugConflict,
9364
9841
  RECOVER_BUDGET_MS: () => RECOVER_BUDGET_MS,
9842
+ REQUESTS_NOT_RECORDED: () => REQUESTS_NOT_RECORDED,
9843
+ REQUEST_BODY_CAPTURE_BYTES: () => REQUEST_BODY_CAPTURE_BYTES,
9844
+ REQUEST_LOG_PAGE_MAX: () => REQUEST_LOG_PAGE_MAX,
9365
9845
  RetryPolicy: () => RetryPolicy,
9846
+ SANDBOX_EXEC_REPORT_MARGIN_MS: () => SANDBOX_EXEC_REPORT_MARGIN_MS,
9847
+ SANDBOX_EXEC_START_ATTEMPTS: () => SANDBOX_EXEC_START_ATTEMPTS,
9848
+ SANDBOX_EXEC_TIMEOUT_MAX_S: () => SANDBOX_EXEC_TIMEOUT_MAX_S,
9849
+ SANDBOX_EXEC_WAIT_MS: () => SANDBOX_EXEC_WAIT_MS,
9850
+ SANDBOX_FILE_MAX_BYTES: () => SANDBOX_FILE_MAX_BYTES,
9366
9851
  SANDBOX_REQUEST_TIMEOUT_MS: () => SANDBOX_REQUEST_TIMEOUT_MS,
9852
+ SANDBOX_WRITE_CHUNK_BYTES: () => SANDBOX_WRITE_CHUNK_BYTES,
9853
+ SANDBOX_WRITE_SKIPPED: () => SANDBOX_WRITE_SKIPPED,
9367
9854
  SECRET_KEY: () => SECRET_KEY,
9855
+ SESSION_AUTH_MODES: () => SESSION_AUTH_MODES,
9368
9856
  SESSION_STATES: () => SESSION_STATES,
9369
9857
  SPAN_PREFIX: () => SPAN_PREFIX,
9370
9858
  STATUS_WAIT_CAP_SECONDS: () => STATUS_WAIT_CAP_SECONDS,
@@ -9376,17 +9864,23 @@ __export(worlds_exports, {
9376
9864
  TOOL_CONTRACT_UNREAD: () => TOOL_CONTRACT_UNREAD,
9377
9865
  TRANSFORMS: () => TRANSFORMS,
9378
9866
  TaskEditClient: () => TaskEditClient,
9867
+ TaskGrades: () => TaskGrades,
9379
9868
  TaskRun: () => TaskRun,
9380
9869
  TaskSessions: () => TaskSessions,
9381
9870
  TransportCause: () => TransportCause,
9382
9871
  UnreachableError: () => UnreachableError,
9383
9872
  VERIFIER_REWARD_PREFIX: () => VERIFIER_REWARD_PREFIX,
9384
9873
  WHITESPACE: () => WHITESPACE,
9874
+ WORLD_REQUEST_VIAS: () => WORLD_REQUEST_VIAS,
9385
9875
  WorldBrowser: () => WorldBrowser,
9386
9876
  WorldCallTooLarge: () => WorldCallTooLarge,
9387
9877
  WorldEditClient: () => WorldEditClient,
9388
9878
  WorldNotice: () => WorldNotice,
9879
+ WorldRequestFilterError: () => WorldRequestFilterError,
9880
+ WorldRequestLedger: () => WorldRequestLedger,
9389
9881
  WorldRequestLog: () => WorldRequestLog,
9882
+ WorldRequestQuery: () => WorldRequestQuery,
9883
+ WorldRequestsNotRecorded: () => WorldRequestsNotRecorded,
9390
9884
  WorldSandboxClient: () => WorldSandboxClient,
9391
9885
  WorldSession: () => WorldSession,
9392
9886
  WorldSessionCallError: () => WorldSessionCallError,
@@ -9396,18 +9890,22 @@ __export(worlds_exports, {
9396
9890
  WorldSurfaceUnavailable: () => WorldSurfaceUnavailable,
9397
9891
  WorldTask: () => WorldTask,
9398
9892
  WorldToolsUnread: () => WorldToolsUnread,
9893
+ WriteTreeFilter: () => WriteTreeFilter,
9399
9894
  aggregateTaskGrade: () => aggregateTaskGrade,
9400
9895
  apiRequest: () => apiRequest,
9401
9896
  applyTransforms: () => applyTransforms,
9402
9897
  archiveMode: () => archiveMode,
9403
9898
  assertBrowserTier: () => assertBrowserTier,
9899
+ assertSessionAuthMode: () => assertSessionAuthMode,
9404
9900
  assertTaskRef: () => assertTaskRef,
9405
9901
  attachManifest: () => attachManifest,
9406
9902
  attachSession: () => attachSession,
9407
9903
  attachTask: () => attachTask,
9408
9904
  buildFileManifest: () => buildFileManifest,
9409
9905
  buildSourceTarball: () => buildSourceTarball,
9906
+ capabilityLabel: () => capabilityLabel,
9410
9907
  captureToolCalls: () => captureToolCalls,
9908
+ carriedWarnings: () => carriedWarnings,
9411
9909
  checkoutIdentity: () => checkoutIdentity,
9412
9910
  closeConnection: () => closeConnection,
9413
9911
  collectArchiveRelPaths: () => collectArchiveRelPaths,
@@ -9426,7 +9924,9 @@ __export(worlds_exports, {
9426
9924
  idleWarning: () => idleWarning,
9427
9925
  ingest: () => ingest,
9428
9926
  ingestToolCalls: () => ingestToolCalls,
9927
+ invalidFields: () => invalidFields,
9429
9928
  isBrowserGone: () => isBrowserGone,
9929
+ isSandboxCommitPending: () => isSandboxCommitPending,
9430
9930
  isSandboxImportPending: () => isSandboxImportPending,
9431
9931
  isTaskIdRef: () => isTaskIdRef,
9432
9932
  isTaskManifest: () => isTaskManifest,
@@ -9473,6 +9973,7 @@ __export(worlds_exports, {
9473
9973
  resolveBrowserMode: () => resolveBrowserMode,
9474
9974
  resolvePushSlug: () => resolvePushSlug,
9475
9975
  roundForm: () => roundForm,
9976
+ rowsRefusal: () => rowsRefusal,
9476
9977
  runSessions: () => runSessions,
9477
9978
  runSet: () => runSet,
9478
9979
  runTask: () => runTask,
@@ -9501,27 +10002,42 @@ __export(worlds_exports, {
9501
10002
  validateWorld: () => validateWorld,
9502
10003
  waitForRun: () => waitForRun,
9503
10004
  withoutUiToken: () => withoutUiToken,
10005
+ worldRequestsUnrecorded: () => worldRequestsUnrecorded,
9504
10006
  writeLocalMeta: () => writeLocalMeta
9505
10007
  });
9506
- function parseErrorBody(text2, limit = 600) {
9507
- const raw = { detail: text2.slice(0, limit), code: null };
10008
+ function edgeAnswer(text2, status) {
10009
+ if (status !== void 0 && status >= 500) return EDGE_ANSWERS[status] ?? EDGE_FAILURE;
10010
+ return /^\s*</.test(text2) ? EDGE_PAGE : null;
10011
+ }
10012
+ function parseErrorBody(text2, status) {
10013
+ const raw = { detail: text2.slice(0, DETAIL_LIMIT), code: null };
9508
10014
  let parsed;
9509
10015
  try {
9510
10016
  parsed = JSON.parse(text2);
9511
10017
  } catch {
9512
- return raw;
10018
+ return { detail: (edgeAnswer(text2, status) ?? text2).slice(0, DETAIL_LIMIT), code: null };
9513
10019
  }
9514
10020
  if (parsed === null || typeof parsed !== "object") return raw;
9515
- const { message, code } = parsed;
10021
+ const { message, code, error } = parsed;
9516
10022
  const stableCode = typeof code === "string" ? code : null;
9517
10023
  if (typeof message !== "string") return { ...raw, code: stableCode };
9518
- if (stableCode === null)
9519
- return { detail: message.slice(0, limit), code: null };
10024
+ const fields = invalidFields(error);
10025
+ const said = fields ? `${message}: ${fields}` : message;
10026
+ if (stableCode === null) return { detail: said.slice(0, DETAIL_LIMIT), code: null };
9520
10027
  return {
9521
- detail: `${message} (${stableCode})`.slice(0, limit),
10028
+ detail: `${said} (${stableCode})`.slice(0, DETAIL_LIMIT),
9522
10029
  code: stableCode
9523
10030
  };
9524
10031
  }
10032
+ function invalidFields(error) {
10033
+ const issues = Array.isArray(error) ? error : [];
10034
+ return issues.filter(
10035
+ (issue) => issue !== null && typeof issue === "object" && typeof issue.message === "string"
10036
+ ).map((issue) => {
10037
+ const path17 = Array.isArray(issue.path) ? issue.path.map(String).join(".") : "";
10038
+ return path17 ? `${path17}: ${issue.message}` : issue.message;
10039
+ }).join("; ");
10040
+ }
9525
10041
  async function apiRequest(options, method, path17, body, init3 = {}) {
9526
10042
  const reply = await new PlatformTransport(requirePlatformEndpoint(options)).send(method, path17, body, init3);
9527
10043
  if (!reply.ok) throw new ApiError(reply.status, method, path17, reply.text);
@@ -9700,7 +10216,7 @@ async function resolveWorld(slugRef, slug, ref, pin, options) {
9700
10216
  }
9701
10217
  return world;
9702
10218
  }
9703
- var ApiError, WorldTask, WorldSet;
10219
+ var ApiError, DETAIL_LIMIT, EDGE_ANSWERS, EDGE_FAILURE, EDGE_PAGE, WorldTask, WorldSet;
9704
10220
  var init_worlds = __esm({
9705
10221
  "src/worlds/index.ts"() {
9706
10222
  "use strict";
@@ -9713,6 +10229,7 @@ var init_worlds = __esm({
9713
10229
  init_sessionContract();
9714
10230
  init_taskRef();
9715
10231
  init_tasks();
10232
+ init_taskGrades();
9716
10233
  init_taskSessions();
9717
10234
  init_taskRun();
9718
10235
  init_setRun();
@@ -9721,6 +10238,7 @@ var init_worlds = __esm({
9721
10238
  init_browser();
9722
10239
  init_surfaceDescriptor();
9723
10240
  init_requestLog();
10241
+ init_requestLedger();
9724
10242
  init_browserReconnect();
9725
10243
  init_nativeComputer();
9726
10244
  init_hub();
@@ -9737,7 +10255,7 @@ var init_worlds = __esm({
9737
10255
  init_worldNotice();
9738
10256
  ApiError = class extends Error {
9739
10257
  constructor(status, method, path17, text2) {
9740
- const parsed = parseErrorBody(text2);
10258
+ const parsed = parseErrorBody(text2, status);
9741
10259
  super(`${method} ${path17} -> ${status}: ${parsed.detail}`);
9742
10260
  this.status = status;
9743
10261
  this.text = text2;
@@ -9748,6 +10266,14 @@ var init_worlds = __esm({
9748
10266
  text;
9749
10267
  code;
9750
10268
  };
10269
+ DETAIL_LIMIT = 600;
10270
+ EDGE_ANSWERS = {
10271
+ 502: "Bad Gateway from the load balancer in front of the platform, not the platform's answer: the web server dropped the connection or restarted mid-request. Retry; if it repeats, the platform is restarting or overloaded.",
10272
+ 503: "Service Unavailable from the load balancer in front of the platform, not the platform's answer: no web server was ready to take the request (a deploy or a restart). Retry in a minute.",
10273
+ 504: "Gateway Time-out from the load balancer in front of the platform, not the platform's answer: the request sent nothing back within the load balancer's idle timeout (60 s unless the deployment raises it: Helm ingress.idleTimeoutSeconds) and was cut there, though the platform may still be running it. Check what it changed before you retry."
10274
+ };
10275
+ EDGE_FAILURE = "The platform failed without its JSON error body: a proxy in front of it answered, or the server stopped before its error handler ran. Retry; if it repeats, report the request and the time.";
10276
+ EDGE_PAGE = "An HTML page answered instead of the platform's JSON: a proxy in front of the platform, or the configured host is not the platform.";
9751
10277
  WorldTask = class {
9752
10278
  constructor(world, name, variant) {
9753
10279
  this.world = world;
@@ -9783,12 +10309,7 @@ var init_worlds = __esm({
9783
10309
  }
9784
10310
  return hit;
9785
10311
  }
9786
- /**
9787
- * Open a LIVE session against one of this world's tasks — a bundled task's
9788
- * name or an inline `WorldTaskSpec`: the platform boots (or reuses) a warm
9789
- * container, and your agent calls its tools through the platform. See
9790
- * worlds/session.ts.
9791
- */
10312
+ /** Open a live session on a bundled task's name or an inline `WorldTaskSpec`; the platform boots or reuses a warm container. */
9792
10313
  async open(task, opts = {}) {
9793
10314
  const { openSession: openSession2 } = await Promise.resolve().then(() => (init_session2(), session_exports2));
9794
10315
  return openSession2(this.slug, {
@@ -9800,11 +10321,7 @@ var init_worlds = __esm({
9800
10321
  options: this.options
9801
10322
  });
9802
10323
  }
9803
- /**
9804
- * Start a HOSTED run of a run config against this world — the platform
9805
- * executes the (Python) world in parallel containers per the config's
9806
- * `parallelism` and files one graded run per model. Returns those runs.
9807
- */
10324
+ /** Start a hosted run of a run config on this version (or `opts.versionId`): one graded run per model, provenance detected unless given. */
9808
10325
  async dispatch(runConfigId, opts = {}) {
9809
10326
  const provenance = opts.provenance ?? detectProvenance();
9810
10327
  return apiRequest(
@@ -12242,7 +12759,7 @@ __export(files_exports, {
12242
12759
  uploadFile: () => uploadFile
12243
12760
  });
12244
12761
  init_worlds();
12245
- import { createHash as createHash10 } from "crypto";
12762
+ import { createHash as createHash11 } from "crypto";
12246
12763
  import * as fs13 from "fs";
12247
12764
  import * as path13 from "path";
12248
12765
  import { Readable, Transform } from "stream";
@@ -12307,7 +12824,7 @@ async function confirmUpload(options = {}, fileId, ok = true) {
12307
12824
  return apiRequest(options, "POST", `${BASE}/confirm`, { fileId, ok });
12308
12825
  }
12309
12826
  async function sha256Base64(localPath) {
12310
- const hash = createHash10("sha256");
12827
+ const hash = createHash11("sha256");
12311
12828
  for await (const chunk of fs13.createReadStream(localPath)) hash.update(chunk);
12312
12829
  return hash.digest("base64");
12313
12830
  }
@@ -12392,7 +12909,7 @@ async function uploadBytes(options = {}, bytes, targetPath, upload = {}) {
12392
12909
  if (!bytes.length) throw new Error("nothing to upload: the content is empty");
12393
12910
  const target = drivePath(targetPath);
12394
12911
  const contentType = upload.contentType ?? contentTypeFor(target);
12395
- const sha2562 = createHash10("sha256").update(bytes).digest("base64");
12912
+ const sha2562 = createHash11("sha256").update(bytes).digest("base64");
12396
12913
  const granted = await requestUpload(options, { path: target, contentLength: bytes.length, contentType, sha256: sha2562, ...upload.overwrite ? { overwrite: true } : {} });
12397
12914
  try {
12398
12915
  await putPresigned(granted.uploadUrl, new Uint8Array(bytes), { contentType, contentLength: bytes.length, sha256: sha2562 });
@@ -12645,10 +13162,10 @@ function swapValue(text2, needle, replacement) {
12645
13162
  }
12646
13163
 
12647
13164
  // src/hooks/standInDigits.ts
12648
- import { createHash as createHash11 } from "crypto";
13165
+ import { createHash as createHash12 } from "crypto";
12649
13166
  function standInDigits(realDigits, identityName) {
12650
13167
  if (!realDigits) return "";
12651
- const digest = createHash11("sha256").update(`${identityName}:${realDigits}`).digest("hex");
13168
+ const digest = createHash12("sha256").update(`${identityName}:${realDigits}`).digest("hex");
12652
13169
  let digits = "";
12653
13170
  for (let i = 0; i < realDigits.length; i++)
12654
13171
  digits += String(parseInt(digest[i % digest.length], 16) % 10);
@@ -12682,7 +13199,7 @@ var DeclaredStandIn = class _DeclaredStandIn {
12682
13199
  };
12683
13200
 
12684
13201
  // src/hooks/alias.ts
12685
- import { createHash as createHash12, createHmac, randomBytes as randomBytes2 } from "crypto";
13202
+ import { createHash as createHash13, createHmac, randomBytes as randomBytes2 } from "crypto";
12686
13203
  var GIVEN = [
12687
13204
  "John",
12688
13205
  "Mary",
@@ -13503,9 +14020,9 @@ var AliasMap = class _AliasMap {
13503
14020
  });
13504
14021
  if (alias.role === "private") {
13505
14022
  for (const slug of this.slugs) {
13506
- const standIn = "sha256:" + createHash12("sha256").update(`${slug}:${canonical(alias.kind, alias.display)}`, "utf8").digest("hex");
14023
+ const standIn = "sha256:" + createHash13("sha256").update(`${slug}:${canonical(alias.kind, alias.display)}`, "utf8").digest("hex");
13507
14024
  alias.variants.push([
13508
- "sha256:" + createHash12("sha256").update(`${slug}:${alias.canonical}`, "utf8").digest("hex"),
14025
+ "sha256:" + createHash13("sha256").update(`${slug}:${alias.canonical}`, "utf8").digest("hex"),
13509
14026
  standIn
13510
14027
  ]);
13511
14028
  this.aliasDigests.add(standIn.toLowerCase());
@@ -15522,6 +16039,120 @@ async function buildHandler(spec, aliases, opts) {
15522
16039
  // src/hooks/live.ts
15523
16040
  import * as fs16 from "fs";
15524
16041
  import * as path15 from "path";
16042
+
16043
+ // src/hooks/vendorAuth.ts
16044
+ var bearer = (auth, value) => ({
16045
+ headers: { authorization: `${prefixesOf(auth)[0]} ${value}` },
16046
+ query: []
16047
+ });
16048
+ var CARRIERS = /* @__PURE__ */ new Map([
16049
+ [
16050
+ "header",
16051
+ (auth, value) => ({
16052
+ headers: {
16053
+ [String(auth.name ?? "").trim().toLowerCase()]: value
16054
+ },
16055
+ query: []
16056
+ })
16057
+ ],
16058
+ ["bearer", bearer],
16059
+ [
16060
+ "basic",
16061
+ (auth, value) => ({
16062
+ headers: {
16063
+ authorization: `Basic ${Buffer.from(basicPair(auth, value)).toString("base64")}`
16064
+ },
16065
+ query: []
16066
+ })
16067
+ ],
16068
+ [
16069
+ "query",
16070
+ (auth, value) => ({
16071
+ headers: {},
16072
+ query: [[String(auth.name ?? "").trim(), value]]
16073
+ })
16074
+ ],
16075
+ ["oauth2", bearer],
16076
+ ["none", () => ({ headers: {}, query: [] })]
16077
+ ]);
16078
+ var AUTH_WORD = /^[A-Za-z0-9!#$%&'*+.^_`|~-]{1,64}$/;
16079
+ var OWNERS = [
16080
+ ["client_id_env", ["oauth2"]],
16081
+ ["credential", ["basic"]],
16082
+ ["prefixes", ["bearer", "oauth2"]],
16083
+ ["scope", ["oauth2"]],
16084
+ ["token_url", ["oauth2"]],
16085
+ ["ttl_seconds", ["oauth2"]]
16086
+ ];
16087
+ var AUTH_MODES = ["vendor", "open"];
16088
+ var positiveSeconds = (value) => typeof value === "number" && Number.isInteger(value) && value >= 1;
16089
+ var NAMED = /* @__PURE__ */ new Set(["header", "query"]);
16090
+ function prefixesOf(auth) {
16091
+ const words2 = auth.prefixes ?? ["Bearer"];
16092
+ const valid = Array.isArray(words2) && words2.length > 0 && words2.every((word) => typeof word === "string" && AUTH_WORD.test(word)) && new Set(words2.map((word) => word.toLowerCase())).size === words2.length;
16093
+ if (!valid)
16094
+ throw new Error(
16095
+ "auth.prefixes lists the distinct words the vendor takes before the key in Authorization"
16096
+ );
16097
+ return words2;
16098
+ }
16099
+ function basicHalf(auth) {
16100
+ const half = auth.credential ?? "user";
16101
+ if (half !== "user" && half !== "password")
16102
+ throw new Error(
16103
+ "auth.credential is the half of the Basic pair the key is: user or password"
16104
+ );
16105
+ return half;
16106
+ }
16107
+ function basicPair(auth, value) {
16108
+ if (value.includes(":")) return value;
16109
+ return basicHalf(auth) === "password" ? `:${value}` : `${value}:`;
16110
+ }
16111
+ var GRAMMAR = /* @__PURE__ */ new Map([
16112
+ ["bearer", prefixesOf],
16113
+ ["oauth2", prefixesOf],
16114
+ ["basic", basicHalf]
16115
+ ]);
16116
+ function authScheme(value) {
16117
+ if (value === void 0) throw new Error("Missing scheme");
16118
+ if (value === "open")
16119
+ throw new Error(
16120
+ 'auth.scheme is how the vendor takes its key; a world whose sessions ask for none is auth.mode = "open"'
16121
+ );
16122
+ if (typeof value !== "string" || !CARRIERS.has(value))
16123
+ throw new Error(
16124
+ `auth.scheme must be one of ${[...CARRIERS.keys()].join(", ")}`
16125
+ );
16126
+ return value;
16127
+ }
16128
+ function vendorAuth(auth) {
16129
+ const scheme = authScheme(auth.scheme);
16130
+ const stray = OWNERS.find(
16131
+ ([key2, owners]) => auth[key2] !== void 0 && !owners.includes(scheme)
16132
+ );
16133
+ if (stray)
16134
+ throw new Error(
16135
+ `${stray[0]} belongs to auth.scheme ${stray[1].join(" or ")}`
16136
+ );
16137
+ if (scheme === "none" && (auth.name ?? auth.secret_env) !== void 0)
16138
+ throw new Error("auth.scheme none takes no name or secret_env");
16139
+ if (NAMED.has(scheme) && auth.name === void 0)
16140
+ throw new Error("Missing name");
16141
+ if (auth.name !== void 0 && (typeof auth.name !== "string" || !auth.name.trim()))
16142
+ throw new Error("name must be a non-empty string");
16143
+ GRAMMAR.get(scheme)?.(auth);
16144
+ if (auth.mode !== void 0 && !AUTH_MODES.includes(auth.mode))
16145
+ throw new Error(`auth.mode is one of ${AUTH_MODES.join(", ")}`);
16146
+ if (auth.ttl_seconds !== void 0 && !positiveSeconds(auth.ttl_seconds))
16147
+ throw new Error("ttl_seconds is a positive whole number of seconds");
16148
+ return { ...auth, scheme };
16149
+ }
16150
+ function carryCredential(auth, value) {
16151
+ const checked = vendorAuth(auth);
16152
+ return CARRIERS.get(checked.scheme)(checked, value);
16153
+ }
16154
+
16155
+ // src/hooks/live.ts
15525
16156
  var USER_AGENT = "gateway-hooks/1 (+https://withgateway.ai)";
15526
16157
  var TAGS = /<(script|style)[^>]*>.*?<\/\1>/gis;
15527
16158
  var STRIP = /<[^>]+>/g;
@@ -15842,7 +16473,9 @@ var HttpTool = class _HttpTool {
15842
16473
  const okStatus = o.ok_status ?? [
15843
16474
  [200, 200]
15844
16475
  ];
15845
- if (!okStatus.some(([low, high]) => response.status >= low && response.status <= high)) {
16476
+ if (!okStatus.some(
16477
+ ([low, high]) => response.status >= low && response.status <= high
16478
+ )) {
15846
16479
  const expected = okStatus.map(([low, high]) => low === high ? String(low) : `${low}-${high}`).join(", ");
15847
16480
  throw new LiveToolError(
15848
16481
  `${this.spec.name}: ${url} answered HTTP ${response.status} (ok_status ${expected}): ${JSON.stringify(body.slice(0, 200))}`,
@@ -15893,7 +16526,8 @@ function readConnection(root) {
15893
16526
  if (!fs16.existsSync(file)) throw new Error(`no connector.toml at ${root}`);
15894
16527
  const raw = parseToml(fs16.readFileSync(file, "utf8"));
15895
16528
  const connector = raw.connector ?? {};
15896
- const auth = raw.auth ?? {};
16529
+ const auth = raw.auth ?? { scheme: "none" };
16530
+ const carrier = vendorAuth(auth);
15897
16531
  const operations = {};
15898
16532
  for (const op of raw.operations ?? []) {
15899
16533
  operations[op.name] = {
@@ -15907,8 +16541,8 @@ function readConnection(root) {
15907
16541
  return {
15908
16542
  slug: connector.slug ?? path15.basename(root),
15909
16543
  baseUrl: (connector.base_url ?? "").replace(/\/+$/, ""),
15910
- scheme: auth.scheme ?? "none",
15911
- ...typeof auth.name === "string" ? { authName: auth.name } : {},
16544
+ scheme: carrier.scheme,
16545
+ carrier,
15912
16546
  ...typeof auth.secret_env === "string" ? { secretEnv: auth.secret_env } : {},
15913
16547
  ...typeof auth.client_id_env === "string" ? { clientIdEnv: auth.client_id_env } : {},
15914
16548
  ...typeof auth.token_url === "string" ? { tokenUrl: auth.token_url } : {},
@@ -16020,13 +16654,9 @@ var ConnectorTool = class {
16020
16654
  };
16021
16655
  for (const [header, variable] of Object.entries(c.extraHeaders))
16022
16656
  headers[header] = this.env(variable, `the ${header} header`);
16023
- const secret = await this.credential();
16024
- if (c.scheme === "header") headers[c.authName ?? ""] = secret ?? "";
16025
- else if (c.scheme === "bearer" || c.scheme === "oauth2")
16026
- headers.authorization = `Bearer ${secret}`;
16027
- else if (c.scheme === "basic")
16028
- headers.authorization = "Basic " + Buffer.from(secret ?? "").toString("base64");
16029
- else if (c.scheme === "query") query.append(c.authName ?? "", secret ?? "");
16657
+ const carried2 = carryCredential(c.carrier, await this.credential() ?? "");
16658
+ Object.assign(headers, carried2.headers);
16659
+ for (const [key2, value] of carried2.query) query.append(key2, value);
16030
16660
  const url = c.baseUrl + pathText + (query.toString() ? `?${query.toString()}` : "");
16031
16661
  const response = await fetch(url, {
16032
16662
  method: this.operation.method,
@@ -17556,6 +18186,7 @@ export {
17556
18186
  NativeComputer,
17557
18187
  OpenAIComputer,
17558
18188
  OpenAIPreviewComputer,
18189
+ PLATFORM_SESSION_HEADER,
17559
18190
  PLATFORM_TIMEOUT_DEFAULT_MS,
17560
18191
  PLATFORM_TIMEOUT_ENV,
17561
18192
  PendingSafetyChecks,
@@ -17566,6 +18197,9 @@ export {
17566
18197
  PushSlugConflict,
17567
18198
  RECOVER_BUDGET_MS,
17568
18199
  REPLAY_ENVIRONMENT,
18200
+ REQUESTS_NOT_RECORDED,
18201
+ REQUEST_BODY_CAPTURE_BYTES,
18202
+ REQUEST_LOG_PAGE_MAX,
17569
18203
  ReplayCase,
17570
18204
  ReplayCheck,
17571
18205
  ReplayError,
@@ -17573,8 +18207,16 @@ export {
17573
18207
  ReplaySuite,
17574
18208
  ReplayTask,
17575
18209
  RetryPolicy,
18210
+ SANDBOX_EXEC_REPORT_MARGIN_MS,
18211
+ SANDBOX_EXEC_START_ATTEMPTS,
18212
+ SANDBOX_EXEC_TIMEOUT_MAX_S,
18213
+ SANDBOX_EXEC_WAIT_MS,
18214
+ SANDBOX_FILE_MAX_BYTES,
17576
18215
  SANDBOX_REQUEST_TIMEOUT_MS,
18216
+ SANDBOX_WRITE_CHUNK_BYTES,
18217
+ SANDBOX_WRITE_SKIPPED,
17577
18218
  SECRET_KEY,
18219
+ SESSION_AUTH_MODES,
17578
18220
  SESSION_STATES,
17579
18221
  SPAN_PREFIX,
17580
18222
  STATUS_WAIT_CAP_SECONDS,
@@ -17594,6 +18236,7 @@ export {
17594
18236
  TOOL_CONTRACT_UNREAD,
17595
18237
  TRANSFORMS,
17596
18238
  TaskEditClient,
18239
+ TaskGrades,
17597
18240
  TaskRun,
17598
18241
  TaskSessions,
17599
18242
  ToolStubRegistry,
@@ -17604,11 +18247,16 @@ export {
17604
18247
  UsersClient,
17605
18248
  VERIFIER_REWARD_PREFIX,
17606
18249
  WHITESPACE,
18250
+ WORLD_REQUEST_VIAS,
17607
18251
  WorldBrowser,
17608
18252
  WorldCallTooLarge,
17609
18253
  WorldEditClient,
17610
18254
  WorldNotice,
18255
+ WorldRequestFilterError,
18256
+ WorldRequestLedger,
17611
18257
  WorldRequestLog,
18258
+ WorldRequestQuery,
18259
+ WorldRequestsNotRecorded,
17612
18260
  WorldSandboxClient,
17613
18261
  WorldSession,
17614
18262
  WorldSessionCallError,
@@ -17618,6 +18266,7 @@ export {
17618
18266
  WorldSurfaceUnavailable,
17619
18267
  WorldTask,
17620
18268
  WorldToolsUnread,
18269
+ WriteTreeFilter,
17621
18270
  addExperimentAttributes,
17622
18271
  aggregateTaskGrade,
17623
18272
  apiRequest,
@@ -17625,6 +18274,7 @@ export {
17625
18274
  archiveMode,
17626
18275
  assembleManifest,
17627
18276
  assertBrowserTier,
18277
+ assertSessionAuthMode,
17628
18278
  assertTaskRef,
17629
18279
  assignVariant,
17630
18280
  attachManifest,
@@ -17634,7 +18284,9 @@ export {
17634
18284
  buildFileManifest,
17635
18285
  buildSourceTarball,
17636
18286
  canonicalJson,
18287
+ capabilityLabel,
17637
18288
  captureToolCalls,
18289
+ carriedWarnings,
17638
18290
  checkoutIdentity,
17639
18291
  clearExperimentContext,
17640
18292
  closeConnection,
@@ -17670,7 +18322,9 @@ export {
17670
18322
  idleWarning,
17671
18323
  ingest,
17672
18324
  ingestToolCalls,
18325
+ invalidFields,
17673
18326
  isBrowserGone,
18327
+ isSandboxCommitPending,
17674
18328
  isSandboxImportPending,
17675
18329
  isTaskIdRef,
17676
18330
  isTaskManifest,
@@ -17727,6 +18381,7 @@ export {
17727
18381
  resolvePushSlug,
17728
18382
  resolveUserId,
17729
18383
  roundForm,
18384
+ rowsRefusal,
17730
18385
  runSessions,
17731
18386
  runSet,
17732
18387
  runSuite,
@@ -17766,6 +18421,7 @@ export {
17766
18421
  validateWorld,
17767
18422
  waitForRun,
17768
18423
  withoutUiToken,
18424
+ worldRequestsUnrecorded,
17769
18425
  writeLocalMeta
17770
18426
  };
17771
18427
  //# sourceMappingURL=index.mjs.map