@leitwerk-dev/server 0.1.7 → 0.1.9

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 (192) hide show
  1. package/dist/app.d.ts.map +1 -1
  2. package/dist/app.js +24 -15
  3. package/dist/app.js.map +1 -1
  4. package/dist/{chunk-GIWHTJSL.js → chunk-2ESDXLNE.js} +228 -101
  5. package/dist/chunk-2ESDXLNE.js.map +1 -0
  6. package/dist/{chunk-OO6VH4FX.js → chunk-DFHOPJRZ.js} +405 -259
  7. package/dist/chunk-DFHOPJRZ.js.map +1 -0
  8. package/dist/config/config-loader.d.ts.map +1 -1
  9. package/dist/config/config-loader.js +14 -25
  10. package/dist/config/config-loader.js.map +1 -1
  11. package/dist/config/config-types.d.ts +5 -17
  12. package/dist/config/config-types.d.ts.map +1 -1
  13. package/dist/db/skill-repo.d.ts +2 -2
  14. package/dist/db/skill-repo.d.ts.map +1 -1
  15. package/dist/db/skill-repo.js +24 -32
  16. package/dist/db/skill-repo.js.map +1 -1
  17. package/dist/external-source-service.d.ts.map +1 -1
  18. package/dist/external-source-service.js +5 -2
  19. package/dist/external-source-service.js.map +1 -1
  20. package/dist/future-execution/execution.d.ts +1 -1
  21. package/dist/future-execution/execution.d.ts.map +1 -1
  22. package/dist/future-execution/execution.js +1 -13
  23. package/dist/future-execution/execution.js.map +1 -1
  24. package/dist/integration-tool-registry.js +1 -1
  25. package/dist/integration-tool-registry.js.map +1 -1
  26. package/dist/model-providers/builtin-server-adapter.d.ts.map +1 -1
  27. package/dist/model-providers/builtin-server-adapter.js +10 -2
  28. package/dist/model-providers/builtin-server-adapter.js.map +1 -1
  29. package/dist/process-action-registry.d.ts +2 -4
  30. package/dist/process-action-registry.d.ts.map +1 -1
  31. package/dist/process-action-registry.js +31 -28
  32. package/dist/process-action-registry.js.map +1 -1
  33. package/dist/process-engine/engine.d.ts.map +1 -1
  34. package/dist/process-engine/engine.js +4 -4
  35. package/dist/process-engine/engine.js.map +1 -1
  36. package/dist/process-engine/operation.d.ts +4 -0
  37. package/dist/process-engine/operation.d.ts.map +1 -1
  38. package/dist/process-engine/ops/execute-action.d.ts.map +1 -1
  39. package/dist/process-engine/ops/execute-action.js +0 -3
  40. package/dist/process-engine/ops/execute-action.js.map +1 -1
  41. package/dist/process-engine/ops/worker-failure.d.ts +2 -0
  42. package/dist/process-engine/ops/worker-failure.d.ts.map +1 -1
  43. package/dist/process-engine/ops/worker-failure.js +2 -0
  44. package/dist/process-engine/ops/worker-failure.js.map +1 -1
  45. package/dist/process-engine/runner.d.ts +2 -2
  46. package/dist/process-engine/runner.d.ts.map +1 -1
  47. package/dist/process-engine/runner.js +13 -1
  48. package/dist/process-engine/runner.js.map +1 -1
  49. package/dist/process-engine/types.d.ts +10 -4
  50. package/dist/process-engine/types.d.ts.map +1 -1
  51. package/dist/process-engine/writes/build-server-transition-writes.d.ts.map +1 -1
  52. package/dist/process-engine/writes/build-server-transition-writes.js +2 -8
  53. package/dist/process-engine/writes/build-server-transition-writes.js.map +1 -1
  54. package/dist/process-engine/writes/build-turn-outcome-writes.d.ts.map +1 -1
  55. package/dist/process-engine/writes/build-turn-outcome-writes.js +1 -2
  56. package/dist/process-engine/writes/build-turn-outcome-writes.js.map +1 -1
  57. package/dist/process-engine/writes/build-turn-selection-writes.d.ts +1 -2
  58. package/dist/process-engine/writes/build-turn-selection-writes.d.ts.map +1 -1
  59. package/dist/process-engine/writes/build-turn-selection-writes.js +1 -57
  60. package/dist/process-engine/writes/build-turn-selection-writes.js.map +1 -1
  61. package/dist/process-engine/writes/build-worker-failure-writes.d.ts +3 -1
  62. package/dist/process-engine/writes/build-worker-failure-writes.d.ts.map +1 -1
  63. package/dist/process-engine/writes/build-worker-failure-writes.js +2 -1
  64. package/dist/process-engine/writes/build-worker-failure-writes.js.map +1 -1
  65. package/dist/process-launch-executor.d.ts +6 -4
  66. package/dist/process-launch-executor.d.ts.map +1 -1
  67. package/dist/process-launch-executor.js +16 -1
  68. package/dist/process-launch-executor.js.map +1 -1
  69. package/dist/process-launch-plan.d.ts.map +1 -1
  70. package/dist/process-launch-plan.js +1 -0
  71. package/dist/process-launch-plan.js.map +1 -1
  72. package/dist/process-operator-attention.d.ts +1 -1
  73. package/dist/process-operator-attention.d.ts.map +1 -1
  74. package/dist/process-operator-attention.js +1 -1
  75. package/dist/process-operator-attention.js.map +1 -1
  76. package/dist/process-ui-snapshot-presenter.d.ts.map +1 -1
  77. package/dist/process-ui-snapshot-presenter.js +24 -3
  78. package/dist/process-ui-snapshot-presenter.js.map +1 -1
  79. package/dist/process-watcher-registry.d.ts.map +1 -1
  80. package/dist/process-watcher-registry.js +13 -5
  81. package/dist/process-watcher-registry.js.map +1 -1
  82. package/dist/routes/skills.d.ts.map +1 -1
  83. package/dist/routes/skills.js +1 -2
  84. package/dist/routes/skills.js.map +1 -1
  85. package/dist/server-automatic-turn-drainer.d.ts.map +1 -1
  86. package/dist/server-automatic-turn-drainer.js +15 -0
  87. package/dist/server-automatic-turn-drainer.js.map +1 -1
  88. package/dist/server-bootstrap/build-host-capabilities.d.ts.map +1 -1
  89. package/dist/server-bootstrap/build-host-capabilities.js +1 -0
  90. package/dist/server-bootstrap/build-host-capabilities.js.map +1 -1
  91. package/dist/skills/skill-frontmatter.d.ts +4 -0
  92. package/dist/skills/skill-frontmatter.d.ts.map +1 -0
  93. package/dist/skills/skill-frontmatter.js +13 -0
  94. package/dist/skills/skill-frontmatter.js.map +1 -0
  95. package/dist/skills/source-importer.d.ts +2 -3
  96. package/dist/skills/source-importer.d.ts.map +1 -1
  97. package/dist/skills/source-importer.js +16 -62
  98. package/dist/skills/source-importer.js.map +1 -1
  99. package/dist/supervisor/accepted-turn-start-replay.d.ts +9 -0
  100. package/dist/supervisor/accepted-turn-start-replay.d.ts.map +1 -0
  101. package/dist/supervisor/accepted-turn-start-replay.js +23 -0
  102. package/dist/supervisor/accepted-turn-start-replay.js.map +1 -0
  103. package/dist/supervisor/ipc-handler.d.ts +9 -0
  104. package/dist/supervisor/ipc-handler.d.ts.map +1 -1
  105. package/dist/supervisor/ipc-handler.js +9 -4
  106. package/dist/supervisor/ipc-handler.js.map +1 -1
  107. package/dist/supervisor/stale-heartbeat-watchdog.d.ts +1 -1
  108. package/dist/supervisor/stale-heartbeat-watchdog.d.ts.map +1 -1
  109. package/dist/supervisor/stale-heartbeat-watchdog.js +47 -5
  110. package/dist/supervisor/stale-heartbeat-watchdog.js.map +1 -1
  111. package/dist/supervisor/worker-event-ingestor.d.ts.map +1 -1
  112. package/dist/supervisor/worker-event-ingestor.js +16 -0
  113. package/dist/supervisor/worker-event-ingestor.js.map +1 -1
  114. package/dist/supervisor/worker-start-payload-builder.d.ts +2 -4
  115. package/dist/supervisor/worker-start-payload-builder.d.ts.map +1 -1
  116. package/dist/supervisor/worker-start-payload-builder.js +3 -1
  117. package/dist/supervisor/worker-start-payload-builder.js.map +1 -1
  118. package/dist/supervisor/worker-supervisor.d.ts +4 -5
  119. package/dist/supervisor/worker-supervisor.d.ts.map +1 -1
  120. package/dist/supervisor/worker-supervisor.js +31 -0
  121. package/dist/supervisor/worker-supervisor.js.map +1 -1
  122. package/dist/supervisor/worker-turn-ipc-recorder.d.ts +12 -3
  123. package/dist/supervisor/worker-turn-ipc-recorder.d.ts.map +1 -1
  124. package/dist/supervisor/worker-turn-ipc-recorder.js +129 -33
  125. package/dist/supervisor/worker-turn-ipc-recorder.js.map +1 -1
  126. package/dist/supervisor/worker-websocket-ipc.d.ts.map +1 -1
  127. package/dist/supervisor/worker-websocket-ipc.js +20 -10
  128. package/dist/supervisor/worker-websocket-ipc.js.map +1 -1
  129. package/dist/test-helpers/fake-worker-supervisor.d.ts.map +1 -1
  130. package/dist/test-helpers/fake-worker-supervisor.js +4 -0
  131. package/dist/test-helpers/fake-worker-supervisor.js.map +1 -1
  132. package/dist/test-helpers/ipc-handler-harness.d.ts.map +1 -1
  133. package/dist/test-helpers/ipc-handler-harness.js +1 -20
  134. package/dist/test-helpers/ipc-handler-harness.js.map +1 -1
  135. package/dist/test-helpers/process-fixtures.d.ts +1 -1
  136. package/dist/test-helpers/process-fixtures.d.ts.map +1 -1
  137. package/dist/test-helpers/process-fixtures.js +0 -6
  138. package/dist/test-helpers/process-fixtures.js.map +1 -1
  139. package/dist/turn-progress.d.ts +12 -0
  140. package/dist/turn-progress.d.ts.map +1 -0
  141. package/dist/turn-progress.js +108 -0
  142. package/dist/turn-progress.js.map +1 -0
  143. package/dist/{writes-DUwQe8MD.d.ts → writes-DNXpryd0.d.ts} +68 -36
  144. package/package.json +10 -10
  145. package/src/app.ts +25 -15
  146. package/src/config/config-loader.ts +33 -25
  147. package/src/config/config-types.ts +6 -13
  148. package/src/db/skill-repo.ts +26 -36
  149. package/src/external-source-service.ts +5 -2
  150. package/src/future-execution/execution.ts +2 -13
  151. package/src/integration-tool-registry.ts +1 -1
  152. package/src/model-providers/builtin-server-adapter.ts +10 -2
  153. package/src/process-action-registry.ts +48 -40
  154. package/src/process-engine/engine.ts +6 -4
  155. package/src/process-engine/operation.ts +5 -0
  156. package/src/process-engine/ops/execute-action.ts +0 -3
  157. package/src/process-engine/ops/worker-failure.ts +4 -0
  158. package/src/process-engine/runner.ts +13 -0
  159. package/src/process-engine/types.ts +14 -2
  160. package/src/process-engine/writes/build-server-transition-writes.ts +1 -14
  161. package/src/process-engine/writes/build-turn-outcome-writes.ts +1 -2
  162. package/src/process-engine/writes/build-turn-selection-writes.ts +0 -75
  163. package/src/process-engine/writes/build-worker-failure-writes.ts +4 -1
  164. package/src/process-launch-executor.ts +24 -15
  165. package/src/process-launch-plan.ts +1 -0
  166. package/src/process-operator-attention.ts +7 -3
  167. package/src/process-ui-snapshot-presenter.ts +24 -6
  168. package/src/process-watcher-registry.ts +15 -5
  169. package/src/routes/skills.ts +1 -3
  170. package/src/server-automatic-turn-drainer.ts +20 -1
  171. package/src/server-bootstrap/build-host-capabilities.ts +1 -0
  172. package/src/skills/skill-frontmatter.ts +13 -0
  173. package/src/skills/source-importer.ts +20 -82
  174. package/src/supervisor/accepted-turn-start-replay.ts +40 -0
  175. package/src/supervisor/ipc-handler.ts +18 -4
  176. package/src/supervisor/stale-heartbeat-watchdog.ts +55 -6
  177. package/src/supervisor/worker-event-ingestor.ts +15 -0
  178. package/src/supervisor/worker-start-payload-builder.ts +5 -2
  179. package/src/supervisor/worker-supervisor.ts +43 -4
  180. package/src/supervisor/worker-turn-ipc-recorder.ts +185 -46
  181. package/src/supervisor/worker-websocket-ipc.ts +28 -13
  182. package/src/test-helpers/fake-worker-supervisor.ts +4 -0
  183. package/src/test-helpers/ipc-handler-harness.ts +1 -22
  184. package/src/test-helpers/process-fixtures.ts +1 -6
  185. package/src/turn-progress.ts +114 -0
  186. package/dist/chunk-GIWHTJSL.js.map +0 -1
  187. package/dist/chunk-OO6VH4FX.js.map +0 -1
  188. package/dist/skills/catalog-sync.d.ts +0 -9
  189. package/dist/skills/catalog-sync.d.ts.map +0 -1
  190. package/dist/skills/catalog-sync.js +0 -7
  191. package/dist/skills/catalog-sync.js.map +0 -1
  192. package/src/skills/catalog-sync.ts +0 -13
