@leitwerk-dev/worker 0.2.1 → 0.3.1

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.
@@ -1842,10 +1842,133 @@ var SdkPiTreeHandleFactory = class {
1842
1842
  }
1843
1843
  };
1844
1844
 
1845
+ // src/pi-resource-bundle.ts
1846
+ import { randomUUID } from "crypto";
1847
+ import { mkdir as mkdir2, open, readFile, rename, rm, writeFile as writeFile2 } from "fs/promises";
1848
+ import path3 from "path";
1849
+ import {
1850
+ createCanonicalPiResourceBundle,
1851
+ sha256Digest,
1852
+ validateResourceRelativePath,
1853
+ verifyCanonicalPiResourceBundle
1854
+ } from "@leitwerk-dev/worker-protocol";
1855
+ function fail(message) {
1856
+ throw new Error(`Invalid Pi resource bundle: ${message}`);
1857
+ }
1858
+ function requireStorageName(value, label) {
1859
+ if (!/^[a-zA-Z0-9_-]+$/u.test(value)) fail(`unsafe ${label}: ${value}`);
1860
+ return value;
1861
+ }
1862
+ async function atomicWrite(pathname, content, mode) {
1863
+ const staging = `${pathname}.staging-${process.pid}-${randomUUID()}`;
1864
+ const handle = await open(staging, "wx", mode);
1865
+ try {
1866
+ await handle.writeFile(content);
1867
+ await handle.sync();
1868
+ } finally {
1869
+ await handle.close();
1870
+ }
1871
+ try {
1872
+ await rename(staging, pathname);
1873
+ } catch (error) {
1874
+ await rm(staging, { force: true });
1875
+ throw error;
1876
+ }
1877
+ }
1878
+ async function persistPiResourceBundleForStart(input) {
1879
+ const digest = requireStorageName(input.digest, "resource digest");
1880
+ const startRecordId = requireStorageName(input.startRecordId, "turn-start id");
1881
+ const bundlesDir = path3.resolve(input.bundlesDir);
1882
+ const startsDir = path3.join(bundlesDir, "starts");
1883
+ const bundlePath = path3.join(bundlesDir, `${digest}.tar`);
1884
+ await mkdir2(startsDir, { recursive: true, mode: 448 });
1885
+ let bundle = null;
1886
+ let reused = false;
1887
+ try {
1888
+ const existing = await readFile(bundlePath);
1889
+ verifyCanonicalPiResourceBundle(existing, digest);
1890
+ bundle = existing;
1891
+ reused = true;
1892
+ } catch (error) {
1893
+ if (error.code !== "ENOENT" && input.archiveBase64 === void 0) {
1894
+ throw error;
1895
+ }
1896
+ }
1897
+ if (!bundle) {
1898
+ if (!input.deliveredBundle && input.archiveBase64 === void 0) {
1899
+ throw new Error(`Pi resource bundle '${digest}' is unavailable on the process volume`);
1900
+ }
1901
+ bundle = input.deliveredBundle ?? Buffer.from(input.archiveBase64, "base64");
1902
+ verifyCanonicalPiResourceBundle(bundle, digest);
1903
+ await atomicWrite(bundlePath, bundle, 384);
1904
+ }
1905
+ const manifest = Buffer.from(
1906
+ `${JSON.stringify({ startRecordId, digest, persistedAt: (/* @__PURE__ */ new Date()).toISOString() })}
1907
+ `,
1908
+ "utf8"
1909
+ );
1910
+ await atomicWrite(path3.join(startsDir, `${startRecordId}.json`), manifest, 384);
1911
+ return { bundle, reused };
1912
+ }
1913
+ async function writeExtractedFiles(root, files) {
1914
+ for (const file of files) {
1915
+ const output = path3.resolve(root, file.path);
1916
+ if (path3.relative(root, output).startsWith("..") || path3.isAbsolute(path3.relative(root, output))) {
1917
+ fail(`path escapes materialization root: ${file.path}`);
1918
+ }
1919
+ await mkdir2(path3.dirname(output), { recursive: true, mode: 448 });
1920
+ await writeFile2(output, file.content, { mode: 420, flag: "wx" });
1921
+ }
1922
+ }
1923
+ async function materializeCanonicalPiResourceBundle(input) {
1924
+ const files = verifyCanonicalPiResourceBundle(input.bundle, input.digest);
1925
+ const targetDir = path3.resolve(input.targetDir);
1926
+ const parent = path3.dirname(targetDir);
1927
+ await mkdir2(parent, { recursive: true, mode: 448 });
1928
+ const marker = path3.join(targetDir, ".leitwerk-resource-digest");
1929
+ try {
1930
+ const current = await import("fs/promises").then(
1931
+ ({ readFile: readFile5 }) => readFile5(marker, "utf8")
1932
+ );
1933
+ if (current === `${input.digest}
1934
+ `) return { targetDir, reused: true };
1935
+ throw new Error(
1936
+ `Managed Pi directory already exists with a different resource digest: ${targetDir}`
1937
+ );
1938
+ } catch (error) {
1939
+ if (error.code !== "ENOENT") throw error;
1940
+ }
1941
+ const staging = path3.join(
1942
+ parent,
1943
+ `.${path3.basename(targetDir)}.staging-${process.pid}-${randomUUID()}`
1944
+ );
1945
+ try {
1946
+ await mkdir2(staging, { mode: 448 });
1947
+ await writeExtractedFiles(staging, files);
1948
+ await writeFile2(path3.join(staging, ".leitwerk-resource-digest"), `${input.digest}
1949
+ `, {
1950
+ mode: 384,
1951
+ flag: "wx"
1952
+ });
1953
+ await rename(staging, targetDir);
1954
+ return { targetDir, reused: false };
1955
+ } catch (error) {
1956
+ await rm(staging, { recursive: true, force: true });
1957
+ if (error.code === "EEXIST") {
1958
+ const current = await import("fs/promises").then(
1959
+ ({ readFile: readFile5 }) => readFile5(marker, "utf8")
1960
+ );
1961
+ if (current === `${input.digest}
1962
+ `) return { targetDir, reused: true };
1963
+ }
1964
+ throw error;
1965
+ }
1966
+ }
1967
+
1845
1968
  // src/development-tool-environment.ts
