@caupulican/pi-adaptative 0.85.4 → 0.86.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 (480) hide show
  1. package/CHANGELOG.md +65 -0
  2. package/dist/bun/cli.d.ts +1 -1
  3. package/dist/bun/cli.d.ts.map +1 -1
  4. package/dist/bun/cli.js +1 -0
  5. package/dist/bun/cli.js.map +1 -1
  6. package/dist/core/agent-paths.d.ts +3 -3
  7. package/dist/core/agent-paths.d.ts.map +1 -1
  8. package/dist/core/agent-paths.js +3 -3
  9. package/dist/core/agent-paths.js.map +1 -1
  10. package/dist/core/agent-session-runtime.d.ts +1 -1
  11. package/dist/core/agent-session-runtime.d.ts.map +1 -1
  12. package/dist/core/agent-session-runtime.js +1 -1
  13. package/dist/core/agent-session-runtime.js.map +1 -1
  14. package/dist/core/agent-session.d.ts +11 -5
  15. package/dist/core/agent-session.d.ts.map +1 -1
  16. package/dist/core/agent-session.js +14 -3
  17. package/dist/core/agent-session.js.map +1 -1
  18. package/dist/core/auth-storage.d.ts +2 -2
  19. package/dist/core/auth-storage.d.ts.map +1 -1
  20. package/dist/core/auth-storage.js +2 -2
  21. package/dist/core/auth-storage.js.map +1 -1
  22. package/dist/core/autonomy/bounded-completion.d.ts.map +1 -1
  23. package/dist/core/autonomy/bounded-completion.js +19 -8
  24. package/dist/core/autonomy/bounded-completion.js.map +1 -1
  25. package/dist/core/autonomy/lane-tool-surface.d.ts +11 -5
  26. package/dist/core/autonomy/lane-tool-surface.d.ts.map +1 -1
  27. package/dist/core/autonomy/lane-tool-surface.js +34 -8
  28. package/dist/core/autonomy/lane-tool-surface.js.map +1 -1
  29. package/dist/core/autonomy/subagent-prompt.d.ts +3 -3
  30. package/dist/core/autonomy/subagent-prompt.js +9 -9
  31. package/dist/core/autonomy/subagent-prompt.js.map +1 -1
  32. package/dist/core/background-lane-controller.d.ts +10 -8
  33. package/dist/core/background-lane-controller.d.ts.map +1 -1
  34. package/dist/core/background-lane-controller.js +23 -13
  35. package/dist/core/background-lane-controller.js.map +1 -1
  36. package/dist/core/bash-execution-controller.d.ts +4 -0
  37. package/dist/core/bash-execution-controller.d.ts.map +1 -1
  38. package/dist/core/bash-execution-controller.js +11 -4
  39. package/dist/core/bash-execution-controller.js.map +1 -1
  40. package/dist/core/bash-executor.d.ts +2 -0
  41. package/dist/core/bash-executor.d.ts.map +1 -1
  42. package/dist/core/bash-executor.js +4 -3
  43. package/dist/core/bash-executor.js.map +1 -1
  44. package/dist/core/billing-failover-controller.d.ts +2 -2
  45. package/dist/core/billing-failover-controller.d.ts.map +1 -1
  46. package/dist/core/billing-failover-controller.js +1 -1
  47. package/dist/core/billing-failover-controller.js.map +1 -1
  48. package/dist/core/capability-contract.d.ts +1 -1
  49. package/dist/core/capability-contract.d.ts.map +1 -1
  50. package/dist/core/capability-contract.js +0 -1
  51. package/dist/core/capability-contract.js.map +1 -1
  52. package/dist/core/compaction-controller.d.ts +8 -2
  53. package/dist/core/compaction-controller.d.ts.map +1 -1
  54. package/dist/core/compaction-controller.js +73 -3
  55. package/dist/core/compaction-controller.js.map +1 -1
  56. package/dist/core/compaction-support.d.ts +2 -2
  57. package/dist/core/compaction-support.d.ts.map +1 -1
  58. package/dist/core/compaction-support.js +9 -1
  59. package/dist/core/compaction-support.js.map +1 -1
  60. package/dist/core/context/artifact-retrieval.d.ts +1 -1
  61. package/dist/core/context/artifact-retrieval.d.ts.map +1 -1
  62. package/dist/core/context/artifact-retrieval.js +1 -1
  63. package/dist/core/context/artifact-retrieval.js.map +1 -1
  64. package/dist/core/context/context-artifacts.d.ts +6 -6
  65. package/dist/core/context/context-artifacts.d.ts.map +1 -1
  66. package/dist/core/context/context-artifacts.js +151 -63
  67. package/dist/core/context/context-artifacts.js.map +1 -1
  68. package/dist/core/context/context-composition.js +1 -1
  69. package/dist/core/context/context-composition.js.map +1 -1
  70. package/dist/core/context/context-store-retention.d.ts.map +1 -1
  71. package/dist/core/context/context-store-retention.js +5 -2
  72. package/dist/core/context/context-store-retention.js.map +1 -1
  73. package/dist/core/context/file-store-memory-provider.js +1 -1
  74. package/dist/core/context/file-store-memory-provider.js.map +1 -1
  75. package/dist/core/context/tool-output-packer.d.ts +1 -1
  76. package/dist/core/context/tool-output-packer.d.ts.map +1 -1
  77. package/dist/core/context/tool-output-packer.js +1 -1
  78. package/dist/core/context/tool-output-packer.js.map +1 -1
  79. package/dist/core/context-gc.d.ts.map +1 -1
  80. package/dist/core/context-gc.js +7 -5
  81. package/dist/core/context-gc.js.map +1 -1
  82. package/dist/core/context-pipeline.d.ts +2 -2
  83. package/dist/core/context-pipeline.d.ts.map +1 -1
  84. package/dist/core/context-pipeline.js +8 -4
  85. package/dist/core/context-pipeline.js.map +1 -1
  86. package/dist/core/cost/cost-summary.d.ts +1 -1
  87. package/dist/core/cost/cost-summary.d.ts.map +1 -1
  88. package/dist/core/cost/cost-summary.js +1 -1
  89. package/dist/core/cost/cost-summary.js.map +1 -1
  90. package/dist/core/cost/daily-usage.d.ts +1 -1
  91. package/dist/core/cost/daily-usage.d.ts.map +1 -1
  92. package/dist/core/cost/daily-usage.js +2 -2
  93. package/dist/core/cost/daily-usage.js.map +1 -1
  94. package/dist/core/cost/session-usage.d.ts +1 -1
  95. package/dist/core/cost/session-usage.d.ts.map +1 -1
  96. package/dist/core/cost/session-usage.js +1 -1
  97. package/dist/core/cost/session-usage.js.map +1 -1
  98. package/dist/core/default-tool-surface.d.ts +1 -0
  99. package/dist/core/default-tool-surface.d.ts.map +1 -1
  100. package/dist/core/default-tool-surface.js +3 -2
  101. package/dist/core/default-tool-surface.js.map +1 -1
  102. package/dist/core/delegation/worker-actions.js +1 -1
  103. package/dist/core/delegation/worker-actions.js.map +1 -1
  104. package/dist/core/delegation/worker-agent-control-coordinator.d.ts +27 -8
  105. package/dist/core/delegation/worker-agent-control-coordinator.d.ts.map +1 -1
  106. package/dist/core/delegation/worker-agent-control-coordinator.js +191 -33
  107. package/dist/core/delegation/worker-agent-control-coordinator.js.map +1 -1
  108. package/dist/core/delegation/worker-agent-control.d.ts +45 -6
  109. package/dist/core/delegation/worker-agent-control.d.ts.map +1 -1
  110. package/dist/core/delegation/worker-agent-control.js +110 -13
  111. package/dist/core/delegation/worker-agent-control.js.map +1 -1
  112. package/dist/core/delegation/worker-attempt-executor.d.ts +1 -1
  113. package/dist/core/delegation/worker-attempt-executor.d.ts.map +1 -1
  114. package/dist/core/delegation/worker-attempt-executor.js +180 -160
  115. package/dist/core/delegation/worker-attempt-executor.js.map +1 -1
  116. package/dist/core/delegation/worker-authority-resolver.d.ts +23 -0
  117. package/dist/core/delegation/worker-authority-resolver.d.ts.map +1 -0
  118. package/dist/core/delegation/worker-authority-resolver.js +128 -0
  119. package/dist/core/delegation/worker-authority-resolver.js.map +1 -0
  120. package/dist/core/delegation/worker-conversation-store.d.ts +2 -1
  121. package/dist/core/delegation/worker-conversation-store.d.ts.map +1 -1
  122. package/dist/core/delegation/worker-conversation-store.js +4 -3
  123. package/dist/core/delegation/worker-conversation-store.js.map +1 -1
  124. package/dist/core/delegation/worker-delegation-controller.d.ts +7 -1
  125. package/dist/core/delegation/worker-delegation-controller.d.ts.map +1 -1
  126. package/dist/core/delegation/worker-delegation-controller.js +260 -87
  127. package/dist/core/delegation/worker-delegation-controller.js.map +1 -1
  128. package/dist/core/delegation/worker-delegation-request.d.ts +25 -4
  129. package/dist/core/delegation/worker-delegation-request.d.ts.map +1 -1
  130. package/dist/core/delegation/worker-delegation-request.js +90 -1
  131. package/dist/core/delegation/worker-delegation-request.js.map +1 -1
  132. package/dist/core/delegation/worker-execution-policy.d.ts +2 -0
  133. package/dist/core/delegation/worker-execution-policy.d.ts.map +1 -1
  134. package/dist/core/delegation/worker-execution-policy.js +22 -12
  135. package/dist/core/delegation/worker-execution-policy.js.map +1 -1
  136. package/dist/core/delegation/worker-lifecycle.d.ts +1 -0
  137. package/dist/core/delegation/worker-lifecycle.d.ts.map +1 -1
  138. package/dist/core/delegation/worker-lifecycle.js +4 -2
  139. package/dist/core/delegation/worker-lifecycle.js.map +1 -1
  140. package/dist/core/delegation/worker-profile-resolver.d.ts +0 -2
  141. package/dist/core/delegation/worker-profile-resolver.d.ts.map +1 -1
  142. package/dist/core/delegation/worker-profile-resolver.js +8 -35
  143. package/dist/core/delegation/worker-profile-resolver.js.map +1 -1
  144. package/dist/core/delegation/worker-recovery-coordinator.d.ts.map +1 -1
  145. package/dist/core/delegation/worker-recovery-coordinator.js +1 -0
  146. package/dist/core/delegation/worker-recovery-coordinator.js.map +1 -1
  147. package/dist/core/delegation/worker-runner.d.ts +6 -1
  148. package/dist/core/delegation/worker-runner.d.ts.map +1 -1
  149. package/dist/core/delegation/worker-runner.js +20 -6
  150. package/dist/core/delegation/worker-runner.js.map +1 -1
  151. package/dist/core/delegation/worker-tree-budget-coordinator.d.ts +47 -0
  152. package/dist/core/delegation/worker-tree-budget-coordinator.d.ts.map +1 -0
  153. package/dist/core/delegation/worker-tree-budget-coordinator.js +210 -0
  154. package/dist/core/delegation/worker-tree-budget-coordinator.js.map +1 -0
  155. package/dist/core/extensions/builtin.d.ts +2 -2
  156. package/dist/core/extensions/builtin.d.ts.map +1 -1
  157. package/dist/core/extensions/builtin.js +2 -2
  158. package/dist/core/extensions/builtin.js.map +1 -1
  159. package/dist/core/extensions/bundled-virtual-modules.d.ts +2 -0
  160. package/dist/core/extensions/bundled-virtual-modules.d.ts.map +1 -0
  161. package/dist/core/extensions/bundled-virtual-modules.js +129 -0
  162. package/dist/core/extensions/bundled-virtual-modules.js.map +1 -0
  163. package/dist/core/extensions/factory-runtime.d.ts +22 -0
  164. package/dist/core/extensions/factory-runtime.d.ts.map +1 -0
  165. package/dist/core/extensions/factory-runtime.js +334 -0
  166. package/dist/core/extensions/factory-runtime.js.map +1 -0
  167. package/dist/core/extensions/index.d.ts +1 -1
  168. package/dist/core/extensions/index.d.ts.map +1 -1
  169. package/dist/core/extensions/index.js +1 -1
  170. package/dist/core/extensions/index.js.map +1 -1
  171. package/dist/core/extensions/lifecycle.d.ts +13 -0
  172. package/dist/core/extensions/lifecycle.d.ts.map +1 -0
  173. package/dist/core/extensions/lifecycle.js +52 -0
  174. package/dist/core/extensions/lifecycle.js.map +1 -0
  175. package/dist/core/extensions/loader.d.ts +3 -24
  176. package/dist/core/extensions/loader.d.ts.map +1 -1
  177. package/dist/core/extensions/loader.js +21 -531
  178. package/dist/core/extensions/loader.js.map +1 -1
  179. package/dist/core/extensions/virtual-modules.d.ts +51 -0
  180. package/dist/core/extensions/virtual-modules.d.ts.map +1 -0
  181. package/dist/core/extensions/virtual-modules.js +59 -0
  182. package/dist/core/extensions/virtual-modules.js.map +1 -0
  183. package/dist/core/foreground-recovery-controller.d.ts +2 -1
  184. package/dist/core/foreground-recovery-controller.d.ts.map +1 -1
  185. package/dist/core/foreground-recovery-controller.js +3 -3
  186. package/dist/core/foreground-recovery-controller.js.map +1 -1
  187. package/dist/core/goal-loop-controller.js +1 -1
  188. package/dist/core/goal-loop-controller.js.map +1 -1
  189. package/dist/core/goals/compact-goal-context.d.ts +1 -1
  190. package/dist/core/goals/compact-goal-context.d.ts.map +1 -1
  191. package/dist/core/goals/compact-goal-context.js +1 -1
  192. package/dist/core/goals/compact-goal-context.js.map +1 -1
  193. package/dist/core/goals/goal-auto-continue-controller.js +1 -1
  194. package/dist/core/goals/goal-auto-continue-controller.js.map +1 -1
  195. package/dist/core/goals/goal-session-controller.d.ts +1 -1
  196. package/dist/core/goals/goal-session-controller.d.ts.map +1 -1
  197. package/dist/core/goals/goal-session-controller.js +1 -1
  198. package/dist/core/goals/goal-session-controller.js.map +1 -1
  199. package/dist/core/http-dispatcher.d.ts +1 -1
  200. package/dist/core/http-dispatcher.d.ts.map +1 -1
  201. package/dist/core/http-dispatcher.js +1 -1
  202. package/dist/core/http-dispatcher.js.map +1 -1
  203. package/dist/core/index.d.ts +3 -2
  204. package/dist/core/index.d.ts.map +1 -1
  205. package/dist/core/index.js +2 -1
  206. package/dist/core/index.js.map +1 -1
  207. package/dist/core/memory/providers/file-store.d.ts.map +1 -1
  208. package/dist/core/memory/providers/file-store.js +1 -1
  209. package/dist/core/memory/providers/file-store.js.map +1 -1
  210. package/dist/core/memory/providers/user-memory-archive.js +1 -1
  211. package/dist/core/memory/providers/user-memory-archive.js.map +1 -1
  212. package/dist/core/model-registry.d.ts +2 -1
  213. package/dist/core/model-registry.d.ts.map +1 -1
  214. package/dist/core/model-registry.js +4 -1
  215. package/dist/core/model-registry.js.map +1 -1
  216. package/dist/core/model-resolver.d.ts +1 -1
  217. package/dist/core/model-resolver.d.ts.map +1 -1
  218. package/dist/core/model-resolver.js +1 -1
  219. package/dist/core/model-resolver.js.map +1 -1
  220. package/dist/core/model-router-controller.js +1 -1
  221. package/dist/core/model-router-controller.js.map +1 -1
  222. package/dist/core/model-selection-controller.js +1 -1
  223. package/dist/core/model-selection-controller.js.map +1 -1
  224. package/dist/core/model-tool-protocol.d.ts +1 -1
  225. package/dist/core/model-tool-protocol.d.ts.map +1 -1
  226. package/dist/core/model-tool-protocol.js +1 -1
  227. package/dist/core/model-tool-protocol.js.map +1 -1
  228. package/dist/core/models/llamacpp-runtime.d.ts +7 -0
  229. package/dist/core/models/llamacpp-runtime.d.ts.map +1 -1
  230. package/dist/core/models/llamacpp-runtime.js +8 -3
  231. package/dist/core/models/llamacpp-runtime.js.map +1 -1
  232. package/dist/core/models/local-runtime.js +1 -1
  233. package/dist/core/models/local-runtime.js.map +1 -1
  234. package/dist/core/models/runtime-process.d.ts.map +1 -1
  235. package/dist/core/models/runtime-process.js +5 -18
  236. package/dist/core/models/runtime-process.js.map +1 -1
  237. package/dist/core/orchestration/bounded-string-array.d.ts +11 -0
  238. package/dist/core/orchestration/bounded-string-array.d.ts.map +1 -0
  239. package/dist/core/orchestration/bounded-string-array.js +17 -0
  240. package/dist/core/orchestration/bounded-string-array.js.map +1 -0
  241. package/dist/core/orchestration/capability-gateway.d.ts +16 -0
  242. package/dist/core/orchestration/capability-gateway.d.ts.map +1 -1
  243. package/dist/core/orchestration/capability-gateway.js +38 -0
  244. package/dist/core/orchestration/capability-gateway.js.map +1 -1
  245. package/dist/core/orchestration/contracts.d.ts +11 -3
  246. package/dist/core/orchestration/contracts.d.ts.map +1 -1
  247. package/dist/core/orchestration/contracts.js +0 -1
  248. package/dist/core/orchestration/contracts.js.map +1 -1
  249. package/dist/core/orchestration/delegation-ledger.d.ts +1 -0
  250. package/dist/core/orchestration/delegation-ledger.d.ts.map +1 -1
  251. package/dist/core/orchestration/delegation-ledger.js +3 -0
  252. package/dist/core/orchestration/delegation-ledger.js.map +1 -1
  253. package/dist/core/orchestration/event-store.d.ts +12 -10
  254. package/dist/core/orchestration/event-store.d.ts.map +1 -1
  255. package/dist/core/orchestration/event-store.js +94 -104
  256. package/dist/core/orchestration/event-store.js.map +1 -1
  257. package/dist/core/orchestration/lane-tool-manifests.d.ts +2 -2
  258. package/dist/core/orchestration/lane-tool-manifests.d.ts.map +1 -1
  259. package/dist/core/orchestration/lane-tool-manifests.js +4 -1
  260. package/dist/core/orchestration/lane-tool-manifests.js.map +1 -1
  261. package/dist/core/orchestration/model-binding.d.ts +1 -1
  262. package/dist/core/orchestration/model-binding.d.ts.map +1 -1
  263. package/dist/core/orchestration/model-binding.js +1 -1
  264. package/dist/core/orchestration/model-binding.js.map +1 -1
  265. package/dist/core/orchestration/policy-compiler.d.ts.map +1 -1
  266. package/dist/core/orchestration/policy-compiler.js +8 -9
  267. package/dist/core/orchestration/policy-compiler.js.map +1 -1
  268. package/dist/core/orchestration/profile-registry.d.ts.map +1 -1
  269. package/dist/core/orchestration/profile-registry.js +4 -10
  270. package/dist/core/orchestration/profile-registry.js.map +1 -1
  271. package/dist/core/orchestration/task-profile-writer.js +1 -1
  272. package/dist/core/orchestration/task-profile-writer.js.map +1 -1
  273. package/dist/core/orchestration/task-runtime.d.ts +1 -0
  274. package/dist/core/orchestration/task-runtime.d.ts.map +1 -1
  275. package/dist/core/orchestration/task-runtime.js +58 -3
  276. package/dist/core/orchestration/task-runtime.js.map +1 -1
  277. package/dist/core/orchestration/worker-execution-contract.d.ts.map +1 -1
  278. package/dist/core/orchestration/worker-execution-contract.js +10 -17
  279. package/dist/core/orchestration/worker-execution-contract.js.map +1 -1
  280. package/dist/core/process-matrix/runtime.d.ts +15 -1
  281. package/dist/core/process-matrix/runtime.d.ts.map +1 -1
  282. package/dist/core/process-matrix/runtime.js +55 -34
  283. package/dist/core/process-matrix/runtime.js.map +1 -1
  284. package/dist/core/reflection-controller.d.ts +4 -3
  285. package/dist/core/reflection-controller.d.ts.map +1 -1
  286. package/dist/core/reflection-controller.js +2 -2
  287. package/dist/core/reflection-controller.js.map +1 -1
  288. package/dist/core/research/model-fitness-controller.js +1 -1
  289. package/dist/core/research/model-fitness-controller.js.map +1 -1
  290. package/dist/core/research/research-lane-controller.d.ts +2 -2
  291. package/dist/core/research/research-lane-controller.d.ts.map +1 -1
  292. package/dist/core/research/research-lane-controller.js +1 -1
  293. package/dist/core/research/research-lane-controller.js.map +1 -1
  294. package/dist/core/resource-loader.d.ts +10 -19
  295. package/dist/core/resource-loader.d.ts.map +1 -1
  296. package/dist/core/resource-loader.js +8 -70
  297. package/dist/core/resource-loader.js.map +1 -1
  298. package/dist/core/risk-classifier.js +3 -3
  299. package/dist/core/risk-classifier.js.map +1 -1
  300. package/dist/core/runtime-builder.d.ts +4 -1
  301. package/dist/core/runtime-builder.d.ts.map +1 -1
  302. package/dist/core/runtime-builder.js +47 -18
  303. package/dist/core/runtime-builder.js.map +1 -1
  304. package/dist/core/scout-controller.d.ts +1 -1
  305. package/dist/core/scout-controller.d.ts.map +1 -1
  306. package/dist/core/scout-controller.js +1 -1
  307. package/dist/core/scout-controller.js.map +1 -1
  308. package/dist/core/sdk.d.ts +2 -2
  309. package/dist/core/sdk.d.ts.map +1 -1
  310. package/dist/core/sdk.js +3 -3
  311. package/dist/core/sdk.js.map +1 -1
  312. package/dist/core/secrets/bitwarden-credential-storage.d.ts +51 -0
  313. package/dist/core/secrets/bitwarden-credential-storage.d.ts.map +1 -0
  314. package/dist/core/secrets/bitwarden-credential-storage.js +345 -0
  315. package/dist/core/secrets/bitwarden-credential-storage.js.map +1 -0
  316. package/dist/core/secrets/credential-exposure-guard.d.ts +8 -4
  317. package/dist/core/secrets/credential-exposure-guard.d.ts.map +1 -1
  318. package/dist/core/secrets/credential-exposure-guard.js +31 -29
  319. package/dist/core/secrets/credential-exposure-guard.js.map +1 -1
  320. package/dist/core/secrets/credential-manager.d.ts +109 -0
  321. package/dist/core/secrets/credential-manager.d.ts.map +1 -0
  322. package/dist/core/secrets/credential-manager.js +384 -0
  323. package/dist/core/secrets/credential-manager.js.map +1 -0
  324. package/dist/core/secrets/credential-project.d.ts +4 -0
  325. package/dist/core/secrets/credential-project.d.ts.map +1 -0
  326. package/dist/core/secrets/credential-project.js +145 -0
  327. package/dist/core/secrets/credential-project.js.map +1 -0
  328. package/dist/core/secrets/secret-dotenv.d.ts +1 -1
  329. package/dist/core/secrets/secret-dotenv.js +1 -1
  330. package/dist/core/secrets/secret-dotenv.js.map +1 -1
  331. package/dist/core/security/context-threat-scanner.d.ts +14 -0
  332. package/dist/core/security/context-threat-scanner.d.ts.map +1 -0
  333. package/dist/core/security/context-threat-scanner.js +71 -0
  334. package/dist/core/security/context-threat-scanner.js.map +1 -0
  335. package/dist/core/session-supervision-runtime.d.ts +4 -1
  336. package/dist/core/session-supervision-runtime.d.ts.map +1 -1
  337. package/dist/core/session-supervision-runtime.js +49 -11
  338. package/dist/core/session-supervision-runtime.js.map +1 -1
  339. package/dist/core/settings-manager.d.ts +4 -2
  340. package/dist/core/settings-manager.d.ts.map +1 -1
  341. package/dist/core/settings-manager.js +10 -6
  342. package/dist/core/settings-manager.js.map +1 -1
  343. package/dist/core/slash-commands.d.ts.map +1 -1
  344. package/dist/core/slash-commands.js +1 -0
  345. package/dist/core/slash-commands.js.map +1 -1
  346. package/dist/core/system-prompt.js +1 -1
  347. package/dist/core/system-prompt.js.map +1 -1
  348. package/dist/core/tool-capability-policy.js +2 -2
  349. package/dist/core/tool-capability-policy.js.map +1 -1
  350. package/dist/core/tool-recovery-logger.js +1 -1
  351. package/dist/core/tool-recovery-logger.js.map +1 -1
  352. package/dist/core/tools/artifact-retrieve.js +1 -1
  353. package/dist/core/tools/artifact-retrieve.js.map +1 -1
  354. package/dist/core/tools/bash.d.ts +2 -2
  355. package/dist/core/tools/bash.d.ts.map +1 -1
  356. package/dist/core/tools/bash.js +16 -4
  357. package/dist/core/tools/bash.js.map +1 -1
  358. package/dist/core/tools/delegate.d.ts +29 -1
  359. package/dist/core/tools/delegate.d.ts.map +1 -1
  360. package/dist/core/tools/delegate.js +179 -28
  361. package/dist/core/tools/delegate.js.map +1 -1
  362. package/dist/core/tools/extensionify-runtime.d.ts +44 -0
  363. package/dist/core/tools/extensionify-runtime.d.ts.map +1 -0
  364. package/dist/core/tools/extensionify-runtime.js +115 -0
  365. package/dist/core/tools/extensionify-runtime.js.map +1 -0
  366. package/dist/core/tools/extensionify.d.ts +9 -30
  367. package/dist/core/tools/extensionify.d.ts.map +1 -1
  368. package/dist/core/tools/extensionify.js +10 -140
  369. package/dist/core/tools/extensionify.js.map +1 -1
  370. package/dist/core/tools/find.d.ts +1 -1
  371. package/dist/core/tools/find.d.ts.map +1 -1
  372. package/dist/core/tools/find.js +1 -1
  373. package/dist/core/tools/find.js.map +1 -1
  374. package/dist/core/tools/git-filter.d.ts +1 -0
  375. package/dist/core/tools/git-filter.d.ts.map +1 -1
  376. package/dist/core/tools/git-filter.js +1 -1
  377. package/dist/core/tools/git-filter.js.map +1 -1
  378. package/dist/core/tools/index.d.ts +2 -4
  379. package/dist/core/tools/index.d.ts.map +1 -1
  380. package/dist/core/tools/index.js +7 -43
  381. package/dist/core/tools/index.js.map +1 -1
  382. package/dist/core/tools/ls.d.ts +1 -1
  383. package/dist/core/tools/ls.d.ts.map +1 -1
  384. package/dist/core/tools/ls.js +1 -1
  385. package/dist/core/tools/ls.js.map +1 -1
  386. package/dist/core/tools/output-accumulator.d.ts +1 -1
  387. package/dist/core/tools/output-accumulator.d.ts.map +1 -1
  388. package/dist/core/tools/output-accumulator.js +1 -1
  389. package/dist/core/tools/output-accumulator.js.map +1 -1
  390. package/dist/core/tools/profile-writer.js +3 -3
  391. package/dist/core/tools/profile-writer.js.map +1 -1
  392. package/dist/core/tools/python.d.ts +2 -0
  393. package/dist/core/tools/python.d.ts.map +1 -1
  394. package/dist/core/tools/python.js +17 -12
  395. package/dist/core/tools/python.js.map +1 -1
  396. package/dist/core/tools/render-utils.js +1 -1
  397. package/dist/core/tools/render-utils.js.map +1 -1
  398. package/dist/core/tools/run-process.d.ts +2 -0
  399. package/dist/core/tools/run-process.d.ts.map +1 -1
  400. package/dist/core/tools/run-process.js +7 -3
  401. package/dist/core/tools/run-process.js.map +1 -1
  402. package/dist/core/tools/search-command-guard.d.ts +8 -0
  403. package/dist/core/tools/search-command-guard.d.ts.map +1 -1
  404. package/dist/core/tools/search-command-guard.js +54 -0
  405. package/dist/core/tools/search-command-guard.js.map +1 -1
  406. package/dist/core/tools/secret-store.d.ts +8 -18
  407. package/dist/core/tools/secret-store.d.ts.map +1 -1
  408. package/dist/core/tools/secret-store.js +83 -348
  409. package/dist/core/tools/secret-store.js.map +1 -1
  410. package/dist/core/tools/shell-contract-router.d.ts.map +1 -1
  411. package/dist/core/tools/shell-contract-router.js +9 -4
  412. package/dist/core/tools/shell-contract-router.js.map +1 -1
  413. package/dist/core/tools/shell-session.d.ts.map +1 -1
  414. package/dist/core/tools/shell-session.js +6 -4
  415. package/dist/core/tools/shell-session.js.map +1 -1
  416. package/dist/core/tools/tool-definition-factory.d.ts +32 -0
  417. package/dist/core/tools/tool-definition-factory.d.ts.map +1 -0
  418. package/dist/core/tools/tool-definition-factory.js +55 -0
  419. package/dist/core/tools/tool-definition-factory.js.map +1 -0
  420. package/dist/core/util/atomic-file.d.ts.map +1 -1
  421. package/dist/core/util/atomic-file.js +79 -32
  422. package/dist/core/util/atomic-file.js.map +1 -1
  423. package/dist/index.d.ts +5 -2
  424. package/dist/index.d.ts.map +1 -1
  425. package/dist/index.js +5 -2
  426. package/dist/index.js.map +1 -1
  427. package/dist/main.d.ts +2 -0
  428. package/dist/main.d.ts.map +1 -1
  429. package/dist/main.js +24 -18
  430. package/dist/main.js.map +1 -1
  431. package/dist/modes/interactive/auto-learn-controller.js +1 -1
  432. package/dist/modes/interactive/auto-learn-controller.js.map +1 -1
  433. package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
  434. package/dist/modes/interactive/components/settings-selector.js +35 -14
  435. package/dist/modes/interactive/components/settings-selector.js.map +1 -1
  436. package/dist/modes/interactive/components/tool-execution.js +1 -1
  437. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  438. package/dist/modes/interactive/interactive-event-controller.js +1 -1
  439. package/dist/modes/interactive/interactive-event-controller.js.map +1 -1
  440. package/dist/modes/interactive/interactive-mode.d.ts +1 -0
  441. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  442. package/dist/modes/interactive/interactive-mode.js +27 -4
  443. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  444. package/dist/modes/interactive/secret-menu-controller.d.ts +21 -0
  445. package/dist/modes/interactive/secret-menu-controller.d.ts.map +1 -0
  446. package/dist/modes/interactive/secret-menu-controller.js +276 -0
  447. package/dist/modes/interactive/secret-menu-controller.js.map +1 -0
  448. package/dist/utils/child-process.js +1 -1
  449. package/dist/utils/child-process.js.map +1 -1
  450. package/dist/utils/tools-manager.d.ts +2 -1
  451. package/dist/utils/tools-manager.d.ts.map +1 -1
  452. package/dist/utils/tools-manager.js +43 -48
  453. package/dist/utils/tools-manager.js.map +1 -1
  454. package/dist/utils/zip-extractor.d.ts +8 -0
  455. package/dist/utils/zip-extractor.d.ts.map +1 -0
  456. package/dist/utils/zip-extractor.js +275 -0
  457. package/dist/utils/zip-extractor.js.map +1 -0
  458. package/docs/harness-architecture.md +34 -22
  459. package/docs/index.md +1 -1
  460. package/docs/resources.md +1 -1
  461. package/docs/settings.md +39 -103
  462. package/docs/usage.md +7 -5
  463. package/docs/worker-profiles.md +9 -7
  464. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  465. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  466. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  467. package/examples/extensions/sandbox/package-lock.json +2 -2
  468. package/examples/extensions/sandbox/package.json +1 -1
  469. package/examples/extensions/with-deps/package-lock.json +2 -2
  470. package/examples/extensions/with-deps/package.json +1 -1
  471. package/npm-shrinkwrap.json +12 -12
  472. package/package.json +7 -5
  473. package/dist/core/secrets/secret-vault-format.d.ts +0 -112
  474. package/dist/core/secrets/secret-vault-format.d.ts.map +0 -1
  475. package/dist/core/secrets/secret-vault-format.js +0 -396
  476. package/dist/core/secrets/secret-vault-format.js.map +0 -1
  477. package/dist/core/secrets/secret-vault.d.ts +0 -72
  478. package/dist/core/secrets/secret-vault.d.ts.map +0 -1
  479. package/dist/core/secrets/secret-vault.js +0 -663
  480. package/dist/core/secrets/secret-vault.js.map +0 -1
