@withgateway/sdk 0.9.1 → 0.9.3

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 (84) hide show
  1. package/dist/agents/index.d.mts +12 -4
  2. package/dist/agents/index.d.ts +12 -4
  3. package/dist/agents/index.js +30 -0
  4. package/dist/agents/index.js.map +1 -1
  5. package/dist/agents/index.mjs +30 -0
  6. package/dist/agents/index.mjs.map +1 -1
  7. package/dist/cli.js +2291 -945
  8. package/dist/cli.js.map +1 -1
  9. package/dist/cli.mjs +2290 -944
  10. package/dist/cli.mjs.map +1 -1
  11. package/dist/files/index.js.map +1 -1
  12. package/dist/files/index.mjs.map +1 -1
  13. package/dist/index.js +325 -184
  14. package/dist/index.js.map +1 -1
  15. package/dist/index.mjs +324 -183
  16. package/dist/index.mjs.map +1 -1
  17. package/dist/traces/index.js.map +1 -1
  18. package/dist/traces/index.mjs.map +1 -1
  19. package/dist/tracing/index.js +1 -1
  20. package/dist/tracing/index.js.map +1 -1
  21. package/dist/tracing/index.mjs +1 -1
  22. package/dist/tracing/index.mjs.map +1 -1
  23. package/dist/worlds/index.d.mts +3 -1
  24. package/dist/worlds/index.d.ts +3 -1
  25. package/dist/worlds/index.js +178 -67
  26. package/dist/worlds/index.js.map +1 -1
  27. package/dist/worlds/index.mjs +177 -66
  28. package/dist/worlds/index.mjs.map +1 -1
  29. package/package.json +1 -1
  30. package/runtime/gatewaysdk/environment/bundle_manifest.py +297 -9
  31. package/runtime/gatewaysdk/environment/factory_documents.py +670 -0
  32. package/runtime/gatewaysdk/environment/factory_rules.py +973 -0
  33. package/runtime/gatewaysdk/environment/factory_shapes.py +253 -0
  34. package/runtime/gatewaysdk/environment/factory_spine.py +1155 -0
  35. package/runtime/gatewaysdk/environment/factory_spine_shapes.py +480 -0
  36. package/runtime/gatewaysdk/environment/schema/admission.py +61 -59
  37. package/runtime/gatewaysdk/environment/schema/cast.py +133 -67
  38. package/runtime/gatewaysdk/environment/schema/compiler.py +16 -17
  39. package/runtime/gatewaysdk/environment/schema/handler_errors.py +58 -4
  40. package/runtime/gatewaysdk/environment/schema/host.py +21 -2
  41. package/runtime/gatewaysdk/environment/schema/host_control.py +3 -1
  42. package/runtime/gatewaysdk/environment/schema/host_loops.py +27 -4
  43. package/runtime/gatewaysdk/environment/schema/host_metrics.py +69 -0
  44. package/runtime/gatewaysdk/environment/schema/host_requests.py +21 -0
  45. package/runtime/gatewaysdk/environment/schema/host_session.py +7 -0
  46. package/runtime/gatewaysdk/environment/schema/host_versions.py +4 -0
  47. package/runtime/gatewaysdk/environment/schema/host_workers.py +172 -50
  48. package/runtime/gatewaysdk/environment/schema/ingest.py +12 -3
  49. package/runtime/gatewaysdk/environment/schema/mapping.py +1 -1
  50. package/runtime/gatewaysdk/environment/schema/measured_tests.py +187 -0
  51. package/runtime/gatewaysdk/environment/schema/platform.py +57 -3
  52. package/runtime/gatewaysdk/environment/schema/platform_query.py +4 -3
  53. package/runtime/gatewaysdk/environment/schema/platform_templates.py +105 -17
  54. package/runtime/gatewaysdk/environment/schema/process_memory.py +76 -0
  55. package/runtime/gatewaysdk/environment/schema/redaction.py +13 -0
  56. package/runtime/gatewaysdk/environment/schema/runtime.py +14 -0
  57. package/runtime/gatewaysdk/environment/schema/scaffold.py +21 -4
  58. package/runtime/gatewaysdk/environment/schema/shape_catalog.py +493 -0
  59. package/runtime/gatewaysdk/environment/schema/shape_declarations.py +219 -0
  60. package/runtime/gatewaysdk/environment/schema/skill.py +1 -0
  61. package/runtime/gatewaysdk/environment/schema/skills/connector-schema-authoring/SKILL.md +1 -0
  62. package/runtime/gatewaysdk/environment/schema/skills/factory-orchestrator/SKILL.md +147 -0
  63. package/runtime/gatewaysdk/environment/schema/skills/world-data-ingestion/ROWS.md +5 -1
  64. package/runtime/gatewaysdk/environment/schema/skills/world-data-ingestion/SKILL.md +4 -4
  65. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/SKILL.md +2 -2
  66. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/cli-mcp-map.md +1 -0
  67. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/shape-catalog.md +59 -0
  68. package/runtime/gatewaysdk/environment/schema/validation.py +14 -0
  69. package/runtime/gatewaysdk/environment/schema/worker.py +7 -4
  70. package/runtime/gatewaysdk/environment/schema/worker_key.py +38 -0
  71. package/runtime/gatewaysdk/environment/schema/worker_peaks.py +38 -0
  72. package/runtime/gatewaysdk/environment/schema/worker_watch.py +50 -0
  73. package/runtime/gatewaysdk/environment/schema/workers.py +237 -68
  74. package/runtime/gatewaysdk/environment/schema/world_host.py +56 -62
  75. package/runtime/gatewaysdk/environment/schema/world_tests.py +3 -1
  76. package/skills/connector-schema-authoring/SKILL.md +1 -0
  77. package/skills/connector-schema-authoring/connector-worlds.md +1 -0
  78. package/skills/connector-schema-authoring/world-schema.md +7 -0
  79. package/skills/factory-orchestrator/SKILL.md +147 -0
  80. package/skills/world-data-ingestion/ROWS.md +5 -1
  81. package/skills/world-data-ingestion/SKILL.md +4 -4
  82. package/skills/worlds-getting-started/SKILL.md +2 -2
  83. package/skills/worlds-getting-started/references/cli-mcp-map.md +1 -0
  84. package/skills/worlds-getting-started/references/shape-catalog.md +59 -0
package/dist/index.mjs CHANGED
@@ -190,10 +190,10 @@ var init_users = __esm({
190
190
  totalItems: Number(meta.totalItems ?? rows.length)
191
191
  };
192
192
  }
