@caupulican/pi-adaptative 0.94.0 → 0.95.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (371) hide show
  1. package/CHANGELOG.md +55 -0
  2. package/dist/bundled-resources/extensions/tmux-agent-manager/README.md +32 -13
  3. package/dist/bundled-resources/extensions/tmux-agent-manager/index.d.ts +7 -4
  4. package/dist/bundled-resources/extensions/tmux-agent-manager/index.d.ts.map +1 -1
  5. package/dist/bundled-resources/extensions/tmux-agent-manager/index.js +173 -293
  6. package/dist/bundled-resources/extensions/tmux-agent-manager/index.js.map +1 -1
  7. package/dist/bundled-resources/extensions/tmux-agent-manager/index.ts +247 -392
  8. package/dist/bundled-resources/extensions/tmux-agent-manager/launch-profile.d.ts +52 -0
  9. package/dist/bundled-resources/extensions/tmux-agent-manager/launch-profile.d.ts.map +1 -0
  10. package/dist/bundled-resources/extensions/tmux-agent-manager/launch-profile.js +118 -0
  11. package/dist/bundled-resources/extensions/tmux-agent-manager/launch-profile.js.map +1 -0
  12. package/dist/bundled-resources/extensions/tmux-agent-manager/launch-profile.ts +169 -0
  13. package/dist/bundled-resources/extensions/tmux-agent-manager/templates/builder-validator.json +1 -1
  14. package/dist/bundled-resources/extensions/tmux-agent-manager/templates/provider-prompt-smoke.json +1 -1
  15. package/dist/bundled-resources/skills/pi-harness-learning/SKILL.md +13 -7
  16. package/dist/bundled-resources/skills/worker-profile-writer/SKILL.md +11 -11
  17. package/dist/core/agent-paths.d.ts +2 -0
  18. package/dist/core/agent-paths.d.ts.map +1 -1
  19. package/dist/core/agent-paths.js +7 -0
  20. package/dist/core/agent-paths.js.map +1 -1
  21. package/dist/core/agent-session.d.ts +11 -41
  22. package/dist/core/agent-session.d.ts.map +1 -1
  23. package/dist/core/agent-session.js +98 -161
  24. package/dist/core/agent-session.js.map +1 -1
  25. package/dist/core/autonomy/envelope-enforcement.d.ts +6 -1
  26. package/dist/core/autonomy/envelope-enforcement.d.ts.map +1 -1
  27. package/dist/core/autonomy/envelope-enforcement.js +26 -25
  28. package/dist/core/autonomy/envelope-enforcement.js.map +1 -1
  29. package/dist/core/autonomy/lane-private-paths.d.ts.map +1 -1
  30. package/dist/core/autonomy/lane-private-paths.js +2 -1
  31. package/dist/core/autonomy/lane-private-paths.js.map +1 -1
  32. package/dist/core/autonomy/lane-tool-surface.d.ts +8 -8
  33. package/dist/core/autonomy/lane-tool-surface.d.ts.map +1 -1
  34. package/dist/core/autonomy/lane-tool-surface.js +45 -30
  35. package/dist/core/autonomy/lane-tool-surface.js.map +1 -1
  36. package/dist/core/autonomy/worker-session-private-scope.d.ts +12 -0
  37. package/dist/core/autonomy/worker-session-private-scope.d.ts.map +1 -0
  38. package/dist/core/autonomy/worker-session-private-scope.js +42 -0
  39. package/dist/core/autonomy/worker-session-private-scope.js.map +1 -0
  40. package/dist/core/autonomy/worker-tool-adapter-registry.d.ts +65 -0
  41. package/dist/core/autonomy/worker-tool-adapter-registry.d.ts.map +1 -0
  42. package/dist/core/autonomy/worker-tool-adapter-registry.js +145 -0
  43. package/dist/core/autonomy/worker-tool-adapter-registry.js.map +1 -0
  44. package/dist/core/background-lane-controller.d.ts +9 -1
  45. package/dist/core/background-lane-controller.d.ts.map +1 -1
  46. package/dist/core/background-lane-controller.js +76 -6
  47. package/dist/core/background-lane-controller.js.map +1 -1
  48. package/dist/core/background-tool-task-controller.d.ts +23 -2
  49. package/dist/core/background-tool-task-controller.d.ts.map +1 -1
  50. package/dist/core/background-tool-task-controller.js +132 -17
  51. package/dist/core/background-tool-task-controller.js.map +1 -1
  52. package/dist/core/context/long-term-memory-trigger.d.ts +3 -1
  53. package/dist/core/context/long-term-memory-trigger.d.ts.map +1 -1
  54. package/dist/core/context/long-term-memory-trigger.js +1 -1
  55. package/dist/core/context/long-term-memory-trigger.js.map +1 -1
  56. package/dist/core/context/okf-memory-provider.d.ts +3 -0
  57. package/dist/core/context/okf-memory-provider.d.ts.map +1 -1
  58. package/dist/core/context/okf-memory-provider.js +66 -31
  59. package/dist/core/context/okf-memory-provider.js.map +1 -1
  60. package/dist/core/context/okf-memory.d.ts +18 -1
  61. package/dist/core/context/okf-memory.d.ts.map +1 -1
  62. package/dist/core/context/okf-memory.js +48 -0
  63. package/dist/core/context/okf-memory.js.map +1 -1
  64. package/dist/core/cost-guard-controller.d.ts +37 -0
  65. package/dist/core/cost-guard-controller.d.ts.map +1 -0
  66. package/dist/core/cost-guard-controller.js +71 -0
  67. package/dist/core/cost-guard-controller.js.map +1 -0
  68. package/dist/core/cost-guard.d.ts +9 -4
  69. package/dist/core/cost-guard.d.ts.map +1 -1
  70. package/dist/core/cost-guard.js +7 -3
  71. package/dist/core/cost-guard.js.map +1 -1
  72. package/dist/core/delegation/worker-agent-control.d.ts +4 -0
  73. package/dist/core/delegation/worker-agent-control.d.ts.map +1 -1
  74. package/dist/core/delegation/worker-agent-control.js.map +1 -1
  75. package/dist/core/delegation/worker-attempt-executor.d.ts +1 -1
  76. package/dist/core/delegation/worker-attempt-executor.d.ts.map +1 -1
  77. package/dist/core/delegation/worker-attempt-executor.js +0 -1
  78. package/dist/core/delegation/worker-attempt-executor.js.map +1 -1
  79. package/dist/core/delegation/worker-authority-resolver.d.ts +16 -3
  80. package/dist/core/delegation/worker-authority-resolver.d.ts.map +1 -1
  81. package/dist/core/delegation/worker-authority-resolver.js +114 -55
  82. package/dist/core/delegation/worker-authority-resolver.js.map +1 -1
  83. package/dist/core/delegation/worker-claim.d.ts +1 -2
  84. package/dist/core/delegation/worker-claim.d.ts.map +1 -1
  85. package/dist/core/delegation/worker-claim.js.map +1 -1
  86. package/dist/core/delegation/worker-delegation-controller.d.ts +19 -6
  87. package/dist/core/delegation/worker-delegation-controller.d.ts.map +1 -1
  88. package/dist/core/delegation/worker-delegation-controller.js +125 -40
  89. package/dist/core/delegation/worker-delegation-controller.js.map +1 -1
  90. package/dist/core/delegation/worker-delegation-request.d.ts +3 -3
  91. package/dist/core/delegation/worker-delegation-request.d.ts.map +1 -1
  92. package/dist/core/delegation/worker-delegation-request.js +13 -19
  93. package/dist/core/delegation/worker-delegation-request.js.map +1 -1
  94. package/dist/core/delegation/worker-execution-policy.d.ts +3 -2
  95. package/dist/core/delegation/worker-execution-policy.d.ts.map +1 -1
  96. package/dist/core/delegation/worker-execution-policy.js +54 -39
  97. package/dist/core/delegation/worker-execution-policy.js.map +1 -1
  98. package/dist/core/delegation/worker-fleet-limits.d.ts +3 -3
  99. package/dist/core/delegation/worker-fleet-limits.d.ts.map +1 -1
  100. package/dist/core/delegation/worker-fleet-limits.js +7 -7
  101. package/dist/core/delegation/worker-fleet-limits.js.map +1 -1
  102. package/dist/core/delegation/worker-machine-scope.d.ts +12 -0
  103. package/dist/core/delegation/worker-machine-scope.d.ts.map +1 -0
  104. package/dist/core/delegation/worker-machine-scope.js +38 -0
  105. package/dist/core/delegation/worker-machine-scope.js.map +1 -0
  106. package/dist/core/delegation/worker-notification-coordinator.d.ts +10 -0
  107. package/dist/core/delegation/worker-notification-coordinator.d.ts.map +1 -1
  108. package/dist/core/delegation/worker-notification-coordinator.js +69 -3
  109. package/dist/core/delegation/worker-notification-coordinator.js.map +1 -1
  110. package/dist/core/delegation/worker-recovery-coordinator.d.ts.map +1 -1
  111. package/dist/core/delegation/worker-recovery-coordinator.js +6 -1
  112. package/dist/core/delegation/worker-recovery-coordinator.js.map +1 -1
  113. package/dist/core/delegation/worker-runner.d.ts +5 -7
  114. package/dist/core/delegation/worker-runner.d.ts.map +1 -1
  115. package/dist/core/delegation/worker-runner.js +1 -4
  116. package/dist/core/delegation/worker-runner.js.map +1 -1
  117. package/dist/core/delegation/worker-write-reservation-coordinator.d.ts +3 -2
  118. package/dist/core/delegation/worker-write-reservation-coordinator.d.ts.map +1 -1
  119. package/dist/core/delegation/worker-write-reservation-coordinator.js +50 -25
  120. package/dist/core/delegation/worker-write-reservation-coordinator.js.map +1 -1
  121. package/dist/core/durable-custom-message-turn-controller.d.ts +6 -0
  122. package/dist/core/durable-custom-message-turn-controller.d.ts.map +1 -1
  123. package/dist/core/durable-custom-message-turn-controller.js +38 -15
  124. package/dist/core/durable-custom-message-turn-controller.js.map +1 -1
  125. package/dist/core/extension-binding-controller.d.ts +5 -1
  126. package/dist/core/extension-binding-controller.d.ts.map +1 -1
  127. package/dist/core/extension-binding-controller.js +15 -0
  128. package/dist/core/extension-binding-controller.js.map +1 -1
  129. package/dist/core/extensions/factory-runtime.d.ts.map +1 -1
  130. package/dist/core/extensions/factory-runtime.js +5 -0
  131. package/dist/core/extensions/factory-runtime.js.map +1 -1
  132. package/dist/core/extensions/runner.d.ts.map +1 -1
  133. package/dist/core/extensions/runner.js +1 -0
  134. package/dist/core/extensions/runner.js.map +1 -1
  135. package/dist/core/extensions/types.d.ts +8 -4
  136. package/dist/core/extensions/types.d.ts.map +1 -1
  137. package/dist/core/extensions/types.js.map +1 -1
  138. package/dist/core/foreground-terminal-handoff-controller.d.ts +31 -0
  139. package/dist/core/foreground-terminal-handoff-controller.d.ts.map +1 -1
  140. package/dist/core/foreground-terminal-handoff-controller.js +239 -55
  141. package/dist/core/foreground-terminal-handoff-controller.js.map +1 -1
  142. package/dist/core/goals/goal-session-controller.d.ts +2 -0
  143. package/dist/core/goals/goal-session-controller.d.ts.map +1 -1
  144. package/dist/core/goals/goal-session-controller.js +8 -0
  145. package/dist/core/goals/goal-session-controller.js.map +1 -1
  146. package/dist/core/goals/goal-tool-core.d.ts +5 -4
  147. package/dist/core/goals/goal-tool-core.d.ts.map +1 -1
  148. package/dist/core/goals/goal-tool-core.js +23 -19
  149. package/dist/core/goals/goal-tool-core.js.map +1 -1
  150. package/dist/core/learning/auto-learn-settings.d.ts +84 -0
  151. package/dist/core/learning/auto-learn-settings.d.ts.map +1 -0
  152. package/dist/core/learning/auto-learn-settings.js +66 -0
  153. package/dist/core/learning/auto-learn-settings.js.map +1 -0
  154. package/dist/core/learning/learning-audit.d.ts +5 -1
  155. package/dist/core/learning/learning-audit.d.ts.map +1 -1
  156. package/dist/core/learning/learning-audit.js +32 -1
  157. package/dist/core/learning/learning-audit.js.map +1 -1
  158. package/dist/core/learning/reflection-engine.d.ts +24 -0
  159. package/dist/core/learning/reflection-engine.d.ts.map +1 -1
  160. package/dist/core/learning/reflection-engine.js +104 -8
  161. package/dist/core/learning/reflection-engine.js.map +1 -1
  162. package/dist/core/local-prefix-warm-controller.d.ts +24 -0
  163. package/dist/core/local-prefix-warm-controller.d.ts.map +1 -0
  164. package/dist/core/local-prefix-warm-controller.js +79 -0
  165. package/dist/core/local-prefix-warm-controller.js.map +1 -0
  166. package/dist/core/memory/okf-project-memory-store.d.ts +28 -0
  167. package/dist/core/memory/okf-project-memory-store.d.ts.map +1 -0
  168. package/dist/core/memory/okf-project-memory-store.js +111 -0
  169. package/dist/core/memory/okf-project-memory-store.js.map +1 -0
  170. package/dist/core/memory/providers/file-store.d.ts +44 -1
  171. package/dist/core/memory/providers/file-store.d.ts.map +1 -1
  172. package/dist/core/memory/providers/file-store.js +341 -24
  173. package/dist/core/memory/providers/file-store.js.map +1 -1
  174. package/dist/core/memory/worker-memory-tools.d.ts +5 -0
  175. package/dist/core/memory/worker-memory-tools.d.ts.map +1 -0
  176. package/dist/core/memory/worker-memory-tools.js +5 -0
  177. package/dist/core/memory/worker-memory-tools.js.map +1 -0
  178. package/dist/core/memory-controller.d.ts +10 -1
  179. package/dist/core/memory-controller.d.ts.map +1 -1
  180. package/dist/core/memory-controller.js +72 -8
  181. package/dist/core/memory-controller.js.map +1 -1
  182. package/dist/core/model-capability.d.ts +7 -0
  183. package/dist/core/model-capability.d.ts.map +1 -1
  184. package/dist/core/model-capability.js +12 -0
  185. package/dist/core/model-capability.js.map +1 -1
  186. package/dist/core/model-registry.d.ts.map +1 -1
  187. package/dist/core/model-registry.js +2 -10
  188. package/dist/core/model-registry.js.map +1 -1
  189. package/dist/core/model-router-controller.d.ts +3 -2
  190. package/dist/core/model-router-controller.d.ts.map +1 -1
  191. package/dist/core/model-router-controller.js +3 -2
  192. package/dist/core/model-router-controller.js.map +1 -1
  193. package/dist/core/orchestration/contracts.d.ts +16 -12
  194. package/dist/core/orchestration/contracts.d.ts.map +1 -1
  195. package/dist/core/orchestration/contracts.js +2 -2
  196. package/dist/core/orchestration/contracts.js.map +1 -1
  197. package/dist/core/orchestration/lane-tool-manifests.d.ts +2 -2
  198. package/dist/core/orchestration/lane-tool-manifests.d.ts.map +1 -1
  199. package/dist/core/orchestration/lane-tool-manifests.js +6 -1
  200. package/dist/core/orchestration/lane-tool-manifests.js.map +1 -1
  201. package/dist/core/orchestration/profile-registry.d.ts.map +1 -1
  202. package/dist/core/orchestration/profile-registry.js +14 -0
  203. package/dist/core/orchestration/profile-registry.js.map +1 -1
  204. package/dist/core/orchestration/task-profile-writer.d.ts +7 -4
  205. package/dist/core/orchestration/task-profile-writer.d.ts.map +1 -1
  206. package/dist/core/orchestration/task-profile-writer.js +71 -59
  207. package/dist/core/orchestration/task-profile-writer.js.map +1 -1
  208. package/dist/core/orchestration/thinking-level-schema.d.ts +7 -0
  209. package/dist/core/orchestration/thinking-level-schema.d.ts.map +1 -0
  210. package/dist/core/orchestration/thinking-level-schema.js +19 -0
  211. package/dist/core/orchestration/thinking-level-schema.js.map +1 -0
  212. package/dist/core/orchestration/worker-execution-contract.d.ts.map +1 -1
  213. package/dist/core/orchestration/worker-execution-contract.js +12 -5
  214. package/dist/core/orchestration/worker-execution-contract.js.map +1 -1
  215. package/dist/core/provider-prompt-contracts.d.ts +1 -4
  216. package/dist/core/provider-prompt-contracts.d.ts.map +1 -1
  217. package/dist/core/provider-prompt-contracts.js +13 -29
  218. package/dist/core/provider-prompt-contracts.js.map +1 -1
  219. package/dist/core/provider-request-context-controller.d.ts +2 -0
  220. package/dist/core/provider-request-context-controller.d.ts.map +1 -1
  221. package/dist/core/provider-request-context-controller.js +10 -3
  222. package/dist/core/provider-request-context-controller.js.map +1 -1
  223. package/dist/core/reflection-controller.d.ts +63 -27
  224. package/dist/core/reflection-controller.d.ts.map +1 -1
  225. package/dist/core/reflection-controller.js +300 -132
  226. package/dist/core/reflection-controller.js.map +1 -1
  227. package/dist/core/runtime-builder.d.ts +1 -0
  228. package/dist/core/runtime-builder.d.ts.map +1 -1
  229. package/dist/core/runtime-builder.js +25 -14
  230. package/dist/core/runtime-builder.js.map +1 -1
  231. package/dist/core/secrets/credential-exposure-guard.d.ts.map +1 -1
  232. package/dist/core/secrets/credential-exposure-guard.js +55 -10
  233. package/dist/core/secrets/credential-exposure-guard.js.map +1 -1
  234. package/dist/core/session-role.d.ts +6 -8
  235. package/dist/core/session-role.d.ts.map +1 -1
  236. package/dist/core/session-role.js +8 -18
  237. package/dist/core/session-role.js.map +1 -1
  238. package/dist/core/settings-manager.d.ts +13 -16
  239. package/dist/core/settings-manager.d.ts.map +1 -1
  240. package/dist/core/settings-manager.js +53 -50
  241. package/dist/core/settings-manager.js.map +1 -1
  242. package/dist/core/skill-vault.d.ts +15 -0
  243. package/dist/core/skill-vault.d.ts.map +1 -1
  244. package/dist/core/skill-vault.js +79 -45
  245. package/dist/core/skill-vault.js.map +1 -1
  246. package/dist/core/skills.d.ts +3 -0
  247. package/dist/core/skills.d.ts.map +1 -1
  248. package/dist/core/skills.js +6 -6
  249. package/dist/core/skills.js.map +1 -1
  250. package/dist/core/system-prompt-builder.d.ts +2 -0
  251. package/dist/core/system-prompt-builder.d.ts.map +1 -1
  252. package/dist/core/system-prompt-builder.js +52 -12
  253. package/dist/core/system-prompt-builder.js.map +1 -1
  254. package/dist/core/system-prompt.js +1 -1
  255. package/dist/core/system-prompt.js.map +1 -1
  256. package/dist/core/tool-capability-policy.d.ts +3 -0
  257. package/dist/core/tool-capability-policy.d.ts.map +1 -1
  258. package/dist/core/tool-capability-policy.js +13 -2
  259. package/dist/core/tool-capability-policy.js.map +1 -1
  260. package/dist/core/toolkit/script-runner.d.ts +2 -1
  261. package/dist/core/toolkit/script-runner.d.ts.map +1 -1
  262. package/dist/core/toolkit/script-runner.js +10 -2
  263. package/dist/core/toolkit/script-runner.js.map +1 -1
  264. package/dist/core/tools/delegate-status.d.ts +3 -1
  265. package/dist/core/tools/delegate-status.d.ts.map +1 -1
  266. package/dist/core/tools/delegate-status.js +5 -1
  267. package/dist/core/tools/delegate-status.js.map +1 -1
  268. package/dist/core/tools/delegate.d.ts +4 -13
  269. package/dist/core/tools/delegate.d.ts.map +1 -1
  270. package/dist/core/tools/delegate.js +173 -73
  271. package/dist/core/tools/delegate.js.map +1 -1
  272. package/dist/core/tools/goal.d.ts +3 -4
  273. package/dist/core/tools/goal.d.ts.map +1 -1
  274. package/dist/core/tools/goal.js +24 -7
  275. package/dist/core/tools/goal.js.map +1 -1
  276. package/dist/core/tools/profile-writer.d.ts +2 -8
  277. package/dist/core/tools/profile-writer.d.ts.map +1 -1
  278. package/dist/core/tools/profile-writer.js +6 -18
  279. package/dist/core/tools/profile-writer.js.map +1 -1
  280. package/dist/core/tools/run-toolkit-script.d.ts +1 -1
  281. package/dist/core/tools/run-toolkit-script.d.ts.map +1 -1
  282. package/dist/core/tools/run-toolkit-script.js +2 -2
  283. package/dist/core/tools/run-toolkit-script.js.map +1 -1
  284. package/dist/core/tools/skill-audit.d.ts +28 -1
  285. package/dist/core/tools/skill-audit.d.ts.map +1 -1
  286. package/dist/core/tools/skill-audit.js +56 -12
  287. package/dist/core/tools/skill-audit.js.map +1 -1
  288. package/dist/core/tools/skill.d.ts +12 -1
  289. package/dist/core/tools/skill.d.ts.map +1 -1
  290. package/dist/core/tools/skill.js +52 -0
  291. package/dist/core/tools/skill.js.map +1 -1
  292. package/dist/core/tools/skillify.d.ts.map +1 -1
  293. package/dist/core/tools/skillify.js +16 -7
  294. package/dist/core/tools/skillify.js.map +1 -1
  295. package/dist/core/tools/task-steps.js +1 -1
  296. package/dist/core/tools/task-steps.js.map +1 -1
  297. package/dist/core/tools/tmux-dispatch.d.ts +4 -16
  298. package/dist/core/tools/tmux-dispatch.d.ts.map +1 -1
  299. package/dist/core/tools/tmux-dispatch.js +5 -20
  300. package/dist/core/tools/tmux-dispatch.js.map +1 -1
  301. package/dist/core/tools/tool-task.d.ts +1 -0
  302. package/dist/core/tools/tool-task.d.ts.map +1 -1
  303. package/dist/core/tools/tool-task.js +13 -8
  304. package/dist/core/tools/tool-task.js.map +1 -1
  305. package/dist/core/util/atomic-file.d.ts +2 -0
  306. package/dist/core/util/atomic-file.d.ts.map +1 -1
  307. package/dist/core/util/atomic-file.js +4 -0
  308. package/dist/core/util/atomic-file.js.map +1 -1
  309. package/dist/core/worktree-sync/codes.d.ts +1 -2
  310. package/dist/core/worktree-sync/codes.d.ts.map +1 -1
  311. package/dist/core/worktree-sync/codes.js +1 -2
  312. package/dist/core/worktree-sync/codes.js.map +1 -1
  313. package/dist/core/worktree-sync/lane-gate.d.ts +4 -8
  314. package/dist/core/worktree-sync/lane-gate.d.ts.map +1 -1
  315. package/dist/core/worktree-sync/lane-gate.js +5 -51
  316. package/dist/core/worktree-sync/lane-gate.js.map +1 -1
  317. package/dist/index.d.ts +5 -0
  318. package/dist/index.d.ts.map +1 -1
  319. package/dist/index.js +7 -0
  320. package/dist/index.js.map +1 -1
  321. package/dist/modes/interactive/auto-learn-controller.d.ts +6 -7
  322. package/dist/modes/interactive/auto-learn-controller.d.ts.map +1 -1
  323. package/dist/modes/interactive/auto-learn-controller.js +32 -207
  324. package/dist/modes/interactive/auto-learn-controller.js.map +1 -1
  325. package/dist/modes/interactive/autonomy-commands.js +2 -2
  326. package/dist/modes/interactive/autonomy-commands.js.map +1 -1
  327. package/dist/modes/interactive/components/activity-lane.d.ts.map +1 -1
  328. package/dist/modes/interactive/components/activity-lane.js +12 -23
  329. package/dist/modes/interactive/components/activity-lane.js.map +1 -1
  330. package/dist/modes/interactive/components/custom-message.d.ts.map +1 -1
  331. package/dist/modes/interactive/components/custom-message.js +142 -1
  332. package/dist/modes/interactive/components/custom-message.js.map +1 -1
  333. package/dist/modes/interactive/components/fitness-role-selector.d.ts.map +1 -1
  334. package/dist/modes/interactive/components/fitness-role-selector.js +2 -2
  335. package/dist/modes/interactive/components/fitness-role-selector.js.map +1 -1
  336. package/dist/modes/interactive/components/footer.js +1 -1
  337. package/dist/modes/interactive/components/footer.js.map +1 -1
  338. package/dist/modes/interactive/components/settings-selector.d.ts +4 -0
  339. package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
  340. package/dist/modes/interactive/components/settings-selector.js +150 -73
  341. package/dist/modes/interactive/components/settings-selector.js.map +1 -1
  342. package/dist/modes/interactive/report-commands.d.ts.map +1 -1
  343. package/dist/modes/interactive/report-commands.js +8 -4
  344. package/dist/modes/interactive/report-commands.js.map +1 -1
  345. package/dist/modes/interactive/settings-selector-flow.d.ts.map +1 -1
  346. package/dist/modes/interactive/settings-selector-flow.js +10 -0
  347. package/dist/modes/interactive/settings-selector-flow.js.map +1 -1
  348. package/docs/extensions.md +8 -0
  349. package/docs/harness-architecture.md +28 -32
  350. package/docs/index.md +1 -1
  351. package/docs/process-matrix.md +8 -6
  352. package/docs/resources.md +1 -1
  353. package/docs/settings.md +61 -51
  354. package/docs/tmux-agent-manager.md +47 -40
  355. package/docs/usage.md +1 -1
  356. package/docs/worker-profiles.md +8 -6
  357. package/docs/worktree-sync.md +26 -20
  358. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  359. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  360. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  361. package/examples/extensions/sandbox/package-lock.json +2 -2
  362. package/examples/extensions/sandbox/package.json +1 -1
  363. package/examples/extensions/with-deps/package-lock.json +2 -2
  364. package/examples/extensions/with-deps/package.json +1 -1
  365. package/npm-shrinkwrap.json +12 -12
  366. package/package.json +4 -4
  367. package/dist/bundled-resources/extensions/tmux-agent-manager/dispatch-grant.d.ts +0 -133
  368. package/dist/bundled-resources/extensions/tmux-agent-manager/dispatch-grant.d.ts.map +0 -1
  369. package/dist/bundled-resources/extensions/tmux-agent-manager/dispatch-grant.js +0 -199
  370. package/dist/bundled-resources/extensions/tmux-agent-manager/dispatch-grant.js.map +0 -1
  371. package/dist/bundled-resources/extensions/tmux-agent-manager/dispatch-grant.ts +0 -312
