@withgateway/sdk 0.3.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (176) hide show
  1. package/README.md +8 -6
  2. package/dist/cli.js +4372 -2265
  3. package/dist/cli.js.map +1 -1
  4. package/dist/cli.mjs +4362 -2256
  5. package/dist/cli.mjs.map +1 -1
  6. package/dist/files/index.d.mts +1 -1
  7. package/dist/files/index.d.ts +1 -1
  8. package/dist/files/index.js +259 -58
  9. package/dist/files/index.js.map +1 -1
  10. package/dist/files/index.mjs +249 -50
  11. package/dist/files/index.mjs.map +1 -1
  12. package/dist/hooks/index.d.mts +1 -1
  13. package/dist/hooks/index.d.ts +1 -1
  14. package/dist/hooks/index.js +124 -11
  15. package/dist/hooks/index.js.map +1 -1
  16. package/dist/hooks/index.mjs +124 -11
  17. package/dist/hooks/index.mjs.map +1 -1
  18. package/dist/{index-C3UzD0G3.d.mts → index-CDPQBsU5.d.mts} +19 -3
  19. package/dist/{index-C3UzD0G3.d.ts → index-CDPQBsU5.d.ts} +19 -3
  20. package/dist/{index-CBqbB_0J.d.ts → index-DUHmS74p.d.ts} +1 -1
  21. package/dist/{index-D-AMnAMa.d.mts → index-mJhG3vZU.d.mts} +1 -1
  22. package/dist/index.d.mts +5 -5
  23. package/dist/index.d.ts +5 -5
  24. package/dist/index.js +2240 -789
  25. package/dist/index.js.map +1 -1
  26. package/dist/index.mjs +2150 -739
  27. package/dist/index.mjs.map +1 -1
  28. package/dist/{media-CbcAfQvd.d.mts → media-BIApiPzS.d.mts} +21 -2
  29. package/dist/{media-CbcAfQvd.d.ts → media-BIApiPzS.d.ts} +21 -2
  30. package/dist/traces/index.d.mts +1 -1
  31. package/dist/traces/index.d.ts +1 -1
  32. package/dist/traces/index.js +253 -52
  33. package/dist/traces/index.js.map +1 -1
  34. package/dist/traces/index.mjs +243 -44
  35. package/dist/traces/index.mjs.map +1 -1
  36. package/dist/tracing/index.d.mts +2 -2
  37. package/dist/tracing/index.d.ts +2 -2
  38. package/dist/tracing/index.js +75 -13
  39. package/dist/tracing/index.js.map +1 -1
  40. package/dist/tracing/index.mjs +75 -13
  41. package/dist/tracing/index.mjs.map +1 -1
  42. package/dist/worlds/index.d.mts +893 -482
  43. package/dist/worlds/index.d.ts +893 -482
  44. package/dist/worlds/index.js +1968 -669
  45. package/dist/worlds/index.js.map +1 -1
  46. package/dist/worlds/index.mjs +1960 -662
  47. package/dist/worlds/index.mjs.map +1 -1
  48. package/package.json +1 -1
  49. package/runtime/gatewaysdk/environment/_bundle.py +2 -27
  50. package/runtime/gatewaysdk/environment/_materialize.py +48 -88
  51. package/runtime/gatewaysdk/environment/_world.py +155 -237
  52. package/runtime/gatewaysdk/environment/backing.py +133 -0
  53. package/runtime/gatewaysdk/environment/core.py +2 -17
  54. package/runtime/gatewaysdk/environment/legacy_sqlite.py +288 -0
  55. package/runtime/gatewaysdk/environment/reward_keys.py +25 -0
  56. package/runtime/gatewaysdk/environment/runtime.py +8 -13
  57. package/runtime/gatewaysdk/environment/schema/__init__.py +4 -4
  58. package/runtime/gatewaysdk/environment/schema/admin_routes.py +86 -0
  59. package/runtime/gatewaysdk/environment/schema/admission.py +174 -0
  60. package/runtime/gatewaysdk/environment/schema/api.py +347 -892
  61. package/runtime/gatewaysdk/environment/schema/assertions.py +458 -0
  62. package/runtime/gatewaysdk/environment/schema/batch.py +44 -39
  63. package/runtime/gatewaysdk/environment/schema/bundle_runtime.py +17 -5
  64. package/runtime/gatewaysdk/environment/schema/cache_layout.py +5 -0
  65. package/runtime/gatewaysdk/environment/schema/call_capture.py +309 -0
  66. package/runtime/gatewaysdk/environment/schema/call_log.py +503 -0
  67. package/runtime/gatewaysdk/environment/schema/call_redaction.py +526 -0
  68. package/runtime/gatewaysdk/environment/schema/cast.py +15 -35
  69. package/runtime/gatewaysdk/environment/schema/compiler.py +334 -158
  70. package/runtime/gatewaysdk/environment/schema/conform.py +14 -39
  71. package/runtime/gatewaysdk/environment/schema/connector.py +113 -211
  72. package/runtime/gatewaysdk/environment/schema/connectors/confluence/connector.toml +1 -12
  73. package/runtime/gatewaysdk/environment/schema/connectors/github/connector.toml +1 -0
  74. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/connector.toml +2 -5
  75. package/runtime/gatewaysdk/environment/schema/cors.py +54 -0
  76. package/runtime/gatewaysdk/environment/schema/credentials.py +313 -8
  77. package/runtime/gatewaysdk/environment/schema/data.py +60 -216
  78. package/runtime/gatewaysdk/environment/schema/database/__init__.py +24 -0
  79. package/runtime/gatewaysdk/environment/schema/database/audit.py +121 -0
  80. package/runtime/gatewaysdk/environment/schema/database/base.py +936 -0
  81. package/runtime/gatewaysdk/environment/schema/database/budget.py +33 -0
  82. package/runtime/gatewaysdk/environment/schema/database/connections.py +101 -0
  83. package/runtime/gatewaysdk/environment/schema/database/engines.py +8 -0
  84. package/runtime/gatewaysdk/environment/schema/database/guard.py +215 -0
  85. package/runtime/gatewaysdk/environment/schema/database/ingest.py +154 -0
  86. package/runtime/gatewaysdk/environment/schema/database/matching.py +58 -0
  87. package/runtime/gatewaysdk/environment/schema/database/provenance.py +30 -0
  88. package/runtime/gatewaysdk/environment/schema/database/reads.py +169 -0
  89. package/runtime/gatewaysdk/environment/schema/database/rows.py +53 -0
  90. package/runtime/gatewaysdk/environment/schema/database/runtime_rows.py +39 -0
  91. package/runtime/gatewaysdk/environment/schema/database/sqlite.py +393 -0
  92. package/runtime/gatewaysdk/environment/schema/declared_routes.py +210 -0
  93. package/runtime/gatewaysdk/environment/schema/domain_migration.py +236 -0
  94. package/runtime/gatewaysdk/environment/schema/door.py +899 -0
  95. package/runtime/gatewaysdk/environment/schema/envelope.py +227 -0
  96. package/runtime/gatewaysdk/environment/schema/extract.py +6 -13
  97. package/runtime/gatewaysdk/environment/schema/grading.py +90 -103
  98. package/runtime/gatewaysdk/environment/schema/handler_errors.py +163 -12
  99. package/runtime/gatewaysdk/environment/schema/host.py +237 -1795
  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 +437 -0
  112. package/runtime/gatewaysdk/environment/schema/lanes.py +53 -0
  113. package/runtime/gatewaysdk/environment/schema/ledger_spill.py +828 -0
  114. package/runtime/gatewaysdk/environment/schema/local.py +58 -170
  115. package/runtime/gatewaysdk/environment/schema/mapping.py +5 -25
  116. package/runtime/gatewaysdk/environment/schema/openapi_import.py +112 -73
  117. package/runtime/gatewaysdk/environment/schema/openapi_paging.py +147 -0
  118. package/runtime/gatewaysdk/environment/schema/openapi_payloads.py +288 -0
  119. package/runtime/gatewaysdk/environment/schema/openapi_routes.py +97 -102
  120. package/runtime/gatewaysdk/environment/schema/openapi_schemas.py +113 -30
  121. package/runtime/gatewaysdk/environment/schema/platform.py +137 -187
  122. package/runtime/gatewaysdk/environment/schema/platform_import.py +2 -3
  123. package/runtime/gatewaysdk/environment/schema/platform_query.py +61 -5
  124. package/runtime/gatewaysdk/environment/schema/primary_key.py +61 -0
  125. package/runtime/gatewaysdk/environment/schema/proof.py +19 -12
  126. package/runtime/gatewaysdk/environment/schema/request_body.py +238 -0
  127. package/runtime/gatewaysdk/environment/schema/request_ledger.py +958 -0
  128. package/runtime/gatewaysdk/environment/schema/route_bindings.py +25 -3
  129. package/runtime/gatewaysdk/environment/schema/route_miss.py +54 -0
  130. package/runtime/gatewaysdk/environment/schema/runtime.py +178 -308
  131. package/runtime/gatewaysdk/environment/schema/served_names.py +58 -0
  132. package/runtime/gatewaysdk/environment/schema/session_files.py +275 -0
  133. package/runtime/gatewaysdk/environment/schema/session_move.py +275 -0
  134. package/runtime/gatewaysdk/environment/schema/skills/agents/connector-template-author.md +5 -1
  135. package/runtime/gatewaysdk/environment/schema/skills/benchmarks-getting-started/SKILL.md +10 -11
  136. package/runtime/gatewaysdk/environment/schema/skills/connector-schema-authoring/SKILL.md +49 -16
  137. package/runtime/gatewaysdk/environment/schema/skills/world-data-ingestion/ROWS.md +39 -9
  138. package/runtime/gatewaysdk/environment/schema/skills/world-data-ingestion/SKILL.md +27 -27
  139. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/SKILL.md +33 -33
  140. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/cli-mcp-map.md +13 -7
  141. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/gotchas.md +49 -1
  142. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/journal-checks.md +182 -0
  143. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/openapi-import.md +50 -21
  144. package/runtime/gatewaysdk/environment/schema/slack.py +4 -8
  145. package/runtime/gatewaysdk/environment/schema/snapshot.py +516 -140
  146. package/runtime/gatewaysdk/environment/schema/spill_files.py +228 -0
  147. package/runtime/gatewaysdk/environment/schema/store_contract.py +8 -14
  148. package/runtime/gatewaysdk/environment/schema/tasks.py +267 -276
  149. package/runtime/gatewaysdk/environment/schema/tools_world.py +146 -242
  150. package/runtime/gatewaysdk/environment/schema/ui.py +24 -5
  151. package/runtime/gatewaysdk/environment/schema/ui_static/app.js +100 -130
  152. package/runtime/gatewaysdk/environment/schema/ui_static/index.html +1 -8
  153. package/runtime/gatewaysdk/environment/schema/validation.py +235 -41
  154. package/runtime/gatewaysdk/environment/schema/verbs.py +32 -36
  155. package/runtime/gatewaysdk/environment/schema/worker.py +6 -4
  156. package/runtime/gatewaysdk/environment/schema/workers.py +345 -96
  157. package/runtime/gatewaysdk/environment/schema/world_host.py +953 -0
  158. package/runtime/gatewaysdk/environment/schema/world_sql.py +81 -0
  159. package/runtime/gatewaysdk/environment/schema/world_tests.py +80 -50
  160. package/runtime/gatewaysdk/environment/score.py +57 -0
  161. package/runtime/gatewaysdk/environment/secret_values.py +36 -0
  162. package/runtime/gatewaysdk/environment/world.py +43 -4
  163. package/runtime/gatewaysdk/environment/world_session_contract.py +46 -5
  164. package/skills/agents/connector-template-author.md +5 -1
  165. package/skills/benchmarks-getting-started/SKILL.md +10 -11
  166. package/skills/connector-schema-authoring/SKILL.md +49 -16
  167. package/skills/connector-schema-authoring/connector-worlds.md +142 -11
  168. package/skills/connector-schema-authoring/world-schema.md +103 -51
  169. package/skills/world-data-ingestion/ROWS.md +39 -9
  170. package/skills/world-data-ingestion/SKILL.md +27 -27
  171. package/skills/worlds-getting-started/SKILL.md +33 -33
  172. package/skills/worlds-getting-started/references/cli-mcp-map.md +13 -7
  173. package/skills/worlds-getting-started/references/gotchas.md +49 -1
  174. package/skills/worlds-getting-started/references/journal-checks.md +182 -0
  175. package/skills/worlds-getting-started/references/openapi-import.md +50 -21
  176. package/runtime/gatewaysdk/environment/schema/store.py +0 -1013
package/dist/index.mjs CHANGED
@@ -190,10 +190,10 @@ var init_users = __esm({
190
190
  totalItems: Number(meta.totalItems ?? rows.length)
191
191
  };
192
192
  }
