@withgateway/sdk 0.2.9 → 0.3.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 (49) hide show
  1. package/dist/cli.js +2355 -486
  2. package/dist/cli.js.map +1 -1
  3. package/dist/cli.mjs +2335 -466
  4. package/dist/cli.mjs.map +1 -1
  5. package/dist/files/index.d.mts +1 -0
  6. package/dist/files/index.d.ts +1 -0
  7. package/dist/files/index.js +1324 -21
  8. package/dist/files/index.js.map +1 -1
  9. package/dist/files/index.mjs +1322 -13
  10. package/dist/files/index.mjs.map +1 -1
  11. package/dist/{index-Cz8Q6Keo.d.mts → index-D6oi1TWE.d.mts} +93 -34
  12. package/dist/{index-BO2SNSgy.d.ts → index-DAb-FCMg.d.ts} +93 -34
  13. package/dist/index.d.mts +4 -3
  14. package/dist/index.d.ts +4 -3
  15. package/dist/index.js +1758 -116
  16. package/dist/index.js.map +1 -1
  17. package/dist/index.mjs +1720 -97
  18. package/dist/index.mjs.map +1 -1
  19. package/dist/media-CbcAfQvd.d.mts +83 -0
  20. package/dist/media-CbcAfQvd.d.ts +83 -0
  21. package/dist/traces/index.d.mts +1 -0
  22. package/dist/traces/index.d.ts +1 -0
  23. package/dist/traces/index.js +1321 -18
  24. package/dist/traces/index.js.map +1 -1
  25. package/dist/traces/index.mjs +1319 -10
  26. package/dist/traces/index.mjs.map +1 -1
  27. package/dist/tracing/index.d.mts +2 -1
  28. package/dist/tracing/index.d.ts +2 -1
  29. package/dist/tracing/index.js +512 -11
  30. package/dist/tracing/index.js.map +1 -1
  31. package/dist/tracing/index.mjs +501 -10
  32. package/dist/tracing/index.mjs.map +1 -1
  33. package/dist/worlds/index.d.mts +583 -63
  34. package/dist/worlds/index.d.ts +583 -63
  35. package/dist/worlds/index.js +1703 -94
  36. package/dist/worlds/index.js.map +1 -1
  37. package/dist/worlds/index.mjs +1689 -80
  38. package/dist/worlds/index.mjs.map +1 -1
  39. package/package.json +1 -1
  40. package/runtime/gatewaysdk/environment/schema/api.py +38 -56
  41. package/runtime/gatewaysdk/environment/schema/grading.py +1 -5
  42. package/runtime/gatewaysdk/environment/schema/host.py +53 -90
  43. package/runtime/gatewaysdk/environment/schema/local.py +15 -7
  44. package/runtime/gatewaysdk/environment/schema/runtime.py +9 -9
  45. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/SKILL.md +7 -7
  46. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/cli-mcp-map.md +1 -0
  47. package/runtime/gatewaysdk/environment/schema/tasks.py +25 -1
  48. package/skills/worlds-getting-started/SKILL.md +7 -7
  49. package/skills/worlds-getting-started/references/cli-mcp-map.md +1 -0
package/dist/cli.mjs CHANGED
@@ -96,10 +96,10 @@ function parseArgs(spec, argv) {
96
96
  else if (f.default !== void 0) flags[f.name] = f.default;
97
97
  }
98
98
  const specs4 = spec.positionals ?? [];
99
- const required = specs4.filter((p) => !p.optional && !p.variadic).length;
100
- if (positionals.length < required)
99
+ const required2 = specs4.filter((p) => !p.optional && !p.variadic).length;
100
+ if (positionals.length < required2)
101
101
  throw new CliError(
102
- `${spec.name} needs ${specs4.slice(0, required).map((p) => `<${p.name}>`).join(" ")}`
102
+ `${spec.name} needs ${specs4.slice(0, required2).map((p) => `<${p.name}>`).join(" ")}`
103
103
  );
104
104
  const variadic = specs4.some((p) => p.variadic);
105
105
  if (!variadic && positionals.length > specs4.length)
@@ -572,7 +572,7 @@ function withoutUiToken(url) {
572
572
  const [beforeHash, hash] = splitHash(url);
573
573
  const q = beforeHash.indexOf("?");
574
574
  if (q < 0) return url;
575
- const kept = beforeHash.slice(q + 1).split("&").filter((pair2) => pair2 !== "" && pair2.split("=")[0] !== UI_TOKEN_QUERY);
575
+ const kept = beforeHash.slice(q + 1).split("&").filter((pair3) => pair3 !== "" && pair3.split("=")[0] !== UI_TOKEN_QUERY);
576
576
  return beforeHash.slice(0, q) + (kept.length ? `?${kept.join("&")}` : "") + hash;
577
577
  }