@@ -1,12 +1,11 @@
1
- import { randomUUID } from "node:crypto";
1
+ import { createHash, randomUUID } from "node:crypto";
2
2
  import { basename } from "node:path";
3
3
  import { AgentBusyError } from "@caupulican/pi-agent-core/agent";
4
4
  import { compactToolResultDetailsForRetention } from "@caupulican/pi-agent-core/message-retention";
5
5
  import { createCustomMessage } from "@caupulican/pi-agent-core/messages";
6
- import { projectToolsForProvider } from "@caupulican/pi-agent-core/provider-tool-projection";
7
6
  import { DEFAULT_STREAM_IDLE, withStreamIdleWatchdog, } from "@caupulican/pi-agent-core/reliability";
8
7
  import { NATIVE_TOOL_PROTOCOL_RESIDUE_ERROR } from "@caupulican/pi-agent-core/tool-protocol-residue";
9
- import { getSupportedThinkingLevels, modelsAreEqual } from "@caupulican/pi-ai/models";
8
+ import { modelsAreEqual } from "@caupulican/pi-ai/models";
10
9
  import { cleanupSessionResources } from "@caupulican/pi-ai/session-resources";
11
10
  import { streamSimple } from "@caupulican/pi-ai/stream";
12
11
  import { getAgentDir } from "../config.js";
