@leitwerk-dev/worker 0.1.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 (269) hide show
  1. package/dist/LICENSE +13 -0
  2. package/dist/automatic-turn-executor.d.ts +28 -0
  3. package/dist/automatic-turn-executor.d.ts.map +1 -0
  4. package/dist/automatic-turn-executor.js +58 -0
  5. package/dist/automatic-turn-executor.js.map +1 -0
  6. package/dist/chunk-N5HLJDWA.js +8124 -0
  7. package/dist/chunk-N5HLJDWA.js.map +1 -0
  8. package/dist/diagnostics.d.ts +23 -0
  9. package/dist/diagnostics.d.ts.map +1 -0
  10. package/dist/diagnostics.js +51 -0
  11. package/dist/diagnostics.js.map +1 -0
  12. package/dist/entry-runtime.d.ts +24 -0
  13. package/dist/entry-runtime.d.ts.map +1 -0
  14. package/dist/entry-runtime.js +160 -0
  15. package/dist/entry-runtime.js.map +1 -0
  16. package/dist/event-translator.d.ts +8 -0
  17. package/dist/event-translator.d.ts.map +1 -0
  18. package/dist/event-translator.js +12 -0
  19. package/dist/event-translator.js.map +1 -0
  20. package/dist/extension-entry-roots.d.ts +7 -0
  21. package/dist/extension-entry-roots.d.ts.map +1 -0
  22. package/dist/extension-entry-roots.js +41 -0
  23. package/dist/extension-entry-roots.js.map +1 -0
  24. package/dist/identified-pi-entry.d.ts +56 -0
  25. package/dist/identified-pi-entry.d.ts.map +1 -0
  26. package/dist/identified-pi-entry.js +125 -0
  27. package/dist/identified-pi-entry.js.map +1 -0
  28. package/dist/index.d.ts +7 -0
  29. package/dist/index.d.ts.map +1 -0
  30. package/dist/index.js +6 -0
  31. package/dist/index.js.map +1 -0
  32. package/dist/input-consumer.d.ts +24 -0
  33. package/dist/input-consumer.d.ts.map +1 -0
  34. package/dist/input-consumer.js +34 -0
  35. package/dist/input-consumer.js.map +1 -0
  36. package/dist/ipc.d.ts +22 -0
  37. package/dist/ipc.d.ts.map +1 -0
  38. package/dist/ipc.js +192 -0
  39. package/dist/ipc.js.map +1 -0
  40. package/dist/logical-prompt-runner.d.ts +49 -0
  41. package/dist/logical-prompt-runner.d.ts.map +1 -0
  42. package/dist/logical-prompt-runner.js +225 -0
  43. package/dist/logical-prompt-runner.js.map +1 -0
  44. package/dist/managed-pi-agent-dir.d.ts +13 -0
  45. package/dist/managed-pi-agent-dir.d.ts.map +1 -0
  46. package/dist/managed-pi-agent-dir.js +66 -0
  47. package/dist/managed-pi-agent-dir.js.map +1 -0
  48. package/dist/managed-pi-bootstrap.d.ts +24 -0
  49. package/dist/managed-pi-bootstrap.d.ts.map +1 -0
  50. package/dist/managed-pi-bootstrap.js +135 -0
  51. package/dist/managed-pi-bootstrap.js.map +1 -0
  52. package/dist/missing-tool-recovery-runner.d.ts +23 -0
  53. package/dist/missing-tool-recovery-runner.d.ts.map +1 -0
  54. package/dist/missing-tool-recovery-runner.js +73 -0
  55. package/dist/missing-tool-recovery-runner.js.map +1 -0
  56. package/dist/pi-adapter.d.ts +134 -0
  57. package/dist/pi-adapter.d.ts.map +1 -0
  58. package/dist/pi-adapter.js +1648 -0
  59. package/dist/pi-adapter.js.map +1 -0
  60. package/dist/pi-branch-guard.d.ts +39 -0
  61. package/dist/pi-branch-guard.d.ts.map +1 -0
  62. package/dist/pi-branch-guard.js +75 -0
  63. package/dist/pi-branch-guard.js.map +1 -0
  64. package/dist/pi-event-reporter.d.ts +15 -0
  65. package/dist/pi-event-reporter.d.ts.map +1 -0
  66. package/dist/pi-event-reporter.js +136 -0
  67. package/dist/pi-event-reporter.js.map +1 -0
  68. package/dist/pi-resource-bundle.d.ts +12 -0
  69. package/dist/pi-resource-bundle.d.ts.map +1 -0
  70. package/dist/pi-resource-bundle.js +58 -0
  71. package/dist/pi-resource-bundle.js.map +1 -0
  72. package/dist/pre-turn-targeted-inputs.d.ts +44 -0
  73. package/dist/pre-turn-targeted-inputs.d.ts.map +1 -0
  74. package/dist/pre-turn-targeted-inputs.js +101 -0
  75. package/dist/pre-turn-targeted-inputs.js.map +1 -0
  76. package/dist/prompt-guards.d.ts +52 -0
  77. package/dist/prompt-guards.d.ts.map +1 -0
  78. package/dist/prompt-guards.js +318 -0
  79. package/dist/prompt-guards.js.map +1 -0
  80. package/dist/question-bridge.d.ts +16 -0
  81. package/dist/question-bridge.d.ts.map +1 -0
  82. package/dist/question-bridge.js +55 -0
  83. package/dist/question-bridge.js.map +1 -0
  84. package/dist/question-tool.d.ts +14 -0
  85. package/dist/question-tool.d.ts.map +1 -0
  86. package/dist/question-tool.js +54 -0
  87. package/dist/question-tool.js.map +1 -0
  88. package/dist/resource-loader-factory.d.ts +11 -0
  89. package/dist/resource-loader-factory.d.ts.map +1 -0
  90. package/dist/resource-loader-factory.js +87 -0
  91. package/dist/resource-loader-factory.js.map +1 -0
  92. package/dist/result-image-upload.d.ts +14 -0
  93. package/dist/result-image-upload.d.ts.map +1 -0
  94. package/dist/result-image-upload.js +183 -0
  95. package/dist/result-image-upload.js.map +1 -0
  96. package/dist/runtime/adapters.d.ts +48 -0
  97. package/dist/runtime/adapters.d.ts.map +1 -0
  98. package/dist/runtime/adapters.js +15 -0
  99. package/dist/runtime/adapters.js.map +1 -0
  100. package/dist/runtime/bootstrap-session.d.ts +95 -0
  101. package/dist/runtime/bootstrap-session.d.ts.map +1 -0
  102. package/dist/runtime/bootstrap-session.js +198 -0
  103. package/dist/runtime/bootstrap-session.js.map +1 -0
  104. package/dist/runtime/bootstrap.d.ts +81 -0
  105. package/dist/runtime/bootstrap.d.ts.map +1 -0
  106. package/dist/runtime/bootstrap.js +440 -0
  107. package/dist/runtime/bootstrap.js.map +1 -0
  108. package/dist/runtime/failure-policy.d.ts +79 -0
  109. package/dist/runtime/failure-policy.d.ts.map +1 -0
  110. package/dist/runtime/failure-policy.js +182 -0
  111. package/dist/runtime/failure-policy.js.map +1 -0
  112. package/dist/runtime/index.d.ts +9 -0
  113. package/dist/runtime/index.d.ts.map +1 -0
  114. package/dist/runtime/index.js +326 -0
  115. package/dist/runtime/index.js.map +1 -0
  116. package/dist/runtime/lifecycle-reducer.d.ts +328 -0
  117. package/dist/runtime/lifecycle-reducer.d.ts.map +1 -0
  118. package/dist/runtime/lifecycle-reducer.js +1100 -0
  119. package/dist/runtime/lifecycle-reducer.js.map +1 -0
  120. package/dist/runtime/llm-turn-execution.d.ts +42 -0
  121. package/dist/runtime/llm-turn-execution.d.ts.map +1 -0
  122. package/dist/runtime/llm-turn-execution.js +472 -0
  123. package/dist/runtime/llm-turn-execution.js.map +1 -0
  124. package/dist/runtime/settings.d.ts +11 -0
  125. package/dist/runtime/settings.d.ts.map +1 -0
  126. package/dist/runtime/settings.js +23 -0
  127. package/dist/runtime/settings.js.map +1 -0
  128. package/dist/runtime/snapshot-policy.d.ts +11 -0
  129. package/dist/runtime/snapshot-policy.d.ts.map +1 -0
  130. package/dist/runtime/snapshot-policy.js +16 -0
  131. package/dist/runtime/snapshot-policy.js.map +1 -0
  132. package/dist/runtime/turn-execution.d.ts +49 -0
  133. package/dist/runtime/turn-execution.d.ts.map +1 -0
  134. package/dist/runtime/turn-execution.js +120 -0
  135. package/dist/runtime/turn-execution.js.map +1 -0
  136. package/dist/session-snapshot-exchange.d.ts +39 -0
  137. package/dist/session-snapshot-exchange.d.ts.map +1 -0
  138. package/dist/session-snapshot-exchange.js +102 -0
  139. package/dist/session-snapshot-exchange.js.map +1 -0
  140. package/dist/test-helpers/fake-websocket.d.ts +16 -0
  141. package/dist/test-helpers/fake-websocket.d.ts.map +1 -0
  142. package/dist/test-helpers/fake-websocket.js +40 -0
  143. package/dist/test-helpers/fake-websocket.js.map +1 -0
  144. package/dist/test-helpers/ipc-harness.d.ts +11 -0
  145. package/dist/test-helpers/ipc-harness.d.ts.map +1 -0
  146. package/dist/test-helpers/ipc-harness.js +17 -0
  147. package/dist/test-helpers/ipc-harness.js.map +1 -0
  148. package/dist/test-helpers/worker-message-builders.d.ts +21 -0
  149. package/dist/test-helpers/worker-message-builders.d.ts.map +1 -0
  150. package/dist/test-helpers/worker-message-builders.js +62 -0
  151. package/dist/test-helpers/worker-message-builders.js.map +1 -0
  152. package/dist/turn-continuation.d.ts +28 -0
  153. package/dist/turn-continuation.d.ts.map +1 -0
  154. package/dist/turn-continuation.js +80 -0
  155. package/dist/turn-continuation.js.map +1 -0
  156. package/dist/turn-execution-error.d.ts +39 -0
  157. package/dist/turn-execution-error.d.ts.map +1 -0
  158. package/dist/turn-execution-error.js +64 -0
  159. package/dist/turn-execution-error.js.map +1 -0
  160. package/dist/turn-execution-result.d.ts +35 -0
  161. package/dist/turn-execution-result.d.ts.map +1 -0
  162. package/dist/turn-execution-result.js +21 -0
  163. package/dist/turn-execution-result.js.map +1 -0
  164. package/dist/turn-outcome-tool-session.d.ts +50 -0
  165. package/dist/turn-outcome-tool-session.d.ts.map +1 -0
  166. package/dist/turn-outcome-tool-session.js +209 -0
  167. package/dist/turn-outcome-tool-session.js.map +1 -0
  168. package/dist/turn-record-id.d.ts +3 -0
  169. package/dist/turn-record-id.d.ts.map +1 -0
  170. package/dist/turn-record-id.js +10 -0
  171. package/dist/turn-record-id.js.map +1 -0
  172. package/dist/turn-result-markdown.d.ts +74 -0
  173. package/dist/turn-result-markdown.d.ts.map +1 -0
  174. package/dist/turn-result-markdown.js +263 -0
  175. package/dist/turn-result-markdown.js.map +1 -0
  176. package/dist/turn-tree-strategy.d.ts +29 -0
  177. package/dist/turn-tree-strategy.d.ts.map +1 -0
  178. package/dist/turn-tree-strategy.js +80 -0
  179. package/dist/turn-tree-strategy.js.map +1 -0
  180. package/dist/worker-entry.d.ts +2 -0
  181. package/dist/worker-entry.d.ts.map +1 -0
  182. package/dist/worker-entry.js +7 -0
  183. package/dist/worker-entry.js.map +1 -0
  184. package/dist/worker-http.d.ts +2 -0
  185. package/dist/worker-http.d.ts.map +1 -0
  186. package/dist/worker-http.js +9 -0
  187. package/dist/worker-http.js.map +1 -0
  188. package/dist/worker-ipc-reporter.d.ts +29 -0
  189. package/dist/worker-ipc-reporter.d.ts.map +1 -0
  190. package/dist/worker-ipc-reporter.js +58 -0
  191. package/dist/worker-ipc-reporter.js.map +1 -0
  192. package/dist/worker-payloads.d.ts +10 -0
  193. package/dist/worker-payloads.d.ts.map +1 -0
  194. package/dist/worker-payloads.js +66 -0
  195. package/dist/worker-payloads.js.map +1 -0
  196. package/dist/worker-start-payload.d.ts +7 -0
  197. package/dist/worker-start-payload.d.ts.map +1 -0
  198. package/dist/worker-start-payload.js +5 -0
  199. package/dist/worker-start-payload.js.map +1 -0
  200. package/dist/workspace/manifest.d.ts +35 -0
  201. package/dist/workspace/manifest.d.ts.map +1 -0
  202. package/dist/workspace/manifest.js +79 -0
  203. package/dist/workspace/manifest.js.map +1 -0
  204. package/dist/workspace/node-run-root-git-ops.d.ts +17 -0
  205. package/dist/workspace/node-run-root-git-ops.d.ts.map +1 -0
  206. package/dist/workspace/node-run-root-git-ops.js +96 -0
  207. package/dist/workspace/node-run-root-git-ops.js.map +1 -0
  208. package/dist/workspace/resource-aggregator.d.ts +15 -0
  209. package/dist/workspace/resource-aggregator.d.ts.map +1 -0
  210. package/dist/workspace/resource-aggregator.js +39 -0
  211. package/dist/workspace/resource-aggregator.js.map +1 -0
  212. package/dist/workspace/run-root.d.ts +52 -0
  213. package/dist/workspace/run-root.d.ts.map +1 -0
  214. package/dist/workspace/run-root.js +209 -0
  215. package/dist/workspace/run-root.js.map +1 -0
  216. package/package.json +55 -0
  217. package/src/automatic-turn-executor.ts +106 -0
  218. package/src/diagnostics.ts +82 -0
  219. package/src/entry-runtime.ts +235 -0
  220. package/src/event-translator.ts +22 -0
  221. package/src/extension-entry-roots.ts +43 -0
  222. package/src/identified-pi-entry.ts +188 -0
  223. package/src/index.ts +54 -0
  224. package/src/input-consumer.ts +71 -0
  225. package/src/ipc.ts +250 -0
  226. package/src/logical-prompt-runner.ts +320 -0
  227. package/src/managed-pi-agent-dir.ts +86 -0
  228. package/src/managed-pi-bootstrap.ts +208 -0
  229. package/src/missing-tool-recovery-runner.ts +112 -0
  230. package/src/pi-adapter.ts +2197 -0
  231. package/src/pi-branch-guard.ts +104 -0
  232. package/src/pi-event-reporter.ts +164 -0
  233. package/src/pi-resource-bundle.ts +90 -0
  234. package/src/pre-turn-targeted-inputs.ts +167 -0
  235. package/src/prompt-guards.ts +385 -0
  236. package/src/question-bridge.ts +69 -0
  237. package/src/question-tool.ts +65 -0
  238. package/src/resource-loader-factory.ts +115 -0
  239. package/src/result-image-upload.ts +256 -0
  240. package/src/runtime/adapters.ts +67 -0
  241. package/src/runtime/bootstrap-session.ts +294 -0
  242. package/src/runtime/bootstrap.ts +621 -0
  243. package/src/runtime/failure-policy.ts +274 -0
  244. package/src/runtime/index.ts +362 -0
  245. package/src/runtime/lifecycle-reducer.ts +1537 -0
  246. package/src/runtime/llm-turn-execution.ts +696 -0
  247. package/src/runtime/settings.ts +41 -0
  248. package/src/runtime/snapshot-policy.ts +28 -0
  249. package/src/runtime/turn-execution.ts +203 -0
  250. package/src/session-snapshot-exchange.ts +155 -0
  251. package/src/test-helpers/fake-websocket.ts +46 -0
  252. package/src/test-helpers/ipc-harness.ts +19 -0
  253. package/src/test-helpers/worker-message-builders.ts +92 -0
  254. package/src/turn-continuation.ts +147 -0
  255. package/src/turn-execution-error.ts +102 -0
  256. package/src/turn-execution-result.ts +48 -0
  257. package/src/turn-outcome-tool-session.ts +311 -0
  258. package/src/turn-record-id.ts +17 -0
  259. package/src/turn-result-markdown.ts +355 -0
  260. package/src/turn-tree-strategy.ts +141 -0
  261. package/src/worker-entry.ts +8 -0
  262. package/src/worker-http.ts +6 -0
  263. package/src/worker-ipc-reporter.ts +100 -0
  264. package/src/worker-payloads.ts +94 -0
  265. package/src/worker-start-payload.ts +10 -0
  266. package/src/workspace/manifest.ts +126 -0
  267. package/src/workspace/node-run-root-git-ops.ts +137 -0
  268. package/src/workspace/resource-aggregator.ts +43 -0
  269. package/src/workspace/run-root.ts +361 -0
