@caupulican/pi-adaptative 0.81.42 → 0.84.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (1414) hide show
  1. package/CHANGELOG.md +57 -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 +1 -1
  62. package/dist/config.d.ts.map +1 -1
  63. package/dist/config.js +10 -15
  64. package/dist/config.js.map +1 -1
  65. package/dist/core/agent-directory-layout.d.ts.map +1 -1
  66. package/dist/core/agent-directory-layout.js.map +1 -1
  67. package/dist/core/agent-paths.d.ts +1 -1
  68. package/dist/core/agent-paths.d.ts.map +1 -1
  69. package/dist/core/agent-paths.js +1 -1
  70. package/dist/core/agent-paths.js.map +1 -1
  71. package/dist/core/agent-session-contracts.d.ts +5 -9
  72. package/dist/core/agent-session-contracts.d.ts.map +1 -1
  73. package/dist/core/agent-session-contracts.js +1 -12
  74. package/dist/core/agent-session-contracts.js.map +1 -1
  75. package/dist/core/agent-session-runtime.d.ts.map +1 -1
  76. package/dist/core/agent-session-runtime.js +10 -25
  77. package/dist/core/agent-session-runtime.js.map +1 -1
  78. package/dist/core/agent-session-services.d.ts.map +1 -1
  79. package/dist/core/agent-session-services.js.map +1 -1
  80. package/dist/core/agent-session.d.ts +24 -1
  81. package/dist/core/agent-session.d.ts.map +1 -1
  82. package/dist/core/agent-session.js +210 -237
  83. package/dist/core/agent-session.js.map +1 -1
  84. package/dist/core/auth-guidance.d.ts.map +1 -1
  85. package/dist/core/auth-guidance.js.map +1 -1
  86. package/dist/core/auth-storage.d.ts +4 -1
  87. package/dist/core/auth-storage.d.ts.map +1 -1
  88. package/dist/core/auth-storage.js +13 -39
  89. package/dist/core/auth-storage.js.map +1 -1
  90. package/dist/core/autonomy/approval-gate.d.ts.map +1 -1
  91. package/dist/core/autonomy/approval-gate.js.map +1 -1
  92. package/dist/core/autonomy/bounded-completion.d.ts.map +1 -1
  93. package/dist/core/autonomy/bounded-completion.js.map +1 -1
  94. package/dist/core/autonomy/contracts.d.ts.map +1 -1
  95. package/dist/core/autonomy/envelope-enforcement.d.ts.map +1 -1
  96. package/dist/core/autonomy/envelope-enforcement.js.map +1 -1
  97. package/dist/core/autonomy/evidence-finding-projection.d.ts +11 -0
  98. package/dist/core/autonomy/evidence-finding-projection.d.ts.map +1 -0
  99. package/dist/core/autonomy/evidence-finding-projection.js +37 -0
  100. package/dist/core/autonomy/evidence-finding-projection.js.map +1 -0
  101. package/dist/core/autonomy/foreground-envelope.d.ts.map +1 -1
  102. package/dist/core/autonomy/foreground-envelope.js.map +1 -1
  103. package/dist/core/autonomy/gates.d.ts.map +1 -1
  104. package/dist/core/autonomy/gates.js.map +1 -1
  105. package/dist/core/autonomy/lane-private-paths.d.ts.map +1 -1
  106. package/dist/core/autonomy/lane-private-paths.js.map +1 -1
  107. package/dist/core/autonomy/lane-tool-surface.d.ts.map +1 -1
  108. package/dist/core/autonomy/lane-tool-surface.js.map +1 -1
  109. package/dist/core/autonomy/lane-tracker.d.ts.map +1 -1
  110. package/dist/core/autonomy/lane-tracker.js +2 -3
  111. package/dist/core/autonomy/lane-tracker.js.map +1 -1
  112. package/dist/core/autonomy/path-scope.d.ts.map +1 -1
  113. package/dist/core/autonomy/path-scope.js.map +1 -1
  114. package/dist/core/autonomy/risk-assessment.d.ts.map +1 -1
  115. package/dist/core/autonomy/session-lane-record.d.ts.map +1 -1
  116. package/dist/core/autonomy/session-lane-record.js.map +1 -1
  117. package/dist/core/autonomy/status.d.ts.map +1 -1
  118. package/dist/core/autonomy/status.js.map +1 -1
  119. package/dist/core/autonomy/subagent-prompt.d.ts.map +1 -1
  120. package/dist/core/autonomy/subagent-prompt.js.map +1 -1
  121. package/dist/core/autonomy/telemetry-events.d.ts.map +1 -1
  122. package/dist/core/autonomy/telemetry-events.js.map +1 -1
  123. package/dist/core/autonomy-telemetry.d.ts.map +1 -1
  124. package/dist/core/autonomy-telemetry.js +2 -4
  125. package/dist/core/autonomy-telemetry.js.map +1 -1
  126. package/dist/core/background-lane-controller.d.ts.map +1 -1
  127. package/dist/core/background-lane-controller.js +2 -15
  128. package/dist/core/background-lane-controller.js.map +1 -1
  129. package/dist/core/background-tool-task-controller.d.ts +88 -0
  130. package/dist/core/background-tool-task-controller.d.ts.map +1 -0
  131. package/dist/core/background-tool-task-controller.js +470 -0
  132. package/dist/core/background-tool-task-controller.js.map +1 -0
  133. package/dist/core/bash-execution-controller.d.ts +1 -0
  134. package/dist/core/bash-execution-controller.d.ts.map +1 -1
  135. package/dist/core/bash-execution-controller.js +5 -4
  136. package/dist/core/bash-execution-controller.js.map +1 -1
  137. package/dist/core/bash-executor.d.ts.map +1 -1
  138. package/dist/core/bash-executor.js.map +1 -1
  139. package/dist/core/bedrock-sso-login.d.ts.map +1 -1
  140. package/dist/core/bedrock-sso-login.js.map +1 -1
  141. package/dist/core/billing-failover-controller.d.ts.map +1 -1
  142. package/dist/core/billing-failover-controller.js +3 -3
  143. package/dist/core/billing-failover-controller.js.map +1 -1
  144. package/dist/core/billing-failover.d.ts.map +1 -1
  145. package/dist/core/billing-failover.js.map +1 -1
  146. package/dist/core/capability-contract.d.ts.map +1 -1
  147. package/dist/core/catalog-manager.d.ts.map +1 -1
  148. package/dist/core/catalog-manager.js +0 -0
  149. package/dist/core/catalog-manager.js.map +1 -1
  150. package/dist/core/compaction-controller.d.ts +2 -0
  151. package/dist/core/compaction-controller.d.ts.map +1 -1
  152. package/dist/core/compaction-controller.js +21 -8
  153. package/dist/core/compaction-controller.js.map +1 -1
  154. package/dist/core/compaction-support.d.ts +8 -0
  155. package/dist/core/compaction-support.d.ts.map +1 -1
  156. package/dist/core/compaction-support.js +0 -2
  157. package/dist/core/compaction-support.js.map +1 -1
  158. package/dist/core/context/artifact-retrieval.d.ts.map +1 -1
  159. package/dist/core/context/artifact-retrieval.js.map +1 -1
  160. package/dist/core/context/brain-curator.d.ts.map +1 -1
  161. package/dist/core/context/brain-curator.js +14 -33
  162. package/dist/core/context/brain-curator.js.map +1 -1
  163. package/dist/core/context/context-artifacts.d.ts.map +1 -1
  164. package/dist/core/context/context-artifacts.js +16 -24
  165. package/dist/core/context/context-artifacts.js.map +1 -1
  166. package/dist/core/context/context-audit.d.ts.map +1 -1
  167. package/dist/core/context/context-audit.js +3 -17
  168. package/dist/core/context/context-audit.js.map +1 -1
  169. package/dist/core/context/context-composition.d.ts.map +1 -1
  170. package/dist/core/context/context-composition.js.map +1 -1
  171. package/dist/core/context/context-item.d.ts.map +1 -1
  172. package/dist/core/context/context-item.js.map +1 -1
  173. package/dist/core/context/context-prompt-enforcement.d.ts.map +1 -1
  174. package/dist/core/context/context-prompt-enforcement.js +3 -16
  175. package/dist/core/context/context-prompt-enforcement.js.map +1 -1
  176. package/dist/core/context/context-prompt-policy.d.ts.map +1 -1
  177. package/dist/core/context/context-prompt-policy.js.map +1 -1
  178. package/dist/core/context/context-retention.d.ts.map +1 -1
  179. package/dist/core/context/context-retention.js.map +1 -1
  180. package/dist/core/context/context-store-retention.d.ts.map +1 -1
  181. package/dist/core/context/context-store-retention.js.map +1 -1
  182. package/dist/core/context/context-store.d.ts.map +1 -1
  183. package/dist/core/context/context-store.js.map +1 -1
  184. package/dist/core/context/context-tool-result.d.ts +4 -0
  185. package/dist/core/context/context-tool-result.d.ts.map +1 -0
  186. package/dist/core/context/context-tool-result.js +15 -0
  187. package/dist/core/context/context-tool-result.js.map +1 -0
  188. package/dist/core/context/current-work-memory.d.ts.map +1 -1
  189. package/dist/core/context/current-work-memory.js.map +1 -1
  190. package/dist/core/context/file-store-memory-provider.d.ts.map +1 -1
  191. package/dist/core/context/file-store-memory-provider.js +7 -28
  192. package/dist/core/context/file-store-memory-provider.js.map +1 -1
  193. package/dist/core/context/local-memory-search.d.ts +11 -0
  194. package/dist/core/context/local-memory-search.d.ts.map +1 -0
  195. package/dist/core/context/local-memory-search.js +37 -0
  196. package/dist/core/context/local-memory-search.js.map +1 -0
  197. package/dist/core/context/long-term-memory-trigger.d.ts.map +1 -1
  198. package/dist/core/context/long-term-memory-trigger.js.map +1 -1
  199. package/dist/core/context/memory-diagnostics.d.ts.map +1 -1
  200. package/dist/core/context/memory-diagnostics.js.map +1 -1
  201. package/dist/core/context/memory-index-store.d.ts.map +1 -1
  202. package/dist/core/context/memory-index-store.js.map +1 -1
  203. package/dist/core/context/memory-prompt-block.d.ts.map +1 -1
  204. package/dist/core/context/memory-prompt-block.js.map +1 -1
  205. package/dist/core/context/memory-prompt-budget.d.ts.map +1 -1
  206. package/dist/core/context/memory-prompt-budget.js.map +1 -1
  207. package/dist/core/context/memory-provider-contract.d.ts.map +1 -1
  208. package/dist/core/context/memory-provider-contract.js.map +1 -1
  209. package/dist/core/context/memory-retrieval.d.ts.map +1 -1
  210. package/dist/core/context/memory-retrieval.js.map +1 -1
  211. package/dist/core/context/memory-tier-composer.d.ts.map +1 -1
  212. package/dist/core/context/memory-tier-composer.js.map +1 -1
  213. package/dist/core/context/message-text.d.ts +7 -0
  214. package/dist/core/context/message-text.d.ts.map +1 -0
  215. package/dist/core/context/message-text.js +68 -0
  216. package/dist/core/context/message-text.js.map +1 -0
  217. package/dist/core/context/okf-memory-provider.d.ts.map +1 -1
  218. package/dist/core/context/okf-memory-provider.js +4 -30
  219. package/dist/core/context/okf-memory-provider.js.map +1 -1
  220. package/dist/core/context/okf-memory.d.ts.map +1 -1
  221. package/dist/core/context/okf-memory.js.map +1 -1
  222. package/dist/core/context/policy-engine.d.ts.map +1 -1
  223. package/dist/core/context/policy-engine.js.map +1 -1
  224. package/dist/core/context/policy-types.d.ts.map +1 -1
  225. package/dist/core/context/sqlite-runtime-index.d.ts.map +1 -1
  226. package/dist/core/context/sqlite-runtime-index.js.map +1 -1
  227. package/dist/core/context/storage-authority.d.ts.map +1 -1
  228. package/dist/core/context/tool-output-packer.d.ts.map +1 -1
  229. package/dist/core/context/tool-output-packer.js.map +1 -1
  230. package/dist/core/context-gc.d.ts.map +1 -1
  231. package/dist/core/context-gc.js +14 -21
  232. package/dist/core/context-gc.js.map +1 -1
  233. package/dist/core/context-pipeline.d.ts +1 -3
  234. package/dist/core/context-pipeline.d.ts.map +1 -1
  235. package/dist/core/context-pipeline.js +64 -145
  236. package/dist/core/context-pipeline.js.map +1 -1
  237. package/dist/core/cost/cost-summary.d.ts.map +1 -1
  238. package/dist/core/cost/cost-summary.js.map +1 -1
  239. package/dist/core/cost/daily-usage.d.ts.map +1 -1
  240. package/dist/core/cost/daily-usage.js.map +1 -1
  241. package/dist/core/cost/session-usage.d.ts.map +1 -1
  242. package/dist/core/cost/session-usage.js.map +1 -1
  243. package/dist/core/cost-guard.d.ts.map +1 -1
  244. package/dist/core/cost-guard.js.map +1 -1
  245. package/dist/core/default-tool-surface.d.ts.map +1 -1
  246. package/dist/core/default-tool-surface.js +1 -0
  247. package/dist/core/default-tool-surface.js.map +1 -1
  248. package/dist/core/defaults.d.ts.map +1 -1
  249. package/dist/core/delegation/managed-lane-controller.d.ts.map +1 -1
  250. package/dist/core/delegation/managed-lane-controller.js +2 -6
  251. package/dist/core/delegation/managed-lane-controller.js.map +1 -1
  252. package/dist/core/delegation/session-worker-claim.d.ts.map +1 -1
  253. package/dist/core/delegation/session-worker-claim.js.map +1 -1
  254. package/dist/core/delegation/worker-action-journal.d.ts.map +1 -1
  255. package/dist/core/delegation/worker-action-journal.js +0 -4
  256. package/dist/core/delegation/worker-action-journal.js.map +1 -1
  257. package/dist/core/delegation/worker-actions.d.ts.map +1 -1
  258. package/dist/core/delegation/worker-actions.js.map +1 -1
  259. package/dist/core/delegation/worker-agent-control-coordinator.d.ts +1 -0
  260. package/dist/core/delegation/worker-agent-control-coordinator.d.ts.map +1 -1
  261. package/dist/core/delegation/worker-agent-control-coordinator.js +13 -15
  262. package/dist/core/delegation/worker-agent-control-coordinator.js.map +1 -1
  263. package/dist/core/delegation/worker-agent-control.d.ts.map +1 -1
  264. package/dist/core/delegation/worker-agent-control.js +1 -4
  265. package/dist/core/delegation/worker-agent-control.js.map +1 -1
  266. package/dist/core/delegation/worker-attempt-executor.d.ts.map +1 -1
  267. package/dist/core/delegation/worker-attempt-executor.js.map +1 -1
  268. package/dist/core/delegation/worker-claim.d.ts.map +1 -1
  269. package/dist/core/delegation/worker-claim.js.map +1 -1
  270. package/dist/core/delegation/worker-conversation-store.d.ts.map +1 -1
  271. package/dist/core/delegation/worker-conversation-store.js +0 -2
  272. package/dist/core/delegation/worker-conversation-store.js.map +1 -1
  273. package/dist/core/delegation/worker-delegation-controller.d.ts.map +1 -1
  274. package/dist/core/delegation/worker-delegation-controller.js +5 -14
  275. package/dist/core/delegation/worker-delegation-controller.js.map +1 -1
  276. package/dist/core/delegation/worker-delegation-request.d.ts.map +1 -1
  277. package/dist/core/delegation/worker-dispatch-scheduler.d.ts.map +1 -1
  278. package/dist/core/delegation/worker-dispatch-scheduler.js +5 -6
  279. package/dist/core/delegation/worker-dispatch-scheduler.js.map +1 -1
  280. package/dist/core/delegation/worker-execution-policy.d.ts.map +1 -1
  281. package/dist/core/delegation/worker-execution-policy.js.map +1 -1
  282. package/dist/core/delegation/worker-lane-projection.d.ts.map +1 -1
  283. package/dist/core/delegation/worker-lane-projection.js.map +1 -1
  284. package/dist/core/delegation/worker-lifecycle.d.ts.map +1 -1
  285. package/dist/core/delegation/worker-lifecycle.js +0 -3
  286. package/dist/core/delegation/worker-lifecycle.js.map +1 -1
  287. package/dist/core/delegation/worker-notification-coordinator.d.ts.map +1 -1
  288. package/dist/core/delegation/worker-notification-coordinator.js +4 -5
  289. package/dist/core/delegation/worker-notification-coordinator.js.map +1 -1
  290. package/dist/core/delegation/worker-process-owner.d.ts.map +1 -1
  291. package/dist/core/delegation/worker-process-owner.js.map +1 -1
  292. package/dist/core/delegation/worker-profile-resolver.d.ts.map +1 -1
  293. package/dist/core/delegation/worker-profile-resolver.js +1 -2
  294. package/dist/core/delegation/worker-profile-resolver.js.map +1 -1
  295. package/dist/core/delegation/worker-recovery-coordinator.d.ts.map +1 -1
  296. package/dist/core/delegation/worker-recovery-coordinator.js +3 -4
  297. package/dist/core/delegation/worker-recovery-coordinator.js.map +1 -1
  298. package/dist/core/delegation/worker-resource-catalog.d.ts.map +1 -1
  299. package/dist/core/delegation/worker-resource-catalog.js.map +1 -1
  300. package/dist/core/delegation/worker-resource-materializer.d.ts.map +1 -1
  301. package/dist/core/delegation/worker-resource-materializer.js +1 -4
  302. package/dist/core/delegation/worker-resource-materializer.js.map +1 -1
  303. package/dist/core/delegation/worker-runner.d.ts +2 -4
  304. package/dist/core/delegation/worker-runner.d.ts.map +1 -1
  305. package/dist/core/delegation/worker-runner.js +6 -18
  306. package/dist/core/delegation/worker-runner.js.map +1 -1
  307. package/dist/core/delegation/worker-task-label.d.ts.map +1 -1
  308. package/dist/core/delegation/worker-task-label.js.map +1 -1
  309. package/dist/core/delegation/worker-terminal-finalizer.d.ts.map +1 -1
  310. package/dist/core/delegation/worker-terminal-finalizer.js.map +1 -1
  311. package/dist/core/delegation/worker-write-reservation-coordinator.d.ts.map +1 -1
  312. package/dist/core/delegation/worker-write-reservation-coordinator.js +1 -4
  313. package/dist/core/delegation/worker-write-reservation-coordinator.js.map +1 -1
  314. package/dist/core/delegation/worker-write-reservation.d.ts.map +1 -1
  315. package/dist/core/delegation/worker-write-reservation.js +0 -2
  316. package/dist/core/delegation/worker-write-reservation.js.map +1 -1
  317. package/dist/core/diagnostics.d.ts.map +1 -1
  318. package/dist/core/doctor.d.ts +5 -5
  319. package/dist/core/doctor.d.ts.map +1 -1
  320. package/dist/core/doctor.js +16 -20
  321. package/dist/core/doctor.js.map +1 -1
  322. package/dist/core/event-bus.d.ts.map +1 -1
  323. package/dist/core/event-bus.js.map +1 -1
  324. package/dist/core/exec.d.ts.map +1 -1
  325. package/dist/core/exec.js +26 -7
  326. package/dist/core/exec.js.map +1 -1
  327. package/dist/core/export-html/ansi-to-html.d.ts.map +1 -1
  328. package/dist/core/export-html/ansi-to-html.js +21 -74
  329. package/dist/core/export-html/ansi-to-html.js.map +1 -1
  330. package/dist/core/export-html/index.d.ts.map +1 -1
  331. package/dist/core/export-html/index.js +4 -0
  332. package/dist/core/export-html/index.js.map +1 -1
  333. package/dist/core/export-html/session-tree-foundations.d.mts +67 -0
  334. package/dist/core/export-html/session-tree-foundations.mjs +313 -0
  335. package/dist/core/export-html/template.css +14 -41
  336. package/dist/core/export-html/template.html +3 -1
  337. package/dist/core/export-html/template.js +26 -435
  338. package/dist/core/export-html/tool-renderer.d.ts.map +1 -1
  339. package/dist/core/export-html/tool-renderer.js.map +1 -1
  340. package/dist/core/extension-import-authority.d.ts.map +1 -1
  341. package/dist/core/extension-import-authority.js.map +1 -1
  342. package/dist/core/extension-metadata.d.ts.map +1 -1
  343. package/dist/core/extension-metadata.js.map +1 -1
  344. package/dist/core/extensions/builtin.d.ts +17 -0
  345. package/dist/core/extensions/builtin.d.ts.map +1 -1
  346. package/dist/core/extensions/builtin.js +18 -54
  347. package/dist/core/extensions/builtin.js.map +1 -1
  348. package/dist/core/extensions/entry-resolution.d.ts +3 -0
  349. package/dist/core/extensions/entry-resolution.d.ts.map +1 -0
  350. package/dist/core/extensions/entry-resolution.js +17 -0
  351. package/dist/core/extensions/entry-resolution.js.map +1 -0
  352. package/dist/core/extensions/index.d.ts.map +1 -1
  353. package/dist/core/extensions/loader.d.ts.map +1 -1
  354. package/dist/core/extensions/loader.js +76 -21
  355. package/dist/core/extensions/loader.js.map +1 -1
  356. package/dist/core/extensions/runner.d.ts +2 -0
  357. package/dist/core/extensions/runner.d.ts.map +1 -1
  358. package/dist/core/extensions/runner.js +41 -112
  359. package/dist/core/extensions/runner.js.map +1 -1
  360. package/dist/core/extensions/stale-context.d.ts.map +1 -1
  361. package/dist/core/extensions/storage.d.ts.map +1 -1
  362. package/dist/core/extensions/storage.js.map +1 -1
  363. package/dist/core/extensions/types.d.ts.map +1 -1
  364. package/dist/core/extensions/types.js.map +1 -1
  365. package/dist/core/extensions/wrapper.d.ts.map +1 -1
  366. package/dist/core/extensions/wrapper.js.map +1 -1
  367. package/dist/core/failure-corpus.d.ts.map +1 -1
  368. package/dist/core/failure-corpus.js +2 -5
  369. package/dist/core/failure-corpus.js.map +1 -1
  370. package/dist/core/footer-data-provider.d.ts.map +1 -1
  371. package/dist/core/footer-data-provider.js +27 -33
  372. package/dist/core/footer-data-provider.js.map +1 -1
  373. package/dist/core/foreground-recovery-controller.d.ts.map +1 -1
  374. package/dist/core/foreground-recovery-controller.js +0 -4
  375. package/dist/core/foreground-recovery-controller.js.map +1 -1
  376. package/dist/core/gateways/channel-provider.d.ts.map +1 -1
  377. package/dist/core/gateways/channel-provider.js +7 -5
  378. package/dist/core/gateways/channel-provider.js.map +1 -1
  379. package/dist/core/goal-loop-controller.d.ts.map +1 -1
  380. package/dist/core/goal-loop-controller.js +0 -1
  381. package/dist/core/goal-loop-controller.js.map +1 -1
  382. package/dist/core/goals/compact-goal-context.d.ts.map +1 -1
  383. package/dist/core/goals/compact-goal-context.js +2 -4
  384. package/dist/core/goals/compact-goal-context.js.map +1 -1
  385. package/dist/core/goals/goal-acceptance.d.ts.map +1 -1
  386. package/dist/core/goals/goal-acceptance.js.map +1 -1
  387. package/dist/core/goals/goal-auto-continue-controller.d.ts.map +1 -1
  388. package/dist/core/goals/goal-auto-continue-controller.js +1 -3
  389. package/dist/core/goals/goal-auto-continue-controller.js.map +1 -1
  390. package/dist/core/goals/goal-continuation-controller.d.ts.map +1 -1
  391. package/dist/core/goals/goal-continuation-controller.js.map +1 -1
  392. package/dist/core/goals/goal-continuation-defaults.d.ts.map +1 -1
  393. package/dist/core/goals/goal-continuation-prompt.d.ts.map +1 -1
  394. package/dist/core/goals/goal-continuation-prompt.js.map +1 -1
  395. package/dist/core/goals/goal-lifecycle.d.ts.map +1 -1
  396. package/dist/core/goals/goal-lifecycle.js.map +1 -1
  397. package/dist/core/goals/goal-record.d.ts.map +1 -1
  398. package/dist/core/goals/goal-record.js.map +1 -1
  399. package/dist/core/goals/goal-runtime-snapshot.d.ts.map +1 -1
  400. package/dist/core/goals/goal-runtime-snapshot.js.map +1 -1
  401. package/dist/core/goals/goal-session-controller.d.ts +15 -0
  402. package/dist/core/goals/goal-session-controller.d.ts.map +1 -1
  403. package/dist/core/goals/goal-session-controller.js +27 -3
  404. package/dist/core/goals/goal-session-controller.js.map +1 -1
  405. package/dist/core/goals/goal-state.d.ts.map +1 -1
  406. package/dist/core/goals/goal-state.js +35 -51
  407. package/dist/core/goals/goal-state.js.map +1 -1
  408. package/dist/core/goals/goal-tool-core.d.ts.map +1 -1
  409. package/dist/core/goals/goal-tool-core.js.map +1 -1
  410. package/dist/core/goals/natural-language-goal.d.ts +9 -0
  411. package/dist/core/goals/natural-language-goal.d.ts.map +1 -0
  412. package/dist/core/goals/natural-language-goal.js +23 -0
  413. package/dist/core/goals/natural-language-goal.js.map +1 -0
  414. package/dist/core/goals/session-goal-state.d.ts.map +1 -1
  415. package/dist/core/goals/session-goal-state.js.map +1 -1
  416. package/dist/core/http-dispatcher.d.ts.map +1 -1
  417. package/dist/core/http-dispatcher.js.map +1 -1
  418. package/dist/core/human-input-controller.d.ts.map +1 -1
  419. package/dist/core/human-input-controller.js +2 -3
  420. package/dist/core/human-input-controller.js.map +1 -1
  421. package/dist/core/human-input.d.ts.map +1 -1
  422. package/dist/core/human-input.js.map +1 -1
  423. package/dist/core/improvement-loop.d.ts.map +1 -1
  424. package/dist/core/improvement-loop.js +11 -11
  425. package/dist/core/improvement-loop.js.map +1 -1
  426. package/dist/core/index.d.ts.map +1 -1
  427. package/dist/core/install-telemetry.d.ts.map +1 -1
  428. package/dist/core/install-telemetry.js.map +1 -1
  429. package/dist/core/isolated-text-completion.d.ts +17 -0
  430. package/dist/core/isolated-text-completion.d.ts.map +1 -0
  431. package/dist/core/isolated-text-completion.js +15 -0
  432. package/dist/core/isolated-text-completion.js.map +1 -0
  433. package/dist/core/keybindings.d.ts +47 -2
  434. package/dist/core/keybindings.d.ts.map +1 -1
  435. package/dist/core/keybindings.js +12 -1
  436. package/dist/core/keybindings.js.map +1 -1
  437. package/dist/core/learning/learning-audit.d.ts.map +1 -1
  438. package/dist/core/learning/learning-audit.js.map +1 -1
  439. package/dist/core/learning/learning-gate.d.ts.map +1 -1
  440. package/dist/core/learning/learning-gate.js.map +1 -1
  441. package/dist/core/learning/observation-store.d.ts.map +1 -1
  442. package/dist/core/learning/observation-store.js +0 -2
  443. package/dist/core/learning/observation-store.js.map +1 -1
  444. package/dist/core/learning/reflection-engine.d.ts +1 -1
  445. package/dist/core/learning/reflection-engine.d.ts.map +1 -1
  446. package/dist/core/learning/reflection-engine.js +3 -0
  447. package/dist/core/learning/reflection-engine.js.map +1 -1
  448. package/dist/core/learning/reflection-turn-analysis.d.ts +20 -0
  449. package/dist/core/learning/reflection-turn-analysis.d.ts.map +1 -0
  450. package/dist/core/learning/reflection-turn-analysis.js +136 -0
  451. package/dist/core/learning/reflection-turn-analysis.js.map +1 -0
  452. package/dist/core/learning/session-learning-decision.d.ts.map +1 -1
  453. package/dist/core/learning/session-learning-decision.js.map +1 -1
  454. package/dist/core/learning/skill-curator.d.ts.map +1 -1
  455. package/dist/core/learning/skill-curator.js +0 -3
  456. package/dist/core/learning/skill-curator.js.map +1 -1
  457. package/dist/core/local-runtime-controller.d.ts +39 -0
  458. package/dist/core/local-runtime-controller.d.ts.map +1 -1
  459. package/dist/core/local-runtime-controller.js +41 -62
  460. package/dist/core/local-runtime-controller.js.map +1 -1
  461. package/dist/core/memory/effectiveness-tracker.d.ts.map +1 -1
  462. package/dist/core/memory/effectiveness-tracker.js +4 -2
  463. package/dist/core/memory/effectiveness-tracker.js.map +1 -1
  464. package/dist/core/memory/memory-manager.d.ts.map +1 -1
  465. package/dist/core/memory/memory-manager.js +7 -7
  466. package/dist/core/memory/memory-manager.js.map +1 -1
  467. package/dist/core/memory/memory-provider.d.ts.map +1 -1
  468. package/dist/core/memory/providers/file-store.d.ts +7 -0
  469. package/dist/core/memory/providers/file-store.d.ts.map +1 -1
  470. package/dist/core/memory/providers/file-store.js +48 -13
  471. package/dist/core/memory/providers/file-store.js.map +1 -1
  472. package/dist/core/memory/providers/transcript-recall-worker-protocol.d.ts +47 -0
  473. package/dist/core/memory/providers/transcript-recall-worker-protocol.d.ts.map +1 -0
  474. package/dist/core/memory/providers/transcript-recall-worker-protocol.js +50 -0
  475. package/dist/core/memory/providers/transcript-recall-worker-protocol.js.map +1 -0
  476. package/dist/core/memory/providers/transcript-recall-worker.d.ts +2 -0
  477. package/dist/core/memory/providers/transcript-recall-worker.d.ts.map +1 -0
  478. package/dist/core/memory/providers/transcript-recall-worker.js +143 -0
  479. package/dist/core/memory/providers/transcript-recall-worker.js.map +1 -0
  480. package/dist/core/memory/providers/transcript-recall.d.ts +24 -13
  481. package/dist/core/memory/providers/transcript-recall.d.ts.map +1 -1
  482. package/dist/core/memory/providers/transcript-recall.js +143 -141
  483. package/dist/core/memory/providers/transcript-recall.js.map +1 -1
  484. package/dist/core/memory/providers/user-memory-archive.d.ts +39 -0
  485. package/dist/core/memory/providers/user-memory-archive.d.ts.map +1 -0
  486. package/dist/core/memory/providers/user-memory-archive.js +258 -0
  487. package/dist/core/memory/providers/user-memory-archive.js.map +1 -0
  488. package/dist/core/memory/transcript-index.d.ts.map +1 -1
  489. package/dist/core/memory/transcript-index.js +1 -1
  490. package/dist/core/memory/transcript-index.js.map +1 -1
  491. package/dist/core/memory-controller.d.ts +9 -0
  492. package/dist/core/memory-controller.d.ts.map +1 -1
  493. package/dist/core/memory-controller.js +57 -16
  494. package/dist/core/memory-controller.js.map +1 -1
  495. package/dist/core/model-capability.d.ts.map +1 -1
  496. package/dist/core/model-capability.js.map +1 -1
  497. package/dist/core/model-output-json.d.ts +10 -0
  498. package/dist/core/model-output-json.d.ts.map +1 -0
  499. package/dist/core/model-output-json.js +43 -0
  500. package/dist/core/model-output-json.js.map +1 -0
  501. package/dist/core/model-registry.d.ts +8 -8
  502. package/dist/core/model-registry.d.ts.map +1 -1
  503. package/dist/core/model-registry.js +29 -52
  504. package/dist/core/model-registry.js.map +1 -1
  505. package/dist/core/model-resolver.d.ts.map +1 -1
  506. package/dist/core/model-resolver.js +1 -1
  507. package/dist/core/model-resolver.js.map +1 -1
  508. package/dist/core/model-router/config-diagnostics.d.ts.map +1 -1
  509. package/dist/core/model-router/config-diagnostics.js.map +1 -1
  510. package/dist/core/model-router/executor-route.d.ts.map +1 -1
  511. package/dist/core/model-router/executor-route.js.map +1 -1
  512. package/dist/core/model-router/fitness-gate.d.ts.map +1 -1
  513. package/dist/core/model-router/fitness-gate.js.map +1 -1
  514. package/dist/core/model-router/intent-classifier.d.ts.map +1 -1
  515. package/dist/core/model-router/route-judge.d.ts.map +1 -1
  516. package/dist/core/model-router/route-judge.js +18 -36
  517. package/dist/core/model-router/route-judge.js.map +1 -1
  518. package/dist/core/model-router/session-buffer.d.ts.map +1 -1
  519. package/dist/core/model-router/session-buffer.js.map +1 -1
  520. package/dist/core/model-router/status.d.ts.map +1 -1
  521. package/dist/core/model-router/status.js.map +1 -1
  522. package/dist/core/model-router/tool-escalation.d.ts.map +1 -1
  523. package/dist/core/model-router/tool-escalation.js.map +1 -1
  524. package/dist/core/model-router-controller.d.ts +1 -0
  525. package/dist/core/model-router-controller.d.ts.map +1 -1
  526. package/dist/core/model-router-controller.js +25 -56
  527. package/dist/core/model-router-controller.js.map +1 -1
  528. package/dist/core/model-selection-controller.d.ts +10 -0
  529. package/dist/core/model-selection-controller.d.ts.map +1 -1
  530. package/dist/core/model-selection-controller.js +0 -1
  531. package/dist/core/model-selection-controller.js.map +1 -1
  532. package/dist/core/model-tool-protocol.d.ts.map +1 -1
  533. package/dist/core/model-tool-protocol.js.map +1 -1
  534. package/dist/core/models/adaptation-store.d.ts.map +1 -1
  535. package/dist/core/models/adaptation-store.js +0 -1
  536. package/dist/core/models/adaptation-store.js.map +1 -1
  537. package/dist/core/models/context-sizing.d.ts.map +1 -1
  538. package/dist/core/models/context-sizing.js.map +1 -1
  539. package/dist/core/models/default-model-suggestions.d.ts.map +1 -1
  540. package/dist/core/models/default-model-suggestions.js.map +1 -1
  541. package/dist/core/models/fitness-store.d.ts.map +1 -1
  542. package/dist/core/models/fitness-store.js +0 -1
  543. package/dist/core/models/fitness-store.js.map +1 -1
  544. package/dist/core/models/host-state-store.d.ts.map +1 -1
  545. package/dist/core/models/host-state-store.js +1 -6
  546. package/dist/core/models/host-state-store.js.map +1 -1
  547. package/dist/core/models/llamacpp-runtime.d.ts +4 -19
  548. package/dist/core/models/llamacpp-runtime.d.ts.map +1 -1
  549. package/dist/core/models/llamacpp-runtime.js +32 -136
  550. package/dist/core/models/llamacpp-runtime.js.map +1 -1
  551. package/dist/core/models/local-registration.d.ts.map +1 -1
  552. package/dist/core/models/local-registration.js +82 -115
  553. package/dist/core/models/local-registration.js.map +1 -1
  554. package/dist/core/models/local-runtime.d.ts +12 -18
  555. package/dist/core/models/local-runtime.d.ts.map +1 -1
  556. package/dist/core/models/local-runtime.js +60 -204
  557. package/dist/core/models/local-runtime.js.map +1 -1
  558. package/dist/core/models/model-endpoint.d.ts.map +1 -1
  559. package/dist/core/models/model-endpoint.js.map +1 -1
  560. package/dist/core/models/model-ref.d.ts.map +1 -1
  561. package/dist/core/models/model-ref.js.map +1 -1
  562. package/dist/core/models/needle-runtime.d.ts +7 -3
  563. package/dist/core/models/needle-runtime.d.ts.map +1 -1
  564. package/dist/core/models/needle-runtime.js +16 -92
  565. package/dist/core/models/needle-runtime.js.map +1 -1
  566. package/dist/core/models/perf-profile.d.ts +1 -1
  567. package/dist/core/models/perf-profile.d.ts.map +1 -1
  568. package/dist/core/models/perf-profile.js +6 -13
  569. package/dist/core/models/perf-profile.js.map +1 -1
  570. package/dist/core/models/prism-llamacpp-lifecycle.d.ts.map +1 -1
  571. package/dist/core/models/prism-llamacpp-lifecycle.js.map +1 -1
  572. package/dist/core/models/runtime-arbiter.d.ts.map +1 -1
  573. package/dist/core/models/runtime-arbiter.js +3 -15
  574. package/dist/core/models/runtime-arbiter.js.map +1 -1
  575. package/dist/core/models/runtime-process.d.ts +100 -0
  576. package/dist/core/models/runtime-process.d.ts.map +1 -0
  577. package/dist/core/models/runtime-process.js +183 -0
  578. package/dist/core/models/runtime-process.js.map +1 -0
  579. package/dist/core/orchestration/agent-resume.d.ts.map +1 -1
  580. package/dist/core/orchestration/agent-resume.js.map +1 -1
  581. package/dist/core/orchestration/attempt-usage.d.ts.map +1 -1
  582. package/dist/core/orchestration/attempt-usage.js.map +1 -1
  583. package/dist/core/orchestration/capability-gateway.d.ts.map +1 -1
  584. package/dist/core/orchestration/capability-gateway.js +0 -14
  585. package/dist/core/orchestration/capability-gateway.js.map +1 -1
  586. package/dist/core/orchestration/contracts.d.ts.map +1 -1
  587. package/dist/core/orchestration/contracts.js.map +1 -1
  588. package/dist/core/orchestration/delegation-ledger.d.ts.map +1 -1
  589. package/dist/core/orchestration/delegation-ledger.js +0 -2
  590. package/dist/core/orchestration/delegation-ledger.js.map +1 -1
  591. package/dist/core/orchestration/event-store.d.ts.map +1 -1
  592. package/dist/core/orchestration/event-store.js +1 -14
  593. package/dist/core/orchestration/event-store.js.map +1 -1
  594. package/dist/core/orchestration/lane-tool-manifests.d.ts.map +1 -1
  595. package/dist/core/orchestration/lane-tool-manifests.js.map +1 -1
  596. package/dist/core/orchestration/model-binding.d.ts.map +1 -1
  597. package/dist/core/orchestration/model-binding.js.map +1 -1
  598. package/dist/core/orchestration/policy-compiler.d.ts.map +1 -1
  599. package/dist/core/orchestration/policy-compiler.js +0 -3
  600. package/dist/core/orchestration/policy-compiler.js.map +1 -1
  601. package/dist/core/orchestration/policy-gate.d.ts.map +1 -1
  602. package/dist/core/orchestration/policy-gate.js +0 -2
  603. package/dist/core/orchestration/policy-gate.js.map +1 -1
  604. package/dist/core/orchestration/profile-registry.d.ts.map +1 -1
  605. package/dist/core/orchestration/profile-registry.js +1 -1
  606. package/dist/core/orchestration/profile-registry.js.map +1 -1
  607. package/dist/core/orchestration/profile-store.d.ts.map +1 -1
  608. package/dist/core/orchestration/profile-store.js +0 -3
  609. package/dist/core/orchestration/profile-store.js.map +1 -1
  610. package/dist/core/orchestration/risk-budget.d.ts.map +1 -1
  611. package/dist/core/orchestration/risk-budget.js.map +1 -1
  612. package/dist/core/orchestration/task-runtime.d.ts +1 -0
  613. package/dist/core/orchestration/task-runtime.d.ts.map +1 -1
  614. package/dist/core/orchestration/task-runtime.js +27 -42
  615. package/dist/core/orchestration/task-runtime.js.map +1 -1
  616. package/dist/core/orchestration/work-state-projection.d.ts.map +1 -1
  617. package/dist/core/orchestration/work-state-projection.js.map +1 -1
  618. package/dist/core/orchestration/worker-execution-contract.d.ts.map +1 -1
  619. package/dist/core/orchestration/worker-execution-contract.js.map +1 -1
  620. package/dist/core/orchestration/worker-result-adapter.d.ts.map +1 -1
  621. package/dist/core/orchestration/worker-result-adapter.js.map +1 -1
  622. package/dist/core/output-guard.d.ts.map +1 -1
  623. package/dist/core/output-guard.js.map +1 -1
  624. package/dist/core/package-manager.d.ts +3 -0
  625. package/dist/core/package-manager.d.ts.map +1 -1
  626. package/dist/core/package-manager.js +88 -353
  627. package/dist/core/package-manager.js.map +1 -1
  628. package/dist/core/process-identity.d.ts.map +1 -1
  629. package/dist/core/process-identity.js.map +1 -1
  630. package/dist/core/process-liveness.d.ts +3 -0
  631. package/dist/core/process-liveness.d.ts.map +1 -0
  632. package/dist/core/process-liveness.js +17 -0
  633. package/dist/core/process-liveness.js.map +1 -0
  634. package/dist/core/process-matrix/codes.d.ts.map +1 -1
  635. package/dist/core/process-matrix/resume-launcher.d.ts.map +1 -1
  636. package/dist/core/process-matrix/resume-launcher.js.map +1 -1
  637. package/dist/core/process-matrix/runtime.d.ts.map +1 -1
  638. package/dist/core/process-matrix/runtime.js.map +1 -1
  639. package/dist/core/process-matrix/store.d.ts.map +1 -1
  640. package/dist/core/process-matrix/store.js.map +1 -1
  641. package/dist/core/process-matrix/supervisor.d.ts.map +1 -1
  642. package/dist/core/process-matrix/supervisor.js.map +1 -1
  643. package/dist/core/profile-filter-controller.d.ts.map +1 -1
  644. package/dist/core/profile-filter-controller.js +7 -8
  645. package/dist/core/profile-filter-controller.js.map +1 -1
  646. package/dist/core/profile-registry.d.ts.map +1 -1
  647. package/dist/core/profile-registry.js +1 -2
  648. package/dist/core/profile-registry.js.map +1 -1
  649. package/dist/core/profile-resource-selection.d.ts.map +1 -1
  650. package/dist/core/profile-resource-selection.js +18 -59
  651. package/dist/core/profile-resource-selection.js.map +1 -1
  652. package/dist/core/prompt-markup.d.ts +3 -0
  653. package/dist/core/prompt-markup.d.ts.map +1 -0
  654. package/dist/core/prompt-markup.js +7 -0
  655. package/dist/core/prompt-markup.js.map +1 -0
  656. package/dist/core/prompt-templates.d.ts.map +1 -1
  657. package/dist/core/prompt-templates.js +13 -39
  658. package/dist/core/prompt-templates.js.map +1 -1
  659. package/dist/core/provider-display-names.d.ts.map +1 -1
  660. package/dist/core/python-runtime.d.ts.map +1 -1
  661. package/dist/core/python-runtime.js.map +1 -1
  662. package/dist/core/reflection-controller.d.ts +22 -1
  663. package/dist/core/reflection-controller.d.ts.map +1 -1
  664. package/dist/core/reflection-controller.js +143 -25
  665. package/dist/core/reflection-controller.js.map +1 -1
  666. package/dist/core/reload-blockers.d.ts +2 -1
  667. package/dist/core/reload-blockers.d.ts.map +1 -1
  668. package/dist/core/reload-blockers.js +4 -14
  669. package/dist/core/reload-blockers.js.map +1 -1
  670. package/dist/core/request-auth.d.ts.map +1 -1
  671. package/dist/core/request-auth.js.map +1 -1
  672. package/dist/core/research/automata-provider.d.ts.map +1 -1
  673. package/dist/core/research/automata-provider.js.map +1 -1
  674. package/dist/core/research/evidence-bundle.d.ts.map +1 -1
  675. package/dist/core/research/evidence-bundle.js.map +1 -1
  676. package/dist/core/research/lane-model-resolver.d.ts.map +1 -1
  677. package/dist/core/research/lane-model-resolver.js +0 -1
  678. package/dist/core/research/lane-model-resolver.js.map +1 -1
  679. package/dist/core/research/model-fitness-controller.d.ts.map +1 -1
  680. package/dist/core/research/model-fitness-controller.js +17 -33
  681. package/dist/core/research/model-fitness-controller.js.map +1 -1
  682. package/dist/core/research/model-fitness.d.ts.map +1 -1
  683. package/dist/core/research/model-fitness.js +4 -25
  684. package/dist/core/research/model-fitness.js.map +1 -1
  685. package/dist/core/research/research-gate.d.ts.map +1 -1
  686. package/dist/core/research/research-gate.js.map +1 -1
  687. package/dist/core/research/research-lane-controller.d.ts.map +1 -1
  688. package/dist/core/research/research-lane-controller.js +5 -10
  689. package/dist/core/research/research-lane-controller.js.map +1 -1
  690. package/dist/core/research/research-runner.d.ts +2 -4
  691. package/dist/core/research/research-runner.d.ts.map +1 -1
  692. package/dist/core/research/research-runner.js +17 -48
  693. package/dist/core/research/research-runner.js.map +1 -1
  694. package/dist/core/research/session-evidence-bundle.d.ts.map +1 -1
  695. package/dist/core/research/session-evidence-bundle.js.map +1 -1
  696. package/dist/core/research/workspace-collector.d.ts.map +1 -1
  697. package/dist/core/research/workspace-collector.js.map +1 -1
  698. package/dist/core/resolve-config-value.d.ts.map +1 -1
  699. package/dist/core/resolve-config-value.js.map +1 -1
  700. package/dist/core/resource-ignore.d.ts +6 -0
  701. package/dist/core/resource-ignore.d.ts.map +1 -0
  702. package/dist/core/resource-ignore.js +44 -0
  703. package/dist/core/resource-ignore.js.map +1 -0
  704. package/dist/core/resource-loader.d.ts +0 -1
  705. package/dist/core/resource-loader.d.ts.map +1 -1
  706. package/dist/core/resource-loader.js +52 -187
  707. package/dist/core/resource-loader.js.map +1 -1
  708. package/dist/core/resource-profile-blocks.d.ts +3 -1
  709. package/dist/core/resource-profile-blocks.d.ts.map +1 -1
  710. package/dist/core/resource-profile-blocks.js +8 -5
  711. package/dist/core/resource-profile-blocks.js.map +1 -1
  712. package/dist/core/resource-profile-equality.d.ts.map +1 -1
  713. package/dist/core/resource-profile-equality.js.map +1 -1
  714. package/dist/core/resource-traversal.d.ts +43 -0
  715. package/dist/core/resource-traversal.d.ts.map +1 -0
  716. package/dist/core/resource-traversal.js +84 -0
  717. package/dist/core/resource-traversal.js.map +1 -0
  718. package/dist/core/risk-classifier.d.ts.map +1 -1
  719. package/dist/core/risk-classifier.js.map +1 -1
  720. package/dist/core/runtime-builder.d.ts +4 -1
  721. package/dist/core/runtime-builder.d.ts.map +1 -1
  722. package/dist/core/runtime-builder.js +25 -50
  723. package/dist/core/runtime-builder.js.map +1 -1
  724. package/dist/core/scout-controller.d.ts.map +1 -1
  725. package/dist/core/scout-controller.js +0 -1
  726. package/dist/core/scout-controller.js.map +1 -1
  727. package/dist/core/sdk.d.ts.map +1 -1
  728. package/dist/core/sdk.js.map +1 -1
  729. package/dist/core/secrets/credential-exposure-guard.d.ts.map +1 -1
  730. package/dist/core/secrets/credential-exposure-guard.js +101 -43
  731. package/dist/core/secrets/credential-exposure-guard.js.map +1 -1
  732. package/dist/core/secrets/secret-dotenv.d.ts.map +1 -1
  733. package/dist/core/secrets/secret-dotenv.js +0 -1
  734. package/dist/core/secrets/secret-dotenv.js.map +1 -1
  735. package/dist/core/secrets/secret-vault-format.d.ts.map +1 -1
  736. package/dist/core/secrets/secret-vault-format.js +0 -1
  737. package/dist/core/secrets/secret-vault-format.js.map +1 -1
  738. package/dist/core/secrets/secret-vault.d.ts.map +1 -1
  739. package/dist/core/secrets/secret-vault.js +2 -10
  740. package/dist/core/secrets/secret-vault.js.map +1 -1
  741. package/dist/core/security/secret-text.d.ts.map +1 -1
  742. package/dist/core/security/secret-text.js.map +1 -1
  743. package/dist/core/security/untrusted-boundary.d.ts.map +1 -1
  744. package/dist/core/security/untrusted-boundary.js.map +1 -1
  745. package/dist/core/session-analytics.d.ts.map +1 -1
  746. package/dist/core/session-analytics.js +18 -50
  747. package/dist/core/session-analytics.js.map +1 -1
  748. package/dist/core/session-artifact-bundle.d.ts.map +1 -1
  749. package/dist/core/session-artifact-bundle.js.map +1 -1
  750. package/dist/core/session-cwd.d.ts.map +1 -1
  751. package/dist/core/session-cwd.js +0 -1
  752. package/dist/core/session-cwd.js.map +1 -1
  753. package/dist/core/session-entry-index.d.ts +8 -0
  754. package/dist/core/session-entry-index.d.ts.map +1 -0
  755. package/dist/core/session-entry-index.js +16 -0
  756. package/dist/core/session-entry-index.js.map +1 -0
  757. package/dist/core/session-image-store.d.ts.map +1 -1
  758. package/dist/core/session-image-store.js +0 -3
  759. package/dist/core/session-image-store.js.map +1 -1
  760. package/dist/core/session-jsonl-writer.d.ts +3 -0
  761. package/dist/core/session-jsonl-writer.d.ts.map +1 -0
  762. package/dist/core/session-jsonl-writer.js +38 -0
  763. package/dist/core/session-jsonl-writer.js.map +1 -0
  764. package/dist/core/session-manager-factory.d.ts.map +1 -1
  765. package/dist/core/session-manager-factory.js.map +1 -1
  766. package/dist/core/session-role.d.ts.map +1 -1
  767. package/dist/core/session-role.js.map +1 -1
  768. package/dist/core/session-snapshot.d.ts.map +1 -1
  769. package/dist/core/session-snapshot.js.map +1 -1
  770. package/dist/core/session-supervision-runtime.d.ts.map +1 -1
  771. package/dist/core/session-supervision-runtime.js +1 -4
  772. package/dist/core/session-supervision-runtime.js.map +1 -1
  773. package/dist/core/session-tree-navigator.d.ts.map +1 -1
  774. package/dist/core/session-tree-navigator.js +0 -1
  775. package/dist/core/session-tree-navigator.js.map +1 -1
  776. package/dist/core/settings-manager.d.ts +2 -1
  777. package/dist/core/settings-manager.d.ts.map +1 -1
  778. package/dist/core/settings-manager.js +64 -162
  779. package/dist/core/settings-manager.js.map +1 -1
  780. package/dist/core/skill-block.d.mts +8 -0
  781. package/dist/core/skill-block.mjs +52 -0
  782. package/dist/core/skill-discovery.d.ts +5 -0
  783. package/dist/core/skill-discovery.d.ts.map +1 -0
  784. package/dist/core/skill-discovery.js +34 -0
  785. package/dist/core/skill-discovery.js.map +1 -0
  786. package/dist/core/skills.d.ts.map +1 -1
  787. package/dist/core/skills.js +23 -159
  788. package/dist/core/skills.js.map +1 -1
  789. package/dist/core/slash-commands.d.ts.map +1 -1
  790. package/dist/core/source-info.d.ts.map +1 -1
  791. package/dist/core/source-info.js.map +1 -1
  792. package/dist/core/spawned-usage.d.ts +21 -0
  793. package/dist/core/spawned-usage.d.ts.map +1 -0
  794. package/dist/core/spawned-usage.js +29 -0
  795. package/dist/core/spawned-usage.js.map +1 -0
  796. package/dist/core/system-prompt-builder.d.ts +4 -0
  797. package/dist/core/system-prompt-builder.d.ts.map +1 -1
  798. package/dist/core/system-prompt-builder.js +15 -8
  799. package/dist/core/system-prompt-builder.js.map +1 -1
  800. package/dist/core/system-prompt.d.ts.map +1 -1
  801. package/dist/core/system-prompt.js +53 -35
  802. package/dist/core/system-prompt.js.map +1 -1
  803. package/dist/core/tasks/session-task-state.d.ts.map +1 -1
  804. package/dist/core/tasks/session-task-state.js.map +1 -1
  805. package/dist/core/tasks/task-command.d.ts.map +1 -1
  806. package/dist/core/tasks/task-command.js.map +1 -1
  807. package/dist/core/tasks/task-contract-monitor.d.ts.map +1 -1
  808. package/dist/core/tasks/task-contract-monitor.js.map +1 -1
  809. package/dist/core/tasks/task-projection.d.ts.map +1 -1
  810. package/dist/core/tasks/task-projection.js.map +1 -1
  811. package/dist/core/tasks/task-state.d.ts.map +1 -1
  812. package/dist/core/tasks/task-state.js.map +1 -1
  813. package/dist/core/text-preview.d.ts +4 -0
  814. package/dist/core/text-preview.d.ts.map +1 -0
  815. package/dist/core/text-preview.js +33 -0
  816. package/dist/core/text-preview.js.map +1 -0
  817. package/dist/core/timings.d.ts.map +1 -1
  818. package/dist/core/timings.js.map +1 -1
  819. package/dist/core/tool-capability-policy.d.ts.map +1 -1
  820. package/dist/core/tool-capability-policy.js.map +1 -1
  821. package/dist/core/tool-gate-controller.d.ts.map +1 -1
  822. package/dist/core/tool-gate-controller.js +86 -87
  823. package/dist/core/tool-gate-controller.js.map +1 -1
  824. package/dist/core/tool-protocol-controller.d.ts +4 -1
  825. package/dist/core/tool-protocol-controller.d.ts.map +1 -1
  826. package/dist/core/tool-protocol-controller.js +19 -23
  827. package/dist/core/tool-protocol-controller.js.map +1 -1
  828. package/dist/core/tool-recovery-log-records.d.ts.map +1 -1
  829. package/dist/core/tool-recovery-log-records.js.map +1 -1
  830. package/dist/core/tool-recovery-log-worker.d.ts.map +1 -1
  831. package/dist/core/tool-recovery-log-worker.js.map +1 -1
  832. package/dist/core/tool-recovery-logger.d.ts.map +1 -1
  833. package/dist/core/tool-recovery-logger.js +12 -24
  834. package/dist/core/tool-recovery-logger.js.map +1 -1
  835. package/dist/core/tool-recovery-stats.d.ts.map +1 -1
  836. package/dist/core/tool-recovery-stats.js +16 -22
  837. package/dist/core/tool-recovery-stats.js.map +1 -1
  838. package/dist/core/tool-repair-health.d.ts.map +1 -1
  839. package/dist/core/tool-repair-health.js.map +1 -1
  840. package/dist/core/tool-repair-settings.d.ts.map +1 -1
  841. package/dist/core/tool-repair-settings.js.map +1 -1
  842. package/dist/core/tool-selection/expected-utility.d.ts.map +1 -1
  843. package/dist/core/tool-selection/expected-utility.js.map +1 -1
  844. package/dist/core/tool-selection/promotion.d.ts.map +1 -1
  845. package/dist/core/tool-selection/promotion.js.map +1 -1
  846. package/dist/core/tool-selection/tool-performance-store.d.ts +2 -0
  847. package/dist/core/tool-selection/tool-performance-store.d.ts.map +1 -1
  848. package/dist/core/tool-selection/tool-performance-store.js +49 -7
  849. package/dist/core/tool-selection/tool-performance-store.js.map +1 -1
  850. package/dist/core/tool-selection/tool-phase-timing.d.ts +19 -0
  851. package/dist/core/tool-selection/tool-phase-timing.d.ts.map +1 -0
  852. package/dist/core/tool-selection/tool-phase-timing.js +63 -0
  853. package/dist/core/tool-selection/tool-phase-timing.js.map +1 -0
  854. package/dist/core/tool-selection/tool-selection-controller.d.ts +2 -5
  855. package/dist/core/tool-selection/tool-selection-controller.d.ts.map +1 -1
  856. package/dist/core/tool-selection/tool-selection-controller.js +50 -30
  857. package/dist/core/tool-selection/tool-selection-controller.js.map +1 -1
  858. package/dist/core/toolkit/reflex-interpreter.d.ts +16 -0
  859. package/dist/core/toolkit/reflex-interpreter.d.ts.map +1 -1
  860. package/dist/core/toolkit/reflex-interpreter.js +21 -0
  861. package/dist/core/toolkit/reflex-interpreter.js.map +1 -1
  862. package/dist/core/toolkit/script-registry.d.ts.map +1 -1
  863. package/dist/core/toolkit/script-registry.js.map +1 -1
  864. package/dist/core/toolkit/script-runner.d.ts.map +1 -1
  865. package/dist/core/toolkit/script-runner.js.map +1 -1
  866. package/dist/core/tools/artifact-retrieve.d.ts.map +1 -1
  867. package/dist/core/tools/artifact-retrieve.js.map +1 -1
  868. package/dist/core/tools/ask-question.d.ts +2 -3
  869. package/dist/core/tools/ask-question.d.ts.map +1 -1
  870. package/dist/core/tools/ask-question.js +14 -40
  871. package/dist/core/tools/ask-question.js.map +1 -1
  872. package/dist/core/tools/bash.d.ts +2 -0
  873. package/dist/core/tools/bash.d.ts.map +1 -1
  874. package/dist/core/tools/bash.js +83 -30
  875. package/dist/core/tools/bash.js.map +1 -1
  876. package/dist/core/tools/context-scout.d.ts.map +1 -1
  877. package/dist/core/tools/context-scout.js.map +1 -1
  878. package/dist/core/tools/delegate-status.d.ts.map +1 -1
  879. package/dist/core/tools/delegate-status.js +9 -7
  880. package/dist/core/tools/delegate-status.js.map +1 -1
  881. package/dist/core/tools/delegate.d.ts.map +1 -1
  882. package/dist/core/tools/delegate.js +6 -6
  883. package/dist/core/tools/delegate.js.map +1 -1
  884. package/dist/core/tools/edit-diff.d.ts.map +1 -1
  885. package/dist/core/tools/edit-diff.js.map +1 -1
  886. package/dist/core/tools/edit.d.ts.map +1 -1
  887. package/dist/core/tools/edit.js.map +1 -1
  888. package/dist/core/tools/extensionify.d.ts.map +1 -1
  889. package/dist/core/tools/extensionify.js.map +1 -1
  890. package/dist/core/tools/fff-search-backend.d.ts +19 -0
  891. package/dist/core/tools/fff-search-backend.d.ts.map +1 -1
  892. package/dist/core/tools/fff-search-backend.js +28 -2
  893. package/dist/core/tools/fff-search-backend.js.map +1 -1
  894. package/dist/core/tools/file-encoding-policy.d.ts.map +1 -1
  895. package/dist/core/tools/file-encoding-policy.js.map +1 -1
  896. package/dist/core/tools/file-mutation-queue.d.ts.map +1 -1
  897. package/dist/core/tools/file-mutation-queue.js.map +1 -1
  898. package/dist/core/tools/find.d.ts +1 -1
  899. package/dist/core/tools/find.d.ts.map +1 -1
  900. package/dist/core/tools/find.js +44 -108
  901. package/dist/core/tools/find.js.map +1 -1
  902. package/dist/core/tools/git-filter.d.ts.map +1 -1
  903. package/dist/core/tools/git-filter.js.map +1 -1
  904. package/dist/core/tools/goal.d.ts.map +1 -1
  905. package/dist/core/tools/goal.js +7 -7
  906. package/dist/core/tools/goal.js.map +1 -1
  907. package/dist/core/tools/grep.d.ts +1 -1
  908. package/dist/core/tools/grep.d.ts.map +1 -1
  909. package/dist/core/tools/grep.js +42 -102
  910. package/dist/core/tools/grep.js.map +1 -1
  911. package/dist/core/tools/index.d.ts.map +1 -1
  912. package/dist/core/tools/index.js.map +1 -1
  913. package/dist/core/tools/ls.d.ts.map +1 -1
  914. package/dist/core/tools/ls.js +20 -36
  915. package/dist/core/tools/ls.js.map +1 -1
  916. package/dist/core/tools/model-fitness.d.ts.map +1 -1
  917. package/dist/core/tools/model-fitness.js.map +1 -1
  918. package/dist/core/tools/orchestration-panel.d.ts +5 -0
  919. package/dist/core/tools/orchestration-panel.d.ts.map +1 -1
  920. package/dist/core/tools/orchestration-panel.js +5 -5
  921. package/dist/core/tools/orchestration-panel.js.map +1 -1
  922. package/dist/core/tools/output-accumulator.d.ts +2 -0
  923. package/dist/core/tools/output-accumulator.d.ts.map +1 -1
  924. package/dist/core/tools/output-accumulator.js +24 -36
  925. package/dist/core/tools/output-accumulator.js.map +1 -1
  926. package/dist/core/tools/path-utils.d.ts.map +1 -1
  927. package/dist/core/tools/path-utils.js.map +1 -1
  928. package/dist/core/tools/persistent-process-coordinator.d.ts +31 -0
  929. package/dist/core/tools/persistent-process-coordinator.d.ts.map +1 -0
  930. package/dist/core/tools/persistent-process-coordinator.js +123 -0
  931. package/dist/core/tools/persistent-process-coordinator.js.map +1 -0
  932. package/dist/core/tools/python.d.ts.map +1 -1
  933. package/dist/core/tools/python.js.map +1 -1
  934. package/dist/core/tools/read.d.ts.map +1 -1
  935. package/dist/core/tools/read.js +14 -13
  936. package/dist/core/tools/read.js.map +1 -1
  937. package/dist/core/tools/render-utils.d.ts +29 -0
  938. package/dist/core/tools/render-utils.d.ts.map +1 -1
  939. package/dist/core/tools/render-utils.js +31 -1
  940. package/dist/core/tools/render-utils.js.map +1 -1
  941. package/dist/core/tools/run-process.d.ts.map +1 -1
  942. package/dist/core/tools/run-process.js.map +1 -1
  943. package/dist/core/tools/run-toolkit-script.d.ts.map +1 -1
  944. package/dist/core/tools/run-toolkit-script.js.map +1 -1
  945. package/dist/core/tools/search-command-guard.d.ts +10 -0
  946. package/dist/core/tools/search-command-guard.d.ts.map +1 -1
  947. package/dist/core/tools/search-command-guard.js +118 -31
  948. package/dist/core/tools/search-command-guard.js.map +1 -1
  949. package/dist/core/tools/search-router.d.ts.map +1 -1
  950. package/dist/core/tools/search-router.js.map +1 -1
  951. package/dist/core/tools/search-tool-runtime.d.ts +19 -0
  952. package/dist/core/tools/search-tool-runtime.d.ts.map +1 -0
  953. package/dist/core/tools/search-tool-runtime.js +12 -0
  954. package/dist/core/tools/search-tool-runtime.js.map +1 -0
  955. package/dist/core/tools/secret-store.d.ts.map +1 -1
  956. package/dist/core/tools/secret-store.js.map +1 -1
  957. package/dist/core/tools/shell-command-parser.d.ts.map +1 -1
  958. package/dist/core/tools/shell-command-parser.js.map +1 -1
  959. package/dist/core/tools/shell-contract-router.d.ts.map +1 -1
  960. package/dist/core/tools/shell-contract-router.js +4 -1
  961. package/dist/core/tools/shell-contract-router.js.map +1 -1
  962. package/dist/core/tools/shell-execution-session.d.ts +4 -0
  963. package/dist/core/tools/shell-execution-session.d.ts.map +1 -0
  964. package/dist/core/tools/shell-execution-session.js +11 -0
  965. package/dist/core/tools/shell-execution-session.js.map +1 -0
  966. package/dist/core/tools/shell-output-projection.d.ts +49 -0
  967. package/dist/core/tools/shell-output-projection.d.ts.map +1 -0
  968. package/dist/core/tools/shell-output-projection.js +381 -0
  969. package/dist/core/tools/shell-output-projection.js.map +1 -0
  970. package/dist/core/tools/shell-session.d.ts +2 -13
  971. package/dist/core/tools/shell-session.d.ts.map +1 -1
  972. package/dist/core/tools/shell-session.js +36 -136
  973. package/dist/core/tools/shell-session.js.map +1 -1
  974. package/dist/core/tools/skill-audit.d.ts.map +1 -1
  975. package/dist/core/tools/skill-audit.js.map +1 -1
  976. package/dist/core/tools/skillify.d.ts.map +1 -1
  977. package/dist/core/tools/skillify.js.map +1 -1
  978. package/dist/core/tools/task-steps.d.ts +8 -8
  979. package/dist/core/tools/task-steps.d.ts.map +1 -1
  980. package/dist/core/tools/task-steps.js +17 -18
  981. package/dist/core/tools/task-steps.js.map +1 -1
  982. package/dist/core/tools/tmux-dispatch.d.ts.map +1 -1
  983. package/dist/core/tools/tmux-dispatch.js.map +1 -1
  984. package/dist/core/tools/tool-definition-wrapper.d.ts.map +1 -1
  985. package/dist/core/tools/tool-definition-wrapper.js.map +1 -1
  986. package/dist/core/tools/tool-task.d.ts +23 -0
  987. package/dist/core/tools/tool-task.d.ts.map +1 -0
  988. package/dist/core/tools/tool-task.js +93 -0
  989. package/dist/core/tools/tool-task.js.map +1 -0
  990. package/dist/core/tools/windows-shell-engine.d.ts +17 -11
  991. package/dist/core/tools/windows-shell-engine.d.ts.map +1 -1
  992. package/dist/core/tools/windows-shell-engine.js +339 -117
  993. package/dist/core/tools/windows-shell-engine.js.map +1 -1
  994. package/dist/core/tools/windows-shell-state.d.ts.map +1 -1
  995. package/dist/core/tools/windows-shell-state.js.map +1 -1
  996. package/dist/core/tools/worktree-sync.d.ts.map +1 -1
  997. package/dist/core/tools/worktree-sync.js +8 -12
  998. package/dist/core/tools/worktree-sync.js.map +1 -1
  999. package/dist/core/tools/write.d.ts.map +1 -1
  1000. package/dist/core/tools/write.js +0 -1
  1001. package/dist/core/tools/write.js.map +1 -1
  1002. package/dist/core/trust-manager.d.ts.map +1 -1
  1003. package/dist/core/trust-manager.js +7 -40
  1004. package/dist/core/trust-manager.js.map +1 -1
  1005. package/dist/core/util/atomic-file.d.ts +19 -0
  1006. package/dist/core/util/atomic-file.d.ts.map +1 -1
  1007. package/dist/core/util/atomic-file.js +50 -15
  1008. package/dist/core/util/atomic-file.js.map +1 -1
  1009. package/dist/core/util/bounded-file.d.ts.map +1 -1
  1010. package/dist/core/util/bounded-file.js.map +1 -1
  1011. package/dist/core/util/bounded-jsonl.d.ts.map +1 -1
  1012. package/dist/core/util/bounded-jsonl.js +2 -9
  1013. package/dist/core/util/bounded-jsonl.js.map +1 -1
  1014. package/dist/core/util/bounded-value.d.ts.map +1 -1
  1015. package/dist/core/util/bounded-value.js.map +1 -1
  1016. package/dist/core/util/json-size.d.ts +3 -0
  1017. package/dist/core/util/json-size.d.ts.map +1 -0
  1018. package/dist/core/util/json-size.js +95 -0
  1019. package/dist/core/util/json-size.js.map +1 -0
  1020. package/dist/core/util/minimatch-cache.d.ts.map +1 -1
  1021. package/dist/core/util/minimatch-cache.js.map +1 -1
  1022. package/dist/core/util/value-guards.d.ts.map +1 -1
  1023. package/dist/core/util/value-guards.js.map +1 -1
  1024. package/dist/core/worktree-sync/codes.d.ts.map +1 -1
  1025. package/dist/core/worktree-sync/git-engine.d.ts.map +1 -1
  1026. package/dist/core/worktree-sync/git-engine.js +20 -36
  1027. package/dist/core/worktree-sync/git-engine.js.map +1 -1
  1028. package/dist/core/worktree-sync/lane-gate.d.ts.map +1 -1
  1029. package/dist/core/worktree-sync/lane-gate.js +1 -4
  1030. package/dist/core/worktree-sync/lane-gate.js.map +1 -1
  1031. package/dist/core/worktree-sync/runtime.d.ts.map +1 -1
  1032. package/dist/core/worktree-sync/runtime.js.map +1 -1
  1033. package/dist/core/worktree-sync/store.d.ts.map +1 -1
  1034. package/dist/core/worktree-sync/store.js.map +1 -1
  1035. package/dist/core/worktree-sync/watcher.d.ts.map +1 -1
  1036. package/dist/core/worktree-sync/watcher.js.map +1 -1
  1037. package/dist/index.d.ts.map +1 -1
  1038. package/dist/index.js.map +1 -1
  1039. package/dist/main.d.ts.map +1 -1
  1040. package/dist/main.js +10 -32
  1041. package/dist/main.js.map +1 -1
  1042. package/dist/migrations.d.ts.map +1 -1
  1043. package/dist/migrations.js +6 -19
  1044. package/dist/migrations.js.map +1 -1
  1045. package/dist/modes/index.d.ts.map +1 -1
  1046. package/dist/modes/interactive/auth-dialogs-controller.d.ts +3 -0
  1047. package/dist/modes/interactive/auth-dialogs-controller.d.ts.map +1 -1
  1048. package/dist/modes/interactive/auth-dialogs-controller.js +96 -132
  1049. package/dist/modes/interactive/auth-dialogs-controller.js.map +1 -1
  1050. package/dist/modes/interactive/auto-learn-controller.d.ts +1 -31
  1051. package/dist/modes/interactive/auto-learn-controller.d.ts.map +1 -1
  1052. package/dist/modes/interactive/auto-learn-controller.js +86 -307
  1053. package/dist/modes/interactive/auto-learn-controller.js.map +1 -1
  1054. package/dist/modes/interactive/autocomplete-provider.d.ts.map +1 -1
  1055. package/dist/modes/interactive/autocomplete-provider.js.map +1 -1
  1056. package/dist/modes/interactive/autonomy-commands.d.ts.map +1 -1
  1057. package/dist/modes/interactive/autonomy-commands.js +2 -8
  1058. package/dist/modes/interactive/autonomy-commands.js.map +1 -1
  1059. package/dist/modes/interactive/clipboard-input.d.ts +5 -1
  1060. package/dist/modes/interactive/clipboard-input.d.ts.map +1 -1
  1061. package/dist/modes/interactive/clipboard-input.js +17 -0
  1062. package/dist/modes/interactive/clipboard-input.js.map +1 -1
  1063. package/dist/modes/interactive/compaction-queue.d.ts.map +1 -1
  1064. package/dist/modes/interactive/compaction-queue.js +13 -18
  1065. package/dist/modes/interactive/compaction-queue.js.map +1 -1
  1066. package/dist/modes/interactive/components/activity-lane.d.ts.map +1 -1
  1067. package/dist/modes/interactive/components/activity-lane.js +6 -10
  1068. package/dist/modes/interactive/components/activity-lane.js.map +1 -1
  1069. package/dist/modes/interactive/components/armin.d.ts +1 -0
  1070. package/dist/modes/interactive/components/armin.d.ts.map +1 -1
  1071. package/dist/modes/interactive/components/armin.js +10 -21
  1072. package/dist/modes/interactive/components/armin.js.map +1 -1
  1073. package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
  1074. package/dist/modes/interactive/components/assistant-message.js +1 -6
  1075. package/dist/modes/interactive/components/assistant-message.js.map +1 -1
  1076. package/dist/modes/interactive/components/bash-execution.d.ts.map +1 -1
  1077. package/dist/modes/interactive/components/bash-execution.js +4 -9
  1078. package/dist/modes/interactive/components/bash-execution.js.map +1 -1
  1079. package/dist/modes/interactive/components/bordered-loader.d.ts.map +1 -1
  1080. package/dist/modes/interactive/components/bordered-loader.js +0 -3
  1081. package/dist/modes/interactive/components/bordered-loader.js.map +1 -1
  1082. package/dist/modes/interactive/components/branch-summary-message.d.ts +3 -8
  1083. package/dist/modes/interactive/components/branch-summary-message.d.ts.map +1 -1
  1084. package/dist/modes/interactive/components/branch-summary-message.js +13 -35
  1085. package/dist/modes/interactive/components/branch-summary-message.js.map +1 -1
  1086. package/dist/modes/interactive/components/compaction-summary-message.d.ts +3 -8
  1087. package/dist/modes/interactive/components/compaction-summary-message.d.ts.map +1 -1
  1088. package/dist/modes/interactive/components/compaction-summary-message.js +14 -36
  1089. package/dist/modes/interactive/components/compaction-summary-message.js.map +1 -1
  1090. package/dist/modes/interactive/components/config-selector.d.ts +1 -0
  1091. package/dist/modes/interactive/components/config-selector.d.ts.map +1 -1
  1092. package/dist/modes/interactive/components/config-selector.js +20 -43
  1093. package/dist/modes/interactive/components/config-selector.js.map +1 -1
  1094. package/dist/modes/interactive/components/countdown-timer.d.ts.map +1 -1
  1095. package/dist/modes/interactive/components/countdown-timer.js +0 -5
  1096. package/dist/modes/interactive/components/countdown-timer.js.map +1 -1
  1097. package/dist/modes/interactive/components/custom-editor.d.ts +2 -0
  1098. package/dist/modes/interactive/components/custom-editor.d.ts.map +1 -1
  1099. package/dist/modes/interactive/components/custom-editor.js +4 -8
  1100. package/dist/modes/interactive/components/custom-editor.js.map +1 -1
  1101. package/dist/modes/interactive/components/custom-message.d.ts.map +1 -1
  1102. package/dist/modes/interactive/components/custom-message.js +1 -6
  1103. package/dist/modes/interactive/components/custom-message.js.map +1 -1
  1104. package/dist/modes/interactive/components/daxnuts.d.ts.map +1 -1
  1105. package/dist/modes/interactive/components/daxnuts.js +6 -8
  1106. package/dist/modes/interactive/components/daxnuts.js.map +1 -1
  1107. package/dist/modes/interactive/components/diff.d.ts.map +1 -1
  1108. package/dist/modes/interactive/components/diff.js.map +1 -1
  1109. package/dist/modes/interactive/components/dynamic-border.d.ts.map +1 -1
  1110. package/dist/modes/interactive/components/dynamic-border.js +0 -1
  1111. package/dist/modes/interactive/components/dynamic-border.js.map +1 -1
  1112. package/dist/modes/interactive/components/earendil-announcement.d.ts.map +1 -1
  1113. package/dist/modes/interactive/components/earendil-announcement.js.map +1 -1
  1114. package/dist/modes/interactive/components/expandable-markdown-message.d.ts +21 -0
  1115. package/dist/modes/interactive/components/expandable-markdown-message.d.ts.map +1 -0
  1116. package/dist/modes/interactive/components/expandable-markdown-message.js +48 -0
  1117. package/dist/modes/interactive/components/expandable-markdown-message.js.map +1 -0
  1118. package/dist/modes/interactive/components/expandable-text.d.ts.map +1 -1
  1119. package/dist/modes/interactive/components/expandable-text.js +0 -2
  1120. package/dist/modes/interactive/components/expandable-text.js.map +1 -1
  1121. package/dist/modes/interactive/components/extension-editor.d.ts.map +1 -1
  1122. package/dist/modes/interactive/components/extension-editor.js +1 -9
  1123. package/dist/modes/interactive/components/extension-editor.js.map +1 -1
  1124. package/dist/modes/interactive/components/extension-input.d.ts.map +1 -1
  1125. package/dist/modes/interactive/components/extension-input.js +2 -8
  1126. package/dist/modes/interactive/components/extension-input.js.map +1 -1
  1127. package/dist/modes/interactive/components/extension-selector.d.ts.map +1 -1
  1128. package/dist/modes/interactive/components/extension-selector.js +5 -20
  1129. package/dist/modes/interactive/components/extension-selector.js.map +1 -1
  1130. package/dist/modes/interactive/components/fitness-role-selector.d.ts.map +1 -1
  1131. package/dist/modes/interactive/components/fitness-role-selector.js +0 -1
  1132. package/dist/modes/interactive/components/fitness-role-selector.js.map +1 -1
  1133. package/dist/modes/interactive/components/footer.d.ts.map +1 -1
  1134. package/dist/modes/interactive/components/footer.js +1 -5
  1135. package/dist/modes/interactive/components/footer.js.map +1 -1
  1136. package/dist/modes/interactive/components/index.d.ts.map +1 -1
  1137. package/dist/modes/interactive/components/keybinding-hints.d.ts.map +1 -1
  1138. package/dist/modes/interactive/components/keybinding-hints.js.map +1 -1
  1139. package/dist/modes/interactive/components/login-dialog.d.ts.map +1 -1
  1140. package/dist/modes/interactive/components/login-dialog.js +4 -10
  1141. package/dist/modes/interactive/components/login-dialog.js.map +1 -1
  1142. package/dist/modes/interactive/components/model-selector.d.ts +2 -2
  1143. package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
  1144. package/dist/modes/interactive/components/model-selector.js +21 -44
  1145. package/dist/modes/interactive/components/model-selector.js.map +1 -1
  1146. package/dist/modes/interactive/components/model-suggestion-selector.d.ts.map +1 -1
  1147. package/dist/modes/interactive/components/model-suggestion-selector.js +0 -1
  1148. package/dist/modes/interactive/components/model-suggestion-selector.js.map +1 -1
  1149. package/dist/modes/interactive/components/oauth-selector.d.ts +1 -1
  1150. package/dist/modes/interactive/components/oauth-selector.d.ts.map +1 -1
  1151. package/dist/modes/interactive/components/oauth-selector.js +16 -32
  1152. package/dist/modes/interactive/components/oauth-selector.js.map +1 -1
  1153. package/dist/modes/interactive/components/profile-resource-editor.d.ts +3 -4
  1154. package/dist/modes/interactive/components/profile-resource-editor.d.ts.map +1 -1
  1155. package/dist/modes/interactive/components/profile-resource-editor.js +34 -93
  1156. package/dist/modes/interactive/components/profile-resource-editor.js.map +1 -1
  1157. package/dist/modes/interactive/components/profile-selector.d.ts.map +1 -1
  1158. package/dist/modes/interactive/components/profile-selector.js +0 -1
  1159. package/dist/modes/interactive/components/profile-selector.js.map +1 -1
  1160. package/dist/modes/interactive/components/scoped-models-selector.d.ts +3 -4
  1161. package/dist/modes/interactive/components/scoped-models-selector.d.ts.map +1 -1
  1162. package/dist/modes/interactive/components/scoped-models-selector.js +34 -79
  1163. package/dist/modes/interactive/components/scoped-models-selector.js.map +1 -1
  1164. package/dist/modes/interactive/components/selector-list.d.ts +63 -0
  1165. package/dist/modes/interactive/components/selector-list.d.ts.map +1 -0
  1166. package/dist/modes/interactive/components/selector-list.js +186 -0
  1167. package/dist/modes/interactive/components/selector-list.js.map +1 -0
  1168. package/dist/modes/interactive/components/session-selector-search.d.ts.map +1 -1
  1169. package/dist/modes/interactive/components/session-selector-search.js.map +1 -1
  1170. package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
  1171. package/dist/modes/interactive/components/session-selector.js +34 -59
  1172. package/dist/modes/interactive/components/session-selector.js.map +1 -1
  1173. package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
  1174. package/dist/modes/interactive/components/settings-selector.js +40 -138
  1175. package/dist/modes/interactive/components/settings-selector.js.map +1 -1
  1176. package/dist/modes/interactive/components/show-images-selector.d.ts +2 -4
  1177. package/dist/modes/interactive/components/show-images-selector.d.ts.map +1 -1
  1178. package/dist/modes/interactive/components/show-images-selector.js +9 -28
  1179. package/dist/modes/interactive/components/show-images-selector.js.map +1 -1
  1180. package/dist/modes/interactive/components/skill-invocation-message.d.ts +3 -8
  1181. package/dist/modes/interactive/components/skill-invocation-message.d.ts.map +1 -1
  1182. package/dist/modes/interactive/components/skill-invocation-message.js +12 -40
  1183. package/dist/modes/interactive/components/skill-invocation-message.js.map +1 -1
  1184. package/dist/modes/interactive/components/theme-selector.d.ts +2 -5
  1185. package/dist/modes/interactive/components/theme-selector.d.ts.map +1 -1
  1186. package/dist/modes/interactive/components/theme-selector.js +11 -37
  1187. package/dist/modes/interactive/components/theme-selector.js.map +1 -1
  1188. package/dist/modes/interactive/components/thinking-selector.d.ts +2 -4
  1189. package/dist/modes/interactive/components/thinking-selector.d.ts.map +1 -1
  1190. package/dist/modes/interactive/components/thinking-selector.js +9 -31
  1191. package/dist/modes/interactive/components/thinking-selector.js.map +1 -1
  1192. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  1193. package/dist/modes/interactive/components/tool-execution.js +9 -28
  1194. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  1195. package/dist/modes/interactive/components/tool-group.d.ts.map +1 -1
  1196. package/dist/modes/interactive/components/tool-group.js +2 -3
  1197. package/dist/modes/interactive/components/tool-group.js.map +1 -1
  1198. package/dist/modes/interactive/components/tool-panel-registry.d.ts.map +1 -1
  1199. package/dist/modes/interactive/components/tool-panel-registry.js +5 -3
  1200. package/dist/modes/interactive/components/tool-panel-registry.js.map +1 -1
  1201. package/dist/modes/interactive/components/tool-title.d.ts.map +1 -1
  1202. package/dist/modes/interactive/components/tool-title.js +0 -4
  1203. package/dist/modes/interactive/components/tool-title.js.map +1 -1
  1204. package/dist/modes/interactive/components/transcript-pager.d.ts +26 -0
  1205. package/dist/modes/interactive/components/transcript-pager.d.ts.map +1 -0
  1206. package/dist/modes/interactive/components/transcript-pager.js +81 -0
  1207. package/dist/modes/interactive/components/transcript-pager.js.map +1 -0
  1208. package/dist/modes/interactive/components/tree-selector.d.ts +1 -12
  1209. package/dist/modes/interactive/components/tree-selector.d.ts.map +1 -1
  1210. package/dist/modes/interactive/components/tree-selector.js +42 -402
  1211. package/dist/modes/interactive/components/tree-selector.js.map +1 -1
  1212. package/dist/modes/interactive/components/trust-selector.d.ts.map +1 -1
  1213. package/dist/modes/interactive/components/trust-selector.js +4 -16
  1214. package/dist/modes/interactive/components/trust-selector.js.map +1 -1
  1215. package/dist/modes/interactive/components/usage-action-selector.d.ts.map +1 -1
  1216. package/dist/modes/interactive/components/usage-action-selector.js +2 -10
  1217. package/dist/modes/interactive/components/usage-action-selector.js.map +1 -1
  1218. package/dist/modes/interactive/components/user-message-selector.d.ts.map +1 -1
  1219. package/dist/modes/interactive/components/user-message-selector.js +3 -6
  1220. package/dist/modes/interactive/components/user-message-selector.js.map +1 -1
  1221. package/dist/modes/interactive/components/user-message.d.ts.map +1 -1
  1222. package/dist/modes/interactive/components/user-message.js +0 -1
  1223. package/dist/modes/interactive/components/user-message.js.map +1 -1
  1224. package/dist/modes/interactive/components/visual-truncate.d.ts.map +1 -1
  1225. package/dist/modes/interactive/components/visual-truncate.js.map +1 -1
  1226. package/dist/modes/interactive/config-backup.d.ts.map +1 -1
  1227. package/dist/modes/interactive/config-backup.js.map +1 -1
  1228. package/dist/modes/interactive/editor-overlay-host.d.ts.map +1 -1
  1229. package/dist/modes/interactive/editor-overlay-host.js +0 -3
  1230. package/dist/modes/interactive/editor-overlay-host.js.map +1 -1
  1231. package/dist/modes/interactive/extension-ui-host.d.ts +2 -0
  1232. package/dist/modes/interactive/extension-ui-host.d.ts.map +1 -1
  1233. package/dist/modes/interactive/extension-ui-host.js +51 -72
  1234. package/dist/modes/interactive/extension-ui-host.js.map +1 -1
  1235. package/dist/modes/interactive/external-editor.d.ts.map +1 -1
  1236. package/dist/modes/interactive/external-editor.js +2 -15
  1237. package/dist/modes/interactive/external-editor.js.map +1 -1
  1238. package/dist/modes/interactive/history-reload-math.d.ts.map +1 -1
  1239. package/dist/modes/interactive/history-reload-math.js.map +1 -1
  1240. package/dist/modes/interactive/interactive-event-controller.d.ts.map +1 -1
  1241. package/dist/modes/interactive/interactive-event-controller.js +23 -16
  1242. package/dist/modes/interactive/interactive-event-controller.js.map +1 -1
  1243. package/dist/modes/interactive/interactive-mode.d.ts +13 -4
  1244. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  1245. package/dist/modes/interactive/interactive-mode.js +126 -207
  1246. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  1247. package/dist/modes/interactive/interactive-selection-prompts.d.ts +20 -0
  1248. package/dist/modes/interactive/interactive-selection-prompts.d.ts.map +1 -0
  1249. package/dist/modes/interactive/interactive-selection-prompts.js +43 -0
  1250. package/dist/modes/interactive/interactive-selection-prompts.js.map +1 -0
  1251. package/dist/modes/interactive/key-handlers.d.ts +2 -1
  1252. package/dist/modes/interactive/key-handlers.d.ts.map +1 -1
  1253. package/dist/modes/interactive/key-handlers.js +4 -2
  1254. package/dist/modes/interactive/key-handlers.js.map +1 -1
  1255. package/dist/modes/interactive/loaded-resources-view.d.ts.map +1 -1
  1256. package/dist/modes/interactive/loaded-resources-view.js.map +1 -1
  1257. package/dist/modes/interactive/local-model-commands.d.ts.map +1 -1
  1258. package/dist/modes/interactive/local-model-commands.js +4 -9
  1259. package/dist/modes/interactive/local-model-commands.js.map +1 -1
  1260. package/dist/modes/interactive/model-fitness-presentation.d.ts +21 -0
  1261. package/dist/modes/interactive/model-fitness-presentation.d.ts.map +1 -0
  1262. package/dist/modes/interactive/model-fitness-presentation.js +13 -0
  1263. package/dist/modes/interactive/model-fitness-presentation.js.map +1 -0
  1264. package/dist/modes/interactive/profile-menu-controller.d.ts +2 -0
  1265. package/dist/modes/interactive/profile-menu-controller.d.ts.map +1 -1
  1266. package/dist/modes/interactive/profile-menu-controller.js +79 -171
  1267. package/dist/modes/interactive/profile-menu-controller.js.map +1 -1
  1268. package/dist/modes/interactive/report-commands.d.ts +2 -0
  1269. package/dist/modes/interactive/report-commands.d.ts.map +1 -1
  1270. package/dist/modes/interactive/report-commands.js +12 -6
  1271. package/dist/modes/interactive/report-commands.js.map +1 -1
  1272. package/dist/modes/interactive/resource-display.d.ts.map +1 -1
  1273. package/dist/modes/interactive/resource-display.js.map +1 -1
  1274. package/dist/modes/interactive/resource-shell-commands.d.ts.map +1 -1
  1275. package/dist/modes/interactive/resource-shell-commands.js +6 -23
  1276. package/dist/modes/interactive/resource-shell-commands.js.map +1 -1
  1277. package/dist/modes/interactive/session-flow-commands.d.ts.map +1 -1
  1278. package/dist/modes/interactive/session-flow-commands.js +21 -25
  1279. package/dist/modes/interactive/session-flow-commands.js.map +1 -1
  1280. package/dist/modes/interactive/session-io-commands.d.ts.map +1 -1
  1281. package/dist/modes/interactive/session-io-commands.js.map +1 -1
  1282. package/dist/modes/interactive/session-replacement-errors.d.ts.map +1 -1
  1283. package/dist/modes/interactive/session-replacement-errors.js.map +1 -1
  1284. package/dist/modes/interactive/settings-selector-flow.d.ts.map +1 -1
  1285. package/dist/modes/interactive/settings-selector-flow.js.map +1 -1
  1286. package/dist/modes/interactive/signal-lifecycle.d.ts.map +1 -1
  1287. package/dist/modes/interactive/signal-lifecycle.js.map +1 -1
  1288. package/dist/modes/interactive/startup-checks.d.ts.map +1 -1
  1289. package/dist/modes/interactive/startup-checks.js +12 -8
  1290. package/dist/modes/interactive/startup-checks.js.map +1 -1
  1291. package/dist/modes/interactive/theme/theme.d.ts.map +1 -1
  1292. package/dist/modes/interactive/theme/theme.js +10 -76
  1293. package/dist/modes/interactive/theme/theme.js.map +1 -1
  1294. package/dist/modes/interactive/usage-commands.d.ts.map +1 -1
  1295. package/dist/modes/interactive/usage-commands.js.map +1 -1
  1296. package/dist/modes/print-mode.d.ts.map +1 -1
  1297. package/dist/modes/print-mode.js +5 -22
  1298. package/dist/modes/print-mode.js.map +1 -1
  1299. package/dist/modes/rpc/jsonl.d.ts.map +1 -1
  1300. package/dist/modes/rpc/jsonl.js +1 -1
  1301. package/dist/modes/rpc/jsonl.js.map +1 -1
  1302. package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
  1303. package/dist/modes/rpc/rpc-client.js +7 -8
  1304. package/dist/modes/rpc/rpc-client.js.map +1 -1
  1305. package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
  1306. package/dist/modes/rpc/rpc-mode.js +5 -20
  1307. package/dist/modes/rpc/rpc-mode.js.map +1 -1
  1308. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  1309. package/dist/modes/rpc/rpc-types.js.map +1 -1
  1310. package/dist/modes/termination-signals.d.ts +4 -0
  1311. package/dist/modes/termination-signals.d.ts.map +1 -0
  1312. package/dist/modes/termination-signals.js +21 -0
  1313. package/dist/modes/termination-signals.js.map +1 -0
  1314. package/dist/package-manager-cli.d.ts.map +1 -1
  1315. package/dist/package-manager-cli.js.map +1 -1
  1316. package/dist/utils/ansi-colors.d.ts +5 -0
  1317. package/dist/utils/ansi-colors.d.ts.map +1 -0
  1318. package/dist/utils/ansi-colors.js +38 -0
  1319. package/dist/utils/ansi-colors.js.map +1 -0
  1320. package/dist/utils/ansi.d.ts.map +1 -1
  1321. package/dist/utils/ansi.js.map +1 -1
  1322. package/dist/utils/changelog.d.ts.map +1 -1
  1323. package/dist/utils/changelog.js.map +1 -1
  1324. package/dist/utils/child-process.d.ts.map +1 -1
  1325. package/dist/utils/child-process.js.map +1 -1
  1326. package/dist/utils/clipboard-image.d.ts.map +1 -1
  1327. package/dist/utils/clipboard-image.js.map +1 -1
  1328. package/dist/utils/clipboard-native.d.ts.map +1 -1
  1329. package/dist/utils/clipboard-native.js.map +1 -1
  1330. package/dist/utils/clipboard.d.ts.map +1 -1
  1331. package/dist/utils/clipboard.js.map +1 -1
  1332. package/dist/utils/deprecation.d.ts.map +1 -1
  1333. package/dist/utils/deprecation.js.map +1 -1
  1334. package/dist/utils/exif-orientation.d.ts.map +1 -1
  1335. package/dist/utils/exif-orientation.js.map +1 -1
  1336. package/dist/utils/external-editor-command.d.ts.map +1 -1
  1337. package/dist/utils/external-editor-command.js.map +1 -1
  1338. package/dist/utils/frontmatter.d.ts.map +1 -1
  1339. package/dist/utils/frontmatter.js.map +1 -1
  1340. package/dist/utils/fs-watch.d.ts.map +1 -1
  1341. package/dist/utils/fs-watch.js.map +1 -1
  1342. package/dist/utils/git.d.ts.map +1 -1
  1343. package/dist/utils/git.js +20 -28
  1344. package/dist/utils/git.js.map +1 -1
  1345. package/dist/utils/highlight-js-languages.d.ts.map +1 -1
  1346. package/dist/utils/html.d.ts.map +1 -1
  1347. package/dist/utils/html.js.map +1 -1
  1348. package/dist/utils/image-convert.d.ts.map +1 -1
  1349. package/dist/utils/image-convert.js.map +1 -1
  1350. package/dist/utils/image-resize-core.d.ts.map +1 -1
  1351. package/dist/utils/image-resize-core.js.map +1 -1
  1352. package/dist/utils/image-resize-worker.d.ts.map +1 -1
  1353. package/dist/utils/image-resize-worker.js.map +1 -1
  1354. package/dist/utils/image-resize.d.ts.map +1 -1
  1355. package/dist/utils/image-resize.js.map +1 -1
  1356. package/dist/utils/json.d.ts.map +1 -1
  1357. package/dist/utils/json.js.map +1 -1
  1358. package/dist/utils/mime.d.ts.map +1 -1
  1359. package/dist/utils/mime.js.map +1 -1
  1360. package/dist/utils/open-browser.d.ts.map +1 -1
  1361. package/dist/utils/open-browser.js.map +1 -1
  1362. package/dist/utils/paths.d.ts.map +1 -1
  1363. package/dist/utils/paths.js.map +1 -1
  1364. package/dist/utils/photon.d.ts.map +1 -1
  1365. package/dist/utils/photon.js.map +1 -1
  1366. package/dist/utils/pi-user-agent.d.ts.map +1 -1
  1367. package/dist/utils/pi-user-agent.js.map +1 -1
  1368. package/dist/utils/platform.d.ts.map +1 -1
  1369. package/dist/utils/platform.js.map +1 -1
  1370. package/dist/utils/process-memory.d.ts.map +1 -1
  1371. package/dist/utils/process-memory.js.map +1 -1
  1372. package/dist/utils/safe-write-stream.d.ts.map +1 -1
  1373. package/dist/utils/safe-write-stream.js.map +1 -1
  1374. package/dist/utils/shell.d.ts.map +1 -1
  1375. package/dist/utils/shell.js.map +1 -1
  1376. package/dist/utils/sleep.d.ts.map +1 -1
  1377. package/dist/utils/sleep.js +2 -15
  1378. package/dist/utils/sleep.js.map +1 -1
  1379. package/dist/utils/stdin-events.d.ts +8 -0
  1380. package/dist/utils/stdin-events.d.ts.map +1 -0
  1381. package/dist/utils/stdin-events.js +19 -0
  1382. package/dist/utils/stdin-events.js.map +1 -0
  1383. package/dist/utils/syntax-highlight.d.ts.map +1 -1
  1384. package/dist/utils/syntax-highlight.js +20 -13
  1385. package/dist/utils/syntax-highlight.js.map +1 -1
  1386. package/dist/utils/tools-manager.d.ts +6 -1
  1387. package/dist/utils/tools-manager.d.ts.map +1 -1
  1388. package/dist/utils/tools-manager.js +59 -2
  1389. package/dist/utils/tools-manager.js.map +1 -1
  1390. package/dist/utils/version-check.d.ts.map +1 -1
  1391. package/dist/utils/version-check.js.map +1 -1
  1392. package/dist/utils/windows-self-update.d.ts.map +1 -1
  1393. package/dist/utils/windows-self-update.js.map +1 -1
  1394. package/dist/utils/work-directory.d.ts.map +1 -1
  1395. package/dist/utils/work-directory.js.map +1 -1
  1396. package/docs/compaction.md +11 -3
  1397. package/docs/development.md +1 -1
  1398. package/docs/sessions.md +6 -0
  1399. package/docs/settings.md +1 -1
  1400. package/docs/windows.md +28 -3
  1401. package/docs/work-directory.md +10 -2
  1402. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  1403. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  1404. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  1405. package/examples/extensions/sandbox/package-lock.json +2 -2
  1406. package/examples/extensions/sandbox/package.json +1 -1
  1407. package/examples/extensions/with-deps/package-lock.json +2 -2
  1408. package/examples/extensions/with-deps/package.json +1 -1
  1409. package/npm-shrinkwrap.json +27 -27
  1410. package/package.json +11 -11
  1411. package/dist/utils/streaming-lines.d.ts +0 -20
  1412. package/dist/utils/streaming-lines.d.ts.map +0 -1
  1413. package/dist/utils/streaming-lines.js +0 -79
  1414. package/dist/utils/streaming-lines.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"reflection-controller.js","sourceRoot":"","sources":["../../src/core/reflection-controller.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAC/D,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAIN,YAAY,EACZ,yBAAyB,GAEzB,MAAM,2BAA2B,CAAC;AAEnC,OAAO,EAKN,yBAAyB,GAIzB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACN,sBAAsB,EACtB,0BAA0B,GAG1B,MAAM,8BAA8B,CAAC;AAEtC,OAAO,EAAE,8BAA8B,EAA+B,MAAM,gC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AAS,CAAC,GAAG,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;YACpC,MAAM,eAAe,GAAG,WAAW,CAAC,OAAO,CAAC,UAAU,EAAE,GAAG,CAAC,CAAC,IAAI,EAAE,CAAC;YACpE,gGAAgG;YAChG,4EAA4E;YAC5E,MAAM,OAAO,GAAG,cAAc,IAAI,kBAAkB,eAAe,4HAA4H,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC;YAC/M,aAAa,CAAC,IAAI,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;YACtC,OAAO,IAAI,CAAC;QACb,CAAC;QAAC,MAAM,CAAC;YACR,oCAAoC;YACpC,OAAO,KAAK,CAAC;QACd,CAAC;IAAA,CACD;CACD","sourcesContent":["/**\n * Native reflection + learning-write controller.\n *\n * Extracted verbatim from agent-session.ts (god-file decomposition). Owns the end-of-loop reflection\n * pass (R2), the isolated-completion primitive it runs on, and the learning-apply/rollback path that\n * turns reflection writes into gated, audited durable memory/skill changes. It mutates NO session\n * fields — every durable effect goes through the bundled memory tool, the session log (via deps), or\n * the skills dir; the whole pass is best-effort and never throws into the turn loop. Reads live\n * session state (model/agent/registry/memory/settings) through narrow deps accessors rather than the\n * whole AgentSession.\n */\n\nimport { existsSync, mkdirSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport {\n\ttype Agent,\n\ttype AgentContext,\n\ttype AgentLoopConfig,\n\trunAgentLoop,\n\tstartAgentProviderRequest,\n\ttype ThinkingLevel,\n} from \"@caupulican/pi-agent-core\";\nimport type { SessionManager } from \"@caupulican/pi-agent-core/node\";\nimport {\n\ttype Api,\n\ttype AssistantMessage,\n\ttype Message,\n\ttype Model,\n\tresolveModelThinkingLevel,\n\ttype SimpleStreamOptions,\n\ttype TextContent,\n\ttype Usage,\n} from \"@caupulican/pi-ai\";\nimport {\n\tcomputeLaneAffinityKey,\n\tDEFAULT_ISOLATED_LANE_KIND,\n\ttype IsolatedCompletionOptions,\n\ttype IsolatedCompletionResult,\n} from \"./agent-session-contracts.ts\";\nimport type { LearningDecision } from \"./autonomy/contracts.ts\";\nimport { AUTONOMY_TELEMETRY_EVENT_TYPES, type AutonomyTelemetryEvent } from \"./autonomy/telemetry-events.ts\";\nimport {\n\tAPPLY_WRITE_REFUSED_REASON_CODE,\n\tappendLearningAuditSnapshot,\n\tcontradictionsForReflectionWrite,\n\tgetLearningAuditSnapshots,\n\ttype LearningAuditRecord,\n\tproposalFromReflectionWrite,\n\trollbackPlanForReflectionWrite,\n} from \"./learning/learning-audit.ts\";\nimport { evaluateLearningDecision } from \"./learning/learning-gate.ts\";\nimport { ObservationStore, observationKey } from \"./learning/observation-store.ts\";\nimport {\n\ttype DemandSignals,\n\tdecideDemand,\n\tReflectionEngine,\n\ttype ReflectionResult,\n\ttype ReflectionWrite,\n} from \"./learning/reflection-engine.ts\";\nimport type { MemoryManager } from \"./memory/memory-manager.ts\";\nimport type { ModelRegistry } from \"./model-registry.ts\";\nimport { registerInFlightWork } from \"./reload-blockers.ts\";\nimport type { SettingsManager } from \"./settings-manager.ts\";\nimport { runSkillAudit } from \"./tools/skill-audit.ts\";\n\nexport interface ReflectionControllerDeps {\n\t/** Current session model (fallback for an isolated call that omits its own model). */\n\tgetModel(): Model<Api> | undefined;\n\t/** The underlying agent — its `streamFn` runs the isolated completion. */\n\tgetAgent(): Agent;\n\t/** True when the session's stream fn is the raw `streamSimple` provider (auth must be injected). */\n\tisRawStreamSimple(): boolean;\n\t/** Model registry for API-key/header resolution on the raw-provider path. */\n\tgetModelRegistry(): ModelRegistry;\n\t/** Memory subsystem — the bundled `memory` tool applies durable writes; fresh block feeds reflection. */\n\tgetMemoryManager(): MemoryManager;\n\t/** Settings — the learning-apply policy (gate thresholds, auto-apply layers) is read here. */\n\tgetSettingsManager(): SettingsManager;\n\t/** Session log — audit snapshots and learning-audit reads go through this. */\n\tgetSessionManager(): SessionManager;\n\t/** Agent dir — reflection-promoted skills are written under `<agentDir>/skills/`. */\n\tgetAgentDir(): string;\n\t/** Child sessions must not learn — the pass returns null for them. */\n\tisChildSession(): boolean;\n\t/** Disposal short-circuits: no completion, no writes against a dead session. */\n\tisDisposed(): boolean;\n\t/** Session-lifetime abort signal — aborts an in-flight reflection completion on dispose. */\n\tgetReflectionSignal(): AbortSignal;\n\t/** Archive a promoted skill (rollback of a `promote_skill` write). */\n\tarchivePromotedSkill(name: string): boolean;\n\t/** G3/G8 autonomy telemetry sink for learning-gate outcomes and approval requests. */\n\temitAutonomyTelemetry(event: AutonomyTelemetryEvent): void;\n\t/** Account the reflection pass's token spend into the cost roll-up (idempotent on reportId). */\n\taddSpawnedUsage(\n\t\tusage: Usage,\n\t\topts?: { label?: string; sourceSessionId?: string; reportId?: string },\n\t): string | undefined;\n\t/** Persist a learning-gate decision snapshot to the session log. */\n\tsaveLearningDecisionSnapshot(decision: LearningDecision): string;\n\t/** Resolve text-tool fallback for the selected isolated model, not the foreground model. */\n\tresolveTextToolCallProtocol(model: Model<Api>): SimpleStreamOptions[\"textToolCallProtocol\"];\n\t/** Ensure a managed-local model is running/resident before any isolated lane calls it. */\n\tensureModelReady(model: Model<Api>): Promise<void>;\n\t/**\n\t * Session working directory — feeds the skill-overlap audit's project-local skill discovery, the\n\t * same `cwd` the model-invoked `skillify`/`skill_audit` tools already receive (tools/index.ts).\n\t * Optional so a host that has not wired it yet still resolves (falls back to `process.cwd()`,\n\t * mirroring the existing profile-resolution fallback in settings-manager.ts).\n\t */\n\tgetCwd?(): string;\n}\n\n// reasonCode when an automatic skill promotion is blocked by an overlap with an existing skill\n// (skill_audit's similarity threshold) and routed to a consolidation proposal instead of a blind write.\nexport const SKILL_OVERLAP_CONSOLIDATION_REASON_CODE = \"skill_overlap_consolidation_proposed\";\n// reasonCode when the overlap audit itself fails — the promotion is held (not written unaudited)\n// rather than silently skipping the check.\nexport const SKILL_AUDIT_UNAVAILABLE_REASON_CODE = \"skill_audit_unavailable\";\n\nexport class ReflectionController {\n\tprivate readonly deps: ReflectionControllerDeps;\n\n\tconstructor(deps: ReflectionControllerDeps) {\n\t\tthis.deps = deps;\n\t}\n\n\t/**\n\t * Run an LLM completion fully ISOLATED from the main session — the load-bearing primitive for\n\t * reflection and bounded child lanes (adaptive-agent design §6c/§7).\n\t *\n\t * Isolation invariants (audited by codex): builds fresh context (no main history), defaults to no\n\t * tools, and passes **no real `sessionId`** — only a deterministic SYNTHETIC cache-affinity key\n\t * (see {@link computeLaneAffinityKey}) derived from `(laneKind, model, systemPrompt)`, which can never\n\t * equal or embed the real session id. A tool-enabled call receives only caller-owned tools and hooks,\n\t * and applies a turn bound only when its owner explicitly supplies one. It cannot mutate `agent.state.messages`, append session entries, or touch the\n\t * foreground tool registry. Mirrors `generateSummary()`'s one-shot mechanics otherwise.\n\t *\n\t * Returns the result even on an error/aborted stop reason (callers — e.g. a background reflection\n\t * microtask — decide whether to act); it does not throw on a model-level error.\n\t */\n\tasync runIsolatedCompletion(opts: IsolatedCompletionOptions): Promise<IsolatedCompletionResult> {\n\t\tif (opts.maxTurns !== undefined && (!Number.isSafeInteger(opts.maxTurns) || opts.maxTurns <= 0)) {\n\t\t\tthrow new Error(\"runIsolatedCompletion: maxTurns must be a positive safe integer when provided\");\n\t\t}\n\t\tconst model = opts.model ?? this.deps.getModel();\n\t\tif (!model) {\n\t\t\tthrow new Error(\"runIsolatedCompletion: no model available\");\n\t\t}\n\t\tawait this.deps.ensureModelReady(model);\n\t\tconst thinkingLevel = resolveModelThinkingLevel(model, opts.thinkingLevel, \"off\");\n\n\t\t// Registered for the full isolated-completion call (one-shot or child-loop) so the\n\t\t// reload gate waits it out — this is the SINGLE choke point every isolated completion in the\n\t\t// codebase runs through (reflection, research/worker/fitness lanes, context-pipeline curation,\n\t\t// model-router judge calls). registerInFlightWork is a pure sync map op (cannot throw), so\n\t\t// placing it as the last statement before `try` still guarantees the matching finally always\n\t\t// runs, on every return path below and on any thrown error.\n\t\tconst deregisterInFlight = registerInFlightWork(\n\t\t\tthis.deps.getAgentDir(),\n\t\t\t\"isolated-completion\",\n\t\t\topts.laneKind ?? DEFAULT_ISOLATED_LANE_KIND,\n\t\t);\n\t\ttry {\n\t\t\t// Fresh, isolated context: explicit messages, caller-owned tools only, nothing from the main session.\n\t\t\tconst history = opts.history ?? [];\n\t\t\tconst context: AgentContext = {\n\t\t\t\tsystemPrompt: opts.systemPrompt,\n\t\t\t\tmessages: [...history, ...opts.messages],\n\t\t\t\ttools: opts.tools ?? [],\n\t\t\t};\n\n\t\t\t// Isolate the prompt cache from the main session by DELIBERATELY never sending the real\n\t\t\t// sessionId. In its place, a deterministic SYNTHETIC affinity key lets providers with\n\t\t\t// session-affinity headers / prompt_cache_key route repeat calls from the SAME lane (same\n\t\t\t// laneKind+model+systemPrompt) to the same cache-warm backend, without entangling this call\n\t\t\t// with — or leaking any identity of — the main session.\n\t\t\tconst affinityKey = computeLaneAffinityKey(\n\t\t\t\topts.laneKind ?? DEFAULT_ISOLATED_LANE_KIND,\n\t\t\t\tmodel,\n\t\t\t\topts.systemPrompt,\n\t\t\t);\n\t\t\tconst options: SimpleStreamOptions = {\n\t\t\t\tmaxTokens: opts.maxTokens,\n\t\t\t\tsignal: opts.signal,\n\t\t\t\tinteractionMode: \"background\",\n\t\t\t\tcacheRetention: opts.cacheRetention,\n\t\t\t\treasoning: thinkingLevel,\n\t\t\t\tsessionId: affinityKey,\n\t\t\t};\n\n\t\t\t// When streamFn is the raw streamSimple (e.g. in tests), auth must be injected explicitly.\n\t\t\t// Throw only when auth genuinely fails — providers that authenticate without an API key\n\t\t\t// (OAuth, local no-key) legitimately return ok with an undefined apiKey.\n\t\t\tif (this.deps.isRawStreamSimple()) {\n\t\t\t\tconst auth = await this.deps.getModelRegistry().getApiKeyAndHeaders(model);\n\t\t\t\tif (!auth.ok) {\n\t\t\t\t\tthrow new Error(auth.error);\n\t\t\t\t}\n\t\t\t\toptions.apiKey = auth.apiKey;\n\t\t\t\toptions.headers = auth.headers;\n\t\t\t}\n\t\t\tconst agent = this.deps.getAgent();\n\t\t\tconst foregroundModel = agent.state.model;\n\t\t\tconst usesForegroundModel = foregroundModel?.provider === model.provider && foregroundModel.id === model.id;\n\t\t\tconst textToolCallProtocol = this.deps.resolveTextToolCallProtocol(model);\n\t\t\tconst maxTurns = opts.maxTurns;\n\t\t\tlet completedTurns = 0;\n\t\t\tconst loopConfig: AgentLoopConfig = {\n\t\t\t\tmodel,\n\t\t\t\tinteractionMode: \"background\",\n\t\t\t\tmaxTokens: opts.maxTokens,\n\t\t\t\tcacheRetention: opts.cacheRetention,\n\t\t\t\treasoning: thinkingLevel,\n\t\t\t\t// Same synthetic per-lane affinity key as the one-shot path above — never the real sessionId.\n\t\t\t\tsessionId: affinityKey,\n\t\t\t\t...(options.apiKey !== undefined ? { apiKey: options.apiKey } : {}),\n\t\t\t\t...(options.headers !== undefined ? { headers: options.headers } : {}),\n\t\t\t\tgetApiKey: agent.getApiKey,\n\t\t\t\tresolveRequestReasoning: agent.resolveRequestReasoning,\n\t\t\t\ttemperature: textToolCallProtocol ? 0 : undefined,\n\t\t\t\ttextToolCallProtocol,\n\t\t\t\tonTextToolProtocolParse: usesForegroundModel ? agent.onTextToolProtocolParse : undefined,\n\t\t\t\ttransport: agent.transport,\n\t\t\t\tthinkingBudgets: agent.thinkingBudgets,\n\t\t\t\tmaxRetryDelayMs: agent.maxRetryDelayMs,\n\t\t\t\t// This remains independent from an owner-provided turn budget: it stops only repeated\n\t\t\t\t// identical tool calls, so legitimate long-running work can continue until completion.\n\t\t\t\tmaxStallTurns: agent.maxStallTurns,\n\t\t\t\tonRunawayStop: usesForegroundModel ? agent.onRunawayStop : undefined,\n\t\t\t\ttoolExecution: \"sequential\",\n\t\t\t\ttoolArgumentTeachEnabled: agent.toolArgumentTeachEnabled,\n\t\t\t\tonToolArgumentValidation: usesForegroundModel ? agent.onToolArgumentValidation : undefined,\n\t\t\t\ttoolValidationEscalationThreshold: agent.toolValidationEscalationThreshold,\n\t\t\t\tonToolValidationEscalation: usesForegroundModel ? agent.onToolValidationEscalation : undefined,\n\t\t\t\tbeforeToolCall: opts.beforeToolCall,\n\t\t\t\tafterToolCall: opts.afterToolCall,\n\t\t\t\tgetSteeringMessages: opts.getSteeringMessages,\n\t\t\t\tgetFollowUpMessages: opts.getFollowUpMessages,\n\t\t\t\ttransformContext: opts.transformContext,\n\t\t\t\trequestPreflight: opts.requestPreflight,\n\t\t\t\t...(maxTurns === undefined\n\t\t\t\t\t? {}\n\t\t\t\t\t: {\n\t\t\t\t\t\t\tshouldStopAfterTurn: () => {\n\t\t\t\t\t\t\t\tcompletedTurns += 1;\n\t\t\t\t\t\t\t\treturn completedTurns >= maxTurns;\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}),\n\t\t\t\tconvertToLlm: agent.convertToLlm,\n\t\t\t};\n\n\t\t\t// An explicitly supplied surface owns a child tool loop even when it is empty: a model may\n\t\t\t// hallucinate an unavailable tool and must receive the bounded unknown-tool result so it can\n\t\t\t// repair. Only an omitted tools option selects the one-shot completion path.\n\t\t\tif (opts.tools !== undefined) {\n\t\t\t\tconst childContext: AgentContext = {\n\t\t\t\t\tsystemPrompt: opts.systemPrompt,\n\t\t\t\t\tmessages: [...history],\n\t\t\t\t\ttools: [...opts.tools],\n\t\t\t\t};\n\t\t\t\tconst messages = await runAgentLoop(\n\t\t\t\t\topts.messages,\n\t\t\t\t\tchildContext,\n\t\t\t\t\tloopConfig,\n\t\t\t\t\tasync (event) => {\n\t\t\t\t\t\tif (event.type === \"message_end\") await opts.onMessage?.(event.message as Message);\n\t\t\t\t\t},\n\t\t\t\t\topts.signal,\n\t\t\t\t\tagent.streamFn,\n\t\t\t\t);\n\t\t\t\tconst assistantMessages = messages.filter(\n\t\t\t\t\t(message): message is AssistantMessage => message.role === \"assistant\",\n\t\t\t\t);\n\t\t\t\tlet finalAssistant = assistantMessages.at(-1);\n\t\t\t\tif (!finalAssistant) {\n\t\t\t\t\tthrow new Error(\"runIsolatedCompletion: child loop produced no assistant message\");\n\t\t\t\t}\n\n\t\t\t\tconst hasFinalText = finalAssistant.content.some(\n\t\t\t\t\t(content) => content.type === \"text\" && content.text.trim().length > 0,\n\t\t\t\t);\n\t\t\t\tconst endedOnToolCall = finalAssistant.content.some((content) => content.type === \"toolCall\");\n\t\t\t\tif (opts.finalTextPrompt && !hasFinalText && endedOnToolCall && !opts.signal?.aborted) {\n\t\t\t\t\t// A hard turn bound may stop immediately after successful tool execution. Preserve that bound,\n\t\t\t\t\t// then allow exactly one tool-free synthesis call so the gathered work is not thrown away.\n\t\t\t\t\tconst finalizationPrompt: Message = {\n\t\t\t\t\t\trole: \"user\",\n\t\t\t\t\t\tcontent: opts.finalTextPrompt,\n\t\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\t};\n\t\t\t\t\tawait opts.onMessage?.(finalizationPrompt);\n\t\t\t\t\tconst finalizationContext: AgentContext = {\n\t\t\t\t\t\tsystemPrompt: opts.systemPrompt,\n\t\t\t\t\t\tmessages: [...history, ...messages, finalizationPrompt],\n\t\t\t\t\t\ttools: [],\n\t\t\t\t\t};\n\t\t\t\t\tconst finalizationStream = await startAgentProviderRequest(\n\t\t\t\t\t\tfinalizationContext,\n\t\t\t\t\t\tloopConfig,\n\t\t\t\t\t\topts.signal,\n\t\t\t\t\t\tagent.streamFn,\n\t\t\t\t\t);\n\t\t\t\t\tfinalAssistant = await finalizationStream.result();\n\t\t\t\t\tawait opts.onMessage?.(finalAssistant);\n\t\t\t\t\tassistantMessages.push(finalAssistant);\n\t\t\t\t\tmessages.push(finalizationPrompt, finalAssistant);\n\t\t\t\t}\n\n\t\t\t\tconst usage = assistantMessages.reduce<Usage>(\n\t\t\t\t\t(total, message) => ({\n\t\t\t\t\t\tinput: total.input + message.usage.input,\n\t\t\t\t\t\toutput: total.output + message.usage.output,\n\t\t\t\t\t\tcacheRead: total.cacheRead + message.usage.cacheRead,\n\t\t\t\t\t\tcacheWrite: total.cacheWrite + message.usage.cacheWrite,\n\t\t\t\t\t\ttotalTokens: total.totalTokens + message.usage.totalTokens,\n\t\t\t\t\t\tcost: {\n\t\t\t\t\t\t\tinput: total.cost.input + message.usage.cost.input,\n\t\t\t\t\t\t\toutput: total.cost.output + message.usage.cost.output,\n\t\t\t\t\t\t\tcacheRead: total.cost.cacheRead + message.usage.cost.cacheRead,\n\t\t\t\t\t\t\tcacheWrite: total.cost.cacheWrite + message.usage.cost.cacheWrite,\n\t\t\t\t\t\t\ttotal: total.cost.total + message.usage.cost.total,\n\t\t\t\t\t\t},\n\t\t\t\t\t}),\n\t\t\t\t\t{\n\t\t\t\t\t\tinput: 0,\n\t\t\t\t\t\toutput: 0,\n\t\t\t\t\t\tcacheRead: 0,\n\t\t\t\t\t\tcacheWrite: 0,\n\t\t\t\t\t\ttotalTokens: 0,\n\t\t\t\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t\tconst text = finalAssistant.content\n\t\t\t\t\t.filter((content): content is TextContent => content.type === \"text\")\n\t\t\t\t\t.map((content) => content.text)\n\t\t\t\t\t.join(\"\");\n\t\t\t\t// Isolated inputs are Message values and this loop only adds assistant/tool-result messages,\n\t\t\t\t// so the child transcript is safely representable by the public Message[] contract.\n\t\t\t\treturn {\n\t\t\t\t\ttext,\n\t\t\t\t\tusage,\n\t\t\t\t\tstopReason: finalAssistant.stopReason,\n\t\t\t\t\tmessages: [...history, ...(messages as Message[])],\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tfor (const message of opts.messages) await opts.onMessage?.(message);\n\t\t\tconst stream = await startAgentProviderRequest(context, loopConfig, opts.signal, agent.streamFn);\n\t\t\tconst result = await stream.result();\n\t\t\tawait opts.onMessage?.(result);\n\t\t\tconst text = result.content\n\t\t\t\t.filter((c): c is TextContent => c.type === \"text\")\n\t\t\t\t.map((c) => c.text)\n\t\t\t\t.join(\"\");\n\t\t\tconst usage: Usage = result.usage ?? {\n\t\t\t\tinput: 0,\n\t\t\t\toutput: 0,\n\t\t\t\tcacheRead: 0,\n\t\t\t\tcacheWrite: 0,\n\t\t\t\ttotalTokens: 0,\n\t\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t\t};\n\t\t\treturn { text, usage, stopReason: result.stopReason, messages: [...history, ...opts.messages, result] };\n\t\t} finally {\n\t\t\tderegisterInFlight();\n\t\t}\n\t}\n\n\t/**\n\t * Native end-of-loop reflection pass (R2). Demand-gates (zero-I/O), and when warranted runs the\n\t * {@link ReflectionEngine} via an isolated completion ({@link runIsolatedCompletion}), applies the\n\t * resulting memory writes through the bundled `memory` tool, and accounts the reflection's token\n\t * cost via the cost-aggregation surface so it stays visible and net-negative-auditable.\n\t *\n\t * Returns `null` when the gate skips (or in a child session, which must not learn). The whole pass\n\t * is best-effort: a model/parse error yields no writes, never throws into the caller.\n\t */\n\tasync runReflectionPass(input: {\n\t\tsignals: DemandSignals;\n\t\trecentTurnText: string;\n\t\tmodel?: Model<Api>;\n\t\tthinkingLevel?: ThinkingLevel;\n\t\tsignal?: AbortSignal;\n\t\t/** Stable id so a duplicate scheduling/retry of the same pass can't double-count its cost. */\n\t\treportId?: string;\n\t}): Promise<ReflectionResult | null> {\n\t\tif (this.deps.isChildSession() || this.deps.isDisposed()) return null;\n\t\tconst plan = decideDemand(input.signals);\n\t\tif (plan.act === \"skip\") return null;\n\n\t\t// Bug #21: tie this background pass to the session lifetime. Disposing the session aborts the\n\t\t// in-flight completion (input.signal can add a more specific abort).\n\t\tconst signal = input.signal\n\t\t\t? AbortSignal.any([input.signal, this.deps.getReflectionSignal()])\n\t\t\t: this.deps.getReflectionSignal();\n\n\t\tconst complete = (systemPrompt: string, userPrompt: string) =>\n\t\t\tthis.runIsolatedCompletion({\n\t\t\t\tsystemPrompt,\n\t\t\t\tmessages: [{ role: \"user\", content: [{ type: \"text\", text: userPrompt }], timestamp: Date.now() }],\n\t\t\t\tmodel: input.model,\n\t\t\t\tthinkingLevel: input.thinkingLevel ?? \"low\",\n\t\t\t\tmaxTokens: plan.tokenBudget,\n\t\t\t\tsignal,\n\t\t\t\t// The reflection system prompt is static (#33) — let the provider cache the prefix so\n\t\t\t\t// repeated passes only pay for the variable tail.\n\t\t\t\tcacheRetention: \"short\",\n\t\t\t\tlaneKind: \"reflection\",\n\t\t\t});\n\n\t\tconst result = await new ReflectionEngine().reflect({\n\t\t\trecentTurnText: input.recentTurnText,\n\t\t\t// Read memory FRESH (not the prefix-cache-frozen system-prompt block) so confront-before-write\n\t\t\t// sees writes made earlier this session.\n\t\t\texistingMemory: this.deps.getMemoryManager().buildSystemPromptBlockFresh() || \"\",\n\t\t\tplan,\n\t\t\tcomplete,\n\t\t});\n\n\t\t// Bug #21: if the session was disposed while the completion was in flight, do NOT write memory\n\t\t// or skills against the dead session.\n\t\tif (this.deps.isDisposed()) return result;\n\n\t\t// Learning apply policy: every durable write is converted to a proposal, decided by the\n\t\t// learning gate, and audited with a rollback plan. With the policy disabled (default) the\n\t\t// legacy direct-apply behavior is preserved — but now leaves audit records with rollback info.\n\t\tconst policy = this.deps.getSettingsManager().getLearningPolicySettings();\n\t\t// The audit id sequence counts STORED snapshots only: it reseeds from the stored count on\n\t\t// every pass, so advancing it for a no-op (which stores nothing) would make later passes\n\t\t// reuse ids — and rollback keys on the id, so a collision blocks or misdirects rollback.\n\t\tlet auditSequence = getLearningAuditSnapshots(this.deps.getSessionManager().getEntries()).length;\n\t\t// G6 evidence strength: durable proposals accumulate observation counts across passes/sessions\n\t\t// so the gate can distinguish a one-off cue from a repeatedly-confirmed lesson. Built once per\n\t\t// pass; every increment is best-effort (store IO must never break reflection).\n\t\tconst observationStore = ObservationStore.forAgentDir(this.deps.getAgentDir());\n\t\tlet writeIndex = 0;\n\t\tfor (const write of result.writes) {\n\t\t\twriteIndex += 1;\n\t\t\tconst proposalId = `${input.reportId ?? \"reflection\"}-w${writeIndex}`;\n\t\t\tconst proposal = proposalFromReflectionWrite(write, proposalId);\n\t\t\tconst rollback = rollbackPlanForReflectionWrite(write);\n\t\t\tlet observations = 1;\n\t\t\tif (policy.enabled) {\n\t\t\t\ttry {\n\t\t\t\t\tobservations = observationStore.increment(observationKey(proposal.layer, proposal.summary));\n\t\t\t\t} catch {\n\t\t\t\t\t// A store read/write failure falls back to a fresh count of 1, which keeps the gate\n\t\t\t\t\t// proposal-first (never spuriously auto-applies) rather than crashing the pass.\n\t\t\t\t\tobservations = 1;\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst decision: LearningDecision = policy.enabled\n\t\t\t\t? evaluateLearningDecision({\n\t\t\t\t\t\tproposal,\n\t\t\t\t\t\tconfidence: policy.reflectionSourceConfidence,\n\t\t\t\t\t\tobservations,\n\t\t\t\t\t\t// A replace/remove supersedes an existing durable fact — the reflection engine's\n\t\t\t\t\t\t// confront-before-write conflict signal — so it routes through approval instead of\n\t\t\t\t\t\t// silently overwriting prior memory. Additive writes contradict nothing.\n\t\t\t\t\t\tcontradictions: contradictionsForReflectionWrite(write),\n\t\t\t\t\t\tsettings: {\n\t\t\t\t\t\t\tenabled: true,\n\t\t\t\t\t\t\tautoApplyEnabled: policy.autoApplyEnabled,\n\t\t\t\t\t\t\tconfidenceThreshold: policy.confidenceThreshold,\n\t\t\t\t\t\t\tminObservations: policy.minObservations,\n\t\t\t\t\t\t\tallowedAutoApplyLayers: policy.allowedAutoApplyLayers,\n\t\t\t\t\t\t\trequireRollbackPlan: policy.requireRollbackPlan,\n\t\t\t\t\t\t\tautoApplySupersessions: policy.autoApplySupersessions,\n\t\t\t\t\t\t},\n\t\t\t\t\t})\n\t\t\t\t: {\n\t\t\t\t\t\tkind: \"apply\",\n\t\t\t\t\t\treasonCode: \"learning_policy_disabled_legacy_apply\",\n\t\t\t\t\t\tconfidence: 0,\n\t\t\t\t\t\tsummary: proposal.summary,\n\t\t\t\t\t\trequiresApproval: false,\n\t\t\t\t\t};\n\n\t\t\tthis.deps.saveLearningDecisionSnapshot(decision);\n\t\t\t// G3: learning-gate outcome. Codes/numbers only — never the proposal summary/memory text.\n\t\t\tthis.deps.emitAutonomyTelemetry({\n\t\t\t\ttype: AUTONOMY_TELEMETRY_EVENT_TYPES.learningDecision,\n\t\t\t\ttimestamp: new Date().toISOString(),\n\t\t\t\tpayload: {\n\t\t\t\t\tkind: decision.kind,\n\t\t\t\t\treasonCode: decision.reasonCode,\n\t\t\t\t\tlayer: proposal.layer,\n\t\t\t\t\tconfidence: decision.confidence,\n\t\t\t\t\trequiresApproval: decision.requiresApproval,\n\t\t\t\t},\n\t\t\t});\n\t\t\t// G8: a proposal that needs human sign-off is an approval REQUEST. Codes/layer only —\n\t\t\t// never the proposal summary/memory text (those live only in the audit snapshot).\n\t\t\tif (decision.requiresApproval) {\n\t\t\t\tthis.deps.emitAutonomyTelemetry({\n\t\t\t\t\ttype: AUTONOMY_TELEMETRY_EVENT_TYPES.approvalRequest,\n\t\t\t\t\ttimestamp: new Date().toISOString(),\n\t\t\t\t\tpayload: {\n\t\t\t\t\t\tkind: decision.kind,\n\t\t\t\t\t\treasonCode: decision.reasonCode,\n\t\t\t\t\t\tlayer: proposal.layer,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t}\n\t\t\t// An automatic skill promotion the gate would otherwise apply must still clear the same\n\t\t\t// skill_audit overlap check the model-invoked `skillify` tool enforces — otherwise reflection\n\t\t\t// can silently write a near-duplicate SKILL.md. A non-overlapping skill is unaffected\n\t\t\t// (skillPromotionBlock stays undefined) and promotes exactly as before.\n\t\t\tconst skillPromotionBlock =\n\t\t\t\twrite.kind === \"promote_skill\" && decision.kind === \"apply\"\n\t\t\t\t\t? this._checkSkillPromotionOverlap(write)\n\t\t\t\t\t: undefined;\n\n\t\t\t// The gate's decision and the write's actual outcome are two different questions: the memory\n\t\t\t// tool can refuse a write (budget exceeded, drift, threat) via details.success:false without\n\t\t\t// throwing. Capture that outcome instead of assuming \"decision.kind === apply\" means it landed\n\t\t\t// — otherwise a refused write leaves a phantom \"apply\" audit whose rollback later fails\n\t\t\t// not-found (or, worse, misfires against whatever now occupies that text).\n\t\t\tconst applied =\n\t\t\t\tdecision.kind === \"apply\" && !skillPromotionBlock ? await this._applyReflectionWrite(write, signal) : false;\n\t\t\tconst writeFailed = decision.kind === \"apply\" && !skillPromotionBlock && !applied;\n\t\t\tif (decision.kind !== \"no-op\") {\n\t\t\t\tauditSequence += 1;\n\t\t\t\tappendLearningAuditSnapshot(this.deps.getSessionManager(), {\n\t\t\t\t\tid: `audit-${auditSequence}`,\n\t\t\t\t\tproposalId,\n\t\t\t\t\tlayer: proposal.layer,\n\t\t\t\t\taction: skillPromotionBlock\n\t\t\t\t\t\t? \"propose\"\n\t\t\t\t\t\t: writeFailed\n\t\t\t\t\t\t\t? \"apply_failed\"\n\t\t\t\t\t\t\t: decision.kind === \"apply\"\n\t\t\t\t\t\t\t\t? \"apply\"\n\t\t\t\t\t\t\t\t: \"propose\",\n\t\t\t\t\tsummary: skillPromotionBlock ? `${proposal.summary} — ${skillPromotionBlock.note}` : proposal.summary,\n\t\t\t\t\treasonCode: skillPromotionBlock\n\t\t\t\t\t\t? skillPromotionBlock.reasonCode\n\t\t\t\t\t\t: writeFailed\n\t\t\t\t\t\t\t? APPLY_WRITE_REFUSED_REASON_CODE\n\t\t\t\t\t\t\t: decision.reasonCode,\n\t\t\t\t\tdecision,\n\t\t\t\t\t// No rollback plan on a failed apply or a held/proposed promotion — nothing durable\n\t\t\t\t\t// landed in either case, so there is nothing to undo.\n\t\t\t\t\trollback: skillPromotionBlock || writeFailed ? undefined : rollback,\n\t\t\t\t\tcreatedAt: new Date().toISOString(),\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\t// Account the reflection's spend so it surfaces in the footer roll-up (net-token visibility).\n\t\t// Idempotent on reportId so a retried/duplicated pass cannot double-count.\n\t\tif (result.usage.cost.total > 0 || result.usage.totalTokens > 0) {\n\t\t\tthis.deps.addSpawnedUsage(result.usage, { label: \"reflection\", reportId: input.reportId });\n\t\t}\n\t\treturn result;\n\t}\n\n\tgetLearningAuditRecords(): LearningAuditRecord[] {\n\t\treturn getLearningAuditSnapshots(this.deps.getSessionManager().getEntries());\n\t}\n\n\t/**\n\t * Roll back one applied durable learning change by executing the inverse operation recorded in\n\t * its audit record (memory ops run through the same bundled memory-tool path as the original\n\t * apply; promoted skills are archived). Appends a linked \"rollback\" audit record on success so\n\t * the change history stays complete and a change cannot be rolled back twice.\n\t */\n\tasync rollbackLearningWrite(auditId: string): Promise<{ ok: boolean; reason: string }> {\n\t\tif (this.deps.isDisposed()) return { ok: false, reason: \"session_disposed\" };\n\n\t\tconst audits = this.getLearningAuditRecords();\n\t\tconst audit = audits.find((record) => record.id === auditId);\n\t\tif (!audit) return { ok: false, reason: \"audit_not_found\" };\n\t\tif (audit.action !== \"apply\") return { ok: false, reason: \"not_an_applied_change\" };\n\t\tif (audits.some((record) => record.action === \"rollback\" && record.rollbackOf === auditId)) {\n\t\t\treturn { ok: false, reason: \"already_rolled_back\" };\n\t\t}\n\t\tconst rollback = audit.rollback;\n\t\tif (!rollback) return { ok: false, reason: \"no_rollback_plan\" };\n\n\t\t// Every inverse must be VERIFIED-applied before the rollback audit is appended: a silently\n\t\t// failed inverse that still recorded \"rollback\" would permanently self-lock the change\n\t\t// behind already_rolled_back while the durable write is in fact still live.\n\t\tswitch (rollback.kind) {\n\t\t\tcase \"memory_remove\": {\n\t\t\t\tif (!rollback.target) return { ok: false, reason: \"missing_rollback_target\" };\n\t\t\t\tif (!(await this._applyReflectionWrite({ kind: \"memory_remove\", target: rollback.target }))) {\n\t\t\t\t\treturn { ok: false, reason: \"rollback_apply_failed\" };\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"memory_restore\": {\n\t\t\t\tif (!rollback.target || rollback.previous === undefined) {\n\t\t\t\t\treturn { ok: false, reason: \"missing_rollback_target\" };\n\t\t\t\t}\n\t\t\t\tconst applied = await this._applyReflectionWrite({\n\t\t\t\t\tkind: \"memory_replace\",\n\t\t\t\t\ttarget: rollback.target,\n\t\t\t\t\ttext: rollback.previous,\n\t\t\t\t});\n\t\t\t\tif (!applied) return { ok: false, reason: \"rollback_apply_failed\" };\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"memory_add\": {\n\t\t\t\tif (rollback.previous === undefined) return { ok: false, reason: \"missing_rollback_target\" };\n\t\t\t\tconst applied = await this._applyReflectionWrite({\n\t\t\t\t\tkind: \"memory_add\",\n\t\t\t\t\tsection: \"MEMORY\",\n\t\t\t\t\ttext: rollback.previous,\n\t\t\t\t});\n\t\t\t\tif (!applied) return { ok: false, reason: \"rollback_apply_failed\" };\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"archive_skill\": {\n\t\t\t\tif (!rollback.target) return { ok: false, reason: \"missing_rollback_target\" };\n\t\t\t\tif (!this.deps.archivePromotedSkill(rollback.target)) {\n\t\t\t\t\treturn { ok: false, reason: \"skill_archive_failed\" };\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tappendLearningAuditSnapshot(this.deps.getSessionManager(), {\n\t\t\tid: `${audit.id}-rollback`,\n\t\t\tproposalId: audit.proposalId,\n\t\t\tlayer: audit.layer,\n\t\t\taction: \"rollback\",\n\t\t\tsummary: `Rolled back: ${audit.summary}`,\n\t\t\treasonCode: \"user_requested_rollback\",\n\t\t\tdecision: audit.decision,\n\t\t\trollbackOf: audit.id,\n\t\t\tcreatedAt: new Date().toISOString(),\n\t\t});\n\t\treturn { ok: true, reason: \"rollback_applied\" };\n\t}\n\n\t/**\n\t * Apply one reflection write through the bundled `memory` tool. `memory_replace`/`memory_remove`\n\t * don't carry a target file, so we try MEMORY.md first and fall back to USER.md when the substring\n\t * isn't found there. Never throws (reflection must never break a turn); returns whether the write\n\t * actually applied so callers that MUST know — rollback's once-only accounting — can react instead\n\t * of recording a success that never happened.\n\t */\n\tprivate async _applyReflectionWrite(write: ReflectionWrite, signal?: AbortSignal): Promise<boolean> {\n\t\t// R7 memory-to-behavior: a recurring procedure is compiled into an executable skill file rather\n\t\t// than stored as a flat fact. Written under the agent skills dir so it loads like any user skill.\n\t\tif (write.kind === \"promote_skill\") {\n\t\t\treturn this._promoteReflectionSkill(write.name, write.description, write.body);\n\t\t}\n\n\t\ttype MemResult = { details?: { success?: boolean; error?: string } };\n\t\ttype MemExec = (\n\t\t\ttoolCallId: string,\n\t\t\tparams: { action: string; target: string; content?: string; oldContent?: string },\n\t\t\tsignal: AbortSignal | undefined,\n\t\t\tonUpdate: undefined,\n\t\t\tctx: undefined,\n\t\t) => Promise<MemResult>;\n\t\tconst memTool = this.deps\n\t\t\t.getMemoryManager()\n\t\t\t.getToolDefinitions()\n\t\t\t.find((t) => t.name === \"memory\");\n\t\tconst exec = memTool?.execute as unknown as MemExec | undefined;\n\t\tif (!exec) return false;\n\n\t\tconst run = (params: Parameters<MemExec>[1]) => exec(\"reflection\", params, signal, undefined, undefined);\n\n\t\tif (write.kind === \"memory_add\") {\n\t\t\ttry {\n\t\t\t\tconst res = await run({\n\t\t\t\t\taction: \"add\",\n\t\t\t\t\ttarget: write.section === \"USER\" ? \"user\" : \"memory\",\n\t\t\t\t\tcontent: write.text,\n\t\t\t\t});\n\t\t\t\treturn res?.details?.success === true;\n\t\t\t} catch {\n\t\t\t\t// best-effort; reflection writes must never throw into the turn loop\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\t// replace / remove carry no target file — try MEMORY.md, then USER.md. The memory tool reports\n\t\t// outcomes via `details.success` (it catches its own errors rather than throwing). Only a\n\t\t// genuine \"not found in the file\" justifies trying the other file; a real failure for a file\n\t\t// (budget exceeded / drift) must NOT fall through and mutate the wrong target.\n\t\tfor (const target of [\"memory\", \"user\"] as const) {\n\t\t\ttry {\n\t\t\t\tconst params =\n\t\t\t\t\twrite.kind === \"memory_replace\"\n\t\t\t\t\t\t? { action: \"replace\", target, oldContent: write.target, content: write.text }\n\t\t\t\t\t\t: { action: \"remove\", target, oldContent: write.target };\n\t\t\t\tconst res = await run(params);\n\t\t\t\tif (res?.details?.success === true) return true; // applied\n\t\t\t\tif (!/not found/i.test(String(res?.details?.error ?? \"\"))) return false; // real failure — don't misapply\n\t\t\t\t// substring simply absent from this file — try the next target\n\t\t\t} catch {\n\t\t\t\t// defensive: if the tool ever does throw, try the next target\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\t/**\n\t * The same skill_audit overlap check the model-invoked `skillify` tool enforces\n\t * (tools/skillify.ts → tools/skill-audit.ts's `runSkillAudit`), run before an AUTOMATIC promotion\n\t * so the reflection engine can never silently write a near-duplicate SKILL.md. Reuses the audit\n\t * seam unchanged (never duplicated) against the same already-loaded skills universe skillify\n\t * compares a draft against. Returns a block reason when the draft overlaps an existing skill above\n\t * the audit's own similarity threshold, or when the audit itself fails (the promotion is held, not\n\t * written unaudited); undefined when clear to promote. Never throws — mirrors every other\n\t * best-effort check in this file.\n\t */\n\tprivate _checkSkillPromotionOverlap(write: {\n\t\tname: string;\n\t\tdescription: string;\n\t\tbody: string;\n\t}): { reasonCode: string; note: string } | undefined {\n\t\ttry {\n\t\t\tconst cwd = this.deps.getCwd?.() ?? process.cwd();\n\t\t\tconst audit = runSkillAudit(cwd, write);\n\t\t\tconst overlap = audit.nearDuplicates.find((d) => d.a === \"[draft]\" || d.b === \"[draft]\");\n\t\t\tif (!overlap) return undefined;\n\t\t\tconst otherPath = overlap.a === \"[draft]\" ? overlap.b : overlap.a;\n\t\t\t// Every skill file is named \"SKILL.md\" — unlike skillify's own display formatter (which takes\n\t\t\t// the path's last segment and always shows that literal filename), look up the declared\n\t\t\t// frontmatter name so the proposal actually names the skill it overlaps with.\n\t\t\tconst otherName = audit.skills.find((s) => s.path === otherPath)?.name ?? otherPath;\n\t\t\treturn {\n\t\t\t\treasonCode: SKILL_OVERLAP_CONSOLIDATION_REASON_CODE,\n\t\t\t\tnote: `overlaps existing skill \"${otherName}\" (${(overlap.similarity * 100).toFixed(0)}% similar) — consolidation proposed instead of a duplicate write`,\n\t\t\t};\n\t\t} catch {\n\t\t\t// Bounded, observable degradation via the promote path's existing error-reporting shape: an\n\t\t\t// audit failure must never throw into the reflection pass, but it also must not silently\n\t\t\t// fall through to an unaudited write — hold the promotion and record why.\n\t\t\treturn {\n\t\t\t\treasonCode: SKILL_AUDIT_UNAVAILABLE_REASON_CODE,\n\t\t\t\tnote: \"skill overlap audit failed; promotion held rather than written unaudited\",\n\t\t\t};\n\t\t}\n\t}\n\n\t/**\n\t * R7: write a reflection-promoted skill as `<agentDir>/skills/<name>/SKILL.md` so it loads like any\n\t * user skill. Best-effort; never clobbers an existing (hand-authored) skill of the same name. The\n\t * overlap audit runs at the call site in {@link runReflectionPass} — a write only reaches here\n\t * once the draft has already cleared it.\n\t */\n\tprivate _promoteReflectionSkill(rawName: string, description: string, body: string): boolean {\n\t\tconst name = rawName\n\t\t\t.trim()\n\t\t\t.toLowerCase()\n\t\t\t.replace(/[^a-z0-9-]+/g, \"-\")\n\t\t\t.replace(/^-+|-+$/g, \"\")\n\t\t\t.slice(0, 64);\n\t\tif (!name || !body.trim()) return false;\n\t\ttry {\n\t\t\tconst dir = join(this.deps.getAgentDir(), \"skills\", name);\n\t\t\tconst file = join(dir, \"SKILL.md\");\n\t\t\tif (existsSync(file)) return false; // do not overwrite an existing skill\n\t\t\tmkdirSync(dir, { recursive: true });\n\t\t\tconst safeDescription = description.replace(/[\\r\\n]+/g, \" \").trim();\n\t\t\t// `promoted: true` marks this as reflection-generated so the curator (#32) can lifecycle-manage\n\t\t\t// it (archive/consolidate) WITHOUT ever touching hand-authored user skills.\n\t\t\tconst content = `---\\nname: ${name}\\ndescription: ${safeDescription}\\npromoted: true\\n---\\n\\n<!-- Auto-generated by the reflection engine (R7 memory-to-behavior). Review and refine. -->\\n\\n${body.trim()}\\n`;\n\t\t\twriteFileSync(file, content, \"utf-8\");\n\t\t\treturn true;\n\t\t} catch {\n\t\t\t// promotion must never break a turn\n\t\t\treturn false;\n\t\t}\n\t}\n}\n"]}
