@leitwerk-dev/worker 0.1.9 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (240) hide show
  1. package/dist/automatic-turn-executor.d.ts +1 -0
  2. package/dist/automatic-turn-executor.d.ts.map +1 -1
  3. package/dist/{chunk-O6332GRG.js → chunk-2LLFMCR6.js} +1511 -1071
  4. package/dist/chunk-2LLFMCR6.js.map +1 -0
  5. package/dist/connection-diagnostics.d.ts +5 -0
  6. package/dist/connection-diagnostics.d.ts.map +1 -0
  7. package/dist/container-entry-main.d.ts +2 -0
  8. package/dist/container-entry-main.d.ts.map +1 -0
  9. package/dist/container-entry-main.js +232 -0
  10. package/dist/container-entry-main.js.map +1 -0
  11. package/dist/container-entry.d.ts +14 -0
  12. package/dist/container-entry.d.ts.map +1 -0
  13. package/dist/development-tool-environment.d.ts +84 -0
  14. package/dist/development-tool-environment.d.ts.map +1 -0
  15. package/dist/diagnostics.d.ts +4 -0
  16. package/dist/diagnostics.d.ts.map +1 -1
  17. package/dist/docker-registry-credentials.d.ts +8 -0
  18. package/dist/docker-registry-credentials.d.ts.map +1 -0
  19. package/dist/entry-runtime.d.ts +19 -0
  20. package/dist/entry-runtime.d.ts.map +1 -1
  21. package/dist/index.d.ts +3 -5
  22. package/dist/index.d.ts.map +1 -1
  23. package/dist/index.js +10 -5
  24. package/dist/index.js.map +1 -1
  25. package/dist/input-consumer.d.ts +7 -11
  26. package/dist/input-consumer.d.ts.map +1 -1
  27. package/dist/ipc.d.ts +10 -0
  28. package/dist/ipc.d.ts.map +1 -1
  29. package/dist/logical-prompt-runner.d.ts.map +1 -1
  30. package/dist/managed-pi-agent-dir.d.ts +8 -1
  31. package/dist/managed-pi-agent-dir.d.ts.map +1 -1
  32. package/dist/managed-pi-bootstrap.d.ts +1 -0
  33. package/dist/managed-pi-bootstrap.d.ts.map +1 -1
  34. package/dist/missing-tool-recovery-runner.d.ts +4 -3
  35. package/dist/missing-tool-recovery-runner.d.ts.map +1 -1
  36. package/dist/pi-adapter.d.ts +88 -1
  37. package/dist/pi-adapter.d.ts.map +1 -1
  38. package/dist/pi-event-reporter.d.ts.map +1 -1
  39. package/dist/pi-resource-bundle.d.ts +17 -1
  40. package/dist/pi-resource-bundle.d.ts.map +1 -1
  41. package/dist/pre-turn-targeted-inputs.d.ts +8 -7
  42. package/dist/pre-turn-targeted-inputs.d.ts.map +1 -1
  43. package/dist/prompt-guards.d.ts +6 -0
  44. package/dist/prompt-guards.d.ts.map +1 -1
  45. package/dist/repository-bash-tool.d.ts +4 -0
  46. package/dist/repository-bash-tool.d.ts.map +1 -0
  47. package/dist/resource-loader-factory.d.ts +1 -2
  48. package/dist/resource-loader-factory.d.ts.map +1 -1
  49. package/dist/result-image-upload.d.ts.map +1 -1
  50. package/dist/runtime/adapters.d.ts +38 -0
  51. package/dist/runtime/adapters.d.ts.map +1 -1
  52. package/dist/runtime/bootstrap-session.d.ts +9 -5
  53. package/dist/runtime/bootstrap-session.d.ts.map +1 -1
  54. package/dist/runtime/bootstrap.d.ts +38 -18
  55. package/dist/runtime/bootstrap.d.ts.map +1 -1
  56. package/dist/runtime/failure-policy.d.ts +1 -0
  57. package/dist/runtime/failure-policy.d.ts.map +1 -1
  58. package/dist/runtime/index.d.ts +4 -1
  59. package/dist/runtime/index.d.ts.map +1 -1
  60. package/dist/runtime/lifecycle-reducer.d.ts.map +1 -1
  61. package/dist/runtime/llm-turn-execution.d.ts +3 -8
  62. package/dist/runtime/llm-turn-execution.d.ts.map +1 -1
  63. package/dist/runtime/turn-execution.d.ts +2 -9
  64. package/dist/runtime/turn-execution.d.ts.map +1 -1
  65. package/dist/session-snapshot-exchange.d.ts +10 -4
  66. package/dist/session-snapshot-exchange.d.ts.map +1 -1
  67. package/dist/turn-continuation.d.ts.map +1 -1
  68. package/dist/turn-execution-error.d.ts +1 -1
  69. package/dist/turn-execution-error.d.ts.map +1 -1
  70. package/dist/turn-execution-result.d.ts +1 -0
  71. package/dist/turn-execution-result.d.ts.map +1 -1
  72. package/dist/turn-outcome-tool-session.d.ts +0 -2
  73. package/dist/turn-outcome-tool-session.d.ts.map +1 -1
  74. package/dist/turn-result-markdown.d.ts +2 -1
  75. package/dist/turn-result-markdown.d.ts.map +1 -1
  76. package/dist/turn-tree-strategy.d.ts +0 -1
  77. package/dist/turn-tree-strategy.d.ts.map +1 -1
  78. package/dist/worker-entry.js +16 -4
  79. package/dist/worker-entry.js.map +1 -1
  80. package/dist/worker-ipc-reporter.d.ts.map +1 -1
  81. package/dist/workspace/manifest.d.ts +4 -7
  82. package/dist/workspace/manifest.d.ts.map +1 -1
  83. package/dist/workspace/node-run-root-git-ops.d.ts +2 -2
  84. package/dist/workspace/node-run-root-git-ops.d.ts.map +1 -1
  85. package/dist/workspace/resource-aggregator.d.ts.map +1 -1
  86. package/dist/workspace/run-root.d.ts +21 -20
  87. package/dist/workspace/run-root.d.ts.map +1 -1
  88. package/package.json +8 -8
  89. package/src/automatic-turn-executor.ts +2 -0
  90. package/src/connection-diagnostics.ts +27 -0
  91. package/src/container-entry-main.ts +24 -0
  92. package/src/container-entry.ts +246 -0
  93. package/src/development-tool-environment.ts +490 -0
  94. package/src/diagnostics.ts +1 -0
  95. package/src/docker-registry-credentials.ts +65 -0
  96. package/src/entry-runtime.ts +29 -5
  97. package/src/index.ts +1 -39
  98. package/src/input-consumer.ts +8 -29
  99. package/src/ipc.ts +50 -2
  100. package/src/logical-prompt-runner.ts +23 -29
  101. package/src/managed-pi-agent-dir.ts +8 -1
  102. package/src/managed-pi-bootstrap.ts +4 -3
  103. package/src/missing-tool-recovery-runner.ts +4 -18
  104. package/src/pi-adapter.ts +125 -56
  105. package/src/pi-event-reporter.ts +16 -38
  106. package/src/pi-resource-bundle.ts +77 -3
  107. package/src/pre-turn-targeted-inputs.ts +9 -11
  108. package/src/prompt-guards.ts +50 -75
  109. package/src/repository-bash-tool.ts +15 -0
  110. package/src/resource-loader-factory.ts +1 -18
  111. package/src/result-image-upload.ts +16 -27
  112. package/src/runtime/adapters.ts +46 -4
  113. package/src/runtime/bootstrap-session.ts +70 -39
  114. package/src/runtime/bootstrap.ts +184 -101
  115. package/src/runtime/failure-policy.ts +36 -42
  116. package/src/runtime/index.ts +47 -15
  117. package/src/runtime/lifecycle-reducer.ts +71 -173
  118. package/src/runtime/llm-turn-execution.ts +13 -30
  119. package/src/runtime/turn-execution.ts +78 -31
  120. package/src/session-snapshot-exchange.ts +46 -68
  121. package/src/turn-continuation.ts +9 -17
  122. package/src/turn-execution-error.ts +3 -11
  123. package/src/turn-execution-result.ts +1 -0
  124. package/src/turn-outcome-tool-session.ts +25 -21
  125. package/src/turn-result-markdown.ts +31 -34
  126. package/src/turn-tree-strategy.ts +6 -19
  127. package/src/worker-entry.ts +8 -0
  128. package/src/worker-ipc-reporter.ts +8 -16
  129. package/src/workspace/manifest.ts +5 -7
  130. package/src/workspace/node-run-root-git-ops.ts +65 -25
  131. package/src/workspace/resource-aggregator.ts +5 -16
  132. package/src/workspace/run-root.ts +50 -89
  133. package/dist/automatic-turn-executor.js +0 -58
  134. package/dist/automatic-turn-executor.js.map +0 -1
  135. package/dist/chunk-O6332GRG.js.map +0 -1
  136. package/dist/diagnostics.js +0 -51
  137. package/dist/diagnostics.js.map +0 -1
  138. package/dist/entry-runtime.js +0 -160
  139. package/dist/entry-runtime.js.map +0 -1
  140. package/dist/event-translator.js +0 -12
  141. package/dist/event-translator.js.map +0 -1
  142. package/dist/extension-entry-roots.js +0 -41
  143. package/dist/extension-entry-roots.js.map +0 -1
  144. package/dist/identified-pi-entry.js +0 -125
  145. package/dist/identified-pi-entry.js.map +0 -1
  146. package/dist/input-consumer.js +0 -34
  147. package/dist/input-consumer.js.map +0 -1
  148. package/dist/integration-tool-bridge.js +0 -53
  149. package/dist/integration-tool-bridge.js.map +0 -1
  150. package/dist/ipc.js +0 -192
  151. package/dist/ipc.js.map +0 -1
  152. package/dist/logical-prompt-runner.js +0 -225
  153. package/dist/logical-prompt-runner.js.map +0 -1
  154. package/dist/managed-pi-agent-dir.js +0 -66
  155. package/dist/managed-pi-agent-dir.js.map +0 -1
  156. package/dist/managed-pi-bootstrap.js +0 -135
  157. package/dist/managed-pi-bootstrap.js.map +0 -1
  158. package/dist/missing-tool-recovery-runner.js +0 -73
  159. package/dist/missing-tool-recovery-runner.js.map +0 -1
  160. package/dist/pi-adapter.js +0 -1648
  161. package/dist/pi-adapter.js.map +0 -1
  162. package/dist/pi-branch-guard.js +0 -75
  163. package/dist/pi-branch-guard.js.map +0 -1
  164. package/dist/pi-event-reporter.js +0 -136
  165. package/dist/pi-event-reporter.js.map +0 -1
  166. package/dist/pi-resource-bundle.js +0 -58
  167. package/dist/pi-resource-bundle.js.map +0 -1
  168. package/dist/pre-turn-targeted-inputs.js +0 -101
  169. package/dist/pre-turn-targeted-inputs.js.map +0 -1
  170. package/dist/prompt-guards.js +0 -318
  171. package/dist/prompt-guards.js.map +0 -1
  172. package/dist/question-bridge.js +0 -24
  173. package/dist/question-bridge.js.map +0 -1
  174. package/dist/question-tool.js +0 -54
  175. package/dist/question-tool.js.map +0 -1
  176. package/dist/replaying-request-bridge.js +0 -71
  177. package/dist/replaying-request-bridge.js.map +0 -1
  178. package/dist/resource-loader-factory.js +0 -87
  179. package/dist/resource-loader-factory.js.map +0 -1
  180. package/dist/result-image-upload.js +0 -183
  181. package/dist/result-image-upload.js.map +0 -1
  182. package/dist/runtime/adapters.js +0 -15
  183. package/dist/runtime/adapters.js.map +0 -1
  184. package/dist/runtime/bootstrap-session.js +0 -199
  185. package/dist/runtime/bootstrap-session.js.map +0 -1
  186. package/dist/runtime/bootstrap.js +0 -440
  187. package/dist/runtime/bootstrap.js.map +0 -1
  188. package/dist/runtime/failure-policy.js +0 -182
  189. package/dist/runtime/failure-policy.js.map +0 -1
  190. package/dist/runtime/index.js +0 -339
  191. package/dist/runtime/index.js.map +0 -1
  192. package/dist/runtime/lifecycle-reducer.js +0 -1142
  193. package/dist/runtime/lifecycle-reducer.js.map +0 -1
  194. package/dist/runtime/llm-turn-execution.js +0 -494
  195. package/dist/runtime/llm-turn-execution.js.map +0 -1
  196. package/dist/runtime/settings.js +0 -24
  197. package/dist/runtime/settings.js.map +0 -1
  198. package/dist/runtime/snapshot-policy.js +0 -16
  199. package/dist/runtime/snapshot-policy.js.map +0 -1
  200. package/dist/runtime/turn-execution.js +0 -151
  201. package/dist/runtime/turn-execution.js.map +0 -1
  202. package/dist/session-snapshot-exchange.js +0 -102
  203. package/dist/session-snapshot-exchange.js.map +0 -1
  204. package/dist/test-helpers/fake-websocket.js +0 -40
  205. package/dist/test-helpers/fake-websocket.js.map +0 -1
  206. package/dist/test-helpers/ipc-harness.d.ts +0 -11
  207. package/dist/test-helpers/ipc-harness.d.ts.map +0 -1
  208. package/dist/test-helpers/ipc-harness.js +0 -17
  209. package/dist/test-helpers/ipc-harness.js.map +0 -1
  210. package/dist/turn-continuation.js +0 -80
  211. package/dist/turn-continuation.js.map +0 -1
  212. package/dist/turn-execution-error.js +0 -64
  213. package/dist/turn-execution-error.js.map +0 -1
  214. package/dist/turn-execution-result.js +0 -21
  215. package/dist/turn-execution-result.js.map +0 -1
  216. package/dist/turn-outcome-tool-session.js +0 -210
  217. package/dist/turn-outcome-tool-session.js.map +0 -1
  218. package/dist/turn-record-id.js +0 -10
  219. package/dist/turn-record-id.js.map +0 -1
  220. package/dist/turn-result-markdown.js +0 -263
  221. package/dist/turn-result-markdown.js.map +0 -1
  222. package/dist/turn-tree-strategy.js +0 -80
  223. package/dist/turn-tree-strategy.js.map +0 -1
  224. package/dist/worker-http.js +0 -9
  225. package/dist/worker-http.js.map +0 -1
  226. package/dist/worker-ipc-reporter.js +0 -58
  227. package/dist/worker-ipc-reporter.js.map +0 -1
  228. package/dist/worker-payloads.js +0 -66
  229. package/dist/worker-payloads.js.map +0 -1
  230. package/dist/worker-start-payload.js +0 -5
  231. package/dist/worker-start-payload.js.map +0 -1
  232. package/dist/workspace/manifest.js +0 -79
  233. package/dist/workspace/manifest.js.map +0 -1
  234. package/dist/workspace/node-run-root-git-ops.js +0 -96
  235. package/dist/workspace/node-run-root-git-ops.js.map +0 -1
  236. package/dist/workspace/resource-aggregator.js +0 -39
  237. package/dist/workspace/resource-aggregator.js.map +0 -1
  238. package/dist/workspace/run-root.js +0 -209
  239. package/dist/workspace/run-root.js.map +0 -1
  240. package/src/test-helpers/ipc-harness.ts +0 -19
