@leitwerk-dev/worker 0.1.8 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (235) 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-ZTJ7UAOC.js → chunk-Y7S2MZD3.js} +1423 -917
  4. package/dist/chunk-Y7S2MZD3.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 +48 -0
  14. package/dist/development-tool-environment.d.ts.map +1 -0
  15. package/dist/diagnostics.d.ts +9 -1
  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 +1 -0
  20. package/dist/entry-runtime.d.ts.map +1 -1
  21. package/dist/index.d.ts +1 -0
  22. package/dist/index.d.ts.map +1 -1
  23. package/dist/index.js +44 -5
  24. package/dist/index.js.map +1 -1
  25. package/dist/input-consumer.d.ts +6 -11
  26. package/dist/input-consumer.d.ts.map +1 -1
  27. package/dist/ipc.d.ts +1 -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-bootstrap.d.ts.map +1 -1
  31. package/dist/missing-tool-recovery-runner.d.ts +4 -3
  32. package/dist/missing-tool-recovery-runner.d.ts.map +1 -1
  33. package/dist/pi-adapter.d.ts +1 -0
  34. package/dist/pi-adapter.d.ts.map +1 -1
  35. package/dist/pi-event-reporter.d.ts.map +1 -1
  36. package/dist/pi-resource-bundle.d.ts +11 -0
  37. package/dist/pi-resource-bundle.d.ts.map +1 -1
  38. package/dist/pre-turn-targeted-inputs.d.ts +8 -7
  39. package/dist/pre-turn-targeted-inputs.d.ts.map +1 -1
  40. package/dist/prompt-guards.d.ts.map +1 -1
  41. package/dist/repository-bash-tool.d.ts +4 -0
  42. package/dist/repository-bash-tool.d.ts.map +1 -0
  43. package/dist/resource-loader-factory.d.ts +1 -2
  44. package/dist/resource-loader-factory.d.ts.map +1 -1
  45. package/dist/result-image-upload.d.ts.map +1 -1
  46. package/dist/runtime/adapters.d.ts +2 -0
  47. package/dist/runtime/adapters.d.ts.map +1 -1
  48. package/dist/runtime/bootstrap-session.d.ts +8 -5
  49. package/dist/runtime/bootstrap-session.d.ts.map +1 -1
  50. package/dist/runtime/bootstrap.d.ts +14 -18
  51. package/dist/runtime/bootstrap.d.ts.map +1 -1
  52. package/dist/runtime/failure-policy.d.ts +1 -0
  53. package/dist/runtime/failure-policy.d.ts.map +1 -1
  54. package/dist/runtime/index.d.ts.map +1 -1
  55. package/dist/runtime/lifecycle-reducer.d.ts +4 -1
  56. package/dist/runtime/lifecycle-reducer.d.ts.map +1 -1
  57. package/dist/runtime/llm-turn-execution.d.ts +3 -8
  58. package/dist/runtime/llm-turn-execution.d.ts.map +1 -1
  59. package/dist/runtime/turn-execution.d.ts +2 -9
  60. package/dist/runtime/turn-execution.d.ts.map +1 -1
  61. package/dist/session-snapshot-exchange.d.ts +0 -4
  62. package/dist/session-snapshot-exchange.d.ts.map +1 -1
  63. package/dist/turn-continuation.d.ts.map +1 -1
  64. package/dist/turn-execution-error.d.ts +1 -1
  65. package/dist/turn-execution-error.d.ts.map +1 -1
  66. package/dist/turn-execution-result.d.ts +1 -0
  67. package/dist/turn-execution-result.d.ts.map +1 -1
  68. package/dist/turn-outcome-tool-session.d.ts +0 -2
  69. package/dist/turn-outcome-tool-session.d.ts.map +1 -1
  70. package/dist/turn-result-markdown.d.ts +2 -1
  71. package/dist/turn-result-markdown.d.ts.map +1 -1
  72. package/dist/turn-tree-strategy.d.ts +0 -1
  73. package/dist/turn-tree-strategy.d.ts.map +1 -1
  74. package/dist/worker-entry.js +16 -4
  75. package/dist/worker-entry.js.map +1 -1
  76. package/dist/worker-ipc-reporter.d.ts.map +1 -1
  77. package/dist/workspace/manifest.d.ts +4 -7
  78. package/dist/workspace/manifest.d.ts.map +1 -1
  79. package/dist/workspace/node-run-root-git-ops.d.ts +2 -2
  80. package/dist/workspace/node-run-root-git-ops.d.ts.map +1 -1
  81. package/dist/workspace/resource-aggregator.d.ts.map +1 -1
  82. package/dist/workspace/run-root.d.ts +9 -20
  83. package/dist/workspace/run-root.d.ts.map +1 -1
  84. package/package.json +8 -8
  85. package/src/automatic-turn-executor.ts +2 -0
  86. package/src/connection-diagnostics.ts +27 -0
  87. package/src/container-entry-main.ts +24 -0
  88. package/src/container-entry.ts +246 -0
  89. package/src/development-tool-environment.ts +452 -0
  90. package/src/diagnostics.ts +3 -1
  91. package/src/docker-registry-credentials.ts +65 -0
  92. package/src/entry-runtime.ts +5 -4
  93. package/src/index.ts +11 -0
  94. package/src/input-consumer.ts +7 -29
  95. package/src/ipc.ts +37 -2
  96. package/src/logical-prompt-runner.ts +23 -29
  97. package/src/managed-pi-bootstrap.ts +3 -3
  98. package/src/missing-tool-recovery-runner.ts +4 -18
  99. package/src/pi-adapter.ts +19 -50
  100. package/src/pi-event-reporter.ts +16 -38
  101. package/src/pi-resource-bundle.ts +67 -1
  102. package/src/pre-turn-targeted-inputs.ts +9 -11
  103. package/src/prompt-guards.ts +44 -75
  104. package/src/repository-bash-tool.ts +15 -0
  105. package/src/resource-loader-factory.ts +1 -18
  106. package/src/result-image-upload.ts +16 -27
  107. package/src/runtime/adapters.ts +2 -0
  108. package/src/runtime/bootstrap-session.ts +69 -39
  109. package/src/runtime/bootstrap.ts +160 -103
  110. package/src/runtime/failure-policy.ts +36 -42
  111. package/src/runtime/index.ts +49 -14
  112. package/src/runtime/lifecycle-reducer.ts +140 -173
  113. package/src/runtime/llm-turn-execution.ts +13 -30
  114. package/src/runtime/turn-execution.ts +91 -9
  115. package/src/session-snapshot-exchange.ts +23 -64
  116. package/src/turn-continuation.ts +9 -17
  117. package/src/turn-execution-error.ts +3 -11
  118. package/src/turn-execution-result.ts +1 -0
  119. package/src/turn-outcome-tool-session.ts +25 -21
  120. package/src/turn-result-markdown.ts +31 -34
  121. package/src/turn-tree-strategy.ts +6 -19
  122. package/src/worker-entry.ts +8 -0
  123. package/src/worker-ipc-reporter.ts +8 -16
  124. package/src/workspace/manifest.ts +5 -7
  125. package/src/workspace/node-run-root-git-ops.ts +65 -25
  126. package/src/workspace/resource-aggregator.ts +5 -16
  127. package/src/workspace/run-root.ts +38 -89
  128. package/dist/automatic-turn-executor.js +0 -58
  129. package/dist/automatic-turn-executor.js.map +0 -1
  130. package/dist/chunk-ZTJ7UAOC.js.map +0 -1
  131. package/dist/diagnostics.js +0 -51
  132. package/dist/diagnostics.js.map +0 -1
  133. package/dist/entry-runtime.js +0 -160
  134. package/dist/entry-runtime.js.map +0 -1
  135. package/dist/event-translator.js +0 -12
  136. package/dist/event-translator.js.map +0 -1
  137. package/dist/extension-entry-roots.js +0 -41
  138. package/dist/extension-entry-roots.js.map +0 -1
  139. package/dist/identified-pi-entry.js +0 -125
  140. package/dist/identified-pi-entry.js.map +0 -1
  141. package/dist/input-consumer.js +0 -34
  142. package/dist/input-consumer.js.map +0 -1
  143. package/dist/integration-tool-bridge.js +0 -53
  144. package/dist/integration-tool-bridge.js.map +0 -1
  145. package/dist/ipc.js +0 -192
  146. package/dist/ipc.js.map +0 -1
  147. package/dist/logical-prompt-runner.js +0 -225
  148. package/dist/logical-prompt-runner.js.map +0 -1
  149. package/dist/managed-pi-agent-dir.js +0 -66
  150. package/dist/managed-pi-agent-dir.js.map +0 -1
  151. package/dist/managed-pi-bootstrap.js +0 -135
  152. package/dist/managed-pi-bootstrap.js.map +0 -1
  153. package/dist/missing-tool-recovery-runner.js +0 -73
  154. package/dist/missing-tool-recovery-runner.js.map +0 -1
  155. package/dist/pi-adapter.js +0 -1648
  156. package/dist/pi-adapter.js.map +0 -1
  157. package/dist/pi-branch-guard.js +0 -75
  158. package/dist/pi-branch-guard.js.map +0 -1
  159. package/dist/pi-event-reporter.js +0 -136
  160. package/dist/pi-event-reporter.js.map +0 -1
  161. package/dist/pi-resource-bundle.js +0 -58
  162. package/dist/pi-resource-bundle.js.map +0 -1
  163. package/dist/pre-turn-targeted-inputs.js +0 -101
  164. package/dist/pre-turn-targeted-inputs.js.map +0 -1
  165. package/dist/prompt-guards.js +0 -318
  166. package/dist/prompt-guards.js.map +0 -1
  167. package/dist/question-bridge.js +0 -24
  168. package/dist/question-bridge.js.map +0 -1
  169. package/dist/question-tool.js +0 -54
  170. package/dist/question-tool.js.map +0 -1
  171. package/dist/replaying-request-bridge.js +0 -71
  172. package/dist/replaying-request-bridge.js.map +0 -1
  173. package/dist/resource-loader-factory.js +0 -87
  174. package/dist/resource-loader-factory.js.map +0 -1
  175. package/dist/result-image-upload.js +0 -183
  176. package/dist/result-image-upload.js.map +0 -1
  177. package/dist/runtime/adapters.js +0 -15
  178. package/dist/runtime/adapters.js.map +0 -1
  179. package/dist/runtime/bootstrap-session.js +0 -199
  180. package/dist/runtime/bootstrap-session.js.map +0 -1
  181. package/dist/runtime/bootstrap.js +0 -440
  182. package/dist/runtime/bootstrap.js.map +0 -1
  183. package/dist/runtime/failure-policy.js +0 -182
  184. package/dist/runtime/failure-policy.js.map +0 -1
  185. package/dist/runtime/index.js +0 -336
  186. package/dist/runtime/index.js.map +0 -1
  187. package/dist/runtime/lifecycle-reducer.js +0 -1100
  188. package/dist/runtime/lifecycle-reducer.js.map +0 -1
  189. package/dist/runtime/llm-turn-execution.js +0 -494
  190. package/dist/runtime/llm-turn-execution.js.map +0 -1
  191. package/dist/runtime/settings.js +0 -24
  192. package/dist/runtime/settings.js.map +0 -1
  193. package/dist/runtime/snapshot-policy.js +0 -16
  194. package/dist/runtime/snapshot-policy.js.map +0 -1
  195. package/dist/runtime/turn-execution.js +0 -121
  196. package/dist/runtime/turn-execution.js.map +0 -1
  197. package/dist/session-snapshot-exchange.js +0 -102
  198. package/dist/session-snapshot-exchange.js.map +0 -1
  199. package/dist/test-helpers/fake-websocket.js +0 -40
  200. package/dist/test-helpers/fake-websocket.js.map +0 -1
  201. package/dist/test-helpers/ipc-harness.d.ts +0 -11
  202. package/dist/test-helpers/ipc-harness.d.ts.map +0 -1
  203. package/dist/test-helpers/ipc-harness.js +0 -17
  204. package/dist/test-helpers/ipc-harness.js.map +0 -1
  205. package/dist/turn-continuation.js +0 -80
  206. package/dist/turn-continuation.js.map +0 -1
  207. package/dist/turn-execution-error.js +0 -64
  208. package/dist/turn-execution-error.js.map +0 -1
  209. package/dist/turn-execution-result.js +0 -21
  210. package/dist/turn-execution-result.js.map +0 -1
  211. package/dist/turn-outcome-tool-session.js +0 -210
  212. package/dist/turn-outcome-tool-session.js.map +0 -1
  213. package/dist/turn-record-id.js +0 -10
  214. package/dist/turn-record-id.js.map +0 -1
  215. package/dist/turn-result-markdown.js +0 -263
  216. package/dist/turn-result-markdown.js.map +0 -1
  217. package/dist/turn-tree-strategy.js +0 -80
  218. package/dist/turn-tree-strategy.js.map +0 -1
  219. package/dist/worker-http.js +0 -9
  220. package/dist/worker-http.js.map +0 -1
  221. package/dist/worker-ipc-reporter.js +0 -58
  222. package/dist/worker-ipc-reporter.js.map +0 -1
  223. package/dist/worker-payloads.js +0 -66
  224. package/dist/worker-payloads.js.map +0 -1
  225. package/dist/worker-start-payload.js +0 -5
  226. package/dist/worker-start-payload.js.map +0 -1
  227. package/dist/workspace/manifest.js +0 -79
  228. package/dist/workspace/manifest.js.map +0 -1
  229. package/dist/workspace/node-run-root-git-ops.js +0 -96
  230. package/dist/workspace/node-run-root-git-ops.js.map +0 -1
  231. package/dist/workspace/resource-aggregator.js +0 -39
  232. package/dist/workspace/resource-aggregator.js.map +0 -1
  233. package/dist/workspace/run-root.js +0 -209
  234. package/dist/workspace/run-root.js.map +0 -1
  235. package/src/test-helpers/ipc-harness.ts +0 -19