1
+ {"version":3,"file":"reflection-controller.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AW,EAAE,EAAE,QAAQ,EAAE,IAAI,CAAC,CAAC;YAC1D,MAAM,IAAI,GAAG,IAAI,CAAC,GAAG,EAAE,UAAU,CAAC,CAAC;YACnC,IAAI,UAAU,CAAC,IAAI,CAAC;gBAAE,OAAO,KAAK,CAAC,CAAC,qCAAqC;YACzE,SAAS,CAAC,GAAG,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;YACpC,MAAM,eAAe,GAAG,WAAW,CAAC,OAAO,CAAC,UAAU,EAAE,GAAG,CAAC,CAAC,IAAI,EAAE,CAAC;YACpE,gGAAgG;YAChG,4EAA4E;YAC5E,MAAM,OAAO,GAAG,cAAc,IAAI,kBAAkB,eAAe,4HAA4H,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC;YAC/M,aAAa,CAAC,IAAI,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;YACtC,OAAO,IAAI,CAAC;QACb,CAAC;QAAC,MAAM,CAAC;YACR,oCAAoC;YACpC,OAAO,KAAK,CAAC;QACd,CAAC;IACF,CAAC;CACD","sourcesContent":["/**\n * Native reflection + learning-write controller.\n *\n * Extracted verbatim from agent-session.ts (god-file decomposition). Owns the end-of-loop reflection\n * pass (R2), the isolated-completion primitive it runs on, and the learning-apply/rollback path that\n * turns reflection writes into gated, audited durable memory/skill changes. It mutates NO session\n * fields — every durable effect goes through the bundled memory tool, the session log (via deps), or\n * the skills dir; the whole pass is best-effort and never throws into the turn loop. Reads live\n * session state (model/agent/registry/memory/settings) through narrow deps accessors rather than the\n * whole AgentSession.\n */\n\nimport { createHash } from \"node:crypto\";\nimport { existsSync, mkdirSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport {\n\ttype Agent,\n\ttype AgentContext,\n\ttype AgentLoopConfig,\n\ttype AgentMessage,\n\trunAgentLoop,\n\tstartAgentProviderRequest,\n\ttype ThinkingLevel,\n} from \"@caupulican/pi-agent-core\";\nimport type { SessionManager } from \"@caupulican/pi-agent-core/node\";\nimport {\n\ttype Api,\n\ttype AssistantMessage,\n\ttype Message,\n\ttype Model,\n\tresolveModelThinkingLevel,\n\ttype SimpleStreamOptions,\n\ttype TextContent,\n\ttype Usage,\n} from \"@caupulican/pi-ai\";\nimport {\n\tcomputeLaneAffinityKey,\n\tDEFAULT_ISOLATED_LANE_KIND,\n\ttype IsolatedCompletionOptions,\n\ttype IsolatedCompletionResult,\n} from \"./agent-session-contracts.ts\";\nimport type { LearningDecision } from \"./autonomy/contracts.ts\";\nimport { AUTONOMY_TELEMETRY_EVENT_TYPES, type AutonomyTelemetryEvent } from \"./autonomy/telemetry-events.ts\";\nimport {\n\tAPPLY_WRITE_REFUSED_REASON_CODE,\n\tappendLearningAuditSnapshot,\n\tcontradictionsForReflectionWrite,\n\tgetLearningAuditSnapshots,\n\ttype LearningAuditRecord,\n\tproposalFromReflectionWrite,\n\trollbackPlanForReflectionWrite,\n} from \"./learning/learning-audit.ts\";\nimport { evaluateLearningDecision } from \"./learning/learning-gate.ts\";\nimport { ObservationStore, observationKey } from \"./learning/observation-store.ts\";\nimport {\n\ttype DemandSignals,\n\tdecideDemand,\n\tReflectionEngine,\n\ttype ReflectionResult,\n\ttype ReflectionWrite,\n} from \"./learning/reflection-engine.ts\";\nimport {\n\tanalyzeReflectionTurn,\n\tboundReflectionSemanticText,\n\ttype ReflectionTurnAnalysis,\n\treflectionTriggerPriority,\n} from \"./learning/reflection-turn-analysis.ts\";\nimport type { MemoryManager } from \"./memory/memory-manager.ts\";\nimport type { ModelRegistry } from \"./model-registry.ts\";\nimport { resolveCliModel } from \"./model-resolver.ts\";\nimport { registerInFlightWork } from \"./reload-blockers.ts\";\nimport type { SettingsManager } from \"./settings-manager.ts\";\nimport { runSkillAudit } from \"./tools/skill-audit.ts\";\n\nexport interface ReflectionControllerDeps {\n\t/** Current session model (fallback for an isolated call that omits its own model). */\n\tgetModel(): Model<Api> | undefined;\n\t/** The underlying agent — its `streamFn` runs the isolated completion. */\n\tgetAgent(): Agent;\n\t/** True when the session's stream fn is the raw `streamSimple` provider (auth must be injected). */\n\tisRawStreamSimple(): boolean;\n\t/** Model registry for API-key/header resolution on the raw-provider path. */\n\tgetModelRegistry(): ModelRegistry;\n\t/** Memory subsystem — the bundled `memory` tool applies durable writes; fresh block feeds reflection. */\n\tgetMemoryManager(): MemoryManager;\n\t/** Settings — the learning-apply policy (gate thresholds, auto-apply layers) is read here. */\n\tgetSettingsManager(): SettingsManager;\n\t/** Session log — audit snapshots and learning-audit reads go through this. */\n\tgetSessionManager(): SessionManager;\n\t/** Agent dir — reflection-promoted skills are written under `<agentDir>/skills/`. */\n\tgetAgentDir(): string;\n\t/** Child sessions must not learn — the pass returns null for them. */\n\tisChildSession(): boolean;\n\t/** Disposal short-circuits: no completion, no writes against a dead session. */\n\tisDisposed(): boolean;\n\t/** Session-lifetime abort signal — aborts an in-flight reflection completion on dispose. */\n\tgetReflectionSignal(): AbortSignal;\n\t/** Archive a promoted skill (rollback of a `promote_skill` write). */\n\tarchivePromotedSkill(name: string): boolean;\n\t/** G3/G8 autonomy telemetry sink for learning-gate outcomes and approval requests. */\n\temitAutonomyTelemetry(event: AutonomyTelemetryEvent): void;\n\t/** Account the reflection pass's token spend into the cost roll-up (idempotent on reportId). */\n\taddSpawnedUsage(\n\t\tusage: Usage,\n\t\topts?: { label?: string; sourceSessionId?: string; reportId?: string },\n\t): string | undefined;\n\t/** Persist a learning-gate decision snapshot to the session log. */\n\tsaveLearningDecisionSnapshot(decision: LearningDecision): string;\n\t/** Resolve text-tool fallback for the selected isolated model, not the foreground model. */\n\tresolveTextToolCallProtocol(model: Model<Api>): SimpleStreamOptions[\"textToolCallProtocol\"];\n\t/** Ensure a managed-local model is running/resident before any isolated lane calls it. */\n\tensureModelReady(model: Model<Api>): Promise<void>;\n\t/**\n\t * Session working directory — feeds the skill-overlap audit's project-local skill discovery, the\n\t * same `cwd` the model-invoked `skillify`/`skill_audit` tools already receive (tools/index.ts).\n\t * Optional so a host that has not wired it yet still resolves (falls back to `process.cwd()`,\n\t * mirroring the existing profile-resolution fallback in settings-manager.ts).\n\t */\n\tgetCwd?(): string;\n}\n\n// reasonCode when an automatic skill promotion is blocked by an overlap with an existing skill\n// (skill_audit's similarity threshold) and routed to a consolidation proposal instead of a blind write.\nexport const SKILL_OVERLAP_CONSOLIDATION_REASON_CODE = \"skill_overlap_consolidation_proposed\";\n// reasonCode when the overlap audit itself fails — the promotion is held (not written unaudited)\n// rather than silently skipping the check.\nexport const SKILL_AUDIT_UNAVAILABLE_REASON_CODE = \"skill_audit_unavailable\";\n\nconst REFLECTION_MIN_INTERVAL_MS = 45_000;\nconst REFLECTION_PENDING_MAX_CHARS = 12_000;\nconst REFLECTION_DIGEST_HISTORY_SIZE = 64;\n\nexport class ReflectionController {\n\tprivate readonly deps: ReflectionControllerDeps;\n\tprivate readonly pendingTurns: Array<{ analysis: ReflectionTurnAnalysis; contextHeadroomPct: number }> = [];\n\tprivate readonly scheduledDigests = new Set<string>();\n\tprivate activeScheduledPass: Promise<void> | undefined;\n\tprivate scheduledTimer: NodeJS.Timeout | undefined;\n\tprivate lastScheduledPassAt = 0;\n\n\tconstructor(deps: ReflectionControllerDeps) {\n\t\tthis.deps = deps;\n\t}\n\n\t/** Analyze once, schedule bounded background reflection when warranted, and return filtered turn text for sync hooks. */\n\tscheduleFromTurn(messages: AgentMessage[], contextHeadroomPct: number): ReflectionTurnAnalysis {\n\t\tconst settings = this.deps.getSettingsManager().getAutoLearnSettings();\n\t\tconst analysis = analyzeReflectionTurn(messages, settings.complexTaskToolCalls ?? 12);\n\t\tconst enabled =\n\t\t\tsettings.enabled !== false &&\n\t\t\tsettings.reflectionReview !== false &&\n\t\t\tprocess.env.PI_NATIVE_REFLECTION !== \"0\" &&\n\t\t\tprocess.env.PI_AUTO_LEARN_CHILD !== \"1\" &&\n\t\t\t!this.deps.isChildSession() &&\n\t\t\t!this.deps.isDisposed();\n\t\tif (!enabled || analysis.trigger === \"none\" || this.scheduledDigests.has(analysis.digest)) return analysis;\n\n\t\tthis.scheduledDigests.add(analysis.digest);\n\t\twhile (this.scheduledDigests.size > REFLECTION_DIGEST_HISTORY_SIZE) {\n\t\t\tconst oldest = this.scheduledDigests.values().next().value;\n\t\t\tif (typeof oldest !== \"string\") break;\n\t\t\tthis.scheduledDigests.delete(oldest);\n\t\t}\n\t\tthis.pendingTurns.push({ analysis, contextHeadroomPct });\n\t\tlet pendingChars = this.pendingTurns.reduce((total, turn) => total + turn.analysis.recentTurnText.length, 0);\n\t\twhile (this.pendingTurns.length > 1 && pendingChars > REFLECTION_PENDING_MAX_CHARS) {\n\t\t\tpendingChars -= this.pendingTurns.shift()?.analysis.recentTurnText.length ?? 0;\n\t\t}\n\t\tthis.schedulePendingPass();\n\t\treturn analysis;\n\t}\n\n\tprivate schedulePendingPass(): void {\n\t\tif (this.activeScheduledPass || this.scheduledTimer || this.pendingTurns.length === 0 || this.deps.isDisposed()) {\n\t\t\treturn;\n\t\t}\n\t\tconst delay = Math.max(0, REFLECTION_MIN_INTERVAL_MS - (Date.now() - this.lastScheduledPassAt));\n\t\tif (delay > 0) {\n\t\t\tthis.scheduledTimer = setTimeout(() => {\n\t\t\t\tthis.scheduledTimer = undefined;\n\t\t\t\tthis.startPendingPass();\n\t\t\t}, delay);\n\t\t\tthis.scheduledTimer.unref?.();\n\t\t\treturn;\n\t\t}\n\t\tthis.startPendingPass();\n\t}\n\n\tprivate startPendingPass(): void {\n\t\tif (this.activeScheduledPass || this.pendingTurns.length === 0 || this.deps.isDisposed()) return;\n\t\tconst turns = this.pendingTurns.splice(0);\n\t\tconst trigger = turns.reduce<DemandSignals[\"trigger\"]>(\n\t\t\t(selected, turn) =>\n\t\t\t\treflectionTriggerPriority(turn.analysis.trigger) > reflectionTriggerPriority(selected)\n\t\t\t\t\t? turn.analysis.trigger\n\t\t\t\t\t: selected,\n\t\t\t\"none\",\n\t\t);\n\t\tconst recentTurnText = boundReflectionSemanticText(\n\t\t\tturns.map((turn) => turn.analysis.recentTurnText).join(\"\\n---\\n\"),\n\t\t\tREFLECTION_PENDING_MAX_CHARS,\n\t\t);\n\t\tconst reportDigest = createHash(\"sha256\")\n\t\t\t.update(turns.map((turn) => turn.analysis.digest).join(\"\\0\"))\n\t\t\t.digest(\"hex\")\n\t\t\t.slice(0, 24);\n\t\tconst settings = this.deps.getSettingsManager().getAutoLearnSettings();\n\t\tlet model: Model<Api> | undefined;\n\t\tif (settings.model && settings.model !== \"active\") {\n\t\t\tconst resolved = resolveCliModel({ cliModel: settings.model, modelRegistry: this.deps.getModelRegistry() });\n\t\t\tif (resolved.model && this.deps.getModelRegistry().hasConfiguredAuth(resolved.model)) model = resolved.model;\n\t\t}\n\t\tconst toolCallCount = turns.reduce((total, turn) => total + turn.analysis.toolCallCount, 0);\n\t\tconst contextHeadroomPct = Math.min(...turns.map((turn) => turn.contextHeadroomPct));\n\t\tthis.lastScheduledPassAt = Date.now();\n\t\tthis.activeScheduledPass = (async () => {\n\t\t\ttry {\n\t\t\t\tawait this.runReflectionPass({\n\t\t\t\t\tsignals: {\n\t\t\t\t\t\ttrigger,\n\t\t\t\t\t\ttoolCallCount,\n\t\t\t\t\t\thadCorrection: turns.some((turn) => turn.analysis.hadCorrection),\n\t\t\t\t\t\tcontextHeadroomPct,\n\t\t\t\t\t\tusefulLately: 0,\n\t\t\t\t\t},\n\t\t\t\t\trecentTurnText,\n\t\t\t\t\treportId: `reflection:${reportDigest}`,\n\t\t\t\t\tmodel,\n\t\t\t\t\tthinkingLevel: settings.thinkingLevel ?? \"low\",\n\t\t\t\t\texplicitUserMemoryInstruction: turns.every((turn) => turn.analysis.explicitUserMemoryInstruction),\n\t\t\t\t});\n\t\t\t} catch {\n\t\t\t\t// Best-effort background learning must never disrupt the foreground turn.\n\t\t\t} finally {\n\t\t\t\tthis.activeScheduledPass = undefined;\n\t\t\t\tthis.schedulePendingPass();\n\t\t\t}\n\t\t})();\n\t}\n\n\tcancelScheduled(): void {\n\t\tif (this.scheduledTimer) clearTimeout(this.scheduledTimer);\n\t\tthis.scheduledTimer = undefined;\n\t\tthis.pendingTurns.length = 0;\n\t}\n\n\tasync waitForActivePass(): Promise<void> {\n\t\twhile (this.activeScheduledPass) await this.activeScheduledPass;\n\t}\n\n\t/**\n\t * Run an LLM completion fully ISOLATED from the main session — the load-bearing primitive for\n\t * reflection and bounded child lanes (adaptive-agent design §6c/§7).\n\t *\n\t * Isolation invariants (audited by codex): builds fresh context (no main history), defaults to no\n\t * tools, and passes **no real `sessionId`** — only a deterministic SYNTHETIC cache-affinity key\n\t * (see {@link computeLaneAffinityKey}) derived from `(laneKind, model, systemPrompt)`, which can never\n\t * equal or embed the real session id. A tool-enabled call receives only caller-owned tools and hooks,\n\t * and applies a turn bound only when its owner explicitly supplies one. It cannot mutate `agent.state.messages`, append session entries, or touch the\n\t * foreground tool registry. Mirrors `generateSummary()`'s one-shot mechanics otherwise.\n\t *\n\t * Returns the result even on an error/aborted stop reason (callers — e.g. a background reflection\n\t * microtask — decide whether to act); it does not throw on a model-level error.\n\t */\n\tasync runIsolatedCompletion(opts: IsolatedCompletionOptions): Promise<IsolatedCompletionResult> {\n\t\tif (opts.maxTurns !== undefined && (!Number.isSafeInteger(opts.maxTurns) || opts.maxTurns <= 0)) {\n\t\t\tthrow new Error(\"runIsolatedCompletion: maxTurns must be a positive safe integer when provided\");\n\t\t}\n\t\tconst model = opts.model ?? this.deps.getModel();\n\t\tif (!model) {\n\t\t\tthrow new Error(\"runIsolatedCompletion: no model available\");\n\t\t}\n\t\tawait this.deps.ensureModelReady(model);\n\t\tconst thinkingLevel = resolveModelThinkingLevel(model, opts.thinkingLevel, \"off\");\n\n\t\t// Registered for the full isolated-completion call (one-shot or child-loop) so the\n\t\t// reload gate waits it out — this is the SINGLE choke point every isolated completion in the\n\t\t// codebase runs through (reflection, research/worker/fitness lanes, context-pipeline curation,\n\t\t// model-router judge calls). registerInFlightWork is a pure sync map op (cannot throw), so\n\t\t// placing it as the last statement before `try` still guarantees the matching finally always\n\t\t// runs, on every return path below and on any thrown error.\n\t\tconst deregisterInFlight = registerInFlightWork(\n\t\t\tthis.deps.getAgentDir(),\n\t\t\t\"isolated-completion\",\n\t\t\topts.laneKind ?? DEFAULT_ISOLATED_LANE_KIND,\n\t\t);\n\t\ttry {\n\t\t\t// Fresh, isolated context: explicit messages, caller-owned tools only, nothing from the main session.\n\t\t\tconst history = opts.history ?? [];\n\t\t\tconst context: AgentContext = {\n\t\t\t\tsystemPrompt: opts.systemPrompt,\n\t\t\t\tmessages: [...history, ...opts.messages],\n\t\t\t\ttools: opts.tools ?? [],\n\t\t\t};\n\n\t\t\t// Isolate the prompt cache from the main session by DELIBERATELY never sending the real\n\t\t\t// sessionId. In its place, a deterministic SYNTHETIC affinity key lets providers with\n\t\t\t// session-affinity headers / prompt_cache_key route repeat calls from the SAME lane (same\n\t\t\t// laneKind+model+systemPrompt) to the same cache-warm backend, without entangling this call\n\t\t\t// with — or leaking any identity of — the main session.\n\t\t\tconst affinityKey = computeLaneAffinityKey(\n\t\t\t\topts.laneKind ?? DEFAULT_ISOLATED_LANE_KIND,\n\t\t\t\tmodel,\n\t\t\t\topts.systemPrompt,\n\t\t\t);\n\t\t\tconst options: SimpleStreamOptions = {\n\t\t\t\tmaxTokens: opts.maxTokens,\n\t\t\t\tsignal: opts.signal,\n\t\t\t\tinteractionMode: \"background\",\n\t\t\t\tcacheRetention: opts.cacheRetention,\n\t\t\t\treasoning: thinkingLevel,\n\t\t\t\tsessionId: affinityKey,\n\t\t\t};\n\n\t\t\t// When streamFn is the raw streamSimple (e.g. in tests), auth must be injected explicitly.\n\t\t\t// Throw only when auth genuinely fails — providers that authenticate without an API key\n\t\t\t// (OAuth, local no-key) legitimately return ok with an undefined apiKey.\n\t\t\tif (this.deps.isRawStreamSimple()) {\n\t\t\t\tconst auth = await this.deps.getModelRegistry().getApiKeyAndHeaders(model);\n\t\t\t\tif (!auth.ok) {\n\t\t\t\t\tthrow new Error(auth.error);\n\t\t\t\t}\n\t\t\t\toptions.apiKey = auth.apiKey;\n\t\t\t\toptions.headers = auth.headers;\n\t\t\t}\n\t\t\tconst agent = this.deps.getAgent();\n\t\t\tconst foregroundModel = agent.state.model;\n\t\t\tconst usesForegroundModel = foregroundModel?.provider === model.provider && foregroundModel.id === model.id;\n\t\t\tconst textToolCallProtocol = this.deps.resolveTextToolCallProtocol(model);\n\t\t\tconst maxTurns = opts.maxTurns;\n\t\t\tlet completedTurns = 0;\n\t\t\tconst loopConfig: AgentLoopConfig = {\n\t\t\t\tmodel,\n\t\t\t\tinteractionMode: \"background\",\n\t\t\t\tmaxTokens: opts.maxTokens,\n\t\t\t\tcacheRetention: opts.cacheRetention,\n\t\t\t\treasoning: thinkingLevel,\n\t\t\t\t// Same synthetic per-lane affinity key as the one-shot path above — never the real sessionId.\n\t\t\t\tsessionId: affinityKey,\n\t\t\t\t...(options.apiKey !== undefined ? { apiKey: options.apiKey } : {}),\n\t\t\t\t...(options.headers !== undefined ? { headers: options.headers } : {}),\n\t\t\t\tgetApiKey: agent.getApiKey,\n\t\t\t\tresolveRequestReasoning: agent.resolveRequestReasoning,\n\t\t\t\ttemperature: textToolCallProtocol ? 0 : undefined,\n\t\t\t\ttextToolCallProtocol,\n\t\t\t\tonTextToolProtocolParse: usesForegroundModel ? agent.onTextToolProtocolParse : undefined,\n\t\t\t\ttransport: agent.transport,\n\t\t\t\tthinkingBudgets: agent.thinkingBudgets,\n\t\t\t\tmaxRetryDelayMs: agent.maxRetryDelayMs,\n\t\t\t\t// This remains independent from an owner-provided turn budget: it stops only repeated\n\t\t\t\t// identical tool calls, so legitimate long-running work can continue until completion.\n\t\t\t\tmaxStallTurns: agent.maxStallTurns,\n\t\t\t\tonRunawayStop: usesForegroundModel ? agent.onRunawayStop : undefined,\n\t\t\t\ttoolExecution: \"sequential\",\n\t\t\t\ttoolArgumentTeachEnabled: agent.toolArgumentTeachEnabled,\n\t\t\t\tonToolArgumentValidation: usesForegroundModel ? agent.onToolArgumentValidation : undefined,\n\t\t\t\ttoolValidationEscalationThreshold: agent.toolValidationEscalationThreshold,\n\t\t\t\tonToolValidationEscalation: usesForegroundModel ? agent.onToolValidationEscalation : undefined,\n\t\t\t\tbeforeToolCall: opts.beforeToolCall,\n\t\t\t\tafterToolCall: opts.afterToolCall,\n\t\t\t\tgetSteeringMessages: opts.getSteeringMessages,\n\t\t\t\tgetFollowUpMessages: opts.getFollowUpMessages,\n\t\t\t\ttransformContext: opts.transformContext,\n\t\t\t\trequestPreflight: opts.requestPreflight,\n\t\t\t\t...(maxTurns === undefined\n\t\t\t\t\t? {}\n\t\t\t\t\t: {\n\t\t\t\t\t\t\tshouldStopAfterTurn: () => {\n\t\t\t\t\t\t\t\tcompletedTurns += 1;\n\t\t\t\t\t\t\t\treturn completedTurns >= maxTurns;\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}),\n\t\t\t\tconvertToLlm: agent.convertToLlm,\n\t\t\t};\n\n\t\t\t// An explicitly supplied surface owns a child tool loop even when it is empty: a model may\n\t\t\t// hallucinate an unavailable tool and must receive the bounded unknown-tool result so it can\n\t\t\t// repair. Only an omitted tools option selects the one-shot completion path.\n\t\t\tif (opts.tools !== undefined) {\n\t\t\t\tconst childContext: AgentContext = {\n\t\t\t\t\tsystemPrompt: opts.systemPrompt,\n\t\t\t\t\tmessages: [...history],\n\t\t\t\t\ttools: [...opts.tools],\n\t\t\t\t};\n\t\t\t\tconst messages = await runAgentLoop(\n\t\t\t\t\topts.messages,\n\t\t\t\t\tchildContext,\n\t\t\t\t\tloopConfig,\n\t\t\t\t\tasync (event) => {\n\t\t\t\t\t\tif (event.type === \"message_end\") await opts.onMessage?.(event.message as Message);\n\t\t\t\t\t},\n\t\t\t\t\topts.signal,\n\t\t\t\t\tagent.streamFn,\n\t\t\t\t);\n\t\t\t\tconst assistantMessages = messages.filter(\n\t\t\t\t\t(message): message is AssistantMessage => message.role === \"assistant\",\n\t\t\t\t);\n\t\t\t\tlet finalAssistant = assistantMessages.at(-1);\n\t\t\t\tif (!finalAssistant) {\n\t\t\t\t\tthrow new Error(\"runIsolatedCompletion: child loop produced no assistant message\");\n\t\t\t\t}\n\n\t\t\t\tconst hasFinalText = finalAssistant.content.some(\n\t\t\t\t\t(content) => content.type === \"text\" && content.text.trim().length > 0,\n\t\t\t\t);\n\t\t\t\tconst endedOnToolCall = finalAssistant.content.some((content) => content.type === \"toolCall\");\n\t\t\t\tif (opts.finalTextPrompt && !hasFinalText && endedOnToolCall && !opts.signal?.aborted) {\n\t\t\t\t\t// A hard turn bound may stop immediately after successful tool execution. Preserve that bound,\n\t\t\t\t\t// then allow exactly one tool-free synthesis call so the gathered work is not thrown away.\n\t\t\t\t\tconst finalizationPrompt: Message = {\n\t\t\t\t\t\trole: \"user\",\n\t\t\t\t\t\tcontent: opts.finalTextPrompt,\n\t\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\t};\n\t\t\t\t\tawait opts.onMessage?.(finalizationPrompt);\n\t\t\t\t\tconst finalizationContext: AgentContext = {\n\t\t\t\t\t\tsystemPrompt: opts.systemPrompt,\n\t\t\t\t\t\tmessages: [...history, ...messages, finalizationPrompt],\n\t\t\t\t\t\ttools: [],\n\t\t\t\t\t};\n\t\t\t\t\tconst finalizationStream = await startAgentProviderRequest(\n\t\t\t\t\t\tfinalizationContext,\n\t\t\t\t\t\tloopConfig,\n\t\t\t\t\t\topts.signal,\n\t\t\t\t\t\tagent.streamFn,\n\t\t\t\t\t);\n\t\t\t\t\tfinalAssistant = await finalizationStream.result();\n\t\t\t\t\tawait opts.onMessage?.(finalAssistant);\n\t\t\t\t\tassistantMessages.push(finalAssistant);\n\t\t\t\t\tmessages.push(finalizationPrompt, finalAssistant);\n\t\t\t\t}\n\n\t\t\t\tconst usage = assistantMessages.reduce<Usage>(\n\t\t\t\t\t(total, message) => ({\n\t\t\t\t\t\tinput: total.input + message.usage.input,\n\t\t\t\t\t\toutput: total.output + message.usage.output,\n\t\t\t\t\t\tcacheRead: total.cacheRead + message.usage.cacheRead,\n\t\t\t\t\t\tcacheWrite: total.cacheWrite + message.usage.cacheWrite,\n\t\t\t\t\t\ttotalTokens: total.totalTokens + message.usage.totalTokens,\n\t\t\t\t\t\tcost: {\n\t\t\t\t\t\t\tinput: total.cost.input + message.usage.cost.input,\n\t\t\t\t\t\t\toutput: total.cost.output + message.usage.cost.output,\n\t\t\t\t\t\t\tcacheRead: total.cost.cacheRead + message.usage.cost.cacheRead,\n\t\t\t\t\t\t\tcacheWrite: total.cost.cacheWrite + message.usage.cost.cacheWrite,\n\t\t\t\t\t\t\ttotal: total.cost.total + message.usage.cost.total,\n\t\t\t\t\t\t},\n\t\t\t\t\t}),\n\t\t\t\t\t{\n\t\t\t\t\t\tinput: 0,\n\t\t\t\t\t\toutput: 0,\n\t\t\t\t\t\tcacheRead: 0,\n\t\t\t\t\t\tcacheWrite: 0,\n\t\t\t\t\t\ttotalTokens: 0,\n\t\t\t\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t\tconst text = finalAssistant.content\n\t\t\t\t\t.filter((content): content is TextContent => content.type === \"text\")\n\t\t\t\t\t.map((content) => content.text)\n\t\t\t\t\t.join(\"\");\n\t\t\t\t// Isolated inputs are Message values and this loop only adds assistant/tool-result messages,\n\t\t\t\t// so the child transcript is safely representable by the public Message[] contract.\n\t\t\t\treturn {\n\t\t\t\t\ttext,\n\t\t\t\t\tusage,\n\t\t\t\t\tstopReason: finalAssistant.stopReason,\n\t\t\t\t\tmessages: [...history, ...(messages as Message[])],\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tfor (const message of opts.messages) await opts.onMessage?.(message);\n\t\t\tconst stream = await startAgentProviderRequest(context, loopConfig, opts.signal, agent.streamFn);\n\t\t\tconst result = await stream.result();\n\t\t\tawait opts.onMessage?.(result);\n\t\t\tconst text = result.content\n\t\t\t\t.filter((c): c is TextContent => c.type === \"text\")\n\t\t\t\t.map((c) => c.text)\n\t\t\t\t.join(\"\");\n\t\t\tconst usage: Usage = result.usage ?? {\n\t\t\t\tinput: 0,\n\t\t\t\toutput: 0,\n\t\t\t\tcacheRead: 0,\n\t\t\t\tcacheWrite: 0,\n\t\t\t\ttotalTokens: 0,\n\t\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t\t};\n\t\t\treturn { text, usage, stopReason: result.stopReason, messages: [...history, ...opts.messages, result] };\n\t\t} finally {\n\t\t\tderegisterInFlight();\n\t\t}\n\t}\n\n\t/**\n\t * Native end-of-loop reflection pass (R2). Demand-gates (zero-I/O), and when warranted runs the\n\t * {@link ReflectionEngine} via an isolated completion ({@link runIsolatedCompletion}), applies the\n\t * resulting memory writes through the bundled `memory` tool, and accounts the reflection's token\n\t * cost via the cost-aggregation surface so it stays visible and net-negative-auditable.\n\t *\n\t * Returns `null` when the gate skips (or in a child session, which must not learn). The whole pass\n\t * is best-effort: a model/parse error yields no writes, never throws into the caller.\n\t */\n\tasync runReflectionPass(input: {\n\t\tsignals: DemandSignals;\n\t\trecentTurnText: string;\n\t\tmodel?: Model<Api>;\n\t\tthinkingLevel?: ThinkingLevel;\n\t\tsignal?: AbortSignal;\n\t\t/** Stable id so a duplicate scheduling/retry of the same pass can't double-count its cost. */\n\t\treportId?: string;\n\t\t/** True only when every turn in this pass explicitly asked Pi to remember durable information. */\n\t\texplicitUserMemoryInstruction?: boolean;\n\t}): Promise<ReflectionResult | null> {\n\t\tif (this.deps.isChildSession() || this.deps.isDisposed()) return null;\n\t\tconst plan = decideDemand(input.signals);\n\t\tif (plan.act === \"skip\") return null;\n\n\t\t// Bug #21: tie this background pass to the session lifetime. Disposing the session aborts the\n\t\t// in-flight completion (input.signal can add a more specific abort).\n\t\tconst signal = input.signal\n\t\t\t? AbortSignal.any([input.signal, this.deps.getReflectionSignal()])\n\t\t\t: this.deps.getReflectionSignal();\n\n\t\tconst complete = (systemPrompt: string, userPrompt: string) =>\n\t\t\tthis.runIsolatedCompletion({\n\t\t\t\tsystemPrompt,\n\t\t\t\tmessages: [{ role: \"user\", content: [{ type: \"text\", text: userPrompt }], timestamp: Date.now() }],\n\t\t\t\tmodel: input.model,\n\t\t\t\tthinkingLevel: input.thinkingLevel ?? \"low\",\n\t\t\t\tmaxTokens: plan.tokenBudget,\n\t\t\t\tsignal,\n\t\t\t\t// The reflection system prompt is static (#33) — let the provider cache the prefix so\n\t\t\t\t// repeated passes only pay for the variable tail.\n\t\t\t\tcacheRetention: \"short\",\n\t\t\t\tlaneKind: \"reflection\",\n\t\t\t});\n\n\t\tconst result = await new ReflectionEngine().reflect({\n\t\t\trecentTurnText: input.recentTurnText,\n\t\t\t// Read memory FRESH (not the prefix-cache-frozen system-prompt block) so confront-before-write\n\t\t\t// sees writes made earlier this session.\n\t\t\texistingMemory: this.deps.getMemoryManager().buildSystemPromptBlockFresh() || \"\",\n\t\t\tplan,\n\t\t\tcomplete,\n\t\t});\n\n\t\t// Bug #21: if the session was disposed while the completion was in flight, do NOT write memory\n\t\t// or skills against the dead session.\n\t\tif (this.deps.isDisposed()) return result;\n\n\t\t// Learning apply policy: every durable write is converted to a proposal, decided by the\n\t\t// learning gate, and audited with a rollback plan. When the policy is explicitly disabled,\n\t\t// legacy direct-apply behavior is preserved — but now leaves audit records with rollback info.\n\t\tconst policy = this.deps.getSettingsManager().getLearningPolicySettings();\n\t\t// The audit id sequence counts STORED snapshots only: it reseeds from the stored count on\n\t\t// every pass, so advancing it for a no-op (which stores nothing) would make later passes\n\t\t// reuse ids — and rollback keys on the id, so a collision blocks or misdirects rollback.\n\t\tlet auditSequence = getLearningAuditSnapshots(this.deps.getSessionManager().getEntries()).length;\n\t\t// G6 evidence strength: durable proposals accumulate observation counts across passes/sessions\n\t\t// so the gate can distinguish a one-off cue from a repeatedly-confirmed lesson. Built once per\n\t\t// pass; every increment is best-effort (store IO must never break reflection).\n\t\tconst observationStore = ObservationStore.forAgentDir(this.deps.getAgentDir());\n\t\tlet writeIndex = 0;\n\t\tfor (const write of result.writes) {\n\t\t\twriteIndex += 1;\n\t\t\tconst proposalId = `${input.reportId ?? \"reflection\"}-w${writeIndex}`;\n\t\t\tconst proposal = proposalFromReflectionWrite(write, proposalId);\n\t\t\tconst rollback = rollbackPlanForReflectionWrite(write);\n\t\t\tlet observations = 1;\n\t\t\tif (policy.enabled) {\n\t\t\t\ttry {\n\t\t\t\t\tobservations = observationStore.increment(observationKey(proposal.layer, proposal.summary));\n\t\t\t\t} catch {\n\t\t\t\t\t// A store read/write failure falls back to a fresh count of 1, which keeps the gate\n\t\t\t\t\t// proposal-first (never spuriously auto-applies) rather than crashing the pass.\n\t\t\t\t\tobservations = 1;\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst explicitUserMemoryWrite =\n\t\t\t\tinput.explicitUserMemoryInstruction === true &&\n\t\t\t\t(write.kind === \"memory_add\" || write.kind === \"memory_replace\");\n\t\t\tconst decision: LearningDecision = explicitUserMemoryWrite\n\t\t\t\t? {\n\t\t\t\t\t\tkind: \"apply\",\n\t\t\t\t\t\treasonCode: \"explicit_user_memory_instruction\",\n\t\t\t\t\t\tconfidence: 100,\n\t\t\t\t\t\tsummary: proposal.summary,\n\t\t\t\t\t\trequiresApproval: false,\n\t\t\t\t\t}\n\t\t\t\t: policy.enabled\n\t\t\t\t\t? evaluateLearningDecision({\n\t\t\t\t\t\t\tproposal,\n\t\t\t\t\t\t\tconfidence: policy.reflectionSourceConfidence,\n\t\t\t\t\t\t\tobservations,\n\t\t\t\t\t\t\t// A replace/remove supersedes an existing durable fact — the reflection engine's\n\t\t\t\t\t\t\t// confront-before-write conflict signal — so it routes through approval instead of\n\t\t\t\t\t\t\t// silently overwriting prior memory. Additive writes contradict nothing.\n\t\t\t\t\t\t\tcontradictions: contradictionsForReflectionWrite(write),\n\t\t\t\t\t\t\tsettings: {\n\t\t\t\t\t\t\t\tenabled: true,\n\t\t\t\t\t\t\t\tautoApplyEnabled: policy.autoApplyEnabled,\n\t\t\t\t\t\t\t\tconfidenceThreshold: policy.confidenceThreshold,\n\t\t\t\t\t\t\t\tminObservations: policy.minObservations,\n\t\t\t\t\t\t\t\tallowedAutoApplyLayers: policy.allowedAutoApplyLayers,\n\t\t\t\t\t\t\t\trequireRollbackPlan: policy.requireRollbackPlan,\n\t\t\t\t\t\t\t\tautoApplySupersessions: policy.autoApplySupersessions,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t})\n\t\t\t\t\t: {\n\t\t\t\t\t\t\tkind: \"apply\",\n\t\t\t\t\t\t\treasonCode: \"learning_policy_disabled_legacy_apply\",\n\t\t\t\t\t\t\tconfidence: 0,\n\t\t\t\t\t\t\tsummary: proposal.summary,\n\t\t\t\t\t\t\trequiresApproval: false,\n\t\t\t\t\t\t};\n\n\t\t\tthis.deps.saveLearningDecisionSnapshot(decision);\n\t\t\t// G3: learning-gate outcome. Codes/numbers only — never the proposal summary/memory text.\n\t\t\tthis.deps.emitAutonomyTelemetry({\n\t\t\t\ttype: AUTONOMY_TELEMETRY_EVENT_TYPES.learningDecision,\n\t\t\t\ttimestamp: new Date().toISOString(),\n\t\t\t\tpayload: {\n\t\t\t\t\tkind: decision.kind,\n\t\t\t\t\treasonCode: decision.reasonCode,\n\t\t\t\t\tlayer: proposal.layer,\n\t\t\t\t\tconfidence: decision.confidence,\n\t\t\t\t\trequiresApproval: decision.requiresApproval,\n\t\t\t\t},\n\t\t\t});\n\t\t\t// G8: a proposal that needs human sign-off is an approval REQUEST. Codes/layer only —\n\t\t\t// never the proposal summary/memory text (those live only in the audit snapshot).\n\t\t\tif (decision.requiresApproval) {\n\t\t\t\tthis.deps.emitAutonomyTelemetry({\n\t\t\t\t\ttype: AUTONOMY_TELEMETRY_EVENT_TYPES.approvalRequest,\n\t\t\t\t\ttimestamp: new Date().toISOString(),\n\t\t\t\t\tpayload: {\n\t\t\t\t\t\tkind: decision.kind,\n\t\t\t\t\t\treasonCode: decision.reasonCode,\n\t\t\t\t\t\tlayer: proposal.layer,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t}\n\t\t\t// An automatic skill promotion the gate would otherwise apply must still clear the same\n\t\t\t// skill_audit overlap check the model-invoked `skillify` tool enforces — otherwise reflection\n\t\t\t// can silently write a near-duplicate SKILL.md. A non-overlapping skill is unaffected\n\t\t\t// (skillPromotionBlock stays undefined) and promotes exactly as before.\n\t\t\tconst skillPromotionBlock =\n\t\t\t\twrite.kind === \"promote_skill\" && decision.kind === \"apply\"\n\t\t\t\t\t? this._checkSkillPromotionOverlap(write)\n\t\t\t\t\t: undefined;\n\n\t\t\t// The gate's decision and the write's actual outcome are two different questions: the memory\n\t\t\t// tool can refuse a write (budget exceeded, drift, threat) via details.success:false without\n\t\t\t// throwing. Capture that outcome instead of assuming \"decision.kind === apply\" means it landed\n\t\t\t// — otherwise a refused write leaves a phantom \"apply\" audit whose rollback later fails\n\t\t\t// not-found (or, worse, misfires against whatever now occupies that text).\n\t\t\tconst applied =\n\t\t\t\tdecision.kind === \"apply\" && !skillPromotionBlock ? await this._applyReflectionWrite(write, signal) : false;\n\t\t\tconst writeFailed = decision.kind === \"apply\" && !skillPromotionBlock && !applied;\n\t\t\tif (decision.kind !== \"no-op\") {\n\t\t\t\tauditSequence += 1;\n\t\t\t\tappendLearningAuditSnapshot(this.deps.getSessionManager(), {\n\t\t\t\t\tid: `audit-${auditSequence}`,\n\t\t\t\t\tproposalId,\n\t\t\t\t\tlayer: proposal.layer,\n\t\t\t\t\taction: skillPromotionBlock\n\t\t\t\t\t\t? \"propose\"\n\t\t\t\t\t\t: writeFailed\n\t\t\t\t\t\t\t? \"apply_failed\"\n\t\t\t\t\t\t\t: decision.kind === \"apply\"\n\t\t\t\t\t\t\t\t? \"apply\"\n\t\t\t\t\t\t\t\t: \"propose\",\n\t\t\t\t\tsummary: skillPromotionBlock ? `${proposal.summary} — ${skillPromotionBlock.note}` : proposal.summary,\n\t\t\t\t\treasonCode: skillPromotionBlock\n\t\t\t\t\t\t? skillPromotionBlock.reasonCode\n\t\t\t\t\t\t: writeFailed\n\t\t\t\t\t\t\t? APPLY_WRITE_REFUSED_REASON_CODE\n\t\t\t\t\t\t\t: decision.reasonCode,\n\t\t\t\t\tdecision,\n\t\t\t\t\t// No rollback plan on a failed apply or a held/proposed promotion — nothing durable\n\t\t\t\t\t// landed in either case, so there is nothing to undo.\n\t\t\t\t\trollback: skillPromotionBlock || writeFailed ? undefined : rollback,\n\t\t\t\t\tcreatedAt: new Date().toISOString(),\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\t// Account the reflection's spend so it surfaces in the footer roll-up (net-token visibility).\n\t\t// Idempotent on reportId so a retried/duplicated pass cannot double-count.\n\t\tif (result.usage.cost.total > 0 || result.usage.totalTokens > 0) {\n\t\t\tthis.deps.addSpawnedUsage(result.usage, { label: \"reflection\", reportId: input.reportId });\n\t\t}\n\t\treturn result;\n\t}\n\n\tgetLearningAuditRecords(): LearningAuditRecord[] {\n\t\treturn getLearningAuditSnapshots(this.deps.getSessionManager().getEntries());\n\t}\n\n\t/**\n\t * Roll back one applied durable learning change by executing the inverse operation recorded in\n\t * its audit record (memory ops run through the same bundled memory-tool path as the original\n\t * apply; promoted skills are archived). Appends a linked \"rollback\" audit record on success so\n\t * the change history stays complete and a change cannot be rolled back twice.\n\t */\n\tasync rollbackLearningWrite(auditId: string): Promise<{ ok: boolean; reason: string }> {\n\t\tif (this.deps.isDisposed()) return { ok: false, reason: \"session_disposed\" };\n\n\t\tconst audits = this.getLearningAuditRecords();\n\t\tconst audit = audits.find((record) => record.id === auditId);\n\t\tif (!audit) return { ok: false, reason: \"audit_not_found\" };\n\t\tif (audit.action !== \"apply\") return { ok: false, reason: \"not_an_applied_change\" };\n\t\tif (audits.some((record) => record.action === \"rollback\" && record.rollbackOf === auditId)) {\n\t\t\treturn { ok: false, reason: \"already_rolled_back\" };\n\t\t}\n\t\tconst rollback = audit.rollback;\n\t\tif (!rollback) return { ok: false, reason: \"no_rollback_plan\" };\n\n\t\t// Every inverse must be VERIFIED-applied before the rollback audit is appended: a silently\n\t\t// failed inverse that still recorded \"rollback\" would permanently self-lock the change\n\t\t// behind already_rolled_back while the durable write is in fact still live.\n\t\tswitch (rollback.kind) {\n\t\t\tcase \"memory_remove\": {\n\t\t\t\tif (!rollback.target) return { ok: false, reason: \"missing_rollback_target\" };\n\t\t\t\tif (!(await this._applyReflectionWrite({ kind: \"memory_remove\", target: rollback.target }))) {\n\t\t\t\t\treturn { ok: false, reason: \"rollback_apply_failed\" };\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"memory_restore\": {\n\t\t\t\tif (!rollback.target || rollback.previous === undefined) {\n\t\t\t\t\treturn { ok: false, reason: \"missing_rollback_target\" };\n\t\t\t\t}\n\t\t\t\tconst applied = await this._applyReflectionWrite({\n\t\t\t\t\tkind: \"memory_replace\",\n\t\t\t\t\ttarget: rollback.target,\n\t\t\t\t\ttext: rollback.previous,\n\t\t\t\t});\n\t\t\t\tif (!applied) return { ok: false, reason: \"rollback_apply_failed\" };\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"memory_add\": {\n\t\t\t\tif (rollback.previous === undefined) return { ok: false, reason: \"missing_rollback_target\" };\n\t\t\t\tconst applied = await this._applyReflectionWrite({\n\t\t\t\t\tkind: \"memory_add\",\n\t\t\t\t\tsection: \"MEMORY\",\n\t\t\t\t\ttext: rollback.previous,\n\t\t\t\t});\n\t\t\t\tif (!applied) return { ok: false, reason: \"rollback_apply_failed\" };\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"archive_skill\": {\n\t\t\t\tif (!rollback.target) return { ok: false, reason: \"missing_rollback_target\" };\n\t\t\t\tif (!this.deps.archivePromotedSkill(rollback.target)) {\n\t\t\t\t\treturn { ok: false, reason: \"skill_archive_failed\" };\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tappendLearningAuditSnapshot(this.deps.getSessionManager(), {\n\t\t\tid: `${audit.id}-rollback`,\n\t\t\tproposalId: audit.proposalId,\n\t\t\tlayer: audit.layer,\n\t\t\taction: \"rollback\",\n\t\t\tsummary: `Rolled back: ${audit.summary}`,\n\t\t\treasonCode: \"user_requested_rollback\",\n\t\t\tdecision: audit.decision,\n\t\t\trollbackOf: audit.id,\n\t\t\tcreatedAt: new Date().toISOString(),\n\t\t});\n\t\treturn { ok: true, reason: \"rollback_applied\" };\n\t}\n\n\t/**\n\t * Apply one reflection write through the bundled `memory` tool. `memory_replace`/`memory_remove`\n\t * don't carry a target file, so we try MEMORY.md first and fall back to USER.md when the substring\n\t * isn't found there. Never throws (reflection must never break a turn); returns whether the write\n\t * actually applied so callers that MUST know — rollback's once-only accounting — can react instead\n\t * of recording a success that never happened.\n\t */\n\tprivate async _applyReflectionWrite(write: ReflectionWrite, signal?: AbortSignal): Promise<boolean> {\n\t\t// R7 memory-to-behavior: a recurring procedure is compiled into an executable skill file rather\n\t\t// than stored as a flat fact. Written under the agent skills dir so it loads like any user skill.\n\t\tif (write.kind === \"promote_skill\") {\n\t\t\treturn this._promoteReflectionSkill(write.name, write.description, write.body);\n\t\t}\n\n\t\ttype MemResult = { details?: { success?: boolean; error?: string } };\n\t\ttype MemExec = (\n\t\t\ttoolCallId: string,\n\t\t\tparams: { action: string; target: string; content?: string; oldContent?: string },\n\t\t\tsignal: AbortSignal | undefined,\n\t\t\tonUpdate: undefined,\n\t\t\tctx: undefined,\n\t\t) => Promise<MemResult>;\n\t\tconst memTool = this.deps\n\t\t\t.getMemoryManager()\n\t\t\t.getToolDefinitions()\n\t\t\t.find((t) => t.name === \"memory\");\n\t\tconst exec = memTool?.execute as unknown as MemExec | undefined;\n\t\tif (!exec) return false;\n\n\t\tconst run = (params: Parameters<MemExec>[1]) => exec(\"reflection\", params, signal, undefined, undefined);\n\n\t\tif (write.kind === \"memory_add\") {\n\t\t\ttry {\n\t\t\t\tconst res = await run({\n\t\t\t\t\taction: \"add\",\n\t\t\t\t\ttarget: write.section === \"USER\" ? \"user\" : \"memory\",\n\t\t\t\t\tcontent: write.text,\n\t\t\t\t});\n\t\t\t\treturn res?.details?.success === true;\n\t\t\t} catch {\n\t\t\t\t// best-effort; reflection writes must never throw into the turn loop\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\t// replace / remove carry no target file — try MEMORY.md, then USER.md. The memory tool reports\n\t\t// outcomes via `details.success` (it catches its own errors rather than throwing). Only a\n\t\t// genuine \"not found in the file\" justifies trying the other file; a real failure for a file\n\t\t// (budget exceeded / drift) must NOT fall through and mutate the wrong target.\n\t\tfor (const target of [\"memory\", \"user\"] as const) {\n\t\t\ttry {\n\t\t\t\tconst params =\n\t\t\t\t\twrite.kind === \"memory_replace\"\n\t\t\t\t\t\t? { action: \"replace\", target, oldContent: write.target, content: write.text }\n\t\t\t\t\t\t: { action: \"remove\", target, oldContent: write.target };\n\t\t\t\tconst res = await run(params);\n\t\t\t\tif (res?.details?.success === true) return true; // applied\n\t\t\t\tif (!/not found/i.test(String(res?.details?.error ?? \"\"))) return false; // real failure — don't misapply\n\t\t\t\t// substring simply absent from this file — try the next target\n\t\t\t} catch {\n\t\t\t\t// defensive: if the tool ever does throw, try the next target\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\t/**\n\t * The same skill_audit overlap check the model-invoked `skillify` tool enforces\n\t * (tools/skillify.ts → tools/skill-audit.ts's `runSkillAudit`), run before an AUTOMATIC promotion\n\t * so the reflection engine can never silently write a near-duplicate SKILL.md. Reuses the audit\n\t * seam unchanged (never duplicated) against the same already-loaded skills universe skillify\n\t * compares a draft against. Returns a block reason when the draft overlaps an existing skill above\n\t * the audit's own similarity threshold, or when the audit itself fails (the promotion is held, not\n\t * written unaudited); undefined when clear to promote. Never throws — mirrors every other\n\t * best-effort check in this file.\n\t */\n\tprivate _checkSkillPromotionOverlap(write: {\n\t\tname: string;\n\t\tdescription: string;\n\t\tbody: string;\n\t}): { reasonCode: string; note: string } | undefined {\n\t\ttry {\n\t\t\tconst cwd = this.deps.getCwd?.() ?? process.cwd();\n\t\t\tconst audit = runSkillAudit(cwd, write);\n\t\t\tconst overlap = audit.nearDuplicates.find((d) => d.a === \"[draft]\" || d.b === \"[draft]\");\n\t\t\tif (!overlap) return undefined;\n\t\t\tconst otherPath = overlap.a === \"[draft]\" ? overlap.b : overlap.a;\n\t\t\t// Every skill file is named \"SKILL.md\" — unlike skillify's own display formatter (which takes\n\t\t\t// the path's last segment and always shows that literal filename), look up the declared\n\t\t\t// frontmatter name so the proposal actually names the skill it overlaps with.\n\t\t\tconst otherName = audit.skills.find((s) => s.path === otherPath)?.name ?? otherPath;\n\t\t\treturn {\n\t\t\t\treasonCode: SKILL_OVERLAP_CONSOLIDATION_REASON_CODE,\n\t\t\t\tnote: `overlaps existing skill \"${otherName}\" (${(overlap.similarity * 100).toFixed(0)}% similar) — consolidation proposed instead of a duplicate write`,\n\t\t\t};\n\t\t} catch {\n\t\t\t// Bounded, observable degradation via the promote path's existing error-reporting shape: an\n\t\t\t// audit failure must never throw into the reflection pass, but it also must not silently\n\t\t\t// fall through to an unaudited write — hold the promotion and record why.\n\t\t\treturn {\n\t\t\t\treasonCode: SKILL_AUDIT_UNAVAILABLE_REASON_CODE,\n\t\t\t\tnote: \"skill overlap audit failed; promotion held rather than written unaudited\",\n\t\t\t};\n\t\t}\n\t}\n\n\t/**\n\t * R7: write a reflection-promoted skill as `<agentDir>/skills/<name>/SKILL.md` so it loads like any\n\t * user skill. Best-effort; never clobbers an existing (hand-authored) skill of the same name. The\n\t * overlap audit runs at the call site in {@link runReflectionPass} — a write only reaches here\n\t * once the draft has already cleared it.\n\t */\n\tprivate _promoteReflectionSkill(rawName: string, description: string, body: string): boolean {\n\t\tconst name = rawName\n\t\t\t.trim()\n\t\t\t.toLowerCase()\n\t\t\t.replace(/[^a-z0-9-]+/g, \"-\")\n\t\t\t.replace(/^-+|-+$/g, \"\")\n\t\t\t.slice(0, 64);\n\t\tif (!name || !body.trim()) return false;\n\t\ttry {\n\t\t\tconst dir = join(this.deps.getAgentDir(), \"skills\", name);\n\t\t\tconst file = join(dir, \"SKILL.md\");\n\t\t\tif (existsSync(file)) return false; // do not overwrite an existing skill\n\t\t\tmkdirSync(dir, { recursive: true });\n\t\t\tconst safeDescription = description.replace(/[\\r\\n]+/g, \" \").trim();\n\t\t\t// `promoted: true` marks this as reflection-generated so the curator (#32) can lifecycle-manage\n\t\t\t// it (archive/consolidate) WITHOUT ever touching hand-authored user skills.\n\t\t\tconst content = `---\\nname: ${name}\\ndescription: ${safeDescription}\\npromoted: true\\n---\\n\\n<!-- Auto-generated by the reflection engine (R7 memory-to-behavior). Review and refine. -->\\n\\n${body.trim()}\\n`;\n\t\t\twriteFileSync(file, content, \"utf-8\");\n\t\t\treturn true;\n\t\t} catch {\n\t\t\t// promotion must never break a turn\n\t\t\treturn false;\n\t\t}\n\t}\n}\n"]}
@@ -1,3 +1,4 @@
1
+ import { isProcessAlive } from "./process-liveness.ts";
1
2
  export declare const ACTIVE_TURN_TTL_MS: number;
