@withgateway/sdk 0.4.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/dist/cli.js +1128 -783
  2. package/dist/cli.js.map +1 -1
  3. package/dist/cli.mjs +1130 -785
  4. package/dist/cli.mjs.map +1 -1
  5. package/dist/files/index.js +47 -18
  6. package/dist/files/index.js.map +1 -1
  7. package/dist/files/index.mjs +47 -18
  8. package/dist/files/index.mjs.map +1 -1
  9. package/dist/{index-mJhG3vZU.d.mts → index-Di9nNqOY.d.mts} +26 -3
  10. package/dist/{index-DUHmS74p.d.ts → index-LA-PMRJT.d.ts} +26 -3
  11. package/dist/index.d.mts +3 -3
  12. package/dist/index.d.ts +3 -3
  13. package/dist/index.js +179 -43
  14. package/dist/index.js.map +1 -1
  15. package/dist/index.mjs +176 -43
  16. package/dist/index.mjs.map +1 -1
  17. package/dist/replay/index.d.mts +1 -1
  18. package/dist/replay/index.d.ts +1 -1
  19. package/dist/replay/index.js.map +1 -1
  20. package/dist/replay/index.mjs.map +1 -1
  21. package/dist/traces/index.js +47 -18
  22. package/dist/traces/index.js.map +1 -1
  23. package/dist/traces/index.mjs +47 -18
  24. package/dist/traces/index.mjs.map +1 -1
  25. package/dist/tracing/index.d.mts +1 -1
  26. package/dist/tracing/index.d.ts +1 -1
  27. package/dist/tracing/index.js +1 -1
  28. package/dist/tracing/index.js.map +1 -1
  29. package/dist/tracing/index.mjs +1 -1
  30. package/dist/tracing/index.mjs.map +1 -1
  31. package/dist/worlds/index.d.mts +184 -85
  32. package/dist/worlds/index.d.ts +184 -85
  33. package/dist/worlds/index.js +176 -43
  34. package/dist/worlds/index.js.map +1 -1
  35. package/dist/worlds/index.mjs +176 -43
  36. package/dist/worlds/index.mjs.map +1 -1
  37. package/package.json +1 -1
  38. package/runtime/gatewaysdk/environment/_bundle.py +4 -6
  39. package/runtime/gatewaysdk/environment/_world.py +24 -1
  40. package/runtime/gatewaysdk/environment/runtime.py +45 -2
  41. package/runtime/gatewaysdk/environment/schema/api.py +24 -3
  42. package/runtime/gatewaysdk/environment/schema/bundle_runtime.py +1 -0
  43. package/runtime/gatewaysdk/environment/schema/call_capture.py +13 -1
  44. package/runtime/gatewaysdk/environment/schema/call_log.py +46 -0
  45. package/runtime/gatewaysdk/environment/schema/call_redaction.py +6 -0
  46. package/runtime/gatewaysdk/environment/schema/compiler.py +4 -1
  47. package/runtime/gatewaysdk/environment/schema/conform.py +32 -8
  48. package/runtime/gatewaysdk/environment/schema/connector.py +5 -0
  49. package/runtime/gatewaysdk/environment/schema/connectors/custom/handlers.py +2 -1
  50. package/runtime/gatewaysdk/environment/schema/connectors/github/api/handlers.py +217 -58
  51. package/runtime/gatewaysdk/environment/schema/connectors/github/connector.toml +9 -19
  52. package/runtime/gatewaysdk/environment/schema/connectors/github/scenarios/default/seed/github_webhooks.json +10 -2
  53. package/runtime/gatewaysdk/environment/schema/connectors/github/tests/webhooks.json +47 -0
  54. package/runtime/gatewaysdk/environment/schema/connectors/github/world.json +21 -0
  55. package/runtime/gatewaysdk/environment/schema/connectors/jamf/api/handlers.py +185 -18
  56. package/runtime/gatewaysdk/environment/schema/connectors/jamf/connector.toml +29 -14
  57. package/runtime/gatewaysdk/environment/schema/connectors/jamf/provenance.json +43 -12
  58. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scenarios/default/seed/jamf_webhooks.json +2 -2
  59. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scope.toml +4 -17
  60. package/runtime/gatewaysdk/environment/schema/connectors/jamf/tests/webhooks.json +107 -0
  61. package/runtime/gatewaysdk/environment/schema/connectors/jamf/vendor-openapi.json +1 -1
  62. package/runtime/gatewaysdk/environment/schema/connectors/linear/api/handlers.py +85 -1
  63. package/runtime/gatewaysdk/environment/schema/connectors/linear/connector.toml +19 -31
  64. package/runtime/gatewaysdk/environment/schema/connectors/linear/provenance.json +18 -8
  65. package/runtime/gatewaysdk/environment/schema/connectors/linear/scenarios/default/seed/webhooks.json +19 -3
  66. package/runtime/gatewaysdk/environment/schema/connectors/linear/tests/test_webhooks.py +71 -0
  67. package/runtime/gatewaysdk/environment/schema/database/guard.py +2 -1
  68. package/runtime/gatewaysdk/environment/schema/handler_errors.py +27 -1
  69. package/runtime/gatewaysdk/environment/schema/journal.py +4 -3
  70. package/runtime/gatewaysdk/environment/schema/local.py +1 -0
  71. package/runtime/gatewaysdk/environment/schema/openapi_schemas.py +20 -5
  72. package/runtime/gatewaysdk/environment/schema/platform.py +16 -219
  73. package/runtime/gatewaysdk/environment/schema/runtime.py +7 -0
  74. package/runtime/gatewaysdk/environment/schema/scaffold.py +2 -1
  75. package/runtime/gatewaysdk/environment/schema/skills/connector-schema-authoring/CONNECTORS.md +3 -3
  76. package/runtime/gatewaysdk/environment/schema/skills/connector-schema-authoring/SKILL.md +19 -22
  77. package/runtime/gatewaysdk/environment/schema/skills/world-data-ingestion/SKILL.md +7 -9
  78. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/SKILL.md +3 -3
  79. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/cli-mcp-map.md +14 -11
  80. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/gotchas.md +36 -5
  81. package/runtime/gatewaysdk/environment/schema/snapshot.py +2 -2
  82. package/runtime/gatewaysdk/environment/schema/tools_world.py +19 -0
  83. package/runtime/gatewaysdk/environment/schema/verbs.py +6 -0
  84. package/runtime/gatewaysdk/environment/schema/webhooks.py +687 -0
  85. package/runtime/gatewaysdk/environment/schema/world_host.py +20 -3
  86. package/runtime/gatewaysdk/environment/schema/world_tests.py +74 -0
  87. package/skills/connector-schema-authoring/CONNECTORS.md +3 -3
  88. package/skills/connector-schema-authoring/SKILL.md +19 -22
  89. package/skills/connector-schema-authoring/connector-worlds.md +153 -11
  90. package/skills/connector-schema-authoring/world-schema.md +7 -6
  91. package/skills/world-data-ingestion/SKILL.md +7 -9
  92. package/skills/worlds-getting-started/SKILL.md +3 -3
  93. package/skills/worlds-getting-started/references/cli-mcp-map.md +14 -11
  94. package/skills/worlds-getting-started/references/gotchas.md +36 -5
package/dist/cli.js CHANGED
@@ -380,11 +380,11 @@ var init_transport = __esm({
380
380
  }
381
381
  };
