@leitwerk-dev/worker 0.1.9 → 0.2.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 (240) hide show
  1. package/dist/automatic-turn-executor.d.ts +1 -0
  2. package/dist/automatic-turn-executor.d.ts.map +1 -1
  3. package/dist/{chunk-O6332GRG.js → chunk-2LLFMCR6.js} +1511 -1071
  4. package/dist/chunk-2LLFMCR6.js.map +1 -0
  5. package/dist/connection-diagnostics.d.ts +5 -0
  6. package/dist/connection-diagnostics.d.ts.map +1 -0
  7. package/dist/container-entry-main.d.ts +2 -0
  8. package/dist/container-entry-main.d.ts.map +1 -0
  9. package/dist/container-entry-main.js +232 -0
  10. package/dist/container-entry-main.js.map +1 -0
  11. package/dist/container-entry.d.ts +14 -0
  12. package/dist/container-entry.d.ts.map +1 -0
  13. package/dist/development-tool-environment.d.ts +84 -0
  14. package/dist/development-tool-environment.d.ts.map +1 -0
  15. package/dist/diagnostics.d.ts +4 -0
  16. package/dist/diagnostics.d.ts.map +1 -1
  17. package/dist/docker-registry-credentials.d.ts +8 -0
  18. package/dist/docker-registry-credentials.d.ts.map +1 -0
  19. package/dist/entry-runtime.d.ts +19 -0
  20. package/dist/entry-runtime.d.ts.map +1 -1
  21. package/dist/index.d.ts +3 -5
  22. package/dist/index.d.ts.map +1 -1
  23. package/dist/index.js +10 -5
  24. package/dist/index.js.map +1 -1
  25. package/dist/input-consumer.d.ts +7 -11
  26. package/dist/input-consumer.d.ts.map +1 -1
  27. package/dist/ipc.d.ts +10 -0
  28. package/dist/ipc.d.ts.map +1 -1
  29. package/dist/logical-prompt-runner.d.ts.map +1 -1
  30. package/dist/managed-pi-agent-dir.d.ts +8 -1
  31. package/dist/managed-pi-agent-dir.d.ts.map +1 -1
  32. package/dist/managed-pi-bootstrap.d.ts +1 -0
  33. package/dist/managed-pi-bootstrap.d.ts.map +1 -1
  34. package/dist/missing-tool-recovery-runner.d.ts +4 -3
  35. package/dist/missing-tool-recovery-runner.d.ts.map +1 -1
  36. package/dist/pi-adapter.d.ts +88 -1
  37. package/dist/pi-adapter.d.ts.map +1 -1
  38. package/dist/pi-event-reporter.d.ts.map +1 -1
  39. package/dist/pi-resource-bundle.d.ts +17 -1
  40. package/dist/pi-resource-bundle.d.ts.map +1 -1
  41. package/dist/pre-turn-targeted-inputs.d.ts +8 -7
  42. package/dist/pre-turn-targeted-inputs.d.ts.map +1 -1
  43. package/dist/prompt-guards.d.ts +6 -0
  44. package/dist/prompt-guards.d.ts.map +1 -1
  45. package/dist/repository-bash-tool.d.ts +4 -0
  46. package/dist/repository-bash-tool.d.ts.map +1 -0
  47. package/dist/resource-loader-factory.d.ts +1 -2
  48. package/dist/resource-loader-factory.d.ts.map +1 -1
  49. package/dist/result-image-upload.d.ts.map +1 -1
  50. package/dist/runtime/adapters.d.ts +38 -0
  51. package/dist/runtime/adapters.d.ts.map +1 -1
  52. package/dist/runtime/bootstrap-session.d.ts +9 -5
  53. package/dist/runtime/bootstrap-session.d.ts.map +1 -1
  54. package/dist/runtime/bootstrap.d.ts +38 -18
  55. package/dist/runtime/bootstrap.d.ts.map +1 -1
  56. package/dist/runtime/failure-policy.d.ts +1 -0
  57. package/dist/runtime/failure-policy.d.ts.map +1 -1
  58. package/dist/runtime/index.d.ts +4 -1
  59. package/dist/runtime/index.d.ts.map +1 -1
  60. package/dist/runtime/lifecycle-reducer.d.ts.map +1 -1
  61. package/dist/runtime/llm-turn-execution.d.ts +3 -8
  62. package/dist/runtime/llm-turn-execution.d.ts.map +1 -1
  63. package/dist/runtime/turn-execution.d.ts +2 -9
  64. package/dist/runtime/turn-execution.d.ts.map +1 -1
  65. package/dist/session-snapshot-exchange.d.ts +10 -4
  66. package/dist/session-snapshot-exchange.d.ts.map +1 -1
  67. package/dist/turn-continuation.d.ts.map +1 -1
  68. package/dist/turn-execution-error.d.ts +1 -1
  69. package/dist/turn-execution-error.d.ts.map +1 -1
  70. package/dist/turn-execution-result.d.ts +1 -0
  71. package/dist/turn-execution-result.d.ts.map +1 -1
  72. package/dist/turn-outcome-tool-session.d.ts +0 -2
  73. package/dist/turn-outcome-tool-session.d.ts.map +1 -1
  74. package/dist/turn-result-markdown.d.ts +2 -1
  75. package/dist/turn-result-markdown.d.ts.map +1 -1
  76. package/dist/turn-tree-strategy.d.ts +0 -1
  77. package/dist/turn-tree-strategy.d.ts.map +1 -1
  78. package/dist/worker-entry.js +16 -4
  79. package/dist/worker-entry.js.map +1 -1
  80. package/dist/worker-ipc-reporter.d.ts.map +1 -1
  81. package/dist/workspace/manifest.d.ts +4 -7
  82. package/dist/workspace/manifest.d.ts.map +1 -1
  83. package/dist/workspace/node-run-root-git-ops.d.ts +2 -2
  84. package/dist/workspace/node-run-root-git-ops.d.ts.map +1 -1
  85. package/dist/workspace/resource-aggregator.d.ts.map +1 -1
  86. package/dist/workspace/run-root.d.ts +21 -20
  87. package/dist/workspace/run-root.d.ts.map +1 -1
  88. package/package.json +8 -8
  89. package/src/automatic-turn-executor.ts +2 -0
  90. package/src/connection-diagnostics.ts +27 -0
  91. package/src/container-entry-main.ts +24 -0
  92. package/src/container-entry.ts +246 -0
  93. package/src/development-tool-environment.ts +490 -0
  94. package/src/diagnostics.ts +1 -0
  95. package/src/docker-registry-credentials.ts +65 -0
  96. package/src/entry-runtime.ts +29 -5
  97. package/src/index.ts +1 -39
  98. package/src/input-consumer.ts +8 -29
  99. package/src/ipc.ts +50 -2
  100. package/src/logical-prompt-runner.ts +23 -29
  101. package/src/managed-pi-agent-dir.ts +8 -1
  102. package/src/managed-pi-bootstrap.ts +4 -3
  103. package/src/missing-tool-recovery-runner.ts +4 -18
  104. package/src/pi-adapter.ts +125 -56
  105. package/src/pi-event-reporter.ts +16 -38
  106. package/src/pi-resource-bundle.ts +77 -3
  107. package/src/pre-turn-targeted-inputs.ts +9 -11
  108. package/src/prompt-guards.ts +50 -75
  109. package/src/repository-bash-tool.ts +15 -0
  110. package/src/resource-loader-factory.ts +1 -18
  111. package/src/result-image-upload.ts +16 -27
  112. package/src/runtime/adapters.ts +46 -4
  113. package/src/runtime/bootstrap-session.ts +70 -39
  114. package/src/runtime/bootstrap.ts +184 -101
  115. package/src/runtime/failure-policy.ts +36 -42
  116. package/src/runtime/index.ts +47 -15
  117. package/src/runtime/lifecycle-reducer.ts +71 -173
  118. package/src/runtime/llm-turn-execution.ts +13 -30
  119. package/src/runtime/turn-execution.ts +78 -31
  120. package/src/session-snapshot-exchange.ts +46 -68
  121. package/src/turn-continuation.ts +9 -17
  122. package/src/turn-execution-error.ts +3 -11
  123. package/src/turn-execution-result.ts +1 -0
  124. package/src/turn-outcome-tool-session.ts +25 -21
  125. package/src/turn-result-markdown.ts +31 -34
  126. package/src/turn-tree-strategy.ts +6 -19
  127. package/src/worker-entry.ts +8 -0
  128. package/src/worker-ipc-reporter.ts +8 -16
  129. package/src/workspace/manifest.ts +5 -7
  130. package/src/workspace/node-run-root-git-ops.ts +65 -25
  131. package/src/workspace/resource-aggregator.ts +5 -16
  132. package/src/workspace/run-root.ts +50 -89
  133. package/dist/automatic-turn-executor.js +0 -58
  134. package/dist/automatic-turn-executor.js.map +0 -1
  135. package/dist/chunk-O6332GRG.js.map +0 -1
  136. package/dist/diagnostics.js +0 -51
  137. package/dist/diagnostics.js.map +0 -1
  138. package/dist/entry-runtime.js +0 -160
  139. package/dist/entry-runtime.js.map +0 -1
  140. package/dist/event-translator.js +0 -12
  141. package/dist/event-translator.js.map +0 -1
  142. package/dist/extension-entry-roots.js +0 -41
  143. package/dist/extension-entry-roots.js.map +0 -1
  144. package/dist/identified-pi-entry.js +0 -125
  145. package/dist/identified-pi-entry.js.map +0 -1
  146. package/dist/input-consumer.js +0 -34
  147. package/dist/input-consumer.js.map +0 -1
  148. package/dist/integration-tool-bridge.js +0 -53
  149. package/dist/integration-tool-bridge.js.map +0 -1
  150. package/dist/ipc.js +0 -192
  151. package/dist/ipc.js.map +0 -1
  152. package/dist/logical-prompt-runner.js +0 -225
  153. package/dist/logical-prompt-runner.js.map +0 -1
  154. package/dist/managed-pi-agent-dir.js +0 -66
  155. package/dist/managed-pi-agent-dir.js.map +0 -1
  156. package/dist/managed-pi-bootstrap.js +0 -135
  157. package/dist/managed-pi-bootstrap.js.map +0 -1
  158. package/dist/missing-tool-recovery-runner.js +0 -73
  159. package/dist/missing-tool-recovery-runner.js.map +0 -1
  160. package/dist/pi-adapter.js +0 -1648
  161. package/dist/pi-adapter.js.map +0 -1
  162. package/dist/pi-branch-guard.js +0 -75
  163. package/dist/pi-branch-guard.js.map +0 -1
  164. package/dist/pi-event-reporter.js +0 -136
  165. package/dist/pi-event-reporter.js.map +0 -1
  166. package/dist/pi-resource-bundle.js +0 -58
  167. package/dist/pi-resource-bundle.js.map +0 -1
  168. package/dist/pre-turn-targeted-inputs.js +0 -101
  169. package/dist/pre-turn-targeted-inputs.js.map +0 -1
  170. package/dist/prompt-guards.js +0 -318
  171. package/dist/prompt-guards.js.map +0 -1
  172. package/dist/question-bridge.js +0 -24
  173. package/dist/question-bridge.js.map +0 -1
  174. package/dist/question-tool.js +0 -54
  175. package/dist/question-tool.js.map +0 -1
  176. package/dist/replaying-request-bridge.js +0 -71
  177. package/dist/replaying-request-bridge.js.map +0 -1
  178. package/dist/resource-loader-factory.js +0 -87
  179. package/dist/resource-loader-factory.js.map +0 -1
  180. package/dist/result-image-upload.js +0 -183
  181. package/dist/result-image-upload.js.map +0 -1
  182. package/dist/runtime/adapters.js +0 -15
  183. package/dist/runtime/adapters.js.map +0 -1
  184. package/dist/runtime/bootstrap-session.js +0 -199
  185. package/dist/runtime/bootstrap-session.js.map +0 -1
  186. package/dist/runtime/bootstrap.js +0 -440
  187. package/dist/runtime/bootstrap.js.map +0 -1
  188. package/dist/runtime/failure-policy.js +0 -182
  189. package/dist/runtime/failure-policy.js.map +0 -1
  190. package/dist/runtime/index.js +0 -339
  191. package/dist/runtime/index.js.map +0 -1
  192. package/dist/runtime/lifecycle-reducer.js +0 -1142
  193. package/dist/runtime/lifecycle-reducer.js.map +0 -1
  194. package/dist/runtime/llm-turn-execution.js +0 -494
  195. package/dist/runtime/llm-turn-execution.js.map +0 -1
  196. package/dist/runtime/settings.js +0 -24
  197. package/dist/runtime/settings.js.map +0 -1
  198. package/dist/runtime/snapshot-policy.js +0 -16
  199. package/dist/runtime/snapshot-policy.js.map +0 -1
  200. package/dist/runtime/turn-execution.js +0 -151
  201. package/dist/runtime/turn-execution.js.map +0 -1
  202. package/dist/session-snapshot-exchange.js +0 -102
  203. package/dist/session-snapshot-exchange.js.map +0 -1
  204. package/dist/test-helpers/fake-websocket.js +0 -40
  205. package/dist/test-helpers/fake-websocket.js.map +0 -1
  206. package/dist/test-helpers/ipc-harness.d.ts +0 -11
  207. package/dist/test-helpers/ipc-harness.d.ts.map +0 -1
  208. package/dist/test-helpers/ipc-harness.js +0 -17
  209. package/dist/test-helpers/ipc-harness.js.map +0 -1
  210. package/dist/turn-continuation.js +0 -80
  211. package/dist/turn-continuation.js.map +0 -1
  212. package/dist/turn-execution-error.js +0 -64
  213. package/dist/turn-execution-error.js.map +0 -1
  214. package/dist/turn-execution-result.js +0 -21
  215. package/dist/turn-execution-result.js.map +0 -1
  216. package/dist/turn-outcome-tool-session.js +0 -210
  217. package/dist/turn-outcome-tool-session.js.map +0 -1
  218. package/dist/turn-record-id.js +0 -10
  219. package/dist/turn-record-id.js.map +0 -1
  220. package/dist/turn-result-markdown.js +0 -263
  221. package/dist/turn-result-markdown.js.map +0 -1
  222. package/dist/turn-tree-strategy.js +0 -80
  223. package/dist/turn-tree-strategy.js.map +0 -1
  224. package/dist/worker-http.js +0 -9
  225. package/dist/worker-http.js.map +0 -1
  226. package/dist/worker-ipc-reporter.js +0 -58
  227. package/dist/worker-ipc-reporter.js.map +0 -1
  228. package/dist/worker-payloads.js +0 -66
  229. package/dist/worker-payloads.js.map +0 -1
  230. package/dist/worker-start-payload.js +0 -5
  231. package/dist/worker-start-payload.js.map +0 -1
  232. package/dist/workspace/manifest.js +0 -79
  233. package/dist/workspace/manifest.js.map +0 -1
  234. package/dist/workspace/node-run-root-git-ops.js +0 -96
  235. package/dist/workspace/node-run-root-git-ops.js.map +0 -1
  236. package/dist/workspace/resource-aggregator.js +0 -39
  237. package/dist/workspace/resource-aggregator.js.map +0 -1
  238. package/dist/workspace/run-root.js +0 -209
  239. package/dist/workspace/run-root.js.map +0 -1
  240. package/src/test-helpers/ipc-harness.ts +0 -19