193
- async requestJson(method, path17, payload) {
193
+ async requestJson(method, path18, payload) {
194
194
  let response;
195
195
  try {
196
- response = await fetch(`${this.host}${path17}`, {
196
+ response = await fetch(`${this.host}${path18}`, {
197
197
  method,
198
198
  headers: {
199
199
  Authorization: this.authHeader(),
@@ -204,17 +204,17 @@ var init_users = __esm({
204
204
  });
205
205
  } catch (error) {
206
206
  throw new UserProfileError(
207
- `${method} ${path17} failed: ${error instanceof Error ? error.message : String(error)}`,
207
+ `${method} ${path18} failed: ${error instanceof Error ? error.message : String(error)}`,
208
208
  { cause: error }
209
209
  );
210
210
  }
211
211
  const text2 = await response.text();
212
212
  if (!response.ok) {
213
213
  throw new UserProfileError(
214
- `${method} ${path17} failed (${response.status}): ${text2.slice(0, 500)}`
214
+ `${method} ${path18} failed (${response.status}): ${text2.slice(0, 500)}`
215
215
  );
216
216
  }
217
- this.log("%s %s -> %s", method, path17, response.status);
217
+ this.log("%s %s -> %s", method, path18, response.status);
218
218
  return safeJson4(text2);
219
219
  }
220
220
  authHeader() {
@@ -403,10 +403,10 @@ var init_scores = __esm({
403
403
  metadata: signalMetadata
404
404
  });
405
405
  }
406
- async request(method, path17, payload) {
406
+ async request(method, path18, payload) {
407
407
  let response;
408
408
  try {
409
- response = await fetch(`${this.host}${path17}`, {
409
+ response = await fetch(`${this.host}${path18}`, {
410
410
  method,
411
411
  headers: {
412
412
  Authorization: this.authHeader(),
@@ -417,17 +417,17 @@ var init_scores = __esm({
417
417
  });
418
418
  } catch (error) {
419
419
  throw new ScoreError(
420
- `${method} ${path17} failed: ${error instanceof Error ? error.message : String(error)}`,
420
+ `${method} ${path18} failed: ${error instanceof Error ? error.message : String(error)}`,
421
421
  { cause: error }
422
422
  );
423
423
  }
424
424
  const text2 = await response.text();
425
425
  if (!response.ok) {
426
426
  throw new ScoreError(
427
- `${method} ${path17} failed (${response.status}): ${text2.slice(0, 500)}`
427
+ `${method} ${path18} failed (${response.status}): ${text2.slice(0, 500)}`
428
428
  );
429
429
  }
430
- this.log("%s %s -> %s", method, path17, response.status);
430
+ this.log("%s %s -> %s", method, path18, response.status);
431
431
  }
432
432
  authHeader() {
433
433
  return `Basic ${Buffer.from(`${this.publicKey}:${this.secretKey}`).toString(
@@ -567,8 +567,8 @@ function invalidFields(error) {
567
567
  return issues.filter(
568
568
  (issue) => issue !== null && typeof issue === "object" && typeof issue.message === "string"
569
569
  ).map((issue) => {
570
- const path17 = Array.isArray(issue.path) ? issue.path.map(String).join(".") : "";
571
- return path17 ? `${path17}: ${issue.message}` : issue.message;
570
+ const path18 = Array.isArray(issue.path) ? issue.path.map(String).join(".") : "";
571
+ return path18 ? `${path18}: ${issue.message}` : issue.message;
572
572
  }).join("; ");
573
573
  }
574
574
  var ApiError, DETAIL_LIMIT, EDGE_ANSWERS, EDGE_FAILURE, EDGE_PAGE;
@@ -576,9 +576,9 @@ var init_apiError = __esm({
576
576
  "src/worlds/apiError.ts"() {
577
577
  "use strict";
578
578
  ApiError = class extends Error {
579
- constructor(status, method, path17, text2) {
579
+ constructor(status, method, path18, text2) {
580
580
  const parsed = parseErrorBody(text2, status);
581
- super(`${method} ${path17} -> ${status}: ${parsed.detail}`);
581
+ super(`${method} ${path18} -> ${status}: ${parsed.detail}`);
582
582
  this.status = status;
583
583
  this.text = text2;
584
584
  this.name = "ApiError";
@@ -1214,9 +1214,9 @@ function surfaceKinds(s) {
1214
1214
  if (s.browser) kinds.push("browser");
1215
1215
  return kinds;
1216
1216
  }
1217
- function uiUrl(ui, path17) {
1217
+ function uiUrl(ui, path18) {
1218
1218
  const base = ui.url.replace(/\/+$/, "");
1219
- const rel = path17.startsWith("/") ? path17 : `/${path17}`;
1219
+ const rel = path18.startsWith("/") ? path18 : `/${path18}`;
1220
1220
  if (!ui.token) return base + rel;
1221
1221
  const [beforeHash, hash] = splitHash(rel);
1222
1222
  const joiner = beforeHash.includes("?") ? "&" : "?";
@@ -2634,13 +2634,13 @@ var init_screen = __esm({
2634
2634
  });
2635
2635
  }
2636
2636
  async drag(action) {
2637
- const path17 = action.args.path ?? [];
2638
- if (path17.length < 2) throw new Error("a drag needs at least two points");
2637
+ const path18 = action.args.path ?? [];
2638
+ if (path18.length < 2) throw new Error("a drag needs at least two points");
2639
2639
  return this.held(action.args.modifiers ?? [], async () => {
2640
- await this.moveTo(path17[0]);
2640
+ await this.moveTo(path18[0]);
2641
2641
  await this.page.mouse.down({ button: "left" });
2642
2642
  try {
2643
- for (const point2 of path17.slice(1)) await this.moveTo(point2, DRAG_STEPS);
2643
+ for (const point2 of path18.slice(1)) await this.moveTo(point2, DRAG_STEPS);
2644
2644
  } finally {
2645
2645
  await this.page.mouse.up({ button: "left" });
2646
2646
  }
@@ -4474,17 +4474,17 @@ var init_session2 = __esm({
4474
4474
  }
4475
4475
  /** The reporter `browser()` uses; exposed for a page you drive yourself. */
4476
4476
  browserRecorder(agentId) {
4477
- const path17 = `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/browser-events`;
4477
+ const path18 = `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/browser-events`;
4478
4478
  const id = agentId ?? process.env.GATEWAY_AGENT_ID ?? `agent-${randomUUID().replace(/-/g, "").slice(0, 8)}`;
4479
4479
  return new BrowserActionRecorder(
4480
4480
  async (events) => {
4481
- await apiRequest(this.options, "POST", path17, { events });
4481
+ await apiRequest(this.options, "POST", path18, { events });
4482
4482
  },
4483
4483
  id,
4484
4484
  {
4485
4485
  // Continue this agent's timeline where the platform has it, so a reopened id never re-numbers from zero.
4486
4486
  resumeFrom: async () => {
4487
- const summary = await apiRequest(this.options, "GET", path17);
4487
+ const summary = await apiRequest(this.options, "GET", path18);
4488
4488
  return summary.agents.find((a) => a.agentId === id)?.nextSeq ?? 0;
4489
4489
  }
4490
4490
  }
@@ -5437,8 +5437,8 @@ var init_taskRunDir = __esm({
5437
5437
  "use strict";
5438
5438
  init_browser();
5439
5439
  TaskRunDir = class {
5440
- constructor(path17) {
5441
- this.path = path17;
5440
+ constructor(path18) {
5441
+ this.path = path18;
5442
5442
  }
5443
5443
  path;
5444
5444
  writeManifest(manifest) {
@@ -5975,7 +5975,7 @@ var require_package = __commonJS({
5975
5975
  "package.json"(exports, module) {
5976
5976
  module.exports = {
5977
5977
  name: "@withgateway/sdk",
5978
- version: "0.9.1",
5978
+ version: "0.9.3",
5979
5979
  description: "Gateway SDK for TypeScript - A/B experiments, tracing, and observability",
5980
5980
  main: "./dist/index.js",
5981
5981
  module: "./dist/index.mjs",
@@ -8446,7 +8446,7 @@ function rebaseConflicts(error) {
8446
8446
  }
8447
8447
  const conflicts = body?.conflicts;
8448
8448
  if (!Array.isArray(conflicts)) return null;
8449
- return conflicts.filter(isConflictPath).map(({ path: path17, reason }) => ({ path: path17, reason }));
8449
+ return conflicts.filter(isConflictPath).map(({ path: path18, reason }) => ({ path: path18, reason }));
8450
8450
  }
8451
8451
  function isConflictPath(value) {
8452
8452
  const entry = value;
@@ -8570,8 +8570,8 @@ var init_sandbox = __esm({
8570
8570
  this.options = options;
8571
8571
  }
8572
8572
  options;
8573
- request(method, path17, body) {
8574
- return apiRequest(this.options, method, path17, body, {
8573
+ request(method, path18, body) {
8574
+ return apiRequest(this.options, method, path18, body, {
8575
8575
  timeoutMs: SANDBOX_REQUEST_TIMEOUT_MS
8576
8576
  });
8577
8577
  }
@@ -8701,13 +8701,16 @@ var init_sandbox = __esm({
8701
8701
  });
8702
8702
 
8703
8703
  // src/worlds/describe.ts
8704
- async function describeWorld(slugRef, options = {}) {
8704
+ async function describeWorld(slugRef, options = {}, entity) {
8705
8705
  const { slug, ref } = parseSlugRef(slugRef);
8706
- const query = ref === void 0 ? "" : `?ref=${encodeURIComponent(ref)}`;
8706
+ const query = new URLSearchParams();
8707
+ if (ref !== void 0) query.set("ref", ref);
8708
+ if (entity !== void 0) query.set("entity", entity);
8709
+ const search = query.toString() ? `?${query}` : "";
8707
8710
  return apiRequest(
8708
8711
  options,
8709
8712
  "GET",
8710
- `/api/public/worlds/${encodeURIComponent(slug)}${query}`
8713
+ `/api/public/worlds/${encodeURIComponent(slug)}${search}`
8711
8714
  );
8712
8715
  }
8713
8716
  var init_describe = __esm({
@@ -9629,8 +9632,8 @@ runpy.run_module('gatewaysdk.environment.schema',run_name='__main__')`;
9629
9632
  });
9630
9633
 
9631
9634
  // src/worlds/databaseEngines.ts
9632
- function isWorldSnapshotOutput(path17) {
9633
- return SNAPSHOT_OUTPUTS.has(path17.slice(path17.lastIndexOf("/") + 1));
9635
+ function isWorldSnapshotOutput(path18) {
9636
+ return SNAPSHOT_OUTPUTS.has(path18.slice(path18.lastIndexOf("/") + 1));
9634
9637
  }
9635
9638
  var WORLD_DATABASE_ENGINES, DEFAULT_WORLD_DATABASE_ENGINE, WORLD_SNAPSHOT_FILE_PATH, WORLD_SNAPSHOT_SIDECAR_PATH, WORLD_SNAPSHOT_CONTENT_TYPE, SNAPSHOT_OUTPUTS;
9636
9639
  var init_databaseEngines = __esm({
@@ -10238,9 +10241,83 @@ if (fn) {
10238
10241
  }
10239
10242
  });
10240
10243
 
10244
+ // src/cli/platform/worldData/manifest.ts
10245
+ import * as fs11 from "fs";
10246
+ import * as path12 from "path";
10247
+ function recordChunk(manifest, chunk) {
10248
+ manifest.chunks = [...manifest.chunks.filter((c) => c.ordinal !== chunk.ordinal), chunk].sort((a, b) => a.ordinal - b.ordinal);
10249
+ }
10250
+ function uploadedEntry(manifest, ordinal, digest) {
10251
+ return manifest.chunks.find((c) => c.ordinal === ordinal && c.digest === digest && c.uploaded) ?? null;
10252
+ }
10253
+ var STEM, MANIFEST_DIR, stamp, sameInputs, ManifestShelf, IMPORT_MANIFESTS;
10254
+ var init_manifest = __esm({
10255
+ "src/cli/platform/worldData/manifest.ts"() {
10256
+ "use strict";
10257
+ init_router();
10258
+ STEM = /^[A-Za-z0-9_-]+$/;
10259
+ MANIFEST_DIR = path12.join(".gateway", "imports");
10260
+ stamp = () => (/* @__PURE__ */ new Date()).toISOString().replace(/\.\d{3}Z$/, "Z");
10261
+ sameInputs = (a, b) => a.length === b.length && a.every((x, i) => x === b[i]);
10262
+ ManifestShelf = class {
10263
+ constructor(dir, stem) {
10264
+ this.dir = dir;
10265
+ this.stem = stem;
10266
+ }
10267
+ dir;
10268
+ stem;
10269
+ dirIn(cwd = process.cwd()) {
10270
+ return path12.join(cwd, this.dir);
10271
+ }
10272
+ file(stem, cwd) {
10273
+ if (!STEM.test(stem)) throw new CliError(`Not a manifest name: ${stem}`);
10274
+ return path12.join(this.dirIn(cwd), `${stem}.json`);
10275
+ }
10276
+ // .gateway/ ignores itself so a manifest, which names hosts and inputs, never enters a repository.
10277
+ write(manifest, cwd = process.cwd()) {
10278
+ const file = this.file(this.stem(manifest), cwd);
10279
+ fs11.mkdirSync(path12.dirname(file), { recursive: true });
10280
+ const ignore = path12.join(cwd, ".gateway", ".gitignore");
10281
+ if (!fs11.existsSync(ignore)) fs11.writeFileSync(ignore, "*\n");
10282
+ manifest.updatedAt = stamp();
10283
+ const tmp = `${file}.tmp`;
10284
+ fs11.writeFileSync(tmp, JSON.stringify(manifest, null, 1) + "\n");
10285
+ fs11.renameSync(tmp, file);
10286
+ return file;
10287
+ }
10288
+ record(manifest, chunk, cwd = process.cwd()) {
10289
+ recordChunk(manifest, chunk);
10290
+ this.write(manifest, cwd);
10291
+ }
10292
+ read(stem, cwd = process.cwd()) {
10293
+ try {
10294
+ const parsed = JSON.parse(fs11.readFileSync(this.file(stem, cwd), "utf8"));
10295
+ return parsed && parsed.version === 1 && this.stem(parsed) === stem ? parsed : null;
10296
+ } catch {
10297
+ return null;
10298
+ }
10299
+ }
10300
+ list(cwd = process.cwd()) {
10301
+ const dir = this.dirIn(cwd);
10302
+ if (!fs11.existsSync(dir)) return [];
10303
+ const out = [];
10304
+ for (const name of fs11.readdirSync(dir)) {
10305
+ const manifest = name.endsWith(".json") ? this.read(name.slice(0, -5), cwd) : null;
10306
+ if (manifest) out.push(manifest);
10307
+ }
10308
+ return out.sort((a, b) => Number(a.updatedAt < b.updatedAt) - Number(a.updatedAt > b.updatedAt));
10309
+ }
10310
+ resumable(slug, inputs, cwd = process.cwd()) {
10311
+ return this.list(cwd).find((m) => !m.completed && m.slug === slug && sameInputs(m.inputs, inputs)) ?? null;
10312
+ }
10313
+ };
10314
+ IMPORT_MANIFESTS = new ManifestShelf(MANIFEST_DIR, (key2) => key2.batchId);
10315
+ }
10316
+ });
10317
+
10241
10318
  // src/cli/platform/worldData/batches.ts
10242
10319
  import { createHash as createHash9 } from "crypto";
10243
- import * as fs11 from "fs";
10320
+ import * as fs12 from "fs";
10244
10321
  function isSettled(status) {
10245
10322
  if (!TERMINAL_STATES.has(status.state)) return false;
10246
10323
  if (status.state !== "applied") return true;
@@ -10302,12 +10379,14 @@ function phaseLine(status) {
10302
10379
  const phase = status.progress?.phase;
10303
10380
  return phase ? `${status.state} (${phase})` : status.state;
10304
10381
  }
10305
- var TERMINAL_STATES, sleepMs, WorldDataApi;
10382
+ var CHUNK_PARALLEL, TERMINAL_STATES, sleepMs, WorldDataApi, ChunkUploader;
10306
10383
  var init_batches = __esm({
10307
10384
  "src/cli/platform/worldData/batches.ts"() {
10308
10385
  "use strict";
10309
10386
  init_config();
10310
10387
  init_router();
10388
+ init_manifest();
10389
+ CHUNK_PARALLEL = 4;
10311
10390
  TERMINAL_STATES = /* @__PURE__ */ new Set([
10312
10391
  "applied",
10313
10392
  "refused",
@@ -10334,13 +10413,7 @@ var init_batches = __esm({
10334
10413
  this.creds,
10335
10414
  "POST",
10336
10415
  `${this.base}/batches/${batchId}/chunks`,
10337
- {
10338
- ordinal: chunk.ordinal,
10339
- digest: chunk.digest,
10340
- bytes: chunk.bytes,
10341
- rows: chunk.rows,
10342
- ...chunk.entity ? { entity: chunk.entity } : {}
10343
- }
10416
+ chunk
10344
10417
  );
10345
10418
  }
10346
10419
  async stageDrive(batchId, chunk) {
@@ -10396,6 +10469,23 @@ var init_batches = __esm({
10396
10469
  message ? { message } : {}
10397
10470
  );
10398
10471
  }
10472
+ chunks(batchId) {
10473
+ return new ChunkUploader(
10474
+ {
10475
+ register: (chunk) => this.register(batchId, chunk),
10476
+ uploaded: (chunkId) => this.markUploaded(batchId, chunkId)
10477
+ },
10478
+ this.sleep
10479
+ );
10480
+ }
10481
+ };
10482
+ ChunkUploader = class {
10483
+ constructor(door, sleep5 = sleepMs) {
10484
+ this.door = door;
10485
+ this.sleep = sleep5;
10486
+ }
10487
+ door;
10488
+ sleep;
10399
10489
  async put(uploadUrl, gz, signed) {
10400
10490
  const headers = signed ?? uploadHeadersFor(gz);
10401
10491
  const delays = [500, 1500, 4e3];
@@ -10422,17 +10512,15 @@ var init_batches = __esm({
10422
10512
  await this.sleep(delays[attempt]);
10423
10513
  }
10424
10514
  }
10425
- async upload(batchId, chunk) {
10426
- const registered = await this.register(batchId, chunk);
10427
- if (!registered.uploaded) {
10428
- if (!registered.uploadUrl)
10429
- throw new CliError(
10430
- `the server registered chunk ${chunk.ordinal} without an upload URL`,
10431
- 1
10432
- );
10433
- await this.put(registered.uploadUrl, chunk.gz, registered.uploadHeaders);
10434
- await this.markUploaded(batchId, registered.chunkId);
10435
- }
10515
+ async upload(chunk) {
10516
+ const registered = await this.door.register({
10517
+ ordinal: chunk.ordinal,
10518
+ digest: chunk.digest,
10519
+ bytes: chunk.bytes,
10520
+ rows: chunk.rows,
10521
+ ...chunk.entity ? { entity: chunk.entity } : {}
10522
+ });
10523
+ if (!registered.uploaded) await this.send(chunk, registered);
10436
10524
  return {
10437
10525
  ordinal: chunk.ordinal,
10438
10526
  digest: chunk.digest,
@@ -10443,6 +10531,28 @@ var init_batches = __esm({
10443
10531
  uploaded: true
10444
10532
  };
10445
10533
  }
10534
+ async send(chunk, registered) {
10535
+ if (!registered.uploadUrl)
10536
+ throw new CliError(
10537
+ `the server registered chunk ${chunk.ordinal} without an upload URL`,
10538
+ 1
10539
+ );
10540
+ await this.put(registered.uploadUrl, chunk.gz, registered.uploadHeaders);
10541
+ await this.door.uploaded(registered.chunkId);
10542
+ }
10543
+ async uploadAll(chunks, kept, parallel, progress) {
10544
+ await forEachLimited(chunks, parallel, async (chunk) => {
10545
+ if (uploadedEntry(kept.manifest, chunk.ordinal, chunk.digest)) {
10546
+ progress(`chunk ${chunk.ordinal}: already uploaded (${chunk.rows} rows)`);
10547
+ return;
10548
+ }
10549
+ const entry = await this.upload(chunk);
10550
+ kept.shelf.record(kept.manifest, entry);
10551
+ progress(
10552
+ `chunk ${chunk.ordinal}: uploaded ${chunk.rows} rows, ${chunk.bytes} bytes (${entry.chunkId})`
10553
+ );
10554
+ });
10555
+ }
10446
10556
  };
10447
10557
  }
10448
10558
  });
@@ -10578,11 +10688,12 @@ async function pushRows(creds, slug, rows, opts = {}) {
10578
10688
  chunkRows: null,
10579
10689
  entity: null
10580
10690
  });
10691
+ const uploader = client2.chunks(opened.batchId);
10581
10692
  await forEachLimited(
10582
10693
  chunks,
10583
- Math.max(1, opts.parallel ?? 4),
10694
+ Math.max(1, opts.parallel ?? CHUNK_PARALLEL),
10584
10695
  async (chunk) => {
10585
- await client2.upload(opened.batchId, chunk);
10696
+ await uploader.upload(chunk);
10586
10697
  }
10587
10698
  );
10588
10699
  await client2.complete(opened.batchId);
@@ -10600,9 +10711,9 @@ var init_push = __esm({
10600
10711
  });
10601
10712
 
10602
10713
  // src/worlds/ingest.ts
10603
- import * as fs12 from "fs";
10714
+ import * as fs13 from "fs";
10604
10715
  import * as os3 from "os";
10605
- import * as path12 from "path";
10716
+ import * as path13 from "path";
10606
10717
  function parseToolCallRecord(raw) {
10607
10718
  const none = { record: null, skip: null };
10608
10719
  if (!isObject2(raw)) return { ...none, refusal: "record is not an object" };
@@ -10623,7 +10734,7 @@ function parseToolCallRecord(raw) {
10623
10734
  }
10624
10735
  function readToolCallRecords(paths) {
10625
10736
  const records = [];
10626
- for (const file of paths) records.push(...toolCallRecordsIn(fs12.readFileSync(file, "utf8"), file));
10737
+ for (const file of paths) records.push(...toolCallRecordsIn(fs13.readFileSync(file, "utf8"), file));
10627
10738
  return records;
10628
10739
  }
10629
10740
  function toolCallRecordsIn(text2, where) {
@@ -10659,7 +10770,7 @@ async function emit(sink, record) {
10659
10770
  return;
10660
10771
  }
10661
10772
  if (typeof sink === "string") {
10662
- fs12.appendFileSync(sink, JSON.stringify(record) + "\n");
10773
+ fs13.appendFileSync(sink, JSON.stringify(record) + "\n");
10663
10774
  return;
10664
10775
  }
10665
10776
  if (typeof sink === "function") {
@@ -10741,7 +10852,7 @@ async function ingest(world, records, options = {}) {
10741
10852
  const redact = options.redact ?? "off";
10742
10853
  const mode = options.mode ?? "append";
10743
10854
  const dryRun = Boolean(options.dryRun);
10744
- const local = fs12.existsSync(world) && fs12.statSync(world).isDirectory();
10855
+ const local = fs13.existsSync(world) && fs13.statSync(world).isDirectory();
10745
10856
  const creds = local ? await runtimeEndpoint(options) : platformEndpoint(options);
10746
10857
  const map = options.map === void 0 ? void 0 : options.map;
10747
10858
  let rows = null;
@@ -10758,9 +10869,9 @@ async function ingest(world, records, options = {}) {
10758
10869
  if (!creds) throw new Error(GATEWAY_KEYS_MISSING);
10759
10870
  const { pull: pull2 } = await Promise.resolve().then(() => (init_hub(), hub_exports));
10760
10871
  const slug = world.split("@", 1)[0];
10761
- const scratch = fs12.mkdtempSync(path12.join(os3.tmpdir(), "gateway-ingest-"));
10872
+ const scratch = fs13.mkdtempSync(path13.join(os3.tmpdir(), "gateway-ingest-"));
10762
10873
  try {
10763
- const pulled = await pull2(world, path12.join(scratch, slug), options);
10874
+ const pulled = await pull2(world, path13.join(scratch, slug), options);
10764
10875
  let report;
10765
10876
  let projected;
10766
10877
  if (rows === null) {
@@ -10781,7 +10892,7 @@ async function ingest(world, records, options = {}) {
10781
10892
  if (status.entityCounts) report.entityCounts = status.entityCounts;
10782
10893
  return report;
10783
10894
  } finally {
10784
- fs12.rmSync(scratch, { recursive: true, force: true });
10895
+ fs13.rmSync(scratch, { recursive: true, force: true });
10785
10896
  }
10786
10897
  }
10787
10898
  async function ingestToolCalls(world, records, options = {}) {
@@ -11246,8 +11357,8 @@ __export(worlds_exports, {
11246
11357
  worldRequestsUnrecorded: () => worldRequestsUnrecorded,
11247
11358
  writeLocalMeta: () => writeLocalMeta
11248
11359
  });
11249
- async function apiRequest(options, method, path17, body, init3 = {}) {
11250
- return new PlatformTransport(requirePlatformEndpoint(options)).json(method, path17, body, init3);
11360
+ async function apiRequest(options, method, path18, body, init3 = {}) {
11361
+ return new PlatformTransport(requirePlatformEndpoint(options)).json(method, path18, body, init3);
11251
11362
  }
11252
11363
  async function setEnvSecret(slug, key2, value, options = {}) {
11253
11364
  return apiRequest(
@@ -12100,8 +12211,8 @@ var GatewayContext = class _GatewayContext {
12100
12211
  }
12101
12212
  return resolved;
12102
12213
  }
12103
- async requestJson(method, path17, payload) {
12104
- const response = await fetch(`${this.host}${path17}`, {
12214
+ async requestJson(method, path18, payload) {
12215
+ const response = await fetch(`${this.host}${path18}`, {
12105
12216
  method,
12106
12217
  headers: {
12107
12218
  Authorization: this.authHeader(),
@@ -12112,7 +12223,7 @@ var GatewayContext = class _GatewayContext {
12112
12223
  const text2 = await response.text();
12113
12224
  const body = text2 ? safeJson(text2) : {};
12114
12225
  if (!response.ok) {
12115
- const message = typeof body.message === "string" ? body.message : `Gateway API ${response.status} on ${path17}`;
12226
+ const message = typeof body.message === "string" ? body.message : `Gateway API ${response.status} on ${path18}`;
12116
12227
  if (response.status === 409) {
12117
12228
  throw new GatewayContextConflictError(
12118
12229
  message,
@@ -12121,7 +12232,7 @@ var GatewayContext = class _GatewayContext {
12121
12232
  }
12122
12233
  throw new GatewayContextError(message);
12123
12234
  }
12124
- this.log("%s %s -> %s", method, path17, response.status);
12235
+ this.log("%s %s -> %s", method, path18, response.status);
12125
12236
  return body;
12126
12237
  }
12127
12238
  authHeader() {
@@ -12228,11 +12339,11 @@ function primaryPathForKind(kind, snapshot) {
12228
12339
  const preferred = kind === "agent" ? "AGENTS.md" : kind === "prompt" ? "PROMPT.md" : kind === "skill" ? "SKILL.md" : "MEMORY.md";
12229
12340
  if (readFile(snapshot, preferred)) return preferred;
12230
12341
  return Object.entries(snapshot.files).find(
12231
- ([path17, entry]) => entry.type === "file" && path17.endsWith(".md")
12342
+ ([path18, entry]) => entry.type === "file" && path18.endsWith(".md")
12232
12343
  )?.[0] ?? null;
12233
12344
  }
12234
- function parseJsonFile(snapshot, path17) {
12235
- const content = readFile(snapshot, path17);
12345
+ function parseJsonFile(snapshot, path18) {
12346
+ const content = readFile(snapshot, path18);
12236
12347
  if (!content) return {};
12237
12348
  try {
12238
12349
  const parsed = JSON.parse(content);
@@ -12241,8 +12352,8 @@ function parseJsonFile(snapshot, path17) {
12241
12352
  return {};
12242
12353
  }
12243
12354
  }
12244
- function readFile(snapshot, path17) {
12245
- const entry = snapshot.files[path17];
12355
+ function readFile(snapshot, path18) {
12356
+ const entry = snapshot.files[path18];
12246
12357
  return entry?.type === "file" ? entry.content : null;
12247
12358
  }
12248
12359
  function provenanceFor(snapshot, label) {
@@ -12344,16 +12455,16 @@ var GatewayMemory = class _GatewayMemory {
12344
12455
  `/api/public/context/memory/${encodeIdentifier2(identifier)}${suffix}`
12345
12456
  );
12346
12457
  }
12347
- async read(target, path17, options = {}) {
12458
+ async read(target, path18, options = {}) {
12348
12459
  const snapshot = typeof target === "string" ? await this.pull(target, options) : target;
12349
- const file = snapshot.files[path17];
12460
+ const file = snapshot.files[path18];
12350
12461
  return file?.type === "file" ? file.content : null;
12351
12462
  }
12352
- async write(target, path17, content, options = {}) {
12463
+ async write(target, path18, content, options = {}) {
12353
12464
  const snapshot = typeof target === "string" ? await this.pull(target) : target;
12354
12465
  return this.push(snapshot.repo.repoHandle, {
12355
12466
  files: {
12356
- [path17]: {
12467
+ [path18]: {
12357
12468
  content,
12358
12469
  ...options.mimeType ? { mimeType: options.mimeType } : {}
12359
12470
  }
@@ -12363,10 +12474,10 @@ var GatewayMemory = class _GatewayMemory {
12363
12474
  ...runtimeContextPayload2(options)
12364
12475
  });
12365
12476
  }
12366
- async delete(target, path17, options = {}) {
12477
+ async delete(target, path18, options = {}) {
12367
12478
  const snapshot = typeof target === "string" ? await this.pull(target) : target;
12368
12479
  return this.push(snapshot.repo.repoHandle, {
12369
- files: { [path17]: null },
12480
+ files: { [path18]: null },
12370
12481
  parentCommit: options.parentCommit ?? snapshot.commit.commitHash,
12371
12482
  message: options.message,
12372
12483
  ...runtimeContextPayload2(options)
@@ -12379,8 +12490,8 @@ var GatewayMemory = class _GatewayMemory {
12379
12490
  payload
12380
12491
  );
12381
12492
  }
12382
- async requestJson(method, path17, payload) {
12383
- const response = await fetch(`${this.host}${path17}`, {
12493
+ async requestJson(method, path18, payload) {
12494
+ const response = await fetch(`${this.host}${path18}`, {
12384
12495
  method,
12385
12496
  headers: {
12386
12497
  Authorization: this.authHeader(),
@@ -12391,7 +12502,7 @@ var GatewayMemory = class _GatewayMemory {
12391
12502
  const text2 = await response.text();
12392
12503
  const body = text2 ? safeJson2(text2) : {};
12393
12504
  if (!response.ok) {
12394
- const message = typeof body.message === "string" ? body.message : `Gateway API ${response.status} on ${path17}`;
12505
+ const message = typeof body.message === "string" ? body.message : `Gateway API ${response.status} on ${path18}`;
12395
12506
  if (response.status === 409) {
12396
12507
  throw new GatewayMemoryConflictError(
12397
12508
  message,
@@ -12400,7 +12511,7 @@ var GatewayMemory = class _GatewayMemory {
12400
12511
  }
12401
12512
  throw new GatewayMemoryError(message);
12402
12513
  }
12403
- this.log("%s %s -> %s", method, path17, response.status);
12514
+ this.log("%s %s -> %s", method, path18, response.status);
12404
12515
  return body;
12405
12516
  }
12406
12517
  authHeader() {
@@ -12562,10 +12673,10 @@ var PersonasClient = class _PersonasClient {
12562
12673
  done: Boolean(payload.done)
12563
12674
  };
12564
12675
  }
12565
- async requestJson(method, path17, payload) {
12676
+ async requestJson(method, path18, payload) {
12566
12677
  let response;
12567
12678
  try {
12568
- response = await fetch(`${this.host}${path17}`, {
12679
+ response = await fetch(`${this.host}${path18}`, {
12569
12680
  method,
12570
12681
  headers: {
12571
12682
  Authorization: this.authHeader(),
@@ -12576,7 +12687,7 @@ var PersonasClient = class _PersonasClient {
12576
12687
  });
12577
12688
  } catch (error) {
12578
12689
  const reason = error instanceof Error ? error.message : String(error);
12579
- throw new PersonaError(`${method} ${path17} failed: ${reason}`, {
12690
+ throw new PersonaError(`${method} ${path18} failed: ${reason}`, {
12580
12691
  cause: error
12581
12692
  });
12582
12693
  }
@@ -12584,10 +12695,10 @@ var PersonasClient = class _PersonasClient {
12584
12695
  if (!response.ok) {
12585
12696
  const detail = text2.slice(0, 500);
12586
12697
  throw new PersonaError(
12587
- `${method} ${path17} failed (${response.status}): ${detail}`
12698
+ `${method} ${path18} failed (${response.status}): ${detail}`
12588
12699
  );
12589
12700
  }
12590
- this.log("%s %s -> %s", method, path17, response.status);
12701
+ this.log("%s %s -> %s", method, path18, response.status);
12591
12702
  return safeJson3(text2);
12592
12703
  }
12593
12704
  authHeader() {
@@ -12812,10 +12923,10 @@ var SessionRecording = class _SessionRecording {
12812
12923
  };
12813
12924
  }
12814
12925
  /** Dump the full session as a JSON fixture (for regression tests). */
12815
- toFixture(path17) {
12816
- mkdirSync(dirname(path17), { recursive: true });
12817
- writeFileSync(path17, JSON.stringify(this.toJSON(), null, 2), "utf-8");
12818
- return path17;
12926
+ toFixture(path18) {
12927
+ mkdirSync(dirname(path18), { recursive: true });
12928
+ writeFileSync(path18, JSON.stringify(this.toJSON(), null, 2), "utf-8");
12929
+ return path18;
12819
12930
  }
12820
12931
  static fromApi(raw) {
12821
12932
  return new _SessionRecording({
@@ -13846,8 +13957,8 @@ var GatewaySecurity = class _GatewaySecurity {
13846
13957
  );
13847
13958
  }
13848
13959
  }
13849
- async postJson(path17, payload) {
13850
- const response = await fetch(`${this.host}${path17}`, {
13960
+ async postJson(path18, payload) {
13961
+ const response = await fetch(`${this.host}${path18}`, {
13851
13962
  method: "POST",
13852
13963
  headers: {
13853
13964
  Authorization: this.authHeader(),
@@ -13858,7 +13969,7 @@ var GatewaySecurity = class _GatewaySecurity {
13858
13969
  if (!response.ok) {
13859
13970
  const body = await response.text();
13860
13971
  throw new GatewaySecurityError(
13861
- `Gateway API ${response.status} on ${path17}: ${body || response.statusText}`
13972
+ `Gateway API ${response.status} on ${path18}: ${body || response.statusText}`
13862
13973
  );
13863
13974
  }
13864
13975
  return await response.json();
@@ -13956,8 +14067,8 @@ var AgentPatch = class _AgentPatch {
13956
14067
  // src/agents/agent.ts
13957
14068
  var AgentVersionConflictError = class extends ApiError {
13958
14069
  currentVersionId;
13959
- constructor(status, method, path17, text2) {
13960
- super(status, method, path17, text2);
14070
+ constructor(status, method, path18, text2) {
14071
+ super(status, method, path18, text2);
13961
14072
  this.name = "AgentVersionConflictError";
13962
14073
  this.currentVersionId = currentVersionOf(text2);
13963
14074
  }
@@ -14127,8 +14238,8 @@ function freezeGrant(grant2) {
14127
14238
  const only = grant2.only ? { only: Object.freeze([...grant2.only]) } : {};
14128
14239
  return Object.freeze({ server: grant2.server, ...only });
14129
14240
  }
14130
- function pathText(path17) {
14131
- return path17.length === 0 ? "definition" : path17.join(".");
14241
+ function pathText(path18) {
14242
+ return path18.length === 0 ? "definition" : path18.join(".");
14132
14243
  }
14133
14244
  function isRecord2(value) {
14134
14245
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -14187,38 +14298,38 @@ var DefinitionReader = class _DefinitionReader {
14187
14298
  );
14188
14299
  return grants.filter((grant2) => grant2 !== null);
14189
14300
  }
14190
- grant(entry, path17) {
14301
+ grant(entry, path18) {
14191
14302
  if (typeof entry === "string") return { server: entry };
14192
- if (!isRecord2(entry)) return this.refuse(path17, "invalid_type", "a server name or { server, only }", null);
14193
- this.unknownFields(entry, GRANT_FIELDS, path17);
14194
- const server = this.string(entry.server, [...path17, "server"]);
14303
+ if (!isRecord2(entry)) return this.refuse(path18, "invalid_type", "a server name or { server, only }", null);
14304
+ this.unknownFields(entry, GRANT_FIELDS, path18);
14305
+ const server = this.string(entry.server, [...path18, "server"]);
14195
14306
  if (server === null) return null;
14196
- return entry.only === void 0 ? { server } : { server, only: this.only(entry.only, [...path17, "only"]) };
14307
+ return entry.only === void 0 ? { server } : { server, only: this.only(entry.only, [...path18, "only"]) };
14197
14308
  }
14198
- only(value, path17) {
14199
- if (!Array.isArray(value)) return this.refuse(path17, "invalid_type", "a list of tool names", []);
14309
+ only(value, path18) {
14310
+ if (!Array.isArray(value)) return this.refuse(path18, "invalid_type", "a list of tool names", []);
14200
14311
  if (value.length === 0)
14201
- this.issue(path17, "too_small", "names at least one tool; leave `only` out to grant the whole server");
14202
- const names = value.map((name, index2) => this.string(name, [...path17, index2]));
14203
- this.noRepeats(names, (index2) => [...path17, index2], "duplicate_tool", "this tool is already named");
14312
+ this.issue(path18, "too_small", "names at least one tool; leave `only` out to grant the whole server");
14313
+ const names = value.map((name, index2) => this.string(name, [...path18, index2]));
14314
+ this.noRepeats(names, (index2) => [...path18, index2], "duplicate_tool", "this tool is already named");
14204
14315
  return names.filter(isString).sort();
14205
14316
  }
14206
- string(value, path17) {
14317
+ string(value, path18) {
14207
14318
  if (typeof value === "string") return value;
14208
- return this.refuse(path17, "invalid_type", "a string", null);
14319
+ return this.refuse(path18, "invalid_type", "a string", null);
14209
14320
  }
14210
- optionalString(value, path17) {
14321
+ optionalString(value, path18) {
14211
14322
  if (value === void 0) return void 0;
14212
- return this.string(value, path17) ?? void 0;
14323
+ return this.string(value, path18) ?? void 0;
14213
14324
  }
14214
- bounded(value, bounds, path17, unit) {
14215
- if (value < bounds.min) this.issue(path17, "too_small", `at least ${bounds.min} ${unit}`);
14216
- if (value > bounds.max) this.issue(path17, "too_large", `at most ${bounds.max} ${unit}`);
14325
+ bounded(value, bounds, path18, unit) {
14326
+ if (value < bounds.min) this.issue(path18, "too_small", `at least ${bounds.min} ${unit}`);
14327
+ if (value > bounds.max) this.issue(path18, "too_large", `at most ${bounds.max} ${unit}`);
14217
14328
  }
14218
- unknownFields(record, known, path17) {
14329
+ unknownFields(record, known, path18) {
14219
14330
  for (const [key2, value] of Object.entries(record)) {
14220
14331
  if (value !== void 0 && !known.has(key2))
14221
- this.issue([...path17, key2], "unknown_field", "not a field of an agent definition");
14332
+ this.issue([...path18, key2], "unknown_field", "not a field of an agent definition");
14222
14333
  }
14223
14334
  }
14224
14335
  noRepeats(values, pathOf, code, message) {
@@ -14229,11 +14340,11 @@ var DefinitionReader = class _DefinitionReader {
14229
14340
  seen.add(value);
14230
14341
  });
14231
14342
  }
14232
- issue(path17, code, message) {
14233
- this.#issues.push({ path: path17, code, message });
14343
+ issue(path18, code, message) {
14344
+ this.#issues.push({ path: path18, code, message });
14234
14345
  }
14235
- refuse(path17, code, message, fallback) {
14236
- this.issue(path17, code, message);
14346
+ refuse(path18, code, message, fallback) {
14347
+ this.issue(path18, code, message);
14237
14348
  return fallback;
14238
14349
  }
14239
14350
  };
@@ -14341,12 +14452,12 @@ var Agents = class {
14341
14452
  }
14342
14453
  return builds;
14343
14454
  }
14344
- async conflictAware(method, path17, body) {
14455
+ async conflictAware(method, path18, body) {
14345
14456
  try {
14346
- return await this.#transport.json(method, path17, body);
14457
+ return await this.#transport.json(method, path18, body);
14347
14458
  } catch (error) {
14348
14459
  if (error instanceof ApiError && error.code === "agent_version_conflict")
14349
- throw new AgentVersionConflictError(error.status, method, path17, error.text);
14460
+ throw new AgentVersionConflictError(error.status, method, path18, error.text);
14350
14461
  throw error;
14351
14462
  }
14352
14463
  }
@@ -14857,6 +14968,35 @@ var AGENT_EFFORTS = ["low", "medium", "high", "xhigh"];
14857
14968
  var TOOL_SERVERS = {
14858
14969
  docs: ["search_docs"],
14859
14970
  drive: ["get_drive_file", "list_drive_files", "save_drive_file"],
14971
+ factory: [
14972
+ "accept_factory_unit",
14973
+ "check_world_sandbox",
14974
+ "close_world_sandbox",
14975
+ "commit_world_sandbox",
14976
+ "describe_member",
14977
+ "diff_factory_revisions",
14978
+ "exec_in_world_sandbox",
14979
+ "generate_spine",
14980
+ "get_factory",
14981
+ "get_factory_data",
14982
+ "get_factory_revision",
14983
+ "get_spine",
14984
+ "get_spine_rows",
14985
+ "get_world_sandbox",
14986
+ "import_world_sandbox_data",
14987
+ "list_factory_revisions",
14988
+ "open_world_sandbox",
14989
+ "query_factory_data",
14990
+ "read_world_sandbox_file",
14991
+ "release_factory_data",
14992
+ "update_entity_graph",
14993
+ "update_ontology",
14994
+ "update_rules",
14995
+ "update_spine",
14996
+ "update_tests",
14997
+ "write_records",
14998
+ "write_world_sandbox_file"
14999
+ ],
14860
15000
  sandbox: [
14861
15001
  "copy_file",
14862
15002
  "execute_python",
@@ -14875,6 +15015,7 @@ var grant = (server) => (options = {}) => options.only ? { server, only: [...opt
14875
15015
  var tools = Object.freeze({
14876
15016
  sandbox: grant("sandbox"),
14877
15017
  drive: grant("drive"),
15018
+ factory: grant("factory"),
14878
15019
  web: grant("web"),
14879
15020
  docs: grant("docs")
14880
15021
  });
@@ -14905,8 +15046,8 @@ __export(files_exports, {
14905
15046
  });
14906
15047
  init_worlds();
14907
15048
  import { createHash as createHash11 } from "crypto";
14908
- import * as fs13 from "fs";
14909
- import * as path13 from "path";
15049
+ import * as fs14 from "fs";
15050
+ import * as path14 from "path";
14910
15051
  import { Readable, Transform } from "stream";
14911
15052
  import { pipeline } from "stream/promises";
14912
15053
  var DRIVE_PREFIX = "drive:";
@@ -14957,9 +15098,9 @@ async function readFile2(options = {}, filePath, limits = {}) {
14957
15098
  async function downloadFile(options = {}, filePath, outPath, onProgress) {
14958
15099
  const file = await getFile(options, filePath);
14959
15100
  const res = await openDownload(file.url);
14960
- fs13.mkdirSync(path13.dirname(path13.resolve(outPath)), { recursive: true });
15101
+ fs14.mkdirSync(path14.dirname(path14.resolve(outPath)), { recursive: true });
14961
15102
  const source = Readable.fromWeb(res.body);
14962
- await pipeline(source, counting((n) => onProgress?.(n, file.sizeBytes)), fs13.createWriteStream(outPath));
15103
+ await pipeline(source, counting((n) => onProgress?.(n, file.sizeBytes)), fs14.createWriteStream(outPath));
14963
15104
  return { ...file, out: outPath };
14964
15105
  }
14965
15106
  async function requestUpload(options = {}, body) {
@@ -14970,7 +15111,7 @@ async function confirmUpload(options = {}, fileId, ok = true) {
14970
15111
  }
14971
15112
  async function sha256Base64(localPath) {
14972
15113
  const hash = createHash11("sha256");
14973
- for await (const chunk of fs13.createReadStream(localPath)) hash.update(chunk);
15114
+ for await (const chunk of fs14.createReadStream(localPath)) hash.update(chunk);
14974
15115
  return hash.digest("base64");
14975
15116
  }
14976
15117
  var CONTENT_TYPES = {
@@ -15006,7 +15147,7 @@ var CONTENT_TYPES = {
15006
15147
  ".mp4": "video/mp4"
15007
15148
  };
15008
15149
  function contentTypeFor(name) {
15009
- return CONTENT_TYPES[path13.extname(name).toLowerCase()] ?? "application/octet-stream";
15150
+ return CONTENT_TYPES[path14.extname(name).toLowerCase()] ?? "application/octet-stream";
15010
15151
  }
15011
15152
  function counting(report) {
15012
15153
  let seen = 0;
@@ -15033,7 +15174,7 @@ async function putPresigned(uploadUrl, body, headers) {
15033
15174
  if (!res.ok) throw new Error(`upload failed: storage answered HTTP ${res.status}: ${(await res.text()).slice(0, 300)}`);
15034
15175
  }
15035
15176
  async function uploadFile(options = {}, localPath, targetPath, upload = {}) {
15036
- const stat = fs13.statSync(localPath);
15177
+ const stat = fs14.statSync(localPath);
15037
15178
  if (!stat.isFile()) throw new Error(`${localPath} is not a file`);
15038
15179
  if (stat.size === 0) throw new Error(`${localPath} is empty; the drive refuses zero-byte uploads`);
15039
15180
  const contentType = upload.contentType ?? contentTypeFor(localPath);
@@ -15041,7 +15182,7 @@ async function uploadFile(options = {}, localPath, targetPath, upload = {}) {
15041
15182
  const target = drivePath(targetPath);
15042
15183
  const granted = await requestUpload(options, { path: target, contentLength: stat.size, contentType, sha256: sha2562, ...upload.overwrite ? { overwrite: true } : {} });
15043
15184
  try {
15044
- const stream = fs13.createReadStream(localPath).pipe(counting((n) => upload.onProgress?.(n, stat.size)));
15185
+ const stream = fs14.createReadStream(localPath).pipe(counting((n) => upload.onProgress?.(n, stat.size)));
15045
15186
  await putPresigned(granted.uploadUrl, Readable.toWeb(stream), { contentType, contentLength: stat.size, sha256: sha2562 });
15046
15187
  } catch (error) {
15047
15188
  await confirmUpload(options, granted.fileId, false).catch(() => void 0);
@@ -16471,7 +16612,7 @@ function mirrorHandle(handle, identity) {
16471
16612
  }
16472
16613
 
16473
16614
  // src/hooks/config.ts
16474
- import * as fs14 from "fs";
16615
+ import * as fs15 from "fs";
16475
16616
 
16476
16617
  // src/cli/platform/worldData/toml.ts
16477
16618
  var TomlDateTime = class {
@@ -16529,26 +16670,26 @@ var TomlReader = class {
16529
16670
  if (header) return this.header(keyPath(header[1], line), line);
16530
16671
  const eq = outsideQuotes(text2, "=");
16531
16672
  if (eq === -1) throw new TomlError(`line ${line}: expected key = value`);
16532
- const path17 = keyPath(text2.slice(0, eq), line);
16673
+ const path18 = keyPath(text2.slice(0, eq), line);
16533
16674
  const [value, rest] = readValue(text2.slice(eq + 1), line);
16534
16675
  if (stripBlank(rest)) throw new TomlError(`line ${line}: unexpected text after value`);
16535
- assign(this.descend(this.current, path17.slice(0, -1), line, "key"), path17, value, line);
16676
+ assign(this.descend(this.current, path18.slice(0, -1), line, "key"), path18, value, line);
16536
16677
  }
16537
- header(path17, line) {
16538
- const parent = this.descend(this.root, path17.slice(0, -1), line, "header");
16539
- const name = path17.at(-1);
16678
+ header(path18, line) {
16679
+ const parent = this.descend(this.root, path18.slice(0, -1), line, "header");
16680
+ const name = path18.at(-1);
16540
16681
  const table2 = own(parent, name) ?? newTable();
16541
16682
  const fresh = isTomlTable(table2) && !INLINE.has(table2) && !this.byDottedKey.has(table2) && !this.defined.has(table2);
16542
- if (!fresh) throw new TomlError(`line ${line}: [${path17.join(".")}] is defined twice`);
16683
+ if (!fresh) throw new TomlError(`line ${line}: [${path18.join(".")}] is defined twice`);
16543
16684
  parent[name] = table2;
16544
16685
  this.open(table2);
16545
16686
  }
16546
- arrayTable(path17, line) {
16547
- const parent = this.descend(this.root, path17.slice(0, -1), line, "header");
16548
- const name = path17.at(-1);
16687
+ arrayTable(path18, line) {
16688
+ const parent = this.descend(this.root, path18.slice(0, -1), line, "header");
16689
+ const name = path18.at(-1);
16549
16690
  const existing = own(parent, name);
16550
16691
  if (existing !== void 0 && !(Array.isArray(existing) && this.tableArrays.has(existing)))
16551
- throw new TomlError(`line ${line}: ${path17.join(".")} is not an array of tables`);
16692
+ throw new TomlError(`line ${line}: ${path18.join(".")} is not an array of tables`);
16552
16693
  const list2 = existing ?? [];
16553
16694
  this.tableArrays.add(list2);
16554
16695
  parent[name] = list2;
@@ -16583,9 +16724,9 @@ var TomlReader = class {
16583
16724
  return target;
16584
16725
  }
16585
16726
  };
16586
- function assign(table2, path17, value, line) {
16587
- const key2 = path17.at(-1);
16588
- if (own(table2, key2) !== void 0) throw new TomlError(`line ${line}: key ${path17.join(".")} is defined twice`);
16727
+ function assign(table2, path18, value, line) {
16728
+ const key2 = path18.at(-1);
16729
+ if (own(table2, key2) !== void 0) throw new TomlError(`line ${line}: key ${path18.join(".")} is defined twice`);
16589
16730
  table2[key2] = value;
16590
16731
  }
16591
16732
  function inlineAt(table2, parts2, line) {
@@ -16795,9 +16936,9 @@ function readInlineTable(s, line) {
16795
16936
  for (; ; ) {
16796
16937
  const eq = outsideQuotes(rest, "=");
16797
16938
  if (eq === -1) throw new TomlError(`line ${line}: expected key = value in inline table`);
16798
- const path17 = keyPath(rest.slice(0, eq), line);
16939
+ const path18 = keyPath(rest.slice(0, eq), line);
16799
16940
  const [value, after] = readValue(rest.slice(eq + 1), line);
16800
- assign(inlineAt(table2, path17.slice(0, -1), line), path17, value, line);
16941
+ assign(inlineAt(table2, path18.slice(0, -1), line), path18, value, line);
16801
16942
  rest = after.replace(/^[ \t]+/, "");
16802
16943
  if (rest.startsWith("}")) {
16803
16944
  INLINE.add(table2);
@@ -17038,9 +17179,9 @@ function alternatives(raw) {
17038
17179
  if (!parts2.length || parts2.includes("*")) return [];
17039
17180
  return parts2;
17040
17181
  }
17041
- function hasPath(node, path17) {
17182
+ function hasPath(node, path18) {
17042
17183
  let current = node;
17043
- for (const part of path17.split(".")) {
17184
+ for (const part of path18.split(".")) {
17044
17185
  if (current && typeof current === "object" && !Array.isArray(current) && part in current) {
17045
17186
  current = current[part];
17046
17187
  continue;
@@ -17081,7 +17222,7 @@ function matches(m, event) {
17081
17222
  if (m.args.length) {
17082
17223
  const haystacks = event.event === "pre_request" || event.event === "post_response" ? [event.request?.query, event.request?.body] : [event.toolInput];
17083
17224
  const present = haystacks.filter((h) => h !== void 0 && h !== null);
17084
- if (!m.args.every((path17) => present.some((h) => hasPath(h, path17))))
17225
+ if (!m.args.every((path18) => present.some((h) => hasPath(h, path18))))
17085
17226
  return false;
17086
17227
  }
17087
17228
  return true;
@@ -17525,9 +17666,9 @@ function vendorOf(config, toolName) {
17525
17666
  return void 0;
17526
17667
  }
17527
17668
  function loadHookConfig(file) {
17528
- if (!fs14.existsSync(file) || !fs14.statSync(file).isFile())
17669
+ if (!fs15.existsSync(file) || !fs15.statSync(file).isFile())
17529
17670
  throw new HookConfigError(`${file}: no such file`);
17530
- const text2 = fs14.readFileSync(file, "utf8");
17671
+ const text2 = fs15.readFileSync(file, "utf8");
17531
17672
  if (file.toLowerCase().endsWith(".json")) {
17532
17673
  let data2;
17533
17674
  try {
@@ -17916,8 +18057,8 @@ function parseHandler(event, raw, position) {
17916
18057
 
17917
18058
  // src/hooks/handlers.ts
17918
18059
  import { spawn as spawn3 } from "child_process";
17919
- import * as fs15 from "fs";
17920
- import * as path14 from "path";
18060
+ import * as fs16 from "fs";
18061
+ import * as path15 from "path";
17921
18062
  import { pathToFileURL } from "url";
17922
18063
  function parseStdout(text2, handler) {
17923
18064
  const stripped = text2.trim();
@@ -18118,8 +18259,8 @@ var RecordHandler = class {
18118
18259
  record.source = this.opts.source ?? null;
18119
18260
  if (Array.isArray(this.sink)) this.sink.push(record);
18120
18261
  else if (typeof this.sink === "string") {
18121
- fs15.mkdirSync(path14.dirname(this.sink), { recursive: true });
18122
- fs15.appendFileSync(this.sink, JSON.stringify(record) + "\n");
18262
+ fs16.mkdirSync(path15.dirname(this.sink), { recursive: true });
18263
+ fs16.appendFileSync(this.sink, JSON.stringify(record) + "\n");
18123
18264
  } else await this.sink(record);
18124
18265
  return allow();
18125
18266
  }
@@ -18329,7 +18470,7 @@ async function importCallable(target, cwd) {
18329
18470
  const hash = target.lastIndexOf("#");
18330
18471
  const modulePath = target.slice(0, hash);
18331
18472
  const exportName = target.slice(hash + 1) || "default";
18332
- const resolved = modulePath.startsWith(".") || path14.isAbsolute(modulePath) ? pathToFileURL(path14.resolve(cwd, modulePath)).href : modulePath;
18473
+ const resolved = modulePath.startsWith(".") || path15.isAbsolute(modulePath) ? pathToFileURL(path15.resolve(cwd, modulePath)).href : modulePath;
18333
18474
  let module;
18334
18475
  try {
18335
18476
  module = await import(resolved);
@@ -18392,8 +18533,8 @@ async function buildHandler(spec, aliases, opts) {
18392
18533
  }
18393
18534
 
18394
18535
  // src/hooks/live.ts
18395
- import * as fs16 from "fs";
18396
- import * as path15 from "path";
18536
+ import * as fs17 from "fs";
18537
+ import * as path16 from "path";
18397
18538
 
18398
18539
  // src/hooks/vendorAuth.ts
18399
18540
  var bearer = (auth, value) => ({
@@ -18877,9 +19018,9 @@ var CallableTool = class _CallableTool {
18877
19018
  }
18878
19019
  };
18879
19020
  function readConnection(root) {
18880
- const file = path15.join(root, "connector.toml");
18881
- if (!fs16.existsSync(file)) throw new Error(`no connector.toml at ${root}`);
18882
- const raw = parseToml(fs16.readFileSync(file, "utf8"));
19021
+ const file = path16.join(root, "connector.toml");
19022
+ if (!fs17.existsSync(file)) throw new Error(`no connector.toml at ${root}`);
19023
+ const raw = parseToml(fs17.readFileSync(file, "utf8"));
18883
19024
  const connector = raw.connector ?? {};
18884
19025
  const auth = raw.auth ?? { scheme: "none" };
18885
19026
  const carrier = vendorAuth(auth);
@@ -18894,7 +19035,7 @@ function readConnection(root) {
18894
19035
  };
18895
19036
  }
18896
19037
  return {
18897
- slug: typeof connector.slug === "string" ? connector.slug : path15.basename(root),
19038
+ slug: typeof connector.slug === "string" ? connector.slug : path16.basename(root),
18898
19039
  baseUrl: (typeof connector.base_url === "string" ? connector.base_url : "").replace(/\/+$/, ""),
18899
19040
  scheme: carrier.scheme,
18900
19041
  carrier,
@@ -18911,8 +19052,8 @@ var ConnectorTool = class {
18911
19052
  this.spec = spec;
18912
19053
  this.live = live;
18913
19054
  let location = spec.options.connector;
18914
- if (!path15.isAbsolute(location)) location = path15.resolve(baseDir, location);
18915
- const root = fs16.existsSync(location) && fs16.statSync(location).isFile() ? path15.dirname(location) : location;
19055
+ if (!path16.isAbsolute(location)) location = path16.resolve(baseDir, location);
19056
+ const root = fs17.existsSync(location) && fs17.statSync(location).isFile() ? path16.dirname(location) : location;
18916
19057
  try {
18917
19058
  this.connection = readConnection(root);
18918
19059
  } catch (error) {
@@ -19065,16 +19206,16 @@ var Recorder = class {
19065
19206
  }
19066
19207
  file;
19067
19208
  write(line) {
19068
- fs16.mkdirSync(path15.dirname(this.file), { recursive: true });
19069
- fs16.appendFileSync(this.file, canonical2(line) + "\n");
19209
+ fs17.mkdirSync(path16.dirname(this.file), { recursive: true });
19210
+ fs17.appendFileSync(this.file, canonical2(line) + "\n");
19070
19211
  }
19071
19212
  };
19072
19213
  var Replay = class {
19073
19214
  constructor(file) {
19074
19215
  this.file = file;
19075
- if (!fs16.existsSync(file))
19216
+ if (!fs17.existsSync(file))
19076
19217
  throw new LiveToolError(`replay: no recording at ${file}`);
19077
- fs16.readFileSync(file, "utf8").split(/\r?\n/).forEach((raw, index2) => {
19218
+ fs17.readFileSync(file, "utf8").split(/\r?\n/).forEach((raw, index2) => {
19078
19219
  if (!raw.trim()) return;
19079
19220
  let line;
19080
19221
  try {
@@ -19161,7 +19302,7 @@ var LiveTools = class _LiveTools {
19161
19302
  ...config.live.record ? { record: interpolatePath(config.live.record, run.runId, directory) } : {},
19162
19303
  ...config.live.replay ? { replay: interpolatePath(config.live.replay, run.runId, directory) } : {}
19163
19304
  };
19164
- return _LiveTools.create(run, live, path15.dirname(path15.resolve(file)));
19305
+ return _LiveTools.create(run, live, path16.dirname(path16.resolve(file)));
19165
19306
  }
19166
19307
  /** The declared tools for a model. `openai`: `{type: "function", function: {name,
19167
19308
  * description, parameters}}`; `anthropic`: `{name, description, input_schema}`. */
@@ -19487,8 +19628,8 @@ var RedactionAudit = class _RedactionAudit {
19487
19628
 
19488
19629
  // src/hooks/run.ts
19489
19630
  import { randomBytes as randomBytes3 } from "crypto";
19490
- import * as fs17 from "fs";
19491
- import * as path16 from "path";
19631
+ import * as fs18 from "fs";
19632
+ import * as path17 from "path";
19492
19633
  var BLOCKING_EVENTS = [
19493
19634
  "pre_tool_call",
19494
19635
  "pre_request",
@@ -19539,12 +19680,12 @@ var HookRun = class _HookRun {
19539
19680
  declaredOnly: options.declaredOnly ?? config.aliasDeclaredOnly
19540
19681
  });
19541
19682
  this.cwd = options.cwd ?? process.cwd();
19542
- this.runDir = options.runDir ?? path16.join(this.cwd, "runs", this.runId);
19683
+ this.runDir = options.runDir ?? path17.join(this.cwd, "runs", this.runId);
19543
19684
  const chosen = options.legend !== void 0 ? options.legend : config.aliasLegend;
19544
- this.legendPath = chosen ? path16.resolve(this.cwd, interpolatePath(chosen, this.runId, this.runDir)) : null;
19685
+ this.legendPath = chosen ? path17.resolve(this.cwd, interpolatePath(chosen, this.runId, this.runDir)) : null;
19545
19686
  this.sessionId = options.session;
19546
19687
  this.source = options.source;
19547
- this.configDir = config.source ? path16.dirname(path16.resolve(config.source)) : this.cwd;
19688
+ this.configDir = config.source ? path17.dirname(path17.resolve(config.source)) : this.cwd;
19548
19689
  }
19549
19690
  /** Build from a parsed config (an object in the file's shape, or a `HookConfig`);
19550
19691
  * handlers are constructed now, so a callable that does not import fails here. */
@@ -19954,8 +20095,8 @@ var HookRun = class _HookRun {
19954
20095
  throw new Error(
19955
20096
  "no legend path: set [alias] legend, pass legend to the run, or give a path"
19956
20097
  );
19957
- fs17.mkdirSync(path16.dirname(target), { recursive: true });
19958
- fs17.writeFileSync(target, JSON.stringify(this.legend(), null, 2) + "\n");
20098
+ fs18.mkdirSync(path17.dirname(target), { recursive: true });
20099
+ fs18.writeFileSync(target, JSON.stringify(this.legend(), null, 2) + "\n");
19959
20100
  return target;
19960
20101
  }
19961
20102
  writeLegendIfConfigured() {
@@ -20051,14 +20192,14 @@ var HookedSession = class {
20051
20192
  * `apiHeaders()`), `pre_request` before it and `post_response` after. Returns
20052
20193
  * `{status, body, headers}`; a 4xx/5xx is returned, not thrown, so the agent sees
20053
20194
  * the vendor's own error shape (rewritten like any result). */
20054
- async request(method, path17, opts = {}) {
20195
+ async request(method, path18, opts = {}) {
20055
20196
  if (!this.inner.api && !this.requestFn)
20056
20197
  throw new Error(
20057
20198
  "this session has no api surface (pass requestFn for a transport of your own)"
20058
20199
  );
20059
20200
  let request = {
20060
20201
  method: method.toUpperCase(),
20061
- path: path17,
20202
+ path: path18,
20062
20203
  query: { ...opts.query ?? {} },
20063
20204
  body: opts.body ?? null
20064
20205
  };