@@ -22,7 +21,7 @@ import { CompactionController } from "./compaction-controller.js";
22
21
  import { CompactionSupport } from "./compaction-support.js";
23
22
  import { buildContextCompositionReport, formatContextCompositionDashboard, } from "./context/context-composition.js";
24
23
  import { ContextPipeline } from "./context-pipeline.js";
25
- import { downgradeReasoning, estimateTurnCostUsd, evaluateCostGuard } from "./cost-guard.js";
24
+ import { CostGuardController } from "./cost-guard-controller.js";
26
25
  import { appendWorkerClaimSnapshot, getLatestWorkerClaimSnapshot, getWorkerClaimSnapshots, } from "./delegation/session-worker-claim.js";
27
26
  import { DurableCustomMessageTurnController } from "./durable-custom-message-turn-controller.js";
28
27
  import { ExtensionBindingController } from "./extension-binding-controller.js";
@@ -38,6 +37,7 @@ import { constrainStreamIdleToHttpTimeout } from "./http-dispatcher.js";
38
37
  import { HumanInputController } from "./human-input-controller.js";
39
38
  import { appendLearningDecisionSnapshot, getLearningDecisionSnapshots } from "./learning/session-learning-decision.js";
40
39
  import { SkillCurator } from "./learning/skill-curator.js";
