@withgateway/sdk 0.2.4 → 0.2.5

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 (46) hide show
  1. package/dist/cli.js +1798 -1713
  2. package/dist/cli.js.map +1 -1
  3. package/dist/cli.mjs +2412 -2327
  4. package/dist/cli.mjs.map +1 -1
  5. package/dist/files/index.js +47 -31
  6. package/dist/files/index.js.map +1 -1
  7. package/dist/files/index.mjs +43 -27
  8. package/dist/files/index.mjs.map +1 -1
  9. package/dist/index.d.mts +1 -1
  10. package/dist/index.d.ts +1 -1
  11. package/dist/index.js +390 -287
  12. package/dist/index.js.map +1 -1
  13. package/dist/index.mjs +375 -271
  14. package/dist/index.mjs.map +1 -1
  15. package/dist/traces/index.js +36 -20
  16. package/dist/traces/index.js.map +1 -1
  17. package/dist/traces/index.mjs +32 -16
  18. package/dist/traces/index.mjs.map +1 -1
  19. package/dist/tracing/index.js +2 -1
  20. package/dist/tracing/index.js.map +1 -1
  21. package/dist/tracing/index.mjs +2 -1
  22. package/dist/tracing/index.mjs.map +1 -1
  23. package/dist/worlds/index.d.mts +26 -22
  24. package/dist/worlds/index.d.ts +26 -22
  25. package/dist/worlds/index.js +307 -203
  26. package/dist/worlds/index.js.map +1 -1
  27. package/dist/worlds/index.mjs +297 -193
  28. package/dist/worlds/index.mjs.map +1 -1
  29. package/package.json +2 -1
  30. package/runtime/gatewaysdk/environment/_bundle.py +14 -24
  31. package/runtime/gatewaysdk/environment/schema/api.py +37 -18
  32. package/runtime/gatewaysdk/environment/schema/data.py +21 -19
  33. package/runtime/gatewaysdk/environment/schema/grading.py +225 -0
  34. package/runtime/gatewaysdk/environment/schema/host.py +156 -546
  35. package/runtime/gatewaysdk/environment/schema/ingest.py +3 -11
  36. package/runtime/gatewaysdk/environment/schema/local.py +32 -126
  37. package/runtime/gatewaysdk/environment/schema/platform.py +14 -22
  38. package/runtime/gatewaysdk/environment/schema/proof.py +237 -0
  39. package/runtime/gatewaysdk/environment/schema/runtime.py +686 -0
  40. package/runtime/gatewaysdk/environment/schema/skill.py +1 -0
  41. package/runtime/gatewaysdk/environment/schema/skills/hooks-getting-started/SKILL.md +6 -4
  42. package/runtime/gatewaysdk/environment/schema/tools_world.py +75 -23
  43. package/runtime/gatewaysdk/environment/schema/verbs.py +136 -0
  44. package/runtime/gatewaysdk/environment/schema/workers.py +14 -0
  45. package/runtime/gatewaysdk/environment/world.py +391 -0
  46. package/skills/hooks-getting-started/SKILL.md +6 -4
package/dist/index.js CHANGED
@@ -195,10 +195,10 @@ var init_users = __esm({
195
195
  totalItems: Number(meta.totalItems ?? rows.length)
196
196
  };
197
197
  }