@@ -1,8 +1,4 @@
1
- import {
2
- failActiveTurnProgress,
3
- type ProcessSemanticEntryRefKey,
4
- type TurnProgressReport,
5
- } from "@leitwerk-dev/domain";
1
+ import type { TurnProgressReport } from "@leitwerk-dev/domain";
6
2
  import type {
7
3
  LlmTurnDefinition,
8
4
  TurnOptions,
@@ -14,7 +10,10 @@ import { assertValidLlmTurnDefinition } from "@leitwerk-dev/process-sdk";
14
10
  import { createAutomaticTurnExecutor } from "../automatic-turn-executor.js";
15
11
  import type { WorkerOperationEmitter } from "../diagnostics.js";
16
12
  import type { PiTreeHandle } from "../pi-adapter.js";
17
- import type { PreTurnTargetedInput } from "../pre-turn-targeted-inputs.js";
13
+ import type {
14
+ AppliedTargetedInputMetadata,
15
+ PreTurnTargetedInput,
16
+ } from "../pre-turn-targeted-inputs.js";
18
17
  import type { WorkerQuestionRequest } from "../question-tool.js";
19
18
  import { TurnExecutionError } from "../turn-execution-error.js";
20
19
  import { TurnExecutionFailure, type TurnExecutionMeta } from "../turn-execution-result.js";
@@ -25,13 +24,7 @@ import { executeLlmTurn } from "./llm-turn-execution.js";
25
24
  export interface AppliedTargetedInput {
26
25
  inputId: string;
27
26
  sequence: number;
28
- meta?: {
29
- currentPrimaryPathLeafId?: string | null;
30
- rootEntryId?: string | null;
31
- targetSemanticRef?: ProcessSemanticEntryRefKey | null;
32
- targetProductName?: string | null;
33
- targetEntryId?: string | null;
34
- };
27
+ meta?: AppliedTargetedInputMetadata;
35
28
  }
36
29
 
37
30
  export type SelectedTurnExecutionResult =
@@ -70,6 +63,22 @@ function failedResult(
70
63
  return { kind: "failed", failure, appliedTargetedInputs };
71
64
  }
72
65
 
66
+ function normalizePreparedData(value: unknown): unknown {
67
+ if (value === undefined) {
68
+ throw new Error("LLM turn preparation must return JSON-serializable data");
69
+ }
70
+ let serialized: string;
71
+ try {
72
+ serialized = JSON.stringify(value);
73
+ } catch {
74
+ throw new Error("LLM turn preparation must return JSON-serializable data");
75
+ }
76
+ if (Buffer.byteLength(serialized, "utf8") > 65_536) {
77
+ throw new Error("LLM turn preparation data exceeds 65536 bytes");
78
+ }
79
+ return JSON.parse(serialized) as unknown;
80
+ }
81
+
73
82
  /** Execute one accepted selected turn and return its single terminal fact. */
74
83
  export async function executeSelectedTurn(
75
84
  input: SelectedTurnExecutionInput,
@@ -89,6 +98,24 @@ export async function executeSelectedTurn(
89
98
  if (!handler) throw new Error(`Validated turn handler '${currentTurnId}' is unavailable`);
90
99
  let automaticIntegrationCallIndex = 0;
91
100
  let latestProgressReport: TurnProgressReport | null = null;
101
+ const reportProgress = (report: TurnProgressReport) => {
102
+ latestProgressReport = report;
103
+ input.emit({ kind: "progress", turnRecordId: input.turnRecordId, report });
104
+ };
105
+ const callIntegrationTool = async (name: string, args: Record<string, unknown>) => {
106
+ const tool = input.integrationTools?.find((candidate) => candidate.name === name);
107
+ if (!tool) {
108
+ throw new Error(`Integration tool '${name}' is not authorized for turn '${currentTurnId}'`);
109
+ }
110
+ automaticIntegrationCallIndex += 1;
111
+ return tool.execute(args, {
112
+ toolCallId:
113
+ selectedTurnType === "automatic"
114
+ ? `${input.turnRecordId}:${automaticIntegrationCallIndex}:${name}`
115
+ : `${input.turnRecordId}:prepare:${automaticIntegrationCallIndex}:${name}`,
116
+ signal: input.signal,
117
+ });
118
+ };
92
119
 
93
120
  const ctx = {
94
121
  process: processSnapshot,
@@ -100,23 +127,8 @@ export async function executeSelectedTurn(
100
127
  workspaceRoot: input.session.workspaceRoot,
101
128
  ...(selectedTurnType === "automatic"
102
129
  ? {
103
- reportProgress(report: TurnProgressReport) {
104
- latestProgressReport = report;
105
- input.emit({ kind: "progress", turnRecordId: input.turnRecordId, report });
106
- },
107
- async callIntegrationTool(name: string, args: Record<string, unknown>) {
108
- const tool = input.integrationTools?.find((candidate) => candidate.name === name);
109
- if (!tool) {
110
- throw new Error(
111
- `Integration tool '${name}' is not authorized for turn '${currentTurnId}'`,
112
- );
113
- }
114
- automaticIntegrationCallIndex += 1;
115
- return tool.execute(args, {
116
- toolCallId: `${input.turnRecordId}:${automaticIntegrationCallIndex}:${name}`,
117
- signal: input.signal,
118
- });
119
- },
130
+ reportProgress,
131
+ callIntegrationTool,
120
132
  }
121
133
  : {}),
122
134
  } as WorkerProcessContext;
@@ -156,9 +168,36 @@ export async function executeSelectedTurn(
156
168
  `Turn '${currentTurnId}' requires a Pi handle`,
157
169
  );
158
170
  }
171
+ let prepared = input.session.llmPreparation?.data;
172
+ if (turnDef.prepare && !input.session.llmPreparation) {
173
+ try {
174
+ prepared = normalizePreparedData(
175
+ await turnDef.prepare({
176
+ ...ctx,
177
+ reportProgress,
178
+ callIntegrationTool,
179
+ }),
180
+ );
181
+ input.emit({ kind: "prepared", turnRecordId: input.turnRecordId, data: prepared });
182
+ } catch (error) {
183
+ const message = error instanceof Error ? error.message : String(error);
184
+ throw new TurnExecutionFailure({
185
+ turnRecordId: input.turnRecordId,
186
+ turnId: currentTurnId,
187
+ turnType: "llm",
188
+ pathType: turnDef.branchType,
189
+ failure: new TurnExecutionError(
190
+ currentTurnId,
191
+ "infrastructure",
192
+ `Turn '${currentTurnId}' preparation failed: ${message}`,
193
+ ),
194
+ });
195
+ }
196
+ }
159
197
  const completed = await executeLlmTurn({
160
198
  resolvedWorkerProcess,
161
199
  ctx,
200
+ ...(turnDef.prepare ? { prepared } : {}),
162
201
  piHandle,
163
202
  turnDef,
164
203
  turnId: currentTurnId,
@@ -226,10 +265,18 @@ export async function executeSelectedTurn(
226
265
  } catch (error) {
227
266
  const failedProgressReport = latestProgressReport as TurnProgressReport | null;
228
267
  if (failedProgressReport) {
268
+ const message = error instanceof Error ? error.message : String(error);
269
+ const steps = failedProgressReport.steps.map((step) =>
270
+ step.status === "in_progress"
271
+ ? { ...step, status: "failed" as const, detail: message }
272
+ : step,
273
+ );
274
+ const report: TurnProgressReport = { ...failedProgressReport, steps };
275
+ latestProgressReport = report;
229
276
  input.emit({
230
277
  kind: "progress",
231
278
  turnRecordId: input.turnRecordId,
232
- report: failActiveTurnProgress(failedProgressReport),
279
+ report,
233
280
  });
234
281
  }
235
282
  if (error instanceof TurnExecutionFailure) return failedResult(error, appliedTargetedInputs);
@@ -1,4 +1,4 @@
1
- import { readFile, stat } from "node:fs/promises";
1
+ import { readFile } from "node:fs/promises";
2
2
  import { isEnoent } from "@leitwerk-dev/process-sdk";
3
3
  import {
4
4
  buildWorkerSessionSnapshotPath,
@@ -11,17 +11,36 @@ import {
11
11
  } from "@leitwerk-dev/worker-protocol";
12
12
  import { resolveWorkerHttpUrl } from "./worker-http.js";
13
13
 
14
+ /** @internal */
14
15
  export type SessionSnapshotUploadResult =
15
- | { kind: "disabled" }
16
- | { kind: "missing" }
17
- | { kind: "empty" }
18
- | { kind: "uploaded"; bytes: number };
16
+ | {
17
+ /** @internal */
18
+ kind: "disabled";
19
+ }
20
+ | {
21
+ /** @internal */
22
+ kind: "missing";
23
+ }
24
+ | {
25
+ /** @internal */
26
+ kind: "empty";
27
+ }
28
+ | {
29
+ /** @internal */
30
+ kind: "uploaded";
31
+ /** @internal */
32
+ bytes: number;
33
+ };
19
34
 
35
+ /** @internal */
20
36
  export interface WorkerSessionSnapshotUploadMetadata {
37
+ /** @internal */
21
38
  turnRecordId?: string | null;
22
39
  }
23
40
 
41
+ /** @internal */
24
42
  export interface WorkerSessionSnapshotExchange {
43
+ /** @internal */
25
44
  uploadSnapshot(
26
45
  treeFile: string,
27
46
  reason: string,
@@ -31,40 +50,6 @@ export interface WorkerSessionSnapshotExchange {
31
50
 
32
51
  type FetchLike = typeof fetch;
33
52
 
34
- export function resolveWorkerSessionSnapshotUrl(input: {
35
- serverUrl: string;
36
- instanceId: string;
37
- }): string {
38
- return resolveWorkerHttpUrl(input.serverUrl, buildWorkerSessionSnapshotPath(input.instanceId));
39
- }
40
-
41
- async function localFileSize(filePath: string): Promise<number | null> {
42
- try {
43
- return (await stat(filePath)).size;
44
- } catch (error) {
45
- if (isEnoent(error)) {
46
- return null;
47
- }
48
- throw error;
49
- }
50
- }
51
-
52
- async function fetchWithTimeout(input: {
53
- fetchImpl: FetchLike;
54
- url: string;
55
- init: RequestInit;
56
- timeoutMs: number;
57
- }): Promise<Response> {
58
- const controller = new AbortController();
59
- const timeout = setTimeout(() => controller.abort(), input.timeoutMs);
60
- timeout.unref?.();
61
- try {
62
- return await input.fetchImpl(input.url, { ...input.init, signal: controller.signal });
63
- } finally {
64
- clearTimeout(timeout);
65
- }
66
- }
67
-
68
53
  export function createWorkerSessionSnapshotExchange(input: {
69
54
  serverUrl: string;
70
55
  token: string;
@@ -78,10 +63,10 @@ export function createWorkerSessionSnapshotExchange(input: {
78
63
  return disabledWorkerSessionSnapshotExchange;
79
64
  }
80
65
  const timeoutMs = input.timeoutMs ?? 30_000;
81
- const snapshotUrl = resolveWorkerSessionSnapshotUrl({
82
- serverUrl: input.serverUrl,
83
- instanceId: input.instanceId,
84
- });
66
+ const snapshotUrl = resolveWorkerHttpUrl(
67
+ input.serverUrl,
68
+ buildWorkerSessionSnapshotPath(input.instanceId),
69
+ );
85
70
  const authHeaders = {
86
71
  authorization: `Bearer ${input.token}`,
87
72
  [WORKER_SESSION_SNAPSHOT_WORKER_ID_HEADER]: input.workerId,
@@ -89,33 +74,26 @@ export function createWorkerSessionSnapshotExchange(input: {
89
74
 
90
75
  return {
91
76
  async uploadSnapshot(treeFile, reason, metadata = {}) {
92
- const size = await localFileSize(treeFile);
93
- if (size === null) {
94
- return { kind: "missing" };
95
- }
96
- if (size === 0) {
97
- return { kind: "empty" };
98
- }
99
- const content = await readFile(treeFile, "utf8");
100
- if (content.length === 0) {
101
- return { kind: "empty" };
77
+ let content: string;
78
+ try {
79
+ content = await readFile(treeFile, "utf8");
80
+ } catch (error) {
81
+ if (isEnoent(error)) return { kind: "missing" };
82
+ throw error;
102
83
  }
103
- const response = await fetchWithTimeout({
104
- fetchImpl,
105
- url: snapshotUrl,
106
- timeoutMs,
107
- init: {
108
- method: "PUT",
109
- headers: {
110
- ...authHeaders,
111
- "content-type": WORKER_SESSION_SNAPSHOT_CONTENT_TYPE,
112
- [WORKER_SESSION_SNAPSHOT_REASON_HEADER]: reason,
113
- ...(metadata.turnRecordId
114
- ? { [WORKER_SESSION_SNAPSHOT_TURN_RECORD_ID_HEADER]: metadata.turnRecordId }
115
- : {}),
116
- },
117
- body: content,
84
+ if (content.length === 0) return { kind: "empty" };
85
+ const response = await fetchImpl(snapshotUrl, {
86
+ method: "PUT",
87
+ headers: {
88
+ ...authHeaders,
89
+ "content-type": WORKER_SESSION_SNAPSHOT_CONTENT_TYPE,
90
+ [WORKER_SESSION_SNAPSHOT_REASON_HEADER]: reason,
91
+ ...(metadata.turnRecordId
92
+ ? { [WORKER_SESSION_SNAPSHOT_TURN_RECORD_ID_HEADER]: metadata.turnRecordId }
93
+ : {}),
118
94
  },
95
+ body: content,
96
+ signal: AbortSignal.timeout(timeoutMs),
119
97
  });
120
98
  if (!response.ok) {
121
99
  throw new Error(`Session snapshot upload failed with HTTP ${response.status}`);
@@ -1,5 +1,9 @@
1
1
  import type { ProcessInstance } from "@leitwerk-dev/domain";
2
- import { DEFAULT_CONTINUE_PROMPT, normalizeContinuePrompt } from "@leitwerk-dev/domain";
2
+ import {
3
+ DEFAULT_CONTINUE_PROMPT,
4
+ normalizeContinuePrompt,
5
+ readNonBlankString,
6
+ } from "@leitwerk-dev/domain";
3
7
  import type { PiTreeHandle } from "./pi-adapter.js";
4
8
  import type { PreTurnTargetedInput } from "./pre-turn-targeted-inputs.js";
5
9
  import { TurnExecutionError } from "./turn-execution-error.js";
@@ -74,14 +78,6 @@ export async function prepareContinuationUserPrompt(input: {
74
78
  return normalizedPrompt;
75
79
  }
76
80
 
77
- function readNonEmptyMetadataString(
78
- metadata: ProcessInstance["metadata"],
79
- key: string,
80
- ): string | null {
81
- const value = metadata?.[key];
82
- return typeof value === "string" && value.trim() !== "" ? value : null;
83
- }
84
-
85
81
  export function resolveTurnContinuationState(input: {
86
82
  process: Pick<ProcessInstance, "selectedTurnId" | "metadata">;
87
83
  turnId: string;
@@ -94,13 +90,9 @@ export function resolveTurnContinuationState(input: {
94
90
  if (input.process.selectedTurnId !== input.turnId) {
95
91
  return null;
96
92
  }
97
- const continueFromPiEntryId = readNonEmptyMetadataString(
98
- input.process.metadata,
99
- "continueFromPiEntryId",
100
- );
101
- const continueFromTurnRecordId = readNonEmptyMetadataString(
102
- input.process.metadata,
103
- "continueFromTurnRecordId",
93
+ const continueFromPiEntryId = readNonBlankString(input.process.metadata?.continueFromPiEntryId);
94
+ const continueFromTurnRecordId = readNonBlankString(
95
+ input.process.metadata?.continueFromTurnRecordId,
104
96
  );
105
97
  if (!continueFromPiEntryId || !continueFromTurnRecordId) {
106
98
  return null;
@@ -110,7 +102,7 @@ export function resolveTurnContinuationState(input: {
110
102
  continuePrompt:
111
103
  normalizeContinuePrompt(input.process.metadata?.continuePrompt) ?? DEFAULT_CONTINUE_PROMPT,
112
104
  savedPrimaryLeafId:
113
- readNonEmptyMetadataString(input.process.metadata, "continueSavedPrimaryLeafEntryId") ??
105
+ readNonBlankString(input.process.metadata?.continueSavedPrimaryLeafEntryId) ??
114
106
  readProcessSemanticEntryRefs(input.state)?.currentPrimaryPathLeaf?.entryId ??
115
107
  null,
116
108
  };
@@ -3,7 +3,7 @@ import type {
3
3
  TurnFailureCode,
4
4
  WorkerErrorClass,
5
5
  } from "@leitwerk-dev/domain";
6
- import { isWorkerErrorClass } from "@leitwerk-dev/domain";
6
+ import { isWorkerErrorClass, toErrorMessage } from "@leitwerk-dev/domain";
7
7
  import { isPiBranchDriftError } from "./pi-branch-guard.js";
8
8
 
9
9
  export type TurnFailureReportOptions = {
@@ -61,10 +61,7 @@ export function classifyRuntimeError(
61
61
  : String(error),
62
62
  };
63
63
  }
64
- if (error instanceof Error && error.message.trim() !== "") {
65
- return { errorClass: fallbackErrorClass, message: error.message };
66
- }
67
- return { errorClass: fallbackErrorClass, message: String(error) };
64
+ return { errorClass: fallbackErrorClass, message: toErrorMessage(error) };
68
65
  }
69
66
 
70
67
  export function buildTurnFailureReport(
@@ -94,9 +91,4 @@ export function buildTurnFailureReport(
94
91
  };
95
92
  }
96
93
 
97
- export function toErrorMessage(error: unknown): string {
98
- if (error instanceof Error && error.message.trim() !== "") {
99
- return error.message;
100
- }
101
- return String(error);
102
- }
94
+ export { toErrorMessage } from "@leitwerk-dev/domain";
@@ -9,6 +9,7 @@ export interface TurnExecutionMeta {
9
9
  forkPiEntryId?: string | null;
10
10
  resultPiEntryId?: string | null;
11
11
  turnResultMarkdown?: string | null;
12
+ resultSummary?: string;
12
13
  rootEntryId?: string | null;
13
14
  }
14
15
 
@@ -45,9 +45,7 @@ export type ToolCompletionSnapshot<TOutcome extends string> = {
45
45
  };
46
46
 
47
47
  export interface TurnOutcomeToolSession<TOutcome extends string> {
48
- readonly outcomeToolNames: string[];
49
48
  readonly usesOutcomeTools: boolean;
50
- readonly requiresMarkdownResultToolCall: boolean;
51
49
  readonly tools: PiCustomTool[];
52
50
  readonly activeTools: readonly string[];
53
51
  addPromptSuffix(promptText: string): string;
@@ -81,19 +79,11 @@ function cloneSelectedOutcome<TOutcome extends string>(
81
79
  function cloneTurnResultMarkdownState(state: TurnResultMarkdownState): TurnResultMarkdownState {
82
80
  return {
83
81
  markdown: state.markdown,
82
+ ...(state.resultSummary ? { resultSummary: state.resultSummary } : {}),
84
83
  publicationCount: state.publicationCount,
85
84
  };
86
85
  }
87
86
 
88
- function snapshotToolCompletionState<TOutcome extends string>(
89
- value: ToolCompletionSnapshot<TOutcome>,
90
- ): ToolCompletionSnapshot<TOutcome> {
91
- return {
92
- selectedOutcome: cloneSelectedOutcome(value.selectedOutcome),
93
- markdownState: cloneTurnResultMarkdownState(value.markdownState),
94
- };
95
- }
96
-
97
87
  export function createTurnOutcomeToolSession<TOutcome extends string>(input: {
98
88
  turnId: string;
99
89
  turnRecordId?: string;
@@ -133,7 +123,15 @@ export function createTurnOutcomeToolSession<TOutcome extends string>(input: {
133
123
  name: outcome,
134
124
  description: spec.description,
135
125
  parameters: {
136
- ...Object.fromEntries(Object.entries(spec.parameters).map(([key, value]) => [key, value])),
126
+ ...Object.fromEntries(Object.entries(spec.parameters)),
127
+ ...(injectsGlobalMarkdownParameter
128
+ ? {
129
+ resultSummary: {
130
+ type: "string",
131
+ description: "Concise result summary for this attempt.",
132
+ },
133
+ }
134
+ : {}),
137
135
  ...(injectsGlobalMarkdownParameter && outcomeToolMarkdownParameterName
138
136
  ? {
139
137
  [outcomeToolMarkdownParameterName]: {
@@ -152,10 +150,19 @@ export function createTurnOutcomeToolSession<TOutcome extends string>(input: {
152
150
  const acceptsOutcome = selectedOutcome === null;
153
151
  if (acceptsOutcome) {
154
152
  let outcomeParams = args;
153
+ if (spec.resultSummaryParameter && typeof args[spec.resultSummaryParameter] === "string")
154
+ turnResultMarkdownStateRef.current.resultSummary = String(
155
+ args[spec.resultSummaryParameter],
156
+ ).trim();
155
157
  if (markdownParameterName) {
156
158
  const published = publishTurnResultMarkdownValue(
157
159
  turnResultMarkdownStateRef.current,
158
160
  args[markdownParameterName],
161
+ spec.resultSummaryParameter
162
+ ? args[spec.resultSummaryParameter]
163
+ : injectsGlobalMarkdownParameter
164
+ ? args.resultSummary
165
+ : undefined,
159
166
  );
160
167
  if (!published.response.ok) {
161
168
  return published.response;
@@ -164,6 +171,7 @@ export function createTurnOutcomeToolSession<TOutcome extends string>(input: {
164
171
  if (injectsGlobalMarkdownParameter) {
165
172
  outcomeParams = { ...args };
166
173
  delete outcomeParams[markdownParameterName];
174
+ delete outcomeParams.resultSummary;
167
175
  }
168
176
  }
169
177
  selectedOutcome = { outcome: outcome as TOutcome, params: outcomeParams };
@@ -223,9 +231,7 @@ export function createTurnOutcomeToolSession<TOutcome extends string>(input: {
223
231
  } satisfies TurnOutcomeToolSession<TOutcome>["terminalAcknowledgement"];
224
232
 
225
233
  return {
226
- outcomeToolNames,
227
234
  usesOutcomeTools,
228
- requiresMarkdownResultToolCall,
229
235
  tools,
230
236
  activeTools,
231
237
  terminalAcknowledgement: terminalAcknowledgementControl,
@@ -252,10 +258,10 @@ export function createTurnOutcomeToolSession<TOutcome extends string>(input: {
252
258
  );
253
259
  },
254
260
  getCompletionState() {
255
- return snapshotToolCompletionState({
256
- selectedOutcome,
257
- markdownState: turnResultMarkdownStateRef.current,
258
- });
261
+ return {
262
+ selectedOutcome: cloneSelectedOutcome(selectedOutcome),
263
+ markdownState: cloneTurnResultMarkdownState(turnResultMarkdownStateRef.current),
264
+ };
259
265
  },
260
266
  shouldBlockToolCall(toolName) {
261
267
  if (selectedOutcome === null) {
@@ -299,9 +305,7 @@ export function createTurnOutcomeToolSession<TOutcome extends string>(input: {
299
305
  : {}),
300
306
  };
301
307
  },
302
- describeRecovery(recovery) {
303
- return describeMissingTurnToolCallRecovery(recovery);
304
- },
308
+ describeRecovery: describeMissingTurnToolCallRecovery,
305
309
  finalizeMarkdown(completionState, assistantMarkdown) {
306
310
  return finalizeTurnResultMarkdown({
307
311
  behavior: input.turnDef.turnResultMarkdown,
@@ -8,6 +8,7 @@ import { readValueAtPath } from "@leitwerk-dev/protocol";
8
8
 
9
9
  export interface TurnResultMarkdownState {
10
10
  markdown: string | null;
11
+ resultSummary?: string;
11
12
  publicationCount: number;
12
13
  }
13
14
 
@@ -74,6 +75,7 @@ export function createTurnResultMarkdownState(): TurnResultMarkdownState {
74
75
  export function publishTurnResultMarkdownValue(
75
76
  state: TurnResultMarkdownState,
76
77
  value: unknown,
78
+ resultSummary?: unknown,
77
79
  ): {
78
80
  state: TurnResultMarkdownState;
79
81
  response: TurnResultMarkdownToolResponse;
@@ -92,6 +94,9 @@ export function publishTurnResultMarkdownValue(
92
94
  }
93
95
  const nextState: TurnResultMarkdownState = {
94
96
  markdown: validation.markdown,
97
+ ...(typeof resultSummary === "string" && resultSummary.trim()
98
+ ? { resultSummary: resultSummary.trim() }
99
+ : {}),
95
100
  publicationCount: state.publicationCount + 1,
96
101
  };
97
102
  return {
@@ -119,6 +124,10 @@ export function createMarkdownResultTool(stateRef: {
119
124
  description:
120
125
  "Publish the operator-facing markdown result for this turn. Pass raw markdown only and do not wrap the entire markdown in triple backticks.",
121
126
  parameters: {
127
+ resultSummary: {
128
+ type: "string",
129
+ description: "Concise summary of this attempt’s result, based on completed work.",
130
+ },
122
131
  markdown: {
123
132
  type: "string",
124
133
  description:
@@ -126,7 +135,11 @@ export function createMarkdownResultTool(stateRef: {
126
135
  },
127
136
  },
128
137
  execute: async (args: Record<string, unknown>) => {
129
- const published = publishTurnResultMarkdownValue(stateRef.current, args.markdown);
138
+ const published = publishTurnResultMarkdownValue(
139
+ stateRef.current,
140
+ args.markdown,
141
+ args.resultSummary,
142
+ );
130
143
  stateRef.current = published.state;
131
144
  return published.response;
132
145
  },
@@ -318,38 +331,22 @@ export function finalizeTurnResultMarkdown(input: {
318
331
  if (!input.behavior || input.behavior.mode === "none") {
319
332
  return { markdown: input.state.markdown ?? null, errorMessage: null };
320
333
  }
321
- if (input.behavior.mode === "assistant_output") {
322
- const markdown =
323
- typeof input.assistantMarkdown === "string" ? input.assistantMarkdown.trim() : "";
324
- if (markdown.length > 0) {
325
- return { markdown, errorMessage: null };
326
- }
327
- return input.behavior.required
328
- ? {
329
- markdown: null,
330
- errorMessage: "Turn requires non-empty assistant output to publish turn result markdown",
331
- }
332
- : { markdown: null, errorMessage: null };
333
- }
334
- if (input.behavior.mode === "outcome_tool_argument") {
335
- if (input.state.markdown) {
336
- return { markdown: input.state.markdown, errorMessage: null };
337
- }
338
- return input.behavior.required
339
- ? {
340
- markdown: null,
341
- errorMessage: `Turn requires a successful outcome tool call with a non-empty '${input.behavior.parameterName}' markdown argument`,
342
- }
343
- : { markdown: null, errorMessage: null };
344
- }
345
- if (input.state.markdown) {
346
- return { markdown: input.state.markdown, errorMessage: null };
347
- }
348
- if (input.behavior.required) {
349
- return {
350
- markdown: null,
351
- errorMessage: `Turn requires a successful '${input.behavior.toolName}' tool call to publish turn result markdown`,
352
- };
334
+ const markdown =
335
+ input.behavior.mode === "assistant_output"
336
+ ? typeof input.assistantMarkdown === "string"
337
+ ? input.assistantMarkdown.trim()
338
+ : null
339
+ : input.state.markdown;
340
+ if (markdown || !input.behavior.required) {
341
+ return { markdown: markdown || null, errorMessage: null };
353
342
  }
354
- return { markdown: null, errorMessage: null };
343
+ return {
344
+ markdown: null,
345
+ errorMessage:
346
+ input.behavior.mode === "assistant_output"
347
+ ? "Turn requires non-empty assistant output to publish turn result markdown"
348
+ : input.behavior.mode === "outcome_tool_argument"
349
+ ? `Turn requires a successful outcome tool call with a non-empty '${input.behavior.parameterName}' markdown argument`
350
+ : `Turn requires a successful '${input.behavior.toolName}' tool call to publish turn result markdown`,
351
+ };
355
352
  }
@@ -24,7 +24,6 @@ export interface TurnTreePlan {
24
24
  }
25
25
 
26
26
  export function resolveRootEntryId(input: {
27
- currentLeafId: string | null;
28
27
  currentBranch: readonly Pick<PiTreeEntry, "id">[];
29
28
  topLevelNodes: readonly Pick<PiTreeNode, "entry">[];
30
29
  }): string | null {
@@ -41,7 +40,7 @@ export function resolveRootEntryIdFromHandle(
41
40
  const currentLeafId = piHandle.getLeafId();
42
41
  const currentBranch = piHandle.getBranch(currentLeafId ?? undefined);
43
42
  const topLevelNodes = piHandle.getTree();
44
- return resolveRootEntryId({ currentLeafId, currentBranch, topLevelNodes });
43
+ return resolveRootEntryId({ currentBranch, topLevelNodes });
45
44
  }
46
45
 
47
46
  function resolveContextAwareTurnStartSelection(input: {
@@ -83,11 +82,7 @@ export function planTurnTreeExecution(input: {
83
82
  hasPreTurnTargetedInputs?: boolean;
84
83
  }): TurnTreePlan {
85
84
  const startTarget = resolveProcessTurnStartTarget({
86
- selection: resolveContextAwareTurnStartSelection({
87
- turnDef: input.turnDef,
88
- preTurnStartSelection: input.preTurnStartSelection,
89
- hasPreTurnTargetedInputs: input.hasPreTurnTargetedInputs,
90
- }),
85
+ selection: resolveContextAwareTurnStartSelection(input),
91
86
  branchType: input.turnDef.branchType,
92
87
  currentLeafId: input.currentLeafId,
93
88
  rootEntryId: input.rootEntryId,
@@ -109,18 +104,10 @@ export async function positionHandleForTurn(
109
104
  piHandle: Pick<PiTreeHandle, "branch" | "branchFromRoot">,
110
105
  plan: TurnTreePlan,
111
106
  ): Promise<void> {
112
- switch (plan.startTarget.kind) {
113
- case "current_leaf": {
114
- return;
115
- }
116
- case "entry": {
117
- await piHandle.branch(plan.startTarget.entryId);
118
- return;
119
- }
120
- case "root": {
121
- await piHandle.branchFromRoot();
122
- return;
123
- }
107
+ if (plan.startTarget.kind === "entry") {
108
+ await piHandle.branch(plan.startTarget.entryId);
109
+ } else if (plan.startTarget.kind === "root") {
110
+ await piHandle.branchFromRoot();
124
111
  }
125
112
  }
126
113