193
- async requestJson(method, path16, payload) {
193
+ async requestJson(method, path17, payload) {
194
194
  let response;
195
195
  try {
196
- response = await fetch(`${this.host}${path16}`, {
196
+ response = await fetch(`${this.host}${path17}`, {
197
197
  method,
198
198
  headers: {
199
199
  Authorization: this.authHeader(),
@@ -204,17 +204,17 @@ var init_users = __esm({
204
204
  });
205
205
  } catch (error) {
206
206
  throw new UserProfileError(
207
- `${method} ${path16} failed: ${error instanceof Error ? error.message : String(error)}`,
207
+ `${method} ${path17} failed: ${error instanceof Error ? error.message : String(error)}`,
208
208
  { cause: error }
209
209
  );
210
210
  }
211
211
  const text2 = await response.text();
212
212
  if (!response.ok) {
213
213
  throw new UserProfileError(
214
- `${method} ${path16} failed (${response.status}): ${text2.slice(0, 500)}`
214
+ `${method} ${path17} failed (${response.status}): ${text2.slice(0, 500)}`
215
215
  );
216
216
  }
217
- this.log("%s %s -> %s", method, path16, response.status);
217
+ this.log("%s %s -> %s", method, path17, response.status);
218
218
  return safeJson4(text2);
219
219
  }
220
220
  authHeader() {
@@ -403,10 +403,10 @@ var init_scores = __esm({
403
403
  metadata: signalMetadata
404
404
  });
405
405
  }
406
- async request(method, path16, payload) {
406
+ async request(method, path17, payload) {
407
407
  let response;
408
408
  try {
409
- response = await fetch(`${this.host}${path16}`, {
409
+ response = await fetch(`${this.host}${path17}`, {
410
410
  method,
411
411
  headers: {
412
412
  Authorization: this.authHeader(),
@@ -417,17 +417,17 @@ var init_scores = __esm({
417
417
  });
418
418
  } catch (error) {
419
419
  throw new ScoreError(
420
- `${method} ${path16} failed: ${error instanceof Error ? error.message : String(error)}`,
420
+ `${method} ${path17} failed: ${error instanceof Error ? error.message : String(error)}`,
421
421
  { cause: error }
422
422
  );
423
423
  }
424
424
  const text2 = await response.text();
425
425
  if (!response.ok) {
426
426
  throw new ScoreError(
427
- `${method} ${path16} failed (${response.status}): ${text2.slice(0, 500)}`
427
+ `${method} ${path17} failed (${response.status}): ${text2.slice(0, 500)}`
428
428
  );
429
429
  }
430
- this.log("%s %s -> %s", method, path16, response.status);
430
+ this.log("%s %s -> %s", method, path17, response.status);
431
431
  }
432
432
  authHeader() {
433
433
  return `Basic ${Buffer.from(`${this.publicKey}:${this.secretKey}`).toString(
@@ -450,6 +450,28 @@ var init_scores = __esm({
450
450
  }
451
451
  });
452
452
 
453
+ // src/worlds/platformEndpoint.ts
454
+ function platformEndpoint(options) {
455
+ const publicKey = options.publicKey ?? process.env.GATEWAY_PUBLIC_KEY;
456
+ const secretKey = options.secretKey ?? process.env.GATEWAY_SECRET_KEY;
457
+ if (!publicKey || !secretKey) return null;
458
+ const host = options.host ?? process.env.GATEWAY_HOST ?? DEFAULT_HOST;
459
+ return { host: host.replace(/\/+$/, ""), publicKey, secretKey };
460
+ }
461
+ function requirePlatformEndpoint(options) {
462
+ const endpoint = platformEndpoint(options);
463
+ if (!endpoint) throw new Error(GATEWAY_KEYS_MISSING);
464
+ return endpoint;
465
+ }
466
+ var DEFAULT_HOST, GATEWAY_KEYS_MISSING;
467
+ var init_platformEndpoint = __esm({
468
+ "src/worlds/platformEndpoint.ts"() {
469
+ "use strict";
470
+ DEFAULT_HOST = "https://withgateway.ai";
471
+ GATEWAY_KEYS_MISSING = "Gateway keys missing: set GATEWAY_PUBLIC_KEY / GATEWAY_SECRET_KEY (or pass publicKey/secretKey).";
472
+ }
473
+ });
474
+
453
475
  // src/worlds/transport.ts
454
476
  function platformTimeoutMs(env = process.env) {
455
477
  const raw = env[PLATFORM_TIMEOUT_ENV];
@@ -458,7 +480,7 @@ function platformTimeoutMs(env = process.env) {
458
480
  if (Number.isInteger(value) && value > 0) return value;
459
481
  throw new Error(`${PLATFORM_TIMEOUT_ENV} must be a positive whole number of milliseconds, not \`${raw}\`.`);
460
482
  }
461
- var PLATFORM_TIMEOUT_ENV, PLATFORM_TIMEOUT_DEFAULT_MS, CHECK_HOST, RETRY, CAUSES, UNKNOWN_CAUSE, TransportCause, UnreachableError, PlatformTransport;
483
+ var PLATFORM_TIMEOUT_ENV, PLATFORM_TIMEOUT_DEFAULT_MS, CHECK_HOST, RETRY, FETCH_LIMIT, CAUSES, UNKNOWN_CAUSE, TransportCause, UnreachableError, sleep2, RetryPolicy, Attempt, PlatformTransport;
462
484
  var init_transport = __esm({
463
485
  "src/worlds/transport.ts"() {
464
486
  "use strict";
@@ -466,7 +488,13 @@ var init_transport = __esm({
466
488
  PLATFORM_TIMEOUT_DEFAULT_MS = 12e4;
467
489
  CHECK_HOST = "Check GATEWAY_HOST (or --host) points at a running platform, then retry.";
468
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
+ };
469
495
  CAUSES = {
496
+ UND_ERR_HEADERS_TIMEOUT: FETCH_LIMIT,
497
+ UND_ERR_BODY_TIMEOUT: FETCH_LIMIT,
470
498
  ECONNREFUSED: { reason: "connection refused", next: CHECK_HOST },
471
499
  ENOTFOUND: { reason: "DNS lookup failed", next: CHECK_HOST },
472
500
  EAI_AGAIN: { reason: "DNS lookup failed", next: CHECK_HOST },
@@ -520,6 +548,56 @@ var init_transport = __esm({
520
548
  route;
521
549
  failure;
522
550
  };
551
+ sleep2 = (ms) => new Promise((resolve11) => setTimeout(resolve11, ms));
552
+ RetryPolicy = class _RetryPolicy {
553
+ constructor(delaysMs, wait = sleep2, budgetMs = Number.POSITIVE_INFINITY, now = Date.now) {
554
+ this.delaysMs = delaysMs;
555
+ this.wait = wait;
556
+ this.budgetMs = budgetMs;
557
+ this.now = now;
558
+ }
559
+ delaysMs;
560
+ wait;
561
+ budgetMs;
562
+ now;
563
+ static NONE = new _RetryPolicy([]);
564
+ /** A platform restart or a short edge outage: no wait starts that would end past five minutes, so a step ends
565
+ * within the budget plus one request timeout. */
566
+ static FILING = new _RetryPolicy([250, 500, 1e3, 2e3, 4e3, 8e3, 16e3, 3e4], sleep2, 3e5);
567
+ static TRANSIENT_STATUSES = /* @__PURE__ */ new Set([502, 503, 504]);
568
+ async run(attempt) {
569
+ const started = this.now();
570
+ for (let tries = 0; ; tries += 1) {
571
+ const outcome = await Attempt.of(attempt);
572
+ const delayMs = this.delaysMs[tries];
573
+ const spent = delayMs === void 0 || this.now() - started + delayMs >= this.budgetMs;
574
+ if (!outcome.transient || spent) return outcome.settle();
575
+ await this.wait(delayMs);
576
+ }
577
+ }
578
+ };
579
+ Attempt = class _Attempt {
580
+ constructor(reply, error, transient) {
581
+ this.reply = reply;
582
+ this.error = error;
583
+ this.transient = transient;
584
+ }
585
+ reply;
586
+ error;
587
+ transient;
588
+ static async of(attempt) {
589
+ try {
590
+ const reply = await attempt();
591
+ return new _Attempt(reply, null, RetryPolicy.TRANSIENT_STATUSES.has(reply.status));
592
+ } catch (error) {
593
+ return new _Attempt(null, error, error instanceof UnreachableError);
594
+ }
595
+ }
596
+ settle() {
597
+ if (this.reply) return this.reply;
598
+ throw this.error;
599
+ }
600
+ };
523
601
  PlatformTransport = class {
524
602
  constructor(endpoint, timeoutMs = platformTimeoutMs()) {
525
603
  this.endpoint = endpoint;
@@ -533,6 +611,9 @@ var init_transport = __esm({
533
611
  }
534
612
  async send(method, route, body, opts = {}) {
535
613
  const timeoutMs = this.budget(opts.timeoutMs);
614
+ return (opts.retry ?? RetryPolicy.NONE).run(() => this.once(method, route, body, timeoutMs));
615
+ }
616
+ async once(method, route, body, timeoutMs) {
536
617
  const payload = body === void 0 ? {} : { body: JSON.stringify(body) };
537
618
  const controller = new AbortController();
538
619
  const timer = setTimeout(() => controller.abort(), timeoutMs);
@@ -713,6 +794,12 @@ var init_browserReconnect = __esm({
713
794
  });
714
795
 
715
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
+ }
716
803
  function assertBrowserTier(value) {
717
804
  if (BROWSER_TIERS.includes(value)) return;
718
805
  throw new Error(
@@ -726,9 +813,9 @@ function surfaceKinds(s) {
726
813
  if (s.browser) kinds.push("browser");
727
814
  return kinds;
728
815
  }
729
- function uiUrl(ui, path16) {
816
+ function uiUrl(ui, path17) {
730
817
  const base = ui.url.replace(/\/+$/, "");
731
- const rel = path16.startsWith("/") ? path16 : `/${path16}`;
818
+ const rel = path17.startsWith("/") ? path17 : `/${path17}`;
732
819
  if (!ui.token) return base + rel;
733
820
  const [beforeHash, hash] = splitHash(rel);
734
821
  const joiner = beforeHash.includes("?") ? "&" : "?";
@@ -749,6 +836,15 @@ function splitHash(url) {
749
836
  const h = url.indexOf("#");
750
837
  return h < 0 ? [url, ""] : [url.slice(0, h), url.slice(h)];
751
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
+ }
752
848
  function redactActionArgs(action, args) {
753
849
  const secretField = action === "browser_type" && SECRET_KEY.test(String(args.selector ?? ""));
754
850
  const out = {};
@@ -808,7 +904,9 @@ async function openBrowser(surfaces, opts = {}) {
808
904
  };
809
905
  const scrubber = new SecretScrubber([
810
906
  surfaces.browser?.wsUrl,
811
- surfaces.ui?.token
907
+ surfaces.ui?.token,
908
+ capabilityLabel(surfaces.ui?.url),
909
+ capabilityLabel(surfaces.api?.url)
812
910
  ]);
813
911
  const reconnector = mode === "hosted" && surfaces.browser.protocol === "cdp" && opts.repair ? new BrowserReconnector(opts.repair, reattach, {
814
912
  scrub: (text2) => scrubber.scrub(text2)
@@ -873,13 +971,15 @@ function computerUseToolkit(browser, opts = {}) {
873
971
  specs
874
972
  };
875
973
  }
876
- var SURFACE_KINDS, BROWSER_TIERS, DEFAULT_VIEWPORT, SETTLE_TIMEOUT_MS, SETTLE_QUIET_MS, SETTLE_POLL_MS, EVENT_BATCH_SIZE, EVENT_FLUSH_INTERVAL_MS, EVENT_MAX_RETRIES, EVENT_SCREENSHOT_QUALITY, EVENT_MAX_STRING, SECRET_KEY, SECRET_VALUE, WorldSurfaceUnavailable, UI_TOKEN_QUERY, BrowserActionRecorder, WorldBrowser, COMPUTER_USE_SPECS, str;
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;
877
975
  var init_browser = __esm({
878
976
  "src/worlds/browser.ts"() {
879
977
  "use strict";
880
978
  init_session2();
881
979
  init_browserReconnect();
882
980
  SURFACE_KINDS = ["tools", "api", "ui", "browser"];
981
+ PLATFORM_SESSION_HEADER = "X-World-Session";
982
+ SESSION_AUTH_MODES = ["vendor", "open"];
883
983
  BROWSER_TIERS = ["standard", "premium"];
884
984
  DEFAULT_VIEWPORT = { width: 1280, height: 800 };
885
985
  SETTLE_TIMEOUT_MS = 5e3;
@@ -900,6 +1000,7 @@ var init_browser = __esm({
900
1000
  surface;
901
1001
  };
902
1002
  UI_TOKEN_QUERY = "token";
1003
+ CAPABILITY_HOST = /^o-[a-z0-9]+-([a-z2-7]{26})(?:-api)?\./;
903
1004
  BrowserActionRecorder = class {
904
1005
  constructor(post, agentId, opts = {}) {
905
1006
  this.post = post;
@@ -969,7 +1070,7 @@ var init_browser = __esm({
969
1070
  }
970
1071
  async send(batch) {
971
1072
  const retries = this.opts.maxRetries ?? EVENT_MAX_RETRIES;
972
- const sleep3 = this.opts.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
1073
+ const sleep5 = this.opts.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
973
1074
  for (let attempt = 0; attempt < retries; attempt++) {
974
1075
  try {
975
1076
  const base = await this.resolveBase();
@@ -986,13 +1087,16 @@ var init_browser = __esm({
986
1087
  );
987
1088
  return;
988
1089
  }
989
- await sleep3(500 * 2 ** attempt);
1090
+ await sleep5(500 * 2 ** attempt);
990
1091
  }
991
1092
  }
992
1093
  }
993
1094
  };
994
1095
  WorldBrowser = class {
995
- 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
+ ])) {
996
1100
  this.ui = ui;
997
1101
  this.mode = mode;
998
1102
  this.teardown = teardown;
@@ -1129,7 +1233,15 @@ var init_browser = __esm({
1129
1233
  seq: recorder.nextSeq(),
1130
1234
  ts: (/* @__PURE__ */ new Date()).toISOString(),
1131
1235
  action,
1132
- 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
+ ),
1133
1245
  ok: failure === null,
1134
1246
  error,
1135
1247
  durationMs: Date.now() - started,
@@ -1145,8 +1257,8 @@ var init_browser = __esm({
1145
1257
  screenshot: null
1146
1258
  };
1147
1259
  try {
1148
- out.url = this.page.url();
1149
- 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());
1150
1262
  const jpeg = await this.page.screenshot({
1151
1263
  type: "jpeg",
1152
1264
  quality: EVENT_SCREENSHOT_QUALITY
@@ -1623,13 +1735,13 @@ var init_screen = __esm({
1623
1735
  });
1624
1736
  }
1625
1737
  async drag(action) {
1626
- const path16 = action.args.path ?? [];
1627
- if (path16.length < 2) throw new Error("a drag needs at least two points");
1738
+ const path17 = action.args.path ?? [];
1739
+ if (path17.length < 2) throw new Error("a drag needs at least two points");
1628
1740
  return this.held(action.args.modifiers ?? [], async () => {
1629
- await this.moveTo(path16[0]);
1741
+ await this.moveTo(path17[0]);
1630
1742
  await this.page.mouse.down({ button: "left" });
1631
1743
  try {
1632
- for (const point2 of path16.slice(1)) await this.moveTo(point2, DRAG_STEPS);
1744
+ for (const point2 of path17.slice(1)) await this.moveTo(point2, DRAG_STEPS);
1633
1745
  } finally {
1634
1746
  await this.page.mouse.up({ button: "left" });
1635
1747
  }
@@ -1720,7 +1832,7 @@ var init_media = __esm({
1720
1832
  put;
1721
1833
  maxBytes;
1722
1834
  /** The uploader for `GATEWAY_HOST` / `GATEWAY_PUBLIC_KEY` /
1723
- * `GATEWAY_SECRET_KEY` (the keys tracing exports with); null when any is unset. */
1835
+ * `GATEWAY_SECRET_KEY` only; null when any is unset, so a run traced with a saved login uploads none. */
1724
1836
  static fromEnv(env = process.env) {
1725
1837
  const host = env.GATEWAY_HOST;
1726
1838
  const publicKey = env.GATEWAY_PUBLIC_KEY;
@@ -2590,13 +2702,16 @@ function idleWarning(idleExpiresAt, now = /* @__PURE__ */ new Date()) {
2590
2702
  const minutes = Math.max(0, Math.floor(leftMs / 6e4));
2591
2703
  return `warning: session expires in ${minutes}m (idle TTL); call a tool to extend it or \`gateway worlds session pin\` to keep it`;
2592
2704
  }
2593
- var CALL_BODY_LIMIT_BYTES, CALL_BODY_LIMIT_LABEL, IDLE_WARNING_MINUTES, EXPLORATORY_TASK, EXPLORATORY_TASK_SOURCE, NO_GRADER_REASON, WorldCallTooLarge;
2705
+ var CALL_BODY_LIMIT_BYTES, CALL_BODY_LIMIT_LABEL, IDLE_WARNING_MINUTES, REQUEST_LOG_PAGE_MAX, REQUEST_BODY_CAPTURE_BYTES, REQUESTS_NOT_RECORDED, EXPLORATORY_TASK, EXPLORATORY_TASK_SOURCE, NO_GRADER_REASON, WorldCallTooLarge, stillStartingHint;
2594
2706
  var init_sessionContract = __esm({
2595
2707
  "src/worlds/sessionContract.ts"() {
2596
2708
  "use strict";
2597
2709
  CALL_BODY_LIMIT_BYTES = 4 * 1024 * 1024;
2598
2710
  CALL_BODY_LIMIT_LABEL = "4mb";
2599
2711
  IDLE_WARNING_MINUTES = 5;
2712
+ REQUEST_LOG_PAGE_MAX = 200;
2713
+ REQUEST_BODY_CAPTURE_BYTES = 64 * 1024;
2714
+ REQUESTS_NOT_RECORDED = "requests_not_recorded";
2600
2715
  EXPLORATORY_TASK = Object.freeze({
2601
2716
  instruction: "exploratory session"
2602
2717
  });
@@ -2626,6 +2741,276 @@ var init_sessionContract = __esm({
2626
2741
  };
2627
2742
  }
2628
2743
  };
2744
+ stillStartingHint = (sessionId) => `It keeps opening: poll \`gateway worlds session status ${sessionId}\` until ready, or end it with \`gateway worlds session close ${sessionId}\`.`;
2745
+ }
2746
+ });
2747
+
2748
+ // src/worlds/toolSchema.ts
2749
+ function schemaFromSignature(spec) {
2750
+ if (spec.inputSchema)
2751
+ return {
2752
+ type: "function",
2753
+ function: {
2754
+ name: modelToolName(spec.name),
2755
+ description: spec.doc ?? spec.name,
2756
+ parameters: spec.inputSchema
2757
+ }
2758
+ };
2759
+ const inside = /\(([\s\S]*)\)\s*$/.exec(spec.signature.trim())?.[1] ?? "";
2760
+ const properties = {};
2761
+ const required2 = [];
2762
+ const params = [];
2763
+ let depth = 0;
2764
+ let current = "";
2765
+ for (const ch of inside) {
2766
+ if ("([{".includes(ch)) depth++;
2767
+ if (")]}".includes(ch)) depth--;
2768
+ if (ch === "," && depth === 0) {
2769
+ params.push(current);
2770
+ current = "";
2771
+ } else current += ch;
2772
+ }
2773
+ if (current.trim()) params.push(current);
2774
+ for (const raw of params) {
2775
+ const param = raw.trim();
2776
+ if (!param || param.startsWith("*") || param === "self") continue;
2777
+ const eq = param.indexOf("=");
2778
+ const name = (eq === -1 ? param : param.slice(0, eq)).split(":")[0].trim();
2779
+ if (!name) continue;
2780
+ if (eq === -1) {
2781
+ properties[name] = { type: "string" };
2782
+ required2.push(name);
2783
+ continue;
2784
+ }
2785
+ const value = param.slice(eq + 1).trim();
2786
+ if (/^-?\d+(\.\d+)?$/.test(value)) properties[name] = { type: "number" };
2787
+ else if (value === "True" || value === "False")
2788
+ properties[name] = { type: "boolean" };
2789
+ else properties[name] = { type: "string" };
2790
+ }
2791
+ return {
2792
+ type: "function",
2793
+ function: {
2794
+ name: modelToolName(spec.name),
2795
+ description: spec.doc ?? spec.name,
2796
+ parameters: { type: "object", properties, required: required2 }
2797
+ }
2798
+ };
2799
+ }
2800
+ var modelToolName;
2801
+ var init_toolSchema = __esm({
2802
+ "src/worlds/toolSchema.ts"() {
2803
+ "use strict";
2804
+ modelToolName = (name) => name.replace(/[^A-Za-z0-9_-]/g, "_").slice(0, 64) || "tool";
2805
+ }
2806
+ });
2807
+
2808
+ // src/worlds/requestLedger.ts
2809
+ function platformMessage(text2) {
2810
+ try {
2811
+ const { message } = JSON.parse(text2);
2812
+ return typeof message === "string" ? message : null;
2813
+ } catch {
2814
+ return null;
2815
+ }
2816
+ }
2817
+ var WORLD_REQUEST_VIAS, WorldRequestFilterError, NOT_RECORDED, WorldRequestsNotRecorded, STATUS, INSTANT, WORLDS, SESSIONS, Instant, WorldRequestQuery, WorldRequestLedger;
2818
+ var init_requestLedger = __esm({
2819
+ "src/worlds/requestLedger.ts"() {
2820
+ "use strict";
2821
+ init_worlds();
2822
+ init_sessionContract();
2823
+ WORLD_REQUEST_VIAS = ["api", "ui", "tool"];
2824
+ WorldRequestFilterError = class extends Error {
2825
+ };
2826
+ NOT_RECORDED = "This session's engine records no requests; only hosted World Host sessions do.";
2827
+ WorldRequestsNotRecorded = class _WorldRequestsNotRecorded extends Error {
2828
+ static from(error) {
2829
+ if (!(error instanceof ApiError) || error.code !== REQUESTS_NOT_RECORDED) return error;
2830
+ return new _WorldRequestsNotRecorded(platformMessage(error.text) || NOT_RECORDED);
2831
+ }
2832
+ static async mapped(read) {
2833
+ try {
2834
+ return await read;
2835
+ } catch (error) {
2836
+ throw _WorldRequestsNotRecorded.from(error);
2837
+ }
2838
+ }
2839
+ };
2840
+ STATUS = /^(?:[1-5]\d\d|[1-5]xx)$/;
2841
+ INSTANT = /^(\d{4})-(\d{2})-(\d{2})(?:T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{1,3}))?)?(Z|[+-]\d{2}:\d{2})?)?$/;
2842
+ WORLDS = "/api/public/worlds";
2843
+ SESSIONS = "/api/public/world-sessions";
2844
+ Instant = class _Instant {
2845
+ static parse(flag, raw) {
2846
+ const match = INSTANT.exec(raw);
2847
+ const millis = match ? _Instant.fromParts(match) : null;
2848
+ if (millis === null)
2849
+ throw new WorldRequestFilterError(
2850
+ `--${flag} must be an ISO 8601 date or time (2026-10-05, 2026-10-05T14:30:00Z), not \`${raw}\`.`
2851
+ );
2852
+ return millis;
2853
+ }
2854
+ static fromParts(match) {
2855
+ const [year, month, day, hour, minute, second] = [1, 2, 3, 4, 5, 6].map((i) => Number(match[i] ?? 0));
2856
+ const offset = _Instant.offsetMinutes(match[8]);
2857
+ if (offset === null || year < 1 || hour > 23 || minute > 59 || second > 59) return null;
2858
+ const date = /* @__PURE__ */ new Date(0);
2859
+ date.setUTCFullYear(year, month - 1, day);
2860
+ if (date.getUTCFullYear() !== year || date.getUTCMonth() !== month - 1 || date.getUTCDate() !== day) return null;
2861
+ date.setUTCHours(hour, minute, second, Number((match[7] ?? "").padEnd(3, "0")));
2862
+ const utc = date.getTime() - offset * 6e4;
2863
+ const utcYear = new Date(utc).getUTCFullYear();
2864
+ return utcYear < 1 || utcYear > 9999 ? null : utc;
2865
+ }
2866
+ static offsetMinutes(zone) {
2867
+ if (zone === void 0 || zone === "Z") return 0;
2868
+ const hours = Number(zone.slice(1, 3));
2869
+ const minutes = Number(zone.slice(4, 6));
2870
+ if (hours > 23 || minutes > 59) return null;
2871
+ return (zone.startsWith("-") ? -1 : 1) * (hours * 60 + minutes);
2872
+ }
2873
+ };
2874
+ WorldRequestQuery = class _WorldRequestQuery {
2875
+ constructor(entries) {
2876
+ this.entries = entries;
2877
+ }
2878
+ entries;
2879
+ static parse(filter = {}) {
2880
+ const via = _WorldRequestQuery.via(filter.via);
2881
+ const status = _WorldRequestQuery.status(filter.status);
2882
+ const since = filter.since === void 0 ? void 0 : Instant.parse("since", filter.since);
2883
+ const until = filter.until === void 0 ? void 0 : Instant.parse("until", filter.until);
2884
+ if (since !== void 0 && until !== void 0 && since > until)
2885
+ throw new WorldRequestFilterError("--since must not be after --until.");
2886
+ const values = [
2887
+ ["session", filter.session],
2888
+ ["version", filter.version],
2889
+ ["via", via],
2890
+ ["operation", filter.operation],
2891
+ ["status", status],
2892
+ ["since", since === void 0 ? void 0 : new Date(since).toISOString()],
2893
+ ["until", until === void 0 ? void 0 : new Date(until).toISOString()],
2894
+ ["limit", filter.limit === void 0 ? void 0 : String(filter.limit)],
2895
+ ["cursor", filter.cursor]
2896
+ ];
2897
+ return new _WorldRequestQuery(values.filter((entry) => entry[1] !== void 0));
2898
+ }
2899
+ static via(value) {
2900
+ if (value === void 0) return void 0;
2901
+ const lower = value.toLowerCase();
2902
+ if (WORLD_REQUEST_VIAS.includes(lower)) return lower;
2903
+ throw new WorldRequestFilterError(`--via must be one of ${WORLD_REQUEST_VIAS.join(", ")}, not \`${value}\`.`);
2904
+ }
2905
+ static status(value) {
2906
+ if (value === void 0) return void 0;
2907
+ const lower = value.toLowerCase();
2908
+ if (STATUS.test(lower)) return lower;
2909
+ throw new WorldRequestFilterError(`--status must be a code (200) or a class (2xx), not \`${value}\`.`);
2910
+ }
2911
+ get filtered() {
2912
+ return this.entries.some(([key2]) => key2 !== "limit");
2913
+ }
2914
+ params() {
2915
+ return this.entries.map(([key2, value]) => [key2, value]);
2916
+ }
2917
+ search() {
2918
+ return this.entries.length ? `?${new URLSearchParams(this.entries).toString()}` : "";
2919
+ }
2920
+ };
2921
+ WorldRequestLedger = class {
2922
+ constructor(options = {}) {
2923
+ this.options = options;
2924
+ }
2925
+ options;
2926
+ /** A page of the world's requests, newest first; `nextCursor` reads the page after it. Narrowed to a session
2927
+ * whose engine records none: `WorldRequestsNotRecorded`. */
2928
+ list(slug, query = WorldRequestQuery.parse()) {
2929
+ return WorldRequestsNotRecorded.mapped(
2930
+ apiRequest(
2931
+ this.options,
2932
+ "GET",
2933
+ `${WORLDS}/${encodeURIComponent(slug)}/requests${query.search()}`
2934
+ )
2935
+ );
2936
+ }
2937
+ /** One of the world's requests, with its headers and bodies. */
2938
+ get(slug, requestId) {
2939
+ return apiRequest(
2940
+ this.options,
2941
+ "GET",
2942
+ `${WORLDS}/${encodeURIComponent(slug)}/requests/${encodeURIComponent(requestId)}`
2943
+ );
2944
+ }
2945
+ /** A page of one session's requests, newest first; `WorldRequestsNotRecorded` when its engine records none. */
2946
+ forSession(sessionId, query = WorldRequestQuery.parse()) {
2947
+ return WorldRequestsNotRecorded.mapped(
2948
+ apiRequest(
2949
+ this.options,
2950
+ "GET",
2951
+ `${SESSIONS}/${encodeURIComponent(sessionId)}/requests${query.search()}`
2952
+ )
2953
+ );
2954
+ }
2955
+ };
2956
+ }
2957
+ });
2958
+
2959
+ // src/worlds/sessionReadiness.ts
2960
+ var READY_TIMEOUT_MS, READY_POLL_MS, sleep3, WorldSessionTimeout, WorldSessionCallError, WorldSessionOpenFailed, ENDED, SessionReadiness;
2961
+ var init_sessionReadiness = __esm({
2962
+ "src/worlds/sessionReadiness.ts"() {
2963
+ "use strict";
2964
+ READY_TIMEOUT_MS = 10 * 6e4;
2965
+ READY_POLL_MS = 2e3;
2966
+ sleep3 = (ms) => new Promise((r) => setTimeout(r, ms));
2967
+ WorldSessionTimeout = class extends Error {
2968
+ };
2969
+ WorldSessionCallError = class extends Error {
2970
+ };
2971
+ WorldSessionOpenFailed = class extends WorldSessionCallError {
2972
+ constructor(sessionId, state2, code, reason) {
2973
+ super(
2974
+ reason === null ? `World session ${sessionId} ${state2.toLowerCase()} before it was ready.` : `World session ${sessionId} failed to open: ${reason}${code ? ` (${code})` : ""}`
2975
+ );
2976
+ this.sessionId = sessionId;
2977
+ this.state = state2;
2978
+ this.code = code;
2979
+ this.name = "WorldSessionOpenFailed";
2980
+ }
2981
+ sessionId;
2982
+ state;
2983
+ code;
2984
+ };
2985
+ ENDED = /* @__PURE__ */ new Set(["FAILED", "STOPPED"]);
2986
+ SessionReadiness = class {
2987
+ constructor(sessionId, status) {
2988
+ this.sessionId = sessionId;
2989
+ this.status = status;
2990
+ }
2991
+ sessionId;
2992
+ status;
2993
+ async wait(timeoutMs = READY_TIMEOUT_MS) {
2994
+ const deadline = Date.now() + timeoutMs;
2995
+ for (; ; ) {
2996
+ const state2 = await this.status();
2997
+ if (state2.ready) return state2;
2998
+ if (ENDED.has(state2.state))
2999
+ throw new WorldSessionOpenFailed(
3000
+ this.sessionId,
3001
+ state2.state,
3002
+ state2.failure?.code ?? null,
3003
+ state2.failure?.message ?? null
3004
+ );
3005
+ const left = deadline - Date.now();
3006
+ if (left <= 0)
3007
+ throw new WorldSessionTimeout(
3008
+ `World session ${this.sessionId} still ${state2.state} after ${Math.round(timeoutMs / 1e3)}s.`
3009
+ );
3010
+ await sleep3(Math.min(READY_POLL_MS, left));
3011
+ }
3012
+ }
3013
+ };
2629
3014
  }
2630
3015
  });
2631
3016
 
@@ -2721,11 +3106,184 @@ var init_taskRef = __esm({
2721
3106
  }
2722
3107
  });
2723
3108
 
3109
+ // src/worlds/worldNotice.ts
3110
+ var TOOL_CONTRACT_UNREAD, DEPRECATION, NOTICE_KINDS, WorldNotice, WorldToolsUnread;
3111
+ var init_worldNotice = __esm({
3112
+ "src/worlds/worldNotice.ts"() {
3113
+ "use strict";
3114
+ TOOL_CONTRACT_UNREAD = "tool-contract-unread";
3115
+ DEPRECATION = { label: "deprecated", next: "Instead", refusesRun: false };
3116
+ NOTICE_KINDS = /* @__PURE__ */ new Map([
3117
+ [TOOL_CONTRACT_UNREAD, { label: "warning", next: "Then", refusesRun: true }]
3118
+ ]);
3119
+ WorldNotice = class _WorldNotice {
3120
+ constructor(notice, kind) {
3121
+ this.notice = notice;
3122
+ this.kind = kind;
3123
+ }
3124
+ notice;
3125
+ kind;
3126
+ static of(notice) {
3127
+ return new _WorldNotice(notice, NOTICE_KINDS.get(notice.code) ?? DEPRECATION);
3128
+ }
3129
+ get refusesRun() {
3130
+ return this.kind.refusesRun;
3131
+ }
3132
+ line() {
3133
+ const { code, message, replacement } = this.notice;
3134
+ return `${this.kind.label} (${code}): ${message} ${this.kind.next}: ${replacement}`;
3135
+ }
3136
+ };
3137
+ WorldToolsUnread = class _WorldToolsUnread extends Error {
3138
+ constructor(world, notice) {
3139
+ super(
3140
+ `refused before the agent ran, nothing filed: world ${world} has no readable tools: ${notice.notice.message} Then: ${notice.notice.replacement}`
3141
+ );
3142
+ this.world = world;
3143
+ this.notice = notice;
3144
+ this.name = "WorldToolsUnread";
3145
+ this.code = notice.notice.code;
3146
+ }
3147
+ world;
3148
+ notice;
3149
+ code;
3150
+ static refuse(world, notices) {
3151
+ const refusing = notices.map((notice) => WorldNotice.of(notice)).find((notice) => notice.refusesRun);
3152
+ if (refusing) throw new _WorldToolsUnread(world, refusing);
3153
+ }
3154
+ };
3155
+ }
3156
+ });
3157
+
3158
+ // src/worlds/grade.ts
3159
+ var messageOf, Score, GradeRefused, GradePayload;
3160
+ var init_grade = __esm({
3161
+ "src/worlds/grade.ts"() {
3162
+ "use strict";
3163
+ messageOf = (error) => (error instanceof Error ? error.message || error.name : String(error)) || "Error";
3164
+ Score = class _Score {
3165
+ static RULE = "a score is a number from 0 to 1";
3166
+ static admits(value) {
3167
+ return Number.isFinite(value) && value >= 0 && value <= 1;
3168
+ }
3169
+ /** Every number among `scores` that is not a score, as `'<key>' = <value>`
3170
+ * and the rule, or null when all of them are. Pairs, not a map, so that no
3171
+ * key hides another. */
3172
+ static problem(scores2) {
3173
+ const refused = [...scores2].flatMap(
3174
+ ([key2, value]) => typeof value === "number" && !_Score.admits(value) ? [`'${key2}' = ${String(value)}`] : []
3175
+ );
3176
+ return refused.length ? `${refused.join(", ")}; ${_Score.RULE}` : null;
3177
+ }
3178
+ };
3179
+ GradeRefused = class extends Error {
3180
+ name = "GradeRefused";
3181
+ };
3182
+ GradePayload = class _GradePayload {
3183
+ /** A grade payload's numbers, checked: every number in it must be a score,
3184
+ * and its rewards and verifiers objects by name, or the grade is refused; a
3185
+ * cross-world verifier's grade that breaks either rule is that verifier's
3186
+ * error, the way the World Host answers one that could not grade. */
3187
+ static read(raw) {
3188
+ if (!_GradePayload.objectOrAbsent(raw))
3189
+ throw new GradeRefused("the grade is not an object");
3190
+ const record = _GradePayload.record(raw);
3191
+ const problem = _GradePayload.problem(record) ?? _GradePayload.verifiersProblem(record.verifiers);
3192
+ if (problem) throw new GradeRefused(problem);
3193
+ const verifiers = _GradePayload.verifiers(record.verifiers);
3194
+ return {
3195
+ ..._GradePayload.numbers(record),
3196
+ ...typeof record.reason === "string" ? { reason: record.reason } : {},
3197
+ ...typeof record.error === "string" ? { error: record.error } : {},
3198
+ ...verifiers ? { verifiers } : {}
3199
+ };
3200
+ }
3201
+ /** A world whose grade call failed (the platform refused it, the host had
3202
+ * lost the session): that world's error, never a score. */
3203
+ static failedCall(error) {
3204
+ return { ..._GradePayload.failed(messageOf(error)), raw: null };
3205
+ }
3206
+ static problem(record) {
3207
+ if (!_GradePayload.objectOrAbsent(record.rewards))
3208
+ return "the grade's rewards are not an object";
3209
+ const scores2 = Score.problem(_GradePayload.scores(record));
3210
+ if (scores2) return `the grade answered ${scores2}`;
3211
+ const twice = _GradePayload.twice(record);
3212
+ return twice.length ? `the grade answered ${twice.map((key2) => `'${key2}'`).join(", ")} both beside and inside rewards` : null;
3213
+ }
3214
+ static twice(record) {
3215
+ return Object.entries(_GradePayload.record(record.rewards)).filter(
3216
+ ([key2, value]) => key2 !== "reward" && typeof value === "number" && typeof record[key2] === "number"
3217
+ ).map(([key2]) => key2);
3218
+ }
3219
+ static verifiersProblem(value) {
3220
+ return _GradePayload.objectOrAbsent(value) ? null : "the grade's verifiers are not an object";
3221
+ }
3222
+ static scores(record) {
3223
+ return [
3224
+ ["reward", record.reward],
3225
+ ...Object.entries(_GradePayload.record(record.rewards)),
3226
+ ...Object.entries(record).filter(
3227
+ ([key2]) => key2 !== "reward" && key2 !== "rewards"
3228
+ )
3229
+ ];
3230
+ }
3231
+ static isRecord(value) {
3232
+ return typeof value === "object" && value !== null && !Array.isArray(value);
3233
+ }
3234
+ static objectOrAbsent(value) {
3235
+ return value === void 0 || value === null || _GradePayload.isRecord(value);
3236
+ }
3237
+ static record(value) {
3238
+ return _GradePayload.isRecord(value) ? value : {};
3239
+ }
3240
+ /** `reward`, and every numeric key under `rewards` (the host's shape) or at
3241
+ * the top level (a bundled verifier's). */
3242
+ static numbers(record) {
3243
+ const rewards = {};
3244
+ for (const [key2, value] of Object.entries(
3245
+ _GradePayload.record(record.rewards)
3246
+ ))
3247
+ if (typeof value === "number") rewards[key2] = value;
3248
+ for (const [key2, value] of Object.entries(record))
3249
+ if (key2 !== "reward" && typeof value === "number") rewards[key2] = value;
3250
+ return {
3251
+ reward: typeof record.reward === "number" ? record.reward : null,
3252
+ rewards
3253
+ };
3254
+ }
3255
+ static verifiers(value) {
3256
+ if (!_GradePayload.isRecord(value)) return void 0;
3257
+ return Object.fromEntries(
3258
+ Object.entries(value).map(([name, grade]) => [
3259
+ name,
3260
+ _GradePayload.verifier(name, grade)
3261
+ ])
3262
+ );
3263
+ }
3264
+ static verifier(name, grade) {
3265
+ if (!_GradePayload.isRecord(grade))
3266
+ return _GradePayload.failed(`the grade's verifier '${name}' is not an object`);
3267
+ const problem = _GradePayload.problem(grade);
3268
+ if (problem) return _GradePayload.failed(problem);
3269
+ return {
3270
+ ..._GradePayload.numbers(grade),
3271
+ ...typeof grade.error === "string" ? { error: grade.error } : {}
3272
+ };
3273
+ }
3274
+ static failed(error) {
3275
+ return { reward: null, rewards: {}, error };
3276
+ }
3277
+ };
3278
+ }
3279
+ });
3280
+
2724
3281
  // src/worlds/session.ts
2725
3282
  var session_exports2 = {};
2726
3283
  __export(session_exports2, {
2727
3284
  WorldSession: () => WorldSession,
2728
3285
  WorldSessionCallError: () => WorldSessionCallError,
3286
+ WorldSessionOpenFailed: () => WorldSessionOpenFailed,
2729
3287
  WorldSessionTimeout: () => WorldSessionTimeout,
2730
3288
  attachSession: () => attachSession,
2731
3289
  isTaskIdRef: () => isTaskIdRef,
@@ -2737,85 +3295,6 @@ __export(session_exports2, {
2737
3295
  taskLabel: () => taskLabel
2738
3296
  });
2739
3297
  import { randomUUID } from "crypto";
2740
- function numericGrade(record) {
2741
- const rewards = {};
2742
- const nested = record.rewards;
2743
- if (nested && typeof nested === "object") {
2744
- for (const [key2, value] of Object.entries(nested)) {
2745
- if (typeof value === "number") rewards[key2] = value;
2746
- }
2747
- }
2748
- for (const [key2, value] of Object.entries(record)) {
2749
- if (key2 !== "reward" && typeof value === "number") rewards[key2] = value;
2750
- }
2751
- return {
2752
- reward: typeof record.reward === "number" ? record.reward : null,
2753
- rewards
2754
- };
2755
- }
2756
- function verifierGrades(value) {
2757
- if (!value || typeof value !== "object") return void 0;
2758
- const out = {};
2759
- for (const [name, grade] of Object.entries(value)) {
2760
- const record = grade && typeof grade === "object" ? grade : {};
2761
- out[name] = {
2762
- ...numericGrade(record),
2763
- ...typeof record.error === "string" ? { error: record.error } : {}
2764
- };
2765
- }
2766
- return out;
2767
- }
2768
- function schemaFromSignature(spec) {
2769
- if (spec.inputSchema)
2770
- return {
2771
- type: "function",
2772
- function: {
2773
- name: modelToolName(spec.name),
2774
- description: spec.doc ?? spec.name,
2775
- parameters: spec.inputSchema
2776
- }
2777
- };
2778
- const inside = /\(([\s\S]*)\)\s*$/.exec(spec.signature.trim())?.[1] ?? "";
2779
- const properties = {};
2780
- const required2 = [];
2781
- const params = [];
2782
- let depth = 0;
2783
- let current = "";
2784
- for (const ch of inside) {
2785
- if ("([{".includes(ch)) depth++;
2786
- if (")]}".includes(ch)) depth--;
2787
- if (ch === "," && depth === 0) {
2788
- params.push(current);
2789
- current = "";
2790
- } else current += ch;
2791
- }
2792
- if (current.trim()) params.push(current);
2793
- for (const raw of params) {
2794
- const param = raw.trim();
2795
- if (!param || param.startsWith("*") || param === "self") continue;
2796
- const eq = param.indexOf("=");
2797
- const name = (eq === -1 ? param : param.slice(0, eq)).split(":")[0].trim();
2798
- if (!name) continue;
2799
- if (eq === -1) {
2800
- properties[name] = { type: "string" };
2801
- required2.push(name);
2802
- continue;
2803
- }
2804
- const value = param.slice(eq + 1).trim();
2805
- if (/^-?\d+(\.\d+)?$/.test(value)) properties[name] = { type: "number" };
2806
- else if (value === "True" || value === "False")
2807
- properties[name] = { type: "boolean" };
2808
- else properties[name] = { type: "string" };
2809
- }
2810
- return {
2811
- type: "function",
2812
- function: {
2813
- name: modelToolName(spec.name),
2814
- description: spec.doc ?? spec.name,
2815
- parameters: { type: "object", properties, required: required2 }
2816
- }
2817
- };
2818
- }
2819
3298
  async function attachSession(sessionId, options = {}) {
2820
3299
  const state2 = await apiRequest(
2821
3300
  options,
@@ -2836,6 +3315,7 @@ async function openSession(slugOrRef, taskOrOpts = {}, positionalOpts = {}) {
2836
3315
  `Unknown world surfaces: ${unknown.join(", ")}; choose from ${SURFACE_KINDS.join(", ")}`
2837
3316
  );
2838
3317
  if (opts.browserTier !== void 0) assertBrowserTier(opts.browserTier);
3318
+ if (opts.auth !== void 0) assertSessionAuthMode(opts.auth);
2839
3319
  const at = slugOrRef.indexOf("@");
2840
3320
  const slug = at === -1 ? slugOrRef : slugOrRef.slice(0, at);
2841
3321
  const ref = at === -1 ? "" : slugOrRef.slice(at + 1);
@@ -2848,7 +3328,8 @@ async function openSession(slugOrRef, taskOrOpts = {}, positionalOpts = {}) {
2848
3328
  ...task === void 0 ? {} : { task },
2849
3329
  ...opts.reuseWarm === void 0 ? {} : { reuseWarm: opts.reuseWarm },
2850
3330
  ...opts.surfaces?.length ? { surfaces: opts.surfaces } : {},
2851
- ...opts.browserTier === void 0 ? {} : { browserTier: opts.browserTier }
3331
+ ...opts.browserTier === void 0 ? {} : { browserTier: opts.browserTier },
3332
+ ...opts.auth === void 0 ? {} : { auth: opts.auth }
2852
3333
  }
2853
3334
  );
2854
3335
  return new WorldSession(state2.sessionId, state2, options);
@@ -2872,6 +3353,7 @@ async function runSessions(opts) {
2872
3353
  const taskRef = tasks[next++];
2873
3354
  let task = taskLabel(taskRef);
2874
3355
  let session = null;
3356
+ let keepWarm = opts.keepWarm ?? true;
2875
3357
  try {
2876
3358
  session = await openSession(opts.world, {
2877
3359
  task: taskRef,
@@ -2879,6 +3361,7 @@ async function runSessions(opts) {
2879
3361
  options
2880
3362
  });
2881
3363
  task = taskLabel(taskRef, session.taskInfo);
3364
+ WorldToolsUnread.refuse(opts.world.split("@", 1)[0], session.deprecations);
2882
3365
  await session.ready();
2883
3366
  const toolkit = await session.toolkit();
2884
3367
  const live = session;
@@ -2901,19 +3384,19 @@ async function runSessions(opts) {
2901
3384
  results.push(result);
2902
3385
  opts.onResult?.(result);
2903
3386
  } catch (error) {
3387
+ if (error instanceof WorldToolsUnread) keepWarm = false;
2904
3388
  const result = {
2905
3389
  task,
2906
3390
  sessionId: session?.sessionId ?? "",
2907
3391
  reward: 0,
2908
3392
  rewards: {},
2909
- // An Error with an empty message would read as "no error" to any
2910
- // caller checking truthiness; name the type instead.
3393
+ // An empty message reads as "no error" to a truthiness check; name the type instead.
2911
3394
  error: (error instanceof Error ? error.message : String(error)) || (error instanceof Error ? error.name : "Unknown error")
2912
3395
  };
2913
3396
  results.push(result);
2914
3397
  opts.onResult?.(result);
2915
3398
  } finally {
2916
- await session?.close({ keepWarm: opts.keepWarm ?? true }).catch(() => void 0);
3399
+ await session?.close({ keepWarm }).catch(() => void 0);
2917
3400
  }
2918
3401
  }
2919
3402
  })
@@ -2927,7 +3410,7 @@ async function runSessions(opts) {
2927
3410
  passed: failed === 0 && (opts.failUnder === void 0 || mean >= opts.failUnder)
2928
3411
  };
2929
3412
  }
2930
- var READY_TIMEOUT_MS, READY_POLL_MS, CALL_TIMEOUT_MS, CALL_POLL_MS, JUDGED_GRADE_TIMEOUT_MS, JUDGED_GRADE_POLL_MS, EXPORT_PAGE, sleep2, modelToolName, WorldSessionTimeout, WorldSessionCallError, WorldSession, OPEN_SESSION_OPTION_KEYS, isOpenSessionOptions;
3413
+ var CALL_TIMEOUT_MS, CALL_POLL_MS, JUDGED_GRADE_TIMEOUT_MS, JUDGED_GRADE_POLL_MS, EXPORT_PAGE, sleep4, WorldSession, OPEN_SESSION_OPTION_KEYS, isOpenSessionOptions;
2931
3414
  var init_session2 = __esm({
2932
3415
  "src/worlds/session.ts"() {
2933
3416
  "use strict";
@@ -2935,22 +3418,21 @@ var init_session2 = __esm({
2935
3418
  init_browser();
2936
3419
  init_nativeComputer();
2937
3420
  init_sessionContract();
3421
+ init_toolSchema();
3422
+ init_requestLedger();
3423
+ init_sessionReadiness();
2938
3424
  init_session();
2939
3425
  init_taskRef();
3426
+ init_worldNotice();
3427
+ init_grade();
2940
3428
  init_taskRef();
2941
- READY_TIMEOUT_MS = 10 * 6e4;
2942
- READY_POLL_MS = 2e3;
3429
+ init_sessionReadiness();
2943
3430
  CALL_TIMEOUT_MS = 3 * 6e4;
2944
3431
  CALL_POLL_MS = 400;
2945
3432
  JUDGED_GRADE_TIMEOUT_MS = 15 * 6e4;
2946
3433
  JUDGED_GRADE_POLL_MS = 2e3;
2947
3434
  EXPORT_PAGE = 500;
2948
- sleep2 = (ms) => new Promise((r) => setTimeout(r, ms));
2949
- modelToolName = (name) => name.replace(/[^A-Za-z0-9_-]/g, "_").slice(0, 64) || "tool";
2950
- WorldSessionTimeout = class extends Error {
2951
- };
2952
- WorldSessionCallError = class extends Error {
2953
- };
3435
+ sleep4 = (ms) => new Promise((r) => setTimeout(r, ms));
2954
3436
  WorldSession = class {
2955
3437
  constructor(sessionId, current, options) {
2956
3438
  this.sessionId = sessionId;
@@ -3020,12 +3502,12 @@ var init_session2 = __esm({
3020
3502
  );
3021
3503
  return api2.url;
3022
3504
  }
3023
- /** Headers every request to `api()` needs. A World Host session gates its
3024
- * api surface on a per-session token; a pod or hosted twin answers with the
3025
- * world's own declared auth and this is `{}`. */
3505
+ /** Headers every request to `api()` needs: a World Host session's token in the
3506
+ * platform's `X-World-Session` header, which every world takes; `{}` for a pod
3507
+ * or hosted twin, which answers with the world's own declared auth. */
3026
3508
  async apiHeaders() {
3027
3509
  const { api: api2 } = await this.surfaces();
3028
- return api2?.token ? { Authorization: `Bearer ${api2.token}` } : {};
3510
+ return api2?.token ? { [PLATFORM_SESSION_HEADER]: api2.token } : {};
3029
3511
  }
3030
3512
  /** URL of the world's UI entry page for this session. */
3031
3513
  async ui() {
@@ -3068,18 +3550,17 @@ var init_session2 = __esm({
3068
3550
  }
3069
3551
  /** The reporter `browser()` uses; exposed for a page you drive yourself. */
3070
3552
  browserRecorder(agentId) {
3071
- const path16 = `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/browser-events`;
3553
+ const path17 = `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/browser-events`;
3072
3554
  const id = agentId ?? process.env.GATEWAY_AGENT_ID ?? `agent-${randomUUID().replace(/-/g, "").slice(0, 8)}`;
3073
3555
  return new BrowserActionRecorder(
3074
3556
  async (events) => {
3075
- await apiRequest(this.options, "POST", path16, { events });
3557
+ await apiRequest(this.options, "POST", path17, { events });
3076
3558
  },
3077
3559
  id,
3078
3560
  {
3079
- // Continue this agent's timeline where the platform has it, so the
3080
- // same id reopened later never re-numbers from zero.
3561
+ // Continue this agent's timeline where the platform has it, so a reopened id never re-numbers from zero.
3081
3562
  resumeFrom: async () => {
3082
- const summary = await apiRequest(this.options, "GET", path16);
3563
+ const summary = await apiRequest(this.options, "GET", path17);
3083
3564
  return summary.agents.find((a) => a.agentId === id)?.nextSeq ?? 0;
3084
3565
  }
3085
3566
  }
@@ -3097,39 +3578,49 @@ var init_session2 = __esm({
3097
3578
  }
3098
3579
  /** The session's latest platform state (one request, no waiting). */
3099
3580
  async status() {
3581
+ return this.refresh(
3582
+ await apiRequest(
3583
+ this.options,
3584
+ "GET",
3585
+ `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}`
3586
+ )
3587
+ );
3588
+ }
3589
+ /** The world started over under the same id, URLs and token, on what its pin (or `version`, which becomes
3590
+ * its pin) resolves to now: base data plus the task's seed. A grade then reads only the new world's requests. */
3591
+ async restart(opts = {}) {
3100
3592
  const fresh = await apiRequest(
3101
3593
  this.options,
3102
- "GET",
3103
- `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}`
3594
+ "POST",
3595
+ `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/restart`,
3596
+ opts.version ? { version: opts.version } : {}
3104
3597
  );
3598
+ this.refresh(fresh);
3599
+ return fresh;
3600
+ }
3601
+ // A status read carries neither the objective nor the open's notices; keep the ones we opened with.
3602
+ refresh(fresh) {
3105
3603
  this.current = {
3106
3604
  instruction: this.current.instruction,
3107
3605
  tools: this.current.tools,
3108
3606
  surfaces: this.current.surfaces,
3109
3607
  task: this.current.task,
3608
+ deprecations: this.current.deprecations,
3110
3609
  ...fresh
3111
3610
  };
3112
3611
  return this.current;
3113
3612
  }
3114
3613
  /**
3115
- * Wait until the container is warm — meaning the process inside it has
3116
- * asked the platform for work, not merely that a job was accepted.
3614
+ * Wait until the session answers calls: a World Host holds it, or the
3615
+ * process inside a pod has asked the platform for work. Throws
3616
+ * `WorldSessionOpenFailed` (with the platform's reason) when it ended
3617
+ * first, and `WorldSessionTimeout` when `timeoutMs` (default ten minutes)
3618
+ * ran out while it was still starting.
3117
3619
  */
3118
3620
  async ready(opts = {}) {
3119
- const deadline = Date.now() + (opts.timeoutMs ?? READY_TIMEOUT_MS);
3120
- for (; ; ) {
3121
- const state2 = await this.status();
3122
- if (state2.ready) return state2;
3123
- if (state2.state === "FAILED" || state2.state === "STOPPED")
3124
- throw new WorldSessionCallError(
3125
- `World session ${state2.state.toLowerCase()} before it was ready.`
3126
- );
3127
- if (Date.now() > deadline)
3128
- throw new WorldSessionTimeout(
3129
- `World session still ${state2.state} after ${Math.round((opts.timeoutMs ?? READY_TIMEOUT_MS) / 1e3)}s.`
3130
- );
3131
- await sleep2(READY_POLL_MS);
3132
- }
3621
+ return new SessionReadiness(this.sessionId, () => this.status()).wait(
3622
+ opts.timeoutMs
3623
+ );
3133
3624
  }
3134
3625
  /** Enqueue one interaction and wait for the container's answer. */
3135
3626
  async exchange(body, timeoutMs) {
@@ -3143,7 +3634,7 @@ var init_session2 = __esm({
3143
3634
  const { callId } = enqueued;
3144
3635
  const judged = enqueued.pending === true;
3145
3636
  const budgetMs = timeoutMs ?? (judged ? JUDGED_GRADE_TIMEOUT_MS : CALL_TIMEOUT_MS);
3146
- const pollMs2 = judged ? JUDGED_GRADE_POLL_MS : CALL_POLL_MS;
3637
+ const pollMs = judged ? JUDGED_GRADE_POLL_MS : CALL_POLL_MS;
3147
3638
  const deadline = Date.now() + budgetMs;
3148
3639
  for (; ; ) {
3149
3640
  const call = await apiRequest(
@@ -3159,7 +3650,7 @@ var init_session2 = __esm({
3159
3650
  throw new WorldSessionTimeout(
3160
3651
  judged ? `Grade ${callId} still ${call.state} after ${Math.round(budgetMs / 1e3)}s \u2014 the judge has not answered; the platform finalizes the call on its own, read it back with export().` : `Call ${callId} still ${call.state} after ${Math.round(budgetMs / 1e3)}s \u2014 the container may have died.`
3161
3652
  );
3162
- await sleep2(pollMs2);
3653
+ await sleep4(pollMs);
3163
3654
  }
3164
3655
  }
3165
3656
  /**
@@ -3208,7 +3699,9 @@ var init_session2 = __esm({
3208
3699
  * calls); assertions and python graders ignore it. `worlds` names the
3209
3700
  * task's other sessions by alias (`{alias: sessionId}`): the platform
3210
3701
  * reads each one's evidence and hands it to the cross-world verifiers
3211
- * anchored on this session, whose grades come back under `verifiers`. */
3702
+ * anchored on this session, whose grades come back under `verifiers`. A
3703
+ * score that is not a number from 0 to 1 is refused by key and value
3704
+ * (`GradeRefused`); a verifier's is that verifier's `error`. */
3212
3705
  async grade(opts = {}) {
3213
3706
  const raw = await this.exchange(
3214
3707
  {
@@ -3218,14 +3711,7 @@ var init_session2 = __esm({
3218
3711
  },
3219
3712
  opts.timeoutMs
3220
3713
  );
3221
- const record = raw && typeof raw === "object" ? raw : {};
3222
- const verifiers = verifierGrades(record.verifiers);
3223
- return {
3224
- ...numericGrade(record),
3225
- ...typeof record.reason === "string" ? { reason: record.reason } : {},
3226
- ...verifiers ? { verifiers } : {},
3227
- raw
3228
- };
3714
+ return { ...GradePayload.read(raw), raw };
3229
3715
  }
3230
3716
  /**
3231
3717
  * Put rows into the LIVE world through its contract, in one batch:
@@ -3257,19 +3743,31 @@ var init_session2 = __esm({
3257
3743
  async reset(opts = {}) {
3258
3744
  await this.exchange({ kind: "reset" }, opts.timeoutMs);
3259
3745
  }
3746
+ /** One page of the session's entries in its world's request ledger, newest
3747
+ * first and without bodies: at most `limit` after `cursor` (the last page's
3748
+ * `nextCursor`). Reading it records nothing in the session. */
3749
+ async requests(opts = {}) {
3750
+ return new WorldRequestLedger(this.options).forSession(
3751
+ this.sessionId,
3752
+ WorldRequestQuery.parse({ cursor: opts.cursor, limit: opts.limit ?? REQUEST_LOG_PAGE_MAX })
3753
+ );
3754
+ }
3755
+ page(route, limit, cursor) {
3756
+ const query = new URLSearchParams({ limit: String(limit) });
3757
+ if (cursor) query.set("cursor", cursor);
3758
+ return apiRequest(
3759
+ this.options,
3760
+ "GET",
3761
+ `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/${route}?${query.toString()}`
3762
+ );
3763
+ }
3260
3764
  /** The session's call log, oldest first: every tool call, seed, reset,
3261
3765
  * grade with its result — the record of the episode. */
3262
3766
  async export() {
3263
3767
  const calls = [];
3264
3768
  let cursor;
3265
3769
  do {
3266
- const params = new URLSearchParams({ limit: String(EXPORT_PAGE) });
3267
- if (cursor) params.set("cursor", cursor);
3268
- const page = await apiRequest(
3269
- this.options,
3270
- "GET",
3271
- `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/calls?${params.toString()}`
3272
- );
3770
+ const page = await this.page("calls", EXPORT_PAGE, cursor);
3273
3771
  for (const call of page.calls) {
3274
3772
  calls.push({
3275
3773
  seq: Number(call.seq),
@@ -3351,6 +3849,7 @@ var init_session2 = __esm({
3351
3849
  "reuseWarm",
3352
3850
  "surfaces",
3353
3851
  "browserTier",
3852
+ "auth",
3354
3853
  "options"
3355
3854
  ]);
3356
3855
  isOpenSessionOptions = (value) => typeof value === "object" && value !== null && Object.keys(value).every((key2) => OPEN_SESSION_OPTION_KEYS.has(key2));
@@ -3465,11 +3964,50 @@ var init_tasks = __esm({
3465
3964
  }
3466
3965
  });
3467
3966
 
3967
+ // src/worlds/taskGrades.ts
3968
+ var TASKS2, compact2, TaskGrades;
3969
+ var init_taskGrades = __esm({
3970
+ "src/worlds/taskGrades.ts"() {
3971
+ "use strict";
3972
+ init_worlds();
3973
+ TASKS2 = "/api/public/world-tasks";
3974
+ compact2 = (body) => Object.fromEntries(Object.entries(body).filter(([, v]) => v !== void 0));
3975
+ TaskGrades = class {
3976
+ constructor(options = {}) {
3977
+ this.options = options;
3978
+ }
3979
+ options;
3980
+ try(sessionId, target) {
3981
+ return apiRequest(
3982
+ this.options,
3983
+ "POST",
3984
+ `${TASKS2}/try`,
3985
+ compact2({ sessionId, ...target })
3986
+ );
3987
+ }
3988
+ regrade(taskId, scope = {}) {
3989
+ return apiRequest(
3990
+ this.options,
3991
+ "POST",
3992
+ `${TASKS2}/${encodeURIComponent(taskId)}/regrade`,
3993
+ compact2({ ...scope })
3994
+ );
3995
+ }
3996
+ };
3997
+ }
3998
+ });
3999
+
3468
4000
  // src/worlds/surfaceDescriptor.ts
3469
4001
  function surfaceDescriptor(s) {
3470
4002
  return {
3471
4003
  surfaces: surfaceKinds(s),
3472
- ...s.api ? { api: { url: s.api.url, ...s.api.token ? { token: s.api.token } : {} } } : {},
4004
+ ...s.api ? {
4005
+ api: {
4006
+ url: s.api.url,
4007
+ ...s.api.token ? { token: s.api.token } : {},
4008
+ ...s.api.auth ? { auth: s.api.auth } : {}
4009
+ }
4010
+ } : {},
3473
4011
  ...s.ui ? { ui: { url: s.ui.url, entry: uiEntryUrl(s.ui), apiPath: s.ui.apiPath ?? null } } : {},
3474
4012
  ...s.browser ? {
3475
4013
  browser: {
@@ -3489,26 +4027,28 @@ var init_surfaceDescriptor = __esm({
3489
4027
 
3490
4028
  // src/worlds/taskSessions.ts
3491
4029
  function aggregateTaskGrade(worlds) {
3492
- const rewards = {};
3493
- const ungraded = [];
3494
- const graded = [];
4030
+ const fold = new TaskGradeFold();
3495
4031
  const verifiers = {};
3496
- const fold = (key2, grade) => {
3497
- if (typeof grade.reward === "number") {
3498
- rewards[key2] = grade.reward;
3499
- graded.push(grade.reward);
3500
- } else ungraded.push(key2);
3501
- for (const [name, value] of Object.entries(grade.rewards))
3502
- rewards[`${key2}.${name}`] = value;
3503
- };
3504
4032
  for (const [alias, grade] of Object.entries(worlds)) {
3505
- fold(alias, grade);
4033
+ fold.add(alias, grade, `world ${alias}`);
3506
4034
  Object.assign(verifiers, grade.verifiers ?? {});
3507
4035
  }
3508
4036
  for (const [name, grade] of Object.entries(verifiers))
3509
- fold(`${VERIFIER_REWARD_PREFIX}${name}`, grade);
3510
- const reward = graded.length > 0 ? graded.reduce((a, b) => a + b, 0) / graded.length : null;
3511
- return { reward, rewards, worlds, ungraded, verifiers };
4037
+ fold.add(`${VERIFIER_REWARD_PREFIX}${name}`, grade, `verifier ${name}`);
4038
+ return {
4039
+ reward: fold.reward(),
4040
+ rewards: fold.rewards,
4041
+ worlds,
4042
+ ungraded: fold.ungraded,
4043
+ verifiers,
4044
+ errors: fold.errors
4045
+ };
4046
+ }
4047
+ function taskGradeError(grade) {
4048
+ const lines = Object.entries(grade.errors).map(
4049
+ ([key2, why]) => `${key2}: ${why}`
4050
+ );
4051
+ return lines.length ? lines.join("; ") : null;
3512
4052
  }
3513
4053
  function fromResponse(answer, options) {
3514
4054
  const sessions2 = {};
@@ -3517,8 +4057,7 @@ function fromResponse(answer, options) {
3517
4057
  sessions2[alias] = new WorldSession(state2.sessionId, state2, options);
3518
4058
  worlds[alias] = {
3519
4059
  slug: state2.slug,
3520
- ref: state2.ref,
3521
- private: state2.private ?? null
4060
+ ref: state2.ref
3522
4061
  };
3523
4062
  }
3524
4063
  return new TaskSessions(
@@ -3593,7 +4132,6 @@ async function attachTask(taskId, options = {}) {
3593
4132
  {
3594
4133
  slug: row.slug ?? "",
3595
4134
  ref: null,
3596
- private: null,
3597
4135
  versionId: row.versionId,
3598
4136
  sessionId: row.sessionId,
3599
4137
  ready: row.ready,
@@ -3623,7 +4161,7 @@ async function attachManifest(manifest, options = {}) {
3623
4161
  Object.fromEntries(
3624
4162
  Object.entries(manifest.sessions).map(([alias, entry]) => [
3625
4163
  alias,
3626
- { slug: entry.slug, ref: entry.ref, private: entry.private ?? null }
4164
+ { slug: entry.slug, ref: entry.ref }
3627
4165
  ])
3628
4166
  )
3629
4167
  );
@@ -3631,12 +4169,13 @@ async function attachManifest(manifest, options = {}) {
3631
4169
  function isTaskManifest(value) {
3632
4170
  return typeof value === "object" && value !== null && !Array.isArray(value) && typeof value.sessions === "object" && value.sessions !== null && !("instruction" in value && "worlds" in value);
3633
4171
  }
3634
- var TASK_SESSIONS, VERIFIER_REWARD_PREFIX, manifestSession, TaskSessions;
4172
+ var TASK_SESSIONS, VERIFIER_REWARD_PREFIX, manifestSession, TaskGradeFold, TaskSessions;
3635
4173
  var init_taskSessions = __esm({
3636
4174
  "src/worlds/taskSessions.ts"() {
3637
4175
  "use strict";
3638
4176
  init_worlds();
3639
4177
  init_browser();
4178
+ init_grade();
3640
4179
  init_surfaceDescriptor();
3641
4180
  init_session2();
3642
4181
  TASK_SESSIONS = "/api/public/world-task-sessions";
@@ -3644,13 +4183,42 @@ var init_taskSessions = __esm({
3644
4183
  manifestSession = (s, state2, world) => ({
3645
4184
  slug: world.slug,
3646
4185
  ref: world.ref,
3647
- private: world.private,
3648
4186
  versionId: state2.versionId,
3649
4187
  sessionId: state2.sessionId,
3650
4188
  ready: state2.ready,
3651
4189
  state: state2.state,
3652
4190
  ...surfaceDescriptor(s)
3653
4191
  });
4192
+ TaskGradeFold = class {
4193
+ rewards = {};
4194
+ ungraded = [];
4195
+ errors = {};
4196
+ sources = /* @__PURE__ */ new Map();
4197
+ graded = [];
4198
+ add(key2, grade, source) {
4199
+ if (grade.error) this.errors[key2] = grade.error;
4200
+ if (typeof grade.reward === "number") {
4201
+ this.put(key2, grade.reward, source);
4202
+ this.graded.push(grade.reward);
4203
+ } else this.ungraded.push(key2);
4204
+ for (const [name, value] of Object.entries(grade.rewards))
4205
+ this.put(`${key2}.${name}`, value, source);
4206
+ }
4207
+ reward() {
4208
+ if (Object.keys(this.errors).length > 0 || !this.graded.length)
4209
+ return null;
4210
+ return this.graded.reduce((a, b) => a + b, 0) / this.graded.length;
4211
+ }
4212
+ put(key2, value, source) {
4213
+ const first = this.sources.get(key2) ?? source;
4214
+ this.sources.set(key2, first);
4215
+ if (first !== source) {
4216
+ this.errors[key2] = `two rewards are named ${key2} (${first} and ${source}); rename one of them`;
4217
+ return;
4218
+ }
4219
+ this.rewards[key2] = value;
4220
+ }
4221
+ };
3654
4222
  TaskSessions = class {
3655
4223
  constructor(taskId, taskVersion, name, instruction, sessions2, worlds, hash = null) {
3656
4224
  this.taskId = taskId;
@@ -3671,7 +4239,7 @@ var init_taskSessions = __esm({
3671
4239
  /** This alias's world as recorded at open/attach — what a `TaskRun`
3672
4240
  * filing needs to name, without exposing the whole map. */
3673
4241
  worldRef(alias) {
3674
- return this.worlds[alias] ?? { slug: "", ref: null, private: null };
4242
+ return this.worlds[alias] ?? { slug: "", ref: null };
3675
4243
  }
3676
4244
  /** The aliases, in the spec's order. */
3677
4245
  get aliases() {
@@ -3729,11 +4297,13 @@ var init_taskSessions = __esm({
3729
4297
  * agent's own account of the whole investigation) goes to every world's
3730
4298
  * judge; a world graded by assertions or python ignores it. Each grade
3731
4299
  * names the task's other sessions by alias, so the cross-world verifiers
3732
- * anchored on that world can read them. */
4300
+ * anchored on that world can read them. A world whose grade call fails is
4301
+ * that world's error: the task's grade names it and keeps every other
4302
+ * world's grade. */
3733
4303
  async grade(opts = {}) {
3734
4304
  return aggregateTaskGrade(
3735
4305
  await this.each(
3736
- (session, alias) => session.grade({ ...opts, worlds: this.otherSessions(alias) })
4306
+ (session, alias) => session.grade({ ...opts, worlds: this.otherSessions(alias) }).catch((error) => GradePayload.failedCall(error))
3737
4307
  )
3738
4308
  );
3739
4309
  }
@@ -3781,12 +4351,16 @@ var init_evals = __esm({
3781
4351
  "src/worlds/evals.ts"() {
3782
4352
  "use strict";
3783
4353
  init_worlds();
4354
+ init_transport();
3784
4355
  EVALUATIONS = "/api/public/benchmark-containers/evaluations";
3785
4356
  GatewayEvalsClient = class {
3786
- constructor(options = {}) {
4357
+ constructor(options = {}, retry = RetryPolicy.FILING) {
3787
4358
  this.options = options;
4359
+ this.retry = retry;
3788
4360
  }
3789
4361
  options;
4362
+ retry;
4363
+ keyed = /* @__PURE__ */ new Set();
3790
4364
  async createEvaluation(versionId, opts = {}) {
3791
4365
  const body = { versionId };
3792
4366
  if (opts.model !== void 0) body.model = opts.model;
@@ -3794,12 +4368,18 @@ var init_evals = __esm({
3794
4368
  if (opts.rolloutsPerExample !== void 0)
3795
4369
  body.rolloutsPerExample = opts.rolloutsPerExample;
3796
4370
  if (opts.metadata !== void 0) body.metadata = opts.metadata;
4371
+ if (opts.idempotencyKey !== void 0)
4372
+ body.idempotencyKey = opts.idempotencyKey;
3797
4373
  const answer = await apiRequest(
3798
4374
  this.options,
3799
4375
  "POST",
3800
4376
  EVALUATIONS,
3801
- body
4377
+ body,
4378
+ {
4379
+ retry: opts.idempotencyKey === void 0 ? RetryPolicy.NONE : this.retry
4380
+ }
3802
4381
  );
4382
+ if (opts.idempotencyKey !== void 0) this.keyed.add(answer.evaluationId);
3803
4383
  return answer.evaluationId;
3804
4384
  }
3805
4385
  async pushSamples(evaluationId, samples) {
@@ -3807,7 +4387,8 @@ var init_evals = __esm({
3807
4387
  this.options,
3808
4388
  "POST",
3809
4389
  `${EVALUATIONS}/${encodeURIComponent(evaluationId)}/samples`,
3810
- { samples }
4390
+ { samples },
4391
+ { retry: this.retryFor(evaluationId) }
3811
4392
  );
3812
4393
  return answer.inserted ?? samples.length;
3813
4394
  }
@@ -3820,10 +4401,297 @@ var init_evals = __esm({
3820
4401
  this.options,
3821
4402
  "POST",
3822
4403
  `${EVALUATIONS}/${encodeURIComponent(evaluationId)}/finalize`,
3823
- body
4404
+ body,
4405
+ { retry: this.retryFor(evaluationId) }
3824
4406
  );
3825
4407
  return answer.status;
3826
4408
  }
4409
+ retryFor(evaluationId) {
4410
+ return this.keyed.has(evaluationId) ? this.retry : RetryPolicy.NONE;
4411
+ }
4412
+ };
4413
+ }
4414
+ });
4415
+
4416
+ // src/worlds/runSignals.ts
4417
+ import { constants } from "os";
4418
+ var OWNER, RunSignals;
4419
+ var init_runSignals = __esm({
4420
+ "src/worlds/runSignals.ts"() {
4421
+ "use strict";
4422
+ OWNER = /* @__PURE__ */ Symbol("RunSignals");
4423
+ RunSignals = class _RunSignals {
4424
+ constructor(target = process) {
4425
+ this.target = target;
4426
+ }
4427
+ target;
4428
+ static SIGNALS = ["SIGINT", "SIGTERM"];
4429
+ cleanups = [];
4430
+ heardSignal = null;
4431
+ heardCount = 0;
4432
+ listening = false;
4433
+ left = false;
4434
+ listener = Object.assign(
4435
+ (signal) => this.heard(signal),
4436
+ { [OWNER]: this }
4437
+ );
4438
+ /** The signal that arrived, once one has: start nothing new. */
4439
+ get signal() {
4440
+ return this.owner().heardSignal;
4441
+ }
4442
+ async during(cleanup, work) {
4443
+ return this.owner().hold(cleanup, work);
4444
+ }
4445
+ owner() {
4446
+ const owners = this.target.listeners("SIGINT").map((listener) => listener[OWNER]);
4447
+ return owners.find((owner) => owner !== void 0) ?? this;
4448
+ }
4449
+ async hold(cleanup, work) {
4450
+ this.listen();
4451
+ this.cleanups.push(cleanup);
4452
+ try {
4453
+ return await work();
4454
+ } finally {
4455
+ this.cleanups.splice(this.cleanups.indexOf(cleanup), 1);
4456
+ if (!this.cleanups.length && this.heardSignal === null) this.unlisten();
4457
+ }
4458
+ }
4459
+ heard(signal) {
4460
+ this.heardCount += 1;
4461
+ if (this.heardCount > 2) return this.leave(signal);
4462
+ this.heardSignal ??= signal;
4463
+ void this.cleanUp(signal, this.heardCount === 2).finally(() => this.leave(signal));
4464
+ }
4465
+ async cleanUp(signal, urgent) {
4466
+ for (const cleanup of [...this.cleanups].reverse())
4467
+ await Promise.resolve().then(() => cleanup(signal, urgent)).catch(() => void 0);
4468
+ }
4469
+ leave(signal) {
4470
+ if (this.left) return;
4471
+ this.left = true;
4472
+ this.unlisten();
4473
+ if (this.target.listenerCount(signal) === 0)
4474
+ this.target.exit(128 + constants.signals[signal]);
4475
+ }
4476
+ listen() {
4477
+ if (this.listening) return;
4478
+ this.listening = true;
4479
+ for (const signal of _RunSignals.SIGNALS)
4480
+ this.target.on(signal, this.listener);
4481
+ }
4482
+ unlisten() {
4483
+ this.listening = false;
4484
+ for (const signal of _RunSignals.SIGNALS)
4485
+ this.target.off(signal, this.listener);
4486
+ }
4487
+ };
4488
+ }
4489
+ });
4490
+
4491
+ // src/worlds/taskRunDir.ts
4492
+ import * as fs from "fs";
4493
+ import * as path from "path";
4494
+ function sessionRecord({ api: api2, ui, browser, ...session }) {
4495
+ return {
4496
+ ...session,
4497
+ ...api2 ? { api: { url: api2.url } } : {},
4498
+ ...ui ? { ui: { ...ui, entry: withoutUiToken(ui.entry) } } : {},
4499
+ ...browser ? { browser: browserRecord(browser) } : {}
4500
+ };
4501
+ }
4502
+ var TaskRunDir, browserRecord;
4503
+ var init_taskRunDir = __esm({
4504
+ "src/worlds/taskRunDir.ts"() {
4505
+ "use strict";
4506
+ init_browser();
4507
+ TaskRunDir = class {
4508
+ constructor(path17) {
4509
+ this.path = path17;
4510
+ }
4511
+ path;
4512
+ writeManifest(manifest) {
4513
+ this.writeJson("manifest.json", {
4514
+ ...manifest,
4515
+ sessions: Object.fromEntries(
4516
+ Object.entries(manifest.sessions).map(([alias, session]) => [
4517
+ alias,
4518
+ sessionRecord(session)
4519
+ ])
4520
+ )
4521
+ });
4522
+ }
4523
+ writeJson(name, value) {
4524
+ this.write(name, JSON.stringify(value, null, 2));
4525
+ }
4526
+ write(name, text2) {
4527
+ fs.mkdirSync(this.path, { recursive: true });
4528
+ fs.writeFileSync(path.join(this.path, name), text2);
4529
+ }
4530
+ };
4531
+ browserRecord = ({ viewport, tier }) => ({
4532
+ viewport,
4533
+ ...tier ? { tier } : {}
4534
+ });
4535
+ }
4536
+ });
4537
+
4538
+ // src/worlds/taskRunOutcome.ts
4539
+ var TaskRunOutcome;
4540
+ var init_taskRunOutcome = __esm({
4541
+ "src/worlds/taskRunOutcome.ts"() {
4542
+ "use strict";
4543
+ init_grade();
4544
+ init_taskSessions();
4545
+ TaskRunOutcome = class {
4546
+ constructor(runId, live, model, runDir) {
4547
+ this.runId = runId;
4548
+ this.live = live;
4549
+ this.model = model;
4550
+ this.runDir = runDir;
4551
+ }
4552
+ runId;
4553
+ live;
4554
+ model;
4555
+ runDir;
4556
+ report = null;
4557
+ extra = {};
4558
+ notes = {};
4559
+ agentError = null;
4560
+ grade = null;
4561
+ traced = false;
4562
+ runError = null;
4563
+ fileError = null;
4564
+ evaluationId;
4565
+ evaluationStatus = null;
4566
+ started = Date.now();
4567
+ stopped(error) {
4568
+ this.runError ??= messageOf(error).slice(0, 2e3);
4569
+ }
4570
+ agentRaised(error) {
4571
+ this.agentError = messageOf(error).slice(0, 2e3);
4572
+ }
4573
+ failure() {
4574
+ const reasons = [
4575
+ this.agentError === null ? null : `agent raised: ${this.agentError}`,
4576
+ this.runError === null ? null : `the run stopped: ${this.runError}`,
4577
+ this.gradeError(),
4578
+ this.grade === null && this.runError === null ? "the run stopped before it was graded" : null
4579
+ ].filter((reason) => reason !== null);
4580
+ return reasons.length ? reasons.join("; ") : null;
4581
+ }
4582
+ async file(evals, setRunId) {
4583
+ let created;
4584
+ try {
4585
+ created = await evals.createEvaluation(this.ref(this.live.aliases[0]).versionId, {
4586
+ model: this.model,
4587
+ rolloutsPerExample: 1,
4588
+ idempotencyKey: this.runId,
4589
+ ...setRunId ? { runId: setRunId } : {},
4590
+ metadata: this.metadata()
4591
+ });
4592
+ await evals.pushSamples(created, [this.sample()]);
4593
+ this.evaluationStatus = await evals.finalizeEvaluation(created, this.finalized());
4594
+ this.evaluationId = created;
4595
+ } catch (error) {
4596
+ this.fileError = created ? `evaluation ${created}: ${messageOf(error)}` : messageOf(error);
4597
+ if (created)
4598
+ await evals.finalizeEvaluation(created, { status: "FAILED", metrics: { error: this.fileError } }).catch(() => void 0);
4599
+ }
4600
+ }
4601
+ summary() {
4602
+ const live = this.live;
4603
+ const { evaluationId: _agentEvaluationId, ...extra } = this.extra;
4604
+ return {
4605
+ ...extra,
4606
+ runId: this.runId,
4607
+ taskId: live.taskId,
4608
+ taskVersion: live.taskVersion,
4609
+ name: live.name,
4610
+ instruction: live.instruction ?? "",
4611
+ model: this.model,
4612
+ aliases: live.aliases,
4613
+ reward: this.grade?.reward ?? null,
4614
+ rewards: this.grade?.rewards ?? {},
4615
+ ungraded: this.grade?.ungraded ?? live.aliases,
4616
+ agentError: this.agentError,
4617
+ runError: this.runError,
4618
+ gradeError: this.gradeError(),
4619
+ fileError: this.fileError,
4620
+ evaluationStatus: this.evaluationStatus,
4621
+ report: this.report,
4622
+ traced: this.traced,
4623
+ runDir: this.runDir,
4624
+ durationSeconds: Math.round((Date.now() - this.started) / 10) / 100,
4625
+ notes: this.notes,
4626
+ filed: this.evaluationId !== void 0,
4627
+ ...this.evaluationId ? { evaluationId: this.evaluationId } : {}
4628
+ };
4629
+ }
4630
+ gradeError() {
4631
+ return this.grade ? taskGradeError(this.grade) : null;
4632
+ }
4633
+ ref(alias) {
4634
+ const { slug, ref } = this.live.worldRef(alias);
4635
+ const session = this.live.sessions[alias];
4636
+ return { slug, ref, versionId: session.versionId, sessionId: session.sessionId };
4637
+ }
4638
+ metadata() {
4639
+ const live = this.live;
4640
+ return {
4641
+ source: "worlds-task-run",
4642
+ task: { id: live.taskId, version: live.taskVersion, name: live.name, hash: live.hash },
4643
+ anchor: live.aliases[0],
4644
+ worlds: Object.fromEntries(live.aliases.map((alias) => [alias, this.ref(alias)])),
4645
+ runId: this.runId
4646
+ };
4647
+ }
4648
+ sample() {
4649
+ const live = this.live;
4650
+ const reward = this.grade?.reward ?? null;
4651
+ const gradeError = this.gradeError();
4652
+ const sample = {
4653
+ exampleId: live.name ?? live.taskId ?? this.runId,
4654
+ task: live.name ?? live.taskId ?? this.runId,
4655
+ rolloutIndex: 0,
4656
+ prompt: live.instruction,
4657
+ ...this.report === null ? {} : { completion: this.report },
4658
+ rewards: this.grade?.rewards ?? {},
4659
+ info: {
4660
+ sessionId: this.runId,
4661
+ worlds: Object.fromEntries(
4662
+ live.aliases.map((alias) => [
4663
+ alias,
4664
+ { ...this.ref(alias), reward: this.grade?.worlds[alias]?.reward ?? null }
4665
+ ])
4666
+ ),
4667
+ ungraded: this.grade?.ungraded ?? live.aliases,
4668
+ verifierVersion: live.taskVersion,
4669
+ traced: this.traced,
4670
+ runDir: this.runDir,
4671
+ ...this.agentError ? { agentError: this.agentError } : {},
4672
+ ...this.runError ? { runError: this.runError } : {},
4673
+ ...gradeError ? { verifyError: gradeError } : {}
4674
+ }
4675
+ };
4676
+ if (typeof reward === "number")
4677
+ Object.assign(sample, { reward, score: reward, correct: reward >= 1 });
4678
+ return sample;
4679
+ }
4680
+ finalized() {
4681
+ const reward = this.grade?.reward ?? null;
4682
+ const failure = this.failure();
4683
+ return {
4684
+ status: failure ? "FAILED" : "COMPLETED",
4685
+ metrics: {
4686
+ ...typeof reward === "number" ? { avg_reward: reward } : {},
4687
+ reward,
4688
+ ...Object.fromEntries(
4689
+ Object.entries(this.grade?.rewards ?? {}).map(([key2, value]) => [`rewards.${key2}`, value])
4690
+ ),
4691
+ ...failure ? { error: failure } : {}
4692
+ }
4693
+ };
4694
+ }
3827
4695
  };
3828
4696
  }
3829
4697
  });
@@ -3836,7 +4704,7 @@ function getEnv(key2) {
3836
4704
  function isGatewayConfigured() {
3837
4705
  return !!(getEnv(GATEWAY_ENV.HOST) && getEnv(GATEWAY_ENV.PUBLIC_KEY) && getEnv(GATEWAY_ENV.SECRET_KEY));
3838
4706
  }
3839
- var GATEWAY_ENV, OPENTELEMETRY_PEERS, MODULE_NOT_FOUND, OpenTelemetryMissing;
4707
+ var GATEWAY_ENV, OTLP_TRACES_PATH, OPENTELEMETRY_PEERS, PINNED_PEERS, MODULE_NOT_FOUND, OpenTelemetryMissing;
3840
4708
  var init_prerequisites = __esm({
3841
4709
  "src/tracing/prerequisites.ts"() {
3842
4710
  "use strict";
@@ -3844,21 +4712,25 @@ var init_prerequisites = __esm({
3844
4712
  HOST: "GATEWAY_HOST",
3845
4713
  PUBLIC_KEY: "GATEWAY_PUBLIC_KEY",
3846
4714
  SECRET_KEY: "GATEWAY_SECRET_KEY",
4715
+ API_KEY: "GATEWAY_API_KEY",
3847
4716
  ENDPOINT: "GATEWAY_OTLP_ENDPOINT"
3848
4717
  };
3849
- OPENTELEMETRY_PEERS = [
3850
- "@opentelemetry/api",
3851
- "@opentelemetry/exporter-trace-otlp-http",
3852
- "@opentelemetry/resources",
3853
- "@opentelemetry/sdk-trace-base",
3854
- "@opentelemetry/sdk-trace-node"
3855
- ];
4718
+ OTLP_TRACES_PATH = "/api/public/otel/v1/traces";
4719
+ OPENTELEMETRY_PEERS = {
4720
+ "@opentelemetry/api": "1.9.0",
4721
+ "@opentelemetry/exporter-trace-otlp-http": "0.222.0",
4722
+ "@opentelemetry/resources": "2.11.0",
4723
+ "@opentelemetry/sdk-trace-base": "2.11.0",
4724
+ "@opentelemetry/sdk-trace-node": "2.11.0"
4725
+ };
4726
+ PINNED_PEERS = Object.entries(OPENTELEMETRY_PEERS).map(([name, version]) => `${name}@${version}`).join(" ");
3856
4727
  MODULE_NOT_FOUND = /* @__PURE__ */ new Set(["MODULE_NOT_FOUND", "ERR_MODULE_NOT_FOUND"]);
3857
4728
  OpenTelemetryMissing = class _OpenTelemetryMissing extends Error {
3858
4729
  constructor() {
3859
4730
  super(
3860
- `OpenTelemetry packages not found. Install them with:
3861
- npm install ${OPENTELEMETRY_PEERS.join(" ")}`
4731
+ `OpenTelemetry packages not found. Install them next to @withgateway/sdk, at the versions it is tested with:
4732
+ npm install ${PINNED_PEERS}
4733
+ npm install -g ${PINNED_PEERS} (the gateway CLI, when it was installed with npm install -g)`
3862
4734
  );
3863
4735
  this.name = "OpenTelemetryMissing";
3864
4736
  }
@@ -4171,7 +5043,7 @@ var require_package = __commonJS({
4171
5043
  "package.json"(exports, module) {
4172
5044
  module.exports = {
4173
5045
  name: "@withgateway/sdk",
4174
- version: "0.3.1",
5046
+ version: "0.4.0",
4175
5047
  description: "Gateway SDK for TypeScript - A/B experiments, tracing, and observability",
4176
5048
  main: "./dist/index.js",
4177
5049
  module: "./dist/index.mjs",
@@ -4679,7 +5551,7 @@ function buildProvider(config, logFn) {
4679
5551
  const host = config.host ?? getEnv(GATEWAY_ENV.HOST);
4680
5552
  const publicKey = config.publicKey ?? getEnv(GATEWAY_ENV.PUBLIC_KEY);
4681
5553
  const secretKey = config.secretKey ?? getEnv(GATEWAY_ENV.SECRET_KEY);
4682
- const endpoint = config.endpoint ?? getEnv(GATEWAY_ENV.ENDPOINT) ?? (host ? `${host.replace(/\/$/, "")}${DEFAULT_OTLP_PATH}` : void 0);
5554
+ const endpoint = config.endpoint ?? getEnv(GATEWAY_ENV.ENDPOINT) ?? (host ? `${host.replace(/\/$/, "")}${OTLP_TRACES_PATH}` : void 0);
4683
5555
  const missing = [];
4684
5556
  if (!host) missing.push("host (or GATEWAY_HOST env var)");
4685
5557
  if (!publicKey) missing.push("publicKey (or GATEWAY_PUBLIC_KEY env var)");
@@ -4922,7 +5794,7 @@ async function shutdown2() {
4922
5794
  function isInitialized() {
4923
5795
  return state.initialized;
4924
5796
  }
4925
- var DEFAULT_OTLP_PATH, state;
5797
+ var state;
4926
5798
  var init_init = __esm({
4927
5799
  "src/tracing/init.ts"() {
4928
5800
  "use strict";
@@ -4933,7 +5805,6 @@ var init_init = __esm({
4933
5805
  init_build();
4934
5806
  init_prerequisites();
4935
5807
  init_prerequisites();
4936
- DEFAULT_OTLP_PATH = "/api/public/otel/v1/traces";
4937
5808
  state = {
4938
5809
  initialized: false,
4939
5810
  provider: null
@@ -4942,39 +5813,78 @@ var init_init = __esm({
4942
5813
  });
4943
5814
 
4944
5815
  // src/worlds/taskTracing.ts
4945
- var TaskTracing;
5816
+ var HOST_WITH_AUTHORITY, TRACING_HELD_ELSEWHERE, TaskTracing;
4946
5817
  var init_taskTracing = __esm({
4947
5818
  "src/worlds/taskTracing.ts"() {
4948
5819
  "use strict";
4949
5820
  init_prerequisites();
5821
+ init_platformEndpoint();
5822
+ HOST_WITH_AUTHORITY = /^[a-z][a-z0-9+.-]*:\/\/[^/\\?#@\s]+(\/|$)/i;
5823
+ TRACING_HELD_ELSEWHERE = "Tracing in this process already sends spans to another destination or with other keys (an earlier run, or the agent's own tracing.init()), so this run's spans would not reach its own project.";
4950
5824
  TaskTracing = class _TaskTracing {
4951
5825
  constructor(load = () => Promise.resolve().then(() => (init_init(), init_exports))) {
4952
5826
  this.load = load;
4953
5827
  }
4954
5828
  load;
4955
5829
  static warned = false;
4956
- async start(requested) {
4957
- if (!requested || !isGatewayConfigured()) return false;
5830
+ static target = null;
5831
+ async start(requested, options) {
5832
+ if (!requested) return false;
5833
+ const endpoint = platformEndpoint(options);
4958
5834
  try {
4959
- (await this.load()).init();
5835
+ await this.initOnce(_TaskTracing.config(endpoint));
4960
5836
  return true;
4961
5837
  } catch (error) {
4962
- _TaskTracing.warnOnce(error);
5838
+ _TaskTracing.warnOnce(_TaskTracing.reason(error, endpoint));
4963
5839
  return false;
4964
5840
  }
4965
5841
  }
4966
- static warnOnce(error) {
5842
+ // init() keeps the first provider for the whole process and ignores later calls, so a later run is
5843
+ // traced only when it exports to the same place with the same keys.
5844
+ async initOnce(config) {
5845
+ const tracing2 = await this.load();
5846
+ const target = JSON.stringify([config.endpoint, config.publicKey, config.secretKey]);
5847
+ if (!tracing2.isInitialized()) {
5848
+ tracing2.init(config);
5849
+ _TaskTracing.target = target;
5850
+ return;
5851
+ }
5852
+ if (_TaskTracing.target !== target) throw new Error(TRACING_HELD_ELSEWHERE);
5853
+ }
5854
+ static config(endpoint) {
5855
+ if (!endpoint) throw new Error(GATEWAY_KEYS_MISSING);
5856
+ return { ...endpoint, endpoint: _TaskTracing.destination(endpoint) };
5857
+ }
5858
+ // B1: a saved login's keys go to their own host only. The redirect is compared as text, never parsed:
5859
+ // a fixed "<host>/" prefix leaves no URL parser room to read another host into it.
5860
+ static destination(endpoint) {
5861
+ const redirect = getEnv(GATEWAY_ENV.ENDPOINT);
5862
+ if (!redirect) return `${endpoint.host}${OTLP_TRACES_PATH}`;
5863
+ if (_TaskTracing.underHost(redirect, endpoint.host) || _TaskTracing.environmentKeys(endpoint)) return redirect;
5864
+ throw new Error(
5865
+ `GATEWAY_OTLP_ENDPOINT is not under ${endpoint.host}, and this run's keys are not GATEWAY_PUBLIC_KEY / GATEWAY_SECRET_KEY: they are sent to ${endpoint.host} only. Unset GATEWAY_OTLP_ENDPOINT, or set both keys in the environment.`
5866
+ );
5867
+ }
5868
+ static underHost(redirect, host) {
5869
+ return HOST_WITH_AUTHORITY.test(host) && redirect.startsWith(`${host}/`);
5870
+ }
5871
+ static environmentKeys(endpoint) {
5872
+ const secretKey = getEnv(GATEWAY_ENV.SECRET_KEY) ?? getEnv(GATEWAY_ENV.API_KEY);
5873
+ return endpoint.publicKey === getEnv(GATEWAY_ENV.PUBLIC_KEY) && endpoint.secretKey === secretKey;
5874
+ }
5875
+ static warnOnce(reason) {
4967
5876
  if (_TaskTracing.warned) return;
4968
5877
  _TaskTracing.warned = true;
4969
5878
  console.warn(
4970
- `[gatewaysdk.tracing] Task runs in this process are not traced. ${_TaskTracing.reason(error)}
5879
+ `[gatewaysdk.tracing] Task runs in this process are not traced. ${reason}
4971
5880
  Pass --no-trace (trace: false) to run untraced without this warning.`
4972
5881
  );
4973
5882
  }
4974
- static reason(error) {
4975
- if (OpenTelemetryMissing.explains(error))
4976
- return new OpenTelemetryMissing().message;
4977
- return error instanceof Error ? error.message : String(error);
5883
+ static reason(error, endpoint) {
5884
+ if (OpenTelemetryMissing.explains(error)) return new OpenTelemetryMissing().message;
5885
+ const message = error instanceof Error ? error.message : String(error);
5886
+ const keys = endpoint ? [endpoint.publicKey, endpoint.secretKey] : [];
5887
+ return keys.reduce((text2, key2) => text2.split(key2).join("[redacted]"), message);
4978
5888
  }
4979
5889
  };
4980
5890
  }
@@ -4982,87 +5892,17 @@ Pass --no-trace (trace: false) to run untraced without this warning.`
4982
5892
 
4983
5893
  // src/worlds/taskRun.ts
4984
5894
  import { randomBytes } from "crypto";
4985
- import * as fs from "fs";
4986
- import * as path from "path";
4987
- function worldRef(live, alias) {
4988
- const { slug, ref } = live.worldRef(alias);
4989
- const session = live.sessions[alias];
4990
- return {
4991
- slug,
4992
- ref,
4993
- versionId: session.versionId,
4994
- sessionId: session.sessionId
4995
- };
4996
- }
4997
- async function fileTaskRun(live, runId, model, report, grade, agentError, traced, runDir, options, setRunId) {
4998
- const aliases = live.aliases;
4999
- const anchor = aliases[0];
5000
- const worldsMeta = Object.fromEntries(
5001
- aliases.map((alias) => [alias, worldRef(live, alias)])
5002
- );
5003
- const evals = new GatewayEvalsClient(options);
5004
- const evaluationId = await evals.createEvaluation(
5005
- worldRef(live, anchor).versionId,
5006
- {
5007
- model,
5008
- rolloutsPerExample: 1,
5009
- ...setRunId ? { runId: setRunId } : {},
5010
- metadata: {
5011
- source: "worlds-task-run",
5012
- task: {
5013
- id: live.taskId,
5014
- version: live.taskVersion,
5015
- name: live.name,
5016
- hash: live.hash
5017
- },
5018
- anchor,
5019
- worlds: worldsMeta,
5020
- runId
5021
- }
5022
- }
5023
- );
5024
- const reward = grade.reward;
5025
- const sample = {
5026
- exampleId: live.name ?? live.taskId ?? runId,
5027
- task: live.name ?? live.taskId ?? runId,
5028
- rolloutIndex: 0,
5029
- prompt: live.instruction,
5030
- ...report === null ? {} : { completion: report },
5031
- rewards: grade.rewards,
5032
- info: {
5033
- sessionId: runId,
5034
- worlds: Object.fromEntries(
5035
- aliases.map((alias) => [
5036
- alias,
5037
- {
5038
- ...worldRef(live, alias),
5039
- reward: grade.worlds[alias]?.reward ?? null
5040
- }
5041
- ])
5042
- ),
5043
- ungraded: grade.ungraded,
5044
- traced,
5045
- runDir,
5046
- ...agentError ? { agentError } : {}
5047
- }
5048
- };
5049
- if (typeof reward === "number") {
5050
- sample.reward = reward;
5051
- sample.score = reward;
5052
- sample.correct = reward >= 1;
5053
- }
5054
- await evals.pushSamples(evaluationId, [sample]);
5055
- await evals.finalizeEvaluation(evaluationId, {
5056
- status: agentError ? "FAILED" : "COMPLETED",
5057
- metrics: {
5058
- ...typeof reward === "number" ? { avg_reward: reward } : {},
5059
- reward,
5060
- ...Object.fromEntries(
5061
- Object.entries(grade.rewards).map(([k, v]) => [`rewards.${k}`, v])
5062
- )
5063
- }
5064
- });
5065
- return evaluationId;
5895
+ import * as path2 from "path";
5896
+ function taskRunFailure(summary) {
5897
+ if (summary.agentError !== null) return `agent raised: ${summary.agentError}`;
5898
+ if (summary.runError !== null) return `the run stopped: ${summary.runError}`;
5899
+ if (summary.gradeError !== null)
5900
+ return `the task could not be graded: ${summary.gradeError}`;
5901
+ if (summary.fileError !== null)
5902
+ return `the run could not be filed: ${summary.fileError}`;
5903
+ if (summary.filed && summary.evaluationStatus !== "COMPLETED")
5904
+ return `the platform settled evaluation ${summary.evaluationId} as ${summary.evaluationStatus}`;
5905
+ return null;
5066
5906
  }
5067
5907
  function reportFromResult(result) {
5068
5908
  if (result === void 0 || result === null)
@@ -5080,110 +5920,47 @@ function reportFromResult(result) {
5080
5920
  );
5081
5921
  return { report, extra };
5082
5922
  }
5923
+ async function refuseUnreadTools(live) {
5924
+ try {
5925
+ for (const alias of live.aliases)
5926
+ WorldToolsUnread.refuse(`${live.worldRef(alias).slug} (alias ${alias})`, live.session(alias).deprecations);
5927
+ } catch (error) {
5928
+ await live.close({ keepWarm: false }).catch(() => void 0);
5929
+ throw error;
5930
+ }
5931
+ }
5083
5932
  async function runTask(ref, agent, opts) {
5084
5933
  const runId = `wtr-${randomBytes(6).toString("hex")}`;
5085
- const outDir = opts.outDir ?? "runs";
5086
- const runDir = path.join(outDir, runId);
5087
- fs.mkdirSync(runDir, { recursive: true });
5088
5934
  const options = opts.options ?? {};
5089
- const live = await openTask(ref, {
5090
- surfaces: opts.surfaces,
5091
- reuseWarm: opts.reuseWarm,
5092
- browserTier: opts.browserTier,
5093
- options
5094
- });
5095
- const started = Date.now();
5096
- try {
5097
- await live.ready();
5098
- const traced = await new TaskTracing().start(opts.trace !== false);
5099
- const taskRun = new TaskRun(
5100
- runId,
5101
- live.instruction ?? "",
5102
- opts.model,
5103
- live.sessions,
5104
- await live.manifest()
5105
- );
5106
- let agentError = null;
5107
- let report = null;
5108
- let extra = {};
5109
- try {
5110
- const invoke = () => agent(taskRun);
5111
- const result = traced ? await (await Promise.resolve().then(() => (init_session(), session_exports))).withSession(runId, invoke) : await invoke();
5112
- ({ report, extra } = reportFromResult(result));
5113
- } catch (error) {
5114
- const message = (error instanceof Error ? error.message : String(error)) || "Unknown error";
5115
- agentError = message.slice(0, 2e3);
5116
- }
5117
- if (traced)
5118
- await Promise.resolve().then(() => (init_init(), init_exports)).then((tracing2) => tracing2.flush()).catch(() => void 0);
5119
- const grade = report !== null ? await live.grade({ report }) : await live.grade();
5120
- fs.writeFileSync(
5121
- path.join(runDir, "manifest.json"),
5122
- JSON.stringify(taskRun.manifest, null, 2)
5123
- );
5124
- fs.writeFileSync(
5125
- path.join(runDir, "grades.json"),
5126
- JSON.stringify(grade, null, 2)
5127
- );
5128
- if (report) fs.writeFileSync(path.join(runDir, "report.md"), report);
5129
- const summary = {
5130
- runId,
5131
- taskId: live.taskId,
5132
- taskVersion: live.taskVersion,
5133
- name: live.name,
5134
- instruction: taskRun.instruction,
5135
- model: opts.model,
5136
- aliases: live.aliases,
5137
- reward: grade.reward,
5138
- rewards: grade.rewards,
5139
- ungraded: grade.ungraded,
5140
- agentError,
5141
- report,
5142
- traced,
5143
- runDir,
5144
- durationSeconds: Math.round((Date.now() - started) / 10) / 100,
5145
- notes: taskRun.notes,
5146
- filed: false,
5147
- ...extra
5148
- };
5149
- if (opts.file !== false) {
5150
- summary.evaluationId = await fileTaskRun(
5151
- live,
5152
- runId,
5153
- opts.model,
5154
- report,
5155
- grade,
5156
- agentError,
5157
- traced,
5158
- runDir,
5159
- options,
5160
- opts.setRunId
5161
- );
5162
- summary.filed = true;
5163
- }
5164
- fs.writeFileSync(
5165
- path.join(runDir, "run.json"),
5166
- JSON.stringify(summary, null, 2)
5167
- );
5168
- return summary;
5169
- } finally {
5170
- if (!opts.keepUp) {
5171
- try {
5172
- await live.close({ keepWarm: false });
5173
- } catch {
5174
- }
5175
- }
5176
- }
5935
+ const opening = new TaskOpening(
5936
+ openTask(ref, {
5937
+ surfaces: opts.surfaces,
5938
+ reuseWarm: opts.reuseWarm,
5939
+ browserTier: opts.browserTier,
5940
+ options
5941
+ }).then(async (live) => {
5942
+ await refuseUnreadTools(live);
5943
+ return new LiveTaskRun(runId, live, opts, options);
5944
+ })
5945
+ );
5946
+ return new RunSignals().during(
5947
+ (signal, urgent) => opening.interrupt(signal, urgent),
5948
+ () => opening.complete(agent)
5949
+ );
5177
5950
  }
5178
- var TaskRun, describeValue, RESULT_CONTRACT;
5951
+ var TaskRun, FILING_UNFINISHED, describeValue, RESULT_CONTRACT, LiveTaskRun, TaskOpening;
5179
5952
  var init_taskRun = __esm({
5180
5953
  "src/worlds/taskRun.ts"() {
5181
5954
  "use strict";
5182
5955
  init_browser();
5183
5956
  init_evals();
5957
+ init_runSignals();
5184
5958
  init_session2();
5185
5959
  init_taskSessions();
5960
+ init_taskRunDir();
5961
+ init_taskRunOutcome();
5186
5962
  init_taskTracing();
5963
+ init_worldNotice();
5187
5964
  TaskRun = class {
5188
5965
  constructor(runId, instruction, model, sessions2, manifest) {
5189
5966
  this.runId = runId;
@@ -5239,15 +6016,134 @@ var init_taskRun = __esm({
5239
6016
  impls[name] = kit.impls[modelToolName(spec.name)];
5240
6017
  }
5241
6018
  }
5242
- return { schemas, impls, specs };
6019
+ return { schemas, impls, specs };
6020
+ }
6021
+ /** Merged into `run.json` under `notes`; a later call overrides an earlier key. */
6022
+ record(notes) {
6023
+ Object.assign(this.notes, notes);
6024
+ }
6025
+ };
6026
+ FILING_UNFINISHED = "the filing did not finish";
6027
+ describeValue = (value) => Array.isArray(value) ? "array" : value === null ? "null" : typeof value;
6028
+ RESULT_CONTRACT = "return a string report, an object {report?: string, ...} or nothing";
6029
+ LiveTaskRun = class {
6030
+ constructor(runId, live, opts, options) {
6031
+ this.live = live;
6032
+ this.opts = opts;
6033
+ this.options = options;
6034
+ this.files = new TaskRunDir(path2.join(opts.outDir ?? "runs", runId));
6035
+ this.outcome = new TaskRunOutcome(runId, live, opts.model, this.files.path);
6036
+ }
6037
+ live;
6038
+ opts;
6039
+ options;
6040
+ files;
6041
+ outcome;
6042
+ played = false;
6043
+ interrupted = false;
6044
+ filing = null;
6045
+ ending = null;
6046
+ async complete(agent) {
6047
+ try {
6048
+ await this.play(agent).catch((error) => this.outcome.stopped(error));
6049
+ this.played = true;
6050
+ await this.file();
6051
+ return this.record();
6052
+ } finally {
6053
+ await this.end();
6054
+ }
6055
+ }
6056
+ async interrupt(signal, urgent = false) {
6057
+ const sessions2 = this.opts.keepUp ? "leaving its sessions up" : "closing its sessions";
6058
+ const how = urgent ? " now, without waiting" : "";
6059
+ process.stderr.write(`${this.outcome.runId} interrupted by ${signal}; ${sessions2}${how}
6060
+ `);
6061
+ if (!this.played) this.outcome.stopped(`interrupted by ${signal}`);
6062
+ this.interrupted = true;
6063
+ try {
6064
+ if (!urgent) await this.filing;
6065
+ this.record();
6066
+ } catch (error) {
6067
+ const why = error instanceof Error ? error.message : String(error);
6068
+ process.stderr.write(`${this.outcome.runId}: run.json not written: ${why}
6069
+ `);
6070
+ } finally {
6071
+ await this.end();
6072
+ }
5243
6073
  }
5244
- /** Merged into `run.json` under `notes`; a later call overrides an earlier key. */
5245
- record(notes) {
5246
- Object.assign(this.notes, notes);
6074
+ summary() {
6075
+ return this.outcome.summary();
6076
+ }
6077
+ async play(agent) {
6078
+ await this.live.ready();
6079
+ this.outcome.traced = await new TaskTracing().start(this.opts.trace !== false, this.options);
6080
+ const run = new TaskRun(
6081
+ this.outcome.runId,
6082
+ this.live.instruction ?? "",
6083
+ this.opts.model,
6084
+ this.live.sessions,
6085
+ await this.live.manifest()
6086
+ );
6087
+ this.outcome.notes = run.notes;
6088
+ this.files.writeManifest(run.manifest);
6089
+ await this.callAgent(agent, run);
6090
+ const report = this.outcome.report;
6091
+ this.outcome.grade = await this.live.grade(report !== null ? { report } : {});
6092
+ this.files.writeJson("grades.json", this.outcome.grade);
6093
+ if (report) this.files.write("report.md", report);
6094
+ }
6095
+ async callAgent(agent, run) {
6096
+ try {
6097
+ const invoke = () => agent(run);
6098
+ const result = this.outcome.traced ? await (await Promise.resolve().then(() => (init_session(), session_exports))).withSession(run.runId, invoke) : await invoke();
6099
+ ({ report: this.outcome.report, extra: this.outcome.extra } = reportFromResult(result));
6100
+ } catch (error) {
6101
+ this.outcome.agentRaised(error);
6102
+ }
6103
+ if (this.outcome.traced)
6104
+ await Promise.resolve().then(() => (init_init(), init_exports)).then((tracing2) => tracing2.flush()).catch(() => void 0);
6105
+ }
6106
+ async file() {
6107
+ if (this.opts.file === false || this.interrupted) return;
6108
+ this.files.writeJson("run.json", { ...this.outcome.summary(), fileError: FILING_UNFINISHED });
6109
+ this.filing = this.outcome.file(new GatewayEvalsClient(this.options), this.opts.setRunId);
6110
+ await this.filing;
6111
+ }
6112
+ record() {
6113
+ const summary = this.outcome.summary();
6114
+ this.files.writeJson("run.json", summary);
6115
+ return summary;
6116
+ }
6117
+ end() {
6118
+ this.ending ??= this.opts.keepUp ? Promise.resolve() : this.live.close({ keepWarm: false }).then(
6119
+ () => void 0,
6120
+ () => void 0
6121
+ );
6122
+ return this.ending;
6123
+ }
6124
+ };
6125
+ TaskOpening = class {
6126
+ interrupting = null;
6127
+ run = null;
6128
+ opened;
6129
+ constructor(opening) {
6130
+ this.opened = opening.then((run) => this.run = run);
6131
+ }
6132
+ async complete(agent) {
6133
+ const run = await this.opened;
6134
+ if (!this.interrupting) return run.complete(agent);
6135
+ await this.interrupting;
6136
+ return run.summary();
6137
+ }
6138
+ interrupt(signal, urgent = false) {
6139
+ if (urgent) return this.run?.interrupt(signal, true) ?? Promise.resolve();
6140
+ this.interrupting ??= this.opened.then(
6141
+ (run) => run.interrupt(signal),
6142
+ () => void 0
6143
+ );
6144
+ return this.interrupting;
5247
6145
  }
5248
6146
  };
5249
- describeValue = (value) => Array.isArray(value) ? "array" : value === null ? "null" : typeof value;
5250
- RESULT_CONTRACT = "return a string report, an object {report?: string, ...} or nothing";
5251
6147
  }
5252
6148
  });
5253
6149
 
@@ -5327,106 +6223,182 @@ async function runSet(datasetId, agent, opts) {
5327
6223
  source: opts.source ?? "sdk",
5328
6224
  ...git && Object.keys(git).length ? { git } : {}
5329
6225
  });
5330
- const close = (status) => apiRequest(
5331
- options,
5332
- "POST",
5333
- `${SET_RUNS}/${encodeURIComponent(opened.id)}/close`,
5334
- { status }
5335
- );
5336
- const onInterrupt = () => {
5337
- void close("failed").finally(() => process.exit(130));
5338
- };
5339
- process.once("SIGINT", onInterrupt);
5340
- const planned = await runPlannedTasks(opened, agent, opts, options).finally(
5341
- () => process.off("SIGINT", onInterrupt)
5342
- );
5343
- const { tasks, failed } = planned;
5344
- const requested = failed ? "failed" : "completed";
5345
- const setRun = await close(requested);
5346
- return {
5347
- setRun,
5348
- tasks,
5349
- failed: failed || setRun.status !== "completed",
5350
- closedAsRequested: setRun.status === requested
5351
- };
6226
+ return new SetRunner(opened, agent, opts, options).run();
5352
6227
  }
5353
- async function runPlannedTasks(opened, agent, opts, options) {
5354
- const tasks = [];
5355
- let failed = false;
5356
- for (const task of opened.tasks) {
5357
- try {
5358
- const summary = await runTask(task.worldTaskId, agent, {
5359
- model: opts.model,
5360
- surfaces: opts.surfaces,
5361
- browserTier: opts.browserTier,
5362
- outDir: opts.outDir,
5363
- trace: opts.trace,
5364
- setRunId: opened.id,
5365
- options
5366
- });
5367
- tasks.push(summary);
5368
- failed ||= summary.agentError !== null;
5369
- opts.onTask?.(summary);
5370
- } catch (error) {
5371
- failed = true;
5372
- const message = error instanceof Error ? error.message : String(error);
5373
- process.stderr.write(`task ${task.name} could not run: ${message}
5374
- `);
5375
- }
5376
- }
5377
- return { tasks, failed };
5378
- }
5379
- var SET_RUNS;
6228
+ var SET_RUNS, SetRunner;
5380
6229
  var init_setRun = __esm({
5381
6230
  "src/worlds/setRun.ts"() {
5382
6231
  "use strict";
5383
6232
  init_worlds();
5384
6233
  init_checkoutProvenance();
6234
+ init_runSignals();
5385
6235
  init_taskRun();
5386
6236
  SET_RUNS = "/api/public/set-runs";
6237
+ SetRunner = class {
6238
+ constructor(opened, agent, opts, options) {
6239
+ this.opened = opened;
6240
+ this.agent = agent;
6241
+ this.opts = opts;
6242
+ this.options = options;
6243
+ }
6244
+ opened;
6245
+ agent;
6246
+ opts;
6247
+ options;
6248
+ tasks = [];
6249
+ failures = [];
6250
+ failed = false;
6251
+ current = null;
6252
+ interrupted = null;
6253
+ signals = new RunSignals();
6254
+ async run() {
6255
+ await this.signals.during(
6256
+ (signal2) => this.interrupt(signal2).then(() => void 0),
6257
+ () => this.runTasks()
6258
+ );
6259
+ const signal = this.signals.signal;
6260
+ if (signal !== null) return this.result(await this.interrupt(signal), "failed");
6261
+ const requested = this.failed ? "failed" : "completed";
6262
+ return this.result(await this.close(requested, this.failures), requested);
6263
+ }
6264
+ interrupt(signal) {
6265
+ const stopped = this.current ? [{ worldTaskId: this.current, reason: `interrupted by ${signal}` }] : [];
6266
+ this.interrupted ??= this.close("failed", [...this.failures, ...stopped]);
6267
+ return this.interrupted;
6268
+ }
6269
+ async runTasks() {
6270
+ for (const task of this.opened.tasks) {
6271
+ if (this.signals.signal !== null) return;
6272
+ this.current = task.worldTaskId;
6273
+ await this.runOne(task);
6274
+ }
6275
+ this.current = null;
6276
+ }
6277
+ async runOne(task) {
6278
+ try {
6279
+ const summary = await runTask(task.worldTaskId, this.agent, {
6280
+ model: this.opts.model,
6281
+ surfaces: this.opts.surfaces,
6282
+ browserTier: this.opts.browserTier,
6283
+ outDir: this.opts.outDir,
6284
+ trace: this.opts.trace,
6285
+ setRunId: this.opened.id,
6286
+ options: this.options
6287
+ });
6288
+ this.tasks.push(summary);
6289
+ this.failed ||= taskRunFailure(summary) !== null;
6290
+ if (summary.fileError !== null)
6291
+ this.failures.push({ worldTaskId: task.worldTaskId, reason: summary.fileError });
6292
+ this.opts.onTask?.(summary);
6293
+ } catch (error) {
6294
+ this.failed = true;
6295
+ const message = error instanceof Error ? error.message : String(error);
6296
+ process.stderr.write(`task ${task.name} could not run: ${message}
6297
+ `);
6298
+ this.failures.push({
6299
+ worldTaskId: task.worldTaskId,
6300
+ reason: message || (error instanceof Error ? error.name : "Error")
6301
+ });
6302
+ }
6303
+ }
6304
+ close(status, failures = []) {
6305
+ return apiRequest(
6306
+ this.options,
6307
+ "POST",
6308
+ `${SET_RUNS}/${encodeURIComponent(this.opened.id)}/close`,
6309
+ { status, ...failures.length ? { failures } : {} }
6310
+ );
6311
+ }
6312
+ result(setRun, requested) {
6313
+ return {
6314
+ setRun,
6315
+ tasks: this.tasks,
6316
+ failed: this.failed || setRun.status !== "completed",
6317
+ closedAsRequested: setRun.status === requested
6318
+ };
6319
+ }
6320
+ };
5387
6321
  }
5388
6322
  });
5389
6323
 
5390
6324
  // src/worlds/requestLog.ts
5391
- var WorldRequestLog;
6325
+ function worldRequestsUnrecorded(counts) {
6326
+ const parts2 = UNRECORDED.map(([field2, one, many]) => [counted(counts[field2]), one, many]).filter(([count]) => count > 0).map(([count, one, many]) => (count === 1 ? one : many).replace("{n}", String(count)));
6327
+ return parts2.length > 0 ? `Not recorded: ${parts2.join(", ")}` : null;
6328
+ }
6329
+ function counted(value) {
6330
+ return typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : 0;
6331
+ }
6332
+ var UNRECORDED, WorldRequestLog;
5392
6333
  var init_requestLog = __esm({
5393
6334
  "src/worlds/requestLog.ts"() {
5394
6335
  "use strict";
6336
+ init_requestLedger();
6337
+ UNRECORDED = [
6338
+ ["lost", "{n} request", "{n} requests"],
6339
+ ["shed", "{n} request's headers and bodies", "{n} requests' headers and bodies"],
6340
+ ["hostsLost", "the requests {n} lost host held", "the requests {n} lost hosts held"]
6341
+ ];
5395
6342
  WorldRequestLog = class _WorldRequestLog {
5396
- constructor(requests) {
6343
+ constructor(requests, notRecorded = null, unrecorded = null) {
5397
6344
  this.requests = requests;
6345
+ this.notRecorded = notRecorded;
6346
+ this.unrecorded = unrecorded;
5398
6347
  }
5399
6348
  requests;
5400
- static async read(session) {
5401
- const state2 = await session.state();
5402
- const calls = state2?.calls;
5403
- if (!Array.isArray(calls)) return null;
5404
- return new _WorldRequestLog(calls.filter((c) => typeof c === "object" && c !== null));
5405
- }
5406
- /** How many older requests the world no longer keeps (its log is bounded): the gap
5407
- * before the first entry it still holds. */
5408
- get dropped() {
5409
- const first = Number(this.requests[0]?.seq) || 1;
5410
- return Math.max(0, first - 1);
5411
- }
5412
- /** Each request in the shape of a ledger line, `kind: "request"`, so one JSONL
5413
- * file holds both. */
6349
+ notRecorded;
6350
+ unrecorded;
6351
+ /** Every entry the ledger holds for the session, oldest first, and the line for what it did not record;
6352
+ * for a session the World Host did not serve, none, and `notRecorded` says why. */
6353
+ static async load(session) {
6354
+ try {
6355
+ return await _WorldRequestLog.pages(session);
6356
+ } catch (error) {
6357
+ const refused = WorldRequestsNotRecorded.from(error);
6358
+ if (!(refused instanceof WorldRequestsNotRecorded)) throw error;
6359
+ return new _WorldRequestLog([], refused.message);
6360
+ }
6361
+ }
6362
+ static async pages(session) {
6363
+ const requests = [];
6364
+ let cursor;
6365
+ for (; ; ) {
6366
+ const page = await session.requests(cursor ? { cursor } : {});
6367
+ requests.push(...page.requests);
6368
+ if (!page.nextCursor || page.requests.length === 0)
6369
+ return new _WorldRequestLog(requests.reverse(), null, worldRequestsUnrecorded(page));
6370
+ cursor = page.nextCursor;
6371
+ }
6372
+ }
6373
+ /** Each entry in the shape of a ledger line, `kind: "request"`, so one JSONL
6374
+ * file holds both: `args` what was asked, `result` what came back under the
6375
+ * entry's `requestId`. */
5414
6376
  asCalls() {
5415
6377
  return this.requests.map((r) => ({
5416
- seq: Number(r.seq) || 0,
6378
+ seq: r.seq,
5417
6379
  kind: "request",
5418
- tool: r.operation ?? null,
6380
+ tool: r.operation,
5419
6381
  args: {
5420
- method: r.method ?? null,
5421
- path: r.path ?? null,
5422
- args: r.args ?? null,
5423
- query: r.query ?? null,
5424
- body: r.body ?? null,
5425
- via: r.via ?? null
6382
+ method: r.method,
6383
+ path: r.path,
6384
+ query: r.query,
6385
+ via: r.via,
6386
+ contentType: r.request.contentType,
6387
+ bodyBytes: r.request.bodyBytes,
6388
+ truncated: r.request.truncated
6389
+ },
6390
+ result: {
6391
+ requestId: r.id,
6392
+ status: r.response.status,
6393
+ rows: r.rows,
6394
+ found: r.found,
6395
+ durationMs: r.durationMs,
6396
+ contentType: r.response.contentType,
6397
+ bodyBytes: r.response.bodyBytes,
6398
+ truncated: r.response.truncated
5426
6399
  },
5427
- result: { status: r.status ?? null, rows: r.rows ?? null, found: r.found ?? null },
5428
6400
  error: null,
5429
- completedAt: r.at ?? null
6401
+ completedAt: r.at
5430
6402
  }));
5431
6403
  }
5432
6404
  };
@@ -5435,7 +6407,7 @@ var init_requestLog = __esm({
5435
6407
 
5436
6408
  // src/worlds/checkoutTarget.ts
5437
6409
  import * as fs2 from "fs";
5438
- import * as path2 from "path";
6410
+ import * as path3 from "path";
5439
6411
  var CheckoutRefusedError, NAMED_EDITS, CheckoutTarget;
5440
6412
  var init_checkoutTarget = __esm({
5441
6413
  "src/worlds/checkoutTarget.ts"() {
@@ -5464,17 +6436,17 @@ var init_checkoutTarget = __esm({
5464
6436
  }
5465
6437
  /** The absolute destination; a relative target may not resolve above `cwd`. */
5466
6438
  static confined(target, cwd) {
5467
- const dir = path2.resolve(cwd, target);
5468
- if (path2.isAbsolute(target)) return dir;
5469
- const rel = path2.relative(cwd, dir);
5470
- if (rel === "" || !rel.startsWith("..") && !path2.isAbsolute(rel))
6439
+ const dir = path3.resolve(cwd, target);
6440
+ if (path3.isAbsolute(target)) return dir;
6441
+ const rel = path3.relative(cwd, dir);
6442
+ if (rel === "" || !rel.startsWith("..") && !path3.isAbsolute(rel))
5471
6443
  return dir;
5472
6444
  throw new CheckoutRefusedError(
5473
6445
  `--target ${target} resolves outside the current directory (${cwd}) \u2014 run from that directory, or pass an absolute path`
5474
6446
  );
5475
6447
  }
5476
6448
  static fresh(slug, cwd) {
5477
- const base = path2.join(cwd, slug);
6449
+ const base = path3.join(cwd, slug);
5478
6450
  let dir = base;
5479
6451
  let i = 1;
5480
6452
  while (fs2.existsSync(dir)) dir = `${base}-${i++}`;
@@ -5501,7 +6473,7 @@ var init_checkoutTarget = __esm({
5501
6473
  ].filter(_CheckoutTarget.confinedRel).sort();
5502
6474
  }
5503
6475
  static confinedRel(rel) {
5504
- if (rel === "" || path2.isAbsolute(rel)) return false;
6476
+ if (rel === "" || path3.isAbsolute(rel)) return false;
5505
6477
  return !rel.split(/[\\/]/).includes("..");
5506
6478
  }
5507
6479
  /** Why `dir` cannot be overwritten, or null when it is a clean checkout of `slug`. */
@@ -5519,9 +6491,9 @@ var init_checkoutTarget = __esm({
5519
6491
  /** Remove the replaced checkout's files (and the dirs they leave empty). */
5520
6492
  clear() {
5521
6493
  for (const rel of this.replaces) {
5522
- const abs = path2.join(this.dir, rel);
6494
+ const abs = path3.join(this.dir, rel);
5523
6495
  fs2.rmSync(abs, { force: true });
5524
- this.pruneEmptyParents(path2.dirname(abs));
6496
+ this.pruneEmptyParents(path3.dirname(abs));
5525
6497
  }
5526
6498
  }
5527
6499
  pruneEmptyParents(from) {
@@ -5529,7 +6501,7 @@ var init_checkoutTarget = __esm({
5529
6501
  while (cur !== this.dir && cur.startsWith(this.dir)) {
5530
6502
  if (fs2.existsSync(cur) && fs2.readdirSync(cur).length > 0) return;
5531
6503
  fs2.rmSync(cur, { recursive: true, force: true });
5532
- cur = path2.dirname(cur);
6504
+ cur = path3.dirname(cur);
5533
6505
  }
5534
6506
  }
5535
6507
  };
@@ -5539,7 +6511,7 @@ var init_checkoutTarget = __esm({
5539
6511
  // src/worlds/worldDir.ts
5540
6512
  import { createHash as createHash4 } from "crypto";
5541
6513
  import * as fs3 from "fs";
5542
- import * as path3 from "path";
6514
+ import * as path4 from "path";
5543
6515
  var WORLD_MANIFEST, API_BUNDLE_MANIFEST, BUNDLED_WORLD_PREFIX, CONNECTOR_SPEC, PYPROJECT, BENCHMARK_CONFIG, WORLD_SCHEMA_MARKERS, WORLD_ROOT_MARKERS, BROAD_ROOT_MARKERS, SKIPPED_DIRS, V1_DEP, V1_IMPORT, V1_TASKSET, HARBOR_TASK, skippedDir, byCodePoint, WorldDir;
5544
6516
  var init_worldDir = __esm({
5545
6517
  "src/worlds/worldDir.ts"() {
@@ -5569,17 +6541,17 @@ var init_worldDir = __esm({
5569
6541
  worldRoot;
5570
6542
  pathsMemo;
5571
6543
  static open(dir) {
5572
- const present = (rel) => fs3.existsSync(path3.join(dir, rel));
6544
+ const present = (rel) => fs3.existsSync(path4.join(dir, rel));
5573
6545
  const bundled = present(API_BUNDLE_MANIFEST) && WORLD_ROOT_MARKERS.some((m) => present(BUNDLED_WORLD_PREFIX + m));
5574
6546
  return new _WorldDir(dir, bundled ? BUNDLED_WORLD_PREFIX : "");
5575
6547
  }
5576
6548
  // ── Files ──────────────────────────────────────────────────────────────
5577
6549
  has(rel) {
5578
- return fs3.existsSync(path3.join(this.dir, rel));
6550
+ return fs3.existsSync(path4.join(this.dir, rel));
5579
6551
  }
5580
6552
  text(rel) {
5581
6553
  try {
5582
- return fs3.readFileSync(path3.join(this.dir, rel), "utf-8");
6554
+ return fs3.readFileSync(path4.join(this.dir, rel), "utf-8");
5583
6555
  } catch {
5584
6556
  return null;
5585
6557
  }
@@ -5598,7 +6570,7 @@ var init_worldDir = __esm({
5598
6570
  const broad = BROAD_ROOT_MARKERS.some((m) => this.has(m));
5599
6571
  const out = [];
5600
6572
  const walk = (rel) => {
5601
- for (const entry of fs3.readdirSync(rel ? path3.join(this.dir, rel) : this.dir, { withFileTypes: true })) {
6573
+ for (const entry of fs3.readdirSync(rel ? path4.join(this.dir, rel) : this.dir, { withFileTypes: true })) {
5602
6574
  const child = rel ? `${rel}/${entry.name}` : entry.name;
5603
6575
  if (entry.isDirectory()) {
5604
6576
  if (!skippedDir(entry.name)) walk(child);
@@ -5619,7 +6591,7 @@ var init_worldDir = __esm({
5619
6591
  get exclusions() {
5620
6592
  const kept = new Set(this.archivePaths);
5621
6593
  const out = [];
5622
- const filesUnder = (rel) => fs3.readdirSync(path3.join(this.dir, rel), { withFileTypes: true }).flatMap((entry) => {
6594
+ const filesUnder = (rel) => fs3.readdirSync(path4.join(this.dir, rel), { withFileTypes: true }).flatMap((entry) => {
5623
6595
  const child = `${rel}/${entry.name}`;
5624
6596
  if (entry.isDirectory()) return filesUnder(child);
5625
6597
  return entry.isFile() ? [child] : [];
@@ -5650,7 +6622,7 @@ var init_worldDir = __esm({
5650
6622
  const hasher = createHash4("sha256");
5651
6623
  for (const rel of this.archivePaths) {
5652
6624
  hasher.update(Buffer.from(`file:${rel}`, "utf-8"));
5653
- hasher.update(fs3.readFileSync(path3.join(this.dir, rel)));
6625
+ hasher.update(fs3.readFileSync(path4.join(this.dir, rel)));
5654
6626
  }
5655
6627
  return hasher.digest("hex");
5656
6628
  }
@@ -5715,7 +6687,7 @@ var init_worldDir = __esm({
5715
6687
 
5716
6688
  // src/worlds/tar.ts
5717
6689
  import * as fs4 from "fs";
5718
- import * as path4 from "path";
6690
+ import * as path5 from "path";
5719
6691
  import { gunzipSync } from "zlib";
5720
6692
  function archiveMode(mode) {
5721
6693
  return (mode & 73) !== 0 ? TAR_EXEC_MODE : TAR_FILE_MODE;
@@ -5801,8 +6773,8 @@ var init_tar = __esm({
5801
6773
  for (const member of this.members()) {
5802
6774
  if (member.typeflag !== "0" && member.typeflag !== "\0") continue;
5803
6775
  if (!_TarArchive.isConfined(member.name)) continue;
5804
- const target = path4.join(dir, member.name);
5805
- fs4.mkdirSync(path4.dirname(target), { recursive: true });
6776
+ const target = path5.join(dir, member.name);
6777
+ fs4.mkdirSync(path5.dirname(target), { recursive: true });
5806
6778
  const mode = archiveMode(member.mode);
5807
6779
  fs4.writeFileSync(target, member.bytes, { mode });
5808
6780
  fs4.chmodSync(target, mode);
@@ -5846,7 +6818,7 @@ __export(hub_exports, {
5846
6818
  import { createHash as createHash5 } from "crypto";
5847
6819
  import { gzipSync } from "zlib";
5848
6820
  import * as fs5 from "fs";
5849
- import * as path5 from "path";
6821
+ import * as path6 from "path";
5850
6822
  function collectArchiveRelPaths(dir) {
5851
6823
  const world = WorldDir.open(dir);
5852
6824
  if (world.hasRootGitignore) {
@@ -5909,7 +6881,7 @@ function tarMember(name, payload, mode) {
5909
6881
  function buildSourceTarball(dir) {
5910
6882
  const parts2 = [];
5911
6883
  for (const relPath of collectArchiveRelPaths(dir)) {
5912
- const abs = path5.join(dir, relPath);
6884
+ const abs = path6.join(dir, relPath);
5913
6885
  parts2.push(
5914
6886
  ...tarMember(
5915
6887
  relPath,
@@ -5923,7 +6895,7 @@ function buildSourceTarball(dir) {
5923
6895
  }
5924
6896
  function readLocalMeta(dir) {
5925
6897
  try {
5926
- const raw = fs5.readFileSync(path5.join(dir, META_RELPATH), "utf-8");
6898
+ const raw = fs5.readFileSync(path6.join(dir, META_RELPATH), "utf-8");
5927
6899
  const parsed = JSON.parse(raw);
5928
6900
  return parsed && typeof parsed === "object" ? parsed : null;
5929
6901
  } catch {
@@ -5946,16 +6918,16 @@ function resolvePushSlug(dir, opts = {}) {
5946
6918
  }
5947
6919
  const first = declared[0];
5948
6920
  if (first) return { ...base, slug: first.slug, source: first.source };
5949
- return { ...base, slug: path5.basename(path5.resolve(dir)), source: "directory name" };
6921
+ return { ...base, slug: path6.basename(path6.resolve(dir)), source: "directory name" };
5950
6922
  }
5951
6923
  function writeLocalMeta(dir, meta) {
5952
- fs5.mkdirSync(path5.join(dir, ".gateway"), { recursive: true });
5953
- fs5.writeFileSync(path5.join(dir, META_RELPATH), JSON.stringify(meta, null, 2));
6924
+ fs5.mkdirSync(path6.join(dir, ".gateway"), { recursive: true });
6925
+ fs5.writeFileSync(path6.join(dir, META_RELPATH), JSON.stringify(meta, null, 2));
5954
6926
  }
5955
6927
  function snapshotTreeHashes(dir) {
5956
6928
  const out = {};
5957
6929
  for (const relPath of collectArchiveRelPaths(dir)) {
5958
- out[relPath] = createHash5("sha256").update(fs5.readFileSync(path5.join(dir, relPath))).digest("hex");
6930
+ out[relPath] = createHash5("sha256").update(fs5.readFileSync(path6.join(dir, relPath))).digest("hex");
5959
6931
  }
5960
6932
  return out;
5961
6933
  }
@@ -5973,7 +6945,7 @@ function localTreeState(dir) {
5973
6945
  }
5974
6946
  function readPyproject(dir) {
5975
6947
  try {
5976
- const text2 = fs5.readFileSync(path5.join(dir, "pyproject.toml"), "utf-8");
6948
+ const text2 = fs5.readFileSync(path6.join(dir, "pyproject.toml"), "utf-8");
5977
6949
  const section = /\[project\]([\s\S]*?)(\n\[|$)/.exec(text2)?.[1] ?? "";
5978
6950
  const name = /\bname\s*=\s*"([^"]+)"/.exec(section)?.[1];
5979
6951
  const version = /\bversion\s*=\s*"([^"]+)"/.exec(section)?.[1];
@@ -5996,7 +6968,7 @@ function readWorldContractVersion(dir) {
5996
6968
  }
5997
6969
  function buildFileManifest(dir) {
5998
6970
  return collectArchiveRelPaths(dir).map((relPath) => {
5999
- const payload = fs5.readFileSync(path5.join(dir, relPath));
6971
+ const payload = fs5.readFileSync(path6.join(dir, relPath));
6000
6972
  return {
6001
6973
  path: relPath,
6002
6974
  isDirectory: false,
@@ -6042,7 +7014,7 @@ async function push(dir, opts = {}) {
6042
7014
  const pyproject = readPyproject(dir);
6043
7015
  const contractVersion = pyproject.version ? void 0 : readWorldContractVersion(dir).version;
6044
7016
  if (contractVersion) pyproject.version = contractVersion;
6045
- const slug = opts.slug ?? localMeta.slug ?? pyproject.name ?? path5.basename(path5.resolve(dir));
7017
+ const slug = opts.slug ?? localMeta.slug ?? pyproject.name ?? path6.basename(path6.resolve(dir));
6046
7018
  const metadata = {
6047
7019
  ...opts.name !== void 0 ? { name: opts.name } : {},
6048
7020
  ...opts.description !== void 0 ? { description: opts.description } : {},
@@ -6121,7 +7093,8 @@ function checkoutIdentity(ref, resolved) {
6121
7093
  async function pull(slugRef, target, options = {}, opts = {}) {
6122
7094
  const at = slugRef.indexOf("@");
6123
7095
  const slug = at === -1 ? slugRef : slugRef.slice(0, at);
6124
- const ref = at === -1 ? "latest" : slugRef.slice(at + 1);
7096
+ const asked = at === -1 ? void 0 : slugRef.slice(at + 1);
7097
+ const ref = asked ?? "latest";
6125
7098
  const landing = CheckoutTarget.resolve(slug, target, {
6126
7099
  cwd: process.cwd(),
6127
7100
  force: opts.force ?? false,
@@ -6129,7 +7102,7 @@ async function pull(slugRef, target, options = {}, opts = {}) {
6129
7102
  });
6130
7103
  const details = await apiRequest(options, "POST", "/api/public/benchmark-containers/resolve-version", {
6131
7104
  slug,
6132
- ref
7105
+ ...asked ? { ref: asked } : {}
6133
7106
  });
6134
7107
  if (!details.downloadUrl) {
6135
7108
  throw new Error(`${slug}@${ref} resolved but has no uploaded bundle`);
@@ -6168,7 +7141,7 @@ async function propose(dir, opts) {
6168
7141
  if (state2.clean)
6169
7142
  throw new Error("Nothing to propose \u2014 the tree matches its base.");
6170
7143
  const changes = state2.dirty.map((relPath) => {
6171
- const abs = path5.join(dir, relPath);
7144
+ const abs = path6.join(dir, relPath);
6172
7145
  if (!fs5.existsSync(abs))
6173
7146
  return { path: relPath, action: "delete" };
6174
7147
  return {
@@ -6209,7 +7182,7 @@ var init_hub = __esm({
6209
7182
  init_worldDir();
6210
7183
  init_tar();
6211
7184
  DEFAULT_BRANCH = "main";
6212
- META_RELPATH = path5.join(".gateway", ".env-metadata.json");
7185
+ META_RELPATH = path6.join(".gateway", ".env-metadata.json");
6213
7186
  FILE_MODE = TAR_FILE_MODE;
6214
7187
  MINTED_SUFFIX = /^-\d+$/;
6215
7188
  PushSlugConflict = class extends Error {
@@ -6315,7 +7288,7 @@ async function validateWorld(dir, opts) {
6315
7288
  options,
6316
7289
  "POST",
6317
7290
  "/api/public/benchmark-containers/resolve-version",
6318
- { slug, ref: branch }
7291
+ { slug, ...branch === DEFAULT_BRANCH ? {} : { ref: branch } }
6319
7292
  );
6320
7293
  tipVersionId = tip.versionId ?? null;
6321
7294
  } catch {
@@ -6422,11 +7395,16 @@ var init_validate = __esm({
6422
7395
  });
6423
7396
 
6424
7397
  // src/worlds/sandbox.ts
7398
+ import { createHash as createHash6, randomUUID as randomUUID2 } from "crypto";
6425
7399
  function parseSlugRef(slugRef) {
6426
7400
  const at = slugRef.indexOf("@");
6427
7401
  if (at === -1) return { slug: slugRef };
6428
7402
  return { slug: slugRef.slice(0, at), ref: slugRef.slice(at + 1) };
6429
7403
  }
7404
+ function nameGlob(pattern) {
7405
+ const literal = (part) => part.replace(/[.+?^${}()|[\]\\]/g, "\\$&");
7406
+ return new RegExp(`^${pattern.split("*").map(literal).join(".*")}$`);
7407
+ }
6430
7408
  function rebaseConflicts(error) {
6431
7409
  if (!(error instanceof ApiError) || error.status !== 409) return null;
6432
7410
  let body;
@@ -6437,14 +7415,15 @@ function rebaseConflicts(error) {
6437
7415
  }
6438
7416
  const conflicts = body?.conflicts;
6439
7417
  if (!Array.isArray(conflicts)) return null;
6440
- return conflicts.filter(isConflictPath).map(({ path: path16, reason }) => ({ path: path16, reason }));
7418
+ return conflicts.filter(isConflictPath).map(({ path: path17, reason }) => ({ path: path17, reason }));
6441
7419
  }
6442
7420
  function isConflictPath(value) {
6443
7421
  const entry = value;
6444
7422
  return typeof entry?.path === "string" && typeof entry.reason === "string";
6445
7423
  }
6446
7424
  function uncommittedPaths(error) {
6447
- if (!(error instanceof ApiError) || error.status !== 409 || error.code !== "sandbox_uncommitted") return null;
7425
+ if (!(error instanceof ApiError) || error.status !== 409 || error.code !== "sandbox_uncommitted")
7426
+ return null;
6448
7427
  let body;
6449
7428
  try {
6450
7429
  body = JSON.parse(error.text);
@@ -6455,6 +7434,53 @@ function uncommittedPaths(error) {
6455
7434
  if (!Array.isArray(uncommitted)) return null;
6456
7435
  return uncommitted.filter((p) => typeof p === "string");
6457
7436
  }
7437
+ function carriedWarnings(error) {
7438
+ const kept = typeof error === "object" && error !== null ? carried.get(error) ?? [] : [];
7439
+ const shown = error instanceof Error ? error.message : "";
7440
+ return unique([...kept, ...bodyWarnings(error)]).filter((warning) => !shown.includes(warning));
7441
+ }
7442
+ function carrying(error, warnings) {
7443
+ if (warnings.length > 0 && typeof error === "object" && error !== null)
7444
+ carried.set(error, unique([...carried.get(error) ?? [], ...warnings]));
7445
+ return error;
7446
+ }
7447
+ function unique(warnings) {
7448
+ return [...new Set(warnings)];
7449
+ }
7450
+ function bodyWarnings(error) {
7451
+ if (!(error instanceof ApiError)) return [];
7452
+ let body;
7453
+ try {
7454
+ body = JSON.parse(error.text);
7455
+ } catch {
7456
+ return [];
7457
+ }
7458
+ const warnings = body?.warnings;
7459
+ if (!Array.isArray(warnings)) return [];
7460
+ return warnings.filter((w) => typeof w === "string");
7461
+ }
7462
+ function deferredWarnings(error) {
7463
+ if (!(error instanceof ApiError) || error.status !== 409 || error.code !== "sandbox_exec_deferred") return null;
7464
+ return bodyWarnings(error);
7465
+ }
7466
+ function rowsRefusal(error) {
7467
+ if (!(error instanceof ApiError) || error.status !== 400 || error.code !== "rows_refused") return null;
7468
+ let body;
7469
+ try {
7470
+ body = JSON.parse(error.text);
7471
+ } catch {
7472
+ return null;
7473
+ }
7474
+ const { message, batchId, refusalCount, refusals, reportUrl } = body;
7475
+ if (typeof batchId !== "string" || typeof refusalCount !== "number" || !Array.isArray(refusals)) return null;
7476
+ return {
7477
+ message: typeof message === "string" ? message : "",
7478
+ batchId,
7479
+ refusalCount,
7480
+ refusals: refusals.filter((r) => typeof r === "object" && r !== null),
7481
+ reportUrl: typeof reportUrl === "string" ? reportUrl : null
7482
+ };
7483
+ }
6458
7484
  function listQuery(filter) {
6459
7485
  const params = new URLSearchParams();
6460
7486
  if (filter.status) params.set("status", filter.status);
@@ -6463,22 +7489,58 @@ function listQuery(filter) {
6463
7489
  const qs3 = params.toString();
6464
7490
  return qs3 ? `?${qs3}` : "";
6465
7491
  }
6466
- var isSandboxImportPending, sid, SANDBOXES, SANDBOX_REQUEST_TIMEOUT_MS, WorldSandboxClient;
7492
+ var isSandboxCommitPending, isSandboxImportPending, sid, SANDBOXES, SANDBOX_REQUEST_TIMEOUT_MS, SANDBOX_WRITE_CHUNK_BYTES, SANDBOX_FILE_MAX_BYTES, SANDBOX_WRITE_SKIPPED, WriteTreeFilter, SANDBOX_EXEC_WAIT_MS, SANDBOX_EXEC_TIMEOUT_MAX_S, SANDBOX_EXEC_REPORT_MARGIN_MS, SANDBOX_EXEC_START_ATTEMPTS, carried, WorldSandboxClient;
6467
7493
  var init_sandbox = __esm({
6468
7494
  "src/worlds/sandbox.ts"() {
6469
7495
  "use strict";
6470
7496
  init_worlds();
7497
+ isSandboxCommitPending = (answer) => !("versionId" in answer);
6471
7498
  isSandboxImportPending = (answer) => !("versionId" in answer);
6472
7499
  sid = encodeURIComponent;
6473
7500
  SANDBOXES = "/api/public/benchmark-containers/sandboxes";
6474
- SANDBOX_REQUEST_TIMEOUT_MS = 66e4;
7501
+ SANDBOX_REQUEST_TIMEOUT_MS = 29e4;
7502
+ SANDBOX_WRITE_CHUNK_BYTES = 4 * 1024 * 1024;
7503
+ SANDBOX_FILE_MAX_BYTES = 256 * 1024 * 1024;
7504
+ SANDBOX_WRITE_SKIPPED = [
7505
+ ".git/",
7506
+ ".gateway/",
7507
+ "scratch/",
7508
+ ".scratch/",
7509
+ "__pycache__/",
7510
+ "*.pyc",
7511
+ ".pytest_cache/",
7512
+ ".mypy_cache/",
7513
+ ".ruff_cache/",
7514
+ "node_modules/",
7515
+ ".venv/",
7516
+ "venv/",
7517
+ ".DS_Store",
7518
+ "*.swp"
7519
+ ];
7520
+ WriteTreeFilter = class {
7521
+ directories = new Set(
7522
+ SANDBOX_WRITE_SKIPPED.filter((pattern) => pattern.endsWith("/")).map((pattern) => pattern.slice(0, -1))
7523
+ );
7524
+ files = SANDBOX_WRITE_SKIPPED.filter((pattern) => !pattern.endsWith("/")).map(nameGlob);
7525
+ skipsDirectory(name) {
7526
+ return this.directories.has(name);
7527
+ }
7528
+ skipsFile(name) {
7529
+ return this.files.some((glob) => glob.test(name));
7530
+ }
7531
+ };
7532
+ SANDBOX_EXEC_WAIT_MS = 4e4;
7533
+ SANDBOX_EXEC_TIMEOUT_MAX_S = 600;
7534
+ SANDBOX_EXEC_REPORT_MARGIN_MS = 35e3;
7535
+ SANDBOX_EXEC_START_ATTEMPTS = 3;
7536
+ carried = /* @__PURE__ */ new WeakMap();
6475
7537
  WorldSandboxClient = class {
6476
7538
  constructor(options = {}) {
6477
7539
  this.options = options;
6478
7540
  }
6479
7541
  options;
6480
- request(method, path16, body) {
6481
- return apiRequest(this.options, method, path16, body, {
7542
+ request(method, path17, body) {
7543
+ return apiRequest(this.options, method, path17, body, {
6482
7544
  timeoutMs: SANDBOX_REQUEST_TIMEOUT_MS
6483
7545
  });
6484
7546
  }
@@ -6496,7 +7558,10 @@ var init_sandbox = __esm({
6496
7558
  }
6497
7559
  /** The project's sandboxes, newest first — how an agent finds one it left open. */
6498
7560
  async list(filter = {}) {
6499
- const res = await this.request("GET", `${SANDBOXES}${listQuery(filter)}`);
7561
+ const res = await this.request(
7562
+ "GET",
7563
+ `${SANDBOXES}${listQuery(filter)}`
7564
+ );
6500
7565
  return res.sandboxes;
6501
7566
  }
6502
7567
  async read(sandboxId, filePath) {
@@ -6504,16 +7569,72 @@ var init_sandbox = __esm({
6504
7569
  "GET",
6505
7570
  `${SANDBOXES}/${sid(sandboxId)}/file?path=${encodeURIComponent(filePath)}`
6506
7571
  );
6507
- return { path: res.path, size: res.size, bytes: Buffer.from(res.contentBase64, "base64") };
7572
+ return {
7573
+ path: res.path,
7574
+ size: res.size,
7575
+ bytes: Buffer.from(res.contentBase64, "base64")
7576
+ };
6508
7577
  }
6509
- write(sandboxId, filePath, bytes) {
6510
- return this.request("PUT", `${SANDBOXES}/${sid(sandboxId)}/file`, {
6511
- path: filePath,
6512
- contentBase64: bytes.toString("base64")
6513
- });
7578
+ /** A file past one chunk goes up in parts under one upload id; the platform lands it whole once the last part's
7579
+ * size and SHA-256 check out. */
7580
+ async write(sandboxId, filePath, bytes) {
7581
+ if (bytes.length <= SANDBOX_WRITE_CHUNK_BYTES)
7582
+ return this.putFile(sandboxId, { path: filePath, contentBase64: bytes.toString("base64") });
7583
+ const whole = { upload: randomUUID2(), size: bytes.length, sha256: createHash6("sha256").update(bytes).digest("hex") };
7584
+ let answer = { path: filePath, received: 0 };
7585
+ for (let offset = 0; offset < bytes.length; offset += SANDBOX_WRITE_CHUNK_BYTES) {
7586
+ const part = bytes.subarray(offset, offset + SANDBOX_WRITE_CHUNK_BYTES);
7587
+ answer = await this.putFile(sandboxId, {
7588
+ path: filePath,
7589
+ contentBase64: part.toString("base64"),
7590
+ ...whole,
7591
+ offset,
7592
+ last: offset + part.length === bytes.length
7593
+ });
7594
+ }
7595
+ return answer;
7596
+ }
7597
+ putFile(sandboxId, body) {
7598
+ return this.request("PUT", `${SANDBOXES}/${sid(sandboxId)}/file`, body);
7599
+ }
7600
+ /** Runs as a job on the platform: a command that outlasts one request is waited on again until its result. */
7601
+ async exec(sandboxId, input) {
7602
+ const budgetMs = (input.timeoutMs ?? SANDBOX_EXEC_TIMEOUT_MAX_S * 1e3) + SANDBOX_EXEC_REPORT_MARGIN_MS;
7603
+ let answer = await this.startExec(sandboxId, { ...input, waitMs: SANDBOX_EXEC_WAIT_MS });
7604
+ const deadline = Date.now() + budgetMs;
7605
+ const warnings = [...answer.warnings ?? []];
7606
+ try {
7607
+ while ("state" in answer) {
7608
+ if (Date.now() >= deadline)
7609
+ throw new Error(
7610
+ `exec ${answer.execId} in sandbox ${sandboxId} has not reported back within ${budgetMs / 1e3} s, past its timeout: the sandbox may have restarted. Check the sandbox's status, then run the command again.`
7611
+ );
7612
+ answer = await this.execStep(sandboxId, { execId: answer.execId, waitMs: SANDBOX_EXEC_WAIT_MS });
7613
+ warnings.push(...answer.warnings ?? []);
7614
+ }
7615
+ } catch (error) {
7616
+ throw carrying(error, warnings);
7617
+ }
7618
+ return { ...answer, warnings };
7619
+ }
7620
+ // A deferred start ran nothing (the platform was still getting the sandbox ready), so starting again is safe. What
7621
+ // getting ready found rides on the deferral alone (no later call reports it), so it is kept for the answer, or for
7622
+ // the error when a later attempt fails.
7623
+ async startExec(sandboxId, body) {
7624
+ const kept = [];
7625
+ for (let attempt = 1; ; attempt += 1) {
7626
+ try {
7627
+ const answer = await this.execStep(sandboxId, body);
7628
+ return { ...answer, warnings: unique([...kept, ...answer.warnings ?? []]) };
7629
+ } catch (error) {
7630
+ const warnings = deferredWarnings(error);
7631
+ if (warnings === null || attempt === SANDBOX_EXEC_START_ATTEMPTS) throw carrying(error, kept);
7632
+ kept.push(...warnings);
7633
+ }
7634
+ }
6514
7635
  }
6515
- exec(sandboxId, input) {
6516
- return this.request("POST", `${SANDBOXES}/${sid(sandboxId)}/exec`, input);
7636
+ execStep(sandboxId, body) {
7637
+ return this.request("POST", `${SANDBOXES}/${sid(sandboxId)}/exec`, body);
6517
7638
  }
6518
7639
  check(sandboxId) {
6519
7640
  return this.request("POST", `${SANDBOXES}/${sid(sandboxId)}/check`, {});
@@ -6521,7 +7642,11 @@ var init_sandbox = __esm({
6521
7642
  /** With `rebase`, a moved base is replayed onto; a 409 then names the conflicting paths (`rebaseConflicts`). */
6522
7643
  commit(sandboxId, input) {
6523
7644
  const { rebase, ...rest } = input;
6524
- return this.request("POST", `${SANDBOXES}/${sid(sandboxId)}/commit`, rebase ? { ...rest, rebase: true } : rest);
7645
+ return this.request(
7646
+ "POST",
7647
+ `${SANDBOXES}/${sid(sandboxId)}/commit`,
7648
+ rebase ? { ...rest, rebase: true } : rest
7649
+ );
6525
7650
  }
6526
7651
  /**
6527
7652
  * A rows file already in the sandbox tree into the PLATFORM world the
@@ -6534,7 +7659,11 @@ var init_sandbox = __esm({
6534
7659
  }
6535
7660
  /** Uncommitted work is a 409 (`uncommittedPaths`) unless `force` discards it. */
6536
7661
  close(sandboxId, opts = {}) {
6537
- return this.request("DELETE", `${SANDBOXES}/${sid(sandboxId)}`, opts.force ? { force: true } : void 0);
7662
+ return this.request(
7663
+ "DELETE",
7664
+ `${SANDBOXES}/${sid(sandboxId)}`,
7665
+ opts.force ? { force: true } : void 0
7666
+ );
6538
7667
  }
6539
7668
  };
6540
7669
  }
@@ -6853,7 +7982,7 @@ var init_json = __esm({
6853
7982
  });
6854
7983
 
6855
7984
  // src/worlds/transforms.ts
6856
- import { createHash as createHash6 } from "crypto";
7985
+ import { createHash as createHash7 } from "crypto";
6857
7986
  function parseTransform(name) {
6858
7987
  const simple = Object.prototype.hasOwnProperty.call(SIMPLE, name) ? SIMPLE[name] : void 0;
6859
7988
  if (simple) return simple;
@@ -6891,7 +8020,7 @@ var init_transforms = __esm({
6891
8020
  return at === -1 ? "" : value.slice(at + 1).toLowerCase();
6892
8021
  };
6893
8022
  stripPrefix = (prefix) => (value) => value.startsWith(prefix) ? value.slice(prefix.length) : value;
6894
- hex = (algorithm, value) => createHash6(algorithm).update(value, "utf8").digest("hex");
8023
+ hex = (algorithm, value) => createHash7(algorithm).update(value, "utf8").digest("hex");
6895
8024
  SIMPLE = {
6896
8025
  lower: (value) => value.toLowerCase(),
6897
8026
  upper: (value) => value.toUpperCase(),
@@ -6915,7 +8044,7 @@ var init_transforms = __esm({
6915
8044
  });
6916
8045
 
6917
8046
  // src/worlds/redaction.ts
6918
- import { createHash as createHash7 } from "crypto";
8047
+ import { createHash as createHash8 } from "crypto";
6919
8048
  function pyText(value) {
6920
8049
  if (typeof value === "string") return value;
6921
8050
  if (Number.isInteger(value)) return String(value);
@@ -6924,7 +8053,7 @@ function pyText(value) {
6924
8053
  return pyFloatRepr(value);
6925
8054
  }
6926
8055
  function hashForm(slug, plaintext) {
6927
- return "sha256:" + createHash7("sha256").update(`${slug}:${pyText(plaintext)}`, "utf8").digest("hex");
8056
+ return "sha256:" + createHash8("sha256").update(`${slug}:${pyText(plaintext)}`, "utf8").digest("hex");
6928
8057
  }
6929
8058
  function preserveForm(slug, plaintext) {
6930
8059
  const kind = typeof plaintext === "string" ? "str" : isInt(plaintext) ? "int" : "float";
@@ -6933,12 +8062,12 @@ function preserveForm(slug, plaintext) {
6933
8062
  }
6934
8063
  function shapeText(slug, text2, kind) {
6935
8064
  const seed = Buffer.from(`${slug}:${text2}`, "utf8");
6936
- let digest = createHash7("sha256").update(seed).digest();
8065
+ let digest = createHash8("sha256").update(seed).digest();
6937
8066
  let cursor = 0;
6938
8067
  const out = [];
6939
8068
  for (const char of text2) {
6940
8069
  if (cursor === digest.length) {
6941
- digest = createHash7("sha256").update(Buffer.concat([digest, seed])).digest();
8070
+ digest = createHash8("sha256").update(Buffer.concat([digest, seed])).digest();
6942
8071
  cursor = 0;
6943
8072
  }
6944
8073
  const byte = digest[cursor];
@@ -7009,6 +8138,17 @@ async function queryRows(slugRef, entity, opts = {}, options = {}) {
7009
8138
  `/api/public/worlds/${encodeURIComponent(slug)}/data${queryRowsSearch(entity, opts, ref)}`
7010
8139
  );
7011
8140
  }
8141
+ async function sqlRows(slugRef, sql, opts = {}, options = {}) {
8142
+ const [slug, ref] = slugRef.split("@", 2);
8143
+ if (!slug || ref === "") throw new Error(`sqlRows needs a slug, optionally slug@ref (got ${slugRef})`);
8144
+ if (!sql.trim()) throw new Error("sqlRows needs one SQL statement");
8145
+ return apiRequest(options, "POST", `/api/public/worlds/${encodeURIComponent(slug)}/data/sql`, {
8146
+ sql,
8147
+ ...ref ? { ref } : {},
8148
+ ...opts.limit !== void 0 ? { limit: opts.limit } : {},
8149
+ ...opts.scenario ? { scenario: opts.scenario } : {}
8150
+ });
8151
+ }
7012
8152
  var init_query = __esm({
7013
8153
  "src/worlds/query.ts"() {
7014
8154
  "use strict";
@@ -7065,7 +8205,7 @@ var init_router = __esm({
7065
8205
  // src/cli/config.ts
7066
8206
  import * as fs6 from "fs";
7067
8207
  import * as os from "os";
7068
- import * as path6 from "path";
8208
+ import * as path7 from "path";
7069
8209
  async function api(creds, method, route, body, init3 = {}) {
7070
8210
  const reply = await new PlatformTransport(creds).send(method, route, body, init3);
7071
8211
  if (!reply.ok) throw new ApiError2(reply.status, method, route, reply.text);
@@ -7080,7 +8220,7 @@ var init_config = __esm({
7080
8220
  init_transport();
7081
8221
  ApiError2 = class extends CliError {
7082
8222
  constructor(status, method, route, text2) {
7083
- const body = parseErrorBody(text2);
8223
+ const body = parseErrorBody(text2, status);
7084
8224
  super(`${method} ${route} -> ${status}: ${body.detail}`, 1);
7085
8225
  this.status = status;
7086
8226
  this.method = method;
@@ -7101,7 +8241,15 @@ var init_config = __esm({
7101
8241
  import { spawn, spawnSync } from "child_process";
7102
8242
  import * as fs7 from "fs";
7103
8243
  import * as net from "net";
7104
- import * as path7 from "path";
8244
+ import * as path8 from "path";
8245
+ function forwardedEnv() {
8246
+ return Object.fromEntries(
8247
+ FORWARDED_ENV.flatMap((name) => {
8248
+ const value = process.env[name];
8249
+ return value ? [[name, value]] : [];
8250
+ })
8251
+ );
8252
+ }
7105
8253
  function tailOf(output) {
7106
8254
  return output.length > DIAGNOSTIC_TAIL ? `\u2026${output.slice(-DIAGNOSTIC_TAIL)}` : output;
7107
8255
  }
@@ -7116,16 +8264,16 @@ function runtimeRoot() {
7116
8264
  const candidates = [];
7117
8265
  if (process.env.GATEWAY_RUNTIME_PATH)
7118
8266
  candidates.push(process.env.GATEWAY_RUNTIME_PATH);
7119
- const entry = process.argv[1] && fs7.existsSync(process.argv[1]) ? path7.dirname(fs7.realpathSync(process.argv[1])) : null;
8267
+ const entry = process.argv[1] && fs7.existsSync(process.argv[1]) ? path8.dirname(fs7.realpathSync(process.argv[1])) : null;
7120
8268
  if (entry) {
7121
- candidates.push(path7.resolve(entry, "..", "runtime"));
7122
- candidates.push(path7.resolve(entry, "..", "..", "runtime"));
7123
- candidates.push(path7.resolve(entry, "..", "..", "sdk", "src"));
8269
+ candidates.push(path8.resolve(entry, "..", "runtime"));
8270
+ candidates.push(path8.resolve(entry, "..", "..", "runtime"));
8271
+ candidates.push(path8.resolve(entry, "..", "..", "sdk", "src"));
7124
8272
  }
7125
- candidates.push(path7.resolve(process.cwd(), "runtime"));
8273
+ candidates.push(path8.resolve(process.cwd(), "runtime"));
7126
8274
  for (const root of candidates)
7127
8275
  if (fs7.existsSync(
7128
- path7.join(root, "gatewaysdk", "environment", "schema", "platform.py")
8276
+ path8.join(root, "gatewaysdk", "environment", "schema", "platform.py")
7129
8277
  ))
7130
8278
  return root;
7131
8279
  return null;
@@ -7214,13 +8362,12 @@ async function localBridge(request, local, opts = {}) {
7214
8362
  ["-I", "-B", "-c", BRIDGE_BOOTSTRAP, local.root],
7215
8363
  {
7216
8364
  stdio: ["pipe", "pipe", "pipe"],
7217
- // This is the author's machine running the author's world: the one
7218
- // place the runtime may import and run a world's own Python (check's
7219
- // handler execution, `worlds call`, `worlds test` tool cases).
8365
+ // The author's machine running the author's world: the one place the runtime may run its Python.
7220
8366
  env: {
7221
8367
  PATH: process.env.PATH ?? "",
7222
8368
  HOME: process.env.HOME ?? "",
7223
8369
  TMPDIR: process.env.TMPDIR ?? "",
8370
+ ...forwardedEnv(),
7224
8371
  GATEWAY_RUNTIME_EXECUTE: "1"
7225
8372
  }
7226
8373
  }
@@ -7266,7 +8413,7 @@ async function localBridge(request, local, opts = {}) {
7266
8413
  child.stdin.end(input);
7267
8414
  });
7268
8415
  }
7269
- var MIN_PYTHON, MIN_PYTHON_LABEL, DIAGNOSTIC_TAIL, BRIDGE_BOOTSTRAP, pythonCache, pythonProbes, PYTHON_CANDIDATES, UV_FIND;
8416
+ var MIN_PYTHON, MIN_PYTHON_LABEL, DIAGNOSTIC_TAIL, FORWARDED_ENV, BRIDGE_BOOTSTRAP, pythonCache, pythonProbes, PYTHON_CANDIDATES, UV_FIND;
7270
8417
  var init_local = __esm({
7271
8418
  "src/cli/runtime/local.ts"() {
7272
8419
  "use strict";
@@ -7275,6 +8422,7 @@ var init_local = __esm({
7275
8422
  MIN_PYTHON = [3, 12];
7276
8423
  MIN_PYTHON_LABEL = MIN_PYTHON.join(".");
7277
8424
  DIAGNOSTIC_TAIL = 600;
8425
+ FORWARDED_ENV = ["VIRTUAL_ENV", "GATEWAY_SNAPSHOT_STORE"];
7278
8426
  BRIDGE_BOOTSTRAP = `import sys,runpy,types,os
7279
8427
  root=sys.argv[1]
7280
8428
  package=types.ModuleType('gatewaysdk')
@@ -7292,18 +8440,46 @@ runpy.run_module('gatewaysdk.environment.schema.platform',run_name='__main__')`;
7292
8440
  }
7293
8441
  });
7294
8442
 
8443
+ // src/worlds/databaseEngines.ts
8444
+ function isWorldSnapshotOutput(path17) {
8445
+ return SNAPSHOT_OUTPUTS.has(path17.slice(path17.lastIndexOf("/") + 1));
8446
+ }
8447
+ var WORLD_DATABASE_ENGINES, DEFAULT_WORLD_DATABASE_ENGINE, WORLD_SNAPSHOT_FILE_PATH, WORLD_SNAPSHOT_SIDECAR_PATH, WORLD_SNAPSHOT_CONTENT_TYPE, SNAPSHOT_OUTPUTS;
8448
+ var init_databaseEngines = __esm({
8449
+ "src/worlds/databaseEngines.ts"() {
8450
+ "use strict";
8451
+ WORLD_DATABASE_ENGINES = [
8452
+ {
8453
+ engine: "sqlite",
8454
+ label: "SQLite",
8455
+ target: "sqlite-json/1",
8456
+ snapshotName: "state.sqlite",
8457
+ contentType: "application/vnd.sqlite3"
8458
+ }
8459
+ ];
8460
+ DEFAULT_WORLD_DATABASE_ENGINE = WORLD_DATABASE_ENGINES[0];
8461
+ WORLD_SNAPSHOT_FILE_PATH = `db/${DEFAULT_WORLD_DATABASE_ENGINE.snapshotName}`;
8462
+ WORLD_SNAPSHOT_SIDECAR_PATH = "db/state.json";
8463
+ WORLD_SNAPSHOT_CONTENT_TYPE = DEFAULT_WORLD_DATABASE_ENGINE.contentType;
8464
+ SNAPSHOT_OUTPUTS = /* @__PURE__ */ new Set([
8465
+ ...WORLD_DATABASE_ENGINES.map((engine) => engine.snapshotName),
8466
+ WORLD_SNAPSHOT_SIDECAR_PATH.slice("db/".length)
8467
+ ]);
8468
+ }
8469
+ });
8470
+
7295
8471
  // src/cli/runtime/client.ts
7296
8472
  import * as fs8 from "fs";
7297
- import * as path8 from "path";
8473
+ import * as path9 from "path";
7298
8474
  function isBuildOutput(relPath) {
7299
- return BUILD_OUTPUT.test(relPath);
8475
+ return isWorldSnapshotOutput(relPath);
7300
8476
  }
7301
8477
  function readWorldFiles(dir, opts = {}) {
7302
8478
  if (!fs8.existsSync(dir) || !fs8.statSync(dir).isDirectory())
7303
8479
  throw new CliError(`Not a directory: ${dir}`);
7304
8480
  const out = [];
7305
8481
  const walk = (rel) => {
7306
- const abs = rel ? path8.join(dir, rel) : dir;
8482
+ const abs = rel ? path9.join(dir, rel) : dir;
7307
8483
  const entries = fs8.readdirSync(abs, { withFileTypes: true });
7308
8484
  entries.sort((a, b) => a.name.localeCompare(b.name));
7309
8485
  for (const entry of entries) {
@@ -7314,7 +8490,7 @@ function readWorldFiles(dir, opts = {}) {
7314
8490
  if (!opts.buildOutputs && isBuildOutput(childRel)) continue;
7315
8491
  out.push({
7316
8492
  path: childRel,
7317
- content: fs8.readFileSync(path8.join(dir, childRel)).toString("base64")
8493
+ content: fs8.readFileSync(path9.join(dir, childRel)).toString("base64")
7318
8494
  });
7319
8495
  }
7320
8496
  }
@@ -7334,15 +8510,15 @@ function writeWorldFiles(dir, files, opts = {}) {
7334
8510
  if (opts.clean && fs8.existsSync(dir)) {
7335
8511
  const keep = new Set(files.map((f) => f.path));
7336
8512
  for (const existing of readWorldFiles(dir)) {
7337
- if (!keep.has(existing.path)) fs8.rmSync(path8.join(dir, existing.path));
8513
+ if (!keep.has(existing.path)) fs8.rmSync(path9.join(dir, existing.path));
7338
8514
  }
7339
8515
  pruneEmptyDirs(dir);
7340
8516
  }
7341
8517
  fs8.mkdirSync(dir, { recursive: true });
7342
8518
  const written = [];
7343
8519
  for (const file of files) {
7344
- const target = path8.join(dir, file.path);
7345
- fs8.mkdirSync(path8.dirname(target), { recursive: true });
8520
+ const target = path9.join(dir, file.path);
8521
+ fs8.mkdirSync(path9.dirname(target), { recursive: true });
7346
8522
  fs8.writeFileSync(target, Buffer.from(file.content, "base64"));
7347
8523
  written.push(file.path);
7348
8524
  }
@@ -7352,7 +8528,7 @@ function pruneEmptyDirs(root) {
7352
8528
  const walk = (abs) => {
7353
8529
  let empty = true;
7354
8530
  for (const entry of fs8.readdirSync(abs, { withFileTypes: true })) {
7355
- const child = path8.join(abs, entry.name);
8531
+ const child = path9.join(abs, entry.name);
7356
8532
  if (entry.isDirectory()) {
7357
8533
  if (SKIP_DIRS.has(entry.name)) {
7358
8534
  empty = false;
@@ -7389,13 +8565,9 @@ function yamlDocument(request) {
7389
8565
  return isYamlSource(String(request.source ?? ""), String(request.document ?? ""));
7390
8566
  return request.command === "conform" && Array.isArray(request.openapi) && request.openapi.some((doc) => YAML_NAME.test(doc.path ?? ""));
7391
8567
  }
7392
- function runsLocally(request) {
7393
- const local = localRuntime();
7394
- return local !== null && !(yamlDocument(request) && !localPythonHasYaml(local.python));
7395
- }
7396
8568
  async function runtime(creds, request, opts = {}) {
7397
- const local = localRuntime();
7398
- if (local && runsLocally(request)) {
8569
+ const local = new RuntimeRoute().local(request);
8570
+ if (local) {
7399
8571
  const payload2 = await localBridge(request, local, opts);
7400
8572
  const detail2 = detailFrom(payload2);
7401
8573
  if (detail2) throw new BridgeRejected(detail2);
@@ -7422,17 +8594,17 @@ async function runtime(creds, request, opts = {}) {
7422
8594
  if (payload === null) throw new CliError(`POST ${route} (${request.command}) returned non-JSON`, 1);
7423
8595
  return payload;
7424
8596
  }
7425
- var MAX_WORLD_FILES, RUNTIME_TIMEOUT_MS, SKIP_DIRS, BUILD_OUTPUT, BridgeRejected, YAML_NAME;
8597
+ var MAX_WORLD_FILES, RUNTIME_TIMEOUT_MS, SKIP_DIRS, BridgeRejected, YAML_NAME, YAML_NEEDS_PYYAML, YAML_NOT_ON_PLATFORM, RuntimeRoute;
7426
8598
  var init_client = __esm({
7427
8599
  "src/cli/runtime/client.ts"() {
7428
8600
  "use strict";
7429
8601
  init_router();
7430
8602
  init_local();
7431
8603
  init_transport();
8604
+ init_databaseEngines();
7432
8605
  MAX_WORLD_FILES = 2e3;
7433
8606
  RUNTIME_TIMEOUT_MS = 18e4;
7434
8607
  SKIP_DIRS = /* @__PURE__ */ new Set(["__pycache__", ".git", "node_modules", ".gateway"]);
7435
- BUILD_OUTPUT = /(^|\/)state\.(sqlite|json)$/;
7436
8608
  BridgeRejected = class extends CliError {
7437
8609
  constructor(detail) {
7438
8610
  super(formatBridgeError(detail), 1);
@@ -7441,6 +8613,26 @@ var init_client = __esm({
7441
8613
  detail;
7442
8614
  };
7443
8615
  YAML_NAME = /\.ya?ml$/i;
8616
+ YAML_NEEDS_PYYAML = "Reading a YAML document needs PyYAML in the Python that runs the schema runtime: pip install pyyaml there, set GATEWAY_PYTHON to an interpreter that has it, or convert the document to JSON";
8617
+ YAML_NOT_ON_PLATFORM = "The platform's schema runtime reads JSON documents only: convert the document to JSON, or read it here with GATEWAY_RUNTIME=local and a Python that has PyYAML (pip install pyyaml, or set GATEWAY_PYTHON to one)";
8618
+ RuntimeRoute = class _RuntimeRoute {
8619
+ constructor(here = localRuntime, hasYaml = localPythonHasYaml) {
8620
+ this.here = here;
8621
+ this.hasYaml = hasYaml;
8622
+ }
8623
+ here;
8624
+ hasYaml;
8625
+ local(request) {
8626
+ const local = this.here();
8627
+ const yaml = yamlDocument(request);
8628
+ if (yaml && local === null) throw _RuntimeRoute.refusal(YAML_NOT_ON_PLATFORM);
8629
+ if (yaml && local !== null && !this.hasYaml(local.python)) throw _RuntimeRoute.refusal(YAML_NEEDS_PYYAML);
8630
+ return local;
8631
+ }
8632
+ static refusal(message) {
8633
+ return new BridgeRejected({ code: "conform", message, schema_path: "/openapi/source" });
8634
+ }
8635
+ };
7444
8636
  }
7445
8637
  });
7446
8638
 
@@ -7455,10 +8647,11 @@ __export(data_exports, {
7455
8647
  ingestLocalToolCalls: () => ingestLocalToolCalls,
7456
8648
  queryLocalWorldData: () => queryLocalWorldData,
7457
8649
  queryLocalWorldDataAcross: () => queryLocalWorldDataAcross,
7458
- showLocalWorldData: () => showLocalWorldData
8650
+ showLocalWorldData: () => showLocalWorldData,
8651
+ sqlLocalWorldData: () => sqlLocalWorldData
7459
8652
  });
7460
8653
  import * as fs9 from "fs";
7461
- import * as path9 from "path";
8654
+ import * as path10 from "path";
7462
8655
  async function importLocalWorldData(dir, rows, opts, creds) {
7463
8656
  const res = await runtime(creds, {
7464
8657
  command: "import-data",
@@ -7489,8 +8682,8 @@ async function importLocalWorldFiles(dir, sources, opts) {
7489
8682
  );
7490
8683
  const res = await runtime(null, {
7491
8684
  command: "import-files",
7492
- world: path9.resolve(dir),
7493
- sources: sources.map((source) => path9.resolve(source)),
8685
+ world: path10.resolve(dir),
8686
+ sources: sources.map((source) => path10.resolve(source)),
7494
8687
  mode: opts.mode ?? "append",
7495
8688
  ...opts.entity ? { entity: opts.entity } : {},
7496
8689
  ...opts.delimiter ? { delimiter: opts.delimiter } : {},
@@ -7516,9 +8709,9 @@ async function chunkLocalWorldFiles(dir, sources, out, opts) {
7516
8709
  );
7517
8710
  const res = await runtime(null, {
7518
8711
  command: "chunk-files",
7519
- world: path9.resolve(dir),
7520
- sources: sources.map((source) => path9.resolve(source)),
7521
- out: path9.resolve(out),
8712
+ world: path10.resolve(dir),
8713
+ sources: sources.map((source) => path10.resolve(source)),
8714
+ out: path10.resolve(out),
7522
8715
  ...opts.entity ? { entity: opts.entity } : {},
7523
8716
  ...opts.delimiter ? { delimiter: opts.delimiter } : {},
7524
8717
  ...opts.chunkBytes ? { chunk_bytes: opts.chunkBytes } : {},
@@ -7529,8 +8722,8 @@ async function chunkLocalWorldFiles(dir, sources, out, opts) {
7529
8722
  function dropBuildOutputs(dir) {
7530
8723
  const dropped = [];
7531
8724
  for (const file of readWorldFiles(dir, { buildOutputs: true })) {
7532
- if (!BUILD_OUTPUT2.test(file.path)) continue;
7533
- fs9.rmSync(path9.join(dir, file.path), { force: true });
8725
+ if (!isBuildOutput(file.path)) continue;
8726
+ fs9.rmSync(path10.join(dir, file.path), { force: true });
7534
8727
  dropped.push(file.path);
7535
8728
  }
7536
8729
  return dropped;
@@ -7597,7 +8790,7 @@ async function queryLocalWorldDataAcross(dir, entity, where, opts) {
7597
8790
  const payload = await localBridge(
7598
8791
  {
7599
8792
  command: "query",
7600
- world: path9.resolve(dir),
8793
+ world: path10.resolve(dir),
7601
8794
  entity,
7602
8795
  across: true,
7603
8796
  ...opts.compare ? { compare: true } : {},
@@ -7613,6 +8806,28 @@ async function queryLocalWorldDataAcross(dir, entity, where, opts) {
7613
8806
  if (detail) throw new BridgeRejected(detail);
7614
8807
  return payload;
7615
8808
  }
8809
+ async function sqlLocalWorldData(dir, sql, opts) {
8810
+ const local = localRuntime();
8811
+ if (!local)
8812
+ throw new CliError(
8813
+ "`worlds data sql` on a directory reads the world's database in place, so it needs the bundled runtime on this machine. " + localRuntimeReason(),
8814
+ 1
8815
+ );
8816
+ const payload = await localBridge(
8817
+ {
8818
+ command: "sql",
8819
+ world: path10.resolve(dir),
8820
+ sql,
8821
+ ...opts.limit !== void 0 ? { limit: opts.limit } : {},
8822
+ ...opts.scenario ? { scenario: opts.scenario } : {}
8823
+ },
8824
+ local
8825
+ );
8826
+ const detail = detailFrom(payload);
8827
+ if (detail) throw new BridgeRejected(detail);
8828
+ const { status: _status, ...answer } = payload;
8829
+ return answer;
8830
+ }
7616
8831
  async function ingestLocalToolCalls(dir, records, opts, creds) {
7617
8832
  const res = await runtime(creds, {
7618
8833
  command: "ingest-calls",
@@ -7644,14 +8859,12 @@ async function ingestLocalToolCalls(dir, records, opts, creds) {
7644
8859
  ...res.batch !== void 0 ? { batch: res.batch } : {}
7645
8860
  };
7646
8861
  }
7647
- var BUILD_OUTPUT2;
7648
8862
  var init_data = __esm({
7649
8863
  "src/cli/runtime/data.ts"() {
7650
8864
  "use strict";
7651
8865
  init_router();
7652
8866
  init_client();
7653
8867
  init_local();
7654
- BUILD_OUTPUT2 = /(^|\/)state\.(sqlite|json)$/;
7655
8868
  }
7656
8869
  });
7657
8870
 
@@ -7670,7 +8883,7 @@ __export(transform_exports, {
7670
8883
  import { spawn as spawn2 } from "child_process";
7671
8884
  import * as fs10 from "fs";
7672
8885
  import * as os2 from "os";
7673
- import * as path10 from "path";
8886
+ import * as path11 from "path";
7674
8887
  import { createRequire } from "module";
7675
8888
  function checkRows(value, where) {
7676
8889
  if (!isObject(value)) throw new CliError(`${where} must return {entity: [rows]}; got ${value === null ? "null" : Array.isArray(value) ? "an array" : typeof value}`, 1);
@@ -7695,27 +8908,27 @@ function typescriptPrefix() {
7695
8908
  }
7696
8909
  }
7697
8910
  function command(script, wrapperDir) {
7698
- const suffix = path10.extname(script).toLowerCase();
8911
+ const suffix = path11.extname(script).toLowerCase();
7699
8912
  if (PYTHON_SUFFIXES.includes(suffix)) return { file: process.env.GATEWAY_PYTHON || "python3", args: ["-c", PY_WRAPPER, script] };
7700
8913
  if (NODE_SUFFIXES.includes(suffix)) {
7701
- const wrapper = path10.join(wrapperDir, "transform-wrapper.mjs");
8914
+ const wrapper = path11.join(wrapperDir, "transform-wrapper.mjs");
7702
8915
  fs10.writeFileSync(wrapper, NODE_WRAPPER);
7703
8916
  const flags = suffix === ".ts" || suffix === ".mts" ? typescriptPrefix() : [];
7704
8917
  return { file: process.env.GATEWAY_NODE || process.execPath, args: [...flags, wrapper, script] };
7705
8918
  }
7706
- throw new CliError(`${path10.basename(script)}: a transform script is .py, .ts, .mjs, .js or .cjs`, 1);
8919
+ throw new CliError(`${path11.basename(script)}: a transform script is .py, .ts, .mjs, .js or .cjs`, 1);
7707
8920
  }
7708
8921
  async function runTransform(script, records, opts = {}) {
7709
8922
  if (!fs10.existsSync(script) || !fs10.statSync(script).isFile()) throw new CliError(`no transform script at ${script}`, 1);
7710
- const resolved = path10.resolve(script);
7711
- const name = path10.basename(script);
8923
+ const resolved = path11.resolve(script);
8924
+ const name = path11.basename(script);
7712
8925
  const timeoutMs = opts.timeoutMs ?? DEFAULT_TRANSFORM_TIMEOUT_MS;
7713
- const scratch = fs10.mkdtempSync(path10.join(os2.tmpdir(), "gateway-transform-"));
8926
+ const scratch = fs10.mkdtempSync(path11.join(os2.tmpdir(), "gateway-transform-"));
7714
8927
  try {
7715
8928
  const { file, args } = command(resolved, scratch);
7716
8929
  const env = Object.fromEntries(Object.entries(process.env).filter(([key2]) => !SCRUBBED.test(key2)));
7717
8930
  const done = await new Promise((resolve11, reject) => {
7718
- const child = spawn2(file, args, { cwd: path10.dirname(resolved), env, stdio: ["pipe", "pipe", "pipe"] });
8931
+ const child = spawn2(file, args, { cwd: path11.dirname(resolved), env, stdio: ["pipe", "pipe", "pipe"] });
7719
8932
  let stdout = "";
7720
8933
  let stderr = "";
7721
8934
  let timedOut = false;
@@ -7838,18 +9051,22 @@ if (fn) {
7838
9051
  });
7839
9052
 
7840
9053
  // src/cli/platform/worldData/batches.ts
7841
- import { createHash as createHash8 } from "crypto";
9054
+ import { createHash as createHash9 } from "crypto";
7842
9055
  import * as fs11 from "fs";
7843
9056
  function isSettled(status) {
7844
9057
  if (!TERMINAL_STATES.has(status.state)) return false;
7845
9058
  if (status.state !== "applied") return true;
7846
9059
  return status.dryRun === true || status.publish !== "now" || !status.snapshotId;
7847
9060
  }
9061
+ function worldDataPollMs() {
9062
+ const raw = Number(process.env.GATEWAY_WORLD_DATA_POLL_MS ?? 1e3);
9063
+ return Number.isFinite(raw) && raw >= 0 ? raw : 1e3;
9064
+ }
7848
9065
  function uploadHeadersFor(gz) {
7849
9066
  return {
7850
9067
  "content-type": "application/gzip",
7851
9068
  "content-length": String(gz.length),
7852
- "x-amz-checksum-sha256": createHash8("sha256").update(gz).digest("base64")
9069
+ "x-amz-checksum-sha256": createHash9("sha256").update(gz).digest("base64")
7853
9070
  };
7854
9071
  }
7855
9072
  async function forEachLimited(items, limit, fn) {
@@ -7876,7 +9093,7 @@ async function forEachLimited(items, limit, fn) {
7876
9093
  if (failure) throw failure;
7877
9094
  }
7878
9095
  async function waitForBatch(client2, batchId, opts = {}) {
7879
- const sleep3 = opts.sleep ?? client2.sleep;
9096
+ const sleep5 = opts.sleep ?? client2.sleep;
7880
9097
  let delay = opts.initialDelayMs ?? 1e3;
7881
9098
  let last = "";
7882
9099
  for (; ; ) {
@@ -7887,7 +9104,9 @@ async function waitForBatch(client2, batchId, opts = {}) {
7887
9104
  last = phase;
7888
9105
  }
7889
9106
  if (isSettled(status)) return status;
7890
- await sleep3(delay);
9107
+ if (opts.deadlineMs !== void 0 && (opts.now ?? Date.now)() >= opts.deadlineMs)
9108
+ return status;
9109
+ await sleep5(delay);
7891
9110
  delay = Math.min(1e4, Math.round(delay * 1.5));
7892
9111
  }
7893
9112
  }
@@ -7909,10 +9128,10 @@ var init_batches = __esm({
7909
9128
  ]);
7910
9129
  sleepMs = (ms) => new Promise((resolve11) => setTimeout(resolve11, ms));
7911
9130
  WorldDataApi = class {
7912
- constructor(creds, slug, sleep3 = sleepMs) {
9131
+ constructor(creds, slug, sleep5 = sleepMs) {
7913
9132
  this.creds = creds;
7914
9133
  this.slug = slug;
7915
- this.sleep = sleep3;
9134
+ this.sleep = sleep5;
7916
9135
  this.base = `/api/public/worlds/${encodeURIComponent(slug)}/data`;
7917
9136
  }
7918
9137
  creds;
@@ -7936,11 +9155,6 @@ var init_batches = __esm({
7936
9155
  }
7937
9156
  );
7938
9157
  }
7939
- /**
7940
- * Stage a project-drive rows file as one chunk, on the platform: the server
7941
- * streams it out of drive storage into chunk storage and answers with the
7942
- * digest and gzipped size it derived. No bytes pass through this process.
7943
- */
7944
9158
  async stageDrive(batchId, chunk) {
7945
9159
  const staged = await api(this.creds, "POST", `${this.base}/batches/${batchId}/chunks`, {
7946
9160
  ordinal: chunk.ordinal,
@@ -7994,11 +9208,6 @@ var init_batches = __esm({
7994
9208
  message ? { message } : {}
7995
9209
  );
7996
9210
  }
7997
- /**
7998
- * PUT the gzipped chunk to its presigned URL with exactly the headers the
7999
- * URL was signed for (the platform's `uploadHeaders`; the same three when it
8000
- * sends none), with backoff on a dropped connection or a 5xx.
8001
- */
8002
9211
  async put(uploadUrl, gz, signed) {
8003
9212
  const headers = signed ?? uploadHeadersFor(gz);
8004
9213
  const delays = [500, 1500, 4e3];
@@ -8025,7 +9234,6 @@ var init_batches = __esm({
8025
9234
  await this.sleep(delays[attempt]);
8026
9235
  }
8027
9236
  }
8028
- /** Register, upload unless the server already holds the content, confirm. */
8029
9237
  async upload(batchId, chunk) {
8030
9238
  const registered = await this.register(batchId, chunk);
8031
9239
  if (!registered.uploaded) {
@@ -8052,7 +9260,7 @@ var init_batches = __esm({
8052
9260
  });
8053
9261
 
8054
9262
  // src/cli/platform/worldData/chunker.ts
8055
- import { createHash as createHash9 } from "crypto";
9263
+ import { createHash as createHash10 } from "crypto";
8056
9264
  import { deflateRawSync } from "zlib";
8057
9265
  function chunkLine(row, declared) {
8058
9266
  if (declared !== null) return dumps(row.row) + "\n";
@@ -8093,12 +9301,12 @@ function finishChunk(ordinal, raw, rows, entity, firstRow = 0) {
8093
9301
  const gz = gzipDeterministic(raw, { name: chunkName(ordinal) });
8094
9302
  return {
8095
9303
  ordinal,
8096
- digest: createHash9("sha256").update(gz).digest("hex"),
9304
+ digest: createHash10("sha256").update(gz).digest("hex"),
8097
9305
  bytes: gz.length,
8098
9306
  rows,
8099
9307
  entity,
8100
9308
  rawBytes: raw.length,
8101
- contentSha256: createHash9("sha256").update(raw).digest("hex"),
9309
+ contentSha256: createHash10("sha256").update(raw).digest("hex"),
8102
9310
  firstRow,
8103
9311
  gz
8104
9312
  };
@@ -8166,22 +9374,33 @@ async function pushRows(creds, slug, rows, opts = {}) {
8166
9374
  publish: opts.publish ?? "now",
8167
9375
  ...opts.message ? { message: opts.message } : {}
8168
9376
  });
8169
- if (!opened.batchId) throw new Error("the platform opened no batch (no batchId in the answer)");
9377
+ if (!opened.batchId)
9378
+ throw new Error("the platform opened no batch (no batchId in the answer)");
8170
9379
  const tagged = (async function* () {
8171
9380
  for (const [entity, listed] of Object.entries(rows))
8172
9381
  for (let index2 = 0; index2 < listed.length; index2++)
8173
- yield { entity, row: parseJson(JSON.stringify(listed[index2])), where: `${entity}[${index2}]` };
9382
+ yield {
9383
+ entity,
9384
+ row: parseJson(JSON.stringify(listed[index2])),
9385
+ where: `${entity}[${index2}]`
9386
+ };
8174
9387
  })();
8175
- const chunks = buildChunks(tagged, { chunkBytes: opts.chunkBytes ?? DEFAULT_CHUNK_BYTES, chunkRows: null, entity: null });
8176
- await forEachLimited(chunks, Math.max(1, opts.parallel ?? 4), async (chunk) => {
8177
- await client2.upload(opened.batchId, chunk);
9388
+ const chunks = buildChunks(tagged, {
9389
+ chunkBytes: opts.chunkBytes ?? DEFAULT_CHUNK_BYTES,
9390
+ chunkRows: null,
9391
+ entity: null
8178
9392
  });
9393
+ await forEachLimited(
9394
+ chunks,
9395
+ Math.max(1, opts.parallel ?? 4),
9396
+ async (chunk) => {
9397
+ await client2.upload(opened.batchId, chunk);
9398
+ }
9399
+ );
8179
9400
  await client2.complete(opened.batchId);
8180
- return waitForBatch(client2, opened.batchId, { initialDelayMs: pollMs() });
8181
- }
8182
- function pollMs() {
8183
- const raw = Number(process.env.GATEWAY_WORLD_DATA_POLL_MS ?? 1e3);
8184
- return Number.isFinite(raw) && raw >= 0 ? raw : 1e3;
9401
+ return waitForBatch(client2, opened.batchId, {
9402
+ initialDelayMs: worldDataPollMs()
9403
+ });
8185
9404
  }
8186
9405
  var init_push = __esm({
8187
9406
  "src/cli/platform/worldData/push.ts"() {
@@ -8195,7 +9414,7 @@ var init_push = __esm({
8195
9414
  // src/worlds/ingest.ts
8196
9415
  import * as fs12 from "fs";
8197
9416
  import * as os3 from "os";
8198
- import * as path11 from "path";
9417
+ import * as path12 from "path";
8199
9418
  function parseToolCallRecord(raw) {
8200
9419
  const none = { record: null, skip: null };
8201
9420
  if (!isObject2(raw)) return { ...none, refusal: "record is not an object" };
@@ -8319,19 +9538,13 @@ function toolCallsFromObservations(observations, opts = {}) {
8319
9538
  }
8320
9539
  return out;
8321
9540
  }
8322
- function credentialsOf(options) {
8323
- const host = (options.host ?? process.env.GATEWAY_HOST ?? "https://withgateway.ai").replace(/\/+$/, "");
8324
- const publicKey = options.publicKey ?? process.env.GATEWAY_PUBLIC_KEY;
8325
- const secretKey = options.secretKey ?? process.env.GATEWAY_SECRET_KEY;
8326
- return publicKey && secretKey ? { host, publicKey, secretKey } : null;
8327
- }
8328
9541
  async function ingest(world, records, options = {}) {
8329
9542
  const { ingestLocalToolCalls: ingestLocalToolCalls2, importLocalWorldData: importLocalWorldData2, checkLocalWorldData: checkLocalWorldData2 } = await Promise.resolve().then(() => (init_data(), data_exports));
8330
9543
  if (options.transform !== void 0 && options.map !== void 0) throw new Error("records go through one of transform, map");
8331
9544
  const redact = options.redact ?? "off";
8332
9545
  const mode = options.mode ?? "append";
8333
9546
  const dryRun = Boolean(options.dryRun);
8334
- const creds = credentialsOf(options);
9547
+ const creds = platformEndpoint(options);
8335
9548
  const local = fs12.existsSync(world) && fs12.statSync(world).isDirectory();
8336
9549
  const map = options.map === void 0 ? void 0 : options.map;
8337
9550
  let rows = null;
@@ -8345,12 +9558,12 @@ async function ingest(world, records, options = {}) {
8345
9558
  const landed = dryRun ? await checkLocalWorldData2(world, rows, creds, { redact }) : await importLocalWorldData2(world, rows, { mode, redact }, creds);
8346
9559
  return transformReport(world, records.length, rows, stderr, { dryRun, redact, changed: !dryRun && landed.changed, kind: landed.kind, entityCounts: landed.entity_counts });
8347
9560
  }
8348
- if (!creds) throw new Error("Gateway keys missing: set GATEWAY_PUBLIC_KEY / GATEWAY_SECRET_KEY (or pass publicKey/secretKey).");
9561
+ if (!creds) throw new Error(GATEWAY_KEYS_MISSING);
8349
9562
  const { pull: pull2 } = await Promise.resolve().then(() => (init_hub(), hub_exports));
8350
9563
  const slug = world.split("@", 1)[0];
8351
- const scratch = fs12.mkdtempSync(path11.join(os3.tmpdir(), "gateway-ingest-"));
9564
+ const scratch = fs12.mkdtempSync(path12.join(os3.tmpdir(), "gateway-ingest-"));
8352
9565
  try {
8353
- const pulled = await pull2(world, path11.join(scratch, slug), options);
9566
+ const pulled = await pull2(world, path12.join(scratch, slug), options);
8354
9567
  let report;
8355
9568
  let projected;
8356
9569
  if (rows === null) {
@@ -8429,18 +9642,19 @@ var init_ingest = __esm({
8429
9642
  "src/worlds/ingest.ts"() {
8430
9643
  "use strict";
8431
9644
  init_worlds();
9645
+ init_platformEndpoint();
8432
9646
  isObject2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
8433
9647
  isoOf = (value) => value instanceof Date ? value.toISOString() : typeof value === "string" ? value : void 0;
8434
9648
  }
8435
9649
  });
8436
9650
 
8437
9651
  // src/worlds/editSessions.ts
8438
- var WORLDS, WorldEditClient, TASK_EDITS, TaskEditClient;
9652
+ var WORLDS2, WorldEditClient, TASK_EDITS, TaskEditClient;
8439
9653
  var init_editSessions = __esm({
8440
9654
  "src/worlds/editSessions.ts"() {
8441
9655
  "use strict";
8442
9656
  init_worlds();
8443
- WORLDS = "/api/public/worlds";
9657
+ WORLDS2 = "/api/public/worlds";
8444
9658
  WorldEditClient = class {
8445
9659
  constructor(options = {}) {
8446
9660
  this.options = options;
@@ -8452,19 +9666,19 @@ var init_editSessions = __esm({
8452
9666
  if (query.status) qs3.set("status", query.status);
8453
9667
  if (query.limit !== void 0) qs3.set("limit", String(query.limit));
8454
9668
  const suffix = qs3.size ? `?${qs3.toString()}` : "";
8455
- return apiRequest(this.options, "GET", `${WORLDS}/${encodeURIComponent(slug)}/edits${suffix}`);
9669
+ return apiRequest(this.options, "GET", `${WORLDS2}/${encodeURIComponent(slug)}/edits${suffix}`);
8456
9670
  }
8457
9671
  /** Seal a session into a version on main (the credential's current one when `sessionId` is omitted). */
8458
9672
  close(slug, input = {}) {
8459
- return apiRequest(this.options, "POST", `${WORLDS}/${encodeURIComponent(slug)}/edits/close`, input);
9673
+ return apiRequest(this.options, "POST", `${WORLDS2}/${encodeURIComponent(slug)}/edits/close`, input);
8460
9674
  }
8461
9675
  /** Drop the session's private branch without making a version. */
8462
9676
  discard(slug, input = {}) {
8463
- return apiRequest(this.options, "POST", `${WORLDS}/${encodeURIComponent(slug)}/edits/discard`, input);
9677
+ return apiRequest(this.options, "POST", `${WORLDS2}/${encodeURIComponent(slug)}/edits/discard`, input);
8464
9678
  }
8465
9679
  /** Undo a sealed session (source and data) as a new sealed session. */
8466
9680
  rollback(slug, input) {
8467
- return apiRequest(this.options, "POST", `${WORLDS}/${encodeURIComponent(slug)}/edits/rollback`, input);
9681
+ return apiRequest(this.options, "POST", `${WORLDS2}/${encodeURIComponent(slug)}/edits/rollback`, input);
8468
9682
  }
8469
9683
  };
8470
9684
  TASK_EDITS = "/api/public/world-task-edits";
@@ -8529,7 +9743,7 @@ var init_dryRun = __esm({
8529
9743
  /** Poll until the run settles or `timeoutSeconds` pass; the last verdict either way. */
8530
9744
  async settle(runId, opts) {
8531
9745
  const now = opts.now ?? Date.now;
8532
- const sleep3 = opts.sleep ?? ((ms) => new Promise((resolve11) => setTimeout(resolve11, ms)));
9746
+ const sleep5 = opts.sleep ?? ((ms) => new Promise((resolve11) => setTimeout(resolve11, ms)));
8533
9747
  const deadline = now() + opts.timeoutSeconds * 1e3;
8534
9748
  for (; ; ) {
8535
9749
  const budget = Math.floor(
@@ -8539,7 +9753,7 @@ var init_dryRun = __esm({
8539
9753
  const verdict = await this.status(runId, budget);
8540
9754
  if (verdict.settled || now() >= deadline) return verdict;
8541
9755
  opts.onProgress?.(verdict);
8542
- if (now() - asked < 1e3) await sleep3(1e3);
9756
+ if (now() - asked < 1e3) await sleep5(1e3);
8543
9757
  }
8544
9758
  }
8545
9759
  };
@@ -8607,6 +9821,8 @@ __export(worlds_exports, {
8607
9821
  EXPLORATORY_TASK: () => EXPLORATORY_TASK,
8608
9822
  EXPLORATORY_TASK_SOURCE: () => EXPLORATORY_TASK_SOURCE,
8609
9823
  GatewayEvalsClient: () => GatewayEvalsClient,
9824
+ GradePayload: () => GradePayload,
9825
+ GradeRefused: () => GradeRefused,
8610
9826
  HostedDryRunClient: () => HostedDryRunClient,
8611
9827
  IDLE_WARNING_MINUTES: () => IDLE_WARNING_MINUTES,
8612
9828
  KEY_NAMES: () => KEY_NAMES,
@@ -8616,52 +9832,80 @@ __export(worlds_exports, {
8616
9832
  NativeComputer: () => NativeComputer,
8617
9833
  OpenAIComputer: () => OpenAIComputer,
8618
9834
  OpenAIPreviewComputer: () => OpenAIPreviewComputer,
9835
+ PLATFORM_SESSION_HEADER: () => PLATFORM_SESSION_HEADER,
8619
9836
  PLATFORM_TIMEOUT_DEFAULT_MS: () => PLATFORM_TIMEOUT_DEFAULT_MS,
8620
9837
  PLATFORM_TIMEOUT_ENV: () => PLATFORM_TIMEOUT_ENV,
8621
9838
  PendingSafetyChecks: () => PendingSafetyChecks,
8622
9839
  PlatformTransport: () => PlatformTransport,
8623
9840
  PushSlugConflict: () => PushSlugConflict,
8624
9841
  RECOVER_BUDGET_MS: () => RECOVER_BUDGET_MS,
9842
+ REQUESTS_NOT_RECORDED: () => REQUESTS_NOT_RECORDED,
9843
+ REQUEST_BODY_CAPTURE_BYTES: () => REQUEST_BODY_CAPTURE_BYTES,
9844
+ REQUEST_LOG_PAGE_MAX: () => REQUEST_LOG_PAGE_MAX,
9845
+ RetryPolicy: () => RetryPolicy,
9846
+ SANDBOX_EXEC_REPORT_MARGIN_MS: () => SANDBOX_EXEC_REPORT_MARGIN_MS,
9847
+ SANDBOX_EXEC_START_ATTEMPTS: () => SANDBOX_EXEC_START_ATTEMPTS,
9848
+ SANDBOX_EXEC_TIMEOUT_MAX_S: () => SANDBOX_EXEC_TIMEOUT_MAX_S,
9849
+ SANDBOX_EXEC_WAIT_MS: () => SANDBOX_EXEC_WAIT_MS,
9850
+ SANDBOX_FILE_MAX_BYTES: () => SANDBOX_FILE_MAX_BYTES,
8625
9851
  SANDBOX_REQUEST_TIMEOUT_MS: () => SANDBOX_REQUEST_TIMEOUT_MS,
9852
+ SANDBOX_WRITE_CHUNK_BYTES: () => SANDBOX_WRITE_CHUNK_BYTES,
9853
+ SANDBOX_WRITE_SKIPPED: () => SANDBOX_WRITE_SKIPPED,
8626
9854
  SECRET_KEY: () => SECRET_KEY,
9855
+ SESSION_AUTH_MODES: () => SESSION_AUTH_MODES,
8627
9856
  SESSION_STATES: () => SESSION_STATES,
8628
9857
  SPAN_PREFIX: () => SPAN_PREFIX,
8629
9858
  STATUS_WAIT_CAP_SECONDS: () => STATUS_WAIT_CAP_SECONDS,
8630
9859
  STRIP_PREFIX: () => STRIP_PREFIX,
8631
9860
  SURFACE_KINDS: () => SURFACE_KINDS,
9861
+ Score: () => Score,
8632
9862
  Screen: () => Screen,
8633
9863
  SecretScrubber: () => SecretScrubber,
9864
+ TOOL_CONTRACT_UNREAD: () => TOOL_CONTRACT_UNREAD,
8634
9865
  TRANSFORMS: () => TRANSFORMS,
8635
9866
  TaskEditClient: () => TaskEditClient,
9867
+ TaskGrades: () => TaskGrades,
8636
9868
  TaskRun: () => TaskRun,
8637
9869
  TaskSessions: () => TaskSessions,
8638
9870
  TransportCause: () => TransportCause,
8639
9871
  UnreachableError: () => UnreachableError,
8640
9872
  VERIFIER_REWARD_PREFIX: () => VERIFIER_REWARD_PREFIX,
8641
9873
  WHITESPACE: () => WHITESPACE,
9874
+ WORLD_REQUEST_VIAS: () => WORLD_REQUEST_VIAS,
8642
9875
  WorldBrowser: () => WorldBrowser,
8643
9876
  WorldCallTooLarge: () => WorldCallTooLarge,
8644
9877
  WorldEditClient: () => WorldEditClient,
9878
+ WorldNotice: () => WorldNotice,
9879
+ WorldRequestFilterError: () => WorldRequestFilterError,
9880
+ WorldRequestLedger: () => WorldRequestLedger,
8645
9881
  WorldRequestLog: () => WorldRequestLog,
9882
+ WorldRequestQuery: () => WorldRequestQuery,
9883
+ WorldRequestsNotRecorded: () => WorldRequestsNotRecorded,
8646
9884
  WorldSandboxClient: () => WorldSandboxClient,
8647
9885
  WorldSession: () => WorldSession,
8648
9886
  WorldSessionCallError: () => WorldSessionCallError,
9887
+ WorldSessionOpenFailed: () => WorldSessionOpenFailed,
8649
9888
  WorldSessionTimeout: () => WorldSessionTimeout,
8650
9889
  WorldSet: () => WorldSet,
8651
9890
  WorldSurfaceUnavailable: () => WorldSurfaceUnavailable,
8652
9891
  WorldTask: () => WorldTask,
9892
+ WorldToolsUnread: () => WorldToolsUnread,
9893
+ WriteTreeFilter: () => WriteTreeFilter,
8653
9894
  aggregateTaskGrade: () => aggregateTaskGrade,
8654
9895
  apiRequest: () => apiRequest,
8655
9896
  applyTransforms: () => applyTransforms,
8656
9897
  archiveMode: () => archiveMode,
8657
9898
  assertBrowserTier: () => assertBrowserTier,
9899
+ assertSessionAuthMode: () => assertSessionAuthMode,
8658
9900
  assertTaskRef: () => assertTaskRef,
8659
9901
  attachManifest: () => attachManifest,
8660
9902
  attachSession: () => attachSession,
8661
9903
  attachTask: () => attachTask,
8662
9904
  buildFileManifest: () => buildFileManifest,
8663
9905
  buildSourceTarball: () => buildSourceTarball,
9906
+ capabilityLabel: () => capabilityLabel,
8664
9907
  captureToolCalls: () => captureToolCalls,
9908
+ carriedWarnings: () => carriedWarnings,
8665
9909
  checkoutIdentity: () => checkoutIdentity,
8666
9910
  closeConnection: () => closeConnection,
8667
9911
  collectArchiveRelPaths: () => collectArchiveRelPaths,
@@ -8680,7 +9924,9 @@ __export(worlds_exports, {
8680
9924
  idleWarning: () => idleWarning,
8681
9925
  ingest: () => ingest,
8682
9926
  ingestToolCalls: () => ingestToolCalls,
9927
+ invalidFields: () => invalidFields,
8683
9928
  isBrowserGone: () => isBrowserGone,
9929
+ isSandboxCommitPending: () => isSandboxCommitPending,
8684
9930
  isSandboxImportPending: () => isSandboxImportPending,
8685
9931
  isTaskIdRef: () => isTaskIdRef,
8686
9932
  isTaskManifest: () => isTaskManifest,
@@ -8692,6 +9938,7 @@ __export(worlds_exports, {
8692
9938
  listTaskSessions: () => listTaskSessions,
8693
9939
  listTasks: () => listTasks,
8694
9940
  localTreeState: () => localTreeState,
9941
+ messageOf: () => messageOf,
8695
9942
  migrateProjectWorlds: () => migrateProjectWorlds,
8696
9943
  migrateWorld: () => migrateWorld,
8697
9944
  modelToolName: () => modelToolName,
@@ -8726,6 +9973,7 @@ __export(worlds_exports, {
8726
9973
  resolveBrowserMode: () => resolveBrowserMode,
8727
9974
  resolvePushSlug: () => resolvePushSlug,
8728
9975
  roundForm: () => roundForm,
9976
+ rowsRefusal: () => rowsRefusal,
8729
9977
  runSessions: () => runSessions,
8730
9978
  runSet: () => runSet,
8731
9979
  runTask: () => runTask,
@@ -8735,10 +9983,14 @@ __export(worlds_exports, {
8735
9983
  setEnvSecret: () => setEnvSecret,
8736
9984
  shapeText: () => shapeText,
8737
9985
  snapshotTreeHashes: () => snapshotTreeHashes,
9986
+ sqlRows: () => sqlRows,
9987
+ stillStartingHint: () => stillStartingHint,
8738
9988
  storedForms: () => storedForms,
8739
9989
  surfaceDescriptor: () => surfaceDescriptor,
8740
9990
  surfaceKinds: () => surfaceKinds,
9991
+ taskGradeError: () => taskGradeError,
8741
9992
  taskLabel: () => taskLabel,
9993
+ taskRunFailure: () => taskRunFailure,
8742
9994
  toolCallRecordsIn: () => toolCallRecordsIn,
8743
9995
  toolCallsFromObservations: () => toolCallsFromObservations,
8744
9996
  uiEntryUrl: () => uiEntryUrl,
@@ -8750,41 +10002,45 @@ __export(worlds_exports, {
8750
10002
  validateWorld: () => validateWorld,
8751
10003
  waitForRun: () => waitForRun,
8752
10004
  withoutUiToken: () => withoutUiToken,
10005
+ worldRequestsUnrecorded: () => worldRequestsUnrecorded,
8753
10006
  writeLocalMeta: () => writeLocalMeta
8754
10007
  });
8755
- function resolveEnv(options) {
8756
- const host = options.host ?? process.env.GATEWAY_HOST ?? "https://withgateway.ai";
8757
- const publicKey = options.publicKey ?? process.env.GATEWAY_PUBLIC_KEY;
8758
- const secretKey = options.secretKey ?? process.env.GATEWAY_SECRET_KEY;
8759
- if (!publicKey || !secretKey) {
8760
- throw new Error(
8761
- "Gateway keys missing: set GATEWAY_PUBLIC_KEY / GATEWAY_SECRET_KEY (or pass publicKey/secretKey)."
8762
- );
8763
- }
8764
- return { host: host.replace(/\/+$/, ""), publicKey, secretKey };
10008
+ function edgeAnswer(text2, status) {
10009
+ if (status !== void 0 && status >= 500) return EDGE_ANSWERS[status] ?? EDGE_FAILURE;
10010
+ return /^\s*</.test(text2) ? EDGE_PAGE : null;
8765
10011
  }
8766
- function parseErrorBody(text2, limit = 600) {
8767
- const raw = { detail: text2.slice(0, limit), code: null };
10012
+ function parseErrorBody(text2, status) {
10013
+ const raw = { detail: text2.slice(0, DETAIL_LIMIT), code: null };
8768
10014
  let parsed;
8769
10015
  try {
8770
10016
  parsed = JSON.parse(text2);
8771
10017
  } catch {
8772
- return raw;
10018
+ return { detail: (edgeAnswer(text2, status) ?? text2).slice(0, DETAIL_LIMIT), code: null };
8773
10019
  }
8774
10020
  if (parsed === null || typeof parsed !== "object") return raw;
8775
- const { message, code } = parsed;
10021
+ const { message, code, error } = parsed;
8776
10022
  const stableCode = typeof code === "string" ? code : null;
8777
10023
  if (typeof message !== "string") return { ...raw, code: stableCode };
8778
- if (stableCode === null)
8779
- return { detail: message.slice(0, limit), code: null };
10024
+ const fields = invalidFields(error);
10025
+ const said = fields ? `${message}: ${fields}` : message;
10026
+ if (stableCode === null) return { detail: said.slice(0, DETAIL_LIMIT), code: null };
8780
10027
  return {
8781
- detail: `${message} (${stableCode})`.slice(0, limit),
10028
+ detail: `${said} (${stableCode})`.slice(0, DETAIL_LIMIT),
8782
10029
  code: stableCode
8783
10030
  };
8784
10031
  }
8785
- async function apiRequest(options, method, path16, body, init3 = {}) {
8786
- const reply = await new PlatformTransport(resolveEnv(options)).send(method, path16, body, init3);
8787
- if (!reply.ok) throw new ApiError(reply.status, method, path16, reply.text);
10032
+ function invalidFields(error) {
10033
+ const issues = Array.isArray(error) ? error : [];
10034
+ return issues.filter(
10035
+ (issue) => issue !== null && typeof issue === "object" && typeof issue.message === "string"
10036
+ ).map((issue) => {
10037
+ const path17 = Array.isArray(issue.path) ? issue.path.map(String).join(".") : "";
10038
+ return path17 ? `${path17}: ${issue.message}` : issue.message;
10039
+ }).join("; ");
10040
+ }
10041
+ async function apiRequest(options, method, path17, body, init3 = {}) {
10042
+ const reply = await new PlatformTransport(requirePlatformEndpoint(options)).send(method, path17, body, init3);
10043
+ if (!reply.ok) throw new ApiError(reply.status, method, path17, reply.text);
8788
10044
  return JSON.parse(reply.text);
8789
10045
  }
8790
10046
  async function setEnvSecret(slug, key2, value, options = {}) {
@@ -8896,7 +10152,6 @@ function detectProvenance() {
8896
10152
  kind: "ci",
8897
10153
  id: env.GITHUB_ACTOR,
8898
10154
  name: env.GITHUB_ACTOR,
8899
- // GitHub serves every account's avatar at /<login>.png.
8900
10155
  imageUrl: `${server}/${env.GITHUB_ACTOR}.png`
8901
10156
  };
8902
10157
  }
@@ -8961,17 +10216,20 @@ async function resolveWorld(slugRef, slug, ref, pin, options) {
8961
10216
  }
8962
10217
  return world;
8963
10218
  }
8964
- var ApiError, WorldTask, WorldSet;
10219
+ var ApiError, DETAIL_LIMIT, EDGE_ANSWERS, EDGE_FAILURE, EDGE_PAGE, WorldTask, WorldSet;
8965
10220
  var init_worlds = __esm({
8966
10221
  "src/worlds/index.ts"() {
8967
10222
  "use strict";
10223
+ init_platformEndpoint();
8968
10224
  init_transport();
8969
10225
  init_transport();
8970
10226
  init_session2();
10227
+ init_grade();
8971
10228
  init_sessionList();
8972
10229
  init_sessionContract();
8973
10230
  init_taskRef();
8974
10231
  init_tasks();
10232
+ init_taskGrades();
8975
10233
  init_taskSessions();
8976
10234
  init_taskRun();
8977
10235
  init_setRun();
@@ -8980,6 +10238,7 @@ var init_worlds = __esm({
8980
10238
  init_browser();
8981
10239
  init_surfaceDescriptor();
8982
10240
  init_requestLog();
10241
+ init_requestLedger();
8983
10242
  init_browserReconnect();
8984
10243
  init_nativeComputer();
8985
10244
  init_hub();
@@ -8993,10 +10252,11 @@ var init_worlds = __esm({
8993
10252
  init_sandbox();
8994
10253
  init_editSessions();
8995
10254
  init_dryRun();
10255
+ init_worldNotice();
8996
10256
  ApiError = class extends Error {
8997
- constructor(status, method, path16, text2) {
8998
- const parsed = parseErrorBody(text2);
8999
- super(`${method} ${path16} -> ${status}: ${parsed.detail}`);
10257
+ constructor(status, method, path17, text2) {
10258
+ const parsed = parseErrorBody(text2, status);
10259
+ super(`${method} ${path17} -> ${status}: ${parsed.detail}`);
9000
10260
  this.status = status;
9001
10261
  this.text = text2;
9002
10262
  this.name = "ApiError";
@@ -9006,6 +10266,14 @@ var init_worlds = __esm({
9006
10266
  text;
9007
10267
  code;
9008
10268
  };
10269
+ DETAIL_LIMIT = 600;
10270
+ EDGE_ANSWERS = {
10271
+ 502: "Bad Gateway from the load balancer in front of the platform, not the platform's answer: the web server dropped the connection or restarted mid-request. Retry; if it repeats, the platform is restarting or overloaded.",
10272
+ 503: "Service Unavailable from the load balancer in front of the platform, not the platform's answer: no web server was ready to take the request (a deploy or a restart). Retry in a minute.",
10273
+ 504: "Gateway Time-out from the load balancer in front of the platform, not the platform's answer: the request sent nothing back within the load balancer's idle timeout (60 s unless the deployment raises it: Helm ingress.idleTimeoutSeconds) and was cut there, though the platform may still be running it. Check what it changed before you retry."
10274
+ };
10275
+ EDGE_FAILURE = "The platform failed without its JSON error body: a proxy in front of it answered, or the server stopped before its error handler ran. Retry; if it repeats, report the request and the time.";
10276
+ EDGE_PAGE = "An HTML page answered instead of the platform's JSON: a proxy in front of the platform, or the configured host is not the platform.";
9009
10277
  WorldTask = class {
9010
10278
  constructor(world, name, variant) {
9011
10279
  this.world = world;
@@ -9041,12 +10309,7 @@ var init_worlds = __esm({
9041
10309
  }
9042
10310
  return hit;
9043
10311
  }
9044
- /**
9045
- * Open a LIVE session against one of this world's tasks — a bundled task's
9046
- * name or an inline `WorldTaskSpec`: the platform boots (or reuses) a warm
9047
- * container, and your agent calls its tools through the platform. See
9048
- * worlds/session.ts.
9049
- */
10312
+ /** Open a live session on a bundled task's name or an inline `WorldTaskSpec`; the platform boots or reuses a warm container. */
9050
10313
  async open(task, opts = {}) {
9051
10314
  const { openSession: openSession2 } = await Promise.resolve().then(() => (init_session2(), session_exports2));
9052
10315
  return openSession2(this.slug, {
@@ -9058,11 +10321,7 @@ var init_worlds = __esm({
9058
10321
  options: this.options
9059
10322
  });
9060
10323
  }
9061
- /**
9062
- * Start a HOSTED run of a run config against this world — the platform
9063
- * executes the (Python) world in parallel containers per the config's
9064
- * `parallelism` and files one graded run per model. Returns those runs.
9065
- */
10324
+ /** Start a hosted run of a run config on this version (or `opts.versionId`): one graded run per model, provenance detected unless given. */
9066
10325
  async dispatch(runConfigId, opts = {}) {
9067
10326
  const provenance = opts.provenance ?? detectProvenance();
9068
10327
  return apiRequest(
@@ -9651,8 +10910,8 @@ var GatewayContext = class _GatewayContext {
9651
10910
  }
9652
10911
  return resolved;
9653
10912
  }
9654
- async requestJson(method, path16, payload) {
9655
- const response = await fetch(`${this.host}${path16}`, {
10913
+ async requestJson(method, path17, payload) {
10914
+ const response = await fetch(`${this.host}${path17}`, {
9656
10915
  method,
9657
10916
  headers: {
9658
10917
  Authorization: this.authHeader(),
@@ -9663,7 +10922,7 @@ var GatewayContext = class _GatewayContext {
9663
10922
  const text2 = await response.text();
9664
10923
  const body = text2 ? safeJson(text2) : {};
9665
10924
  if (!response.ok) {
9666
- const message = typeof body.message === "string" ? body.message : `Gateway API ${response.status} on ${path16}`;
10925
+ const message = typeof body.message === "string" ? body.message : `Gateway API ${response.status} on ${path17}`;
9667
10926
  if (response.status === 409) {
9668
10927
  throw new GatewayContextConflictError(
9669
10928
  message,
@@ -9672,7 +10931,7 @@ var GatewayContext = class _GatewayContext {
9672
10931
  }
9673
10932
  throw new GatewayContextError(message);
9674
10933
  }
9675
- this.log("%s %s -> %s", method, path16, response.status);
10934
+ this.log("%s %s -> %s", method, path17, response.status);
9676
10935
  return body;
9677
10936
  }
9678
10937
  authHeader() {
@@ -9779,11 +11038,11 @@ function primaryPathForKind(kind, snapshot) {
9779
11038
  const preferred = kind === "agent" ? "AGENTS.md" : kind === "prompt" ? "PROMPT.md" : kind === "skill" ? "SKILL.md" : "MEMORY.md";
9780
11039
  if (readFile(snapshot, preferred)) return preferred;
9781
11040
  return Object.entries(snapshot.files).find(
9782
- ([path16, entry]) => entry.type === "file" && path16.endsWith(".md")
11041
+ ([path17, entry]) => entry.type === "file" && path17.endsWith(".md")
9783
11042
  )?.[0] ?? null;
9784
11043
  }
9785
- function parseJsonFile(snapshot, path16) {
9786
- const content = readFile(snapshot, path16);
11044
+ function parseJsonFile(snapshot, path17) {
11045
+ const content = readFile(snapshot, path17);
9787
11046
  if (!content) return {};
9788
11047
  try {
9789
11048
  const parsed = JSON.parse(content);
@@ -9792,8 +11051,8 @@ function parseJsonFile(snapshot, path16) {
9792
11051
  return {};
9793
11052
  }
9794
11053
  }
9795
- function readFile(snapshot, path16) {
9796
- const entry = snapshot.files[path16];
11054
+ function readFile(snapshot, path17) {
11055
+ const entry = snapshot.files[path17];
9797
11056
  return entry?.type === "file" ? entry.content : null;
9798
11057
  }
9799
11058
  function provenanceFor(snapshot, label) {
@@ -9895,16 +11154,16 @@ var GatewayMemory = class _GatewayMemory {
9895
11154
  `/api/public/context/memory/${encodeIdentifier2(identifier)}${suffix}`
9896
11155
  );
9897
11156
  }
9898
- async read(target, path16, options = {}) {
11157
+ async read(target, path17, options = {}) {
9899
11158
  const snapshot = typeof target === "string" ? await this.pull(target, options) : target;
9900
- const file = snapshot.files[path16];
11159
+ const file = snapshot.files[path17];
9901
11160
  return file?.type === "file" ? file.content : null;
9902
11161
  }
9903
- async write(target, path16, content, options = {}) {
11162
+ async write(target, path17, content, options = {}) {
9904
11163
  const snapshot = typeof target === "string" ? await this.pull(target) : target;
9905
11164
  return this.push(snapshot.repo.repoHandle, {
9906
11165
  files: {
9907
- [path16]: {
11166
+ [path17]: {
9908
11167
  content,
9909
11168
  ...options.mimeType ? { mimeType: options.mimeType } : {}
9910
11169
  }
@@ -9914,10 +11173,10 @@ var GatewayMemory = class _GatewayMemory {
9914
11173
  ...runtimeContextPayload2(options)
9915
11174
  });
9916
11175
  }
9917
- async delete(target, path16, options = {}) {
11176
+ async delete(target, path17, options = {}) {
9918
11177
  const snapshot = typeof target === "string" ? await this.pull(target) : target;
9919
11178
  return this.push(snapshot.repo.repoHandle, {
9920
- files: { [path16]: null },
11179
+ files: { [path17]: null },
9921
11180
  parentCommit: options.parentCommit ?? snapshot.commit.commitHash,
9922
11181
  message: options.message,
9923
11182
  ...runtimeContextPayload2(options)
@@ -9930,8 +11189,8 @@ var GatewayMemory = class _GatewayMemory {
9930
11189
  payload
9931
11190
  );
9932
11191
  }
9933
- async requestJson(method, path16, payload) {
9934
- const response = await fetch(`${this.host}${path16}`, {
11192
+ async requestJson(method, path17, payload) {
11193
+ const response = await fetch(`${this.host}${path17}`, {
9935
11194
  method,
9936
11195
  headers: {
9937
11196
  Authorization: this.authHeader(),
@@ -9942,7 +11201,7 @@ var GatewayMemory = class _GatewayMemory {
9942
11201
  const text2 = await response.text();
9943
11202
  const body = text2 ? safeJson2(text2) : {};
9944
11203
  if (!response.ok) {
9945
- const message = typeof body.message === "string" ? body.message : `Gateway API ${response.status} on ${path16}`;
11204
+ const message = typeof body.message === "string" ? body.message : `Gateway API ${response.status} on ${path17}`;
9946
11205
  if (response.status === 409) {
9947
11206
  throw new GatewayMemoryConflictError(
9948
11207
  message,
@@ -9951,7 +11210,7 @@ var GatewayMemory = class _GatewayMemory {
9951
11210
  }
9952
11211
  throw new GatewayMemoryError(message);
9953
11212
  }
9954
- this.log("%s %s -> %s", method, path16, response.status);
11213
+ this.log("%s %s -> %s", method, path17, response.status);
9955
11214
  return body;
9956
11215
  }
9957
11216
  authHeader() {
@@ -10113,10 +11372,10 @@ var PersonasClient = class _PersonasClient {
10113
11372
  done: Boolean(payload.done)
10114
11373
  };
10115
11374
  }
10116
- async requestJson(method, path16, payload) {
11375
+ async requestJson(method, path17, payload) {
10117
11376
  let response;
10118
11377
  try {
10119
- response = await fetch(`${this.host}${path16}`, {
11378
+ response = await fetch(`${this.host}${path17}`, {
10120
11379
  method,
10121
11380
  headers: {
10122
11381
  Authorization: this.authHeader(),
@@ -10127,7 +11386,7 @@ var PersonasClient = class _PersonasClient {
10127
11386
  });
10128
11387
  } catch (error) {
10129
11388
  const reason = error instanceof Error ? error.message : String(error);
10130
- throw new PersonaError(`${method} ${path16} failed: ${reason}`, {
11389
+ throw new PersonaError(`${method} ${path17} failed: ${reason}`, {
10131
11390
  cause: error
10132
11391
  });
10133
11392
  }
@@ -10135,10 +11394,10 @@ var PersonasClient = class _PersonasClient {
10135
11394
  if (!response.ok) {
10136
11395
  const detail = text2.slice(0, 500);
10137
11396
  throw new PersonaError(
10138
- `${method} ${path16} failed (${response.status}): ${detail}`
11397
+ `${method} ${path17} failed (${response.status}): ${detail}`
10139
11398
  );
10140
11399
  }
10141
- this.log("%s %s -> %s", method, path16, response.status);
11400
+ this.log("%s %s -> %s", method, path17, response.status);
10142
11401
  return safeJson3(text2);
10143
11402
  }
10144
11403
  authHeader() {
@@ -10363,10 +11622,10 @@ var SessionRecording = class _SessionRecording {
10363
11622
  };
10364
11623
  }
10365
11624
  /** Dump the full session as a JSON fixture (for regression tests). */
10366
- toFixture(path16) {
10367
- mkdirSync(dirname(path16), { recursive: true });
10368
- writeFileSync(path16, JSON.stringify(this.toJSON(), null, 2), "utf-8");
10369
- return path16;
11625
+ toFixture(path17) {
11626
+ mkdirSync(dirname(path17), { recursive: true });
11627
+ writeFileSync(path17, JSON.stringify(this.toJSON(), null, 2), "utf-8");
11628
+ return path17;
10370
11629
  }
10371
11630
  static fromApi(raw) {
10372
11631
  return new _SessionRecording({
@@ -11397,8 +12656,8 @@ var GatewaySecurity = class _GatewaySecurity {
11397
12656
  );
11398
12657
  }
11399
12658
  }
11400
- async postJson(path16, payload) {
11401
- const response = await fetch(`${this.host}${path16}`, {
12659
+ async postJson(path17, payload) {
12660
+ const response = await fetch(`${this.host}${path17}`, {
11402
12661
  method: "POST",
11403
12662
  headers: {
11404
12663
  Authorization: this.authHeader(),
@@ -11409,7 +12668,7 @@ var GatewaySecurity = class _GatewaySecurity {
11409
12668
  if (!response.ok) {
11410
12669
  const body = await response.text();
11411
12670
  throw new GatewaySecurityError(
11412
- `Gateway API ${response.status} on ${path16}: ${body || response.statusText}`
12671
+ `Gateway API ${response.status} on ${path17}: ${body || response.statusText}`
11413
12672
  );
11414
12673
  }
11415
12674
  return await response.json();
@@ -11500,9 +12759,9 @@ __export(files_exports, {
11500
12759
  uploadFile: () => uploadFile
11501
12760
  });
11502
12761
  init_worlds();
11503
- import { createHash as createHash10 } from "crypto";
12762
+ import { createHash as createHash11 } from "crypto";
11504
12763
  import * as fs13 from "fs";
11505
- import * as path12 from "path";
12764
+ import * as path13 from "path";
11506
12765
  import { Readable, Transform } from "stream";
11507
12766
  import { pipeline } from "stream/promises";
11508
12767
  var DRIVE_PREFIX = "drive:";
@@ -11553,7 +12812,7 @@ async function readFile2(options = {}, filePath, limits = {}) {
11553
12812
  async function downloadFile(options = {}, filePath, outPath, onProgress) {
11554
12813
  const file = await getFile(options, filePath);
11555
12814
  const res = await openDownload(file.url);
11556
- fs13.mkdirSync(path12.dirname(path12.resolve(outPath)), { recursive: true });
12815
+ fs13.mkdirSync(path13.dirname(path13.resolve(outPath)), { recursive: true });
11557
12816
  const source = Readable.fromWeb(res.body);
11558
12817
  await pipeline(source, counting((n) => onProgress?.(n, file.sizeBytes)), fs13.createWriteStream(outPath));
11559
12818
  return { ...file, out: outPath };
@@ -11565,7 +12824,7 @@ async function confirmUpload(options = {}, fileId, ok = true) {
11565
12824
  return apiRequest(options, "POST", `${BASE}/confirm`, { fileId, ok });
11566
12825
  }
11567
12826
  async function sha256Base64(localPath) {
11568
- const hash = createHash10("sha256");
12827
+ const hash = createHash11("sha256");
11569
12828
  for await (const chunk of fs13.createReadStream(localPath)) hash.update(chunk);
11570
12829
  return hash.digest("base64");
11571
12830
  }
@@ -11602,7 +12861,7 @@ var CONTENT_TYPES = {
11602
12861
  ".mp4": "video/mp4"
11603
12862
  };
11604
12863
  function contentTypeFor(name) {
11605
- return CONTENT_TYPES[path12.extname(name).toLowerCase()] ?? "application/octet-stream";
12864
+ return CONTENT_TYPES[path13.extname(name).toLowerCase()] ?? "application/octet-stream";
11606
12865
  }
11607
12866
  function counting(report) {
11608
12867
  let seen = 0;
@@ -11650,7 +12909,7 @@ async function uploadBytes(options = {}, bytes, targetPath, upload = {}) {
11650
12909
  if (!bytes.length) throw new Error("nothing to upload: the content is empty");
11651
12910
  const target = drivePath(targetPath);
11652
12911
  const contentType = upload.contentType ?? contentTypeFor(target);
11653
- const sha2562 = createHash10("sha256").update(bytes).digest("base64");
12912
+ const sha2562 = createHash11("sha256").update(bytes).digest("base64");
11654
12913
  const granted = await requestUpload(options, { path: target, contentLength: bytes.length, contentType, sha256: sha2562, ...upload.overwrite ? { overwrite: true } : {} });
11655
12914
  try {
11656
12915
  await putPresigned(granted.uploadUrl, new Uint8Array(bytes), { contentType, contentLength: bytes.length, sha256: sha2562 });
@@ -11903,10 +13162,10 @@ function swapValue(text2, needle, replacement) {
11903
13162
  }
11904
13163
 
11905
13164
  // src/hooks/standInDigits.ts
11906
- import { createHash as createHash11 } from "crypto";
13165
+ import { createHash as createHash12 } from "crypto";
11907
13166
  function standInDigits(realDigits, identityName) {
11908
13167
  if (!realDigits) return "";
11909
- const digest = createHash11("sha256").update(`${identityName}:${realDigits}`).digest("hex");
13168
+ const digest = createHash12("sha256").update(`${identityName}:${realDigits}`).digest("hex");
11910
13169
  let digits = "";
11911
13170
  for (let i = 0; i < realDigits.length; i++)
11912
13171
  digits += String(parseInt(digest[i % digest.length], 16) % 10);
@@ -11940,7 +13199,7 @@ var DeclaredStandIn = class _DeclaredStandIn {
11940
13199
  };
11941
13200
 
11942
13201
  // src/hooks/alias.ts
11943
- import { createHash as createHash12, createHmac, randomBytes as randomBytes2 } from "crypto";
13202
+ import { createHash as createHash13, createHmac, randomBytes as randomBytes2 } from "crypto";
11944
13203
  var GIVEN = [
11945
13204
  "John",
11946
13205
  "Mary",
@@ -12761,9 +14020,9 @@ var AliasMap = class _AliasMap {
12761
14020
  });
12762
14021
  if (alias.role === "private") {
12763
14022
  for (const slug of this.slugs) {
12764
- const standIn = "sha256:" + createHash12("sha256").update(`${slug}:${canonical(alias.kind, alias.display)}`, "utf8").digest("hex");
14023
+ const standIn = "sha256:" + createHash13("sha256").update(`${slug}:${canonical(alias.kind, alias.display)}`, "utf8").digest("hex");
12765
14024
  alias.variants.push([
12766
- "sha256:" + createHash12("sha256").update(`${slug}:${alias.canonical}`, "utf8").digest("hex"),
14025
+ "sha256:" + createHash13("sha256").update(`${slug}:${alias.canonical}`, "utf8").digest("hex"),
12767
14026
  standIn
12768
14027
  ]);
12769
14028
  this.aliasDigests.add(standIn.toLowerCase());
@@ -13424,9 +14683,9 @@ function alternatives(raw) {
13424
14683
  if (!parts2.length || parts2.includes("*")) return [];
13425
14684
  return parts2;
13426
14685
  }
13427
- function hasPath(node, path16) {
14686
+ function hasPath(node, path17) {
13428
14687
  let current = node;
13429
- for (const part of path16.split(".")) {
14688
+ for (const part of path17.split(".")) {
13430
14689
  if (current && typeof current === "object" && !Array.isArray(current) && part in current) {
13431
14690
  current = current[part];
13432
14691
  continue;
@@ -13467,7 +14726,7 @@ function matches(m, event) {
13467
14726
  if (m.args.length) {
13468
14727
  const haystacks = event.event === "pre_request" || event.event === "post_response" ? [event.request?.query, event.request?.body] : [event.toolInput];
13469
14728
  const present = haystacks.filter((h) => h !== void 0 && h !== null);
13470
- if (!m.args.every((path16) => present.some((h) => hasPath(h, path16))))
14729
+ if (!m.args.every((path17) => present.some((h) => hasPath(h, path17))))
13471
14730
  return false;
13472
14731
  }
13473
14732
  return true;
@@ -14303,7 +15562,7 @@ function parseHandler(event, raw, position) {
14303
15562
  // src/hooks/handlers.ts
14304
15563
  import { spawn as spawn3 } from "child_process";
14305
15564
  import * as fs15 from "fs";
14306
- import * as path13 from "path";
15565
+ import * as path14 from "path";
14307
15566
  import { pathToFileURL } from "url";
14308
15567
  function parseStdout(text2, handler) {
14309
15568
  const stripped = text2.trim();
@@ -14504,7 +15763,7 @@ var RecordHandler = class {
14504
15763
  record.source = this.opts.source ?? null;
14505
15764
  if (Array.isArray(this.sink)) this.sink.push(record);
14506
15765
  else if (typeof this.sink === "string") {
14507
- fs15.mkdirSync(path13.dirname(this.sink), { recursive: true });
15766
+ fs15.mkdirSync(path14.dirname(this.sink), { recursive: true });
14508
15767
  fs15.appendFileSync(this.sink, JSON.stringify(record) + "\n");
14509
15768
  } else await this.sink(record);
14510
15769
  return allow();
@@ -14715,7 +15974,7 @@ async function importCallable(target, cwd) {
14715
15974
  const hash = target.lastIndexOf("#");
14716
15975
  const modulePath = target.slice(0, hash);
14717
15976
  const exportName = target.slice(hash + 1) || "default";
14718
- const resolved = modulePath.startsWith(".") || path13.isAbsolute(modulePath) ? pathToFileURL(path13.resolve(cwd, modulePath)).href : modulePath;
15977
+ const resolved = modulePath.startsWith(".") || path14.isAbsolute(modulePath) ? pathToFileURL(path14.resolve(cwd, modulePath)).href : modulePath;
14719
15978
  let module;
14720
15979
  try {
14721
15980
  module = await import(resolved);
@@ -14779,7 +16038,121 @@ async function buildHandler(spec, aliases, opts) {
14779
16038
 
14780
16039
  // src/hooks/live.ts
14781
16040
  import * as fs16 from "fs";
14782
- import * as path14 from "path";
16041
+ import * as path15 from "path";
16042
+
16043
+ // src/hooks/vendorAuth.ts
16044
+ var bearer = (auth, value) => ({
16045
+ headers: { authorization: `${prefixesOf(auth)[0]} ${value}` },
16046
+ query: []
16047
+ });
16048
+ var CARRIERS = /* @__PURE__ */ new Map([
16049
+ [
16050
+ "header",
16051
+ (auth, value) => ({
16052
+ headers: {
16053
+ [String(auth.name ?? "").trim().toLowerCase()]: value
16054
+ },
16055
+ query: []
16056
+ })
16057
+ ],
16058
+ ["bearer", bearer],
16059
+ [
16060
+ "basic",
16061
+ (auth, value) => ({
16062
+ headers: {
16063
+ authorization: `Basic ${Buffer.from(basicPair(auth, value)).toString("base64")}`
16064
+ },
16065
+ query: []
16066
+ })
16067
+ ],
16068
+ [
16069
+ "query",
16070
+ (auth, value) => ({
16071
+ headers: {},
16072
+ query: [[String(auth.name ?? "").trim(), value]]
16073
+ })
16074
+ ],
16075
+ ["oauth2", bearer],
16076
+ ["none", () => ({ headers: {}, query: [] })]
16077
+ ]);
16078
+ var AUTH_WORD = /^[A-Za-z0-9!#$%&'*+.^_`|~-]{1,64}$/;
16079
+ var OWNERS = [
16080
+ ["client_id_env", ["oauth2"]],
16081
+ ["credential", ["basic"]],
16082
+ ["prefixes", ["bearer", "oauth2"]],
16083
+ ["scope", ["oauth2"]],
16084
+ ["token_url", ["oauth2"]],
16085
+ ["ttl_seconds", ["oauth2"]]
16086
+ ];
16087
+ var AUTH_MODES = ["vendor", "open"];
16088
+ var positiveSeconds = (value) => typeof value === "number" && Number.isInteger(value) && value >= 1;
16089
+ var NAMED = /* @__PURE__ */ new Set(["header", "query"]);
16090
+ function prefixesOf(auth) {
16091
+ const words2 = auth.prefixes ?? ["Bearer"];
16092
+ const valid = Array.isArray(words2) && words2.length > 0 && words2.every((word) => typeof word === "string" && AUTH_WORD.test(word)) && new Set(words2.map((word) => word.toLowerCase())).size === words2.length;
16093
+ if (!valid)
16094
+ throw new Error(
16095
+ "auth.prefixes lists the distinct words the vendor takes before the key in Authorization"
16096
+ );
16097
+ return words2;
16098
+ }
16099
+ function basicHalf(auth) {
16100
+ const half = auth.credential ?? "user";
16101
+ if (half !== "user" && half !== "password")
16102
+ throw new Error(
16103
+ "auth.credential is the half of the Basic pair the key is: user or password"
16104
+ );
16105
+ return half;
16106
+ }
16107
+ function basicPair(auth, value) {
16108
+ if (value.includes(":")) return value;
16109
+ return basicHalf(auth) === "password" ? `:${value}` : `${value}:`;
16110
+ }
16111
+ var GRAMMAR = /* @__PURE__ */ new Map([
16112
+ ["bearer", prefixesOf],
16113
+ ["oauth2", prefixesOf],
16114
+ ["basic", basicHalf]
16115
+ ]);
16116
+ function authScheme(value) {
16117
+ if (value === void 0) throw new Error("Missing scheme");
16118
+ if (value === "open")
16119
+ throw new Error(
16120
+ 'auth.scheme is how the vendor takes its key; a world whose sessions ask for none is auth.mode = "open"'
16121
+ );
16122
+ if (typeof value !== "string" || !CARRIERS.has(value))
16123
+ throw new Error(
16124
+ `auth.scheme must be one of ${[...CARRIERS.keys()].join(", ")}`
16125
+ );
16126
+ return value;
16127
+ }
16128
+ function vendorAuth(auth) {
16129
+ const scheme = authScheme(auth.scheme);
16130
+ const stray = OWNERS.find(
16131
+ ([key2, owners]) => auth[key2] !== void 0 && !owners.includes(scheme)
16132
+ );
16133
+ if (stray)
16134
+ throw new Error(
16135
+ `${stray[0]} belongs to auth.scheme ${stray[1].join(" or ")}`
16136
+ );
16137
+ if (scheme === "none" && (auth.name ?? auth.secret_env) !== void 0)
16138
+ throw new Error("auth.scheme none takes no name or secret_env");
16139
+ if (NAMED.has(scheme) && auth.name === void 0)
16140
+ throw new Error("Missing name");
16141
+ if (auth.name !== void 0 && (typeof auth.name !== "string" || !auth.name.trim()))
16142
+ throw new Error("name must be a non-empty string");
16143
+ GRAMMAR.get(scheme)?.(auth);
16144
+ if (auth.mode !== void 0 && !AUTH_MODES.includes(auth.mode))
16145
+ throw new Error(`auth.mode is one of ${AUTH_MODES.join(", ")}`);
16146
+ if (auth.ttl_seconds !== void 0 && !positiveSeconds(auth.ttl_seconds))
16147
+ throw new Error("ttl_seconds is a positive whole number of seconds");
16148
+ return { ...auth, scheme };
16149
+ }
16150
+ function carryCredential(auth, value) {
16151
+ const checked = vendorAuth(auth);
16152
+ return CARRIERS.get(checked.scheme)(checked, value);
16153
+ }
16154
+
16155
+ // src/hooks/live.ts
14783
16156
  var USER_AGENT = "gateway-hooks/1 (+https://withgateway.ai)";
14784
16157
  var TAGS = /<(script|style)[^>]*>.*?<\/\1>/gis;
14785
16158
  var STRIP = /<[^>]+>/g;
@@ -14799,13 +16172,13 @@ var Pacer = class {
14799
16172
  /** Waits until the interval since the tool's last call has passed; resolves to the
14800
16173
  * seconds waited. `sleep`/`clock` are injectable for tests. */
14801
16174
  async wait(name, intervalMs, opts = {}) {
14802
- const sleep3 = opts.sleep ?? ((seconds) => new Promise((resolve11) => setTimeout(resolve11, seconds * 1e3)));
16175
+ const sleep5 = opts.sleep ?? ((seconds) => new Promise((resolve11) => setTimeout(resolve11, seconds * 1e3)));
14803
16176
  const clock = opts.clock ?? (() => Date.now() / 1e3);
14804
16177
  const now = clock();
14805
16178
  const due = (this.last.get(name) ?? -Infinity) + intervalMs / 1e3;
14806
16179
  const waited = Math.max(0, due - now);
14807
16180
  this.last.set(name, Math.max(now, due));
14808
- if (waited) await sleep3(waited);
16181
+ if (waited) await sleep5(waited);
14809
16182
  return Math.round(waited * 1e3) / 1e3;
14810
16183
  }
14811
16184
  };
@@ -15100,7 +16473,9 @@ var HttpTool = class _HttpTool {
15100
16473
  const okStatus = o.ok_status ?? [
15101
16474
  [200, 200]
15102
16475
  ];
15103
- if (!okStatus.some(([low, high]) => response.status >= low && response.status <= high)) {
16476
+ if (!okStatus.some(
16477
+ ([low, high]) => response.status >= low && response.status <= high
16478
+ )) {
15104
16479
  const expected = okStatus.map(([low, high]) => low === high ? String(low) : `${low}-${high}`).join(", ");
15105
16480
  throw new LiveToolError(
15106
16481
  `${this.spec.name}: ${url} answered HTTP ${response.status} (ok_status ${expected}): ${JSON.stringify(body.slice(0, 200))}`,
@@ -15147,11 +16522,12 @@ var CallableTool = class _CallableTool {
15147
16522
  }
15148
16523
  };
15149
16524
  function readConnection(root) {
15150
- const file = path14.join(root, "connector.toml");
16525
+ const file = path15.join(root, "connector.toml");
15151
16526
  if (!fs16.existsSync(file)) throw new Error(`no connector.toml at ${root}`);
15152
16527
  const raw = parseToml(fs16.readFileSync(file, "utf8"));
15153
16528
  const connector = raw.connector ?? {};
15154
- const auth = raw.auth ?? {};
16529
+ const auth = raw.auth ?? { scheme: "none" };
16530
+ const carrier = vendorAuth(auth);
15155
16531
  const operations = {};
15156
16532
  for (const op of raw.operations ?? []) {
15157
16533
  operations[op.name] = {
@@ -15163,10 +16539,10 @@ function readConnection(root) {
15163
16539
  };
15164
16540
  }
15165
16541
  return {
15166
- slug: connector.slug ?? path14.basename(root),
16542
+ slug: connector.slug ?? path15.basename(root),
15167
16543
  baseUrl: (connector.base_url ?? "").replace(/\/+$/, ""),
15168
- scheme: auth.scheme ?? "none",
15169
- ...typeof auth.name === "string" ? { authName: auth.name } : {},
16544
+ scheme: carrier.scheme,
16545
+ carrier,
15170
16546
  ...typeof auth.secret_env === "string" ? { secretEnv: auth.secret_env } : {},
15171
16547
  ...typeof auth.client_id_env === "string" ? { clientIdEnv: auth.client_id_env } : {},
15172
16548
  ...typeof auth.token_url === "string" ? { tokenUrl: auth.token_url } : {},
@@ -15180,8 +16556,8 @@ var ConnectorTool = class {
15180
16556
  this.spec = spec;
15181
16557
  this.live = live;
15182
16558
  let location = spec.options.connector;
15183
- if (!path14.isAbsolute(location)) location = path14.resolve(baseDir, location);
15184
- const root = fs16.existsSync(location) && fs16.statSync(location).isFile() ? path14.dirname(location) : location;
16559
+ if (!path15.isAbsolute(location)) location = path15.resolve(baseDir, location);
16560
+ const root = fs16.existsSync(location) && fs16.statSync(location).isFile() ? path15.dirname(location) : location;
15185
16561
  try {
15186
16562
  this.connection = readConnection(root);
15187
16563
  } catch (error) {
@@ -15278,13 +16654,9 @@ var ConnectorTool = class {
15278
16654
  };
15279
16655
  for (const [header, variable] of Object.entries(c.extraHeaders))
15280
16656
  headers[header] = this.env(variable, `the ${header} header`);
15281
- const secret = await this.credential();
15282
- if (c.scheme === "header") headers[c.authName ?? ""] = secret ?? "";
15283
- else if (c.scheme === "bearer" || c.scheme === "oauth2")
15284
- headers.authorization = `Bearer ${secret}`;
15285
- else if (c.scheme === "basic")
15286
- headers.authorization = "Basic " + Buffer.from(secret ?? "").toString("base64");
15287
- else if (c.scheme === "query") query.append(c.authName ?? "", secret ?? "");
16657
+ const carried2 = carryCredential(c.carrier, await this.credential() ?? "");
16658
+ Object.assign(headers, carried2.headers);
16659
+ for (const [key2, value] of carried2.query) query.append(key2, value);
15288
16660
  const url = c.baseUrl + pathText + (query.toString() ? `?${query.toString()}` : "");
15289
16661
  const response = await fetch(url, {
15290
16662
  method: this.operation.method,
@@ -15338,7 +16710,7 @@ var Recorder = class {
15338
16710
  }
15339
16711
  file;
15340
16712
  write(line) {
15341
- fs16.mkdirSync(path14.dirname(this.file), { recursive: true });
16713
+ fs16.mkdirSync(path15.dirname(this.file), { recursive: true });
15342
16714
  fs16.appendFileSync(this.file, canonical2(line) + "\n");
15343
16715
  }
15344
16716
  };
@@ -15434,7 +16806,7 @@ var LiveTools = class _LiveTools {
15434
16806
  ...config.live.record ? { record: interpolatePath(config.live.record, run.runId, directory) } : {},
15435
16807
  ...config.live.replay ? { replay: interpolatePath(config.live.replay, run.runId, directory) } : {}
15436
16808
  };
15437
- return _LiveTools.create(run, live, path14.dirname(path14.resolve(file)));
16809
+ return _LiveTools.create(run, live, path15.dirname(path15.resolve(file)));
15438
16810
  }
15439
16811
  /** The declared tools for a model. `openai`: `{type: "function", function: {name,
15440
16812
  * description, parameters}}`; `anthropic`: `{name, description, input_schema}`. */
@@ -15761,7 +17133,7 @@ var RedactionAudit = class _RedactionAudit {
15761
17133
  // src/hooks/run.ts
15762
17134
  import { randomBytes as randomBytes3 } from "crypto";
15763
17135
  import * as fs17 from "fs";
15764
- import * as path15 from "path";
17136
+ import * as path16 from "path";
15765
17137
  var BLOCKING_EVENTS = [
15766
17138
  "pre_tool_call",
15767
17139
  "pre_request",
@@ -15812,12 +17184,12 @@ var HookRun = class _HookRun {
15812
17184
  declaredOnly: options.declaredOnly ?? config.aliasDeclaredOnly
15813
17185
  });
15814
17186
  this.cwd = options.cwd ?? process.cwd();
15815
- this.runDir = options.runDir ?? path15.join(this.cwd, "runs", this.runId);
17187
+ this.runDir = options.runDir ?? path16.join(this.cwd, "runs", this.runId);
15816
17188
  const chosen = options.legend !== void 0 ? options.legend : config.aliasLegend;
15817
- this.legendPath = chosen ? path15.resolve(this.cwd, interpolatePath(chosen, this.runId, this.runDir)) : null;
17189
+ this.legendPath = chosen ? path16.resolve(this.cwd, interpolatePath(chosen, this.runId, this.runDir)) : null;
15818
17190
  this.sessionId = options.session;
15819
17191
  this.source = options.source;
15820
- this.configDir = config.source ? path15.dirname(path15.resolve(config.source)) : this.cwd;
17192
+ this.configDir = config.source ? path16.dirname(path16.resolve(config.source)) : this.cwd;
15821
17193
  }
15822
17194
  /** Build from a parsed config (an object in the file's shape, or a `HookConfig`);
15823
17195
  * handlers are constructed now, so a callable that does not import fails here. */
@@ -16227,7 +17599,7 @@ var HookRun = class _HookRun {
16227
17599
  throw new Error(
16228
17600
  "no legend path: set [alias] legend, pass legend to the run, or give a path"
16229
17601
  );
16230
- fs17.mkdirSync(path15.dirname(target), { recursive: true });
17602
+ fs17.mkdirSync(path16.dirname(target), { recursive: true });
16231
17603
  fs17.writeFileSync(target, JSON.stringify(this.legend(), null, 2) + "\n");
16232
17604
  return target;
16233
17605
  }
@@ -16324,14 +17696,14 @@ var HookedSession = class {
16324
17696
  * `apiHeaders()`), `pre_request` before it and `post_response` after. Returns
16325
17697
  * `{status, body, headers}`; a 4xx/5xx is returned, not thrown, so the agent sees
16326
17698
  * the vendor's own error shape (rewritten like any result). */
16327
- async request(method, path16, opts = {}) {
17699
+ async request(method, path17, opts = {}) {
16328
17700
  if (!this.inner.api && !this.requestFn)
16329
17701
  throw new Error(
16330
17702
  "this session has no api surface (pass requestFn for a transport of your own)"
16331
17703
  );
16332
17704
  let request = {
16333
17705
  method: method.toUpperCase(),
16334
- path: path16,
17706
+ path: path17,
16335
17707
  query: { ...opts.query ?? {} },
16336
17708
  body: opts.body ?? null
16337
17709
  };
@@ -16803,6 +18175,8 @@ export {
16803
18175
  GatewaySecurityError,
16804
18176
  GatewayToolApprovalRequiredError,
16805
18177
  GatewayToolBlockedError,
18178
+ GradePayload,
18179
+ GradeRefused,
16806
18180
  HostedDryRunClient,
16807
18181
  IDLE_WARNING_MINUTES,
16808
18182
  KEY_NAMES,
@@ -16812,6 +18186,7 @@ export {
16812
18186
  NativeComputer,
16813
18187
  OpenAIComputer,
16814
18188
  OpenAIPreviewComputer,
18189
+ PLATFORM_SESSION_HEADER,
16815
18190
  PLATFORM_TIMEOUT_DEFAULT_MS,
16816
18191
  PLATFORM_TIMEOUT_ENV,
16817
18192
  PendingSafetyChecks,
@@ -16822,14 +18197,26 @@ export {
16822
18197
  PushSlugConflict,
16823
18198
  RECOVER_BUDGET_MS,
16824
18199
  REPLAY_ENVIRONMENT,
18200
+ REQUESTS_NOT_RECORDED,
18201
+ REQUEST_BODY_CAPTURE_BYTES,
18202
+ REQUEST_LOG_PAGE_MAX,
16825
18203
  ReplayCase,
16826
18204
  ReplayCheck,
16827
18205
  ReplayError,
16828
18206
  ReplayReport,
16829
18207
  ReplaySuite,
16830
18208
  ReplayTask,
18209
+ RetryPolicy,
18210
+ SANDBOX_EXEC_REPORT_MARGIN_MS,
18211
+ SANDBOX_EXEC_START_ATTEMPTS,
18212
+ SANDBOX_EXEC_TIMEOUT_MAX_S,
18213
+ SANDBOX_EXEC_WAIT_MS,
18214
+ SANDBOX_FILE_MAX_BYTES,
16831
18215
  SANDBOX_REQUEST_TIMEOUT_MS,
18216
+ SANDBOX_WRITE_CHUNK_BYTES,
18217
+ SANDBOX_WRITE_SKIPPED,
16832
18218
  SECRET_KEY,
18219
+ SESSION_AUTH_MODES,
16833
18220
  SESSION_STATES,
16834
18221
  SPAN_PREFIX,
16835
18222
  STATUS_WAIT_CAP_SECONDS,
@@ -16837,6 +18224,7 @@ export {
16837
18224
  SUCCESS_METRIC_NAME_KEY,
16838
18225
  SUCCESS_SIGNAL_KEY,
16839
18226
  SURFACE_KINDS,
18227
+ Score,
16840
18228
  ScoreError,
16841
18229
  ScoresClient,
16842
18230
  Screen,
@@ -16845,8 +18233,10 @@ export {
16845
18233
  SessionRecording,
16846
18234
  SessionTrace,
16847
18235
  StubMissError,
18236
+ TOOL_CONTRACT_UNREAD,
16848
18237
  TRANSFORMS,
16849
18238
  TaskEditClient,
18239
+ TaskGrades,
16850
18240
  TaskRun,
16851
18241
  TaskSessions,
16852
18242
  ToolStubRegistry,
@@ -16857,17 +18247,26 @@ export {
16857
18247
  UsersClient,
16858
18248
  VERIFIER_REWARD_PREFIX,
16859
18249
  WHITESPACE,
18250
+ WORLD_REQUEST_VIAS,
16860
18251
  WorldBrowser,
16861
18252
  WorldCallTooLarge,
16862
18253
  WorldEditClient,
18254
+ WorldNotice,
18255
+ WorldRequestFilterError,
18256
+ WorldRequestLedger,
16863
18257
  WorldRequestLog,
18258
+ WorldRequestQuery,
18259
+ WorldRequestsNotRecorded,
16864
18260
  WorldSandboxClient,
16865
18261
  WorldSession,
16866
18262
  WorldSessionCallError,
18263
+ WorldSessionOpenFailed,
16867
18264
  WorldSessionTimeout,
16868
18265
  WorldSet,
16869
18266
  WorldSurfaceUnavailable,
16870
18267
  WorldTask,
18268
+ WorldToolsUnread,
18269
+ WriteTreeFilter,
16871
18270
  addExperimentAttributes,
16872
18271
  aggregateTaskGrade,
16873
18272
  apiRequest,
@@ -16875,6 +18274,7 @@ export {
16875
18274
  archiveMode,
16876
18275
  assembleManifest,
16877
18276
  assertBrowserTier,
18277
+ assertSessionAuthMode,
16878
18278
  assertTaskRef,
16879
18279
  assignVariant,
16880
18280
  attachManifest,
@@ -16884,7 +18284,9 @@ export {
16884
18284
  buildFileManifest,
16885
18285
  buildSourceTarball,
16886
18286
  canonicalJson,
18287
+ capabilityLabel,
16887
18288
  captureToolCalls,
18289
+ carriedWarnings,
16888
18290
  checkoutIdentity,
16889
18291
  clearExperimentContext,
16890
18292
  closeConnection,
@@ -16920,7 +18322,9 @@ export {
16920
18322
  idleWarning,
16921
18323
  ingest,
16922
18324
  ingestToolCalls,
18325
+ invalidFields,
16923
18326
  isBrowserGone,
18327
+ isSandboxCommitPending,
16924
18328
  isSandboxImportPending,
16925
18329
  isTaskIdRef,
16926
18330
  isTaskManifest,
@@ -16934,6 +18338,7 @@ export {
16934
18338
  loadSession,
16935
18339
  localTreeState,
16936
18340
  memory,
18341
+ messageOf,
16937
18342
  migrateProjectWorlds,
16938
18343
  migrateWorld,
16939
18344
  modelToolName,
@@ -16976,6 +18381,7 @@ export {
16976
18381
  resolvePushSlug,
16977
18382
  resolveUserId,
16978
18383
  roundForm,
18384
+ rowsRefusal,
16979
18385
  runSessions,
16980
18386
  runSet,
16981
18387
  runSuite,
@@ -16991,12 +18397,16 @@ export {
16991
18397
  setExperimentContext,
16992
18398
  shapeText,
16993
18399
  snapshotTreeHashes,
18400
+ sqlRows,
18401
+ stillStartingHint,
16994
18402
  storedForms,
16995
18403
  success,
16996
18404
  suite,
16997
18405
  surfaceDescriptor,
16998
18406
  surfaceKinds,
18407
+ taskGradeError,
16999
18408
  taskLabel,
18409
+ taskRunFailure,
17000
18410
  toolCallRecordsIn,
17001
18411
  toolCallsFromObservations,
17002
18412
  traces_exports as traces,
@@ -17011,6 +18421,7 @@ export {
17011
18421
  validateWorld,
17012
18422
  waitForRun,
17013
18423
  withoutUiToken,
18424
+ worldRequestsUnrecorded,
17014
18425
  writeLocalMeta
17015
18426
  };
17016
18427
  //# sourceMappingURL=index.mjs.map