package/src/index.ts CHANGED
@@ -1,54 +1,16 @@
1
1
  export { createWorkerEntryRuntime } from "./entry-runtime.js";
2
- export {
3
- type DeclaredCredentialFile,
4
- resolveManagedPiAgentDir,
5
- writeManagedPiCredentialFiles,
6
- } from "./managed-pi-agent-dir.js";
7
2
  export type {
8
- AgentSessionEventTranslation,
9
- PiCustomTool,
10
- PiEvent,
11
- PiEventHandler,
12
- PiEventType,
13
3
  PiManagedBootstrapOptions,
14
4
  PiManagedBootstrapResult,
15
- PiPromptOptions,
16
- PiRunDetails,
17
- PiSessionDiagnostic,
18
- PiSessionDiagnosticHandler,
19
- PiSessionDiagnosticLevel,
20
- PiTreeEntry,
21
- PiTreeHandle,
22
5
  PiTreeHandleFactory,
23
6
  PiTreeHandleOptions,
24
- PiTreeNode,
25
7
  PiTreePlanningOptions,
26
8
  PiTreePlanningSnapshot,
27
- PiTurnExecutionResult,
28
- } from "./pi-adapter.js";
29
- export {
30
- doesPiEventResetInactivity,
31
- SdkPiTreeHandle,
32
- SdkPiTreeHandleFactory,
33
- translateAgentSessionEventEnvelope,
34
9
  } from "./pi-adapter.js";