@@ -0,0 +1,355 @@
1
+ import type { FailedTurnRecoveryCode } from "@leitwerk-dev/domain";
2
+ import {
3
+ MARKDOWN_RESULT_TOOL_NAME,
4
+ type PiCustomTool,
5
+ type TurnResultMarkdownBehavior,
6
+ } from "@leitwerk-dev/process-sdk";
7
+ import { readValueAtPath } from "@leitwerk-dev/protocol";
8
+
9
+ export interface TurnResultMarkdownState {
10
+ markdown: string | null;
11
+ publicationCount: number;
12
+ }
13
+
14
+ export interface TurnResultMarkdownToolResponse {
15
+ ok: boolean;
16
+ code: string;
17
+ message: string;
18
+ data: Record<string, unknown>;
19
+ }
20
+
21
+ export interface MissingTurnToolCallRecovery {
22
+ failureCode: FailedTurnRecoveryCode;
23
+ missingToolNames: string[];
24
+ missingOutcomeToolNames: string[];
25
+ missingMarkdownResult: boolean;
26
+ requiresOutcomeToolMarkdown: boolean;
27
+ outcomeToolMarkdownParameterName?: string;
28
+ }
29
+
30
+ function isWrappedInSingleOuterFence(value: string): boolean {
31
+ const trimmed = value.trim();
32
+ const openingFence = /^(?<fence>`{3,}|~{3,})(?<info>[^\n]*)\n/.exec(trimmed);
33
+ if (!openingFence?.groups?.fence) {
34
+ return false;
35
+ }
36
+ return trimmed.endsWith(`\n${openingFence.groups.fence}`);
37
+ }
38
+
39
+ export function validateTurnResultMarkdownValue(
40
+ value: unknown,
41
+ ): { ok: true; markdown: string } | { ok: false; code: string; message: string } {
42
+ if (typeof value !== "string") {
43
+ return {
44
+ ok: false,
45
+ code: "markdown_string_required",
46
+ message: "markdown_result requires a string markdown value",
47
+ };
48
+ }
49
+ const markdown = value.replace(/\r\n?/g, "\n").trim();
50
+ if (markdown === "") {
51
+ return {
52
+ ok: false,
53
+ code: "markdown_required",
54
+ message: "markdown_result requires non-empty markdown",
55
+ };
56
+ }
57
+ if (isWrappedInSingleOuterFence(markdown)) {
58
+ return {
59
+ ok: false,
60
+ code: "outer_code_fence_not_allowed",
61
+ message: "Pass raw markdown to markdown_result, not a single outer fenced code block",
62
+ };
63
+ }
64
+ return { ok: true, markdown };
65
+ }
66
+
67
+ export function createTurnResultMarkdownState(): TurnResultMarkdownState {
68
+ return {
69
+ markdown: null,
70
+ publicationCount: 0,
71
+ };
72
+ }
73
+
74
+ export function publishTurnResultMarkdownValue(
75
+ state: TurnResultMarkdownState,
76
+ value: unknown,
77
+ ): {
78
+ state: TurnResultMarkdownState;
79
+ response: TurnResultMarkdownToolResponse;
80
+ } {
81
+ const validation = validateTurnResultMarkdownValue(value);
82
+ if (!validation.ok) {
83
+ return {
84
+ state,
85
+ response: {
86
+ ok: false,
87
+ code: validation.code,
88
+ message: validation.message,
89
+ data: {},
90
+ },
91
+ };
92
+ }
93
+ const nextState: TurnResultMarkdownState = {
94
+ markdown: validation.markdown,
95
+ publicationCount: state.publicationCount + 1,
96
+ };
97
+ return {
98
+ state: nextState,
99
+ response: {
100
+ ok: true,
101
+ code: state.publicationCount === 0 ? "markdown_result_recorded" : "markdown_result_updated",
102
+ message:
103
+ state.publicationCount === 0
104
+ ? "Recorded the markdown result for this turn"
105
+ : "Updated the markdown result for this turn",
106
+ data: {
107
+ publicationCount: nextState.publicationCount,
108
+ markdownLength: validation.markdown.length,
109
+ },
110
+ },
111
+ };
112
+ }
113
+
114
+ export function createMarkdownResultTool(stateRef: {
115
+ current: TurnResultMarkdownState;
116
+ }): PiCustomTool {
117
+ return {
118
+ name: MARKDOWN_RESULT_TOOL_NAME,
119
+ description:
120
+ "Publish the operator-facing markdown result for this turn. Pass raw markdown only and do not wrap the entire markdown in triple backticks.",
121
+ parameters: {
122
+ markdown: {
123
+ type: "string",
124
+ description:
125
+ "Raw markdown content to render for this turn. Do not wrap the entire markdown in triple backticks.",
126
+ },
127
+ },
128
+ execute: async (args: Record<string, unknown>) => {
129
+ const published = publishTurnResultMarkdownValue(stateRef.current, args.markdown);
130
+ stateRef.current = published.state;
131
+ return published.response;
132
+ },
133
+ };
134
+ }
135
+
136
+ export function buildTurnToolCallPromptSuffix(options: {
137
+ outcomeToolNames: readonly string[];
138
+ requiresMarkdownResultToolCall: boolean;
139
+ outcomeToolMarkdownParameterName?: string;
140
+ }): string {
141
+ const outcomeToolNames = options.outcomeToolNames.filter((name) => name.trim().length > 0);
142
+ if (
143
+ !options.requiresMarkdownResultToolCall &&
144
+ !options.outcomeToolMarkdownParameterName &&
145
+ outcomeToolNames.length === 0
146
+ ) {
147
+ return "";
148
+ }
149
+ const lines = [
150
+ "Tool completion requirements:",
151
+ "- Keep any normal assistant reply focused and include required result markdown when applicable.",
152
+ "- Do not end with plain text only; finish the turn by calling the required tool(s).",
153
+ ];
154
+ if (options.requiresMarkdownResultToolCall) {
155
+ lines.push(
156
+ outcomeToolNames.length > 0
157
+ ? "- Call the markdown_result tool before the final outcome tool."
158
+ : "- End the turn by calling the markdown_result tool.",
159
+ );
160
+ }
161
+ if (outcomeToolNames.length === 1) {
162
+ lines.push(`- End the turn by calling the ${outcomeToolNames[0]} outcome tool.`);
163
+ } else if (outcomeToolNames.length > 1) {
164
+ lines.push(
165
+ `- End the turn by calling exactly one of these outcome tools: ${outcomeToolNames.join(", ")}.`,
166
+ );
167
+ }
168
+ if (options.outcomeToolMarkdownParameterName && outcomeToolNames.length > 0) {
169
+ lines.push(
170
+ `- Include the operator-facing markdown result in the ${options.outcomeToolMarkdownParameterName} argument of the outcome tool you call.`,
171
+ );
172
+ }
173
+ lines.push("- A turn that ends without the required tool call is treated as a failure.");
174
+ return `\n\n${lines.join("\n")}`;
175
+ }
176
+
177
+ export function buildTurnResultMarkdownPromptSuffix(
178
+ behavior: TurnResultMarkdownBehavior | undefined,
179
+ options: { usesOutcomeTools: boolean; hasResultImageTool: boolean },
180
+ ): string {
181
+ const imageGuidance = options.hasResultImageTool
182
+ ? "\n- Use upload_result_images for intended screenshots or visual goldens before the terminal outcome."
183
+ : "";
184
+ const visualGuidance = `${imageGuidance}\n- Mermaid diagrams need no upload: include their source in a fenced mermaid block when a diagram materially clarifies the result.`;
185
+ if (behavior?.mode === "assistant_output") {
186
+ const outcomeInstruction = options.usesOutcomeTools
187
+ ? "\n- After writing the markdown, call the appropriate outcome tool to finish the turn."
188
+ : "";
189
+ return `\n\nResult publication requirements:\n- Write the operator-facing markdown result as your normal assistant response for this turn.\n- Do not call markdown_result; the leitwerk captures your assistant output automatically.${visualGuidance}${outcomeInstruction}`;
190
+ }
191
+ if (behavior?.mode === "outcome_tool_argument") {
192
+ return `\n\nResult publication requirements:\n- Include the operator-facing markdown result in the ${behavior.parameterName} argument of the outcome tool you call to finish this turn.\n- Do not call markdown_result; the leitwerk captures the outcome tool's ${behavior.parameterName} argument automatically.${visualGuidance}`;
193
+ }
194
+ if (behavior?.mode !== "tool_call" || behavior.toolName !== MARKDOWN_RESULT_TOOL_NAME) {
195
+ return "";
196
+ }
197
+ const requirementPrefix = behavior.required
198
+ ? "Before finishing the turn, you must publish the operator-facing markdown result."
199
+ : "If you want operator-facing markdown rendered for this turn, publish it before finishing.";
200
+ const outcomeInstruction = options.usesOutcomeTools
201
+ ? "\n- After the markdown_result tool call succeeds, call the appropriate outcome tool to finish the turn."
202
+ : "";
203
+ return `\n\nResult publication requirements:\n- ${requirementPrefix}\n- Call the markdown_result tool with the raw markdown you want the operator UI to render.\n- Do not wrap the entire markdown in triple backticks.\n- If you revise the markdown, call markdown_result again. The most recent successful call is used.${visualGuidance}${outcomeInstruction}`;
204
+ }
205
+
206
+ export function maybeCaptureTurnResultMarkdownFromToolCall(input: {
207
+ behavior: TurnResultMarkdownBehavior | undefined;
208
+ stateRef: { current: TurnResultMarkdownState };
209
+ toolName: string;
210
+ args: Record<string, unknown>;
211
+ result: unknown;
212
+ }): void {
213
+ const { behavior, stateRef, toolName, args, result } = input;
214
+ if (!behavior || behavior.mode !== "tool_call" || behavior.toolName !== toolName) {
215
+ return;
216
+ }
217
+ if (toolName === MARKDOWN_RESULT_TOOL_NAME) {
218
+ return;
219
+ }
220
+ const sourceValue = behavior.source === "result" ? result : args;
221
+ const candidate = readValueAtPath(sourceValue, behavior.path);
222
+ const published = publishTurnResultMarkdownValue(stateRef.current, candidate);
223
+ if (published.response.ok) {
224
+ stateRef.current = published.state;
225
+ }
226
+ }
227
+
228
+ export function resolveMissingTurnToolCallRecovery(input: {
229
+ selectedOutcome: { outcome: string; params: Record<string, unknown> } | null;
230
+ outcomeToolNames: readonly string[];
231
+ turnResultMarkdownBehavior: TurnResultMarkdownBehavior | undefined;
232
+ turnResultMarkdownState: TurnResultMarkdownState;
233
+ }): MissingTurnToolCallRecovery | null {
234
+ const missingOutcomeToolNames =
235
+ input.selectedOutcome === null
236
+ ? [...new Set(input.outcomeToolNames.filter((name) => name.trim() !== ""))]
237
+ : [];
238
+ const missingMarkdownResult =
239
+ input.turnResultMarkdownBehavior?.mode === "tool_call" &&
240
+ input.turnResultMarkdownBehavior.toolName === MARKDOWN_RESULT_TOOL_NAME &&
241
+ input.turnResultMarkdownBehavior.required === true &&
242
+ !input.turnResultMarkdownState.markdown;
243
+ const outcomeToolMarkdownParameterName =
244
+ input.turnResultMarkdownBehavior?.mode === "outcome_tool_argument"
245
+ ? input.turnResultMarkdownBehavior.parameterName
246
+ : undefined;
247
+ if (!missingMarkdownResult && missingOutcomeToolNames.length === 0) {
248
+ return null;
249
+ }
250
+ return {
251
+ failureCode:
252
+ missingMarkdownResult && missingOutcomeToolNames.length > 0
253
+ ? "missing_required_tool_calls"
254
+ : missingMarkdownResult
255
+ ? "missing_markdown_result"
256
+ : "missing_outcome_tool",
257
+ missingToolNames: [
258
+ ...(missingMarkdownResult ? [MARKDOWN_RESULT_TOOL_NAME] : []),
259
+ ...missingOutcomeToolNames,
260
+ ],
261
+ missingOutcomeToolNames,
262
+ missingMarkdownResult,
263
+ requiresOutcomeToolMarkdown: Boolean(outcomeToolMarkdownParameterName),
264
+ ...(outcomeToolMarkdownParameterName ? { outcomeToolMarkdownParameterName } : {}),
265
+ };
266
+ }
267
+
268
+ export function buildMissingTurnToolCallRecoveryPrompt(
269
+ recovery: MissingTurnToolCallRecovery,
270
+ ): string {
271
+ const lines = [
272
+ "Your previous reply did not finish this turn because it missed required tool calls.",
273
+ "Continue from your previous work without starting over.",
274
+ ];
275
+ if (recovery.missingMarkdownResult && recovery.missingOutcomeToolNames.length > 0) {
276
+ lines.push(
277
+ "Call markdown_result now with the operator-facing markdown for this turn, then call the required outcome tool to finish.",
278
+ );
279
+ } else if (recovery.missingMarkdownResult) {
280
+ lines.push("Call markdown_result now with the operator-facing markdown for this turn.");
281
+ }
282
+ if (recovery.missingOutcomeToolNames.length === 1) {
283
+ lines.push(
284
+ `Call the ${recovery.missingOutcomeToolNames[0]} outcome tool now to finish the turn.`,
285
+ );
286
+ } else if (recovery.missingOutcomeToolNames.length > 1) {
287
+ lines.push(
288
+ `Call exactly one of these outcome tools now: ${recovery.missingOutcomeToolNames.join(", ")}.`,
289
+ );
290
+ }
291
+ if (recovery.requiresOutcomeToolMarkdown && recovery.outcomeToolMarkdownParameterName) {
292
+ lines.push(
293
+ `Include the operator-facing markdown result in the ${recovery.outcomeToolMarkdownParameterName} argument of that outcome tool.`,
294
+ );
295
+ }
296
+ lines.push("Do not end with plain text only.");
297
+ return lines.join("\n");
298
+ }
299
+
300
+ export function describeMissingTurnToolCallRecovery(recovery: MissingTurnToolCallRecovery): string {
301
+ if (recovery.missingMarkdownResult && recovery.missingOutcomeToolNames.length > 0) {
302
+ return `missing required tool calls (${MARKDOWN_RESULT_TOOL_NAME} and one outcome tool: ${recovery.missingOutcomeToolNames.join(", ")})`;
303
+ }
304
+ if (recovery.missingMarkdownResult) {
305
+ return `missing required '${MARKDOWN_RESULT_TOOL_NAME}' tool call`;
306
+ }
307
+ if (recovery.missingOutcomeToolNames.length === 1) {
308
+ return `missing required '${recovery.missingOutcomeToolNames[0]}' outcome tool call`;
309
+ }
310
+ return `missing required outcome tool call (choose one of: ${recovery.missingOutcomeToolNames.join(", ")})`;
311
+ }
312
+
313
+ export function finalizeTurnResultMarkdown(input: {
314
+ behavior: TurnResultMarkdownBehavior | undefined;
315
+ state: TurnResultMarkdownState;
316
+ assistantMarkdown?: string | null;
317
+ }): { markdown: string | null; errorMessage: string | null } {
318
+ if (!input.behavior || input.behavior.mode === "none") {
319
+ return { markdown: input.state.markdown ?? null, errorMessage: null };
320
+ }
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
+ };
353
+ }
354
+ return { markdown: null, errorMessage: null };
355
+ }
@@ -0,0 +1,141 @@
1
+ import {
2
+ type ProcessProductRefs,
3
+ type ProcessSemanticEntryRefs,
4
+ type ProcessTurnRecordPathType,
5
+ type ProcessTurnStartSelection,
6
+ type ProcessTurnStartTarget,
7
+ resolveProcessTurnStartSelection,
8
+ resolveProcessTurnStartTarget,
9
+ } from "@leitwerk-dev/domain";
10
+ import {
11
+ type LlmTurnDefinition,
12
+ type PiTreeEntry,
13
+ type PiTreeNode,
14
+ resolveLlmTurnRestorePrimaryLeafAfterTurn,
15
+ } from "@leitwerk-dev/process-sdk";
16
+ import type { PiTreeHandle } from "./pi-adapter.js";
17
+
18
+ export interface TurnTreePlan {
19
+ pathType: ProcessTurnRecordPathType;
20
+ forkPiEntryId: string | null;
21
+ savedPrimaryLeafId: string | null;
22
+ restorePrimaryLeafAfterTurn: boolean;
23
+ startTarget: ProcessTurnStartTarget;
24
+ }
25
+
26
+ export function resolveRootEntryId(input: {
27
+ currentLeafId: string | null;
28
+ currentBranch: readonly Pick<PiTreeEntry, "id">[];
29
+ topLevelNodes: readonly Pick<PiTreeNode, "entry">[];
30
+ }): string | null {
31
+ if (input.currentBranch.length > 0) {
32
+ return input.currentBranch[0]?.id ?? null;
33
+ }
34
+
35
+ return input.topLevelNodes[0]?.entry.id ?? null;
36
+ }
37
+
38
+ export function resolveRootEntryIdFromHandle(
39
+ piHandle: Pick<PiTreeHandle, "getLeafId" | "getBranch" | "getTree">,
40
+ ): string | null {
41
+ const currentLeafId = piHandle.getLeafId();
42
+ const currentBranch = piHandle.getBranch(currentLeafId ?? undefined);
43
+ const topLevelNodes = piHandle.getTree();
44
+ return resolveRootEntryId({ currentLeafId, currentBranch, topLevelNodes });
45
+ }
46
+
47
+ function resolveContextAwareTurnStartSelection(input: {
48
+ turnDef: Pick<LlmTurnDefinition<string>, "branchType" | "context" | "startFrom">;
49
+ preTurnStartSelection?: ProcessTurnStartSelection | null;
50
+ hasPreTurnTargetedInputs?: boolean;
51
+ }): ProcessTurnStartSelection {
52
+ const authoredSelection = resolveProcessTurnStartSelection(input.turnDef);
53
+ if (input.preTurnStartSelection) {
54
+ return input.preTurnStartSelection;
55
+ }
56
+ if (input.hasPreTurnTargetedInputs) {
57
+ return authoredSelection;
58
+ }
59
+ if (input.turnDef.context === "fresh" && input.turnDef.branchType === "primary") {
60
+ return { kind: "session_root" };
61
+ }
62
+ if (
63
+ input.turnDef.context === "fresh_seeded" &&
64
+ input.turnDef.branchType === "primary" &&
65
+ !input.turnDef.startFrom
66
+ ) {
67
+ return { kind: "session_root" };
68
+ }
69
+ return authoredSelection;
70
+ }
71
+
72
+ export function planTurnTreeExecution(input: {
73
+ turnDef: Pick<
74
+ LlmTurnDefinition<string>,
75
+ "branchType" | "context" | "startFrom" | "restorePrimaryLeafAfterTurn"
76
+ >;
77
+ currentLeafId: string | null;
78
+ rootEntryId: string | null;
79
+ semanticEntryRefs?: ProcessSemanticEntryRefs | null;
80
+ productRefs?: ProcessProductRefs | null;
81
+ entryExists?: (entryId: string) => boolean;
82
+ preTurnStartSelection?: ProcessTurnStartSelection | null;
83
+ hasPreTurnTargetedInputs?: boolean;
84
+ }): TurnTreePlan {
85
+ const startTarget = resolveProcessTurnStartTarget({
86
+ selection: resolveContextAwareTurnStartSelection({
87
+ turnDef: input.turnDef,
88
+ preTurnStartSelection: input.preTurnStartSelection,
89
+ hasPreTurnTargetedInputs: input.hasPreTurnTargetedInputs,
90
+ }),
91
+ branchType: input.turnDef.branchType,
92
+ currentLeafId: input.currentLeafId,
93
+ rootEntryId: input.rootEntryId,
94
+ semanticEntryRefs: input.semanticEntryRefs,
95
+ productRefs: input.productRefs,
96
+ entryExists: input.entryExists,
97
+ });
98
+
99
+ return {
100
+ pathType: input.turnDef.branchType,
101
+ forkPiEntryId: startTarget.forkPiEntryId,
102
+ savedPrimaryLeafId: input.currentLeafId,
103
+ restorePrimaryLeafAfterTurn: resolveLlmTurnRestorePrimaryLeafAfterTurn(input.turnDef),
104
+ startTarget: startTarget.startTarget,
105
+ };
106
+ }
107
+
108
+ export async function positionHandleForTurn(
109
+ piHandle: Pick<PiTreeHandle, "branch" | "branchFromRoot">,
110
+ plan: TurnTreePlan,
111
+ ): 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
+ }
124
+ }
125
+ }
126
+
127
+ export async function restoreHandleAfterTurn(
128
+ piHandle: Pick<PiTreeHandle, "branch" | "branchFromRoot">,
129
+ plan: TurnTreePlan,
130
+ ): Promise<void> {
131
+ if (!plan.restorePrimaryLeafAfterTurn) {
132
+ return;
133
+ }
134
+
135
+ if (plan.savedPrimaryLeafId) {
136
+ await piHandle.branch(plan.savedPrimaryLeafId);
137
+ return;
138
+ }
139
+
140
+ await piHandle.branchFromRoot();
141
+ }
@@ -0,0 +1,8 @@
1
+ import { createWorkerEntryRuntime } from "./entry-runtime.js";
2
+
3
+ const runtime = createWorkerEntryRuntime();
4
+
5
+ void runtime.start().catch((e) => {
6
+ console.error(e);
7
+ process.exit(1);
8
+ });
@@ -0,0 +1,6 @@
1
+ export function resolveWorkerHttpUrl(serverUrl: string, pathname: string): string {
2
+ const base = new URL(serverUrl);
3
+ if (base.protocol === "ws:") base.protocol = "http:";
4
+ if (base.protocol === "wss:") base.protocol = "https:";
5
+ return new URL(pathname, base).toString();
6
+ }
@@ -0,0 +1,100 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import type { WorkerToServerMessage } from "@leitwerk-dev/worker-protocol";
3
+ import { createIpcMessage } from "@leitwerk-dev/worker-protocol";
4
+ import { buildWorkerDiagnosticPayload, type WorkerDiagnosticPayload } from "./diagnostics.js";
5
+
6
+ type WorkerMessageType = WorkerToServerMessage["type"];
7
+ type Payload<T extends WorkerMessageType> = Extract<WorkerToServerMessage, { type: T }>["payload"];
8
+
9
+ export interface WorkerProtocolFact<T extends WorkerMessageType = WorkerMessageType> {
10
+ kind: "protocol";
11
+ type: T;
12
+ payload: Payload<T>;
13
+ }
14
+
15
+ export interface WorkerIpcReporter {
16
+ project(fact: WorkerProtocolFact): void;
17
+ workerEvent(
18
+ eventType: string,
19
+ data: Record<string, unknown>,
20
+ selectedTurnId?: string | null,
21
+ ): Extract<WorkerToServerMessage, { type: "worker.event" }>["payload"];
22
+ workerTrace(input: WorkerDiagnosticPayload, selectedTurnId?: string | null): void;
23
+ workerError(input: WorkerDiagnosticPayload, selectedTurnId?: string | null): void;
24
+ }
25
+
26
+ const EXTENSION_FACTS = new Set<WorkerMessageType>([
27
+ "worker.state",
28
+ "worker.ready",
29
+ "worker.turn_started",
30
+ "worker.turn_outcome",
31
+ "worker.turn_failed",
32
+ "worker.lifecycle_parked",
33
+ "worker.input_consumed",
34
+ "worker.cleanup_started",
35
+ "worker.cleanup_completed",
36
+ "worker.failed",
37
+ ]);
38
+
39
+ /** Envelopes protocol-ready facts and preserves IPC-before-extension ordering. */
40
+ export function createWorkerIpcReporter(options: {
41
+ instanceId: string;
42
+ workerId: string;
43
+ now(): Date;
44
+ send(message: WorkerToServerMessage): void;
45
+ emitExtensionEvent?(event: string, payload: unknown): void;
46
+ }): WorkerIpcReporter {
47
+ const project = (fact: WorkerProtocolFact): void => {
48
+ options.send(
49
+ createIpcMessage({
50
+ type: fact.type,
51
+ messageId: randomUUID(),
52
+ instanceId: options.instanceId,
53
+ workerId: options.workerId,
54
+ sentAt: options.now().toISOString(),
55
+ payload: fact.payload,
56
+ } as never) as WorkerToServerMessage,
57
+ );
58
+ if (EXTENSION_FACTS.has(fact.type)) options.emitExtensionEvent?.(fact.type, fact.payload);
59
+ };
60
+ const workerEvent = (
61
+ eventType: string,
62
+ data: Record<string, unknown>,
63
+ selectedTurnId: string | null = null,
64
+ ) => {
65
+ const payload = {
66
+ eventType,
67
+ selectedTurnId,
68
+ data: {
69
+ ...data,
70
+ timestamp:
71
+ typeof data.timestamp === "string" && data.timestamp.trim() !== ""
72
+ ? data.timestamp
73
+ : options.now().toISOString(),
74
+ },
75
+ };
76
+ project({ kind: "protocol", type: "worker.event", payload });
77
+ options.emitExtensionEvent?.("worker.event", payload);
78
+ return payload;
79
+ };
80
+ return {
81
+ project,
82
+ 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
+ },
99
+ };
100
+ }