578
578
  function splitHash(url) {
@@ -707,7 +707,7 @@ var SURFACE_KINDS, BROWSER_TIERS, DEFAULT_VIEWPORT, SETTLE_TIMEOUT_MS, SETTLE_QU
707
707
  var init_browser = __esm({
708
708
  "src/worlds/browser.ts"() {
709
709
  "use strict";
710
- init_session();
710
+ init_session2();
711
711
  init_browserReconnect();
712
712
  SURFACE_KINDS = ["tools", "api", "ui", "browser"];
713
713
  BROWSER_TIERS = ["standard", "premium"];
@@ -853,6 +853,10 @@ var init_browser = __esm({
853
853
  get agentId() {
854
854
  return this.recorder?.agentId ?? null;
855
855
  }
856
+ /** `text` with this session's credentials (UI token, browser address) removed. */
857
+ scrub(text2) {
858
+ return this.scrubber.scrub(text2);
859
+ }
856
860
  watchNetwork(page) {
857
861
  page.on("request", () => {
858
862
  this.inflight += 1;
@@ -1139,6 +1143,1269 @@ var init_browser = __esm({
1139
1143
  }
1140
1144
  });
1141
1145
 
1146
+ // src/worlds/nativeComputer/actions.ts
1147
+ function toNumber(value) {
1148
+ if (typeof value !== "number" || !Number.isFinite(value))
1149
+ throw new Error(`not a number: ${JSON.stringify(value) ?? String(value)}`);
1150
+ return value;
1151
+ }
1152
+ function toInt(value) {
1153
+ return Math.trunc(toNumber(value));
1154
+ }
1155
+ var ACTION_NAMES, SECRET_TEXT, BOUNDS, ComputerAction;
1156
+ var init_actions = __esm({
1157
+ "src/worlds/nativeComputer/actions.ts"() {
1158
+ "use strict";
1159
+ ACTION_NAMES = [
1160
+ "screenshot",
1161
+ "zoom",
1162
+ "click",
1163
+ "move",
1164
+ "mouse_down",
1165
+ "mouse_up",
1166
+ "drag",
1167
+ "scroll",
1168
+ "type",
1169
+ "key",
1170
+ "hold_key",
1171
+ "wait",
1172
+ "cursor_position",
1173
+ "history"
1174
+ ];
1175
+ SECRET_TEXT = "[redacted]";
1176
+ BOUNDS = {
1177
+ seconds: [0, 300],
1178
+ repeat: [1, 100],
1179
+ count: [1, 3],
1180
+ dx: [-1e4, 1e4],
1181
+ dy: [-1e4, 1e4]
1182
+ };
1183
+ ComputerAction = class {
1184
+ constructor(name, args = {}) {
1185
+ this.name = name;
1186
+ this.args = args;
1187
+ if (!ACTION_NAMES.includes(name))
1188
+ throw new Error(`unknown computer action: ${name}`);
1189
+ for (const [key2, [low, high]] of Object.entries(BOUNDS)) {
1190
+ const value = args[key2];
1191
+ if (value !== void 0 && !(Number(value) >= low && Number(value) <= high))
1192
+ throw new Error(
1193
+ `${name} ${key2} must be between ${low} and ${high}, got ${String(value)}`
1194
+ );
1195
+ }
1196
+ }
1197
+ name;
1198
+ args;
1199
+ /** Flat arguments for the browser timeline and the trace: lists become
1200
+ * `"x,y"` strings, and typed text is withheld when it went into a
1201
+ * credential field. */
1202
+ recordArgs(secretText) {
1203
+ const out = {};
1204
+ for (const [key2, value] of Object.entries(this.args))
1205
+ out[key2] = Array.isArray(value) ? value.flat().join(",") : value;
1206
+ if (secretText && "text" in out) out.text = SECRET_TEXT;
1207
+ return out;
1208
+ }
1209
+ };
1210
+ }
1211
+ });
1212
+
1213
+ // src/worlds/nativeComputer/display.ts
1214
+ var FIT_STEP, Display;
1215
+ var init_display = __esm({
1216
+ "src/worlds/nativeComputer/display.ts"() {
1217
+ "use strict";
1218
+ FIT_STEP = 0.98;
1219
+ Display = class _Display {
1220
+ constructor(width, height, viewportWidth, viewportHeight) {
1221
+ this.width = width;
1222
+ this.height = height;
1223
+ this.viewportWidth = viewportWidth;
1224
+ this.viewportHeight = viewportHeight;
1225
+ }
1226
+ width;
1227
+ height;
1228
+ viewportWidth;
1229
+ viewportHeight;
1230
+ /** `size` when the caller names one; otherwise the largest downscale of the
1231
+ * viewport (at most 1:1) that `fits` the provider's limits. */
1232
+ static forViewport(viewport, size, fits = () => true) {
1233
+ const { width, height } = viewport;
1234
+ if (size) return _Display.sized(size[0], size[1], width, height);
1235
+ let scale = 1;
1236
+ while (!fits(Math.round(width * scale), Math.round(height * scale)))
1237
+ scale *= FIT_STEP;
1238
+ return new _Display(
1239
+ Math.round(width * scale),
1240
+ Math.round(height * scale),
1241
+ width,
1242
+ height
1243
+ );
1244
+ }
1245
+ /** A caller's display keeps the viewport's shape: screenshots are scaled
1246
+ * uniformly, so another aspect ratio would map clicks off the image. */
1247
+ static sized(width, height, viewportWidth, viewportHeight) {
1248
+ if (width <= 0 || height <= 0)
1249
+ throw new Error(`display ${width}x${height} must be positive`);
1250
+ const sameShape = width * viewportHeight / viewportWidth;
1251
+ if (Math.abs(sameShape - height) > 1)
1252
+ throw new Error(
1253
+ `display ${width}x${height} must keep the viewport's aspect ratio (${viewportWidth}x${viewportHeight}); try ${width}x${Math.round(sameShape)}`
1254
+ );
1255
+ return new _Display(width, height, viewportWidth, viewportHeight);
1256
+ }
1257
+ get scaled() {
1258
+ return this.width !== this.viewportWidth || this.height !== this.viewportHeight;
1259
+ }
1260
+ get scale() {
1261
+ return Math.min(
1262
+ this.width / this.viewportWidth,
1263
+ this.height / this.viewportHeight
1264
+ );
1265
+ }
1266
+ toPage(x, y) {
1267
+ return [
1268
+ x * this.viewportWidth / this.width,
1269
+ y * this.viewportHeight / this.height
1270
+ ];
1271
+ }
1272
+ };
1273
+ }
1274
+ });
1275
+
1276
+ // src/worlds/nativeComputer/screen.ts
1277
+ function pngWidth(png) {
1278
+ if (png.length < 24 || !png.subarray(0, 8).equals(PNG_SIGNATURE)) return null;
1279
+ return png.readUInt32BE(16);
1280
+ }
1281
+ function isNativePage(page) {
1282
+ const candidate = page;
1283
+ const mouse = candidate?.mouse;
1284
+ return typeof candidate?.context === "function" && NATIVE_METHODS.every((m) => typeof mouse?.[m] === "function");
1285
+ }
1286
+ var FOCUSED_FIELD_JS, SECRET_FOCUS, DRAG_STEPS, PNG_SIGNATURE, NATIVE_METHODS, Screen;
1287
+ var init_screen = __esm({
1288
+ "src/worlds/nativeComputer/screen.ts"() {
1289
+ "use strict";
1290
+ init_browser();
1291
+ FOCUSED_FIELD_JS = "(() => { let e = document.activeElement; const inner = (el) => (el.shadowRoot && el.shadowRoot.activeElement) || (el.contentDocument && el.contentDocument.activeElement); while (e && inner(e)) e = inner(e); if (!e) return ''; if (e.tagName === 'IFRAME' || e.tagName === 'FRAME') return 'frame'; if (!(e.tagName === 'INPUT' || e.tagName === 'TEXTAREA' || e.isContentEditable)) return 'opaque'; return [e.type, e.name, e.id, e.getAttribute('autocomplete')].filter(Boolean).join(' '); })()";
1292
+ SECRET_FOCUS = ["password", "frame", "opaque"];
1293
+ DRAG_STEPS = 5;
1294
+ PNG_SIGNATURE = Buffer.from([
1295
+ 137,
1296
+ 80,
1297
+ 78,
1298
+ 71,
1299
+ 13,
1300
+ 10,
1301
+ 26,
1302
+ 10
1303
+ ]);
1304
+ NATIVE_METHODS = ["move", "click", "down", "up", "wheel"];
1305
+ Screen = class {
1306
+ constructor(browser, display) {
1307
+ this.browser = browser;
1308
+ this.display = display;
1309
+ }
1310
+ browser;
1311
+ display;
1312
+ cursor = [0, 0];
1313
+ pixelRatio = 1;
1314
+ handlers = {
1315
+ screenshot: async () => ({ image: await this.screenshot() }),
1316
+ zoom: (a) => this.zoom(a),
1317
+ click: (a) => this.click(a),
1318
+ move: (a) => this.held(a.args.modifiers ?? [], () => this.moveTo(this.point(a))),
1319
+ mouse_down: async (a) => {
1320
+ await this.page.mouse.down({ button: a.args.button ?? "left" });
1321
+ return {};
1322
+ },
1323
+ mouse_up: async (a) => {
1324
+ await this.page.mouse.up({ button: a.args.button ?? "left" });
1325
+ return {};
1326
+ },
1327
+ drag: (a) => this.drag(a),
1328
+ scroll: (a) => this.scroll(a),
1329
+ type: async (a) => {
1330
+ await this.page.keyboard.type(a.args.text ?? "");
1331
+ return {};
1332
+ },
1333
+ key: (a) => this.key(a),
1334
+ hold_key: (a) => this.held(
1335
+ a.args.keys ?? [],
1336
+ () => this.page.waitForTimeout((a.args.seconds ?? 0) * 1e3)
1337
+ ),
1338
+ wait: async (a) => {
1339
+ await this.page.waitForTimeout((a.args.seconds ?? 0) * 1e3);
1340
+ return {};
1341
+ },
1342
+ cursor_position: async () => ({
1343
+ text: `X=${this.cursor[0]}, Y=${this.cursor[1]}`
1344
+ }),
1345
+ history: async (a) => {
1346
+ const navigate = {
1347
+ back: () => this.page.goBack(),
1348
+ forward: () => this.page.goForward()
1349
+ };
1350
+ await navigate[a.args.direction ?? "back"]();
1351
+ return {};
1352
+ }
1353
+ };
1354
+ /** The live page (a new object after a reconnect), as pixel-level Playwright. */
1355
+ get page() {
1356
+ const page = this.browser.page;
1357
+ if (!isNativePage(page))
1358
+ throw new Error(
1359
+ "native computer use needs a Playwright page (mouse.move/click/down/up/wheel, context())"
1360
+ );
1361
+ return page;
1362
+ }
1363
+ run(action) {
1364
+ return this.handlers[action.name](action);
1365
+ }
1366
+ /** A PNG of the viewport at the model's display size. */
1367
+ async screenshot() {
1368
+ if (!this.display.scaled) return this.page.screenshot({ type: "png" });
1369
+ const { viewportWidth: width, viewportHeight: height } = this.display;
1370
+ return this.capture({ x: 0, y: 0, width, height }, this.display.scale);
1371
+ }
1372
+ /** Whether keystrokes go to a credential field (a password input, or one
1373
+ * named like a token, key or PIN), looking through shadow roots and
1374
+ * same-origin frames. An unreadable page, a cross-origin frame or a focus
1375
+ * that is not a text field (a closed shadow root's host) counts as one. */
1376
+ async focusedFieldIsSecret() {
1377
+ let described;
1378
+ try {
1379
+ described = String(await this.page.evaluate(FOCUSED_FIELD_JS) ?? "");
1380
+ } catch {
1381
+ return true;
1382
+ }
1383
+ return SECRET_FOCUS.some((prefix) => described.startsWith(prefix)) || SECRET_KEY.test(described);
1384
+ }
1385
+ /** CDP renders a clip at the page's device pixel ratio as well as its
1386
+ * `scale` (a Retina host doubles it), so a capture of the wrong width
1387
+ * measures that ratio and is taken once more, corrected. */
1388
+ async capture(clip, scale) {
1389
+ const wanted = Math.round(clip.width * scale);
1390
+ const png = await this.cdpCapture(clip, scale / this.pixelRatio);
1391
+ const width = pngWidth(png);
1392
+ if (width === null || Math.abs(width - wanted) <= 1) return png;
1393
+ this.pixelRatio *= width / wanted;
1394
+ return this.cdpCapture(clip, scale / this.pixelRatio);
1395
+ }
1396
+ async cdpCapture(clip, scale) {
1397
+ const page = this.page;
1398
+ const session = await page.context().newCDPSession(page);
1399
+ try {
1400
+ const shot = await session.send("Page.captureScreenshot", {
1401
+ format: "png",
1402
+ clip: { ...clip, scale }
1403
+ });
1404
+ return Buffer.from(shot.data, "base64");
1405
+ } finally {
1406
+ await session.detach();
1407
+ }
1408
+ }
1409
+ point(action) {
1410
+ const { x, y } = action.args;
1411
+ return x === void 0 || y === void 0 ? this.cursor : [x, y];
1412
+ }
1413
+ async moveTo(point2, steps = 1) {
1414
+ const [x, y] = this.display.toPage(point2[0], point2[1]);
1415
+ await this.page.mouse.move(x, y, { steps });
1416
+ this.cursor = point2;
1417
+ }
1418
+ async held(modifiers, fn) {
1419
+ for (const key2 of modifiers) await this.page.keyboard.down(key2);
1420
+ try {
1421
+ await fn();
1422
+ } finally {
1423
+ for (const key2 of [...modifiers].reverse())
1424
+ await this.page.keyboard.up(key2);
1425
+ }
1426
+ return {};
1427
+ }
1428
+ async zoom(action) {
1429
+ const [x0, y0, x1, y1] = action.args.region ?? [0, 0, 0, 0];
1430
+ const [left, top] = this.display.toPage(x0, y0);
1431
+ const [right, bottom] = this.display.toPage(x1, y1);
1432
+ if (right <= left || bottom <= top)
1433
+ throw new Error("zoom region must have x1 > x0 and y1 > y0");
1434
+ const width = right - left;
1435
+ const height = bottom - top;
1436
+ const scale = Math.min(
1437
+ this.display.width / width,
1438
+ this.display.height / height
1439
+ );
1440
+ return {
1441
+ image: await this.capture({ x: left, y: top, width, height }, scale)
1442
+ };
1443
+ }
1444
+ async click(action) {
1445
+ const point2 = this.point(action);
1446
+ return this.held(action.args.modifiers ?? [], async () => {
1447
+ await this.moveTo(point2);
1448
+ const [x, y] = this.display.toPage(point2[0], point2[1]);
1449
+ await this.page.mouse.click(x, y, {
1450
+ button: action.args.button ?? "left",
1451
+ clickCount: action.args.count ?? 1
1452
+ });
1453
+ });
1454
+ }
1455
+ async drag(action) {
1456
+ const path44 = action.args.path ?? [];
1457
+ if (path44.length < 2) throw new Error("a drag needs at least two points");
1458
+ return this.held(action.args.modifiers ?? [], async () => {
1459
+ await this.moveTo(path44[0]);
1460
+ await this.page.mouse.down({ button: "left" });
1461
+ try {
1462
+ for (const point2 of path44.slice(1)) await this.moveTo(point2, DRAG_STEPS);
1463
+ } finally {
1464
+ await this.page.mouse.up({ button: "left" });
1465
+ }
1466
+ });
1467
+ }
1468
+ async scroll(action) {
1469
+ await this.moveTo(this.point(action));
1470
+ const scale = this.display.scale;
1471
+ return this.held(
1472
+ action.args.modifiers ?? [],
1473
+ () => this.page.mouse.wheel(
1474
+ (action.args.dx ?? 0) / scale,
1475
+ (action.args.dy ?? 0) / scale
1476
+ )
1477
+ );
1478
+ }
1479
+ async key(action) {
1480
+ const combo = (action.args.keys ?? []).join("+");
1481
+ for (let i = 0; i < (action.args.repeat ?? 1); i += 1)
1482
+ await this.page.keyboard.press(combo);
1483
+ return {};
1484
+ }
1485
+ };
1486
+ }
1487
+ });
1488
+
1489
+ // src/tracing/media.ts
1490
+ import { createHash } from "crypto";
1491
+ async function putBytes(url, data, headers) {
1492
+ const controller = new AbortController();
1493
+ const timer = setTimeout(() => controller.abort(), PUT_TIMEOUT_MS);
1494
+ try {
1495
+ const res = await fetch(url, {
1496
+ method: "PUT",
1497
+ body: new Uint8Array(data),
1498
+ headers,
1499
+ signal: controller.signal
1500
+ });
1501
+ return {
1502
+ status: res.status,
1503
+ error: res.ok ? null : (await res.text()).slice(0, MAX_UPLOAD_ERROR)
1504
+ };
1505
+ } catch (error) {
1506
+ return {
1507
+ status: NETWORK_FAILURE_STATUS,
1508
+ error: error instanceof Error ? error.name : "Error"
1509
+ };
1510
+ } finally {
1511
+ clearTimeout(timer);
1512
+ }
1513
+ }
1514
+ var MEDIA_PATH, MAX_MEDIA_BYTES, PUT_TIMEOUT_MS, MAX_UPLOAD_ERROR, NETWORK_FAILURE_STATUS, MediaUploadError, MediaReference, MediaUploader;
1515
+ var init_media = __esm({
1516
+ "src/tracing/media.ts"() {
1517
+ "use strict";
1518
+ init_transport();
1519
+ MEDIA_PATH = "/api/public/media";
1520
+ MAX_MEDIA_BYTES = 5 * 1024 * 1024;
1521
+ PUT_TIMEOUT_MS = 3e4;
1522
+ MAX_UPLOAD_ERROR = 500;
1523
+ NETWORK_FAILURE_STATUS = 599;
1524
+ MediaUploadError = class extends Error {
1525
+ constructor(message, status) {
1526
+ super(message);
1527
+ this.status = status;
1528
+ this.name = "MediaUploadError";
1529
+ }
1530
+ status;
1531
+ };
1532
+ MediaReference = class {
1533
+ constructor(mediaId, contentType) {
1534
+ this.mediaId = mediaId;
1535
+ this.contentType = contentType;
1536
+ }
1537
+ mediaId;
1538
+ contentType;
1539
+ toString() {
1540
+ return `@@@langfuseMedia:type=${this.contentType}|id=${this.mediaId}|source=bytes@@@`;
1541
+ }
1542
+ };
1543
+ MediaUploader = class _MediaUploader {
1544
+ constructor(transport, put = putBytes, maxBytes = MAX_MEDIA_BYTES) {
1545
+ this.transport = transport;
1546
+ this.put = put;
1547
+ this.maxBytes = maxBytes;
1548
+ }
1549
+ transport;
1550
+ put;
1551
+ maxBytes;
1552
+ /** The uploader for `GATEWAY_HOST` / `GATEWAY_PUBLIC_KEY` /
1553
+ * `GATEWAY_SECRET_KEY` (the keys tracing exports with); null when any is unset. */
1554
+ static fromEnv(env = process.env) {
1555
+ const host = env.GATEWAY_HOST;
1556
+ const publicKey = env.GATEWAY_PUBLIC_KEY;
1557
+ const secretKey = env.GATEWAY_SECRET_KEY;
1558
+ if (!host || !publicKey || !secretKey) return null;
1559
+ return new _MediaUploader(
1560
+ new PlatformTransport({
1561
+ host: host.replace(/\/$/, ""),
1562
+ publicKey,
1563
+ secretKey
1564
+ })
1565
+ );
1566
+ }
1567
+ /** Store `data` linked to the trace (and observation) and return its reference. */
1568
+ async upload(data, link) {
1569
+ if (data.length > this.maxBytes)
1570
+ throw new MediaUploadError(
1571
+ `media is ${data.length} bytes, over the ${this.maxBytes}-byte cap`
1572
+ );
1573
+ const sha256Hash = createHash("sha256").update(data).digest("base64");
1574
+ const answer = await this.send("POST", MEDIA_PATH, {
1575
+ traceId: link.traceId,
1576
+ observationId: link.observationId,
1577
+ contentType: link.contentType,
1578
+ contentLength: data.length,
1579
+ sha256Hash,
1580
+ field: link.field
1581
+ });
1582
+ if (typeof answer.mediaId !== "string" || !answer.mediaId)
1583
+ throw new MediaUploadError(
1584
+ "POST /api/public/media answered without a mediaId"
1585
+ );
1586
+ const reference = new MediaReference(answer.mediaId, link.contentType);
1587
+ if (answer.uploadUrl)
1588
+ await this.store(reference, answer.uploadUrl, data, sha256Hash);
1589
+ return reference;
1590
+ }
1591
+ async store(reference, url, data, sha256Hash) {
1592
+ const started = Date.now();
1593
+ const { status, error } = await this.put(url, data, {
1594
+ "Content-Type": reference.contentType,
1595
+ "x-amz-checksum-sha256": sha256Hash,
1596
+ "x-ms-blob-type": "BlockBlob"
1597
+ });
1598
+ await this.send(
1599
+ "PATCH",
1600
+ `${MEDIA_PATH}/${encodeURIComponent(reference.mediaId)}`,
1601
+ {
1602
+ uploadedAt: (/* @__PURE__ */ new Date()).toISOString(),
1603
+ uploadHttpStatus: status,
1604
+ uploadHttpError: error,
1605
+ uploadTimeMs: Date.now() - started
1606
+ }
1607
+ );
1608
+ if (status < 200 || status >= 300)
1609
+ throw new MediaUploadError(
1610
+ `media storage refused the upload (HTTP ${status})`,
1611
+ status
1612
+ );
1613
+ }
1614
+ async send(method, route, body) {
1615
+ const reply = await this.transport.send(method, route, body);
1616
+ if (!reply.ok)
1617
+ throw new MediaUploadError(
1618
+ `${method} ${route} -> ${reply.status}`,
1619
+ reply.status
1620
+ );
1621
+ return reply.text ? JSON.parse(reply.text) : {};
1622
+ }
1623
+ };
1624
+ }
1625
+ });
1626
+
1627
+ // src/worlds/nativeComputer/trace.ts
1628
+ function loadOtelApi() {
1629
+ if (otelApi !== void 0) return otelApi;
1630
+ try {
1631
+ otelApi = __require("@opentelemetry/api");
1632
+ } catch {
1633
+ otelApi = null;
1634
+ }
1635
+ return otelApi;
1636
+ }
1637
+ function errorText(error) {
1638
+ return error instanceof Error ? `${error.name}: ${error.message}` : String(error);
1639
+ }
1640
+ function errorName(error) {
1641
+ return error instanceof Error ? error.name : "Error";
1642
+ }
1643
+ var SPAN_PREFIX, MAX_UPLOAD_FAILURES, TRACER_NAME, MAX_ERROR, otelApi, ActionTracer;
1644
+ var init_trace = __esm({
1645
+ "src/worlds/nativeComputer/trace.ts"() {
1646
+ "use strict";
1647
+ init_media();
1648
+ SPAN_PREFIX = "computer.";
1649
+ MAX_UPLOAD_FAILURES = 3;
1650
+ TRACER_NAME = "@withgateway/sdk";
1651
+ MAX_ERROR = 1e3;
1652
+ ActionTracer = class _ActionTracer {
1653
+ constructor(media, warn2 = (m) => console.warn(m)) {
1654
+ this.media = media;
1655
+ this.warn = warn2;
1656
+ }
1657
+ media;
1658
+ warn;
1659
+ failures = 0;
1660
+ warned = false;
1661
+ static fromEnv() {
1662
+ return new _ActionTracer(MediaUploader.fromEnv());
1663
+ }
1664
+ /** `args` are already redacted. A failure's status goes through `scrub`:
1665
+ * browser errors quote the session's ws URL and UI token. */
1666
+ async span(action, args, run, capture, scrub) {
1667
+ const otel = loadOtelApi();
1668
+ if (!otel) return run();
1669
+ const { SpanStatusCode, trace: trace3 } = otel;
1670
+ const attributes = {
1671
+ "gateway.observation.type": "tool",
1672
+ "tool.name": SPAN_PREFIX + action.name,
1673
+ "gateway.observation.input": JSON.stringify({
1674
+ action: action.name,
1675
+ ...args
1676
+ })
1677
+ };
1678
+ return trace3.getTracer(TRACER_NAME).startActiveSpan(
1679
+ SPAN_PREFIX + action.name,
1680
+ { attributes },
1681
+ async (span) => {
1682
+ try {
1683
+ const result = await run();
1684
+ await this.finish(span, result, capture);
1685
+ span.setStatus({ code: SpanStatusCode.OK });
1686
+ return result;
1687
+ } catch (error) {
1688
+ span.setStatus({
1689
+ code: SpanStatusCode.ERROR,
1690
+ message: scrub(errorText(error)).slice(0, MAX_ERROR)
1691
+ });
1692
+ throw error;
1693
+ } finally {
1694
+ span.end();
1695
+ }
1696
+ }
1697
+ );
1698
+ }
1699
+ async finish(span, result, capture) {
1700
+ if (!span.isRecording()) return;
1701
+ const output = {
1702
+ screenshot: await this.screenshot(span, result, capture)
1703
+ };
1704
+ if (result.text !== void 0) output.text = result.text;
1705
+ span.setAttribute("gateway.observation.output", JSON.stringify(output));
1706
+ }
1707
+ async screenshot(span, result, capture) {
1708
+ let png;
1709
+ try {
1710
+ png = result.image ?? await capture();
1711
+ } catch (error) {
1712
+ return `[screenshot unavailable: ${errorName(error)}]`;
1713
+ }
1714
+ return this.reference(png, span);
1715
+ }
1716
+ async reference(png, span) {
1717
+ if (!this.media)
1718
+ return "[screenshot not uploaded: GATEWAY_HOST / GATEWAY_PUBLIC_KEY / GATEWAY_SECRET_KEY unset]";
1719
+ if (this.failures >= MAX_UPLOAD_FAILURES)
1720
+ return "[screenshot not uploaded: uploads disabled after repeated failures]";
1721
+ const { traceId, spanId } = span.spanContext();
1722
+ try {
1723
+ const reference = await this.media.upload(png, {
1724
+ contentType: "image/png",
1725
+ traceId,
1726
+ observationId: spanId,
1727
+ field: "output"
1728
+ });
1729
+ this.failures = 0;
1730
+ return reference.toString();
1731
+ } catch (error) {
1732
+ return this.failed(error);
1733
+ }
1734
+ }
1735
+ failed(error) {
1736
+ this.failures += 1;
1737
+ if (!this.warned) {
1738
+ this.warned = true;
1739
+ this.warn(
1740
+ `native computer: screenshot upload failed (${errorName(error)}: ${error instanceof Error ? error.message : String(error)}); spans keep going without it`
1741
+ );
1742
+ }
1743
+ return `[screenshot not uploaded: ${errorName(error)}]`;
1744
+ }
1745
+ };
1746
+ }
1747
+ });
1748
+
1749
+ // src/worlds/nativeComputer/base.ts
1750
+ function readField(item, ...names) {
1751
+ const record = item ?? {};
1752
+ return names.map((name) => record[name]).find((value) => value !== void 0 && value !== null);
1753
+ }
1754
+ var REPLAYABLE, SETTLING, EVENT_PREFIX, NativeComputer;
1755
+ var init_base = __esm({
1756
+ "src/worlds/nativeComputer/base.ts"() {
1757
+ "use strict";
1758
+ init_browser();
1759
+ init_actions();
1760
+ init_display();
1761
+ init_screen();
1762
+ init_trace();
1763
+ REPLAYABLE = /* @__PURE__ */ new Set(["screenshot", "zoom", "cursor_position", "wait"]);
1764
+ SETTLING = /* @__PURE__ */ new Set(["click", "mouse_up", "drag", "key", "history"]);
1765
+ EVENT_PREFIX = "computer_";
1766
+ NativeComputer = class _NativeComputer {
1767
+ constructor(browser, options = {}) {
1768
+ this.browser = browser;
1769
+ const kind = this.constructor;
1770
+ this.display = Display.forViewport(
1771
+ browser.viewport,
1772
+ options.display,
1773
+ (w, h) => kind.fits(w, h)
1774
+ );
1775
+ this.screen = new Screen(browser, this.display);
1776
+ this.tracer = options.tracer ?? ActionTracer.fromEnv();
1777
+ }
1778
+ browser;
1779
+ static kinds = /* @__PURE__ */ new Map();
1780
+ display;
1781
+ screen;
1782
+ tracer;
1783
+ queue = Promise.resolve();
1784
+ static register(provider, kind) {
1785
+ _NativeComputer.kinds.set(provider, kind);
1786
+ }
1787
+ static get providers() {
1788
+ return [..._NativeComputer.kinds.keys()].sort();
1789
+ }
1790
+ static forProvider(provider, browser, options = {}) {
1791
+ const Kind = _NativeComputer.kinds.get(provider);
1792
+ if (!Kind)
1793
+ throw new Error(
1794
+ `unknown computer-use provider '${provider}'; choose from ${_NativeComputer.providers.join(", ")}`
1795
+ );
1796
+ return new Kind(browser, options);
1797
+ }
1798
+ /** Whether a screenshot of this size is within the provider's limits. */
1799
+ static fits(_width, _height) {
1800
+ return true;
1801
+ }
1802
+ /** Run one provider-shaped action (an OpenAI action object, or an Anthropic
1803
+ * `{ action: "left_click", ... }` input) and return what it produced: the
1804
+ * door for any agent framework that hands actions over one at a time. */
1805
+ executeAction(raw) {
1806
+ return this.perform(this.parse(raw));
1807
+ }
1808
+ /** Run one action on the page: reported on the session's browser timeline
1809
+ * and, when tracing is on, as a span with the screen after. */
1810
+ async perform(action) {
1811
+ const secret = action.name === "type" && await this.screen.focusedFieldIsSecret();
1812
+ const event = EVENT_PREFIX + action.name;
1813
+ const args = redactActionArgs(event, action.recordArgs(secret));
1814
+ return this.tracer.span(
1815
+ action,
1816
+ args,
1817
+ () => this.browser.act(
1818
+ event,
1819
+ args,
1820
+ () => this.runOnScreen(action),
1821
+ this.onLoss(action)
1822
+ ),
1823
+ () => this.screen.screenshot(),
1824
+ (text2) => this.browser.scrub(text2)
1825
+ );
1826
+ }
1827
+ async performAll(actions) {
1828
+ const results = [];
1829
+ for (const action of actions) results.push(await this.perform(action));
1830
+ return results;
1831
+ }
1832
+ /** The screen as the model sees it, as a traced `screenshot` action. */
1833
+ async screenshot() {
1834
+ return (await this.perform(new ComputerAction("screenshot"))).image ?? Buffer.alloc(0);
1835
+ }
1836
+ /** Run `fn` after every earlier call made through here: the AI SDK starts a
1837
+ * step's tool calls concurrently, but one screen takes one action at a time. */
1838
+ serial(fn) {
1839
+ const next = this.queue.then(fn, fn);
1840
+ this.queue = next.catch(() => void 0);
1841
+ return next;
1842
+ }
1843
+ async runOnScreen(action) {
1844
+ const result = await this.screen.run(action);
1845
+ if (SETTLING.has(action.name)) await this.browser.settle();
1846
+ return result;
1847
+ }
1848
+ onLoss(action) {
1849
+ return REPLAYABLE.has(action.name) ? "retry" : "report";
1850
+ }
1851
+ };
1852
+ }
1853
+ });
1854
+
1855
+ // src/worlds/nativeComputer/keys.ts
1856
+ function playwrightKey(token) {
1857
+ return KEY_NAMES[token.toLowerCase()] ?? token;
1858
+ }
1859
+ function letterOrName(key2) {
1860
+ return /^[a-zA-Z]$/.test(key2) ? key2.toLowerCase() : playwrightKey(key2);
1861
+ }
1862
+ function modifierChord(text2) {
1863
+ return typeof text2 === "string" && text2 ? [...KeyChord.fromXdotool(text2).keys] : [];
1864
+ }
1865
+ function modifierKeys(keys) {
1866
+ return Array.isArray(keys) && keys.length > 0 ? [...KeyChord.fromKeys(keys.map(String)).keys] : [];
1867
+ }
1868
+ var F_KEYS, KEY_NAMES, KeyChord;
1869
+ var init_keys = __esm({
1870
+ "src/worlds/nativeComputer/keys.ts"() {
1871
+ "use strict";
1872
+ F_KEYS = Object.fromEntries(
1873
+ Array.from({ length: 12 }, (_, i) => [`f${i + 1}`, `F${i + 1}`])
1874
+ );
1875
+ KEY_NAMES = {
1876
+ return: "Enter",
1877
+ enter: "Enter",
1878
+ kp_enter: "Enter",
1879
+ esc: "Escape",
1880
+ escape: "Escape",
1881
+ tab: "Tab",
1882
+ space: "Space",
1883
+ backspace: "Backspace",
1884
+ delete: "Delete",
1885
+ del: "Delete",
1886
+ insert: "Insert",
1887
+ home: "Home",
1888
+ end: "End",
1889
+ pageup: "PageUp",
1890
+ page_up: "PageUp",
1891
+ prior: "PageUp",
1892
+ pagedown: "PageDown",
1893
+ page_down: "PageDown",
1894
+ next: "PageDown",
1895
+ up: "ArrowUp",
1896
+ arrowup: "ArrowUp",
1897
+ down: "ArrowDown",
1898
+ arrowdown: "ArrowDown",
1899
+ left: "ArrowLeft",
1900
+ arrowleft: "ArrowLeft",
1901
+ right: "ArrowRight",
1902
+ arrowright: "ArrowRight",
1903
+ ctrl: "Control",
1904
+ control: "Control",
1905
+ shift: "Shift",
1906
+ alt: "Alt",
1907
+ option: "Alt",
1908
+ super: "Meta",
1909
+ meta: "Meta",
1910
+ cmd: "Meta",
1911
+ command: "Meta",
1912
+ win: "Meta",
1913
+ capslock: "CapsLock",
1914
+ caps_lock: "CapsLock",
1915
+ plus: "+",
1916
+ minus: "-",
1917
+ ...F_KEYS
1918
+ };
1919
+ KeyChord = class _KeyChord {
1920
+ constructor(keys) {
1921
+ this.keys = keys;
1922
+ if (keys.length === 0)
1923
+ throw new Error("a key action needs at least one key");
1924
+ }
1925
+ keys;
1926
+ /** `ctrl+shift+t` / `Return`: Anthropic's vocabulary, case kept. */
1927
+ static fromXdotool(text2) {
1928
+ return new _KeyChord(
1929
+ text2.trim().split("+").filter(Boolean).map(playwrightKey)
1930
+ );
1931
+ }
1932
+ /** `["CTRL", "A"]`: OpenAI's vocabulary. A lone letter is the unshifted key. */
1933
+ static fromKeys(keys) {
1934
+ return new _KeyChord(keys.map(letterOrName));
1935
+ }
1936
+ /** What `page.keyboard.press` takes: `Control+a`. */
1937
+ get combo() {
1938
+ return this.keys.join("+");
1939
+ }
1940
+ };
1941
+ }
1942
+ });
1943
+
1944
+ // src/worlds/nativeComputer/anthropic.ts
1945
+ function required(raw, key2) {
1946
+ const value = raw[key2];
1947
+ if (value === void 0 || value === null)
1948
+ throw new Error(`${String(raw.action)} needs ${key2}`);
1949
+ return value;
1950
+ }
1951
+ function pair(raw, key2) {
1952
+ const value = required(raw, key2);
1953
+ return [toInt(value[0]), toInt(value[1])];
1954
+ }
1955
+ function point(raw) {
1956
+ if (raw.coordinate === void 0 || raw.coordinate === null) return {};
1957
+ const [x, y] = pair(raw, "coordinate");
1958
+ return { x, y };
1959
+ }
1960
+ function chord(raw) {
1961
+ return [...KeyChord.fromXdotool(String(required(raw, "text"))).keys];
1962
+ }
1963
+ function click(button, count) {
1964
+ return (raw) => new ComputerAction("click", {
1965
+ ...point(raw),
1966
+ button,
1967
+ count,
1968
+ modifiers: modifierChord(raw.text)
1969
+ });
1970
+ }
1971
+ var SCROLL_STEP_PX, NOT_EXECUTED, MAX_ERROR2, SCROLL_DIRECTIONS, MEMBERS, AnthropicComputer, AnthropicComputer20251124;
1972
+ var init_anthropic = __esm({
1973
+ "src/worlds/nativeComputer/anthropic.ts"() {
1974
+ "use strict";
1975
+ init_actions();
1976
+ init_base();
1977
+ init_keys();
1978
+ SCROLL_STEP_PX = 100;
1979
+ NOT_EXECUTED = "Not executed: an earlier computer action in this turn failed.";
1980
+ MAX_ERROR2 = 1e3;
1981
+ SCROLL_DIRECTIONS = {
1982
+ up: [0, -1],
1983
+ down: [0, 1],
1984
+ left: [-1, 0],
1985
+ right: [1, 0]
1986
+ };
1987
+ MEMBERS = {
1988
+ screenshot: () => new ComputerAction("screenshot"),
1989
+ zoom: (raw) => new ComputerAction("zoom", {
1990
+ region: required(raw, "region").map(toInt)
1991
+ }),
1992
+ left_click: click("left", 1),
1993
+ right_click: click("right", 1),
1994
+ middle_click: click("middle", 1),
1995
+ double_click: click("left", 2),
1996
+ triple_click: click("left", 3),
1997
+ left_click_drag: (raw) => new ComputerAction("drag", {
1998
+ path: [pair(raw, "start_coordinate"), pair(raw, "coordinate")],
1999
+ modifiers: modifierChord(raw.text)
2000
+ }),
2001
+ mouse_move: (raw) => {
2002
+ const [x, y] = pair(raw, "coordinate");
2003
+ return new ComputerAction("move", { x, y });
2004
+ },
2005
+ left_mouse_down: () => new ComputerAction("mouse_down", { button: "left" }),
2006
+ left_mouse_up: () => new ComputerAction("mouse_up", { button: "left" }),
2007
+ cursor_position: () => new ComputerAction("cursor_position"),
2008
+ scroll: (raw) => {
2009
+ const direction = String(raw.scroll_direction ?? "down");
2010
+ if (!Object.hasOwn(SCROLL_DIRECTIONS, direction))
2011
+ throw new Error(
2012
+ `scroll_direction must be one of ${Object.keys(SCROLL_DIRECTIONS).join(", ")}`
2013
+ );
2014
+ const [dx, dy] = SCROLL_DIRECTIONS[direction];
2015
+ const amount = toInt(raw.scroll_amount ?? 1) * SCROLL_STEP_PX;
2016
+ return new ComputerAction("scroll", {
2017
+ ...point(raw),
2018
+ dx: dx * amount,
2019
+ dy: dy * amount,
2020
+ modifiers: modifierChord(raw.text)
2021
+ });
2022
+ },
2023
+ type: (raw) => new ComputerAction("type", { text: String(required(raw, "text")) }),
2024
+ key: (raw) => new ComputerAction("key", {
2025
+ keys: chord(raw),
2026
+ repeat: toInt(raw.repeat ?? 1)
2027
+ }),
2028
+ hold_key: (raw) => new ComputerAction("hold_key", {
2029
+ keys: chord(raw),
2030
+ seconds: toNumber(required(raw, "duration"))
2031
+ }),
2032
+ wait: (raw) => new ComputerAction("wait", { seconds: toNumber(raw.duration ?? 1) })
2033
+ };
2034
+ AnthropicComputer = class _AnthropicComputer extends NativeComputer {
2035
+ static TOOL_TYPE = "computer_toolset_20260801";
2036
+ static TOOLSET = "computer";
2037
+ static BETA = null;
2038
+ static MAX_LONG_EDGE = 2576;
2039
+ static MAX_VISUAL_TOKENS = 4784;
2040
+ static PATCH_PX = 28;
2041
+ static fits(width, height) {
2042
+ const tokens = Math.ceil(width / this.PATCH_PX) * Math.ceil(height / this.PATCH_PX);
2043
+ return Math.max(width, height) <= this.MAX_LONG_EDGE && tokens <= this.MAX_VISUAL_TOKENS;
2044
+ }
2045
+ tool() {
2046
+ return { type: _AnthropicComputer.TOOL_TYPE };
2047
+ }
2048
+ /** Whether a content block is a call to this computer. */
2049
+ owns(block) {
2050
+ return readField(block, "type") === "tool_use" && readField(block, "toolset_name") === _AnthropicComputer.TOOLSET;
2051
+ }
2052
+ member(block) {
2053
+ return [
2054
+ String(readField(block, "name")),
2055
+ { ...readField(block, "input") ?? {} }
2056
+ ];
2057
+ }
2058
+ parse(raw) {
2059
+ const name = String(readField(raw, "action"));
2060
+ const parser = Object.hasOwn(MEMBERS, name) ? MEMBERS[name] : void 0;
2061
+ if (!parser) throw new Error(`unknown computer action: ${name}`);
2062
+ return parser(raw);
2063
+ }
2064
+ /** Run every computer `tool_use` in a response's content, in order, and
2065
+ * return one `tool_result` per block. Other blocks are skipped. */
2066
+ async execute(content) {
2067
+ const results = [];
2068
+ let failed2 = false;
2069
+ for (const block of content) {
2070
+ if (!this.owns(block)) continue;
2071
+ if (failed2) {
2072
+ results.push(this.envelope(block, NOT_EXECUTED, true));
2073
+ continue;
2074
+ }
2075
+ const [result, blockFailed] = await this.runBlock(block);
2076
+ results.push(result);
2077
+ failed2 = blockFailed;
2078
+ }
2079
+ return results;
2080
+ }
2081
+ /** The content an `ActionResult` goes back to the model as. */
2082
+ static content(result) {
2083
+ if (result.image)
2084
+ return [
2085
+ {
2086
+ type: "image",
2087
+ source: {
2088
+ type: "base64",
2089
+ media_type: "image/png",
2090
+ data: result.image.toString("base64")
2091
+ }
2092
+ }
2093
+ ];
2094
+ return [{ type: "text", text: result.text ?? "OK" }];
2095
+ }
2096
+ /** For `anthropic.tools.computerToolset_20260801({ ...computer.aiSdk() })`
2097
+ * (or `computer_20251124` with the legacy kind): `execute` runs one action
2098
+ * and returns `{ type: "image", data }` or text; `toModelOutput` turns that
2099
+ * into the tool result. Calls run one at a time, and once a call fails the
2100
+ * rest of that step's calls answer as not executed. */
2101
+ aiSdk() {
2102
+ let failedStep;
2103
+ const execute = (input, options) => this.serial(async () => {
2104
+ const step = options?.messages?.length;
2105
+ if (step !== void 0 && step === failedStep)
2106
+ throw new Error(NOT_EXECUTED);
2107
+ try {
2108
+ return _AnthropicComputer.aiSdkOutput(await this.executeAction(input));
2109
+ } catch (error) {
2110
+ failedStep = step;
2111
+ throw error instanceof Error ? new Error(this.browser.scrub(error.message)) : error;
2112
+ }
2113
+ });
2114
+ return {
2115
+ execute,
2116
+ toModelOutput: ({ output }) => _AnthropicComputer.aiSdkModelOutput(output)
2117
+ };
2118
+ }
2119
+ static aiSdkOutput(result) {
2120
+ if (result.image)
2121
+ return { type: "image", data: result.image.toString("base64") };
2122
+ return result.text ?? "OK";
2123
+ }
2124
+ /** `image-data` is what AI SDK 6's Anthropic provider turns into an image
2125
+ * block; AI SDK 7 still accepts it (and converts it to a `file` part). */
2126
+ static aiSdkModelOutput(output) {
2127
+ if (typeof output === "string") return { type: "text", value: output };
2128
+ return {
2129
+ type: "content",
2130
+ value: [
2131
+ { type: "image-data", data: output.data, mediaType: "image/png" }
2132
+ ]
2133
+ };
2134
+ }
2135
+ envelope(block, content, isError = false) {
2136
+ return {
2137
+ type: "tool_result",
2138
+ tool_use_id: String(readField(block, "id")),
2139
+ toolset_name: _AnthropicComputer.TOOLSET,
2140
+ content,
2141
+ ...isError ? { is_error: true } : {}
2142
+ };
2143
+ }
2144
+ async runBlock(block) {
2145
+ const [name, payload] = this.member(block);
2146
+ try {
2147
+ const result = await this.executeAction({ ...payload, action: name });
2148
+ return [this.envelope(block, _AnthropicComputer.content(result)), false];
2149
+ } catch (error) {
2150
+ const detail = error instanceof Error ? `${error.name}: ${error.message}` : String(error);
2151
+ return [
2152
+ this.envelope(
2153
+ block,
2154
+ this.browser.scrub(`Error: ${detail}`).slice(0, MAX_ERROR2),
2155
+ true
2156
+ ),
2157
+ true
2158
+ ];
2159
+ }
2160
+ }
2161
+ };
2162
+ AnthropicComputer20251124 = class _AnthropicComputer20251124 extends AnthropicComputer {
2163
+ static TOOL_TYPE = "computer_20251124";
2164
+ static BETA = "computer-use-2025-11-24";
2165
+ static MAX_LONG_EDGE = 1568;
2166
+ static MAX_PIXELS = 115e4;
2167
+ static fits(width, height) {
2168
+ return Math.max(width, height) <= this.MAX_LONG_EDGE && width * height <= this.MAX_PIXELS;
2169
+ }
2170
+ tool() {
2171
+ return {
2172
+ type: _AnthropicComputer20251124.TOOL_TYPE,
2173
+ name: AnthropicComputer.TOOLSET,
2174
+ display_width_px: this.display.width,
2175
+ display_height_px: this.display.height,
2176
+ enable_zoom: true
2177
+ };
2178
+ }
2179
+ owns(block) {
2180
+ return readField(block, "type") === "tool_use" && readField(block, "name") === AnthropicComputer.TOOLSET;
2181
+ }
2182
+ member(block) {
2183
+ const { action, ...payload } = readField(block, "input") ?? {};
2184
+ return [String(action ?? ""), payload];
2185
+ }
2186
+ envelope(block, content, isError = false) {
2187
+ const { toolset_name: _dropped, ...rest } = super.envelope(
2188
+ block,
2189
+ content,
2190
+ isError
2191
+ );
2192
+ return rest;
2193
+ }
2194
+ };
2195
+ NativeComputer.register("anthropic", AnthropicComputer);
2196
+ NativeComputer.register(
2197
+ "anthropic-computer-20251124",
2198
+ AnthropicComputer20251124
2199
+ );
2200
+ }
2201
+ });
2202
+
2203
+ // src/worlds/nativeComputer/openai.ts
2204
+ function safetyCheck(raw) {
2205
+ const check = { id: String(readField(raw, "id") ?? "") };
2206
+ const code = readField(raw, "code");
2207
+ const message = readField(raw, "message");
2208
+ if (code !== void 0) check.code = String(code);
2209
+ if (message !== void 0) check.message = String(message);
2210
+ return check;
2211
+ }
2212
+ function dataUrl(png) {
2213
+ return `data:image/png;base64,${png.toString("base64")}`;
2214
+ }
2215
+ function xy(raw) {
2216
+ return {
2217
+ x: toInt(readField(raw, "x") ?? 0),
2218
+ y: toInt(readField(raw, "y") ?? 0)
2219
+ };
2220
+ }
2221
+ function held(raw) {
2222
+ return modifierKeys(readField(raw, "keys"));
2223
+ }
2224
+ var WAIT_SECONDS, BUTTONS, HISTORY_BUTTONS, PendingSafetyChecks, ACTIONS, OpenAIComputer, OpenAIPreviewComputer;
2225
+ var init_openai = __esm({
2226
+ "src/worlds/nativeComputer/openai.ts"() {
2227
+ "use strict";
2228
+ init_actions();
2229
+ init_base();
2230
+ init_keys();
2231
+ WAIT_SECONDS = 1;
2232
+ BUTTONS = {
2233
+ left: "left",
2234
+ right: "right",
2235
+ wheel: "middle",
2236
+ middle: "middle"
2237
+ };
2238
+ HISTORY_BUTTONS = /* @__PURE__ */ new Set(["back", "forward"]);
2239
+ PendingSafetyChecks = class extends Error {
2240
+ constructor(callId, checks) {
2241
+ const listed2 = checks.map((c) => `${c.code ?? "check"}: ${c.message ?? ""}`.trim()).join("; ");
2242
+ super(
2243
+ `computer_call ${callId} needs ${checks.length} safety check(s) acknowledged: ${listed2}`
2244
+ );
2245
+ this.callId = callId;
2246
+ this.checks = checks;
2247
+ this.name = "PendingSafetyChecks";
2248
+ }
2249
+ callId;
2250
+ checks;
2251
+ };
2252
+ ACTIONS = {
2253
+ click: (raw) => {
2254
+ const button = String(readField(raw, "button") ?? "left");
2255
+ if (HISTORY_BUTTONS.has(button))
2256
+ return new ComputerAction("history", {
2257
+ direction: button
2258
+ });
2259
+ if (!Object.hasOwn(BUTTONS, button))
2260
+ throw new Error(`unknown mouse button: ${button}`);
2261
+ return new ComputerAction("click", {
2262
+ ...xy(raw),
2263
+ button: BUTTONS[button],
2264
+ count: 1,
2265
+ modifiers: held(raw)
2266
+ });
2267
+ },
2268
+ double_click: (raw) => new ComputerAction("click", {
2269
+ ...xy(raw),
2270
+ button: "left",
2271
+ count: 2,
2272
+ modifiers: held(raw)
2273
+ }),
2274
+ drag: (raw) => new ComputerAction("drag", {
2275
+ path: (readField(raw, "path") ?? []).map(
2276
+ (p) => [toInt(readField(p, "x")), toInt(readField(p, "y"))]
2277
+ ),
2278
+ modifiers: held(raw)
2279
+ }),
2280
+ keypress: (raw) => new ComputerAction("key", {
2281
+ keys: [
2282
+ ...KeyChord.fromKeys(readField(raw, "keys") ?? []).keys
2283
+ ],
2284
+ repeat: 1
2285
+ }),
2286
+ move: (raw) => new ComputerAction("move", { ...xy(raw), modifiers: held(raw) }),
2287
+ scroll: (raw) => new ComputerAction("scroll", {
2288
+ ...xy(raw),
2289
+ dx: toInt(readField(raw, "scroll_x", "scrollX") ?? 0),
2290
+ dy: toInt(readField(raw, "scroll_y", "scrollY") ?? 0),
2291
+ modifiers: held(raw)
2292
+ }),
2293
+ type: (raw) => new ComputerAction("type", { text: String(readField(raw, "text") ?? "") }),
2294
+ wait: () => new ComputerAction("wait", { seconds: WAIT_SECONDS }),
2295
+ screenshot: () => new ComputerAction("screenshot")
2296
+ };
2297
+ OpenAIComputer = class _OpenAIComputer extends NativeComputer {
2298
+ tool() {
2299
+ return { type: "computer" };
2300
+ }
2301
+ owns(item) {
2302
+ return readField(item, "type") === "computer_call";
2303
+ }
2304
+ parse(raw) {
2305
+ const kind = String(readField(raw, "type"));
2306
+ const parser = Object.hasOwn(ACTIONS, kind) ? ACTIONS[kind] : void 0;
2307
+ if (!parser) throw new Error(`unknown computer action: ${kind}`);
2308
+ return parser(raw);
2309
+ }
2310
+ static actionsOf(call3) {
2311
+ const batch = readField(call3, "actions");
2312
+ if (Array.isArray(batch)) return batch;
2313
+ const single = readField(call3, "action");
2314
+ return single === void 0 ? [] : [single];
2315
+ }
2316
+ /** Run a `computer_call`'s actions and return its `computer_call_output`.
2317
+ * Throws `PendingSafetyChecks` (before anything runs) while a check the
2318
+ * model raised is not in `acknowledged`. */
2319
+ async execute(call3, acknowledged = []) {
2320
+ const callId = String(readField(call3, "call_id", "callId"));
2321
+ const checks = (readField(
2322
+ call3,
2323
+ "pending_safety_checks",
2324
+ "pendingSafetyChecks"
2325
+ ) ?? []).map(safetyCheck);
2326
+ const png = await this.runCall(
2327
+ callId,
2328
+ _OpenAIComputer.actionsOf(call3),
2329
+ checks,
2330
+ acknowledged
2331
+ );
2332
+ return {
2333
+ type: "computer_call_output",
2334
+ call_id: callId,
2335
+ output: {
2336
+ type: "computer_screenshot",
2337
+ image_url: dataUrl(png),
2338
+ detail: "original"
2339
+ },
2340
+ ...checks.length > 0 ? { acknowledged_safety_checks: checks } : {}
2341
+ };
2342
+ }
2343
+ /** For `openai.tools.computer({ ...computer.aiSdk() })`: `execute` runs a
2344
+ * call's `actions` and returns the screenshot output. A call with pending
2345
+ * safety checks asks for approval first (`needsApproval`), so the AI SDK's
2346
+ * approval flow puts them in front of a person; once approved, `execute`
2347
+ * acknowledges them. */
2348
+ aiSdk() {
2349
+ return {
2350
+ needsApproval: (input) => (input.pendingSafetyChecks ?? []).length > 0,
2351
+ execute: (input) => this.serial(async () => {
2352
+ const checks = (input.pendingSafetyChecks ?? []).map(safetyCheck);
2353
+ const png = await this.runCall(
2354
+ "ai-sdk",
2355
+ input.actions ?? [],
2356
+ checks,
2357
+ checks
2358
+ );
2359
+ return {
2360
+ output: { type: "computer_screenshot", imageUrl: dataUrl(png) },
2361
+ ...checks.length > 0 ? { acknowledgedSafetyChecks: checks } : {}
2362
+ };
2363
+ })
2364
+ };
2365
+ }
2366
+ /** The batch's actions, run after the safety checks clear; the screen after them. */
2367
+ async runCall(callId, rawActions, checks, acknowledged) {
2368
+ const cleared = new Set(acknowledged.map((c) => safetyCheck(c).id));
2369
+ const waiting = checks.filter((c) => !c.id || !cleared.has(c.id));
2370
+ if (waiting.length > 0) throw new PendingSafetyChecks(callId, waiting);
2371
+ const actions = rawActions.map((raw) => this.parse(raw));
2372
+ const results = await this.performAll(actions);
2373
+ const last = actions.at(-1);
2374
+ if (last?.name === "screenshot")
2375
+ return results.at(-1)?.image ?? Buffer.alloc(0);
2376
+ return this.screenshot();
2377
+ }
2378
+ };
2379
+ OpenAIPreviewComputer = class extends OpenAIComputer {
2380
+ tool() {
2381
+ return {
2382
+ type: "computer_use_preview",
2383
+ display_width: this.display.width,
2384
+ display_height: this.display.height,
2385
+ environment: "browser"
2386
+ };
2387
+ }
2388
+ };
2389
+ NativeComputer.register("openai", OpenAIComputer);
2390
+ NativeComputer.register("openai-preview", OpenAIPreviewComputer);
2391
+ }
2392
+ });
2393
+
2394
+ // src/worlds/nativeComputer/index.ts
2395
+ var init_nativeComputer = __esm({
2396
+ "src/worlds/nativeComputer/index.ts"() {
2397
+ "use strict";
2398
+ init_actions();
2399
+ init_base();
2400
+ init_display();
2401
+ init_keys();
2402
+ init_screen();
2403
+ init_trace();
2404
+ init_anthropic();
2405
+ init_openai();
2406
+ }
2407
+ });
2408
+
1142
2409
  // src/worlds/sessionContract.ts
1143
2410
  function serializeCallBody(body) {
1144
2411
  const text2 = JSON.stringify(body);
@@ -1192,6 +2459,75 @@ var init_sessionContract = __esm({
1192
2459
  }
1193
2460
  });
1194
2461
 
2462
+ // src/tracing/session.ts
2463
+ var session_exports = {};
2464
+ __export(session_exports, {
2465
+ SESSION_ID_ATTRIBUTE: () => SESSION_ID_ATTRIBUTE,
2466
+ SessionSpanProcessor: () => SessionSpanProcessor,
2467
+ WORLD_SESSION_ID_ATTRIBUTE: () => WORLD_SESSION_ID_ATTRIBUTE,
2468
+ getAmbientSessionId: () => getAmbientSessionId,
2469
+ getCurrentWorldSessionId: () => getCurrentWorldSessionId,
2470
+ withSession: () => withSession,
2471
+ withWorldSession: () => withWorldSession
2472
+ });
2473
+ import { AsyncLocalStorage } from "async_hooks";
2474
+ function getAmbientSessionId() {
2475
+ return currentSessionStorage.getStore();
2476
+ }
2477
+ function getCurrentWorldSessionId() {
2478
+ return currentWorldSessionStorage.getStore();
2479
+ }
2480
+ function runIn(storage, value, fn) {
2481
+ return new Promise((resolve29, reject) => {
2482
+ storage.run(value, () => {
2483
+ Promise.resolve().then(fn).then(resolve29, reject);
2484
+ });
2485
+ });
2486
+ }
2487
+ function withSession(sessionId, fn) {
2488
+ return runIn(currentSessionStorage, sessionId, fn);
2489
+ }
2490
+ function withWorldSession(worldSessionId, fn) {
2491
+ return runIn(
2492
+ currentWorldSessionStorage,
2493
+ worldSessionId,
2494
+ () => withSession(worldSessionId, fn)
2495
+ );
2496
+ }
2497
+ var SESSION_ID_ATTRIBUTE, WORLD_SESSION_ID_ATTRIBUTE, processStorage, currentSessionStorage, currentWorldSessionStorage, SessionSpanProcessor;
2498
+ var init_session = __esm({
2499
+ "src/tracing/session.ts"() {
2500
+ "use strict";
2501
+ SESSION_ID_ATTRIBUTE = "gateway.session.id";
2502
+ WORLD_SESSION_ID_ATTRIBUTE = "gateway.trace.metadata.world_session_id";
2503
+ processStorage = (name) => {
2504
+ const key2 = /* @__PURE__ */ Symbol.for(`@withgateway/sdk/${name}`);
2505
+ const slots = globalThis;
2506
+ slots[key2] ??= new AsyncLocalStorage();
2507
+ return slots[key2];
2508
+ };
2509
+ currentSessionStorage = processStorage("session-storage");
2510
+ currentWorldSessionStorage = processStorage("world-session-storage");
2511
+ SessionSpanProcessor = class {
2512
+ onStart(span, _parentContext) {
2513
+ const worldSessionId = getCurrentWorldSessionId();
2514
+ if (worldSessionId)
2515
+ span.setAttribute(WORLD_SESSION_ID_ATTRIBUTE, worldSessionId);
2516
+ const sessionId = getAmbientSessionId();
2517
+ if (!sessionId || span.attributes?.[SESSION_ID_ATTRIBUTE] !== void 0)
2518
+ return;
2519
+ span.setAttribute(SESSION_ID_ATTRIBUTE, sessionId);
2520
+ }
2521
+ onEnd(_span) {
2522
+ }
2523
+ async shutdown() {
2524
+ }
2525
+ async forceFlush() {
2526
+ }
2527
+ };
2528
+ }
2529
+ });
2530
+
1195
2531
  // src/worlds/taskRef.ts
1196
2532
  var isTaskIdRef, isTaskSpec, taskLabel, assertTaskRef;
1197
2533
  var init_taskRef = __esm({
@@ -1216,8 +2552,8 @@ var init_taskRef = __esm({
1216
2552
  });
1217
2553
 
1218
2554
  // src/worlds/session.ts
1219
- var session_exports = {};
1220
- __export(session_exports, {
2555
+ var session_exports2 = {};
2556
+ __export(session_exports2, {
1221
2557
  WorldSession: () => WorldSession,
1222
2558
  WorldSessionCallError: () => WorldSessionCallError,
1223
2559
  WorldSessionTimeout: () => WorldSessionTimeout,
@@ -1271,7 +2607,7 @@ function schemaFromSignature(spec) {
1271
2607
  };
1272
2608
  const inside = /\(([\s\S]*)\)\s*$/.exec(spec.signature.trim())?.[1] ?? "";
1273
2609
  const properties = {};
1274
- const required = [];
2610
+ const required2 = [];
1275
2611
  const params = [];
1276
2612
  let depth = 0;
1277
2613
  let current = "";
@@ -1292,7 +2628,7 @@ function schemaFromSignature(spec) {
1292
2628
  if (!name) continue;
1293
2629
  if (eq === -1) {
1294
2630
  properties[name] = { type: "string" };
1295
- required.push(name);
2631
+ required2.push(name);
1296
2632
  continue;
1297
2633
  }
1298
2634
  const value = param.slice(eq + 1).trim();
@@ -1306,7 +2642,7 @@ function schemaFromSignature(spec) {
1306
2642
  function: {
1307
2643
  name: modelToolName(spec.name),
1308
2644
  description: spec.doc ?? spec.name,
1309
- parameters: { type: "object", properties, required }
2645
+ parameters: { type: "object", properties, required: required2 }
1310
2646
  }
1311
2647
  };
1312
2648
  }
@@ -1375,13 +2711,16 @@ async function runSessions(opts) {
1375
2711
  task = taskLabel(taskRef, session.taskInfo);
1376
2712
  await session.ready();
1377
2713
  const toolkit = await session.toolkit();
1378
- await opts.agent({
1379
- session,
1380
- toolkit,
1381
- instruction: session.instruction ?? (isTaskSpec(taskRef) ? taskRef.instruction : task),
1382
- task,
1383
- taskRef
1384
- });
2714
+ const live = session;
2715
+ await live.withTraceContext(
2716
+ () => opts.agent({
2717
+ session: live,
2718
+ toolkit,
2719
+ instruction: live.instruction ?? (isTaskSpec(taskRef) ? taskRef.instruction : task),
2720
+ task,
2721
+ taskRef
2722
+ })
2723
+ );
1385
2724
  const graded = await session.grade();
1386
2725
  const result = {
1387
2726
  task,
@@ -1419,12 +2758,14 @@ async function runSessions(opts) {
1419
2758
  };
1420
2759
  }
1421
2760
  var READY_TIMEOUT_MS, READY_POLL_MS, CALL_TIMEOUT_MS, CALL_POLL_MS, JUDGED_GRADE_TIMEOUT_MS, JUDGED_GRADE_POLL_MS, EXPORT_PAGE, sleep, modelToolName, WorldSessionTimeout, WorldSessionCallError, WorldSession, OPEN_SESSION_OPTION_KEYS, isOpenSessionOptions;
1422
- var init_session = __esm({
2761
+ var init_session2 = __esm({
1423
2762
  "src/worlds/session.ts"() {
1424
2763
  "use strict";
1425
2764
  init_worlds();
1426
2765
  init_browser();
2766
+ init_nativeComputer();
1427
2767
  init_sessionContract();
2768
+ init_session();
1428
2769
  init_taskRef();
1429
2770
  init_taskRef();
1430
2771
  READY_TIMEOUT_MS = 10 * 6e4;
@@ -1578,6 +2919,12 @@ var init_session = __esm({
1578
2919
  computerUseTools(browser) {
1579
2920
  return computerUseToolkit(browser);
1580
2921
  }
2922
+ /** The browser as a provider's own pixel-based computer-use tool: `anthropic`
2923
+ * (`computer_toolset_20260801`), `openai` (Responses `computer`),
2924
+ * `anthropic-computer-20251124` or `openai-preview`. See `nativeComputer/`. */
2925
+ nativeComputer(browser, provider = "anthropic", options = {}) {
2926
+ return NativeComputer.forProvider(provider, browser, options);
2927
+ }
1581
2928
  /** The session's latest platform state (one request, no waiting). */
1582
2929
  async status() {
1583
2930
  const fresh = await apiRequest(
@@ -1629,18 +2976,18 @@ var init_session = __esm({
1629
2976
  const pollMs3 = judged ? JUDGED_GRADE_POLL_MS : CALL_POLL_MS;
1630
2977
  const deadline = Date.now() + budgetMs;
1631
2978
  for (; ; ) {
1632
- const call2 = await apiRequest(
2979
+ const call3 = await apiRequest(
1633
2980
  this.options,
1634
2981
  "GET",
1635
2982
  `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/calls/${encodeURIComponent(callId)}`
1636
2983
  );
1637
- if (call2.done) {
1638
- if (call2.error) throw new WorldSessionCallError(call2.error);
1639
- return call2.result;
2984
+ if (call3.done) {
2985
+ if (call3.error) throw new WorldSessionCallError(call3.error);
2986
+ return call3.result;
1640
2987
  }
1641
2988
  if (Date.now() > deadline)
1642
2989
  throw new WorldSessionTimeout(
1643
- judged ? `Grade ${callId} still ${call2.state} after ${Math.round(budgetMs / 1e3)}s \u2014 the judge has not answered; the platform finalizes the call on its own, read it back with export().` : `Call ${callId} still ${call2.state} after ${Math.round(budgetMs / 1e3)}s \u2014 the container may have died.`
2990
+ judged ? `Grade ${callId} still ${call3.state} after ${Math.round(budgetMs / 1e3)}s \u2014 the judge has not answered; the platform finalizes the call on its own, read it back with export().` : `Call ${callId} still ${call3.state} after ${Math.round(budgetMs / 1e3)}s \u2014 the container may have died.`
1644
2991
  );
1645
2992
  await sleep(pollMs3);
1646
2993
  }
@@ -1753,15 +3100,15 @@ var init_session = __esm({
1753
3100
  "GET",
1754
3101
  `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/calls?${params.toString()}`
1755
3102
  );
1756
- for (const call2 of page.calls) {
3103
+ for (const call3 of page.calls) {
1757
3104
  calls.push({
1758
- seq: Number(call2.seq),
1759
- kind: String(call2.kind ?? "call"),
1760
- tool: typeof call2.tool === "string" ? call2.tool : null,
1761
- args: call2.args ?? null,
1762
- result: call2.result ?? null,
1763
- error: typeof call2.error === "string" ? call2.error : null,
1764
- completedAt: typeof call2.completedAt === "string" ? call2.completedAt : null
3105
+ seq: Number(call3.seq),
3106
+ kind: String(call3.kind ?? "call"),
3107
+ tool: typeof call3.tool === "string" ? call3.tool : null,
3108
+ args: call3.args ?? null,
3109
+ result: call3.result ?? null,
3110
+ error: typeof call3.error === "string" ? call3.error : null,
3111
+ completedAt: typeof call3.completedAt === "string" ? call3.completedAt : null
1765
3112
  });
1766
3113
  }
1767
3114
  cursor = page.nextCursor ?? void 0;
@@ -1812,6 +3159,21 @@ var init_session = __esm({
1812
3159
  { keepWarm: opts.keepWarm ?? false }
1813
3160
  );
1814
3161
  }
3162
+ /**
3163
+ * Run `fn` as work inside this session: spans it records take `sessionId`
3164
+ * as their session id and carry `world_session_id` trace metadata, so the
3165
+ * agent's traces land in the same session as the platform's traces of this
3166
+ * session's tool calls. A `withSession()` block inside still wins for the
3167
+ * session id. No effect before `tracing.init()`. `runSessions` wraps each
3168
+ * agent call in it.
3169
+ *
3170
+ * ```typescript
3171
+ * await session.withTraceContext(() => myAgent(toolkit, session.instruction));
3172
+ * ```
3173
+ */
3174
+ withTraceContext(fn) {
3175
+ return withWorldSession(this.sessionId, fn);
3176
+ }
1815
3177
  };
1816
3178
  OPEN_SESSION_OPTION_KEYS = /* @__PURE__ */ new Set([
1817
3179
  "task",
@@ -1961,7 +3323,11 @@ function fromResponse(answer, options) {
1961
3323
  const worlds = {};
1962
3324
  for (const [alias, state2] of Object.entries(answer.sessions)) {
1963
3325
  sessions[alias] = new WorldSession(state2.sessionId, state2, options);
1964
- worlds[alias] = { slug: state2.slug, ref: state2.ref };
3326
+ worlds[alias] = {
3327
+ slug: state2.slug,
3328
+ ref: state2.ref,
3329
+ private: state2.private ?? null
3330
+ };
1965
3331
  }
1966
3332
  return new TaskSessions(
1967
3333
  answer.taskId,
@@ -2035,6 +3401,7 @@ async function attachTask(taskId, options = {}) {
2035
3401
  {
2036
3402
  slug: row.slug ?? "",
2037
3403
  ref: null,
3404
+ private: null,
2038
3405
  versionId: row.versionId,
2039
3406
  sessionId: row.sessionId,
2040
3407
  ready: row.ready,
@@ -2064,7 +3431,7 @@ async function attachManifest(manifest, options = {}) {
2064
3431
  Object.fromEntries(
2065
3432
  Object.entries(manifest.sessions).map(([alias, entry]) => [
2066
3433
  alias,
2067
- { slug: entry.slug, ref: entry.ref }
3434
+ { slug: entry.slug, ref: entry.ref, private: entry.private ?? null }
2068
3435
  ])
2069
3436
  )
2070
3437
  );
@@ -2078,12 +3445,13 @@ var init_taskSessions = __esm({
2078
3445
  "use strict";
2079
3446
  init_worlds();
2080
3447
  init_browser();
2081
- init_session();
3448
+ init_session2();
2082
3449
  TASK_SESSIONS = "/api/public/world-task-sessions";
2083
3450
  VERIFIER_REWARD_PREFIX = "x.";
2084
3451
  manifestSession = (s, state2, world) => ({
2085
3452
  slug: world.slug,
2086
3453
  ref: world.ref,
3454
+ private: world.private,
2087
3455
  versionId: state2.versionId,
2088
3456
  sessionId: state2.sessionId,
2089
3457
  ready: state2.ready,
@@ -2118,10 +3486,10 @@ var init_taskSessions = __esm({
2118
3486
  sessions;
2119
3487
  worlds;
2120
3488
  hash;
2121
- /** This alias's `{slug, ref}` as recorded at open/attach — the world a
2122
- * `TaskRun` filing needs to name, without exposing the whole map. */
3489
+ /** This alias's world as recorded at open/attach — what a `TaskRun`
3490
+ * filing needs to name, without exposing the whole map. */
2123
3491
  worldRef(alias) {
2124
- return this.worlds[alias] ?? { slug: "", ref: null };
3492
+ return this.worlds[alias] ?? { slug: "", ref: null, private: null };
2125
3493
  }
2126
3494
  /** The aliases, in the spec's order. */
2127
3495
  get aliases() {
@@ -2485,7 +3853,7 @@ var init_users = __esm({
2485
3853
  });
2486
3854
 
2487
3855
  // src/tracing/identity.ts
2488
- import { AsyncLocalStorage } from "async_hooks";
3856
+ import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
2489
3857
  import { isSpanContextValid, trace } from "@opentelemetry/api";
2490
3858
  function resolveUserId() {
2491
3859
  const contextual = currentUserStorage.getStore();
@@ -2499,7 +3867,7 @@ var init_identity = __esm({
2499
3867
  "use strict";
2500
3868
  init_users();
2501
3869
  USER_ID_ATTRIBUTE = "gateway.user.id";
2502
- currentUserStorage = new AsyncLocalStorage();
3870
+ currentUserStorage = new AsyncLocalStorage2();
2503
3871
  IdentitySpanProcessor = class {
2504
3872
  onStart(span, _parentContext) {
2505
3873
  const userId = resolveUserId();
@@ -2517,43 +3885,224 @@ var init_identity = __esm({
2517
3885
  }
2518
3886
  });
2519
3887
 
2520
- // src/tracing/session.ts
2521
- var session_exports2 = {};
2522
- __export(session_exports2, {
2523
- SESSION_ID_ATTRIBUTE: () => SESSION_ID_ATTRIBUTE,
2524
- SessionSpanProcessor: () => SessionSpanProcessor,
2525
- getAmbientSessionId: () => getAmbientSessionId,
2526
- withSession: () => withSession
2527
- });
2528
- import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
2529
- function getAmbientSessionId() {
2530
- return currentSessionStorage.getStore();
3888
+ // src/tracing/secrets.ts
3889
+ function jsonOrUndefined(text2) {
3890
+ let parsed;
3891
+ try {
3892
+ parsed = JSON.parse(text2);
3893
+ } catch {
3894
+ return void 0;
3895
+ }
3896
+ if (typeof parsed === "string") return parsed;
3897
+ return parsed !== null && typeof parsed === "object" ? parsed : void 0;
2531
3898
  }
2532
- function withSession(sessionId, fn) {
2533
- return new Promise((resolve29, reject) => {
2534
- currentSessionStorage.run(sessionId, () => {
2535
- Promise.resolve().then(fn).then(resolve29, reject);
2536
- });
3899
+ function encodings(value) {
3900
+ return [value, percentEncoded(value), JSON.stringify(value).slice(1, -1)];
3901
+ }
3902
+ function percentEncoded(value) {
3903
+ try {
3904
+ return encodeURIComponent(value);
3905
+ } catch {
3906
+ return value;
3907
+ }
3908
+ }
3909
+ function union(sets) {
3910
+ return new Set(sets.flatMap((set) => [...set]));
3911
+ }
3912
+ function leaves(value) {
3913
+ if (typeof value === "string") {
3914
+ return [...value].length >= MIN_SECRET_LENGTH ? /* @__PURE__ */ new Set([value]) : /* @__PURE__ */ new Set();
3915
+ }
3916
+ if (Array.isArray(value)) return union(value.map(leaves));
3917
+ if (value === null || typeof value !== "object") return /* @__PURE__ */ new Set();
3918
+ return union(Object.values(value).map(leaves));
3919
+ }
3920
+ function sameAttributes(before, after) {
3921
+ const keys = Object.keys(before);
3922
+ if (keys.length !== Object.keys(after).length) return false;
3923
+ return keys.every(
3924
+ (key2) => before[key2] === after[key2] || sameArray(before[key2], after[key2])
3925
+ );
3926
+ }
3927
+ function sameArray(before, after) {
3928
+ if (!Array.isArray(before) || !Array.isArray(after)) return false;
3929
+ return before.length === after.length && before.every((item, i) => item === after[i]);
3930
+ }
3931
+ function scrubbedRead(reads, property) {
3932
+ return typeof property === "string" && property in reads ? reads[property] : void 0;
3933
+ }
3934
+ function viewOf(span, reads) {
3935
+ const view = new Proxy(span, {
3936
+ get(target, property) {
3937
+ const read = scrubbedRead(reads, property);
3938
+ if (read) return read();
3939
+ const value = Reflect.get(target, property, target);
3940
+ if (typeof value !== "function") return value;
3941
+ return (...args) => {
3942
+ const result = value.apply(target, args);
3943
+ return result === target ? view : result;
3944
+ };
3945
+ },
3946
+ getOwnPropertyDescriptor(target, property) {
3947
+ const descriptor = Reflect.getOwnPropertyDescriptor(target, property);
3948
+ const read = scrubbedRead(reads, property);
3949
+ if (!read || !descriptor || !("value" in descriptor)) return descriptor;
3950
+ return { ...descriptor, value: read() };
3951
+ }
2537
3952
  });
3953
+ return view;
2538
3954
  }
2539
- var SESSION_ID_ATTRIBUTE, currentSessionStorage, SessionSpanProcessor;
2540
- var init_session2 = __esm({
2541
- "src/tracing/session.ts"() {
3955
+ var SECRET_KEYS, REDACTED2, MIN_SECRET_LENGTH, SpanSecrets, SPAN_SECRETS, SecretRedactingSpanProcessor;
3956
+ var init_secrets = __esm({
3957
+ "src/tracing/secrets.ts"() {
2542
3958
  "use strict";
2543
- SESSION_ID_ATTRIBUTE = "gateway.session.id";
2544
- currentSessionStorage = new AsyncLocalStorage2();
2545
- SessionSpanProcessor = class {
2546
- onStart(span, _parentContext) {
2547
- const sessionId = getAmbientSessionId();
2548
- if (sessionId) {
2549
- span.setAttribute(SESSION_ID_ATTRIBUTE, sessionId);
3959
+ SECRET_KEYS = /* @__PURE__ */ new Set([
3960
+ "authorization_token",
3961
+ "authorizationToken"
3962
+ ]);
3963
+ REDACTED2 = "[redacted: holds a credential]";
3964
+ MIN_SECRET_LENGTH = 8;
3965
+ SpanSecrets = class {
3966
+ constructor(keys = SECRET_KEYS) {
3967
+ this.keys = keys;
3968
+ }
3969
+ keys;
3970
+ isSecret(key2) {
3971
+ return this.keys.has(key2);
3972
+ }
3973
+ drops(attribute) {
3974
+ return this.mentions(attribute);
3975
+ }
3976
+ strip(value) {
3977
+ if (typeof value === "string") return this.stripNested(value);
3978
+ if (Array.isArray(value)) return value.map((item) => this.strip(item));
3979
+ if (value === null || typeof value !== "object") return value;
3980
+ return Object.fromEntries(
3981
+ Object.entries(value).filter(([key2]) => !this.isSecret(key2)).map(([key2, item]) => [key2, this.strip(item)])
3982
+ );
3983
+ }
3984
+ scrubAttribute(value) {
3985
+ try {
3986
+ return this.scrubbedValue(value);
3987
+ } catch {
3988
+ return Array.isArray(value) ? [REDACTED2] : REDACTED2;
3989
+ }
3990
+ }
3991
+ scrubbedValue(value) {
3992
+ if (typeof value === "string") return this.scrubbedText(value);
3993
+ if (!Array.isArray(value)) return value;
3994
+ const results = value.map(
3995
+ (item) => typeof item === "string" ? this.cleaned(item) : { text: item, removed: /* @__PURE__ */ new Set() }
3996
+ );
3997
+ const removed = new Set(results.flatMap((r) => [...r.removed]));
3998
+ const scrubbed = results.map((r) => r.text);
3999
+ const withheld = scrubbed.some(
4000
+ (item) => typeof item === "string" && this.carries(item, removed)
4001
+ );
4002
+ return withheld ? [REDACTED2] : scrubbed;
4003
+ }
4004
+ scrubAttributes(attributes) {
4005
+ return Object.fromEntries(
4006
+ Object.entries(attributes).filter(([key2]) => !this.drops(key2)).map(([key2, value]) => [key2, this.scrubAttribute(value)])
4007
+ );
4008
+ }
4009
+ mentions(text2) {
4010
+ return [...this.keys].some((key2) => text2.includes(key2));
4011
+ }
4012
+ scrubbedText(text2) {
4013
+ const { text: cleaned, removed } = this.cleaned(text2);
4014
+ return this.carries(cleaned, removed) ? REDACTED2 : cleaned;
4015
+ }
4016
+ cleaned(text2) {
4017
+ if (!this.mentions(text2)) return { text: text2, removed: /* @__PURE__ */ new Set() };
4018
+ const parsed = jsonOrUndefined(text2);
4019
+ if (parsed === void 0) return { text: REDACTED2, removed: /* @__PURE__ */ new Set() };
4020
+ return {
4021
+ text: JSON.stringify(this.strip(parsed)),
4022
+ removed: this.removed(parsed)
4023
+ };
4024
+ }
4025
+ carries(text2, removed) {
4026
+ if (text2 === REDACTED2 || this.mentions(text2)) return true;
4027
+ return [...removed].some(
4028
+ (value) => encodings(value).some((form) => text2.includes(form))
4029
+ );
4030
+ }
4031
+ removed(value) {
4032
+ if (typeof value === "string") {
4033
+ const nested = this.mentions(value) ? jsonOrUndefined(value) : void 0;
4034
+ return nested === void 0 ? /* @__PURE__ */ new Set() : this.removed(nested);
4035
+ }
4036
+ if (Array.isArray(value)) return union(value.map((v) => this.removed(v)));
4037
+ if (value === null || typeof value !== "object") return /* @__PURE__ */ new Set();
4038
+ return union(
4039
+ Object.entries(value).map(
4040
+ ([key2, item]) => this.isSecret(key2) ? leaves(item) : this.removed(item)
4041
+ )
4042
+ );
4043
+ }
4044
+ stripNested(text2) {
4045
+ if (!this.mentions(text2)) return text2;
4046
+ const parsed = jsonOrUndefined(text2);
4047
+ if (parsed === void 0) return text2;
4048
+ return JSON.stringify(this.strip(parsed));
4049
+ }
4050
+ };
4051
+ SPAN_SECRETS = new SpanSecrets();
4052
+ SecretRedactingSpanProcessor = class {
4053
+ constructor(inner, secrets = SPAN_SECRETS) {
4054
+ this.inner = inner;
4055
+ this.secrets = secrets;
4056
+ }
4057
+ inner;
4058
+ secrets;
4059
+ views = /* @__PURE__ */ new WeakMap();
4060
+ onStart(span, parentContext) {
4061
+ this.inner.onStart(this.viewFor(span), parentContext);
4062
+ }
4063
+ onEnd(span) {
4064
+ const view = this.viewFor(span);
4065
+ try {
4066
+ void [view.attributes, view.events, view.status];
4067
+ } catch (error) {
4068
+ console.warn(
4069
+ `[gatewaysdk.tracing] Dropped span "${span.name}": could not redact it: ${error?.name}`
4070
+ );
4071
+ return;
2550
4072
  }
4073
+ this.inner.onEnd(view);
4074
+ }
4075
+ viewFor(span) {
4076
+ const known = this.views.get(span);
4077
+ if (known) return known;
4078
+ const view = viewOf(span, {
4079
+ attributes: () => this.scrubbedAttributes(span.attributes),
4080
+ events: () => span.events.map((event) => this.scrubbedEvent(event)),
4081
+ status: () => this.scrubbedStatus(span.status)
4082
+ });
4083
+ this.views.set(span, view);
4084
+ return view;
2551
4085
  }
2552
- onEnd(_span) {
4086
+ forceFlush() {
4087
+ return this.inner.forceFlush();
2553
4088
  }
2554
- async shutdown() {
4089
+ shutdown() {
4090
+ return this.inner.shutdown();
2555
4091
  }
2556
- async forceFlush() {
4092
+ scrubbedAttributes(attributes) {
4093
+ const clean2 = this.secrets.scrubAttributes(attributes);
4094
+ return sameAttributes(attributes, clean2) ? attributes : clean2;
4095
+ }
4096
+ scrubbedStatus(status) {
4097
+ if (!status.message) return status;
4098
+ const message = this.secrets.scrubAttribute(status.message);
4099
+ return message === status.message ? status : { ...status, message };
4100
+ }
4101
+ scrubbedEvent(event) {
4102
+ if (!event.attributes) return event;
4103
+ const attributes = this.scrubbedAttributes(event.attributes);
4104
+ if (attributes === event.attributes) return event;
4105
+ return { ...event, attributes };
2557
4106
  }
2558
4107
  };
2559
4108
  }
@@ -2579,14 +4128,14 @@ function coerceSignalValue(value) {
2579
4128
  return { numericValue: value, inferredType: "NUMERIC" };
2580
4129
  }
2581
4130
  async function success(name, value = true, options = {}) {
2582
- let client3;
4131
+ let client4;
2583
4132
  try {
2584
- client3 = ScoresClient.fromEnv();
4133
+ client4 = ScoresClient.fromEnv();
2585
4134
  } catch (error) {
2586
4135
  console.warn(`[gateway.scores] success '${name}' skipped`, error);
2587
4136
  return;
2588
4137
  }
2589
- await client3.success(name, value, options);
4138
+ await client4.success(name, value, options);
2590
4139
  }
2591
4140
  var SUCCESS_SIGNAL_KEY, SUCCESS_METRIC_NAME_KEY, AGENT_ID_KEY, ScoreError, ScoresClient, scores;
2592
4141
  var init_scores = __esm({
@@ -2780,7 +4329,7 @@ var require_package = __commonJS({
2780
4329
  "package.json"(exports, module) {
2781
4330
  module.exports = {
2782
4331
  name: "@withgateway/sdk",
2783
- version: "0.2.9",
4332
+ version: "0.3.0",
2784
4333
  description: "Gateway SDK for TypeScript - A/B experiments, tracing, and observability",
2785
4334
  main: "./dist/index.js",
2786
4335
  module: "./dist/index.mjs",
@@ -2980,7 +4529,7 @@ var require_package = __commonJS({
2980
4529
  });
2981
4530
 
2982
4531
  // src/build/index.ts
2983
- import { createHash } from "crypto";
4532
+ import { createHash as createHash2 } from "crypto";
2984
4533
  function canonicalJson(value) {
2985
4534
  if (value === null || typeof value !== "object") {
2986
4535
  return JSON.stringify(value);
@@ -2992,7 +4541,7 @@ function canonicalJson(value) {
2992
4541
  return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonicalJson(v)}`).join(",")}}`;
2993
4542
  }
2994
4543
  function sha256(text2) {
2995
- return `sha256:${createHash("sha256").update(text2).digest("hex")}`;
4544
+ return `sha256:${createHash2("sha256").update(text2).digest("hex")}`;
2996
4545
  }
2997
4546
  function getRegisteredTools() {
2998
4547
  return [...registeredTools.values()].sort(
@@ -3300,7 +4849,7 @@ function buildProvider(config, logFn) {
3300
4849
  const spanProcessors = [];
3301
4850
  if (config.customSpanProcessors) {
3302
4851
  for (const sp of config.customSpanProcessors) {
3303
- spanProcessors.push(sp);
4852
+ spanProcessors.push(new SecretRedactingSpanProcessor(sp));
3304
4853
  logFn(
3305
4854
  "Added custom span processor: %s",
3306
4855
  sp.constructor?.name ?? "unknown"
@@ -3319,7 +4868,11 @@ function buildProvider(config, logFn) {
3319
4868
  if (config.batch?.maxExportBatchSize) {
3320
4869
  batchConfig.maxExportBatchSize = config.batch.maxExportBatchSize;
3321
4870
  }
3322
- spanProcessors.push(new BatchSpanProcessor(exporter, batchConfig));
4871
+ spanProcessors.push(
4872
+ new SecretRedactingSpanProcessor(
4873
+ new BatchSpanProcessor(exporter, batchConfig)
4874
+ )
4875
+ );
3323
4876
  let provider = new NodeTracerProvider({
3324
4877
  resource: createResource(resourceAttrs)
3325
4878
  });
@@ -3457,7 +5010,8 @@ var init_init = __esm({
3457
5010
  "src/tracing/init.ts"() {
3458
5011
  "use strict";
3459
5012
  init_identity();
3460
- init_session2();
5013
+ init_secrets();
5014
+ init_session();
3461
5015
  init_scores();
3462
5016
  init_build();
3463
5017
  ENV_VARS = {
@@ -3613,7 +5167,7 @@ async function runTask(ref, agent, opts) {
3613
5167
  let extra = {};
3614
5168
  try {
3615
5169
  const invoke = () => agent(taskRun);
3616
- const result = traced ? await (await Promise.resolve().then(() => (init_session2(), session_exports2))).withSession(runId, invoke) : await invoke();
5170
+ const result = traced ? await (await Promise.resolve().then(() => (init_session(), session_exports))).withSession(runId, invoke) : await invoke();
3617
5171
  ({ report, extra } = reportFromResult(result));
3618
5172
  } catch (error) {
3619
5173
  const message = (error instanceof Error ? error.message : String(error)) || "Unknown error";
@@ -3686,7 +5240,7 @@ var init_taskRun = __esm({
3686
5240
  "use strict";
3687
5241
  init_browser();
3688
5242
  init_evals();
3689
- init_session();
5243
+ init_session2();
3690
5244
  init_taskSessions();
3691
5245
  TaskRun = class {
3692
5246
  constructor(runId, instruction, model, sessions, manifest) {
@@ -3995,7 +5549,7 @@ var init_checkoutTarget = __esm({
3995
5549
  });
3996
5550
 
3997
5551
  // src/worlds/worldDir.ts
3998
- import { createHash as createHash2 } from "crypto";
5552
+ import { createHash as createHash3 } from "crypto";
3999
5553
  import * as fs3 from "fs";
4000
5554
  import * as path3 from "path";
4001
5555
  var WORLD_MANIFEST, API_BUNDLE_MANIFEST, BUNDLED_WORLD_PREFIX, CONNECTOR_SPEC, PYPROJECT, BENCHMARK_CONFIG, WORLD_SCHEMA_MARKERS, WORLD_ROOT_MARKERS, BROAD_ROOT_MARKERS, SKIPPED_DIRS, V1_DEP, V1_IMPORT, V1_TASKSET, HARBOR_TASK, skippedDir, byCodePoint, WorldDir;
@@ -4105,7 +5659,7 @@ var init_worldDir = __esm({
4105
5659
  * sorted order: the version's identity, byte-compatible with
4106
5660
  * `_archive.compute_content_hash` and Prime Intellect. */
4107
5661
  get contentHash() {
4108
- const hasher = createHash2("sha256");
5662
+ const hasher = createHash3("sha256");
4109
5663
  for (const rel of this.archivePaths) {
4110
5664
  hasher.update(Buffer.from(`file:${rel}`, "utf-8"));
4111
5665
  hasher.update(fs3.readFileSync(path3.join(this.dir, rel)));
@@ -4301,7 +5855,7 @@ __export(hub_exports, {
4301
5855
  snapshotTreeHashes: () => snapshotTreeHashes,
4302
5856
  writeLocalMeta: () => writeLocalMeta
4303
5857
  });
4304
- import { createHash as createHash3 } from "crypto";
5858
+ import { createHash as createHash4 } from "crypto";
4305
5859
  import { gzipSync } from "zlib";
4306
5860
  import * as fs5 from "fs";
4307
5861
  import * as path5 from "path";
@@ -4413,7 +5967,7 @@ function writeLocalMeta(dir, meta) {
4413
5967
  function snapshotTreeHashes(dir) {
4414
5968
  const out = {};
4415
5969
  for (const relPath of collectArchiveRelPaths(dir)) {
4416
- out[relPath] = createHash3("sha256").update(fs5.readFileSync(path5.join(dir, relPath))).digest("hex");
5970
+ out[relPath] = createHash4("sha256").update(fs5.readFileSync(path5.join(dir, relPath))).digest("hex");
4417
5971
  }
4418
5972
  return out;
4419
5973
  }
@@ -4459,7 +6013,7 @@ function buildFileManifest(dir) {
4459
6013
  path: relPath,
4460
6014
  isDirectory: false,
4461
6015
  size: payload.length,
4462
- sha256: createHash3("sha256").update(payload).digest("hex")
6016
+ sha256: createHash4("sha256").update(payload).digest("hex")
4463
6017
  };
4464
6018
  });
4465
6019
  }
@@ -4684,7 +6238,7 @@ var init_hub = __esm({
4684
6238
  tracked;
4685
6239
  declared;
4686
6240
  };
4687
- sha256b64 = (data) => createHash3("sha256").update(data).digest("base64");
6241
+ sha256b64 = (data) => createHash4("sha256").update(data).digest("base64");
4688
6242
  DetachedPushError = class extends Error {
4689
6243
  constructor(dir, tag) {
4690
6244
  super(
@@ -5322,7 +6876,7 @@ var init_json = __esm({
5322
6876
  });
5323
6877
 
5324
6878
  // src/worlds/transforms.ts
5325
- import { createHash as createHash4 } from "crypto";
6879
+ import { createHash as createHash5 } from "crypto";
5326
6880
  function parseTransform(name) {
5327
6881
  const simple = Object.prototype.hasOwnProperty.call(SIMPLE, name) ? SIMPLE[name] : void 0;
5328
6882
  if (simple) return simple;
@@ -5360,7 +6914,7 @@ var init_transforms = __esm({
5360
6914
  return at === -1 ? "" : value.slice(at + 1).toLowerCase();
5361
6915
  };
5362
6916
  stripPrefix = (prefix) => (value) => value.startsWith(prefix) ? value.slice(prefix.length) : value;
5363
- hex = (algorithm, value) => createHash4(algorithm).update(value, "utf8").digest("hex");
6917
+ hex = (algorithm, value) => createHash5(algorithm).update(value, "utf8").digest("hex");
5364
6918
  SIMPLE = {
5365
6919
  lower: (value) => value.toLowerCase(),
5366
6920
  upper: (value) => value.toUpperCase(),
@@ -5384,7 +6938,7 @@ var init_transforms = __esm({
5384
6938
  });
5385
6939
 
5386
6940
  // src/worlds/redaction.ts
5387
- import { createHash as createHash5 } from "crypto";
6941
+ import { createHash as createHash6 } from "crypto";
5388
6942
  function pyText(value) {
5389
6943
  if (typeof value === "string") return value;
5390
6944
  if (Number.isInteger(value)) return String(value);
@@ -5393,7 +6947,7 @@ function pyText(value) {
5393
6947
  return pyFloatRepr(value);
5394
6948
  }
5395
6949
  function hashForm(slug, plaintext) {
5396
- return "sha256:" + createHash5("sha256").update(`${slug}:${pyText(plaintext)}`, "utf8").digest("hex");
6950
+ return "sha256:" + createHash6("sha256").update(`${slug}:${pyText(plaintext)}`, "utf8").digest("hex");
5397
6951
  }
5398
6952
  function preserveForm(slug, plaintext) {
5399
6953
  const kind = typeof plaintext === "string" ? "str" : isInt(plaintext) ? "int" : "float";
@@ -5402,12 +6956,12 @@ function preserveForm(slug, plaintext) {
5402
6956
  }
5403
6957
  function shapeText(slug, text2, kind) {
5404
6958
  const seed = Buffer.from(`${slug}:${text2}`, "utf8");
5405
- let digest2 = createHash5("sha256").update(seed).digest();
6959
+ let digest2 = createHash6("sha256").update(seed).digest();
5406
6960
  let cursor = 0;
5407
6961
  const out = [];
5408
6962
  for (const char of text2) {
5409
6963
  if (cursor === digest2.length) {
5410
- digest2 = createHash5("sha256").update(Buffer.concat([digest2, seed])).digest();
6964
+ digest2 = createHash6("sha256").update(Buffer.concat([digest2, seed])).digest();
5411
6965
  cursor = 0;
5412
6966
  }
5413
6967
  const byte = digest2[cursor];
@@ -6253,9 +7807,9 @@ import * as path9 from "path";
6253
7807
  import { createRequire } from "module";
6254
7808
  function checkRows(value, where) {
6255
7809
  if (!isObject2(value)) throw new CliError(`${where} must return {entity: [rows]}; got ${value === null ? "null" : Array.isArray(value) ? "an array" : typeof value}`, 1);
6256
- for (const [entity, listed] of Object.entries(value)) {
6257
- if (!Array.isArray(listed)) throw new CliError(`${where}: ${entity} must be a list of rows; got ${listed === null ? "null" : typeof listed}`, 1);
6258
- listed.forEach((row, index2) => {
7810
+ for (const [entity, listed2] of Object.entries(value)) {
7811
+ if (!Array.isArray(listed2)) throw new CliError(`${where}: ${entity} must be a list of rows; got ${listed2 === null ? "null" : typeof listed2}`, 1);
7812
+ listed2.forEach((row, index2) => {
6259
7813
  if (!isObject2(row)) throw new CliError(`${where}: ${entity}[${index2}] is not an object`, 1);
6260
7814
  });
6261
7815
  }
@@ -6417,7 +7971,7 @@ if (fn) {
6417
7971
  });
6418
7972
 
6419
7973
  // src/cli/platform/worldData/batches.ts
6420
- import { createHash as createHash6 } from "crypto";
7974
+ import { createHash as createHash7 } from "crypto";
6421
7975
  import * as fs10 from "fs";
6422
7976
  function isSettled(status) {
6423
7977
  if (!TERMINAL_STATES.has(status.state)) return false;
@@ -6428,7 +7982,7 @@ function uploadHeadersFor(gz) {
6428
7982
  return {
6429
7983
  "content-type": "application/gzip",
6430
7984
  "content-length": String(gz.length),
6431
- "x-amz-checksum-sha256": createHash6("sha256").update(gz).digest("base64")
7985
+ "x-amz-checksum-sha256": createHash7("sha256").update(gz).digest("base64")
6432
7986
  };
6433
7987
  }
6434
7988
  async function forEachLimited(items, limit, fn) {
@@ -6454,12 +8008,12 @@ async function forEachLimited(items, limit, fn) {
6454
8008
  await Promise.all(inFlight);
6455
8009
  if (failure) throw failure;
6456
8010
  }
6457
- async function waitForBatch(client3, batchId, opts = {}) {
6458
- const sleep4 = opts.sleep ?? client3.sleep;
8011
+ async function waitForBatch(client4, batchId, opts = {}) {
8012
+ const sleep4 = opts.sleep ?? client4.sleep;
6459
8013
  let delay = opts.initialDelayMs ?? 1e3;
6460
8014
  let last = "";
6461
8015
  for (; ; ) {
6462
- const status = await client3.get(batchId);
8016
+ const status = await client4.get(batchId);
6463
8017
  const phase = phaseLine(status);
6464
8018
  if (phase !== last) {
6465
8019
  opts.onPhase?.(phase);
@@ -6653,7 +8207,7 @@ var init_batches = __esm({
6653
8207
  });
6654
8208
 
6655
8209
  // src/cli/platform/worldData/chunker.ts
6656
- import { createHash as createHash7 } from "crypto";
8210
+ import { createHash as createHash8 } from "crypto";
6657
8211
  import { deflateRawSync } from "zlib";
6658
8212
  function chunkLine(row, declared) {
6659
8213
  if (declared !== null) return dumps(row.row) + "\n";
@@ -6694,12 +8248,12 @@ function finishChunk(ordinal, raw, rows, entity, firstRow = 0) {
6694
8248
  const gz = gzipDeterministic(raw, { name: chunkName(ordinal) });
6695
8249
  return {
6696
8250
  ordinal,
6697
- digest: createHash7("sha256").update(gz).digest("hex"),
8251
+ digest: createHash8("sha256").update(gz).digest("hex"),
6698
8252
  bytes: gz.length,
6699
8253
  rows,
6700
8254
  entity,
6701
8255
  rawBytes: raw.length,
6702
- contentSha256: createHash7("sha256").update(raw).digest("hex"),
8256
+ contentSha256: createHash8("sha256").update(raw).digest("hex"),
6703
8257
  firstRow,
6704
8258
  gz
6705
8259
  };
@@ -6779,8 +8333,8 @@ __export(push_exports, {
6779
8333
  pushRows: () => pushRows
6780
8334
  });
6781
8335
  async function pushRows(creds, slug, rows, opts = {}) {
6782
- const client3 = opts.sleep ? new WorldDataApi(creds, slug, opts.sleep) : new WorldDataApi(creds, slug);
6783
- const opened = await client3.open({
8336
+ const client4 = opts.sleep ? new WorldDataApi(creds, slug, opts.sleep) : new WorldDataApi(creds, slug);
8337
+ const opened = await client4.open({
6784
8338
  mode: opts.mode ?? "append",
6785
8339
  merge: "upsert",
6786
8340
  ...opts.redact && opts.redact !== "off" ? { redact: opts.redact } : {},
@@ -6791,16 +8345,16 @@ async function pushRows(creds, slug, rows, opts = {}) {
6791
8345
  });
6792
8346
  if (!opened.batchId) throw new Error("the platform opened no batch (no batchId in the answer)");
6793
8347
  const tagged = (async function* () {
6794
- for (const [entity, listed] of Object.entries(rows))
6795
- for (let index2 = 0; index2 < listed.length; index2++)
6796
- yield { entity, row: parseJson(JSON.stringify(listed[index2])), where: `${entity}[${index2}]` };
8348
+ for (const [entity, listed2] of Object.entries(rows))
8349
+ for (let index2 = 0; index2 < listed2.length; index2++)
8350
+ yield { entity, row: parseJson(JSON.stringify(listed2[index2])), where: `${entity}[${index2}]` };
6797
8351
  })();
6798
8352
  const chunks = buildChunks(tagged, { chunkBytes: opts.chunkBytes ?? DEFAULT_CHUNK_BYTES, chunkRows: null, entity: null });
6799
8353
  await forEachLimited(chunks, Math.max(1, opts.parallel ?? 4), async (chunk) => {
6800
- await client3.upload(opened.batchId, chunk);
8354
+ await client4.upload(opened.batchId, chunk);
6801
8355
  });
6802
- await client3.complete(opened.batchId);
6803
- return waitForBatch(client3, opened.batchId, { initialDelayMs: pollMs() });
8356
+ await client4.complete(opened.batchId);
8357
+ return waitForBatch(client4, opened.batchId, { initialDelayMs: pollMs() });
6804
8358
  }
6805
8359
  function pollMs() {
6806
8360
  const raw = Number(process.env.GATEWAY_WORLD_DATA_POLL_MS ?? 1e3);
@@ -6857,12 +8411,12 @@ function toolCallRecordsIn(text2, where) {
6857
8411
  const stripped = text2.trim();
6858
8412
  if (!stripped) return [];
6859
8413
  if (stripped.startsWith("[")) {
6860
- const listed = JSON.parse(stripped);
6861
- if (!Array.isArray(listed)) throw new Error(`${where} is neither a JSON array nor JSON Lines`);
6862
- listed.forEach((item, index2) => {
8414
+ const listed2 = JSON.parse(stripped);
8415
+ if (!Array.isArray(listed2)) throw new Error(`${where} is neither a JSON array nor JSON Lines`);
8416
+ listed2.forEach((item, index2) => {
6863
8417
  if (!isObject3(item)) throw new Error(`${where}[${index2}] is not an object`);
6864
8418
  });
6865
- return listed;
8419
+ return listed2;
6866
8420
  }
6867
8421
  const records2 = [];
6868
8422
  const lines = text2.split(/\r?\n/);
@@ -7020,7 +8574,7 @@ function transformReport(world, records2, rows, stderr, outcome) {
7020
8574
  ingested: records2,
7021
8575
  skipped: {},
7022
8576
  refusals: [],
7023
- rows: Object.fromEntries(Object.entries(rows).map(([entity, listed]) => [entity, listed.length])),
8577
+ rows: Object.fromEntries(Object.entries(rows).map(([entity, listed2]) => [entity, listed2.length])),
7024
8578
  dryRun: outcome.dryRun,
7025
8579
  redact: outcome.redact,
7026
8580
  changed: outcome.changed,
@@ -7069,7 +8623,7 @@ var init_ingest = __esm({
7069
8623
  });
7070
8624
 
7071
8625
  // src/worlds/editSessions.ts
7072
- var WORLDS, WorldEditClient;
8626
+ var WORLDS, WorldEditClient, TASK_EDITS, TaskEditClient;
7073
8627
  var init_editSessions = __esm({
7074
8628
  "src/worlds/editSessions.ts"() {
7075
8629
  "use strict";
@@ -7101,6 +8655,22 @@ var init_editSessions = __esm({
7101
8655
  return apiRequest(this.options, "POST", `${WORLDS}/${encodeURIComponent(slug)}/edits/rollback`, input);
7102
8656
  }
7103
8657
  };
8658
+ TASK_EDITS = "/api/public/world-task-edits";
8659
+ TaskEditClient = class {
8660
+ constructor(options = {}) {
8661
+ this.options = options;
8662
+ }
8663
+ options;
8664
+ status(task) {
8665
+ return apiRequest(this.options, "POST", `${TASK_EDITS}/status`, { task });
8666
+ }
8667
+ close(task, input = {}) {
8668
+ return apiRequest(this.options, "POST", `${TASK_EDITS}/close`, { task, ...input });
8669
+ }
8670
+ rollback(task, input) {
8671
+ return apiRequest(this.options, "POST", `${TASK_EDITS}/rollback`, { task, ...input });
8672
+ }
8673
+ };
7104
8674
  }
7105
8675
  });
7106
8676
 
@@ -7196,6 +8766,10 @@ var init_dryRun = __esm({
7196
8766
  // src/worlds/index.ts
7197
8767
  var worlds_exports = {};
7198
8768
  __export(worlds_exports, {
8769
+ ACTION_NAMES: () => ACTION_NAMES,
8770
+ ActionTracer: () => ActionTracer,
8771
+ AnthropicComputer: () => AnthropicComputer,
8772
+ AnthropicComputer20251124: () => AnthropicComputer20251124,
7199
8773
  ApiError: () => ApiError,
7200
8774
  BROWSER_GONE_PATTERNS: () => BROWSER_GONE_PATTERNS,
7201
8775
  BROWSER_TIERS: () => BROWSER_TIERS,
@@ -7207,11 +8781,13 @@ __export(worlds_exports, {
7207
8781
  CALL_BODY_LIMIT_LABEL: () => CALL_BODY_LIMIT_LABEL,
7208
8782
  COMPUTER_USE_SPECS: () => COMPUTER_USE_SPECS,
7209
8783
  CheckoutProvenance: () => CheckoutProvenance,
8784
+ ComputerAction: () => ComputerAction,
7210
8785
  DEFAULT_BRANCH: () => DEFAULT_BRANCH,
7211
8786
  DEFAULT_VIEWPORT: () => DEFAULT_VIEWPORT,
7212
8787
  DRY_RUN_AGENT: () => DRY_RUN_AGENT,
7213
8788
  DRY_RUN_KIND: () => DRY_RUN_KIND,
7214
8789
  DetachedPushError: () => DetachedPushError,
8790
+ Display: () => Display,
7215
8791
  DryRunOutcome: () => DryRunOutcome,
7216
8792
  EVENT_BATCH_SIZE: () => EVENT_BATCH_SIZE,
7217
8793
  EVENT_FLUSH_INTERVAL_MS: () => EVENT_FLUSH_INTERVAL_MS,
@@ -7221,19 +8797,30 @@ __export(worlds_exports, {
7221
8797
  GatewayEvalsClient: () => GatewayEvalsClient,
7222
8798
  HostedDryRunClient: () => HostedDryRunClient,
7223
8799
  IDLE_WARNING_MINUTES: () => IDLE_WARNING_MINUTES,
8800
+ KEY_NAMES: () => KEY_NAMES,
8801
+ KeyChord: () => KeyChord,
8802
+ NOT_EXECUTED: () => NOT_EXECUTED,
7224
8803
  NO_GRADER_REASON: () => NO_GRADER_REASON,
8804
+ NativeComputer: () => NativeComputer,
8805
+ OpenAIComputer: () => OpenAIComputer,
8806
+ OpenAIPreviewComputer: () => OpenAIPreviewComputer,
7225
8807
  PLATFORM_TIMEOUT_DEFAULT_MS: () => PLATFORM_TIMEOUT_DEFAULT_MS,
7226
8808
  PLATFORM_TIMEOUT_ENV: () => PLATFORM_TIMEOUT_ENV,
8809
+ PendingSafetyChecks: () => PendingSafetyChecks,
7227
8810
  PlatformTransport: () => PlatformTransport,
7228
8811
  PushSlugConflict: () => PushSlugConflict,
7229
8812
  RECOVER_BUDGET_MS: () => RECOVER_BUDGET_MS,
7230
8813
  SANDBOX_REQUEST_TIMEOUT_MS: () => SANDBOX_REQUEST_TIMEOUT_MS,
8814
+ SECRET_KEY: () => SECRET_KEY,
7231
8815
  SESSION_STATES: () => SESSION_STATES,
8816
+ SPAN_PREFIX: () => SPAN_PREFIX,
7232
8817
  STATUS_WAIT_CAP_SECONDS: () => STATUS_WAIT_CAP_SECONDS,
7233
8818
  STRIP_PREFIX: () => STRIP_PREFIX,
7234
8819
  SURFACE_KINDS: () => SURFACE_KINDS,
8820
+ Screen: () => Screen,
7235
8821
  SecretScrubber: () => SecretScrubber,
7236
8822
  TRANSFORMS: () => TRANSFORMS,
8823
+ TaskEditClient: () => TaskEditClient,
7237
8824
  TaskRun: () => TaskRun,
7238
8825
  TaskSessions: () => TaskSessions,
7239
8826
  TransportCause: () => TransportCause,
@@ -7306,6 +8893,7 @@ __export(worlds_exports, {
7306
8893
  parseTransform: () => parseTransform,
7307
8894
  parseWorldTaskRefs: () => parseWorldTaskRefs,
7308
8895
  platformTimeoutMs: () => platformTimeoutMs,
8896
+ playwrightKey: () => playwrightKey,
7309
8897
  preserveForm: () => preserveForm,
7310
8898
  propose: () => propose,
7311
8899
  pull: () => pull,
@@ -7315,6 +8903,7 @@ __export(worlds_exports, {
7315
8903
  pyText: () => pyText,
7316
8904
  queryRows: () => queryRows,
7317
8905
  queryRowsSearch: () => queryRowsSearch,
8906
+ readField: () => readField,
7318
8907
  readLocalMeta: () => readLocalMeta,
7319
8908
  readToolCallRecords: () => readToolCallRecords,
7320
8909
  rebaseConflicts: () => rebaseConflicts,
@@ -7564,7 +9153,7 @@ var init_worlds = __esm({
7564
9153
  "use strict";
7565
9154
  init_transport();
7566
9155
  init_transport();
7567
- init_session();
9156
+ init_session2();
7568
9157
  init_sessionList();
7569
9158
  init_sessionContract();
7570
9159
  init_taskRef();
@@ -7576,6 +9165,7 @@ var init_worlds = __esm({
7576
9165
  init_evals();
7577
9166
  init_browser();
7578
9167
  init_browserReconnect();
9168
+ init_nativeComputer();
7579
9169
  init_hub();
7580
9170
  init_validate();
7581
9171
  init_describe();
@@ -7642,7 +9232,7 @@ var init_worlds = __esm({
7642
9232
  * worlds/session.ts.
7643
9233
  */
7644
9234
  async open(task, opts = {}) {
7645
- const { openSession: openSession2 } = await Promise.resolve().then(() => (init_session(), session_exports));
9235
+ const { openSession: openSession2 } = await Promise.resolve().then(() => (init_session2(), session_exports2));
7646
9236
  return openSession2(this.slug, {
7647
9237
  task,
7648
9238
  versionId: this.version.versionId,
@@ -8558,7 +10148,7 @@ var init_connector = __esm({
8558
10148
  });
8559
10149
 
8560
10150
  // src/files/index.ts
8561
- import { createHash as createHash11 } from "crypto";
10151
+ import { createHash as createHash12 } from "crypto";
8562
10152
  import * as fs32 from "fs";
8563
10153
  import * as path23 from "path";
8564
10154
  import { Readable, Transform } from "stream";
@@ -8612,7 +10202,7 @@ async function confirmUpload(options = {}, fileId, ok = true) {
8612
10202
  return apiRequest(options, "POST", `${BASE}/confirm`, { fileId, ok });
8613
10203
  }
8614
10204
  async function sha256Base64(localPath) {
8615
- const hash = createHash11("sha256");
10205
+ const hash = createHash12("sha256");
8616
10206
  for await (const chunk of fs32.createReadStream(localPath)) hash.update(chunk);
8617
10207
  return hash.digest("base64");
8618
10208
  }
@@ -8665,7 +10255,7 @@ async function uploadBytes(options = {}, bytes, targetPath, upload = {}) {
8665
10255
  if (!bytes.length) throw new Error("nothing to upload: the content is empty");
8666
10256
  const target = drivePath(targetPath);
8667
10257
  const contentType = upload.contentType ?? contentTypeFor(target);
8668
- const sha2562 = createHash11("sha256").update(bytes).digest("base64");
10258
+ const sha2562 = createHash12("sha256").update(bytes).digest("base64");
8669
10259
  const granted = await requestUpload(options, { path: target, contentLength: bytes.length, contentType, sha256: sha2562, ...upload.overwrite ? { overwrite: true } : {} });
8670
10260
  try {
8671
10261
  await putPresigned(granted.uploadUrl, new Uint8Array(bytes), { contentType, contentLength: bytes.length, sha256: sha2562 });
@@ -9752,10 +11342,10 @@ function swapValue(text2, needle, replacement) {
9752
11342
  }
9753
11343
 
9754
11344
  // src/hooks/standInDigits.ts
9755
- import { createHash as createHash8 } from "crypto";
11345
+ import { createHash as createHash9 } from "crypto";
9756
11346
  function standInDigits(realDigits, identityName) {
9757
11347
  if (!realDigits) return "";
9758
- const digest2 = createHash8("sha256").update(`${identityName}:${realDigits}`).digest("hex");
11348
+ const digest2 = createHash9("sha256").update(`${identityName}:${realDigits}`).digest("hex");
9759
11349
  let digits = "";
9760
11350
  for (let i = 0; i < realDigits.length; i++)
9761
11351
  digits += String(parseInt(digest2[i % digest2.length], 16) % 10);
@@ -9789,7 +11379,7 @@ var DeclaredStandIn = class _DeclaredStandIn {
9789
11379
  };
9790
11380
 
9791
11381
  // src/hooks/alias.ts
9792
- import { createHash as createHash9, createHmac, randomBytes as randomBytes2 } from "crypto";
11382
+ import { createHash as createHash10, createHmac, randomBytes as randomBytes2 } from "crypto";
9793
11383
  var GIVEN = [
9794
11384
  "John",
9795
11385
  "Mary",
@@ -10049,7 +11639,7 @@ function nameParts(name) {
10049
11639
  function format(template, parts2) {
10050
11640
  return template.replace(/\{(\w+)\}/g, (_, key2) => parts2[key2] ?? "").trim();
10051
11641
  }
10052
- var pair = (real, fake, template) => [
11642
+ var pair2 = (real, fake, template) => [
10053
11643
  format(template, real),
10054
11644
  format(template, fake)
10055
11645
  ];
@@ -10109,7 +11699,7 @@ function namePairs(real, fake) {
10109
11699
  const out = [[real, fake]];
10110
11700
  if (realParts.given && realParts.surname) {
10111
11701
  for (const template of NAME_FORMS) {
10112
- const p = pair(realParts, fakeParts, template);
11702
+ const p = pair2(realParts, fakeParts, template);
10113
11703
  if (p[0].length > 2 && !p[0].includes("{")) out.push(p);
10114
11704
  }
10115
11705
  }
@@ -10147,7 +11737,7 @@ function emailPairs(real, fake) {
10147
11737
  };
10148
11738
  const out = [[real, fake]];
10149
11739
  for (const template of EMAIL_FORMS) {
10150
- const p = pair(realParts, fakeParts, template);
11740
+ const p = pair2(realParts, fakeParts, template);
10151
11741
  if (p[0].length > 2) out.push(p);
10152
11742
  }
10153
11743
  return dedupe(out);
@@ -10598,9 +12188,9 @@ var AliasMap = class _AliasMap {
10598
12188
  });
10599
12189
  if (alias.role === "private") {
10600
12190
  for (const slug of this.slugs) {
10601
- const standIn = "sha256:" + createHash9("sha256").update(`${slug}:${canonical(alias.kind, alias.display)}`, "utf8").digest("hex");
12191
+ const standIn = "sha256:" + createHash10("sha256").update(`${slug}:${canonical(alias.kind, alias.display)}`, "utf8").digest("hex");
10602
12192
  alias.variants.push([
10603
- "sha256:" + createHash9("sha256").update(`${slug}:${alias.canonical}`, "utf8").digest("hex"),
12193
+ "sha256:" + createHash10("sha256").update(`${slug}:${alias.canonical}`, "utf8").digest("hex"),
10604
12194
  standIn
10605
12195
  ]);
10606
12196
  this.aliasDigests.add(standIn.toLowerCase());
@@ -11414,7 +13004,7 @@ function inputSchema(shorthand, position) {
11414
13004
  `${position}.input: expected a table of field = "type"`
11415
13005
  );
11416
13006
  const properties = {};
11417
- const required = [];
13007
+ const required2 = [];
11418
13008
  for (const [name, raw] of Object.entries(shorthand)) {
11419
13009
  if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name))
11420
13010
  throw new HookConfigError(
@@ -11448,9 +13038,9 @@ function inputSchema(shorthand, position) {
11448
13038
  `${position}.input.${name}: expected "type" or a schema table`
11449
13039
  );
11450
13040
  properties[name] = schema;
11451
- if (!optional) required.push(name);
13041
+ if (!optional) required2.push(name);
11452
13042
  }
11453
- return { type: "object", properties, required };
13043
+ return { type: "object", properties, required: required2 };
11454
13044
  }
11455
13045
  function placeholders(value) {
11456
13046
  if (typeof value === "string")
@@ -15601,7 +17191,7 @@ function editVerbSpecs() {
15601
17191
  MESSAGE_FLAG,
15602
17192
  {
15603
17193
  name: "force",
15604
- help: "Roll back even when later sessions changed the same paths (their edits to those paths are undone too).",
17194
+ help: "Also undo what reached main after it (later sessions, or writes outside sessions).",
15605
17195
  boolean: true
15606
17196
  },
15607
17197
  HOST_FLAG
@@ -15654,7 +17244,7 @@ var CastRefusal = class extends CliError {
15654
17244
  type;
15655
17245
  };
15656
17246
  var article = (type) => /^[aeiou]/i.test(type) ? "an" : "a";
15657
- var MEMBERS = /* @__PURE__ */ new Set([
17247
+ var MEMBERS2 = /* @__PURE__ */ new Set([
15658
17248
  "integer",
15659
17249
  "number",
15660
17250
  "boolean",
@@ -15673,7 +17263,7 @@ var BOOLEANS = {
15673
17263
  };
15674
17264
  function typeMembers(type) {
15675
17265
  if (type === null) return [];
15676
- return type.split("|").map((part) => part.trim().toLowerCase()).filter((part) => MEMBERS.has(part));
17266
+ return type.split("|").map((part) => part.trim().toLowerCase()).filter((part) => MEMBERS2.has(part));
15677
17267
  }
15678
17268
  function castAs(member, cell) {
15679
17269
  const text2 = cell.trim();
@@ -15709,10 +17299,10 @@ function castJson(member, text2) {
15709
17299
  return isObject(value) ? value : void 0;
15710
17300
  }
15711
17301
  var FieldCaster = class {
15712
- constructor(name, type, required) {
17302
+ constructor(name, type, required2) {
15713
17303
  this.name = name;
15714
17304
  this.type = type;
15715
- this.required = required;
17305
+ this.required = required2;
15716
17306
  this.members = typeMembers(type);
15717
17307
  }
15718
17308
  name;
@@ -16461,8 +18051,8 @@ function parseRows(paths, entity, options = {}) {
16461
18051
  for (const path44 of paths) {
16462
18052
  const text2 = readText(path44);
16463
18053
  const parsed = isDelimitedName(path44) ? csvRowsIn(text2, path44, entity, options) : rowsIn(text2, path44, entity);
16464
- for (const [name, listed] of Object.entries(parsed)) {
16465
- (rows[name] ??= []).push(...listed);
18054
+ for (const [name, listed2] of Object.entries(parsed)) {
18055
+ (rows[name] ??= []).push(...listed2);
16466
18056
  }
16467
18057
  }
16468
18058
  return rows;
@@ -16510,12 +18100,12 @@ function rowsIn(text2, path44, entity) {
16510
18100
  return jsonlRows2(stripped, path44, entity);
16511
18101
  }
16512
18102
  const out = {};
16513
- for (const [name, listed] of Object.entries(document)) {
16514
- if (!Array.isArray(listed))
18103
+ for (const [name, listed2] of Object.entries(document)) {
18104
+ if (!Array.isArray(listed2))
16515
18105
  throw refuse2(
16516
18106
  `${path44}: ${name} must map to an array of rows (JSONL lines are {"entity", "row"})`
16517
18107
  );
16518
- out[name] = listed.map(
18108
+ out[name] = listed2.map(
16519
18109
  (row, index2) => rowObject2(row, `${path44}:${name}[${index2}]`)
16520
18110
  );
16521
18111
  }
@@ -16622,10 +18212,10 @@ var UNCOMMITTED_LISTED = 10;
16622
18212
  function failOnUncommitted(sandboxId, error) {
16623
18213
  const paths = uncommittedPaths(error);
16624
18214
  if (paths === null) throw error;
16625
- const listed = paths.slice(0, UNCOMMITTED_LISTED);
18215
+ const listed2 = paths.slice(0, UNCOMMITTED_LISTED);
16626
18216
  const more = paths.length > UNCOMMITTED_LISTED ? ", \u2026" : "";
16627
18217
  throw new CliError(
16628
- `${paths.length} uncommitted file(s) (${listed.join(", ")}${more}): commit them (gateway worlds sandbox commit ${sandboxId} -m "<why>") or discard them (gateway worlds sandbox close ${sandboxId} --force)`,
18218
+ `${paths.length} uncommitted file(s) (${listed2.join(", ")}${more}): commit them (gateway worlds sandbox commit ${sandboxId} -m "<why>") or discard them (gateway worlds sandbox close ${sandboxId} --force)`,
16629
18219
  1
16630
18220
  );
16631
18221
  }
@@ -17853,16 +19443,16 @@ function registerBenchCommands(root) {
17853
19443
  return 0;
17854
19444
  }
17855
19445
  const limit = arg.int(args, "limit");
17856
- const listed = await api(
19446
+ const listed2 = await api(
17857
19447
  creds,
17858
19448
  "GET",
17859
19449
  `/api/public/worlds/${encodeURIComponent(slug)}/tests${limit ? `?limit=${limit}` : ""}`
17860
19450
  );
17861
- if (!listed.runs.length)
19451
+ if (!listed2.runs.length)
17862
19452
  ctx.stdout(
17863
19453
  "no test runs yet \u2014 ship tests/ with the world and push, or `gateway worlds test <slug>`"
17864
19454
  );
17865
- for (const r of listed.runs) {
19455
+ for (const r of listed2.runs) {
17866
19456
  const s = r.summary;
17867
19457
  ctx.stdout(
17868
19458
  `${r.createdAt} ${r.state.padEnd(7)} ${r.trigger.padEnd(6)} ${r.versionId} ${s ? `${s.passed ?? 0} passed, ${s.failed ?? 0} failed` : r.error ?? ""} ${r.id}`
@@ -18106,7 +19696,7 @@ function importReport(dir, from) {
18106
19696
 
18107
19697
  // src/benchmarks/container.ts
18108
19698
  import { spawnSync as spawnSync2 } from "child_process";
18109
- import { createHash as createHash10 } from "crypto";
19699
+ import { createHash as createHash11 } from "crypto";
18110
19700
  import * as fs28 from "fs";
18111
19701
  import * as os4 from "os";
18112
19702
  import * as path20 from "path";
@@ -18489,7 +20079,7 @@ var DOCKER_SAFE = /^[A-Za-z0-9 ._-]*$/;
18489
20079
  function dockerNameComponent(raw) {
18490
20080
  const plain = raw.toLowerCase().replace(/[^a-z0-9._-]+/g, "-").replace(/[._-]{2,}/g, "-").replace(/^[._-]+|[._-]+$/g, "");
18491
20081
  if (DOCKER_SAFE.test(raw)) return plain || "x";
18492
- const digest2 = createHash10("sha1").update(raw, "utf8").digest("hex").slice(0, 8);
20082
+ const digest2 = createHash11("sha1").update(raw, "utf8").digest("hex").slice(0, 8);
18493
20083
  return `${plain || "x"}-${digest2}`;
18494
20084
  }
18495
20085
  function dockerImageName(dirName, taskId) {
@@ -19059,17 +20649,17 @@ async function hostedDryRun(args, ctx, creds, pushDir) {
19059
20649
  ctx,
19060
20650
  pushDir
19061
20651
  );
19062
- const listed = await target.tasks(creds);
19063
- const task = pickTask(arg.str(args, "task"), listed.names, target.slug, ctx);
20652
+ const listed2 = await target.tasks(creds);
20653
+ const task = pickTask(arg.str(args, "task"), listed2.names, target.slug, ctx);
19064
20654
  ctx.stderr(
19065
20655
  `target ${target.slug}${target.ref ? `@${target.ref}` : ""} (${target.source}) \xB7 task ${task} \xB7 hosted, harbor oracle`
19066
20656
  );
19067
- const client3 = new HostedDryRunClient(worldsOptions(creds));
20657
+ const client4 = new HostedDryRunClient(worldsOptions(creds));
19068
20658
  const containerId = target.containerId ?? await resolveEnvironmentId(creds, target.slug);
19069
- const dispatched = await client3.dispatch({
20659
+ const dispatched = await client4.dispatch({
19070
20660
  containerId,
19071
20661
  task,
19072
- ...listed.versionId ? { versionId: listed.versionId } : {}
20662
+ ...listed2.versionId ? { versionId: listed2.versionId } : {}
19073
20663
  });
19074
20664
  const json = arg.bool(args, "json");
19075
20665
  if (arg.bool(args, "no-wait")) {
@@ -19078,7 +20668,7 @@ async function hostedDryRun(args, ctx, creds, pushDir) {
19078
20668
  return 0;
19079
20669
  }
19080
20670
  const timeoutSeconds = arg.int(args, "wait-timeout") ?? 1200;
19081
- const verdict = await client3.settle(dispatched.runId, {
20671
+ const verdict = await client4.settle(dispatched.runId, {
19082
20672
  timeoutSeconds,
19083
20673
  onProgress: (v) => ctx.stderr(`# ${dispatched.task}: ${progressLine(v)}`)
19084
20674
  });
@@ -19867,11 +21457,11 @@ function branchMoved(err) {
19867
21457
  return err instanceof ApiError && err.status === 409 && /has moved/.test(err.message);
19868
21458
  }
19869
21459
  function refuseSlug(slug, existing, classified, incoming) {
19870
- const held = existing.shape ? STORED_SHAPE_LABELS[existing.shape] ?? existing.shape : existing.substrate;
21460
+ const held2 = existing.shape ? STORED_SHAPE_LABELS[existing.shape] ?? existing.shape : existing.substrate;
19871
21461
  const heldSide = existing.substrate === "world" ? "a world, hosted on the World Host" : "a container benchmark, executed by the benchmark runner";
19872
21462
  const thisSide = incoming === "world" ? "a world for the World Host" : "a container benchmark for the benchmark runner";
19873
21463
  throw new CliError(
19874
- `benchmarks push: slug \`${slug}\` already holds a ${held} \u2014 ${heldSide} \u2014 and this tree is a ${SHAPE_LABELS[classified.shape]}, ${thisSide}. A slug holds one substrate: pass --slug <new-slug>, or push a ${existing.substrate === "world" ? "world" : "container"} tree to add a version of \`${slug}\`. Nothing was written (the hub's versions door refuses the same push with benchmark_substrate_mismatch).`,
21464
+ `benchmarks push: slug \`${slug}\` already holds a ${held2} \u2014 ${heldSide} \u2014 and this tree is a ${SHAPE_LABELS[classified.shape]}, ${thisSide}. A slug holds one substrate: pass --slug <new-slug>, or push a ${existing.substrate === "world" ? "world" : "container"} tree to add a version of \`${slug}\`. Nothing was written (the hub's versions door refuses the same push with benchmark_substrate_mismatch).`,
19875
21465
  2
19876
21466
  );
19877
21467
  }
@@ -20418,9 +22008,9 @@ function iso(value) {
20418
22008
  return text2.endsWith("Z") || text2.slice(10).includes("+") ? text2 : text2 + "Z";
20419
22009
  }
20420
22010
  function recordsFromClickhouse(document, where = "clickhouse") {
20421
- const listed = isObject9(document) ? document.rows ?? document.results : document;
20422
- if (!Array.isArray(listed)) throw new CliError(`${where}: expected {rows|results: [...]} or a list of observations`, 1);
20423
- return listed.map((row, index2) => {
22011
+ const listed2 = isObject9(document) ? document.rows ?? document.results : document;
22012
+ if (!Array.isArray(listed2)) throw new CliError(`${where}: expected {rows|results: [...]} or a list of observations`, 1);
22013
+ return listed2.map((row, index2) => {
20424
22014
  if (!isObject9(row)) throw new CliError(`${where}[${index2}] is not an object`, 1);
20425
22015
  if (typeof row.name !== "string") throw new CliError(`${where}[${index2}] has no name; expected columns ${CLICKHOUSE_COLUMNS.join(", ")}`, 1);
20426
22016
  const record = { tool: row.name, args: decoded(row.input, true), result: decoded(row.output, false) };
@@ -20482,21 +22072,21 @@ async function fetchSessionCalls(creds, sessionId) {
20482
22072
  function recordsFromSessionCalls(calls, sessionId) {
20483
22073
  const records2 = [];
20484
22074
  const skipped = {};
20485
- for (const call2 of calls) {
20486
- if (call2.kind !== "call") {
20487
- const reason = `kind ${String(call2.kind ?? "unknown")}`;
22075
+ for (const call3 of calls) {
22076
+ if (call3.kind !== "call") {
22077
+ const reason = `kind ${String(call3.kind ?? "unknown")}`;
20488
22078
  skipped[reason] = (skipped[reason] ?? 0) + 1;
20489
22079
  continue;
20490
22080
  }
20491
- if (typeof call2.tool !== "string" || !call2.tool) {
22081
+ if (typeof call3.tool !== "string" || !call3.tool) {
20492
22082
  skipped["no tool"] = (skipped["no tool"] ?? 0) + 1;
20493
22083
  continue;
20494
22084
  }
20495
- const record = { tool: call2.tool, args: isObject9(call2.args) ? call2.args : {}, session: sessionId };
20496
- if (call2.error !== void 0 && call2.error !== null && call2.error !== "") record.error = String(call2.error);
20497
- else record.result = call2.result;
20498
- if (typeof call2.completedAt === "string") record.at = call2.completedAt;
20499
- record.source = `session:${sessionId}/${String(call2.seq ?? "?")}`;
22085
+ const record = { tool: call3.tool, args: isObject9(call3.args) ? call3.args : {}, session: sessionId };
22086
+ if (call3.error !== void 0 && call3.error !== null && call3.error !== "") record.error = String(call3.error);
22087
+ else record.result = call3.result;
22088
+ if (typeof call3.completedAt === "string") record.at = call3.completedAt;
22089
+ record.source = `session:${sessionId}/${String(call3.seq ?? "?")}`;
20500
22090
  records2.push(record);
20501
22091
  }
20502
22092
  return { records: records2, skipped };
@@ -20515,7 +22105,7 @@ async function extractRows(input, config, opts, out) {
20515
22105
  if (!entity) throw new CliError(`Unknown entity ${opts.entity}; the world has ${Object.keys(config.entities).sort().join(", ")}`, 1);
20516
22106
  const keys = entity.primaryKey;
20517
22107
  const summary2 = { read: 0, rows: 0, unknownFields: {}, redacted: { dropped: 0, hashed: 0 } };
20518
- const held = /* @__PURE__ */ new Map();
22108
+ const held2 = /* @__PURE__ */ new Map();
20519
22109
  const skipped = {};
20520
22110
  const skip = (reason) => {
20521
22111
  skipped[reason] = (skipped[reason] ?? 0) + 1;
@@ -20525,16 +22115,16 @@ async function extractRows(input, config, opts, out) {
20525
22115
  const row = clean(raw, entity.fields, summary2);
20526
22116
  if (!keys.every((name) => row.has(name))) return skip(`row lacks the primary key (${keys.join(", ")})`);
20527
22117
  const key2 = dumps(keys.map((name) => row.get(name)));
20528
- const existing = held.get(key2);
20529
- if (!existing) held.set(key2, row);
20530
- else if (opts.merge === "upsert") held.set(key2, row);
22118
+ const existing = held2.get(key2);
22119
+ if (!existing) held2.set(key2, row);
22120
+ else if (opts.merge === "upsert") held2.set(key2, row);
20531
22121
  else for (const [name, value] of row) if (!existing.has(name)) existing.set(name, value);
20532
22122
  };
20533
22123
  await adapters[opts.shape](input, config, keys, take, skip);
20534
22124
  if (Object.keys(skipped).length) summary2.skipped = skipped;
20535
22125
  if (summary2.read === 0 && Object.keys(skipped).length) summary2.hint = SHAPE_HINT[opts.shape];
20536
22126
  const policy = opts.redact ? config.redact : null;
20537
- for (const row of held.values()) {
22127
+ for (const row of held2.values()) {
20538
22128
  let final = row;
20539
22129
  if (policy) {
20540
22130
  final = redact(row, policy, config.slug ?? "");
@@ -20583,9 +22173,9 @@ var toolResults = async (input, _config, keys, take, skip) => {
20583
22173
  skip("record has no raw_output object");
20584
22174
  continue;
20585
22175
  }
20586
- let listed = raw.get("results");
20587
- if (listed === void 0 || listed === null) listed = raw.get("items");
20588
- const items = objects(listed);
22176
+ let listed2 = raw.get("results");
22177
+ if (listed2 === void 0 || listed2 === null) listed2 = raw.get("items");
22178
+ const items = objects(listed2);
20589
22179
  if (items.length === 0) skip("raw_output has no results[] or items[]");
20590
22180
  for (const item of items) {
20591
22181
  if (keys.every((name) => item.has(name))) take(item);
@@ -20817,10 +22407,10 @@ function skeleton(records2, entities, kind, opts = {}) {
20817
22407
  const shapeNames = Object.keys(group.shapes);
20818
22408
  if (kind === "tool-call" && shapeNames.length && shapeNames.every((shape) => shape === "an array of objects")) select = "result[*]";
20819
22409
  else if (kind === "tool-call" && shapeNames.length && shapeNames.every((shape) => shape === "an object")) {
20820
- const listed = Object.entries(group.fields).filter(([, info]) => info.list && Object.keys(info.nested).length).map(([name2]) => name2);
20821
- if (listed.length === 1) {
20822
- select = `result.${listed[0]}[*]`;
20823
- lines.push(`# result.${listed[0]} holds the rows: [*] selects each item of an array`);
22410
+ const listed2 = Object.entries(group.fields).filter(([, info]) => info.list && Object.keys(info.nested).length).map(([name2]) => name2);
22411
+ if (listed2.length === 1) {
22412
+ select = `result.${listed2[0]}[*]`;
22413
+ lines.push(`# result.${listed2[0]} holds the rows: [*] selects each item of an array`);
20824
22414
  }
20825
22415
  }
20826
22416
  lines.push("[[sources]]", `name = "${name}"`, `kind = "${kind}"`, `select = "${select}"`);
@@ -21190,7 +22780,7 @@ var TreeImport = class _TreeImport {
21190
22780
  );
21191
22781
  if (!dryRun) await this.refuseOverInlineCap(paths);
21192
22782
  const rows = parseRows(paths, this.entity);
21193
- const count = Object.values(rows).reduce((n, listed) => n + listed.length, 0);
22783
+ const count = Object.values(rows).reduce((n, listed2) => n + listed2.length, 0);
21194
22784
  const { importLocalWorldData: importLocalWorldData2, checkLocalWorldData: checkLocalWorldData2 } = await runtimeData();
21195
22785
  const { credentialsForRuntime: credentialsForRuntime2 } = await runtimeLocal();
21196
22786
  const creds = credentialsForRuntime2(void 0);
@@ -21361,9 +22951,9 @@ async function rowsOrRefuse(source2, files) {
21361
22951
  yield* source2;
21362
22952
  })();
21363
22953
  }
21364
- async function stageDriveChunks(client3, batchId, drive, entity, manifest, progress) {
22954
+ async function stageDriveChunks(client4, batchId, drive, entity, manifest, progress) {
21365
22955
  for (const [ordinal, path44] of drive.entries()) {
21366
- const entry = await client3.stageDrive(batchId, { ordinal, path: path44, entity });
22956
+ const entry = await client4.stageDrive(batchId, { ordinal, path: path44, entity });
21367
22957
  recordChunk(manifest, entry);
21368
22958
  writeManifest(manifest);
21369
22959
  progress(
@@ -22031,8 +23621,8 @@ function parseWhere(clauses) {
22031
23621
  if (!field2)
22032
23622
  throw new CliError(`--where takes field=value, got '${clause}'`);
22033
23623
  const value = clause.slice(eq + 1);
22034
- const held = where[field2];
22035
- where[field2] = held === void 0 ? value : [...Array.isArray(held) ? held : [held], value];
23624
+ const held2 = where[field2];
23625
+ where[field2] = held2 === void 0 ? value : [...Array.isArray(held2) ? held2 : [held2], value];
22036
23626
  }
22037
23627
  return where;
22038
23628
  }
@@ -22124,7 +23714,7 @@ async function importBatch(world, files, args, ctx, purpose, onStatus, labels =
22124
23714
  const named2 = inputLabels(files, labels);
22125
23715
  const creds = credentials(args);
22126
23716
  const flags = importFlags(args, purpose);
22127
- const client3 = new WorldDataApi(creds, slug);
23717
+ const client4 = new WorldDataApi(creds, slug);
22128
23718
  const progress = (line) => {
22129
23719
  if (showProgress()) ctx.stderr(line);
22130
23720
  };
@@ -22156,7 +23746,7 @@ async function importBatch(world, files, args, ctx, purpose, onStatus, labels =
22156
23746
  );
22157
23747
  let manifest;
22158
23748
  if (resumable) {
22159
- const status2 = await client3.get(resumable.batchId);
23749
+ const status2 = await client4.get(resumable.batchId);
22160
23750
  if (status2.state !== "open" && status2.state !== "uploading")
22161
23751
  throw new CliError(
22162
23752
  `batch ${resumable.batchId} is ${status2.state}; only an open or uploading batch resumes`,
@@ -22167,7 +23757,7 @@ async function importBatch(world, files, args, ctx, purpose, onStatus, labels =
22167
23757
  `resuming batch ${manifest.batchId} (${manifest.chunks.length} chunks recorded)`
22168
23758
  );
22169
23759
  } else {
22170
- const opened = await client3.open({
23760
+ const opened = await client4.open({
22171
23761
  mode: plan.mode,
22172
23762
  merge: plan.merge,
22173
23763
  ...plan.redact && plan.redact !== "off" ? { redact: plan.redact } : {},
@@ -22199,7 +23789,7 @@ async function importBatch(world, files, args, ctx, purpose, onStatus, labels =
22199
23789
  }
22200
23790
  const batchId = manifest.batchId;
22201
23791
  const staged = await stageDriveChunks(
22202
- client3,
23792
+ client4,
22203
23793
  batchId,
22204
23794
  drive,
22205
23795
  plan.entity,
@@ -22220,14 +23810,14 @@ async function importBatch(world, files, args, ctx, purpose, onStatus, labels =
22220
23810
  progress(`chunk ${chunk.ordinal}: already uploaded (${chunk.rows} rows)`);
22221
23811
  return;
22222
23812
  }
22223
- const entry = await client3.upload(batchId, chunk);
23813
+ const entry = await client4.upload(batchId, chunk);
22224
23814
  recordChunk(manifest, entry);
22225
23815
  writeManifest(manifest);
22226
23816
  progress(
22227
23817
  `chunk ${chunk.ordinal}: uploaded ${chunk.rows} rows, ${chunk.bytes} bytes (${entry.chunkId})`
22228
23818
  );
22229
23819
  });
22230
- await client3.complete(batchId);
23820
+ await client4.complete(batchId);
22231
23821
  manifest.completed = true;
22232
23822
  writeManifest(manifest);
22233
23823
  progress(`batch ${batchId} complete: ${manifest.chunks.length} chunks`);
@@ -22236,7 +23826,7 @@ async function importBatch(world, files, args, ctx, purpose, onStatus, labels =
22236
23826
  else ctx.stdout(JSON.stringify({ batchId, state: "queued" }));
22237
23827
  return 0;
22238
23828
  }
22239
- const status = await waitForBatch(client3, batchId, {
23829
+ const status = await waitForBatch(client4, batchId, {
22240
23830
  onPhase: (line) => progress(line),
22241
23831
  initialDelayMs: pollMs2()
22242
23832
  });
@@ -22604,9 +24194,9 @@ async function ingestCommand(world, inputs, args, ctx, labels = {}) {
22604
24194
  skipped: {},
22605
24195
  refusals: [],
22606
24196
  rows: Object.fromEntries(
22607
- Object.entries(projected).map(([entity, listed]) => [
24197
+ Object.entries(projected).map(([entity, listed2]) => [
22608
24198
  entity,
22609
- listed.length
24199
+ listed2.length
22610
24200
  ])
22611
24201
  ),
22612
24202
  dryRun,
@@ -22775,8 +24365,8 @@ function readDatasetItems(file) {
22775
24365
  if (Array.isArray(data)) return data;
22776
24366
  if (data && typeof data === "object") {
22777
24367
  const record = data;
22778
- const listed = record.tasks ?? record.items;
22779
- return Array.isArray(listed) ? listed : [];
24368
+ const listed2 = record.tasks ?? record.items;
24369
+ return Array.isArray(listed2) ? listed2 : [];
22780
24370
  }
22781
24371
  return [];
22782
24372
  }
@@ -22813,11 +24403,11 @@ function registerDatasetCommands(root) {
22813
24403
  const creds = credentials(args);
22814
24404
  const agent = arg.str(args, "agent");
22815
24405
  if (agent) {
22816
- const listed = await rawRequest(creds, "GET", "/api/public/agents");
22817
- if (!listed.ok) {
22818
- ctx.stderr(`Warning: Could not fetch agents for validation: HTTP ${listed.status}`);
24406
+ const listed2 = await rawRequest(creds, "GET", "/api/public/agents");
24407
+ if (!listed2.ok) {
24408
+ ctx.stderr(`Warning: Could not fetch agents for validation: HTTP ${listed2.status}`);
22819
24409
  } else {
22820
- const agents = (listed.json().agents ?? []).filter((a) => a.name === agent);
24410
+ const agents = (listed2.json().agents ?? []).filter((a) => a.name === agent);
22821
24411
  if (agents.length === 0) ctx.stderr(`Warning: Agent '${agent}' not found, skipping validation`);
22822
24412
  else if (!agents[0].taskInputSchema)
22823
24413
  ctx.stdout(`Agent '${agent}' has no taskInputSchema, skipping validation`);
@@ -23465,13 +25055,13 @@ function registerSecretCommands(root) {
23465
25055
  init_config();
23466
25056
  init_router();
23467
25057
  init_worlds();
23468
- import * as fs48 from "fs";
25058
+ import * as fs49 from "fs";
23469
25059
  init_shared();
23470
25060
 
23471
25061
  // src/cli/platform/task.ts
23472
25062
  init_config();
23473
25063
  init_router();
23474
- import * as fs47 from "fs";
25064
+ import * as fs48 from "fs";
23475
25065
  import * as path37 from "path";
23476
25066
  import { pathToFileURL as pathToFileURL3 } from "url";
23477
25067
 
@@ -23479,7 +25069,7 @@ import { pathToFileURL as pathToFileURL3 } from "url";
23479
25069
  init_router();
23480
25070
  init_config();
23481
25071
  init_worlds();
23482
- init_session();
25072
+ init_session2();
23483
25073
  init_hub();
23484
25074
  init_validate();
23485
25075
  init_client();
@@ -23956,30 +25546,11 @@ function registerRunCommands2(worlds) {
23956
25546
  // src/cli/platform/task.ts
23957
25547
  init_worlds();
23958
25548
  init_shared();
23959
- async function findTaskByName(name, options) {
23960
- for (let page = 1; ; page++) {
23961
- const batch = await listTasks({ page, limit: 100 }, options);
23962
- const hit = batch.tasks.find((task) => task.name === name);
23963
- if (hit) return hit;
23964
- if (page >= batch.meta.totalPages) return null;
23965
- }
23966
- }
23967
- var WORLD_FLAG = {
23968
- name: "world",
23969
- short: "w",
23970
- help: "Pin the task to this world (slug); validated against its contract."
23971
- };
23972
- var NO_WORLD_FLAG = {
23973
- name: "no-world",
23974
- help: "Unpin the task so it can open on any world.",
23975
- boolean: true
23976
- };
23977
- var MESSAGE_FLAG3 = {
23978
- name: "message",
23979
- short: "m",
23980
- help: "Note kept with this version."
23981
- };
23982
- var TASK_SPEC_HELP = 'A task spec is JSON:\n {"instruction": "<what the agent is told>",\n "name": "<optional>",\n "seed": {"mode": "append|replace", "rows": {"<entity>": [{...row}, ...]}}, # rows go UNDER seed.rows\n "grader": {"kind": "assertions", "checks": [{"entity": "<entity>", "where": {"<field>": <scalar>},\n "assert": "exists|absent|count|all|any",\n "count": {"eq"|"gte"|"lte": <n>}, # assert: count\n "field": "<field>", "op": "eq|neq|in|gt|gte|lt|lte|contains", "value": <scalar>}]} # assert: all|any\n | {"kind": "python", "source": "<verify.py body>", "timeoutSeconds"?: <n>}\n | {"kind": "rubric", "rubric": "<what the judge looks for>", "criteria"?: [{"id", "description", "weight"?}]},\n "tools": ["<tool>", ...], # optional allow-list\n "metadata": {...}, # optional, echoed back\n "worlds": {"<alias>": {"slug": "<world>", "ref"?: "<branch|tag|version id>", "seed"?, "grader"?, "tools"?}}} # multi-world: one session per alias\nWithout seed the session starts on the version\'s base data; without grader `grade` answers reward: null.\nWith worlds, seed/grader/tools live under each alias (not at the top level) and `worlds task up` opens the sessions.';
25549
+
25550
+ // src/cli/platform/taskSpec.ts
25551
+ init_router();
25552
+ import * as fs47 from "fs";
25553
+ var TASK_SPEC_HELP = 'A task spec is JSON:\n {"instruction": "<what the agent is told>",\n "name": "<optional>",\n "seed": {"mode": "append|replace", "rows": {"<entity>": [{...row}, ...]}}, # rows go UNDER seed.rows\n "grader": {"kind": "assertions", "checks": [{"entity": "<entity>", "where": {"<field>": <scalar>},\n "assert": "exists|absent|count|all|any",\n "count": {"eq"|"gte"|"lte": <n>}, # assert: count\n "field": "<field>", "op": "eq|neq|in|gt|gte|lt|lte|contains", "value": <scalar>}]} # assert: all|any\n | {"kind": "python", "source": "<verify.py body>", "timeoutSeconds"?: <n>}\n | {"kind": "rubric", "rubric": "<what the judge looks for>", "criteria"?: [{"id", "description", "weight"?}]},\n "tools": ["<tool>", ...], # optional allow-list\n "metadata": {...}, # optional, echoed back\n "worlds": {"<alias>": {"slug": "<world>", "ref"?: "<branch|tag|version id>", "seed"?, "grader"?, "tools"?}}, # multi-world: one session per alias\n "verifiers": [{"name": "<name>", "scope": ["<alias>", "<alias>", ...], "kind": "assertions|python", "checks"|"source": ...}]} # cross-world: entities as <alias>.<entity>, call logs as <alias>.calls\nWithout seed the session starts on the version\'s base data; without grader `grade` answers reward: null.\nWith worlds, seed/grader/tools live under each alias (not at the top level) and `worlds task up` opens the sessions.\nWithout worlds, a verifier runs on the session named by its first scope alias, so "name" must be that alias.';
23983
25554
  var SPEC_KEYS = /* @__PURE__ */ new Set([
23984
25555
  "name",
23985
25556
  "instruction",
@@ -23987,13 +25558,18 @@ var SPEC_KEYS = /* @__PURE__ */ new Set([
23987
25558
  "grader",
23988
25559
  "tools",
23989
25560
  "metadata",
23990
- "worlds"
25561
+ "worlds",
25562
+ "verifiers"
23991
25563
  ]);
23992
25564
  var WORLD_KEYS = /* @__PURE__ */ new Set(["slug", "ref", "seed", "grader", "tools"]);
23993
25565
  var SEED_KEYS = /* @__PURE__ */ new Set(["mode", "redact", "rows"]);
23994
25566
  var SEED_MODES = /* @__PURE__ */ new Set(["append", "replace"]);
23995
25567
  var SEED_REDACT = /* @__PURE__ */ new Set(["off", "apply", "refuse"]);
23996
25568
  var GRADER_KINDS = /* @__PURE__ */ new Set(["assertions", "python", "rubric"]);
25569
+ var VERIFIER_KEYS = /* @__PURE__ */ new Map([
25570
+ ["assertions", /* @__PURE__ */ new Set(["name", "scope", "kind", "checks"])],
25571
+ ["python", /* @__PURE__ */ new Set(["name", "scope", "kind", "source", "timeoutSeconds"])]
25572
+ ]);
23997
25573
  var CHECK_KEYS = /* @__PURE__ */ new Set([
23998
25574
  "id",
23999
25575
  "weight",
@@ -24017,134 +25593,241 @@ var FIELD_OPS = /* @__PURE__ */ new Set([
24017
25593
  "contains"
24018
25594
  ]);
24019
25595
  var isRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
24020
- function taskSpecIssues(spec) {
24021
- const issues = [];
24022
- for (const key2 of Object.keys(spec))
24023
- if (!SPEC_KEYS.has(key2))
24024
- issues.push(
24025
- `unknown key "${key2}" (a spec has ${[...SPEC_KEYS].join(", ")})`
24026
- );
24027
- if (spec.name !== void 0 && typeof spec.name !== "string")
24028
- issues.push("name is a string");
24029
- if (spec.metadata !== void 0 && !isRecord(spec.metadata))
24030
- issues.push("metadata is a JSON object");
24031
- toolsIssues(spec.tools, "tools", issues);
24032
- seedIssues(spec.seed, "seed", issues);
24033
- graderIssues(spec.grader, "grader", issues);
24034
- const worlds = spec.worlds;
24035
- if (worlds !== void 0) {
25596
+ var isStringList = (value) => Array.isArray(value) && value.every((item) => typeof item === "string");
25597
+ var oneOf = (set, value) => typeof value === "string" && set.has(value);
25598
+ var listed = (set) => [...set].join(", ");
25599
+ var repeatedAt = (items, i) => items.indexOf(items[i]) < i;
25600
+ var checkKey = (check, i) => {
25601
+ if (!isRecord(check)) return void 0;
25602
+ return typeof check.id === "string" ? check.id : `check_${i}`;
25603
+ };
25604
+ var keyCollision = (check, i) => typeof check.id === "string" ? `check id '${check.id}' is used twice (an id of the form check_<n> is also the positional key of check n)` : `check ${i} has no id and its positional key 'check_${i}' is taken by another check's id`;
25605
+ var TaskSpecCheck = class {
25606
+ constructor(spec) {
25607
+ this.spec = spec;
25608
+ }
25609
+ spec;
25610
+ issues = [];
25611
+ run() {
25612
+ const spec = this.spec;
25613
+ for (const key2 of Object.keys(spec).filter((k) => !SPEC_KEYS.has(k)))
25614
+ this.issue(`unknown key "${key2}" (a spec has ${listed(SPEC_KEYS)})`);
25615
+ if (spec.name !== void 0 && typeof spec.name !== "string")
25616
+ this.issue("name is a string");
25617
+ if (spec.metadata !== void 0 && !isRecord(spec.metadata))
25618
+ this.issue("metadata is a JSON object");
25619
+ this.tools(spec.tools, "tools");
25620
+ this.seed(spec.seed, "seed");
25621
+ this.grader(spec.grader, "grader");
25622
+ this.verifiers(spec.verifiers);
25623
+ this.worlds(spec.worlds);
25624
+ return this.issues;
25625
+ }
25626
+ issue(message) {
25627
+ this.issues.push(message);
25628
+ }
25629
+ worlds(worlds) {
25630
+ if (worlds === void 0) return;
24036
25631
  for (const key2 of ["seed", "grader", "tools"])
24037
- if (spec[key2] !== void 0)
24038
- issues.push(
25632
+ if (this.spec[key2] !== void 0)
25633
+ this.issue(
24039
25634
  `a task with worlds carries ${key2} per world (worlds.<alias>.${key2}), not at the top level`
24040
25635
  );
24041
25636
  if (!isRecord(worlds) || !Object.keys(worlds).length)
24042
- issues.push(
25637
+ return this.issue(
24043
25638
  'worlds is {"<alias>": {"slug": "<world>", "ref"?, "seed"?, "grader"?, "tools"?}} with at least one alias'
24044
25639
  );
24045
- else
24046
- for (const [alias, world] of Object.entries(worlds)) {
24047
- const at = `worlds.${alias}`;
24048
- if (!isRecord(world)) {
24049
- issues.push(`${at} is an object {slug, ref?, seed?, grader?, tools?}`);
24050
- continue;
24051
- }
24052
- for (const k of Object.keys(world))
24053
- if (!WORLD_KEYS.has(k))
24054
- issues.push(
24055
- `${at}.${k} is not a world key (${[...WORLD_KEYS].join(", ")})`
24056
- );
24057
- if (typeof world.slug !== "string" || !world.slug)
24058
- issues.push(`${at}.slug names the hosted world the alias opens`);
24059
- if (world.ref !== void 0 && typeof world.ref !== "string")
24060
- issues.push(`${at}.ref is a branch, tag or version id`);
24061
- toolsIssues(world.tools, `${at}.tools`, issues);
24062
- seedIssues(world.seed, `${at}.seed`, issues);
24063
- graderIssues(world.grader, `${at}.grader`, issues);
24064
- }
24065
- }
24066
- return issues;
24067
- }
24068
- function toolsIssues(tools, at, issues) {
24069
- if (tools !== void 0 && (!Array.isArray(tools) || tools.some((t) => typeof t !== "string")))
24070
- issues.push(`${at} is a list of tool names`);
24071
- }
24072
- function seedIssues(seed, at, issues) {
24073
- if (seed === void 0) return;
24074
- if (!isRecord(seed)) return void issues.push(`${at} is an object {mode?, rows}`);
24075
- const strays = Object.keys(seed).filter((k) => !SEED_KEYS.has(k));
24076
- if (seed.rows === void 0 && strays.length)
24077
- issues.push(
24078
- `${at}.rows is missing \u2014 rows go under ${at}.rows, not ${at}.${strays[0]}: {"seed": {"rows": {${strays.map((k) => `"${k}": [...]`).join(", ")}}}}`
24079
- );
24080
- else {
25640
+ for (const [alias, world] of Object.entries(worlds))
25641
+ this.world(world, `worlds.${alias}`);
25642
+ }
25643
+ world(world, at) {
25644
+ if (!isRecord(world))
25645
+ return this.issue(
25646
+ `${at} is an object {slug, ref?, seed?, grader?, tools?}`
25647
+ );
25648
+ for (const k of Object.keys(world).filter((k2) => !WORLD_KEYS.has(k2)))
25649
+ this.issue(`${at}.${k} is not a world key (${listed(WORLD_KEYS)})`);
25650
+ if (typeof world.slug !== "string" || !world.slug)
25651
+ this.issue(`${at}.slug names the hosted world the alias opens`);
25652
+ if (world.ref !== void 0 && typeof world.ref !== "string")
25653
+ this.issue(`${at}.ref is a branch, tag or version id`);
25654
+ this.tools(world.tools, `${at}.tools`);
25655
+ this.seed(world.seed, `${at}.seed`);
25656
+ this.grader(world.grader, `${at}.grader`);
25657
+ }
25658
+ tools(tools, at) {
25659
+ if (tools !== void 0 && !isStringList(tools))
25660
+ this.issue(`${at} is a list of tool names`);
25661
+ }
25662
+ seed(seed, at) {
25663
+ if (seed === void 0) return;
25664
+ if (!isRecord(seed)) return this.issue(`${at} is an object {mode?, rows}`);
25665
+ this.seedRows(seed, at);
25666
+ if (seed.mode !== void 0 && !oneOf(SEED_MODES, seed.mode))
25667
+ this.issue(
25668
+ `${at}.mode is append or replace, got ${JSON.stringify(seed.mode)}`
25669
+ );
25670
+ if (seed.redact !== void 0 && !oneOf(SEED_REDACT, seed.redact))
25671
+ this.issue(
25672
+ `${at}.redact is off, apply or refuse, got ${JSON.stringify(seed.redact)}`
25673
+ );
25674
+ }
25675
+ seedRows(seed, at) {
25676
+ const strays = Object.keys(seed).filter((k) => !SEED_KEYS.has(k));
25677
+ if (seed.rows === void 0 && strays.length)
25678
+ return this.issue(
25679
+ `${at}.rows is missing \u2014 rows go under ${at}.rows, not ${at}.${strays[0]}: {"seed": {"rows": {${strays.map((k) => `"${k}": [...]`).join(", ")}}}}`
25680
+ );
24081
25681
  for (const k of strays)
24082
- issues.push(`${at}.${k} is not a seed key (seed has mode, redact, rows)`);
24083
- if (!isRecord(seed.rows)) issues.push(`${at}.rows is {"<entity>": [row, ...]}`);
24084
- else
24085
- for (const [entity, rows] of Object.entries(seed.rows))
24086
- if (!Array.isArray(rows) || !rows.every(isRecord))
24087
- issues.push(`${at}.rows.${entity} is a list of row objects`);
25682
+ this.issue(`${at}.${k} is not a seed key (seed has mode, redact, rows)`);
25683
+ if (!isRecord(seed.rows))
25684
+ return this.issue(`${at}.rows is {"<entity>": [row, ...]}`);
25685
+ for (const [entity, rows] of Object.entries(seed.rows))
25686
+ if (!Array.isArray(rows) || !rows.every(isRecord))
25687
+ this.issue(`${at}.rows.${entity} is a list of row objects`);
25688
+ }
25689
+ grader(grader, at) {
25690
+ if (grader === void 0) return;
25691
+ if (!isRecord(grader)) return this.issue(`${at} is an object {kind, ...}`);
25692
+ if (!oneOf(GRADER_KINDS, grader.kind))
25693
+ return this.issue(
25694
+ `${at}.kind is one of assertions, python, rubric, got ${JSON.stringify(grader.kind)}` + (grader.checks !== void 0 ? ' (checks go with kind: "assertions")' : "")
25695
+ );
25696
+ this.graderBodies[grader.kind](grader, at);
24088
25697
  }
24089
- if (seed.mode !== void 0 && !(typeof seed.mode === "string" && SEED_MODES.has(seed.mode)))
24090
- issues.push(
24091
- `${at}.mode is append or replace, got ${JSON.stringify(seed.mode)}`
24092
- );
24093
- if (seed.redact !== void 0 && !(typeof seed.redact === "string" && SEED_REDACT.has(seed.redact)))
24094
- issues.push(
24095
- `${at}.redact is off, apply or refuse, got ${JSON.stringify(seed.redact)}`
24096
- );
24097
- }
24098
- function graderIssues(grader, at, issues) {
24099
- if (grader === void 0) return;
24100
- if (!isRecord(grader)) return void issues.push(`${at} is an object {kind, ...}`);
24101
- if (!(typeof grader.kind === "string" && GRADER_KINDS.has(grader.kind)))
24102
- return void issues.push(
24103
- `${at}.kind is one of assertions, python, rubric, got ${JSON.stringify(grader.kind)}` + (grader.checks !== void 0 ? ' (checks go with kind: "assertions")' : "")
24104
- );
24105
- if (grader.kind === "assertions") {
24106
- const checks = grader.checks;
25698
+ graderBodies = {
25699
+ assertions: (grader, at) => this.checks(grader.checks, at),
25700
+ python: (grader, at) => {
25701
+ if (typeof grader.source !== "string" || !grader.source)
25702
+ this.issue(`${at}.source is the verify.py body (kind: "python")`);
25703
+ },
25704
+ rubric: (grader, at) => {
25705
+ if (typeof grader.rubric !== "string" || !grader.rubric)
25706
+ this.issue(
25707
+ `${at}.rubric is what the judge is told to look for (kind: "rubric")`
25708
+ );
25709
+ }
25710
+ };
25711
+ checks(checks, at) {
24107
25712
  if (!Array.isArray(checks) || !checks.length)
24108
- return void issues.push(`${at}.checks is a non-empty list of checks`);
24109
- checks.forEach((check, i) => checkIssues(check, `${at}.checks[${i}]`, issues));
24110
- } else if (grader.kind === "python") {
24111
- if (typeof grader.source !== "string" || !grader.source)
24112
- issues.push(`${at}.source is the verify.py body (kind: "python")`);
24113
- } else if (typeof grader.rubric !== "string" || !grader.rubric)
24114
- issues.push(
24115
- `${at}.rubric is what the judge is told to look for (kind: "rubric")`
24116
- );
24117
- }
24118
- function checkIssues(check, at, issues) {
24119
- if (!isRecord(check))
24120
- return void issues.push(`${at} is an object {entity, where?, assert?, ...}`);
24121
- for (const k of Object.keys(check))
24122
- if (!CHECK_KEYS.has(k))
24123
- issues.push(`${at}.${k} is not a check key (${[...CHECK_KEYS].join(", ")})`);
24124
- if (typeof check.entity !== "string" || !check.entity)
24125
- issues.push(`${at}.entity names the entity the check selects rows of`);
24126
- if (check.where !== void 0 && !isRecord(check.where))
24127
- issues.push(`${at}.where is {"<field>": <scalar>}`);
24128
- const assert = check.assert ?? "exists";
24129
- if (!(typeof assert === "string" && ASSERTIONS.has(assert)))
24130
- return void issues.push(
24131
- `${at}.assert is one of exists, absent, count, all, any, got ${JSON.stringify(assert)}`
24132
- );
24133
- if (assert === "count" && !isRecord(check.count))
24134
- issues.push(`${at}: assert "count" needs count: {eq|gte|lte: <n>}`);
24135
- if (assert !== "count" && check.count !== void 0)
24136
- issues.push(`${at}.count only goes with assert: "count"`);
24137
- const predicate = assert === "all" || assert === "any";
24138
- if (predicate && typeof check.field !== "string")
24139
- issues.push(`${at}: assert "${assert}" needs field (and value) to test`);
24140
- if (predicate && check.value === void 0)
24141
- issues.push(`${at}: assert "${assert}" needs value to compare with`);
24142
- if (!predicate && (check.field !== void 0 || check.op !== void 0 || check.value !== void 0))
24143
- issues.push(`${at}.field/op/value only go with assert: "all" or "any"`);
24144
- if (check.op !== void 0 && !(typeof check.op === "string" && FIELD_OPS.has(check.op)))
24145
- issues.push(
24146
- `${at}.op is one of ${[...FIELD_OPS].join(", ")}, got ${JSON.stringify(check.op)}`
25713
+ return this.issue(`${at}.checks is a non-empty list of checks`);
25714
+ const keys = checks.map((check, i) => checkKey(check, i));
25715
+ checks.forEach((check, i) => {
25716
+ if (keys[i] !== void 0 && repeatedAt(keys, i))
25717
+ this.issue(`${at}.checks[${i}]: ${keyCollision(check, i)}`);
25718
+ this.check(check, `${at}.checks[${i}]`);
25719
+ });
25720
+ }
25721
+ check(check, at) {
25722
+ if (!isRecord(check))
25723
+ return this.issue(`${at} is an object {entity, where?, assert?, ...}`);
25724
+ for (const k of Object.keys(check).filter((k2) => !CHECK_KEYS.has(k2)))
25725
+ this.issue(`${at}.${k} is not a check key (${listed(CHECK_KEYS)})`);
25726
+ if (typeof check.entity !== "string" || !check.entity)
25727
+ this.issue(`${at}.entity names the entity the check selects rows of`);
25728
+ if (check.where !== void 0 && !isRecord(check.where))
25729
+ this.issue(`${at}.where is {"<field>": <scalar>}`);
25730
+ const assert = check.assert ?? "exists";
25731
+ if (!oneOf(ASSERTIONS, assert))
25732
+ return this.issue(
25733
+ `${at}.assert is one of exists, absent, count, all, any, got ${JSON.stringify(assert)}`
25734
+ );
25735
+ if (assert === "count" && !isRecord(check.count))
25736
+ this.issue(`${at}: assert "count" needs count: {eq|gte|lte: <n>}`);
25737
+ if (assert !== "count" && check.count !== void 0)
25738
+ this.issue(`${at}.count only goes with assert: "count"`);
25739
+ const predicate = assert === "all" || assert === "any";
25740
+ if (predicate && typeof check.field !== "string")
25741
+ this.issue(`${at}: assert "${assert}" needs field (and value) to test`);
25742
+ if (predicate && check.value === void 0)
25743
+ this.issue(`${at}: assert "${assert}" needs value to compare with`);
25744
+ if (!predicate && (check.field !== void 0 || check.op !== void 0 || check.value !== void 0))
25745
+ this.issue(`${at}.field/op/value only go with assert: "all" or "any"`);
25746
+ if (check.op !== void 0 && !oneOf(FIELD_OPS, check.op))
25747
+ this.issue(
25748
+ `${at}.op is one of ${listed(FIELD_OPS)}, got ${JSON.stringify(check.op)}`
25749
+ );
25750
+ }
25751
+ verifiers(verifiers) {
25752
+ if (verifiers === void 0) return;
25753
+ if (!Array.isArray(verifiers) || !verifiers.length)
25754
+ return this.issue(
25755
+ 'verifiers is a non-empty list of {name, scope: ["<alias>", "<alias>", ...], kind, checks|source}'
25756
+ );
25757
+ const names = verifiers.map((v) => isRecord(v) ? v.name : void 0);
25758
+ verifiers.forEach((verifier, i) => {
25759
+ const at = `verifiers[${i}]`;
25760
+ if (typeof names[i] === "string" && repeatedAt(names, i))
25761
+ this.issue(`${at}.name "${names[i]}" is used twice`);
25762
+ this.verifier(verifier, at);
25763
+ });
25764
+ }
25765
+ verifier(verifier, at) {
25766
+ if (!isRecord(verifier))
25767
+ return this.issue(`${at} is an object {name, scope, kind, ...}`);
25768
+ if (typeof verifier.name !== "string" || !verifier.name)
25769
+ this.issue(`${at}.name names the verifier`);
25770
+ this.scope(verifier.scope, at);
25771
+ const keys = VERIFIER_KEYS.get(verifier.kind);
25772
+ if (!keys)
25773
+ return this.issue(
25774
+ `${at}.kind is assertions or python (a rubric cannot be a verifier)`
25775
+ );
25776
+ for (const k of Object.keys(verifier).filter((k2) => !keys.has(k2)))
25777
+ this.issue(
25778
+ `${at}.${k} is not a key of a verifier of kind ${verifier.kind} (${listed(keys)})`
25779
+ );
25780
+ this.grader(verifier, at);
25781
+ this.crossChecks(verifier, at);
25782
+ }
25783
+ scope(scope, at) {
25784
+ if (!isStringList(scope) || scope.length < 2)
25785
+ return this.issue(
25786
+ `${at}.scope lists two or more of the task's world aliases`
25787
+ );
25788
+ if (new Set(scope).size !== scope.length)
25789
+ this.issue(`${at}.scope lists each alias once`);
25790
+ this.scopeInWorlds(scope, at);
25791
+ this.anchor(scope[0], at);
25792
+ }
25793
+ scopeInWorlds(scope, at) {
25794
+ const worlds = this.spec.worlds;
25795
+ if (worlds === void 0 && scope[0] !== this.spec.name)
25796
+ this.issue(
25797
+ `${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`
25798
+ );
25799
+ if (!isRecord(worlds)) return;
25800
+ const aliases = Object.keys(worlds);
25801
+ for (const alias of scope.filter((a) => !aliases.includes(a)))
25802
+ this.issue(
25803
+ `${at}.scope names "${alias}", which is not one of worlds (${aliases.join(", ")})`
25804
+ );
25805
+ }
25806
+ anchor(alias, at) {
25807
+ const worlds = isRecord(this.spec.worlds) ? this.spec.worlds : {};
25808
+ const world = worlds[alias];
25809
+ const grader = (isRecord(world) ? world.grader : void 0) ?? this.spec.grader;
25810
+ if (!isRecord(grader) || grader.kind !== "rubric") return;
25811
+ this.issue(
25812
+ `${at} is anchored on "${alias}", whose grader is a rubric judged on the platform; anchor it (scope[0]) on a world graded by assertions, python or nothing`
24147
25813
  );
25814
+ }
25815
+ crossChecks(verifier, at) {
25816
+ const { scope, checks } = verifier;
25817
+ if (verifier.kind !== "assertions") return;
25818
+ if (!isStringList(scope) || !Array.isArray(checks)) return;
25819
+ checks.forEach((check, i) => {
25820
+ const entity = isRecord(check) ? check.entity : void 0;
25821
+ if (typeof entity !== "string" || !entity) return;
25822
+ if (entity.includes(".") && scope.includes(entity.split(".")[0])) return;
25823
+ this.issue(
25824
+ `${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(", ")})`
25825
+ );
25826
+ });
25827
+ }
25828
+ };
25829
+ function taskSpecIssues(spec) {
25830
+ return new TaskSpecCheck(spec).run();
24148
25831
  }
24149
25832
  function readTaskSpec(file, flag = "--spec") {
24150
25833
  let parsed;
@@ -24155,7 +25838,7 @@ function readTaskSpec(file, flag = "--spec") {
24155
25838
  `${flag} ${file}: ${error instanceof Error ? error.message : String(error)}`
24156
25839
  );
24157
25840
  }
24158
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed) || typeof parsed.instruction !== "string")
25841
+ if (!isRecord(parsed) || typeof parsed.instruction !== "string")
24159
25842
  throw new CliError(
24160
25843
  `${flag} ${file}: a task spec is a JSON object with an "instruction" string`
24161
25844
  );
@@ -24169,12 +25852,37 @@ ${TASK_SPEC_HELP}`
24169
25852
  );
24170
25853
  return parsed;
24171
25854
  }
25855
+
25856
+ // src/cli/platform/task.ts
25857
+ async function findTaskByName(name, options) {
25858
+ for (let page = 1; ; page++) {
25859
+ const batch = await listTasks({ page, limit: 100 }, options);
25860
+ const hit = batch.tasks.find((task) => task.name === name);
25861
+ if (hit) return hit;
25862
+ if (page >= batch.meta.totalPages) return null;
25863
+ }
25864
+ }
25865
+ var WORLD_FLAG = {
25866
+ name: "world",
25867
+ short: "w",
25868
+ help: "Pin the task to this world (slug); validated against its contract."
25869
+ };
25870
+ var NO_WORLD_FLAG = {
25871
+ name: "no-world",
25872
+ help: "Unpin the task so it can open on any world.",
25873
+ boolean: true
25874
+ };
25875
+ var MESSAGE_FLAG3 = {
25876
+ name: "message",
25877
+ short: "m",
25878
+ help: "Note kept with this version."
25879
+ };
24172
25880
  async function loadTaskAgent(spec) {
24173
25881
  const hash = spec.indexOf("#");
24174
25882
  const file = hash === -1 ? spec : spec.slice(0, hash);
24175
25883
  const exportName = hash === -1 ? void 0 : spec.slice(hash + 1);
24176
25884
  const abs = path37.resolve(file);
24177
- if (!fs47.existsSync(abs)) throw new CliError(`--agent ${spec} does not exist`);
25885
+ if (!fs48.existsSync(abs)) throw new CliError(`--agent ${spec} does not exist`);
24178
25886
  const ext = path37.extname(abs);
24179
25887
  if (ext === ".ts" || ext === ".mts" || ext === ".cts")
24180
25888
  await registerTypeScriptLoader(abs);
@@ -24200,7 +25908,7 @@ function worldFromFlags(world, noWorld) {
24200
25908
  }
24201
25909
  function readJsonFile(file, what) {
24202
25910
  try {
24203
- return JSON.parse(fs47.readFileSync(file, "utf8"));
25911
+ return JSON.parse(fs48.readFileSync(file, "utf8"));
24204
25912
  } catch (error) {
24205
25913
  throw new CliError(
24206
25914
  `${what} ${file}: ${error instanceof Error ? error.message : String(error)}`
@@ -24208,7 +25916,7 @@ function readJsonFile(file, what) {
24208
25916
  }
24209
25917
  }
24210
25918
  function taskTarget(positional) {
24211
- if (!fs47.existsSync(positional)) return { kind: "id", taskId: positional };
25919
+ if (!fs48.existsSync(positional)) return { kind: "id", taskId: positional };
24212
25920
  const parsed = readJsonFile(positional, "task");
24213
25921
  if (isTaskManifest(parsed)) return { kind: "manifest", manifest: parsed };
24214
25922
  if (parsed && typeof parsed === "object" && typeof parsed.instruction === "string")
@@ -24230,19 +25938,19 @@ var TARGET_POSITIONAL = {
24230
25938
  help: "Task id, or the manifest file `task up --out` wrote."
24231
25939
  };
24232
25940
  function emitManifest(ctx, manifest, out) {
24233
- if (out) fs47.writeFileSync(out, JSON.stringify(manifest, null, 2) + "\n");
25941
+ if (out) fs48.writeFileSync(out, JSON.stringify(manifest, null, 2) + "\n");
24234
25942
  printJson(ctx, manifest);
24235
25943
  if (out) ctx.stderr(`wrote the manifest to ${out}`);
24236
25944
  }
24237
25945
  function pairsFromFlags(flag, pairs3) {
24238
25946
  const out = {};
24239
- for (const pair2 of pairs3) {
24240
- const eq = pair2.indexOf("=");
25947
+ for (const pair3 of pairs3) {
25948
+ const eq = pair3.indexOf("=");
24241
25949
  if (eq <= 0)
24242
25950
  throw new CliError(
24243
- `--${flag} takes key=value, got ${JSON.stringify(pair2)}`
25951
+ `--${flag} takes key=value, got ${JSON.stringify(pair3)}`
24244
25952
  );
24245
- out[pair2.slice(0, eq)] = pair2.slice(eq + 1);
25953
+ out[pair3.slice(0, eq)] = pair3.slice(eq + 1);
24246
25954
  }
24247
25955
  return out;
24248
25956
  }
@@ -24259,7 +25967,7 @@ function registerTaskCommands(root) {
24259
25967
  positionals: [
24260
25968
  {
24261
25969
  name: "spec",
24262
- help: "JSON file: {instruction, seed?, grader?, metadata?, name?}."
25970
+ help: "JSON file: {instruction, seed?, grader?, metadata?, name?, worlds?, verifiers?}."
24263
25971
  }
24264
25972
  ],
24265
25973
  flags: [
@@ -24478,7 +26186,7 @@ function registerTaskCommands(root) {
24478
26186
  },
24479
26187
  HOST_FLAG
24480
26188
  ],
24481
- notes: "A task spec with `worlds` \u2014 {alias: {slug, ref?, seed?, grader?, tools?}} \u2014 is one instruction over several hosted\nworlds. `up` opens one session per alias (each on that world's own seed, grader and tools) in ONE platform call:\nif any world refuses, the ones that opened are closed and the error names every alias that failed, so nothing is\never half up. The manifest is keyed by alias; each entry is what `session open` prints for that world (api.url +\ntoken for --surface api). Later commands take the task id (finds the stored task's live sessions) or the manifest.",
26189
+ notes: "A task spec with `worlds` \u2014 {alias: {slug, ref?, seed?, grader?, tools?}} \u2014 is one instruction over several hosted\nworlds. `up` opens one session per alias (each on that world's own seed, grader and tools) in ONE platform call:\nif any world refuses, the ones that opened are closed and the error names every alias that failed, so nothing is\never half up. The manifest is keyed by alias; each entry is what `session open` prints for that world (api.url +\ntoken for --surface api). Later commands take the task id (finds the stored task's live sessions) or the manifest.\nA world where you have unsealed edits comes up at your tip (`private: true`); everyone else still gets shared main.\n`gateway worlds task edit status <task>` lists them; `task edit close <task>` seals them on every world at once.",
24482
26190
  run: async (args, ctx) => {
24483
26191
  const target = taskTarget(args.positionals[0]);
24484
26192
  if (target.kind === "manifest")
@@ -24639,23 +26347,23 @@ function registerTaskCommands(root) {
24639
26347
  const exported = await live.export();
24640
26348
  const lines = [];
24641
26349
  for (const [alias, calls] of Object.entries(exported))
24642
- for (const call2 of calls)
26350
+ for (const call3 of calls)
24643
26351
  lines.push(
24644
26352
  JSON.stringify({
24645
26353
  world: alias,
24646
- seq: call2.seq,
24647
- kind: call2.kind,
24648
- tool: call2.tool,
24649
- args: call2.args,
24650
- result: call2.result,
24651
- error: call2.error,
24652
- completedAt: call2.completedAt
26354
+ seq: call3.seq,
26355
+ kind: call3.kind,
26356
+ tool: call3.tool,
26357
+ args: call3.args,
26358
+ result: call3.result,
26359
+ error: call3.error,
26360
+ completedAt: call3.completedAt
24653
26361
  })
24654
26362
  );
24655
26363
  const text2 = lines.join("\n") + (lines.length ? "\n" : "");
24656
26364
  const out = arg.str(args, "out");
24657
26365
  if (out) {
24658
- fs47.writeFileSync(out, text2);
26366
+ fs48.writeFileSync(out, text2);
24659
26367
  ctx.stdout(
24660
26368
  `wrote ${lines.length} calls from ${Object.keys(exported).length} worlds to ${out}`
24661
26369
  );
@@ -25098,7 +26806,7 @@ source (bundled|stored|inline|none)/name/hash/id/version.
25098
26806
  try {
25099
26807
  const url = await browser.goto(arg.str(args, "path"));
25100
26808
  const shot = arg.str(args, "screenshot");
25101
- if (shot) fs48.writeFileSync(shot, await browser.screenshot());
26809
+ if (shot) fs49.writeFileSync(shot, await browser.screenshot());
25102
26810
  printJson(ctx, {
25103
26811
  url,
25104
26812
  title: await browser.title(),
@@ -25224,21 +26932,21 @@ world's [redact] policy over the rows first; --redact refuse rejects plaintext i
25224
26932
  );
25225
26933
  const deadline = Date.now() + SEED_TIMEOUT_MS;
25226
26934
  for (; ; ) {
25227
- const call2 = await api(
26935
+ const call3 = await api(
25228
26936
  creds,
25229
26937
  "GET",
25230
26938
  `${sessionRoute(sessionId)}/calls/${encodeURIComponent(callId)}`
25231
26939
  );
25232
- const settled = call2.done || call2.state === "completed" || call2.state === "failed";
26940
+ const settled = call3.done || call3.state === "completed" || call3.state === "failed";
25233
26941
  if (settled) {
25234
- if (call2.error || call2.state === "failed")
25235
- throw new CliError(call2.error ?? "seed failed", 1);
25236
- printJson(ctx, { sessionId, mode, ...redact2 !== "off" ? { redact: redact2 } : {}, result: call2.result });
26942
+ if (call3.error || call3.state === "failed")
26943
+ throw new CliError(call3.error ?? "seed failed", 1);
26944
+ printJson(ctx, { sessionId, mode, ...redact2 !== "off" ? { redact: redact2 } : {}, result: call3.result });
25237
26945
  return;
25238
26946
  }
25239
26947
  if (Date.now() > deadline)
25240
26948
  throw new CliError(
25241
- `Seed call ${callId} still ${call2.state} after ${SEED_TIMEOUT_MS / 1e3}s.`,
26949
+ `Seed call ${callId} still ${call3.state} after ${SEED_TIMEOUT_MS / 1e3}s.`,
25242
26950
  1
25243
26951
  );
25244
26952
  await sleep2(SEED_POLL_MS);
@@ -25271,9 +26979,9 @@ world's [redact] policy over the rows first; --redact refuse rejects plaintext i
25271
26979
  cursor = page.nextCursor ?? void 0;
25272
26980
  } while (cursor);
25273
26981
  const lines = calls.map(
25274
- (call2) => JSON.stringify(
26982
+ (call3) => JSON.stringify(
25275
26983
  Object.fromEntries(
25276
- EXPORT_KEYS.map((key2) => [key2, call2[key2] ?? null])
26984
+ EXPORT_KEYS.map((key2) => [key2, call3[key2] ?? null])
25277
26985
  )
25278
26986
  )
25279
26987
  );
@@ -25281,12 +26989,12 @@ world's [redact] policy over the rows first; --redact refuse rejects plaintext i
25281
26989
  const out = arg.str(args, "out");
25282
26990
  const to = arg.str(args, "to");
25283
26991
  if (out) {
25284
- fs48.writeFileSync(out, text2);
26992
+ fs49.writeFileSync(out, text2);
25285
26993
  ctx.stdout(`wrote ${lines.length} calls to ${out}`);
25286
26994
  } else if (!to && text2) process.stdout.write(text2);
25287
26995
  if (!to) return;
25288
26996
  const scratch = out ? null : scratchFile(`${sessionId}.calls.jsonl`);
25289
- if (scratch) fs48.writeFileSync(scratch.file, text2);
26997
+ if (scratch) fs49.writeFileSync(scratch.file, text2);
25290
26998
  try {
25291
26999
  const landed = await landInDrive(scratch?.file ?? out, to, creds);
25292
27000
  ctx.stdout(`wrote ${lines.length} calls to drive:${landed.path}`);
@@ -25300,6 +27008,166 @@ world's [redact] policy over the rows first; --redact refuse rejects plaintext i
25300
27008
  // src/cli/platform/index.ts
25301
27009
  init_skill();
25302
27010
 
27011
+ // src/cli/platform/taskEditVerbs.ts
27012
+ init_config();
27013
+ init_router();
27014
+ init_editSessions();
27015
+ init_worlds();
27016
+ init_shared();
27017
+ var TASK_POSITIONAL = {
27018
+ name: "task",
27019
+ help: "Task id, a spec file with a `worlds` table, or the manifest `task up --out` wrote."
27020
+ };
27021
+ var TASK_VERSION_FLAG = {
27022
+ name: "task-version",
27023
+ help: "With a task id: that version's worlds instead of the current one's."
27024
+ };
27025
+ var MESSAGE_FLAG4 = {
27026
+ name: "message",
27027
+ short: "m",
27028
+ help: "Change reason recorded on every session it seals or writes (and on a version a rebase writes), shown in History."
27029
+ };
27030
+ function taskEditTarget(positional, version) {
27031
+ const target = taskTarget(positional);
27032
+ if (target.kind === "id")
27033
+ return { id: target.taskId, ...version === void 0 ? {} : { version } };
27034
+ if (target.kind === "spec") {
27035
+ if (!target.spec.worlds)
27036
+ throw new CliError(
27037
+ "task edit needs a spec that names its worlds ({instruction, worlds: {alias: {slug, \u2026}}}); for one world use `gateway worlds edit`"
27038
+ );
27039
+ return target.spec;
27040
+ }
27041
+ const { manifest } = target;
27042
+ if (manifest.taskId)
27043
+ return {
27044
+ id: manifest.taskId,
27045
+ ...manifest.taskVersion === null ? {} : { version: manifest.taskVersion }
27046
+ };
27047
+ return {
27048
+ instruction: manifest.instruction ?? "task",
27049
+ worlds: Object.fromEntries(
27050
+ Object.entries(manifest.sessions).map(([alias, s]) => [
27051
+ alias,
27052
+ { slug: s.slug, ...s.ref ? { ref: s.ref } : {} }
27053
+ ])
27054
+ )
27055
+ };
27056
+ }
27057
+ function client3(args) {
27058
+ return new TaskEditClient(worldsOptions(credentials(args)));
27059
+ }
27060
+ async function call2(run) {
27061
+ try {
27062
+ return await run();
27063
+ } catch (error) {
27064
+ if (error instanceof ApiError)
27065
+ throw new CliError(`Error: ${error.message}`, 1);
27066
+ throw error;
27067
+ }
27068
+ }
27069
+ function registerTaskEditVerbs(root) {
27070
+ const edit = root.group("worlds", "Build, seed, serve and run worlds.").group(
27071
+ "task",
27072
+ "Stored tasks: instruction + seed + grader kept by the project, outside any bundle."
27073
+ ).group(
27074
+ "edit",
27075
+ "Edit sessions across every world a task names: see what this credential has not sealed, seal every world onto main in one step (all or none), roll the group back together."
27076
+ );
27077
+ edit.command({
27078
+ name: "status",
27079
+ output: "json",
27080
+ help: "Per world of the task: this credential's open edit session (edits, base, tip) and what sealing now would do (fast-forward, rebase or conflict with its paths); `unsealed` lists the worlds holding edits only you see.",
27081
+ positionals: [TASK_POSITIONAL],
27082
+ flags: [TASK_VERSION_FLAG, HOST_FLAG],
27083
+ notes: "Your own `task up` opens the worlds listed under `unsealed` at your tip (`private: true`); colleagues, run configs\nand schedules keep shared main until `task edit close` seals them. `parked` lists sessions stuck in conflict.",
27084
+ run: async (args, ctx) => {
27085
+ const task = taskEditTarget(
27086
+ args.positionals[0],
27087
+ arg.int(args, "task-version")
27088
+ );
27089
+ printJson(ctx, await call2(() => client3(args).status(task)));
27090
+ }
27091
+ });
27092
+ edit.command({
27093
+ name: "close",
27094
+ help: "Seal this credential's open edit session on every world of the task in ONE step: every main moves, or none does. Prints {groupId, worlds: {alias: {slug, session}}, skipped}.",
27095
+ positionals: [TASK_POSITIONAL],
27096
+ flags: [
27097
+ TASK_VERSION_FLAG,
27098
+ {
27099
+ name: "require-all",
27100
+ help: "Refuse unless every world has an open edit to seal (default: skip those that have none and list them).",
27101
+ boolean: true
27102
+ },
27103
+ {
27104
+ name: "force",
27105
+ help: "Where main moved under a session on the same paths, keep the session's files instead of refusing the whole close.",
27106
+ boolean: true
27107
+ },
27108
+ MESSAGE_FLAG4,
27109
+ HOST_FLAG
27110
+ ],
27111
+ notes: "Each world seals as `gateway worlds edit close` would: a fast-forward, or a rebase when main moved on other\npaths. If any world conflicts, is missing, names a ref other than main, holds a session of yours parked in\nconflict, or fails, NOTHING is sealed and the error (exit 1) names every world's problem. The sessions share\n`groupId`: `task edit rollback --group` undoes them.",
27112
+ run: async (args, ctx) => {
27113
+ const task = taskEditTarget(
27114
+ args.positionals[0],
27115
+ arg.int(args, "task-version")
27116
+ );
27117
+ printJson(
27118
+ ctx,
27119
+ await call2(
27120
+ () => client3(args).close(task, {
27121
+ requireAll: arg.bool(args, "require-all") || void 0,
27122
+ force: arg.bool(args, "force") || void 0,
27123
+ message: arg.str(args, "message")
27124
+ })
27125
+ )
27126
+ );
27127
+ }
27128
+ });
27129
+ edit.command({
27130
+ name: "rollback",
27131
+ help: "Undo a seal group: every world's main returns to the source and data it had before the group, in one step, as new sealed sessions sharing a new groupId (so the rollback is itself reversible).",
27132
+ positionals: [TASK_POSITIONAL],
27133
+ flags: [
27134
+ TASK_VERSION_FLAG,
27135
+ {
27136
+ name: "group",
27137
+ help: "The groupId `task edit close` printed (required)."
27138
+ },
27139
+ {
27140
+ name: "force",
27141
+ help: "Also undo what reached those worlds' main after the group: later sessions or writes outside sessions (refused without it).",
27142
+ boolean: true
27143
+ },
27144
+ MESSAGE_FLAG4,
27145
+ HOST_FLAG
27146
+ ],
27147
+ run: async (args, ctx) => {
27148
+ const groupId = arg.str(args, "group");
27149
+ if (!groupId)
27150
+ throw new CliError(
27151
+ "task edit rollback needs --group <groupId> (printed by `task edit close`)"
27152
+ );
27153
+ const task = taskEditTarget(
27154
+ args.positionals[0],
27155
+ arg.int(args, "task-version")
27156
+ );
27157
+ printJson(
27158
+ ctx,
27159
+ await call2(
27160
+ () => client3(args).rollback(task, {
27161
+ groupId,
27162
+ force: arg.bool(args, "force") || void 0,
27163
+ message: arg.str(args, "message")
27164
+ })
27165
+ )
27166
+ );
27167
+ }
27168
+ });
27169
+ }
27170
+
25303
27171
  // src/cli/platform/taskRunSet.ts
25304
27172
  init_config();
25305
27173
  init_router();
@@ -25386,7 +27254,7 @@ function registerTaskRunSet(root) {
25386
27254
  // src/cli/platform/traces.ts
25387
27255
  init_config();
25388
27256
  init_router();
25389
- import * as fs49 from "fs";
27257
+ import * as fs50 from "fs";
25390
27258
 
25391
27259
  // src/traces/index.ts
25392
27260
  init_worlds();
@@ -25545,11 +27413,11 @@ function registerTracesCommands(root) {
25545
27413
  flags: [...FILTER_FLAGS, { name: "limit", help: "At most this many (pages of 100 underneath).", default: "50" }, JSON_FLAG3, HOST_FLAG],
25546
27414
  run: async (args, ctx) => {
25547
27415
  const options = worldsOptions(credentials(args));
25548
- const listed = [];
25549
- for await (const trace3 of iterateTraces(options, filtersOf(args), { max: limitOf(args, 50) })) listed.push(trace3);
25550
- if (arg.bool(args, "json")) return void printJson(ctx, listed);
25551
- if (!listed.length) return void ctx.stderr("no traces match");
25552
- for (const trace3 of listed) ctx.stdout(traceLine(trace3));
27416
+ const listed2 = [];
27417
+ for await (const trace3 of iterateTraces(options, filtersOf(args), { max: limitOf(args, 50) })) listed2.push(trace3);
27418
+ if (arg.bool(args, "json")) return void printJson(ctx, listed2);
27419
+ if (!listed2.length) return void ctx.stderr("no traces match");
27420
+ for (const trace3 of listed2) ctx.stdout(traceLine(trace3));
25553
27421
  }
25554
27422
  });
25555
27423
  traces.command({
@@ -25603,7 +27471,7 @@ function registerTracesCommands(root) {
25603
27471
  const scratch = toDrive ? scratchFile("traces.jsonl") : null;
25604
27472
  const file = toStdout ? null : scratch?.file ?? out;
25605
27473
  try {
25606
- const sink = file ? fs49.createWriteStream(file) : null;
27474
+ const sink = file ? fs50.createWriteStream(file) : null;
25607
27475
  const write = (record) => {
25608
27476
  const line = JSON.stringify(record) + "\n";
25609
27477
  if (sink) sink.write(line);
@@ -25634,11 +27502,11 @@ function registerTracesCommands(root) {
25634
27502
  ],
25635
27503
  run: async (args, ctx) => {
25636
27504
  const filters = { fromTimestamp: arg.str(args, "from"), toTimestamp: arg.str(args, "to"), environment: arg.str(args, "environment") };
25637
- const listed = [];
25638
- for await (const session of iterateSessions(worldsOptions(credentials(args)), filters, { max: limitOf(args, 50) })) listed.push(session);
25639
- if (arg.bool(args, "json")) return void printJson(ctx, listed);
25640
- if (!listed.length) return void ctx.stderr("no sessions match");
25641
- for (const session of listed) ctx.stdout(`${session.id} ${session.createdAt} ${session.environment}`);
27505
+ const listed2 = [];
27506
+ for await (const session of iterateSessions(worldsOptions(credentials(args)), filters, { max: limitOf(args, 50) })) listed2.push(session);
27507
+ if (arg.bool(args, "json")) return void printJson(ctx, listed2);
27508
+ if (!listed2.length) return void ctx.stderr("no sessions match");
27509
+ for (const session of listed2) ctx.stdout(`${session.id} ${session.createdAt} ${session.environment}`);
25642
27510
  }
25643
27511
  });
25644
27512
  sessions.command({
@@ -25721,8 +27589,8 @@ function registerTracesCommands(root) {
25721
27589
  });
25722
27590
  }
25723
27591
  function readFile2(file) {
25724
- if (!fs49.existsSync(file)) throw new CliError(`${file} does not exist`, 1);
25725
- return fs49.readFileSync(file, "utf8");
27592
+ if (!fs50.existsSync(file)) throw new CliError(`${file} does not exist`, 1);
27593
+ return fs50.readFileSync(file, "utf8");
25726
27594
  }
25727
27595
 
25728
27596
  // src/cli/platform/worldData/chunks.ts
@@ -25910,6 +27778,7 @@ function registerPlatformCommands(root) {
25910
27778
  registerSessionCommands(root);
25911
27779
  registerTaskCommands(root);
25912
27780
  registerTaskRunSet(root);
27781
+ registerTaskEditVerbs(root);
25913
27782
  registerConnectorCommands(root);
25914
27783
  registerSkillCommands(root);
25915
27784
  registerDataCommands(root);
@@ -25931,7 +27800,7 @@ init_router();
25931
27800
  init_config();
25932
27801
  init_local();
25933
27802
  init_client();
25934
- import * as fs50 from "fs";
27803
+ import * as fs51 from "fs";
25935
27804
  import * as path38 from "path";
25936
27805
  var HOST_FLAG4 = {
25937
27806
  name: "host",
@@ -25963,9 +27832,9 @@ function wireParams(params) {
25963
27832
  }
25964
27833
  function requireConnectorToml(dir) {
25965
27834
  const file = path38.join(dir, "connector.toml");
25966
- if (!fs50.existsSync(file))
27835
+ if (!fs51.existsSync(file))
25967
27836
  throw new CliError(`${dir} holds no connector.toml`, 1);
25968
- return fs50.readFileSync(file, "utf8");
27837
+ return fs51.readFileSync(file, "utf8");
25969
27838
  }
25970
27839
  function renderConnection(spec) {
25971
27840
  const lines = [`${spec.slug} ${spec.baseUrl} auth=${spec.auth}`];
@@ -26057,9 +27926,9 @@ async function remoteCapture(creds, world, opts, ctx) {
26057
27926
  if (!res.ok)
26058
27927
  throw new CliError(`download ${drivePath2} -> ${res.status}`, 1);
26059
27928
  const destination = path38.join(world, relative4);
26060
- fs50.mkdirSync(path38.dirname(destination), { recursive: true });
27929
+ fs51.mkdirSync(path38.dirname(destination), { recursive: true });
26061
27930
  const bytes = Buffer.from(await res.arrayBuffer());
26062
- fs50.writeFileSync(destination, bytes);
27931
+ fs51.writeFileSync(destination, bytes);
26063
27932
  written.push(relative4);
26064
27933
  for (const name of undeclaredParams(bytes))
26065
27934
  ctx.stderr(
@@ -26067,7 +27936,7 @@ async function remoteCapture(creds, world, opts, ctx) {
26067
27936
  );
26068
27937
  }
26069
27938
  const manifestPath2 = path38.join(world, CAPTURES, MANIFEST);
26070
- const existing = fs50.existsSync(manifestPath2) ? JSON.parse(fs50.readFileSync(manifestPath2, "utf8")) : [];
27939
+ const existing = fs51.existsSync(manifestPath2) ? JSON.parse(fs51.readFileSync(manifestPath2, "utf8")) : [];
26071
27940
  const known = new Set(
26072
27941
  existing.map(
26073
27942
  (e) => e && typeof e === "object" ? e.file : void 0
@@ -26080,8 +27949,8 @@ async function remoteCapture(creds, world, opts, ctx) {
26080
27949
  existing.push(entry);
26081
27950
  known.add(file);
26082
27951
  }
26083
- fs50.mkdirSync(path38.dirname(manifestPath2), { recursive: true });
26084
- fs50.writeFileSync(manifestPath2, sortedJson(existing, 1) + "\n");
27952
+ fs51.mkdirSync(path38.dirname(manifestPath2), { recursive: true });
27953
+ fs51.writeFileSync(manifestPath2, sortedJson(existing, 1) + "\n");
26085
27954
  return written;
26086
27955
  }
26087
27956
  function outcomeOk(outcome) {
@@ -26171,8 +28040,8 @@ function registerConnectorCommands2(connector) {
26171
28040
  `local capture runs the vendor call from this machine and needs python3 >= 3.12 (the CLI bundles the runtime). ${localRuntimeReason()} Or use --remote to capture from the platform.`
26172
28041
  );
26173
28042
  const argv = ["connector-capture", dir, "--op", op];
26174
- for (const pair2 of arg.list(args, "arg")) argv.push("--arg", pair2);
26175
- for (const pair2 of arg.list(args, "param")) argv.push("--param", pair2);
28043
+ for (const pair3 of arg.list(args, "arg")) argv.push("--arg", pair3);
28044
+ for (const pair3 of arg.list(args, "param")) argv.push("--param", pair3);
26176
28045
  const maxPages = arg.int(args, "max-pages");
26177
28046
  if (maxPages !== void 0) argv.push("--max-pages", String(maxPages));
26178
28047
  return localModule(argv, local);
@@ -26217,11 +28086,11 @@ function registerConnectorCommands2(connector) {
26217
28086
  throw new CliError("conform needs --openapi FILE (repeatable)");
26218
28087
  requireConnectorToml(dir);
26219
28088
  const openapi = documents.map((file) => {
26220
- if (!fs50.existsSync(file))
28089
+ if (!fs51.existsSync(file))
26221
28090
  throw new CliError(`--openapi ${file} does not exist`);
26222
28091
  return {
26223
28092
  path: path38.basename(file),
26224
- content: fs50.readFileSync(file).toString("base64")
28093
+ content: fs51.readFileSync(file).toString("base64")
26225
28094
  };
26226
28095
  });
26227
28096
  const limit = arg.int(args, "limit");
@@ -26239,7 +28108,7 @@ function registerConnectorCommands2(connector) {
26239
28108
  ctx.stdout(JSON.stringify(summary2));
26240
28109
  const out = arg.str(args, "out");
26241
28110
  if (out) {
26242
- fs50.writeFileSync(out, JSON.stringify(report, null, 1) + "\n");
28111
+ fs51.writeFileSync(out, JSON.stringify(report, null, 1) + "\n");
26243
28112
  ctx.stdout(`report: ${out}`);
26244
28113
  }
26245
28114
  return Number(summary2.status_mismatch) || Number(summary2.schema_violations) ? 1 : 0;
@@ -26268,7 +28137,7 @@ function registerConnectorCommands2(connector) {
26268
28137
  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.",
26269
28138
  run: async (args, ctx) => {
26270
28139
  const dir = path38.resolve(args.positionals[0]);
26271
- if (!fs50.existsSync(path38.join(dir, CAPTURES)))
28140
+ if (!fs51.existsSync(path38.join(dir, CAPTURES)))
26272
28141
  throw new CliError(
26273
28142
  `${dir} holds no ${CAPTURES}/ \u2014 run \`connector capture --remote\` first`,
26274
28143
  1
@@ -26299,7 +28168,7 @@ function registerConnectorCommands2(connector) {
26299
28168
  ` ${refusal.capture ?? "?"} ${refusal.pointer}: ${refusal.detail}`
26300
28169
  );
26301
28170
  if (report) {
26302
- fs50.writeFileSync(
28171
+ fs51.writeFileSync(
26303
28172
  report,
26304
28173
  refusals.map((r) => JSON.stringify(r) + "\n").join("")
26305
28174
  );
@@ -26329,10 +28198,10 @@ function registerConnectorCommands2(connector) {
26329
28198
  init_router();
26330
28199
  init_config();
26331
28200
  init_worlds();
26332
- init_session();
28201
+ init_session2();
26333
28202
  init_hub();
26334
28203
  init_local();
26335
- import * as fs51 from "fs";
28204
+ import * as fs52 from "fs";
26336
28205
  import * as path39 from "path";
26337
28206
  function registerServeCommand(worlds) {
26338
28207
  worlds.command({
@@ -26376,7 +28245,7 @@ function registerServeCommand(worlds) {
26376
28245
  run: async (args, ctx) => {
26377
28246
  const target = args.positionals[0];
26378
28247
  const local = localRuntime();
26379
- if (local && fs51.existsSync(target) && fs51.statSync(target).isDirectory()) {
28248
+ if (local && fs52.existsSync(target) && fs52.statSync(target).isDirectory()) {
26380
28249
  const port = arg.int(args, "port") ?? 8080;
26381
28250
  if (!Number.isInteger(port) || port < 0 || port > 65535)
26382
28251
  throw new CliError(
@@ -26397,7 +28266,7 @@ function registerServeCommand(worlds) {
26397
28266
  );
26398
28267
  return localModule(argv, local);
26399
28268
  }
26400
- if (!local && fs51.existsSync(target) && fs51.statSync(target).isDirectory())
28269
+ if (!local && fs52.existsSync(target) && fs52.statSync(target).isDirectory())
26401
28270
  ctx.stderr(
26402
28271
  `# ${localRuntimeReason()}
26403
28272
  # 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).`
@@ -26410,7 +28279,7 @@ function registerServeCommand(worlds) {
26410
28279
  };
26411
28280
  let slugRef = target;
26412
28281
  let versionId;
26413
- if (fs51.existsSync(target) && fs51.statSync(target).isDirectory()) {
28282
+ if (fs52.existsSync(target) && fs52.statSync(target).isDirectory()) {
26414
28283
  const dir = path39.resolve(target);
26415
28284
  const meta = readLocalMeta(dir);
26416
28285
  const slug = meta?.slug ?? path39.basename(dir);
@@ -26420,7 +28289,7 @@ function registerServeCommand(worlds) {
26420
28289
  ctx.stderr(
26421
28290
  "`worlds serve` runs a local session with the Python runtime; opening a hosted api-surface session instead."
26422
28291
  );
26423
- if (!local && !(fs51.existsSync(target) && fs51.statSync(target).isDirectory())) ctx.stderr(`# ${localRuntimeReason()}`);
28292
+ if (!local && !(fs52.existsSync(target) && fs52.statSync(target).isDirectory())) ctx.stderr(`# ${localRuntimeReason()}`);
26424
28293
  let scenario = arg.str(args, "scenario") ?? arg.str(args, "task");
26425
28294
  if (!scenario) {
26426
28295
  const world = await openWorld(slugRef, options);
@@ -26463,7 +28332,7 @@ init_shared();
26463
28332
  init_local();
26464
28333
  init_config();
26465
28334
  init_client();
26466
- import * as fs52 from "fs";
28335
+ import * as fs53 from "fs";
26467
28336
  import * as path40 from "path";
26468
28337
  function renderWorldTestReport(report) {
26469
28338
  const lines = [];
@@ -26520,7 +28389,7 @@ function registerTestCommand(worlds) {
26520
28389
  run: async (args, ctx) => {
26521
28390
  const target = args.positionals[0] ?? ".";
26522
28391
  const dir = path40.resolve(target);
26523
- if (!fs52.existsSync(dir) || !fs52.statSync(dir).isDirectory()) {
28392
+ if (!fs53.existsSync(dir) || !fs53.statSync(dir).isDirectory()) {
26524
28393
  if (/[\/\\]/.test(target) || target.startsWith("."))
26525
28394
  throw new CliError(`Not a directory: ${dir}`, 1);
26526
28395
  const creds2 = resolveCredentials(arg.str(args, "host"));
@@ -26587,7 +28456,7 @@ function registerTestCommand(worlds) {
26587
28456
  }
26588
28457
  const out2 = arg.str(args, "out");
26589
28458
  if (out2)
26590
- fs52.writeFileSync(
28459
+ fs53.writeFileSync(
26591
28460
  out2,
26592
28461
  JSON.stringify(
26593
28462
  {
@@ -26616,7 +28485,7 @@ function registerTestCommand(worlds) {
26616
28485
  const s = report.summary ?? {};
26617
28486
  if (!(s.total ?? 0) && !(report.python?.files?.length ?? 0)) {
26618
28487
  const tests = path40.join(dir, "tests");
26619
- const state2 = fs52.existsSync(tests) ? "holds none" : "does not exist";
28488
+ const state2 = fs53.existsSync(tests) ? "holds none" : "does not exist";
26620
28489
  ctx.stdout(`no cases: ${tests} ${state2} (see \`gateway worlds test --help\` for the shapes)`);
26621
28490
  }
26622
28491
  ctx.stdout(
@@ -26625,7 +28494,7 @@ function registerTestCommand(worlds) {
26625
28494
  }
26626
28495
  const out = arg.str(args, "out");
26627
28496
  if (out) {
26628
- fs52.writeFileSync(out, JSON.stringify(report, null, 1) + "\n");
28497
+ fs53.writeFileSync(out, JSON.stringify(report, null, 1) + "\n");
26629
28498
  ctx.stdout(`report: ${out}`);
26630
28499
  }
26631
28500
  return report.summary?.status === "passed" ? 0 : 1;
@@ -26635,13 +28504,13 @@ function registerTestCommand(worlds) {
26635
28504
 
26636
28505
  // src/cli/runtime/call.ts
26637
28506
  init_router();
26638
- init_session();
28507
+ init_session2();
26639
28508
  init_sessionContract();
26640
28509
  init_shared();
26641
28510
  init_local();
26642
28511
  init_client();
26643
28512
  init_storeContract();
26644
- import * as fs53 from "fs";
28513
+ import * as fs54 from "fs";
26645
28514
  import * as path41 from "path";
26646
28515
  function parseArgs2(raw, stdin) {
26647
28516
  if (raw === void 0) return {};
@@ -26649,8 +28518,8 @@ function parseArgs2(raw, stdin) {
26649
28518
  if (raw === "-") text2 = stdin;
26650
28519
  else if (raw.startsWith("@")) {
26651
28520
  const file = raw.slice(1);
26652
- if (!fs53.existsSync(file)) throw new CliError(`--args ${raw}: ${file} does not exist`);
26653
- text2 = fs53.readFileSync(file, "utf8");
28521
+ if (!fs54.existsSync(file)) throw new CliError(`--args ${raw}: ${file} does not exist`);
28522
+ text2 = fs54.readFileSync(file, "utf8");
26654
28523
  }
26655
28524
  let value;
26656
28525
  try {
@@ -26725,7 +28594,7 @@ async function callHosted(sessionId, tool, args, wants, options) {
26725
28594
  return settleStatus(report);
26726
28595
  }
26727
28596
  function looksLikeSessionId(target) {
26728
- return !target.includes("/") && !target.startsWith(".") && !fs53.existsSync(target);
28597
+ return !target.includes("/") && !target.startsWith(".") && !fs54.existsSync(target);
26729
28598
  }
26730
28599
  async function callServed(base, tool, args, wants) {
26731
28600
  const url = base.replace(/\/+$/, "");
@@ -26845,7 +28714,7 @@ Examples:
26845
28714
  }
26846
28715
  if (arg.bool(args, "close")) throw new CliError("--close ends a served or hosted session; pass its url or id instead of a directory");
26847
28716
  const dir = path41.resolve(target);
26848
- if (!fs53.existsSync(dir) || !fs53.statSync(dir).isDirectory()) throw new CliError(`Not a directory: ${dir}`, 1);
28717
+ if (!fs54.existsSync(dir) || !fs54.statSync(dir).isDirectory()) throw new CliError(`Not a directory: ${dir}`, 1);
26849
28718
  const local = localRuntime();
26850
28719
  if (!local)
26851
28720
  throw new CliError(
@@ -26882,12 +28751,12 @@ Examples:
26882
28751
 
26883
28752
  // src/cli/runtime/scaffold.ts
26884
28753
  init_router();
26885
- import * as fs55 from "fs";
28754
+ import * as fs56 from "fs";
26886
28755
  import * as path42 from "path";
26887
28756
 
26888
28757
  // src/cli/runtime/scaffoldJson.ts
26889
28758
  init_router();
26890
- import * as fs54 from "fs";
28759
+ import * as fs55 from "fs";
26891
28760
  var PROPERTY_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
26892
28761
  var isObject12 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
26893
28762
  function resolveObjectSchema(root, schema) {
@@ -26901,10 +28770,10 @@ function resolveObjectSchema(root, schema) {
26901
28770
  return schema;
26902
28771
  }
26903
28772
  function readJsonFile2(file) {
26904
- if (!fs54.existsSync(file)) throw new CliError(`${file} does not exist; run \`gateway worlds schema init\` first`, 1);
28773
+ if (!fs55.existsSync(file)) throw new CliError(`${file} does not exist; run \`gateway worlds schema init\` first`, 1);
26905
28774
  let parsed;
26906
28775
  try {
26907
- parsed = JSON.parse(fs54.readFileSync(file, "utf8"));
28776
+ parsed = JSON.parse(fs55.readFileSync(file, "utf8"));
26908
28777
  } catch (err) {
26909
28778
  throw new CliError(`${file} is not valid JSON: ${err.message}`, 1);
26910
28779
  }
@@ -27135,7 +29004,7 @@ var MAX_ENTITY_NAME = 64;
27135
29004
  var FIELD_TYPES = /* @__PURE__ */ new Set(["string", "integer", "number", "boolean"]);
27136
29005
  function parseFields(spec) {
27137
29006
  const properties = {};
27138
- const required = [];
29007
+ const required2 = [];
27139
29008
  for (const raw of spec.split(",")) {
27140
29009
  const item = raw.trim();
27141
29010
  if (!item) continue;
@@ -27153,10 +29022,10 @@ function parseFields(spec) {
27153
29022
  );
27154
29023
  if (name in properties) throw new CliError(`Duplicate field ${name}`);
27155
29024
  properties[name] = { type };
27156
- if (!optional) required.push(name);
29025
+ if (!optional) required2.push(name);
27157
29026
  }
27158
29027
  if (!Object.keys(properties).length) throw new CliError("--fields declares no properties");
27159
- return { type: "object", properties, required, additionalProperties: false };
29028
+ return { type: "object", properties, required: required2, additionalProperties: false };
27160
29029
  }
27161
29030
  function parseRelationship(spec) {
27162
29031
  const arrow = spec.indexOf("->");
@@ -27213,13 +29082,13 @@ function addEntity(root, spec) {
27213
29082
  if (payload.type !== "object" || payload.additionalProperties !== false)
27214
29083
  throw new CliError('An entity payload must be a closed object: type "object" with additionalProperties false');
27215
29084
  const properties = isObject12(payload.properties) ? payload.properties : {};
27216
- const required = Array.isArray(payload.required) ? payload.required : [];
29085
+ const required2 = Array.isArray(payload.required) ? payload.required : [];
27217
29086
  for (const key2 of spec.primaryKey) {
27218
29087
  const prop = properties[key2];
27219
29088
  if (!isObject12(prop)) throw new CliError(`Primary key field ${key2} is not a property of the payload`);
27220
29089
  if (prop.type !== "string" && prop.type !== "integer")
27221
29090
  throw new CliError(`Primary key field ${key2} must be a string or integer property`);
27222
- if (!required.includes(key2)) throw new CliError(`Primary key field ${key2} must be required`);
29091
+ if (!required2.includes(key2)) throw new CliError(`Primary key field ${key2} must be required`);
27223
29092
  }
27224
29093
  for (const rel of spec.relationships)
27225
29094
  for (const field2 of rel.fields)
@@ -27403,10 +29272,10 @@ function removeDependency(toml, alias) {
27403
29272
  }
27404
29273
  function dependencyServes(depDir) {
27405
29274
  const manifest = path42.join(depDir, "gateway-env.toml");
27406
- if (!fs55.existsSync(manifest)) return void 0;
27407
- const tools = manifestServedTools(fs55.readFileSync(manifest, "utf8"));
29275
+ if (!fs56.existsSync(manifest)) return void 0;
29276
+ const tools = manifestServedTools(fs56.readFileSync(manifest, "utf8"));
27408
29277
  const connector = path42.join(depDir, "connector.toml");
27409
- const routes = fs55.existsSync(connector) ? declaredRoutes(fs55.readFileSync(connector, "utf8")).map((r) => r.name).filter(Boolean) : [];
29278
+ const routes = fs56.existsSync(connector) ? declaredRoutes(fs56.readFileSync(connector, "utf8")).map((r) => r.name).filter(Boolean) : [];
27410
29279
  return tools === void 0 ? void 0 : { tools, routes };
27411
29280
  }
27412
29281
  function addDependency(toml, spec, depServes, opts = {}) {
@@ -27490,40 +29359,40 @@ function dependencyPath(toml, alias) {
27490
29359
  }
27491
29360
  function readManifest2(dir) {
27492
29361
  const file = path42.join(dir, "gateway-env.toml");
27493
- if (!fs55.existsSync(file)) throw new CliError(`${dir} holds no gateway-env.toml; run \`gateway worlds schema init\` first`, 1);
27494
- return { file, toml: fs55.readFileSync(file, "utf8") };
29362
+ if (!fs56.existsSync(file)) throw new CliError(`${dir} holds no gateway-env.toml; run \`gateway worlds schema init\` first`, 1);
29363
+ return { file, toml: fs56.readFileSync(file, "utf8") };
27495
29364
  }
27496
29365
  function verifierNames2(dir) {
27497
29366
  const folder = path42.join(dir, "verifiers");
27498
- if (!fs55.existsSync(folder)) return void 0;
27499
- return fs55.readdirSync(folder).filter((f) => f.endsWith(".sql")).map((f) => f.slice(0, -4)).sort();
29367
+ if (!fs56.existsSync(folder)) return void 0;
29368
+ return fs56.readdirSync(folder).filter((f) => f.endsWith(".sql")).map((f) => f.slice(0, -4)).sort();
27500
29369
  }
27501
29370
  var toPosix = (p) => p.split(path42.sep).join("/");
27502
29371
  var pinSlug = (name) => name.toLowerCase().replace(/[^a-z0-9._-]+/g, "-").replace(/^[^a-z0-9]+/, "") || "world";
27503
29372
  function declaredEntities(dir) {
27504
29373
  const file = path42.join(dir, "schema", "world.json");
27505
- if (!fs55.existsSync(file)) return void 0;
29374
+ if (!fs56.existsSync(file)) return void 0;
27506
29375
  const gateway = readJsonFile2(file)["x-gateway"];
27507
29376
  return isObject12(gateway) && isObject12(gateway.entities) ? Object.keys(gateway.entities) : [];
27508
29377
  }
27509
29378
  function worldEntityShapes(dir) {
27510
29379
  const file = path42.join(dir, "schema", "world.json");
27511
- return fs55.existsSync(file) ? declaredEntityShapes(readJsonFile2(file)) : void 0;
29380
+ return fs56.existsSync(file) ? declaredEntityShapes(readJsonFile2(file)) : void 0;
27512
29381
  }
27513
29382
  function declaredHandlerTools(dir) {
27514
29383
  const file = path42.join(dir, "schema", "world.json");
27515
- if (!fs55.existsSync(file)) return [];
29384
+ if (!fs56.existsSync(file)) return [];
27516
29385
  const gateway = readJsonFile2(file)["x-gateway"];
27517
29386
  return isObject12(gateway) && isObject12(gateway.tools) ? Object.keys(gateway.tools) : [];
27518
29387
  }
27519
29388
  var WORLD_SLUG = /^[a-z0-9][a-z0-9-]*$/;
27520
29389
  function connectorTomlSkeleton(dir) {
27521
29390
  const manifest = path42.join(dir, "gateway-env.toml");
27522
- if (!fs55.existsSync(dir))
29391
+ if (!fs56.existsSync(dir))
27523
29392
  throw new CliError(`${dir} does not exist; run \`gateway worlds schema init ${dir} --connector custom\` to start a world there`, 1);
27524
- if (!fs55.existsSync(manifest))
29393
+ if (!fs56.existsSync(manifest))
27525
29394
  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);
27526
- const name = /^\s*name\s*=\s*"([^"]*)"/m.exec(fs55.readFileSync(manifest, "utf8"))?.[1];
29395
+ const name = /^\s*name\s*=\s*"([^"]*)"/m.exec(fs56.readFileSync(manifest, "utf8"))?.[1];
27527
29396
  const slug = name && WORLD_SLUG.test(name) ? name : path42.basename(dir).toLowerCase().replace(/[^a-z0-9-]+/g, "-").replace(/^-+|-+$/g, "") || "world";
27528
29397
  return [
27529
29398
  `# ${slug}'s API surface: the HTTP routes the world serves beside its tools, from one`,
@@ -27580,20 +29449,20 @@ function whereClauseDefect(clause) {
27580
29449
  function addVerifier(dir, name, entity, where) {
27581
29450
  const sql = verifierSql(name, entity, where);
27582
29451
  const file = path42.join(dir, "verifiers", `${name}.sql`);
27583
- if (fs55.existsSync(file))
29452
+ if (fs56.existsSync(file))
27584
29453
  throw new CliError(`verifiers/${name}.sql already exists (have: ${(verifierNames2(dir) ?? []).join(", ")}); edit it, or pick another name`);
27585
- fs55.mkdirSync(path42.dirname(file), { recursive: true });
27586
- fs55.writeFileSync(file, sql);
29454
+ fs56.mkdirSync(path42.dirname(file), { recursive: true });
29455
+ fs56.writeFileSync(file, sql);
27587
29456
  return file;
27588
29457
  }
27589
29458
  function repointScaffoldVerifier(dir, entity, declared) {
27590
29459
  const file = path42.join(dir, "verifiers", "state_present.sql");
27591
- if (!fs55.existsSync(file)) return null;
27592
- const text2 = fs55.readFileSync(file, "utf8");
29460
+ if (!fs56.existsSync(file)) return null;
29461
+ const text2 = fs56.readFileSync(file, "utf8");
27593
29462
  const match = SCAFFOLD_VERIFIER.exec(text2);
27594
29463
  if (!match || text2 !== scaffoldVerifier(match[1])) return null;
27595
29464
  if (declared.includes(match[1])) return null;
27596
- fs55.writeFileSync(file, scaffoldVerifier(entity));
29465
+ fs56.writeFileSync(file, scaffoldVerifier(entity));
27597
29466
  return file;
27598
29467
  }
27599
29468
  function parsePairs(values, flag) {
@@ -27656,7 +29525,7 @@ function registerScaffoldCommands(worlds) {
27656
29525
  unique: arg.list(args, "unique").map((u) => u.split(",").map((f) => f.trim()).filter(Boolean)),
27657
29526
  relationships: arg.list(args, "relationship").map(parseRelationship)
27658
29527
  });
27659
- fs55.writeFileSync(file, JSON.stringify(document, null, 2) + "\n");
29528
+ fs56.writeFileSync(file, JSON.stringify(document, null, 2) + "\n");
27660
29529
  const out = { status: "ok", entity: name, declaration, file: path42.relative(process.cwd(), file) || file };
27661
29530
  if (def) out.def = def;
27662
29531
  const verifier = repointScaffoldVerifier(dir, name, declaredEntities(dir) ?? []);
@@ -27737,21 +29606,21 @@ function registerScaffoldCommands(worlds) {
27737
29606
  const depArg = args.positionals[2];
27738
29607
  const depDir = path42.resolve(depArg);
27739
29608
  const { file, toml } = readManifest2(dir);
27740
- if (!fs55.existsSync(path42.join(depDir, "gateway-env.toml"))) {
29609
+ if (!fs56.existsSync(path42.join(depDir, "gateway-env.toml"))) {
27741
29610
  const fromWorld = path42.resolve(dir, depArg);
27742
- const hint = fromWorld !== depDir && fs55.existsSync(path42.join(fromWorld, "gateway-env.toml")) ? `; paths resolve from your shell, not from the world: did you mean ${path42.relative(process.cwd(), fromWorld) || "."}?` : "";
29611
+ const hint = fromWorld !== depDir && fs56.existsSync(path42.join(fromWorld, "gateway-env.toml")) ? `; paths resolve from your shell, not from the world: did you mean ${path42.relative(process.cwd(), fromWorld) || "."}?` : "";
27743
29612
  throw new CliError(
27744
29613
  `${depDir} holds no gateway-env.toml; the dependency must be a schema world (\`gateway worlds schema init\`)${hint}`,
27745
29614
  1
27746
29615
  );
27747
29616
  }
27748
29617
  if (path42.resolve(depDir) === dir) throw new CliError("A world cannot depend on itself");
27749
- const depToml = fs55.readFileSync(path42.join(depDir, "gateway-env.toml"), "utf8");
29618
+ const depToml = fs56.readFileSync(path42.join(depDir, "gateway-env.toml"), "utf8");
27750
29619
  if (declaredAliases(depToml).length)
27751
29620
  throw new CliError(`${depDir} has [dependencies] of its own (${declaredAliases(depToml).join(", ")}); links nest one level`);
27752
29621
  const task = arg.str(args, "task");
27753
- if (task !== void 0 && !fs55.existsSync(path42.join(depDir, "scenarios", task))) {
27754
- const have = fs55.existsSync(path42.join(depDir, "scenarios")) ? fs55.readdirSync(path42.join(depDir, "scenarios")) : [];
29622
+ if (task !== void 0 && !fs56.existsSync(path42.join(depDir, "scenarios", task))) {
29623
+ const have = fs56.existsSync(path42.join(depDir, "scenarios")) ? fs56.readdirSync(path42.join(depDir, "scenarios")) : [];
27755
29624
  throw new CliError(`${depDir} has no scenarios/${task}/ (have: ${have.join(", ") || "none"})`);
27756
29625
  }
27757
29626
  const rel = toPosix(path42.relative(dir, depDir)) || ".";
@@ -27764,7 +29633,7 @@ function registerScaffoldCommands(worlds) {
27764
29633
  entities: arg.list(args, "map").map(parseEntityMap)
27765
29634
  };
27766
29635
  const updated = addDependency(toml, spec, dependencyServes(depDir), { replace: arg.bool(args, "replace") });
27767
- fs55.writeFileSync(file, updated);
29636
+ fs56.writeFileSync(file, updated);
27768
29637
  ctx.stdout(
27769
29638
  JSON.stringify(
27770
29639
  {
@@ -27837,7 +29706,7 @@ function registerScaffoldCommands(worlds) {
27837
29706
  { verifiers: verifierNames2(dir), depVerifiers },
27838
29707
  { replace: arg.bool(args, "replace") }
27839
29708
  );
27840
- fs55.writeFileSync(file, updated);
29709
+ fs56.writeFileSync(file, updated);
27841
29710
  ctx.stdout(
27842
29711
  JSON.stringify(
27843
29712
  {
@@ -27904,7 +29773,7 @@ function registerScaffoldCommands(worlds) {
27904
29773
  run: async (args, ctx) => {
27905
29774
  const dir = path42.resolve(args.positionals[0]);
27906
29775
  const file = path42.join(dir, "connector.toml");
27907
- const created = !fs55.existsSync(file);
29776
+ const created = !fs56.existsSync(file);
27908
29777
  const routePath = arg.str(args, "path");
27909
29778
  if (routePath === void 0) throw new CliError("--path is required, e.g. --path /users");
27910
29779
  const spec = {
@@ -27927,13 +29796,13 @@ function registerScaffoldCommands(worlds) {
27927
29796
  }
27928
29797
  };
27929
29798
  const replace = arg.bool(args, "replace");
27930
- const current = created ? connectorTomlSkeleton(dir) : fs55.readFileSync(file, "utf8");
29799
+ const current = created ? connectorTomlSkeleton(dir) : fs56.readFileSync(file, "utf8");
27931
29800
  const updated = addRoute(current, spec, declaredEntities(dir), {
27932
29801
  replace,
27933
29802
  handlerTools: declaredHandlerTools(dir),
27934
29803
  entities: worldEntityShapes(dir)
27935
29804
  });
27936
- fs55.writeFileSync(file, updated);
29805
+ fs56.writeFileSync(file, updated);
27937
29806
  ctx.stdout(
27938
29807
  JSON.stringify(
27939
29808
  {
@@ -27979,13 +29848,13 @@ function registerRuntimeCommands(root) {
27979
29848
  }
27980
29849
 
27981
29850
  // src/cli/version.ts
27982
- import * as fs56 from "fs";
29851
+ import * as fs57 from "fs";
27983
29852
  import * as path43 from "path";
27984
29853
  function cliVersion() {
27985
- if (true) return "0.2.9";
29854
+ if (true) return "0.3.0";
27986
29855
  if (typeof __dirname !== "string") return "unknown";
27987
29856
  try {
27988
- const pkg = JSON.parse(fs56.readFileSync(path43.resolve(__dirname, "../../package.json"), "utf8"));
29857
+ const pkg = JSON.parse(fs57.readFileSync(path43.resolve(__dirname, "../../package.json"), "utf8"));
27989
29858
  return pkg.version ?? "unknown";
27990
29859
  } catch {
27991
29860
  return "unknown";