35
- export {
36
- createCanonicalPiResourceBundle,
37
- type ExtractedPiResourceFile,
38
- materializeCanonicalPiResourceBundle,
39
- type PiResourceBundle,
40
- type PiResourceFile,
41
- sha256Digest,
42
- validateResourceRelativePath,
43
- verifyCanonicalPiResourceBundle,
44
- } from "./pi-resource-bundle.js";
10
+ export { SdkPiTreeHandleFactory } from "./pi-adapter.js";
45
11
  export {
46
12
  createWorkerRuntime,
47
- nodeWorkerRuntimeScheduler,
48
- type ResultImageToolFactory,
49
- type WorkerRuntime,
50
13
  type WorkerRuntimeAdapters,
51
14
  type WorkerRuntimeConfig,
52
- type WorkerRuntimeOptions,
53
15
  type WorkerRuntimeScheduler,
54
16
  } from "./runtime/index.js";
@@ -1,4 +1,4 @@
1
- import type { ProcessInputTarget } from "@leitwerk-dev/domain";
1
+ import type { InputDelivery } from "@leitwerk-dev/worker-protocol";
2
2
  import type { PiTreeHandle } from "./pi-adapter.js";
3
3
 
4
4
  export type InputDeliveryMode = "prompt" | "steer";
@@ -9,47 +9,26 @@ export interface DeliveredInput {
9
9
  deliveryMode: InputDeliveryMode;
10
10
  }
