@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,2197 @@
1
+ import { access, mkdir, writeFile } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { type AssistantMessage, retryAssistantCall } from "@earendil-works/pi-ai";
4
+ import type {
5
+ AgentSession,
6
+ AgentSessionEvent,
7
+ AgentSessionServices,
8
+ ModelRuntime,
9
+ ToolDefinition,
10
+ } from "@earendil-works/pi-coding-agent";
11
+ import type {
12
+ PiCustomMessageInput,
13
+ PiCustomTool,
14
+ PiEvent,
15
+ PiEventHandler,
16
+ PiEventType,
17
+ PiPromptOptions,
18
+ PiRunDetails,
19
+ PiSessionDiagnostic,
20
+ PiSessionDiagnosticHandler,
21
+ PiTreeEntry,
22
+ PiTreeHandle,
23
+ PiTreeNode,
24
+ PiTurnExecutionResult,
25
+ } from "@leitwerk-dev/process-sdk";
26
+ import { resolvePiAgentDir } from "@leitwerk-dev/process-sdk/pi-config";
27
+ import type { ConfigSnapshot } from "@leitwerk-dev/protocol";
28
+ import { parseDurationMs } from "@leitwerk-dev/watcher-utils";
29
+ import type { ManagedPiResourceManifest } from "./managed-pi-bootstrap.js";
30
+ import {
31
+ assertResultStayedOnExecutionBranch,
32
+ isPiBranchDriftError,
33
+ PiBranchDriftError,
34
+ type PiBranchOperation,
35
+ resolveExecutionAnchorEntryId,
36
+ } from "./pi-branch-guard.js";
37
+ import { buildLeitwerkResourceLoaderOptions } from "./resource-loader-factory.js";
38
+
39
+ const LEITWERK_TOOL_BOOTSTRAP_NAME = "__leitwerk_runtime_bootstrap__";
40
+
41
+ export type {
42
+ PiCustomMessageInput,
43
+ PiCustomTool,
44
+ PiEvent,
45
+ PiEventHandler,
46
+ PiEventType,
47
+ PiPromptOptions,
48
+ PiRunDetails,
49
+ PiSessionDiagnostic,
50
+ PiSessionDiagnosticHandler,
51
+ PiSessionDiagnosticLevel,
52
+ PiTreeEntry,
53
+ PiTreeHandle,
54
+ PiTreeNode,
55
+ PiTurnExecutionResult,
56
+ } from "@leitwerk-dev/process-sdk";
57
+ export { isPiBranchDriftError, PiBranchDriftError } from "./pi-branch-guard.js";
58
+
59
+ export interface PiTreeHandleOptions {
60
+ instanceId: string;
61
+ treeFile: string;
62
+ workspaceRoot: string;
63
+ sessionCwd?: string;
64
+ resume: boolean;
65
+ agentDir?: string;
66
+ configSnapshot?: ConfigSnapshot;
67
+ modelProfileId?: string | null;
68
+ piConfig?: {
69
+ systemPrompt?: string;
70
+ appendSystemPrompt?: string;
71
+ availableToolNames: string[];
72
+ };
73
+ }
74
+
75
+ export interface PiManagedBootstrapOptions {
76
+ agentDir: string;
77
+ workspaceRoot: string;
78
+ sessionCwd: string;
79
+ configSnapshot: ConfigSnapshot;
80
+ piConfig: PiTreeHandleOptions["piConfig"];
81
+ manifest: ManagedPiResourceManifest;
82
+ expectedModel: { providerId: string; modelId: string };
83
+ }
84
+
85
+ export interface PiManagedBootstrapResult {
86
+ loadedResourceIds: string[];
87
+ loadedAgentsFiles: Array<{ path: string; sizeBytes: number }>;
88
+ loadedSkillFiles: Array<{ name: string; path: string }>;
89
+ resolvedModel: { providerId: string; modelId: string };
90
+ diagnostics: string[];
91
+ }
92
+
93
+ export interface PiTreeHandleFactory {
94
+ prepareManagedBootstrap(opts: PiManagedBootstrapOptions): Promise<PiManagedBootstrapResult>;
95
+ inspectPrimaryTree(opts: PiTreePlanningOptions): Promise<PiTreePlanningSnapshot>;
96
+ createPrimaryTreeHandle(opts: PiTreeHandleOptions): Promise<PiTreeHandle>;
97
+ }
98
+
99
+ export interface PiTreePlanningOptions {
100
+ treeFile: string;
101
+ sessionCwd: string;
102
+ }
103
+
104
+ export interface PiTreePlanningSnapshot {
105
+ currentLeafId: string | null;
106
+ entries: readonly Pick<PiTreeEntry, "id" | "parentId">[];
107
+ }
108
+
109
+ /** Read persisted tree topology without creating a Pi session or mutating the tree file. */
110
+ export async function inspectPiTreeForPlanning(
111
+ input: PiTreePlanningOptions,
112
+ ): Promise<PiTreePlanningSnapshot> {
113
+ try {
114
+ await access(input.treeFile);
115
+ } catch (error) {
116
+ if (
117
+ typeof error === "object" &&
118
+ error !== null &&
119
+ "code" in error &&
120
+ (error as { code?: unknown }).code === "ENOENT"
121
+ ) {
122
+ return { currentLeafId: null, entries: [] };
123
+ }
124
+ throw error;
125
+ }
126
+
127
+ const { SessionManager } = await import("@earendil-works/pi-coding-agent");
128
+ const manager = SessionManager.open(
129
+ input.treeFile,
130
+ path.dirname(input.treeFile),
131
+ input.sessionCwd,
132
+ );
133
+ const entries: Array<Pick<PiTreeEntry, "id" | "parentId">> = [];
134
+ const visit = (nodes: readonly PiTreeNode[]) => {
135
+ for (const node of nodes) {
136
+ entries.push({ id: node.entry.id, parentId: node.entry.parentId });
137
+ visit(node.children);
138
+ }
139
+ };
140
+ visit(manager.getTree() as unknown as readonly PiTreeNode[]);
141
+ return {
142
+ currentLeafId: manager.getLeafId() ?? null,
143
+ entries,
144
+ };
145
+ }
146
+
147
+ interface MutableAgentSessionRuntime {
148
+ _customTools: ToolDefinition[];
149
+ _refreshToolRegistry(options?: {
150
+ activeToolNames?: string[];
151
+ includeAllExtensionTools?: boolean;
152
+ }): void;
153
+ }
154
+
155
+ interface SessionManagerWithCustomMessages {
156
+ appendCustomMessageEntry(
157
+ customType: string,
158
+ content: string,
159
+ display: boolean,
160
+ details?: unknown,
161
+ ): string;
162
+ }
163
+
164
+ interface SessionManagerWithCompaction {
165
+ appendCompaction(
166
+ summary: string,
167
+ firstKeptEntryId: string,
168
+ tokensBefore: number,
169
+ details?: unknown,
170
+ fromHook?: boolean,
171
+ ): string;
172
+ }
173
+
174
+ interface PiBeforeToolCallContext {
175
+ toolCall: { name: string };
176
+ }
177
+
178
+ interface PiAgentLoopConfig {
179
+ shouldStopAfterTurn?: (...args: unknown[]) => boolean | Promise<boolean>;
180
+ [key: string]: unknown;
181
+ }
182
+
183
+ interface PiCompletedTurnContext {
184
+ message?: {
185
+ content?: unknown;
186
+ stopReason?: unknown;
187
+ };
188
+ }
189
+
190
+ interface MutableAgentRuntimeHooks {
191
+ beforeToolCall?: (context: PiBeforeToolCallContext, signal: unknown) => unknown;
192
+ createLoopConfig?: (loopOptions?: unknown) => PiAgentLoopConfig;
193
+ }
194
+
195
+ function toIsoTimestamp(value: unknown): string {
196
+ if (typeof value === "number" && Number.isFinite(value)) {
197
+ return new Date(value).toISOString();
198
+ }
199
+ if (typeof value === "string" && value.trim() !== "") {
200
+ return value;
201
+ }
202
+ return new Date().toISOString();
203
+ }
204
+
205
+ function isObjectLike(value: unknown): value is Record<string, unknown> {
206
+ return typeof value === "object" && value !== null;
207
+ }
208
+
209
+ function toToolSchema(parameters: Record<string, unknown>): Record<string, unknown> {
210
+ if (
211
+ isObjectLike(parameters) &&
212
+ parameters.type === "object" &&
213
+ isObjectLike(parameters.properties)
214
+ ) {
215
+ return parameters;
216
+ }
217
+
218
+ const properties: Record<string, unknown> = {};
219
+ const required: string[] = [];
220
+ for (const [key, spec] of Object.entries(parameters)) {
221
+ if (isObjectLike(spec)) {
222
+ const {
223
+ required: isRequired,
224
+ requiredErrorCode: _requiredErrorCode,
225
+ invalidErrorCode: _invalidErrorCode,
226
+ minItemsErrorCode: _minItemsErrorCode,
227
+ minimumErrorCode: _minimumErrorCode,
228
+ ...jsonSchemaSpec
229
+ } = spec;
230
+ properties[key] = { ...jsonSchemaSpec };
231
+ if (isRequired === true) {
232
+ required.push(key);
233
+ }
234
+ } else {
235
+ properties[key] = { type: "string" };
236
+ }
237
+ }
238
+
239
+ return {
240
+ type: "object",
241
+ properties,
242
+ required,
243
+ additionalProperties: false,
244
+ };
245
+ }
246
+
247
+ const LEITWERK_TOOL_BOOTSTRAP: ToolDefinition = {
248
+ name: LEITWERK_TOOL_BOOTSTRAP_NAME,
249
+ label: LEITWERK_TOOL_BOOTSTRAP_NAME,
250
+ description: "Internal leitwerk bootstrap tool",
251
+ promptSnippet: `${LEITWERK_TOOL_BOOTSTRAP_NAME}: Internal leitwerk bootstrap tool`,
252
+ parameters: toToolSchema({}) as ToolDefinition["parameters"],
253
+ execute: async () => ({
254
+ content: [{ type: "text", text: "leitwerk bootstrap" }],
255
+ details: { ok: true },
256
+ }),
257
+ };
258
+
259
+ function stringifyToolResult(result: unknown): string {
260
+ if (typeof result === "string") {
261
+ return result;
262
+ }
263
+ if (result === undefined) {
264
+ return "ok";
265
+ }
266
+ try {
267
+ return JSON.stringify(result, null, 2);
268
+ } catch {
269
+ return String(result);
270
+ }
271
+ }
272
+
273
+ export const TERMINAL_ACKNOWLEDGEMENT_INSTRUCTION =
274
+ 'Outcome accepted successfully. Do not call any more tools. Reply only with "done".';
275
+
276
+ function toToolDefinition(
277
+ tool: PiCustomTool,
278
+ terminalAcknowledgement?: TerminalAcknowledgementRuntime | null,
279
+ suspendPromptGuards?: () => () => void,
280
+ ): ToolDefinition {
281
+ return {
282
+ name: tool.name,
283
+ label: tool.name,
284
+ description: tool.description,
285
+ promptSnippet: `${tool.name}: ${tool.description}`,
286
+ parameters: toToolSchema(tool.parameters) as ToolDefinition["parameters"],
287
+ ...(tool.executionMode ? { executionMode: tool.executionMode } : {}),
288
+ execute: async (toolCallId, args, signal) => {
289
+ const acknowledgementState = terminalAcknowledgement?.state();
290
+ const result = await tool.execute(args as Record<string, unknown>, {
291
+ toolCallId,
292
+ signal: signal ?? new AbortController().signal,
293
+ suspendPromptGuards,
294
+ });
295
+ return {
296
+ content: [
297
+ {
298
+ type: "text",
299
+ text:
300
+ terminalAcknowledgement?.onToolExecuted(acknowledgementState) ??
301
+ stringifyToolResult(result),
302
+ },
303
+ ],
304
+ details: result,
305
+ };
306
+ },
307
+ };
308
+ }
309
+
310
+ function getMutableSession(session: AgentSession): MutableAgentSessionRuntime {
311
+ const candidate = session as unknown as Partial<MutableAgentSessionRuntime>;
312
+ if (
313
+ !Array.isArray(candidate._customTools) ||
314
+ typeof candidate._refreshToolRegistry !== "function"
315
+ ) {
316
+ throw new Error(
317
+ "AgentSession does not expose the _customTools/_refreshToolRegistry hooks required for temporary tools",
318
+ );
319
+ }
320
+ return candidate as MutableAgentSessionRuntime;
321
+ }
322
+
323
+ function toTemporaryToolRegistrationError(error: unknown): Error {
324
+ return new Error(
325
+ "Pi SDK version incompatible: temporary tool registration unavailable",
326
+ error instanceof Error ? { cause: error } : undefined,
327
+ );
328
+ }
329
+
330
+ function validateRequestedActiveTools(
331
+ requestedToolNames: readonly string[],
332
+ availableToolNames: readonly string[],
333
+ ): void {
334
+ for (const toolName of requestedToolNames) {
335
+ if (!availableToolNames.includes(toolName)) {
336
+ throw new Error(
337
+ `Requested active Pi tool '${toolName}' is not available for this process. Available tools: ${availableToolNames.join(", ")}`,
338
+ );
339
+ }
340
+ }
341
+ }
342
+
343
+ function toPiRunDetails(input: {
344
+ loadedAgentsFiles: Array<{ path: string; content: string }>;
345
+ loadedSkills: Array<{ name: string; path: string }>;
346
+ availableToolNames: string[];
347
+ }): PiRunDetails {
348
+ return {
349
+ loadedAgentsFiles: input.loadedAgentsFiles.map((file) => ({
350
+ path: file.path,
351
+ sizeBytes: Buffer.byteLength(file.content, "utf8"),
352
+ })),
353
+ loadedSkills: input.loadedSkills.map((skill) => ({ name: skill.name, path: skill.path })),
354
+ availableToolNames: [...input.availableToolNames],
355
+ };
356
+ }
357
+
358
+ function updateAgentMessagesForCurrentLeaf(session: AgentSession): void {
359
+ const context = session.sessionManager.buildSessionContext();
360
+ session.agent.state.messages = context.messages;
361
+ }
362
+
363
+ function activeTurnId(state: { currentTurnId: string | null; turnSequence: number }): string {
364
+ return state.currentTurnId ?? `turn-${state.turnSequence}`;
365
+ }
366
+
367
+ function readNonEmptyString(value: unknown): string | null {
368
+ return typeof value === "string" && value.trim() !== "" ? value : null;
369
+ }
370
+
371
+ function readFiniteNumber(value: unknown): number | null {
372
+ if (typeof value === "number" && Number.isFinite(value)) {
373
+ return value;
374
+ }
375
+ if (typeof value === "string" && value.trim() !== "") {
376
+ const parsed = Number(value);
377
+ if (Number.isFinite(parsed)) {
378
+ return parsed;
379
+ }
380
+ }
381
+ return null;
382
+ }
383
+
384
+ function listRecordKeys(value: Record<string, unknown>): string[] {
385
+ return Object.keys(value).slice(0, 12);
386
+ }
387
+
388
+ function summarizeAgentMessages(messages: unknown): Record<string, unknown> {
389
+ if (!Array.isArray(messages)) {
390
+ return { messageCount: 0 };
391
+ }
392
+ const roles = Array.from(
393
+ new Set(
394
+ messages
395
+ .map((message) => (isObjectLike(message) ? readNonEmptyString(message.role) : null))
396
+ .filter((role): role is string => role !== null),
397
+ ),
398
+ ).slice(0, 8);
399
+ return {
400
+ messageCount: messages.length,
401
+ ...(roles.length > 0 ? { roles } : {}),
402
+ };
403
+ }
404
+
405
+ function readToolCallBlockFromPartial(
406
+ assistantMessageEvent: Record<string, unknown>,
407
+ ): Record<string, unknown> | null {
408
+ const contentIndex = readFiniteNumber(assistantMessageEvent.contentIndex);
409
+ if (contentIndex === null) {
410
+ return null;
411
+ }
412
+ const partial = isObjectLike(assistantMessageEvent.partial)
413
+ ? assistantMessageEvent.partial
414
+ : null;
415
+ const content = Array.isArray(partial?.content) ? partial.content : null;
416
+ const block = content?.[contentIndex];
417
+ return isObjectLike(block) && block.type === "toolCall" ? block : null;
418
+ }
419
+
420
+ function extractAssistantPromptError(entry: PiTreeEntry): Error | null {
421
+ const message = entry.message as
422
+ | Partial<{
423
+ role: string;
424
+ stopReason: string;
425
+ errorMessage: string;
426
+ provider: string;
427
+ model: string;
428
+ }>
429
+ | undefined;
430
+ if (message?.role !== "assistant" || message.stopReason !== "error") {
431
+ return null;
432
+ }
433
+ const errorMessage =
434
+ readNonEmptyString(message.errorMessage) ?? "Pi assistant turn stopped with error";
435
+ const error = new Error(errorMessage) as Error & {
436
+ provider?: string;
437
+ model?: string;
438
+ stopReason?: string;
439
+ };
440
+ error.stopReason = "error";
441
+ const provider = readNonEmptyString(message.provider);
442
+ const model = readNonEmptyString(message.model);
443
+ if (provider) {
444
+ error.provider = provider;
445
+ }
446
+ if (model) {
447
+ error.model = model;
448
+ }
449
+ return error;
450
+ }
451
+
452
+ function isAssistantEntry(entry: PiTreeEntry): boolean {
453
+ const message = entry.message as Partial<{ role: string }> | undefined;
454
+ return message?.role === "assistant";
455
+ }
456
+
457
+ function extractTextFromMessageContent(content: unknown): string {
458
+ if (typeof content === "string") {
459
+ return content;
460
+ }
461
+ if (!Array.isArray(content)) {
462
+ return "";
463
+ }
464
+ return content
465
+ .map((block) => {
466
+ if (!isObjectLike(block) || block.type !== "text") {
467
+ return "";
468
+ }
469
+ return typeof block.text === "string" ? block.text : "";
470
+ })
471
+ .filter((text) => text.trim() !== "")
472
+ .join("\n\n");
473
+ }
474
+
475
+ function extractAssistantMarkdown(entry: PiTreeEntry | undefined): string | null {
476
+ if (!entry || !isAssistantEntry(entry)) {
477
+ return null;
478
+ }
479
+ const text = extractTextFromMessageContent(entry.message?.content).trim();
480
+ return text.length > 0 ? text : null;
481
+ }
482
+
483
+ function findFinalAssistantMarkdown(entries: readonly PiTreeEntry[]): string | null {
484
+ for (let index = entries.length - 1; index >= 0; index -= 1) {
485
+ const markdown = extractAssistantMarkdown(entries[index]);
486
+ if (markdown) {
487
+ return markdown;
488
+ }
489
+ }
490
+ return null;
491
+ }
492
+
493
+ function findFinalAssistantPromptError(entries: readonly PiTreeEntry[]): Error | null {
494
+ for (let index = entries.length - 1; index >= 0; index -= 1) {
495
+ const entry = entries[index];
496
+ if (!isAssistantEntry(entry)) {
497
+ continue;
498
+ }
499
+ return extractAssistantPromptError(entry);
500
+ }
501
+ return null;
502
+ }
503
+
504
+ const TERMINAL_ACKNOWLEDGEMENT_CLEANUP_TIMEOUT_MS = 1_000;
505
+
506
+ type TerminalAcknowledgementRunOutcome = { kind: "completed" } | { kind: "failed"; error: unknown };
507
+
508
+ class TerminalAcknowledgementRuntime {
509
+ private acknowledgementTurnStarted = false;
510
+ private timeout: ReturnType<typeof setTimeout> | null = null;
511
+ private resolveTimeout!: () => void;
512
+ private readonly timeoutReached = new Promise<void>((resolve) => {
513
+ this.resolveTimeout = resolve;
514
+ });
515
+
516
+ constructor(
517
+ private readonly control: NonNullable<PiPromptOptions["terminalAcknowledgement"]>,
518
+ private readonly abort: () => Promise<void>,
519
+ private readonly getLeafEntry: () => PiTreeEntry | undefined,
520
+ ) {}
521
+
522
+ state(): string {
523
+ return this.control.state();
524
+ }
525
+
526
+ onToolExecuted(stateBeforeExecution: string | undefined): string | undefined {
527
+ if (stateBeforeExecution !== "open" || this.control.state() !== "outcome_accepted") {
528
+ return undefined;
529
+ }
530
+ if (this.timeout === null) {
531
+ this.timeout = setTimeout(() => {
532
+ this.control.markFailed(
533
+ `Terminal acknowledgement exceeded ${this.control.timeoutMs}ms and was ignored`,
534
+ );
535
+ this.resolveTimeout();
536
+ }, this.control.timeoutMs);
537
+ }
538
+ return TERMINAL_ACKNOWLEDGEMENT_INSTRUCTION;
539
+ }
540
+
541
+ onBeforeToolCall(toolName: string): void {
542
+ if (!this.acknowledgementTurnStarted || this.control.state() !== "outcome_accepted") {
543
+ return;
544
+ }
545
+ this.control.markFailed(
546
+ `Terminal acknowledgement attempted blocked tool '${toolName}' and was ignored`,
547
+ );
548
+ this.clearTimeout();
549
+ }
550
+
551
+ onTurnCompleted(args: readonly unknown[]): boolean | null {
552
+ const state = this.control.state();
553
+ if (!this.acknowledgementTurnStarted) {
554
+ if (state !== "outcome_accepted") return null;
555
+ this.acknowledgementTurnStarted = true;
556
+ return false;
557
+ }
558
+ if (state === "outcome_accepted") {
559
+ const context = isObjectLike(args[0]) ? (args[0] as PiCompletedTurnContext) : null;
560
+ this.settleFromMessage(context?.message);
561
+ }
562
+ return true;
563
+ }
564
+
565
+ async run(run: () => Promise<void>): Promise<void> {
566
+ const runOutcome = run().then<
567
+ TerminalAcknowledgementRunOutcome,
568
+ TerminalAcknowledgementRunOutcome
569
+ >(
570
+ () => ({ kind: "completed" }),
571
+ (error: unknown) => ({ kind: "failed", error }),
572
+ );
573
+ const firstOutcome = await Promise.race([
574
+ runOutcome,
575
+ this.timeoutReached.then(() => ({ kind: "timeout" }) as const),
576
+ ]);
577
+ if (firstOutcome.kind === "timeout") {
578
+ const finalRunOutcome = await this.abortAndAwaitCleanup(runOutcome);
579
+ if (this.control.isOperatorAbortRequested() && finalRunOutcome.kind === "failed") {
580
+ throw finalRunOutcome.error;
581
+ }
582
+ return;
583
+ }
584
+ if (firstOutcome.kind === "completed") {
585
+ this.settleAfterRun();
586
+ return;
587
+ }
588
+ if (!this.canIgnoreRunError()) {
589
+ throw firstOutcome.error;
590
+ }
591
+ }
592
+
593
+ dispose(): void {
594
+ this.clearTimeout();
595
+ }
596
+
597
+ private settleAfterRun(): void {
598
+ if (
599
+ this.control.state() !== "outcome_accepted" ||
600
+ !this.acknowledgementTurnStarted ||
601
+ this.control.isOperatorAbortRequested()
602
+ ) {
603
+ return;
604
+ }
605
+ this.settleFromMessage(this.getLeafEntry()?.message);
606
+ }
607
+
608
+ private canIgnoreRunError(): boolean {
609
+ if (this.control.isOperatorAbortRequested()) return false;
610
+ if (!this.acknowledgementTurnStarted || this.control.state() !== "outcome_accepted") {
611
+ return false;
612
+ }
613
+ const leaf = this.getLeafEntry();
614
+ if (!leaf || !extractAssistantPromptError(leaf)) return false;
615
+ this.settleFromMessage(leaf.message);
616
+ return true;
617
+ }
618
+
619
+ private async abortAndAwaitCleanup(
620
+ runOutcome: Promise<TerminalAcknowledgementRunOutcome>,
621
+ ): Promise<TerminalAcknowledgementRunOutcome> {
622
+ const abortOutcome = this.abort().then(
623
+ () => ({ kind: "completed" }) as const,
624
+ (error: unknown) => ({ kind: "failed", error }) as const,
625
+ );
626
+ let cleanupTimeout: ReturnType<typeof setTimeout> | null = null;
627
+ const cleanupTimedOut = new Promise<true>((resolve) => {
628
+ cleanupTimeout = setTimeout(() => resolve(true), TERMINAL_ACKNOWLEDGEMENT_CLEANUP_TIMEOUT_MS);
629
+ });
630
+ const cleanupOutcome = await Promise.race([
631
+ Promise.all([runOutcome, abortOutcome]).then(([finalRunOutcome, finalAbortOutcome]) => ({
632
+ finalRunOutcome,
633
+ finalAbortOutcome,
634
+ })),
635
+ cleanupTimedOut,
636
+ ]);
637
+ if (cleanupTimeout !== null) clearTimeout(cleanupTimeout);
638
+ if (cleanupOutcome === true) {
639
+ throw new Error(
640
+ `Timed-out terminal acknowledgement did not stop within ${TERMINAL_ACKNOWLEDGEMENT_CLEANUP_TIMEOUT_MS}ms`,
641
+ );
642
+ }
643
+ if (cleanupOutcome.finalAbortOutcome.kind === "failed") {
644
+ throw new Error("Failed to abort timed-out terminal acknowledgement", {
645
+ cause: cleanupOutcome.finalAbortOutcome.error,
646
+ });
647
+ }
648
+ return cleanupOutcome.finalRunOutcome;
649
+ }
650
+
651
+ private settleFromMessage(messageValue: unknown): void {
652
+ const message = isObjectLike(messageValue) ? messageValue : null;
653
+ const responseText = extractTextFromMessageContent(message?.content).trim();
654
+ const stopReason = readNonEmptyString(message?.stopReason);
655
+ if (responseText !== "" && stopReason !== "error" && stopReason !== "aborted") {
656
+ this.control.markSucceeded();
657
+ } else {
658
+ const reason = readNonEmptyString(message?.errorMessage) ?? stopReason ?? "no assistant text";
659
+ this.control.markFailed(`Terminal acknowledgement failed and was ignored: ${reason}`);
660
+ }
661
+ this.clearTimeout();
662
+ }
663
+
664
+ private clearTimeout(): void {
665
+ if (this.timeout === null) return;
666
+ clearTimeout(this.timeout);
667
+ this.timeout = null;
668
+ }
669
+ }
670
+
671
+ function describeRetryStart(input: {
672
+ attempt: number;
673
+ maxAttempts: number;
674
+ delayMs: number;
675
+ errorMessage: string;
676
+ }): string {
677
+ const retryLabel =
678
+ input.attempt > 0 && input.maxAttempts > 0
679
+ ? `Retry ${input.attempt}/${input.maxAttempts} scheduled`
680
+ : input.attempt > 0
681
+ ? `Retry ${input.attempt} scheduled`
682
+ : "Retry scheduled";
683
+ const delayLabel = input.delayMs > 0 ? ` in ${input.delayMs}ms` : "";
684
+ return input.errorMessage
685
+ ? `${retryLabel}${delayLabel}: ${input.errorMessage}`
686
+ : `${retryLabel}${delayLabel}`;
687
+ }
688
+
689
+ function describeRetryEnd(input: {
690
+ success: boolean;
691
+ attempt: number;
692
+ finalError: string | null;
693
+ }): string {
694
+ const attemptLabel = input.attempt === 1 ? "1 retry" : `${input.attempt} retries`;
695
+ if (input.success) {
696
+ return input.attempt > 0
697
+ ? `Retry sequence succeeded after ${attemptLabel}`
698
+ : "Retry sequence succeeded";
699
+ }
700
+ return input.finalError
701
+ ? `Retry sequence failed after ${attemptLabel}: ${input.finalError}`
702
+ : `Retry sequence failed after ${attemptLabel}`;
703
+ }
704
+
705
+ export interface AgentSessionEventTranslation {
706
+ piEvents: PiEvent[];
707
+ diagnostics: PiSessionDiagnostic[];
708
+ }
709
+
710
+ const INACTIVITY_RESET_EVENT_TYPES = new Set<PiEventType>([
711
+ "turn.start",
712
+ "stream.delta",
713
+ "tool.call",
714
+ "tool.update",
715
+ "tool.result",
716
+ "toolcall.start",
717
+ "toolcall.delta",
718
+ "toolcall.end",
719
+ "compaction.start",
720
+ "compaction.end",
721
+ "error",
722
+ "retry.start",
723
+ "retry.end",
724
+ ]);
725
+
726
+ export function doesPiEventResetInactivity(event: PiEvent): boolean {
727
+ return INACTIVITY_RESET_EVENT_TYPES.has(event.type);
728
+ }
729
+
730
+ function omitType(value: Record<string, unknown>): Record<string, unknown> {
731
+ const { type: _type, ...rest } = value;
732
+ return rest;
733
+ }
734
+
735
+ function normalizePiEventData(value: Record<string, unknown>): Record<string, unknown> {
736
+ const raw = omitType(value);
737
+ const normalized: Record<string, unknown> = {};
738
+ const partialToolCall = readToolCallBlockFromPartial(raw);
739
+ const rawToolCall = isObjectLike(raw.toolCall)
740
+ ? raw.toolCall
741
+ : isObjectLike(partialToolCall)
742
+ ? partialToolCall
743
+ : null;
744
+ const toolCallId = readNonEmptyString(raw.toolCallId) ?? readNonEmptyString(rawToolCall?.id);
745
+ const name =
746
+ readNonEmptyString(raw.name) ??
747
+ readNonEmptyString(raw.toolName) ??
748
+ readNonEmptyString(rawToolCall?.name);
749
+ if (toolCallId) {
750
+ normalized.toolCallId = toolCallId;
751
+ }
752
+ if (name) {
753
+ normalized.name = name;
754
+ }
755
+ if ("args" in raw && !("arguments" in raw)) {
756
+ normalized.arguments = raw.args;
757
+ } else if ("arguments" in raw) {
758
+ normalized.arguments = raw.arguments;
759
+ } else if (rawToolCall && "arguments" in rawToolCall) {
760
+ normalized.arguments = rawToolCall.arguments;
761
+ }
762
+ if (rawToolCall && "thoughtSignature" in rawToolCall) {
763
+ normalized.thoughtSignature = rawToolCall.thoughtSignature;
764
+ }
765
+ if ("delta" in raw) {
766
+ normalized.delta = raw.delta;
767
+ }
768
+ if ("partialResult" in raw) {
769
+ normalized.partialResult = raw.partialResult;
770
+ }
771
+ if ("result" in raw) {
772
+ normalized.result = raw.result;
773
+ }
774
+ if ("isError" in raw) {
775
+ normalized.isError = raw.isError;
776
+ }
777
+ for (const [key, entryValue] of Object.entries(raw)) {
778
+ if (key === "toolName" || key === "args" || key === "toolCall" || key === "partial") {
779
+ continue;
780
+ }
781
+ if (key in normalized) {
782
+ continue;
783
+ }
784
+ normalized[key] = entryValue;
785
+ }
786
+ return normalized;
787
+ }
788
+
789
+ function readSessionEventTimestamp(event: unknown): string {
790
+ const eventRecord = isObjectLike(event) ? event : {};
791
+ const messageTimestamp = isObjectLike(eventRecord.message)
792
+ ? (eventRecord.message as { timestamp?: unknown }).timestamp
793
+ : undefined;
794
+ return toIsoTimestamp(messageTimestamp ?? eventRecord.timestamp);
795
+ }
796
+
797
+ function buildSessionDiagnostic(input: {
798
+ level: PiSessionDiagnostic["level"];
799
+ code: string;
800
+ message: string;
801
+ timestamp: string;
802
+ turnId?: string;
803
+ details?: Record<string, unknown>;
804
+ }): PiSessionDiagnostic {
805
+ return {
806
+ level: input.level,
807
+ code: input.code,
808
+ message: input.message,
809
+ timestamp: input.timestamp,
810
+ ...(input.turnId ? { turnId: input.turnId } : {}),
811
+ ...(input.details ? { details: input.details } : {}),
812
+ };
813
+ }
814
+
815
+ function summarizeSessionGlobalDiagnosticDetails(
816
+ event: AgentSessionEvent,
817
+ ): Record<string, unknown> {
818
+ const raw = omitType(event as unknown as Record<string, unknown>);
819
+ const base = {
820
+ category: "session_global",
821
+ eventType: event.type,
822
+ };
823
+ if (event.type === "queue_update") {
824
+ return {
825
+ ...base,
826
+ steeringCount: Array.isArray(event.steering) ? event.steering.length : 0,
827
+ followUpCount: Array.isArray(event.followUp) ? event.followUp.length : 0,
828
+ };
829
+ }
830
+ if (event.type === "agent_end") {
831
+ return {
832
+ ...base,
833
+ ...summarizeAgentMessages((event as { messages?: unknown }).messages),
834
+ };
835
+ }
836
+ const keys = listRecordKeys(raw);
837
+ return keys.length > 0 ? { ...base, keys } : base;
838
+ }
839
+
840
+ function buildKnownSessionGlobalDiagnostic(
841
+ event: AgentSessionEvent,
842
+ code: string,
843
+ message: string,
844
+ ): PiSessionDiagnostic {
845
+ return buildSessionDiagnostic({
846
+ level: "info",
847
+ code,
848
+ message,
849
+ timestamp: readSessionEventTimestamp(event),
850
+ details: summarizeSessionGlobalDiagnosticDetails(event),
851
+ });
852
+ }
853
+
854
+ function buildUnknownSessionEventDiagnostic(
855
+ event: AgentSessionEvent,
856
+ state: { currentTurnId: string | null },
857
+ ): PiSessionDiagnostic {
858
+ const eventType =
859
+ readNonEmptyString((event as unknown as Record<string, unknown>).type) ?? "unknown";
860
+ const raw = omitType(event as unknown as Record<string, unknown>);
861
+ const keys = listRecordKeys(raw);
862
+ return buildSessionDiagnostic({
863
+ level: "warn",
864
+ code: "pi.session.event_unknown",
865
+ message: `Unhandled Pi session event '${eventType}'`,
866
+ timestamp: readSessionEventTimestamp(event),
867
+ ...(state.currentTurnId ? { turnId: state.currentTurnId } : {}),
868
+ details: {
869
+ kind: "session.event.unknown",
870
+ scope: "agent_session_event",
871
+ eventType,
872
+ ...(keys.length > 0 ? { keys } : {}),
873
+ },
874
+ });
875
+ }
876
+
877
+ function buildUnknownAssistantEventDiagnostic(input: {
878
+ event: AgentSessionEvent;
879
+ assistantMessageEvent: Record<string, unknown>;
880
+ turnId: string;
881
+ timestamp: string;
882
+ }): PiSessionDiagnostic {
883
+ const assistantEventType = readNonEmptyString(input.assistantMessageEvent.type) ?? "unknown";
884
+ const raw = omitType(input.assistantMessageEvent);
885
+ const keys = listRecordKeys(raw);
886
+ const contentIndex = readFiniteNumber(input.assistantMessageEvent.contentIndex);
887
+ return buildSessionDiagnostic({
888
+ level: "warn",
889
+ code: "pi.session.event_unknown",
890
+ message: `Unhandled Pi assistant message_update event '${assistantEventType}'`,
891
+ timestamp: input.timestamp,
892
+ turnId: input.turnId,
893
+ details: {
894
+ kind: "session.event.unknown",
895
+ scope: "assistant_message_event",
896
+ eventType: input.event.type,
897
+ assistantEventType,
898
+ ...(contentIndex !== null ? { contentIndex } : {}),
899
+ ...(keys.length > 0 ? { keys } : {}),
900
+ },
901
+ });
902
+ }
903
+
904
+ export function translateAgentSessionEventEnvelope(
905
+ event: AgentSessionEvent,
906
+ state: { currentTurnId: string | null; turnSequence: number },
907
+ ): AgentSessionEventTranslation {
908
+ const runtimeEventType = (event as unknown as { type?: unknown }).type;
909
+ if (runtimeEventType === "session_info_changed") {
910
+ return {
911
+ piEvents: [],
912
+ diagnostics: [
913
+ buildKnownSessionGlobalDiagnostic(
914
+ event,
915
+ "pi.session_info_changed",
916
+ "Pi session info changed",
917
+ ),
918
+ ],
919
+ };
920
+ }
921
+ switch (event.type) {
922
+ case "turn_start": {
923
+ const rawTurnIndex = (event as { turnIndex?: unknown }).turnIndex;
924
+ const turnIndex =
925
+ typeof rawTurnIndex === "number" && Number.isFinite(rawTurnIndex)
926
+ ? rawTurnIndex
927
+ : state.turnSequence + 1;
928
+ state.turnSequence = turnIndex;
929
+ const turnId = `turn-${turnIndex}`;
930
+ state.currentTurnId = turnId;
931
+ return {
932
+ piEvents: [
933
+ {
934
+ type: "turn.start",
935
+ turnId,
936
+ data: {},
937
+ timestamp: toIsoTimestamp((event as { timestamp?: unknown }).timestamp),
938
+ },
939
+ ],
940
+ diagnostics: [],
941
+ };
942
+ }
943
+ case "turn_end": {
944
+ const turnId = state.currentTurnId ?? `turn-${state.turnSequence}`;
945
+ state.currentTurnId = null;
946
+ return {
947
+ piEvents: [
948
+ {
949
+ type: "turn.end",
950
+ turnId,
951
+ data: {},
952
+ timestamp: toIsoTimestamp((event.message as { timestamp?: unknown }).timestamp),
953
+ },
954
+ ],
955
+ diagnostics: [],
956
+ };
957
+ }
958
+ case "message_start":
959
+ return { piEvents: [], diagnostics: [] };
960
+ case "message_update": {
961
+ const turnId = state.currentTurnId;
962
+ if (!turnId) {
963
+ return { piEvents: [], diagnostics: [] };
964
+ }
965
+ const assistantMessageEvent = event.assistantMessageEvent as unknown as Record<
966
+ string,
967
+ unknown
968
+ >;
969
+ const timestamp = toIsoTimestamp((event.message as { timestamp?: unknown }).timestamp);
970
+ switch (event.assistantMessageEvent.type) {
971
+ case "text_delta":
972
+ return {
973
+ piEvents: [
974
+ {
975
+ type: "stream.delta",
976
+ turnId,
977
+ data: {
978
+ text: event.assistantMessageEvent.delta,
979
+ streamType: "text",
980
+ },
981
+ timestamp,
982
+ },
983
+ ],
984
+ diagnostics: [],
985
+ };
986
+ case "thinking_delta":
987
+ return {
988
+ piEvents: [
989
+ {
990
+ type: "stream.delta",
991
+ turnId,
992
+ data: {
993
+ text: event.assistantMessageEvent.delta,
994
+ streamType: "thinking",
995
+ },
996
+ timestamp,
997
+ },
998
+ ],
999
+ diagnostics: [],
1000
+ };
1001
+ case "toolcall_start":
1002
+ return {
1003
+ piEvents: [
1004
+ {
1005
+ type: "toolcall.start",
1006
+ turnId,
1007
+ data: normalizePiEventData(assistantMessageEvent),
1008
+ timestamp,
1009
+ },
1010
+ ],
1011
+ diagnostics: [],
1012
+ };
1013
+ case "toolcall_delta":
1014
+ return {
1015
+ piEvents: [
1016
+ {
1017
+ type: "toolcall.delta",
1018
+ turnId,
1019
+ data: normalizePiEventData(assistantMessageEvent),
1020
+ timestamp,
1021
+ },
1022
+ ],
1023
+ diagnostics: [],
1024
+ };
1025
+ case "toolcall_end":
1026
+ return {
1027
+ piEvents: [
1028
+ {
1029
+ type: "toolcall.end",
1030
+ turnId,
1031
+ data: normalizePiEventData(assistantMessageEvent),
1032
+ timestamp,
1033
+ },
1034
+ ],
1035
+ diagnostics: [],
1036
+ };
1037
+ case "start":
1038
+ case "done":
1039
+ case "error":
1040
+ case "text_start":
1041
+ case "text_end":
1042
+ case "thinking_start":
1043
+ case "thinking_end":
1044
+ return { piEvents: [], diagnostics: [] };
1045
+ default:
1046
+ return {
1047
+ piEvents: [],
1048
+ diagnostics: [
1049
+ buildUnknownAssistantEventDiagnostic({
1050
+ event,
1051
+ assistantMessageEvent,
1052
+ turnId,
1053
+ timestamp,
1054
+ }),
1055
+ ],
1056
+ };
1057
+ }
1058
+ }
1059
+ case "message_end": {
1060
+ const assistantMessage = event.message as Partial<{
1061
+ role: string;
1062
+ stopReason: string;
1063
+ errorMessage: string;
1064
+ provider: string;
1065
+ model: string;
1066
+ timestamp: unknown;
1067
+ usage: {
1068
+ input: number;
1069
+ output: number;
1070
+ reasoning?: number;
1071
+ cacheRead: number;
1072
+ cacheWrite: number;
1073
+ totalTokens: number;
1074
+ cost: {
1075
+ input: number;
1076
+ output: number;
1077
+ cacheRead: number;
1078
+ cacheWrite: number;
1079
+ total: number;
1080
+ };
1081
+ };
1082
+ }>;
1083
+ const timestamp = toIsoTimestamp(assistantMessage.timestamp);
1084
+ const piEvents: PiEvent[] = [];
1085
+ if (assistantMessage.role === "assistant" && assistantMessage.usage) {
1086
+ const usage = assistantMessage.usage;
1087
+ const cacheHitRate =
1088
+ usage.cacheRead + usage.input > 0 ? usage.cacheRead / (usage.cacheRead + usage.input) : 0;
1089
+ piEvents.push({
1090
+ type: "usage",
1091
+ turnId: activeTurnId(state),
1092
+ data: {
1093
+ input: usage.input,
1094
+ output: usage.output,
1095
+ ...(usage.reasoning !== undefined ? { reasoning: usage.reasoning } : {}),
1096
+ cacheRead: usage.cacheRead,
1097
+ cacheWrite: usage.cacheWrite,
1098
+ totalTokens: usage.totalTokens,
1099
+ cost: usage.cost,
1100
+ cacheHitRate,
1101
+ },
1102
+ timestamp,
1103
+ });
1104
+ }
1105
+ const errorMessage = readNonEmptyString(assistantMessage.errorMessage);
1106
+ if (
1107
+ assistantMessage.role === "assistant" &&
1108
+ assistantMessage.stopReason === "error" &&
1109
+ errorMessage
1110
+ ) {
1111
+ piEvents.push({
1112
+ type: "error",
1113
+ turnId: activeTurnId(state),
1114
+ data: {
1115
+ message: errorMessage,
1116
+ errorMessage,
1117
+ stopReason: assistantMessage.stopReason,
1118
+ source: "assistant",
1119
+ ...(readNonEmptyString(assistantMessage.provider)
1120
+ ? { provider: assistantMessage.provider }
1121
+ : {}),
1122
+ ...(readNonEmptyString(assistantMessage.model)
1123
+ ? { model: assistantMessage.model }
1124
+ : {}),
1125
+ },
1126
+ timestamp,
1127
+ });
1128
+ }
1129
+ return { piEvents, diagnostics: [] };
1130
+ }
1131
+ case "auto_retry_start":
1132
+ return {
1133
+ piEvents: [
1134
+ {
1135
+ type: "retry.start",
1136
+ turnId: activeTurnId(state),
1137
+ data: {
1138
+ attempt: event.attempt,
1139
+ maxAttempts: event.maxAttempts,
1140
+ delayMs: event.delayMs,
1141
+ errorMessage: event.errorMessage,
1142
+ message: describeRetryStart({
1143
+ attempt: event.attempt,
1144
+ maxAttempts: event.maxAttempts,
1145
+ delayMs: event.delayMs,
1146
+ errorMessage: event.errorMessage,
1147
+ }),
1148
+ },
1149
+ timestamp: new Date().toISOString(),
1150
+ },
1151
+ ],
1152
+ diagnostics: [],
1153
+ };
1154
+ case "auto_retry_end": {
1155
+ const finalError = readNonEmptyString(event.finalError);
1156
+ return {
1157
+ piEvents: [
1158
+ {
1159
+ type: "retry.end",
1160
+ turnId: activeTurnId(state),
1161
+ data: {
1162
+ success: event.success,
1163
+ attempt: event.attempt,
1164
+ ...(finalError ? { finalError } : {}),
1165
+ message: describeRetryEnd({
1166
+ success: event.success,
1167
+ attempt: event.attempt,
1168
+ finalError,
1169
+ }),
1170
+ },
1171
+ timestamp: new Date().toISOString(),
1172
+ },
1173
+ ],
1174
+ diagnostics: [],
1175
+ };
1176
+ }
1177
+ case "tool_execution_start":
1178
+ return {
1179
+ piEvents: [
1180
+ {
1181
+ type: "tool.call",
1182
+ turnId: state.currentTurnId ?? `turn-tool-${event.toolCallId}`,
1183
+ data: {
1184
+ toolCallId: event.toolCallId,
1185
+ name: event.toolName,
1186
+ arguments: event.args,
1187
+ },
1188
+ timestamp: new Date().toISOString(),
1189
+ },
1190
+ ],
1191
+ diagnostics: [],
1192
+ };
1193
+ case "tool_execution_update":
1194
+ return {
1195
+ piEvents: [
1196
+ {
1197
+ type: "tool.update",
1198
+ turnId: state.currentTurnId ?? `turn-tool-${event.toolCallId}`,
1199
+ data: normalizePiEventData(event as unknown as Record<string, unknown>),
1200
+ timestamp: readSessionEventTimestamp(event),
1201
+ },
1202
+ ],
1203
+ diagnostics: [],
1204
+ };
1205
+ case "tool_execution_end": {
1206
+ const turnId = state.currentTurnId ?? `turn-tool-${event.toolCallId}`;
1207
+ const timestamp = new Date().toISOString();
1208
+ const toolResultEvent: PiEvent = {
1209
+ type: "tool.result",
1210
+ turnId,
1211
+ data: {
1212
+ toolCallId: event.toolCallId,
1213
+ name: event.toolName,
1214
+ result: event.result,
1215
+ isError: event.isError,
1216
+ },
1217
+ timestamp,
1218
+ };
1219
+ if (!event.isError) {
1220
+ return { piEvents: [toolResultEvent], diagnostics: [] };
1221
+ }
1222
+ return {
1223
+ piEvents: [
1224
+ toolResultEvent,
1225
+ {
1226
+ type: "error",
1227
+ turnId,
1228
+ data: {
1229
+ message:
1230
+ typeof event.result === "string" ? event.result : stringifyToolResult(event.result),
1231
+ errorMessage:
1232
+ typeof event.result === "string" ? event.result : stringifyToolResult(event.result),
1233
+ toolName: event.toolName,
1234
+ source: "tool",
1235
+ },
1236
+ timestamp,
1237
+ },
1238
+ ],
1239
+ diagnostics: [],
1240
+ };
1241
+ }
1242
+ case "compaction_start":
1243
+ return {
1244
+ piEvents: [
1245
+ {
1246
+ type: "compaction.start",
1247
+ turnId: activeTurnId(state),
1248
+ data: normalizePiEventData(event as unknown as Record<string, unknown>),
1249
+ timestamp: readSessionEventTimestamp(event),
1250
+ },
1251
+ ],
1252
+ diagnostics: [],
1253
+ };
1254
+ case "compaction_end":
1255
+ return {
1256
+ piEvents: [
1257
+ {
1258
+ type: "compaction.end",
1259
+ turnId: activeTurnId(state),
1260
+ data: normalizePiEventData(event as unknown as Record<string, unknown>),
1261
+ timestamp: readSessionEventTimestamp(event),
1262
+ },
1263
+ ],
1264
+ diagnostics: [],
1265
+ };
1266
+ case "agent_start":
1267
+ return {
1268
+ piEvents: [],
1269
+ diagnostics: [
1270
+ buildKnownSessionGlobalDiagnostic(event, "pi.agent_start", "Pi agent run started"),
1271
+ ],
1272
+ };
1273
+ case "agent_end":
1274
+ return {
1275
+ piEvents: [],
1276
+ diagnostics: [
1277
+ buildKnownSessionGlobalDiagnostic(event, "pi.agent_end", "Pi agent run ended"),
1278
+ ],
1279
+ };
1280
+ case "agent_settled":
1281
+ return {
1282
+ piEvents: [],
1283
+ diagnostics: [
1284
+ buildKnownSessionGlobalDiagnostic(event, "pi.agent_settled", "Pi agent run settled"),
1285
+ ],
1286
+ };
1287
+ case "queue_update":
1288
+ return {
1289
+ piEvents: [],
1290
+ diagnostics: [
1291
+ buildKnownSessionGlobalDiagnostic(event, "pi.queue_update", "Pi session queue updated"),
1292
+ ],
1293
+ };
1294
+ default:
1295
+ return {
1296
+ piEvents: [],
1297
+ diagnostics: [buildUnknownSessionEventDiagnostic(event, state)],
1298
+ };
1299
+ }
1300
+ }
1301
+
1302
+ export class SdkPiTreeHandle implements PiTreeHandle {
1303
+ readonly sessionId: string;
1304
+ readonly treeFile: string;
1305
+ readonly isResumed: boolean;
1306
+
1307
+ private readonly eventState = { currentTurnId: null as string | null, turnSequence: 0 };
1308
+ private readonly eventHandlers = new Set<PiEventHandler>();
1309
+ private readonly diagnosticHandlers = new Set<PiSessionDiagnosticHandler>();
1310
+ private sessionUnsubscribe: (() => void) | null = null;
1311
+ private continuationRetryAbortController: AbortController | null = null;
1312
+ private readonly availableToolNames: string[];
1313
+ private readonly runDetails: PiRunDetails;
1314
+
1315
+ constructor(
1316
+ private readonly session: AgentSession,
1317
+ options: {
1318
+ treeFile: string;
1319
+ isResumed: boolean;
1320
+ availableToolNames: string[];
1321
+ runDetails: PiRunDetails;
1322
+ },
1323
+ ) {
1324
+ this.sessionId = session.sessionId;
1325
+ this.treeFile = options.treeFile;
1326
+ this.isResumed = options.isResumed;
1327
+ this.availableToolNames = [...options.availableToolNames];
1328
+ this.runDetails = {
1329
+ loadedAgentsFiles: options.runDetails.loadedAgentsFiles.map((file) => ({ ...file })),
1330
+ loadedSkills: options.runDetails.loadedSkills.map((skill) => ({ ...skill })),
1331
+ availableToolNames: [...options.runDetails.availableToolNames],
1332
+ };
1333
+ }
1334
+
1335
+ getRunDetails(): PiRunDetails {
1336
+ return {
1337
+ loadedAgentsFiles: this.runDetails.loadedAgentsFiles.map((file) => ({ ...file })),
1338
+ loadedSkills: this.runDetails.loadedSkills.map((skill) => ({ ...skill })),
1339
+ availableToolNames: [...this.runDetails.availableToolNames],
1340
+ };
1341
+ }
1342
+
1343
+ getLeafId(): string | null {
1344
+ return this.session.sessionManager.getLeafId();
1345
+ }
1346
+
1347
+ getEntry(id: string): PiTreeEntry | undefined {
1348
+ return this.session.sessionManager.getEntry(id) as PiTreeEntry | undefined;
1349
+ }
1350
+
1351
+ getBranch(fromId?: string): PiTreeEntry[] {
1352
+ return this.session.sessionManager.getBranch(fromId) as PiTreeEntry[];
1353
+ }
1354
+
1355
+ getChildren(parentId: string): PiTreeEntry[] {
1356
+ return this.session.sessionManager.getChildren(parentId) as PiTreeEntry[];
1357
+ }
1358
+
1359
+ getTree(): PiTreeNode[] {
1360
+ return this.session.sessionManager.getTree() as unknown as PiTreeNode[];
1361
+ }
1362
+
1363
+ async branch(entryId: string): Promise<void> {
1364
+ this.session.sessionManager.branch(entryId);
1365
+ updateAgentMessagesForCurrentLeaf(this.session);
1366
+ }
1367
+
1368
+ async branchFromRoot(): Promise<void> {
1369
+ this.session.sessionManager.resetLeaf();
1370
+ updateAgentMessagesForCurrentLeaf(this.session);
1371
+ }
1372
+
1373
+ async resetLeaf(): Promise<void> {
1374
+ await this.branchFromRoot();
1375
+ }
1376
+
1377
+ async compact(customInstructions?: string, details?: unknown): Promise<unknown> {
1378
+ if (details === undefined) {
1379
+ const result = await this.session.compact(customInstructions);
1380
+ updateAgentMessagesForCurrentLeaf(this.session);
1381
+ return result;
1382
+ }
1383
+
1384
+ const sessionManager = this.session.sessionManager as unknown as SessionManagerWithCompaction;
1385
+ if (typeof sessionManager.appendCompaction !== "function") {
1386
+ throw new Error("Pi SDK version incompatible: compaction detail insertion unavailable");
1387
+ }
1388
+
1389
+ const appendCompaction = sessionManager.appendCompaction;
1390
+ let appendCount = 0;
1391
+ sessionManager.appendCompaction = (
1392
+ summary,
1393
+ firstKeptEntryId,
1394
+ tokensBefore,
1395
+ _originalDetails,
1396
+ fromHook,
1397
+ ) => {
1398
+ appendCount += 1;
1399
+ return appendCompaction.call(
1400
+ sessionManager,
1401
+ summary,
1402
+ firstKeptEntryId,
1403
+ tokensBefore,
1404
+ details,
1405
+ fromHook,
1406
+ );
1407
+ };
1408
+
1409
+ try {
1410
+ const result = await this.session.compact(customInstructions);
1411
+ if (appendCount !== 1) {
1412
+ throw new Error(
1413
+ `Pi SDK compaction detail insertion expected one append, received ${appendCount}`,
1414
+ );
1415
+ }
1416
+ updateAgentMessagesForCurrentLeaf(this.session);
1417
+ return result;
1418
+ } finally {
1419
+ sessionManager.appendCompaction = appendCompaction;
1420
+ }
1421
+ }
1422
+
1423
+ private async withToolConfiguration(
1424
+ options: PiPromptOptions,
1425
+ run: () => Promise<void>,
1426
+ ): Promise<void> {
1427
+ const customTools = options.tools ?? [];
1428
+ const requestedActiveToolNames =
1429
+ options.activeTools !== undefined ? [...options.activeTools] : [];
1430
+ validateRequestedActiveTools(requestedActiveToolNames, this.availableToolNames);
1431
+ const previousActiveToolNames = this.session.getActiveToolNames();
1432
+ const needsRuntimeHooks =
1433
+ options.shouldBlockToolCall !== undefined || options.terminalAcknowledgement !== undefined;
1434
+ if (
1435
+ customTools.length === 0 &&
1436
+ !needsRuntimeHooks &&
1437
+ previousActiveToolNames.length === requestedActiveToolNames.length &&
1438
+ previousActiveToolNames.every(
1439
+ (toolName, index) => toolName === requestedActiveToolNames[index],
1440
+ )
1441
+ ) {
1442
+ return run();
1443
+ }
1444
+
1445
+ let mutableSession: MutableAgentSessionRuntime;
1446
+ try {
1447
+ mutableSession = getMutableSession(this.session);
1448
+ } catch (error) {
1449
+ throw toTemporaryToolRegistrationError(error);
1450
+ }
1451
+ const mutableAgent = this.session.agent as unknown as MutableAgentRuntimeHooks;
1452
+ const previousCustomTools = [...mutableSession._customTools];
1453
+ const previousBeforeToolCall = mutableAgent.beforeToolCall;
1454
+ const previousCreateLoopConfig = mutableAgent.createLoopConfig;
1455
+ const loopConfigHook = previousCreateLoopConfig;
1456
+ if (options.terminalAcknowledgement && typeof loopConfigHook !== "function") {
1457
+ throw new Error("Pi SDK version incompatible: agent loop configuration hook unavailable");
1458
+ }
1459
+ const terminalAcknowledgement = options.terminalAcknowledgement
1460
+ ? new TerminalAcknowledgementRuntime(
1461
+ options.terminalAcknowledgement,
1462
+ () => this.abortTurn(),
1463
+ () => {
1464
+ const leafId = this.getLeafId();
1465
+ return leafId ? this.getEntry(leafId) : undefined;
1466
+ },
1467
+ )
1468
+ : null;
1469
+ const tempDefinitions = customTools.map((tool) =>
1470
+ toToolDefinition(tool, terminalAcknowledgement, options.suspendPromptGuards),
1471
+ );
1472
+ mutableSession._customTools = [...previousCustomTools, ...tempDefinitions];
1473
+ mutableSession._refreshToolRegistry({
1474
+ activeToolNames: [
1475
+ ...new Set([...requestedActiveToolNames, ...tempDefinitions.map((tool) => tool.name)]),
1476
+ ],
1477
+ });
1478
+ if (needsRuntimeHooks) {
1479
+ mutableAgent.beforeToolCall = async (context, signal) => {
1480
+ terminalAcknowledgement?.onBeforeToolCall(context.toolCall.name);
1481
+ const blockedReason = options.shouldBlockToolCall?.(context.toolCall.name);
1482
+ if (blockedReason) {
1483
+ return { block: true, reason: blockedReason };
1484
+ }
1485
+ return await previousBeforeToolCall?.(context as never, signal);
1486
+ };
1487
+ if (terminalAcknowledgement && typeof loopConfigHook === "function") {
1488
+ mutableAgent.createLoopConfig = (loopOptions?: unknown) => {
1489
+ const baseConfig = loopConfigHook.call(mutableAgent, loopOptions);
1490
+ const previousShouldStop = baseConfig.shouldStopAfterTurn;
1491
+ return {
1492
+ ...baseConfig,
1493
+ shouldStopAfterTurn: async (...args: unknown[]) => {
1494
+ const acknowledgementDecision =
1495
+ terminalAcknowledgement?.onTurnCompleted(args) ?? null;
1496
+ if (acknowledgementDecision !== null) {
1497
+ return acknowledgementDecision;
1498
+ }
1499
+ if (typeof previousShouldStop === "function") {
1500
+ return await previousShouldStop(...args);
1501
+ }
1502
+ return false;
1503
+ },
1504
+ };
1505
+ };
1506
+ }
1507
+ }
1508
+
1509
+ try {
1510
+ if (terminalAcknowledgement) {
1511
+ await terminalAcknowledgement.run(run);
1512
+ } else {
1513
+ await run();
1514
+ }
1515
+ } finally {
1516
+ terminalAcknowledgement?.dispose();
1517
+ mutableSession._customTools = previousCustomTools;
1518
+ mutableAgent.beforeToolCall = previousBeforeToolCall;
1519
+ mutableAgent.createLoopConfig = previousCreateLoopConfig;
1520
+ mutableSession._refreshToolRegistry({
1521
+ activeToolNames: previousActiveToolNames,
1522
+ });
1523
+ }
1524
+ }
1525
+
1526
+ /**
1527
+ * Pi 0.81 has no public session-level continue API. Mirror its public retry
1528
+ * contract for a retained prompt leaf without calling private session methods.
1529
+ */
1530
+ private async runRetryAwareContinuation(): Promise<void> {
1531
+ const controller = new AbortController();
1532
+ this.continuationRetryAbortController = controller;
1533
+ try {
1534
+ await retryAssistantCall(
1535
+ async () => {
1536
+ await this.session.agent.continue();
1537
+ const leafId = this.getLeafId();
1538
+ const message = leafId ? this.getEntry(leafId)?.message : undefined;
1539
+ if (message?.role !== "assistant") {
1540
+ throw new Error("Pi continuation completed without an assistant message");
1541
+ }
1542
+ return message as AssistantMessage;
1543
+ },
1544
+ this.session.settingsManager.getRetrySettings(),
1545
+ controller.signal,
1546
+ {
1547
+ onRetryScheduled: (attempt, maxAttempts, delayMs, errorMessage) => {
1548
+ this.emitSessionEvent({
1549
+ type: "auto_retry_start",
1550
+ attempt,
1551
+ maxAttempts,
1552
+ delayMs,
1553
+ errorMessage,
1554
+ });
1555
+ const messages = this.session.agent.state.messages;
1556
+ if (messages.at(-1)?.role === "assistant") {
1557
+ this.session.agent.state.messages = messages.slice(0, -1);
1558
+ }
1559
+ },
1560
+ onRetryFinished: (success, attempt, finalError) =>
1561
+ this.emitSessionEvent({
1562
+ type: "auto_retry_end",
1563
+ success,
1564
+ attempt,
1565
+ finalError: controller.signal.aborted ? "Retry cancelled" : finalError,
1566
+ }),
1567
+ },
1568
+ );
1569
+ await this.session.waitForIdle();
1570
+ } finally {
1571
+ if (this.continuationRetryAbortController === controller) {
1572
+ this.continuationRetryAbortController = null;
1573
+ }
1574
+ }
1575
+ }
1576
+
1577
+ private createExecutionBranchSnapshot() {
1578
+ const startLeafId = this.getLeafId();
1579
+ const beforeEntryIds = new Set(
1580
+ (this.session.sessionManager.getEntries() as PiTreeEntry[]).map((entry) => entry.id),
1581
+ );
1582
+ return {
1583
+ startLeafId,
1584
+ createdEntries: () =>
1585
+ (this.session.sessionManager.getEntries() as PiTreeEntry[]).filter(
1586
+ (entry) => !beforeEntryIds.has(entry.id),
1587
+ ),
1588
+ assertResult: (
1589
+ operation: PiBranchOperation,
1590
+ anchorEntryId: string | null,
1591
+ resultEntryId: string | null,
1592
+ ) =>
1593
+ assertResultStayedOnExecutionBranch({
1594
+ operation,
1595
+ startLeafId,
1596
+ beforeEntryIds,
1597
+ anchorEntryId,
1598
+ resultEntryId,
1599
+ getBranch: (entryId) => this.getBranch(entryId),
1600
+ }),
1601
+ };
1602
+ }
1603
+
1604
+ private async captureTurnExecutionResult(
1605
+ operation: PiBranchOperation,
1606
+ run: () => Promise<void>,
1607
+ missingLeafMessage: string,
1608
+ terminalAcknowledgement?: PiPromptOptions["terminalAcknowledgement"],
1609
+ ): Promise<PiTurnExecutionResult> {
1610
+ const branch = this.createExecutionBranchSnapshot();
1611
+ const readVerifiedCreatedEntries = (resultEntryId: string | null): PiTreeEntry[] => {
1612
+ const createdEntries = branch.createdEntries();
1613
+ branch.assertResult(
1614
+ operation,
1615
+ resolveExecutionAnchorEntryId({
1616
+ operation,
1617
+ startLeafId: branch.startLeafId,
1618
+ createdEntries,
1619
+ }),
1620
+ resultEntryId,
1621
+ );
1622
+ return createdEntries;
1623
+ };
1624
+ try {
1625
+ await run();
1626
+ } catch (error) {
1627
+ try {
1628
+ readVerifiedCreatedEntries(this.getLeafId());
1629
+ } catch (driftError) {
1630
+ if (isPiBranchDriftError(driftError)) {
1631
+ throw driftError;
1632
+ }
1633
+ }
1634
+ throw error;
1635
+ }
1636
+ const endLeafId = this.getLeafId();
1637
+ if (!endLeafId) {
1638
+ throw new Error(missingLeafMessage);
1639
+ }
1640
+ const createdEntries = readVerifiedCreatedEntries(endLeafId);
1641
+ const createdEntryIds = createdEntries.map((entry) => entry.id);
1642
+ const resultBranchEntryIds = new Set(this.getBranch(endLeafId).map((entry) => entry.id));
1643
+ const branchCreatedEntries = createdEntries.filter((entry) =>
1644
+ resultBranchEntryIds.has(entry.id),
1645
+ );
1646
+ const promptError = findFinalAssistantPromptError(branchCreatedEntries);
1647
+ if (promptError && terminalAcknowledgement?.state() !== "acknowledgement_failed_ignored") {
1648
+ throw promptError;
1649
+ }
1650
+ return {
1651
+ startLeafId: branch.startLeafId,
1652
+ endLeafId,
1653
+ createdEntryIds,
1654
+ resultEntryId: endLeafId,
1655
+ assistantMarkdown: findFinalAssistantMarkdown(branchCreatedEntries),
1656
+ };
1657
+ }
1658
+
1659
+ private async executePrompt(
1660
+ options: PiPromptOptions,
1661
+ run: () => Promise<void>,
1662
+ ): Promise<PiTurnExecutionResult> {
1663
+ return await this.captureTurnExecutionResult(
1664
+ "prompt",
1665
+ () => this.withToolConfiguration(options, run),
1666
+ "Pi prompt completed without an active leaf",
1667
+ options.terminalAcknowledgement,
1668
+ );
1669
+ }
1670
+
1671
+ async prompt(text: string, options: PiPromptOptions = {}): Promise<PiTurnExecutionResult> {
1672
+ return await this.executePrompt(options, () => this.session.prompt(text));
1673
+ }
1674
+
1675
+ async promptLiteral(text: string, options: PiPromptOptions = {}): Promise<PiTurnExecutionResult> {
1676
+ return await this.executePrompt(options, () => this.session.sendUserMessage(text));
1677
+ }
1678
+
1679
+ async promptCustom(
1680
+ input: PiCustomMessageInput,
1681
+ options: PiPromptOptions = {},
1682
+ ): Promise<PiTurnExecutionResult> {
1683
+ return await this.executePrompt(options, () =>
1684
+ this.session.sendCustomMessage(
1685
+ { customType: "leitwerk", ...input, display: input.display ?? false },
1686
+ { triggerTurn: true },
1687
+ ),
1688
+ );
1689
+ }
1690
+
1691
+ async continueTurn(options: PiPromptOptions = {}): Promise<PiTurnExecutionResult> {
1692
+ updateAgentMessagesForCurrentLeaf(this.session);
1693
+ return await this.captureTurnExecutionResult(
1694
+ "continue",
1695
+ () => this.withToolConfiguration(options, () => this.runRetryAwareContinuation()),
1696
+ "Pi continuation completed without an active leaf",
1697
+ options.terminalAcknowledgement,
1698
+ );
1699
+ }
1700
+
1701
+ async appendCustomMessage(input: PiCustomMessageInput): Promise<string> {
1702
+ const branch = this.createExecutionBranchSnapshot();
1703
+ const sessionManager = this.session
1704
+ .sessionManager as unknown as SessionManagerWithCustomMessages;
1705
+ if (typeof sessionManager.appendCustomMessageEntry !== "function") {
1706
+ throw new Error("Pi SDK version incompatible: custom message insertion unavailable");
1707
+ }
1708
+ const entryId = sessionManager.appendCustomMessageEntry(
1709
+ "leitwerk",
1710
+ input.content,
1711
+ input.display ?? false,
1712
+ input.details,
1713
+ );
1714
+ updateAgentMessagesForCurrentLeaf(this.session);
1715
+ const endLeafId = this.getLeafId();
1716
+ if (endLeafId !== entryId) {
1717
+ throw new PiBranchDriftError({
1718
+ operation: "continue",
1719
+ anchorEntryId: entryId,
1720
+ rejectedResultEntryId: endLeafId ?? entryId,
1721
+ });
1722
+ }
1723
+ branch.assertResult("continue", entryId, entryId);
1724
+ return entryId;
1725
+ }
1726
+
1727
+ async steer(text: string): Promise<void> {
1728
+ await this.session.steer(text);
1729
+ }
1730
+
1731
+ async abortTurn(): Promise<void> {
1732
+ this.continuationRetryAbortController?.abort(new Error("Retry cancelled"));
1733
+ await this.session.abort();
1734
+ }
1735
+
1736
+ subscribe(handler: PiEventHandler): () => void {
1737
+ this.eventHandlers.add(handler);
1738
+ this.ensureSessionSubscription();
1739
+ return () => {
1740
+ this.eventHandlers.delete(handler);
1741
+ this.releaseSessionSubscriptionIfIdle();
1742
+ };
1743
+ }
1744
+
1745
+ subscribeDiagnostics(handler: PiSessionDiagnosticHandler): () => void {
1746
+ this.diagnosticHandlers.add(handler);
1747
+ this.ensureSessionSubscription();
1748
+ return () => {
1749
+ this.diagnosticHandlers.delete(handler);
1750
+ this.releaseSessionSubscriptionIfIdle();
1751
+ };
1752
+ }
1753
+
1754
+ private ensureSessionSubscription(): void {
1755
+ if (this.sessionUnsubscribe) {
1756
+ return;
1757
+ }
1758
+ this.sessionUnsubscribe = this.session.subscribe((event) => this.emitSessionEvent(event));
1759
+ }
1760
+
1761
+ private emitSessionEvent(event: AgentSessionEvent): void {
1762
+ const translated = translateAgentSessionEventEnvelope(event, this.eventState);
1763
+ for (const piEvent of translated.piEvents) this.emitSubscribedEvent(piEvent);
1764
+ for (const diagnostic of translated.diagnostics) this.emitSubscribedDiagnostic(diagnostic);
1765
+ }
1766
+
1767
+ private releaseSessionSubscriptionIfIdle(): void {
1768
+ if (
1769
+ !this.sessionUnsubscribe ||
1770
+ this.eventHandlers.size > 0 ||
1771
+ this.diagnosticHandlers.size > 0
1772
+ ) {
1773
+ return;
1774
+ }
1775
+ const unsubscribe = this.sessionUnsubscribe;
1776
+ this.sessionUnsubscribe = null;
1777
+ unsubscribe();
1778
+ }
1779
+
1780
+ private emitSubscribedEvent(event: PiEvent): void {
1781
+ for (const handler of this.eventHandlers) {
1782
+ try {
1783
+ handler(event);
1784
+ } catch (error) {
1785
+ console.warn("Pi event subscriber failed", error);
1786
+ }
1787
+ }
1788
+ }
1789
+
1790
+ private emitSubscribedDiagnostic(diagnostic: PiSessionDiagnostic): void {
1791
+ for (const handler of this.diagnosticHandlers) {
1792
+ try {
1793
+ handler(diagnostic);
1794
+ } catch (error) {
1795
+ console.warn("Pi diagnostic subscriber failed", error);
1796
+ }
1797
+ }
1798
+ }
1799
+
1800
+ async close(): Promise<void> {
1801
+ if (this.sessionUnsubscribe) {
1802
+ this.sessionUnsubscribe();
1803
+ this.sessionUnsubscribe = null;
1804
+ }
1805
+ this.eventHandlers.clear();
1806
+ this.diagnosticHandlers.clear();
1807
+ if (this.session.isStreaming) {
1808
+ try {
1809
+ await this.session.abort();
1810
+ } catch (error) {
1811
+ console.warn(`Failed to abort streaming Pi handle '${this.sessionId}' during close`, error);
1812
+ }
1813
+ }
1814
+ this.session.dispose();
1815
+ }
1816
+ }
1817
+
1818
+ interface PiRuntimeDiagnosticSummary {
1819
+ type?: string;
1820
+ message: string;
1821
+ }
1822
+
1823
+ function collectPiRuntimeDiagnostics(services: AgentSessionServices): PiRuntimeDiagnosticSummary[] {
1824
+ const extensionLoadDiagnostics = services.resourceLoader
1825
+ .getExtensions()
1826
+ .errors.map(({ path: extensionPath, error }) => ({
1827
+ type: "error",
1828
+ message: `Extension '${extensionPath}' failed to load: ${error}`,
1829
+ }));
1830
+ const resourceDiagnostics = [
1831
+ ...services.resourceLoader.getSkills().diagnostics,
1832
+ ...services.resourceLoader.getPrompts().diagnostics,
1833
+ ...services.resourceLoader.getThemes().diagnostics,
1834
+ ].map((diagnostic) => ({
1835
+ type: diagnostic.type === "error" ? "error" : diagnostic.type,
1836
+ message: diagnostic.message,
1837
+ }));
1838
+ return [...services.diagnostics, ...extensionLoadDiagnostics, ...resourceDiagnostics];
1839
+ }
1840
+
1841
+ function pathIsWithin(root: string, candidate: string): boolean {
1842
+ const relative = path.relative(path.resolve(root), path.resolve(candidate));
1843
+ return relative === "" || (!relative.startsWith(`..${path.sep}`) && relative !== "..");
1844
+ }
1845
+
1846
+ function assertLoadedPathAllowed(input: {
1847
+ path: string;
1848
+ agentDir: string;
1849
+ workspaceRoot: string;
1850
+ kind: string;
1851
+ }): void {
1852
+ if (pathIsWithin(input.agentDir, input.path)) return;
1853
+ const aggregatedAgentsPath = path.join(input.workspaceRoot, "AGENTS.md");
1854
+ const aggregatedSkillsRoot = path.join(input.workspaceRoot, ".leitwerk", "skills");
1855
+ if (
1856
+ path.resolve(input.path) === path.resolve(aggregatedAgentsPath) ||
1857
+ pathIsWithin(aggregatedSkillsRoot, input.path)
1858
+ ) {
1859
+ return;
1860
+ }
1861
+ throw new Error(
1862
+ `Pi ${input.kind} loaded outside the managed resource snapshot or approved process workspace inputs: ${input.path}`,
1863
+ );
1864
+ }
1865
+
1866
+ function validateManagedLoadedResources(input: {
1867
+ services: AgentSessionServices;
1868
+ manifest: ManagedPiResourceManifest;
1869
+ agentDir: string;
1870
+ workspaceRoot: string;
1871
+ }): string[] {
1872
+ const extensions = input.services.resourceLoader.getExtensions().extensions;
1873
+ const skills = input.services.resourceLoader.getSkills().skills;
1874
+ const prompts = input.services.resourceLoader.getPrompts().prompts;
1875
+ const agentsFiles = input.services.resourceLoader.getAgentsFiles().agentsFiles;
1876
+ for (const extension of extensions) {
1877
+ assertLoadedPathAllowed({
1878
+ path: extension.resolvedPath,
1879
+ agentDir: input.agentDir,
1880
+ workspaceRoot: input.workspaceRoot,
1881
+ kind: "extension",
1882
+ });
1883
+ }
1884
+ for (const skill of skills) {
1885
+ assertLoadedPathAllowed({
1886
+ path: skill.filePath,
1887
+ agentDir: input.agentDir,
1888
+ workspaceRoot: input.workspaceRoot,
1889
+ kind: "skill",
1890
+ });
1891
+ }
1892
+ for (const prompt of prompts) {
1893
+ assertLoadedPathAllowed({
1894
+ path: prompt.filePath,
1895
+ agentDir: input.agentDir,
1896
+ workspaceRoot: input.workspaceRoot,
1897
+ kind: "prompt",
1898
+ });
1899
+ }
1900
+ for (const agentsFile of agentsFiles) {
1901
+ assertLoadedPathAllowed({
1902
+ path: agentsFile.path,
1903
+ agentDir: input.agentDir,
1904
+ workspaceRoot: input.workspaceRoot,
1905
+ kind: "context file",
1906
+ });
1907
+ }
1908
+
1909
+ const loadedResourceIds: string[] = [];
1910
+ for (const resource of input.manifest.provenance) {
1911
+ const expectedPath = path.resolve(input.agentDir, resource.snapshotPath);
1912
+ let loaded = resource.kind === "generated";
1913
+ if (resource.kind === "extension") {
1914
+ loaded = extensions.some(
1915
+ (extension) => path.resolve(extension.resolvedPath) === expectedPath,
1916
+ );
1917
+ } else if (resource.kind === "skill") {
1918
+ loaded = skills.some((skill) => pathIsWithin(skill.baseDir, expectedPath));
1919
+ } else if (resource.kind === "prompt") {
1920
+ loaded = prompts.some((prompt) => path.resolve(prompt.filePath) === expectedPath);
1921
+ }
1922
+ if (!loaded) {
1923
+ throw new Error(
1924
+ `Pi did not load declared ${resource.kind} resource '${resource.snapshotPath}'`,
1925
+ );
1926
+ }
1927
+ loadedResourceIds.push(resource.snapshotPath);
1928
+ }
1929
+ return loadedResourceIds;
1930
+ }
1931
+
1932
+ async function createManagedAgentSessionServices(input: {
1933
+ agentDir: string;
1934
+ sessionCwd: string;
1935
+ workspaceRoot: string;
1936
+ piConfig?: PiTreeHandleOptions["piConfig"];
1937
+ }): Promise<AgentSessionServices> {
1938
+ const { createAgentSessionServices, ModelRuntime, SettingsManager } = await import(
1939
+ "@earendil-works/pi-coding-agent"
1940
+ );
1941
+ const settingsManager = SettingsManager.create(input.sessionCwd, input.agentDir);
1942
+ const modelRuntime = await ModelRuntime.create({
1943
+ authPath: path.join(input.agentDir, "auth.json"),
1944
+ modelsPath: path.join(input.agentDir, "models.json"),
1945
+ });
1946
+ return createAgentSessionServices({
1947
+ cwd: input.sessionCwd,
1948
+ agentDir: input.agentDir,
1949
+ modelRuntime,
1950
+ settingsManager,
1951
+ resourceLoaderOptions: await buildLeitwerkResourceLoaderOptions(
1952
+ input.workspaceRoot,
1953
+ input.agentDir,
1954
+ {
1955
+ systemPrompt: input.piConfig?.systemPrompt,
1956
+ appendSystemPrompt: input.piConfig?.appendSystemPrompt,
1957
+ },
1958
+ ),
1959
+ });
1960
+ }
1961
+
1962
+ function formatPiRuntimeDiagnostics(
1963
+ diagnostics: readonly PiRuntimeDiagnosticSummary[] | undefined,
1964
+ ): string {
1965
+ const messages = (diagnostics ?? [])
1966
+ .filter((diagnostic) => diagnostic.type === undefined || diagnostic.type === "error")
1967
+ .map((diagnostic) => diagnostic.message.trim())
1968
+ .filter((message) => message.length > 0);
1969
+ if (messages.length === 0) {
1970
+ return "";
1971
+ }
1972
+ return ` Pi extension diagnostics: ${messages.join("; ")}`;
1973
+ }
1974
+
1975
+ function resolveModelSelection(
1976
+ modelProfileId: string | null | undefined,
1977
+ configSnapshot: ConfigSnapshot | undefined,
1978
+ modelRuntime: ModelRuntime,
1979
+ diagnostics?: readonly PiRuntimeDiagnosticSummary[],
1980
+ ): { model?: ReturnType<ModelRuntime["getModel"]>; thinkingLevel?: string } {
1981
+ if (!modelProfileId) {
1982
+ return {};
1983
+ }
1984
+
1985
+ const profile = configSnapshot?.pi.model_profiles.find(
1986
+ (candidate) => candidate.id === modelProfileId,
1987
+ );
1988
+ if (!profile) {
1989
+ throw new Error(`Unknown model profile '${modelProfileId}'`);
1990
+ }
1991
+
1992
+ const model = modelRuntime.getModel(profile.provider, profile.model_id);
1993
+ if (!model) {
1994
+ throw new Error(
1995
+ `Unable to resolve configured model '${profile.provider}/${profile.model_id}' for profile '${modelProfileId}'.${formatPiRuntimeDiagnostics(diagnostics)}`,
1996
+ );
1997
+ }
1998
+
1999
+ return {
2000
+ model,
2001
+ thinkingLevel: profile.thinking_level,
2002
+ };
2003
+ }
2004
+
2005
+ function isAlreadyExistsError(error: unknown): boolean {
2006
+ return (
2007
+ typeof error === "object" &&
2008
+ error !== null &&
2009
+ "code" in error &&
2010
+ (error as { code?: unknown }).code === "EEXIST"
2011
+ );
2012
+ }
2013
+
2014
+ async function ensureSessionFileExists(input: {
2015
+ treeFile: string;
2016
+ instanceId: string;
2017
+ sessionCwd: string;
2018
+ sessionVersion: number;
2019
+ }): Promise<void> {
2020
+ await mkdir(path.dirname(input.treeFile), { recursive: true });
2021
+ const header = {
2022
+ type: "session",
2023
+ version: input.sessionVersion,
2024
+ id: input.instanceId,
2025
+ timestamp: new Date().toISOString(),
2026
+ cwd: input.sessionCwd,
2027
+ };
2028
+ try {
2029
+ await writeFile(input.treeFile, `${JSON.stringify(header)}\n`, { flag: "wx" });
2030
+ } catch (error) {
2031
+ if (isAlreadyExistsError(error)) {
2032
+ return;
2033
+ }
2034
+ throw error;
2035
+ }
2036
+ }
2037
+
2038
+ function applyPiRetryOverrides(
2039
+ services: AgentSessionServices,
2040
+ configSnapshot: ConfigSnapshot | undefined,
2041
+ ): void {
2042
+ const piRetryConfig = configSnapshot?.pi.retry;
2043
+ const retryOverrides = {
2044
+ enabled: piRetryConfig?.enabled ?? true,
2045
+ maxRetries: piRetryConfig?.max_retries ?? 3,
2046
+ baseDelayMs: parseDurationMs(piRetryConfig?.base_delay ?? "2s", 2_000, {
2047
+ allowHours: true,
2048
+ }),
2049
+ provider: {
2050
+ ...(piRetryConfig?.provider.timeout
2051
+ ? {
2052
+ timeoutMs: parseDurationMs(piRetryConfig.provider.timeout, 0, {
2053
+ allowHours: true,
2054
+ }),
2055
+ }
2056
+ : {}),
2057
+ ...(piRetryConfig?.provider.max_retries !== null &&
2058
+ piRetryConfig?.provider.max_retries !== undefined
2059
+ ? { maxRetries: piRetryConfig.provider.max_retries }
2060
+ : {}),
2061
+ maxRetryDelayMs: parseDurationMs(piRetryConfig?.provider.max_retry_delay ?? "60s", 60_000, {
2062
+ allowHours: true,
2063
+ }),
2064
+ },
2065
+ };
2066
+ services.settingsManager.applyOverrides({ retry: retryOverrides as never });
2067
+ }
2068
+
2069
+ function managedServicesKey(agentDir: string, sessionCwd: string): string {
2070
+ return `${path.resolve(agentDir)}\0${path.resolve(sessionCwd)}`;
2071
+ }
2072
+
2073
+ export class SdkPiTreeHandleFactory implements PiTreeHandleFactory {
2074
+ private readonly preparedServices = new Map<string, AgentSessionServices>();
2075
+
2076
+ async prepareManagedBootstrap(
2077
+ opts: PiManagedBootstrapOptions,
2078
+ ): Promise<PiManagedBootstrapResult> {
2079
+ const services = await createManagedAgentSessionServices({
2080
+ agentDir: opts.agentDir,
2081
+ sessionCwd: opts.sessionCwd,
2082
+ workspaceRoot: opts.workspaceRoot,
2083
+ piConfig: opts.piConfig,
2084
+ });
2085
+ applyPiRetryOverrides(services, opts.configSnapshot);
2086
+ const diagnostics = collectPiRuntimeDiagnostics(services);
2087
+ const fatalDiagnostics = diagnostics.filter(
2088
+ (diagnostic) => diagnostic.type === undefined || diagnostic.type === "error",
2089
+ );
2090
+ if (fatalDiagnostics.length > 0) {
2091
+ throw new Error(
2092
+ `Pi managed bootstrap failed.${formatPiRuntimeDiagnostics(fatalDiagnostics)}`,
2093
+ );
2094
+ }
2095
+ const model = services.modelRuntime.getModel(
2096
+ opts.expectedModel.providerId,
2097
+ opts.expectedModel.modelId,
2098
+ );
2099
+ if (!model) {
2100
+ throw new Error(
2101
+ `Unable to resolve managed Pi model '${opts.expectedModel.providerId}/${opts.expectedModel.modelId}'.${formatPiRuntimeDiagnostics(diagnostics)}`,
2102
+ );
2103
+ }
2104
+ const loadedResourceIds = validateManagedLoadedResources({
2105
+ services,
2106
+ manifest: opts.manifest,
2107
+ agentDir: opts.agentDir,
2108
+ workspaceRoot: opts.workspaceRoot,
2109
+ });
2110
+ const runDetails = toPiRunDetails({
2111
+ loadedAgentsFiles: services.resourceLoader.getAgentsFiles().agentsFiles,
2112
+ loadedSkills: services.resourceLoader.getSkills().skills.map((skill) => ({
2113
+ name: skill.name,
2114
+ path: skill.filePath,
2115
+ })),
2116
+ availableToolNames: opts.piConfig?.availableToolNames ?? [],
2117
+ });
2118
+ this.preparedServices.set(managedServicesKey(opts.agentDir, opts.sessionCwd), services);
2119
+ return {
2120
+ loadedResourceIds,
2121
+ loadedAgentsFiles: runDetails.loadedAgentsFiles,
2122
+ loadedSkillFiles: runDetails.loadedSkills,
2123
+ resolvedModel: { ...opts.expectedModel },
2124
+ diagnostics: diagnostics.map((diagnostic) => diagnostic.message),
2125
+ };
2126
+ }
2127
+
2128
+ async inspectPrimaryTree(opts: PiTreePlanningOptions): Promise<PiTreePlanningSnapshot> {
2129
+ return inspectPiTreeForPlanning(opts);
2130
+ }
2131
+
2132
+ async createPrimaryTreeHandle(opts: PiTreeHandleOptions): Promise<PiTreeHandle> {
2133
+ const { CURRENT_SESSION_VERSION, createAgentSessionFromServices, SessionManager } =
2134
+ await import("@earendil-works/pi-coding-agent");
2135
+ const agentDir = resolvePiAgentDir({
2136
+ agentDir: opts.agentDir,
2137
+ configSnapshot: opts.configSnapshot,
2138
+ fallbackDir: opts.workspaceRoot,
2139
+ });
2140
+ const sessionCwd = opts.sessionCwd ?? opts.workspaceRoot;
2141
+ const availableToolNames = opts.piConfig?.availableToolNames ?? [];
2142
+ const key = managedServicesKey(agentDir, sessionCwd);
2143
+ const preparedServices = this.preparedServices.get(key);
2144
+ if (preparedServices) this.preparedServices.delete(key);
2145
+ const services =
2146
+ preparedServices ??
2147
+ (await createManagedAgentSessionServices({
2148
+ agentDir,
2149
+ sessionCwd,
2150
+ workspaceRoot: opts.workspaceRoot,
2151
+ piConfig: opts.piConfig,
2152
+ }));
2153
+ if (!preparedServices) applyPiRetryOverrides(services, opts.configSnapshot);
2154
+ await ensureSessionFileExists({
2155
+ treeFile: opts.treeFile,
2156
+ instanceId: opts.instanceId,
2157
+ sessionCwd,
2158
+ sessionVersion: CURRENT_SESSION_VERSION,
2159
+ });
2160
+ const sessionManager = SessionManager.open(
2161
+ opts.treeFile,
2162
+ path.dirname(opts.treeFile),
2163
+ sessionCwd,
2164
+ );
2165
+ const modelSelection = resolveModelSelection(
2166
+ opts.modelProfileId,
2167
+ opts.configSnapshot,
2168
+ services.modelRuntime,
2169
+ collectPiRuntimeDiagnostics(services),
2170
+ );
2171
+ const { session } = await createAgentSessionFromServices({
2172
+ services,
2173
+ sessionManager,
2174
+ ...(modelSelection.model ? { model: modelSelection.model } : {}),
2175
+ ...(modelSelection.thinkingLevel
2176
+ ? { thinkingLevel: modelSelection.thinkingLevel as never }
2177
+ : {}),
2178
+ customTools: [LEITWERK_TOOL_BOOTSTRAP],
2179
+ noTools: "builtin",
2180
+ });
2181
+ getMutableSession(session)._refreshToolRegistry({ activeToolNames: [] });
2182
+ const runDetails = toPiRunDetails({
2183
+ loadedAgentsFiles: services.resourceLoader.getAgentsFiles().agentsFiles,
2184
+ loadedSkills: services.resourceLoader.getSkills().skills.map((skill) => ({
2185
+ name: skill.name,
2186
+ path: skill.filePath,
2187
+ })),
2188
+ availableToolNames,
2189
+ });
2190
+ return new SdkPiTreeHandle(session, {
2191
+ treeFile: opts.treeFile,
2192
+ isResumed: opts.resume,
2193
+ availableToolNames,
2194
+ runDetails,
2195
+ });
2196
+ }
2197
+ }