@leitwerk-dev/server 0.2.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -562,11 +562,11 @@ function formatValibotPath(issue2) {
562
562
  return formatted;
563
563
  }
564
564
  function formatConfigSchemaIssue(issue2) {
565
- const path5 = formatValibotPath(issue2);
565
+ const path6 = formatValibotPath(issue2);
566
566
  if (issue2.type === "non_empty") {
567
- return { path: path5, message: `${path5} must not be empty when specified` };
567
+ return { path: path6, message: `${path6} must not be empty when specified` };
568
568
  }
569
- return { path: path5, message: `${path5}: ${issue2.message}` };
569
+ return { path: path6, message: `${path6}: ${issue2.message}` };
570
570
  }
571
571
  function collectConfigSchemaErrors(config) {
572
572
  const parsed = v.safeParse(configSchema, config, { abortEarly: false });
@@ -617,12 +617,12 @@ function collectServerBaseUrlErrors(config) {
617
617
  function collectWorkerRuntimeProfileErrors(config) {
618
618
  const errors = [];
619
619
  const profileIds = new Set(Object.keys(config.worker_runtime_profiles ?? {}));
620
- const checkReference = (value, path5) => {
620
+ const checkReference = (value, path6) => {
621
621
  if (typeof value !== "string" || value.trim() === "") {
622
622
  return;
623
623
  }
624
624
  if (!profileIds.has(value)) {
625
- errors.push(`Unknown worker runtime profile '${value}' at ${path5}`);
625
+ errors.push(`Unknown worker runtime profile '${value}' at ${path6}`);
626
626
  }
627
627
  };
628
628
  for (const [id, profile] of Object.entries(config.worker_runtime_profiles ?? {})) {
@@ -970,12 +970,12 @@ function validateConfig(raw) {
970
970
  const config = applyConfigDefaults(raw);
971
971
  return validateResolvedConfig(config);
972
972
  }
973
- function shouldRedactForLogging(path5, key) {
974
- return SENSITIVE_CONFIG_KEY_PATTERN.test(key) || key === "url" && (path5[0] === "notifications" || path5.some((segment) => /webhook/i.test(segment)));
973
+ function shouldRedactForLogging(path6, key) {
974
+ return SENSITIVE_CONFIG_KEY_PATTERN.test(key) || key === "url" && (path6[0] === "notifications" || path6.some((segment) => /webhook/i.test(segment)));
975
975
  }
976
- function sanitizeConfigForLogging(value, path5 = []) {
976
+ function sanitizeConfigForLogging(value, path6 = []) {
977
977
  if (Array.isArray(value)) {
978
- return value.map((entry, index2) => sanitizeConfigForLogging(entry, [...path5, String(index2)]));
978
+ return value.map((entry, index2) => sanitizeConfigForLogging(entry, [...path6, String(index2)]));
979
979
  }
980
980
  const parsedRecord = v.safeParse(unknownRecordSchema, value);
981
981
  if (!parsedRecord.success) {
@@ -983,11 +983,11 @@ function sanitizeConfigForLogging(value, path5 = []) {
983
983
  }
984
984
  const sanitized = {};
985
985
  for (const [key, entry] of Object.entries(parsedRecord.output)) {
986
- if (shouldRedactForLogging(path5, key)) {
986
+ if (shouldRedactForLogging(path6, key)) {
987
987
  sanitized[key] = entry === "" ? "" : REDACTED_LOG_VALUE;
988
988
  continue;
989
989
  }
990
- sanitized[key] = sanitizeConfigForLogging(entry, [...path5, key]);
990
+ sanitized[key] = sanitizeConfigForLogging(entry, [...path6, key]);
991
991
  }
992
992
  return sanitized;
993
993
  }
@@ -6872,9 +6872,9 @@ function createLaunchPipeline(deps) {
6872
6872
  broadcast(run);
6873
6873
  return run;
6874
6874
  }
6875
- function fail(id, stepId, failure) {
6876
- mutate(id, (run) => failLaunchRun(run, stepId, failure.safeSummary));
6877
- return { kind: "failed", failure };
6875
+ function fail(id, stepId, failure2) {
6876
+ mutate(id, (run) => failLaunchRun(run, stepId, failure2.safeSummary));
6877
+ return { kind: "failed", failure: failure2 };
6878
6878
  }
6879
6879
  return {
6880
6880
  open(input) {
@@ -6950,11 +6950,11 @@ function createLaunchPipeline(deps) {
6950
6950
  };
6951
6951
  } catch (error) {
6952
6952
  const run = deps.launchRuns.getById(launchRunId);
6953
- const failure = adapter.unexpectedFailure?.(error) ?? {
6953
+ const failure2 = adapter.unexpectedFailure?.(error) ?? {
6954
6954
  safeSummary: "The launch could not be completed. Try again.",
6955
6955
  value: error
6956
6956
  };
6957
- return fail(launchRunId, run ? activeStepId(run) : "validate_request", failure);
6957
+ return fail(launchRunId, run ? activeStepId(run) : "validate_request", failure2);
6958
6958
  } finally {
6959
6959
  deps.launchRuns.deleteReplay(launchRunId);
6960
6960
  }
@@ -6962,6 +6962,444 @@ function createLaunchPipeline(deps) {
6962
6962
  };
6963
6963
  }
6964
6964
 
6965
+ // src/pi-resources/bundle-cache.ts
6966
+ import { sha256Digest as sha256Digest2 } from "@leitwerk-dev/worker-protocol";
6967
+
6968
+ // src/model-providers/provider-boundary-utils.ts
6969
+ function positiveBound(value, fallback, name) {
6970
+ const resolved2 = value ?? fallback;
6971
+ if (!Number.isSafeInteger(resolved2) || resolved2 < 1) {
6972
+ throw new Error(`${name} must be a positive safe integer`);
6973
+ }
6974
+ return resolved2;
6975
+ }
6976
+ async function withTimeout(work, timeoutMs, sentinelMessage = "timeout") {
6977
+ let timer;
6978
+ try {
6979
+ return await Promise.race([
6980
+ work,
6981
+ new Promise((_resolve, reject) => {
6982
+ timer = setTimeout(() => reject(new Error(sentinelMessage)), timeoutMs);
6983
+ })
6984
+ ]);
6985
+ } finally {
6986
+ if (timer) clearTimeout(timer);
6987
+ }
6988
+ }
6989
+ function validateCredentialStatus(value, message = "invalid credential status") {
6990
+ if (typeof value !== "object" || value === null || typeof value.available !== "boolean" || !(value.revision === null || Number.isSafeInteger(value.revision) && value.revision >= 0)) {
6991
+ throw new Error(message);
6992
+ }
6993
+ return value;
6994
+ }
6995
+
6996
+ // src/pi-resources/bundle-cache.ts
6997
+ var DEFAULT_MAX_ENTRIES = 64;
6998
+ var DEFAULT_MAX_BYTES = 256 * 1024 * 1024;
6999
+ function createPiResourceBundleCache(options = {}) {
7000
+ const maxEntries = positiveBound(options.maxEntries, DEFAULT_MAX_ENTRIES, "maxEntries");
7001
+ const maxBytes = positiveBound(options.maxBytes, DEFAULT_MAX_BYTES, "maxBytes");
7002
+ const entries = /* @__PURE__ */ new Map();
7003
+ let totalBytes = 0;
7004
+ function touch(entry) {
7005
+ entries.delete(entry.digest);
7006
+ entries.set(entry.digest, entry);
7007
+ }
7008
+ function oldestUnpinned(excluding) {
7009
+ for (const entry of entries.values()) {
7010
+ if (entry.digest !== excluding && entry.pins === 0) return entry;
7011
+ }
7012
+ return null;
7013
+ }
7014
+ function remove(entry) {
7015
+ if (!entries.delete(entry.digest)) return;
7016
+ totalBytes -= entry.bytes.byteLength;
7017
+ }
7018
+ function enforceBounds(newDigest) {
7019
+ while (entries.size > maxEntries || totalBytes > maxBytes) {
7020
+ const candidate2 = oldestUnpinned(newDigest);
7021
+ if (!candidate2) {
7022
+ const inserted = entries.get(newDigest);
7023
+ if (inserted?.pins === 0) remove(inserted);
7024
+ throw new Error("Pi resource bundle cache capacity is exhausted by pinned bundles");
7025
+ }
7026
+ remove(candidate2);
7027
+ }
7028
+ }
7029
+ return {
7030
+ put(bundle) {
7031
+ if (typeof bundle.digest !== "string" || sha256Digest2(bundle.bytes) !== bundle.digest) {
7032
+ throw new Error("Pi resource bundle digest does not match its bytes");
7033
+ }
7034
+ if (bundle.bytes.byteLength > maxBytes) {
7035
+ throw new Error(
7036
+ `Pi resource bundle size ${bundle.bytes.byteLength} exceeds cache byte limit ${maxBytes}`
7037
+ );
7038
+ }
7039
+ const existing = entries.get(bundle.digest);
7040
+ if (existing) {
7041
+ touch(existing);
7042
+ return;
7043
+ }
7044
+ const bytes = Uint8Array.from(bundle.bytes);
7045
+ const entry = {
7046
+ digest: bundle.digest,
7047
+ bytes,
7048
+ pins: 0
7049
+ };
7050
+ entries.set(entry.digest, entry);
7051
+ totalBytes += entry.bytes.byteLength;
7052
+ enforceBounds(entry.digest);
7053
+ },
7054
+ get(digest) {
7055
+ const entry = entries.get(digest);
7056
+ if (!entry) return null;
7057
+ touch(entry);
7058
+ return { digest: entry.digest, bytes: Uint8Array.from(entry.bytes) };
7059
+ },
7060
+ has: (digest) => entries.has(digest),
7061
+ pin(digest) {
7062
+ const entry = entries.get(digest);
7063
+ if (!entry) return false;
7064
+ entry.pins += 1;
7065
+ touch(entry);
7066
+ return true;
7067
+ },
7068
+ unpin(digest) {
7069
+ const entry = entries.get(digest);
7070
+ if (!entry || entry.pins === 0) return false;
7071
+ entry.pins -= 1;
7072
+ touch(entry);
7073
+ return true;
7074
+ },
7075
+ gc() {
7076
+ const removed = [...entries.values()].filter((entry) => entry.pins === 0);
7077
+ let removedBytes = 0;
7078
+ for (const entry of removed) {
7079
+ removedBytes += entry.bytes.byteLength;
7080
+ remove(entry);
7081
+ }
7082
+ return {
7083
+ removedDigests: removed.map((entry) => entry.digest),
7084
+ removedBytes
7085
+ };
7086
+ },
7087
+ stats() {
7088
+ const values = [...entries.values()];
7089
+ return {
7090
+ entries: entries.size,
7091
+ bytes: totalBytes,
7092
+ pinnedEntries: values.filter((entry) => entry.pins > 0).length,
7093
+ pins: values.reduce((total, entry) => total + entry.pins, 0)
7094
+ };
7095
+ }
7096
+ };
7097
+ }
7098
+
7099
+ // src/pi-resources/bundle-pin-lifecycle.ts
7100
+ function pinnedDigest(process2, turnStarts, turnRecords2) {
7101
+ if (process2.currentExecution?.kind !== "worker_start") return null;
7102
+ const start = turnStarts.getById(process2.currentExecution.id);
7103
+ if (!start || start.instanceId !== process2.id || start.turnType !== "llm") return null;
7104
+ if (start.state.kind !== "starting" && start.state.kind !== "accepted") return null;
7105
+ if (start.state.start.kind !== "llm") return null;
7106
+ return start.state.kind === "starting" || turnRecords2.getById(start.state.turnRecordId)?.status === "running" ? start.state.start.piResourceSnapshotDigest : null;
7107
+ }
7108
+ function createPiResourceBundlePinReconciler(deps) {
7109
+ const pinnedByInstance = /* @__PURE__ */ new Map();
7110
+ return {
7111
+ reconcile(process2) {
7112
+ const next = pinnedDigest(process2, deps.turnStarts, deps.turnRecords);
7113
+ const previous = pinnedByInstance.get(process2.id) ?? null;
7114
+ if (previous === next) {
7115
+ return { missingDigest: next && !deps.bundleCache.has(next) ? next : null };
7116
+ }
7117
+ if (previous) deps.bundleCache.unpin(previous);
7118
+ pinnedByInstance.delete(process2.id);
7119
+ if (!next) {
7120
+ return { missingDigest: null };
7121
+ }
7122
+ if (!deps.bundleCache.pin(next)) {
7123
+ return { missingDigest: next };
7124
+ }
7125
+ pinnedByInstance.set(process2.id, next);
7126
+ return { missingDigest: null };
7127
+ }
7128
+ };
7129
+ }
7130
+
7131
+ // src/pi-resources/assemble.ts
7132
+ import { lstat as lstat2, realpath as realpath2 } from "node:fs/promises";
7133
+ import path2 from "node:path";
7134
+ import {
7135
+ canonicalizeJson,
7136
+ canonicalJsonStringify,
7137
+ createCanonicalPiResourceBundle,
7138
+ PI_RESOURCE_SNAPSHOT_SCHEMA_VERSION,
7139
+ sha256Digest as sha256Digest3,
7140
+ validateResourceRelativePath as validateResourceRelativePath2
7141
+ } from "@leitwerk-dev/worker-protocol";
7142
+ import { build } from "esbuild";
7143
+ import {
7144
+ PI_RESOURCE_SNAPSHOT_SCHEMA_VERSION as PI_RESOURCE_SNAPSHOT_SCHEMA_VERSION2
7145
+ } from "@leitwerk-dev/worker-protocol";
7146
+ function jsonBytes(value, location) {
7147
+ return Buffer.from(`${canonicalJsonStringify(value, location)}
7148
+ `, "utf8");
7149
+ }
7150
+ var FORBIDDEN_SECRET_KEYS = /* @__PURE__ */ new Set([
7151
+ "apikey",
7152
+ "accesstoken",
7153
+ "refreshtoken",
7154
+ "brokertoken",
7155
+ "clientsecret",
7156
+ "privatekey",
7157
+ "password",
7158
+ "secret",
7159
+ "authorization"
7160
+ ]);
7161
+ function assertNoCredentialFields(value, location) {
7162
+ if (Array.isArray(value)) {
7163
+ value.forEach((item, index2) => {
7164
+ assertNoCredentialFields(item, `${location}[${index2}]`);
7165
+ });
7166
+ return;
7167
+ }
7168
+ if (typeof value !== "object" || value === null) return;
7169
+ for (const [key, nested] of Object.entries(value)) {
7170
+ const normalizedKey = key.toLowerCase().replaceAll(/[^a-z0-9]/g, "");
7171
+ if (FORBIDDEN_SECRET_KEYS.has(normalizedKey)) {
7172
+ throw new Error(
7173
+ `${location}.${key} is credential-bearing and cannot enter a Pi resource snapshot`
7174
+ );
7175
+ }
7176
+ assertNoCredentialFields(nested, `${location}.${key}`);
7177
+ }
7178
+ }
7179
+ function safeExtensionSegment(ownerExtensionId) {
7180
+ const normalized = ownerExtensionId.normalize("NFKD").replaceAll(/[^A-Za-z0-9._-]+/g, "-").replaceAll(/^-+|-+$/g, "") || "extension";
7181
+ if (Buffer.byteLength(normalized, "utf8") <= 56) return normalized;
7182
+ return `${normalized.slice(0, 43)}-${sha256Digest3(Buffer.from(ownerExtensionId)).slice(0, 12)}`;
7183
+ }
7184
+ function extensionSnapshotPath(contribution, index2) {
7185
+ const prefix = String(index2 * 10).padStart(3, "0");
7186
+ return validateResourceRelativePath2(
7187
+ `extensions/${prefix}-${safeExtensionSegment(contribution.ownerExtensionId)}.js`
7188
+ );
7189
+ }
7190
+ var PI_CORE_EXTERNALS = ["@earendil-works/pi-ai", "@earendil-works/pi-coding-agent"];
7191
+ async function buildPiExtensionWrapper(entryPath) {
7192
+ const result = await build({
7193
+ absWorkingDir: path2.dirname(entryPath),
7194
+ bundle: true,
7195
+ stdin: {
7196
+ contents: `
7197
+ import contribution from ${JSON.stringify(entryPath)};
7198
+ import { readFileSync } from "node:fs";
7199
+
7200
+ function readGenerated() {
7201
+ return JSON.parse(readFileSync(new URL("../generated.json", import.meta.url), "utf8"));
7202
+ }
7203
+
7204
+ function credentialBag(generated) {
7205
+ let values;
7206
+ const load = () => {
7207
+ if (values) return values;
7208
+ values = {};
7209
+ for (const credentialPath of generated.declaredCredentialPaths) {
7210
+ if (typeof credentialPath !== "string" || credentialPath.startsWith("/") || credentialPath.includes("..") || credentialPath.includes("\\\\")) {
7211
+ throw new Error("Invalid declared Pi credential path");
7212
+ }
7213
+ const credential = JSON.parse(readFileSync(new URL("../" + credentialPath, import.meta.url), "utf8"));
7214
+ if (credential && typeof credential === "object" && !Array.isArray(credential)) Object.assign(values, credential);
7215
+ }
7216
+ return values;
7217
+ };
7218
+ return {
7219
+ get(key) { const value = load()[key]; return typeof value === "string" ? value : undefined; },
7220
+ require(key) { const value = this.get(key); if (value === undefined) throw new Error("Required Pi worker secret '" + key + "' is unavailable"); return value; },
7221
+ keys() { return Object.keys(load()).filter((key) => typeof load()[key] === "string").sort(); },
7222
+ };
7223
+ }
7224
+
7225
+ export default async function leitwerkPiExtension(pi) {
7226
+ if (typeof contribution !== "function") throw new Error("Leitwerk Pi worker entry must default-export a function");
7227
+ const generated = readGenerated();
7228
+ const workerConfig = generated.providerWorkerConfig === null ? null : generated.providerWorkerConfig?.value;
7229
+ const report = (event) => {
7230
+ if (!event || typeof event !== "object" || Array.isArray(event)) throw new Error("Pi worker report must be an object");
7231
+ pi.events?.emit?.("leitwerk:provider-report", event);
7232
+ };
7233
+ await contribution(pi, {
7234
+ model: { providerId: generated.model.providerId, modelId: generated.model.modelId },
7235
+ options: { ...generated.providerOptions },
7236
+ workerConfig,
7237
+ secrets: credentialBag(generated),
7238
+ report,
7239
+ });
7240
+ }
7241
+ `,
7242
+ resolveDir: path2.dirname(entryPath),
7243
+ sourcefile: "leitwerk-pi-wrapper.js"
7244
+ },
7245
+ format: "esm",
7246
+ platform: "node",
7247
+ target: "node22",
7248
+ write: false,
7249
+ minify: true,
7250
+ sourcemap: false,
7251
+ legalComments: "none",
7252
+ external: PI_CORE_EXTERNALS
7253
+ });
7254
+ const output = result.outputFiles[0];
7255
+ if (!output) throw new Error(`Pi extension wrapper did not produce output for '${entryPath}'`);
7256
+ return output.contents;
7257
+ }
7258
+ function normalizeCredentialPaths(paths) {
7259
+ const seen = /* @__PURE__ */ new Set();
7260
+ const normalized = paths.map((credentialPath) => {
7261
+ const result = validateResourceRelativePath2(credentialPath);
7262
+ if (seen.has(result)) throw new Error(`Duplicate declared credential path '${result}'`);
7263
+ seen.add(result);
7264
+ return result;
7265
+ });
7266
+ return normalized.sort(compareResourcePaths);
7267
+ }
7268
+ function assertCredentialPathsDoNotOverlap(credentialPaths, immutablePaths) {
7269
+ const files = [...immutablePaths];
7270
+ for (const credentialPath of credentialPaths) {
7271
+ for (const immutablePath of files) {
7272
+ if (credentialPath === immutablePath || credentialPath.startsWith(`${immutablePath}/`) || immutablePath.startsWith(`${credentialPath}/`)) {
7273
+ throw new Error(
7274
+ `Declared credential path '${credentialPath}' overlaps immutable resource '${immutablePath}'`
7275
+ );
7276
+ }
7277
+ }
7278
+ }
7279
+ }
7280
+ function requireNonEmptyString(value, location) {
7281
+ if (typeof value !== "string" || value.trim() === "") {
7282
+ throw new Error(`${location} must be a non-empty string`);
7283
+ }
7284
+ }
7285
+ function validateAssemblyInput(input) {
7286
+ requireNonEmptyString(input.model.profileId, "model.profileId");
7287
+ requireNonEmptyString(input.model.providerId, "model.providerId");
7288
+ requireNonEmptyString(input.model.modelId, "model.modelId");
7289
+ requireNonEmptyString(input.model.thinkingLevel, "model.thinkingLevel");
7290
+ requireNonEmptyString(input.compatibility.workerApiVersion, "compatibility.workerApiVersion");
7291
+ requireNonEmptyString(input.compatibility.piVersion, "compatibility.piVersion");
7292
+ if (input.compatibility.protocolVersion !== void 0) {
7293
+ requireNonEmptyString(input.compatibility.protocolVersion, "compatibility.protocolVersion");
7294
+ }
7295
+ for (const [fieldId, value] of Object.entries(input.providerOptions)) {
7296
+ if (fieldId.trim() === "" || typeof value !== "string") {
7297
+ throw new Error("providerOptions must contain non-empty field ids and string values");
7298
+ }
7299
+ }
7300
+ if (input.providerWorkerConfig && (!Number.isSafeInteger(input.providerWorkerConfig.version) || input.providerWorkerConfig.version < 1)) {
7301
+ throw new Error("providerWorkerConfig.version must be a positive safe integer");
7302
+ }
7303
+ if (input.systemPrompt !== void 0 && input.systemPrompt !== null) {
7304
+ if (typeof input.systemPrompt !== "string") throw new Error("systemPrompt must be a string");
7305
+ }
7306
+ if (input.appendSystemPrompt !== void 0 && input.appendSystemPrompt !== null) {
7307
+ if (typeof input.appendSystemPrompt !== "string") {
7308
+ throw new Error("appendSystemPrompt must be a string");
7309
+ }
7310
+ }
7311
+ }
7312
+ async function assemblePiResourceSnapshot(input) {
7313
+ validateAssemblyInput(input);
7314
+ assertNoCredentialFields(input.piSettings, "piSettings");
7315
+ assertNoCredentialFields(input.piModels ?? {}, "piModels");
7316
+ assertNoCredentialFields(input.providerOptions, "providerOptions");
7317
+ assertNoCredentialFields(input.providerWorkerConfig?.value ?? {}, "providerWorkerConfig.value");
7318
+ const collector = new ResourceCollector(input.limits);
7319
+ const seenOwners = /* @__PURE__ */ new Set();
7320
+ const workerSourceIdentities = /* @__PURE__ */ new Map();
7321
+ const workerSourceRealPaths = /* @__PURE__ */ new Map();
7322
+ const settings = { ...input.piSettings, packages: [], defaultProjectTrust: "never" };
7323
+ collector.addBytes("settings.json", jsonBytes(settings, "settings.json"));
7324
+ collector.addBytes("models.json", jsonBytes(input.piModels ?? { providers: {} }, "models.json"));
7325
+ if (input.systemPrompt !== void 0 && input.systemPrompt !== null) {
7326
+ collector.addBytes("SYSTEM.md", Buffer.from(input.systemPrompt, "utf8"));
7327
+ }
7328
+ if (input.appendSystemPrompt !== void 0 && input.appendSystemPrompt !== null) {
7329
+ collector.addBytes("APPEND_SYSTEM.md", Buffer.from(input.appendSystemPrompt, "utf8"));
7330
+ }
7331
+ for (const layer of input.resourceLayers ?? []) collector.addBundle(layer.bundle, layer.owner);
7332
+ for (const [index2, contribution] of input.piContributions.entries()) {
7333
+ if (seenOwners.has(contribution.ownerExtensionId)) {
7334
+ throw new Error(
7335
+ `Extension '${contribution.ownerExtensionId}' appears more than once in Pi contributions`
7336
+ );
7337
+ }
7338
+ seenOwners.add(contribution.ownerExtensionId);
7339
+ const baseOwner = {
7340
+ ownerExtensionId: contribution.ownerExtensionId,
7341
+ packageName: contribution.packageName
7342
+ };
7343
+ if (contribution.workerEntryPath) {
7344
+ validatePhysicalSourcePath(contribution.workerEntryPath);
7345
+ const source = await lstat2(contribution.workerEntryPath);
7346
+ if (source.isSymbolicLink() || !source.isFile()) {
7347
+ throw new Error(
7348
+ `Pi resource source must be a regular file: ${contribution.workerEntryPath}`
7349
+ );
7350
+ }
7351
+ const identity = `${source.dev}:${source.ino}`;
7352
+ const physicalPath = await realpath2(contribution.workerEntryPath);
7353
+ const first = workerSourceIdentities.get(identity) ?? workerSourceRealPaths.get(physicalPath);
7354
+ if (first) {
7355
+ throw new Error(
7356
+ `Physical Pi resource file is included more than once: ${contribution.workerEntryPath} (first: ${first})`
7357
+ );
7358
+ }
7359
+ workerSourceIdentities.set(identity, contribution.workerEntryPath);
7360
+ workerSourceRealPaths.set(physicalPath, contribution.workerEntryPath);
7361
+ const snapshotPath = extensionSnapshotPath(contribution, index2);
7362
+ collector.addBytes(
7363
+ snapshotPath,
7364
+ await buildPiExtensionWrapper(contribution.workerEntryPath),
7365
+ { kind: "extension", ...baseOwner }
7366
+ );
7367
+ }
7368
+ for (const skillDirectory of contribution.resources.skillDirectories) {
7369
+ await collector.addDirectory(skillDirectory, "skills", { kind: "skill", ...baseOwner });
7370
+ }
7371
+ for (const promptDirectory of contribution.resources.promptDirectories) {
7372
+ await collector.addDirectory(promptDirectory, "prompts", { kind: "prompt", ...baseOwner });
7373
+ }
7374
+ }
7375
+ const credentialPaths = normalizeCredentialPaths(input.declaredCredentialPaths);
7376
+ assertCredentialPathsDoNotOverlap(credentialPaths, [...collector.files.keys(), "generated.json"]);
7377
+ const provenance = collector.provenance.slice().sort((left, right) => compareResourcePaths(left.snapshotPath, right.snapshotPath));
7378
+ const generated = {
7379
+ schemaVersion: PI_RESOURCE_SNAPSHOT_SCHEMA_VERSION,
7380
+ model: { ...input.model },
7381
+ providerOptions: { ...input.providerOptions },
7382
+ providerWorkerConfig: input.providerWorkerConfig ? {
7383
+ version: input.providerWorkerConfig.version,
7384
+ value: canonicalizeJson(
7385
+ input.providerWorkerConfig.value,
7386
+ "providerWorkerConfig.value"
7387
+ )
7388
+ } : null,
7389
+ declaredCredentialPaths: credentialPaths,
7390
+ compatibility: { ...input.compatibility },
7391
+ provenance
7392
+ };
7393
+ collector.addBytes("generated.json", jsonBytes(generated, "generated.json"));
7394
+ const resourceFiles = collector.toResourceFiles();
7395
+ const bundle = createCanonicalPiResourceBundle(resourceFiles);
7396
+ return {
7397
+ bundle,
7398
+ generated,
7399
+ files: collector.provenance.map(({ snapshotPath, sha256, size }) => ({ path: snapshotPath, sha256, size })).sort((left, right) => compareResourcePaths(left.path, right.path))
7400
+ };
7401
+ }
7402
+
6965
7403
  // src/process-operator-attention.ts
6966
7404
  import { trimToNull as trimToNull6 } from "@leitwerk-dev/domain";
6967
7405
  import { isHumanTurnDefinition } from "@leitwerk-dev/process-sdk";
@@ -7122,6 +7560,394 @@ function broadcastProcessAttentionToast(deps, input) {
7122
7560
  return true;
7123
7561
  }
7124
7562
 
7563
+ // src/worker-runtime-profile-selection.ts
7564
+ function trimToUndefined(value) {
7565
+ if (typeof value !== "string") {
7566
+ return void 0;
7567
+ }
7568
+ const trimmed = value.trim();
7569
+ return trimmed.length > 0 ? trimmed : void 0;
7570
+ }
7571
+ function defaultWorkerRuntimeProfile(config) {
7572
+ if (config.workers.runner === "local") {
7573
+ return config.workers.default_runtime_profile ?? "local";
7574
+ }
7575
+ return (config.workers.runner === "kubernetes" ? config.kubernetes?.default_worker_runtime_profile : void 0) ?? config.workers.default_runtime_profile ?? null;
7576
+ }
7577
+ function selectWorkerRuntimeProfile(input) {
7578
+ const override = trimToUndefined(input.processOverride);
7579
+ if (override) {
7580
+ return resolveProfileImage(override, input.profiles);
7581
+ }
7582
+ const declared = input.componentProfiles.map((entry) => ({ component: entry.component, profile: trimToUndefined(entry.profile) })).filter(
7583
+ (entry) => entry.profile !== void 0
7584
+ );
7585
+ const distinct = new Set(declared.map((entry) => entry.profile));
7586
+ if (distinct.size > 1) {
7587
+ const summary = declared.map((entry) => `${entry.component}=${entry.profile}`).sort().join(", ");
7588
+ return {
7589
+ ok: false,
7590
+ error: `Process '${input.processId}' has conflicting component worker runtime profiles (${summary}); set process_configs.${input.processId}.worker_runtime_profile to resolve`
7591
+ };
7592
+ }
7593
+ if (distinct.size === 1) {
7594
+ const [only] = distinct;
7595
+ return resolveProfileImage(only, input.profiles);
7596
+ }
7597
+ const fallback = trimToUndefined(input.defaultProfile);
7598
+ if (!fallback) {
7599
+ return {
7600
+ ok: false,
7601
+ error: `Process '${input.processId}' selects no worker runtime profile and no default worker runtime profile is configured`
7602
+ };
7603
+ }
7604
+ return resolveProfileImage(fallback, input.profiles);
7605
+ }
7606
+ function resolveProfileImage(runtimeProfile, profiles) {
7607
+ const profile = profiles[runtimeProfile];
7608
+ if (!profile) {
7609
+ return {
7610
+ ok: false,
7611
+ error: `Unknown worker runtime profile '${runtimeProfile}'; configure it under worker_runtime_profiles`
7612
+ };
7613
+ }
7614
+ return {
7615
+ ok: true,
7616
+ runtimeProfile,
7617
+ image: { reference: profile.image }
7618
+ };
7619
+ }
7620
+ function buildRuntimeProfileSelectionInput(args) {
7621
+ const { config, processId, componentKeys } = args;
7622
+ const componentProfiles = componentKeys.map((component) => ({
7623
+ component,
7624
+ profile: config.components[component]?.worker_runtime_profile
7625
+ }));
7626
+ return {
7627
+ processId,
7628
+ processOverride: config.process_configs?.[processId]?.worker_runtime_profile,
7629
+ componentProfiles,
7630
+ defaultProfile: defaultWorkerRuntimeProfile(config) ?? void 0,
7631
+ profiles: config.worker_runtime_profiles ?? {}
7632
+ };
7633
+ }
7634
+
7635
+ // src/process-engine/turn-start-preflight.ts
7636
+ import { filterProviderOptionsForDefinition } from "@leitwerk-dev/process-sdk";
7637
+ import { IPC_PROTOCOL_VERSION, WORKER_API_VERSION } from "@leitwerk-dev/worker-protocol";
7638
+
7639
+ // src/model-providers/provider-options.ts
7640
+ import {
7641
+ resolveProviderOptions
7642
+ } from "@leitwerk-dev/process-sdk";
7643
+ var DEFAULT_OPTION_CHOICE_TIMEOUT_MS = 5e3;
7644
+ var DEFAULT_MAX_CHOICE_FIELDS = 64;
7645
+ var DEFAULT_MAX_CHOICES_PER_FIELD = 256;
7646
+ var DEFAULT_MAX_CHOICE_TEXT_LENGTH = 512;
7647
+ function resolveRegisteredProviderOptions(input) {
7648
+ return resolveProviderOptions({
7649
+ definition: input.provider.definition.options,
7650
+ config: input.provider.config,
7651
+ explicit: input.explicit,
7652
+ profileDefaults: input.profileDefaults
7653
+ });
7654
+ }
7655
+ function validateConfiguredProviderOptions(input) {
7656
+ const result = resolveRegisteredProviderOptions({
7657
+ provider: input.provider,
7658
+ profileDefaults: input.values
7659
+ });
7660
+ if (result.ok) {
7661
+ return [];
7662
+ }
7663
+ return result.issues.filter((issue2) => issue2.code !== "required");
7664
+ }
7665
+ async function loadProviderOptionChoices(input) {
7666
+ const choicesLoader = input.provider.definition.options?.choices;
7667
+ if (!choicesLoader) {
7668
+ return { ok: true, choices: {} };
7669
+ }
7670
+ const timeoutMs = positiveBound(
7671
+ input.timeoutMs,
7672
+ DEFAULT_OPTION_CHOICE_TIMEOUT_MS,
7673
+ "Provider option choice timeout"
7674
+ );
7675
+ const maxFields = positiveBound(
7676
+ input.maxFields,
7677
+ DEFAULT_MAX_CHOICE_FIELDS,
7678
+ "Maximum choice fields"
7679
+ );
7680
+ const maxChoices = positiveBound(
7681
+ input.maxChoicesPerField,
7682
+ DEFAULT_MAX_CHOICES_PER_FIELD,
7683
+ "Maximum choices per field"
7684
+ );
7685
+ const maxTextLength = positiveBound(
7686
+ input.maxTextLength,
7687
+ DEFAULT_MAX_CHOICE_TEXT_LENGTH,
7688
+ "Maximum choice text length"
7689
+ );
7690
+ try {
7691
+ const credentialStatus = validateCredentialStatus(
7692
+ await withTimeout(Promise.resolve(input.credentialStatus(input.provider)), timeoutMs)
7693
+ );
7694
+ const raw = await withTimeout(
7695
+ Promise.resolve(choicesLoader({ config: input.provider.config, credentialStatus })),
7696
+ timeoutMs
7697
+ );
7698
+ const entries = Object.entries(raw);
7699
+ if (entries.length > maxFields) {
7700
+ throw new Error("too many fields");
7701
+ }
7702
+ const fields = input.provider.definition.options?.fields ?? {};
7703
+ const bounded = {};
7704
+ for (const [fieldId, choices] of entries) {
7705
+ if (!(fieldId in fields) || !Array.isArray(choices) || choices.length > maxChoices) {
7706
+ throw new Error("invalid field choices");
7707
+ }
7708
+ bounded[fieldId] = choices.map((choice) => {
7709
+ if (typeof choice?.value !== "string" || typeof choice?.label !== "string" || choice.value.length > maxTextLength || choice.label.length > maxTextLength) {
7710
+ throw new Error("invalid choice");
7711
+ }
7712
+ return { value: choice.value, label: choice.label };
7713
+ });
7714
+ }
7715
+ return { ok: true, choices: bounded };
7716
+ } catch (error) {
7717
+ return {
7718
+ ok: false,
7719
+ safeReason: error instanceof Error && error.message === "timeout" ? "Provider option choices timed out" : "Provider option choices are temporarily unavailable"
7720
+ };
7721
+ }
7722
+ }
7723
+
7724
+ // src/process-engine/turn-start-preflight.ts
7725
+ var PI_RUNTIME_VERSION = "0.81.1";
7726
+ function failure(requestedModelProfileId, providerOptions, code, safeSummary, modelSelectionProvenance, availabilityRevision) {
7727
+ return {
7728
+ kind: "preparation_failed",
7729
+ requestedModelProfileId,
7730
+ providerOptions,
7731
+ code,
7732
+ safeSummary,
7733
+ ...modelSelectionProvenance ? { modelSelectionProvenance } : {},
7734
+ ...availabilityRevision !== void 0 ? { availabilityRevision } : {}
7735
+ };
7736
+ }
7737
+ function previousProviderOptions(state) {
7738
+ if (state.kind === "preparation_failed") return { ...state.providerOptions };
7739
+ if (state.kind === "superseded" || state.kind === "starting" || state.kind === "accepted") {
7740
+ return state.start?.kind === "llm" ? { ...state.start.providerOptions } : {};
7741
+ }
7742
+ return state.start.kind === "llm" ? { ...state.start.providerOptions } : {};
7743
+ }
7744
+ function previousProviderId(deps, state) {
7745
+ if (state.kind !== "preparation_failed") {
7746
+ return state.start?.kind === "llm" ? state.start.model.providerId : null;
7747
+ }
7748
+ const profileId = state.requestedModelProfileId;
7749
+ return profileId ? deps.config.pi.model_profiles.find((profile) => profile.id === profileId)?.provider ?? null : null;
7750
+ }
7751
+ function parkPreparationFailure(writes, write, state) {
7752
+ write.input.state = state;
7753
+ writes.processPatch.lifecycleStatus = "error";
7754
+ writes.workerIntent = { kind: "reconcile" };
7755
+ }
7756
+ function candidateProcess(process2, writes) {
7757
+ return { ...process2, ...writes.processPatch };
7758
+ }
7759
+ function resolveRuntimeProfile(deps, process2) {
7760
+ if (deps.config.workers.runner === "local") {
7761
+ return { ok: true, id: defaultWorkerRuntimeProfile(deps.config) ?? "local" };
7762
+ }
7763
+ const selection = selectWorkerRuntimeProfile(
7764
+ buildRuntimeProfileSelectionInput({
7765
+ config: deps.config,
7766
+ processId: process2.processId,
7767
+ componentKeys: deps.projects.listByInstance(process2.id).map((project) => project.key)
7768
+ })
7769
+ );
7770
+ return selection.ok ? { ok: true, id: selection.runtimeProfile } : { ok: false, message: selection.error };
7771
+ }
7772
+ function resolveProviderWorkerConfig(provider, options) {
7773
+ if (provider.definition.worker.kind !== "extension_pi_worker") return null;
7774
+ const definition = provider.definition.worker.config;
7775
+ if (!definition) return null;
7776
+ const projected = definition.resolve({ config: provider.config, options });
7777
+ const value = definition.schema.parse(projected);
7778
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
7779
+ throw new Error("Provider worker configuration must be a JSON object");
7780
+ }
7781
+ return { version: definition.version, value };
7782
+ }
7783
+ function resolveProviderPiModels(provider) {
7784
+ const worker = provider.definition.worker;
7785
+ return worker.kind === "configured_pi_provider" ? worker.resolveModels({ config: provider.config }) : { providers: {} };
7786
+ }
7787
+ function buildPiSettings(config) {
7788
+ return {
7789
+ retry: {
7790
+ enabled: config.pi.retry.enabled,
7791
+ maxRetries: config.pi.retry.max_retries,
7792
+ baseDelay: config.pi.retry.base_delay,
7793
+ provider: {
7794
+ timeout: config.pi.retry.provider.timeout,
7795
+ maxRetries: config.pi.retry.provider.max_retries,
7796
+ maxRetryDelay: config.pi.retry.provider.max_retry_delay
7797
+ }
7798
+ }
7799
+ };
7800
+ }
7801
+ async function prepareCreatedTurnStarts(deps, process2, writes, explicitProviderOptions, availabilitySnapshot) {
7802
+ const nextProcess = candidateProcess(process2, writes);
7803
+ const availability = availabilitySnapshot ?? deps.modelStatusCache.snapshot();
7804
+ const provenance = nextProcess.selectedTurnModelKind && nextProcess.selectedTurnModelSource ? {
7805
+ kind: nextProcess.selectedTurnModelKind,
7806
+ source: nextProcess.selectedTurnModelSource
7807
+ } : void 0;
7808
+ for (let index2 = 0; index2 < writes.turnStartWrites.length; index2 += 1) {
7809
+ const write = writes.turnStartWrites[index2];
7810
+ if (!write || write.kind !== "create" || write.input.turnType !== "llm") continue;
7811
+ const requestedProfileId = nextProcess.selectedTurnModelProfileId?.trim() || null;
7812
+ const retainedState = write.input.state;
7813
+ const retainedOptions = previousProviderOptions(retainedState);
7814
+ if (retainedState.kind === "preparation_failed" && retainedState.code === "invalid_model_configuration") {
7815
+ parkPreparationFailure(writes, write, retainedState);
7816
+ continue;
7817
+ }
7818
+ if (!requestedProfileId) {
7819
+ parkPreparationFailure(
7820
+ writes,
7821
+ write,
7822
+ failure(
7823
+ null,
7824
+ retainedOptions,
7825
+ "model_required",
7826
+ "Choose a model before retrying startup",
7827
+ void 0,
7828
+ availability.revision
7829
+ )
7830
+ );
7831
+ continue;
7832
+ }
7833
+ const profile = deps.config.pi.model_profiles.find((item) => item.id === requestedProfileId);
7834
+ if (!profile) {
7835
+ return {
7836
+ ok: false,
7837
+ code: "invalid_model_profile",
7838
+ message: `Unknown model profile '${requestedProfileId}'`
7839
+ };
7840
+ }
7841
+ const provider = deps.registry.require(profile.provider);
7842
+ const retainedProviderId = previousProviderId(deps, retainedState);
7843
+ const recoveryOptions = explicitProviderOptions ? { ...explicitProviderOptions } : retainedProviderId !== null && retainedProviderId !== provider.id ? {
7844
+ ...filterProviderOptionsForDefinition(provider.definition.options, retainedOptions)
7845
+ } : retainedOptions;
7846
+ const optionResult = resolveRegisteredProviderOptions({
7847
+ provider,
7848
+ explicit: recoveryOptions,
7849
+ profileDefaults: profile.provider_options ?? {}
7850
+ });
7851
+ if (!optionResult.ok) {
7852
+ const onlyRequired = optionResult.issues.every((issue2) => issue2.code === "required");
7853
+ if (!onlyRequired) {
7854
+ return {
7855
+ ok: false,
7856
+ code: "invalid_provider_options",
7857
+ message: optionResult.issues.map((issue2) => issue2.message).join("; ")
7858
+ };
7859
+ }
7860
+ parkPreparationFailure(
7861
+ writes,
7862
+ write,
7863
+ failure(
7864
+ profile.id,
7865
+ recoveryOptions,
7866
+ "provider_options_required",
7867
+ optionResult.issues.map((issue2) => issue2.message).join("; ")
7868
+ )
7869
+ );
7870
+ continue;
7871
+ }
7872
+ const status = availability.profiles.find((candidate2) => candidate2.profileId === profile.id);
7873
+ if (!status || status.availability !== "available") {
7874
+ parkPreparationFailure(
7875
+ writes,
7876
+ write,
7877
+ failure(
7878
+ profile.id,
7879
+ recoveryOptions,
7880
+ !status || status.availability === "stale" ? "model_stale" : "model_unavailable",
7881
+ status?.safeReason ?? "The selected model status is stale",
7882
+ provenance,
7883
+ availability.revision
7884
+ )
7885
+ );
7886
+ continue;
7887
+ }
7888
+ try {
7889
+ const runtimeProfile = resolveRuntimeProfile(deps, nextProcess);
7890
+ if (!runtimeProfile.ok) throw new Error(runtimeProfile.message);
7891
+ const providerWorkerConfig = resolveProviderWorkerConfig(provider, optionResult.value);
7892
+ const piSettings = buildPiSettings(deps.config);
7893
+ const model = {
7894
+ profileId: profile.id,
7895
+ providerId: profile.provider,
7896
+ modelId: profile.model_id,
7897
+ thinkingLevel: profile.thinking_level ?? "off"
7898
+ };
7899
+ const resourceLayers = deps.processSkills.listResourceLayers(nextProcess.id);
7900
+ const assembled = await assemblePiResourceSnapshot({
7901
+ resourceLayers,
7902
+ piContributions: deps.piContributions,
7903
+ model,
7904
+ providerOptions: optionResult.value,
7905
+ providerWorkerConfig,
7906
+ piSettings,
7907
+ piModels: resolveProviderPiModels(provider),
7908
+ declaredCredentialPaths: [
7909
+ "auth.json",
7910
+ ...provider.definition.worker.kind === "extension_pi_worker" ? provider.definition.worker.credentialFiles ?? [] : []
7911
+ ],
7912
+ compatibility: {
7913
+ workerApiVersion: WORKER_API_VERSION,
7914
+ piVersion: PI_RUNTIME_VERSION,
7915
+ protocolVersion: IPC_PROTOCOL_VERSION
7916
+ }
7917
+ });
7918
+ deps.bundleCache.put(assembled.bundle);
7919
+ write.input.state = {
7920
+ kind: "starting",
7921
+ start: {
7922
+ kind: "llm",
7923
+ model,
7924
+ ...provenance ? { modelSelectionProvenance: provenance } : {},
7925
+ availabilityRevision: availability.revision,
7926
+ providerOptions: { ...optionResult.value },
7927
+ providerWorkerConfig,
7928
+ piResourceSnapshotDigest: assembled.bundle.digest,
7929
+ workerRuntimeProfileId: runtimeProfile.id,
7930
+ piSettings
7931
+ }
7932
+ };
7933
+ writes.processPatch.lifecycleStatus = "active";
7934
+ writes.workerIntent = { kind: "restart_worker" };
7935
+ } catch {
7936
+ parkPreparationFailure(
7937
+ writes,
7938
+ write,
7939
+ failure(
7940
+ profile.id,
7941
+ { ...optionResult.value },
7942
+ "provider_preflight_failed",
7943
+ "The provider could not prepare this worker start"
7944
+ )
7945
+ );
7946
+ }
7947
+ }
7948
+ return { ok: true };
7949
+ }
7950
+
7125
7951
  // src/process-operation-coordinator.ts
7126
7952
  function createProcessOperationCoordinator() {
7127
7953
  const tails = /* @__PURE__ */ new Map();
@@ -7152,7 +7978,7 @@ import {
7152
7978
  stat,
7153
7979
  unlink
7154
7980
  } from "node:fs/promises";
7155
- import path2 from "node:path";
7981
+ import path3 from "node:path";
7156
7982
  import { atomicWriteUtf8, isEnoent } from "@leitwerk-dev/process-sdk";
7157
7983
 
7158
7984
  // src/pi-session-tree.ts
@@ -7376,13 +8202,13 @@ function assertSafeSessionInstanceId(instanceId) {
7376
8202
  }
7377
8203
  function resolveSessionSnapshotPath(rootDir, instanceId) {
7378
8204
  assertSafeSessionInstanceId(instanceId);
7379
- return path2.join(rootDir, `${instanceId}.jsonl`);
8205
+ return path3.join(rootDir, `${instanceId}.jsonl`);
7380
8206
  }
7381
8207
  async function atomicCopyFile(sourcePath, targetPath) {
7382
- await mkdir(path2.dirname(targetPath), { recursive: true });
7383
- const tempPath = path2.join(
7384
- path2.dirname(targetPath),
7385
- `.${path2.basename(targetPath)}.${randomUUID()}.tmp`
8208
+ await mkdir(path3.dirname(targetPath), { recursive: true });
8209
+ const tempPath = path3.join(
8210
+ path3.dirname(targetPath),
8211
+ `.${path3.basename(targetPath)}.${randomUUID()}.tmp`
7386
8212
  );
7387
8213
  try {
7388
8214
  await copyFile(sourcePath, tempPath);
@@ -7425,7 +8251,7 @@ async function loadSnapshotGeneration(treeFile, expectedSignature) {
7425
8251
  }
7426
8252
  }
7427
8253
  function createFileBackedProcessSessionSnapshotStore(treeFilesDir) {
7428
- const rootDir = path2.resolve(treeFilesDir);
8254
+ const rootDir = path3.resolve(treeFilesDir);
7429
8255
  const resolveTreeFile = (instanceId) => resolveSessionSnapshotPath(rootDir, instanceId);
7430
8256
  return {
7431
8257
  async readSnapshotHandle(instanceId) {
@@ -7857,7 +8683,7 @@ function buildTurnTraceIndexFromSession(input) {
7857
8683
 
7858
8684
  // src/session-transfer-service.ts
7859
8685
  import { createHash as createHash3 } from "node:crypto";
7860
- import path4 from "node:path";
8686
+ import path5 from "node:path";
7861
8687
  import { Transform } from "node:stream";
7862
8688
  import { pipeline } from "node:stream/promises";
7863
8689
  import { setTimeout as delay } from "node:timers/promises";
@@ -7868,7 +8694,7 @@ import {
7868
8694
 
7869
8695
  // src/supervisor/worker-storage-layout.ts
7870
8696
  import { existsSync as existsSync3, mkdirSync as mkdirSync2 } from "node:fs";
7871
- import path3 from "node:path";
8697
+ import path4 from "node:path";
7872
8698
  import { expandPiAgentDir } from "@leitwerk-dev/process-sdk/pi-config";
7873
8699
  function normalizeContainerMountPath(mountPath) {
7874
8700
  const trimmed = mountPath.trim();
@@ -7876,18 +8702,18 @@ function normalizeContainerMountPath(mountPath) {
7876
8702
  return "/state";
7877
8703
  }
7878
8704
  const withLeadingSlash = trimmed.startsWith("/") ? trimmed : `/${trimmed}`;
7879
- return path3.posix.normalize(withLeadingSlash);
8705
+ return path4.posix.normalize(withLeadingSlash);
7880
8706
  }
7881
8707
  function joinContainerPath(mountPath, ...segments) {
7882
8708
  const normalized = normalizeContainerMountPath(mountPath);
7883
- return path3.posix.join(normalized, ...segments);
8709
+ return path4.posix.join(normalized, ...segments);
7884
8710
  }
7885
8711
  function createLocalWorkerStorageLayout(input) {
7886
8712
  return (instanceId) => {
7887
- const processWorkspacesDir = path3.resolve(input.processWorkspacesDir);
7888
- const treeFilesDir = path3.resolve(input.treeFilesDir);
7889
- const workspaceRoot = path3.join(processWorkspacesDir, instanceId);
7890
- const primaryTreeFile = path3.join(treeFilesDir, `${instanceId}.jsonl`);
8713
+ const processWorkspacesDir = path4.resolve(input.processWorkspacesDir);
8714
+ const treeFilesDir = path4.resolve(input.treeFilesDir);
8715
+ const workspaceRoot = path4.join(processWorkspacesDir, instanceId);
8716
+ const primaryTreeFile = path4.join(treeFilesDir, `${instanceId}.jsonl`);
7891
8717
  const resume = existsSync3(workspaceRoot) || existsSync3(primaryTreeFile);
7892
8718
  mkdirSync2(processWorkspacesDir, { recursive: true });
7893
8719
  mkdirSync2(treeFilesDir, { recursive: true });
@@ -7895,7 +8721,7 @@ function createLocalWorkerStorageLayout(input) {
7895
8721
  return {
7896
8722
  primaryTreeFile,
7897
8723
  workspaceRoot,
7898
- piResourceBundlesDir: path3.join(workspaceRoot, ".leitwerk", "pi-resource-bundles"),
8724
+ piResourceBundlesDir: path4.join(workspaceRoot, ".leitwerk", "pi-resource-bundles"),
7899
8725
  resume
7900
8726
  };
7901
8727
  };
@@ -7946,12 +8772,12 @@ function presentSessionTransferOperation(attempt) {
7946
8772
  }
7947
8773
  function relativeSessionCwd(input) {
7948
8774
  if (!input.repositoryBacked) return null;
7949
- const relative = path4.relative(path4.resolve(input.workspaceRoot), path4.resolve(input.sourceCwd));
8775
+ const relative = path5.relative(path5.resolve(input.workspaceRoot), path5.resolve(input.sourceCwd));
7950
8776
  if (relative === "") return ".";
7951
- if (relative === ".." || relative.startsWith(`..${path4.sep}`) || path4.isAbsolute(relative)) {
8777
+ if (relative === ".." || relative.startsWith(`..${path5.sep}`) || path5.isAbsolute(relative)) {
7952
8778
  throw new Error("Repository-backed Pi session cwd is outside the process workspace");
7953
8779
  }
7954
- return relative.split(path4.sep).join("/");
8780
+ return relative.split(path5.sep).join("/");
7955
8781
  }
7956
8782
  function createSessionTransferService(deps) {
7957
8783
  const now2 = deps.now ?? (() => /* @__PURE__ */ new Date());
@@ -8703,20 +9529,20 @@ function presentLaunchPlanPreparationIssues(issues) {
8703
9529
  message: issue2.message
8704
9530
  }));
8705
9531
  }
8706
- function presentProcessModelPolicyFailure(failure) {
8707
- switch (failure.code) {
9532
+ function presentProcessModelPolicyFailure(failure2) {
9533
+ switch (failure2.code) {
8708
9534
  case "model_required":
8709
9535
  return "Choose a model before starting this turn";
8710
9536
  case "unknown_model_profile":
8711
- return `Unknown model profile '${failure.modelProfileId}'`;
9537
+ return `Unknown model profile '${failure2.modelProfileId}'`;
8712
9538
  case "model_profile_not_allowed":
8713
- return `Model profile '${failure.modelProfileId}' is not allowed for process '${failure.processId}'`;
9539
+ return `Model profile '${failure2.modelProfileId}' is not allowed for process '${failure2.processId}'`;
8714
9540
  case "model_stale":
8715
- return failure.reason ?? "Model status has not been refreshed";
9541
+ return failure2.reason ?? "Model status has not been refreshed";
8716
9542
  case "model_unavailable":
8717
- return failure.reason ?? "The selected model is unavailable";
9543
+ return failure2.reason ?? "The selected model is unavailable";
8718
9544
  case "invalid_model_configuration":
8719
- return failure.source === "selection_provenance" ? "Persisted model selection provenance is invalid" : "Persisted model configuration is invalid";
9545
+ return failure2.source === "selection_provenance" ? "Persisted model selection provenance is invalid" : "Persisted model configuration is invalid";
8720
9546
  case "stale_evaluation_snapshot":
8721
9547
  return "Model availability changed repeatedly during evaluation";
8722
9548
  }
@@ -8766,9 +9592,9 @@ function presentProcessModelConfiguration(projection) {
8766
9592
 
8767
9593
  // src/process-turn-navigation.ts
8768
9594
  function presentProcessTurnNavigation(input) {
8769
- const path5 = input.graph.happyPath ?? [];
8770
- const currentIndex = path5.indexOf(input.selectedTurnId ?? "");
8771
- const nextId = input.lifecycleStatus === "active" && currentIndex >= 0 ? path5[currentIndex + 1] : void 0;
9595
+ const path6 = input.graph.happyPath ?? [];
9596
+ const currentIndex = path6.indexOf(input.selectedTurnId ?? "");
9597
+ const nextId = input.lifecycleStatus === "active" && currentIndex >= 0 ? path6[currentIndex + 1] : void 0;
8772
9598
  const next = nextId ? input.graph.turns.get(nextId) : void 0;
8773
9599
  return {
8774
9600
  turns: input.turns.map((turn) => ({
@@ -10113,13 +10939,13 @@ function setupDetail(event) {
10113
10939
  return null;
10114
10940
  }
10115
10941
  const provider = asRecord(event.data.provider) ?? {};
10116
- const path5 = stringValueOrNull(event.data.path) ?? stringValueOrNull(provider.path);
10942
+ const path6 = stringValueOrNull(event.data.path) ?? stringValueOrNull(provider.path);
10117
10943
  const pollInterval = stringValueOrNull(event.data.pollInterval) ?? stringValueOrNull(provider.pollInterval);
10118
- if (path5 && pollInterval) {
10119
- return `Watching ${path5} \xB7 polling every ${pollInterval}.`;
10944
+ if (path6 && pollInterval) {
10945
+ return `Watching ${path6} \xB7 polling every ${pollInterval}.`;
10120
10946
  }
10121
- if (path5) {
10122
- return `Watching ${path5}.`;
10947
+ if (path6) {
10948
+ return `Watching ${path6}.`;
10123
10949
  }
10124
10950
  if (pollInterval) {
10125
10951
  return `Polling every ${pollInterval}.`;
@@ -11004,6 +11830,136 @@ function createBroadcaster() {
11004
11830
  };
11005
11831
  }
11006
11832
 
11833
+ // src/process-engine/writes/writes.ts
11834
+ import {
11835
+ CONTINUE_PROMPT_METADATA_KEY as CONTINUE_PROMPT_METADATA_KEY2,
11836
+ FAILED_TURN_RECOVERY_METADATA_KEY,
11837
+ SYSTEM_ACTOR as SYSTEM_ACTOR2
11838
+ } from "@leitwerk-dev/domain";
11839
+ var METADATA_KEY_GROUPS = {
11840
+ retry: ["retryForkPiEntryId", "retryFromTurnRecordId"],
11841
+ continuation: [
11842
+ "continueFromPiEntryId",
11843
+ "continueFromTurnRecordId",
11844
+ "continueSavedPrimaryLeafEntryId",
11845
+ CONTINUE_PROMPT_METADATA_KEY2,
11846
+ FAILED_TURN_RECOVERY_METADATA_KEY
11847
+ ]
11848
+ };
11849
+ function createWrites(init = {}) {
11850
+ return {
11851
+ processPatch: init.processPatch ?? {},
11852
+ changedFields: [...init.changedFields ?? []],
11853
+ ...init.projectWrite ? { projectWrite: init.projectWrite } : {},
11854
+ turnRecordWrites: [...init.turnRecordWrites ?? []],
11855
+ turnStartWrites: [...init.turnStartWrites ?? []],
11856
+ turnAnnotationWrites: [...init.turnAnnotationWrites ?? []],
11857
+ leafOutcomeSnapshotWrites: [...init.leafOutcomeSnapshotWrites ?? []],
11858
+ events: [...init.events ?? []],
11859
+ broadcasts: [...init.broadcasts ?? []],
11860
+ queuedInputs: [...init.queuedInputs ?? []],
11861
+ extensionEvents: [...init.extensionEvents ?? []],
11862
+ futureExecutionPlans: [...init.futureExecutionPlans ?? []],
11863
+ pendingExternalSourceFireWrites: [...init.pendingExternalSourceFireWrites ?? []],
11864
+ ...init.workerIntent ? { workerIntent: init.workerIntent } : {}
11865
+ };
11866
+ }
11867
+ function mergeWrites(...writesList) {
11868
+ const merged = createWrites();
11869
+ for (const writes of writesList) {
11870
+ if (!writes) continue;
11871
+ Object.assign(merged.processPatch, writes.processPatch);
11872
+ for (const field of writes.changedFields) {
11873
+ if (!merged.changedFields.includes(field)) {
11874
+ merged.changedFields.push(field);
11875
+ }
11876
+ }
11877
+ if (writes.projectWrite) {
11878
+ if (merged.projectWrite) throw new Error("Cannot merge multiple process-project writes");
11879
+ merged.projectWrite = writes.projectWrite;
11880
+ }
11881
+ merged.turnRecordWrites.push(...writes.turnRecordWrites);
11882
+ merged.turnStartWrites.push(...writes.turnStartWrites);
11883
+ merged.turnAnnotationWrites.push(...writes.turnAnnotationWrites);
11884
+ merged.leafOutcomeSnapshotWrites.push(...writes.leafOutcomeSnapshotWrites);
11885
+ merged.events.push(...writes.events);
11886
+ merged.broadcasts.push(...writes.broadcasts);
11887
+ merged.queuedInputs.push(...writes.queuedInputs);
11888
+ merged.extensionEvents.push(...writes.extensionEvents);
11889
+ merged.futureExecutionPlans.push(...writes.futureExecutionPlans);
11890
+ merged.pendingExternalSourceFireWrites.push(...writes.pendingExternalSourceFireWrites);
11891
+ if (writes.workerIntent) {
11892
+ merged.workerIntent = writes.workerIntent;
11893
+ }
11894
+ }
11895
+ return merged;
11896
+ }
11897
+ function isWriteBuildFailure(value) {
11898
+ return typeof value === "object" && value !== null && "ok" in value && value.ok === false;
11899
+ }
11900
+ function applyProcessPatchField(writes, process2, field, value) {
11901
+ if (process2[field] === value) {
11902
+ return;
11903
+ }
11904
+ writes.processPatch[field] = value;
11905
+ if (!writes.changedFields.includes(field)) {
11906
+ writes.changedFields.push(field);
11907
+ }
11908
+ }
11909
+ function applyMetadataPatch(writes, process2, nextMetadata) {
11910
+ if (JSON.stringify(process2.metadata ?? null) === JSON.stringify(nextMetadata)) {
11911
+ return;
11912
+ }
11913
+ writes.processPatch.metadata = nextMetadata;
11914
+ if (!writes.changedFields.includes("metadata")) {
11915
+ writes.changedFields.push("metadata");
11916
+ }
11917
+ }
11918
+ function updateProcessMetadata(writes, process2, clearGroups = [], update = () => {
11919
+ }) {
11920
+ const nextMetadata = process2.metadata ? { ...process2.metadata } : {};
11921
+ for (const group of clearGroups) {
11922
+ for (const key of METADATA_KEY_GROUPS[group]) delete nextMetadata[key];
11923
+ }
11924
+ update(nextMetadata);
11925
+ applyMetadataPatch(writes, process2, Object.keys(nextMetadata).length > 0 ? nextMetadata : null);
11926
+ }
11927
+ function appendProcessEvent(writes, process2, input) {
11928
+ writes.events.push({
11929
+ instanceId: process2.id,
11930
+ eventType: input.eventType,
11931
+ ...input.data ? { data: input.data } : {}
11932
+ });
11933
+ writes.broadcasts.push({
11934
+ type: "process.event",
11935
+ payload: {
11936
+ eventType: input.eventType,
11937
+ level: input.level,
11938
+ message: input.message
11939
+ },
11940
+ instanceId: process2.id
11941
+ });
11942
+ }
11943
+ function stampActorOnEvents(writes, actor, eventType) {
11944
+ const resolvedActor = actor ?? SYSTEM_ACTOR2;
11945
+ let stamped = 0;
11946
+ for (const event of writes.events) {
11947
+ if (event.eventType === eventType) {
11948
+ event.data = { ...event.data ?? {}, actor: resolvedActor };
11949
+ stamped += 1;
11950
+ }
11951
+ }
11952
+ return stamped;
11953
+ }
11954
+ function stampActorOnQueuedInputs(writes, actor) {
11955
+ if (!actor) {
11956
+ return;
11957
+ }
11958
+ writes.queuedInputs = writes.queuedInputs.map(
11959
+ (queuedInput) => queuedInput.actor ? queuedInput : { ...queuedInput, actor }
11960
+ );
11961
+ }
11962
+
11007
11963
  export {
11008
11964
  resolveApiTokenPolicy,
11009
11965
  ApiTokenValidationError,
@@ -11034,13 +11990,19 @@ export {
11034
11990
  normalizeProcessTitleInput,
11035
11991
  applySubmittedProcessTitleToLaunchPlan,
11036
11992
  SKILL_RESOURCE_OWNER,
11037
- compareResourcePaths,
11038
- validatePhysicalSourcePath,
11039
11993
  ResourceCollector,
11040
11994
  createAllRepos,
11041
11995
  recordTurnProgress,
11042
11996
  normalizeExternalEventDescription,
11043
11997
  normalizeExternalObservation,
11998
+ createWrites,
11999
+ mergeWrites,
12000
+ isWriteBuildFailure,
12001
+ applyProcessPatchField,
12002
+ updateProcessMetadata,
12003
+ appendProcessEvent,
12004
+ stampActorOnEvents,
12005
+ stampActorOnQueuedInputs,
11044
12006
  buildProcessFlowViewForProcess,
11045
12007
  getProcessGraph2 as getProcessGraph,
11046
12008
  getProcessTurnGraph,
@@ -11068,10 +12030,22 @@ export {
11068
12030
  createLaunchPipeline,
11069
12031
  buildStartupEvidence,
11070
12032
  projectLaunchRunStartup,
12033
+ positiveBound,
12034
+ withTimeout,
12035
+ validateCredentialStatus,
12036
+ resolveRegisteredProviderOptions,
12037
+ validateConfiguredProviderOptions,
12038
+ loadProviderOptionChoices,
12039
+ createPiResourceBundleCache,
12040
+ createPiResourceBundlePinReconciler,
11071
12041
  getProcessDisplayName,
11072
12042
  listVisibleActionsForProcess,
11073
12043
  getSelectedTurnSummaryForProcess,
11074
12044
  broadcastProcessAttentionToast,
12045
+ defaultWorkerRuntimeProfile,
12046
+ selectWorkerRuntimeProfile,
12047
+ buildRuntimeProfileSelectionInput,
12048
+ prepareCreatedTurnStarts,
11075
12049
  createProcessOperationCoordinator,
11076
12050
  ProcessSessionReader,
11077
12051
  isSafeSessionInstanceId,
@@ -11112,4 +12086,4 @@ export {
11112
12086
  createProjectedSessionSnapshotStore,
11113
12087
  createBroadcaster
11114
12088
  };
11115
- //# sourceMappingURL=chunk-ZSKM25SD.js.map
12089
+ //# sourceMappingURL=chunk-KIOQNNG6.js.map