@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,256 @@
1
+ import { constants } from "node:fs";
2
+ import { open, realpath, stat } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import type { PiCustomTool } from "@leitwerk-dev/process-sdk";
5
+ import {
6
+ buildWorkerResultImageUploadPath,
7
+ parseWorkerResultImageUploadResponse,
8
+ type ResultImageMimeType,
9
+ WORKER_RESULT_IMAGE_WORKER_ID_HEADER,
10
+ } from "@leitwerk-dev/worker-protocol";
11
+ import { resolveWorkerHttpUrl } from "./worker-http.js";
12
+
13
+ type ImageEntry = { path: string; alt: string };
14
+ type FailedImage = ImageEntry & { status: "failed"; code: string; message: string };
15
+ type UploadedImage = ImageEntry & {
16
+ status: "uploaded";
17
+ imageId: string;
18
+ url: string;
19
+ markdown: string;
20
+ mimeType: ResultImageMimeType;
21
+ byteSize: number;
22
+ };
23
+ type ImageResult = FailedImage | UploadedImage;
24
+
25
+ const DEFAULT_UPLOAD_TIMEOUT_MS = 30_000;
26
+ const MAX_UPLOAD_ATTEMPTS = 2;
27
+ const RETRY_DELAY_MS = 250;
28
+
29
+ function failure(entry: ImageEntry, code: string, message: string): FailedImage {
30
+ return { ...entry, status: "failed", code, message };
31
+ }
32
+
33
+ function isWithinRoot(rootReal: string, fileReal: string): boolean {
34
+ const relative = path.relative(rootReal, fileReal);
35
+ return relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
36
+ }
37
+
38
+ function isRetryableResponse(response: Response): boolean {
39
+ return response.status >= 500;
40
+ }
41
+
42
+ async function sleep(ms: number): Promise<void> {
43
+ if (ms <= 0) return;
44
+ await new Promise<void>((resolve) => setTimeout(resolve, ms));
45
+ }
46
+
47
+ async function readBoundedWorkspaceFile(
48
+ entry: ImageEntry,
49
+ workspaceRoot: string,
50
+ maxSizeBytes: number,
51
+ ): Promise<Buffer | FailedImage> {
52
+ const rootReal = await realpath(workspaceRoot);
53
+ const candidatePath = path.resolve(workspaceRoot, entry.path);
54
+ const fileReal = await realpath(candidatePath);
55
+ if (!isWithinRoot(rootReal, fileReal)) {
56
+ return failure(
57
+ entry,
58
+ "path_outside_workspace",
59
+ "Image path resolves outside the process workspace",
60
+ );
61
+ }
62
+ const handle = await open(fileReal, constants.O_RDONLY | constants.O_NOFOLLOW);
63
+ try {
64
+ const before = await handle.stat();
65
+ if (!before.isFile()) return failure(entry, "not_a_file", "Image path is not a regular file");
66
+ if (before.size > maxSizeBytes) {
67
+ return failure(entry, "image_too_large", `Image exceeds the ${maxSizeBytes}-byte limit`);
68
+ }
69
+
70
+ // Re-resolve the caller-visible path after opening and compare inode identity.
71
+ // This rejects a final component or parent directory swapped during validation.
72
+ const currentReal = await realpath(candidatePath);
73
+ const current = await stat(currentReal);
74
+ if (
75
+ !isWithinRoot(rootReal, currentReal) ||
76
+ current.dev !== before.dev ||
77
+ current.ino !== before.ino
78
+ ) {
79
+ return failure(entry, "image_changed", "Image path changed during validation");
80
+ }
81
+
82
+ const target = Buffer.alloc(before.size + 1);
83
+ let offset = 0;
84
+ while (offset < target.length) {
85
+ const { bytesRead } = await handle.read(target, offset, target.length - offset, offset);
86
+ if (bytesRead === 0) break;
87
+ offset += bytesRead;
88
+ }
89
+ const after = await handle.stat();
90
+ if (
91
+ offset > maxSizeBytes ||
92
+ after.size !== offset ||
93
+ after.dev !== before.dev ||
94
+ after.ino !== before.ino
95
+ ) {
96
+ return failure(entry, "image_changed", "Image changed size during validation");
97
+ }
98
+ return target.subarray(0, offset);
99
+ } finally {
100
+ await handle.close();
101
+ }
102
+ }
103
+
104
+ async function prepareImage(
105
+ entry: ImageEntry,
106
+ workspaceRoot: string,
107
+ maxSizeBytes: number,
108
+ ): Promise<Buffer | FailedImage> {
109
+ if (!entry.path.trim() || !entry.alt.trim())
110
+ return failure(entry, "invalid_image_entry", "Image path and alt text must be non-empty");
111
+ try {
112
+ return await readBoundedWorkspaceFile(entry, workspaceRoot, maxSizeBytes);
113
+ } catch (error) {
114
+ const missing = (error as NodeJS.ErrnoException).code === "ENOENT";
115
+ return failure(
116
+ entry,
117
+ missing ? "image_not_found" : "image_unreadable",
118
+ missing ? "Image file does not exist" : "Image file could not be read safely",
119
+ );
120
+ }
121
+ }
122
+
123
+ export function createUploadResultImagesTool(input: {
124
+ workspaceRoot: string;
125
+ instanceId: string;
126
+ turnRecordId: string;
127
+ workerId: string;
128
+ serverUrl: string;
129
+ token: string;
130
+ maxSizeBytes: number;
131
+ fetchImpl?: typeof fetch;
132
+ requestTimeoutMs?: number;
133
+ sleepImpl?: (ms: number) => Promise<void>;
134
+ }): PiCustomTool {
135
+ return {
136
+ name: "upload_result_images",
137
+ description:
138
+ "Upload all intended repository-generated screenshots or visual goldens in one batch before the terminal outcome, then embed the Markdown snippets returned for successful entries. A partial upload failure must not block an otherwise valid result.",
139
+ parameters: {
140
+ images: {
141
+ type: "array",
142
+ minItems: 1,
143
+ items: {
144
+ type: "object",
145
+ properties: { path: { type: "string" }, alt: { type: "string" } },
146
+ required: ["path", "alt"],
147
+ },
148
+ },
149
+ },
150
+ executionMode: "sequential",
151
+ async execute(args) {
152
+ const raw = Array.isArray(args.images) ? args.images : [];
153
+ if (raw.length === 0)
154
+ return {
155
+ ok: false,
156
+ code: "result_images_upload_failed",
157
+ message: "Provide at least one image",
158
+ data: { images: [], markdown: "" },
159
+ };
160
+ const entries = raw.map((value): ImageEntry => {
161
+ const record = value && typeof value === "object" ? (value as Record<string, unknown>) : {};
162
+ return {
163
+ path: typeof record.path === "string" ? record.path : "",
164
+ alt: typeof record.alt === "string" ? record.alt : "",
165
+ };
166
+ });
167
+ const url = resolveWorkerHttpUrl(
168
+ input.serverUrl,
169
+ buildWorkerResultImageUploadPath(input.instanceId, input.turnRecordId),
170
+ );
171
+ const results: ImageResult[] = await Promise.all(
172
+ entries.map(async (entry) => {
173
+ const prepared = await prepareImage(entry, input.workspaceRoot, input.maxSizeBytes);
174
+ if (!Buffer.isBuffer(prepared)) return prepared;
175
+ let finalFailure = failure(entry, "upload_failed", "Image upload failed");
176
+ for (let attempt = 0; attempt < MAX_UPLOAD_ATTEMPTS; attempt += 1) {
177
+ let response: Response | null = null;
178
+ const signal = AbortSignal.timeout(input.requestTimeoutMs ?? DEFAULT_UPLOAD_TIMEOUT_MS);
179
+ try {
180
+ response = await (input.fetchImpl ?? fetch)(url, {
181
+ method: "POST",
182
+ headers: {
183
+ authorization: `Bearer ${input.token}`,
184
+ [WORKER_RESULT_IMAGE_WORKER_ID_HEADER]: input.workerId,
185
+ "content-type": "application/octet-stream",
186
+ },
187
+ body: new Uint8Array(prepared),
188
+ signal,
189
+ });
190
+ } catch {
191
+ finalFailure = failure(
192
+ entry,
193
+ signal.aborted ? "upload_timeout" : "upload_failed",
194
+ signal.aborted ? "Image upload timed out" : "Image upload failed",
195
+ );
196
+ }
197
+ if (response) {
198
+ if (response.ok) {
199
+ try {
200
+ const body = parseWorkerResultImageUploadResponse(await response.json());
201
+ if (!body)
202
+ return failure(
203
+ entry,
204
+ "upload_invalid_response",
205
+ "Image upload response was invalid",
206
+ );
207
+ return {
208
+ ...entry,
209
+ status: "uploaded" as const,
210
+ ...body,
211
+ markdown: `![${entry.alt.replace(/[\\\]]/g, "\\$&")}](${body.url})`,
212
+ };
213
+ } catch {
214
+ return failure(
215
+ entry,
216
+ "upload_invalid_response",
217
+ "Image upload response was invalid",
218
+ );
219
+ }
220
+ }
221
+ finalFailure = failure(
222
+ entry,
223
+ `upload_http_${response.status}`,
224
+ `Image upload was rejected with HTTP ${response.status}`,
225
+ );
226
+ if (!isRetryableResponse(response)) return finalFailure;
227
+ }
228
+ if (attempt + 1 < MAX_UPLOAD_ATTEMPTS) {
229
+ await (input.sleepImpl ?? sleep)(RETRY_DELAY_MS);
230
+ }
231
+ }
232
+ return finalFailure;
233
+ }),
234
+ );
235
+ const uploaded = results.filter(
236
+ (result): result is UploadedImage => result.status === "uploaded",
237
+ );
238
+ const all = uploaded.length === results.length;
239
+ const partial = uploaded.length > 0 && !all;
240
+ return {
241
+ ok: uploaded.length > 0,
242
+ code: all
243
+ ? "result_images_uploaded"
244
+ : partial
245
+ ? "result_images_partially_uploaded"
246
+ : "result_images_upload_failed",
247
+ message: all
248
+ ? "Uploaded all result images"
249
+ : partial
250
+ ? `Uploaded ${uploaded.length} of ${results.length} result images`
251
+ : "No result images were uploaded",
252
+ data: { images: results, markdown: uploaded.map(({ markdown }) => markdown).join("\n\n") },
253
+ };
254
+ },
255
+ };
256
+ }
@@ -0,0 +1,67 @@
1
+ import type { ResolvedWorkerProcess } from "@leitwerk-dev/extension-runtime";
2
+ import type { EventBus, PiCustomTool } from "@leitwerk-dev/process-sdk";
3
+ import type { WorkerIpc } from "../ipc.js";
4
+ import type { PiTreeHandleFactory } from "../pi-adapter.js";
5
+ import type { PromptGuardScheduler, PromptGuardTimer } from "../prompt-guards.js";
6
+ import type { WorkerSessionSnapshotExchange } from "../session-snapshot-exchange.js";
7
+ import type { RunRootGitOps } from "../workspace/run-root.js";
8
+
9
+ export type WorkerRuntimeTimer = PromptGuardTimer;
10
+
11
+ export interface WorkerRuntimeScheduler extends PromptGuardScheduler {
12
+ sleep(delayMs: number): Promise<void>;
13
+ now(): Date;
14
+ }
15
+
16
+ export const nodeWorkerRuntimeScheduler: WorkerRuntimeScheduler = {
17
+ setTimeout(handler, delayMs) {
18
+ return setTimeout(handler, delayMs);
19
+ },
20
+ clearTimeout(timer) {
21
+ clearTimeout(timer);
22
+ },
23
+ sleep(delayMs) {
24
+ return new Promise((resolve) => setTimeout(resolve, delayMs));
25
+ },
26
+ now() {
27
+ return new Date();
28
+ },
29
+ };
30
+
31
+ export interface WorkerRuntimeConfig {
32
+ instanceId: string;
33
+ workerId: string;
34
+ heartbeatIntervalMs?: number;
35
+ turnMaxDurationMs?: number;
36
+ turnInactivityTimeoutMs?: number;
37
+ turnAbortGracePeriodMs?: number;
38
+ }
39
+
40
+ export interface ResultImageToolFactory {
41
+ create(input: {
42
+ workspaceRoot?: string;
43
+ instanceId: string;
44
+ turnRecordId: string;
45
+ }): PiCustomTool | null;
46
+ }
47
+
48
+ export interface WorkerRuntimeAdapters {
49
+ transport: WorkerIpc;
50
+ sessionSnapshots: WorkerSessionSnapshotExchange;
51
+ resultImageTools: ResultImageToolFactory;
52
+ piFactory: PiTreeHandleFactory;
53
+ gitOps: RunRootGitOps;
54
+ scheduler: WorkerRuntimeScheduler;
55
+ exit(code: number): void;
56
+ stderr?: NodeJS.WritableStream;
57
+ extensionEvents?: EventBus;
58
+ resolveWorkerProcess?: (
59
+ processId: string,
60
+ opts?: { paramsJson?: string | null; stateJson?: string | null },
61
+ ) => Promise<ResolvedWorkerProcess | undefined> | ResolvedWorkerProcess | undefined;
62
+ }
63
+
64
+ export interface WorkerRuntimeOptions {
65
+ config: WorkerRuntimeConfig;
66
+ adapters: WorkerRuntimeAdapters;
67
+ }
@@ -0,0 +1,294 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import type {
4
+ PreparedTurnStart,
5
+ ProcessInstance,
6
+ ProcessProject,
7
+ ProcessSemanticEntryRefKey,
8
+ } from "@leitwerk-dev/domain";
9
+ import type { ResolvedWorkerProcess } from "@leitwerk-dev/extension-runtime";
10
+ import type { WorkerReadyPayload, WorkerStartPayload } from "@leitwerk-dev/worker-protocol";
11
+ import type { WorkerDiagnosticPayload } from "../diagnostics.js";
12
+ import type { InputItem } from "../input-consumer.js";
13
+ import type { PiTreeHandle, PiTreeHandleFactory } from "../pi-adapter.js";
14
+ import type { WorkerSessionSnapshotExchange } from "../session-snapshot-exchange.js";
15
+ import { isLlmWorkerStartPayload } from "../worker-start-payload.js";
16
+ import type { RunRootGitOps } from "../workspace/run-root.js";
17
+ import type { WorkerRuntimeScheduler } from "./adapters.js";
18
+ import {
19
+ activatePreparedStart,
20
+ bootstrapWorkerRuntime,
21
+ type PreparedStartActivation,
22
+ } from "./bootstrap.js";
23
+ import type { WorkerRuntimeSettings } from "./settings.js";
24
+
25
+ interface PreparedSessionBase {
26
+ processSnapshot: ProcessInstance;
27
+ projectSnapshots: ProcessProject[];
28
+ resolvedWorkerProcess: ResolvedWorkerProcess;
29
+ selectedTurnId: string;
30
+ startRecordId: string;
31
+ proposedTurnRecordId: string;
32
+ acceptedTurnRecordId: string | null;
33
+ treeFile: string;
34
+ workspaceRoot: string;
35
+ turnResultMarkdownBySemanticRef?: Partial<Record<ProcessSemanticEntryRefKey, string>>;
36
+ turnResultMarkdownByProduct?: Record<string, string>;
37
+ settings: WorkerRuntimeSettings;
38
+ }
39
+
40
+ export interface PreparedAutomaticSession extends PreparedSessionBase {
41
+ kind: "automatic";
42
+ piAvailable: false;
43
+ activeModelProfileId: null;
44
+ }
45
+
46
+ export interface PreparedLlmSession extends PreparedSessionBase {
47
+ kind: "llm";
48
+ preparedTurnStart: PreparedTurnStart;
49
+ configSnapshot: Extract<WorkerStartPayload, { bootstrap: { kind: "llm" } }>["configSnapshot"];
50
+ piAvailable: boolean;
51
+ activeModelProfileId: string | null;
52
+ }
53
+
54
+ export type PreparedWorkerSession = PreparedAutomaticSession | PreparedLlmSession;
55
+
56
+ export interface CredentialRefreshDescriptor {
57
+ agentDir: string;
58
+ declaredCredentialPaths: readonly string[];
59
+ providerId: string;
60
+ revision: number;
61
+ }
62
+
63
+ export interface WorkerBootstrapCompletion {
64
+ session: PreparedWorkerSession;
65
+ pendingInputs: InputItem[];
66
+ readyPayload: WorkerReadyPayload;
67
+ credentialRefresh?: CredentialRefreshDescriptor;
68
+ diagnostics: string[];
69
+ }
70
+
71
+ function validatePreparedSession(input: {
72
+ bootstrapped: Awaited<ReturnType<typeof bootstrapWorkerRuntime>>;
73
+ payload: WorkerStartPayload;
74
+ settings: WorkerRuntimeSettings;
75
+ }): PreparedWorkerSession {
76
+ const { bootstrapped, payload, settings } = input;
77
+ const process = bootstrapped.resolvedWorkerProcess;
78
+ if (!process)
79
+ throw new Error(`Worker process '${bootstrapped.processSnapshot.processId}' is unavailable`);
80
+ const selectedTurnId = bootstrapped.processSnapshot.selectedTurnId ?? process.startTurnId;
81
+ const binding = process.turns?.get(selectedTurnId);
82
+ const handler = process.definition.turns.get(selectedTurnId);
83
+ if (!binding || !handler) throw new Error(`Selected turn '${selectedTurnId}' is unavailable`);
84
+ const turnStartState = payload.turnStart.state;
85
+ if (turnStartState.kind !== "starting" && turnStartState.kind !== "accepted") {
86
+ throw new Error(`Worker start '${payload.turnStart.id}' has no prepared turn`);
87
+ }
88
+ const preparedKind =
89
+ turnStartState.kind === "starting" ? turnStartState.start.kind : payload.turnStart.turnType;
90
+ if (binding.definition.kind !== preparedKind) {
91
+ throw new Error(
92
+ `Prepared ${preparedKind} start does not match selected ${binding.definition.kind} turn`,
93
+ );
94
+ }
95
+ const base = {
96
+ processSnapshot: bootstrapped.processSnapshot,
97
+ projectSnapshots: bootstrapped.projectSnapshots,
98
+ resolvedWorkerProcess: process,
99
+ selectedTurnId,
100
+ startRecordId: payload.turnStart.id,
101
+ proposedTurnRecordId: payload.turnStart.proposedTurnRecordId,
102
+ acceptedTurnRecordId:
103
+ payload.turnStart.state.kind === "accepted" ? payload.turnStart.state.turnRecordId : null,
104
+ treeFile: payload.treePaths.primaryTreeFile,
105
+ workspaceRoot: payload.treePaths.workspaceRoot,
106
+ turnResultMarkdownBySemanticRef: payload.turnResultMarkdownBySemanticRef,
107
+ turnResultMarkdownByProduct: payload.turnResultMarkdownByProduct,
108
+ settings,
109
+ };
110
+ if (binding.definition.kind === "automatic") {
111
+ return { ...base, kind: "automatic", piAvailable: false, activeModelProfileId: null };
112
+ }
113
+ if (!isLlmWorkerStartPayload(payload) || bootstrapped.readyPayload.receipt.kind !== "llm") {
114
+ throw new Error(`Selected LLM turn '${selectedTurnId}' lacks LLM bootstrap resources`);
115
+ }
116
+ const preparedTurnStart = bootstrapped.readyPayload.receipt.preparedStart;
117
+ if (!preparedTurnStart)
118
+ throw new Error(`Selected LLM turn '${selectedTurnId}' lacks a prepared tree start`);
119
+ return {
120
+ ...base,
121
+ kind: "llm",
122
+ preparedTurnStart,
123
+ configSnapshot: payload.configSnapshot,
124
+ piAvailable: false,
125
+ activeModelProfileId: bootstrapped.processSnapshot.selectedTurnModelProfileId ?? null,
126
+ };
127
+ }
128
+
129
+ type WorkerLiveResourcesDeps = {
130
+ instanceId: string;
131
+ piFactory: PiTreeHandleFactory;
132
+ gitOps: RunRootGitOps;
133
+ scheduler: WorkerRuntimeScheduler;
134
+ sessionSnapshots?: WorkerSessionSnapshotExchange;
135
+ resolveWorkerProcess?: (
136
+ processId: string,
137
+ opts?: { paramsJson?: string | null; stateJson?: string | null },
138
+ ) => Promise<ResolvedWorkerProcess | undefined> | ResolvedWorkerProcess | undefined;
139
+ progress(payload: WorkerDiagnosticPayload): void;
140
+ };
141
+
142
+ /** Private concrete holder for provisional and active live resources. */
143
+ export class WorkerLiveResources {
144
+ #piHandle: PiTreeHandle | null = null;
145
+ #activeTurnAbort: AbortController | null = null;
146
+ #provisional = new Map<string, PreparedStartActivation>();
147
+
148
+ constructor(private readonly deps: WorkerLiveResourcesDeps) {}
149
+
150
+ get piHandle(): PiTreeHandle | null {
151
+ return this.#piHandle;
152
+ }
153
+
154
+ async bootstrap(
155
+ payload: WorkerStartPayload,
156
+ settings: WorkerRuntimeSettings,
157
+ ): Promise<WorkerBootstrapCompletion> {
158
+ const bootstrapped = await bootstrapWorkerRuntime({
159
+ instanceId: this.deps.instanceId,
160
+ payload,
161
+ piFactory: this.deps.piFactory,
162
+ gitOps: this.deps.gitOps,
163
+ scheduler: this.deps.scheduler,
164
+ resolveWorkerProcess: this.deps.resolveWorkerProcess,
165
+ });
166
+ this.#provisional.set(payload.turnStart.id, bootstrapped.activation);
167
+ return {
168
+ session: validatePreparedSession({ bootstrapped, payload, settings }),
169
+ pendingInputs: bootstrapped.pendingInputs,
170
+ readyPayload: bootstrapped.readyPayload,
171
+ ...(bootstrapped.credentialRefresh
172
+ ? { credentialRefresh: bootstrapped.credentialRefresh }
173
+ : {}),
174
+ diagnostics: bootstrapped.diagnostics,
175
+ };
176
+ }
177
+
178
+ async activate(startRecordId: string, turnRecordId: string, session: PreparedWorkerSession) {
179
+ if (session.proposedTurnRecordId !== turnRecordId) {
180
+ throw new Error("Accepted turn record id does not match the prepared worker start");
181
+ }
182
+ const activation = this.#provisional.get(startRecordId);
183
+ if (!activation) throw new Error("Prepared worker start activation is unavailable");
184
+ this.#provisional.delete(startRecordId);
185
+ const activated = await activatePreparedStart({
186
+ instanceId: this.deps.instanceId,
187
+ piFactory: this.deps.piFactory,
188
+ activation,
189
+ });
190
+ this.#piHandle = activated.piHandle;
191
+ return { diagnostics: activated.diagnostics };
192
+ }
193
+
194
+ async uploadSnapshot(
195
+ source: { kind: "automatic" | "llm"; treeFile: string },
196
+ reason: string,
197
+ metadata: { turnRecordId: string | null; required: boolean },
198
+ ): Promise<void> {
199
+ if (source.kind === "automatic") return;
200
+ if (!this.deps.sessionSnapshots) throw new Error("Session snapshot exchange is unavailable");
201
+ let lastError: unknown;
202
+ for (let attempt = 1; attempt <= 3; attempt++) {
203
+ try {
204
+ const result = await this.deps.sessionSnapshots.uploadSnapshot(source.treeFile, reason, {
205
+ turnRecordId: metadata.turnRecordId,
206
+ });
207
+ if (result.kind === "uploaded") return;
208
+ if (!metadata.required) return;
209
+ throw new Error(`Session snapshot upload returned ${result.kind}`);
210
+ } catch (error) {
211
+ lastError = error;
212
+ this.deps.progress({
213
+ level: "warn",
214
+ code: "session_snapshot.upload_failed",
215
+ message: `Session snapshot upload failed: ${error instanceof Error ? error.message : String(error)}`,
216
+ details: { attempt, reason },
217
+ });
218
+ if (attempt < 3) await this.deps.scheduler.sleep(100 * attempt);
219
+ }
220
+ }
221
+ if (!metadata.required) return;
222
+ throw new Error(
223
+ `Mandatory session snapshot upload failed before ${reason}: ${lastError instanceof Error ? lastError.message : String(lastError)}`,
224
+ );
225
+ }
226
+
227
+ async runTurn<T>(operation: (signal: AbortSignal) => Promise<T>): Promise<T> {
228
+ if (this.#activeTurnAbort) throw new Error("A selected turn is already active");
229
+ const controller = new AbortController();
230
+ this.#activeTurnAbort = controller;
231
+ try {
232
+ return await operation(controller.signal);
233
+ } finally {
234
+ if (this.#activeTurnAbort === controller) this.#activeTurnAbort = null;
235
+ }
236
+ }
237
+
238
+ abortActiveTurn(): boolean {
239
+ if (!this.#activeTurnAbort) return false;
240
+ this.#activeTurnAbort.abort();
241
+ return true;
242
+ }
243
+
244
+ async abortTurn(): Promise<void> {
245
+ await this.#piHandle?.abortTurn();
246
+ }
247
+
248
+ async cleanup(): Promise<void> {
249
+ this.#provisional.clear();
250
+ await this.#piHandle?.close();
251
+ this.#piHandle = null;
252
+ this.deps.gitOps.cleanupRepositoryCredentials?.();
253
+ }
254
+ }
255
+
256
+ function strings(value: unknown, name: string): Record<string, string> {
257
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
258
+ throw new Error(`Credential file '${name}' must contain a JSON object`);
259
+ }
260
+ return Object.fromEntries(
261
+ Object.entries(value).filter(
262
+ (entry): entry is [string, string] => typeof entry[1] === "string",
263
+ ),
264
+ );
265
+ }
266
+
267
+ /** Reads one credential sample. Values are transient command-result data. */
268
+ export async function sampleCredentialFiles(
269
+ descriptor: CredentialRefreshDescriptor,
270
+ ): Promise<{ values: Record<string, string>; fingerprint: string }> {
271
+ const values: Record<string, string> = {};
272
+ for (const credentialPath of descriptor.declaredCredentialPaths) {
273
+ const json = JSON.parse(await readFile(path.join(descriptor.agentDir, credentialPath), "utf8"));
274
+ if (credentialPath === "auth.json") {
275
+ if (!json || typeof json !== "object" || Array.isArray(json)) {
276
+ throw new Error(`Credential file '${credentialPath}' must contain a JSON object`);
277
+ }
278
+ const selected = (json as Record<string, unknown>)[descriptor.providerId];
279
+ if (selected && typeof selected === "object" && !Array.isArray(selected)) {
280
+ for (const [key, value] of Object.entries(selected as Record<string, unknown>)) {
281
+ if (key === "key" && typeof value === "string") values.apiKey = value;
282
+ else if (["string", "number", "boolean"].includes(typeof value))
283
+ values[key] = String(value);
284
+ }
285
+ }
286
+ } else Object.assign(values, strings(json, credentialPath));
287
+ }
288
+ const fingerprint = JSON.stringify(
289
+ Object.keys(values)
290
+ .sort()
291
+ .map((key) => [key, values[key]]),
292
+ );
293
+ return { values, fingerprint };
294
+ }