@leitwerk-dev/worker 0.1.9 → 0.2.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 (234) hide show
  1. package/dist/automatic-turn-executor.d.ts +1 -0
  2. package/dist/automatic-turn-executor.d.ts.map +1 -1
  3. package/dist/{chunk-O6332GRG.js → chunk-Y7S2MZD3.js} +1349 -932
  4. package/dist/chunk-Y7S2MZD3.js.map +1 -0
  5. package/dist/connection-diagnostics.d.ts +5 -0
  6. package/dist/connection-diagnostics.d.ts.map +1 -0
  7. package/dist/container-entry-main.d.ts +2 -0
  8. package/dist/container-entry-main.d.ts.map +1 -0
  9. package/dist/container-entry-main.js +232 -0
  10. package/dist/container-entry-main.js.map +1 -0
  11. package/dist/container-entry.d.ts +14 -0
  12. package/dist/container-entry.d.ts.map +1 -0
  13. package/dist/development-tool-environment.d.ts +48 -0
  14. package/dist/development-tool-environment.d.ts.map +1 -0
  15. package/dist/diagnostics.d.ts +4 -0
  16. package/dist/diagnostics.d.ts.map +1 -1
  17. package/dist/docker-registry-credentials.d.ts +8 -0
  18. package/dist/docker-registry-credentials.d.ts.map +1 -0
  19. package/dist/entry-runtime.d.ts +1 -0
  20. package/dist/entry-runtime.d.ts.map +1 -1
  21. package/dist/index.d.ts +1 -0
  22. package/dist/index.d.ts.map +1 -1
  23. package/dist/index.js +44 -5
  24. package/dist/index.js.map +1 -1
  25. package/dist/input-consumer.d.ts +6 -11
  26. package/dist/input-consumer.d.ts.map +1 -1
  27. package/dist/ipc.d.ts +1 -0
  28. package/dist/ipc.d.ts.map +1 -1
  29. package/dist/logical-prompt-runner.d.ts.map +1 -1
  30. package/dist/managed-pi-bootstrap.d.ts.map +1 -1
  31. package/dist/missing-tool-recovery-runner.d.ts +4 -3
  32. package/dist/missing-tool-recovery-runner.d.ts.map +1 -1
  33. package/dist/pi-adapter.d.ts +1 -0
  34. package/dist/pi-adapter.d.ts.map +1 -1
  35. package/dist/pi-event-reporter.d.ts.map +1 -1
  36. package/dist/pi-resource-bundle.d.ts +11 -0
  37. package/dist/pi-resource-bundle.d.ts.map +1 -1
  38. package/dist/pre-turn-targeted-inputs.d.ts +8 -7
  39. package/dist/pre-turn-targeted-inputs.d.ts.map +1 -1
  40. package/dist/prompt-guards.d.ts.map +1 -1
  41. package/dist/repository-bash-tool.d.ts +4 -0
  42. package/dist/repository-bash-tool.d.ts.map +1 -0
  43. package/dist/resource-loader-factory.d.ts +1 -2
  44. package/dist/resource-loader-factory.d.ts.map +1 -1
  45. package/dist/result-image-upload.d.ts.map +1 -1
  46. package/dist/runtime/adapters.d.ts +2 -0
  47. package/dist/runtime/adapters.d.ts.map +1 -1
  48. package/dist/runtime/bootstrap-session.d.ts +8 -5
  49. package/dist/runtime/bootstrap-session.d.ts.map +1 -1
  50. package/dist/runtime/bootstrap.d.ts +14 -18
  51. package/dist/runtime/bootstrap.d.ts.map +1 -1
  52. package/dist/runtime/failure-policy.d.ts +1 -0
  53. package/dist/runtime/failure-policy.d.ts.map +1 -1
  54. package/dist/runtime/index.d.ts.map +1 -1
  55. package/dist/runtime/lifecycle-reducer.d.ts.map +1 -1
  56. package/dist/runtime/llm-turn-execution.d.ts +3 -8
  57. package/dist/runtime/llm-turn-execution.d.ts.map +1 -1
  58. package/dist/runtime/turn-execution.d.ts +2 -9
  59. package/dist/runtime/turn-execution.d.ts.map +1 -1
  60. package/dist/session-snapshot-exchange.d.ts +0 -4
  61. package/dist/session-snapshot-exchange.d.ts.map +1 -1
  62. package/dist/turn-continuation.d.ts.map +1 -1
  63. package/dist/turn-execution-error.d.ts +1 -1
  64. package/dist/turn-execution-error.d.ts.map +1 -1
  65. package/dist/turn-execution-result.d.ts +1 -0
  66. package/dist/turn-execution-result.d.ts.map +1 -1
  67. package/dist/turn-outcome-tool-session.d.ts +0 -2
  68. package/dist/turn-outcome-tool-session.d.ts.map +1 -1
  69. package/dist/turn-result-markdown.d.ts +2 -1
  70. package/dist/turn-result-markdown.d.ts.map +1 -1
  71. package/dist/turn-tree-strategy.d.ts +0 -1
  72. package/dist/turn-tree-strategy.d.ts.map +1 -1
  73. package/dist/worker-entry.js +16 -4
  74. package/dist/worker-entry.js.map +1 -1
  75. package/dist/worker-ipc-reporter.d.ts.map +1 -1
  76. package/dist/workspace/manifest.d.ts +4 -7
  77. package/dist/workspace/manifest.d.ts.map +1 -1
  78. package/dist/workspace/node-run-root-git-ops.d.ts +2 -2
  79. package/dist/workspace/node-run-root-git-ops.d.ts.map +1 -1
  80. package/dist/workspace/resource-aggregator.d.ts.map +1 -1
  81. package/dist/workspace/run-root.d.ts +9 -20
  82. package/dist/workspace/run-root.d.ts.map +1 -1
  83. package/package.json +8 -8
  84. package/src/automatic-turn-executor.ts +2 -0
  85. package/src/connection-diagnostics.ts +27 -0
  86. package/src/container-entry-main.ts +24 -0
  87. package/src/container-entry.ts +246 -0
  88. package/src/development-tool-environment.ts +452 -0
  89. package/src/diagnostics.ts +1 -0
  90. package/src/docker-registry-credentials.ts +65 -0
  91. package/src/entry-runtime.ts +5 -4
  92. package/src/index.ts +11 -0
  93. package/src/input-consumer.ts +7 -29
  94. package/src/ipc.ts +37 -2
  95. package/src/logical-prompt-runner.ts +23 -29
  96. package/src/managed-pi-bootstrap.ts +3 -3
  97. package/src/missing-tool-recovery-runner.ts +4 -18
  98. package/src/pi-adapter.ts +19 -50
  99. package/src/pi-event-reporter.ts +16 -38
  100. package/src/pi-resource-bundle.ts +67 -1
  101. package/src/pre-turn-targeted-inputs.ts +9 -11
  102. package/src/prompt-guards.ts +44 -75
  103. package/src/repository-bash-tool.ts +15 -0
  104. package/src/resource-loader-factory.ts +1 -18
  105. package/src/result-image-upload.ts +16 -27
  106. package/src/runtime/adapters.ts +2 -0
  107. package/src/runtime/bootstrap-session.ts +69 -39
  108. package/src/runtime/bootstrap.ts +160 -103
  109. package/src/runtime/failure-policy.ts +36 -42
  110. package/src/runtime/index.ts +43 -14
  111. package/src/runtime/lifecycle-reducer.ts +71 -173
  112. package/src/runtime/llm-turn-execution.ts +13 -30
  113. package/src/runtime/turn-execution.ts +78 -31
  114. package/src/session-snapshot-exchange.ts +23 -64
  115. package/src/turn-continuation.ts +9 -17
  116. package/src/turn-execution-error.ts +3 -11
  117. package/src/turn-execution-result.ts +1 -0
  118. package/src/turn-outcome-tool-session.ts +25 -21
  119. package/src/turn-result-markdown.ts +31 -34
  120. package/src/turn-tree-strategy.ts +6 -19
  121. package/src/worker-entry.ts +8 -0
  122. package/src/worker-ipc-reporter.ts +8 -16
  123. package/src/workspace/manifest.ts +5 -7
  124. package/src/workspace/node-run-root-git-ops.ts +65 -25
  125. package/src/workspace/resource-aggregator.ts +5 -16
  126. package/src/workspace/run-root.ts +38 -89
  127. package/dist/automatic-turn-executor.js +0 -58
  128. package/dist/automatic-turn-executor.js.map +0 -1
  129. package/dist/chunk-O6332GRG.js.map +0 -1
  130. package/dist/diagnostics.js +0 -51
  131. package/dist/diagnostics.js.map +0 -1
  132. package/dist/entry-runtime.js +0 -160
  133. package/dist/entry-runtime.js.map +0 -1
  134. package/dist/event-translator.js +0 -12
  135. package/dist/event-translator.js.map +0 -1
  136. package/dist/extension-entry-roots.js +0 -41
  137. package/dist/extension-entry-roots.js.map +0 -1
  138. package/dist/identified-pi-entry.js +0 -125
  139. package/dist/identified-pi-entry.js.map +0 -1
  140. package/dist/input-consumer.js +0 -34
  141. package/dist/input-consumer.js.map +0 -1
  142. package/dist/integration-tool-bridge.js +0 -53
  143. package/dist/integration-tool-bridge.js.map +0 -1
  144. package/dist/ipc.js +0 -192
  145. package/dist/ipc.js.map +0 -1
  146. package/dist/logical-prompt-runner.js +0 -225
  147. package/dist/logical-prompt-runner.js.map +0 -1
  148. package/dist/managed-pi-agent-dir.js +0 -66
  149. package/dist/managed-pi-agent-dir.js.map +0 -1
  150. package/dist/managed-pi-bootstrap.js +0 -135
  151. package/dist/managed-pi-bootstrap.js.map +0 -1
  152. package/dist/missing-tool-recovery-runner.js +0 -73
  153. package/dist/missing-tool-recovery-runner.js.map +0 -1
  154. package/dist/pi-adapter.js +0 -1648
  155. package/dist/pi-adapter.js.map +0 -1
  156. package/dist/pi-branch-guard.js +0 -75
  157. package/dist/pi-branch-guard.js.map +0 -1
  158. package/dist/pi-event-reporter.js +0 -136
  159. package/dist/pi-event-reporter.js.map +0 -1
  160. package/dist/pi-resource-bundle.js +0 -58
  161. package/dist/pi-resource-bundle.js.map +0 -1
  162. package/dist/pre-turn-targeted-inputs.js +0 -101
  163. package/dist/pre-turn-targeted-inputs.js.map +0 -1
  164. package/dist/prompt-guards.js +0 -318
  165. package/dist/prompt-guards.js.map +0 -1
  166. package/dist/question-bridge.js +0 -24
  167. package/dist/question-bridge.js.map +0 -1
  168. package/dist/question-tool.js +0 -54
  169. package/dist/question-tool.js.map +0 -1
  170. package/dist/replaying-request-bridge.js +0 -71
  171. package/dist/replaying-request-bridge.js.map +0 -1
  172. package/dist/resource-loader-factory.js +0 -87
  173. package/dist/resource-loader-factory.js.map +0 -1
  174. package/dist/result-image-upload.js +0 -183
  175. package/dist/result-image-upload.js.map +0 -1
  176. package/dist/runtime/adapters.js +0 -15
  177. package/dist/runtime/adapters.js.map +0 -1
  178. package/dist/runtime/bootstrap-session.js +0 -199
  179. package/dist/runtime/bootstrap-session.js.map +0 -1
  180. package/dist/runtime/bootstrap.js +0 -440
  181. package/dist/runtime/bootstrap.js.map +0 -1
  182. package/dist/runtime/failure-policy.js +0 -182
  183. package/dist/runtime/failure-policy.js.map +0 -1
  184. package/dist/runtime/index.js +0 -339
  185. package/dist/runtime/index.js.map +0 -1
  186. package/dist/runtime/lifecycle-reducer.js +0 -1142
  187. package/dist/runtime/lifecycle-reducer.js.map +0 -1
  188. package/dist/runtime/llm-turn-execution.js +0 -494
  189. package/dist/runtime/llm-turn-execution.js.map +0 -1
  190. package/dist/runtime/settings.js +0 -24
  191. package/dist/runtime/settings.js.map +0 -1
  192. package/dist/runtime/snapshot-policy.js +0 -16
  193. package/dist/runtime/snapshot-policy.js.map +0 -1
  194. package/dist/runtime/turn-execution.js +0 -151
  195. package/dist/runtime/turn-execution.js.map +0 -1
  196. package/dist/session-snapshot-exchange.js +0 -102
  197. package/dist/session-snapshot-exchange.js.map +0 -1
  198. package/dist/test-helpers/fake-websocket.js +0 -40
  199. package/dist/test-helpers/fake-websocket.js.map +0 -1
  200. package/dist/test-helpers/ipc-harness.d.ts +0 -11
  201. package/dist/test-helpers/ipc-harness.d.ts.map +0 -1
  202. package/dist/test-helpers/ipc-harness.js +0 -17
  203. package/dist/test-helpers/ipc-harness.js.map +0 -1
  204. package/dist/turn-continuation.js +0 -80
  205. package/dist/turn-continuation.js.map +0 -1
  206. package/dist/turn-execution-error.js +0 -64
  207. package/dist/turn-execution-error.js.map +0 -1
  208. package/dist/turn-execution-result.js +0 -21
  209. package/dist/turn-execution-result.js.map +0 -1
  210. package/dist/turn-outcome-tool-session.js +0 -210
  211. package/dist/turn-outcome-tool-session.js.map +0 -1
  212. package/dist/turn-record-id.js +0 -10
  213. package/dist/turn-record-id.js.map +0 -1
  214. package/dist/turn-result-markdown.js +0 -263
  215. package/dist/turn-result-markdown.js.map +0 -1
  216. package/dist/turn-tree-strategy.js +0 -80
  217. package/dist/turn-tree-strategy.js.map +0 -1
  218. package/dist/worker-http.js +0 -9
  219. package/dist/worker-http.js.map +0 -1
  220. package/dist/worker-ipc-reporter.js +0 -58
  221. package/dist/worker-ipc-reporter.js.map +0 -1
  222. package/dist/worker-payloads.js +0 -66
  223. package/dist/worker-payloads.js.map +0 -1
  224. package/dist/worker-start-payload.js +0 -5
  225. package/dist/worker-start-payload.js.map +0 -1
  226. package/dist/workspace/manifest.js +0 -79
  227. package/dist/workspace/manifest.js.map +0 -1
  228. package/dist/workspace/node-run-root-git-ops.js +0 -96
  229. package/dist/workspace/node-run-root-git-ops.js.map +0 -1
  230. package/dist/workspace/resource-aggregator.js +0 -39
  231. package/dist/workspace/resource-aggregator.js.map +0 -1
  232. package/dist/workspace/run-root.js +0 -209
  233. package/dist/workspace/run-root.js.map +0 -1
  234. package/src/test-helpers/ipc-harness.ts +0 -19