40
+ import { isWarmableLocalModel, LocalPrefixWarmController } from "./local-prefix-warm-controller.js";
41
41
  import { LocalRuntimeController } from "./local-runtime-controller.js";
42
42
  import { MemoryController } from "./memory-controller.js";
43
43
  import { deriveModelCapabilityProfile, evaluateLaneWorkerRefusal, filterToolNamesForCapability, } from "./model-capability.js";
@@ -45,8 +45,6 @@ import { isLocalOrManagedRouterModel } from "./model-router/tool-escalation.js";
45
45
  import { formatModelRouterModel, ModelRouterController } from "./model-router-controller.js";
46
46
  import { ModelSelectionController } from "./model-selection-controller.js";
47
47
  import { ModelAdaptationStore } from "./models/adaptation-store.js";
48
- import { HF_TRANSFORMERS_PROVIDER, OLLAMA_PROVIDER } from "./models/local-registration.js";
49
- import { isLoopbackModelEndpoint } from "./models/model-endpoint.js";
50
48
  import { DEFAULT_ADAPTIVE_STREAM_IDLE_CEILING_MS, estimateContextPromptTokens, resolveAdaptiveStreamIdleOptions, withModelPerfProfile, } from "./models/perf-profile.js";
51
49
  import { resolveConfiguredOrchestrationModel } from "./orchestration/model-binding.js";
