@leitwerk-dev/worker 0.1.9 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (240) hide show
  1. package/dist/automatic-turn-executor.d.ts +1 -0
  2. package/dist/automatic-turn-executor.d.ts.map +1 -1
  3. package/dist/{chunk-O6332GRG.js → chunk-2LLFMCR6.js} +1511 -1071
  4. package/dist/chunk-2LLFMCR6.js.map +1 -0
  5. package/dist/connection-diagnostics.d.ts +5 -0
  6. package/dist/connection-diagnostics.d.ts.map +1 -0
  7. package/dist/container-entry-main.d.ts +2 -0
  8. package/dist/container-entry-main.d.ts.map +1 -0
  9. package/dist/container-entry-main.js +232 -0
  10. package/dist/container-entry-main.js.map +1 -0
  11. package/dist/container-entry.d.ts +14 -0
  12. package/dist/container-entry.d.ts.map +1 -0
  13. package/dist/development-tool-environment.d.ts +84 -0
  14. package/dist/development-tool-environment.d.ts.map +1 -0
  15. package/dist/diagnostics.d.ts +4 -0
  16. package/dist/diagnostics.d.ts.map +1 -1
  17. package/dist/docker-registry-credentials.d.ts +8 -0
  18. package/dist/docker-registry-credentials.d.ts.map +1 -0
  19. package/dist/entry-runtime.d.ts +19 -0
  20. package/dist/entry-runtime.d.ts.map +1 -1
  21. package/dist/index.d.ts +3 -5
  22. package/dist/index.d.ts.map +1 -1
  23. package/dist/index.js +10 -5
  24. package/dist/index.js.map +1 -1
  25. package/dist/input-consumer.d.ts +7 -11
  26. package/dist/input-consumer.d.ts.map +1 -1
  27. package/dist/ipc.d.ts +10 -0
  28. package/dist/ipc.d.ts.map +1 -1
  29. package/dist/logical-prompt-runner.d.ts.map +1 -1
  30. package/dist/managed-pi-agent-dir.d.ts +8 -1
  31. package/dist/managed-pi-agent-dir.d.ts.map +1 -1
  32. package/dist/managed-pi-bootstrap.d.ts +1 -0
  33. package/dist/managed-pi-bootstrap.d.ts.map +1 -1
  34. package/dist/missing-tool-recovery-runner.d.ts +4 -3
  35. package/dist/missing-tool-recovery-runner.d.ts.map +1 -1
  36. package/dist/pi-adapter.d.ts +88 -1
  37. package/dist/pi-adapter.d.ts.map +1 -1
  38. package/dist/pi-event-reporter.d.ts.map +1 -1
  39. package/dist/pi-resource-bundle.d.ts +17 -1
  40. package/dist/pi-resource-bundle.d.ts.map +1 -1
  41. package/dist/pre-turn-targeted-inputs.d.ts +8 -7
  42. package/dist/pre-turn-targeted-inputs.d.ts.map +1 -1
  43. package/dist/prompt-guards.d.ts +6 -0
  44. package/dist/prompt-guards.d.ts.map +1 -1
  45. package/dist/repository-bash-tool.d.ts +4 -0
  46. package/dist/repository-bash-tool.d.ts.map +1 -0
  47. package/dist/resource-loader-factory.d.ts +1 -2
  48. package/dist/resource-loader-factory.d.ts.map +1 -1
  49. package/dist/result-image-upload.d.ts.map +1 -1
  50. package/dist/runtime/adapters.d.ts +38 -0
  51. package/dist/runtime/adapters.d.ts.map +1 -1
  52. package/dist/runtime/bootstrap-session.d.ts +9 -5
  53. package/dist/runtime/bootstrap-session.d.ts.map +1 -1
  54. package/dist/runtime/bootstrap.d.ts +38 -18
  55. package/dist/runtime/bootstrap.d.ts.map +1 -1
  56. package/dist/runtime/failure-policy.d.ts +1 -0
  57. package/dist/runtime/failure-policy.d.ts.map +1 -1
  58. package/dist/runtime/index.d.ts +4 -1
  59. package/dist/runtime/index.d.ts.map +1 -1
  60. package/dist/runtime/lifecycle-reducer.d.ts.map +1 -1
  61. package/dist/runtime/llm-turn-execution.d.ts +3 -8
  62. package/dist/runtime/llm-turn-execution.d.ts.map +1 -1
  63. package/dist/runtime/turn-execution.d.ts +2 -9
  64. package/dist/runtime/turn-execution.d.ts.map +1 -1
  65. package/dist/session-snapshot-exchange.d.ts +10 -4
  66. package/dist/session-snapshot-exchange.d.ts.map +1 -1
  67. package/dist/turn-continuation.d.ts.map +1 -1
  68. package/dist/turn-execution-error.d.ts +1 -1
  69. package/dist/turn-execution-error.d.ts.map +1 -1
  70. package/dist/turn-execution-result.d.ts +1 -0
  71. package/dist/turn-execution-result.d.ts.map +1 -1
  72. package/dist/turn-outcome-tool-session.d.ts +0 -2
  73. package/dist/turn-outcome-tool-session.d.ts.map +1 -1
  74. package/dist/turn-result-markdown.d.ts +2 -1
  75. package/dist/turn-result-markdown.d.ts.map +1 -1
  76. package/dist/turn-tree-strategy.d.ts +0 -1
  77. package/dist/turn-tree-strategy.d.ts.map +1 -1
  78. package/dist/worker-entry.js +16 -4
  79. package/dist/worker-entry.js.map +1 -1
  80. package/dist/worker-ipc-reporter.d.ts.map +1 -1
  81. package/dist/workspace/manifest.d.ts +4 -7
  82. package/dist/workspace/manifest.d.ts.map +1 -1
  83. package/dist/workspace/node-run-root-git-ops.d.ts +2 -2
  84. package/dist/workspace/node-run-root-git-ops.d.ts.map +1 -1
  85. package/dist/workspace/resource-aggregator.d.ts.map +1 -1
  86. package/dist/workspace/run-root.d.ts +21 -20
  87. package/dist/workspace/run-root.d.ts.map +1 -1
  88. package/package.json +8 -8
  89. package/src/automatic-turn-executor.ts +2 -0
  90. package/src/connection-diagnostics.ts +27 -0
  91. package/src/container-entry-main.ts +24 -0
  92. package/src/container-entry.ts +246 -0
  93. package/src/development-tool-environment.ts +490 -0
  94. package/src/diagnostics.ts +1 -0
  95. package/src/docker-registry-credentials.ts +65 -0
  96. package/src/entry-runtime.ts +29 -5
  97. package/src/index.ts +1 -39
  98. package/src/input-consumer.ts +8 -29
  99. package/src/ipc.ts +50 -2
  100. package/src/logical-prompt-runner.ts +23 -29
  101. package/src/managed-pi-agent-dir.ts +8 -1
  102. package/src/managed-pi-bootstrap.ts +4 -3
  103. package/src/missing-tool-recovery-runner.ts +4 -18
  104. package/src/pi-adapter.ts +125 -56
  105. package/src/pi-event-reporter.ts +16 -38
  106. package/src/pi-resource-bundle.ts +77 -3
  107. package/src/pre-turn-targeted-inputs.ts +9 -11
  108. package/src/prompt-guards.ts +50 -75
  109. package/src/repository-bash-tool.ts +15 -0
  110. package/src/resource-loader-factory.ts +1 -18
  111. package/src/result-image-upload.ts +16 -27
  112. package/src/runtime/adapters.ts +46 -4
  113. package/src/runtime/bootstrap-session.ts +70 -39
  114. package/src/runtime/bootstrap.ts +184 -101
  115. package/src/runtime/failure-policy.ts +36 -42
  116. package/src/runtime/index.ts +47 -15
  117. package/src/runtime/lifecycle-reducer.ts +71 -173
  118. package/src/runtime/llm-turn-execution.ts +13 -30
  119. package/src/runtime/turn-execution.ts +78 -31
  120. package/src/session-snapshot-exchange.ts +46 -68
  121. package/src/turn-continuation.ts +9 -17
  122. package/src/turn-execution-error.ts +3 -11
  123. package/src/turn-execution-result.ts +1 -0
  124. package/src/turn-outcome-tool-session.ts +25 -21
  125. package/src/turn-result-markdown.ts +31 -34
  126. package/src/turn-tree-strategy.ts +6 -19
  127. package/src/worker-entry.ts +8 -0
  128. package/src/worker-ipc-reporter.ts +8 -16
  129. package/src/workspace/manifest.ts +5 -7
  130. package/src/workspace/node-run-root-git-ops.ts +65 -25
  131. package/src/workspace/resource-aggregator.ts +5 -16
  132. package/src/workspace/run-root.ts +50 -89
  133. package/dist/automatic-turn-executor.js +0 -58
  134. package/dist/automatic-turn-executor.js.map +0 -1
  135. package/dist/chunk-O6332GRG.js.map +0 -1
  136. package/dist/diagnostics.js +0 -51
  137. package/dist/diagnostics.js.map +0 -1
  138. package/dist/entry-runtime.js +0 -160
  139. package/dist/entry-runtime.js.map +0 -1
  140. package/dist/event-translator.js +0 -12
  141. package/dist/event-translator.js.map +0 -1
  142. package/dist/extension-entry-roots.js +0 -41
  143. package/dist/extension-entry-roots.js.map +0 -1
  144. package/dist/identified-pi-entry.js +0 -125
  145. package/dist/identified-pi-entry.js.map +0 -1
  146. package/dist/input-consumer.js +0 -34
  147. package/dist/input-consumer.js.map +0 -1
  148. package/dist/integration-tool-bridge.js +0 -53
  149. package/dist/integration-tool-bridge.js.map +0 -1
  150. package/dist/ipc.js +0 -192
  151. package/dist/ipc.js.map +0 -1
  152. package/dist/logical-prompt-runner.js +0 -225
  153. package/dist/logical-prompt-runner.js.map +0 -1
  154. package/dist/managed-pi-agent-dir.js +0 -66
  155. package/dist/managed-pi-agent-dir.js.map +0 -1
  156. package/dist/managed-pi-bootstrap.js +0 -135
  157. package/dist/managed-pi-bootstrap.js.map +0 -1
  158. package/dist/missing-tool-recovery-runner.js +0 -73
  159. package/dist/missing-tool-recovery-runner.js.map +0 -1
  160. package/dist/pi-adapter.js +0 -1648
  161. package/dist/pi-adapter.js.map +0 -1
  162. package/dist/pi-branch-guard.js +0 -75
  163. package/dist/pi-branch-guard.js.map +0 -1
  164. package/dist/pi-event-reporter.js +0 -136
  165. package/dist/pi-event-reporter.js.map +0 -1
  166. package/dist/pi-resource-bundle.js +0 -58
  167. package/dist/pi-resource-bundle.js.map +0 -1
  168. package/dist/pre-turn-targeted-inputs.js +0 -101
  169. package/dist/pre-turn-targeted-inputs.js.map +0 -1
  170. package/dist/prompt-guards.js +0 -318
  171. package/dist/prompt-guards.js.map +0 -1
  172. package/dist/question-bridge.js +0 -24
  173. package/dist/question-bridge.js.map +0 -1
  174. package/dist/question-tool.js +0 -54
  175. package/dist/question-tool.js.map +0 -1
  176. package/dist/replaying-request-bridge.js +0 -71
  177. package/dist/replaying-request-bridge.js.map +0 -1
  178. package/dist/resource-loader-factory.js +0 -87
  179. package/dist/resource-loader-factory.js.map +0 -1
  180. package/dist/result-image-upload.js +0 -183
  181. package/dist/result-image-upload.js.map +0 -1
  182. package/dist/runtime/adapters.js +0 -15
  183. package/dist/runtime/adapters.js.map +0 -1
  184. package/dist/runtime/bootstrap-session.js +0 -199
  185. package/dist/runtime/bootstrap-session.js.map +0 -1
  186. package/dist/runtime/bootstrap.js +0 -440
  187. package/dist/runtime/bootstrap.js.map +0 -1
  188. package/dist/runtime/failure-policy.js +0 -182
  189. package/dist/runtime/failure-policy.js.map +0 -1
  190. package/dist/runtime/index.js +0 -339
  191. package/dist/runtime/index.js.map +0 -1
  192. package/dist/runtime/lifecycle-reducer.js +0 -1142
  193. package/dist/runtime/lifecycle-reducer.js.map +0 -1
  194. package/dist/runtime/llm-turn-execution.js +0 -494
  195. package/dist/runtime/llm-turn-execution.js.map +0 -1
  196. package/dist/runtime/settings.js +0 -24
  197. package/dist/runtime/settings.js.map +0 -1
  198. package/dist/runtime/snapshot-policy.js +0 -16
  199. package/dist/runtime/snapshot-policy.js.map +0 -1
  200. package/dist/runtime/turn-execution.js +0 -151
  201. package/dist/runtime/turn-execution.js.map +0 -1
  202. package/dist/session-snapshot-exchange.js +0 -102
  203. package/dist/session-snapshot-exchange.js.map +0 -1
  204. package/dist/test-helpers/fake-websocket.js +0 -40
  205. package/dist/test-helpers/fake-websocket.js.map +0 -1
  206. package/dist/test-helpers/ipc-harness.d.ts +0 -11
  207. package/dist/test-helpers/ipc-harness.d.ts.map +0 -1
  208. package/dist/test-helpers/ipc-harness.js +0 -17
  209. package/dist/test-helpers/ipc-harness.js.map +0 -1
  210. package/dist/turn-continuation.js +0 -80
  211. package/dist/turn-continuation.js.map +0 -1
  212. package/dist/turn-execution-error.js +0 -64
  213. package/dist/turn-execution-error.js.map +0 -1
  214. package/dist/turn-execution-result.js +0 -21
  215. package/dist/turn-execution-result.js.map +0 -1
  216. package/dist/turn-outcome-tool-session.js +0 -210
  217. package/dist/turn-outcome-tool-session.js.map +0 -1
  218. package/dist/turn-record-id.js +0 -10
  219. package/dist/turn-record-id.js.map +0 -1
  220. package/dist/turn-result-markdown.js +0 -263
  221. package/dist/turn-result-markdown.js.map +0 -1
  222. package/dist/turn-tree-strategy.js +0 -80
  223. package/dist/turn-tree-strategy.js.map +0 -1
  224. package/dist/worker-http.js +0 -9
  225. package/dist/worker-http.js.map +0 -1
  226. package/dist/worker-ipc-reporter.js +0 -58
  227. package/dist/worker-ipc-reporter.js.map +0 -1
  228. package/dist/worker-payloads.js +0 -66
  229. package/dist/worker-payloads.js.map +0 -1
  230. package/dist/worker-start-payload.js +0 -5
  231. package/dist/worker-start-payload.js.map +0 -1
  232. package/dist/workspace/manifest.js +0 -79
  233. package/dist/workspace/manifest.js.map +0 -1
  234. package/dist/workspace/node-run-root-git-ops.js +0 -96
  235. package/dist/workspace/node-run-root-git-ops.js.map +0 -1
  236. package/dist/workspace/resource-aggregator.js +0 -39
  237. package/dist/workspace/resource-aggregator.js.map +0 -1
  238. package/dist/workspace/run-root.js +0 -209
  239. package/dist/workspace/run-root.js.map +0 -1
  240. package/src/test-helpers/ipc-harness.ts +0 -19
