@leitwerk-dev/server 0.2.1 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (123) hide show
  1. package/dist/{app-WfwKzrVk.d.ts → app-BuJCdkvy.d.ts} +82 -2
  2. package/dist/app-MSJXFK33.js +8 -0
  3. package/dist/app.d.ts.map +1 -1
  4. package/dist/{chunk-ZSKM25SD.js → chunk-HK6BLLHA.js} +1702 -496
  5. package/dist/chunk-HK6BLLHA.js.map +1 -0
  6. package/dist/{chunk-CNITOV76.js → chunk-QCHS3X33.js} +546 -1132
  7. package/dist/chunk-QCHS3X33.js.map +1 -0
  8. package/dist/db/database.d.ts.map +1 -1
  9. package/dist/db/mapped-llm-run-repo.d.ts +56 -0
  10. package/dist/db/mapped-llm-run-repo.d.ts.map +1 -0
  11. package/dist/db/process-turn-record-repo.d.ts +3 -1
  12. package/dist/db/process-turn-record-repo.d.ts.map +1 -1
  13. package/dist/db/repo-helpers.d.ts +6 -0
  14. package/dist/db/repo-helpers.d.ts.map +1 -1
  15. package/dist/db/repositories.d.ts +4 -0
  16. package/dist/db/repositories.d.ts.map +1 -1
  17. package/dist/db/schema.d.ts +415 -0
  18. package/dist/db/schema.d.ts.map +1 -1
  19. package/dist/db/turn-start-record-repo.d.ts.map +1 -1
  20. package/dist/domain-logic/outcome-tools.d.ts.map +1 -1
  21. package/dist/future-execution-presenter.d.ts +4 -14
  22. package/dist/future-execution-presenter.d.ts.map +1 -1
  23. package/dist/index.js +2 -2
  24. package/dist/launch-coordinator-test-harness.d.ts.map +1 -1
  25. package/dist/main.js +3 -3
  26. package/dist/process-action-presenter.d.ts +16 -0
  27. package/dist/process-action-presenter.d.ts.map +1 -0
  28. package/dist/process-engine/mapped-turns.d.ts +45 -0
  29. package/dist/process-engine/mapped-turns.d.ts.map +1 -0
  30. package/dist/process-engine/operation.d.ts +1 -1
  31. package/dist/process-engine/operation.d.ts.map +1 -1
  32. package/dist/process-engine/ops/accept-worker-turn-start.d.ts +2 -0
  33. package/dist/process-engine/ops/accept-worker-turn-start.d.ts.map +1 -1
  34. package/dist/process-engine/ops/retry-startup.d.ts.map +1 -1
  35. package/dist/process-engine/ops/turn-outcome.d.ts.map +1 -1
  36. package/dist/process-engine/recorder.d.ts.map +1 -1
  37. package/dist/process-engine/types.d.ts +5 -0
  38. package/dist/process-engine/types.d.ts.map +1 -1
  39. package/dist/process-engine/writes/build-process-abort-writes.d.ts.map +1 -1
  40. package/dist/process-engine/writes/build-recovery-start-writes.d.ts.map +1 -1
  41. package/dist/process-engine/writes/build-turn-outcome-writes.d.ts +8 -1
  42. package/dist/process-engine/writes/build-turn-outcome-writes.d.ts.map +1 -1
  43. package/dist/process-engine/writes/build-turn-selection-writes.d.ts.map +1 -1
  44. package/dist/process-engine/writes/commit-writes.d.ts.map +1 -1
  45. package/dist/process-engine/writes/reserve-selected-turn-start.d.ts +5 -0
  46. package/dist/process-engine/writes/reserve-selected-turn-start.d.ts.map +1 -0
  47. package/dist/process-engine/writes/writes.d.ts +18 -0
  48. package/dist/process-engine/writes/writes.d.ts.map +1 -1
  49. package/dist/process-turn-navigation.d.ts +12 -2
  50. package/dist/process-turn-navigation.d.ts.map +1 -1
  51. package/dist/process-ui-snapshot-presenter.d.ts +2 -1
  52. package/dist/process-ui-snapshot-presenter.d.ts.map +1 -1
  53. package/dist/routes/process-actions.d.ts.map +1 -1
  54. package/dist/routes/process-diagnostics-assembler.d.ts +3 -1
  55. package/dist/routes/process-diagnostics-assembler.d.ts.map +1 -1
  56. package/dist/routes/process-primary-path-assembler.d.ts +4 -12
  57. package/dist/routes/process-primary-path-assembler.d.ts.map +1 -1
  58. package/dist/routes/process-route-helpers.d.ts +7 -32
  59. package/dist/routes/process-route-helpers.d.ts.map +1 -1
  60. package/dist/supervisor/ipc-handler.d.ts.map +1 -1
  61. package/dist/supervisor/worker-start-payload-builder.d.ts +2 -0
  62. package/dist/supervisor/worker-start-payload-builder.d.ts.map +1 -1
  63. package/dist/supervisor/worker-supervisor.d.ts +2 -0
  64. package/dist/supervisor/worker-supervisor.d.ts.map +1 -1
  65. package/dist/supervisor/worker-turn-ipc-recorder.d.ts +2 -2
  66. package/dist/supervisor/worker-turn-ipc-recorder.d.ts.map +1 -1
  67. package/dist/test-helpers/accepted-turn-start.d.ts +23 -4
  68. package/dist/test-helpers/accepted-turn-start.d.ts.map +1 -1
  69. package/dist/test-helpers/owned-test-deps.d.ts +18 -0
  70. package/dist/test-helpers/owned-test-deps.d.ts.map +1 -0
  71. package/dist/test-helpers/prepared-fixture-start.d.ts +14 -0
  72. package/dist/test-helpers/prepared-fixture-start.d.ts.map +1 -0
  73. package/dist/testing.d.ts +2 -1
  74. package/dist/testing.d.ts.map +1 -1
  75. package/dist/testing.js +72 -11
  76. package/dist/testing.js.map +1 -1
  77. package/package.json +11 -11
  78. package/src/app.ts +2 -0
  79. package/src/db/database.ts +28 -0
  80. package/src/db/mapped-llm-run-repo.ts +177 -0
  81. package/src/db/process-turn-record-repo.ts +8 -1
  82. package/src/db/repo-helpers.ts +11 -1
  83. package/src/db/repositories.ts +5 -0
  84. package/src/db/schema.ts +70 -1
  85. package/src/db/turn-start-record-repo.ts +5 -1
  86. package/src/domain-logic/outcome-tools.ts +50 -6
  87. package/src/future-execution-presenter.ts +10 -17
  88. package/src/launch-coordinator-test-harness.ts +8 -4
  89. package/src/process-action-presenter.ts +133 -0
  90. package/src/process-engine/engine.ts +2 -2
  91. package/src/process-engine/mapped-turns.ts +330 -0
  92. package/src/process-engine/operation.ts +1 -1
  93. package/src/process-engine/ops/accept-worker-turn-start.ts +6 -0
  94. package/src/process-engine/ops/retry-startup.ts +1 -0
  95. package/src/process-engine/ops/turn-outcome.ts +7 -5
  96. package/src/process-engine/recorder.ts +12 -0
  97. package/src/process-engine/runner.ts +8 -8
  98. package/src/process-engine/types.ts +6 -0
  99. package/src/process-engine/writes/build-process-abort-writes.ts +1 -0
  100. package/src/process-engine/writes/build-recovery-start-writes.ts +1 -0
  101. package/src/process-engine/writes/build-turn-outcome-writes.ts +80 -20
  102. package/src/process-engine/writes/build-turn-selection-writes.ts +2 -31
  103. package/src/process-engine/writes/commit-writes.ts +5 -0
  104. package/src/process-engine/writes/reserve-selected-turn-start.ts +44 -0
  105. package/src/process-engine/writes/writes.ts +27 -0
  106. package/src/process-turn-navigation.ts +86 -8
  107. package/src/process-ui-snapshot-presenter.ts +40 -4
  108. package/src/routes/process-actions.ts +1 -1
  109. package/src/routes/process-diagnostics-assembler.ts +32 -6
  110. package/src/routes/process-primary-path-assembler.ts +17 -33
  111. package/src/routes/process-route-helpers.ts +8 -165
  112. package/src/supervisor/ipc-handler.ts +27 -18
  113. package/src/supervisor/worker-start-payload-builder.ts +25 -0
  114. package/src/supervisor/worker-supervisor.ts +2 -0
  115. package/src/supervisor/worker-turn-ipc-recorder.ts +13 -1
  116. package/src/test-helpers/accepted-turn-start.ts +54 -27
  117. package/src/test-helpers/owned-test-deps.ts +45 -0
  118. package/src/test-helpers/prepared-fixture-start.ts +74 -0
  119. package/src/testing.ts +5 -1
  120. package/dist/app-7PKX73TU.js +0 -8
  121. package/dist/chunk-CNITOV76.js.map +0 -1
  122. package/dist/chunk-ZSKM25SD.js.map +0 -1
  123. /package/dist/{app-7PKX73TU.js.map → app-MSJXFK33.js.map} +0 -0