@@ -1,1648 +0,0 @@
1
- import { access, mkdir, writeFile } from "node:fs/promises";
2
- import path from "node:path";
3
- import { retryAssistantCall } from "@earendil-works/pi-ai";
4
- import { resolvePiAgentDir } from "@leitwerk-dev/process-sdk/pi-config";
5
- import { parseDurationMs } from "@leitwerk-dev/watcher-utils";
6
- import { assertResultStayedOnExecutionBranch, isPiBranchDriftError, PiBranchDriftError, resolveExecutionAnchorEntryId, } from "./pi-branch-guard.js";
7
- import { buildLeitwerkResourceLoaderOptions } from "./resource-loader-factory.js";
8
- const LEITWERK_TOOL_BOOTSTRAP_NAME = "__leitwerk_runtime_bootstrap__";
9
- export { isPiBranchDriftError, PiBranchDriftError } from "./pi-branch-guard.js";
10
- /** Read persisted tree topology without creating a Pi session or mutating the tree file. */
11
- export async function inspectPiTreeForPlanning(input) {
12
- try {
13
- await access(input.treeFile);
14
- }
15
- catch (error) {
16
- if (typeof error === "object" &&
17
- error !== null &&
18
- "code" in error &&
19
- error.code === "ENOENT") {
20
- return { currentLeafId: null, entries: [] };
21
- }
22
- throw error;
23
- }
24
- const { SessionManager } = await import("@earendil-works/pi-coding-agent");
25
- const manager = SessionManager.open(input.treeFile, path.dirname(input.treeFile), input.sessionCwd);
26
- const entries = [];
27
- const visit = (nodes) => {
28
- for (const node of nodes) {
29
- entries.push({ id: node.entry.id, parentId: node.entry.parentId });
30
- visit(node.children);
31
- }
32
- };
33
- visit(manager.getTree());
34
- return {
35
- currentLeafId: manager.getLeafId() ?? null,
36
- entries,
37
- };
38
- }
39
- function toIsoTimestamp(value) {
40
- if (typeof value === "number" && Number.isFinite(value)) {
41
- return new Date(value).toISOString();
42
- }
43
- if (typeof value === "string" && value.trim() !== "") {
44
- return value;
45
- }
46
- return new Date().toISOString();
47
- }
48
- function isObjectLike(value) {
49
- return typeof value === "object" && value !== null;
50
- }
51
- function toToolSchema(parameters) {
52
- if (isObjectLike(parameters) &&
53
- parameters.type === "object" &&
54
- isObjectLike(parameters.properties)) {
55
- return parameters;
56
- }
57
- const properties = {};
58
- const required = [];
59
- for (const [key, spec] of Object.entries(parameters)) {
60
- if (isObjectLike(spec)) {
61
- const { required: isRequired, requiredErrorCode: _requiredErrorCode, invalidErrorCode: _invalidErrorCode, minItemsErrorCode: _minItemsErrorCode, minimumErrorCode: _minimumErrorCode, ...jsonSchemaSpec } = spec;
62
- properties[key] = { ...jsonSchemaSpec };
63
- if (isRequired === true) {
64
- required.push(key);
65
- }
66
- }
67
- else {
68
- properties[key] = { type: "string" };
69
- }
70
- }
71
- return {
72
- type: "object",
73
- properties,
74
- required,
75
- additionalProperties: false,
76
- };
77
- }
78
- const LEITWERK_TOOL_BOOTSTRAP = {
79
- name: LEITWERK_TOOL_BOOTSTRAP_NAME,
80
- label: LEITWERK_TOOL_BOOTSTRAP_NAME,
81
- description: "Internal leitwerk bootstrap tool",
82
- promptSnippet: `${LEITWERK_TOOL_BOOTSTRAP_NAME}: Internal leitwerk bootstrap tool`,
83
- parameters: toToolSchema({}),
84
- execute: async () => ({
85
- content: [{ type: "text", text: "leitwerk bootstrap" }],
86
- details: { ok: true },
87
- }),
88
- };
89
- function stringifyToolResult(result) {
90
- if (typeof result === "string") {
91
- return result;
92
- }
93
- if (result === undefined) {
94
- return "ok";
95
- }
96
- try {
97
- return JSON.stringify(result, null, 2);
98
- }
99
- catch {
100
- return String(result);
101
- }
102
- }
103
- export const TERMINAL_ACKNOWLEDGEMENT_INSTRUCTION = 'Outcome accepted successfully. Do not call any more tools. Reply only with "done".';
104
- function toToolDefinition(tool, terminalAcknowledgement, suspendPromptGuards) {
105
- return {
106
- name: tool.name,
107
- label: tool.name,
108
- description: tool.description,
109
- promptSnippet: `${tool.name}: ${tool.description}`,
110
- parameters: toToolSchema(tool.parameters),
111
- ...(tool.executionMode ? { executionMode: tool.executionMode } : {}),
112
- execute: async (toolCallId, args, signal) => {
113
- const acknowledgementState = terminalAcknowledgement?.state();
114
- const result = await tool.execute(args, {
115
- toolCallId,
116
- signal: signal ?? new AbortController().signal,
117
- suspendPromptGuards,
118
- });
119
- return {
120
- content: [
121
- {
122
- type: "text",
123
- text: terminalAcknowledgement?.onToolExecuted(acknowledgementState) ??
124
- stringifyToolResult(result),
125
- },
126
- ],
127
- details: result,
128
- };
129
- },
130
- };
131
- }
132
- function getMutableSession(session) {
133
- const candidate = session;
134
- if (!Array.isArray(candidate._customTools) ||
135
- typeof candidate._refreshToolRegistry !== "function") {
136
- throw new Error("AgentSession does not expose the _customTools/_refreshToolRegistry hooks required for temporary tools");
137
- }
138
- return candidate;
139
- }
140
- function toTemporaryToolRegistrationError(error) {
141
- return new Error("Pi SDK version incompatible: temporary tool registration unavailable", error instanceof Error ? { cause: error } : undefined);
142
- }
143
- function validateRequestedActiveTools(requestedToolNames, availableToolNames) {
144
- for (const toolName of requestedToolNames) {
145
- if (!availableToolNames.includes(toolName)) {
146
- throw new Error(`Requested active Pi tool '${toolName}' is not available for this process. Available tools: ${availableToolNames.join(", ")}`);
147
- }
148
- }
149
- }
150
- function toPiRunDetails(input) {
151
- return {
152
- loadedAgentsFiles: input.loadedAgentsFiles.map((file) => ({
153
- path: file.path,
154
- sizeBytes: Buffer.byteLength(file.content, "utf8"),
155
- })),
156
- loadedSkills: input.loadedSkills.map((skill) => ({ name: skill.name, path: skill.path })),
157
- availableToolNames: [...input.availableToolNames],
158
- };
159
- }
160
- function updateAgentMessagesForCurrentLeaf(session) {
161
- const context = session.sessionManager.buildSessionContext();
162
- session.agent.state.messages = context.messages;
163
- }
164
- function activeTurnId(state) {
165
- return state.currentTurnId ?? `turn-${state.turnSequence}`;
166
- }
167
- function readNonEmptyString(value) {
168
- return typeof value === "string" && value.trim() !== "" ? value : null;
169
- }
170
- function readFiniteNumber(value) {
171
- if (typeof value === "number" && Number.isFinite(value)) {
172
- return value;
173
- }
174
- if (typeof value === "string" && value.trim() !== "") {
175
- const parsed = Number(value);
176
- if (Number.isFinite(parsed)) {
177
- return parsed;
178
- }
179
- }
180
- return null;
181
- }
182
- function listRecordKeys(value) {
183
- return Object.keys(value).slice(0, 12);
184
- }
185
- function summarizeAgentMessages(messages) {
186
- if (!Array.isArray(messages)) {
187
- return { messageCount: 0 };
188
- }
189
- const roles = Array.from(new Set(messages
190
- .map((message) => (isObjectLike(message) ? readNonEmptyString(message.role) : null))
191
- .filter((role) => role !== null))).slice(0, 8);
192
- return {
193
- messageCount: messages.length,
194
- ...(roles.length > 0 ? { roles } : {}),
195
- };
196
- }
197
- function readToolCallBlockFromPartial(assistantMessageEvent) {
198
- const contentIndex = readFiniteNumber(assistantMessageEvent.contentIndex);
199
- if (contentIndex === null) {
200
- return null;
201
- }
202
- const partial = isObjectLike(assistantMessageEvent.partial)
203
- ? assistantMessageEvent.partial
204
- : null;
205
- const content = Array.isArray(partial?.content) ? partial.content : null;
206
- const block = content?.[contentIndex];
207
- return isObjectLike(block) && block.type === "toolCall" ? block : null;
208
- }
209
- function extractAssistantPromptError(entry) {
210
- const message = entry.message;
211
- if (message?.role !== "assistant" || message.stopReason !== "error") {
212
- return null;
213
- }
214
- const errorMessage = readNonEmptyString(message.errorMessage) ?? "Pi assistant turn stopped with error";
215
- const error = new Error(errorMessage);
216
- error.stopReason = "error";
217
- const provider = readNonEmptyString(message.provider);
218
- const model = readNonEmptyString(message.model);
219
- if (provider) {
220
- error.provider = provider;
221
- }
222
- if (model) {
223
- error.model = model;
224
- }
225
- return error;
226
- }
227
- function isAssistantEntry(entry) {
228
- const message = entry.message;
229
- return message?.role === "assistant";
230
- }
231
- function extractTextFromMessageContent(content) {
232
- if (typeof content === "string") {
233
- return content;
234
- }
235
- if (!Array.isArray(content)) {
236
- return "";
237
- }
238
- return content
239
- .map((block) => {
240
- if (!isObjectLike(block) || block.type !== "text") {
241
- return "";
242
- }
243
- return typeof block.text === "string" ? block.text : "";
244
- })
245
- .filter((text) => text.trim() !== "")
246
- .join("\n\n");
247
- }
248
- function extractAssistantMarkdown(entry) {
249
- if (!entry || !isAssistantEntry(entry)) {
250
- return null;
251
- }
252
- const text = extractTextFromMessageContent(entry.message?.content).trim();
253
- return text.length > 0 ? text : null;
254
- }
255
- function findFinalAssistantMarkdown(entries) {
256
- for (let index = entries.length - 1; index >= 0; index -= 1) {
257
- const markdown = extractAssistantMarkdown(entries[index]);
258
- if (markdown) {
259
- return markdown;
260
- }
261
- }
262
- return null;
263
- }
264
- function findFinalAssistantPromptError(entries) {
265
- for (let index = entries.length - 1; index >= 0; index -= 1) {
266
- const entry = entries[index];
267
- if (!isAssistantEntry(entry)) {
268
- continue;
269
- }
270
- return extractAssistantPromptError(entry);
271
- }
272
- return null;
273
- }
274
- const TERMINAL_ACKNOWLEDGEMENT_CLEANUP_TIMEOUT_MS = 1_000;
275
- class TerminalAcknowledgementRuntime {
276
- control;
277
- abort;
278
- getLeafEntry;
279
- acknowledgementTurnStarted = false;
280
- timeout = null;
281
- resolveTimeout;
282
- timeoutReached = new Promise((resolve) => {
283
- this.resolveTimeout = resolve;
284
- });
285
- constructor(control, abort, getLeafEntry) {
286
- this.control = control;
287
- this.abort = abort;
288
- this.getLeafEntry = getLeafEntry;
289
- }
290
- state() {
291
- return this.control.state();
292
- }
293
- onToolExecuted(stateBeforeExecution) {
294
- if (stateBeforeExecution !== "open" || this.control.state() !== "outcome_accepted") {
295
- return undefined;
296
- }
297
- if (this.timeout === null) {
298
- this.timeout = setTimeout(() => {
299
- this.control.markFailed(`Terminal acknowledgement exceeded ${this.control.timeoutMs}ms and was ignored`);
300
- this.resolveTimeout();
301
- }, this.control.timeoutMs);
302
- }
303
- return TERMINAL_ACKNOWLEDGEMENT_INSTRUCTION;
304
- }
305
- onBeforeToolCall(toolName) {
306
- if (!this.acknowledgementTurnStarted || this.control.state() !== "outcome_accepted") {
307
- return;
308
- }
309
- this.control.markFailed(`Terminal acknowledgement attempted blocked tool '${toolName}' and was ignored`);
310
- this.clearTimeout();
311
- }
312
- onTurnCompleted(args) {
313
- const state = this.control.state();
314
- if (!this.acknowledgementTurnStarted) {
315
- if (state !== "outcome_accepted")
316
- return null;
317
- this.acknowledgementTurnStarted = true;
318
- return false;
319
- }
320
- if (state === "outcome_accepted") {
321
- const context = isObjectLike(args[0]) ? args[0] : null;
322
- this.settleFromMessage(context?.message);
323
- }
324
- return true;
325
- }
326
- async run(run) {
327
- const runOutcome = run().then(() => ({ kind: "completed" }), (error) => ({ kind: "failed", error }));
328
- const firstOutcome = await Promise.race([
329
- runOutcome,
330
- this.timeoutReached.then(() => ({ kind: "timeout" })),
331
- ]);
332
- if (firstOutcome.kind === "timeout") {
333
- const finalRunOutcome = await this.abortAndAwaitCleanup(runOutcome);
334
- if (this.control.isOperatorAbortRequested() && finalRunOutcome.kind === "failed") {
335
- throw finalRunOutcome.error;
336
- }
337
- return;
338
- }
339
- if (firstOutcome.kind === "completed") {
340
- this.settleAfterRun();
341
- return;
342
- }
343
- if (!this.canIgnoreRunError()) {
344
- throw firstOutcome.error;
345
- }
346
- }
347
- dispose() {
348
- this.clearTimeout();
349
- }
350
- settleAfterRun() {
351
- if (this.control.state() !== "outcome_accepted" ||
352
- !this.acknowledgementTurnStarted ||
353
- this.control.isOperatorAbortRequested()) {
354
- return;
355
- }
356
- this.settleFromMessage(this.getLeafEntry()?.message);
357
- }
358
- canIgnoreRunError() {
359
- if (this.control.isOperatorAbortRequested())
360
- return false;
361
- if (!this.acknowledgementTurnStarted || this.control.state() !== "outcome_accepted") {
362
- return false;
363
- }
364
- const leaf = this.getLeafEntry();
365
- if (!leaf || !extractAssistantPromptError(leaf))
366
- return false;
367
- this.settleFromMessage(leaf.message);
368
- return true;
369
- }
370
- async abortAndAwaitCleanup(runOutcome) {
371
- const abortOutcome = this.abort().then(() => ({ kind: "completed" }), (error) => ({ kind: "failed", error }));
372
- let cleanupTimeout = null;
373
- const cleanupTimedOut = new Promise((resolve) => {
374
- cleanupTimeout = setTimeout(() => resolve(true), TERMINAL_ACKNOWLEDGEMENT_CLEANUP_TIMEOUT_MS);
375
- });
376
- const cleanupOutcome = await Promise.race([
377
- Promise.all([runOutcome, abortOutcome]).then(([finalRunOutcome, finalAbortOutcome]) => ({
378
- finalRunOutcome,
379
- finalAbortOutcome,
380
- })),
381
- cleanupTimedOut,
382
- ]);
383
- if (cleanupTimeout !== null)
384
- clearTimeout(cleanupTimeout);
385
- if (cleanupOutcome === true) {
386
- throw new Error(`Timed-out terminal acknowledgement did not stop within ${TERMINAL_ACKNOWLEDGEMENT_CLEANUP_TIMEOUT_MS}ms`);
387
- }
388
- if (cleanupOutcome.finalAbortOutcome.kind === "failed") {
389
- throw new Error("Failed to abort timed-out terminal acknowledgement", {
390
- cause: cleanupOutcome.finalAbortOutcome.error,
391
- });
392
- }
393
- return cleanupOutcome.finalRunOutcome;
394
- }
395
- settleFromMessage(messageValue) {
396
- const message = isObjectLike(messageValue) ? messageValue : null;
397
- const responseText = extractTextFromMessageContent(message?.content).trim();
398
- const stopReason = readNonEmptyString(message?.stopReason);
399
- if (responseText !== "" && stopReason !== "error" && stopReason !== "aborted") {
400
- this.control.markSucceeded();
401
- }
402
- else {
403
- const reason = readNonEmptyString(message?.errorMessage) ?? stopReason ?? "no assistant text";
404
- this.control.markFailed(`Terminal acknowledgement failed and was ignored: ${reason}`);
405
- }
406
- this.clearTimeout();
407
- }
408
- clearTimeout() {
409
- if (this.timeout === null)
410
- return;
411
- clearTimeout(this.timeout);
412
- this.timeout = null;
413
- }
414
- }
415
- function describeRetryStart(input) {
416
- const retryLabel = input.attempt > 0 && input.maxAttempts > 0
417
- ? `Retry ${input.attempt}/${input.maxAttempts} scheduled`
418
- : input.attempt > 0
419
- ? `Retry ${input.attempt} scheduled`
420
- : "Retry scheduled";
421
- const delayLabel = input.delayMs > 0 ? ` in ${input.delayMs}ms` : "";
422
- return input.errorMessage
423
- ? `${retryLabel}${delayLabel}: ${input.errorMessage}`
424
- : `${retryLabel}${delayLabel}`;
425
- }
426
- function describeRetryEnd(input) {
427
- const attemptLabel = input.attempt === 1 ? "1 retry" : `${input.attempt} retries`;
428
- if (input.success) {
429
- return input.attempt > 0
430
- ? `Retry sequence succeeded after ${attemptLabel}`
431
- : "Retry sequence succeeded";
432
- }
433
- return input.finalError
434
- ? `Retry sequence failed after ${attemptLabel}: ${input.finalError}`
435
- : `Retry sequence failed after ${attemptLabel}`;
436
- }
437
- const INACTIVITY_RESET_EVENT_TYPES = new Set([
438
- "turn.start",
439
- "stream.delta",
440
- "tool.call",
441
- "tool.update",
442
- "tool.result",
443
- "toolcall.start",
444
- "toolcall.delta",
445
- "toolcall.end",
446
- "compaction.start",
447
- "compaction.end",
448
- "error",
449
- "retry.start",
450
- "retry.end",
451
- ]);
452
- export function doesPiEventResetInactivity(event) {
453
- return INACTIVITY_RESET_EVENT_TYPES.has(event.type);
454
- }
455
- function omitType(value) {
456
- const { type: _type, ...rest } = value;
457
- return rest;
458
- }
459
- function normalizePiEventData(value) {
460
- const raw = omitType(value);
461
- const normalized = {};
462
- const partialToolCall = readToolCallBlockFromPartial(raw);
463
- const rawToolCall = isObjectLike(raw.toolCall)
464
- ? raw.toolCall
465
- : isObjectLike(partialToolCall)
466
- ? partialToolCall
467
- : null;
468
- const toolCallId = readNonEmptyString(raw.toolCallId) ?? readNonEmptyString(rawToolCall?.id);
469
- const name = readNonEmptyString(raw.name) ??
470
- readNonEmptyString(raw.toolName) ??
471
- readNonEmptyString(rawToolCall?.name);
472
- if (toolCallId) {
473
- normalized.toolCallId = toolCallId;
474
- }
475
- if (name) {
476
- normalized.name = name;
477
- }
478
- if ("args" in raw && !("arguments" in raw)) {
479
- normalized.arguments = raw.args;
480
- }
481
- else if ("arguments" in raw) {
482
- normalized.arguments = raw.arguments;
483
- }
484
- else if (rawToolCall && "arguments" in rawToolCall) {
485
- normalized.arguments = rawToolCall.arguments;
486
- }
487
- if (rawToolCall && "thoughtSignature" in rawToolCall) {
488
- normalized.thoughtSignature = rawToolCall.thoughtSignature;
489
- }
490
- if ("delta" in raw) {
491
- normalized.delta = raw.delta;
492
- }
493
- if ("partialResult" in raw) {
494
- normalized.partialResult = raw.partialResult;
495
- }
496
- if ("result" in raw) {
497
- normalized.result = raw.result;
498
- }
499
- if ("isError" in raw) {
500
- normalized.isError = raw.isError;
501
- }
502
- for (const [key, entryValue] of Object.entries(raw)) {
503
- if (key === "toolName" || key === "args" || key === "toolCall" || key === "partial") {
504
- continue;
505
- }
506
- if (key in normalized) {
507
- continue;
508
- }
509
- normalized[key] = entryValue;
510
- }
511
- return normalized;
512
- }
513
- function readSessionEventTimestamp(event) {
514
- const eventRecord = isObjectLike(event) ? event : {};
515
- const messageTimestamp = isObjectLike(eventRecord.message)
516
- ? eventRecord.message.timestamp
517
- : undefined;
518
- return toIsoTimestamp(messageTimestamp ?? eventRecord.timestamp);
519
- }
520
- function buildSessionDiagnostic(input) {
521
- return {
522
- level: input.level,
523
- code: input.code,
524
- message: input.message,
525
- timestamp: input.timestamp,
526
- ...(input.turnId ? { turnId: input.turnId } : {}),
527
- ...(input.details ? { details: input.details } : {}),
528
- };
529
- }
530
- function summarizeSessionGlobalDiagnosticDetails(event) {
531
- const raw = omitType(event);
532
- const base = {
533
- category: "session_global",
534
- eventType: event.type,
535
- };
536
- if (event.type === "queue_update") {
537
- return {
538
- ...base,
539
- steeringCount: Array.isArray(event.steering) ? event.steering.length : 0,
540
- followUpCount: Array.isArray(event.followUp) ? event.followUp.length : 0,
541
- };
542
- }
543
- if (event.type === "agent_end") {
544
- return {
545
- ...base,
546
- ...summarizeAgentMessages(event.messages),
547
- };
548
- }
549
- const keys = listRecordKeys(raw);
550
- return keys.length > 0 ? { ...base, keys } : base;
551
- }
552
- function buildKnownSessionGlobalDiagnostic(event, code, message) {
553
- return buildSessionDiagnostic({
554
- level: "info",
555
- code,
556
- message,
557
- timestamp: readSessionEventTimestamp(event),
558
- details: summarizeSessionGlobalDiagnosticDetails(event),
559
- });
560
- }
561
- function buildUnknownSessionEventDiagnostic(event, state) {
562
- const eventType = readNonEmptyString(event.type) ?? "unknown";
563
- const raw = omitType(event);
564
- const keys = listRecordKeys(raw);
565
- return buildSessionDiagnostic({
566
- level: "warn",
567
- code: "pi.session.event_unknown",
568
- message: `Unhandled Pi session event '${eventType}'`,
569
- timestamp: readSessionEventTimestamp(event),
570
- ...(state.currentTurnId ? { turnId: state.currentTurnId } : {}),
571
- details: {
572
- kind: "session.event.unknown",
573
- scope: "agent_session_event",
574
- eventType,
575
- ...(keys.length > 0 ? { keys } : {}),
576
- },
577
- });
578
- }
579
- function buildUnknownAssistantEventDiagnostic(input) {
580
- const assistantEventType = readNonEmptyString(input.assistantMessageEvent.type) ?? "unknown";
581
- const raw = omitType(input.assistantMessageEvent);
582
- const keys = listRecordKeys(raw);
583
- const contentIndex = readFiniteNumber(input.assistantMessageEvent.contentIndex);
584
- return buildSessionDiagnostic({
585
- level: "warn",
586
- code: "pi.session.event_unknown",
587
- message: `Unhandled Pi assistant message_update event '${assistantEventType}'`,
588
- timestamp: input.timestamp,
589
- turnId: input.turnId,
590
- details: {
591
- kind: "session.event.unknown",
592
- scope: "assistant_message_event",
593
- eventType: input.event.type,
594
- assistantEventType,
595
- ...(contentIndex !== null ? { contentIndex } : {}),
596
- ...(keys.length > 0 ? { keys } : {}),
597
- },
598
- });
599
- }
600
- export function translateAgentSessionEventEnvelope(event, state) {
601
- const runtimeEventType = event.type;
602
- if (runtimeEventType === "session_info_changed") {
603
- return {
604
- piEvents: [],
605
- diagnostics: [
606
- buildKnownSessionGlobalDiagnostic(event, "pi.session_info_changed", "Pi session info changed"),
607
- ],
608
- };
609
- }
610
- switch (event.type) {
611
- case "turn_start": {
612
- const rawTurnIndex = event.turnIndex;
613
- const turnIndex = typeof rawTurnIndex === "number" && Number.isFinite(rawTurnIndex)
614
- ? rawTurnIndex
615
- : state.turnSequence + 1;
616
- state.turnSequence = turnIndex;
617
- const turnId = `turn-${turnIndex}`;
618
- state.currentTurnId = turnId;
619
- return {
620
- piEvents: [
621
- {
622
- type: "turn.start",
623
- turnId,
624
- data: {},
625
- timestamp: toIsoTimestamp(event.timestamp),
626
- },
627
- ],
628
- diagnostics: [],
629
- };
630
- }
631
- case "turn_end": {
632
- const turnId = state.currentTurnId ?? `turn-${state.turnSequence}`;
633
- state.currentTurnId = null;
634
- return {
635
- piEvents: [
636
- {
637
- type: "turn.end",
638
- turnId,
639
- data: {},
640
- timestamp: toIsoTimestamp(event.message.timestamp),
641
- },
642
- ],
643
- diagnostics: [],
644
- };
645
- }
646
- case "message_start":
647
- return { piEvents: [], diagnostics: [] };
648
- case "message_update": {
649
- const turnId = state.currentTurnId;
650
- if (!turnId) {
651
- return { piEvents: [], diagnostics: [] };
652
- }
653
- const assistantMessageEvent = event.assistantMessageEvent;
654
- const timestamp = toIsoTimestamp(event.message.timestamp);
655
- switch (event.assistantMessageEvent.type) {
656
- case "text_delta":
657
- return {
658
- piEvents: [
659
- {
660
- type: "stream.delta",
661
- turnId,
662
- data: {
663
- text: event.assistantMessageEvent.delta,
664
- streamType: "text",
665
- },
666
- timestamp,
667
- },
668
- ],
669
- diagnostics: [],
670
- };
671
- case "thinking_delta":
672
- return {
673
- piEvents: [
674
- {
675
- type: "stream.delta",
676
- turnId,
677
- data: {
678
- text: event.assistantMessageEvent.delta,
679
- streamType: "thinking",
680
- },
681
- timestamp,
682
- },
683
- ],
684
- diagnostics: [],
685
- };
686
- case "toolcall_start":
687
- return {
688
- piEvents: [
689
- {
690
- type: "toolcall.start",
691
- turnId,
692
- data: normalizePiEventData(assistantMessageEvent),
693
- timestamp,
694
- },
695
- ],
696
- diagnostics: [],
697
- };
698
- case "toolcall_delta":
699
- return {
700
- piEvents: [
701
- {
702
- type: "toolcall.delta",
703
- turnId,
704
- data: normalizePiEventData(assistantMessageEvent),
705
- timestamp,
706
- },
707
- ],
708
- diagnostics: [],
709
- };
710
- case "toolcall_end":
711
- return {
712
- piEvents: [
713
- {
714
- type: "toolcall.end",
715
- turnId,
716
- data: normalizePiEventData(assistantMessageEvent),
717
- timestamp,
718
- },
719
- ],
720
- diagnostics: [],
721
- };
722
- case "start":
723
- case "done":
724
- case "error":
725
- case "text_start":
726
- case "text_end":
727
- case "thinking_start":
728
- case "thinking_end":
729
- return { piEvents: [], diagnostics: [] };
730
- default:
731
- return {
732
- piEvents: [],
733
- diagnostics: [
734
- buildUnknownAssistantEventDiagnostic({
735
- event,
736
- assistantMessageEvent,
737
- turnId,
738
- timestamp,
739
- }),
740
- ],
741
- };
742
- }
743
- }
744
- case "message_end": {
745
- const assistantMessage = event.message;
746
- const timestamp = toIsoTimestamp(assistantMessage.timestamp);
747
- const piEvents = [];
748
- if (assistantMessage.role === "assistant" && assistantMessage.usage) {
749
- const usage = assistantMessage.usage;
750
- const cacheHitRate = usage.cacheRead + usage.input > 0 ? usage.cacheRead / (usage.cacheRead + usage.input) : 0;
751
- piEvents.push({
752
- type: "usage",
753
- turnId: activeTurnId(state),
754
- data: {
755
- input: usage.input,
756
- output: usage.output,
757
- ...(usage.reasoning !== undefined ? { reasoning: usage.reasoning } : {}),
758
- cacheRead: usage.cacheRead,
759
- cacheWrite: usage.cacheWrite,
760
- totalTokens: usage.totalTokens,
761
- cost: usage.cost,
762
- cacheHitRate,
763
- },
764
- timestamp,
765
- });
766
- }
767
- const errorMessage = readNonEmptyString(assistantMessage.errorMessage);
768
- if (assistantMessage.role === "assistant" &&
769
- assistantMessage.stopReason === "error" &&
770
- errorMessage) {
771
- piEvents.push({
772
- type: "error",
773
- turnId: activeTurnId(state),
774
- data: {
775
- message: errorMessage,
776
- errorMessage,
777
- stopReason: assistantMessage.stopReason,
778
- source: "assistant",
779
- ...(readNonEmptyString(assistantMessage.provider)
780
- ? { provider: assistantMessage.provider }
781
- : {}),
782
- ...(readNonEmptyString(assistantMessage.model)
783
- ? { model: assistantMessage.model }
784
- : {}),
785
- },
786
- timestamp,
787
- });
788
- }
789
- return { piEvents, diagnostics: [] };
790
- }
791
- case "auto_retry_start":
792
- return {
793
- piEvents: [
794
- {
795
- type: "retry.start",
796
- turnId: activeTurnId(state),
797
- data: {
798
- attempt: event.attempt,
799
- maxAttempts: event.maxAttempts,
800
- delayMs: event.delayMs,
801
- errorMessage: event.errorMessage,
802
- message: describeRetryStart({
803
- attempt: event.attempt,
804
- maxAttempts: event.maxAttempts,
805
- delayMs: event.delayMs,
806
- errorMessage: event.errorMessage,
807
- }),
808
- },
809
- timestamp: new Date().toISOString(),
810
- },
811
- ],
812
- diagnostics: [],
813
- };
814
- case "auto_retry_end": {
815
- const finalError = readNonEmptyString(event.finalError);
816
- return {
817
- piEvents: [
818
- {
819
- type: "retry.end",
820
- turnId: activeTurnId(state),
821
- data: {
822
- success: event.success,
823
- attempt: event.attempt,
824
- ...(finalError ? { finalError } : {}),
825
- message: describeRetryEnd({
826
- success: event.success,
827
- attempt: event.attempt,
828
- finalError,
829
- }),
830
- },
831
- timestamp: new Date().toISOString(),
832
- },
833
- ],
834
- diagnostics: [],
835
- };
836
- }
837
- case "tool_execution_start":
838
- return {
839
- piEvents: [
840
- {
841
- type: "tool.call",
842
- turnId: state.currentTurnId ?? `turn-tool-${event.toolCallId}`,
843
- data: {
844
- toolCallId: event.toolCallId,
845
- name: event.toolName,
846
- arguments: event.args,
847
- },
848
- timestamp: new Date().toISOString(),
849
- },
850
- ],
851
- diagnostics: [],
852
- };
853
- case "tool_execution_update":
854
- return {
855
- piEvents: [
856
- {
857
- type: "tool.update",
858
- turnId: state.currentTurnId ?? `turn-tool-${event.toolCallId}`,
859
- data: normalizePiEventData(event),
860
- timestamp: readSessionEventTimestamp(event),
861
- },
862
- ],
863
- diagnostics: [],
864
- };
865
- case "tool_execution_end": {
866
- const turnId = state.currentTurnId ?? `turn-tool-${event.toolCallId}`;
867
- const timestamp = new Date().toISOString();
868
- const toolResultEvent = {
869
- type: "tool.result",
870
- turnId,
871
- data: {
872
- toolCallId: event.toolCallId,
873
- name: event.toolName,
874
- result: event.result,
875
- isError: event.isError,
876
- },
877
- timestamp,
878
- };
879
- if (!event.isError) {
880
- return { piEvents: [toolResultEvent], diagnostics: [] };
881
- }
882
- return {
883
- piEvents: [
884
- toolResultEvent,
885
- {
886
- type: "error",
887
- turnId,
888
- data: {
889
- message: typeof event.result === "string" ? event.result : stringifyToolResult(event.result),
890
- errorMessage: typeof event.result === "string" ? event.result : stringifyToolResult(event.result),
891
- toolName: event.toolName,
892
- source: "tool",
893
- },
894
- timestamp,
895
- },
896
- ],
897
- diagnostics: [],
898
- };
899
- }
900
- case "compaction_start":
901
- return {
902
- piEvents: [
903
- {
904
- type: "compaction.start",
905
- turnId: activeTurnId(state),
906
- data: normalizePiEventData(event),
907
- timestamp: readSessionEventTimestamp(event),
908
- },
909
- ],
910
- diagnostics: [],
911
- };
912
- case "compaction_end":
913
- return {
914
- piEvents: [
915
- {
916
- type: "compaction.end",
917
- turnId: activeTurnId(state),
918
- data: normalizePiEventData(event),
919
- timestamp: readSessionEventTimestamp(event),
920
- },
921
- ],
922
- diagnostics: [],
923
- };
924
- case "agent_start":
925
- return {
926
- piEvents: [],
927
- diagnostics: [
928
- buildKnownSessionGlobalDiagnostic(event, "pi.agent_start", "Pi agent run started"),
929
- ],
930
- };
931
- case "agent_end":
932
- return {
933
- piEvents: [],
934
- diagnostics: [
935
- buildKnownSessionGlobalDiagnostic(event, "pi.agent_end", "Pi agent run ended"),
936
- ],
937
- };
938
- case "agent_settled":
939
- return {
940
- piEvents: [],
941
- diagnostics: [
942
- buildKnownSessionGlobalDiagnostic(event, "pi.agent_settled", "Pi agent run settled"),
943
- ],
944
- };
945
- case "queue_update":
946
- return {
947
- piEvents: [],
948
- diagnostics: [
949
- buildKnownSessionGlobalDiagnostic(event, "pi.queue_update", "Pi session queue updated"),
950
- ],
951
- };
952
- default:
953
- return {
954
- piEvents: [],
955
- diagnostics: [buildUnknownSessionEventDiagnostic(event, state)],
956
- };
957
- }
958
- }
959
- export class SdkPiTreeHandle {
960
- session;
961
- sessionId;
962
- treeFile;
963
- isResumed;
964
- eventState = { currentTurnId: null, turnSequence: 0 };
965
- eventHandlers = new Set();
966
- diagnosticHandlers = new Set();
967
- sessionUnsubscribe = null;
968
- continuationRetryAbortController = null;
969
- availableToolNames;
970
- runDetails;
971
- constructor(session, options) {
972
- this.session = session;
973
- this.sessionId = session.sessionId;
974
- this.treeFile = options.treeFile;
975
- this.isResumed = options.isResumed;
976
- this.availableToolNames = [...options.availableToolNames];
977
- this.runDetails = {
978
- loadedAgentsFiles: options.runDetails.loadedAgentsFiles.map((file) => ({ ...file })),
979
- loadedSkills: options.runDetails.loadedSkills.map((skill) => ({ ...skill })),
980
- availableToolNames: [...options.runDetails.availableToolNames],
981
- };
982
- }
983
- getRunDetails() {
984
- return {
985
- loadedAgentsFiles: this.runDetails.loadedAgentsFiles.map((file) => ({ ...file })),
986
- loadedSkills: this.runDetails.loadedSkills.map((skill) => ({ ...skill })),
987
- availableToolNames: [...this.runDetails.availableToolNames],
988
- };
989
- }
990
- getLeafId() {
991
- return this.session.sessionManager.getLeafId();
992
- }
993
- getEntry(id) {
994
- return this.session.sessionManager.getEntry(id);
995
- }
996
- getBranch(fromId) {
997
- return this.session.sessionManager.getBranch(fromId);
998
- }
999
- getChildren(parentId) {
1000
- return this.session.sessionManager.getChildren(parentId);
1001
- }
1002
- getTree() {
1003
- return this.session.sessionManager.getTree();
1004
- }
1005
- async branch(entryId) {
1006
- this.session.sessionManager.branch(entryId);
1007
- updateAgentMessagesForCurrentLeaf(this.session);
1008
- }
1009
- async branchFromRoot() {
1010
- this.session.sessionManager.resetLeaf();
1011
- updateAgentMessagesForCurrentLeaf(this.session);
1012
- }
1013
- async resetLeaf() {
1014
- await this.branchFromRoot();
1015
- }
1016
- async compact(customInstructions, details) {
1017
- if (details === undefined) {
1018
- const result = await this.session.compact(customInstructions);
1019
- updateAgentMessagesForCurrentLeaf(this.session);
1020
- return result;
1021
- }
1022
- const sessionManager = this.session.sessionManager;
1023
- if (typeof sessionManager.appendCompaction !== "function") {
1024
- throw new Error("Pi SDK version incompatible: compaction detail insertion unavailable");
1025
- }
1026
- const appendCompaction = sessionManager.appendCompaction;
1027
- let appendCount = 0;
1028
- sessionManager.appendCompaction = (summary, firstKeptEntryId, tokensBefore, _originalDetails, fromHook) => {
1029
- appendCount += 1;
1030
- return appendCompaction.call(sessionManager, summary, firstKeptEntryId, tokensBefore, details, fromHook);
1031
- };
1032
- try {
1033
- const result = await this.session.compact(customInstructions);
1034
- if (appendCount !== 1) {
1035
- throw new Error(`Pi SDK compaction detail insertion expected one append, received ${appendCount}`);
1036
- }
1037
- updateAgentMessagesForCurrentLeaf(this.session);
1038
- return result;
1039
- }
1040
- finally {
1041
- sessionManager.appendCompaction = appendCompaction;
1042
- }
1043
- }
1044
- async withToolConfiguration(options, run) {
1045
- const customTools = options.tools ?? [];
1046
- const requestedActiveToolNames = options.activeTools !== undefined ? [...options.activeTools] : [];
1047
- validateRequestedActiveTools(requestedActiveToolNames, this.availableToolNames);
1048
- const previousActiveToolNames = this.session.getActiveToolNames();
1049
- const needsRuntimeHooks = options.shouldBlockToolCall !== undefined || options.terminalAcknowledgement !== undefined;
1050
- if (customTools.length === 0 &&
1051
- !needsRuntimeHooks &&
1052
- previousActiveToolNames.length === requestedActiveToolNames.length &&
1053
- previousActiveToolNames.every((toolName, index) => toolName === requestedActiveToolNames[index])) {
1054
- return run();
1055
- }
1056
- let mutableSession;
1057
- try {
1058
- mutableSession = getMutableSession(this.session);
1059
- }
1060
- catch (error) {
1061
- throw toTemporaryToolRegistrationError(error);
1062
- }
1063
- const mutableAgent = this.session.agent;
1064
- const previousCustomTools = [...mutableSession._customTools];
1065
- const previousBeforeToolCall = mutableAgent.beforeToolCall;
1066
- const previousCreateLoopConfig = mutableAgent.createLoopConfig;
1067
- const loopConfigHook = previousCreateLoopConfig;
1068
- if (options.terminalAcknowledgement && typeof loopConfigHook !== "function") {
1069
- throw new Error("Pi SDK version incompatible: agent loop configuration hook unavailable");
1070
- }
1071
- const terminalAcknowledgement = options.terminalAcknowledgement
1072
- ? new TerminalAcknowledgementRuntime(options.terminalAcknowledgement, () => this.abortTurn(), () => {
1073
- const leafId = this.getLeafId();
1074
- return leafId ? this.getEntry(leafId) : undefined;
1075
- })
1076
- : null;
1077
- const tempDefinitions = customTools.map((tool) => toToolDefinition(tool, terminalAcknowledgement, options.suspendPromptGuards));
1078
- mutableSession._customTools = [...previousCustomTools, ...tempDefinitions];
1079
- mutableSession._refreshToolRegistry({
1080
- activeToolNames: [
1081
- ...new Set([...requestedActiveToolNames, ...tempDefinitions.map((tool) => tool.name)]),
1082
- ],
1083
- });
1084
- if (needsRuntimeHooks) {
1085
- mutableAgent.beforeToolCall = async (context, signal) => {
1086
- terminalAcknowledgement?.onBeforeToolCall(context.toolCall.name);
1087
- const blockedReason = options.shouldBlockToolCall?.(context.toolCall.name);
1088
- if (blockedReason) {
1089
- return { block: true, reason: blockedReason };
1090
- }
1091
- return await previousBeforeToolCall?.(context, signal);
1092
- };
1093
- if (terminalAcknowledgement && typeof loopConfigHook === "function") {
1094
- mutableAgent.createLoopConfig = (loopOptions) => {
1095
- const baseConfig = loopConfigHook.call(mutableAgent, loopOptions);
1096
- const previousShouldStop = baseConfig.shouldStopAfterTurn;
1097
- return {
1098
- ...baseConfig,
1099
- shouldStopAfterTurn: async (...args) => {
1100
- const acknowledgementDecision = terminalAcknowledgement?.onTurnCompleted(args) ?? null;
1101
- if (acknowledgementDecision !== null) {
1102
- return acknowledgementDecision;
1103
- }
1104
- if (typeof previousShouldStop === "function") {
1105
- return await previousShouldStop(...args);
1106
- }
1107
- return false;
1108
- },
1109
- };
1110
- };
1111
- }
1112
- }
1113
- try {
1114
- if (terminalAcknowledgement) {
1115
- await terminalAcknowledgement.run(run);
1116
- }
1117
- else {
1118
- await run();
1119
- }
1120
- }
1121
- finally {
1122
- terminalAcknowledgement?.dispose();
1123
- mutableSession._customTools = previousCustomTools;
1124
- mutableAgent.beforeToolCall = previousBeforeToolCall;
1125
- mutableAgent.createLoopConfig = previousCreateLoopConfig;
1126
- mutableSession._refreshToolRegistry({
1127
- activeToolNames: previousActiveToolNames,
1128
- });
1129
- }
1130
- }
1131
- /**
1132
- * Pi 0.81 has no public session-level continue API. Mirror its public retry
1133
- * contract for a retained prompt leaf without calling private session methods.
1134
- */
1135
- async runRetryAwareContinuation() {
1136
- const controller = new AbortController();
1137
- this.continuationRetryAbortController = controller;
1138
- try {
1139
- await retryAssistantCall(async () => {
1140
- await this.session.agent.continue();
1141
- const leafId = this.getLeafId();
1142
- const message = leafId ? this.getEntry(leafId)?.message : undefined;
1143
- if (message?.role !== "assistant") {
1144
- throw new Error("Pi continuation completed without an assistant message");
1145
- }
1146
- return message;
1147
- }, this.session.settingsManager.getRetrySettings(), controller.signal, {
1148
- onRetryScheduled: (attempt, maxAttempts, delayMs, errorMessage) => {
1149
- this.emitSessionEvent({
1150
- type: "auto_retry_start",
1151
- attempt,
1152
- maxAttempts,
1153
- delayMs,
1154
- errorMessage,
1155
- });
1156
- const messages = this.session.agent.state.messages;
1157
- if (messages.at(-1)?.role === "assistant") {
1158
- this.session.agent.state.messages = messages.slice(0, -1);
1159
- }
1160
- },
1161
- onRetryFinished: (success, attempt, finalError) => this.emitSessionEvent({
1162
- type: "auto_retry_end",
1163
- success,
1164
- attempt,
1165
- finalError: controller.signal.aborted ? "Retry cancelled" : finalError,
1166
- }),
1167
- });
1168
- await this.session.waitForIdle();
1169
- }
1170
- finally {
1171
- if (this.continuationRetryAbortController === controller) {
1172
- this.continuationRetryAbortController = null;
1173
- }
1174
- }
1175
- }
1176
- createExecutionBranchSnapshot() {
1177
- const startLeafId = this.getLeafId();
1178
- const beforeEntryIds = new Set(this.session.sessionManager.getEntries().map((entry) => entry.id));
1179
- return {
1180
- startLeafId,
1181
- createdEntries: () => this.session.sessionManager.getEntries().filter((entry) => !beforeEntryIds.has(entry.id)),
1182
- assertResult: (operation, anchorEntryId, resultEntryId) => assertResultStayedOnExecutionBranch({
1183
- operation,
1184
- startLeafId,
1185
- beforeEntryIds,
1186
- anchorEntryId,
1187
- resultEntryId,
1188
- getBranch: (entryId) => this.getBranch(entryId),
1189
- }),
1190
- };
1191
- }
1192
- async captureTurnExecutionResult(operation, run, missingLeafMessage, terminalAcknowledgement) {
1193
- const branch = this.createExecutionBranchSnapshot();
1194
- const readVerifiedCreatedEntries = (resultEntryId) => {
1195
- const createdEntries = branch.createdEntries();
1196
- branch.assertResult(operation, resolveExecutionAnchorEntryId({
1197
- operation,
1198
- startLeafId: branch.startLeafId,
1199
- createdEntries,
1200
- }), resultEntryId);
1201
- return createdEntries;
1202
- };
1203
- try {
1204
- await run();
1205
- }
1206
- catch (error) {
1207
- try {
1208
- readVerifiedCreatedEntries(this.getLeafId());
1209
- }
1210
- catch (driftError) {
1211
- if (isPiBranchDriftError(driftError)) {
1212
- throw driftError;
1213
- }
1214
- }
1215
- throw error;
1216
- }
1217
- const endLeafId = this.getLeafId();
1218
- if (!endLeafId) {
1219
- throw new Error(missingLeafMessage);
1220
- }
1221
- const createdEntries = readVerifiedCreatedEntries(endLeafId);
1222
- const createdEntryIds = createdEntries.map((entry) => entry.id);
1223
- const resultBranchEntryIds = new Set(this.getBranch(endLeafId).map((entry) => entry.id));
1224
- const branchCreatedEntries = createdEntries.filter((entry) => resultBranchEntryIds.has(entry.id));
1225
- const promptError = findFinalAssistantPromptError(branchCreatedEntries);
1226
- if (promptError && terminalAcknowledgement?.state() !== "acknowledgement_failed_ignored") {
1227
- throw promptError;
1228
- }
1229
- return {
1230
- startLeafId: branch.startLeafId,
1231
- endLeafId,
1232
- createdEntryIds,
1233
- resultEntryId: endLeafId,
1234
- assistantMarkdown: findFinalAssistantMarkdown(branchCreatedEntries),
1235
- };
1236
- }
1237
- async executePrompt(options, run) {
1238
- return await this.captureTurnExecutionResult("prompt", () => this.withToolConfiguration(options, run), "Pi prompt completed without an active leaf", options.terminalAcknowledgement);
1239
- }
1240
- async prompt(text, options = {}) {
1241
- return await this.executePrompt(options, () => this.session.prompt(text));
1242
- }
1243
- async promptLiteral(text, options = {}) {
1244
- return await this.executePrompt(options, () => this.session.sendUserMessage(text));
1245
- }
1246
- async promptCustom(input, options = {}) {
1247
- return await this.executePrompt(options, () => this.session.sendCustomMessage({ customType: "leitwerk", ...input, display: input.display ?? false }, { triggerTurn: true }));
1248
- }
1249
- async continueTurn(options = {}) {
1250
- updateAgentMessagesForCurrentLeaf(this.session);
1251
- return await this.captureTurnExecutionResult("continue", () => this.withToolConfiguration(options, () => this.runRetryAwareContinuation()), "Pi continuation completed without an active leaf", options.terminalAcknowledgement);
1252
- }
1253
- async appendCustomMessage(input) {
1254
- const branch = this.createExecutionBranchSnapshot();
1255
- const sessionManager = this.session
1256
- .sessionManager;
1257
- if (typeof sessionManager.appendCustomMessageEntry !== "function") {
1258
- throw new Error("Pi SDK version incompatible: custom message insertion unavailable");
1259
- }
1260
- const entryId = sessionManager.appendCustomMessageEntry("leitwerk", input.content, input.display ?? false, input.details);
1261
- updateAgentMessagesForCurrentLeaf(this.session);
1262
- const endLeafId = this.getLeafId();
1263
- if (endLeafId !== entryId) {
1264
- throw new PiBranchDriftError({
1265
- operation: "continue",
1266
- anchorEntryId: entryId,
1267
- rejectedResultEntryId: endLeafId ?? entryId,
1268
- });
1269
- }
1270
- branch.assertResult("continue", entryId, entryId);
1271
- return entryId;
1272
- }
1273
- async steer(text) {
1274
- await this.session.steer(text);
1275
- }
1276
- async abortTurn() {
1277
- this.continuationRetryAbortController?.abort(new Error("Retry cancelled"));
1278
- await this.session.abort();
1279
- }
1280
- subscribe(handler) {
1281
- this.eventHandlers.add(handler);
1282
- this.ensureSessionSubscription();
1283
- return () => {
1284
- this.eventHandlers.delete(handler);
1285
- this.releaseSessionSubscriptionIfIdle();
1286
- };
1287
- }
1288
- subscribeDiagnostics(handler) {
1289
- this.diagnosticHandlers.add(handler);
1290
- this.ensureSessionSubscription();
1291
- return () => {
1292
- this.diagnosticHandlers.delete(handler);
1293
- this.releaseSessionSubscriptionIfIdle();
1294
- };
1295
- }
1296
- ensureSessionSubscription() {
1297
- if (this.sessionUnsubscribe) {
1298
- return;
1299
- }
1300
- this.sessionUnsubscribe = this.session.subscribe((event) => this.emitSessionEvent(event));
1301
- }
1302
- emitSessionEvent(event) {
1303
- const translated = translateAgentSessionEventEnvelope(event, this.eventState);
1304
- for (const piEvent of translated.piEvents)
1305
- this.emitSubscribedEvent(piEvent);
1306
- for (const diagnostic of translated.diagnostics)
1307
- this.emitSubscribedDiagnostic(diagnostic);
1308
- }
1309
- releaseSessionSubscriptionIfIdle() {
1310
- if (!this.sessionUnsubscribe ||
1311
- this.eventHandlers.size > 0 ||
1312
- this.diagnosticHandlers.size > 0) {
1313
- return;
1314
- }
1315
- const unsubscribe = this.sessionUnsubscribe;
1316
- this.sessionUnsubscribe = null;
1317
- unsubscribe();
1318
- }
1319
- emitSubscribedEvent(event) {
1320
- for (const handler of this.eventHandlers) {
1321
- try {
1322
- handler(event);
1323
- }
1324
- catch (error) {
1325
- console.warn("Pi event subscriber failed", error);
1326
- }
1327
- }
1328
- }
1329
- emitSubscribedDiagnostic(diagnostic) {
1330
- for (const handler of this.diagnosticHandlers) {
1331
- try {
1332
- handler(diagnostic);
1333
- }
1334
- catch (error) {
1335
- console.warn("Pi diagnostic subscriber failed", error);
1336
- }
1337
- }
1338
- }
1339
- async close() {
1340
- if (this.sessionUnsubscribe) {
1341
- this.sessionUnsubscribe();
1342
- this.sessionUnsubscribe = null;
1343
- }
1344
- this.eventHandlers.clear();
1345
- this.diagnosticHandlers.clear();
1346
- if (this.session.isStreaming) {
1347
- try {
1348
- await this.session.abort();
1349
- }
1350
- catch (error) {
1351
- console.warn(`Failed to abort streaming Pi handle '${this.sessionId}' during close`, error);
1352
- }
1353
- }
1354
- this.session.dispose();
1355
- }
1356
- }
1357
- function collectPiRuntimeDiagnostics(services) {
1358
- const extensionLoadDiagnostics = services.resourceLoader
1359
- .getExtensions()
1360
- .errors.map(({ path: extensionPath, error }) => ({
1361
- type: "error",
1362
- message: `Extension '${extensionPath}' failed to load: ${error}`,
1363
- }));
1364
- const resourceDiagnostics = [
1365
- ...services.resourceLoader.getSkills().diagnostics,
1366
- ...services.resourceLoader.getPrompts().diagnostics,
1367
- ...services.resourceLoader.getThemes().diagnostics,
1368
- ].map((diagnostic) => ({
1369
- type: diagnostic.type === "error" ? "error" : diagnostic.type,
1370
- message: diagnostic.message,
1371
- }));
1372
- return [...services.diagnostics, ...extensionLoadDiagnostics, ...resourceDiagnostics];
1373
- }
1374
- function pathIsWithin(root, candidate) {
1375
- const relative = path.relative(path.resolve(root), path.resolve(candidate));
1376
- return relative === "" || (!relative.startsWith(`..${path.sep}`) && relative !== "..");
1377
- }
1378
- function assertLoadedPathAllowed(input) {
1379
- if (pathIsWithin(input.agentDir, input.path))
1380
- return;
1381
- const aggregatedAgentsPath = path.join(input.workspaceRoot, "AGENTS.md");
1382
- const aggregatedSkillsRoot = path.join(input.workspaceRoot, ".leitwerk", "skills");
1383
- if (path.resolve(input.path) === path.resolve(aggregatedAgentsPath) ||
1384
- pathIsWithin(aggregatedSkillsRoot, input.path)) {
1385
- return;
1386
- }
1387
- throw new Error(`Pi ${input.kind} loaded outside the managed resource snapshot or approved process workspace inputs: ${input.path}`);
1388
- }
1389
- function validateManagedLoadedResources(input) {
1390
- const extensions = input.services.resourceLoader.getExtensions().extensions;
1391
- const skills = input.services.resourceLoader.getSkills().skills;
1392
- const prompts = input.services.resourceLoader.getPrompts().prompts;
1393
- const agentsFiles = input.services.resourceLoader.getAgentsFiles().agentsFiles;
1394
- for (const extension of extensions) {
1395
- assertLoadedPathAllowed({
1396
- path: extension.resolvedPath,
1397
- agentDir: input.agentDir,
1398
- workspaceRoot: input.workspaceRoot,
1399
- kind: "extension",
1400
- });
1401
- }
1402
- for (const skill of skills) {
1403
- assertLoadedPathAllowed({
1404
- path: skill.filePath,
1405
- agentDir: input.agentDir,
1406
- workspaceRoot: input.workspaceRoot,
1407
- kind: "skill",
1408
- });
1409
- }
1410
- for (const prompt of prompts) {
1411
- assertLoadedPathAllowed({
1412
- path: prompt.filePath,
1413
- agentDir: input.agentDir,
1414
- workspaceRoot: input.workspaceRoot,
1415
- kind: "prompt",
1416
- });
1417
- }
1418
- for (const agentsFile of agentsFiles) {
1419
- assertLoadedPathAllowed({
1420
- path: agentsFile.path,
1421
- agentDir: input.agentDir,
1422
- workspaceRoot: input.workspaceRoot,
1423
- kind: "context file",
1424
- });
1425
- }
1426
- const loadedResourceIds = [];
1427
- for (const resource of input.manifest.provenance) {
1428
- const expectedPath = path.resolve(input.agentDir, resource.snapshotPath);
1429
- let loaded = resource.kind === "generated";
1430
- if (resource.kind === "extension") {
1431
- loaded = extensions.some((extension) => path.resolve(extension.resolvedPath) === expectedPath);
1432
- }
1433
- else if (resource.kind === "skill") {
1434
- loaded = skills.some((skill) => pathIsWithin(skill.baseDir, expectedPath));
1435
- }
1436
- else if (resource.kind === "prompt") {
1437
- loaded = prompts.some((prompt) => path.resolve(prompt.filePath) === expectedPath);
1438
- }
1439
- if (!loaded) {
1440
- throw new Error(`Pi did not load declared ${resource.kind} resource '${resource.snapshotPath}'`);
1441
- }
1442
- loadedResourceIds.push(resource.snapshotPath);
1443
- }
1444
- return loadedResourceIds;
1445
- }
1446
- async function createManagedAgentSessionServices(input) {
1447
- const { createAgentSessionServices, ModelRuntime, SettingsManager } = await import("@earendil-works/pi-coding-agent");
1448
- const settingsManager = SettingsManager.create(input.sessionCwd, input.agentDir);
1449
- const modelRuntime = await ModelRuntime.create({
1450
- authPath: path.join(input.agentDir, "auth.json"),
1451
- modelsPath: path.join(input.agentDir, "models.json"),
1452
- });
1453
- return createAgentSessionServices({
1454
- cwd: input.sessionCwd,
1455
- agentDir: input.agentDir,
1456
- modelRuntime,
1457
- settingsManager,
1458
- resourceLoaderOptions: await buildLeitwerkResourceLoaderOptions(input.workspaceRoot, input.agentDir, {
1459
- systemPrompt: input.piConfig?.systemPrompt,
1460
- appendSystemPrompt: input.piConfig?.appendSystemPrompt,
1461
- }),
1462
- });
1463
- }
1464
- function formatPiRuntimeDiagnostics(diagnostics) {
1465
- const messages = (diagnostics ?? [])
1466
- .filter((diagnostic) => diagnostic.type === undefined || diagnostic.type === "error")
1467
- .map((diagnostic) => diagnostic.message.trim())
1468
- .filter((message) => message.length > 0);
1469
- if (messages.length === 0) {
1470
- return "";
1471
- }
1472
- return ` Pi extension diagnostics: ${messages.join("; ")}`;
1473
- }
1474
- function resolveModelSelection(modelProfileId, configSnapshot, modelRuntime, diagnostics) {
1475
- if (!modelProfileId) {
1476
- return {};
1477
- }
1478
- const profile = configSnapshot?.pi.model_profiles.find((candidate) => candidate.id === modelProfileId);
1479
- if (!profile) {
1480
- throw new Error(`Unknown model profile '${modelProfileId}'`);
1481
- }
1482
- const model = modelRuntime.getModel(profile.provider, profile.model_id);
1483
- if (!model) {
1484
- throw new Error(`Unable to resolve configured model '${profile.provider}/${profile.model_id}' for profile '${modelProfileId}'.${formatPiRuntimeDiagnostics(diagnostics)}`);
1485
- }
1486
- return {
1487
- model,
1488
- thinkingLevel: profile.thinking_level,
1489
- };
1490
- }
1491
- function isAlreadyExistsError(error) {
1492
- return (typeof error === "object" &&
1493
- error !== null &&
1494
- "code" in error &&
1495
- error.code === "EEXIST");
1496
- }
1497
- async function ensureSessionFileExists(input) {
1498
- await mkdir(path.dirname(input.treeFile), { recursive: true });
1499
- const header = {
1500
- type: "session",
1501
- version: input.sessionVersion,
1502
- id: input.instanceId,
1503
- timestamp: new Date().toISOString(),
1504
- cwd: input.sessionCwd,
1505
- };
1506
- try {
1507
- await writeFile(input.treeFile, `${JSON.stringify(header)}\n`, { flag: "wx" });
1508
- }
1509
- catch (error) {
1510
- if (isAlreadyExistsError(error)) {
1511
- return;
1512
- }
1513
- throw error;
1514
- }
1515
- }
1516
- function applyPiRetryOverrides(services, configSnapshot) {
1517
- const piRetryConfig = configSnapshot?.pi.retry;
1518
- const retryOverrides = {
1519
- enabled: piRetryConfig?.enabled ?? true,
1520
- maxRetries: piRetryConfig?.max_retries ?? 3,
1521
- baseDelayMs: parseDurationMs(piRetryConfig?.base_delay ?? "2s", 2_000, {
1522
- allowHours: true,
1523
- }),
1524
- provider: {
1525
- ...(piRetryConfig?.provider.timeout
1526
- ? {
1527
- timeoutMs: parseDurationMs(piRetryConfig.provider.timeout, 0, {
1528
- allowHours: true,
1529
- }),
1530
- }
1531
- : {}),
1532
- ...(piRetryConfig?.provider.max_retries !== null &&
1533
- piRetryConfig?.provider.max_retries !== undefined
1534
- ? { maxRetries: piRetryConfig.provider.max_retries }
1535
- : {}),
1536
- maxRetryDelayMs: parseDurationMs(piRetryConfig?.provider.max_retry_delay ?? "60s", 60_000, {
1537
- allowHours: true,
1538
- }),
1539
- },
1540
- };
1541
- services.settingsManager.applyOverrides({ retry: retryOverrides });
1542
- }
1543
- function managedServicesKey(agentDir, sessionCwd) {
1544
- return `${path.resolve(agentDir)}\0${path.resolve(sessionCwd)}`;
1545
- }
1546
- export class SdkPiTreeHandleFactory {
1547
- preparedServices = new Map();
1548
- async prepareManagedBootstrap(opts) {
1549
- const services = await createManagedAgentSessionServices({
1550
- agentDir: opts.agentDir,
1551
- sessionCwd: opts.sessionCwd,
1552
- workspaceRoot: opts.workspaceRoot,
1553
- piConfig: opts.piConfig,
1554
- });
1555
- applyPiRetryOverrides(services, opts.configSnapshot);
1556
- const diagnostics = collectPiRuntimeDiagnostics(services);
1557
- const fatalDiagnostics = diagnostics.filter((diagnostic) => diagnostic.type === undefined || diagnostic.type === "error");
1558
- if (fatalDiagnostics.length > 0) {
1559
- throw new Error(`Pi managed bootstrap failed.${formatPiRuntimeDiagnostics(fatalDiagnostics)}`);
1560
- }
1561
- const model = services.modelRuntime.getModel(opts.expectedModel.providerId, opts.expectedModel.modelId);
1562
- if (!model) {
1563
- throw new Error(`Unable to resolve managed Pi model '${opts.expectedModel.providerId}/${opts.expectedModel.modelId}'.${formatPiRuntimeDiagnostics(diagnostics)}`);
1564
- }
1565
- const loadedResourceIds = validateManagedLoadedResources({
1566
- services,
1567
- manifest: opts.manifest,
1568
- agentDir: opts.agentDir,
1569
- workspaceRoot: opts.workspaceRoot,
1570
- });
1571
- const runDetails = toPiRunDetails({
1572
- loadedAgentsFiles: services.resourceLoader.getAgentsFiles().agentsFiles,
1573
- loadedSkills: services.resourceLoader.getSkills().skills.map((skill) => ({
1574
- name: skill.name,
1575
- path: skill.filePath,
1576
- })),
1577
- availableToolNames: opts.piConfig?.availableToolNames ?? [],
1578
- });
1579
- this.preparedServices.set(managedServicesKey(opts.agentDir, opts.sessionCwd), services);
1580
- return {
1581
- loadedResourceIds,
1582
- loadedAgentsFiles: runDetails.loadedAgentsFiles,
1583
- loadedSkillFiles: runDetails.loadedSkills,
1584
- resolvedModel: { ...opts.expectedModel },
1585
- diagnostics: diagnostics.map((diagnostic) => diagnostic.message),
1586
- };
1587
- }
1588
- async inspectPrimaryTree(opts) {
1589
- return inspectPiTreeForPlanning(opts);
1590
- }
1591
- async createPrimaryTreeHandle(opts) {
1592
- const { CURRENT_SESSION_VERSION, createAgentSessionFromServices, SessionManager } = await import("@earendil-works/pi-coding-agent");
1593
- const agentDir = resolvePiAgentDir({
1594
- agentDir: opts.agentDir,
1595
- configSnapshot: opts.configSnapshot,
1596
- fallbackDir: opts.workspaceRoot,
1597
- });
1598
- const sessionCwd = opts.sessionCwd ?? opts.workspaceRoot;
1599
- const availableToolNames = opts.piConfig?.availableToolNames ?? [];
1600
- const key = managedServicesKey(agentDir, sessionCwd);
1601
- const preparedServices = this.preparedServices.get(key);
1602
- if (preparedServices)
1603
- this.preparedServices.delete(key);
1604
- const services = preparedServices ??
1605
- (await createManagedAgentSessionServices({
1606
- agentDir,
1607
- sessionCwd,
1608
- workspaceRoot: opts.workspaceRoot,
1609
- piConfig: opts.piConfig,
1610
- }));
1611
- if (!preparedServices)
1612
- applyPiRetryOverrides(services, opts.configSnapshot);
1613
- await ensureSessionFileExists({
1614
- treeFile: opts.treeFile,
1615
- instanceId: opts.instanceId,
1616
- sessionCwd,
1617
- sessionVersion: CURRENT_SESSION_VERSION,
1618
- });
1619
- const sessionManager = SessionManager.open(opts.treeFile, path.dirname(opts.treeFile), sessionCwd);
1620
- const modelSelection = resolveModelSelection(opts.modelProfileId, opts.configSnapshot, services.modelRuntime, collectPiRuntimeDiagnostics(services));
1621
- const { session } = await createAgentSessionFromServices({
1622
- services,
1623
- sessionManager,
1624
- ...(modelSelection.model ? { model: modelSelection.model } : {}),
1625
- ...(modelSelection.thinkingLevel
1626
- ? { thinkingLevel: modelSelection.thinkingLevel }
1627
- : {}),
1628
- customTools: [LEITWERK_TOOL_BOOTSTRAP],
1629
- noTools: "builtin",
1630
- });
1631
- getMutableSession(session)._refreshToolRegistry({ activeToolNames: [] });
1632
- const runDetails = toPiRunDetails({
1633
- loadedAgentsFiles: services.resourceLoader.getAgentsFiles().agentsFiles,
1634
- loadedSkills: services.resourceLoader.getSkills().skills.map((skill) => ({
1635
- name: skill.name,
1636
- path: skill.filePath,
1637
- })),
1638
- availableToolNames,
1639
- });
1640
- return new SdkPiTreeHandle(session, {
1641
- treeFile: opts.treeFile,
1642
- isResumed: opts.resume,
1643
- availableToolNames,
1644
- runDetails,
1645
- });
1646
- }
1647
- }
1648
- //# sourceMappingURL=pi-adapter.js.map