2
3
  export declare const AUTO_RELOAD_COORDINATOR_TTL_MS: number;
3
4
  export declare function getReloadCoordinationDir(agentDir?: string): string;
@@ -33,7 +34,7 @@ export interface ReloadBlockerOptions {
33
34
  includeAutoLearnSessions?: boolean;
34
35
  isProcessAlive?: (pid: number | undefined) => boolean;
35
36
  }
36
- export declare function isReloadSessionProcessAlive(pid: number | undefined): boolean;
37
+ export { isProcessAlive as isReloadSessionProcessAlive };
37
38
  export declare function describeReloadSession(record: Pick<ReloadSessionRecord, "key" | "pid" | "sessionId" | "sessionFile" | "cwd">): string;
38
39
  export declare function getPendingReloadBlockers(options?: ReloadBlockerOptions): PendingReloadBlockers;
39
40
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"reload-blockers.d.ts","sourceRoot":"","sources":["../../src/core/reload-blockers.ts"],"names":[],"mappings":"AAaA,eAAO,MAAM,kBAAkB,QAAa,CAAC;AAC7C,eAAO,MAAM,8BAA8B,QAAc,CAAC;AAE1D,wBAAgB,wBAAwB,CAAC,QAAQ,GAAE,MA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AAK,GAAG,WAAW,GAAG,aAAa,GAAG,KAAK,CAAC,GACpF,MAAM,CAOR;AAED,wBAAgB,wBAAwB,CAAC,OAAO,GAAE,oBAAyB,GAAG,qBAAqB,CAgBlG;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,MAAM,gBAAgB,GAAG,MAAM,GAAG,OAAO,GAAG,qBAAqB,CAAC;AAExE,MAAM,WAAW,gBAAgB;IAChC,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,gBAAgB,CAAC;IACvB,KAAK,EAAE,MAAM,CAAC;IACd,YAAY,EAAE,MAAM,CAAC;CACrB;AAKD,oGAAoG;AACpG,wBAAgB,oBAAoB,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,gBAAgB,EAAE,KAAK,EAAE,MAAM,GAAG,MAAM,IAAI,CAgBxG;AAED,2FAA2F;AAC3F,wBAAgB,oBAAoB,CAAC,QAAQ,EAAE,MAAM,GAAG,gBAAgB,EAAE,CAGzE;AAED,wBAAgB,wBAAwB,CAAC,IAAI,EAAE,gBAAgB,GAAG,MAAM,CAEvE;AAED;;;GAGG;AACH,wBAAgB,iCAAiC,IAAI,IAAI,CAExD","sourcesContent":["/**\n * Reload/live-op blocker sources for THIS process's reload gate (`RuntimeBuilder`, see\n * runtime-builder.ts): cross-process peer/coordinator sessions (file-backed, below) AND the\n * in-process quiesce registry (`registerInFlightWork`/`getInFlightWorkUnits`) that tracks background\n * lanes, context-scout runs, and isolated completions running in THIS process. The gate reads both;\n * `getPendingReloadBlockers` (cross-process) also backs the `/autonomy` status text.\n */\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { getAgentDir } from \"../config.ts\";\nimport { getProcessWorkRun } from \"../utils/work-directory.ts\";\nimport { isRecordObject } from \"./util/value-guards.ts\";\n\nexport const ACTIVE_TURN_TTL_MS = 5 * 60_000;\nexport const AUTO_RELOAD_COORDINATOR_TTL_MS = 10 * 60_000;\n\nexport function getReloadCoordinationDir(agentDir: string = getAgentDir()): string {\n\treturn getProcessWorkRun(agentDir, \"coordination\", \"reload\", \"state\").path;\n}\n\nexport interface ReloadSessionRecord {\n\tkey: string;\n\tsource: \"active-turn\" | \"coordinator\";\n\tpid?: number;\n\tsessionId?: string;\n\tsessionFile?: string;\n\tcwd?: string;\n\tactive?: boolean;\n\tupdatedAt?: number;\n\tseenAt?: number;\n\treloadedAt?: number;\n\treason?: string;\n}\n\nexport interface PendingReloadBlockers {\n\tpending: boolean;\n\treason: string;\n\tblockers: ReloadSessionRecord[];\n\tdescriptions: string[];\n}\n\nexport interface ReloadBlockerOptions {\n\tagentDir?: string;\n\tnow?: number;\n\townKey?: string;\n\townPid?: number;\n\townSessionId?: string;\n\townSessionFile?: string;\n\tactiveTurnTtlMs?: number;\n\tcoordinatorTtlMs?: number;\n\t/** Auto Learn workers are memory-first, short-lived, and should not block foreground reload/adaptive work by default. */\n\tincludeAutoLearnSessions?: boolean;\n\tisProcessAlive?: (pid: number | undefined) => boolean;\n}\n\ninterface ParsedSession {\n\tpid?: number;\n\tsessionId?: string;\n\tsessionFile?: string;\n\tcwd?: string;\n\tactive?: boolean;\n\tupdatedAt?: number;\n\tseenAt?: number;\n\treloadedAt?: number;\n}\n\nfunction readJsonFile(file: string): unknown {\n\ttry {\n\t\tif (!existsSync(file)) return undefined;\n\t\treturn JSON.parse(readFileSync(file, \"utf8\")) as unknown;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction stringValue(value: unknown): string | undefined {\n\treturn typeof value === \"string\" && value.length > 0 ? value : undefined;\n}\n\nfunction numberValue(value: unknown): number | undefined {\n\tif (typeof value === \"number\" && Number.isFinite(value)) return value;\n\treturn undefined;\n}\n\nfunction booleanValue(value: unknown): boolean | undefined {\n\treturn typeof value === \"boolean\" ? value : undefined;\n}\n\nfunction parseSession(value: unknown): ParsedSession | undefined {\n\tif (!isRecordObject(value)) return undefined;\n\treturn {\n\t\tpid: numberValue(value.pid),\n\t\tsessionId: stringValue(value.sessionId),\n\t\tsessionFile: stringValue(value.sessionFile),\n\t\tcwd: stringValue(value.cwd),\n\t\tactive: booleanValue(value.active),\n\t\tupdatedAt: numberValue(value.updatedAt),\n\t\tseenAt: numberValue(value.seenAt),\n\t\treloadedAt: numberValue(value.reloadedAt),\n\t};\n}\n\nexport function isReloadSessionProcessAlive(pid: number | undefined): boolean {\n\tif (pid === undefined || !Number.isFinite(pid) || pid <= 0) return false;\n\ttry {\n\t\tprocess.kill(pid, 0);\n\t\treturn true;\n\t} catch (error) {\n\t\tconst code =\n\t\t\terror && typeof error === \"object\" && \"code\" in error ? String((error as { code?: unknown }).code) : \"\";\n\t\treturn code === \"EPERM\";\n\t}\n}\n\nfunction isOwnSession(key: string, session: ParsedSession, options: ReloadBlockerOptions): boolean {\n\tif (options.ownKey && key === options.ownKey) return true;\n\tif (options.ownPid !== undefined && session.pid === options.ownPid) return true;\n\tif (options.ownSessionId && session.sessionId === options.ownSessionId) return true;\n\tif (options.ownSessionFile && session.sessionFile === options.ownSessionFile) return true;\n\treturn false;\n}\n\nfunction isAutoLearnSession(session: ParsedSession): boolean {\n\treturn !!session.sessionId?.startsWith(\"auto-learn-\");\n}\n\nfunction shouldIgnoreSession(session: ParsedSession, options: ReloadBlockerOptions): boolean {\n\treturn options.includeAutoLearnSessions !== true && isAutoLearnSession(session);\n}\n\nfunction addBlocker(blockers: Map<string, ReloadSessionRecord>, record: ReloadSessionRecord): void {\n\tconst identity = [\n\t\trecord.key,\n\t\trecord.pid ?? \"\",\n\t\trecord.sessionId ?? \"\",\n\t\trecord.sessionFile ?? \"\",\n\t\trecord.cwd ?? \"\",\n\t].join(\"\\0\");\n\tconst existing = blockers.get(identity);\n\tif (!existing || (existing.source === \"coordinator\" && record.source === \"active-turn\")) {\n\t\tblockers.set(identity, record);\n\t}\n}\n\nfunction activeTurnBlockers(options: ReloadBlockerOptions): ReloadSessionRecord[] {\n\tconst agentDir = options.agentDir ?? getAgentDir();\n\tconst now = options.now ?? Date.now();\n\tconst ttl = options.activeTurnTtlMs ?? ACTIVE_TURN_TTL_MS;\n\tconst isAlive = options.isProcessAlive ?? isReloadSessionProcessAlive;\n\tconst registry = readJsonFile(join(getReloadCoordinationDir(agentDir), \"active-turns.json\"));\n\tif (!isRecordObject(registry) || !isRecordObject(registry.sessions)) return [];\n\n\tconst blockers: ReloadSessionRecord[] = [];\n\tfor (const [key, rawSession] of Object.entries(registry.sessions)) {\n\t\tconst session = parseSession(rawSession);\n\t\tif (!session?.active) continue;\n\t\tif (isOwnSession(key, session, options) || shouldIgnoreSession(session, options)) continue;\n\t\tif (session.updatedAt === undefined || now - session.updatedAt > ttl) continue;\n\t\tif (!isAlive(session.pid)) continue;\n\t\tblockers.push({ key, source: \"active-turn\", ...session });\n\t}\n\treturn blockers;\n}\n\nfunction coordinatorBlockers(options: ReloadBlockerOptions): { blockers: ReloadSessionRecord[]; reason: string } {\n\tconst agentDir = options.agentDir ?? getAgentDir();\n\tconst now = options.now ?? Date.now();\n\tconst ttl = options.coordinatorTtlMs ?? AUTO_RELOAD_COORDINATOR_TTL_MS;\n\tconst isAlive = options.isProcessAlive ?? isReloadSessionProcessAlive;\n\tconst coordinator = readJsonFile(join(getReloadCoordinationDir(agentDir), \"auto-reload-state.json\"));\n\tif (!isRecordObject(coordinator) || !isRecordObject(coordinator.changes)) return { blockers: [], reason: \"\" };\n\n\tconst blockers: ReloadSessionRecord[] = [];\n\tlet reason = \"\";\n\tfor (const rawChange of Object.values(coordinator.changes)) {\n\t\tif (!isRecordObject(rawChange)) continue;\n\t\tconst firstSeenAt = numberValue(rawChange.firstSeenAt);\n\t\tif (firstSeenAt === undefined || now - firstSeenAt > ttl) continue;\n\t\treason ||= stringValue(rawChange.reason) ?? \"\";\n\t\tif (!isRecordObject(rawChange.sessions)) continue;\n\t\tfor (const [key, rawSession] of Object.entries(rawChange.sessions)) {\n\t\t\tconst session = parseSession(rawSession);\n\t\t\tif (!session) continue;\n\t\t\tif (session.reloadedAt !== undefined) continue;\n\t\t\tif (isOwnSession(key, session, options) || shouldIgnoreSession(session, options)) continue;\n\t\t\tif (!isAlive(session.pid)) continue;\n\t\t\tblockers.push({ key, source: \"coordinator\", reason: stringValue(rawChange.reason), ...session });\n\t\t}\n\t}\n\treturn { blockers, reason };\n}\n\nexport function describeReloadSession(\n\trecord: Pick<ReloadSessionRecord, \"key\" | \"pid\" | \"sessionId\" | \"sessionFile\" | \"cwd\">,\n): string {\n\tconst label = record.sessionId ?? record.sessionFile ?? record.cwd ?? String(record.pid ?? \"unknown\");\n\tconst parts = [`${record.key}:${label}`];\n\tif (record.pid !== undefined) parts.push(`pid=${record.pid}`);\n\tif (record.cwd) parts.push(`cwd=${record.cwd}`);\n\tif (record.sessionFile) parts.push(`file=${record.sessionFile}`);\n\treturn parts.join(\" \");\n}\n\nexport function getPendingReloadBlockers(options: ReloadBlockerOptions = {}): PendingReloadBlockers {\n\tconst byIdentity = new Map<string, ReloadSessionRecord>();\n\tfor (const blocker of activeTurnBlockers(options)) addBlocker(byIdentity, blocker);\n\tconst coordinator = coordinatorBlockers(options);\n\tfor (const blocker of coordinator.blockers) addBlocker(byIdentity, blocker);\n\tconst blockers = [...byIdentity.values()].sort((a, b) =>\n\t\tdescribeReloadSession(a).localeCompare(describeReloadSession(b)),\n\t);\n\treturn {\n\t\tpending: blockers.length > 0,\n\t\treason:\n\t\t\tcoordinator.reason ||\n\t\t\t(blockers.length ? \"Pi auto-reload is waiting for active peer/background session(s).\" : \"\"),\n\t\tblockers,\n\t\tdescriptions: blockers.map(describeReloadSession),\n\t};\n}\n\n/**\n * In-process quiesce registry: the reload gate's unified source of truth for background work\n * running IN THIS PROCESS that must finish before a `/reload`, profile switch, or live extension\n * load/unload/reconcile may proceed — background lanes (research/worker/model-fitness), the\n * context-scout's own Agent, and isolated completions (through their single choke point,\n * `ReflectionController.runIsolatedCompletion`) all register here. Foreground streaming/compaction\n * are NOT registered here — the host already exposes those via `RuntimeBuilderDeps.isStreaming`/`isCompacting`,\n * and the gate checks both alongside this registry instead of duplicating that state into a second tracker.\n *\n * Keyed by `agentDir`, matching every cross-process function above, so two sessions rooted at\n * different agent dirs (as every test harness in this repo constructs them) never see each other's\n * in-flight work.\n *\n * Registration is a plain in-memory counter, not file-backed — nothing here survives a process\n * restart, and nothing needs to: a crashed process cannot hold its own reload gate hostage. The\n * returned deregister function MUST be called from a `finally` block by every caller — an\n * un-deregistered unit would wedge the gate forever — so deregistering twice is a safe no-op rather\n * than a footgun for a caller that also deregisters on an early-return path.\n */\nexport type InFlightWorkKind = \"lane\" | \"scout\" | \"isolated-completion\";\n\nexport interface InFlightWorkUnit {\n\tid: number;\n\tkind: InFlightWorkKind;\n\tlabel: string;\n\tregisteredAt: number;\n}\n\nlet _nextInFlightWorkId = 1;\nconst _inFlightWorkByAgentDir = new Map<string, Map<number, InFlightWorkUnit>>();\n\n/** Registers one in-flight background work unit for `agentDir`. Returns its deregister function. */\nexport function registerInFlightWork(agentDir: string, kind: InFlightWorkKind, label: string): () => void {\n\tlet units = _inFlightWorkByAgentDir.get(agentDir);\n\tif (!units) {\n\t\tunits = new Map<number, InFlightWorkUnit>();\n\t\t_inFlightWorkByAgentDir.set(agentDir, units);\n\t}\n\tconst scopedUnits = units;\n\tconst id = _nextInFlightWorkId++;\n\tscopedUnits.set(id, { id, kind, label, registeredAt: Date.now() });\n\tlet deregistered = false;\n\treturn () => {\n\t\tif (deregistered) return;\n\t\tderegistered = true;\n\t\tscopedUnits.delete(id);\n\t\tif (scopedUnits.size === 0) _inFlightWorkByAgentDir.delete(agentDir);\n\t};\n}\n\n/** Live in-flight units for `agentDir`, oldest first. Empty when nothing is registered. */\nexport function getInFlightWorkUnits(agentDir: string): InFlightWorkUnit[] {\n\tconst units = _inFlightWorkByAgentDir.get(agentDir);\n\treturn units ? [...units.values()].sort((a, b) => a.id - b.id) : [];\n}\n\nexport function describeInFlightWorkUnit(unit: InFlightWorkUnit): string {\n\treturn `${unit.kind}:${unit.label}`;\n}\n\n/**\n * Test-only escape hatch: clears every agentDir's registry so one test's leaked registration cannot\n * block another's reload gate or status text.\n */\nexport function resetInFlightWorkRegistryForTests(): void {\n\t_inFlightWorkByAgentDir.clear();\n}\n"]}
1
+ {"version":3,"file":"reload-blockers.d.ts","sourceRoot":"","sources":["../../src/core/reload-blockers.ts"],"names":[],"mappings":"AAWA,OAAO,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAGvD,eAAO,MAAM,kBAAkB,QAAa,CAAC;AAC7C,eAAO,MAAM,8BAA8B,QAAc,CAAC;AAE1D,wBAAgB,wBAAwB,CAAC,QAAQ,GAAE,MAAsB,GAAG,MAAM,CAEjF;AAED,MAAM,WAAW,mBAAmB;IACnC,GAAG,EAAE,MAAM,CAAC;IACZ,MAAM,EAAE,aAAa,GAAG,aAAa,CAAC;IACtC,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,MAAM,CAAC,EAAE,OAAO,CAAC;IACjB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,MAAM,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,qBAAqB;IACrC,OAAO,EAAE,OAAO,CAAC;IACjB,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,mBAAmB,EAAE,CAAC;IAChC,YAAY,EAAE,MAAM,EAAE,CAAC;CACvB;AAED,MAAM,WAAW,oBAAoB;IACpC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,yHAAyH;IACzH,wBAAwB,CAAC,EAAE,OAAO,CAAC;IACnC,cAAc,CAAC,EAAE,CAAC,GAAG,EAAE,MAAM,GAAG,SAAS,KAAK,OAAO,CAAC;CACtD;AAiDD,OAAO,EAAE,cAAc,IAAI,2BAA2B,EAAE,CAAC;AAgFzD,wBAAgB,qBAAqB,CACpC,MAAM,EAAE,IAAI,CAAC,mBAAmB,EAAE,KAAK,GAAG,KAAK,GAAG,WAAW,GAAG,aAAa,GAAG,KAAK,CAAC,GACpF,MAAM,CAOR;AAED,wBAAgB,wBAAwB,CAAC,OAAO,GAAE,oBAAyB,GAAG,qBAAqB,CAgBlG;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,MAAM,gBAAgB,GAAG,MAAM,GAAG,OAAO,GAAG,qBAAqB,CAAC;AAExE,MAAM,WAAW,gBAAgB;IAChC,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,gBAAgB,CAAC;IACvB,KAAK,EAAE,MAAM,CAAC;IACd,YAAY,EAAE,MAAM,CAAC;CACrB;AAKD,oGAAoG;AACpG,wBAAgB,oBAAoB,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,gBAAgB,EAAE,KAAK,EAAE,MAAM,GAAG,MAAM,IAAI,CAgBxG;AAED,2FAA2F;AAC3F,wBAAgB,oBAAoB,CAAC,QAAQ,EAAE,MAAM,GAAG,gBAAgB,EAAE,CAGzE;AAED,wBAAgB,wBAAwB,CAAC,IAAI,EAAE,gBAAgB,GAAG,MAAM,CAEvE;AAED;;;GAGG;AACH,wBAAgB,iCAAiC,IAAI,IAAI,CAExD"}
@@ -9,6 +9,7 @@ import { existsSync, readFileSync } from "node:fs";
9
9
  import { join } from "node:path";