382
382
  UnreachableError = class extends Error {
383
- constructor(host, method, route, failure2) {
384
- super(`${method} ${route}: no answer from ${host}: ${failure2.describe()}. ${failure2.next}`);
383
+ constructor(host, method, route2, failure2) {
384
+ super(`${method} ${route2}: no answer from ${host}: ${failure2.describe()}. ${failure2.next}`);
385
385
  this.host = host;
386
386
  this.method = method;
387
- this.route = route;
387
+ this.route = route2;
388
388
  this.failure = failure2;
389
389
  this.name = "UnreachableError";
390
390
  }
@@ -454,16 +454,16 @@ var init_transport = __esm({
454
454
  budget(ownMs) {
455
455
  return Math.max(ownMs ?? 0, this.timeoutMs);
456
456
  }
457
- async send(method, route, body, opts = {}) {
457
+ async send(method, route2, body, opts = {}) {
458
458
  const timeoutMs3 = this.budget(opts.timeoutMs);
459
- return (opts.retry ?? RetryPolicy.NONE).run(() => this.once(method, route, body, timeoutMs3));
459
+ return (opts.retry ?? RetryPolicy.NONE).run(() => this.once(method, route2, body, timeoutMs3));
460
460
  }
461
- async once(method, route, body, timeoutMs3) {
461
+ async once(method, route2, body, timeoutMs3) {
462
462
  const payload = body === void 0 ? {} : { body: JSON.stringify(body) };
463
463
  const controller = new AbortController();
464
464
  const timer = setTimeout(() => controller.abort(), timeoutMs3);
465
465
  try {
466
- const res = await fetch(`${this.endpoint.host}${route}`, {
466
+ const res = await fetch(`${this.endpoint.host}${route2}`, {
467
467
  method,
468
468
  headers: {
469
469
  "content-type": "application/json",
@@ -476,7 +476,7 @@ var init_transport = __esm({
476
476
  return { status: res.status, ok: res.ok, text: await res.text() };
477
477
  } catch (error) {
478
478
  const cause = controller.signal.aborted ? TransportCause.timeout(timeoutMs3) : TransportCause.of(error);
479
- throw new UnreachableError(this.endpoint.host, method, route, cause);
479
+ throw new UnreachableError(this.endpoint.host, method, route2, cause);
480
480
  } finally {
481
481
  clearTimeout(timer);
482
482
  }
@@ -915,7 +915,7 @@ var init_browser = __esm({
915
915
  }
916
916
  async send(batch) {
917
917
  const retries = this.opts.maxRetries ?? EVENT_MAX_RETRIES;
918
- const sleep6 = this.opts.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
918
+ const sleep7 = this.opts.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
919
919
  for (let attempt = 0; attempt < retries; attempt++) {
920
920
  try {
921
921
  const base = await this.resolveBase();
@@ -932,7 +932,7 @@ var init_browser = __esm({
932
932
  );
933
933
  return;
934
934
  }
935
- await sleep6(500 * 2 ** attempt);
935
+ await sleep7(500 * 2 ** attempt);
936
936
  }
937
937
  }
938
938
  }
@@ -1738,11 +1738,11 @@ var init_media = __esm({
1738
1738
  status
1739
1739
  );
1740
1740
  }
1741
- async send(method, route, body) {
1742
- const reply = await this.transport.send(method, route, body);
1741
+ async send(method, route2, body) {
1742
+ const reply = await this.transport.send(method, route2, body);
1743
1743
  if (!reply.ok)
1744
1744
  throw new MediaUploadError(
1745
- `${method} ${route} -> ${reply.status}`,
1745
+ `${method} ${route2} -> ${reply.status}`,
1746
1746
  reply.status
1747
1747
  );
1748
1748
  return reply.text ? JSON.parse(reply.text) : {};
@@ -2095,7 +2095,7 @@ function click(button, count) {
2095
2095
  modifiers: modifierChord(raw.text)
2096
2096
  });
2097
2097
  }
2098
- var SCROLL_STEP_PX, NOT_EXECUTED, MAX_ERROR2, SCROLL_DIRECTIONS, MEMBERS, AnthropicComputer, AnthropicComputer20251124;
2098
+ var SCROLL_STEP_PX, NOT_EXECUTED, MAX_ERROR2, SCROLL_DIRECTIONS, IMAGE_PARTS, MEMBERS, AnthropicComputer, AnthropicComputer20251124;
2099
2099
  var init_anthropic = __esm({
2100
2100
  "src/worlds/nativeComputer/anthropic.ts"() {
2101
2101
  "use strict";
@@ -2111,6 +2111,14 @@ var init_anthropic = __esm({
2111
2111
  left: [-1, 0],
2112
2112
  right: [1, 0]
2113
2113
  };
2114
+ IMAGE_PARTS = {
2115
+ 6: (data) => ({ type: "image-data", data, mediaType: "image/png" }),
2116
+ 7: (data) => ({
2117
+ type: "file",
2118
+ mediaType: "image/png",
2119
+ data: { type: "data", data }
2120
+ })
2121
+ };
2114
2122
  MEMBERS = {
2115
2123
  screenshot: () => new ComputerAction("screenshot"),
2116
2124
  zoom: (raw) => new ComputerAction("zoom", {
@@ -2220,15 +2228,17 @@ var init_anthropic = __esm({
2220
2228
  ];
2221
2229
  return [{ type: "text", text: result.text ?? "OK" }];
2222
2230
  }
2223
- /** For `anthropic.tools.computerToolset_20260801({ ...computer.aiSdk() })`
2224
- * (or `computer_20251124` with the legacy kind): `execute` runs one action
2225
- * and returns `{ type: "image", data }` or text; `toModelOutput` turns that
2226
- * into the tool result. Calls run one at a time, and once a call fails the
2231
+ /** For `anthropic.tools.computerToolset_20260801(computer.aiSdk({ version: 7 }))`
2232
+ * (AI SDK 7 only), or `computer_20251124` with the legacy kind (AI SDK 6
2233
+ * and 7): `execute` runs one action and returns `{ type: "image", data }` or
2234
+ * text; `toModelOutput` turns that into the tool result in the part shape
2235
+ * of `options.version`. Calls run one at a time, and once a call fails the
2227
2236
  * rest of that step's calls answer as not executed. */
2228
- aiSdk() {
2237
+ aiSdk(options = {}) {
2238
+ const imagePart = _AnthropicComputer.imagePart(options);
2229
2239
  let failedStep;
2230
- const execute = (input, options) => this.serial(async () => {
2231
- const step = options?.messages?.length;
2240
+ const execute = (input, options2) => this.serial(async () => {
2241
+ const step = options2?.messages?.length;
2232
2242
  if (step !== void 0 && step === failedStep)
2233
2243
  throw new Error(NOT_EXECUTED);
2234
2244
  try {
@@ -2240,7 +2250,7 @@ var init_anthropic = __esm({
2240
2250
  });
2241
2251
  return {
2242
2252
  execute,
2243
- toModelOutput: ({ output }) => _AnthropicComputer.aiSdkModelOutput(output)
2253
+ toModelOutput: ({ output }) => _AnthropicComputer.modelOutput(output, imagePart)
2244
2254
  };
2245
2255
  }
2246
2256
  static aiSdkOutput(result) {
@@ -2248,16 +2258,26 @@ var init_anthropic = __esm({
2248
2258
  return { type: "image", data: result.image.toString("base64") };
2249
2259
  return result.text ?? "OK";
2250
2260
  }
2251
- /** `image-data` is what AI SDK 6's Anthropic provider turns into an image
2252
- * block; AI SDK 7 still accepts it (and converts it to a `file` part). */
2253
- static aiSdkModelOutput(output) {
2261
+ /** A screenshot as the image part of AI SDK `options.version`:
2262
+ * `image-data` for 6 (the default), `file` with `{ type: "data", data }`
2263
+ * for 7. */
2264
+ static aiSdkModelOutput(output, options = {}) {
2265
+ return _AnthropicComputer.modelOutput(
2266
+ output,
2267
+ _AnthropicComputer.imagePart(options)
2268
+ );
2269
+ }
2270
+ static imagePart({
2271
+ version = 6
2272
+ }) {
2273
+ if (Object.hasOwn(IMAGE_PARTS, version)) return IMAGE_PARTS[version];
2274
+ throw new Error(
2275
+ `unsupported AI SDK version ${version}; choose ${Object.keys(IMAGE_PARTS).join(" or ")}`
2276
+ );
2277
+ }
2278
+ static modelOutput(output, imagePart) {
2254
2279
  if (typeof output === "string") return { type: "text", value: output };
2255
- return {
2256
- type: "content",
2257
- value: [
2258
- { type: "image-data", data: output.data, mediaType: "image/png" }
2259
- ]
2260
- };
2280
+ return { type: "content", value: [imagePart(output.data)] };
2261
2281
  }
2262
2282
  envelope(block2, content, isError = false) {
2263
2283
  return {
@@ -2665,7 +2685,7 @@ var init_requestLedger = __esm({
2665
2685
  "use strict";
2666
2686
  init_worlds();
2667
2687
  init_sessionContract();
2668
- WORLD_REQUEST_VIAS = ["api", "ui", "tool"];
2688
+ WORLD_REQUEST_VIAS = ["api", "ui", "tool", "webhook"];
2669
2689
  WorldRequestFilterError = class extends Error {
2670
2690
  };
2671
2691
  NOT_RECORDED = "This session's engine records no requests; only hosted World Host sessions do.";
@@ -3398,8 +3418,8 @@ var init_session2 = __esm({
3398
3418
  const path51 = `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/browser-events`;
3399
3419
  const id = agentId ?? process.env.GATEWAY_AGENT_ID ?? `agent-${(0, import_node_crypto2.randomUUID)().replace(/-/g, "").slice(0, 8)}`;
3400
3420
  return new BrowserActionRecorder(
3401
- async (events) => {
3402
- await apiRequest(this.options, "POST", path51, { events });
3421
+ async (events2) => {
3422
+ await apiRequest(this.options, "POST", path51, { events: events2 });
3403
3423
  },
3404
3424
  id,
3405
3425
  {
@@ -3597,13 +3617,13 @@ var init_session2 = __esm({
3597
3617
  WorldRequestQuery.parse({ cursor: opts.cursor, limit: opts.limit ?? REQUEST_LOG_PAGE_MAX })
3598
3618
  );
3599
3619
  }
3600
- page(route, limit, cursor) {
3620
+ page(route2, limit, cursor) {
3601
3621
  const query2 = new URLSearchParams({ limit: String(limit) });
3602
3622
  if (cursor) query2.set("cursor", cursor);
3603
3623
  return apiRequest(
3604
3624
  this.options,
3605
3625
  "GET",
3606
- `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/${route}?${query2.toString()}`
3626
+ `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/${route2}?${query2.toString()}`
3607
3627
  );
3608
3628
  }
3609
3629
  /** The session's call log, oldest first: every tool call, seed, reset,
@@ -3830,12 +3850,12 @@ var init_taskGrades = __esm({
3830
3850
  compact2({ sessionId, ...target })
3831
3851
  );
3832
3852
  }
3833
- regrade(taskId, scope = {}) {
3853
+ regrade(taskId, scope2 = {}) {
3834
3854
  return apiRequest(
3835
3855
  this.options,
3836
3856
  "POST",
3837
3857
  `${TASKS2}/${encodeURIComponent(taskId)}/regrade`,
3838
- compact2({ ...scope })
3858
+ compact2({ ...scope2 })
3839
3859
  );
3840
3860
  }
3841
3861
  };
@@ -5271,7 +5291,7 @@ var require_package = __commonJS({
5271
5291
  "package.json"(exports2, module2) {
5272
5292
  module2.exports = {
5273
5293
  name: "@withgateway/sdk",
5274
- version: "0.4.0",
5294
+ version: "0.6.0",
5275
5295
  description: "Gateway SDK for TypeScript - A/B experiments, tracing, and observability",
5276
5296
  main: "./dist/index.js",
5277
5297
  module: "./dist/index.mjs",
@@ -6051,13 +6071,13 @@ function reportFromResult(result) {
6051
6071
  throw new Error(
6052
6072
  `agent returned ${describeValue(result)}; ${RESULT_CONTRACT}`
6053
6073
  );
6054
- const { report, ...extra } = result;
6055
- if (report === void 0 || report === null) return { report: null, extra };
6056
- if (typeof report !== "string")
6074
+ const { report: report2, ...extra } = result;
6075
+ if (report2 === void 0 || report2 === null) return { report: null, extra };
6076
+ if (typeof report2 !== "string")
6057
6077
  throw new Error(
6058
- `agent returned a report of type ${describeValue(report)}; ${RESULT_CONTRACT}`
6078
+ `agent returned a report of type ${describeValue(report2)}; ${RESULT_CONTRACT}`
6059
6079
  );
6060
- return { report, extra };
6080
+ return { report: report2, extra };
6061
6081
  }
6062
6082
  async function refuseUnreadTools(live) {
6063
6083
  try {
@@ -6228,10 +6248,10 @@ var init_taskRun = __esm({
6228
6248
  this.outcome.notes = run.notes;
6229
6249
  this.files.writeManifest(run.manifest);
6230
6250
  await this.callAgent(agent, run);
6231
- const report = this.outcome.report;
6232
- this.outcome.grade = await this.live.grade(report !== null ? { report } : {});
6251
+ const report2 = this.outcome.report;
6252
+ this.outcome.grade = await this.live.grade(report2 !== null ? { report: report2 } : {});
6233
6253
  this.files.writeJson("grades.json", this.outcome.grade);
6234
- if (report) this.files.write("report.md", report);
6254
+ if (report2) this.files.write("report.md", report2);
6235
6255
  }
6236
6256
  async callAgent(agent, run) {
6237
6257
  try {
@@ -6546,6 +6566,112 @@ var init_requestLog = __esm({
6546
6566
  }
6547
6567
  });
6548
6568
 
6569
+ // src/worlds/webhooks.ts
6570
+ async function listWebhooks(options, sessionId, page = {}) {
6571
+ const query2 = new URLSearchParams({
6572
+ after: String(page.after ?? 0),
6573
+ limit: String(page.limit ?? WORLD_WEBHOOK_PAGE_MAX),
6574
+ tail: String(page.tail ?? false)
6575
+ });
6576
+ if (page.epoch) query2.set("epoch", page.epoch);
6577
+ return apiRequest(options, "GET", `${route(sessionId)}?${query2.toString()}`);
6578
+ }
6579
+ var WORLD_WEBHOOK_PAGE_MAX, FORWARD_TIMEOUT_MS, ERROR_CHARS, route, WorldWebhookForwarder;
6580
+ var init_webhooks = __esm({
6581
+ "src/worlds/webhooks.ts"() {
6582
+ "use strict";
6583
+ init_worlds();
6584
+ WORLD_WEBHOOK_PAGE_MAX = 100;
6585
+ FORWARD_TIMEOUT_MS = 1e4;
6586
+ ERROR_CHARS = 500;
6587
+ route = (sessionId) => `/api/public/world-sessions/${encodeURIComponent(sessionId)}/webhooks`;
6588
+ WorldWebhookForwarder = class {
6589
+ constructor(options, sessionId, forwardTo, opts = {}) {
6590
+ this.options = options;
6591
+ this.sessionId = sessionId;
6592
+ this.forwardTo = forwardTo;
6593
+ this.send = opts.fetch ?? fetch;
6594
+ }
6595
+ options;
6596
+ sessionId;
6597
+ forwardTo;
6598
+ after = 0;
6599
+ epoch = null;
6600
+ answers = [];
6601
+ send;
6602
+ get cursor() {
6603
+ return this.after;
6604
+ }
6605
+ /** Where forwarding begins: the deliveries the session still holds (`replay`), or only those it sends from now. */
6606
+ async start(replay) {
6607
+ if (replay) return null;
6608
+ const page = await this.poll([], { tail: true, limit: 1 });
6609
+ this.follow(page);
6610
+ return page;
6611
+ }
6612
+ /** One poll: the answers held so far sent, the next page forwarded. A poll that fails keeps its answers for the next. */
6613
+ async round() {
6614
+ const page = await this.withAnswers((answers) => this.poll(answers));
6615
+ const forwarded = [];
6616
+ for (const delivery of page.deliveries) {
6617
+ const answer = await this.forward(delivery);
6618
+ this.answers.push(answer);
6619
+ forwarded.push({ delivery, answer });
6620
+ }
6621
+ this.follow(page);
6622
+ return { page, forwarded };
6623
+ }
6624
+ /** Sends the answers still held; the cursor stays, so a delivery this poll returns is forwarded by the next round. */
6625
+ async settle() {
6626
+ if (this.answers.length === 0) return 0;
6627
+ const page = await this.withAnswers((answers) => this.poll(answers, { limit: 1 }));
6628
+ return page.answered;
6629
+ }
6630
+ follow(page) {
6631
+ this.after = page.next;
6632
+ this.epoch = page.epoch;
6633
+ }
6634
+ async withAnswers(poll) {
6635
+ const answers = this.answers.splice(0, WORLD_WEBHOOK_PAGE_MAX);
6636
+ try {
6637
+ return await poll(answers);
6638
+ } catch (error) {
6639
+ this.answers.unshift(...answers);
6640
+ throw error;
6641
+ }
6642
+ }
6643
+ poll(answers, opts = {}) {
6644
+ return apiRequest(this.options, "POST", route(this.sessionId), {
6645
+ after: this.after,
6646
+ epoch: this.epoch,
6647
+ tail: opts.tail ?? false,
6648
+ limit: opts.limit ?? WORLD_WEBHOOK_PAGE_MAX,
6649
+ subscriptions: false,
6650
+ answers
6651
+ });
6652
+ }
6653
+ async forward(delivery) {
6654
+ const started = Date.now();
6655
+ try {
6656
+ const reply = await this.send(this.forwardTo, {
6657
+ method: "POST",
6658
+ headers: delivery.headers,
6659
+ body: delivery.payload,
6660
+ redirect: "manual",
6661
+ signal: AbortSignal.timeout(FORWARD_TIMEOUT_MS)
6662
+ });
6663
+ await reply.arrayBuffer().catch(() => void 0);
6664
+ if (reply.status < 100 || reply.status > 599) throw new Error("the receiver answered an invalid HTTP status");
6665
+ return { id: delivery.id, status: reply.status, durationMs: Date.now() - started, error: null };
6666
+ } catch (error) {
6667
+ const message = error instanceof Error ? error.message : String(error);
6668
+ return { id: delivery.id, status: 0, durationMs: Date.now() - started, error: message.slice(0, ERROR_CHARS) };
6669
+ }
6670
+ }
6671
+ };
6672
+ }
6673
+ });
6674
+
6549
6675
  // src/worlds/checkoutTarget.ts
6550
6676
  var fs2, path3, CheckoutRefusedError, NAMED_EDITS, CheckoutTarget;
6551
6677
  var init_checkoutTarget = __esm({
@@ -7356,20 +7482,20 @@ var init_hub = __esm({
7356
7482
  function fmtScore(score) {
7357
7483
  return score === null ? "no score" : score.toFixed(3);
7358
7484
  }
7359
- function buildMarkdown(report, minScore, source2) {
7485
+ function buildMarkdown(report2, minScore, source2) {
7360
7486
  const lines = [];
7361
7487
  lines.push(
7362
- `### World validation ${report.ok ? "passed" : "failed"} \u2014 \`${report.slug}@${report.branch}\``
7488
+ `### World validation ${report2.ok ? "passed" : "failed"} \u2014 \`${report2.slug}@${report2.branch}\``
7363
7489
  );
7364
7490
  lines.push("");
7365
7491
  const commitLink = source2?.repoUrl && source2?.commit ? `[\`${source2.commit.slice(0, 12)}\`](${source2.repoUrl}/commit/${source2.commit})` : null;
7366
7492
  lines.push(
7367
- `Ran the pull request's own world source` + (commitLink ? ` (${commitLink} on \`${report.branch}\`` : ` (`) + `${commitLink ? ", " : ""}pinned as \`${report.contentHash.slice(0, 12)}\`) through run config **${report.runConfig.name}**` + (minScore !== null ? `, gating at score \u2265 ${minScore}.` : ".")
7493
+ `Ran the pull request's own world source` + (commitLink ? ` (${commitLink} on \`${report2.branch}\`` : ` (`) + `${commitLink ? ", " : ""}pinned as \`${report2.contentHash.slice(0, 12)}\`) through run config **${report2.runConfig.name}**` + (minScore !== null ? `, gating at score \u2265 ${minScore}.` : ".")
7368
7494
  );
7369
7495
  lines.push("");
7370
7496
  lines.push("| Model | Status | Score | Run |");
7371
7497
  lines.push("| --- | --- | ---: | --- |");
7372
- for (const run of report.runs) {
7498
+ for (const run of report2.runs) {
7373
7499
  const r = run.report;
7374
7500
  const link = r?.url ? `[open](${r.url})` : "\u2014";
7375
7501
  const status = run.failure ? `\u274C ${run.failure}` : `\u2705 ${r?.status ?? "COMPLETED"}`;
@@ -7377,7 +7503,7 @@ function buildMarkdown(report, minScore, source2) {
7377
7503
  `| \`${run.model}\` | ${status} | ${fmtScore(r?.score ?? null)} | ${link} |`
7378
7504
  );
7379
7505
  }
7380
- const taskRows = report.runs.flatMap(
7506
+ const taskRows = report2.runs.flatMap(
7381
7507
  (run) => (run.report?.samples ?? []).map((sample3) => ({
7382
7508
  model: run.model,
7383
7509
  task: sample3.task ?? "?",
@@ -7470,9 +7596,9 @@ async function validateWorld(dir, opts) {
7470
7596
  } catch {
7471
7597
  projectId = null;
7472
7598
  }
7473
- const fallbackUrl = (report) => {
7474
- if (report.url) return report.url;
7475
- const evaluationId = report.evaluations[0]?.id;
7599
+ const fallbackUrl = (report2) => {
7600
+ if (report2.url) return report2.url;
7601
+ const evaluationId = report2.evaluations[0]?.id;
7476
7602
  return projectId && evaluationId ? `${host}/project/${projectId}/environment/runs/${encodeURIComponent(evaluationId)}` : null;
7477
7603
  };
7478
7604
  const runs = [];
@@ -7487,28 +7613,28 @@ async function validateWorld(dir, opts) {
7487
7613
  continue;
7488
7614
  }
7489
7615
  progress(`waiting on ${run.model} (run ${run.runId})\u2026`);
7490
- let report = null;
7616
+ let report2 = null;
7491
7617
  let failure2 = null;
7492
7618
  try {
7493
- report = await waitForRun(run.runId, {
7619
+ report2 = await waitForRun(run.runId, {
7494
7620
  timeoutMinutes: opts.timeoutMinutes ?? 45,
7495
7621
  options,
7496
7622
  onTick: (r) => progress(
7497
7623
  `\u2026${run.model}: ${r.status.toLowerCase()} (${r.shardsCompleted ?? 0}/${r.parallelism} shards)`
7498
7624
  )
7499
7625
  });
7500
- report = { ...report, url: fallbackUrl(report) };
7501
- if (report.status.toUpperCase() !== "COMPLETED") {
7502
- failure2 = report.status;
7626
+ report2 = { ...report2, url: fallbackUrl(report2) };
7627
+ if (report2.status.toUpperCase() !== "COMPLETED") {
7628
+ failure2 = report2.status;
7503
7629
  } else if (minScore !== null) {
7504
- if (report.score === null) failure2 = "completed without a score";
7505
- else if (report.score < minScore)
7506
- failure2 = `score ${fmtScore(report.score)} < ${minScore}`;
7630
+ if (report2.score === null) failure2 = "completed without a score";
7631
+ else if (report2.score < minScore)
7632
+ failure2 = `score ${fmtScore(report2.score)} < ${minScore}`;
7507
7633
  }
7508
7634
  } catch (error) {
7509
7635
  failure2 = error instanceof Error ? error.message : String(error);
7510
7636
  }
7511
- runs.push({ model: run.model, runId: run.runId, report, failure: failure2 });
7637
+ runs.push({ model: run.model, runId: run.runId, report: report2, failure: failure2 });
7512
7638
  }
7513
7639
  const base = {
7514
7640
  ok: runs.length > 0 && runs.every((r) => r.failure === null),
@@ -8825,8 +8951,8 @@ async function runtime(creds, request2, opts = {}) {
8825
8951
  throw new CliError(
8826
8952
  "This needs the schema runtime (the CLI bundles it) or platform credentials (`gateway auth login`). " + localRuntimeReason()
8827
8953
  );
8828
- const route = "/api/public/worlds/runtime";
8829
- const res = await new PlatformTransport(creds).send("POST", route, request2, {
8954
+ const route2 = "/api/public/worlds/runtime";
8955
+ const res = await new PlatformTransport(creds).send("POST", route2, request2, {
8830
8956
  timeoutMs: opts.timeoutMs ?? RUNTIME_TIMEOUT_MS
8831
8957
  });
8832
8958
  let payload = null;
@@ -8838,12 +8964,12 @@ async function runtime(creds, request2, opts = {}) {
8838
8964
  const detail = detailFrom(payload);
8839
8965
  if (detail) throw new BridgeRejected(detail);
8840
8966
  if (!res.ok)
8841
- throw new CliError(`POST ${route} (${request2.command}) -> ${res.status}: ${res.text.slice(0, 600)}`, 1);
8842
- if (payload === null) throw new CliError(`POST ${route} (${request2.command}) returned non-JSON`, 1);
8967
+ throw new CliError(`POST ${route2} (${request2.command}) -> ${res.status}: ${res.text.slice(0, 600)}`, 1);
8968
+ if (payload === null) throw new CliError(`POST ${route2} (${request2.command}) returned non-JSON`, 1);
8843
8969
  return payload;
8844
8970
  }
8845
- function withoutFiles(report) {
8846
- const { files: _files, ...rest } = report;
8971
+ function withoutFiles(report2) {
8972
+ const { files: _files, ...rest } = report2;
8847
8973
  return rest;
8848
8974
  }
8849
8975
  function sortedJson(value, indent = 2) {
@@ -9360,7 +9486,7 @@ async function forEachLimited(items, limit, fn) {
9360
9486
  if (failure2) throw failure2;
9361
9487
  }
9362
9488
  async function waitForBatch(client5, batchId, opts = {}) {
9363
- const sleep6 = opts.sleep ?? client5.sleep;
9489
+ const sleep7 = opts.sleep ?? client5.sleep;
9364
9490
  let delay = opts.initialDelayMs ?? 1e3;
9365
9491
  let last = "";
9366
9492
  for (; ; ) {
@@ -9373,7 +9499,7 @@ async function waitForBatch(client5, batchId, opts = {}) {
9373
9499
  if (isSettled(status)) return status;
9374
9500
  if (opts.deadlineMs !== void 0 && (opts.now ?? Date.now)() >= opts.deadlineMs)
9375
9501
  return status;
9376
- await sleep6(delay);
9502
+ await sleep7(delay);
9377
9503
  delay = Math.min(1e4, Math.round(delay * 1.5));
9378
9504
  }
9379
9505
  }
@@ -9419,10 +9545,10 @@ var init_batches = __esm({
9419
9545
  sleepMs = (ms) => new Promise((resolve32) => setTimeout(resolve32, ms));
9420
9546
  slugOf = (world) => world.split("@", 1)[0];
9421
9547
  WorldDataApi = class {
9422
- constructor(creds, slug, sleep6 = sleepMs) {
9548
+ constructor(creds, slug, sleep7 = sleepMs) {
9423
9549
  this.creds = creds;
9424
9550
  this.slug = slug;
9425
- this.sleep = sleep6;
9551
+ this.sleep = sleep7;
9426
9552
  this.base = `/api/public/worlds/${encodeURIComponent(slug)}/data`;
9427
9553
  }
9428
9554
  creds;
@@ -9885,25 +10011,25 @@ async function ingest(world, records2, options = {}) {
9885
10011
  const scratch = fs11.mkdtempSync(path11.join(os2.tmpdir(), "gateway-ingest-"));
9886
10012
  try {
9887
10013
  const pulled = await pull2(world, path11.join(scratch, slug), options);
9888
- let report;
10014
+ let report2;
9889
10015
  let projected;
9890
10016
  if (rows === null) {
9891
10017
  const proven = await ingestLocalToolCalls2(pulled.dir, records2, { redact: "off", dryRun: true, mode, map }, creds);
9892
- report = reportOf(world, proven, redact2);
10018
+ report2 = reportOf(world, proven, redact2);
9893
10019
  projected = proven.projected ?? {};
9894
10020
  } else {
9895
10021
  const proven = await checkLocalWorldData2(pulled.dir, rows, creds);
9896
- report = transformReport(world, records2.length, rows, stderr, { dryRun, redact: redact2, changed: false, kind: proven.kind, entityCounts: proven.entity_counts });
10022
+ report2 = transformReport(world, records2.length, rows, stderr, { dryRun, redact: redact2, changed: false, kind: proven.kind, entityCounts: proven.entity_counts });
9897
10023
  projected = rows;
9898
10024
  }
9899
- report.dryRun = dryRun;
9900
- if (dryRun || report.refusals.length || !Object.keys(projected).length) return report;
10025
+ report2.dryRun = dryRun;
10026
+ if (dryRun || report2.refusals.length || !Object.keys(projected).length) return report2;
9901
10027
  const { pushRows: pushRows2 } = await Promise.resolve().then(() => (init_push(), push_exports));
9902
10028
  const status = await pushRows2(creds, slug, projected, { mode, redact: redact2, message: options.message });
9903
- report.batch = status;
9904
- report.changed = status.state === "applied" || status.state === "published";
9905
- if (status.entityCounts) report.entityCounts = status.entityCounts;
9906
- return report;
10029
+ report2.batch = status;
10030
+ report2.changed = status.state === "applied" || status.state === "published";
10031
+ if (status.entityCounts) report2.entityCounts = status.entityCounts;
10032
+ return report2;
9907
10033
  } finally {
9908
10034
  fs11.rmSync(scratch, { recursive: true, force: true });
9909
10035
  }
@@ -10067,7 +10193,7 @@ var init_dryRun = __esm({
10067
10193
  /** Poll until the run settles or `timeoutSeconds` pass; the last verdict either way. */
10068
10194
  async settle(runId, opts) {
10069
10195
  const now = opts.now ?? Date.now;
10070
- const sleep6 = opts.sleep ?? ((ms) => new Promise((resolve32) => setTimeout(resolve32, ms)));
10196
+ const sleep7 = opts.sleep ?? ((ms) => new Promise((resolve32) => setTimeout(resolve32, ms)));
10071
10197
  const deadline = now() + opts.timeoutSeconds * 1e3;
10072
10198
  for (; ; ) {
10073
10199
  const budget = Math.floor(
@@ -10077,7 +10203,7 @@ var init_dryRun = __esm({
10077
10203
  const verdict = await this.status(runId, budget);
10078
10204
  if (verdict.settled || now() >= deadline) return verdict;
10079
10205
  opts.onProgress?.(verdict);
10080
- if (now() - asked < 1e3) await sleep6(1e3);
10206
+ if (now() - asked < 1e3) await sleep7(1e3);
10081
10207
  }
10082
10208
  }
10083
10209
  };
@@ -10196,6 +10322,7 @@ __export(worlds_exports, {
10196
10322
  VERIFIER_REWARD_PREFIX: () => VERIFIER_REWARD_PREFIX,
10197
10323
  WHITESPACE: () => WHITESPACE,
10198
10324
  WORLD_REQUEST_VIAS: () => WORLD_REQUEST_VIAS,
10325
+ WORLD_WEBHOOK_PAGE_MAX: () => WORLD_WEBHOOK_PAGE_MAX,
10199
10326
  WorldBrowser: () => WorldBrowser,
10200
10327
  WorldCallTooLarge: () => WorldCallTooLarge,
10201
10328
  WorldEditClient: () => WorldEditClient,
@@ -10214,6 +10341,7 @@ __export(worlds_exports, {
10214
10341
  WorldSurfaceUnavailable: () => WorldSurfaceUnavailable,
10215
10342
  WorldTask: () => WorldTask,
10216
10343
  WorldToolsUnread: () => WorldToolsUnread,
10344
+ WorldWebhookForwarder: () => WorldWebhookForwarder,
10217
10345
  WriteTreeFilter: () => WriteTreeFilter,
10218
10346
  aggregateTaskGrade: () => aggregateTaskGrade,
10219
10347
  apiRequest: () => apiRequest,
@@ -10261,6 +10389,7 @@ __export(worlds_exports, {
10261
10389
  listSessions: () => listSessions,
10262
10390
  listTaskSessions: () => listTaskSessions,
10263
10391
  listTasks: () => listTasks,
10392
+ listWebhooks: () => listWebhooks,
10264
10393
  localTreeState: () => localTreeState,
10265
10394
  messageOf: () => messageOf,
10266
10395
  migrateProjectWorlds: () => migrateProjectWorlds,
@@ -10563,6 +10692,7 @@ var init_worlds = __esm({
10563
10692
  init_surfaceDescriptor();
10564
10693
  init_requestLog();
10565
10694
  init_requestLedger();
10695
+ init_webhooks();
10566
10696
  init_browserReconnect();
10567
10697
  init_nativeComputer();
10568
10698
  init_hub();
@@ -10751,9 +10881,9 @@ function resolveCredentials(hostFlag, secretKeyFlag) {
10751
10881
  );
10752
10882
  return { host, publicKey, secretKey };
10753
10883
  }
10754
- async function api(creds, method, route, body, init2 = {}) {
10755
- const reply = await new PlatformTransport(creds).send(method, route, body, init2);
10756
- if (!reply.ok) throw new ApiError2(reply.status, method, route, reply.text);
10884
+ async function api(creds, method, route2, body, init2 = {}) {
10885
+ const reply = await new PlatformTransport(creds).send(method, route2, body, init2);
10886
+ if (!reply.ok) throw new ApiError2(reply.status, method, route2, reply.text);
10757
10887
  return reply.text ? JSON.parse(reply.text) : {};
10758
10888
  }
10759
10889
  function printJson(ctx, value) {
@@ -10772,12 +10902,12 @@ var init_config = __esm({
10772
10902
  STORED_FIELDS = ["host", "public_key", "api_key"];
10773
10903
  ENV_FILE_FORM = "GATEWAY_ENV_FILE=path loads a KEY=value file first: `KEY = value`, quoted values, `export KEY=value` and `#` comments are all accepted; the shell's environment wins.";
10774
10904
  ApiError2 = class extends CliError {
10775
- constructor(status, method, route, text2) {
10905
+ constructor(status, method, route2, text2) {
10776
10906
  const body = parseErrorBody(text2, status);
10777
- super(`${method} ${route} -> ${status}: ${body.detail}`, 1);
10907
+ super(`${method} ${route2} -> ${status}: ${body.detail}`, 1);
10778
10908
  this.status = status;
10779
10909
  this.method = method;
10780
- this.route = route;
10910
+ this.route = route2;
10781
10911
  this.text = text2;
10782
10912
  this.code = body.code;
10783
10913
  }
@@ -10884,27 +11014,27 @@ function packagedFiles(name) {
10884
11014
  return files;
10885
11015
  }
10886
11016
  function installSkill(destination, name, force = false) {
10887
- const report = { written: [], unchanged: [], conflicts: [] };
11017
+ const report2 = { written: [], unchanged: [], conflicts: [] };
10888
11018
  const planned = [];
10889
11019
  for (const [relative6, source2] of Object.entries(packagedFiles(name))) {
10890
11020
  const content = fs17.readFileSync(source2);
10891
11021
  const target = path16.join(destination, relative6);
10892
- if (fs17.existsSync(target) && fs17.readFileSync(target).equals(content)) report.unchanged.push(relative6);
10893
- else if (fs17.existsSync(target) && !force) report.conflicts.push(relative6);
11022
+ if (fs17.existsSync(target) && fs17.readFileSync(target).equals(content)) report2.unchanged.push(relative6);
11023
+ else if (fs17.existsSync(target) && !force) report2.conflicts.push(relative6);
10894
11024
  else {
10895
11025
  planned.push([target, content]);
10896
- report.written.push(relative6);
11026
+ report2.written.push(relative6);
10897
11027
  }
10898
11028
  }
10899
- if (report.conflicts.length) {
10900
- report.written = [];
10901
- return report;
11029
+ if (report2.conflicts.length) {
11030
+ report2.written = [];
11031
+ return report2;
10902
11032
  }
10903
11033
  for (const [target, content] of planned) {
10904
11034
  fs17.mkdirSync(path16.dirname(target), { recursive: true });
10905
11035
  fs17.writeFileSync(target, content);
10906
11036
  }
10907
- return report;
11037
+ return report2;
10908
11038
  }
10909
11039
  function printOrInstallSkill(ctx, name, install, force) {
10910
11040
  const text2 = skillText(name);
@@ -10912,15 +11042,15 @@ function printOrInstallSkill(ctx, name, install, force) {
10912
11042
  process.stdout.write(text2);
10913
11043
  return;
10914
11044
  }
10915
- const report = installSkill(install, name, force);
10916
- if (report.conflicts.length) {
11045
+ const report2 = installSkill(install, name, force);
11046
+ if (report2.conflicts.length) {
10917
11047
  ctx.stderr("Refusing to overwrite files that differ from the packaged skill:");
10918
- for (const relative6 of report.conflicts) ctx.stderr(` ${path16.join(install, relative6)}`);
11048
+ for (const relative6 of report2.conflicts) ctx.stderr(` ${path16.join(install, relative6)}`);
10919
11049
  ctx.stderr("Pass --force to replace them.");
10920
11050
  return 1;
10921
11051
  }
10922
- for (const relative6 of report.written) ctx.stdout(`wrote ${path16.join(install, relative6)}`);
10923
- for (const relative6 of report.unchanged) ctx.stdout(`unchanged ${path16.join(install, relative6)}`);
11052
+ for (const relative6 of report2.written) ctx.stdout(`wrote ${path16.join(install, relative6)}`);
11053
+ for (const relative6 of report2.unchanged) ctx.stdout(`unchanged ${path16.join(install, relative6)}`);
10924
11054
  const step = NEXT_STEPS[name];
10925
11055
  if (step) ctx.stdout(`next: ${step}`);
10926
11056
  }
@@ -11027,8 +11157,8 @@ function credentials(args) {
11027
11157
  function worldsOptions(creds) {
11028
11158
  return { host: creds.host, publicKey: creds.publicKey, secretKey: creds.secretKey };
11029
11159
  }
11030
- async function rawRequest(creds, method, route, body) {
11031
- const reply = await new PlatformTransport(creds).send(method, route, body);
11160
+ async function rawRequest(creds, method, route2, body) {
11161
+ const reply = await new PlatformTransport(creds).send(method, route2, body);
11032
11162
  return {
11033
11163
  ...reply,
11034
11164
  json: () => reply.text ? JSON.parse(reply.text) : {}
@@ -11129,7 +11259,7 @@ var init_shared = __esm({
11129
11259
  codePoints = (cell) => [...cell].length;
11130
11260
  sleep4 = (ms) => new Promise((resolve32) => setTimeout(resolve32, ms));
11131
11261
  SECRET_PROMPT = "Paste the value, then Ctrl-D:";
11132
- REQUEST_LOG_NOTES = "The ledger holds the calls the platform brokered: tool calls, seeds, grades, resets. --requests appends the\nsession's entries in its world's request ledger as kind \"request\" lines, oldest first: every request the\nworld received (via api, ui or tool) with its status, sizes and timing, kept after the session stops. Bodies\nstay in the ledger: `gateway worlds requests show <slug> <result.requestId>` reads one entry's. Reading them\nrecords nothing in the session. A session the World Host did not serve records none, and stderr says so; a\nsession the platform does not answer for fails the command (exit 1) and nothing is written.";
11262
+ REQUEST_LOG_NOTES = "The ledger holds the calls the platform brokered: tool calls, seeds, grades, resets. --requests appends the\nsession's entries in its world's request ledger as kind \"request\" lines, oldest first: every request the\nworld received (via api, ui, tool or webhook) with its status, sizes and timing, kept after the session stops. Bodies\nstay in the ledger: `gateway worlds requests show <slug> <result.requestId>` reads one entry's. Reading them\nrecords nothing in the session. A session the World Host did not serve records none, and stderr says so; a\nsession the platform does not answer for fails the command (exit 1) and nothing is written.";
11133
11263
  }
11134
11264
  });
11135
11265
 
@@ -11149,8 +11279,8 @@ function splitTemplateFiles(files) {
11149
11279
  function walk2(root) {
11150
11280
  const out = [];
11151
11281
  const visit = (rel) => {
11152
- const abs = rel ? path24.join(root, rel) : root;
11153
- for (const entry of fs31.readdirSync(abs, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
11282
+ const abs = rel ? path25.join(root, rel) : root;
11283
+ for (const entry of fs32.readdirSync(abs, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
11154
11284
  const childRel = rel ? `${rel}/${entry.name}` : entry.name;
11155
11285
  if (entry.isSymbolicLink()) continue;
11156
11286
  if (entry.isDirectory()) {
@@ -11167,14 +11297,14 @@ function walk2(root) {
11167
11297
  return out;
11168
11298
  }
11169
11299
  function readText3(root, relative6) {
11170
- const bytes = fs31.readFileSync(path24.join(root, relative6));
11300
+ const bytes = fs32.readFileSync(path25.join(root, relative6));
11171
11301
  const text2 = bytes.toString("utf8");
11172
11302
  if (Buffer.from(text2, "utf8").length !== bytes.length || text2.includes("\uFFFD"))
11173
11303
  return null;
11174
11304
  return text2;
11175
11305
  }
11176
11306
  function isBuildOutput2(relative6) {
11177
- const name = path24.basename(relative6);
11307
+ const name = path25.basename(relative6);
11178
11308
  if (BUILD_OUTPUT_NAMES.has(name)) return true;
11179
11309
  for (const suffix of BUILD_OUTPUT_SUFFIXES)
11180
11310
  if (name.endsWith(suffix)) return true;
@@ -11189,7 +11319,7 @@ function templatePath(relative6) {
11189
11319
  return ROOT_CARRIED_FILES.has(relative6) ? relative6 : null;
11190
11320
  if (parts2[0] === "schema") {
11191
11321
  const name = parts2[parts2.length - 1];
11192
- if (parts2.length !== 2 || !SUPPORTING_SUFFIXES.has(path24.extname(name)) || GENERATED_NAMES.has(name))
11322
+ if (parts2.length !== 2 || !SUPPORTING_SUFFIXES.has(path25.extname(name)) || GENERATED_NAMES.has(name))
11193
11323
  return null;
11194
11324
  return name;
11195
11325
  }
@@ -11198,7 +11328,7 @@ function templatePath(relative6) {
11198
11328
  return null;
11199
11329
  }
11200
11330
  function collectTemplate(directory) {
11201
- if (fs31.existsSync(path24.join(directory, "world.json"))) {
11331
+ if (fs32.existsSync(path25.join(directory, "world.json"))) {
11202
11332
  const files2 = {};
11203
11333
  for (const relative6 of walk2(directory)) {
11204
11334
  const text2 = readText3(directory, relative6);
@@ -11211,7 +11341,7 @@ function collectTemplate(directory) {
11211
11341
  }
11212
11342
  return { source: "template", files: files2, skipped: [] };
11213
11343
  }
11214
- if (!fs31.existsSync(path24.join(directory, "schema", "world.json")))
11344
+ if (!fs32.existsSync(path25.join(directory, "schema", "world.json")))
11215
11345
  throw new CliError(
11216
11346
  `${directory}: neither a connector template (world.json) nor a world (schema/world.json)`,
11217
11347
  1
@@ -11270,7 +11400,7 @@ function registerConnectorCommands(root) {
11270
11400
  run: async (args, ctx) => {
11271
11401
  const dir = args.positionals[0];
11272
11402
  const gathered = collectTemplate(dir);
11273
- const slug = arg.str(args, "slug") ?? path24.basename(path24.resolve(dir));
11403
+ const slug = arg.str(args, "slug") ?? path25.basename(path25.resolve(dir));
11274
11404
  const creds = credentials(args);
11275
11405
  const files = Object.fromEntries(
11276
11406
  Object.entries(gathered.files).map(([p, content]) => [
@@ -11385,7 +11515,7 @@ function registerConnectorCommands(root) {
11385
11515
  run: async (args, ctx) => {
11386
11516
  const slug = args.positionals[0];
11387
11517
  const out = arg.str(args, "out") ?? slug;
11388
- if (fs31.existsSync(out) && (!fs31.statSync(out).isDirectory() || fs31.readdirSync(out).length > 0))
11518
+ if (fs32.existsSync(out) && (!fs32.statSync(out).isDirectory() || fs32.readdirSync(out).length > 0))
11389
11519
  throw new CliError(`${out}: must be a new or empty directory`, 1);
11390
11520
  const pulled = await api(
11391
11521
  credentials(args),
@@ -11399,9 +11529,9 @@ function registerConnectorCommands(root) {
11399
11529
  `Refusing a template path outside the directory: ${relative6}`,
11400
11530
  1
11401
11531
  );
11402
- const target = path24.join(out, relative6);
11403
- fs31.mkdirSync(path24.dirname(target), { recursive: true });
11404
- fs31.writeFileSync(target, files[relative6]);
11532
+ const target = path25.join(out, relative6);
11533
+ fs32.mkdirSync(path25.dirname(target), { recursive: true });
11534
+ fs32.writeFileSync(target, files[relative6]);
11405
11535
  ctx.stdout(relative6);
11406
11536
  }
11407
11537
  ctx.stderr(
@@ -11509,12 +11639,12 @@ function flattenFiles(slug, pulled) {
11509
11639
  }
11510
11640
  return files;
11511
11641
  }
11512
- var fs31, path24, CONNECTORS, HUB, CLONE, WORLD_SKIPPED_DIRS, WORLD_SKIPPED_FILES, WORLD_CARRIED_DIRS, ROOT_CARRIED_FILES, SUPPORTING_SUFFIXES, GENERATED_NAMES, BUILD_OUTPUT_SUFFIXES, BUILD_OUTPUT_NAMES, WORLD_ARTIFACT_DIRS, WORLD_ARTIFACT_FILES, CONNECTOR_ONLY_FILES;
11642
+ var fs32, path25, CONNECTORS, HUB, CLONE, WORLD_SKIPPED_DIRS, WORLD_SKIPPED_FILES, WORLD_CARRIED_DIRS, ROOT_CARRIED_FILES, SUPPORTING_SUFFIXES, GENERATED_NAMES, BUILD_OUTPUT_SUFFIXES, BUILD_OUTPUT_NAMES, WORLD_ARTIFACT_DIRS, WORLD_ARTIFACT_FILES, CONNECTOR_ONLY_FILES;
11513
11643
  var init_connector = __esm({
11514
11644
  "src/cli/platform/connector.ts"() {
11515
11645
  "use strict";
11516
- fs31 = __toESM(require("fs"));
11517
- path24 = __toESM(require("path"));
11646
+ fs32 = __toESM(require("fs"));
11647
+ path25 = __toESM(require("path"));
11518
11648
  init_config();
11519
11649
  init_router();
11520
11650
  init_shared();
@@ -11602,9 +11732,9 @@ async function readFile(options = {}, filePath, limits = {}) {
11602
11732
  async function downloadFile(options = {}, filePath, outPath, onProgress) {
11603
11733
  const file = await getFile(options, filePath);
11604
11734
  const res = await openDownload(file.url);
11605
- fs33.mkdirSync(path26.dirname(path26.resolve(outPath)), { recursive: true });
11735
+ fs34.mkdirSync(path27.dirname(path27.resolve(outPath)), { recursive: true });
11606
11736
  const source2 = import_node_stream.Readable.fromWeb(res.body);
11607
- await (0, import_promises.pipeline)(source2, counting((n) => onProgress?.(n, file.sizeBytes)), fs33.createWriteStream(outPath));
11737
+ await (0, import_promises.pipeline)(source2, counting((n) => onProgress?.(n, file.sizeBytes)), fs34.createWriteStream(outPath));
11608
11738
  return { ...file, out: outPath };
11609
11739
  }
11610
11740
  async function requestUpload(options = {}, body) {
@@ -11615,18 +11745,18 @@ async function confirmUpload(options = {}, fileId, ok = true) {
11615
11745
  }
11616
11746
  async function sha256Base64(localPath) {
11617
11747
  const hash = (0, import_node_crypto16.createHash)("sha256");
11618
- for await (const chunk of fs33.createReadStream(localPath)) hash.update(chunk);
11748
+ for await (const chunk of fs34.createReadStream(localPath)) hash.update(chunk);
11619
11749
  return hash.digest("base64");
11620
11750
  }
11621
11751
  function contentTypeFor(name) {
11622
- return CONTENT_TYPES[path26.extname(name).toLowerCase()] ?? "application/octet-stream";
11752
+ return CONTENT_TYPES[path27.extname(name).toLowerCase()] ?? "application/octet-stream";
11623
11753
  }
11624
- function counting(report) {
11754
+ function counting(report2) {
11625
11755
  let seen = 0;
11626
11756
  return new import_node_stream.Transform({
11627
11757
  transform(chunk, _encoding, callback) {
11628
11758
  seen += chunk.length;
11629
- report(seen);
11759
+ report2(seen);
11630
11760
  callback(null, chunk);
11631
11761
  }
11632
11762
  });
@@ -11646,7 +11776,7 @@ async function putPresigned(uploadUrl, body, headers) {
11646
11776
  if (!res.ok) throw new Error(`upload failed: storage answered HTTP ${res.status}: ${(await res.text()).slice(0, 300)}`);
11647
11777
  }
11648
11778
  async function uploadFile(options = {}, localPath, targetPath, upload = {}) {
11649
- const stat = fs33.statSync(localPath);
11779
+ const stat = fs34.statSync(localPath);
11650
11780
  if (!stat.isFile()) throw new Error(`${localPath} is not a file`);
11651
11781
  if (stat.size === 0) throw new Error(`${localPath} is empty; the drive refuses zero-byte uploads`);
11652
11782
  const contentType = upload.contentType ?? contentTypeFor(localPath);
@@ -11654,7 +11784,7 @@ async function uploadFile(options = {}, localPath, targetPath, upload = {}) {
11654
11784
  const target = drivePath(targetPath);
11655
11785
  const granted = await requestUpload(options, { path: target, contentLength: stat.size, contentType, sha256: sha2563, ...upload.overwrite ? { overwrite: true } : {} });
11656
11786
  try {
11657
- const stream = fs33.createReadStream(localPath).pipe(counting((n) => upload.onProgress?.(n, stat.size)));
11787
+ const stream = fs34.createReadStream(localPath).pipe(counting((n) => upload.onProgress?.(n, stat.size)));
11658
11788
  await putPresigned(granted.uploadUrl, import_node_stream.Readable.toWeb(stream), { contentType, contentLength: stat.size, sha256: sha2563 });
11659
11789
  } catch (error) {
11660
11790
  await confirmUpload(options, granted.fileId, false).catch(() => void 0);
@@ -11702,13 +11832,13 @@ async function listFileConnectors(options = {}) {
11702
11832
  async function syncFileConnector(options = {}, connectorId) {
11703
11833
  return apiRequest(options, "POST", `${BASE}/connectors/sync`, { connectorId });
11704
11834
  }
11705
- var import_node_crypto16, fs33, path26, import_node_stream, import_promises, DRIVE_PREFIX, BASE, CONTENT_TYPES;
11835
+ var import_node_crypto16, fs34, path27, import_node_stream, import_promises, DRIVE_PREFIX, BASE, CONTENT_TYPES;
11706
11836
  var init_files = __esm({
11707
11837
  "src/files/index.ts"() {
11708
11838
  "use strict";
11709
11839
  import_node_crypto16 = require("crypto");
11710
- fs33 = __toESM(require("fs"));
11711
- path26 = __toESM(require("path"));
11840
+ fs34 = __toESM(require("fs"));
11841
+ path27 = __toESM(require("path"));
11712
11842
  import_node_stream = require("stream");
11713
11843
  import_promises = require("stream/promises");
11714
11844
  init_worlds();
@@ -11930,29 +12060,29 @@ async function initFromOpenApi(args, ctx, dir) {
11930
12060
  ...arg.list(args, "exclude").length ? { exclude: arg.list(args, "exclude") } : {},
11931
12061
  ...name ? { name } : {}
11932
12062
  };
11933
- const report = await runtime(creds, request2);
11934
- if (!report.written) {
12063
+ const report2 = await runtime(creds, request2);
12064
+ if (!report2.written) {
11935
12065
  ctx.stdout(
11936
- sortedJson({ status: "ok", written: false, plan: report.plan }, 0)
12066
+ sortedJson({ status: "ok", written: false, plan: report2.plan }, 0)
11937
12067
  );
11938
12068
  return;
11939
12069
  }
11940
- const files = report.files ?? [];
12070
+ const files = report2.files ?? [];
11941
12071
  if (!files.length)
11942
12072
  throw new CliError(
11943
12073
  "The importer compiled the world but returned no files",
11944
12074
  1
11945
12075
  );
11946
12076
  writeWorldFiles(dir, files);
11947
- const { files: _files, ...rest } = report;
12077
+ const { files: _files, ...rest } = report2;
11948
12078
  ctx.stdout(sortedJson({ ...rest, kind: "schema", api: "connector.toml" }, 0));
11949
12079
  }
11950
- var fs34, path27, OPENAPI_MAX_BYTES, FROM_OPENAPI_FLAGS, OpenApiSourceArg, LocalSource, UrlSource, DriveSource;
12080
+ var fs35, path28, OPENAPI_MAX_BYTES, FROM_OPENAPI_FLAGS, OpenApiSourceArg, LocalSource, UrlSource, DriveSource;
11951
12081
  var init_schemaOpenApi = __esm({
11952
12082
  "src/cli/runtime/schemaOpenApi.ts"() {
11953
12083
  "use strict";
11954
- fs34 = __toESM(require("fs"));
11955
- path27 = __toESM(require("path"));
12084
+ fs35 = __toESM(require("fs"));
12085
+ path28 = __toESM(require("path"));
11956
12086
  init_router();
11957
12087
  init_config();
11958
12088
  init_files();
@@ -12010,12 +12140,12 @@ var init_schemaOpenApi = __esm({
12010
12140
  };
12011
12141
  LocalSource = class extends OpenApiSourceArg {
12012
12142
  async bytes() {
12013
- const abs = path27.resolve(this.spelled);
12014
- if (!fs34.existsSync(abs) || !fs34.statSync(abs).isFile())
12143
+ const abs = path28.resolve(this.spelled);
12144
+ if (!fs35.existsSync(abs) || !fs35.statSync(abs).isFile())
12015
12145
  throw new CliError(`--from-openapi ${this.spelled}: no such file`);
12016
- const { size } = fs34.statSync(abs);
12146
+ const { size } = fs35.statSync(abs);
12017
12147
  if (size > OPENAPI_MAX_BYTES) throw this.tooBig(size);
12018
- return fs34.readFileSync(abs);
12148
+ return fs35.readFileSync(abs);
12019
12149
  }
12020
12150
  };
12021
12151
  UrlSource = class extends OpenApiSourceArg {
@@ -12125,16 +12255,16 @@ function uiSection(toml) {
12125
12255
  return out;
12126
12256
  }
12127
12257
  function declareUi(dir) {
12128
- const spec = path28.join(dir, "connector.toml");
12129
- if (!fs35.existsSync(spec))
12258
+ const spec = path29.join(dir, "connector.toml");
12259
+ if (!fs36.existsSync(spec))
12130
12260
  throw new CliError(
12131
12261
  `${dir} has no connector.toml: a ui shows the world's routes, and this world declares none. Add the vendor's routes first (\`gateway worlds connector route add\`), or start from a connector template.`
12132
12262
  );
12133
- const text2 = fs35.readFileSync(spec, "utf8");
12263
+ const text2 = fs36.readFileSync(spec, "utf8");
12134
12264
  if (/^\[ui\]\s*$/m.test(text2)) return false;
12135
12265
  const firstRoute = /^\[\[operations\]\]/m.exec(text2);
12136
12266
  const next = firstRoute ? text2.slice(0, firstRoute.index) + UI_SECTION + "\n" + text2.slice(firstRoute.index) : text2.replace(/\n*$/, "\n") + "\n" + UI_SECTION;
12137
- fs35.writeFileSync(spec, next);
12267
+ fs36.writeFileSync(spec, next);
12138
12268
  return true;
12139
12269
  }
12140
12270
  async function listTemplates(creds) {
@@ -12383,7 +12513,7 @@ function registerSchemaCommands(schema) {
12383
12513
  ],
12384
12514
  notes: "The world is a gateway-world/1 tree: schema/world.json (entities), gateway-env.toml ([schema], [tools],\n[[tasks]]), tools/handlers.py, verifiers/*.sql, and connector.toml + api/handlers.py for its API surface.\nA shipped template arrives with its routes; a custom world declares its own with\n`gateway worlds connector route add`, which creates connector.toml on the first route. The output's\n`next` lists the commands in order.\nHave a vendor's Swagger/OpenAPI document and no world yet? `--from-openapi <path|drive:<path>|url>`\nwrites both from it: keyed schemas become entities, path+method pairs become routes; `--plan-only`\npreviews, `--include '/repos/{owner}/{repo}/issues*'` narrows a big spec. `connector conform` then\nchecks the served world back against the same document.",
12385
12515
  run: async (args, ctx) => {
12386
- const dir = path28.resolve(args.positionals[0]);
12516
+ const dir = path29.resolve(args.positionals[0]);
12387
12517
  if (arg.str(args, "from-openapi")) return initFromOpenApi(args, ctx, dir);
12388
12518
  assertEmptyTarget(dir);
12389
12519
  const connector = arg.str(args, "connector") ?? "custom";
@@ -12395,7 +12525,7 @@ function registerSchemaCommands(schema) {
12395
12525
  );
12396
12526
  const hostFlag = arg.str(args, "host");
12397
12527
  const workspace = connector.startsWith(WORKSPACE_PREFIX);
12398
- let report;
12528
+ let report2;
12399
12529
  let commit = null;
12400
12530
  if (workspace) {
12401
12531
  const slug = connector.slice(WORKSPACE_PREFIX.length);
@@ -12408,36 +12538,36 @@ function registerSchemaCommands(schema) {
12408
12538
  const pulled = await pullWorkspaceTemplate(creds, slug);
12409
12539
  commit = pulled.commit;
12410
12540
  const { carried: carried2, contract } = splitTemplateFiles(pulled.files);
12411
- report = await runtime(creds, {
12541
+ report2 = await runtime(creds, {
12412
12542
  command: "init-template-files",
12413
12543
  connector: slug,
12414
12544
  files: contract,
12415
12545
  ...name ? { name } : {}
12416
12546
  });
12417
- report.files = [...report.files ?? [], ...carried2];
12547
+ report2.files = [...report2.files ?? [], ...carried2];
12418
12548
  } else {
12419
12549
  const creds = localRuntime() ? null : platformCredentials2(
12420
12550
  hostFlag,
12421
12551
  `${connector} is a shipped template and scaffolds offline with the bundled runtime, but ${localRuntimeReason()} Without it the platform scaffolds it.`
12422
12552
  );
12423
- report = await runtime(creds, {
12553
+ report2 = await runtime(creds, {
12424
12554
  command: "init-template",
12425
12555
  connector,
12426
12556
  ...name ? { name } : {},
12427
12557
  ...withExampleTool ? { with_example_tool: true } : {}
12428
12558
  });
12429
12559
  }
12430
- const files = report.files ?? [];
12560
+ const files = report2.files ?? [];
12431
12561
  if (!files.length)
12432
12562
  throw new CliError(
12433
12563
  "The runtime compiled the world but returned no files",
12434
12564
  1
12435
12565
  );
12436
12566
  writeWorldFiles(dir, files);
12437
- const hasRoutes = fs35.existsSync(path28.join(dir, "connector.toml"));
12567
+ const hasRoutes = fs36.existsSync(path29.join(dir, "connector.toml"));
12438
12568
  const out = {
12439
12569
  status: "ok",
12440
- domain: report.domain,
12570
+ domain: report2.domain,
12441
12571
  kind: "schema",
12442
12572
  api: hasRoutes ? "connector.toml" : null,
12443
12573
  next: initNextSteps(args.positionals[0], { hasRoutes, blank: connector === "custom" })
@@ -12469,9 +12599,9 @@ function registerSchemaCommands(schema) {
12469
12599
  notes: "With the bundled runtime (a python3 on this machine) the world is checked in place: its handlers are\nimported and every declared tool bound (`handler_execution.status: ok`), the verifiers run over the\ninitial state (`verifiers.<name>.initial_score`), and each `[dependencies]` entry with a `path` is\nopened beside it so a cross-world verifier runs too. On the platform the handlers report `not_run`.\n`tools` (top level and under handler_execution) is the declared handlers; `handler_execution.served`\nis every name `worlds call` answers: the handlers and a dependency's `alias.tool` (a route answers over HTTP).\nA stale tree says whether `schema compile` will succeed or refuse (rows written against the old contract).\nThe handler pass also reads every tools/*.py statically: a `store.<name>` off the store API is refused at\nfile:line with the available methods, before any handler is imported.\n" + STORE_API_NOTE
12470
12600
  } : {},
12471
12601
  run: async (args, ctx) => {
12472
- const dir = path28.resolve(args.positionals[0]);
12602
+ const dir = path29.resolve(args.positionals[0]);
12473
12603
  const creds = credentialsForRuntime(arg.str(args, "host"));
12474
- const report = await runtime(
12604
+ const report2 = await runtime(
12475
12605
  creds,
12476
12606
  command2 === "compile" ? { command: "compile", ...worldPayload(dir) } : {
12477
12607
  command: "validate",
@@ -12479,9 +12609,9 @@ function registerSchemaCommands(schema) {
12479
12609
  ...localRuntime() ? { execute: true } : {}
12480
12610
  }
12481
12611
  );
12482
- if (command2 === "compile" && report.files?.length)
12483
- writeWorldFiles(dir, report.files);
12484
- ctx.stdout(sortedJson(withoutFiles(report), 0));
12612
+ if (command2 === "compile" && report2.files?.length)
12613
+ writeWorldFiles(dir, report2.files);
12614
+ ctx.stdout(sortedJson(withoutFiles(report2), 0));
12485
12615
  }
12486
12616
  });
12487
12617
  }
@@ -12499,7 +12629,7 @@ function registerSchemaCommands(schema) {
12499
12629
  ],
12500
12630
  notes: "`gateway worlds describe <dir|slug>` is the same view with row counts, and works on a platform slug.",
12501
12631
  run: async (args, ctx) => {
12502
- const dir = path28.resolve(args.positionals[0]);
12632
+ const dir = path29.resolve(args.positionals[0]);
12503
12633
  const creds = credentialsForRuntime(arg.str(args, "host"));
12504
12634
  const description = await describeLocalWorld(dir, creds);
12505
12635
  if (arg.bool(args, "json"))
@@ -12538,19 +12668,19 @@ function registerSchemaCommands(schema) {
12538
12668
  flags: [HOST_FLAG2],
12539
12669
  notes: "Writes ui/static/{index.html, app.js, contract.json}: a dependency-free page that lists, reads, creates,\nupdates and deletes every entity through the world's own routes, with foreign keys linked. `schema compile`\nregenerates it as the contract changes; set `[ui] generated = false` to hand-write the directory instead.\n`worlds serve` mounts it at /__ui/; `worlds session open --surface ui,browser` serves it on the session's\nui origin and `worlds session browse` drives it. A world with no connector.toml has no routes for a ui to\ncall and is refused.",
12540
12670
  run: async (args, ctx) => {
12541
- const dir = path28.resolve(args.positionals[0]);
12671
+ const dir = path29.resolve(args.positionals[0]);
12542
12672
  const declared = declareUi(dir);
12543
12673
  const creds = credentialsForRuntime(arg.str(args, "host"));
12544
- const report = await runtime(creds, {
12674
+ const report2 = await runtime(creds, {
12545
12675
  command: "compile",
12546
12676
  files: readWorldFiles(dir)
12547
12677
  });
12548
- if (report.files?.length) writeWorldFiles(dir, report.files);
12678
+ if (report2.files?.length) writeWorldFiles(dir, report2.files);
12549
12679
  const ui = uiSection(
12550
- fs35.readFileSync(path28.join(dir, "connector.toml"), "utf8")
12680
+ fs36.readFileSync(path29.join(dir, "connector.toml"), "utf8")
12551
12681
  );
12552
12682
  const staticDir = ui.static ?? "ui/static";
12553
- const files = (report.files ?? []).map((f) => f.path).filter((p) => p.startsWith(`${staticDir}/`));
12683
+ const files = (report2.files ?? []).map((f) => f.path).filter((p) => p.startsWith(`${staticDir}/`));
12554
12684
  ctx.stdout(
12555
12685
  sortedJson(
12556
12686
  {
@@ -12562,7 +12692,7 @@ function registerSchemaCommands(schema) {
12562
12692
  generated: ui.generated !== "false"
12563
12693
  },
12564
12694
  files,
12565
- domain: report.domain
12695
+ domain: report2.domain
12566
12696
  },
12567
12697
  0
12568
12698
  )
@@ -12602,14 +12732,14 @@ function registerSchemaCommands(schema) {
12602
12732
  from: arg.str(args, "from") ?? "captures",
12603
12733
  ...write ? { write: true } : {}
12604
12734
  });
12605
- const report = res.report ?? {};
12606
- const changes = report.changes ?? [];
12607
- const compared = Object.values(report.entities ?? {}).reduce(
12735
+ const report2 = res.report ?? {};
12736
+ const changes = report2.changes ?? [];
12737
+ const compared = Object.values(report2.entities ?? {}).reduce(
12608
12738
  (a, b) => a + b,
12609
12739
  0
12610
12740
  );
12611
12741
  ctx.stdout(
12612
- `reconciled from ${report.source ?? "captures"}: ${compared} captured rows compared, ${changes.length} changes`
12742
+ `reconciled from ${report2.source ?? "captures"}: ${compared} captured rows compared, ${changes.length} changes`
12613
12743
  );
12614
12744
  for (const c of changes)
12615
12745
  ctx.stdout(` ${c.entity}.${c.field} ${c.change} ${c.detail}`);
@@ -12621,12 +12751,12 @@ function registerSchemaCommands(schema) {
12621
12751
  }
12622
12752
  });
12623
12753
  }
12624
- var fs35, path28, HOST_FLAG2, UI_SECTION, WORKSPACE_PREFIX, describedOnPlatform, describedLocally, enumValue;
12754
+ var fs36, path29, HOST_FLAG2, UI_SECTION, WORKSPACE_PREFIX, describedOnPlatform, describedLocally, enumValue;
12625
12755
  var init_schema = __esm({
12626
12756
  "src/cli/runtime/schema.ts"() {
12627
12757
  "use strict";
12628
- fs35 = __toESM(require("fs"));
12629
- path28 = __toESM(require("path"));
12758
+ fs36 = __toESM(require("fs"));
12759
+ path29 = __toESM(require("path"));
12630
12760
  init_router();
12631
12761
  init_config();
12632
12762
  init_local();
@@ -12653,7 +12783,7 @@ var init_schema = __esm({
12653
12783
  ...description,
12654
12784
  where: "local",
12655
12785
  path: dir,
12656
- on_platform: `gateway worlds describe ${path28.basename(dir)}@main`
12786
+ on_platform: `gateway worlds describe ${path29.basename(dir)}@main`
12657
12787
  });
12658
12788
  enumValue = (value) => typeof value === "string" ? value : JSON.stringify(value);
12659
12789
  }
@@ -15762,13 +15892,13 @@ var Pacer = class {
15762
15892
  /** Waits until the interval since the tool's last call has passed; resolves to the
15763
15893
  * seconds waited. `sleep`/`clock` are injectable for tests. */
15764
15894
  async wait(name, intervalMs, opts = {}) {
15765
- const sleep6 = opts.sleep ?? ((seconds) => new Promise((resolve32) => setTimeout(resolve32, seconds * 1e3)));
15895
+ const sleep7 = opts.sleep ?? ((seconds) => new Promise((resolve32) => setTimeout(resolve32, seconds * 1e3)));
15766
15896
  const clock = opts.clock ?? (() => Date.now() / 1e3);
15767
15897
  const now = clock();
15768
15898
  const due = (this.last.get(name) ?? -Infinity) + intervalMs / 1e3;
15769
15899
  const waited = Math.max(0, due - now);
15770
15900
  this.last.set(name, Math.max(now, due));
15771
- if (waited) await sleep6(waited);
15901
+ if (waited) await sleep7(waited);
15772
15902
  return Math.round(waited * 1e3) / 1e3;
15773
15903
  }
15774
15904
  };
@@ -17141,10 +17271,10 @@ var HookRun = class _HookRun {
17141
17271
  /** `run_end`: every handler sees the report and the artifacts; a deny (the alias
17142
17272
  * outgoing scan found a real value) or a failed handler fails the run. Waits for the
17143
17273
  * `async` handlers first. Findings are returned either way. */
17144
- async end(report, artifacts = {}) {
17274
+ async end(report2, artifacts = {}) {
17145
17275
  await this.drain();
17146
17276
  const event = this.event("run_end", "run_end", {
17147
- report,
17277
+ report: report2,
17148
17278
  artifacts: { ...artifacts }
17149
17279
  });
17150
17280
  const before = this.findings.length;
@@ -17446,16 +17576,16 @@ function readFieldKinds(file, cwd) {
17446
17576
  if (!fs18.existsSync(target)) throw new CliError(`${target} not found (--field-kinds)`, 2);
17447
17577
  return JSON.parse(fs18.readFileSync(target, "utf8"));
17448
17578
  }
17449
- function summaryLines(report, sampleSize) {
17450
- const body = report.toDict();
17451
- const head = report.ok ? `no detected leaks: ${body.census.total} identifier(s) checked across ${report.recordsScanned} record(s)` : `${report.findings.length} finding(s): ${body.leaked_identifiers} of ${body.census.total} identifiers reached the model (coverage ${body.coverage})`;
17452
- const findings = report.findings.map(
17579
+ function summaryLines(report2, sampleSize) {
17580
+ const body = report2.toDict();
17581
+ const head = report2.ok ? `no detected leaks: ${body.census.total} identifier(s) checked across ${report2.recordsScanned} record(s)` : `${report2.findings.length} finding(s): ${body.leaked_identifiers} of ${body.census.total} identifiers reached the model (coverage ${body.coverage})`;
17582
+ const findings = report2.findings.map(
17453
17583
  (f) => ` record ${f.record} ${f.tool.padEnd(24)} ${f.kind.padEnd(12)} ${f.source.padEnd(8)} ${f.prefix}\u2026`
17454
17584
  );
17455
- const sample3 = report.reviewSample(sampleSize).map((s) => ` record ${s.record} ${s.tool}: ${s.text.slice(0, 160)}`);
17585
+ const sample3 = report2.reviewSample(sampleSize).map((s) => ` record ${s.record} ${s.tool}: ${s.text.slice(0, 160)}`);
17456
17586
  return [
17457
17587
  head,
17458
- `detectors: ${report.detectors.join(", ")} (a value in no list and matching no pattern is invisible to them)`,
17588
+ `detectors: ${report2.detectors.join(", ")} (a value in no list and matching no pattern is invisible to them)`,
17459
17589
  ...findings,
17460
17590
  ...sample3.length > 0 ? ["review sample (shown to the model, nothing flagged; read these):", ...sample3] : []
17461
17591
  ];
@@ -17474,10 +17604,10 @@ function registerHooksAuditCommand(hooks) {
17474
17604
  const target = args.positionals[0];
17475
17605
  if (!target) throw new CliError("audit needs a run directory", 2);
17476
17606
  const cwd = process.cwd();
17477
- const report = new AuditRunDir(target, cwd).audit(readFieldKinds(arg.str(args, "field-kinds"), cwd));
17478
- if (arg.bool(args, "json")) printJson(ctx, report.toDict());
17479
- else summaryLines(report, Number(arg.str(args, "sample") ?? 0)).forEach((line) => ctx.stdout(line));
17480
- return report.ok ? 0 : 1;
17607
+ const report2 = new AuditRunDir(target, cwd).audit(readFieldKinds(arg.str(args, "field-kinds"), cwd));
17608
+ if (arg.bool(args, "json")) printJson(ctx, report2.toDict());
17609
+ else summaryLines(report2, Number(arg.str(args, "sample") ?? 0)).forEach((line) => ctx.stdout(line));
17610
+ return report2.ok ? 0 : 1;
17481
17611
  }
17482
17612
  });
17483
17613
  }
@@ -17823,8 +17953,8 @@ async function runCodingAgentHook(configFile, input, opts) {
17823
17953
  note
17824
17954
  };
17825
17955
  }
17826
- const report = readLastAssistantText(input.transcript_path);
17827
- const verdict = await run.end(report, {});
17956
+ const report2 = readLastAssistantText(input.transcript_path);
17957
+ const verdict = await run.end(report2, {});
17828
17958
  if (!verdict.passed)
17829
17959
  return {
17830
17960
  output: {
@@ -17910,9 +18040,9 @@ function registerHooksCommands(root) {
17910
18040
  run: async (args, ctx) => {
17911
18041
  const file = args.positionals[0];
17912
18042
  if (!file) throw new CliError("gateway hooks check <config>");
17913
- let report;
18043
+ let report2;
17914
18044
  try {
17915
- report = await checkHooks(file, {
18045
+ report2 = await checkHooks(file, {
17916
18046
  event: arg.str(args, "event"),
17917
18047
  tool: arg.str(args, "tool"),
17918
18048
  input: readJsonFlag(args, "input"),
@@ -17925,16 +18055,16 @@ function registerHooksCommands(root) {
17925
18055
  throw error;
17926
18056
  }
17927
18057
  if (arg.bool(args, "json")) {
17928
- printJson(ctx, report);
17929
- return report.problems.length ? 1 : 0;
18058
+ printJson(ctx, report2);
18059
+ return report2.problems.length ? 1 : 0;
17930
18060
  }
17931
18061
  ctx.stdout(
17932
- `${report.config}: ${report.rules} rule(s), ${report.handlers} handler(s) \u2014 valid`
18062
+ `${report2.config}: ${report2.rules} rule(s), ${report2.handlers} handler(s) \u2014 valid`
17933
18063
  );
17934
18064
  ctx.stdout(
17935
- `sample: ${report.event} ${report.tool} ${JSON.stringify(report.input)}`
18065
+ `sample: ${report2.event} ${report2.tool} ${JSON.stringify(report2.input)}`
17936
18066
  );
17937
- for (const rule of report.outcomes) {
18067
+ for (const rule of report2.outcomes) {
17938
18068
  ctx.stdout(
17939
18069
  `${rule.matched ? "fires " : "skips "} ${rule.position} matcher: ${rule.matcher}`
17940
18070
  );
@@ -17950,9 +18080,9 @@ function registerHooksCommands(root) {
17950
18080
  );
17951
18081
  }
17952
18082
  }
17953
- if (report.tools.length) {
17954
- ctx.stdout(`tools: ${report.tools.length} declared`);
17955
- for (const t of report.tools) {
18083
+ if (report2.tools.length) {
18084
+ ctx.stdout(`tools: ${report2.tools.length} declared`);
18085
+ for (const t of report2.tools) {
17956
18086
  const params = t.parameters;
17957
18087
  const fields = Object.keys(params.properties ?? {}).map(
17958
18088
  (f) => params.required?.includes(f) ? f : `${f}?`
@@ -17962,8 +18092,8 @@ function registerHooksCommands(root) {
17962
18092
  );
17963
18093
  }
17964
18094
  }
17965
- if (report.probe) {
17966
- const p = report.probe;
18095
+ if (report2.probe) {
18096
+ const p = report2.probe;
17967
18097
  if (p.error)
17968
18098
  ctx.stdout(
17969
18099
  `probe ${p.tool}: FAILED after ${p.elapsed}s \u2014 ${p.error}`
@@ -17979,8 +18109,8 @@ function registerHooksCommands(root) {
17979
18109
  );
17980
18110
  }
17981
18111
  }
17982
- if (report.problems.length) {
17983
- for (const problem of report.problems)
18112
+ if (report2.problems.length) {
18113
+ for (const problem of report2.problems)
17984
18114
  ctx.stderr(`problem: ${problem}`);
17985
18115
  return 1;
17986
18116
  }
@@ -18244,7 +18374,7 @@ function registerAuthCommands(root) {
18244
18374
  }
18245
18375
 
18246
18376
  // src/cli/platform/bench.ts
18247
- var fs26 = __toESM(require("fs"));
18377
+ var fs27 = __toESM(require("fs"));
18248
18378
  init_config();
18249
18379
  init_router();
18250
18380
  init_hub();
@@ -18750,8 +18880,8 @@ function editVerbSpecs() {
18750
18880
  }
18751
18881
 
18752
18882
  // src/cli/platform/sandboxVerbs.ts
18753
- var fs24 = __toESM(require("fs"));
18754
- var path19 = __toESM(require("path"));
18883
+ var fs25 = __toESM(require("fs"));
18884
+ var path20 = __toESM(require("path"));
18755
18885
  init_config();
18756
18886
  init_router();
18757
18887
  init_sandbox();
@@ -19085,8 +19215,8 @@ var ScanError = class extends Error {
19085
19215
  };
19086
19216
  var WS = /* @__PURE__ */ new Set([32, 10, 13, 9]);
19087
19217
  var TopLevelScanner = class {
19088
- constructor(events) {
19089
- this.events = events;
19218
+ constructor(events2) {
19219
+ this.events = events2;
19090
19220
  }
19091
19221
  events;
19092
19222
  mode = "start";
@@ -19698,17 +19828,55 @@ var REDACT_FLAG = {
19698
19828
  // src/cli/platform/sandboxVerbs.ts
19699
19829
  init_shared();
19700
19830
 
19831
+ // src/cli/version.ts
19832
+ var fs24 = __toESM(require("fs"));
19833
+ var path19 = __toESM(require("path"));
19834
+ function cliVersion() {
19835
+ if (true) return "0.6.0";
19836
+ if (typeof __dirname !== "string") return "unknown";
19837
+ try {
19838
+ const pkg = JSON.parse(fs24.readFileSync(path19.resolve(__dirname, "../../package.json"), "utf8"));
19839
+ return pkg.version ?? "unknown";
19840
+ } catch {
19841
+ return "unknown";
19842
+ }
19843
+ }
19844
+ var CliRelease = class _CliRelease {
19845
+ constructor(version) {
19846
+ this.version = version;
19847
+ }
19848
+ version;
19849
+ static current() {
19850
+ return new _CliRelease(cliVersion());
19851
+ }
19852
+ olderThan(other) {
19853
+ const mine = _CliRelease.parts(this.version);
19854
+ const theirs = _CliRelease.parts(other);
19855
+ if (!mine || !theirs) return false;
19856
+ const index2 = mine.findIndex((part, at) => part !== theirs[at]);
19857
+ return index2 !== -1 && mine[index2] < theirs[index2];
19858
+ }
19859
+ staleNotice(platform) {
19860
+ if (!platform || !this.olderThan(platform)) return null;
19861
+ return `gateway ${this.version} is older than the platform's ${platform}; flags and verbs may be missing here: npm install -g @withgateway/sdk@latest`;
19862
+ }
19863
+ static parts(version) {
19864
+ const match = /^(\d+)\.(\d+)\.(\d+)/.exec(version);
19865
+ return match ? match.slice(1, 4).map(Number) : null;
19866
+ }
19867
+ };
19868
+
19701
19869
  // src/cli/platform/sandboxImportReport.ts
19702
19870
  init_config();
19703
19871
  init_sandbox();
19704
19872
  init_shared();
19705
19873
  init_batches();
19706
19874
  var SandboxImportReport = class {
19707
- constructor(sandbox, creds, sandboxId, report, ctx) {
19875
+ constructor(sandbox, creds, sandboxId, report2, ctx) {
19708
19876
  this.sandbox = sandbox;
19709
19877
  this.creds = creds;
19710
19878
  this.sandboxId = sandboxId;
19711
- this.report = report;
19879
+ this.report = report2;
19712
19880
  this.ctx = ctx;
19713
19881
  }
19714
19882
  sandbox;
@@ -19819,7 +19987,7 @@ function assertWriteSize(bytes, filePath) {
19819
19987
  );
19820
19988
  }
19821
19989
  function walk(dir, filter, rel, out) {
19822
- for (const entry of fs24.readdirSync(path19.join(dir, rel), { withFileTypes: true })) {
19990
+ for (const entry of fs25.readdirSync(path20.join(dir, rel), { withFileTypes: true })) {
19823
19991
  const child = rel ? `${rel}/${entry.name}` : entry.name;
19824
19992
  if (entry.isDirectory() && filter.skipsDirectory(entry.name)) out.skipped.push(`${child}/`);
19825
19993
  else if (entry.isDirectory()) walk(dir, filter, child, out);
@@ -19833,7 +20001,7 @@ async function writeTree(args, ctx, sandboxId, target, dir) {
19833
20001
  const { files, skipped } = walk(dir, new WriteTreeFilter(), "", { files: [], skipped: [] });
19834
20002
  files.sort();
19835
20003
  skipped.sort();
19836
- for (const rel of files) assertWriteSize(fs24.statSync(path19.join(dir, rel)).size, rel);
20004
+ for (const rel of files) assertWriteSize(fs25.statSync(path20.join(dir, rel)).size, rel);
19837
20005
  if (skipped.length > 0)
19838
20006
  ctx.stderr(
19839
20007
  `skipped ${skipped.length} path${skipped.length === 1 ? "" : "s"} the platform never versions: ` + skipped.slice(0, SKIPPED_LISTED).join(", ") + (skipped.length > SKIPPED_LISTED ? ", \u2026" : "")
@@ -19842,15 +20010,15 @@ async function writeTree(args, ctx, sandboxId, target, dir) {
19842
20010
  const written = [];
19843
20011
  for (const rel of files)
19844
20012
  written.push(
19845
- await sandbox.write(sandboxId, target === "." ? rel : `${target}/${rel}`, fs24.readFileSync(path19.join(dir, rel)))
20013
+ await sandbox.write(sandboxId, target === "." ? rel : `${target}/${rel}`, fs25.readFileSync(path20.join(dir, rel)))
19846
20014
  );
19847
20015
  return written;
19848
20016
  }
19849
20017
  async function sourceBytes(from, content, stdin, filePath) {
19850
20018
  if (content !== void 0) return Buffer.from(content, "utf8");
19851
20019
  if (from === void 0) return Buffer.from(await stdin(), "utf8");
19852
- assertWriteSize(fs24.statSync(from).size, filePath);
19853
- return fs24.readFileSync(from);
20020
+ assertWriteSize(fs25.statSync(from).size, filePath);
20021
+ return fs25.readFileSync(from);
19854
20022
  }
19855
20023
  function client2(args) {
19856
20024
  return new WorldSandboxClient(worldsOptions(credentials(args)));
@@ -20016,16 +20184,16 @@ function sandboxVerbSpecs() {
20016
20184
  ],
20017
20185
  notes: "A new-world sandbox reports baseVersionId/baseContentHash null, branch main and pendingSlug; `check` runs the push gate the first commit will run.",
20018
20186
  run: async (args, ctx) => {
20019
- printJson(
20020
- ctx,
20021
- await client2(args).open(
20022
- openTarget(
20023
- args.positionals[0],
20024
- arg.str(args, "new"),
20025
- arg.str(args, "from")
20026
- )
20187
+ const opened = await client2(args).open(
20188
+ openTarget(
20189
+ args.positionals[0],
20190
+ arg.str(args, "new"),
20191
+ arg.str(args, "from")
20027
20192
  )
20028
20193
  );
20194
+ printJson(ctx, opened);
20195
+ const stale = CliRelease.current().staleNotice(opened.cli?.version);
20196
+ if (stale) ctx.stderr(`warning: ${stale}`);
20029
20197
  }
20030
20198
  },
20031
20199
  {
@@ -20091,7 +20259,7 @@ function sandboxVerbSpecs() {
20091
20259
  const file = await client2(args).read(sandboxId, filePath);
20092
20260
  const out = arg.str(args, "out");
20093
20261
  if (out) {
20094
- fs24.writeFileSync(out, file.bytes);
20262
+ fs25.writeFileSync(out, file.bytes);
20095
20263
  printJson(ctx, { path: file.path, size: file.size, out });
20096
20264
  return;
20097
20265
  }
@@ -20121,7 +20289,7 @@ function sandboxVerbSpecs() {
20121
20289
  const content = arg.str(args, "content");
20122
20290
  if (from && content !== void 0)
20123
20291
  throw new CliError("--from and --content are mutually exclusive");
20124
- if (from && fs24.statSync(from).isDirectory())
20292
+ if (from && fs25.statSync(from).isDirectory())
20125
20293
  return printJson(ctx, await writeTree(args, ctx, sandboxId, filePath, from));
20126
20294
  const bytes = await sourceBytes(from, content, () => ctx.stdin(), filePath);
20127
20295
  assertWriteSize(bytes.length, filePath);
@@ -20283,7 +20451,7 @@ function sandboxVerbSpecs() {
20283
20451
  run: async (args, ctx) => {
20284
20452
  const [sandboxId, filePath] = args.positionals;
20285
20453
  const sandbox = client2(args);
20286
- const report = new SandboxImportReport(
20454
+ const report2 = new SandboxImportReport(
20287
20455
  sandbox,
20288
20456
  credentials(args),
20289
20457
  sandboxId,
@@ -20306,9 +20474,9 @@ function sandboxVerbSpecs() {
20306
20474
  })
20307
20475
  );
20308
20476
  } catch (error) {
20309
- return report.refused(error);
20477
+ return report2.refused(error);
20310
20478
  }
20311
- return report.answered(answer);
20479
+ return report2.answered(answer);
20312
20480
  }
20313
20481
  },
20314
20482
  {
@@ -20335,8 +20503,8 @@ function sandboxVerbSpecs() {
20335
20503
  }
20336
20504
 
20337
20505
  // src/cli/platform/versionVerbs.ts
20338
- var fs25 = __toESM(require("fs"));
20339
- var path20 = __toESM(require("path"));
20506
+ var fs26 = __toESM(require("fs"));
20507
+ var path21 = __toESM(require("path"));
20340
20508
  init_config();
20341
20509
  init_router();
20342
20510
  init_hub();
@@ -20373,7 +20541,7 @@ function bumpPostVersion(version) {
20373
20541
  }
20374
20542
  function readPyprojectVersion(dir) {
20375
20543
  try {
20376
- const text2 = fs25.readFileSync(path20.join(dir, "pyproject.toml"), "utf8");
20544
+ const text2 = fs26.readFileSync(path21.join(dir, "pyproject.toml"), "utf8");
20377
20545
  const section = /\[project\]([\s\S]*?)(\n\[|$)/.exec(text2)?.[1] ?? "";
20378
20546
  return /\bversion\s*=\s*"([^"]+)"/.exec(section)?.[1];
20379
20547
  } catch {
@@ -20381,10 +20549,10 @@ function readPyprojectVersion(dir) {
20381
20549
  }
20382
20550
  }
20383
20551
  function updatePyprojectVersion(file, newVersion) {
20384
- const content = fs25.readFileSync(file, "utf8");
20552
+ const content = fs26.readFileSync(file, "utf8");
20385
20553
  const updated = content.replace(/(\s*)version\s*=\s*["'][^"']*["']/, `$1version = "${newVersion}"`);
20386
20554
  if (updated === content) throw new CliError("version line not found or unchanged in pyproject.toml", 1);
20387
- fs25.writeFileSync(file, updated);
20555
+ fs26.writeFileSync(file, updated);
20388
20556
  }
20389
20557
  function applyVersionBump(dir, args) {
20390
20558
  const picked = ["auto-bump", "rc", "post"].filter((name) => arg.bool(args, name));
@@ -20393,11 +20561,11 @@ function applyVersionBump(dir, args) {
20393
20561
  const current = readPyprojectVersion(dir);
20394
20562
  if (!current)
20395
20563
  throw new CliError(
20396
- `--${picked[0]} needs a [project].version in ${path20.join(dir, "pyproject.toml")} to bump; this dir has none.`,
20564
+ `--${picked[0]} needs a [project].version in ${path21.join(dir, "pyproject.toml")} to bump; this dir has none.`,
20397
20565
  1
20398
20566
  );
20399
20567
  const next = picked[0] === "auto-bump" ? bumpVersion(current) : picked[0] === "rc" ? bumpRcVersion(current) : bumpPostVersion(current);
20400
- updatePyprojectVersion(path20.join(dir, "pyproject.toml"), next);
20568
+ updatePyprojectVersion(path21.join(dir, "pyproject.toml"), next);
20401
20569
  return next;
20402
20570
  }
20403
20571
  var VERSION_ID_FLAG = { name: "version-id", help: "Version id (default: the main tip)." };
@@ -20467,7 +20635,7 @@ function versionVerbSpecs() {
20467
20635
  "Push without --build-wheel, or build the wheel with the Python CLI."
20468
20636
  );
20469
20637
  const dir = args.positionals[0] ?? ".";
20470
- if (!fs25.existsSync(dir) || !fs25.statSync(dir).isDirectory()) throw new CliError(`Not a directory: ${dir}`, 1);
20638
+ if (!fs26.existsSync(dir) || !fs26.statSync(dir).isDirectory()) throw new CliError(`Not a directory: ${dir}`, 1);
20471
20639
  const options = worldsOptions(credentials(args));
20472
20640
  applyVersionBump(dir, args);
20473
20641
  await checkSchemaTreeBeforePush(dir);
@@ -20906,7 +21074,7 @@ function registerBenchCommands(root) {
20906
21074
  await cancelRun(credentials(args), runId)
20907
21075
  );
20908
21076
  const options = worldsOptions(credentials(args));
20909
- const report = arg.bool(args, "wait") ? await waitForRun(runId, {
21077
+ const report2 = arg.bool(args, "wait") ? await waitForRun(runId, {
20910
21078
  timeoutMinutes: arg.int(args, "timeout-min") ?? 45,
20911
21079
  options,
20912
21080
  onTick: (r) => ctx.stderr(
@@ -20914,22 +21082,22 @@ function registerBenchCommands(root) {
20914
21082
  )
20915
21083
  }) : await getRun(runId, options);
20916
21084
  ctx.stdout(
20917
- `${report.id} ${report.status}${report.score !== null ? ` score=${report.score.toFixed(3)}` : ""} (${report.model ?? "?"} \xB7 ${report.versionLabel ?? "?"} \xB7 x${report.parallelism})`
21085
+ `${report2.id} ${report2.status}${report2.score !== null ? ` score=${report2.score.toFixed(3)}` : ""} (${report2.model ?? "?"} \xB7 ${report2.versionLabel ?? "?"} \xB7 x${report2.parallelism})`
20918
21086
  );
20919
- for (const sample3 of report.samples) {
21087
+ for (const sample3 of report2.samples) {
20920
21088
  const subs = Object.entries(sample3.rewards).filter(([, v]) => typeof v === "number").map(([k, v]) => `${k}=${v.toFixed(2)}`).join(" ");
20921
21089
  ctx.stdout(
20922
21090
  ` ${(sample3.reward ?? 0).toFixed(2)} ${sample3.task ?? "?"}${subs ? ` [${subs}]` : ""}`
20923
21091
  );
20924
21092
  }
20925
- if (report.summary) ctx.stdout(` ${report.summary}`);
20926
- if (!report.terminal) {
21093
+ if (report2.summary) ctx.stdout(` ${report2.summary}`);
21094
+ if (!report2.terminal) {
20927
21095
  ctx.stderr(
20928
- `run ${report.id} is still ${report.status.toLowerCase()}; pass --wait to poll it to a verdict`
21096
+ `run ${report2.id} is still ${report2.status.toLowerCase()}; pass --wait to poll it to a verdict`
20929
21097
  );
20930
21098
  return 0;
20931
21099
  }
20932
- return report.status.toUpperCase() === "COMPLETED" ? 0 : 1;
21100
+ return report2.status.toUpperCase() === "COMPLETED" ? 0 : 1;
20933
21101
  }
20934
21102
  });
20935
21103
  bench.command({
@@ -21117,7 +21285,7 @@ function registerBenchCommands(root) {
21117
21285
  if (!runConfig)
21118
21286
  throw new CliError("bench validate needs --run-config NAME");
21119
21287
  const minScoreRaw = arg.str(args, "min-score");
21120
- const report = await validateWorld(args.positionals[0] ?? ".", {
21288
+ const report2 = await validateWorld(args.positionals[0] ?? ".", {
21121
21289
  slug: arg.str(args, "slug"),
21122
21290
  runConfig,
21123
21291
  branch: arg.str(args, "branch"),
@@ -21126,17 +21294,17 @@ function registerBenchCommands(root) {
21126
21294
  onProgress: (line) => ctx.stderr(line),
21127
21295
  options: worldsOptions(credentials(args))
21128
21296
  });
21129
- for (const run of report.runs) {
21297
+ for (const run of report2.runs) {
21130
21298
  ctx.stdout(
21131
21299
  `${run.model}: ${run.failure ? `FAIL \u2014 ${run.failure}` : "pass"}${run.report?.score != null ? ` score=${run.report.score.toFixed(3)}` : ""}${run.report?.url ? ` ${run.report.url}` : ""}`
21132
21300
  );
21133
21301
  }
21134
21302
  const summaryFile = arg.str(args, "summary-file");
21135
- if (summaryFile) fs26.writeFileSync(summaryFile, report.markdown + "\n");
21303
+ if (summaryFile) fs27.writeFileSync(summaryFile, report2.markdown + "\n");
21136
21304
  const stepSummary2 = process.env.GITHUB_STEP_SUMMARY;
21137
- if (stepSummary2) fs26.appendFileSync(stepSummary2, report.markdown + "\n");
21138
- ctx.stdout(report.ok ? "validation passed" : "validation FAILED");
21139
- return report.ok ? 0 : 1;
21305
+ if (stepSummary2) fs27.appendFileSync(stepSummary2, report2.markdown + "\n");
21306
+ ctx.stdout(report2.ok ? "validation passed" : "validation FAILED");
21307
+ return report2.ok ? 0 : 1;
21140
21308
  }
21141
21309
  });
21142
21310
  bench.command({
@@ -21323,16 +21491,16 @@ function registerBenchCommands(root) {
21323
21491
  }
21324
21492
 
21325
21493
  // src/cli/platform/benchmarks.ts
21326
- var fs37 = __toESM(require("fs"));
21327
- var path30 = __toESM(require("path"));
21494
+ var fs38 = __toESM(require("fs"));
21495
+ var path31 = __toESM(require("path"));
21328
21496
  init_config();
21329
21497
  init_router();
21330
21498
  init_hub();
21331
21499
  init_worlds();
21332
21500
 
21333
21501
  // src/benchmarks/index.ts
21334
- var fs27 = __toESM(require("fs"));
21335
- var path21 = __toESM(require("path"));
21502
+ var fs28 = __toESM(require("fs"));
21503
+ var path22 = __toESM(require("path"));
21336
21504
  init_worldDir();
21337
21505
  var BENCHMARKS_SKILL = "benchmarks-getting-started";
21338
21506
  var BENCHMARK_KINDS = ["world", "harbor", "verifiers", "image"];
@@ -21374,9 +21542,9 @@ var SHAPE_LABELS = {
21374
21542
  none: "not a world and not a benchmark package"
21375
21543
  };
21376
21544
  function declaredTasks(dir) {
21377
- const file = path21.join(dir, "gateway-env.toml");
21378
- if (!fs27.existsSync(file)) return [];
21379
- const toml = fs27.readFileSync(file, "utf8");
21545
+ const file = path22.join(dir, "gateway-env.toml");
21546
+ if (!fs28.existsSync(file)) return [];
21547
+ const toml = fs28.readFileSync(file, "utf8");
21380
21548
  const ids = [];
21381
21549
  let inTask = false;
21382
21550
  for (const raw of toml.split("\n")) {
@@ -21394,8 +21562,8 @@ function declaredTasks(dir) {
21394
21562
  return ids;
21395
21563
  }
21396
21564
  function firstLine(file) {
21397
- if (!fs27.existsSync(file)) return null;
21398
- const text2 = fs27.readFileSync(file, "utf8").trim();
21565
+ if (!fs28.existsSync(file)) return null;
21566
+ const text2 = fs28.readFileSync(file, "utf8").trim();
21399
21567
  return text2 ? text2.split("\n")[0].trim() : null;
21400
21568
  }
21401
21569
  function importReport(dir, from) {
@@ -21403,12 +21571,12 @@ function importReport(dir, from) {
21403
21571
  const tasks = [];
21404
21572
  if (from === "harbor") {
21405
21573
  for (const taskDir of harborTaskDirs(dir)) {
21406
- const id = path21.basename(taskDir);
21407
- const tests = path21.join(dir, taskDir, "tests");
21408
- const grader = fs27.existsSync(tests) ? fs27.readdirSync(tests).map((f) => `tests/${f}`).join(", ") || "tests/ (empty)" : "no tests/";
21574
+ const id = path22.basename(taskDir);
21575
+ const tests = path22.join(dir, taskDir, "tests");
21576
+ const grader = fs28.existsSync(tests) ? fs28.readdirSync(tests).map((f) => `tests/${f}`).join(", ") || "tests/ (empty)" : "no tests/";
21409
21577
  tasks.push({
21410
21578
  id,
21411
- prompt: firstLine(path21.join(dir, taskDir, "instruction.md")),
21579
+ prompt: firstLine(path22.join(dir, taskDir, "instruction.md")),
21412
21580
  grader,
21413
21581
  expressible: false,
21414
21582
  reason: `${grader} grades a container filesystem after the agent runs; a world task grades world state with SQL verifiers`
@@ -21417,7 +21585,7 @@ function importReport(dir, from) {
21417
21585
  } else {
21418
21586
  const pkg = verifiersPackage(dir);
21419
21587
  if (pkg) {
21420
- const source2 = fs27.readFileSync(path21.join(dir, pkg.init), "utf8");
21588
+ const source2 = fs28.readFileSync(path22.join(dir, pkg.init), "utf8");
21421
21589
  const rewards = [...source2.matchAll(/@vf\.reward[^\n]*\n\s*(?:async\s+)?def\s+(\w+)/g)].map((m) => m[1]);
21422
21590
  const tasksets = [...source2.matchAll(/class\s+(\w+)\s*\(\s*(?:vf|v1|verifiers(?:\.v1)?)?\.?Taskset\s*[,)]/g)].map(
21423
21591
  (m) => m[1]
@@ -21448,9 +21616,9 @@ function importReport(dir, from) {
21448
21616
  // src/benchmarks/container.ts
21449
21617
  var import_node_child_process5 = require("child_process");
21450
21618
  var import_node_crypto15 = require("crypto");
21451
- var fs28 = __toESM(require("fs"));
21619
+ var fs29 = __toESM(require("fs"));
21452
21620
  var os4 = __toESM(require("os"));
21453
- var path22 = __toESM(require("path"));
21621
+ var path23 = __toESM(require("path"));
21454
21622
  var DEFAULT_IMAGE = "python:3.11-slim";
21455
21623
  var REWARD_JSON = "/logs/verifier/reward.json";
21456
21624
  var REWARD_TXT = "/logs/verifier/reward.txt";
@@ -21480,11 +21648,11 @@ timeout_sec = 120.0
21480
21648
  var TEST_SH = '#!/bin/bash\n# The task owns its grading. The only contract the platform reads is the\n# named numeric metrics this script writes to /logs/verifier/reward.json;\n# `reward` is the headline (1.0 = pass), every other key a sub-reward.\nmkdir -p /logs/verifier\n\nfile_exists=0.0\ncontent_ok=0.0\nif [ -f /app/hello.txt ]; then\n file_exists=1.0\n if [ "$(tr -d \'\\n\' < /app/hello.txt)" = "Hello, Gateway!" ]; then\n content_ok=1.0\n fi\nfi\nreward=$content_ok\n\ncat > /logs/verifier/reward.json <<EOF\n{"reward": ${reward}, "file_exists": ${file_exists}, "content_ok": ${content_ok}}\nEOF\necho "reward=${reward} file_exists=${file_exists} content_ok=${content_ok}"\n';
21481
21649
  var SOLVE_SH = "#!/bin/bash\n# The reference solution: what harbor's `oracle` agent runs, and what\n# `gateway benchmarks dry-run` runs before the tests. It must score 1.0.\nset -euo pipefail\nmkdir -p /app\nprintf 'Hello, Gateway!\\n' > /app/hello.txt\n";
21482
21650
  function writeHarborScaffold(dir, opts = {}) {
21483
- const name = opts.name ?? path22.basename(path22.resolve(dir));
21651
+ const name = opts.name ?? path23.basename(path23.resolve(dir));
21484
21652
  const task = opts.task ?? "hello-world";
21485
21653
  const image = opts.image ?? DEFAULT_IMAGE;
21486
21654
  const prompt = opts.prompt ?? HELLO_PROMPT;
21487
- const taskDir = path22.join(dir, "tasks", task);
21655
+ const taskDir = path23.join(dir, "tasks", task);
21488
21656
  const files = {
21489
21657
  "pyproject.toml": `[project]
21490
21658
  name = "${name}"
@@ -21513,16 +21681,16 @@ WORKDIR /app
21513
21681
  [`tasks/${task}/solution/solve.sh`]: SOLVE_SH
21514
21682
  };
21515
21683
  for (const [rel, content] of Object.entries(files)) {
21516
- const target = path22.join(dir, rel);
21517
- fs28.mkdirSync(path22.dirname(target), { recursive: true });
21518
- fs28.writeFileSync(target, content);
21519
- if (rel.endsWith(".sh")) fs28.chmodSync(target, 493);
21684
+ const target = path23.join(dir, rel);
21685
+ fs29.mkdirSync(path23.dirname(target), { recursive: true });
21686
+ fs29.writeFileSync(target, content);
21687
+ if (rel.endsWith(".sh")) fs29.chmodSync(target, 493);
21520
21688
  }
21521
21689
  void taskDir;
21522
21690
  return { task, files: Object.keys(files) };
21523
21691
  }
21524
21692
  function writeVerifiersScaffold(dir, opts = {}) {
21525
- const name = opts.name ?? path22.basename(path22.resolve(dir));
21693
+ const name = opts.name ?? path23.basename(path23.resolve(dir));
21526
21694
  const pkg = name.replace(/-/g, "_").replace(/[^A-Za-z0-9_]/g, "_");
21527
21695
  const task = opts.task ?? "capital_of_france";
21528
21696
  const files = {
@@ -21577,9 +21745,9 @@ Taskset), \`push\`, \`run\`, \`results\`; skill: \`gateway worlds skill benchmar
21577
21745
  `
21578
21746
  };
21579
21747
  for (const [rel, content] of Object.entries(files)) {
21580
- const target = path22.join(dir, rel);
21581
- fs28.mkdirSync(path22.dirname(target), { recursive: true });
21582
- fs28.writeFileSync(target, content);
21748
+ const target = path23.join(dir, rel);
21749
+ fs29.mkdirSync(path23.dirname(target), { recursive: true });
21750
+ fs29.writeFileSync(target, content);
21583
21751
  }
21584
21752
  return { pkg, files: Object.keys(files) };
21585
21753
  }
@@ -21610,7 +21778,7 @@ function readTomlScalars(text2) {
21610
21778
  return out;
21611
21779
  }
21612
21780
  function readText2(file) {
21613
- return fs28.existsSync(file) ? fs28.readFileSync(file, "utf8") : null;
21781
+ return fs29.existsSync(file) ? fs29.readFileSync(file, "utf8") : null;
21614
21782
  }
21615
21783
  function checkTestScript(text2, rel) {
21616
21784
  const problems = [];
@@ -21651,11 +21819,11 @@ function imageSourceReport(taskDir, ref, dockerfile) {
21651
21819
  };
21652
21820
  }
21653
21821
  function validateHarborTask(dir, taskDir) {
21654
- const full = path22.join(dir, taskDir);
21655
- const id = path22.basename(taskDir);
21822
+ const full = path23.join(dir, taskDir);
21823
+ const id = path23.basename(taskDir);
21656
21824
  const problems = [];
21657
21825
  const warnings = [];
21658
- const toml = readText2(path22.join(full, "task.toml"));
21826
+ const toml = readText2(path23.join(full, "task.toml"));
21659
21827
  let ref = null;
21660
21828
  let agent = null;
21661
21829
  let verifier = null;
@@ -21668,11 +21836,11 @@ function validateHarborTask(dir, taskDir) {
21668
21836
  agent = typeof parsed.agent?.timeout_sec === "number" ? parsed.agent.timeout_sec : null;
21669
21837
  verifier = typeof parsed.verifier?.timeout_sec === "number" ? parsed.verifier.timeout_sec : null;
21670
21838
  }
21671
- const dockerfile = readText2(path22.join(full, DOCKERFILE_REL));
21672
- const composeRel = COMPOSE_RELS.find((rel) => fs28.existsSync(path22.join(full, rel))) ?? null;
21673
- const compose = composeRel ? readText2(path22.join(full, composeRel)) : null;
21839
+ const dockerfile = readText2(path23.join(full, DOCKERFILE_REL));
21840
+ const composeRel = COMPOSE_RELS.find((rel) => fs29.existsSync(path23.join(full, rel))) ?? null;
21841
+ const compose = composeRel ? readText2(path23.join(full, composeRel)) : null;
21674
21842
  const secrets = compose === null ? [] : composeRequiredNames(compose);
21675
- const environment = fs28.existsSync(path22.join(full, "environment"));
21843
+ const environment = fs29.existsSync(path23.join(full, "environment"));
21676
21844
  const source2 = ref ? "docker_image" : dockerfile !== null ? "dockerfile" : null;
21677
21845
  if (source2 === null && composeRel === null)
21678
21846
  problems.push(`${taskDir}: no image \u2014 set [environment] docker_image in task.toml or add ${DOCKERFILE_REL}`);
@@ -21682,10 +21850,10 @@ function validateHarborTask(dir, taskDir) {
21682
21850
  problems.push(...sources.problems);
21683
21851
  warnings.push(...sources.warnings);
21684
21852
  if (!environment) warnings.push(`${taskDir}/environment/ missing; harbor expects the directory (a Dockerfile, a compose file, or files to upload)`);
21685
- const instruction = readText2(path22.join(full, "instruction.md"));
21853
+ const instruction = readText2(path23.join(full, "instruction.md"));
21686
21854
  if (instruction === null) problems.push(`${taskDir}/instruction.md missing (what the agent is told)`);
21687
21855
  else if (!instruction.trim()) problems.push(`${taskDir}/instruction.md is empty`);
21688
- const tests = readText2(path22.join(full, "tests", "test.sh"));
21856
+ const tests = readText2(path23.join(full, "tests", "test.sh"));
21689
21857
  if (tests === null) problems.push(`${taskDir}/tests/test.sh missing (the grader; it must write ${REWARD_JSON})`);
21690
21858
  else {
21691
21859
  const checked = checkTestScript(tests, `${taskDir}/tests/test.sh`);
@@ -21693,17 +21861,17 @@ function validateHarborTask(dir, taskDir) {
21693
21861
  warnings.push(...checked.warnings);
21694
21862
  }
21695
21863
  for (const sub of ["tests", "solution", "environment"]) {
21696
- const linked = path22.join(full, sub);
21864
+ const linked = path23.join(full, sub);
21697
21865
  let isLink = false;
21698
21866
  try {
21699
- isLink = fs28.lstatSync(linked).isSymbolicLink();
21867
+ isLink = fs29.lstatSync(linked).isSymbolicLink();
21700
21868
  } catch {
21701
21869
  isLink = false;
21702
21870
  }
21703
21871
  if (isLink)
21704
21872
  problems.push(`${taskDir}/${sub} is a symlink (docker -v follows host symlinks, so whatever it points at would be mounted); make it a real directory`);
21705
21873
  }
21706
- const solution = fs28.existsSync(path22.join(full, "solution", "solve.sh"));
21874
+ const solution = fs29.existsSync(path23.join(full, "solution", "solve.sh"));
21707
21875
  if (!solution) warnings.push(`${taskDir}/solution/solve.sh missing: dry-run and harbor's oracle agent have no reference solution to prove the grader with (the runner does not need it)`);
21708
21876
  return {
21709
21877
  id,
@@ -21726,7 +21894,7 @@ function validateHarbor(dir) {
21726
21894
  const warnings = [];
21727
21895
  const tasks = harborTaskDirs(dir).map((taskDir) => validateHarborTask(dir, taskDir));
21728
21896
  if (tasks.length === 0) problems.push(`${dir} holds no harbor task (tasks/<name>/task.toml)`);
21729
- if (!fs28.existsSync(path22.join(dir, "pyproject.toml")))
21897
+ if (!fs29.existsSync(path23.join(dir, "pyproject.toml")))
21730
21898
  warnings.push("no pyproject.toml: the slug is the directory name and the version is unrecorded (`benchmarks init --kind harbor` writes one)");
21731
21899
  const detectedKind = detectEnvKind(dir);
21732
21900
  if (detectedKind !== "harbor")
@@ -21743,8 +21911,8 @@ function validateVerifiers(dir) {
21743
21911
  let info;
21744
21912
  if (!pkg) problems.push(`${dir} is not a verifiers package (pyproject.toml plus a Python package with __init__.py)`);
21745
21913
  else {
21746
- const init2 = path22.join(dir, pkg.init);
21747
- const source2 = fs28.readFileSync(init2, "utf8");
21914
+ const init2 = path23.join(dir, pkg.init);
21915
+ const source2 = fs29.readFileSync(init2, "utf8");
21748
21916
  const read = inspectVerifiersSource(init2, source2);
21749
21917
  if (read.syntaxError !== null) problems.push(`${pkg.init} does not parse: ${read.syntaxError}`);
21750
21918
  if (read.fallback) warnings.push("python3 is not on PATH, so the package was read by pattern, not parsed: a SyntaxError would surface at dry-run");
@@ -21756,7 +21924,7 @@ function validateVerifiers(dir) {
21756
21924
  seen.add(name);
21757
21925
  }
21758
21926
  const taskset = read.taskset;
21759
- const pyproject = fs28.readFileSync(path22.join(dir, "pyproject.toml"), "utf8");
21927
+ const pyproject = fs29.readFileSync(path23.join(dir, "pyproject.toml"), "utf8");
21760
21928
  const v1 = /verifiers\s*(?:\[[^\]]*\])?\s*(?:>=|~=|==|>)\s*(?:0\.(?:[2-9]\d*|[1-9]\d+)|[1-9]\d*)/.test(pyproject) || /verifiers\.v1|from\s+verifiers\s+import\s+v1/.test(source2);
21761
21929
  info = { name: pkg.name, init: pkg.init, taskset, rewards, v1 };
21762
21930
  if (!v1) warnings.push("pyproject.toml pins no `verifiers>=0.2`: the runner will run it as a v0 (legacy `load_environment`) package");
@@ -21821,9 +21989,9 @@ function inspectVerifiersSource(init2, source2) {
21821
21989
  var TMP_PLACEHOLDER = "<tmp>";
21822
21990
  var LOGS_PLACEHOLDER = `${TMP_PLACEHOLDER}/logs`;
21823
21991
  function treeSlug(dir) {
21824
- const pyproject = readText2(path22.join(dir, "pyproject.toml"));
21992
+ const pyproject = readText2(path23.join(dir, "pyproject.toml"));
21825
21993
  const name = pyproject === null ? void 0 : readTomlScalars(pyproject).project?.name;
21826
- return typeof name === "string" && name ? name : path22.basename(path22.resolve(dir));
21994
+ return typeof name === "string" && name ? name : path23.basename(path23.resolve(dir));
21827
21995
  }
21828
21996
  var DOCKER_NAME_PREFIX = "gateway-benchmarks-dryrun";
21829
21997
  var DOCKER_SAFE = /^[A-Za-z0-9 ._-]*$/;
@@ -21850,17 +22018,17 @@ ${volumes}
21850
22018
  }
21851
22019
  function harborRunPlan(dir, taskId, scratch = TMP_PLACEHOLDER) {
21852
22020
  const dirs = harborTaskDirs(dir);
21853
- const taskDir = taskId ? dirs.find((d) => path22.basename(d) === taskId) : dirs[0];
22021
+ const taskDir = taskId ? dirs.find((d) => path23.basename(d) === taskId) : dirs[0];
21854
22022
  if (!taskDir)
21855
22023
  throw new Error(
21856
- taskId ? `no task ${taskId} in ${dir}; tasks: ${dirs.map((d) => path22.basename(d)).join(", ") || "none"}` : `${dir} holds no harbor task`
22024
+ taskId ? `no task ${taskId} in ${dir}; tasks: ${dirs.map((d) => path23.basename(d)).join(", ") || "none"}` : `${dir} holds no harbor task`
21857
22025
  );
21858
22026
  const validation = validateHarborTask(dir, taskDir);
21859
- const full = path22.resolve(dir, taskDir);
21860
- const tag = dockerImageName(path22.basename(path22.resolve(dir)), validation.id);
22027
+ const full = path23.resolve(dir, taskDir);
22028
+ const tag = dockerImageName(path23.basename(path23.resolve(dir)), validation.id);
21861
22029
  const logsDir = `${scratch}/logs`;
21862
- const mounts = [{ host: path22.join(full, "tests"), container: "/tests", mode: "ro" }];
21863
- if (validation.files.solution) mounts.push({ host: path22.join(full, "solution"), container: "/solution", mode: "ro" });
22030
+ const mounts = [{ host: path23.join(full, "tests"), container: "/tests", mode: "ro" }];
22031
+ if (validation.files.solution) mounts.push({ host: path23.join(full, "solution"), container: "/solution", mode: "ro" });
21864
22032
  mounts.push({ host: logsDir, container: "/logs", mode: "rw" });
21865
22033
  const steps = [];
21866
22034
  if (validation.files.solution)
@@ -21872,8 +22040,8 @@ function harborRunPlan(dir, taskId, scratch = TMP_PLACEHOLDER) {
21872
22040
  const script = `mkdir -p /logs/verifier && ${steps.filter((s) => !s.command.startsWith("(")).map((s) => s.command).join(" && ")}`;
21873
22041
  const commands = { run: [] };
21874
22042
  if (validation.image.source === "dockerfile") {
21875
- const dockerfile = path22.resolve(dir, validation.image.dockerfile);
21876
- commands.build = [bin, "build", "-t", tag, "-f", dockerfile, path22.dirname(dockerfile)];
22043
+ const dockerfile = path23.resolve(dir, validation.image.dockerfile);
22044
+ commands.build = [bin, "build", "-t", tag, "-f", dockerfile, path23.dirname(dockerfile)];
21877
22045
  }
21878
22046
  if (validation.image.source === "docker_image") commands.pull = [bin, "pull", "--quiet", validation.image.ref];
21879
22047
  let compose = null;
@@ -21883,7 +22051,7 @@ function harborRunPlan(dir, taskId, scratch = TMP_PLACEHOLDER) {
21883
22051
  for (const mount of mounts) commands.run.push("-v", `${mount.host}:${mount.container}${mount.mode === "ro" ? ":ro" : ""}`);
21884
22052
  commands.run.push(uses ?? "<no image>", "bash", "-lc", script);
21885
22053
  } else {
21886
- const file = path22.resolve(dir, validation.image.compose);
22054
+ const file = path23.resolve(dir, validation.image.compose);
21887
22055
  const base = `${scratch}/docker-compose.base.yaml`;
21888
22056
  const project = tag;
21889
22057
  compose = { file, base, project, secrets: validation.secrets };
@@ -21891,7 +22059,7 @@ function harborRunPlan(dir, taskId, scratch = TMP_PLACEHOLDER) {
21891
22059
  commands.run = [...composeArgs, "run", "--rm", "main", "bash", "-lc", script];
21892
22060
  commands.down = [...composeArgs, "down", "--volumes", "--remove-orphans"];
21893
22061
  env.MAIN_IMAGE_NAME = uses ?? "";
21894
- env.CONTEXT_DIR = path22.join(full, "environment");
22062
+ env.CONTEXT_DIR = path23.join(full, "environment");
21895
22063
  if (validation.image.ref) env.PREBUILT_IMAGE_NAME = validation.image.ref;
21896
22064
  }
21897
22065
  return {
@@ -21907,7 +22075,7 @@ function harborRunPlan(dir, taskId, scratch = TMP_PLACEHOLDER) {
21907
22075
  commands,
21908
22076
  reward: { file: REWARD_JSON, fallback: REWARD_TXT },
21909
22077
  timeouts: { agent: validation.timeouts.agent ?? 300, verifier: validation.timeouts.verifier ?? 120 },
21910
- runner: `harbor run -p ${path22.join(dir, "tasks")} -a mini-swe-agent -m <provider/model> -e docker -o <jobs> -k <rollouts> -n <concurrency> -y -q`,
22078
+ runner: `harbor run -p ${path23.join(dir, "tasks")} -a mini-swe-agent -m <provider/model> -e docker -o <jobs> -k <rollouts> -n <concurrency> -y -q`,
21911
22079
  validation
21912
22080
  };
21913
22081
  }
@@ -21944,11 +22112,11 @@ function dryRunHarbor(dir, plan) {
21944
22112
  if (!image) return { executed: false, reason: "the task names no image", commands };
21945
22113
  const secrets = plan.compose ? missingComposeSecrets(dir, plan.compose.secrets) : null;
21946
22114
  if (secrets) return { executed: false, reason: secrets, commands };
21947
- const scratch = fs28.mkdtempSync(path22.join(os4.tmpdir(), "gateway-benchmarks-dryrun-"));
21948
- const logs = path22.join(scratch, "logs");
21949
- fs28.mkdirSync(path22.join(logs, "verifier"), { recursive: true });
22115
+ const scratch = fs29.mkdtempSync(path23.join(os4.tmpdir(), "gateway-benchmarks-dryrun-"));
22116
+ const logs = path23.join(scratch, "logs");
22117
+ fs29.mkdirSync(path23.join(logs, "verifier"), { recursive: true });
21950
22118
  const place = (a) => a.split(TMP_PLACEHOLDER).join(scratch);
21951
- if (plan.compose) fs28.writeFileSync(place(plan.compose.base), composeBase(image, plan.mounts.map((m) => ({ ...m, host: place(m.host) }))));
22119
+ if (plan.compose) fs29.writeFileSync(place(plan.compose.base), composeBase(image, plan.mounts.map((m) => ({ ...m, host: place(m.host) }))));
21952
22120
  const outputs = [];
21953
22121
  const spawnArgv = (argv, timeoutMs3) => {
21954
22122
  commands.push(shellLine(argv));
@@ -21964,7 +22132,7 @@ function dryRunHarbor(dir, plan) {
21964
22132
  return { executed: true, docker: docker.version, image, exitCode: pullStatus, output: outputs.join("\n"), commands, reason: notGraded("docker pull", pullStatus) };
21965
22133
  const exitCode = spawnArgv(plan.commands.run.map(place), (plan.timeouts.agent + plan.timeouts.verifier) * 1e3);
21966
22134
  if (plan.commands.down) spawnArgv(plan.commands.down.map(place), 5 * 6e4);
21967
- const rewards = readReward(path22.join(logs, "verifier"));
22135
+ const rewards = readReward(path23.join(logs, "verifier"));
21968
22136
  return {
21969
22137
  executed: true,
21970
22138
  docker: docker.version,
@@ -21978,7 +22146,7 @@ function dryRunHarbor(dir, plan) {
21978
22146
  };
21979
22147
  }
21980
22148
  function readReward(verifierDir) {
21981
- const json = readText2(path22.join(verifierDir, "reward.json"));
22149
+ const json = readText2(path23.join(verifierDir, "reward.json"));
21982
22150
  if (json !== null) {
21983
22151
  try {
21984
22152
  const parsed = JSON.parse(json);
@@ -21989,7 +22157,7 @@ function readReward(verifierDir) {
21989
22157
  return null;
21990
22158
  }
21991
22159
  }
21992
- const txt = readText2(path22.join(verifierDir, "reward.txt"));
22160
+ const txt = readText2(path23.join(verifierDir, "reward.txt"));
21993
22161
  if (txt !== null && /^-?\d+(\.\d+)?\s*$/.test(txt)) return { reward: Number(txt.trim()) };
21994
22162
  return null;
21995
22163
  }
@@ -22017,9 +22185,9 @@ function verifiersDiscoverScript(bundle, pkg) {
22017
22185
  }
22018
22186
  function verifiersRunPlan(dir, validation, python = null) {
22019
22187
  const pkg = validation.package;
22020
- const name = pkg?.name ?? path22.basename(path22.resolve(dir));
22188
+ const name = pkg?.name ?? path23.basename(path23.resolve(dir));
22021
22189
  const bin = dockerBin();
22022
- const tree = path22.resolve(dir);
22190
+ const tree = path23.resolve(dir);
22023
22191
  return {
22024
22192
  kind: "verifiers",
22025
22193
  package: name,
@@ -22090,7 +22258,7 @@ function dryRunVerifiers(dir, plan, opts) {
22090
22258
  }
22091
22259
 
22092
22260
  // src/cli/platform/benchmarksDryRun.ts
22093
- var fs29 = __toESM(require("fs"));
22261
+ var fs30 = __toESM(require("fs"));
22094
22262
  init_config();
22095
22263
  init_router();
22096
22264
  init_hub();
@@ -22213,7 +22381,7 @@ var HostedDryRunTarget = class _HostedDryRunTarget {
22213
22381
  dir;
22214
22382
  /** `slug`, `slug@ref`, or a dir that tracks a slug (`.gateway/.env-metadata.json`, the same file `push` writes). */
22215
22383
  static async resolve(ref, opts, ctx, pushDir) {
22216
- if (fs29.existsSync(ref) && fs29.statSync(ref).isDirectory())
22384
+ if (fs30.existsSync(ref) && fs30.statSync(ref).isDirectory())
22217
22385
  return _HostedDryRunTarget.fromDir(ref, opts, ctx, pushDir);
22218
22386
  const at = ref.indexOf("@");
22219
22387
  if (at === -1)
@@ -22670,8 +22838,8 @@ function printProvider(ctx, providers, only) {
22670
22838
  init_client();
22671
22839
 
22672
22840
  // src/cli/runtime/scaffoldVerifiers.ts
22673
- var fs30 = __toESM(require("fs"));
22674
- var path23 = __toESM(require("path"));
22841
+ var fs31 = __toESM(require("fs"));
22842
+ var path24 = __toESM(require("path"));
22675
22843
  init_router();
22676
22844
  var SCAFFOLD_VERIFIER = /^-- Scores 1\.0 once the world holds any (\S+) row; edit for real tasks\.\n/;
22677
22845
  function scaffoldVerifier(entity) {
@@ -22682,15 +22850,15 @@ SELECT CASE WHEN COUNT(*) > 0 THEN 1.0 ELSE 0.0 END FROM "${entity}";
22682
22850
  `;
22683
22851
  }
22684
22852
  function scaffoldVerifierEntity(file) {
22685
- if (!fs30.existsSync(file)) return void 0;
22686
- const text2 = fs30.readFileSync(file, "utf8");
22853
+ if (!fs31.existsSync(file)) return void 0;
22854
+ const text2 = fs31.readFileSync(file, "utf8");
22687
22855
  const entity = SCAFFOLD_VERIFIER.exec(text2)?.[1];
22688
22856
  return entity !== void 0 && text2 === scaffoldVerifier(entity) ? entity : void 0;
22689
22857
  }
22690
22858
  function verifierNames(dir) {
22691
- const folder = path23.join(dir, "verifiers");
22692
- if (!fs30.existsSync(folder)) return void 0;
22693
- return fs30.readdirSync(folder).filter((f) => f.endsWith(".sql")).map((f) => f.slice(0, -4)).sort();
22859
+ const folder = path24.join(dir, "verifiers");
22860
+ if (!fs31.existsSync(folder)) return void 0;
22861
+ return fs31.readdirSync(folder).filter((f) => f.endsWith(".sql")).map((f) => f.slice(0, -4)).sort();
22694
22862
  }
22695
22863
  function verifierSql(name, entity, where) {
22696
22864
  if (!/^[A-Za-z_][A-Za-z0-9_-]*$/.test(name)) throw new CliError(`Verifier names match [A-Za-z_][A-Za-z0-9_-]*, got ${JSON.stringify(name)}`);
@@ -22730,18 +22898,18 @@ function whereClauseDefect(clause) {
22730
22898
  }
22731
22899
  function addVerifier(dir, name, entity, where) {
22732
22900
  const sql = verifierSql(name, entity, where);
22733
- const file = path23.join(dir, "verifiers", `${name}.sql`);
22734
- if (fs30.existsSync(file))
22901
+ const file = path24.join(dir, "verifiers", `${name}.sql`);
22902
+ if (fs31.existsSync(file))
22735
22903
  throw new CliError(`verifiers/${name}.sql already exists (have: ${(verifierNames(dir) ?? []).join(", ")}); edit it, or pick another name`);
22736
- fs30.mkdirSync(path23.dirname(file), { recursive: true });
22737
- fs30.writeFileSync(file, sql);
22904
+ fs31.mkdirSync(path24.dirname(file), { recursive: true });
22905
+ fs31.writeFileSync(file, sql);
22738
22906
  return file;
22739
22907
  }
22740
22908
  function repointScaffoldVerifier(dir, entity, declared) {
22741
- const file = path23.join(dir, "verifiers", "state_present.sql");
22909
+ const file = path24.join(dir, "verifiers", "state_present.sql");
22742
22910
  const named2 = scaffoldVerifierEntity(file);
22743
22911
  if (named2 === void 0 || declared.includes(named2)) return null;
22744
- fs30.writeFileSync(file, scaffoldVerifier(entity));
22912
+ fs31.writeFileSync(file, scaffoldVerifier(entity));
22745
22913
  return file;
22746
22914
  }
22747
22915
 
@@ -22750,8 +22918,8 @@ init_local();
22750
22918
  init_shared();
22751
22919
 
22752
22920
  // src/cli/platform/worlds.ts
22753
- var fs36 = __toESM(require("fs"));
22754
- var path29 = __toESM(require("path"));
22921
+ var fs37 = __toESM(require("fs"));
22922
+ var path30 = __toESM(require("path"));
22755
22923
  init_config();
22756
22924
  init_router();
22757
22925
  init_describe();
@@ -22815,10 +22983,10 @@ var isDirectory = (p) => import_node_fs.default.existsSync(p) && import_node_fs.
22815
22983
  // src/cli/platform/worlds.ts
22816
22984
  var WORLDS3 = "/api/public/worlds";
22817
22985
  function collectFiles(directory) {
22818
- if (!fs36.existsSync(directory) || !fs36.statSync(directory).isDirectory())
22986
+ if (!fs37.existsSync(directory) || !fs37.statSync(directory).isDirectory())
22819
22987
  throw new CliError(`${directory}: not a directory`, 1);
22820
22988
  return walk2(directory).map((relative6) => {
22821
- const bytes = fs36.readFileSync(path29.join(directory, relative6));
22989
+ const bytes = fs37.readFileSync(path30.join(directory, relative6));
22822
22990
  const text2 = bytes.toString("utf8");
22823
22991
  return Buffer.from(text2, "utf8").equals(bytes) && !text2.includes("\uFFFD") ? { path: relative6, content: text2 } : {
22824
22992
  path: relative6,
@@ -22836,7 +23004,7 @@ async function describeLocalDirectory(dir, hostFlag) {
22836
23004
  const counts = await showLocalWorldData2(dir, void 0, creds);
22837
23005
  return describedLocally2(withRowCounts2(description, counts.entity_counts ?? {}), dir);
22838
23006
  }
22839
- var isDir = (candidate) => fs36.existsSync(candidate) && fs36.statSync(candidate).isDirectory();
23007
+ var isDir = (candidate) => fs37.existsSync(candidate) && fs37.statSync(candidate).isDirectory();
22840
23008
  function worldTreeFiles(from) {
22841
23009
  if (classifyTree(from).shape !== "none") return collectFiles(from);
22842
23010
  const files = collectFiles(from);
@@ -22944,7 +23112,7 @@ async function createOne(creds, body) {
22944
23112
  return api(creds, "POST", WORLDS3, body, { timeoutMs: 6e5 });
22945
23113
  }
22946
23114
  async function runBatch(file, args, ctx) {
22947
- const text2 = file === "-" ? fs36.readFileSync(0, "utf8") : fs36.readFileSync(file, "utf8");
23115
+ const text2 = file === "-" ? fs37.readFileSync(0, "utf8") : fs37.readFileSync(file, "utf8");
22948
23116
  const requests = text2.split("\n").map((line) => line.trim()).filter(Boolean).map(batchLine);
22949
23117
  if (requests.length === 0)
22950
23118
  throw new CliError("batch file holds no worlds", 1);
@@ -23141,21 +23309,21 @@ function registerWorldCommands(root) {
23141
23309
  const options = worldsOptions(credentials(args));
23142
23310
  const reports = slug ? [await migrateWorld(slug, { apply, force: arg.bool(args, "force") || void 0 }, options)] : (await migrateProjectWorlds({ apply }, options)).worlds;
23143
23311
  if (arg.bool(args, "json")) printJson(ctx, slug ? reports[0] : { worlds: reports, applied: apply });
23144
- else for (const report of reports) ctx.stdout(migrationLine(report, apply));
23312
+ else for (const report2 of reports) ctx.stdout(migrationLine(report2, apply));
23145
23313
  if (!apply && reports.some((r) => !r.refusal && !r.unchanged))
23146
23314
  ctx.stderr("dry run; add --apply to commit");
23147
23315
  return reports.some((r) => r.refusal) ? 2 : 0;
23148
23316
  }
23149
23317
  });
23150
23318
  }
23151
- function migrationLine(report, apply) {
23152
- if (report.refusal)
23153
- return `${report.slug}: ${report.shape} -> refused (${report.refusal.code}): ${report.refusal.message}`;
23154
- if (report.unchanged) return `${report.slug}: schema world already; nothing to migrate`;
23155
- const head = `${report.slug}: ${report.shape} -> schema (${report.files} files)`;
23156
- if (report.applied && report.version)
23157
- return `${head} migrated as ${report.version.contentHash.slice(0, 12)}`;
23158
- const plan = report.actions.map((a) => `
23319
+ function migrationLine(report2, apply) {
23320
+ if (report2.refusal)
23321
+ return `${report2.slug}: ${report2.shape} -> refused (${report2.refusal.code}): ${report2.refusal.message}`;
23322
+ if (report2.unchanged) return `${report2.slug}: schema world already; nothing to migrate`;
23323
+ const head = `${report2.slug}: ${report2.shape} -> schema (${report2.files} files)`;
23324
+ if (report2.applied && report2.version)
23325
+ return `${head} migrated as ${report2.version.contentHash.slice(0, 12)}`;
23326
+ const plan = report2.actions.map((a) => `
23159
23327
  - ${a}`).join("");
23160
23328
  return apply ? `${head} unchanged (identical tree already the head)${plan}` : `${head} would:${plan}`;
23161
23329
  }
@@ -23211,7 +23379,7 @@ function refuseKind(dir, classified, wanted, command2) {
23211
23379
  );
23212
23380
  }
23213
23381
  function resolveKind(dir, args, command2) {
23214
- if (!fs37.existsSync(dir) || !fs37.statSync(dir).isDirectory()) throw new CliError(`Not a directory: ${dir}`, 1);
23382
+ if (!fs38.existsSync(dir) || !fs38.statSync(dir).isDirectory()) throw new CliError(`Not a directory: ${dir}`, 1);
23215
23383
  const classified = classifyTree(dir);
23216
23384
  const actual = kindOfTree(classified);
23217
23385
  const wanted = arg.str(args, "kind");
@@ -23221,7 +23389,7 @@ function resolveKind(dir, args, command2) {
23221
23389
  }
23222
23390
  function firstEntity(dir) {
23223
23391
  try {
23224
- const world = JSON.parse(fs37.readFileSync(path30.join(dir, "schema", "world.json"), "utf8"));
23392
+ const world = JSON.parse(fs38.readFileSync(path31.join(dir, "schema", "world.json"), "utf8"));
23225
23393
  const entities = world["x-gateway"]?.entities ?? world.entities;
23226
23394
  if (Array.isArray(entities)) return entities[0]?.name ?? null;
23227
23395
  if (entities && typeof entities === "object") return Object.keys(entities)[0] ?? null;
@@ -23230,30 +23398,30 @@ function firstEntity(dir) {
23230
23398
  return null;
23231
23399
  }
23232
23400
  function readConfig2(dir) {
23233
- const file = path30.join(dir, BENCHMARK_CONFIG2);
23234
- if (!fs37.existsSync(file)) return {};
23401
+ const file = path31.join(dir, BENCHMARK_CONFIG2);
23402
+ if (!fs38.existsSync(file)) return {};
23235
23403
  try {
23236
- return JSON.parse(fs37.readFileSync(file, "utf8"));
23404
+ return JSON.parse(fs38.readFileSync(file, "utf8"));
23237
23405
  } catch {
23238
23406
  throw new CliError(`${file} is not JSON`, 1);
23239
23407
  }
23240
23408
  }
23241
23409
  function writeConfig2(dir, config) {
23242
- fs37.writeFileSync(path30.join(dir, BENCHMARK_CONFIG2), JSON.stringify({ ...config, note: "Defaults for `gateway benchmarks run` when --model / --rollouts are not given." }, null, 2) + "\n");
23410
+ fs38.writeFileSync(path31.join(dir, BENCHMARK_CONFIG2), JSON.stringify({ ...config, note: "Defaults for `gateway benchmarks run` when --model / --rollouts are not given." }, null, 2) + "\n");
23243
23411
  }
23244
- function printValidation(ctx, report) {
23245
- ctx.stdout(`${report.dir}: ${report.kind} benchmark \u2014 runner reads it as ${report.detectedKind} \u2014 ${report.ok ? "ok" : `${report.problems.length + report.tasks.reduce((n, t) => n + t.problems.length, 0)} problem(s)`}`);
23246
- for (const task of report.tasks) {
23412
+ function printValidation(ctx, report2) {
23413
+ ctx.stdout(`${report2.dir}: ${report2.kind} benchmark \u2014 runner reads it as ${report2.detectedKind} \u2014 ${report2.ok ? "ok" : `${report2.problems.length + report2.tasks.reduce((n, t) => n + t.problems.length, 0)} problem(s)`}`);
23414
+ for (const task of report2.tasks) {
23247
23415
  const image = imageLabel(task.image);
23248
23416
  const secrets = task.secrets.length ? `; secrets ${task.secrets.join(", ")}` : "";
23249
23417
  ctx.stdout(` ${task.problems.length ? "FAIL" : "ok "} ${task.id}: image ${image}${secrets}; instruction ${task.files.instruction ? "yes" : "MISSING"}; tests/test.sh ${task.files.tests ? "yes" : "MISSING"}; solution ${task.files.solution ? "yes" : "none"}`);
23250
23418
  for (const problem of task.problems) ctx.stdout(` problem: ${problem}`);
23251
23419
  for (const warning of task.warnings) ctx.stdout(` note: ${warning}`);
23252
23420
  }
23253
- if (report.package)
23254
- ctx.stdout(` package ${report.package.name} (${report.package.init}): ${report.package.v1 ? "verifiers v1" : "verifiers v0"}; Taskset ${report.package.taskset ?? "NONE"}; rewards ${report.package.rewards.join(", ") || "none by name"}`);
23255
- for (const problem of report.problems) ctx.stdout(` problem: ${problem}`);
23256
- for (const warning of report.warnings) ctx.stdout(` note: ${warning}`);
23421
+ if (report2.package)
23422
+ ctx.stdout(` package ${report2.package.name} (${report2.package.init}): ${report2.package.v1 ? "verifiers v1" : "verifiers v0"}; Taskset ${report2.package.taskset ?? "NONE"}; rewards ${report2.package.rewards.join(", ") || "none by name"}`);
23423
+ for (const problem of report2.problems) ctx.stdout(` problem: ${problem}`);
23424
+ for (const warning of report2.warnings) ctx.stdout(` note: ${warning}`);
23257
23425
  }
23258
23426
  function taskSummary(ids, shown2 = 5) {
23259
23427
  const head = ids.slice(0, shown2).join(", ");
@@ -23322,7 +23490,7 @@ async function dryRunWorld(dir, task, opts = {}) {
23322
23490
  };
23323
23491
  if (!local)
23324
23492
  return { ...base, note: `not executed: ${opts.plan ? "--plan" : localRuntimeReason() || "no bundled runtime"} \u2014 the steps above are what would run. ${base.note}` };
23325
- const payload = await localBridge({ command: "dry-run", world: path30.resolve(dir), task }, local);
23493
+ const payload = await localBridge({ command: "dry-run", world: path31.resolve(dir), task }, local);
23326
23494
  const detail = detailFrom(payload);
23327
23495
  if (detail) throw new BridgeRejected(detail);
23328
23496
  const answer = payload;
@@ -23419,11 +23587,11 @@ proposals: \`gateway bench\`. Walkthrough: \`gateway worlds skill ${BENCHMARKS_S
23419
23587
  "benchmarks init --kind image is not shipped: the benchmark runner has no hub engine for a bring-your-own image \u2014 its generic engine (deploy/benchmark-runner/engines/generic_runner.py) runs registry entries from benchmarks.json, not pushed versions, and `bench push --image` only records the ref on a world's server image. Shipping it needs an `image` kind in detect_env_kind, a runner branch that runs the version's imageRef through the generic engine and harvests a reward, and the harvest itself. Package the benchmark as a harbor task instead (`--kind harbor`: your image in [environment] docker_image, your grader in tests/test.sh).",
23420
23588
  2
23421
23589
  );
23422
- if (fs37.existsSync(dir) && fs37.readdirSync(dir).length > 0)
23590
+ if (fs38.existsSync(dir) && fs38.readdirSync(dir).length > 0)
23423
23591
  throw new CliError(`${dir} is not empty; init writes a fresh ${kind} tree`, 1);
23424
23592
  const models = arg.list(args, "model");
23425
23593
  const rollouts = arg.int(args, "rollouts") ?? 1;
23426
- const slug = path30.basename(path30.resolve(dir));
23594
+ const slug = path31.basename(path31.resolve(dir));
23427
23595
  if (kind === "harbor") {
23428
23596
  const scaffold = writeHarborScaffold(dir, {
23429
23597
  name: arg.str(args, "name"),
@@ -23473,8 +23641,8 @@ proposals: \`gateway bench\`. Walkthrough: \`gateway worlds skill ${BENCHMARKS_S
23473
23641
  if (verifiers.length === 0) {
23474
23642
  const entity = firstEntity(dir);
23475
23643
  if (!entity) throw new CliError(`${dir}: schema/world.json declares no entity to write a verifier for`, 1);
23476
- fs37.mkdirSync(path30.join(dir, "verifiers"), { recursive: true });
23477
- fs37.writeFileSync(path30.join(dir, "verifiers", "state_present.sql"), scaffoldVerifier(entity));
23644
+ fs38.mkdirSync(path31.join(dir, "verifiers"), { recursive: true });
23645
+ fs38.writeFileSync(path31.join(dir, "verifiers", "state_present.sql"), scaffoldVerifier(entity));
23478
23646
  verifiers = ["state_present"];
23479
23647
  }
23480
23648
  const taskId = arg.str(args, "task") ?? "first_task";
@@ -23510,8 +23678,8 @@ proposals: \`gateway bench\`. Walkthrough: \`gateway worlds skill ${BENCHMARKS_S
23510
23678
  const checked = await captureSub(root, ["worlds", "schema", "check", dir, ...host ? ["--host", host] : []], ctx);
23511
23679
  ctx.stdout(checked.out);
23512
23680
  if (checked.code !== 0) return checked.code;
23513
- const report2 = safeJson2(checked.out);
23514
- const tasks = Array.isArray(report2.tasks) ? report2.tasks : [];
23681
+ const report3 = safeJson2(checked.out);
23682
+ const tasks = Array.isArray(report3.tasks) ? report3.tasks : [];
23515
23683
  if (tasks.length === 0) {
23516
23684
  ctx.stderr(`${dir} declares no [[tasks]]; a benchmark needs at least one: gateway worlds schema task add ${dir} <id> --prompt "..." --verifier <name>`);
23517
23685
  return 2;
@@ -23519,11 +23687,11 @@ proposals: \`gateway bench\`. Walkthrough: \`gateway worlds skill ${BENCHMARKS_S
23519
23687
  ctx.stderr(`benchmark ok (world): ${tasks.length} task(s): ${tasks.map((t) => t.id ?? "?").join(", ")}`);
23520
23688
  return 0;
23521
23689
  }
23522
- const report = kind === "harbor" ? validateHarbor(dir) : validateVerifiers(dir);
23523
- if (arg.bool(args, "json")) printJson(ctx, report);
23524
- else printValidation(ctx, report);
23525
- if (!report.ok) return 2;
23526
- ctx.stderr(`benchmark ok (${kind}): ${kind === "harbor" ? taskSummary(report.tasks.map((t) => t.id)) : `package ${report.package?.name}`}; next: gateway benchmarks dry-run ${dir}`);
23690
+ const report2 = kind === "harbor" ? validateHarbor(dir) : validateVerifiers(dir);
23691
+ if (arg.bool(args, "json")) printJson(ctx, report2);
23692
+ else printValidation(ctx, report2);
23693
+ if (!report2.ok) return 2;
23694
+ ctx.stderr(`benchmark ok (${kind}): ${kind === "harbor" ? taskSummary(report2.tasks.map((t) => t.id)) : `package ${report2.package?.name}`}; next: gateway benchmarks dry-run ${dir}`);
23527
23695
  return 0;
23528
23696
  };
23529
23697
  benchmarks.command({
@@ -23642,12 +23810,12 @@ proposals: \`gateway bench\`. Walkthrough: \`gateway worlds skill ${BENCHMARKS_S
23642
23810
  const force = arg.bool(args, "force");
23643
23811
  const message = arg.str(args, "message");
23644
23812
  const name = arg.str(args, "name");
23645
- let report = null;
23813
+ let report2 = null;
23646
23814
  if (kind !== "world") {
23647
- report = kind === "harbor" ? validateHarbor(dir) : validateVerifiers(dir);
23648
- if (!report.ok)
23815
+ report2 = kind === "harbor" ? validateHarbor(dir) : validateVerifiers(dir);
23816
+ if (!report2.ok)
23649
23817
  throw new CliError(
23650
- `benchmarks push: ${dir} does not validate (${[...report.problems, ...report.tasks.flatMap((t) => t.problems)].slice(0, 3).join("; ")}); run \`gateway benchmarks validate ${dir}\``,
23818
+ `benchmarks push: ${dir} does not validate (${[...report2.problems, ...report2.tasks.flatMap((t) => t.problems)].slice(0, 3).join("; ")}); run \`gateway benchmarks validate ${dir}\``,
23651
23819
  2
23652
23820
  );
23653
23821
  }
@@ -23661,7 +23829,7 @@ proposals: \`gateway bench\`. Walkthrough: \`gateway worlds skill ${BENCHMARKS_S
23661
23829
  const existing = await existingSlug(creds, slug);
23662
23830
  const incoming = kind === "world" ? "world" : "container";
23663
23831
  if (existing?.substrate && existing.substrate !== incoming) refuseSlug(slug, existing, classified, incoming);
23664
- const describe3 = kind === "harbor" ? `${report.tasks.length} task(s)` : kind === "verifiers" ? `package ${report.package?.name}` : `${tasks.length} task(s)`;
23832
+ const describe3 = kind === "harbor" ? `${report2.tasks.length} task(s)` : kind === "verifiers" ? `package ${report2.package?.name}` : `${tasks.length} task(s)`;
23665
23833
  if (kind !== "world" || existing?.substrate === "world") {
23666
23834
  const pushed = await push(dir, { slug, name, message, force, options: worldsOptions(creds) }).catch((err) => {
23667
23835
  if (!branchMoved(err)) throw err;
@@ -23729,7 +23897,7 @@ before anything is sent); dispatch again for more. Never set max_tokens on the m
23729
23897
  const dirFlag = arg.str(args, "dir");
23730
23898
  const config = dirFlag ? readConfig2(dirFlag) : {};
23731
23899
  if (dirFlag) {
23732
- const owner = config.slug ?? path30.basename(path30.resolve(dirFlag));
23900
+ const owner = config.slug ?? path31.basename(path31.resolve(dirFlag));
23733
23901
  if (owner !== slug)
23734
23902
  throw new CliError(`benchmarks run: --dir ${dirFlag} is the benchmark \`${owner}\` (its benchmark.json), not \`${slug}\`; pass that benchmark's --dir, or --model and -k explicitly`, 2);
23735
23903
  }
@@ -23763,17 +23931,17 @@ before anything is sent); dispatch again for more. Never set max_tokens on the m
23763
23931
  const dir = args.positionals[0];
23764
23932
  const from = arg.str(args, "from");
23765
23933
  if (from !== "harbor" && from !== "verifiers") throw new CliError("benchmarks import needs --from harbor|verifiers");
23766
- if (!fs37.existsSync(dir) || !fs37.statSync(dir).isDirectory()) throw new CliError(`Not a directory: ${dir}`, 1);
23767
- const report = importReport(dir, from);
23768
- if (arg.bool(args, "json")) printJson(ctx, report);
23934
+ if (!fs38.existsSync(dir) || !fs38.statSync(dir).isDirectory()) throw new CliError(`Not a directory: ${dir}`, 1);
23935
+ const report2 = importReport(dir, from);
23936
+ if (arg.bool(args, "json")) printJson(ctx, report2);
23769
23937
  else {
23770
- ctx.stdout(`${dir}: ${SHAPE_LABELS[report.shape]} \u2014 ${report.tasks.length} ${from} task(s), ${report.converted} converted, ${report.refused} refused`);
23771
- for (const task of report.tasks)
23938
+ ctx.stdout(`${dir}: ${SHAPE_LABELS[report2.shape]} \u2014 ${report2.tasks.length} ${from} task(s), ${report2.converted} converted, ${report2.refused} refused`);
23939
+ for (const task of report2.tasks)
23772
23940
  ctx.stdout(` ${task.expressible ? "ok " : "refused"} ${task.id}: ${task.grader}${task.prompt ? ` \u2014 "${task.prompt.slice(0, 80)}"` : ""}
23773
23941
  ${task.reason}`);
23774
- ctx.stdout(report.note);
23942
+ ctx.stdout(report2.note);
23775
23943
  }
23776
- return report.refused > 0 || report.tasks.length === 0 ? 2 : 0;
23944
+ return report2.refused > 0 || report2.tasks.length === 0 ? 2 : 0;
23777
23945
  }
23778
23946
  });
23779
23947
  }
@@ -23783,8 +23951,8 @@ init_connector();
23783
23951
 
23784
23952
  // src/cli/platform/dashboards.ts
23785
23953
  var import_node_child_process6 = require("child_process");
23786
- var fs39 = __toESM(require("fs"));
23787
- var path32 = __toESM(require("path"));
23954
+ var fs40 = __toESM(require("fs"));
23955
+ var path33 = __toESM(require("path"));
23788
23956
  init_config();
23789
23957
  init_router();
23790
23958
  init_checkoutTarget();
@@ -23820,8 +23988,8 @@ var DashboardClient = class {
23820
23988
 
23821
23989
  // src/cli/platform/dashboards/dashboardDir.ts
23822
23990
  var import_node_crypto17 = require("crypto");
23823
- var fs38 = __toESM(require("fs"));
23824
- var path31 = __toESM(require("path"));
23991
+ var fs39 = __toESM(require("fs"));
23992
+ var path32 = __toESM(require("path"));
23825
23993
  init_router();
23826
23994
  var DASHBOARD_MANIFEST = "gateway-dashboard.json";
23827
23995
  var RENDER_DIR = "render";
@@ -23835,14 +24003,14 @@ var DashboardDir = class _DashboardDir {
23835
24003
  root;
23836
24004
  manifest;
23837
24005
  static at(root) {
23838
- return new _DashboardDir(path31.resolve(root), _DashboardDir.readManifest(root));
24006
+ return new _DashboardDir(path32.resolve(root), _DashboardDir.readManifest(root));
23839
24007
  }
23840
24008
  static isDashboard(root) {
23841
24009
  return _DashboardDir.readManifest(root) !== null;
23842
24010
  }
23843
24011
  static readManifest(root) {
23844
24012
  try {
23845
- const parsed = JSON.parse(fs38.readFileSync(path31.join(root, DASHBOARD_MANIFEST), "utf8"));
24013
+ const parsed = JSON.parse(fs39.readFileSync(path32.join(root, DASHBOARD_MANIFEST), "utf8"));
23846
24014
  return typeof parsed?.id === "string" && typeof parsed.stamp === "string" ? parsed : null;
23847
24015
  } catch {
23848
24016
  return null;
@@ -23875,7 +24043,7 @@ var DashboardDir = class _DashboardDir {
23875
24043
  const local = this.localFiles();
23876
24044
  const files = [...local.entries()].filter(([rel]) => rel.startsWith(`${RENDER_DIR}/`)).map(([rel, content]) => ({ path: rel.slice(RENDER_DIR.length + 1), content }));
23877
24045
  if (files.length === 0)
23878
- throw new CliError(`no render files under ${path31.join(this.root, RENDER_DIR)} \u2014 nothing to push`, 2);
24046
+ throw new CliError(`no render files under ${path32.join(this.root, RENDER_DIR)} \u2014 nothing to push`, 2);
23879
24047
  const entry = manifest.entrypoint ?? void 0;
23880
24048
  return {
23881
24049
  files,
@@ -23891,7 +24059,7 @@ var DashboardDir = class _DashboardDir {
23891
24059
  }
23892
24060
  /** Lay a pulled or created dashboard into the directory and record it. */
23893
24061
  write(code) {
23894
- fs38.mkdirSync(this.root, { recursive: true });
24062
+ fs39.mkdirSync(this.root, { recursive: true });
23895
24063
  for (const file of code.files) this.writeFile(`${RENDER_DIR}/${file.path}`, file.content);
23896
24064
  if (code.transform !== null) this.writeFile(TRANSFORM_FILE, code.transform);
23897
24065
  return this.record({ ...code, files: this.hashes() });
@@ -23911,7 +24079,7 @@ var DashboardDir = class _DashboardDir {
23911
24079
  url: manifest.url,
23912
24080
  files: manifest.files
23913
24081
  };
23914
- fs38.writeFileSync(path31.join(this.root, DASHBOARD_MANIFEST), JSON.stringify(kept, null, 2) + "\n");
24082
+ fs39.writeFileSync(path32.join(this.root, DASHBOARD_MANIFEST), JSON.stringify(kept, null, 2) + "\n");
23915
24083
  return new _DashboardDir(this.root, kept);
23916
24084
  }
23917
24085
  hashes() {
@@ -23922,33 +24090,33 @@ var DashboardDir = class _DashboardDir {
23922
24090
  /** Every regular file under `render/` plus `transform.js`; hidden files are skipped, links refused. */
23923
24091
  localFiles() {
23924
24092
  const out = /* @__PURE__ */ new Map();
23925
- const renderRoot = path31.join(this.root, RENDER_DIR);
23926
- if (fs38.existsSync(renderRoot)) this.walk(renderRoot, out);
23927
- const transform = path31.join(this.root, TRANSFORM_FILE);
23928
- if (fs38.existsSync(transform)) out.set(TRANSFORM_FILE, this.readRegular(transform));
24093
+ const renderRoot = path32.join(this.root, RENDER_DIR);
24094
+ if (fs39.existsSync(renderRoot)) this.walk(renderRoot, out);
24095
+ const transform = path32.join(this.root, TRANSFORM_FILE);
24096
+ if (fs39.existsSync(transform)) out.set(TRANSFORM_FILE, this.readRegular(transform));
23929
24097
  return new Map([...out.entries()].sort(([a], [b]) => a.localeCompare(b)));
23930
24098
  }
23931
24099
  walk(dir, out) {
23932
- for (const entry of fs38.readdirSync(dir, { withFileTypes: true })) {
24100
+ for (const entry of fs39.readdirSync(dir, { withFileTypes: true })) {
23933
24101
  if (entry.name.startsWith(".")) continue;
23934
- const full = path31.join(dir, entry.name);
24102
+ const full = path32.join(dir, entry.name);
23935
24103
  if (entry.isDirectory()) this.walk(full, out);
23936
- else out.set(path31.relative(this.root, full).split(path31.sep).join("/"), this.readRegular(full));
24104
+ else out.set(path32.relative(this.root, full).split(path32.sep).join("/"), this.readRegular(full));
23937
24105
  }
23938
24106
  }
23939
24107
  readRegular(file) {
23940
- if (!fs38.lstatSync(file).isFile())
24108
+ if (!fs39.lstatSync(file).isFile())
23941
24109
  throw new CliError(`${file} is not a regular file (links are not followed) \u2014 replace it with the file itself`, 2);
23942
- return fs38.readFileSync(file, "utf8");
24110
+ return fs39.readFileSync(file, "utf8");
23943
24111
  }
23944
24112
  /** A server-named path lands under the directory or not at all (B4). */
23945
24113
  writeFile(rel, content) {
23946
24114
  const parts2 = rel.split("/");
23947
- const escapes = path31.isAbsolute(rel) || rel.includes("\\") || parts2.some((p) => p === ".." || p === "");
24115
+ const escapes = path32.isAbsolute(rel) || rel.includes("\\") || parts2.some((p) => p === ".." || p === "");
23948
24116
  if (escapes) throw new CliError(`refusing to write ${JSON.stringify(rel)}: not a path inside the dashboard`, 1);
23949
- const target = path31.join(this.root, ...parts2);
23950
- fs38.mkdirSync(path31.dirname(target), { recursive: true });
23951
- fs38.writeFileSync(target, content);
24117
+ const target = path32.join(this.root, ...parts2);
24118
+ fs39.mkdirSync(path32.dirname(target), { recursive: true });
24119
+ fs39.writeFileSync(target, content);
23952
24120
  }
23953
24121
  };
23954
24122
  function dashboardDirName(name) {
@@ -24004,7 +24172,7 @@ function checkout(ctx, code, landing2) {
24004
24172
  url: code.url
24005
24173
  });
24006
24174
  }
24007
- var looksLikePath = (value) => value === "." || value.includes("/") || value.includes(path32.sep) || fs39.existsSync(value);
24175
+ var looksLikePath = (value) => value === "." || value.includes("/") || value.includes(path33.sep) || fs40.existsSync(value);
24008
24176
  function dashboardId(target) {
24009
24177
  const candidate = target ?? ".";
24010
24178
  if (!looksLikePath(candidate)) return candidate;
@@ -24147,7 +24315,7 @@ function registerDashboardCommands(root) {
24147
24315
  taskId: arg.str(args, "task"),
24148
24316
  includeHtml: out ? true : void 0
24149
24317
  });
24150
- if (out && rendered.html !== null) fs39.writeFileSync(out, rendered.html);
24318
+ if (out && rendered.html !== null) fs40.writeFileSync(out, rendered.html);
24151
24319
  const summary2 = {
24152
24320
  success: rendered.success,
24153
24321
  error: rendered.error,
@@ -24156,7 +24324,7 @@ function registerDashboardCommands(root) {
24156
24324
  executionTimeMs: rendered.executionTimeMs,
24157
24325
  url: rendered.url
24158
24326
  };
24159
- printJson(ctx, out ? { ...summary2, out: path32.resolve(out) } : summary2);
24327
+ printJson(ctx, out ? { ...summary2, out: path33.resolve(out) } : summary2);
24160
24328
  return rendered.success ? 0 : 1;
24161
24329
  }
24162
24330
  });
@@ -24177,9 +24345,9 @@ function registerDashboardCommands(root) {
24177
24345
  }
24178
24346
 
24179
24347
  // src/cli/platform/data.ts
24180
- var fs46 = __toESM(require("fs"));
24348
+ var fs47 = __toESM(require("fs"));
24181
24349
  var os7 = __toESM(require("os"));
24182
- var path38 = __toESM(require("path"));
24350
+ var path39 = __toESM(require("path"));
24183
24351
  var import_node_stream2 = require("stream");
24184
24352
  init_config();
24185
24353
  init_router();
@@ -24526,15 +24694,15 @@ function pyDumpsPlain(value) {
24526
24694
  }
24527
24695
 
24528
24696
  // src/cli/platform/worldData/ingestMap.ts
24529
- var fs40 = __toESM(require("fs"));
24530
- var path33 = __toESM(require("path"));
24697
+ var fs41 = __toESM(require("fs"));
24698
+ var path34 = __toESM(require("path"));
24531
24699
  init_router();
24532
24700
  var MAP_FILE = "ingest.toml";
24533
24701
  var MAP_KINDS = ["tool-call", "rows", "csv"];
24534
24702
  var SAMPLE_WIDTH = 48;
24535
24703
  function readMapping(file) {
24536
- if (!fs40.existsSync(file) || !fs40.statSync(file).isFile()) throw new CliError(`no mapping file at ${file}`, 1);
24537
- const text2 = fs40.readFileSync(file, "utf8");
24704
+ if (!fs41.existsSync(file) || !fs41.statSync(file).isFile()) throw new CliError(`no mapping file at ${file}`, 1);
24705
+ const text2 = fs41.readFileSync(file, "utf8");
24538
24706
  try {
24539
24707
  parseToml(text2);
24540
24708
  } catch (error) {
@@ -24544,8 +24712,8 @@ function readMapping(file) {
24544
24712
  return text2;
24545
24713
  }
24546
24714
  function worldMapping(dir) {
24547
- const file = path33.join(dir, MAP_FILE);
24548
- return fs40.existsSync(file) ? fs40.readFileSync(file, "utf8") : null;
24715
+ const file = path34.join(dir, MAP_FILE);
24716
+ return fs41.existsSync(file) ? fs41.readFileSync(file, "utf8") : null;
24549
24717
  }
24550
24718
  var isObject10 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
24551
24719
  function sample2(value) {
@@ -24654,7 +24822,7 @@ function skeleton(records2, entities, kind, opts = {}) {
24654
24822
  }
24655
24823
 
24656
24824
  // src/cli/platform/worldData/records.ts
24657
- var fs41 = __toESM(require("fs"));
24825
+ var fs42 = __toESM(require("fs"));
24658
24826
  init_router();
24659
24827
  init_ingest();
24660
24828
  var FROM = ["tool-calls", "traces", "rows", "csv"];
@@ -24684,24 +24852,24 @@ function readInputRecords(files, from, readText4, options = {}) {
24684
24852
  return records2;
24685
24853
  }
24686
24854
  var readFileText = (file) => {
24687
- if (!fs41.existsSync(file) || !fs41.statSync(file).isFile()) throw new CliError(`Cannot read ${file}`, 1);
24688
- return fs41.readFileSync(file, "utf8");
24855
+ if (!fs42.existsSync(file) || !fs42.statSync(file).isFile()) throw new CliError(`Cannot read ${file}`, 1);
24856
+ return fs42.readFileSync(file, "utf8");
24689
24857
  };
24690
24858
 
24691
24859
  // src/cli/platform/data.ts
24692
24860
  init_transform();
24693
24861
 
24694
24862
  // src/cli/platform/worldData/manifest.ts
24695
- var fs42 = __toESM(require("fs"));
24696
- var path34 = __toESM(require("path"));
24863
+ var fs43 = __toESM(require("fs"));
24864
+ var path35 = __toESM(require("path"));
24697
24865
  init_router();
24698
- var MANIFEST_DIR = path34.join(".gateway", "imports");
24866
+ var MANIFEST_DIR = path35.join(".gateway", "imports");
24699
24867
  function manifestDir(cwd = process.cwd()) {
24700
- return path34.join(cwd, MANIFEST_DIR);
24868
+ return path35.join(cwd, MANIFEST_DIR);
24701
24869
  }
24702
24870
  function manifestPath(batchId, cwd = process.cwd()) {
24703
24871
  if (!/^[A-Za-z0-9_-]+$/.test(batchId)) throw new CliError(`Not a batch id: ${batchId}`);
24704
- return path34.join(manifestDir(cwd), `${batchId}.json`);
24872
+ return path35.join(manifestDir(cwd), `${batchId}.json`);
24705
24873
  }
24706
24874
  var stamp = () => (/* @__PURE__ */ new Date()).toISOString().replace(/\.\d{3}Z$/, "Z");
24707
24875
  function newManifest(fields) {
@@ -24710,18 +24878,18 @@ function newManifest(fields) {
24710
24878
  }
24711
24879
  function writeManifest(manifest, cwd = process.cwd()) {
24712
24880
  const file = manifestPath(manifest.batchId, cwd);
24713
- fs42.mkdirSync(path34.dirname(file), { recursive: true });
24714
- const ignore = path34.join(cwd, ".gateway", ".gitignore");
24715
- if (!fs42.existsSync(ignore)) fs42.writeFileSync(ignore, "*\n");
24881
+ fs43.mkdirSync(path35.dirname(file), { recursive: true });
24882
+ const ignore = path35.join(cwd, ".gateway", ".gitignore");
24883
+ if (!fs43.existsSync(ignore)) fs43.writeFileSync(ignore, "*\n");
24716
24884
  manifest.updatedAt = stamp();
24717
24885
  const tmp = `${file}.tmp`;
24718
- fs42.writeFileSync(tmp, JSON.stringify(manifest, null, 1) + "\n");
24719
- fs42.renameSync(tmp, file);
24886
+ fs43.writeFileSync(tmp, JSON.stringify(manifest, null, 1) + "\n");
24887
+ fs43.renameSync(tmp, file);
24720
24888
  return file;
24721
24889
  }
24722
24890
  function readManifest(batchId, cwd = process.cwd()) {
24723
24891
  try {
24724
- const parsed = JSON.parse(fs42.readFileSync(manifestPath(batchId, cwd), "utf8"));
24892
+ const parsed = JSON.parse(fs43.readFileSync(manifestPath(batchId, cwd), "utf8"));
24725
24893
  return parsed && parsed.version === 1 && parsed.batchId === batchId ? parsed : null;
24726
24894
  } catch {
24727
24895
  return null;
@@ -24735,9 +24903,9 @@ function uploadedEntry(manifest, ordinal, digest2) {
24735
24903
  }
24736
24904
  function listManifests(cwd = process.cwd()) {
24737
24905
  const dir = manifestDir(cwd);
24738
- if (!fs42.existsSync(dir)) return [];
24906
+ if (!fs43.existsSync(dir)) return [];
24739
24907
  const out = [];
24740
- for (const name of fs42.readdirSync(dir)) {
24908
+ for (const name of fs43.readdirSync(dir)) {
24741
24909
  if (!name.endsWith(".json")) continue;
24742
24910
  const manifest = readManifest(name.slice(0, -5), cwd);
24743
24911
  if (manifest) out.push(manifest);
@@ -24753,15 +24921,15 @@ function findResumable(slug, inputs, cwd = process.cwd()) {
24753
24921
  init_describe();
24754
24922
 
24755
24923
  // src/cli/platform/worldData/worldConfig.ts
24756
- var fs43 = __toESM(require("fs"));
24757
- var path35 = __toESM(require("path"));
24924
+ var fs44 = __toESM(require("fs"));
24925
+ var path36 = __toESM(require("path"));
24758
24926
  init_router();
24759
24927
  function loadWorldConfig(dir) {
24760
- const worldFile = ["schema/world.json", "world.json"].map((p) => path35.join(dir, p)).find((p) => fs43.existsSync(p));
24928
+ const worldFile = ["schema/world.json", "world.json"].map((p) => path36.join(dir, p)).find((p) => fs44.existsSync(p));
24761
24929
  if (!worldFile) throw new CliError(`${dir} has no schema/world.json; extract needs a schema world`, 1);
24762
24930
  let document;
24763
24931
  try {
24764
- document = JSON.parse(fs43.readFileSync(worldFile, "utf8"));
24932
+ document = JSON.parse(fs44.readFileSync(worldFile, "utf8"));
24765
24933
  } catch {
24766
24934
  throw new CliError(`${worldFile} is not valid JSON`, 1);
24767
24935
  }
@@ -24773,8 +24941,8 @@ function loadWorldConfig(dir) {
24773
24941
  const primaryKey = Array.isArray(entity.primary_key) ? entity.primary_key : [];
24774
24942
  entities[name] = { primaryKey, fields: declaredFields(document, entity.schema) };
24775
24943
  }
24776
- const connectorFile = path35.join(dir, "connector.toml");
24777
- const spec = fs43.existsSync(connectorFile) ? readSpec(connectorFile) : readEnvPolicy(path35.join(dir, "gateway-env.toml"));
24944
+ const connectorFile = path36.join(dir, "connector.toml");
24945
+ const spec = fs44.existsSync(connectorFile) ? readSpec(connectorFile) : readEnvPolicy(path36.join(dir, "gateway-env.toml"));
24778
24946
  return { dir, slug: spec.slug, entities, redact: spec.redact, envelope: spec.envelope, hitsKey: spec.hitsKey, operations: spec.operations };
24779
24947
  }
24780
24948
  function declaredFields(document, schema) {
@@ -24792,7 +24960,7 @@ function declaredFields(document, schema) {
24792
24960
  var NO_SPEC = { slug: null, redact: { hash: [], drop: [], preserve: [], round: {} }, envelope: "", hitsKey: "hits", operations: {} };
24793
24961
  function readToml(file) {
24794
24962
  try {
24795
- return parseToml(fs43.readFileSync(file, "utf8"));
24963
+ return parseToml(fs44.readFileSync(file, "utf8"));
24796
24964
  } catch (error) {
24797
24965
  if (error instanceof TomlError) throw new CliError(`${file}: ${error.message}`, 1);
24798
24966
  throw error;
@@ -24812,7 +24980,7 @@ function readSpec(file) {
24812
24980
  };
24813
24981
  }
24814
24982
  function readEnvPolicy(file) {
24815
- if (!fs43.existsSync(file)) return NO_SPEC;
24983
+ if (!fs44.existsSync(file)) return NO_SPEC;
24816
24984
  const raw = readToml(file);
24817
24985
  if (raw.redact === void 0) return NO_SPEC;
24818
24986
  const name = table2(raw.environment).name;
@@ -24849,24 +25017,24 @@ function rounding(value) {
24849
25017
  }
24850
25018
 
24851
25019
  // src/cli/platform/worldData/treeImport.ts
24852
- var fs45 = __toESM(require("fs"));
25020
+ var fs46 = __toESM(require("fs"));
24853
25021
  var os6 = __toESM(require("os"));
24854
- var path37 = __toESM(require("path"));
25022
+ var path38 = __toESM(require("path"));
24855
25023
  init_config();
24856
25024
  init_router();
24857
25025
  init_hub();
24858
25026
 
24859
25027
  // src/cli/platform/worldData/driveIo.ts
24860
- var fs44 = __toESM(require("fs"));
25028
+ var fs45 = __toESM(require("fs"));
24861
25029
  var os5 = __toESM(require("os"));
24862
- var path36 = __toESM(require("path"));
25030
+ var path37 = __toESM(require("path"));
24863
25031
  init_files();
24864
25032
  init_shared();
24865
25033
  async function stageDriveInputs(inputs, creds) {
24866
25034
  if (!inputs.some(isDriveRef))
24867
25035
  return { files: inputs, labels: {}, cleanup: () => void 0 };
24868
- const scratch = fs44.mkdtempSync(path36.join(os5.tmpdir(), "gateway-drive-in-"));
24869
- const cleanup = () => fs44.rmSync(scratch, { recursive: true, force: true });
25036
+ const scratch = fs45.mkdtempSync(path37.join(os5.tmpdir(), "gateway-drive-in-"));
25037
+ const cleanup = () => fs45.rmSync(scratch, { recursive: true, force: true });
24870
25038
  const labels = {};
24871
25039
  const files = [];
24872
25040
  try {
@@ -24877,7 +25045,7 @@ async function stageDriveInputs(inputs, creds) {
24877
25045
  continue;
24878
25046
  }
24879
25047
  const target = drivePath(input);
24880
- const local = path36.join(scratch, `${index2}-${path36.basename(target)}`);
25048
+ const local = path37.join(scratch, `${index2}-${path37.basename(target)}`);
24881
25049
  await downloadFile(options, target, local);
24882
25050
  labels[local] = `drive:${target}`;
24883
25051
  files.push(local);
@@ -24900,10 +25068,10 @@ async function landInDrive(localFile, to, creds) {
24900
25068
  });
24901
25069
  }
24902
25070
  function scratchFile(name) {
24903
- const dir = fs44.mkdtempSync(path36.join(os5.tmpdir(), "gateway-drive-out-"));
25071
+ const dir = fs45.mkdtempSync(path37.join(os5.tmpdir(), "gateway-drive-out-"));
24904
25072
  return {
24905
- file: path36.join(dir, name),
24906
- cleanup: () => fs44.rmSync(dir, { recursive: true, force: true })
25073
+ file: path37.join(dir, name),
25074
+ cleanup: () => fs45.rmSync(dir, { recursive: true, force: true })
24907
25075
  };
24908
25076
  }
24909
25077
  var TO_FLAG = {
@@ -24946,7 +25114,7 @@ var TreeImport = class _TreeImport {
24946
25114
  /** The platform slug this directory would import into: its pulled metadata, else its name. */
24947
25115
  get slug() {
24948
25116
  const slug = readLocalMeta(this.dir)?.slug;
24949
- return typeof slug === "string" && slug ? slug : path37.basename(path37.resolve(this.dir));
25117
+ return typeof slug === "string" && slug ? slug : path38.basename(path38.resolve(this.dir));
24950
25118
  }
24951
25119
  /** Import (or, `dryRun`, prove) the files; prints the report `data check` prints; the exit code. */
24952
25120
  async run(dryRun) {
@@ -25019,7 +25187,7 @@ var TreeImport = class _TreeImport {
25019
25187
  `${what} across ${paths.length} file(s) exceed the inline cap (${INLINE_ROWS} rows / ${INLINE_BYTES} bytes) a directory takes at once without the bundled runtime; install python3 (the runtime then streams the files in place, 4 MiB / 100000 rows), split the rows into smaller files, or import into the platform world \`${this.slug}\` (\`gateway worlds data import ${this.slug} <rows>\`), which streams them`,
25020
25188
  1
25021
25189
  );
25022
- const size = paths.reduce((n, p) => n + fs45.statSync(p).size, 0);
25190
+ const size = paths.reduce((n, p) => n + fs46.statSync(p).size, 0);
25023
25191
  if (size > INLINE_BYTES) throw tooLarge(`${size} bytes`);
25024
25192
  let count = 0;
25025
25193
  for await (const _ of readRows(paths.map(fileInput), this.entity))
@@ -25041,8 +25209,8 @@ var TreeImport = class _TreeImport {
25041
25209
  });
25042
25210
  return 2;
25043
25211
  }
25044
- write(report) {
25045
- if (this.report !== void 0) fs45.writeFileSync(this.report, report);
25212
+ write(report2) {
25213
+ if (this.report !== void 0) fs46.writeFileSync(this.report, report2);
25046
25214
  }
25047
25215
  };
25048
25216
  var StagedPaths = class {
@@ -25055,13 +25223,13 @@ var StagedPaths = class {
25055
25223
  async stage(ctx) {
25056
25224
  for (const file of this.files) {
25057
25225
  if (file === "-") {
25058
- this.scratch ??= fs45.mkdtempSync(path37.join(os6.tmpdir(), "gateway-stdin-"));
25059
- const stdin = path37.join(this.scratch, "stdin.rows");
25060
- fs45.writeFileSync(stdin, await ctx.stdin());
25226
+ this.scratch ??= fs46.mkdtempSync(path38.join(os6.tmpdir(), "gateway-stdin-"));
25227
+ const stdin = path38.join(this.scratch, "stdin.rows");
25228
+ fs46.writeFileSync(stdin, await ctx.stdin());
25061
25229
  this.list.push(stdin);
25062
25230
  continue;
25063
25231
  }
25064
- if (!fs45.existsSync(file) || !fs45.statSync(file).isFile()) throw new CliError(`Cannot read ${file}`, 1);
25232
+ if (!fs46.existsSync(file) || !fs46.statSync(file).isFile()) throw new CliError(`Cannot read ${file}`, 1);
25065
25233
  this.list.push(file);
25066
25234
  }
25067
25235
  }
@@ -25076,7 +25244,7 @@ var StagedPaths = class {
25076
25244
  return total;
25077
25245
  }
25078
25246
  dispose() {
25079
- if (this.scratch) fs45.rmSync(this.scratch, { recursive: true, force: true });
25247
+ if (this.scratch) fs46.rmSync(this.scratch, { recursive: true, force: true });
25080
25248
  }
25081
25249
  };
25082
25250
  function refusalsFromBridge(detail) {
@@ -25135,11 +25303,11 @@ function registerDataReadCommands(data) {
25135
25303
  slugOf(slug)
25136
25304
  ).get(batchId);
25137
25305
  printJson(ctx, printableStatus(status));
25138
- const report = arg.str(args, "report");
25139
- if (report === void 0) return;
25140
- const written = await writeRefusalReport(status, report);
25306
+ const report2 = arg.str(args, "report");
25307
+ if (report2 === void 0) return;
25308
+ const written = await writeRefusalReport(status, report2);
25141
25309
  ctx.stderr(
25142
- `${written} refusal${written === 1 ? "" : "s"} written to ${report}`
25310
+ `${written} refusal${written === 1 ? "" : "s"} written to ${report2}`
25143
25311
  );
25144
25312
  }
25145
25313
  });
@@ -25512,7 +25680,7 @@ primary key, the world's [redact] policy applied. Summary on stderr:
25512
25680
  const file = local ?? scratch?.file ?? null;
25513
25681
  try {
25514
25682
  const input = source2 === "-" ? stdinInput(ctx) : fileInput(staged.files[0]);
25515
- const sink = file ? fs46.createWriteStream(file) : null;
25683
+ const sink = file ? fs47.createWriteStream(file) : null;
25516
25684
  const write = sink ? (line) => void sink.write(line + "\n") : (line) => ctx.stdout(line);
25517
25685
  const summary2 = await extractRows(
25518
25686
  input,
@@ -25987,7 +26155,7 @@ function rowInputs(files, ctx) {
25987
26155
  if (files.filter((f) => f === "-").length > 1)
25988
26156
  throw new CliError("stdin (-) can be read once");
25989
26157
  for (const file of files) {
25990
- if (file !== "-" && !(fs46.existsSync(file) && fs46.statSync(file).isFile()))
26158
+ if (file !== "-" && !(fs47.existsSync(file) && fs47.statSync(file).isFile()))
25991
26159
  throw new CliError(`Cannot read ${file}`, 1);
25992
26160
  }
25993
26161
  return files.map((f) => f === "-" ? stdinInput(ctx) : fileInput(f));
@@ -26246,11 +26414,11 @@ async function pullCalls(out, to, from, staged, args, ctx) {
26246
26414
  const toStdout = out === "-";
26247
26415
  if (toStdout) {
26248
26416
  if (text2) process.stdout.write(text2);
26249
- } else if (out) fs46.writeFileSync(out, text2);
26417
+ } else if (out) fs47.writeFileSync(out, text2);
26250
26418
  let landed;
26251
26419
  if (to) {
26252
26420
  const scratch = out && !toStdout ? null : scratchFile("calls.jsonl");
26253
- if (scratch) fs46.writeFileSync(scratch.file, text2);
26421
+ if (scratch) fs47.writeFileSync(scratch.file, text2);
26254
26422
  try {
26255
26423
  landed = `drive:${(await landInDrive(scratch?.file ?? out, to, credentials(args))).path}`;
26256
26424
  } finally {
@@ -26307,20 +26475,20 @@ async function mapInitCommand(world, samples, args, ctx) {
26307
26475
  delimiter: delimiterFlag(args) ?? void 0
26308
26476
  });
26309
26477
  const text2 = skeleton(records2, config.entities, kind, {
26310
- sampleName: samples.map((f) => path38.basename(f)).join(", "),
26478
+ sampleName: samples.map((f) => path39.basename(f)).join(", "),
26311
26479
  entity: arg.str(args, "entity")
26312
26480
  });
26313
- const out = arg.str(args, "out") ?? (local ? path38.join(world, MAP_FILE) : "-");
26481
+ const out = arg.str(args, "out") ?? (local ? path39.join(world, MAP_FILE) : "-");
26314
26482
  if (out === "-") {
26315
26483
  ctx.stdout(text2.replace(/\n$/, ""));
26316
26484
  return 0;
26317
26485
  }
26318
- if (fs46.existsSync(out) && !arg.bool(args, "dry-run"))
26486
+ if (fs47.existsSync(out) && !arg.bool(args, "dry-run"))
26319
26487
  throw new CliError(
26320
26488
  `${out} exists; pass --out for another path, or move it first`,
26321
26489
  1
26322
26490
  );
26323
- fs46.writeFileSync(out, text2);
26491
+ fs47.writeFileSync(out, text2);
26324
26492
  const fromFlag = from === "tool-calls" ? "" : ` --from ${from}`;
26325
26493
  ctx.stderr(
26326
26494
  `wrote ${out}: fill in the entity and fields, then run \`gateway worlds data ingest ${world} ${samples[0]}${fromFlag} --map ${out} --dry-run\``
@@ -26548,12 +26716,12 @@ async function ingestCommand(world, inputs, args, ctx, labels = {}) {
26548
26716
  const full = out;
26549
26717
  let code = full.refusals.length ? 2 : 0;
26550
26718
  if (!local && !dryRun && !full.refusals.length && Object.keys(projected).length) {
26551
- const scratch = fs46.mkdtempSync(
26552
- path38.join(os7.tmpdir(), "gateway-ingest-rows-")
26719
+ const scratch = fs47.mkdtempSync(
26720
+ path39.join(os7.tmpdir(), "gateway-ingest-rows-")
26553
26721
  );
26554
26722
  try {
26555
- const rowsFile = path38.join(scratch, "rows.json");
26556
- fs46.writeFileSync(rowsFile, JSON.stringify(projected));
26723
+ const rowsFile = path39.join(scratch, "rows.json");
26724
+ fs47.writeFileSync(rowsFile, JSON.stringify(projected));
26557
26725
  code = await importBatch(
26558
26726
  world,
26559
26727
  [rowsFile],
@@ -26568,11 +26736,11 @@ async function ingestCommand(world, inputs, args, ctx, labels = {}) {
26568
26736
  }
26569
26737
  );
26570
26738
  } finally {
26571
- fs46.rmSync(scratch, { recursive: true, force: true });
26739
+ fs47.rmSync(scratch, { recursive: true, force: true });
26572
26740
  }
26573
26741
  }
26574
26742
  if (reportFile !== void 0)
26575
- fs46.writeFileSync(
26743
+ fs47.writeFileSync(
26576
26744
  reportFile,
26577
26745
  full.refusals.map((r) => JSON.stringify(r) + "\n").join("")
26578
26746
  );
@@ -26582,38 +26750,38 @@ async function ingestCommand(world, inputs, args, ctx, labels = {}) {
26582
26750
  return code;
26583
26751
  }
26584
26752
  var pairs = (table3) => Object.entries(table3).sort().map(([key2, count]) => `${key2} ${count}`).join(", ");
26585
- function renderIngest(report, ctx) {
26586
- const skipped = Object.values(report.skipped).reduce((n, c) => n + c, 0);
26753
+ function renderIngest(report2, ctx) {
26754
+ const skipped = Object.values(report2.skipped).reduce((n, c) => n + c, 0);
26587
26755
  ctx.stdout(
26588
- `${report.records} records, ${report.ingested} ingested, ${skipped} skipped, ${report.refusals.length} refused` + (report.dryRun ? " (dry run)" : "") + (report.via ? ` \u2014 via ${report.via}` : "")
26756
+ `${report2.records} records, ${report2.ingested} ingested, ${skipped} skipped, ${report2.refusals.length} refused` + (report2.dryRun ? " (dry run)" : "") + (report2.via ? ` \u2014 via ${report2.via}` : "")
26589
26757
  );
26590
- for (const [entity, count] of Object.entries(report.rows).sort())
26758
+ for (const [entity, count] of Object.entries(report2.rows).sort())
26591
26759
  ctx.stdout(` ${entity}: ${count} rows`);
26592
- if (report.note) ctx.stdout(` note: ${report.note}`);
26593
- if (skipped) ctx.stdout(` skipped: ${pairs(report.skipped)}`);
26594
- if (report.unmatched && Object.keys(report.unmatched).length)
26760
+ if (report2.note) ctx.stdout(` note: ${report2.note}`);
26761
+ if (skipped) ctx.stdout(` skipped: ${pairs(report2.skipped)}`);
26762
+ if (report2.unmatched && Object.keys(report2.unmatched).length)
26595
26763
  ctx.stdout(
26596
- ` unmatched (no [[sources]] claimed them, skipped): ${pairs(report.unmatched)}`
26764
+ ` unmatched (no [[sources]] claimed them, skipped): ${pairs(report2.unmatched)}`
26597
26765
  );
26598
- if (report.unknownTools && Object.keys(report.unknownTools).length)
26766
+ if (report2.unknownTools && Object.keys(report2.unknownTools).length)
26599
26767
  ctx.stdout(
26600
- ` not the world's operations (not converted): ${pairs(report.unknownTools)}`
26768
+ ` not the world's operations (not converted): ${pairs(report2.unknownTools)}`
26601
26769
  );
26602
- if (report.notConverted && Object.keys(report.notConverted).length)
26603
- ctx.stdout(` observations not converted: ${pairs(report.notConverted)}`);
26604
- if (report.filtered) ctx.stdout(` dropped by --tool: ${report.filtered}`);
26605
- for (const source2 of report.sources ?? []) renderSource(source2, ctx);
26606
- for (const refusal of report.refusals)
26770
+ if (report2.notConverted && Object.keys(report2.notConverted).length)
26771
+ ctx.stdout(` observations not converted: ${pairs(report2.notConverted)}`);
26772
+ if (report2.filtered) ctx.stdout(` dropped by --tool: ${report2.filtered}`);
26773
+ for (const source2 of report2.sources ?? []) renderSource(source2, ctx);
26774
+ for (const refusal of report2.refusals)
26607
26775
  ctx.stdout(
26608
26776
  ` refused [${refusal.index ?? "-"}] ${refusal.tool ?? refusal.pointer ?? "-"}: ${refusal.reason}`
26609
26777
  );
26610
- if (report.batch)
26778
+ if (report2.batch)
26611
26779
  ctx.stdout(
26612
- ` batch ${String(report.batch.batchId ?? "?")} ${String(report.batch.state ?? "?")}` + (report.batch.versionId ? ` -> version ${String(report.batch.versionId)}` : "")
26780
+ ` batch ${String(report2.batch.batchId ?? "?")} ${String(report2.batch.state ?? "?")}` + (report2.batch.versionId ? ` -> version ${String(report2.batch.versionId)}` : "")
26613
26781
  );
26614
- if (report.entityCounts)
26615
- ctx.stdout(` entity counts: ${pairs(report.entityCounts)}`);
26616
- if (report.redact !== "off") ctx.stdout(` redact: ${report.redact}`);
26782
+ if (report2.entityCounts)
26783
+ ctx.stdout(` entity counts: ${pairs(report2.entityCounts)}`);
26784
+ if (report2.redact !== "off") ctx.stdout(` redact: ${report2.redact}`);
26617
26785
  }
26618
26786
  function renderSource(source2, ctx) {
26619
26787
  ctx.stdout(
@@ -26629,8 +26797,8 @@ function renderSource(source2, ctx) {
26629
26797
  ctx.stdout(` ${entity} fields never set: ${fields.join(", ")}`);
26630
26798
  }
26631
26799
  async function pullWorld(slugRef, creds) {
26632
- const target = path38.join(
26633
- fs46.mkdtempSync(path38.join(os7.tmpdir(), "gateway-world-data-")),
26800
+ const target = path39.join(
26801
+ fs47.mkdtempSync(path39.join(os7.tmpdir(), "gateway-world-data-")),
26634
26802
  slugOf(slugRef)
26635
26803
  );
26636
26804
  const pulled = await pull(slugRef, target, worldsOptions(creds));
@@ -26638,20 +26806,20 @@ async function pullWorld(slugRef, creds) {
26638
26806
  }
26639
26807
 
26640
26808
  // src/cli/platform/dataset.ts
26641
- var fs47 = __toESM(require("fs"));
26642
- var path39 = __toESM(require("path"));
26809
+ var fs48 = __toESM(require("fs"));
26810
+ var path40 = __toESM(require("path"));
26643
26811
  init_config();
26644
26812
  init_router();
26645
26813
  init_shared();
26646
26814
  function readDatasetItems(file) {
26647
- const raw = fs47.readFileSync(file, "utf8").trim();
26648
- const looksJson = path39.extname(file) === ".json" || raw.startsWith("{") || raw.startsWith("[");
26815
+ const raw = fs48.readFileSync(file, "utf8").trim();
26816
+ const looksJson = path40.extname(file) === ".json" || raw.startsWith("{") || raw.startsWith("[");
26649
26817
  if (looksJson) {
26650
26818
  let data;
26651
26819
  try {
26652
26820
  data = JSON.parse(raw);
26653
26821
  } catch (error) {
26654
- if (path39.extname(file) === ".json") throw error;
26822
+ if (path40.extname(file) === ".json") throw error;
26655
26823
  data = void 0;
26656
26824
  }
26657
26825
  if (data !== void 0) {
@@ -26689,10 +26857,10 @@ function registerDatasetCommands(root) {
26689
26857
  const file = args.positionals[0];
26690
26858
  const name = arg.str(args, "name");
26691
26859
  if (!name) throw new CliError("dataset upload needs --name");
26692
- if (!fs47.existsSync(file)) throw new CliError(`Error: File not found: ${file}`, 1);
26860
+ if (!fs48.existsSync(file)) throw new CliError(`Error: File not found: ${file}`, 1);
26693
26861
  const items = readDatasetItems(file);
26694
26862
  if (items.length === 0) throw new CliError("Error: No items found in file.", 1);
26695
- ctx.stdout(`Found ${items.length} items in ${path39.basename(file)}`);
26863
+ ctx.stdout(`Found ${items.length} items in ${path40.basename(file)}`);
26696
26864
  const creds = credentials(args);
26697
26865
  const agent = arg.str(args, "agent");
26698
26866
  if (agent) {
@@ -26724,8 +26892,8 @@ function registerDatasetCommands(root) {
26724
26892
  }
26725
26893
 
26726
26894
  // src/cli/platform/files.ts
26727
- var fs48 = __toESM(require("fs"));
26728
- var path40 = __toESM(require("path"));
26895
+ var fs49 = __toESM(require("fs"));
26896
+ var path41 = __toESM(require("path"));
26729
26897
  init_config();
26730
26898
  init_router();
26731
26899
  init_files();
@@ -26805,7 +26973,7 @@ function registerFilesCommands(root) {
26805
26973
  flags: [{ name: "out", help: "Local path to write (default the file's own name in the working directory)." }, HOST_FLAG],
26806
26974
  run: async (args, ctx) => {
26807
26975
  const target = drivePath(args.positionals[0]);
26808
- const out = arg.str(args, "out") ?? path40.basename(target);
26976
+ const out = arg.str(args, "out") ?? path41.basename(target);
26809
26977
  const result = await downloadFile(worldsOptions(credentials(args)), target, out, progressReporter(ctx, `drive:${target}`));
26810
26978
  ctx.stdout(`drive:${result.path} -> ${out} (${result.sizeBytes ?? "?"} bytes)`);
26811
26979
  }
@@ -26865,7 +27033,7 @@ function registerFilesCommands(root) {
26865
27033
  { name: "to", help: "Drive path to save to, e.g. imports/products.csv." },
26866
27034
  {
26867
27035
  name: "header",
26868
- help: 'Request header "Name: value" (repeatable). A value may name a project secret as {{secret:NAME}}; the platform expands it, the secret never reaches this machine.',
27036
+ help: 'Request header "Name: value" (repeatable). A value may name a project secret as {{secret:NAME}}; the platform expands it, the secret never reaches this machine, and it is sent only to the origins the secret lists.',
26869
27037
  repeat: true
26870
27038
  },
26871
27039
  { name: "content-type", help: "MIME type to record (default: the response's, else from the name)." },
@@ -26874,7 +27042,7 @@ function registerFilesCommands(root) {
26874
27042
  JSON_FLAG2,
26875
27043
  HOST_FLAG
26876
27044
  ],
26877
- notes: "The platform fetches the URL (MCP twin download_url_to_drive, route POST /api/public/files/fetch): the bytes\nnever touch this machine, and --header values are sent only to the URL's origin, never to a host a redirect\npoints at. A project secret the value names must exist (`gateway secret set NAME`); the platform refuses an\nunknown one by name and never echoes an expanded value. An http:// URL is fetched with a plaintext warning.\n--local downloads here and uploads the bytes, for a URL the platform cannot reach.",
27045
+ notes: "The platform fetches the URL (MCP twin download_url_to_drive, route POST /api/public/files/fetch): the bytes\nnever touch this machine. A plain --header goes only to the URL's origin, never to a host a redirect points at;\none that names a project secret also follows a redirect to another origin that secret lists. The secret must\nexist and list the URL's origin (`gateway secret set NAME\n--allowed-origin <origin>`, or `gateway secret origins NAME <origin>`); the platform refuses an unknown secret,\none with no origins, an unlisted origin and a redirect to one by name, and never echoes an expanded\nvalue. An http:// URL is fetched with a plaintext warning.\n--local downloads here and uploads the bytes, for a URL the platform cannot reach.",
26878
27046
  run: async (args, ctx) => {
26879
27047
  const url = args.positionals[0];
26880
27048
  const to = arg.str(args, "to");
@@ -26917,23 +27085,23 @@ function planUploads(inputs, to) {
26917
27085
  const join39 = (...parts2) => parts2.filter(Boolean).join("/");
26918
27086
  const plan = [];
26919
27087
  for (const input of inputs) {
26920
- if (!fs48.existsSync(input)) throw new CliError(`${input} does not exist`, 1);
26921
- if (fs48.statSync(input).isDirectory()) {
26922
- const root = path40.resolve(input);
26923
- for (const file of walk3(root)) plan.push({ local: file, path: join39(base, path40.basename(root), path40.relative(root, file).split(path40.sep).join("/")) });
27088
+ if (!fs49.existsSync(input)) throw new CliError(`${input} does not exist`, 1);
27089
+ if (fs49.statSync(input).isDirectory()) {
27090
+ const root = path41.resolve(input);
27091
+ for (const file of walk3(root)) plan.push({ local: file, path: join39(base, path41.basename(root), path41.relative(root, file).split(path41.sep).join("/")) });
26924
27092
  continue;
26925
27093
  }
26926
- const oneFileNamedInFull = inputs.length === 1 && base !== "" && !to.endsWith("/") && path40.extname(base) !== "";
26927
- plan.push({ local: input, path: oneFileNamedInFull ? base : join39(base, path40.basename(input)) });
27094
+ const oneFileNamedInFull = inputs.length === 1 && base !== "" && !to.endsWith("/") && path41.extname(base) !== "";
27095
+ plan.push({ local: input, path: oneFileNamedInFull ? base : join39(base, path41.basename(input)) });
26928
27096
  }
26929
27097
  if (!plan.length) throw new CliError("nothing to upload: the directories are empty", 1);
26930
27098
  return plan;
26931
27099
  }
26932
27100
  function walk3(dir) {
26933
27101
  const out = [];
26934
- for (const entry of fs48.readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
27102
+ for (const entry of fs49.readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
26935
27103
  if (entry.name.startsWith(".")) continue;
26936
- const full = path40.join(dir, entry.name);
27104
+ const full = path41.join(dir, entry.name);
26937
27105
  if (entry.isDirectory()) out.push(...walk3(full));
26938
27106
  else if (entry.isFile()) out.push(full);
26939
27107
  }
@@ -27180,13 +27348,13 @@ function registerReleaseCommands(root) {
27180
27348
  }
27181
27349
 
27182
27350
  // src/cli/platform/requests.ts
27183
- var fs49 = __toESM(require("fs"));
27351
+ var fs50 = __toESM(require("fs"));
27184
27352
  init_router();
27185
27353
  init_worlds();
27186
27354
  init_shared();
27187
27355
  var NOT_RECORDED_EXIT = 3;
27188
27356
  var FILTER_FLAGS = [
27189
- { name: "via", help: "Only requests that came in by this door: api, ui or tool." },
27357
+ { name: "via", help: "Only requests that came in by this door: api, ui, tool or webhook." },
27190
27358
  { name: "operation", help: "Only requests to this operation (the route's or the tool's name)." },
27191
27359
  { name: "status", help: "Only responses with this status: a code (404) or a class (2xx, 4xx, 5xx)." },
27192
27360
  {
@@ -27289,11 +27457,11 @@ var WorldRequestText = class _WorldRequestText {
27289
27457
  return [(part.bodyBytes ?? 0) > 0 ? "(binary body not kept)" : "(no body)"];
27290
27458
  }
27291
27459
  };
27292
- function queryOf(args, scope = {}) {
27460
+ function queryOf(args, scope2 = {}) {
27293
27461
  const limit = listLimit(arg.int(args, "limit"));
27294
27462
  try {
27295
27463
  return WorldRequestQuery.parse({
27296
- ...scope,
27464
+ ...scope2,
27297
27465
  via: arg.str(args, "via"),
27298
27466
  operation: arg.str(args, "operation"),
27299
27467
  status: arg.str(args, "status"),
@@ -27370,7 +27538,7 @@ function registerRequestCommands(root) {
27370
27538
  const [slug, requestId] = args.positionals;
27371
27539
  const entry = await ledgerOf(args).get(slug, requestId);
27372
27540
  const out = arg.str(args, "out");
27373
- if (out) fs49.writeFileSync(out, `${WorldRequestText.json(entry)}
27541
+ if (out) fs50.writeFileSync(out, `${WorldRequestText.json(entry)}
27374
27542
  `);
27375
27543
  emit(ctx, args, entry, () => WorldRequestText.entry(entry, !out), WorldRequestText.json);
27376
27544
  if (!out) return;
@@ -27497,6 +27665,11 @@ function registerRunCommands(root) {
27497
27665
  init_config();
27498
27666
  init_router();
27499
27667
  init_shared();
27668
+ var ORIGIN_HELP = "An https origin (https://host[:port]) a fetch header that uses this secret may be sent to; repeatable. A secret with none is never expanded into a `files fetch` header.";
27669
+ function originsLine(name, origins) {
27670
+ if (origins.length === 0) return `Secret '${name}' has no allowed origins: it is never sent in a fetch header.`;
27671
+ return `Secret '${name}' may be sent to: ${origins.join(", ")}`;
27672
+ }
27500
27673
  function registerSecretCommands(root) {
27501
27674
  const secret = root.group("secret", "Manage project secrets (encrypted env vars for agent containers).");
27502
27675
  secret.command({
@@ -27507,6 +27680,7 @@ function registerSecretCommands(root) {
27507
27680
  { name: "value", short: "v", help: "Secret value. If omitted, it is read from stdin." },
27508
27681
  { name: "description", short: "d", help: "Human-readable description" },
27509
27682
  { name: "scope", help: "Scope: agent, worker, or both", default: "agent" },
27683
+ { name: "allowed-origin", help: ORIGIN_HELP, repeat: true },
27510
27684
  HOST_FLAG,
27511
27685
  API_KEY_FLAG
27512
27686
  ],
@@ -27518,6 +27692,8 @@ function registerSecretCommands(root) {
27518
27692
  const payload = { name, value, scope: arg.str(args, "scope") ?? "agent" };
27519
27693
  const description = arg.str(args, "description");
27520
27694
  if (description) payload.description = description;
27695
+ const origins = arg.list(args, "allowed-origin");
27696
+ if (origins.length) payload.allowedOrigins = origins;
27521
27697
  const saved = await rawRequest(creds, "POST", "/api/public/secrets", payload);
27522
27698
  if (!saved.ok) throw failed(saved.status, saved.text);
27523
27699
  const data = saved.json();
@@ -27525,9 +27701,34 @@ function registerSecretCommands(root) {
27525
27701
  ctx.stdout(`Secret '${data.name ?? name}' ${verb} (${data.displayValue ?? "****"})`);
27526
27702
  }
27527
27703
  });
27704
+ secret.command({
27705
+ name: "origins",
27706
+ help: "Set the origins a secret may be sent to in a `files fetch` header (replaces the list; the value is untouched).",
27707
+ positionals: [
27708
+ { name: "name", help: "Secret name" },
27709
+ { name: "origin", help: "https://host[:port], one or more", variadic: true }
27710
+ ],
27711
+ flags: [
27712
+ { name: "none", help: "Clear the list: the secret is then never sent in a fetch header.", boolean: true },
27713
+ HOST_FLAG,
27714
+ API_KEY_FLAG
27715
+ ],
27716
+ run: async (args, ctx) => {
27717
+ const [name, ...origins] = args.positionals;
27718
+ const named2 = origins.length > 0;
27719
+ if (arg.bool(args, "none") === named2)
27720
+ throw new CliError("name at least one origin, or pass --none to clear the list (not both)", 2);
27721
+ const res = await rawRequest(credentials(args), "PUT", `/api/public/secrets/${encodeURIComponent(name)}`, {
27722
+ allowedOrigins: origins
27723
+ });
27724
+ if (!res.ok) throw failed(res.status, res.text);
27725
+ const data = res.json();
27726
+ ctx.stdout(originsLine(data.name ?? name, data.allowedOrigins ?? []));
27727
+ }
27728
+ });
27528
27729
  secret.command({
27529
27730
  name: "list",
27530
- help: "List project secrets (names and descriptions only, not values).",
27731
+ help: "List project secrets (names, descriptions and allowed origins, not values).",
27531
27732
  flags: [HOST_FLAG, API_KEY_FLAG],
27532
27733
  run: async (args, ctx) => {
27533
27734
  const res = await api(credentials(args), "GET", "/api/public/secrets");
@@ -27536,11 +27737,12 @@ function registerSecretCommands(root) {
27536
27737
  ctx.stdout("No secrets configured. Run `gateway secret set <name>` to add one.");
27537
27738
  return;
27538
27739
  }
27539
- ctx.stdout(`${"Name".padEnd(30)} ${"Scope".padEnd(10)} Description`);
27540
- ctx.stdout("-".repeat(70));
27740
+ ctx.stdout(`${"Name".padEnd(30)} ${"Scope".padEnd(10)} ${"Description".padEnd(28)} Allowed origins`);
27741
+ ctx.stdout("-".repeat(100));
27541
27742
  for (const s of secrets) {
27542
27743
  const desc = (s.description ?? "").slice(0, 28);
27543
- ctx.stdout(`${(s.name ?? "").padEnd(30)} ${(s.scope ?? "").padEnd(10)} ${desc}`);
27744
+ const origins = (s.allowedOrigins ?? []).join(", ");
27745
+ ctx.stdout(`${(s.name ?? "").padEnd(30)} ${(s.scope ?? "").padEnd(10)} ${desc.padEnd(28)} ${origins}`.trimEnd());
27544
27746
  }
27545
27747
  }
27546
27748
  });
@@ -27558,7 +27760,7 @@ function registerSecretCommands(root) {
27558
27760
  }
27559
27761
 
27560
27762
  // src/cli/platform/session.ts
27561
- var fs53 = __toESM(require("fs"));
27763
+ var fs54 = __toESM(require("fs"));
27562
27764
  init_config();
27563
27765
  init_router();
27564
27766
  init_worlds();
@@ -27566,11 +27768,11 @@ init_surfaceDescriptor();
27566
27768
  init_shared();
27567
27769
 
27568
27770
  // src/cli/platform/task.ts
27569
- var fs52 = __toESM(require("fs"));
27771
+ var fs53 = __toESM(require("fs"));
27570
27772
 
27571
27773
  // src/cli/agentModule.ts
27572
- var fs50 = __toESM(require("fs"));
27573
- var path41 = __toESM(require("path"));
27774
+ var fs51 = __toESM(require("fs"));
27775
+ var path42 = __toESM(require("path"));
27574
27776
  var import_node_url2 = require("url");
27575
27777
  init_router();
27576
27778
  var JAVASCRIPT = [".js", ".mjs", ".cjs"];
@@ -27587,7 +27789,7 @@ var AgentModule = class _AgentModule {
27587
27789
  static FORM = "file.mjs[#export] (.js/.mjs/.cjs, or .ts with tsx installed): the default export, or the export #name names";
27588
27790
  static parse(spec) {
27589
27791
  const hash = spec.lastIndexOf("#");
27590
- if (hash === -1 || fs50.existsSync(spec)) return new _AgentModule(spec, spec, null);
27792
+ if (hash === -1 || fs51.existsSync(spec)) return new _AgentModule(spec, spec, null);
27591
27793
  return new _AgentModule(spec, spec.slice(0, hash), spec.slice(hash + 1) || null);
27592
27794
  }
27593
27795
  sessionAgent() {
@@ -27597,8 +27799,8 @@ var AgentModule = class _AgentModule {
27597
27799
  return this.load("async (run) => report (see @withgateway/sdk/worlds TaskRun)");
27598
27800
  }
27599
27801
  async load(signature) {
27600
- const abs = path41.resolve(this.file);
27601
- if (!fs50.existsSync(abs)) throw new CliError(`--agent ${this.spec} does not exist`);
27802
+ const abs = path42.resolve(this.file);
27803
+ if (!fs51.existsSync(abs)) throw new CliError(`--agent ${this.spec} does not exist`);
27602
27804
  await _AgentModule.prepare(abs);
27603
27805
  const mod = await import((0, import_node_url2.pathToFileURL)(abs).href);
27604
27806
  const candidate = this.exportName ? mod[this.exportName] : _AgentModule.defaultOf(mod);
@@ -27616,7 +27818,7 @@ var AgentModule = class _AgentModule {
27616
27818
  return candidate;
27617
27819
  }
27618
27820
  static async prepare(abs) {
27619
- const ext = path41.extname(abs);
27821
+ const ext = path42.extname(abs);
27620
27822
  if (TYPESCRIPT.includes(ext)) return _AgentModule.registerTypeScript(abs);
27621
27823
  if (JAVASCRIPT.includes(ext)) return;
27622
27824
  throw new CliError(
@@ -27718,7 +27920,7 @@ init_worlds();
27718
27920
  init_shared();
27719
27921
 
27720
27922
  // src/cli/platform/taskSpec.ts
27721
- var fs51 = __toESM(require("fs"));
27923
+ var fs52 = __toESM(require("fs"));
27722
27924
  init_router();
27723
27925
  var TASK_SPEC_HELP = `A task spec is JSON:
27724
27926
  {"instruction": "<what the agent is told>",
@@ -27978,25 +28180,25 @@ var TaskSpecCheck = class {
27978
28180
  this.grader(verifier, at);
27979
28181
  this.crossChecks(verifier, at);
27980
28182
  }
27981
- scope(scope, at) {
27982
- if (!isStringList(scope) || scope.length < 2)
28183
+ scope(scope2, at) {
28184
+ if (!isStringList(scope2) || scope2.length < 2)
27983
28185
  return this.issue(
27984
28186
  `${at}.scope lists two or more of the task's world aliases`
27985
28187
  );
27986
- if (new Set(scope).size !== scope.length)
28188
+ if (new Set(scope2).size !== scope2.length)
27987
28189
  this.issue(`${at}.scope lists each alias once`);
27988
- this.scopeInWorlds(scope, at);
27989
- this.anchor(scope[0], at);
28190
+ this.scopeInWorlds(scope2, at);
28191
+ this.anchor(scope2[0], at);
27990
28192
  }
27991
- scopeInWorlds(scope, at) {
28193
+ scopeInWorlds(scope2, at) {
27992
28194
  const worlds = this.spec.worlds;
27993
- if (worlds === void 0 && scope[0] !== this.spec.name)
28195
+ if (worlds === void 0 && scope2[0] !== this.spec.name)
27994
28196
  this.issue(
27995
- `${at}.scope[0] is "${scope[0]}", so the task's name must be "${scope[0]}": on a task without worlds a verifier runs on the session of its first scope alias`
28197
+ `${at}.scope[0] is "${scope2[0]}", so the task's name must be "${scope2[0]}": on a task without worlds a verifier runs on the session of its first scope alias`
27996
28198
  );
27997
28199
  if (!isRecord(worlds)) return;
27998
28200
  const aliases = Object.keys(worlds);
27999
- for (const alias of scope.filter((a) => !aliases.includes(a)))
28201
+ for (const alias of scope2.filter((a) => !aliases.includes(a)))
28000
28202
  this.issue(
28001
28203
  `${at}.scope names "${alias}", which is not one of worlds (${aliases.join(", ")})`
28002
28204
  );
@@ -28011,15 +28213,15 @@ var TaskSpecCheck = class {
28011
28213
  );
28012
28214
  }
28013
28215
  crossChecks(verifier, at) {
28014
- const { scope, checks } = verifier;
28216
+ const { scope: scope2, checks } = verifier;
28015
28217
  if (verifier.kind !== "assertions") return;
28016
- if (!isStringList(scope) || !Array.isArray(checks)) return;
28218
+ if (!isStringList(scope2) || !Array.isArray(checks)) return;
28017
28219
  checks.forEach((check, i) => {
28018
28220
  const entity = isRecord(check) ? check.entity : void 0;
28019
28221
  if (typeof entity !== "string" || !entity) return;
28020
- if (entity.includes(".") && scope.includes(entity.split(".")[0])) return;
28222
+ if (entity.includes(".") && scope2.includes(entity.split(".")[0])) return;
28021
28223
  this.issue(
28022
- `${at}.checks[${i}].entity is "${entity}": a cross-world check names its entity as <alias>.<entity> (or <alias>.calls) with the alias in scope (${scope.join(", ")})`
28224
+ `${at}.checks[${i}].entity is "${entity}": a cross-world check names its entity as <alias>.<entity> (or <alias>.calls) with the alias in scope (${scope2.join(", ")})`
28023
28225
  );
28024
28226
  });
28025
28227
  }
@@ -28030,7 +28232,7 @@ function taskSpecIssues(spec) {
28030
28232
  function readTaskSpec(file, flag = "--spec") {
28031
28233
  let parsed;
28032
28234
  try {
28033
- parsed = JSON.parse(fs51.readFileSync(file, "utf8"));
28235
+ parsed = JSON.parse(fs52.readFileSync(file, "utf8"));
28034
28236
  } catch (error) {
28035
28237
  throw new CliError(
28036
28238
  `${flag} ${file}: ${error instanceof Error ? error.message : String(error)}`
@@ -28083,7 +28285,7 @@ function worldFromFlags(world, noWorld) {
28083
28285
  }
28084
28286
  function readJsonFile(file, what) {
28085
28287
  try {
28086
- return JSON.parse(fs52.readFileSync(file, "utf8"));
28288
+ return JSON.parse(fs53.readFileSync(file, "utf8"));
28087
28289
  } catch (error) {
28088
28290
  throw new CliError(
28089
28291
  `${what} ${file}: ${error instanceof Error ? error.message : String(error)}`
@@ -28091,7 +28293,7 @@ function readJsonFile(file, what) {
28091
28293
  }
28092
28294
  }
28093
28295
  function taskTarget(positional) {
28094
- if (!fs52.existsSync(positional)) return { kind: "id", taskId: positional };
28296
+ if (!fs53.existsSync(positional)) return { kind: "id", taskId: positional };
28095
28297
  const parsed = readJsonFile(positional, "task");
28096
28298
  if (isTaskManifest(parsed)) return { kind: "manifest", manifest: parsed };
28097
28299
  if (parsed && typeof parsed === "object" && typeof parsed.instruction === "string")
@@ -28113,7 +28315,7 @@ var TARGET_POSITIONAL2 = {
28113
28315
  help: "Task id, or the manifest file `task up --out` wrote."
28114
28316
  };
28115
28317
  function emitManifest(ctx, manifest, out) {
28116
- if (out) fs52.writeFileSync(out, JSON.stringify(manifest, null, 2) + "\n");
28318
+ if (out) fs53.writeFileSync(out, JSON.stringify(manifest, null, 2) + "\n");
28117
28319
  printJson(ctx, manifest);
28118
28320
  if (out) ctx.stderr(`wrote the manifest to ${out}`);
28119
28321
  }
@@ -28553,7 +28755,7 @@ function registerTaskCommands(root) {
28553
28755
  const text2 = lines.join("\n") + (lines.length ? "\n" : "");
28554
28756
  const out = arg.str(args, "out");
28555
28757
  if (out) {
28556
- fs52.writeFileSync(out, text2);
28758
+ fs53.writeFileSync(out, text2);
28557
28759
  ctx.stdout(
28558
28760
  `wrote ${lines.length - requests} calls${wanted ? ` and ${requests} requests` : ""} from ${Object.keys(exported).length} worlds to ${out}`
28559
28761
  );
@@ -28990,7 +29192,7 @@ source (bundled|stored|inline|none)/name/hash/id/version.
28990
29192
  try {
28991
29193
  const url = await browser.goto(arg.str(args, "path"));
28992
29194
  const shot = arg.str(args, "screenshot");
28993
- if (shot) fs53.writeFileSync(shot, await browser.screenshot());
29195
+ if (shot) fs54.writeFileSync(shot, await browser.screenshot());
28994
29196
  printJson(ctx, {
28995
29197
  url,
28996
29198
  title: await browser.title(),
@@ -29205,12 +29407,12 @@ world's [redact] policy over the rows first; --redact refuse rejects plaintext i
29205
29407
  const out = arg.str(args, "out");
29206
29408
  const to = arg.str(args, "to");
29207
29409
  if (out) {
29208
- fs53.writeFileSync(out, text2);
29410
+ fs54.writeFileSync(out, text2);
29209
29411
  ctx.stdout(`wrote ${counted2} to ${out}`);
29210
29412
  } else if (!to && text2) process.stdout.write(text2);
29211
29413
  if (!to) return;
29212
29414
  const scratch = out ? null : scratchFile(`${sessionId}.calls.jsonl`);
29213
- if (scratch) fs53.writeFileSync(scratch.file, text2);
29415
+ if (scratch) fs54.writeFileSync(scratch.file, text2);
29214
29416
  try {
29215
29417
  const landed = await landInDrive(scratch?.file ?? out, to, creds);
29216
29418
  ctx.stdout(`wrote ${counted2} to drive:${landed.path}`);
@@ -29221,6 +29423,152 @@ world's [redact] policy over the rows first; --redact refuse rejects plaintext i
29221
29423
  });
29222
29424
  }
29223
29425
 
29426
+ // src/cli/platform/webhooks.ts
29427
+ init_router();
29428
+ init_worlds();
29429
+ init_webhooks();
29430
+ init_shared();
29431
+ var POLL_MS = 1e3;
29432
+ var POLL_MIN_MS = 100;
29433
+ var BACKOFF_MIN_MS = 1e3;
29434
+ var BACKOFF_MAX_MS = 3e4;
29435
+ var PASSING_STATUSES = /* @__PURE__ */ new Set([408, 429]);
29436
+ var PASSING_CONFLICTS = /* @__PURE__ */ new Set(["session_starting", "session_recovering"]);
29437
+ var POLL_MAX_MS = 36e5;
29438
+ function permanent(error) {
29439
+ if (!(error instanceof ApiError)) return false;
29440
+ const passing = error.status === 409 && PASSING_CONFLICTS.has(error.code ?? "");
29441
+ return error.status >= 400 && error.status < 500 && !PASSING_STATUSES.has(error.status) && !passing;
29442
+ }
29443
+ function events(list) {
29444
+ return list.length ? list.join(",") : "*";
29445
+ }
29446
+ function scope(values) {
29447
+ const narrowed = Object.entries(values).filter(([, held2]) => held2.length);
29448
+ return narrowed.map(([name, held2]) => `${name}=${held2.join(",")}`).join(" ") || "-";
29449
+ }
29450
+ function listingLines(listing) {
29451
+ if (!listing.declared) return ["This world declares no [webhooks]."];
29452
+ const rows = listing.subscriptions.map((sub) => [
29453
+ sub.url ?? "-",
29454
+ events(sub.events),
29455
+ scope(sub.scope),
29456
+ sub.enabled ? "on" : "off",
29457
+ String(sub.sent)
29458
+ ]);
29459
+ if (rows.length === 0) return ["No webhooks registered."];
29460
+ const table3 = textTable(rows, ["URL", "EVENTS", "SCOPE", "STATE", "SENT"]);
29461
+ return listing.truncated ? [...table3, `(the first ${rows.length} subscriptions)`] : table3;
29462
+ }
29463
+ function forwardTarget(args) {
29464
+ const target = arg.str(args, "forward-to") ?? "";
29465
+ let url;
29466
+ try {
29467
+ url = new URL(target);
29468
+ } catch {
29469
+ throw new CliError("--forward-to must be an http(s) URL, e.g. http://localhost:3000/webhooks");
29470
+ }
29471
+ if (url.protocol !== "http:" && url.protocol !== "https:")
29472
+ throw new CliError("--forward-to must be an http(s) URL, e.g. http://localhost:3000/webhooks");
29473
+ if (url.username || url.password)
29474
+ throw new CliError("--forward-to carries no user:password; a receiver's own check reads the signature");
29475
+ return url.toString();
29476
+ }
29477
+ function forwardedLine(item) {
29478
+ const { delivery, answer } = item;
29479
+ const answered = answer.status ? String(answer.status) : `no answer (${answer.error ?? "unreachable"})`;
29480
+ return `${delivery.eventType} ${delivery.id} \u2192 ${answered} ${answer.durationMs} ms`;
29481
+ }
29482
+ function report(ctx, args, forwarded) {
29483
+ for (const item of forwarded)
29484
+ if (args.flags.json === true) ctx.stdout(JSON.stringify({ ...item.answer, eventType: item.delivery.eventType }));
29485
+ else ctx.stdout(forwardedLine(item));
29486
+ }
29487
+ var sleep5 = (ms, signal) => new Promise((wake) => {
29488
+ const timer = setTimeout(wake, ms);
29489
+ signal.addEventListener("abort", () => (clearTimeout(timer), wake()), { once: true });
29490
+ });
29491
+ async function listen(forwarder, ctx, args) {
29492
+ const stop = new AbortController();
29493
+ const halt = () => stop.abort();
29494
+ process.once("SIGINT", halt);
29495
+ process.once("SIGTERM", halt);
29496
+ const once = arg.bool(args, "once");
29497
+ const interval = arg.int(args, "interval-ms") ?? POLL_MS;
29498
+ let backoff = Math.max(interval, BACKOFF_MIN_MS);
29499
+ let started = false;
29500
+ try {
29501
+ while (!stop.signal.aborted) {
29502
+ let polled;
29503
+ try {
29504
+ if (!started) await forwarder.start(once || arg.bool(args, "replay"));
29505
+ started = true;
29506
+ polled = await forwarder.round();
29507
+ } catch (error) {
29508
+ if (once || permanent(error)) throw error;
29509
+ ctx.stderr(`poll failed (${error instanceof Error ? error.message : String(error)}); retrying in ${backoff} ms`);
29510
+ await sleep5(backoff, stop.signal);
29511
+ backoff = Math.min(backoff * 2, BACKOFF_MAX_MS);
29512
+ continue;
29513
+ }
29514
+ backoff = Math.max(interval, BACKOFF_MIN_MS);
29515
+ const { page, forwarded } = polled;
29516
+ if (page.reset) ctx.stderr("the session's feed started over (a restart or a move); forwarding from its start");
29517
+ if (page.missed) ctx.stderr(`${page.missed} delivery(ies) left the session's feed before they were read`);
29518
+ report(ctx, args, forwarded);
29519
+ if (once && !page.more) break;
29520
+ if (!page.more) await sleep5(interval, stop.signal);
29521
+ }
29522
+ } finally {
29523
+ process.off("SIGINT", halt);
29524
+ process.off("SIGTERM", halt);
29525
+ await forwarder.settle().catch((error) => {
29526
+ ctx.stderr(`the last answers were not sent: ${error instanceof Error ? error.message : String(error)}`);
29527
+ if (!stop.signal.aborted) throw error;
29528
+ });
29529
+ }
29530
+ }
29531
+ function registerWebhookCommands(root) {
29532
+ const session = root.group("worlds", "Build, seed, serve and run worlds.").group("session", "Live world sessions with api/ui/browser surfaces.");
29533
+ session.command({
29534
+ name: "webhooks",
29535
+ help: "The webhooks the session's world declares: each subscription and how many deliveries it was sent.",
29536
+ positionals: [{ name: "session_id", help: "Session id." }],
29537
+ flags: [JSON_OUTPUT_FLAG, HOST_FLAG],
29538
+ notes: "Only a World Host session's world sends webhooks; it declares them in connector.toml [webhooks].\nForward them to a receiver on this machine with `gateway worlds session listen <id> --forward-to <url>`.",
29539
+ run: async (args, ctx) => {
29540
+ const listing = await listWebhooks(worldsOptions(credentials(args)), args.positionals[0], {
29541
+ tail: true,
29542
+ limit: 1
29543
+ });
29544
+ emit(ctx, args, listing, () => listingLines(listing));
29545
+ }
29546
+ });
29547
+ session.command({
29548
+ name: "listen",
29549
+ help: "Forward every webhook the session's world sends to a URL, signed as the vendor signs it.",
29550
+ positionals: [{ name: "session_id", help: "Session id." }],
29551
+ flags: [
29552
+ { name: "forward-to", help: "Where each delivery is POSTed: an http(s) URL (http://localhost:3000/webhooks)." },
29553
+ { name: "replay", help: "Also forward the deliveries the session already holds (up to 500), not only new ones.", boolean: true },
29554
+ { name: "interval-ms", help: "How long to wait between polls when nothing is new.", default: String(POLL_MS) },
29555
+ { name: "once", help: "Forward every delivery the session holds now, then exit (implies --replay).", boolean: true },
29556
+ JSON_OUTPUT_FLAG,
29557
+ HOST_FLAG
29558
+ ],
29559
+ notes: "Each delivery keeps its headers (svix-signature, X-Hub-Signature-256, ...) and exact body, so the receiver\nverifies it with the secret the world gave when the webhook was registered. The receiver's status goes back\nto the world's request ledger (`gateway worlds requests <slug> --via webhook`), once per delivery. Only deliveries\nsent from now are forwarded unless --replay; a Svix receiver refuses one older than about 5 minutes. Ctrl-C stops.",
29560
+ run: async (args, ctx) => {
29561
+ const target = forwardTarget(args);
29562
+ const interval = arg.int(args, "interval-ms") ?? POLL_MS;
29563
+ if (interval < POLL_MIN_MS || interval > POLL_MAX_MS)
29564
+ throw new CliError(`--interval-ms is from ${POLL_MIN_MS} to ${POLL_MAX_MS}`);
29565
+ const forwarder = new WorldWebhookForwarder(worldsOptions(credentials(args)), args.positionals[0], target);
29566
+ if (args.flags.json !== true) ctx.stderr(`forwarding ${args.positionals[0]} webhooks to ${target}`);
29567
+ await listen(forwarder, ctx, args);
29568
+ }
29569
+ });
29570
+ }
29571
+
29224
29572
  // src/cli/platform/index.ts
29225
29573
  init_skill();
29226
29574
 
@@ -29385,7 +29733,7 @@ function registerTaskEditVerbs(root) {
29385
29733
  }
29386
29734
 
29387
29735
  // src/cli/platform/taskGradeVerbs.ts
29388
- var fs54 = __toESM(require("fs"));
29736
+ var fs55 = __toESM(require("fs"));
29389
29737
  init_router();
29390
29738
  init_worlds();
29391
29739
  init_shared();
@@ -29446,7 +29794,7 @@ function regradeRefusal(regrade) {
29446
29794
  return null;
29447
29795
  }
29448
29796
  function trialTarget(positional, version) {
29449
- if (!fs54.existsSync(positional)) return { taskId: positional, ...version === void 0 ? {} : { version } };
29797
+ if (!fs55.existsSync(positional)) return { taskId: positional, ...version === void 0 ? {} : { version } };
29450
29798
  if (version !== void 0) throw new CliError("--version goes with a task id, not a spec file");
29451
29799
  return { spec: readTaskSpec(positional, "task") };
29452
29800
  }
@@ -29601,7 +29949,7 @@ function registerTaskRunSet(root) {
29601
29949
  }
29602
29950
 
29603
29951
  // src/cli/platform/traces.ts
29604
- var fs55 = __toESM(require("fs"));
29952
+ var fs56 = __toESM(require("fs"));
29605
29953
  init_config();
29606
29954
  init_router();
29607
29955
 
@@ -29820,7 +30168,7 @@ function registerTracesCommands(root) {
29820
30168
  const scratch = toDrive ? scratchFile("traces.jsonl") : null;
29821
30169
  const file = toStdout ? null : scratch?.file ?? out;
29822
30170
  try {
29823
- const sink = file ? fs55.createWriteStream(file) : null;
30171
+ const sink = file ? fs56.createWriteStream(file) : null;
29824
30172
  const write = (record) => {
29825
30173
  const line = JSON.stringify(record) + "\n";
29826
30174
  if (sink) sink.write(line);
@@ -29938,8 +30286,8 @@ function registerTracesCommands(root) {
29938
30286
  });
29939
30287
  }
29940
30288
  function readFile2(file) {
29941
- if (!fs55.existsSync(file)) throw new CliError(`${file} does not exist`, 1);
29942
- return fs55.readFileSync(file, "utf8");
30289
+ if (!fs56.existsSync(file)) throw new CliError(`${file} does not exist`, 1);
30290
+ return fs56.readFileSync(file, "utf8");
29943
30291
  }
29944
30292
 
29945
30293
  // src/cli/platform/worldData/chunks.ts
@@ -29985,8 +30333,8 @@ var TreeChunks = class _TreeChunks {
29985
30333
  const paths = new StagedPaths(this.files);
29986
30334
  try {
29987
30335
  await paths.stage(this.ctx);
29988
- const report = await this.cut(paths.list);
29989
- printJson(this.ctx, report);
30336
+ const report2 = await this.cut(paths.list);
30337
+ printJson(this.ctx, report2);
29990
30338
  return 0;
29991
30339
  } finally {
29992
30340
  paths.dispose();
@@ -30126,6 +30474,7 @@ function registerPlatformCommands(root) {
30126
30474
  registerWorldCommands(root);
30127
30475
  registerSessionCommands(root);
30128
30476
  registerRequestCommands(root);
30477
+ registerWebhookCommands(root);
30129
30478
  registerTaskCommands(root);
30130
30479
  registerTaskRunSet(root);
30131
30480
  registerTaskEditVerbs(root);
@@ -30148,8 +30497,8 @@ function registerPlatformCommands(root) {
30148
30497
  init_schema();
30149
30498
 
30150
30499
  // src/cli/runtime/connector.ts
30151
- var fs56 = __toESM(require("fs"));
30152
- var path42 = __toESM(require("path"));
30500
+ var fs57 = __toESM(require("fs"));
30501
+ var path43 = __toESM(require("path"));
30153
30502
  init_router();
30154
30503
  init_config();
30155
30504
  init_local();
@@ -30183,10 +30532,10 @@ function wireParams(params) {
30183
30532
  return names.size === list.length ? Object.fromEntries(list) : list;
30184
30533
  }
30185
30534
  function requireConnectorToml(dir) {
30186
- const file = path42.join(dir, "connector.toml");
30187
- if (!fs56.existsSync(file))
30535
+ const file = path43.join(dir, "connector.toml");
30536
+ if (!fs57.existsSync(file))
30188
30537
  throw new CliError(`${dir} holds no connector.toml`, 1);
30189
- return fs56.readFileSync(file, "utf8");
30538
+ return fs57.readFileSync(file, "utf8");
30190
30539
  }
30191
30540
  function renderConnection(spec) {
30192
30541
  const lines = [`${spec.slug} ${spec.baseUrl} auth=${spec.auth}`];
@@ -30205,7 +30554,7 @@ function undeclaredParams(record) {
30205
30554
  return [];
30206
30555
  }
30207
30556
  }
30208
- var sleep5 = (ms) => new Promise((r) => setTimeout(r, ms));
30557
+ var sleep6 = (ms) => new Promise((r) => setTimeout(r, ms));
30209
30558
  async function resolveEnvironmentId2(creds, ref) {
30210
30559
  const listing = await api(
30211
30560
  creds,
@@ -30220,7 +30569,7 @@ async function remoteCapture(creds, world, opts, ctx) {
30220
30569
  const specText = requireConnectorToml(world);
30221
30570
  const containerId = await resolveEnvironmentId2(
30222
30571
  creds,
30223
- opts.environment ?? path42.basename(path42.resolve(world))
30572
+ opts.environment ?? path43.basename(path43.resolve(world))
30224
30573
  );
30225
30574
  const base = `/api/public/environments/${encodeURIComponent(containerId)}`;
30226
30575
  const params = wireParams(opts.params);
@@ -30257,7 +30606,7 @@ async function remoteCapture(creds, world, opts, ctx) {
30257
30606
  `Remote capture still ${view.stage} after ${opts.timeoutSeconds}s; poll it with the request id ${requestId}`,
30258
30607
  1
30259
30608
  );
30260
- await sleep5(opts.pollMs ?? 5e3);
30609
+ await sleep6(opts.pollMs ?? 5e3);
30261
30610
  }
30262
30611
  const slugPrefix = `worlds/${view.worldSlug}/`;
30263
30612
  const written = [];
@@ -30277,18 +30626,18 @@ async function remoteCapture(creds, world, opts, ctx) {
30277
30626
  const res = await fetch(info.url);
30278
30627
  if (!res.ok)
30279
30628
  throw new CliError(`download ${drivePath2} -> ${res.status}`, 1);
30280
- const destination = path42.join(world, relative6);
30281
- fs56.mkdirSync(path42.dirname(destination), { recursive: true });
30629
+ const destination = path43.join(world, relative6);
30630
+ fs57.mkdirSync(path43.dirname(destination), { recursive: true });
30282
30631
  const bytes = Buffer.from(await res.arrayBuffer());
30283
- fs56.writeFileSync(destination, bytes);
30632
+ fs57.writeFileSync(destination, bytes);
30284
30633
  written.push(relative6);
30285
30634
  for (const name of undeclaredParams(bytes))
30286
30635
  ctx.stderr(
30287
30636
  `# note: ${name} is not declared by operation ${opts.op} in connector.toml; sent as given`
30288
30637
  );
30289
30638
  }
30290
- const manifestPath2 = path42.join(world, CAPTURES, MANIFEST);
30291
- const existing = fs56.existsSync(manifestPath2) ? JSON.parse(fs56.readFileSync(manifestPath2, "utf8")) : [];
30639
+ const manifestPath2 = path43.join(world, CAPTURES, MANIFEST);
30640
+ const existing = fs57.existsSync(manifestPath2) ? JSON.parse(fs57.readFileSync(manifestPath2, "utf8")) : [];
30292
30641
  const known = new Set(
30293
30642
  existing.map(
30294
30643
  (e) => e && typeof e === "object" ? e.file : void 0
@@ -30301,13 +30650,14 @@ async function remoteCapture(creds, world, opts, ctx) {
30301
30650
  existing.push(entry);
30302
30651
  known.add(file);
30303
30652
  }
30304
- fs56.mkdirSync(path42.dirname(manifestPath2), { recursive: true });
30305
- fs56.writeFileSync(manifestPath2, sortedJson(existing, 1) + "\n");
30653
+ fs57.mkdirSync(path43.dirname(manifestPath2), { recursive: true });
30654
+ fs57.writeFileSync(manifestPath2, sortedJson(existing, 1) + "\n");
30306
30655
  return written;
30307
30656
  }
30657
+ var PASSING_SCHEMA_STATES = /* @__PURE__ */ new Set(["ok", "no-schema", "no-body"]);
30308
30658
  function outcomeOk(outcome) {
30309
30659
  if (typeof outcome.ok === "boolean") return outcome.ok;
30310
- return outcome.documented && outcome.status != null && (outcome.expected ?? []).includes(String(outcome.status)) && (outcome.schema === "ok" || outcome.schema === "no-schema");
30660
+ return outcome.documented && outcome.status != null && (outcome.expected ?? []).includes(String(outcome.status)) && PASSING_SCHEMA_STATES.has(outcome.schema ?? "");
30311
30661
  }
30312
30662
  function renderConformOutcome(outcome) {
30313
30663
  const mark = !outcome.documented ? " ? " : outcomeOk(outcome) ? " ok " : " FAIL";
@@ -30329,7 +30679,7 @@ function registerConnectorCommands2(connector) {
30329
30679
  ],
30330
30680
  flags: [HOST_FLAG3],
30331
30681
  run: async (args, ctx) => {
30332
- const dir = path42.resolve(args.positionals[0]);
30682
+ const dir = path43.resolve(args.positionals[0]);
30333
30683
  requireConnectorToml(dir);
30334
30684
  const creds = credentialsForRuntime(arg.str(args, "host"));
30335
30685
  const res = await runtime(creds, {
@@ -30385,7 +30735,7 @@ and runs on this machine when a python3 >= ${MIN_PYTHON_LABEL} is installed (the
30385
30735
  HOST_FLAG3
30386
30736
  ],
30387
30737
  run: async (args, ctx) => {
30388
- const dir = path42.resolve(args.positionals[0]);
30738
+ const dir = path43.resolve(args.positionals[0]);
30389
30739
  const op = arg.str(args, "op");
30390
30740
  if (!op) throw new CliError("capture needs --op");
30391
30741
  if (!arg.bool(args, "remote")) {
@@ -30435,17 +30785,17 @@ and runs on this machine when a python3 >= ${MIN_PYTHON_LABEL} is installed (the
30435
30785
  HOST_FLAG3
30436
30786
  ],
30437
30787
  run: async (args, ctx) => {
30438
- const dir = path42.resolve(args.positionals[0]);
30788
+ const dir = path43.resolve(args.positionals[0]);
30439
30789
  const documents = arg.list(args, "openapi");
30440
30790
  if (!documents.length)
30441
30791
  throw new CliError("conform needs --openapi FILE (repeatable)");
30442
30792
  requireConnectorToml(dir);
30443
30793
  const openapi = documents.map((file) => {
30444
- if (!fs56.existsSync(file))
30794
+ if (!fs57.existsSync(file))
30445
30795
  throw new CliError(`--openapi ${file} does not exist`);
30446
30796
  return {
30447
- path: path42.basename(file),
30448
- content: fs56.readFileSync(file).toString("base64")
30797
+ path: path43.basename(file),
30798
+ content: fs57.readFileSync(file).toString("base64")
30449
30799
  };
30450
30800
  });
30451
30801
  const limit = arg.int(args, "limit");
@@ -30456,14 +30806,14 @@ and runs on this machine when a python3 >= ${MIN_PYTHON_LABEL} is installed (the
30456
30806
  openapi,
30457
30807
  ...limit !== void 0 ? { max_operations: limit } : {}
30458
30808
  });
30459
- const report = res.report ?? {};
30460
- for (const outcome of report.operations ?? report.outcomes ?? [])
30809
+ const report2 = res.report ?? {};
30810
+ for (const outcome of report2.operations ?? report2.outcomes ?? [])
30461
30811
  ctx.stdout(renderConformOutcome(outcome));
30462
- const summary2 = report.summary ?? {};
30812
+ const summary2 = report2.summary ?? {};
30463
30813
  ctx.stdout(JSON.stringify(summary2));
30464
30814
  const out = arg.str(args, "out");
30465
30815
  if (out) {
30466
- fs56.writeFileSync(out, JSON.stringify(report, null, 1) + "\n");
30816
+ fs57.writeFileSync(out, JSON.stringify(report2, null, 1) + "\n");
30467
30817
  ctx.stdout(`report: ${out}`);
30468
30818
  }
30469
30819
  return Number(summary2.status_mismatch) || Number(summary2.schema_violations) ? 1 : 0;
@@ -30491,16 +30841,16 @@ and runs on this machine when a python3 >= ${MIN_PYTHON_LABEL} is installed (the
30491
30841
  ],
30492
30842
  notes: "An ingest stops at the first row the contract refuses; --dry-run reports all of them at once, grouped\nby capture, entity and pointer, so a forty-capture world is fixed in one pass. Exit 2 when any row is refused.",
30493
30843
  run: async (args, ctx) => {
30494
- const dir = path42.resolve(args.positionals[0]);
30495
- if (!fs56.existsSync(path42.join(dir, CAPTURES)))
30844
+ const dir = path43.resolve(args.positionals[0]);
30845
+ if (!fs57.existsSync(path43.join(dir, CAPTURES)))
30496
30846
  throw new CliError(
30497
30847
  `${dir} holds no ${CAPTURES}/ \u2014 run \`connector capture --remote\` first`,
30498
30848
  1
30499
30849
  );
30500
30850
  const batchId = arg.str(args, "batch-id");
30501
30851
  const dryRun = arg.bool(args, "dry-run");
30502
- const report = arg.str(args, "report");
30503
- if (report && !dryRun)
30852
+ const report2 = arg.str(args, "report");
30853
+ if (report2 && !dryRun)
30504
30854
  throw new CliError("--report belongs to `connector ingest --dry-run`");
30505
30855
  const creds = credentialsForRuntime(arg.str(args, "host"));
30506
30856
  if (dryRun) {
@@ -30522,12 +30872,12 @@ and runs on this machine when a python3 >= ${MIN_PYTHON_LABEL} is installed (the
30522
30872
  ctx.stdout(
30523
30873
  ` ${refusal.capture ?? "?"} ${refusal.pointer}: ${refusal.detail}`
30524
30874
  );
30525
- if (report) {
30526
- fs56.writeFileSync(
30527
- report,
30875
+ if (report2) {
30876
+ fs57.writeFileSync(
30877
+ report2,
30528
30878
  refusals.map((r) => JSON.stringify(r) + "\n").join("")
30529
30879
  );
30530
- ctx.stdout(`report: ${report}`);
30880
+ ctx.stdout(`report: ${report2}`);
30531
30881
  }
30532
30882
  return refusals.length ? 2 : 0;
30533
30883
  }
@@ -30550,8 +30900,8 @@ and runs on this machine when a python3 >= ${MIN_PYTHON_LABEL} is installed (the
30550
30900
  }
30551
30901
 
30552
30902
  // src/cli/runtime/run.ts
30553
- var fs57 = __toESM(require("fs"));
30554
- var path43 = __toESM(require("path"));
30903
+ var fs58 = __toESM(require("fs"));
30904
+ var path44 = __toESM(require("path"));
30555
30905
  init_router();
30556
30906
  init_config();
30557
30907
  init_shared();
@@ -30567,11 +30917,11 @@ var HOST_FLAG4 = {
30567
30917
  env: "GATEWAY_HOST"
30568
30918
  };
30569
30919
  function resolveTarget(target, versionFlag) {
30570
- if (fs57.existsSync(target) && fs57.statSync(target).isDirectory()) {
30571
- const dir = path43.resolve(target);
30920
+ if (fs58.existsSync(target) && fs58.statSync(target).isDirectory()) {
30921
+ const dir = path44.resolve(target);
30572
30922
  const meta = readLocalMeta(dir);
30573
30923
  return {
30574
- slug: meta?.slug ?? path43.basename(dir),
30924
+ slug: meta?.slug ?? path44.basename(dir),
30575
30925
  ref: meta?.branch ?? null,
30576
30926
  versionId: versionFlag ?? meta?.versionId ?? null,
30577
30927
  dir
@@ -30799,8 +31149,8 @@ function registerRunCommands2(worlds) {
30799
31149
  }
30800
31150
  ],
30801
31151
  run: async (args, ctx) => {
30802
- const dir = path43.resolve(args.positionals[0]);
30803
- if (!fs57.existsSync(dir) || !fs57.statSync(dir).isDirectory())
31152
+ const dir = path44.resolve(args.positionals[0]);
31153
+ if (!fs58.existsSync(dir) || !fs58.statSync(dir).isDirectory())
30804
31154
  throw new CliError(`path is not a directory: ${args.positionals[0]}`);
30805
31155
  const agentFile = arg.str(args, "agent");
30806
31156
  const runConfig = arg.str(args, "run-config");
@@ -30828,7 +31178,7 @@ function registerRunCommands2(worlds) {
30828
31178
  const summaryFile = arg.str(args, "summary-file");
30829
31179
  const agent = agentFile ? await AgentModule.parse(agentFile).sessionAgent() : null;
30830
31180
  if (runConfig) {
30831
- const report = await validateWorld(dir, {
31181
+ const report2 = await validateWorld(dir, {
30832
31182
  slug,
30833
31183
  runConfig,
30834
31184
  branch,
@@ -30837,15 +31187,15 @@ function registerRunCommands2(worlds) {
30837
31187
  onProgress: (line) => ctx.stderr(line),
30838
31188
  options
30839
31189
  });
30840
- const { markdown, ...summary3 } = report;
31190
+ const { markdown, ...summary3 } = report2;
30841
31191
  ctx.stdout(JSON.stringify(summary3, null, 2));
30842
31192
  if (summaryFile)
30843
- fs57.writeFileSync(
31193
+ fs58.writeFileSync(
30844
31194
  summaryFile,
30845
31195
  JSON.stringify(summary3, null, 2) + "\n"
30846
31196
  );
30847
31197
  appendStepSummary(markdown);
30848
- return report.ok ? 0 : 1;
31198
+ return report2.ok ? 0 : 1;
30849
31199
  }
30850
31200
  let pushed;
30851
31201
  if (pinnedVersion) {
@@ -30891,7 +31241,7 @@ function registerRunCommands2(worlds) {
30891
31241
  const out = { ...summary2, branch, contentHash: pushed.contentHash };
30892
31242
  ctx.stdout(JSON.stringify(out, null, 2));
30893
31243
  if (summaryFile)
30894
- fs57.writeFileSync(summaryFile, JSON.stringify(out, null, 2) + "\n");
31244
+ fs58.writeFileSync(summaryFile, JSON.stringify(out, null, 2) + "\n");
30895
31245
  const rows = [
30896
31246
  ["avg reward", summary2.mean === null ? "n/a" : summary2.mean.toFixed(3)],
30897
31247
  ["tasks", String(summary2.results.length)],
@@ -30913,8 +31263,8 @@ function registerRunCommands2(worlds) {
30913
31263
  }
30914
31264
 
30915
31265
  // src/cli/runtime/serve.ts
30916
- var fs58 = __toESM(require("fs"));
30917
- var path44 = __toESM(require("path"));
31266
+ var fs59 = __toESM(require("fs"));
31267
+ var path45 = __toESM(require("path"));
30918
31268
  init_router();
30919
31269
  init_config();
30920
31270
  init_worlds();
@@ -30988,14 +31338,14 @@ GATEWAY_RUNTIME=platform forces the hosted path.`,
30988
31338
  run: async (args, ctx) => {
30989
31339
  const target = args.positionals[0];
30990
31340
  const local = localRuntime();
30991
- if (local && fs58.existsSync(target) && fs58.statSync(target).isDirectory()) {
31341
+ if (local && fs59.existsSync(target) && fs59.statSync(target).isDirectory()) {
30992
31342
  const port = arg.int(args, "port") ?? 8080;
30993
31343
  if (!Number.isInteger(port) || port < 0 || port > 65535)
30994
31344
  throw new CliError(
30995
31345
  `--port must be a port number (got ${String(args.flags.port)})`
30996
31346
  );
30997
31347
  if (port !== 0) await assertPortFree(port);
30998
- const argv = ["serve", path44.resolve(target), "--port", String(port)];
31348
+ const argv = ["serve", path45.resolve(target), "--port", String(port)];
30999
31349
  const apiKey = arg.str(args, "api-key");
31000
31350
  if (apiKey) argv.push("--api-key", apiKey);
31001
31351
  const uiPort = arg.str(args, "ui-port");
@@ -31005,11 +31355,11 @@ GATEWAY_RUNTIME=platform forces the hosted path.`,
31005
31355
  const task = arg.str(args, "task");
31006
31356
  if (task) argv.push("--task", task);
31007
31357
  ctx.stderr(
31008
- `# serving ${path44.resolve(target)} on http://127.0.0.1:${port} (local runtime: ${local.python})`
31358
+ `# serving ${path45.resolve(target)} on http://127.0.0.1:${port} (local runtime: ${local.python})`
31009
31359
  );
31010
31360
  return localModule(argv, local);
31011
31361
  }
31012
- if (!local && fs58.existsSync(target) && fs58.statSync(target).isDirectory())
31362
+ if (!local && fs59.existsSync(target) && fs59.statSync(target).isDirectory())
31013
31363
  ctx.stderr(
31014
31364
  `# ${localRuntimeReason()}
31015
31365
  # A local directory is served here only by the bundled Python runtime; without one the CLI can only open a hosted session of a world already published (gateway worlds create <slug> --from ${target}), which needs a login (gateway auth login).`
@@ -31022,17 +31372,17 @@ GATEWAY_RUNTIME=platform forces the hosted path.`,
31022
31372
  };
31023
31373
  let slugRef = target;
31024
31374
  let versionId;
31025
- if (fs58.existsSync(target) && fs58.statSync(target).isDirectory()) {
31026
- const dir = path44.resolve(target);
31375
+ if (fs59.existsSync(target) && fs59.statSync(target).isDirectory()) {
31376
+ const dir = path45.resolve(target);
31027
31377
  const meta = readLocalMeta(dir);
31028
- const slug = meta?.slug ?? path44.basename(dir);
31378
+ const slug = meta?.slug ?? path45.basename(dir);
31029
31379
  slugRef = meta?.branch ? `${slug}@${meta.branch}` : slug;
31030
31380
  versionId = meta?.versionId;
31031
31381
  }
31032
31382
  ctx.stderr(
31033
31383
  "`worlds serve` runs a local session with the Python runtime; opening a hosted api-surface session instead."
31034
31384
  );
31035
- if (!local && !(fs58.existsSync(target) && fs58.statSync(target).isDirectory())) ctx.stderr(`# ${localRuntimeReason()}`);
31385
+ if (!local && !(fs59.existsSync(target) && fs59.statSync(target).isDirectory())) ctx.stderr(`# ${localRuntimeReason()}`);
31036
31386
  let scenario = arg.str(args, "scenario") ?? arg.str(args, "task");
31037
31387
  if (!scenario) {
31038
31388
  const world = await openWorld(slugRef, options);
@@ -31070,17 +31420,18 @@ GATEWAY_RUNTIME=platform forces the hosted path.`,
31070
31420
  }
31071
31421
 
31072
31422
  // src/cli/runtime/test.ts
31073
- var fs59 = __toESM(require("fs"));
31074
- var path45 = __toESM(require("path"));
31423
+ var fs60 = __toESM(require("fs"));
31424
+ var path46 = __toESM(require("path"));
31075
31425
  init_router();
31076
31426
  init_shared();
31077
31427
  init_local();
31078
31428
  init_config();
31079
31429
  init_client();
31080
- function renderWorldTestReport(report) {
31430
+ var PYTHON_MARKS = { passed: " ok ", skipped: "skip" };
31431
+ function renderWorldTestReport(report2) {
31081
31432
  const lines = [];
31082
31433
  let group = null;
31083
- for (const c of report.cases ?? []) {
31434
+ for (const c of report2.cases ?? []) {
31084
31435
  const own = c.group?.trim() || "";
31085
31436
  if (own !== (group ?? "") || group === null) {
31086
31437
  group = own;
@@ -31092,7 +31443,15 @@ function renderWorldTestReport(report) {
31092
31443
  if (c.description) lines.push(` ${c.description}`);
31093
31444
  for (const p of c.problems ?? []) lines.push(` ! ${p}`);
31094
31445
  }
31095
- const py = report.python;
31446
+ const py = report2.python;
31447
+ let pyGroup = null;
31448
+ for (const c of py?.cases ?? []) {
31449
+ if (c.group !== pyGroup) lines.push(`== ${c.group ?? "python tests"}`);
31450
+ pyGroup = c.group ?? null;
31451
+ lines.push(`${PYTHON_MARKS[c.status] ?? "FAIL"} ${c.name}`);
31452
+ for (const p of c.problems ?? []) lines.push(` ! ${p.split("\n")[0]}`);
31453
+ }
31454
+ if (py?.cases_omitted) lines.push(` \u2026 ${py.cases_omitted} more not shown`);
31096
31455
  if (py && py.status !== "none") {
31097
31456
  const detail = py.reason ?? (py.status === "skipped" ? "skipped" : `${py.tests ?? 0} tests, ${py.failures ?? 0} failures, ${py.errors ?? 0} errors`);
31098
31457
  lines.push(
@@ -31112,7 +31471,7 @@ function registerTestCommand(worlds) {
31112
31471
  positionals: [
31113
31472
  {
31114
31473
  name: "path",
31115
- help: "World directory (a schema world, or its api bundle), or a platform slug[@versionId] to run the suite on the platform."
31474
+ help: "World directory (a schema world, or its api bundle), or a platform slug[@ref] (a branch, tag, semver or version id) to run the suite on the platform."
31116
31475
  }
31117
31476
  ],
31118
31477
  flags: [
@@ -31131,15 +31490,15 @@ function registerTestCommand(worlds) {
31131
31490
  notes: 'A world\'s tests live in <world>/tests/ and run in order against ONE session of the world, so a case sees\nwhat the cases before it wrote. *.json files hold cases of two shapes:\n {name, tool: "send_message", args: {...}, expect} a tool call (root tools by name, a dependency\'s as alias.tool);\n {name, request: {method, path, query?, headers?, body?, auth?}, expect} an HTTP call on the vendor routes (connector.toml).\nexpect is {status?, json?, length?, contains?, headers?}; a refused call (unknown tool, arguments off the\nschema) answers 400 with {error, detail}; a handler that raises answers 500 with {error: its message}.\ntests/test_*.py run under pytest with WORLD_DIR, WORLD_URL, WORLD_API_KEY, WORLD_ADMIN_TOKEN (the session\'s\nkey to its /__world/* routes, sent as X-World-Admin-Token) and, for a world with [ui], WORLD_UI_URL (its\npage on its own origin) set; a Python without pytest FAILS the suite, it never skips it.\nNo tests/ directory passes as zero cases. With `[actions] on_push = ["tests"]` in gateway-env.toml the\nplatform runs the same suite on every push; `gateway bench tests <slug>` reads those runs. Exit 1 when any\ntest fails.',
31132
31491
  run: async (args, ctx) => {
31133
31492
  const target = args.positionals[0] ?? ".";
31134
- const dir = path45.resolve(target);
31135
- if (!fs59.existsSync(dir) || !fs59.statSync(dir).isDirectory()) {
31493
+ const dir = path46.resolve(target);
31494
+ if (!fs60.existsSync(dir) || !fs60.statSync(dir).isDirectory()) {
31136
31495
  if (/[\/\\]/.test(target) || target.startsWith("."))
31137
31496
  throw new CliError(`Not a directory: ${dir}`, 1);
31138
31497
  const creds2 = resolveCredentials(arg.str(args, "host"));
31139
31498
  const [slug, ref] = target.split("@");
31140
31499
  const scenario2 = arg.str(args, "scenario");
31141
31500
  const body = {
31142
- ...ref ? { versionId: ref } : {},
31501
+ ...ref ? { ref } : {},
31143
31502
  ...scenario2 ? { scenario: scenario2 } : {}
31144
31503
  };
31145
31504
  const url = `/api/public/worlds/${encodeURIComponent(slug)}/tests`;
@@ -31175,7 +31534,7 @@ function registerTestCommand(worlds) {
31175
31534
  if (++misses >= 5) throw error;
31176
31535
  }
31177
31536
  }
31178
- const report2 = run.report ?? {};
31537
+ const report3 = run.report ?? {};
31179
31538
  if (arg.bool(args, "json"))
31180
31539
  ctx.stdout(
31181
31540
  JSON.stringify(
@@ -31184,15 +31543,15 @@ function registerTestCommand(worlds) {
31184
31543
  state: run.state,
31185
31544
  trigger: run.trigger ?? null,
31186
31545
  versionId: run.versionId,
31187
- ...report2
31546
+ ...report3
31188
31547
  },
31189
31548
  null,
31190
31549
  1
31191
31550
  )
31192
31551
  );
31193
31552
  else {
31194
- for (const line of renderWorldTestReport(report2)) ctx.stdout(line);
31195
- const s = run.summary ?? report2.summary ?? {};
31553
+ for (const line of renderWorldTestReport(report3)) ctx.stdout(line);
31554
+ const s = run.summary ?? report3.summary ?? {};
31196
31555
  ctx.stdout(
31197
31556
  `${run.state}: ${s.passed ?? 0} passed, ${s.failed ?? 0} failed, ${s.skipped ?? 0} skipped (run ${run.id}${run.trigger ? `, trigger ${run.trigger}` : ""}, on ${run.versionId})`
31198
31557
  );
@@ -31200,7 +31559,7 @@ function registerTestCommand(worlds) {
31200
31559
  }
31201
31560
  const out2 = arg.str(args, "out");
31202
31561
  if (out2)
31203
- fs59.writeFileSync(
31562
+ fs60.writeFileSync(
31204
31563
  out2,
31205
31564
  JSON.stringify(
31206
31565
  {
@@ -31208,7 +31567,7 @@ function registerTestCommand(worlds) {
31208
31567
  state: run.state,
31209
31568
  trigger: run.trigger ?? null,
31210
31569
  versionId: run.versionId,
31211
- ...report2
31570
+ ...report3
31212
31571
  },
31213
31572
  null,
31214
31573
  1
@@ -31223,14 +31582,14 @@ function registerTestCommand(worlds) {
31223
31582
  ...worldPayload(dir),
31224
31583
  ...scenario ? { scenario } : {}
31225
31584
  });
31226
- const report = res.report ?? {};
31227
- if (arg.bool(args, "json")) ctx.stdout(JSON.stringify(report, null, 1));
31585
+ const report2 = res.report ?? {};
31586
+ if (arg.bool(args, "json")) ctx.stdout(JSON.stringify(report2, null, 1));
31228
31587
  else {
31229
- for (const line of renderWorldTestReport(report)) ctx.stdout(line);
31230
- const s = report.summary ?? {};
31231
- if (!(s.total ?? 0) && !(report.python?.files?.length ?? 0)) {
31232
- const tests = path45.join(dir, "tests");
31233
- const state2 = fs59.existsSync(tests) ? "holds none" : "does not exist";
31588
+ for (const line of renderWorldTestReport(report2)) ctx.stdout(line);
31589
+ const s = report2.summary ?? {};
31590
+ if (!(s.total ?? 0) && !(report2.python?.files?.length ?? 0)) {
31591
+ const tests = path46.join(dir, "tests");
31592
+ const state2 = fs60.existsSync(tests) ? "holds none" : "does not exist";
31234
31593
  ctx.stdout(`no cases: ${tests} ${state2} (see \`gateway worlds test --help\` for the shapes)`);
31235
31594
  }
31236
31595
  ctx.stdout(
@@ -31239,17 +31598,17 @@ function registerTestCommand(worlds) {
31239
31598
  }
31240
31599
  const out = arg.str(args, "out");
31241
31600
  if (out) {
31242
- fs59.writeFileSync(out, JSON.stringify(report, null, 1) + "\n");
31601
+ fs60.writeFileSync(out, JSON.stringify(report2, null, 1) + "\n");
31243
31602
  ctx.stdout(`report: ${out}`);
31244
31603
  }
31245
- return report.summary?.status === "passed" ? 0 : 1;
31604
+ return report2.summary?.status === "passed" ? 0 : 1;
31246
31605
  }
31247
31606
  });
31248
31607
  }
31249
31608
 
31250
31609
  // src/cli/runtime/call.ts
31251
- var fs60 = __toESM(require("fs"));
31252
- var path46 = __toESM(require("path"));
31610
+ var fs61 = __toESM(require("fs"));
31611
+ var path47 = __toESM(require("path"));
31253
31612
  init_router();
31254
31613
  init_session2();
31255
31614
  init_sessionContract();
@@ -31263,8 +31622,8 @@ function parseArgs2(raw, stdin) {
31263
31622
  if (raw === "-") text2 = stdin;
31264
31623
  else if (raw.startsWith("@")) {
31265
31624
  const file = raw.slice(1);
31266
- if (!fs60.existsSync(file)) throw new CliError(`--args ${raw}: ${file} does not exist`);
31267
- text2 = fs60.readFileSync(file, "utf8");
31625
+ if (!fs61.existsSync(file)) throw new CliError(`--args ${raw}: ${file} does not exist`);
31626
+ text2 = fs61.readFileSync(file, "utf8");
31268
31627
  }
31269
31628
  let value;
31270
31629
  try {
@@ -31277,10 +31636,10 @@ function parseArgs2(raw, stdin) {
31277
31636
  return value;
31278
31637
  }
31279
31638
  var SERVED_URL = /^https?:\/\//;
31280
- function settleStatus(report) {
31281
- const code = report.result.status;
31282
- report.status = code >= 200 && code < 300 ? "ok" : code >= 500 ? "error" : "refused";
31283
- return report;
31639
+ function settleStatus(report2) {
31640
+ const code = report2.result.status;
31641
+ report2.status = code >= 200 && code < 300 ? "ok" : code >= 500 ? "error" : "refused";
31642
+ return report2;
31284
31643
  }
31285
31644
  async function sessionVerb(base, verb, body) {
31286
31645
  let response;
@@ -31309,7 +31668,7 @@ function platformFailureBody(detail) {
31309
31668
  }
31310
31669
  async function callHosted(sessionId, tool, args, wants, options) {
31311
31670
  const live = await attachSession(sessionId, options);
31312
- const report = {
31671
+ const report2 = {
31313
31672
  status: "ok",
31314
31673
  tools: (await live.toolkit()).specs.map((spec) => spec.name),
31315
31674
  result: { status: 0, body: null }
@@ -31321,25 +31680,25 @@ async function callHosted(sessionId, tool, args, wants, options) {
31321
31680
  if (mode !== void 0 && mode !== "append" && mode !== "replace")
31322
31681
  throw new CliError("--seed mode must be append or replace");
31323
31682
  const seeded = await live.seed(rows, mode ? { mode } : {});
31324
- report.seed = seeded;
31683
+ report2.seed = seeded;
31325
31684
  }
31326
31685
  try {
31327
31686
  const answer = await live.call(tool, args);
31328
- report.result = isRouteAnswer(answer) ? answer : { status: 200, body: answer };
31687
+ report2.result = isRouteAnswer(answer) ? answer : { status: 200, body: answer };
31329
31688
  } catch (error) {
31330
31689
  if (!(error instanceof WorldSessionCallError)) throw error;
31331
- report.result = { status: 500, body: platformFailureBody(error.message) };
31690
+ report2.result = { status: 500, body: platformFailureBody(error.message) };
31332
31691
  }
31333
- if (wants.state) report.state = await live.state();
31334
- if (wants.grade) report.grade = await live.grade();
31692
+ if (wants.state) report2.state = await live.state();
31693
+ if (wants.grade) report2.grade = await live.grade();
31335
31694
  if (wants.close) {
31336
31695
  await live.close();
31337
- report.closed = true;
31696
+ report2.closed = true;
31338
31697
  }
31339
- return settleStatus(report);
31698
+ return settleStatus(report2);
31340
31699
  }
31341
31700
  function looksLikeSessionId(target) {
31342
- return !target.includes("/") && !target.startsWith(".") && !fs60.existsSync(target);
31701
+ return !target.includes("/") && !target.startsWith(".") && !fs61.existsSync(target);
31343
31702
  }
31344
31703
  async function callServed(base, tool, args, wants) {
31345
31704
  const url = base.replace(/\/+$/, "");
@@ -31349,7 +31708,7 @@ async function callServed(base, tool, args, wants) {
31349
31708
  `${url} is not a served world session: GET /__session/tools answered ${tools.status}.` + (tools.status === 401 || tools.status === 403 || tools.status === 404 ? " A hosted session's api url takes its own token and serves no /__session verbs \u2014 pass the sessionId `gateway worlds session open` printed instead." : ""),
31350
31709
  1
31351
31710
  );
31352
- const report = {
31711
+ const report2 = {
31353
31712
  status: "ok",
31354
31713
  tools: tools.body.tools,
31355
31714
  result: { status: 0, body: null }
@@ -31358,18 +31717,18 @@ async function callServed(base, tool, args, wants) {
31358
31717
  const seeded = await sessionVerb(url, "seed", wants.seed);
31359
31718
  if (seeded.status !== 200)
31360
31719
  throw new CliError(`POST /__session/seed answered ${seeded.status}: ${JSON.stringify(seeded.body)}`, 1);
31361
- report.seed = seeded.body;
31720
+ report2.seed = seeded.body;
31362
31721
  }
31363
31722
  const answer = await sessionVerb(url, "call", { tool, args });
31364
- report.result = answer.status === 200 && answer.body && typeof answer.body === "object" && "status" in answer.body ? answer.body : { status: answer.status, body: answer.body };
31365
- if (wants.state) report.state = (await sessionVerb(url, "state")).body;
31366
- if (wants.grade) report.grade = (await sessionVerb(url, "grade", {})).body;
31723
+ report2.result = answer.status === 200 && answer.body && typeof answer.body === "object" && "status" in answer.body ? answer.body : { status: answer.status, body: answer.body };
31724
+ if (wants.state) report2.state = (await sessionVerb(url, "state")).body;
31725
+ if (wants.grade) report2.grade = (await sessionVerb(url, "grade", {})).body;
31367
31726
  if (wants.close) {
31368
31727
  const closed = await sessionVerb(url, "close", {});
31369
31728
  if (closed.status !== 200) throw new CliError(`POST /__session/close answered ${closed.status}`, 1);
31370
- report.closed = true;
31729
+ report2.closed = true;
31371
31730
  }
31372
- return settleStatus(report);
31731
+ return settleStatus(report2);
31373
31732
  }
31374
31733
  function registerCallCommand(worlds) {
31375
31734
  worlds.command({
@@ -31430,14 +31789,14 @@ Examples:
31430
31789
  throw new CliError(`--${flag} belongs to \`gateway worlds serve\`; the session at ${target} already has its own`);
31431
31790
  const stdin2 = args.flags.args === "-" || args.flags.seed === "-" ? await ctx.stdin() : "";
31432
31791
  const seedRaw2 = arg.str(args, "seed");
31433
- const report2 = await callServed(target, tool, parseArgs2(arg.str(args, "args"), stdin2), {
31792
+ const report3 = await callServed(target, tool, parseArgs2(arg.str(args, "args"), stdin2), {
31434
31793
  ...seedRaw2 === void 0 ? {} : { seed: parseArgs2(seedRaw2, stdin2) },
31435
31794
  state: arg.bool(args, "state"),
31436
31795
  grade: arg.bool(args, "grade"),
31437
31796
  close: arg.bool(args, "close")
31438
31797
  });
31439
- ctx.stdout(JSON.stringify(report2, null, 2));
31440
- return report2.result.status >= 200 && report2.result.status < 300 ? 0 : 1;
31798
+ ctx.stdout(JSON.stringify(report3, null, 2));
31799
+ return report3.result.status >= 200 && report3.result.status < 300 ? 0 : 1;
31441
31800
  }
31442
31801
  if (looksLikeSessionId(target)) {
31443
31802
  for (const flag of ["task", "scenario"])
@@ -31446,7 +31805,7 @@ Examples:
31446
31805
  const stdin2 = args.flags.args === "-" || args.flags.seed === "-" ? await ctx.stdin() : "";
31447
31806
  const seedRaw2 = arg.str(args, "seed");
31448
31807
  try {
31449
- const report2 = await callHosted(
31808
+ const report3 = await callHosted(
31450
31809
  target,
31451
31810
  tool,
31452
31811
  parseArgs2(arg.str(args, "args"), stdin2),
@@ -31458,8 +31817,8 @@ Examples:
31458
31817
  },
31459
31818
  worldsOptions(credentials(args))
31460
31819
  );
31461
- ctx.stdout(JSON.stringify(report2, null, 2));
31462
- return report2.result.status >= 200 && report2.result.status < 300 ? 0 : 1;
31820
+ ctx.stdout(JSON.stringify(report3, null, 2));
31821
+ return report3.result.status >= 200 && report3.result.status < 300 ? 0 : 1;
31463
31822
  } catch (error) {
31464
31823
  if (!(error instanceof WorldCallTooLarge)) throw error;
31465
31824
  ctx.stdout(JSON.stringify(error.toJSON(), null, 2));
@@ -31467,8 +31826,8 @@ Examples:
31467
31826
  }
31468
31827
  }
31469
31828
  if (arg.bool(args, "close")) throw new CliError("--close ends a served or hosted session; pass its url or id instead of a directory");
31470
- const dir = path46.resolve(target);
31471
- if (!fs60.existsSync(dir) || !fs60.statSync(dir).isDirectory()) throw new CliError(`Not a directory: ${dir}`, 1);
31829
+ const dir = path47.resolve(target);
31830
+ if (!fs61.existsSync(dir) || !fs61.statSync(dir).isDirectory()) throw new CliError(`Not a directory: ${dir}`, 1);
31472
31831
  const local = localRuntime();
31473
31832
  if (!local)
31474
31833
  throw new CliError(
@@ -31496,20 +31855,20 @@ Examples:
31496
31855
  );
31497
31856
  const detail = detailFrom(payload);
31498
31857
  if (detail) throw new BridgeRejected(detail);
31499
- const report = settleStatus(payload);
31500
- ctx.stdout(JSON.stringify(report, null, 2));
31501
- return report.result.status >= 200 && report.result.status < 300 ? 0 : 1;
31858
+ const report2 = settleStatus(payload);
31859
+ ctx.stdout(JSON.stringify(report2, null, 2));
31860
+ return report2.result.status >= 200 && report2.result.status < 300 ? 0 : 1;
31502
31861
  }
31503
31862
  });
31504
31863
  }
31505
31864
 
31506
31865
  // src/cli/runtime/scaffold.ts
31507
- var fs64 = __toESM(require("fs"));
31508
- var path49 = __toESM(require("path"));
31866
+ var fs65 = __toESM(require("fs"));
31867
+ var path50 = __toESM(require("path"));
31509
31868
  init_router();
31510
31869
 
31511
31870
  // src/cli/runtime/scaffoldJson.ts
31512
- var fs61 = __toESM(require("fs"));
31871
+ var fs62 = __toESM(require("fs"));
31513
31872
  init_router();
31514
31873
  var PROPERTY_NAME = /^[A-Za-z_][A-Za-z0-9_-]*$/;
31515
31874
  var isObject12 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
@@ -31524,10 +31883,10 @@ function resolveObjectSchema(root, schema) {
31524
31883
  return schema;
31525
31884
  }
31526
31885
  function readJsonFile2(file) {
31527
- if (!fs61.existsSync(file)) throw new CliError(`${file} does not exist; run \`gateway worlds schema init\` first`, 1);
31886
+ if (!fs62.existsSync(file)) throw new CliError(`${file} does not exist; run \`gateway worlds schema init\` first`, 1);
31528
31887
  let parsed;
31529
31888
  try {
31530
- parsed = JSON.parse(fs61.readFileSync(file, "utf8"));
31889
+ parsed = JSON.parse(fs62.readFileSync(file, "utf8"));
31531
31890
  } catch (err) {
31532
31891
  throw new CliError(`${file} is not valid JSON: ${err.message}`, 1);
31533
31892
  }
@@ -31627,7 +31986,7 @@ function declaredRoutes(toml) {
31627
31986
  const params = list("params");
31628
31987
  if (params) current.params = params;
31629
31988
  }
31630
- for (const route of routes) if (!route.methods.length) route.methods.push("GET");
31989
+ for (const route2 of routes) if (!route2.methods.length) route2.methods.push("GET");
31631
31990
  return routes;
31632
31991
  }
31633
31992
  function removeRoute(toml, name) {
@@ -31705,10 +32064,10 @@ function addRoute(toml, spec, declaredEntities2, options = {}) {
31705
32064
  `--action ${spec.api.action} writes, but --method GET reads; pass --method ${spec.api.action === "create" ? "POST" : spec.api.action === "update" ? "PATCH" : "DELETE"}`
31706
32065
  );
31707
32066
  const sameParams = (a, b) => a.length === b.length && [...a].sort().every((v, i) => v === [...b].sort()[i]);
31708
- for (const route of declaredRoutes(toml))
31709
- if (route.name !== spec.name && route.path === spec.path && route.methods.includes(spec.method) && sameParams(route.params, spec.params))
32067
+ for (const route2 of declaredRoutes(toml))
32068
+ if (route2.name !== spec.name && route2.path === spec.path && route2.methods.includes(spec.method) && sameParams(route2.params, spec.params))
31710
32069
  throw new CliError(
31711
- `${spec.method} ${spec.path} is already answered by operation ${route.name} with the same params; a second route there would never be reached \u2014 give it another path, method or --param, or --replace that one`
32070
+ `${spec.method} ${spec.path} is already answered by operation ${route2.name} with the same params; a second route there would never be reached \u2014 give it another path, method or --param, or --replace that one`
31712
32071
  );
31713
32072
  if (spec.entity !== void 0 && declaredEntities2 && !declaredEntities2.includes(spec.entity))
31714
32073
  throw new CliError(
@@ -31753,8 +32112,8 @@ function declaredEntityShapes(root) {
31753
32112
  }
31754
32113
 
31755
32114
  // src/cli/runtime/scaffoldEntityRemove.ts
31756
- var fs62 = __toESM(require("fs"));
31757
- var path47 = __toESM(require("path"));
32115
+ var fs63 = __toESM(require("fs"));
32116
+ var path48 = __toESM(require("path"));
31758
32117
  init_router();
31759
32118
  var LOCAL_DEF = "#/$defs/";
31760
32119
  function localRefs(value, found = /* @__PURE__ */ new Set()) {
@@ -31789,8 +32148,8 @@ var EntityRemoval = class _EntityRemoval {
31789
32148
  file;
31790
32149
  root;
31791
32150
  static open(dir) {
31792
- const file = path47.join(dir, "schema", "world.json");
31793
- if (!fs62.existsSync(file)) throw new CliError(`${dir} has no schema/world.json`);
32151
+ const file = path48.join(dir, "schema", "world.json");
32152
+ if (!fs63.existsSync(file)) throw new CliError(`${dir} has no schema/world.json`);
31794
32153
  return new _EntityRemoval(dir, file, readJsonFile2(file));
31795
32154
  }
31796
32155
  get entities() {
@@ -31800,8 +32159,8 @@ var EntityRemoval = class _EntityRemoval {
31800
32159
  return gateway.entities;
31801
32160
  }
31802
32161
  read(rel) {
31803
- const file = path47.join(this.dir, rel);
31804
- return fs62.existsSync(file) ? fs62.readFileSync(file, "utf8") : void 0;
32162
+ const file = path48.join(this.dir, rel);
32163
+ return fs63.existsSync(file) ? fs63.readFileSync(file, "utf8") : void 0;
31805
32164
  }
31806
32165
  relationships(name) {
31807
32166
  return Object.entries(this.entities).filter(([other]) => other !== name).filter(
@@ -31821,11 +32180,11 @@ var EntityRemoval = class _EntityRemoval {
31821
32180
  return [...new Set(found)];
31822
32181
  }
31823
32182
  verifiers(name) {
31824
- const placeholder = path47.join(this.dir, "verifiers", "state_present.sql");
31825
- return (verifierNames(this.dir) ?? []).map((verifier) => path47.join(this.dir, "verifiers", `${verifier}.sql`)).filter((file) => !(file === placeholder && scaffoldVerifierEntity(file) === name)).filter((file) => sqlMentions(fs62.readFileSync(file, "utf8"), name)).map((file) => `verifiers/${path47.basename(file)} reads ${name}`);
32183
+ const placeholder = path48.join(this.dir, "verifiers", "state_present.sql");
32184
+ return (verifierNames(this.dir) ?? []).map((verifier) => path48.join(this.dir, "verifiers", `${verifier}.sql`)).filter((file) => !(file === placeholder && scaffoldVerifierEntity(file) === name)).filter((file) => sqlMentions(fs63.readFileSync(file, "utf8"), name)).map((file) => `verifiers/${path48.basename(file)} reads ${name}`);
31826
32185
  }
31827
32186
  data(name) {
31828
- const text2 = this.read(path47.join("data", "initial.json"));
32187
+ const text2 = this.read(path48.join("data", "initial.json"));
31829
32188
  if (text2 === void 0) return [];
31830
32189
  const journal = this.journal(text2);
31831
32190
  const rows = (journal.mutations ?? []).filter((m) => m.entity === name).length;
@@ -31879,7 +32238,7 @@ var EntityRemoval = class _EntityRemoval {
31879
32238
  const defs = isObject12(this.root.$defs) ? this.root.$defs : {};
31880
32239
  removedDefs.forEach((def) => delete defs[def]);
31881
32240
  delete this.entities[name];
31882
- fs62.writeFileSync(this.file, JSON.stringify(this.root, null, 2) + "\n");
32241
+ fs63.writeFileSync(this.file, JSON.stringify(this.root, null, 2) + "\n");
31883
32242
  const remaining = Object.keys(this.entities).sort();
31884
32243
  return { removedDefs, verifier: repointScaffoldVerifier(this.dir, remaining[0], remaining) };
31885
32244
  }
@@ -31894,18 +32253,18 @@ function registerEntityRemove(entity) {
31894
32253
  ],
31895
32254
  notes: "Nothing is written when the entity is still referenced: every connector.toml operation that answers from\nit, every verifiers/*.sql that reads it, rows of it in data/initial.json, a [dependencies.<alias>.entities]\nmap and another entity's relationship are named, one per line (exit 2). The world keeps at least one entity:\n`gateway worlds schema entity add` the replacement first. The untouched placeholder verifiers/state_present.sql\nis re-pointed at an entity that stays. Then `gateway worlds schema compile <path>` and `gateway worlds schema check <path>`.",
31896
32255
  run: async (args, ctx) => {
31897
- const dir = path47.resolve(args.positionals[0]);
32256
+ const dir = path48.resolve(args.positionals[0]);
31898
32257
  const name = args.positionals[1];
31899
32258
  const { removedDefs, verifier } = EntityRemoval.open(dir).remove(name);
31900
- const rel = path47.relative(process.cwd(), dir) || ".";
32259
+ const rel = path48.relative(process.cwd(), dir) || ".";
31901
32260
  ctx.stdout(
31902
32261
  JSON.stringify(
31903
32262
  {
31904
32263
  status: "ok",
31905
32264
  entity: name,
31906
32265
  removedDefs,
31907
- ...verifier ? { verifier: path47.relative(process.cwd(), verifier) || verifier } : {},
31908
- file: path47.relative(process.cwd(), path47.join(dir, "schema", "world.json")),
32266
+ ...verifier ? { verifier: path48.relative(process.cwd(), verifier) || verifier } : {},
32267
+ file: path48.relative(process.cwd(), path48.join(dir, "schema", "world.json")),
31909
32268
  next: [`gateway worlds schema compile ${rel}`, `gateway worlds schema check ${rel}`]
31910
32269
  },
31911
32270
  null,
@@ -31917,8 +32276,8 @@ function registerEntityRemove(entity) {
31917
32276
  }
31918
32277
 
31919
32278
  // src/cli/runtime/scaffoldHandlers.ts
31920
- var fs63 = __toESM(require("fs"));
31921
- var path48 = __toESM(require("path"));
32279
+ var fs64 = __toESM(require("fs"));
32280
+ var path49 = __toESM(require("path"));
31922
32281
  init_router();
31923
32282
  var PYTHON_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
31924
32283
  var HANDLERS_FILE = "api/handlers.py";
@@ -31928,12 +32287,12 @@ var HandlerStub = class {
31928
32287
  this.name = name;
31929
32288
  if (!PYTHON_NAME.test(name))
31930
32289
  throw new CliError(`--handler is a Python function name ([A-Za-z_][A-Za-z0-9_]*), got ${JSON.stringify(name)}`);
31931
- this.file = path48.join(dir, HANDLERS_FILE);
32290
+ this.file = path49.join(dir, HANDLERS_FILE);
31932
32291
  }
31933
32292
  name;
31934
32293
  file;
31935
32294
  get source() {
31936
- return fs63.existsSync(this.file) ? fs63.readFileSync(this.file, "utf8") : void 0;
32295
+ return fs64.existsSync(this.file) ? fs64.readFileSync(this.file, "utf8") : void 0;
31937
32296
  }
31938
32297
  get defined() {
31939
32298
  const source2 = this.source ?? "";
@@ -31951,9 +32310,9 @@ var HandlerStub = class {
31951
32310
  ensure() {
31952
32311
  if (this.defined) return false;
31953
32312
  const current = this.source;
31954
- fs63.mkdirSync(path48.dirname(this.file), { recursive: true });
32313
+ fs64.mkdirSync(path49.dirname(this.file), { recursive: true });
31955
32314
  const head = current === void 0 ? HEADER : current.replace(/\n*$/, "\n");
31956
- fs63.writeFileSync(this.file, `${head}
32315
+ fs64.writeFileSync(this.file, `${head}
31957
32316
 
31958
32317
  ${this.stub()}`);
31959
32318
  return true;
@@ -32233,11 +32592,11 @@ function removeDependency(toml, alias) {
32233
32592
  return kept.join("\n") + "\n";
32234
32593
  }
32235
32594
  function dependencyServes(depDir) {
32236
- const manifest = path49.join(depDir, "gateway-env.toml");
32237
- if (!fs64.existsSync(manifest)) return void 0;
32238
- const tools = manifestServedTools(fs64.readFileSync(manifest, "utf8"));
32239
- const connector = path49.join(depDir, "connector.toml");
32240
- const routes = fs64.existsSync(connector) ? declaredRoutes(fs64.readFileSync(connector, "utf8")).map((r) => r.name).filter(Boolean) : [];
32595
+ const manifest = path50.join(depDir, "gateway-env.toml");
32596
+ if (!fs65.existsSync(manifest)) return void 0;
32597
+ const tools = manifestServedTools(fs65.readFileSync(manifest, "utf8"));
32598
+ const connector = path50.join(depDir, "connector.toml");
32599
+ const routes = fs65.existsSync(connector) ? declaredRoutes(fs65.readFileSync(connector, "utf8")).map((r) => r.name).filter(Boolean) : [];
32241
32600
  return tools === void 0 ? void 0 : { tools, routes };
32242
32601
  }
32243
32602
  function addDependency(toml, spec, depServes, opts = {}) {
@@ -32250,7 +32609,7 @@ function addDependency(toml, spec, depServes, opts = {}) {
32250
32609
  toml = removeDependency(toml, spec.alias);
32251
32610
  }
32252
32611
  if (!PIN.test(spec.pin)) throw new CliError(`--pin is <slug>@<ref>, got ${JSON.stringify(spec.pin)}`);
32253
- if (path49.isAbsolute(spec.path)) throw new CliError("The dependency path is stored relative to the world");
32612
+ if (path50.isAbsolute(spec.path)) throw new CliError("The dependency path is stored relative to the world");
32254
32613
  if (depServes) {
32255
32614
  const serves = Array.isArray(depServes) ? { tools: depServes, routes: [] } : depServes;
32256
32615
  for (const tool of spec.tools)
@@ -32320,37 +32679,37 @@ function dependencyPath(toml, alias) {
32320
32679
  return void 0;
32321
32680
  }
32322
32681
  function readManifest2(dir) {
32323
- const file = path49.join(dir, "gateway-env.toml");
32324
- if (!fs64.existsSync(file)) throw new CliError(`${dir} holds no gateway-env.toml; run \`gateway worlds schema init\` first`, 1);
32325
- return { file, toml: fs64.readFileSync(file, "utf8") };
32682
+ const file = path50.join(dir, "gateway-env.toml");
32683
+ if (!fs65.existsSync(file)) throw new CliError(`${dir} holds no gateway-env.toml; run \`gateway worlds schema init\` first`, 1);
32684
+ return { file, toml: fs65.readFileSync(file, "utf8") };
32326
32685
  }
32327
- var toPosix = (p) => p.split(path49.sep).join("/");
32686
+ var toPosix = (p) => p.split(path50.sep).join("/");
32328
32687
  var pinSlug = (name) => name.toLowerCase().replace(/[^a-z0-9._-]+/g, "-").replace(/^[^a-z0-9]+/, "") || "world";
32329
32688
  function declaredEntities(dir) {
32330
- const file = path49.join(dir, "schema", "world.json");
32331
- if (!fs64.existsSync(file)) return void 0;
32689
+ const file = path50.join(dir, "schema", "world.json");
32690
+ if (!fs65.existsSync(file)) return void 0;
32332
32691
  const gateway = readJsonFile2(file)["x-gateway"];
32333
32692
  return isObject12(gateway) && isObject12(gateway.entities) ? Object.keys(gateway.entities) : [];
32334
32693
  }
32335
32694
  function worldEntityShapes(dir) {
32336
- const file = path49.join(dir, "schema", "world.json");
32337
- return fs64.existsSync(file) ? declaredEntityShapes(readJsonFile2(file)) : void 0;
32695
+ const file = path50.join(dir, "schema", "world.json");
32696
+ return fs65.existsSync(file) ? declaredEntityShapes(readJsonFile2(file)) : void 0;
32338
32697
  }
32339
32698
  function declaredHandlerTools(dir) {
32340
- const file = path49.join(dir, "schema", "world.json");
32341
- if (!fs64.existsSync(file)) return [];
32699
+ const file = path50.join(dir, "schema", "world.json");
32700
+ if (!fs65.existsSync(file)) return [];
32342
32701
  const gateway = readJsonFile2(file)["x-gateway"];
32343
32702
  return isObject12(gateway) && isObject12(gateway.tools) ? Object.keys(gateway.tools) : [];
32344
32703
  }
32345
32704
  var WORLD_SLUG = /^[a-z0-9][a-z0-9-]*$/;
32346
32705
  function connectorTomlSkeleton(dir) {
32347
- const manifest = path49.join(dir, "gateway-env.toml");
32348
- if (!fs64.existsSync(dir))
32706
+ const manifest = path50.join(dir, "gateway-env.toml");
32707
+ if (!fs65.existsSync(dir))
32349
32708
  throw new CliError(`${dir} does not exist; run \`gateway worlds schema init ${dir} --connector custom\` to start a world there`, 1);
32350
- if (!fs64.existsSync(manifest))
32709
+ if (!fs65.existsSync(manifest))
32351
32710
  throw new CliError(`${dir} holds no connector.toml and no gateway-env.toml (not a world); run \`gateway worlds schema init ${dir} --connector custom\` first`, 1);
32352
- const name = /^\s*name\s*=\s*"([^"]*)"/m.exec(fs64.readFileSync(manifest, "utf8"))?.[1];
32353
- const slug = name && WORLD_SLUG.test(name) ? name : path49.basename(dir).toLowerCase().replace(/[^a-z0-9-]+/g, "-").replace(/^-+|-+$/g, "") || "world";
32711
+ const name = /^\s*name\s*=\s*"([^"]*)"/m.exec(fs65.readFileSync(manifest, "utf8"))?.[1];
32712
+ const slug = name && WORLD_SLUG.test(name) ? name : path50.basename(dir).toLowerCase().replace(/[^a-z0-9-]+/g, "-").replace(/^-+|-+$/g, "") || "world";
32354
32713
  return [
32355
32714
  `# ${slug}'s API surface: the HTTP routes the world serves beside its tools, from one`,
32356
32715
  "# World Host session. Declare routes with `gateway worlds connector route add`; an",
@@ -32402,8 +32761,8 @@ function registerScaffoldCommands(worlds) {
32402
32761
  ],
32403
32762
  notes: "Exactly one of --ref, --fields or --schema. The file is rewritten with two-space indentation;\nrun `gateway worlds schema compile <path>` afterwards (the compiled contract is stale until then), then\n`gateway worlds schema check <path>` for the full contract check.",
32404
32763
  run: async (args, ctx) => {
32405
- const dir = path49.resolve(args.positionals[0]);
32406
- const file = path49.join(dir, "schema", "world.json");
32764
+ const dir = path50.resolve(args.positionals[0]);
32765
+ const file = path50.join(dir, "schema", "world.json");
32407
32766
  const root = readJsonFile2(file);
32408
32767
  let inline;
32409
32768
  const schemaFlag = arg.str(args, "schema");
@@ -32427,12 +32786,12 @@ function registerScaffoldCommands(worlds) {
32427
32786
  unique: arg.list(args, "unique").map((u) => u.split(",").map((f) => f.trim()).filter(Boolean)),
32428
32787
  relationships: arg.list(args, "relationship").map(parseRelationship)
32429
32788
  });
32430
- fs64.writeFileSync(file, JSON.stringify(document, null, 2) + "\n");
32431
- const out = { status: "ok", entity: name, declaration, file: path49.relative(process.cwd(), file) || file };
32789
+ fs65.writeFileSync(file, JSON.stringify(document, null, 2) + "\n");
32790
+ const out = { status: "ok", entity: name, declaration, file: path50.relative(process.cwd(), file) || file };
32432
32791
  if (def) out.def = def;
32433
32792
  const verifier = repointScaffoldVerifier(dir, name, declaredEntities(dir) ?? []);
32434
32793
  if (verifier) {
32435
- out.verifier = path49.relative(process.cwd(), verifier) || verifier;
32794
+ out.verifier = path50.relative(process.cwd(), verifier) || verifier;
32436
32795
  ctx.stderr(`# ${out.verifier} named an entity the catalog no longer declares; it now scores over ${name}`);
32437
32796
  }
32438
32797
  ctx.stdout(JSON.stringify(out, null, 2));
@@ -32452,7 +32811,7 @@ function registerScaffoldCommands(worlds) {
32452
32811
  ],
32453
32812
  notes: "A verifier is one SQL statement returning one number in 0..1 (1.0 passed, 0.0 failed, in between partial\ncredit); each entity is a table named as in the catalog, each field a column. Edit the file freely, then\n`gateway worlds schema task add <path> <task> --verifier <name>` grades a task on it.",
32454
32813
  run: async (args, ctx) => {
32455
- const dir = path49.resolve(args.positionals[0]);
32814
+ const dir = path50.resolve(args.positionals[0]);
32456
32815
  const name = args.positionals[1];
32457
32816
  const entity2 = arg.str(args, "entity");
32458
32817
  const declared = declaredEntities(dir);
@@ -32460,14 +32819,14 @@ function registerScaffoldCommands(worlds) {
32460
32819
  if (!entity2) throw new CliError(`--entity is required: one of ${declared.join(", ") || "(declare one with `gateway worlds schema entity add` first)"}`);
32461
32820
  if (!declared.includes(entity2)) throw new CliError(`Unknown entity ${entity2}; the world has ${declared.join(", ") || "none"}`);
32462
32821
  const file = addVerifier(dir, name, entity2, arg.str(args, "where"));
32463
- const rel = path49.relative(process.cwd(), dir) || ".";
32822
+ const rel = path50.relative(process.cwd(), dir) || ".";
32464
32823
  ctx.stdout(
32465
32824
  JSON.stringify(
32466
32825
  {
32467
32826
  status: "ok",
32468
32827
  verifier: name,
32469
32828
  entity: entity2,
32470
- file: path49.relative(process.cwd(), file) || file,
32829
+ file: path50.relative(process.cwd(), file) || file,
32471
32830
  next: `gateway worlds schema task add ${rel} <task_id> --prompt "<what the agent is told>" --verifier ${name}`
32472
32831
  },
32473
32832
  null,
@@ -32504,39 +32863,39 @@ function registerScaffoldCommands(worlds) {
32504
32863
  ],
32505
32864
  notes: "The block is appended; existing text is untouched. `path` is written relative to the world so\n`schema check`, `test`, `serve` and `call` open the dependency here; the pin is what the platform\nresolves when both worlds are pushed. Then `gateway worlds schema check <path>` shows the link under\n`dependencies`, and `gateway worlds schema task add` grades it with --world <alias>=<verifier>.",
32506
32865
  run: async (args, ctx) => {
32507
- const dir = path49.resolve(args.positionals[0]);
32866
+ const dir = path50.resolve(args.positionals[0]);
32508
32867
  const alias = args.positionals[1];
32509
32868
  const depArg = args.positionals[2];
32510
- const depDir = path49.resolve(depArg);
32869
+ const depDir = path50.resolve(depArg);
32511
32870
  const { file, toml } = readManifest2(dir);
32512
- if (!fs64.existsSync(path49.join(depDir, "gateway-env.toml"))) {
32513
- const fromWorld = path49.resolve(dir, depArg);
32514
- const hint = fromWorld !== depDir && fs64.existsSync(path49.join(fromWorld, "gateway-env.toml")) ? `; paths resolve from your shell, not from the world: did you mean ${path49.relative(process.cwd(), fromWorld) || "."}?` : "";
32871
+ if (!fs65.existsSync(path50.join(depDir, "gateway-env.toml"))) {
32872
+ const fromWorld = path50.resolve(dir, depArg);
32873
+ const hint = fromWorld !== depDir && fs65.existsSync(path50.join(fromWorld, "gateway-env.toml")) ? `; paths resolve from your shell, not from the world: did you mean ${path50.relative(process.cwd(), fromWorld) || "."}?` : "";
32515
32874
  throw new CliError(
32516
32875
  `${depDir} holds no gateway-env.toml; the dependency must be a schema world (\`gateway worlds schema init\`)${hint}`,
32517
32876
  1
32518
32877
  );
32519
32878
  }
32520
- if (path49.resolve(depDir) === dir) throw new CliError("A world cannot depend on itself");
32521
- const depToml = fs64.readFileSync(path49.join(depDir, "gateway-env.toml"), "utf8");
32879
+ if (path50.resolve(depDir) === dir) throw new CliError("A world cannot depend on itself");
32880
+ const depToml = fs65.readFileSync(path50.join(depDir, "gateway-env.toml"), "utf8");
32522
32881
  if (declaredAliases(depToml).length)
32523
32882
  throw new CliError(`${depDir} has [dependencies] of its own (${declaredAliases(depToml).join(", ")}); links nest one level`);
32524
32883
  const task = arg.str(args, "task");
32525
- if (task !== void 0 && !fs64.existsSync(path49.join(depDir, "scenarios", task))) {
32526
- const have = fs64.existsSync(path49.join(depDir, "scenarios")) ? fs64.readdirSync(path49.join(depDir, "scenarios")) : [];
32884
+ if (task !== void 0 && !fs65.existsSync(path50.join(depDir, "scenarios", task))) {
32885
+ const have = fs65.existsSync(path50.join(depDir, "scenarios")) ? fs65.readdirSync(path50.join(depDir, "scenarios")) : [];
32527
32886
  throw new CliError(`${depDir} has no scenarios/${task}/ (have: ${have.join(", ") || "none"})`);
32528
32887
  }
32529
- const rel = toPosix(path49.relative(dir, depDir)) || ".";
32888
+ const rel = toPosix(path50.relative(dir, depDir)) || ".";
32530
32889
  const spec = {
32531
32890
  alias,
32532
- pin: arg.str(args, "pin") ?? `${pinSlug(manifestName(depToml) ?? path49.basename(depDir))}@main`,
32891
+ pin: arg.str(args, "pin") ?? `${pinSlug(manifestName(depToml) ?? path50.basename(depDir))}@main`,
32533
32892
  path: rel.startsWith(".") ? rel : `./${rel}`,
32534
32893
  task,
32535
32894
  tools: arg.list(args, "tools").flatMap((t) => t.split(",")).map((t) => t.trim()).filter(Boolean),
32536
32895
  entities: arg.list(args, "map").map(parseEntityMap)
32537
32896
  };
32538
32897
  const updated = addDependency(toml, spec, dependencyServes(depDir), { replace: arg.bool(args, "replace") });
32539
- fs64.writeFileSync(file, updated);
32898
+ fs65.writeFileSync(file, updated);
32540
32899
  ctx.stdout(
32541
32900
  JSON.stringify(
32542
32901
  {
@@ -32547,8 +32906,8 @@ function registerScaffoldCommands(worlds) {
32547
32906
  task: spec.task ?? null,
32548
32907
  tools: spec.tools.map((t) => `${alias}.${t}`),
32549
32908
  verifiers: (verifierNames(depDir) ?? []).map((v) => `${alias}/${v}`),
32550
- file: path49.relative(process.cwd(), file) || file,
32551
- next: `gateway worlds schema check ${path49.relative(process.cwd(), dir) || "."}`
32909
+ file: path50.relative(process.cwd(), file) || file,
32910
+ next: `gateway worlds schema check ${path50.relative(process.cwd(), dir) || "."}`
32552
32911
  },
32553
32912
  null,
32554
32913
  2
@@ -32579,7 +32938,7 @@ function registerScaffoldCommands(worlds) {
32579
32938
  ],
32580
32939
  notes: "Verifiers are SQL files returning one number in 0..1; each becomes a key in `rewards` (`slack/state_present`\nfor a dependency's). Then `gateway worlds schema check <path>` lists the task, and\n`gateway worlds serve <path> --task <id>` opens a session on it.\nAn id that is already declared (benchmarks init pre-declares one graded by its placeholder verifier)\nis refused unless --replace, which swaps that block for this one.",
32581
32940
  run: async (args, ctx) => {
32582
- const dir = path49.resolve(args.positionals[0]);
32941
+ const dir = path50.resolve(args.positionals[0]);
32583
32942
  const { file, toml } = readManifest2(dir);
32584
32943
  const prompt = arg.str(args, "prompt");
32585
32944
  if (prompt === void 0) throw new CliError("--prompt is required: what the agent is told");
@@ -32595,7 +32954,7 @@ function registerScaffoldCommands(worlds) {
32595
32954
  const depVerifiers = {};
32596
32955
  for (const alias of Object.keys(worlds2)) {
32597
32956
  const rel = dependencyPath(toml, alias);
32598
- if (rel !== void 0) depVerifiers[alias] = verifierNames(path49.resolve(dir, rel));
32957
+ if (rel !== void 0) depVerifiers[alias] = verifierNames(path50.resolve(dir, rel));
32599
32958
  }
32600
32959
  const spec = {
32601
32960
  id: args.positionals[1],
@@ -32609,7 +32968,7 @@ function registerScaffoldCommands(worlds) {
32609
32968
  { verifiers: verifierNames(dir), depVerifiers },
32610
32969
  { replace: arg.bool(args, "replace") }
32611
32970
  );
32612
- fs64.writeFileSync(file, updated);
32971
+ fs65.writeFileSync(file, updated);
32613
32972
  ctx.stdout(
32614
32973
  JSON.stringify(
32615
32974
  {
@@ -32619,11 +32978,11 @@ function registerScaffoldCommands(worlds) {
32619
32978
  verifiers: spec.verifiers,
32620
32979
  worlds: worlds2,
32621
32980
  rewards: [...spec.verifiers, ...Object.entries(worlds2).flatMap(([a, names]) => names.map((n) => `${a}/${n}`))],
32622
- file: path49.relative(process.cwd(), file) || file,
32981
+ file: path50.relative(process.cwd(), file) || file,
32623
32982
  next: [
32624
- `gateway worlds schema compile ${path49.relative(process.cwd(), dir) || "."} # a manifest edit invalidates the compiled contract`,
32625
- `gateway worlds schema check ${path49.relative(process.cwd(), dir) || "."}`,
32626
- `gateway worlds serve ${path49.relative(process.cwd(), dir) || "."} --task ${spec.id}`
32983
+ `gateway worlds schema compile ${path50.relative(process.cwd(), dir) || "."} # a manifest edit invalidates the compiled contract`,
32984
+ `gateway worlds schema check ${path50.relative(process.cwd(), dir) || "."}`,
32985
+ `gateway worlds serve ${path50.relative(process.cwd(), dir) || "."} --task ${spec.id}`
32627
32986
  ]
32628
32987
  },
32629
32988
  null,
@@ -32674,9 +33033,9 @@ function registerScaffoldCommands(worlds) {
32674
33033
  ],
32675
33034
  notes: "A schema world with no connector.toml yet gets one: [connector] slug from its [environment] name, a\nplaceholder base_url, then this route. That file is the world's API surface, served with its tools.\nExisting text is untouched; the block is appended. With --replace the block already declared under this\nname (and its [operations.api]) is removed first and the new one appended, every other byte kept.\n--entity must already be declared in schema/world.json (`gateway worlds schema entity add`). A create\nroute mints its entity's primary key (uuid, or int for an integer key) unless --body maps it or\n--generate names it, so a POST without an id is created rather than refused. --action handler\n--handler <fn> writes a 501 stub def <fn>(ctx, args, query, body) into api/handlers.py unless it is\ndefined there already. A new connector.toml starts with [auth] scheme = \"bearer\": the token a hosted\nsession hands the agent; `worlds serve` accepts the bearer --api-key pins (default `conform`). Then\n`gateway worlds connector validate <path>`.",
32676
33035
  run: async (args, ctx) => {
32677
- const dir = path49.resolve(args.positionals[0]);
32678
- const file = path49.join(dir, "connector.toml");
32679
- const created = !fs64.existsSync(file);
33036
+ const dir = path50.resolve(args.positionals[0]);
33037
+ const file = path50.join(dir, "connector.toml");
33038
+ const created = !fs65.existsSync(file);
32680
33039
  const routePath = arg.str(args, "path");
32681
33040
  if (routePath === void 0) throw new CliError("--path is required, e.g. --path /users");
32682
33041
  const spec = {
@@ -32700,13 +33059,13 @@ function registerScaffoldCommands(worlds) {
32700
33059
  };
32701
33060
  const replace = arg.bool(args, "replace");
32702
33061
  const handler = spec.api.action === "handler" && spec.api.handler ? new HandlerStub(dir, spec.api.handler) : void 0;
32703
- const current = created ? connectorTomlSkeleton(dir) : fs64.readFileSync(file, "utf8");
33062
+ const current = created ? connectorTomlSkeleton(dir) : fs65.readFileSync(file, "utf8");
32704
33063
  const updated = addRoute(current, spec, declaredEntities(dir), {
32705
33064
  replace,
32706
33065
  handlerTools: declaredHandlerTools(dir),
32707
33066
  entities: worldEntityShapes(dir)
32708
33067
  });
32709
- fs64.writeFileSync(file, updated);
33068
+ fs65.writeFileSync(file, updated);
32710
33069
  const written = handler?.ensure();
32711
33070
  ctx.stdout(
32712
33071
  JSON.stringify(
@@ -32719,7 +33078,7 @@ function registerScaffoldCommands(worlds) {
32719
33078
  ...replace ? { replaced: true } : {},
32720
33079
  ...created ? { created: true } : {},
32721
33080
  ...handler ? { handler: { file: HANDLERS_FILE, function: handler.name, written } } : {},
32722
- file: path49.relative(process.cwd(), file) || file
33081
+ file: path50.relative(process.cwd(), file) || file
32723
33082
  },
32724
33083
  null,
32725
33084
  2
@@ -32753,20 +33112,6 @@ function registerRuntimeCommands(root) {
32753
33112
  registerCallCommand(worlds);
32754
33113
  }
32755
33114
 
32756
- // src/cli/version.ts
32757
- var fs65 = __toESM(require("fs"));
32758
- var path50 = __toESM(require("path"));
32759
- function cliVersion() {
32760
- if (true) return "0.4.0";
32761
- if (typeof __dirname !== "string") return "unknown";
32762
- try {
32763
- const pkg = JSON.parse(fs65.readFileSync(path50.resolve(__dirname, "../../package.json"), "utf8"));
32764
- return pkg.version ?? "unknown";
32765
- } catch {
32766
- return "unknown";
32767
- }
32768
- }
32769
-
32770
33115
  // src/cli/main.ts
32771
33116
  init_transport();
32772
33117
  function buildCli() {