@@ -58,6 +58,7 @@ import {
58
58
  processDefinesLeafOutcome,
59
59
  publicEngineFailureMessage,
60
60
  publicInternalEngineFailureMessage,
61
+ recordTurnProgress,
61
62
  requireApiActor,
62
63
  resolveActor,
63
64
  resolveCommitMessageMetadata,
@@ -68,10 +69,11 @@ import {
68
69
  sendLauncherRequestNormalizationError,
69
70
  sendScheduledActionMutationResponse,
70
71
  serializeProcessGraph,
72
+ skillFrontmatter,
71
73
  snapshotLiveTurnProjection,
72
74
  truncateTextAtWordBoundary,
73
75
  validateConfig
74
- } from "./chunk-GIWHTJSL.js";
76
+ } from "./chunk-2ESDXLNE.js";
75
77
 
76
78
  // src/extension-ui/catalog.ts
77
79
  import { readFile, stat } from "fs/promises";
@@ -432,7 +434,6 @@ function createExtensionHost() {
432
434
 
433
435
  // src/process-engine/writes/build-turn-selection-writes.ts
434
436
  import {
435
- isWaitingTurnType,
436
437
  lifecycleStatusForSelectedTurnType
437
438
  } from "@leitwerk-dev/domain";
438
439
 
@@ -726,55 +727,6 @@ function validateTurnSelectionWorkerIntent(processGraphs, process2, targetTurnId
726
727
  }
727
728
  return null;
728
729
  }
729
- function parseReviewSubjectFromState(value) {
730
- if (typeof value !== "object" || value === null || Array.isArray(value)) {
731
- return null;
732
- }
733
- const reviewSubject = value.reviewSubject;
734
- if (typeof reviewSubject !== "object" || reviewSubject === null || Array.isArray(reviewSubject)) {
735
- return null;
736
- }
737
- const kind = reviewSubject.kind;
738
- return typeof kind === "string" ? { kind } : null;
739
- }
740
- function parseReviewSubjectFromStateJson(stateJson) {
741
- if (!stateJson) {
742
- return null;
743
- }
744
- try {
745
- return parseReviewSubjectFromState(JSON.parse(stateJson));
746
- } catch {
747
- return null;
748
- }
749
- }
750
- function validateReviewSubjectTurnInvariant(processGraphs, process2, targetTurnId, nextState = void 0) {
751
- if (!targetTurnId) {
752
- return null;
753
- }
754
- const targetTurn = getProcessTurnGraph(processGraphs, process2.processId, targetTurnId);
755
- if (!targetTurn?.reviewSubject) {
756
- return null;
757
- }
758
- const reviewSubject = nextState === void 0 ? parseReviewSubjectFromStateJson(process2.stateJson) : parseReviewSubjectFromState(nextState);
759
- if (isWaitingTurnType(targetTurn.turnType)) {
760
- if (reviewSubject?.kind === targetTurn.reviewSubject.kind) {
761
- return null;
762
- }
763
- return {
764
- ok: false,
765
- code: "invalid_transition",
766
- message: `Transition into '${targetTurnId}' requires reviewSubject.kind '${targetTurn.reviewSubject.kind}'`
767
- };
768
- }
769
- if (reviewSubject) {
770
- return null;
771
- }
772
- return {
773
- ok: false,
774
- code: "invalid_transition",
775
- message: `Transition into '${targetTurnId}' requires a non-null reviewSubject`
776
- };
777
- }
778
730
  function deriveLifecycleStatusForSelectedTurn(processGraphs, processId, turnId) {
779
731
  const turn = getProcessTurnGraph(processGraphs, processId, turnId);
780
732
  return turn ? lifecycleStatusForSelectedTurnType(turn.turnType) : "active";
@@ -823,15 +775,6 @@ function buildTurnSelectionWrites(processGraphs, process2, input) {
823
775
  };
824
776
  }
825
777
  }
826
- const reviewSubjectValidation = validateReviewSubjectTurnInvariant(
827
- processGraphs,
828
- process2,
829
- input.toTurnId,
830
- input.state
831
- );
832
- if (reviewSubjectValidation) {
833
- return reviewSubjectValidation;
834
- }
835
778
  const writes = createWrites({ workerIntent: input.workerIntent ?? { kind: "reconcile" } });
836
779
  applyProcessPatchField(writes, process2, "selectedTurnId", input.toTurnId);
837
780
  applyProcessPatchField(writes, process2, "lifecycleStatus", targetLifecycleStatus);
@@ -1395,6 +1338,11 @@ function requireApiKey(secrets) {
1395
1338
  }
1396
1339
  return value;
1397
1340
  }
