@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,385 @@
1
+ import type { WorkerErrorClass } from "@leitwerk-dev/domain";
2
+ import type { WorkerDiagnosticPayload, WorkerOperationEmitter } from "./diagnostics.js";
3
+ import {
4
+ doesPiEventResetInactivity,
5
+ type PiTreeHandle,
6
+ type PiTurnExecutionResult,
7
+ } from "./pi-adapter.js";
8
+ import { toErrorMessage } from "./turn-execution-error.js";
9
+
10
+ export type PromptGuardTimer = ReturnType<typeof setTimeout>;
11
+
12
+ export interface PromptGuardScheduler {
13
+ setTimeout(handler: () => void, delayMs: number): PromptGuardTimer;
14
+ clearTimeout(timer: PromptGuardTimer): void;
15
+ sleep(delayMs: number): Promise<void>;
16
+ now(): Date;
17
+ }
18
+
19
+ export type PromptGuardTimeoutKind = "max_duration" | "inactivity";
20
+
21
+ /** Shared by custom tools and one prompt attempt to pause execution budgets safely. */
22
+ export class PromptGuardSuspension {
23
+ private listener: ((paused: boolean) => void) | null = null;
24
+
25
+ suspend(): () => void {
26
+ this.listener?.(true);
27
+ let suspended = true;
28
+ return () => {
29
+ if (!suspended) return;
30
+ suspended = false;
31
+ this.listener?.(false);
32
+ };
33
+ }
34
+
35
+ subscribe(listener: (paused: boolean) => void): () => void {
36
+ this.listener = listener;
37
+ return () => {
38
+ this.listener = null;
39
+ };
40
+ }
41
+ }
42
+
43
+ export class PromptTimeoutError extends Error {
44
+ readonly timeoutKind: PromptGuardTimeoutKind;
45
+ readonly timeoutMs: number;
46
+
47
+ constructor(turnId: string, timeoutKind: PromptGuardTimeoutKind, timeoutMs: number) {
48
+ super(
49
+ timeoutKind === "inactivity"
50
+ ? `Turn '${turnId}' exceeded inactivity timeout after ${timeoutMs}ms without Pi activity`
51
+ : `Turn '${turnId}' exceeded maximum duration of ${timeoutMs}ms`,
52
+ );
53
+ this.name = "PromptTimeoutError";
54
+ this.timeoutKind = timeoutKind;
55
+ this.timeoutMs = timeoutMs;
56
+ }
57
+ }
58
+
59
+ /**
60
+ * Raised when an operator explicitly stops the in-flight turn. Carries the
61
+ * `operator_abort` error class so the parked failure reads as an intentional
62
+ * stop (with continue / go-back recovery) rather than a model or infra failure.
63
+ */
64
+ export class OperatorAbortError extends Error {
65
+ readonly errorClass: WorkerErrorClass = "operator_abort";
66
+
67
+ constructor(turnId: string) {
68
+ super(
69
+ `Stopped by operator. Continue from the saved work, or go back and choose a different action.`,
70
+ );
71
+ this.name = "OperatorAbortError";
72
+ this.turnId = turnId;
73
+ }
74
+
75
+ readonly turnId: string;
76
+ }
77
+
78
+ export interface PromptGuardCallbacks {
79
+ scheduler: PromptGuardScheduler;
80
+ turnMaxDurationMs?: number;
81
+ turnInactivityTimeoutMs?: number;
82
+ turnAbortGracePeriodMs?: number;
83
+ operatorAbortSignal?: AbortSignal;
84
+ guardSuspension?: PromptGuardSuspension;
85
+ emit?: WorkerOperationEmitter;
86
+ }
87
+
88
+ export interface PromptExecutionAttemptResult {
89
+ result: PiTurnExecutionResult;
90
+ sawCompaction: boolean;
91
+ }
92
+
93
+ export async function promptWithGuards(
94
+ deps: PromptGuardCallbacks,
95
+ input: {
96
+ piHandle: Pick<PiTreeHandle, "subscribe" | "abortTurn">;
97
+ turnRecordId: string;
98
+ turnId: string;
99
+ runPrompt: () => Promise<PiTurnExecutionResult>;
100
+ },
101
+ ): Promise<PromptExecutionAttemptResult> {
102
+ const turnMaxDurationMs = deps.turnMaxDurationMs;
103
+ const turnInactivityTimeoutMs = deps.turnInactivityTimeoutMs;
104
+ const turnAbortGracePeriodMs = deps.turnAbortGracePeriodMs ?? 5_000;
105
+ const trace = (payload: WorkerDiagnosticPayload) => deps.emit?.({ kind: "trace", payload });
106
+ const reportError = (payload: WorkerDiagnosticPayload) => deps.emit?.({ kind: "error", payload });
107
+ const taint = (reason: string) => deps.emit?.({ kind: "session_tainted", reason });
108
+ const timeoutDetails = {
109
+ ...(turnMaxDurationMs && turnMaxDurationMs > 0 ? { turnMaxDurationMs } : {}),
110
+ ...(turnInactivityTimeoutMs && turnInactivityTimeoutMs > 0 ? { turnInactivityTimeoutMs } : {}),
111
+ };
112
+ trace({
113
+ level: "info",
114
+ code: "turn.prompt_started",
115
+ message: `Turn '${input.turnId}' prompt started`,
116
+ turnRecordId: input.turnRecordId,
117
+ turnId: input.turnId,
118
+ ...(Object.keys(timeoutDetails).length > 0 ? { details: timeoutDetails } : {}),
119
+ });
120
+
121
+ let maxDurationTimer: PromptGuardTimer | null = null;
122
+ let inactivityTimer: PromptGuardTimer | null = null;
123
+ let rejectTimeout: ((error: Error) => void) | null = null;
124
+ let timedOut = false;
125
+ let aborted = false;
126
+ let sawCompaction = false;
127
+ let removeOperatorAbortListener: (() => void) | null = null;
128
+ let removeSuspensionListener: (() => void) | null = null;
129
+ let guardsPaused = false;
130
+ let maxDurationRemainingMs = turnMaxDurationMs ?? 0;
131
+ let maxDurationArmedAt = 0;
132
+
133
+ const clearTimers = () => {
134
+ if (maxDurationTimer !== null) {
135
+ deps.scheduler.clearTimeout(maxDurationTimer);
136
+ maxDurationTimer = null;
137
+ }
138
+ if (inactivityTimer !== null) {
139
+ deps.scheduler.clearTimeout(inactivityTimer);
140
+ inactivityTimer = null;
141
+ }
142
+ };
143
+
144
+ const requestAbortForTimeout = (timeoutKind: PromptGuardTimeoutKind, timeoutMs: number) => {
145
+ if (timedOut || aborted) {
146
+ return;
147
+ }
148
+ timedOut = true;
149
+ clearTimers();
150
+ const error = new PromptTimeoutError(input.turnId, timeoutKind, timeoutMs);
151
+ reportError({
152
+ level: "error",
153
+ code:
154
+ timeoutKind === "inactivity"
155
+ ? "guard.turn_inactivity_timeout"
156
+ : "guard.turn_max_duration_exceeded",
157
+ message: error.message,
158
+ turnRecordId: input.turnRecordId,
159
+ turnId: input.turnId,
160
+ errorClass: "llm_error" satisfies WorkerErrorClass,
161
+ details: { timeoutMs, timeoutKind },
162
+ });
163
+ taint(`${timeoutKind}:${input.turnId}`);
164
+ trace({
165
+ level: "warn",
166
+ code: "guard.abort_requested",
167
+ message: `Requesting abort for turn '${input.turnId}' after ${timeoutKind}`,
168
+ turnRecordId: input.turnRecordId,
169
+ turnId: input.turnId,
170
+ details: { turnAbortGracePeriodMs, timeoutMs, timeoutKind },
171
+ });
172
+ rejectTimeout?.(error);
173
+
174
+ void (async () => {
175
+ let abortCompleted = false;
176
+ try {
177
+ await Promise.race([
178
+ input.piHandle.abortTurn().then(() => {
179
+ abortCompleted = true;
180
+ }),
181
+ deps.scheduler.sleep(turnAbortGracePeriodMs),
182
+ ]);
183
+ if (!abortCompleted) {
184
+ reportError({
185
+ level: "error",
186
+ code: "guard.abort_grace_elapsed",
187
+ message: `Timed out turn '${input.turnId}' did not abort within ${turnAbortGracePeriodMs}ms`,
188
+ turnRecordId: input.turnRecordId,
189
+ turnId: input.turnId,
190
+ errorClass: "infrastructure",
191
+ details: { turnAbortGracePeriodMs, timeoutKind },
192
+ });
193
+ }
194
+ } catch (error) {
195
+ reportError({
196
+ level: "error",
197
+ code: "guard.abort_failed",
198
+ message: `Failed to abort timed out turn '${input.turnId}': ${toErrorMessage(error)}`,
199
+ turnRecordId: input.turnRecordId,
200
+ turnId: input.turnId,
201
+ errorClass: "infrastructure",
202
+ details: { timeoutKind },
203
+ });
204
+ }
205
+ })();
206
+ };
207
+
208
+ const requestOperatorAbort = () => {
209
+ if (timedOut || aborted) {
210
+ return;
211
+ }
212
+ aborted = true;
213
+ clearTimers();
214
+ const error = new OperatorAbortError(input.turnId);
215
+ reportError({
216
+ level: "error",
217
+ code: "guard.operator_abort_requested",
218
+ message: error.message,
219
+ turnRecordId: input.turnRecordId,
220
+ turnId: input.turnId,
221
+ errorClass: "operator_abort" satisfies WorkerErrorClass,
222
+ });
223
+ taint(`operator_abort:${input.turnId}`);
224
+ trace({
225
+ level: "warn",
226
+ code: "guard.abort_requested",
227
+ message: `Requesting abort for turn '${input.turnId}' after operator stop`,
228
+ turnRecordId: input.turnRecordId,
229
+ turnId: input.turnId,
230
+ details: { turnAbortGracePeriodMs },
231
+ });
232
+ rejectTimeout?.(error);
233
+
234
+ void (async () => {
235
+ let abortCompleted = false;
236
+ try {
237
+ await Promise.race([
238
+ input.piHandle.abortTurn().then(() => {
239
+ abortCompleted = true;
240
+ }),
241
+ deps.scheduler.sleep(turnAbortGracePeriodMs),
242
+ ]);
243
+ if (!abortCompleted) {
244
+ reportError({
245
+ level: "error",
246
+ code: "guard.abort_grace_elapsed",
247
+ message: `Operator-stopped turn '${input.turnId}' did not abort within ${turnAbortGracePeriodMs}ms`,
248
+ turnRecordId: input.turnRecordId,
249
+ turnId: input.turnId,
250
+ errorClass: "infrastructure",
251
+ details: { turnAbortGracePeriodMs },
252
+ });
253
+ }
254
+ } catch (error) {
255
+ reportError({
256
+ level: "error",
257
+ code: "guard.abort_failed",
258
+ message: `Failed to abort operator-stopped turn '${input.turnId}': ${toErrorMessage(error)}`,
259
+ turnRecordId: input.turnRecordId,
260
+ turnId: input.turnId,
261
+ errorClass: "infrastructure",
262
+ });
263
+ }
264
+ })();
265
+ };
266
+
267
+ const armMaxDurationTimer = () => {
268
+ if (
269
+ !turnMaxDurationMs ||
270
+ turnMaxDurationMs <= 0 ||
271
+ maxDurationRemainingMs <= 0 ||
272
+ guardsPaused ||
273
+ timedOut ||
274
+ aborted
275
+ )
276
+ return;
277
+ maxDurationArmedAt = deps.scheduler.now().getTime();
278
+ maxDurationTimer = deps.scheduler.setTimeout(() => {
279
+ requestAbortForTimeout("max_duration", turnMaxDurationMs);
280
+ }, maxDurationRemainingMs);
281
+ };
282
+
283
+ const resetInactivityTimer = () => {
284
+ if (
285
+ !turnInactivityTimeoutMs ||
286
+ turnInactivityTimeoutMs <= 0 ||
287
+ guardsPaused ||
288
+ timedOut ||
289
+ aborted
290
+ ) {
291
+ return;
292
+ }
293
+ if (inactivityTimer !== null) {
294
+ deps.scheduler.clearTimeout(inactivityTimer);
295
+ }
296
+ inactivityTimer = deps.scheduler.setTimeout(() => {
297
+ requestAbortForTimeout("inactivity", turnInactivityTimeoutMs);
298
+ }, turnInactivityTimeoutMs);
299
+ };
300
+
301
+ const unsubscribe = input.piHandle.subscribe((event) => {
302
+ if (event.type === "compaction.start" || event.type === "compaction.end") {
303
+ sawCompaction = true;
304
+ }
305
+ if (doesPiEventResetInactivity(event)) {
306
+ resetInactivityTimer();
307
+ }
308
+ });
309
+
310
+ const operatorAbortSignal = deps.operatorAbortSignal;
311
+ const guardPromise = new Promise<never>((_, reject) => {
312
+ rejectTimeout = reject;
313
+ armMaxDurationTimer();
314
+ resetInactivityTimer();
315
+ });
316
+ removeSuspensionListener =
317
+ deps.guardSuspension?.subscribe((paused) => {
318
+ if (guardsPaused === paused || timedOut || aborted) return;
319
+ guardsPaused = paused;
320
+ if (paused) {
321
+ if (maxDurationTimer !== null) {
322
+ maxDurationRemainingMs = Math.max(
323
+ 1,
324
+ maxDurationRemainingMs -
325
+ Math.max(0, deps.scheduler.now().getTime() - maxDurationArmedAt),
326
+ );
327
+ }
328
+ clearTimers();
329
+ trace({
330
+ level: "info",
331
+ code: "guard.suspended_for_operator",
332
+ message: `Turn '${input.turnId}' execution budgets paused for operator input`,
333
+ turnRecordId: input.turnRecordId,
334
+ turnId: input.turnId,
335
+ });
336
+ } else {
337
+ armMaxDurationTimer();
338
+ resetInactivityTimer();
339
+ }
340
+ }) ?? null;
341
+
342
+ // The executor above runs synchronously, so rejectTimeout is set by now.
343
+ // Wire the operator abort listener here (not inside the executor) so the
344
+ // removeOperatorAbortListener assignment stays in the main control flow.
345
+ if (operatorAbortSignal) {
346
+ if (operatorAbortSignal.aborted) {
347
+ requestOperatorAbort();
348
+ } else {
349
+ const onAbort = () => requestOperatorAbort();
350
+ operatorAbortSignal.addEventListener("abort", onAbort, { once: true });
351
+ removeOperatorAbortListener = () => operatorAbortSignal.removeEventListener("abort", onAbort);
352
+ }
353
+ }
354
+
355
+ const hasGuards =
356
+ (turnMaxDurationMs !== undefined && turnMaxDurationMs > 0) ||
357
+ (turnInactivityTimeoutMs !== undefined && turnInactivityTimeoutMs > 0) ||
358
+ operatorAbortSignal !== undefined;
359
+
360
+ try {
361
+ if (aborted) {
362
+ await guardPromise;
363
+ }
364
+ const result = !hasGuards
365
+ ? await input.runPrompt()
366
+ : await Promise.race([input.runPrompt(), guardPromise]);
367
+ trace({
368
+ level: "info",
369
+ code: "turn.prompt_completed",
370
+ message: `Turn '${input.turnId}' prompt completed`,
371
+ turnRecordId: input.turnRecordId,
372
+ turnId: input.turnId,
373
+ details: { resultPiEntryId: result.resultEntryId },
374
+ });
375
+ return {
376
+ result,
377
+ sawCompaction,
378
+ };
379
+ } finally {
380
+ unsubscribe();
381
+ clearTimers();
382
+ removeOperatorAbortListener?.();
383
+ removeSuspensionListener?.();
384
+ }
385
+ }
@@ -0,0 +1,69 @@
1
+ import type {
2
+ ServerToWorkerMessage,
3
+ WorkerQuestionRequestedPayload,
4
+ } from "@leitwerk-dev/worker-protocol";
5
+ import type { WorkerQuestionRequest } from "./question-tool.js";
6
+ import type { WorkerIpcReporter } from "./worker-ipc-reporter.js";
7
+
8
+ interface PendingQuestion {
9
+ payload: WorkerQuestionRequestedPayload;
10
+ resolve(answers: string[]): void;
11
+ reject(error: Error): void;
12
+ removeAbort(): void;
13
+ }
14
+
15
+ export class WorkerQuestionBridge {
16
+ private readonly pending = new Map<string, PendingQuestion>();
17
+
18
+ constructor(private readonly reporter: WorkerIpcReporter) {}
19
+
20
+ request(request: WorkerQuestionRequest): Promise<string[]> {
21
+ if (this.pending.has(request.toolCallId)) {
22
+ return Promise.reject(new Error("Duplicate in-flight question request"));
23
+ }
24
+ const payload: WorkerQuestionRequestedPayload = {
25
+ turnRecordId: request.turnRecordId,
26
+ toolCallId: request.toolCallId,
27
+ questions: request.questions,
28
+ };
29
+ return new Promise<string[]>((resolve, reject) => {
30
+ const onAbort = () => {
31
+ this.pending.delete(request.toolCallId);
32
+ reject(new Error("Question request cancelled because the turn stopped"));
33
+ };
34
+ request.signal.addEventListener("abort", onAbort, { once: true });
35
+ this.pending.set(request.toolCallId, {
36
+ payload,
37
+ resolve,
38
+ reject,
39
+ removeAbort: () => request.signal.removeEventListener("abort", onAbort),
40
+ });
41
+ this.emit(payload);
42
+ });
43
+ }
44
+
45
+ handle(message: Extract<ServerToWorkerMessage, { type: "worker.question_response" }>): boolean {
46
+ const pending = this.pending.get(message.payload.toolCallId);
47
+ if (!pending || pending.payload.turnRecordId !== message.payload.turnRecordId) return false;
48
+ this.pending.delete(message.payload.toolCallId);
49
+ pending.removeAbort();
50
+ pending.resolve([...message.payload.answers]);
51
+ return true;
52
+ }
53
+
54
+ replay(): void {
55
+ for (const pending of this.pending.values()) this.emit(pending.payload);
56
+ }
57
+
58
+ cancelAll(reason: string): void {
59
+ for (const pending of this.pending.values()) {
60
+ pending.removeAbort();
61
+ pending.reject(new Error(reason));
62
+ }
63
+ this.pending.clear();
64
+ }
65
+
66
+ private emit(payload: WorkerQuestionRequestedPayload): void {
67
+ this.reporter.project({ kind: "protocol", type: "worker.question_requested", payload });
68
+ }
69
+ }
@@ -0,0 +1,65 @@
1
+ import { type NormalizedQuestion, normalizeAskQuestionsInput } from "@leitwerk-dev/domain";
2
+ import type { PiCustomTool } from "@leitwerk-dev/process-sdk";
3
+
4
+ export interface WorkerQuestionRequest {
5
+ turnRecordId: string;
6
+ toolCallId: string;
7
+ questions: NormalizedQuestion[];
8
+ signal: AbortSignal;
9
+ }
10
+
11
+ export function createAskQuestionsTool(input: {
12
+ turnRecordId: string;
13
+ request(request: WorkerQuestionRequest): Promise<string[]>;
14
+ }): PiCustomTool {
15
+ return {
16
+ name: "ask_questions",
17
+ description:
18
+ "Pause this turn to ask the operator one or more focused questions. For every question, provide distinct prepared choices, clearly mark one choice as recommended in its label, and explain why in its details. The same turn resumes with one free-text answer per question.",
19
+ executionMode: "sequential",
20
+ parameters: {
21
+ questions: {
22
+ type: "array",
23
+ description: "Questions to present in order",
24
+ required: true,
25
+ items: {
26
+ type: "object",
27
+ properties: {
28
+ question: { type: "string" },
29
+ selection: { type: "string", enum: ["single", "multiple"] },
30
+ options: {
31
+ type: "array",
32
+ items: {
33
+ type: "object",
34
+ properties: {
35
+ label: { type: "string" },
36
+ details: { type: "string" },
37
+ },
38
+ required: ["label"],
39
+ },
40
+ },
41
+ },
42
+ required: ["question", "selection", "options"],
43
+ },
44
+ },
45
+ },
46
+ async execute(args, context) {
47
+ if (!context) throw new Error("ask_questions requires a correlated tool-call context");
48
+ const questions = normalizeAskQuestionsInput(args);
49
+ const resumeGuards = context.suspendPromptGuards?.();
50
+ try {
51
+ const answers = await input.request({
52
+ turnRecordId: input.turnRecordId,
53
+ toolCallId: context.toolCallId,
54
+ questions,
55
+ signal: context.signal,
56
+ });
57
+ return { answers };
58
+ } finally {
59
+ resumeGuards?.();
60
+ }
61
+ },
62
+ };
63
+ }
64
+
65
+ export const ASK_QUESTIONS_PROMPT_GUIDANCE = `\n\nOperator questions:\n- Use ask_questions only when an operator decision would materially improve this turn.\n- Ask focused questions with distinct prepared options. For each question, clearly mark one option as recommended in its label and explain why in its details; do not guess after calling it.\n- The tool pauses this same turn and returns answers in question order. You may call it again for a follow-up after it returns.\n`;
@@ -0,0 +1,115 @@
1
+ import { existsSync, readdirSync, readFileSync } from "node:fs";
2
+ import path from "node:path";
3
+ import type { DefaultResourceLoader, SettingsManager } from "@earendil-works/pi-coding-agent";
4
+
5
+ const AGGREGATED_AGENTS_REL = "AGENTS.md";
6
+ const AGGREGATED_SKILLS_DIR_REL = path.join(".leitwerk", "skills");
7
+
8
+ type DefaultResourceLoaderConstructorOptions = ConstructorParameters<
9
+ typeof DefaultResourceLoader
10
+ >[0];
11
+
12
+ type LeitwerkResourceLoaderOptions = Omit<
13
+ DefaultResourceLoaderConstructorOptions,
14
+ "cwd" | "agentDir" | "settingsManager"
15
+ >;
16
+
17
+ export interface ResourceLoaderOptions {
18
+ systemPrompt?: string;
19
+ appendSystemPrompt?: string;
20
+ }
21
+
22
+ const PI_EXTENSION_SUFFIXES = new Set([".js", ".mjs", ".cjs", ".ts", ".mts", ".cts"]);
23
+
24
+ function managedExtensionPaths(root: string): string[] {
25
+ if (!existsSync(root)) return [];
26
+ const paths: string[] = [];
27
+ const visit = (directory: string): void => {
28
+ for (const entry of readdirSync(directory, { withFileTypes: true })) {
29
+ const entryPath = path.join(directory, entry.name);
30
+ if (entry.isDirectory()) visit(entryPath);
31
+ else if (entry.isFile() && PI_EXTENSION_SUFFIXES.has(path.extname(entry.name))) {
32
+ paths.push(entryPath);
33
+ }
34
+ }
35
+ };
36
+ visit(root);
37
+ return paths.sort((left, right) => left.localeCompare(right));
38
+ }
39
+
40
+ export async function buildLeitwerkResourceLoaderOptions(
41
+ workspaceRoot: string,
42
+ agentDir: string,
43
+ options: ResourceLoaderOptions = {},
44
+ ): Promise<LeitwerkResourceLoaderOptions> {
45
+ const { loadSkillsFromDir } = await import("@earendil-works/pi-coding-agent");
46
+ const aggregatedAgentsPath = path.join(workspaceRoot, AGGREGATED_AGENTS_REL);
47
+ const aggregatedSkillsDir = path.join(workspaceRoot, AGGREGATED_SKILLS_DIR_REL);
48
+ const managedExtensionsDir = path.join(agentDir, "extensions");
49
+ const managedSkillsDir = path.join(agentDir, "skills");
50
+ const managedPromptsDir = path.join(agentDir, "prompts");
51
+ return {
52
+ // Disable cwd and ambient discovery. Only the immutable managed snapshot and
53
+ // explicitly aggregated process-workspace inputs may reach Pi.
54
+ noExtensions: true,
55
+ noSkills: true,
56
+ noPromptTemplates: true,
57
+ noThemes: true,
58
+ noContextFiles: true,
59
+ additionalExtensionPaths: managedExtensionPaths(managedExtensionsDir),
60
+ additionalSkillPaths: existsSync(managedSkillsDir) ? [managedSkillsDir] : [],
61
+ additionalPromptTemplatePaths: existsSync(managedPromptsDir) ? [managedPromptsDir] : [],
62
+ systemPrompt: options.systemPrompt,
63
+ appendSystemPrompt: options.appendSystemPrompt ? [options.appendSystemPrompt] : undefined,
64
+ skillsOverride(base) {
65
+ if (!existsSync(aggregatedSkillsDir)) {
66
+ return base;
67
+ }
68
+ const extra = loadSkillsFromDir({
69
+ dir: aggregatedSkillsDir,
70
+ source: "process-workspace",
71
+ });
72
+ return {
73
+ skills: [...base.skills, ...extra.skills],
74
+ diagnostics: [...base.diagnostics, ...extra.diagnostics],
75
+ };
76
+ },
77
+ agentsFilesOverride(base) {
78
+ if (!existsSync(aggregatedAgentsPath)) {
79
+ return base;
80
+ }
81
+ const normalizedAggregatedAgentsPath = path.resolve(aggregatedAgentsPath);
82
+ if (
83
+ base.agentsFiles.some((file) => path.resolve(file.path) === normalizedAggregatedAgentsPath)
84
+ ) {
85
+ return base;
86
+ }
87
+ return {
88
+ agentsFiles: [
89
+ ...base.agentsFiles,
90
+ {
91
+ path: aggregatedAgentsPath,
92
+ content: readFileSync(aggregatedAgentsPath, "utf8"),
93
+ },
94
+ ],
95
+ };
96
+ },
97
+ };
98
+ }
99
+
100
+ export async function createResourceLoader(
101
+ workspaceRoot: string,
102
+ settingsManager: SettingsManager,
103
+ agentDir: string,
104
+ options: ResourceLoaderOptions = {},
105
+ ): Promise<DefaultResourceLoader> {
106
+ const { DefaultResourceLoader } = await import("@earendil-works/pi-coding-agent");
107
+ const loader = new DefaultResourceLoader({
108
+ cwd: workspaceRoot,
109
+ agentDir,
110
+ settingsManager,
111
+ ...(await buildLeitwerkResourceLoaderOptions(workspaceRoot, agentDir, options)),
112
+ });
113
+ await loader.reload();
114
+ return loader;
115
+ }