198
- async requestJson(method, path13, payload) {
198
+ async requestJson(method, path14, payload) {
199
199
  let response;
200
200
  try {
201
- response = await fetch(`${this.host}${path13}`, {
201
+ response = await fetch(`${this.host}${path14}`, {
202
202
  method,
203
203
  headers: {
204
204
  Authorization: this.authHeader(),
@@ -209,17 +209,17 @@ var init_users = __esm({
209
209
  });
210
210
  } catch (error) {
211
211
  throw new UserProfileError(
212
- `${method} ${path13} failed: ${error instanceof Error ? error.message : String(error)}`,
212
+ `${method} ${path14} failed: ${error instanceof Error ? error.message : String(error)}`,
213
213
  { cause: error }
214
214
  );
215
215
  }
216
216
  const text2 = await response.text();
217
217
  if (!response.ok) {
218
218
  throw new UserProfileError(
219
- `${method} ${path13} failed (${response.status}): ${text2.slice(0, 500)}`
219
+ `${method} ${path14} failed (${response.status}): ${text2.slice(0, 500)}`
220
220
  );
221
221
  }
222
- this.log("%s %s -> %s", method, path13, response.status);
222
+ this.log("%s %s -> %s", method, path14, response.status);
223
223
  return safeJson4(text2);
224
224
  }
225
225
  authHeader() {
@@ -408,10 +408,10 @@ var init_scores = __esm({
408
408
  metadata: signalMetadata
409
409
  });
410
410
  }
411
- async request(method, path13, payload) {
411
+ async request(method, path14, payload) {
412
412
  let response;
413
413
  try {
414
- response = await fetch(`${this.host}${path13}`, {
414
+ response = await fetch(`${this.host}${path14}`, {
415
415
  method,
416
416
  headers: {
417
417
  Authorization: this.authHeader(),
@@ -422,17 +422,17 @@ var init_scores = __esm({
422
422
  });
423
423
  } catch (error) {
424
424
  throw new ScoreError(
425
- `${method} ${path13} failed: ${error instanceof Error ? error.message : String(error)}`,
425
+ `${method} ${path14} failed: ${error instanceof Error ? error.message : String(error)}`,
426
426
  { cause: error }
427
427
  );
428
428
  }
429
429
  const text2 = await response.text();
430
430
  if (!response.ok) {
431
431
  throw new ScoreError(
432
- `${method} ${path13} failed (${response.status}): ${text2.slice(0, 500)}`
432
+ `${method} ${path14} failed (${response.status}): ${text2.slice(0, 500)}`
433
433
  );
434
434
  }
435
- this.log("%s %s -> %s", method, path13, response.status);
435
+ this.log("%s %s -> %s", method, path14, response.status);
436
436
  }
437
437
  authHeader() {
438
438
  return `Basic ${Buffer.from(`${this.publicKey}:${this.secretKey}`).toString(
@@ -463,9 +463,9 @@ function surfaceKinds(s) {
463
463
  if (s.browser) kinds.push("browser");
464
464
  return kinds;
465
465
  }
466
- function uiUrl(ui, path13) {
466
+ function uiUrl(ui, path14) {
467
467
  const base = ui.url.replace(/\/+$/, "");
468
- const rel = path13.startsWith("/") ? path13 : `/${path13}`;
468
+ const rel = path14.startsWith("/") ? path14 : `/${path14}`;
469
469
  if (!ui.token) return base + rel;
470
470
  const [beforeHash, hash] = splitHash(rel);
471
471
  const joiner = beforeHash.includes("?") ? "&" : "?";
@@ -1022,12 +1022,13 @@ async function openSession(slugOrRef, taskOrOpts, positionalOpts = {}) {
1022
1022
  );
1023
1023
  const at = slugOrRef.indexOf("@");
1024
1024
  const slug = at === -1 ? slugOrRef : slugOrRef.slice(0, at);
1025
+ const ref = at === -1 ? "" : slugOrRef.slice(at + 1);
1025
1026
  const state2 = await apiRequest(
1026
1027
  options,
1027
1028
  "POST",
1028
1029
  "/api/public/world-sessions",
1029
1030
  {
1030
- ...opts.versionId ? { versionId: opts.versionId } : { slug },
1031
+ ...opts.versionId ? { versionId: opts.versionId } : { slug, ...ref && { ref } },
1031
1032
  task,
1032
1033
  ...opts.reuseWarm === void 0 ? {} : { reuseWarm: opts.reuseWarm },
1033
1034
  ...opts.surfaces?.length ? { surfaces: opts.surfaces } : {}
@@ -1226,18 +1227,18 @@ var init_session = __esm({
1226
1227
  }
1227
1228
  /** The reporter `browser()` uses; exposed for a page you drive yourself. */
1228
1229
  browserRecorder(agentId) {
1229
- const path13 = `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/browser-events`;
1230
+ const path14 = `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/browser-events`;
1230
1231
  const id = agentId ?? process.env.GATEWAY_AGENT_ID ?? `agent-${(0, import_node_crypto.randomUUID)().replace(/-/g, "").slice(0, 8)}`;
1231
1232
  return new BrowserActionRecorder(
1232
1233
  async (events) => {
1233
- await apiRequest(this.options, "POST", path13, { events });
1234
+ await apiRequest(this.options, "POST", path14, { events });
1234
1235
  },
1235
1236
  id,
1236
1237
  {
1237
1238
  // Continue this agent's timeline where the platform has it, so the
1238
1239
  // same id reopened later never re-numbers from zero.
1239
1240
  resumeFrom: async () => {
1240
- const summary = await apiRequest(this.options, "GET", path13);
1241
+ const summary = await apiRequest(this.options, "GET", path14);
1241
1242
  return summary.agents.find((a) => a.agentId === id)?.nextSeq ?? 0;
1242
1243
  }
1243
1244
  }
@@ -2000,7 +2001,7 @@ var require_package = __commonJS({
2000
2001
  "package.json"(exports2, module2) {
2001
2002
  module2.exports = {
2002
2003
  name: "@withgateway/sdk",
2003
- version: "0.2.4",
2004
+ version: "0.2.5",
2004
2005
  description: "Gateway SDK for TypeScript - A/B experiments, tracing, and observability",
2005
2006
  main: "./dist/index.js",
2006
2007
  module: "./dist/index.mjs",
@@ -2104,6 +2105,7 @@ var require_package = __commonJS({
2104
2105
  "typecheck:examples": "tsc -p tsconfig.examples.json --noEmit",
2105
2106
  test: "vitest",
2106
2107
  "test:run": "vitest run",
2108
+ "test:integration": "vitest run --config vitest.integration.config.ts",
2107
2109
  lint: "eslint src --ext .ts",
2108
2110
  clean: "rm -rf dist",
2109
2111
  example: "tsx examples/test-ab-experiment.ts",
@@ -3048,6 +3050,152 @@ var init_taskRun = __esm({
3048
3050
  }
3049
3051
  });
3050
3052
 
3053
+ // src/worlds/worldDir.ts
3054
+ var import_node_crypto4, fs2, path2, WORLD_MANIFEST, API_BUNDLE_MANIFEST, BUNDLED_WORLD_PREFIX, CONNECTOR_SPEC, PYPROJECT, WORLD_SCHEMA_MARKERS, WORLD_ROOT_MARKERS, BROAD_ROOT_MARKERS, SKIPPED_DIRS, V1_DEP, V1_IMPORT, V1_TASKSET, HARBOR_TASK, skippedDir, byCodePoint, WorldDir;
3055
+ var init_worldDir = __esm({
3056
+ "src/worlds/worldDir.ts"() {
3057
+ "use strict";
3058
+ import_node_crypto4 = require("crypto");
3059
+ fs2 = __toESM(require("fs"));
3060
+ path2 = __toESM(require("path"));
3061
+ WORLD_MANIFEST = "gateway-env.toml";
3062
+ API_BUNDLE_MANIFEST = "gateway-api-world.toml";
3063
+ BUNDLED_WORLD_PREFIX = "server/world/";
3064
+ CONNECTOR_SPEC = "connector.toml";
3065
+ PYPROJECT = "pyproject.toml";
3066
+ WORLD_SCHEMA_MARKERS = ["schema/world.json", "schema/runtime.json", "schema/lock.json"];
3067
+ WORLD_ROOT_MARKERS = [CONNECTOR_SPEC, ...WORLD_SCHEMA_MARKERS];
3068
+ BROAD_ROOT_MARKERS = [WORLD_MANIFEST, API_BUNDLE_MANIFEST];
3069
+ SKIPPED_DIRS = /* @__PURE__ */ new Set(["dist", "build", "outputs", "__pycache__"]);
3070
+ V1_DEP = /["']verifiers\s*(?:\[[^\]]*\])?\s*(?:>=|~=|==|>)\s*(?:0\.(?:[2-9]\d*|[1-9]\d+)|[1-9]\d*)/;
3071
+ V1_IMPORT = /^\s*(?:from\s+verifiers\.v1\s+import\b|from\s+verifiers\s+import\s+v1\b|import\s+verifiers\.v1\b)/m;
3072
+ V1_TASKSET = /class\s+\w+\s*\(\s*(?:(?:vf|v1|verifiers(?:\.v1)?)\.)?Taskset\s*[,)]/;
3073
+ HARBOR_TASK = /^(?:tasks\/)?([^/]+)\/task\.toml$/;
3074
+ skippedDir = (name) => name.startsWith(".") || SKIPPED_DIRS.has(name) || name.endsWith(".egg-info");
3075
+ byCodePoint = (a, b) => Buffer.compare(Buffer.from(a, "utf-8"), Buffer.from(b, "utf-8"));
3076
+ WorldDir = class _WorldDir {
3077
+ constructor(dir, worldRoot) {
3078
+ this.dir = dir;
3079
+ this.worldRoot = worldRoot;
3080
+ }
3081
+ pathsMemo;
3082
+ static open(dir) {
3083
+ const present = (rel) => fs2.existsSync(path2.join(dir, rel));
3084
+ const bundled = present(API_BUNDLE_MANIFEST) && WORLD_ROOT_MARKERS.some((m) => present(BUNDLED_WORLD_PREFIX + m));
3085
+ return new _WorldDir(dir, bundled ? BUNDLED_WORLD_PREFIX : "");
3086
+ }
3087
+ // ── Files ──────────────────────────────────────────────────────────────
3088
+ has(rel) {
3089
+ return fs2.existsSync(path2.join(this.dir, rel));
3090
+ }
3091
+ text(rel) {
3092
+ try {
3093
+ return fs2.readFileSync(path2.join(this.dir, rel), "utf-8");
3094
+ } catch {
3095
+ return null;
3096
+ }
3097
+ }
3098
+ /** A path under the authored world's root. */
3099
+ worldPath(rel) {
3100
+ return this.worldRoot + rel;
3101
+ }
3102
+ /** Every regular file the archive rules keep (`_archive.py`: no hidden,
3103
+ * dist, build, outputs, pycache or egg-info directories), as sorted
3104
+ * relpaths. Root files enter only when a Gateway manifest widens the root
3105
+ * or they are README.md, pyproject.toml or Python. */
3106
+ get archivePaths() {
3107
+ if (this.pathsMemo) return this.pathsMemo;
3108
+ const broad = BROAD_ROOT_MARKERS.some((m) => this.has(m));
3109
+ const out = [];
3110
+ const walk = (rel) => {
3111
+ for (const entry of fs2.readdirSync(rel ? path2.join(this.dir, rel) : this.dir, { withFileTypes: true })) {
3112
+ const child = rel ? `${rel}/${entry.name}` : entry.name;
3113
+ if (entry.isDirectory()) {
3114
+ if (!skippedDir(entry.name)) walk(child);
3115
+ } else if (entry.isFile() && !entry.name.startsWith(".")) {
3116
+ const rootKept = broad || ["README.md", PYPROJECT].includes(entry.name) || entry.name.endsWith(".py");
3117
+ if (rel || rootKept) out.push(child);
3118
+ }
3119
+ }
3120
+ };
3121
+ walk("");
3122
+ return this.pathsMemo = out.sort(byCodePoint);
3123
+ }
3124
+ /** A root `.gitignore` is present: the Python SDK honours it when
3125
+ * collecting, this package does not reimplement gitignore. */
3126
+ get hasRootGitignore() {
3127
+ return this.has(".gitignore");
3128
+ }
3129
+ /** SHA-256 over `utf8("file:" + relpath)` + bytes per archive path in
3130
+ * sorted order: the version's identity, byte-compatible with
3131
+ * `_archive.compute_content_hash` and Prime Intellect. */
3132
+ get contentHash() {
3133
+ const hasher = (0, import_node_crypto4.createHash)("sha256");
3134
+ for (const rel of this.archivePaths) {
3135
+ hasher.update(Buffer.from(`file:${rel}`, "utf-8"));
3136
+ hasher.update(fs2.readFileSync(path2.join(this.dir, rel)));
3137
+ }
3138
+ return hasher.digest("hex");
3139
+ }
3140
+ // ── Markers ────────────────────────────────────────────────────────────
3141
+ get isApiBundle() {
3142
+ return this.has(API_BUNDLE_MANIFEST);
3143
+ }
3144
+ get hasManifest() {
3145
+ return this.has(this.worldPath(WORLD_MANIFEST));
3146
+ }
3147
+ get hasSchemaMarker() {
3148
+ return WORLD_SCHEMA_MARKERS.some((m) => this.has(this.worldPath(m)));
3149
+ }
3150
+ /** Harbor task dirs, relative to the tree: `tasks/<name>` when a `tasks/`
3151
+ * dir holds them, else the root `<name>` dirs. */
3152
+ taskDirs() {
3153
+ const names = /* @__PURE__ */ new Set();
3154
+ for (const rel of this.archivePaths) {
3155
+ const m = HARBOR_TASK.exec(rel);
3156
+ if (m) names.add(rel.startsWith("tasks/") ? `tasks/${m[1]}` : m[1]);
3157
+ }
3158
+ const under = [...names].filter((n) => n.startsWith("tasks/"));
3159
+ return (under.length ? under : [...names]).sort();
3160
+ }
3161
+ /** The Python package of a verifiers tree (`<pkg>/__init__.py` or
3162
+ * `src/<pkg>/__init__.py`), or null. */
3163
+ pythonPackage() {
3164
+ if (!this.has(PYPROJECT)) return null;
3165
+ for (const base of ["", "src/"]) {
3166
+ const init3 = this.archivePaths.find((rel) => {
3167
+ const m = /^([^/]+)\/__init__\.py$/.exec(rel.startsWith(base) ? rel.slice(base.length) : "");
3168
+ return m !== null && m[1] !== "tests";
3169
+ });
3170
+ if (init3) return { name: init3.slice(base.length).split("/")[0], init: init3 };
3171
+ }
3172
+ return null;
3173
+ }
3174
+ /** The package targets the `verifiers.v1` API: read from the root
3175
+ * pyproject and every archived Python module. */
3176
+ get isVerifiersV1() {
3177
+ for (const rel of this.archivePaths) {
3178
+ if (rel !== PYPROJECT && !rel.endsWith(".py")) continue;
3179
+ const text2 = this.text(rel);
3180
+ if (text2 === null) continue;
3181
+ if (rel === PYPROJECT ? V1_DEP.test(text2) : V1_IMPORT.test(text2) || text2.includes("__all__") && V1_TASKSET.test(text2))
3182
+ return true;
3183
+ }
3184
+ return false;
3185
+ }
3186
+ // ── The answer ─────────────────────────────────────────────────────────
3187
+ /** The runner's kind (`detect_env_kind`): api / mock-tools win over
3188
+ * everything, a harbor task tree next, then the verifiers API version. */
3189
+ get kind() {
3190
+ if (this.isApiBundle) return "api";
3191
+ if (this.has(WORLD_MANIFEST)) return "mock-tools";
3192
+ if (this.taskDirs().length) return "harbor";
3193
+ return this.isVerifiersV1 ? "verifiers-v1" : "verifiers";
3194
+ }
3195
+ };
3196
+ }
3197
+ });
3198
+
3051
3199
  // src/worlds/hub.ts
3052
3200
  var hub_exports = {};
3053
3201
  __export(hub_exports, {
@@ -3056,7 +3204,6 @@ __export(hub_exports, {
3056
3204
  collectArchiveRelPaths: () => collectArchiveRelPaths,
3057
3205
  computeContentHash: () => computeContentHash,
3058
3206
  createRef: () => createRef,
3059
- isIncludedInContentHash: () => isIncludedInContentHash,
3060
3207
  localTreeState: () => localTreeState,
3061
3208
  propose: () => propose,
3062
3209
  pull: () => pull,
@@ -3066,53 +3213,18 @@ __export(hub_exports, {
3066
3213
  snapshotTreeHashes: () => snapshotTreeHashes,
3067
3214
  writeLocalMeta: () => writeLocalMeta
3068
3215
  });
3069
- function isExcludedDirComponent(component) {
3070
- return component.startsWith(".") || ROOT_EXCLUDED_DIRS.has(component) || component.endsWith(".egg-info");
3071
- }
3072
- function isIncludedInContentHash(relPath, includeAllRootFiles) {
3073
- const parts2 = relPath.split("/");
3074
- const name = parts2[parts2.length - 1];
3075
- const dirParts = parts2.slice(0, -1);
3076
- if (name.startsWith(".")) return false;
3077
- if (parts2.includes("__pycache__")) return false;
3078
- if (dirParts.length === 0) {
3079
- return includeAllRootFiles || name === "README.md" || name === "pyproject.toml" || BROAD_ROOT_MARKERS.includes(name) || name.endsWith(".py");
3080
- }
3081
- return !dirParts.some(isExcludedDirComponent);
3082
- }
3083
3216
  function collectArchiveRelPaths(dir) {
3084
- if (fs2.existsSync(path2.join(dir, ".gitignore"))) {
3217
+ const world = WorldDir.open(dir);
3218
+ if (world.hasRootGitignore) {
3085
3219
  throw new Error(
3086
3220
  "This bundle has a root .gitignore, which the Python CLI honors via gitignore_parser. Reimplementing that imperfectly here would silently produce a different content hash, so the TS CLI refuses. Remove the .gitignore (or bake its effect into the tree) and retry."
3087
3221
  );
3088
3222
  }
3089
- const out = [];
3090
- const includeAllRootFiles = BROAD_ROOT_MARKERS.some(
3091
- (marker) => fs2.existsSync(path2.join(dir, marker))
3092
- );
3093
- const walk = (rel) => {
3094
- const abs = rel ? path2.join(dir, rel) : dir;
3095
- for (const entry of fs2.readdirSync(abs, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
3096
- const childRel = rel ? `${rel}/${entry.name}` : entry.name;
3097
- if (entry.isDirectory()) {
3098
- if (!isExcludedDirComponent(entry.name)) walk(childRel);
3099
- } else if (entry.isFile()) {
3100
- if (isIncludedInContentHash(childRel, includeAllRootFiles)) {
3101
- out.push(childRel);
3102
- }
3103
- }
3104
- }
3105
- };
3106
- walk("");
3107
- return out.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
3223
+ return world.archivePaths;
3108
3224
  }
3109
3225
  function computeContentHash(dir) {
3110
- const hasher = (0, import_node_crypto4.createHash)("sha256");
3111
- for (const relPath of collectArchiveRelPaths(dir)) {
3112
- hasher.update(Buffer.from(`file:${relPath}`, "utf-8"));
3113
- hasher.update(fs2.readFileSync(path2.join(dir, relPath)));
3114
- }
3115
- return hasher.digest("hex");
3226
+ collectArchiveRelPaths(dir);
3227
+ return WorldDir.open(dir).contentHash;
3116
3228
  }
3117
3229
  function octal(value, length) {
3118
3230
  return Buffer.from(value.toString(8).padStart(length - 1, "0") + "\0", "ascii");
@@ -3160,14 +3272,14 @@ function tarMember(name, payload) {
3160
3272
  function buildSourceTarball(dir) {
3161
3273
  const parts2 = [];
3162
3274
  for (const relPath of collectArchiveRelPaths(dir)) {
3163
- parts2.push(...tarMember(relPath, fs2.readFileSync(path2.join(dir, relPath))));
3275
+ parts2.push(...tarMember(relPath, fs3.readFileSync(path3.join(dir, relPath))));
3164
3276
  }
3165
3277
  parts2.push(Buffer.alloc(1024));
3166
3278
  return (0, import_node_zlib.gzipSync)(Buffer.concat(parts2), { level: 9 });
3167
3279
  }
3168
3280
  function readLocalMeta(dir) {
3169
3281
  try {
3170
- const raw = fs2.readFileSync(path2.join(dir, META_RELPATH), "utf-8");
3282
+ const raw = fs3.readFileSync(path3.join(dir, META_RELPATH), "utf-8");
3171
3283
  const parsed = JSON.parse(raw);
3172
3284
  return parsed && typeof parsed === "object" ? parsed : null;
3173
3285
  } catch {
@@ -3178,16 +3290,16 @@ function pushSlug(dir, explicit) {
3178
3290
  if (explicit) return explicit;
3179
3291
  const meta = readLocalMeta(dir);
3180
3292
  if (typeof meta?.slug === "string" && meta.slug) return meta.slug;
3181
- return readPyproject(dir).name ?? path2.basename(path2.resolve(dir));
3293
+ return readPyproject(dir).name ?? path3.basename(path3.resolve(dir));
3182
3294
  }
3183
3295
  function writeLocalMeta(dir, meta) {
3184
- fs2.mkdirSync(path2.join(dir, ".gateway"), { recursive: true });
3185
- fs2.writeFileSync(path2.join(dir, META_RELPATH), JSON.stringify(meta, null, 2));
3296
+ fs3.mkdirSync(path3.join(dir, ".gateway"), { recursive: true });
3297
+ fs3.writeFileSync(path3.join(dir, META_RELPATH), JSON.stringify(meta, null, 2));
3186
3298
  }
3187
3299
  function snapshotTreeHashes(dir) {
3188
3300
  const out = {};
3189
3301
  for (const relPath of collectArchiveRelPaths(dir)) {
3190
- out[relPath] = (0, import_node_crypto4.createHash)("sha256").update(fs2.readFileSync(path2.join(dir, relPath))).digest("hex");
3302
+ out[relPath] = (0, import_node_crypto5.createHash)("sha256").update(fs3.readFileSync(path3.join(dir, relPath))).digest("hex");
3191
3303
  }
3192
3304
  return out;
3193
3305
  }
@@ -3205,7 +3317,7 @@ function localTreeState(dir) {
3205
3317
  }
3206
3318
  function readPyproject(dir) {
3207
3319
  try {
3208
- const text2 = fs2.readFileSync(path2.join(dir, "pyproject.toml"), "utf-8");
3320
+ const text2 = fs3.readFileSync(path3.join(dir, "pyproject.toml"), "utf-8");
3209
3321
  const section = /\[project\]([\s\S]*?)(\n\[|$)/.exec(text2)?.[1] ?? "";
3210
3322
  const name = /\bname\s*=\s*"([^"]+)"/.exec(section)?.[1];
3211
3323
  const version = /\bversion\s*=\s*"([^"]+)"/.exec(section)?.[1];
@@ -3215,33 +3327,32 @@ function readPyproject(dir) {
3215
3327
  }
3216
3328
  }
3217
3329
  function readWorldContractVersion(dir) {
3218
- for (const rel of ["schema/world.json", path2.join("server", "world", "schema", "world.json")]) {
3219
- try {
3220
- const parsed = JSON.parse(fs2.readFileSync(path2.join(dir, rel), "utf-8"));
3221
- const pkg = parsed["x-gateway"]?.package;
3222
- if (pkg?.version) return { name: pkg.id, version: pkg.version };
3223
- } catch {
3224
- }
3330
+ const world = WorldDir.open(dir);
3331
+ try {
3332
+ const parsed = JSON.parse(world.text(world.worldPath("schema/world.json")) ?? "");
3333
+ const pkg = parsed["x-gateway"]?.package;
3334
+ if (pkg?.version) return { name: pkg.id, version: pkg.version };
3335
+ } catch {
3225
3336
  }
3226
3337
  return {};
3227
3338
  }
3228
3339
  function buildFileManifest(dir) {
3229
3340
  const entries = [];
3230
3341
  const walk = (rel) => {
3231
- const abs = rel ? path2.join(dir, rel) : dir;
3232
- for (const entry of fs2.readdirSync(abs, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
3342
+ const abs = rel ? path3.join(dir, rel) : dir;
3343
+ for (const entry of fs3.readdirSync(abs, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
3233
3344
  const childRel = rel ? `${rel}/${entry.name}` : entry.name;
3234
3345
  if (entry.isDirectory()) {
3235
3346
  if (!SKIP_DIRS.has(entry.name) && !entry.name.endsWith(".egg-info")) {
3236
3347
  walk(childRel);
3237
3348
  }
3238
3349
  } else if (entry.isFile()) {
3239
- const payload = fs2.readFileSync(path2.join(dir, childRel));
3350
+ const payload = fs3.readFileSync(path3.join(dir, childRel));
3240
3351
  entries.push({
3241
3352
  path: childRel,
3242
3353
  isDirectory: false,
3243
3354
  size: payload.length,
3244
- sha256: (0, import_node_crypto4.createHash)("sha256").update(payload).digest("hex")
3355
+ sha256: (0, import_node_crypto5.createHash)("sha256").update(payload).digest("hex")
3245
3356
  });
3246
3357
  }
3247
3358
  }
@@ -3264,7 +3375,7 @@ async function putObject(url, data, shaB64) {
3264
3375
  }
3265
3376
  async function push(dir, opts = {}) {
3266
3377
  const options = opts.options ?? {};
3267
- if (!fs2.statSync(dir).isDirectory()) throw new Error(`Not a directory: ${dir}`);
3378
+ if (!fs3.statSync(dir).isDirectory()) throw new Error(`Not a directory: ${dir}`);
3268
3379
  const localMeta = readLocalMeta(dir) ?? {};
3269
3380
  const branch = opts.branch ?? localMeta.branch ?? DEFAULT_BRANCH;
3270
3381
  const baseVersionId = opts.baseVersionId ?? localMeta.versionId ?? null;
@@ -3272,18 +3383,18 @@ async function push(dir, opts = {}) {
3272
3383
  const pyproject = readPyproject(dir);
3273
3384
  const contractVersion = pyproject.version ? void 0 : readWorldContractVersion(dir).version;
3274
3385
  if (contractVersion) pyproject.version = contractVersion;
3275
- const slug = opts.slug ?? localMeta.slug ?? pyproject.name ?? path2.basename(path2.resolve(dir));
3386
+ const slug = opts.slug ?? localMeta.slug ?? pyproject.name ?? path3.basename(path3.resolve(dir));
3387
+ const metadata = {
3388
+ name: opts.name ?? pyproject.name ?? slug,
3389
+ ...opts.description !== void 0 ? { description: opts.description } : {},
3390
+ ...opts.tags !== void 0 ? { tags: opts.tags } : {},
3391
+ ...opts.visibility ? { visibility: opts.visibility } : {}
3392
+ };
3276
3393
  const resolve10 = await apiRequest(
3277
3394
  options,
3278
3395
  "POST",
3279
3396
  "/api/public/benchmark-containers/resolve",
3280
- {
3281
- slug,
3282
- name: opts.name ?? pyproject.name ?? slug,
3283
- ...opts.description ? { description: opts.description } : {},
3284
- ...opts.tags?.length ? { tags: opts.tags } : {},
3285
- ...opts.visibility ? { visibility: opts.visibility } : {}
3286
- }
3397
+ { slug, ...metadata }
3287
3398
  );
3288
3399
  const tarball = buildSourceTarball(dir);
3289
3400
  const bundleSha256 = sha256b64(tarball);
@@ -3307,7 +3418,7 @@ async function push(dir, opts = {}) {
3307
3418
  options,
3308
3419
  "POST",
3309
3420
  `/api/public/benchmark-containers/versions/${version.versionId}/finalize`,
3310
- { branch, baseVersionId, ...opts.force ? { force: true } : {} }
3421
+ { branch, baseVersionId, ...opts.force ? { force: true } : {}, ...metadata }
3311
3422
  );
3312
3423
  writeLocalMeta(dir, {
3313
3424
  ...localMeta,
@@ -3352,9 +3463,9 @@ function extractBundle(bundle, dir) {
3352
3463
  longName = null;
3353
3464
  if (typeflag !== "0" && typeflag !== "") continue;
3354
3465
  if (name.startsWith("/") || name.split("/").includes("..")) continue;
3355
- const target = path2.join(dir, name);
3356
- fs2.mkdirSync(path2.dirname(target), { recursive: true });
3357
- fs2.writeFileSync(target, body);
3466
+ const target = path3.join(dir, name);
3467
+ fs3.mkdirSync(path3.dirname(target), { recursive: true });
3468
+ fs3.writeFileSync(target, body);
3358
3469
  written++;
3359
3470
  }
3360
3471
  return written;
@@ -3370,13 +3481,13 @@ async function pull(slugRef, target, options = {}) {
3370
3481
  if (!details.downloadUrl) {
3371
3482
  throw new Error(`${slug}@${ref} resolved but has no uploaded bundle`);
3372
3483
  }
3373
- let dir = target ?? path2.join(process.cwd(), slug);
3484
+ let dir = target ?? path3.join(process.cwd(), slug);
3374
3485
  if (!target) {
3375
3486
  let i = 1;
3376
3487
  const base = dir;
3377
- while (fs2.existsSync(dir)) dir = `${base}-${i++}`;
3488
+ while (fs3.existsSync(dir)) dir = `${base}-${i++}`;
3378
3489
  }
3379
- fs2.mkdirSync(dir, { recursive: true });
3490
+ fs3.mkdirSync(dir, { recursive: true });
3380
3491
  const resp = await fetch(details.downloadUrl);
3381
3492
  if (!resp.ok) throw new Error(`bundle download -> ${resp.status}`);
3382
3493
  const bundle = Buffer.from(await resp.arrayBuffer());
@@ -3406,12 +3517,12 @@ async function propose(dir, opts) {
3406
3517
  const state2 = localTreeState(dir);
3407
3518
  if (state2.clean) throw new Error("Nothing to propose \u2014 the tree matches its base.");
3408
3519
  const changes = state2.dirty.map((relPath) => {
3409
- const abs = path2.join(dir, relPath);
3410
- if (!fs2.existsSync(abs)) return { path: relPath, action: "delete" };
3520
+ const abs = path3.join(dir, relPath);
3521
+ if (!fs3.existsSync(abs)) return { path: relPath, action: "delete" };
3411
3522
  return {
3412
3523
  path: relPath,
3413
3524
  action: "write",
3414
- newContent: fs2.readFileSync(abs, "utf-8")
3525
+ newContent: fs3.readFileSync(abs, "utf-8")
3415
3526
  };
3416
3527
  });
3417
3528
  const res = await apiRequest(
@@ -3437,17 +3548,18 @@ async function createRef(slug, name, kind, versionId, options = {}) {
3437
3548
  ...versionId ? { versionId } : {}
3438
3549
  });
3439
3550
  }
3440
- var import_node_crypto4, import_node_zlib, fs2, path2, DEFAULT_BRANCH, META_RELPATH, SKIP_DIRS, ROOT_EXCLUDED_DIRS, BROAD_ROOT_MARKERS, sha256b64;
3551
+ var import_node_crypto5, import_node_zlib, fs3, path3, DEFAULT_BRANCH, META_RELPATH, SKIP_DIRS, sha256b64;
3441
3552
  var init_hub = __esm({
3442
3553
  "src/worlds/hub.ts"() {
3443
3554
  "use strict";
3444
- import_node_crypto4 = require("crypto");
3555
+ import_node_crypto5 = require("crypto");
3445
3556
  import_node_zlib = require("zlib");
3446
- fs2 = __toESM(require("fs"));
3447
- path2 = __toESM(require("path"));
3557
+ fs3 = __toESM(require("fs"));
3558
+ path3 = __toESM(require("path"));
3448
3559
  init_worlds();
3560
+ init_worldDir();
3449
3561
  DEFAULT_BRANCH = "main";
3450
- META_RELPATH = path2.join(".gateway", ".env-metadata.json");
3562
+ META_RELPATH = path3.join(".gateway", ".env-metadata.json");
3451
3563
  SKIP_DIRS = /* @__PURE__ */ new Set([
3452
3564
  ".git",
3453
3565
  "__pycache__",
@@ -3458,9 +3570,7 @@ var init_hub = __esm({
3458
3570
  "build",
3459
3571
  "outputs"
3460
3572
  ]);
3461
- ROOT_EXCLUDED_DIRS = /* @__PURE__ */ new Set(["dist", "build", "outputs", "__pycache__"]);
3462
- BROAD_ROOT_MARKERS = ["gateway-env.toml", "gateway-api-world.toml"];
3463
- sha256b64 = (data) => (0, import_node_crypto4.createHash)("sha256").update(data).digest("base64");
3573
+ sha256b64 = (data) => (0, import_node_crypto5.createHash)("sha256").update(data).digest("base64");
3464
3574
  }
3465
3575
  });
3466
3576
 
@@ -3976,15 +4086,15 @@ function applyTransforms(value, chain) {
3976
4086
  for (const step of steps) out = step(out);
3977
4087
  return out;
3978
4088
  }
3979
- var import_node_crypto5, WHITESPACE, WHITESPACE_EDGES, WHITESPACE_RUN, NOT_DIGIT, STRIP_PREFIX, trim, emailLocalPart, emailDomain, stripPrefix, hex, SIMPLE, TRANSFORMS, text;
4089
+ var import_node_crypto6, WHITESPACE, WHITESPACE_EDGES, WHITESPACE_RUN, NOT_DIGIT, STRIP_PREFIX, trim, emailLocalPart, emailDomain, stripPrefix, hex, SIMPLE, TRANSFORMS, text;
3980
4090
  var init_transforms = __esm({
3981
4091
  "src/worlds/transforms.ts"() {
3982
4092
  "use strict";
3983
- import_node_crypto5 = require("crypto");
4093
+ import_node_crypto6 = require("crypto");
3984
4094
  init_json();
3985
4095
  WHITESPACE = " \n\r\f\v";
3986
- WHITESPACE_EDGES = /^[ \t\n\r\f\v]+|[ \t\n\r\f\v]+$/g;
3987
- WHITESPACE_RUN = /[ \t\n\r\f\v]+/g;
4096
+ WHITESPACE_EDGES = new RegExp(`^[${WHITESPACE}]+|[${WHITESPACE}]+$`, "g");
4097
+ WHITESPACE_RUN = new RegExp(`[${WHITESPACE}]+`, "g");
3988
4098
  NOT_DIGIT = /[^0-9]/g;
3989
4099
  STRIP_PREFIX = "strip_prefix";
3990
4100
  trim = (value) => value.replace(WHITESPACE_EDGES, "");
@@ -3997,7 +4107,7 @@ var init_transforms = __esm({
3997
4107
  return at === -1 ? "" : value.slice(at + 1).toLowerCase();
3998
4108
  };
3999
4109
  stripPrefix = (prefix) => (value) => value.startsWith(prefix) ? value.slice(prefix.length) : value;
4000
- hex = (algorithm, value) => (0, import_node_crypto5.createHash)(algorithm).update(value, "utf8").digest("hex");
4110
+ hex = (algorithm, value) => (0, import_node_crypto6.createHash)(algorithm).update(value, "utf8").digest("hex");
4001
4111
  SIMPLE = {
4002
4112
  lower: (value) => value.toLowerCase(),
4003
4113
  upper: (value) => value.toUpperCase(),
@@ -4029,7 +4139,7 @@ function pyText(value) {
4029
4139
  return pyFloatRepr(value);
4030
4140
  }
4031
4141
  function hashForm(slug, plaintext) {
4032
- return "sha256:" + (0, import_node_crypto6.createHash)("sha256").update(`${slug}:${pyText(plaintext)}`, "utf8").digest("hex");
4142
+ return "sha256:" + (0, import_node_crypto7.createHash)("sha256").update(`${slug}:${pyText(plaintext)}`, "utf8").digest("hex");
4033
4143
  }
4034
4144
  function preserveForm(slug, plaintext) {
4035
4145
  const kind = typeof plaintext === "string" ? "str" : isInt(plaintext) ? "int" : "float";
@@ -4038,12 +4148,12 @@ function preserveForm(slug, plaintext) {
4038
4148
  }
4039
4149
  function shapeText(slug, text2, kind) {
4040
4150
  const seed = Buffer.from(`${slug}:${text2}`, "utf8");
4041
- let digest = (0, import_node_crypto6.createHash)("sha256").update(seed).digest();
4151
+ let digest = (0, import_node_crypto7.createHash)("sha256").update(seed).digest();
4042
4152
  let cursor = 0;
4043
4153
  const out = [];
4044
4154
  for (const char of text2) {
4045
4155
  if (cursor === digest.length) {
4046
- digest = (0, import_node_crypto6.createHash)("sha256").update(Buffer.concat([digest, seed])).digest();
4156
+ digest = (0, import_node_crypto7.createHash)("sha256").update(Buffer.concat([digest, seed])).digest();
4047
4157
  cursor = 0;
4048
4158
  }
4049
4159
  const byte = digest[cursor];
@@ -4080,11 +4190,11 @@ function storedForms(world, field, plaintext, transform) {
4080
4190
  if (policy !== null) return [roundForm(plaintext, world.redact.round[field])];
4081
4191
  return [plaintext];
4082
4192
  }
4083
- var import_node_crypto6, isInt;
4193
+ var import_node_crypto7, isInt;
4084
4194
  var init_redaction = __esm({
4085
4195
  "src/worlds/redaction.ts"() {
4086
4196
  "use strict";
4087
- import_node_crypto6 = require("crypto");
4197
+ import_node_crypto7 = require("crypto");
4088
4198
  init_json();
4089
4199
  init_transforms();
4090
4200
  isInt = (value) => typeof value === "number" && Number.isInteger(value);
@@ -4092,8 +4202,9 @@ var init_redaction = __esm({
4092
4202
  });
4093
4203
 
4094
4204
  // src/worlds/query.ts
4095
- function queryRowsSearch(entity, opts = {}) {
4205
+ function queryRowsSearch(entity, opts = {}, ref) {
4096
4206
  const search = new URLSearchParams();
4207
+ if (ref) search.set("ref", ref);
4097
4208
  search.set("entity", entity);
4098
4209
  if (opts.where && Object.keys(opts.where).length) search.set("where", JSON.stringify(opts.where));
4099
4210
  if (opts.limit !== void 0) search.set("limit", String(opts.limit));
@@ -4103,17 +4214,15 @@ function queryRowsSearch(entity, opts = {}) {
4103
4214
  if (opts.compare) search.set("compare", "true");
4104
4215
  return `?${search.toString()}`;
4105
4216
  }
4106
- async function queryRows(slug, entity, opts = {}, options = {}) {
4107
- if (slug.includes("@"))
4108
- throw new Error(
4109
- `queryRows reads a world's head version: pass the slug without @ref (got ${slug})`
4110
- );
4217
+ async function queryRows(slugRef, entity, opts = {}, options = {}) {
4218
+ const [slug, ref] = slugRef.split("@", 2);
4219
+ if (!slug || ref === "") throw new Error(`queryRows needs a slug, optionally slug@ref (got ${slugRef})`);
4111
4220
  if (!entity) throw new Error("queryRows needs an entity");
4112
4221
  if (opts.compare && !opts.across) throw new Error("queryRows: compare needs across");
4113
4222
  return apiRequest(
4114
4223
  options,
4115
4224
  "GET",
4116
- `/api/public/worlds/${encodeURIComponent(slug)}/data${queryRowsSearch(entity, opts)}`
4225
+ `/api/public/worlds/${encodeURIComponent(slug)}/data${queryRowsSearch(entity, opts, ref)}`
4117
4226
  );
4118
4227
  }
4119
4228
  var init_query = __esm({
@@ -4190,13 +4299,13 @@ async function api(creds, method, route, body, init3 = {}) {
4190
4299
  clearTimeout(timer);
4191
4300
  }
4192
4301
  }
4193
- var fs3, os, path3, ApiError;
4302
+ var fs4, os, path4, ApiError;
4194
4303
  var init_config = __esm({
4195
4304
  "src/cli/config.ts"() {
4196
4305
  "use strict";
4197
- fs3 = __toESM(require("fs"));
4306
+ fs4 = __toESM(require("fs"));
4198
4307
  os = __toESM(require("os"));
4199
- path3 = __toESM(require("path"));
4308
+ path4 = __toESM(require("path"));
4200
4309
  init_router();
4201
4310
  ApiError = class extends CliError {
4202
4311
  constructor(status, method, route, text2) {
@@ -4225,16 +4334,16 @@ function runtimeRoot() {
4225
4334
  const candidates = [];
4226
4335
  if (process.env.GATEWAY_RUNTIME_PATH)
4227
4336
  candidates.push(process.env.GATEWAY_RUNTIME_PATH);
4228
- const entry = process.argv[1] && fs4.existsSync(process.argv[1]) ? path4.dirname(fs4.realpathSync(process.argv[1])) : null;
4337
+ const entry = process.argv[1] && fs5.existsSync(process.argv[1]) ? path5.dirname(fs5.realpathSync(process.argv[1])) : null;
4229
4338
  if (entry) {
4230
- candidates.push(path4.resolve(entry, "..", "runtime"));
4231
- candidates.push(path4.resolve(entry, "..", "..", "runtime"));
4232
- candidates.push(path4.resolve(entry, "..", "..", "sdk", "src"));
4339
+ candidates.push(path5.resolve(entry, "..", "runtime"));
4340
+ candidates.push(path5.resolve(entry, "..", "..", "runtime"));
4341
+ candidates.push(path5.resolve(entry, "..", "..", "sdk", "src"));
4233
4342
  }
4234
- candidates.push(path4.resolve(process.cwd(), "runtime"));
4343
+ candidates.push(path5.resolve(process.cwd(), "runtime"));
4235
4344
  for (const root of candidates)
4236
- if (fs4.existsSync(
4237
- path4.join(root, "gatewaysdk", "environment", "schema", "platform.py")
4345
+ if (fs5.existsSync(
4346
+ path5.join(root, "gatewaysdk", "environment", "schema", "platform.py")
4238
4347
  ))
4239
4348
  return root;
4240
4349
  return null;
@@ -4375,14 +4484,14 @@ async function localBridge(request, local, opts = {}) {
4375
4484
  child.stdin.end(input);
4376
4485
  });
4377
4486
  }
4378
- var import_node_child_process, fs4, net, path4, MIN_PYTHON, DIAGNOSTIC_TAIL, BRIDGE_BOOTSTRAP, pythonCache, pythonProbes, PYTHON_CANDIDATES, UV_FIND;
4487
+ var import_node_child_process, fs5, net, path5, MIN_PYTHON, DIAGNOSTIC_TAIL, BRIDGE_BOOTSTRAP, pythonCache, pythonProbes, PYTHON_CANDIDATES, UV_FIND;
4379
4488
  var init_local = __esm({
4380
4489
  "src/cli/runtime/local.ts"() {
4381
4490
  "use strict";
4382
4491
  import_node_child_process = require("child_process");
4383
- fs4 = __toESM(require("fs"));
4492
+ fs5 = __toESM(require("fs"));
4384
4493
  net = __toESM(require("net"));
4385
- path4 = __toESM(require("path"));
4494
+ path5 = __toESM(require("path"));
4386
4495
  init_router();
4387
4496
  init_config();
4388
4497
  MIN_PYTHON = [3, 11];
@@ -4410,12 +4519,12 @@ function isBuildOutput(relPath) {
4410
4519
  return BUILD_OUTPUT.test(relPath);
4411
4520
  }
4412
4521
  function readWorldFiles(dir, opts = {}) {
4413
- if (!fs5.existsSync(dir) || !fs5.statSync(dir).isDirectory())
4522
+ if (!fs6.existsSync(dir) || !fs6.statSync(dir).isDirectory())
4414
4523
  throw new CliError(`Not a directory: ${dir}`);
4415
4524
  const out = [];
4416
4525
  const walk = (rel) => {
4417
- const abs = rel ? path5.join(dir, rel) : dir;
4418
- const entries = fs5.readdirSync(abs, { withFileTypes: true });
4526
+ const abs = rel ? path6.join(dir, rel) : dir;
4527
+ const entries = fs6.readdirSync(abs, { withFileTypes: true });
4419
4528
  entries.sort((a, b) => a.name.localeCompare(b.name));
4420
4529
  for (const entry of entries) {
4421
4530
  const childRel = rel ? `${rel}/${entry.name}` : entry.name;
@@ -4425,7 +4534,7 @@ function readWorldFiles(dir, opts = {}) {
4425
4534
  if (!opts.buildOutputs && isBuildOutput(childRel)) continue;
4426
4535
  out.push({
4427
4536
  path: childRel,
4428
- content: fs5.readFileSync(path5.join(dir, childRel)).toString("base64")
4537
+ content: fs6.readFileSync(path6.join(dir, childRel)).toString("base64")
4429
4538
  });
4430
4539
  }
4431
4540
  }
@@ -4440,19 +4549,19 @@ function assertSafeRelPath(rel) {
4440
4549
  }
4441
4550
  function writeWorldFiles(dir, files, opts = {}) {
4442
4551
  for (const file of files) assertSafeRelPath(file.path);
4443
- if (opts.clean && fs5.existsSync(dir)) {
4552
+ if (opts.clean && fs6.existsSync(dir)) {
4444
4553
  const keep = new Set(files.map((f) => f.path));
4445
4554
  for (const existing of readWorldFiles(dir)) {
4446
- if (!keep.has(existing.path)) fs5.rmSync(path5.join(dir, existing.path));
4555
+ if (!keep.has(existing.path)) fs6.rmSync(path6.join(dir, existing.path));
4447
4556
  }
4448
4557
  pruneEmptyDirs(dir);
4449
4558
  }
4450
- fs5.mkdirSync(dir, { recursive: true });
4559
+ fs6.mkdirSync(dir, { recursive: true });
4451
4560
  const written = [];
4452
4561
  for (const file of files) {
4453
- const target = path5.join(dir, file.path);
4454
- fs5.mkdirSync(path5.dirname(target), { recursive: true });
4455
- fs5.writeFileSync(target, Buffer.from(file.content, "base64"));
4562
+ const target = path6.join(dir, file.path);
4563
+ fs6.mkdirSync(path6.dirname(target), { recursive: true });
4564
+ fs6.writeFileSync(target, Buffer.from(file.content, "base64"));
4456
4565
  written.push(file.path);
4457
4566
  }
4458
4567
  return written;
@@ -4460,14 +4569,14 @@ function writeWorldFiles(dir, files, opts = {}) {
4460
4569
  function pruneEmptyDirs(root) {
4461
4570
  const walk = (abs) => {
4462
4571
  let empty = true;
4463
- for (const entry of fs5.readdirSync(abs, { withFileTypes: true })) {
4464
- const child = path5.join(abs, entry.name);
4572
+ for (const entry of fs6.readdirSync(abs, { withFileTypes: true })) {
4573
+ const child = path6.join(abs, entry.name);
4465
4574
  if (entry.isDirectory()) {
4466
4575
  if (SKIP_DIRS2.has(entry.name)) {
4467
4576
  empty = false;
4468
4577
  continue;
4469
4578
  }
4470
- if (walk(child)) fs5.rmdirSync(child);
4579
+ if (walk(child)) fs6.rmdirSync(child);
4471
4580
  else empty = false;
4472
4581
  } else empty = false;
4473
4582
  }
@@ -4531,12 +4640,12 @@ async function runtime(creds, request, opts = {}) {
4531
4640
  clearTimeout(timer);
4532
4641
  }
4533
4642
  }
4534
- var fs5, path5, SKIP_DIRS2, BUILD_OUTPUT, BridgeRejected;
4643
+ var fs6, path6, SKIP_DIRS2, BUILD_OUTPUT, BridgeRejected;
4535
4644
  var init_client = __esm({
4536
4645
  "src/cli/runtime/client.ts"() {
4537
4646
  "use strict";
4538
- fs5 = __toESM(require("fs"));
4539
- path5 = __toESM(require("path"));
4647
+ fs6 = __toESM(require("fs"));
4648
+ path6 = __toESM(require("path"));
4540
4649
  init_router();
4541
4650
  init_local();
4542
4651
  SKIP_DIRS2 = /* @__PURE__ */ new Set(["__pycache__", ".git", "node_modules", ".gateway"]);
@@ -4586,7 +4695,7 @@ function dropBuildOutputs(dir) {
4586
4695
  const dropped = [];
4587
4696
  for (const file of readWorldFiles(dir, { buildOutputs: true })) {
4588
4697
  if (!BUILD_OUTPUT2.test(file.path)) continue;
4589
- fs6.rmSync(path6.join(dir, file.path), { force: true });
4698
+ fs7.rmSync(path7.join(dir, file.path), { force: true });
4590
4699
  dropped.push(file.path);
4591
4700
  }
4592
4701
  return dropped;
@@ -4597,6 +4706,7 @@ async function checkLocalWorldData(dir, rows, creds, opts = {}) {
4597
4706
  files: readWorldFiles(dir),
4598
4707
  rows,
4599
4708
  mode: "append",
4709
+ dry_run: true,
4600
4710
  ...opts.redact && opts.redact !== "off" ? { redact: opts.redact } : {}
4601
4711
  });
4602
4712
  return {
@@ -4652,7 +4762,7 @@ async function queryLocalWorldDataAcross(dir, entity, where, opts) {
4652
4762
  const payload = await localBridge(
4653
4763
  {
4654
4764
  command: "query",
4655
- world: path6.resolve(dir),
4765
+ world: path7.resolve(dir),
4656
4766
  entity,
4657
4767
  across: true,
4658
4768
  ...opts.compare ? { compare: true } : {},
@@ -4699,12 +4809,12 @@ async function ingestLocalToolCalls(dir, records, opts, creds) {
4699
4809
  ...res.batch !== void 0 ? { batch: res.batch } : {}
4700
4810
  };
4701
4811
  }
4702
- var fs6, path6, BUILD_OUTPUT2;
4812
+ var fs7, path7, BUILD_OUTPUT2;
4703
4813
  var init_data = __esm({
4704
4814
  "src/cli/runtime/data.ts"() {
4705
4815
  "use strict";
4706
- fs6 = __toESM(require("fs"));
4707
- path6 = __toESM(require("path"));
4816
+ fs7 = __toESM(require("fs"));
4817
+ path7 = __toESM(require("path"));
4708
4818
  init_router();
4709
4819
  init_client();
4710
4820
  init_local();
@@ -4747,27 +4857,27 @@ function typescriptPrefix() {
4747
4857
  }
4748
4858
  }
4749
4859
  function command(script, wrapperDir) {
4750
- const suffix = path7.extname(script).toLowerCase();
4860
+ const suffix = path8.extname(script).toLowerCase();
4751
4861
  if (PYTHON_SUFFIXES.includes(suffix)) return { file: process.env.GATEWAY_PYTHON || "python3", args: ["-c", PY_WRAPPER, script] };
4752
4862
  if (NODE_SUFFIXES.includes(suffix)) {
4753
- const wrapper = path7.join(wrapperDir, "transform-wrapper.mjs");
4754
- fs7.writeFileSync(wrapper, NODE_WRAPPER);
4863
+ const wrapper = path8.join(wrapperDir, "transform-wrapper.mjs");
4864
+ fs8.writeFileSync(wrapper, NODE_WRAPPER);
4755
4865
  const flags = suffix === ".ts" || suffix === ".mts" ? typescriptPrefix() : [];
4756
4866
  return { file: process.env.GATEWAY_NODE || process.execPath, args: [...flags, wrapper, script] };
4757
4867
  }
4758
- throw new CliError(`${path7.basename(script)}: a transform script is .py, .ts, .mjs, .js or .cjs`, 1);
4868
+ throw new CliError(`${path8.basename(script)}: a transform script is .py, .ts, .mjs, .js or .cjs`, 1);
4759
4869
  }
4760
4870
  async function runTransform(script, records, opts = {}) {
4761
- if (!fs7.existsSync(script) || !fs7.statSync(script).isFile()) throw new CliError(`no transform script at ${script}`, 1);
4762
- const resolved = path7.resolve(script);
4763
- const name = path7.basename(script);
4871
+ if (!fs8.existsSync(script) || !fs8.statSync(script).isFile()) throw new CliError(`no transform script at ${script}`, 1);
4872
+ const resolved = path8.resolve(script);
4873
+ const name = path8.basename(script);
4764
4874
  const timeoutMs = opts.timeoutMs ?? DEFAULT_TRANSFORM_TIMEOUT_MS;
4765
- const scratch = fs7.mkdtempSync(path7.join(os2.tmpdir(), "gateway-transform-"));
4875
+ const scratch = fs8.mkdtempSync(path8.join(os2.tmpdir(), "gateway-transform-"));
4766
4876
  try {
4767
4877
  const { file, args } = command(resolved, scratch);
4768
4878
  const env = Object.fromEntries(Object.entries(process.env).filter(([key2]) => !SCRUBBED.test(key2)));
4769
4879
  const done = await new Promise((resolve10, reject) => {
4770
- const child = (0, import_node_child_process2.spawn)(file, args, { cwd: path7.dirname(resolved), env, stdio: ["pipe", "pipe", "pipe"] });
4880
+ const child = (0, import_node_child_process2.spawn)(file, args, { cwd: path8.dirname(resolved), env, stdio: ["pipe", "pipe", "pipe"] });
4771
4881
  let stdout = "";
4772
4882
  let stderr = "";
4773
4883
  let timedOut = false;
@@ -4798,21 +4908,21 @@ async function runTransform(script, records, opts = {}) {
4798
4908
  }
4799
4909
  return { rows: checkRows(value, name), stderr: done.stderr };
4800
4910
  } finally {
4801
- fs7.rmSync(scratch, { recursive: true, force: true });
4911
+ fs8.rmSync(scratch, { recursive: true, force: true });
4802
4912
  }
4803
4913
  }
4804
4914
  async function transformRecords(transform, records, opts = {}) {
4805
4915
  if (typeof transform === "function") return { rows: checkRows(await transform(records), "transform(records)"), stderr: "" };
4806
4916
  return runTransform(transform, records, opts);
4807
4917
  }
4808
- var import_node_child_process2, fs7, os2, path7, import_node_module, import_meta, DEFAULT_TRANSFORM_TIMEOUT_MS, NODE_SUFFIXES, PYTHON_SUFFIXES, SCRUBBED, PY_WRAPPER, NODE_WRAPPER, isObject, tail;
4918
+ var import_node_child_process2, fs8, os2, path8, import_node_module, import_meta, DEFAULT_TRANSFORM_TIMEOUT_MS, NODE_SUFFIXES, PYTHON_SUFFIXES, SCRUBBED, PY_WRAPPER, NODE_WRAPPER, isObject, tail;
4809
4919
  var init_transform = __esm({
4810
4920
  "src/cli/platform/worldData/transform.ts"() {
4811
4921
  "use strict";
4812
4922
  import_node_child_process2 = require("child_process");
4813
- fs7 = __toESM(require("fs"));
4923
+ fs8 = __toESM(require("fs"));
4814
4924
  os2 = __toESM(require("os"));
4815
- path7 = __toESM(require("path"));
4925
+ path8 = __toESM(require("path"));
4816
4926
  import_node_module = require("module");
4817
4927
  init_router();
4818
4928
  import_meta = {};
@@ -4896,11 +5006,16 @@ if (fn) {
4896
5006
  });
4897
5007
 
4898
5008
  // src/cli/platform/worldData/batches.ts
5009
+ function isSettled(status) {
5010
+ if (!TERMINAL_STATES.has(status.state)) return false;
5011
+ if (status.state !== "applied") return true;
5012
+ return status.dryRun === true || status.publish !== "now" || !status.snapshotId;
5013
+ }
4899
5014
  function uploadHeadersFor(gz) {
4900
5015
  return {
4901
5016
  "content-type": "application/gzip",
4902
5017
  "content-length": String(gz.length),
4903
- "x-amz-checksum-sha256": (0, import_node_crypto7.createHash)("sha256").update(gz).digest("base64")
5018
+ "x-amz-checksum-sha256": (0, import_node_crypto8.createHash)("sha256").update(gz).digest("base64")
4904
5019
  };
4905
5020
  }
4906
5021
  async function forEachLimited(items, limit, fn) {
@@ -4937,7 +5052,7 @@ async function waitForBatch(client2, batchId, opts = {}) {
4937
5052
  opts.onPhase?.(phase);
4938
5053
  last = phase;
4939
5054
  }
4940
- if (TERMINAL_STATES.has(status.state)) return status;
5055
+ if (isSettled(status)) return status;
4941
5056
  await sleep3(delay);
4942
5057
  delay = Math.min(1e4, Math.round(delay * 1.5));
4943
5058
  }
@@ -4946,12 +5061,12 @@ function phaseLine(status) {
4946
5061
  const phase = status.progress?.phase;
4947
5062
  return phase ? `${status.state} (${phase})` : status.state;
4948
5063
  }
4949
- var import_node_crypto7, fs8, TERMINAL_STATES, sleepMs, WorldDataApi;
5064
+ var import_node_crypto8, fs9, TERMINAL_STATES, sleepMs, WorldDataApi;
4950
5065
  var init_batches = __esm({
4951
5066
  "src/cli/platform/worldData/batches.ts"() {
4952
5067
  "use strict";
4953
- import_node_crypto7 = require("crypto");
4954
- fs8 = __toESM(require("fs"));
5068
+ import_node_crypto8 = require("crypto");
5069
+ fs9 = __toESM(require("fs"));
4955
5070
  init_config();
4956
5071
  init_router();
4957
5072
  TERMINAL_STATES = /* @__PURE__ */ new Set(["applied", "refused", "published", "failed"]);
@@ -5062,12 +5177,12 @@ function finishChunk(ordinal, raw, rows, entity, firstRow = 0) {
5062
5177
  const gz = gzipDeterministic(raw, { name: chunkName(ordinal) });
5063
5178
  return {
5064
5179
  ordinal,
5065
- digest: (0, import_node_crypto8.createHash)("sha256").update(gz).digest("hex"),
5180
+ digest: (0, import_node_crypto9.createHash)("sha256").update(gz).digest("hex"),
5066
5181
  bytes: gz.length,
5067
5182
  rows,
5068
5183
  entity,
5069
5184
  rawBytes: raw.length,
5070
- contentSha256: (0, import_node_crypto8.createHash)("sha256").update(raw).digest("hex"),
5185
+ contentSha256: (0, import_node_crypto9.createHash)("sha256").update(raw).digest("hex"),
5071
5186
  firstRow,
5072
5187
  gz
5073
5188
  };
@@ -5095,11 +5210,11 @@ function crc32(data) {
5095
5210
  for (let i = 0; i < data.length; i++) crc = table[(crc ^ data[i]) & 255] ^ crc >>> 8;
5096
5211
  return (crc ^ 4294967295) >>> 0;
5097
5212
  }
5098
- var import_node_crypto8, import_node_zlib2, DEFAULT_CHUNK_BYTES, GZIP_LEVEL, chunkName, table;
5213
+ var import_node_crypto9, import_node_zlib2, DEFAULT_CHUNK_BYTES, GZIP_LEVEL, chunkName, table;
5099
5214
  var init_chunker = __esm({
5100
5215
  "src/cli/platform/worldData/chunker.ts"() {
5101
5216
  "use strict";
5102
- import_node_crypto8 = require("crypto");
5217
+ import_node_crypto9 = require("crypto");
5103
5218
  import_node_zlib2 = require("zlib");
5104
5219
  init_json();
5105
5220
  DEFAULT_CHUNK_BYTES = 64 * 1024 * 1024;
@@ -5172,7 +5287,7 @@ function parseToolCallRecord(raw) {
5172
5287
  }
5173
5288
  function readToolCallRecords(paths) {
5174
5289
  const records = [];
5175
- for (const file of paths) records.push(...toolCallRecordsIn(fs9.readFileSync(file, "utf8"), file));
5290
+ for (const file of paths) records.push(...toolCallRecordsIn(fs10.readFileSync(file, "utf8"), file));
5176
5291
  return records;
5177
5292
  }
5178
5293
  function toolCallRecordsIn(text2, where) {
@@ -5208,7 +5323,7 @@ async function emit(sink, record) {
5208
5323
  return;
5209
5324
  }
5210
5325
  if (typeof sink === "string") {
5211
- fs9.appendFileSync(sink, JSON.stringify(record) + "\n");
5326
+ fs10.appendFileSync(sink, JSON.stringify(record) + "\n");
5212
5327
  return;
5213
5328
  }
5214
5329
  if (typeof sink === "function") {
@@ -5239,14 +5354,6 @@ function captureToolCalls(tools, sink, opts = {}) {
5239
5354
  }
5240
5355
  return wrapped;
5241
5356
  }
5242
- function jsonish(value) {
5243
- if (typeof value !== "string") return value;
5244
- try {
5245
- return JSON.parse(value);
5246
- } catch {
5247
- return value;
5248
- }
5249
- }
5250
5357
  function toolCallsFromObservations(observations, opts = {}) {
5251
5358
  const known = opts.tools ? new Set(opts.tools) : null;
5252
5359
  const sinceMs = opts.since ? Date.parse(opts.since) : NaN;
@@ -5273,10 +5380,9 @@ function toolCallsFromObservations(observations, opts = {}) {
5273
5380
  out.unknownTools[tool] = (out.unknownTools[tool] ?? 0) + 1;
5274
5381
  continue;
5275
5382
  }
5276
- const input = jsonish(observation.input);
5277
- const record = { tool, args: isObject2(input) ? input : {} };
5383
+ const record = { tool, args: isObject2(observation.input) ? observation.input : {} };
5278
5384
  if (observation.level === "ERROR") record.error = observation.statusMessage || "ERROR";
5279
- else record.result = jsonish(observation.output);
5385
+ else record.result = observation.output;
5280
5386
  if (at !== void 0) record.at = at;
5281
5387
  if (opts.session) record.session = opts.session;
5282
5388
  record.source = `trace:${observation.traceId ?? "?"}/${observation.id ?? "?"}`;
@@ -5297,7 +5403,7 @@ async function ingest(world, records, options = {}) {
5297
5403
  const mode = options.mode ?? "append";
5298
5404
  const dryRun = Boolean(options.dryRun);
5299
5405
  const creds = credentialsOf(options);
5300
- const local = fs9.existsSync(world) && fs9.statSync(world).isDirectory();
5406
+ const local = fs10.existsSync(world) && fs10.statSync(world).isDirectory();
5301
5407
  const map = options.map === void 0 ? void 0 : options.map;
5302
5408
  let rows = null;
5303
5409
  let stderr = "";
@@ -5313,9 +5419,9 @@ async function ingest(world, records, options = {}) {
5313
5419
  if (!creds) throw new Error("Gateway keys missing: set GATEWAY_PUBLIC_KEY / GATEWAY_SECRET_KEY (or pass publicKey/secretKey).");
5314
5420
  const { pull: pull2 } = await Promise.resolve().then(() => (init_hub(), hub_exports));
5315
5421
  const slug = world.split("@", 1)[0];
5316
- const scratch = fs9.mkdtempSync(path8.join(os3.tmpdir(), "gateway-ingest-"));
5422
+ const scratch = fs10.mkdtempSync(path9.join(os3.tmpdir(), "gateway-ingest-"));
5317
5423
  try {
5318
- const pulled = await pull2(world, path8.join(scratch, slug), options);
5424
+ const pulled = await pull2(world, path9.join(scratch, slug), options);
5319
5425
  let report;
5320
5426
  let projected;
5321
5427
  if (rows === null) {
@@ -5336,7 +5442,7 @@ async function ingest(world, records, options = {}) {
5336
5442
  if (status.entityCounts) report.entityCounts = status.entityCounts;
5337
5443
  return report;
5338
5444
  } finally {
5339
- fs9.rmSync(scratch, { recursive: true, force: true });
5445
+ fs10.rmSync(scratch, { recursive: true, force: true });
5340
5446
  }
5341
5447
  }
5342
5448
  async function ingestToolCalls(world, records, options = {}) {
@@ -5389,13 +5495,13 @@ async function sessionToolObservations(sessionId, options = {}) {
5389
5495
  for (const observation of trace5.observations ?? []) out.push({ traceId: trace5.id ?? null, ...observation });
5390
5496
  return out;
5391
5497
  }
5392
- var fs9, os3, path8, isObject2, isoOf;
5498
+ var fs10, os3, path9, isObject2, isoOf;
5393
5499
  var init_ingest = __esm({
5394
5500
  "src/worlds/ingest.ts"() {
5395
5501
  "use strict";
5396
- fs9 = __toESM(require("fs"));
5502
+ fs10 = __toESM(require("fs"));
5397
5503
  os3 = __toESM(require("os"));
5398
- path8 = __toESM(require("path"));
5504
+ path9 = __toESM(require("path"));
5399
5505
  init_worlds();
5400
5506
  isObject2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
5401
5507
  isoOf = (value) => value instanceof Date ? value.toISOString() : typeof value === "string" ? value : void 0;
@@ -5449,7 +5555,6 @@ __export(worlds_exports, {
5449
5555
  hashForm: () => hashForm,
5450
5556
  ingest: () => ingest,
5451
5557
  ingestToolCalls: () => ingestToolCalls,
5452
- isIncludedInContentHash: () => isIncludedInContentHash,
5453
5558
  isTaskIdRef: () => isTaskIdRef,
5454
5559
  isTaskManifest: () => isTaskManifest,
5455
5560
  isTaskSpec: () => isTaskSpec,
@@ -5515,9 +5620,9 @@ function resolveEnv(options) {
5515
5620
  }
5516
5621
  return { host: host.replace(/\/+$/, ""), publicKey, secretKey };
5517
5622
  }
5518
- async function apiRequest(options, method, path13, body) {
5623
+ async function apiRequest(options, method, path14, body) {
5519
5624
  const { host, publicKey, secretKey } = resolveEnv(options);
5520
- const res = await fetch(`${host}${path13}`, {
5625
+ const res = await fetch(`${host}${path14}`, {
5521
5626
  method,
5522
5627
  headers: {
5523
5628
  "content-type": "application/json",
@@ -5526,7 +5631,7 @@ async function apiRequest(options, method, path13, body) {
5526
5631
  ...body === void 0 ? {} : { body: JSON.stringify(body) }
5527
5632
  });
5528
5633
  const text2 = await res.text();
5529
- if (!res.ok) throw new ApiError2(res.status, method, path13, text2.slice(0, 400));
5634
+ if (!res.ok) throw new ApiError2(res.status, method, path14, text2.slice(0, 400));
5530
5635
  return JSON.parse(text2);
5531
5636
  }
5532
5637
  async function setEnvSecret(slug, key2, value, options = {}) {
@@ -5697,8 +5802,8 @@ var init_worlds = __esm({
5697
5802
  init_migrate();
5698
5803
  init_ingest();
5699
5804
  ApiError2 = class extends Error {
5700
- constructor(status, method, path13, body) {
5701
- super(`${method} ${path13} -> ${status}: ${body}`);
5805
+ constructor(status, method, path14, body) {
5806
+ super(`${method} ${path14} -> ${status}: ${body}`);
5702
5807
  this.status = status;
5703
5808
  this.name = "ApiError";
5704
5809
  }
@@ -5879,7 +5984,6 @@ __export(src_exports, {
5879
5984
  identify: () => identify,
5880
5985
  ingest: () => ingest,
5881
5986
  ingestToolCalls: () => ingestToolCalls,
5882
- isIncludedInContentHash: () => isIncludedInContentHash,
5883
5987
  isTaskIdRef: () => isTaskIdRef,
5884
5988
  isTaskManifest: () => isTaskManifest,
5885
5989
  isTaskSpec: () => isTaskSpec,
@@ -6527,8 +6631,8 @@ var GatewayContext = class _GatewayContext {
6527
6631
  }
6528
6632
  return resolved;
6529
6633
  }
6530
- async requestJson(method, path13, payload) {
6531
- const response = await fetch(`${this.host}${path13}`, {
6634
+ async requestJson(method, path14, payload) {
6635
+ const response = await fetch(`${this.host}${path14}`, {
6532
6636
  method,
6533
6637
  headers: {
6534
6638
  Authorization: this.authHeader(),
@@ -6539,7 +6643,7 @@ var GatewayContext = class _GatewayContext {
6539
6643
  const text2 = await response.text();
6540
6644
  const body = text2 ? safeJson(text2) : {};
6541
6645
  if (!response.ok) {
6542
- const message = typeof body.message === "string" ? body.message : `Gateway API ${response.status} on ${path13}`;
6646
+ const message = typeof body.message === "string" ? body.message : `Gateway API ${response.status} on ${path14}`;
6543
6647
  if (response.status === 409) {
6544
6648
  throw new GatewayContextConflictError(
6545
6649
  message,
@@ -6548,7 +6652,7 @@ var GatewayContext = class _GatewayContext {
6548
6652
  }
6549
6653
  throw new GatewayContextError(message);
6550
6654
  }
6551
- this.log("%s %s -> %s", method, path13, response.status);
6655
+ this.log("%s %s -> %s", method, path14, response.status);
6552
6656
  return body;
6553
6657
  }
6554
6658
  authHeader() {
@@ -6655,11 +6759,11 @@ function primaryPathForKind(kind, snapshot) {
6655
6759
  const preferred = kind === "agent" ? "AGENTS.md" : kind === "prompt" ? "PROMPT.md" : kind === "skill" ? "SKILL.md" : "MEMORY.md";
6656
6760
  if (readFile(snapshot, preferred)) return preferred;
6657
6761
  return Object.entries(snapshot.files).find(
6658
- ([path13, entry]) => entry.type === "file" && path13.endsWith(".md")
6762
+ ([path14, entry]) => entry.type === "file" && path14.endsWith(".md")
6659
6763
  )?.[0] ?? null;
6660
6764
  }
6661
- function parseJsonFile(snapshot, path13) {
6662
- const content = readFile(snapshot, path13);
6765
+ function parseJsonFile(snapshot, path14) {
6766
+ const content = readFile(snapshot, path14);
6663
6767
  if (!content) return {};
6664
6768
  try {
6665
6769
  const parsed = JSON.parse(content);
@@ -6668,8 +6772,8 @@ function parseJsonFile(snapshot, path13) {
6668
6772
  return {};
6669
6773
  }
6670
6774
  }
6671
- function readFile(snapshot, path13) {
6672
- const entry = snapshot.files[path13];
6775
+ function readFile(snapshot, path14) {
6776
+ const entry = snapshot.files[path14];
6673
6777
  return entry?.type === "file" ? entry.content : null;
6674
6778
  }
6675
6779
  function provenanceFor(snapshot, label) {
@@ -6771,16 +6875,16 @@ var GatewayMemory = class _GatewayMemory {
6771
6875
  `/api/public/context/memory/${encodeIdentifier2(identifier)}${suffix}`
6772
6876
  );
6773
6877
  }
6774
- async read(target, path13, options = {}) {
6878
+ async read(target, path14, options = {}) {
6775
6879
  const snapshot = typeof target === "string" ? await this.pull(target, options) : target;
6776
- const file = snapshot.files[path13];
6880
+ const file = snapshot.files[path14];
6777
6881
  return file?.type === "file" ? file.content : null;
6778
6882
  }
6779
- async write(target, path13, content, options = {}) {
6883
+ async write(target, path14, content, options = {}) {
6780
6884
  const snapshot = typeof target === "string" ? await this.pull(target) : target;
6781
6885
  return this.push(snapshot.repo.repoHandle, {
6782
6886
  files: {
6783
- [path13]: {
6887
+ [path14]: {
6784
6888
  content,
6785
6889
  ...options.mimeType ? { mimeType: options.mimeType } : {}
6786
6890
  }
@@ -6790,10 +6894,10 @@ var GatewayMemory = class _GatewayMemory {
6790
6894
  ...runtimeContextPayload2(options)
6791
6895
  });
6792
6896
  }
6793
- async delete(target, path13, options = {}) {
6897
+ async delete(target, path14, options = {}) {
6794
6898
  const snapshot = typeof target === "string" ? await this.pull(target) : target;
6795
6899
  return this.push(snapshot.repo.repoHandle, {
6796
- files: { [path13]: null },
6900
+ files: { [path14]: null },
6797
6901
  parentCommit: options.parentCommit ?? snapshot.commit.commitHash,
6798
6902
  message: options.message,
6799
6903
  ...runtimeContextPayload2(options)
@@ -6806,8 +6910,8 @@ var GatewayMemory = class _GatewayMemory {
6806
6910
  payload
6807
6911
  );
6808
6912
  }
6809
- async requestJson(method, path13, payload) {
6810
- const response = await fetch(`${this.host}${path13}`, {
6913
+ async requestJson(method, path14, payload) {
6914
+ const response = await fetch(`${this.host}${path14}`, {
6811
6915
  method,
6812
6916
  headers: {
6813
6917
  Authorization: this.authHeader(),
@@ -6818,7 +6922,7 @@ var GatewayMemory = class _GatewayMemory {
6818
6922
  const text2 = await response.text();
6819
6923
  const body = text2 ? safeJson2(text2) : {};
6820
6924
  if (!response.ok) {
6821
- const message = typeof body.message === "string" ? body.message : `Gateway API ${response.status} on ${path13}`;
6925
+ const message = typeof body.message === "string" ? body.message : `Gateway API ${response.status} on ${path14}`;
6822
6926
  if (response.status === 409) {
6823
6927
  throw new GatewayMemoryConflictError(
6824
6928
  message,
@@ -6827,7 +6931,7 @@ var GatewayMemory = class _GatewayMemory {
6827
6931
  }
6828
6932
  throw new GatewayMemoryError(message);
6829
6933
  }
6830
- this.log("%s %s -> %s", method, path13, response.status);
6934
+ this.log("%s %s -> %s", method, path14, response.status);
6831
6935
  return body;
6832
6936
  }
6833
6937
  authHeader() {
@@ -6989,10 +7093,10 @@ var PersonasClient = class _PersonasClient {
6989
7093
  done: Boolean(payload.done)
6990
7094
  };
6991
7095
  }
6992
- async requestJson(method, path13, payload) {
7096
+ async requestJson(method, path14, payload) {
6993
7097
  let response;
6994
7098
  try {
6995
- response = await fetch(`${this.host}${path13}`, {
7099
+ response = await fetch(`${this.host}${path14}`, {
6996
7100
  method,
6997
7101
  headers: {
6998
7102
  Authorization: this.authHeader(),
@@ -7003,7 +7107,7 @@ var PersonasClient = class _PersonasClient {
7003
7107
  });
7004
7108
  } catch (error) {
7005
7109
  const reason = error instanceof Error ? error.message : String(error);
7006
- throw new PersonaError(`${method} ${path13} failed: ${reason}`, {
7110
+ throw new PersonaError(`${method} ${path14} failed: ${reason}`, {
7007
7111
  cause: error
7008
7112
  });
7009
7113
  }
@@ -7011,10 +7115,10 @@ var PersonasClient = class _PersonasClient {
7011
7115
  if (!response.ok) {
7012
7116
  const detail = text2.slice(0, 500);
7013
7117
  throw new PersonaError(
7014
- `${method} ${path13} failed (${response.status}): ${detail}`
7118
+ `${method} ${path14} failed (${response.status}): ${detail}`
7015
7119
  );
7016
7120
  }
7017
- this.log("%s %s -> %s", method, path13, response.status);
7121
+ this.log("%s %s -> %s", method, path14, response.status);
7018
7122
  return safeJson3(text2);
7019
7123
  }
7020
7124
  authHeader() {
@@ -7239,10 +7343,10 @@ var SessionRecording = class _SessionRecording {
7239
7343
  };
7240
7344
  }
7241
7345
  /** Dump the full session as a JSON fixture (for regression tests). */
7242
- toFixture(path13) {
7243
- (0, import_node_fs.mkdirSync)((0, import_node_path.dirname)(path13), { recursive: true });
7244
- (0, import_node_fs.writeFileSync)(path13, JSON.stringify(this.toJSON(), null, 2), "utf-8");
7245
- return path13;
7346
+ toFixture(path14) {
7347
+ (0, import_node_fs.mkdirSync)((0, import_node_path.dirname)(path14), { recursive: true });
7348
+ (0, import_node_fs.writeFileSync)(path14, JSON.stringify(this.toJSON(), null, 2), "utf-8");
7349
+ return path14;
7246
7350
  }
7247
7351
  static fromApi(raw) {
7248
7352
  return new _SessionRecording({
@@ -8273,8 +8377,8 @@ var GatewaySecurity = class _GatewaySecurity {
8273
8377
  );
8274
8378
  }
8275
8379
  }
8276
- async postJson(path13, payload) {
8277
- const response = await fetch(`${this.host}${path13}`, {
8380
+ async postJson(path14, payload) {
8381
+ const response = await fetch(`${this.host}${path14}`, {
8278
8382
  method: "POST",
8279
8383
  headers: {
8280
8384
  Authorization: this.authHeader(),
@@ -8285,7 +8389,7 @@ var GatewaySecurity = class _GatewaySecurity {
8285
8389
  if (!response.ok) {
8286
8390
  const body = await response.text();
8287
8391
  throw new GatewaySecurityError(
8288
- `Gateway API ${response.status} on ${path13}: ${body || response.statusText}`
8392
+ `Gateway API ${response.status} on ${path14}: ${body || response.statusText}`
8289
8393
  );
8290
8394
  }
8291
8395
  return await response.json();
@@ -8374,9 +8478,9 @@ __export(files_exports, {
8374
8478
  uploadBytes: () => uploadBytes,
8375
8479
  uploadFile: () => uploadFile
8376
8480
  });
8377
- var import_node_crypto9 = require("crypto");
8378
- var fs10 = __toESM(require("fs"));
8379
- var path9 = __toESM(require("path"));
8481
+ var import_node_crypto10 = require("crypto");
8482
+ var fs11 = __toESM(require("fs"));
8483
+ var path10 = __toESM(require("path"));
8380
8484
  var import_node_stream = require("stream");
8381
8485
  var import_promises = require("stream/promises");
8382
8486
  init_worlds();
@@ -8425,9 +8529,9 @@ async function readFile2(options = {}, filePath) {
8425
8529
  async function downloadFile(options = {}, filePath, outPath, onProgress) {
8426
8530
  const file = await getFile(options, filePath);
8427
8531
  const res = await openDownload(file.url);
8428
- fs10.mkdirSync(path9.dirname(path9.resolve(outPath)), { recursive: true });
8532
+ fs11.mkdirSync(path10.dirname(path10.resolve(outPath)), { recursive: true });
8429
8533
  const source = import_node_stream.Readable.fromWeb(res.body);
8430
- await (0, import_promises.pipeline)(source, counting((n) => onProgress?.(n, file.sizeBytes)), fs10.createWriteStream(outPath));
8534
+ await (0, import_promises.pipeline)(source, counting((n) => onProgress?.(n, file.sizeBytes)), fs11.createWriteStream(outPath));
8431
8535
  return { ...file, out: outPath };
8432
8536
  }
8433
8537
  async function requestUpload(options = {}, body) {
@@ -8437,8 +8541,8 @@ async function confirmUpload(options = {}, fileId, ok = true) {
8437
8541
  return apiRequest(options, "POST", `${BASE}/confirm`, { fileId, ok });
8438
8542
  }
8439
8543
  async function sha256Base64(localPath) {
8440
- const hash = (0, import_node_crypto9.createHash)("sha256");
8441
- for await (const chunk of fs10.createReadStream(localPath)) hash.update(chunk);
8544
+ const hash = (0, import_node_crypto10.createHash)("sha256");
8545
+ for await (const chunk of fs11.createReadStream(localPath)) hash.update(chunk);
8442
8546
  return hash.digest("base64");
8443
8547
  }
8444
8548
  var CONTENT_TYPES = {
@@ -8474,7 +8578,7 @@ var CONTENT_TYPES = {
8474
8578
  ".mp4": "video/mp4"
8475
8579
  };
8476
8580
  function contentTypeFor(name) {
8477
- return CONTENT_TYPES[path9.extname(name).toLowerCase()] ?? "application/octet-stream";
8581
+ return CONTENT_TYPES[path10.extname(name).toLowerCase()] ?? "application/octet-stream";
8478
8582
  }
8479
8583
  function counting(report) {
8480
8584
  let seen = 0;
@@ -8501,7 +8605,7 @@ async function putPresigned(uploadUrl, body, headers) {
8501
8605
  if (!res.ok) throw new Error(`upload failed: storage answered HTTP ${res.status}: ${(await res.text()).slice(0, 300)}`);
8502
8606
  }
8503
8607
  async function uploadFile(options = {}, localPath, targetPath, upload = {}) {
8504
- const stat = fs10.statSync(localPath);
8608
+ const stat = fs11.statSync(localPath);
8505
8609
  if (!stat.isFile()) throw new Error(`${localPath} is not a file`);
8506
8610
  if (stat.size === 0) throw new Error(`${localPath} is empty; the drive refuses zero-byte uploads`);
8507
8611
  const contentType = upload.contentType ?? contentTypeFor(localPath);
@@ -8509,7 +8613,7 @@ async function uploadFile(options = {}, localPath, targetPath, upload = {}) {
8509
8613
  const target = drivePath(targetPath);
8510
8614
  const granted = await requestUpload(options, { path: target, contentLength: stat.size, contentType, sha256: sha2562, ...upload.overwrite ? { overwrite: true } : {} });
8511
8615
  try {
8512
- const stream = fs10.createReadStream(localPath).pipe(counting((n) => upload.onProgress?.(n, stat.size)));
8616
+ const stream = fs11.createReadStream(localPath).pipe(counting((n) => upload.onProgress?.(n, stat.size)));
8513
8617
  await putPresigned(granted.uploadUrl, import_node_stream.Readable.toWeb(stream), { contentType, contentLength: stat.size, sha256: sha2562 });
8514
8618
  } catch (error) {
8515
8619
  await confirmUpload(options, granted.fileId, false).catch(() => void 0);
@@ -8522,7 +8626,7 @@ async function uploadBytes(options = {}, bytes, targetPath, upload = {}) {
8522
8626
  if (!bytes.length) throw new Error("nothing to upload: the content is empty");
8523
8627
  const target = drivePath(targetPath);
8524
8628
  const contentType = upload.contentType ?? contentTypeFor(target);
8525
- const sha2562 = (0, import_node_crypto9.createHash)("sha256").update(bytes).digest("base64");
8629
+ const sha2562 = (0, import_node_crypto10.createHash)("sha256").update(bytes).digest("base64");
8526
8630
  const granted = await requestUpload(options, { path: target, contentLength: bytes.length, contentType, sha256: sha2562, ...upload.overwrite ? { overwrite: true } : {} });
8527
8631
  try {
8528
8632
  await putPresigned(granted.uploadUrl, new Uint8Array(bytes), { contentType, contentLength: bytes.length, sha256: sha2562 });
@@ -8715,7 +8819,7 @@ __export(hooks_exports, {
8715
8819
  });
8716
8820
 
8717
8821
  // src/hooks/alias.ts
8718
- var import_node_crypto10 = require("crypto");
8822
+ var import_node_crypto11 = require("crypto");
8719
8823
  var GIVEN = [
8720
8824
  "John",
8721
8825
  "Mary",
@@ -8906,7 +9010,7 @@ function findKind(kind, text2) {
8906
9010
  return out;
8907
9011
  }
8908
9012
  function newRunKey() {
8909
- return (0, import_node_crypto10.randomBytes)(32).toString("hex");
9013
+ return (0, import_node_crypto11.randomBytes)(32).toString("hex");
8910
9014
  }
8911
9015
  function canonical(kind, value) {
8912
9016
  const text2 = String(value).normalize("NFKC").trim();
@@ -8963,7 +9067,7 @@ function explodeIp(text2) {
8963
9067
  return groups.map((g) => g.padStart(4, "0")).join(":") + zone;
8964
9068
  }
8965
9069
  function index(runKey, kind, value, salt = "") {
8966
- const digest = (0, import_node_crypto10.createHmac)("sha256", Buffer.from(runKey, "hex")).update(`${kind}:${value}:${salt}`, "utf8").digest();
9070
+ const digest = (0, import_node_crypto11.createHmac)("sha256", Buffer.from(runKey, "hex")).update(`${kind}:${value}:${salt}`, "utf8").digest();
8967
9071
  return digest.readBigUInt64BE(0);
8968
9072
  }
8969
9073
  var pick = (pool, n) => pool[Number(n % BigInt(pool.length))];
@@ -9446,7 +9550,7 @@ var AliasMap = class _AliasMap {
9446
9550
  const existing = this.aliases.get(key2);
9447
9551
  if (existing) return existing.display;
9448
9552
  if (this.aliasDigests.has(digest.toLowerCase())) return digest;
9449
- const standIn = "sha256:" + (0, import_node_crypto10.createHmac)("sha256", Buffer.from(this.runKey, "hex")).update(digest, "utf8").digest("hex");
9553
+ const standIn = "sha256:" + (0, import_node_crypto11.createHmac)("sha256", Buffer.from(this.runKey, "hex")).update(digest, "utf8").digest("hex");
9450
9554
  this.aliasDigests.add(standIn.toLowerCase());
9451
9555
  const alias = {
9452
9556
  kind: "digest",
@@ -9484,9 +9588,9 @@ var AliasMap = class _AliasMap {
9484
9588
  });
9485
9589
  if (alias.role === "private") {
9486
9590
  for (const slug of this.slugs) {
9487
- const standIn = "sha256:" + (0, import_node_crypto10.createHash)("sha256").update(`${slug}:${canonical(alias.kind, alias.display)}`, "utf8").digest("hex");
9591
+ const standIn = "sha256:" + (0, import_node_crypto11.createHash)("sha256").update(`${slug}:${canonical(alias.kind, alias.display)}`, "utf8").digest("hex");
9488
9592
  alias.variants.push([
9489
- "sha256:" + (0, import_node_crypto10.createHash)("sha256").update(`${slug}:${alias.canonical}`, "utf8").digest("hex"),
9593
+ "sha256:" + (0, import_node_crypto11.createHash)("sha256").update(`${slug}:${alias.canonical}`, "utf8").digest("hex"),
9490
9594
  standIn
9491
9595
  ]);
9492
9596
  this.aliasDigests.add(standIn.toLowerCase());
@@ -9783,7 +9887,7 @@ function mirrorHandle(handle, identity) {
9783
9887
  }
9784
9888
 
9785
9889
  // src/hooks/config.ts
9786
- var fs11 = __toESM(require("fs"));
9890
+ var fs12 = __toESM(require("fs"));
9787
9891
 
9788
9892
  // src/cli/platform/worldData/toml.ts
9789
9893
  var TomlError = class extends Error {
@@ -10131,9 +10235,9 @@ function alternatives(raw) {
10131
10235
  if (!parts2.length || parts2.includes("*")) return [];
10132
10236
  return parts2;
10133
10237
  }
10134
- function hasPath(node, path13) {
10238
+ function hasPath(node, path14) {
10135
10239
  let current = node;
10136
- for (const part of path13.split(".")) {
10240
+ for (const part of path14.split(".")) {
10137
10241
  if (current && typeof current === "object" && !Array.isArray(current) && part in current) {
10138
10242
  current = current[part];
10139
10243
  continue;
@@ -10174,7 +10278,7 @@ function matches(m, event) {
10174
10278
  if (m.args.length) {
10175
10279
  const haystacks = event.event === "pre_request" || event.event === "post_response" ? [event.request?.query, event.request?.body] : [event.toolInput];
10176
10280
  const present = haystacks.filter((h) => h !== void 0 && h !== null);
10177
- if (!m.args.every((path13) => present.some((h) => hasPath(h, path13))))
10281
+ if (!m.args.every((path14) => present.some((h) => hasPath(h, path14))))
10178
10282
  return false;
10179
10283
  }
10180
10284
  return true;
@@ -10617,9 +10721,9 @@ function vendorOf(config, toolName) {
10617
10721
  return void 0;
10618
10722
  }
10619
10723
  function loadHookConfig(file) {
10620
- if (!fs11.existsSync(file) || !fs11.statSync(file).isFile())
10724
+ if (!fs12.existsSync(file) || !fs12.statSync(file).isFile())
10621
10725
  throw new HookConfigError(`${file}: no such file`);
10622
- const text2 = fs11.readFileSync(file, "utf8");
10726
+ const text2 = fs12.readFileSync(file, "utf8");
10623
10727
  if (file.toLowerCase().endsWith(".json")) {
10624
10728
  let data2;
10625
10729
  try {
@@ -10999,8 +11103,8 @@ function parseHandler(event, raw, position) {
10999
11103
 
11000
11104
  // src/hooks/handlers.ts
11001
11105
  var import_node_child_process3 = require("child_process");
11002
- var fs12 = __toESM(require("fs"));
11003
- var path10 = __toESM(require("path"));
11106
+ var fs13 = __toESM(require("fs"));
11107
+ var path11 = __toESM(require("path"));
11004
11108
  var import_node_url = require("url");
11005
11109
  function parseStdout(text2, handler) {
11006
11110
  const stripped = text2.trim();
@@ -11194,8 +11298,8 @@ var RecordHandler = class {
11194
11298
  record.source = this.opts.source ?? null;
11195
11299
  if (Array.isArray(this.sink)) this.sink.push(record);
11196
11300
  else if (typeof this.sink === "string") {
11197
- fs12.mkdirSync(path10.dirname(this.sink), { recursive: true });
11198
- fs12.appendFileSync(this.sink, JSON.stringify(record) + "\n");
11301
+ fs13.mkdirSync(path11.dirname(this.sink), { recursive: true });
11302
+ fs13.appendFileSync(this.sink, JSON.stringify(record) + "\n");
11199
11303
  } else await this.sink(record);
11200
11304
  return allow();
11201
11305
  }
@@ -11400,7 +11504,7 @@ async function importCallable(target, cwd) {
11400
11504
  const hash = target.lastIndexOf("#");
11401
11505
  const modulePath = target.slice(0, hash);
11402
11506
  const exportName = target.slice(hash + 1) || "default";
11403
- const resolved = modulePath.startsWith(".") || path10.isAbsolute(modulePath) ? (0, import_node_url.pathToFileURL)(path10.resolve(cwd, modulePath)).href : modulePath;
11507
+ const resolved = modulePath.startsWith(".") || path11.isAbsolute(modulePath) ? (0, import_node_url.pathToFileURL)(path11.resolve(cwd, modulePath)).href : modulePath;
11404
11508
  let module2;
11405
11509
  try {
11406
11510
  module2 = await import(resolved);
@@ -11463,8 +11567,8 @@ async function buildHandler(spec, aliases, opts) {
11463
11567
  }
11464
11568
 
11465
11569
  // src/hooks/live.ts
11466
- var fs13 = __toESM(require("fs"));
11467
- var path11 = __toESM(require("path"));
11570
+ var fs14 = __toESM(require("fs"));
11571
+ var path12 = __toESM(require("path"));
11468
11572
  var USER_AGENT = "gateway-hooks/1 (+https://withgateway.ai)";
11469
11573
  var TAGS = /<(script|style)[^>]*>.*?<\/\1>/gis;
11470
11574
  var STRIP = /<[^>]+>/g;
@@ -11828,9 +11932,9 @@ var CallableTool = class _CallableTool {
11828
11932
  }
11829
11933
  };
11830
11934
  function readConnection(root) {
11831
- const file = path11.join(root, "connector.toml");
11832
- if (!fs13.existsSync(file)) throw new Error(`no connector.toml at ${root}`);
11833
- const raw = parseToml(fs13.readFileSync(file, "utf8"));
11935
+ const file = path12.join(root, "connector.toml");
11936
+ if (!fs14.existsSync(file)) throw new Error(`no connector.toml at ${root}`);
11937
+ const raw = parseToml(fs14.readFileSync(file, "utf8"));
11834
11938
  const connector = raw.connector ?? {};
11835
11939
  const auth = raw.auth ?? {};
11836
11940
  const operations = {};
@@ -11844,7 +11948,7 @@ function readConnection(root) {
11844
11948
  };
11845
11949
  }
11846
11950
  return {
11847
- slug: connector.slug ?? path11.basename(root),
11951
+ slug: connector.slug ?? path12.basename(root),
11848
11952
  baseUrl: (connector.base_url ?? "").replace(/\/+$/, ""),
11849
11953
  scheme: auth.scheme ?? "none",
11850
11954
  ...typeof auth.name === "string" ? { authName: auth.name } : {},
@@ -11861,8 +11965,8 @@ var ConnectorTool = class {
11861
11965
  this.spec = spec;
11862
11966
  this.live = live;
11863
11967
  let location = spec.options.connector;
11864
- if (!path11.isAbsolute(location)) location = path11.resolve(baseDir, location);
11865
- const root = fs13.existsSync(location) && fs13.statSync(location).isFile() ? path11.dirname(location) : location;
11968
+ if (!path12.isAbsolute(location)) location = path12.resolve(baseDir, location);
11969
+ const root = fs14.existsSync(location) && fs14.statSync(location).isFile() ? path12.dirname(location) : location;
11866
11970
  try {
11867
11971
  this.connection = readConnection(root);
11868
11972
  } catch (error) {
@@ -12016,16 +12120,16 @@ var Recorder = class {
12016
12120
  this.file = file;
12017
12121
  }
12018
12122
  write(line) {
12019
- fs13.mkdirSync(path11.dirname(this.file), { recursive: true });
12020
- fs13.appendFileSync(this.file, canonical2(line) + "\n");
12123
+ fs14.mkdirSync(path12.dirname(this.file), { recursive: true });
12124
+ fs14.appendFileSync(this.file, canonical2(line) + "\n");
12021
12125
  }
12022
12126
  };
12023
12127
  var Replay = class {
12024
12128
  constructor(file) {
12025
12129
  this.file = file;
12026
- if (!fs13.existsSync(file))
12130
+ if (!fs14.existsSync(file))
12027
12131
  throw new LiveToolError(`replay: no recording at ${file}`);
12028
- fs13.readFileSync(file, "utf8").split(/\r?\n/).forEach((raw, index2) => {
12132
+ fs14.readFileSync(file, "utf8").split(/\r?\n/).forEach((raw, index2) => {
12029
12133
  if (!raw.trim()) return;
12030
12134
  let line;
12031
12135
  try {
@@ -12109,7 +12213,7 @@ var LiveTools = class _LiveTools {
12109
12213
  ...config.live.record ? { record: interpolatePath(config.live.record, run.runId, directory) } : {},
12110
12214
  ...config.live.replay ? { replay: interpolatePath(config.live.replay, run.runId, directory) } : {}
12111
12215
  };
12112
- return _LiveTools.create(run, live, path11.dirname(path11.resolve(file)));
12216
+ return _LiveTools.create(run, live, path12.dirname(path12.resolve(file)));
12113
12217
  }
12114
12218
  /** The declared tools for a model. `openai`: `{type: "function", function: {name,
12115
12219
  * description, parameters}}`; `anthropic`: `{name, description, input_schema}`. */
@@ -12207,9 +12311,9 @@ var LiveTools = class _LiveTools {
12207
12311
  };
12208
12312
 
12209
12313
  // src/hooks/run.ts
12210
- var import_node_crypto11 = require("crypto");
12211
- var fs14 = __toESM(require("fs"));
12212
- var path12 = __toESM(require("path"));
12314
+ var import_node_crypto12 = require("crypto");
12315
+ var fs15 = __toESM(require("fs"));
12316
+ var path13 = __toESM(require("path"));
12213
12317
  var BLOCKING_EVENTS = [
12214
12318
  "pre_tool_call",
12215
12319
  "pre_request",
@@ -12251,7 +12355,7 @@ var HookRun = class _HookRun {
12251
12355
  source;
12252
12356
  constructor(config, options) {
12253
12357
  this.config = config;
12254
- this.runId = options.runId ?? `run-${(0, import_node_crypto11.randomBytes)(6).toString("hex")}`;
12358
+ this.runId = options.runId ?? `run-${(0, import_node_crypto12.randomBytes)(6).toString("hex")}`;
12255
12359
  this.runKey = options.runKey ?? newRunKey();
12256
12360
  this.alias = new AliasMap(this.runKey, options.slugs ?? config.aliasSlugs, {
12257
12361
  publicLayerWins: config.aliasPublicLayerWins,
@@ -12259,12 +12363,12 @@ var HookRun = class _HookRun {
12259
12363
  mintInbound: options.mintInbound ?? config.aliasMintInbound
12260
12364
  });
12261
12365
  this.cwd = options.cwd ?? process.cwd();
12262
- this.runDir = options.runDir ?? path12.join(this.cwd, "runs", this.runId);
12366
+ this.runDir = options.runDir ?? path13.join(this.cwd, "runs", this.runId);
12263
12367
  const chosen = options.legend !== void 0 ? options.legend : config.aliasLegend;
12264
- this.legendPath = chosen ? path12.resolve(this.cwd, interpolatePath(chosen, this.runId, this.runDir)) : null;
12368
+ this.legendPath = chosen ? path13.resolve(this.cwd, interpolatePath(chosen, this.runId, this.runDir)) : null;
12265
12369
  this.sessionId = options.session;
12266
12370
  this.source = options.source;
12267
- this.configDir = config.source ? path12.dirname(path12.resolve(config.source)) : this.cwd;
12371
+ this.configDir = config.source ? path13.dirname(path13.resolve(config.source)) : this.cwd;
12268
12372
  }
12269
12373
  /** Build from a parsed config (an object in the file's shape, or a `HookConfig`);
12270
12374
  * handlers are constructed now, so a callable that does not import fails here. */
@@ -12674,8 +12778,8 @@ var HookRun = class _HookRun {
12674
12778
  throw new Error(
12675
12779
  "no legend path: set [alias] legend, pass legend to the run, or give a path"
12676
12780
  );
12677
- fs14.mkdirSync(path12.dirname(target), { recursive: true });
12678
- fs14.writeFileSync(target, JSON.stringify(this.legend(), null, 2) + "\n");
12781
+ fs15.mkdirSync(path13.dirname(target), { recursive: true });
12782
+ fs15.writeFileSync(target, JSON.stringify(this.legend(), null, 2) + "\n");
12679
12783
  return target;
12680
12784
  }
12681
12785
  writeLegendIfConfigured() {
@@ -12767,14 +12871,14 @@ var HookedSession = class {
12767
12871
  * `apiHeaders()`), `pre_request` before it and `post_response` after. Returns
12768
12872
  * `{status, body, headers}`; a 4xx/5xx is returned, not thrown, so the agent sees
12769
12873
  * the vendor's own error shape (rewritten like any result). */
12770
- async request(method, path13, opts = {}) {
12874
+ async request(method, path14, opts = {}) {
12771
12875
  if (!this.inner.api && !this.requestFn)
12772
12876
  throw new Error(
12773
12877
  "this session has no api surface (pass requestFn for a transport of your own)"
12774
12878
  );
12775
12879
  let request = {
12776
12880
  method: method.toUpperCase(),
12777
- path: path13,
12881
+ path: path14,
12778
12882
  query: { ...opts.query ?? {} },
12779
12883
  body: opts.body ?? null
12780
12884
  };
@@ -13252,7 +13356,6 @@ var tracing = {
13252
13356
  identify,
13253
13357
  ingest,
13254
13358
  ingestToolCalls,
13255
- isIncludedInContentHash,
13256
13359
  isTaskIdRef,
13257
13360
  isTaskManifest,
13258
13361
  isTaskSpec,