52
50
  import { validateOrchestrationProfile } from "./orchestration/profile-registry.js";
@@ -61,6 +59,7 @@ import { collectWorkspaceSources } from "./research/workspace-collector.js";
61
59
  import { RuntimeBuilder } from "./runtime-builder.js";
62
60
  import { SessionAnalytics } from "./session-analytics.js";
63
61
  import { SessionImageStore } from "./session-image-store.js";
62
+ import { isWorkerSession } from "./session-role.js";
64
63
  import { createSessionShutdownTracker } from "./session-shutdown.js";
65
64
  import { getActiveSessionBranchEntries } from "./session-snapshot.js";
66
65
  import { SessionTreeNavigator } from "./session-tree-navigator.js";
@@ -128,15 +127,7 @@ export class AgentSession {
128
127
  this._turnIndex = 0;
129
128
  /** Per-agent persistent shell session identity: stable across runtime reloads, disposed with the session. */
130
129
  this._shellSessionKey = `agent:${randomUUID()}`;
131
- this._completedPrefixWarms = new Set();
132
130
  this._gatewayRegistry = new GatewayRegistry();
133
- /**
134
- * `getSpawnedUsage().cost` snapshotted at the start of the CURRENT foreground prompt cycle (see
135
- * `_promptUnserialized`), so the cost guard can attribute only background/spawned spend since THIS
136
- * turn began, not the session's entire lifetime spend. Reset on every new user prompt; every
137
- * round-trip within the same turn (tool-call iterations) shares this one baseline.
138
- */
139
- this._costGuardTurnBaselineUsd = 0;
140
131
  this._disposed = false;
141
132
  this._reflectionAbort = new AbortController();
142
133
  this._extensionMode = "print";
@@ -238,13 +229,20 @@ export class AgentSession {
238
229
  }
239
230
  }
240
231
  if (event.type === "agent_end" && !this._willRetryAfterAgentEnd(event)) {
241
- const contextHeadroomPct = Math.max(0, 100 - (this.getContextUsage()?.percent ?? 0));
242
- const reflectionTurn = this._reflection.scheduleFromTurn(event.messages, contextHeadroomPct);
232
+ const reflectionTurn = this._reflection.analyzeCompletedTurn(event.messages);
243
233
  // The shared projection excludes raw tool-result payloads and bounds both roles before any
244
- // provider sees the turn. Synchronization is serialized in the background by MemoryController.
234
+ // deterministic memory sync. No reflection provider request is scheduled at this boundary.
245
235
  this._memory.scheduleTurnSync(reflectionTurn.userText, reflectionTurn.assistantText);
236
+ if (reflectionTurn.trigger !== "none")
237
+ this._reflection.queueCurrentTurnCue(reflectionTurn.trigger);
246
238
  this._goals.endQueuedOwnerChatGoalExecution();
247
239
  }
240
+ // Error/abort turns bypass the normal steering boundary, and a completion can arrive after the
241
+ // final normal poll. agent_end is the fallback before foreground recovery decides whether queued
242
+ // steering requires one continuation; turn_end is intentionally not a flush.
243
+ if (event.type === "agent_end") {
244
+ this._terminalHandoffs.flushProviderBoundary();
245
+ }
248
246
  };
249
247
  this.agent = config.agent;
250
248
  // Bound every provider stream this session starts against a silently dead connection: a
@@ -263,7 +261,7 @@ export class AgentSession {
263
261
  const resolvedReasoning = previousResolveRequestReasoning
264
262
  ? previousResolveRequestReasoning(reasoning, request)
265
263
  : reasoning;
266
- return this._resolveCostGuardRequestReasoning(request.model, request.context, resolvedReasoning, request.maxTokens);
264
+ return this._costGuard.resolveRequestReasoning(request.model, request.context, resolvedReasoning, request.maxTokens);
267
265
  };
268
266
  const profiledStreamFn = withModelPerfProfile(baseStreamFn, {
269
267
  modelKey: (model) => formatModelRouterModel(model),
@@ -286,7 +284,7 @@ export class AgentSession {
286
284
  base: httpBounded.options,
287
285
  profile,
288
286
  promptTokens: estimateContextPromptTokens(context),
289
- localClass: this._isWarmableLocalModel(model),
287
+ localClass: isWarmableLocalModel(model),
290
288
  ceilingMs: httpBounded.adaptiveCeilingMs ?? DEFAULT_ADAPTIVE_STREAM_IDLE_CEILING_MS,
291
289
  });
292
290
  return { ...httpBounded.options, ...adaptive };
@@ -351,6 +349,15 @@ export class AgentSession {
351
349
  resolveConfiguredTierModel: (tier) => this._modelRouter.resolveConfiguredTierModel(tier),
352
350
  formatModel: (model) => formatModelRouterModel(model),
353
351
  });