@@ -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-HK6BLLHA.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 {
@@ -1198,6 +1086,37 @@ function canAbort(lifecycleStatus) {
1198
1086
  return lifecycleStatus !== "completed" && lifecycleStatus !== "aborted";
1199
1087
  }
1200
1088
 
1089
+ // src/process-engine/writes/reserve-selected-turn-start.ts
1090
+ function reserveSelectedTurnStart(writes, process2, turnId, turnType, iteration) {
1091
+ const startId = generateId("tsr");
1092
+ writes.turnStartWrites.push({
1093
+ kind: "create",
1094
+ input: {
1095
+ id: startId,
1096
+ instanceId: process2.id,
1097
+ turnId,
1098
+ turnType,
1099
+ proposedTurnRecordId: generateId("trn"),
1100
+ startKind: "selected_turn",
1101
+ recoveryTurnRecordId: null,
1102
+ continuation: null,
1103
+ state: turnType === "automatic" ? { kind: "starting", start: { kind: "automatic" } } : {
1104
+ kind: "preparation_failed",
1105
+ requestedModelProfileId: process2.selectedTurnModelProfileId ?? null,
1106
+ providerOptions: {},
1107
+ code: "model_required",
1108
+ safeSummary: "LLM start requires model preflight"
1109
+ },
1110
+ ...iteration ? { iteration } : {}
1111
+ }
1112
+ });
1113
+ applyProcessPatchField(writes, process2, "currentExecution", {
1114
+ kind: "worker_start",
1115
+ id: startId
1116
+ });
1117
+ if (turnType === "llm") applyProcessPatchField(writes, process2, "lifecycleStatus", "error");
1118
+ }
1119
+
1201
1120
  // src/process-engine/writes/build-turn-selection-writes.ts
1202
1121
  function deriveLifecycleStatusForSelectedTurn(processGraphs, processId, turnId) {
1203
1122
  const turn = getProcessTurnGraph(processGraphs, processId, turnId);
@@ -1254,33 +1173,7 @@ function buildTurnSelectionWrites(processGraphs, process2, input) {
1254
1173
  if (input.toTurnId && targetLifecycleStatus === "active") {
1255
1174
  const target = getProcessTurnGraph(processGraphs, process2.processId, input.toTurnId);
1256
1175
  if (target?.turnType === "llm" || target?.turnType === "automatic") {
1257
- const startId = generateId("tsr");
1258
- writes.turnStartWrites.push({
1259
- kind: "create",
1260
- input: {
1261
- id: startId,
1262
- instanceId: process2.id,
1263
- turnId: input.toTurnId,
1264
- turnType: target.turnType,
1265
- proposedTurnRecordId: generateId("trn"),
1266
- startKind: "selected_turn",
1267
- recoveryTurnRecordId: null,
1268
- continuation: null,
1269
- state: target.turnType === "automatic" ? { kind: "starting", start: { kind: "automatic" } } : {
1270
- kind: "preparation_failed",
1271
- requestedModelProfileId: process2.selectedTurnModelProfileId ?? null,
1272
- providerOptions: {},
1273
- code: "model_required",
1274
- safeSummary: "LLM start requires model preflight"
1275
- }
1276
- }
1277
- });
1278
- applyProcessPatchField(writes, process2, "currentExecution", {
1279
- kind: "worker_start",
1280
- id: startId
1281
- });
1282
- if (target.turnType === "llm")
1283
- applyProcessPatchField(writes, process2, "lifecycleStatus", "error");
1176
+ reserveSelectedTurnStart(writes, process2, input.toTurnId, target.turnType);
1284
1177
  }
1285
1178
  } else if (input.toTurnId === null || targetLifecycleStatus === "waiting" || targetLifecycleStatus === "completed" || targetLifecycleStatus === "aborted") {
1286
1179
  applyProcessPatchField(writes, process2, "currentExecution", null);
@@ -2574,7 +2467,7 @@ function createExternalSourceService(deps) {
2574
2467
 
2575
2468
  // src/future-execution/lifecycle.ts
2576
2469
  import {
2577
- SYSTEM_ACTOR as SYSTEM_ACTOR3
2470
+ SYSTEM_ACTOR as SYSTEM_ACTOR2
2578
2471
  } from "@leitwerk-dev/domain";
2579
2472
  import {
2580
2473
  parseFutureActionPayloadJson as parseFutureActionPayloadJson3,
@@ -2918,7 +2811,7 @@ async function planProcessAction(input) {
2918
2811
  if ("ok" in planned) {
2919
2812
  return planned;
2920
2813
  }
2921
- const candidateProcess2 = {
2814
+ const candidateProcess = {
2922
2815
  ...input.process,
2923
2816
  ...planned.processPatch
2924
2817
  };
@@ -2930,7 +2823,7 @@ async function planProcessAction(input) {
2930
2823
  visibleAction: visibleAction ?? null,
2931
2824
  resolvedTurnAction,
2932
2825
  writes: planned,
2933
- candidateProcess: candidateProcess2,
2826
+ candidateProcess,
2934
2827
  candidateSelectedTurnId
2935
2828
  };
2936
2829
  }
@@ -4331,7 +4224,7 @@ function createFutureExecutionExecutor(deps) {
4331
4224
  // src/future-execution/launch-lifecycle.ts
4332
4225
  import {
4333
4226
  normalizeLaunchModelConfigInput,
4334
- SYSTEM_ACTOR as SYSTEM_ACTOR2
4227
+ SYSTEM_ACTOR
4335
4228
  } from "@leitwerk-dev/domain";
4336
4229
  import {
4337
4230
  parseFutureLaunchPayloadJson as parseFutureLaunchPayloadJson3,
@@ -4568,7 +4461,7 @@ function createFutureLaunchLifecycle(deps, options = {}) {
4568
4461
  payload: parsed.value,
4569
4462
  request: launchRequest.value,
4570
4463
  launcher: resolved.launcher,
4571
- actor: actor ?? launchRequest.value.actor ?? SYSTEM_ACTOR2
4464
+ actor: actor ?? launchRequest.value.actor ?? SYSTEM_ACTOR
4572
4465
  }
4573
4466
  };
4574
4467
  },
@@ -4676,7 +4569,7 @@ function createFutureLaunchLifecycle(deps, options = {}) {
4676
4569
  /** @internal */
4677
4570
  async commitPreparedLaunch(prepared, opts) {
4678
4571
  if (prepared.schedule.mode !== "now")
4679
- return persistPreparedLaunch({ ...prepared, actor: opts?.actor ?? SYSTEM_ACTOR2 });
4572
+ return persistPreparedLaunch({ ...prepared, actor: opts?.actor ?? SYSTEM_ACTOR });
4680
4573
  const created = await createProcessFromLaunchPlan(deps, prepared.launchPlan, {
4681
4574
  ...opts,
4682
4575
  resourceSelections: prepared.resourceSelections,
@@ -4757,7 +4650,7 @@ function createFutureLaunchLifecycle(deps, options = {}) {
4757
4650
  return persistPreparedLaunch({
4758
4651
  ...prepared.prepared,
4759
4652
  existing,
4760
- actor: opts?.actor ?? launchRequest.value.actor ?? SYSTEM_ACTOR2
4653
+ actor: opts?.actor ?? launchRequest.value.actor ?? SYSTEM_ACTOR
4761
4654
  });
4762
4655
  });
4763
4656
  }
@@ -5096,7 +4989,7 @@ function createFutureExecutionLifecycle(deps, _options = {}) {
5096
4989
  actionInput: request.input,
5097
4990
  nextTurnModelProfileId: typeof request.nextTurnModelProfileId === "string" ? request.nextTurnModelProfileId : null,
5098
4991
  overrideProvided: typeof request.nextTurnModelProfileId === "string",
5099
- actor: opts?.actor ?? SYSTEM_ACTOR3,
4992
+ actor: opts?.actor ?? SYSTEM_ACTOR2,
5100
4993
  nextRunAt: validatedSchedule.nextRunAt,
5101
4994
  operationTime
5102
4995
  });
@@ -5149,7 +5042,7 @@ function createFutureExecutionLifecycle(deps, _options = {}) {
5149
5042
  source: "scheduled",
5150
5043
  scheduledExecutionId: existing.id,
5151
5044
  consumeScheduledExecutionOnSuccess: true,
5152
- actor: opts?.actor ?? resolvedActionRequest.value.actor ?? SYSTEM_ACTOR3
5045
+ actor: opts?.actor ?? resolvedActionRequest.value.actor ?? SYSTEM_ACTOR2
5153
5046
  }
5154
5047
  );
5155
5048
  }
@@ -5174,7 +5067,7 @@ function createFutureExecutionLifecycle(deps, _options = {}) {
5174
5067
  actionInput: resolvedActionRequest.value.input,
5175
5068
  nextTurnModelProfileId: resolvedActionRequest.value.nextTurnModelProfileId,
5176
5069
  overrideProvided: resolvedActionRequest.value.nextTurnModelProfileId !== null,
5177
- actor: opts?.actor ?? resolvedActionRequest.value.actor ?? SYSTEM_ACTOR3,
5070
+ actor: opts?.actor ?? resolvedActionRequest.value.actor ?? SYSTEM_ACTOR2,
5178
5071
  nextRunAt: validatedSchedule.nextRunAt,
5179
5072
  operationTime
5180
5073
  });
@@ -6896,34 +6789,6 @@ function createModelProviderCredentialService(input) {
6896
6789
  };
6897
6790
  }
6898
6791
 
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
6792
  // src/model-providers/model-status-cache.ts
6928
6793
  var DEFAULT_STATUS_TTL_MS = 3e4;
6929
6794
  var DEFAULT_STATUS_TIMEOUT_MS = 5e3;
@@ -7129,91 +6994,6 @@ function createModelStatusCache(input) {
7129
6994
  };
7130
6995
  }
7131
6996
 
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
6997
  // src/model-providers/registry.ts
7218
6998
  import { toErrorMessage as errorMessage } from "@leitwerk-dev/domain";
7219
6999
  var defaultModelProviderCredentialStatus = (provider) => provider.definition.credential ? { available: false, revision: null } : { available: true, revision: null };
@@ -7415,414 +7195,6 @@ async function createModelProviderServerAdapterRegistry(input) {
7415
7195
  };
7416
7196
  }
7417
7197
 
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
7198
  // src/process-deletion-service.ts
7827
7199
  var TERMINAL_STATUSES2 = /* @__PURE__ */ new Set(["completed", "aborted"]);
7828
7200
  var CLEANUP_FAILURE_MESSAGE = "The process could not be deleted; retry deletion";
@@ -7916,6 +7288,7 @@ function buildAbortProcessWrites(input) {
7916
7288
  if (isWriteBuildFailure(writes)) {
7917
7289
  return writes;
7918
7290
  }
7291
+ writes.mappedRunWrites.push({ kind: "abort_active" });
7919
7292
  if (input.currentWorkerStart?.state.kind === "starting") {
7920
7293
  writes.turnStartWrites.push({
7921
7294
  kind: "cas_state",
@@ -8046,7 +7419,7 @@ var AbortProcess = defineOperation({
8046
7419
  });
8047
7420
 
8048
7421
  // src/process-engine/ops/abort-turn.ts
8049
- import { SYSTEM_ACTOR as SYSTEM_ACTOR4 } from "@leitwerk-dev/domain";
7422
+ import { SYSTEM_ACTOR as SYSTEM_ACTOR3 } from "@leitwerk-dev/domain";
8050
7423
  var AbortTurn = defineOperation({
8051
7424
  kind: "abort_turn",
8052
7425
  label: "Abort running turn",
@@ -8072,7 +7445,7 @@ var AbortTurn = defineOperation({
8072
7445
  if (!supervisor.getWorker(ctx.process.id)) {
8073
7446
  return reject("worker_unavailable", "No active worker is available to stop this turn");
8074
7447
  }
8075
- const actor = input.actor ?? SYSTEM_ACTOR4;
7448
+ const actor = input.actor ?? SYSTEM_ACTOR3;
8076
7449
  const writes = createWrites({ workerIntent: { kind: "abort_turn", reason: input.reason } });
8077
7450
  appendProcessEvent(writes, ctx.process, {
8078
7451
  eventType: "turn_abort_requested",
@@ -8121,6 +7494,9 @@ function preparedStartMatchesDefinition(prepared, definition) {
8121
7494
  var AcceptWorkerTurnStart = defineOperation({
8122
7495
  kind: "accept_worker_turn_start",
8123
7496
  label: "Accept worker turn start",
7497
+ afterRecord(input, data) {
7498
+ input.onRecorded?.(data.turnRecordId);
7499
+ },
8124
7500
  decide(ctx, input) {
8125
7501
  if (ctx.process.lifecycleStatus !== "active" || ctx.process.currentExecution?.kind !== "worker_start" || ctx.process.currentExecution.id !== input.startRecordId) {
8126
7502
  return reject("stale_turn_start", "Worker start is no longer current and active");
@@ -8184,7 +7560,8 @@ var AcceptWorkerTurnStart = defineOperation({
8184
7560
  turnStartRecordId: start.id,
8185
7561
  acceptedWorkerLeaseId: lease.id,
8186
7562
  modelProfileId: acceptedLlmStart?.model.profileId ?? null,
8187
- modelSelectionProvenance: acceptedLlmStart?.modelSelectionProvenance ?? null
7563
+ modelSelectionProvenance: acceptedLlmStart?.modelSelectionProvenance ?? null,
7564
+ iteration: start.iteration ?? null
8188
7565
  }
8189
7566
  }
8190
7567
  ],
@@ -8226,7 +7603,7 @@ function readCurrentPrimaryPathLeafEntryId(stateJson) {
8226
7603
 
8227
7604
  // src/process-engine/writes/build-continue-failed-turn-writes.ts
8228
7605
  import {
8229
- CONTINUE_PROMPT_METADATA_KEY as CONTINUE_PROMPT_METADATA_KEY2,
7606
+ CONTINUE_PROMPT_METADATA_KEY,
8230
7607
  inferTerminalRecordingFailedTurnRecoveryContext,
8231
7608
  normalizeContinuePrompt,
8232
7609
  readFailedTurnRecoveryContext
@@ -8254,6 +7631,7 @@ function buildRecoveryStartWrites({ process: process2, failedRun, acceptedStart
8254
7631
  turnId: failedRun.turnId,
8255
7632
  proposedTurnRecordId: generateId("trn"),
8256
7633
  recoveryTurnRecordId: failedRun.id,
7634
+ iteration: failedRun.iteration ?? null,
8257
7635
  state: recovery.turnType === "automatic" ? { kind: "starting", start: { kind: "automatic" } } : {
8258
7636
  kind: "preparation_failed",
8259
7637
  requestedModelProfileId: failedRun.modelProfileId,
@@ -8287,7 +7665,7 @@ function buildContinueFailedTurnWrites(input) {
8287
7665
  if (!failedTurnRecovery) {
8288
7666
  throw new Error(`Failed turn '${failedRun.id}' is missing recovery context`);
8289
7667
  }
8290
- const continuePrompt = normalizeContinuePrompt(input.prompt) ?? normalizeContinuePrompt(process2.metadata?.[CONTINUE_PROMPT_METADATA_KEY2]) ?? failedTurnRecovery.suggestedContinuePrompt;
7668
+ const continuePrompt = normalizeContinuePrompt(input.prompt) ?? normalizeContinuePrompt(process2.metadata?.[CONTINUE_PROMPT_METADATA_KEY]) ?? failedTurnRecovery.suggestedContinuePrompt;
8291
7669
  const currentPrimaryPathLeafEntryId = readCurrentPrimaryPathLeafEntryId(process2.stateJson);
8292
7670
  const plan = buildRecoveryStartWrites(input, {
8293
7671
  startKind: "continue",
@@ -8301,7 +7679,7 @@ function buildContinueFailedTurnWrites(input) {
8301
7679
  updateProcessMetadata(plan, process2, ["retry"], (metadata) => {
8302
7680
  metadata.continueFromTurnRecordId = failedRun.id;
8303
7681
  metadata.continueFromPiEntryId = continueFromPiEntryId;
8304
- metadata[CONTINUE_PROMPT_METADATA_KEY2] = continuePrompt;
7682
+ metadata[CONTINUE_PROMPT_METADATA_KEY] = continuePrompt;
8305
7683
  if (failedRun.pathType !== "primary" && currentPrimaryPathLeafEntryId && currentPrimaryPathLeafEntryId !== continueFromPiEntryId) {
8306
7684
  metadata.continueSavedPrimaryLeafEntryId = currentPrimaryPathLeafEntryId;
8307
7685
  } else {
@@ -8503,7 +7881,7 @@ var ParkDeferredProcessActivationFailure = defineOperation({
8503
7881
  });
8504
7882
 
8505
7883
  // src/process-engine/ops/execute-action.ts
8506
- import { isProcessTurnType, SYSTEM_ACTOR as SYSTEM_ACTOR5 } from "@leitwerk-dev/domain";
7884
+ import { isProcessTurnType, SYSTEM_ACTOR as SYSTEM_ACTOR4 } from "@leitwerk-dev/domain";
8507
7885
  import {
8508
7886
  isLlmTurnDefinition as isLlmTurnDefinition2
8509
7887
  } from "@leitwerk-dev/process-sdk";
@@ -8619,7 +7997,7 @@ var ExecuteAction = defineOperation({
8619
7997
  async decide(ctx, input) {
8620
7998
  const actionSource = input.opts?.source ?? "ui";
8621
7999
  const actionOrigin = input.opts?.origin ?? DEFAULT_ACTION_ORIGIN_BY_SOURCE[actionSource];
8622
- const actor = input.opts?.actor ?? SYSTEM_ACTOR5;
8000
+ const actor = input.opts?.actor ?? SYSTEM_ACTOR4;
8623
8001
  const scheduledAction = ctx.deps.futureExecutions.getScheduledActionByInstance(
8624
8002
  input.instanceId
8625
8003
  );
@@ -9010,7 +8388,8 @@ var RetryStartup = defineOperation({
9010
8388
  startKind: "startup_retry",
9011
8389
  recoveryTurnRecordId: failed.recoveryTurnRecordId,
9012
8390
  continuation: failed.continuation,
9013
- state
8391
+ state,
8392
+ iteration: failed.iteration ?? null
9014
8393
  }
9015
8394
  });
9016
8395
  applyProcessPatchField(writes, ctx.process, "currentExecution", { kind: "worker_start", id });
@@ -9266,6 +8645,9 @@ async function captureLeafOutcomeSnapshot(options) {
9266
8645
  }
9267
8646
  }
9268
8647
 
8648
+ // src/process-engine/writes/build-turn-outcome-writes.ts
8649
+ import { SafeOutcomePlanningError as SafeOutcomePlanningError2 } from "@leitwerk-dev/process-sdk";
8650
+
9269
8651
  // src/domain-logic/outcome-tools.ts
9270
8652
  import {
9271
8653
  isUnknownRecord as isJsonObject,
@@ -9324,14 +8706,49 @@ var scalarParameters = {
9324
8706
  plural: "objects"
9325
8707
  }
9326
8708
  };
8709
+ function matchesNestedOutcomeSpec(spec, value) {
8710
+ switch (spec.type) {
8711
+ case "string":
8712
+ return typeof value === "string";
8713
+ case "number":
8714
+ return typeof value === "number" && Number.isFinite(value);
8715
+ case "boolean":
8716
+ return typeof value === "boolean";
8717
+ case "array": {
8718
+ const itemSpec = spec.items;
8719
+ return Array.isArray(value) && (spec.minItems === void 0 || value.length >= spec.minItems) && (!itemSpec || value.every((item) => matchesNestedOutcomeSpec(itemSpec, item)));
8720
+ }
8721
+ case "object": {
8722
+ if (!isJsonObject(value)) return false;
8723
+ const properties = spec.properties ?? {};
8724
+ if ((spec.required ?? []).some((key) => !Object.hasOwn(value, key))) return false;
8725
+ if (spec.additionalProperties === false && Object.keys(value).some((key) => !Object.hasOwn(properties, key)))
8726
+ return false;
8727
+ return Object.entries(properties).every(
8728
+ ([key, property]) => !Object.hasOwn(value, key) || matchesNestedOutcomeSpec(property, value[key])
8729
+ );
8730
+ }
8731
+ default:
8732
+ return false;
8733
+ }
8734
+ }
9327
8735
  function compileOutcomeParameterSchema(spec) {
9328
- return spec.type === "array" ? v3.array(scalarParameters[spec.items?.type ?? "string"].schema) : scalarParameters[spec.type].schema;
8736
+ if (spec.type !== "array") return scalarParameters[spec.type].schema;
8737
+ const itemSpec = spec.items ?? { type: "string" };
8738
+ return v3.custom(
8739
+ (value) => Array.isArray(value) && value.every((item) => matchesNestedOutcomeSpec(itemSpec, item)),
8740
+ "Expected an array matching its declared item schema"
8741
+ );
9329
8742
  }
9330
8743
  function effectiveArrayItemCount(spec, value) {
9331
8744
  return (spec.items?.type ?? "string") === "string" ? normalizeStringArray(value).length : value.length;
9332
8745
  }
9333
8746
  function expectedParameterLabel(spec) {
9334
- return spec.type === "array" ? `an array of ${scalarParameters[spec.items?.type ?? "string"].plural}` : scalarParameters[spec.type].label;
8747
+ if (spec.type !== "array") return scalarParameters[spec.type].label;
8748
+ if (spec.items?.type === "object")
8749
+ return spec.items.properties ? "an array of objects matching the declared schema" : "an array of objects";
8750
+ if (spec.items?.type === "array") return "an array of arrays matching the declared schema";
8751
+ return `an array of ${scalarParameters[spec.items?.type ?? "string"].plural}`;
9335
8752
  }
9336
8753
  function jsonValuesEqual(left, right) {
9337
8754
  if (left === right) {
@@ -9509,26 +8926,262 @@ function validateTurnOutcome(payload, turnDefinition, knownProjectKeys) {
9509
8926
  );
9510
8927
  }
9511
8928
 
8929
+ // src/process-engine/mapped-turns.ts
8930
+ import {
8931
+ collectMappedResults,
8932
+ freezeMappedItems,
8933
+ SafeOutcomePlanningError,
8934
+ yieldMappedItemResult
8935
+ } from "@leitwerk-dev/process-sdk";
8936
+ var MAX_EMPTY_MAPPED_ENTRIES = 16;
8937
+ function getMappedTurnSpec(registry, processId, turnId) {
8938
+ if (!registry || !turnId) return void 0;
8939
+ const turn = registry.getTurnDefinition(processId, turnId);
8940
+ return turn?.kind === "llm" ? turn.forEach : void 0;
8941
+ }
8942
+ function failure(code, message) {
8943
+ return { ok: false, code, message };
8944
+ }
8945
+ function planningFailure(error, code) {
8946
+ if (error instanceof SafeOutcomePlanningError) return failure(error.code, error.message);
8947
+ throw error instanceof Error ? error : new Error(`${code}: ${String(error)}`);
8948
+ }
8949
+ function serverContext(registry, process2, projects) {
8950
+ const { params: params2, state } = registry.resolveContextData(process2.processId, process2);
8951
+ return { process: process2, projects, params: params2, state };
8952
+ }
8953
+ function appendInto(target, source) {
8954
+ Object.assign(target, mergeWrites(target, source));
8955
+ }
8956
+ async function collectAndRoute(input) {
8957
+ let collected;
8958
+ try {
8959
+ collected = await collectMappedResults({
8960
+ turnId: input.turnId,
8961
+ spec: input.spec,
8962
+ ctx: input.ctx,
8963
+ resultJsons: input.resultJsons
8964
+ });
8965
+ } catch (error) {
8966
+ return planningFailure(error, "mapped_collect_failed");
8967
+ }
8968
+ const writes = buildServerTransitionWrites(input.processGraphs, input.process, {
8969
+ turnId: collected.route.nextTurnId ?? null,
8970
+ ...collected.route.lifecycleStatus ? { lifecycleStatus: collected.route.lifecycleStatus } : {},
8971
+ trigger: collected.route.trigger,
8972
+ state: collected.state
8973
+ });
8974
+ if (isWriteBuildFailure(writes)) return writes;
8975
+ appendProcessEvent(writes, input.process, {
8976
+ eventType: "mapped_run_collected",
8977
+ level: "info",
8978
+ message: `Collected ${input.resultJsons.length} result(s) for ${input.turnId}`,
8979
+ data: {
8980
+ runId: input.runId,
8981
+ turnId: input.turnId,
8982
+ itemCount: input.resultJsons.length,
8983
+ trigger: collected.route.trigger
8984
+ }
8985
+ });
8986
+ return writes;
8987
+ }
8988
+ async function planMappedTurnEntries(input) {
8989
+ const { writes } = input;
8990
+ const active = input.mappedRuns?.getActiveByInstance(input.process.id) ?? null;
8991
+ let activeAborted = false;
8992
+ for (let entry = 0; entry <= MAX_EMPTY_MAPPED_ENTRIES; entry += 1) {
8993
+ const candidate = { ...input.process, ...writes.processPatch };
8994
+ const startIndex = writes.turnStartWrites.findIndex(
8995
+ (write) => write.kind === "create" && write.input.turnType === "llm" && write.input.startKind === "selected_turn" && !write.input.iteration && write.input.turnId === candidate.selectedTurnId
8996
+ );
8997
+ const start = startIndex >= 0 ? writes.turnStartWrites[startIndex] : void 0;
8998
+ const spec = start?.kind === "create" ? getMappedTurnSpec(input.registry, candidate.processId, start.input.turnId) : void 0;
8999
+ if (!start || start.kind !== "create" || !spec || !input.registry) {
9000
+ const leavesActiveRun = active !== null && !activeAborted && !writes.mappedRunWrites.some((write) => write.kind === "complete_item") && (candidate.selectedTurnId !== active.turnId || candidate.lifecycleStatus === "completed" || candidate.lifecycleStatus === "aborted");
9001
+ if (leavesActiveRun) writes.mappedRunWrites.push({ kind: "abort_active" });
9002
+ return { ok: true };
9003
+ }
9004
+ if (entry === MAX_EMPTY_MAPPED_ENTRIES) {
9005
+ return failure("mapped_turn_loop", "Too many consecutive empty mapped turns");
9006
+ }
9007
+ if (!input.mappedRuns) {
9008
+ return failure("mapped_runs_unavailable", "Mapped turn storage is not available");
9009
+ }
9010
+ if (active && !activeAborted) {
9011
+ writes.mappedRunWrites.push({ kind: "abort_active" });
9012
+ activeAborted = true;
9013
+ }
9014
+ const turnId = start.input.turnId;
9015
+ const projects = input.projects.listByInstance(input.process.id);
9016
+ let ctx = serverContext(input.registry, candidate, projects);
9017
+ let frozen;
9018
+ try {
9019
+ frozen = freezeMappedItems(turnId, spec, ctx);
9020
+ } catch (error) {
9021
+ return planningFailure(error, "invalid_mapped_items");
9022
+ }
9023
+ const runId = generateId("mlr");
9024
+ writes.mappedRunWrites.push({
9025
+ kind: "create",
9026
+ input: {
9027
+ id: runId,
9028
+ instanceId: input.process.id,
9029
+ turnId,
9030
+ status: frozen.items.length > 0 ? "active" : "completed",
9031
+ items: frozen.items.map((item) => ({
9032
+ itemIndex: item.index,
9033
+ itemKey: item.key,
9034
+ label: item.label,
9035
+ itemJson: item.itemJson
9036
+ }))
9037
+ }
9038
+ });
9039
+ appendProcessEvent(writes, candidate, {
9040
+ eventType: "mapped_run_started",
9041
+ level: "info",
9042
+ message: `Froze ${frozen.items.length} item(s) for ${turnId}`,
9043
+ data: { runId, turnId, itemCount: frozen.items.length }
9044
+ });
9045
+ if (frozen.state !== void 0) {
9046
+ applyProcessPatchField(writes, candidate, "stateJson", JSON.stringify(frozen.state));
9047
+ ctx = { ...ctx, state: frozen.state };
9048
+ }
9049
+ const first = frozen.items[0];
9050
+ if (first) {
9051
+ start.input.iteration = { runId, itemKey: first.key, itemIndex: 0 };
9052
+ return { ok: true };
9053
+ }
9054
+ writes.turnStartWrites.splice(startIndex, 1);
9055
+ const routed = await collectAndRoute({
9056
+ processGraphs: input.processGraphs,
9057
+ process: { ...input.process, ...writes.processPatch },
9058
+ ctx,
9059
+ spec,
9060
+ turnId,
9061
+ runId,
9062
+ resultJsons: []
9063
+ });
9064
+ if (isWriteBuildFailure(routed)) return routed;
9065
+ appendInto(writes, routed);
9066
+ }
9067
+ return failure("mapped_turn_loop", "Too many consecutive empty mapped turns");
9068
+ }
9069
+ async function buildMappedItemOutcomeWrites(input) {
9070
+ const { payload, iteration } = input;
9071
+ if (!input.mappedRuns) {
9072
+ return failure("mapped_runs_unavailable", "Mapped turn storage is not available");
9073
+ }
9074
+ if (!iteration) {
9075
+ return failure("mapped_item_missing", `Turn '${payload.turnId}' has no active mapped item`);
9076
+ }
9077
+ const run = input.mappedRuns.getById(iteration.runId);
9078
+ const item = input.mappedRuns.getItem(iteration.runId, iteration.itemIndex);
9079
+ if (!run || !item || run.status !== "active" || run.turnId !== payload.turnId || run.nextIndex !== iteration.itemIndex || item.itemKey !== iteration.itemKey || item.status !== "pending") {
9080
+ return failure(
9081
+ "stale_mapped_item",
9082
+ `Mapped item '${iteration.itemKey}' is no longer the current item of '${payload.turnId}'`
9083
+ );
9084
+ }
9085
+ const ctx = serverContext(input.registry, input.process, input.projects);
9086
+ let resultJson;
9087
+ try {
9088
+ resultJson = await yieldMappedItemResult({
9089
+ turnId: payload.turnId,
9090
+ spec: input.spec,
9091
+ ctx,
9092
+ iteration: {
9093
+ runId: run.id,
9094
+ itemKey: item.itemKey,
9095
+ itemLabel: item.label,
9096
+ itemIndex: item.itemIndex,
9097
+ itemCount: run.itemCount,
9098
+ item: JSON.parse(item.itemJson)
9099
+ },
9100
+ event: {
9101
+ turnRecordId: payload.turnRecordId,
9102
+ turnId: payload.turnId,
9103
+ outcome: payload.outcome,
9104
+ params: payload.params ?? {},
9105
+ turnResultMarkdown: payload.turnResultMarkdown ?? null,
9106
+ ...input.prepared !== void 0 ? { prepared: input.prepared } : {}
9107
+ }
9108
+ });
9109
+ } catch (error) {
9110
+ return planningFailure(error, "invalid_mapped_result");
9111
+ }
9112
+ const writes = createWrites();
9113
+ writes.mappedRunWrites.push({
9114
+ kind: "complete_item",
9115
+ input: {
9116
+ runId: run.id,
9117
+ itemIndex: item.itemIndex,
9118
+ outcome: payload.outcome,
9119
+ resultJson,
9120
+ turnRecordId: payload.turnRecordId
9121
+ }
9122
+ });
9123
+ const nextIndex = item.itemIndex + 1;
9124
+ if (nextIndex < run.itemCount) {
9125
+ const next = input.mappedRuns.getItem(run.id, nextIndex);
9126
+ if (!next) return failure("stale_mapped_item", `Mapped run '${run.id}' lost item ${nextIndex}`);
9127
+ reserveSelectedTurnStart(writes, input.process, payload.turnId, "llm", {
9128
+ runId: run.id,
9129
+ itemKey: next.itemKey,
9130
+ itemIndex: nextIndex
9131
+ });
9132
+ writes.workerIntent = { kind: "reconcile" };
9133
+ return writes;
9134
+ }
9135
+ const resultJsons = input.mappedRuns.listItems(run.id).map((stored) => stored.itemIndex === item.itemIndex ? resultJson : stored.resultJson);
9136
+ if (resultJsons.some((json) => json === null)) {
9137
+ return failure("stale_mapped_item", `Mapped run '${run.id}' is missing item results`);
9138
+ }
9139
+ const routed = await collectAndRoute({
9140
+ processGraphs: input.processGraphs,
9141
+ process: input.process,
9142
+ ctx,
9143
+ spec: input.spec,
9144
+ turnId: payload.turnId,
9145
+ runId: run.id,
9146
+ resultJsons
9147
+ });
9148
+ if (isWriteBuildFailure(routed)) return routed;
9149
+ return mergeWrites(writes, routed);
9150
+ }
9151
+
9512
9152
  // src/process-engine/writes/build-turn-outcome-writes.ts
9513
9153
  function hasExplicitTurnSelectionChange(process2, writes) {
9514
9154
  return writes.processPatch.selectedTurnId !== void 0 && writes.processPatch.selectedTurnId !== process2.selectedTurnId;
9515
9155
  }
9516
- async function buildProcessTurnOutcomeEffectWrites(processGraphs, process2, projects, payload, processActionRegistry, turnRecords) {
9156
+ function loadPreparedData(process2, payload, events) {
9157
+ const preparationEvent = events?.listByInstanceTurnRecordEventTypes(process2.id, payload.turnRecordId, ["turn.prepared"]).at(-1);
9158
+ return preparationEvent?.data && typeof preparationEvent.data === "object" && "data" in preparationEvent.data ? preparationEvent.data.data : void 0;
9159
+ }
9160
+ async function buildProcessTurnOutcomeEffectWrites(processGraphs, process2, projects, payload, processActionRegistry, turnRecords, events) {
9517
9161
  const serverDef = processActionRegistry.getServerDefinition(process2.processId);
9518
9162
  const handlers = serverDef?.turnOutcomeHandlers.get(payload.turnId) ?? [];
9519
9163
  const { params: params2, state } = processActionRegistry.resolveContextData(process2.processId, process2);
9520
9164
  const plan = createProcessPlanCollector({ process: process2, projects, params: params2, state, turnRecords });
9165
+ const prepared = loadPreparedData(process2, payload, events);
9521
9166
  for (const handler of handlers) {
9522
- await handler(
9523
- {
9524
- turnRecordId: payload.turnRecordId,
9525
- turnId: payload.turnId,
9526
- outcome: payload.outcome,
9527
- params: payload.params ?? {},
9528
- turnResultMarkdown: payload.turnResultMarkdown ?? null
9529
- },
9530
- plan.context
9531
- );
9167
+ try {
9168
+ await handler(
9169
+ {
9170
+ turnRecordId: payload.turnRecordId,
9171
+ turnId: payload.turnId,
9172
+ outcome: payload.outcome,
9173
+ params: payload.params ?? {},
9174
+ turnResultMarkdown: payload.turnResultMarkdown ?? null,
9175
+ ...prepared !== void 0 ? { prepared } : {}
9176
+ },
9177
+ plan.context
9178
+ );
9179
+ } catch (error) {
9180
+ if (error instanceof SafeOutcomePlanningError2) {
9181
+ return { ok: false, code: error.code, message: error.message };
9182
+ }
9183
+ throw error;
9184
+ }
9532
9185
  }
9533
9186
  for (const queuedInput of plan.queuedInputs) {
9534
9187
  const validationError = validateQueuedProcessInput(queuedInput);
@@ -9597,29 +9250,57 @@ async function buildTurnOutcomeWrites(input) {
9597
9250
  );
9598
9251
  }
9599
9252
  const processForEffects = { ...input.process, ...baseWrites.processPatch };
9253
+ const outcomeEvent = createDeferredExtensionEvent(input.process.id, "turn_outcome", {
9254
+ turnRecordId: input.payload.turnRecordId,
9255
+ turnId: input.payload.turnId,
9256
+ outcome: input.payload.outcome,
9257
+ params: input.payload.params ?? {},
9258
+ turnResultMarkdown: input.payload.turnResultMarkdown ?? null
9259
+ });
9260
+ const mappedSpec = turnDefinition?.kind === "llm" ? turnDefinition.forEach : void 0;
9261
+ if (mappedSpec) {
9262
+ const mappedWrites = await buildMappedItemOutcomeWrites({
9263
+ processGraphs: input.processGraphs,
9264
+ registry: input.processActionRegistry,
9265
+ mappedRuns: input.mappedRuns,
9266
+ process: processForEffects,
9267
+ projects: input.projects,
9268
+ payload: input.payload,
9269
+ spec: mappedSpec,
9270
+ iteration: input.iteration,
9271
+ prepared: loadPreparedData(processForEffects, input.payload, input.events)
9272
+ });
9273
+ if (isWriteBuildFailure(mappedWrites)) {
9274
+ return mappedWrites;
9275
+ }
9276
+ const writes2 = mergeWrites(baseWrites, mappedWrites);
9277
+ writes2.extensionEvents.push(outcomeEvent);
9278
+ return writes2;
9279
+ }
9600
9280
  const effectWrites = await buildProcessTurnOutcomeEffectWrites(
9601
9281
  input.processGraphs,
9602
9282
  processForEffects,
9603
9283
  input.projects,
9604
9284
  input.payload,
9605
9285
  input.processActionRegistry,
9606
- input.turnRecords
9286
+ input.turnRecords,
9287
+ input.events
9607
9288
  );
9608
9289
  if (isWriteBuildFailure(effectWrites)) {
9609
9290
  return effectWrites;
9610
9291
  }
9611
9292
  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)) {
9293
+ let candidateProcess = { ...input.process, ...writes.processPatch };
9294
+ if (candidateProcess.selectedTurnId === input.payload.turnId && candidateProcess.lifecycleStatus === "active" && !hasExplicitTurnSelectionChange(input.process, effectWrites)) {
9614
9295
  const outcomeTransition = findOutcomeTransition(
9615
9296
  input.processGraphs,
9616
- candidateProcess2.processId,
9297
+ candidateProcess.processId,
9617
9298
  input.payload.turnId,
9618
9299
  input.payload.outcome
9619
9300
  );
9620
9301
  if (outcomeTransition) {
9621
- const transitionWrites = buildTurnSelectionWrites(input.processGraphs, candidateProcess2, {
9622
- fromTurnId: candidateProcess2.selectedTurnId,
9302
+ const transitionWrites = buildTurnSelectionWrites(input.processGraphs, candidateProcess, {
9303
+ fromTurnId: candidateProcess.selectedTurnId,
9623
9304
  toTurnId: outcomeTransition.toTurnId,
9624
9305
  ...outcomeTransition.lifecycleStatus !== void 0 ? { lifecycleStatus: outcomeTransition.lifecycleStatus } : {},
9625
9306
  state: void 0
@@ -9628,18 +9309,10 @@ async function buildTurnOutcomeWrites(input) {
9628
9309
  return transitionWrites;
9629
9310
  }
9630
9311
  writes = mergeWrites(writes, transitionWrites);
9631
- candidateProcess2 = { ...candidateProcess2, ...transitionWrites.processPatch };
9312
+ candidateProcess = { ...candidateProcess, ...transitionWrites.processPatch };
9632
9313
  }
9633
9314
  }
9634
- writes.extensionEvents.push(
9635
- createDeferredExtensionEvent(input.process.id, "turn_outcome", {
9636
- turnRecordId: input.payload.turnRecordId,
9637
- turnId: input.payload.turnId,
9638
- outcome: input.payload.outcome,
9639
- params: input.payload.params ?? {},
9640
- turnResultMarkdown: input.payload.turnResultMarkdown ?? null
9641
- })
9642
- );
9315
+ writes.extensionEvents.push(outcomeEvent);
9643
9316
  return writes;
9644
9317
  }
9645
9318
 
@@ -9771,10 +9444,8 @@ var TurnOutcome = defineOperation({
9771
9444
  });
9772
9445
  const payload = resolveEffectiveOutcomePayload({ payload: initialPayload, publication });
9773
9446
  const publishedProduct = publication.productName;
9774
- const expected = ctx.process.currentExecution?.kind === "worker_start" ? (() => {
9775
- const state = ctx.deps.turnStarts.getById(ctx.process.currentExecution.id)?.state;
9776
- return state?.kind === "accepted" ? state.turnRecordId : null;
9777
- })() : null;
9447
+ const currentStart = ctx.process.currentExecution?.kind === "worker_start" ? ctx.deps.turnStarts.getById(ctx.process.currentExecution.id) : null;
9448
+ const expected = currentStart?.state.kind === "accepted" ? currentStart.state.turnRecordId : null;
9778
9449
  const correlationError = validateTurnOutcomeCorrelation(ctx.process, payload, expected);
9779
9450
  if (correlationError) {
9780
9451
  return reject(correlationError.code, correlationError.message);
@@ -9927,14 +9598,17 @@ var TurnOutcome = defineOperation({
9927
9598
  if (ctx.process.lifecycleStatus === "error") {
9928
9599
  applyProcessPatchField(baseWrites, ctx.process, "lifecycleStatus", "active");
9929
9600
  }
9930
- const candidateProcess2 = { ...ctx.process, ...baseWrites.processPatch };
9601
+ const candidateProcess = { ...ctx.process, ...baseWrites.processPatch };
9931
9602
  const outcomeWrites = await buildTurnOutcomeWrites({
9932
- process: candidateProcess2,
9603
+ process: candidateProcess,
9933
9604
  projects,
9934
9605
  payload,
9935
9606
  turnRecords: ctx.deps.turnRecords,
9607
+ events: ctx.deps.events,
9936
9608
  processGraphs: ctx.deps.processGraphs,
9937
- processActionRegistry
9609
+ processActionRegistry,
9610
+ mappedRuns: ctx.deps.mappedRuns,
9611
+ iteration: currentStart?.iteration ?? null
9938
9612
  });
9939
9613
  if (isWriteBuildFailure(outcomeWrites)) {
9940
9614
  return reject(outcomeWrites.code, outcomeWrites.message);
@@ -10300,6 +9974,11 @@ function commitWrites(deps, instanceId, writes) {
10300
9974
  return deps.transaction((repos) => {
10301
9975
  const processBefore = repos.processes.getById(instanceId);
10302
9976
  const committedTurnRecords = [];
9977
+ for (const write of writes.mappedRunWrites) {
9978
+ if (write.kind === "create") repos.mappedRuns.create(write.input);
9979
+ else if (write.kind === "complete_item") repos.mappedRuns.completeItem(write.input);
9980
+ else repos.mappedRuns.abortActiveByInstance(instanceId);
9981
+ }
10303
9982
  for (const write of writes.turnStartWrites) {
10304
9983
  if (write.kind === "create") repos.turnStarts.create(write.input);
10305
9984
  else if (!repos.turnStarts.compareAndSetState(write)) {
@@ -10563,25 +10242,36 @@ function buildRecordedDecision(input) {
10563
10242
  };
10564
10243
  }
10565
10244
  async function record2(deps, operation, input, initialProcess, decision) {
10245
+ const mappedPlan = await planMappedTurnEntries({
10246
+ processGraphs: deps.processGraphs,
10247
+ registry: deps.getProcessActionRegistry?.(),
10248
+ mappedRuns: deps.mappedRuns,
10249
+ projects: deps.projects,
10250
+ process: initialProcess,
10251
+ writes: decision.writes
10252
+ });
10253
+ if (!mappedPlan.ok) {
10254
+ return { ok: false, stage: "pre_commit", code: mappedPlan.code, message: mappedPlan.message };
10255
+ }
10566
10256
  const baselineWrites = structuredClone(decision.writes);
10567
10257
  const runModelPreparation = async (availability) => {
10568
- const candidateProcess2 = {
10258
+ const candidateProcess = {
10569
10259
  ...initialProcess,
10570
10260
  ...decision.writes.processPatch
10571
10261
  };
10572
10262
  const createdStart = decision.writes.turnStartWrites.find(
10573
10263
  (write) => write.kind === "create" && write.input.turnType === "llm"
10574
10264
  );
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) {
10265
+ const shouldResolveSelection = !!candidateProcess.selectedTurnId && (!!createdStart || candidateProcess.selectedTurnId !== initialProcess.selectedTurnId || candidateProcess.lifecycleStatus === "active" && initialProcess.lifecycleStatus !== "active" || Object.hasOwn(decision.metadata ?? {}, "nextTurnModelProfileId"));
10266
+ if (!candidateProcess.selectedTurnId) {
10577
10267
  applyProcessPatchField(decision.writes, initialProcess, "selectedTurnModelProfileId", null);
10578
10268
  applyProcessPatchField(decision.writes, initialProcess, "selectedTurnModelKind", null);
10579
10269
  applyProcessPatchField(decision.writes, initialProcess, "selectedTurnModelSource", null);
10580
- } else if (shouldResolveSelection && candidateProcess2.selectedTurnId) {
10270
+ } else if (shouldResolveSelection && candidateProcess.selectedTurnId) {
10581
10271
  const resolution = deps.processModelPolicy.evaluate({
10582
10272
  kind: "process_turn",
10583
- process: candidateProcess2,
10584
- turnId: candidateProcess2.selectedTurnId,
10273
+ process: candidateProcess,
10274
+ turnId: candidateProcess.selectedTurnId,
10585
10275
  availability,
10586
10276
  startKind: createdStart?.input.startKind,
10587
10277
  initialSelection: createdStart?.input.startKind === "selected_turn" && initialProcess.selectedTurnId === null && initialProcess.lifecycleStatus === "discovered" && initialProcess.planRevision === 0,
@@ -10590,7 +10280,7 @@ async function record2(deps, operation, input, initialProcess, decision) {
10590
10280
  if (!resolution.ok && resolution.code !== "model_unavailable" && resolution.code !== "model_stale" && resolution.code !== "model_required") {
10591
10281
  const message = presentProcessModelPolicyFailure(resolution);
10592
10282
  if (createdStart) {
10593
- parkInvalidModelConfiguration(decision.writes, createdStart, candidateProcess2, message);
10283
+ parkInvalidModelConfiguration(decision.writes, createdStart, candidateProcess, message);
10594
10284
  return { ok: true };
10595
10285
  }
10596
10286
  return {
@@ -10872,12 +10562,6 @@ function createEngineRunner(deps, options = {}) {
10872
10562
  if (lockedOutcome.kind === "pre_commit_failed") {
10873
10563
  return mapPreCommitFailure(lockedOutcome.failure, lockedOutcome.initialProcess);
10874
10564
  }
10875
- if (lockedOutcome.kind === "post_commit_failed") {
10876
- return mapPostCommitFailure(
10877
- lockedOutcome.recorded,
10878
- lockedOutcome.failure
10879
- );
10880
- }
10881
10565
  const { recorded } = lockedOutcome;
10882
10566
  try {
10883
10567
  operation.afterRecord?.(input, recorded.data);
@@ -10890,6 +10574,12 @@ function createEngineRunner(deps, options = {}) {
10890
10574
  code: "after_record_callback_failed"
10891
10575
  });
10892
10576
  }
10577
+ if (lockedOutcome.kind === "post_commit_failed") {
10578
+ return mapPostCommitFailure(
10579
+ lockedOutcome.recorded,
10580
+ lockedOutcome.failure
10581
+ );
10582
+ }
10893
10583
  try {
10894
10584
  await deps.afterRecord?.(recorded.process);
10895
10585
  const dispatchResult = await dispatchReactions(
@@ -11039,8 +10729,8 @@ function createProcessEngine(deps) {
11039
10729
  const result = await run(WorkerFailure, { instanceId, payload });
11040
10730
  return maybeBroadcastErrorAttentionToast2(result, { errorCode: payload.errorCode });
11041
10731
  },
11042
- acceptWorkerTurnStart(instanceId, input) {
11043
- return run(AcceptWorkerTurnStart, { instanceId, ...input });
10732
+ acceptWorkerTurnStart(instanceId, input, options) {
10733
+ return run(AcceptWorkerTurnStart, { instanceId, ...input, onRecorded: options?.onRecorded });
11044
10734
  },
11045
10735
  async recordTurnOutcome(instanceId, payload, options) {
11046
10736
  return maybeBroadcastActionRequiredToast2(
@@ -11363,309 +11053,6 @@ async function reconcileProcessesOnStartup(deps) {
11363
11053
  );
11364
11054
  }
11365
11055
 
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
11056
  // src/process-launcher-registry.ts
11670
11057
  import { buildProcessLaunchers } from "@leitwerk-dev/process-sdk";
11671
11058
 
@@ -13251,7 +12638,7 @@ var RepositoryCredentialService = class {
13251
12638
  // src/result-image-store.ts
13252
12639
  import { createHash as createHash2, randomUUID as randomUUID2 } from "node:crypto";
13253
12640
  import { mkdir, readdir, readFile as readFile2, rename, rm, writeFile } from "node:fs/promises";
13254
- import path3 from "node:path";
12641
+ import path2 from "node:path";
13255
12642
  import {
13256
12643
  isResultImageStorageSegment,
13257
12644
  parseResultImageId
@@ -13271,12 +12658,12 @@ var ResultImageStore = class {
13271
12658
  rootDir;
13272
12659
  /** @internal */
13273
12660
  constructor(input) {
13274
- this.rootDir = path3.resolve(input.rootDir);
12661
+ this.rootDir = path2.resolve(input.rootDir);
13275
12662
  }
13276
12663
  turnDir(instanceId, turnRecordId) {
13277
12664
  if (!isResultImageStorageSegment(instanceId) || !isResultImageStorageSegment(turnRecordId))
13278
12665
  throw new Error("Invalid result image storage id");
13279
- return path3.join(this.rootDir, instanceId, turnRecordId);
12666
+ return path2.join(this.rootDir, instanceId, turnRecordId);
13280
12667
  }
13281
12668
  /** @internal */
13282
12669
  async put(input) {
@@ -13284,8 +12671,8 @@ var ResultImageStore = class {
13284
12671
  await mkdir(dir, { recursive: true });
13285
12672
  const digest = createHash2("sha256").update(input.bytes).digest("hex");
13286
12673
  const imageId = `img_${digest}.${EXTENSIONS[input.mimeType]}`;
13287
- const destination = path3.join(dir, imageId);
13288
- const temporary = path3.join(dir, `.${imageId}.${randomUUID2()}.tmp`);
12674
+ const destination = path2.join(dir, imageId);
12675
+ const temporary = path2.join(dir, `.${imageId}.${randomUUID2()}.tmp`);
13289
12676
  try {
13290
12677
  await writeFile(temporary, input.bytes, { flag: "wx" });
13291
12678
  await rename(temporary, destination);
@@ -13298,7 +12685,7 @@ var ResultImageStore = class {
13298
12685
  async deleteProcess(instanceId) {
13299
12686
  if (!isResultImageStorageSegment(instanceId))
13300
12687
  throw new Error("Invalid result image storage id");
13301
- await rm(path3.join(this.rootDir, instanceId), { recursive: true, force: true });
12688
+ await rm(path2.join(this.rootDir, instanceId), { recursive: true, force: true });
13302
12689
  }
13303
12690
  /** @internal */
13304
12691
  async cleanupProcesses(input) {
@@ -13313,7 +12700,7 @@ var ResultImageStore = class {
13313
12700
  for (const entry of entries) {
13314
12701
  if (!entry.isDirectory() || !isResultImageStorageSegment(entry.name) || input.retainedInstanceIds.has(entry.name) && !input.expiredInstanceIds?.has(entry.name))
13315
12702
  continue;
13316
- await rm(path3.join(this.rootDir, entry.name), { recursive: true, force: true });
12703
+ await rm(path2.join(this.rootDir, entry.name), { recursive: true, force: true });
13317
12704
  removed.push(entry.name);
13318
12705
  }
13319
12706
  return removed;
@@ -13323,7 +12710,7 @@ var ResultImageStore = class {
13323
12710
  const extension = parseResultImageId(imageId)?.extension;
13324
12711
  if (!extension) return null;
13325
12712
  try {
13326
- const bytes = await readFile2(path3.join(this.turnDir(instanceId, turnRecordId), imageId));
12713
+ const bytes = await readFile2(path2.join(this.turnDir(instanceId, turnRecordId), imageId));
13327
12714
  return {
13328
12715
  metadata: { imageId, mimeType: MIME_BY_EXTENSION[extension], byteSize: bytes.length },
13329
12716
  bytes
@@ -13468,8 +12855,8 @@ function createAppLifecycle(input) {
13468
12855
  }
13469
12856
 
13470
12857
  // src/server-bootstrap/build-host-capabilities.ts
13471
- import path4 from "node:path";
13472
- import { SYSTEM_ACTOR as SYSTEM_ACTOR6 } from "@leitwerk-dev/domain";
12858
+ import path3 from "node:path";
12859
+ import { SYSTEM_ACTOR as SYSTEM_ACTOR5 } from "@leitwerk-dev/domain";
13473
12860
  import {
13474
12861
  coreHostCapabilities,
13475
12862
  createCapabilityAccessor
@@ -13483,7 +12870,7 @@ function buildHostCapabilities(input) {
13483
12870
  return input.config.server.base_url;
13484
12871
  },
13485
12872
  get processWorkspacesDir() {
13486
- return path4.resolve(input.config.storage.process_workspaces_dir);
12873
+ return path3.resolve(input.config.storage.process_workspaces_dir);
13487
12874
  },
13488
12875
  components: input.config.components,
13489
12876
  externalWrites: input.baseDeps.externalWrites,
@@ -13512,13 +12899,13 @@ function buildHostCapabilities(input) {
13512
12899
  startProgrammatic(request, opts) {
13513
12900
  return input.launchCoordinator.startProgrammatic(request, {
13514
12901
  idempotencyKey: opts.idempotencyKey,
13515
- actor: opts.actor ?? SYSTEM_ACTOR6
12902
+ actor: opts.actor ?? SYSTEM_ACTOR5
13516
12903
  });
13517
12904
  },
13518
12905
  startWatcher(watcher, event, opts) {
13519
12906
  return input.launchCoordinator.startWatcher(watcher, event, {
13520
12907
  idempotencyKey: opts.idempotencyKey,
13521
- actor: opts.actor ?? SYSTEM_ACTOR6
12908
+ actor: opts.actor ?? SYSTEM_ACTOR5
13522
12909
  });
13523
12910
  }
13524
12911
  },
@@ -13810,7 +13197,7 @@ function registerInternalSessionTransferExportRoutes(app, service) {
13810
13197
  // src/routes/internal-worker-session-snapshot.ts
13811
13198
  import { mkdtemp, rm as rm2, writeFile as writeFile2 } from "node:fs/promises";
13812
13199
  import { tmpdir } from "node:os";
13813
- import path5 from "node:path";
13200
+ import path4 from "node:path";
13814
13201
  import { StringDecoder } from "node:string_decoder";
13815
13202
  import {
13816
13203
  WORKER_SESSION_SNAPSHOT_CONTENT_TYPE,
@@ -13909,8 +13296,8 @@ function validateJsonLine(line, lineNumber) {
13909
13296
  }
13910
13297
  }
13911
13298
  async function streamSnapshotToTempFile(payload, bodyLimit) {
13912
- const dir = await mkdtemp(path5.join(tmpdir(), "leitwerk-session-snapshot-"));
13913
- const file = path5.join(dir, "snapshot.jsonl");
13299
+ const dir = await mkdtemp(path4.join(tmpdir(), "leitwerk-session-snapshot-"));
13300
+ const file = path4.join(dir, "snapshot.jsonl");
13914
13301
  let bytes = 0;
13915
13302
  const decoder = new StringDecoder("utf8");
13916
13303
  let pendingLine = "";
@@ -14039,7 +13426,7 @@ function registerInternalWorkerSessionSnapshotRoutes(input) {
14039
13426
  await input.sessionSnapshots.writeSnapshotFile(instanceId, body.path);
14040
13427
  reply.code(204).send();
14041
13428
  } finally {
14042
- if (body?.path) await rm2(path5.dirname(body.path), { recursive: true, force: true });
13429
+ if (body?.path) await rm2(path4.dirname(body.path), { recursive: true, force: true });
14043
13430
  }
14044
13431
  return reply;
14045
13432
  }
@@ -14877,7 +14264,6 @@ var ProcessDiagnosticsAssembler = class {
14877
14264
  return null;
14878
14265
  }
14879
14266
  const projects = this.deps.projects.listByInstance(instanceId);
14880
- const piSessionTree = await this.deps.sessionReader.readPiSessionTree(instanceId);
14881
14267
  const recentEvents = this.deps.events.listByInstance(instanceId, 500);
14882
14268
  const retainedOperationalEvents = this.deps.events.listByInstanceEventTypes(
14883
14269
  instanceId,
@@ -14892,7 +14278,7 @@ var ProcessDiagnosticsAssembler = class {
14892
14278
  availability: this.deps.modelStatusCache.snapshot()
14893
14279
  })
14894
14280
  );
14895
- return {
14281
+ const detail = {
14896
14282
  process: process2,
14897
14283
  projects,
14898
14284
  inputs: this.deps.inputs.listByInstance(instanceId),
@@ -14904,7 +14290,6 @@ var ProcessDiagnosticsAssembler = class {
14904
14290
  processDisplayName: getProcessDisplayName(this.deps, process2.processId),
14905
14291
  processGraph: serializeProcessGraph(this.deps.processGraphs, process2.processId),
14906
14292
  processFlow: buildProcessFlowViewForProcess(this.deps.processGraphs, process2.processId),
14907
- piSessionEntries: piSessionTree.entries,
14908
14293
  definesLeafOutcome: processDefinesLeafOutcome(this.deps, process2),
14909
14294
  selectedTurn: getSelectedTurnSummaryForProcess(this.deps, process2),
14910
14295
  scheduledAction: getScheduledActionDetailForProcess(this.deps, process2),
@@ -14914,6 +14299,8 @@ var ProcessDiagnosticsAssembler = class {
14914
14299
  actions: listVisibleActionsForProcess2(this.deps, process2),
14915
14300
  toolRenderers: [...this.deps.toolRenderers?.values() ?? []]
14916
14301
  };
14302
+ const piSessionTree = await this.deps.sessionReader.readPiSessionTree(instanceId);
14303
+ return { ...detail, piSessionEntries: piSessionTree.entries };
14917
14304
  }
14918
14305
  async assembleRetryConfig(instanceId) {
14919
14306
  const process2 = this.deps.processes.getById(instanceId);
@@ -14961,12 +14348,12 @@ var ProcessPrimaryPathAssembler = class {
14961
14348
  this.deps = deps;
14962
14349
  }
14963
14350
  deps;
14964
- capture(instanceId, overrides = {}) {
14965
- const process2 = overrides.process ?? this.deps.processes.getById(instanceId);
14351
+ capture(instanceId) {
14352
+ const process2 = this.deps.processes.getById(instanceId);
14966
14353
  if (!process2) {
14967
14354
  return null;
14968
14355
  }
14969
- const turnRecords = overrides.turnRecords ?? this.deps.turnRecords.listByInstance(process2.id);
14356
+ const turnRecords = this.deps.turnRecords.listByInstance(process2.id);
14970
14357
  const currentTurnRecordId = resolveCurrentExecutionTurnRecordId(process2, this.deps.turnStarts);
14971
14358
  const activeTurnRecord = currentTurnRecordId ? turnRecords.find(
14972
14359
  (turnRecord) => turnRecord.id === currentTurnRecordId && turnRecord.status === "running"
@@ -14989,26 +14376,20 @@ var ProcessPrimaryPathAssembler = class {
14989
14376
  return {
14990
14377
  process: process2,
14991
14378
  currentExecutionTurnRecordId: currentTurnRecordId,
14992
- workerLease: overrides.workerLease !== void 0 ? overrides.workerLease : this.deps.leases.getByInstance(process2.id),
14379
+ workerLease: this.deps.leases.getByInstance(process2.id),
14993
14380
  turnRecords,
14994
- turnAnnotations: overrides.turnAnnotations ?? this.deps.turnAnnotations.listByInstance(process2.id),
14381
+ turnAnnotations: this.deps.turnAnnotations.listByInstance(process2.id),
14995
14382
  events,
14996
14383
  eventWindowTruncated
14997
14384
  };
14998
14385
  }
14999
- project(captured, session) {
15000
- return buildPrimaryPathSnapshotFromTree({
15001
- ...captured,
15002
- tree: session.parsedTree
15003
- });
15004
- }
15005
14386
  async assemble(instanceId) {
15006
14387
  const captured = this.capture(instanceId);
15007
14388
  if (!captured) {
15008
14389
  return null;
15009
14390
  }
15010
14391
  const session = await this.deps.sessionReader.readSessionTree(instanceId);
15011
- return this.project(captured, session);
14392
+ return buildPrimaryPathSnapshotFromTree({ ...captured, tree: session.parsedTree });
15012
14393
  }
15013
14394
  };
15014
14395
 
@@ -15912,7 +15293,7 @@ function registerHttp(input) {
15912
15293
 
15913
15294
  // src/server-topology.ts
15914
15295
  import { readFileSync } from "node:fs";
15915
- var defaultFileReader = (path10) => readFileSync(path10, "utf8");
15296
+ var defaultFileReader = (path9) => readFileSync(path9, "utf8");
15916
15297
  function resolveServerTlsOptions(config, readFile5 = defaultFileReader) {
15917
15298
  const tls = config.internal_tls;
15918
15299
  if (!tls || tls.enabled !== true) {
@@ -16087,21 +15468,21 @@ function createSessionTransferHelperRelays(deps) {
16087
15468
  import { execFile } from "node:child_process";
16088
15469
  import { mkdtemp as mkdtemp2, readdir as readdir2, readFile as readFile4, rm as rm3 } from "node:fs/promises";
16089
15470
  import { tmpdir as tmpdir2 } from "node:os";
16090
- import path6 from "node:path";
15471
+ import path5 from "node:path";
16091
15472
  import { promisify } from "node:util";
16092
15473
  import {
16093
- createCanonicalPiResourceBundle as createCanonicalPiResourceBundle2
15474
+ createCanonicalPiResourceBundle
16094
15475
  } from "@leitwerk-dev/worker-protocol";
16095
15476
  var execFileAsync = promisify(execFile);
16096
15477
  var GIT_ENV = { ...process.env, GIT_TERMINAL_PROMPT: "0", GIT_ASKPASS: "/bin/false" };
16097
15478
  var FORBIDDEN_SKILL_NAMES = /* @__PURE__ */ new Set([".git"]);
16098
15479
  function isWithin(root, candidate) {
16099
- const relative = path6.relative(root, candidate);
16100
- return relative === "" || relative !== ".." && !relative.startsWith(`..${path6.sep}`);
15480
+ const relative = path5.relative(root, candidate);
15481
+ return relative === "" || relative !== ".." && !relative.startsWith(`..${path5.sep}`);
16101
15482
  }
16102
15483
  async function importSkillDirectory(root, skill, sourceRevision) {
16103
15484
  const collector = new ResourceCollector();
16104
- await collector.addDirectory(path6.resolve(root), `skills/${skill.id}`, SKILL_RESOURCE_OWNER, {
15485
+ await collector.addDirectory(path5.resolve(root), `skills/${skill.id}`, SKILL_RESOURCE_OWNER, {
16105
15486
  forbiddenNames: FORBIDDEN_SKILL_NAMES
16106
15487
  });
16107
15488
  const files = collector.toResourceFiles();
@@ -16112,7 +15493,7 @@ async function importSkillDirectory(root, skill, sourceRevision) {
16112
15493
  skillId: skill.id,
16113
15494
  label: skill.label ?? skill.id,
16114
15495
  description: skill.description ?? null,
16115
- bundle: createCanonicalPiResourceBundle2(files),
15496
+ bundle: createCanonicalPiResourceBundle(files),
16116
15497
  sourceRevision
16117
15498
  };
16118
15499
  }
@@ -16144,14 +15525,14 @@ async function discoverSkillRoots(catalogRoot) {
16144
15525
  const entries = (await readdir2(directory, { withFileTypes: true })).sort(
16145
15526
  (left, right) => left.name.localeCompare(right.name)
16146
15527
  );
16147
- const skillId = path6.basename(directory);
15528
+ const skillId = path5.basename(directory);
16148
15529
  if (SAFE_SKILL_ID_PATTERN.test(skillId) && entries.some((entry) => entry.name === "SKILL.md" && entry.isFile())) {
16149
15530
  result.push(directory);
16150
15531
  return;
16151
15532
  }
16152
15533
  for (const entry of entries) {
16153
15534
  if (entry.isDirectory() && entry.name !== ".git") {
16154
- await visit(path6.join(directory, entry.name));
15535
+ await visit(path5.join(directory, entry.name));
16155
15536
  }
16156
15537
  }
16157
15538
  };
@@ -16159,20 +15540,20 @@ async function discoverSkillRoots(catalogRoot) {
16159
15540
  return result;
16160
15541
  }
16161
15542
  function repositorySourcePath(checkoutRoot, skillRoot) {
16162
- return path6.relative(checkoutRoot, skillRoot).split(path6.sep).join(path6.posix.sep);
15543
+ return path5.relative(checkoutRoot, skillRoot).split(path5.sep).join(path5.posix.sep);
16163
15544
  }
16164
15545
  async function importSkillRepository(repository) {
16165
- const tempRoot = await mkdtemp2(path6.join(tmpdir2(), "leitwerk-skill-repository-"));
15546
+ const tempRoot = await mkdtemp2(path5.join(tmpdir2(), "leitwerk-skill-repository-"));
16166
15547
  try {
16167
- const checkout = await checkoutGitSource(repository, path6.join(tempRoot, "checkout"));
16168
- const catalogRoot = path6.resolve(checkout.root, repository.path ?? "skills");
15548
+ const checkout = await checkoutGitSource(repository, path5.join(tempRoot, "checkout"));
15549
+ const catalogRoot = path5.resolve(checkout.root, repository.path ?? "skills");
16169
15550
  if (!isWithin(checkout.root, catalogRoot)) {
16170
15551
  throw new Error(`Skill repository '${repository.id}' path escapes its checkout`);
16171
15552
  }
16172
15553
  const skillRoots = await discoverSkillRoots(catalogRoot);
16173
15554
  const rootsById = /* @__PURE__ */ new Map();
16174
15555
  for (const skillRoot of skillRoots) {
16175
- const skillId = path6.basename(skillRoot);
15556
+ const skillId = path5.basename(skillRoot);
16176
15557
  const previous = rootsById.get(skillId);
16177
15558
  if (previous) {
16178
15559
  throw new Error(
@@ -16183,8 +15564,8 @@ async function importSkillRepository(repository) {
16183
15564
  }
16184
15565
  const skills = [];
16185
15566
  for (const skillRoot of skillRoots) {
16186
- const skillId = path6.basename(skillRoot);
16187
- const markdown = await readFile4(path6.join(skillRoot, "SKILL.md"), "utf8");
15567
+ const skillId = path5.basename(skillRoot);
15568
+ const markdown = await readFile4(path5.join(skillRoot, "SKILL.md"), "utf8");
16188
15569
  const imported = await importSkillDirectory(
16189
15570
  skillRoot,
16190
15571
  {
@@ -16279,12 +15660,12 @@ function createSkillCatalogService(input) {
16279
15660
 
16280
15661
  // src/supervisor/diagnostic-trace-writer.ts
16281
15662
  import { appendFileSync, mkdirSync } from "node:fs";
16282
- import path7 from "node:path";
15663
+ import path6 from "node:path";
16283
15664
  function createDiagnosticTraceWriter(directory) {
16284
15665
  mkdirSync(directory, { recursive: true, mode: 448 });
16285
15666
  return {
16286
15667
  append(instanceId, text) {
16287
- appendFileSync(path7.join(directory, `${instanceId}.log`), text, {
15668
+ appendFileSync(path6.join(directory, `${instanceId}.log`), text, {
16288
15669
  encoding: "utf8",
16289
15670
  mode: 384
16290
15671
  });
@@ -16760,6 +16141,7 @@ function createWorkerTurnIpcRecorder(deps, callbacks) {
16760
16141
  return;
16761
16142
  }
16762
16143
  const fallback = await deps.commands.recordWorkerFailure(input.instanceId, {
16144
+ workerLeaseId: input.workerLeaseId,
16763
16145
  errorCode: details.code,
16764
16146
  message: `Server could not durably record worker turn ${input.terminalType}: ${details.message}`,
16765
16147
  errorClass: "infrastructure",
@@ -16803,7 +16185,7 @@ function createWorkerTurnIpcRecorder(deps, callbacks) {
16803
16185
  }
16804
16186
  };
16805
16187
  return {
16806
- recordTurnOutcome(instanceId, workerId, payload) {
16188
+ recordTurnOutcome(instanceId, workerId, workerLeaseId, payload) {
16807
16189
  const { turnId, ...rest } = payload;
16808
16190
  if (terminalWasAlreadyRecorded(deps, rest.turnRecordId, "outcome")) {
16809
16191
  acknowledge(instanceId, workerId, rest.turnRecordId);
@@ -16815,6 +16197,7 @@ function createWorkerTurnIpcRecorder(deps, callbacks) {
16815
16197
  void recordTerminal({
16816
16198
  instanceId,
16817
16199
  workerId,
16200
+ workerLeaseId,
16818
16201
  turnRecordId: rest.turnRecordId,
16819
16202
  terminalType: "outcome",
16820
16203
  record: () => deps.commands.recordTurnOutcome(
@@ -16832,12 +16215,13 @@ function createWorkerTurnIpcRecorder(deps, callbacks) {
16832
16215
  recoveryContext: createGenericFailedTurnRecoveryContext()
16833
16216
  });
16834
16217
  },
16835
- recordTurnFailed(instanceId, workerId, payload) {
16218
+ recordTurnFailed(instanceId, workerId, workerLeaseId, payload) {
16836
16219
  const { errorClass, failureCode, failureDetails: details, ...rest } = payload;
16837
16220
  if (errorClass !== void 0 && !isWorkerErrorClass(errorClass)) {
16838
16221
  void recoverRecordingFailure({
16839
16222
  instanceId,
16840
16223
  workerId,
16224
+ workerLeaseId,
16841
16225
  turnRecordId: rest.turnRecordId,
16842
16226
  terminalType: "failure",
16843
16227
  failure: new Error(`Invalid worker error class '${errorClass}'`)
@@ -16855,6 +16239,7 @@ function createWorkerTurnIpcRecorder(deps, callbacks) {
16855
16239
  void recordTerminal({
16856
16240
  instanceId,
16857
16241
  workerId,
16242
+ workerLeaseId,
16858
16243
  turnRecordId: rest.turnRecordId,
16859
16244
  terminalType: "failure",
16860
16245
  record: () => deps.commands.recordTurnFailed(
@@ -17042,32 +16427,41 @@ function createIpcHandler(deps, callbacks) {
17042
16427
  break;
17043
16428
  }
17044
16429
  case "worker.turn_started": {
17045
- void deps.commands.acceptWorkerTurnStart(instanceId, {
17046
- workerLeaseId: activeLease.id,
17047
- startRecordId: msg.payload.startRecordId,
17048
- proposedTurnRecordId: msg.payload.proposedTurnRecordId
17049
- }).then((result) => {
17050
- if (!result.ok || !result.data) {
16430
+ let accepted = false;
16431
+ const onRecorded = (turnRecordId) => {
16432
+ accepted = true;
16433
+ eventIngestor.noteTurnStarted(instanceId, turnRecordId);
16434
+ callbacks.onWorkerTurnStartAccepted?.(instanceId, workerId, {
16435
+ startRecordId: msg.payload.startRecordId,
16436
+ turnRecordId
16437
+ });
16438
+ };
16439
+ void deps.commands.acceptWorkerTurnStart(
16440
+ instanceId,
16441
+ {
16442
+ workerLeaseId: activeLease.id,
16443
+ startRecordId: msg.payload.startRecordId,
16444
+ proposedTurnRecordId: msg.payload.proposedTurnRecordId
16445
+ },
16446
+ { onRecorded }
16447
+ ).then(() => {
16448
+ if (!accepted) {
17051
16449
  callbacks.onWorkerFailed?.(instanceId, workerId, "Worker turn start was rejected");
17052
16450
  return;
17053
16451
  }
17054
- eventIngestor.noteTurnStarted(instanceId, result.data.turnRecordId);
17055
16452
  launchCoordinator?.refresh(instanceId);
17056
- callbacks.onWorkerTurnStartAccepted?.(instanceId, workerId, {
17057
- startRecordId: msg.payload.startRecordId,
17058
- turnRecordId: result.data.turnRecordId
17059
- });
17060
- }).catch(
17061
- () => callbacks.onWorkerFailed?.(instanceId, workerId, "Worker turn start failed")
17062
- );
16453
+ }).catch(() => {
16454
+ if (!accepted)
16455
+ callbacks.onWorkerFailed?.(instanceId, workerId, "Worker turn start failed");
16456
+ });
17063
16457
  break;
17064
16458
  }
17065
16459
  case "worker.turn_outcome": {
17066
- turnRecorder.recordTurnOutcome(instanceId, workerId, msg.payload);
16460
+ turnRecorder.recordTurnOutcome(instanceId, workerId, activeLease.id, msg.payload);
17067
16461
  break;
17068
16462
  }
17069
16463
  case "worker.turn_failed": {
17070
- turnRecorder.recordTurnFailed(instanceId, workerId, msg.payload);
16464
+ turnRecorder.recordTurnFailed(instanceId, workerId, activeLease.id, msg.payload);
17071
16465
  break;
17072
16466
  }
17073
16467
  case "worker.lifecycle_parked": {
@@ -17567,8 +16961,8 @@ function decideIdleWorkerStop(input) {
17567
16961
  }
17568
16962
 
17569
16963
  // 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 = {}) {
16964
+ import { WORKER_API_VERSION } from "@leitwerk-dev/worker-protocol";
16965
+ function checkWorkerApiCompatibility(payload, expectedApiVersion = WORKER_API_VERSION, options = {}) {
17572
16966
  if (payload.apiVersion === void 0) {
17573
16967
  if (options.requireApiVersion === true) {
17574
16968
  return {
@@ -17716,7 +17110,7 @@ function createWorkerShutdownController(input) {
17716
17110
 
17717
17111
  // src/supervisor/worker-start-payload-builder.ts
17718
17112
  import { randomUUID as randomUUID5 } from "node:crypto";
17719
- import path8 from "node:path";
17113
+ import path7 from "node:path";
17720
17114
  import { parseProductRefsFromStateJsonLenient } from "@leitwerk-dev/domain";
17721
17115
  import { parseDurationMs as parseDurationMs6 } from "@leitwerk-dev/watcher-utils";
17722
17116
  import {
@@ -17834,6 +17228,22 @@ function buildTurnResultMarkdownByProduct(process2, deps) {
17834
17228
  }
17835
17229
  return Object.keys(byProduct).length > 0 ? byProduct : void 0;
17836
17230
  }
17231
+ function resolveMappedItem(start, deps) {
17232
+ if (!start.iteration) return void 0;
17233
+ const run = deps.mappedRuns?.getById(start.iteration.runId);
17234
+ const item = deps.mappedRuns?.getItem(start.iteration.runId, start.iteration.itemIndex);
17235
+ if (!run || !item || item.itemKey !== start.iteration.itemKey) {
17236
+ throw new Error(`Mapped item for worker start '${start.id}' is unavailable`);
17237
+ }
17238
+ return {
17239
+ runId: run.id,
17240
+ itemKey: item.itemKey,
17241
+ itemLabel: item.label,
17242
+ itemIndex: item.itemIndex,
17243
+ itemCount: run.itemCount,
17244
+ item: JSON.parse(item.itemJson)
17245
+ };
17246
+ }
17837
17247
  function resolveLlmPreparation(start, deps) {
17838
17248
  const sourceTurnRecordId = start.state.kind === "accepted" ? start.state.turnRecordId : start.startKind === "continue" ? start.recoveryTurnRecordId : null;
17839
17249
  if (!sourceTurnRecordId) return void 0;
@@ -17904,6 +17314,7 @@ function createWorkerStartPayloadBuilder(deps) {
17904
17314
  const llmPreparation = start.turnType === "llm" ? resolveLlmPreparation(start, deps) : void 0;
17905
17315
  const resumeLeafEntryId = treePaths.resume ? deps.turnRecords.getLatestSucceededPrimaryByInstance(instanceId)?.resultPiEntryId ?? null : null;
17906
17316
  const contextSnapshot = buildWorkerRuntimeContextSnapshot(process2, start);
17317
+ const iteration = resolveMappedItem(start, deps);
17907
17318
  const repositoryCredentials = deps.resolveRepositoryCredentials?.({
17908
17319
  process: process2,
17909
17320
  projects: deps.projects.listByInstance(process2.id)
@@ -17946,13 +17357,14 @@ function createWorkerStartPayloadBuilder(deps) {
17946
17357
  30 * 60 * 1e3,
17947
17358
  { allowHours: true }
17948
17359
  ),
17949
- processStorageRoot: deps.config.workers.runner === "local" ? treePaths.workspaceRoot : path8.dirname(treePaths.workspaceRoot)
17360
+ processStorageRoot: deps.config.workers.runner === "local" ? treePaths.workspaceRoot : path7.dirname(treePaths.workspaceRoot)
17950
17361
  },
17951
17362
  ...treePaths.resume ? { resumeLeafEntryId } : {},
17952
17363
  ...llmPreparation ? { llmPreparation } : {},
17953
17364
  ...repositoryCredentials.length > 0 ? { repositoryCredentials } : {},
17954
17365
  ...dockerRegistryCredentials.length > 0 ? { dockerRegistryCredentials } : {},
17955
- ...integrationTools && integrationTools.length > 0 ? { integrationTools } : {}
17366
+ ...integrationTools && integrationTools.length > 0 ? { integrationTools } : {},
17367
+ ...iteration ? { iteration } : {}
17956
17368
  };
17957
17369
  const payload = bootstrap.kind === "llm" ? {
17958
17370
  ...payloadBase,
@@ -19400,7 +18812,7 @@ ${configErrors.join("\n")}`);
19400
18812
  for (const process2 of repos.processes.listAll()) await sessionSnapshots.backfill(process2.id);
19401
18813
  const sessionReader = new ProcessSessionReader(sessionSnapshots);
19402
18814
  const resultImages = new ResultImageStore({
19403
- rootDir: path9.join(config.storage.tree_files_dir, "result-images")
18815
+ rootDir: path8.join(config.storage.tree_files_dir, "result-images")
19404
18816
  });
19405
18817
  const authService = createAuthService({ config, repos });
19406
18818
  await registerWebsocket(app, broadcaster, workerWebSocketIpc, authService);
@@ -19580,6 +18992,7 @@ ${configErrors.join("\n")}`);
19580
18992
  turnStarts: baseDeps.turnStarts,
19581
18993
  leases: baseDeps.leases,
19582
18994
  turnAnnotations: baseDeps.turnAnnotations,
18995
+ mappedRuns: baseDeps.mappedRuns,
19583
18996
  transaction: baseDeps.transaction,
19584
18997
  broadcaster,
19585
18998
  config,
@@ -19640,7 +19053,7 @@ ${configErrors.join("\n")}`);
19640
19053
  toolApprovalGate
19641
19054
  });
19642
19055
  const diagnosticTraceWriter = createDiagnosticTraceWriter(
19643
- path9.join(config.storage.tree_files_dir, "diagnostic-traces")
19056
+ path8.join(config.storage.tree_files_dir, "diagnostic-traces")
19644
19057
  );
19645
19058
  const ipcHandler = createIpcHandler(
19646
19059
  {
@@ -19762,6 +19175,7 @@ ${configErrors.join("\n")}`);
19762
19175
  inputs: baseDeps.inputs,
19763
19176
  turnRecords: baseDeps.turnRecords,
19764
19177
  turnStarts: baseDeps.turnStarts,
19178
+ mappedRuns: baseDeps.mappedRuns,
19765
19179
  events: baseDeps.events,
19766
19180
  broadcaster,
19767
19181
  runnerRuntime,
@@ -20163,4 +19577,4 @@ ${configErrors.join("\n")}`);
20163
19577
  export {
20164
19578
  createAppContext
20165
19579
  };
20166
- //# sourceMappingURL=chunk-CNITOV76.js.map
19580
+ //# sourceMappingURL=chunk-QCHS3X33.js.map