@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
@@ -41,9 +41,9 @@ function surfaceKinds(s) {
41
41
  if (s.browser) kinds.push("browser");
42
42
  return kinds;
43
43
  }
44
- function uiUrl(ui, path9) {
44
+ function uiUrl(ui, path10) {
45
45
  const base = ui.url.replace(/\/+$/, "");
46
- const rel = path9.startsWith("/") ? path9 : `/${path9}`;
46
+ const rel = path10.startsWith("/") ? path10 : `/${path10}`;
47
47
  if (!ui.token) return base + rel;
48
48
  const [beforeHash, hash] = splitHash(rel);
49
49
  const joiner = beforeHash.includes("?") ? "&" : "?";
@@ -600,12 +600,13 @@ async function openSession(slugOrRef, taskOrOpts, positionalOpts = {}) {
600
600
  );
601
601
  const at = slugOrRef.indexOf("@");
602
602
  const slug = at === -1 ? slugOrRef : slugOrRef.slice(0, at);
603
+ const ref = at === -1 ? "" : slugOrRef.slice(at + 1);
603
604
  const state2 = await apiRequest(
604
605
  options,
605
606
  "POST",
606
607
  "/api/public/world-sessions",
607
608
  {
608
- ...opts.versionId ? { versionId: opts.versionId } : { slug },
609
+ ...opts.versionId ? { versionId: opts.versionId } : { slug, ...ref && { ref } },
609
610
  task,
610
611
  ...opts.reuseWarm === void 0 ? {} : { reuseWarm: opts.reuseWarm },
611
612
  ...opts.surfaces?.length ? { surfaces: opts.surfaces } : {}
@@ -804,18 +805,18 @@ var init_session = __esm({
804
805
  }
805
806
  /** The reporter `browser()` uses; exposed for a page you drive yourself. */
806
807
  browserRecorder(agentId) {
807
- const path9 = `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/browser-events`;
808
+ const path10 = `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/browser-events`;
808
809
  const id = agentId ?? process.env.GATEWAY_AGENT_ID ?? `agent-${(0, import_node_crypto.randomUUID)().replace(/-/g, "").slice(0, 8)}`;
809
810
  return new BrowserActionRecorder(
810
811
  async (events) => {
811
- await apiRequest(this.options, "POST", path9, { events });
812
+ await apiRequest(this.options, "POST", path10, { events });
812
813
  },
813
814
  id,
814
815
  {
815
816
  // Continue this agent's timeline where the platform has it, so the
816
817
  // same id reopened later never re-numbers from zero.
817
818
  resumeFrom: async () => {
818
- const summary = await apiRequest(this.options, "GET", path9);
819
+ const summary = await apiRequest(this.options, "GET", path10);
819
820
  return summary.agents.find((a) => a.agentId === id)?.nextSeq ?? 0;
820
821
  }
821
822
  }
@@ -1621,10 +1622,10 @@ var init_users = __esm({
1621
1622
  totalItems: Number(meta.totalItems ?? rows.length)
1622
1623
  };
1623
1624
  }
1624
- async requestJson(method, path9, payload) {
1625
+ async requestJson(method, path10, payload) {
1625
1626
  let response;
1626
1627
  try {
1627
- response = await fetch(`${this.host}${path9}`, {
1628
+ response = await fetch(`${this.host}${path10}`, {
1628
1629
  method,
1629
1630
  headers: {
1630
1631
  Authorization: this.authHeader(),
@@ -1635,17 +1636,17 @@ var init_users = __esm({
1635
1636
  });
1636
1637
  } catch (error) {
1637
1638
  throw new UserProfileError(
1638
- `${method} ${path9} failed: ${error instanceof Error ? error.message : String(error)}`,
1639
+ `${method} ${path10} failed: ${error instanceof Error ? error.message : String(error)}`,
1639
1640
  { cause: error }
1640
1641
  );
1641
1642
  }
1642
1643
  const text2 = await response.text();
1643
1644
  if (!response.ok) {
1644
1645
  throw new UserProfileError(
1645
- `${method} ${path9} failed (${response.status}): ${text2.slice(0, 500)}`
1646
+ `${method} ${path10} failed (${response.status}): ${text2.slice(0, 500)}`
1646
1647
  );
1647
1648
  }
1648
- this.log("%s %s -> %s", method, path9, response.status);
1649
+ this.log("%s %s -> %s", method, path10, response.status);
1649
1650
  return safeJson(text2);
1650
1651
  }
1651
1652
  authHeader() {
@@ -1909,10 +1910,10 @@ var init_scores = __esm({
1909
1910
  metadata: signalMetadata
1910
1911
  });
1911
1912
  }
1912
- async request(method, path9, payload) {
1913
+ async request(method, path10, payload) {
1913
1914
  let response;
1914
1915
  try {
1915
- response = await fetch(`${this.host}${path9}`, {
1916
+ response = await fetch(`${this.host}${path10}`, {
1916
1917
  method,
1917
1918
  headers: {
1918
1919
  Authorization: this.authHeader(),
@@ -1923,17 +1924,17 @@ var init_scores = __esm({
1923
1924
  });
1924
1925
  } catch (error) {
1925
1926
  throw new ScoreError(
1926
- `${method} ${path9} failed: ${error instanceof Error ? error.message : String(error)}`,
1927
+ `${method} ${path10} failed: ${error instanceof Error ? error.message : String(error)}`,
1927
1928
  { cause: error }
1928
1929
  );
1929
1930
  }
1930
1931
  const text2 = await response.text();
1931
1932
  if (!response.ok) {
1932
1933
  throw new ScoreError(
1933
- `${method} ${path9} failed (${response.status}): ${text2.slice(0, 500)}`
1934
+ `${method} ${path10} failed (${response.status}): ${text2.slice(0, 500)}`
1934
1935
  );
1935
1936
  }
1936
- this.log("%s %s -> %s", method, path9, response.status);
1937
+ this.log("%s %s -> %s", method, path10, response.status);
1937
1938
  }
1938
1939
  authHeader() {
1939
1940
  return `Basic ${Buffer.from(`${this.publicKey}:${this.secretKey}`).toString(
@@ -1961,7 +1962,7 @@ var require_package = __commonJS({
1961
1962
  "package.json"(exports2, module2) {
1962
1963
  module2.exports = {
1963
1964
  name: "@withgateway/sdk",
1964
- version: "0.2.4",
1965
+ version: "0.2.5",
1965
1966
  description: "Gateway SDK for TypeScript - A/B experiments, tracing, and observability",
1966
1967
  main: "./dist/index.js",
1967
1968
  module: "./dist/index.mjs",
@@ -2065,6 +2066,7 @@ var require_package = __commonJS({
2065
2066
  "typecheck:examples": "tsc -p tsconfig.examples.json --noEmit",
2066
2067
  test: "vitest",
2067
2068
  "test:run": "vitest run",
2069
+ "test:integration": "vitest run --config vitest.integration.config.ts",
2068
2070
  lint: "eslint src --ext .ts",
2069
2071
  clean: "rm -rf dist",
2070
2072
  example: "tsx examples/test-ab-experiment.ts",
@@ -2922,6 +2924,152 @@ var init_taskRun = __esm({
2922
2924
  }
2923
2925
  });
2924
2926
 
2927
+ // src/worlds/worldDir.ts
2928
+ 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;
2929
+ var init_worldDir = __esm({
2930
+ "src/worlds/worldDir.ts"() {
2931
+ "use strict";
2932
+ import_node_crypto4 = require("crypto");
2933
+ fs2 = __toESM(require("fs"));
2934
+ path2 = __toESM(require("path"));
2935
+ WORLD_MANIFEST = "gateway-env.toml";
2936
+ API_BUNDLE_MANIFEST = "gateway-api-world.toml";
2937
+ BUNDLED_WORLD_PREFIX = "server/world/";
2938
+ CONNECTOR_SPEC = "connector.toml";
2939
+ PYPROJECT = "pyproject.toml";
2940
+ WORLD_SCHEMA_MARKERS = ["schema/world.json", "schema/runtime.json", "schema/lock.json"];
2941
+ WORLD_ROOT_MARKERS = [CONNECTOR_SPEC, ...WORLD_SCHEMA_MARKERS];
2942
+ BROAD_ROOT_MARKERS = [WORLD_MANIFEST, API_BUNDLE_MANIFEST];
2943
+ SKIPPED_DIRS = /* @__PURE__ */ new Set(["dist", "build", "outputs", "__pycache__"]);
2944
+ V1_DEP = /["']verifiers\s*(?:\[[^\]]*\])?\s*(?:>=|~=|==|>)\s*(?:0\.(?:[2-9]\d*|[1-9]\d+)|[1-9]\d*)/;
2945
+ V1_IMPORT = /^\s*(?:from\s+verifiers\.v1\s+import\b|from\s+verifiers\s+import\s+v1\b|import\s+verifiers\.v1\b)/m;
2946
+ V1_TASKSET = /class\s+\w+\s*\(\s*(?:(?:vf|v1|verifiers(?:\.v1)?)\.)?Taskset\s*[,)]/;
2947
+ HARBOR_TASK = /^(?:tasks\/)?([^/]+)\/task\.toml$/;
2948
+ skippedDir = (name) => name.startsWith(".") || SKIPPED_DIRS.has(name) || name.endsWith(".egg-info");
2949
+ byCodePoint = (a, b) => Buffer.compare(Buffer.from(a, "utf-8"), Buffer.from(b, "utf-8"));
2950
+ WorldDir = class _WorldDir {
2951
+ constructor(dir, worldRoot) {
2952
+ this.dir = dir;
2953
+ this.worldRoot = worldRoot;
2954
+ }
2955
+ pathsMemo;
2956
+ static open(dir) {
2957
+ const present = (rel) => fs2.existsSync(path2.join(dir, rel));
2958
+ const bundled = present(API_BUNDLE_MANIFEST) && WORLD_ROOT_MARKERS.some((m) => present(BUNDLED_WORLD_PREFIX + m));
2959
+ return new _WorldDir(dir, bundled ? BUNDLED_WORLD_PREFIX : "");
2960
+ }
2961
+ // ── Files ──────────────────────────────────────────────────────────────
2962
+ has(rel) {
2963
+ return fs2.existsSync(path2.join(this.dir, rel));
2964
+ }
2965
+ text(rel) {
2966
+ try {
2967
+ return fs2.readFileSync(path2.join(this.dir, rel), "utf-8");
2968
+ } catch {
2969
+ return null;
2970
+ }
2971
+ }
2972
+ /** A path under the authored world's root. */
2973
+ worldPath(rel) {
2974
+ return this.worldRoot + rel;
2975
+ }
2976
+ /** Every regular file the archive rules keep (`_archive.py`: no hidden,
2977
+ * dist, build, outputs, pycache or egg-info directories), as sorted
2978
+ * relpaths. Root files enter only when a Gateway manifest widens the root
2979
+ * or they are README.md, pyproject.toml or Python. */
2980
+ get archivePaths() {
2981
+ if (this.pathsMemo) return this.pathsMemo;
2982
+ const broad = BROAD_ROOT_MARKERS.some((m) => this.has(m));
2983
+ const out = [];
2984
+ const walk = (rel) => {
2985
+ for (const entry of fs2.readdirSync(rel ? path2.join(this.dir, rel) : this.dir, { withFileTypes: true })) {
2986
+ const child = rel ? `${rel}/${entry.name}` : entry.name;
2987
+ if (entry.isDirectory()) {
2988
+ if (!skippedDir(entry.name)) walk(child);
2989
+ } else if (entry.isFile() && !entry.name.startsWith(".")) {
2990
+ const rootKept = broad || ["README.md", PYPROJECT].includes(entry.name) || entry.name.endsWith(".py");
2991
+ if (rel || rootKept) out.push(child);
2992
+ }
2993
+ }
2994
+ };
2995
+ walk("");
2996
+ return this.pathsMemo = out.sort(byCodePoint);
2997
+ }
2998
+ /** A root `.gitignore` is present: the Python SDK honours it when
2999
+ * collecting, this package does not reimplement gitignore. */
3000
+ get hasRootGitignore() {
3001
+ return this.has(".gitignore");
3002
+ }
3003
+ /** SHA-256 over `utf8("file:" + relpath)` + bytes per archive path in
3004
+ * sorted order: the version's identity, byte-compatible with
3005
+ * `_archive.compute_content_hash` and Prime Intellect. */
3006
+ get contentHash() {
3007
+ const hasher = (0, import_node_crypto4.createHash)("sha256");
3008
+ for (const rel of this.archivePaths) {
3009
+ hasher.update(Buffer.from(`file:${rel}`, "utf-8"));
3010
+ hasher.update(fs2.readFileSync(path2.join(this.dir, rel)));
3011
+ }
3012
+ return hasher.digest("hex");
3013
+ }
3014
+ // ── Markers ────────────────────────────────────────────────────────────
3015
+ get isApiBundle() {
3016
+ return this.has(API_BUNDLE_MANIFEST);
3017
+ }
3018
+ get hasManifest() {
3019
+ return this.has(this.worldPath(WORLD_MANIFEST));
3020
+ }
3021
+ get hasSchemaMarker() {
3022
+ return WORLD_SCHEMA_MARKERS.some((m) => this.has(this.worldPath(m)));
3023
+ }
3024
+ /** Harbor task dirs, relative to the tree: `tasks/<name>` when a `tasks/`
3025
+ * dir holds them, else the root `<name>` dirs. */
3026
+ taskDirs() {
3027
+ const names = /* @__PURE__ */ new Set();
3028
+ for (const rel of this.archivePaths) {
3029
+ const m = HARBOR_TASK.exec(rel);
3030
+ if (m) names.add(rel.startsWith("tasks/") ? `tasks/${m[1]}` : m[1]);
3031
+ }
3032
+ const under = [...names].filter((n) => n.startsWith("tasks/"));
3033
+ return (under.length ? under : [...names]).sort();
3034
+ }
3035
+ /** The Python package of a verifiers tree (`<pkg>/__init__.py` or
3036
+ * `src/<pkg>/__init__.py`), or null. */
3037
+ pythonPackage() {
3038
+ if (!this.has(PYPROJECT)) return null;
3039
+ for (const base of ["", "src/"]) {
3040
+ const init2 = this.archivePaths.find((rel) => {
3041
+ const m = /^([^/]+)\/__init__\.py$/.exec(rel.startsWith(base) ? rel.slice(base.length) : "");
3042
+ return m !== null && m[1] !== "tests";
3043
+ });
3044
+ if (init2) return { name: init2.slice(base.length).split("/")[0], init: init2 };
3045
+ }
3046
+ return null;
3047
+ }
3048
+ /** The package targets the `verifiers.v1` API: read from the root
3049
+ * pyproject and every archived Python module. */
3050
+ get isVerifiersV1() {
3051
+ for (const rel of this.archivePaths) {
3052
+ if (rel !== PYPROJECT && !rel.endsWith(".py")) continue;
3053
+ const text2 = this.text(rel);
3054
+ if (text2 === null) continue;
3055
+ if (rel === PYPROJECT ? V1_DEP.test(text2) : V1_IMPORT.test(text2) || text2.includes("__all__") && V1_TASKSET.test(text2))
3056
+ return true;
3057
+ }
3058
+ return false;
3059
+ }
3060
+ // ── The answer ─────────────────────────────────────────────────────────
3061
+ /** The runner's kind (`detect_env_kind`): api / mock-tools win over
3062
+ * everything, a harbor task tree next, then the verifiers API version. */
3063
+ get kind() {
3064
+ if (this.isApiBundle) return "api";
3065
+ if (this.has(WORLD_MANIFEST)) return "mock-tools";
3066
+ if (this.taskDirs().length) return "harbor";
3067
+ return this.isVerifiersV1 ? "verifiers-v1" : "verifiers";
3068
+ }
3069
+ };
3070
+ }
3071
+ });
3072
+
2925
3073
  // src/worlds/hub.ts
2926
3074
  var hub_exports = {};
2927
3075
  __export(hub_exports, {
@@ -2930,7 +3078,6 @@ __export(hub_exports, {
2930
3078
  collectArchiveRelPaths: () => collectArchiveRelPaths,
2931
3079
  computeContentHash: () => computeContentHash,
2932
3080
  createRef: () => createRef,
2933
- isIncludedInContentHash: () => isIncludedInContentHash,
2934
3081
  localTreeState: () => localTreeState,
2935
3082
  propose: () => propose,
2936
3083
  pull: () => pull,
@@ -2940,53 +3087,18 @@ __export(hub_exports, {
2940
3087
  snapshotTreeHashes: () => snapshotTreeHashes,
2941
3088
  writeLocalMeta: () => writeLocalMeta
2942
3089
  });
2943
- function isExcludedDirComponent(component) {
2944
- return component.startsWith(".") || ROOT_EXCLUDED_DIRS.has(component) || component.endsWith(".egg-info");
2945
- }
2946
- function isIncludedInContentHash(relPath, includeAllRootFiles) {
2947
- const parts = relPath.split("/");
2948
- const name = parts[parts.length - 1];
2949
- const dirParts = parts.slice(0, -1);
2950
- if (name.startsWith(".")) return false;
2951
- if (parts.includes("__pycache__")) return false;
2952
- if (dirParts.length === 0) {
2953
- return includeAllRootFiles || name === "README.md" || name === "pyproject.toml" || BROAD_ROOT_MARKERS.includes(name) || name.endsWith(".py");
2954
- }
2955
- return !dirParts.some(isExcludedDirComponent);
2956
- }
2957
3090
  function collectArchiveRelPaths(dir) {
2958
- if (fs2.existsSync(path2.join(dir, ".gitignore"))) {
3091
+ const world = WorldDir.open(dir);
3092
+ if (world.hasRootGitignore) {
2959
3093
  throw new Error(
2960
3094
  "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."
2961
3095
  );
2962
3096
  }
2963
- const out = [];
2964
- const includeAllRootFiles = BROAD_ROOT_MARKERS.some(
2965
- (marker) => fs2.existsSync(path2.join(dir, marker))
2966
- );
2967
- const walk = (rel) => {
2968
- const abs = rel ? path2.join(dir, rel) : dir;
2969
- for (const entry of fs2.readdirSync(abs, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
2970
- const childRel = rel ? `${rel}/${entry.name}` : entry.name;
2971
- if (entry.isDirectory()) {
2972
- if (!isExcludedDirComponent(entry.name)) walk(childRel);
2973
- } else if (entry.isFile()) {
2974
- if (isIncludedInContentHash(childRel, includeAllRootFiles)) {
2975
- out.push(childRel);
2976
- }
2977
- }
2978
- }
2979
- };
2980
- walk("");
2981
- return out.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
3097
+ return world.archivePaths;
2982
3098
  }
2983
3099
  function computeContentHash(dir) {
2984
- const hasher = (0, import_node_crypto4.createHash)("sha256");
2985
- for (const relPath of collectArchiveRelPaths(dir)) {
2986
- hasher.update(Buffer.from(`file:${relPath}`, "utf-8"));
2987
- hasher.update(fs2.readFileSync(path2.join(dir, relPath)));
2988
- }
2989
- return hasher.digest("hex");
3100
+ collectArchiveRelPaths(dir);
3101
+ return WorldDir.open(dir).contentHash;
2990
3102
  }
2991
3103
  function octal(value, length) {
2992
3104
  return Buffer.from(value.toString(8).padStart(length - 1, "0") + "\0", "ascii");
@@ -3034,14 +3146,14 @@ function tarMember(name, payload) {
3034
3146
  function buildSourceTarball(dir) {
3035
3147
  const parts = [];
3036
3148
  for (const relPath of collectArchiveRelPaths(dir)) {
3037
- parts.push(...tarMember(relPath, fs2.readFileSync(path2.join(dir, relPath))));
3149
+ parts.push(...tarMember(relPath, fs3.readFileSync(path3.join(dir, relPath))));
3038
3150
  }
3039
3151
  parts.push(Buffer.alloc(1024));
3040
3152
  return (0, import_node_zlib.gzipSync)(Buffer.concat(parts), { level: 9 });
3041
3153
  }
3042
3154
  function readLocalMeta(dir) {
3043
3155
  try {
3044
- const raw = fs2.readFileSync(path2.join(dir, META_RELPATH), "utf-8");
3156
+ const raw = fs3.readFileSync(path3.join(dir, META_RELPATH), "utf-8");
3045
3157
  const parsed = JSON.parse(raw);
3046
3158
  return parsed && typeof parsed === "object" ? parsed : null;
3047
3159
  } catch {
@@ -3052,16 +3164,16 @@ function pushSlug(dir, explicit) {
3052
3164
  if (explicit) return explicit;
3053
3165
  const meta = readLocalMeta(dir);
3054
3166
  if (typeof meta?.slug === "string" && meta.slug) return meta.slug;
3055
- return readPyproject(dir).name ?? path2.basename(path2.resolve(dir));
3167
+ return readPyproject(dir).name ?? path3.basename(path3.resolve(dir));
3056
3168
  }
3057
3169
  function writeLocalMeta(dir, meta) {
3058
- fs2.mkdirSync(path2.join(dir, ".gateway"), { recursive: true });
3059
- fs2.writeFileSync(path2.join(dir, META_RELPATH), JSON.stringify(meta, null, 2));
3170
+ fs3.mkdirSync(path3.join(dir, ".gateway"), { recursive: true });
3171
+ fs3.writeFileSync(path3.join(dir, META_RELPATH), JSON.stringify(meta, null, 2));
3060
3172
  }
3061
3173
  function snapshotTreeHashes(dir) {
3062
3174
  const out = {};
3063
3175
  for (const relPath of collectArchiveRelPaths(dir)) {
3064
- out[relPath] = (0, import_node_crypto4.createHash)("sha256").update(fs2.readFileSync(path2.join(dir, relPath))).digest("hex");
3176
+ out[relPath] = (0, import_node_crypto5.createHash)("sha256").update(fs3.readFileSync(path3.join(dir, relPath))).digest("hex");
3065
3177
  }
3066
3178
  return out;
3067
3179
  }
@@ -3079,7 +3191,7 @@ function localTreeState(dir) {
3079
3191
  }
3080
3192
  function readPyproject(dir) {
3081
3193
  try {
3082
- const text2 = fs2.readFileSync(path2.join(dir, "pyproject.toml"), "utf-8");
3194
+ const text2 = fs3.readFileSync(path3.join(dir, "pyproject.toml"), "utf-8");
3083
3195
  const section = /\[project\]([\s\S]*?)(\n\[|$)/.exec(text2)?.[1] ?? "";
3084
3196
  const name = /\bname\s*=\s*"([^"]+)"/.exec(section)?.[1];
3085
3197
  const version = /\bversion\s*=\s*"([^"]+)"/.exec(section)?.[1];
@@ -3089,33 +3201,32 @@ function readPyproject(dir) {
3089
3201
  }
3090
3202
  }
3091
3203
  function readWorldContractVersion(dir) {
3092
- for (const rel of ["schema/world.json", path2.join("server", "world", "schema", "world.json")]) {
3093
- try {
3094
- const parsed = JSON.parse(fs2.readFileSync(path2.join(dir, rel), "utf-8"));
3095
- const pkg = parsed["x-gateway"]?.package;
3096
- if (pkg?.version) return { name: pkg.id, version: pkg.version };
3097
- } catch {
3098
- }
3204
+ const world = WorldDir.open(dir);
3205
+ try {
3206
+ const parsed = JSON.parse(world.text(world.worldPath("schema/world.json")) ?? "");
3207
+ const pkg = parsed["x-gateway"]?.package;
3208
+ if (pkg?.version) return { name: pkg.id, version: pkg.version };
3209
+ } catch {
3099
3210
  }
3100
3211
  return {};
3101
3212
  }
3102
3213
  function buildFileManifest(dir) {
3103
3214
  const entries = [];
3104
3215
  const walk = (rel) => {
3105
- const abs = rel ? path2.join(dir, rel) : dir;
3106
- for (const entry of fs2.readdirSync(abs, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
3216
+ const abs = rel ? path3.join(dir, rel) : dir;
3217
+ for (const entry of fs3.readdirSync(abs, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
3107
3218
  const childRel = rel ? `${rel}/${entry.name}` : entry.name;
3108
3219
  if (entry.isDirectory()) {
3109
3220
  if (!SKIP_DIRS.has(entry.name) && !entry.name.endsWith(".egg-info")) {
3110
3221
  walk(childRel);
3111
3222
  }
3112
3223
  } else if (entry.isFile()) {
3113
- const payload = fs2.readFileSync(path2.join(dir, childRel));
3224
+ const payload = fs3.readFileSync(path3.join(dir, childRel));
3114
3225
  entries.push({
3115
3226
  path: childRel,
3116
3227
  isDirectory: false,
3117
3228
  size: payload.length,
3118
- sha256: (0, import_node_crypto4.createHash)("sha256").update(payload).digest("hex")
3229
+ sha256: (0, import_node_crypto5.createHash)("sha256").update(payload).digest("hex")
3119
3230
  });
3120
3231
  }
3121
3232
  }
@@ -3138,7 +3249,7 @@ async function putObject(url, data, shaB64) {
3138
3249
  }
3139
3250
  async function push(dir, opts = {}) {
3140
3251
  const options = opts.options ?? {};
3141
- if (!fs2.statSync(dir).isDirectory()) throw new Error(`Not a directory: ${dir}`);
3252
+ if (!fs3.statSync(dir).isDirectory()) throw new Error(`Not a directory: ${dir}`);
3142
3253
  const localMeta = readLocalMeta(dir) ?? {};
3143
3254
  const branch = opts.branch ?? localMeta.branch ?? DEFAULT_BRANCH;
3144
3255
  const baseVersionId = opts.baseVersionId ?? localMeta.versionId ?? null;
@@ -3146,18 +3257,18 @@ async function push(dir, opts = {}) {
3146
3257
  const pyproject = readPyproject(dir);
3147
3258
  const contractVersion = pyproject.version ? void 0 : readWorldContractVersion(dir).version;
3148
3259
  if (contractVersion) pyproject.version = contractVersion;
3149
- const slug = opts.slug ?? localMeta.slug ?? pyproject.name ?? path2.basename(path2.resolve(dir));
3260
+ const slug = opts.slug ?? localMeta.slug ?? pyproject.name ?? path3.basename(path3.resolve(dir));
3261
+ const metadata = {
3262
+ name: opts.name ?? pyproject.name ?? slug,
3263
+ ...opts.description !== void 0 ? { description: opts.description } : {},
3264
+ ...opts.tags !== void 0 ? { tags: opts.tags } : {},
3265
+ ...opts.visibility ? { visibility: opts.visibility } : {}
3266
+ };
3150
3267
  const resolve6 = await apiRequest(
3151
3268
  options,
3152
3269
  "POST",
3153
3270
  "/api/public/benchmark-containers/resolve",
3154
- {
3155
- slug,
3156
- name: opts.name ?? pyproject.name ?? slug,
3157
- ...opts.description ? { description: opts.description } : {},
3158
- ...opts.tags?.length ? { tags: opts.tags } : {},
3159
- ...opts.visibility ? { visibility: opts.visibility } : {}
3160
- }
3271
+ { slug, ...metadata }
3161
3272
  );
3162
3273
  const tarball = buildSourceTarball(dir);
3163
3274
  const bundleSha256 = sha256b64(tarball);
@@ -3181,7 +3292,7 @@ async function push(dir, opts = {}) {
3181
3292
  options,
3182
3293
  "POST",
3183
3294
  `/api/public/benchmark-containers/versions/${version.versionId}/finalize`,
3184
- { branch, baseVersionId, ...opts.force ? { force: true } : {} }
3295
+ { branch, baseVersionId, ...opts.force ? { force: true } : {}, ...metadata }
3185
3296
  );
3186
3297
  writeLocalMeta(dir, {
3187
3298
  ...localMeta,
@@ -3226,9 +3337,9 @@ function extractBundle(bundle, dir) {
3226
3337
  longName = null;
3227
3338
  if (typeflag !== "0" && typeflag !== "") continue;
3228
3339
  if (name.startsWith("/") || name.split("/").includes("..")) continue;
3229
- const target = path2.join(dir, name);
3230
- fs2.mkdirSync(path2.dirname(target), { recursive: true });
3231
- fs2.writeFileSync(target, body);
3340
+ const target = path3.join(dir, name);
3341
+ fs3.mkdirSync(path3.dirname(target), { recursive: true });
3342
+ fs3.writeFileSync(target, body);
3232
3343
  written++;
3233
3344
  }
3234
3345
  return written;
@@ -3244,13 +3355,13 @@ async function pull(slugRef, target, options = {}) {
3244
3355
  if (!details.downloadUrl) {
3245
3356
  throw new Error(`${slug}@${ref} resolved but has no uploaded bundle`);
3246
3357
  }
3247
- let dir = target ?? path2.join(process.cwd(), slug);
3358
+ let dir = target ?? path3.join(process.cwd(), slug);
3248
3359
  if (!target) {
3249
3360
  let i = 1;
3250
3361
  const base = dir;
3251
- while (fs2.existsSync(dir)) dir = `${base}-${i++}`;
3362
+ while (fs3.existsSync(dir)) dir = `${base}-${i++}`;
3252
3363
  }
3253
- fs2.mkdirSync(dir, { recursive: true });
3364
+ fs3.mkdirSync(dir, { recursive: true });
3254
3365
  const resp = await fetch(details.downloadUrl);
3255
3366
  if (!resp.ok) throw new Error(`bundle download -> ${resp.status}`);
3256
3367
  const bundle = Buffer.from(await resp.arrayBuffer());
@@ -3280,12 +3391,12 @@ async function propose(dir, opts) {
3280
3391
  const state2 = localTreeState(dir);
3281
3392
  if (state2.clean) throw new Error("Nothing to propose \u2014 the tree matches its base.");
3282
3393
  const changes = state2.dirty.map((relPath) => {
3283
- const abs = path2.join(dir, relPath);
3284
- if (!fs2.existsSync(abs)) return { path: relPath, action: "delete" };
3394
+ const abs = path3.join(dir, relPath);
3395
+ if (!fs3.existsSync(abs)) return { path: relPath, action: "delete" };
3285
3396
  return {
3286
3397
  path: relPath,
3287
3398
  action: "write",
3288
- newContent: fs2.readFileSync(abs, "utf-8")
3399
+ newContent: fs3.readFileSync(abs, "utf-8")
3289
3400
  };
3290
3401
  });
3291
3402
  const res = await apiRequest(
@@ -3311,17 +3422,18 @@ async function createRef(slug, name, kind, versionId, options = {}) {
3311
3422
  ...versionId ? { versionId } : {}
3312
3423
  });
3313
3424
  }
3314
- var import_node_crypto4, import_node_zlib, fs2, path2, DEFAULT_BRANCH, META_RELPATH, SKIP_DIRS, ROOT_EXCLUDED_DIRS, BROAD_ROOT_MARKERS, sha256b64;
3425
+ var import_node_crypto5, import_node_zlib, fs3, path3, DEFAULT_BRANCH, META_RELPATH, SKIP_DIRS, sha256b64;
3315
3426
  var init_hub = __esm({
3316
3427
  "src/worlds/hub.ts"() {
3317
3428
  "use strict";
3318
- import_node_crypto4 = require("crypto");
3429
+ import_node_crypto5 = require("crypto");
3319
3430
  import_node_zlib = require("zlib");
3320
- fs2 = __toESM(require("fs"));
3321
- path2 = __toESM(require("path"));
3431
+ fs3 = __toESM(require("fs"));
3432
+ path3 = __toESM(require("path"));
3322
3433
  init_worlds();
3434
+ init_worldDir();
3323
3435
  DEFAULT_BRANCH = "main";
3324
- META_RELPATH = path2.join(".gateway", ".env-metadata.json");
3436
+ META_RELPATH = path3.join(".gateway", ".env-metadata.json");
3325
3437
  SKIP_DIRS = /* @__PURE__ */ new Set([
3326
3438
  ".git",
3327
3439
  "__pycache__",
@@ -3332,9 +3444,7 @@ var init_hub = __esm({
3332
3444
  "build",
3333
3445
  "outputs"
3334
3446
  ]);
3335
- ROOT_EXCLUDED_DIRS = /* @__PURE__ */ new Set(["dist", "build", "outputs", "__pycache__"]);
3336
- BROAD_ROOT_MARKERS = ["gateway-env.toml", "gateway-api-world.toml"];
3337
- sha256b64 = (data) => (0, import_node_crypto4.createHash)("sha256").update(data).digest("base64");
3447
+ sha256b64 = (data) => (0, import_node_crypto5.createHash)("sha256").update(data).digest("base64");
3338
3448
  }
3339
3449
  });
3340
3450
 
@@ -3850,15 +3960,15 @@ function applyTransforms(value, chain) {
3850
3960
  for (const step of steps) out = step(out);
3851
3961
  return out;
3852
3962
  }
3853
- var import_node_crypto5, WHITESPACE, WHITESPACE_EDGES, WHITESPACE_RUN, NOT_DIGIT, STRIP_PREFIX, trim, emailLocalPart, emailDomain, stripPrefix, hex, SIMPLE, TRANSFORMS, text;
3963
+ var import_node_crypto6, WHITESPACE, WHITESPACE_EDGES, WHITESPACE_RUN, NOT_DIGIT, STRIP_PREFIX, trim, emailLocalPart, emailDomain, stripPrefix, hex, SIMPLE, TRANSFORMS, text;
3854
3964
  var init_transforms = __esm({
3855
3965
  "src/worlds/transforms.ts"() {
3856
3966
  "use strict";
3857
- import_node_crypto5 = require("crypto");
3967
+ import_node_crypto6 = require("crypto");
3858
3968
  init_json();
3859
3969
  WHITESPACE = " \n\r\f\v";
3860
- WHITESPACE_EDGES = /^[ \t\n\r\f\v]+|[ \t\n\r\f\v]+$/g;
3861
- WHITESPACE_RUN = /[ \t\n\r\f\v]+/g;
3970
+ WHITESPACE_EDGES = new RegExp(`^[${WHITESPACE}]+|[${WHITESPACE}]+$`, "g");
3971
+ WHITESPACE_RUN = new RegExp(`[${WHITESPACE}]+`, "g");
3862
3972
  NOT_DIGIT = /[^0-9]/g;
3863
3973
  STRIP_PREFIX = "strip_prefix";
3864
3974
  trim = (value) => value.replace(WHITESPACE_EDGES, "");
@@ -3871,7 +3981,7 @@ var init_transforms = __esm({
3871
3981
  return at === -1 ? "" : value.slice(at + 1).toLowerCase();
3872
3982
  };
3873
3983
  stripPrefix = (prefix) => (value) => value.startsWith(prefix) ? value.slice(prefix.length) : value;
3874
- hex = (algorithm, value) => (0, import_node_crypto5.createHash)(algorithm).update(value, "utf8").digest("hex");
3984
+ hex = (algorithm, value) => (0, import_node_crypto6.createHash)(algorithm).update(value, "utf8").digest("hex");
3875
3985
  SIMPLE = {
3876
3986
  lower: (value) => value.toLowerCase(),
3877
3987
  upper: (value) => value.toUpperCase(),
@@ -3903,7 +4013,7 @@ function pyText(value) {
3903
4013
  return pyFloatRepr(value);
3904
4014
  }
3905
4015
  function hashForm(slug, plaintext) {
3906
- return "sha256:" + (0, import_node_crypto6.createHash)("sha256").update(`${slug}:${pyText(plaintext)}`, "utf8").digest("hex");
4016
+ return "sha256:" + (0, import_node_crypto7.createHash)("sha256").update(`${slug}:${pyText(plaintext)}`, "utf8").digest("hex");
3907
4017
  }
3908
4018
  function preserveForm(slug, plaintext) {
3909
4019
  const kind = typeof plaintext === "string" ? "str" : isInt(plaintext) ? "int" : "float";
@@ -3912,12 +4022,12 @@ function preserveForm(slug, plaintext) {
3912
4022
  }
3913
4023
  function shapeText(slug, text2, kind) {
3914
4024
  const seed = Buffer.from(`${slug}:${text2}`, "utf8");
3915
- let digest = (0, import_node_crypto6.createHash)("sha256").update(seed).digest();
4025
+ let digest = (0, import_node_crypto7.createHash)("sha256").update(seed).digest();
3916
4026
  let cursor = 0;
3917
4027
  const out = [];
3918
4028
  for (const char of text2) {
3919
4029
  if (cursor === digest.length) {
3920
- digest = (0, import_node_crypto6.createHash)("sha256").update(Buffer.concat([digest, seed])).digest();
4030
+ digest = (0, import_node_crypto7.createHash)("sha256").update(Buffer.concat([digest, seed])).digest();
3921
4031
  cursor = 0;
3922
4032
  }
3923
4033
  const byte = digest[cursor];
@@ -3954,11 +4064,11 @@ function storedForms(world, field, plaintext, transform) {
3954
4064
  if (policy !== null) return [roundForm(plaintext, world.redact.round[field])];
3955
4065
  return [plaintext];
3956
4066
  }
3957
- var import_node_crypto6, isInt;
4067
+ var import_node_crypto7, isInt;
3958
4068
  var init_redaction = __esm({
3959
4069
  "src/worlds/redaction.ts"() {
3960
4070
  "use strict";
3961
- import_node_crypto6 = require("crypto");
4071
+ import_node_crypto7 = require("crypto");
3962
4072
  init_json();
3963
4073
  init_transforms();
3964
4074
  isInt = (value) => typeof value === "number" && Number.isInteger(value);
@@ -3966,8 +4076,9 @@ var init_redaction = __esm({
3966
4076
  });
3967
4077
 
3968
4078
  // src/worlds/query.ts
3969
- function queryRowsSearch(entity, opts = {}) {
4079
+ function queryRowsSearch(entity, opts = {}, ref) {
3970
4080
  const search = new URLSearchParams();
4081
+ if (ref) search.set("ref", ref);
3971
4082
  search.set("entity", entity);
3972
4083
  if (opts.where && Object.keys(opts.where).length) search.set("where", JSON.stringify(opts.where));
3973
4084
  if (opts.limit !== void 0) search.set("limit", String(opts.limit));
@@ -3977,17 +4088,15 @@ function queryRowsSearch(entity, opts = {}) {
3977
4088
  if (opts.compare) search.set("compare", "true");
3978
4089
  return `?${search.toString()}`;
3979
4090
  }
3980
- async function queryRows(slug, entity, opts = {}, options = {}) {
3981
- if (slug.includes("@"))
3982
- throw new Error(
3983
- `queryRows reads a world's head version: pass the slug without @ref (got ${slug})`
3984
- );
4091
+ async function queryRows(slugRef, entity, opts = {}, options = {}) {
4092
+ const [slug, ref] = slugRef.split("@", 2);
4093
+ if (!slug || ref === "") throw new Error(`queryRows needs a slug, optionally slug@ref (got ${slugRef})`);
3985
4094
  if (!entity) throw new Error("queryRows needs an entity");
3986
4095
  if (opts.compare && !opts.across) throw new Error("queryRows: compare needs across");
3987
4096
  return apiRequest(
3988
4097
  options,
3989
4098
  "GET",
3990
- `/api/public/worlds/${encodeURIComponent(slug)}/data${queryRowsSearch(entity, opts)}`
4099
+ `/api/public/worlds/${encodeURIComponent(slug)}/data${queryRowsSearch(entity, opts, ref)}`
3991
4100
  );
3992
4101
  }
3993
4102
  var init_query = __esm({
@@ -4064,13 +4173,13 @@ async function api(creds, method, route, body, init2 = {}) {
4064
4173
  clearTimeout(timer);
4065
4174
  }
4066
4175
  }
4067
- var fs3, os, path3, ApiError;
4176
+ var fs4, os, path4, ApiError;
4068
4177
  var init_config = __esm({
4069
4178
  "src/cli/config.ts"() {
4070
4179
  "use strict";
4071
- fs3 = __toESM(require("fs"));
4180
+ fs4 = __toESM(require("fs"));
4072
4181
  os = __toESM(require("os"));
4073
- path3 = __toESM(require("path"));
4182
+ path4 = __toESM(require("path"));
4074
4183
  init_router();
4075
4184
  ApiError = class extends CliError {
4076
4185
  constructor(status, method, route, text2) {
@@ -4099,16 +4208,16 @@ function runtimeRoot() {
4099
4208
  const candidates = [];
4100
4209
  if (process.env.GATEWAY_RUNTIME_PATH)
4101
4210
  candidates.push(process.env.GATEWAY_RUNTIME_PATH);
4102
- const entry = process.argv[1] && fs4.existsSync(process.argv[1]) ? path4.dirname(fs4.realpathSync(process.argv[1])) : null;
4211
+ const entry = process.argv[1] && fs5.existsSync(process.argv[1]) ? path5.dirname(fs5.realpathSync(process.argv[1])) : null;
4103
4212
  if (entry) {
4104
- candidates.push(path4.resolve(entry, "..", "runtime"));
4105
- candidates.push(path4.resolve(entry, "..", "..", "runtime"));
4106
- candidates.push(path4.resolve(entry, "..", "..", "sdk", "src"));
4213
+ candidates.push(path5.resolve(entry, "..", "runtime"));
4214
+ candidates.push(path5.resolve(entry, "..", "..", "runtime"));
4215
+ candidates.push(path5.resolve(entry, "..", "..", "sdk", "src"));
4107
4216
  }
4108
- candidates.push(path4.resolve(process.cwd(), "runtime"));
4217
+ candidates.push(path5.resolve(process.cwd(), "runtime"));
4109
4218
  for (const root of candidates)
4110
- if (fs4.existsSync(
4111
- path4.join(root, "gatewaysdk", "environment", "schema", "platform.py")
4219
+ if (fs5.existsSync(
4220
+ path5.join(root, "gatewaysdk", "environment", "schema", "platform.py")
4112
4221
  ))
4113
4222
  return root;
4114
4223
  return null;
@@ -4249,14 +4358,14 @@ async function localBridge(request, local, opts = {}) {
4249
4358
  child.stdin.end(input);
4250
4359
  });
4251
4360
  }
4252
- var import_node_child_process, fs4, net, path4, MIN_PYTHON, DIAGNOSTIC_TAIL, BRIDGE_BOOTSTRAP, pythonCache, pythonProbes, PYTHON_CANDIDATES, UV_FIND;
4361
+ var import_node_child_process, fs5, net, path5, MIN_PYTHON, DIAGNOSTIC_TAIL, BRIDGE_BOOTSTRAP, pythonCache, pythonProbes, PYTHON_CANDIDATES, UV_FIND;
4253
4362
  var init_local = __esm({
4254
4363
  "src/cli/runtime/local.ts"() {
4255
4364
  "use strict";
4256
4365
  import_node_child_process = require("child_process");
4257
- fs4 = __toESM(require("fs"));
4366
+ fs5 = __toESM(require("fs"));
4258
4367
  net = __toESM(require("net"));
4259
- path4 = __toESM(require("path"));
4368
+ path5 = __toESM(require("path"));
4260
4369
  init_router();
4261
4370
  init_config();
4262
4371
  MIN_PYTHON = [3, 11];
@@ -4284,12 +4393,12 @@ function isBuildOutput(relPath) {
4284
4393
  return BUILD_OUTPUT.test(relPath);
4285
4394
  }
4286
4395
  function readWorldFiles(dir, opts = {}) {
4287
- if (!fs5.existsSync(dir) || !fs5.statSync(dir).isDirectory())
4396
+ if (!fs6.existsSync(dir) || !fs6.statSync(dir).isDirectory())
4288
4397
  throw new CliError(`Not a directory: ${dir}`);
4289
4398
  const out = [];
4290
4399
  const walk = (rel) => {
4291
- const abs = rel ? path5.join(dir, rel) : dir;
4292
- const entries = fs5.readdirSync(abs, { withFileTypes: true });
4400
+ const abs = rel ? path6.join(dir, rel) : dir;
4401
+ const entries = fs6.readdirSync(abs, { withFileTypes: true });
4293
4402
  entries.sort((a, b) => a.name.localeCompare(b.name));
4294
4403
  for (const entry of entries) {
4295
4404
  const childRel = rel ? `${rel}/${entry.name}` : entry.name;
@@ -4299,7 +4408,7 @@ function readWorldFiles(dir, opts = {}) {
4299
4408
  if (!opts.buildOutputs && isBuildOutput(childRel)) continue;
4300
4409
  out.push({
4301
4410
  path: childRel,
4302
- content: fs5.readFileSync(path5.join(dir, childRel)).toString("base64")
4411
+ content: fs6.readFileSync(path6.join(dir, childRel)).toString("base64")
4303
4412
  });
4304
4413
  }
4305
4414
  }
@@ -4314,19 +4423,19 @@ function assertSafeRelPath(rel) {
4314
4423
  }
4315
4424
  function writeWorldFiles(dir, files, opts = {}) {
4316
4425
  for (const file of files) assertSafeRelPath(file.path);
4317
- if (opts.clean && fs5.existsSync(dir)) {
4426
+ if (opts.clean && fs6.existsSync(dir)) {
4318
4427
  const keep = new Set(files.map((f) => f.path));
4319
4428
  for (const existing of readWorldFiles(dir)) {
4320
- if (!keep.has(existing.path)) fs5.rmSync(path5.join(dir, existing.path));
4429
+ if (!keep.has(existing.path)) fs6.rmSync(path6.join(dir, existing.path));
4321
4430
  }
4322
4431
  pruneEmptyDirs(dir);
4323
4432
  }
4324
- fs5.mkdirSync(dir, { recursive: true });
4433
+ fs6.mkdirSync(dir, { recursive: true });
4325
4434
  const written = [];
4326
4435
  for (const file of files) {
4327
- const target = path5.join(dir, file.path);
4328
- fs5.mkdirSync(path5.dirname(target), { recursive: true });
4329
- fs5.writeFileSync(target, Buffer.from(file.content, "base64"));
4436
+ const target = path6.join(dir, file.path);
4437
+ fs6.mkdirSync(path6.dirname(target), { recursive: true });
4438
+ fs6.writeFileSync(target, Buffer.from(file.content, "base64"));
4330
4439
  written.push(file.path);
4331
4440
  }
4332
4441
  return written;
@@ -4334,14 +4443,14 @@ function writeWorldFiles(dir, files, opts = {}) {
4334
4443
  function pruneEmptyDirs(root) {
4335
4444
  const walk = (abs) => {
4336
4445
  let empty = true;
4337
- for (const entry of fs5.readdirSync(abs, { withFileTypes: true })) {
4338
- const child = path5.join(abs, entry.name);
4446
+ for (const entry of fs6.readdirSync(abs, { withFileTypes: true })) {
4447
+ const child = path6.join(abs, entry.name);
4339
4448
  if (entry.isDirectory()) {
4340
4449
  if (SKIP_DIRS2.has(entry.name)) {
4341
4450
  empty = false;
4342
4451
  continue;
4343
4452
  }
4344
- if (walk(child)) fs5.rmdirSync(child);
4453
+ if (walk(child)) fs6.rmdirSync(child);
4345
4454
  else empty = false;
4346
4455
  } else empty = false;
4347
4456
  }
@@ -4405,12 +4514,12 @@ async function runtime(creds, request, opts = {}) {
4405
4514
  clearTimeout(timer);
4406
4515
  }
4407
4516
  }
4408
- var fs5, path5, SKIP_DIRS2, BUILD_OUTPUT, BridgeRejected;
4517
+ var fs6, path6, SKIP_DIRS2, BUILD_OUTPUT, BridgeRejected;
4409
4518
  var init_client = __esm({
4410
4519
  "src/cli/runtime/client.ts"() {
4411
4520
  "use strict";
4412
- fs5 = __toESM(require("fs"));
4413
- path5 = __toESM(require("path"));
4521
+ fs6 = __toESM(require("fs"));
4522
+ path6 = __toESM(require("path"));
4414
4523
  init_router();
4415
4524
  init_local();
4416
4525
  SKIP_DIRS2 = /* @__PURE__ */ new Set(["__pycache__", ".git", "node_modules", ".gateway"]);
@@ -4460,7 +4569,7 @@ function dropBuildOutputs(dir) {
4460
4569
  const dropped = [];
4461
4570
  for (const file of readWorldFiles(dir, { buildOutputs: true })) {
4462
4571
  if (!BUILD_OUTPUT2.test(file.path)) continue;
4463
- fs6.rmSync(path6.join(dir, file.path), { force: true });
4572
+ fs7.rmSync(path7.join(dir, file.path), { force: true });
4464
4573
  dropped.push(file.path);
4465
4574
  }
4466
4575
  return dropped;
@@ -4471,6 +4580,7 @@ async function checkLocalWorldData(dir, rows, creds, opts = {}) {
4471
4580
  files: readWorldFiles(dir),
4472
4581
  rows,
4473
4582
  mode: "append",
4583
+ dry_run: true,
4474
4584
  ...opts.redact && opts.redact !== "off" ? { redact: opts.redact } : {}
4475
4585
  });
4476
4586
  return {
@@ -4526,7 +4636,7 @@ async function queryLocalWorldDataAcross(dir, entity, where, opts) {
4526
4636
  const payload = await localBridge(
4527
4637
  {
4528
4638
  command: "query",
4529
- world: path6.resolve(dir),
4639
+ world: path7.resolve(dir),
4530
4640
  entity,
4531
4641
  across: true,
4532
4642
  ...opts.compare ? { compare: true } : {},
@@ -4573,12 +4683,12 @@ async function ingestLocalToolCalls(dir, records, opts, creds) {
4573
4683
  ...res.batch !== void 0 ? { batch: res.batch } : {}
4574
4684
  };
4575
4685
  }
4576
- var fs6, path6, BUILD_OUTPUT2;
4686
+ var fs7, path7, BUILD_OUTPUT2;
4577
4687
  var init_data = __esm({
4578
4688
  "src/cli/runtime/data.ts"() {
4579
4689
  "use strict";
4580
- fs6 = __toESM(require("fs"));
4581
- path6 = __toESM(require("path"));
4690
+ fs7 = __toESM(require("fs"));
4691
+ path7 = __toESM(require("path"));
4582
4692
  init_router();
4583
4693
  init_client();
4584
4694
  init_local();
@@ -4621,27 +4731,27 @@ function typescriptPrefix() {
4621
4731
  }
4622
4732
  }
4623
4733
  function command(script, wrapperDir) {
4624
- const suffix = path7.extname(script).toLowerCase();
4734
+ const suffix = path8.extname(script).toLowerCase();
4625
4735
  if (PYTHON_SUFFIXES.includes(suffix)) return { file: process.env.GATEWAY_PYTHON || "python3", args: ["-c", PY_WRAPPER, script] };
4626
4736
  if (NODE_SUFFIXES.includes(suffix)) {
4627
- const wrapper = path7.join(wrapperDir, "transform-wrapper.mjs");
4628
- fs7.writeFileSync(wrapper, NODE_WRAPPER);
4737
+ const wrapper = path8.join(wrapperDir, "transform-wrapper.mjs");
4738
+ fs8.writeFileSync(wrapper, NODE_WRAPPER);
4629
4739
  const flags = suffix === ".ts" || suffix === ".mts" ? typescriptPrefix() : [];
4630
4740
  return { file: process.env.GATEWAY_NODE || process.execPath, args: [...flags, wrapper, script] };
4631
4741
  }
4632
- throw new CliError(`${path7.basename(script)}: a transform script is .py, .ts, .mjs, .js or .cjs`, 1);
4742
+ throw new CliError(`${path8.basename(script)}: a transform script is .py, .ts, .mjs, .js or .cjs`, 1);
4633
4743
  }
4634
4744
  async function runTransform(script, records, opts = {}) {
4635
- if (!fs7.existsSync(script) || !fs7.statSync(script).isFile()) throw new CliError(`no transform script at ${script}`, 1);
4636
- const resolved = path7.resolve(script);
4637
- const name = path7.basename(script);
4745
+ if (!fs8.existsSync(script) || !fs8.statSync(script).isFile()) throw new CliError(`no transform script at ${script}`, 1);
4746
+ const resolved = path8.resolve(script);
4747
+ const name = path8.basename(script);
4638
4748
  const timeoutMs = opts.timeoutMs ?? DEFAULT_TRANSFORM_TIMEOUT_MS;
4639
- const scratch = fs7.mkdtempSync(path7.join(os2.tmpdir(), "gateway-transform-"));
4749
+ const scratch = fs8.mkdtempSync(path8.join(os2.tmpdir(), "gateway-transform-"));
4640
4750
  try {
4641
4751
  const { file, args } = command(resolved, scratch);
4642
4752
  const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !SCRUBBED.test(key)));
4643
4753
  const done = await new Promise((resolve6, reject) => {
4644
- const child = (0, import_node_child_process2.spawn)(file, args, { cwd: path7.dirname(resolved), env, stdio: ["pipe", "pipe", "pipe"] });
4754
+ const child = (0, import_node_child_process2.spawn)(file, args, { cwd: path8.dirname(resolved), env, stdio: ["pipe", "pipe", "pipe"] });
4645
4755
  let stdout = "";
4646
4756
  let stderr = "";
4647
4757
  let timedOut = false;
@@ -4672,21 +4782,21 @@ async function runTransform(script, records, opts = {}) {
4672
4782
  }
4673
4783
  return { rows: checkRows(value, name), stderr: done.stderr };
4674
4784
  } finally {
4675
- fs7.rmSync(scratch, { recursive: true, force: true });
4785
+ fs8.rmSync(scratch, { recursive: true, force: true });
4676
4786
  }
4677
4787
  }
4678
4788
  async function transformRecords(transform, records, opts = {}) {
4679
4789
  if (typeof transform === "function") return { rows: checkRows(await transform(records), "transform(records)"), stderr: "" };
4680
4790
  return runTransform(transform, records, opts);
4681
4791
  }
4682
- 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;
4792
+ 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;
4683
4793
  var init_transform = __esm({
4684
4794
  "src/cli/platform/worldData/transform.ts"() {
4685
4795
  "use strict";
4686
4796
  import_node_child_process2 = require("child_process");
4687
- fs7 = __toESM(require("fs"));
4797
+ fs8 = __toESM(require("fs"));
4688
4798
  os2 = __toESM(require("os"));
4689
- path7 = __toESM(require("path"));
4799
+ path8 = __toESM(require("path"));
4690
4800
  import_node_module = require("module");
4691
4801
  init_router();
4692
4802
  import_meta = {};
@@ -4770,11 +4880,16 @@ if (fn) {
4770
4880
  });
4771
4881
 
4772
4882
  // src/cli/platform/worldData/batches.ts
4883
+ function isSettled(status) {
4884
+ if (!TERMINAL_STATES.has(status.state)) return false;
4885
+ if (status.state !== "applied") return true;
4886
+ return status.dryRun === true || status.publish !== "now" || !status.snapshotId;
4887
+ }
4773
4888
  function uploadHeadersFor(gz) {
4774
4889
  return {
4775
4890
  "content-type": "application/gzip",
4776
4891
  "content-length": String(gz.length),
4777
- "x-amz-checksum-sha256": (0, import_node_crypto7.createHash)("sha256").update(gz).digest("base64")
4892
+ "x-amz-checksum-sha256": (0, import_node_crypto8.createHash)("sha256").update(gz).digest("base64")
4778
4893
  };
4779
4894
  }
4780
4895
  async function forEachLimited(items, limit, fn) {
@@ -4811,7 +4926,7 @@ async function waitForBatch(client, batchId, opts = {}) {
4811
4926
  opts.onPhase?.(phase);
4812
4927
  last = phase;
4813
4928
  }
4814
- if (TERMINAL_STATES.has(status.state)) return status;
4929
+ if (isSettled(status)) return status;
4815
4930
  await sleep2(delay);
4816
4931
  delay = Math.min(1e4, Math.round(delay * 1.5));
4817
4932
  }
@@ -4820,12 +4935,12 @@ function phaseLine(status) {
4820
4935
  const phase = status.progress?.phase;
4821
4936
  return phase ? `${status.state} (${phase})` : status.state;
4822
4937
  }
4823
- var import_node_crypto7, fs8, TERMINAL_STATES, sleepMs, WorldDataApi;
4938
+ var import_node_crypto8, fs9, TERMINAL_STATES, sleepMs, WorldDataApi;
4824
4939
  var init_batches = __esm({
4825
4940
  "src/cli/platform/worldData/batches.ts"() {
4826
4941
  "use strict";
4827
- import_node_crypto7 = require("crypto");
4828
- fs8 = __toESM(require("fs"));
4942
+ import_node_crypto8 = require("crypto");
4943
+ fs9 = __toESM(require("fs"));
4829
4944
  init_config();
4830
4945
  init_router();
4831
4946
  TERMINAL_STATES = /* @__PURE__ */ new Set(["applied", "refused", "published", "failed"]);
@@ -4936,12 +5051,12 @@ function finishChunk(ordinal, raw, rows, entity, firstRow = 0) {
4936
5051
  const gz = gzipDeterministic(raw, { name: chunkName(ordinal) });
4937
5052
  return {
4938
5053
  ordinal,
4939
- digest: (0, import_node_crypto8.createHash)("sha256").update(gz).digest("hex"),
5054
+ digest: (0, import_node_crypto9.createHash)("sha256").update(gz).digest("hex"),
4940
5055
  bytes: gz.length,
4941
5056
  rows,
4942
5057
  entity,
4943
5058
  rawBytes: raw.length,
4944
- contentSha256: (0, import_node_crypto8.createHash)("sha256").update(raw).digest("hex"),
5059
+ contentSha256: (0, import_node_crypto9.createHash)("sha256").update(raw).digest("hex"),
4945
5060
  firstRow,
4946
5061
  gz
4947
5062
  };
@@ -4969,11 +5084,11 @@ function crc32(data) {
4969
5084
  for (let i = 0; i < data.length; i++) crc = table[(crc ^ data[i]) & 255] ^ crc >>> 8;
4970
5085
  return (crc ^ 4294967295) >>> 0;
4971
5086
  }
4972
- var import_node_crypto8, import_node_zlib2, DEFAULT_CHUNK_BYTES, GZIP_LEVEL, chunkName, table;
5087
+ var import_node_crypto9, import_node_zlib2, DEFAULT_CHUNK_BYTES, GZIP_LEVEL, chunkName, table;
4973
5088
  var init_chunker = __esm({
4974
5089
  "src/cli/platform/worldData/chunker.ts"() {
4975
5090
  "use strict";
4976
- import_node_crypto8 = require("crypto");
5091
+ import_node_crypto9 = require("crypto");
4977
5092
  import_node_zlib2 = require("zlib");
4978
5093
  init_json();
4979
5094
  DEFAULT_CHUNK_BYTES = 64 * 1024 * 1024;
@@ -5046,7 +5161,7 @@ function parseToolCallRecord(raw) {
5046
5161
  }
5047
5162
  function readToolCallRecords(paths) {
5048
5163
  const records = [];
5049
- for (const file of paths) records.push(...toolCallRecordsIn(fs9.readFileSync(file, "utf8"), file));
5164
+ for (const file of paths) records.push(...toolCallRecordsIn(fs10.readFileSync(file, "utf8"), file));
5050
5165
  return records;
5051
5166
  }
5052
5167
  function toolCallRecordsIn(text2, where) {
@@ -5082,7 +5197,7 @@ async function emit(sink, record) {
5082
5197
  return;
5083
5198
  }
5084
5199
  if (typeof sink === "string") {
5085
- fs9.appendFileSync(sink, JSON.stringify(record) + "\n");
5200
+ fs10.appendFileSync(sink, JSON.stringify(record) + "\n");
5086
5201
  return;
5087
5202
  }
5088
5203
  if (typeof sink === "function") {
@@ -5113,14 +5228,6 @@ function captureToolCalls(tools, sink, opts = {}) {
5113
5228
  }
5114
5229
  return wrapped;
5115
5230
  }
5116
- function jsonish(value) {
5117
- if (typeof value !== "string") return value;
5118
- try {
5119
- return JSON.parse(value);
5120
- } catch {
5121
- return value;
5122
- }
5123
- }
5124
5231
  function toolCallsFromObservations(observations, opts = {}) {
5125
5232
  const known = opts.tools ? new Set(opts.tools) : null;
5126
5233
  const sinceMs = opts.since ? Date.parse(opts.since) : NaN;
@@ -5147,10 +5254,9 @@ function toolCallsFromObservations(observations, opts = {}) {
5147
5254
  out.unknownTools[tool] = (out.unknownTools[tool] ?? 0) + 1;
5148
5255
  continue;
5149
5256
  }
5150
- const input = jsonish(observation.input);
5151
- const record = { tool, args: isObject2(input) ? input : {} };
5257
+ const record = { tool, args: isObject2(observation.input) ? observation.input : {} };
5152
5258
  if (observation.level === "ERROR") record.error = observation.statusMessage || "ERROR";
5153
- else record.result = jsonish(observation.output);
5259
+ else record.result = observation.output;
5154
5260
  if (at !== void 0) record.at = at;
5155
5261
  if (opts.session) record.session = opts.session;
5156
5262
  record.source = `trace:${observation.traceId ?? "?"}/${observation.id ?? "?"}`;
@@ -5171,7 +5277,7 @@ async function ingest(world, records, options = {}) {
5171
5277
  const mode = options.mode ?? "append";
5172
5278
  const dryRun = Boolean(options.dryRun);
5173
5279
  const creds = credentialsOf(options);
5174
- const local = fs9.existsSync(world) && fs9.statSync(world).isDirectory();
5280
+ const local = fs10.existsSync(world) && fs10.statSync(world).isDirectory();
5175
5281
  const map = options.map === void 0 ? void 0 : options.map;
5176
5282
  let rows = null;
5177
5283
  let stderr = "";
@@ -5187,9 +5293,9 @@ async function ingest(world, records, options = {}) {
5187
5293
  if (!creds) throw new Error("Gateway keys missing: set GATEWAY_PUBLIC_KEY / GATEWAY_SECRET_KEY (or pass publicKey/secretKey).");
5188
5294
  const { pull: pull2 } = await Promise.resolve().then(() => (init_hub(), hub_exports));
5189
5295
  const slug = world.split("@", 1)[0];
5190
- const scratch = fs9.mkdtempSync(path8.join(os3.tmpdir(), "gateway-ingest-"));
5296
+ const scratch = fs10.mkdtempSync(path9.join(os3.tmpdir(), "gateway-ingest-"));
5191
5297
  try {
5192
- const pulled = await pull2(world, path8.join(scratch, slug), options);
5298
+ const pulled = await pull2(world, path9.join(scratch, slug), options);
5193
5299
  let report;
5194
5300
  let projected;
5195
5301
  if (rows === null) {
@@ -5210,7 +5316,7 @@ async function ingest(world, records, options = {}) {
5210
5316
  if (status.entityCounts) report.entityCounts = status.entityCounts;
5211
5317
  return report;
5212
5318
  } finally {
5213
- fs9.rmSync(scratch, { recursive: true, force: true });
5319
+ fs10.rmSync(scratch, { recursive: true, force: true });
5214
5320
  }
5215
5321
  }
5216
5322
  async function ingestToolCalls(world, records, options = {}) {
@@ -5263,13 +5369,13 @@ async function sessionToolObservations(sessionId, options = {}) {
5263
5369
  for (const observation of trace3.observations ?? []) out.push({ traceId: trace3.id ?? null, ...observation });
5264
5370
  return out;
5265
5371
  }
5266
- var fs9, os3, path8, isObject2, isoOf;
5372
+ var fs10, os3, path9, isObject2, isoOf;
5267
5373
  var init_ingest = __esm({
5268
5374
  "src/worlds/ingest.ts"() {
5269
5375
  "use strict";
5270
- fs9 = __toESM(require("fs"));
5376
+ fs10 = __toESM(require("fs"));
5271
5377
  os3 = __toESM(require("os"));
5272
- path8 = __toESM(require("path"));
5378
+ path9 = __toESM(require("path"));
5273
5379
  init_worlds();
5274
5380
  isObject2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
5275
5381
  isoOf = (value) => value instanceof Date ? value.toISOString() : typeof value === "string" ? value : void 0;
@@ -5323,7 +5429,6 @@ __export(worlds_exports, {
5323
5429
  hashForm: () => hashForm,
5324
5430
  ingest: () => ingest,
5325
5431
  ingestToolCalls: () => ingestToolCalls,
5326
- isIncludedInContentHash: () => isIncludedInContentHash,
5327
5432
  isTaskIdRef: () => isTaskIdRef,
5328
5433
  isTaskManifest: () => isTaskManifest,
5329
5434
  isTaskSpec: () => isTaskSpec,
@@ -5390,9 +5495,9 @@ function resolveEnv(options) {
5390
5495
  }
5391
5496
  return { host: host.replace(/\/+$/, ""), publicKey, secretKey };
5392
5497
  }
5393
- async function apiRequest(options, method, path9, body) {
5498
+ async function apiRequest(options, method, path10, body) {
5394
5499
  const { host, publicKey, secretKey } = resolveEnv(options);
5395
- const res = await fetch(`${host}${path9}`, {
5500
+ const res = await fetch(`${host}${path10}`, {
5396
5501
  method,
5397
5502
  headers: {
5398
5503
  "content-type": "application/json",
@@ -5401,7 +5506,7 @@ async function apiRequest(options, method, path9, body) {
5401
5506
  ...body === void 0 ? {} : { body: JSON.stringify(body) }
5402
5507
  });
5403
5508
  const text2 = await res.text();
5404
- if (!res.ok) throw new ApiError2(res.status, method, path9, text2.slice(0, 400));
5509
+ if (!res.ok) throw new ApiError2(res.status, method, path10, text2.slice(0, 400));
5405
5510
  return JSON.parse(text2);
5406
5511
  }
5407
5512
  async function setEnvSecret(slug, key, value, options = {}) {
@@ -5571,8 +5676,8 @@ var init_worlds = __esm({
5571
5676
  init_migrate();
5572
5677
  init_ingest();
5573
5678
  ApiError2 = class extends Error {
5574
- constructor(status, method, path9, body) {
5575
- super(`${method} ${path9} -> ${status}: ${body}`);
5679
+ constructor(status, method, path10, body) {
5680
+ super(`${method} ${path10} -> ${status}: ${body}`);
5576
5681
  this.status = status;
5577
5682
  this.name = "ApiError";
5578
5683
  }
@@ -5688,7 +5793,6 @@ init_worlds();
5688
5793
  hashForm,
5689
5794
  ingest,
5690
5795
  ingestToolCalls,
5691
- isIncludedInContentHash,
5692
5796
  isTaskIdRef,
5693
5797
  isTaskManifest,
5694
5798
  isTaskSpec,