11
11
 
12
- export interface InputItem {
13
- inputId: string;
14
- sequence: number;
15
- source: string;
16
- kind: string;
17
- target: ProcessInputTarget | null;
18
- bodyMarkdown: string;
19
- }
12
+ /** @internal */
13
+ export interface InputItem extends Omit<InputDelivery, "receivedAt"> {}
20
14
 
21
15
  export type TargetedInputItem = InputItem & { target: NonNullable<InputItem["target"]> };
22
16
 
23
- export function filterInputsAfterConsumedSequence(
24
- inputs: readonly InputItem[],
25
- lastSequenceConsumed: number,
26
- ): InputItem[] {
27
- return inputs.filter((input) => input.sequence > lastSequenceConsumed);
28
- }
17
+ type InputDeliverySession = Pick<PiTreeHandle, "prompt" | "steer">;
29
18
 
30
19
  export function classifyDeliveryMode(
31
20
  input: InputItem,
32
21
  sessionHasActiveTurn: boolean,
33
22
  ): InputDeliveryMode {
34
- if (input.kind === "system_event") {
35
- return "steer";
36
- }
37
- if (sessionHasActiveTurn) {
38
- return "steer";
39
- }
40
- return "prompt";
23
+ return input.kind === "system_event" || sessionHasActiveTurn ? "steer" : "prompt";
41
24
  }