1341
+ function configuredBaseUrl(config) {
1342
+ if (!config || typeof config !== "object" || Array.isArray(config)) return void 0;
1343
+ const value = config.baseUrl;
1344
+ return typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
1345
+ }
1398
1346
  function createBuiltinPiServerAdapter(builtinProviderId) {
1399
1347
  return definePiServerAdapter({
1400
1348
  async generateText(input) {
@@ -1403,10 +1351,12 @@ function createBuiltinPiServerAdapter(builtinProviderId) {
1403
1351
  `Built-in adapter '${builtinProviderId}' cannot serve provider '${input.providerId}'`
1404
1352
  );
1405
1353
  }
1406
- const model = getModel(builtinProviderId, input.modelId);
1407
- if (!model) {
1354
+ const canonicalModel = getModel(builtinProviderId, input.modelId);
1355
+ if (!canonicalModel) {
1408
1356
  throw new Error(`Built-in Pi model '${builtinProviderId}/${input.modelId}' is unavailable`);
1409
1357
  }
1358
+ const baseUrl = configuredBaseUrl(input.config);
1359
+ const model = baseUrl ? { ...canonicalModel, baseUrl } : canonicalModel;
1410
1360
  const reasoning = resolveThinkingLevel(input.thinkingLevel);
1411
1361
  const message = await completeSimple(
1412
1362
  model,
@@ -3219,17 +3169,6 @@ function buildServerTransitionWrites(processGraphs, process2, request) {
3219
3169
  const turnChanged = targetTurnId !== void 0 && targetTurnId !== process2.selectedTurnId;
3220
3170
  const effectiveTargetTurnId = targetTurnId === void 0 ? process2.selectedTurnId : targetTurnId;
3221
3171
  const effectiveTargetLifecycleStatus = targetTurnId === void 0 ? request.lifecycleStatus ?? process2.lifecycleStatus : targetLifecycleStatus;
3222
- if (effectiveTargetTurnId !== void 0) {
3223
- const reviewSubjectValidation = validateReviewSubjectTurnInvariant(
3224
- processGraphs,
3225
- process2,
3226
- effectiveTargetTurnId,
3227
- request.state
3228
- );
3229
- if (reviewSubjectValidation) {
3230
- return reviewSubjectValidation;
3231
- }
3232
- }
3233
3172
  const resolvedWorkerIntent = resolveRuntimeWorkerIntent(
3234
3173
  processGraphs,
3235
3174
  process2,
@@ -3241,7 +3180,7 @@ function buildServerTransitionWrites(processGraphs, process2, request) {
3241
3180
  if (resolvedWorkerIntent && "ok" in resolvedWorkerIntent) {
3242
3181
  return resolvedWorkerIntent;
3243
3182
  }
3244
- if (targetTurnId !== void 0 && turnChanged) {
3183
+ if (targetTurnId !== void 0) {
3245
3184
  const selectionWrites = buildTurnSelectionWrites(processGraphs, process2, {
3246
3185
  fromTurnId: process2.selectedTurnId,
3247
3186
  toTurnId: targetTurnId,
@@ -3438,7 +3377,7 @@ async function buildTurnOutcomeWrites(input) {
3438
3377
  }
3439
3378
  let writes = mergeWrites(baseWrites, effectWrites);
3440
3379
  let candidateProcess2 = { ...input.process, ...writes.processPatch };
3441
- if (candidateProcess2.selectedTurnId === input.payload.turnId && candidateProcess2.lifecycleStatus !== "completed" && candidateProcess2.lifecycleStatus !== "aborted" && !hasExplicitTurnSelectionChange(input.process, effectWrites)) {
3380
+ if (candidateProcess2.selectedTurnId === input.payload.turnId && candidateProcess2.lifecycleStatus === "active" && !hasExplicitTurnSelectionChange(input.process, effectWrites)) {
3442
3381
  const outcomeTransition = findOutcomeTransition(
3443
3382
  input.processGraphs,
3444
3383
  candidateProcess2.processId,
@@ -3513,6 +3452,9 @@ function maybeBroadcastErrorAttentionToast(deps, result, input = {}) {
3513
3452
  }
3514
3453
 
3515
3454
  // src/server-automatic-turn-drainer.ts
3455
+ import {
3456
+ failActiveTurnProgress
3457
+ } from "@leitwerk-dev/domain";
3516
3458
  import { isServerAutomaticTurnDefinition as isServerAutomaticTurnDefinition2 } from "@leitwerk-dev/process-sdk";
3517
3459
  function toErrorMessage(error) {
3518
3460
  if (error instanceof Error && error.message.trim() !== "") {
@@ -3640,6 +3582,7 @@ function createServerAutomaticTurnDrainer(deps, getService) {
3640
3582
  }
3641
3583
  const current = deps.processes.getById(instanceId) ?? process2;
3642
3584
  const { params, state } = deps.getProcessActionRegistry?.()?.resolveContextData(current.processId, current) ?? { params: {}, state: {} };
3585
+ let latestProgressReport = null;
3643
3586
  try {
3644
3587
  const result = await turnDef.run({
3645
3588
  process: current,
@@ -3651,6 +3594,10 @@ function createServerAutomaticTurnDrainer(deps, getService) {
3651
3594
  },
3652
3595
  readProductTurnResultMarkdown(productName) {
3653
3596
  return resolveProductMarkdownForServerAutomatic(deps, current, productName);
3597
+ },
3598
+ reportProgress(report) {
3599
+ latestProgressReport = report;
3600
+ recordTurnProgress(deps, { instanceId, turnRecordId, report });
3654
3601
  }
3655
3602
  });
3656
3603
  const recorded = await service.recordTurnOutcome(instanceId, {
@@ -3679,6 +3626,14 @@ function createServerAutomaticTurnDrainer(deps, getService) {
3679
3626
  return;
3680
3627
  }
3681
3628
  } catch (error) {
3629
+ const failedProgressReport = latestProgressReport;
3630
+ if (failedProgressReport) {
3631
+ recordTurnProgress(deps, {
3632
+ instanceId,
3633
+ turnRecordId,
3634
+ report: failActiveTurnProgress(failedProgressReport)
3635
+ });
3636
+ }
3682
3637
  await service.recordTurnFailed(instanceId, {
3683
3638
  instanceId,
3684
3639
  turnRecordId,
@@ -5070,7 +5025,6 @@ var ExecuteAction = defineOperation({
5070
5025
  actionId: input.actionId,
5071
5026
  actionLabel,
5072
5027
  ...sourceTurnRecordId ? { sourceTurnRecordId } : {},
5073
- ...resolvedTurnAction.reviewSubject ? { reviewSubject: resolvedTurnAction.reviewSubject.kind } : {},
5074
5028
  selectedTurnId: ctx.process.selectedTurnId,
5075
5029
  selectedTurnIdBefore: ctx.process.selectedTurnId,
5076
5030
  ...causedSelectedTurnId ? {
@@ -5975,9 +5929,10 @@ function toTurnFailedPayload(input) {
5975
5929
  turnType: input.activeTurnRecord.turnType,
5976
5930
  pathType: input.activeTurnRecord.pathType,
5977
5931
  forkPiEntryId: input.activeTurnRecord.forkPiEntryId,
5978
- resultPiEntryId: input.activeTurnRecord.resultPiEntryId,
5932
+ resultPiEntryId: input.resultPiEntryId ?? input.activeTurnRecord.resultPiEntryId,
5979
5933
  errorSummary: input.message,
5980
- errorClass: input.errorClass
5934
+ errorClass: input.errorClass,
5935
+ recoveryContext: input.recoveryContext
5981
5936
  };
5982
5937
  }
5983
5938
  function buildWorkerFailureWrites(input) {
@@ -6070,7 +6025,9 @@ var WorkerFailure = defineOperation({
6070
6025
  message: input.payload.message,
6071
6026
  errorCode: input.payload.errorCode,
6072
6027
  errorClass: input.payload.errorClass,
6073
- activeTurnRecord: runningTurnRecord
6028
+ activeTurnRecord: runningTurnRecord,
6029
+ resultPiEntryId: input.payload.resultPiEntryId,
6030
+ recoveryContext: input.payload.recoveryContext
6074
6031
  })
6075
6032
  });
6076
6033
  }
@@ -6650,7 +6607,7 @@ function mapSuccess(recorded) {
6650
6607
  };
6651
6608
  }
6652
6609
  function createEngineRunner(deps, options = {}) {
6653
- return async function run(operation, input) {
6610
+ return async function run(operation, input, runOptions = {}) {
6654
6611
  const lockedOutcome = await deps.processOperations.runExclusive(
6655
6612
  input.instanceId,
6656
6613
  async () => {
@@ -6751,6 +6708,17 @@ function createEngineRunner(deps, options = {}) {
6751
6708
  );
6752
6709
  }
6753
6710
  const { recorded } = lockedOutcome;
6711
+ try {
6712
+ runOptions.afterRecord?.(recorded.data);
6713
+ } catch (error) {
6714
+ logProcessEngineError(deps.logger, {
6715
+ err: error,
6716
+ operationKind: operation.kind,
6717
+ instanceId: input.instanceId,
6718
+ stage: "post_commit",
6719
+ code: "after_record_callback_failed"
6720
+ });
6721
+ }
6754
6722
  try {
6755
6723
  await deps.afterRecord?.(recorded.process);
6756
6724
  } catch (error) {
@@ -6935,11 +6903,13 @@ function createProcessEngine(deps) {
6935
6903
  acceptWorkerTurnStart(instanceId, input) {
6936
6904
  return run(AcceptWorkerTurnStart, { instanceId, ...input });
6937
6905
  },
6938
- async recordTurnOutcome(instanceId, payload) {
6939
- return maybeBroadcastActionRequiredToast2(await run(TurnOutcome, { instanceId, payload }));
6906
+ async recordTurnOutcome(instanceId, payload, options) {
6907
+ return maybeBroadcastActionRequiredToast2(
6908
+ await run(TurnOutcome, { instanceId, payload }, { afterRecord: options?.onRecorded })
6909
+ );
6940
6910
  },
6941
- recordTurnFailed(instanceId, payload) {
6942
- return run(TurnFailed, { instanceId, payload });
6911
+ recordTurnFailed(instanceId, payload, options) {
6912
+ return run(TurnFailed, { instanceId, payload }, { afterRecord: options?.onRecorded });
6943
6913
  },
6944
6914
  updateSemanticEntryRefs(instanceId, patch) {
6945
6915
  return run(UpdateSemanticRefs, { instanceId, patch });
@@ -8046,7 +8016,8 @@ function buildProcessLaunchPlan(input) {
8046
8016
  },
8047
8017
  titleSourceFields: input.launchConfig.titleSourceFields?.map((field) => ({ ...field })),
8048
8018
  projectInputs: normalizeProjectInputs(input.launchConfig, input.commitMessages),
8049
- startTurnId: input.launchConfig.startTurnId ?? null
8019
+ startTurnId: input.launchConfig.startTurnId ?? null,
8020
+ ...input.launchConfig.skillIds ? { skillIds: [...input.launchConfig.skillIds] } : {}
8050
8021
  };
8051
8022
  }
8052
8023
 
@@ -8057,7 +8028,7 @@ function collectProcessWatchers(processDef) {
8057
8028
  function buildLaunchPlan(watcher, launchConfig, commitMessages) {
8058
8029
  return buildProcessLaunchPlan({
8059
8030
  processDef: watcher.processDef,
8060
- launchConfig,
8031
+ launchConfig: { ...launchConfig, skillIds: watcher.launchSkillIds },
8061
8032
  launcherId: `${watcher.processId}.${watcher.definition.id}`,
8062
8033
  metadataAdditions: {
8063
8034
  processWatcherId: watcher.definition.id,
@@ -8078,6 +8049,14 @@ function parseConfiguredWatcher(input) {
8078
8049
  if (presentation.targetSummary.trim() === "") {
8079
8050
  throw new Error("presentConfig() must return a non-empty targetSummary");
8080
8051
  }
8052
+ const parsedLaunch = parsed.launchModelConfig ?? {
8053
+ defaultModelProfileId: null,
8054
+ turnConfigs: {}
8055
+ };
8056
+ const launchModelConfig = {
8057
+ defaultModelProfileId: parsedLaunch.defaultModelProfileId ?? null,
8058
+ turnConfigs: parsedLaunch.turnConfigs ?? {}
8059
+ };
8081
8060
  return {
8082
8061
  processId: input.processId,
8083
8062
  processDisplayName: input.processDisplayName,
@@ -8087,10 +8066,8 @@ function parseConfiguredWatcher(input) {
8087
8066
  enabled: parsed.enabled,
8088
8067
  presentation,
8089
8068
  configPath: input.configPath,
8090
- launchModelConfig: parsed.launchModelConfig ?? {
8091
- defaultModelProfileId: null,
8092
- turnConfigs: {}
8093
- }
8069
+ launchModelConfig,
8070
+ launchSkillIds: "skillIds" in parsedLaunch && Array.isArray(parsedLaunch.skillIds) ? parsedLaunch.skillIds : []
8094
8071
  };
8095
8072
  } catch (error) {
8096
8073
  const message = error instanceof Error ? error.message : String(error);
@@ -8477,8 +8454,18 @@ function createWorkerEventIngestor(deps) {
8477
8454
  if (!process2) {
8478
8455
  return;
8479
8456
  }
8480
- const currentTurnRecordId = (process2.currentExecution?.kind === "server_turn" ? process2.currentExecution.id : null) ?? liveTurnRecordIds.get(instanceId) ?? null;
8457
+ const currentTurnRecordId = (process2.currentExecution?.kind === "server_turn" ? process2.currentExecution.id : null) ?? liveTurnRecordIds.get(instanceId) ?? deps.turnRecords.listByInstance(instanceId).find((record3) => record3.status === "running" && record3.turnId === process2.selectedTurnId)?.id ?? null;
8481
8458
  const data = asWsEventPayloadRecord(payload.data);
8459
+ if (payload.eventType === "turn.progress") {
8460
+ const reportedTurnRecordId = readWsEventNonEmptyString(data.turnRecordId);
8461
+ if (!reportedTurnRecordId || reportedTurnRecordId !== currentTurnRecordId) return;
8462
+ recordTurnProgress(deps, {
8463
+ instanceId,
8464
+ turnRecordId: reportedTurnRecordId,
8465
+ report: data.report
8466
+ });
8467
+ return;
8468
+ }
8482
8469
  const projection = getLiveTurnProjection(instanceId, currentTurnRecordId);
8483
8470
  const appliedProjectionEvent = applyPiEventToLiveTurnProjection(projection, {
8484
8471
  eventType: payload.eventType,
@@ -8646,59 +8633,157 @@ function createWorkerInputAckHandler(deps) {
8646
8633
  }
8647
8634
 
8648
8635
  // src/supervisor/worker-turn-ipc-recorder.ts
8649
- import { isTurnFailureCode, isWorkerErrorClass } from "@leitwerk-dev/domain";
8650
- function maybeNormalizeTurnCorrelationFailure(deps, instanceId, result, eventType) {
8651
- if (result.ok) {
8652
- return;
8636
+ import {
8637
+ createGenericFailedTurnRecoveryContext,
8638
+ isTurnFailureCode,
8639
+ isWorkerErrorClass
8640
+ } from "@leitwerk-dev/domain";
8641
+ function terminalWasAlreadyRecorded(deps, turnRecordId, terminalType) {
8642
+ const record3 = deps.turnRecords.getById(turnRecordId);
8643
+ return terminalType === "outcome" ? record3?.status === "succeeded" : record3?.status === "failed";
8644
+ }
8645
+ function failureDetails(result) {
8646
+ if (result instanceof Error) {
8647
+ return { code: "turn_terminal_recording_threw", message: result.message };
8653
8648
  }
8654
- if (result.code !== "stale_turn_record" && result.code !== "missing_turn_record_id") {
8655
- return;
8649
+ if (typeof result === "object" && result !== null && "ok" in result && result.ok === false) {
8650
+ const rejected = result;
8651
+ return {
8652
+ code: typeof rejected.code === "string" ? rejected.code : "turn_terminal_recording_rejected",
8653
+ message: typeof rejected.message === "string" ? rejected.message : "Turn terminal recording was rejected"
8654
+ };
8656
8655
  }
8657
- void deps.commands.recordWorkerFailure(instanceId, {
8658
- errorCode: result.code,
8659
- message: `Worker emitted ${eventType} with invalid turn-record correlation: ${result.message}`,
8660
- errorClass: "infrastructure"
8661
- }).catch(() => {
8662
- });
8656
+ return {
8657
+ code: "turn_terminal_recording_failed",
8658
+ message: "Turn terminal recording failed"
8659
+ };
8663
8660
  }
8664
8661
  function createWorkerTurnIpcRecorder(deps, callbacks) {
8662
+ const acknowledge = (instanceId, workerId, turnRecordId) => {
8663
+ callbacks.onTurnTerminalRecorded?.(instanceId, workerId, turnRecordId);
8664
+ };
8665
+ const reportRecordingFailure = (input) => {
8666
+ try {
8667
+ callbacks.onTurnTerminalRecordingFailed?.(input);
8668
+ } catch {
8669
+ }
8670
+ };
8671
+ const recoverRecordingFailure = async (input) => {
8672
+ if (terminalWasAlreadyRecorded(deps, input.turnRecordId, input.terminalType)) {
8673
+ acknowledge(input.instanceId, input.workerId, input.turnRecordId);
8674
+ return;
8675
+ }
8676
+ const details = failureDetails(input.failure);
8677
+ reportRecordingFailure({
8678
+ instanceId: input.instanceId,
8679
+ workerId: input.workerId,
8680
+ turnRecordId: input.turnRecordId,
8681
+ terminalType: input.terminalType,
8682
+ ...details
8683
+ });
8684
+ try {
8685
+ const fallback = await deps.commands.recordWorkerFailure(input.instanceId, {
8686
+ errorCode: details.code,
8687
+ message: `Server could not durably record worker turn ${input.terminalType}: ${details.message}`,
8688
+ errorClass: "infrastructure",
8689
+ resultPiEntryId: input.resultPiEntryId,
8690
+ recoveryContext: input.recoveryContext
8691
+ });
8692
+ if (fallback.ok || terminalWasAlreadyRecorded(deps, input.turnRecordId, "failure")) {
8693
+ acknowledge(input.instanceId, input.workerId, input.turnRecordId);
8694
+ } else {
8695
+ reportRecordingFailure({
8696
+ instanceId: input.instanceId,
8697
+ workerId: input.workerId,
8698
+ turnRecordId: input.turnRecordId,
8699
+ terminalType: input.terminalType,
8700
+ code: "worker_failure_fallback_rejected",
8701
+ message: fallback.message
8702
+ });
8703
+ }
8704
+ } catch (fallbackError) {
8705
+ const fallbackDetails = failureDetails(fallbackError);
8706
+ reportRecordingFailure({
8707
+ instanceId: input.instanceId,
8708
+ workerId: input.workerId,
8709
+ turnRecordId: input.turnRecordId,
8710
+ terminalType: input.terminalType,
8711
+ code: "worker_failure_fallback_failed",
8712
+ message: fallbackDetails.message
8713
+ });
8714
+ }
8715
+ };
8716
+ const recover = (input) => (failure2) => recoverRecordingFailure({ ...input, failure: failure2 });
8717
+ const clearLiveTurn = (instanceId, turnRecordId) => {
8718
+ if (deps.eventIngestor.getLiveTurnRecordId(instanceId) === turnRecordId) {
8719
+ deps.eventIngestor.clearLiveTurnState(instanceId);
8720
+ }
8721
+ };
8665
8722
  return {
8666
- recordTurnOutcome(instanceId, payload) {
8723
+ recordTurnOutcome(instanceId, workerId, payload) {
8667
8724
  const { turnId, ...rest } = payload;
8668
- if (deps.eventIngestor.getLiveTurnRecordId(instanceId) === rest.turnRecordId) {
8669
- deps.eventIngestor.clearLiveTurnState(instanceId);
8725
+ if (terminalWasAlreadyRecorded(deps, rest.turnRecordId, "outcome")) {
8726
+ acknowledge(instanceId, workerId, rest.turnRecordId);
8727
+ return;
8670
8728
  }
8671
- void deps.commands.recordTurnOutcome(instanceId, {
8729
+ clearLiveTurn(instanceId, rest.turnRecordId);
8730
+ const recoverOutcome = recover({
8672
8731
  instanceId,
8673
- turnId,
8674
- ...rest
8675
- }).then((result) => {
8676
- if (!result.ok) {
8677
- maybeNormalizeTurnCorrelationFailure(deps, instanceId, result, "worker.turn_outcome");
8678
- return;
8679
- }
8680
- callbacks.onTurnOutcomeRecorded?.(instanceId, turnId, rest.outcome, rest.params);
8681
- }).catch(() => {
8732
+ workerId,
8733
+ turnRecordId: rest.turnRecordId,
8734
+ terminalType: "outcome",
8735
+ resultPiEntryId: rest.resultPiEntryId,
8736
+ recoveryContext: createGenericFailedTurnRecoveryContext()
8682
8737
  });
8738
+ void deps.commands.recordTurnOutcome(
8739
+ instanceId,
8740
+ {
8741
+ instanceId,
8742
+ turnId,
8743
+ ...rest
8744
+ },
8745
+ { onRecorded: () => acknowledge(instanceId, workerId, rest.turnRecordId) }
8746
+ ).then((result) => {
8747
+ if (!result.ok) return recoverOutcome(result);
8748
+ callbacks.onTurnOutcomeRecorded?.(instanceId, turnId, rest.outcome, rest.params);
8749
+ }).catch(recoverOutcome);
8683
8750
  },
8684
- recordTurnFailed(instanceId, payload) {
8685
- const { errorClass, failureCode, failureDetails, ...rest } = payload;
8751
+ recordTurnFailed(instanceId, workerId, payload) {
8752
+ const { errorClass, failureCode, failureDetails: details, ...rest } = payload;
8686
8753
  if (errorClass !== void 0 && !isWorkerErrorClass(errorClass)) {
8754
+ void recoverRecordingFailure({
8755
+ instanceId,
8756
+ workerId,
8757
+ turnRecordId: rest.turnRecordId,
8758
+ terminalType: "failure",
8759
+ failure: new Error(`Invalid worker error class '${errorClass}'`)
8760
+ });
8687
8761
  return;
8688
8762
  }
8689
- const normalizedFailureCode = failureCode && isTurnFailureCode(failureCode) ? failureCode : void 0;
8690
- if (deps.eventIngestor.getLiveTurnRecordId(instanceId) === rest.turnRecordId) {
8691
- deps.eventIngestor.clearLiveTurnState(instanceId);
8763
+ if (terminalWasAlreadyRecorded(deps, rest.turnRecordId, "failure")) {
8764
+ acknowledge(instanceId, workerId, rest.turnRecordId);
8765
+ return;
8692
8766
  }
8693
- void deps.commands.recordTurnFailed(instanceId, {
8767
+ const normalizedFailureCode = failureCode && isTurnFailureCode(failureCode) ? failureCode : void 0;
8768
+ clearLiveTurn(instanceId, rest.turnRecordId);
8769
+ const recoverFailure = recover({
8694
8770
  instanceId,
8695
- errorClass,
8696
- ...normalizedFailureCode ? { failureCode: normalizedFailureCode, failureDetails } : {},
8697
- ...rest
8698
- }).then((result) => {
8699
- maybeNormalizeTurnCorrelationFailure(deps, instanceId, result, "worker.turn_failed");
8700
- }).catch(() => {
8771
+ workerId,
8772
+ turnRecordId: rest.turnRecordId,
8773
+ terminalType: "failure",
8774
+ resultPiEntryId: rest.resultPiEntryId,
8775
+ recoveryContext: rest.recoveryContext
8701
8776
  });
8777
+ void deps.commands.recordTurnFailed(
8778
+ instanceId,
8779
+ {
8780
+ instanceId,
8781
+ errorClass,
8782
+ ...normalizedFailureCode ? { failureCode: normalizedFailureCode, failureDetails: details } : {},
8783
+ ...rest
8784
+ },
8785
+ { onRecorded: () => acknowledge(instanceId, workerId, rest.turnRecordId) }
8786
+ ).then((result) => result.ok ? void 0 : recoverFailure(result)).catch(recoverFailure);
8702
8787
  }
8703
8788
  };
8704
8789
  }
@@ -8721,11 +8806,15 @@ function createIpcHandler(deps, callbacks) {
8721
8806
  const inputAckHandler = createWorkerInputAckHandler(deps);
8722
8807
  const turnRecorder = createWorkerTurnIpcRecorder(
8723
8808
  {
8724
- processes: deps.processes,
8809
+ turnRecords: deps.turnRecords,
8725
8810
  commands: deps.commands,
8726
8811
  eventIngestor
8727
8812
  },
8728
- { onTurnOutcomeRecorded: callbacks.onTurnOutcomeRecorded }
8813
+ {
8814
+ onTurnOutcomeRecorded: callbacks.onTurnOutcomeRecorded,
8815
+ onTurnTerminalRecorded: callbacks.onTurnTerminalRecorded,
8816
+ onTurnTerminalRecordingFailed: callbacks.onTurnTerminalRecordingFailed
8817
+ }
8729
8818
  );
8730
8819
  return {
8731
8820
  handleMessage(envelope) {
@@ -8798,6 +8887,7 @@ function createIpcHandler(deps, callbacks) {
8798
8887
  }
8799
8888
  const result = observeWorkerLease("bootstrap_completed", "worker.ready");
8800
8889
  if (result.kind === "applied") {
8890
+ deps.leases.updateHeartbeat(activeLease.workerId);
8801
8891
  void deps.commands.updateSemanticEntryRefs(instanceId, {
8802
8892
  rootEntry: msg.payload.rootEntryId !== void 0 ? msg.payload.rootEntryId ? { entryId: msg.payload.rootEntryId, turnRecordId: null } : null : void 0
8803
8893
  }).catch(() => {
@@ -8856,11 +8946,11 @@ function createIpcHandler(deps, callbacks) {
8856
8946
  break;
8857
8947
  }
8858
8948
  case "worker.turn_outcome": {
8859
- turnRecorder.recordTurnOutcome(instanceId, msg.payload);
8949
+ turnRecorder.recordTurnOutcome(instanceId, workerId, msg.payload);
8860
8950
  break;
8861
8951
  }
8862
8952
  case "worker.turn_failed": {
8863
- turnRecorder.recordTurnFailed(instanceId, msg.payload);
8953
+ turnRecorder.recordTurnFailed(instanceId, workerId, msg.payload);
8864
8954
  break;
8865
8955
  }
8866
8956
  case "worker.lifecycle_parked": {
@@ -9052,6 +9142,21 @@ import {
9052
9142
  WORKER_SNAPSHOT_TOKEN_ENV
9053
9143
  } from "@leitwerk-dev/worker-protocol";
9054
9144
 
9145
+ // src/supervisor/accepted-turn-start-replay.ts
9146
+ function resolveAcceptedTurnStartReplay(deps, instanceId, workerId) {
9147
+ const lease = deps.leases.getByInstance(instanceId);
9148
+ if (!lease || lease.workerId !== workerId || lease.state !== "idle") return null;
9149
+ const process2 = deps.processes.getById(instanceId);
9150
+ if (!process2 || process2.currentExecution?.kind !== "worker_start") return null;
9151
+ const start = deps.turnStarts.getById(process2.currentExecution.id);
9152
+ if (!start || start.instanceId !== instanceId || start.state.kind !== "accepted" || start.state.acceptedWorkerLeaseId !== lease.id)
9153
+ return null;
9154
+ const turnRecord = deps.turnRecords.getById(start.state.turnRecordId);
9155
+ if (!turnRecord || turnRecord.instanceId !== instanceId || turnRecord.status !== "running" || turnRecord.acceptedWorkerLeaseId !== lease.id)
9156
+ return null;
9157
+ return { startRecordId: start.id, turnRecordId: turnRecord.id, startedAt: turnRecord.startedAt };
9158
+ }
9159
+
9055
9160
  // src/supervisor/adoption/adoption-plan.ts
9056
9161
  function workerDescriptorKey(descriptor) {
9057
9162
  return `${descriptor.namespace ?? ""}/${descriptor.unitId}`;
@@ -9640,7 +9745,7 @@ function createWorkerStartPayloadBuilder(deps) {
9640
9745
  process2.processId,
9641
9746
  start.turnId
9642
9747
  );
9643
- const integrationToolNames = selectedTurn?.kind === "llm" ? selectedTurn.integrationTools ?? [] : [];
9748
+ const integrationToolNames = selectedTurn?.kind === "llm" || selectedTurn?.kind === "automatic" ? selectedTurn.integrationTools ?? [] : [];
9644
9749
  const integrationTools = integrationToolNames.length > 0 ? deps.integrationTools?.declarations(integrationToolNames) : void 0;
9645
9750
  if (integrationToolNames.length > 0 && !integrationTools) {
9646
9751
  throw new Error(`Integration tools are unavailable for turn '${start.turnId}'`);
@@ -9786,6 +9891,24 @@ function createWorkerWebSocketIpcManager(options = {}) {
9786
9891
  return false;
9787
9892
  }
9788
9893
  }
9894
+ function queueOutbound(entry, data) {
9895
+ if (entry.outbound.length >= maxBufferedMessages) {
9896
+ entry.outbound = [];
9897
+ reportRuntimeError(
9898
+ entry,
9899
+ new WorkerOutboundBufferOverflowError(
9900
+ entry.instanceId,
9901
+ entry.workerId,
9902
+ maxBufferedMessages
9903
+ )
9904
+ );
9905
+ if (entry.socket) {
9906
+ closeSocket(entry, entry.socket, 1011, "worker websocket outbound buffer overflow");
9907
+ }
9908
+ return;
9909
+ }
9910
+ entry.outbound.push(data);
9911
+ }
9789
9912
  function flushOutbound(entry, socket) {
9790
9913
  while (entry.outbound.length > 0) {
9791
9914
  const data = entry.outbound[0];
@@ -9909,21 +10032,17 @@ function createWorkerWebSocketIpcManager(options = {}) {
9909
10032
  }
9910
10033
  const data = serializeMessage(message);
9911
10034
  if (!entry.socket || !entry.socketAuthenticated) {
9912
- if (entry.outbound.length >= maxBufferedMessages) {
9913
- entry.outbound = [];
9914
- reportRuntimeError(
9915
- entry,
9916
- new WorkerOutboundBufferOverflowError(instanceId, workerId, maxBufferedMessages)
9917
- );
9918
- if (entry.socket) {
9919
- closeSocket(entry, entry.socket, 1011, "worker websocket outbound buffer overflow");
9920
- }
9921
- return;
9922
- }
9923
- entry.outbound.push(data);
10035
+ queueOutbound(entry, data);
9924
10036
  return;
9925
10037
  }
9926
- sendNow(entry, entry.socket, data);
10038
+ const socket = entry.socket;
10039
+ if (sendNow(entry, socket, data)) {
10040
+ return;
10041
+ }
10042
+ if (entry.socket === socket) {
10043
+ closeSocket(entry, socket, 1011, "worker websocket unavailable during send");
10044
+ }
10045
+ queueOutbound(entry, data);
9927
10046
  },
9928
10047
  unregister(instanceId, workerId, reason) {
9929
10048
  const key = connectionKey(instanceId, workerId);
@@ -10118,6 +10237,16 @@ function createWorkerSupervisor(deps) {
10118
10237
  const lease = safeGetLeaseByInstance(instanceId);
10119
10238
  return lease?.workerId === workerId && (lease.state === "spawning" || lease.state === "bootstrapping");
10120
10239
  }
10240
+ function reconcileAcceptedTurnStart(instanceId, workerId) {
10241
+ if (workers.get(instanceId)?.workerId !== workerId) return false;
10242
+ const replay = resolveAcceptedTurnStartReplay(deps, instanceId, workerId);
10243
+ if (!replay) return false;
10244
+ sendToCurrentWorker(instanceId, workerId, {
10245
+ type: "worker.turn_start_accepted",
10246
+ payload: { startRecordId: replay.startRecordId, turnRecordId: replay.turnRecordId }
10247
+ });
10248
+ return true;
10249
+ }
10121
10250
  function routeEnvelope(envelope, instanceId) {
10122
10251
  const currentHandle = workers.get(instanceId);
10123
10252
  if (envelope.instanceId !== instanceId || currentHandle && envelope.workerId !== currentHandle.workerId) {
@@ -10166,6 +10295,10 @@ function createWorkerSupervisor(deps) {
10166
10295
  }
10167
10296
  if (envelope.type === "worker.heartbeat") {
10168
10297
  adoptionCoordinator.onHeartbeat(instanceId, envelope.workerId, envelope.payload);
10298
+ const reportedState = typeof envelope.payload === "object" && envelope.payload !== null && "state" in envelope.payload ? envelope.payload.state : null;
10299
+ if (reportedState === "idle") {
10300
+ reconcileAcceptedTurnStart(instanceId, envelope.workerId);
10301
+ }
10169
10302
  }
10170
10303
  if (envelope.type === "worker.ready") {
10171
10304
  adoptionCoordinator.onWorkerReady(instanceId);
@@ -10530,6 +10663,20 @@ function createWorkerSupervisor(deps) {
10530
10663
  payload: { startRecordId, turnRecordId }
10531
10664
  });
10532
10665
  },
10666
+ reconcileAcceptedTurnStart,
10667
+ acknowledgeTurnTerminal(instanceId, workerId, payload) {
10668
+ runnerRuntime.webSocketIpc.send(
10669
+ instanceId,
10670
+ workerId,
10671
+ createIpcMessage4({
10672
+ type: "worker.turn_terminal_recorded",
10673
+ payload,
10674
+ messageId: randomUUID5(),
10675
+ instanceId,
10676
+ workerId
10677
+ })
10678
+ );
10679
+ },
10533
10680
  questionResponse(instanceId, workerId, payload) {
10534
10681
  sendToCurrentWorker(instanceId, workerId, { type: "worker.question_response", payload });
10535
10682
  },
@@ -11246,10 +11393,13 @@ function createExternalSourceService(deps) {
11246
11393
  });
11247
11394
  return armed;
11248
11395
  }
11249
- if (!isHumanTurnDefinition(turnDef)) {
11396
+ if (!isHumanTurnDefinition(turnDef) && turnDef.kind !== "automatic") {
11250
11397
  return [];
11251
11398
  }
11252
11399
  for (const [externalActionId, action] of Object.entries(turnDef.externalActions ?? {})) {
11400
+ if (action.when && !action.when({ process: process2, projects, params, state })) {
11401
+ continue;
11402
+ }
11253
11403
  const id = getExternalActionArmingId({ turnId, externalActionId });
11254
11404
  armed.push({
11255
11405
  id,
@@ -11313,7 +11463,7 @@ function createExternalSourceService(deps) {
11313
11463
  }
11314
11464
  for (const [turnId, binding] of processDef.turns) {
11315
11465
  const turnDef = binding.definition;
11316
- if (isHumanTurnDefinition(turnDef)) {
11466
+ if (isHumanTurnDefinition(turnDef) || turnDef.kind === "automatic") {
11317
11467
  for (const [externalActionId, action] of Object.entries(turnDef.externalActions ?? {})) {
11318
11468
  if (getExternalActionArmingId({ turnId, externalActionId }) === armingId) {
11319
11469
  return { turnId, externalActionId, sourceKind: action.source.kind };
@@ -12268,6 +12418,20 @@ function launchStartFailure(commit, result) {
12268
12418
  };
12269
12419
  }
12270
12420
  async function createProcessFromLaunchPlanWithDisposition(deps, launchPlan, opts, futureExecutionPlan) {
12421
+ let resourceSelections = opts?.resourceSelections;
12422
+ if (!resourceSelections && launchPlan.skillIds) {
12423
+ try {
12424
+ resourceSelections = deps.skills.resolveActive(launchPlan.skillIds);
12425
+ } catch (error) {
12426
+ return {
12427
+ ok: false,
12428
+ stage: "pre_commit",
12429
+ status: 400,
12430
+ body: { error: error instanceof Error ? error.message : String(error) }
12431
+ };
12432
+ }
12433
+ }
12434
+ opts = { ...opts, resourceSelections: resourceSelections ?? [] };
12271
12435
  if (deps.repositoryCredentials) {
12272
12436
  try {
12273
12437
  deps.repositoryCredentials.validateLaunch({
@@ -12290,8 +12454,8 @@ async function createProcessFromLaunchPlanWithDisposition(deps, launchPlan, opts
12290
12454
  deps,
12291
12455
  launchPlan,
12292
12456
  futureExecutionPlan,
12293
- opts?.resourceSelections,
12294
- opts?.launchIntent
12457
+ opts.resourceSelections,
12458
+ opts.launchIntent
12295
12459
  );
12296
12460
  } catch (error) {
12297
12461
  const dedupKey = launchPlan.handoffDedupKey?.trim() || null;
@@ -12617,19 +12781,7 @@ async function executeScheduledLaunch(deps, execution) {
12617
12781
  computeNextCronRun(execution, new Date(execution.nextRunAt))
12618
12782
  ) : planConsumeFutureExecution(execution);
12619
12783
  const result = await createScheduledProcessFromLaunchPlan(
12620
- {
12621
- processes: deps.processes,
12622
- projects: deps.projects,
12623
- processSkills: deps.processSkills,
12624
- handoffDedupKeys: deps.handoffDedupKeys,
12625
- futureExecutions: deps.futureExecutions,
12626
- broadcaster: deps.broadcaster,
12627
- commands: deps.commands,
12628
- processTitles: deps.processTitles,
12629
- extensionHost: deps.extensionHost,
12630
- logger: deps.logger,
12631
- transaction: deps.transaction
12632
- },
12784
+ deps,
12633
12785
  preparedLaunchPlan.launchPlan,
12634
12786
  transitionPlan,
12635
12787
  {
@@ -13916,7 +14068,7 @@ function createIntegrationToolRequestService(input) {
13916
14068
  process2.processId,
13917
14069
  turn.turnId
13918
14070
  );
13919
- if (turnDefinition?.kind !== "llm" || !turnDefinition.integrationTools?.includes(payload.toolName)) {
14071
+ if (turnDefinition?.kind !== "llm" && turnDefinition?.kind !== "automatic" || !turnDefinition.integrationTools?.includes(payload.toolName)) {
13920
14072
  return fail(`Integration tool '${payload.toolName}' is not authorized for this turn`);
13921
14073
  }
13922
14074
  const projects = input.repos.projects.listByInstance(instanceId);
@@ -15293,6 +15445,7 @@ function buildHostCapabilities(input) {
15293
15445
  commitMessages: input.config.commit_messages,
15294
15446
  processes: input.baseDeps.processes,
15295
15447
  projects: input.baseDeps.projects,
15448
+ skills: input.baseDeps.skills,
15296
15449
  processSkills: input.baseDeps.processSkills,
15297
15450
  handoffDedupKeys: input.baseDeps.handoffDedupKeys,
15298
15451
  futureExecutions: input.baseDeps.futureExecutions,
@@ -16913,8 +17066,7 @@ function registerSkillRoutes(app, deps) {
16913
17066
  return { revisionId };
16914
17067
  } catch (error) {
16915
17068
  const message = error instanceof Error ? error.message : "Skill could not be registered";
16916
- const conflict = message.includes("conflicting") || message.includes("managed by configuration");
16917
- return reply.code(conflict ? 409 : 404).send({ error: message });
17069
+ return reply.code(message.includes("conflicting") ? 409 : 404).send({ error: message });
16918
17070
  }
16919
17071
  }
16920
17072
  );
@@ -17100,21 +17252,24 @@ function isWithin(root, candidate) {
17100
17252
  const relative = path8.relative(root, candidate);
17101
17253
  return relative === "" || relative !== ".." && !relative.startsWith(`..${path8.sep}`);
17102
17254
  }
17103
- async function importSkillDirectory(root, skill, sourceRevision) {
17255
+ async function importSkillDirectory(root, checkoutRoot, sourceRevision) {
17256
+ const skillId = path8.basename(root);
17257
+ const metadata = skillFrontmatter(await readFile5(path8.join(root, "SKILL.md"), "utf8"));
17104
17258
  const collector = new ResourceCollector();
17105
- await collector.addDirectory(path8.resolve(root), `skills/${skill.id}`, SKILL_RESOURCE_OWNER, {
17259
+ await collector.addDirectory(path8.resolve(root), `skills/${skillId}`, SKILL_RESOURCE_OWNER, {
17106
17260
  forbiddenNames: FORBIDDEN_SKILL_NAMES
17107
17261
  });
17108
17262
  const files = collector.toResourceFiles();
17109
- if (!files.some((file) => file.path === `skills/${skill.id}/SKILL.md`)) {
17110
- throw new Error(`Skill '${skill.id}' must contain a regular root SKILL.md`);
17263
+ if (!files.some((file) => file.path === `skills/${skillId}/SKILL.md`)) {
17264
+ throw new Error(`Skill '${skillId}' must contain a regular root SKILL.md`);
17111
17265
  }
17112
17266
  return {
17113
- skillId: skill.id,
17114
- label: skill.label ?? skill.id,
17115
- description: skill.description ?? null,
17267
+ skillId,
17268
+ label: metadataText(metadata.name) ?? fallbackLabel(skillId),
17269
+ description: metadataText(metadata.description),
17116
17270
  bundle: createCanonicalPiResourceBundle2(files),
17117
- sourceRevision
17271
+ sourceRevision,
17272
+ sourcePath: repositorySourcePath(checkoutRoot, root)
17118
17273
  };
17119
17274
  }
17120
17275
  async function checkoutGitSource(source, root) {
@@ -17129,12 +17284,8 @@ async function checkoutGitSource(source, root) {
17129
17284
  const { stdout } = await execFileAsync("git", ["-C", root, "rev-parse", "HEAD"]);
17130
17285
  return { root, commit: stdout.trim() };
17131
17286
  }
17132
- function metadataValue(markdown, key) {
17133
- if (!markdown.startsWith("---")) return null;
17134
- const end = markdown.indexOf("\n---", 3);
17135
- if (end < 0) return null;
17136
- const match = markdown.slice(3, end).match(new RegExp(`^${key}:\\s*["']?([^\\n"']+)["']?\\s*$`, "m"));
17137
- return match?.[1]?.trim() || null;
17287
+ function metadataText(value) {
17288
+ return typeof value === "string" ? value.trim() || null : null;
17138
17289
  }
17139
17290
  function fallbackLabel(id) {
17140
17291
  return id.split(/[-_.]+/).filter(Boolean).map((part) => `${part[0]?.toUpperCase() ?? ""}${part.slice(1)}`).join(" ");
@@ -17146,7 +17297,7 @@ async function discoverSkillRoots(catalogRoot) {
17146
17297
  (left, right) => left.name.localeCompare(right.name)
17147
17298
  );
17148
17299
  const skillId = path8.basename(directory);
17149
- if (directory !== catalogRoot && SAFE_SKILL_ID_PATTERN.test(skillId) && entries.some((entry) => entry.name === "SKILL.md" && entry.isFile())) {
17300
+ if (SAFE_SKILL_ID_PATTERN.test(skillId) && entries.some((entry) => entry.name === "SKILL.md" && entry.isFile())) {
17150
17301
  result.push(directory);
17151
17302
  return;
17152
17303
  }
@@ -17165,10 +17316,7 @@ function repositorySourcePath(checkoutRoot, skillRoot) {
17165
17316
  async function importSkillRepository(repository) {
17166
17317
  const tempRoot = await mkdtemp2(path8.join(tmpdir2(), "leitwerk-skill-repository-"));
17167
17318
  try {
17168
- const checkout = await checkoutGitSource(
17169
- { kind: "git", url: repository.url, ref: repository.ref, path: repository.path ?? "skills" },
17170
- path8.join(tempRoot, "checkout")
17171
- );
17319
+ const checkout = await checkoutGitSource(repository, path8.join(tempRoot, "checkout"));
17172
17320
  const catalogRoot = path8.resolve(checkout.root, repository.path ?? "skills");
17173
17321
  if (!isWithin(checkout.root, catalogRoot)) {
17174
17322
  throw new Error(`Skill repository '${repository.id}' path escapes its checkout`);
@@ -17187,61 +17335,13 @@ async function importSkillRepository(repository) {
17187
17335
  }
17188
17336
  const skills = [];
17189
17337
  for (const skillRoot of skillRoots) {
17190
- const skillId = path8.basename(skillRoot);
17191
- const markdown = await readFile5(path8.join(skillRoot, "SKILL.md"), "utf8");
17192
- const imported = await importSkillDirectory(
17193
- skillRoot,
17194
- {
17195
- id: skillId,
17196
- label: metadataValue(markdown, "name") ?? fallbackLabel(skillId),
17197
- description: metadataValue(markdown, "description") ?? void 0,
17198
- source: { kind: "local", path: skillRoot }
17199
- },
17200
- checkout.commit
17201
- );
17202
- skills.push({
17203
- ...imported,
17204
- sourcePath: repositorySourcePath(checkout.root, skillRoot)
17205
- });
17338
+ skills.push(await importSkillDirectory(skillRoot, checkout.root, checkout.commit));
17206
17339
  }
17207
17340
  return { commit: checkout.commit, skills };
17208
17341
  } finally {
17209
17342
  await rm3(tempRoot, { recursive: true, force: true });
17210
17343
  }
17211
17344
  }
17212
- async function importConfiguredSkills(skills, configRoot) {
17213
- let tempRoot = null;
17214
- const checkouts = /* @__PURE__ */ new Map();
17215
- try {
17216
- const result = [];
17217
- for (const skill of skills) {
17218
- if (skill.source.kind === "local") {
17219
- result.push(
17220
- await importSkillDirectory(path8.resolve(configRoot, skill.source.path), skill, null)
17221
- );
17222
- continue;
17223
- }
17224
- const key = `${skill.source.url}\0${skill.source.ref}`;
17225
- let checkout = checkouts.get(key);
17226
- if (!checkout) {
17227
- tempRoot ??= await mkdtemp2(path8.join(tmpdir2(), "leitwerk-skills-"));
17228
- checkout = await checkoutGitSource(
17229
- skill.source,
17230
- path8.join(tempRoot, String(checkouts.size))
17231
- );
17232
- checkouts.set(key, checkout);
17233
- }
17234
- const selected = path8.resolve(checkout.root, skill.source.path);
17235
- if (!isWithin(checkout.root, selected)) {
17236
- throw new Error(`Skill '${skill.id}' Git path escapes its checkout`);
17237
- }
17238
- result.push(await importSkillDirectory(selected, skill, checkout.commit));
17239
- }
17240
- return result;
17241
- } finally {
17242
- if (tempRoot) await rm3(tempRoot, { recursive: true, force: true });
17243
- }
17244
- }
17245
17345
 
17246
17346
  // src/skills/catalog-service.ts
17247
17347
  function createSkillCatalogService(input) {
@@ -17315,12 +17415,6 @@ function createSkillCatalogService(input) {
17315
17415
  };
17316
17416
  }
17317
17417
 
17318
- // src/skills/catalog-sync.ts
17319
- async function syncConfiguredSkillCatalog(input) {
17320
- const imported = await importConfiguredSkills(input.skills, input.configRoot);
17321
- input.repos.transaction((repos) => repos.skills.reconcile(imported));
17322
- }
17323
-
17324
17418
  // src/supervisor/stale-heartbeat-watchdog.ts
17325
17419
  import { parseDurationMs as parseDurationMs5 } from "@leitwerk-dev/watcher-utils";
17326
17420
  function startStaleHeartbeatWatchdog(deps) {
@@ -17329,7 +17423,9 @@ function startStaleHeartbeatWatchdog(deps) {
17329
17423
  const now2 = deps.now ?? (() => Date.now());
17330
17424
  const setIntervalImpl = deps.setIntervalImpl ?? setInterval;
17331
17425
  const clearIntervalImpl = deps.clearIntervalImpl ?? clearInterval;
17426
+ const acceptedStartReconciliations = /* @__PURE__ */ new Map();
17332
17427
  const tick = () => {
17428
+ const observedReconciliations = /* @__PURE__ */ new Set();
17333
17429
  for (const lease of deps.leases.listActive()) {
17334
17430
  if (deps.supervisor.isAdoptionPending?.(lease.instanceId)) {
17335
17431
  continue;
@@ -17337,15 +17433,48 @@ function startStaleHeartbeatWatchdog(deps) {
17337
17433
  if (lease.state !== "idle" && lease.state !== "busy" && lease.state !== "draining") {
17338
17434
  continue;
17339
17435
  }
17340
- const heartbeatAt = lease.lastHeartbeatAt ?? lease.startedAt;
17341
- const lastSeenMs = Date.parse(heartbeatAt);
17342
- if (!Number.isFinite(lastSeenMs) || now2() - lastSeenMs < timeoutMs) {
17343
- continue;
17344
- }
17345
17436
  const process2 = deps.processes.getById(lease.instanceId);
17346
17437
  if (!process2) {
17347
17438
  continue;
17348
17439
  }
17440
+ const acceptedStart = lease.state === "idle" ? resolveAcceptedTurnStartReplay(deps, lease.instanceId, lease.workerId) : null;
17441
+ const acceptedAtMs = acceptedStart ? Date.parse(acceptedStart.startedAt) : Number.NaN;
17442
+ if (acceptedStart && Number.isFinite(acceptedAtMs) && now2() - acceptedAtMs >= timeoutMs) {
17443
+ observedReconciliations.add(lease.instanceId);
17444
+ const reconciliation = acceptedStartReconciliations.get(lease.instanceId);
17445
+ if (!reconciliation || reconciliation.turnRecordId !== acceptedStart.turnRecordId) {
17446
+ if (deps.supervisor.reconcileAcceptedTurnStart(lease.instanceId, lease.workerId)) {
17447
+ acceptedStartReconciliations.set(lease.instanceId, {
17448
+ turnRecordId: acceptedStart.turnRecordId,
17449
+ startedAtMs: now2()
17450
+ });
17451
+ continue;
17452
+ }
17453
+ } else if (now2() - reconciliation.startedAtMs < timeoutMs) {
17454
+ continue;
17455
+ }
17456
+ acceptedStartReconciliations.delete(lease.instanceId);
17457
+ deps.ipcHandler.handleMessage(
17458
+ createServerObservedWorkerFailedMessage({
17459
+ instanceId: lease.instanceId,
17460
+ workerId: lease.workerId,
17461
+ state: lease.state,
17462
+ errorCode: "idle_worker_running_turn",
17463
+ message: `Worker ${lease.workerId} reported idle while turn ${acceptedStart.turnRecordId} remained running`,
17464
+ errorClass: "infrastructure",
17465
+ selectedTurnId: process2.selectedTurnId
17466
+ })
17467
+ );
17468
+ deps.supervisor.getWorker(lease.instanceId)?.kill();
17469
+ continue;
17470
+ }
17471
+ if (!lease.lastHeartbeatAt) {
17472
+ continue;
17473
+ }
17474
+ const lastSeenMs = Date.parse(lease.lastHeartbeatAt);
17475
+ if (!Number.isFinite(lastSeenMs) || now2() - lastSeenMs < timeoutMs) {
17476
+ continue;
17477
+ }
17349
17478
  deps.ipcHandler.handleMessage(
17350
17479
  createServerObservedWorkerFailedMessage({
17351
17480
  instanceId: lease.instanceId,
@@ -17359,6 +17488,11 @@ function startStaleHeartbeatWatchdog(deps) {
17359
17488
  );
17360
17489
  deps.supervisor.getWorker(lease.instanceId)?.kill();
17361
17490
  }
17491
+ for (const instanceId of acceptedStartReconciliations.keys()) {
17492
+ if (!observedReconciliations.has(instanceId)) {
17493
+ acceptedStartReconciliations.delete(instanceId);
17494
+ }
17495
+ }
17362
17496
  };
17363
17497
  const timer = setIntervalImpl(tick, intervalMs);
17364
17498
  return {
@@ -17420,7 +17554,8 @@ async function createConfiguredWorkerRunnerRuntime(input) {
17420
17554
  ...pod ? {
17421
17555
  annotations: pod.annotations,
17422
17556
  nodeSelector: pod.node_selector,
17423
- tolerations: pod.tolerations
17557
+ tolerations: pod.tolerations,
17558
+ hostAliases: pod.host_aliases
17424
17559
  } : {}
17425
17560
  }
17426
17561
  });
@@ -17507,12 +17642,10 @@ ${configErrors.join("\n")}`);
17507
17642
  const repos = createAllRepos(db, {
17508
17643
  ...credentialCipher ? { credentialCipher } : {}
17509
17644
  });
17510
- await syncConfiguredSkillCatalog({
17511
- skills: config.skills ?? [],
17512
- configRoot: opts.extensionLoadingStartDir ?? process.cwd(),
17513
- repos
17645
+ repos.transaction((transactionRepos) => {
17646
+ transactionRepos.skills.deactivateConfiguredSkills();
17647
+ transactionRepos.skills.backfillDependencies();
17514
17648
  });
17515
- repos.transaction((transactionRepos) => transactionRepos.skills.backfillDependencies());
17516
17649
  const skillCatalog = createSkillCatalogService({
17517
17650
  repositories: config.skill_repositories ?? [],
17518
17651
  repos
@@ -17887,6 +18020,23 @@ ${configErrors.join("\n")}`);
17887
18020
  } : void 0
17888
18021
  },
17889
18022
  {
18023
+ onTurnTerminalRecorded(instanceId, workerId, turnRecordId) {
18024
+ supervisor?.acknowledgeTurnTerminal(instanceId, workerId, { turnRecordId });
18025
+ },
18026
+ onTurnTerminalRecordingFailed(input) {
18027
+ app.log.error(input, "Worker turn terminal recording failed");
18028
+ baseDeps.events.create({
18029
+ instanceId: input.instanceId,
18030
+ eventType: "worker_terminal_recording_failed",
18031
+ data: {
18032
+ workerId: input.workerId,
18033
+ turnRecordId: input.turnRecordId,
18034
+ terminalType: input.terminalType,
18035
+ code: input.code,
18036
+ message: input.message
18037
+ }
18038
+ });
18039
+ },
17890
18040
  onWorkerTurnStartAccepted(instanceId, workerId, payload) {
17891
18041
  supervisor?.acceptTurnStart(
17892
18042
  instanceId,
@@ -17933,13 +18083,7 @@ ${configErrors.join("\n")}`);
17933
18083
  },
17934
18084
  resolveRepositoryCredentials: (input) => repositoryCredentials.resolveWorkerCredentials(input),
17935
18085
  integrationTools,
17936
- resolveCredential(providerId, options) {
17937
- const credential = modelProviderCredentials.resolve(providerId, options);
17938
- return credential && credential.revision !== null ? {
17939
- revision: credential.revision,
17940
- values: credential.values
17941
- } : null;
17942
- }
18086
+ resolveCredential: (providerId, options) => modelProviderCredentials.resolve(providerId, options)
17943
18087
  });
17944
18088
  let staleHeartbeatWatchdog = null;
17945
18089
  let retainedVolumeCleanupTimer = null;
@@ -17998,6 +18142,8 @@ ${configErrors.join("\n")}`);
17998
18142
  staleHeartbeatWatchdog = startStaleHeartbeatWatchdog({
17999
18143
  leases: baseDeps.leases,
18000
18144
  processes: baseDeps.processes,
18145
+ turnRecords: baseDeps.turnRecords,
18146
+ turnStarts: baseDeps.turnStarts,
18001
18147
  ipcHandler,
18002
18148
  supervisor,
18003
18149
  staleHeartbeatTimeout: config.workers.stale_heartbeat_timeout
@@ -18289,4 +18435,4 @@ export {
18289
18435
  createApp,
18290
18436
  createAppContext
18291
18437
  };
18292
- //# sourceMappingURL=chunk-OO6VH4FX.js.map
18438
+ //# sourceMappingURL=chunk-DFHOPJRZ.js.map