@@ -1,4 +1,4 @@
1
- import { getSessionEntryUsage } from "@caupulican/pi-agent-core";
1
+ import { getSessionEntryUsage } from "@caupulican/pi-agent-core/usage";
2
2
  import { SPAWNED_USAGE_CUSTOM_TYPE } from "../agent-session-contracts.js";
3
3
  function isFiniteCost(value) {
4
4
  return typeof value === "number" && Number.isFinite(value);
@@ -1 +1 @@
1
- {"version":3,"file":"cost-summary.js","sourceRoot":"","sources":["../../../src/core/cost/cost-summary.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,MAAM,2BAA2B,CAAC;AAGjE,OAAO,EAAE,yBAAyB,EAA2B,MAAM,+BAA+B,CAAC;AAsBnG,SAAS,YAAY,CAAC,KAAc;IACnC,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;AAC5D,CAAC;AAED,SAAS,iBAAiB,CAA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AAC,aAAa,UAAU,CAAC,OAAO,CAAC,YAAY,EAAE,SAAS,CAAC,wBAAwB,CAAC,CAAC;IAC9F,CAAC;IACD,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AACzB,CAAC","sourcesContent":["import { getSessionEntryUsage } from \"@caupulican/pi-agent-core\";\nimport type { SessionEntry } from \"@caupulican/pi-agent-core/node\";\nimport type { Usage } from \"@caupulican/pi-ai\";\nimport { SPAWNED_USAGE_CUSTOM_TYPE, type SpawnedUsageReport } from \"../agent-session-contracts.ts\";\nimport type { DailyUsageTotals, DailyUsageWindow } from \"./daily-usage.ts\";\n\nexport interface CurrentSessionCostTotals {\n\townCost: number;\n\tsubagentCost: number;\n\tsubagentReports: number;\n\tcurrentCost: number;\n}\n\nexport interface CurrentSessionCostAccumulator extends CurrentSessionCostTotals {\n\tseenSubagentReportIds: Set<string>;\n}\n\nexport interface SessionCostSummary extends CurrentSessionCostTotals {\n\ttodayCost: number;\n\ttodayOwnCost: number;\n\ttodaySubagentCost: number;\n\ttodayWindow: DailyUsageWindow;\n\ttodayRollover: \"local-midnight\";\n}\n\nfunction isFiniteCost(value: unknown): value is number {\n\treturn typeof value === \"number\" && Number.isFinite(value);\n}\n\nfunction getUsageTotalCost(usage: Usage | undefined): number | undefined {\n\tconst total = usage?.cost?.total;\n\treturn isFiniteCost(total) ? total : undefined;\n}\n\nexport function createCurrentSessionCostAccumulator(): CurrentSessionCostAccumulator {\n\treturn {\n\t\townCost: 0,\n\t\tsubagentCost: 0,\n\t\tsubagentReports: 0,\n\t\tcurrentCost: 0,\n\t\tseenSubagentReportIds: new Set<string>(),\n\t};\n}\n\nexport function accumulateCurrentSessionCostsFromEntries(\n\taccumulator: CurrentSessionCostAccumulator,\n\tentries: readonly SessionEntry[],\n): CurrentSessionCostAccumulator {\n\tfor (const entry of entries) {\n\t\tconst usage = getSessionEntryUsage(entry);\n\t\tif (usage) {\n\t\t\tconst total = getUsageTotalCost(usage);\n\t\t\tif (total !== undefined) accumulator.ownCost += total;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (entry.type !== \"custom\" || entry.customType !== SPAWNED_USAGE_CUSTOM_TYPE) continue;\n\t\tconst report = entry.data as SpawnedUsageReport | undefined;\n\t\tconst total = getUsageTotalCost(report?.usage);\n\t\tif (total === undefined) continue;\n\t\tif (report?.reportId) {\n\t\t\tif (accumulator.seenSubagentReportIds.has(report.reportId)) continue;\n\t\t\taccumulator.seenSubagentReportIds.add(report.reportId);\n\t\t}\n\t\taccumulator.subagentCost += total;\n\t\taccumulator.subagentReports += 1;\n\t}\n\taccumulator.currentCost = accumulator.ownCost + accumulator.subagentCost;\n\treturn accumulator;\n}\n\nexport function aggregateCurrentSessionCostsFromEntries(entries: readonly SessionEntry[]): CurrentSessionCostTotals {\n\tconst { seenSubagentReportIds: _seenSubagentReportIds, ...totals } = accumulateCurrentSessionCostsFromEntries(\n\t\tcreateCurrentSessionCostAccumulator(),\n\t\tentries,\n\t);\n\treturn totals;\n}\n\nexport function createSessionCostSummary(args: {\n\tentries?: readonly SessionEntry[];\n\tdailyTotals: DailyUsageTotals;\n\ttodayWindow: DailyUsageWindow;\n\tcurrentTotals?: CurrentSessionCostTotals;\n}): SessionCostSummary {\n\tconst currentSource = args.currentTotals ?? aggregateCurrentSessionCostsFromEntries(args.entries ?? []);\n\tconst current: CurrentSessionCostTotals = {\n\t\townCost: currentSource.ownCost,\n\t\tsubagentCost: currentSource.subagentCost,\n\t\tsubagentReports: currentSource.subagentReports,\n\t\tcurrentCost: currentSource.currentCost,\n\t};\n\treturn {\n\t\t...current,\n\t\ttodayCost: args.dailyTotals.totalCost,\n\t\ttodayOwnCost: args.dailyTotals.ownCost,\n\t\ttodaySubagentCost: args.dailyTotals.spawnedCost,\n\t\ttodayWindow: args.todayWindow,\n\t\ttodayRollover: \"local-midnight\",\n\t};\n}\n\nexport function hasCostSummarySignal(summary: SessionCostSummary): boolean {\n\treturn summary.currentCost > 0 || summary.todayCost > 0 || summary.subagentReports > 0;\n}\n\nexport function hasSubagentCostSignal(summary: Pick<SessionCostSummary, \"subagentReports\" | \"subagentCost\">): boolean {\n\treturn summary.subagentReports > 0 || summary.subagentCost > 0;\n}\n\nfunction formatCost(value: number, precision: number): string {\n\treturn `$${value.toFixed(precision)}`;\n}\n\nexport function formatFooterCostParts(\n\tsummary: SessionCostSummary,\n\tprecision = 3,\n\toptions: { subscription?: boolean } = {},\n): string[] {\n\tconst parts: string[] = [];\n\tif (summary.currentCost > 0 || hasSubagentCostSignal(summary) || options.subscription) {\n\t\tparts.push(`CURRENT:${formatCost(summary.currentCost, precision)}${options.subscription ? \" (sub)\" : \"\"}`);\n\t}\n\tif (summary.todayCost > 0) {\n\t\tparts.push(`TODAY:${formatCost(summary.todayCost, precision)}`);\n\t}\n\tif (hasSubagentCostSignal(summary)) {\n\t\tparts.push(`SUBAGENTS:${formatCost(summary.subagentCost, precision)} in CURRENT`);\n\t}\n\treturn parts;\n}\n\nexport function formatStatusCostSummary(summary: SessionCostSummary, precision = 4): string {\n\tconst parts = [\n\t\t`CURRENT ${formatCost(summary.currentCost, precision)}`,\n\t\t`TODAY ${formatCost(summary.todayCost, precision)}`,\n\t];\n\tif (hasSubagentCostSignal(summary)) {\n\t\tparts.push(`SUBAGENTS ${formatCost(summary.subagentCost, precision)} (included in CURRENT)`);\n\t}\n\treturn parts.join(\", \");\n}\n"]}
1
+ {"version":3,"file":"cost-summary.js","sourceRoot":"","sources":["../../../src/core/cost/cost-summary.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,oBAAoB,EAAE,MAAM,iCAAiC,CAAC;AAEvE,OAAO,EAAE,yBAAyB,EAA2B,MAAM,+BAA+B,CAAC;AAsBnG,SAAS,YAAY,CAAC,KAAc;IACnC,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;AAC5D,CAAC;AAED,SAAS,iBAAiB,CAAC,KAAwB;IAClD,MAAM,KAAK,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,CAAC,YAAY,EAAE,SAAS,CAAC,wBAAwB,CAAC,CAAC;IAC9F,CAAC;IACD,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AACzB,CAAC","sourcesContent":["import type { SessionEntry } from \"@caupulican/pi-agent-core/session\";\nimport { getSessionEntryUsage } from \"@caupulican/pi-agent-core/usage\";\nimport type { Usage } from \"@caupulican/pi-ai\";\nimport { SPAWNED_USAGE_CUSTOM_TYPE, type SpawnedUsageReport } from \"../agent-session-contracts.ts\";\nimport type { DailyUsageTotals, DailyUsageWindow } from \"./daily-usage.ts\";\n\nexport interface CurrentSessionCostTotals {\n\townCost: number;\n\tsubagentCost: number;\n\tsubagentReports: number;\n\tcurrentCost: number;\n}\n\nexport interface CurrentSessionCostAccumulator extends CurrentSessionCostTotals {\n\tseenSubagentReportIds: Set<string>;\n}\n\nexport interface SessionCostSummary extends CurrentSessionCostTotals {\n\ttodayCost: number;\n\ttodayOwnCost: number;\n\ttodaySubagentCost: number;\n\ttodayWindow: DailyUsageWindow;\n\ttodayRollover: \"local-midnight\";\n}\n\nfunction isFiniteCost(value: unknown): value is number {\n\treturn typeof value === \"number\" && Number.isFinite(value);\n}\n\nfunction getUsageTotalCost(usage: Usage | undefined): number | undefined {\n\tconst total = usage?.cost?.total;\n\treturn isFiniteCost(total) ? total : undefined;\n}\n\nexport function createCurrentSessionCostAccumulator(): CurrentSessionCostAccumulator {\n\treturn {\n\t\townCost: 0,\n\t\tsubagentCost: 0,\n\t\tsubagentReports: 0,\n\t\tcurrentCost: 0,\n\t\tseenSubagentReportIds: new Set<string>(),\n\t};\n}\n\nexport function accumulateCurrentSessionCostsFromEntries(\n\taccumulator: CurrentSessionCostAccumulator,\n\tentries: readonly SessionEntry[],\n): CurrentSessionCostAccumulator {\n\tfor (const entry of entries) {\n\t\tconst usage = getSessionEntryUsage(entry);\n\t\tif (usage) {\n\t\t\tconst total = getUsageTotalCost(usage);\n\t\t\tif (total !== undefined) accumulator.ownCost += total;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (entry.type !== \"custom\" || entry.customType !== SPAWNED_USAGE_CUSTOM_TYPE) continue;\n\t\tconst report = entry.data as SpawnedUsageReport | undefined;\n\t\tconst total = getUsageTotalCost(report?.usage);\n\t\tif (total === undefined) continue;\n\t\tif (report?.reportId) {\n\t\t\tif (accumulator.seenSubagentReportIds.has(report.reportId)) continue;\n\t\t\taccumulator.seenSubagentReportIds.add(report.reportId);\n\t\t}\n\t\taccumulator.subagentCost += total;\n\t\taccumulator.subagentReports += 1;\n\t}\n\taccumulator.currentCost = accumulator.ownCost + accumulator.subagentCost;\n\treturn accumulator;\n}\n\nexport function aggregateCurrentSessionCostsFromEntries(entries: readonly SessionEntry[]): CurrentSessionCostTotals {\n\tconst { seenSubagentReportIds: _seenSubagentReportIds, ...totals } = accumulateCurrentSessionCostsFromEntries(\n\t\tcreateCurrentSessionCostAccumulator(),\n\t\tentries,\n\t);\n\treturn totals;\n}\n\nexport function createSessionCostSummary(args: {\n\tentries?: readonly SessionEntry[];\n\tdailyTotals: DailyUsageTotals;\n\ttodayWindow: DailyUsageWindow;\n\tcurrentTotals?: CurrentSessionCostTotals;\n}): SessionCostSummary {\n\tconst currentSource = args.currentTotals ?? aggregateCurrentSessionCostsFromEntries(args.entries ?? []);\n\tconst current: CurrentSessionCostTotals = {\n\t\townCost: currentSource.ownCost,\n\t\tsubagentCost: currentSource.subagentCost,\n\t\tsubagentReports: currentSource.subagentReports,\n\t\tcurrentCost: currentSource.currentCost,\n\t};\n\treturn {\n\t\t...current,\n\t\ttodayCost: args.dailyTotals.totalCost,\n\t\ttodayOwnCost: args.dailyTotals.ownCost,\n\t\ttodaySubagentCost: args.dailyTotals.spawnedCost,\n\t\ttodayWindow: args.todayWindow,\n\t\ttodayRollover: \"local-midnight\",\n\t};\n}\n\nexport function hasCostSummarySignal(summary: SessionCostSummary): boolean {\n\treturn summary.currentCost > 0 || summary.todayCost > 0 || summary.subagentReports > 0;\n}\n\nexport function hasSubagentCostSignal(summary: Pick<SessionCostSummary, \"subagentReports\" | \"subagentCost\">): boolean {\n\treturn summary.subagentReports > 0 || summary.subagentCost > 0;\n}\n\nfunction formatCost(value: number, precision: number): string {\n\treturn `$${value.toFixed(precision)}`;\n}\n\nexport function formatFooterCostParts(\n\tsummary: SessionCostSummary,\n\tprecision = 3,\n\toptions: { subscription?: boolean } = {},\n): string[] {\n\tconst parts: string[] = [];\n\tif (summary.currentCost > 0 || hasSubagentCostSignal(summary) || options.subscription) {\n\t\tparts.push(`CURRENT:${formatCost(summary.currentCost, precision)}${options.subscription ? \" (sub)\" : \"\"}`);\n\t}\n\tif (summary.todayCost > 0) {\n\t\tparts.push(`TODAY:${formatCost(summary.todayCost, precision)}`);\n\t}\n\tif (hasSubagentCostSignal(summary)) {\n\t\tparts.push(`SUBAGENTS:${formatCost(summary.subagentCost, precision)} in CURRENT`);\n\t}\n\treturn parts;\n}\n\nexport function formatStatusCostSummary(summary: SessionCostSummary, precision = 4): string {\n\tconst parts = [\n\t\t`CURRENT ${formatCost(summary.currentCost, precision)}`,\n\t\t`TODAY ${formatCost(summary.todayCost, precision)}`,\n\t];\n\tif (hasSubagentCostSignal(summary)) {\n\t\tparts.push(`SUBAGENTS ${formatCost(summary.subagentCost, precision)} (included in CURRENT)`);\n\t}\n\treturn parts.join(\", \");\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { type SessionEntry } from "@caupulican/pi-agent-core/node";
1
+ import { type SessionEntry } from "@caupulican/pi-agent-core/session";
2
2
  export type DailyUsageWindow = {
3
3
  startMs: number;
4
4
  endMs: number;
@@ -1 +1 @@
1
- {"version":3,"file":"daily-usage.d.ts","sourceRoot":"","sources":["../../../src/core/cost/daily-usage.ts"],"names":[],"mappings":"AAGA,OAAO,EAAuB,KAAK,YAAY,EAAE,MAAM,gCAAgC,CAAC;AAIxF,MAAM,MAAM,gBAAgB,GAAG;IAC9B,OAAO,EAAE,MAAM,CAAC;IAChB,KAAK,EAAE,MAAM,C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,EAAE,MAAM,CAAC;CACd,CAAC;AAEF,MAAM,MAAM,gBAAgB,GAAG;IAC9B,OAAO,EAAE,MAAM,CAAC;IAChB,WAAW,EAAE,MAAM,CAAC;IACpB,SAAS,EAAE,MAAM,CAAC;IAClB,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,MAAM,CAAC;IACf,SAAS,EAAE,MAAM,CAAC;IAClB,UAAU,EAAE,MAAM,CAAC;IACnB,WAAW,EAAE,MAAM,CAAC;IACpB,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,MAAM,CAAC;CAChB,CAAC;AA6EF,wBAAgB,8BAA8B,CAC7C,OAAO,EAAE,SAAS,YAAY,EAAE,EAChC,MAAM,EAAE,gBAAgB,GACtB,gBAAgB,CAKlB;AAED,MAAM,WAAW,2BAA2B;IAC3C,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,SAAS,YAAY,EAAE,CAAC;CACjC;AAUD,wBAAgB,mCAAmC,CAClD,UAAU,EAAE,MAAM,EAClB,MAAM,EAAE,gBAAgB,EACxB,WAAW,CAAC,EAAE,2BAA2B,GACvC,gBAAgB,CAclB;AAED,wBAAgB,kCAAkC,CACjD,WAAW,EAAE,MAAM,EACnB,MAAM,EAAE,gBAAgB,EACxB,WAAW,CAAC,EAAE,2BAA2B,GACvC,gBAAgB,CAkBlB;AAED,wBAAgB,yBAAyB,CACxC,MAAM,EAAE,gBAAgB,EACxB,WAAW,GAAE,CAAC,KAAK,EAAE,MAAM,KAAK,MAAyB,GACvD,MAAM,CAQR;AAED,wBAAgB,iBAAiB,CAAC,GAAG,OAAa,GAAG,gBAAgB,CAMpE"}
@@ -1,7 +1,7 @@
1
1
  import { existsSync, readdirSync, statSync } from "node:fs";
2
2
  import { join, resolve } from "node:path";
3
- import { getSessionEntryUsage } from "@caupulican/pi-agent-core";
4
- import { loadEntriesFromFile } from "@caupulican/pi-agent-core/node";
3
+ import { loadEntriesFromFile } from "@caupulican/pi-agent-core/session";
4
+ import { getSessionEntryUsage } from "@caupulican/pi-agent-core/usage";
5
5
  import { SPAWNED_USAGE_CUSTOM_TYPE } from "../agent-session-contracts.js";
6
6
  function createZeroTotals() {
7
7
  return {
@@ -1 +1 @@
1
- {"version":3,"file":"daily-usage.js","sourceRoot":"","sources":["../../../src/core/cost/daily-usage.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AAC5D,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,EAAE,oBAAoB,EAAE,MAAM,2BAA2B,CAAC;AACjE,OAAO,EAAE,mBAAmB,EAAqB,MAAM,gCAAgC,CAAC;AAExF,OAAO,EAAE,yBAAyB,EAA2B,MAAM,+BAA+B,CAAC;AAoBnG,SAAS,gBAAgB;IACxB,OAAO;QACN,OAAO,EAAE,CAAC;QACV,WAAW,EAAE,CAAC;QACd,SAAS,EAAE,CAAC;QACZ,KAAK,EAAE,CAAC;QACR,MAAM,EAAE,CAAC;QACT,SAAS,EAAE,CAAC;QACZ,UAAU,EAAE,CAAC;QACb,WAAW,EAAE,CAAC;QACd,QAAQ,EAAE,CAAC;QACX,OAAO,EAAE,CAAC;KACV,CAAC;AACH,CAAC;AAED,SAAS,cAAc,CAAC,SAAiB,EAAE,MAAwB;IAClE,OAAO,SAAS,IAAI,MAAM,CAAC,OAAO,IAAI,SAAS,GAAG,MAAM,CAAC,KAAK,CAAC;AAChE,CAAC;AAED,SAAS,QAAQ,CAChB,MAA+F,EAC/F,KAAY;IAEZ,MAAM,CAAC,KAAK,IAAI,KAAK,CAAC,KAAK,CAAC;IAC5B,MAAM,CAAC,MAAM,IAAI,KAAK,CAAC,MAAM,CAAC;IAC9B,MAAM,CAAC,SAAS,IAAI,KAAK,CAAC,SAAS,CAAC;IACpC,MAAM,CAAC,UAAU,IAAI,KAAK,CAAC,UAAU,CAAC;IACtC,MAAM,CAAC,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C,CAAC,CAAC;IAC3B,MAAM,GAAG,GAAG,IAAI,IAAI,CAAC,KAAK,CAAC,CAAC;IAC5B,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC,CAAC;IAC/B,OAAO,EAAE,OAAO,EAAE,KAAK,CAAC,OAAO,EAAE,EAAE,KAAK,EAAE,GAAG,CAAC,OAAO,EAAE,EAAE,CAAC;AAC3D,CAAC","sourcesContent":["import { existsSync, readdirSync, statSync } from \"node:fs\";\nimport { join, resolve } from \"node:path\";\nimport { getSessionEntryUsage } from \"@caupulican/pi-agent-core\";\nimport { loadEntriesFromFile, type SessionEntry } from \"@caupulican/pi-agent-core/node\";\nimport type { Usage } from \"@caupulican/pi-ai\";\nimport { SPAWNED_USAGE_CUSTOM_TYPE, type SpawnedUsageReport } from \"../agent-session-contracts.ts\";\n\nexport type DailyUsageWindow = {\n\tstartMs: number;\n\tendMs: number;\n};\n\nexport type DailyUsageTotals = {\n\townCost: number;\n\tspawnedCost: number;\n\ttotalCost: number;\n\tinput: number;\n\toutput: number;\n\tcacheRead: number;\n\tcacheWrite: number;\n\ttotalTokens: number;\n\tsessions: number;\n\treports: number;\n};\n\nfunction createZeroTotals(): DailyUsageTotals {\n\treturn {\n\t\townCost: 0,\n\t\tspawnedCost: 0,\n\t\ttotalCost: 0,\n\t\tinput: 0,\n\t\toutput: 0,\n\t\tcacheRead: 0,\n\t\tcacheWrite: 0,\n\t\ttotalTokens: 0,\n\t\tsessions: 0,\n\t\treports: 0,\n\t};\n}\n\nfunction isInsideWindow(timestamp: number, window: DailyUsageWindow): boolean {\n\treturn timestamp >= window.startMs && timestamp < window.endMs;\n}\n\nfunction addUsage(\n\ttotals: Pick<DailyUsageTotals, \"input\" | \"output\" | \"cacheRead\" | \"cacheWrite\" | \"totalTokens\">,\n\tusage: Usage,\n): void {\n\ttotals.input += usage.input;\n\ttotals.output += usage.output;\n\ttotals.cacheRead += usage.cacheRead;\n\ttotals.cacheWrite += usage.cacheWrite;\n\ttotals.totalTokens += usage.totalTokens;\n}\n\nfunction addDailyUsageFromEntries(\n\ttotals: DailyUsageTotals,\n\tentries: readonly SessionEntry[],\n\twindow: DailyUsageWindow,\n\tseenSpawnedReportIds: Set<string>,\n): boolean {\n\tlet hasUsage = false;\n\tfor (const entry of entries) {\n\t\tif (!isInsideWindow(Date.parse(entry.timestamp), window)) continue;\n\t\tconst usage = getSessionEntryUsage(entry);\n\t\tif (usage) {\n\t\t\ttotals.ownCost += usage.cost.total;\n\t\t\taddUsage(totals, usage);\n\t\t\thasUsage = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (entry.type === \"custom\" && entry.customType === SPAWNED_USAGE_CUSTOM_TYPE) {\n\t\t\tconst data = entry.data as SpawnedUsageReport | undefined;\n\t\t\tif (!data?.usage) continue;\n\t\t\tif (data.reportId) {\n\t\t\t\tif (seenSpawnedReportIds.has(data.reportId)) continue;\n\t\t\t\tseenSpawnedReportIds.add(data.reportId);\n\t\t\t}\n\t\t\ttotals.spawnedCost += data.usage.cost.total;\n\t\t\ttotals.reports += 1;\n\t\t\taddUsage(totals, data.usage);\n\t\t\thasUsage = true;\n\t\t}\n\t}\n\treturn hasUsage;\n}\n\nfunction finishTotals(totals: DailyUsageTotals): DailyUsageTotals {\n\ttotals.totalCost = totals.ownCost + totals.spawnedCost;\n\treturn totals;\n}\n\nfunction shouldReadSessionFile(filePath: string, window: DailyUsageWindow): boolean {\n\ttry {\n\t\treturn statSync(filePath).mtimeMs >= window.startMs;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nexport function aggregateDailyUsageFromEntries(\n\tentries: readonly SessionEntry[],\n\twindow: DailyUsageWindow,\n): DailyUsageTotals {\n\tconst totals = createZeroTotals();\n\tconst hasUsage = addDailyUsageFromEntries(totals, entries, window, new Set());\n\ttotals.sessions = hasUsage ? 1 : 0;\n\treturn finishTotals(totals);\n}\n\nexport interface LiveSessionDailyUsageSource {\n\tfilePath: string;\n\tentries: readonly SessionEntry[];\n}\n\nfunction getSessionEntries(\n\tfilePath: string,\n\tliveSession: LiveSessionDailyUsageSource | undefined,\n): readonly SessionEntry[] {\n\tif (liveSession && resolve(filePath) === resolve(liveSession.filePath)) return liveSession.entries;\n\treturn loadEntriesFromFile(filePath).filter((entry): entry is SessionEntry => entry.type !== \"session\");\n}\n\nexport function aggregateDailyUsageFromSessionFiles(\n\tsessionDir: string,\n\twindow: DailyUsageWindow,\n\tliveSession?: LiveSessionDailyUsageSource,\n): DailyUsageTotals {\n\tconst totals = createZeroTotals();\n\tif (!sessionDir || !existsSync(sessionDir)) return totals;\n\tconst seenSpawnedReportIds = new Set<string>();\n\tfor (const name of readdirSync(sessionDir)) {\n\t\tif (!name.endsWith(\".jsonl\")) continue;\n\t\tconst filePath = join(sessionDir, name);\n\t\tif (!shouldReadSessionFile(filePath, window)) continue;\n\t\tconst entries = getSessionEntries(filePath, liveSession);\n\t\tif (addDailyUsageFromEntries(totals, entries, window, seenSpawnedReportIds)) {\n\t\t\ttotals.sessions += 1;\n\t\t}\n\t}\n\treturn finishTotals(totals);\n}\n\nexport function aggregateDailyUsageFromSessionRoot(\n\tsessionRoot: string,\n\twindow: DailyUsageWindow,\n\tliveSession?: LiveSessionDailyUsageSource,\n): DailyUsageTotals {\n\tconst totals = createZeroTotals();\n\tif (!sessionRoot || !existsSync(sessionRoot)) return totals;\n\tconst seenSpawnedReportIds = new Set<string>();\n\tfor (const name of readdirSync(sessionRoot)) {\n\t\tconst dir = join(sessionRoot, name);\n\t\tif (!existsSync(dir) || !statSync(dir).isDirectory()) continue;\n\t\tfor (const fileName of readdirSync(dir)) {\n\t\t\tif (!fileName.endsWith(\".jsonl\")) continue;\n\t\t\tconst filePath = join(dir, fileName);\n\t\t\tif (!shouldReadSessionFile(filePath, window)) continue;\n\t\t\tconst entries = getSessionEntries(filePath, liveSession);\n\t\t\tif (addDailyUsageFromEntries(totals, entries, window, seenSpawnedReportIds)) {\n\t\t\t\ttotals.sessions += 1;\n\t\t\t}\n\t\t}\n\t}\n\treturn finishTotals(totals);\n}\n\nexport function formatDailyUsageBreakdown(\n\ttotals: DailyUsageTotals,\n\tformatLabel: (label: string) => string = (label) => label,\n): string {\n\treturn [\n\t\t`${formatLabel(\"Today:\")} $${totals.totalCost.toFixed(4)}`,\n\t\t`${formatLabel(\"Own/session messages:\")} $${totals.ownCost.toFixed(4)}`,\n\t\t`${formatLabel(\"Spawned/background reports:\")} $${totals.spawnedCost.toFixed(4)}`,\n\t\t`${formatLabel(\"Sessions scanned:\")} ${totals.sessions}`,\n\t\t`${formatLabel(\"Spawned/background report count:\")} ${totals.reports}`,\n\t].join(\"\\n\");\n}\n\nexport function getLocalDayWindow(now = new Date()): DailyUsageWindow {\n\tconst start = new Date(now);\n\tstart.setHours(0, 0, 0, 0);\n\tconst end = new Date(start);\n\tend.setDate(end.getDate() + 1);\n\treturn { startMs: start.getTime(), endMs: end.getTime() };\n}\n"]}
1
+ {"version":3,"file":"daily-usage.js","sourceRoot":"","sources":["../../../src/core/cost/daily-usage.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AAC5D,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,EAAE,mBAAmB,EAAqB,MAAM,mCAAmC,CAAC;AAC3F,OAAO,EAAE,oBAAoB,EAAE,MAAM,iCAAiC,CAAC;AAEvE,OAAO,EAAE,yBAAyB,EAA2B,MAAM,+BAA+B,CAAC;AAoBnG,SAAS,gBAAgB;IACxB,OAAO;QACN,OAAO,EAAE,CAAC;QACV,WAAW,EAAE,CAAC;QACd,SAAS,EAAE,CAAC;QACZ,KAAK,EAAE,CAAC;QACR,MAAM,EAAE,CAAC;QACT,SAAS,EAAE,CAAC;QACZ,UAAU,EAAE,CAAC;QACb,WAAW,EAAE,CAAC;QACd,QAAQ,EAAE,CAAC;QACX,OAAO,EAAE,CAAC;KACV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,MAAM,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE;QACjF,GAAG,WAAW,CAAC,mBAAmB,CAAC,IAAI,MAAM,CAAC,QAAQ,EAAE;QACxD,GAAG,WAAW,CAAC,kCAAkC,CAAC,IAAI,MAAM,CAAC,OAAO,EAAE;KACtE,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AACd,CAAC;AAED,MAAM,UAAU,iBAAiB,CAAC,GAAG,GAAG,IAAI,IAAI,EAAE;IACjD,MAAM,KAAK,GAAG,IAAI,IAAI,CAAC,GAAG,CAAC,CAAC;IAC5B,KAAK,CAAC,QAAQ,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;IAC3B,MAAM,GAAG,GAAG,IAAI,IAAI,CAAC,KAAK,CAAC,CAAC;IAC5B,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC,CAAC;IAC/B,OAAO,EAAE,OAAO,EAAE,KAAK,CAAC,OAAO,EAAE,EAAE,KAAK,EAAE,GAAG,CAAC,OAAO,EAAE,EAAE,CAAC;AAC3D,CAAC","sourcesContent":["import { existsSync, readdirSync, statSync } from \"node:fs\";\nimport { join, resolve } from \"node:path\";\nimport { loadEntriesFromFile, type SessionEntry } from \"@caupulican/pi-agent-core/session\";\nimport { getSessionEntryUsage } from \"@caupulican/pi-agent-core/usage\";\nimport type { Usage } from \"@caupulican/pi-ai\";\nimport { SPAWNED_USAGE_CUSTOM_TYPE, type SpawnedUsageReport } from \"../agent-session-contracts.ts\";\n\nexport type DailyUsageWindow = {\n\tstartMs: number;\n\tendMs: number;\n};\n\nexport type DailyUsageTotals = {\n\townCost: number;\n\tspawnedCost: number;\n\ttotalCost: number;\n\tinput: number;\n\toutput: number;\n\tcacheRead: number;\n\tcacheWrite: number;\n\ttotalTokens: number;\n\tsessions: number;\n\treports: number;\n};\n\nfunction createZeroTotals(): DailyUsageTotals {\n\treturn {\n\t\townCost: 0,\n\t\tspawnedCost: 0,\n\t\ttotalCost: 0,\n\t\tinput: 0,\n\t\toutput: 0,\n\t\tcacheRead: 0,\n\t\tcacheWrite: 0,\n\t\ttotalTokens: 0,\n\t\tsessions: 0,\n\t\treports: 0,\n\t};\n}\n\nfunction isInsideWindow(timestamp: number, window: DailyUsageWindow): boolean {\n\treturn timestamp >= window.startMs && timestamp < window.endMs;\n}\n\nfunction addUsage(\n\ttotals: Pick<DailyUsageTotals, \"input\" | \"output\" | \"cacheRead\" | \"cacheWrite\" | \"totalTokens\">,\n\tusage: Usage,\n): void {\n\ttotals.input += usage.input;\n\ttotals.output += usage.output;\n\ttotals.cacheRead += usage.cacheRead;\n\ttotals.cacheWrite += usage.cacheWrite;\n\ttotals.totalTokens += usage.totalTokens;\n}\n\nfunction addDailyUsageFromEntries(\n\ttotals: DailyUsageTotals,\n\tentries: readonly SessionEntry[],\n\twindow: DailyUsageWindow,\n\tseenSpawnedReportIds: Set<string>,\n): boolean {\n\tlet hasUsage = false;\n\tfor (const entry of entries) {\n\t\tif (!isInsideWindow(Date.parse(entry.timestamp), window)) continue;\n\t\tconst usage = getSessionEntryUsage(entry);\n\t\tif (usage) {\n\t\t\ttotals.ownCost += usage.cost.total;\n\t\t\taddUsage(totals, usage);\n\t\t\thasUsage = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (entry.type === \"custom\" && entry.customType === SPAWNED_USAGE_CUSTOM_TYPE) {\n\t\t\tconst data = entry.data as SpawnedUsageReport | undefined;\n\t\t\tif (!data?.usage) continue;\n\t\t\tif (data.reportId) {\n\t\t\t\tif (seenSpawnedReportIds.has(data.reportId)) continue;\n\t\t\t\tseenSpawnedReportIds.add(data.reportId);\n\t\t\t}\n\t\t\ttotals.spawnedCost += data.usage.cost.total;\n\t\t\ttotals.reports += 1;\n\t\t\taddUsage(totals, data.usage);\n\t\t\thasUsage = true;\n\t\t}\n\t}\n\treturn hasUsage;\n}\n\nfunction finishTotals(totals: DailyUsageTotals): DailyUsageTotals {\n\ttotals.totalCost = totals.ownCost + totals.spawnedCost;\n\treturn totals;\n}\n\nfunction shouldReadSessionFile(filePath: string, window: DailyUsageWindow): boolean {\n\ttry {\n\t\treturn statSync(filePath).mtimeMs >= window.startMs;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nexport function aggregateDailyUsageFromEntries(\n\tentries: readonly SessionEntry[],\n\twindow: DailyUsageWindow,\n): DailyUsageTotals {\n\tconst totals = createZeroTotals();\n\tconst hasUsage = addDailyUsageFromEntries(totals, entries, window, new Set());\n\ttotals.sessions = hasUsage ? 1 : 0;\n\treturn finishTotals(totals);\n}\n\nexport interface LiveSessionDailyUsageSource {\n\tfilePath: string;\n\tentries: readonly SessionEntry[];\n}\n\nfunction getSessionEntries(\n\tfilePath: string,\n\tliveSession: LiveSessionDailyUsageSource | undefined,\n): readonly SessionEntry[] {\n\tif (liveSession && resolve(filePath) === resolve(liveSession.filePath)) return liveSession.entries;\n\treturn loadEntriesFromFile(filePath).filter((entry): entry is SessionEntry => entry.type !== \"session\");\n}\n\nexport function aggregateDailyUsageFromSessionFiles(\n\tsessionDir: string,\n\twindow: DailyUsageWindow,\n\tliveSession?: LiveSessionDailyUsageSource,\n): DailyUsageTotals {\n\tconst totals = createZeroTotals();\n\tif (!sessionDir || !existsSync(sessionDir)) return totals;\n\tconst seenSpawnedReportIds = new Set<string>();\n\tfor (const name of readdirSync(sessionDir)) {\n\t\tif (!name.endsWith(\".jsonl\")) continue;\n\t\tconst filePath = join(sessionDir, name);\n\t\tif (!shouldReadSessionFile(filePath, window)) continue;\n\t\tconst entries = getSessionEntries(filePath, liveSession);\n\t\tif (addDailyUsageFromEntries(totals, entries, window, seenSpawnedReportIds)) {\n\t\t\ttotals.sessions += 1;\n\t\t}\n\t}\n\treturn finishTotals(totals);\n}\n\nexport function aggregateDailyUsageFromSessionRoot(\n\tsessionRoot: string,\n\twindow: DailyUsageWindow,\n\tliveSession?: LiveSessionDailyUsageSource,\n): DailyUsageTotals {\n\tconst totals = createZeroTotals();\n\tif (!sessionRoot || !existsSync(sessionRoot)) return totals;\n\tconst seenSpawnedReportIds = new Set<string>();\n\tfor (const name of readdirSync(sessionRoot)) {\n\t\tconst dir = join(sessionRoot, name);\n\t\tif (!existsSync(dir) || !statSync(dir).isDirectory()) continue;\n\t\tfor (const fileName of readdirSync(dir)) {\n\t\t\tif (!fileName.endsWith(\".jsonl\")) continue;\n\t\t\tconst filePath = join(dir, fileName);\n\t\t\tif (!shouldReadSessionFile(filePath, window)) continue;\n\t\t\tconst entries = getSessionEntries(filePath, liveSession);\n\t\t\tif (addDailyUsageFromEntries(totals, entries, window, seenSpawnedReportIds)) {\n\t\t\t\ttotals.sessions += 1;\n\t\t\t}\n\t\t}\n\t}\n\treturn finishTotals(totals);\n}\n\nexport function formatDailyUsageBreakdown(\n\ttotals: DailyUsageTotals,\n\tformatLabel: (label: string) => string = (label) => label,\n): string {\n\treturn [\n\t\t`${formatLabel(\"Today:\")} $${totals.totalCost.toFixed(4)}`,\n\t\t`${formatLabel(\"Own/session messages:\")} $${totals.ownCost.toFixed(4)}`,\n\t\t`${formatLabel(\"Spawned/background reports:\")} $${totals.spawnedCost.toFixed(4)}`,\n\t\t`${formatLabel(\"Sessions scanned:\")} ${totals.sessions}`,\n\t\t`${formatLabel(\"Spawned/background report count:\")} ${totals.reports}`,\n\t].join(\"\\n\");\n}\n\nexport function getLocalDayWindow(now = new Date()): DailyUsageWindow {\n\tconst start = new Date(now);\n\tstart.setHours(0, 0, 0, 0);\n\tconst end = new Date(start);\n\tend.setDate(end.getDate() + 1);\n\treturn { startMs: start.getTime(), endMs: end.getTime() };\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { type SessionEntry } from "@caupulican/pi-agent-core/node";
1
+ import { type SessionEntry } from "@caupulican/pi-agent-core/session";
2
2
  import type { Usage } from "@caupulican/pi-ai";
3
3
  export declare function readAutoLearnSessionIdFromFile(filePath: string): string | undefined;
4
4
  export declare function findChildSessionFile(sessionDir: string, sessionId: string): string | undefined;
@@ -1 +1 @@
1
- {"version":3,"file":"session-usage.d.ts","sourceRoot":"","sources":["../../../src/core/cost/session-usage.ts"],"names":[],"mappings":"AAEA,OAAO,EAAuB,KAAK,YAAY,EAAE,MAAM,gCAAgC,CAAC;AACxF,OAAO,KAAK,EAAoB,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAsBjE,wBAAgB,8BAA8B,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAqBnF;AAED,wBAAgB,oBAAoB,CAAC,UAAU,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAuC9F;AAED,wBAAgB,0CAA0C,CAAC,OAAO,EAAE,YAAY,EAAE,GAAG,KAAK,CAyDzF;AAED,wBAAgB,mCAAmC,CAAC,IAAI,EAAE;IACzD,KAAK,EAAE,MAAM,CAAC;IACd,UAAU,EAAE,MAAM,CAAC;IACnB,SAAS,EAAE,MAAM,CAAC;IAClB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,aAAa,EAAE;QACd,eAAe,EAAE,CAChB,KAAK,EAAE,KAAK,EACZ,IAAI,EAAE;YAAE,KAAK,EAAE,MAAM,CAAC;YAAC,eAAe,EAAE,MAAM,CAAC;YAAC,QAAQ,EAAE,MAAM,CAAA;SAAE,KAC9D,MAAM,GAAG,SAAS,CAAC;KACxB,CAAC;IACF,SAAS,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,KAAK,IAAI,CAAC;CACvD,GAAG,IAAI,CA0BP"}
1
+ {"version":3,"file":"session-usage.d.ts","sourceRoot":"","sources":["../../../src/core/cost/session-usage.ts"],"names":[],"mappings":"AAEA,OAAO,EAAuB,KAAK,YAAY,EAAE,MAAM,mCAAmC,CAAC;AAC3F,OAAO,KAAK,EAAoB,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAsBjE,wBAAgB,8BAA8B,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAqBnF;AAED,wBAAgB,oBAAoB,CAAC,UAAU,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAuC9F;AAED,wBAAgB,0CAA0C,CAAC,OAAO,EAAE,YAAY,EAAE,GAAG,KAAK,CAyDzF;AAED,wBAAgB,mCAAmC,CAAC,IAAI,EAAE;IACzD,KAAK,EAAE,MAAM,CAAC;IACd,UAAU,EAAE,MAAM,CAAC;IACnB,SAAS,EAAE,MAAM,CAAC;IAClB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,aAAa,EAAE;QACd,eAAe,EAAE,CAChB,KAAK,EAAE,KAAK,EACZ,IAAI,EAAE;YAAE,KAAK,EAAE,MAAM,CAAC;YAAC,eAAe,EAAE,MAAM,CAAC;YAAC,QAAQ,EAAE,MAAM,CAAA;SAAE,KAC9D,MAAM,GAAG,SAAS,CAAC;KACxB,CAAC;IACF,SAAS,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,KAAK,IAAI,CAAC;CACvD,GAAG,IAAI,CA0BP"}
@@ -1,6 +1,6 @@
1
1
  import * as fs from "node:fs";
2
2
  import { basename, join } from "node:path";
3
- import { loadEntriesFromFile } from "@caupulican/pi-agent-core/node";
3
+ import { loadEntriesFromFile } from "@caupulican/pi-agent-core/session";
4
4
  import { SPAWNED_USAGE_CUSTOM_TYPE } from "../agent-session.js";
5
5
  function isUsage(value) {
6
6
  if (!value || typeof value !== "object")
@@ -1 +1 @@
1
- {"version":3,"file":"session-usage.js","sourceRoot":"","sources":["../../../src/core/cost/session-usage.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,SAAS,CAAC;AAC9B,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAC3C,OAAO,EAAE,mBAAmB,EAAqB,MAAM,gCAAgC,CAAC;AAExF,OAAO,EAAE,yBAAyB,EAA2B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,EAAE,SAAS;QAC1B,QAAQ,EAAE,cAAc,KAAK,IAAI,SAAS,EAAE;KAC5C,CAAC,CAAC;IACH,IAAI,OAAO,IAAI,SAAS,EAAE,CAAC;QAC1B,SAAS,CAAC,OAAO,EAAE,8BAA8B,SAAS,GAAG,CAAC,CAAC;IAChE,CAAC;AACF,CAAC","sourcesContent":["import * as fs from \"node:fs\";\nimport { basename, join } from \"node:path\";\nimport { loadEntriesFromFile, type SessionEntry } from \"@caupulican/pi-agent-core/node\";\nimport type { AssistantMessage, Usage } from \"@caupulican/pi-ai\";\nimport { SPAWNED_USAGE_CUSTOM_TYPE, type SpawnedUsageReport } from \"../agent-session.ts\";\n\nfunction isUsage(value: unknown): value is Usage {\n\tif (!value || typeof value !== \"object\") return false;\n\tconst usage = value as Partial<Usage>;\n\tconst cost = usage.cost as Partial<Usage[\"cost\"]> | undefined;\n\treturn (\n\t\ttypeof usage.input === \"number\" &&\n\t\ttypeof usage.output === \"number\" &&\n\t\ttypeof usage.cacheRead === \"number\" &&\n\t\ttypeof usage.cacheWrite === \"number\" &&\n\t\ttypeof usage.totalTokens === \"number\" &&\n\t\t!!cost &&\n\t\ttypeof cost.input === \"number\" &&\n\t\ttypeof cost.output === \"number\" &&\n\t\ttypeof cost.cacheRead === \"number\" &&\n\t\ttypeof cost.cacheWrite === \"number\" &&\n\t\ttypeof cost.total === \"number\"\n\t);\n}\n\nexport function readAutoLearnSessionIdFromFile(filePath: string): string | undefined {\n\tlet fd: number | undefined;\n\ttry {\n\t\tfd = fs.openSync(filePath, \"r\");\n\t\tconst buffer = Buffer.alloc(64 * 1024);\n\t\tconst bytesRead = fs.readSync(fd, buffer, 0, buffer.length, 0);\n\t\tconst firstLine = buffer.toString(\"utf8\", 0, bytesRead).split(\"\\n\", 1)[0]?.trim();\n\t\tif (!firstLine) return undefined;\n\t\tconst header = JSON.parse(firstLine) as Record<string, unknown>;\n\t\treturn header.type === \"session\" && typeof header.id === \"string\" ? header.id : undefined;\n\t} catch {\n\t\treturn undefined;\n\t} finally {\n\t\tif (fd !== undefined) {\n\t\t\ttry {\n\t\t\t\tfs.closeSync(fd);\n\t\t\t} catch {\n\t\t\t\t// Ignore close errors\n\t\t\t}\n\t\t}\n\t}\n}\n\nexport function findChildSessionFile(sessionDir: string, sessionId: string): string | undefined {\n\tif (!fs.existsSync(sessionDir)) return undefined;\n\n\tconst jsonlFiles: string[] = [];\n\n\tfunction collectJsonlFiles(dirPath: string) {\n\t\tlet currentEntries: fs.Dirent[];\n\t\ttry {\n\t\t\tcurrentEntries = fs.readdirSync(dirPath, { withFileTypes: true });\n\t\t} catch {\n\t\t\treturn;\n\t\t}\n\t\tfor (const entry of currentEntries) {\n\t\t\tconst fullPath = join(dirPath, entry.name);\n\t\t\tif (entry.isDirectory()) {\n\t\t\t\tcollectJsonlFiles(fullPath);\n\t\t\t} else if (entry.isFile() && entry.name.endsWith(\".jsonl\")) {\n\t\t\t\tjsonlFiles.push(fullPath);\n\t\t\t}\n\t\t}\n\t}\n\n\tcollectJsonlFiles(sessionDir);\n\n\tfor (const file of jsonlFiles) {\n\t\tconst base = basename(file);\n\t\tif (base === `${sessionId}.jsonl` || base.endsWith(`_${sessionId}.jsonl`)) {\n\t\t\treturn file;\n\t\t}\n\t}\n\n\tfor (const file of jsonlFiles) {\n\t\tconst headerId = readAutoLearnSessionIdFromFile(file);\n\t\tif (headerId === sessionId) {\n\t\t\treturn file;\n\t\t}\n\t}\n\n\treturn undefined;\n}\n\nexport function aggregateCumulativeUsageFromSessionEntries(entries: SessionEntry[]): Usage {\n\tlet input = 0;\n\tlet output = 0;\n\tlet cacheRead = 0;\n\tlet cacheWrite = 0;\n\tlet totalTokens = 0;\n\tlet costInput = 0;\n\tlet costOutput = 0;\n\tlet costCacheRead = 0;\n\tlet costCacheWrite = 0;\n\tlet costTotal = 0;\n\n\tconst add = (usage: Usage) => {\n\t\tinput += usage.input;\n\t\toutput += usage.output;\n\t\tcacheRead += usage.cacheRead;\n\t\tcacheWrite += usage.cacheWrite;\n\t\ttotalTokens += usage.totalTokens;\n\t\tcostInput += usage.cost.input;\n\t\tcostOutput += usage.cost.output;\n\t\tcostCacheRead += usage.cost.cacheRead;\n\t\tcostCacheWrite += usage.cost.cacheWrite;\n\t\tcostTotal += usage.cost.total;\n\t};\n\n\tconst seenSpawnedReportIds = new Set<string>();\n\tfor (const entry of entries) {\n\t\tif (entry.type === \"message\" && entry.message.role === \"assistant\") {\n\t\t\tconst usage = (entry.message as AssistantMessage).usage;\n\t\t\tif (usage && isUsage(usage)) {\n\t\t\t\tadd(usage);\n\t\t\t}\n\t\t} else if (entry.type === \"custom\" && entry.customType === SPAWNED_USAGE_CUSTOM_TYPE) {\n\t\t\tconst data = entry.data as SpawnedUsageReport | undefined;\n\t\t\tif (!data?.usage || !isUsage(data.usage)) continue;\n\t\t\tif (data.reportId) {\n\t\t\t\tif (seenSpawnedReportIds.has(data.reportId)) continue;\n\t\t\t\tseenSpawnedReportIds.add(data.reportId);\n\t\t\t}\n\t\t\tadd(data.usage);\n\t\t}\n\t}\n\n\treturn {\n\t\tinput,\n\t\toutput,\n\t\tcacheRead,\n\t\tcacheWrite,\n\t\ttotalTokens,\n\t\tcost: {\n\t\t\tinput: costInput,\n\t\t\toutput: costOutput,\n\t\t\tcacheRead: costCacheRead,\n\t\t\tcacheWrite: costCacheWrite,\n\t\t\ttotal: costTotal,\n\t\t},\n\t};\n}\n\nexport function reportCompletedAutoLearnUsageHelper(args: {\n\trunId: string;\n\tsessionDir: string;\n\tsessionId: string;\n\tlogPath?: string;\n\tparentSession: {\n\t\taddSpawnedUsage: (\n\t\t\tusage: Usage,\n\t\t\topts: { label: string; sourceSessionId: string; reportId: string },\n\t\t) => string | undefined;\n\t};\n\tappendLog?: (logPath: string, message: string) => void;\n}): void {\n\tconst { runId, sessionDir, sessionId, logPath, parentSession, appendLog } = args;\n\tconst sessionFile = findChildSessionFile(sessionDir, sessionId);\n\tif (!sessionFile) {\n\t\tif (logPath && appendLog) {\n\t\t\tappendLog(logPath, `Auto Learn usage report skipped: no child session file found for ${sessionId}.`);\n\t\t}\n\t\treturn;\n\t}\n\tconst fileEntries = loadEntriesFromFile(sessionFile);\n\tconst sessionEntries = fileEntries.filter((entry): entry is SessionEntry => entry.type !== \"session\");\n\tconst usage = aggregateCumulativeUsageFromSessionEntries(sessionEntries);\n\tif (usage.cost.total === 0 && usage.totalTokens === 0) {\n\t\tif (logPath && appendLog) {\n\t\t\tappendLog(logPath, `Auto Learn usage report skipped: child session had no usage for ${sessionId}.`);\n\t\t}\n\t\treturn;\n\t}\n\tparentSession.addSpawnedUsage(usage, {\n\t\tlabel: \"auto-learn\",\n\t\tsourceSessionId: sessionId,\n\t\treportId: `auto-learn:${runId}:${sessionId}`,\n\t});\n\tif (logPath && appendLog) {\n\t\tappendLog(logPath, `Auto Learn usage reported: ${sessionId}.`);\n\t}\n}\n"]}
1
+ {"version":3,"file":"session-usage.js","sourceRoot":"","sources":["../../../src/core/cost/session-usage.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,SAAS,CAAC;AAC9B,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAC3C,OAAO,EAAE,mBAAmB,EAAqB,MAAM,mCAAmC,CAAC;AAE3F,OAAO,EAAE,yBAAyB,EAA2B,MAAM,qBAAqB,CAAC;AAEzF,SAAS,OAAO,CAAC,KAAc;IAC9B,IAAI,CAAC,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ;QAAE,OAAO,KAAK,CAAC;IACtD,MAAM,KAAK,GAAG,KAAuB,CAAC;IACtC,MAAM,IAAI,GAAG,KAAK,CAAC,IAA0C,CAAC;IAC9D,OAAO,CACN,OAAO,KAAK,CAAC,KAAK,KAAK,QAAQ;QAC/B,OAAO,KAAK,CAAC,MAAM,KAAK,QAAQ;QAChC,OAAO,KAAK,CAAC,SAAS,KAAK,QAAQ;QACnC,OAAO,KAAK,CAAC,UAAU,KAAK,QAAQ;QACpC,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EAAE,GAAG,IAAI,CAAC;IACjF,MAAM,WAAW,GAAG,oBAAoB,CAAC,UAAU,EAAE,SAAS,CAAC,CAAC;IAChE,IAAI,CAAC,WAAW,EAAE,CAAC;QAClB,IAAI,OAAO,IAAI,SAAS,EAAE,CAAC;YAC1B,SAAS,CAAC,OAAO,EAAE,oEAAoE,SAAS,GAAG,CAAC,CAAC;QACtG,CAAC;QACD,OAAO;IACR,CAAC;IACD,MAAM,WAAW,GAAG,mBAAmB,CAAC,WAAW,CAAC,CAAC;IACrD,MAAM,cAAc,GAAG,WAAW,CAAC,MAAM,CAAC,CAAC,KAAK,EAAyB,EAAE,CAAC,KAAK,CAAC,IAAI,KAAK,SAAS,CAAC,CAAC;IACtG,MAAM,KAAK,GAAG,0CAA0C,CAAC,cAAc,CAAC,CAAC;IACzE,IAAI,KAAK,CAAC,IAAI,CAAC,KAAK,KAAK,CAAC,IAAI,KAAK,CAAC,WAAW,KAAK,CAAC,EAAE,CAAC;QACvD,IAAI,OAAO,IAAI,SAAS,EAAE,CAAC;YAC1B,SAAS,CAAC,OAAO,EAAE,mEAAmE,SAAS,GAAG,CAAC,CAAC;QACrG,CAAC;QACD,OAAO;IACR,CAAC;IACD,aAAa,CAAC,eAAe,CAAC,KAAK,EAAE;QACpC,KAAK,EAAE,YAAY;QACnB,eAAe,EAAE,SAAS;QAC1B,QAAQ,EAAE,cAAc,KAAK,IAAI,SAAS,EAAE;KAC5C,CAAC,CAAC;IACH,IAAI,OAAO,IAAI,SAAS,EAAE,CAAC;QAC1B,SAAS,CAAC,OAAO,EAAE,8BAA8B,SAAS,GAAG,CAAC,CAAC;IAChE,CAAC;AACF,CAAC","sourcesContent":["import * as fs from \"node:fs\";\nimport { basename, join } from \"node:path\";\nimport { loadEntriesFromFile, type SessionEntry } from \"@caupulican/pi-agent-core/session\";\nimport type { AssistantMessage, Usage } from \"@caupulican/pi-ai\";\nimport { SPAWNED_USAGE_CUSTOM_TYPE, type SpawnedUsageReport } from \"../agent-session.ts\";\n\nfunction isUsage(value: unknown): value is Usage {\n\tif (!value || typeof value !== \"object\") return false;\n\tconst usage = value as Partial<Usage>;\n\tconst cost = usage.cost as Partial<Usage[\"cost\"]> | undefined;\n\treturn (\n\t\ttypeof usage.input === \"number\" &&\n\t\ttypeof usage.output === \"number\" &&\n\t\ttypeof usage.cacheRead === \"number\" &&\n\t\ttypeof usage.cacheWrite === \"number\" &&\n\t\ttypeof usage.totalTokens === \"number\" &&\n\t\t!!cost &&\n\t\ttypeof cost.input === \"number\" &&\n\t\ttypeof cost.output === \"number\" &&\n\t\ttypeof cost.cacheRead === \"number\" &&\n\t\ttypeof cost.cacheWrite === \"number\" &&\n\t\ttypeof cost.total === \"number\"\n\t);\n}\n\nexport function readAutoLearnSessionIdFromFile(filePath: string): string | undefined {\n\tlet fd: number | undefined;\n\ttry {\n\t\tfd = fs.openSync(filePath, \"r\");\n\t\tconst buffer = Buffer.alloc(64 * 1024);\n\t\tconst bytesRead = fs.readSync(fd, buffer, 0, buffer.length, 0);\n\t\tconst firstLine = buffer.toString(\"utf8\", 0, bytesRead).split(\"\\n\", 1)[0]?.trim();\n\t\tif (!firstLine) return undefined;\n\t\tconst header = JSON.parse(firstLine) as Record<string, unknown>;\n\t\treturn header.type === \"session\" && typeof header.id === \"string\" ? header.id : undefined;\n\t} catch {\n\t\treturn undefined;\n\t} finally {\n\t\tif (fd !== undefined) {\n\t\t\ttry {\n\t\t\t\tfs.closeSync(fd);\n\t\t\t} catch {\n\t\t\t\t// Ignore close errors\n\t\t\t}\n\t\t}\n\t}\n}\n\nexport function findChildSessionFile(sessionDir: string, sessionId: string): string | undefined {\n\tif (!fs.existsSync(sessionDir)) return undefined;\n\n\tconst jsonlFiles: string[] = [];\n\n\tfunction collectJsonlFiles(dirPath: string) {\n\t\tlet currentEntries: fs.Dirent[];\n\t\ttry {\n\t\t\tcurrentEntries = fs.readdirSync(dirPath, { withFileTypes: true });\n\t\t} catch {\n\t\t\treturn;\n\t\t}\n\t\tfor (const entry of currentEntries) {\n\t\t\tconst fullPath = join(dirPath, entry.name);\n\t\t\tif (entry.isDirectory()) {\n\t\t\t\tcollectJsonlFiles(fullPath);\n\t\t\t} else if (entry.isFile() && entry.name.endsWith(\".jsonl\")) {\n\t\t\t\tjsonlFiles.push(fullPath);\n\t\t\t}\n\t\t}\n\t}\n\n\tcollectJsonlFiles(sessionDir);\n\n\tfor (const file of jsonlFiles) {\n\t\tconst base = basename(file);\n\t\tif (base === `${sessionId}.jsonl` || base.endsWith(`_${sessionId}.jsonl`)) {\n\t\t\treturn file;\n\t\t}\n\t}\n\n\tfor (const file of jsonlFiles) {\n\t\tconst headerId = readAutoLearnSessionIdFromFile(file);\n\t\tif (headerId === sessionId) {\n\t\t\treturn file;\n\t\t}\n\t}\n\n\treturn undefined;\n}\n\nexport function aggregateCumulativeUsageFromSessionEntries(entries: SessionEntry[]): Usage {\n\tlet input = 0;\n\tlet output = 0;\n\tlet cacheRead = 0;\n\tlet cacheWrite = 0;\n\tlet totalTokens = 0;\n\tlet costInput = 0;\n\tlet costOutput = 0;\n\tlet costCacheRead = 0;\n\tlet costCacheWrite = 0;\n\tlet costTotal = 0;\n\n\tconst add = (usage: Usage) => {\n\t\tinput += usage.input;\n\t\toutput += usage.output;\n\t\tcacheRead += usage.cacheRead;\n\t\tcacheWrite += usage.cacheWrite;\n\t\ttotalTokens += usage.totalTokens;\n\t\tcostInput += usage.cost.input;\n\t\tcostOutput += usage.cost.output;\n\t\tcostCacheRead += usage.cost.cacheRead;\n\t\tcostCacheWrite += usage.cost.cacheWrite;\n\t\tcostTotal += usage.cost.total;\n\t};\n\n\tconst seenSpawnedReportIds = new Set<string>();\n\tfor (const entry of entries) {\n\t\tif (entry.type === \"message\" && entry.message.role === \"assistant\") {\n\t\t\tconst usage = (entry.message as AssistantMessage).usage;\n\t\t\tif (usage && isUsage(usage)) {\n\t\t\t\tadd(usage);\n\t\t\t}\n\t\t} else if (entry.type === \"custom\" && entry.customType === SPAWNED_USAGE_CUSTOM_TYPE) {\n\t\t\tconst data = entry.data as SpawnedUsageReport | undefined;\n\t\t\tif (!data?.usage || !isUsage(data.usage)) continue;\n\t\t\tif (data.reportId) {\n\t\t\t\tif (seenSpawnedReportIds.has(data.reportId)) continue;\n\t\t\t\tseenSpawnedReportIds.add(data.reportId);\n\t\t\t}\n\t\t\tadd(data.usage);\n\t\t}\n\t}\n\n\treturn {\n\t\tinput,\n\t\toutput,\n\t\tcacheRead,\n\t\tcacheWrite,\n\t\ttotalTokens,\n\t\tcost: {\n\t\t\tinput: costInput,\n\t\t\toutput: costOutput,\n\t\t\tcacheRead: costCacheRead,\n\t\t\tcacheWrite: costCacheWrite,\n\t\t\ttotal: costTotal,\n\t\t},\n\t};\n}\n\nexport function reportCompletedAutoLearnUsageHelper(args: {\n\trunId: string;\n\tsessionDir: string;\n\tsessionId: string;\n\tlogPath?: string;\n\tparentSession: {\n\t\taddSpawnedUsage: (\n\t\t\tusage: Usage,\n\t\t\topts: { label: string; sourceSessionId: string; reportId: string },\n\t\t) => string | undefined;\n\t};\n\tappendLog?: (logPath: string, message: string) => void;\n}): void {\n\tconst { runId, sessionDir, sessionId, logPath, parentSession, appendLog } = args;\n\tconst sessionFile = findChildSessionFile(sessionDir, sessionId);\n\tif (!sessionFile) {\n\t\tif (logPath && appendLog) {\n\t\t\tappendLog(logPath, `Auto Learn usage report skipped: no child session file found for ${sessionId}.`);\n\t\t}\n\t\treturn;\n\t}\n\tconst fileEntries = loadEntriesFromFile(sessionFile);\n\tconst sessionEntries = fileEntries.filter((entry): entry is SessionEntry => entry.type !== \"session\");\n\tconst usage = aggregateCumulativeUsageFromSessionEntries(sessionEntries);\n\tif (usage.cost.total === 0 && usage.totalTokens === 0) {\n\t\tif (logPath && appendLog) {\n\t\t\tappendLog(logPath, `Auto Learn usage report skipped: child session had no usage for ${sessionId}.`);\n\t\t}\n\t\treturn;\n\t}\n\tparentSession.addSpawnedUsage(usage, {\n\t\tlabel: \"auto-learn\",\n\t\tsourceSessionId: sessionId,\n\t\treportId: `auto-learn:${runId}:${sessionId}`,\n\t});\n\tif (logPath && appendLog) {\n\t\tappendLog(logPath, `Auto Learn usage reported: ${sessionId}.`);\n\t}\n}\n"]}
@@ -8,6 +8,7 @@
8
8
  * `bash` is the stable agent shell contract on every platform; its finite grammar routes to
9
9
  * PowerShell on Windows. `python` is a separate bounded, uv-managed execution contract.
10
10
  */
11
+ export declare const STABLE_SHELL_TOOL_NAME: "bash";
11
12
  export declare function getDefaultActiveToolNames(_platform?: NodeJS.Platform): readonly string[];
12
13
  /** Current-process default tool request. */
13
14
  export declare const DEFAULT_ACTIVE_TOOL_NAMES: readonly string[];
@@ -1 +1 @@
1
- {"version":3,"file":"default-tool-surface.d.ts","sourceRoot":"","sources":["../../src/core/default-tool-surface.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,wBAAgB,yBAAyB,CAAC,SAAS,GAAE,MAAM,CAAC,QAA2B,GAAG,SAAS,MAAM,EAAE,CAiB1G;AAED,4CAA4C;AAC5C,eAAO,MAAM,yBAAyB,EAAE,SAAS,MAAM,EAAgC,CAAC;AAExF,uFAAuF;AACvF,wBAAgB,uBAAuB,CACtC,KAAK,EAAE,SAAS,MAAM,EAAE,EACxB,SAAS,GAAE,MAAM,CAAC,QAA2B,GAC3C,MAAM,EAAE,CAOV"}
1
+ {"version":3,"file":"default-tool-surface.d.ts","sourceRoot":"","sources":["../../src/core/default-tool-surface.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,eAAO,MAAM,sBAAsB,EAAG,MAAe,CAAC;AAEtD,wBAAgB,yBAAyB,CAAC,SAAS,GAAE,MAAM,CAAC,QAA2B,GAAG,SAAS,MAAM,EAAE,CAiB1G;AAED,4CAA4C;AAC5C,eAAO,MAAM,yBAAyB,EAAE,SAAS,MAAM,EAAgC,CAAC;AAExF,uFAAuF;AACvF,wBAAgB,uBAAuB,CACtC,KAAK,EAAE,SAAS,MAAM,EAAE,EACxB,SAAS,GAAE,MAAM,CAAC,QAA2B,GAC3C,MAAM,EAAE,CAOV"}
@@ -8,10 +8,11 @@
8
8
  * `bash` is the stable agent shell contract on every platform; its finite grammar routes to
9
9
  * PowerShell on Windows. `python` is a separate bounded, uv-managed execution contract.
10
10
  */
11
+ export const STABLE_SHELL_TOOL_NAME = "bash";
11
12
  export function getDefaultActiveToolNames(_platform = process.platform) {
12
13
  return [
13
14
  "read",
14
- "bash",
15
+ STABLE_SHELL_TOOL_NAME,
15
16
  "python",
16
17
  "edit",
17
18
  "write",
@@ -32,7 +33,7 @@ export const DEFAULT_ACTIVE_TOOL_NAMES = getDefaultActiveToolNames();
32
33
  export function mapToolNamesForPlatform(names, _platform = process.platform) {
33
34
  const mapped = [];
34
35
  for (const name of names) {
35
- const resolved = name === "powershell" ? "bash" : name;
36
+ const resolved = name === "powershell" ? STABLE_SHELL_TOOL_NAME : name;
36
37
  if (!mapped.includes(resolved))
37
38
  mapped.push(resolved);
38
39
  }
@@ -1 +1 @@
1
- {"version":3,"file":"default-tool-surface.js","sourceRoot":"","sources":["../../src/core/default-tool-surface.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,MAAM,UAAU,yBAAyB,CAAC,SAAS,GAAoB,OAAO,CAAC,QAAQ;IACtF,OAAO;QACN,MAAM;QACN,MAAM;QACN,QAAQ;QACR,MAAM;QACN,OAAO;QACP,eAAe;QACf,MAAM;QACN,YAAY;QACZ,cAAc;QACd,cAAc;QACd,UAAU;QACV,gBAAgB;QAChB,WAAW;QACX,oBAAoB;KACpB,CAAC;AACH,CAAC;AAED,4CAA4C;AAC5C,MAAM,CAAC,MAAM,yBAAyB,GAAsB,yBAAyB,EAAE,CAAC;AAExF,uFAAuF;AACvF,MAAM,UAAU,uBAAuB,CACtC,KAAwB,EACxB,SAAS,GAAoB,OAAO,CAAC,QAAQ;IAE7C,MAAM,MAAM,GAAa,EAAE,CAAC;IAC5B,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;QAC1B,MAAM,QAAQ,GAAG,IAAI,KAAK,YAAY,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC;QACvD,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,QAAQ,CAAC;YAAE,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;IACvD,CAAC;IACD,OAAO,MAAM,CAAC;AACf,CAAC","sourcesContent":["/**\n * Default built-in tool request shared by every AgentSession construction path.\n *\n * RuntimeBuilder still registers additional opt-in tools, while model capability and UAC profile\n * filters may only narrow this request. Keeping the SDK and direct-runtime paths on one list avoids\n * silently losing goal/delegation/toolkit capabilities in SDK-created interactive sessions.\n *\n * `bash` is the stable agent shell contract on every platform; its finite grammar routes to\n * PowerShell on Windows. `python` is a separate bounded, uv-managed execution contract.\n */\nexport function getDefaultActiveToolNames(_platform: NodeJS.Platform = process.platform): readonly string[] {\n\treturn [\n\t\t\"read\",\n\t\t\"bash\",\n\t\t\"python\",\n\t\t\"edit\",\n\t\t\"write\",\n\t\t\"context_audit\",\n\t\t\"goal\",\n\t\t\"task_steps\",\n\t\t\"ask_question\",\n\t\t\"secret_store\",\n\t\t\"delegate\",\n\t\t\"profile_writer\",\n\t\t\"tool_task\",\n\t\t\"run_toolkit_script\",\n\t];\n}\n\n/** Current-process default tool request. */\nexport const DEFAULT_ACTIVE_TOOL_NAMES: readonly string[] = getDefaultActiveToolNames();\n\n/** Map legacy/platform-specific shell names to the stable Bash-like agent contract. */\nexport function mapToolNamesForPlatform(\n\tnames: readonly string[],\n\t_platform: NodeJS.Platform = process.platform,\n): string[] {\n\tconst mapped: string[] = [];\n\tfor (const name of names) {\n\t\tconst resolved = name === \"powershell\" ? \"bash\" : name;\n\t\tif (!mapped.includes(resolved)) mapped.push(resolved);\n\t}\n\treturn mapped;\n}\n"]}
1
+ {"version":3,"file":"default-tool-surface.js","sourceRoot":"","sources":["../../src/core/default-tool-surface.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,MAAM,CAAC,MAAM,sBAAsB,GAAG,MAAe,CAAC;AAEtD,MAAM,UAAU,yBAAyB,CAAC,SAAS,GAAoB,OAAO,CAAC,QAAQ;IACtF,OAAO;QACN,MAAM;QACN,sBAAsB;QACtB,QAAQ;QACR,MAAM;QACN,OAAO;QACP,eAAe;QACf,MAAM;QACN,YAAY;QACZ,cAAc;QACd,cAAc;QACd,UAAU;QACV,gBAAgB;QAChB,WAAW;QACX,oBAAoB;KACpB,CAAC;AACH,CAAC;AAED,4CAA4C;AAC5C,MAAM,CAAC,MAAM,yBAAyB,GAAsB,yBAAyB,EAAE,CAAC;AAExF,uFAAuF;AACvF,MAAM,UAAU,uBAAuB,CACtC,KAAwB,EACxB,SAAS,GAAoB,OAAO,CAAC,QAAQ;IAE7C,MAAM,MAAM,GAAa,EAAE,CAAC;IAC5B,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;QAC1B,MAAM,QAAQ,GAAG,IAAI,KAAK,YAAY,CAAC,CAAC,CAAC,sBAAsB,CAAC,CAAC,CAAC,IAAI,CAAC;QACvE,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,QAAQ,CAAC;YAAE,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;IACvD,CAAC;IACD,OAAO,MAAM,CAAC;AACf,CAAC","sourcesContent":["/**\n * Default built-in tool request shared by every AgentSession construction path.\n *\n * RuntimeBuilder still registers additional opt-in tools, while model capability and UAC profile\n * filters may only narrow this request. Keeping the SDK and direct-runtime paths on one list avoids\n * silently losing goal/delegation/toolkit capabilities in SDK-created interactive sessions.\n *\n * `bash` is the stable agent shell contract on every platform; its finite grammar routes to\n * PowerShell on Windows. `python` is a separate bounded, uv-managed execution contract.\n */\nexport const STABLE_SHELL_TOOL_NAME = \"bash\" as const;\n\nexport function getDefaultActiveToolNames(_platform: NodeJS.Platform = process.platform): readonly string[] {\n\treturn [\n\t\t\"read\",\n\t\tSTABLE_SHELL_TOOL_NAME,\n\t\t\"python\",\n\t\t\"edit\",\n\t\t\"write\",\n\t\t\"context_audit\",\n\t\t\"goal\",\n\t\t\"task_steps\",\n\t\t\"ask_question\",\n\t\t\"secret_store\",\n\t\t\"delegate\",\n\t\t\"profile_writer\",\n\t\t\"tool_task\",\n\t\t\"run_toolkit_script\",\n\t];\n}\n\n/** Current-process default tool request. */\nexport const DEFAULT_ACTIVE_TOOL_NAMES: readonly string[] = getDefaultActiveToolNames();\n\n/** Map legacy/platform-specific shell names to the stable Bash-like agent contract. */\nexport function mapToolNamesForPlatform(\n\tnames: readonly string[],\n\t_platform: NodeJS.Platform = process.platform,\n): string[] {\n\tconst mapped: string[] = [];\n\tfor (const name of names) {\n\t\tconst resolved = name === \"powershell\" ? STABLE_SHELL_TOOL_NAME : name;\n\t\tif (!mapped.includes(resolved)) mapped.push(resolved);\n\t}\n\treturn mapped;\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import { existsSync, mkdirSync, writeFileSync } from "node:fs";
2
2
  import { dirname, relative, resolve } from "node:path";
3
- import { validateToolArguments } from "@caupulican/pi-ai";
3
+ import { validateToolArguments } from "@caupulican/pi-ai/validation";
4
4
  import { Type } from "typebox";
5
5
  import { safeRealpathSync } from "../autonomy/path-scope.js";
6
6
  import { CapabilityGatewayDeniedError } from "../orchestration/capability-gateway.js";
@@ -1 +1 @@
1
- {"version":3,"file":"worker-actions.js","sourceRoot":"","sources":["../../../src/core/delegation/worker-actions.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAC/D,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAEvD,OAAO,EAAE,qBAAqB,EAAE,MAAM,mBAAmB,CAAC;AAC1D,OAAO,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAC/B,OAAO,EAAE,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AAC7D,OAAO,EAA0B,4B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,SAAS,EAAE,CAAC;gBAC1D,MAAM,CAAC,kBAAkB,CAAC,IAAI,CAAC;oBAC9B,IAAI,EAAE,MAAM,CAAC,IAAI;oBACjB,QAAQ,EAAE,aAAa,CAAC,QAAQ;oBAChC,KAAK,EAAE,SAAS;oBAChB,UAAU,EAAE,+BAA+B;oBAC3C,eAAe,EAAE,kBAAkB,MAAM,EAAE;iBAC3C,CAAC,CAAC;YACJ,CAAC;iBAAM,CAAC;gBACP,IAAI,aAAa,EAAE,IAAI,KAAK,SAAS,EAAE,CAAC;oBACvC,IAAI,CAAC;wBACJ,IAAI,CAAC,aAAa,EAAE,YAAY,CAAC,aAAa,EAAE,mCAAmC,EAAE;4BACpF,eAAe,EAAE,kBAAkB,MAAM,EAAE;yBAC3C,CAAC,CAAC;oBACJ,CAAC;oBAAC,MAAM,CAAC;wBACR,MAAM,CAAC,kBAAkB,CAAC,IAAI,CAAC;4BAC9B,IAAI,EAAE,MAAM,CAAC,IAAI;4BACjB,QAAQ,EAAE,aAAa,CAAC,QAAQ;4BAChC,KAAK,EAAE,SAAS;4BAChB,UAAU,EAAE,+BAA+B;4BAC3C,eAAe,EAAE,kBAAkB,MAAM,EAAE;yBAC3C,CAAC,CAAC;oBACJ,CAAC;gBACF,CAAC;gBACD,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,MAAM,CAAC,IAAI,EAAE,MAAM,EAAE,oDAAoD,EAAE,CAAC,CAAC;YACzG,CAAC;QACF,CAAC;IACF,CAAC;IACD,OAAO,MAAM,CAAC;AACf,CAAC","sourcesContent":["import { existsSync, mkdirSync, writeFileSync } from \"node:fs\";\nimport { dirname, relative, resolve } from \"node:path\";\nimport type { Tool, ToolArgumentValidationOptions } from \"@caupulican/pi-ai\";\nimport { validateToolArguments } from \"@caupulican/pi-ai\";\nimport { Type } from \"typebox\";\nimport { safeRealpathSync } from \"../autonomy/path-scope.ts\";\nimport { type CapabilityGateway, CapabilityGatewayDeniedError } from \"../orchestration/capability-gateway.ts\";\nimport type { ToolCapabilityManifest } from \"../orchestration/contracts.ts\";\nimport { readBoundedTextFileSync } from \"../util/bounded-file.ts\";\nimport { isPlainRecord } from \"../util/value-guards.ts\";\nimport type { WorkerActionInspectionRequired, WorkerActionJournal } from \"./worker-action-journal.ts\";\n\n/**\n * Code-writing workers (G2): the worker MODEL never touches the filesystem — it emits strict-JSON\n * actions, and this RUNNER-side module applies them deterministically through the compiled\n * execution grant. That keeps the structural-contract philosophy (a local model without\n * tool-calling templates can still write code) and makes enforcement execution-time, not\n * validation-only: an out-of-scope action is REFUSED with a reason, never silently dropped, and\n * refusals surface as blockers on the result.\n */\n\nexport interface WorkerAction {\n\top: \"write\" | \"edit\";\n\tpath: string;\n\t/** write: full file content. */\n\tcontent?: string;\n\t/** edit: exact string to replace (must occur in the file). */\n\told?: string;\n\t/** edit: replacement text. */\n\tnew?: string;\n}\n\nexport type WorkerActionRejectionCode =\n\t| \"worker_actions_invalid_shape\"\n\t| \"worker_actions_too_many\"\n\t| \"worker_actions_path_too_long\"\n\t| \"worker_actions_field_too_large\"\n\t| \"worker_actions_payload_too_large\";\n\nexport interface AcceptedWorkerActions {\n\tkind: \"accepted\";\n\tactions: WorkerAction[];\n}\n\nexport interface RejectedWorkerActions {\n\tkind: \"rejected\";\n\treasonCode: WorkerActionRejectionCode;\n\tmessage: string;\n}\n\n/** The sole structured-action admission result used before execution or worker-result projection. */\nexport type WorkerActionParseOutcome = AcceptedWorkerActions | RejectedWorkerActions;\n\n/** Bounded model-to-filesystem mutation contract. All execution callers pass through this owner. */\nexport const MAX_WORKER_ACTIONS = 20;\nexport const MAX_WORKER_ACTION_PATH_CHARS = 2_048;\nexport const MAX_WORKER_ACTION_TEXT_CHARS = 512 * 1024;\n/** Limits all source/replacement payloads for one atomic worker action batch. */\nexport const MAX_WORKER_ACTION_PAYLOAD_CHARS = 512 * 1024;\n/**\n * A structured edit only needs bounded source/replacement text. Limit the target read to 2 MiB:\n * this admits the largest UTF-8 text payload (512 Ki code units at four bytes each)\n * without letting a small edit cause an unbounded repository-file allocation.\n */\nexport const MAX_WORKER_ACTION_EDIT_TARGET_BYTES = 2 * 1024 * 1024;\n\nconst workerActionSchema = Type.Union([\n\tType.Object(\n\t\t{\n\t\t\top: Type.Literal(\"write\"),\n\t\t\tpath: Type.String({ minLength: 1, maxLength: MAX_WORKER_ACTION_PATH_CHARS }),\n\t\t\tcontent: Type.String({ maxLength: MAX_WORKER_ACTION_TEXT_CHARS }),\n\t\t},\n\t\t{ additionalProperties: false },\n\t),\n\tType.Object(\n\t\t{\n\t\t\top: Type.Literal(\"edit\"),\n\t\t\tpath: Type.String({ minLength: 1, maxLength: MAX_WORKER_ACTION_PATH_CHARS }),\n\t\t\told: Type.String({ minLength: 1, maxLength: MAX_WORKER_ACTION_TEXT_CHARS }),\n\t\t\tnew: Type.String({ maxLength: MAX_WORKER_ACTION_TEXT_CHARS }),\n\t\t},\n\t\t{ additionalProperties: false },\n\t),\n]);\n\nconst workerActionsTool: Tool = {\n\tname: \"worker_actions\",\n\tdescription: \"Worker filesystem action list\",\n\tparameters: Type.Object(\n\t\t{ actions: Type.Array(workerActionSchema, { maxItems: MAX_WORKER_ACTIONS }) },\n\t\t{ additionalProperties: false },\n\t),\n};\n\nfunction rejectWorkerActions(reasonCode: WorkerActionRejectionCode): RejectedWorkerActions {\n\tconst messages: Record<WorkerActionRejectionCode, string> = {\n\t\tworker_actions_invalid_shape: \"worker actions must be a strict JSON write/edit action list\",\n\t\tworker_actions_too_many: `worker actions exceed the ${MAX_WORKER_ACTIONS}-action limit`,\n\t\tworker_actions_path_too_long: \"worker action path exceeds the allowed limit\",\n\t\tworker_actions_field_too_large: \"worker actions contain a field larger than the allowed limit\",\n\t\tworker_actions_payload_too_large: \"worker actions exceed the aggregate payload limit\",\n\t};\n\treturn { kind: \"rejected\", reasonCode, message: messages[reasonCode] };\n}\n\nfunction validateWorkerActions(\n\traw: unknown,\n\tvalidation?: ToolArgumentValidationOptions,\n): readonly unknown[] | undefined {\n\ttry {\n\t\tconst validated = validateToolArguments(\n\t\t\tworkerActionsTool,\n\t\t\t{ type: \"toolCall\", id: \"worker-actions\", name: \"worker_actions\", arguments: { actions: raw } },\n\t\t\tvalidation,\n\t\t).actions;\n\t\treturn Array.isArray(validated) ? validated : undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/**\n * Normalizes every model or direct caller before it can reach the gateway, journal, or filesystem.\n * Any malformed entry rejects the entire batch so a partially malformed request cannot mutate a\n * surprising prefix.\n */\nfunction normalizeWorkerActions(raw: readonly unknown[]): WorkerActionParseOutcome {\n\tif (raw.length > MAX_WORKER_ACTIONS) return rejectWorkerActions(\"worker_actions_too_many\");\n\tconst actions: WorkerAction[] = [];\n\tlet payloadChars = 0;\n\tfor (const entry of raw) {\n\t\tif (!isPlainRecord(entry)) return rejectWorkerActions(\"worker_actions_invalid_shape\");\n\t\tconst descriptors = Object.getOwnPropertyDescriptors(entry);\n\t\tconst op = descriptors.op?.value;\n\t\tif (op !== \"write\" && op !== \"edit\") return rejectWorkerActions(\"worker_actions_invalid_shape\");\n\t\tconst expectedKeys = op === \"write\" ? [\"op\", \"path\", \"content\"] : [\"op\", \"path\", \"old\", \"new\"];\n\t\tif (\n\t\t\tReflect.ownKeys(entry).length !== expectedKeys.length ||\n\t\t\t!expectedKeys.every((key) => {\n\t\t\t\tconst descriptor = descriptors[key];\n\t\t\t\treturn descriptor?.enumerable === true && \"value\" in descriptor;\n\t\t\t})\n\t\t)\n\t\t\treturn rejectWorkerActions(\"worker_actions_invalid_shape\");\n\t\tconst actionPath = descriptors.path?.value;\n\t\tif (typeof actionPath !== \"string\" || actionPath.length === 0)\n\t\t\treturn rejectWorkerActions(\"worker_actions_invalid_shape\");\n\t\tif (actionPath.length > MAX_WORKER_ACTION_PATH_CHARS) return rejectWorkerActions(\"worker_actions_path_too_long\");\n\t\tif (op === \"write\") {\n\t\t\tconst content = descriptors.content?.value;\n\t\t\tif (typeof content !== \"string\") return rejectWorkerActions(\"worker_actions_invalid_shape\");\n\t\t\tif (content.length > MAX_WORKER_ACTION_TEXT_CHARS)\n\t\t\t\treturn rejectWorkerActions(\"worker_actions_field_too_large\");\n\t\t\tif (payloadChars + content.length > MAX_WORKER_ACTION_PAYLOAD_CHARS)\n\t\t\t\treturn rejectWorkerActions(\"worker_actions_payload_too_large\");\n\t\t\tpayloadChars += content.length;\n\t\t\tactions.push({ op: \"write\", path: actionPath, content });\n\t\t} else {\n\t\t\tconst old = descriptors.old?.value;\n\t\t\tconst replacement = descriptors.new?.value;\n\t\t\tif (typeof old !== \"string\" || old.length === 0 || typeof replacement !== \"string\")\n\t\t\t\treturn rejectWorkerActions(\"worker_actions_invalid_shape\");\n\t\t\tif (old.length > MAX_WORKER_ACTION_TEXT_CHARS || replacement.length > MAX_WORKER_ACTION_TEXT_CHARS)\n\t\t\t\treturn rejectWorkerActions(\"worker_actions_field_too_large\");\n\t\t\tif (payloadChars + old.length + replacement.length > MAX_WORKER_ACTION_PAYLOAD_CHARS)\n\t\t\t\treturn rejectWorkerActions(\"worker_actions_payload_too_large\");\n\t\t\tpayloadChars += old.length + replacement.length;\n\t\t\tactions.push({ op: \"edit\", path: actionPath, old, new: replacement });\n\t\t}\n\t}\n\treturn { kind: \"accepted\", actions };\n}\n\nexport function parseWorkerActions(raw: unknown, validation?: ToolArgumentValidationOptions): WorkerActionParseOutcome {\n\tif (raw === undefined) return { kind: \"accepted\", actions: [] };\n\tconst candidate = Array.isArray(raw) ? normalizeWorkerActions(raw) : undefined;\n\tif (candidate?.kind === \"rejected\") return candidate;\n\tconst validated = validateWorkerActions(candidate?.actions ?? raw, validation);\n\tif (!validated) return rejectWorkerActions(\"worker_actions_invalid_shape\");\n\treturn normalizeWorkerActions(validated);\n}\n\nexport interface AppliedActionsReport {\n\t/** Repo-relative paths actually changed. */\n\tchangedFiles: string[];\n\t/** Grant refusals (execution-time enforcement) — surfaced, never silent. */\n\trefused: Array<{ path: string; reason: string }>;\n\t/** Actions that were in scope but could not be applied (missing file, old-text not found). */\n\tfailed: Array<{ path: string; reason: string }>;\n\t/** Durable replay blocks. The parent must inspect workspace/evidence instead of re-executing. */\n\tinspectionRequired: Array<{\n\t\tpath: string;\n\t\tactionId: string;\n\t\tstate: WorkerActionInspectionRequired[\"state\"];\n\t\treasonCode: string;\n\t\tevidencePointer?: string;\n\t}>;\n}\n\nexport function applyWorkerActions(args: {\n\tactions: readonly WorkerAction[];\n\tgateway: CapabilityGateway;\n\ttoolManifests: readonly ToolCapabilityManifest[];\n\tcwd: string;\n\t/** Optional durable mutation journal for one fenced worker attempt. */\n\tactionJournal?: WorkerActionJournal;\n}): AppliedActionsReport {\n\tconst report: AppliedActionsReport = { changedFiles: [], refused: [], failed: [], inspectionRequired: [] };\n\tconst manifests = new Map(args.toolManifests.map((manifest) => [manifest.toolName, manifest]));\n\tconst parsedActions = parseWorkerActions(args.actions);\n\tif (parsedActions.kind === \"rejected\") {\n\t\treport.failed.push({ path: \"<worker_actions>\", reason: `${parsedActions.reasonCode}: ${parsedActions.message}` });\n\t\treturn report;\n\t}\n\tfor (const [index, action] of parsedActions.actions.entries()) {\n\t\tconst manifest = manifests.get(action.op);\n\t\tif (!manifest) {\n\t\t\treport.refused.push({\n\t\t\t\tpath: action.path,\n\t\t\t\treason: `${action.op} is not present in the compiled tool manifest`,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\ttry {\n\t\t\targs.gateway.authorizeToolCall(manifest, action.op, { path: action.path });\n\t\t} catch (error) {\n\t\t\tif (error instanceof CapabilityGatewayDeniedError) {\n\t\t\t\treport.refused.push({ path: action.path, reason: `${error.reasonCode}: ${error.message}` });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t\tlet target: string;\n\t\tlet relativePath: string;\n\t\ttry {\n\t\t\ttarget = safeRealpathSync(resolve(args.cwd, action.path));\n\t\t\trelativePath = relative(args.cwd, target).replaceAll(\"\\\\\", \"/\");\n\t\t} catch {\n\t\t\treport.failed.push({ path: action.path, reason: \"target path could not be resolved\" });\n\t\t\tcontinue;\n\t\t}\n\t\tlet journalPermit: ReturnType<WorkerActionJournal[\"begin\"]> | undefined;\n\t\tif (args.actionJournal) {\n\t\t\ttry {\n\t\t\t\tjournalPermit = args.actionJournal.begin({ index, action, targetPath: target });\n\t\t\t} catch {\n\t\t\t\treport.failed.push({ path: action.path, reason: \"mutation journal intent could not be persisted\" });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (journalPermit.kind === \"inspection_required\") {\n\t\t\t\treport.inspectionRequired.push({\n\t\t\t\t\tpath: action.path,\n\t\t\t\t\tactionId: journalPermit.actionId,\n\t\t\t\t\tstate: journalPermit.state,\n\t\t\t\t\treasonCode: journalPermit.reasonCode,\n\t\t\t\t\t...(journalPermit.evidencePointer ? { evidencePointer: journalPermit.evidencePointer } : {}),\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\tlet mutationStarted = false;\n\t\ttry {\n\t\t\tif (action.op === \"write\") {\n\t\t\t\t// mkdir may create one or more parents before an error or process interruption. Once it\n\t\t\t\t// is invoked the durable intent is conservatively unknown, never replayed as a precondition failure.\n\t\t\t\tmutationStarted = true;\n\t\t\t\tmkdirSync(dirname(target), { recursive: true });\n\t\t\t\twriteFileSync(target, action.content ?? \"\", \"utf-8\");\n\t\t\t} else {\n\t\t\t\tif (!existsSync(target)) {\n\t\t\t\t\tthrow new Error(\"worker_action_file_missing\");\n\t\t\t\t}\n\t\t\t\tconst current = readBoundedTextFileSync(\n\t\t\t\t\ttarget,\n\t\t\t\t\tMAX_WORKER_ACTION_EDIT_TARGET_BYTES,\n\t\t\t\t\t\"Worker action edit target\",\n\t\t\t\t);\n\t\t\t\tif (!action.old || !current.includes(action.old)) {\n\t\t\t\t\tthrow new Error(\"worker_action_old_text_missing\");\n\t\t\t\t}\n\t\t\t\tmutationStarted = true;\n\t\t\t\twriteFileSync(\n\t\t\t\t\ttarget,\n\t\t\t\t\tcurrent.replace(action.old, () => action.new ?? \"\"),\n\t\t\t\t\t\"utf-8\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (!report.changedFiles.includes(relativePath)) report.changedFiles.push(relativePath);\n\t\t\tjournalPermit?.kind === \"execute\" &&\n\t\t\t\targs.actionJournal?.recordSucceeded(journalPermit, {\n\t\t\t\t\tevidencePointer: `workspace:file:${target}`,\n\t\t\t\t});\n\t\t} catch {\n\t\t\tif (mutationStarted && journalPermit?.kind === \"execute\") {\n\t\t\t\treport.inspectionRequired.push({\n\t\t\t\t\tpath: action.path,\n\t\t\t\t\tactionId: journalPermit.actionId,\n\t\t\t\t\tstate: \"unknown\",\n\t\t\t\t\treasonCode: \"worker_action_outcome_unknown\",\n\t\t\t\t\tevidencePointer: `workspace:file:${target}`,\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tif (journalPermit?.kind === \"execute\") {\n\t\t\t\t\ttry {\n\t\t\t\t\t\targs.actionJournal?.recordFailed(journalPermit, \"worker_action_precondition_failed\", {\n\t\t\t\t\t\t\tevidencePointer: `workspace:file:${target}`,\n\t\t\t\t\t\t});\n\t\t\t\t\t} catch {\n\t\t\t\t\t\treport.inspectionRequired.push({\n\t\t\t\t\t\t\tpath: action.path,\n\t\t\t\t\t\t\tactionId: journalPermit.actionId,\n\t\t\t\t\t\t\tstate: \"unknown\",\n\t\t\t\t\t\t\treasonCode: \"worker_action_outcome_unknown\",\n\t\t\t\t\t\t\tevidencePointer: `workspace:file:${target}`,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treport.failed.push({ path: action.path, reason: \"action precondition or filesystem operation failed\" });\n\t\t\t}\n\t\t}\n\t}\n\treturn report;\n}\n"]}
1
+ {"version":3,"file":"worker-actions.js","sourceRoot":"","sources":["../../../src/core/delegation/worker-actions.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,SAAS,CA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cesContent":["import { existsSync, mkdirSync, writeFileSync } from \"node:fs\";\nimport { dirname, relative, resolve } from \"node:path\";\nimport type { Tool, ToolArgumentValidationOptions } from \"@caupulican/pi-ai\";\nimport { validateToolArguments } from \"@caupulican/pi-ai/validation\";\nimport { Type } from \"typebox\";\nimport { safeRealpathSync } from \"../autonomy/path-scope.ts\";\nimport { type CapabilityGateway, CapabilityGatewayDeniedError } from \"../orchestration/capability-gateway.ts\";\nimport type { ToolCapabilityManifest } from \"../orchestration/contracts.ts\";\nimport { readBoundedTextFileSync } from \"../util/bounded-file.ts\";\nimport { isPlainRecord } from \"../util/value-guards.ts\";\nimport type { WorkerActionInspectionRequired, WorkerActionJournal } from \"./worker-action-journal.ts\";\n\n/**\n * Code-writing workers (G2): the worker MODEL never touches the filesystem — it emits strict-JSON\n * actions, and this RUNNER-side module applies them deterministically through the compiled\n * execution grant. That keeps the structural-contract philosophy (a local model without\n * tool-calling templates can still write code) and makes enforcement execution-time, not\n * validation-only: an out-of-scope action is REFUSED with a reason, never silently dropped, and\n * refusals surface as blockers on the result.\n */\n\nexport interface WorkerAction {\n\top: \"write\" | \"edit\";\n\tpath: string;\n\t/** write: full file content. */\n\tcontent?: string;\n\t/** edit: exact string to replace (must occur in the file). */\n\told?: string;\n\t/** edit: replacement text. */\n\tnew?: string;\n}\n\nexport type WorkerActionRejectionCode =\n\t| \"worker_actions_invalid_shape\"\n\t| \"worker_actions_too_many\"\n\t| \"worker_actions_path_too_long\"\n\t| \"worker_actions_field_too_large\"\n\t| \"worker_actions_payload_too_large\";\n\nexport interface AcceptedWorkerActions {\n\tkind: \"accepted\";\n\tactions: WorkerAction[];\n}\n\nexport interface RejectedWorkerActions {\n\tkind: \"rejected\";\n\treasonCode: WorkerActionRejectionCode;\n\tmessage: string;\n}\n\n/** The sole structured-action admission result used before execution or worker-result projection. */\nexport type WorkerActionParseOutcome = AcceptedWorkerActions | RejectedWorkerActions;\n\n/** Bounded model-to-filesystem mutation contract. All execution callers pass through this owner. */\nexport const MAX_WORKER_ACTIONS = 20;\nexport const MAX_WORKER_ACTION_PATH_CHARS = 2_048;\nexport const MAX_WORKER_ACTION_TEXT_CHARS = 512 * 1024;\n/** Limits all source/replacement payloads for one atomic worker action batch. */\nexport const MAX_WORKER_ACTION_PAYLOAD_CHARS = 512 * 1024;\n/**\n * A structured edit only needs bounded source/replacement text. Limit the target read to 2 MiB:\n * this admits the largest UTF-8 text payload (512 Ki code units at four bytes each)\n * without letting a small edit cause an unbounded repository-file allocation.\n */\nexport const MAX_WORKER_ACTION_EDIT_TARGET_BYTES = 2 * 1024 * 1024;\n\nconst workerActionSchema = Type.Union([\n\tType.Object(\n\t\t{\n\t\t\top: Type.Literal(\"write\"),\n\t\t\tpath: Type.String({ minLength: 1, maxLength: MAX_WORKER_ACTION_PATH_CHARS }),\n\t\t\tcontent: Type.String({ maxLength: MAX_WORKER_ACTION_TEXT_CHARS }),\n\t\t},\n\t\t{ additionalProperties: false },\n\t),\n\tType.Object(\n\t\t{\n\t\t\top: Type.Literal(\"edit\"),\n\t\t\tpath: Type.String({ minLength: 1, maxLength: MAX_WORKER_ACTION_PATH_CHARS }),\n\t\t\told: Type.String({ minLength: 1, maxLength: MAX_WORKER_ACTION_TEXT_CHARS }),\n\t\t\tnew: Type.String({ maxLength: MAX_WORKER_ACTION_TEXT_CHARS }),\n\t\t},\n\t\t{ additionalProperties: false },\n\t),\n]);\n\nconst workerActionsTool: Tool = {\n\tname: \"worker_actions\",\n\tdescription: \"Worker filesystem action list\",\n\tparameters: Type.Object(\n\t\t{ actions: Type.Array(workerActionSchema, { maxItems: MAX_WORKER_ACTIONS }) },\n\t\t{ additionalProperties: false },\n\t),\n};\n\nfunction rejectWorkerActions(reasonCode: WorkerActionRejectionCode): RejectedWorkerActions {\n\tconst messages: Record<WorkerActionRejectionCode, string> = {\n\t\tworker_actions_invalid_shape: \"worker actions must be a strict JSON write/edit action list\",\n\t\tworker_actions_too_many: `worker actions exceed the ${MAX_WORKER_ACTIONS}-action limit`,\n\t\tworker_actions_path_too_long: \"worker action path exceeds the allowed limit\",\n\t\tworker_actions_field_too_large: \"worker actions contain a field larger than the allowed limit\",\n\t\tworker_actions_payload_too_large: \"worker actions exceed the aggregate payload limit\",\n\t};\n\treturn { kind: \"rejected\", reasonCode, message: messages[reasonCode] };\n}\n\nfunction validateWorkerActions(\n\traw: unknown,\n\tvalidation?: ToolArgumentValidationOptions,\n): readonly unknown[] | undefined {\n\ttry {\n\t\tconst validated = validateToolArguments(\n\t\t\tworkerActionsTool,\n\t\t\t{ type: \"toolCall\", id: \"worker-actions\", name: \"worker_actions\", arguments: { actions: raw } },\n\t\t\tvalidation,\n\t\t).actions;\n\t\treturn Array.isArray(validated) ? validated : undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/**\n * Normalizes every model or direct caller before it can reach the gateway, journal, or filesystem.\n * Any malformed entry rejects the entire batch so a partially malformed request cannot mutate a\n * surprising prefix.\n */\nfunction normalizeWorkerActions(raw: readonly unknown[]): WorkerActionParseOutcome {\n\tif (raw.length > MAX_WORKER_ACTIONS) return rejectWorkerActions(\"worker_actions_too_many\");\n\tconst actions: WorkerAction[] = [];\n\tlet payloadChars = 0;\n\tfor (const entry of raw) {\n\t\tif (!isPlainRecord(entry)) return rejectWorkerActions(\"worker_actions_invalid_shape\");\n\t\tconst descriptors = Object.getOwnPropertyDescriptors(entry);\n\t\tconst op = descriptors.op?.value;\n\t\tif (op !== \"write\" && op !== \"edit\") return rejectWorkerActions(\"worker_actions_invalid_shape\");\n\t\tconst expectedKeys = op === \"write\" ? [\"op\", \"path\", \"content\"] : [\"op\", \"path\", \"old\", \"new\"];\n\t\tif (\n\t\t\tReflect.ownKeys(entry).length !== expectedKeys.length ||\n\t\t\t!expectedKeys.every((key) => {\n\t\t\t\tconst descriptor = descriptors[key];\n\t\t\t\treturn descriptor?.enumerable === true && \"value\" in descriptor;\n\t\t\t})\n\t\t)\n\t\t\treturn rejectWorkerActions(\"worker_actions_invalid_shape\");\n\t\tconst actionPath = descriptors.path?.value;\n\t\tif (typeof actionPath !== \"string\" || actionPath.length === 0)\n\t\t\treturn rejectWorkerActions(\"worker_actions_invalid_shape\");\n\t\tif (actionPath.length > MAX_WORKER_ACTION_PATH_CHARS) return rejectWorkerActions(\"worker_actions_path_too_long\");\n\t\tif (op === \"write\") {\n\t\t\tconst content = descriptors.content?.value;\n\t\t\tif (typeof content !== \"string\") return rejectWorkerActions(\"worker_actions_invalid_shape\");\n\t\t\tif (content.length > MAX_WORKER_ACTION_TEXT_CHARS)\n\t\t\t\treturn rejectWorkerActions(\"worker_actions_field_too_large\");\n\t\t\tif (payloadChars + content.length > MAX_WORKER_ACTION_PAYLOAD_CHARS)\n\t\t\t\treturn rejectWorkerActions(\"worker_actions_payload_too_large\");\n\t\t\tpayloadChars += content.length;\n\t\t\tactions.push({ op: \"write\", path: actionPath, content });\n\t\t} else {\n\t\t\tconst old = descriptors.old?.value;\n\t\t\tconst replacement = descriptors.new?.value;\n\t\t\tif (typeof old !== \"string\" || old.length === 0 || typeof replacement !== \"string\")\n\t\t\t\treturn rejectWorkerActions(\"worker_actions_invalid_shape\");\n\t\t\tif (old.length > MAX_WORKER_ACTION_TEXT_CHARS || replacement.length > MAX_WORKER_ACTION_TEXT_CHARS)\n\t\t\t\treturn rejectWorkerActions(\"worker_actions_field_too_large\");\n\t\t\tif (payloadChars + old.length + replacement.length > MAX_WORKER_ACTION_PAYLOAD_CHARS)\n\t\t\t\treturn rejectWorkerActions(\"worker_actions_payload_too_large\");\n\t\t\tpayloadChars += old.length + replacement.length;\n\t\t\tactions.push({ op: \"edit\", path: actionPath, old, new: replacement });\n\t\t}\n\t}\n\treturn { kind: \"accepted\", actions };\n}\n\nexport function parseWorkerActions(raw: unknown, validation?: ToolArgumentValidationOptions): WorkerActionParseOutcome {\n\tif (raw === undefined) return { kind: \"accepted\", actions: [] };\n\tconst candidate = Array.isArray(raw) ? normalizeWorkerActions(raw) : undefined;\n\tif (candidate?.kind === \"rejected\") return candidate;\n\tconst validated = validateWorkerActions(candidate?.actions ?? raw, validation);\n\tif (!validated) return rejectWorkerActions(\"worker_actions_invalid_shape\");\n\treturn normalizeWorkerActions(validated);\n}\n\nexport interface AppliedActionsReport {\n\t/** Repo-relative paths actually changed. */\n\tchangedFiles: string[];\n\t/** Grant refusals (execution-time enforcement) — surfaced, never silent. */\n\trefused: Array<{ path: string; reason: string }>;\n\t/** Actions that were in scope but could not be applied (missing file, old-text not found). */\n\tfailed: Array<{ path: string; reason: string }>;\n\t/** Durable replay blocks. The parent must inspect workspace/evidence instead of re-executing. */\n\tinspectionRequired: Array<{\n\t\tpath: string;\n\t\tactionId: string;\n\t\tstate: WorkerActionInspectionRequired[\"state\"];\n\t\treasonCode: string;\n\t\tevidencePointer?: string;\n\t}>;\n}\n\nexport function applyWorkerActions(args: {\n\tactions: readonly WorkerAction[];\n\tgateway: CapabilityGateway;\n\ttoolManifests: readonly ToolCapabilityManifest[];\n\tcwd: string;\n\t/** Optional durable mutation journal for one fenced worker attempt. */\n\tactionJournal?: WorkerActionJournal;\n}): AppliedActionsReport {\n\tconst report: AppliedActionsReport = { changedFiles: [], refused: [], failed: [], inspectionRequired: [] };\n\tconst manifests = new Map(args.toolManifests.map((manifest) => [manifest.toolName, manifest]));\n\tconst parsedActions = parseWorkerActions(args.actions);\n\tif (parsedActions.kind === \"rejected\") {\n\t\treport.failed.push({ path: \"<worker_actions>\", reason: `${parsedActions.reasonCode}: ${parsedActions.message}` });\n\t\treturn report;\n\t}\n\tfor (const [index, action] of parsedActions.actions.entries()) {\n\t\tconst manifest = manifests.get(action.op);\n\t\tif (!manifest) {\n\t\t\treport.refused.push({\n\t\t\t\tpath: action.path,\n\t\t\t\treason: `${action.op} is not present in the compiled tool manifest`,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\ttry {\n\t\t\targs.gateway.authorizeToolCall(manifest, action.op, { path: action.path });\n\t\t} catch (error) {\n\t\t\tif (error instanceof CapabilityGatewayDeniedError) {\n\t\t\t\treport.refused.push({ path: action.path, reason: `${error.reasonCode}: ${error.message}` });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t\tlet target: string;\n\t\tlet relativePath: string;\n\t\ttry {\n\t\t\ttarget = safeRealpathSync(resolve(args.cwd, action.path));\n\t\t\trelativePath = relative(args.cwd, target).replaceAll(\"\\\\\", \"/\");\n\t\t} catch {\n\t\t\treport.failed.push({ path: action.path, reason: \"target path could not be resolved\" });\n\t\t\tcontinue;\n\t\t}\n\t\tlet journalPermit: ReturnType<WorkerActionJournal[\"begin\"]> | undefined;\n\t\tif (args.actionJournal) {\n\t\t\ttry {\n\t\t\t\tjournalPermit = args.actionJournal.begin({ index, action, targetPath: target });\n\t\t\t} catch {\n\t\t\t\treport.failed.push({ path: action.path, reason: \"mutation journal intent could not be persisted\" });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (journalPermit.kind === \"inspection_required\") {\n\t\t\t\treport.inspectionRequired.push({\n\t\t\t\t\tpath: action.path,\n\t\t\t\t\tactionId: journalPermit.actionId,\n\t\t\t\t\tstate: journalPermit.state,\n\t\t\t\t\treasonCode: journalPermit.reasonCode,\n\t\t\t\t\t...(journalPermit.evidencePointer ? { evidencePointer: journalPermit.evidencePointer } : {}),\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\tlet mutationStarted = false;\n\t\ttry {\n\t\t\tif (action.op === \"write\") {\n\t\t\t\t// mkdir may create one or more parents before an error or process interruption. Once it\n\t\t\t\t// is invoked the durable intent is conservatively unknown, never replayed as a precondition failure.\n\t\t\t\tmutationStarted = true;\n\t\t\t\tmkdirSync(dirname(target), { recursive: true });\n\t\t\t\twriteFileSync(target, action.content ?? \"\", \"utf-8\");\n\t\t\t} else {\n\t\t\t\tif (!existsSync(target)) {\n\t\t\t\t\tthrow new Error(\"worker_action_file_missing\");\n\t\t\t\t}\n\t\t\t\tconst current = readBoundedTextFileSync(\n\t\t\t\t\ttarget,\n\t\t\t\t\tMAX_WORKER_ACTION_EDIT_TARGET_BYTES,\n\t\t\t\t\t\"Worker action edit target\",\n\t\t\t\t);\n\t\t\t\tif (!action.old || !current.includes(action.old)) {\n\t\t\t\t\tthrow new Error(\"worker_action_old_text_missing\");\n\t\t\t\t}\n\t\t\t\tmutationStarted = true;\n\t\t\t\twriteFileSync(\n\t\t\t\t\ttarget,\n\t\t\t\t\tcurrent.replace(action.old, () => action.new ?? \"\"),\n\t\t\t\t\t\"utf-8\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (!report.changedFiles.includes(relativePath)) report.changedFiles.push(relativePath);\n\t\t\tjournalPermit?.kind === \"execute\" &&\n\t\t\t\targs.actionJournal?.recordSucceeded(journalPermit, {\n\t\t\t\t\tevidencePointer: `workspace:file:${target}`,\n\t\t\t\t});\n\t\t} catch {\n\t\t\tif (mutationStarted && journalPermit?.kind === \"execute\") {\n\t\t\t\treport.inspectionRequired.push({\n\t\t\t\t\tpath: action.path,\n\t\t\t\t\tactionId: journalPermit.actionId,\n\t\t\t\t\tstate: \"unknown\",\n\t\t\t\t\treasonCode: \"worker_action_outcome_unknown\",\n\t\t\t\t\tevidencePointer: `workspace:file:${target}`,\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tif (journalPermit?.kind === \"execute\") {\n\t\t\t\t\ttry {\n\t\t\t\t\t\targs.actionJournal?.recordFailed(journalPermit, \"worker_action_precondition_failed\", {\n\t\t\t\t\t\t\tevidencePointer: `workspace:file:${target}`,\n\t\t\t\t\t\t});\n\t\t\t\t\t} catch {\n\t\t\t\t\t\treport.inspectionRequired.push({\n\t\t\t\t\t\t\tpath: action.path,\n\t\t\t\t\t\t\tactionId: journalPermit.actionId,\n\t\t\t\t\t\t\tstate: \"unknown\",\n\t\t\t\t\t\t\treasonCode: \"worker_action_outcome_unknown\",\n\t\t\t\t\t\t\tevidencePointer: `workspace:file:${target}`,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treport.failed.push({ path: action.path, reason: \"action precondition or filesystem operation failed\" });\n\t\t\t}\n\t\t}\n\t}\n\treturn report;\n}\n"]}
@@ -1,9 +1,10 @@
1
1
  import type { AgentMessage } from "@caupulican/pi-agent-core";
2
2
  import type { WorkerDelegationRunOutcome } from "../agent-session-contracts.ts";
3
3
  import type { LaneRecord } from "../autonomy/lane-tracker.ts";
4
+ import type { AgentBindingContract } from "../orchestration/contracts.ts";
4
5
  import type { AttemptRuntimeState } from "../orchestration/task-runtime.ts";
5
- import { type WorkerAgentControlPort } from "./worker-agent-control.ts";
6
- import type { WorkerConversation } from "./worker-conversation-store.ts";
6
+ import { type WorkerAgentControlPort, type WorkerAgentControlScope, type WorkerAgentMessageOptions, type WorkerAgentTranscriptOptions } from "./worker-agent-control.ts";
7
+ import { type WorkerConversation } from "./worker-conversation-store.ts";
7
8
  import type { WorkerDelegationRequest } from "./worker-delegation-request.ts";
8
9
  import type { WorkerDispatchScheduler } from "./worker-dispatch-scheduler.ts";
9
10
  import type { WorkerLifecycle } from "./worker-lifecycle.ts";
@@ -19,6 +20,7 @@ export interface WorkerAgentControlCoordinatorOptions {
19
20
  statusChanged(): void;
20
21
  abortLane(laneId: string, reasonCode: string): void;
21
22
  cancelLane(laneId: string, reasonCode: string): LaneRecord | undefined;
23
+ yieldCapacity?(callerAgentId: string, targetAgentId: string): () => void;
22
24
  }
23
25
  /**
24
26
  * Sole owner of model-facing logical-agent controls and their durable inboxes.
@@ -30,31 +32,34 @@ export declare class WorkerAgentControlCoordinator implements WorkerAgentControl
30
32
  private readonly options;
31
33
  private readonly mailboxes;
32
34
  private readonly stateListeners;
35
+ private readonly conversations;
33
36
  constructor(options: WorkerAgentControlCoordinatorOptions);
34
37
  getProcessOwnerId(): string;
35
- sendWorkerAgentMessage(agentId: string, message: string): {
38
+ listWorkerAgents(scope?: WorkerAgentControlScope): AgentBindingContract[];
39
+ readWorkerAgentTranscript(agentId: string, options?: WorkerAgentTranscriptOptions): ReturnType<WorkerAgentControlPort["readWorkerAgentTranscript"]>;
40
+ sendWorkerAgentMessage(agentId: string, message: string, options?: WorkerAgentMessageOptions): {
36
41
  messageId: string;
37
42
  queued: true;
38
43
  };
39
- followUpWorkerAgent(agentId: string, message: string): {
44
+ followUpWorkerAgent(agentId: string, message: string, options?: WorkerAgentMessageOptions): {
40
45
  started: boolean;
41
46
  steering: boolean;
42
47
  messageId: string;
43
48
  record?: LaneRecord;
44
49
  skipReason?: string;
45
50
  };
46
- interruptWorkerAgent(agentId: string): {
51
+ interruptWorkerAgent(agentId: string, scope?: WorkerAgentControlScope): {
47
52
  interrupted: boolean;
48
53
  reason?: string;
49
54
  };
50
- resumeWorkerAgent(agentId: string): {
55
+ resumeWorkerAgent(agentId: string, scope?: WorkerAgentControlScope): {
51
56
  started: boolean;
52
57
  record?: LaneRecord;
53
58
  skipReason?: string;
54
59
  };
55
- cancelWorkerAgent(agentId: string, reasonCode?: string): LaneRecord | undefined;
60
+ cancelWorkerAgent(agentId: string, reasonCode?: string, scope?: WorkerAgentControlScope): LaneRecord | undefined;
56
61
  /** Event-driven wait: durable projection plus state/mailbox notifications, never output polling. */
57
- waitForWorkerAgent(agentId: string, timeoutMs?: number): Promise<{
62
+ waitForWorkerAgent(agentId: string, timeoutMs?: number, scope?: WorkerAgentControlScope): Promise<{
58
63
  status: "active" | "suspended" | "idle" | "unknown";
59
64
  }>;
60
65
  /** Read mailbox items at a safe boundary and reconcile the narrow append-before-ack crash window. */
@@ -66,11 +71,25 @@ export declare class WorkerAgentControlCoordinator implements WorkerAgentControl
66
71
  }): void;
67
72
  /** Called by controller-owned execution transitions after lifecycle state changed. */
68
73
  signalStateChanged(): void;
74
+ /** Route a terminal child edge to its owning parent without injecting into an active model turn. */
75
+ deliverWorkerTerminalHandoff(args: {
76
+ parentAgentId: string;
77
+ childAgentId: string;
78
+ terminalAttemptId: string;
79
+ record: LaneRecord;
80
+ }): {
81
+ messageId: string;
82
+ started: boolean;
83
+ };
69
84
  private requireControl;
70
85
  private requireKnownAgent;
86
+ private requireVisibleAgent;
87
+ private requireControllableAgent;
88
+ private latestAgentAttempt;
71
89
  private controlledAgentAttempt;
72
90
  private getMailbox;
73
91
  private subscribeStateChanges;
92
+ private enqueuePeerMessage;
74
93
  private mailboxMessage;
75
94
  }
76
95
  //# sourceMappingURL=worker-agent-control-coordinator.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"worker-agent-control-coordinator.d.ts","sourceRoot":"","sources":["../../../src/core/delegation/worker-agent-control-coordinator.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAC;AAC9D,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,+BAA+B,CAAC;AAChF,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,6BAA6B,CAAC;AAE9D,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,kCAAkC,CAAC;AAC5E,OAAO,EAAE,KAAK,sBAAsB,EAA+C,MAAM,2BAA2B,CAAC;AACrH,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,gCAAgC,CAAC;AACzE,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,gCAAgC,CAAC;AAC9E,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,gCAAgC,CAAC;AAC9E,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAE7D,MAAM,WAAW,oCAAoC;IACpD,QAAQ,EAAE,MAAM,CAAC;IACjB,eAAe,EAAE,MAAM,CAAC;IACxB,cAAc,EAAE,MAAM,CAAC;IACvB,kBAAkB,IAAI,OAAO,CAAC;IAC9B,YAAY,IAAI,eAAe,CAAC;IAChC,gBAAgB,CAAC,OAAO,EAAE,mBAAmB,GAAG,uBAAuB,CAAC;IACxE,GAAG,CAAC,OAAO,EAAE,uBAAuB,EAAE,MAAM,EAAE,UAAU,GAAG,OAAO,CAAC,0BAA0B,CAAC,CAA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AC,OAAO,EAAE,MAAM,EAAE,UAAU,SAAoB,GAAG,UAAU,GAAG,SAAS,CAOzF;IAED,oGAAoG;IACpG,kBAAkB,CACjB,OAAO,EAAE,MAAM,EACf,SAAS,SAAS,GAChB,OAAO,CAAC;QAAE,MAAM,EAAE,QAAQ,GAAG,WAAW,GAAG,MAAM,GAAG,SAAS,CAAA;KAAE,CAAC,CAsClE;IAED,qGAAqG;IACrG,8BAA8B,CAC7B,OAAO,EAAE,MAAM,EACf,YAAY,EAAE,kBAAkB,EAChC,eAAe,EAAE,OAAO,GACtB,YAAY,EAAE,CAUhB;IAED,2FAA2F;IAC3F,yBAAyB,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,OAAO,CAAA;KAAE,GAAG,IAAI,CAI5F;IAED,sFAAsF;IACtF,kBAAkB,IAAI,IAAI,CAEzB;IAED,OAAO,CAAC,cAAc;IAMtB,OAAO,CAAC,iBAAiB;IAQzB,OAAO,CAAC,sBAAsB;IAY9B,OAAO,CAAC,UAAU;IAalB,OAAO,CAAC,qBAAqB;IAK7B,OAAO,CAAC,cAAc;CAOtB"}
1
+ {"version":3,"file":"worker-agent-control-coordinator.d.ts","sourceRoot":"","sources":["../../../src/core/delegation/worker-agent-control-coordinator.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAC;AAC9D,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,+BAA+B,CAAC;AAChF,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,6BAA6B,CAAC;AAC9D,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,+BAA+B,CAAC;AAC1E,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,kCAAkC,CAAC;AAC5E,OAAO,EACN,KAAK,sBAAsB,EAC3B,KAAK,uBAAuB,EAG5B,KAAK,yBAAyB,EAC9B,KAAK,4BAA4B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