1846
1969
  import { statfsSync } from "fs";
1847
- import { mkdir as mkdir2, rename, writeFile as writeFile2 } from "fs/promises";
1848
- import path3 from "path";
1970
+ import { mkdir as mkdir3, rename as rename2, writeFile as writeFile3 } from "fs/promises";
1971
+ import path4 from "path";
1849
1972
  import { execa } from "execa";
1850
1973
  var PINNED_MISE_VERSION = "2026.8.14";
1851
1974
  var OUTPUT_LIMIT_BYTES = 64 * 1024;
@@ -1926,18 +2049,18 @@ function buildMiseSubprocessEnvironment(base, config) {
1926
2049
  }
1927
2050
  }
1928
2051
  if (config.runner === "isolated") {
1929
- const miseRoot = path3.join(config.processStorageRoot, "tooling", "mise");
2052
+ const miseRoot = path4.join(config.processStorageRoot, "tooling", "mise");
1930
2053
  env.MISE_DATA_DIR = miseRoot;
1931
- env.MISE_INSTALLS_DIR = path3.join(miseRoot, "installs");
1932
- env.MISE_CACHE_DIR = path3.join(miseRoot, "cache");
1933
- env.MISE_STATE_DIR = path3.join(miseRoot, "state");
2054
+ env.MISE_INSTALLS_DIR = path4.join(miseRoot, "installs");
2055
+ env.MISE_CACHE_DIR = path4.join(miseRoot, "cache");
2056
+ env.MISE_STATE_DIR = path4.join(miseRoot, "state");
1934
2057
  }
1935
2058
  return env;
1936
2059
  }
1937
2060
  function localShimDirectory(env) {
1938
- if (env.MISE_DATA_DIR) return path3.join(env.MISE_DATA_DIR, "shims");
1939
- if (env.XDG_DATA_HOME) return path3.join(env.XDG_DATA_HOME, "mise", "shims");
1940
- return path3.join(env.HOME ?? "", ".local", "share", "mise", "shims");
2061
+ if (env.MISE_DATA_DIR) return path4.join(env.MISE_DATA_DIR, "shims");
2062
+ if (env.XDG_DATA_HOME) return path4.join(env.XDG_DATA_HOME, "mise", "shims");
2063
+ return path4.join(env.HOME ?? "", ".local", "share", "mise", "shims");
1941
2064
  }
