@caupulican/pi-adaptative 0.81.42 → 0.81.43

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 (1406) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/dist/bun/cli.d.ts.map +1 -1
  3. package/dist/bun/cli.js.map +1 -1
  4. package/dist/bun/register-bedrock.d.ts.map +1 -1
  5. package/dist/bun/restore-sandbox-env.d.ts.map +1 -1
  6. package/dist/bun/restore-sandbox-env.js.map +1 -1
  7. package/dist/bundled-resources/extensions/tmux-agent-manager/dispatch-grant.d.ts.map +1 -1
  8. package/dist/bundled-resources/extensions/tmux-agent-manager/dispatch-grant.js.map +1 -1
  9. package/dist/bundled-resources/extensions/tmux-agent-manager/index.d.ts.map +1 -1
  10. package/dist/bundled-resources/extensions/tmux-agent-manager/index.js +52 -49
  11. package/dist/bundled-resources/extensions/tmux-agent-manager/index.js.map +1 -1
  12. package/dist/bundled-resources/extensions/tmux-agent-manager/index.ts +62 -57
  13. package/dist/bundled-resources/prompts/skillify.md +1 -1
  14. package/dist/bundled-resources/runtimes/pi-shell-engine/commands/fs.py +16 -19
  15. package/dist/bundled-resources/runtimes/pi-shell-engine/commands/search.py +12 -26
  16. package/dist/bundled-resources/runtimes/pi-shell-engine/commands/strings.py +15 -121
  17. package/dist/bundled-resources/runtimes/pi-shell-engine/commands/text.py +52 -79
  18. package/dist/bundled-resources/runtimes/pi-shell-engine/escapes.py +70 -0
  19. package/dist/bundled-resources/runtimes/pi-shell-engine/exec.py +110 -61
  20. package/dist/bundled-resources/runtimes/pi-shell-engine/main.py +106 -23
  21. package/dist/bundled-resources/runtimes/pi-shell-engine/paths.py +10 -0
  22. package/dist/bundled-resources/runtimes/pi-shell-engine/proc.py +12 -4
  23. package/dist/bundled-resources/runtimes/pi-shell-engine/shell_args.py +22 -0
  24. package/dist/bundled-resources/runtimes/pi-shell-engine/state.py +9 -2
  25. package/dist/bundled-resources/runtimes/pi-shell-engine/tokens.py +129 -259
  26. package/dist/bundled-resources/skills/authorized-web-security-audit/SKILL.md +187 -0
  27. package/dist/bundled-resources/skills/authorized-web-security-audit/references/assessment-contract.md +92 -0
  28. package/dist/bundled-resources/skills/deduplicate-by-evidence/SKILL.md +134 -0
  29. package/dist/bundled-resources/skills/evidence-gated-tdd/SKILL.md +93 -0
  30. package/dist/bundled-resources/skills/evidence-gated-tdd/references/evidence-model.md +27 -0
  31. package/dist/bundled-resources/skills/evidence-gated-tdd/references/security-scanners.md +24 -0
  32. package/dist/bundled-resources/skills/harness-self-adaptation/SKILL.md +4 -2
  33. package/dist/bundled-resources/skills/secure-agent-tool-surfaces/SKILL.md +217 -0
  34. package/dist/bundled-resources/skills/secure-agent-tool-surfaces/references/defensive-exploit-catalogue.md +175 -0
  35. package/dist/bundled-resources/skills/secure-agent-tool-surfaces/references/tool-boundary-checklist.md +87 -0
  36. package/dist/bundled-resources/skills/skill-architect/SKILL.md +2 -2
  37. package/dist/bundled-resources/skills/skill-creator/SKILL.md +188 -0
  38. package/dist/bundled-resources/skills/skill-creator/references/pi-skill-contract.md +73 -0
  39. package/dist/bundled-resources/skills/skill-creator/scripts/init-skill.mjs +142 -0
  40. package/dist/bundled-resources/skills/skill-creator/scripts/validate-skill.mjs +122 -0
  41. package/dist/cli/args.d.ts.map +1 -1
  42. package/dist/cli/args.js.map +1 -1
  43. package/dist/cli/config-selector.d.ts.map +1 -1
  44. package/dist/cli/config-selector.js.map +1 -1
  45. package/dist/cli/file-processor.d.ts.map +1 -1
  46. package/dist/cli/file-processor.js +8 -8
  47. package/dist/cli/file-processor.js.map +1 -1
  48. package/dist/cli/initial-message.d.ts +1 -1
  49. package/dist/cli/initial-message.d.ts.map +1 -1
  50. package/dist/cli/initial-message.js.map +1 -1
  51. package/dist/cli/list-models.d.ts.map +1 -1
  52. package/dist/cli/list-models.js.map +1 -1
  53. package/dist/cli/piped-stdin.d.ts +4 -0
  54. package/dist/cli/piped-stdin.d.ts.map +1 -0
  55. package/dist/cli/piped-stdin.js +13 -0
  56. package/dist/cli/piped-stdin.js.map +1 -0
  57. package/dist/cli/session-picker.d.ts.map +1 -1
  58. package/dist/cli/session-picker.js.map +1 -1
  59. package/dist/cli.d.ts.map +1 -1
  60. package/dist/cli.js.map +1 -1
  61. package/dist/config.d.ts.map +1 -1
  62. package/dist/config.js +9 -14
  63. package/dist/config.js.map +1 -1
  64. package/dist/core/agent-directory-layout.d.ts.map +1 -1
  65. package/dist/core/agent-directory-layout.js.map +1 -1
  66. package/dist/core/agent-paths.d.ts.map +1 -1
  67. package/dist/core/agent-paths.js.map +1 -1
  68. package/dist/core/agent-session-contracts.d.ts +5 -9
  69. package/dist/core/agent-session-contracts.d.ts.map +1 -1
  70. package/dist/core/agent-session-contracts.js +1 -12
  71. package/dist/core/agent-session-contracts.js.map +1 -1
  72. package/dist/core/agent-session-runtime.d.ts.map +1 -1
  73. package/dist/core/agent-session-runtime.js +10 -25
  74. package/dist/core/agent-session-runtime.js.map +1 -1
  75. package/dist/core/agent-session-services.d.ts.map +1 -1
  76. package/dist/core/agent-session-services.js.map +1 -1
  77. package/dist/core/agent-session.d.ts +24 -1
  78. package/dist/core/agent-session.d.ts.map +1 -1
  79. package/dist/core/agent-session.js +210 -237
  80. package/dist/core/agent-session.js.map +1 -1
  81. package/dist/core/auth-guidance.d.ts.map +1 -1
  82. package/dist/core/auth-guidance.js.map +1 -1
  83. package/dist/core/auth-storage.d.ts +4 -1
  84. package/dist/core/auth-storage.d.ts.map +1 -1
  85. package/dist/core/auth-storage.js +13 -39
  86. package/dist/core/auth-storage.js.map +1 -1
  87. package/dist/core/autonomy/approval-gate.d.ts.map +1 -1
  88. package/dist/core/autonomy/approval-gate.js.map +1 -1
  89. package/dist/core/autonomy/bounded-completion.d.ts.map +1 -1
  90. package/dist/core/autonomy/bounded-completion.js.map +1 -1
  91. package/dist/core/autonomy/contracts.d.ts.map +1 -1
  92. package/dist/core/autonomy/envelope-enforcement.d.ts.map +1 -1
  93. package/dist/core/autonomy/envelope-enforcement.js.map +1 -1
  94. package/dist/core/autonomy/evidence-finding-projection.d.ts +11 -0
  95. package/dist/core/autonomy/evidence-finding-projection.d.ts.map +1 -0
  96. package/dist/core/autonomy/evidence-finding-projection.js +37 -0
  97. package/dist/core/autonomy/evidence-finding-projection.js.map +1 -0
  98. package/dist/core/autonomy/foreground-envelope.d.ts.map +1 -1
  99. package/dist/core/autonomy/foreground-envelope.js.map +1 -1
  100. package/dist/core/autonomy/gates.d.ts.map +1 -1
  101. package/dist/core/autonomy/gates.js.map +1 -1
  102. package/dist/core/autonomy/lane-private-paths.d.ts.map +1 -1
  103. package/dist/core/autonomy/lane-private-paths.js.map +1 -1
  104. package/dist/core/autonomy/lane-tool-surface.d.ts.map +1 -1
  105. package/dist/core/autonomy/lane-tool-surface.js.map +1 -1
  106. package/dist/core/autonomy/lane-tracker.d.ts.map +1 -1
  107. package/dist/core/autonomy/lane-tracker.js +2 -3
  108. package/dist/core/autonomy/lane-tracker.js.map +1 -1
  109. package/dist/core/autonomy/path-scope.d.ts.map +1 -1
  110. package/dist/core/autonomy/path-scope.js.map +1 -1
  111. package/dist/core/autonomy/risk-assessment.d.ts.map +1 -1
  112. package/dist/core/autonomy/session-lane-record.d.ts.map +1 -1
  113. package/dist/core/autonomy/session-lane-record.js.map +1 -1
  114. package/dist/core/autonomy/status.d.ts.map +1 -1
  115. package/dist/core/autonomy/status.js.map +1 -1
  116. package/dist/core/autonomy/subagent-prompt.d.ts.map +1 -1
  117. package/dist/core/autonomy/subagent-prompt.js.map +1 -1
  118. package/dist/core/autonomy/telemetry-events.d.ts.map +1 -1
  119. package/dist/core/autonomy/telemetry-events.js.map +1 -1
  120. package/dist/core/autonomy-telemetry.d.ts.map +1 -1
  121. package/dist/core/autonomy-telemetry.js +2 -4
  122. package/dist/core/autonomy-telemetry.js.map +1 -1
  123. package/dist/core/background-lane-controller.d.ts.map +1 -1
  124. package/dist/core/background-lane-controller.js +2 -15
  125. package/dist/core/background-lane-controller.js.map +1 -1
  126. package/dist/core/background-tool-task-controller.d.ts +88 -0
  127. package/dist/core/background-tool-task-controller.d.ts.map +1 -0
  128. package/dist/core/background-tool-task-controller.js +470 -0
  129. package/dist/core/background-tool-task-controller.js.map +1 -0
  130. package/dist/core/bash-execution-controller.d.ts +1 -0
  131. package/dist/core/bash-execution-controller.d.ts.map +1 -1
  132. package/dist/core/bash-execution-controller.js +5 -4
  133. package/dist/core/bash-execution-controller.js.map +1 -1
  134. package/dist/core/bash-executor.d.ts.map +1 -1
  135. package/dist/core/bash-executor.js.map +1 -1
  136. package/dist/core/bedrock-sso-login.d.ts.map +1 -1
  137. package/dist/core/bedrock-sso-login.js.map +1 -1
  138. package/dist/core/billing-failover-controller.d.ts.map +1 -1
  139. package/dist/core/billing-failover-controller.js +3 -3
  140. package/dist/core/billing-failover-controller.js.map +1 -1
  141. package/dist/core/billing-failover.d.ts.map +1 -1
  142. package/dist/core/billing-failover.js.map +1 -1
  143. package/dist/core/capability-contract.d.ts.map +1 -1
  144. package/dist/core/catalog-manager.d.ts.map +1 -1
  145. package/dist/core/catalog-manager.js +0 -0
  146. package/dist/core/catalog-manager.js.map +1 -1
  147. package/dist/core/compaction-controller.d.ts +2 -0
  148. package/dist/core/compaction-controller.d.ts.map +1 -1
  149. package/dist/core/compaction-controller.js +21 -8
  150. package/dist/core/compaction-controller.js.map +1 -1
  151. package/dist/core/compaction-support.d.ts +8 -0
  152. package/dist/core/compaction-support.d.ts.map +1 -1
  153. package/dist/core/compaction-support.js +0 -2
  154. package/dist/core/compaction-support.js.map +1 -1
  155. package/dist/core/context/artifact-retrieval.d.ts.map +1 -1
  156. package/dist/core/context/artifact-retrieval.js.map +1 -1
  157. package/dist/core/context/brain-curator.d.ts.map +1 -1
  158. package/dist/core/context/brain-curator.js +14 -33
  159. package/dist/core/context/brain-curator.js.map +1 -1
  160. package/dist/core/context/context-artifacts.d.ts.map +1 -1
  161. package/dist/core/context/context-artifacts.js +16 -24
  162. package/dist/core/context/context-artifacts.js.map +1 -1
  163. package/dist/core/context/context-audit.d.ts.map +1 -1
  164. package/dist/core/context/context-audit.js +3 -17
  165. package/dist/core/context/context-audit.js.map +1 -1
  166. package/dist/core/context/context-composition.d.ts.map +1 -1
  167. package/dist/core/context/context-composition.js.map +1 -1
  168. package/dist/core/context/context-item.d.ts.map +1 -1
  169. package/dist/core/context/context-item.js.map +1 -1
  170. package/dist/core/context/context-prompt-enforcement.d.ts.map +1 -1
  171. package/dist/core/context/context-prompt-enforcement.js +3 -16
  172. package/dist/core/context/context-prompt-enforcement.js.map +1 -1
  173. package/dist/core/context/context-prompt-policy.d.ts.map +1 -1
  174. package/dist/core/context/context-prompt-policy.js.map +1 -1
  175. package/dist/core/context/context-retention.d.ts.map +1 -1
  176. package/dist/core/context/context-retention.js.map +1 -1
  177. package/dist/core/context/context-store-retention.d.ts.map +1 -1
  178. package/dist/core/context/context-store-retention.js.map +1 -1
  179. package/dist/core/context/context-store.d.ts.map +1 -1
  180. package/dist/core/context/context-store.js.map +1 -1
  181. package/dist/core/context/context-tool-result.d.ts +4 -0
  182. package/dist/core/context/context-tool-result.d.ts.map +1 -0
  183. package/dist/core/context/context-tool-result.js +15 -0
  184. package/dist/core/context/context-tool-result.js.map +1 -0
  185. package/dist/core/context/current-work-memory.d.ts.map +1 -1
  186. package/dist/core/context/current-work-memory.js.map +1 -1
  187. package/dist/core/context/file-store-memory-provider.d.ts.map +1 -1
  188. package/dist/core/context/file-store-memory-provider.js +7 -28
  189. package/dist/core/context/file-store-memory-provider.js.map +1 -1
  190. package/dist/core/context/local-memory-search.d.ts +11 -0
  191. package/dist/core/context/local-memory-search.d.ts.map +1 -0
  192. package/dist/core/context/local-memory-search.js +37 -0
  193. package/dist/core/context/local-memory-search.js.map +1 -0
  194. package/dist/core/context/long-term-memory-trigger.d.ts.map +1 -1
  195. package/dist/core/context/long-term-memory-trigger.js.map +1 -1
  196. package/dist/core/context/memory-diagnostics.d.ts.map +1 -1
  197. package/dist/core/context/memory-diagnostics.js.map +1 -1
  198. package/dist/core/context/memory-index-store.d.ts.map +1 -1
  199. package/dist/core/context/memory-index-store.js.map +1 -1
  200. package/dist/core/context/memory-prompt-block.d.ts.map +1 -1
  201. package/dist/core/context/memory-prompt-block.js.map +1 -1
  202. package/dist/core/context/memory-prompt-budget.d.ts.map +1 -1
  203. package/dist/core/context/memory-prompt-budget.js.map +1 -1
  204. package/dist/core/context/memory-provider-contract.d.ts.map +1 -1
  205. package/dist/core/context/memory-provider-contract.js.map +1 -1
  206. package/dist/core/context/memory-retrieval.d.ts.map +1 -1
  207. package/dist/core/context/memory-retrieval.js.map +1 -1
  208. package/dist/core/context/memory-tier-composer.d.ts.map +1 -1
  209. package/dist/core/context/memory-tier-composer.js.map +1 -1
  210. package/dist/core/context/message-text.d.ts +7 -0
  211. package/dist/core/context/message-text.d.ts.map +1 -0
  212. package/dist/core/context/message-text.js +68 -0
  213. package/dist/core/context/message-text.js.map +1 -0
  214. package/dist/core/context/okf-memory-provider.d.ts.map +1 -1
  215. package/dist/core/context/okf-memory-provider.js +4 -30
  216. package/dist/core/context/okf-memory-provider.js.map +1 -1
  217. package/dist/core/context/okf-memory.d.ts.map +1 -1
  218. package/dist/core/context/okf-memory.js.map +1 -1
  219. package/dist/core/context/policy-engine.d.ts.map +1 -1
  220. package/dist/core/context/policy-engine.js.map +1 -1
  221. package/dist/core/context/policy-types.d.ts.map +1 -1
  222. package/dist/core/context/sqlite-runtime-index.d.ts.map +1 -1
  223. package/dist/core/context/sqlite-runtime-index.js.map +1 -1
  224. package/dist/core/context/storage-authority.d.ts.map +1 -1
  225. package/dist/core/context/tool-output-packer.d.ts.map +1 -1
  226. package/dist/core/context/tool-output-packer.js.map +1 -1
  227. package/dist/core/context-gc.d.ts.map +1 -1
  228. package/dist/core/context-gc.js +14 -21
  229. package/dist/core/context-gc.js.map +1 -1
  230. package/dist/core/context-pipeline.d.ts +1 -3
  231. package/dist/core/context-pipeline.d.ts.map +1 -1
  232. package/dist/core/context-pipeline.js +64 -145
  233. package/dist/core/context-pipeline.js.map +1 -1
  234. package/dist/core/cost/cost-summary.d.ts.map +1 -1
  235. package/dist/core/cost/cost-summary.js.map +1 -1
  236. package/dist/core/cost/daily-usage.d.ts.map +1 -1
  237. package/dist/core/cost/daily-usage.js.map +1 -1
  238. package/dist/core/cost/session-usage.d.ts.map +1 -1
  239. package/dist/core/cost/session-usage.js.map +1 -1
  240. package/dist/core/cost-guard.d.ts.map +1 -1
  241. package/dist/core/cost-guard.js.map +1 -1
  242. package/dist/core/default-tool-surface.d.ts.map +1 -1
  243. package/dist/core/default-tool-surface.js +1 -0
  244. package/dist/core/default-tool-surface.js.map +1 -1
  245. package/dist/core/defaults.d.ts.map +1 -1
  246. package/dist/core/delegation/managed-lane-controller.d.ts.map +1 -1
  247. package/dist/core/delegation/managed-lane-controller.js +2 -6
  248. package/dist/core/delegation/managed-lane-controller.js.map +1 -1
  249. package/dist/core/delegation/session-worker-claim.d.ts.map +1 -1
  250. package/dist/core/delegation/session-worker-claim.js.map +1 -1
  251. package/dist/core/delegation/worker-action-journal.d.ts.map +1 -1
  252. package/dist/core/delegation/worker-action-journal.js +0 -4
  253. package/dist/core/delegation/worker-action-journal.js.map +1 -1
  254. package/dist/core/delegation/worker-actions.d.ts.map +1 -1
  255. package/dist/core/delegation/worker-actions.js.map +1 -1
  256. package/dist/core/delegation/worker-agent-control-coordinator.d.ts +1 -0
  257. package/dist/core/delegation/worker-agent-control-coordinator.d.ts.map +1 -1
  258. package/dist/core/delegation/worker-agent-control-coordinator.js +13 -15
  259. package/dist/core/delegation/worker-agent-control-coordinator.js.map +1 -1
  260. package/dist/core/delegation/worker-agent-control.d.ts.map +1 -1
  261. package/dist/core/delegation/worker-agent-control.js +1 -4
  262. package/dist/core/delegation/worker-agent-control.js.map +1 -1
  263. package/dist/core/delegation/worker-attempt-executor.d.ts.map +1 -1
  264. package/dist/core/delegation/worker-attempt-executor.js.map +1 -1
  265. package/dist/core/delegation/worker-claim.d.ts.map +1 -1
  266. package/dist/core/delegation/worker-claim.js.map +1 -1
  267. package/dist/core/delegation/worker-conversation-store.d.ts.map +1 -1
  268. package/dist/core/delegation/worker-conversation-store.js +0 -2
  269. package/dist/core/delegation/worker-conversation-store.js.map +1 -1
  270. package/dist/core/delegation/worker-delegation-controller.d.ts.map +1 -1
  271. package/dist/core/delegation/worker-delegation-controller.js +5 -14
  272. package/dist/core/delegation/worker-delegation-controller.js.map +1 -1
  273. package/dist/core/delegation/worker-delegation-request.d.ts.map +1 -1
  274. package/dist/core/delegation/worker-dispatch-scheduler.d.ts.map +1 -1
  275. package/dist/core/delegation/worker-dispatch-scheduler.js +5 -6
  276. package/dist/core/delegation/worker-dispatch-scheduler.js.map +1 -1
  277. package/dist/core/delegation/worker-execution-policy.d.ts.map +1 -1
  278. package/dist/core/delegation/worker-execution-policy.js.map +1 -1
  279. package/dist/core/delegation/worker-lane-projection.d.ts.map +1 -1
  280. package/dist/core/delegation/worker-lane-projection.js.map +1 -1
  281. package/dist/core/delegation/worker-lifecycle.d.ts.map +1 -1
  282. package/dist/core/delegation/worker-lifecycle.js +0 -3
  283. package/dist/core/delegation/worker-lifecycle.js.map +1 -1
  284. package/dist/core/delegation/worker-notification-coordinator.d.ts.map +1 -1
  285. package/dist/core/delegation/worker-notification-coordinator.js +4 -5
  286. package/dist/core/delegation/worker-notification-coordinator.js.map +1 -1
  287. package/dist/core/delegation/worker-process-owner.d.ts.map +1 -1
  288. package/dist/core/delegation/worker-process-owner.js.map +1 -1
  289. package/dist/core/delegation/worker-profile-resolver.d.ts.map +1 -1
  290. package/dist/core/delegation/worker-profile-resolver.js +1 -2
  291. package/dist/core/delegation/worker-profile-resolver.js.map +1 -1
  292. package/dist/core/delegation/worker-recovery-coordinator.d.ts.map +1 -1
  293. package/dist/core/delegation/worker-recovery-coordinator.js +3 -4
  294. package/dist/core/delegation/worker-recovery-coordinator.js.map +1 -1
  295. package/dist/core/delegation/worker-resource-catalog.d.ts.map +1 -1
  296. package/dist/core/delegation/worker-resource-catalog.js.map +1 -1
  297. package/dist/core/delegation/worker-resource-materializer.d.ts.map +1 -1
  298. package/dist/core/delegation/worker-resource-materializer.js +1 -4
  299. package/dist/core/delegation/worker-resource-materializer.js.map +1 -1
  300. package/dist/core/delegation/worker-runner.d.ts +2 -4
  301. package/dist/core/delegation/worker-runner.d.ts.map +1 -1
  302. package/dist/core/delegation/worker-runner.js +6 -18
  303. package/dist/core/delegation/worker-runner.js.map +1 -1
  304. package/dist/core/delegation/worker-task-label.d.ts.map +1 -1
  305. package/dist/core/delegation/worker-task-label.js.map +1 -1
  306. package/dist/core/delegation/worker-terminal-finalizer.d.ts.map +1 -1
  307. package/dist/core/delegation/worker-terminal-finalizer.js.map +1 -1
  308. package/dist/core/delegation/worker-write-reservation-coordinator.d.ts.map +1 -1
  309. package/dist/core/delegation/worker-write-reservation-coordinator.js +1 -4
  310. package/dist/core/delegation/worker-write-reservation-coordinator.js.map +1 -1
  311. package/dist/core/delegation/worker-write-reservation.d.ts.map +1 -1
  312. package/dist/core/delegation/worker-write-reservation.js +0 -2
  313. package/dist/core/delegation/worker-write-reservation.js.map +1 -1
  314. package/dist/core/diagnostics.d.ts.map +1 -1
  315. package/dist/core/doctor.d.ts.map +1 -1
  316. package/dist/core/doctor.js.map +1 -1
  317. package/dist/core/event-bus.d.ts.map +1 -1
  318. package/dist/core/event-bus.js.map +1 -1
  319. package/dist/core/exec.d.ts.map +1 -1
  320. package/dist/core/exec.js +26 -7
  321. package/dist/core/exec.js.map +1 -1
  322. package/dist/core/export-html/ansi-to-html.d.ts.map +1 -1
  323. package/dist/core/export-html/ansi-to-html.js +21 -74
  324. package/dist/core/export-html/ansi-to-html.js.map +1 -1
  325. package/dist/core/export-html/index.d.ts.map +1 -1
  326. package/dist/core/export-html/index.js +4 -0
  327. package/dist/core/export-html/index.js.map +1 -1
  328. package/dist/core/export-html/session-tree-foundations.d.mts +67 -0
  329. package/dist/core/export-html/session-tree-foundations.mjs +313 -0
  330. package/dist/core/export-html/template.css +14 -41
  331. package/dist/core/export-html/template.html +3 -1
  332. package/dist/core/export-html/template.js +26 -435
  333. package/dist/core/export-html/tool-renderer.d.ts.map +1 -1
  334. package/dist/core/export-html/tool-renderer.js.map +1 -1
  335. package/dist/core/extension-import-authority.d.ts.map +1 -1
  336. package/dist/core/extension-import-authority.js.map +1 -1
  337. package/dist/core/extension-metadata.d.ts.map +1 -1
  338. package/dist/core/extension-metadata.js.map +1 -1
  339. package/dist/core/extensions/builtin.d.ts +17 -0
  340. package/dist/core/extensions/builtin.d.ts.map +1 -1
  341. package/dist/core/extensions/builtin.js +18 -54
  342. package/dist/core/extensions/builtin.js.map +1 -1
  343. package/dist/core/extensions/entry-resolution.d.ts +3 -0
  344. package/dist/core/extensions/entry-resolution.d.ts.map +1 -0
  345. package/dist/core/extensions/entry-resolution.js +17 -0
  346. package/dist/core/extensions/entry-resolution.js.map +1 -0
  347. package/dist/core/extensions/index.d.ts.map +1 -1
  348. package/dist/core/extensions/loader.d.ts.map +1 -1
  349. package/dist/core/extensions/loader.js +76 -21
  350. package/dist/core/extensions/loader.js.map +1 -1
  351. package/dist/core/extensions/runner.d.ts +2 -0
  352. package/dist/core/extensions/runner.d.ts.map +1 -1
  353. package/dist/core/extensions/runner.js +41 -112
  354. package/dist/core/extensions/runner.js.map +1 -1
  355. package/dist/core/extensions/stale-context.d.ts.map +1 -1
  356. package/dist/core/extensions/storage.d.ts.map +1 -1
  357. package/dist/core/extensions/storage.js.map +1 -1
  358. package/dist/core/extensions/types.d.ts.map +1 -1
  359. package/dist/core/extensions/types.js.map +1 -1
  360. package/dist/core/extensions/wrapper.d.ts.map +1 -1
  361. package/dist/core/extensions/wrapper.js.map +1 -1
  362. package/dist/core/failure-corpus.d.ts.map +1 -1
  363. package/dist/core/failure-corpus.js +2 -5
  364. package/dist/core/failure-corpus.js.map +1 -1
  365. package/dist/core/footer-data-provider.d.ts.map +1 -1
  366. package/dist/core/footer-data-provider.js +27 -33
  367. package/dist/core/footer-data-provider.js.map +1 -1
  368. package/dist/core/foreground-recovery-controller.d.ts.map +1 -1
  369. package/dist/core/foreground-recovery-controller.js +0 -4
  370. package/dist/core/foreground-recovery-controller.js.map +1 -1
  371. package/dist/core/gateways/channel-provider.d.ts.map +1 -1
  372. package/dist/core/gateways/channel-provider.js +7 -5
  373. package/dist/core/gateways/channel-provider.js.map +1 -1
  374. package/dist/core/goal-loop-controller.d.ts.map +1 -1
  375. package/dist/core/goal-loop-controller.js +0 -1
  376. package/dist/core/goal-loop-controller.js.map +1 -1
  377. package/dist/core/goals/compact-goal-context.d.ts.map +1 -1
  378. package/dist/core/goals/compact-goal-context.js +2 -4
  379. package/dist/core/goals/compact-goal-context.js.map +1 -1
  380. package/dist/core/goals/goal-acceptance.d.ts.map +1 -1
  381. package/dist/core/goals/goal-acceptance.js.map +1 -1
  382. package/dist/core/goals/goal-auto-continue-controller.d.ts.map +1 -1
  383. package/dist/core/goals/goal-auto-continue-controller.js +1 -3
  384. package/dist/core/goals/goal-auto-continue-controller.js.map +1 -1
  385. package/dist/core/goals/goal-continuation-controller.d.ts.map +1 -1
  386. package/dist/core/goals/goal-continuation-controller.js.map +1 -1
  387. package/dist/core/goals/goal-continuation-defaults.d.ts.map +1 -1
  388. package/dist/core/goals/goal-continuation-prompt.d.ts.map +1 -1
  389. package/dist/core/goals/goal-continuation-prompt.js.map +1 -1
  390. package/dist/core/goals/goal-lifecycle.d.ts.map +1 -1
  391. package/dist/core/goals/goal-lifecycle.js.map +1 -1
  392. package/dist/core/goals/goal-record.d.ts.map +1 -1
  393. package/dist/core/goals/goal-record.js.map +1 -1
  394. package/dist/core/goals/goal-runtime-snapshot.d.ts.map +1 -1
  395. package/dist/core/goals/goal-runtime-snapshot.js.map +1 -1
  396. package/dist/core/goals/goal-session-controller.d.ts +15 -0
  397. package/dist/core/goals/goal-session-controller.d.ts.map +1 -1
  398. package/dist/core/goals/goal-session-controller.js +27 -3
  399. package/dist/core/goals/goal-session-controller.js.map +1 -1
  400. package/dist/core/goals/goal-state.d.ts.map +1 -1
  401. package/dist/core/goals/goal-state.js +35 -51
  402. package/dist/core/goals/goal-state.js.map +1 -1
  403. package/dist/core/goals/goal-tool-core.d.ts.map +1 -1
  404. package/dist/core/goals/goal-tool-core.js.map +1 -1
  405. package/dist/core/goals/natural-language-goal.d.ts +9 -0
  406. package/dist/core/goals/natural-language-goal.d.ts.map +1 -0
  407. package/dist/core/goals/natural-language-goal.js +23 -0
  408. package/dist/core/goals/natural-language-goal.js.map +1 -0
  409. package/dist/core/goals/session-goal-state.d.ts.map +1 -1
  410. package/dist/core/goals/session-goal-state.js.map +1 -1
  411. package/dist/core/http-dispatcher.d.ts.map +1 -1
  412. package/dist/core/http-dispatcher.js.map +1 -1
  413. package/dist/core/human-input-controller.d.ts.map +1 -1
  414. package/dist/core/human-input-controller.js +2 -3
  415. package/dist/core/human-input-controller.js.map +1 -1
  416. package/dist/core/human-input.d.ts.map +1 -1
  417. package/dist/core/human-input.js.map +1 -1
  418. package/dist/core/improvement-loop.d.ts.map +1 -1
  419. package/dist/core/improvement-loop.js +11 -11
  420. package/dist/core/improvement-loop.js.map +1 -1
  421. package/dist/core/index.d.ts.map +1 -1
  422. package/dist/core/install-telemetry.d.ts.map +1 -1
  423. package/dist/core/install-telemetry.js.map +1 -1
  424. package/dist/core/isolated-text-completion.d.ts +17 -0
  425. package/dist/core/isolated-text-completion.d.ts.map +1 -0
  426. package/dist/core/isolated-text-completion.js +15 -0
  427. package/dist/core/isolated-text-completion.js.map +1 -0
  428. package/dist/core/keybindings.d.ts +47 -2
  429. package/dist/core/keybindings.d.ts.map +1 -1
  430. package/dist/core/keybindings.js +12 -1
  431. package/dist/core/keybindings.js.map +1 -1
  432. package/dist/core/learning/learning-audit.d.ts.map +1 -1
  433. package/dist/core/learning/learning-audit.js.map +1 -1
  434. package/dist/core/learning/learning-gate.d.ts.map +1 -1
  435. package/dist/core/learning/learning-gate.js.map +1 -1
  436. package/dist/core/learning/observation-store.d.ts.map +1 -1
  437. package/dist/core/learning/observation-store.js +0 -2
  438. package/dist/core/learning/observation-store.js.map +1 -1
  439. package/dist/core/learning/reflection-engine.d.ts +1 -1
  440. package/dist/core/learning/reflection-engine.d.ts.map +1 -1
  441. package/dist/core/learning/reflection-engine.js +3 -0
  442. package/dist/core/learning/reflection-engine.js.map +1 -1
  443. package/dist/core/learning/reflection-turn-analysis.d.ts +20 -0
  444. package/dist/core/learning/reflection-turn-analysis.d.ts.map +1 -0
  445. package/dist/core/learning/reflection-turn-analysis.js +136 -0
  446. package/dist/core/learning/reflection-turn-analysis.js.map +1 -0
  447. package/dist/core/learning/session-learning-decision.d.ts.map +1 -1
  448. package/dist/core/learning/session-learning-decision.js.map +1 -1
  449. package/dist/core/learning/skill-curator.d.ts.map +1 -1
  450. package/dist/core/learning/skill-curator.js +0 -3
  451. package/dist/core/learning/skill-curator.js.map +1 -1
  452. package/dist/core/local-runtime-controller.d.ts +39 -0
  453. package/dist/core/local-runtime-controller.d.ts.map +1 -1
  454. package/dist/core/local-runtime-controller.js +41 -62
  455. package/dist/core/local-runtime-controller.js.map +1 -1
  456. package/dist/core/memory/effectiveness-tracker.d.ts.map +1 -1
  457. package/dist/core/memory/effectiveness-tracker.js +4 -2
  458. package/dist/core/memory/effectiveness-tracker.js.map +1 -1
  459. package/dist/core/memory/memory-manager.d.ts.map +1 -1
  460. package/dist/core/memory/memory-manager.js +7 -7
  461. package/dist/core/memory/memory-manager.js.map +1 -1
  462. package/dist/core/memory/memory-provider.d.ts.map +1 -1
  463. package/dist/core/memory/providers/file-store.d.ts +7 -0
  464. package/dist/core/memory/providers/file-store.d.ts.map +1 -1
  465. package/dist/core/memory/providers/file-store.js +48 -13
  466. package/dist/core/memory/providers/file-store.js.map +1 -1
  467. package/dist/core/memory/providers/transcript-recall-worker-protocol.d.ts +47 -0
  468. package/dist/core/memory/providers/transcript-recall-worker-protocol.d.ts.map +1 -0
  469. package/dist/core/memory/providers/transcript-recall-worker-protocol.js +50 -0
  470. package/dist/core/memory/providers/transcript-recall-worker-protocol.js.map +1 -0
  471. package/dist/core/memory/providers/transcript-recall-worker.d.ts +2 -0
  472. package/dist/core/memory/providers/transcript-recall-worker.d.ts.map +1 -0
  473. package/dist/core/memory/providers/transcript-recall-worker.js +143 -0
  474. package/dist/core/memory/providers/transcript-recall-worker.js.map +1 -0
  475. package/dist/core/memory/providers/transcript-recall.d.ts +24 -13
  476. package/dist/core/memory/providers/transcript-recall.d.ts.map +1 -1
  477. package/dist/core/memory/providers/transcript-recall.js +143 -141
  478. package/dist/core/memory/providers/transcript-recall.js.map +1 -1
  479. package/dist/core/memory/providers/user-memory-archive.d.ts +39 -0
  480. package/dist/core/memory/providers/user-memory-archive.d.ts.map +1 -0
  481. package/dist/core/memory/providers/user-memory-archive.js +258 -0
  482. package/dist/core/memory/providers/user-memory-archive.js.map +1 -0
  483. package/dist/core/memory/transcript-index.d.ts.map +1 -1
  484. package/dist/core/memory/transcript-index.js +1 -1
  485. package/dist/core/memory/transcript-index.js.map +1 -1
  486. package/dist/core/memory-controller.d.ts +9 -0
  487. package/dist/core/memory-controller.d.ts.map +1 -1
  488. package/dist/core/memory-controller.js +57 -16
  489. package/dist/core/memory-controller.js.map +1 -1
  490. package/dist/core/model-capability.d.ts.map +1 -1
  491. package/dist/core/model-capability.js.map +1 -1
  492. package/dist/core/model-output-json.d.ts +10 -0
  493. package/dist/core/model-output-json.d.ts.map +1 -0
  494. package/dist/core/model-output-json.js +43 -0
  495. package/dist/core/model-output-json.js.map +1 -0
  496. package/dist/core/model-registry.d.ts +8 -8
  497. package/dist/core/model-registry.d.ts.map +1 -1
  498. package/dist/core/model-registry.js +29 -52
  499. package/dist/core/model-registry.js.map +1 -1
  500. package/dist/core/model-resolver.d.ts.map +1 -1
  501. package/dist/core/model-resolver.js +1 -1
  502. package/dist/core/model-resolver.js.map +1 -1
  503. package/dist/core/model-router/config-diagnostics.d.ts.map +1 -1
  504. package/dist/core/model-router/config-diagnostics.js.map +1 -1
  505. package/dist/core/model-router/executor-route.d.ts.map +1 -1
  506. package/dist/core/model-router/executor-route.js.map +1 -1
  507. package/dist/core/model-router/fitness-gate.d.ts.map +1 -1
  508. package/dist/core/model-router/fitness-gate.js.map +1 -1
  509. package/dist/core/model-router/intent-classifier.d.ts.map +1 -1
  510. package/dist/core/model-router/route-judge.d.ts.map +1 -1
  511. package/dist/core/model-router/route-judge.js +18 -36
  512. package/dist/core/model-router/route-judge.js.map +1 -1
  513. package/dist/core/model-router/session-buffer.d.ts.map +1 -1
  514. package/dist/core/model-router/session-buffer.js.map +1 -1
  515. package/dist/core/model-router/status.d.ts.map +1 -1
  516. package/dist/core/model-router/status.js.map +1 -1
  517. package/dist/core/model-router/tool-escalation.d.ts.map +1 -1
  518. package/dist/core/model-router/tool-escalation.js.map +1 -1
  519. package/dist/core/model-router-controller.d.ts +1 -0
  520. package/dist/core/model-router-controller.d.ts.map +1 -1
  521. package/dist/core/model-router-controller.js +25 -56
  522. package/dist/core/model-router-controller.js.map +1 -1
  523. package/dist/core/model-selection-controller.d.ts +10 -0
  524. package/dist/core/model-selection-controller.d.ts.map +1 -1
  525. package/dist/core/model-selection-controller.js +0 -1
  526. package/dist/core/model-selection-controller.js.map +1 -1
  527. package/dist/core/model-tool-protocol.d.ts.map +1 -1
  528. package/dist/core/model-tool-protocol.js.map +1 -1
  529. package/dist/core/models/adaptation-store.d.ts.map +1 -1
  530. package/dist/core/models/adaptation-store.js +0 -1
  531. package/dist/core/models/adaptation-store.js.map +1 -1
  532. package/dist/core/models/context-sizing.d.ts.map +1 -1
  533. package/dist/core/models/context-sizing.js.map +1 -1
  534. package/dist/core/models/default-model-suggestions.d.ts.map +1 -1
  535. package/dist/core/models/default-model-suggestions.js.map +1 -1
  536. package/dist/core/models/fitness-store.d.ts.map +1 -1
  537. package/dist/core/models/fitness-store.js +0 -1
  538. package/dist/core/models/fitness-store.js.map +1 -1
  539. package/dist/core/models/host-state-store.d.ts.map +1 -1
  540. package/dist/core/models/host-state-store.js +1 -6
  541. package/dist/core/models/host-state-store.js.map +1 -1
  542. package/dist/core/models/llamacpp-runtime.d.ts +4 -19
  543. package/dist/core/models/llamacpp-runtime.d.ts.map +1 -1
  544. package/dist/core/models/llamacpp-runtime.js +32 -136
  545. package/dist/core/models/llamacpp-runtime.js.map +1 -1
  546. package/dist/core/models/local-registration.d.ts.map +1 -1
  547. package/dist/core/models/local-registration.js +82 -115
  548. package/dist/core/models/local-registration.js.map +1 -1
  549. package/dist/core/models/local-runtime.d.ts +12 -18
  550. package/dist/core/models/local-runtime.d.ts.map +1 -1
  551. package/dist/core/models/local-runtime.js +60 -204
  552. package/dist/core/models/local-runtime.js.map +1 -1
  553. package/dist/core/models/model-endpoint.d.ts.map +1 -1
  554. package/dist/core/models/model-endpoint.js.map +1 -1
  555. package/dist/core/models/model-ref.d.ts.map +1 -1
  556. package/dist/core/models/model-ref.js.map +1 -1
  557. package/dist/core/models/needle-runtime.d.ts +7 -3
  558. package/dist/core/models/needle-runtime.d.ts.map +1 -1
  559. package/dist/core/models/needle-runtime.js +16 -92
  560. package/dist/core/models/needle-runtime.js.map +1 -1
  561. package/dist/core/models/perf-profile.d.ts +1 -1
  562. package/dist/core/models/perf-profile.d.ts.map +1 -1
  563. package/dist/core/models/perf-profile.js +6 -13
  564. package/dist/core/models/perf-profile.js.map +1 -1
  565. package/dist/core/models/prism-llamacpp-lifecycle.d.ts.map +1 -1
  566. package/dist/core/models/prism-llamacpp-lifecycle.js.map +1 -1
  567. package/dist/core/models/runtime-arbiter.d.ts.map +1 -1
  568. package/dist/core/models/runtime-arbiter.js +3 -15
  569. package/dist/core/models/runtime-arbiter.js.map +1 -1
  570. package/dist/core/models/runtime-process.d.ts +100 -0
  571. package/dist/core/models/runtime-process.d.ts.map +1 -0
  572. package/dist/core/models/runtime-process.js +183 -0
  573. package/dist/core/models/runtime-process.js.map +1 -0
  574. package/dist/core/orchestration/agent-resume.d.ts.map +1 -1
  575. package/dist/core/orchestration/agent-resume.js.map +1 -1
  576. package/dist/core/orchestration/attempt-usage.d.ts.map +1 -1
  577. package/dist/core/orchestration/attempt-usage.js.map +1 -1
  578. package/dist/core/orchestration/capability-gateway.d.ts.map +1 -1
  579. package/dist/core/orchestration/capability-gateway.js +0 -14
  580. package/dist/core/orchestration/capability-gateway.js.map +1 -1
  581. package/dist/core/orchestration/contracts.d.ts.map +1 -1
  582. package/dist/core/orchestration/contracts.js.map +1 -1
  583. package/dist/core/orchestration/delegation-ledger.d.ts.map +1 -1
  584. package/dist/core/orchestration/delegation-ledger.js +0 -2
  585. package/dist/core/orchestration/delegation-ledger.js.map +1 -1
  586. package/dist/core/orchestration/event-store.d.ts.map +1 -1
  587. package/dist/core/orchestration/event-store.js +1 -14
  588. package/dist/core/orchestration/event-store.js.map +1 -1
  589. package/dist/core/orchestration/lane-tool-manifests.d.ts.map +1 -1
  590. package/dist/core/orchestration/lane-tool-manifests.js.map +1 -1
  591. package/dist/core/orchestration/model-binding.d.ts.map +1 -1
  592. package/dist/core/orchestration/model-binding.js.map +1 -1
  593. package/dist/core/orchestration/policy-compiler.d.ts.map +1 -1
  594. package/dist/core/orchestration/policy-compiler.js +0 -3
  595. package/dist/core/orchestration/policy-compiler.js.map +1 -1
  596. package/dist/core/orchestration/policy-gate.d.ts.map +1 -1
  597. package/dist/core/orchestration/policy-gate.js +0 -2
  598. package/dist/core/orchestration/policy-gate.js.map +1 -1
  599. package/dist/core/orchestration/profile-registry.d.ts.map +1 -1
  600. package/dist/core/orchestration/profile-registry.js +1 -1
  601. package/dist/core/orchestration/profile-registry.js.map +1 -1
  602. package/dist/core/orchestration/profile-store.d.ts.map +1 -1
  603. package/dist/core/orchestration/profile-store.js +0 -3
  604. package/dist/core/orchestration/profile-store.js.map +1 -1
  605. package/dist/core/orchestration/risk-budget.d.ts.map +1 -1
  606. package/dist/core/orchestration/risk-budget.js.map +1 -1
  607. package/dist/core/orchestration/task-runtime.d.ts +1 -0
  608. package/dist/core/orchestration/task-runtime.d.ts.map +1 -1
  609. package/dist/core/orchestration/task-runtime.js +27 -42
  610. package/dist/core/orchestration/task-runtime.js.map +1 -1
  611. package/dist/core/orchestration/work-state-projection.d.ts.map +1 -1
  612. package/dist/core/orchestration/work-state-projection.js.map +1 -1
  613. package/dist/core/orchestration/worker-execution-contract.d.ts.map +1 -1
  614. package/dist/core/orchestration/worker-execution-contract.js.map +1 -1
  615. package/dist/core/orchestration/worker-result-adapter.d.ts.map +1 -1
  616. package/dist/core/orchestration/worker-result-adapter.js.map +1 -1
  617. package/dist/core/output-guard.d.ts.map +1 -1
  618. package/dist/core/output-guard.js.map +1 -1
  619. package/dist/core/package-manager.d.ts +3 -0
  620. package/dist/core/package-manager.d.ts.map +1 -1
  621. package/dist/core/package-manager.js +88 -353
  622. package/dist/core/package-manager.js.map +1 -1
  623. package/dist/core/process-identity.d.ts.map +1 -1
  624. package/dist/core/process-identity.js.map +1 -1
  625. package/dist/core/process-liveness.d.ts +3 -0
  626. package/dist/core/process-liveness.d.ts.map +1 -0
  627. package/dist/core/process-liveness.js +17 -0
  628. package/dist/core/process-liveness.js.map +1 -0
  629. package/dist/core/process-matrix/codes.d.ts.map +1 -1
  630. package/dist/core/process-matrix/resume-launcher.d.ts.map +1 -1
  631. package/dist/core/process-matrix/resume-launcher.js.map +1 -1
  632. package/dist/core/process-matrix/runtime.d.ts.map +1 -1
  633. package/dist/core/process-matrix/runtime.js.map +1 -1
  634. package/dist/core/process-matrix/store.d.ts.map +1 -1
  635. package/dist/core/process-matrix/store.js.map +1 -1
  636. package/dist/core/process-matrix/supervisor.d.ts.map +1 -1
  637. package/dist/core/process-matrix/supervisor.js.map +1 -1
  638. package/dist/core/profile-filter-controller.d.ts.map +1 -1
  639. package/dist/core/profile-filter-controller.js +7 -8
  640. package/dist/core/profile-filter-controller.js.map +1 -1
  641. package/dist/core/profile-registry.d.ts.map +1 -1
  642. package/dist/core/profile-registry.js +1 -2
  643. package/dist/core/profile-registry.js.map +1 -1
  644. package/dist/core/profile-resource-selection.d.ts.map +1 -1
  645. package/dist/core/profile-resource-selection.js +18 -59
  646. package/dist/core/profile-resource-selection.js.map +1 -1
  647. package/dist/core/prompt-markup.d.ts +3 -0
  648. package/dist/core/prompt-markup.d.ts.map +1 -0
  649. package/dist/core/prompt-markup.js +7 -0
  650. package/dist/core/prompt-markup.js.map +1 -0
  651. package/dist/core/prompt-templates.d.ts.map +1 -1
  652. package/dist/core/prompt-templates.js +13 -39
  653. package/dist/core/prompt-templates.js.map +1 -1
  654. package/dist/core/provider-display-names.d.ts.map +1 -1
  655. package/dist/core/python-runtime.d.ts.map +1 -1
  656. package/dist/core/python-runtime.js.map +1 -1
  657. package/dist/core/reflection-controller.d.ts +22 -1
  658. package/dist/core/reflection-controller.d.ts.map +1 -1
  659. package/dist/core/reflection-controller.js +143 -25
  660. package/dist/core/reflection-controller.js.map +1 -1
  661. package/dist/core/reload-blockers.d.ts +2 -1
  662. package/dist/core/reload-blockers.d.ts.map +1 -1
  663. package/dist/core/reload-blockers.js +4 -14
  664. package/dist/core/reload-blockers.js.map +1 -1
  665. package/dist/core/request-auth.d.ts.map +1 -1
  666. package/dist/core/request-auth.js.map +1 -1
  667. package/dist/core/research/automata-provider.d.ts.map +1 -1
  668. package/dist/core/research/automata-provider.js.map +1 -1
  669. package/dist/core/research/evidence-bundle.d.ts.map +1 -1
  670. package/dist/core/research/evidence-bundle.js.map +1 -1
  671. package/dist/core/research/lane-model-resolver.d.ts.map +1 -1
  672. package/dist/core/research/lane-model-resolver.js +0 -1
  673. package/dist/core/research/lane-model-resolver.js.map +1 -1
  674. package/dist/core/research/model-fitness-controller.d.ts.map +1 -1
  675. package/dist/core/research/model-fitness-controller.js +17 -33
  676. package/dist/core/research/model-fitness-controller.js.map +1 -1
  677. package/dist/core/research/model-fitness.d.ts.map +1 -1
  678. package/dist/core/research/model-fitness.js +4 -25
  679. package/dist/core/research/model-fitness.js.map +1 -1
  680. package/dist/core/research/research-gate.d.ts.map +1 -1
  681. package/dist/core/research/research-gate.js.map +1 -1
  682. package/dist/core/research/research-lane-controller.d.ts.map +1 -1
  683. package/dist/core/research/research-lane-controller.js +5 -10
  684. package/dist/core/research/research-lane-controller.js.map +1 -1
  685. package/dist/core/research/research-runner.d.ts +2 -4
  686. package/dist/core/research/research-runner.d.ts.map +1 -1
  687. package/dist/core/research/research-runner.js +17 -48
  688. package/dist/core/research/research-runner.js.map +1 -1
  689. package/dist/core/research/session-evidence-bundle.d.ts.map +1 -1
  690. package/dist/core/research/session-evidence-bundle.js.map +1 -1
  691. package/dist/core/research/workspace-collector.d.ts.map +1 -1
  692. package/dist/core/research/workspace-collector.js.map +1 -1
  693. package/dist/core/resolve-config-value.d.ts.map +1 -1
  694. package/dist/core/resolve-config-value.js.map +1 -1
  695. package/dist/core/resource-ignore.d.ts +6 -0
  696. package/dist/core/resource-ignore.d.ts.map +1 -0
  697. package/dist/core/resource-ignore.js +44 -0
  698. package/dist/core/resource-ignore.js.map +1 -0
  699. package/dist/core/resource-loader.d.ts +0 -1
  700. package/dist/core/resource-loader.d.ts.map +1 -1
  701. package/dist/core/resource-loader.js +52 -187
  702. package/dist/core/resource-loader.js.map +1 -1
  703. package/dist/core/resource-profile-blocks.d.ts +3 -1
  704. package/dist/core/resource-profile-blocks.d.ts.map +1 -1
  705. package/dist/core/resource-profile-blocks.js +8 -5
  706. package/dist/core/resource-profile-blocks.js.map +1 -1
  707. package/dist/core/resource-profile-equality.d.ts.map +1 -1
  708. package/dist/core/resource-profile-equality.js.map +1 -1
  709. package/dist/core/resource-traversal.d.ts +43 -0
  710. package/dist/core/resource-traversal.d.ts.map +1 -0
  711. package/dist/core/resource-traversal.js +84 -0
  712. package/dist/core/resource-traversal.js.map +1 -0
  713. package/dist/core/risk-classifier.d.ts.map +1 -1
  714. package/dist/core/risk-classifier.js.map +1 -1
  715. package/dist/core/runtime-builder.d.ts +4 -1
  716. package/dist/core/runtime-builder.d.ts.map +1 -1
  717. package/dist/core/runtime-builder.js +25 -50
  718. package/dist/core/runtime-builder.js.map +1 -1
  719. package/dist/core/scout-controller.d.ts.map +1 -1
  720. package/dist/core/scout-controller.js +0 -1
  721. package/dist/core/scout-controller.js.map +1 -1
  722. package/dist/core/sdk.d.ts.map +1 -1
  723. package/dist/core/sdk.js.map +1 -1
  724. package/dist/core/secrets/credential-exposure-guard.d.ts.map +1 -1
  725. package/dist/core/secrets/credential-exposure-guard.js +70 -44
  726. package/dist/core/secrets/credential-exposure-guard.js.map +1 -1
  727. package/dist/core/secrets/secret-dotenv.d.ts.map +1 -1
  728. package/dist/core/secrets/secret-dotenv.js +0 -1
  729. package/dist/core/secrets/secret-dotenv.js.map +1 -1
  730. package/dist/core/secrets/secret-vault-format.d.ts.map +1 -1
  731. package/dist/core/secrets/secret-vault-format.js +0 -1
  732. package/dist/core/secrets/secret-vault-format.js.map +1 -1
  733. package/dist/core/secrets/secret-vault.d.ts.map +1 -1
  734. package/dist/core/secrets/secret-vault.js +2 -10
  735. package/dist/core/secrets/secret-vault.js.map +1 -1
  736. package/dist/core/security/secret-text.d.ts.map +1 -1
  737. package/dist/core/security/secret-text.js.map +1 -1
  738. package/dist/core/security/untrusted-boundary.d.ts.map +1 -1
  739. package/dist/core/security/untrusted-boundary.js.map +1 -1
  740. package/dist/core/session-analytics.d.ts.map +1 -1
  741. package/dist/core/session-analytics.js +18 -50
  742. package/dist/core/session-analytics.js.map +1 -1
  743. package/dist/core/session-artifact-bundle.d.ts.map +1 -1
  744. package/dist/core/session-artifact-bundle.js.map +1 -1
  745. package/dist/core/session-cwd.d.ts.map +1 -1
  746. package/dist/core/session-cwd.js +0 -1
  747. package/dist/core/session-cwd.js.map +1 -1
  748. package/dist/core/session-entry-index.d.ts +8 -0
  749. package/dist/core/session-entry-index.d.ts.map +1 -0
  750. package/dist/core/session-entry-index.js +16 -0
  751. package/dist/core/session-entry-index.js.map +1 -0
  752. package/dist/core/session-image-store.d.ts.map +1 -1
  753. package/dist/core/session-image-store.js +0 -3
  754. package/dist/core/session-image-store.js.map +1 -1
  755. package/dist/core/session-jsonl-writer.d.ts +3 -0
  756. package/dist/core/session-jsonl-writer.d.ts.map +1 -0
  757. package/dist/core/session-jsonl-writer.js +38 -0
  758. package/dist/core/session-jsonl-writer.js.map +1 -0
  759. package/dist/core/session-manager-factory.d.ts.map +1 -1
  760. package/dist/core/session-manager-factory.js.map +1 -1
  761. package/dist/core/session-role.d.ts.map +1 -1
  762. package/dist/core/session-role.js.map +1 -1
  763. package/dist/core/session-snapshot.d.ts.map +1 -1
  764. package/dist/core/session-snapshot.js.map +1 -1
  765. package/dist/core/session-supervision-runtime.d.ts.map +1 -1
  766. package/dist/core/session-supervision-runtime.js +1 -4
  767. package/dist/core/session-supervision-runtime.js.map +1 -1
  768. package/dist/core/session-tree-navigator.d.ts.map +1 -1
  769. package/dist/core/session-tree-navigator.js +0 -1
  770. package/dist/core/session-tree-navigator.js.map +1 -1
  771. package/dist/core/settings-manager.d.ts +2 -1
  772. package/dist/core/settings-manager.d.ts.map +1 -1
  773. package/dist/core/settings-manager.js +64 -162
  774. package/dist/core/settings-manager.js.map +1 -1
  775. package/dist/core/skill-block.d.mts +8 -0
  776. package/dist/core/skill-block.mjs +52 -0
  777. package/dist/core/skill-discovery.d.ts +5 -0
  778. package/dist/core/skill-discovery.d.ts.map +1 -0
  779. package/dist/core/skill-discovery.js +34 -0
  780. package/dist/core/skill-discovery.js.map +1 -0
  781. package/dist/core/skills.d.ts.map +1 -1
  782. package/dist/core/skills.js +23 -159
  783. package/dist/core/skills.js.map +1 -1
  784. package/dist/core/slash-commands.d.ts.map +1 -1
  785. package/dist/core/source-info.d.ts.map +1 -1
  786. package/dist/core/source-info.js.map +1 -1
  787. package/dist/core/spawned-usage.d.ts +21 -0
  788. package/dist/core/spawned-usage.d.ts.map +1 -0
  789. package/dist/core/spawned-usage.js +29 -0
  790. package/dist/core/spawned-usage.js.map +1 -0
  791. package/dist/core/system-prompt-builder.d.ts +4 -0
  792. package/dist/core/system-prompt-builder.d.ts.map +1 -1
  793. package/dist/core/system-prompt-builder.js +15 -8
  794. package/dist/core/system-prompt-builder.js.map +1 -1
  795. package/dist/core/system-prompt.d.ts.map +1 -1
  796. package/dist/core/system-prompt.js +52 -35
  797. package/dist/core/system-prompt.js.map +1 -1
  798. package/dist/core/tasks/session-task-state.d.ts.map +1 -1
  799. package/dist/core/tasks/session-task-state.js.map +1 -1
  800. package/dist/core/tasks/task-command.d.ts.map +1 -1
  801. package/dist/core/tasks/task-command.js.map +1 -1
  802. package/dist/core/tasks/task-contract-monitor.d.ts.map +1 -1
  803. package/dist/core/tasks/task-contract-monitor.js.map +1 -1
  804. package/dist/core/tasks/task-projection.d.ts.map +1 -1
  805. package/dist/core/tasks/task-projection.js.map +1 -1
  806. package/dist/core/tasks/task-state.d.ts.map +1 -1
  807. package/dist/core/tasks/task-state.js.map +1 -1
  808. package/dist/core/text-preview.d.ts +4 -0
  809. package/dist/core/text-preview.d.ts.map +1 -0
  810. package/dist/core/text-preview.js +33 -0
  811. package/dist/core/text-preview.js.map +1 -0
  812. package/dist/core/timings.d.ts.map +1 -1
  813. package/dist/core/timings.js.map +1 -1
  814. package/dist/core/tool-capability-policy.d.ts.map +1 -1
  815. package/dist/core/tool-capability-policy.js.map +1 -1
  816. package/dist/core/tool-gate-controller.d.ts.map +1 -1
  817. package/dist/core/tool-gate-controller.js +86 -87
  818. package/dist/core/tool-gate-controller.js.map +1 -1
  819. package/dist/core/tool-protocol-controller.d.ts +4 -1
  820. package/dist/core/tool-protocol-controller.d.ts.map +1 -1
  821. package/dist/core/tool-protocol-controller.js +19 -23
  822. package/dist/core/tool-protocol-controller.js.map +1 -1
  823. package/dist/core/tool-recovery-log-records.d.ts.map +1 -1
  824. package/dist/core/tool-recovery-log-records.js.map +1 -1
  825. package/dist/core/tool-recovery-log-worker.d.ts.map +1 -1
  826. package/dist/core/tool-recovery-log-worker.js.map +1 -1
  827. package/dist/core/tool-recovery-logger.d.ts.map +1 -1
  828. package/dist/core/tool-recovery-logger.js +12 -24
  829. package/dist/core/tool-recovery-logger.js.map +1 -1
  830. package/dist/core/tool-recovery-stats.d.ts.map +1 -1
  831. package/dist/core/tool-recovery-stats.js +16 -22
  832. package/dist/core/tool-recovery-stats.js.map +1 -1
  833. package/dist/core/tool-repair-health.d.ts.map +1 -1
  834. package/dist/core/tool-repair-health.js.map +1 -1
  835. package/dist/core/tool-repair-settings.d.ts.map +1 -1
  836. package/dist/core/tool-repair-settings.js.map +1 -1
  837. package/dist/core/tool-selection/expected-utility.d.ts.map +1 -1
  838. package/dist/core/tool-selection/expected-utility.js.map +1 -1
  839. package/dist/core/tool-selection/promotion.d.ts.map +1 -1
  840. package/dist/core/tool-selection/promotion.js.map +1 -1
  841. package/dist/core/tool-selection/tool-performance-store.d.ts +2 -0
  842. package/dist/core/tool-selection/tool-performance-store.d.ts.map +1 -1
  843. package/dist/core/tool-selection/tool-performance-store.js +49 -7
  844. package/dist/core/tool-selection/tool-performance-store.js.map +1 -1
  845. package/dist/core/tool-selection/tool-phase-timing.d.ts +19 -0
  846. package/dist/core/tool-selection/tool-phase-timing.d.ts.map +1 -0
  847. package/dist/core/tool-selection/tool-phase-timing.js +63 -0
  848. package/dist/core/tool-selection/tool-phase-timing.js.map +1 -0
  849. package/dist/core/tool-selection/tool-selection-controller.d.ts +2 -5
  850. package/dist/core/tool-selection/tool-selection-controller.d.ts.map +1 -1
  851. package/dist/core/tool-selection/tool-selection-controller.js +50 -30
  852. package/dist/core/tool-selection/tool-selection-controller.js.map +1 -1
  853. package/dist/core/toolkit/reflex-interpreter.d.ts +16 -0
  854. package/dist/core/toolkit/reflex-interpreter.d.ts.map +1 -1
  855. package/dist/core/toolkit/reflex-interpreter.js +21 -0
  856. package/dist/core/toolkit/reflex-interpreter.js.map +1 -1
  857. package/dist/core/toolkit/script-registry.d.ts.map +1 -1
  858. package/dist/core/toolkit/script-registry.js.map +1 -1
  859. package/dist/core/toolkit/script-runner.d.ts.map +1 -1
  860. package/dist/core/toolkit/script-runner.js.map +1 -1
  861. package/dist/core/tools/artifact-retrieve.d.ts.map +1 -1
  862. package/dist/core/tools/artifact-retrieve.js.map +1 -1
  863. package/dist/core/tools/ask-question.d.ts +2 -3
  864. package/dist/core/tools/ask-question.d.ts.map +1 -1
  865. package/dist/core/tools/ask-question.js +14 -40
  866. package/dist/core/tools/ask-question.js.map +1 -1
  867. package/dist/core/tools/bash.d.ts +2 -0
  868. package/dist/core/tools/bash.d.ts.map +1 -1
  869. package/dist/core/tools/bash.js +83 -30
  870. package/dist/core/tools/bash.js.map +1 -1
  871. package/dist/core/tools/context-scout.d.ts.map +1 -1
  872. package/dist/core/tools/context-scout.js.map +1 -1
  873. package/dist/core/tools/delegate-status.d.ts.map +1 -1
  874. package/dist/core/tools/delegate-status.js +9 -7
  875. package/dist/core/tools/delegate-status.js.map +1 -1
  876. package/dist/core/tools/delegate.d.ts.map +1 -1
  877. package/dist/core/tools/delegate.js +6 -6
  878. package/dist/core/tools/delegate.js.map +1 -1
  879. package/dist/core/tools/edit-diff.d.ts.map +1 -1
  880. package/dist/core/tools/edit-diff.js.map +1 -1
  881. package/dist/core/tools/edit.d.ts.map +1 -1
  882. package/dist/core/tools/edit.js.map +1 -1
  883. package/dist/core/tools/extensionify.d.ts.map +1 -1
  884. package/dist/core/tools/extensionify.js.map +1 -1
  885. package/dist/core/tools/fff-search-backend.d.ts +19 -0
  886. package/dist/core/tools/fff-search-backend.d.ts.map +1 -1
  887. package/dist/core/tools/fff-search-backend.js +28 -2
  888. package/dist/core/tools/fff-search-backend.js.map +1 -1
  889. package/dist/core/tools/file-encoding-policy.d.ts.map +1 -1
  890. package/dist/core/tools/file-encoding-policy.js.map +1 -1
  891. package/dist/core/tools/file-mutation-queue.d.ts.map +1 -1
  892. package/dist/core/tools/file-mutation-queue.js.map +1 -1
  893. package/dist/core/tools/find.d.ts +1 -1
  894. package/dist/core/tools/find.d.ts.map +1 -1
  895. package/dist/core/tools/find.js +44 -108
  896. package/dist/core/tools/find.js.map +1 -1
  897. package/dist/core/tools/git-filter.d.ts.map +1 -1
  898. package/dist/core/tools/git-filter.js.map +1 -1
  899. package/dist/core/tools/goal.d.ts.map +1 -1
  900. package/dist/core/tools/goal.js +7 -7
  901. package/dist/core/tools/goal.js.map +1 -1
  902. package/dist/core/tools/grep.d.ts +1 -1
  903. package/dist/core/tools/grep.d.ts.map +1 -1
  904. package/dist/core/tools/grep.js +42 -102
  905. package/dist/core/tools/grep.js.map +1 -1
  906. package/dist/core/tools/index.d.ts.map +1 -1
  907. package/dist/core/tools/index.js.map +1 -1
  908. package/dist/core/tools/ls.d.ts.map +1 -1
  909. package/dist/core/tools/ls.js +20 -36
  910. package/dist/core/tools/ls.js.map +1 -1
  911. package/dist/core/tools/model-fitness.d.ts.map +1 -1
  912. package/dist/core/tools/model-fitness.js.map +1 -1
  913. package/dist/core/tools/orchestration-panel.d.ts +5 -0
  914. package/dist/core/tools/orchestration-panel.d.ts.map +1 -1
  915. package/dist/core/tools/orchestration-panel.js +5 -5
  916. package/dist/core/tools/orchestration-panel.js.map +1 -1
  917. package/dist/core/tools/output-accumulator.d.ts +2 -0
  918. package/dist/core/tools/output-accumulator.d.ts.map +1 -1
  919. package/dist/core/tools/output-accumulator.js +24 -36
  920. package/dist/core/tools/output-accumulator.js.map +1 -1
  921. package/dist/core/tools/path-utils.d.ts.map +1 -1
  922. package/dist/core/tools/path-utils.js.map +1 -1
  923. package/dist/core/tools/persistent-process-coordinator.d.ts +31 -0
  924. package/dist/core/tools/persistent-process-coordinator.d.ts.map +1 -0
  925. package/dist/core/tools/persistent-process-coordinator.js +123 -0
  926. package/dist/core/tools/persistent-process-coordinator.js.map +1 -0
  927. package/dist/core/tools/python.d.ts.map +1 -1
  928. package/dist/core/tools/python.js.map +1 -1
  929. package/dist/core/tools/read.d.ts.map +1 -1
  930. package/dist/core/tools/read.js +14 -13
  931. package/dist/core/tools/read.js.map +1 -1
  932. package/dist/core/tools/render-utils.d.ts +29 -0
  933. package/dist/core/tools/render-utils.d.ts.map +1 -1
  934. package/dist/core/tools/render-utils.js +31 -1
  935. package/dist/core/tools/render-utils.js.map +1 -1
  936. package/dist/core/tools/run-process.d.ts.map +1 -1
  937. package/dist/core/tools/run-process.js.map +1 -1
  938. package/dist/core/tools/run-toolkit-script.d.ts.map +1 -1
  939. package/dist/core/tools/run-toolkit-script.js.map +1 -1
  940. package/dist/core/tools/search-command-guard.d.ts +10 -0
  941. package/dist/core/tools/search-command-guard.d.ts.map +1 -1
  942. package/dist/core/tools/search-command-guard.js +118 -31
  943. package/dist/core/tools/search-command-guard.js.map +1 -1
  944. package/dist/core/tools/search-router.d.ts.map +1 -1
  945. package/dist/core/tools/search-router.js.map +1 -1
  946. package/dist/core/tools/search-tool-runtime.d.ts +19 -0
  947. package/dist/core/tools/search-tool-runtime.d.ts.map +1 -0
  948. package/dist/core/tools/search-tool-runtime.js +12 -0
  949. package/dist/core/tools/search-tool-runtime.js.map +1 -0
  950. package/dist/core/tools/secret-store.d.ts.map +1 -1
  951. package/dist/core/tools/secret-store.js.map +1 -1
  952. package/dist/core/tools/shell-command-parser.d.ts.map +1 -1
  953. package/dist/core/tools/shell-command-parser.js.map +1 -1
  954. package/dist/core/tools/shell-contract-router.d.ts.map +1 -1
  955. package/dist/core/tools/shell-contract-router.js +4 -1
  956. package/dist/core/tools/shell-contract-router.js.map +1 -1
  957. package/dist/core/tools/shell-execution-session.d.ts +4 -0
  958. package/dist/core/tools/shell-execution-session.d.ts.map +1 -0
  959. package/dist/core/tools/shell-execution-session.js +11 -0
  960. package/dist/core/tools/shell-execution-session.js.map +1 -0
  961. package/dist/core/tools/shell-output-projection.d.ts +49 -0
  962. package/dist/core/tools/shell-output-projection.d.ts.map +1 -0
  963. package/dist/core/tools/shell-output-projection.js +381 -0
  964. package/dist/core/tools/shell-output-projection.js.map +1 -0
  965. package/dist/core/tools/shell-session.d.ts +2 -13
  966. package/dist/core/tools/shell-session.d.ts.map +1 -1
  967. package/dist/core/tools/shell-session.js +36 -136
  968. package/dist/core/tools/shell-session.js.map +1 -1
  969. package/dist/core/tools/skill-audit.d.ts.map +1 -1
  970. package/dist/core/tools/skill-audit.js.map +1 -1
  971. package/dist/core/tools/skillify.d.ts.map +1 -1
  972. package/dist/core/tools/skillify.js.map +1 -1
  973. package/dist/core/tools/task-steps.d.ts +8 -8
  974. package/dist/core/tools/task-steps.d.ts.map +1 -1
  975. package/dist/core/tools/task-steps.js +17 -18
  976. package/dist/core/tools/task-steps.js.map +1 -1
  977. package/dist/core/tools/tmux-dispatch.d.ts.map +1 -1
  978. package/dist/core/tools/tmux-dispatch.js.map +1 -1
  979. package/dist/core/tools/tool-definition-wrapper.d.ts.map +1 -1
  980. package/dist/core/tools/tool-definition-wrapper.js.map +1 -1
  981. package/dist/core/tools/tool-task.d.ts +23 -0
  982. package/dist/core/tools/tool-task.d.ts.map +1 -0
  983. package/dist/core/tools/tool-task.js +93 -0
  984. package/dist/core/tools/tool-task.js.map +1 -0
  985. package/dist/core/tools/windows-shell-engine.d.ts +17 -11
  986. package/dist/core/tools/windows-shell-engine.d.ts.map +1 -1
  987. package/dist/core/tools/windows-shell-engine.js +339 -117
  988. package/dist/core/tools/windows-shell-engine.js.map +1 -1
  989. package/dist/core/tools/windows-shell-state.d.ts.map +1 -1
  990. package/dist/core/tools/windows-shell-state.js.map +1 -1
  991. package/dist/core/tools/worktree-sync.d.ts.map +1 -1
  992. package/dist/core/tools/worktree-sync.js +8 -12
  993. package/dist/core/tools/worktree-sync.js.map +1 -1
  994. package/dist/core/tools/write.d.ts.map +1 -1
  995. package/dist/core/tools/write.js +0 -1
  996. package/dist/core/tools/write.js.map +1 -1
  997. package/dist/core/trust-manager.d.ts.map +1 -1
  998. package/dist/core/trust-manager.js +7 -40
  999. package/dist/core/trust-manager.js.map +1 -1
  1000. package/dist/core/util/atomic-file.d.ts +19 -0
  1001. package/dist/core/util/atomic-file.d.ts.map +1 -1
  1002. package/dist/core/util/atomic-file.js +50 -15
  1003. package/dist/core/util/atomic-file.js.map +1 -1
  1004. package/dist/core/util/bounded-file.d.ts.map +1 -1
  1005. package/dist/core/util/bounded-file.js.map +1 -1
  1006. package/dist/core/util/bounded-jsonl.d.ts.map +1 -1
  1007. package/dist/core/util/bounded-jsonl.js +2 -9
  1008. package/dist/core/util/bounded-jsonl.js.map +1 -1
  1009. package/dist/core/util/bounded-value.d.ts.map +1 -1
  1010. package/dist/core/util/bounded-value.js.map +1 -1
  1011. package/dist/core/util/json-size.d.ts +3 -0
  1012. package/dist/core/util/json-size.d.ts.map +1 -0
  1013. package/dist/core/util/json-size.js +95 -0
  1014. package/dist/core/util/json-size.js.map +1 -0
  1015. package/dist/core/util/minimatch-cache.d.ts.map +1 -1
  1016. package/dist/core/util/minimatch-cache.js.map +1 -1
  1017. package/dist/core/util/value-guards.d.ts.map +1 -1
  1018. package/dist/core/util/value-guards.js.map +1 -1
  1019. package/dist/core/worktree-sync/codes.d.ts.map +1 -1
  1020. package/dist/core/worktree-sync/git-engine.d.ts.map +1 -1
  1021. package/dist/core/worktree-sync/git-engine.js +20 -36
  1022. package/dist/core/worktree-sync/git-engine.js.map +1 -1
  1023. package/dist/core/worktree-sync/lane-gate.d.ts.map +1 -1
  1024. package/dist/core/worktree-sync/lane-gate.js +1 -4
  1025. package/dist/core/worktree-sync/lane-gate.js.map +1 -1
  1026. package/dist/core/worktree-sync/runtime.d.ts.map +1 -1
  1027. package/dist/core/worktree-sync/runtime.js.map +1 -1
  1028. package/dist/core/worktree-sync/store.d.ts.map +1 -1
  1029. package/dist/core/worktree-sync/store.js.map +1 -1
  1030. package/dist/core/worktree-sync/watcher.d.ts.map +1 -1
  1031. package/dist/core/worktree-sync/watcher.js.map +1 -1
  1032. package/dist/index.d.ts.map +1 -1
  1033. package/dist/index.js.map +1 -1
  1034. package/dist/main.d.ts.map +1 -1
  1035. package/dist/main.js +10 -32
  1036. package/dist/main.js.map +1 -1
  1037. package/dist/migrations.d.ts.map +1 -1
  1038. package/dist/migrations.js +6 -19
  1039. package/dist/migrations.js.map +1 -1
  1040. package/dist/modes/index.d.ts.map +1 -1
  1041. package/dist/modes/interactive/auth-dialogs-controller.d.ts +3 -0
  1042. package/dist/modes/interactive/auth-dialogs-controller.d.ts.map +1 -1
  1043. package/dist/modes/interactive/auth-dialogs-controller.js +96 -132
  1044. package/dist/modes/interactive/auth-dialogs-controller.js.map +1 -1
  1045. package/dist/modes/interactive/auto-learn-controller.d.ts +1 -31
  1046. package/dist/modes/interactive/auto-learn-controller.d.ts.map +1 -1
  1047. package/dist/modes/interactive/auto-learn-controller.js +86 -307
  1048. package/dist/modes/interactive/auto-learn-controller.js.map +1 -1
  1049. package/dist/modes/interactive/autocomplete-provider.d.ts.map +1 -1
  1050. package/dist/modes/interactive/autocomplete-provider.js.map +1 -1
  1051. package/dist/modes/interactive/autonomy-commands.d.ts.map +1 -1
  1052. package/dist/modes/interactive/autonomy-commands.js +2 -8
  1053. package/dist/modes/interactive/autonomy-commands.js.map +1 -1
  1054. package/dist/modes/interactive/clipboard-input.d.ts +5 -1
  1055. package/dist/modes/interactive/clipboard-input.d.ts.map +1 -1
  1056. package/dist/modes/interactive/clipboard-input.js +17 -0
  1057. package/dist/modes/interactive/clipboard-input.js.map +1 -1
  1058. package/dist/modes/interactive/compaction-queue.d.ts.map +1 -1
  1059. package/dist/modes/interactive/compaction-queue.js +13 -18
  1060. package/dist/modes/interactive/compaction-queue.js.map +1 -1
  1061. package/dist/modes/interactive/components/activity-lane.d.ts.map +1 -1
  1062. package/dist/modes/interactive/components/activity-lane.js +6 -10
  1063. package/dist/modes/interactive/components/activity-lane.js.map +1 -1
  1064. package/dist/modes/interactive/components/armin.d.ts +1 -0
  1065. package/dist/modes/interactive/components/armin.d.ts.map +1 -1
  1066. package/dist/modes/interactive/components/armin.js +10 -21
  1067. package/dist/modes/interactive/components/armin.js.map +1 -1
  1068. package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
  1069. package/dist/modes/interactive/components/assistant-message.js +1 -6
  1070. package/dist/modes/interactive/components/assistant-message.js.map +1 -1
  1071. package/dist/modes/interactive/components/bash-execution.d.ts.map +1 -1
  1072. package/dist/modes/interactive/components/bash-execution.js +4 -9
  1073. package/dist/modes/interactive/components/bash-execution.js.map +1 -1
  1074. package/dist/modes/interactive/components/bordered-loader.d.ts.map +1 -1
  1075. package/dist/modes/interactive/components/bordered-loader.js +0 -3
  1076. package/dist/modes/interactive/components/bordered-loader.js.map +1 -1
  1077. package/dist/modes/interactive/components/branch-summary-message.d.ts +3 -8
  1078. package/dist/modes/interactive/components/branch-summary-message.d.ts.map +1 -1
  1079. package/dist/modes/interactive/components/branch-summary-message.js +13 -35
  1080. package/dist/modes/interactive/components/branch-summary-message.js.map +1 -1
  1081. package/dist/modes/interactive/components/compaction-summary-message.d.ts +3 -8
  1082. package/dist/modes/interactive/components/compaction-summary-message.d.ts.map +1 -1
  1083. package/dist/modes/interactive/components/compaction-summary-message.js +14 -36
  1084. package/dist/modes/interactive/components/compaction-summary-message.js.map +1 -1
  1085. package/dist/modes/interactive/components/config-selector.d.ts +1 -0
  1086. package/dist/modes/interactive/components/config-selector.d.ts.map +1 -1
  1087. package/dist/modes/interactive/components/config-selector.js +20 -43
  1088. package/dist/modes/interactive/components/config-selector.js.map +1 -1
  1089. package/dist/modes/interactive/components/countdown-timer.d.ts.map +1 -1
  1090. package/dist/modes/interactive/components/countdown-timer.js +0 -5
  1091. package/dist/modes/interactive/components/countdown-timer.js.map +1 -1
  1092. package/dist/modes/interactive/components/custom-editor.d.ts +2 -0
  1093. package/dist/modes/interactive/components/custom-editor.d.ts.map +1 -1
  1094. package/dist/modes/interactive/components/custom-editor.js +4 -8
  1095. package/dist/modes/interactive/components/custom-editor.js.map +1 -1
  1096. package/dist/modes/interactive/components/custom-message.d.ts.map +1 -1
  1097. package/dist/modes/interactive/components/custom-message.js +1 -6
  1098. package/dist/modes/interactive/components/custom-message.js.map +1 -1
  1099. package/dist/modes/interactive/components/daxnuts.d.ts.map +1 -1
  1100. package/dist/modes/interactive/components/daxnuts.js +6 -8
  1101. package/dist/modes/interactive/components/daxnuts.js.map +1 -1
  1102. package/dist/modes/interactive/components/diff.d.ts.map +1 -1
  1103. package/dist/modes/interactive/components/diff.js.map +1 -1
  1104. package/dist/modes/interactive/components/dynamic-border.d.ts.map +1 -1
  1105. package/dist/modes/interactive/components/dynamic-border.js +0 -1
  1106. package/dist/modes/interactive/components/dynamic-border.js.map +1 -1
  1107. package/dist/modes/interactive/components/earendil-announcement.d.ts.map +1 -1
  1108. package/dist/modes/interactive/components/earendil-announcement.js.map +1 -1
  1109. package/dist/modes/interactive/components/expandable-markdown-message.d.ts +21 -0
  1110. package/dist/modes/interactive/components/expandable-markdown-message.d.ts.map +1 -0
  1111. package/dist/modes/interactive/components/expandable-markdown-message.js +48 -0
  1112. package/dist/modes/interactive/components/expandable-markdown-message.js.map +1 -0
  1113. package/dist/modes/interactive/components/expandable-text.d.ts.map +1 -1
  1114. package/dist/modes/interactive/components/expandable-text.js +0 -2
  1115. package/dist/modes/interactive/components/expandable-text.js.map +1 -1
  1116. package/dist/modes/interactive/components/extension-editor.d.ts.map +1 -1
  1117. package/dist/modes/interactive/components/extension-editor.js +1 -9
  1118. package/dist/modes/interactive/components/extension-editor.js.map +1 -1
  1119. package/dist/modes/interactive/components/extension-input.d.ts.map +1 -1
  1120. package/dist/modes/interactive/components/extension-input.js +2 -8
  1121. package/dist/modes/interactive/components/extension-input.js.map +1 -1
  1122. package/dist/modes/interactive/components/extension-selector.d.ts.map +1 -1
  1123. package/dist/modes/interactive/components/extension-selector.js +5 -20
  1124. package/dist/modes/interactive/components/extension-selector.js.map +1 -1
  1125. package/dist/modes/interactive/components/fitness-role-selector.d.ts.map +1 -1
  1126. package/dist/modes/interactive/components/fitness-role-selector.js +0 -1
  1127. package/dist/modes/interactive/components/fitness-role-selector.js.map +1 -1
  1128. package/dist/modes/interactive/components/footer.d.ts.map +1 -1
  1129. package/dist/modes/interactive/components/footer.js +1 -5
  1130. package/dist/modes/interactive/components/footer.js.map +1 -1
  1131. package/dist/modes/interactive/components/index.d.ts.map +1 -1
  1132. package/dist/modes/interactive/components/keybinding-hints.d.ts.map +1 -1
  1133. package/dist/modes/interactive/components/keybinding-hints.js.map +1 -1
  1134. package/dist/modes/interactive/components/login-dialog.d.ts.map +1 -1
  1135. package/dist/modes/interactive/components/login-dialog.js +4 -10
  1136. package/dist/modes/interactive/components/login-dialog.js.map +1 -1
  1137. package/dist/modes/interactive/components/model-selector.d.ts +2 -2
  1138. package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
  1139. package/dist/modes/interactive/components/model-selector.js +21 -44
  1140. package/dist/modes/interactive/components/model-selector.js.map +1 -1
  1141. package/dist/modes/interactive/components/model-suggestion-selector.d.ts.map +1 -1
  1142. package/dist/modes/interactive/components/model-suggestion-selector.js +0 -1
  1143. package/dist/modes/interactive/components/model-suggestion-selector.js.map +1 -1
  1144. package/dist/modes/interactive/components/oauth-selector.d.ts +1 -1
  1145. package/dist/modes/interactive/components/oauth-selector.d.ts.map +1 -1
  1146. package/dist/modes/interactive/components/oauth-selector.js +16 -32
  1147. package/dist/modes/interactive/components/oauth-selector.js.map +1 -1
  1148. package/dist/modes/interactive/components/profile-resource-editor.d.ts +3 -4
  1149. package/dist/modes/interactive/components/profile-resource-editor.d.ts.map +1 -1
  1150. package/dist/modes/interactive/components/profile-resource-editor.js +34 -93
  1151. package/dist/modes/interactive/components/profile-resource-editor.js.map +1 -1
  1152. package/dist/modes/interactive/components/profile-selector.d.ts.map +1 -1
  1153. package/dist/modes/interactive/components/profile-selector.js +0 -1
  1154. package/dist/modes/interactive/components/profile-selector.js.map +1 -1
  1155. package/dist/modes/interactive/components/scoped-models-selector.d.ts +3 -4
  1156. package/dist/modes/interactive/components/scoped-models-selector.d.ts.map +1 -1
  1157. package/dist/modes/interactive/components/scoped-models-selector.js +34 -79
  1158. package/dist/modes/interactive/components/scoped-models-selector.js.map +1 -1
  1159. package/dist/modes/interactive/components/selector-list.d.ts +63 -0
  1160. package/dist/modes/interactive/components/selector-list.d.ts.map +1 -0
  1161. package/dist/modes/interactive/components/selector-list.js +186 -0
  1162. package/dist/modes/interactive/components/selector-list.js.map +1 -0
  1163. package/dist/modes/interactive/components/session-selector-search.d.ts.map +1 -1
  1164. package/dist/modes/interactive/components/session-selector-search.js.map +1 -1
  1165. package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
  1166. package/dist/modes/interactive/components/session-selector.js +34 -59
  1167. package/dist/modes/interactive/components/session-selector.js.map +1 -1
  1168. package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
  1169. package/dist/modes/interactive/components/settings-selector.js +40 -138
  1170. package/dist/modes/interactive/components/settings-selector.js.map +1 -1
  1171. package/dist/modes/interactive/components/show-images-selector.d.ts +2 -4
  1172. package/dist/modes/interactive/components/show-images-selector.d.ts.map +1 -1
  1173. package/dist/modes/interactive/components/show-images-selector.js +9 -28
  1174. package/dist/modes/interactive/components/show-images-selector.js.map +1 -1
  1175. package/dist/modes/interactive/components/skill-invocation-message.d.ts +3 -8
  1176. package/dist/modes/interactive/components/skill-invocation-message.d.ts.map +1 -1
  1177. package/dist/modes/interactive/components/skill-invocation-message.js +12 -40
  1178. package/dist/modes/interactive/components/skill-invocation-message.js.map +1 -1
  1179. package/dist/modes/interactive/components/theme-selector.d.ts +2 -5
  1180. package/dist/modes/interactive/components/theme-selector.d.ts.map +1 -1
  1181. package/dist/modes/interactive/components/theme-selector.js +11 -37
  1182. package/dist/modes/interactive/components/theme-selector.js.map +1 -1
  1183. package/dist/modes/interactive/components/thinking-selector.d.ts +2 -4
  1184. package/dist/modes/interactive/components/thinking-selector.d.ts.map +1 -1
  1185. package/dist/modes/interactive/components/thinking-selector.js +9 -31
  1186. package/dist/modes/interactive/components/thinking-selector.js.map +1 -1
  1187. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  1188. package/dist/modes/interactive/components/tool-execution.js +9 -28
  1189. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  1190. package/dist/modes/interactive/components/tool-group.d.ts.map +1 -1
  1191. package/dist/modes/interactive/components/tool-group.js +2 -3
  1192. package/dist/modes/interactive/components/tool-group.js.map +1 -1
  1193. package/dist/modes/interactive/components/tool-panel-registry.d.ts.map +1 -1
  1194. package/dist/modes/interactive/components/tool-panel-registry.js +5 -3
  1195. package/dist/modes/interactive/components/tool-panel-registry.js.map +1 -1
  1196. package/dist/modes/interactive/components/tool-title.d.ts.map +1 -1
  1197. package/dist/modes/interactive/components/tool-title.js +0 -4
  1198. package/dist/modes/interactive/components/tool-title.js.map +1 -1
  1199. package/dist/modes/interactive/components/transcript-pager.d.ts +26 -0
  1200. package/dist/modes/interactive/components/transcript-pager.d.ts.map +1 -0
  1201. package/dist/modes/interactive/components/transcript-pager.js +81 -0
  1202. package/dist/modes/interactive/components/transcript-pager.js.map +1 -0
  1203. package/dist/modes/interactive/components/tree-selector.d.ts +1 -12
  1204. package/dist/modes/interactive/components/tree-selector.d.ts.map +1 -1
  1205. package/dist/modes/interactive/components/tree-selector.js +42 -402
  1206. package/dist/modes/interactive/components/tree-selector.js.map +1 -1
  1207. package/dist/modes/interactive/components/trust-selector.d.ts.map +1 -1
  1208. package/dist/modes/interactive/components/trust-selector.js +4 -16
  1209. package/dist/modes/interactive/components/trust-selector.js.map +1 -1
  1210. package/dist/modes/interactive/components/usage-action-selector.d.ts.map +1 -1
  1211. package/dist/modes/interactive/components/usage-action-selector.js +2 -10
  1212. package/dist/modes/interactive/components/usage-action-selector.js.map +1 -1
  1213. package/dist/modes/interactive/components/user-message-selector.d.ts.map +1 -1
  1214. package/dist/modes/interactive/components/user-message-selector.js +3 -6
  1215. package/dist/modes/interactive/components/user-message-selector.js.map +1 -1
  1216. package/dist/modes/interactive/components/user-message.d.ts.map +1 -1
  1217. package/dist/modes/interactive/components/user-message.js +0 -1
  1218. package/dist/modes/interactive/components/user-message.js.map +1 -1
  1219. package/dist/modes/interactive/components/visual-truncate.d.ts.map +1 -1
  1220. package/dist/modes/interactive/components/visual-truncate.js.map +1 -1
  1221. package/dist/modes/interactive/config-backup.d.ts.map +1 -1
  1222. package/dist/modes/interactive/config-backup.js.map +1 -1
  1223. package/dist/modes/interactive/editor-overlay-host.d.ts.map +1 -1
  1224. package/dist/modes/interactive/editor-overlay-host.js +0 -3
  1225. package/dist/modes/interactive/editor-overlay-host.js.map +1 -1
  1226. package/dist/modes/interactive/extension-ui-host.d.ts +2 -0
  1227. package/dist/modes/interactive/extension-ui-host.d.ts.map +1 -1
  1228. package/dist/modes/interactive/extension-ui-host.js +51 -72
  1229. package/dist/modes/interactive/extension-ui-host.js.map +1 -1
  1230. package/dist/modes/interactive/external-editor.d.ts.map +1 -1
  1231. package/dist/modes/interactive/external-editor.js +2 -15
  1232. package/dist/modes/interactive/external-editor.js.map +1 -1
  1233. package/dist/modes/interactive/history-reload-math.d.ts.map +1 -1
  1234. package/dist/modes/interactive/history-reload-math.js.map +1 -1
  1235. package/dist/modes/interactive/interactive-event-controller.d.ts.map +1 -1
  1236. package/dist/modes/interactive/interactive-event-controller.js +23 -16
  1237. package/dist/modes/interactive/interactive-event-controller.js.map +1 -1
  1238. package/dist/modes/interactive/interactive-mode.d.ts +13 -4
  1239. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  1240. package/dist/modes/interactive/interactive-mode.js +123 -204
  1241. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  1242. package/dist/modes/interactive/interactive-selection-prompts.d.ts +20 -0
  1243. package/dist/modes/interactive/interactive-selection-prompts.d.ts.map +1 -0
  1244. package/dist/modes/interactive/interactive-selection-prompts.js +43 -0
  1245. package/dist/modes/interactive/interactive-selection-prompts.js.map +1 -0
  1246. package/dist/modes/interactive/key-handlers.d.ts +2 -1
  1247. package/dist/modes/interactive/key-handlers.d.ts.map +1 -1
  1248. package/dist/modes/interactive/key-handlers.js +4 -2
  1249. package/dist/modes/interactive/key-handlers.js.map +1 -1
  1250. package/dist/modes/interactive/loaded-resources-view.d.ts.map +1 -1
  1251. package/dist/modes/interactive/loaded-resources-view.js.map +1 -1
  1252. package/dist/modes/interactive/local-model-commands.d.ts.map +1 -1
  1253. package/dist/modes/interactive/local-model-commands.js +4 -9
  1254. package/dist/modes/interactive/local-model-commands.js.map +1 -1
  1255. package/dist/modes/interactive/model-fitness-presentation.d.ts +21 -0
  1256. package/dist/modes/interactive/model-fitness-presentation.d.ts.map +1 -0
  1257. package/dist/modes/interactive/model-fitness-presentation.js +13 -0
  1258. package/dist/modes/interactive/model-fitness-presentation.js.map +1 -0
  1259. package/dist/modes/interactive/profile-menu-controller.d.ts +2 -0
  1260. package/dist/modes/interactive/profile-menu-controller.d.ts.map +1 -1
  1261. package/dist/modes/interactive/profile-menu-controller.js +79 -171
  1262. package/dist/modes/interactive/profile-menu-controller.js.map +1 -1
  1263. package/dist/modes/interactive/report-commands.d.ts +2 -0
  1264. package/dist/modes/interactive/report-commands.d.ts.map +1 -1
  1265. package/dist/modes/interactive/report-commands.js +12 -6
  1266. package/dist/modes/interactive/report-commands.js.map +1 -1
  1267. package/dist/modes/interactive/resource-display.d.ts.map +1 -1
  1268. package/dist/modes/interactive/resource-display.js.map +1 -1
  1269. package/dist/modes/interactive/resource-shell-commands.d.ts.map +1 -1
  1270. package/dist/modes/interactive/resource-shell-commands.js +6 -23
  1271. package/dist/modes/interactive/resource-shell-commands.js.map +1 -1
  1272. package/dist/modes/interactive/session-flow-commands.d.ts.map +1 -1
  1273. package/dist/modes/interactive/session-flow-commands.js +21 -25
  1274. package/dist/modes/interactive/session-flow-commands.js.map +1 -1
  1275. package/dist/modes/interactive/session-io-commands.d.ts.map +1 -1
  1276. package/dist/modes/interactive/session-io-commands.js.map +1 -1
  1277. package/dist/modes/interactive/session-replacement-errors.d.ts.map +1 -1
  1278. package/dist/modes/interactive/session-replacement-errors.js.map +1 -1
  1279. package/dist/modes/interactive/settings-selector-flow.d.ts.map +1 -1
  1280. package/dist/modes/interactive/settings-selector-flow.js.map +1 -1
  1281. package/dist/modes/interactive/signal-lifecycle.d.ts.map +1 -1
  1282. package/dist/modes/interactive/signal-lifecycle.js.map +1 -1
  1283. package/dist/modes/interactive/startup-checks.d.ts.map +1 -1
  1284. package/dist/modes/interactive/startup-checks.js +12 -8
  1285. package/dist/modes/interactive/startup-checks.js.map +1 -1
  1286. package/dist/modes/interactive/theme/theme.d.ts.map +1 -1
  1287. package/dist/modes/interactive/theme/theme.js +10 -76
  1288. package/dist/modes/interactive/theme/theme.js.map +1 -1
  1289. package/dist/modes/interactive/usage-commands.d.ts.map +1 -1
  1290. package/dist/modes/interactive/usage-commands.js.map +1 -1
  1291. package/dist/modes/print-mode.d.ts.map +1 -1
  1292. package/dist/modes/print-mode.js +5 -22
  1293. package/dist/modes/print-mode.js.map +1 -1
  1294. package/dist/modes/rpc/jsonl.d.ts.map +1 -1
  1295. package/dist/modes/rpc/jsonl.js +1 -1
  1296. package/dist/modes/rpc/jsonl.js.map +1 -1
  1297. package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
  1298. package/dist/modes/rpc/rpc-client.js +7 -8
  1299. package/dist/modes/rpc/rpc-client.js.map +1 -1
  1300. package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
  1301. package/dist/modes/rpc/rpc-mode.js +5 -20
  1302. package/dist/modes/rpc/rpc-mode.js.map +1 -1
  1303. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  1304. package/dist/modes/rpc/rpc-types.js.map +1 -1
  1305. package/dist/modes/termination-signals.d.ts +4 -0
  1306. package/dist/modes/termination-signals.d.ts.map +1 -0
  1307. package/dist/modes/termination-signals.js +21 -0
  1308. package/dist/modes/termination-signals.js.map +1 -0
  1309. package/dist/package-manager-cli.d.ts.map +1 -1
  1310. package/dist/package-manager-cli.js.map +1 -1
  1311. package/dist/utils/ansi-colors.d.ts +5 -0
  1312. package/dist/utils/ansi-colors.d.ts.map +1 -0
  1313. package/dist/utils/ansi-colors.js +38 -0
  1314. package/dist/utils/ansi-colors.js.map +1 -0
  1315. package/dist/utils/ansi.d.ts.map +1 -1
  1316. package/dist/utils/ansi.js.map +1 -1
  1317. package/dist/utils/changelog.d.ts.map +1 -1
  1318. package/dist/utils/changelog.js.map +1 -1
  1319. package/dist/utils/child-process.d.ts.map +1 -1
  1320. package/dist/utils/child-process.js.map +1 -1
  1321. package/dist/utils/clipboard-image.d.ts.map +1 -1
  1322. package/dist/utils/clipboard-image.js.map +1 -1
  1323. package/dist/utils/clipboard-native.d.ts.map +1 -1
  1324. package/dist/utils/clipboard-native.js.map +1 -1
  1325. package/dist/utils/clipboard.d.ts.map +1 -1
  1326. package/dist/utils/clipboard.js.map +1 -1
  1327. package/dist/utils/deprecation.d.ts.map +1 -1
  1328. package/dist/utils/deprecation.js.map +1 -1
  1329. package/dist/utils/exif-orientation.d.ts.map +1 -1
  1330. package/dist/utils/exif-orientation.js.map +1 -1
  1331. package/dist/utils/external-editor-command.d.ts.map +1 -1
  1332. package/dist/utils/external-editor-command.js.map +1 -1
  1333. package/dist/utils/frontmatter.d.ts.map +1 -1
  1334. package/dist/utils/frontmatter.js.map +1 -1
  1335. package/dist/utils/fs-watch.d.ts.map +1 -1
  1336. package/dist/utils/fs-watch.js.map +1 -1
  1337. package/dist/utils/git.d.ts.map +1 -1
  1338. package/dist/utils/git.js +20 -28
  1339. package/dist/utils/git.js.map +1 -1
  1340. package/dist/utils/highlight-js-languages.d.ts.map +1 -1
  1341. package/dist/utils/html.d.ts.map +1 -1
  1342. package/dist/utils/html.js.map +1 -1
  1343. package/dist/utils/image-convert.d.ts.map +1 -1
  1344. package/dist/utils/image-convert.js.map +1 -1
  1345. package/dist/utils/image-resize-core.d.ts.map +1 -1
  1346. package/dist/utils/image-resize-core.js.map +1 -1
  1347. package/dist/utils/image-resize-worker.d.ts.map +1 -1
  1348. package/dist/utils/image-resize-worker.js.map +1 -1
  1349. package/dist/utils/image-resize.d.ts.map +1 -1
  1350. package/dist/utils/image-resize.js.map +1 -1
  1351. package/dist/utils/json.d.ts.map +1 -1
  1352. package/dist/utils/json.js.map +1 -1
  1353. package/dist/utils/mime.d.ts.map +1 -1
  1354. package/dist/utils/mime.js.map +1 -1
  1355. package/dist/utils/open-browser.d.ts.map +1 -1
  1356. package/dist/utils/open-browser.js.map +1 -1
  1357. package/dist/utils/paths.d.ts.map +1 -1
  1358. package/dist/utils/paths.js.map +1 -1
  1359. package/dist/utils/photon.d.ts.map +1 -1
  1360. package/dist/utils/photon.js.map +1 -1
  1361. package/dist/utils/pi-user-agent.d.ts.map +1 -1
  1362. package/dist/utils/pi-user-agent.js.map +1 -1
  1363. package/dist/utils/platform.d.ts.map +1 -1
  1364. package/dist/utils/platform.js.map +1 -1
  1365. package/dist/utils/process-memory.d.ts.map +1 -1
  1366. package/dist/utils/process-memory.js.map +1 -1
  1367. package/dist/utils/safe-write-stream.d.ts.map +1 -1
  1368. package/dist/utils/safe-write-stream.js.map +1 -1
  1369. package/dist/utils/shell.d.ts.map +1 -1
  1370. package/dist/utils/shell.js.map +1 -1
  1371. package/dist/utils/sleep.d.ts.map +1 -1
  1372. package/dist/utils/sleep.js +2 -15
  1373. package/dist/utils/sleep.js.map +1 -1
  1374. package/dist/utils/stdin-events.d.ts +8 -0
  1375. package/dist/utils/stdin-events.d.ts.map +1 -0
  1376. package/dist/utils/stdin-events.js +19 -0
  1377. package/dist/utils/stdin-events.js.map +1 -0
  1378. package/dist/utils/syntax-highlight.d.ts.map +1 -1
  1379. package/dist/utils/syntax-highlight.js +20 -13
  1380. package/dist/utils/syntax-highlight.js.map +1 -1
  1381. package/dist/utils/tools-manager.d.ts.map +1 -1
  1382. package/dist/utils/tools-manager.js.map +1 -1
  1383. package/dist/utils/version-check.d.ts.map +1 -1
  1384. package/dist/utils/version-check.js.map +1 -1
  1385. package/dist/utils/windows-self-update.d.ts.map +1 -1
  1386. package/dist/utils/windows-self-update.js.map +1 -1
  1387. package/dist/utils/work-directory.d.ts.map +1 -1
  1388. package/dist/utils/work-directory.js.map +1 -1
  1389. package/docs/compaction.md +11 -3
  1390. package/docs/sessions.md +6 -0
  1391. package/docs/settings.md +1 -1
  1392. package/docs/windows.md +26 -1
  1393. package/docs/work-directory.md +9 -1
  1394. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  1395. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  1396. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  1397. package/examples/extensions/sandbox/package-lock.json +2 -2
  1398. package/examples/extensions/sandbox/package.json +1 -1
  1399. package/examples/extensions/with-deps/package-lock.json +2 -2
  1400. package/examples/extensions/with-deps/package.json +1 -1
  1401. package/npm-shrinkwrap.json +16 -16
  1402. package/package.json +10 -10
  1403. package/dist/utils/streaming-lines.d.ts +0 -20
  1404. package/dist/utils/streaming-lines.d.ts.map +0 -1
  1405. package/dist/utils/streaming-lines.js +0 -79
  1406. package/dist/utils/streaming-lines.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"bash-execution-controller.d.ts","sourceRoot":"","sources":["../../src/core/bash-execution-controller.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,KAAK,EAAE,KAAK,EAAwB,MAAM,2BAA2B,CAAC;AAC7E,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,gCAAgC,CAAC;AACrE,OAAO,EAAE,KAAK,UAAU,EAA6B,MAAM,oBAAoB,CAAC;AAChF,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAC7D,OAAO,EAAE,KAAK,cAAc,EAAoE,MAAM,iBAAiB,CAAC;AAExH,MAAM,WAAW,2BAA2B;IAC3C,QAAQ,IAAI,KAAK,CAAC;IAClB,iBAAiB,IAAI,cAAc,CAAC;IACpC,kBAAkB,IAAI,eAAe,CAAC;IACtC,yFAAuF;IACvF,WAAW,IAAI,OAAO,CAAC;IACvB,kGAAgG;IAChG,kBAAkB,CAAC,IAAI,MAAM,CAAC;CAC9B;AAED,MAAM,WAAW,oBAAoB;IACpC,kBAAkB,CAAC,EAAE,OAAO,CAAC;IAC7B,UAAU,CAAC,EAAE,cAAc,CAAC;IAC5B,kEAAkE;IAClE,QAAQ,CAAC,EAAE,MAAM,CAAC,QAAQ,CAAC;IAC3B,kFAAkF;IAClF,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,mGAAmG;IACnG,YAAY,CAAC,EAAE,OAAO,CAAC;CACvB;AAED,qBAAa,uBAAuB;IACnC,OAAO,CAAC,qBAAqB,CAA8B;IAC3D,OAAO,CAAC,oBAAoB,CAA8B;IAE1D,OAAO,CAAC,QAAQ,CAAC,IAAI,CAA8B;IAEnD,YAAY,IAAI,EAAE,2BAA2B,EAE5C;IAEK,WAAW,CAChB,OAAO,EAAE,MAAM,EACf,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,EACjC,OAAO,CAAC,EAAE,oBAAoB,GAC5B,OAAO,CAAC,UAAU,CAAC,CAgCrB;IAED;;;OAGG;IACH,gBAAgB,CAAC,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,UAAU,EAAE,OAAO,CAAC,EAAE;QAAE,kBAAkB,CAAC,EAAE,OAAO,CAAA;KAAE,GAAG,IAAI,CAwBtG;IAED;;OAEG;IACH,SAAS,IAAI,IAAI,CAIhB;IAED,kDAAkD;IAClD,IAAI,aAAa,IAAI,OAAO,CAE3B;IAED,oEAAoE;IACpE,IAAI,sBAAsB,IAAI,OAAO,CAEpC;IAED;;;OAGG;IACH,wBAAwB,IAAI,IAAI,CAY/B;CACD","sourcesContent":["/**\n * Standalone bash-command execution (the `/bash` path + extension-driven bash).\n *\n * Extracted verbatim from agent-session.ts (god-file decomposition). Owns the bash abort controller\n * and the pending-message queue that defers appending a bash result while the agent is streaming (so\n * tool_use/tool_result ordering is never broken); the deferred messages are flushed by the session on\n * agent turn completion. Persists results through the session log via deps.\n */\n\nimport type { Agent, BashExecutionMessage } from \"@caupulican/pi-agent-core\";\nimport type { SessionManager } from \"@caupulican/pi-agent-core/node\";\nimport { type BashResult, executeBashWithOperations } from \"./bash-executor.ts\";\nimport type { SettingsManager } from \"./settings-manager.ts\";\nimport { type BashOperations, createLocalPlatformShellOperations, resolveCommandTimeoutSeconds } from \"./tools/bash.ts\";\n\nexport interface BashExecutionControllerDeps {\n\tgetAgent(): Agent;\n\tgetSessionManager(): SessionManager;\n\tgetSettingsManager(): SettingsManager;\n\t/** Whether the agent is currently streaming — defers appending a bash result if so. */\n\tisStreaming(): boolean;\n\t/** Per-agent persistent shell session key — user `!` commands share the agent's shell state. */\n\tgetShellSessionKey?(): string;\n}\n\nexport interface BashExecutionOptions {\n\texcludeFromContext?: boolean;\n\toperations?: BashOperations;\n\t/** Injectable target platform for tests and embedded runtimes. */\n\tplatform?: NodeJS.Platform;\n\t/** Wall-clock timeout in seconds; non-positive values use the bounded default. */\n\ttimeout?: number;\n\t/** Route complex/state-mutating Bash constructs to the Python engine on Windows. Default: true. */\n\tpythonEngine?: boolean;\n}\n\nexport class BashExecutionController {\n\tprivate _bashAbortControllers = new Set<AbortController>();\n\tprivate _pendingBashMessages: BashExecutionMessage[] = [];\n\n\tprivate readonly deps: BashExecutionControllerDeps;\n\n\tconstructor(deps: BashExecutionControllerDeps) {\n\t\tthis.deps = deps;\n\t}\n\n\tasync executeBash(\n\t\tcommand: string,\n\t\tonChunk?: (chunk: string) => void,\n\t\toptions?: BashExecutionOptions,\n\t): Promise<BashResult> {\n\t\tconst abortController = new AbortController();\n\t\tthis._bashAbortControllers.add(abortController);\n\n\t\tconst commandPrefix = this.deps.getSettingsManager().getShellCommandPrefix();\n\t\tconst shellPath = this.deps.getSettingsManager().getShellPath();\n\t\tconst platform = options?.platform ?? process.platform;\n\t\tconst enableGitFilter = !options?.operations && !commandPrefix && !shellPath;\n\t\tconst operations = createLocalPlatformShellOperations(\n\t\t\t{\n\t\t\t\tshellPath,\n\t\t\t\tcommandPrefix,\n\t\t\t\toperations: options?.operations,\n\t\t\t\tsessionKey: this.deps.getShellSessionKey?.(),\n\t\t\t\tpythonEngine: options?.pythonEngine,\n\t\t\t},\n\t\t\tplatform,\n\t\t);\n\n\t\ttry {\n\t\t\tconst result = await executeBashWithOperations(command, this.deps.getSessionManager().getCwd(), operations, {\n\t\t\t\tonChunk,\n\t\t\t\tsignal: abortController.signal,\n\t\t\t\tenableGitFilter,\n\t\t\t\ttimeout: resolveCommandTimeoutSeconds(options?.timeout),\n\t\t\t});\n\n\t\t\tthis.recordBashResult(command, result, options);\n\t\t\treturn result;\n\t\t} finally {\n\t\t\tthis._bashAbortControllers.delete(abortController);\n\t\t}\n\t}\n\n\t/**\n\t * Record a bash execution result in session history.\n\t * Used by executeBash and by extensions that handle bash execution themselves.\n\t */\n\trecordBashResult(command: string, result: BashResult, options?: { excludeFromContext?: boolean }): void {\n\t\tconst bashMessage: BashExecutionMessage = {\n\t\t\trole: \"bashExecution\",\n\t\t\tcommand,\n\t\t\toutput: result.output,\n\t\t\texitCode: result.exitCode,\n\t\t\tcancelled: result.cancelled,\n\t\t\ttruncated: result.truncated,\n\t\t\tfullOutputPath: result.fullOutputPath,\n\t\t\ttimestamp: Date.now(),\n\t\t\texcludeFromContext: options?.excludeFromContext,\n\t\t};\n\n\t\t// If agent is streaming, defer adding to avoid breaking tool_use/tool_result ordering\n\t\tif (this.deps.isStreaming()) {\n\t\t\t// Queue for later - will be flushed on agent_end\n\t\t\tthis._pendingBashMessages.push(bashMessage);\n\t\t} else {\n\t\t\t// Add to agent state immediately\n\t\t\tthis.deps.getAgent().state.messages.push(bashMessage);\n\n\t\t\t// Save to session\n\t\t\tthis.deps.getSessionManager().appendMessage(bashMessage);\n\t\t}\n\t}\n\n\t/**\n\t * Cancel running bash command.\n\t */\n\tabortBash(): void {\n\t\tfor (const controller of this._bashAbortControllers) {\n\t\t\tcontroller.abort();\n\t\t}\n\t}\n\n\t/** Whether a bash command is currently running */\n\tget isBashRunning(): boolean {\n\t\treturn this._bashAbortControllers.size > 0;\n\t}\n\n\t/** Whether there are pending bash messages waiting to be flushed */\n\tget hasPendingBashMessages(): boolean {\n\t\treturn this._pendingBashMessages.length > 0;\n\t}\n\n\t/**\n\t * Flush pending bash messages to agent state and session.\n\t * Called after agent turn completes to maintain proper message ordering.\n\t */\n\tflushPendingBashMessages(): void {\n\t\tif (this._pendingBashMessages.length === 0) return;\n\n\t\tfor (const bashMessage of this._pendingBashMessages) {\n\t\t\t// Add to agent state\n\t\t\tthis.deps.getAgent().state.messages.push(bashMessage);\n\n\t\t\t// Save to session\n\t\t\tthis.deps.getSessionManager().appendMessage(bashMessage);\n\t\t}\n\n\t\tthis._pendingBashMessages = [];\n\t}\n}\n"]}
