@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,208 @@
1
+ import { lstat, readFile } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { VERSION as PI_VERSION } from "@earendil-works/pi-coding-agent";
4
+ import type { ResolvedTurnStart } from "@leitwerk-dev/domain";
5
+ import {
6
+ canonicalJsonEqual,
7
+ IPC_PROTOCOL_VERSION,
8
+ type PiResourceManifest,
9
+ parsePiResourceManifest,
10
+ WORKER_API_VERSION,
11
+ type WorkerCredentialMaterial,
12
+ } from "@leitwerk-dev/worker-protocol";
13
+ import type { DeclaredCredentialFile } from "./managed-pi-agent-dir.js";
14
+
15
+ type ResolvedLlmTurnStart = Extract<ResolvedTurnStart, { kind: "llm" }>;
16
+
17
+ type JsonRecord = Record<string, unknown>;
18
+
19
+ export type ManagedPiResourceManifest = PiResourceManifest;
20
+
21
+ function fail(message: string): never {
22
+ throw new Error(`Invalid managed Pi resource snapshot: ${message}`);
23
+ }
24
+
25
+ function record(value: unknown, location: string): JsonRecord {
26
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
27
+ fail(`${location} must be an object`);
28
+ }
29
+ return value as JsonRecord;
30
+ }
31
+
32
+ function assertJsonEqual(actual: unknown, expected: unknown, location: string): void {
33
+ if (!canonicalJsonEqual(actual, expected)) {
34
+ fail(`${location} does not match the resolved LLM start`);
35
+ }
36
+ }
37
+
38
+ function assertModelMatchesStart(
39
+ manifest: ManagedPiResourceManifest,
40
+ start: ResolvedLlmTurnStart,
41
+ ): void {
42
+ for (const key of ["profileId", "providerId", "modelId", "thinkingLevel"] as const) {
43
+ if (manifest.model[key] !== start.model[key]) {
44
+ fail(
45
+ `generated.json model ${key} '${manifest.model[key]}' does not match start '${start.model[key]}'`,
46
+ );
47
+ }
48
+ }
49
+ }
50
+
51
+ function assertCompatibility(manifest: ManagedPiResourceManifest): void {
52
+ if (manifest.compatibility.workerApiVersion !== WORKER_API_VERSION) {
53
+ fail(
54
+ `server snapshot worker API version '${manifest.compatibility.workerApiVersion}' does not match local worker API version '${WORKER_API_VERSION}'`,
55
+ );
56
+ }
57
+ if (manifest.compatibility.piVersion !== PI_VERSION) {
58
+ fail(
59
+ `server snapshot Pi version '${manifest.compatibility.piVersion}' does not match local worker Pi version '${PI_VERSION}'`,
60
+ );
61
+ }
62
+ if (
63
+ manifest.compatibility.protocolVersion !== undefined &&
64
+ manifest.compatibility.protocolVersion !== IPC_PROTOCOL_VERSION
65
+ ) {
66
+ fail(
67
+ `server snapshot protocol version '${manifest.compatibility.protocolVersion}' does not match local worker protocol version '${IPC_PROTOCOL_VERSION}'`,
68
+ );
69
+ }
70
+ }
71
+
72
+ export async function readAndValidateManagedPiResourceManifest(input: {
73
+ agentDir: string;
74
+ resourceDigest: string;
75
+ start: ResolvedLlmTurnStart;
76
+ }): Promise<ManagedPiResourceManifest> {
77
+ const marker = await readFile(path.join(input.agentDir, ".leitwerk-resource-digest"), "utf8");
78
+ if (marker !== `${input.resourceDigest}\n`) {
79
+ fail("materialized resource digest marker does not match the delivered bundle");
80
+ }
81
+ let parsed: unknown;
82
+ try {
83
+ parsed = JSON.parse(await readFile(path.join(input.agentDir, "generated.json"), "utf8"));
84
+ } catch (error) {
85
+ throw new Error("Invalid managed Pi resource snapshot: generated.json is unreadable", {
86
+ cause: error,
87
+ });
88
+ }
89
+ const manifest = parsePiResourceManifest(parsed);
90
+ assertModelMatchesStart(manifest, input.start);
91
+ assertCompatibility(manifest);
92
+ assertJsonEqual(manifest.providerOptions, input.start.providerOptions, "providerOptions");
93
+ assertJsonEqual(
94
+ manifest.providerWorkerConfig,
95
+ input.start.providerWorkerConfig,
96
+ "providerWorkerConfig",
97
+ );
98
+ let settings: unknown;
99
+ try {
100
+ settings = JSON.parse(await readFile(path.join(input.agentDir, "settings.json"), "utf8"));
101
+ } catch (error) {
102
+ throw new Error("Invalid managed Pi resource snapshot: settings.json is unreadable", {
103
+ cause: error,
104
+ });
105
+ }
106
+ assertJsonEqual(
107
+ settings,
108
+ { ...input.start.piSettings, packages: [], defaultProjectTrust: "never" },
109
+ "settings.json",
110
+ );
111
+ return manifest;
112
+ }
113
+
114
+ export function buildManagedPiCredentialFiles(input: {
115
+ manifest: ManagedPiResourceManifest;
116
+ credential: WorkerCredentialMaterial | null;
117
+ providerId: string;
118
+ }): DeclaredCredentialFile[] {
119
+ if (input.credential && input.credential.providerId !== input.providerId) {
120
+ throw new Error(
121
+ `Credential provider '${input.credential.providerId}' does not match selected provider '${input.providerId}'`,
122
+ );
123
+ }
124
+ const values = input.credential?.values ?? {};
125
+ const apiKey = values.apiKey;
126
+ if (apiKey !== undefined && apiKey.trim() === "") {
127
+ throw new Error(`Credential apiKey for provider '${input.providerId}' is empty`);
128
+ }
129
+ let auth: Record<string, unknown> = {};
130
+ if (apiKey) {
131
+ auth = { [input.providerId]: { type: "api_key", key: apiKey } };
132
+ } else if (values.type === "oauth") {
133
+ const entry: Record<string, unknown> = { type: "oauth" };
134
+ for (const key of ["refresh", "access"] as const) {
135
+ if (values[key] !== undefined) entry[key] = values[key];
136
+ }
137
+ if (values.expires !== undefined) {
138
+ const expires = Number(values.expires);
139
+ entry.expires = Number.isNaN(expires) ? values.expires : expires;
140
+ }
141
+ auth = { [input.providerId]: entry };
142
+ }
143
+ if (
144
+ Object.keys(auth).length > 0 &&
145
+ !input.manifest.declaredCredentialPaths.includes("auth.json")
146
+ ) {
147
+ throw new Error(
148
+ `Provider '${input.providerId}' standard credential requires declared auth.json`,
149
+ );
150
+ }
151
+ return input.manifest.declaredCredentialPaths.map((credentialPath) => ({
152
+ path: credentialPath,
153
+ content: `${JSON.stringify(credentialPath === "auth.json" ? auth : values, null, 2)}\n`,
154
+ }));
155
+ }
156
+
157
+ export async function assertManagedPiCredentialFiles(input: {
158
+ agentDir: string;
159
+ manifest: ManagedPiResourceManifest;
160
+ credential: WorkerCredentialMaterial | null;
161
+ }): Promise<void> {
162
+ for (const credentialPath of input.manifest.declaredCredentialPaths) {
163
+ const target = path.join(input.agentDir, credentialPath);
164
+ const stat = await lstat(target).catch(() => null);
165
+ if (!stat?.isFile() || stat.isSymbolicLink()) {
166
+ throw new Error(`Declared credential file '${credentialPath}' is missing or unsafe`);
167
+ }
168
+ if ((stat.mode & 0o777) !== 0o600) {
169
+ throw new Error(`Declared credential file '${credentialPath}' must have mode 0600`);
170
+ }
171
+ }
172
+ if (input.credential && input.manifest.declaredCredentialPaths.includes("auth.json")) {
173
+ const auth = record(
174
+ JSON.parse(await readFile(path.join(input.agentDir, "auth.json"), "utf8")),
175
+ "auth.json",
176
+ );
177
+ if (input.credential.values.apiKey) {
178
+ const providerCredential = record(
179
+ auth[input.credential.providerId],
180
+ `auth.json.${input.credential.providerId}`,
181
+ );
182
+ if (
183
+ (providerCredential.type !== "api_key" && providerCredential.type !== undefined) ||
184
+ providerCredential.key !== input.credential.values.apiKey
185
+ ) {
186
+ throw new Error(
187
+ `Standard Pi credential for provider '${input.credential.providerId}' was not loaded`,
188
+ );
189
+ }
190
+ } else if (input.credential.values.refresh || input.credential.values.access) {
191
+ const providerCredential = record(
192
+ auth[input.credential.providerId],
193
+ `auth.json.${input.credential.providerId}`,
194
+ );
195
+ if (
196
+ providerCredential.type !== "oauth" ||
197
+ (input.credential.values.refresh &&
198
+ providerCredential.refresh !== input.credential.values.refresh) ||
199
+ (input.credential.values.access &&
200
+ providerCredential.access !== input.credential.values.access)
201
+ ) {
202
+ throw new Error(
203
+ `Standard Pi OAuth credential for provider '${input.credential.providerId}' was not loaded`,
204
+ );
205
+ }
206
+ }
207
+ }
208
+ }
@@ -0,0 +1,112 @@
1
+ import type { FailedTurnRecoveryContext } from "@leitwerk-dev/domain";
2
+ import type { WorkerDiagnosticPayload, WorkerOperationEmitter } from "./diagnostics.js";
3
+ import type { LogicalPromptAttempt, LogicalTurnPromptPlan } from "./logical-prompt-runner.js";
4
+ import type { PiTreeHandle } from "./pi-adapter.js";
5
+ import type {
6
+ ToolCompletionSnapshot,
7
+ TurnOutcomeToolSession,
8
+ } from "./turn-outcome-tool-session.js";
9
+
10
+ export const MAX_MISSING_TOOL_CALL_RECOVERY_ATTEMPTS = 3;
11
+
12
+ export async function runMissingToolRecovery<TOutcome extends string>(input: {
13
+ turnId: string;
14
+ turnRecordId: string;
15
+ piHandle: PiTreeHandle;
16
+ initialAttempt: LogicalPromptAttempt<TOutcome>;
17
+ toolSession: TurnOutcomeToolSession<TOutcome>;
18
+ emit?: WorkerOperationEmitter;
19
+ executeLogicalPromptPlan(
20
+ plan: LogicalTurnPromptPlan,
21
+ options?: { baseState?: ToolCompletionSnapshot<TOutcome> },
22
+ ): Promise<LogicalPromptAttempt<TOutcome>>;
23
+ }): Promise<{
24
+ recovered: boolean;
25
+ finalAttempt: LogicalPromptAttempt<TOutcome>;
26
+ recoveryContext: FailedTurnRecoveryContext | null;
27
+ baseMissingToolRecoveryDescription: string | null;
28
+ }> {
29
+ const trace = (payload: WorkerDiagnosticPayload) => input.emit?.({ kind: "trace", payload });
30
+ const reportError = (payload: WorkerDiagnosticPayload) =>
31
+ input.emit?.({ kind: "error", payload });
32
+ const baseMissingToolRecovery = input.toolSession.resolveMissingToolRecovery(
33
+ input.initialAttempt.completionState,
34
+ );
35
+ if (!baseMissingToolRecovery) {
36
+ return {
37
+ recovered: true,
38
+ finalAttempt: input.initialAttempt,
39
+ recoveryContext: null,
40
+ baseMissingToolRecoveryDescription: null,
41
+ };
42
+ }
43
+
44
+ const recoveryContext = input.toolSession.buildRecoveryContext(baseMissingToolRecovery);
45
+ const description = input.toolSession.describeRecovery(baseMissingToolRecovery);
46
+ reportError({
47
+ level: "warn",
48
+ code: "turn.required_tool_call_missing",
49
+ message: `Turn '${input.turnId}' is missing required tool calls: ${description}`,
50
+ turnRecordId: input.turnRecordId,
51
+ turnId: input.turnId,
52
+ errorClass: "protocol_error",
53
+ details: {
54
+ attemptBudget: MAX_MISSING_TOOL_CALL_RECOVERY_ATTEMPTS,
55
+ missingToolNames: baseMissingToolRecovery.missingToolNames,
56
+ },
57
+ });
58
+
59
+ let finalAttempt = input.initialAttempt;
60
+ for (
61
+ let recoveryAttempt = 1;
62
+ recoveryAttempt <= MAX_MISSING_TOOL_CALL_RECOVERY_ATTEMPTS;
63
+ recoveryAttempt += 1
64
+ ) {
65
+ trace({
66
+ level: "info",
67
+ code: "turn.required_tool_call_retry_requested",
68
+ message: `Turn '${input.turnId}' is retrying after a missing required tool call`,
69
+ turnRecordId: input.turnRecordId,
70
+ turnId: input.turnId,
71
+ details: {
72
+ recoveryAttempt,
73
+ missingToolNames: baseMissingToolRecovery.missingToolNames,
74
+ },
75
+ });
76
+ finalAttempt = await input.executeLogicalPromptPlan(
77
+ {
78
+ kind: "continue",
79
+ continueUserPrompt: recoveryContext.suggestedContinuePrompt,
80
+ prepareForContinuation: async () =>
81
+ await input.piHandle.branch(input.initialAttempt.promptResult.resultEntryId),
82
+ },
83
+ { baseState: input.initialAttempt.completionState },
84
+ );
85
+ if (!input.toolSession.resolveMissingToolRecovery(finalAttempt.completionState)) {
86
+ return {
87
+ recovered: true,
88
+ finalAttempt,
89
+ recoveryContext,
90
+ baseMissingToolRecoveryDescription: description,
91
+ };
92
+ }
93
+ }
94
+
95
+ reportError({
96
+ level: "error",
97
+ code: "turn.required_tool_call_retry_exhausted",
98
+ message: `Turn '${input.turnId}' still missed required tool calls after ${MAX_MISSING_TOOL_CALL_RECOVERY_ATTEMPTS} automatic recovery attempts`,
99
+ turnRecordId: input.turnRecordId,
100
+ turnId: input.turnId,
101
+ errorClass: "protocol_error",
102
+ details: {
103
+ missingToolNames: baseMissingToolRecovery.missingToolNames,
104
+ },
105
+ });
106
+ return {
107
+ recovered: false,
108
+ finalAttempt,
109
+ recoveryContext,
110
+ baseMissingToolRecoveryDescription: description,
111
+ };
112
+ }