@caupulican/pi-adaptative 0.81.39 → 0.81.41

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 (884) hide show
  1. package/CHANGELOG.md +77 -0
  2. package/README.md +2 -0
  3. package/dist/bundled-resources/extensions/tmux-agent-manager/dispatch-grant.d.ts +2 -0
  4. package/dist/bundled-resources/extensions/tmux-agent-manager/dispatch-grant.d.ts.map +1 -1
  5. package/dist/bundled-resources/extensions/tmux-agent-manager/dispatch-grant.js +3 -0
  6. package/dist/bundled-resources/extensions/tmux-agent-manager/dispatch-grant.js.map +1 -1
  7. package/dist/bundled-resources/extensions/tmux-agent-manager/dispatch-grant.ts +4 -0
  8. package/dist/bundled-resources/extensions/tmux-agent-manager/index.d.ts +9 -0
  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 +290 -107
  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 +357 -122
  13. package/dist/bundled-resources/skills/tool-call-repair/references/repair-catalogue.md +2 -2
  14. package/dist/cli/args.d.ts +4 -0
  15. package/dist/cli/args.d.ts.map +1 -1
  16. package/dist/cli/args.js +31 -1
  17. package/dist/cli/args.js.map +1 -1
  18. package/dist/core/agent-directory-layout.d.ts +15 -0
  19. package/dist/core/agent-directory-layout.d.ts.map +1 -0
  20. package/dist/core/agent-directory-layout.js +72 -0
  21. package/dist/core/agent-directory-layout.js.map +1 -0
  22. package/dist/core/agent-paths.d.ts +25 -2
  23. package/dist/core/agent-paths.d.ts.map +1 -1
  24. package/dist/core/agent-paths.js +79 -4
  25. package/dist/core/agent-paths.js.map +1 -1
  26. package/dist/core/agent-session-contracts.d.ts +293 -0
  27. package/dist/core/agent-session-contracts.d.ts.map +1 -0
  28. package/dist/core/agent-session-contracts.js +26 -0
  29. package/dist/core/agent-session-contracts.js.map +1 -0
  30. package/dist/core/agent-session-runtime.d.ts +52 -8
  31. package/dist/core/agent-session-runtime.d.ts.map +1 -1
  32. package/dist/core/agent-session-runtime.js +400 -79
  33. package/dist/core/agent-session-runtime.js.map +1 -1
  34. package/dist/core/agent-session-services.d.ts +1 -0
  35. package/dist/core/agent-session-services.d.ts.map +1 -1
  36. package/dist/core/agent-session-services.js +1 -0
  37. package/dist/core/agent-session-services.js.map +1 -1
  38. package/dist/core/agent-session.d.ts +74 -518
  39. package/dist/core/agent-session.d.ts.map +1 -1
  40. package/dist/core/agent-session.js +370 -1432
  41. package/dist/core/agent-session.js.map +1 -1
  42. package/dist/core/auth-storage.d.ts.map +1 -1
  43. package/dist/core/auth-storage.js +3 -1
  44. package/dist/core/auth-storage.js.map +1 -1
  45. package/dist/core/autonomy/approval-gate.d.ts +3 -2
  46. package/dist/core/autonomy/approval-gate.d.ts.map +1 -1
  47. package/dist/core/autonomy/approval-gate.js +6 -28
  48. package/dist/core/autonomy/approval-gate.js.map +1 -1
  49. package/dist/core/autonomy/bounded-completion.d.ts +1 -1
  50. package/dist/core/autonomy/bounded-completion.d.ts.map +1 -1
  51. package/dist/core/autonomy/bounded-completion.js +1 -1
  52. package/dist/core/autonomy/bounded-completion.js.map +1 -1
  53. package/dist/core/autonomy/contracts.d.ts +20 -12
  54. package/dist/core/autonomy/contracts.d.ts.map +1 -1
  55. package/dist/core/autonomy/contracts.js.map +1 -1
  56. package/dist/core/autonomy/foreground-envelope.d.ts +8 -2
  57. package/dist/core/autonomy/foreground-envelope.d.ts.map +1 -1
  58. package/dist/core/autonomy/foreground-envelope.js +8 -25
  59. package/dist/core/autonomy/foreground-envelope.js.map +1 -1
  60. package/dist/core/autonomy/gates.d.ts.map +1 -1
  61. package/dist/core/autonomy/gates.js +8 -10
  62. package/dist/core/autonomy/gates.js.map +1 -1
  63. package/dist/core/autonomy/lane-private-paths.d.ts +2 -0
  64. package/dist/core/autonomy/lane-private-paths.d.ts.map +1 -0
  65. package/dist/core/autonomy/lane-private-paths.js +16 -0
  66. package/dist/core/autonomy/lane-private-paths.js.map +1 -0
  67. package/dist/core/autonomy/lane-tool-surface.d.ts +10 -0
  68. package/dist/core/autonomy/lane-tool-surface.d.ts.map +1 -1
  69. package/dist/core/autonomy/lane-tool-surface.js +48 -9
  70. package/dist/core/autonomy/lane-tool-surface.js.map +1 -1
  71. package/dist/core/autonomy/lane-tracker.d.ts +14 -0
  72. package/dist/core/autonomy/lane-tracker.d.ts.map +1 -1
  73. package/dist/core/autonomy/lane-tracker.js +38 -0
  74. package/dist/core/autonomy/lane-tracker.js.map +1 -1
  75. package/dist/core/autonomy/risk-assessment.d.ts +1 -2
  76. package/dist/core/autonomy/risk-assessment.d.ts.map +1 -1
  77. package/dist/core/autonomy/risk-assessment.js +1 -123
  78. package/dist/core/autonomy/risk-assessment.js.map +1 -1
  79. package/dist/core/autonomy/session-lane-record.d.ts +4 -4
  80. package/dist/core/autonomy/session-lane-record.d.ts.map +1 -1
  81. package/dist/core/autonomy/session-lane-record.js +16 -29
  82. package/dist/core/autonomy/session-lane-record.js.map +1 -1
  83. package/dist/core/autonomy/telemetry-events.d.ts +1 -1
  84. package/dist/core/autonomy/telemetry-events.d.ts.map +1 -1
  85. package/dist/core/autonomy/telemetry-events.js +1 -1
  86. package/dist/core/autonomy/telemetry-events.js.map +1 -1
  87. package/dist/core/autonomy-telemetry.d.ts +7 -7
  88. package/dist/core/autonomy-telemetry.d.ts.map +1 -1
  89. package/dist/core/autonomy-telemetry.js +9 -9
  90. package/dist/core/autonomy-telemetry.js.map +1 -1
  91. package/dist/core/background-lane-controller.d.ts +56 -236
  92. package/dist/core/background-lane-controller.d.ts.map +1 -1
  93. package/dist/core/background-lane-controller.js +141 -1273
  94. package/dist/core/background-lane-controller.js.map +1 -1
  95. package/dist/core/bedrock-sso-login.d.ts +16 -0
  96. package/dist/core/bedrock-sso-login.d.ts.map +1 -0
  97. package/dist/core/bedrock-sso-login.js +98 -0
  98. package/dist/core/bedrock-sso-login.js.map +1 -0
  99. package/dist/core/capability-contract.d.ts +4 -0
  100. package/dist/core/capability-contract.d.ts.map +1 -0
  101. package/dist/core/capability-contract.js +28 -0
  102. package/dist/core/capability-contract.js.map +1 -0
  103. package/dist/core/compaction-controller.d.ts +90 -0
  104. package/dist/core/compaction-controller.d.ts.map +1 -0
  105. package/dist/core/compaction-controller.js +452 -0
  106. package/dist/core/compaction-controller.js.map +1 -0
  107. package/dist/core/compaction-support.d.ts +13 -17
  108. package/dist/core/compaction-support.d.ts.map +1 -1
  109. package/dist/core/compaction-support.js +3 -3
  110. package/dist/core/compaction-support.js.map +1 -1
  111. package/dist/core/context/context-artifacts.d.ts +6 -2
  112. package/dist/core/context/context-artifacts.d.ts.map +1 -1
  113. package/dist/core/context/context-artifacts.js +34 -2
  114. package/dist/core/context/context-artifacts.js.map +1 -1
  115. package/dist/core/context/context-store-retention.d.ts +8 -2
  116. package/dist/core/context/context-store-retention.d.ts.map +1 -1
  117. package/dist/core/context/context-store-retention.js +158 -35
  118. package/dist/core/context/context-store-retention.js.map +1 -1
  119. package/dist/core/context/okf-memory.d.ts.map +1 -1
  120. package/dist/core/context/okf-memory.js +9 -11
  121. package/dist/core/context/okf-memory.js.map +1 -1
  122. package/dist/core/context/sqlite-runtime-index.d.ts.map +1 -1
  123. package/dist/core/context/sqlite-runtime-index.js +6 -8
  124. package/dist/core/context/sqlite-runtime-index.js.map +1 -1
  125. package/dist/core/context-gc.d.ts +3 -0
  126. package/dist/core/context-gc.d.ts.map +1 -1
  127. package/dist/core/context-gc.js +10 -5
  128. package/dist/core/context-gc.js.map +1 -1
  129. package/dist/core/context-pipeline.d.ts +1 -1
  130. package/dist/core/context-pipeline.d.ts.map +1 -1
  131. package/dist/core/context-pipeline.js +16 -37
  132. package/dist/core/context-pipeline.js.map +1 -1
  133. package/dist/core/cost/cost-summary.d.ts.map +1 -1
  134. package/dist/core/cost/cost-summary.js +5 -3
  135. package/dist/core/cost/cost-summary.js.map +1 -1
  136. package/dist/core/cost/daily-usage.d.ts.map +1 -1
  137. package/dist/core/cost/daily-usage.js +4 -5
  138. package/dist/core/cost/daily-usage.js.map +1 -1
  139. package/dist/core/default-tool-surface.d.ts.map +1 -1
  140. package/dist/core/default-tool-surface.js +2 -0
  141. package/dist/core/default-tool-surface.js.map +1 -1
  142. package/dist/core/delegation/managed-lane-controller.d.ts +34 -0
  143. package/dist/core/delegation/managed-lane-controller.d.ts.map +1 -0
  144. package/dist/core/delegation/managed-lane-controller.js +217 -0
  145. package/dist/core/delegation/managed-lane-controller.js.map +1 -0
  146. package/dist/core/delegation/session-worker-claim.d.ts +44 -0
  147. package/dist/core/delegation/session-worker-claim.d.ts.map +1 -0
  148. package/dist/core/delegation/session-worker-claim.js +98 -0
  149. package/dist/core/delegation/session-worker-claim.js.map +1 -0
  150. package/dist/core/delegation/worker-actions.d.ts +7 -5
  151. package/dist/core/delegation/worker-actions.d.ts.map +1 -1
  152. package/dist/core/delegation/worker-actions.js +20 -4
  153. package/dist/core/delegation/worker-actions.js.map +1 -1
  154. package/dist/core/delegation/{worker-result.d.ts → worker-claim.d.ts} +13 -13
  155. package/dist/core/delegation/worker-claim.d.ts.map +1 -0
  156. package/dist/core/delegation/{worker-result.js → worker-claim.js} +61 -51
  157. package/dist/core/delegation/worker-claim.js.map +1 -0
  158. package/dist/core/delegation/worker-delegation-controller.d.ts +110 -0
  159. package/dist/core/delegation/worker-delegation-controller.d.ts.map +1 -0
  160. package/dist/core/delegation/worker-delegation-controller.js +861 -0
  161. package/dist/core/delegation/worker-delegation-controller.js.map +1 -0
  162. package/dist/core/delegation/worker-delegation-request.d.ts +11 -0
  163. package/dist/core/delegation/worker-delegation-request.d.ts.map +1 -0
  164. package/dist/core/delegation/worker-delegation-request.js +2 -0
  165. package/dist/core/delegation/worker-delegation-request.js.map +1 -0
  166. package/dist/core/delegation/worker-dispatch-scheduler.d.ts +40 -0
  167. package/dist/core/delegation/worker-dispatch-scheduler.d.ts.map +1 -0
  168. package/dist/core/delegation/worker-dispatch-scheduler.js +93 -0
  169. package/dist/core/delegation/worker-dispatch-scheduler.js.map +1 -0
  170. package/dist/core/delegation/worker-execution-policy.d.ts +62 -0
  171. package/dist/core/delegation/worker-execution-policy.d.ts.map +1 -0
  172. package/dist/core/delegation/worker-execution-policy.js +160 -0
  173. package/dist/core/delegation/worker-execution-policy.js.map +1 -0
  174. package/dist/core/delegation/worker-lane-projection.d.ts +14 -0
  175. package/dist/core/delegation/worker-lane-projection.d.ts.map +1 -0
  176. package/dist/core/delegation/worker-lane-projection.js +100 -0
  177. package/dist/core/delegation/worker-lane-projection.js.map +1 -0
  178. package/dist/core/delegation/worker-lifecycle.d.ts +97 -0
  179. package/dist/core/delegation/worker-lifecycle.d.ts.map +1 -0
  180. package/dist/core/delegation/worker-lifecycle.js +339 -0
  181. package/dist/core/delegation/worker-lifecycle.js.map +1 -0
  182. package/dist/core/delegation/worker-notification-coordinator.d.ts +36 -0
  183. package/dist/core/delegation/worker-notification-coordinator.d.ts.map +1 -0
  184. package/dist/core/delegation/worker-notification-coordinator.js +90 -0
  185. package/dist/core/delegation/worker-notification-coordinator.js.map +1 -0
  186. package/dist/core/delegation/worker-profile-resolver.d.ts +55 -0
  187. package/dist/core/delegation/worker-profile-resolver.d.ts.map +1 -0
  188. package/dist/core/delegation/worker-profile-resolver.js +113 -0
  189. package/dist/core/delegation/worker-profile-resolver.js.map +1 -0
  190. package/dist/core/delegation/worker-runner.d.ts +25 -14
  191. package/dist/core/delegation/worker-runner.d.ts.map +1 -1
  192. package/dist/core/delegation/worker-runner.js +122 -53
  193. package/dist/core/delegation/worker-runner.js.map +1 -1
  194. package/dist/core/delegation/worker-task-label.d.ts +3 -0
  195. package/dist/core/delegation/worker-task-label.d.ts.map +1 -0
  196. package/dist/core/delegation/worker-task-label.js +11 -0
  197. package/dist/core/delegation/worker-task-label.js.map +1 -0
  198. package/dist/core/doctor.d.ts +8 -0
  199. package/dist/core/doctor.d.ts.map +1 -1
  200. package/dist/core/doctor.js +32 -1
  201. package/dist/core/doctor.js.map +1 -1
  202. package/dist/core/extension-import-authority.d.ts +6 -0
  203. package/dist/core/extension-import-authority.d.ts.map +1 -0
  204. package/dist/core/extension-import-authority.js +10 -0
  205. package/dist/core/extension-import-authority.js.map +1 -0
  206. package/dist/core/extensions/index.d.ts +1 -1
  207. package/dist/core/extensions/index.d.ts.map +1 -1
  208. package/dist/core/extensions/index.js.map +1 -1
  209. package/dist/core/extensions/loader.d.ts +5 -1
  210. package/dist/core/extensions/loader.d.ts.map +1 -1
  211. package/dist/core/extensions/loader.js +52 -18
  212. package/dist/core/extensions/loader.js.map +1 -1
  213. package/dist/core/extensions/runner.d.ts +3 -0
  214. package/dist/core/extensions/runner.d.ts.map +1 -1
  215. package/dist/core/extensions/runner.js +20 -5
  216. package/dist/core/extensions/runner.js.map +1 -1
  217. package/dist/core/extensions/stale-context.d.ts +2 -0
  218. package/dist/core/extensions/stale-context.d.ts.map +1 -0
  219. package/dist/core/extensions/stale-context.js +2 -0
  220. package/dist/core/extensions/stale-context.js.map +1 -0
  221. package/dist/core/extensions/storage.d.ts +8 -0
  222. package/dist/core/extensions/storage.d.ts.map +1 -0
  223. package/dist/core/extensions/storage.js +28 -0
  224. package/dist/core/extensions/storage.js.map +1 -0
  225. package/dist/core/extensions/types.d.ts +78 -21
  226. package/dist/core/extensions/types.d.ts.map +1 -1
  227. package/dist/core/extensions/types.js.map +1 -1
  228. package/dist/core/failure-corpus.d.ts +1 -15
  229. package/dist/core/failure-corpus.d.ts.map +1 -1
  230. package/dist/core/failure-corpus.js +9 -37
  231. package/dist/core/failure-corpus.js.map +1 -1
  232. package/dist/core/foreground-recovery-controller.d.ts +53 -0
  233. package/dist/core/foreground-recovery-controller.d.ts.map +1 -0
  234. package/dist/core/foreground-recovery-controller.js +111 -0
  235. package/dist/core/foreground-recovery-controller.js.map +1 -0
  236. package/dist/core/gateways/channel-provider.d.ts +3 -0
  237. package/dist/core/gateways/channel-provider.d.ts.map +1 -1
  238. package/dist/core/gateways/channel-provider.js +31 -6
  239. package/dist/core/gateways/channel-provider.js.map +1 -1
  240. package/dist/core/goal-loop-controller.d.ts +14 -9
  241. package/dist/core/goal-loop-controller.d.ts.map +1 -1
  242. package/dist/core/goal-loop-controller.js +47 -75
  243. package/dist/core/goal-loop-controller.js.map +1 -1
  244. package/dist/core/goals/compact-goal-context.d.ts +11 -0
  245. package/dist/core/goals/compact-goal-context.d.ts.map +1 -0
  246. package/dist/core/goals/compact-goal-context.js +59 -0
  247. package/dist/core/goals/compact-goal-context.js.map +1 -0
  248. package/dist/core/goals/goal-acceptance.d.ts +11 -0
  249. package/dist/core/goals/goal-acceptance.d.ts.map +1 -0
  250. package/dist/core/goals/goal-acceptance.js +27 -0
  251. package/dist/core/goals/goal-acceptance.js.map +1 -0
  252. package/dist/core/goals/goal-auto-continue-controller.d.ts +28 -0
  253. package/dist/core/goals/goal-auto-continue-controller.d.ts.map +1 -0
  254. package/dist/core/goals/goal-auto-continue-controller.js +90 -0
  255. package/dist/core/goals/goal-auto-continue-controller.js.map +1 -0
  256. package/dist/core/goals/goal-continuation-controller.d.ts +2 -2
  257. package/dist/core/goals/goal-continuation-controller.d.ts.map +1 -1
  258. package/dist/core/goals/goal-continuation-controller.js +52 -11
  259. package/dist/core/goals/goal-continuation-controller.js.map +1 -1
  260. package/dist/core/goals/goal-continuation-defaults.d.ts +4 -29
  261. package/dist/core/goals/goal-continuation-defaults.d.ts.map +1 -1
  262. package/dist/core/goals/goal-continuation-defaults.js +4 -32
  263. package/dist/core/goals/goal-continuation-defaults.js.map +1 -1
  264. package/dist/core/goals/goal-continuation-prompt.d.ts +8 -18
  265. package/dist/core/goals/goal-continuation-prompt.d.ts.map +1 -1
  266. package/dist/core/goals/goal-continuation-prompt.js +9 -179
  267. package/dist/core/goals/goal-continuation-prompt.js.map +1 -1
  268. package/dist/core/goals/goal-lifecycle.d.ts +43 -0
  269. package/dist/core/goals/goal-lifecycle.d.ts.map +1 -0
  270. package/dist/core/goals/goal-lifecycle.js +102 -0
  271. package/dist/core/goals/goal-lifecycle.js.map +1 -0
  272. package/dist/core/goals/goal-record.d.ts +17 -0
  273. package/dist/core/goals/goal-record.d.ts.map +1 -0
  274. package/dist/core/goals/goal-record.js +31 -0
  275. package/dist/core/goals/goal-record.js.map +1 -0
  276. package/dist/core/goals/goal-runtime-snapshot.d.ts +11 -9
  277. package/dist/core/goals/goal-runtime-snapshot.d.ts.map +1 -1
  278. package/dist/core/goals/goal-runtime-snapshot.js +10 -8
  279. package/dist/core/goals/goal-runtime-snapshot.js.map +1 -1
  280. package/dist/core/goals/goal-session-controller.d.ts +42 -0
  281. package/dist/core/goals/goal-session-controller.d.ts.map +1 -0
  282. package/dist/core/goals/goal-session-controller.js +128 -0
  283. package/dist/core/goals/goal-session-controller.js.map +1 -0
  284. package/dist/core/goals/goal-state.d.ts +46 -25
  285. package/dist/core/goals/goal-state.d.ts.map +1 -1
  286. package/dist/core/goals/goal-state.js +91 -24
  287. package/dist/core/goals/goal-state.js.map +1 -1
  288. package/dist/core/goals/goal-tool-core.d.ts +9 -10
  289. package/dist/core/goals/goal-tool-core.d.ts.map +1 -1
  290. package/dist/core/goals/goal-tool-core.js +60 -75
  291. package/dist/core/goals/goal-tool-core.js.map +1 -1
  292. package/dist/core/goals/session-goal-state.d.ts +20 -12
  293. package/dist/core/goals/session-goal-state.d.ts.map +1 -1
  294. package/dist/core/goals/session-goal-state.js +133 -33
  295. package/dist/core/goals/session-goal-state.js.map +1 -1
  296. package/dist/core/human-input-controller.d.ts +47 -0
  297. package/dist/core/human-input-controller.d.ts.map +1 -0
  298. package/dist/core/human-input-controller.js +181 -0
  299. package/dist/core/human-input-controller.js.map +1 -0
  300. package/dist/core/human-input.d.ts +100 -0
  301. package/dist/core/human-input.d.ts.map +1 -0
  302. package/dist/core/human-input.js +362 -0
  303. package/dist/core/human-input.js.map +1 -0
  304. package/dist/core/index.d.ts +9 -1
  305. package/dist/core/index.d.ts.map +1 -1
  306. package/dist/core/index.js +9 -1
  307. package/dist/core/index.js.map +1 -1
  308. package/dist/core/{telemetry.d.ts → install-telemetry.d.ts} +1 -1
  309. package/dist/core/install-telemetry.d.ts.map +1 -0
  310. package/dist/core/{telemetry.js → install-telemetry.js} +1 -1
  311. package/dist/core/install-telemetry.js.map +1 -0
  312. package/dist/core/keybindings.d.ts +17 -1
  313. package/dist/core/keybindings.d.ts.map +1 -1
  314. package/dist/core/keybindings.js +24 -6
  315. package/dist/core/keybindings.js.map +1 -1
  316. package/dist/core/learning/learning-audit.d.ts +2 -4
  317. package/dist/core/learning/learning-audit.d.ts.map +1 -1
  318. package/dist/core/learning/learning-audit.js +9 -29
  319. package/dist/core/learning/learning-audit.js.map +1 -1
  320. package/dist/core/learning/learning-gate.d.ts.map +1 -1
  321. package/dist/core/learning/learning-gate.js +1 -6
  322. package/dist/core/learning/learning-gate.js.map +1 -1
  323. package/dist/core/learning/session-learning-decision.d.ts +2 -4
  324. package/dist/core/learning/session-learning-decision.d.ts.map +1 -1
  325. package/dist/core/learning/session-learning-decision.js +9 -29
  326. package/dist/core/learning/session-learning-decision.js.map +1 -1
  327. package/dist/core/local-runtime-controller.d.ts +1 -1
  328. package/dist/core/local-runtime-controller.d.ts.map +1 -1
  329. package/dist/core/local-runtime-controller.js.map +1 -1
  330. package/dist/core/memory-controller.d.ts.map +1 -1
  331. package/dist/core/memory-controller.js +4 -4
  332. package/dist/core/memory-controller.js.map +1 -1
  333. package/dist/core/model-capability.d.ts +0 -19
  334. package/dist/core/model-capability.d.ts.map +1 -1
  335. package/dist/core/model-capability.js +1 -19
  336. package/dist/core/model-capability.js.map +1 -1
  337. package/dist/core/model-registry.d.ts +6 -1
  338. package/dist/core/model-registry.d.ts.map +1 -1
  339. package/dist/core/model-registry.js +13 -5
  340. package/dist/core/model-registry.js.map +1 -1
  341. package/dist/core/model-resolver.d.ts +17 -2
  342. package/dist/core/model-resolver.d.ts.map +1 -1
  343. package/dist/core/model-resolver.js +38 -25
  344. package/dist/core/model-resolver.js.map +1 -1
  345. package/dist/core/model-router/intent-classifier.d.ts +1 -4
  346. package/dist/core/model-router/intent-classifier.d.ts.map +1 -1
  347. package/dist/core/model-router/intent-classifier.js +1 -156
  348. package/dist/core/model-router/intent-classifier.js.map +1 -1
  349. package/dist/core/model-router-controller.d.ts +1 -1
  350. package/dist/core/model-router-controller.d.ts.map +1 -1
  351. package/dist/core/model-router-controller.js +2 -2
  352. package/dist/core/model-router-controller.js.map +1 -1
  353. package/dist/core/model-selection-controller.d.ts +5 -5
  354. package/dist/core/model-selection-controller.d.ts.map +1 -1
  355. package/dist/core/model-selection-controller.js.map +1 -1
  356. package/dist/core/model-tool-protocol.d.ts +23 -0
  357. package/dist/core/model-tool-protocol.d.ts.map +1 -0
  358. package/dist/core/model-tool-protocol.js +43 -0
  359. package/dist/core/model-tool-protocol.js.map +1 -0
  360. package/dist/core/models/adaptation-store.d.ts +4 -6
  361. package/dist/core/models/adaptation-store.d.ts.map +1 -1
  362. package/dist/core/models/adaptation-store.js +95 -83
  363. package/dist/core/models/adaptation-store.js.map +1 -1
  364. package/dist/core/models/fitness-store.d.ts +2 -12
  365. package/dist/core/models/fitness-store.d.ts.map +1 -1
  366. package/dist/core/models/fitness-store.js +84 -57
  367. package/dist/core/models/fitness-store.js.map +1 -1
  368. package/dist/core/models/host-state-store.d.ts +34 -0
  369. package/dist/core/models/host-state-store.d.ts.map +1 -0
  370. package/dist/core/models/host-state-store.js +86 -0
  371. package/dist/core/models/host-state-store.js.map +1 -0
  372. package/dist/core/orchestration/agent-resume.d.ts +24 -0
  373. package/dist/core/orchestration/agent-resume.d.ts.map +1 -0
  374. package/dist/core/orchestration/agent-resume.js +90 -0
  375. package/dist/core/orchestration/agent-resume.js.map +1 -0
  376. package/dist/core/orchestration/capability-gateway.d.ts +61 -0
  377. package/dist/core/orchestration/capability-gateway.d.ts.map +1 -0
  378. package/dist/core/orchestration/capability-gateway.js +152 -0
  379. package/dist/core/orchestration/capability-gateway.js.map +1 -0
  380. package/dist/core/orchestration/contracts.d.ts +343 -0
  381. package/dist/core/orchestration/contracts.d.ts.map +1 -0
  382. package/dist/core/orchestration/contracts.js +135 -0
  383. package/dist/core/orchestration/contracts.js.map +1 -0
  384. package/dist/core/orchestration/delegation-ledger.d.ts +56 -0
  385. package/dist/core/orchestration/delegation-ledger.d.ts.map +1 -0
  386. package/dist/core/orchestration/delegation-ledger.js +200 -0
  387. package/dist/core/orchestration/delegation-ledger.js.map +1 -0
  388. package/dist/core/orchestration/event-store.d.ts +83 -0
  389. package/dist/core/orchestration/event-store.d.ts.map +1 -0
  390. package/dist/core/orchestration/event-store.js +560 -0
  391. package/dist/core/orchestration/event-store.js.map +1 -0
  392. package/dist/core/orchestration/lane-tool-manifests.d.ts +9 -0
  393. package/dist/core/orchestration/lane-tool-manifests.d.ts.map +1 -0
  394. package/dist/core/orchestration/lane-tool-manifests.js +37 -0
  395. package/dist/core/orchestration/lane-tool-manifests.js.map +1 -0
  396. package/dist/core/orchestration/model-binding.d.ts +15 -0
  397. package/dist/core/orchestration/model-binding.d.ts.map +1 -0
  398. package/dist/core/orchestration/model-binding.js +29 -0
  399. package/dist/core/orchestration/model-binding.js.map +1 -0
  400. package/dist/core/orchestration/policy-compiler.d.ts +49 -0
  401. package/dist/core/orchestration/policy-compiler.d.ts.map +1 -0
  402. package/dist/core/orchestration/policy-compiler.js +191 -0
  403. package/dist/core/orchestration/policy-compiler.js.map +1 -0
  404. package/dist/core/orchestration/policy-gate.d.ts +18 -0
  405. package/dist/core/orchestration/policy-gate.d.ts.map +1 -0
  406. package/dist/core/orchestration/policy-gate.js +24 -0
  407. package/dist/core/orchestration/policy-gate.js.map +1 -0
  408. package/dist/core/orchestration/profile-registry.d.ts +51 -0
  409. package/dist/core/orchestration/profile-registry.d.ts.map +1 -0
  410. package/dist/core/orchestration/profile-registry.js +393 -0
  411. package/dist/core/orchestration/profile-registry.js.map +1 -0
  412. package/dist/core/orchestration/profile-store.d.ts +31 -0
  413. package/dist/core/orchestration/profile-store.d.ts.map +1 -0
  414. package/dist/core/orchestration/profile-store.js +136 -0
  415. package/dist/core/orchestration/profile-store.js.map +1 -0
  416. package/dist/core/orchestration/risk-budget.d.ts +9 -0
  417. package/dist/core/orchestration/risk-budget.d.ts.map +1 -0
  418. package/dist/core/orchestration/risk-budget.js +48 -0
  419. package/dist/core/orchestration/risk-budget.js.map +1 -0
  420. package/dist/core/orchestration/task-runtime.d.ts +168 -0
  421. package/dist/core/orchestration/task-runtime.d.ts.map +1 -0
  422. package/dist/core/orchestration/task-runtime.js +1600 -0
  423. package/dist/core/orchestration/task-runtime.js.map +1 -0
  424. package/dist/core/orchestration/work-state-projection.d.ts +32 -0
  425. package/dist/core/orchestration/work-state-projection.d.ts.map +1 -0
  426. package/dist/core/orchestration/work-state-projection.js +116 -0
  427. package/dist/core/orchestration/work-state-projection.js.map +1 -0
  428. package/dist/core/orchestration/worker-execution-contract.d.ts +21 -0
  429. package/dist/core/orchestration/worker-execution-contract.d.ts.map +1 -0
  430. package/dist/core/orchestration/worker-execution-contract.js +179 -0
  431. package/dist/core/orchestration/worker-execution-contract.js.map +1 -0
  432. package/dist/core/orchestration/worker-result-adapter.d.ts +21 -0
  433. package/dist/core/orchestration/worker-result-adapter.d.ts.map +1 -0
  434. package/dist/core/orchestration/worker-result-adapter.js +109 -0
  435. package/dist/core/orchestration/worker-result-adapter.js.map +1 -0
  436. package/dist/core/package-manager.d.ts.map +1 -1
  437. package/dist/core/package-manager.js +20 -3
  438. package/dist/core/package-manager.js.map +1 -1
  439. package/dist/core/process-identity.d.ts +11 -0
  440. package/dist/core/process-identity.d.ts.map +1 -0
  441. package/dist/core/process-identity.js +26 -0
  442. package/dist/core/process-identity.js.map +1 -0
  443. package/dist/core/process-matrix/codes.d.ts +14 -3
  444. package/dist/core/process-matrix/codes.d.ts.map +1 -1
  445. package/dist/core/process-matrix/codes.js.map +1 -1
  446. package/dist/core/process-matrix/resume-launcher.d.ts +26 -0
  447. package/dist/core/process-matrix/resume-launcher.d.ts.map +1 -0
  448. package/dist/core/process-matrix/resume-launcher.js +62 -0
  449. package/dist/core/process-matrix/resume-launcher.js.map +1 -0
  450. package/dist/core/process-matrix/runtime.d.ts +37 -22
  451. package/dist/core/process-matrix/runtime.d.ts.map +1 -1
  452. package/dist/core/process-matrix/runtime.js +399 -76
  453. package/dist/core/process-matrix/runtime.js.map +1 -1
  454. package/dist/core/process-matrix/store.d.ts +5 -2
  455. package/dist/core/process-matrix/store.d.ts.map +1 -1
  456. package/dist/core/process-matrix/store.js +123 -14
  457. package/dist/core/process-matrix/store.js.map +1 -1
  458. package/dist/core/process-matrix/supervisor.d.ts +10 -7
  459. package/dist/core/process-matrix/supervisor.d.ts.map +1 -1
  460. package/dist/core/process-matrix/supervisor.js +45 -14
  461. package/dist/core/process-matrix/supervisor.js.map +1 -1
  462. package/dist/core/profile-filter-controller.d.ts +8 -1
  463. package/dist/core/profile-filter-controller.d.ts.map +1 -1
  464. package/dist/core/profile-filter-controller.js +23 -5
  465. package/dist/core/profile-filter-controller.js.map +1 -1
  466. package/dist/core/profile-registry.d.ts.map +1 -1
  467. package/dist/core/profile-registry.js +6 -8
  468. package/dist/core/profile-registry.js.map +1 -1
  469. package/dist/core/prompt-templates.d.ts +1 -0
  470. package/dist/core/prompt-templates.d.ts.map +1 -1
  471. package/dist/core/prompt-templates.js +18 -29
  472. package/dist/core/prompt-templates.js.map +1 -1
  473. package/dist/core/reflection-controller.d.ts +5 -5
  474. package/dist/core/reflection-controller.d.ts.map +1 -1
  475. package/dist/core/reflection-controller.js +5 -2
  476. package/dist/core/reflection-controller.js.map +1 -1
  477. package/dist/core/reload-blockers.d.ts.map +1 -1
  478. package/dist/core/reload-blockers.js +6 -8
  479. package/dist/core/reload-blockers.js.map +1 -1
  480. package/dist/core/request-auth.d.ts +7 -0
  481. package/dist/core/request-auth.d.ts.map +1 -0
  482. package/dist/core/request-auth.js +8 -0
  483. package/dist/core/request-auth.js.map +1 -0
  484. package/dist/core/research/evidence-bundle.d.ts.map +1 -1
  485. package/dist/core/research/evidence-bundle.js +1 -6
  486. package/dist/core/research/evidence-bundle.js.map +1 -1
  487. package/dist/core/research/lane-model-resolver.d.ts +33 -0
  488. package/dist/core/research/lane-model-resolver.d.ts.map +1 -0
  489. package/dist/core/research/lane-model-resolver.js +65 -0
  490. package/dist/core/research/lane-model-resolver.js.map +1 -0
  491. package/dist/core/research/model-fitness-controller.d.ts +38 -0
  492. package/dist/core/research/model-fitness-controller.d.ts.map +1 -0
  493. package/dist/core/research/model-fitness-controller.js +106 -0
  494. package/dist/core/research/model-fitness-controller.js.map +1 -0
  495. package/dist/core/research/model-fitness.d.ts +1 -1
  496. package/dist/core/research/model-fitness.d.ts.map +1 -1
  497. package/dist/core/research/model-fitness.js +4 -4
  498. package/dist/core/research/model-fitness.js.map +1 -1
  499. package/dist/core/research/research-gate.d.ts.map +1 -1
  500. package/dist/core/research/research-gate.js +7 -7
  501. package/dist/core/research/research-gate.js.map +1 -1
  502. package/dist/core/research/research-lane-controller.d.ts +62 -0
  503. package/dist/core/research/research-lane-controller.d.ts.map +1 -0
  504. package/dist/core/research/research-lane-controller.js +292 -0
  505. package/dist/core/research/research-lane-controller.js.map +1 -0
  506. package/dist/core/research/session-evidence-bundle.d.ts +2 -4
  507. package/dist/core/research/session-evidence-bundle.d.ts.map +1 -1
  508. package/dist/core/research/session-evidence-bundle.js +10 -46
  509. package/dist/core/research/session-evidence-bundle.js.map +1 -1
  510. package/dist/core/resource-loader.d.ts.map +1 -1
  511. package/dist/core/resource-loader.js +23 -8
  512. package/dist/core/resource-loader.js.map +1 -1
  513. package/dist/core/risk-classifier.d.ts +6 -0
  514. package/dist/core/risk-classifier.d.ts.map +1 -0
  515. package/dist/core/risk-classifier.js +233 -0
  516. package/dist/core/risk-classifier.js.map +1 -0
  517. package/dist/core/runtime-builder.d.ts +41 -23
  518. package/dist/core/runtime-builder.d.ts.map +1 -1
  519. package/dist/core/runtime-builder.js +365 -253
  520. package/dist/core/runtime-builder.js.map +1 -1
  521. package/dist/core/sdk.d.ts +6 -3
  522. package/dist/core/sdk.d.ts.map +1 -1
  523. package/dist/core/sdk.js +68 -25
  524. package/dist/core/sdk.js.map +1 -1
  525. package/dist/core/secrets/credential-exposure-guard.d.ts +9 -0
  526. package/dist/core/secrets/credential-exposure-guard.d.ts.map +1 -0
  527. package/dist/core/secrets/credential-exposure-guard.js +241 -0
  528. package/dist/core/secrets/credential-exposure-guard.js.map +1 -0
  529. package/dist/core/secrets/secret-dotenv.d.ts +27 -0
  530. package/dist/core/secrets/secret-dotenv.d.ts.map +1 -0
  531. package/dist/core/secrets/secret-dotenv.js +183 -0
  532. package/dist/core/secrets/secret-dotenv.js.map +1 -0
  533. package/dist/core/secrets/secret-vault-format.d.ts +112 -0
  534. package/dist/core/secrets/secret-vault-format.d.ts.map +1 -0
  535. package/dist/core/secrets/secret-vault-format.js +397 -0
  536. package/dist/core/secrets/secret-vault-format.js.map +1 -0
  537. package/dist/core/secrets/secret-vault.d.ts +72 -0
  538. package/dist/core/secrets/secret-vault.d.ts.map +1 -0
  539. package/dist/core/secrets/secret-vault.js +671 -0
  540. package/dist/core/secrets/secret-vault.js.map +1 -0
  541. package/dist/core/session-analytics.d.ts +4 -23
  542. package/dist/core/session-analytics.d.ts.map +1 -1
  543. package/dist/core/session-analytics.js +67 -70
  544. package/dist/core/session-analytics.js.map +1 -1
  545. package/dist/core/session-image-store.d.ts +33 -0
  546. package/dist/core/session-image-store.d.ts.map +1 -0
  547. package/dist/core/session-image-store.js +283 -0
  548. package/dist/core/session-image-store.js.map +1 -0
  549. package/dist/core/session-role.d.ts +11 -4
  550. package/dist/core/session-role.d.ts.map +1 -1
  551. package/dist/core/session-role.js +24 -5
  552. package/dist/core/session-role.js.map +1 -1
  553. package/dist/core/session-snapshot.d.ts +34 -0
  554. package/dist/core/session-snapshot.d.ts.map +1 -0
  555. package/dist/core/session-snapshot.js +68 -0
  556. package/dist/core/session-snapshot.js.map +1 -0
  557. package/dist/core/session-supervision-runtime.d.ts +31 -0
  558. package/dist/core/session-supervision-runtime.d.ts.map +1 -0
  559. package/dist/core/session-supervision-runtime.js +97 -0
  560. package/dist/core/session-supervision-runtime.js.map +1 -0
  561. package/dist/core/session-tree-navigator.d.ts +4 -6
  562. package/dist/core/session-tree-navigator.d.ts.map +1 -1
  563. package/dist/core/session-tree-navigator.js +4 -1
  564. package/dist/core/session-tree-navigator.js.map +1 -1
  565. package/dist/core/settings-manager.d.ts +10 -5
  566. package/dist/core/settings-manager.d.ts.map +1 -1
  567. package/dist/core/settings-manager.js +81 -29
  568. package/dist/core/settings-manager.js.map +1 -1
  569. package/dist/core/slash-commands.d.ts.map +1 -1
  570. package/dist/core/slash-commands.js +2 -2
  571. package/dist/core/slash-commands.js.map +1 -1
  572. package/dist/core/tasks/session-task-state.d.ts +2 -4
  573. package/dist/core/tasks/session-task-state.d.ts.map +1 -1
  574. package/dist/core/tasks/session-task-state.js +10 -28
  575. package/dist/core/tasks/session-task-state.js.map +1 -1
  576. package/dist/core/tasks/task-projection.d.ts +20 -0
  577. package/dist/core/tasks/task-projection.d.ts.map +1 -0
  578. package/dist/core/tasks/task-projection.js +47 -0
  579. package/dist/core/tasks/task-projection.js.map +1 -0
  580. package/dist/core/tasks/task-state.d.ts +4 -0
  581. package/dist/core/tasks/task-state.d.ts.map +1 -1
  582. package/dist/core/tasks/task-state.js +28 -11
  583. package/dist/core/tasks/task-state.js.map +1 -1
  584. package/dist/core/tool-capability-policy.d.ts +13 -0
  585. package/dist/core/tool-capability-policy.d.ts.map +1 -0
  586. package/dist/core/tool-capability-policy.js +86 -0
  587. package/dist/core/tool-capability-policy.js.map +1 -0
  588. package/dist/core/tool-gate-controller.d.ts.map +1 -1
  589. package/dist/core/tool-gate-controller.js +8 -2
  590. package/dist/core/tool-gate-controller.js.map +1 -1
  591. package/dist/core/tool-protocol-controller.d.ts +89 -0
  592. package/dist/core/tool-protocol-controller.d.ts.map +1 -0
  593. package/dist/core/tool-protocol-controller.js +512 -0
  594. package/dist/core/tool-protocol-controller.js.map +1 -0
  595. package/dist/core/tool-recovery-log-records.d.ts +2 -3
  596. package/dist/core/tool-recovery-log-records.d.ts.map +1 -1
  597. package/dist/core/tool-recovery-log-records.js +9 -35
  598. package/dist/core/tool-recovery-log-records.js.map +1 -1
  599. package/dist/core/tool-recovery-stats.d.ts +21 -1
  600. package/dist/core/tool-recovery-stats.d.ts.map +1 -1
  601. package/dist/core/tool-recovery-stats.js.map +1 -1
  602. package/dist/core/tool-selection/tool-performance-store.d.ts +3 -7
  603. package/dist/core/tool-selection/tool-performance-store.d.ts.map +1 -1
  604. package/dist/core/tool-selection/tool-performance-store.js +97 -138
  605. package/dist/core/tool-selection/tool-performance-store.js.map +1 -1
  606. package/dist/core/tools/ask-question.d.ts +124 -0
  607. package/dist/core/tools/ask-question.d.ts.map +1 -0
  608. package/dist/core/tools/ask-question.js +693 -0
  609. package/dist/core/tools/ask-question.js.map +1 -0
  610. package/dist/core/tools/bash.d.ts +5 -0
  611. package/dist/core/tools/bash.d.ts.map +1 -1
  612. package/dist/core/tools/bash.js +59 -5
  613. package/dist/core/tools/bash.js.map +1 -1
  614. package/dist/core/tools/delegate-status.d.ts +31 -3
  615. package/dist/core/tools/delegate-status.d.ts.map +1 -1
  616. package/dist/core/tools/delegate-status.js +148 -29
  617. package/dist/core/tools/delegate-status.js.map +1 -1
  618. package/dist/core/tools/delegate.d.ts +15 -13
  619. package/dist/core/tools/delegate.d.ts.map +1 -1
  620. package/dist/core/tools/delegate.js +106 -23
  621. package/dist/core/tools/delegate.js.map +1 -1
  622. package/dist/core/tools/extensionify.d.ts.map +1 -1
  623. package/dist/core/tools/extensionify.js +1 -0
  624. package/dist/core/tools/extensionify.js.map +1 -1
  625. package/dist/core/tools/git-filter.d.ts +1 -8
  626. package/dist/core/tools/git-filter.d.ts.map +1 -1
  627. package/dist/core/tools/git-filter.js +2 -63
  628. package/dist/core/tools/git-filter.js.map +1 -1
  629. package/dist/core/tools/goal.d.ts +10 -8
  630. package/dist/core/tools/goal.d.ts.map +1 -1
  631. package/dist/core/tools/goal.js +106 -28
  632. package/dist/core/tools/goal.js.map +1 -1
  633. package/dist/core/tools/index.d.ts +1 -0
  634. package/dist/core/tools/index.d.ts.map +1 -1
  635. package/dist/core/tools/index.js +1 -0
  636. package/dist/core/tools/index.js.map +1 -1
  637. package/dist/core/tools/model-fitness.d.ts.map +1 -1
  638. package/dist/core/tools/model-fitness.js +2 -2
  639. package/dist/core/tools/model-fitness.js.map +1 -1
  640. package/dist/core/tools/orchestration-panel.d.ts +40 -0
  641. package/dist/core/tools/orchestration-panel.d.ts.map +1 -0
  642. package/dist/core/tools/orchestration-panel.js +124 -0
  643. package/dist/core/tools/orchestration-panel.js.map +1 -0
  644. package/dist/core/tools/output-accumulator.d.ts +11 -0
  645. package/dist/core/tools/output-accumulator.d.ts.map +1 -1
  646. package/dist/core/tools/output-accumulator.js +36 -3
  647. package/dist/core/tools/output-accumulator.js.map +1 -1
  648. package/dist/core/tools/python.d.ts +2 -0
  649. package/dist/core/tools/python.d.ts.map +1 -1
  650. package/dist/core/tools/python.js +3 -1
  651. package/dist/core/tools/python.js.map +1 -1
  652. package/dist/core/tools/read.d.ts.map +1 -1
  653. package/dist/core/tools/read.js +1 -1
  654. package/dist/core/tools/read.js.map +1 -1
  655. package/dist/core/tools/run-process.d.ts +26 -0
  656. package/dist/core/tools/run-process.d.ts.map +1 -0
  657. package/dist/core/tools/run-process.js +138 -0
  658. package/dist/core/tools/run-process.js.map +1 -0
  659. package/dist/core/tools/search-command-guard.d.ts +14 -0
  660. package/dist/core/tools/search-command-guard.d.ts.map +1 -0
  661. package/dist/core/tools/search-command-guard.js +333 -0
  662. package/dist/core/tools/search-command-guard.js.map +1 -0
  663. package/dist/core/tools/secret-store.d.ts +38 -0
  664. package/dist/core/tools/secret-store.d.ts.map +1 -0
  665. package/dist/core/tools/secret-store.js +412 -0
  666. package/dist/core/tools/secret-store.js.map +1 -0
  667. package/dist/core/tools/shell-command-parser.d.ts +16 -0
  668. package/dist/core/tools/shell-command-parser.d.ts.map +1 -0
  669. package/dist/core/tools/shell-command-parser.js +113 -0
  670. package/dist/core/tools/shell-command-parser.js.map +1 -0
  671. package/dist/core/tools/task-steps.d.ts +2 -0
  672. package/dist/core/tools/task-steps.d.ts.map +1 -1
  673. package/dist/core/tools/task-steps.js +99 -0
  674. package/dist/core/tools/task-steps.js.map +1 -1
  675. package/dist/core/tools/tmux-dispatch.d.ts +3 -5
  676. package/dist/core/tools/tmux-dispatch.d.ts.map +1 -1
  677. package/dist/core/tools/tmux-dispatch.js +4 -4
  678. package/dist/core/tools/tmux-dispatch.js.map +1 -1
  679. package/dist/core/tools/windows-shell-engine.d.ts.map +1 -1
  680. package/dist/core/tools/windows-shell-engine.js +4 -6
  681. package/dist/core/tools/windows-shell-engine.js.map +1 -1
  682. package/dist/core/util/atomic-file.d.ts +6 -2
  683. package/dist/core/util/atomic-file.d.ts.map +1 -1
  684. package/dist/core/util/atomic-file.js +4 -4
  685. package/dist/core/util/atomic-file.js.map +1 -1
  686. package/dist/core/util/bounded-jsonl.d.ts +10 -0
  687. package/dist/core/util/bounded-jsonl.d.ts.map +1 -0
  688. package/dist/core/util/bounded-jsonl.js +75 -0
  689. package/dist/core/util/bounded-jsonl.js.map +1 -0
  690. package/dist/core/util/value-guards.d.ts +5 -0
  691. package/dist/core/util/value-guards.d.ts.map +1 -0
  692. package/dist/core/util/value-guards.js +12 -0
  693. package/dist/core/util/value-guards.js.map +1 -0
  694. package/dist/core/worktree-sync/store.d.ts +3 -3
  695. package/dist/core/worktree-sync/store.d.ts.map +1 -1
  696. package/dist/core/worktree-sync/store.js +10 -5
  697. package/dist/core/worktree-sync/store.js.map +1 -1
  698. package/dist/index.d.ts +15 -4
  699. package/dist/index.d.ts.map +1 -1
  700. package/dist/index.js +14 -3
  701. package/dist/index.js.map +1 -1
  702. package/dist/main.d.ts.map +1 -1
  703. package/dist/main.js +149 -51
  704. package/dist/main.js.map +1 -1
  705. package/dist/migrations.d.ts +4 -6
  706. package/dist/migrations.d.ts.map +1 -1
  707. package/dist/migrations.js +186 -28
  708. package/dist/migrations.js.map +1 -1
  709. package/dist/modes/interactive/auth-dialogs-controller.d.ts +4 -0
  710. package/dist/modes/interactive/auth-dialogs-controller.d.ts.map +1 -1
  711. package/dist/modes/interactive/auth-dialogs-controller.js +60 -1
  712. package/dist/modes/interactive/auth-dialogs-controller.js.map +1 -1
  713. package/dist/modes/interactive/clipboard-input.d.ts +7 -1
  714. package/dist/modes/interactive/clipboard-input.d.ts.map +1 -1
  715. package/dist/modes/interactive/clipboard-input.js +44 -6
  716. package/dist/modes/interactive/clipboard-input.js.map +1 -1
  717. package/dist/modes/interactive/components/activity-lane.d.ts +55 -0
  718. package/dist/modes/interactive/components/activity-lane.d.ts.map +1 -0
  719. package/dist/modes/interactive/components/activity-lane.js +304 -0
  720. package/dist/modes/interactive/components/activity-lane.js.map +1 -0
  721. package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
  722. package/dist/modes/interactive/components/assistant-message.js +19 -10
  723. package/dist/modes/interactive/components/assistant-message.js.map +1 -1
  724. package/dist/modes/interactive/components/expandable-text.d.ts +12 -0
  725. package/dist/modes/interactive/components/expandable-text.d.ts.map +1 -0
  726. package/dist/modes/interactive/components/expandable-text.js +17 -0
  727. package/dist/modes/interactive/components/expandable-text.js.map +1 -0
  728. package/dist/modes/interactive/components/extension-editor.d.ts +15 -1
  729. package/dist/modes/interactive/components/extension-editor.d.ts.map +1 -1
  730. package/dist/modes/interactive/components/extension-editor.js +30 -21
  731. package/dist/modes/interactive/components/extension-editor.js.map +1 -1
  732. package/dist/modes/interactive/components/extension-input.d.ts +1 -0
  733. package/dist/modes/interactive/components/extension-input.d.ts.map +1 -1
  734. package/dist/modes/interactive/components/extension-input.js +6 -1
  735. package/dist/modes/interactive/components/extension-input.js.map +1 -1
  736. package/dist/modes/interactive/components/scoped-models-selector.d.ts +2 -2
  737. package/dist/modes/interactive/components/scoped-models-selector.d.ts.map +1 -1
  738. package/dist/modes/interactive/components/scoped-models-selector.js +23 -14
  739. package/dist/modes/interactive/components/scoped-models-selector.js.map +1 -1
  740. package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
  741. package/dist/modes/interactive/components/settings-selector.js +6 -6
  742. package/dist/modes/interactive/components/settings-selector.js.map +1 -1
  743. package/dist/modes/interactive/components/tool-execution.d.ts +19 -11
  744. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  745. package/dist/modes/interactive/components/tool-execution.js +53 -20
  746. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  747. package/dist/modes/interactive/components/tool-group.d.ts.map +1 -1
  748. package/dist/modes/interactive/components/tool-group.js +3 -0
  749. package/dist/modes/interactive/components/tool-group.js.map +1 -1
  750. package/dist/modes/interactive/components/usage-action-selector.d.ts +16 -0
  751. package/dist/modes/interactive/components/usage-action-selector.d.ts.map +1 -0
  752. package/dist/modes/interactive/components/usage-action-selector.js +46 -0
  753. package/dist/modes/interactive/components/usage-action-selector.js.map +1 -0
  754. package/dist/modes/interactive/config-backup.d.ts.map +1 -1
  755. package/dist/modes/interactive/config-backup.js +5 -4
  756. package/dist/modes/interactive/config-backup.js.map +1 -1
  757. package/dist/modes/interactive/extension-ui-host.d.ts +14 -0
  758. package/dist/modes/interactive/extension-ui-host.d.ts.map +1 -1
  759. package/dist/modes/interactive/extension-ui-host.js +77 -15
  760. package/dist/modes/interactive/extension-ui-host.js.map +1 -1
  761. package/dist/modes/interactive/external-editor.d.ts +15 -0
  762. package/dist/modes/interactive/external-editor.d.ts.map +1 -1
  763. package/dist/modes/interactive/external-editor.js +27 -19
  764. package/dist/modes/interactive/external-editor.js.map +1 -1
  765. package/dist/modes/interactive/history-reload-math.d.ts +6 -2
  766. package/dist/modes/interactive/history-reload-math.d.ts.map +1 -1
  767. package/dist/modes/interactive/history-reload-math.js +10 -5
  768. package/dist/modes/interactive/history-reload-math.js.map +1 -1
  769. package/dist/modes/interactive/interactive-event-controller.d.ts +74 -0
  770. package/dist/modes/interactive/interactive-event-controller.d.ts.map +1 -0
  771. package/dist/modes/interactive/interactive-event-controller.js +328 -0
  772. package/dist/modes/interactive/interactive-event-controller.js.map +1 -0
  773. package/dist/modes/interactive/interactive-mode.d.ts +22 -24
  774. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  775. package/dist/modes/interactive/interactive-mode.js +245 -595
  776. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  777. package/dist/modes/interactive/key-handlers.d.ts.map +1 -1
  778. package/dist/modes/interactive/key-handlers.js +1 -1
  779. package/dist/modes/interactive/key-handlers.js.map +1 -1
  780. package/dist/modes/interactive/loaded-resources-view.d.ts +20 -0
  781. package/dist/modes/interactive/loaded-resources-view.d.ts.map +1 -0
  782. package/dist/modes/interactive/loaded-resources-view.js +147 -0
  783. package/dist/modes/interactive/loaded-resources-view.js.map +1 -0
  784. package/dist/modes/interactive/profile-menu-controller.d.ts.map +1 -1
  785. package/dist/modes/interactive/profile-menu-controller.js +7 -7
  786. package/dist/modes/interactive/profile-menu-controller.js.map +1 -1
  787. package/dist/modes/interactive/report-commands.d.ts.map +1 -1
  788. package/dist/modes/interactive/report-commands.js +21 -0
  789. package/dist/modes/interactive/report-commands.js.map +1 -1
  790. package/dist/modes/interactive/resource-display.d.ts.map +1 -1
  791. package/dist/modes/interactive/resource-display.js +8 -2
  792. package/dist/modes/interactive/resource-display.js.map +1 -1
  793. package/dist/modes/interactive/resource-shell-commands.d.ts +1 -5
  794. package/dist/modes/interactive/resource-shell-commands.d.ts.map +1 -1
  795. package/dist/modes/interactive/resource-shell-commands.js +0 -5
  796. package/dist/modes/interactive/resource-shell-commands.js.map +1 -1
  797. package/dist/modes/interactive/session-flow-commands.d.ts +27 -8
  798. package/dist/modes/interactive/session-flow-commands.d.ts.map +1 -1
  799. package/dist/modes/interactive/session-flow-commands.js +150 -64
  800. package/dist/modes/interactive/session-flow-commands.js.map +1 -1
  801. package/dist/modes/interactive/session-io-commands.d.ts.map +1 -1
  802. package/dist/modes/interactive/session-io-commands.js +16 -6
  803. package/dist/modes/interactive/session-io-commands.js.map +1 -1
  804. package/dist/modes/interactive/session-replacement-errors.d.ts +7 -0
  805. package/dist/modes/interactive/session-replacement-errors.d.ts.map +1 -0
  806. package/dist/modes/interactive/session-replacement-errors.js +15 -0
  807. package/dist/modes/interactive/session-replacement-errors.js.map +1 -0
  808. package/dist/modes/interactive/startup-checks.d.ts.map +1 -1
  809. package/dist/modes/interactive/startup-checks.js +1 -1
  810. package/dist/modes/interactive/startup-checks.js.map +1 -1
  811. package/dist/modes/interactive/usage-commands.d.ts +34 -0
  812. package/dist/modes/interactive/usage-commands.d.ts.map +1 -0
  813. package/dist/modes/interactive/usage-commands.js +225 -0
  814. package/dist/modes/interactive/usage-commands.js.map +1 -0
  815. package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
  816. package/dist/modes/rpc/rpc-mode.js +82 -23
  817. package/dist/modes/rpc/rpc-mode.js.map +1 -1
  818. package/dist/modes/rpc/rpc-types.d.ts +15 -0
  819. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  820. package/dist/modes/rpc/rpc-types.js +138 -1
  821. package/dist/modes/rpc/rpc-types.js.map +1 -1
  822. package/dist/utils/clipboard-image.d.ts.map +1 -1
  823. package/dist/utils/clipboard-image.js +2 -13
  824. package/dist/utils/clipboard-image.js.map +1 -1
  825. package/dist/utils/clipboard-native.d.ts +1 -0
  826. package/dist/utils/clipboard-native.d.ts.map +1 -1
  827. package/dist/utils/clipboard-native.js.map +1 -1
  828. package/dist/utils/clipboard.d.ts +1 -0
  829. package/dist/utils/clipboard.d.ts.map +1 -1
  830. package/dist/utils/clipboard.js +52 -1
  831. package/dist/utils/clipboard.js.map +1 -1
  832. package/dist/utils/platform.d.ts +3 -0
  833. package/dist/utils/platform.d.ts.map +1 -0
  834. package/dist/utils/platform.js +8 -0
  835. package/dist/utils/platform.js.map +1 -0
  836. package/dist/utils/shell.d.ts.map +1 -1
  837. package/dist/utils/shell.js +5 -3
  838. package/dist/utils/shell.js.map +1 -1
  839. package/dist/utils/version-check.d.ts.map +1 -1
  840. package/dist/utils/version-check.js +3 -1
  841. package/dist/utils/version-check.js.map +1 -1
  842. package/dist/utils/work-directory.d.ts +11 -0
  843. package/dist/utils/work-directory.d.ts.map +1 -1
  844. package/dist/utils/work-directory.js +30 -9
  845. package/dist/utils/work-directory.js.map +1 -1
  846. package/docs/UI_POLISH_ORCHESTRATION.md +38 -0
  847. package/docs/UI_QUALITY_ORCHESTRATION.md +28 -0
  848. package/docs/docs.json +4 -0
  849. package/docs/extensions.md +62 -2
  850. package/docs/harness-architecture.md +156 -0
  851. package/docs/keybindings.md +11 -1
  852. package/docs/process-matrix.md +59 -26
  853. package/docs/providers.md +9 -1
  854. package/docs/rpc.md +45 -2
  855. package/docs/sessions.md +15 -0
  856. package/docs/settings.md +125 -11
  857. package/docs/task-steps.md +8 -0
  858. package/docs/telemetry.md +19 -0
  859. package/docs/tmux-agent-manager.md +10 -3
  860. package/docs/ui-reference/README.md +9 -0
  861. package/docs/ui-reference/orchestration-after.txt +14 -0
  862. package/docs/ui-reference/orchestration-before.txt +13 -0
  863. package/docs/ui-reference/orchestration-reference.txt +16 -0
  864. package/docs/usage.md +22 -2
  865. package/docs/work-directory.md +19 -8
  866. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  867. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  868. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  869. package/examples/extensions/question.ts +34 -245
  870. package/examples/extensions/questionnaire.ts +41 -407
  871. package/examples/extensions/sandbox/package-lock.json +2 -2
  872. package/examples/extensions/sandbox/package.json +1 -1
  873. package/examples/extensions/with-deps/package-lock.json +2 -2
  874. package/examples/extensions/with-deps/package.json +1 -1
  875. package/npm-shrinkwrap.json +13 -13
  876. package/package.json +4 -4
  877. package/dist/core/delegation/session-worker-result.d.ts +0 -46
  878. package/dist/core/delegation/session-worker-result.d.ts.map +0 -1
  879. package/dist/core/delegation/session-worker-result.js +0 -113
  880. package/dist/core/delegation/session-worker-result.js.map +0 -1
  881. package/dist/core/delegation/worker-result.d.ts.map +0 -1
  882. package/dist/core/delegation/worker-result.js.map +0 -1
  883. package/dist/core/telemetry.d.ts.map +0 -1
  884. package/dist/core/telemetry.js.map +0 -1