@@ -1,4 +1,4 @@
1
- import type { ProcessSemanticEntryRefKey } from "@leitwerk-dev/domain";
1
+ import type { TurnProgressReport } from "@leitwerk-dev/domain";
2
2
  import type {
3
3
  LlmTurnDefinition,
4
4
  TurnOptions,
@@ -10,7 +10,10 @@ import { assertValidLlmTurnDefinition } from "@leitwerk-dev/process-sdk";
10
10
  import { createAutomaticTurnExecutor } from "../automatic-turn-executor.js";
11
11
  import type { WorkerOperationEmitter } from "../diagnostics.js";
12
12
  import type { PiTreeHandle } from "../pi-adapter.js";
13
- import type { PreTurnTargetedInput } from "../pre-turn-targeted-inputs.js";
13
+ import type {
14
+ AppliedTargetedInputMetadata,
15
+ PreTurnTargetedInput,
16
+ } from "../pre-turn-targeted-inputs.js";
14
17
  import type { WorkerQuestionRequest } from "../question-tool.js";
15
18
  import { TurnExecutionError } from "../turn-execution-error.js";
16
19
  import { TurnExecutionFailure, type TurnExecutionMeta } from "../turn-execution-result.js";
@@ -21,13 +24,7 @@ import { executeLlmTurn } from "./llm-turn-execution.js";
21
24
  export interface AppliedTargetedInput {
22
25
  inputId: string;
23
26
  sequence: number;
24
- meta?: {
25
- currentPrimaryPathLeafId?: string | null;
26
- rootEntryId?: string | null;
27
- targetSemanticRef?: ProcessSemanticEntryRefKey | null;
28
- targetProductName?: string | null;
29
- targetEntryId?: string | null;
30
- };
27
+ meta?: AppliedTargetedInputMetadata;
31
28
  }
32
29
 
33
30
  export type SelectedTurnExecutionResult =
@@ -66,6 +63,22 @@ function failedResult(
66
63
  return { kind: "failed", failure, appliedTargetedInputs };
67
64
  }
68
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
+
69
82
  /** Execute one accepted selected turn and return its single terminal fact. */
70
83
  export async function executeSelectedTurn(
71
84
  input: SelectedTurnExecutionInput,
@@ -83,6 +96,26 @@ export async function executeSelectedTurn(
83
96
  }
84
97
  const handler = resolvedWorkerProcess.definition.turns.get(currentTurnId);
85
98
  if (!handler) throw new Error(`Validated turn handler '${currentTurnId}' is unavailable`);
99
+ let automaticIntegrationCallIndex = 0;
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
+ };
86
119
 
87
120
  const ctx = {
88
121
  process: processSnapshot,
@@ -92,6 +125,12 @@ export async function executeSelectedTurn(
92
125
  turnResultMarkdownBySemanticRef: input.session.turnResultMarkdownBySemanticRef,
93
126
  turnResultMarkdownByProduct: input.session.turnResultMarkdownByProduct,
94
127
  workspaceRoot: input.session.workspaceRoot,
128
+ ...(selectedTurnType === "automatic"
129
+ ? {
130
+ reportProgress,
131
+ callIntegrationTool,
132
+ }
133
+ : {}),
95
134
  } as WorkerProcessContext;
96
135
  let terminal: SelectedTurnExecutionResult | null = null;
97
136
  const appliedTargetedInputs: AppliedTargetedInput[] = [];
@@ -129,9 +168,36 @@ export async function executeSelectedTurn(
129
168
  `Turn '${currentTurnId}' requires a Pi handle`,
130
169
  );
131
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
+ }
132
197
  const completed = await executeLlmTurn({
133
198
  resolvedWorkerProcess,
134
199
  ctx,
200
+ ...(turnDef.prepare ? { prepared } : {}),
135
201
  piHandle,
136
202
  turnDef,
137
203
  turnId: currentTurnId,
@@ -197,6 +263,22 @@ export async function executeSelectedTurn(
197
263
  }
198
264
  return terminal;
199
265
  } catch (error) {
266
+ const failedProgressReport = latestProgressReport as TurnProgressReport | null;
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;
276
+ input.emit({
277
+ kind: "progress",
278
+ turnRecordId: input.turnRecordId,
279
+ report,
280
+ });
281
+ }
200
282
  if (error instanceof TurnExecutionFailure) return failedResult(error, appliedTargetedInputs);
201
283
  if (automaticExecutor)
202
284
  return failedResult(automaticExecutor.failure(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,
@@ -31,40 +31,6 @@ export interface WorkerSessionSnapshotExchange {
31
31
 
32
32
  type FetchLike = typeof fetch;
33
33
 
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
34
  export function createWorkerSessionSnapshotExchange(input: {
69
35
  serverUrl: string;
70
36
  token: string;
@@ -78,10 +44,10 @@ export function createWorkerSessionSnapshotExchange(input: {
78
44
  return disabledWorkerSessionSnapshotExchange;
79
45
  }
80
46
  const timeoutMs = input.timeoutMs ?? 30_000;
81
- const snapshotUrl = resolveWorkerSessionSnapshotUrl({
82
- serverUrl: input.serverUrl,
83
- instanceId: input.instanceId,
84
- });
47
+ const snapshotUrl = resolveWorkerHttpUrl(
48
+ input.serverUrl,
49
+ buildWorkerSessionSnapshotPath(input.instanceId),
50
+ );
85
51
  const authHeaders = {
86
52
  authorization: `Bearer ${input.token}`,
87
53
  [WORKER_SESSION_SNAPSHOT_WORKER_ID_HEADER]: input.workerId,
@@ -89,33 +55,26 @@ export function createWorkerSessionSnapshotExchange(input: {
89
55
 
90
56
  return {
91
57
  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" };
58
+ let content: string;
59
+ try {
60
+ content = await readFile(treeFile, "utf8");
61
+ } catch (error) {
62
+ if (isEnoent(error)) return { kind: "missing" };
63
+ throw error;
102
64
  }
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,
65
+ if (content.length === 0) return { kind: "empty" };
66
+ const response = await fetchImpl(snapshotUrl, {
67
+ method: "PUT",
68
+ headers: {
69
+ ...authHeaders,
70
+ "content-type": WORKER_SESSION_SNAPSHOT_CONTENT_TYPE,
71
+ [WORKER_SESSION_SNAPSHOT_REASON_HEADER]: reason,
72
+ ...(metadata.turnRecordId
73
+ ? { [WORKER_SESSION_SNAPSHOT_TURN_RECORD_ID_HEADER]: metadata.turnRecordId }
74
+ : {}),
118
75
  },
76
+ body: content,
77
+ signal: AbortSignal.timeout(timeoutMs),
119
78
  });
120
79
  if (!response.ok) {
121
80
  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
 
@@ -1,6 +1,14 @@
1
1
  import { createWorkerEntryRuntime } from "./entry-runtime.js";
2
2
 
3
3
  const runtime = createWorkerEntryRuntime();
4
+ for (const signal of ["SIGTERM", "SIGINT"] as const) {
5
+ process.once(signal, () => {
6
+ void runtime.stop(signal).then(
7
+ () => process.exit(0),
8
+ () => process.exit(1),
9
+ );
10
+ });
11
+ }
4
12
 
5
13
  void runtime.start().catch((e) => {
6
14
  console.error(e);
@@ -77,24 +77,16 @@ export function createWorkerIpcReporter(options: {
77
77
  options.emitExtensionEvent?.("worker.event", payload);
78
78
  return payload;
79
79
  };
80
+ const diagnosticReporter =
81
+ (eventType: "worker.trace" | "worker.error") =>
82
+ (input: WorkerDiagnosticPayload, selectedTurnId: string | null = null): void => {
83
+ const payload = workerEvent(eventType, buildWorkerDiagnosticPayload(input), selectedTurnId);
84
+ options.emitExtensionEvent?.(eventType, payload);
85
+ };
80
86
  return {
81
87
  project,
82
88
  workerEvent,
83
- workerTrace(input, selectedTurnId = null) {
84
- const payload = workerEvent(
85
- "worker.trace",
86
- buildWorkerDiagnosticPayload(input),
87
- selectedTurnId,
88
- );
89
- options.emitExtensionEvent?.("worker.trace", payload);
90
- },
91
- workerError(input, selectedTurnId = null) {
92
- const payload = workerEvent(
93
- "worker.error",
94
- buildWorkerDiagnosticPayload(input),
95
- selectedTurnId,
96
- );
97
- options.emitExtensionEvent?.("worker.error", payload);
98
- },
89
+ workerTrace: diagnosticReporter("worker.trace"),
90
+ workerError: diagnosticReporter("worker.error"),
99
91
  };
100
92
  }