10
10
  import { getAgentDir } from "../config.js";
11
11
  import { getProcessWorkRun } from "../utils/work-directory.js";
12
+ import { isProcessAlive } from "./process-liveness.js";
12
13
  import { isRecordObject } from "./util/value-guards.js";
13
14
  export const ACTIVE_TURN_TTL_MS = 5 * 60_000;
14
15
  export const AUTO_RELOAD_COORDINATOR_TTL_MS = 10 * 60_000;
@@ -50,18 +51,7 @@ function parseSession(value) {
50
51
  reloadedAt: numberValue(value.reloadedAt),
51
52
  };
52
53
  }
53
- export function isReloadSessionProcessAlive(pid) {
54
- if (pid === undefined || !Number.isFinite(pid) || pid <= 0)
55
- return false;
56
- try {
57
- process.kill(pid, 0);
58
- return true;
59
- }
60
- catch (error) {
61
- const code = error && typeof error === "object" && "code" in error ? String(error.code) : "";
62
- return code === "EPERM";
63
- }
64
- }
54
+ export { isProcessAlive as isReloadSessionProcessAlive };
65
55
  function isOwnSession(key, session, options) {
66
56
  if (options.ownKey && key === options.ownKey)
67
57
  return true;
@@ -96,7 +86,7 @@ function activeTurnBlockers(options) {
96
86
  const agentDir = options.agentDir ?? getAgentDir();
97
87
  const now = options.now ?? Date.now();
98
88
  const ttl = options.activeTurnTtlMs ?? ACTIVE_TURN_TTL_MS;
99
- const isAlive = options.isProcessAlive ?? isReloadSessionProcessAlive;
89
+ const isAlive = options.isProcessAlive ?? isProcessAlive;
100
90
  const registry = readJsonFile(join(getReloadCoordinationDir(agentDir), "active-turns.json"));
101
91
  if (!isRecordObject(registry) || !isRecordObject(registry.sessions))
102
92
  return [];
@@ -119,7 +109,7 @@ function coordinatorBlockers(options) {
119
109
  const agentDir = options.agentDir ?? getAgentDir();
120
110
  const now = options.now ?? Date.now();
121
111
  const ttl = options.coordinatorTtlMs ?? AUTO_RELOAD_COORDINATOR_TTL_MS;
122
- const isAlive = options.isProcessAlive ?? isReloadSessionProcessAlive;
112
+ const isAlive = options.isProcessAlive ?? isProcessAlive;
123
113
  const coordinator = readJsonFile(join(getReloadCoordinationDir(agentDir), "auto-reload-state.json"));
124
114
  if (!isRecordObject(coordinator) || !isRecordObject(coordinator.changes))
125
115
  return { blockers: [],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C,KAAK,EAAE,CAAC;AAAA,CACpC;AAED;;;GAGG;AACH,MAAM,UAAU,iCAAiC,GAAS;IACzD,uBAAuB,CAAC,KAAK,EAAE,CAAC;AAAA,CAChC","sourcesContent":["/**\n * Reload/live-op blocker sources for THIS process's reload gate (`RuntimeBuilder`, see\n * runtime-builder.ts): cross-process peer/coordinator sessions (file-backed, below) AND the\n * in-process quiesce registry (`registerInFlightWork`/`getInFlightWorkUnits`) that tracks background\n * lanes, context-scout runs, and isolated completions running in THIS process. The gate reads both;\n * `getPendingReloadBlockers` (cross-process) also backs the `/autonomy` status text.\n */\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { getAgentDir } from \"../config.ts\";\nimport { getProcessWorkRun } from \"../utils/work-directory.ts\";\nimport { isRecordObject } from \"./util/value-guards.ts\";\n\nexport const ACTIVE_TURN_TTL_MS = 5 * 60_000;\nexport const AUTO_RELOAD_COORDINATOR_TTL_MS = 10 * 60_000;\n\nexport function getReloadCoordinationDir(agentDir: string = getAgentDir()): string {\n\treturn getProcessWorkRun(agentDir, \"coordination\", \"reload\", \"state\").path;\n}\n\nexport interface ReloadSessionRecord {\n\tkey: string;\n\tsource: \"active-turn\" | \"coordinator\";\n\tpid?: number;\n\tsessionId?: string;\n\tsessionFile?: string;\n\tcwd?: string;\n\tactive?: boolean;\n\tupdatedAt?: number;\n\tseenAt?: number;\n\treloadedAt?: number;\n\treason?: string;\n}\n\nexport interface PendingReloadBlockers {\n\tpending: boolean;\n\treason: string;\n\tblockers: ReloadSessionRecord[];\n\tdescriptions: string[];\n}\n\nexport interface ReloadBlockerOptions {\n\tagentDir?: string;\n\tnow?: number;\n\townKey?: string;\n\townPid?: number;\n\townSessionId?: string;\n\townSessionFile?: string;\n\tactiveTurnTtlMs?: number;\n\tcoordinatorTtlMs?: number;\n\t/** Auto Learn workers are memory-first, short-lived, and should not block foreground reload/adaptive work by default. */\n\tincludeAutoLearnSessions?: boolean;\n\tisProcessAlive?: (pid: number | undefined) => boolean;\n}\n\ninterface ParsedSession {\n\tpid?: number;\n\tsessionId?: string;\n\tsessionFile?: string;\n\tcwd?: string;\n\tactive?: boolean;\n\tupdatedAt?: number;\n\tseenAt?: number;\n\treloadedAt?: number;\n}\n\nfunction readJsonFile(file: string): unknown {\n\ttry {\n\t\tif (!existsSync(file)) return undefined;\n\t\treturn JSON.parse(readFileSync(file, \"utf8\")) as unknown;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction stringValue(value: unknown): string | undefined {\n\treturn typeof value === \"string\" && value.length > 0 ? value : undefined;\n}\n\nfunction numberValue(value: unknown): number | undefined {\n\tif (typeof value === \"number\" && Number.isFinite(value)) return value;\n\treturn undefined;\n}\n\nfunction booleanValue(value: unknown): boolean | undefined {\n\treturn typeof value === \"boolean\" ? value : undefined;\n}\n\nfunction parseSession(value: unknown): ParsedSession | undefined {\n\tif (!isRecordObject(value)) return undefined;\n\treturn {\n\t\tpid: numberValue(value.pid),\n\t\tsessionId: stringValue(value.sessionId),\n\t\tsessionFile: stringValue(value.sessionFile),\n\t\tcwd: stringValue(value.cwd),\n\t\tactive: booleanValue(value.active),\n\t\tupdatedAt: numberValue(value.updatedAt),\n\t\tseenAt: numberValue(value.seenAt),\n\t\treloadedAt: numberValue(value.reloadedAt),\n\t};\n}\n\nexport function isReloadSessionProcessAlive(pid: number | undefined): boolean {\n\tif (pid === undefined || !Number.isFinite(pid) || pid <= 0) return false;\n\ttry {\n\t\tprocess.kill(pid, 0);\n\t\treturn true;\n\t} catch (error) {\n\t\tconst code =\n\t\t\terror && typeof error === \"object\" && \"code\" in error ? String((error as { code?: unknown }).code) : \"\";\n\t\treturn code === \"EPERM\";\n\t}\n}\n\nfunction isOwnSession(key: string, session: ParsedSession, options: ReloadBlockerOptions): boolean {\n\tif (options.ownKey && key === options.ownKey) return true;\n\tif (options.ownPid !== undefined && session.pid === options.ownPid) return true;\n\tif (options.ownSessionId && session.sessionId === options.ownSessionId) return true;\n\tif (options.ownSessionFile && session.sessionFile === options.ownSessionFile) return true;\n\treturn false;\n}\n\nfunction isAutoLearnSession(session: ParsedSession): boolean {\n\treturn !!session.sessionId?.startsWith(\"auto-learn-\");\n}\n\nfunction shouldIgnoreSession(session: ParsedSession, options: ReloadBlockerOptions): boolean {\n\treturn options.includeAutoLearnSessions !== true && isAutoLearnSession(session);\n}\n\nfunction addBlocker(blockers: Map<string, ReloadSessionRecord>, record: ReloadSessionRecord): void {\n\tconst identity = [\n\t\trecord.key,\n\t\trecord.pid ?? \"\",\n\t\trecord.sessionId ?? \"\",\n\t\trecord.sessionFile ?? \"\",\n\t\trecord.cwd ?? \"\",\n\t].join(\"\\0\");\n\tconst existing = blockers.get(identity);\n\tif (!existing || (existing.source === \"coordinator\" && record.source === \"active-turn\")) {\n\t\tblockers.set(identity, record);\n\t}\n}\n\nfunction activeTurnBlockers(options: ReloadBlockerOptions): ReloadSessionRecord[] {\n\tconst agentDir = options.agentDir ?? getAgentDir();\n\tconst now = options.now ?? Date.now();\n\tconst ttl = options.activeTurnTtlMs ?? ACTIVE_TURN_TTL_MS;\n\tconst isAlive = options.isProcessAlive ?? isReloadSessionProcessAlive;\n\tconst registry = readJsonFile(join(getReloadCoordinationDir(agentDir), \"active-turns.json\"));\n\tif (!isRecordObject(registry) || !isRecordObject(registry.sessions)) return [];\n\n\tconst blockers: ReloadSessionRecord[] = [];\n\tfor (const [key, rawSession] of Object.entries(registry.sessions)) {\n\t\tconst session = parseSession(rawSession);\n\t\tif (!session?.active) continue;\n\t\tif (isOwnSession(key, session, options) || shouldIgnoreSession(session, options)) continue;\n\t\tif (session.updatedAt === undefined || now - session.updatedAt > ttl) continue;\n\t\tif (!isAlive(session.pid)) continue;\n\t\tblockers.push({ key, source: \"active-turn\", ...session });\n\t}\n\treturn blockers;\n}\n\nfunction coordinatorBlockers(options: ReloadBlockerOptions): { blockers: ReloadSessionRecord[]; reason: string } {\n\tconst agentDir = options.agentDir ?? getAgentDir();\n\tconst now = options.now ?? Date.now();\n\tconst ttl = options.coordinatorTtlMs ?? AUTO_RELOAD_COORDINATOR_TTL_MS;\n\tconst isAlive = options.isProcessAlive ?? isReloadSessionProcessAlive;\n\tconst coordinator = readJsonFile(join(getReloadCoordinationDir(agentDir), \"auto-reload-state.json\"));\n\tif (!isRecordObject(coordinator) || !isRecordObject(coordinator.changes)) return { blockers: [], reason: \"\" };\n\n\tconst blockers: ReloadSessionRecord[] = [];\n\tlet reason = \"\";\n\tfor (const rawChange of Object.values(coordinator.changes)) {\n\t\tif (!isRecordObject(rawChange)) continue;\n\t\tconst firstSeenAt = numberValue(rawChange.firstSeenAt);\n\t\tif (firstSeenAt === undefined || now - firstSeenAt > ttl) continue;\n\t\treason ||= stringValue(rawChange.reason) ?? \"\";\n\t\tif (!isRecordObject(rawChange.sessions)) continue;\n\t\tfor (const [key, rawSession] of Object.entries(rawChange.sessions)) {\n\t\t\tconst session = parseSession(rawSession);\n\t\t\tif (!session) continue;\n\t\t\tif (session.reloadedAt !== undefined) continue;\n\t\t\tif (isOwnSession(key, session, options) || shouldIgnoreSession(session, options)) continue;\n\t\t\tif (!isAlive(session.pid)) continue;\n\t\t\tblockers.push({ key, source: \"coordinator\", reason: stringValue(rawChange.reason), ...session });\n\t\t}\n\t}\n\treturn { blockers, reason };\n}\n\nexport function describeReloadSession(\n\trecord: Pick<ReloadSessionRecord, \"key\" | \"pid\" | \"sessionId\" | \"sessionFile\" | \"cwd\">,\n): string {\n\tconst label = record.sessionId ?? record.sessionFile ?? record.cwd ?? String(record.pid ?? \"unknown\");\n\tconst parts = [`${record.key}:${label}`];\n\tif (record.pid !== undefined) parts.push(`pid=${record.pid}`);\n\tif (record.cwd) parts.push(`cwd=${record.cwd}`);\n\tif (record.sessionFile) parts.push(`file=${record.sessionFile}`);\n\treturn parts.join(\" \");\n}\n\nexport function getPendingReloadBlockers(options: ReloadBlockerOptions = {}): PendingReloadBlockers {\n\tconst byIdentity = new Map<string, ReloadSessionRecord>();\n\tfor (const blocker of activeTurnBlockers(options)) addBlocker(byIdentity, blocker);\n\tconst coordinator = coordinatorBlockers(options);\n\tfor (const blocker of coordinator.blockers) addBlocker(byIdentity, blocker);\n\tconst blockers = [...byIdentity.values()].sort((a, b) =>\n\t\tdescribeReloadSession(a).localeCompare(describeReloadSession(b)),\n\t);\n\treturn {\n\t\tpending: blockers.length > 0,\n\t\treason:\n\t\t\tcoordinator.reason ||\n\t\t\t(blockers.length ? \"Pi auto-reload is waiting for active peer/background session(s).\" : \"\"),\n\t\tblockers,\n\t\tdescriptions: blockers.map(describeReloadSession),\n\t};\n}\n\n/**\n * In-process quiesce registry: the reload gate's unified source of truth for background work\n * running IN THIS PROCESS that must finish before a `/reload`, profile switch, or live extension\n * load/unload/reconcile may proceed — background lanes (research/worker/model-fitness), the\n * context-scout's own Agent, and isolated completions (through their single choke point,\n * `ReflectionController.runIsolatedCompletion`) all register here. Foreground streaming/compaction\n * are NOT registered here — the host already exposes those via `RuntimeBuilderDeps.isStreaming`/`isCompacting`,\n * and the gate checks both alongside this registry instead of duplicating that state into a second tracker.\n *\n * Keyed by `agentDir`, matching every cross-process function above, so two sessions rooted at\n * different agent dirs (as every test harness in this repo constructs them) never see each other's\n * in-flight work.\n *\n * Registration is a plain in-memory counter, not file-backed — nothing here survives a process\n * restart, and nothing needs to: a crashed process cannot hold its own reload gate hostage. The\n * returned deregister function MUST be called from a `finally` block by every caller — an\n * un-deregistered unit would wedge the gate forever — so deregistering twice is a safe no-op rather\n * than a footgun for a caller that also deregisters on an early-return path.\n */\nexport type InFlightWorkKind = \"lane\" | \"scout\" | \"isolated-completion\";\n\nexport interface InFlightWorkUnit {\n\tid: number;\n\tkind: InFlightWorkKind;\n\tlabel: string;\n\tregisteredAt: number;\n}\n\nlet _nextInFlightWorkId = 1;\nconst _inFlightWorkByAgentDir = new Map<string, Map<number, InFlightWorkUnit>>();\n\n/** Registers one in-flight background work unit for `agentDir`. Returns its deregister function. */\nexport function registerInFlightWork(agentDir: string, kind: InFlightWorkKind, label: string): () => void {\n\tlet units = _inFlightWorkByAgentDir.get(agentDir);\n\tif (!units) {\n\t\tunits = new Map<number, InFlightWorkUnit>();\n\t\t_inFlightWorkByAgentDir.set(agentDir, units);\n\t}\n\tconst scopedUnits = units;\n\tconst id = _nextInFlightWorkId++;\n\tscopedUnits.set(id, { id, kind, label, registeredAt: Date.now() });\n\tlet deregistered = false;\n\treturn () => {\n\t\tif (deregistered) return;\n\t\tderegistered = true;\n\t\tscopedUnits.delete(id);\n\t\tif (scopedUnits.size === 0) _inFlightWorkByAgentDir.delete(agentDir);\n\t};\n}\n\n/** Live in-flight units for `agentDir`, oldest first. Empty when nothing is registered. */\nexport function getInFlightWorkUnits(agentDir: string): InFlightWorkUnit[] {\n\tconst units = _inFlightWorkByAgentDir.get(agentDir);\n\treturn units ? [...units.values()].sort((a, b) => a.id - b.id) : [];\n}\n\nexport function describeInFlightWorkUnit(unit: InFlightWorkUnit): string {\n\treturn `${unit.kind}:${unit.label}`;\n}\n\n/**\n * Test-only escape hatch: clears every agentDir's registry so one test's leaked registration cannot\n * block another's reload gate or status text.\n */\nexport function resetInFlightWorkRegistryForTests(): void {\n\t_inFlightWorkByAgentDir.clear();\n}\n"]}
1
+ {"version":3,"file":"reload-blockers.js","sourceRoot":"","sources":["../../src/core/reload-blockers.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACnD,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAE,iBAAiB,EAAE,MAAM,4BAA4B,CAAC;AAC/D,OAAO,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AACvD,OAAO,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AAExD,MAAM,CAAC,MAAM,kBAAkB,GAAG,CAAC,GAAG,MAAM,CAAC;AAC7C,MAAM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AAG,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;AACrE,CAAC;AAED,MAAM,UAAU,wBAAwB,CAAC,IAAsB;IAC9D,OAAO,GAAG,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC,KAAK,EAAE,CAAC;AACrC,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,iCAAiC;IAChD,uBAAuB,CAAC,KAAK,EAAE,CAAC;AACjC,CAAC","sourcesContent":["/**\n * Reload/live-op blocker sources for THIS process's reload gate (`RuntimeBuilder`, see\n * runtime-builder.ts): cross-process peer/coordinator sessions (file-backed, below) AND the\n * in-process quiesce registry (`registerInFlightWork`/`getInFlightWorkUnits`) that tracks background\n * lanes, context-scout runs, and isolated completions running in THIS process. The gate reads both;\n * `getPendingReloadBlockers` (cross-process) also backs the `/autonomy` status text.\n */\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { getAgentDir } from \"../config.ts\";\nimport { getProcessWorkRun } from \"../utils/work-directory.ts\";\nimport { isProcessAlive } from \"./process-liveness.ts\";\nimport { isRecordObject } from \"./util/value-guards.ts\";\n\nexport const ACTIVE_TURN_TTL_MS = 5 * 60_000;\nexport const AUTO_RELOAD_COORDINATOR_TTL_MS = 10 * 60_000;\n\nexport function getReloadCoordinationDir(agentDir: string = getAgentDir()): string {\n\treturn getProcessWorkRun(agentDir, \"coordination\", \"reload\", \"state\").path;\n}\n\nexport interface ReloadSessionRecord {\n\tkey: string;\n\tsource: \"active-turn\" | \"coordinator\";\n\tpid?: number;\n\tsessionId?: string;\n\tsessionFile?: string;\n\tcwd?: string;\n\tactive?: boolean;\n\tupdatedAt?: number;\n\tseenAt?: number;\n\treloadedAt?: number;\n\treason?: string;\n}\n\nexport interface PendingReloadBlockers {\n\tpending: boolean;\n\treason: string;\n\tblockers: ReloadSessionRecord[];\n\tdescriptions: string[];\n}\n\nexport interface ReloadBlockerOptions {\n\tagentDir?: string;\n\tnow?: number;\n\townKey?: string;\n\townPid?: number;\n\townSessionId?: string;\n\townSessionFile?: string;\n\tactiveTurnTtlMs?: number;\n\tcoordinatorTtlMs?: number;\n\t/** Auto Learn workers are memory-first, short-lived, and should not block foreground reload/adaptive work by default. */\n\tincludeAutoLearnSessions?: boolean;\n\tisProcessAlive?: (pid: number | undefined) => boolean;\n}\n\ninterface ParsedSession {\n\tpid?: number;\n\tsessionId?: string;\n\tsessionFile?: string;\n\tcwd?: string;\n\tactive?: boolean;\n\tupdatedAt?: number;\n\tseenAt?: number;\n\treloadedAt?: number;\n}\n\nfunction readJsonFile(file: string): unknown {\n\ttry {\n\t\tif (!existsSync(file)) return undefined;\n\t\treturn JSON.parse(readFileSync(file, \"utf8\")) as unknown;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction stringValue(value: unknown): string | undefined {\n\treturn typeof value === \"string\" && value.length > 0 ? value : undefined;\n}\n\nfunction numberValue(value: unknown): number | undefined {\n\tif (typeof value === \"number\" && Number.isFinite(value)) return value;\n\treturn undefined;\n}\n\nfunction booleanValue(value: unknown): boolean | undefined {\n\treturn typeof value === \"boolean\" ? value : undefined;\n}\n\nfunction parseSession(value: unknown): ParsedSession | undefined {\n\tif (!isRecordObject(value)) return undefined;\n\treturn {\n\t\tpid: numberValue(value.pid),\n\t\tsessionId: stringValue(value.sessionId),\n\t\tsessionFile: stringValue(value.sessionFile),\n\t\tcwd: stringValue(value.cwd),\n\t\tactive: booleanValue(value.active),\n\t\tupdatedAt: numberValue(value.updatedAt),\n\t\tseenAt: numberValue(value.seenAt),\n\t\treloadedAt: numberValue(value.reloadedAt),\n\t};\n}\n\nexport { isProcessAlive as isReloadSessionProcessAlive };\n\nfunction isOwnSession(key: string, session: ParsedSession, options: ReloadBlockerOptions): boolean {\n\tif (options.ownKey && key === options.ownKey) return true;\n\tif (options.ownPid !== undefined && session.pid === options.ownPid) return true;\n\tif (options.ownSessionId && session.sessionId === options.ownSessionId) return true;\n\tif (options.ownSessionFile && session.sessionFile === options.ownSessionFile) return true;\n\treturn false;\n}\n\nfunction isAutoLearnSession(session: ParsedSession): boolean {\n\treturn !!session.sessionId?.startsWith(\"auto-learn-\");\n}\n\nfunction shouldIgnoreSession(session: ParsedSession, options: ReloadBlockerOptions): boolean {\n\treturn options.includeAutoLearnSessions !== true && isAutoLearnSession(session);\n}\n\nfunction addBlocker(blockers: Map<string, ReloadSessionRecord>, record: ReloadSessionRecord): void {\n\tconst identity = [\n\t\trecord.key,\n\t\trecord.pid ?? \"\",\n\t\trecord.sessionId ?? \"\",\n\t\trecord.sessionFile ?? \"\",\n\t\trecord.cwd ?? \"\",\n\t].join(\"\\0\");\n\tconst existing = blockers.get(identity);\n\tif (!existing || (existing.source === \"coordinator\" && record.source === \"active-turn\")) {\n\t\tblockers.set(identity, record);\n\t}\n}\n\nfunction activeTurnBlockers(options: ReloadBlockerOptions): ReloadSessionRecord[] {\n\tconst agentDir = options.agentDir ?? getAgentDir();\n\tconst now = options.now ?? Date.now();\n\tconst ttl = options.activeTurnTtlMs ?? ACTIVE_TURN_TTL_MS;\n\tconst isAlive = options.isProcessAlive ?? isProcessAlive;\n\tconst registry = readJsonFile(join(getReloadCoordinationDir(agentDir), \"active-turns.json\"));\n\tif (!isRecordObject(registry) || !isRecordObject(registry.sessions)) return [];\n\n\tconst blockers: ReloadSessionRecord[] = [];\n\tfor (const [key, rawSession] of Object.entries(registry.sessions)) {\n\t\tconst session = parseSession(rawSession);\n\t\tif (!session?.active) continue;\n\t\tif (isOwnSession(key, session, options) || shouldIgnoreSession(session, options)) continue;\n\t\tif (session.updatedAt === undefined || now - session.updatedAt > ttl) continue;\n\t\tif (!isAlive(session.pid)) continue;\n\t\tblockers.push({ key, source: \"active-turn\", ...session });\n\t}\n\treturn blockers;\n}\n\nfunction coordinatorBlockers(options: ReloadBlockerOptions): { blockers: ReloadSessionRecord[]; reason: string } {\n\tconst agentDir = options.agentDir ?? getAgentDir();\n\tconst now = options.now ?? Date.now();\n\tconst ttl = options.coordinatorTtlMs ?? AUTO_RELOAD_COORDINATOR_TTL_MS;\n\tconst isAlive = options.isProcessAlive ?? isProcessAlive;\n\tconst coordinator = readJsonFile(join(getReloadCoordinationDir(agentDir), \"auto-reload-state.json\"));\n\tif (!isRecordObject(coordinator) || !isRecordObject(coordinator.changes)) return { blockers: [], reason: \"\" };\n\n\tconst blockers: ReloadSessionRecord[] = [];\n\tlet reason = \"\";\n\tfor (const rawChange of Object.values(coordinator.changes)) {\n\t\tif (!isRecordObject(rawChange)) continue;\n\t\tconst firstSeenAt = numberValue(rawChange.firstSeenAt);\n\t\tif (firstSeenAt === undefined || now - firstSeenAt > ttl) continue;\n\t\treason ||= stringValue(rawChange.reason) ?? \"\";\n\t\tif (!isRecordObject(rawChange.sessions)) continue;\n\t\tfor (const [key, rawSession] of Object.entries(rawChange.sessions)) {\n\t\t\tconst session = parseSession(rawSession);\n\t\t\tif (!session) continue;\n\t\t\tif (session.reloadedAt !== undefined) continue;\n\t\t\tif (isOwnSession(key, session, options) || shouldIgnoreSession(session, options)) continue;\n\t\t\tif (!isAlive(session.pid)) continue;\n\t\t\tblockers.push({ key, source: \"coordinator\", reason: stringValue(rawChange.reason), ...session });\n\t\t}\n\t}\n\treturn { blockers, reason };\n}\n\nexport function describeReloadSession(\n\trecord: Pick<ReloadSessionRecord, \"key\" | \"pid\" | \"sessionId\" | \"sessionFile\" | \"cwd\">,\n): string {\n\tconst label = record.sessionId ?? record.sessionFile ?? record.cwd ?? String(record.pid ?? \"unknown\");\n\tconst parts = [`${record.key}:${label}`];\n\tif (record.pid !== undefined) parts.push(`pid=${record.pid}`);\n\tif (record.cwd) parts.push(`cwd=${record.cwd}`);\n\tif (record.sessionFile) parts.push(`file=${record.sessionFile}`);\n\treturn parts.join(\" \");\n}\n\nexport function getPendingReloadBlockers(options: ReloadBlockerOptions = {}): PendingReloadBlockers {\n\tconst byIdentity = new Map<string, ReloadSessionRecord>();\n\tfor (const blocker of activeTurnBlockers(options)) addBlocker(byIdentity, blocker);\n\tconst coordinator = coordinatorBlockers(options);\n\tfor (const blocker of coordinator.blockers) addBlocker(byIdentity, blocker);\n\tconst blockers = [...byIdentity.values()].sort((a, b) =>\n\t\tdescribeReloadSession(a).localeCompare(describeReloadSession(b)),\n\t);\n\treturn {\n\t\tpending: blockers.length > 0,\n\t\treason:\n\t\t\tcoordinator.reason ||\n\t\t\t(blockers.length ? \"Pi auto-reload is waiting for active peer/background session(s).\" : \"\"),\n\t\tblockers,\n\t\tdescriptions: blockers.map(describeReloadSession),\n\t};\n}\n\n/**\n * In-process quiesce registry: the reload gate's unified source of truth for background work\n * running IN THIS PROCESS that must finish before a `/reload`, profile switch, or live extension\n * load/unload/reconcile may proceed — background lanes (research/worker/model-fitness), the\n * context-scout's own Agent, and isolated completions (through their single choke point,\n * `ReflectionController.runIsolatedCompletion`) all register here. Foreground streaming/compaction\n * are NOT registered here — the host already exposes those via `RuntimeBuilderDeps.isStreaming`/`isCompacting`,\n * and the gate checks both alongside this registry instead of duplicating that state into a second tracker.\n *\n * Keyed by `agentDir`, matching every cross-process function above, so two sessions rooted at\n * different agent dirs (as every test harness in this repo constructs them) never see each other's\n * in-flight work.\n *\n * Registration is a plain in-memory counter, not file-backed — nothing here survives a process\n * restart, and nothing needs to: a crashed process cannot hold its own reload gate hostage. The\n * returned deregister function MUST be called from a `finally` block by every caller — an\n * un-deregistered unit would wedge the gate forever — so deregistering twice is a safe no-op rather\n * than a footgun for a caller that also deregisters on an early-return path.\n */\nexport type InFlightWorkKind = \"lane\" | \"scout\" | \"isolated-completion\";\n\nexport interface InFlightWorkUnit {\n\tid: number;\n\tkind: InFlightWorkKind;\n\tlabel: string;\n\tregisteredAt: number;\n}\n\nlet _nextInFlightWorkId = 1;\nconst _inFlightWorkByAgentDir = new Map<string, Map<number, InFlightWorkUnit>>();\n\n/** Registers one in-flight background work unit for `agentDir`. Returns its deregister function. */\nexport function registerInFlightWork(agentDir: string, kind: InFlightWorkKind, label: string): () => void {\n\tlet units = _inFlightWorkByAgentDir.get(agentDir);\n\tif (!units) {\n\t\tunits = new Map<number, InFlightWorkUnit>();\n\t\t_inFlightWorkByAgentDir.set(agentDir, units);\n\t}\n\tconst scopedUnits = units;\n\tconst id = _nextInFlightWorkId++;\n\tscopedUnits.set(id, { id, kind, label, registeredAt: Date.now() });\n\tlet deregistered = false;\n\treturn () => {\n\t\tif (deregistered) return;\n\t\tderegistered = true;\n\t\tscopedUnits.delete(id);\n\t\tif (scopedUnits.size === 0) _inFlightWorkByAgentDir.delete(agentDir);\n\t};\n}\n\n/** Live in-flight units for `agentDir`, oldest first. Empty when nothing is registered. */\nexport function getInFlightWorkUnits(agentDir: string): InFlightWorkUnit[] {\n\tconst units = _inFlightWorkByAgentDir.get(agentDir);\n\treturn units ? [...units.values()].sort((a, b) => a.id - b.id) : [];\n}\n\nexport function describeInFlightWorkUnit(unit: InFlightWorkUnit): string {\n\treturn `${unit.kind}:${unit.label}`;\n}\n\n/**\n * Test-only escape hatch: clears every agentDir's registry so one test's leaked registration cannot\n * block another's reload gate or status text.\n */\nexport function resetInFlightWorkRegistryForTests(): void {\n\t_inFlightWorkByAgentDir.clear();\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"request-auth.d.ts","sourceRoot":"","sources":["../../src/core/request-auth.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,WAAW;IAC3B,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CACjC;AAID,wBAAgB,wBAAwB,CAAC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,SAAS,GAAG,OAAO,CAI7F;AAED,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,WAAW,GAAG,OAAO,CAE/D","sourcesContent":["export interface RequestAuth {\n\tapiKey?: string;\n\theaders?: Record<string, string>;\n}\n\nconst AUTHENTICATION_HEADER_NAMES = new Set([\"authorization\", \"api-key\", \"x-api-key\"]);\n\nexport function hasAuthenticationHeaders(headers: Record<string, string> | undefined): boolean {\n\treturn Object.entries(headers ?? {}).some(\n\t\t([name, value]) => AUTHENTICATION_HEADER_NAMES.has(name.toLowerCase()) && value.trim().length > 0,\n\t);\n}\n\nexport function hasUsableRequestAuth(auth: RequestAuth): boolean {\n\treturn Boolean(auth.apiKey?.trim()) || hasAuthenticationHeaders(auth.headers);\n}\n"]}
1
+ {"version":3,"file":"request-auth.d.ts","sourceRoot":"","sources":["../../src/core/request-auth.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,WAAW;IAC3B,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CACjC;AAID,wBAAgB,wBAAwB,CAAC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,SAAS,GAAG,OAAO,CAI7F;AAED,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,WAAW,GAAG,OAAO,CAE/D"}
@@ -1 +1 @@
1
- {"version":3,"file":"request-auth.js","sourceRoot":"","sources":["../../src/core/request-auth.ts"],"names":[],"mappings":"AAKA,MAAM,2BAA2B,GAAG,IAAI,GAAG,CAAC,CAAC,eAAe,EAAE,SAAS,EAAE,WAAW,CAAC,CAAC,CAAC;AAEvF,MAAM,UAAU,wBAAwB,CAAC,OAA2C,EAAW;IAC9F,OAAO,MAAM,CAAC,OAAO,CAAC,OAAO,IAAI,EAAE,CAAC,CAAC,IAAI,CACxC,CAAC,CAAC,IAAI,EAAE,KAAK,CAAC,EAAE,EAAE,CAAC,2BAA2B,CAAC,GAAG,CAAC,IAAI,CAAC,WAAW,EAAE,CAAC,IAAI,KAAK,CAAC,IAAI,EAAE,CAAC,MAAM,GAAG,CAAC,CACjG,CAAC;AAAA,CACF;AAED,MAAM,UAAU,oBAAoB,CAAC,IAAiB,EAAW;IAChE,OAAO,OAAO,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,EAAE,CAAC,IAAI,wBAAwB,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;AAAA,CAC9E","sourcesContent":["export interface RequestAuth {\n\tapiKey?: string;\n\theaders?: Record<string, string>;\n}\n\nconst AUTHENTICATION_HEADER_NAMES = new Set([\"authorization\", \"api-key\", \"x-api-key\"]);\n\nexport function hasAuthenticationHeaders(headers: Record<string, string> | undefined): boolean {\n\treturn Object.entries(headers ?? {}).some(\n\t\t([name, value]) => AUTHENTICATION_HEADER_NAMES.has(name.toLowerCase()) && value.trim().length > 0,\n\t);\n}\n\nexport function hasUsableRequestAuth(auth: RequestAuth): boolean {\n\treturn Boolean(auth.apiKey?.trim()) || hasAuthenticationHeaders(auth.headers);\n}\n"]}
1
+ {"version":3,"file":"request-auth.js","sourceRoot":"","sources":["../../src/core/request-auth.ts"],"names":[],"mappings":"AAKA,MAAM,2BAA2B,GAAG,IAAI,GAAG,CAAC,CAAC,eAAe,EAAE,SAAS,EAAE,WAAW,CAAC,CAAC,CAAC;AAEvF,MAAM,UAAU,wBAAwB,CAAC,OAA2C;IACnF,OAAO,MAAM,CAAC,OAAO,CAAC,OAAO,IAAI,EAAE,CAAC,CAAC,IAAI,CACxC,CAAC,CAAC,IAAI,EAAE,KAAK,CAAC,EAAE,EAAE,CAAC,2BAA2B,CAAC,GAAG,CAAC,IAAI,CAAC,WAAW,EAAE,CAAC,IAAI,KAAK,CAAC,IAAI,EAAE,CAAC,MAAM,GAAG,CAAC,CACjG,CAAC;AACH,CAAC;AAED,MAAM,UAAU,oBAAoB,CAAC,IAAiB;IACrD,OAAO,OAAO,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,EAAE,CAAC,IAAI,wBAAwB,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;AAC/E,CAAC","sourcesContent":["export interface RequestAuth {\n\tapiKey?: string;\n\theaders?: Record<string, string>;\n}\n\nconst AUTHENTICATION_HEADER_NAMES = new Set([\"authorization\", \"api-key\", \"x-api-key\"]);\n\nexport function hasAuthenticationHeaders(headers: Record<string, string> | undefined): boolean {\n\treturn Object.entries(headers ?? {}).some(\n\t\t([name, value]) => AUTHENTICATION_HEADER_NAMES.has(name.toLowerCase()) && value.trim().length > 0,\n\t);\n}\n\nexport function hasUsableRequestAuth(auth: RequestAuth): boolean {\n\treturn Boolean(auth.apiKey?.trim()) || hasAuthenticationHeaders(auth.headers);\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"automata-provider.d.ts","sourceRoot":"","sources":["../../../src/core/research/automata-provider.ts"],"names":[],"mappings":"AAEA,wBAAgB,mBAAmB,CAAC,IAAI,EAAE;IAAE,cAAc,CAAC,EAAE,MAAM,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,CAAA;CAAE,GAAG,OAAO,CAW/F","sourcesContent":["import fs from \"node:fs\";\n\nexport function isAutomataAvailable(args: { executablePath?: string; dbPath?: string }): boolean {\n\tif (!args.executablePath || !args.dbPath) {\n\t\treturn false;\n\t}\n\ttry {\n\t\tconst execExists = fs.existsSync(args.executablePath);\n\t\tconst dbExists = fs.existsSync(args.dbPath);\n\t\treturn execExists && dbExists;\n\t} catch {\n\t\treturn false;\n\t}\n}\n"]}
1
+ {"version":3,"file":"automata-provider.d.ts","sourceRoot":"","sources":["../../../src/core/research/automata-provider.ts"],"names":[],"mappings":"AAEA,wBAAgB,mBAAmB,CAAC,IAAI,EAAE;IAAE,cAAc,CAAC,EAAE,MAAM,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,CAAA;CAAE,GAAG,OAAO,CAW/F"}
@@ -1 +1 @@
1
- {"version":3,"file":"automata-provider.js","sourceRoot":"","sources":["../../../src/core/research/automata-provider.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,SAAS,CAAC;AAEzB,MAAM,UAAU,mBAAmB,CAAC,IAAkD,EAAW;IAChG,IAAI,CAAC,IAAI,CAAC,cAAc,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC;QAC1C,OAAO,KAAK,CAAC;IACd,CAAC;IACD,IAAI,CAAC;QACJ,MAAM,UAAU,GAAG,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC;QACtD,MAAM,QAAQ,GAAG,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QAC5C,OAAO,UAAU,IAAI,QAAQ,CAAC;IAC/B,CAAC;IAAC,MAAM,CAAC;QACR,OAAO,KAAK,CAAC;IACd,CAAC;AAAA,CACD","sourcesContent":["import fs from \"node:fs\";\n\nexport function isAutomataAvailable(args: { executablePath?: string; dbPath?: string }): boolean {\n\tif (!args.executablePath || !args.dbPath) {\n\t\treturn false;\n\t}\n\ttry {\n\t\tconst execExists = fs.existsSync(args.executablePath);\n\t\tconst dbExists = fs.existsSync(args.dbPath);\n\t\treturn execExists && dbExists;\n\t} catch {\n\t\treturn false;\n\t}\n}\n"]}
1
+ {"version":3,"file":"automata-provider.js","sourceRoot":"","sources":["../../../src/core/research/automata-provider.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,SAAS,CAAC;AAEzB,MAAM,UAAU,mBAAmB,CAAC,IAAkD;IACrF,IAAI,CAAC,IAAI,CAAC,cAAc,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC;QAC1C,OAAO,KAAK,CAAC;IACd,CAAC;IACD,IAAI,CAAC;QACJ,MAAM,UAAU,GAAG,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC;QACtD,MAAM,QAAQ,GAAG,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QAC5C,OAAO,UAAU,IAAI,QAAQ,CAAC;IAC/B,CAAC;IAAC,MAAM,CAAC;QACR,OAAO,KAAK,CAAC;IACd,CAAC;AACF,CAAC","sourcesContent":["import fs from \"node:fs\";\n\nexport function isAutomataAvailable(args: { executablePath?: string; dbPath?: string }): boolean {\n\tif (!args.executablePath || !args.dbPath) {\n\t\treturn false;\n\t}\n\ttry {\n\t\tconst execExists = fs.existsSync(args.executablePath);\n\t\tconst dbExists = fs.existsSync(args.dbPath);\n\t\treturn execExists && dbExists;\n\t} catch {\n\t\treturn false;\n\t}\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"evidence-bundle.d.ts","sourceRoot":"","sources":["../../../src/core/research/evidence-bundle.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACX,cAAc,EACd,WAAW,EAEX,OAAO,EAGP,MAAM,0BAA0B,CAAC;AAGlC,gFAAgF;AAChF,eAAO,MAAM,wBAAwB,OAAQ,CAAC;AAC9C,eAAO,MAAM,6BAA6B,MAAM,CAAC;AACjD,eAAO,MAAM,oBAAoB,KAAK,CAAC;AACvC,eAAO,MAAM,qBAAqB,KAAK,CAAC;AACxC,eAAO,MAAM,4BAA4B,MAAM,CAAC;AAChD,eAAO,MAAM,6BAA6B,MAAM,CAAC;AACjD,eAAO,MAAM,uBAAuB,OAAQ,CAAC;AAC7C,eAAO,MAAM,0BAA0B,OAAQ,CAAC;AAChD,eAAO,MAAM,4BAA4B,KAAK,CAAC;AAC/C,eAAO,MAAM,2BAA2B,IAAI,CAAC;AAC7C,eAAO,MAAM,6BAA6B,KAAK,CAAC;AAChD,eAAO,MAAM,iCAAiC,KAAK,CAAC;AACpD,eAAO,MAAM,+BAA+B,MAAM,CAAC;AACnD,eAAO,MAAM,kCAAkC,OAAQ,CAAC;AA4FxD;;;GAGG;AACH,wBAAgB,iCAAiC,CAAC,KAAK,EAAE,OAAO,GAAG,cAAc,CA6EhF;AA8BD,wBAAgB,oBAAoB,CAAC,IAAI,EAAE;IAC1C,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,EAAE,SAAS,WAAW,EAAE,CAAC;IAChC,QAAQ,EAAE,SAAS,OAAO,EAAE,CAAC;IAC7B,GAAG,CAAC,EAAE,MAAM,CAAC;CACb,GAAG,cAAc,CAOjB;AAED,wBAAgB,6BAA6B,CAAC,MAAM,EAAE,cAAc,GAAG,cAAc,CAEpF;AAED,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,cAAc,CAOxE","sourcesContent":["import type {\n\tEvidenceBundle,\n\tEvidenceRef,\n\tEvidenceSourceKind,\n\tFinding,\n\tJsonObject,\n\tJsonValue,\n} from \"../autonomy/contracts.ts\";\nimport { isPlainRecord } from \"../util/value-guards.ts\";\n\n/** Bounds every durable evidence bundle, including worker-authored evidence. */\nexport const MAX_EVIDENCE_QUERY_CHARS = 4_096;\nexport const MAX_EVIDENCE_CREATED_AT_CHARS = 128;\nexport const MAX_EVIDENCE_SOURCES = 64;\nexport const MAX_EVIDENCE_FINDINGS = 64;\nexport const MAX_EVIDENCE_SOURCE_ID_CHARS = 256;\nexport const MAX_EVIDENCE_FINDING_ID_CHARS = 256;\nexport const MAX_EVIDENCE_TEXT_CHARS = 8_000;\nexport const MAX_EVIDENCE_EXCERPT_CHARS = 8_000;\nexport const MAX_EVIDENCE_IDS_PER_FINDING = 64;\nexport const MAX_EVIDENCE_METADATA_DEPTH = 8;\nexport const MAX_EVIDENCE_METADATA_ENTRIES = 64;\nexport const MAX_EVIDENCE_METADATA_ARRAY_ITEMS = 64;\nexport const MAX_EVIDENCE_METADATA_KEY_CHARS = 256;\nexport const MAX_EVIDENCE_METADATA_STRING_CHARS = 4_096;\n\nfunction invalidEvidence(message: string): never {\n\tthrow new Error(`Invalid evidence bundle: ${message}`);\n}\n\n/**\n * Reads only own data properties. This is deliberately not Object.entries()/spread: snapshots\n * and external lane reports are untrusted, and a getter must never execute while validating them.\n */\nfunction ownDataRecord(value: unknown, label: string): Record<string, unknown> {\n\tif (!isPlainRecord(value)) invalidEvidence(`${label} must be a plain object.`);\n\tconst descriptors = Object.getOwnPropertyDescriptors(value);\n\tconst record: Record<string, unknown> = Object.create(null) as Record<string, unknown>;\n\tfor (const [key, descriptor] of Object.entries(descriptors)) {\n\t\tif (!(\"value\" in descriptor)) invalidEvidence(`${label}.${key} must not be an accessor.`);\n\t\trecord[key] = descriptor.value;\n\t}\n\treturn record;\n}\n\nfunction requiredBoundedString(value: unknown, label: string, maximumChars: number): string {\n\tif (typeof value !== \"string\" || value.length === 0) invalidEvidence(`${label} must be a non-empty string.`);\n\tif (value.length > maximumChars) invalidEvidence(`${label} exceeds ${maximumChars} characters.`);\n\treturn value;\n}\n\nfunction optionalBoundedString(value: unknown, label: string, maximumChars: number): string | undefined {\n\tif (value === undefined) return undefined;\n\treturn requiredBoundedString(value, label, maximumChars);\n}\n\nfunction boundedArray(value: unknown, label: string, maximumItems: number): readonly unknown[] {\n\tif (!Array.isArray(value)) invalidEvidence(`${label} must be an array.`);\n\tif (value.length > maximumItems) invalidEvidence(`${label} exceeds ${maximumItems} entries.`);\n\treturn value;\n}\n\nfunction ownArrayValue(array: readonly unknown[], index: number, label: string): unknown {\n\tconst descriptor = Object.getOwnPropertyDescriptor(array, String(index));\n\tif (!descriptor || !(\"value\" in descriptor)) invalidEvidence(`${label}[${index}] must be a data value.`);\n\treturn descriptor.value;\n}\n\nfunction normalizeJsonValue(value: unknown, label: string, depth: number): JsonValue {\n\tif (value === null || typeof value === \"boolean\") return value;\n\tif (typeof value === \"string\") {\n\t\tif (value.length > MAX_EVIDENCE_METADATA_STRING_CHARS) {\n\t\t\tinvalidEvidence(`${label} exceeds ${MAX_EVIDENCE_METADATA_STRING_CHARS} characters.`);\n\t\t}\n\t\treturn value;\n\t}\n\tif (typeof value === \"number\") {\n\t\tif (!Number.isFinite(value)) invalidEvidence(`${label} must be finite.`);\n\t\treturn value;\n\t}\n\tif (depth >= MAX_EVIDENCE_METADATA_DEPTH) {\n\t\tinvalidEvidence(`${label} exceeds metadata depth ${MAX_EVIDENCE_METADATA_DEPTH}.`);\n\t}\n\tif (Array.isArray(value)) {\n\t\tif (value.length > MAX_EVIDENCE_METADATA_ARRAY_ITEMS) {\n\t\t\tinvalidEvidence(`${label} exceeds ${MAX_EVIDENCE_METADATA_ARRAY_ITEMS} entries.`);\n\t\t}\n\t\tconst copied: JsonValue[] = [];\n\t\tfor (let index = 0; index < value.length; index++) {\n\t\t\tcopied.push(normalizeJsonValue(ownArrayValue(value, index, label), `${label}[${index}]`, depth + 1));\n\t\t}\n\t\treturn copied;\n\t}\n\tconst record = ownDataRecord(value, label);\n\tconst entries = Object.entries(record);\n\tif (entries.length > MAX_EVIDENCE_METADATA_ENTRIES) {\n\t\tinvalidEvidence(`${label} exceeds ${MAX_EVIDENCE_METADATA_ENTRIES} entries.`);\n\t}\n\tconst copied: JsonObject = {};\n\tfor (const [key, nested] of entries) {\n\t\tif (key.length > MAX_EVIDENCE_METADATA_KEY_CHARS) {\n\t\t\tinvalidEvidence(`${label} contains a key exceeding ${MAX_EVIDENCE_METADATA_KEY_CHARS} characters.`);\n\t\t}\n\t\tcopied[key] = normalizeJsonValue(nested, `${label}.${key}`, depth + 1);\n\t}\n\treturn copied;\n}\n\nfunction normalizeMetadata(value: unknown, label: string): JsonObject {\n\tconst normalized = normalizeJsonValue(value, label, 0);\n\tif (Array.isArray(normalized) || normalized === null || typeof normalized !== \"object\") {\n\t\tinvalidEvidence(`${label} must be an object.`);\n\t}\n\treturn normalized;\n}\n\n/**\n * Validates and copies an evidence bundle without invoking accessors or preserving unbounded\n * foreign object graphs. This is the sole boundary used for durable worker-claim evidence.\n */\nexport function normalizeEvidenceBundleForStorage(value: unknown): EvidenceBundle {\n\tconst bundle = ownDataRecord(value, \"bundle\");\n\tconst query = requiredBoundedString(bundle.query, \"bundle.query\", MAX_EVIDENCE_QUERY_CHARS);\n\tconst createdAt = optionalBoundedString(bundle.createdAt, \"bundle.createdAt\", MAX_EVIDENCE_CREATED_AT_CHARS);\n\tconst sourceValues = boundedArray(bundle.sources, \"bundle.sources\", MAX_EVIDENCE_SOURCES);\n\tconst findingValues = boundedArray(bundle.findings, \"bundle.findings\", MAX_EVIDENCE_FINDINGS);\n\tconst sources: EvidenceRef[] = [];\n\tfor (let index = 0; index < sourceValues.length; index++) {\n\t\tconst source = ownDataRecord(ownArrayValue(sourceValues, index, \"bundle.sources\"), `bundle.sources[${index}]`);\n\t\tconst sourceKind = source.kind;\n\t\tif (\n\t\t\ttypeof sourceKind !== \"string\" ||\n\t\t\t![\"workspace\", \"transcript\", \"automata\", \"web\", \"user\", \"tool\"].includes(sourceKind)\n\t\t) {\n\t\t\tinvalidEvidence(`bundle.sources[${index}].kind is invalid.`);\n\t\t}\n\t\tconst kind = sourceKind as EvidenceSourceKind;\n\t\tif (typeof source.trusted !== \"boolean\") invalidEvidence(`bundle.sources[${index}].trusted must be boolean.`);\n\t\tsources.push({\n\t\t\tid: requiredBoundedString(source.id, `bundle.sources[${index}].id`, MAX_EVIDENCE_SOURCE_ID_CHARS),\n\t\t\tkind,\n\t\t\ttrusted: source.trusted,\n\t\t\t...(source.title !== undefined\n\t\t\t\t? { title: optionalBoundedString(source.title, `bundle.sources[${index}].title`, MAX_EVIDENCE_TEXT_CHARS) }\n\t\t\t\t: {}),\n\t\t\t...(source.uri !== undefined\n\t\t\t\t? { uri: optionalBoundedString(source.uri, `bundle.sources[${index}].uri`, MAX_EVIDENCE_TEXT_CHARS) }\n\t\t\t\t: {}),\n\t\t\t...(source.excerpt !== undefined\n\t\t\t\t? {\n\t\t\t\t\t\texcerpt: optionalBoundedString(\n\t\t\t\t\t\t\tsource.excerpt,\n\t\t\t\t\t\t\t`bundle.sources[${index}].excerpt`,\n\t\t\t\t\t\t\tMAX_EVIDENCE_EXCERPT_CHARS,\n\t\t\t\t\t\t),\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t\t...(source.metadata !== undefined\n\t\t\t\t? { metadata: normalizeMetadata(source.metadata, `bundle.sources[${index}].metadata`) }\n\t\t\t\t: {}),\n\t\t});\n\t}\n\tconst findings: Finding[] = [];\n\tfor (let index = 0; index < findingValues.length; index++) {\n\t\tconst finding = ownDataRecord(\n\t\t\townArrayValue(findingValues, index, \"bundle.findings\"),\n\t\t\t`bundle.findings[${index}]`,\n\t\t);\n\t\tconst evidenceIdValues = boundedArray(\n\t\t\tfinding.evidenceIds,\n\t\t\t`bundle.findings[${index}].evidenceIds`,\n\t\t\tMAX_EVIDENCE_IDS_PER_FINDING,\n\t\t);\n\t\tconst evidenceIds: string[] = [];\n\t\tfor (let evidenceIndex = 0; evidenceIndex < evidenceIdValues.length; evidenceIndex++) {\n\t\t\tevidenceIds.push(\n\t\t\t\trequiredBoundedString(\n\t\t\t\t\townArrayValue(evidenceIdValues, evidenceIndex, `bundle.findings[${index}].evidenceIds`),\n\t\t\t\t\t`bundle.findings[${index}].evidenceIds[${evidenceIndex}]`,\n\t\t\t\t\tMAX_EVIDENCE_SOURCE_ID_CHARS,\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t\tif (\n\t\t\tfinding.confidence !== undefined &&\n\t\t\t(typeof finding.confidence !== \"number\" || !Number.isFinite(finding.confidence))\n\t\t) {\n\t\t\tinvalidEvidence(`bundle.findings[${index}].confidence must be finite.`);\n\t\t}\n\t\tfindings.push({\n\t\t\tid: requiredBoundedString(finding.id, `bundle.findings[${index}].id`, MAX_EVIDENCE_FINDING_ID_CHARS),\n\t\t\tsummary: requiredBoundedString(finding.summary, `bundle.findings[${index}].summary`, MAX_EVIDENCE_TEXT_CHARS),\n\t\t\tevidenceIds,\n\t\t\t...(finding.confidence !== undefined ? { confidence: finding.confidence } : {}),\n\t\t});\n\t}\n\treturn { query, sources, findings, ...(createdAt !== undefined ? { createdAt } : {}) };\n}\n\nfunction cloneJsonValue(value: JsonValue): JsonValue {\n\tif (Array.isArray(value)) {\n\t\treturn value.map(cloneJsonValue);\n\t}\n\tif (value !== null && typeof value === \"object\") {\n\t\treturn Object.fromEntries(Object.entries(value).map(([key, nested]) => [key, cloneJsonValue(nested)]));\n\t}\n\treturn value;\n}\n\nfunction cloneJsonObject(value: JsonObject): JsonObject {\n\treturn Object.fromEntries(Object.entries(value).map(([key, nested]) => [key, cloneJsonValue(nested)]));\n}\n\nfunction cloneEvidenceRef(source: EvidenceRef): EvidenceRef {\n\treturn {\n\t\t...source,\n\t\tmetadata: source.metadata ? cloneJsonObject(source.metadata) : undefined,\n\t};\n}\n\nfunction cloneFinding(finding: Finding): Finding {\n\treturn {\n\t\t...finding,\n\t\tevidenceIds: [...finding.evidenceIds],\n\t};\n}\n\nexport function createEvidenceBundle(args: {\n\tquery: string;\n\tsources: readonly EvidenceRef[];\n\tfindings: readonly Finding[];\n\tnow?: string;\n}): EvidenceBundle {\n\treturn {\n\t\tquery: args.query,\n\t\tsources: args.sources.map(cloneEvidenceRef),\n\t\tfindings: args.findings.map(cloneFinding),\n\t\tcreatedAt: args.now,\n\t};\n}\n\nexport function cloneEvidenceBundleForStorage(bundle: EvidenceBundle): EvidenceBundle {\n\treturn normalizeEvidenceBundleForStorage(bundle);\n}\n\nexport function isEvidenceBundle(value: unknown): value is EvidenceBundle {\n\ttry {\n\t\tnormalizeEvidenceBundleForStorage(value);\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n"]}
1
+ {"version":3,"file":"evidence-bundle.d.ts","sourceRoot":"","sources":["../../../src/core/research/evidence-bundle.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACX,cAAc,EACd,WAAW,EAEX,OAAO,EAGP,MAAM,0BAA0B,CAAC;AAGlC,gFAAgF;AAChF,eAAO,MAAM,wBAAwB,OAAQ,CAAC;AAC9C,eAAO,MAAM,6BAA6B,MAAM,CAAC;AACjD,eAAO,MAAM,oBAAoB,KAAK,CAAC;AACvC,eAAO,MAAM,qBAAqB,KAAK,CAAC;AACxC,eAAO,MAAM,4BAA4B,MAAM,CAAC;AAChD,eAAO,MAAM,6BAA6B,MAAM,CAAC;AACjD,eAAO,MAAM,uBAAuB,OAAQ,CAAC;AAC7C,eAAO,MAAM,0BAA0B,OAAQ,CAAC;AAChD,eAAO,MAAM,4BAA4B,KAAK,CAAC;AAC/C,eAAO,MAAM,2BAA2B,IAAI,CAAC;AAC7C,eAAO,MAAM,6BAA6B,KAAK,CAAC;AAChD,eAAO,MAAM,iCAAiC,KAAK,CAAC;AACpD,eAAO,MAAM,+BAA+B,MAAM,CAAC;AACnD,eAAO,MAAM,kCAAkC,OAAQ,CAAC;AA4FxD;;;GAGG;AACH,wBAAgB,iCAAiC,CAAC,KAAK,EAAE,OAAO,GAAG,cAAc,CA6EhF;AA8BD,wBAAgB,oBAAoB,CAAC,IAAI,EAAE;IAC1C,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,EAAE,SAAS,WAAW,EAAE,CAAC;IAChC,QAAQ,EAAE,SAAS,OAAO,EAAE,CAAC;IAC7B,GAAG,CAAC,EAAE,MAAM,CAAC;CACb,GAAG,cAAc,CAOjB;AAED,wBAAgB,6BAA6B,CAAC,MAAM,EAAE,cAAc,GAAG,cAAc,CAEpF;AAED,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,cAAc,CAOxE"}