@@ -8,10 +8,10 @@
8
8
  import { buildEntryId } from "./store.js";
9
9
  export function buildMasterEntry(facts) {
10
10
  return {
11
- entryId: buildEntryId("master", facts.sessionId),
11
+ entryId: buildEntryId("master", facts.agent.resumeContext.sessionId),
12
12
  role: "master",
13
+ agent: structuredClone(facts.agent),
13
14
  pid: facts.pid,
14
- sessionId: facts.sessionId,
15
15
  hostname: facts.hostname,
16
16
  startedAt: facts.now,
17
17
  heartbeatAt: facts.now,
@@ -20,10 +20,10 @@ export function buildMasterEntry(facts) {
20
20
  }
21
21
  export function buildWorkerEntry(facts) {
22
22
  const entry = {
23
- entryId: buildEntryId("worker", facts.sessionId),
23
+ entryId: buildEntryId("worker", facts.agent.resumeContext.sessionId),
24
24
  role: "worker",
25
+ agent: structuredClone(facts.agent),
25
26
  pid: facts.pid,
26
- sessionId: facts.sessionId,
27
27
  hostname: facts.hostname,
28
28
  startedAt: facts.now,
29
29
  heartbeatAt: facts.now,
@@ -32,14 +32,14 @@ export function buildWorkerEntry(facts) {
32
32
  };
33
33
  if (facts.parentSessionId !== undefined)
34
34
  entry.parentSessionId = facts.parentSessionId;
35
- if (facts.laneKey !== undefined)
36
- entry.laneKey = facts.laneKey;
37
35
  if (facts.tmuxSession !== undefined)
38
36
  entry.tmuxSession = facts.tmuxSession;
39
37
  if (facts.tmuxPanePid !== undefined)
40
38
  entry.tmuxPanePid = facts.tmuxPanePid;
41
39
  if (facts.taskRef !== undefined)
42
40
  entry.taskRef = facts.taskRef;
41
+ if (facts.taskSummary !== undefined)
42
+ entry.taskSummary = facts.taskSummary;
43
43
  return entry;
44
44
  }
45
45
  export function applyHeartbeat(entry, now) {
@@ -55,7 +55,7 @@ export function detectOrphanedWorkers(entries, deps) {
55
55
  return false;
56
56
  if (entry.status === "closed")
57
57
  return false;
58
- if (deps.ownSessionId !== undefined && entry.sessionId === deps.ownSessionId)
58
+ if (deps.ownSessionId !== undefined && entry.agent.resumeContext.sessionId === deps.ownSessionId)
59
59
  return false;
60
60
  if (entry.parentPid === undefined)
61
61
  return false;
@@ -71,6 +71,17 @@ export function markResumable(entry, payload, now) {
71
71
  export function markClosed(entry, now) {
72
72
  return { ...entry, status: "closed", heartbeatAt: now };
73
73
  }
74
+ export function markTerminal(entry, terminal, now) {
75
+ return {
76
+ ...markClosed(entry, now),
77
+ terminal: { code: terminal.code, signal: terminal.signal, observedAt: now },
78
+ };
79
+ }
80
+ export function markTerminalNotificationDelivered(entry, now) {
81
+ if (!entry.terminal)
82
+ return entry;
83
+ return { ...entry, terminal: { ...entry.terminal, notificationDeliveredAt: now } };
84
+ }
74
85
  /** Claim (or reclaim) an entry under a new parent: back to `running`, wind-down reason cleared. */
75
86
  export function applyAdoption(entry, adoption) {
76
87
  const next = { ...entry, status: "running", parentPid: adoption.parentPid };
@@ -97,21 +108,41 @@ export function pollWorkerDirective(freshEntry, knownParentPid, deps) {
97
108
  return { code: "none" };
98
109
  }
99
110
  /**
100
- * Prune `closed` entries and any `running`/`winding_down` entry whose OWN pid is dead (a crashed
101
- * process that never reached `closed`). `resumable`/`adopted` entries are kept until they age past
102
- * `resumableTtlMs` -- they carry a payload a future session may still pick up.
111
+ * Prune `closed` entries and unrecoverable dead processes. A dead Pi worker that was interrupted
112
+ * before persisting its own resumable transition is repaired from its already-durable logical-agent
113
+ * identity. `resumable`/`adopted` entries are kept until they age past `resumableTtlMs`.
103
114
  */
104
115
  export function reconcileMatrix(entries, deps) {
105
116
  const kept = [];
106
117
  const prunedEntryIds = [];
118
+ const recoveredEntryIds = [];
107
119
  for (const entry of entries) {
108
120
  if (entry.status === "closed") {
109
- prunedEntryIds.push(entry.entryId);
121
+ const terminalAt = Date.parse(entry.terminal?.observedAt ?? entry.heartbeatAt);
122
+ const terminalExpired = !Number.isFinite(terminalAt) || deps.now - terminalAt > deps.resumableTtlMs;
123
+ if (entry.terminal && !entry.terminal.notificationDeliveredAt && !terminalExpired)
124
+ kept.push(entry);
125
+ else
126
+ prunedEntryIds.push(entry.entryId);
110
127
  continue;
111
128
  }
112
129
  if (entry.status === "running" || entry.status === "winding_down") {
113
130
  if (!deps.isPidAlive(entry.pid)) {
114
- prunedEntryIds.push(entry.entryId);
131
+ if (entry.role === "worker" && entry.agent.resumeContext.provider === "pi") {
132
+ const payload = {
133
+ agent: structuredClone(entry.agent),
134
+ lastCode: "resumable",
135
+ };
136
+ if (entry.taskRef !== undefined)
137
+ payload.taskRef = entry.taskRef;
138
+ if (entry.taskSummary !== undefined)
139
+ payload.taskSummary = entry.taskSummary;
140
+ kept.push(markResumable(entry, payload, new Date(deps.now).toISOString()));
141
+ recoveredEntryIds.push(entry.entryId);
142
+ }
143
+ else {
144
+ prunedEntryIds.push(entry.entryId);
145
+ }
115
146
  continue;
116
147
  }
117
148
  kept.push(entry);
@@ -119,12 +150,12 @@ export function reconcileMatrix(entries, deps) {
119
150
  }
120
151
  // resumable / adopted: TTL-gated on the entry's own last heartbeat.
121
152
  const heartbeatMs = Date.parse(entry.heartbeatAt);
122
- if (Number.isFinite(heartbeatMs) && deps.now - heartbeatMs > deps.resumableTtlMs) {
153
+ if (!Number.isFinite(heartbeatMs) || deps.now - heartbeatMs > deps.resumableTtlMs) {
123
154
  prunedEntryIds.push(entry.entryId);
124
155
  continue;
125
156
  }
126
157
  kept.push(entry);
127
158
  }
128
- return { code: "reconciled", kept, prunedEntryIds };
159
+ return { code: "reconciled", kept, prunedEntryIds, recoveredEntryIds };
129
160
  }
130
161
  //# sourceMappingURL=supervisor.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"supervisor.js","sourceRoot":"","sources":["../../../src/core/process-matrix/supervisor.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,KAAK,CAAC,MAAM,KAAK,QAAQ,EAAE,CAAC;YAC/B,cAAc,CAAC,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;YACnC,SAAS;QACV,CAAC;QACD,IAAI,KAAK,CAAC,MAAM,KAAK,SAAS,IAAI,KAAK,CAAC,MAAM,KAAK,cAAc,EAAE,CAAC;YACnE,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,KAAK,CAAC,GAAG,CAAC,EAAE,CAAC;gBACjC,cAAc,CAAC,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;gBACnC,SAAS;YACV,CAAC;YACD,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;YACjB,SAAS;QACV,CAAC;QACD,oEAAoE;QACpE,MAAM,WAAW,GAAG,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC;QAClD,IAAI,MAAM,CAAC,QAAQ,CAAC,WAAW,CAAC,IAAI,IAAI,CAAC,GAAG,GAAG,WAAW,GAAG,IAAI,CAAC,cAAc,EAAE,CAAC;YAClF,cAAc,CAAC,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;YACnC,SAAS;QACV,CAAC;QACD,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IAClB,CAAC;IACD,OAAO,EAAE,IAAI,EAAE,YAAY,EAAE,IAAI,EAAE,cAAc,EAAE,CAAC;AAAA,CACpD","sourcesContent":["/**\n * Process-matrix supervisor: PURE state-transition functions over `ProcessMatrixEntry`. Every\n * function here takes its notion of \"now\" and process liveness as an explicit argument/dependency\n * -- no `Date.now()`, no `process.kill` inside this module -- so the whole lifecycle (orphan\n * detection, wind-down, adoption, reconcile) is deterministically testable without real timers or\n * real processes. `runtime.ts` is the only caller that supplies real deps and real I/O.\n */\n\nimport type {\n\tProcessMatrixEntry,\n\tReconcileMatrixResult,\n\tResumablePayload,\n\tWindDownReason,\n\tWorkerDirective,\n} from \"./codes.ts\";\nimport { buildEntryId } from \"./store.ts\";\n\nexport interface BuildMasterEntryFacts {\n\tsessionId: string;\n\tpid: number;\n\thostname: string;\n\tnow: string;\n}\n\nexport function buildMasterEntry(facts: BuildMasterEntryFacts): ProcessMatrixEntry {\n\treturn {\n\t\tentryId: buildEntryId(\"master\", facts.sessionId),\n\t\trole: \"master\",\n\t\tpid: facts.pid,\n\t\tsessionId: facts.sessionId,\n\t\thostname: facts.hostname,\n\t\tstartedAt: facts.now,\n\t\theartbeatAt: facts.now,\n\t\tstatus: \"running\",\n\t};\n}\n\nexport interface BuildWorkerEntryFacts {\n\tsessionId: string;\n\tpid: number;\n\thostname: string;\n\tnow: string;\n\tparentPid: number;\n\tparentSessionId?: string;\n\tlaneKey?: string;\n\ttmuxSession?: string;\n\ttmuxPanePid?: number;\n\ttaskRef?: string;\n}\n\nexport function buildWorkerEntry(facts: BuildWorkerEntryFacts): ProcessMatrixEntry {\n\tconst entry: ProcessMatrixEntry = {\n\t\tentryId: buildEntryId(\"worker\", facts.sessionId),\n\t\trole: \"worker\",\n\t\tpid: facts.pid,\n\t\tsessionId: facts.sessionId,\n\t\thostname: facts.hostname,\n\t\tstartedAt: facts.now,\n\t\theartbeatAt: facts.now,\n\t\tstatus: \"running\",\n\t\tparentPid: facts.parentPid,\n\t};\n\tif (facts.parentSessionId !== undefined) entry.parentSessionId = facts.parentSessionId;\n\tif (facts.laneKey !== undefined) entry.laneKey = facts.laneKey;\n\tif (facts.tmuxSession !== undefined) entry.tmuxSession = facts.tmuxSession;\n\tif (facts.tmuxPanePid !== undefined) entry.tmuxPanePid = facts.tmuxPanePid;\n\tif (facts.taskRef !== undefined) entry.taskRef = facts.taskRef;\n\treturn entry;\n}\n\nexport function applyHeartbeat(entry: ProcessMatrixEntry, now: string): ProcessMatrixEntry {\n\treturn { ...entry, heartbeatAt: now };\n}\n\nexport interface DetectOrphanedWorkersDeps {\n\tisPidAlive: (pid: number) => boolean;\n\t/** This session's own sessionId -- never treat yourself as an orphan you found. */\n\townSessionId?: string;\n}\n\n/**\n * Worker entries whose `parentPid` is dead, excluding this session's own entry and anything\n * already `closed` (a closed worker isn't \"orphaned\", it's already done).\n */\nexport function detectOrphanedWorkers(\n\tentries: ProcessMatrixEntry[],\n\tdeps: DetectOrphanedWorkersDeps,\n): ProcessMatrixEntry[] {\n\treturn entries.filter((entry) => {\n\t\tif (entry.role !== \"worker\") return false;\n\t\tif (entry.status === \"closed\") return false;\n\t\tif (deps.ownSessionId !== undefined && entry.sessionId === deps.ownSessionId) return false;\n\t\tif (entry.parentPid === undefined) return false;\n\t\treturn !deps.isPidAlive(entry.parentPid);\n\t});\n}\n\nexport function beginWindDown(entry: ProcessMatrixEntry, reason: WindDownReason, now: string): ProcessMatrixEntry {\n\treturn { ...entry, status: \"winding_down\", windDownReason: reason, heartbeatAt: now };\n}\n\nexport function markResumable(entry: ProcessMatrixEntry, payload: ResumablePayload, now: string): ProcessMatrixEntry {\n\treturn { ...entry, status: \"resumable\", resumable: payload, heartbeatAt: now };\n}\n\nexport function markClosed(entry: ProcessMatrixEntry, now: string): ProcessMatrixEntry {\n\treturn { ...entry, status: \"closed\", heartbeatAt: now };\n}\n\nexport interface AdoptionFacts {\n\tparentPid: number;\n\tparentSessionId?: string;\n}\n\n/** Claim (or reclaim) an entry under a new parent: back to `running`, wind-down reason cleared. */\nexport function applyAdoption(entry: ProcessMatrixEntry, adoption: AdoptionFacts): ProcessMatrixEntry {\n\tconst next: ProcessMatrixEntry = { ...entry, status: \"running\", parentPid: adoption.parentPid };\n\tdelete next.windDownReason;\n\tif (adoption.parentSessionId !== undefined) next.parentSessionId = adoption.parentSessionId;\n\treturn next;\n}\n\nexport interface PollWorkerDirectiveDeps {\n\tisPidAlive: (pid: number) => boolean;\n}\n\n/**\n * A worker calls this against its OWN freshly re-read entry to learn whether a master wrote a\n * directive into it: an adoption (a new, live `parentPid` the worker didn't already know about)\n * or a cooperative cleanup request (`windDownReason === \"user_cleanup\"`). `knownParentPid` is the\n * parent the worker itself currently believes it has -- an unchanged, still-known parentPid never\n * counts as a new adoption.\n */\nexport function pollWorkerDirective(\n\tfreshEntry: ProcessMatrixEntry,\n\tknownParentPid: number | undefined,\n\tdeps: PollWorkerDirectiveDeps,\n): WorkerDirective {\n\tif (freshEntry.windDownReason === \"user_cleanup\") return { code: \"user_cleanup\" };\n\tif (\n\t\tfreshEntry.parentPid !== undefined &&\n\t\tfreshEntry.parentPid !== knownParentPid &&\n\t\tdeps.isPidAlive(freshEntry.parentPid)\n\t) {\n\t\treturn { code: \"adopt\", parentPid: freshEntry.parentPid };\n\t}\n\treturn { code: \"none\" };\n}\n\nexport interface ReconcileMatrixDeps {\n\tisPidAlive: (pid: number) => boolean;\n\t/** Epoch ms \"now\", compared against a resumable/adopted entry's `heartbeatAt`. */\n\tnow: number;\n\tresumableTtlMs: number;\n}\n\n/**\n * Prune `closed` entries and any `running`/`winding_down` entry whose OWN pid is dead (a crashed\n * process that never reached `closed`). `resumable`/`adopted` entries are kept until they age past\n * `resumableTtlMs` -- they carry a payload a future session may still pick up.\n */\nexport function reconcileMatrix(entries: ProcessMatrixEntry[], deps: ReconcileMatrixDeps): ReconcileMatrixResult {\n\tconst kept: ProcessMatrixEntry[] = [];\n\tconst prunedEntryIds: string[] = [];\n\tfor (const entry of entries) {\n\t\tif (entry.status === \"closed\") {\n\t\t\tprunedEntryIds.push(entry.entryId);\n\t\t\tcontinue;\n\t\t}\n\t\tif (entry.status === \"running\" || entry.status === \"winding_down\") {\n\t\t\tif (!deps.isPidAlive(entry.pid)) {\n\t\t\t\tprunedEntryIds.push(entry.entryId);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tkept.push(entry);\n\t\t\tcontinue;\n\t\t}\n\t\t// resumable / adopted: TTL-gated on the entry's own last heartbeat.\n\t\tconst heartbeatMs = Date.parse(entry.heartbeatAt);\n\t\tif (Number.isFinite(heartbeatMs) && deps.now - heartbeatMs > deps.resumableTtlMs) {\n\t\t\tprunedEntryIds.push(entry.entryId);\n\t\t\tcontinue;\n\t\t}\n\t\tkept.push(entry);\n\t}\n\treturn { code: \"reconciled\", kept, prunedEntryIds };\n}\n"]}
1
+ {"version":3,"file":"supervisor.js","sourceRoot":"","sources":["../../../src/core/process-matrix/supervisor.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAWH,OAAO,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAS1C,MAAM,UAAU,gBAAgB,CAAC,KAA4B,EAAsB;IAClF,OAAO;QACN,OAAO,EAAE,YAAY,CAAC,QAAQ,EAAE,KAAK,CAAC,KAAK,CAAC,aAAa,CAAC,SAAS,CAAC;QACpE,IAAI,EAAE,QAAQ;QACd,KAAK,EAAE,eAAe,CAAC,KAAK,CAAC,KAAK,CAAC;QACnC,GAAG,EAAE,KAAK,CAAC,GAAG;QACd,QAAQ,EAAE,KAAK,CAAC,QAAQ;QACxB,SAAS,EAAE,KAAK,CAAC,GAAG;QACpB,WAAW,EAAE,KAAK,CAAC,GAAG;QACtB,MAAM,EAAE,SAAS;KACjB,CAAC;AAAA,CACF;AAeD,MAAM,UAAU,gBAAgB,CAAC,KAA4B,EAAsB;IAClF,MAAM,KAAK,GAAuB;QACjC,OAAO,EAAE,YAAY,CAAC,QAAQ,EAAE,KAAK,CAAC,KAAK,CAAC,aAAa,CAAC,SAAS,CAAC;QACpE,IAAI,EAAE,QAAQ;QACd,KAAK,EAAE,eAAe,CAAC,KAAK,CAAC,KAAK,CAAC;QACnC,GAAG,EAAE,KAAK,CAAC,GAAG;QACd,QAAQ,EAAE,KAAK,CAAC,QAAQ;QACxB,SAAS,EAAE,KAAK,CAAC,GAAG;QACpB,WAAW,EAAE,KAAK,CAAC,GAAG;QACtB,MAAM,EAAE,SAAS;QACjB,SAAS,EAAE,KAAK,CAAC,SAAS;KAC1B,CAAC;IACF,IAAI,KAAK,CAAC,eAAe,KAAK,SAAS;QAAE,KAAK,CAAC,eAAe,GAAG,KAAK,CAAC,eAAe,CAAC;IACvF,IAAI,KAAK,CAAC,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AAC,MAAM,CAAC,QAAQ,CAAC,WAAW,CAAC,IAAI,IAAI,CAAC,GAAG,GAAG,WAAW,GAAG,IAAI,CAAC,cAAc,EAAE,CAAC;YACnF,cAAc,CAAC,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;YACnC,SAAS;QACV,CAAC;QACD,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IAClB,CAAC;IACD,OAAO,EAAE,IAAI,EAAE,YAAY,EAAE,IAAI,EAAE,cAAc,EAAE,iBAAiB,EAAE,CAAC;AAAA,CACvE","sourcesContent":["/**\n * Process-matrix supervisor: PURE state-transition functions over `ProcessMatrixEntry`. Every\n * function here takes its notion of \"now\" and process liveness as an explicit argument/dependency\n * -- no `Date.now()`, no `process.kill` inside this module -- so the whole lifecycle (orphan\n * detection, wind-down, adoption, reconcile) is deterministically testable without real timers or\n * real processes. `runtime.ts` is the only caller that supplies real deps and real I/O.\n */\n\nimport type { AgentIdentityContract } from \"../orchestration/contracts.ts\";\nimport type {\n\tProcessMatrixEntry,\n\tProcessTerminalHandoff,\n\tReconcileMatrixResult,\n\tResumablePayload,\n\tWindDownReason,\n\tWorkerDirective,\n} from \"./codes.ts\";\nimport { buildEntryId } from \"./store.ts\";\n\nexport interface BuildMasterEntryFacts {\n\tagent: AgentIdentityContract;\n\tpid: number;\n\thostname: string;\n\tnow: string;\n}\n\nexport function buildMasterEntry(facts: BuildMasterEntryFacts): ProcessMatrixEntry {\n\treturn {\n\t\tentryId: buildEntryId(\"master\", facts.agent.resumeContext.sessionId),\n\t\trole: \"master\",\n\t\tagent: structuredClone(facts.agent),\n\t\tpid: facts.pid,\n\t\thostname: facts.hostname,\n\t\tstartedAt: facts.now,\n\t\theartbeatAt: facts.now,\n\t\tstatus: \"running\",\n\t};\n}\n\nexport interface BuildWorkerEntryFacts {\n\tagent: AgentIdentityContract;\n\tpid: number;\n\thostname: string;\n\tnow: string;\n\tparentPid: number;\n\tparentSessionId?: string;\n\ttmuxSession?: string;\n\ttmuxPanePid?: number;\n\ttaskRef?: string;\n\ttaskSummary?: string;\n}\n\nexport function buildWorkerEntry(facts: BuildWorkerEntryFacts): ProcessMatrixEntry {\n\tconst entry: ProcessMatrixEntry = {\n\t\tentryId: buildEntryId(\"worker\", facts.agent.resumeContext.sessionId),\n\t\trole: \"worker\",\n\t\tagent: structuredClone(facts.agent),\n\t\tpid: facts.pid,\n\t\thostname: facts.hostname,\n\t\tstartedAt: facts.now,\n\t\theartbeatAt: facts.now,\n\t\tstatus: \"running\",\n\t\tparentPid: facts.parentPid,\n\t};\n\tif (facts.parentSessionId !== undefined) entry.parentSessionId = facts.parentSessionId;\n\tif (facts.tmuxSession !== undefined) entry.tmuxSession = facts.tmuxSession;\n\tif (facts.tmuxPanePid !== undefined) entry.tmuxPanePid = facts.tmuxPanePid;\n\tif (facts.taskRef !== undefined) entry.taskRef = facts.taskRef;\n\tif (facts.taskSummary !== undefined) entry.taskSummary = facts.taskSummary;\n\treturn entry;\n}\n\nexport function applyHeartbeat(entry: ProcessMatrixEntry, now: string): ProcessMatrixEntry {\n\treturn { ...entry, heartbeatAt: now };\n}\n\nexport interface DetectOrphanedWorkersDeps {\n\tisPidAlive: (pid: number) => boolean;\n\t/** This session's own sessionId -- never treat yourself as an orphan you found. */\n\townSessionId?: string;\n}\n\n/**\n * Worker entries whose `parentPid` is dead, excluding this session's own entry and anything\n * already `closed` (a closed worker isn't \"orphaned\", it's already done).\n */\nexport function detectOrphanedWorkers(\n\tentries: ProcessMatrixEntry[],\n\tdeps: DetectOrphanedWorkersDeps,\n): ProcessMatrixEntry[] {\n\treturn entries.filter((entry) => {\n\t\tif (entry.role !== \"worker\") return false;\n\t\tif (entry.status === \"closed\") return false;\n\t\tif (deps.ownSessionId !== undefined && entry.agent.resumeContext.sessionId === deps.ownSessionId) return false;\n\t\tif (entry.parentPid === undefined) return false;\n\t\treturn !deps.isPidAlive(entry.parentPid);\n\t});\n}\n\nexport function beginWindDown(entry: ProcessMatrixEntry, reason: WindDownReason, now: string): ProcessMatrixEntry {\n\treturn { ...entry, status: \"winding_down\", windDownReason: reason, heartbeatAt: now };\n}\n\nexport function markResumable(entry: ProcessMatrixEntry, payload: ResumablePayload, now: string): ProcessMatrixEntry {\n\treturn { ...entry, status: \"resumable\", resumable: payload, heartbeatAt: now };\n}\n\nexport function markClosed(entry: ProcessMatrixEntry, now: string): ProcessMatrixEntry {\n\treturn { ...entry, status: \"closed\", heartbeatAt: now };\n}\n\nexport function markTerminal(\n\tentry: ProcessMatrixEntry,\n\tterminal: Pick<ProcessTerminalHandoff, \"code\" | \"signal\">,\n\tnow: string,\n): ProcessMatrixEntry {\n\treturn {\n\t\t...markClosed(entry, now),\n\t\tterminal: { code: terminal.code, signal: terminal.signal, observedAt: now },\n\t};\n}\n\nexport function markTerminalNotificationDelivered(entry: ProcessMatrixEntry, now: string): ProcessMatrixEntry {\n\tif (!entry.terminal) return entry;\n\treturn { ...entry, terminal: { ...entry.terminal, notificationDeliveredAt: now } };\n}\n\nexport interface AdoptionFacts {\n\tparentPid: number;\n\tparentSessionId?: string;\n}\n\n/** Claim (or reclaim) an entry under a new parent: back to `running`, wind-down reason cleared. */\nexport function applyAdoption(entry: ProcessMatrixEntry, adoption: AdoptionFacts): ProcessMatrixEntry {\n\tconst next: ProcessMatrixEntry = { ...entry, status: \"running\", parentPid: adoption.parentPid };\n\tdelete next.windDownReason;\n\tif (adoption.parentSessionId !== undefined) next.parentSessionId = adoption.parentSessionId;\n\treturn next;\n}\n\nexport interface PollWorkerDirectiveDeps {\n\tisPidAlive: (pid: number) => boolean;\n}\n\n/**\n * A worker calls this against its OWN freshly re-read entry to learn whether a master wrote a\n * directive into it: an adoption (a new, live `parentPid` the worker didn't already know about)\n * or a cooperative cleanup request (`windDownReason === \"user_cleanup\"`). `knownParentPid` is the\n * parent the worker itself currently believes it has -- an unchanged, still-known parentPid never\n * counts as a new adoption.\n */\nexport function pollWorkerDirective(\n\tfreshEntry: ProcessMatrixEntry,\n\tknownParentPid: number | undefined,\n\tdeps: PollWorkerDirectiveDeps,\n): WorkerDirective {\n\tif (freshEntry.windDownReason === \"user_cleanup\") return { code: \"user_cleanup\" };\n\tif (\n\t\tfreshEntry.parentPid !== undefined &&\n\t\tfreshEntry.parentPid !== knownParentPid &&\n\t\tdeps.isPidAlive(freshEntry.parentPid)\n\t) {\n\t\treturn { code: \"adopt\", parentPid: freshEntry.parentPid };\n\t}\n\treturn { code: \"none\" };\n}\n\nexport interface ReconcileMatrixDeps {\n\tisPidAlive: (pid: number) => boolean;\n\t/** Epoch ms \"now\", compared against a resumable/adopted entry's `heartbeatAt`. */\n\tnow: number;\n\tresumableTtlMs: number;\n}\n\n/**\n * Prune `closed` entries and unrecoverable dead processes. A dead Pi worker that was interrupted\n * before persisting its own resumable transition is repaired from its already-durable logical-agent\n * identity. `resumable`/`adopted` entries are kept until they age past `resumableTtlMs`.\n */\nexport function reconcileMatrix(entries: ProcessMatrixEntry[], deps: ReconcileMatrixDeps): ReconcileMatrixResult {\n\tconst kept: ProcessMatrixEntry[] = [];\n\tconst prunedEntryIds: string[] = [];\n\tconst recoveredEntryIds: string[] = [];\n\tfor (const entry of entries) {\n\t\tif (entry.status === \"closed\") {\n\t\t\tconst terminalAt = Date.parse(entry.terminal?.observedAt ?? entry.heartbeatAt);\n\t\t\tconst terminalExpired = !Number.isFinite(terminalAt) || deps.now - terminalAt > deps.resumableTtlMs;\n\t\t\tif (entry.terminal && !entry.terminal.notificationDeliveredAt && !terminalExpired) kept.push(entry);\n\t\t\telse prunedEntryIds.push(entry.entryId);\n\t\t\tcontinue;\n\t\t}\n\t\tif (entry.status === \"running\" || entry.status === \"winding_down\") {\n\t\t\tif (!deps.isPidAlive(entry.pid)) {\n\t\t\t\tif (entry.role === \"worker\" && entry.agent.resumeContext.provider === \"pi\") {\n\t\t\t\t\tconst payload: ResumablePayload = {\n\t\t\t\t\t\tagent: structuredClone(entry.agent),\n\t\t\t\t\t\tlastCode: \"resumable\",\n\t\t\t\t\t};\n\t\t\t\t\tif (entry.taskRef !== undefined) payload.taskRef = entry.taskRef;\n\t\t\t\t\tif (entry.taskSummary !== undefined) payload.taskSummary = entry.taskSummary;\n\t\t\t\t\tkept.push(markResumable(entry, payload, new Date(deps.now).toISOString()));\n\t\t\t\t\trecoveredEntryIds.push(entry.entryId);\n\t\t\t\t} else {\n\t\t\t\t\tprunedEntryIds.push(entry.entryId);\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tkept.push(entry);\n\t\t\tcontinue;\n\t\t}\n\t\t// resumable / adopted: TTL-gated on the entry's own last heartbeat.\n\t\tconst heartbeatMs = Date.parse(entry.heartbeatAt);\n\t\tif (!Number.isFinite(heartbeatMs) || deps.now - heartbeatMs > deps.resumableTtlMs) {\n\t\t\tprunedEntryIds.push(entry.entryId);\n\t\t\tcontinue;\n\t\t}\n\t\tkept.push(entry);\n\t}\n\treturn { code: \"reconciled\", kept, prunedEntryIds, recoveredEntryIds };\n}\n"]}
@@ -9,6 +9,7 @@
9
9
  */
10
10
  import type { Agent, ThinkingLevel } from "@caupulican/pi-agent-core";
11
11
  import type { SessionManager } from "@caupulican/pi-agent-core/node";
12
+ import { type ExtensionImportAuthority } from "./extension-import-authority.ts";
12
13
  import type { Extension } from "./extensions/index.ts";
13
14
  import type { ModelRegistry } from "./model-registry.ts";
14
15
  import type { ResourceLoader } from "./resource-loader.ts";
@@ -61,7 +62,13 @@ export declare class ProfileFilterController {
61
62
  deriveToolProfileFilter(): Required<ResourceProfileFilterSettings>;
62
63
  isToolOrCommandAllowedByProfile(name: string): boolean;
63
64
  private _hasToolOrCommandProfileGate;
64
- filterExtensionsForRuntime(extensions: Extension[]): Extension[];
65
+ /**
66
+ * Decide whether a path has authority to cross the import boundary. Explicit owner loads may
67
+ * proceed without a profile, while discovery-driven loads require an active profile grant.
68
+ * User disables remain a hard stop for both paths.
69
+ */
70
+ isExtensionPathAllowed(extensionPath: string, authority: ExtensionImportAuthority, baseDir?: string): boolean;
71
+ filterExtensionsForRuntime(extensions: Extension[], explicitLiveExtensionPaths?: ReadonlySet<string>): Extension[];
65
72
  /**
66
73
  * /context observations for skills/prompts/extensions the active resource profile removed from
67
74
  * listings — the analog of the withheld-AGENTS.md warning. Strict UAC makes these silently absent,
@@ -1 +1 @@
1
- {"version":3,"file":"profile-filter-controller.d.ts","sourceRoot":"","sources":["../../src/core/profile-filter-controller.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,KAAK,EAAE,KAAK,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AACtE,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,gCAAgC,CAAC;AACrE,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AACvD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAEzD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAC3D,OAAO,EAEN,KAAK,6BAA6B,EAClC,KAAK,eAAe,EACpB,MAAM,uBAAuB,CAAC;AAE/B,MAAM,WAAW,2BAA2B;IAC3C,kBAAkB,IAAI,eAAe,CAAC;IACtC,iBAAiB,IAAI,cAAc,CAAC;IACpC,gBAAgB,IAAI,aAAa,CAAC;IAClC,MAAM,IAAI,MAAM,CAAC;IACjB,QAAQ,IAAI,KAAK,CAAC;IAClB,iBAAiB,IAAI,cAAc,CAAC;IACpC,yEAAyE;IACzE,mBAAmB,IAAI,GAAG,CAAC,MAAM,CAAC,GAAG,SAAS,CAAC;IAC/C,0CAA0C;IAC1C,oBAAoB,IAAI,GAAG,CAAC,MAAM,CAAC,GAAG,SAAS,CAAC;IAChD,kFAAkF;IAClF,oBAAoB,IAAI,QAAQ,CAAC,6BAA6B,CAAC,GAAG,SAAS,CAAC;IAC5E,0FAA0F;IAC1F,eAAe,IAAI,OAAO,CAAC;IAC3B,qEAAqE;IACrE,kBAAkB,IAAI,OAAO,CAAC;IAC9B,6DAA6D;IAC7D,gBAAgB,CAAC,KAAK,EAAE,aAAa,GAAG,IAAI,CAAC;CAC7C;AAED,MAAM,WAAW,2BAA2B;IAC3C,sBAAsB,EAAE,MAAM,EAAE,CAAC;IACjC,2BAA2B,EAAE,MAAM,CAAC;IACpC,sBAAsB,EAAE,OAAO,CAAC;IAChC,yBAAyB,EAAE,OAAO,CAAC;CACnC;AAED,qBAAa,uBAAuB;IACnC,qFAAqF;IACrF,OAAO,CAAC,uBAAuB,CAAgB;IAC/C,kGAAkG;IAClG,OAAO,CAAC,4BAA4B,CAAK;IACzC,2GAA2G;IAC3G,OAAO,CAAC,uBAAuB,CAAS;IACxC,OAAO,CAAC,0BAA0B,CAAS;IAE3C,OAAO,CAAC,QAAQ,CAAC,IAAI,CAA8B;IAEnD,YAAY,IAAI,EAAE,2BAA2B,EAE5C;IAED,4FAA4F;IAC5F,yBAAyB,IAAI,MAAM,EAAE,CAEpC;IAED,oBAAoB,IAAI,2BAA2B,CAOlD;IAED,qBAAqB,CAAC,QAAQ,EAAE,2BAA2B,GAAG,IAAI,CAKjE;IAED;;;;OAIG;IACH,uBAAuB,IAAI,QAAQ,CAAC,6BAA6B,CAAC,CAGjE;IAED,+BAA+B,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAUrD;IAED,OAAO,CAAC,4BAA4B;IASpC,0BAA0B,CAAC,UAAU,EAAE,SAAS,EAAE,GAAG,SAAS,EAAE,CAuC/D;IAED;;;;;;;;;;;;;OAaG;IACH,iCAAiC,IAAI,MAAM,EAAE,CA0B5C;IAED;;;;;OAKG;IACG,iCAAiC,IAAI,OAAO,CAAC,IAAI,CAAC,CA0DvD;CACD","sourcesContent":["/**\n * Resource-profile tool/extension gating + reload-time profile model re-application.\n *\n * Extracted verbatim from agent-session.ts (god-file decomposition). Resolves the active resource\n * profile's tool allow/block filter, filters the runtime extension set (tracking the withheld/inert\n * tallies it owns), reports the /context \"withheld by profile\" observations, and — on reload —\n * re-applies a profile-bound model/thinking level unless an explicit launch flag set them. Owns the\n * inert-extension warnings and profile-denied-extension count; everything else is read through deps.\n */\n\nimport type { Agent, ThinkingLevel } from \"@caupulican/pi-agent-core\";\nimport type { SessionManager } from \"@caupulican/pi-agent-core/node\";\nimport type { Extension } from \"./extensions/index.ts\";\nimport type { ModelRegistry } from \"./model-registry.ts\";\nimport { findInitialModel, resolveProfileModelSettings } from \"./model-resolver.ts\";\nimport type { ResourceLoader } from \"./resource-loader.ts\";\nimport {\n\tmatchesResourceProfilePattern,\n\ttype ResourceProfileFilterSettings,\n\ttype SettingsManager,\n} from \"./settings-manager.ts\";\n\nexport interface ProfileFilterControllerDeps {\n\tgetSettingsManager(): SettingsManager;\n\tgetResourceLoader(): ResourceLoader;\n\tgetModelRegistry(): ModelRegistry;\n\tgetCwd(): string;\n\tgetAgent(): Agent;\n\tgetSessionManager(): SessionManager;\n\t/** Construction-time tool allow-set (undefined = no allow-list gate). */\n\tgetAllowedToolNames(): Set<string> | undefined;\n\t/** Construction-time tool exclude-set. */\n\tgetExcludedToolNames(): Set<string> | undefined;\n\t/** Live resource-profile tool filter (re-derived on reload; may be undefined). */\n\tgetToolProfileFilter(): Required<ResourceProfileFilterSettings> | undefined;\n\t/** Whether the model was set by an explicit launch flag (profile must not clobber it). */\n\tisExplicitModel(): boolean;\n\t/** Whether the thinking level was set by an explicit launch flag. */\n\tisExplicitThinking(): boolean;\n\t/** Apply a thinking level (delegates to model-selection). */\n\tsetThinkingLevel(level: ThinkingLevel): void;\n}\n\nexport interface ProfileFilterReloadSnapshot {\n\tinertExtensionWarnings: string[];\n\tprofileDeniedExtensionCount: number;\n\tprofileControlledModel: boolean;\n\tprofileControlledThinking: boolean;\n}\n\nexport class ProfileFilterController {\n\t/** G12: extensions loaded but rendered fully inert by the profile's tools filter. */\n\tprivate _inertExtensionWarnings: string[] = [];\n\t/** Count of extensions withheld by the active resource profile (for the /context observation). */\n\tprivate _profileDeniedExtensionCount = 0;\n\t/** Whether the last applied profile generation, rather than the base session selection, owns the field. */\n\tprivate _profileControlledModel = false;\n\tprivate _profileControlledThinking = false;\n\n\tprivate readonly deps: ProfileFilterControllerDeps;\n\n\tconstructor(deps: ProfileFilterControllerDeps) {\n\t\tthis.deps = deps;\n\t}\n\n\t/** Inert-extension warnings tracked by the last {@link filterExtensionsForRuntime} pass. */\n\tgetInertExtensionWarnings(): string[] {\n\t\treturn this._inertExtensionWarnings;\n\t}\n\n\tcreateReloadSnapshot(): ProfileFilterReloadSnapshot {\n\t\treturn {\n\t\t\tinertExtensionWarnings: [...this._inertExtensionWarnings],\n\t\t\tprofileDeniedExtensionCount: this._profileDeniedExtensionCount,\n\t\t\tprofileControlledModel: this._profileControlledModel,\n\t\t\tprofileControlledThinking: this._profileControlledThinking,\n\t\t};\n\t}\n\n\trestoreReloadSnapshot(snapshot: ProfileFilterReloadSnapshot): void {\n\t\tthis._inertExtensionWarnings = [...snapshot.inertExtensionWarnings];\n\t\tthis._profileDeniedExtensionCount = snapshot.profileDeniedExtensionCount;\n\t\tthis._profileControlledModel = snapshot.profileControlledModel;\n\t\tthis._profileControlledThinking = snapshot.profileControlledThinking;\n\t}\n\n\t/**\n\t * Resolve the active resource-profile tool allow/block filter from current settings.\n\t * Mirrors the construction-time derivation (settingsManager.getResourceProfileFilter(\"tools\"))\n\t * so reload() can re-apply it after a live settings/profile edit.\n\t */\n\tderiveToolProfileFilter(): Required<ResourceProfileFilterSettings> {\n\t\tconst filter = this.deps.getSettingsManager().getResourceProfileFilter(\"tools\");\n\t\treturn { allow: filter.allow ?? [], block: filter.block ?? [] };\n\t}\n\n\tisToolOrCommandAllowedByProfile(name: string): boolean {\n\t\tconst allowedToolNames = this.deps.getAllowedToolNames();\n\t\tconst excludedToolNames = this.deps.getExcludedToolNames();\n\t\tif (allowedToolNames && !allowedToolNames.has(name)) return false;\n\t\tif (excludedToolNames?.has(name)) return false;\n\t\tconst filter = this.deps.getToolProfileFilter();\n\t\tif (!filter) return true;\n\t\tif (filter.allow.length > 0 && !matchesResourceProfilePattern(name, filter.allow)) return false;\n\t\tif (matchesResourceProfilePattern(name, filter.block)) return false;\n\t\treturn true;\n\t}\n\n\tprivate _hasToolOrCommandProfileGate(): boolean {\n\t\tconst toolProfileFilter = this.deps.getToolProfileFilter();\n\t\treturn Boolean(\n\t\t\tthis.deps.getAllowedToolNames() ||\n\t\t\t\tthis.deps.getExcludedToolNames() ||\n\t\t\t\t(toolProfileFilter && (toolProfileFilter.allow.length > 0 || toolProfileFilter.block.length > 0)),\n\t\t);\n\t}\n\n\tfilterExtensionsForRuntime(extensions: Extension[]): Extension[] {\n\t\tconst settingsManager = this.deps.getSettingsManager();\n\t\tthis._inertExtensionWarnings = [];\n\t\tthis._profileDeniedExtensionCount = 0;\n\t\tif (settingsManager.getActiveResourceProfileNames().length === 0) {\n\t\t\tif (settingsManager.hasExplicitActiveResourceProfileSelection()) {\n\t\t\t\t// An explicit profile selection that resolves to no active profile is a deliberate\n\t\t\t\t// deny-all — every extension is withheld by that choice.\n\t\t\t\tthis._profileDeniedExtensionCount = extensions.length;\n\t\t\t\treturn [];\n\t\t\t}\n\t\t\t// No profile in play: only inline/SDK extensions load by default. That is the baseline, not\n\t\t\t// a profile denial, so it is not counted as withheld.\n\t\t\treturn extensions.filter((extension) => extension.sourceInfo.source === \"inline\");\n\t\t}\n\t\tconst hasToolOrCommandGate = this._hasToolOrCommandProfileGate();\n\t\tconst allowedExtensions = extensions.filter((extension) =>\n\t\t\tsettingsManager.isResourceAllowedByProfile(\"extensions\", extension.path, extension.sourceInfo.baseDir),\n\t\t);\n\t\tthis._profileDeniedExtensionCount = extensions.length - allowedExtensions.length;\n\t\treturn allowedExtensions.map((extension) => {\n\t\t\tif (!hasToolOrCommandGate) return extension;\n\t\t\tconst tools = new Map(\n\t\t\t\tArray.from(extension.tools.entries()).filter(([name]) => this.isToolOrCommandAllowedByProfile(name)),\n\t\t\t);\n\t\t\tconst commands = new Map(\n\t\t\t\tArray.from(extension.commands.entries()).filter(([name]) => this.isToolOrCommandAllowedByProfile(name)),\n\t\t\t);\n\t\t\t// G12: an extension the profile ALLOWS whose every tool and command the tools filter\n\t\t\t// then denies loads and runs lifecycle hooks but is completely uninvocable — surface\n\t\t\t// it instead of presenting a \"loaded\" extension that silently does nothing.\n\t\t\tif (extension.tools.size + extension.commands.size > 0 && tools.size + commands.size === 0) {\n\t\t\t\tconst name = extension.path.split(/[\\\\/]/).pop() ?? extension.path;\n\t\t\t\tthis._inertExtensionWarnings.push(\n\t\t\t\t\t`extension \"${name}\" is loaded but fully inert: the active profile's tools filter denies all ${extension.tools.size} tool(s) and ${extension.commands.size} command(s) it contributes`,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn { ...extension, tools, commands };\n\t\t});\n\t}\n\n\t/**\n\t * /context observations for skills/prompts/extensions the active resource profile removed from\n\t * listings — the analog of the withheld-AGENTS.md warning. Strict UAC makes these silently absent,\n\t * so a lean profile's effect on the resource surface stays visible. Counts are profile-scoped\n\t * (skills/prompts via the profile-independent discovery universe filtered by the live profile\n\t * filter; extensions via the runtime filter's denied tally). Empty when nothing is withheld.\n\t *\n\t * Uses `isResourceDeniedByActiveProfile` (profile-only), not `isResourceAllowedByProfile` (which\n\t * also folds in the user's own legacy `disabledResources` list): a plain user-disabled resource\n\t * must never be misattributed to \"the active resource profile\" — that case is already surfaced by\n\t * the G14 disable-wins warning. With no active profile at all, the helper always reports nothing\n\t * denied, so this naturally stays silent (extensions keep their own runtime-filter-derived count,\n\t * which is already correctly zero absent a profile).\n\t */\n\tprofileDeniedResourceObservations(): string[] {\n\t\tconst settingsManager = this.deps.getSettingsManager();\n\t\tconst resourceLoader = this.deps.getResourceLoader();\n\t\tconst cwd = this.deps.getCwd();\n\t\tconst observations: string[] = [];\n\t\tconst withheld = (kind: \"skills\" | \"prompts\", paths: string[]): number =>\n\t\t\tpaths.filter((path) => settingsManager.isResourceDeniedByActiveProfile(kind, path, cwd)).length;\n\n\t\tconst skillsWithheld = withheld(\"skills\", resourceLoader.getDiscoverableSkillPaths());\n\t\tif (skillsWithheld > 0) {\n\t\t\tobservations.push(\n\t\t\t\t`${skillsWithheld} skill(s) withheld by the active resource profile — grant the \"skills\" kind to restore them`,\n\t\t\t);\n\t\t}\n\t\tconst promptsWithheld = withheld(\"prompts\", resourceLoader.getDiscoverablePromptPaths());\n\t\tif (promptsWithheld > 0) {\n\t\t\tobservations.push(\n\t\t\t\t`${promptsWithheld} prompt(s) withheld by the active resource profile — grant the \"prompts\" kind to restore them`,\n\t\t\t);\n\t\t}\n\t\tif (this._profileDeniedExtensionCount > 0) {\n\t\t\tobservations.push(\n\t\t\t\t`${this._profileDeniedExtensionCount} extension(s) withheld by the active resource profile — grant the \"extensions\" kind to restore them`,\n\t\t\t);\n\t\t}\n\t\treturn observations;\n\t}\n\n\t/**\n\t * Re-resolve the active resource profile's model/thinking from current settings and apply it.\n\t * Only acts when the profile actually binds model/thinking AND that field was not set by an\n\t * explicit launch flag — so live profile edits apply on reload without clobbering an explicit\n\t * --model/--thinking. A no-op for profiles that don't bind a model.\n\t */\n\tasync reapplyActiveProfileModelSettings(): Promise<void> {\n\t\tif (this.deps.isExplicitModel() && this.deps.isExplicitThinking()) return;\n\t\tconst settingsManager = this.deps.getSettingsManager();\n\t\tconst activeProfileNames = settingsManager.getActiveResourceProfileNames();\n\t\tconst profileSettings =\n\t\t\tactiveProfileNames.length > 0\n\t\t\t\t? resolveProfileModelSettings({\n\t\t\t\t\t\tactiveProfileNames,\n\t\t\t\t\t\tregistry: settingsManager.getProfileRegistry(),\n\t\t\t\t\t\tmodelRegistry: this.deps.getModelRegistry(),\n\t\t\t\t\t\tcwd: this.deps.getCwd(),\n\t\t\t\t\t})\n\t\t\t\t: {};\n\t\tif (profileSettings.error) {\n\t\t\tthrow new Error(`Profile model resolution error: ${profileSettings.error}`);\n\t\t}\n\t\tconst mustRestoreBaseModel =\n\t\t\t!this.deps.isExplicitModel() && this._profileControlledModel && !profileSettings.model;\n\t\tconst mustRestoreBaseThinking =\n\t\t\t!this.deps.isExplicitThinking() && this._profileControlledThinking && !profileSettings.thinkingLevel;\n\t\tconst baseSelection =\n\t\t\tmustRestoreBaseModel || mustRestoreBaseThinking\n\t\t\t\t? await findInitialModel({\n\t\t\t\t\t\tscopedModels: [],\n\t\t\t\t\t\tisContinuing: true,\n\t\t\t\t\t\tdefaultProvider: settingsManager.getDefaultProvider(),\n\t\t\t\t\t\tdefaultModelId: settingsManager.getDefaultModel(),\n\t\t\t\t\t\tdefaultThinkingLevel: settingsManager.getDefaultThinkingLevel(),\n\t\t\t\t\t\tmodelRegistry: this.deps.getModelRegistry(),\n\t\t\t\t\t})\n\t\t\t\t: undefined;\n\t\tlet modelChanged = false;\n\t\tconst nextModel = profileSettings.model ?? (mustRestoreBaseModel ? baseSelection?.model : undefined);\n\t\tif (!this.deps.isExplicitModel() && nextModel) {\n\t\t\tconst current = this.deps.getAgent().state.model;\n\t\t\tconst next = nextModel;\n\t\t\tif (!current || current.provider !== next.provider || current.id !== next.id) {\n\t\t\t\t// Mirror the startup/cycle path: set the model directly (no auth gate, no settings\n\t\t\t\t// persist) so re-applying the profile model behaves like initial resolution rather\n\t\t\t\t// than a runtime model switch. No model_select emit here — reload rebuilds the\n\t\t\t\t// extension runtime and emits session_start(\"reload\") right after, and the UI\n\t\t\t\t// re-renders from session.model.\n\t\t\t\tthis.deps.getAgent().state.model = next;\n\t\t\t\tthis.deps.getSessionManager().appendModelChange(next.provider, next.id);\n\t\t\t\tmodelChanged = true;\n\t\t\t}\n\t\t}\n\t\tthis._profileControlledModel = !this.deps.isExplicitModel() && Boolean(profileSettings.model);\n\t\tif (!this.deps.isExplicitThinking() && profileSettings.thinkingLevel) {\n\t\t\tthis.deps.setThinkingLevel(profileSettings.thinkingLevel);\n\t\t} else if (mustRestoreBaseThinking && baseSelection) {\n\t\t\tthis.deps.setThinkingLevel(baseSelection.thinkingLevel);\n\t\t} else if (modelChanged) {\n\t\t\t// A model-only situation switch still has to clamp the inherited/explicit level. This\n\t\t\t// prevents Sol/Terra Ultra from leaking into Luna or another model that stops at Max.\n\t\t\tthis.deps.setThinkingLevel(this.deps.getAgent().state.thinkingLevel);\n\t\t}\n\t\tthis._profileControlledThinking = !this.deps.isExplicitThinking() && Boolean(profileSettings.thinkingLevel);\n\t}\n}\n"]}
1
+ {"version":3,"file":"profile-filter-controller.d.ts","sourceRoot":"","sources":["../../src/core/profile-filter-controller.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,KAAK,EAAE,KAAK,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AACtE,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,gCAAgC,CAAC;AACrE,OAAO,EAAE,KAAK,wBAAwB,EAAmC,MAAM,iCAAiC,CAAC;AACjH,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AACvD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAEzD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAC3D,OAAO,EAEN,KAAK,6BAA6B,EAClC,KAAK,eAAe,EACpB,MAAM,uBAAuB,CAAC;AAE/B,MAAM,WAAW,2BAA2B;IAC3C,kBAAkB,IAAI,eAAe,CAAC;IACtC,iBAAiB,IAAI,cAAc,CAAC;IACpC,gBAAgB,IAAI,aAAa,CAAC;IAClC,MAAM,IAAI,MAAM,CAAC;IACjB,QAAQ,IAAI,KAAK,CAAC;IAClB,iBAAiB,IAAI,cAAc,CAAC;IACpC,yEAAyE;IACzE,mBAAmB,IAAI,GAAG,CAAC,MAAM,CAAC,GAAG,SAAS,CAAC;IAC/C,0CAA0C;IAC1C,oBAAoB,IAAI,GAAG,CAAC,MAAM,CAAC,GAAG,SAAS,CAAC;IAChD,kFAAkF;IAClF,oBAAoB,IAAI,QAAQ,CAAC,6BAA6B,CAAC,GAAG,SAAS,CAAC;IAC5E,0FAA0F;IAC1F,eAAe,IAAI,OAAO,CAAC;IAC3B,qEAA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DvD;CACD","sourcesContent":["/**\n * Resource-profile tool/extension gating + reload-time profile model re-application.\n *\n * Extracted verbatim from agent-session.ts (god-file decomposition). Resolves the active resource\n * profile's tool allow/block filter, filters the runtime extension set (tracking the withheld/inert\n * tallies it owns), reports the /context \"withheld by profile\" observations, and — on reload —\n * re-applies a profile-bound model/thinking level unless an explicit launch flag set them. Owns the\n * inert-extension warnings and profile-denied-extension count; everything else is read through deps.\n */\n\nimport type { Agent, ThinkingLevel } from \"@caupulican/pi-agent-core\";\nimport type { SessionManager } from \"@caupulican/pi-agent-core/node\";\nimport { type ExtensionImportAuthority, isExtensionPathAllowedForImport } from \"./extension-import-authority.ts\";\nimport type { Extension } from \"./extensions/index.ts\";\nimport type { ModelRegistry } from \"./model-registry.ts\";\nimport { findInitialModel, resolveProfileModelSettings } from \"./model-resolver.ts\";\nimport type { ResourceLoader } from \"./resource-loader.ts\";\nimport {\n\tmatchesResourceProfilePattern,\n\ttype ResourceProfileFilterSettings,\n\ttype SettingsManager,\n} from \"./settings-manager.ts\";\n\nexport interface ProfileFilterControllerDeps {\n\tgetSettingsManager(): SettingsManager;\n\tgetResourceLoader(): ResourceLoader;\n\tgetModelRegistry(): ModelRegistry;\n\tgetCwd(): string;\n\tgetAgent(): Agent;\n\tgetSessionManager(): SessionManager;\n\t/** Construction-time tool allow-set (undefined = no allow-list gate). */\n\tgetAllowedToolNames(): Set<string> | undefined;\n\t/** Construction-time tool exclude-set. */\n\tgetExcludedToolNames(): Set<string> | undefined;\n\t/** Live resource-profile tool filter (re-derived on reload; may be undefined). */\n\tgetToolProfileFilter(): Required<ResourceProfileFilterSettings> | undefined;\n\t/** Whether the model was set by an explicit launch flag (profile must not clobber it). */\n\tisExplicitModel(): boolean;\n\t/** Whether the thinking level was set by an explicit launch flag. */\n\tisExplicitThinking(): boolean;\n\t/** Apply a thinking level (delegates to model-selection). */\n\tsetThinkingLevel(level: ThinkingLevel): void;\n}\n\nexport interface ProfileFilterReloadSnapshot {\n\tinertExtensionWarnings: string[];\n\tprofileDeniedExtensionCount: number;\n\tprofileControlledModel: boolean;\n\tprofileControlledThinking: boolean;\n}\n\nexport class ProfileFilterController {\n\t/** G12: extensions loaded but rendered fully inert by the profile's tools filter. */\n\tprivate _inertExtensionWarnings: string[] = [];\n\t/** Count of extensions withheld by the active resource profile (for the /context observation). */\n\tprivate _profileDeniedExtensionCount = 0;\n\t/** Whether the last applied profile generation, rather than the base session selection, owns the field. */\n\tprivate _profileControlledModel = false;\n\tprivate _profileControlledThinking = false;\n\n\tprivate readonly deps: ProfileFilterControllerDeps;\n\n\tconstructor(deps: ProfileFilterControllerDeps) {\n\t\tthis.deps = deps;\n\t}\n\n\t/** Inert-extension warnings tracked by the last {@link filterExtensionsForRuntime} pass. */\n\tgetInertExtensionWarnings(): string[] {\n\t\treturn this._inertExtensionWarnings;\n\t}\n\n\tcreateReloadSnapshot(): ProfileFilterReloadSnapshot {\n\t\treturn {\n\t\t\tinertExtensionWarnings: [...this._inertExtensionWarnings],\n\t\t\tprofileDeniedExtensionCount: this._profileDeniedExtensionCount,\n\t\t\tprofileControlledModel: this._profileControlledModel,\n\t\t\tprofileControlledThinking: this._profileControlledThinking,\n\t\t};\n\t}\n\n\trestoreReloadSnapshot(snapshot: ProfileFilterReloadSnapshot): void {\n\t\tthis._inertExtensionWarnings = [...snapshot.inertExtensionWarnings];\n\t\tthis._profileDeniedExtensionCount = snapshot.profileDeniedExtensionCount;\n\t\tthis._profileControlledModel = snapshot.profileControlledModel;\n\t\tthis._profileControlledThinking = snapshot.profileControlledThinking;\n\t}\n\n\t/**\n\t * Resolve the active resource-profile tool allow/block filter from current settings.\n\t * Mirrors the construction-time derivation (settingsManager.getResourceProfileFilter(\"tools\"))\n\t * so reload() can re-apply it after a live settings/profile edit.\n\t */\n\tderiveToolProfileFilter(): Required<ResourceProfileFilterSettings> {\n\t\tconst filter = this.deps.getSettingsManager().getResourceProfileFilter(\"tools\");\n\t\treturn { allow: filter.allow ?? [], block: filter.block ?? [] };\n\t}\n\n\tisToolOrCommandAllowedByProfile(name: string): boolean {\n\t\tconst allowedToolNames = this.deps.getAllowedToolNames();\n\t\tconst excludedToolNames = this.deps.getExcludedToolNames();\n\t\tif (allowedToolNames && !allowedToolNames.has(name)) return false;\n\t\tif (excludedToolNames?.has(name)) return false;\n\t\tconst filter = this.deps.getToolProfileFilter();\n\t\tif (!filter) return true;\n\t\tif (filter.allow.length > 0 && !matchesResourceProfilePattern(name, filter.allow)) return false;\n\t\tif (matchesResourceProfilePattern(name, filter.block)) return false;\n\t\treturn true;\n\t}\n\n\tprivate _hasToolOrCommandProfileGate(): boolean {\n\t\tconst toolProfileFilter = this.deps.getToolProfileFilter();\n\t\treturn Boolean(\n\t\t\tthis.deps.getAllowedToolNames() ||\n\t\t\t\tthis.deps.getExcludedToolNames() ||\n\t\t\t\t(toolProfileFilter && (toolProfileFilter.allow.length > 0 || toolProfileFilter.block.length > 0)),\n\t\t);\n\t}\n\n\t/**\n\t * Decide whether a path has authority to cross the import boundary. Explicit owner loads may\n\t * proceed without a profile, while discovery-driven loads require an active profile grant.\n\t * User disables remain a hard stop for both paths.\n\t */\n\tisExtensionPathAllowed(extensionPath: string, authority: ExtensionImportAuthority, baseDir = \"\"): boolean {\n\t\treturn isExtensionPathAllowedForImport(this.deps.getSettingsManager(), extensionPath, authority, baseDir);\n\t}\n\n\tfilterExtensionsForRuntime(extensions: Extension[], explicitLiveExtensionPaths?: ReadonlySet<string>): Extension[] {\n\t\tconst settingsManager = this.deps.getSettingsManager();\n\t\tthis._inertExtensionWarnings = [];\n\t\tthis._profileDeniedExtensionCount = 0;\n\t\tif (settingsManager.getActiveResourceProfileNames().length === 0) {\n\t\t\tif (settingsManager.hasExplicitActiveResourceProfileSelection()) {\n\t\t\t\t// An explicit profile selection that resolves to no active profile is a deliberate\n\t\t\t\t// deny-all — every extension is withheld by that choice.\n\t\t\t\tthis._profileDeniedExtensionCount = extensions.length;\n\t\t\t\treturn [];\n\t\t\t}\n\t\t\t// No profile in play: inline/SDK extensions and exact owner-approved CLI/live loads are the\n\t\t\t// only runtime authorities. Discovery alone must never promote an extension into executable code.\n\t\t\t// This baseline is not a profile denial, so it is not counted as withheld.\n\t\t\treturn extensions.filter((extension) => {\n\t\t\t\tif (extension.sourceInfo.source === \"inline\") return true;\n\t\t\t\tconst explicitlyApproved =\n\t\t\t\t\textension.sourceInfo.source === \"cli\" ||\n\t\t\t\t\texplicitLiveExtensionPaths?.has(extension.path) === true ||\n\t\t\t\t\texplicitLiveExtensionPaths?.has(extension.resolvedPath) === true;\n\t\t\t\treturn (\n\t\t\t\t\texplicitlyApproved &&\n\t\t\t\t\tthis.isExtensionPathAllowed(extension.path, \"explicit\", extension.sourceInfo.baseDir)\n\t\t\t\t);\n\t\t\t});\n\t\t}\n\t\tconst hasToolOrCommandGate = this._hasToolOrCommandProfileGate();\n\t\tconst allowedExtensions = extensions.filter((extension) =>\n\t\t\tthis.isExtensionPathAllowed(extension.path, \"profile\", extension.sourceInfo.baseDir),\n\t\t);\n\t\tthis._profileDeniedExtensionCount = extensions.length - allowedExtensions.length;\n\t\treturn allowedExtensions.map((extension) => {\n\t\t\tif (!hasToolOrCommandGate) return extension;\n\t\t\tconst tools = new Map(\n\t\t\t\tArray.from(extension.tools.entries()).filter(([name]) => this.isToolOrCommandAllowedByProfile(name)),\n\t\t\t);\n\t\t\tconst commands = new Map(\n\t\t\t\tArray.from(extension.commands.entries()).filter(([name]) => this.isToolOrCommandAllowedByProfile(name)),\n\t\t\t);\n\t\t\t// G12: an extension the profile ALLOWS whose every tool and command the tools filter\n\t\t\t// then denies loads and runs lifecycle hooks but is completely uninvocable — surface\n\t\t\t// it instead of presenting a \"loaded\" extension that silently does nothing.\n\t\t\tif (extension.tools.size + extension.commands.size > 0 && tools.size + commands.size === 0) {\n\t\t\t\tconst name = extension.path.split(/[\\\\/]/).pop() ?? extension.path;\n\t\t\t\tthis._inertExtensionWarnings.push(\n\t\t\t\t\t`extension \"${name}\" is loaded but fully inert: the active profile's tools filter denies all ${extension.tools.size} tool(s) and ${extension.commands.size} command(s) it contributes`,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn { ...extension, tools, commands };\n\t\t});\n\t}\n\n\t/**\n\t * /context observations for skills/prompts/extensions the active resource profile removed from\n\t * listings — the analog of the withheld-AGENTS.md warning. Strict UAC makes these silently absent,\n\t * so a lean profile's effect on the resource surface stays visible. Counts are profile-scoped\n\t * (skills/prompts via the profile-independent discovery universe filtered by the live profile\n\t * filter; extensions via the runtime filter's denied tally). Empty when nothing is withheld.\n\t *\n\t * Uses `isResourceDeniedByActiveProfile` (profile-only), not `isResourceAllowedByProfile` (which\n\t * also folds in the user's own legacy `disabledResources` list): a plain user-disabled resource\n\t * must never be misattributed to \"the active resource profile\" — that case is already surfaced by\n\t * the G14 disable-wins warning. With no active profile at all, the helper always reports nothing\n\t * denied, so this naturally stays silent (extensions keep their own runtime-filter-derived count,\n\t * which is already correctly zero absent a profile).\n\t */\n\tprofileDeniedResourceObservations(): string[] {\n\t\tconst settingsManager = this.deps.getSettingsManager();\n\t\tconst resourceLoader = this.deps.getResourceLoader();\n\t\tconst cwd = this.deps.getCwd();\n\t\tconst observations: string[] = [];\n\t\tconst withheld = (kind: \"skills\" | \"prompts\", paths: string[]): number =>\n\t\t\tpaths.filter((path) => settingsManager.isResourceDeniedByActiveProfile(kind, path, cwd)).length;\n\n\t\tconst skillsWithheld = withheld(\"skills\", resourceLoader.getDiscoverableSkillPaths());\n\t\tif (skillsWithheld > 0) {\n\t\t\tobservations.push(\n\t\t\t\t`${skillsWithheld} skill(s) withheld by the active resource profile — grant the \"skills\" kind to restore them`,\n\t\t\t);\n\t\t}\n\t\tconst promptsWithheld = withheld(\"prompts\", resourceLoader.getDiscoverablePromptPaths());\n\t\tif (promptsWithheld > 0) {\n\t\t\tobservations.push(\n\t\t\t\t`${promptsWithheld} prompt(s) withheld by the active resource profile — grant the \"prompts\" kind to restore them`,\n\t\t\t);\n\t\t}\n\t\tif (this._profileDeniedExtensionCount > 0) {\n\t\t\tobservations.push(\n\t\t\t\t`${this._profileDeniedExtensionCount} extension(s) withheld by the active resource profile — grant the \"extensions\" kind to restore them`,\n\t\t\t);\n\t\t}\n\t\treturn observations;\n\t}\n\n\t/**\n\t * Re-resolve the active resource profile's model/thinking from current settings and apply it.\n\t * Only acts when the profile actually binds model/thinking AND that field was not set by an\n\t * explicit launch flag — so live profile edits apply on reload without clobbering an explicit\n\t * --model/--thinking. A no-op for profiles that don't bind a model.\n\t */\n\tasync reapplyActiveProfileModelSettings(): Promise<void> {\n\t\tif (this.deps.isExplicitModel() && this.deps.isExplicitThinking()) return;\n\t\tconst settingsManager = this.deps.getSettingsManager();\n\t\tconst activeProfileNames = settingsManager.getActiveResourceProfileNames();\n\t\tconst profileSettings =\n\t\t\tactiveProfileNames.length > 0\n\t\t\t\t? resolveProfileModelSettings({\n\t\t\t\t\t\tactiveProfileNames,\n\t\t\t\t\t\tregistry: settingsManager.getProfileRegistry(),\n\t\t\t\t\t\tmodelRegistry: this.deps.getModelRegistry(),\n\t\t\t\t\t\tcwd: this.deps.getCwd(),\n\t\t\t\t\t})\n\t\t\t\t: {};\n\t\tif (profileSettings.error) {\n\t\t\tthrow new Error(`Profile model resolution error: ${profileSettings.error}`);\n\t\t}\n\t\tconst mustRestoreBaseModel =\n\t\t\t!this.deps.isExplicitModel() && this._profileControlledModel && !profileSettings.model;\n\t\tconst mustRestoreBaseThinking =\n\t\t\t!this.deps.isExplicitThinking() && this._profileControlledThinking && !profileSettings.thinkingLevel;\n\t\tconst baseSelection =\n\t\t\tmustRestoreBaseModel || mustRestoreBaseThinking\n\t\t\t\t? await findInitialModel({\n\t\t\t\t\t\tscopedModels: [],\n\t\t\t\t\t\tisContinuing: true,\n\t\t\t\t\t\tdefaultProvider: settingsManager.getDefaultProvider(),\n\t\t\t\t\t\tdefaultModelId: settingsManager.getDefaultModel(),\n\t\t\t\t\t\tdefaultThinkingLevel: settingsManager.getDefaultThinkingLevel(),\n\t\t\t\t\t\tmodelRegistry: this.deps.getModelRegistry(),\n\t\t\t\t\t})\n\t\t\t\t: undefined;\n\t\tlet modelChanged = false;\n\t\tconst nextModel = profileSettings.model ?? (mustRestoreBaseModel ? baseSelection?.model : undefined);\n\t\tif (!this.deps.isExplicitModel() && nextModel) {\n\t\t\tconst current = this.deps.getAgent().state.model;\n\t\t\tconst next = nextModel;\n\t\t\tif (!current || current.provider !== next.provider || current.id !== next.id) {\n\t\t\t\t// Mirror the startup/cycle path: set the model directly (no auth gate, no settings\n\t\t\t\t// persist) so re-applying the profile model behaves like initial resolution rather\n\t\t\t\t// than a runtime model switch. No model_select emit here — reload rebuilds the\n\t\t\t\t// extension runtime and emits session_start(\"reload\") right after, and the UI\n\t\t\t\t// re-renders from session.model.\n\t\t\t\tthis.deps.getAgent().state.model = next;\n\t\t\t\tthis.deps.getSessionManager().appendModelChange(next.provider, next.id);\n\t\t\t\tmodelChanged = true;\n\t\t\t}\n\t\t}\n\t\tthis._profileControlledModel = !this.deps.isExplicitModel() && Boolean(profileSettings.model);\n\t\tif (!this.deps.isExplicitThinking() && profileSettings.thinkingLevel) {\n\t\t\tthis.deps.setThinkingLevel(profileSettings.thinkingLevel);\n\t\t} else if (mustRestoreBaseThinking && baseSelection) {\n\t\t\tthis.deps.setThinkingLevel(baseSelection.thinkingLevel);\n\t\t} else if (modelChanged) {\n\t\t\t// A model-only situation switch still has to clamp the inherited/explicit level. This\n\t\t\t// prevents Sol/Terra Ultra from leaking into Luna or another model that stops at Max.\n\t\t\tthis.deps.setThinkingLevel(this.deps.getAgent().state.thinkingLevel);\n\t\t}\n\t\tthis._profileControlledThinking = !this.deps.isExplicitThinking() && Boolean(profileSettings.thinkingLevel);\n\t}\n}\n"]}
@@ -7,6 +7,7 @@
7
7
  * re-applies a profile-bound model/thinking level unless an explicit launch flag set them. Owns the
8
8
  * inert-extension warnings and profile-denied-extension count; everything else is read through deps.
9
9
  */
10
+ import { isExtensionPathAllowedForImport } from "./extension-import-authority.js";
10
11
  import { findInitialModel, resolveProfileModelSettings } from "./model-resolver.js";
11
12
  import { matchesResourceProfilePattern, } from "./settings-manager.js";
12
13
  export class ProfileFilterController {
@@ -70,7 +71,15 @@ export class ProfileFilterController {
70
71
  this.deps.getExcludedToolNames() ||
71
72
  (toolProfileFilter && (toolProfileFilter.allow.length > 0 || toolProfileFilter.block.length > 0)));
72
73
  }
73
- filterExtensionsForRuntime(extensions) {
74
+ /**
75
+ * Decide whether a path has authority to cross the import boundary. Explicit owner loads may
76
+ * proceed without a profile, while discovery-driven loads require an active profile grant.
77
+ * User disables remain a hard stop for both paths.
78
+ */
79
+ isExtensionPathAllowed(extensionPath, authority, baseDir = "") {
80
+ return isExtensionPathAllowedForImport(this.deps.getSettingsManager(), extensionPath, authority, baseDir);
81
+ }
82
+ filterExtensionsForRuntime(extensions, explicitLiveExtensionPaths) {
74
83
  const settingsManager = this.deps.getSettingsManager();
75
84
  this._inertExtensionWarnings = [];
76
85
  this._profileDeniedExtensionCount = 0;
@@ -81,12 +90,21 @@ export class ProfileFilterController {
81
90
  this._profileDeniedExtensionCount = extensions.length;
82
91
  return [];
83
92
  }
84
- // No profile in play: only inline/SDK extensions load by default. That is the baseline, not
85
- // a profile denial, so it is not counted as withheld.
86
- return extensions.filter((extension) => extension.sourceInfo.source === "inline");
93
+ // No profile in play: inline/SDK extensions and exact owner-approved CLI/live loads are the
94
+ // only runtime authorities. Discovery alone must never promote an extension into executable code.
95
+ // This baseline is not a profile denial, so it is not counted as withheld.
96
+ return extensions.filter((extension) => {
97
+ if (extension.sourceInfo.source === "inline")
98
+ return true;
99
+ const explicitlyApproved = extension.sourceInfo.source === "cli" ||
100
+ explicitLiveExtensionPaths?.has(extension.path) === true ||
101
+ explicitLiveExtensionPaths?.has(extension.resolvedPath) === true;
102
+ return (explicitlyApproved &&
103
+ this.isExtensionPathAllowed(extension.path, "explicit", extension.sourceInfo.baseDir));
104
+ });
87
105
  }
88
106
  const hasToolOrCommandGate = this._hasToolOrCommandProfileGate();
89
- const allowedExtensions = extensions.filter((extension) => settingsManager.isResourceAllowedByProfile("extensions", extension.path, extension.sourceInfo.baseDir));
107
+ const allowedExtensions = extensions.filter((extension) => this.isExtensionPathAllowed(extension.path, "profile", extension.sourceInfo.baseDir));
90
108
  this._profileDeniedExtensionCount = extensions.length - allowedExtensions.length;
91
109
  return allowedExtensions.map((extension) => {
92
110
  if (!hasToolOrCommandGate)
@@ -1 +1 @@
1
- {"version":3,"file":"profile-filter-controller.js","sourceRoot":"","sources":["../../src/core/profile-filter-controller.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAMH,OAAO,EAAE,gBAAgB,EAAE,2BAA2B,EAAE,MAAM,qBAAqB,CAAC;AAEpF,OAAO,EACN,6BAA6B,GAG7B,MAAM,uBAAuB,CAAC;AA8B/B,MAAM,OAAO,uBAAuB;IACnC,qFAAqF;IAC7E,uBAAuB,GAAa,EAAE,CAAC;IAC/C,kGAAkG;IAC1F,4BAA4B,GAAG,CAAC,CAAC;IACzC,2GAA2G;IACnG,uBAAuB,GAAG,KAAK,CAAC;IAChC,0BAA0B,GAAG,KAAK,CAAC;IAE1B,IAAI,CAA8B;IAEnD,YAAY,IAAiC,EAAE;QAC9C,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IAAA,CACjB;IAED,4FAA4F;IAC5F,yBAAyB,GAAa;QACrC,OAAO,IAAI,CAAC,uBAAuB,CAAC;IAAA,CACpC;IAED,oBAAoB,GAAgC;QACnD,OAAO;YACN,sBAAsB,EAAE,CAAC,GAAG,IAAI,CAAC,uBAAuB,CAAC;YACzD,2BAA2B,EAAE,IAAI,CAAC,4BAA4B;YAC9D,sBAAsB,EAAE,IAAI,CAAC,uBAAuB;YACpD,yBAAyB,EAAE,IAAI,CAAC,0BAA0B;SAC1D,CAAC;IAAA,CACF;IAED,qBAAqB,CAAC,QAAqC,EAAQ;QAClE,IAAI,CAAC,uBAAuB,GAAG,CAAC,GAAG,QAAQ,CAAC,sB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C,CAAC;QACzD,CAAC;aAAM,IAAI,YAAY,EAAE,CAAC;YACzB,sFAAsF;YACtF,sFAAsF;YACtF,IAAI,CAAC,IAAI,CAAC,gBAAgB,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,CAAC,KAAK,CAAC,aAAa,CAAC,CAAC;QACtE,CAAC;QACD,IAAI,CAAC,0BAA0B,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,kBAAkB,EAAE,IAAI,OAAO,CAAC,eAAe,CAAC,aAAa,CAAC,CAAC;IAAA,CAC5G;CACD","sourcesContent":["/**\n * Resource-profile tool/extension gating + reload-time profile model re-application.\n *\n * Extracted verbatim from agent-session.ts (god-file decomposition). Resolves the active resource\n * profile's tool allow/block filter, filters the runtime extension set (tracking the withheld/inert\n * tallies it owns), reports the /context \"withheld by profile\" observations, and — on reload —\n * re-applies a profile-bound model/thinking level unless an explicit launch flag set them. Owns the\n * inert-extension warnings and profile-denied-extension count; everything else is read through deps.\n */\n\nimport type { Agent, ThinkingLevel } from \"@caupulican/pi-agent-core\";\nimport type { SessionManager } from \"@caupulican/pi-agent-core/node\";\nimport type { Extension } from \"./extensions/index.ts\";\nimport type { ModelRegistry } from \"./model-registry.ts\";\nimport { findInitialModel, resolveProfileModelSettings } from \"./model-resolver.ts\";\nimport type { ResourceLoader } from \"./resource-loader.ts\";\nimport {\n\tmatchesResourceProfilePattern,\n\ttype ResourceProfileFilterSettings,\n\ttype SettingsManager,\n} from \"./settings-manager.ts\";\n\nexport interface ProfileFilterControllerDeps {\n\tgetSettingsManager(): SettingsManager;\n\tgetResourceLoader(): ResourceLoader;\n\tgetModelRegistry(): ModelRegistry;\n\tgetCwd(): string;\n\tgetAgent(): Agent;\n\tgetSessionManager(): SessionManager;\n\t/** Construction-time tool allow-set (undefined = no allow-list gate). */\n\tgetAllowedToolNames(): Set<string> | undefined;\n\t/** Construction-time tool exclude-set. */\n\tgetExcludedToolNames(): Set<string> | undefined;\n\t/** Live resource-profile tool filter (re-derived on reload; may be undefined). */\n\tgetToolProfileFilter(): Required<ResourceProfileFilterSettings> | undefined;\n\t/** Whether the model was set by an explicit launch flag (profile must not clobber it). */\n\tisExplicitModel(): boolean;\n\t/** Whether the thinking level was set by an explicit launch flag. */\n\tisExplicitThinking(): boolean;\n\t/** Apply a thinking level (delegates to model-selection). */\n\tsetThinkingLevel(level: ThinkingLevel): void;\n}\n\nexport interface ProfileFilterReloadSnapshot {\n\tinertExtensionWarnings: string[];\n\tprofileDeniedExtensionCount: number;\n\tprofileControlledModel: boolean;\n\tprofileControlledThinking: boolean;\n}\n\nexport class ProfileFilterController {\n\t/** G12: extensions loaded but rendered fully inert by the profile's tools filter. */\n\tprivate _inertExtensionWarnings: string[] = [];\n\t/** Count of extensions withheld by the active resource profile (for the /context observation). */\n\tprivate _profileDeniedExtensionCount = 0;\n\t/** Whether the last applied profile generation, rather than the base session selection, owns the field. */\n\tprivate _profileControlledModel = false;\n\tprivate _profileControlledThinking = false;\n\n\tprivate readonly deps: ProfileFilterControllerDeps;\n\n\tconstructor(deps: ProfileFilterControllerDeps) {\n\t\tthis.deps = deps;\n\t}\n\n\t/** Inert-extension warnings tracked by the last {@link filterExtensionsForRuntime} pass. */\n\tgetInertExtensionWarnings(): string[] {\n\t\treturn this._inertExtensionWarnings;\n\t}\n\n\tcreateReloadSnapshot(): ProfileFilterReloadSnapshot {\n\t\treturn {\n\t\t\tinertExtensionWarnings: [...this._inertExtensionWarnings],\n\t\t\tprofileDeniedExtensionCount: this._profileDeniedExtensionCount,\n\t\t\tprofileControlledModel: this._profileControlledModel,\n\t\t\tprofileControlledThinking: this._profileControlledThinking,\n\t\t};\n\t}\n\n\trestoreReloadSnapshot(snapshot: ProfileFilterReloadSnapshot): void {\n\t\tthis._inertExtensionWarnings = [...snapshot.inertExtensionWarnings];\n\t\tthis._profileDeniedExtensionCount = snapshot.profileDeniedExtensionCount;\n\t\tthis._profileControlledModel = snapshot.profileControlledModel;\n\t\tthis._profileControlledThinking = snapshot.profileControlledThinking;\n\t}\n\n\t/**\n\t * Resolve the active resource-profile tool allow/block filter from current settings.\n\t * Mirrors the construction-time derivation (settingsManager.getResourceProfileFilter(\"tools\"))\n\t * so reload() can re-apply it after a live settings/profile edit.\n\t */\n\tderiveToolProfileFilter(): Required<ResourceProfileFilterSettings> {\n\t\tconst filter = this.deps.getSettingsManager().getResourceProfileFilter(\"tools\");\n\t\treturn { allow: filter.allow ?? [], block: filter.block ?? [] };\n\t}\n\n\tisToolOrCommandAllowedByProfile(name: string): boolean {\n\t\tconst allowedToolNames = this.deps.getAllowedToolNames();\n\t\tconst excludedToolNames = this.deps.getExcludedToolNames();\n\t\tif (allowedToolNames && !allowedToolNames.has(name)) return false;\n\t\tif (excludedToolNames?.has(name)) return false;\n\t\tconst filter = this.deps.getToolProfileFilter();\n\t\tif (!filter) return true;\n\t\tif (filter.allow.length > 0 && !matchesResourceProfilePattern(name, filter.allow)) return false;\n\t\tif (matchesResourceProfilePattern(name, filter.block)) return false;\n\t\treturn true;\n\t}\n\n\tprivate _hasToolOrCommandProfileGate(): boolean {\n\t\tconst toolProfileFilter = this.deps.getToolProfileFilter();\n\t\treturn Boolean(\n\t\t\tthis.deps.getAllowedToolNames() ||\n\t\t\t\tthis.deps.getExcludedToolNames() ||\n\t\t\t\t(toolProfileFilter && (toolProfileFilter.allow.length > 0 || toolProfileFilter.block.length > 0)),\n\t\t);\n\t}\n\n\tfilterExtensionsForRuntime(extensions: Extension[]): Extension[] {\n\t\tconst settingsManager = this.deps.getSettingsManager();\n\t\tthis._inertExtensionWarnings = [];\n\t\tthis._profileDeniedExtensionCount = 0;\n\t\tif (settingsManager.getActiveResourceProfileNames().length === 0) {\n\t\t\tif (settingsManager.hasExplicitActiveResourceProfileSelection()) {\n\t\t\t\t// An explicit profile selection that resolves to no active profile is a deliberate\n\t\t\t\t// deny-all — every extension is withheld by that choice.\n\t\t\t\tthis._profileDeniedExtensionCount = extensions.length;\n\t\t\t\treturn [];\n\t\t\t}\n\t\t\t// No profile in play: only inline/SDK extensions load by default. That is the baseline, not\n\t\t\t// a profile denial, so it is not counted as withheld.\n\t\t\treturn extensions.filter((extension) => extension.sourceInfo.source === \"inline\");\n\t\t}\n\t\tconst hasToolOrCommandGate = this._hasToolOrCommandProfileGate();\n\t\tconst allowedExtensions = extensions.filter((extension) =>\n\t\t\tsettingsManager.isResourceAllowedByProfile(\"extensions\", extension.path, extension.sourceInfo.baseDir),\n\t\t);\n\t\tthis._profileDeniedExtensionCount = extensions.length - allowedExtensions.length;\n\t\treturn allowedExtensions.map((extension) => {\n\t\t\tif (!hasToolOrCommandGate) return extension;\n\t\t\tconst tools = new Map(\n\t\t\t\tArray.from(extension.tools.entries()).filter(([name]) => this.isToolOrCommandAllowedByProfile(name)),\n\t\t\t);\n\t\t\tconst commands = new Map(\n\t\t\t\tArray.from(extension.commands.entries()).filter(([name]) => this.isToolOrCommandAllowedByProfile(name)),\n\t\t\t);\n\t\t\t// G12: an extension the profile ALLOWS whose every tool and command the tools filter\n\t\t\t// then denies loads and runs lifecycle hooks but is completely uninvocable — surface\n\t\t\t// it instead of presenting a \"loaded\" extension that silently does nothing.\n\t\t\tif (extension.tools.size + extension.commands.size > 0 && tools.size + commands.size === 0) {\n\t\t\t\tconst name = extension.path.split(/[\\\\/]/).pop() ?? extension.path;\n\t\t\t\tthis._inertExtensionWarnings.push(\n\t\t\t\t\t`extension \"${name}\" is loaded but fully inert: the active profile's tools filter denies all ${extension.tools.size} tool(s) and ${extension.commands.size} command(s) it contributes`,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn { ...extension, tools, commands };\n\t\t});\n\t}\n\n\t/**\n\t * /context observations for skills/prompts/extensions the active resource profile removed from\n\t * listings — the analog of the withheld-AGENTS.md warning. Strict UAC makes these silently absent,\n\t * so a lean profile's effect on the resource surface stays visible. Counts are profile-scoped\n\t * (skills/prompts via the profile-independent discovery universe filtered by the live profile\n\t * filter; extensions via the runtime filter's denied tally). Empty when nothing is withheld.\n\t *\n\t * Uses `isResourceDeniedByActiveProfile` (profile-only), not `isResourceAllowedByProfile` (which\n\t * also folds in the user's own legacy `disabledResources` list): a plain user-disabled resource\n\t * must never be misattributed to \"the active resource profile\" — that case is already surfaced by\n\t * the G14 disable-wins warning. With no active profile at all, the helper always reports nothing\n\t * denied, so this naturally stays silent (extensions keep their own runtime-filter-derived count,\n\t * which is already correctly zero absent a profile).\n\t */\n\tprofileDeniedResourceObservations(): string[] {\n\t\tconst settingsManager = this.deps.getSettingsManager();\n\t\tconst resourceLoader = this.deps.getResourceLoader();\n\t\tconst cwd = this.deps.getCwd();\n\t\tconst observations: string[] = [];\n\t\tconst withheld = (kind: \"skills\" | \"prompts\", paths: string[]): number =>\n\t\t\tpaths.filter((path) => settingsManager.isResourceDeniedByActiveProfile(kind, path, cwd)).length;\n\n\t\tconst skillsWithheld = withheld(\"skills\", resourceLoader.getDiscoverableSkillPaths());\n\t\tif (skillsWithheld > 0) {\n\t\t\tobservations.push(\n\t\t\t\t`${skillsWithheld} skill(s) withheld by the active resource profile — grant the \"skills\" kind to restore them`,\n\t\t\t);\n\t\t}\n\t\tconst promptsWithheld = withheld(\"prompts\", resourceLoader.getDiscoverablePromptPaths());\n\t\tif (promptsWithheld > 0) {\n\t\t\tobservations.push(\n\t\t\t\t`${promptsWithheld} prompt(s) withheld by the active resource profile — grant the \"prompts\" kind to restore them`,\n\t\t\t);\n\t\t}\n\t\tif (this._profileDeniedExtensionCount > 0) {\n\t\t\tobservations.push(\n\t\t\t\t`${this._profileDeniedExtensionCount} extension(s) withheld by the active resource profile — grant the \"extensions\" kind to restore them`,\n\t\t\t);\n\t\t}\n\t\treturn observations;\n\t}\n\n\t/**\n\t * Re-resolve the active resource profile's model/thinking from current settings and apply it.\n\t * Only acts when the profile actually binds model/thinking AND that field was not set by an\n\t * explicit launch flag — so live profile edits apply on reload without clobbering an explicit\n\t * --model/--thinking. A no-op for profiles that don't bind a model.\n\t */\n\tasync reapplyActiveProfileModelSettings(): Promise<void> {\n\t\tif (this.deps.isExplicitModel() && this.deps.isExplicitThinking()) return;\n\t\tconst settingsManager = this.deps.getSettingsManager();\n\t\tconst activeProfileNames = settingsManager.getActiveResourceProfileNames();\n\t\tconst profileSettings =\n\t\t\tactiveProfileNames.length > 0\n\t\t\t\t? resolveProfileModelSettings({\n\t\t\t\t\t\tactiveProfileNames,\n\t\t\t\t\t\tregistry: settingsManager.getProfileRegistry(),\n\t\t\t\t\t\tmodelRegistry: this.deps.getModelRegistry(),\n\t\t\t\t\t\tcwd: this.deps.getCwd(),\n\t\t\t\t\t})\n\t\t\t\t: {};\n\t\tif (profileSettings.error) {\n\t\t\tthrow new Error(`Profile model resolution error: ${profileSettings.error}`);\n\t\t}\n\t\tconst mustRestoreBaseModel =\n\t\t\t!this.deps.isExplicitModel() && this._profileControlledModel && !profileSettings.model;\n\t\tconst mustRestoreBaseThinking =\n\t\t\t!this.deps.isExplicitThinking() && this._profileControlledThinking && !profileSettings.thinkingLevel;\n\t\tconst baseSelection =\n\t\t\tmustRestoreBaseModel || mustRestoreBaseThinking\n\t\t\t\t? await findInitialModel({\n\t\t\t\t\t\tscopedModels: [],\n\t\t\t\t\t\tisContinuing: true,\n\t\t\t\t\t\tdefaultProvider: settingsManager.getDefaultProvider(),\n\t\t\t\t\t\tdefaultModelId: settingsManager.getDefaultModel(),\n\t\t\t\t\t\tdefaultThinkingLevel: settingsManager.getDefaultThinkingLevel(),\n\t\t\t\t\t\tmodelRegistry: this.deps.getModelRegistry(),\n\t\t\t\t\t})\n\t\t\t\t: undefined;\n\t\tlet modelChanged = false;\n\t\tconst nextModel = profileSettings.model ?? (mustRestoreBaseModel ? baseSelection?.model : undefined);\n\t\tif (!this.deps.isExplicitModel() && nextModel) {\n\t\t\tconst current = this.deps.getAgent().state.model;\n\t\t\tconst next = nextModel;\n\t\t\tif (!current || current.provider !== next.provider || current.id !== next.id) {\n\t\t\t\t// Mirror the startup/cycle path: set the model directly (no auth gate, no settings\n\t\t\t\t// persist) so re-applying the profile model behaves like initial resolution rather\n\t\t\t\t// than a runtime model switch. No model_select emit here — reload rebuilds the\n\t\t\t\t// extension runtime and emits session_start(\"reload\") right after, and the UI\n\t\t\t\t// re-renders from session.model.\n\t\t\t\tthis.deps.getAgent().state.model = next;\n\t\t\t\tthis.deps.getSessionManager().appendModelChange(next.provider, next.id);\n\t\t\t\tmodelChanged = true;\n\t\t\t}\n\t\t}\n\t\tthis._profileControlledModel = !this.deps.isExplicitModel() && Boolean(profileSettings.model);\n\t\tif (!this.deps.isExplicitThinking() && profileSettings.thinkingLevel) {\n\t\t\tthis.deps.setThinkingLevel(profileSettings.thinkingLevel);\n\t\t} else if (mustRestoreBaseThinking && baseSelection) {\n\t\t\tthis.deps.setThinkingLevel(baseSelection.thinkingLevel);\n\t\t} else if (modelChanged) {\n\t\t\t// A model-only situation switch still has to clamp the inherited/explicit level. This\n\t\t\t// prevents Sol/Terra Ultra from leaking into Luna or another model that stops at Max.\n\t\t\tthis.deps.setThinkingLevel(this.deps.getAgent().state.thinkingLevel);\n\t\t}\n\t\tthis._profileControlledThinking = !this.deps.isExplicitThinking() && Boolean(profileSettings.thinkingLevel);\n\t}\n}\n"]}
1
+ {"version":3,"file":"profile-filter-controller.js","sourceRoot":"","sources":["../../src/core/profile-filter-controller.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAIH,OAAO,EAAiC,+BAA+B,EAAE,MAAM,iCAAiC,CAAC;AAGjH,OAAO,EAAE,gBAAgB,EAAE,2BAA2B,EAAE,MAAM,qBAAqB,CAAC;AAEpF,OAAO,EACN,6BAA6B,GAG7B,MAAM,uBAAuB,CAAC;AA8B/B,MAAM,OAAO,uBAAuB;IACnC,qFAAqF;IAC7E,uBAAuB,GAAa,EAAE,CAAC;IAC/C,kGAAkG;IAC1F,4BAA4B,GAAG,CAAC,CAAC;IACzC,2GAA2G;IACnG,uBAAuB,GAAG,KAAK,CAAC;IAChC,0BAA0B,GAAG,KAAK,CAAC;IAE1B,IAAI,CAA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;YACtF,IAAI,CAAC,IAAI,CAAC,gBAAgB,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,CAAC,KAAK,CAAC,aAAa,CAAC,CAAC;QACtE,CAAC;QACD,IAAI,CAAC,0BAA0B,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,kBAAkB,EAAE,IAAI,OAAO,CAAC,eAAe,CAAC,aAAa,CAAC,CAAC;IAAA,CAC5G;CACD","sourcesContent":["/**\n * Resource-profile tool/extension gating + reload-time profile model re-application.\n *\n * Extracted verbatim from agent-session.ts (god-file decomposition). Resolves the active resource\n * profile's tool allow/block filter, filters the runtime extension set (tracking the withheld/inert\n * tallies it owns), reports the /context \"withheld by profile\" observations, and — on reload —\n * re-applies a profile-bound model/thinking level unless an explicit launch flag set them. Owns the\n * inert-extension warnings and profile-denied-extension count; everything else is read through deps.\n */\n\nimport type { Agent, ThinkingLevel } from \"@caupulican/pi-agent-core\";\nimport type { SessionManager } from \"@caupulican/pi-agent-core/node\";\nimport { type ExtensionImportAuthority, isExtensionPathAllowedForImport } from \"./extension-import-authority.ts\";\nimport type { Extension } from \"./extensions/index.ts\";\nimport type { ModelRegistry } from \"./model-registry.ts\";\nimport { findInitialModel, resolveProfileModelSettings } from \"./model-resolver.ts\";\nimport type { ResourceLoader } from \"./resource-loader.ts\";\nimport {\n\tmatchesResourceProfilePattern,\n\ttype ResourceProfileFilterSettings,\n\ttype SettingsManager,\n} from \"./settings-manager.ts\";\n\nexport interface ProfileFilterControllerDeps {\n\tgetSettingsManager(): SettingsManager;\n\tgetResourceLoader(): ResourceLoader;\n\tgetModelRegistry(): ModelRegistry;\n\tgetCwd(): string;\n\tgetAgent(): Agent;\n\tgetSessionManager(): SessionManager;\n\t/** Construction-time tool allow-set (undefined = no allow-list gate). */\n\tgetAllowedToolNames(): Set<string> | undefined;\n\t/** Construction-time tool exclude-set. */\n\tgetExcludedToolNames(): Set<string> | undefined;\n\t/** Live resource-profile tool filter (re-derived on reload; may be undefined). */\n\tgetToolProfileFilter(): Required<ResourceProfileFilterSettings> | undefined;\n\t/** Whether the model was set by an explicit launch flag (profile must not clobber it). */\n\tisExplicitModel(): boolean;\n\t/** Whether the thinking level was set by an explicit launch flag. */\n\tisExplicitThinking(): boolean;\n\t/** Apply a thinking level (delegates to model-selection). */\n\tsetThinkingLevel(level: ThinkingLevel): void;\n}\n\nexport interface ProfileFilterReloadSnapshot {\n\tinertExtensionWarnings: string[];\n\tprofileDeniedExtensionCount: number;\n\tprofileControlledModel: boolean;\n\tprofileControlledThinking: boolean;\n}\n\nexport class ProfileFilterController {\n\t/** G12: extensions loaded but rendered fully inert by the profile's tools filter. */\n\tprivate _inertExtensionWarnings: string[] = [];\n\t/** Count of extensions withheld by the active resource profile (for the /context observation). */\n\tprivate _profileDeniedExtensionCount = 0;\n\t/** Whether the last applied profile generation, rather than the base session selection, owns the field. */\n\tprivate _profileControlledModel = false;\n\tprivate _profileControlledThinking = false;\n\n\tprivate readonly deps: ProfileFilterControllerDeps;\n\n\tconstructor(deps: ProfileFilterControllerDeps) {\n\t\tthis.deps = deps;\n\t}\n\n\t/** Inert-extension warnings tracked by the last {@link filterExtensionsForRuntime} pass. */\n\tgetInertExtensionWarnings(): string[] {\n\t\treturn this._inertExtensionWarnings;\n\t}\n\n\tcreateReloadSnapshot(): ProfileFilterReloadSnapshot {\n\t\treturn {\n\t\t\tinertExtensionWarnings: [...this._inertExtensionWarnings],\n\t\t\tprofileDeniedExtensionCount: this._profileDeniedExtensionCount,\n\t\t\tprofileControlledModel: this._profileControlledModel,\n\t\t\tprofileControlledThinking: this._profileControlledThinking,\n\t\t};\n\t}\n\n\trestoreReloadSnapshot(snapshot: ProfileFilterReloadSnapshot): void {\n\t\tthis._inertExtensionWarnings = [...snapshot.inertExtensionWarnings];\n\t\tthis._profileDeniedExtensionCount = snapshot.profileDeniedExtensionCount;\n\t\tthis._profileControlledModel = snapshot.profileControlledModel;\n\t\tthis._profileControlledThinking = snapshot.profileControlledThinking;\n\t}\n\n\t/**\n\t * Resolve the active resource-profile tool allow/block filter from current settings.\n\t * Mirrors the construction-time derivation (settingsManager.getResourceProfileFilter(\"tools\"))\n\t * so reload() can re-apply it after a live settings/profile edit.\n\t */\n\tderiveToolProfileFilter(): Required<ResourceProfileFilterSettings> {\n\t\tconst filter = this.deps.getSettingsManager().getResourceProfileFilter(\"tools\");\n\t\treturn { allow: filter.allow ?? [], block: filter.block ?? [] };\n\t}\n\n\tisToolOrCommandAllowedByProfile(name: string): boolean {\n\t\tconst allowedToolNames = this.deps.getAllowedToolNames();\n\t\tconst excludedToolNames = this.deps.getExcludedToolNames();\n\t\tif (allowedToolNames && !allowedToolNames.has(name)) return false;\n\t\tif (excludedToolNames?.has(name)) return false;\n\t\tconst filter = this.deps.getToolProfileFilter();\n\t\tif (!filter) return true;\n\t\tif (filter.allow.length > 0 && !matchesResourceProfilePattern(name, filter.allow)) return false;\n\t\tif (matchesResourceProfilePattern(name, filter.block)) return false;\n\t\treturn true;\n\t}\n\n\tprivate _hasToolOrCommandProfileGate(): boolean {\n\t\tconst toolProfileFilter = this.deps.getToolProfileFilter();\n\t\treturn Boolean(\n\t\t\tthis.deps.getAllowedToolNames() ||\n\t\t\t\tthis.deps.getExcludedToolNames() ||\n\t\t\t\t(toolProfileFilter && (toolProfileFilter.allow.length > 0 || toolProfileFilter.block.length > 0)),\n\t\t);\n\t}\n\n\t/**\n\t * Decide whether a path has authority to cross the import boundary. Explicit owner loads may\n\t * proceed without a profile, while discovery-driven loads require an active profile grant.\n\t * User disables remain a hard stop for both paths.\n\t */\n\tisExtensionPathAllowed(extensionPath: string, authority: ExtensionImportAuthority, baseDir = \"\"): boolean {\n\t\treturn isExtensionPathAllowedForImport(this.deps.getSettingsManager(), extensionPath, authority, baseDir);\n\t}\n\n\tfilterExtensionsForRuntime(extensions: Extension[], explicitLiveExtensionPaths?: ReadonlySet<string>): Extension[] {\n\t\tconst settingsManager = this.deps.getSettingsManager();\n\t\tthis._inertExtensionWarnings = [];\n\t\tthis._profileDeniedExtensionCount = 0;\n\t\tif (settingsManager.getActiveResourceProfileNames().length === 0) {\n\t\t\tif (settingsManager.hasExplicitActiveResourceProfileSelection()) {\n\t\t\t\t// An explicit profile selection that resolves to no active profile is a deliberate\n\t\t\t\t// deny-all — every extension is withheld by that choice.\n\t\t\t\tthis._profileDeniedExtensionCount = extensions.length;\n\t\t\t\treturn [];\n\t\t\t}\n\t\t\t// No profile in play: inline/SDK extensions and exact owner-approved CLI/live loads are the\n\t\t\t// only runtime authorities. Discovery alone must never promote an extension into executable code.\n\t\t\t// This baseline is not a profile denial, so it is not counted as withheld.\n\t\t\treturn extensions.filter((extension) => {\n\t\t\t\tif (extension.sourceInfo.source === \"inline\") return true;\n\t\t\t\tconst explicitlyApproved =\n\t\t\t\t\textension.sourceInfo.source === \"cli\" ||\n\t\t\t\t\texplicitLiveExtensionPaths?.has(extension.path) === true ||\n\t\t\t\t\texplicitLiveExtensionPaths?.has(extension.resolvedPath) === true;\n\t\t\t\treturn (\n\t\t\t\t\texplicitlyApproved &&\n\t\t\t\t\tthis.isExtensionPathAllowed(extension.path, \"explicit\", extension.sourceInfo.baseDir)\n\t\t\t\t);\n\t\t\t});\n\t\t}\n\t\tconst hasToolOrCommandGate = this._hasToolOrCommandProfileGate();\n\t\tconst allowedExtensions = extensions.filter((extension) =>\n\t\t\tthis.isExtensionPathAllowed(extension.path, \"profile\", extension.sourceInfo.baseDir),\n\t\t);\n\t\tthis._profileDeniedExtensionCount = extensions.length - allowedExtensions.length;\n\t\treturn allowedExtensions.map((extension) => {\n\t\t\tif (!hasToolOrCommandGate) return extension;\n\t\t\tconst tools = new Map(\n\t\t\t\tArray.from(extension.tools.entries()).filter(([name]) => this.isToolOrCommandAllowedByProfile(name)),\n\t\t\t);\n\t\t\tconst commands = new Map(\n\t\t\t\tArray.from(extension.commands.entries()).filter(([name]) => this.isToolOrCommandAllowedByProfile(name)),\n\t\t\t);\n\t\t\t// G12: an extension the profile ALLOWS whose every tool and command the tools filter\n\t\t\t// then denies loads and runs lifecycle hooks but is completely uninvocable — surface\n\t\t\t// it instead of presenting a \"loaded\" extension that silently does nothing.\n\t\t\tif (extension.tools.size + extension.commands.size > 0 && tools.size + commands.size === 0) {\n\t\t\t\tconst name = extension.path.split(/[\\\\/]/).pop() ?? extension.path;\n\t\t\t\tthis._inertExtensionWarnings.push(\n\t\t\t\t\t`extension \"${name}\" is loaded but fully inert: the active profile's tools filter denies all ${extension.tools.size} tool(s) and ${extension.commands.size} command(s) it contributes`,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn { ...extension, tools, commands };\n\t\t});\n\t}\n\n\t/**\n\t * /context observations for skills/prompts/extensions the active resource profile removed from\n\t * listings — the analog of the withheld-AGENTS.md warning. Strict UAC makes these silently absent,\n\t * so a lean profile's effect on the resource surface stays visible. Counts are profile-scoped\n\t * (skills/prompts via the profile-independent discovery universe filtered by the live profile\n\t * filter; extensions via the runtime filter's denied tally). Empty when nothing is withheld.\n\t *\n\t * Uses `isResourceDeniedByActiveProfile` (profile-only), not `isResourceAllowedByProfile` (which\n\t * also folds in the user's own legacy `disabledResources` list): a plain user-disabled resource\n\t * must never be misattributed to \"the active resource profile\" — that case is already surfaced by\n\t * the G14 disable-wins warning. With no active profile at all, the helper always reports nothing\n\t * denied, so this naturally stays silent (extensions keep their own runtime-filter-derived count,\n\t * which is already correctly zero absent a profile).\n\t */\n\tprofileDeniedResourceObservations(): string[] {\n\t\tconst settingsManager = this.deps.getSettingsManager();\n\t\tconst resourceLoader = this.deps.getResourceLoader();\n\t\tconst cwd = this.deps.getCwd();\n\t\tconst observations: string[] = [];\n\t\tconst withheld = (kind: \"skills\" | \"prompts\", paths: string[]): number =>\n\t\t\tpaths.filter((path) => settingsManager.isResourceDeniedByActiveProfile(kind, path, cwd)).length;\n\n\t\tconst skillsWithheld = withheld(\"skills\", resourceLoader.getDiscoverableSkillPaths());\n\t\tif (skillsWithheld > 0) {\n\t\t\tobservations.push(\n\t\t\t\t`${skillsWithheld} skill(s) withheld by the active resource profile — grant the \"skills\" kind to restore them`,\n\t\t\t);\n\t\t}\n\t\tconst promptsWithheld = withheld(\"prompts\", resourceLoader.getDiscoverablePromptPaths());\n\t\tif (promptsWithheld > 0) {\n\t\t\tobservations.push(\n\t\t\t\t`${promptsWithheld} prompt(s) withheld by the active resource profile — grant the \"prompts\" kind to restore them`,\n\t\t\t);\n\t\t}\n\t\tif (this._profileDeniedExtensionCount > 0) {\n\t\t\tobservations.push(\n\t\t\t\t`${this._profileDeniedExtensionCount} extension(s) withheld by the active resource profile — grant the \"extensions\" kind to restore them`,\n\t\t\t);\n\t\t}\n\t\treturn observations;\n\t}\n\n\t/**\n\t * Re-resolve the active resource profile's model/thinking from current settings and apply it.\n\t * Only acts when the profile actually binds model/thinking AND that field was not set by an\n\t * explicit launch flag — so live profile edits apply on reload without clobbering an explicit\n\t * --model/--thinking. A no-op for profiles that don't bind a model.\n\t */\n\tasync reapplyActiveProfileModelSettings(): Promise<void> {\n\t\tif (this.deps.isExplicitModel() && this.deps.isExplicitThinking()) return;\n\t\tconst settingsManager = this.deps.getSettingsManager();\n\t\tconst activeProfileNames = settingsManager.getActiveResourceProfileNames();\n\t\tconst profileSettings =\n\t\t\tactiveProfileNames.length > 0\n\t\t\t\t? resolveProfileModelSettings({\n\t\t\t\t\t\tactiveProfileNames,\n\t\t\t\t\t\tregistry: settingsManager.getProfileRegistry(),\n\t\t\t\t\t\tmodelRegistry: this.deps.getModelRegistry(),\n\t\t\t\t\t\tcwd: this.deps.getCwd(),\n\t\t\t\t\t})\n\t\t\t\t: {};\n\t\tif (profileSettings.error) {\n\t\t\tthrow new Error(`Profile model resolution error: ${profileSettings.error}`);\n\t\t}\n\t\tconst mustRestoreBaseModel =\n\t\t\t!this.deps.isExplicitModel() && this._profileControlledModel && !profileSettings.model;\n\t\tconst mustRestoreBaseThinking =\n\t\t\t!this.deps.isExplicitThinking() && this._profileControlledThinking && !profileSettings.thinkingLevel;\n\t\tconst baseSelection =\n\t\t\tmustRestoreBaseModel || mustRestoreBaseThinking\n\t\t\t\t? await findInitialModel({\n\t\t\t\t\t\tscopedModels: [],\n\t\t\t\t\t\tisContinuing: true,\n\t\t\t\t\t\tdefaultProvider: settingsManager.getDefaultProvider(),\n\t\t\t\t\t\tdefaultModelId: settingsManager.getDefaultModel(),\n\t\t\t\t\t\tdefaultThinkingLevel: settingsManager.getDefaultThinkingLevel(),\n\t\t\t\t\t\tmodelRegistry: this.deps.getModelRegistry(),\n\t\t\t\t\t})\n\t\t\t\t: undefined;\n\t\tlet modelChanged = false;\n\t\tconst nextModel = profileSettings.model ?? (mustRestoreBaseModel ? baseSelection?.model : undefined);\n\t\tif (!this.deps.isExplicitModel() && nextModel) {\n\t\t\tconst current = this.deps.getAgent().state.model;\n\t\t\tconst next = nextModel;\n\t\t\tif (!current || current.provider !== next.provider || current.id !== next.id) {\n\t\t\t\t// Mirror the startup/cycle path: set the model directly (no auth gate, no settings\n\t\t\t\t// persist) so re-applying the profile model behaves like initial resolution rather\n\t\t\t\t// than a runtime model switch. No model_select emit here — reload rebuilds the\n\t\t\t\t// extension runtime and emits session_start(\"reload\") right after, and the UI\n\t\t\t\t// re-renders from session.model.\n\t\t\t\tthis.deps.getAgent().state.model = next;\n\t\t\t\tthis.deps.getSessionManager().appendModelChange(next.provider, next.id);\n\t\t\t\tmodelChanged = true;\n\t\t\t}\n\t\t}\n\t\tthis._profileControlledModel = !this.deps.isExplicitModel() && Boolean(profileSettings.model);\n\t\tif (!this.deps.isExplicitThinking() && profileSettings.thinkingLevel) {\n\t\t\tthis.deps.setThinkingLevel(profileSettings.thinkingLevel);\n\t\t} else if (mustRestoreBaseThinking && baseSelection) {\n\t\t\tthis.deps.setThinkingLevel(baseSelection.thinkingLevel);\n\t\t} else if (modelChanged) {\n\t\t\t// A model-only situation switch still has to clamp the inherited/explicit level. This\n\t\t\t// prevents Sol/Terra Ultra from leaking into Luna or another model that stops at Max.\n\t\t\tthis.deps.setThinkingLevel(this.deps.getAgent().state.thinkingLevel);\n\t\t}\n\t\tthis._profileControlledThinking = !this.deps.isExplicitThinking() && Boolean(profileSettings.thinkingLevel);\n\t}\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"profile-registry.d.ts","sourceRoot":"","sources":["../../src/core/profile-registry.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAM/D,OAAO,KAAK,EACX,mBAAmB,EACnB,sBAAsB,EAEtB,uBAAuB,EACvB,QAAQ,EACR,MAAM,uBAAuB,CAAC;AAG/B,MAAM,MAAM,aAAa,GACtB,iBAAiB,GACjB,kBAAkB,GAClB,mBAAmB,GACnB,cAAc,GACd,mBAAmB,GACnB,QAAQ,GACR,UAAU,GACV,QAAQ,CAAC;AAEZ,MAAM,WAAW,iBAAiB;IACjC,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,QAAQ,CAAC,EAAE,aAAa,CAAC;IACzB,WAAW,CAAC,EAAE,mBAAmB,CAAC;IAClC,8FAA8F;IAC9F,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,SAAS,EAAE,uBAAuB,CAAC;IACnC,MAAM,EAAE,aAAa,CAAC;IACtB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,OAAO,CAAC,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,yBAAyB;IACzC,MAAM,EAAE,aAAa,CAAC;IACtB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,OAAO,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,sBAAsB;IACtC,cAAc,EAAE,QAAQ,CAAC;IACzB,eAAe,EAAE,QAAQ,CAAC;IAC1B,wBAAwB,EAAE,QAAQ,CAAC;IACnC,gCAAgC,EAAE,MAAM,CAAC,MAAM,EAAE,sBAAsB,CAAC,CAAC;IACzE,oCAAoC,EAAE,MAAM,CAAC,MAAM,EAAE,uBAAuB,CAAC,CAAC;IAC9E,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,qBAAqB,CAAC,EAAE,MAAM,EAAE,CAAC;CACjC;AAID,6FAA6F;AAC7F,eAAO,MAAM,uBAAuB,eAAe,CAAC;AAUpD;;;GAGG;AACH,eAAO,MAAM,0BAA0B,EAAE,iBAKxC,CAAC;AAgOF,qBAAa,eAAe;IAC3B,OAAO,CAAC,OAAO,CAAyB;IACxC,OAAO,CAAC,WAAW,CAAmC;IAEtD,YAAY,OAAO,EAAE,sBAAsB,EAE1C;IAED,eAAe,IAAI,yBAAyB,EAAE,CAG7C;IAED,YAAY,IAAI,iBAAiB,EAAE,CAgBlC;IAED,UAAU,CAAC,IAAI,EAAE,MAAM,GAAG,iBAAiB,GAAG,SAAS,CAItD;IAED,iBAAiB,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,iBAAiB,GAAG,SAAS,CAQ7E;IAED,OAAO,CAAC,iBAAiB;IAkCzB,OAAO,CAAC,gBAAgB;IA8CxB,OAAO,CAAC,4BAA4B;IAQpC,OAAO,CAAC,eAAe;CAuBvB","sourcesContent":["import type { ThinkingLevel } from \"@caupulican/pi-agent-core\";\nimport { existsSync, readdirSync, readFileSync, statSync } from \"fs\";\nimport { basename, dirname, join, resolve } from \"path\";\nimport { isValidThinkingLevel } from \"../cli/args.ts\";\nimport { resolvePath } from \"../utils/paths.ts\";\nimport { mergeResourceProfileSettings } from \"./resource-profile-blocks.ts\";\nimport type {\n\tModelRouterSettings,\n\tProfileDefinitionInput,\n\tResourceProfileKind,\n\tResourceProfileSettings,\n\tSettings,\n} from \"./settings-manager.ts\";\nimport { validateSkillName } from \"./skills.ts\";\n\nexport type ProfileSource =\n\t| \"global-settings\"\n\t| \"project-settings\"\n\t| \"external-settings\"\n\t| \"profile-file\"\n\t| \"directory-overlay\"\n\t| \"inline\"\n\t| \"embedded\"\n\t| \"bundle\";\n\nexport interface NormalizedProfile {\n\tname: string;\n\tdescription?: string;\n\tmodel?: string;\n\tthinking?: ThinkingLevel;\n\tmodelRouter?: ModelRouterSettings;\n\t/** Situational identity injected into the system prompt while this profile is active (R6). */\n\tsoul?: string;\n\tresources: ResourceProfileSettings;\n\tsource: ProfileSource;\n\tsourcePath?: string;\n\tbaseDir?: string;\n}\n\nexport interface ProfileRegistryDiagnostic {\n\tsource: ProfileSource;\n\tpath?: string;\n\tmessage: string;\n}\n\nexport interface ProfileRegistryOptions {\n\tglobalSettings: Settings;\n\tprojectSettings: Settings;\n\tdirectoryProfileSettings: Settings;\n\tinlineResourceProfileDefinitions: Record<string, ProfileDefinitionInput>;\n\tdiscoveredResourceProfileDefinitions: Record<string, ResourceProfileSettings>;\n\tprofilesDir?: string;\n\texternalResourceRoots?: string[];\n}\n\nconst RESOURCE_PROFILE_KINDS: ResourceProfileKind[] = [\"extensions\", \"skills\", \"prompts\", \"themes\", \"agents\", \"tools\"];\n\n/** Name of the built-in, always-available profile that enables every discovered resource. */\nexport const ALL_ACTIVE_PROFILE_NAME = \"all-active\";\n\nfunction buildAllActiveResources(): ResourceProfileSettings {\n\tconst resources: ResourceProfileSettings = {};\n\tfor (const kind of RESOURCE_PROFILE_KINDS) {\n\t\tresources[kind] = { allow: [\"*\"] };\n\t}\n\treturn resources;\n}\n\n/**\n * The built-in \"all-active\" profile. Registered as the weakest candidate in\n * `collectCandidates()` so any user-defined profile of the same name overrides it.\n */\nexport const ALL_ACTIVE_BUILTIN_PROFILE: NormalizedProfile = {\n\tname: ALL_ACTIVE_PROFILE_NAME,\n\tdescription: \"Everything on: all discovered extensions, skills, prompts, themes, agents, and tools\",\n\tresources: buildAllActiveResources(),\n\tsource: \"embedded\",\n};\n\ninterface ProfileCandidate {\n\tprofile: NormalizedProfile;\n\tprecedence: number;\n\torder: number;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn Boolean(value) && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction asNonEmptyString(value: unknown): string | undefined {\n\treturn typeof value === \"string\" && value.trim().length > 0 ? value.trim() : undefined;\n}\n\nfunction asStringArray(value: unknown): string[] | undefined {\n\tif (!Array.isArray(value)) return undefined;\n\tconst strings = value.filter((item): item is string => typeof item === \"string\" && item.trim().length > 0);\n\treturn strings.length > 0 ? strings : undefined;\n}\n\nfunction shouldResolveAgainstBaseDir(pattern: string): boolean {\n\treturn pattern.startsWith(\"./\") || pattern.startsWith(\"../\");\n}\n\nfunction normalizePattern(pattern: string, baseDir: string | undefined): string {\n\tconst trimmed = pattern.trim();\n\tif (!baseDir || !shouldResolveAgainstBaseDir(trimmed)) return trimmed;\n\treturn resolvePath(trimmed, baseDir, { trim: true });\n}\n\nfunction normalizeStringArray(value: unknown, baseDir: string | undefined): string[] | undefined {\n\tconst strings = asStringArray(value);\n\tif (!strings) return undefined;\n\treturn strings.map((pattern) => normalizePattern(pattern, baseDir));\n}\n\nfunction normalizeResourceProfileSettings(value: unknown, baseDir: string | undefined): ResourceProfileSettings {\n\tif (!isRecord(value)) {\n\t\tthrow new Error(\"resources must be an object\");\n\t}\n\tconst result: ResourceProfileSettings = {};\n\tfor (const kind of RESOURCE_PROFILE_KINDS) {\n\t\tconst filterValue = value[kind];\n\t\tif (filterValue === undefined) continue;\n\t\tif (!isRecord(filterValue)) {\n\t\t\tthrow new Error(`${kind} filter must be an object`);\n\t\t}\n\t\tconst allow = normalizeStringArray(filterValue.allow, baseDir);\n\t\tconst block = normalizeStringArray(filterValue.block, baseDir);\n\t\tresult[kind] = { allow, block };\n\t}\n\treturn result;\n}\n\nfunction validateProfileName(name: string): string[] {\n\treturn validateSkillName(name);\n}\n\nfunction normalizeThinking(value: unknown): ThinkingLevel | undefined {\n\tconst thinking = asNonEmptyString(value);\n\tif (!thinking) return undefined;\n\tif (!isValidThinkingLevel(thinking)) {\n\t\tthrow new Error(`thinking must be one of off, minimal, low, medium, high, xhigh, max, ultra`);\n\t}\n\treturn thinking;\n}\n\nfunction normalizeModelRouterSettings(value: unknown): ModelRouterSettings | undefined {\n\tif (!isRecord(value)) return undefined;\n\tconst settings: ModelRouterSettings = {};\n\tfor (const key of [\"enabled\", \"judgeEnabled\", \"fitnessGate\"] as const) {\n\t\tconst candidate = value[key];\n\t\tif (typeof candidate === \"boolean\") settings[key] = candidate;\n\t}\n\tfor (const key of [\n\t\t\"cheapModel\",\n\t\t\"mediumModel\",\n\t\t\"expensiveModel\",\n\t\t\"learningModel\",\n\t\t\"judgeModel\",\n\t\t\"executorModel\",\n\t] as const) {\n\t\tconst candidate = asNonEmptyString(value[key]);\n\t\tif (candidate) settings[key] = candidate;\n\t}\n\tfor (const key of [\n\t\t\"cheapThinking\",\n\t\t\"mediumThinking\",\n\t\t\"expensiveThinking\",\n\t\t\"executorThinking\",\n\t\t\"judgeThinking\",\n\t] as const) {\n\t\tconst candidate = asNonEmptyString(value[key]);\n\t\tif (!candidate) continue;\n\t\tif (!isValidThinkingLevel(candidate)) {\n\t\t\tthrow new Error(`${key} must be one of off, minimal, low, medium, high, xhigh, max, ultra`);\n\t\t}\n\t\tsettings[key] = candidate;\n\t}\n\treturn Object.keys(settings).length > 0 ? settings : undefined;\n}\n\nfunction normalizeWrapperProfile(options: {\n\tvalue: unknown;\n\tsource: ProfileSource;\n\tsourcePath?: string;\n\tbaseDir?: string;\n\tfallbackName?: string;\n}): NormalizedProfile {\n\tif (!isRecord(options.value)) {\n\t\tthrow new Error(\"profile JSON must be an object\");\n\t}\n\tconst name = asNonEmptyString(options.value.name) ?? options.fallbackName;\n\tif (!name) {\n\t\tthrow new Error(\"profile name is required\");\n\t}\n\tconst nameErrors = validateProfileName(name);\n\tif (nameErrors.length > 0) {\n\t\tthrow new Error(`invalid profile name \"${name}\": ${nameErrors.join(\", \")}`);\n\t}\n\tconst resources = normalizeResourceProfileSettings(options.value.resources ?? {}, options.baseDir);\n\tconst description = asNonEmptyString(options.value.description);\n\tconst model = asNonEmptyString(options.value.model);\n\tconst thinking = normalizeThinking(options.value.thinking);\n\tconst modelRouter = normalizeModelRouterSettings(options.value.modelRouter);\n\tconst soul = asNonEmptyString(options.value.soul);\n\treturn {\n\t\tname,\n\t\tdescription,\n\t\tmodel,\n\t\tthinking,\n\t\tmodelRouter,\n\t\tsoul,\n\t\tresources,\n\t\tsource: options.source,\n\t\tsourcePath: options.sourcePath,\n\t\tbaseDir: options.baseDir,\n\t};\n}\n\nfunction normalizeSettingsProfiles(\n\tsettings: Settings,\n\tsource: ProfileSource,\n\tbaseDir?: string,\n\tsourcePath?: string,\n): Array<Omit<NormalizedProfile, \"source\"> & { source?: ProfileSource }> {\n\tconst profiles: Array<Omit<NormalizedProfile, \"source\"> & { source?: ProfileSource }> = [];\n\tfor (const [name, definition] of Object.entries(settings.resourceProfiles ?? {})) {\n\t\tconst nameErrors = validateProfileName(name);\n\t\tif (nameErrors.length > 0) continue;\n\t\tif (isRecord(definition) && Object.hasOwn(definition, \"resources\")) {\n\t\t\tprofiles.push(\n\t\t\t\tnormalizeWrapperProfile({\n\t\t\t\t\tvalue: { ...definition, name },\n\t\t\t\t\tsource,\n\t\t\t\t\tsourcePath,\n\t\t\t\t\tbaseDir,\n\t\t\t\t\tfallbackName: name,\n\t\t\t\t}),\n\t\t\t);\n\t\t\tcontinue;\n\t\t}\n\t\tprofiles.push({\n\t\t\tname,\n\t\t\tresources: mergeResourceProfileSettings(undefined, definition as ResourceProfileSettings),\n\t\t\tsourcePath,\n\t\t\tbaseDir,\n\t\t});\n\t}\n\treturn profiles.map((profile) => ({ ...profile, source }));\n}\n\nfunction normalizeInlineDefinitions(\n\tdefinitions: Record<string, ProfileDefinitionInput>,\n\tsource: ProfileSource,\n): NormalizedProfile[] {\n\tconst profiles: NormalizedProfile[] = [];\n\tfor (const [name, definition] of Object.entries(definitions)) {\n\t\ttry {\n\t\t\tprofiles.push(\n\t\t\t\tnormalizeWrapperProfile({\n\t\t\t\t\tvalue: { ...definition, name },\n\t\t\t\t\tsource,\n\t\t\t\t\tfallbackName: name,\n\t\t\t\t}),\n\t\t\t);\n\t\t} catch {\n\t\t\t// Inline names/definitions are validated at the SettingsManager API boundary.\n\t\t}\n\t}\n\treturn profiles;\n}\n\nfunction loadSettingsFileProfiles(sourcePath: string, source: ProfileSource): NormalizedProfile[] {\n\ttry {\n\t\tconst stats = statSync(sourcePath);\n\t\tif (!stats.isFile()) return [];\n\t\tconst parsed = JSON.parse(readFileSync(sourcePath, \"utf-8\")) as Settings;\n\t\treturn normalizeSettingsProfiles(parsed, source, dirname(resolve(sourcePath)), resolve(sourcePath)).map(\n\t\t\t(profile) => ({\n\t\t\t\t...profile,\n\t\t\t\tsource,\n\t\t\t}),\n\t\t);\n\t} catch {\n\t\treturn [];\n\t}\n}\n\nfunction normalizeDefinitions(\n\tdefinitions: Record<string, ResourceProfileSettings>,\n\tsource: ProfileSource,\n): NormalizedProfile[] {\n\tconst profiles: NormalizedProfile[] = [];\n\tfor (const [name, resources] of Object.entries(definitions)) {\n\t\tconst nameErrors = validateProfileName(name);\n\t\tif (nameErrors.length > 0) continue;\n\t\tprofiles.push({ name, resources: mergeResourceProfileSettings(undefined, resources), source });\n\t}\n\treturn profiles;\n}\n\nexport class ProfileRegistry {\n\tprivate options: ProfileRegistryOptions;\n\tprivate diagnostics: ProfileRegistryDiagnostic[] = [];\n\n\tconstructor(options: ProfileRegistryOptions) {\n\t\tthis.options = options;\n\t}\n\n\tlistDiagnostics(): ProfileRegistryDiagnostic[] {\n\t\tthis.collectCandidates();\n\t\treturn [...this.diagnostics];\n\t}\n\n\tlistProfiles(): NormalizedProfile[] {\n\t\tconst candidates = this.collectCandidates();\n\t\tconst winners = new Map<string, ProfileCandidate>();\n\t\tfor (const candidate of candidates) {\n\t\t\tconst existing = winners.get(candidate.profile.name);\n\t\t\tif (\n\t\t\t\t!existing ||\n\t\t\t\tcandidate.precedence < existing.precedence ||\n\t\t\t\t(candidate.precedence === existing.precedence && candidate.order < existing.order)\n\t\t\t) {\n\t\t\t\twinners.set(candidate.profile.name, candidate);\n\t\t\t}\n\t\t}\n\t\treturn Array.from(winners.values())\n\t\t\t.sort((a, b) => a.profile.name.localeCompare(b.profile.name))\n\t\t\t.map((candidate) => candidate.profile);\n\t}\n\n\tgetProfile(name: string): NormalizedProfile | undefined {\n\t\tconst trimmed = name.trim();\n\t\tif (!trimmed) return undefined;\n\t\treturn this.listProfiles().find((profile) => profile.name === trimmed);\n\t}\n\n\tresolveProfileRef(ref: string, fromDir: string): NormalizedProfile | undefined {\n\t\tconst trimmed = ref.trim();\n\t\tif (!trimmed) return undefined;\n\t\tif (trimmed.startsWith(\"./\") || trimmed.startsWith(\"../\")) {\n\t\t\tconst sourcePath = resolvePath(trimmed, fromDir, { trim: true });\n\t\t\treturn this.loadProfileFile(sourcePath, \"profile-file\", 0)?.profile;\n\t\t}\n\t\treturn this.getProfile(trimmed);\n\t}\n\n\tprivate collectCandidates(): ProfileCandidate[] {\n\t\tthis.diagnostics = [];\n\t\tconst candidates: ProfileCandidate[] = [];\n\t\tlet order = 0;\n\t\tconst add = (profile: NormalizedProfile, precedence: number): void => {\n\t\t\tcandidates.push({ profile, precedence, order: order++ });\n\t\t};\n\n\t\tfor (const profile of normalizeInlineDefinitions(this.options.inlineResourceProfileDefinitions, \"inline\")) {\n\t\t\tadd(profile, 1);\n\t\t}\n\t\tfor (const profile of normalizeSettingsProfiles(this.options.directoryProfileSettings, \"directory-overlay\")) {\n\t\t\tadd({ ...profile, source: \"directory-overlay\" }, 2);\n\t\t}\n\t\tfor (const profile of normalizeSettingsProfiles(this.options.projectSettings, \"project-settings\")) {\n\t\t\tadd({ ...profile, source: \"project-settings\" }, 3);\n\t\t}\n\t\tfor (const profile of this.loadProfileFiles()) {\n\t\t\tadd(profile.profile, profile.precedence);\n\t\t}\n\t\tfor (const profile of this.loadExternalSettingsProfiles()) {\n\t\t\tadd(profile, 4.2);\n\t\t}\n\t\tfor (const profile of normalizeSettingsProfiles(this.options.globalSettings, \"global-settings\")) {\n\t\t\tadd({ ...profile, source: \"global-settings\" }, 5);\n\t\t}\n\t\tfor (const profile of normalizeDefinitions(this.options.discoveredResourceProfileDefinitions, \"embedded\")) {\n\t\t\tadd(profile, 6);\n\t\t}\n\t\tadd(ALL_ACTIVE_BUILTIN_PROFILE, 7);\n\n\t\treturn candidates;\n\t}\n\n\tprivate loadProfileFiles(): ProfileCandidate[] {\n\t\tconst candidates: ProfileCandidate[] = [];\n\t\tlet order = 0;\n\n\t\tconst profilesDir = this.options.profilesDir;\n\t\tif (profilesDir && existsSync(profilesDir)) {\n\t\t\ttry {\n\t\t\t\tconst entries = readdirSync(profilesDir)\n\t\t\t\t\t.filter((entry) => entry.endsWith(\".json\"))\n\t\t\t\t\t.sort();\n\t\t\t\tfor (const entry of entries) {\n\t\t\t\t\tconst sourcePath = join(profilesDir, entry);\n\t\t\t\t\tconst loaded = this.loadProfileFile(sourcePath, \"profile-file\", order++);\n\t\t\t\t\tif (loaded) {\n\t\t\t\t\t\tcandidates.push({ ...loaded, precedence: 4 });\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tthis.diagnostics.push({ source: \"profile-file\", path: profilesDir, message: String(error) });\n\t\t\t}\n\t\t}\n\n\t\tconst externalRoots = this.options.externalResourceRoots ?? [];\n\t\tfor (const root of externalRoots) {\n\t\t\tconst extProfilesDir = join(root, \"profiles\");\n\t\t\tif (existsSync(extProfilesDir)) {\n\t\t\t\ttry {\n\t\t\t\t\tconst entries = readdirSync(extProfilesDir)\n\t\t\t\t\t\t.filter((entry) => entry.endsWith(\".json\"))\n\t\t\t\t\t\t.sort();\n\t\t\t\t\tfor (const entry of entries) {\n\t\t\t\t\t\tconst sourcePath = join(extProfilesDir, entry);\n\t\t\t\t\t\tconst loaded = this.loadProfileFile(sourcePath, \"profile-file\", order++);\n\t\t\t\t\t\tif (loaded) {\n\t\t\t\t\t\t\tcandidates.push({ ...loaded, precedence: 4.1 });\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} catch (error) {\n\t\t\t\t\tthis.diagnostics.push({ source: \"profile-file\", path: extProfilesDir, message: String(error) });\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn candidates;\n\t}\n\n\tprivate loadExternalSettingsProfiles(): NormalizedProfile[] {\n\t\tconst profiles: NormalizedProfile[] = [];\n\t\tfor (const root of this.options.externalResourceRoots ?? []) {\n\t\t\tprofiles.push(...loadSettingsFileProfiles(join(root, \"settings.json\"), \"external-settings\"));\n\t\t}\n\t\treturn profiles;\n\t}\n\n\tprivate loadProfileFile(sourcePath: string, source: ProfileSource, order: number): ProfileCandidate | undefined {\n\t\ttry {\n\t\t\tconst stats = statSync(sourcePath);\n\t\t\tif (!stats.isFile()) return undefined;\n\t\t\tconst parsed = JSON.parse(readFileSync(sourcePath, \"utf-8\"));\n\t\t\tconst fallbackName = basename(sourcePath, \".json\");\n\t\t\treturn {\n\t\t\t\tprofile: normalizeWrapperProfile({\n\t\t\t\t\tvalue: parsed,\n\t\t\t\t\tsource,\n\t\t\t\t\tsourcePath: resolve(sourcePath),\n\t\t\t\t\tbaseDir: dirname(resolve(sourcePath)),\n\t\t\t\t\tfallbackName,\n\t\t\t\t}),\n\t\t\t\tprecedence: 0,\n\t\t\t\torder,\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tthis.diagnostics.push({ source, path: sourcePath, message });\n\t\t\treturn undefined;\n\t\t}\n\t}\n}\n"]}
1
+ {"version":3,"file":"profile-registry.d.ts","sourceRoot":"","sources":["../../src/core/profile-registry.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAM/D,OAAO,KAAK,EACX,mBAAmB,EACnB,sBAAsB,EAEtB,uBAAuB,EACvB,QAAQ,EACR,MAAM,uBAAuB,CAAC;AAI/B,MAAM,MAAM,aAAa,GACtB,iBAAiB,GACjB,kBAAkB,GAClB,mBAAmB,GACnB,cAAc,GACd,mBAAmB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,CAAC,IAAI,EAAE,MAAM,GAAG,iBAAiB,GAAG,SAAS,CAItD;IAED,iBAAiB,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,iBAAiB,GAAG,SAAS,CAQ7E;IAED,OAAO,CAAC,iBAAiB;IAkCzB,OAAO,CAAC,gBAAgB;IA8CxB,OAAO,CAAC,4BAA4B;IAQpC,OAAO,CAAC,eAAe;CAuBvB","sourcesContent":["import type { ThinkingLevel } from \"@caupulican/pi-agent-core\";\nimport { existsSync, readdirSync, readFileSync, statSync } from \"fs\";\nimport { basename, dirname, join, resolve } from \"path\";\nimport { isValidThinkingLevel } from \"../cli/args.ts\";\nimport { resolvePath } from \"../utils/paths.ts\";\nimport { mergeResourceProfileSettings } from \"./resource-profile-blocks.ts\";\nimport type {\n\tModelRouterSettings,\n\tProfileDefinitionInput,\n\tResourceProfileKind,\n\tResourceProfileSettings,\n\tSettings,\n} from \"./settings-manager.ts\";\nimport { validateSkillName } from \"./skills.ts\";\nimport { isRecordObject } from \"./util/value-guards.ts\";\n\nexport type ProfileSource =\n\t| \"global-settings\"\n\t| \"project-settings\"\n\t| \"external-settings\"\n\t| \"profile-file\"\n\t| \"directory-overlay\"\n\t| \"inline\"\n\t| \"embedded\"\n\t| \"bundle\";\n\nexport interface NormalizedProfile {\n\tname: string;\n\tdescription?: string;\n\tmodel?: string;\n\tthinking?: ThinkingLevel;\n\tmodelRouter?: ModelRouterSettings;\n\t/** Situational identity injected into the system prompt while this profile is active (R6). */\n\tsoul?: string;\n\tresources: ResourceProfileSettings;\n\tsource: ProfileSource;\n\tsourcePath?: string;\n\tbaseDir?: string;\n}\n\nexport interface ProfileRegistryDiagnostic {\n\tsource: ProfileSource;\n\tpath?: string;\n\tmessage: string;\n}\n\nexport interface ProfileRegistryOptions {\n\tglobalSettings: Settings;\n\tprojectSettings: Settings;\n\tdirectoryProfileSettings: Settings;\n\tinlineResourceProfileDefinitions: Record<string, ProfileDefinitionInput>;\n\tdiscoveredResourceProfileDefinitions: Record<string, ResourceProfileSettings>;\n\tprofilesDir?: string;\n\texternalResourceRoots?: string[];\n}\n\nconst RESOURCE_PROFILE_KINDS: ResourceProfileKind[] = [\"extensions\", \"skills\", \"prompts\", \"themes\", \"agents\", \"tools\"];\n\n/** Name of the built-in, always-available profile that enables every discovered resource. */\nexport const ALL_ACTIVE_PROFILE_NAME = \"all-active\";\n\nfunction buildAllActiveResources(): ResourceProfileSettings {\n\tconst resources: ResourceProfileSettings = {};\n\tfor (const kind of RESOURCE_PROFILE_KINDS) {\n\t\tresources[kind] = { allow: [\"*\"] };\n\t}\n\treturn resources;\n}\n\n/**\n * The built-in \"all-active\" profile. Registered as the weakest candidate in\n * `collectCandidates()` so any user-defined profile of the same name overrides it.\n */\nexport const ALL_ACTIVE_BUILTIN_PROFILE: NormalizedProfile = {\n\tname: ALL_ACTIVE_PROFILE_NAME,\n\tdescription: \"Everything on: all discovered extensions, skills, prompts, themes, agents, and tools\",\n\tresources: buildAllActiveResources(),\n\tsource: \"embedded\",\n};\n\ninterface ProfileCandidate {\n\tprofile: NormalizedProfile;\n\tprecedence: number;\n\torder: number;\n}\n\nfunction asNonEmptyString(value: unknown): string | undefined {\n\treturn typeof value === \"string\" && value.trim().length > 0 ? value.trim() : undefined;\n}\n\nfunction asStringArray(value: unknown): string[] | undefined {\n\tif (!Array.isArray(value)) return undefined;\n\tconst strings = value.filter((item): item is string => typeof item === \"string\" && item.trim().length > 0);\n\treturn strings.length > 0 ? strings : undefined;\n}\n\nfunction shouldResolveAgainstBaseDir(pattern: string): boolean {\n\treturn pattern.startsWith(\"./\") || pattern.startsWith(\"../\");\n}\n\nfunction normalizePattern(pattern: string, baseDir: string | undefined): string {\n\tconst trimmed = pattern.trim();\n\tif (!baseDir || !shouldResolveAgainstBaseDir(trimmed)) return trimmed;\n\treturn resolvePath(trimmed, baseDir, { trim: true });\n}\n\nfunction normalizeStringArray(value: unknown, baseDir: string | undefined): string[] | undefined {\n\tconst strings = asStringArray(value);\n\tif (!strings) return undefined;\n\treturn strings.map((pattern) => normalizePattern(pattern, baseDir));\n}\n\nfunction normalizeResourceProfileSettings(value: unknown, baseDir: string | undefined): ResourceProfileSettings {\n\tif (!isRecordObject(value)) {\n\t\tthrow new Error(\"resources must be an object\");\n\t}\n\tconst result: ResourceProfileSettings = {};\n\tfor (const kind of RESOURCE_PROFILE_KINDS) {\n\t\tconst filterValue = value[kind];\n\t\tif (filterValue === undefined) continue;\n\t\tif (!isRecordObject(filterValue)) {\n\t\t\tthrow new Error(`${kind} filter must be an object`);\n\t\t}\n\t\tconst allow = normalizeStringArray(filterValue.allow, baseDir);\n\t\tconst block = normalizeStringArray(filterValue.block, baseDir);\n\t\tresult[kind] = { allow, block };\n\t}\n\treturn result;\n}\n\nfunction validateProfileName(name: string): string[] {\n\treturn validateSkillName(name);\n}\n\nfunction normalizeThinking(value: unknown): ThinkingLevel | undefined {\n\tconst thinking = asNonEmptyString(value);\n\tif (!thinking) return undefined;\n\tif (!isValidThinkingLevel(thinking)) {\n\t\tthrow new Error(`thinking must be one of off, minimal, low, medium, high, xhigh, max, ultra`);\n\t}\n\treturn thinking;\n}\n\nfunction normalizeModelRouterSettings(value: unknown): ModelRouterSettings | undefined {\n\tif (!isRecordObject(value)) return undefined;\n\tconst settings: ModelRouterSettings = {};\n\tfor (const key of [\"enabled\", \"judgeEnabled\", \"fitnessGate\"] as const) {\n\t\tconst candidate = value[key];\n\t\tif (typeof candidate === \"boolean\") settings[key] = candidate;\n\t}\n\tfor (const key of [\n\t\t\"cheapModel\",\n\t\t\"mediumModel\",\n\t\t\"expensiveModel\",\n\t\t\"learningModel\",\n\t\t\"judgeModel\",\n\t\t\"executorModel\",\n\t] as const) {\n\t\tconst candidate = asNonEmptyString(value[key]);\n\t\tif (candidate) settings[key] = candidate;\n\t}\n\tfor (const key of [\n\t\t\"cheapThinking\",\n\t\t\"mediumThinking\",\n\t\t\"expensiveThinking\",\n\t\t\"executorThinking\",\n\t\t\"judgeThinking\",\n\t] as const) {\n\t\tconst candidate = asNonEmptyString(value[key]);\n\t\tif (!candidate) continue;\n\t\tif (!isValidThinkingLevel(candidate)) {\n\t\t\tthrow new Error(`${key} must be one of off, minimal, low, medium, high, xhigh, max, ultra`);\n\t\t}\n\t\tsettings[key] = candidate;\n\t}\n\treturn Object.keys(settings).length > 0 ? settings : undefined;\n}\n\nfunction normalizeWrapperProfile(options: {\n\tvalue: unknown;\n\tsource: ProfileSource;\n\tsourcePath?: string;\n\tbaseDir?: string;\n\tfallbackName?: string;\n}): NormalizedProfile {\n\tif (!isRecordObject(options.value)) {\n\t\tthrow new Error(\"profile JSON must be an object\");\n\t}\n\tconst name = asNonEmptyString(options.value.name) ?? options.fallbackName;\n\tif (!name) {\n\t\tthrow new Error(\"profile name is required\");\n\t}\n\tconst nameErrors = validateProfileName(name);\n\tif (nameErrors.length > 0) {\n\t\tthrow new Error(`invalid profile name \"${name}\": ${nameErrors.join(\", \")}`);\n\t}\n\tconst resources = normalizeResourceProfileSettings(options.value.resources ?? {}, options.baseDir);\n\tconst description = asNonEmptyString(options.value.description);\n\tconst model = asNonEmptyString(options.value.model);\n\tconst thinking = normalizeThinking(options.value.thinking);\n\tconst modelRouter = normalizeModelRouterSettings(options.value.modelRouter);\n\tconst soul = asNonEmptyString(options.value.soul);\n\treturn {\n\t\tname,\n\t\tdescription,\n\t\tmodel,\n\t\tthinking,\n\t\tmodelRouter,\n\t\tsoul,\n\t\tresources,\n\t\tsource: options.source,\n\t\tsourcePath: options.sourcePath,\n\t\tbaseDir: options.baseDir,\n\t};\n}\n\nfunction normalizeSettingsProfiles(\n\tsettings: Settings,\n\tsource: ProfileSource,\n\tbaseDir?: string,\n\tsourcePath?: string,\n): Array<Omit<NormalizedProfile, \"source\"> & { source?: ProfileSource }> {\n\tconst profiles: Array<Omit<NormalizedProfile, \"source\"> & { source?: ProfileSource }> = [];\n\tfor (const [name, definition] of Object.entries(settings.resourceProfiles ?? {})) {\n\t\tconst nameErrors = validateProfileName(name);\n\t\tif (nameErrors.length > 0) continue;\n\t\tif (isRecordObject(definition) && Object.hasOwn(definition, \"resources\")) {\n\t\t\tprofiles.push(\n\t\t\t\tnormalizeWrapperProfile({\n\t\t\t\t\tvalue: { ...definition, name },\n\t\t\t\t\tsource,\n\t\t\t\t\tsourcePath,\n\t\t\t\t\tbaseDir,\n\t\t\t\t\tfallbackName: name,\n\t\t\t\t}),\n\t\t\t);\n\t\t\tcontinue;\n\t\t}\n\t\tprofiles.push({\n\t\t\tname,\n\t\t\tresources: mergeResourceProfileSettings(undefined, definition as ResourceProfileSettings),\n\t\t\tsourcePath,\n\t\t\tbaseDir,\n\t\t});\n\t}\n\treturn profiles.map((profile) => ({ ...profile, source }));\n}\n\nfunction normalizeInlineDefinitions(\n\tdefinitions: Record<string, ProfileDefinitionInput>,\n\tsource: ProfileSource,\n): NormalizedProfile[] {\n\tconst profiles: NormalizedProfile[] = [];\n\tfor (const [name, definition] of Object.entries(definitions)) {\n\t\ttry {\n\t\t\tprofiles.push(\n\t\t\t\tnormalizeWrapperProfile({\n\t\t\t\t\tvalue: { ...definition, name },\n\t\t\t\t\tsource,\n\t\t\t\t\tfallbackName: name,\n\t\t\t\t}),\n\t\t\t);\n\t\t} catch {\n\t\t\t// Inline names/definitions are validated at the SettingsManager API boundary.\n\t\t}\n\t}\n\treturn profiles;\n}\n\nfunction loadSettingsFileProfiles(sourcePath: string, source: ProfileSource): NormalizedProfile[] {\n\ttry {\n\t\tconst stats = statSync(sourcePath);\n\t\tif (!stats.isFile()) return [];\n\t\tconst parsed = JSON.parse(readFileSync(sourcePath, \"utf-8\")) as Settings;\n\t\treturn normalizeSettingsProfiles(parsed, source, dirname(resolve(sourcePath)), resolve(sourcePath)).map(\n\t\t\t(profile) => ({\n\t\t\t\t...profile,\n\t\t\t\tsource,\n\t\t\t}),\n\t\t);\n\t} catch {\n\t\treturn [];\n\t}\n}\n\nfunction normalizeDefinitions(\n\tdefinitions: Record<string, ResourceProfileSettings>,\n\tsource: ProfileSource,\n): NormalizedProfile[] {\n\tconst profiles: NormalizedProfile[] = [];\n\tfor (const [name, resources] of Object.entries(definitions)) {\n\t\tconst nameErrors = validateProfileName(name);\n\t\tif (nameErrors.length > 0) continue;\n\t\tprofiles.push({ name, resources: mergeResourceProfileSettings(undefined, resources), source });\n\t}\n\treturn profiles;\n}\n\nexport class ProfileRegistry {\n\tprivate options: ProfileRegistryOptions;\n\tprivate diagnostics: ProfileRegistryDiagnostic[] = [];\n\n\tconstructor(options: ProfileRegistryOptions) {\n\t\tthis.options = options;\n\t}\n\n\tlistDiagnostics(): ProfileRegistryDiagnostic[] {\n\t\tthis.collectCandidates();\n\t\treturn [...this.diagnostics];\n\t}\n\n\tlistProfiles(): NormalizedProfile[] {\n\t\tconst candidates = this.collectCandidates();\n\t\tconst winners = new Map<string, ProfileCandidate>();\n\t\tfor (const candidate of candidates) {\n\t\t\tconst existing = winners.get(candidate.profile.name);\n\t\t\tif (\n\t\t\t\t!existing ||\n\t\t\t\tcandidate.precedence < existing.precedence ||\n\t\t\t\t(candidate.precedence === existing.precedence && candidate.order < existing.order)\n\t\t\t) {\n\t\t\t\twinners.set(candidate.profile.name, candidate);\n\t\t\t}\n\t\t}\n\t\treturn Array.from(winners.values())\n\t\t\t.sort((a, b) => a.profile.name.localeCompare(b.profile.name))\n\t\t\t.map((candidate) => candidate.profile);\n\t}\n\n\tgetProfile(name: string): NormalizedProfile | undefined {\n\t\tconst trimmed = name.trim();\n\t\tif (!trimmed) return undefined;\n\t\treturn this.listProfiles().find((profile) => profile.name === trimmed);\n\t}\n\n\tresolveProfileRef(ref: string, fromDir: string): NormalizedProfile | undefined {\n\t\tconst trimmed = ref.trim();\n\t\tif (!trimmed) return undefined;\n\t\tif (trimmed.startsWith(\"./\") || trimmed.startsWith(\"../\")) {\n\t\t\tconst sourcePath = resolvePath(trimmed, fromDir, { trim: true });\n\t\t\treturn this.loadProfileFile(sourcePath, \"profile-file\", 0)?.profile;\n\t\t}\n\t\treturn this.getProfile(trimmed);\n\t}\n\n\tprivate collectCandidates(): ProfileCandidate[] {\n\t\tthis.diagnostics = [];\n\t\tconst candidates: ProfileCandidate[] = [];\n\t\tlet order = 0;\n\t\tconst add = (profile: NormalizedProfile, precedence: number): void => {\n\t\t\tcandidates.push({ profile, precedence, order: order++ });\n\t\t};\n\n\t\tfor (const profile of normalizeInlineDefinitions(this.options.inlineResourceProfileDefinitions, \"inline\")) {\n\t\t\tadd(profile, 1);\n\t\t}\n\t\tfor (const profile of normalizeSettingsProfiles(this.options.directoryProfileSettings, \"directory-overlay\")) {\n\t\t\tadd({ ...profile, source: \"directory-overlay\" }, 2);\n\t\t}\n\t\tfor (const profile of normalizeSettingsProfiles(this.options.projectSettings, \"project-settings\")) {\n\t\t\tadd({ ...profile, source: \"project-settings\" }, 3);\n\t\t}\n\t\tfor (const profile of this.loadProfileFiles()) {\n\t\t\tadd(profile.profile, profile.precedence);\n\t\t}\n\t\tfor (const profile of this.loadExternalSettingsProfiles()) {\n\t\t\tadd(profile, 4.2);\n\t\t}\n\t\tfor (const profile of normalizeSettingsProfiles(this.options.globalSettings, \"global-settings\")) {\n\t\t\tadd({ ...profile, source: \"global-settings\" }, 5);\n\t\t}\n\t\tfor (const profile of normalizeDefinitions(this.options.discoveredResourceProfileDefinitions, \"embedded\")) {\n\t\t\tadd(profile, 6);\n\t\t}\n\t\tadd(ALL_ACTIVE_BUILTIN_PROFILE, 7);\n\n\t\treturn candidates;\n\t}\n\n\tprivate loadProfileFiles(): ProfileCandidate[] {\n\t\tconst candidates: ProfileCandidate[] = [];\n\t\tlet order = 0;\n\n\t\tconst profilesDir = this.options.profilesDir;\n\t\tif (profilesDir && existsSync(profilesDir)) {\n\t\t\ttry {\n\t\t\t\tconst entries = readdirSync(profilesDir)\n\t\t\t\t\t.filter((entry) => entry.endsWith(\".json\"))\n\t\t\t\t\t.sort();\n\t\t\t\tfor (const entry of entries) {\n\t\t\t\t\tconst sourcePath = join(profilesDir, entry);\n\t\t\t\t\tconst loaded = this.loadProfileFile(sourcePath, \"profile-file\", order++);\n\t\t\t\t\tif (loaded) {\n\t\t\t\t\t\tcandidates.push({ ...loaded, precedence: 4 });\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tthis.diagnostics.push({ source: \"profile-file\", path: profilesDir, message: String(error) });\n\t\t\t}\n\t\t}\n\n\t\tconst externalRoots = this.options.externalResourceRoots ?? [];\n\t\tfor (const root of externalRoots) {\n\t\t\tconst extProfilesDir = join(root, \"profiles\");\n\t\t\tif (existsSync(extProfilesDir)) {\n\t\t\t\ttry {\n\t\t\t\t\tconst entries = readdirSync(extProfilesDir)\n\t\t\t\t\t\t.filter((entry) => entry.endsWith(\".json\"))\n\t\t\t\t\t\t.sort();\n\t\t\t\t\tfor (const entry of entries) {\n\t\t\t\t\t\tconst sourcePath = join(extProfilesDir, entry);\n\t\t\t\t\t\tconst loaded = this.loadProfileFile(sourcePath, \"profile-file\", order++);\n\t\t\t\t\t\tif (loaded) {\n\t\t\t\t\t\t\tcandidates.push({ ...loaded, precedence: 4.1 });\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} catch (error) {\n\t\t\t\t\tthis.diagnostics.push({ source: \"profile-file\", path: extProfilesDir, message: String(error) });\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn candidates;\n\t}\n\n\tprivate loadExternalSettingsProfiles(): NormalizedProfile[] {\n\t\tconst profiles: NormalizedProfile[] = [];\n\t\tfor (const root of this.options.externalResourceRoots ?? []) {\n\t\t\tprofiles.push(...loadSettingsFileProfiles(join(root, \"settings.json\"), \"external-settings\"));\n\t\t}\n\t\treturn profiles;\n\t}\n\n\tprivate loadProfileFile(sourcePath: string, source: ProfileSource, order: number): ProfileCandidate | undefined {\n\t\ttry {\n\t\t\tconst stats = statSync(sourcePath);\n\t\t\tif (!stats.isFile()) return undefined;\n\t\t\tconst parsed = JSON.parse(readFileSync(sourcePath, \"utf-8\"));\n\t\t\tconst fallbackName = basename(sourcePath, \".json\");\n\t\t\treturn {\n\t\t\t\tprofile: normalizeWrapperProfile({\n\t\t\t\t\tvalue: parsed,\n\t\t\t\t\tsource,\n\t\t\t\t\tsourcePath: resolve(sourcePath),\n\t\t\t\t\tbaseDir: dirname(resolve(sourcePath)),\n\t\t\t\t\tfallbackName,\n\t\t\t\t}),\n\t\t\t\tprecedence: 0,\n\t\t\t\torder,\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tthis.diagnostics.push({ source, path: sourcePath, message });\n\t\t\treturn undefined;\n\t\t}\n\t}\n}\n"]}
@@ -4,6 +4,7 @@ import { isValidThinkingLevel } from "../cli/args.js";
4
4
  import { resolvePath } from "../utils/paths.js";
5
5
  import { mergeResourceProfileSettings } from "./resource-profile-blocks.js";
6
6
  import { validateSkillName } from "./skills.js";
7
+ import { isRecordObject } from "./util/value-guards.js";
7
8
  const RESOURCE_PROFILE_KINDS = ["extensions", "skills", "prompts", "themes", "agents", "tools"];
8
9
  /** Name of the built-in, always-available profile that enables every discovered resource. */
9
10
  export const ALL_ACTIVE_PROFILE_NAME = "all-active";
@@ -24,9 +25,6 @@ export const ALL_ACTIVE_BUILTIN_PROFILE = {
24
25
  resources: buildAllActiveResources(),
25
26
  source: "embedded",
26
27
  };
27
- function isRecord(value) {
28
- return Boolean(value) && typeof value === "object" && !Array.isArray(value);
29
- }
30
28
  function asNonEmptyString(value) {
31
29
  return typeof value === "string" && value.trim().length > 0 ? value.trim() : undefined;
32
30
  }
@@ -52,7 +50,7 @@ function normalizeStringArray(value, baseDir) {
52
50
  return strings.map((pattern) => normalizePattern(pattern, baseDir));
53
51
  }
54
52
  function normalizeResourceProfileSettings(value, baseDir) {
55
- if (!isRecord(value)) {
53
+ if (!isRecordObject(value)) {
56
54
  throw new Error("resources must be an object");
57
55
  }
58
56
  const result = {};
@@ -60,7 +58,7 @@ function normalizeResourceProfileSettings(value, baseDir) {
60
58
  const filterValue = value[kind];
61
59
  if (filterValue === undefined)
62
60
  continue;
63
- if (!isRecord(filterValue)) {
61
+ if (!isRecordObject(filterValue)) {
64
62
  throw new Error(`${kind} filter must be an object`);
65
63
  }
66
64
  const allow = normalizeStringArray(filterValue.allow, baseDir);
@@ -82,7 +80,7 @@ function normalizeThinking(value) {
82
80
  return thinking;
83
81
  }
84
82
  function normalizeModelRouterSettings(value) {
85
- if (!isRecord(value))
83
+ if (!isRecordObject(value))
86
84
  return undefined;
87
85
  const settings = {};
88
86
  for (const key of ["enabled", "judgeEnabled", "fitnessGate"]) {
@@ -120,7 +118,7 @@ function normalizeModelRouterSettings(value) {
120
118
  return Object.keys(settings).length > 0 ? settings : undefined;
121
119
  }
122
120
  function normalizeWrapperProfile(options) {
123
- if (!isRecord(options.value)) {
121
+ if (!isRecordObject(options.value)) {
124
122
  throw new Error("profile JSON must be an object");
125
123
  }
126
124
  const name = asNonEmptyString(options.value.name) ?? options.fallbackName;
@@ -156,7 +154,7 @@ function normalizeSettingsProfiles(settings, source, baseDir, sourcePath) {
156
154
  const nameErrors = validateProfileName(name);
157
155
  if (nameErrors.length > 0)
158
156
  continue;
159
- if (isRecord(definition) && Object.hasOwn(definition, "resources")) {
157
+ if (isRecordObject(definition) && Object.hasOwn(definition, "resources")) {
160
158
  profiles.push(normalizeWrapperProfile({
161
159
  value: { ...definition, name },
162
160
  source,