352
+ this._localPrefixWarm = new LocalPrefixWarmController({
353
+ getStreamFn: () => this.agent.streamFn,
354
+ getTools: () => this.agent.state.tools,
355
+ getSystemPrompt: () => this._baseSystemPrompt,
356
+ getRequestHooks: () => ({ onPayload: this.agent.onPayload, onResponse: this.agent.onResponse }),
357
+ isRawStreamSimple: (streamFn) => this._isRawStreamSimple(streamFn),
358
+ getRequiredRequestAuth: (model) => this._getRequiredRequestAuth(model),
359
+ ensureManagedModelReady: (model) => this._localRuntimeController.ensureIsolatedModelReady(model),
360
+ });
354
361
  this._systemPromptBuilder = new SystemPromptBuilder({
355
362
  getCwd: () => this._cwd,
356
363
  getSettingsManager: () => this.settingsManager,
@@ -362,6 +369,7 @@ export class AgentSession {
362
369
  getModelAdaptationRules: () => this._toolProtocol.getAdaptationRulesForPrompt(),
363
370
  getActiveExtensions: () => this._extensionRunner.activeExtensions,
364
371
  getModelCapabilityProfile: () => this.getModelCapabilityProfile(),
372
+ isChildSession: () => this._isChildSession,
365
373
  // The evidence-gated tool-selection hint block — self-gated by kill switch/evidence
366
374
  // thresholds inside getActiveHints() itself, so this is a plain always-on pass-through.
367
375
  getToolSelectionHints: () => this._toolSelection.getActiveHints(),
@@ -379,6 +387,12 @@ export class AgentSession {
379
387
  getLearningAuditRecords: () => this.getLearningAuditRecords(),
380
388
  });
381
389
  this._modelRegistry = config.modelRegistry;
390
+ this._costGuard = new CostGuardController({
391
+ getSettings: () => this.settingsManager.getCostGuardSettings(),
392
+ getCompactionReserveTokens: () => this.settingsManager.getCompactionReserveTokens(),
393
+ getSpawnedUsageCost: () => this.getSpawnedUsage().cost,
394
+ isUnmeteredSubscription: (model) => model.provider === "openai-codex" && this._modelRegistry.isUsingOAuth(model),
395
+ });
382
396
  this._humanInput = new HumanInputController({
383
397
  getSessionManager: () => this.sessionManager,
384
398
  getUIContext: () => this._extensionUIContext,
@@ -413,6 +427,8 @@ export class AgentSession {
413
427
  getModelRegistry: () => this._modelRegistry,
414
428
  isModelExhausted: (model) => this._foregroundRecovery.isModelExhausted(`${model.provider}/${model.id}`),
415
429
  getModel: () => this.model ?? undefined,
430
+ getForegroundThinkingLevel: () => this.thinkingLevel,
431
+ getForegroundToolNames: () => this.getActiveToolNames(),
416
432
  isDelegateToolActive: () => this.getActiveToolNames().includes("delegate"),
417
433
  isGoalToolActive: () => hasGoalContinuationControl(this.getActiveToolNames()),
418
434
  getCapabilityEnvelope: () => this.capabilityEnvelope,
@@ -427,6 +443,15 @@ export class AgentSession {
427
443
  saveEvidenceBundleSnapshot: (bundle) => this.saveEvidenceBundleSnapshot(bundle),
428
444
  saveWorkerClaimSnapshot: (claim, request) => this.saveWorkerClaimSnapshot(claim, request),
429
445
  readMemoryForLane: (query) => this._memory.readMemoryForLane(query),
446
+ getArtifactStore: () => this._getToolArtifactStore(),
447
+ getSkillReadBroker: () => ({
448
+ search: (query) => this._skillVault.search(query),
449
+ read: (name) => this._skillVault.read(name),
450
+ }),
451
+ getSkillAuditSource: () => ({
452
+ getSkills: () => this._skillVault.getSkillsSnapshot(),
453
+ redactPath: (path) => `skill:${createHash("sha256").update(path).digest("hex").slice(0, 12)}`,
454
+ }),
430
455
  addSpawnedUsage: (usage, opts) => this.addSpawnedUsage(usage, opts),
431
456
  runIsolatedCompletion: (opts) => this.runIsolatedCompletion(opts),
432
457
  // RAW loop, deliberately bypassing the public `continueGoalLoop` — that method now delegates
@@ -481,6 +506,7 @@ export class AgentSession {
481
506
  });
482
507
  this._backgroundToolTasks = new BackgroundToolTaskController({
483
508
  getSessionId: () => this.sessionManager.getSessionId(),
509
+ getGoalId: () => this._goals.getExecutionGoalId(),
484
510
  getSessionLineageIds: () => this.sessionManager.getSessionLineageIds(),
485
511
  getArtifactStore: () => this._getToolArtifactStore(),
486
512
  loadPersistedRecordsNewestFirst: () => loadBackgroundToolTaskRecordsNewestFirst(this.sessionManager),
@@ -548,6 +574,7 @@ export class AgentSession {
548
574
  enqueueRelevanceCuration: (messages, report) => this._enqueueRelevanceCuration(messages, report),
549
575
  maybeDrainBrainCuration: () => this._maybeDrainBrainCuration(),
550
576
  appendMemoryEvidence: (messages, report) => this._maybeAppendMemoryEvidenceBlock(messages, report),
577
+ previewReflectionCue: () => this._reflection.previewCurrentTurnCue(),
551
578
  getGoalState: () => this.getGoalStateSnapshot(),
552
579
  skillVault: this._skillVault,
553
580
  });
@@ -586,6 +613,7 @@ export class AgentSession {
586
613
  this._durableCustomMessageTurns = new DurableCustomMessageTurnController({
587
614
  foreground: this._foregroundRecovery,
588
615
  goals: this._goals,
616
+ enqueueSteeringMessage: (message) => this.agent.steer(message),
589
617
  });
590
618
  this._terminalHandoffs = new ForegroundTerminalHandoffController({
591
619
  foreground: this._foregroundRecovery,
@@ -594,6 +622,7 @@ export class AgentSession {
594
622
  getWorkerClaimSnapshot: (laneId) => getLatestWorkerClaimSnapshot(getActiveSessionBranchEntries(this.sessionManager), laneId),
595
623
  getWorkerResult: (laneId) => this._backgroundLanes.getWorkerResult(laneId),
596
624
  startCustomMessageTurn: (message, lease, goalId) => this._durableCustomMessageTurns.start(message, lease, goalId),
625
+ enqueueCustomMessageTurn: (message) => this._durableCustomMessageTurns.enqueue(message),
597
626
  sendCustomMessage: (message, options, lease) => this._sendCustomMessage(message, options, lease),
598
627
  warn: (message) => this._emit({ type: "warning", message }),
599
628
  });
@@ -632,9 +661,14 @@ export class AgentSession {
632
661
  isRawStreamSimple: () => this._isRawStreamSimple(this.agent.streamFn),
633
662
  getModelRegistry: () => this._modelRegistry,
634
663
  getMemoryManager: () => this._memory.getMemoryManager(),
664
+ getFreshOkfMemoryForReflection: () => this._memory.getFreshOkfMemoryForReflection(),
665
+ applyStructuredReflectionWrite: (write, signal) => this._memory.applyStructuredReflectionWrite(write, signal),
666
+ rollbackStructuredReflectionWrite: this._memory.rollbackStructuredReflectionWrite.bind(this._memory),
635
667
  getSettingsManager: () => this.settingsManager,
636
668
  getSessionManager: () => this.sessionManager,
637
669
  getAgentDir: () => this._agentDir,
670
+ getCwd: () => this._cwd,
671
+ getSkillsForAudit: () => this._resourceLoader.getActiveSkills(),
638
672
  isChildSession: () => this._isChildSession,
639
673
  isDisposed: () => this._disposed,
640
674
  getReflectionSignal: () => this._reflectionAbort.signal,
@@ -665,7 +699,7 @@ export class AgentSession {
665
699
  : undefined;
666
700
  this._isExplicitModel = config.isExplicitModel ?? false;
667
701
  this._isExplicitThinking = config.isExplicitThinking ?? false;
668
- this._isChildSession = config.isChildSession ?? process.env.PI_CHILD_SESSION === "1";
702
+ this._isChildSession = (config.isChildSession ?? process.env.PI_CHILD_SESSION === "1") || isWorkerSession();
669
703
  this._baseToolsOverride = config.baseToolsOverride;
670
704
  this._sessionStartEvent = config.sessionStartEvent ?? { type: "session_start", reason: "startup" };
671
705
  this._runtimeBuilder = new RuntimeBuilder({
@@ -953,79 +987,15 @@ export class AgentSession {
953
987
  activeToolNames: this._initialActiveToolNames,
954
988
  includeAllExtensionTools: true,
955
989
  });
956
- this._scheduleLocalPrefixWarm(this.agent.state.model, "session-start");
990
+ this._unsubscribeSettingsChanges = this.settingsManager.subscribeChanges(() => {
991
+ this._refreshBaseSystemPrompt();
992
+ });
993
+ this._localPrefixWarm.schedule(this.agent.state.model);
957
994
  }
958
995
  /** Model registry for API key resolution and model discovery */
959
996
  get modelRegistry() {
960
997
  return this._modelRegistry;
961
998
  }
962
- _scheduleLocalPrefixWarm(model, _reason) {
963
- if (!model || !this._isWarmableLocalModel(model))
964
- return;
965
- const modelKey = formatModelRouterModel(model);
966
- if (this._completedPrefixWarms.has(modelKey) || this._prefixWarmer?.modelKey === modelKey)
967
- return;
968
- this._cancelPrefixWarm();
969
- const controller = new AbortController();
970
- const timer = setTimeout(() => {
971
- const warmer = this._prefixWarmer;
972
- if (!warmer || warmer.controller !== controller || controller.signal.aborted)
973
- return;
974
- warmer.timer = undefined;
975
- void this._runLocalPrefixWarm(model, modelKey, controller);
976
- }, 0);
977
- timer.unref?.();
978
- this._prefixWarmer = { modelKey, controller, timer };
979
- }
980
- _cancelPrefixWarm() {
981
- const warmer = this._prefixWarmer;
982
- if (!warmer)
983
- return;
984
- if (warmer.timer)
985
- clearTimeout(warmer.timer);
986
- warmer.controller.abort(new Error("prefix warmer preempted"));
987
- this._prefixWarmer = undefined;
988
- }
989
- async _runLocalPrefixWarm(model, modelKey, controller) {
990
- try {
991
- const options = {
992
- maxTokens: 1,
993
- signal: controller.signal,
994
- onPayload: this.agent.onPayload,
995
- onResponse: this.agent.onResponse,
996
- };
997
- if (this._isRawStreamSimple(this.agent.streamFn)) {
998
- const auth = await this._getRequiredRequestAuth(model);
999
- options.apiKey = auth.apiKey;
1000
- options.headers = auth.headers;
1001
- }
1002
- if (controller.signal.aborted)
1003
- return;
1004
- if (model.provider === OLLAMA_PROVIDER || model.provider === HF_TRANSFORMERS_PROVIDER) {
1005
- await this._localRuntimeController.ensureIsolatedModelReady(model);
1006
- }
1007
- if (controller.signal.aborted)
1008
- return;
1009
- const stream = await this.agent.streamFn(model, {
1010
- systemPrompt: this._baseSystemPrompt,
1011
- tools: projectToolsForProvider(this.agent.state.tools),
1012
- messages: [],
1013
- }, options);
1014
- await stream.result();
1015
- if (!controller.signal.aborted)
1016
- this._completedPrefixWarms.add(modelKey);
1017
- }
1018
- catch {
1019
- // Best-effort cache warm only; a miss must never affect the real turn.
1020
- }
1021
- finally {
1022
- if (this._prefixWarmer?.controller === controller)
1023
- this._prefixWarmer = undefined;
1024
- }
1025
- }
1026
- _isWarmableLocalModel(model) {
1027
- return model.api === "openai-completions" && isLoopbackModelEndpoint(model.baseUrl);
1028
- }
1029
999
  /**
1030
1000
  * True when the session's stream fn is the raw `streamSimple` provider entry (directly, or as the
1031
1001
  * base wrapped by the idle watchdog at construction). Callers use this to decide whether request
@@ -1080,58 +1050,16 @@ export class AgentSession {
1080
1050
  _resolveCompactionThinkingLevel(compactionModel, sessionModel) {
1081
1051
  return this._compactionSupport.resolveThinkingLevel(this.thinkingLevel, compactionModel, sessionModel);
1082
1052
  }
1083
- /**
1084
- * Resolve the foreground request's cost policy after routing/context conversion, when the actual
1085
- * model, full system prompt, converted messages, and tool schemas are known. The guard is a
1086
- * projection threshold rather than a hard output cap: warning mode never reduces capability, while
1087
- * opt-in downgrade changes only this request's reasoning effort. Best-effort: never throws.
1088
- *
1089
- * The ceiling is turn-cumulative: the next foreground call's projection is folded together with
1090
- * background/research/worker/reflection spend recorded SINCE THIS TURN BEGAN — {@link getSpawnedUsage}'s
1091
- * already-recorded rollup (the same read-side-deduped total the footer's SUBAGENTS line uses) minus the
1092
- * baseline snapshotted before a new turn enters routing in `_promptUnserialized`
1093
- * ({@link _costGuardTurnBaselineUsd}) — so a
1094
- * turn that is cheap in the foreground but has spent heavily via background lanes THIS turn still trips
1095
- * the warning, while a prior turn's background spend does not keep every later turn's guard stuck
1096
- * "over". A background lane that finishes mid-turn is attributed to whichever turn it completes in.
1097
- * Per-lane dollar caps (research/worker `maxUsd`) are separate and untouched by this guard.
1098
- */
1099
- _resolveCostGuardRequestReasoning(model, context, reasoning, requestMaxTokens) {
1100
- try {
1101
- const guard = this.settingsManager.getCostGuardSettings();
1102
- const isChatGptSubscription = model.provider === "openai-codex" && this._modelRegistry.isUsingOAuth(model);
1103
- if (guard.maxTurnUsd <= 0 || !model.cost || isChatGptSubscription) {
1104
- this._lastCostGuardDecision = undefined;
1105
- return reasoning;
1106
- }
1107
- const inputTokens = estimateContextPromptTokens(context);
1108
- // Use an explicit request cap when present; otherwise project against the session response
1109
- // reserve instead of a frontier model's theoretical 128K output maximum.
1110
- const maxOutputTokens = Math.min(model.maxTokens ?? 4096, requestMaxTokens ?? this.settingsManager.getCompactionReserveTokens());
1111
- const estUsd = estimateTurnCostUsd({
1112
- inputTokens,
1113
- maxOutputTokens,
1114
- cost: model.cost,
1115
- longContextPricing: model.longContextPricing,
1116
- });
1117
- // Only spend recorded SINCE this turn's baseline counts -- never negative (a dedup/rollup
1118
- // correction could otherwise move the total backward transiently).
1119
- const cumulativeBackgroundUsd = Math.max(0, this.getSpawnedUsage().cost - this._costGuardTurnBaselineUsd);
1120
- const decision = evaluateCostGuard(estUsd, { maxTurnUsd: guard.maxTurnUsd, action: guard.action }, cumulativeBackgroundUsd);
1121
- this._lastCostGuardDecision = decision;
1122
- if (!decision.over || guard.action !== "downgrade" || reasoning === undefined)
1123
- return reasoning;
1124
- const next = downgradeReasoning(reasoning, getSupportedThinkingLevels(model), model.thinkingLevelMap);
1125
- return next;
1126
- }
1127
- catch {
1128
- // cost guard must never disrupt a turn
1129
- return reasoning;
1130
- }
1131
- }
1132
1053
  /** Latest cost-guard decision (for the host footer/UI to surface a warning). Undefined if disabled. */
1133
1054
  getLastCostGuardDecision() {
1134
- return this._lastCostGuardDecision;
1055
+ return this._costGuard.getLastDecision();
1056
+ }
1057
+ /** Apply an explicit guard choice and invalidate all prior decision/envelope projections immediately. */
1058
+ setCostGuardSettings(settings, scope = "global") {
1059
+ this.settingsManager.setCostGuardSettings(settings, scope);
1060
+ this._costGuard.invalidateDecision();
1061
+ if (this._currentForegroundEnvelope)
1062
+ this._refreshForegroundEnvelope();
1135
1063
  }
1136
1064
  get _skillCurator() {
1137
1065
  if (!this._skillCuratorInstance) {
@@ -1175,6 +1103,13 @@ export class AgentSession {
1175
1103
  }
1176
1104
  _installAgentTurnRefresh() {
1177
1105
  const previousPrepareNextTurn = this.agent.prepareNextTurn?.bind(this.agent);
1106
+ const previousBeforeSteeringPoll = this.agent.beforeSteeringPoll?.bind(this.agent);
1107
+ this.agent.beforeSteeringPoll = async (signal) => {
1108
+ await previousBeforeSteeringPoll?.(signal);
1109
+ // This is later than async turn preparation and the graceful-stop check, making it the
1110
+ // authoritative last-moment inbox refresh before the queue is drained.
1111
+ this._terminalHandoffs.flushProviderBoundary();
1112
+ };
1178
1113
  this.agent.prepareNextTurn = async (signal) => {
1179
1114
  const previous = previousPrepareNextTurn ? await previousPrepareNextTurn(signal) : undefined;
1180
1115
  const snapshot = this._createAgentContextSnapshot();
@@ -1737,18 +1672,21 @@ export class AgentSession {
1737
1672
  safely(() => this._backgroundLanes.clearGoalAutoContinueTimer());
1738
1673
  safely(() => this._backgroundLanes.clearResearchLaneTimer());
1739
1674
  safely(() => this._foregroundRecovery.shutdown());
1675
+ safely(() => this._durableCustomMessageTurns.shutdown());
1740
1676
  safely(() => this.abortRetry());
1741
1677
  safely(() => this.abortCompaction());
1742
1678
  safely(() => this.abortBranchSummary());
1743
1679
  safely(() => this.abortBash());
1744
1680
  safely(() => this._skillVault.unload());
1681
+ safely(() => this._unsubscribeSettingsChanges?.());
1682
+ this._unsubscribeSettingsChanges = undefined;
1745
1683
  trackRequired(() => disposeShellExecutionSessionAndWait(this._shellSessionKey));
1746
- safely(() => this._cancelPrefixWarm());
1684
+ safely(() => this._localPrefixWarm.cancel());
1747
1685
  safely(() => this.agent.abort());
1748
1686
  track(() => this._gatewayRegistry.stop());
1749
1687
  track(() => this._backgroundToolTasks.shutdown());
1750
1688
  track(() => this._runtimeBuilder.dispose());
1751
- safely(() => this._reflection.cancelScheduled());
1689
+ safely(() => this._reflection.dispose());
1752
1690
  safely(() => this._reflectionAbort.abort());
1753
1691
  safely(() => this._backgroundLanes.abortInFlightLanes());
1754
1692
  safely(() => this._providerRequestRuntime.dispose());
@@ -1761,12 +1699,7 @@ export class AgentSession {
1761
1699
  track(() => this._resourceLoader.dispose?.() ?? Promise.resolve());
1762
1700
  safely(() => this._disconnectFromAgent());
1763
1701
  this._eventListeners = [];
1764
- // Let an aborted in-flight reflection reach its terminal state, then flush session-owned write
1765
- // hooks before releasing provider locks/handles. This prevents a late write racing shutdown.
1766
- track(async () => {
1767
- await this._reflection.waitForActivePass();
1768
- await this._memory.shutdown();
1769
- });
1702
+ track(() => this._memory.shutdown());
1770
1703
  track(() => this._toolRecoveryLogger.shutdown());
1771
1704
  safely(() => cleanupSessionResources(this.sessionId));
1772
1705
  // Best-effort final sweep for any grep/find artifact already released (reference
@@ -1824,7 +1757,7 @@ export class AgentSession {
1824
1757
  turnIndex: this._turnIndex,
1825
1758
  activeToolNames: this.getActiveToolNames(),
1826
1759
  cwd: this._cwd,
1827
- maxTurnUsd: this.settingsManager.getCostGuardSettings().maxTurnUsd,
1760
+ maxTurnUsd: this._costGuard.getEnabledMaxTurnUsd(),
1828
1761
  });
1829
1762
  }
1830
1763
  /**
@@ -2086,7 +2019,7 @@ export class AgentSession {
2086
2019
  }
2087
2020
  async _promptUnserialized(text, options, submission) {
2088
2021
  this._toolProtocol.applyRepairLayerSettings();
2089
- this._cancelPrefixWarm();
2022
+ this._localPrefixWarm.cancel();
2090
2023
  const expandPromptTemplates = options?.expandPromptTemplates ?? true;
2091
2024
  const processSlashCommands = options?.processSlashCommands ?? expandPromptTemplates;
2092
2025
  const preflightResult = options?.preflightResult;
@@ -2171,9 +2104,9 @@ export class AgentSession {
2171
2104
  if (!options?.internalContextType) {
2172
2105
  admittedGoalId = this._goals.startOwnerChatGoal(expandedText, this.agent.state.messages) ?? admittedGoalId;
2173
2106
  }
2174
- // This submission is starting a new foreground turn. Queued steer/follow-up messages above
2175
- // remain part of the already-active turn and must not erase its spawned-cost baseline.
2176
- this._costGuardTurnBaselineUsd = this.getSpawnedUsage().cost;
2107
+ // Queued steer/follow-up messages remain in the active turn; only a new submission resets the
2108
+ // cost controller's spawned-usage baseline shared by every round trip in this turn.
2109
+ this._costGuard.beginForegroundTurn();
2177
2110
  // Flush any pending bash messages before the new prompt
2178
2111
  this._flushPendingBashMessages();
2179
2112
  // Build the user message now — before the router judge — and paint it to the UI
@@ -2270,6 +2203,10 @@ export class AgentSession {
2270
2203
  // recall must never break a turn
2271
2204
  }
2272
2205
  }
2206
+ // Queue one durable logical cue. ProviderRequestContextController owns its transient preview
2207
+ // and accepted-plan commit, so it never enters or needs cleanup from agent history.
2208
+ if (!options?.internalContextType)
2209
+ this._reflection.queueCurrentTurnCue("root-turn");
2273
2210
  // Add user message (built earlier, before the router judge, so it could be painted
2274
2211
  // immediately — see the early message_start emit above).
2275
2212
  messages.push(promptMessage);
@@ -2650,7 +2587,7 @@ export class AgentSession {
2650
2587
  // =========================================================================
2651
2588
  async setModel(model, options = {}) {
2652
2589
  await this._modelSelection.setModel(model, options);
2653
- this._scheduleLocalPrefixWarm(this.agent.state.model, "selection");
2590
+ this._localPrefixWarm.schedule(this.agent.state.model);
2654
2591
  }
2655
2592
  /** Re-resolve startup profile model/thinking after allowed extension providers are bound. */
2656
2593
  async reapplyActiveProfileModelSettings() {
@@ -2659,12 +2596,12 @@ export class AgentSession {
2659
2596
  const activeToolNames = this._requestedActiveToolNames ?? this.getActiveToolNames();
2660
2597
  this._refreshToolRegistry({ activeToolNames, includeAllExtensionTools: true });
2661
2598
  if (!modelsAreEqual(previousModel, this.model)) {
2662
- this._scheduleLocalPrefixWarm(this.model, "selection");
2599
+ this._localPrefixWarm.schedule(this.model);
2663
2600
  }
2664
2601
  }
2665
2602
  async cycleModel(direction = "forward") {
2666
2603
  const result = await this._modelSelection.cycleModel(direction);
2667
- this._scheduleLocalPrefixWarm(result?.model, "selection");
2604
+ this._localPrefixWarm.schedule(result?.model);
2668
2605
  return result;
2669
2606
  }
2670
2607
  // =========================================================================
@@ -2835,6 +2772,7 @@ export class AgentSession {
2835
2772
  }
2836
2773
  async reload() {
2837
2774
  this._foregroundLifecycle.reload();
2775
+ this._reflection.invalidateCurrentTurnCueStateCache();
2838
2776
  this.agent.state.messages = this.sessionManager.buildSessionContext().messages;
2839
2777
  return this._runtimeBuilder.reload();
2840
2778
  }
@@ -2924,7 +2862,9 @@ export class AgentSession {
2924
2862
  // Tree Navigation
2925
2863
  // =========================================================================
2926
2864
  async navigateTree(targetId, options = {}) {
2927
- return this._treeNavigator.navigateTree(targetId, options);
2865
+ const result = await this._treeNavigator.navigateTree(targetId, options);
2866
+ this._reflection.invalidateCurrentTurnCueStateCache();
2867
+ return result;
2928
2868
  }
2929
2869
  getUserMessagesForForking() {
2930
2870
  return this._treeNavigator.getUserMessagesForForking();
@@ -3120,16 +3060,13 @@ export class AgentSession {
3120
3060
  async continueGoalLoop(options) {
3121
3061
  return this._backgroundLanes.continueGoalLoopExclusive(options);
3122
3062
  }
3123
- /**
3124
- * Run a one-shot LLM completion fully ISOLATED from the main session — the load-bearing primitive
3125
- * for native reflection (see reflection-controller.ts for the isolation invariants).
3126
- */
3063
+ /** Run one explicit isolated completion for bounded host-owned consumers. */
3127
3064
  async runIsolatedCompletion(opts) {
3128
3065
  return this._reflection.runIsolatedCompletion(opts);
3129
3066
  }
3130
3067
  /**
3131
- * Native end-of-loop reflection pass. Delegates to {@link ReflectionController}; returns null
3132
- * when the demand gate skips or in a child session.
3068
+ * Explicit compatibility/application reflection pass. Automatic reflection never calls this
3069
+ * method; it returns null when the demand gate skips or in a child session.
3133
3070
  */
3134
3071
  async runReflectionPass(input) {
3135
3072
  return this._reflection.runReflectionPass(input);