@withgateway/sdk 0.3.3 → 0.6.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 (158) hide show
  1. package/README.md +4 -3
  2. package/dist/cli.js +3005 -1401
  3. package/dist/cli.js.map +1 -1
  4. package/dist/cli.mjs +2996 -1392
  5. package/dist/cli.mjs.map +1 -1
  6. package/dist/files/index.js +128 -37
  7. package/dist/files/index.js.map +1 -1
  8. package/dist/files/index.mjs +126 -35
  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-mJhG3vZU.d.mts → index-Di9nNqOY.d.mts} +26 -3
  19. package/dist/{index-DUHmS74p.d.ts → index-LA-PMRJT.d.ts} +26 -3
  20. package/dist/index.d.mts +4 -4
  21. package/dist/index.d.ts +4 -4
  22. package/dist/index.js +1078 -260
  23. package/dist/index.js.map +1 -1
  24. package/dist/index.mjs +1040 -251
  25. package/dist/index.mjs.map +1 -1
  26. package/dist/replay/index.d.mts +1 -1
  27. package/dist/replay/index.d.ts +1 -1
  28. package/dist/replay/index.js.map +1 -1
  29. package/dist/replay/index.mjs.map +1 -1
  30. package/dist/traces/index.js +125 -34
  31. package/dist/traces/index.js.map +1 -1
  32. package/dist/traces/index.mjs +123 -32
  33. package/dist/traces/index.mjs.map +1 -1
  34. package/dist/tracing/index.d.mts +1 -1
  35. package/dist/tracing/index.d.ts +1 -1
  36. package/dist/tracing/index.js +7 -1
  37. package/dist/tracing/index.js.map +1 -1
  38. package/dist/tracing/index.mjs +7 -1
  39. package/dist/tracing/index.mjs.map +1 -1
  40. package/dist/worlds/index.d.mts +819 -438
  41. package/dist/worlds/index.d.ts +819 -438
  42. package/dist/worlds/index.js +912 -236
  43. package/dist/worlds/index.js.map +1 -1
  44. package/dist/worlds/index.mjs +908 -232
  45. package/dist/worlds/index.mjs.map +1 -1
  46. package/package.json +1 -1
  47. package/runtime/gatewaysdk/environment/_bundle.py +4 -6
  48. package/runtime/gatewaysdk/environment/_materialize.py +5 -25
  49. package/runtime/gatewaysdk/environment/_world.py +82 -66
  50. package/runtime/gatewaysdk/environment/backing.py +20 -24
  51. package/runtime/gatewaysdk/environment/core.py +1 -16
  52. package/runtime/gatewaysdk/environment/legacy_sqlite.py +14 -27
  53. package/runtime/gatewaysdk/environment/runtime.py +45 -2
  54. package/runtime/gatewaysdk/environment/schema/admission.py +174 -0
  55. package/runtime/gatewaysdk/environment/schema/api.py +198 -474
  56. package/runtime/gatewaysdk/environment/schema/assertions.py +458 -0
  57. package/runtime/gatewaysdk/environment/schema/batch.py +3 -3
  58. package/runtime/gatewaysdk/environment/schema/bundle_runtime.py +1 -0
  59. package/runtime/gatewaysdk/environment/schema/cache_layout.py +5 -0
  60. package/runtime/gatewaysdk/environment/schema/call_capture.py +321 -0
  61. package/runtime/gatewaysdk/environment/schema/call_log.py +276 -18
  62. package/runtime/gatewaysdk/environment/schema/call_redaction.py +207 -19
  63. package/runtime/gatewaysdk/environment/schema/cast.py +15 -35
  64. package/runtime/gatewaysdk/environment/schema/compiler.py +4 -1
  65. package/runtime/gatewaysdk/environment/schema/conform.py +38 -35
  66. package/runtime/gatewaysdk/environment/schema/connector.py +94 -152
  67. package/runtime/gatewaysdk/environment/schema/connectors/confluence/connector.toml +1 -12
  68. package/runtime/gatewaysdk/environment/schema/connectors/custom/handlers.py +2 -1
  69. package/runtime/gatewaysdk/environment/schema/connectors/github/api/handlers.py +217 -58
  70. package/runtime/gatewaysdk/environment/schema/connectors/github/connector.toml +10 -19
  71. package/runtime/gatewaysdk/environment/schema/connectors/github/scenarios/default/seed/github_webhooks.json +10 -2
  72. package/runtime/gatewaysdk/environment/schema/connectors/github/tests/webhooks.json +47 -0
  73. package/runtime/gatewaysdk/environment/schema/connectors/github/world.json +21 -0
  74. package/runtime/gatewaysdk/environment/schema/connectors/jamf/api/handlers.py +185 -18
  75. package/runtime/gatewaysdk/environment/schema/connectors/jamf/connector.toml +29 -14
  76. package/runtime/gatewaysdk/environment/schema/connectors/jamf/provenance.json +43 -12
  77. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scenarios/default/seed/jamf_webhooks.json +2 -2
  78. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scope.toml +4 -17
  79. package/runtime/gatewaysdk/environment/schema/connectors/jamf/tests/webhooks.json +107 -0
  80. package/runtime/gatewaysdk/environment/schema/connectors/jamf/vendor-openapi.json +1 -1
  81. package/runtime/gatewaysdk/environment/schema/connectors/linear/api/handlers.py +85 -1
  82. package/runtime/gatewaysdk/environment/schema/connectors/linear/connector.toml +19 -31
  83. package/runtime/gatewaysdk/environment/schema/connectors/linear/provenance.json +18 -8
  84. package/runtime/gatewaysdk/environment/schema/connectors/linear/scenarios/default/seed/webhooks.json +19 -3
  85. package/runtime/gatewaysdk/environment/schema/connectors/linear/tests/test_webhooks.py +71 -0
  86. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/connector.toml +2 -5
  87. package/runtime/gatewaysdk/environment/schema/cors.py +54 -0
  88. package/runtime/gatewaysdk/environment/schema/credentials.py +313 -8
  89. package/runtime/gatewaysdk/environment/schema/data.py +14 -13
  90. package/runtime/gatewaysdk/environment/schema/database/base.py +106 -165
  91. package/runtime/gatewaysdk/environment/schema/database/guard.py +45 -37
  92. package/runtime/gatewaysdk/environment/schema/database/reads.py +169 -0
  93. package/runtime/gatewaysdk/environment/schema/database/sqlite.py +57 -31
  94. package/runtime/gatewaysdk/environment/schema/declared_routes.py +210 -0
  95. package/runtime/gatewaysdk/environment/schema/door.py +899 -0
  96. package/runtime/gatewaysdk/environment/schema/envelope.py +86 -28
  97. package/runtime/gatewaysdk/environment/schema/grading.py +58 -86
  98. package/runtime/gatewaysdk/environment/schema/handler_errors.py +52 -5
  99. package/runtime/gatewaysdk/environment/schema/host.py +229 -1695
  100. package/runtime/gatewaysdk/environment/schema/host_control.py +144 -0
  101. package/runtime/gatewaysdk/environment/schema/host_handoff.py +370 -0
  102. package/runtime/gatewaysdk/environment/schema/host_loops.py +97 -0
  103. package/runtime/gatewaysdk/environment/schema/host_owners.py +121 -0
  104. package/runtime/gatewaysdk/environment/schema/host_proxy.py +111 -0
  105. package/runtime/gatewaysdk/environment/schema/host_requests.py +6 -0
  106. package/runtime/gatewaysdk/environment/schema/host_session.py +126 -0
  107. package/runtime/gatewaysdk/environment/schema/host_surfaces.py +79 -21
  108. package/runtime/gatewaysdk/environment/schema/host_transfers.py +127 -0
  109. package/runtime/gatewaysdk/environment/schema/host_versions.py +242 -0
  110. package/runtime/gatewaysdk/environment/schema/host_workers.py +577 -0
  111. package/runtime/gatewaysdk/environment/schema/journal.py +438 -0
  112. package/runtime/gatewaysdk/environment/schema/ledger_spill.py +828 -0
  113. package/runtime/gatewaysdk/environment/schema/local.py +32 -116
  114. package/runtime/gatewaysdk/environment/schema/openapi_schemas.py +20 -5
  115. package/runtime/gatewaysdk/environment/schema/platform.py +29 -234
  116. package/runtime/gatewaysdk/environment/schema/request_body.py +238 -0
  117. package/runtime/gatewaysdk/environment/schema/request_ledger.py +958 -0
  118. package/runtime/gatewaysdk/environment/schema/route_bindings.py +25 -3
  119. package/runtime/gatewaysdk/environment/schema/route_miss.py +54 -0
  120. package/runtime/gatewaysdk/environment/schema/runtime.py +136 -176
  121. package/runtime/gatewaysdk/environment/schema/scaffold.py +2 -1
  122. package/runtime/gatewaysdk/environment/schema/session_files.py +133 -24
  123. package/runtime/gatewaysdk/environment/schema/session_move.py +275 -0
  124. package/runtime/gatewaysdk/environment/schema/skills/agents/connector-template-author.md +5 -1
  125. package/runtime/gatewaysdk/environment/schema/skills/benchmarks-getting-started/SKILL.md +8 -9
  126. package/runtime/gatewaysdk/environment/schema/skills/connector-schema-authoring/CONNECTORS.md +3 -3
  127. package/runtime/gatewaysdk/environment/schema/skills/connector-schema-authoring/SKILL.md +50 -28
  128. package/runtime/gatewaysdk/environment/schema/skills/world-data-ingestion/ROWS.md +12 -8
  129. package/runtime/gatewaysdk/environment/schema/skills/world-data-ingestion/SKILL.md +20 -22
  130. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/SKILL.md +25 -25
  131. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/cli-mcp-map.md +24 -16
  132. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/gotchas.md +71 -7
  133. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/journal-checks.md +182 -0
  134. package/runtime/gatewaysdk/environment/schema/snapshot.py +150 -30
  135. package/runtime/gatewaysdk/environment/schema/spill_files.py +228 -0
  136. package/runtime/gatewaysdk/environment/schema/tasks.py +229 -323
  137. package/runtime/gatewaysdk/environment/schema/tools_world.py +103 -203
  138. package/runtime/gatewaysdk/environment/schema/validation.py +69 -1
  139. package/runtime/gatewaysdk/environment/schema/verbs.py +38 -36
  140. package/runtime/gatewaysdk/environment/schema/webhooks.py +687 -0
  141. package/runtime/gatewaysdk/environment/schema/worker.py +6 -4
  142. package/runtime/gatewaysdk/environment/schema/workers.py +203 -39
  143. package/runtime/gatewaysdk/environment/schema/world_host.py +970 -0
  144. package/runtime/gatewaysdk/environment/schema/world_tests.py +83 -11
  145. package/runtime/gatewaysdk/environment/world.py +1 -1
  146. package/runtime/gatewaysdk/environment/world_session_contract.py +14 -0
  147. package/skills/agents/connector-template-author.md +5 -1
  148. package/skills/benchmarks-getting-started/SKILL.md +8 -9
  149. package/skills/connector-schema-authoring/CONNECTORS.md +3 -3
  150. package/skills/connector-schema-authoring/SKILL.md +50 -28
  151. package/skills/connector-schema-authoring/connector-worlds.md +282 -18
  152. package/skills/connector-schema-authoring/world-schema.md +7 -6
  153. package/skills/world-data-ingestion/ROWS.md +12 -8
  154. package/skills/world-data-ingestion/SKILL.md +20 -22
  155. package/skills/worlds-getting-started/SKILL.md +25 -25
  156. package/skills/worlds-getting-started/references/cli-mcp-map.md +24 -16
  157. package/skills/worlds-getting-started/references/gotchas.md +71 -7
  158. 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 },
@@ -529,11 +535,11 @@ var init_transport = __esm({
529
535
  }
530
536
  };