1
+ {"version":3,"file":"bash-execution-controller.d.ts","sourceRoot":"","sources":["../../src/core/bash-execution-controller.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAGH,OAAO,KAAK,EAAE,KAAK,EAAwB,MAAM,2BAA2B,CAAC;AAC7E,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,gCAAgC,CAAC;AACrE,OAAO,EAAE,KAAK,UAAU,EAA6B,MAAM,oBAAoB,CAAC;AAChF,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAC7D,OAAO,EAAE,KAAK,cAAc,EAAoE,MAAM,iBAAiB,CAAC;AAExH,MAAM,WAAW,2BAA2B;IAC3C,QAAQ,IAAI,KAAK,CAAC;IAClB,iBAAiB,IAAI,cAAc,CAAC;IACpC,kBAAkB,IAAI,eAAe,CAAC;IACtC,uFAAuF;IACvF,WAAW,IAAI,OAAO,CAAC;IACvB,gGAAgG;IAChG,kBAAkB,CAAC,IAAI,MAAM,CAAC;CAC9B;AAED,MAAM,WAAW,oBAAoB;IACpC,kBAAkB,CAAC,EAAE,OAAO,CAAC;IAC7B,UAAU,CAAC,EAAE,cAAc,CAAC;IAC5B,kEAAkE;IAClE,QAAQ,CAAC,EAAE,MAAM,CAAC,QAAQ,CAAC;IAC3B,kFAAkF;IAClF,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,mGAAmG;IACnG,YAAY,CAAC,EAAE,OAAO,CAAC;CACvB;AAED,qBAAa,uBAAuB;IACnC,OAAO,CAAC,qBAAqB,CAA8B;IAC3D,OAAO,CAAC,oBAAoB,CAA8B;IAC1D,OAAO,CAAC,QAAQ,CAAC,eAAe,CAAS;IAEzC,OAAO,CAAC,QAAQ,CAAC,IAAI,CAA8B;IAEnD,YAAY,IAAI,EAAE,2BAA2B,EAG5C;IAEK,WAAW,CAChB,OAAO,EAAE,MAAM,EACf,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,EACjC,OAAO,CAAC,EAAE,oBAAoB,GAC5B,OAAO,CAAC,UAAU,CAAC,CAgCrB;IAED;;;OAGG;IACH,gBAAgB,CAAC,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,UAAU,EAAE,OAAO,CAAC,EAAE;QAAE,kBAAkB,CAAC,EAAE,OAAO,CAAA;KAAE,GAAG,IAAI,CAwBtG;IAED;;OAEG;IACH,SAAS,IAAI,IAAI,CAIhB;IAED,kDAAkD;IAClD,IAAI,aAAa,IAAI,OAAO,CAE3B;IAED,oEAAoE;IACpE,IAAI,sBAAsB,IAAI,OAAO,CAEpC;IAED;;;OAGG;IACH,wBAAwB,IAAI,IAAI,CAY/B;CACD"}
@@ -6,14 +6,15 @@
6
6
  * tool_use/tool_result ordering is never broken); the deferred messages are flushed by the session on