42
25
 
43
26
  export async function deliverInput(
44
- session: PiTreeHandle,
27
+ session: InputDeliverySession,
45
28
  input: InputItem,
46
29
  mode: InputDeliveryMode,
47
30
  ): Promise<DeliveredInput> {
48
- if (mode === "prompt") {
49
- await session.prompt(input.bodyMarkdown);
50
- } else {
51
- await session.steer(input.bodyMarkdown);
52
- }
31
+ await session[mode](input.bodyMarkdown);
53
32
  return {
54
33
  inputId: input.inputId,
55
34
  sequence: input.sequence,
@@ -58,7 +37,7 @@ export async function deliverInput(
58
37
  }
59
38
 
60
39
  export async function deliverBatch(
61
- session: PiTreeHandle,
40
+ session: InputDeliverySession,
62
41
  inputs: InputItem[],
63
42
  hasActiveTurn: boolean,
64
43
  ): Promise<DeliveredInput[]> {
package/src/ipc.ts CHANGED
@@ -8,13 +8,21 @@ import {
8
8
  WORKER_IPC_SERVER_URL_ENV,
9
9
  type WorkerToServerMessage,
10
10
  } from "@leitwerk-dev/worker-protocol";
11
+ import { createConnectionDiagnosticRecorder } from "./connection-diagnostics.js";
11
12
 
13
+ /** @internal */
12
14
  export interface WorkerIpc {
15
+ /** @internal */
13
16
  send(message: WorkerToServerMessage): void;
17
+ /** @internal */
14
18
  onMessage(handler: (message: ServerToWorkerMessage) => void): void;
19
+ /** @internal */
15
20
  onError(handler: (error: Error) => void): void;
21
+ /** @internal */
16
22
  onConnect?(handler: () => void): void;
23
+ /** @internal */
17
24
  start(): void;
25
+ /** @internal */
18
26
  stop(): void;
19
27
  }
20
28
 
@@ -69,12 +77,36 @@ function webSocketDataToText(data: WebSocketMessageEventLike["data"]): string {
69
77
  return data.toString("utf8");
70
78
  }
71
79
 
80
+ // Only known transport codes are safe to retain: native error messages may contain URLs.
81
+ const connectionErrorCodes = new Set([
82
+ "ECONNREFUSED",
83
+ "ECONNRESET",
84
+ "ENOTFOUND",
85
+ "EAI_AGAIN",
86
+ "ETIMEDOUT",
87
+ "ENETUNREACH",
88
+ "EHOSTUNREACH",
89
+ "CERT_HAS_EXPIRED",
90
+ "DEPTH_ZERO_SELF_SIGNED_CERT",
91
+ ]);
92
+ function connectionErrorCode(value: unknown): string {
93
+ for (let depth = 0; depth < 4 && value && typeof value === "object"; depth += 1) {
94
+ const error = value as { code?: unknown; error?: unknown; cause?: unknown };
95
+ if (typeof error.code === "string" && connectionErrorCodes.has(error.code)) {
96
+ return error.code;
97
+ }
98
+ value = error.error ?? error.cause;
99
+ }
100
+ return "websocket_error";
101
+ }
102
+
72
103
  export function createWebSocketWorkerIpc(input: {
73
104
  serverUrl: string;
74
105
  instanceId: string;
75
106
  workerId: string;
76
107
  token: string;
77
108
  reconnect?: boolean;
109
+ onDiagnostic?: (message: string) => void;
78
110
  }): WorkerIpc {
79
111
  let messageHandler: ((message: ServerToWorkerMessage) => void) | undefined;
80
112
  let errorHandler: ((error: Error) => void) | undefined;
@@ -89,6 +121,8 @@ export function createWebSocketWorkerIpc(input: {
89
121
 
90
122
  const reconnectEnabled = input.reconnect === true;
91
123
  const emitError = (error: unknown) => errorHandler?.(toError(error));
124
+ const diagnostic = (detail: string) =>
125
+ `Worker connection ${openedOnce ? "reconnecting" : "initial_connect"}: attempt=${reconnectAttempt + 1}; ${detail}`;
92
126
  const clearReconnectTimer = () => {
93
127
  if (reconnectTimer) {
94
128
  clearTimeout(reconnectTimer);
@@ -147,7 +181,8 @@ export function createWebSocketWorkerIpc(input: {
147
181
  reconnectTimer = null;
148
182
  connect();
149
183
  }, delayMs);
150
- reconnectTimer.unref?.();
184
+ // A pending connection must keep the worker alive, including before bootstrap.
185
+ // stop() clears this timer; the server owns the startup deadline.
151
186
  };
152
187
 
153
188
  return {
@@ -186,12 +221,15 @@ export function createWebSocketWorkerIpc(input: {
186
221
  }
187
222
  socket = new WebSocketImpl(toWebSocketUrl(input));
188
223
  socket.addEventListener("open", () => {
224
+ input.onDiagnostic?.("");
189
225
  reconnectAttempt = 0;
190
226
  flushOutbound();
191
227
  });
192
228
  socket.addEventListener("message", (event) => deliverText(webSocketDataToText(event.data)));
193
229
  socket.addEventListener("error", (event) => {
194
- if (!stopping && !reconnectEnabled) {
230
+ if (stopping) return;
231
+ input.onDiagnostic?.(diagnostic(`error=${connectionErrorCode(event)}`));
232
+ if (!reconnectEnabled) {
195
233
  emitError(event instanceof Error ? event : new Error("Worker WebSocket error"));
196
234
  }
197
235
  });
@@ -199,6 +237,9 @@ export function createWebSocketWorkerIpc(input: {
199
237
  if (stopping) {
200
238
  return;
201
239
  }
240
+ input.onDiagnostic?.(
241
+ diagnostic(`close=${Number.isInteger(event?.code) ? event?.code : "unknown"}`),
242
+ );
202
243
  socket = null;
203
244
  if (reconnectEnabled && event?.code !== 1008) {
204
245
  scheduleReconnect(connect);
@@ -230,6 +271,8 @@ export function createWebSocketWorkerIpc(input: {
230
271
  }
231
272
 
232
273
  export function createWorkerIpcFromEnvironment(input: {
274
+ /** Observe sanitized connection summaries without replacing standard diagnostics. */
275
+ onDiagnostic?: (message: string) => void;
233
276
  env?: NodeJS.ProcessEnv;
234
277
  instanceId: string;
235
278
  workerId: string;
@@ -240,11 +283,16 @@ export function createWorkerIpcFromEnvironment(input: {
240
283
  if (!serverUrl || !token) {
241
284
  throw new Error("WebSocket worker IPC requires LEITWERK_SERVER_URL and worker token env");
242
285
  }
286
+ const recordDiagnostic = createConnectionDiagnosticRecorder();
243
287
  return createWebSocketWorkerIpc({
244
288
  serverUrl,
245
289
  instanceId: input.instanceId,
246
290
  workerId: input.workerId,
247
291
  token,
248
292
  reconnect: env[WORKER_IPC_RECONNECT_ENV] === "1",
293
+ onDiagnostic(message) {
294
+ recordDiagnostic(message);
295
+ input.onDiagnostic?.(message);
296
+ },
249
297
  });
250
298
  }
@@ -30,13 +30,11 @@ export function shouldAutoContinueAfterPromptReturn(input: {
30
30
  sawCompaction: boolean;
31
31
  compactionContinueAttempts: number;
32
32
  }): boolean {
33
- if (input.resolvedOutcome) {
34
- return false;
35
- }
36
- if (!input.sawCompaction) {
37
- return false;
38
- }
39
- return input.compactionContinueAttempts < MAX_COMPACTION_CONTINUE_ATTEMPTS;
33
+ return (
34
+ !input.resolvedOutcome &&
35
+ input.sawCompaction &&
36
+ input.compactionContinueAttempts < MAX_COMPACTION_CONTINUE_ATTEMPTS
37
+ );
40
38
  }
41
39
 
42
40
  function isContextWindowError(error: unknown): boolean {
@@ -158,9 +156,7 @@ export async function executeLogicalPromptPlan<TOutcome extends string>(input: {
158
156
  };
159
157
 
160
158
  for (;;) {
161
- const continuePlan = currentPlan.kind === "continue" ? currentPlan : null;
162
- const promptPlan = currentPlan.kind === "prompt" ? currentPlan : null;
163
- const usingContinueThisAttempt = continuePlan !== null;
159
+ const plan = currentPlan;
164
160
  const guardSuspension = new PromptGuardSuspension();
165
161
  const promptOptions =
166
162
  input.toolSession.tools.length > 0
@@ -178,13 +174,16 @@ export async function executeLogicalPromptPlan<TOutcome extends string>(input: {
178
174
  }
179
175
  : { activeTools: input.toolSession.activeTools };
180
176
 
181
- let preparedPromptRun: (() => Promise<PiTurnExecutionResult>) | null = null;
182
- if (continuePlan) {
177
+ let runPrompt = () =>
178
+ plan.kind === "continue"
179
+ ? input.piHandle.continueTurn(promptOptions)
180
+ : input.piHandle.prompt(plan.promptText ?? "", promptOptions);
181
+ if (plan.kind === "continue") {
183
182
  try {
184
- await continuePlan.prepareForContinuation?.();
185
- if (continuePlan.continueUserPrompt !== null) {
186
- const content = continuePlan.continueUserPrompt;
187
- const identity = continuePlan.identifiedPrompt;
183
+ await plan.prepareForContinuation?.();
184
+ if (plan.continueUserPrompt !== null) {
185
+ const content = plan.continueUserPrompt;
186
+ const identity = plan.identifiedPrompt;
188
187
  if (identity) {
189
188
  const expectedParentId = input.piHandle.getLeafId();
190
189
  if (findIdentifiedPrompt(input.piHandle, identity)) {
@@ -195,7 +194,7 @@ export async function executeLogicalPromptPlan<TOutcome extends string>(input: {
195
194
  expectedParentId,
196
195
  });
197
196
  } else {
198
- preparedPromptRun = () =>
197
+ runPrompt = () =>
199
198
  input.piHandle.promptCustom({ content, details: identity }, promptOptions);
200
199
  }
201
200
  } else {
@@ -205,7 +204,7 @@ export async function executeLogicalPromptPlan<TOutcome extends string>(input: {
205
204
  promptText: content,
206
205
  });
207
206
  if (promptText) {
208
- preparedPromptRun = () => input.piHandle.promptLiteral(promptText, promptOptions);
207
+ runPrompt = () => input.piHandle.promptLiteral(promptText, promptOptions);
209
208
  }
210
209
  }
211
210
  }
@@ -229,13 +228,7 @@ export async function executeLogicalPromptPlan<TOutcome extends string>(input: {
229
228
  piHandle: input.piHandle,
230
229
  turnRecordId: input.turnRecordId,
231
230
  turnId: input.turnId,
232
- runPrompt: () => {
233
- if (preparedPromptRun) return preparedPromptRun();
234
- if (continuePlan) {
235
- return input.piHandle.continueTurn(promptOptions);
236
- }
237
- return input.piHandle.prompt(promptPlan?.promptText ?? "", promptOptions);
238
- },
231
+ runPrompt,
239
232
  },
240
233
  );
241
234
  if (input.toolSession.terminalAcknowledgement.state() === "outcome_accepted") {
@@ -306,14 +299,15 @@ export async function executeLogicalPromptPlan<TOutcome extends string>(input: {
306
299
  continue;
307
300
  }
308
301
  return reportFailure(error, {
309
- code: usingContinueThisAttempt ? "turn.continue_failed" : "turn.prompt_failed",
302
+ code: plan.kind === "continue" ? "turn.continue_failed" : "turn.prompt_failed",
310
303
  emitWorkerError: !(
311
304
  error instanceof PromptTimeoutError || error instanceof OperatorAbortError
312
305
  ),
313
306
  fallbackErrorClass: "llm_error",
314
- messagePrefix: usingContinueThisAttempt
315
- ? `Turn '${input.turnId}' continuation failed`
316
- : `Turn '${input.turnId}' prompt failed`,
307
+ messagePrefix:
308
+ plan.kind === "continue"
309
+ ? `Turn '${input.turnId}' continuation failed`
310
+ : `Turn '${input.turnId}' prompt failed`,
317
311
  });
318
312
  }
319
313
  }
@@ -10,9 +10,13 @@ function safeSegment(value: string, name: string): string {
10
10
  return value;
11
11
  }
12
12
 
13
+ /** @internal */
13
14
  export function resolveManagedPiAgentDir(input: {
15
+ /** @internal */
14
16
  agentDirRoot: string;
17
+ /** @internal */
15
18
  instanceId: string;
19
+ /** @internal */
16
20
  startOrLeaseId: string;
17
21
  }): string {
18
22
  const root = path.resolve(input.agentDirRoot);
@@ -51,12 +55,15 @@ async function assertNoSymlinkParents(root: string, target: string): Promise<voi
51
55
  }
52
56
  }
53
57
 
58
+ /** @internal */
54
59
  export interface DeclaredCredentialFile {
60
+ /** @internal */
55
61
  path: string;
62
+ /** @internal */
56
63
  content: string | Uint8Array;
57
64
  }
58
65
 
59
- /** Atomically writes declared credential files inside an existing managed directory. */
66
+ /** Atomically writes declared credential files inside an existing managed directory. @internal */
60
67
  export async function writeManagedPiCredentialFiles(
61
68
  agentDir: string,
62
69
  files: readonly DeclaredCredentialFile[],
@@ -1,6 +1,5 @@
1
1
  import { lstat, readFile } from "node:fs/promises";
2
2
  import path from "node:path";
3
- import { VERSION as PI_VERSION } from "@earendil-works/pi-coding-agent";
4
3
  import type { ResolvedTurnStart } from "@leitwerk-dev/domain";
5
4
  import {
6
5
  canonicalJsonEqual,
@@ -16,6 +15,7 @@ type ResolvedLlmTurnStart = Extract<ResolvedTurnStart, { kind: "llm" }>;
16
15
 
17
16
  type JsonRecord = Record<string, unknown>;
18
17
 
18
+ /** @internal */
19
19
  export type ManagedPiResourceManifest = PiResourceManifest;
20
20
 
21
21
  function fail(message: string): never {
@@ -48,7 +48,8 @@ function assertModelMatchesStart(
48
48
  }
49
49
  }
50
50
 
51
- function assertCompatibility(manifest: ManagedPiResourceManifest): void {
51
+ async function assertCompatibility(manifest: ManagedPiResourceManifest): Promise<void> {
52
+ const { VERSION: PI_VERSION } = await import("@earendil-works/pi-coding-agent");
52
53
  if (manifest.compatibility.workerApiVersion !== WORKER_API_VERSION) {
53
54
  fail(
54
55
  `server snapshot worker API version '${manifest.compatibility.workerApiVersion}' does not match local worker API version '${WORKER_API_VERSION}'`,
@@ -88,7 +89,7 @@ export async function readAndValidateManagedPiResourceManifest(input: {
88
89
  }
89
90
  const manifest = parsePiResourceManifest(parsed);
90
91
  assertModelMatchesStart(manifest, input.start);
91
- assertCompatibility(manifest);
92
+ await assertCompatibility(manifest);
92
93
  assertJsonEqual(manifest.providerOptions, input.start.providerOptions, "providerOptions");
93
94
  assertJsonEqual(
94
95
  manifest.providerWorkerConfig,
@@ -21,10 +21,8 @@ export async function runMissingToolRecovery<TOutcome extends string>(input: {
21
21
  options?: { baseState?: ToolCompletionSnapshot<TOutcome> },
22
22
  ): Promise<LogicalPromptAttempt<TOutcome>>;
23
23
  }): Promise<{
24
- recovered: boolean;
25
24
  finalAttempt: LogicalPromptAttempt<TOutcome>;
26
- recoveryContext: FailedTurnRecoveryContext | null;
27
- baseMissingToolRecoveryDescription: string | null;
25
+ failure?: { recoveryContext: FailedTurnRecoveryContext; description: string };
28
26
  }> {
29
27
  const trace = (payload: WorkerDiagnosticPayload) => input.emit?.({ kind: "trace", payload });
30
28
  const reportError = (payload: WorkerDiagnosticPayload) =>
@@ -33,12 +31,7 @@ export async function runMissingToolRecovery<TOutcome extends string>(input: {
33
31
  input.initialAttempt.completionState,
34
32
  );
35
33
  if (!baseMissingToolRecovery) {
36
- return {
37
- recovered: true,
38
- finalAttempt: input.initialAttempt,
39
- recoveryContext: null,
40
- baseMissingToolRecoveryDescription: null,
41
- };
34
+ return { finalAttempt: input.initialAttempt };
42
35
  }
43
36
 
44
37
  const recoveryContext = input.toolSession.buildRecoveryContext(baseMissingToolRecovery);
@@ -83,12 +76,7 @@ export async function runMissingToolRecovery<TOutcome extends string>(input: {
83
76
  { baseState: input.initialAttempt.completionState },
84
77
  );
85
78
  if (!input.toolSession.resolveMissingToolRecovery(finalAttempt.completionState)) {
86
- return {
87
- recovered: true,
88
- finalAttempt,
89
- recoveryContext,
90
- baseMissingToolRecoveryDescription: description,
91
- };
79
+ return { finalAttempt };
92
80
  }
93
81
  }
94
82
 
@@ -104,9 +92,7 @@ export async function runMissingToolRecovery<TOutcome extends string>(input: {
104
92
  },
105
93
  });
106
94
  return {
107
- recovered: false,
108
95
  finalAttempt,
109
- recoveryContext,
110
- baseMissingToolRecoveryDescription: description,
96
+ failure: { recoveryContext, description },
111
97
  };
112
98
  }