531
537
  UnreachableError = class extends Error {
532
- constructor(host, method, route, failure) {
533
- super(`${method} ${route}: no answer from ${host}: ${failure.describe()}. ${failure.next}`);
538
+ constructor(host, method, route2, failure) {
539
+ super(`${method} ${route2}: no answer from ${host}: ${failure.describe()}. ${failure.next}`);
534
540
  this.host = host;
535
541
  this.method = method;
536
- this.route = route;
542
+ this.route = route2;
537
543
  this.failure = failure;
538
544
  this.name = "UnreachableError";
539
545
  }
@@ -603,16 +609,16 @@ var init_transport = __esm({
603
609
  budget(ownMs) {
604
610
  return Math.max(ownMs ?? 0, this.timeoutMs);
605
611
  }
606
- async send(method, route, body, opts = {}) {
612
+ async send(method, route2, body, opts = {}) {
607
613
  const timeoutMs = this.budget(opts.timeoutMs);
608
- return (opts.retry ?? RetryPolicy.NONE).run(() => this.once(method, route, body, timeoutMs));
614
+ return (opts.retry ?? RetryPolicy.NONE).run(() => this.once(method, route2, body, timeoutMs));
609
615
  }
610
- async once(method, route, body, timeoutMs) {
616
+ async once(method, route2, body, timeoutMs) {
611
617
  const payload = body === void 0 ? {} : { body: JSON.stringify(body) };
612
618
  const controller = new AbortController();
613
619
  const timer = setTimeout(() => controller.abort(), timeoutMs);
614
620
  try {
615
- const res = await fetch(`${this.endpoint.host}${route}`, {
621
+ const res = await fetch(`${this.endpoint.host}${route2}`, {
616
622
  method,
617
623
  headers: {
618
624
  "content-type": "application/json",
@@ -625,7 +631,7 @@ var init_transport = __esm({
625
631
  return { status: res.status, ok: res.ok, text: await res.text() };
626
632
  } catch (error) {
627
633
  const cause = controller.signal.aborted ? TransportCause.timeout(timeoutMs) : TransportCause.of(error);
628
- throw new UnreachableError(this.endpoint.host, method, route, cause);
634
+ throw new UnreachableError(this.endpoint.host, method, route2, cause);
629
635
  } finally {
630
636
  clearTimeout(timer);
631
637
  }
@@ -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
@@ -1856,11 +1893,11 @@ var init_media = __esm({
1856
1893
  status
1857
1894
  );
1858
1895
  }
1859
- async send(method, route, body) {
1860
- const reply = await this.transport.send(method, route, body);
1896
+ async send(method, route2, body) {
1897
+ const reply = await this.transport.send(method, route2, body);
1861
1898
  if (!reply.ok)
1862
1899
  throw new MediaUploadError(
1863
- `${method} ${route} -> ${reply.status}`,
1900
+ `${method} ${route2} -> ${reply.status}`,
1864
1901
  reply.status
1865
1902
  );
1866
1903
  return reply.text ? JSON.parse(reply.text) : {};
@@ -2213,7 +2250,7 @@ function click(button, count) {
2213
2250
  modifiers: modifierChord(raw.text)
2214
2251
  });
2215
2252
  }
2216
- var SCROLL_STEP_PX, NOT_EXECUTED, MAX_ERROR2, SCROLL_DIRECTIONS, MEMBERS, AnthropicComputer, AnthropicComputer20251124;
2253
+ var SCROLL_STEP_PX, NOT_EXECUTED, MAX_ERROR2, SCROLL_DIRECTIONS, IMAGE_PARTS, MEMBERS, AnthropicComputer, AnthropicComputer20251124;
2217
2254
  var init_anthropic = __esm({
2218
2255
  "src/worlds/nativeComputer/anthropic.ts"() {
2219
2256
  "use strict";
@@ -2229,6 +2266,14 @@ var init_anthropic = __esm({
2229
2266
  left: [-1, 0],
2230
2267
  right: [1, 0]
2231
2268
  };
2269
+ IMAGE_PARTS = {
2270
+ 6: (data) => ({ type: "image-data", data, mediaType: "image/png" }),
2271
+ 7: (data) => ({
2272
+ type: "file",
2273
+ mediaType: "image/png",
2274
+ data: { type: "data", data }
2275
+ })
2276
+ };
2232
2277
  MEMBERS = {
2233
2278
  screenshot: () => new ComputerAction("screenshot"),
2234
2279
  zoom: (raw) => new ComputerAction("zoom", {
@@ -2338,15 +2383,17 @@ var init_anthropic = __esm({
2338
2383
  ];
2339
2384
  return [{ type: "text", text: result.text ?? "OK" }];
2340
2385
  }
2341
- /** For `anthropic.tools.computerToolset_20260801({ ...computer.aiSdk() })`
2342
- * (or `computer_20251124` with the legacy kind): `execute` runs one action
2343
- * and returns `{ type: "image", data }` or text; `toModelOutput` turns that
2344
- * into the tool result. Calls run one at a time, and once a call fails the
2386
+ /** For `anthropic.tools.computerToolset_20260801(computer.aiSdk({ version: 7 }))`
2387
+ * (AI SDK 7 only), or `computer_20251124` with the legacy kind (AI SDK 6
2388
+ * and 7): `execute` runs one action and returns `{ type: "image", data }` or
2389
+ * text; `toModelOutput` turns that into the tool result in the part shape
2390
+ * of `options.version`. Calls run one at a time, and once a call fails the
2345
2391
  * rest of that step's calls answer as not executed. */
2346
- aiSdk() {
2392
+ aiSdk(options = {}) {
2393
+ const imagePart = _AnthropicComputer.imagePart(options);
2347
2394
  let failedStep;
2348
- const execute = (input, options) => this.serial(async () => {
2349
- const step = options?.messages?.length;
2395
+ const execute = (input, options2) => this.serial(async () => {
2396
+ const step = options2?.messages?.length;
2350
2397
  if (step !== void 0 && step === failedStep)
2351
2398
  throw new Error(NOT_EXECUTED);
2352
2399
  try {
@@ -2358,7 +2405,7 @@ var init_anthropic = __esm({
2358
2405
  });
2359
2406
  return {
2360
2407
  execute,
2361
- toModelOutput: ({ output }) => _AnthropicComputer.aiSdkModelOutput(output)
2408
+ toModelOutput: ({ output }) => _AnthropicComputer.modelOutput(output, imagePart)
2362
2409
  };
2363
2410
  }
2364
2411
  static aiSdkOutput(result) {
@@ -2366,16 +2413,26 @@ var init_anthropic = __esm({
2366
2413
  return { type: "image", data: result.image.toString("base64") };
2367
2414
  return result.text ?? "OK";
2368
2415
  }
2369
- /** `image-data` is what AI SDK 6's Anthropic provider turns into an image
2370
- * block; AI SDK 7 still accepts it (and converts it to a `file` part). */
2371
- static aiSdkModelOutput(output) {
2416
+ /** A screenshot as the image part of AI SDK `options.version`:
2417
+ * `image-data` for 6 (the default), `file` with `{ type: "data", data }`
2418
+ * for 7. */
2419
+ static aiSdkModelOutput(output, options = {}) {
2420
+ return _AnthropicComputer.modelOutput(
2421
+ output,
2422
+ _AnthropicComputer.imagePart(options)
2423
+ );
2424
+ }
2425
+ static imagePart({
2426
+ version = 6
2427
+ }) {
2428
+ if (Object.hasOwn(IMAGE_PARTS, version)) return IMAGE_PARTS[version];
2429
+ throw new Error(
2430
+ `unsupported AI SDK version ${version}; choose ${Object.keys(IMAGE_PARTS).join(" or ")}`
2431
+ );
2432
+ }
2433
+ static modelOutput(output, imagePart) {
2372
2434
  if (typeof output === "string") return { type: "text", value: output };
2373
- return {
2374
- type: "content",
2375
- value: [
2376
- { type: "image-data", data: output.data, mediaType: "image/png" }
2377
- ]
2378
- };
2435
+ return { type: "content", value: [imagePart(output.data)] };
2379
2436
  }
2380
2437
  envelope(block, content, isError = false) {
2381
2438
  return {
@@ -2665,13 +2722,16 @@ function idleWarning(idleExpiresAt, now = /* @__PURE__ */ new Date()) {
2665
2722
  const minutes = Math.max(0, Math.floor(leftMs / 6e4));
2666
2723
  return `warning: session expires in ${minutes}m (idle TTL); call a tool to extend it or \`gateway worlds session pin\` to keep it`;
2667
2724
  }
2668
- var CALL_BODY_LIMIT_BYTES, CALL_BODY_LIMIT_LABEL, IDLE_WARNING_MINUTES, EXPLORATORY_TASK, EXPLORATORY_TASK_SOURCE, NO_GRADER_REASON, WorldCallTooLarge, stillStartingHint;
2725
+ 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
2726
  var init_sessionContract = __esm({
2670
2727
  "src/worlds/sessionContract.ts"() {
2671
2728
  "use strict";
2672
2729
  CALL_BODY_LIMIT_BYTES = 4 * 1024 * 1024;
2673
2730
  CALL_BODY_LIMIT_LABEL = "4mb";
2674
2731
  IDLE_WARNING_MINUTES = 5;
2732
+ REQUEST_LOG_PAGE_MAX = 200;
2733
+ REQUEST_BODY_CAPTURE_BYTES = 64 * 1024;
2734
+ REQUESTS_NOT_RECORDED = "requests_not_recorded";
2675
2735
  EXPLORATORY_TASK = Object.freeze({
2676
2736
  instruction: "exploratory session"
2677
2737
  });
@@ -2705,6 +2765,217 @@ var init_sessionContract = __esm({
2705
2765
  }
2706
2766
  });
2707
2767
 
2768
+ // src/worlds/toolSchema.ts
2769
+ function schemaFromSignature(spec) {
2770
+ if (spec.inputSchema)
2771
+ return {
2772
+ type: "function",
2773
+ function: {
2774
+ name: modelToolName(spec.name),
2775
+ description: spec.doc ?? spec.name,
2776
+ parameters: spec.inputSchema
2777
+ }
2778
+ };
2779
+ const inside = /\(([\s\S]*)\)\s*$/.exec(spec.signature.trim())?.[1] ?? "";
2780
+ const properties = {};
2781
+ const required2 = [];
2782
+ const params = [];
2783
+ let depth = 0;
2784
+ let current = "";
2785
+ for (const ch of inside) {
2786
+ if ("([{".includes(ch)) depth++;
2787
+ if (")]}".includes(ch)) depth--;
2788
+ if (ch === "," && depth === 0) {
2789
+ params.push(current);
2790
+ current = "";
2791
+ } else current += ch;
2792
+ }
2793
+ if (current.trim()) params.push(current);
2794
+ for (const raw of params) {
2795
+ const param = raw.trim();
2796
+ if (!param || param.startsWith("*") || param === "self") continue;
2797
+ const eq = param.indexOf("=");
2798
+ const name = (eq === -1 ? param : param.slice(0, eq)).split(":")[0].trim();
2799
+ if (!name) continue;
2800
+ if (eq === -1) {
2801
+ properties[name] = { type: "string" };
2802
+ required2.push(name);
2803
+ continue;
2804
+ }
2805
+ const value = param.slice(eq + 1).trim();
2806
+ if (/^-?\d+(\.\d+)?$/.test(value)) properties[name] = { type: "number" };
2807
+ else if (value === "True" || value === "False")
2808
+ properties[name] = { type: "boolean" };
2809
+ else properties[name] = { type: "string" };
2810
+ }
2811
+ return {
2812
+ type: "function",
2813
+ function: {
2814
+ name: modelToolName(spec.name),
2815
+ description: spec.doc ?? spec.name,
2816
+ parameters: { type: "object", properties, required: required2 }
2817
+ }
2818
+ };
2819
+ }
2820
+ var modelToolName;
2821
+ var init_toolSchema = __esm({
2822
+ "src/worlds/toolSchema.ts"() {
2823
+ "use strict";
2824
+ modelToolName = (name) => name.replace(/[^A-Za-z0-9_-]/g, "_").slice(0, 64) || "tool";
2825
+ }
2826
+ });
2827
+
2828
+ // src/worlds/requestLedger.ts
2829
+ function platformMessage(text2) {
2830
+ try {
2831
+ const { message } = JSON.parse(text2);
2832
+ return typeof message === "string" ? message : null;
2833
+ } catch {
2834
+ return null;
2835
+ }
2836
+ }
2837
+ var WORLD_REQUEST_VIAS, WorldRequestFilterError, NOT_RECORDED, WorldRequestsNotRecorded, STATUS, INSTANT, WORLDS, SESSIONS, Instant, WorldRequestQuery, WorldRequestLedger;
2838
+ var init_requestLedger = __esm({
2839
+ "src/worlds/requestLedger.ts"() {
2840
+ "use strict";
2841
+ init_worlds();
2842
+ init_sessionContract();
2843
+ WORLD_REQUEST_VIAS = ["api", "ui", "tool", "webhook"];
2844
+ WorldRequestFilterError = class extends Error {
2845
+ };
2846
+ NOT_RECORDED = "This session's engine records no requests; only hosted World Host sessions do.";
2847
+ WorldRequestsNotRecorded = class _WorldRequestsNotRecorded extends Error {
2848
+ static from(error) {
2849
+ if (!(error instanceof ApiError) || error.code !== REQUESTS_NOT_RECORDED) return error;
2850
+ return new _WorldRequestsNotRecorded(platformMessage(error.text) || NOT_RECORDED);
2851
+ }
2852
+ static async mapped(read) {
2853
+ try {
2854
+ return await read;
2855
+ } catch (error) {
2856
+ throw _WorldRequestsNotRecorded.from(error);
2857
+ }
2858
+ }
2859
+ };
2860
+ STATUS = /^(?:[1-5]\d\d|[1-5]xx)$/;
2861
+ INSTANT = /^(\d{4})-(\d{2})-(\d{2})(?:T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{1,3}))?)?(Z|[+-]\d{2}:\d{2})?)?$/;
2862
+ WORLDS = "/api/public/worlds";
2863
+ SESSIONS = "/api/public/world-sessions";
2864
+ Instant = class _Instant {
2865
+ static parse(flag, raw) {
2866
+ const match = INSTANT.exec(raw);
2867
+ const millis = match ? _Instant.fromParts(match) : null;
2868
+ if (millis === null)
2869
+ throw new WorldRequestFilterError(
2870
+ `--${flag} must be an ISO 8601 date or time (2026-10-05, 2026-10-05T14:30:00Z), not \`${raw}\`.`
2871
+ );
2872
+ return millis;
2873
+ }
2874
+ static fromParts(match) {
2875
+ const [year, month, day, hour, minute, second] = [1, 2, 3, 4, 5, 6].map((i) => Number(match[i] ?? 0));
2876
+ const offset = _Instant.offsetMinutes(match[8]);
2877
+ if (offset === null || year < 1 || hour > 23 || minute > 59 || second > 59) return null;
2878
+ const date = /* @__PURE__ */ new Date(0);
2879
+ date.setUTCFullYear(year, month - 1, day);
2880
+ if (date.getUTCFullYear() !== year || date.getUTCMonth() !== month - 1 || date.getUTCDate() !== day) return null;
2881
+ date.setUTCHours(hour, minute, second, Number((match[7] ?? "").padEnd(3, "0")));
2882
+ const utc = date.getTime() - offset * 6e4;
2883
+ const utcYear = new Date(utc).getUTCFullYear();
2884
+ return utcYear < 1 || utcYear > 9999 ? null : utc;
2885
+ }
2886
+ static offsetMinutes(zone) {
2887
+ if (zone === void 0 || zone === "Z") return 0;
2888
+ const hours = Number(zone.slice(1, 3));
2889
+ const minutes = Number(zone.slice(4, 6));
2890
+ if (hours > 23 || minutes > 59) return null;
2891
+ return (zone.startsWith("-") ? -1 : 1) * (hours * 60 + minutes);
2892
+ }
2893
+ };
2894
+ WorldRequestQuery = class _WorldRequestQuery {
2895
+ constructor(entries) {
2896
+ this.entries = entries;
2897
+ }
2898
+ entries;
2899
+ static parse(filter = {}) {
2900
+ const via = _WorldRequestQuery.via(filter.via);
2901
+ const status = _WorldRequestQuery.status(filter.status);
2902
+ const since = filter.since === void 0 ? void 0 : Instant.parse("since", filter.since);
2903
+ const until = filter.until === void 0 ? void 0 : Instant.parse("until", filter.until);
2904
+ if (since !== void 0 && until !== void 0 && since > until)
2905
+ throw new WorldRequestFilterError("--since must not be after --until.");
2906
+ const values = [
2907
+ ["session", filter.session],
2908
+ ["version", filter.version],
2909
+ ["via", via],
2910
+ ["operation", filter.operation],
2911
+ ["status", status],
2912
+ ["since", since === void 0 ? void 0 : new Date(since).toISOString()],
2913
+ ["until", until === void 0 ? void 0 : new Date(until).toISOString()],
2914
+ ["limit", filter.limit === void 0 ? void 0 : String(filter.limit)],
2915
+ ["cursor", filter.cursor]
2916
+ ];
2917
+ return new _WorldRequestQuery(values.filter((entry) => entry[1] !== void 0));
2918
+ }
2919
+ static via(value) {
2920
+ if (value === void 0) return void 0;
2921
+ const lower = value.toLowerCase();
2922
+ if (WORLD_REQUEST_VIAS.includes(lower)) return lower;
2923
+ throw new WorldRequestFilterError(`--via must be one of ${WORLD_REQUEST_VIAS.join(", ")}, not \`${value}\`.`);
2924
+ }
2925
+ static status(value) {
2926
+ if (value === void 0) return void 0;
2927
+ const lower = value.toLowerCase();
2928
+ if (STATUS.test(lower)) return lower;
2929
+ throw new WorldRequestFilterError(`--status must be a code (200) or a class (2xx), not \`${value}\`.`);
2930
+ }
2931
+ get filtered() {
2932
+ return this.entries.some(([key2]) => key2 !== "limit");
2933
+ }
2934
+ params() {
2935
+ return this.entries.map(([key2, value]) => [key2, value]);
2936
+ }
2937
+ search() {
2938
+ return this.entries.length ? `?${new URLSearchParams(this.entries).toString()}` : "";
2939
+ }
2940
+ };
2941
+ WorldRequestLedger = class {
2942
+ constructor(options = {}) {
2943
+ this.options = options;
2944
+ }
2945
+ options;
2946
+ /** A page of the world's requests, newest first; `nextCursor` reads the page after it. Narrowed to a session
2947
+ * whose engine records none: `WorldRequestsNotRecorded`. */
2948
+ list(slug, query = WorldRequestQuery.parse()) {
2949
+ return WorldRequestsNotRecorded.mapped(
2950
+ apiRequest(
2951
+ this.options,
2952
+ "GET",
2953
+ `${WORLDS}/${encodeURIComponent(slug)}/requests${query.search()}`
2954
+ )
2955
+ );
2956
+ }
2957
+ /** One of the world's requests, with its headers and bodies. */
2958
+ get(slug, requestId) {
2959
+ return apiRequest(
2960
+ this.options,
2961
+ "GET",
2962
+ `${WORLDS}/${encodeURIComponent(slug)}/requests/${encodeURIComponent(requestId)}`
2963
+ );
2964
+ }
2965
+ /** A page of one session's requests, newest first; `WorldRequestsNotRecorded` when its engine records none. */
2966
+ forSession(sessionId, query = WorldRequestQuery.parse()) {
2967
+ return WorldRequestsNotRecorded.mapped(
2968
+ apiRequest(
2969
+ this.options,
2970
+ "GET",
2971
+ `${SESSIONS}/${encodeURIComponent(sessionId)}/requests${query.search()}`
2972
+ )
2973
+ );
2974
+ }
2975
+ };
2976
+ }
2977
+ });
2978
+
2708
2979
  // src/worlds/sessionReadiness.ts
2709
2980
  var READY_TIMEOUT_MS, READY_POLL_MS, sleep3, WorldSessionTimeout, WorldSessionCallError, WorldSessionOpenFailed, ENDED, SessionReadiness;
2710
2981
  var init_sessionReadiness = __esm({
@@ -3044,57 +3315,6 @@ __export(session_exports2, {
3044
3315
  taskLabel: () => taskLabel
3045
3316
  });
3046
3317
  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
3318
  async function attachSession(sessionId, options = {}) {
3099
3319
  const state2 = await apiRequest(
3100
3320
  options,
@@ -3115,6 +3335,7 @@ async function openSession(slugOrRef, taskOrOpts = {}, positionalOpts = {}) {
3115
3335
  `Unknown world surfaces: ${unknown.join(", ")}; choose from ${SURFACE_KINDS.join(", ")}`
3116
3336
  );
3117
3337
  if (opts.browserTier !== void 0) assertBrowserTier(opts.browserTier);
3338
+ if (opts.auth !== void 0) assertSessionAuthMode(opts.auth);
3118
3339
  const at = slugOrRef.indexOf("@");
3119
3340
  const slug = at === -1 ? slugOrRef : slugOrRef.slice(0, at);
3120
3341
  const ref = at === -1 ? "" : slugOrRef.slice(at + 1);
@@ -3127,7 +3348,8 @@ async function openSession(slugOrRef, taskOrOpts = {}, positionalOpts = {}) {
3127
3348
  ...task === void 0 ? {} : { task },
3128
3349
  ...opts.reuseWarm === void 0 ? {} : { reuseWarm: opts.reuseWarm },
3129
3350
  ...opts.surfaces?.length ? { surfaces: opts.surfaces } : {},
3130
- ...opts.browserTier === void 0 ? {} : { browserTier: opts.browserTier }
3351
+ ...opts.browserTier === void 0 ? {} : { browserTier: opts.browserTier },
3352
+ ...opts.auth === void 0 ? {} : { auth: opts.auth }
3131
3353
  }
3132
3354
  );
3133
3355
  return new WorldSession(state2.sessionId, state2, options);
@@ -3208,7 +3430,7 @@ async function runSessions(opts) {
3208
3430
  passed: failed === 0 && (opts.failUnder === void 0 || mean >= opts.failUnder)
3209
3431
  };
3210
3432
  }
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;
3433
+ 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
3434
  var init_session2 = __esm({
3213
3435
  "src/worlds/session.ts"() {
3214
3436
  "use strict";
@@ -3216,6 +3438,8 @@ var init_session2 = __esm({
3216
3438
  init_browser();
3217
3439
  init_nativeComputer();
3218
3440
  init_sessionContract();
3441
+ init_toolSchema();
3442
+ init_requestLedger();
3219
3443
  init_sessionReadiness();
3220
3444
  init_session();
3221
3445
  init_taskRef();
@@ -3229,7 +3453,6 @@ var init_session2 = __esm({
3229
3453
  JUDGED_GRADE_POLL_MS = 2e3;
3230
3454
  EXPORT_PAGE = 500;
3231
3455
  sleep4 = (ms) => new Promise((r) => setTimeout(r, ms));
3232
- modelToolName = (name) => name.replace(/[^A-Za-z0-9_-]/g, "_").slice(0, 64) || "tool";
3233
3456
  WorldSession = class {
3234
3457
  constructor(sessionId, current, options) {
3235
3458
  this.sessionId = sessionId;
@@ -3299,12 +3522,12 @@ var init_session2 = __esm({
3299
3522
  );
3300
3523
  return api2.url;
3301
3524
  }
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 `{}`. */
3525
+ /** Headers every request to `api()` needs: a World Host session's token in the
3526
+ * platform's `X-World-Session` header, which every world takes; `{}` for a pod
3527
+ * or hosted twin, which answers with the world's own declared auth. */
3305
3528
  async apiHeaders() {
3306
3529
  const { api: api2 } = await this.surfaces();
3307
- return api2?.token ? { Authorization: `Bearer ${api2.token}` } : {};
3530
+ return api2?.token ? { [PLATFORM_SESSION_HEADER]: api2.token } : {};
3308
3531
  }
3309
3532
  /** URL of the world's UI entry page for this session. */
3310
3533
  async ui() {
@@ -3375,11 +3598,28 @@ var init_session2 = __esm({
3375
3598
  }
3376
3599
  /** The session's latest platform state (one request, no waiting). */
3377
3600
  async status() {
3601
+ return this.refresh(
3602
+ await apiRequest(
3603
+ this.options,
3604
+ "GET",
3605
+ `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}`
3606
+ )
3607
+ );
3608
+ }
3609
+ /** The world started over under the same id, URLs and token, on what its pin (or `version`, which becomes
3610
+ * its pin) resolves to now: base data plus the task's seed. A grade then reads only the new world's requests. */
3611
+ async restart(opts = {}) {
3378
3612
  const fresh = await apiRequest(
3379
3613
  this.options,
3380
- "GET",
3381
- `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}`
3614
+ "POST",
3615
+ `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/restart`,
3616
+ opts.version ? { version: opts.version } : {}
3382
3617
  );
3618
+ this.refresh(fresh);
3619
+ return fresh;
3620
+ }
3621
+ // A status read carries neither the objective nor the open's notices; keep the ones we opened with.
3622
+ refresh(fresh) {
3383
3623
  this.current = {
3384
3624
  instruction: this.current.instruction,
3385
3625
  tools: this.current.tools,
@@ -3414,7 +3654,7 @@ var init_session2 = __esm({
3414
3654
  const { callId } = enqueued;
3415
3655
  const judged = enqueued.pending === true;
3416
3656
  const budgetMs = timeoutMs ?? (judged ? JUDGED_GRADE_TIMEOUT_MS : CALL_TIMEOUT_MS);
3417
- const pollMs2 = judged ? JUDGED_GRADE_POLL_MS : CALL_POLL_MS;
3657
+ const pollMs = judged ? JUDGED_GRADE_POLL_MS : CALL_POLL_MS;
3418
3658
  const deadline = Date.now() + budgetMs;
3419
3659
  for (; ; ) {
3420
3660
  const call = await apiRequest(
@@ -3430,7 +3670,7 @@ var init_session2 = __esm({
3430
3670
  throw new WorldSessionTimeout(
3431
3671
  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
3672
  );
3433
- await sleep4(pollMs2);
3673
+ await sleep4(pollMs);
3434
3674
  }
3435
3675
  }
3436
3676
  /**
@@ -3523,19 +3763,31 @@ var init_session2 = __esm({
3523
3763
  async reset(opts = {}) {
3524
3764
  await this.exchange({ kind: "reset" }, opts.timeoutMs);
3525
3765
  }
3766
+ /** One page of the session's entries in its world's request ledger, newest
3767
+ * first and without bodies: at most `limit` after `cursor` (the last page's
3768
+ * `nextCursor`). Reading it records nothing in the session. */
3769
+ async requests(opts = {}) {
3770
+ return new WorldRequestLedger(this.options).forSession(
3771
+ this.sessionId,
3772
+ WorldRequestQuery.parse({ cursor: opts.cursor, limit: opts.limit ?? REQUEST_LOG_PAGE_MAX })
3773
+ );
3774
+ }
3775
+ page(route2, limit, cursor) {
3776
+ const query = new URLSearchParams({ limit: String(limit) });
3777
+ if (cursor) query.set("cursor", cursor);
3778
+ return apiRequest(
3779
+ this.options,
3780
+ "GET",
3781
+ `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/${route2}?${query.toString()}`
3782
+ );
3783
+ }
3526
3784
  /** The session's call log, oldest first: every tool call, seed, reset,
3527
3785
  * grade with its result — the record of the episode. */
3528
3786
  async export() {
3529
3787
  const calls = [];
3530
3788
  let cursor;
3531
3789
  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
- );
3790
+ const page = await this.page("calls", EXPORT_PAGE, cursor);
3539
3791
  for (const call of page.calls) {
3540
3792
  calls.push({
3541
3793
  seq: Number(call.seq),
@@ -3617,6 +3869,7 @@ var init_session2 = __esm({
3617
3869
  "reuseWarm",
3618
3870
  "surfaces",
3619
3871
  "browserTier",
3872
+ "auth",
3620
3873
  "options"
3621
3874
  ]);
3622
3875
  isOpenSessionOptions = (value) => typeof value === "object" && value !== null && Object.keys(value).every((key2) => OPEN_SESSION_OPTION_KEYS.has(key2));
@@ -3731,11 +3984,50 @@ var init_tasks = __esm({
3731
3984
  }
3732
3985
  });
3733
3986
 
3987
+ // src/worlds/taskGrades.ts
3988
+ var TASKS2, compact2, TaskGrades;
3989
+ var init_taskGrades = __esm({
3990
+ "src/worlds/taskGrades.ts"() {
3991
+ "use strict";
3992
+ init_worlds();
3993
+ TASKS2 = "/api/public/world-tasks";
3994
+ compact2 = (body) => Object.fromEntries(Object.entries(body).filter(([, v]) => v !== void 0));
3995
+ TaskGrades = class {
3996
+ constructor(options = {}) {
3997
+ this.options = options;
3998
+ }
3999
+ options;
4000
+ try(sessionId, target) {
4001
+ return apiRequest(
4002
+ this.options,
4003
+ "POST",
4004
+ `${TASKS2}/try`,
4005
+ compact2({ sessionId, ...target })
4006
+ );
4007
+ }
4008
+ regrade(taskId, scope = {}) {
4009
+ return apiRequest(
4010
+ this.options,
4011
+ "POST",
4012
+ `${TASKS2}/${encodeURIComponent(taskId)}/regrade`,
4013
+ compact2({ ...scope })
4014
+ );
4015
+ }
4016
+ };
4017
+ }
4018
+ });
4019
+
3734
4020
  // src/worlds/surfaceDescriptor.ts
3735
4021
  function surfaceDescriptor(s) {
3736
4022
  return {
3737
4023
  surfaces: surfaceKinds(s),
3738
- ...s.api ? { api: { url: s.api.url, ...s.api.token ? { token: s.api.token } : {} } } : {},
4024
+ ...s.api ? {
4025
+ api: {
4026
+ url: s.api.url,
4027
+ ...s.api.token ? { token: s.api.token } : {},
4028
+ ...s.api.auth ? { auth: s.api.auth } : {}
4029
+ }
4030
+ } : {},
3739
4031
  ...s.ui ? { ui: { url: s.ui.url, entry: uiEntryUrl(s.ui), apiPath: s.ui.apiPath ?? null } } : {},
3740
4032
  ...s.browser ? {
3741
4033
  browser: {
@@ -3785,8 +4077,7 @@ function fromResponse(answer, options) {
3785
4077
  sessions2[alias] = new WorldSession(state2.sessionId, state2, options);
3786
4078
  worlds[alias] = {
3787
4079
  slug: state2.slug,
3788
- ref: state2.ref,
3789
- private: state2.private ?? null
4080
+ ref: state2.ref
3790
4081
  };
3791
4082
  }
3792
4083
  return new TaskSessions(
@@ -3861,7 +4152,6 @@ async function attachTask(taskId, options = {}) {
3861
4152
  {
3862
4153
  slug: row.slug ?? "",
3863
4154
  ref: null,
3864
- private: null,
3865
4155
  versionId: row.versionId,
3866
4156
  sessionId: row.sessionId,
3867
4157
  ready: row.ready,
@@ -3891,7 +4181,7 @@ async function attachManifest(manifest, options = {}) {
3891
4181
  Object.fromEntries(
3892
4182
  Object.entries(manifest.sessions).map(([alias, entry]) => [
3893
4183
  alias,
3894
- { slug: entry.slug, ref: entry.ref, private: entry.private ?? null }
4184
+ { slug: entry.slug, ref: entry.ref }
3895
4185
  ])
3896
4186
  )
3897
4187
  );
@@ -3913,7 +4203,6 @@ var init_taskSessions = __esm({
3913
4203
  manifestSession = (s, state2, world) => ({
3914
4204
  slug: world.slug,
3915
4205
  ref: world.ref,
3916
- private: world.private,
3917
4206
  versionId: state2.versionId,
3918
4207
  sessionId: state2.sessionId,
3919
4208
  ready: state2.ready,
@@ -3970,7 +4259,7 @@ var init_taskSessions = __esm({
3970
4259
  /** This alias's world as recorded at open/attach — what a `TaskRun`
3971
4260
  * filing needs to name, without exposing the whole map. */
3972
4261
  worldRef(alias) {
3973
- return this.worlds[alias] ?? { slug: "", ref: null, private: null };
4262
+ return this.worlds[alias] ?? { slug: "", ref: null };
3974
4263
  }
3975
4264
  /** The aliases, in the spec's order. */
3976
4265
  get aliases() {
@@ -4295,16 +4584,12 @@ var init_taskRunOutcome = __esm({
4295
4584
  evaluationId;
4296
4585
  evaluationStatus = null;
4297
4586
  started = Date.now();
4298
- /** The run stopped short of a grade; the first reason stands. */
4299
4587
  stopped(error) {
4300
4588
  this.runError ??= messageOf(error).slice(0, 2e3);
4301
4589
  }
4302
4590
  agentRaised(error) {
4303
4591
  this.agentError = messageOf(error).slice(0, 2e3);
4304
4592
  }
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
4593
  failure() {
4309
4594
  const reasons = [
4310
4595
  this.agentError === null ? null : `agent raised: ${this.agentError}`,
@@ -4400,6 +4685,7 @@ var init_taskRunOutcome = __esm({
4400
4685
  ])
4401
4686
  ),
4402
4687
  ungraded: this.grade?.ungraded ?? live.aliases,
4688
+ verifierVersion: live.taskVersion,
4403
4689
  traced: this.traced,
4404
4690
  runDir: this.runDir,
4405
4691
  ...this.agentError ? { agentError: this.agentError } : {},
@@ -4777,7 +5063,7 @@ var require_package = __commonJS({
4777
5063
  "package.json"(exports, module) {
4778
5064
  module.exports = {
4779
5065
  name: "@withgateway/sdk",
4780
- version: "0.3.3",
5066
+ version: "0.6.0",
4781
5067
  description: "Gateway SDK for TypeScript - A/B experiments, tracing, and observability",
4782
5068
  main: "./dist/index.js",
4783
5069
  module: "./dist/index.mjs",
@@ -6056,51 +6342,195 @@ var init_setRun = __esm({
6056
6342
  });
6057
6343
 
6058
6344
  // src/worlds/requestLog.ts
6059
- var WorldRequestLog;
6345
+ function worldRequestsUnrecorded(counts) {
6346
+ 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)));
6347
+ return parts2.length > 0 ? `Not recorded: ${parts2.join(", ")}` : null;
6348
+ }
6349
+ function counted(value) {
6350
+ return typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : 0;
6351
+ }
6352
+ var UNRECORDED, WorldRequestLog;
6060
6353
  var init_requestLog = __esm({
6061
6354
  "src/worlds/requestLog.ts"() {
6062
6355
  "use strict";
6356
+ init_requestLedger();
6357
+ UNRECORDED = [
6358
+ ["lost", "{n} request", "{n} requests"],
6359
+ ["shed", "{n} request's headers and bodies", "{n} requests' headers and bodies"],
6360
+ ["hostsLost", "the requests {n} lost host held", "the requests {n} lost hosts held"]
6361
+ ];
6063
6362
  WorldRequestLog = class _WorldRequestLog {
6064
- constructor(requests) {
6363
+ constructor(requests, notRecorded = null, unrecorded = null) {
6065
6364
  this.requests = requests;
6365
+ this.notRecorded = notRecorded;
6366
+ this.unrecorded = unrecorded;
6066
6367
  }
6067
6368
  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. */
6369
+ notRecorded;
6370
+ unrecorded;
6371
+ /** Every entry the ledger holds for the session, oldest first, and the line for what it did not record;
6372
+ * for a session the World Host did not serve, none, and `notRecorded` says why. */
6373
+ static async load(session) {
6374
+ try {
6375
+ return await _WorldRequestLog.pages(session);
6376
+ } catch (error) {
6377
+ const refused = WorldRequestsNotRecorded.from(error);
6378
+ if (!(refused instanceof WorldRequestsNotRecorded)) throw error;
6379
+ return new _WorldRequestLog([], refused.message);
6380
+ }
6381
+ }
6382
+ static async pages(session) {
6383
+ const requests = [];
6384
+ let cursor;
6385
+ for (; ; ) {
6386
+ const page = await session.requests(cursor ? { cursor } : {});
6387
+ requests.push(...page.requests);
6388
+ if (!page.nextCursor || page.requests.length === 0)
6389
+ return new _WorldRequestLog(requests.reverse(), null, worldRequestsUnrecorded(page));
6390
+ cursor = page.nextCursor;
6391
+ }
6392
+ }
6393
+ /** Each entry in the shape of a ledger line, `kind: "request"`, so one JSONL
6394
+ * file holds both: `args` what was asked, `result` what came back under the
6395
+ * entry's `requestId`. */
6082
6396
  asCalls() {
6083
6397
  return this.requests.map((r) => ({
6084
- seq: Number(r.seq) || 0,
6398
+ seq: r.seq,
6085
6399
  kind: "request",
6086
- tool: r.operation ?? null,
6400
+ tool: r.operation,
6087
6401
  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
6402
+ method: r.method,
6403
+ path: r.path,
6404
+ query: r.query,
6405
+ via: r.via,
6406
+ contentType: r.request.contentType,
6407
+ bodyBytes: r.request.bodyBytes,
6408
+ truncated: r.request.truncated
6409
+ },
6410
+ result: {
6411
+ requestId: r.id,
6412
+ status: r.response.status,
6413
+ rows: r.rows,
6414
+ found: r.found,
6415
+ durationMs: r.durationMs,
6416
+ contentType: r.response.contentType,
6417
+ bodyBytes: r.response.bodyBytes,
6418
+ truncated: r.response.truncated
6094
6419
  },
6095
- result: { status: r.status ?? null, rows: r.rows ?? null, found: r.found ?? null },
6096
6420
  error: null,
6097
- completedAt: r.at ?? null
6421
+ completedAt: r.at
6098
6422
  }));
6099
6423
  }
6100
6424
  };
6101
6425
  }
6102
6426
  });
6103
6427
 
6428
+ // src/worlds/webhooks.ts
6429
+ async function listWebhooks(options, sessionId, page = {}) {
6430
+ const query = new URLSearchParams({
6431
+ after: String(page.after ?? 0),
6432
+ limit: String(page.limit ?? WORLD_WEBHOOK_PAGE_MAX),
6433
+ tail: String(page.tail ?? false)
6434
+ });
6435
+ if (page.epoch) query.set("epoch", page.epoch);
6436
+ return apiRequest(options, "GET", `${route(sessionId)}?${query.toString()}`);
6437
+ }
6438
+ var WORLD_WEBHOOK_PAGE_MAX, FORWARD_TIMEOUT_MS, ERROR_CHARS, route, WorldWebhookForwarder;
6439
+ var init_webhooks = __esm({
6440
+ "src/worlds/webhooks.ts"() {
6441
+ "use strict";
6442
+ init_worlds();
6443
+ WORLD_WEBHOOK_PAGE_MAX = 100;
6444
+ FORWARD_TIMEOUT_MS = 1e4;
6445
+ ERROR_CHARS = 500;
6446
+ route = (sessionId) => `/api/public/world-sessions/${encodeURIComponent(sessionId)}/webhooks`;
6447
+ WorldWebhookForwarder = class {
6448
+ constructor(options, sessionId, forwardTo, opts = {}) {
6449
+ this.options = options;
6450
+ this.sessionId = sessionId;
6451
+ this.forwardTo = forwardTo;
6452
+ this.send = opts.fetch ?? fetch;
6453
+ }
6454
+ options;
6455
+ sessionId;
6456
+ forwardTo;
6457
+ after = 0;
6458
+ epoch = null;
6459
+ answers = [];
6460
+ send;
6461
+ get cursor() {
6462
+ return this.after;
6463
+ }
6464
+ /** Where forwarding begins: the deliveries the session still holds (`replay`), or only those it sends from now. */
6465
+ async start(replay2) {
6466
+ if (replay2) return null;
6467
+ const page = await this.poll([], { tail: true, limit: 1 });
6468
+ this.follow(page);
6469
+ return page;
6470
+ }
6471
+ /** One poll: the answers held so far sent, the next page forwarded. A poll that fails keeps its answers for the next. */
6472
+ async round() {
6473
+ const page = await this.withAnswers((answers) => this.poll(answers));
6474
+ const forwarded = [];
6475
+ for (const delivery of page.deliveries) {
6476
+ const answer = await this.forward(delivery);
6477
+ this.answers.push(answer);
6478
+ forwarded.push({ delivery, answer });
6479
+ }
6480
+ this.follow(page);
6481
+ return { page, forwarded };
6482
+ }
6483
+ /** Sends the answers still held; the cursor stays, so a delivery this poll returns is forwarded by the next round. */
6484
+ async settle() {
6485
+ if (this.answers.length === 0) return 0;
6486
+ const page = await this.withAnswers((answers) => this.poll(answers, { limit: 1 }));
6487
+ return page.answered;
6488
+ }
6489
+ follow(page) {
6490
+ this.after = page.next;
6491
+ this.epoch = page.epoch;
6492
+ }
6493
+ async withAnswers(poll) {
6494
+ const answers = this.answers.splice(0, WORLD_WEBHOOK_PAGE_MAX);
6495
+ try {
6496
+ return await poll(answers);
6497
+ } catch (error) {
6498
+ this.answers.unshift(...answers);
6499
+ throw error;
6500
+ }
6501
+ }
6502
+ poll(answers, opts = {}) {
6503
+ return apiRequest(this.options, "POST", route(this.sessionId), {
6504
+ after: this.after,
6505
+ epoch: this.epoch,
6506
+ tail: opts.tail ?? false,
6507
+ limit: opts.limit ?? WORLD_WEBHOOK_PAGE_MAX,
6508
+ subscriptions: false,
6509
+ answers
6510
+ });
6511
+ }
6512
+ async forward(delivery) {
6513
+ const started = Date.now();
6514
+ try {
6515
+ const reply = await this.send(this.forwardTo, {
6516
+ method: "POST",
6517
+ headers: delivery.headers,
6518
+ body: delivery.payload,
6519
+ redirect: "manual",
6520
+ signal: AbortSignal.timeout(FORWARD_TIMEOUT_MS)
6521
+ });
6522
+ await reply.arrayBuffer().catch(() => void 0);
6523
+ if (reply.status < 100 || reply.status > 599) throw new Error("the receiver answered an invalid HTTP status");
6524
+ return { id: delivery.id, status: reply.status, durationMs: Date.now() - started, error: null };
6525
+ } catch (error) {
6526
+ const message = error instanceof Error ? error.message : String(error);
6527
+ return { id: delivery.id, status: 0, durationMs: Date.now() - started, error: message.slice(0, ERROR_CHARS) };
6528
+ }
6529
+ }
6530
+ };
6531
+ }
6532
+ });
6533
+
6104
6534
  // src/worlds/checkoutTarget.ts
6105
6535
  import * as fs2 from "fs";
6106
6536
  import * as path3 from "path";
@@ -6789,7 +7219,8 @@ function checkoutIdentity(ref, resolved) {
6789
7219
  async function pull(slugRef, target, options = {}, opts = {}) {
6790
7220
  const at = slugRef.indexOf("@");
6791
7221
  const slug = at === -1 ? slugRef : slugRef.slice(0, at);
6792
- const ref = at === -1 ? "latest" : slugRef.slice(at + 1);
7222
+ const asked = at === -1 ? void 0 : slugRef.slice(at + 1);
7223
+ const ref = asked ?? "latest";
6793
7224
  const landing = CheckoutTarget.resolve(slug, target, {
6794
7225
  cwd: process.cwd(),
6795
7226
  force: opts.force ?? false,
@@ -6797,7 +7228,7 @@ async function pull(slugRef, target, options = {}, opts = {}) {
6797
7228
  });
6798
7229
  const details = await apiRequest(options, "POST", "/api/public/benchmark-containers/resolve-version", {
6799
7230
  slug,
6800
- ref
7231
+ ...asked ? { ref: asked } : {}
6801
7232
  });
6802
7233
  if (!details.downloadUrl) {
6803
7234
  throw new Error(`${slug}@${ref} resolved but has no uploaded bundle`);
@@ -6983,7 +7414,7 @@ async function validateWorld(dir, opts) {
6983
7414
  options,
6984
7415
  "POST",
6985
7416
  "/api/public/benchmark-containers/resolve-version",
6986
- { slug, ref: branch }
7417
+ { slug, ...branch === DEFAULT_BRANCH ? {} : { ref: branch } }
6987
7418
  );
6988
7419
  tipVersionId = tip.versionId ?? null;
6989
7420
  } catch {
@@ -7090,11 +7521,16 @@ var init_validate = __esm({
7090
7521
  });
7091
7522
 
7092
7523
  // src/worlds/sandbox.ts
7524
+ import { createHash as createHash6, randomUUID as randomUUID2 } from "crypto";
7093
7525
  function parseSlugRef(slugRef) {
7094
7526
  const at = slugRef.indexOf("@");
7095
7527
  if (at === -1) return { slug: slugRef };
7096
7528
  return { slug: slugRef.slice(0, at), ref: slugRef.slice(at + 1) };
7097
7529
  }
7530
+ function nameGlob(pattern) {
7531
+ const literal = (part) => part.replace(/[.+?^${}()|[\]\\]/g, "\\$&");
7532
+ return new RegExp(`^${pattern.split("*").map(literal).join(".*")}$`);
7533
+ }
7098
7534
  function rebaseConflicts(error) {
7099
7535
  if (!(error instanceof ApiError) || error.status !== 409) return null;
7100
7536
  let body;
@@ -7112,7 +7548,8 @@ function isConflictPath(value) {
7112
7548
  return typeof entry?.path === "string" && typeof entry.reason === "string";
7113
7549
  }
7114
7550
  function uncommittedPaths(error) {
7115
- if (!(error instanceof ApiError) || error.status !== 409 || error.code !== "sandbox_uncommitted") return null;
7551
+ if (!(error instanceof ApiError) || error.status !== 409 || error.code !== "sandbox_uncommitted")
7552
+ return null;
7116
7553
  let body;
7117
7554
  try {
7118
7555
  body = JSON.parse(error.text);
@@ -7123,6 +7560,53 @@ function uncommittedPaths(error) {
7123
7560
  if (!Array.isArray(uncommitted)) return null;
7124
7561
  return uncommitted.filter((p) => typeof p === "string");
7125
7562
  }
7563
+ function carriedWarnings(error) {
7564
+ const kept = typeof error === "object" && error !== null ? carried.get(error) ?? [] : [];
7565
+ const shown = error instanceof Error ? error.message : "";
7566
+ return unique([...kept, ...bodyWarnings(error)]).filter((warning) => !shown.includes(warning));
7567
+ }
7568
+ function carrying(error, warnings) {
7569
+ if (warnings.length > 0 && typeof error === "object" && error !== null)
7570
+ carried.set(error, unique([...carried.get(error) ?? [], ...warnings]));
7571
+ return error;
7572
+ }
7573
+ function unique(warnings) {
7574
+ return [...new Set(warnings)];
7575
+ }
7576
+ function bodyWarnings(error) {
7577
+ if (!(error instanceof ApiError)) return [];
7578
+ let body;
7579
+ try {
7580
+ body = JSON.parse(error.text);
7581
+ } catch {
7582
+ return [];
7583
+ }
7584
+ const warnings = body?.warnings;
7585
+ if (!Array.isArray(warnings)) return [];
7586
+ return warnings.filter((w) => typeof w === "string");
7587
+ }
7588
+ function deferredWarnings(error) {
7589
+ if (!(error instanceof ApiError) || error.status !== 409 || error.code !== "sandbox_exec_deferred") return null;
7590
+ return bodyWarnings(error);
7591
+ }
7592
+ function rowsRefusal(error) {
7593
+ if (!(error instanceof ApiError) || error.status !== 400 || error.code !== "rows_refused") return null;
7594
+ let body;
7595
+ try {
7596
+ body = JSON.parse(error.text);
7597
+ } catch {
7598
+ return null;
7599
+ }
7600
+ const { message, batchId, refusalCount, refusals, reportUrl } = body;
7601
+ if (typeof batchId !== "string" || typeof refusalCount !== "number" || !Array.isArray(refusals)) return null;
7602
+ return {
7603
+ message: typeof message === "string" ? message : "",
7604
+ batchId,
7605
+ refusalCount,
7606
+ refusals: refusals.filter((r) => typeof r === "object" && r !== null),
7607
+ reportUrl: typeof reportUrl === "string" ? reportUrl : null
7608
+ };
7609
+ }
7126
7610
  function listQuery(filter) {
7127
7611
  const params = new URLSearchParams();
7128
7612
  if (filter.status) params.set("status", filter.status);
@@ -7131,15 +7615,51 @@ function listQuery(filter) {
7131
7615
  const qs3 = params.toString();
7132
7616
  return qs3 ? `?${qs3}` : "";
7133
7617
  }
7134
- var isSandboxImportPending, sid, SANDBOXES, SANDBOX_REQUEST_TIMEOUT_MS, WorldSandboxClient;
7618
+ 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
7619
  var init_sandbox = __esm({
7136
7620
  "src/worlds/sandbox.ts"() {
7137
7621
  "use strict";
7138
7622
  init_worlds();
7623
+ isSandboxCommitPending = (answer) => !("versionId" in answer);
7139
7624
  isSandboxImportPending = (answer) => !("versionId" in answer);
7140
7625
  sid = encodeURIComponent;
7141
7626
  SANDBOXES = "/api/public/benchmark-containers/sandboxes";
7142
- SANDBOX_REQUEST_TIMEOUT_MS = 66e4;
7627
+ SANDBOX_REQUEST_TIMEOUT_MS = 29e4;
7628
+ SANDBOX_WRITE_CHUNK_BYTES = 4 * 1024 * 1024;
7629
+ SANDBOX_FILE_MAX_BYTES = 256 * 1024 * 1024;
7630
+ SANDBOX_WRITE_SKIPPED = [
7631
+ ".git/",
7632
+ ".gateway/",
7633
+ "scratch/",
7634
+ ".scratch/",
7635
+ "__pycache__/",
7636
+ "*.pyc",
7637
+ ".pytest_cache/",
7638
+ ".mypy_cache/",
7639
+ ".ruff_cache/",
7640
+ "node_modules/",
7641
+ ".venv/",
7642
+ "venv/",
7643
+ ".DS_Store",
7644
+ "*.swp"
7645
+ ];
7646
+ WriteTreeFilter = class {
7647
+ directories = new Set(
7648
+ SANDBOX_WRITE_SKIPPED.filter((pattern) => pattern.endsWith("/")).map((pattern) => pattern.slice(0, -1))
7649
+ );
7650
+ files = SANDBOX_WRITE_SKIPPED.filter((pattern) => !pattern.endsWith("/")).map(nameGlob);
7651
+ skipsDirectory(name) {
7652
+ return this.directories.has(name);
7653
+ }
7654
+ skipsFile(name) {
7655
+ return this.files.some((glob) => glob.test(name));
7656
+ }
7657
+ };
7658
+ SANDBOX_EXEC_WAIT_MS = 4e4;
7659
+ SANDBOX_EXEC_TIMEOUT_MAX_S = 600;
7660
+ SANDBOX_EXEC_REPORT_MARGIN_MS = 35e3;
7661
+ SANDBOX_EXEC_START_ATTEMPTS = 3;
7662
+ carried = /* @__PURE__ */ new WeakMap();
7143
7663
  WorldSandboxClient = class {
7144
7664
  constructor(options = {}) {
7145
7665
  this.options = options;
@@ -7164,7 +7684,10 @@ var init_sandbox = __esm({
7164
7684
  }
7165
7685
  /** The project's sandboxes, newest first — how an agent finds one it left open. */
7166
7686
  async list(filter = {}) {
7167
- const res = await this.request("GET", `${SANDBOXES}${listQuery(filter)}`);
7687
+ const res = await this.request(
7688
+ "GET",
7689
+ `${SANDBOXES}${listQuery(filter)}`
7690
+ );
7168
7691
  return res.sandboxes;
7169
7692
  }
7170
7693
  async read(sandboxId, filePath) {
@@ -7172,16 +7695,72 @@ var init_sandbox = __esm({
7172
7695
  "GET",
7173
7696
  `${SANDBOXES}/${sid(sandboxId)}/file?path=${encodeURIComponent(filePath)}`
7174
7697
  );
7175
- return { path: res.path, size: res.size, bytes: Buffer.from(res.contentBase64, "base64") };
7698
+ return {
7699
+ path: res.path,
7700
+ size: res.size,
7701
+ bytes: Buffer.from(res.contentBase64, "base64")
7702
+ };
7176
7703
  }
7177
- write(sandboxId, filePath, bytes) {
7178
- return this.request("PUT", `${SANDBOXES}/${sid(sandboxId)}/file`, {
7179
- path: filePath,
7180
- contentBase64: bytes.toString("base64")
7181
- });
7704
+ /** A file past one chunk goes up in parts under one upload id; the platform lands it whole once the last part's
7705
+ * size and SHA-256 check out. */
7706
+ async write(sandboxId, filePath, bytes) {
7707
+ if (bytes.length <= SANDBOX_WRITE_CHUNK_BYTES)
7708
+ return this.putFile(sandboxId, { path: filePath, contentBase64: bytes.toString("base64") });
7709
+ const whole = { upload: randomUUID2(), size: bytes.length, sha256: createHash6("sha256").update(bytes).digest("hex") };
7710
+ let answer = { path: filePath, received: 0 };
7711
+ for (let offset = 0; offset < bytes.length; offset += SANDBOX_WRITE_CHUNK_BYTES) {
7712
+ const part = bytes.subarray(offset, offset + SANDBOX_WRITE_CHUNK_BYTES);
7713
+ answer = await this.putFile(sandboxId, {
7714
+ path: filePath,
7715
+ contentBase64: part.toString("base64"),
7716
+ ...whole,
7717
+ offset,
7718
+ last: offset + part.length === bytes.length
7719
+ });
7720
+ }
7721
+ return answer;
7722
+ }
7723
+ putFile(sandboxId, body) {
7724
+ return this.request("PUT", `${SANDBOXES}/${sid(sandboxId)}/file`, body);
7725
+ }
7726
+ /** Runs as a job on the platform: a command that outlasts one request is waited on again until its result. */
7727
+ async exec(sandboxId, input) {
7728
+ const budgetMs = (input.timeoutMs ?? SANDBOX_EXEC_TIMEOUT_MAX_S * 1e3) + SANDBOX_EXEC_REPORT_MARGIN_MS;
7729
+ let answer = await this.startExec(sandboxId, { ...input, waitMs: SANDBOX_EXEC_WAIT_MS });
7730
+ const deadline = Date.now() + budgetMs;
7731
+ const warnings = [...answer.warnings ?? []];
7732
+ try {
7733
+ while ("state" in answer) {
7734
+ if (Date.now() >= deadline)
7735
+ throw new Error(
7736
+ `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.`
7737
+ );
7738
+ answer = await this.execStep(sandboxId, { execId: answer.execId, waitMs: SANDBOX_EXEC_WAIT_MS });
7739
+ warnings.push(...answer.warnings ?? []);
7740
+ }
7741
+ } catch (error) {
7742
+ throw carrying(error, warnings);
7743
+ }
7744
+ return { ...answer, warnings };
7745
+ }
7746
+ // A deferred start ran nothing (the platform was still getting the sandbox ready), so starting again is safe. What
7747
+ // getting ready found rides on the deferral alone (no later call reports it), so it is kept for the answer, or for
7748
+ // the error when a later attempt fails.
7749
+ async startExec(sandboxId, body) {
7750
+ const kept = [];
7751
+ for (let attempt = 1; ; attempt += 1) {
7752
+ try {
7753
+ const answer = await this.execStep(sandboxId, body);
7754
+ return { ...answer, warnings: unique([...kept, ...answer.warnings ?? []]) };
7755
+ } catch (error) {
7756
+ const warnings = deferredWarnings(error);
7757
+ if (warnings === null || attempt === SANDBOX_EXEC_START_ATTEMPTS) throw carrying(error, kept);
7758
+ kept.push(...warnings);
7759
+ }
7760
+ }
7182
7761
  }
7183
- exec(sandboxId, input) {
7184
- return this.request("POST", `${SANDBOXES}/${sid(sandboxId)}/exec`, input);
7762
+ execStep(sandboxId, body) {
7763
+ return this.request("POST", `${SANDBOXES}/${sid(sandboxId)}/exec`, body);
7185
7764
  }
7186
7765
  check(sandboxId) {
7187
7766
  return this.request("POST", `${SANDBOXES}/${sid(sandboxId)}/check`, {});
@@ -7189,7 +7768,11 @@ var init_sandbox = __esm({
7189
7768
  /** With `rebase`, a moved base is replayed onto; a 409 then names the conflicting paths (`rebaseConflicts`). */
7190
7769
  commit(sandboxId, input) {
7191
7770
  const { rebase, ...rest } = input;
7192
- return this.request("POST", `${SANDBOXES}/${sid(sandboxId)}/commit`, rebase ? { ...rest, rebase: true } : rest);
7771
+ return this.request(
7772
+ "POST",
7773
+ `${SANDBOXES}/${sid(sandboxId)}/commit`,
7774
+ rebase ? { ...rest, rebase: true } : rest
7775
+ );
7193
7776
  }
7194
7777
  /**
7195
7778
  * A rows file already in the sandbox tree into the PLATFORM world the
@@ -7202,7 +7785,11 @@ var init_sandbox = __esm({
7202
7785
  }
7203
7786
  /** Uncommitted work is a 409 (`uncommittedPaths`) unless `force` discards it. */
7204
7787
  close(sandboxId, opts = {}) {
7205
- return this.request("DELETE", `${SANDBOXES}/${sid(sandboxId)}`, opts.force ? { force: true } : void 0);
7788
+ return this.request(
7789
+ "DELETE",
7790
+ `${SANDBOXES}/${sid(sandboxId)}`,
7791
+ opts.force ? { force: true } : void 0
7792
+ );
7206
7793
  }
7207
7794
  };
7208
7795
  }
@@ -7521,7 +8108,7 @@ var init_json = __esm({
7521
8108
  });
7522
8109
 
7523
8110
  // src/worlds/transforms.ts
7524
- import { createHash as createHash6 } from "crypto";
8111
+ import { createHash as createHash7 } from "crypto";
7525
8112
  function parseTransform(name) {
7526
8113
  const simple = Object.prototype.hasOwnProperty.call(SIMPLE, name) ? SIMPLE[name] : void 0;
7527
8114
  if (simple) return simple;
@@ -7559,7 +8146,7 @@ var init_transforms = __esm({
7559
8146
  return at === -1 ? "" : value.slice(at + 1).toLowerCase();
7560
8147
  };
7561
8148
  stripPrefix = (prefix) => (value) => value.startsWith(prefix) ? value.slice(prefix.length) : value;
7562
- hex = (algorithm, value) => createHash6(algorithm).update(value, "utf8").digest("hex");
8149
+ hex = (algorithm, value) => createHash7(algorithm).update(value, "utf8").digest("hex");
7563
8150
  SIMPLE = {
7564
8151
  lower: (value) => value.toLowerCase(),
7565
8152
  upper: (value) => value.toUpperCase(),
@@ -7583,7 +8170,7 @@ var init_transforms = __esm({
7583
8170
  });
7584
8171
 
7585
8172
  // src/worlds/redaction.ts
7586
- import { createHash as createHash7 } from "crypto";
8173
+ import { createHash as createHash8 } from "crypto";
7587
8174
  function pyText(value) {
7588
8175
  if (typeof value === "string") return value;
7589
8176
  if (Number.isInteger(value)) return String(value);
@@ -7592,7 +8179,7 @@ function pyText(value) {
7592
8179
  return pyFloatRepr(value);
7593
8180
  }
7594
8181
  function hashForm(slug, plaintext) {
7595
- return "sha256:" + createHash7("sha256").update(`${slug}:${pyText(plaintext)}`, "utf8").digest("hex");
8182
+ return "sha256:" + createHash8("sha256").update(`${slug}:${pyText(plaintext)}`, "utf8").digest("hex");
7596
8183
  }
7597
8184
  function preserveForm(slug, plaintext) {
7598
8185
  const kind = typeof plaintext === "string" ? "str" : isInt(plaintext) ? "int" : "float";
@@ -7601,12 +8188,12 @@ function preserveForm(slug, plaintext) {
7601
8188
  }
7602
8189
  function shapeText(slug, text2, kind) {
7603
8190
  const seed = Buffer.from(`${slug}:${text2}`, "utf8");
7604
- let digest = createHash7("sha256").update(seed).digest();
8191
+ let digest = createHash8("sha256").update(seed).digest();
7605
8192
  let cursor = 0;
7606
8193
  const out = [];
7607
8194
  for (const char of text2) {
7608
8195
  if (cursor === digest.length) {
7609
- digest = createHash7("sha256").update(Buffer.concat([digest, seed])).digest();
8196
+ digest = createHash8("sha256").update(Buffer.concat([digest, seed])).digest();
7610
8197
  cursor = 0;
7611
8198
  }
7612
8199
  const byte = digest[cursor];
@@ -7745,9 +8332,9 @@ var init_router = __esm({
7745
8332
  import * as fs6 from "fs";
7746
8333
  import * as os from "os";
7747
8334
  import * as path7 from "path";
7748
- async function api(creds, method, route, body, init3 = {}) {
7749
- const reply = await new PlatformTransport(creds).send(method, route, body, init3);
7750
- if (!reply.ok) throw new ApiError2(reply.status, method, route, reply.text);
8335
+ async function api(creds, method, route2, body, init3 = {}) {
8336
+ const reply = await new PlatformTransport(creds).send(method, route2, body, init3);
8337
+ if (!reply.ok) throw new ApiError2(reply.status, method, route2, reply.text);
7751
8338
  return reply.text ? JSON.parse(reply.text) : {};
7752
8339
  }
7753
8340
  var ApiError2;
@@ -7758,12 +8345,12 @@ var init_config = __esm({
7758
8345
  init_worlds();
7759
8346
  init_transport();
7760
8347
  ApiError2 = class extends CliError {
7761
- constructor(status, method, route, text2) {
7762
- const body = parseErrorBody(text2);
7763
- super(`${method} ${route} -> ${status}: ${body.detail}`, 1);
8348
+ constructor(status, method, route2, text2) {
8349
+ const body = parseErrorBody(text2, status);
8350
+ super(`${method} ${route2} -> ${status}: ${body.detail}`, 1);
7764
8351
  this.status = status;
7765
8352
  this.method = method;
7766
- this.route = route;
8353
+ this.route = route2;
7767
8354
  this.text = text2;
7768
8355
  this.code = body.code;
7769
8356
  }
@@ -7781,6 +8368,14 @@ import { spawn, spawnSync } from "child_process";
7781
8368
  import * as fs7 from "fs";
7782
8369
  import * as net from "net";
7783
8370
  import * as path8 from "path";
8371
+ function forwardedEnv() {
8372
+ return Object.fromEntries(
8373
+ FORWARDED_ENV.flatMap((name) => {
8374
+ const value = process.env[name];
8375
+ return value ? [[name, value]] : [];
8376
+ })
8377
+ );
8378
+ }
7784
8379
  function tailOf(output) {
7785
8380
  return output.length > DIAGNOSTIC_TAIL ? `\u2026${output.slice(-DIAGNOSTIC_TAIL)}` : output;
7786
8381
  }
@@ -7898,7 +8493,7 @@ async function localBridge(request, local, opts = {}) {
7898
8493
  PATH: process.env.PATH ?? "",
7899
8494
  HOME: process.env.HOME ?? "",
7900
8495
  TMPDIR: process.env.TMPDIR ?? "",
7901
- ...process.env.VIRTUAL_ENV ? { VIRTUAL_ENV: process.env.VIRTUAL_ENV } : {},
8496
+ ...forwardedEnv(),
7902
8497
  GATEWAY_RUNTIME_EXECUTE: "1"
7903
8498
  }
7904
8499
  }
@@ -7944,7 +8539,7 @@ async function localBridge(request, local, opts = {}) {
7944
8539
  child.stdin.end(input);
7945
8540
  });
7946
8541
  }
7947
- var MIN_PYTHON, MIN_PYTHON_LABEL, DIAGNOSTIC_TAIL, BRIDGE_BOOTSTRAP, pythonCache, pythonProbes, PYTHON_CANDIDATES, UV_FIND;
8542
+ var MIN_PYTHON, MIN_PYTHON_LABEL, DIAGNOSTIC_TAIL, FORWARDED_ENV, BRIDGE_BOOTSTRAP, pythonCache, pythonProbes, PYTHON_CANDIDATES, UV_FIND;
7948
8543
  var init_local = __esm({
7949
8544
  "src/cli/runtime/local.ts"() {
7950
8545
  "use strict";
@@ -7953,6 +8548,7 @@ var init_local = __esm({
7953
8548
  MIN_PYTHON = [3, 12];
7954
8549
  MIN_PYTHON_LABEL = MIN_PYTHON.join(".");
7955
8550
  DIAGNOSTIC_TAIL = 600;
8551
+ FORWARDED_ENV = ["VIRTUAL_ENV", "GATEWAY_SNAPSHOT_STORE"];
7956
8552
  BRIDGE_BOOTSTRAP = `import sys,runpy,types,os
7957
8553
  root=sys.argv[1]
7958
8554
  package=types.ModuleType('gatewaysdk')
@@ -8107,8 +8703,8 @@ async function runtime(creds, request, opts = {}) {
8107
8703
  throw new CliError(
8108
8704
  "This needs the schema runtime (the CLI bundles it) or platform credentials (`gateway auth login`). " + localRuntimeReason()
8109
8705
  );
8110
- const route = "/api/public/worlds/runtime";
8111
- const res = await new PlatformTransport(creds).send("POST", route, request, {
8706
+ const route2 = "/api/public/worlds/runtime";
8707
+ const res = await new PlatformTransport(creds).send("POST", route2, request, {
8112
8708
  timeoutMs: opts.timeoutMs ?? RUNTIME_TIMEOUT_MS
8113
8709
  });
8114
8710
  let payload = null;
@@ -8120,8 +8716,8 @@ async function runtime(creds, request, opts = {}) {
8120
8716
  const detail = detailFrom(payload);
8121
8717
  if (detail) throw new BridgeRejected(detail);
8122
8718
  if (!res.ok)
8123
- throw new CliError(`POST ${route} (${request.command}) -> ${res.status}: ${res.text.slice(0, 600)}`, 1);
8124
- if (payload === null) throw new CliError(`POST ${route} (${request.command}) returned non-JSON`, 1);
8719
+ throw new CliError(`POST ${route2} (${request.command}) -> ${res.status}: ${res.text.slice(0, 600)}`, 1);
8720
+ if (payload === null) throw new CliError(`POST ${route2} (${request.command}) returned non-JSON`, 1);
8125
8721
  return payload;
8126
8722
  }
8127
8723
  var MAX_WORLD_FILES, RUNTIME_TIMEOUT_MS, SKIP_DIRS, BridgeRejected, YAML_NAME, YAML_NEEDS_PYYAML, YAML_NOT_ON_PLATFORM, RuntimeRoute;
@@ -8581,18 +9177,22 @@ if (fn) {
8581
9177
  });
8582
9178
 
8583
9179
  // src/cli/platform/worldData/batches.ts
8584
- import { createHash as createHash8 } from "crypto";
9180
+ import { createHash as createHash9 } from "crypto";
8585
9181
  import * as fs11 from "fs";
8586
9182
  function isSettled(status) {
8587
9183
  if (!TERMINAL_STATES.has(status.state)) return false;
8588
9184
  if (status.state !== "applied") return true;
8589
9185
  return status.dryRun === true || status.publish !== "now" || !status.snapshotId;
8590
9186
  }
9187
+ function worldDataPollMs() {
9188
+ const raw = Number(process.env.GATEWAY_WORLD_DATA_POLL_MS ?? 1e3);
9189
+ return Number.isFinite(raw) && raw >= 0 ? raw : 1e3;
9190
+ }
8591
9191
  function uploadHeadersFor(gz) {
8592
9192
  return {
8593
9193
  "content-type": "application/gzip",
8594
9194
  "content-length": String(gz.length),
8595
- "x-amz-checksum-sha256": createHash8("sha256").update(gz).digest("base64")
9195
+ "x-amz-checksum-sha256": createHash9("sha256").update(gz).digest("base64")
8596
9196
  };
8597
9197
  }
8598
9198
  async function forEachLimited(items, limit, fn) {
@@ -8630,6 +9230,8 @@ async function waitForBatch(client2, batchId, opts = {}) {
8630
9230
  last = phase;
8631
9231
  }
8632
9232
  if (isSettled(status)) return status;
9233
+ if (opts.deadlineMs !== void 0 && (opts.now ?? Date.now)() >= opts.deadlineMs)
9234
+ return status;
8633
9235
  await sleep5(delay);
8634
9236
  delay = Math.min(1e4, Math.round(delay * 1.5));
8635
9237
  }
@@ -8679,11 +9281,6 @@ var init_batches = __esm({
8679
9281
  }
8680
9282
  );
8681
9283
  }
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
9284
  async stageDrive(batchId, chunk) {
8688
9285
  const staged = await api(this.creds, "POST", `${this.base}/batches/${batchId}/chunks`, {
8689
9286
  ordinal: chunk.ordinal,
@@ -8737,11 +9334,6 @@ var init_batches = __esm({
8737
9334
  message ? { message } : {}
8738
9335
  );
8739
9336
  }
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
9337
  async put(uploadUrl, gz, signed) {
8746
9338
  const headers = signed ?? uploadHeadersFor(gz);
8747
9339
  const delays = [500, 1500, 4e3];
@@ -8768,7 +9360,6 @@ var init_batches = __esm({
8768
9360
  await this.sleep(delays[attempt]);
8769
9361
  }
8770
9362
  }
8771
- /** Register, upload unless the server already holds the content, confirm. */
8772
9363
  async upload(batchId, chunk) {
8773
9364
  const registered = await this.register(batchId, chunk);
8774
9365
  if (!registered.uploaded) {
@@ -8795,7 +9386,7 @@ var init_batches = __esm({
8795
9386
  });
8796
9387
 
8797
9388
  // src/cli/platform/worldData/chunker.ts
8798
- import { createHash as createHash9 } from "crypto";
9389
+ import { createHash as createHash10 } from "crypto";
8799
9390
  import { deflateRawSync } from "zlib";
8800
9391
  function chunkLine(row, declared) {
8801
9392
  if (declared !== null) return dumps(row.row) + "\n";
@@ -8836,12 +9427,12 @@ function finishChunk(ordinal, raw, rows, entity, firstRow = 0) {
8836
9427
  const gz = gzipDeterministic(raw, { name: chunkName(ordinal) });
8837
9428
  return {
8838
9429
  ordinal,
8839
- digest: createHash9("sha256").update(gz).digest("hex"),
9430
+ digest: createHash10("sha256").update(gz).digest("hex"),
8840
9431
  bytes: gz.length,
8841
9432
  rows,
8842
9433
  entity,
8843
9434
  rawBytes: raw.length,
8844
- contentSha256: createHash9("sha256").update(raw).digest("hex"),
9435
+ contentSha256: createHash10("sha256").update(raw).digest("hex"),
8845
9436
  firstRow,
8846
9437
  gz
8847
9438
  };
@@ -8909,22 +9500,33 @@ async function pushRows(creds, slug, rows, opts = {}) {
8909
9500
  publish: opts.publish ?? "now",
8910
9501
  ...opts.message ? { message: opts.message } : {}
8911
9502
  });
8912
- if (!opened.batchId) throw new Error("the platform opened no batch (no batchId in the answer)");
9503
+ if (!opened.batchId)
9504
+ throw new Error("the platform opened no batch (no batchId in the answer)");
8913
9505
  const tagged = (async function* () {
8914
9506
  for (const [entity, listed] of Object.entries(rows))
8915
9507
  for (let index2 = 0; index2 < listed.length; index2++)
8916
- yield { entity, row: parseJson(JSON.stringify(listed[index2])), where: `${entity}[${index2}]` };
9508
+ yield {
9509
+ entity,
9510
+ row: parseJson(JSON.stringify(listed[index2])),
9511
+ where: `${entity}[${index2}]`
9512
+ };
8917
9513
  })();
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);
9514
+ const chunks = buildChunks(tagged, {
9515
+ chunkBytes: opts.chunkBytes ?? DEFAULT_CHUNK_BYTES,
9516
+ chunkRows: null,
9517
+ entity: null
8921
9518
  });
9519
+ await forEachLimited(
9520
+ chunks,
9521
+ Math.max(1, opts.parallel ?? 4),
9522
+ async (chunk) => {
9523
+ await client2.upload(opened.batchId, chunk);
9524
+ }
9525
+ );
8922
9526
  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;
9527
+ return waitForBatch(client2, opened.batchId, {
9528
+ initialDelayMs: worldDataPollMs()
9529
+ });
8928
9530
  }
8929
9531
  var init_push = __esm({
8930
9532
  "src/cli/platform/worldData/push.ts"() {
@@ -9173,12 +9775,12 @@ var init_ingest = __esm({
9173
9775
  });
9174
9776
 
9175
9777
  // src/worlds/editSessions.ts
9176
- var WORLDS, WorldEditClient, TASK_EDITS, TaskEditClient;
9778
+ var WORLDS2, WorldEditClient, TASK_EDITS, TaskEditClient;
9177
9779
  var init_editSessions = __esm({
9178
9780
  "src/worlds/editSessions.ts"() {
9179
9781
  "use strict";
9180
9782
  init_worlds();
9181
- WORLDS = "/api/public/worlds";
9783
+ WORLDS2 = "/api/public/worlds";
9182
9784
  WorldEditClient = class {
9183
9785
  constructor(options = {}) {
9184
9786
  this.options = options;
@@ -9190,19 +9792,19 @@ var init_editSessions = __esm({
9190
9792
  if (query.status) qs3.set("status", query.status);
9191
9793
  if (query.limit !== void 0) qs3.set("limit", String(query.limit));
9192
9794
  const suffix = qs3.size ? `?${qs3.toString()}` : "";
9193
- return apiRequest(this.options, "GET", `${WORLDS}/${encodeURIComponent(slug)}/edits${suffix}`);
9795
+ return apiRequest(this.options, "GET", `${WORLDS2}/${encodeURIComponent(slug)}/edits${suffix}`);
9194
9796
  }
9195
9797
  /** Seal a session into a version on main (the credential's current one when `sessionId` is omitted). */
9196
9798
  close(slug, input = {}) {
9197
- return apiRequest(this.options, "POST", `${WORLDS}/${encodeURIComponent(slug)}/edits/close`, input);
9799
+ return apiRequest(this.options, "POST", `${WORLDS2}/${encodeURIComponent(slug)}/edits/close`, input);
9198
9800
  }
9199
9801
  /** Drop the session's private branch without making a version. */
9200
9802
  discard(slug, input = {}) {
9201
- return apiRequest(this.options, "POST", `${WORLDS}/${encodeURIComponent(slug)}/edits/discard`, input);
9803
+ return apiRequest(this.options, "POST", `${WORLDS2}/${encodeURIComponent(slug)}/edits/discard`, input);
9202
9804
  }
9203
9805
  /** Undo a sealed session (source and data) as a new sealed session. */
9204
9806
  rollback(slug, input) {
9205
- return apiRequest(this.options, "POST", `${WORLDS}/${encodeURIComponent(slug)}/edits/rollback`, input);
9807
+ return apiRequest(this.options, "POST", `${WORLDS2}/${encodeURIComponent(slug)}/edits/rollback`, input);
9206
9808
  }
9207
9809
  };
9208
9810
  TASK_EDITS = "/api/public/world-task-edits";
@@ -9356,15 +9958,27 @@ __export(worlds_exports, {
9356
9958
  NativeComputer: () => NativeComputer,
9357
9959
  OpenAIComputer: () => OpenAIComputer,
9358
9960
  OpenAIPreviewComputer: () => OpenAIPreviewComputer,
9961
+ PLATFORM_SESSION_HEADER: () => PLATFORM_SESSION_HEADER,
9359
9962
  PLATFORM_TIMEOUT_DEFAULT_MS: () => PLATFORM_TIMEOUT_DEFAULT_MS,
9360
9963
  PLATFORM_TIMEOUT_ENV: () => PLATFORM_TIMEOUT_ENV,
9361
9964
  PendingSafetyChecks: () => PendingSafetyChecks,
9362
9965
  PlatformTransport: () => PlatformTransport,
9363
9966
  PushSlugConflict: () => PushSlugConflict,
9364
9967
  RECOVER_BUDGET_MS: () => RECOVER_BUDGET_MS,
9968
+ REQUESTS_NOT_RECORDED: () => REQUESTS_NOT_RECORDED,
9969
+ REQUEST_BODY_CAPTURE_BYTES: () => REQUEST_BODY_CAPTURE_BYTES,
9970
+ REQUEST_LOG_PAGE_MAX: () => REQUEST_LOG_PAGE_MAX,
9365
9971
  RetryPolicy: () => RetryPolicy,
9972
+ SANDBOX_EXEC_REPORT_MARGIN_MS: () => SANDBOX_EXEC_REPORT_MARGIN_MS,
9973
+ SANDBOX_EXEC_START_ATTEMPTS: () => SANDBOX_EXEC_START_ATTEMPTS,
9974
+ SANDBOX_EXEC_TIMEOUT_MAX_S: () => SANDBOX_EXEC_TIMEOUT_MAX_S,
9975
+ SANDBOX_EXEC_WAIT_MS: () => SANDBOX_EXEC_WAIT_MS,
9976
+ SANDBOX_FILE_MAX_BYTES: () => SANDBOX_FILE_MAX_BYTES,
9366
9977
  SANDBOX_REQUEST_TIMEOUT_MS: () => SANDBOX_REQUEST_TIMEOUT_MS,
9978
+ SANDBOX_WRITE_CHUNK_BYTES: () => SANDBOX_WRITE_CHUNK_BYTES,
9979
+ SANDBOX_WRITE_SKIPPED: () => SANDBOX_WRITE_SKIPPED,
9367
9980
  SECRET_KEY: () => SECRET_KEY,
9981
+ SESSION_AUTH_MODES: () => SESSION_AUTH_MODES,
9368
9982
  SESSION_STATES: () => SESSION_STATES,
9369
9983
  SPAN_PREFIX: () => SPAN_PREFIX,
9370
9984
  STATUS_WAIT_CAP_SECONDS: () => STATUS_WAIT_CAP_SECONDS,
@@ -9376,17 +9990,24 @@ __export(worlds_exports, {
9376
9990
  TOOL_CONTRACT_UNREAD: () => TOOL_CONTRACT_UNREAD,
9377
9991
  TRANSFORMS: () => TRANSFORMS,
9378
9992
  TaskEditClient: () => TaskEditClient,
9993
+ TaskGrades: () => TaskGrades,
9379
9994
  TaskRun: () => TaskRun,
9380
9995
  TaskSessions: () => TaskSessions,
9381
9996
  TransportCause: () => TransportCause,
9382
9997
  UnreachableError: () => UnreachableError,
9383
9998
  VERIFIER_REWARD_PREFIX: () => VERIFIER_REWARD_PREFIX,
9384
9999
  WHITESPACE: () => WHITESPACE,
10000
+ WORLD_REQUEST_VIAS: () => WORLD_REQUEST_VIAS,
10001
+ WORLD_WEBHOOK_PAGE_MAX: () => WORLD_WEBHOOK_PAGE_MAX,
9385
10002
  WorldBrowser: () => WorldBrowser,
9386
10003
  WorldCallTooLarge: () => WorldCallTooLarge,
9387
10004
  WorldEditClient: () => WorldEditClient,
9388
10005
  WorldNotice: () => WorldNotice,
10006
+ WorldRequestFilterError: () => WorldRequestFilterError,
10007
+ WorldRequestLedger: () => WorldRequestLedger,
9389
10008
  WorldRequestLog: () => WorldRequestLog,
10009
+ WorldRequestQuery: () => WorldRequestQuery,
10010
+ WorldRequestsNotRecorded: () => WorldRequestsNotRecorded,
9390
10011
  WorldSandboxClient: () => WorldSandboxClient,
9391
10012
  WorldSession: () => WorldSession,
9392
10013
  WorldSessionCallError: () => WorldSessionCallError,
@@ -9396,18 +10017,23 @@ __export(worlds_exports, {
9396
10017
  WorldSurfaceUnavailable: () => WorldSurfaceUnavailable,
9397
10018
  WorldTask: () => WorldTask,
9398
10019
  WorldToolsUnread: () => WorldToolsUnread,
10020
+ WorldWebhookForwarder: () => WorldWebhookForwarder,
10021
+ WriteTreeFilter: () => WriteTreeFilter,
9399
10022
  aggregateTaskGrade: () => aggregateTaskGrade,
9400
10023
  apiRequest: () => apiRequest,
9401
10024
  applyTransforms: () => applyTransforms,
9402
10025
  archiveMode: () => archiveMode,
9403
10026
  assertBrowserTier: () => assertBrowserTier,
10027
+ assertSessionAuthMode: () => assertSessionAuthMode,
9404
10028
  assertTaskRef: () => assertTaskRef,
9405
10029
  attachManifest: () => attachManifest,
9406
10030
  attachSession: () => attachSession,
9407
10031
  attachTask: () => attachTask,
9408
10032
  buildFileManifest: () => buildFileManifest,
9409
10033
  buildSourceTarball: () => buildSourceTarball,
10034
+ capabilityLabel: () => capabilityLabel,
9410
10035
  captureToolCalls: () => captureToolCalls,
10036
+ carriedWarnings: () => carriedWarnings,
9411
10037
  checkoutIdentity: () => checkoutIdentity,
9412
10038
  closeConnection: () => closeConnection,
9413
10039
  collectArchiveRelPaths: () => collectArchiveRelPaths,
@@ -9426,7 +10052,9 @@ __export(worlds_exports, {
9426
10052
  idleWarning: () => idleWarning,
9427
10053
  ingest: () => ingest,
9428
10054
  ingestToolCalls: () => ingestToolCalls,
10055
+ invalidFields: () => invalidFields,
9429
10056
  isBrowserGone: () => isBrowserGone,
10057
+ isSandboxCommitPending: () => isSandboxCommitPending,
9430
10058
  isSandboxImportPending: () => isSandboxImportPending,
9431
10059
  isTaskIdRef: () => isTaskIdRef,
9432
10060
  isTaskManifest: () => isTaskManifest,
@@ -9437,6 +10065,7 @@ __export(worlds_exports, {
9437
10065
  listSessions: () => listSessions,
9438
10066
  listTaskSessions: () => listTaskSessions,
9439
10067
  listTasks: () => listTasks,
10068
+ listWebhooks: () => listWebhooks,
9440
10069
  localTreeState: () => localTreeState,
9441
10070
  messageOf: () => messageOf,
9442
10071
  migrateProjectWorlds: () => migrateProjectWorlds,
@@ -9473,6 +10102,7 @@ __export(worlds_exports, {
9473
10102
  resolveBrowserMode: () => resolveBrowserMode,
9474
10103
  resolvePushSlug: () => resolvePushSlug,
9475
10104
  roundForm: () => roundForm,
10105
+ rowsRefusal: () => rowsRefusal,
9476
10106
  runSessions: () => runSessions,
9477
10107
  runSet: () => runSet,
9478
10108
  runTask: () => runTask,
@@ -9501,27 +10131,42 @@ __export(worlds_exports, {
9501
10131
  validateWorld: () => validateWorld,
9502
10132
  waitForRun: () => waitForRun,
9503
10133
  withoutUiToken: () => withoutUiToken,
10134
+ worldRequestsUnrecorded: () => worldRequestsUnrecorded,
9504
10135
  writeLocalMeta: () => writeLocalMeta
9505
10136
  });
9506
- function parseErrorBody(text2, limit = 600) {
9507
- const raw = { detail: text2.slice(0, limit), code: null };
10137
+ function edgeAnswer(text2, status) {
10138
+ if (status !== void 0 && status >= 500) return EDGE_ANSWERS[status] ?? EDGE_FAILURE;
10139
+ return /^\s*</.test(text2) ? EDGE_PAGE : null;
10140
+ }
10141
+ function parseErrorBody(text2, status) {
10142
+ const raw = { detail: text2.slice(0, DETAIL_LIMIT), code: null };
9508
10143
  let parsed;
9509
10144
  try {
9510
10145
  parsed = JSON.parse(text2);
9511
10146
  } catch {
9512
- return raw;
10147
+ return { detail: (edgeAnswer(text2, status) ?? text2).slice(0, DETAIL_LIMIT), code: null };
9513
10148
  }
9514
10149
  if (parsed === null || typeof parsed !== "object") return raw;
9515
- const { message, code } = parsed;
10150
+ const { message, code, error } = parsed;
9516
10151
  const stableCode = typeof code === "string" ? code : null;
9517
10152
  if (typeof message !== "string") return { ...raw, code: stableCode };
9518
- if (stableCode === null)
9519
- return { detail: message.slice(0, limit), code: null };
10153
+ const fields = invalidFields(error);
10154
+ const said = fields ? `${message}: ${fields}` : message;
10155
+ if (stableCode === null) return { detail: said.slice(0, DETAIL_LIMIT), code: null };
9520
10156
  return {
9521
- detail: `${message} (${stableCode})`.slice(0, limit),
10157
+ detail: `${said} (${stableCode})`.slice(0, DETAIL_LIMIT),
9522
10158
  code: stableCode
9523
10159
  };
9524
10160
  }
10161
+ function invalidFields(error) {
10162
+ const issues = Array.isArray(error) ? error : [];
10163
+ return issues.filter(
10164
+ (issue) => issue !== null && typeof issue === "object" && typeof issue.message === "string"
10165
+ ).map((issue) => {
10166
+ const path17 = Array.isArray(issue.path) ? issue.path.map(String).join(".") : "";
10167
+ return path17 ? `${path17}: ${issue.message}` : issue.message;
10168
+ }).join("; ");
10169
+ }
9525
10170
  async function apiRequest(options, method, path17, body, init3 = {}) {
9526
10171
  const reply = await new PlatformTransport(requirePlatformEndpoint(options)).send(method, path17, body, init3);
9527
10172
  if (!reply.ok) throw new ApiError(reply.status, method, path17, reply.text);
@@ -9700,7 +10345,7 @@ async function resolveWorld(slugRef, slug, ref, pin, options) {
9700
10345
  }
9701
10346
  return world;
9702
10347
  }
9703
- var ApiError, WorldTask, WorldSet;
10348
+ var ApiError, DETAIL_LIMIT, EDGE_ANSWERS, EDGE_FAILURE, EDGE_PAGE, WorldTask, WorldSet;
9704
10349
  var init_worlds = __esm({
9705
10350
  "src/worlds/index.ts"() {
9706
10351
  "use strict";
@@ -9713,6 +10358,7 @@ var init_worlds = __esm({
9713
10358
  init_sessionContract();
9714
10359
  init_taskRef();
9715
10360
  init_tasks();
10361
+ init_taskGrades();
9716
10362
  init_taskSessions();
9717
10363
  init_taskRun();
9718
10364
  init_setRun();
@@ -9721,6 +10367,8 @@ var init_worlds = __esm({
9721
10367
  init_browser();
9722
10368
  init_surfaceDescriptor();
9723
10369
  init_requestLog();
10370
+ init_requestLedger();
10371
+ init_webhooks();
9724
10372
  init_browserReconnect();
9725
10373
  init_nativeComputer();
9726
10374
  init_hub();
@@ -9737,7 +10385,7 @@ var init_worlds = __esm({
9737
10385
  init_worldNotice();
9738
10386
  ApiError = class extends Error {
9739
10387
  constructor(status, method, path17, text2) {
9740
- const parsed = parseErrorBody(text2);
10388
+ const parsed = parseErrorBody(text2, status);
9741
10389
  super(`${method} ${path17} -> ${status}: ${parsed.detail}`);
9742
10390
  this.status = status;
9743
10391
  this.text = text2;
@@ -9748,6 +10396,14 @@ var init_worlds = __esm({
9748
10396
  text;
9749
10397
  code;
9750
10398
  };
10399
+ DETAIL_LIMIT = 600;
10400
+ EDGE_ANSWERS = {
10401
+ 502: "Bad Gateway from the load balancer in front of the platform, not the platform's answer: the web server dropped the connection or restarted mid-request. Retry; if it repeats, the platform is restarting or overloaded.",
10402
+ 503: "Service Unavailable from the load balancer in front of the platform, not the platform's answer: no web server was ready to take the request (a deploy or a restart). Retry in a minute.",
10403
+ 504: "Gateway Time-out from the load balancer in front of the platform, not the platform's answer: the request sent nothing back within the load balancer's idle timeout (60 s unless the deployment raises it: Helm ingress.idleTimeoutSeconds) and was cut there, though the platform may still be running it. Check what it changed before you retry."
10404
+ };
10405
+ EDGE_FAILURE = "The platform failed without its JSON error body: a proxy in front of it answered, or the server stopped before its error handler ran. Retry; if it repeats, report the request and the time.";
10406
+ EDGE_PAGE = "An HTML page answered instead of the platform's JSON: a proxy in front of the platform, or the configured host is not the platform.";
9751
10407
  WorldTask = class {
9752
10408
  constructor(world, name, variant) {
9753
10409
  this.world = world;
@@ -9783,12 +10439,7 @@ var init_worlds = __esm({
9783
10439
  }
9784
10440
  return hit;
9785
10441
  }
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
- */
10442
+ /** Open a live session on a bundled task's name or an inline `WorldTaskSpec`; the platform boots or reuses a warm container. */
9792
10443
  async open(task, opts = {}) {
9793
10444
  const { openSession: openSession2 } = await Promise.resolve().then(() => (init_session2(), session_exports2));
9794
10445
  return openSession2(this.slug, {
@@ -9800,11 +10451,7 @@ var init_worlds = __esm({
9800
10451
  options: this.options
9801
10452
  });
9802
10453
  }
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
- */
10454
+ /** Start a hosted run of a run config on this version (or `opts.versionId`): one graded run per model, provenance detected unless given. */
9808
10455
  async dispatch(runConfigId, opts = {}) {
9809
10456
  const provenance = opts.provenance ?? detectProvenance();
9810
10457
  return apiRequest(
@@ -12242,7 +12889,7 @@ __export(files_exports, {
12242
12889
  uploadFile: () => uploadFile
12243
12890
  });
12244
12891
  init_worlds();
12245
- import { createHash as createHash10 } from "crypto";
12892
+ import { createHash as createHash11 } from "crypto";
12246
12893
  import * as fs13 from "fs";
12247
12894
  import * as path13 from "path";
12248
12895
  import { Readable, Transform } from "stream";
@@ -12307,7 +12954,7 @@ async function confirmUpload(options = {}, fileId, ok = true) {
12307
12954
  return apiRequest(options, "POST", `${BASE}/confirm`, { fileId, ok });
12308
12955
  }
12309
12956
  async function sha256Base64(localPath) {
12310
- const hash = createHash10("sha256");
12957
+ const hash = createHash11("sha256");
12311
12958
  for await (const chunk of fs13.createReadStream(localPath)) hash.update(chunk);
12312
12959
  return hash.digest("base64");
12313
12960
  }
@@ -12392,7 +13039,7 @@ async function uploadBytes(options = {}, bytes, targetPath, upload = {}) {
12392
13039
  if (!bytes.length) throw new Error("nothing to upload: the content is empty");
12393
13040
  const target = drivePath(targetPath);
12394
13041
  const contentType = upload.contentType ?? contentTypeFor(target);
12395
- const sha2562 = createHash10("sha256").update(bytes).digest("base64");
13042
+ const sha2562 = createHash11("sha256").update(bytes).digest("base64");
12396
13043
  const granted = await requestUpload(options, { path: target, contentLength: bytes.length, contentType, sha256: sha2562, ...upload.overwrite ? { overwrite: true } : {} });
12397
13044
  try {
12398
13045
  await putPresigned(granted.uploadUrl, new Uint8Array(bytes), { contentType, contentLength: bytes.length, sha256: sha2562 });
@@ -12645,10 +13292,10 @@ function swapValue(text2, needle, replacement) {
12645
13292
  }
12646
13293
 
12647
13294
  // src/hooks/standInDigits.ts
12648
- import { createHash as createHash11 } from "crypto";
13295
+ import { createHash as createHash12 } from "crypto";
12649
13296
  function standInDigits(realDigits, identityName) {
12650
13297
  if (!realDigits) return "";
12651
- const digest = createHash11("sha256").update(`${identityName}:${realDigits}`).digest("hex");
13298
+ const digest = createHash12("sha256").update(`${identityName}:${realDigits}`).digest("hex");
12652
13299
  let digits = "";
12653
13300
  for (let i = 0; i < realDigits.length; i++)
12654
13301
  digits += String(parseInt(digest[i % digest.length], 16) % 10);
@@ -12682,7 +13329,7 @@ var DeclaredStandIn = class _DeclaredStandIn {
12682
13329
  };
12683
13330
 
12684
13331
  // src/hooks/alias.ts
12685
- import { createHash as createHash12, createHmac, randomBytes as randomBytes2 } from "crypto";
13332
+ import { createHash as createHash13, createHmac, randomBytes as randomBytes2 } from "crypto";
12686
13333
  var GIVEN = [
12687
13334
  "John",
12688
13335
  "Mary",
@@ -13503,9 +14150,9 @@ var AliasMap = class _AliasMap {
13503
14150
  });
13504
14151
  if (alias.role === "private") {
13505
14152
  for (const slug of this.slugs) {
13506
- const standIn = "sha256:" + createHash12("sha256").update(`${slug}:${canonical(alias.kind, alias.display)}`, "utf8").digest("hex");
14153
+ const standIn = "sha256:" + createHash13("sha256").update(`${slug}:${canonical(alias.kind, alias.display)}`, "utf8").digest("hex");
13507
14154
  alias.variants.push([
13508
- "sha256:" + createHash12("sha256").update(`${slug}:${alias.canonical}`, "utf8").digest("hex"),
14155
+ "sha256:" + createHash13("sha256").update(`${slug}:${alias.canonical}`, "utf8").digest("hex"),
13509
14156
  standIn
13510
14157
  ]);
13511
14158
  this.aliasDigests.add(standIn.toLowerCase());
@@ -15522,6 +16169,120 @@ async function buildHandler(spec, aliases, opts) {
15522
16169
  // src/hooks/live.ts
15523
16170
  import * as fs16 from "fs";
15524
16171
  import * as path15 from "path";
16172
+
16173
+ // src/hooks/vendorAuth.ts
16174
+ var bearer = (auth, value) => ({
16175
+ headers: { authorization: `${prefixesOf(auth)[0]} ${value}` },
16176
+ query: []
16177
+ });
16178
+ var CARRIERS = /* @__PURE__ */ new Map([
16179
+ [
16180
+ "header",
16181
+ (auth, value) => ({
16182
+ headers: {
16183
+ [String(auth.name ?? "").trim().toLowerCase()]: value
16184
+ },
16185
+ query: []
16186
+ })
16187
+ ],
16188
+ ["bearer", bearer],
16189
+ [
16190
+ "basic",
16191
+ (auth, value) => ({
16192
+ headers: {
16193
+ authorization: `Basic ${Buffer.from(basicPair(auth, value)).toString("base64")}`
16194
+ },
16195
+ query: []
16196
+ })
16197
+ ],
16198
+ [
16199
+ "query",
16200
+ (auth, value) => ({
16201
+ headers: {},
16202
+ query: [[String(auth.name ?? "").trim(), value]]
16203
+ })
16204
+ ],
16205
+ ["oauth2", bearer],
16206
+ ["none", () => ({ headers: {}, query: [] })]
16207
+ ]);
16208
+ var AUTH_WORD = /^[A-Za-z0-9!#$%&'*+.^_`|~-]{1,64}$/;
16209
+ var OWNERS = [
16210
+ ["client_id_env", ["oauth2"]],
16211
+ ["credential", ["basic"]],
16212
+ ["prefixes", ["bearer", "oauth2"]],
16213
+ ["scope", ["oauth2"]],
16214
+ ["token_url", ["oauth2"]],
16215
+ ["ttl_seconds", ["oauth2"]]
16216
+ ];
16217
+ var AUTH_MODES = ["vendor", "open"];
16218
+ var positiveSeconds = (value) => typeof value === "number" && Number.isInteger(value) && value >= 1;
16219
+ var NAMED = /* @__PURE__ */ new Set(["header", "query"]);
16220
+ function prefixesOf(auth) {
16221
+ const words2 = auth.prefixes ?? ["Bearer"];
16222
+ 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;
16223
+ if (!valid)
16224
+ throw new Error(
16225
+ "auth.prefixes lists the distinct words the vendor takes before the key in Authorization"
16226
+ );
16227
+ return words2;
16228
+ }
16229
+ function basicHalf(auth) {
16230
+ const half = auth.credential ?? "user";
16231
+ if (half !== "user" && half !== "password")
16232
+ throw new Error(
16233
+ "auth.credential is the half of the Basic pair the key is: user or password"
16234
+ );
16235
+ return half;
16236
+ }
16237
+ function basicPair(auth, value) {
16238
+ if (value.includes(":")) return value;
16239
+ return basicHalf(auth) === "password" ? `:${value}` : `${value}:`;
16240
+ }
16241
+ var GRAMMAR = /* @__PURE__ */ new Map([
16242
+ ["bearer", prefixesOf],
16243
+ ["oauth2", prefixesOf],
16244
+ ["basic", basicHalf]
16245
+ ]);
16246
+ function authScheme(value) {
16247
+ if (value === void 0) throw new Error("Missing scheme");
16248
+ if (value === "open")
16249
+ throw new Error(
16250
+ 'auth.scheme is how the vendor takes its key; a world whose sessions ask for none is auth.mode = "open"'
16251
+ );
16252
+ if (typeof value !== "string" || !CARRIERS.has(value))
16253
+ throw new Error(
16254
+ `auth.scheme must be one of ${[...CARRIERS.keys()].join(", ")}`
16255
+ );
16256
+ return value;
16257
+ }
16258
+ function vendorAuth(auth) {
16259
+ const scheme = authScheme(auth.scheme);
16260
+ const stray = OWNERS.find(
16261
+ ([key2, owners]) => auth[key2] !== void 0 && !owners.includes(scheme)
16262
+ );
16263
+ if (stray)
16264
+ throw new Error(
16265
+ `${stray[0]} belongs to auth.scheme ${stray[1].join(" or ")}`
16266
+ );
16267
+ if (scheme === "none" && (auth.name ?? auth.secret_env) !== void 0)
16268
+ throw new Error("auth.scheme none takes no name or secret_env");
16269
+ if (NAMED.has(scheme) && auth.name === void 0)
16270
+ throw new Error("Missing name");
16271
+ if (auth.name !== void 0 && (typeof auth.name !== "string" || !auth.name.trim()))
16272
+ throw new Error("name must be a non-empty string");
16273
+ GRAMMAR.get(scheme)?.(auth);
16274
+ if (auth.mode !== void 0 && !AUTH_MODES.includes(auth.mode))
16275
+ throw new Error(`auth.mode is one of ${AUTH_MODES.join(", ")}`);
16276
+ if (auth.ttl_seconds !== void 0 && !positiveSeconds(auth.ttl_seconds))
16277
+ throw new Error("ttl_seconds is a positive whole number of seconds");
16278
+ return { ...auth, scheme };
16279
+ }
16280
+ function carryCredential(auth, value) {
16281
+ const checked = vendorAuth(auth);
16282
+ return CARRIERS.get(checked.scheme)(checked, value);
16283
+ }
16284
+
16285
+ // src/hooks/live.ts
15525
16286
  var USER_AGENT = "gateway-hooks/1 (+https://withgateway.ai)";
15526
16287
  var TAGS = /<(script|style)[^>]*>.*?<\/\1>/gis;
15527
16288
  var STRIP = /<[^>]+>/g;
@@ -15842,7 +16603,9 @@ var HttpTool = class _HttpTool {
15842
16603
  const okStatus = o.ok_status ?? [
15843
16604
  [200, 200]
15844
16605
  ];
15845
- if (!okStatus.some(([low, high]) => response.status >= low && response.status <= high)) {
16606
+ if (!okStatus.some(
16607
+ ([low, high]) => response.status >= low && response.status <= high
16608
+ )) {
15846
16609
  const expected = okStatus.map(([low, high]) => low === high ? String(low) : `${low}-${high}`).join(", ");
15847
16610
  throw new LiveToolError(
15848
16611
  `${this.spec.name}: ${url} answered HTTP ${response.status} (ok_status ${expected}): ${JSON.stringify(body.slice(0, 200))}`,
@@ -15893,7 +16656,8 @@ function readConnection(root) {
15893
16656
  if (!fs16.existsSync(file)) throw new Error(`no connector.toml at ${root}`);
15894
16657
  const raw = parseToml(fs16.readFileSync(file, "utf8"));
15895
16658
  const connector = raw.connector ?? {};
15896
- const auth = raw.auth ?? {};
16659
+ const auth = raw.auth ?? { scheme: "none" };
16660
+ const carrier = vendorAuth(auth);
15897
16661
  const operations = {};
15898
16662
  for (const op of raw.operations ?? []) {
15899
16663
  operations[op.name] = {
@@ -15907,8 +16671,8 @@ function readConnection(root) {
15907
16671
  return {
15908
16672
  slug: connector.slug ?? path15.basename(root),
15909
16673
  baseUrl: (connector.base_url ?? "").replace(/\/+$/, ""),
15910
- scheme: auth.scheme ?? "none",
15911
- ...typeof auth.name === "string" ? { authName: auth.name } : {},
16674
+ scheme: carrier.scheme,
16675
+ carrier,
15912
16676
  ...typeof auth.secret_env === "string" ? { secretEnv: auth.secret_env } : {},
15913
16677
  ...typeof auth.client_id_env === "string" ? { clientIdEnv: auth.client_id_env } : {},
15914
16678
  ...typeof auth.token_url === "string" ? { tokenUrl: auth.token_url } : {},
@@ -16020,13 +16784,9 @@ var ConnectorTool = class {
16020
16784
  };
16021
16785
  for (const [header, variable] of Object.entries(c.extraHeaders))
16022
16786
  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 ?? "");
16787
+ const carried2 = carryCredential(c.carrier, await this.credential() ?? "");
16788
+ Object.assign(headers, carried2.headers);
16789
+ for (const [key2, value] of carried2.query) query.append(key2, value);
16030
16790
  const url = c.baseUrl + pathText + (query.toString() ? `?${query.toString()}` : "");
16031
16791
  const response = await fetch(url, {
16032
16792
  method: this.operation.method,
@@ -17556,6 +18316,7 @@ export {
17556
18316
  NativeComputer,
17557
18317
  OpenAIComputer,
17558
18318
  OpenAIPreviewComputer,
18319
+ PLATFORM_SESSION_HEADER,
17559
18320
  PLATFORM_TIMEOUT_DEFAULT_MS,
17560
18321
  PLATFORM_TIMEOUT_ENV,
17561
18322
  PendingSafetyChecks,
@@ -17566,6 +18327,9 @@ export {
17566
18327
  PushSlugConflict,
17567
18328
  RECOVER_BUDGET_MS,
17568
18329
  REPLAY_ENVIRONMENT,
18330
+ REQUESTS_NOT_RECORDED,
18331
+ REQUEST_BODY_CAPTURE_BYTES,
18332
+ REQUEST_LOG_PAGE_MAX,
17569
18333
  ReplayCase,
17570
18334
  ReplayCheck,
17571
18335
  ReplayError,
@@ -17573,8 +18337,16 @@ export {
17573
18337
  ReplaySuite,
17574
18338
  ReplayTask,
17575
18339
  RetryPolicy,
18340
+ SANDBOX_EXEC_REPORT_MARGIN_MS,
18341
+ SANDBOX_EXEC_START_ATTEMPTS,
18342
+ SANDBOX_EXEC_TIMEOUT_MAX_S,
18343
+ SANDBOX_EXEC_WAIT_MS,
18344
+ SANDBOX_FILE_MAX_BYTES,
17576
18345
  SANDBOX_REQUEST_TIMEOUT_MS,
18346
+ SANDBOX_WRITE_CHUNK_BYTES,
18347
+ SANDBOX_WRITE_SKIPPED,
17577
18348
  SECRET_KEY,
18349
+ SESSION_AUTH_MODES,
17578
18350
  SESSION_STATES,
17579
18351
  SPAN_PREFIX,
17580
18352
  STATUS_WAIT_CAP_SECONDS,
@@ -17594,6 +18366,7 @@ export {
17594
18366
  TOOL_CONTRACT_UNREAD,
17595
18367
  TRANSFORMS,
17596
18368
  TaskEditClient,
18369
+ TaskGrades,
17597
18370
  TaskRun,
17598
18371
  TaskSessions,
17599
18372
  ToolStubRegistry,
@@ -17604,11 +18377,17 @@ export {
17604
18377
  UsersClient,
17605
18378
  VERIFIER_REWARD_PREFIX,
17606
18379
  WHITESPACE,
18380
+ WORLD_REQUEST_VIAS,
18381
+ WORLD_WEBHOOK_PAGE_MAX,
17607
18382
  WorldBrowser,
17608
18383
  WorldCallTooLarge,
17609
18384
  WorldEditClient,
17610
18385
  WorldNotice,
18386
+ WorldRequestFilterError,
18387
+ WorldRequestLedger,
17611
18388
  WorldRequestLog,
18389
+ WorldRequestQuery,
18390
+ WorldRequestsNotRecorded,
17612
18391
  WorldSandboxClient,
17613
18392
  WorldSession,
17614
18393
  WorldSessionCallError,
@@ -17618,6 +18397,8 @@ export {
17618
18397
  WorldSurfaceUnavailable,
17619
18398
  WorldTask,
17620
18399
  WorldToolsUnread,
18400
+ WorldWebhookForwarder,
18401
+ WriteTreeFilter,
17621
18402
  addExperimentAttributes,
17622
18403
  aggregateTaskGrade,
17623
18404
  apiRequest,
@@ -17625,6 +18406,7 @@ export {
17625
18406
  archiveMode,
17626
18407
  assembleManifest,
17627
18408
  assertBrowserTier,
18409
+ assertSessionAuthMode,
17628
18410
  assertTaskRef,
17629
18411
  assignVariant,
17630
18412
  attachManifest,
@@ -17634,7 +18416,9 @@ export {
17634
18416
  buildFileManifest,
17635
18417
  buildSourceTarball,
17636
18418
  canonicalJson,
18419
+ capabilityLabel,
17637
18420
  captureToolCalls,
18421
+ carriedWarnings,
17638
18422
  checkoutIdentity,
17639
18423
  clearExperimentContext,
17640
18424
  closeConnection,
@@ -17670,7 +18454,9 @@ export {
17670
18454
  idleWarning,
17671
18455
  ingest,
17672
18456
  ingestToolCalls,
18457
+ invalidFields,
17673
18458
  isBrowserGone,
18459
+ isSandboxCommitPending,
17674
18460
  isSandboxImportPending,
17675
18461
  isTaskIdRef,
17676
18462
  isTaskManifest,
@@ -17681,6 +18467,7 @@ export {
17681
18467
  listSessions,
17682
18468
  listTaskSessions,
17683
18469
  listTasks,
18470
+ listWebhooks,
17684
18471
  loadSession,
17685
18472
  localTreeState,
17686
18473
  memory,
@@ -17727,6 +18514,7 @@ export {
17727
18514
  resolvePushSlug,
17728
18515
  resolveUserId,
17729
18516
  roundForm,
18517
+ rowsRefusal,
17730
18518
  runSessions,
17731
18519
  runSet,
17732
18520
  runSuite,
@@ -17766,6 +18554,7 @@ export {
17766
18554
  validateWorld,
17767
18555
  waitForRun,
17768
18556
  withoutUiToken,
18557
+ worldRequestsUnrecorded,
17769
18558
  writeLocalMeta
17770
18559
  };
17771
18560
  //# sourceMappingURL=index.mjs.map