7
7
  * agent turn completion. Persists results through the session log via deps.
8
8
  */
9
+ import { randomUUID } from "node:crypto";
9
10
  import { executeBashWithOperations } from "./bash-executor.js";
10
11
  import { createLocalPlatformShellOperations, resolveCommandTimeoutSeconds } from "./tools/bash.js";
11
12
  export class BashExecutionController {
12
- _bashAbortControllers = new Set();
13
- _pendingBashMessages = [];
14
- deps;
15
13
  constructor(deps) {
14
+ this._bashAbortControllers = new Set();
15
+ this._pendingBashMessages = [];
16
16
  this.deps = deps;
17
+ this.shellSessionKey = deps.getShellSessionKey?.() ?? `bash-controller:${randomUUID()}`;
17
18
  }
18
19
  async executeBash(command, onChunk, options) {
19
20
  const abortController = new AbortController();
@@ -26,7 +27,7 @@ export class BashExecutionController {
26
27
  shellPath,
27
28
  commandPrefix,
28
29
  operations: options?.operations,
29
- sessionKey: this.deps.getShellSessionKey?.(),
30
+ sessionKey: this.shellSessionKey,
30
31
  pythonEngine: options?.pythonEngine,
31
32
  }, platform);
32
33
  try {
@@ -1 +1 @@
1
- {"version":3,"file":"bash-execution-controller.js","sourceRoot":"","sources":["../../src/core/bash-execution-controller.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAIH,OAAO,EAAmB,yBAAyB,EAAE,MAAM,oBAAoB,CAAC;AAEhF,OAAO,EAAuB,kCAAkC,EAAE,4BAA4B,EAAE,MAAM,iBAAiB,CAAC;AAuBxH,MAAM,OAAO,uBAAuB;IAC3B,qBAAqB,GAAG,IAAI,GAAG,EAAmB,CAAC;IACnD,oBAAoB,GAA2B,EAAE,CAAC;IAEzC,IAAI,CAA8B;IAEnD,YAAY,IAAiC,EAAE;QAC9C,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IAAA,CACjB;IAED,KAAK,CAAC,WAAW,CAChB,OAAe,EACf,OAAiC,EACjC,OAA8B,EACR;QACtB,MAAM,eAAe,GAAG,IAAI,eAAe,EAAE,CAAC;QAC9C,IAAI,CAAC,qBAAqB,CAAC,GAAG,CAAC,eAAe,CAAC,CAAC;QAEhD,MAAM,aAAa,GAAG,IAAI,CAAC,IAAI,CAAC,kBAAkB,EAAE,CAAC,qBAAqB,EAAE,CAAC;QAC7E,MAAM,SAAS,GAAG,IAAI,CAAC,IAAI,CAAC,kBAAkB,EAAE,CAAC,YAAY,EAAE,CAAC;QAChE,MAAM,QAAQ,GAAG,OAAO,EAAE,QAAQ,IAAI,OAAO,CAAC,QAAQ,CAAC;QACvD,MAAM,eAAe,GAAG,CAAC,OAAO,EAAE,UAAU,IAAI,CAAC,aAAa,IAAI,CAAC,SAAS,CAAC;QAC7E,MAAM,UAAU,GAAG,kCAAkC,CACpD;YAC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W,CAAC,CAAC;QAC7C,CAAC;aAAM,CAAC;YACP,iCAAiC;YACjC,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,CAAC,KAAK,CAAC,QAAQ,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;YAEtD,kBAAkB;YAClB,IAAI,CAAC,IAAI,CAAC,iBAAiB,EAAE,CAAC,aAAa,CAAC,WAAW,CAAC,CAAC;QAC1D,CAAC;IAAA,CACD;IAED;;OAEG;IACH,SAAS,GAAS;QACjB,KAAK,MAAM,UAAU,IAAI,IAAI,CAAC,qBAAqB,EAAE,CAAC;YACrD,UAAU,CAAC,KAAK,EAAE,CAAC;QACpB,CAAC;IAAA,CACD;IAED,kDAAkD;IAClD,IAAI,aAAa,GAAY;QAC5B,OAAO,IAAI,CAAC,qBAAqB,CAAC,IAAI,GAAG,CAAC,CAAC;IAAA,CAC3C;IAED,oEAAoE;IACpE,IAAI,sBAAsB,GAAY;QACrC,OAAO,IAAI,CAAC,oBAAoB,CAAC,MAAM,GAAG,CAAC,CAAC;IAAA,CAC5C;IAED;;;OAGG;IACH,wBAAwB,GAAS;QAChC,IAAI,IAAI,CAAC,oBAAoB,CAAC,MAAM,KAAK,CAAC;YAAE,OAAO;QAEnD,KAAK,MAAM,WAAW,IAAI,IAAI,CAAC,oBAAoB,EAAE,CAAC;YACrD,qBAAqB;YACrB,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,CAAC,KAAK,CAAC,QAAQ,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;YAEtD,kBAAkB;YAClB,IAAI,CAAC,IAAI,CAAC,iBAAiB,EAAE,CAAC,aAAa,CAAC,WAAW,CAAC,CAAC;QAC1D,CAAC;QAED,IAAI,CAAC,oBAAoB,GAAG,EAAE,CAAC;IAAA,CAC/B;CACD","sourcesContent":["/**\n * Standalone bash-command execution (the `/bash` path + extension-driven bash).\n *\n * Extracted verbatim from agent-session.ts (god-file decomposition). Owns the bash abort controller\n * and the pending-message queue that defers appending a bash result while the agent is streaming (so\n * tool_use/tool_result ordering is never broken); the deferred messages are flushed by the session on\n * agent turn completion. Persists results through the session log via deps.\n */\n\nimport type { Agent, BashExecutionMessage } from \"@caupulican/pi-agent-core\";\nimport type { SessionManager } from \"@caupulican/pi-agent-core/node\";\nimport { type BashResult, executeBashWithOperations } from \"./bash-executor.ts\";\nimport type { SettingsManager } from \"./settings-manager.ts\";\nimport { type BashOperations, createLocalPlatformShellOperations, resolveCommandTimeoutSeconds } from \"./tools/bash.ts\";\n\nexport interface BashExecutionControllerDeps {\n\tgetAgent(): Agent;\n\tgetSessionManager(): SessionManager;\n\tgetSettingsManager(): SettingsManager;\n\t/** Whether the agent is currently streaming — defers appending a bash result if so. */\n\tisStreaming(): boolean;\n\t/** Per-agent persistent shell session key — user `!` commands share the agent's shell state. */\n\tgetShellSessionKey?(): string;\n}\n\nexport interface BashExecutionOptions {\n\texcludeFromContext?: boolean;\n\toperations?: BashOperations;\n\t/** Injectable target platform for tests and embedded runtimes. */\n\tplatform?: NodeJS.Platform;\n\t/** Wall-clock timeout in seconds; non-positive values use the bounded default. */\n\ttimeout?: number;\n\t/** Route complex/state-mutating Bash constructs to the Python engine on Windows. Default: true. */\n\tpythonEngine?: boolean;\n}\n\nexport class BashExecutionController {\n\tprivate _bashAbortControllers = new Set<AbortController>();\n\tprivate _pendingBashMessages: BashExecutionMessage[] = [];\n\n\tprivate readonly deps: BashExecutionControllerDeps;\n\n\tconstructor(deps: BashExecutionControllerDeps) {\n\t\tthis.deps = deps;\n\t}\n\n\tasync executeBash(\n\t\tcommand: string,\n\t\tonChunk?: (chunk: string) => void,\n\t\toptions?: BashExecutionOptions,\n\t): Promise<BashResult> {\n\t\tconst abortController = new AbortController();\n\t\tthis._bashAbortControllers.add(abortController);\n\n\t\tconst commandPrefix = this.deps.getSettingsManager().getShellCommandPrefix();\n\t\tconst shellPath = this.deps.getSettingsManager().getShellPath();\n\t\tconst platform = options?.platform ?? process.platform;\n\t\tconst enableGitFilter = !options?.operations && !commandPrefix && !shellPath;\n\t\tconst operations = createLocalPlatformShellOperations(\n\t\t\t{\n\t\t\t\tshellPath,\n\t\t\t\tcommandPrefix,\n\t\t\t\toperations: options?.operations,\n\t\t\t\tsessionKey: this.deps.getShellSessionKey?.(),\n\t\t\t\tpythonEngine: options?.pythonEngine,\n\t\t\t},\n\t\t\tplatform,\n\t\t);\n\n\t\ttry {\n\t\t\tconst result = await executeBashWithOperations(command, this.deps.getSessionManager().getCwd(), operations, {\n\t\t\t\tonChunk,\n\t\t\t\tsignal: abortController.signal,\n\t\t\t\tenableGitFilter,\n\t\t\t\ttimeout: resolveCommandTimeoutSeconds(options?.timeout),\n\t\t\t});\n\n\t\t\tthis.recordBashResult(command, result, options);\n\t\t\treturn result;\n\t\t} finally {\n\t\t\tthis._bashAbortControllers.delete(abortController);\n\t\t}\n\t}\n\n\t/**\n\t * Record a bash execution result in session history.\n\t * Used by executeBash and by extensions that handle bash execution themselves.\n\t */\n\trecordBashResult(command: string, result: BashResult, options?: { excludeFromContext?: boolean }): void {\n\t\tconst bashMessage: BashExecutionMessage = {\n\t\t\trole: \"bashExecution\",\n\t\t\tcommand,\n\t\t\toutput: result.output,\n\t\t\texitCode: result.exitCode,\n\t\t\tcancelled: result.cancelled,\n\t\t\ttruncated: result.truncated,\n\t\t\tfullOutputPath: result.fullOutputPath,\n\t\t\ttimestamp: Date.now(),\n\t\t\texcludeFromContext: options?.excludeFromContext,\n\t\t};\n\n\t\t// If agent is streaming, defer adding to avoid breaking tool_use/tool_result ordering\n\t\tif (this.deps.isStreaming()) {\n\t\t\t// Queue for later - will be flushed on agent_end\n\t\t\tthis._pendingBashMessages.push(bashMessage);\n\t\t} else {\n\t\t\t// Add to agent state immediately\n\t\t\tthis.deps.getAgent().state.messages.push(bashMessage);\n\n\t\t\t// Save to session\n\t\t\tthis.deps.getSessionManager().appendMessage(bashMessage);\n\t\t}\n\t}\n\n\t/**\n\t * Cancel running bash command.\n\t */\n\tabortBash(): void {\n\t\tfor (const controller of this._bashAbortControllers) {\n\t\t\tcontroller.abort();\n\t\t}\n\t}\n\n\t/** Whether a bash command is currently running */\n\tget isBashRunning(): boolean {\n\t\treturn this._bashAbortControllers.size > 0;\n\t}\n\n\t/** Whether there are pending bash messages waiting to be flushed */\n\tget hasPendingBashMessages(): boolean {\n\t\treturn this._pendingBashMessages.length > 0;\n\t}\n\n\t/**\n\t * Flush pending bash messages to agent state and session.\n\t * Called after agent turn completes to maintain proper message ordering.\n\t */\n\tflushPendingBashMessages(): void {\n\t\tif (this._pendingBashMessages.length === 0) return;\n\n\t\tfor (const bashMessage of this._pendingBashMessages) {\n\t\t\t// Add to agent state\n\t\t\tthis.deps.getAgent().state.messages.push(bashMessage);\n\n\t\t\t// Save to session\n\t\t\tthis.deps.getSessionManager().appendMessage(bashMessage);\n\t\t}\n\n\t\tthis._pendingBashMessages = [];\n\t}\n}\n"]}
1
+ {"version":3,"file":"bash-execution-controller.js","sourceRoot":"","sources":["../../src/core/bash-execution-controller.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAGzC,OAAO,EAAmB,yBAAyB,EAAE,MAAM,oBAAoB,CAAC;AAEhF,OAAO,EAAuB,kCAAkC,EAAE,4BAA4B,EAAE,MAAM,iBAAiB,CAAC;AAuBxH,MAAM,OAAO,uBAAuB;IAOnC,YAAY,IAAiC;QANrC,0BAAqB,GAAG,IAAI,GAAG,EAAmB,CAAC;QACnD,yBAAoB,GAA2B,EAAE,CAAC;QAMzD,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,eAAe,GAAG,IAAI,CAAC,kBAAkB,EAAE,EAAE,IAAI,mBAAmB,UAAU,EAAE,EAAE,CAAC;IACzF,CAAC;IAED,KAAK,CAAC,WAAW,CAChB,OAAe,EACf,OAAiC,EACjC,OAA8B;QAE9B,MAAM,eAAe,GAAG,IAAI,eAAe,EAAE,CAAC;QAC9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I,CAAC,IAAI,CAAC,QAAQ,EAAE,CAAC,KAAK,CAAC,QAAQ,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;YAEtD,kBAAkB;YAClB,IAAI,CAAC,IAAI,CAAC,iBAAiB,EAAE,CAAC,aAAa,CAAC,WAAW,CAAC,CAAC;QAC1D,CAAC;QAED,IAAI,CAAC,oBAAoB,GAAG,EAAE,CAAC;IAChC,CAAC;CACD","sourcesContent":["/**\n * Standalone bash-command execution (the `/bash` path + extension-driven bash).\n *\n * Extracted verbatim from agent-session.ts (god-file decomposition). Owns the bash abort controller\n * and the pending-message queue that defers appending a bash result while the agent is streaming (so\n * tool_use/tool_result ordering is never broken); the deferred messages are flushed by the session on\n * agent turn completion. Persists results through the session log via deps.\n */\n\nimport { randomUUID } from \"node:crypto\";\nimport type { Agent, BashExecutionMessage } from \"@caupulican/pi-agent-core\";\nimport type { SessionManager } from \"@caupulican/pi-agent-core/node\";\nimport { type BashResult, executeBashWithOperations } from \"./bash-executor.ts\";\nimport type { SettingsManager } from \"./settings-manager.ts\";\nimport { type BashOperations, createLocalPlatformShellOperations, resolveCommandTimeoutSeconds } from \"./tools/bash.ts\";\n\nexport interface BashExecutionControllerDeps {\n\tgetAgent(): Agent;\n\tgetSessionManager(): SessionManager;\n\tgetSettingsManager(): SettingsManager;\n\t/** Whether the agent is currently streaming — defers appending a bash result if so. */\n\tisStreaming(): boolean;\n\t/** Per-agent persistent shell session key — user `!` commands share the agent's shell state. */\n\tgetShellSessionKey?(): string;\n}\n\nexport interface BashExecutionOptions {\n\texcludeFromContext?: boolean;\n\toperations?: BashOperations;\n\t/** Injectable target platform for tests and embedded runtimes. */\n\tplatform?: NodeJS.Platform;\n\t/** Wall-clock timeout in seconds; non-positive values use the bounded default. */\n\ttimeout?: number;\n\t/** Route complex/state-mutating Bash constructs to the Python engine on Windows. Default: true. */\n\tpythonEngine?: boolean;\n}\n\nexport class BashExecutionController {\n\tprivate _bashAbortControllers = new Set<AbortController>();\n\tprivate _pendingBashMessages: BashExecutionMessage[] = [];\n\tprivate readonly shellSessionKey: string;\n\n\tprivate readonly deps: BashExecutionControllerDeps;\n\n\tconstructor(deps: BashExecutionControllerDeps) {\n\t\tthis.deps = deps;\n\t\tthis.shellSessionKey = deps.getShellSessionKey?.() ?? `bash-controller:${randomUUID()}`;\n\t}\n\n\tasync executeBash(\n\t\tcommand: string,\n\t\tonChunk?: (chunk: string) => void,\n\t\toptions?: BashExecutionOptions,\n\t): Promise<BashResult> {\n\t\tconst abortController = new AbortController();\n\t\tthis._bashAbortControllers.add(abortController);\n\n\t\tconst commandPrefix = this.deps.getSettingsManager().getShellCommandPrefix();\n\t\tconst shellPath = this.deps.getSettingsManager().getShellPath();\n\t\tconst platform = options?.platform ?? process.platform;\n\t\tconst enableGitFilter = !options?.operations && !commandPrefix && !shellPath;\n\t\tconst operations = createLocalPlatformShellOperations(\n\t\t\t{\n\t\t\t\tshellPath,\n\t\t\t\tcommandPrefix,\n\t\t\t\toperations: options?.operations,\n\t\t\t\tsessionKey: this.shellSessionKey,\n\t\t\t\tpythonEngine: options?.pythonEngine,\n\t\t\t},\n\t\t\tplatform,\n\t\t);\n\n\t\ttry {\n\t\t\tconst result = await executeBashWithOperations(command, this.deps.getSessionManager().getCwd(), operations, {\n\t\t\t\tonChunk,\n\t\t\t\tsignal: abortController.signal,\n\t\t\t\tenableGitFilter,\n\t\t\t\ttimeout: resolveCommandTimeoutSeconds(options?.timeout),\n\t\t\t});\n\n\t\t\tthis.recordBashResult(command, result, options);\n\t\t\treturn result;\n\t\t} finally {\n\t\t\tthis._bashAbortControllers.delete(abortController);\n\t\t}\n\t}\n\n\t/**\n\t * Record a bash execution result in session history.\n\t * Used by executeBash and by extensions that handle bash execution themselves.\n\t */\n\trecordBashResult(command: string, result: BashResult, options?: { excludeFromContext?: boolean }): void {\n\t\tconst bashMessage: BashExecutionMessage = {\n\t\t\trole: \"bashExecution\",\n\t\t\tcommand,\n\t\t\toutput: result.output,\n\t\t\texitCode: result.exitCode,\n\t\t\tcancelled: result.cancelled,\n\t\t\ttruncated: result.truncated,\n\t\t\tfullOutputPath: result.fullOutputPath,\n\t\t\ttimestamp: Date.now(),\n\t\t\texcludeFromContext: options?.excludeFromContext,\n\t\t};\n\n\t\t// If agent is streaming, defer adding to avoid breaking tool_use/tool_result ordering\n\t\tif (this.deps.isStreaming()) {\n\t\t\t// Queue for later - will be flushed on agent_end\n\t\t\tthis._pendingBashMessages.push(bashMessage);\n\t\t} else {\n\t\t\t// Add to agent state immediately\n\t\t\tthis.deps.getAgent().state.messages.push(bashMessage);\n\n\t\t\t// Save to session\n\t\t\tthis.deps.getSessionManager().appendMessage(bashMessage);\n\t\t}\n\t}\n\n\t/**\n\t * Cancel running bash command.\n\t */\n\tabortBash(): void {\n\t\tfor (const controller of this._bashAbortControllers) {\n\t\t\tcontroller.abort();\n\t\t}\n\t}\n\n\t/** Whether a bash command is currently running */\n\tget isBashRunning(): boolean {\n\t\treturn this._bashAbortControllers.size > 0;\n\t}\n\n\t/** Whether there are pending bash messages waiting to be flushed */\n\tget hasPendingBashMessages(): boolean {\n\t\treturn this._pendingBashMessages.length > 0;\n\t}\n\n\t/**\n\t * Flush pending bash messages to agent state and session.\n\t * Called after agent turn completes to maintain proper message ordering.\n\t */\n\tflushPendingBashMessages(): void {\n\t\tif (this._pendingBashMessages.length === 0) return;\n\n\t\tfor (const bashMessage of this._pendingBashMessages) {\n\t\t\t// Add to agent state\n\t\t\tthis.deps.getAgent().state.messages.push(bashMessage);\n\n\t\t\t// Save to session\n\t\t\tthis.deps.getSessionManager().appendMessage(bashMessage);\n\t\t}\n\n\t\tthis._pendingBashMessages = [];\n\t}\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"bash-executor.d.ts","sourceRoot":"","sources":["../../src/core/bash-executor.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAWH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAOtD,MAAM,WAAW,mBAAmB;IACnC,+DAA+D;IAC/D,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,CAAC;IAClC,mCAAmC;IACnC,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB,2FAA2F;IAC3F,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B,wHAAwH;IACxH,OAAO,CAAC,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,UAAU;IAC1B,sEAAsE;IACtE,MAAM,EAAE,MAAM,CAAC;IACf,wDAAwD;IACxD,QAAQ,EAAE,MAAM,GAAG,SAAS,CAAC;IAC7B,mDAAmD;IACnD,SAAS,EAAE,OAAO,CAAC;IACnB,uCAAuC;IACvC,SAAS,EAAE,OAAO,CAAC;IACnB,yFAAyF;IACzF,cAAc,CAAC,EAAE,MAAM,CAAC;CACxB;AAUD;;;GAGG;AACH,wBAAsB,yBAAyB,CAC9C,OAAO,EAAE,MAAM,EACf,GAAG,EAAE,MAAM,EACX,UAAU,EAAE,cAAc,EAC1B,OAAO,CAAC,EAAE,mBAAmB,GAC3B,OAAO,CAAC,UAAU,CAAC,CAiKrB","sourcesContent":["/**\n * Bash command execution with streaming support and cancellation.\n *\n * This module provides a unified bash execution implementation used by:\n * - AgentSession.executeBash() for interactive and RPC modes\n * - Direct calls from modes that need bash execution\n */\n\nimport { randomBytes } from \"node:crypto\";\nimport type { WriteStream } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { sanitizeBinaryOutput } from \"@caupulican/pi-agent-core\";\nimport { DEFAULT_MAX_BYTES, truncateTail } from \"@caupulican/pi-agent-core/node\";\nimport { getAgentDir } from \"../config.ts\";\nimport { stripAnsi } from \"../utils/ansi.ts\";\nimport { createSafeWriteStream, endWriteStream } from \"../utils/safe-write-stream.ts\";\nimport { getProcessWorkRun } from \"../utils/work-directory.ts\";\nimport type { BashOperations } from \"./tools/bash.ts\";\nimport { classifyGitCommand, executeFilteredGit } from \"./tools/git-filter.ts\";\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface BashExecutorOptions {\n\t/** Callback for streaming output chunks (already sanitized) */\n\tonChunk?: (chunk: string) => void;\n\t/** AbortSignal for cancellation */\n\tsignal?: AbortSignal;\n\t/** Enable conservative pi-native git output filtering for local default execution paths */\n\tenableGitFilter?: boolean;\n\t/** Wall-clock timeout in seconds. Direct interactive/RPC callers provide the same bounded default as the agent tool. */\n\ttimeout?: number;\n}\n\nexport interface BashResult {\n\t/** Combined stdout + stderr output (sanitized, possibly truncated) */\n\toutput: string;\n\t/** Process exit code (undefined if killed/cancelled) */\n\texitCode: number | undefined;\n\t/** Whether the command was cancelled via signal */\n\tcancelled: boolean;\n\t/** Whether the output was truncated */\n\ttruncated: boolean;\n\t/** Path to temp file containing full output (if output exceeded truncation threshold) */\n\tfullOutputPath?: string;\n}\n\n// ============================================================================\n// Implementation\n// ============================================================================\n\nfunction getBashOutputPath(id: string): string {\n\treturn join(getProcessWorkRun(getAgentDir(), \"outputs\", \"bash\").path, `pi-bash-${id}.log`);\n}\n\n/**\n * Execute a bash command using custom BashOperations.\n * Used for remote execution (SSH, containers, etc.).\n */\nexport async function executeBashWithOperations(\n\tcommand: string,\n\tcwd: string,\n\toperations: BashOperations,\n\toptions?: BashExecutorOptions,\n): Promise<BashResult> {\n\tif (options?.enableGitFilter) {\n\t\tconst classification = classifyGitCommand(command, process.env);\n\t\tif (classification.eligible && classification.subcommand) {\n\t\t\tconst res = await executeFilteredGit(\n\t\t\t\tcwd,\n\t\t\t\tclassification.subcommand,\n\t\t\t\tclassification.globalOptions || [],\n\t\t\t\tclassification.subcommandArgs || [],\n\t\t\t\t{ signal: options.signal, timeout: options.timeout },\n\t\t\t);\n\t\t\tif (res.exitCode !== -100) {\n\t\t\t\tconst rawBytes = res.rawBytes ?? Buffer.from(res.rawOut, \"utf-8\");\n\t\t\t\t// The filter already spills oversized output to a temp file; reuse it\n\t\t\t\t// instead of materializing another full copy here.\n\t\t\t\tlet fullOutputPath = res.fullOutputPath;\n\t\t\t\tif (fullOutputPath === undefined && rawBytes.length > DEFAULT_MAX_BYTES) {\n\t\t\t\t\tconst id = randomBytes(8).toString(\"hex\");\n\t\t\t\t\tconst spillPath = getBashOutputPath(id);\n\t\t\t\t\tfullOutputPath = spillPath;\n\t\t\t\t\t// On stream failure (e.g. disk full), drop the advertised path instead of\n\t\t\t\t\t// pointing at a partial/missing file.\n\t\t\t\t\tconst tempFileStream = createSafeWriteStream(spillPath, () => {\n\t\t\t\t\t\tfullOutputPath = undefined;\n\t\t\t\t\t});\n\t\t\t\t\ttempFileStream.write(rawBytes);\n\t\t\t\t\t// Await the flush so the returned path points at a COMPLETE file, not one mid-write.\n\t\t\t\t\tawait endWriteStream(tempFileStream);\n\t\t\t\t}\n\t\t\t\toptions.onChunk?.(res.output);\n\t\t\t\treturn {\n\t\t\t\t\toutput: res.output,\n\t\t\t\t\texitCode: res.exitCode,\n\t\t\t\t\tcancelled: options.signal?.aborted ?? false,\n\t\t\t\t\ttruncated: res.fullOutputPath !== undefined || rawBytes.length > DEFAULT_MAX_BYTES,\n\t\t\t\t\tfullOutputPath,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t}\n\n\tconst outputChunks: string[] = [];\n\tlet outputBytes = 0;\n\tconst maxOutputBytes = DEFAULT_MAX_BYTES * 2;\n\n\tlet tempFilePath: string | undefined;\n\tlet tempFileStream: WriteStream | undefined;\n\tlet totalBytes = 0;\n\n\tconst ensureTempFile = () => {\n\t\tif (tempFilePath) {\n\t\t\treturn;\n\t\t}\n\t\tconst id = randomBytes(8).toString(\"hex\");\n\t\ttempFilePath = getBashOutputPath(id);\n\t\t// On stream failure (e.g. disk full), drop the artifact instead of\n\t\t// crashing the process; the rolling in-memory output is still returned.\n\t\ttempFileStream = createSafeWriteStream(tempFilePath, () => {\n\t\t\ttempFileStream = undefined;\n\t\t\ttempFilePath = undefined;\n\t\t});\n\t\tfor (const chunk of outputChunks) {\n\t\t\ttempFileStream.write(chunk);\n\t\t}\n\t};\n\n\tconst decoder = new TextDecoder();\n\n\tconst onData = (data: Buffer) => {\n\t\ttotalBytes += data.length;\n\n\t\t// Sanitize: strip ANSI, replace binary garbage, normalize newlines\n\t\tconst text = sanitizeBinaryOutput(stripAnsi(decoder.decode(data, { stream: true }))).replace(/\\r/g, \"\");\n\n\t\t// Start writing to temp file if exceeds threshold\n\t\tif (totalBytes > DEFAULT_MAX_BYTES) {\n\t\t\tensureTempFile();\n\t\t}\n\n\t\t// Guard writableEnded: custom BashOperations may deliver late onData\n\t\t// callbacks after an abort path has already ended the stream.\n\t\tif (tempFileStream && !tempFileStream.writableEnded) {\n\t\t\ttempFileStream.write(text);\n\t\t}\n\n\t\t// Keep rolling buffer\n\t\toutputChunks.push(text);\n\t\toutputBytes += text.length;\n\t\twhile (outputBytes > maxOutputBytes && outputChunks.length > 1) {\n\t\t\tconst removed = outputChunks.shift()!;\n\t\t\toutputBytes -= removed.length;\n\t\t}\n\n\t\t// Stream to callback\n\t\tif (options?.onChunk) {\n\t\t\toptions.onChunk(text);\n\t\t}\n\t};\n\n\ttry {\n\t\tconst result = await operations.exec(command, cwd, {\n\t\t\tonData,\n\t\t\tsignal: options?.signal,\n\t\t\ttimeout: options?.timeout,\n\t\t});\n\n\t\tconst fullOutput = outputChunks.join(\"\");\n\t\tconst truncationResult = truncateTail(fullOutput);\n\t\tif (truncationResult.truncated) {\n\t\t\tensureTempFile();\n\t\t}\n\t\tif (tempFileStream) {\n\t\t\t// Await the flush so fullOutputPath refers to a fully-written file on return, not one still\n\t\t\t// draining its buffer — otherwise a fast reader can see partial/empty content.\n\t\t\tawait endWriteStream(tempFileStream);\n\t\t}\n\t\tconst cancelled = options?.signal?.aborted ?? false;\n\n\t\treturn {\n\t\t\toutput: truncationResult.truncated ? truncationResult.content : fullOutput,\n\t\t\texitCode: cancelled ? undefined : (result.exitCode ?? undefined),\n\t\t\tcancelled,\n\t\t\ttruncated: truncationResult.truncated,\n\t\t\tfullOutputPath: tempFilePath,\n\t\t};\n\t} catch (err) {\n\t\t// Check if it was an abort\n\t\tif (options?.signal?.aborted) {\n\t\t\tconst fullOutput = outputChunks.join(\"\");\n\t\t\tconst truncationResult = truncateTail(fullOutput);\n\t\t\tif (truncationResult.truncated) {\n\t\t\t\tensureTempFile();\n\t\t\t}\n\t\t\tif (tempFileStream) {\n\t\t\t\tawait endWriteStream(tempFileStream);\n\t\t\t}\n\t\t\treturn {\n\t\t\t\toutput: truncationResult.truncated ? truncationResult.content : fullOutput,\n\t\t\t\texitCode: undefined,\n\t\t\t\tcancelled: true,\n\t\t\t\ttruncated: truncationResult.truncated,\n\t\t\t\tfullOutputPath: tempFilePath,\n\t\t\t};\n\t\t}\n\n\t\tif (tempFileStream) {\n\t\t\tawait endWriteStream(tempFileStream);\n\t\t}\n\n\t\t// The silence watchdog (see tools/bash.ts) throws a raw `silence:<secs>` sentinel.\n\t\t// Map it to the same user-facing message the interactive bash tool shows, instead of\n\t\t// leaking the sentinel to callers of this path (interactive !cmd, RPC).\n\t\tif (err instanceof Error && err.message.startsWith(\"silence:\")) {\n\t\t\tconst secs = err.message.split(\":\")[1];\n\t\t\tthrow new Error(\n\t\t\t\t`Command killed after ${secs}s of silence (no output). If the command is legitimately quiet for long stretches, re-run it with an explicit timeout.`,\n\t\t\t);\n\t\t}\n\n\t\tthrow err;\n\t}\n}\n"]}
1
+ {"version":3,"file":"bash-executor.d.ts","sourceRoot":"","sources":["../../src/core/bash-executor.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAWH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAOtD,MAAM,WAAW,mBAAmB;IACnC,+DAA+D;IAC/D,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,CAAC;IAClC,mCAAmC;IACnC,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB,2FAA2F;IAC3F,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B,wHAAwH;IACxH,OAAO,CAAC,EAAE,MA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AAO,CAAC,CAAC,CAAC,UAAU;gBAC1E,QAAQ,EAAE,SAAS;gBACnB,SAAS,EAAE,IAAI;gBACf,SAAS,EAAE,gBAAgB,CAAC,SAAS;gBACrC,cAAc,EAAE,YAAY;aAC5B,CAAC;QACH,CAAC;QAED,IAAI,cAAc,EAAE,CAAC;YACpB,MAAM,cAAc,CAAC,cAAc,CAAC,CAAC;QACtC,CAAC;QAED,mFAAmF;QACnF,qFAAqF;QACrF,wEAAwE;QACxE,IAAI,GAAG,YAAY,KAAK,IAAI,GAAG,CAAC,OAAO,CAAC,UAAU,CAAC,UAAU,CAAC,EAAE,CAAC;YAChE,MAAM,IAAI,GAAG,GAAG,CAAC,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;YACvC,MAAM,IAAI,KAAK,CACd,wBAAwB,IAAI,wHAAwH,CACpJ,CAAC;QACH,CAAC;QAED,MAAM,GAAG,CAAC;IACX,CAAC;AAAA,CACD","sourcesContent":["/**\n * Bash command execution with streaming support and cancellation.\n *\n * This module provides a unified bash execution implementation used by:\n * - AgentSession.executeBash() for interactive and RPC modes\n * - Direct calls from modes that need bash execution\n */\n\nimport { randomBytes } from \"node:crypto\";\nimport type { WriteStream } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { sanitizeBinaryOutput } from \"@caupulican/pi-agent-core\";\nimport { DEFAULT_MAX_BYTES, truncateTail } from \"@caupulican/pi-agent-core/node\";\nimport { getAgentDir } from \"../config.ts\";\nimport { stripAnsi } from \"../utils/ansi.ts\";\nimport { createSafeWriteStream, endWriteStream } from \"../utils/safe-write-stream.ts\";\nimport { getProcessWorkRun } from \"../utils/work-directory.ts\";\nimport type { BashOperations } from \"./tools/bash.ts\";\nimport { classifyGitCommand, executeFilteredGit } from \"./tools/git-filter.ts\";\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface BashExecutorOptions {\n\t/** Callback for streaming output chunks (already sanitized) */\n\tonChunk?: (chunk: string) => void;\n\t/** AbortSignal for cancellation */\n\tsignal?: AbortSignal;\n\t/** Enable conservative pi-native git output filtering for local default execution paths */\n\tenableGitFilter?: boolean;\n\t/** Wall-clock timeout in seconds. Direct interactive/RPC callers provide the same bounded default as the agent tool. */\n\ttimeout?: number;\n}\n\nexport interface BashResult {\n\t/** Combined stdout + stderr output (sanitized, possibly truncated) */\n\toutput: string;\n\t/** Process exit code (undefined if killed/cancelled) */\n\texitCode: number | undefined;\n\t/** Whether the command was cancelled via signal */\n\tcancelled: boolean;\n\t/** Whether the output was truncated */\n\ttruncated: boolean;\n\t/** Path to temp file containing full output (if output exceeded truncation threshold) */\n\tfullOutputPath?: string;\n}\n\n// ============================================================================\n// Implementation\n// ============================================================================\n\nfunction getBashOutputPath(id: string): string {\n\treturn join(getProcessWorkRun(getAgentDir(), \"outputs\", \"bash\").path, `pi-bash-${id}.log`);\n}\n\n/**\n * Execute a bash command using custom BashOperations.\n * Used for remote execution (SSH, containers, etc.).\n */\nexport async function executeBashWithOperations(\n\tcommand: string,\n\tcwd: string,\n\toperations: BashOperations,\n\toptions?: BashExecutorOptions,\n): Promise<BashResult> {\n\tif (options?.enableGitFilter) {\n\t\tconst classification = classifyGitCommand(command, process.env);\n\t\tif (classification.eligible && classification.subcommand) {\n\t\t\tconst res = await executeFilteredGit(\n\t\t\t\tcwd,\n\t\t\t\tclassification.subcommand,\n\t\t\t\tclassification.globalOptions || [],\n\t\t\t\tclassification.subcommandArgs || [],\n\t\t\t\t{ signal: options.signal, timeout: options.timeout },\n\t\t\t);\n\t\t\tif (res.exitCode !== -100) {\n\t\t\t\tconst rawBytes = res.rawBytes ?? Buffer.from(res.rawOut, \"utf-8\");\n\t\t\t\t// The filter already spills oversized output to a temp file; reuse it\n\t\t\t\t// instead of materializing another full copy here.\n\t\t\t\tlet fullOutputPath = res.fullOutputPath;\n\t\t\t\tif (fullOutputPath === undefined && rawBytes.length > DEFAULT_MAX_BYTES) {\n\t\t\t\t\tconst id = randomBytes(8).toString(\"hex\");\n\t\t\t\t\tconst spillPath = getBashOutputPath(id);\n\t\t\t\t\tfullOutputPath = spillPath;\n\t\t\t\t\t// On stream failure (e.g. disk full), drop the advertised path instead of\n\t\t\t\t\t// pointing at a partial/missing file.\n\t\t\t\t\tconst tempFileStream = createSafeWriteStream(spillPath, () => {\n\t\t\t\t\t\tfullOutputPath = undefined;\n\t\t\t\t\t});\n\t\t\t\t\ttempFileStream.write(rawBytes);\n\t\t\t\t\t// Await the flush so the returned path points at a COMPLETE file, not one mid-write.\n\t\t\t\t\tawait endWriteStream(tempFileStream);\n\t\t\t\t}\n\t\t\t\toptions.onChunk?.(res.output);\n\t\t\t\treturn {\n\t\t\t\t\toutput: res.output,\n\t\t\t\t\texitCode: res.exitCode,\n\t\t\t\t\tcancelled: options.signal?.aborted ?? false,\n\t\t\t\t\ttruncated: res.fullOutputPath !== undefined || rawBytes.length > DEFAULT_MAX_BYTES,\n\t\t\t\t\tfullOutputPath,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t}\n\n\tconst outputChunks: string[] = [];\n\tlet outputBytes = 0;\n\tconst maxOutputBytes = DEFAULT_MAX_BYTES * 2;\n\n\tlet tempFilePath: string | undefined;\n\tlet tempFileStream: WriteStream | undefined;\n\tlet totalBytes = 0;\n\n\tconst ensureTempFile = () => {\n\t\tif (tempFilePath) {\n\t\t\treturn;\n\t\t}\n\t\tconst id = randomBytes(8).toString(\"hex\");\n\t\ttempFilePath = getBashOutputPath(id);\n\t\t// On stream failure (e.g. disk full), drop the artifact instead of\n\t\t// crashing the process; the rolling in-memory output is still returned.\n\t\ttempFileStream = createSafeWriteStream(tempFilePath, () => {\n\t\t\ttempFileStream = undefined;\n\t\t\ttempFilePath = undefined;\n\t\t});\n\t\tfor (const chunk of outputChunks) {\n\t\t\ttempFileStream.write(chunk);\n\t\t}\n\t};\n\n\tconst decoder = new TextDecoder();\n\n\tconst onData = (data: Buffer) => {\n\t\ttotalBytes += data.length;\n\n\t\t// Sanitize: strip ANSI, replace binary garbage, normalize newlines\n\t\tconst text = sanitizeBinaryOutput(stripAnsi(decoder.decode(data, { stream: true }))).replace(/\\r/g, \"\");\n\n\t\t// Start writing to temp file if exceeds threshold\n\t\tif (totalBytes > DEFAULT_MAX_BYTES) {\n\t\t\tensureTempFile();\n\t\t}\n\n\t\t// Guard writableEnded: custom BashOperations may deliver late onData\n\t\t// callbacks after an abort path has already ended the stream.\n\t\tif (tempFileStream && !tempFileStream.writableEnded) {\n\t\t\ttempFileStream.write(text);\n\t\t}\n\n\t\t// Keep rolling buffer\n\t\toutputChunks.push(text);\n\t\toutputBytes += text.length;\n\t\twhile (outputBytes > maxOutputBytes && outputChunks.length > 1) {\n\t\t\tconst removed = outputChunks.shift()!;\n\t\t\toutputBytes -= removed.length;\n\t\t}\n\n\t\t// Stream to callback\n\t\tif (options?.onChunk) {\n\t\t\toptions.onChunk(text);\n\t\t}\n\t};\n\n\ttry {\n\t\tconst result = await operations.exec(command, cwd, {\n\t\t\tonData,\n\t\t\tsignal: options?.signal,\n\t\t\ttimeout: options?.timeout,\n\t\t});\n\n\t\tconst fullOutput = outputChunks.join(\"\");\n\t\tconst truncationResult = truncateTail(fullOutput);\n\t\tif (truncationResult.truncated) {\n\t\t\tensureTempFile();\n\t\t}\n\t\tif (tempFileStream) {\n\t\t\t// Await the flush so fullOutputPath refers to a fully-written file on return, not one still\n\t\t\t// draining its buffer — otherwise a fast reader can see partial/empty content.\n\t\t\tawait endWriteStream(tempFileStream);\n\t\t}\n\t\tconst cancelled = options?.signal?.aborted ?? false;\n\n\t\treturn {\n\t\t\toutput: truncationResult.truncated ? truncationResult.content : fullOutput,\n\t\t\texitCode: cancelled ? undefined : (result.exitCode ?? undefined),\n\t\t\tcancelled,\n\t\t\ttruncated: truncationResult.truncated,\n\t\t\tfullOutputPath: tempFilePath,\n\t\t};\n\t} catch (err) {\n\t\t// Check if it was an abort\n\t\tif (options?.signal?.aborted) {\n\t\t\tconst fullOutput = outputChunks.join(\"\");\n\t\t\tconst truncationResult = truncateTail(fullOutput);\n\t\t\tif (truncationResult.truncated) {\n\t\t\t\tensureTempFile();\n\t\t\t}\n\t\t\tif (tempFileStream) {\n\t\t\t\tawait endWriteStream(tempFileStream);\n\t\t\t}\n\t\t\treturn {\n\t\t\t\toutput: truncationResult.truncated ? truncationResult.content : fullOutput,\n\t\t\t\texitCode: undefined,\n\t\t\t\tcancelled: true,\n\t\t\t\ttruncated: truncationResult.truncated,\n\t\t\t\tfullOutputPath: tempFilePath,\n\t\t\t};\n\t\t}\n\n\t\tif (tempFileStream) {\n\t\t\tawait endWriteStream(tempFileStream);\n\t\t}\n\n\t\t// The silence watchdog (see tools/bash.ts) throws a raw `silence:<secs>` sentinel.\n\t\t// Map it to the same user-facing message the interactive bash tool shows, instead of\n\t\t// leaking the sentinel to callers of this path (interactive !cmd, RPC).\n\t\tif (err instanceof Error && err.message.startsWith(\"silence:\")) {\n\t\t\tconst secs = err.message.split(\":\")[1];\n\t\t\tthrow new Error(\n\t\t\t\t`Command killed after ${secs}s of silence (no output). If the command is legitimately quiet for long stretches, re-run it with an explicit timeout.`,\n\t\t\t);\n\t\t}\n\n\t\tthrow err;\n\t}\n}\n"]}
1
+ {"version":3,"file":"bash-executor.js","sourceRoot":"","sources":["../../src/core/bash-executor.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAE1C,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,oBAAoB,EAAE,MAAM,2BAA2B,CAAC;AACjE,OAAO,EAAE,iBAAiB,EAAE,YAAY,EAAE,MAAM,gCAAgC,CAAC;AACjF,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAE,qBAAqB,EAAE,cAAc,EAAE,MAAM,+BAA+B,CAAC;AACtF,OAAO,EAAE,iBAAiB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AAE,CAAC;gBAChC,cAAc,EAAE,CAAC;YAClB,CAAC;YACD,IAAI,cAAc,EAAE,CAAC;gBACpB,MAAM,cAAc,CAAC,cAAc,CAAC,CAAC;YACtC,CAAC;YACD,OAAO;gBACN,MAAM,EAAE,gBAAgB,CAAC,SAAS,CAAC,CAAC,CAAC,gBAAgB,CAAC,OAAO,CAAC,CAAC,CAAC,UAAU;gBAC1E,QAAQ,EAAE,SAAS;gBACnB,SAAS,EAAE,IAAI;gBACf,SAAS,EAAE,gBAAgB,CAAC,SAAS;gBACrC,cAAc,EAAE,YAAY;aAC5B,CAAC;QACH,CAAC;QAED,IAAI,cAAc,EAAE,CAAC;YACpB,MAAM,cAAc,CAAC,cAAc,CAAC,CAAC;QACtC,CAAC;QAED,mFAAmF;QACnF,qFAAqF;QACrF,wEAAwE;QACxE,IAAI,GAAG,YAAY,KAAK,IAAI,GAAG,CAAC,OAAO,CAAC,UAAU,CAAC,UAAU,CAAC,EAAE,CAAC;YAChE,MAAM,IAAI,GAAG,GAAG,CAAC,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;YACvC,MAAM,IAAI,KAAK,CACd,wBAAwB,IAAI,wHAAwH,CACpJ,CAAC;QACH,CAAC;QAED,MAAM,GAAG,CAAC;IACX,CAAC;AACF,CAAC","sourcesContent":["/**\n * Bash command execution with streaming support and cancellation.\n *\n * This module provides a unified bash execution implementation used by:\n * - AgentSession.executeBash() for interactive and RPC modes\n * - Direct calls from modes that need bash execution\n */\n\nimport { randomBytes } from \"node:crypto\";\nimport type { WriteStream } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { sanitizeBinaryOutput } from \"@caupulican/pi-agent-core\";\nimport { DEFAULT_MAX_BYTES, truncateTail } from \"@caupulican/pi-agent-core/node\";\nimport { getAgentDir } from \"../config.ts\";\nimport { stripAnsi } from \"../utils/ansi.ts\";\nimport { createSafeWriteStream, endWriteStream } from \"../utils/safe-write-stream.ts\";\nimport { getProcessWorkRun } from \"../utils/work-directory.ts\";\nimport type { BashOperations } from \"./tools/bash.ts\";\nimport { classifyGitCommand, executeFilteredGit } from \"./tools/git-filter.ts\";\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface BashExecutorOptions {\n\t/** Callback for streaming output chunks (already sanitized) */\n\tonChunk?: (chunk: string) => void;\n\t/** AbortSignal for cancellation */\n\tsignal?: AbortSignal;\n\t/** Enable conservative pi-native git output filtering for local default execution paths */\n\tenableGitFilter?: boolean;\n\t/** Wall-clock timeout in seconds. Direct interactive/RPC callers provide the same bounded default as the agent tool. */\n\ttimeout?: number;\n}\n\nexport interface BashResult {\n\t/** Combined stdout + stderr output (sanitized, possibly truncated) */\n\toutput: string;\n\t/** Process exit code (undefined if killed/cancelled) */\n\texitCode: number | undefined;\n\t/** Whether the command was cancelled via signal */\n\tcancelled: boolean;\n\t/** Whether the output was truncated */\n\ttruncated: boolean;\n\t/** Path to temp file containing full output (if output exceeded truncation threshold) */\n\tfullOutputPath?: string;\n}\n\n// ============================================================================\n// Implementation\n// ============================================================================\n\nfunction getBashOutputPath(id: string): string {\n\treturn join(getProcessWorkRun(getAgentDir(), \"outputs\", \"bash\").path, `pi-bash-${id}.log`);\n}\n\n/**\n * Execute a bash command using custom BashOperations.\n * Used for remote execution (SSH, containers, etc.).\n */\nexport async function executeBashWithOperations(\n\tcommand: string,\n\tcwd: string,\n\toperations: BashOperations,\n\toptions?: BashExecutorOptions,\n): Promise<BashResult> {\n\tif (options?.enableGitFilter) {\n\t\tconst classification = classifyGitCommand(command, process.env);\n\t\tif (classification.eligible && classification.subcommand) {\n\t\t\tconst res = await executeFilteredGit(\n\t\t\t\tcwd,\n\t\t\t\tclassification.subcommand,\n\t\t\t\tclassification.globalOptions || [],\n\t\t\t\tclassification.subcommandArgs || [],\n\t\t\t\t{ signal: options.signal, timeout: options.timeout },\n\t\t\t);\n\t\t\tif (res.exitCode !== -100) {\n\t\t\t\tconst rawBytes = res.rawBytes ?? Buffer.from(res.rawOut, \"utf-8\");\n\t\t\t\t// The filter already spills oversized output to a temp file; reuse it\n\t\t\t\t// instead of materializing another full copy here.\n\t\t\t\tlet fullOutputPath = res.fullOutputPath;\n\t\t\t\tif (fullOutputPath === undefined && rawBytes.length > DEFAULT_MAX_BYTES) {\n\t\t\t\t\tconst id = randomBytes(8).toString(\"hex\");\n\t\t\t\t\tconst spillPath = getBashOutputPath(id);\n\t\t\t\t\tfullOutputPath = spillPath;\n\t\t\t\t\t// On stream failure (e.g. disk full), drop the advertised path instead of\n\t\t\t\t\t// pointing at a partial/missing file.\n\t\t\t\t\tconst tempFileStream = createSafeWriteStream(spillPath, () => {\n\t\t\t\t\t\tfullOutputPath = undefined;\n\t\t\t\t\t});\n\t\t\t\t\ttempFileStream.write(rawBytes);\n\t\t\t\t\t// Await the flush so the returned path points at a COMPLETE file, not one mid-write.\n\t\t\t\t\tawait endWriteStream(tempFileStream);\n\t\t\t\t}\n\t\t\t\toptions.onChunk?.(res.output);\n\t\t\t\treturn {\n\t\t\t\t\toutput: res.output,\n\t\t\t\t\texitCode: res.exitCode,\n\t\t\t\t\tcancelled: options.signal?.aborted ?? false,\n\t\t\t\t\ttruncated: res.fullOutputPath !== undefined || rawBytes.length > DEFAULT_MAX_BYTES,\n\t\t\t\t\tfullOutputPath,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t}\n\n\tconst outputChunks: string[] = [];\n\tlet outputBytes = 0;\n\tconst maxOutputBytes = DEFAULT_MAX_BYTES * 2;\n\n\tlet tempFilePath: string | undefined;\n\tlet tempFileStream: WriteStream | undefined;\n\tlet totalBytes = 0;\n\n\tconst ensureTempFile = () => {\n\t\tif (tempFilePath) {\n\t\t\treturn;\n\t\t}\n\t\tconst id = randomBytes(8).toString(\"hex\");\n\t\ttempFilePath = getBashOutputPath(id);\n\t\t// On stream failure (e.g. disk full), drop the artifact instead of\n\t\t// crashing the process; the rolling in-memory output is still returned.\n\t\ttempFileStream = createSafeWriteStream(tempFilePath, () => {\n\t\t\ttempFileStream = undefined;\n\t\t\ttempFilePath = undefined;\n\t\t});\n\t\tfor (const chunk of outputChunks) {\n\t\t\ttempFileStream.write(chunk);\n\t\t}\n\t};\n\n\tconst decoder = new TextDecoder();\n\n\tconst onData = (data: Buffer) => {\n\t\ttotalBytes += data.length;\n\n\t\t// Sanitize: strip ANSI, replace binary garbage, normalize newlines\n\t\tconst text = sanitizeBinaryOutput(stripAnsi(decoder.decode(data, { stream: true }))).replace(/\\r/g, \"\");\n\n\t\t// Start writing to temp file if exceeds threshold\n\t\tif (totalBytes > DEFAULT_MAX_BYTES) {\n\t\t\tensureTempFile();\n\t\t}\n\n\t\t// Guard writableEnded: custom BashOperations may deliver late onData\n\t\t// callbacks after an abort path has already ended the stream.\n\t\tif (tempFileStream && !tempFileStream.writableEnded) {\n\t\t\ttempFileStream.write(text);\n\t\t}\n\n\t\t// Keep rolling buffer\n\t\toutputChunks.push(text);\n\t\toutputBytes += text.length;\n\t\twhile (outputBytes > maxOutputBytes && outputChunks.length > 1) {\n\t\t\tconst removed = outputChunks.shift()!;\n\t\t\toutputBytes -= removed.length;\n\t\t}\n\n\t\t// Stream to callback\n\t\tif (options?.onChunk) {\n\t\t\toptions.onChunk(text);\n\t\t}\n\t};\n\n\ttry {\n\t\tconst result = await operations.exec(command, cwd, {\n\t\t\tonData,\n\t\t\tsignal: options?.signal,\n\t\t\ttimeout: options?.timeout,\n\t\t});\n\n\t\tconst fullOutput = outputChunks.join(\"\");\n\t\tconst truncationResult = truncateTail(fullOutput);\n\t\tif (truncationResult.truncated) {\n\t\t\tensureTempFile();\n\t\t}\n\t\tif (tempFileStream) {\n\t\t\t// Await the flush so fullOutputPath refers to a fully-written file on return, not one still\n\t\t\t// draining its buffer — otherwise a fast reader can see partial/empty content.\n\t\t\tawait endWriteStream(tempFileStream);\n\t\t}\n\t\tconst cancelled = options?.signal?.aborted ?? false;\n\n\t\treturn {\n\t\t\toutput: truncationResult.truncated ? truncationResult.content : fullOutput,\n\t\t\texitCode: cancelled ? undefined : (result.exitCode ?? undefined),\n\t\t\tcancelled,\n\t\t\ttruncated: truncationResult.truncated,\n\t\t\tfullOutputPath: tempFilePath,\n\t\t};\n\t} catch (err) {\n\t\t// Check if it was an abort\n\t\tif (options?.signal?.aborted) {\n\t\t\tconst fullOutput = outputChunks.join(\"\");\n\t\t\tconst truncationResult = truncateTail(fullOutput);\n\t\t\tif (truncationResult.truncated) {\n\t\t\t\tensureTempFile();\n\t\t\t}\n\t\t\tif (tempFileStream) {\n\t\t\t\tawait endWriteStream(tempFileStream);\n\t\t\t}\n\t\t\treturn {\n\t\t\t\toutput: truncationResult.truncated ? truncationResult.content : fullOutput,\n\t\t\t\texitCode: undefined,\n\t\t\t\tcancelled: true,\n\t\t\t\ttruncated: truncationResult.truncated,\n\t\t\t\tfullOutputPath: tempFilePath,\n\t\t\t};\n\t\t}\n\n\t\tif (tempFileStream) {\n\t\t\tawait endWriteStream(tempFileStream);\n\t\t}\n\n\t\t// The silence watchdog (see tools/bash.ts) throws a raw `silence:<secs>` sentinel.\n\t\t// Map it to the same user-facing message the interactive bash tool shows, instead of\n\t\t// leaking the sentinel to callers of this path (interactive !cmd, RPC).\n\t\tif (err instanceof Error && err.message.startsWith(\"silence:\")) {\n\t\t\tconst secs = err.message.split(\":\")[1];\n\t\t\tthrow new Error(\n\t\t\t\t`Command killed after ${secs}s of silence (no output). If the command is legitimately quiet for long stretches, re-run it with an explicit timeout.`,\n\t\t\t);\n\t\t}\n\n\t\tthrow err;\n\t}\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"bedrock-sso-login.d.ts","sourceRoot":"","sources":["../../src/core/bedrock-sso-login.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,8BAA8B,EAAE,MAAM,mBAAmB,CAAC;AAExE,OAAO,EAAmB,WAAW,EAAE,MAAM,WAAW,CAAC;AAQzD,KAAK,cAAc,GAAG,OAAO,WAAW,CAAC;AAEzC,MAAM,WAAW,sBAAsB;IACtC,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB,OAAO,CAAC,EAAE,cAAc,CAAC;IACzB,QAAQ,CAAC,EAAE,MAAM,OAAO,CAAC;IACzB,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,GAAG,CAAC,EAAE,MAAM,CAAC,UAAU,CAAC;CACxB;AAiED,kGAAkG;AAClG,wBAAsB,sBAAsB,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,GAAE,sBAA2B,GAAG,OAAO,CAAC,IAAI,CAAC,CAkBjH;AAED,mGAAmG;AACnG,eAAO,MAAM,+BAA+B,EAAE,8BAK7C,CAAC","sourcesContent":["import type { InteractiveAuthRecoveryHandler } from \"@caupulican/pi-ai\";\nimport { stripAnsi } from \"../utils/ansi.ts\";\nimport { type ExecResult, execCommand } from \"./exec.ts\";\nimport { isWorkerSession } from \"./session-role.ts\";\n\nconst LOGIN_TIMEOUT_MS = 15 * 60_000;\nconst LOGIN_OUTPUT_LIMIT = 32 * 1024;\nconst ERROR_DETAIL_LIMIT = 512;\nconst activeLogins = new Map<string, Promise<void>>();\n\ntype ExecuteCommand = typeof execCommand;\n\nexport interface BedrockSsoLoginOptions {\n\tsignal?: AbortSignal;\n\texecute?: ExecuteCommand;\n\tisWorker?: () => boolean;\n\tcwd?: string;\n\tenv?: NodeJS.ProcessEnv;\n}\n\nfunction validateProfile(profile: string): string {\n\tconst normalized = profile.trim();\n\tif (!normalized) throw new Error(\"AWS profile name is required\");\n\tif (normalized.length > 256 || /[\\u0000-\\u001f\\u007f-\\u009f]/.test(normalized)) {\n\t\tthrow new Error(\"AWS profile name contains unsupported characters\");\n\t}\n\treturn normalized;\n}\n\nfunction compactOutputDetail(result: ExecResult): string | undefined {\n\tconst raw = result.stderr.trim() || result.stdout.trim();\n\tif (!raw) return undefined;\n\tconst withoutAnsi = stripAnsi(raw);\n\tconst lines = withoutAnsi\n\t\t.split(/\\r?\\n/)\n\t\t.map((line) => line.trim())\n\t\t.filter(Boolean);\n\tconst detail = lines.at(-1);\n\tif (!detail) return undefined;\n\treturn detail.length <= ERROR_DETAIL_LIMIT ? detail : `${detail.slice(0, ERROR_DETAIL_LIMIT - 1)}…`;\n}\n\nasync function executeLogin(profile: string, options: BedrockSsoLoginOptions): Promise<void> {\n\tconst execute = options.execute ?? execCommand;\n\tconst result = await execute(\"aws\", [\"sso\", \"login\", \"--profile\", profile], options.cwd ?? process.cwd(), {\n\t\tsignal: options.signal,\n\t\ttimeout: LOGIN_TIMEOUT_MS,\n\t\tenv: options.env ?? process.env,\n\t\tmaxBuffer: LOGIN_OUTPUT_LIMIT,\n\t});\n\tif (result.errorMessage) {\n\t\tconst detail = result.errorMessage.slice(0, ERROR_DETAIL_LIMIT);\n\t\tthrow new Error(`AWS CLI v2 is required for managed SSO login: ${detail}`);\n\t}\n\tif (result.killed) {\n\t\tthrow new Error(options.signal?.aborted ? \"AWS SSO login was cancelled\" : \"AWS SSO login timed out\");\n\t}\n\tif (result.code !== 0) {\n\t\tconst detail = compactOutputDetail(result) ?? `aws exited with code ${result.code}`;\n\t\tthrow new Error(`AWS SSO login failed for profile \"${profile}\": ${detail}`);\n\t}\n}\n\nfunction waitForSharedLogin(login: Promise<void>, signal: AbortSignal | undefined): Promise<void> {\n\tif (!signal) return login;\n\treturn new Promise<void>((resolve, reject) => {\n\t\tlet settled = false;\n\t\tconst finish = (settle: () => void) => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t\t\tsettle();\n\t\t};\n\t\tconst onAbort = () => finish(() => reject(new Error(\"AWS SSO login was cancelled\")));\n\t\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\t\tvoid login.then(\n\t\t\t() => finish(resolve),\n\t\t\t(error: unknown) => finish(() => reject(error)),\n\t\t);\n\t\tif (signal.aborted) onAbort();\n\t});\n}\n\n/** Run one foreground AWS SSO login per profile; concurrent callers share its terminal result. */\nexport async function loginBedrockSsoProfile(profile: string, options: BedrockSsoLoginOptions = {}): Promise<void> {\n\tconst normalized = validateProfile(profile);\n\tif ((options.isWorker ?? isWorkerSession)()) {\n\t\tthrow new Error(\n\t\t\t`AWS SSO authentication for profile \"${normalized}\" requires a user session; run /login amazon-bedrock in the owning user session.`,\n\t\t);\n\t}\n\tif (options.signal?.aborted) throw new Error(\"AWS SSO login was cancelled\");\n\n\tconst existing = activeLogins.get(normalized);\n\tif (existing) return waitForSharedLogin(existing, options.signal);\n\tconst login = executeLogin(normalized, options);\n\tactiveLogins.set(normalized, login);\n\ttry {\n\t\tawait login;\n\t} finally {\n\t\tif (activeLogins.get(normalized) === login) activeLogins.delete(normalized);\n\t}\n}\n\n/** Restore one request-owned Bedrock SSO session after the provider identifies explicit expiry. */\nexport const recoverBedrockSsoAuthentication: InteractiveAuthRecoveryHandler = async (request) => {\n\tawait loginBedrockSsoProfile(request.profile, {\n\t\t...(request.signal ? { signal: request.signal } : {}),\n\t});\n\treturn true;\n};\n"]}
1
+ {"version":3,"file":"bedrock-sso-login.d.ts","sourceRoot":"","sources":["../../src/core/bedrock-sso-login.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,8BAA8B,EAAE,MAAM,mBAAmB,CAAC;AAExE,OAAO,EAAmB,WAAW,EAAE,MAAM,WAAW,CAAC;AAQzD,KAAK,cAAc,GAAG,OAAO,WAAW,CAAC;AAEzC,MAAM,WAAW,sBAAsB;IACtC,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB,OAAO,CAAC,EAAE,cAAc,CAAC;IACzB,QAAQ,CAAC,EAAE,MAAM,OAAO,CAAC;IACzB,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,GAAG,CAAC,EAAE,MAAM,CAAC,UAAU,CAAC;CACxB;AAiED,kGAAkG;AAClG,wBAAsB,sBAAsB,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,GAAE,sBAA2B,GAAG,OAAO,CAAC,IAAI,CAAC,CAkBjH;AAED,mGAAmG;AACnG,eAAO,MAAM,+BAA+B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U,GAAG,eAAe,CAAC,OAAO,CAAC,CAAC;IAC5C,IAAI,CAAC,OAAO,CAAC,QAAQ,IAAI,eAAe,CAAC,EAAE,EAAE,CAAC;QAC7C,MAAM,IAAI,KAAK,CACd,uCAAuC,UAAU,kFAAkF,CACnI,CAAC;IACH,CAAC;IACD,IAAI,OAAO,CAAC,MAAM,EAAE,OAAO;QAAE,MAAM,IAAI,KAAK,CAAC,6BAA6B,CAAC,CAAC;IAE5E,MAAM,QAAQ,GAAG,YAAY,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;IAC9C,IAAI,QAAQ;QAAE,OAAO,kBAAkB,CAAC,QAAQ,EAAE,OAAO,CAAC,MAAM,CAAC,CAAC;IAClE,MAAM,KAAK,GAAG,YAAY,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC;IAChD,YAAY,CAAC,GAAG,CAAC,UAAU,EAAE,KAAK,CAAC,CAAC;IACpC,IAAI,CAAC;QACJ,MAAM,KAAK,CAAC;IACb,CAAC;YAAS,CAAC;QACV,IAAI,YAAY,CAAC,GAAG,CAAC,UAAU,CAAC,KAAK,KAAK;YAAE,YAAY,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;IAC7E,CAAC;AAAA,CACD;AAED,mGAAmG;AACnG,MAAM,CAAC,MAAM,+BAA+B,GAAmC,KAAK,EAAE,OAAO,EAAE,EAAE,CAAC;IACjG,MAAM,sBAAsB,CAAC,OAAO,CAAC,OAAO,EAAE;QAC7C,GAAG,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;KACrD,CAAC,CAAC;IACH,OAAO,IAAI,CAAC;AAAA,CACZ,CAAC","sourcesContent":["import type { InteractiveAuthRecoveryHandler } from \"@caupulican/pi-ai\";\nimport { stripAnsi } from \"../utils/ansi.ts\";\nimport { type ExecResult, execCommand } from \"./exec.ts\";\nimport { isWorkerSession } from \"./session-role.ts\";\n\nconst LOGIN_TIMEOUT_MS = 15 * 60_000;\nconst LOGIN_OUTPUT_LIMIT = 32 * 1024;\nconst ERROR_DETAIL_LIMIT = 512;\nconst activeLogins = new Map<string, Promise<void>>();\n\ntype ExecuteCommand = typeof execCommand;\n\nexport interface BedrockSsoLoginOptions {\n\tsignal?: AbortSignal;\n\texecute?: ExecuteCommand;\n\tisWorker?: () => boolean;\n\tcwd?: string;\n\tenv?: NodeJS.ProcessEnv;\n}\n\nfunction validateProfile(profile: string): string {\n\tconst normalized = profile.trim();\n\tif (!normalized) throw new Error(\"AWS profile name is required\");\n\tif (normalized.length > 256 || /[\\u0000-\\u001f\\u007f-\\u009f]/.test(normalized)) {\n\t\tthrow new Error(\"AWS profile name contains unsupported characters\");\n\t}\n\treturn normalized;\n}\n\nfunction compactOutputDetail(result: ExecResult): string | undefined {\n\tconst raw = result.stderr.trim() || result.stdout.trim();\n\tif (!raw) return undefined;\n\tconst withoutAnsi = stripAnsi(raw);\n\tconst lines = withoutAnsi\n\t\t.split(/\\r?\\n/)\n\t\t.map((line) => line.trim())\n\t\t.filter(Boolean);\n\tconst detail = lines.at(-1);\n\tif (!detail) return undefined;\n\treturn detail.length <= ERROR_DETAIL_LIMIT ? detail : `${detail.slice(0, ERROR_DETAIL_LIMIT - 1)}…`;\n}\n\nasync function executeLogin(profile: string, options: BedrockSsoLoginOptions): Promise<void> {\n\tconst execute = options.execute ?? execCommand;\n\tconst result = await execute(\"aws\", [\"sso\", \"login\", \"--profile\", profile], options.cwd ?? process.cwd(), {\n\t\tsignal: options.signal,\n\t\ttimeout: LOGIN_TIMEOUT_MS,\n\t\tenv: options.env ?? process.env,\n\t\tmaxBuffer: LOGIN_OUTPUT_LIMIT,\n\t});\n\tif (result.errorMessage) {\n\t\tconst detail = result.errorMessage.slice(0, ERROR_DETAIL_LIMIT);\n\t\tthrow new Error(`AWS CLI v2 is required for managed SSO login: ${detail}`);\n\t}\n\tif (result.killed) {\n\t\tthrow new Error(options.signal?.aborted ? \"AWS SSO login was cancelled\" : \"AWS SSO login timed out\");\n\t}\n\tif (result.code !== 0) {\n\t\tconst detail = compactOutputDetail(result) ?? `aws exited with code ${result.code}`;\n\t\tthrow new Error(`AWS SSO login failed for profile \"${profile}\": ${detail}`);\n\t}\n}\n\nfunction waitForSharedLogin(login: Promise<void>, signal: AbortSignal | undefined): Promise<void> {\n\tif (!signal) return login;\n\treturn new Promise<void>((resolve, reject) => {\n\t\tlet settled = false;\n\t\tconst finish = (settle: () => void) => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t\t\tsettle();\n\t\t};\n\t\tconst onAbort = () => finish(() => reject(new Error(\"AWS SSO login was cancelled\")));\n\t\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\t\tvoid login.then(\n\t\t\t() => finish(resolve),\n\t\t\t(error: unknown) => finish(() => reject(error)),\n\t\t);\n\t\tif (signal.aborted) onAbort();\n\t});\n}\n\n/** Run one foreground AWS SSO login per profile; concurrent callers share its terminal result. */\nexport async function loginBedrockSsoProfile(profile: string, options: BedrockSsoLoginOptions = {}): Promise<void> {\n\tconst normalized = validateProfile(profile);\n\tif ((options.isWorker ?? isWorkerSession)()) {\n\t\tthrow new Error(\n\t\t\t`AWS SSO authentication for profile \"${normalized}\" requires a user session; run /login amazon-bedrock in the owning user session.`,\n\t\t);\n\t}\n\tif (options.signal?.aborted) throw new Error(\"AWS SSO login was cancelled\");\n\n\tconst existing = activeLogins.get(normalized);\n\tif (existing) return waitForSharedLogin(existing, options.signal);\n\tconst login = executeLogin(normalized, options);\n\tactiveLogins.set(normalized, login);\n\ttry {\n\t\tawait login;\n\t} finally {\n\t\tif (activeLogins.get(normalized) === login) activeLogins.delete(normalized);\n\t}\n}\n\n/** Restore one request-owned Bedrock SSO session after the provider identifies explicit expiry. */\nexport const recoverBedrockSsoAuthentication: InteractiveAuthRecoveryHandler = async (request) => {\n\tawait loginBedrockSsoProfile(request.profile, {\n\t\t...(request.signal ? { signal: request.signal } : {}),\n\t});\n\treturn true;\n};\n"]}
1
+ {"version":3,"file":"bedrock-sso-login.js","sourceRoot":"","sources":["../../src/core/bedrock-sso-login.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAmB,WAAW,EAAE,MAAM,WAAW,CAAC;AACzD,OAAO,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AAEpD,MAAM,gBAAgB,GAAG,EAAE,GAAG,MAAM,CAAC;AACrC,MAAM,kBAAkB,GAAG,EAAE,GAAG,IAAI,CAAC;AACrC,MAAM,kBAAkB,GAAG,GAAG,CAAC;AAC/B,MAAM,YAAY,GAAG,IAAI,GAAG,EAAyB,CAAC;AAYtD,SAAS,eAAe,CAAC,OAAe;IACvC,MAAM,UAAU,GAAG,OAAO,CAAC,IAAI,EAAE,CAAC;IAClC,IAAI,CAAC,UAAU;QAAE,MAAM,IAAI,KAAK,CAAC,8BAA8B,CAAC,CAAC;IACjE,IAAI,UAAU,CAAC,MAAM,GAAG,GAAG,IAAI,8BAA8B,CAAC,IAAI,CAAC,UAAU,CAAC,EAAE,CAAC;QAChF,MAAM,IAAI,KAAK,CAAC,kDAAkD,CAAC,CAAC;IACrE,CAAC;IACD,OAAO,UAAU,CAAC;AACnB,CAAC;AAED,SAAS,mBAAmB,CAAC,MAAkB;IAC9C,MAAM,GAAG,GAAG,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,IAAI,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC;IACzD,IAAI,CAAC,GAAG;QAAE,OAAO,SAAS,CAAC;IAC3B,MAAM,WAAW,GAAG,SAAS,CAAC,GAAG,CAAC,CAAC;IACnC,MAAM,KAAK,GAAG,WAAW;SACvB,KAAK,CAAC,OAAO,CAAC;SACd,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC;SAC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C,OAAO,CAAC,CAAC;IAC5C,IAAI,CAAC,OAAO,CAAC,QAAQ,IAAI,eAAe,CAAC,EAAE,EAAE,CAAC;QAC7C,MAAM,IAAI,KAAK,CACd,uCAAuC,UAAU,kFAAkF,CACnI,CAAC;IACH,CAAC;IACD,IAAI,OAAO,CAAC,MAAM,EAAE,OAAO;QAAE,MAAM,IAAI,KAAK,CAAC,6BAA6B,CAAC,CAAC;IAE5E,MAAM,QAAQ,GAAG,YAAY,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;IAC9C,IAAI,QAAQ;QAAE,OAAO,kBAAkB,CAAC,QAAQ,EAAE,OAAO,CAAC,MAAM,CAAC,CAAC;IAClE,MAAM,KAAK,GAAG,YAAY,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC;IAChD,YAAY,CAAC,GAAG,CAAC,UAAU,EAAE,KAAK,CAAC,CAAC;IACpC,IAAI,CAAC;QACJ,MAAM,KAAK,CAAC;IACb,CAAC;YAAS,CAAC;QACV,IAAI,YAAY,CAAC,GAAG,CAAC,UAAU,CAAC,KAAK,KAAK;YAAE,YAAY,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;IAC7E,CAAC;AACF,CAAC;AAED,mGAAmG;AACnG,MAAM,CAAC,MAAM,+BAA+B,GAAmC,KAAK,EAAE,OAAO,EAAE,EAAE;IAChG,MAAM,sBAAsB,CAAC,OAAO,CAAC,OAAO,EAAE;QAC7C,GAAG,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;KACrD,CAAC,CAAC;IACH,OAAO,IAAI,CAAC;AACb,CAAC,CAAC","sourcesContent":["import type { InteractiveAuthRecoveryHandler } from \"@caupulican/pi-ai\";\nimport { stripAnsi } from \"../utils/ansi.ts\";\nimport { type ExecResult, execCommand } from \"./exec.ts\";\nimport { isWorkerSession } from \"./session-role.ts\";\n\nconst LOGIN_TIMEOUT_MS = 15 * 60_000;\nconst LOGIN_OUTPUT_LIMIT = 32 * 1024;\nconst ERROR_DETAIL_LIMIT = 512;\nconst activeLogins = new Map<string, Promise<void>>();\n\ntype ExecuteCommand = typeof execCommand;\n\nexport interface BedrockSsoLoginOptions {\n\tsignal?: AbortSignal;\n\texecute?: ExecuteCommand;\n\tisWorker?: () => boolean;\n\tcwd?: string;\n\tenv?: NodeJS.ProcessEnv;\n}\n\nfunction validateProfile(profile: string): string {\n\tconst normalized = profile.trim();\n\tif (!normalized) throw new Error(\"AWS profile name is required\");\n\tif (normalized.length > 256 || /[\\u0000-\\u001f\\u007f-\\u009f]/.test(normalized)) {\n\t\tthrow new Error(\"AWS profile name contains unsupported characters\");\n\t}\n\treturn normalized;\n}\n\nfunction compactOutputDetail(result: ExecResult): string | undefined {\n\tconst raw = result.stderr.trim() || result.stdout.trim();\n\tif (!raw) return undefined;\n\tconst withoutAnsi = stripAnsi(raw);\n\tconst lines = withoutAnsi\n\t\t.split(/\\r?\\n/)\n\t\t.map((line) => line.trim())\n\t\t.filter(Boolean);\n\tconst detail = lines.at(-1);\n\tif (!detail) return undefined;\n\treturn detail.length <= ERROR_DETAIL_LIMIT ? detail : `${detail.slice(0, ERROR_DETAIL_LIMIT - 1)}…`;\n}\n\nasync function executeLogin(profile: string, options: BedrockSsoLoginOptions): Promise<void> {\n\tconst execute = options.execute ?? execCommand;\n\tconst result = await execute(\"aws\", [\"sso\", \"login\", \"--profile\", profile], options.cwd ?? process.cwd(), {\n\t\tsignal: options.signal,\n\t\ttimeout: LOGIN_TIMEOUT_MS,\n\t\tenv: options.env ?? process.env,\n\t\tmaxBuffer: LOGIN_OUTPUT_LIMIT,\n\t});\n\tif (result.errorMessage) {\n\t\tconst detail = result.errorMessage.slice(0, ERROR_DETAIL_LIMIT);\n\t\tthrow new Error(`AWS CLI v2 is required for managed SSO login: ${detail}`);\n\t}\n\tif (result.killed) {\n\t\tthrow new Error(options.signal?.aborted ? \"AWS SSO login was cancelled\" : \"AWS SSO login timed out\");\n\t}\n\tif (result.code !== 0) {\n\t\tconst detail = compactOutputDetail(result) ?? `aws exited with code ${result.code}`;\n\t\tthrow new Error(`AWS SSO login failed for profile \"${profile}\": ${detail}`);\n\t}\n}\n\nfunction waitForSharedLogin(login: Promise<void>, signal: AbortSignal | undefined): Promise<void> {\n\tif (!signal) return login;\n\treturn new Promise<void>((resolve, reject) => {\n\t\tlet settled = false;\n\t\tconst finish = (settle: () => void) => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t\t\tsettle();\n\t\t};\n\t\tconst onAbort = () => finish(() => reject(new Error(\"AWS SSO login was cancelled\")));\n\t\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\t\tvoid login.then(\n\t\t\t() => finish(resolve),\n\t\t\t(error: unknown) => finish(() => reject(error)),\n\t\t);\n\t\tif (signal.aborted) onAbort();\n\t});\n}\n\n/** Run one foreground AWS SSO login per profile; concurrent callers share its terminal result. */\nexport async function loginBedrockSsoProfile(profile: string, options: BedrockSsoLoginOptions = {}): Promise<void> {\n\tconst normalized = validateProfile(profile);\n\tif ((options.isWorker ?? isWorkerSession)()) {\n\t\tthrow new Error(\n\t\t\t`AWS SSO authentication for profile \"${normalized}\" requires a user session; run /login amazon-bedrock in the owning user session.`,\n\t\t);\n\t}\n\tif (options.signal?.aborted) throw new Error(\"AWS SSO login was cancelled\");\n\n\tconst existing = activeLogins.get(normalized);\n\tif (existing) return waitForSharedLogin(existing, options.signal);\n\tconst login = executeLogin(normalized, options);\n\tactiveLogins.set(normalized, login);\n\ttry {\n\t\tawait login;\n\t} finally {\n\t\tif (activeLogins.get(normalized) === login) activeLogins.delete(normalized);\n\t}\n}\n\n/** Restore one request-owned Bedrock SSO session after the provider identifies explicit expiry. */\nexport const recoverBedrockSsoAuthentication: InteractiveAuthRecoveryHandler = async (request) => {\n\tawait loginBedrockSsoProfile(request.profile, {\n\t\t...(request.signal ? { signal: request.signal } : {}),\n\t});\n\treturn true;\n};\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"billing-failover-controller.d.ts","sourceRoot":"","sources":["../../src/core/billing-failover-controller.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,2BAA2B,CAAC;AACvD,OAAO,EAAE,KAAK,eAAe,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAC;AAClF,OAAO,KAAK,EAAO,gBAAgB,EAAS,MAAM,mBAAmB,CAAC;AAEtE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACzD,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,0BAA0B,CAAC;AAM1E,qBAAa,yBAAyB;IACrC,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAyC;IAEnE,aAAa,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,MAAM,GAAG,IAAI,CAE/C;IAED,WAAW,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAMhC;IAED,QAAQ,IAAI,MAAM,EAAE,CAEnB;CACD;AAED,MAAM,WAAW,6BAA6B;IAC7C,KAAK,EAAE,KAAK,CAAC;IACb,aAAa,EAAE,aAAa,CAAC;IAC7B,IAAI,CAAC,KAAK,EAAE;QAAE,IAAI,EAAE,SAAS,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,GAAG,IAAI,CAAC;IACxD,SAAS,EAAE,yBAAyB,CAAC;IACrC,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B,aAAa,CAAC,CAAC,IAAI,EAAE;QACpB,QAAQ,CAAC,EAAE,MAAM,CAAC;QAClB,OAAO,CAAC,EAAE,MAAM,CAAC;QACjB,OAAO,EAAE,MAAM,CAAC;QAChB,UAAU,EAAE,UAAU,CAAC,OAAO,eAAe,CAAC,CAAC;KAC/C,GAAG,IAAI,CAAC;CACT;AAED,qBAAa,yBAAyB;IACrC,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAgC;IACrD,OAAO,CAAC,UAAU,CAAqB;IAEvC,YAAY,IAAI,EAAE,6BAA6B,EAE9C;IAED,WAAW,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAEhC;IAED,iBAAiB,IAAI,MAAM,EAAE,CAE5B;IAED,aAAa,IAAI,MAAM,GAAG,SAAS,CAElC;IAED,SAAS,IAAI,yBAAyB,CAErC;IAEK,oBAAoB,CAAC,OAAO,EAAE,gBAAgB,EAAE,UAAU,CAAC,EAAE,eAAe,GAAG,OAAO,CAAC,OAAO,CAAC,CAwBpG;CACD","sourcesContent":["import type { Agent } from \"@caupulican/pi-agent-core\";\nimport { type ClassifiedError, classifyFailure } from \"@caupulican/pi-agent-core\";\nimport type { Api, AssistantMessage, Model } from \"@caupulican/pi-ai\";\nimport { decideBillingFailover } from \"./billing-failover.ts\";\nimport type { ModelRegistry } from \"./model-registry.ts\";\nimport type { ModelRouterFailoverStatus } from \"./model-router/status.ts\";\n\nconst DEFAULT_MODEL_PER_PROVIDER: Record<string, string> = {\n\t\"openai-codex\": \"gpt-5.6-sol\",\n};\n\nexport class ExhaustedProviderRegistry {\n\tprivate readonly exhausted = new Map<string, number | undefined>();\n\n\tmarkExhausted(ref: string, until?: number): void {\n\t\tthis.exhausted.set(ref, until);\n\t}\n\n\tisExhausted(ref: string): boolean {\n\t\tconst until = this.exhausted.get(ref);\n\t\tif (until === undefined) return this.exhausted.has(ref);\n\t\tif (Date.now() < until) return true;\n\t\tthis.exhausted.delete(ref);\n\t\treturn false;\n\t}\n\n\tsnapshot(): string[] {\n\t\treturn [...this.exhausted.keys()].filter((ref) => this.isExhausted(ref));\n\t}\n}\n\nexport interface BillingFailoverControllerDeps {\n\tagent: Agent;\n\tmodelRegistry: ModelRegistry;\n\temit(event: { type: \"warning\"; message: string }): void;\n\texhausted: ExhaustedProviderRegistry;\n\tsubscriptionHop?: boolean;\n\trecordFailure?(args: {\n\t\tprovider?: string;\n\t\tmodelId?: string;\n\t\tmessage: string;\n\t\tclassified: ReturnType<typeof classifyFailure>;\n\t}): void;\n}\n\nexport class BillingFailoverController {\n\tprivate readonly deps: BillingFailoverControllerDeps;\n\tprivate lastNotice: string | undefined;\n\n\tconstructor(deps: BillingFailoverControllerDeps) {\n\t\tthis.deps = deps;\n\t}\n\n\tisExhausted(ref: string): boolean {\n\t\treturn this.deps.exhausted.isExhausted(ref);\n\t}\n\n\tsnapshotExhausted(): string[] {\n\t\treturn this.deps.exhausted.snapshot();\n\t}\n\n\tgetLastNotice(): string | undefined {\n\t\treturn this.lastNotice;\n\t}\n\n\tgetStatus(): ModelRouterFailoverStatus {\n\t\treturn { exhausted: this.snapshotExhausted(), lastNotice: this.lastNotice };\n\t}\n\n\tasync handleAssistantError(message: AssistantMessage, classified?: ClassifiedError): Promise<boolean> {\n\t\tif (message.stopReason !== \"error\") return false;\n\t\tclassified ??= classifyFailure({ message: message.errorMessage ?? \"\", provider: message.provider });\n\t\tif (classified.reason !== \"billing_or_quota\") return false;\n\t\tconst failedModel = this.deps.modelRegistry.find(message.provider, message.model) ?? this.deps.agent.state.model;\n\t\tconst failedRef = `${failedModel.provider}/${failedModel.id}`;\n\t\tthis.deps.exhausted.markExhausted(failedRef, expiryFromRetryAfter(classified.retryAfterMs));\n\n\t\tconst defaultModelId = DEFAULT_MODEL_PER_PROVIDER[failedModel.provider];\n\t\tconst hop = defaultModelId ? this.deps.modelRegistry.find(failedModel.provider, defaultModelId) : undefined;\n\t\tconst action = decideBillingFailover({\n\t\t\tfailedModel: { provider: failedModel.provider, id: failedModel.id },\n\t\t\tbillingClass: this.deps.modelRegistry.isUsingOAuth(failedModel) ? \"subscription\" : \"metered\",\n\t\t\tproviderDefaultModelId: defaultModelId,\n\t\t\thopResolvesWithAuth: Boolean(hop && this.deps.modelRegistry.hasConfiguredAuth(hop)),\n\t\t\thopExhausted: hop ? this.deps.exhausted.isExhausted(`${hop.provider}/${hop.id}`) : false,\n\t\t\tsubscriptionHop: this.deps.subscriptionHop,\n\t\t});\n\t\tif (action.action === \"failover\") {\n\t\t\tthis.deps.agent.state.model = hop as Model<Api>;\n\t\t}\n\t\tthis.lastNotice = action.notice;\n\t\tthis.deps.emit({ type: \"warning\", message: action.notice });\n\t\treturn true;\n\t}\n}\n\nfunction expiryFromRetryAfter(retryAfterMs: number | undefined): number | undefined {\n\treturn retryAfterMs === undefined ? undefined : Date.now() + retryAfterMs;\n}\n"]}
1
+ {"version":3,"file":"billing-failover-controller.d.ts","sourceRoot":"","sources":["../../src/core/billing-failover-controller.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,2BAA2B,CAAC;AACvD,OAAO,EAAE,KAAK,eAAe,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAC;AAClF,OAAO,KAAK,EAAO,gBAAgB,EAAS,MAAM,mBAAmB,CAAC;AAEtE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACzD,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,0BAA0B,CAAC;AAM1E,qBAAa,yBAAyB;IACrC,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAyC;IAEnE,aAAa,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,MAAM,GAAG,IAAI,CAE/C;IAED,WAAW,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAMhC;IAED,QAAQ,IAAI,MAAM,EAAE,CAEnB;CACD;AAED,MAAM,WAAW,6BAA6B;IAC7C,KAAK,EAAE,KAAK,CAAC;IACb,aAAa,EAAE,aAAa,CAAC;IAC7B,IAAI,CAAC,KAAK,EAAE;QAAE,IAAI,EAAE,SAAS,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,GAAG,IAAI,CAAC;IACxD,SAAS,EAAE,yBAAyB,CAAC;IACrC,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B,aAAa,CAAC,CAAC,IAAI,EAAE;QACpB,QAAQ,CAAC,EAAE,MAAM,CAAC;QAClB,OAAO,CAAC,EAAE,MAAM,CAAC;QACjB,OAAO,EAAE,MAAM,CAAC;QAChB,UAAU,EAAE,UAAU,CAAC,OAAO,eAAe,CAAC,CAAC;KAC/C,GAAG,IAAI,CAAC;CACT;AAED,qBAAa,yBAAyB;IACrC,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAgC;IACrD,OAAO,CAAC,UAAU,CAAqB;IAEvC,YAAY,IAAI,EAAE,6BAA6B,EAE9C;IAED,WAAW,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAEhC;IAED,iBAAiB,IAAI,MAAM,EAAE,CAE5B;IAED,aAAa,IAAI,MAAM,GAAG,SAAS,CAElC;IAED,SAAS,IAAI,yBAAyB,CAErC;IAEK,oBAAoB,CAAC,OAAO,EAAE,gBAAgB,EAAE,UAAU,CAAC,EAAE,eAAe,GAAG,OAAO,CAAC,OAAO,CAAC,CAwBpG;CACD"}
@@ -4,7 +4,9 @@ const DEFAULT_MODEL_PER_PROVIDER = {
4
4
  "openai-codex": "gpt-5.6-sol",
5
5
  };
6
6
  export class ExhaustedProviderRegistry {
7
- exhausted = new Map();
7
+ constructor() {
8
+ this.exhausted = new Map();
9
+ }
8
10
  markExhausted(ref, until) {
9
11
  this.exhausted.set(ref, until);
10
12
  }
@@ -22,8 +24,6 @@ export class ExhaustedProviderRegistry {
22
24
  }
23
25
  }
24
26
  export class BillingFailoverController {
25
- deps;
26
- lastNotice;
27
27
  constructor(deps) {
28
28
  this.deps = deps;
29
29
  }
@@ -1 +1 @@
1
- {"version":3,"file":"billing-failover-controller.js","sourceRoot":"","sources":["../../src/core/billing-failover-controller.ts"],"names":[],"mappings":"AACA,OAAO,EAAwB,eAAe,EAAE,MAAM,2BAA2B,CAAC;AAElF,OAAO,EAAE,qBAAqB,EAAE,MAAM,uBAAuB,CAAC;AAI9D,MAAM,0BAA0B,GAA2B;IAC1D,cAAc,EAAE,aAAa;CAC7B,CAAC;AAEF,MAAM,OAAO,yBAAy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AAY,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,cAAc,CAAC,CAAC,CAAC,SAAS;YAC5F,sBAAsB,EAAE,cAAc;YACtC,mBAAmB,EAAE,OAAO,CAAC,GAAG,IAAI,IAAI,CAAC,IAAI,CAAC,aAAa,CAAC,iBAAiB,CAAC,GAAG,CAAC,CAAC;YACnF,YAAY,EAAE,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,WAAW,CAAC,GAAG,GAAG,CAAC,QAAQ,IAAI,GAAG,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,KAAK;YACxF,eAAe,EAAE,IAAI,CAAC,IAAI,CAAC,eAAe;SAC1C,CAAC,CAAC;QACH,IAAI,MAAM,CAAC,MAAM,KAAK,UAAU,EAAE,CAAC;YAClC,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,KAAK,GAAG,GAAiB,CAAC;QACjD,CAAC;QACD,IAAI,CAAC,UAAU,GAAG,MAAM,CAAC,MAAM,CAAC;QAChC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,CAAC,CAAC;QAC5D,OAAO,IAAI,CAAC;IAAA,CACZ;CACD;AAED,SAAS,oBAAoB,CAAC,YAAgC,EAAsB;IACnF,OAAO,YAAY,KAAK,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,YAAY,CAAC;AAAA,CAC1E","sourcesContent":["import type { Agent } from \"@caupulican/pi-agent-core\";\nimport { type ClassifiedError, classifyFailure } from \"@caupulican/pi-agent-core\";\nimport type { Api, AssistantMessage, Model } from \"@caupulican/pi-ai\";\nimport { decideBillingFailover } from \"./billing-failover.ts\";\nimport type { ModelRegistry } from \"./model-registry.ts\";\nimport type { ModelRouterFailoverStatus } from \"./model-router/status.ts\";\n\nconst DEFAULT_MODEL_PER_PROVIDER: Record<string, string> = {\n\t\"openai-codex\": \"gpt-5.6-sol\",\n};\n\nexport class ExhaustedProviderRegistry {\n\tprivate readonly exhausted = new Map<string, number | undefined>();\n\n\tmarkExhausted(ref: string, until?: number): void {\n\t\tthis.exhausted.set(ref, until);\n\t}\n\n\tisExhausted(ref: string): boolean {\n\t\tconst until = this.exhausted.get(ref);\n\t\tif (until === undefined) return this.exhausted.has(ref);\n\t\tif (Date.now() < until) return true;\n\t\tthis.exhausted.delete(ref);\n\t\treturn false;\n\t}\n\n\tsnapshot(): string[] {\n\t\treturn [...this.exhausted.keys()].filter((ref) => this.isExhausted(ref));\n\t}\n}\n\nexport interface BillingFailoverControllerDeps {\n\tagent: Agent;\n\tmodelRegistry: ModelRegistry;\n\temit(event: { type: \"warning\"; message: string }): void;\n\texhausted: ExhaustedProviderRegistry;\n\tsubscriptionHop?: boolean;\n\trecordFailure?(args: {\n\t\tprovider?: string;\n\t\tmodelId?: string;\n\t\tmessage: string;\n\t\tclassified: ReturnType<typeof classifyFailure>;\n\t}): void;\n}\n\nexport class BillingFailoverController {\n\tprivate readonly deps: BillingFailoverControllerDeps;\n\tprivate lastNotice: string | undefined;\n\n\tconstructor(deps: BillingFailoverControllerDeps) {\n\t\tthis.deps = deps;\n\t}\n\n\tisExhausted(ref: string): boolean {\n\t\treturn this.deps.exhausted.isExhausted(ref);\n\t}\n\n\tsnapshotExhausted(): string[] {\n\t\treturn this.deps.exhausted.snapshot();\n\t}\n\n\tgetLastNotice(): string | undefined {\n\t\treturn this.lastNotice;\n\t}\n\n\tgetStatus(): ModelRouterFailoverStatus {\n\t\treturn { exhausted: this.snapshotExhausted(), lastNotice: this.lastNotice };\n\t}\n\n\tasync handleAssistantError(message: AssistantMessage, classified?: ClassifiedError): Promise<boolean> {\n\t\tif (message.stopReason !== \"error\") return false;\n\t\tclassified ??= classifyFailure({ message: message.errorMessage ?? \"\", provider: message.provider });\n\t\tif (classified.reason !== \"billing_or_quota\") return false;\n\t\tconst failedModel = this.deps.modelRegistry.find(message.provider, message.model) ?? this.deps.agent.state.model;\n\t\tconst failedRef = `${failedModel.provider}/${failedModel.id}`;\n\t\tthis.deps.exhausted.markExhausted(failedRef, expiryFromRetryAfter(classified.retryAfterMs));\n\n\t\tconst defaultModelId = DEFAULT_MODEL_PER_PROVIDER[failedModel.provider];\n\t\tconst hop = defaultModelId ? this.deps.modelRegistry.find(failedModel.provider, defaultModelId) : undefined;\n\t\tconst action = decideBillingFailover({\n\t\t\tfailedModel: { provider: failedModel.provider, id: failedModel.id },\n\t\t\tbillingClass: this.deps.modelRegistry.isUsingOAuth(failedModel) ? \"subscription\" : \"metered\",\n\t\t\tproviderDefaultModelId: defaultModelId,\n\t\t\thopResolvesWithAuth: Boolean(hop && this.deps.modelRegistry.hasConfiguredAuth(hop)),\n\t\t\thopExhausted: hop ? this.deps.exhausted.isExhausted(`${hop.provider}/${hop.id}`) : false,\n\t\t\tsubscriptionHop: this.deps.subscriptionHop,\n\t\t});\n\t\tif (action.action === \"failover\") {\n\t\t\tthis.deps.agent.state.model = hop as Model<Api>;\n\t\t}\n\t\tthis.lastNotice = action.notice;\n\t\tthis.deps.emit({ type: \"warning\", message: action.notice });\n\t\treturn true;\n\t}\n}\n\nfunction expiryFromRetryAfter(retryAfterMs: number | undefined): number | undefined {\n\treturn retryAfterMs === undefined ? undefined : Date.now() + retryAfterMs;\n}\n"]}
1
+ {"version":3,"file":"billing-failover-controller.js","sourceRoot":"","sources":["../../src/core/billing-failover-controller.ts"],"names":[],"mappings":"AACA,OAAO,EAAwB,eAAe,EAAE,MAAM,2BAA2B,CAAC;AAElF,OAAO,EAAE,qBAAqB,EAAE,MAAM,uBAAuB,CAAC;AAI9D,MAAM,0BAA0B,GAA2B;IAC1D,cAAc,EAAE,aAAa;CAC7B,CAAC;AAEF,MAAM,OAAO,yBAAyB;IAAtC;QACkB,cAAS,GAAG,IAAI,GAAG,EAA8B,CAAC;IAiBpE,CAAC;IAfA,aAAa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I,CAAC,aAAa,CAAC,iBAAiB,CAAC,GAAG,CAAC,CAAC;YACnF,YAAY,EAAE,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,WAAW,CAAC,GAAG,GAAG,CAAC,QAAQ,IAAI,GAAG,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,KAAK;YACxF,eAAe,EAAE,IAAI,CAAC,IAAI,CAAC,eAAe;SAC1C,CAAC,CAAC;QACH,IAAI,MAAM,CAAC,MAAM,KAAK,UAAU,EAAE,CAAC;YAClC,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,KAAK,GAAG,GAAiB,CAAC;QACjD,CAAC;QACD,IAAI,CAAC,UAAU,GAAG,MAAM,CAAC,MAAM,CAAC;QAChC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,CAAC,CAAC;QAC5D,OAAO,IAAI,CAAC;IACb,CAAC;CACD;AAED,SAAS,oBAAoB,CAAC,YAAgC;IAC7D,OAAO,YAAY,KAAK,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,YAAY,CAAC;AAC3E,CAAC","sourcesContent":["import type { Agent } from \"@caupulican/pi-agent-core\";\nimport { type ClassifiedError, classifyFailure } from \"@caupulican/pi-agent-core\";\nimport type { Api, AssistantMessage, Model } from \"@caupulican/pi-ai\";\nimport { decideBillingFailover } from \"./billing-failover.ts\";\nimport type { ModelRegistry } from \"./model-registry.ts\";\nimport type { ModelRouterFailoverStatus } from \"./model-router/status.ts\";\n\nconst DEFAULT_MODEL_PER_PROVIDER: Record<string, string> = {\n\t\"openai-codex\": \"gpt-5.6-sol\",\n};\n\nexport class ExhaustedProviderRegistry {\n\tprivate readonly exhausted = new Map<string, number | undefined>();\n\n\tmarkExhausted(ref: string, until?: number): void {\n\t\tthis.exhausted.set(ref, until);\n\t}\n\n\tisExhausted(ref: string): boolean {\n\t\tconst until = this.exhausted.get(ref);\n\t\tif (until === undefined) return this.exhausted.has(ref);\n\t\tif (Date.now() < until) return true;\n\t\tthis.exhausted.delete(ref);\n\t\treturn false;\n\t}\n\n\tsnapshot(): string[] {\n\t\treturn [...this.exhausted.keys()].filter((ref) => this.isExhausted(ref));\n\t}\n}\n\nexport interface BillingFailoverControllerDeps {\n\tagent: Agent;\n\tmodelRegistry: ModelRegistry;\n\temit(event: { type: \"warning\"; message: string }): void;\n\texhausted: ExhaustedProviderRegistry;\n\tsubscriptionHop?: boolean;\n\trecordFailure?(args: {\n\t\tprovider?: string;\n\t\tmodelId?: string;\n\t\tmessage: string;\n\t\tclassified: ReturnType<typeof classifyFailure>;\n\t}): void;\n}\n\nexport class BillingFailoverController {\n\tprivate readonly deps: BillingFailoverControllerDeps;\n\tprivate lastNotice: string | undefined;\n\n\tconstructor(deps: BillingFailoverControllerDeps) {\n\t\tthis.deps = deps;\n\t}\n\n\tisExhausted(ref: string): boolean {\n\t\treturn this.deps.exhausted.isExhausted(ref);\n\t}\n\n\tsnapshotExhausted(): string[] {\n\t\treturn this.deps.exhausted.snapshot();\n\t}\n\n\tgetLastNotice(): string | undefined {\n\t\treturn this.lastNotice;\n\t}\n\n\tgetStatus(): ModelRouterFailoverStatus {\n\t\treturn { exhausted: this.snapshotExhausted(), lastNotice: this.lastNotice };\n\t}\n\n\tasync handleAssistantError(message: AssistantMessage, classified?: ClassifiedError): Promise<boolean> {\n\t\tif (message.stopReason !== \"error\") return false;\n\t\tclassified ??= classifyFailure({ message: message.errorMessage ?? \"\", provider: message.provider });\n\t\tif (classified.reason !== \"billing_or_quota\") return false;\n\t\tconst failedModel = this.deps.modelRegistry.find(message.provider, message.model) ?? this.deps.agent.state.model;\n\t\tconst failedRef = `${failedModel.provider}/${failedModel.id}`;\n\t\tthis.deps.exhausted.markExhausted(failedRef, expiryFromRetryAfter(classified.retryAfterMs));\n\n\t\tconst defaultModelId = DEFAULT_MODEL_PER_PROVIDER[failedModel.provider];\n\t\tconst hop = defaultModelId ? this.deps.modelRegistry.find(failedModel.provider, defaultModelId) : undefined;\n\t\tconst action = decideBillingFailover({\n\t\t\tfailedModel: { provider: failedModel.provider, id: failedModel.id },\n\t\t\tbillingClass: this.deps.modelRegistry.isUsingOAuth(failedModel) ? \"subscription\" : \"metered\",\n\t\t\tproviderDefaultModelId: defaultModelId,\n\t\t\thopResolvesWithAuth: Boolean(hop && this.deps.modelRegistry.hasConfiguredAuth(hop)),\n\t\t\thopExhausted: hop ? this.deps.exhausted.isExhausted(`${hop.provider}/${hop.id}`) : false,\n\t\t\tsubscriptionHop: this.deps.subscriptionHop,\n\t\t});\n\t\tif (action.action === \"failover\") {\n\t\t\tthis.deps.agent.state.model = hop as Model<Api>;\n\t\t}\n\t\tthis.lastNotice = action.notice;\n\t\tthis.deps.emit({ type: \"warning\", message: action.notice });\n\t\treturn true;\n\t}\n}\n\nfunction expiryFromRetryAfter(retryAfterMs: number | undefined): number | undefined {\n\treturn retryAfterMs === undefined ? undefined : Date.now() + retryAfterMs;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"billing-failover.d.ts","sourceRoot":"","sources":["../../src/core/billing-failover.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,YAAY,GAAG,cAAc,GAAG,SAAS,CAAC;AAEtD,MAAM,MAAM,qBAAqB,GAC9B;IAAE,MAAM,EAAE,UAAU,CAAC;IAAC,EAAE,EAAE;QAAE,QAAQ,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,GACjF;IAAE,MAAM,EAAE,UAAU,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAAC;AAE1C,MAAM,WAAW,oBAAoB;IACpC,WAAW,EAAE;QAAE,QAAQ,EAAE,MAAM,CAAC;QAAC,EAAE,EAAE,MAAM,CAAA;KAAE,CAAC;IAC9C,YAAY,EAAE,YAAY,CAAC;IAC3B,sBAAsB,EAAE,MAAM,GAAG,SAAS,CAAC;IAC3C,mBAAmB,EAAE,OAAO,CAAC;IAC7B,YAAY,EAAE,OAAO,CAAC;IACtB,eAAe,CAAC,EAAE,OAAO,CAAC;CAC1B;AAMD,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,oBAAoB,GAAG,qBAAqB,CAkBxF","sourcesContent":["export type BillingClass = \"subscription\" | \"metered\";\n\nexport type BillingFailoverAction =\n\t| { action: \"failover\"; to: { provider: string; modelId: string }; notice: string }\n\t| { action: \"halt_ask\"; notice: string };\n\nexport interface BillingFailoverInput {\n\tfailedModel: { provider: string; id: string };\n\tbillingClass: BillingClass;\n\tproviderDefaultModelId: string | undefined;\n\thopResolvesWithAuth: boolean;\n\thopExhausted: boolean;\n\tsubscriptionHop?: boolean;\n}\n\nfunction haltNotice(provider: string, modelId: string): string {\n\treturn `Provider quota/limit reached for ${provider}/${modelId}: switch models (/model), wait for the limit window, or re-send to retry`;\n}\n\nexport function decideBillingFailover(input: BillingFailoverInput): BillingFailoverAction {\n\tconst { failedModel, providerDefaultModelId } = input;\n\tconst subscriptionHop = input.subscriptionHop ?? true;\n\tif (\n\t\tinput.billingClass === \"subscription\" &&\n\t\tsubscriptionHop &&\n\t\tproviderDefaultModelId &&\n\t\tproviderDefaultModelId !== failedModel.id &&\n\t\tinput.hopResolvesWithAuth &&\n\t\t!input.hopExhausted\n\t) {\n\t\treturn {\n\t\t\taction: \"failover\",\n\t\t\tto: { provider: failedModel.provider, modelId: providerDefaultModelId },\n\t\t\tnotice: `${failedModel.id} quota reached — switched to ${failedModel.provider}/${providerDefaultModelId}`,\n\t\t};\n\t}\n\treturn { action: \"halt_ask\", notice: haltNotice(failedModel.provider, failedModel.id) };\n}\n"]}
1
+ {"version":3,"file":"billing-failover.d.ts","sourceRoot":"","sources":["../../src/core/billing-failover.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,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QACF,OAAO;YACN,MAAM,EAAE,UAAU;YAClB,EAAE,EAAE,EAAE,QAAQ,EAAE,WAAW,CAAC,QAAQ,EAAE,OAAO,EAAE,sBAAsB,EAAE;YACvE,MAAM,EAAE,GAAG,WAAW,CAAC,EAAE,kCAAgC,WAAW,CAAC,QAAQ,IAAI,sBAAsB,EAAE;SACzG,CAAC;IACH,CAAC;IACD,OAAO,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,EAAE,UAAU,CAAC,WAAW,CAAC,QAAQ,EAAE,WAAW,CAAC,EAAE,CAAC,EAAE,CAAC;AAAA,CACxF","sourcesContent":["export type BillingClass = \"subscription\" | \"metered\";\n\nexport type BillingFailoverAction =\n\t| { action: \"failover\"; to: { provider: string; modelId: string }; notice: string }\n\t| { action: \"halt_ask\"; notice: string };\n\nexport interface BillingFailoverInput {\n\tfailedModel: { provider: string; id: string };\n\tbillingClass: BillingClass;\n\tproviderDefaultModelId: string | undefined;\n\thopResolvesWithAuth: boolean;\n\thopExhausted: boolean;\n\tsubscriptionHop?: boolean;\n}\n\nfunction haltNotice(provider: string, modelId: string): string {\n\treturn `Provider quota/limit reached for ${provider}/${modelId}: switch models (/model), wait for the limit window, or re-send to retry`;\n}\n\nexport function decideBillingFailover(input: BillingFailoverInput): BillingFailoverAction {\n\tconst { failedModel, providerDefaultModelId } = input;\n\tconst subscriptionHop = input.subscriptionHop ?? true;\n\tif (\n\t\tinput.billingClass === \"subscription\" &&\n\t\tsubscriptionHop &&\n\t\tproviderDefaultModelId &&\n\t\tproviderDefaultModelId !== failedModel.id &&\n\t\tinput.hopResolvesWithAuth &&\n\t\t!input.hopExhausted\n\t) {\n\t\treturn {\n\t\t\taction: \"failover\",\n\t\t\tto: { provider: failedModel.provider, modelId: providerDefaultModelId },\n\t\t\tnotice: `${failedModel.id} quota reached — switched to ${failedModel.provider}/${providerDefaultModelId}`,\n\t\t};\n\t}\n\treturn { action: \"halt_ask\", notice: haltNotice(failedModel.provider, failedModel.id) };\n}\n"]}
1
+ {"version":3,"file":"billing-failover.js","sourceRoot":"","sources":["../../src/core/billing-failover.ts"],"names":[],"mappings":"AAeA,SAAS,UAAU,CAAC,QAAgB,EAAE,OAAe;IACpD,OAAO,oCAAoC,QAAQ,IAAI,OAAO,0EAA0E,CAAC;AAC1I,CAAC;AAED,MAAM,UAAU,qBAAqB,CAAC,KAA2B;IAChE,MAAM,EAAE,WAAW,EAAE,sBAAsB,EAAE,GAAG,KAAK,CAAC;IACtD,MAAM,eAAe,GAAG,KAAK,CAAC,eAAe,IAAI,IAAI,CAAC;IACtD,IACC,KAAK,CAAC,YAAY,KAAK,cAAc;QACrC,eAAe;QACf,sBAAsB;QACtB,sBAAsB,KAAK,WAAW,CAAC,EAAE;QACzC,KAAK,CAAC,mBAAmB;QACzB,CAAC,KAAK,CAAC,YAAY,EAClB,CAAC;QACF,OAAO;YACN,MAAM,EAAE,UAAU;YAClB,EAAE,EAAE,EAAE,QAAQ,EAAE,WAAW,CAAC,QAAQ,EAAE,OAAO,EAAE,sBAAsB,EAAE;YACvE,MAAM,EAAE,GAAG,WAAW,CAAC,EAAE,gCAAgC,WAAW,CAAC,QAAQ,IAAI,sBAAsB,EAAE;SACzG,CAAC;IACH,CAAC;IACD,OAAO,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,EAAE,UAAU,CAAC,WAAW,CAAC,QAAQ,EAAE,WAAW,CAAC,EAAE,CAAC,EAAE,CAAC;AACzF,CAAC","sourcesContent":["export type BillingClass = \"subscription\" | \"metered\";\n\nexport type BillingFailoverAction =\n\t| { action: \"failover\"; to: { provider: string; modelId: string }; notice: string }\n\t| { action: \"halt_ask\"; notice: string };\n\nexport interface BillingFailoverInput {\n\tfailedModel: { provider: string; id: string };\n\tbillingClass: BillingClass;\n\tproviderDefaultModelId: string | undefined;\n\thopResolvesWithAuth: boolean;\n\thopExhausted: boolean;\n\tsubscriptionHop?: boolean;\n}\n\nfunction haltNotice(provider: string, modelId: string): string {\n\treturn `Provider quota/limit reached for ${provider}/${modelId}: switch models (/model), wait for the limit window, or re-send to retry`;\n}\n\nexport function decideBillingFailover(input: BillingFailoverInput): BillingFailoverAction {\n\tconst { failedModel, providerDefaultModelId } = input;\n\tconst subscriptionHop = input.subscriptionHop ?? true;\n\tif (\n\t\tinput.billingClass === \"subscription\" &&\n\t\tsubscriptionHop &&\n\t\tproviderDefaultModelId &&\n\t\tproviderDefaultModelId !== failedModel.id &&\n\t\tinput.hopResolvesWithAuth &&\n\t\t!input.hopExhausted\n\t) {\n\t\treturn {\n\t\t\taction: \"failover\",\n\t\t\tto: { provider: failedModel.provider, modelId: providerDefaultModelId },\n\t\t\tnotice: `${failedModel.id} quota reached — switched to ${failedModel.provider}/${providerDefaultModelId}`,\n\t\t};\n\t}\n\treturn { action: \"halt_ask\", notice: haltNotice(failedModel.provider, failedModel.id) };\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"capability-contract.d.ts","sourceRoot":"","sources":["../../src/core/capability-contract.ts"],"names":[],"mappings":"AAAA,6EAA6E;AAC7E,eAAO,MAAM,oBAAoB,ibAyBvB,CAAC;AAEX,MAAM,MAAM,iBAAiB,GAAG,CAAC,OAAO,oBAAoB,CAAC,CAAC,MAAM,CAAC,CAAC","sourcesContent":["/** Canonical semantic authority vocabulary shared by every harness plane. */\nexport const HARNESS_CAPABILITIES = [\n\t\"filesystem.read\",\n\t\"filesystem.write\",\n\t\"process.exec\",\n\t\"network.http\",\n\t\"service.mcp\",\n\t\"credentials.use\",\n\t\"credentials.modify\",\n\t\"tests.execute\",\n\t\"worktree.read\",\n\t\"worktree.mutate\",\n\t\"memory.query\",\n\t\"memory.mutate\",\n\t\"settings.read\",\n\t\"settings.write\",\n\t\"skill.read\",\n\t\"skill.write\",\n\t\"source.read\",\n\t\"source.write\",\n\t\"research.execute\",\n\t\"workflow.plan\",\n\t\"workflow.delegate\",\n\t\"policy.modify\",\n\t\"learning.propose\",\n\t\"publish.execute\",\n] as const;\n\nexport type HarnessCapability = (typeof HARNESS_CAPABILITIES)[number];\n"]}
1
+ {"version":3,"file":"capability-contract.d.ts","sourceRoot":"","sources":["../../src/core/capability-contract.ts"],"names":[],"mappings":"AAAA,6EAA6E;AAC7E,eAAO,MAAM,oBAAoB,YAChC,iBAAiB,EACjB,kBAAkB,EAClB,cAAc,EACd,cAAc,EACd,aAAa,EACb,iBAAiB,EACjB,oBAAoB,EACpB,eAAe,EACf,eAAe,EACf,iBAAiB,EACjB,cAAc,EACd,eAAe,EACf,eAAe,EACf,gBAAgB,EAChB,YAAY,EACZ,aAAa,EACb,aAAa,EACb,cAAc,EACd,kBAAkB,EAClB,eAAe,EACf,mBAAmB,EACnB,eAAe,EACf,kBAAkB,EAClB,iBAAiB,CACR,CAAC;AAEX,MAAM,MAAM,iBAAiB,GAAG,CAAC,OAAO,oBAAoB,CAAC,CAAC,MAAM,CAAC,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"catalog-manager.d.ts","sourceRoot":"","sources":["../../src/core/catalog-manager.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAMH,eAAO,MAAM,aAAa,kEAAmE,CAAC;AAC9F,MAAM,MAAM,WAAW,GAAG,CAAC,OAAO,aAAa,CAAC,CAAC,MAAM,CAAC,CAAC;AAEzD,MAAM,MAAM,aAAa,GAAG,eAAe,GAAG,YAAY,GAAG,UAAU,CAAC;AAExE,MAAM,WAAW,YAAY;IAC5B,IAAI,EAAE,WAAW,CAAC;IAClB,gEAAgE;IAChE,IAAI,EAAE,MAAM,CAAC;IACb,iDAAiD;IACjD,WAAW,EAAE,MAAM,CAAC;IACpB,qDAAqD;IACrD,WAAW,EAAE,MAAM,CAAC;CACpB;AAED,qBAAa,cAAc;IAC1B,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAS;IAClC,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAS;IAEpC,YAAY,QAAQ,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,EAG/C;IAED,kEAAkE;IAClE,IAAI,IAAI,YAAY,EAAE,CAsBrB;IAED,+EAA+E;IAC/E,MAAM,CAAC,KAAK,EAAE,YAAY,GAAG,aAAa,CAGzC;IAED,mFAAmF;IACnF,OAAO,CAAC,KAAK,EAAE,YAAY,GAAG,IAAI,CAEjC;IAED;;;OAGG;IACH,MAAM,IAAI,YAAY,EAAE,CASvB;IAED,qGAAqG;IACrG,MAAM,CAAC,KAAK,EAAE,YAAY,GAAG,IAAI,CAKhC;CACD;AAqBD;;;;GAIG;AACH,wBAAgB,QAAQ,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAwC/C","sourcesContent":["/**\n * CatalogManager — round resource management (resource-management design).\n *\n * A user-pointed **catalog directory** (a folder/repo holding `{skills,extensions,agents,prompts,themes}`)\n * is the easy-to-setup source of a user's workflows. From it pi can:\n * - **install** a resource = copy it into the pi user level (`<agentDir>/<kind>/`),\n * - **update** = hash-compare what's installed against the catalog and re-sync changed/outdated ones,\n * - **backup** = copy a user-level resource back into the catalog.\n * Per machine, the user installs only the subset they want; `update` refreshes exactly those.\n *\n * Copies are content-recursive (`cpSync`); status is decided by a recursive content hash so it is\n * portable across machines (mtimes differ; content does not).\n */\n\nimport { createHash, randomBytes } from \"node:crypto\";\nimport { cpSync, existsSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, statSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\nexport const CATALOG_KINDS = [\"skills\", \"extensions\", \"agents\", \"prompts\", \"themes\"] as const;\nexport type CatalogKind = (typeof CATALOG_KINDS)[number];\n\nexport type CatalogStatus = \"not-installed\" | \"up-to-date\" | \"outdated\";\n\nexport interface CatalogEntry {\n\tkind: CatalogKind;\n\t/** Top-level name in the catalog (a directory or file name). */\n\tname: string;\n\t/** Absolute path of the entry in the catalog. */\n\tcatalogPath: string;\n\t/** Absolute path where it installs at user level. */\n\tinstallPath: string;\n}\n\nexport class CatalogManager {\n\tprivate readonly agentDir: string;\n\tprivate readonly catalogDir: string;\n\n\tconstructor(agentDir: string, catalogDir: string) {\n\t\tthis.agentDir = agentDir;\n\t\tthis.catalogDir = catalogDir;\n\t}\n\n\t/** Every resource discovered in the catalog, across all kinds. */\n\tlist(): CatalogEntry[] {\n\t\tconst entries: CatalogEntry[] = [];\n\t\tfor (const kind of CATALOG_KINDS) {\n\t\t\tconst kindDir = join(this.catalogDir, kind);\n\t\t\tif (!existsSync(kindDir)) continue;\n\t\t\tlet names: string[];\n\t\t\ttry {\n\t\t\t\tnames = readdirSync(kindDir);\n\t\t\t} catch {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tfor (const name of names) {\n\t\t\t\tif (name.startsWith(\".\")) continue;\n\t\t\t\tentries.push({\n\t\t\t\t\tkind,\n\t\t\t\t\tname,\n\t\t\t\t\tcatalogPath: join(kindDir, name),\n\t\t\t\t\tinstallPath: join(this.agentDir, kind, name),\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\treturn entries;\n\t}\n\n\t/** Status of one catalog entry relative to what is installed at user level. */\n\tstatus(entry: CatalogEntry): CatalogStatus {\n\t\tif (!existsSync(entry.installPath)) return \"not-installed\";\n\t\treturn hashPath(entry.catalogPath) === hashPath(entry.installPath) ? \"up-to-date\" : \"outdated\";\n\t}\n\n\t/** Copy a catalog entry into the user level (install or overwrite), atomically. */\n\tinstall(entry: CatalogEntry): void {\n\t\tsafeCopy(entry.catalogPath, entry.installPath);\n\t}\n\n\t/**\n\t * Re-sync every INSTALLED resource that is outdated relative to the catalog (catalog → user level).\n\t * Never installs things the user has not already chosen on this machine. Returns the updated entries.\n\t */\n\tupdate(): CatalogEntry[] {\n\t\tconst updated: CatalogEntry[] = [];\n\t\tfor (const entry of this.list()) {\n\t\t\tif (this.status(entry) === \"outdated\") {\n\t\t\t\tthis.install(entry);\n\t\t\t\tupdated.push(entry);\n\t\t\t}\n\t\t}\n\t\treturn updated;\n\t}\n\n\t/** Copy a user-level resource back into the catalog (backup). Requires it to exist at user level. */\n\tbackup(entry: CatalogEntry): void {\n\t\tif (!existsSync(entry.installPath)) {\n\t\t\tthrow new Error(`Cannot back up \"${entry.kind}/${entry.name}\": not installed at user level.`);\n\t\t}\n\t\tsafeCopy(entry.installPath, entry.catalogPath);\n\t}\n}\n\n/**\n * Copy `src` over `dest` without ever leaving a partially-copied tree at `dest` (Bug #18): copy into a\n * sibling temp first, then swap it into place; on any failure the temp is removed and `dest` is left\n * untouched.\n */\nfunction safeCopy(src: string, dest: string): void {\n\tconst tmp = `${dest}.pi-tmp-${randomBytes(6).toString(\"hex\")}`;\n\ttry {\n\t\tcpSync(src, tmp, { recursive: true, force: true });\n\t\trmSync(dest, { recursive: true, force: true });\n\t\trenameSync(tmp, dest);\n\t} catch (err) {\n\t\ttry {\n\t\t\trmSync(tmp, { recursive: true, force: true });\n\t\t} catch {}\n\t\tthrow err;\n\t}\n}\n\n/**\n * Content hash of a file or directory tree: stable across machines (ignores mtimes/paths outside the\n * tree). Files contribute their relative path + bytes; directories are walked in sorted order so the\n * hash is deterministic.\n */\nexport function hashPath(target: string): string {\n\tconst hash = createHash(\"sha256\");\n\tconst seen = new Set<string>(); // real paths already visited — breaks circular symlinks (Bug #19)\n\tconst walk = (abs: string, rel: string, depth: number): void => {\n\t\tif (depth > 64) return; // hard depth cap as a backstop\n\t\tlet real: string;\n\t\ttry {\n\t\t\treal = realpathSync(abs);\n\t\t} catch {\n\t\t\treturn;\n\t\t}\n\t\tif (seen.has(real)) return; // already walked (symlink loop or shared target)\n\t\tseen.add(real);\n\t\tlet stats: ReturnType<typeof statSync>;\n\t\ttry {\n\t\t\tstats = statSync(abs);\n\t\t} catch {\n\t\t\treturn;\n\t\t}\n\t\tif (stats.isDirectory()) {\n\t\t\tlet children: string[];\n\t\t\ttry {\n\t\t\t\tchildren = readdirSync(abs).sort();\n\t\t\t} catch {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tfor (const child of children) {\n\t\t\t\twalk(join(abs, child), rel ? `${rel}/${child}` : child, depth + 1);\n\t\t\t}\n\t\t} else if (stats.isFile()) {\n\t\t\thash.update(`\u0000${rel}\u0000`);\n\t\t\ttry {\n\t\t\t\thash.update(readFileSync(abs));\n\t\t\t} catch {\n\t\t\t\t// unreadable file → contributes only its path\n\t\t\t}\n\t\t}\n\t};\n\twalk(target, \"\", 0);\n\treturn hash.digest(\"hex\");\n}\n"]}
1
+ {"version":3,"file":"catalog-manager.d.ts","sourceRoot":"","sources":["../../src/core/catalog-manager.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAMH,eAAO,MAAM,aAAa,YAAI,QAAQ,EAAE,YAAY,EAAE,QAAQ,EAAE,SAAS,EAAE,QAAQ,CAAU,CAAC;AAC9F,MAAM,MAAM,WAAW,GAAG,CAAC,OAAO,aAAa,CAAC,CAAC,MAAM,CAAC,CAAC;AAEzD,MAAM,MAAM,aAAa,GAAG,eAAe,GAAG,YAAY,GAAG,UAAU,CAAC;AAExE,MAAM,WAAW,YAAY;IAC5B,IAAI,EAAE,WAAW,CAAC;IAClB,gEAAgE;IAChE,IAAI,EAAE,MAAM,CAAC;IACb,iDAAiD;IACjD,WAAW,EAAE,MAAM,CAAC;IACpB,qDAAqD;IACrD,WAAW,EAAE,MAAM,CAAC;CACpB;AAED,qBAAa,cAAc;IAC1B,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAS;IAClC,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAS;IAEpC,YAAY,QAAQ,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,EAG/C;IAED,kEAAkE;IAClE,IAAI,IAAI,YAAY,EAAE,CAsBrB;IAED,+EAA+E;IAC/E,MAAM,CAAC,KAAK,EAAE,YAAY,GAAG,aAAa,CAGzC;IAED,mFAAmF;IACnF,OAAO,CAAC,KAAK,EAAE,YAAY,GAAG,IAAI,CAEjC;IAED;;;OAGG;IACH,MAAM,IAAI,YAAY,EAAE,CASvB;IAED,qGAAqG;IACrG,MAAM,CAAC,KAAK,EAAE,YAAY,GAAG,IAAI,CAKhC;CACD;AAq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CatalogManager — round resource management (resource-management design).\n *\n * A user-pointed **catalog directory** (a folder/repo holding `{skills,extensions,agents,prompts,themes}`)\n * is the easy-to-setup source of a user's workflows. From it pi can:\n * - **install** a resource = copy it into the pi user level (`<agentDir>/<kind>/`),\n * - **update** = hash-compare what's installed against the catalog and re-sync changed/outdated ones,\n * - **backup** = copy a user-level resource back into the catalog.\n * Per machine, the user installs only the subset they want; `update` refreshes exactly those.\n *\n * Copies are content-recursive (`cpSync`); status is decided by a recursive content hash so it is\n * portable across machines (mtimes differ; content does not).\n */\n\nimport { createHash, randomBytes } from \"node:crypto\";\nimport { cpSync, existsSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, statSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\nexport const CATALOG_KINDS = [\"skills\", \"extensions\", \"agents\", \"prompts\", \"themes\"] as const;\nexport type CatalogKind = (typeof CATALOG_KINDS)[number];\n\nexport type CatalogStatus = \"not-installed\" | \"up-to-date\" | \"outdated\";\n\nexport interface CatalogEntry {\n\tkind: CatalogKind;\n\t/** Top-level name in the catalog (a directory or file name). */\n\tname: string;\n\t/** Absolute path of the entry in the catalog. */\n\tcatalogPath: string;\n\t/** Absolute path where it installs at user level. */\n\tinstallPath: string;\n}\n\nexport class CatalogManager {\n\tprivate readonly agentDir: string;\n\tprivate readonly catalogDir: string;\n\n\tconstructor(agentDir: string, catalogDir: string) {\n\t\tthis.agentDir = agentDir;\n\t\tthis.catalogDir = catalogDir;\n\t}\n\n\t/** Every resource discovered in the catalog, across all kinds. */\n\tlist(): CatalogEntry[] {\n\t\tconst entries: CatalogEntry[] = [];\n\t\tfor (const kind of CATALOG_KINDS) {\n\t\t\tconst kindDir = join(this.catalogDir, kind);\n\t\t\tif (!existsSync(kindDir)) continue;\n\t\t\tlet names: string[];\n\t\t\ttry {\n\t\t\t\tnames = readdirSync(kindDir);\n\t\t\t} catch {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tfor (const name of names) {\n\t\t\t\tif (name.startsWith(\".\")) continue;\n\t\t\t\tentries.push({\n\t\t\t\t\tkind,\n\t\t\t\t\tname,\n\t\t\t\t\tcatalogPath: join(kindDir, name),\n\t\t\t\t\tinstallPath: join(this.agentDir, kind, name),\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\treturn entries;\n\t}\n\n\t/** Status of one catalog entry relative to what is installed at user level. */\n\tstatus(entry: CatalogEntry): CatalogStatus {\n\t\tif (!existsSync(entry.installPath)) return \"not-installed\";\n\t\treturn hashPath(entry.catalogPath) === hashPath(entry.installPath) ? \"up-to-date\" : \"outdated\";\n\t}\n\n\t/** Copy a catalog entry into the user level (install or overwrite), atomically. */\n\tinstall(entry: CatalogEntry): void {\n\t\tsafeCopy(entry.catalogPath, entry.installPath);\n\t}\n\n\t/**\n\t * Re-sync every INSTALLED resource that is outdated relative to the catalog (catalog → user level).\n\t * Never installs things the user has not already chosen on this machine. Returns the updated entries.\n\t */\n\tupdate(): CatalogEntry[] {\n\t\tconst updated: CatalogEntry[] = [];\n\t\tfor (const entry of this.list()) {\n\t\t\tif (this.status(entry) === \"outdated\") {\n\t\t\t\tthis.install(entry);\n\t\t\t\tupdated.push(entry);\n\t\t\t}\n\t\t}\n\t\treturn updated;\n\t}\n\n\t/** Copy a user-level resource back into the catalog (backup). Requires it to exist at user level. */\n\tbackup(entry: CatalogEntry): void {\n\t\tif (!existsSync(entry.installPath)) {\n\t\t\tthrow new Error(`Cannot back up \"${entry.kind}/${entry.name}\": not installed at user level.`);\n\t\t}\n\t\tsafeCopy(entry.installPath, entry.catalogPath);\n\t}\n}\n\n/**\n * Copy `src` over `dest` without ever leaving a partially-copied tree at `dest` (Bug #18): copy into a\n * sibling temp first, then swap it into place; on any failure the temp is removed and `dest` is left\n * untouched.\n */\nfunction safeCopy(src: string, dest: string): void {\n\tconst tmp = `${dest}.pi-tmp-${randomBytes(6).toString(\"hex\")}`;\n\ttry {\n\t\tcpSync(src, tmp, { recursive: true, force: true });\n\t\trmSync(dest, { recursive: true, force: true });\n\t\trenameSync(tmp, dest);\n\t} catch (err) {\n\t\ttry {\n\t\t\trmSync(tmp, { recursive: true, force: true });\n\t\t} catch {}\n\t\tthrow err;\n\t}\n}\n\n/**\n * Content hash of a file or directory tree: stable across machines (ignores mtimes/paths outside the\n * tree). Files contribute their relative path + bytes; directories are walked in sorted order so the\n * hash is deterministic.\n */\nexport function hashPath(target: string): string {\n\tconst hash = createHash(\"sha256\");\n\tconst seen = new Set<string>(); // real paths already visited — breaks circular symlinks (Bug #19)\n\tconst walk = (abs: string, rel: string, depth: number): void => {\n\t\tif (depth > 64) return; // hard depth cap as a backstop\n\t\tlet real: string;\n\t\ttry {\n\t\t\treal = realpathSync(abs);\n\t\t} catch {\n\t\t\treturn;\n\t\t}\n\t\tif (seen.has(real)) return; // already walked (symlink loop or shared target)\n\t\tseen.add(real);\n\t\tlet stats: ReturnType<typeof statSync>;\n\t\ttry {\n\t\t\tstats = statSync(abs);\n\t\t} catch {\n\t\t\treturn;\n\t\t}\n\t\tif (stats.isDirectory()) {\n\t\t\tlet children: string[];\n\t\t\ttry {\n\t\t\t\tchildren = readdirSync(abs).sort();\n\t\t\t} catch {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tfor (const child of children) {\n\t\t\t\twalk(join(abs, child), rel ? `${rel}/${child}` : child, depth + 1);\n\t\t\t}\n\t\t} else if (stats.isFile()) {\n\t\t\thash.update(`\u0000${rel}\u0000`);\n\t\t\ttry {\n\t\t\t\thash.update(readFileSync(abs));\n\t\t\t} catch {\n\t\t\t\t// unreadable file → contributes only its path\n\t\t\t}\n\t\t}\n\t};\n\twalk(target, \"\", 0);\n\treturn hash.digest(\"hex\");\n}\n"]}
1
+ {"version":3,"file":"catalog-manager.js","sourceRoot":"","sources":["../../src/core/catalog-manager.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AACtD,OAAO,EAAE,MAAM,E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AAE,CAAC;YACzB,IAAI,QAAkB,CAAC;YACvB,IAAI,CAAC;gBACJ,QAAQ,GAAG,WAAW,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,CAAC;YACpC,CAAC;YAAC,MAAM,CAAC;gBACR,OAAO;YACR,CAAC;YACD,KAAK,MAAM,KAAK,IAAI,QAAQ,EAAE,CAAC;gBAC9B,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,KAAK,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC,GAAG,GAAG,IAAI,KAAK,EAAE,CAAC,CAAC,CAAC,KAAK,EAAE,KAAK,GAAG,CAAC,CAAC,CAAC;YACpE,CAAC;QACF,CAAC;aAAM,IAAI,KAAK,CAAC,MAAM,EAAE,EAAE,CAAC;YAC3B,IAAI,CAAC,MAAM,CAAC,IAAI,GAAG,GAAG,CAAC,CAAC;YACxB,IAAI,CAAC;gBACJ,IAAI,CAAC,MAAM,CAAC,YAAY,CAAC,GAAG,CAAC,CAAC,CAAC;YAChC,CAAC;YAAC,MAAM,CAAC;gBACR,8CAA8C;YAC/C,CAAC;QACF,CAAC;IACF,CAAC,CAAC;IACF,IAAI,CAAC,MAAM,EAAE,EAAE,EAAE,CAAC,CAAC,CAAC;IACpB,OAAO,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AAC3B,CAAC","sourcesContent":["/**\n * CatalogManager — round resource management (resource-management design).\n *\n * A user-pointed **catalog directory** (a folder/repo holding `{skills,extensions,agents,prompts,themes}`)\n * is the easy-to-setup source of a user's workflows. From it pi can:\n * - **install** a resource = copy it into the pi user level (`<agentDir>/<kind>/`),\n * - **update** = hash-compare what's installed against the catalog and re-sync changed/outdated ones,\n * - **backup** = copy a user-level resource back into the catalog.\n * Per machine, the user installs only the subset they want; `update` refreshes exactly those.\n *\n * Copies are content-recursive (`cpSync`); status is decided by a recursive content hash so it is\n * portable across machines (mtimes differ; content does not).\n */\n\nimport { createHash, randomBytes } from \"node:crypto\";\nimport { cpSync, existsSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, statSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\nexport const CATALOG_KINDS = [\"skills\", \"extensions\", \"agents\", \"prompts\", \"themes\"] as const;\nexport type CatalogKind = (typeof CATALOG_KINDS)[number];\n\nexport type CatalogStatus = \"not-installed\" | \"up-to-date\" | \"outdated\";\n\nexport interface CatalogEntry {\n\tkind: CatalogKind;\n\t/** Top-level name in the catalog (a directory or file name). */\n\tname: string;\n\t/** Absolute path of the entry in the catalog. */\n\tcatalogPath: string;\n\t/** Absolute path where it installs at user level. */\n\tinstallPath: string;\n}\n\nexport class CatalogManager {\n\tprivate readonly agentDir: string;\n\tprivate readonly catalogDir: string;\n\n\tconstructor(agentDir: string, catalogDir: string) {\n\t\tthis.agentDir = agentDir;\n\t\tthis.catalogDir = catalogDir;\n\t}\n\n\t/** Every resource discovered in the catalog, across all kinds. */\n\tlist(): CatalogEntry[] {\n\t\tconst entries: CatalogEntry[] = [];\n\t\tfor (const kind of CATALOG_KINDS) {\n\t\t\tconst kindDir = join(this.catalogDir, kind);\n\t\t\tif (!existsSync(kindDir)) continue;\n\t\t\tlet names: string[];\n\t\t\ttry {\n\t\t\t\tnames = readdirSync(kindDir);\n\t\t\t} catch {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tfor (const name of names) {\n\t\t\t\tif (name.startsWith(\".\")) continue;\n\t\t\t\tentries.push({\n\t\t\t\t\tkind,\n\t\t\t\t\tname,\n\t\t\t\t\tcatalogPath: join(kindDir, name),\n\t\t\t\t\tinstallPath: join(this.agentDir, kind, name),\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\treturn entries;\n\t}\n\n\t/** Status of one catalog entry relative to what is installed at user level. */\n\tstatus(entry: CatalogEntry): CatalogStatus {\n\t\tif (!existsSync(entry.installPath)) return \"not-installed\";\n\t\treturn hashPath(entry.catalogPath) === hashPath(entry.installPath) ? \"up-to-date\" : \"outdated\";\n\t}\n\n\t/** Copy a catalog entry into the user level (install or overwrite), atomically. */\n\tinstall(entry: CatalogEntry): void {\n\t\tsafeCopy(entry.catalogPath, entry.installPath);\n\t}\n\n\t/**\n\t * Re-sync every INSTALLED resource that is outdated relative to the catalog (catalog → user level).\n\t * Never installs things the user has not already chosen on this machine. Returns the updated entries.\n\t */\n\tupdate(): CatalogEntry[] {\n\t\tconst updated: CatalogEntry[] = [];\n\t\tfor (const entry of this.list()) {\n\t\t\tif (this.status(entry) === \"outdated\") {\n\t\t\t\tthis.install(entry);\n\t\t\t\tupdated.push(entry);\n\t\t\t}\n\t\t}\n\t\treturn updated;\n\t}\n\n\t/** Copy a user-level resource back into the catalog (backup). Requires it to exist at user level. */\n\tbackup(entry: CatalogEntry): void {\n\t\tif (!existsSync(entry.installPath)) {\n\t\t\tthrow new Error(`Cannot back up \"${entry.kind}/${entry.name}\": not installed at user level.`);\n\t\t}\n\t\tsafeCopy(entry.installPath, entry.catalogPath);\n\t}\n}\n\n/**\n * Copy `src` over `dest` without ever leaving a partially-copied tree at `dest` (Bug #18): copy into a\n * sibling temp first, then swap it into place; on any failure the temp is removed and `dest` is left\n * untouched.\n */\nfunction safeCopy(src: string, dest: string): void {\n\tconst tmp = `${dest}.pi-tmp-${randomBytes(6).toString(\"hex\")}`;\n\ttry {\n\t\tcpSync(src, tmp, { recursive: true, force: true });\n\t\trmSync(dest, { recursive: true, force: true });\n\t\trenameSync(tmp, dest);\n\t} catch (err) {\n\t\ttry {\n\t\t\trmSync(tmp, { recursive: true, force: true });\n\t\t} catch {}\n\t\tthrow err;\n\t}\n}\n\n/**\n * Content hash of a file or directory tree: stable across machines (ignores mtimes/paths outside the\n * tree). Files contribute their relative path + bytes; directories are walked in sorted order so the\n * hash is deterministic.\n */\nexport function hashPath(target: string): string {\n\tconst hash = createHash(\"sha256\");\n\tconst seen = new Set<string>(); // real paths already visited — breaks circular symlinks (Bug #19)\n\tconst walk = (abs: string, rel: string, depth: number): void => {\n\t\tif (depth > 64) return; // hard depth cap as a backstop\n\t\tlet real: string;\n\t\ttry {\n\t\t\treal = realpathSync(abs);\n\t\t} catch {\n\t\t\treturn;\n\t\t}\n\t\tif (seen.has(real)) return; // already walked (symlink loop or shared target)\n\t\tseen.add(real);\n\t\tlet stats: ReturnType<typeof statSync>;\n\t\ttry {\n\t\t\tstats = statSync(abs);\n\t\t} catch {\n\t\t\treturn;\n\t\t}\n\t\tif (stats.isDirectory()) {\n\t\t\tlet children: string[];\n\t\t\ttry {\n\t\t\t\tchildren = readdirSync(abs).sort();\n\t\t\t} catch {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tfor (const child of children) {\n\t\t\t\twalk(join(abs, child), rel ? `${rel}/${child}` : child, depth + 1);\n\t\t\t}\n\t\t} else if (stats.isFile()) {\n\t\t\thash.update(`\u0000${rel}\u0000`);\n\t\t\ttry {\n\t\t\t\thash.update(readFileSync(abs));\n\t\t\t} catch {\n\t\t\t\t// unreadable file → contributes only its path\n\t\t\t}\n\t\t}\n\t};\n\twalk(target, \"\", 0);\n\treturn hash.digest(\"hex\");\n}\n"]}
@@ -48,6 +48,7 @@ export interface CompactionControllerDeps {
48
48
  emit(event: CompactionControllerEvent): void;
49
49
  estimateCurrentContextTokens(messages: AgentMessage[]): number;
50
50
  buildPreDigest(): ((text: string, signal?: AbortSignal) => Promise<string>) | undefined;
51
+ getMemoryPreCompressInsight(): Promise<string>;
51
52
  refreshAfterCompaction(): void;
52
53
  getFailureCorpus(): FailureCorpusRecorder;
53
54
  measureLiveContextTokens(): number;
@@ -72,6 +73,7 @@ export declare class CompactionController {
72
73
  private overflowRecoveryAttempted;
73
74
  private readonly deps;
74
75
  constructor(deps: CompactionControllerDeps);
76
+ private buildCompactionInstructions;
75
77
  isRunning(): boolean;
76
78
  resetOverflowRecovery(): void;
77
79
  abort(): void;
@@ -1 +1 @@
1
- {"version":3,"file":"compaction-controller.d.ts","sourceRoot":"","sources":["../../src/core/compaction-controller.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KA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AEK,OAAO,CAAC,kBAAkB,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAkIpE;IAEK,KAAK,CAAC,gBAAgB,EAAE,gBAAgB,EAAE,gBAAgB,UAAO,GAAG,OAAO,CAAC,OAAO,CAAC,CAiEzF;IAED,wBAAwB,IAAI,MAAM,CAWjC;IAEK,OAAO,CAAC,MAAM,EAAE,oBAAoB,EAAE,SAAS,EAAE,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,CAgJhF;IAEK,gBAAgB,CACrB,GAAG,EAAE,MAAM,OAAO,CAAC,gBAAgB,CAAC,EACpC,MAAM,EAAE,WAAW,EACnB,QAAQ,CAAC,EAAE,MAAM,GACf,OAAO,CAAC,gBAAgB,CAAC,CAQ3B;IAED,OAAO,CAAC,wBAAwB;YAQlB,sBAAsB;YAkBtB,WAAW;CAuBzB","sourcesContent":["import type { Agent, AgentMessage, RetryPolicy, ThinkingLevel } from \"@caupulican/pi-agent-core\";\nimport { classifyFailure, computeRetryDelayMs, DEFAULT_RETRY_POLICY, sleepAbortable } from \"@caupulican/pi-agent-core\";\nimport {\n\ttype CompactionEntry,\n\ttype CompactionPreparation,\n\ttype CompactionResult,\n\ttype CompactionSettings,\n\tcalculateContextTokens,\n\tcompact,\n\tcreateDeterministicCompaction,\n\testimateContextTokens,\n\tgetLatestCompactionEntry,\n\tprepareCompaction,\n\trunCompactionLoop,\n\ttype SessionManager,\n\tshouldCompact,\n} from \"@caupulican/pi-agent-core/node\";\nimport type { Api, AssistantMessage, Model } from \"@caupulican/pi-ai\";\nimport { isContextOverflow } from \"@caupulican/pi-ai\";\nimport { formatNoModelSelectedMessage } from \"./auth-guidance.ts\";\nimport type { ExtensionRunner, SessionBeforeCompactResult } from \"./extensions/index.ts\";\nimport type { FailureCorpusRecorder } from \"./failure-corpus.ts\";\nimport type { SettingsManager } from \"./settings-manager.ts\";\n\nexport type AutoCompactionReason = \"overflow\" | \"threshold\";\n\ntype CompactionControllerEvent =\n\t| { type: \"compaction_start\"; reason: \"manual\" | AutoCompactionReason }\n\t| {\n\t\t\ttype: \"compaction_end\";\n\t\t\treason: \"manual\" | AutoCompactionReason;\n\t\t\tresult: CompactionResult | undefined;\n\t\t\taborted: boolean;\n\t\t\twillRetry: boolean;\n\t\t\terrorMessage?: string;\n\t\t\tskipReason?: string;\n\t }\n\t| { type: \"warning\"; message: string };\n\nexport interface CompactionControllerDeps {\n\tagent: Agent;\n\tsessionManager: SessionManager;\n\tsettingsManager: SettingsManager;\n\tgetModel(): Model<Api> | undefined;\n\tgetAdaptedSettings(): CompactionSettings;\n\tgetRequestAuth(model: Model<Api>): Promise<{ apiKey?: string; headers?: Record<string, string> }>;\n\tresolveModelAndAuth(\n\t\tcompactionModel: Model<Api>,\n\t\tsessionModel: Model<Api>,\n\t): Promise<{ model: Model<Api>; apiKey?: string; headers?: Record<string, string>; failure?: string }>;\n\tresolveModel(sessionModel: Model<Api>): Model<Api>;\n\tgetSelectionReason(): string | undefined;\n\tresolveThinkingLevel(compactionModel: Model<Api>, sessionModel: Model<Api>): ThinkingLevel | undefined;\n\tdescribeSummarizer(): string;\n\tgetExtensionRunner(): ExtensionRunner;\n\tisRawStream(): boolean;\n\tdisconnectAgent(): void;\n\treconnectAgent(): void;\n\tabortForeground(): Promise<void>;\n\temit(event: CompactionControllerEvent): void;\n\testimateCurrentContextTokens(messages: AgentMessage[]): number;\n\tbuildPreDigest(): ((text: string, signal?: AbortSignal) => Promise<string>) | undefined;\n\trefreshAfterCompaction(): void;\n\tgetFailureCorpus(): FailureCorpusRecorder;\n\tmeasureLiveContextTokens(): number;\n\trunAutoCompaction(reason: AutoCompactionReason, willRetry: boolean): Promise<boolean>;\n\tcompactWithRetry(\n\t\trun: () => Promise<CompactionResult>,\n\t\tsignal: AbortSignal,\n\t\tprovider?: string,\n\t): Promise<CompactionResult>;\n}\n\nexport async function runCompactionWithRetry<T>(options: {\n\trun(): Promise<T>;\n\tsignal: AbortSignal;\n\tprovider?: string;\n\tgetRetrySettings(): { enabled: boolean; maxRetries: number; baseDelayMs: number };\n\trecordFailure(record: Parameters<FailureCorpusRecorder[\"record\"]>[0]): void;\n}): Promise<T> {\n\tconst retrySettings = options.getRetrySettings();\n\tconst maxAttempts = retrySettings.enabled ? Math.max(1, retrySettings.maxRetries + 1) : 1;\n\tconst policy: RetryPolicy = {\n\t\tmaxAttempts,\n\t\tbaseDelayMs: retrySettings.baseDelayMs,\n\t\tmaxDelayMs: DEFAULT_RETRY_POLICY.maxDelayMs,\n\t\tjitterRatio: 0,\n\t};\n\tfor (let attempt = 1; ; attempt++) {\n\t\ttry {\n\t\t\treturn await options.run();\n\t\t} catch (error) {\n\t\t\tif (options.signal.aborted || attempt >= maxAttempts) throw error;\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tconst classified = classifyFailure({ message, provider: options.provider });\n\t\t\toptions.recordFailure({ provider: options.provider, message, classified });\n\t\t\tif (!classified.retryable) throw error;\n\t\t\tawait sleepAbortable(\n\t\t\t\tcomputeRetryDelayMs(policy, attempt, { retryAfterMs: classified.retryAfterMs }),\n\t\t\t\toptions.signal,\n\t\t\t);\n\t\t}\n\t}\n}\n\n/** Owns compaction detection, execution, retry, persistence, notification, and cancellation. */\nexport class CompactionController {\n\tprivate manualAbortController: AbortController | undefined;\n\tprivate autoAbortController: AbortController | undefined;\n\tprivate overflowRecoveryAttempted = false;\n\tprivate readonly deps: CompactionControllerDeps;\n\n\tconstructor(deps: CompactionControllerDeps) {\n\t\tthis.deps = deps;\n\t}\n\n\tisRunning(): boolean {\n\t\treturn this.manualAbortController !== undefined || this.autoAbortController !== undefined;\n\t}\n\n\tresetOverflowRecovery(): void {\n\t\tthis.overflowRecoveryAttempted = false;\n\t}\n\n\tabort(): void {\n\t\tthis.manualAbortController?.abort();\n\t\tthis.autoAbortController?.abort();\n\t}\n\n\tcheckContextWindowUsageWarning(): void {\n\t\tconst model = this.deps.getModel();\n\t\tif (!model) return;\n\t\tconst contextWindow = model.contextWindow ?? 0;\n\t\tif (contextWindow <= 0) return;\n\n\t\tconst systemPromptTokens = Math.ceil((this.deps.agent.state.systemPrompt ?? \"\").length / 4);\n\t\tlet toolsChars = 0;\n\t\tfor (const tool of this.deps.agent.state.tools || []) {\n\t\t\ttoolsChars += tool.name.length;\n\t\t\ttoolsChars += tool.description?.length ?? 0;\n\t\t\tif (tool.parameters) toolsChars += JSON.stringify(tool.parameters).length;\n\t\t}\n\t\tconst baseTokens = systemPromptTokens + Math.ceil(toolsChars / 4);\n\n\t\tif (baseTokens >= contextWindow) {\n\t\t\tthis.deps.emit({\n\t\t\t\ttype: \"warning\",\n\t\t\t\tmessage: `Base configuration (system prompt and active tools) consumes ${baseTokens} tokens, which exceeds the model's context window of ${contextWindow} tokens. The model cannot process any prompts in this state.`,\n\t\t\t});\n\t\t} else if (baseTokens >= contextWindow * 0.7) {\n\t\t\tthis.deps.emit({\n\t\t\t\ttype: \"warning\",\n\t\t\t\tmessage: `Base configuration (system prompt and active tools) consumes ${baseTokens} tokens (${Math.round((baseTokens / contextWindow) * 100)}% of the ${contextWindow} context window). This leaves very little room for conversation history and may cause immediate compaction or context overflow.`,\n\t\t\t});\n\t\t}\n\t}\n\n\tasync maybeCompactBeforeContextTransform(\n\t\tmessages: AgentMessage[],\n\t\tprojectContextGc: (messages: AgentMessage[]) => AgentMessage[],\n\t): Promise<boolean> {\n\t\tconst settings = this.deps.getAdaptedSettings();\n\t\tconst model = this.deps.getModel();\n\t\tconst contextWindow = model?.contextWindow ?? 0;\n\t\tif (!settings.enabled || !model || contextWindow <= 0 || this.isRunning()) return false;\n\n\t\tconst triggerTokens = model.autoCompactionTriggerTokens;\n\t\tconst contextTokens = this.deps.estimateCurrentContextTokens(messages);\n\t\tif (!shouldCompact(contextTokens, contextWindow, settings, triggerTokens)) return false;\n\t\tconst projectedMessages = projectContextGc(messages);\n\t\tconst projectedTokens = this.deps.estimateCurrentContextTokens(projectedMessages);\n\t\tif (!shouldCompact(projectedTokens, contextWindow, settings, triggerTokens)) return false;\n\n\t\tconst latestBefore = getLatestCompactionEntry(this.deps.sessionManager.getBranch())?.id;\n\t\tawait this.deps.runAutoCompaction(\"threshold\", false);\n\t\tconst latestAfter = getLatestCompactionEntry(this.deps.sessionManager.getBranch())?.id;\n\t\treturn Boolean(latestAfter && latestAfter !== latestBefore);\n\t}\n\n\tasync compact(customInstructions?: string): Promise<CompactionResult> {\n\t\tthis.deps.disconnectAgent();\n\t\tawait this.deps.abortForeground();\n\t\tthis.manualAbortController = new AbortController();\n\t\tthis.deps.emit({ type: \"compaction_start\", reason: \"manual\" });\n\n\t\ttry {\n\t\t\tconst sessionModel = this.deps.getModel();\n\t\t\tif (!sessionModel) throw new Error(formatNoModelSelectedMessage());\n\n\t\t\tconst selectedCompactionModel = this.deps.resolveModel(sessionModel);\n\t\t\tif (this.deps.isRawStream()) await this.deps.getRequestAuth(selectedCompactionModel);\n\t\t\tconst selectionReason = this.deps.getSelectionReason() ?? \"unknown\";\n\t\t\tconst settings = this.deps.getAdaptedSettings();\n\t\t\tconst initialBranch = this.deps.sessionManager.getBranch();\n\t\t\tconst initialPreparation = prepareCompaction(initialBranch, settings);\n\t\t\tif (!initialPreparation) {\n\t\t\t\tconst lastEntry = initialBranch[initialBranch.length - 1];\n\t\t\t\tif (lastEntry?.type === \"compaction\") throw new Error(\"Already compacted\");\n\t\t\t\tthrow new Error(\"Nothing to compact (session too small)\");\n\t\t\t}\n\n\t\t\tconst signal = this.manualAbortController.signal;\n\t\t\tconst extension = await this.getExtensionCompaction(\n\t\t\t\tinitialPreparation,\n\t\t\t\tinitialBranch,\n\t\t\t\tcustomInstructions,\n\t\t\t\tsignal,\n\t\t\t);\n\t\t\tif (extension.cancelled) throw new Error(\"Compaction cancelled\");\n\t\t\tif (extension.result) {\n\t\t\t\tawait this.applyResult(extension.result, true);\n\t\t\t\tthis.deps.emit({\n\t\t\t\t\ttype: \"compaction_end\",\n\t\t\t\t\treason: \"manual\",\n\t\t\t\t\tresult: extension.result,\n\t\t\t\t\taborted: false,\n\t\t\t\t\twillRetry: false,\n\t\t\t\t});\n\t\t\t\treturn extension.result;\n\t\t\t}\n\n\t\t\tlet appliedResult: CompactionResult | undefined;\n\t\t\tconst outcome = await runCompactionLoop({\n\t\t\t\tmeasureLiveTokens: () =>\n\t\t\t\t\tMath.max(this.deps.estimateCurrentContextTokens(this.deps.agent.state.messages), 1),\n\t\t\t\tshouldCompact: () => true,\n\t\t\t\tgetPostApplyMargin: () => 0,\n\t\t\t\tgetBranch: () => this.deps.sessionManager.getBranch(),\n\t\t\t\tgetBaseKeepRecentTokens: () => settings.keepRecentTokens,\n\t\t\t\tresolveModelAndAuth: async (modelTier) => {\n\t\t\t\t\tconst model = modelTier === \"cheap\" ? selectedCompactionModel : sessionModel;\n\t\t\t\t\treturn this.deps.resolveModelAndAuth(model, sessionModel);\n\t\t\t\t},\n\t\t\t\tsummarizeAndVerify: async (params, model, apiKey, headers, branch) => {\n\t\t\t\t\tconst preparation = prepareCompaction(\n\t\t\t\t\t\tbranch,\n\t\t\t\t\t\t{ ...settings, keepRecentTokens: params.keepRecentTokens },\n\t\t\t\t\t\t{ allowTrailingCompactionAsPrevious: true },\n\t\t\t\t\t);\n\t\t\t\t\tif (!preparation) throw new Error(\"Nothing to compact (session too small)\");\n\t\t\t\t\tconst compactionThinkingLevel = this.deps.resolveThinkingLevel(model, sessionModel);\n\t\t\t\t\tconst result = await this.deps.compactWithRetry(\n\t\t\t\t\t\t() =>\n\t\t\t\t\t\t\tcompact(\n\t\t\t\t\t\t\t\tpreparation,\n\t\t\t\t\t\t\t\tmodel,\n\t\t\t\t\t\t\t\tapiKey,\n\t\t\t\t\t\t\t\theaders,\n\t\t\t\t\t\t\t\tcustomInstructions,\n\t\t\t\t\t\t\t\tsignal,\n\t\t\t\t\t\t\t\tcompactionThinkingLevel,\n\t\t\t\t\t\t\t\tthis.deps.agent.streamFn,\n\t\t\t\t\t\t\t\tthis.deps.buildPreDigest(),\n\t\t\t\t\t\t\t\t{ chunked: params.chunked },\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t\tmodel.provider,\n\t\t\t\t\t);\n\t\t\t\t\treturn { result };\n\t\t\t\t},\n\t\t\t\tbuildDeterministicCheckpoint: () => ({ result: createDeterministicCompaction(initialPreparation) }),\n\t\t\t\tapply: async (result) => {\n\t\t\t\t\tif (signal.aborted) throw new Error(\"Compaction cancelled\");\n\t\t\t\t\tawait this.applyResult(result, false);\n\t\t\t\t\tappliedResult = result;\n\t\t\t\t},\n\t\t\t\tverifyPostApplyEffect: () => false,\n\t\t\t\tonTransition: ({ cycle, cause, detail }) => {\n\t\t\t\t\tthis.deps.emit({\n\t\t\t\t\t\ttype: \"warning\",\n\t\t\t\t\t\tmessage: `manual compaction cycle ${cycle}: ${cause}${detail ? ` (${detail})` : \"\"} — retrying from step 0 (${this.deps.describeSummarizer()})`,\n\t\t\t\t\t});\n\t\t\t\t},\n\t\t\t\tsignal,\n\t\t\t});\n\n\t\t\tif (outcome.kind === \"failed\") {\n\t\t\t\tif (outcome.reason === \"aborted\") throw new Error(\"Compaction cancelled\");\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`manual compaction failed after retry ladder using ${selectedCompactionModel.provider}/${selectedCompactionModel.id} (${selectionReason}); first failure: ${outcome.reason}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (outcome.kind === \"skip\" || !appliedResult) {\n\t\t\t\tthrow new Error(outcome.kind === \"skip\" ? outcome.reason : \"Compaction failed\");\n\t\t\t}\n\t\t\tthis.deps.emit({\n\t\t\t\ttype: \"compaction_end\",\n\t\t\t\treason: \"manual\",\n\t\t\t\tresult: appliedResult,\n\t\t\t\taborted: false,\n\t\t\t\twillRetry: false,\n\t\t\t});\n\t\t\treturn appliedResult;\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tconst aborted = message === \"Compaction cancelled\" || (error instanceof Error && error.name === \"AbortError\");\n\t\t\tthis.deps.emit({\n\t\t\t\ttype: \"compaction_end\",\n\t\t\t\treason: \"manual\",\n\t\t\t\tresult: undefined,\n\t\t\t\taborted,\n\t\t\t\twillRetry: false,\n\t\t\t\terrorMessage: aborted ? undefined : `Compaction failed: ${message}`,\n\t\t\t});\n\t\t\tthrow error;\n\t\t} finally {\n\t\t\tthis.manualAbortController = undefined;\n\t\t\tthis.deps.reconnectAgent();\n\t\t}\n\t}\n\n\tasync check(assistantMessage: AssistantMessage, skipAbortedCheck = true): Promise<boolean> {\n\t\tconst settings = this.deps.getAdaptedSettings();\n\t\tif (!settings.enabled) return false;\n\t\tif (skipAbortedCheck && assistantMessage.stopReason === \"aborted\") return false;\n\n\t\tconst model = this.deps.getModel();\n\t\tconst contextWindow = model?.contextWindow ?? 0;\n\t\tconst sameModel = model && assistantMessage.provider === model.provider && assistantMessage.model === model.id;\n\t\tconst compactionEntry = getLatestCompactionEntry(this.deps.sessionManager.getBranch());\n\t\tconst assistantIsFromBeforeCompaction =\n\t\t\tcompactionEntry !== null && assistantMessage.timestamp <= new Date(compactionEntry.timestamp).getTime();\n\t\tif (assistantIsFromBeforeCompaction) return false;\n\n\t\tif (sameModel && isContextOverflow(assistantMessage, contextWindow)) {\n\t\t\tif (this.overflowRecoveryAttempted) {\n\t\t\t\tthis.deps.emit({\n\t\t\t\t\ttype: \"compaction_end\",\n\t\t\t\t\treason: \"overflow\",\n\t\t\t\t\tresult: undefined,\n\t\t\t\t\taborted: false,\n\t\t\t\t\twillRetry: false,\n\t\t\t\t\terrorMessage:\n\t\t\t\t\t\t\"Context overflow recovery failed after one compact-and-retry attempt. Try reducing context or switching to a larger-context model.\",\n\t\t\t\t});\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tthis.overflowRecoveryAttempted = true;\n\t\t\tconst messages = this.deps.agent.state.messages;\n\t\t\tif (messages.length > 0 && messages[messages.length - 1].role === \"assistant\") {\n\t\t\t\tthis.deps.agent.state.messages = messages.slice(0, -1);\n\t\t\t}\n\t\t\treturn this.deps.runAutoCompaction(\"overflow\", true);\n\t\t}\n\n\t\tlet contextTokens: number;\n\t\tif (assistantMessage.stopReason === \"error\") {\n\t\t\tconst messages = this.deps.agent.state.messages;\n\t\t\tconst estimate = estimateContextTokens(messages);\n\t\t\tif (estimate.lastUsageIndex === null) return false;\n\t\t\tconst usageMessage = messages[estimate.lastUsageIndex];\n\t\t\tif (\n\t\t\t\tcompactionEntry &&\n\t\t\t\tusageMessage.role === \"assistant\" &&\n\t\t\t\tusageMessage.timestamp <= new Date(compactionEntry.timestamp).getTime()\n\t\t\t) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tcontextTokens = estimate.tokens;\n\t\t} else {\n\t\t\tcontextTokens = calculateContextTokens(assistantMessage.usage);\n\t\t\tconst estimate = estimateContextTokens(this.deps.agent.state.messages);\n\t\t\tif (estimate.lastUsageIndex !== null) {\n\t\t\t\tconst usageMessage = this.deps.agent.state.messages[estimate.lastUsageIndex];\n\t\t\t\tconst usageIsPostCompaction = !(\n\t\t\t\t\tcompactionEntry &&\n\t\t\t\t\tusageMessage.role === \"assistant\" &&\n\t\t\t\t\tusageMessage.timestamp <= new Date(compactionEntry.timestamp).getTime()\n\t\t\t\t);\n\t\t\t\tif (usageIsPostCompaction) contextTokens = Math.max(contextTokens, estimate.tokens);\n\t\t\t}\n\t\t}\n\t\tif (shouldCompact(contextTokens, contextWindow, settings, model?.autoCompactionTriggerTokens)) {\n\t\t\treturn this.deps.runAutoCompaction(\"threshold\", false);\n\t\t}\n\t\treturn false;\n\t}\n\n\tmeasureLiveContextTokens(): number {\n\t\tconst estimatedTokens = this.deps.estimateCurrentContextTokens(this.deps.agent.state.messages);\n\t\tconst assistantMessage = this.findLastAssistantMessage();\n\t\tif (!assistantMessage || assistantMessage.stopReason === \"error\" || assistantMessage.stopReason === \"aborted\") {\n\t\t\treturn estimatedTokens;\n\t\t}\n\t\tconst compactionEntry = getLatestCompactionEntry(this.deps.sessionManager.getBranch());\n\t\tif (compactionEntry && assistantMessage.timestamp <= new Date(compactionEntry.timestamp).getTime()) {\n\t\t\treturn estimatedTokens;\n\t\t}\n\t\treturn Math.max(calculateContextTokens(assistantMessage.usage), estimatedTokens);\n\t}\n\n\tasync runAuto(reason: AutoCompactionReason, willRetry: boolean): Promise<boolean> {\n\t\tconst settings = this.deps.getAdaptedSettings();\n\t\tconst model = this.deps.getModel();\n\t\tthis.deps.emit({ type: \"compaction_start\", reason });\n\t\tconst hadQueuedMessages = this.deps.agent.hasQueuedMessages();\n\t\tthis.autoAbortController = new AbortController();\n\t\tconst signal = this.autoAbortController.signal;\n\t\tlet fromExtension = false;\n\t\tlet lastCompaction: CompactionResult | undefined;\n\t\tlet extensionCancelled = false;\n\t\ttry {\n\t\t\tif (!model) {\n\t\t\t\tthis.deps.emit({\n\t\t\t\t\ttype: \"compaction_end\",\n\t\t\t\t\treason,\n\t\t\t\t\tresult: undefined,\n\t\t\t\t\taborted: false,\n\t\t\t\t\twillRetry: false,\n\t\t\t\t\tskipReason: \"no model selected\",\n\t\t\t\t});\n\t\t\t\treturn hadQueuedMessages || this.deps.agent.hasQueuedMessages();\n\t\t\t}\n\n\t\t\tconst contextWindow = model.contextWindow;\n\t\t\tconst margin = Math.max(0, Math.floor(0.01 * contextWindow));\n\t\t\tconst outcome = await runCompactionLoop({\n\t\t\t\tgetBranch: () => this.deps.sessionManager.getBranch(),\n\t\t\t\tmeasureLiveTokens: () => this.deps.measureLiveContextTokens(),\n\t\t\t\tshouldCompact:\n\t\t\t\t\treason === \"overflow\"\n\t\t\t\t\t\t? () => true\n\t\t\t\t\t\t: (tokens) => shouldCompact(tokens, contextWindow, settings, model.autoCompactionTriggerTokens),\n\t\t\t\tgetPostApplyMargin: () => margin,\n\t\t\t\tgetBaseKeepRecentTokens: () => settings.keepRecentTokens,\n\t\t\t\tresolveModelAndAuth: async (modelTier) =>\n\t\t\t\t\tthis.deps.resolveModelAndAuth(modelTier === \"session\" ? model : this.deps.resolveModel(model), model),\n\t\t\t\tsummarizeAndVerify: async (params, compactModel, apiKey, headers, branchEntries) => {\n\t\t\t\t\tfromExtension = false;\n\t\t\t\t\tconst preparation = prepareCompaction(branchEntries, {\n\t\t\t\t\t\t...settings,\n\t\t\t\t\t\tkeepRecentTokens: params.keepRecentTokens,\n\t\t\t\t\t});\n\t\t\t\t\tif (!preparation) throw new Error(\"already compacted\");\n\t\t\t\t\tconst compactionThinkingLevel = this.deps.resolveThinkingLevel(compactModel, model);\n\t\t\t\t\tconst extension = await this.getExtensionCompaction(preparation, branchEntries, undefined, signal);\n\t\t\t\t\tif (extension.cancelled) {\n\t\t\t\t\t\textensionCancelled = true;\n\t\t\t\t\t\tthrow new Error(\"auto-compaction-cancelled\");\n\t\t\t\t\t}\n\t\t\t\t\tif (extension.result) {\n\t\t\t\t\t\tfromExtension = true;\n\t\t\t\t\t\treturn { result: extension.result };\n\t\t\t\t\t}\n\t\t\t\t\tconst result = await this.deps.compactWithRetry(\n\t\t\t\t\t\t() =>\n\t\t\t\t\t\t\tcompact(\n\t\t\t\t\t\t\t\tpreparation,\n\t\t\t\t\t\t\t\tcompactModel,\n\t\t\t\t\t\t\t\tapiKey,\n\t\t\t\t\t\t\t\theaders,\n\t\t\t\t\t\t\t\tundefined,\n\t\t\t\t\t\t\t\tsignal,\n\t\t\t\t\t\t\t\tcompactionThinkingLevel,\n\t\t\t\t\t\t\t\tthis.deps.agent.streamFn,\n\t\t\t\t\t\t\t\tthis.deps.buildPreDigest(),\n\t\t\t\t\t\t\t\t{ chunked: params.chunked },\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t\tcompactModel.provider,\n\t\t\t\t\t);\n\t\t\t\t\treturn { result };\n\t\t\t\t},\n\t\t\t\tbuildDeterministicCheckpoint: () => {\n\t\t\t\t\tconst preparation = prepareCompaction(this.deps.sessionManager.getBranch(), settings);\n\t\t\t\t\tif (!preparation) throw new Error(\"already compacted\");\n\t\t\t\t\tfromExtension = false;\n\t\t\t\t\treturn { result: createDeterministicCompaction(preparation) };\n\t\t\t\t},\n\t\t\t\tapply: async (result) => {\n\t\t\t\t\tlastCompaction = result;\n\t\t\t\t\tawait this.applyResult(result, fromExtension);\n\t\t\t\t},\n\t\t\t\tverifyPostApplyEffect: reason === \"overflow\" ? () => false : undefined,\n\t\t\t\tonTransition: ({ cycle, cause, detail }) => {\n\t\t\t\t\tthis.deps.emit({\n\t\t\t\t\t\ttype: \"warning\",\n\t\t\t\t\t\tmessage: `auto-compaction cycle ${cycle}: ${cause}${detail ? ` (${detail})` : \"\"} — retrying from step 0 (${this.deps.describeSummarizer()})`,\n\t\t\t\t\t});\n\t\t\t\t},\n\t\t\t\tsignal,\n\t\t\t});\n\n\t\t\tif (outcome.kind === \"skip\") {\n\t\t\t\tthis.deps.emit({\n\t\t\t\t\ttype: \"compaction_end\",\n\t\t\t\t\treason,\n\t\t\t\t\tresult: undefined,\n\t\t\t\t\taborted: false,\n\t\t\t\t\twillRetry: false,\n\t\t\t\t\tskipReason: outcome.reason,\n\t\t\t\t});\n\t\t\t\treturn hadQueuedMessages || this.deps.agent.hasQueuedMessages();\n\t\t\t}\n\t\t\tif (outcome.kind === \"failed\") {\n\t\t\t\tif (outcome.reason === \"aborted\") {\n\t\t\t\t\tthis.deps.emit({ type: \"compaction_end\", reason, result: undefined, aborted: true, willRetry: false });\n\t\t\t\t\treturn hadQueuedMessages || this.deps.agent.hasQueuedMessages();\n\t\t\t\t}\n\t\t\t\tthrow new Error(outcome.reason);\n\t\t\t}\n\t\t\tif (extensionCancelled || signal.aborted) {\n\t\t\t\tthis.deps.emit({ type: \"compaction_end\", reason, result: undefined, aborted: true, willRetry: false });\n\t\t\t\treturn hadQueuedMessages || this.deps.agent.hasQueuedMessages();\n\t\t\t}\n\n\t\t\tconst result = outcome.kind === \"success\" ? outcome.result : lastCompaction;\n\t\t\tif (!result) throw new Error(\"Auto-compaction succeeded without a result\");\n\t\t\tthis.deps.emit({ type: \"compaction_end\", reason, result, aborted: false, willRetry });\n\t\t\tif (willRetry) {\n\t\t\t\tconst messages = this.deps.agent.state.messages;\n\t\t\t\tconst lastMessage = messages[messages.length - 1];\n\t\t\t\tif (lastMessage?.role === \"assistant\" && lastMessage.stopReason === \"error\") {\n\t\t\t\t\tthis.deps.agent.state.messages = messages.slice(0, -1);\n\t\t\t\t}\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\treturn hadQueuedMessages || this.deps.agent.hasQueuedMessages();\n\t\t} catch (error) {\n\t\t\tconst errorMessage = error instanceof Error ? error.message : \"compaction failed\";\n\t\t\tthis.deps.emit({\n\t\t\t\ttype: \"compaction_end\",\n\t\t\t\treason,\n\t\t\t\tresult: undefined,\n\t\t\t\taborted: false,\n\t\t\t\twillRetry: false,\n\t\t\t\terrorMessage:\n\t\t\t\t\treason === \"overflow\"\n\t\t\t\t\t\t? `Context overflow recovery failed: ${errorMessage}`\n\t\t\t\t\t\t: `Auto-compaction failed: ${errorMessage}`,\n\t\t\t});\n\t\t\treturn hadQueuedMessages || this.deps.agent.hasQueuedMessages();\n\t\t} finally {\n\t\t\tthis.autoAbortController = undefined;\n\t\t}\n\t}\n\n\tasync compactWithRetry(\n\t\trun: () => Promise<CompactionResult>,\n\t\tsignal: AbortSignal,\n\t\tprovider?: string,\n\t): Promise<CompactionResult> {\n\t\treturn runCompactionWithRetry({\n\t\t\trun,\n\t\t\tsignal,\n\t\t\tprovider,\n\t\t\tgetRetrySettings: () => this.deps.settingsManager.getRetrySettings(),\n\t\t\trecordFailure: (record) => this.deps.getFailureCorpus().record(record),\n\t\t});\n\t}\n\n\tprivate findLastAssistantMessage(): AssistantMessage | undefined {\n\t\tfor (let index = this.deps.agent.state.messages.length - 1; index >= 0; index--) {\n\t\t\tconst message = this.deps.agent.state.messages[index];\n\t\t\tif (message.role === \"assistant\") return message;\n\t\t}\n\t\treturn undefined;\n\t}\n\n\tprivate async getExtensionCompaction(\n\t\tpreparation: CompactionPreparation,\n\t\tbranchEntries: ReturnType<SessionManager[\"getBranch\"]>,\n\t\tcustomInstructions: string | undefined,\n\t\tsignal: AbortSignal,\n\t): Promise<{ cancelled: boolean; result?: CompactionResult }> {\n\t\tconst extensionRunner = this.deps.getExtensionRunner();\n\t\tif (!extensionRunner.hasHandlers(\"session_before_compact\")) return { cancelled: false };\n\t\tconst extensionResult = (await extensionRunner.emit({\n\t\t\ttype: \"session_before_compact\",\n\t\t\tpreparation,\n\t\t\tbranchEntries,\n\t\t\tcustomInstructions,\n\t\t\tsignal,\n\t\t})) as SessionBeforeCompactResult | undefined;\n\t\treturn { cancelled: extensionResult?.cancel === true, result: extensionResult?.compaction };\n\t}\n\n\tprivate async applyResult(result: CompactionResult, fromExtension: boolean): Promise<void> {\n\t\tthis.deps.sessionManager.appendCompaction(\n\t\t\tresult.summary,\n\t\t\tresult.firstKeptEntryId,\n\t\t\tresult.tokensBefore,\n\t\t\tresult.details,\n\t\t\tfromExtension,\n\t\t\tresult.usage,\n\t\t);\n\t\tthis.deps.refreshAfterCompaction();\n\t\tconst savedEntry = this.deps.sessionManager\n\t\t\t.getEntries()\n\t\t\t.find((entry) => entry.type === \"compaction\" && entry.summary === result.summary) as\n\t\t\t| CompactionEntry\n\t\t\t| undefined;\n\t\tif (savedEntry) {\n\t\t\tawait this.deps.getExtensionRunner().emit({\n\t\t\t\ttype: \"session_compact\",\n\t\t\t\tcompactionEntry: savedEntry,\n\t\t\t\tfromExtension,\n\t\t\t});\n\t\t}\n\t}\n}\n"]}
1
+ {"version":3,"file":"compaction-controller.d.ts","sourceRoot":"","sources":["../../src/core/compaction-controller.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,YAAY,EAAe,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAEjG,OAAO,EAGN,KAAK,gBAAgB,EACrB,KAAK,kBAAkB,EAQvB,KAAK,cAAc,EAEnB,MAAM,gCAAgC,CAAC;AACxC,OAAO,KAAK,EAAE,GAAG,EAAE,gBAAgB,EAAE,KAAK,EA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