1942
2065
  function emitDiagnosticTrace(trace, value) {
1943
2066
  if (!trace) return;
@@ -2112,11 +2235,11 @@ var MiseDevelopmentToolEnvironment = class {
2112
2235
  );
2113
2236
  if (input.config.runner === "isolated") {
2114
2237
  await Promise.all(
2115
- [env.MISE_DATA_DIR, env.MISE_INSTALLS_DIR, env.MISE_CACHE_DIR, env.MISE_STATE_DIR].filter((value) => Boolean(value)).map((directory) => mkdir2(directory, { recursive: true }))
2238
+ [env.MISE_DATA_DIR, env.MISE_INSTALLS_DIR, env.MISE_CACHE_DIR, env.MISE_STATE_DIR].filter((value) => Boolean(value)).map((directory) => mkdir3(directory, { recursive: true }))
2116
2239
  );
2117
2240
  }
2118
- const shimDirectory = input.config.runner === "isolated" ? path3.join(env.MISE_DATA_DIR, "shims") : localShimDirectory({ ...this.baseEnv, ...env });
2119
- env.PATH = [shimDirectory, env.PATH].filter(Boolean).join(path3.delimiter);
2241
+ const shimDirectory = input.config.runner === "isolated" ? path4.join(env.MISE_DATA_DIR, "shims") : localShimDirectory({ ...this.baseEnv, ...env });
2242
+ env.PATH = [shimDirectory, env.PATH].filter(Boolean).join(path4.delimiter);
2120
2243
  const repositories = [];
2121
2244
  const warnings = [];
2122
2245
  for (const repository of [...input.repositories].sort(
@@ -2188,20 +2311,20 @@ var MiseDevelopmentToolEnvironment = class {
2188
2311
  const commandEnvironment = {
2189
2312
  ...this.baseEnv,
2190
2313
  ...Object.fromEntries(Object.entries(env).filter(([key]) => key.startsWith("MISE_"))),
2191
- PATH: [shimDirectory, this.baseEnv.PATH].filter(Boolean).join(path3.delimiter)
2314
+ PATH: [shimDirectory, this.baseEnv.PATH].filter(Boolean).join(path4.delimiter)
2192
2315
  };
2193
- const evidenceDir = path3.join(input.config.processStorageRoot, "tooling", "mise-preparation");
2194
- await mkdir2(evidenceDir, { recursive: true });
2316
+ const evidenceDir = path4.join(input.config.processStorageRoot, "tooling", "mise-preparation");
2317
+ await mkdir3(evidenceDir, { recursive: true });
2195
2318
  const evidence = {
2196
2319
  schemaVersion: 1,
2197
2320
  preparedAt: (/* @__PURE__ */ new Date()).toISOString(),
2198
2321
  miseVersion,
2199
2322
  repositories
2200
2323
  };
2201
- const temporary = path3.join(evidenceDir, `.latest-${process.pid}.json`);
2202
- await writeFile2(temporary, `${JSON.stringify(evidence, null, 2)}
2324
+ const temporary = path4.join(evidenceDir, `.latest-${process.pid}.json`);
2325
+ await writeFile3(temporary, `${JSON.stringify(evidence, null, 2)}
2203
2326
  `, { mode: 384 });
2204
- await rename(temporary, path3.join(evidenceDir, "latest.json"));
2327
+ await rename2(temporary, path4.join(evidenceDir, "latest.json"));
2205
2328
  return { miseVersion, commandEnvironment, repositories, warnings };
2206
2329
  }
2207
2330
  };
@@ -2579,7 +2702,7 @@ async function restoreHandleAfterTurn(piHandle, plan) {
2579
2702
  }
2580
2703
 
2581
2704
  // src/worker-ipc-reporter.ts
2582
- import { randomUUID } from "crypto";
2705
+ import { randomUUID as randomUUID2 } from "crypto";
2583
2706
  import { createIpcMessage } from "@leitwerk-dev/worker-protocol";
2584
2707
 
2585
2708
  // src/diagnostics.ts
@@ -2651,7 +2774,7 @@ function createWorkerIpcReporter(options) {
2651
2774
  options.send(
2652
2775
  createIpcMessage({
2653
2776
  type: fact.type,
2654
- messageId: randomUUID(),
2777
+ messageId: randomUUID2(),
2655
2778
  instanceId: options.instanceId,
2656
2779
  workerId: options.workerId,
2657
2780
  sentAt: options.now().toISOString(),
@@ -2764,10 +2887,10 @@ import { repositoryHttpsUrl } from "@leitwerk-dev/process-sdk";
2764
2887
  import { createTemplateContext, resolveProcessPiConfig } from "@leitwerk-dev/process-sdk/pi-config";
2765
2888
 
2766
2889
  // src/managed-pi-agent-dir.ts
2767
- import { randomUUID as randomUUID2 } from "crypto";
2768
- import { chmod, lstat, mkdir as mkdir3, rename as rename2, writeFile as writeFile3 } from "fs/promises";
2890
+ import { randomUUID as randomUUID3 } from "crypto";
2891
+ import { chmod, lstat, mkdir as mkdir4, rename as rename3, writeFile as writeFile4 } from "fs/promises";
2769
2892
  import { homedir } from "os";
2770
- import path4 from "path";
2893
+ import path5 from "path";
2771
2894
  function safeSegment(value, name) {
2772
2895
  if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(value)) {
2773
2896
  throw new Error(`Invalid managed Pi ${name}`);
@@ -2775,21 +2898,21 @@ function safeSegment(value, name) {
2775
2898
  return value;
2776
2899
  }
2777
2900
  function resolveManagedPiAgentDir(input) {
2778
- const root = path4.resolve(input.agentDirRoot);
2779
- const ambient = path4.resolve(homedir(), ".pi", "agent");
2901
+ const root = path5.resolve(input.agentDirRoot);
2902
+ const ambient = path5.resolve(homedir(), ".pi", "agent");
2780
2903
  if (root === ambient)
2781
2904
  throw new Error("Managed Pi agent directory must not be ambient ~/.pi/agent");
2782
- return path4.join(
2905
+ return path5.join(
2783
2906
  root,
2784
2907
  safeSegment(input.instanceId, "instance id"),
2785
2908
  safeSegment(input.startOrLeaseId, "start id")
2786
2909
  );
2787
2910
  }
2788
2911
  function normalizeManagedPiCredentialPath(value) {
2789
- if (!value || path4.posix.isAbsolute(value) || value.includes("\\")) {
2912
+ if (!value || path5.posix.isAbsolute(value) || value.includes("\\")) {
2790
2913
  throw new Error(`Invalid credential file path '${value}'`);
2791
2914
  }
2792
- const normalized = path4.posix.normalize(value);
2915
+ const normalized = path5.posix.normalize(value);
2793
2916
  if (normalized === "." || normalized === ".." || normalized.startsWith("../")) {
2794
2917
  throw new Error(`Invalid credential file path '${value}'`);
2795
2918
  }
@@ -2797,19 +2920,19 @@ function normalizeManagedPiCredentialPath(value) {
2797
2920
  }
2798
2921
  async function assertNoSymlinkParents(root, target) {
2799
2922
  let current = root;
2800
- for (const part of path4.relative(root, path4.dirname(target)).split(path4.sep).filter(Boolean)) {
2801
- current = path4.join(current, part);
2923
+ for (const part of path5.relative(root, path5.dirname(target)).split(path5.sep).filter(Boolean)) {
2924
+ current = path5.join(current, part);
2802
2925
  try {
2803
2926
  if ((await lstat(current)).isSymbolicLink())
2804
2927
  throw new Error(`Credential parent is a symlink: ${current}`);
2805
2928
  } catch (error) {
2806
2929
  if (error.code !== "ENOENT") throw error;
2807
- await mkdir3(current, { recursive: false, mode: 448 });
2930
+ await mkdir4(current, { recursive: false, mode: 448 });
2808
2931
  }
2809
2932
  }
2810
2933
  }
2811
2934
  async function writeManagedPiCredentialFiles(agentDir, files) {
2812
- const root = path4.resolve(agentDir);
2935
+ const root = path5.resolve(agentDir);
2813
2936
  if ((await lstat(root)).isSymbolicLink()) {
2814
2937
  throw new Error(`Managed Pi directory is a symlink: ${root}`);
2815
2938
  }
@@ -2818,48 +2941,48 @@ async function writeManagedPiCredentialFiles(agentDir, files) {
2818
2941
  const relative = normalizeManagedPiCredentialPath(file.path);
2819
2942
  if (seen.has(relative)) throw new Error(`Duplicate credential file path '${relative}'`);
2820
2943
  seen.add(relative);
2821
- const target = path4.resolve(root, relative);
2822
- if (!target.startsWith(`${root}${path4.sep}`))
2944
+ const target = path5.resolve(root, relative);
2945
+ if (!target.startsWith(`${root}${path5.sep}`))
2823
2946
  throw new Error(`Credential path escapes managed directory: ${relative}`);
2824
2947
  await assertNoSymlinkParents(root, target);
2825
- const tmp = path4.join(
2826
- path4.dirname(target),
2827
- `.${path4.basename(target)}.tmp-${process.pid}-${randomUUID2()}`
2948
+ const tmp = path5.join(
2949
+ path5.dirname(target),
2950
+ `.${path5.basename(target)}.tmp-${process.pid}-${randomUUID3()}`
2828
2951
  );
2829
- await writeFile3(tmp, file.content, { mode: 384, flag: "wx" });
2952
+ await writeFile4(tmp, file.content, { mode: 384, flag: "wx" });
2830
2953
  await chmod(tmp, 384);
2831
- await rename2(tmp, target);
2954
+ await rename3(tmp, target);
2832
2955
  await chmod(target, 384);
2833
2956
  }
2834
2957
  }
2835
2958
 
2836
2959
  // src/managed-pi-bootstrap.ts
2837
- import { lstat as lstat2, readFile } from "fs/promises";
2838
- import path5 from "path";
2960
+ import { lstat as lstat2, readFile as readFile2 } from "fs/promises";
2961
+ import path6 from "path";
2839
2962
  import {
2840
2963
  canonicalJsonEqual,
2841
2964
  IPC_PROTOCOL_VERSION,
2842
2965
  parsePiResourceManifest,
2843
2966
  WORKER_API_VERSION
2844
2967
  } from "@leitwerk-dev/worker-protocol";
2845
- function fail(message) {
2968
+ function fail2(message) {
2846
2969
  throw new Error(`Invalid managed Pi resource snapshot: ${message}`);
2847
2970
  }
2848
2971
  function record(value, location) {
2849
2972
  if (typeof value !== "object" || value === null || Array.isArray(value)) {
2850
- fail(`${location} must be an object`);
2973
+ fail2(`${location} must be an object`);
2851
2974
  }
2852
2975
  return value;
2853
2976
  }
2854
2977
  function assertJsonEqual(actual, expected, location) {
2855
2978
  if (!canonicalJsonEqual(actual, expected)) {
2856
- fail(`${location} does not match the resolved LLM start`);
2979
+ fail2(`${location} does not match the resolved LLM start`);
2857
2980
  }
2858
2981
  }
2859
2982
  function assertModelMatchesStart(manifest, start) {
2860
2983
  for (const key of ["profileId", "providerId", "modelId", "thinkingLevel"]) {
2861
2984
  if (manifest.model[key] !== start.model[key]) {
2862
- fail(
2985
+ fail2(
2863
2986
  `generated.json model ${key} '${manifest.model[key]}' does not match start '${start.model[key]}'`
2864
2987
  );
2865
2988
  }
@@ -2868,30 +2991,30 @@ function assertModelMatchesStart(manifest, start) {
2868
2991
  async function assertCompatibility(manifest) {
2869
2992
  const { VERSION: PI_VERSION } = await import("@earendil-works/pi-coding-agent");
2870
2993
  if (manifest.compatibility.workerApiVersion !== WORKER_API_VERSION) {
2871
- fail(
2994
+ fail2(
2872
2995
  `server snapshot worker API version '${manifest.compatibility.workerApiVersion}' does not match local worker API version '${WORKER_API_VERSION}'`
2873
2996
  );
2874
2997
  }
2875
2998
  if (manifest.compatibility.piVersion !== PI_VERSION) {
2876
- fail(
2999
+ fail2(
2877
3000
  `server snapshot Pi version '${manifest.compatibility.piVersion}' does not match local worker Pi version '${PI_VERSION}'`
2878
3001
  );
2879
3002
  }
2880
3003
  if (manifest.compatibility.protocolVersion !== void 0 && manifest.compatibility.protocolVersion !== IPC_PROTOCOL_VERSION) {
2881
- fail(
3004
+ fail2(
2882
3005
  `server snapshot protocol version '${manifest.compatibility.protocolVersion}' does not match local worker protocol version '${IPC_PROTOCOL_VERSION}'`
2883
3006
  );
2884
3007
  }
2885
3008
  }
2886
3009
  async function readAndValidateManagedPiResourceManifest(input) {
2887
- const marker = await readFile(path5.join(input.agentDir, ".leitwerk-resource-digest"), "utf8");
3010
+ const marker = await readFile2(path6.join(input.agentDir, ".leitwerk-resource-digest"), "utf8");
2888
3011
  if (marker !== `${input.resourceDigest}
2889
3012
  `) {
2890
- fail("materialized resource digest marker does not match the delivered bundle");
3013
+ fail2("materialized resource digest marker does not match the delivered bundle");
2891
3014
  }
2892
3015
  let parsed;
2893
3016
  try {
2894
- parsed = JSON.parse(await readFile(path5.join(input.agentDir, "generated.json"), "utf8"));
3017
+ parsed = JSON.parse(await readFile2(path6.join(input.agentDir, "generated.json"), "utf8"));
2895
3018
  } catch (error) {
2896
3019
  throw new Error("Invalid managed Pi resource snapshot: generated.json is unreadable", {
2897
3020
  cause: error
@@ -2908,7 +3031,7 @@ async function readAndValidateManagedPiResourceManifest(input) {
2908
3031
  );
2909
3032
  let settings;
2910
3033
  try {
2911
- settings = JSON.parse(await readFile(path5.join(input.agentDir, "settings.json"), "utf8"));
3034
+ settings = JSON.parse(await readFile2(path6.join(input.agentDir, "settings.json"), "utf8"));
2912
3035
  } catch (error) {
2913
3036
  throw new Error("Invalid managed Pi resource snapshot: settings.json is unreadable", {
2914
3037
  cause: error
@@ -2959,7 +3082,7 @@ function buildManagedPiCredentialFiles(input) {
2959
3082
  }
2960
3083
  async function assertManagedPiCredentialFiles(input) {
2961
3084
  for (const credentialPath of input.manifest.declaredCredentialPaths) {
2962
- const target = path5.join(input.agentDir, credentialPath);
3085
+ const target = path6.join(input.agentDir, credentialPath);
2963
3086
  const stat2 = await lstat2(target).catch(() => null);
2964
3087
  if (!stat2?.isFile() || stat2.isSymbolicLink()) {
2965
3088
  throw new Error(`Declared credential file '${credentialPath}' is missing or unsafe`);
@@ -2970,7 +3093,7 @@ async function assertManagedPiCredentialFiles(input) {
2970
3093
  }
2971
3094
  if (input.credential && input.manifest.declaredCredentialPaths.includes("auth.json")) {
2972
3095
  const auth = record(
2973
- JSON.parse(await readFile(path5.join(input.agentDir, "auth.json"), "utf8")),
3096
+ JSON.parse(await readFile2(path6.join(input.agentDir, "auth.json"), "utf8")),
2974
3097
  "auth.json"
2975
3098
  );
2976
3099
  if (input.credential.values.apiKey) {
@@ -2997,129 +3120,6 @@ async function assertManagedPiCredentialFiles(input) {
2997
3120
  }
2998
3121
  }
2999
3122
 
3000
- // src/pi-resource-bundle.ts
3001
- import { randomUUID as randomUUID3 } from "crypto";
3002
- import { mkdir as mkdir4, open, readFile as readFile2, rename as rename3, rm, writeFile as writeFile4 } from "fs/promises";
3003
- import path6 from "path";
3004
- import {
3005
- createCanonicalPiResourceBundle,
3006
- sha256Digest,
3007
- validateResourceRelativePath,
3008
- verifyCanonicalPiResourceBundle
3009
- } from "@leitwerk-dev/worker-protocol";
3010
- function fail2(message) {
3011
- throw new Error(`Invalid Pi resource bundle: ${message}`);
3012
- }
3013
- function requireStorageName(value, label) {
3014
- if (!/^[a-zA-Z0-9_-]+$/u.test(value)) fail2(`unsafe ${label}: ${value}`);
3015
- return value;
3016
- }
3017
- async function atomicWrite(pathname, content, mode) {
3018
- const staging = `${pathname}.staging-${process.pid}-${randomUUID3()}`;
3019
- const handle = await open(staging, "wx", mode);
3020
- try {
3021
- await handle.writeFile(content);
3022
- await handle.sync();
3023
- } finally {
3024
- await handle.close();
3025
- }
3026
- try {
3027
- await rename3(staging, pathname);
3028
- } catch (error) {
3029
- await rm(staging, { force: true });
3030
- throw error;
3031
- }
3032
- }
3033
- async function persistPiResourceBundleForStart(input) {
3034
- const digest = requireStorageName(input.digest, "resource digest");
3035
- const startRecordId = requireStorageName(input.startRecordId, "turn-start id");
3036
- const bundlesDir = path6.resolve(input.bundlesDir);
3037
- const startsDir = path6.join(bundlesDir, "starts");
3038
- const bundlePath = path6.join(bundlesDir, `${digest}.tar`);
3039
- await mkdir4(startsDir, { recursive: true, mode: 448 });
3040
- let bundle = null;
3041
- let reused = false;
3042
- try {
3043
- const existing = await readFile2(bundlePath);
3044
- verifyCanonicalPiResourceBundle(existing, digest);
3045
- bundle = existing;
3046
- reused = true;
3047
- } catch (error) {
3048
- if (error.code !== "ENOENT" && input.archiveBase64 === void 0) {
3049
- throw error;
3050
- }
3051
- }
3052
- if (!bundle) {
3053
- if (!input.deliveredBundle && input.archiveBase64 === void 0) {
3054
- throw new Error(`Pi resource bundle '${digest}' is unavailable on the process volume`);
3055
- }
3056
- bundle = input.deliveredBundle ?? Buffer.from(input.archiveBase64, "base64");
3057
- verifyCanonicalPiResourceBundle(bundle, digest);
3058
- await atomicWrite(bundlePath, bundle, 384);
3059
- }
3060
- const manifest = Buffer.from(
3061
- `${JSON.stringify({ startRecordId, digest, persistedAt: (/* @__PURE__ */ new Date()).toISOString() })}
3062
- `,
3063
- "utf8"
3064
- );
3065
- await atomicWrite(path6.join(startsDir, `${startRecordId}.json`), manifest, 384);
3066
- return { bundle, reused };
3067
- }
3068
- async function writeExtractedFiles(root, files) {
3069
- for (const file of files) {
3070
- const output = path6.resolve(root, file.path);
3071
- if (path6.relative(root, output).startsWith("..") || path6.isAbsolute(path6.relative(root, output))) {
3072
- fail2(`path escapes materialization root: ${file.path}`);
3073
- }
3074
- await mkdir4(path6.dirname(output), { recursive: true, mode: 448 });
3075
- await writeFile4(output, file.content, { mode: 420, flag: "wx" });
3076
- }
3077
- }
3078
- async function materializeCanonicalPiResourceBundle(input) {
3079
- const files = verifyCanonicalPiResourceBundle(input.bundle, input.digest);
3080
- const targetDir = path6.resolve(input.targetDir);
3081
- const parent = path6.dirname(targetDir);
3082
- await mkdir4(parent, { recursive: true, mode: 448 });
3083
- const marker = path6.join(targetDir, ".leitwerk-resource-digest");
3084
- try {
3085
- const current = await import("fs/promises").then(
3086
- ({ readFile: readFile5 }) => readFile5(marker, "utf8")
3087
- );
3088
- if (current === `${input.digest}
3089
- `) return { targetDir, reused: true };
3090
- throw new Error(
3091
- `Managed Pi directory already exists with a different resource digest: ${targetDir}`
3092
- );
3093
- } catch (error) {
3094
- if (error.code !== "ENOENT") throw error;
3095
- }
3096
- const staging = path6.join(
3097
- parent,
3098
- `.${path6.basename(targetDir)}.staging-${process.pid}-${randomUUID3()}`
3099
- );
3100
- try {
3101
- await mkdir4(staging, { mode: 448 });
3102
- await writeExtractedFiles(staging, files);
3103
- await writeFile4(path6.join(staging, ".leitwerk-resource-digest"), `${input.digest}
3104
- `, {
3105
- mode: 384,
3106
- flag: "wx"
3107
- });
3108
- await rename3(staging, targetDir);
3109
- return { targetDir, reused: false };
3110
- } catch (error) {
3111
- await rm(staging, { recursive: true, force: true });
3112
- if (error.code === "EEXIST") {
3113
- const current = await import("fs/promises").then(
3114
- ({ readFile: readFile5 }) => readFile5(marker, "utf8")
3115
- );
3116
- if (current === `${input.digest}
3117
- `) return { targetDir, reused: true };
3118
- }
3119
- throw error;
3120
- }
3121
- }
3122
-
3123
3123
  // src/pre-turn-targeted-inputs.ts
3124
3124
  import {
3125
3125
  resolveProcessProductRefEntryId,
@@ -3876,7 +3876,8 @@ async function activatePreparedStart(input) {
3876
3876
  agentDir: prepared.managedAgentDir,
3877
3877
  configSnapshot: prepared.startPayload.configSnapshot,
3878
3878
  modelProfileId: prepared.managedModelProfileId,
3879
- piConfig: prepared.resolvedPiConfig
3879
+ piConfig: prepared.resolvedPiConfig,
3880
+ ...prepared.startPayload.iteration ? { iteration: prepared.startPayload.iteration } : {}
3880
3881
  });
3881
3882
  const diagnostics = await restorePrimaryPathLeaf(
3882
3883
  piHandle,
@@ -4164,7 +4165,8 @@ function validatePreparedSession(input) {
4164
4165
  turnResultMarkdownBySemanticRef: payload.turnResultMarkdownBySemanticRef,
4165
4166
  turnResultMarkdownByProduct: payload.turnResultMarkdownByProduct,
4166
4167
  settings,
4167
- integrationTools: payload.integrationTools ?? []
4168
+ integrationTools: payload.integrationTools ?? [],
4169
+ ...payload.iteration ? { iteration: payload.iteration } : {}
4168
4170
  };
4169
4171
  if (binding.definition.kind === "automatic") {
4170
4172
  return { ...base, kind: "automatic", piAvailable: false, activeModelProfileId: null };
@@ -7382,6 +7384,7 @@ async function executeSelectedTurn(input) {
7382
7384
  turnResultMarkdownBySemanticRef: input.session.turnResultMarkdownBySemanticRef,
7383
7385
  turnResultMarkdownByProduct: input.session.turnResultMarkdownByProduct,
7384
7386
  workspaceRoot: input.session.workspaceRoot,
7387
+ ...input.session.iteration ? { iteration: input.session.iteration } : {},
7385
7388
  ...selectedTurnType === "automatic" ? {
7386
7389
  reportProgress,
7387
7390
  callIntegrationTool
@@ -7646,7 +7649,12 @@ function createWorkerRuntime(options) {
7646
7649
  adapters.exit(command.code);
7647
7650
  return;
7648
7651
  case "bootstrap":
7649
- void resources.bootstrap(command.payload, resolveWorkerRuntimeSettings(config, command.payload)).then(
7652
+ void Promise.resolve().then(() => adapters.beforeTurnBootstrap?.(command.payload.turnStart.turnId)).then(
7653
+ () => resources.bootstrap(
7654
+ command.payload,
7655
+ resolveWorkerRuntimeSettings(config, command.payload)
7656
+ )
7657
+ ).then(
7650
7658
  (completion) => complete({
7651
7659
  kind: "bootstrap_succeeded",
7652
7660
  startRecordId: command.startRecordId,
@@ -8627,6 +8635,8 @@ for (const line of input.split('\\n')) {
8627
8635
  const i = line.indexOf('=');
8628
8636
  if (i < 0) continue;
8629
8637
  const key = line.slice(0, i);
8638
+ // Git >= 2.46 advertises repeatable capability[] lines; only single-valued keys are matched.
8639
+ if (key.endsWith('[]')) continue;
8630
8640
  if (Object.hasOwn(fields, key)) process.exit(0);
8631
8641
  fields[key] = line.slice(i + 1);
8632
8642
  }
@@ -8774,6 +8784,7 @@ function createWorkerEntryRuntime(overrides = {}) {
8774
8784
  extensionEvents: workerExtensionApi.events,
8775
8785
  stderr: overrides.stderr,
8776
8786
  scheduler,
8787
+ beforeTurnBootstrap: overrides.beforeTurnBootstrap,
8777
8788
  exit: overrides.exit ?? ((code) => process.exit(code))
8778
8789
  }
8779
8790
  });
@@ -8781,7 +8792,8 @@ function createWorkerEntryRuntime(overrides = {}) {
8781
8792
 
8782
8793
  export {
8783
8794
  SdkPiTreeHandleFactory,
8795
+ persistPiResourceBundleForStart,
8784
8796
  createWorkerRuntime,
8785
8797
  createWorkerEntryRuntime
8786
8798
  };
8787
- //# sourceMappingURL=chunk-2LLFMCR6.js.map
8799
+ //# sourceMappingURL=chunk-4WPLQCF6.js.map