@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.
@@ -7,6 +7,8 @@ import {
7
7
  SAFE_SKILL_ID_PATTERN,
8
8
  SKILL_RESOURCE_OWNER,
9
9
  actorForRequest,
10
+ appendProcessEvent,
11
+ applyProcessPatchField,
10
12
  applySubmittedProcessTitleToLaunchPlan,
11
13
  authenticateBrowserRequest,
12
14
  authenticateRequest,
@@ -18,9 +20,9 @@ import {
18
20
  buildProcessFlowViewForProcess,
19
21
  buildProcessLaunchConfigurationView,
20
22
  buildProcessRunDetailsView,
23
+ buildRuntimeProfileSelectionInput,
21
24
  buildStartupEvidence,
22
25
  closeDatabase,
23
- compareResourcePaths,
24
26
  completeCommittedLaunch,
25
27
  createAllRepos,
26
28
  createBroadcaster,
@@ -30,11 +32,15 @@ import {
30
32
  createInMemoryDatabase,
31
33
  createLaunchPipeline,
32
34
  createOpaqueToken,
35
+ createPiResourceBundleCache,
36
+ createPiResourceBundlePinReconciler,
33
37
  createProcessOperationCoordinator,
34
38
  createProjectedSessionSnapshotStore,
35
39
  createServerProcessModelPolicy,
36
40
  createSessionTransferService,
37
41
  createWorkerStorageLayout,
42
+ createWrites,
43
+ defaultWorkerRuntimeProfile,
38
44
  evaluateAtStableAvailabilityRevision,
39
45
  failLaunchRun,
40
46
  finishLaunchRun,
@@ -56,11 +62,14 @@ import {
56
62
  isLoopbackHttpUrl,
57
63
  isSafeSessionInstanceId,
58
64
  isTurnAvailableForProcessGraph,
65
+ isWriteBuildFailure,
59
66
  isoFromNow,
60
67
  listVisibleActionsForProcess,
61
68
  listVisibleActionsForProcess2,
69
+ loadProviderOptionChoices,
62
70
  logProcessEngineError,
63
71
  mergeProcessEventWindowsAscending,
72
+ mergeWrites,
64
73
  normalizeActionRequest,
65
74
  normalizeContinueRequest,
66
75
  normalizeExternalEventDescription,
@@ -69,6 +78,8 @@ import {
69
78
  normalizeProcessTitleInput,
70
79
  normalizeRecoveryModelRequest,
71
80
  now,
81
+ positiveBound,
82
+ prepareCreatedTurnStarts,
72
83
  presentLaunchPlanPreparationIssues,
73
84
  presentLauncherModelConfigPreview,
74
85
  presentLauncherModelConfigSchema,
@@ -87,23 +98,30 @@ import {
87
98
  resolveCurrentExecutionTurnRecordId,
88
99
  resolveDockerRegistryCredentials,
89
100
  resolveProcessStorageSize,
101
+ resolveRegisteredProviderOptions,
90
102
  resolveWorkerPiAgentDir,
91
103
  routeConfig,
104
+ selectWorkerRuntimeProfile,
92
105
  sendActionRequestNormalizationError,
93
106
  sendLauncherLookupFailure,
94
107
  sendLauncherMutationResponse,
95
108
  sendLauncherRequestNormalizationError,
96
109
  sendScheduledActionMutationResponse,
97
110
  serializeProcessGraph,
111
+ stampActorOnEvents,
112
+ stampActorOnQueuedInputs,
98
113
  tokenExpiry,
99
114
  truncateTextAtWordBoundary,
115
+ updateProcessMetadata,
100
116
  validateConfig,
101
- validatePhysicalSourcePath,
102
- verifyOpaqueToken
103
- } from "./chunk-ZSKM25SD.js";
117
+ validateConfiguredProviderOptions,
118
+ validateCredentialStatus,
119
+ verifyOpaqueToken,
120
+ withTimeout
121
+ } from "./chunk-KIOQNNG6.js";
104
122
 
105
123
  // src/app.ts
106
- import path9 from "node:path";
124
+ import path8 from "node:path";
107
125
  import cookie from "@fastify/cookie";
108
126
  import {
109
127
  serializeResolvedExtensionEntries,
@@ -933,136 +951,6 @@ import {
933
951
  isHumanTurnDefinition
934
952
  } from "@leitwerk-dev/process-sdk";
935
953
 
936
- // src/process-engine/writes/writes.ts
937
- import {
938
- CONTINUE_PROMPT_METADATA_KEY,
939
- FAILED_TURN_RECOVERY_METADATA_KEY,
940
- SYSTEM_ACTOR
941
- } from "@leitwerk-dev/domain";
942
- var METADATA_KEY_GROUPS = {
943
- retry: ["retryForkPiEntryId", "retryFromTurnRecordId"],
944
- continuation: [
945
- "continueFromPiEntryId",
946
- "continueFromTurnRecordId",
947
- "continueSavedPrimaryLeafEntryId",
948
- CONTINUE_PROMPT_METADATA_KEY,
949
- FAILED_TURN_RECOVERY_METADATA_KEY
950
- ]
951
- };
952
- function createWrites(init = {}) {
953
- return {
954
- processPatch: init.processPatch ?? {},
955
- changedFields: [...init.changedFields ?? []],
956
- ...init.projectWrite ? { projectWrite: init.projectWrite } : {},
957
- turnRecordWrites: [...init.turnRecordWrites ?? []],
958
- turnStartWrites: [...init.turnStartWrites ?? []],
959
- turnAnnotationWrites: [...init.turnAnnotationWrites ?? []],
960
- leafOutcomeSnapshotWrites: [...init.leafOutcomeSnapshotWrites ?? []],
961
- events: [...init.events ?? []],
962
- broadcasts: [...init.broadcasts ?? []],
963
- queuedInputs: [...init.queuedInputs ?? []],
964
- extensionEvents: [...init.extensionEvents ?? []],
965
- futureExecutionPlans: [...init.futureExecutionPlans ?? []],
966
- pendingExternalSourceFireWrites: [...init.pendingExternalSourceFireWrites ?? []],
967
- ...init.workerIntent ? { workerIntent: init.workerIntent } : {}
968
- };
969
- }
970
- function mergeWrites(...writesList) {
971
- const merged = createWrites();
972
- for (const writes of writesList) {
973
- if (!writes) continue;
974
- Object.assign(merged.processPatch, writes.processPatch);
975
- for (const field of writes.changedFields) {
976
- if (!merged.changedFields.includes(field)) {
977
- merged.changedFields.push(field);
978
- }
979
- }
980
- if (writes.projectWrite) {
981
- if (merged.projectWrite) throw new Error("Cannot merge multiple process-project writes");
982
- merged.projectWrite = writes.projectWrite;
983
- }
984
- merged.turnRecordWrites.push(...writes.turnRecordWrites);
985
- merged.turnStartWrites.push(...writes.turnStartWrites);
986
- merged.turnAnnotationWrites.push(...writes.turnAnnotationWrites);
987
- merged.leafOutcomeSnapshotWrites.push(...writes.leafOutcomeSnapshotWrites);
988
- merged.events.push(...writes.events);
989
- merged.broadcasts.push(...writes.broadcasts);
990
- merged.queuedInputs.push(...writes.queuedInputs);
991
- merged.extensionEvents.push(...writes.extensionEvents);
992
- merged.futureExecutionPlans.push(...writes.futureExecutionPlans);
993
- merged.pendingExternalSourceFireWrites.push(...writes.pendingExternalSourceFireWrites);
994
- if (writes.workerIntent) {
995
- merged.workerIntent = writes.workerIntent;
996
- }
997
- }
998
- return merged;
999
- }
1000
- function isWriteBuildFailure(value) {
1001
- return typeof value === "object" && value !== null && "ok" in value && value.ok === false;
1002
- }
1003
- function applyProcessPatchField(writes, process2, field, value) {
1004
- if (process2[field] === value) {
1005
- return;
1006
- }
1007
- writes.processPatch[field] = value;
1008
- if (!writes.changedFields.includes(field)) {
1009
- writes.changedFields.push(field);
1010
- }
1011
- }
1012
- function applyMetadataPatch(writes, process2, nextMetadata) {
1013
- if (JSON.stringify(process2.metadata ?? null) === JSON.stringify(nextMetadata)) {
1014
- return;
1015
- }
1016
- writes.processPatch.metadata = nextMetadata;
1017
- if (!writes.changedFields.includes("metadata")) {
1018
- writes.changedFields.push("metadata");
1019
- }
1020
- }
1021
- function updateProcessMetadata(writes, process2, clearGroups = [], update = () => {
1022
- }) {
1023
- const nextMetadata = process2.metadata ? { ...process2.metadata } : {};
1024
- for (const group of clearGroups) {
1025
- for (const key of METADATA_KEY_GROUPS[group]) delete nextMetadata[key];
1026
- }
1027
- update(nextMetadata);
1028
- applyMetadataPatch(writes, process2, Object.keys(nextMetadata).length > 0 ? nextMetadata : null);
1029
- }
1030
- function appendProcessEvent(writes, process2, input) {
1031
- writes.events.push({
1032
- instanceId: process2.id,
1033
- eventType: input.eventType,
1034
- ...input.data ? { data: input.data } : {}
1035
- });
1036
- writes.broadcasts.push({
1037
- type: "process.event",
1038
- payload: {
1039
- eventType: input.eventType,
1040
- level: input.level,
1041
- message: input.message
1042
- },
1043
- instanceId: process2.id
1044
- });
1045
- }
1046
- function stampActorOnEvents(writes, actor, eventType) {
1047
- const resolvedActor = actor ?? SYSTEM_ACTOR;
1048
- let stamped = 0;
1049
- for (const event of writes.events) {
1050
- if (event.eventType === eventType) {
1051
- event.data = { ...event.data ?? {}, actor: resolvedActor };
1052
- stamped += 1;
1053
- }
1054
- }
1055
- return stamped;
1056
- }
1057
- function stampActorOnQueuedInputs(writes, actor) {
1058
- if (!actor) {
1059
- return;
1060
- }
1061
- writes.queuedInputs = writes.queuedInputs.map(
1062
- (queuedInput) => queuedInput.actor ? queuedInput : { ...queuedInput, actor }
1063
- );
1064
- }
1065
-
1066
954
  // src/process-engine/decision.ts
1067
955
  function accept(input = {}) {
1068
956
  return {
@@ -2046,7 +1934,7 @@ function createExternalSourceService(deps) {
2046
1934
  `External source '${input.armingId}' is stale for selected turn '${String(ctx.process.selectedTurnId)}'`
2047
1935
  );
2048
1936
  }
2049
- const failedDecision = (failure2) => {
1937
+ const failedDecision = (failure) => {
2050
1938
  const writes = createWrites();
2051
1939
  appendExternalSourceEvent(
2052
1940
  writes,
@@ -2056,11 +1944,11 @@ function createExternalSourceService(deps) {
2056
1944
  ...armingEventData(arming),
2057
1945
  provider: input.event,
2058
1946
  fireInput: input.input,
2059
- code: failure2.code,
2060
- message: failure2.message
1947
+ code: failure.code,
1948
+ message: failure.message
2061
1949
  })
2062
1950
  );
2063
- return accept({ writes, data: { ok: false, code: failure2.code } });
1951
+ return accept({ writes, data: { ok: false, code: failure.code } });
2064
1952
  };
2065
1953
  const effectWrites = await buildExternalSourceEffectWrites({
2066
1954
  arming,
@@ -2574,7 +2462,7 @@ function createExternalSourceService(deps) {
2574
2462
 
2575
2463
  // src/future-execution/lifecycle.ts
2576
2464
  import {
2577
- SYSTEM_ACTOR as SYSTEM_ACTOR3
2465
+ SYSTEM_ACTOR as SYSTEM_ACTOR2
2578
2466
  } from "@leitwerk-dev/domain";
2579
2467
  import {
2580
2468
  parseFutureActionPayloadJson as parseFutureActionPayloadJson3,
@@ -2918,7 +2806,7 @@ async function planProcessAction(input) {
2918
2806
  if ("ok" in planned) {
2919
2807
  return planned;
2920
2808
  }
2921
- const candidateProcess2 = {
2809
+ const candidateProcess = {
2922
2810
  ...input.process,
2923
2811
  ...planned.processPatch
2924
2812
  };
@@ -2930,7 +2818,7 @@ async function planProcessAction(input) {
2930
2818
  visibleAction: visibleAction ?? null,
2931
2819
  resolvedTurnAction,
2932
2820
  writes: planned,
2933
- candidateProcess: candidateProcess2,
2821
+ candidateProcess,
2934
2822
  candidateSelectedTurnId
2935
2823
  };
2936
2824
  }
@@ -3648,15 +3536,15 @@ function recoverDeduplicatedCommit(deps, dedupKey, futureExecutionPlan) {
3648
3536
  return deps.transaction((repos) => reuseDeduplicatedCommit(repos, dedupKey, futureExecutionPlan));
3649
3537
  }
3650
3538
  function launchStartFailure(commit, result) {
3651
- const failure2 = mapLaunchStartFailure(result);
3539
+ const failure = mapLaunchStartFailure(result);
3652
3540
  const process2 = result.process ?? commit.process;
3653
3541
  return {
3654
3542
  ok: false,
3655
3543
  stage: "post_commit",
3656
- status: failure2.status,
3544
+ status: failure.status,
3657
3545
  body: {
3658
- ...failure2.body,
3659
- process: failure2.body.process ?? process2,
3546
+ ...failure.body,
3547
+ process: failure.body.process ?? process2,
3660
3548
  projects: commit.projects
3661
3549
  },
3662
3550
  process: process2,
@@ -3772,12 +3660,12 @@ async function createProcessFromLaunchPlanWithDisposition(deps, launchPlan, opts
3772
3660
  reused: commit.dedupReused === true
3773
3661
  } : launchStartFailure(commit, started);
3774
3662
  } catch (error) {
3775
- const failure2 = toLaunchFailureBody(error, {
3663
+ const failure = toLaunchFailureBody(error, {
3776
3664
  createdProcess: commit.process,
3777
3665
  projects: commit.projects
3778
3666
  });
3779
3667
  return {
3780
- ...failure2,
3668
+ ...failure,
3781
3669
  stage: "post_commit",
3782
3670
  process: commit.process,
3783
3671
  projects: commit.projects
@@ -4331,7 +4219,7 @@ function createFutureExecutionExecutor(deps) {
4331
4219
  // src/future-execution/launch-lifecycle.ts
4332
4220
  import {
4333
4221
  normalizeLaunchModelConfigInput,
4334
- SYSTEM_ACTOR as SYSTEM_ACTOR2
4222
+ SYSTEM_ACTOR
4335
4223
  } from "@leitwerk-dev/domain";
4336
4224
  import {
4337
4225
  parseFutureLaunchPayloadJson as parseFutureLaunchPayloadJson3,
@@ -4546,29 +4434,29 @@ function createFutureLaunchLifecycle(deps, options = {}) {
4546
4434
  const opened = deps.launchPipeline.open({ launcherId: existing.launcherId, origin: "ui" });
4547
4435
  const result = await deps.launchPipeline.run(opened.launchRunId, {
4548
4436
  async resolve() {
4549
- const failure2 = (value) => ({
4437
+ const failure = (value) => ({
4550
4438
  kind: "failed",
4551
4439
  failure: { safeSummary: "Review the launch configuration and try again.", value }
4552
4440
  });
4553
4441
  if (!deps.launcherService)
4554
- return failure2({ kind: "unavailable", reason: "Launcher service is not available" });
4442
+ return failure({ kind: "unavailable", reason: "Launcher service is not available" });
4555
4443
  const parsed = parseFutureLaunchPayloadJson3(existing.payloadJson);
4556
4444
  if (!parsed.ok)
4557
- return failure2(invalidOutcome("invalid_payload", "Scheduled launch payload is invalid"));
4445
+ return failure(invalidOutcome("invalid_payload", "Scheduled launch payload is invalid"));
4558
4446
  const launchRequest = resolveScheduledLaunchUpdateRequest(existing, request, parsed.value);
4559
- if (!launchRequest.ok) return failure2({ kind: "invalid", issues: [launchRequest.issue] });
4447
+ if (!launchRequest.ok) return failure({ kind: "invalid", issues: [launchRequest.issue] });
4560
4448
  const resolved = await deps.launcherService.resolveUiLauncher(
4561
4449
  existing.launcherId ?? parsed.value.launchPlan.launcherId,
4562
4450
  launchRequest.value.launcherInput
4563
4451
  );
4564
- if (!resolved.ok) return failure2(launcherResolutionFailure(resolved));
4452
+ if (!resolved.ok) return failure(launcherResolutionFailure(resolved));
4565
4453
  return {
4566
4454
  kind: "resolved",
4567
4455
  value: {
4568
4456
  payload: parsed.value,
4569
4457
  request: launchRequest.value,
4570
4458
  launcher: resolved.launcher,
4571
- actor: actor ?? launchRequest.value.actor ?? SYSTEM_ACTOR2
4459
+ actor: actor ?? launchRequest.value.actor ?? SYSTEM_ACTOR
4572
4460
  }
4573
4461
  };
4574
4462
  },
@@ -4676,7 +4564,7 @@ function createFutureLaunchLifecycle(deps, options = {}) {
4676
4564
  /** @internal */
4677
4565
  async commitPreparedLaunch(prepared, opts) {
4678
4566
  if (prepared.schedule.mode !== "now")
4679
- return persistPreparedLaunch({ ...prepared, actor: opts?.actor ?? SYSTEM_ACTOR2 });
4567
+ return persistPreparedLaunch({ ...prepared, actor: opts?.actor ?? SYSTEM_ACTOR });
4680
4568
  const created = await createProcessFromLaunchPlan(deps, prepared.launchPlan, {
4681
4569
  ...opts,
4682
4570
  resourceSelections: prepared.resourceSelections,
@@ -4757,7 +4645,7 @@ function createFutureLaunchLifecycle(deps, options = {}) {
4757
4645
  return persistPreparedLaunch({
4758
4646
  ...prepared.prepared,
4759
4647
  existing,
4760
- actor: opts?.actor ?? launchRequest.value.actor ?? SYSTEM_ACTOR2
4648
+ actor: opts?.actor ?? launchRequest.value.actor ?? SYSTEM_ACTOR
4761
4649
  });
4762
4650
  });
4763
4651
  }
@@ -5096,7 +4984,7 @@ function createFutureExecutionLifecycle(deps, _options = {}) {
5096
4984
  actionInput: request.input,
5097
4985
  nextTurnModelProfileId: typeof request.nextTurnModelProfileId === "string" ? request.nextTurnModelProfileId : null,
5098
4986
  overrideProvided: typeof request.nextTurnModelProfileId === "string",
5099
- actor: opts?.actor ?? SYSTEM_ACTOR3,
4987
+ actor: opts?.actor ?? SYSTEM_ACTOR2,
5100
4988
  nextRunAt: validatedSchedule.nextRunAt,
5101
4989
  operationTime
5102
4990
  });
@@ -5149,7 +5037,7 @@ function createFutureExecutionLifecycle(deps, _options = {}) {
5149
5037
  source: "scheduled",
5150
5038
  scheduledExecutionId: existing.id,
5151
5039
  consumeScheduledExecutionOnSuccess: true,
5152
- actor: opts?.actor ?? resolvedActionRequest.value.actor ?? SYSTEM_ACTOR3
5040
+ actor: opts?.actor ?? resolvedActionRequest.value.actor ?? SYSTEM_ACTOR2
5153
5041
  }
5154
5042
  );
5155
5043
  }
@@ -5174,7 +5062,7 @@ function createFutureExecutionLifecycle(deps, _options = {}) {
5174
5062
  actionInput: resolvedActionRequest.value.input,
5175
5063
  nextTurnModelProfileId: resolvedActionRequest.value.nextTurnModelProfileId,
5176
5064
  overrideProvided: resolvedActionRequest.value.nextTurnModelProfileId !== null,
5177
- actor: opts?.actor ?? resolvedActionRequest.value.actor ?? SYSTEM_ACTOR3,
5065
+ actor: opts?.actor ?? resolvedActionRequest.value.actor ?? SYSTEM_ACTOR2,
5178
5066
  nextRunAt: validatedSchedule.nextRunAt,
5179
5067
  operationTime
5180
5068
  });
@@ -6138,7 +6026,7 @@ function createLaunchCoordinator(deps) {
6138
6026
  const projected = project(run);
6139
6027
  return JSON.stringify(projected) === JSON.stringify(run) ? run : mutate(run.id, () => projected);
6140
6028
  }
6141
- function failure2(safeSummary, value) {
6029
+ function failure(safeSummary, value) {
6142
6030
  return { safeSummary, value };
6143
6031
  }
6144
6032
  function existingLaunchResult(run) {
@@ -6181,7 +6069,7 @@ function createLaunchCoordinator(deps) {
6181
6069
  if (request.request.schedule.mode !== "now") {
6182
6070
  return {
6183
6071
  kind: "failed",
6184
- failure: failure2("Use the scheduling controls to save a future launch.", {
6072
+ failure: failure("Use the scheduling controls to save a future launch.", {
6185
6073
  kind: "invalid",
6186
6074
  issues: [
6187
6075
  {
@@ -6198,7 +6086,7 @@ function createLaunchCoordinator(deps) {
6198
6086
  );
6199
6087
  return resolved.ok ? { kind: "resolved", value: resolved.launcher } : {
6200
6088
  kind: "failed",
6201
- failure: failure2("Review the highlighted launcher fields and try again.", {
6089
+ failure: failure("Review the highlighted launcher fields and try again.", {
6202
6090
  kind: "invalid",
6203
6091
  issues: resolved.errors
6204
6092
  })
@@ -6241,7 +6129,7 @@ function createLaunchCoordinator(deps) {
6241
6129
  } : prepared.prepared
6242
6130
  } : {
6243
6131
  ok: false,
6244
- failure: failure2("Review the launch configuration and try again.", prepared.outcome)
6132
+ failure: failure("Review the launch configuration and try again.", prepared.outcome)
6245
6133
  };
6246
6134
  },
6247
6135
  async commit(prepared, ctx) {
@@ -6269,14 +6157,14 @@ function createLaunchCoordinator(deps) {
6269
6157
  }
6270
6158
  return {
6271
6159
  kind: "failed",
6272
- failure: failure2(
6160
+ failure: failure(
6273
6161
  "The process could not be created. Check availability and try again.",
6274
6162
  result
6275
6163
  )
6276
6164
  };
6277
6165
  },
6278
6166
  unexpectedFailure() {
6279
- return failure2("The launch could not be completed. Try again.", {
6167
+ return failure("The launch could not be completed. Try again.", {
6280
6168
  kind: "failed",
6281
6169
  issue: { code: "launch_failed", message: "The launch could not be completed" }
6282
6170
  });
@@ -6451,7 +6339,7 @@ function createLaunchCoordinator(deps) {
6451
6339
  );
6452
6340
  return prepared.ok ? { ok: true, value: prepared.launchPlan } : {
6453
6341
  ok: false,
6454
- failure: failure2(
6342
+ failure: failure(
6455
6343
  "The launch model configuration is unavailable. Review the watcher configuration.",
6456
6344
  prepared
6457
6345
  )
@@ -6896,34 +6784,6 @@ function createModelProviderCredentialService(input) {
6896
6784
  };
6897
6785
  }
6898
6786
 
6899
- // src/model-providers/provider-boundary-utils.ts
6900
- function positiveBound(value, fallback, name) {
6901
- const resolved = value ?? fallback;
6902
- if (!Number.isSafeInteger(resolved) || resolved < 1) {
6903
- throw new Error(`${name} must be a positive safe integer`);
6904
- }
6905
- return resolved;
6906
- }
6907
- async function withTimeout(work, timeoutMs, sentinelMessage = "timeout") {
6908
- let timer;
6909
- try {
6910
- return await Promise.race([
6911
- work,
6912
- new Promise((_resolve, reject2) => {
6913
- timer = setTimeout(() => reject2(new Error(sentinelMessage)), timeoutMs);
6914
- })
6915
- ]);
6916
- } finally {
6917
- if (timer) clearTimeout(timer);
6918
- }
6919
- }
6920
- function validateCredentialStatus(value, message = "invalid credential status") {
6921
- if (typeof value !== "object" || value === null || typeof value.available !== "boolean" || !(value.revision === null || Number.isSafeInteger(value.revision) && value.revision >= 0)) {
6922
- throw new Error(message);
6923
- }
6924
- return value;
6925
- }
6926
-
6927
6787
  // src/model-providers/model-status-cache.ts
6928
6788
  var DEFAULT_STATUS_TTL_MS = 3e4;
6929
6789
  var DEFAULT_STATUS_TIMEOUT_MS = 5e3;
@@ -7129,91 +6989,6 @@ function createModelStatusCache(input) {
7129
6989
  };
7130
6990
  }
7131
6991
 
7132
- // src/model-providers/provider-options.ts
7133
- import {
7134
- resolveProviderOptions
7135
- } from "@leitwerk-dev/process-sdk";
7136
- var DEFAULT_OPTION_CHOICE_TIMEOUT_MS = 5e3;
7137
- var DEFAULT_MAX_CHOICE_FIELDS = 64;
7138
- var DEFAULT_MAX_CHOICES_PER_FIELD = 256;
7139
- var DEFAULT_MAX_CHOICE_TEXT_LENGTH = 512;
7140
- function resolveRegisteredProviderOptions(input) {
7141
- return resolveProviderOptions({
7142
- definition: input.provider.definition.options,
7143
- config: input.provider.config,
7144
- explicit: input.explicit,
7145
- profileDefaults: input.profileDefaults
7146
- });
7147
- }
7148
- function validateConfiguredProviderOptions(input) {
7149
- const result = resolveRegisteredProviderOptions({
7150
- provider: input.provider,
7151
- profileDefaults: input.values
7152
- });
7153
- if (result.ok) {
7154
- return [];
7155
- }
7156
- return result.issues.filter((issue) => issue.code !== "required");
7157
- }
7158
- async function loadProviderOptionChoices(input) {
7159
- const choicesLoader = input.provider.definition.options?.choices;
7160
- if (!choicesLoader) {
7161
- return { ok: true, choices: {} };
7162
- }
7163
- const timeoutMs = positiveBound(
7164
- input.timeoutMs,
7165
- DEFAULT_OPTION_CHOICE_TIMEOUT_MS,
7166
- "Provider option choice timeout"
7167
- );
7168
- const maxFields = positiveBound(
7169
- input.maxFields,
7170
- DEFAULT_MAX_CHOICE_FIELDS,
7171
- "Maximum choice fields"
7172
- );
7173
- const maxChoices = positiveBound(
7174
- input.maxChoicesPerField,
7175
- DEFAULT_MAX_CHOICES_PER_FIELD,
7176
- "Maximum choices per field"
7177
- );
7178
- const maxTextLength = positiveBound(
7179
- input.maxTextLength,
7180
- DEFAULT_MAX_CHOICE_TEXT_LENGTH,
7181
- "Maximum choice text length"
7182
- );
7183
- try {
7184
- const credentialStatus = validateCredentialStatus(
7185
- await withTimeout(Promise.resolve(input.credentialStatus(input.provider)), timeoutMs)
7186
- );
7187
- const raw = await withTimeout(
7188
- Promise.resolve(choicesLoader({ config: input.provider.config, credentialStatus })),
7189
- timeoutMs
7190
- );
7191
- const entries = Object.entries(raw);
7192
- if (entries.length > maxFields) {
7193
- throw new Error("too many fields");
7194
- }
7195
- const fields = input.provider.definition.options?.fields ?? {};
7196
- const bounded = {};
7197
- for (const [fieldId, choices] of entries) {
7198
- if (!(fieldId in fields) || !Array.isArray(choices) || choices.length > maxChoices) {
7199
- throw new Error("invalid field choices");
7200
- }
7201
- bounded[fieldId] = choices.map((choice) => {
7202
- if (typeof choice?.value !== "string" || typeof choice?.label !== "string" || choice.value.length > maxTextLength || choice.label.length > maxTextLength) {
7203
- throw new Error("invalid choice");
7204
- }
7205
- return { value: choice.value, label: choice.label };
7206
- });
7207
- }
7208
- return { ok: true, choices: bounded };
7209
- } catch (error) {
7210
- return {
7211
- ok: false,
7212
- safeReason: error instanceof Error && error.message === "timeout" ? "Provider option choices timed out" : "Provider option choices are temporarily unavailable"
7213
- };
7214
- }
7215
- }
7216
-
7217
6992
  // src/model-providers/registry.ts
7218
6993
  import { toErrorMessage as errorMessage } from "@leitwerk-dev/domain";
7219
6994
  var defaultModelProviderCredentialStatus = (provider) => provider.definition.credential ? { available: false, revision: null } : { available: true, revision: null };
@@ -7415,414 +7190,6 @@ async function createModelProviderServerAdapterRegistry(input) {
7415
7190
  };
7416
7191
  }
7417
7192
 
7418
- // src/pi-resources/assemble.ts
7419
- import { lstat, realpath } from "node:fs/promises";
7420
- import path2 from "node:path";
7421
- import {
7422
- canonicalizeJson,
7423
- canonicalJsonStringify,
7424
- createCanonicalPiResourceBundle,
7425
- PI_RESOURCE_SNAPSHOT_SCHEMA_VERSION,
7426
- sha256Digest,
7427
- validateResourceRelativePath
7428
- } from "@leitwerk-dev/worker-protocol";
7429
- import { build } from "esbuild";
7430
- import {
7431
- PI_RESOURCE_SNAPSHOT_SCHEMA_VERSION as PI_RESOURCE_SNAPSHOT_SCHEMA_VERSION2
7432
- } from "@leitwerk-dev/worker-protocol";
7433
- function jsonBytes(value, location) {
7434
- return Buffer.from(`${canonicalJsonStringify(value, location)}
7435
- `, "utf8");
7436
- }
7437
- var FORBIDDEN_SECRET_KEYS = /* @__PURE__ */ new Set([
7438
- "apikey",
7439
- "accesstoken",
7440
- "refreshtoken",
7441
- "brokertoken",
7442
- "clientsecret",
7443
- "privatekey",
7444
- "password",
7445
- "secret",
7446
- "authorization"
7447
- ]);
7448
- function assertNoCredentialFields(value, location) {
7449
- if (Array.isArray(value)) {
7450
- value.forEach((item, index) => {
7451
- assertNoCredentialFields(item, `${location}[${index}]`);
7452
- });
7453
- return;
7454
- }
7455
- if (typeof value !== "object" || value === null) return;
7456
- for (const [key, nested] of Object.entries(value)) {
7457
- const normalizedKey = key.toLowerCase().replaceAll(/[^a-z0-9]/g, "");
7458
- if (FORBIDDEN_SECRET_KEYS.has(normalizedKey)) {
7459
- throw new Error(
7460
- `${location}.${key} is credential-bearing and cannot enter a Pi resource snapshot`
7461
- );
7462
- }
7463
- assertNoCredentialFields(nested, `${location}.${key}`);
7464
- }
7465
- }
7466
- function safeExtensionSegment(ownerExtensionId) {
7467
- const normalized = ownerExtensionId.normalize("NFKD").replaceAll(/[^A-Za-z0-9._-]+/g, "-").replaceAll(/^-+|-+$/g, "") || "extension";
7468
- if (Buffer.byteLength(normalized, "utf8") <= 56) return normalized;
7469
- return `${normalized.slice(0, 43)}-${sha256Digest(Buffer.from(ownerExtensionId)).slice(0, 12)}`;
7470
- }
7471
- function extensionSnapshotPath(contribution, index) {
7472
- const prefix = String(index * 10).padStart(3, "0");
7473
- return validateResourceRelativePath(
7474
- `extensions/${prefix}-${safeExtensionSegment(contribution.ownerExtensionId)}.js`
7475
- );
7476
- }
7477
- var PI_CORE_EXTERNALS = ["@earendil-works/pi-ai", "@earendil-works/pi-coding-agent"];
7478
- async function buildPiExtensionWrapper(entryPath) {
7479
- const result = await build({
7480
- absWorkingDir: path2.dirname(entryPath),
7481
- bundle: true,
7482
- stdin: {
7483
- contents: `
7484
- import contribution from ${JSON.stringify(entryPath)};
7485
- import { readFileSync } from "node:fs";
7486
-
7487
- function readGenerated() {
7488
- return JSON.parse(readFileSync(new URL("../generated.json", import.meta.url), "utf8"));
7489
- }
7490
-
7491
- function credentialBag(generated) {
7492
- let values;
7493
- const load = () => {
7494
- if (values) return values;
7495
- values = {};
7496
- for (const credentialPath of generated.declaredCredentialPaths) {
7497
- if (typeof credentialPath !== "string" || credentialPath.startsWith("/") || credentialPath.includes("..") || credentialPath.includes("\\\\")) {
7498
- throw new Error("Invalid declared Pi credential path");
7499
- }
7500
- const credential = JSON.parse(readFileSync(new URL("../" + credentialPath, import.meta.url), "utf8"));
7501
- if (credential && typeof credential === "object" && !Array.isArray(credential)) Object.assign(values, credential);
7502
- }
7503
- return values;
7504
- };
7505
- return {
7506
- get(key) { const value = load()[key]; return typeof value === "string" ? value : undefined; },
7507
- require(key) { const value = this.get(key); if (value === undefined) throw new Error("Required Pi worker secret '" + key + "' is unavailable"); return value; },
7508
- keys() { return Object.keys(load()).filter((key) => typeof load()[key] === "string").sort(); },
7509
- };
7510
- }
7511
-
7512
- export default async function leitwerkPiExtension(pi) {
7513
- if (typeof contribution !== "function") throw new Error("Leitwerk Pi worker entry must default-export a function");
7514
- const generated = readGenerated();
7515
- const workerConfig = generated.providerWorkerConfig === null ? null : generated.providerWorkerConfig?.value;
7516
- const report = (event) => {
7517
- if (!event || typeof event !== "object" || Array.isArray(event)) throw new Error("Pi worker report must be an object");
7518
- pi.events?.emit?.("leitwerk:provider-report", event);
7519
- };
7520
- await contribution(pi, {
7521
- model: { providerId: generated.model.providerId, modelId: generated.model.modelId },
7522
- options: { ...generated.providerOptions },
7523
- workerConfig,
7524
- secrets: credentialBag(generated),
7525
- report,
7526
- });
7527
- }
7528
- `,
7529
- resolveDir: path2.dirname(entryPath),
7530
- sourcefile: "leitwerk-pi-wrapper.js"
7531
- },
7532
- format: "esm",
7533
- platform: "node",
7534
- target: "node22",
7535
- write: false,
7536
- minify: true,
7537
- sourcemap: false,
7538
- legalComments: "none",
7539
- external: PI_CORE_EXTERNALS
7540
- });
7541
- const output = result.outputFiles[0];
7542
- if (!output) throw new Error(`Pi extension wrapper did not produce output for '${entryPath}'`);
7543
- return output.contents;
7544
- }
7545
- function normalizeCredentialPaths(paths) {
7546
- const seen = /* @__PURE__ */ new Set();
7547
- const normalized = paths.map((credentialPath) => {
7548
- const result = validateResourceRelativePath(credentialPath);
7549
- if (seen.has(result)) throw new Error(`Duplicate declared credential path '${result}'`);
7550
- seen.add(result);
7551
- return result;
7552
- });
7553
- return normalized.sort(compareResourcePaths);
7554
- }
7555
- function assertCredentialPathsDoNotOverlap(credentialPaths, immutablePaths) {
7556
- const files = [...immutablePaths];
7557
- for (const credentialPath of credentialPaths) {
7558
- for (const immutablePath of files) {
7559
- if (credentialPath === immutablePath || credentialPath.startsWith(`${immutablePath}/`) || immutablePath.startsWith(`${credentialPath}/`)) {
7560
- throw new Error(
7561
- `Declared credential path '${credentialPath}' overlaps immutable resource '${immutablePath}'`
7562
- );
7563
- }
7564
- }
7565
- }
7566
- }
7567
- function requireNonEmptyString(value, location) {
7568
- if (typeof value !== "string" || value.trim() === "") {
7569
- throw new Error(`${location} must be a non-empty string`);
7570
- }
7571
- }
7572
- function validateAssemblyInput(input) {
7573
- requireNonEmptyString(input.model.profileId, "model.profileId");
7574
- requireNonEmptyString(input.model.providerId, "model.providerId");
7575
- requireNonEmptyString(input.model.modelId, "model.modelId");
7576
- requireNonEmptyString(input.model.thinkingLevel, "model.thinkingLevel");
7577
- requireNonEmptyString(input.compatibility.workerApiVersion, "compatibility.workerApiVersion");
7578
- requireNonEmptyString(input.compatibility.piVersion, "compatibility.piVersion");
7579
- if (input.compatibility.protocolVersion !== void 0) {
7580
- requireNonEmptyString(input.compatibility.protocolVersion, "compatibility.protocolVersion");
7581
- }
7582
- for (const [fieldId, value] of Object.entries(input.providerOptions)) {
7583
- if (fieldId.trim() === "" || typeof value !== "string") {
7584
- throw new Error("providerOptions must contain non-empty field ids and string values");
7585
- }
7586
- }
7587
- if (input.providerWorkerConfig && (!Number.isSafeInteger(input.providerWorkerConfig.version) || input.providerWorkerConfig.version < 1)) {
7588
- throw new Error("providerWorkerConfig.version must be a positive safe integer");
7589
- }
7590
- if (input.systemPrompt !== void 0 && input.systemPrompt !== null) {
7591
- if (typeof input.systemPrompt !== "string") throw new Error("systemPrompt must be a string");
7592
- }
7593
- if (input.appendSystemPrompt !== void 0 && input.appendSystemPrompt !== null) {
7594
- if (typeof input.appendSystemPrompt !== "string") {
7595
- throw new Error("appendSystemPrompt must be a string");
7596
- }
7597
- }
7598
- }
7599
- async function assemblePiResourceSnapshot(input) {
7600
- validateAssemblyInput(input);
7601
- assertNoCredentialFields(input.piSettings, "piSettings");
7602
- assertNoCredentialFields(input.piModels ?? {}, "piModels");
7603
- assertNoCredentialFields(input.providerOptions, "providerOptions");
7604
- assertNoCredentialFields(input.providerWorkerConfig?.value ?? {}, "providerWorkerConfig.value");
7605
- const collector = new ResourceCollector(input.limits);
7606
- const seenOwners = /* @__PURE__ */ new Set();
7607
- const workerSourceIdentities = /* @__PURE__ */ new Map();
7608
- const workerSourceRealPaths = /* @__PURE__ */ new Map();
7609
- const settings = { ...input.piSettings, packages: [], defaultProjectTrust: "never" };
7610
- collector.addBytes("settings.json", jsonBytes(settings, "settings.json"));
7611
- collector.addBytes("models.json", jsonBytes(input.piModels ?? { providers: {} }, "models.json"));
7612
- if (input.systemPrompt !== void 0 && input.systemPrompt !== null) {
7613
- collector.addBytes("SYSTEM.md", Buffer.from(input.systemPrompt, "utf8"));
7614
- }
7615
- if (input.appendSystemPrompt !== void 0 && input.appendSystemPrompt !== null) {
7616
- collector.addBytes("APPEND_SYSTEM.md", Buffer.from(input.appendSystemPrompt, "utf8"));
7617
- }
7618
- for (const layer of input.resourceLayers ?? []) collector.addBundle(layer.bundle, layer.owner);
7619
- for (const [index, contribution] of input.piContributions.entries()) {
7620
- if (seenOwners.has(contribution.ownerExtensionId)) {
7621
- throw new Error(
7622
- `Extension '${contribution.ownerExtensionId}' appears more than once in Pi contributions`
7623
- );
7624
- }
7625
- seenOwners.add(contribution.ownerExtensionId);
7626
- const baseOwner = {
7627
- ownerExtensionId: contribution.ownerExtensionId,
7628
- packageName: contribution.packageName
7629
- };
7630
- if (contribution.workerEntryPath) {
7631
- validatePhysicalSourcePath(contribution.workerEntryPath);
7632
- const source = await lstat(contribution.workerEntryPath);
7633
- if (source.isSymbolicLink() || !source.isFile()) {
7634
- throw new Error(
7635
- `Pi resource source must be a regular file: ${contribution.workerEntryPath}`
7636
- );
7637
- }
7638
- const identity = `${source.dev}:${source.ino}`;
7639
- const physicalPath = await realpath(contribution.workerEntryPath);
7640
- const first = workerSourceIdentities.get(identity) ?? workerSourceRealPaths.get(physicalPath);
7641
- if (first) {
7642
- throw new Error(
7643
- `Physical Pi resource file is included more than once: ${contribution.workerEntryPath} (first: ${first})`
7644
- );
7645
- }
7646
- workerSourceIdentities.set(identity, contribution.workerEntryPath);
7647
- workerSourceRealPaths.set(physicalPath, contribution.workerEntryPath);
7648
- const snapshotPath = extensionSnapshotPath(contribution, index);
7649
- collector.addBytes(
7650
- snapshotPath,
7651
- await buildPiExtensionWrapper(contribution.workerEntryPath),
7652
- { kind: "extension", ...baseOwner }
7653
- );
7654
- }
7655
- for (const skillDirectory of contribution.resources.skillDirectories) {
7656
- await collector.addDirectory(skillDirectory, "skills", { kind: "skill", ...baseOwner });
7657
- }
7658
- for (const promptDirectory of contribution.resources.promptDirectories) {
7659
- await collector.addDirectory(promptDirectory, "prompts", { kind: "prompt", ...baseOwner });
7660
- }
7661
- }
7662
- const credentialPaths = normalizeCredentialPaths(input.declaredCredentialPaths);
7663
- assertCredentialPathsDoNotOverlap(credentialPaths, [...collector.files.keys(), "generated.json"]);
7664
- const provenance = collector.provenance.slice().sort((left, right) => compareResourcePaths(left.snapshotPath, right.snapshotPath));
7665
- const generated = {
7666
- schemaVersion: PI_RESOURCE_SNAPSHOT_SCHEMA_VERSION,
7667
- model: { ...input.model },
7668
- providerOptions: { ...input.providerOptions },
7669
- providerWorkerConfig: input.providerWorkerConfig ? {
7670
- version: input.providerWorkerConfig.version,
7671
- value: canonicalizeJson(
7672
- input.providerWorkerConfig.value,
7673
- "providerWorkerConfig.value"
7674
- )
7675
- } : null,
7676
- declaredCredentialPaths: credentialPaths,
7677
- compatibility: { ...input.compatibility },
7678
- provenance
7679
- };
7680
- collector.addBytes("generated.json", jsonBytes(generated, "generated.json"));
7681
- const resourceFiles = collector.toResourceFiles();
7682
- const bundle = createCanonicalPiResourceBundle(resourceFiles);
7683
- return {
7684
- bundle,
7685
- generated,
7686
- files: collector.provenance.map(({ snapshotPath, sha256, size }) => ({ path: snapshotPath, sha256, size })).sort((left, right) => compareResourcePaths(left.path, right.path))
7687
- };
7688
- }
7689
-
7690
- // src/pi-resources/bundle-cache.ts
7691
- import { sha256Digest as sha256Digest2 } from "@leitwerk-dev/worker-protocol";
7692
- var DEFAULT_MAX_ENTRIES = 64;
7693
- var DEFAULT_MAX_BYTES = 256 * 1024 * 1024;
7694
- function createPiResourceBundleCache(options = {}) {
7695
- const maxEntries = positiveBound(options.maxEntries, DEFAULT_MAX_ENTRIES, "maxEntries");
7696
- const maxBytes = positiveBound(options.maxBytes, DEFAULT_MAX_BYTES, "maxBytes");
7697
- const entries = /* @__PURE__ */ new Map();
7698
- let totalBytes = 0;
7699
- function touch(entry) {
7700
- entries.delete(entry.digest);
7701
- entries.set(entry.digest, entry);
7702
- }
7703
- function oldestUnpinned(excluding) {
7704
- for (const entry of entries.values()) {
7705
- if (entry.digest !== excluding && entry.pins === 0) return entry;
7706
- }
7707
- return null;
7708
- }
7709
- function remove(entry) {
7710
- if (!entries.delete(entry.digest)) return;
7711
- totalBytes -= entry.bytes.byteLength;
7712
- }
7713
- function enforceBounds(newDigest) {
7714
- while (entries.size > maxEntries || totalBytes > maxBytes) {
7715
- const candidate = oldestUnpinned(newDigest);
7716
- if (!candidate) {
7717
- const inserted = entries.get(newDigest);
7718
- if (inserted?.pins === 0) remove(inserted);
7719
- throw new Error("Pi resource bundle cache capacity is exhausted by pinned bundles");
7720
- }
7721
- remove(candidate);
7722
- }
7723
- }
7724
- return {
7725
- put(bundle) {
7726
- if (typeof bundle.digest !== "string" || sha256Digest2(bundle.bytes) !== bundle.digest) {
7727
- throw new Error("Pi resource bundle digest does not match its bytes");
7728
- }
7729
- if (bundle.bytes.byteLength > maxBytes) {
7730
- throw new Error(
7731
- `Pi resource bundle size ${bundle.bytes.byteLength} exceeds cache byte limit ${maxBytes}`
7732
- );
7733
- }
7734
- const existing = entries.get(bundle.digest);
7735
- if (existing) {
7736
- touch(existing);
7737
- return;
7738
- }
7739
- const bytes = Uint8Array.from(bundle.bytes);
7740
- const entry = {
7741
- digest: bundle.digest,
7742
- bytes,
7743
- pins: 0
7744
- };
7745
- entries.set(entry.digest, entry);
7746
- totalBytes += entry.bytes.byteLength;
7747
- enforceBounds(entry.digest);
7748
- },
7749
- get(digest) {
7750
- const entry = entries.get(digest);
7751
- if (!entry) return null;
7752
- touch(entry);
7753
- return { digest: entry.digest, bytes: Uint8Array.from(entry.bytes) };
7754
- },
7755
- has: (digest) => entries.has(digest),
7756
- pin(digest) {
7757
- const entry = entries.get(digest);
7758
- if (!entry) return false;
7759
- entry.pins += 1;
7760
- touch(entry);
7761
- return true;
7762
- },
7763
- unpin(digest) {
7764
- const entry = entries.get(digest);
7765
- if (!entry || entry.pins === 0) return false;
7766
- entry.pins -= 1;
7767
- touch(entry);
7768
- return true;
7769
- },
7770
- gc() {
7771
- const removed = [...entries.values()].filter((entry) => entry.pins === 0);
7772
- let removedBytes = 0;
7773
- for (const entry of removed) {
7774
- removedBytes += entry.bytes.byteLength;
7775
- remove(entry);
7776
- }
7777
- return {
7778
- removedDigests: removed.map((entry) => entry.digest),
7779
- removedBytes
7780
- };
7781
- },
7782
- stats() {
7783
- const values = [...entries.values()];
7784
- return {
7785
- entries: entries.size,
7786
- bytes: totalBytes,
7787
- pinnedEntries: values.filter((entry) => entry.pins > 0).length,
7788
- pins: values.reduce((total, entry) => total + entry.pins, 0)
7789
- };
7790
- }
7791
- };
7792
- }
7793
-
7794
- // src/pi-resources/bundle-pin-lifecycle.ts
7795
- function pinnedDigest(process2, turnStarts, turnRecords) {
7796
- if (process2.currentExecution?.kind !== "worker_start") return null;
7797
- const start = turnStarts.getById(process2.currentExecution.id);
7798
- if (!start || start.instanceId !== process2.id || start.turnType !== "llm") return null;
7799
- if (start.state.kind !== "starting" && start.state.kind !== "accepted") return null;
7800
- if (start.state.start.kind !== "llm") return null;
7801
- return start.state.kind === "starting" || turnRecords.getById(start.state.turnRecordId)?.status === "running" ? start.state.start.piResourceSnapshotDigest : null;
7802
- }
7803
- function createPiResourceBundlePinReconciler(deps) {
7804
- const pinnedByInstance = /* @__PURE__ */ new Map();
7805
- return {
7806
- reconcile(process2) {
7807
- const next = pinnedDigest(process2, deps.turnStarts, deps.turnRecords);
7808
- const previous = pinnedByInstance.get(process2.id) ?? null;
7809
- if (previous === next) {
7810
- return { missingDigest: next && !deps.bundleCache.has(next) ? next : null };
7811
- }
7812
- if (previous) deps.bundleCache.unpin(previous);
7813
- pinnedByInstance.delete(process2.id);
7814
- if (!next) {
7815
- return { missingDigest: null };
7816
- }
7817
- if (!deps.bundleCache.pin(next)) {
7818
- return { missingDigest: next };
7819
- }
7820
- pinnedByInstance.set(process2.id, next);
7821
- return { missingDigest: null };
7822
- }
7823
- };
7824
- }
7825
-
7826
7193
  // src/process-deletion-service.ts
7827
7194
  var TERMINAL_STATUSES2 = /* @__PURE__ */ new Set(["completed", "aborted"]);
7828
7195
  var CLEANUP_FAILURE_MESSAGE = "The process could not be deleted; retry deletion";
@@ -8046,7 +7413,7 @@ var AbortProcess = defineOperation({
8046
7413
  });
8047
7414
 
8048
7415
  // src/process-engine/ops/abort-turn.ts
8049
- import { SYSTEM_ACTOR as SYSTEM_ACTOR4 } from "@leitwerk-dev/domain";
7416
+ import { SYSTEM_ACTOR as SYSTEM_ACTOR3 } from "@leitwerk-dev/domain";
8050
7417
  var AbortTurn = defineOperation({
8051
7418
  kind: "abort_turn",
8052
7419
  label: "Abort running turn",
@@ -8072,7 +7439,7 @@ var AbortTurn = defineOperation({
8072
7439
  if (!supervisor.getWorker(ctx.process.id)) {
8073
7440
  return reject("worker_unavailable", "No active worker is available to stop this turn");
8074
7441
  }
8075
- const actor = input.actor ?? SYSTEM_ACTOR4;
7442
+ const actor = input.actor ?? SYSTEM_ACTOR3;
8076
7443
  const writes = createWrites({ workerIntent: { kind: "abort_turn", reason: input.reason } });
8077
7444
  appendProcessEvent(writes, ctx.process, {
8078
7445
  eventType: "turn_abort_requested",
@@ -8226,7 +7593,7 @@ function readCurrentPrimaryPathLeafEntryId(stateJson) {
8226
7593
 
8227
7594
  // src/process-engine/writes/build-continue-failed-turn-writes.ts
8228
7595
  import {
8229
- CONTINUE_PROMPT_METADATA_KEY as CONTINUE_PROMPT_METADATA_KEY2,
7596
+ CONTINUE_PROMPT_METADATA_KEY,
8230
7597
  inferTerminalRecordingFailedTurnRecoveryContext,
8231
7598
  normalizeContinuePrompt,
8232
7599
  readFailedTurnRecoveryContext
@@ -8287,7 +7654,7 @@ function buildContinueFailedTurnWrites(input) {
8287
7654
  if (!failedTurnRecovery) {
8288
7655
  throw new Error(`Failed turn '${failedRun.id}' is missing recovery context`);
8289
7656
  }
8290
- const continuePrompt = normalizeContinuePrompt(input.prompt) ?? normalizeContinuePrompt(process2.metadata?.[CONTINUE_PROMPT_METADATA_KEY2]) ?? failedTurnRecovery.suggestedContinuePrompt;
7657
+ const continuePrompt = normalizeContinuePrompt(input.prompt) ?? normalizeContinuePrompt(process2.metadata?.[CONTINUE_PROMPT_METADATA_KEY]) ?? failedTurnRecovery.suggestedContinuePrompt;
8291
7658
  const currentPrimaryPathLeafEntryId = readCurrentPrimaryPathLeafEntryId(process2.stateJson);
8292
7659
  const plan = buildRecoveryStartWrites(input, {
8293
7660
  startKind: "continue",
@@ -8301,7 +7668,7 @@ function buildContinueFailedTurnWrites(input) {
8301
7668
  updateProcessMetadata(plan, process2, ["retry"], (metadata) => {
8302
7669
  metadata.continueFromTurnRecordId = failedRun.id;
8303
7670
  metadata.continueFromPiEntryId = continueFromPiEntryId;
8304
- metadata[CONTINUE_PROMPT_METADATA_KEY2] = continuePrompt;
7671
+ metadata[CONTINUE_PROMPT_METADATA_KEY] = continuePrompt;
8305
7672
  if (failedRun.pathType !== "primary" && currentPrimaryPathLeafEntryId && currentPrimaryPathLeafEntryId !== continueFromPiEntryId) {
8306
7673
  metadata.continueSavedPrimaryLeafEntryId = currentPrimaryPathLeafEntryId;
8307
7674
  } else {
@@ -8503,7 +7870,7 @@ var ParkDeferredProcessActivationFailure = defineOperation({
8503
7870
  });
8504
7871
 
8505
7872
  // src/process-engine/ops/execute-action.ts
8506
- import { isProcessTurnType, SYSTEM_ACTOR as SYSTEM_ACTOR5 } from "@leitwerk-dev/domain";
7873
+ import { isProcessTurnType, SYSTEM_ACTOR as SYSTEM_ACTOR4 } from "@leitwerk-dev/domain";
8507
7874
  import {
8508
7875
  isLlmTurnDefinition as isLlmTurnDefinition2
8509
7876
  } from "@leitwerk-dev/process-sdk";
@@ -8619,7 +7986,7 @@ var ExecuteAction = defineOperation({
8619
7986
  async decide(ctx, input) {
8620
7987
  const actionSource = input.opts?.source ?? "ui";
8621
7988
  const actionOrigin = input.opts?.origin ?? DEFAULT_ACTION_ORIGIN_BY_SOURCE[actionSource];
8622
- const actor = input.opts?.actor ?? SYSTEM_ACTOR5;
7989
+ const actor = input.opts?.actor ?? SYSTEM_ACTOR4;
8623
7990
  const scheduledAction = ctx.deps.futureExecutions.getScheduledActionByInstance(
8624
7991
  input.instanceId
8625
7992
  );
@@ -9609,17 +8976,17 @@ async function buildTurnOutcomeWrites(input) {
9609
8976
  return effectWrites;
9610
8977
  }
9611
8978
  let writes = mergeWrites(baseWrites, effectWrites);
9612
- let candidateProcess2 = { ...input.process, ...writes.processPatch };
9613
- if (candidateProcess2.selectedTurnId === input.payload.turnId && candidateProcess2.lifecycleStatus === "active" && !hasExplicitTurnSelectionChange(input.process, effectWrites)) {
8979
+ let candidateProcess = { ...input.process, ...writes.processPatch };
8980
+ if (candidateProcess.selectedTurnId === input.payload.turnId && candidateProcess.lifecycleStatus === "active" && !hasExplicitTurnSelectionChange(input.process, effectWrites)) {
9614
8981
  const outcomeTransition = findOutcomeTransition(
9615
8982
  input.processGraphs,
9616
- candidateProcess2.processId,
8983
+ candidateProcess.processId,
9617
8984
  input.payload.turnId,
9618
8985
  input.payload.outcome
9619
8986
  );
9620
8987
  if (outcomeTransition) {
9621
- const transitionWrites = buildTurnSelectionWrites(input.processGraphs, candidateProcess2, {
9622
- fromTurnId: candidateProcess2.selectedTurnId,
8988
+ const transitionWrites = buildTurnSelectionWrites(input.processGraphs, candidateProcess, {
8989
+ fromTurnId: candidateProcess.selectedTurnId,
9623
8990
  toTurnId: outcomeTransition.toTurnId,
9624
8991
  ...outcomeTransition.lifecycleStatus !== void 0 ? { lifecycleStatus: outcomeTransition.lifecycleStatus } : {},
9625
8992
  state: void 0
@@ -9628,7 +8995,7 @@ async function buildTurnOutcomeWrites(input) {
9628
8995
  return transitionWrites;
9629
8996
  }
9630
8997
  writes = mergeWrites(writes, transitionWrites);
9631
- candidateProcess2 = { ...candidateProcess2, ...transitionWrites.processPatch };
8998
+ candidateProcess = { ...candidateProcess, ...transitionWrites.processPatch };
9632
8999
  }
9633
9000
  }
9634
9001
  writes.extensionEvents.push(
@@ -9927,9 +9294,9 @@ var TurnOutcome = defineOperation({
9927
9294
  if (ctx.process.lifecycleStatus === "error") {
9928
9295
  applyProcessPatchField(baseWrites, ctx.process, "lifecycleStatus", "active");
9929
9296
  }
9930
- const candidateProcess2 = { ...ctx.process, ...baseWrites.processPatch };
9297
+ const candidateProcess = { ...ctx.process, ...baseWrites.processPatch };
9931
9298
  const outcomeWrites = await buildTurnOutcomeWrites({
9932
- process: candidateProcess2,
9299
+ process: candidateProcess,
9933
9300
  projects,
9934
9301
  payload,
9935
9302
  turnRecords: ctx.deps.turnRecords,
@@ -10565,23 +9932,23 @@ function buildRecordedDecision(input) {
10565
9932
  async function record2(deps, operation, input, initialProcess, decision) {
10566
9933
  const baselineWrites = structuredClone(decision.writes);
10567
9934
  const runModelPreparation = async (availability) => {
10568
- const candidateProcess2 = {
9935
+ const candidateProcess = {
10569
9936
  ...initialProcess,
10570
9937
  ...decision.writes.processPatch
10571
9938
  };
10572
9939
  const createdStart = decision.writes.turnStartWrites.find(
10573
9940
  (write) => write.kind === "create" && write.input.turnType === "llm"
10574
9941
  );
10575
- const shouldResolveSelection = !!candidateProcess2.selectedTurnId && (!!createdStart || candidateProcess2.selectedTurnId !== initialProcess.selectedTurnId || candidateProcess2.lifecycleStatus === "active" && initialProcess.lifecycleStatus !== "active" || Object.hasOwn(decision.metadata ?? {}, "nextTurnModelProfileId"));
10576
- if (!candidateProcess2.selectedTurnId) {
9942
+ const shouldResolveSelection = !!candidateProcess.selectedTurnId && (!!createdStart || candidateProcess.selectedTurnId !== initialProcess.selectedTurnId || candidateProcess.lifecycleStatus === "active" && initialProcess.lifecycleStatus !== "active" || Object.hasOwn(decision.metadata ?? {}, "nextTurnModelProfileId"));
9943
+ if (!candidateProcess.selectedTurnId) {
10577
9944
  applyProcessPatchField(decision.writes, initialProcess, "selectedTurnModelProfileId", null);
10578
9945
  applyProcessPatchField(decision.writes, initialProcess, "selectedTurnModelKind", null);
10579
9946
  applyProcessPatchField(decision.writes, initialProcess, "selectedTurnModelSource", null);
10580
- } else if (shouldResolveSelection && candidateProcess2.selectedTurnId) {
9947
+ } else if (shouldResolveSelection && candidateProcess.selectedTurnId) {
10581
9948
  const resolution = deps.processModelPolicy.evaluate({
10582
9949
  kind: "process_turn",
10583
- process: candidateProcess2,
10584
- turnId: candidateProcess2.selectedTurnId,
9950
+ process: candidateProcess,
9951
+ turnId: candidateProcess.selectedTurnId,
10585
9952
  availability,
10586
9953
  startKind: createdStart?.input.startKind,
10587
9954
  initialSelection: createdStart?.input.startKind === "selected_turn" && initialProcess.selectedTurnId === null && initialProcess.lifecycleStatus === "discovered" && initialProcess.planRevision === 0,
@@ -10590,7 +9957,7 @@ async function record2(deps, operation, input, initialProcess, decision) {
10590
9957
  if (!resolution.ok && resolution.code !== "model_unavailable" && resolution.code !== "model_stale" && resolution.code !== "model_required") {
10591
9958
  const message = presentProcessModelPolicyFailure(resolution);
10592
9959
  if (createdStart) {
10593
- parkInvalidModelConfiguration(decision.writes, createdStart, candidateProcess2, message);
9960
+ parkInvalidModelConfiguration(decision.writes, createdStart, candidateProcess, message);
10594
9961
  return { ok: true };
10595
9962
  }
10596
9963
  return {
@@ -10730,27 +10097,27 @@ function resolveMessages(operation, input) {
10730
10097
  function shouldReportBestEffortFailures(operation, input) {
10731
10098
  return typeof operation.reportBestEffortFailures === "function" ? operation.reportBestEffortFailures(input) : operation.reportBestEffortFailures === true;
10732
10099
  }
10733
- function mapPreCommitFailure(failure2, initialProcess) {
10100
+ function mapPreCommitFailure(failure, initialProcess) {
10734
10101
  return {
10735
10102
  ok: false,
10736
- code: failure2.code,
10103
+ code: failure.code,
10737
10104
  message: publicEngineFailureMessage({
10738
- code: failure2.code,
10739
- message: failure2.message,
10105
+ code: failure.code,
10106
+ message: failure.message,
10740
10107
  stage: "pre_commit"
10741
10108
  }),
10742
10109
  ...initialProcess ? { process: initialProcess } : {},
10743
- ...failure2.data !== void 0 ? { data: failure2.data } : {},
10110
+ ...failure.data !== void 0 ? { data: failure.data } : {},
10744
10111
  stage: "pre_commit"
10745
10112
  };
10746
10113
  }
10747
- function mapPostCommitFailure(recorded, failure2) {
10114
+ function mapPostCommitFailure(recorded, failure) {
10748
10115
  return {
10749
10116
  ok: false,
10750
- code: failure2.code,
10117
+ code: failure.code,
10751
10118
  message: publicEngineFailureMessage({
10752
- code: failure2.code,
10753
- message: failure2.message,
10119
+ code: failure.code,
10120
+ message: failure.message,
10754
10121
  stage: "post_commit"
10755
10122
  }),
10756
10123
  process: recorded.process,
@@ -10996,8 +10363,8 @@ function createProcessEngine(deps) {
10996
10363
  activateDeferredProcess(instanceId, prepared) {
10997
10364
  return run(ActivateDeferredProcess, { instanceId, prepared });
10998
10365
  },
10999
- parkDeferredProcessActivationFailure(instanceId, failure2) {
11000
- return run(ParkDeferredProcessActivationFailure, { instanceId, failure: failure2 });
10366
+ parkDeferredProcessActivationFailure(instanceId, failure) {
10367
+ return run(ParkDeferredProcessActivationFailure, { instanceId, failure });
11001
10368
  },
11002
10369
  startProcess(instanceId, startTurnId, opts) {
11003
10370
  return run(StartProcess, { instanceId, startTurnId, actor: opts?.actor });
@@ -11363,309 +10730,6 @@ async function reconcileProcessesOnStartup(deps) {
11363
10730
  );
11364
10731
  }
11365
10732
 
11366
- // src/process-engine/turn-start-preflight.ts
11367
- import { filterProviderOptionsForDefinition } from "@leitwerk-dev/process-sdk";
11368
- import { IPC_PROTOCOL_VERSION, WORKER_API_VERSION } from "@leitwerk-dev/worker-protocol";
11369
-
11370
- // src/worker-runtime-profile-selection.ts
11371
- function trimToUndefined(value) {
11372
- if (typeof value !== "string") {
11373
- return void 0;
11374
- }
11375
- const trimmed = value.trim();
11376
- return trimmed.length > 0 ? trimmed : void 0;
11377
- }
11378
- function defaultWorkerRuntimeProfile(config) {
11379
- if (config.workers.runner === "local") {
11380
- return config.workers.default_runtime_profile ?? "local";
11381
- }
11382
- return (config.workers.runner === "kubernetes" ? config.kubernetes?.default_worker_runtime_profile : void 0) ?? config.workers.default_runtime_profile ?? null;
11383
- }
11384
- function selectWorkerRuntimeProfile(input) {
11385
- const override = trimToUndefined(input.processOverride);
11386
- if (override) {
11387
- return resolveProfileImage(override, input.profiles);
11388
- }
11389
- const declared = input.componentProfiles.map((entry) => ({ component: entry.component, profile: trimToUndefined(entry.profile) })).filter(
11390
- (entry) => entry.profile !== void 0
11391
- );
11392
- const distinct = new Set(declared.map((entry) => entry.profile));
11393
- if (distinct.size > 1) {
11394
- const summary = declared.map((entry) => `${entry.component}=${entry.profile}`).sort().join(", ");
11395
- return {
11396
- ok: false,
11397
- error: `Process '${input.processId}' has conflicting component worker runtime profiles (${summary}); set process_configs.${input.processId}.worker_runtime_profile to resolve`
11398
- };
11399
- }
11400
- if (distinct.size === 1) {
11401
- const [only] = distinct;
11402
- return resolveProfileImage(only, input.profiles);
11403
- }
11404
- const fallback = trimToUndefined(input.defaultProfile);
11405
- if (!fallback) {
11406
- return {
11407
- ok: false,
11408
- error: `Process '${input.processId}' selects no worker runtime profile and no default worker runtime profile is configured`
11409
- };
11410
- }
11411
- return resolveProfileImage(fallback, input.profiles);
11412
- }
11413
- function resolveProfileImage(runtimeProfile, profiles) {
11414
- const profile = profiles[runtimeProfile];
11415
- if (!profile) {
11416
- return {
11417
- ok: false,
11418
- error: `Unknown worker runtime profile '${runtimeProfile}'; configure it under worker_runtime_profiles`
11419
- };
11420
- }
11421
- return {
11422
- ok: true,
11423
- runtimeProfile,
11424
- image: { reference: profile.image }
11425
- };
11426
- }
11427
- function buildRuntimeProfileSelectionInput(args) {
11428
- const { config, processId, componentKeys } = args;
11429
- const componentProfiles = componentKeys.map((component) => ({
11430
- component,
11431
- profile: config.components[component]?.worker_runtime_profile
11432
- }));
11433
- return {
11434
- processId,
11435
- processOverride: config.process_configs?.[processId]?.worker_runtime_profile,
11436
- componentProfiles,
11437
- defaultProfile: defaultWorkerRuntimeProfile(config) ?? void 0,
11438
- profiles: config.worker_runtime_profiles ?? {}
11439
- };
11440
- }
11441
-
11442
- // src/process-engine/turn-start-preflight.ts
11443
- var PI_RUNTIME_VERSION = "0.81.1";
11444
- function failure(requestedModelProfileId, providerOptions, code, safeSummary, modelSelectionProvenance, availabilityRevision) {
11445
- return {
11446
- kind: "preparation_failed",
11447
- requestedModelProfileId,
11448
- providerOptions,
11449
- code,
11450
- safeSummary,
11451
- ...modelSelectionProvenance ? { modelSelectionProvenance } : {},
11452
- ...availabilityRevision !== void 0 ? { availabilityRevision } : {}
11453
- };
11454
- }
11455
- function previousProviderOptions(state) {
11456
- if (state.kind === "preparation_failed") return { ...state.providerOptions };
11457
- if (state.kind === "superseded" || state.kind === "starting" || state.kind === "accepted") {
11458
- return state.start?.kind === "llm" ? { ...state.start.providerOptions } : {};
11459
- }
11460
- return state.start.kind === "llm" ? { ...state.start.providerOptions } : {};
11461
- }
11462
- function previousProviderId(deps, state) {
11463
- if (state.kind !== "preparation_failed") {
11464
- return state.start?.kind === "llm" ? state.start.model.providerId : null;
11465
- }
11466
- const profileId = state.requestedModelProfileId;
11467
- return profileId ? deps.config.pi.model_profiles.find((profile) => profile.id === profileId)?.provider ?? null : null;
11468
- }
11469
- function parkPreparationFailure(writes, write, state) {
11470
- write.input.state = state;
11471
- writes.processPatch.lifecycleStatus = "error";
11472
- writes.workerIntent = { kind: "reconcile" };
11473
- }
11474
- function candidateProcess(process2, writes) {
11475
- return { ...process2, ...writes.processPatch };
11476
- }
11477
- function resolveRuntimeProfile(deps, process2) {
11478
- if (deps.config.workers.runner === "local") {
11479
- return { ok: true, id: defaultWorkerRuntimeProfile(deps.config) ?? "local" };
11480
- }
11481
- const selection = selectWorkerRuntimeProfile(
11482
- buildRuntimeProfileSelectionInput({
11483
- config: deps.config,
11484
- processId: process2.processId,
11485
- componentKeys: deps.projects.listByInstance(process2.id).map((project) => project.key)
11486
- })
11487
- );
11488
- return selection.ok ? { ok: true, id: selection.runtimeProfile } : { ok: false, message: selection.error };
11489
- }
11490
- function resolveProviderWorkerConfig(provider, options) {
11491
- if (provider.definition.worker.kind !== "extension_pi_worker") return null;
11492
- const definition = provider.definition.worker.config;
11493
- if (!definition) return null;
11494
- const projected = definition.resolve({ config: provider.config, options });
11495
- const value = definition.schema.parse(projected);
11496
- if (typeof value !== "object" || value === null || Array.isArray(value)) {
11497
- throw new Error("Provider worker configuration must be a JSON object");
11498
- }
11499
- return { version: definition.version, value };
11500
- }
11501
- function resolveProviderPiModels(provider) {
11502
- const worker = provider.definition.worker;
11503
- return worker.kind === "configured_pi_provider" ? worker.resolveModels({ config: provider.config }) : { providers: {} };
11504
- }
11505
- function buildPiSettings(config) {
11506
- return {
11507
- retry: {
11508
- enabled: config.pi.retry.enabled,
11509
- maxRetries: config.pi.retry.max_retries,
11510
- baseDelay: config.pi.retry.base_delay,
11511
- provider: {
11512
- timeout: config.pi.retry.provider.timeout,
11513
- maxRetries: config.pi.retry.provider.max_retries,
11514
- maxRetryDelay: config.pi.retry.provider.max_retry_delay
11515
- }
11516
- }
11517
- };
11518
- }
11519
- async function prepareCreatedTurnStarts(deps, process2, writes, explicitProviderOptions, availabilitySnapshot) {
11520
- const nextProcess = candidateProcess(process2, writes);
11521
- const availability = availabilitySnapshot ?? deps.modelStatusCache.snapshot();
11522
- const provenance = nextProcess.selectedTurnModelKind && nextProcess.selectedTurnModelSource ? {
11523
- kind: nextProcess.selectedTurnModelKind,
11524
- source: nextProcess.selectedTurnModelSource
11525
- } : void 0;
11526
- for (let index = 0; index < writes.turnStartWrites.length; index += 1) {
11527
- const write = writes.turnStartWrites[index];
11528
- if (!write || write.kind !== "create" || write.input.turnType !== "llm") continue;
11529
- const requestedProfileId = nextProcess.selectedTurnModelProfileId?.trim() || null;
11530
- const retainedState = write.input.state;
11531
- const retainedOptions = previousProviderOptions(retainedState);
11532
- if (retainedState.kind === "preparation_failed" && retainedState.code === "invalid_model_configuration") {
11533
- parkPreparationFailure(writes, write, retainedState);
11534
- continue;
11535
- }
11536
- if (!requestedProfileId) {
11537
- parkPreparationFailure(
11538
- writes,
11539
- write,
11540
- failure(
11541
- null,
11542
- retainedOptions,
11543
- "model_required",
11544
- "Choose a model before retrying startup",
11545
- void 0,
11546
- availability.revision
11547
- )
11548
- );
11549
- continue;
11550
- }
11551
- const profile = deps.config.pi.model_profiles.find((item) => item.id === requestedProfileId);
11552
- if (!profile) {
11553
- return {
11554
- ok: false,
11555
- code: "invalid_model_profile",
11556
- message: `Unknown model profile '${requestedProfileId}'`
11557
- };
11558
- }
11559
- const provider = deps.registry.require(profile.provider);
11560
- const retainedProviderId = previousProviderId(deps, retainedState);
11561
- const recoveryOptions = explicitProviderOptions ? { ...explicitProviderOptions } : retainedProviderId !== null && retainedProviderId !== provider.id ? {
11562
- ...filterProviderOptionsForDefinition(provider.definition.options, retainedOptions)
11563
- } : retainedOptions;
11564
- const optionResult = resolveRegisteredProviderOptions({
11565
- provider,
11566
- explicit: recoveryOptions,
11567
- profileDefaults: profile.provider_options ?? {}
11568
- });
11569
- if (!optionResult.ok) {
11570
- const onlyRequired = optionResult.issues.every((issue) => issue.code === "required");
11571
- if (!onlyRequired) {
11572
- return {
11573
- ok: false,
11574
- code: "invalid_provider_options",
11575
- message: optionResult.issues.map((issue) => issue.message).join("; ")
11576
- };
11577
- }
11578
- parkPreparationFailure(
11579
- writes,
11580
- write,
11581
- failure(
11582
- profile.id,
11583
- recoveryOptions,
11584
- "provider_options_required",
11585
- optionResult.issues.map((issue) => issue.message).join("; ")
11586
- )
11587
- );
11588
- continue;
11589
- }
11590
- const status = availability.profiles.find((candidate) => candidate.profileId === profile.id);
11591
- if (!status || status.availability !== "available") {
11592
- parkPreparationFailure(
11593
- writes,
11594
- write,
11595
- failure(
11596
- profile.id,
11597
- recoveryOptions,
11598
- !status || status.availability === "stale" ? "model_stale" : "model_unavailable",
11599
- status?.safeReason ?? "The selected model status is stale",
11600
- provenance,
11601
- availability.revision
11602
- )
11603
- );
11604
- continue;
11605
- }
11606
- try {
11607
- const runtimeProfile = resolveRuntimeProfile(deps, nextProcess);
11608
- if (!runtimeProfile.ok) throw new Error(runtimeProfile.message);
11609
- const providerWorkerConfig = resolveProviderWorkerConfig(provider, optionResult.value);
11610
- const piSettings = buildPiSettings(deps.config);
11611
- const model = {
11612
- profileId: profile.id,
11613
- providerId: profile.provider,
11614
- modelId: profile.model_id,
11615
- thinkingLevel: profile.thinking_level ?? "off"
11616
- };
11617
- const resourceLayers = deps.processSkills.listResourceLayers(nextProcess.id);
11618
- const assembled = await assemblePiResourceSnapshot({
11619
- resourceLayers,
11620
- piContributions: deps.piContributions,
11621
- model,
11622
- providerOptions: optionResult.value,
11623
- providerWorkerConfig,
11624
- piSettings,
11625
- piModels: resolveProviderPiModels(provider),
11626
- declaredCredentialPaths: [
11627
- "auth.json",
11628
- ...provider.definition.worker.kind === "extension_pi_worker" ? provider.definition.worker.credentialFiles ?? [] : []
11629
- ],
11630
- compatibility: {
11631
- workerApiVersion: WORKER_API_VERSION,
11632
- piVersion: PI_RUNTIME_VERSION,
11633
- protocolVersion: IPC_PROTOCOL_VERSION
11634
- }
11635
- });
11636
- deps.bundleCache.put(assembled.bundle);
11637
- write.input.state = {
11638
- kind: "starting",
11639
- start: {
11640
- kind: "llm",
11641
- model,
11642
- ...provenance ? { modelSelectionProvenance: provenance } : {},
11643
- availabilityRevision: availability.revision,
11644
- providerOptions: { ...optionResult.value },
11645
- providerWorkerConfig,
11646
- piResourceSnapshotDigest: assembled.bundle.digest,
11647
- workerRuntimeProfileId: runtimeProfile.id,
11648
- piSettings
11649
- }
11650
- };
11651
- writes.processPatch.lifecycleStatus = "active";
11652
- writes.workerIntent = { kind: "restart_worker" };
11653
- } catch {
11654
- parkPreparationFailure(
11655
- writes,
11656
- write,
11657
- failure(
11658
- profile.id,
11659
- { ...optionResult.value },
11660
- "provider_preflight_failed",
11661
- "The provider could not prepare this worker start"
11662
- )
11663
- );
11664
- }
11665
- }
11666
- return { ok: true };
11667
- }
11668
-
11669
10733
  // src/process-launcher-registry.ts
11670
10734
  import { buildProcessLaunchers } from "@leitwerk-dev/process-sdk";
11671
10735
 
@@ -13251,7 +12315,7 @@ var RepositoryCredentialService = class {
13251
12315
  // src/result-image-store.ts
13252
12316
  import { createHash as createHash2, randomUUID as randomUUID2 } from "node:crypto";
13253
12317
  import { mkdir, readdir, readFile as readFile2, rename, rm, writeFile } from "node:fs/promises";
13254
- import path3 from "node:path";
12318
+ import path2 from "node:path";
13255
12319
  import {
13256
12320
  isResultImageStorageSegment,
13257
12321
  parseResultImageId
@@ -13271,12 +12335,12 @@ var ResultImageStore = class {
13271
12335
  rootDir;
13272
12336
  /** @internal */
13273
12337
  constructor(input) {
13274
- this.rootDir = path3.resolve(input.rootDir);
12338
+ this.rootDir = path2.resolve(input.rootDir);
13275
12339
  }
13276
12340
  turnDir(instanceId, turnRecordId) {
13277
12341
  if (!isResultImageStorageSegment(instanceId) || !isResultImageStorageSegment(turnRecordId))
13278
12342
  throw new Error("Invalid result image storage id");
13279
- return path3.join(this.rootDir, instanceId, turnRecordId);
12343
+ return path2.join(this.rootDir, instanceId, turnRecordId);
13280
12344
  }
13281
12345
  /** @internal */
13282
12346
  async put(input) {
@@ -13284,8 +12348,8 @@ var ResultImageStore = class {
13284
12348
  await mkdir(dir, { recursive: true });
13285
12349
  const digest = createHash2("sha256").update(input.bytes).digest("hex");
13286
12350
  const imageId = `img_${digest}.${EXTENSIONS[input.mimeType]}`;
13287
- const destination = path3.join(dir, imageId);
13288
- const temporary = path3.join(dir, `.${imageId}.${randomUUID2()}.tmp`);
12351
+ const destination = path2.join(dir, imageId);
12352
+ const temporary = path2.join(dir, `.${imageId}.${randomUUID2()}.tmp`);
13289
12353
  try {
13290
12354
  await writeFile(temporary, input.bytes, { flag: "wx" });
13291
12355
  await rename(temporary, destination);
@@ -13298,7 +12362,7 @@ var ResultImageStore = class {
13298
12362
  async deleteProcess(instanceId) {
13299
12363
  if (!isResultImageStorageSegment(instanceId))
13300
12364
  throw new Error("Invalid result image storage id");
13301
- await rm(path3.join(this.rootDir, instanceId), { recursive: true, force: true });
12365
+ await rm(path2.join(this.rootDir, instanceId), { recursive: true, force: true });
13302
12366
  }
13303
12367
  /** @internal */
13304
12368
  async cleanupProcesses(input) {
@@ -13313,7 +12377,7 @@ var ResultImageStore = class {
13313
12377
  for (const entry of entries) {
13314
12378
  if (!entry.isDirectory() || !isResultImageStorageSegment(entry.name) || input.retainedInstanceIds.has(entry.name) && !input.expiredInstanceIds?.has(entry.name))
13315
12379
  continue;
13316
- await rm(path3.join(this.rootDir, entry.name), { recursive: true, force: true });
12380
+ await rm(path2.join(this.rootDir, entry.name), { recursive: true, force: true });
13317
12381
  removed.push(entry.name);
13318
12382
  }
13319
12383
  return removed;
@@ -13323,7 +12387,7 @@ var ResultImageStore = class {
13323
12387
  const extension = parseResultImageId(imageId)?.extension;
13324
12388
  if (!extension) return null;
13325
12389
  try {
13326
- const bytes = await readFile2(path3.join(this.turnDir(instanceId, turnRecordId), imageId));
12390
+ const bytes = await readFile2(path2.join(this.turnDir(instanceId, turnRecordId), imageId));
13327
12391
  return {
13328
12392
  metadata: { imageId, mimeType: MIME_BY_EXTENSION[extension], byteSize: bytes.length },
13329
12393
  bytes
@@ -13468,8 +12532,8 @@ function createAppLifecycle(input) {
13468
12532
  }
13469
12533
 
13470
12534
  // src/server-bootstrap/build-host-capabilities.ts
13471
- import path4 from "node:path";
13472
- import { SYSTEM_ACTOR as SYSTEM_ACTOR6 } from "@leitwerk-dev/domain";
12535
+ import path3 from "node:path";
12536
+ import { SYSTEM_ACTOR as SYSTEM_ACTOR5 } from "@leitwerk-dev/domain";
13473
12537
  import {
13474
12538
  coreHostCapabilities,
13475
12539
  createCapabilityAccessor
@@ -13483,7 +12547,7 @@ function buildHostCapabilities(input) {
13483
12547
  return input.config.server.base_url;
13484
12548
  },
13485
12549
  get processWorkspacesDir() {
13486
- return path4.resolve(input.config.storage.process_workspaces_dir);
12550
+ return path3.resolve(input.config.storage.process_workspaces_dir);
13487
12551
  },
13488
12552
  components: input.config.components,
13489
12553
  externalWrites: input.baseDeps.externalWrites,
@@ -13512,13 +12576,13 @@ function buildHostCapabilities(input) {
13512
12576
  startProgrammatic(request, opts) {
13513
12577
  return input.launchCoordinator.startProgrammatic(request, {
13514
12578
  idempotencyKey: opts.idempotencyKey,
13515
- actor: opts.actor ?? SYSTEM_ACTOR6
12579
+ actor: opts.actor ?? SYSTEM_ACTOR5
13516
12580
  });
13517
12581
  },
13518
12582
  startWatcher(watcher, event, opts) {
13519
12583
  return input.launchCoordinator.startWatcher(watcher, event, {
13520
12584
  idempotencyKey: opts.idempotencyKey,
13521
- actor: opts.actor ?? SYSTEM_ACTOR6
12585
+ actor: opts.actor ?? SYSTEM_ACTOR5
13522
12586
  });
13523
12587
  }
13524
12588
  },
@@ -13810,7 +12874,7 @@ function registerInternalSessionTransferExportRoutes(app, service) {
13810
12874
  // src/routes/internal-worker-session-snapshot.ts
13811
12875
  import { mkdtemp, rm as rm2, writeFile as writeFile2 } from "node:fs/promises";
13812
12876
  import { tmpdir } from "node:os";
13813
- import path5 from "node:path";
12877
+ import path4 from "node:path";
13814
12878
  import { StringDecoder } from "node:string_decoder";
13815
12879
  import {
13816
12880
  WORKER_SESSION_SNAPSHOT_CONTENT_TYPE,
@@ -13909,8 +12973,8 @@ function validateJsonLine(line, lineNumber) {
13909
12973
  }
13910
12974
  }
13911
12975
  async function streamSnapshotToTempFile(payload, bodyLimit) {
13912
- const dir = await mkdtemp(path5.join(tmpdir(), "leitwerk-session-snapshot-"));
13913
- const file = path5.join(dir, "snapshot.jsonl");
12976
+ const dir = await mkdtemp(path4.join(tmpdir(), "leitwerk-session-snapshot-"));
12977
+ const file = path4.join(dir, "snapshot.jsonl");
13914
12978
  let bytes = 0;
13915
12979
  const decoder = new StringDecoder("utf8");
13916
12980
  let pendingLine = "";
@@ -14039,7 +13103,7 @@ function registerInternalWorkerSessionSnapshotRoutes(input) {
14039
13103
  await input.sessionSnapshots.writeSnapshotFile(instanceId, body.path);
14040
13104
  reply.code(204).send();
14041
13105
  } finally {
14042
- if (body?.path) await rm2(path5.dirname(body.path), { recursive: true, force: true });
13106
+ if (body?.path) await rm2(path4.dirname(body.path), { recursive: true, force: true });
14043
13107
  }
14044
13108
  return reply;
14045
13109
  }
@@ -14405,8 +13469,8 @@ function mapEngineFailure(result, variant) {
14405
13469
  };
14406
13470
  }
14407
13471
  function sendEngineFailure(reply, result, variant) {
14408
- const failure2 = mapEngineFailure(result, variant);
14409
- return reply.code(failure2.status).send(failure2.body);
13472
+ const failure = mapEngineFailure(result, variant);
13473
+ return reply.code(failure.status).send(failure.body);
14410
13474
  }
14411
13475
 
14412
13476
  // src/routes/process-actions.ts
@@ -15912,7 +14976,7 @@ function registerHttp(input) {
15912
14976
 
15913
14977
  // src/server-topology.ts
15914
14978
  import { readFileSync } from "node:fs";
15915
- var defaultFileReader = (path10) => readFileSync(path10, "utf8");
14979
+ var defaultFileReader = (path9) => readFileSync(path9, "utf8");
15916
14980
  function resolveServerTlsOptions(config, readFile5 = defaultFileReader) {
15917
14981
  const tls = config.internal_tls;
15918
14982
  if (!tls || tls.enabled !== true) {
@@ -16087,21 +15151,21 @@ function createSessionTransferHelperRelays(deps) {
16087
15151
  import { execFile } from "node:child_process";
16088
15152
  import { mkdtemp as mkdtemp2, readdir as readdir2, readFile as readFile4, rm as rm3 } from "node:fs/promises";
16089
15153
  import { tmpdir as tmpdir2 } from "node:os";
16090
- import path6 from "node:path";
15154
+ import path5 from "node:path";
16091
15155
  import { promisify } from "node:util";
16092
15156
  import {
16093
- createCanonicalPiResourceBundle as createCanonicalPiResourceBundle2
15157
+ createCanonicalPiResourceBundle
16094
15158
  } from "@leitwerk-dev/worker-protocol";
16095
15159
  var execFileAsync = promisify(execFile);
16096
15160
  var GIT_ENV = { ...process.env, GIT_TERMINAL_PROMPT: "0", GIT_ASKPASS: "/bin/false" };
16097
15161
  var FORBIDDEN_SKILL_NAMES = /* @__PURE__ */ new Set([".git"]);
16098
15162
  function isWithin(root, candidate) {
16099
- const relative = path6.relative(root, candidate);
16100
- return relative === "" || relative !== ".." && !relative.startsWith(`..${path6.sep}`);
15163
+ const relative = path5.relative(root, candidate);
15164
+ return relative === "" || relative !== ".." && !relative.startsWith(`..${path5.sep}`);
16101
15165
  }
16102
15166
  async function importSkillDirectory(root, skill, sourceRevision) {
16103
15167
  const collector = new ResourceCollector();
16104
- await collector.addDirectory(path6.resolve(root), `skills/${skill.id}`, SKILL_RESOURCE_OWNER, {
15168
+ await collector.addDirectory(path5.resolve(root), `skills/${skill.id}`, SKILL_RESOURCE_OWNER, {
16105
15169
  forbiddenNames: FORBIDDEN_SKILL_NAMES
16106
15170
  });
16107
15171
  const files = collector.toResourceFiles();
@@ -16112,7 +15176,7 @@ async function importSkillDirectory(root, skill, sourceRevision) {
16112
15176
  skillId: skill.id,
16113
15177
  label: skill.label ?? skill.id,
16114
15178
  description: skill.description ?? null,
16115
- bundle: createCanonicalPiResourceBundle2(files),
15179
+ bundle: createCanonicalPiResourceBundle(files),
16116
15180
  sourceRevision
16117
15181
  };
16118
15182
  }
@@ -16144,14 +15208,14 @@ async function discoverSkillRoots(catalogRoot) {
16144
15208
  const entries = (await readdir2(directory, { withFileTypes: true })).sort(
16145
15209
  (left, right) => left.name.localeCompare(right.name)
16146
15210
  );
16147
- const skillId = path6.basename(directory);
15211
+ const skillId = path5.basename(directory);
16148
15212
  if (SAFE_SKILL_ID_PATTERN.test(skillId) && entries.some((entry) => entry.name === "SKILL.md" && entry.isFile())) {
16149
15213
  result.push(directory);
16150
15214
  return;
16151
15215
  }
16152
15216
  for (const entry of entries) {
16153
15217
  if (entry.isDirectory() && entry.name !== ".git") {
16154
- await visit(path6.join(directory, entry.name));
15218
+ await visit(path5.join(directory, entry.name));
16155
15219
  }
16156
15220
  }
16157
15221
  };
@@ -16159,20 +15223,20 @@ async function discoverSkillRoots(catalogRoot) {
16159
15223
  return result;
16160
15224
  }
16161
15225
  function repositorySourcePath(checkoutRoot, skillRoot) {
16162
- return path6.relative(checkoutRoot, skillRoot).split(path6.sep).join(path6.posix.sep);
15226
+ return path5.relative(checkoutRoot, skillRoot).split(path5.sep).join(path5.posix.sep);
16163
15227
  }
16164
15228
  async function importSkillRepository(repository) {
16165
- const tempRoot = await mkdtemp2(path6.join(tmpdir2(), "leitwerk-skill-repository-"));
15229
+ const tempRoot = await mkdtemp2(path5.join(tmpdir2(), "leitwerk-skill-repository-"));
16166
15230
  try {
16167
- const checkout = await checkoutGitSource(repository, path6.join(tempRoot, "checkout"));
16168
- const catalogRoot = path6.resolve(checkout.root, repository.path ?? "skills");
15231
+ const checkout = await checkoutGitSource(repository, path5.join(tempRoot, "checkout"));
15232
+ const catalogRoot = path5.resolve(checkout.root, repository.path ?? "skills");
16169
15233
  if (!isWithin(checkout.root, catalogRoot)) {
16170
15234
  throw new Error(`Skill repository '${repository.id}' path escapes its checkout`);
16171
15235
  }
16172
15236
  const skillRoots = await discoverSkillRoots(catalogRoot);
16173
15237
  const rootsById = /* @__PURE__ */ new Map();
16174
15238
  for (const skillRoot of skillRoots) {
16175
- const skillId = path6.basename(skillRoot);
15239
+ const skillId = path5.basename(skillRoot);
16176
15240
  const previous = rootsById.get(skillId);
16177
15241
  if (previous) {
16178
15242
  throw new Error(
@@ -16183,8 +15247,8 @@ async function importSkillRepository(repository) {
16183
15247
  }
16184
15248
  const skills = [];
16185
15249
  for (const skillRoot of skillRoots) {
16186
- const skillId = path6.basename(skillRoot);
16187
- const markdown = await readFile4(path6.join(skillRoot, "SKILL.md"), "utf8");
15250
+ const skillId = path5.basename(skillRoot);
15251
+ const markdown = await readFile4(path5.join(skillRoot, "SKILL.md"), "utf8");
16188
15252
  const imported = await importSkillDirectory(
16189
15253
  skillRoot,
16190
15254
  {
@@ -16279,12 +15343,12 @@ function createSkillCatalogService(input) {
16279
15343
 
16280
15344
  // src/supervisor/diagnostic-trace-writer.ts
16281
15345
  import { appendFileSync, mkdirSync } from "node:fs";
16282
- import path7 from "node:path";
15346
+ import path6 from "node:path";
16283
15347
  function createDiagnosticTraceWriter(directory) {
16284
15348
  mkdirSync(directory, { recursive: true, mode: 448 });
16285
15349
  return {
16286
15350
  append(instanceId, text) {
16287
- appendFileSync(path7.join(directory, `${instanceId}.log`), text, {
15351
+ appendFileSync(path6.join(directory, `${instanceId}.log`), text, {
16288
15352
  encoding: "utf8",
16289
15353
  mode: 384
16290
15354
  });
@@ -17567,8 +16631,8 @@ function decideIdleWorkerStop(input) {
17567
16631
  }
17568
16632
 
17569
16633
  // src/supervisor/worker-api-compatibility.ts
17570
- import { WORKER_API_VERSION as WORKER_API_VERSION2 } from "@leitwerk-dev/worker-protocol";
17571
- function checkWorkerApiCompatibility(payload, expectedApiVersion = WORKER_API_VERSION2, options = {}) {
16634
+ import { WORKER_API_VERSION } from "@leitwerk-dev/worker-protocol";
16635
+ function checkWorkerApiCompatibility(payload, expectedApiVersion = WORKER_API_VERSION, options = {}) {
17572
16636
  if (payload.apiVersion === void 0) {
17573
16637
  if (options.requireApiVersion === true) {
17574
16638
  return {
@@ -17716,7 +16780,7 @@ function createWorkerShutdownController(input) {
17716
16780
 
17717
16781
  // src/supervisor/worker-start-payload-builder.ts
17718
16782
  import { randomUUID as randomUUID5 } from "node:crypto";
17719
- import path8 from "node:path";
16783
+ import path7 from "node:path";
17720
16784
  import { parseProductRefsFromStateJsonLenient } from "@leitwerk-dev/domain";
17721
16785
  import { parseDurationMs as parseDurationMs6 } from "@leitwerk-dev/watcher-utils";
17722
16786
  import {
@@ -17946,7 +17010,7 @@ function createWorkerStartPayloadBuilder(deps) {
17946
17010
  30 * 60 * 1e3,
17947
17011
  { allowHours: true }
17948
17012
  ),
17949
- processStorageRoot: deps.config.workers.runner === "local" ? treePaths.workspaceRoot : path8.dirname(treePaths.workspaceRoot)
17013
+ processStorageRoot: deps.config.workers.runner === "local" ? treePaths.workspaceRoot : path7.dirname(treePaths.workspaceRoot)
17950
17014
  },
17951
17015
  ...treePaths.resume ? { resumeLeafEntryId } : {},
17952
17016
  ...llmPreparation ? { llmPreparation } : {},
@@ -19400,7 +18464,7 @@ ${configErrors.join("\n")}`);
19400
18464
  for (const process2 of repos.processes.listAll()) await sessionSnapshots.backfill(process2.id);
19401
18465
  const sessionReader = new ProcessSessionReader(sessionSnapshots);
19402
18466
  const resultImages = new ResultImageStore({
19403
- rootDir: path9.join(config.storage.tree_files_dir, "result-images")
18467
+ rootDir: path8.join(config.storage.tree_files_dir, "result-images")
19404
18468
  });
19405
18469
  const authService = createAuthService({ config, repos });
19406
18470
  await registerWebsocket(app, broadcaster, workerWebSocketIpc, authService);
@@ -19640,7 +18704,7 @@ ${configErrors.join("\n")}`);
19640
18704
  toolApprovalGate
19641
18705
  });
19642
18706
  const diagnosticTraceWriter = createDiagnosticTraceWriter(
19643
- path9.join(config.storage.tree_files_dir, "diagnostic-traces")
18707
+ path8.join(config.storage.tree_files_dir, "diagnostic-traces")
19644
18708
  );
19645
18709
  const ipcHandler = createIpcHandler(
19646
18710
  {
@@ -20163,4 +19227,4 @@ ${configErrors.join("\n")}`);
20163
19227
  export {
20164
19228
  createAppContext
20165
19229
  };
20166
- //# sourceMappingURL=chunk-CNITOV76.js.map
19230
+ //# sourceMappingURL=chunk-LK3RO6C7.js.map