package/src/pi-adapter.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { access, mkdir, writeFile } from "node:fs/promises";
2
2
  import path from "node:path";
3
- import { type AssistantMessage, retryAssistantCall } from "@earendil-works/pi-ai";
3
+ import type { AssistantMessage } from "@earendil-works/pi-ai";
4
4
  import type {
5
5
  AgentSession,
6
6
  AgentSessionEvent,
@@ -8,6 +8,7 @@ import type {
8
8
  ModelRuntime,
9
9
  ToolDefinition,
10
10
  } from "@earendil-works/pi-coding-agent";
11
+ import { readFiniteNumber, readNonBlankString as readNonEmptyString } from "@leitwerk-dev/domain";
11
12
  import type {
12
13
  PiCustomMessageInput,
13
14
  PiCustomTool,
@@ -22,7 +23,9 @@ import type {
22
23
  PiTreeHandle,
23
24
  PiTreeNode,
24
25
  PiTurnExecutionResult,
26
+ PiUsageData,
25
27
  } from "@leitwerk-dev/process-sdk";
28
+ import { hasErrorCode, isEnoent } from "@leitwerk-dev/process-sdk";
26
29
  import { resolvePiAgentDir } from "@leitwerk-dev/process-sdk/pi-config";
27
30
  import type { ConfigSnapshot } from "@leitwerk-dev/protocol";
28
31
  import { parseDurationMs } from "@leitwerk-dev/watcher-utils";
@@ -34,6 +37,7 @@ import {
34
37
  type PiBranchOperation,
35
38
  resolveExecutionAnchorEntryId,
36
39
  } from "./pi-branch-guard.js";
40
+ import { createRepositoryBashTool } from "./repository-bash-tool.js";
37
41
  import { buildLeitwerkResourceLoaderOptions } from "./resource-loader-factory.js";
38
42
 
39
43
  const LEITWERK_TOOL_BOOTSTRAP_NAME = "__leitwerk_runtime_bootstrap__";
@@ -48,7 +52,6 @@ export type {
48
52
  PiRunDetails,
49
53
  PiSessionDiagnostic,
50
54
  PiSessionDiagnosticHandler,
51
- PiSessionDiagnosticLevel,
52
55
  PiTreeEntry,
53
56
  PiTreeHandle,
54
57
  PiTreeNode,
@@ -56,53 +59,110 @@ export type {
56
59
  } from "@leitwerk-dev/process-sdk";
57
60
  export { isPiBranchDriftError, PiBranchDriftError } from "./pi-branch-guard.js";
58
61
 
62
+ /** @public */
59
63
  export interface PiTreeHandleOptions {
64
+ /** @internal */
60
65
  instanceId: string;
66
+ /** @internal */
61
67
  treeFile: string;
68
+ /** @public */
62
69
  workspaceRoot: string;
70
+ /** @public */
63
71
  sessionCwd?: string;
72
+ /** @internal */
64
73
  resume: boolean;
74
+ /** @internal */
65
75
  agentDir?: string;
76
+ /** @internal */
66
77
  configSnapshot?: ConfigSnapshot;
78
+ /** @internal */
67
79
  modelProfileId?: string | null;
80
+ /** @internal */
68
81
  piConfig?: {
82
+ /** @internal */
69
83
  systemPrompt?: string;
84
+ /** @internal */
70
85
  appendSystemPrompt?: string;
86
+ /** @internal */
71
87
  availableToolNames: string[];
72
88
  };
73
89
  }
74
90
 
91
+ /** @internal */
75
92
  export interface PiManagedBootstrapOptions {
93
+ /** @internal */
76
94
  agentDir: string;
95
+ /** @internal */
77
96
  workspaceRoot: string;
97
+ /** @internal */
78
98
  sessionCwd: string;
99
+ /** @internal */
79
100
  configSnapshot: ConfigSnapshot;
101
+ /** @internal */
80
102
  piConfig: PiTreeHandleOptions["piConfig"];
103
+ /** @internal */
81
104
  manifest: ManagedPiResourceManifest;
82
- expectedModel: { providerId: string; modelId: string };
105
+ /** @internal */
106
+ expectedModel: {
107
+ /** @internal */
108
+ providerId: string;
109
+ /** @internal */
110
+ modelId: string;
111
+ };
83
112
  }
84
113
 
114
+ /** @internal */
85
115
  export interface PiManagedBootstrapResult {
116
+ /** @internal */
86
117
  loadedResourceIds: string[];
87
- loadedAgentsFiles: Array<{ path: string; sizeBytes: number }>;
88
- loadedSkillFiles: Array<{ name: string; path: string }>;
89
- resolvedModel: { providerId: string; modelId: string };
118
+ /** @internal */
119
+ loadedAgentsFiles: Array<{
120
+ /** @internal */
121
+ path: string;
122
+ /** @internal */
123
+ sizeBytes: number;
124
+ }>;
125
+ /** @internal */
126
+ loadedSkillFiles: Array<{
127
+ /** @internal */
128
+ name: string;
129
+ /** @internal */
130
+ path: string;
131
+ }>;
132
+ /** @internal */
133
+ resolvedModel: {
134
+ /** @internal */
135
+ providerId: string;
136
+ /** @internal */
137
+ modelId: string;
138
+ };
139
+ /** @internal */
90
140
  diagnostics: string[];
91
141
  }
92
142
 
143
+ /** @public */
93
144
  export interface PiTreeHandleFactory {
145
+ /** @internal */
94
146
  prepareManagedBootstrap(opts: PiManagedBootstrapOptions): Promise<PiManagedBootstrapResult>;
147
+ /** @internal */
95
148
  inspectPrimaryTree(opts: PiTreePlanningOptions): Promise<PiTreePlanningSnapshot>;
149
+ /** @internal */
96
150
  createPrimaryTreeHandle(opts: PiTreeHandleOptions): Promise<PiTreeHandle>;
97
151
  }
98
152
 
153
+ /** @internal */
99
154
  export interface PiTreePlanningOptions {
155
+ /** @internal */
100
156
  treeFile: string;
157
+ /** @internal */
101
158
  sessionCwd: string;
102
159
  }
103
160
 
161
+ /** @internal */
104
162
  export interface PiTreePlanningSnapshot {
163
+ /** @internal */
105
164
  currentLeafId: string | null;
165
+ /** @internal */
106
166
  entries: readonly Pick<PiTreeEntry, "id" | "parentId">[];
107
167
  }
108
168
 
@@ -113,12 +173,7 @@ export async function inspectPiTreeForPlanning(
113
173
  try {
114
174
  await access(input.treeFile);
115
175
  } catch (error) {
116
- if (
117
- typeof error === "object" &&
118
- error !== null &&
119
- "code" in error &&
120
- (error as { code?: unknown }).code === "ENOENT"
121
- ) {
176
+ if (isEnoent(error)) {
122
177
  return { currentLeafId: null, entries: [] };
123
178
  }
124
179
  throw error;
@@ -364,23 +419,6 @@ function activeTurnId(state: { currentTurnId: string | null; turnSequence: numbe
364
419
  return state.currentTurnId ?? `turn-${state.turnSequence}`;
365
420
  }
366
421
 
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
422
  function listRecordKeys(value: Record<string, unknown>): string[] {
385
423
  return Object.keys(value).slice(0, 12);
386
424
  }
@@ -702,8 +740,11 @@ function describeRetryEnd(input: {
702
740
  : `Retry sequence failed after ${attemptLabel}`;
703
741
  }
704
742
 
743
+ /** @internal */
705
744
  export interface AgentSessionEventTranslation {
745
+ /** @internal */
706
746
  piEvents: PiEvent[];
747
+ /** @internal */
707
748
  diagnostics: PiSessionDiagnostic[];
708
749
  }
709
750
 
@@ -723,6 +764,7 @@ const INACTIVITY_RESET_EVENT_TYPES = new Set<PiEventType>([
723
764
  "retry.end",
724
765
  ]);
725
766
 
767
+ /** @internal */
726
768
  export function doesPiEventResetInactivity(event: PiEvent): boolean {
727
769
  return INACTIVITY_RESET_EVENT_TYPES.has(event.type);
728
770
  }
@@ -901,9 +943,15 @@ function buildUnknownAssistantEventDiagnostic(input: {
901
943
  });
902
944
  }
903
945
 
946
+ /** @internal */
904
947
  export function translateAgentSessionEventEnvelope(
905
948
  event: AgentSessionEvent,
906
- state: { currentTurnId: string | null; turnSequence: number },
949
+ state: {
950
+ /** @internal */
951
+ currentTurnId: string | null;
952
+ /** @internal */
953
+ turnSequence: number;
954
+ },
907
955
  ): AgentSessionEventTranslation {
908
956
  const runtimeEventType = (event as unknown as { type?: unknown }).type;
909
957
  if (runtimeEventType === "session_info_changed") {
@@ -1064,21 +1112,7 @@ export function translateAgentSessionEventEnvelope(
1064
1112
  provider: string;
1065
1113
  model: string;
1066
1114
  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
- };
1115
+ usage: Omit<PiUsageData, "cacheHitRate">;
1082
1116
  }>;
1083
1117
  const timestamp = toIsoTimestamp(assistantMessage.timestamp);
1084
1118
  const piEvents: PiEvent[] = [];
@@ -1299,9 +1333,13 @@ export function translateAgentSessionEventEnvelope(
1299
1333
  }
1300
1334
  }
1301
1335
 
1336
+ /** @internal */
1302
1337
  export class SdkPiTreeHandle implements PiTreeHandle {
1338
+ /** @internal */
1303
1339
  readonly sessionId: string;
1340
+ /** @internal */
1304
1341
  readonly treeFile: string;
1342
+ /** @internal */
1305
1343
  readonly isResumed: boolean;
1306
1344
 
1307
1345
  private readonly eventState = { currentTurnId: null as string | null, turnSequence: 0 };
@@ -1312,12 +1350,17 @@ export class SdkPiTreeHandle implements PiTreeHandle {
1312
1350
  private readonly availableToolNames: string[];
1313
1351
  private readonly runDetails: PiRunDetails;
1314
1352
 
1353
+ /** @internal */
1315
1354
  constructor(
1316
1355
  private readonly session: AgentSession,
1317
1356
  options: {
1357
+ /** @internal */
1318
1358
  treeFile: string;
1359
+ /** @internal */
1319
1360
  isResumed: boolean;
1361
+ /** @internal */
1320
1362
  availableToolNames: string[];
1363
+ /** @internal */
1321
1364
  runDetails: PiRunDetails;
1322
1365
  },
1323
1366
  ) {
@@ -1332,6 +1375,7 @@ export class SdkPiTreeHandle implements PiTreeHandle {
1332
1375
  };
1333
1376
  }
1334
1377
 
1378
+ /** @internal */
1335
1379
  getRunDetails(): PiRunDetails {
1336
1380
  return {
1337
1381
  loadedAgentsFiles: this.runDetails.loadedAgentsFiles.map((file) => ({ ...file })),
@@ -1340,40 +1384,49 @@ export class SdkPiTreeHandle implements PiTreeHandle {
1340
1384
  };
1341
1385
  }
1342
1386
 
1387
+ /** @internal */
1343
1388
  getLeafId(): string | null {
1344
1389
  return this.session.sessionManager.getLeafId();
1345
1390
  }
1346
1391
 
1392
+ /** @internal */
1347
1393
  getEntry(id: string): PiTreeEntry | undefined {
1348
1394
  return this.session.sessionManager.getEntry(id) as PiTreeEntry | undefined;
1349
1395
  }
1350
1396
 
1397
+ /** @internal */
1351
1398
  getBranch(fromId?: string): PiTreeEntry[] {
1352
1399
  return this.session.sessionManager.getBranch(fromId) as PiTreeEntry[];
1353
1400
  }
1354
1401
 
1402
+ /** @internal */
1355
1403
  getChildren(parentId: string): PiTreeEntry[] {
1356
1404
  return this.session.sessionManager.getChildren(parentId) as PiTreeEntry[];
1357
1405
  }
1358
1406
 
1407
+ /** @internal */
1359
1408
  getTree(): PiTreeNode[] {
1360
1409
  return this.session.sessionManager.getTree() as unknown as PiTreeNode[];
1361
1410
  }
1362
1411
 
1412
+ /** @internal */
1363
1413
  async branch(entryId: string): Promise<void> {
1364
1414
  this.session.sessionManager.branch(entryId);
1365
1415
  updateAgentMessagesForCurrentLeaf(this.session);
1366
1416
  }
1367
1417
 
1418
+ /** @internal */
1368
1419
  async branchFromRoot(): Promise<void> {
1369
1420
  this.session.sessionManager.resetLeaf();
1370
1421
  updateAgentMessagesForCurrentLeaf(this.session);
1371
1422
  }
1372
1423
 
1424
+ /** @internal */
1373
1425
  async resetLeaf(): Promise<void> {
1374
1426
  await this.branchFromRoot();
1375
1427
  }
1376
1428
 
1429
+ /** @internal */
1377
1430
  async compact(customInstructions?: string, details?: unknown): Promise<unknown> {
1378
1431
  if (details === undefined) {
1379
1432
  const result = await this.session.compact(customInstructions);
@@ -1531,6 +1584,7 @@ export class SdkPiTreeHandle implements PiTreeHandle {
1531
1584
  const controller = new AbortController();
1532
1585
  this.continuationRetryAbortController = controller;
1533
1586
  try {
1587
+ const { retryAssistantCall } = await import("@earendil-works/pi-ai");
1534
1588
  await retryAssistantCall(
1535
1589
  async () => {
1536
1590
  await this.session.agent.continue();
@@ -1668,14 +1722,17 @@ export class SdkPiTreeHandle implements PiTreeHandle {
1668
1722
  );
1669
1723
  }
1670
1724
 
1725
+ /** @internal */
1671
1726
  async prompt(text: string, options: PiPromptOptions = {}): Promise<PiTurnExecutionResult> {
1672
1727
  return await this.executePrompt(options, () => this.session.prompt(text));
1673
1728
  }
1674
1729
 
1730
+ /** @internal */
1675
1731
  async promptLiteral(text: string, options: PiPromptOptions = {}): Promise<PiTurnExecutionResult> {
1676
1732
  return await this.executePrompt(options, () => this.session.sendUserMessage(text));
1677
1733
  }
1678
1734
 
1735
+ /** @internal */
1679
1736
  async promptCustom(
1680
1737
  input: PiCustomMessageInput,
1681
1738
  options: PiPromptOptions = {},
@@ -1688,6 +1745,7 @@ export class SdkPiTreeHandle implements PiTreeHandle {
1688
1745
  );
1689
1746
  }
1690
1747
 
1748
+ /** @internal */
1691
1749
  async continueTurn(options: PiPromptOptions = {}): Promise<PiTurnExecutionResult> {
1692
1750
  updateAgentMessagesForCurrentLeaf(this.session);
1693
1751
  return await this.captureTurnExecutionResult(
@@ -1698,6 +1756,7 @@ export class SdkPiTreeHandle implements PiTreeHandle {
1698
1756
  );
1699
1757
  }
1700
1758
 
1759
+ /** @internal */
1701
1760
  async appendCustomMessage(input: PiCustomMessageInput): Promise<string> {
1702
1761
  const branch = this.createExecutionBranchSnapshot();
1703
1762
  const sessionManager = this.session
@@ -1724,15 +1783,18 @@ export class SdkPiTreeHandle implements PiTreeHandle {
1724
1783
  return entryId;
1725
1784
  }
1726
1785
 
1786
+ /** @internal */
1727
1787
  async steer(text: string): Promise<void> {
1728
1788
  await this.session.steer(text);
1729
1789
  }
1730
1790
 
1791
+ /** @internal */
1731
1792
  async abortTurn(): Promise<void> {
1732
1793
  this.continuationRetryAbortController?.abort(new Error("Retry cancelled"));
1733
1794
  await this.session.abort();
1734
1795
  }
1735
1796
 
1797
+ /** @internal */
1736
1798
  subscribe(handler: PiEventHandler): () => void {
1737
1799
  this.eventHandlers.add(handler);
1738
1800
  this.ensureSessionSubscription();
@@ -1742,6 +1804,7 @@ export class SdkPiTreeHandle implements PiTreeHandle {
1742
1804
  };
1743
1805
  }
1744
1806
 
1807
+ /** @internal */
1745
1808
  subscribeDiagnostics(handler: PiSessionDiagnosticHandler): () => void {
1746
1809
  this.diagnosticHandlers.add(handler);
1747
1810
  this.ensureSessionSubscription();
@@ -1797,6 +1860,7 @@ export class SdkPiTreeHandle implements PiTreeHandle {
1797
1860
  }
1798
1861
  }
1799
1862
 
1863
+ /** @internal */
1800
1864
  async close(): Promise<void> {
1801
1865
  if (this.sessionUnsubscribe) {
1802
1866
  this.sessionUnsubscribe();
@@ -2002,15 +2066,6 @@ function resolveModelSelection(
2002
2066
  };
2003
2067
  }
2004
2068
 
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
2069
  async function ensureSessionFileExists(input: {
2015
2070
  treeFile: string;
2016
2071
  instanceId: string;
@@ -2028,7 +2083,7 @@ async function ensureSessionFileExists(input: {
2028
2083
  try {
2029
2084
  await writeFile(input.treeFile, `${JSON.stringify(header)}\n`, { flag: "wx" });
2030
2085
  } catch (error) {
2031
- if (isAlreadyExistsError(error)) {
2086
+ if (hasErrorCode(error, "EEXIST")) {
2032
2087
  return;
2033
2088
  }
2034
2089
  throw error;
@@ -2070,9 +2125,18 @@ function managedServicesKey(agentDir: string, sessionCwd: string): string {
2070
2125
  return `${path.resolve(agentDir)}\0${path.resolve(sessionCwd)}`;
2071
2126
  }
2072
2127
 
2128
+ /** @internal */
2073
2129
  export class SdkPiTreeHandleFactory implements PiTreeHandleFactory {
2074
2130
  private readonly preparedServices = new Map<string, AgentSessionServices>();
2075
2131
 
2132
+ /** @internal */
2133
+ constructor() {
2134
+ // Module loading can overlap IPC connection and workspace materialization.
2135
+ // Bootstrap awaits the same module and reports any import failure.
2136
+ void import("@earendil-works/pi-coding-agent").catch(() => undefined);
2137
+ }
2138
+
2139
+ /** @internal */
2076
2140
  async prepareManagedBootstrap(
2077
2141
  opts: PiManagedBootstrapOptions,
2078
2142
  ): Promise<PiManagedBootstrapResult> {
@@ -2125,10 +2189,12 @@ export class SdkPiTreeHandleFactory implements PiTreeHandleFactory {
2125
2189
  };
2126
2190
  }
2127
2191
 
2192
+ /** @internal */
2128
2193
  async inspectPrimaryTree(opts: PiTreePlanningOptions): Promise<PiTreePlanningSnapshot> {
2129
2194
  return inspectPiTreeForPlanning(opts);
2130
2195
  }
2131
2196
 
2197
+ /** @internal */
2132
2198
  async createPrimaryTreeHandle(opts: PiTreeHandleOptions): Promise<PiTreeHandle> {
2133
2199
  const { CURRENT_SESSION_VERSION, createAgentSessionFromServices, SessionManager } =
2134
2200
  await import("@earendil-works/pi-coding-agent");
@@ -2175,7 +2241,10 @@ export class SdkPiTreeHandleFactory implements PiTreeHandleFactory {
2175
2241
  ...(modelSelection.thinkingLevel
2176
2242
  ? { thinkingLevel: modelSelection.thinkingLevel as never }
2177
2243
  : {}),
2178
- customTools: [LEITWERK_TOOL_BOOTSTRAP],
2244
+ customTools: [
2245
+ LEITWERK_TOOL_BOOTSTRAP,
2246
+ (await createRepositoryBashTool(sessionCwd)) as ToolDefinition,
2247
+ ],
2179
2248
  noTools: "builtin",
2180
2249
  });
2181
2250
  getMutableSession(session)._refreshToolRegistry({ activeToolNames: [] });
@@ -1,3 +1,4 @@
1
+ import { readFiniteNumber, readNonBlankString } from "@leitwerk-dev/domain";
1
2
  import { translatePiEvent } from "./event-translator.js";
2
3
  import type { PiEvent, PiSessionDiagnostic, PiTreeHandle } from "./pi-adapter.js";
3
4
  import type { WorkerIpcReporter } from "./worker-ipc-reporter.js";
@@ -15,25 +16,6 @@ export interface PiEventReporterOptions {
15
16
  onLifecycleObservation?(kind: "pi_turn_started" | "pi_turn_ended"): void;
16
17
  }
17
18
 
18
- function readPiEventString(data: Record<string, unknown>, key: string): string | null {
19
- const value = data[key];
20
- return typeof value === "string" && value.trim() !== "" ? value : null;
21
- }
22
-
23
- function readPiEventNumber(data: Record<string, unknown>, key: string): number | null {
24
- const value = data[key];
25
- if (typeof value === "number" && Number.isFinite(value)) {
26
- return value;
27
- }
28
- if (typeof value === "string" && value.trim() !== "") {
29
- const parsed = Number(value);
30
- if (Number.isFinite(parsed)) {
31
- return parsed;
32
- }
33
- }
34
- return null;
35
- }
36
-
37
19
  export function createPiEventReporter(options: PiEventReporterOptions): PiEventReporter {
38
20
  let currentPiAttempt = 1;
39
21
  let currentPiMaxAttempts: number | null = null;
@@ -45,14 +27,14 @@ export function createPiEventReporter(options: PiEventReporterOptions): PiEventR
45
27
 
46
28
  const reportPiError = (event: PiEvent) => {
47
29
  const message =
48
- readPiEventString(event.data, "message") ??
49
- readPiEventString(event.data, "errorMessage") ??
30
+ readNonBlankString(event.data.message) ??
31
+ readNonBlankString(event.data.errorMessage) ??
50
32
  "Pi reported an error";
51
- const toolName = readPiEventString(event.data, "toolName");
52
- const source = readPiEventString(event.data, "source");
53
- const provider = readPiEventString(event.data, "provider");
54
- const model = readPiEventString(event.data, "model");
55
- const stopReason = readPiEventString(event.data, "stopReason");
33
+ const toolName = readNonBlankString(event.data.toolName);
34
+ const source = readNonBlankString(event.data.source);
35
+ const provider = readNonBlankString(event.data.provider);
36
+ const model = readNonBlankString(event.data.model);
37
+ const stopReason = readNonBlankString(event.data.stopReason);
56
38
  options.reporter.workerError({
57
39
  level: "error",
58
40
  code: toolName || source === "tool" ? "pi.tool_error" : "pi.request_failed",
@@ -73,13 +55,13 @@ export function createPiEventReporter(options: PiEventReporterOptions): PiEventR
73
55
  };
74
56
 
75
57
  const reportPiRetryLifecycle = (event: PiEvent) => {
76
- const attempt = readPiEventNumber(event.data, "attempt");
77
- const maxAttempts = readPiEventNumber(event.data, "maxAttempts");
78
- const delayMs = readPiEventNumber(event.data, "delayMs");
79
- const errorMessage = readPiEventString(event.data, "errorMessage");
80
- const finalError = readPiEventString(event.data, "finalError");
58
+ const attempt = readFiniteNumber(event.data.attempt);
59
+ const maxAttempts = readFiniteNumber(event.data.maxAttempts);
60
+ const delayMs = readFiniteNumber(event.data.delayMs);
61
+ const errorMessage = readNonBlankString(event.data.errorMessage);
62
+ const finalError = readNonBlankString(event.data.finalError);
81
63
  const message =
82
- readPiEventString(event.data, "message") ??
64
+ readNonBlankString(event.data.message) ??
83
65
  (event.type === "retry.start"
84
66
  ? "Pi scheduled an automatic retry"
85
67
  : event.data.success === true
@@ -153,12 +135,8 @@ export function createPiEventReporter(options: PiEventReporterOptions): PiEventR
153
135
  );
154
136
  options.emitExtensionEvent?.("worker.pi_event", payload);
155
137
  });
156
- piHandle.subscribeDiagnostics?.((diagnostic) => {
157
- reportPiDiagnostic(diagnostic);
158
- });
159
- },
160
- resetRetryState() {
161
- resetPiRetryState();
138
+ piHandle.subscribeDiagnostics?.(reportPiDiagnostic);
162
139
  },
140
+ resetRetryState: resetPiRetryState,
163
141
  };
164
142
  }
@@ -1,5 +1,5 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import { mkdir, rename, rm, writeFile } from "node:fs/promises";
2
+ import { mkdir, open, readFile, rename, rm, writeFile } from "node:fs/promises";
3
3
  import path from "node:path";
4
4
  import {
5
5
  createCanonicalPiResourceBundle,
@@ -25,6 +25,72 @@ function fail(message: string): never {
25
25
  throw new Error(`Invalid Pi resource bundle: ${message}`);
26
26
  }
27
27
 
28
+ function requireStorageName(value: string, label: string): string {
29
+ if (!/^[a-zA-Z0-9_-]+$/u.test(value)) fail(`unsafe ${label}: ${value}`);
30
+ return value;
31
+ }
32
+
33
+ async function atomicWrite(pathname: string, content: Uint8Array, mode: number): Promise<void> {
34
+ const staging = `${pathname}.staging-${process.pid}-${randomUUID()}`;
35
+ const handle = await open(staging, "wx", mode);
36
+ try {
37
+ await handle.writeFile(content);
38
+ await handle.sync();
39
+ } finally {
40
+ await handle.close();
41
+ }
42
+ try {
43
+ await rename(staging, pathname);
44
+ } catch (error) {
45
+ await rm(staging, { force: true });
46
+ throw error;
47
+ }
48
+ }
49
+
50
+ /** Resolves an immutable bundle from delivered bytes or the process volume and records its start. */
51
+ export async function persistPiResourceBundleForStart(input: {
52
+ bundlesDir: string;
53
+ startRecordId: string;
54
+ digest: string;
55
+ archiveBase64?: string;
56
+ deliveredBundle?: Uint8Array;
57
+ }): Promise<{ bundle: Uint8Array; reused: boolean }> {
58
+ const digest = requireStorageName(input.digest, "resource digest");
59
+ const startRecordId = requireStorageName(input.startRecordId, "turn-start id");
60
+ const bundlesDir = path.resolve(input.bundlesDir);
61
+ const startsDir = path.join(bundlesDir, "starts");
62
+ const bundlePath = path.join(bundlesDir, `${digest}.tar`);
63
+ await mkdir(startsDir, { recursive: true, mode: 0o700 });
64
+
65
+ let bundle: Uint8Array | null = null;
66
+ let reused = false;
67
+ try {
68
+ const existing = await readFile(bundlePath);
69
+ verifyCanonicalPiResourceBundle(existing, digest);
70
+ bundle = existing;
71
+ reused = true;
72
+ } catch (error) {
73
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT" && input.archiveBase64 === undefined) {
74
+ throw error;
75
+ }
76
+ }
77
+ if (!bundle) {
78
+ if (!input.deliveredBundle && input.archiveBase64 === undefined) {
79
+ throw new Error(`Pi resource bundle '${digest}' is unavailable on the process volume`);
80
+ }
81
+ bundle = input.deliveredBundle ?? Buffer.from(input.archiveBase64 as string, "base64");
82
+ verifyCanonicalPiResourceBundle(bundle, digest);
83
+ await atomicWrite(bundlePath, bundle, 0o600);
84
+ }
85
+
86
+ const manifest = Buffer.from(
87
+ `${JSON.stringify({ startRecordId, digest, persistedAt: new Date().toISOString() })}\n`,
88
+ "utf8",
89
+ );
90
+ await atomicWrite(path.join(startsDir, `${startRecordId}.json`), manifest, 0o600);
91
+ return { bundle, reused };
92
+ }
93
+
28
94
  async function writeExtractedFiles(
29
95
  root: string,
30
96
  files: readonly ExtractedPiResourceFile[],
@@ -42,12 +108,20 @@ async function writeExtractedFiles(
42
108
  }
43
109
  }
44
110
 
45
- /** Extracts a verified bundle into an empty staging directory, then atomically publishes it. */
111
+ /** Extracts a verified bundle into an empty staging directory, then atomically publishes it. @internal */
46
112
  export async function materializeCanonicalPiResourceBundle(input: {
113
+ /** @internal */
47
114
  bundle: Uint8Array;
115
+ /** @internal */
48
116
  digest: string;
117
+ /** @internal */
118
+ targetDir: string;
119
+ }): Promise<{
120
+ /** @internal */
49
121
  targetDir: string;
50
- }): Promise<{ targetDir: string; reused: boolean }> {
122
+ /** @internal */
123
+ reused: boolean;
124
+ }> {
51
125
  const files = verifyCanonicalPiResourceBundle(input.bundle, input.digest);
52
126
  const targetDir = path.resolve(input.targetDir);
53
127
  const parent = path.dirname(targetDir);
@@ -18,6 +18,14 @@ export type PreTurnTargetedInput = Pick<
18
18
  target: NonNullable<InputItem["target"]>;
19
19
  };
20
20
 
21
+ export type AppliedTargetedInputMetadata = {
22
+ currentPrimaryPathLeafId?: string | null;
23
+ rootEntryId?: string | null;
24
+ targetSemanticRef?: ProcessSemanticEntryRefKey | null;
25
+ targetProductName?: string | null;
26
+ targetEntryId?: string | null;
27
+ };
28
+
21
29
  function resolveTargetSemanticRef(
22
30
  target: PreTurnTargetedInput["target"],
23
31
  ): ProcessSemanticEntryRefKey | null {
@@ -128,17 +136,7 @@ export async function applyPreTurnTargetedInputs(input: {
128
136
  recoveryBaseEntryId?: string | null;
129
137
  reuseExistingWithoutBranching?: boolean;
130
138
  requireExisting?: boolean;
131
- onApplied?(
132
- inputId: string,
133
- sequence: number,
134
- meta?: {
135
- currentPrimaryPathLeafId?: string | null;
136
- rootEntryId?: string | null;
137
- targetSemanticRef?: ProcessSemanticEntryRefKey | null;
138
- targetProductName?: string | null;
139
- targetEntryId?: string | null;
140
- },
141
- ): void;
139
+ onApplied?(inputId: string, sequence: number, meta?: AppliedTargetedInputMetadata): void;
142
140
  }): Promise<void> {
143
141
  if (input.inputs.length === 0) {
144
142
  return;