@hassangameryt/freeflow 0.7.3 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (426) hide show
  1. package/.agents/plugins/marketplace.json +2 -2
  2. package/.claude-plugin/marketplace.json +1 -1
  3. package/.claude-plugin/plugin.json +2 -2
  4. package/.codex-plugin/plugin.json +3 -3
  5. package/.cursor-plugin/plugin.json +1 -1
  6. package/NOTICE +14 -0
  7. package/README.md +101 -159
  8. package/capabilities/cognitive-routing/SKILL.md +47 -210
  9. package/capabilities/cognitive-routing/references/coordinator.md +163 -0
  10. package/capabilities/cognitive-routing/references/worker.md +38 -0
  11. package/capabilities/compaction/SKILL.md +49 -0
  12. package/capabilities/compaction/references/summary-format.md +250 -0
  13. package/capabilities/messaging/SKILL.md +49 -0
  14. package/capabilities/task-memory/SKILL.md +87 -0
  15. package/command-surface.json +8 -52
  16. package/gemini-extension.json +1 -1
  17. package/hooks/claude/hooks.json +13 -3
  18. package/hooks/codex/hooks.json +2 -1
  19. package/hooks/shared/runtime-context.mjs +73 -83
  20. package/licenses/Apache-2.0.txt +55 -0
  21. package/package.json +42 -12
  22. package/pi-extension/README.md +41 -0
  23. package/pi-extension/dist/ask-user/ask.js +108 -0
  24. package/pi-extension/dist/ask-user/form.js +250 -0
  25. package/pi-extension/dist/ask-user/questions.js +66 -0
  26. package/pi-extension/dist/ask-user/tool.js +124 -0
  27. package/pi-extension/dist/cognitive-routing/assembler.js +417 -0
  28. package/pi-extension/dist/cognitive-routing/bootstrap.js +90 -0
  29. package/pi-extension/dist/{cognitive-routing-v2 → cognitive-routing}/config.js +8 -6
  30. package/pi-extension/dist/cognitive-routing/economics.js +45 -0
  31. package/pi-extension/dist/cognitive-routing/event-schema.js +388 -0
  32. package/pi-extension/dist/{session-sources/events.js → cognitive-routing/event-store.js} +107 -41
  33. package/pi-extension/dist/cognitive-routing/gate.js +256 -0
  34. package/pi-extension/dist/cognitive-routing/handlers.js +901 -0
  35. package/pi-extension/dist/cognitive-routing/handoffs.js +350 -0
  36. package/pi-extension/dist/cognitive-routing/model-control.js +476 -0
  37. package/pi-extension/dist/cognitive-routing/projection.js +520 -0
  38. package/pi-extension/dist/cognitive-routing/provenance.js +83 -0
  39. package/pi-extension/dist/{cognitive-routing-v2 → cognitive-routing}/render.js +15 -15
  40. package/pi-extension/dist/cognitive-routing/runtime.js +398 -0
  41. package/pi-extension/dist/{cognitive-routing-v2 → cognitive-routing}/schemas.js +47 -11
  42. package/pi-extension/dist/cognitive-routing/session.js +223 -0
  43. package/pi-extension/dist/{session-sources → cognitive-routing}/sources.js +126 -87
  44. package/pi-extension/dist/{cognitive-routing-v2 → cognitive-routing}/state.js +55 -386
  45. package/pi-extension/dist/cognitive-routing/status.js +81 -0
  46. package/pi-extension/dist/cognitive-routing/tools.js +74 -0
  47. package/pi-extension/dist/{cognitive-routing-v2 → cognitive-routing}/types.js +14 -11
  48. package/pi-extension/dist/compaction/carry.js +205 -0
  49. package/pi-extension/dist/compaction/config.js +24 -0
  50. package/pi-extension/dist/compaction/controller.js +494 -0
  51. package/pi-extension/dist/compaction/harness.js +93 -0
  52. package/pi-extension/dist/compaction/results.js +159 -0
  53. package/pi-extension/dist/compaction/thresholds.js +35 -0
  54. package/pi-extension/dist/compaction/tool.js +57 -0
  55. package/pi-extension/dist/host/branch.js +13 -0
  56. package/pi-extension/dist/host/canonical.js +12 -0
  57. package/pi-extension/dist/host/catalog.js +62 -0
  58. package/pi-extension/dist/host/config-validation.js +233 -0
  59. package/pi-extension/dist/host/config.js +361 -0
  60. package/pi-extension/dist/host/inbound.js +142 -0
  61. package/pi-extension/dist/host/projection-tags.js +60 -0
  62. package/pi-extension/dist/host/prompts.js +93 -0
  63. package/pi-extension/dist/{session-sources → host}/read-only-session.js +117 -1
  64. package/pi-extension/dist/{runtime → host}/request-history.js +125 -39
  65. package/pi-extension/dist/host/rows.js +25 -0
  66. package/pi-extension/dist/host/runtime-state.js +204 -0
  67. package/pi-extension/dist/host/section-keeper.js +85 -0
  68. package/pi-extension/dist/host/settings/freeflow-command.js +2323 -0
  69. package/pi-extension/dist/{settings/settings-tui.js → host/settings/settings-view.js} +205 -73
  70. package/pi-extension/dist/host/staging.js +28 -0
  71. package/pi-extension/dist/host/status.js +115 -0
  72. package/pi-extension/dist/index.js +1004 -188
  73. package/pi-extension/dist/messaging/config.js +27 -0
  74. package/pi-extension/dist/messaging/messaging.js +398 -0
  75. package/pi-extension/dist/messaging/registry.js +57 -0
  76. package/pi-extension/dist/messaging/render.js +90 -0
  77. package/pi-extension/dist/messaging/tools.js +109 -0
  78. package/pi-extension/dist/messaging/transport.js +101 -0
  79. package/pi-extension/dist/provider-support/cache/anchor.js +21 -0
  80. package/pi-extension/dist/provider-support/cache/anthropic.js +102 -0
  81. package/pi-extension/dist/provider-support/cache/health.js +73 -0
  82. package/pi-extension/dist/provider-support/cache/index.js +58 -0
  83. package/pi-extension/dist/provider-support/cache/keepalive.js +222 -0
  84. package/pi-extension/dist/provider-support/cache/monitor.js +17 -0
  85. package/pi-extension/dist/provider-support/cache/openai-responses.js +48 -0
  86. package/pi-extension/dist/provider-support/effort.js +13 -0
  87. package/pi-extension/dist/provider-support/index.js +44 -3
  88. package/pi-extension/dist/provider-support/{astra → openai}/adapter.js +46 -29
  89. package/pi-extension/dist/provider-support/{astra → openai}/history.js +10 -8
  90. package/pi-extension/dist/provider-support/{astra → openai}/index.js +8 -4
  91. package/pi-extension/dist/provider-support/{astra → openai}/session-state.js +29 -38
  92. package/pi-extension/dist/provider-support/routes.js +17 -0
  93. package/pi-extension/dist/task-memory/config.js +49 -0
  94. package/pi-extension/dist/task-memory/registry.js +119 -0
  95. package/pi-extension/dist/task-memory/render.js +107 -0
  96. package/pi-extension/dist/task-memory/runtime.js +994 -0
  97. package/pi-extension/dist/task-memory/tool.js +233 -0
  98. package/pi-extension/dist/tool-execution/apply-patch/grammar.js +23 -0
  99. package/pi-extension/dist/tool-execution/apply-patch/match.js +38 -0
  100. package/pi-extension/dist/tool-execution/apply-patch/parser.js +177 -0
  101. package/pi-extension/dist/tool-execution/apply-patch/plan.js +201 -0
  102. package/pi-extension/dist/tool-execution/apply-patch/tool.js +84 -0
  103. package/pi-extension/dist/tool-execution/background.js +430 -0
  104. package/pi-extension/dist/tool-execution/bash-guard.js +23 -0
  105. package/pi-extension/dist/tool-execution/config.js +33 -0
  106. package/pi-extension/dist/tool-execution/edit-messages.js +120 -0
  107. package/pi-extension/dist/tool-execution/file-state.js +138 -0
  108. package/pi-extension/dist/tool-execution/file-tracking.js +163 -0
  109. package/pi-extension/dist/tool-execution/guidance-notices.js +124 -0
  110. package/pi-extension/dist/tool-execution/prompt.js +54 -0
  111. package/pi-extension/dist/tool-execution/skill-reads.js +143 -0
  112. package/pi-extension/dist/tool-execution/tools.js +16 -0
  113. package/pi-extension/freeflow/README.md +9 -0
  114. package/runtime/prompts/cognitive-routing.md +4 -4
  115. package/runtime/prompts/core.md +29 -72
  116. package/runtime/prompts/interaction-contract.md +18 -8
  117. package/runtime/prompts/tool-execution.md +25 -0
  118. package/runtime/prompts/working-method.md +25 -0
  119. package/skills/deliver-work/SKILL.md +76 -0
  120. package/skills/deliver-work/references/branch-closeout.md +134 -0
  121. package/skills/deliver-work/references/commit.md +83 -0
  122. package/skills/deliver-work/references/launch.md +94 -0
  123. package/skills/deliver-work/references/release.md +85 -0
  124. package/skills/deliver-work/scripts/commit-state.mjs +139 -0
  125. package/skills/deliver-work/scripts/delivery-state.mjs +107 -0
  126. package/skills/deliver-work/scripts/lib/git-state.mjs +178 -0
  127. package/skills/deliver-work/scripts/push-route.mjs +122 -0
  128. package/skills/deliver-work/scripts/release-preflight.mjs +177 -0
  129. package/skills/discuss-work/SKILL.md +148 -0
  130. package/skills/{discuss → discuss-work}/references/discussion-continuity.md +13 -50
  131. package/skills/discuss-work/references/learning-action.md +36 -0
  132. package/skills/discuss-work/scripts/choices.mjs +101 -0
  133. package/skills/discuss-work/scripts/lib/choices.mjs +159 -0
  134. package/skills/evaluate-behavior/SKILL.md +107 -0
  135. package/skills/evaluate-behavior/references/authoring.md +381 -0
  136. package/skills/evaluate-behavior/references/coding-tasks.md +145 -0
  137. package/skills/evaluate-behavior/references/conversations-pipelines-judges.md +177 -0
  138. package/skills/evaluate-behavior/references/design-and-measurement.md +273 -0
  139. package/skills/evaluate-behavior/references/running-and-evidence.md +245 -0
  140. package/skills/evaluate-behavior/scripts/claude-guard.mjs +76 -0
  141. package/skills/evaluate-behavior/scripts/guard-rules.mjs +309 -0
  142. package/skills/evaluate-behavior/scripts/lib/agreement.mjs +90 -0
  143. package/skills/evaluate-behavior/scripts/lib/arms.mjs +55 -0
  144. package/skills/evaluate-behavior/scripts/lib/budget.mjs +87 -0
  145. package/skills/evaluate-behavior/scripts/lib/build-source.mjs +287 -0
  146. package/skills/evaluate-behavior/scripts/lib/clear.mjs +74 -0
  147. package/skills/evaluate-behavior/scripts/lib/container.mjs +395 -0
  148. package/skills/evaluate-behavior/scripts/lib/decision.mjs +418 -0
  149. package/skills/evaluate-behavior/scripts/lib/definitions.mjs +1072 -0
  150. package/skills/evaluate-behavior/scripts/lib/freeflow.mjs +103 -0
  151. package/skills/evaluate-behavior/scripts/lib/grade-command.mjs +591 -0
  152. package/skills/evaluate-behavior/scripts/lib/grade-comparison.mjs +90 -0
  153. package/skills/{evaluate-skill → evaluate-behavior}/scripts/lib/grade-interaction.mjs +19 -18
  154. package/skills/{evaluate-skill → evaluate-behavior}/scripts/lib/grade-support.mjs +32 -5
  155. package/skills/{evaluate-skill → evaluate-behavior}/scripts/lib/grade-workspace.mjs +28 -12
  156. package/skills/evaluate-behavior/scripts/lib/grade.mjs +101 -0
  157. package/skills/evaluate-behavior/scripts/lib/hooks.mjs +98 -0
  158. package/skills/evaluate-behavior/scripts/lib/hosts/claude-code/confinement.mjs +196 -0
  159. package/skills/evaluate-behavior/scripts/lib/hosts/claude-code/constraints.mjs +111 -0
  160. package/skills/evaluate-behavior/scripts/lib/hosts/claude-code/index.mjs +48 -0
  161. package/skills/evaluate-behavior/scripts/lib/hosts/claude-code/isolation.mjs +74 -0
  162. package/skills/evaluate-behavior/scripts/lib/hosts/claude-code/launch.mjs +123 -0
  163. package/skills/evaluate-behavior/scripts/lib/hosts/claude-code/model-call.mjs +73 -0
  164. package/skills/evaluate-behavior/scripts/lib/hosts/claude-code/recorder.mjs +178 -0
  165. package/skills/evaluate-behavior/scripts/lib/hosts/claude-code/session.mjs +494 -0
  166. package/skills/evaluate-behavior/scripts/lib/hosts/claude-code/skills.mjs +81 -0
  167. package/skills/evaluate-behavior/scripts/lib/hosts/index.mjs +31 -0
  168. package/skills/evaluate-behavior/scripts/lib/hosts/names.mjs +3 -0
  169. package/skills/evaluate-behavior/scripts/lib/hosts/pi/confinement.mjs +173 -0
  170. package/skills/evaluate-behavior/scripts/lib/hosts/pi/host.mjs +148 -0
  171. package/skills/evaluate-behavior/scripts/lib/hosts/pi/index.mjs +70 -0
  172. package/skills/evaluate-behavior/scripts/lib/hosts/pi/isolation.mjs +81 -0
  173. package/skills/evaluate-behavior/scripts/lib/hosts/pi/model-call.mjs +79 -0
  174. package/skills/evaluate-behavior/scripts/lib/hosts/pi/process.mjs +241 -0
  175. package/skills/{evaluate-skill/scripts/lib → evaluate-behavior/scripts/lib/hosts/pi}/rpc.mjs +144 -26
  176. package/skills/evaluate-behavior/scripts/lib/identity.mjs +82 -0
  177. package/skills/evaluate-behavior/scripts/lib/judge.mjs +688 -0
  178. package/skills/evaluate-behavior/scripts/lib/metrics.mjs +332 -0
  179. package/skills/evaluate-behavior/scripts/lib/model-call.mjs +17 -0
  180. package/skills/evaluate-behavior/scripts/lib/participants.mjs +616 -0
  181. package/skills/{evaluate-skill → evaluate-behavior}/scripts/lib/process.mjs +22 -0
  182. package/skills/evaluate-behavior/scripts/lib/queue.mjs +54 -0
  183. package/skills/evaluate-behavior/scripts/lib/reference.mjs +343 -0
  184. package/skills/evaluate-behavior/scripts/lib/reuse.mjs +277 -0
  185. package/skills/evaluate-behavior/scripts/lib/review.mjs +933 -0
  186. package/skills/evaluate-behavior/scripts/lib/runner.mjs +732 -0
  187. package/skills/{evaluate-skill → evaluate-behavior}/scripts/lib/sandbox.mjs +121 -14
  188. package/skills/evaluate-behavior/scripts/lib/scan-shell.mjs +457 -0
  189. package/skills/evaluate-behavior/scripts/lib/scan.mjs +479 -0
  190. package/skills/evaluate-behavior/scripts/lib/seal.mjs +91 -0
  191. package/skills/evaluate-behavior/scripts/lib/shell.mjs +560 -0
  192. package/skills/evaluate-behavior/scripts/lib/source-override.mjs +64 -0
  193. package/skills/evaluate-behavior/scripts/lib/subject-file.mjs +88 -0
  194. package/skills/{evaluate-skill/scripts/lib/pi.mjs → evaluate-behavior/scripts/lib/subject.mjs} +239 -262
  195. package/skills/evaluate-behavior/scripts/lib/task-copy.mjs +124 -0
  196. package/skills/evaluate-behavior/scripts/lib/trials.mjs +524 -0
  197. package/skills/evaluate-behavior/scripts/lib/validity.mjs +68 -0
  198. package/skills/evaluate-behavior/scripts/lib/view-html.mjs +454 -0
  199. package/skills/{evaluate-skill → evaluate-behavior}/scripts/lib/view.mjs +218 -11
  200. package/skills/evaluate-behavior/scripts/pi-command-tool.mjs +159 -0
  201. package/skills/evaluate-behavior/scripts/pi-container-route.mjs +23 -0
  202. package/skills/evaluate-behavior/scripts/pi-guard.mjs +77 -0
  203. package/skills/evaluate-behavior/scripts/pi-login-refresh.mjs +31 -0
  204. package/skills/evaluate-behavior/scripts/skill-eval.mjs +586 -0
  205. package/skills/execute-work/SKILL.md +96 -72
  206. package/skills/execute-work/references/code-practices.md +27 -49
  207. package/skills/execute-work/references/design.md +271 -0
  208. package/skills/execute-work/references/diagnose.md +117 -0
  209. package/skills/execute-work/references/migration.md +108 -0
  210. package/skills/execute-work/references/simplify.md +65 -0
  211. package/skills/execute-work/scripts/self-review.mjs +422 -0
  212. package/skills/execute-work/scripts/touch-map.mjs +290 -0
  213. package/skills/review-work/SKILL.md +94 -64
  214. package/skills/review-work/references/adjudication.md +94 -0
  215. package/skills/review-work/references/artifact.md +198 -0
  216. package/skills/review-work/references/evals-and-judges.md +66 -0
  217. package/skills/review-work/references/work.md +177 -0
  218. package/skills/review-work/scripts/check-brief.mjs +128 -0
  219. package/skills/review-work/scripts/review-packet.mjs +233 -0
  220. package/skills/setup-freeflow/SKILL.md +69 -16
  221. package/skills/track-work/SKILL.md +135 -151
  222. package/skills/track-work/references/handoff.md +190 -0
  223. package/skills/track-work/references/projects.md +51 -0
  224. package/skills/track-work/references/working-record-format.md +201 -344
  225. package/skills/track-work/scripts/lib/document.mjs +79 -19
  226. package/skills/track-work/scripts/lib/format.mjs +18 -1
  227. package/skills/track-work/scripts/lib/recover.mjs +254 -0
  228. package/skills/track-work/scripts/lib/registry.mjs +656 -0
  229. package/skills/track-work/scripts/lib/search.mjs +40 -0
  230. package/skills/track-work/scripts/lib/store.mjs +53 -21
  231. package/skills/track-work/scripts/lib/transitions.mjs +79 -4
  232. package/skills/track-work/scripts/lib/views.mjs +50 -1
  233. package/skills/track-work/scripts/working-record.mjs +263 -22
  234. package/skills/verify-work/SKILL.md +64 -47
  235. package/skills/verify-work/references/feature-map.md +120 -0
  236. package/skills/verify-work/references/runtime-evidence.md +203 -0
  237. package/skills/verify-work/references/test-design.md +27 -6
  238. package/skills/verify-work/scripts/test-changes.mjs +246 -0
  239. package/skills/write-docs/SKILL.md +171 -0
  240. package/skills/write-docs/references/documentation-shapes.md +184 -0
  241. package/skills/write-docs/references/spec-and-plan-shapes.md +308 -0
  242. package/skills/write-docs/scripts/artifact-check.mjs +148 -0
  243. package/skills/write-docs/scripts/docs-check.mjs +229 -0
  244. package/skills/write-docs/scripts/plan-lint.mjs +123 -0
  245. package/skills/write-skill/SKILL.md +165 -165
  246. package/skills/write-skill/references/activation-and-wording.md +143 -0
  247. package/skills/write-skill/references/placement-and-dependencies.md +154 -0
  248. package/skills/write-skill/scripts/lib/compare.mjs +701 -0
  249. package/skills/write-skill/scripts/lib/similarity.mjs +56 -0
  250. package/skills/write-skill/scripts/lib/skill-author.mjs +197 -3
  251. package/skills/write-skill/scripts/skill-author.mjs +67 -8
  252. package/capabilities/context-virtualization/SKILL.md +0 -103
  253. package/capabilities/conversation-history/SKILL.md +0 -53
  254. package/hooks/tests/check-host-adapters.test.mjs +0 -82
  255. package/hooks/tests/check-runtime-context-hook.sh +0 -212
  256. package/pi-extension/dist/cognitive-routing-v2/projection.js +0 -330
  257. package/pi-extension/dist/cognitive-routing-v2/runtime.js +0 -2181
  258. package/pi-extension/dist/cognitive-routing-v2/tools.js +0 -60
  259. package/pi-extension/dist/context-virtualization/commands.js +0 -89
  260. package/pi-extension/dist/context-virtualization/projector.js +0 -42
  261. package/pi-extension/dist/context-virtualization/runtime.js +0 -378
  262. package/pi-extension/dist/context-virtualization/state.js +0 -57
  263. package/pi-extension/dist/context-virtualization/types.js +0 -10
  264. package/pi-extension/dist/conversation-history/passages.js +0 -66
  265. package/pi-extension/dist/conversation-history/ranking.js +0 -105
  266. package/pi-extension/dist/conversation-history/runtime.js +0 -226
  267. package/pi-extension/dist/conversation-history/search.js +0 -56
  268. package/pi-extension/dist/conversation-history/types.js +0 -1
  269. package/pi-extension/dist/freeflow-context/resolver.js +0 -120
  270. package/pi-extension/dist/freeflow-context/runtime.js +0 -80
  271. package/pi-extension/dist/freeflow-context/source-projector.js +0 -95
  272. package/pi-extension/dist/freeflow-context/tool.js +0 -314
  273. package/pi-extension/dist/freeflow-context/types.js +0 -12
  274. package/pi-extension/dist/freeflow-context/visibility.js +0 -28
  275. package/pi-extension/dist/integrations/mcp-config.js +0 -29
  276. package/pi-extension/dist/runtime/runtime-context.js +0 -754
  277. package/pi-extension/dist/runtime/runtime-identity.js +0 -5
  278. package/pi-extension/dist/session-sources/provenance.js +0 -32
  279. package/pi-extension/dist/settings/settings-ui.js +0 -1360
  280. package/pi-extension/dist/ui/text-component.js +0 -57
  281. package/pi-extension/src/cognitive-routing-v2/budget.ts +0 -42
  282. package/pi-extension/src/cognitive-routing-v2/config.ts +0 -173
  283. package/pi-extension/src/cognitive-routing-v2/projection.ts +0 -375
  284. package/pi-extension/src/cognitive-routing-v2/render.ts +0 -277
  285. package/pi-extension/src/cognitive-routing-v2/runtime.ts +0 -2241
  286. package/pi-extension/src/cognitive-routing-v2/schemas.ts +0 -180
  287. package/pi-extension/src/cognitive-routing-v2/state.ts +0 -839
  288. package/pi-extension/src/cognitive-routing-v2/tools.ts +0 -62
  289. package/pi-extension/src/cognitive-routing-v2/types.ts +0 -254
  290. package/pi-extension/src/context-virtualization/commands.ts +0 -111
  291. package/pi-extension/src/context-virtualization/projector.ts +0 -62
  292. package/pi-extension/src/context-virtualization/runtime.ts +0 -428
  293. package/pi-extension/src/context-virtualization/state.ts +0 -79
  294. package/pi-extension/src/context-virtualization/types.ts +0 -92
  295. package/pi-extension/src/conversation-history/passages.ts +0 -81
  296. package/pi-extension/src/conversation-history/ranking.ts +0 -155
  297. package/pi-extension/src/conversation-history/runtime.ts +0 -250
  298. package/pi-extension/src/conversation-history/search.ts +0 -79
  299. package/pi-extension/src/conversation-history/types.ts +0 -31
  300. package/pi-extension/src/freeflow-context/resolver.ts +0 -139
  301. package/pi-extension/src/freeflow-context/runtime.ts +0 -100
  302. package/pi-extension/src/freeflow-context/source-projector.ts +0 -106
  303. package/pi-extension/src/freeflow-context/tool.ts +0 -366
  304. package/pi-extension/src/freeflow-context/types.ts +0 -70
  305. package/pi-extension/src/freeflow-context/visibility.ts +0 -53
  306. package/pi-extension/src/index.ts +0 -390
  307. package/pi-extension/src/integrations/mcp-config.ts +0 -32
  308. package/pi-extension/src/provider-support/astra/adapter.ts +0 -108
  309. package/pi-extension/src/provider-support/astra/history.ts +0 -145
  310. package/pi-extension/src/provider-support/astra/index.ts +0 -12
  311. package/pi-extension/src/provider-support/astra/session-state.ts +0 -113
  312. package/pi-extension/src/provider-support/index.ts +0 -5
  313. package/pi-extension/src/runtime/request-history.ts +0 -243
  314. package/pi-extension/src/runtime/runtime-context.ts +0 -860
  315. package/pi-extension/src/runtime/runtime-identity.ts +0 -8
  316. package/pi-extension/src/session-sources/events.ts +0 -230
  317. package/pi-extension/src/session-sources/provenance.ts +0 -39
  318. package/pi-extension/src/session-sources/read-only-session.ts +0 -170
  319. package/pi-extension/src/session-sources/sources.ts +0 -334
  320. package/pi-extension/src/settings/settings-tui.ts +0 -501
  321. package/pi-extension/src/settings/settings-ui.ts +0 -1652
  322. package/pi-extension/src/ui/text-component.ts +0 -66
  323. package/pi-extension/tests/cache-reuse/history.test.js +0 -117
  324. package/pi-extension/tests/cache-reuse/native.test.js +0 -91
  325. package/pi-extension/tests/cache-reuse/settings.test.js +0 -211
  326. package/pi-extension/tests/cognitive-routing-v2/communication.test.js +0 -577
  327. package/pi-extension/tests/cognitive-routing-v2/compaction-input.test.js +0 -183
  328. package/pi-extension/tests/cognitive-routing-v2/delegation.test.js +0 -557
  329. package/pi-extension/tests/cognitive-routing-v2/native.test.js +0 -474
  330. package/pi-extension/tests/cognitive-routing-v2/performance.test.js +0 -87
  331. package/pi-extension/tests/cognitive-routing-v2/persistence.test.js +0 -300
  332. package/pi-extension/tests/cognitive-routing-v2/projection.test.js +0 -241
  333. package/pi-extension/tests/cognitive-routing-v2/recovery.test.js +0 -1034
  334. package/pi-extension/tests/cognitive-routing-v2/render.test.js +0 -244
  335. package/pi-extension/tests/cognitive-routing-v2/runtime.test.js +0 -423
  336. package/pi-extension/tests/cognitive-routing-v2/stabilization.test.js +0 -521
  337. package/pi-extension/tests/cognitive-routing-v2/state.test.js +0 -586
  338. package/pi-extension/tests/context-virtualization/extension.test.js +0 -775
  339. package/pi-extension/tests/context-virtualization/projector.test.js +0 -110
  340. package/pi-extension/tests/context-virtualization/runtime.test.js +0 -230
  341. package/pi-extension/tests/conversation-history/runtime.test.js +0 -98
  342. package/pi-extension/tests/conversation-history/search.test.js +0 -97
  343. package/pi-extension/tests/fixtures/pi-host.js +0 -4
  344. package/pi-extension/tests/fixtures/routing-native.js +0 -191
  345. package/pi-extension/tests/integration/mode-free-core.test.js +0 -220
  346. package/pi-extension/tests/integration/pi-extension.test.js +0 -1447
  347. package/pi-extension/tests/integration/prompt-architecture.test.js +0 -447
  348. package/pi-extension/tests/integration/unaffected-regressions.test.js +0 -478
  349. package/pi-extension/tests/provider-support/astra-boundaries.test.js +0 -75
  350. package/pi-extension/tests/provider-support/astra.test.js +0 -306
  351. package/pi-extension/tests/provider-support/cli.test.js +0 -92
  352. package/pi-extension/tests/provider-support/native.test.js +0 -183
  353. package/pi-extension/tests/settings/settings-tui.test.js +0 -243
  354. package/pi-extension/tsconfig.json +0 -16
  355. package/plugin.json +0 -33
  356. package/runtime/prompts/context-virtualization.md +0 -3
  357. package/runtime/prompts/conversation-history.md +0 -3
  358. package/skills/action-selection/SKILL.md +0 -100
  359. package/skills/action-selection/references/trajectory-stalls.md +0 -71
  360. package/skills/bypass/SKILL.md +0 -153
  361. package/skills/commit-work/SKILL.md +0 -145
  362. package/skills/commit-work/references/git-state-edges.md +0 -94
  363. package/skills/commit-work/references/simple-push.md +0 -92
  364. package/skills/commit-work/references/staging-decisions.md +0 -106
  365. package/skills/decision-gate/SKILL.md +0 -106
  366. package/skills/design-for-depth/SKILL.md +0 -117
  367. package/skills/design-for-depth/references/design-pressure-signals.md +0 -182
  368. package/skills/design-for-depth/references/implementation-decisions.md +0 -76
  369. package/skills/design-for-depth/references/interface-design-loop.md +0 -136
  370. package/skills/design-for-depth/references/module-and-dependency-design.md +0 -147
  371. package/skills/design-for-depth/references/software-design-philosophy.md +0 -202
  372. package/skills/design-for-depth/references/state-and-failure-boundaries.md +0 -136
  373. package/skills/diagnose-failure/SKILL.md +0 -125
  374. package/skills/diagnose-failure/references/diagnostic-loop-catalog.md +0 -48
  375. package/skills/diagnose-failure/references/flaky-and-performance-diagnosis.md +0 -51
  376. package/skills/discuss/SKILL.md +0 -116
  377. package/skills/evaluate-skill/SKILL.md +0 -219
  378. package/skills/evaluate-skill/references/evaluation-definition-schema.md +0 -385
  379. package/skills/evaluate-skill/references/evaluation-design.md +0 -112
  380. package/skills/evaluate-skill/references/execution-and-evidence.md +0 -90
  381. package/skills/evaluate-skill/references/review-and-revision.md +0 -92
  382. package/skills/evaluate-skill/scripts/lib/definitions.mjs +0 -407
  383. package/skills/evaluate-skill/scripts/lib/grade-comparison.mjs +0 -60
  384. package/skills/evaluate-skill/scripts/lib/grade.mjs +0 -64
  385. package/skills/evaluate-skill/scripts/lib/runner.mjs +0 -368
  386. package/skills/evaluate-skill/scripts/pi-guard.mjs +0 -164
  387. package/skills/evaluate-skill/scripts/skill-eval.mjs +0 -102
  388. package/skills/execute-work/references/execute-work-edges.md +0 -68
  389. package/skills/finish-branch/SKILL.md +0 -117
  390. package/skills/finish-branch/references/integration-options.md +0 -80
  391. package/skills/handoff/SKILL.md +0 -82
  392. package/skills/handoff/references/handoff-templates.md +0 -150
  393. package/skills/launch-work/SKILL.md +0 -116
  394. package/skills/launch-work/references/launch-readiness.md +0 -85
  395. package/skills/migration-work/SKILL.md +0 -115
  396. package/skills/migration-work/references/migration-lifecycle.md +0 -82
  397. package/skills/release-work/SKILL.md +0 -118
  398. package/skills/release-work/references/release-evidence.md +0 -78
  399. package/skills/review-artifact/SKILL.md +0 -142
  400. package/skills/review-artifact/references/adjudicate-artifact-review.md +0 -101
  401. package/skills/review-artifact/references/independent-artifact-reviewer-contract.md +0 -159
  402. package/skills/review-work/references/adjudicate-work-review.md +0 -97
  403. package/skills/review-work/references/independent-work-reviewer-contract.md +0 -139
  404. package/skills/review-work/references/security-risk-lens.md +0 -69
  405. package/skills/setup-freeflow/references/activation-contract.md +0 -109
  406. package/skills/setup-freeflow/references/host-setup.md +0 -67
  407. package/skills/simplify-code/SKILL.md +0 -85
  408. package/skills/simplify-code/references/simplification-patterns.md +0 -70
  409. package/skills/verify-work/references/browser-runtime-evidence.md +0 -55
  410. package/skills/verify-work/references/integration-evidence.md +0 -47
  411. package/skills/verify-work/references/performance-evidence.md +0 -57
  412. package/skills/workflow/SKILL.md +0 -127
  413. package/skills/workflow/references/domain-skill-composition.md +0 -43
  414. package/skills/write-plan/SKILL.md +0 -92
  415. package/skills/write-plan/references/plan-shapes.md +0 -156
  416. package/skills/write-skill/references/activation-boundaries.md +0 -104
  417. package/skills/write-skill/references/agent-first-instructions.md +0 -121
  418. package/skills/write-skill/references/progressive-disclosure.md +0 -127
  419. package/skills/write-skill/references/skill-dependency-graphs.md +0 -190
  420. package/skills/write-spec/SKILL.md +0 -92
  421. package/skills/write-spec/references/artifact-standards.md +0 -86
  422. package/skills/write-spec/references/decision-records.md +0 -78
  423. package/skills/write-spec/references/spec-shapes.md +0 -143
  424. /package/pi-extension/dist/{cognitive-routing-v2 → cognitive-routing}/budget.js +0 -0
  425. /package/skills/{evaluate-skill → evaluate-behavior}/scripts/lib/evidence.mjs +0 -0
  426. /package/skills/{evaluate-skill → evaluate-behavior}/scripts/pi-observer.mjs +0 -0
@@ -1,1360 +0,0 @@
1
- import { execFile } from "node:child_process";
2
- import { appendFile, mkdir, readFile, rm, writeFile } from "node:fs/promises";
3
- import { dirname, isAbsolute, join, resolve } from "node:path";
4
- import { promisify } from "node:util";
5
- import {
6
- readCapabilityState,
7
- readFreeflowConfig,
8
- readFreeflowConfigLayers,
9
- readFreeflowLocalConfig,
10
- resetSessionOverrides,
11
- setSessionCoreOverride,
12
- } from "../runtime/runtime-context.js";
13
- import { PiSettingsComponent } from "./settings-tui.js";
14
- import { isPiFlowHost } from "../runtime/runtime-identity.js";
15
- import { isWorkerProfile, workersForDelegation } from "../cognitive-routing-v2/types.js";
16
- const DEFAULT_FREEFLOW_ENABLED = true;
17
- const DEFAULT_CONTEXT_VIRTUALIZATION_ENABLED = false;
18
- const DEFAULT_CONVERSATION_HISTORY_ENABLED = false;
19
- const LOCAL_INHERIT = "inherit";
20
- const execFileAsync = promisify(execFile);
21
- function isRecord(value) {
22
- return typeof value === "object" && value !== null && !Array.isArray(value);
23
- }
24
- function cloneJson(value) {
25
- if (value === undefined) return value;
26
- try {
27
- return JSON.parse(JSON.stringify(value));
28
- } catch (error) {
29
- throw new Error(`Could not clone settings value: ${error instanceof Error ? error.message : String(error)}`);
30
- }
31
- }
32
- function getPath(source, path) {
33
- let current = source;
34
- for (const key of path) {
35
- if (!isRecord(current)) return undefined;
36
- current = current[key];
37
- }
38
- return current;
39
- }
40
- function setPath(target, path, value) {
41
- let current = target;
42
- for (const key of path.slice(0, -1)) {
43
- const next = current[key];
44
- if (!isRecord(next)) {
45
- current[key] = {};
46
- }
47
- current = current[key];
48
- }
49
- current[path[path.length - 1]] = value;
50
- }
51
- function deletePath(target, path) {
52
- let current = target;
53
- const parents = [];
54
- for (const key of path.slice(0, -1)) {
55
- if (!isRecord(current)) return;
56
- parents.push({ object: current, key });
57
- current = current[key];
58
- }
59
- if (!isRecord(current)) return;
60
- delete current[path[path.length - 1]];
61
- for (let index = parents.length - 1; index >= 0; index--) {
62
- const { object, key } = parents[index];
63
- const child = object[key];
64
- if (isRecord(child) && Object.keys(child).length === 0) {
65
- delete object[key];
66
- }
67
- }
68
- }
69
- function valuesEqual(a, b) {
70
- return JSON.stringify(a) === JSON.stringify(b);
71
- }
72
- function isEmptyValue(value) {
73
- return Array.isArray(value) && value.length === 0;
74
- }
75
- function setConfigValue(config, item, value) {
76
- if (!item.path?.length) {
77
- throw new Error(`${item.label} is a settings group, not a writable setting.`);
78
- }
79
- if (item.defaultValue !== undefined && valuesEqual(value, item.defaultValue)) {
80
- deletePath(config, item.path);
81
- return;
82
- }
83
- if (isEmptyValue(value)) {
84
- deletePath(config, item.path);
85
- return;
86
- }
87
- setPath(config, item.path, value);
88
- }
89
- function booleanValue(value) {
90
- return value === true ? "enabled" : "disabled";
91
- }
92
- function configValueForChoice(item, value) {
93
- const key = String(value);
94
- if (item.configValues && Object.hasOwn(item.configValues, key)) {
95
- return item.configValues[key];
96
- }
97
- return value;
98
- }
99
- function effectiveItemValue(item) {
100
- return item.effectiveValue === undefined ? item.value : item.effectiveValue;
101
- }
102
- function formatCoreValue(value) {
103
- if (typeof value === "boolean") return booleanValue(value);
104
- if (isRecord(value) && typeof value.provider === "string" && typeof value.model === "string") {
105
- const effort = typeof value.thinking === "string" ? ` · ${value.thinking}` : "";
106
- return `${value.provider}/${value.model}${effort}`;
107
- }
108
- return String(value ?? "");
109
- }
110
- function coreDisplaySuffix(item, inactive = false) {
111
- const source = item.effectiveSource ?? "builtin";
112
- const parts =
113
- item.configScope === "repository" && source === "local"
114
- ? [`effective ${formatCoreValue(effectiveItemValue(item))}`, source]
115
- : [source];
116
- if (inactive) parts.push("inactive");
117
- return `(${parts.join(" · ")})`;
118
- }
119
- function updateScopedItemState(item, value) {
120
- if (!item.configScope) return;
121
- const configValue = configValueForChoice(item, value);
122
- if (item.configScope === "session" || item.configScope === "local") {
123
- item.effectiveValue = configValue === undefined ? item.inheritedValue : configValue;
124
- item.effectiveSource = configValue === undefined ? (item.inheritedSource ?? "builtin") : item.configScope;
125
- return;
126
- }
127
- if (item.localOverrideValue !== undefined) {
128
- item.effectiveValue = item.localOverrideValue;
129
- item.effectiveSource = "local";
130
- return;
131
- }
132
- item.effectiveValue = configValue;
133
- item.effectiveSource =
134
- item.defaultValue !== undefined && valuesEqual(configValue, item.defaultValue) ? "builtin" : "repository";
135
- }
136
- function createScopedBooleanItem(options) {
137
- const repositoryValue = getPath(options.rawConfig, options.path);
138
- const inheritedValue = typeof repositoryValue === "boolean" ? repositoryValue : options.defaultValue;
139
- const inheritedSource = typeof repositoryValue === "boolean" ? "repository" : "builtin";
140
- const localValue = getPath(options.localConfig, options.path);
141
- let item;
142
- if (options.scope === "local") {
143
- const selectedValue = typeof localValue === "boolean" ? String(localValue) : LOCAL_INHERIT;
144
- item = {
145
- id: options.id,
146
- label: options.label,
147
- description: `${options.description} Choose inherit to use the repository value; use /freeflow settings repo to edit shared defaults.`,
148
- path: options.path,
149
- kind: "enum",
150
- value: selectedValue,
151
- values: [LOCAL_INHERIT, "true", "false"],
152
- valueLabels: {
153
- inherit: "Inherit repository",
154
- true: "enabled",
155
- false: "disabled",
156
- },
157
- valueDescriptions: {
158
- inherit: `Use ${formatCoreValue(inheritedValue)} from ${inheritedSource}.`,
159
- true: "Set a personal enabled override.",
160
- false: "Set a personal disabled override.",
161
- },
162
- format: (value) => {
163
- if (value === LOCAL_INHERIT) return LOCAL_INHERIT;
164
- return booleanValue(value === "true");
165
- },
166
- configScope: "local",
167
- configValues: {
168
- inherit: undefined,
169
- true: true,
170
- false: false,
171
- },
172
- effectiveValue: options.effectiveValue,
173
- effectiveSource: options.effectiveSource,
174
- inheritedValue,
175
- inheritedSource,
176
- };
177
- } else {
178
- item = {
179
- id: options.id,
180
- label: options.label,
181
- description: `${options.description} This edits shared .freeflow/config.json.`,
182
- path: options.path,
183
- kind: "boolean",
184
- value: inheritedValue,
185
- defaultValue: options.defaultValue,
186
- configScope: "repository",
187
- effectiveValue: options.effectiveValue,
188
- effectiveSource: options.effectiveSource,
189
- localOverrideValue: typeof localValue === "boolean" ? localValue : undefined,
190
- };
191
- }
192
- item.displaySuffix = coreDisplaySuffix(item);
193
- return item;
194
- }
195
- function createScopedDelegationItem(options) {
196
- const path = ["cognitiveRouting", "delegation"];
197
- const repositoryValue = getPath(options.rawConfig, path);
198
- const inheritedValue = ["executor", "helper", "both"].includes(repositoryValue) ? repositoryValue : "executor";
199
- const inheritedSource = repositoryValue === undefined ? "builtin" : "repository";
200
- const localValue = getPath(options.localConfig, path);
201
- const descriptions = {
202
- executor: "Coordinator delegates assignments to Executor.",
203
- helper: "Coordinator delegates supporting assignments to Helper and keeps production implementation.",
204
- both: "Coordinator chooses Helper or Executor for each assignment.",
205
- };
206
- const item =
207
- options.scope === "local"
208
- ? {
209
- id: "freeflow.cognitiveRouting.delegation",
210
- label: "Delegation method",
211
- description:
212
- "Choose enabled workers for automatic routing. Inherit uses the repository value; this setting does not rank model presets.",
213
- path,
214
- kind: "enum",
215
- value: ["executor", "helper", "both"].includes(localValue) ? localValue : LOCAL_INHERIT,
216
- values: [LOCAL_INHERIT, "executor", "helper", "both"],
217
- valueLabels: {
218
- inherit: "Inherit repository",
219
- executor: "Executor only",
220
- helper: "Helper only",
221
- both: "Helper and Executor",
222
- },
223
- valueDescriptions: {
224
- inherit: `Use ${inheritedValue} from ${inheritedSource}.`,
225
- ...descriptions,
226
- },
227
- configScope: "local",
228
- configValues: { inherit: undefined, executor: "executor", helper: "helper", both: "both" },
229
- effectiveValue: options.effectiveValue,
230
- effectiveSource: options.effectiveSource,
231
- inheritedValue,
232
- inheritedSource,
233
- }
234
- : {
235
- id: "freeflow.cognitiveRouting.delegation",
236
- label: "Delegation method",
237
- description: "Choose enabled workers for automatic routing. This edits shared .freeflow/config.json.",
238
- path,
239
- kind: "enum",
240
- value: inheritedValue,
241
- values: ["executor", "helper", "both"],
242
- valueLabels: {
243
- executor: "Executor only",
244
- helper: "Helper only",
245
- both: "Helper and Executor",
246
- },
247
- valueDescriptions: descriptions,
248
- defaultValue: "executor",
249
- configScope: "repository",
250
- effectiveValue: options.effectiveValue,
251
- effectiveSource: options.effectiveSource,
252
- localOverrideValue: ["executor", "helper", "both"].includes(localValue) ? localValue : undefined,
253
- };
254
- item.displaySuffix = coreDisplaySuffix(item);
255
- return item;
256
- }
257
- function resolveSettingsCoreView(rawConfig, layers) {
258
- const localConfig = layers?.local.valid && isRecord(layers.local.parsed) ? layers.local.parsed : {};
259
- const fallbackCore = {
260
- enabled: getPath(rawConfig, ["enabled"]) !== false,
261
- contextVirtualization: getPath(rawConfig, ["contextVirtualization"]) === true,
262
- conversationHistory: getPath(rawConfig, ["conversationHistory"]) === true,
263
- };
264
- const fallbackSources = {
265
- enabled: typeof getPath(rawConfig, ["enabled"]) === "boolean" ? "repository" : "builtin",
266
- contextVirtualization:
267
- typeof getPath(rawConfig, ["contextVirtualization"]) === "boolean" ? "repository" : "builtin",
268
- conversationHistory: typeof getPath(rawConfig, ["conversationHistory"]) === "boolean" ? "repository" : "builtin",
269
- };
270
- return {
271
- localConfig,
272
- core: layers?.coreConfig ?? fallbackCore,
273
- sources: layers?.sources ?? fallbackSources,
274
- };
275
- }
276
- function createSessionBooleanItem(options) {
277
- const override = options.sessionOverrides[options.key];
278
- const item = {
279
- id: options.id,
280
- label: options.label,
281
- description: options.description,
282
- kind: "enum",
283
- value: typeof override === "boolean" ? String(override) : LOCAL_INHERIT,
284
- values: [LOCAL_INHERIT, "true", "false"],
285
- valueLabels: {
286
- inherit: "Inherit configured value",
287
- true: "Enabled for this session",
288
- false: "Disabled for this session",
289
- },
290
- valueDescriptions: {
291
- inherit: `Use ${formatCoreValue(options.inheritedValue)} from ${options.inheritedSource}.`,
292
- true: "Temporarily enable this setting for the current Pi session.",
293
- false: "Temporarily disable this setting for the current Pi session.",
294
- },
295
- format: (value) => {
296
- if (value === LOCAL_INHERIT) return LOCAL_INHERIT;
297
- return booleanValue(value === "true");
298
- },
299
- configScope: "session",
300
- configValues: {
301
- inherit: undefined,
302
- true: true,
303
- false: false,
304
- },
305
- effectiveValue: options.effectiveValue,
306
- effectiveSource: options.effectiveSource,
307
- inheritedValue: options.inheritedValue,
308
- inheritedSource: options.inheritedSource,
309
- };
310
- item.displaySuffix = coreDisplaySuffix(item);
311
- return item;
312
- }
313
- function sessionFreeflowItems(state, cognitiveRoutingController, ctx) {
314
- const sessionOverrides = state.sessionOverrides;
315
- const configured = state.configuredCoreConfig;
316
- const configuredSources = state.configuredSources;
317
- const effectiveSources = state.configSources;
318
- const freeflowItem = createSessionBooleanItem({
319
- id: "freeflow.enabled",
320
- label: "Freeflow",
321
- description: "Temporary master override for this Pi session.",
322
- key: "enabled",
323
- inheritedValue: configured.enabled,
324
- inheritedSource: configuredSources.enabled,
325
- effectiveValue: state.enabled,
326
- effectiveSource: effectiveSources.enabled,
327
- sessionOverrides,
328
- });
329
- const contextVirtualizationItem = createSessionBooleanItem({
330
- id: "freeflow.contextVirtualization",
331
- label: "Context Virtualization",
332
- description: "Temporary Context Virtualization override for this Pi session.",
333
- key: "contextVirtualization",
334
- inheritedValue: configured.contextVirtualization,
335
- inheritedSource: configuredSources.contextVirtualization,
336
- effectiveValue: state.contextVirtualization.enabled,
337
- effectiveSource: effectiveSources.contextVirtualization,
338
- sessionOverrides,
339
- });
340
- const conversationHistoryItem = createSessionBooleanItem({
341
- id: "freeflow.conversationHistory",
342
- label: "Conversation History",
343
- description: "Temporary Conversation History override for this Pi session.",
344
- key: "conversationHistory",
345
- inheritedValue: configured.conversationHistory,
346
- inheritedSource: configuredSources.conversationHistory,
347
- effectiveValue: state.conversationHistory.enabled,
348
- effectiveSource: effectiveSources.conversationHistory,
349
- sessionOverrides,
350
- });
351
- const freeflowInactive = !state.enabled;
352
- contextVirtualizationItem.inactive = freeflowInactive;
353
- conversationHistoryItem.inactive = freeflowInactive;
354
- const cognitiveRoutingState = cognitiveRoutingController?.state();
355
- const delegation = state.cognitiveRouting?.delegation ?? "executor";
356
- const heldProfile = cognitiveRoutingState?.controlMode.startsWith("manual-")
357
- ? cognitiveRoutingState.activeProfile
358
- : undefined;
359
- const availableProfiles = ["coordinator", ...workersForDelegation(delegation)];
360
- if (heldProfile === "coordinator" || isWorkerProfile(heldProfile)) availableProfiles.push(heldProfile);
361
- const manualProfiles = [...new Set(availableProfiles)];
362
- const cognitiveRoutingProfile = heldProfile && manualProfiles.includes(heldProfile) ? heldProfile : "auto";
363
- const cognitiveRoutingItem = state.cognitiveRouting
364
- ? {
365
- id: "freeflow.cognitiveRouting.profile",
366
- label: "Cognitive Routing",
367
- description: "Hold an enabled profile manually or release the hold for automatic model control.",
368
- kind: "enum",
369
- value: cognitiveRoutingProfile,
370
- values: ["auto", ...manualProfiles],
371
- valueLabels: Object.fromEntries([
372
- ["auto", "automatic"],
373
- ...manualProfiles.map((profile) => [profile, `manual · ${profile}`]),
374
- ]),
375
- valueDescriptions: Object.fromEntries([
376
- ["auto", "Release the manual hold and return to Coordinator reconciliation."],
377
- ...manualProfiles.map((profile) => [profile, `Hold the ${profile} profile until /freeflow profile auto.`]),
378
- ]),
379
- inactive: freeflowInactive || !state.cognitiveRouting.effective || cognitiveRoutingController === undefined,
380
- runtimeInactive: state.cognitiveRouting.blockingReason?.code === "runtime_disabled",
381
- displaySuffix: cognitiveRoutingState?.effective ? cognitiveRoutingProfile : "unavailable",
382
- }
383
- : undefined;
384
- const sessionProfiles = cognitiveRoutingController?.sessionProfileOverrides();
385
- const profileItems =
386
- state.cognitiveRouting && cognitiveRoutingController
387
- ? manualProfiles.map((name) =>
388
- cognitiveRoutingProfileItem({
389
- name,
390
- scope: "session",
391
- rawConfig: {},
392
- localConfig: {},
393
- capabilityState: state.cognitiveRouting,
394
- ctx,
395
- sessionProfiles,
396
- }),
397
- )
398
- : [];
399
- const cognitiveRoutingPresets = profileItems.length
400
- ? {
401
- id: "freeflow.cognitiveRouting.presets",
402
- label: "Cognitive Routing presets",
403
- description: "Temporarily choose complete model/effort pairs for profiles enabled in this Pi session.",
404
- kind: "group",
405
- value: profileItems.some((item) => item.value !== LOCAL_INHERIT && item.value !== undefined),
406
- displaySuffix: `${profileItems.filter((item) => item.value !== LOCAL_INHERIT && item.value !== undefined).length}/${profileItems.length} session overrides`,
407
- inactive: freeflowInactive || !state.cognitiveRouting?.effective || cognitiveRoutingController === undefined,
408
- children: profileItems,
409
- }
410
- : undefined;
411
- return [
412
- freeflowItem,
413
- ...(cognitiveRoutingItem ? [cognitiveRoutingItem] : []),
414
- ...(cognitiveRoutingPresets ? [cognitiveRoutingPresets] : []),
415
- {
416
- id: "freeflow.session.reset",
417
- label: "Reset session overrides",
418
- description:
419
- "Clear Freeflow, Context Virtualization, Conversation History, and routing profile overrides for this Pi session.",
420
- kind: "enum",
421
- value: "available",
422
- values: ["reset"],
423
- valueLabels: { reset: "Reset all session overrides" },
424
- valueDescriptions: { reset: "Return every session setting and routing preset to its configured value." },
425
- format: () => "available",
426
- transient: true,
427
- },
428
- {
429
- id: "freeflow.context",
430
- label: "Freeflow Context",
431
- description: "Choose which context projection and conversation-history operations are available to the model.",
432
- kind: "group",
433
- value: contextVirtualizationItem.effectiveValue === true || conversationHistoryItem.effectiveValue === true,
434
- displaySuffix: `${[contextVirtualizationItem, conversationHistoryItem].filter((item) => item.effectiveValue === true).length}/2 enabled`,
435
- children: [contextVirtualizationItem, conversationHistoryItem],
436
- },
437
- ];
438
- }
439
- const COGNITIVE_ROUTING_THINKING_LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
440
- const COGNITIVE_ROUTING_EFFORT_DESCRIPTIONS = {
441
- off: "No reasoning",
442
- minimal: "Very brief reasoning",
443
- low: "Light reasoning",
444
- medium: "Moderate reasoning",
445
- high: "Deep reasoning",
446
- xhigh: "Extra-high reasoning",
447
- max: "Maximum reasoning",
448
- };
449
- function cognitiveRoutingModelKey(provider, model) {
450
- return `${provider}/${model}`;
451
- }
452
- function isCognitiveRoutingProfile(value) {
453
- return (
454
- isRecord(value) &&
455
- typeof value.provider === "string" &&
456
- typeof value.model === "string" &&
457
- typeof value.thinking === "string" &&
458
- COGNITIVE_ROUTING_THINKING_LEVELS.includes(value.thinking)
459
- );
460
- }
461
- function cognitiveRoutingThinkingLevels(model, registry) {
462
- if (typeof registry?.clampThinkingLevel !== "function") {
463
- return model?.reasoning === true ? [...COGNITIVE_ROUTING_THINKING_LEVELS] : ["off"];
464
- }
465
- return COGNITIVE_ROUTING_THINKING_LEVELS.filter((level) => {
466
- try {
467
- return registry.clampThinkingLevel(model, level) === level;
468
- } catch {
469
- return false;
470
- }
471
- });
472
- }
473
- function cognitiveRoutingModelOptions(ctx) {
474
- const registry = ctx?.modelRegistry;
475
- if (typeof registry?.getAvailable !== "function") return [];
476
- let models;
477
- try {
478
- models = registry.getAvailable();
479
- } catch {
480
- return [];
481
- }
482
- if (!Array.isArray(models)) return [];
483
- return models
484
- .filter((model) => typeof model?.provider === "string" && typeof model?.id === "string")
485
- .map((model) => {
486
- const thinkingLevels = cognitiveRoutingThinkingLevels(model, registry);
487
- const provider = model.provider;
488
- const modelId = model.id;
489
- const key = cognitiveRoutingModelKey(provider, modelId);
490
- const displayName = typeof model.name === "string" && model.name !== modelId ? model.name : undefined;
491
- return {
492
- key,
493
- provider,
494
- model: modelId,
495
- label: key,
496
- description: displayName ? `${displayName} · ${thinkingLevels.join(", ")}` : thinkingLevels.join(", "),
497
- thinkingLevels,
498
- };
499
- })
500
- .filter((model) => model.thinkingLevels.length > 0)
501
- .sort((a, b) => a.label.localeCompare(b.label));
502
- }
503
- function cognitiveRoutingProfileDisplay(value) {
504
- return isCognitiveRoutingProfile(value) ? formatCoreValue(value) : "not configured";
505
- }
506
- function cognitiveRoutingSettingsSource(source) {
507
- if (source === "session") return "session";
508
- if (source === "repository") return "repository";
509
- if (source === "personal" || source === "local") return "local";
510
- return "builtin";
511
- }
512
- function cognitiveRoutingProfileDisplaySuffix(source, scope) {
513
- if (!source) return undefined;
514
- if (source === "session") return "(session override)";
515
- if (source === "personal" && scope === "repository") return "(effective personal)";
516
- return `(${source})`;
517
- }
518
- function cognitiveRoutingConfirmStep(summary) {
519
- return {
520
- title: "Confirm preset",
521
- choices: [
522
- {
523
- key: "__save__",
524
- value: "save",
525
- label: `Save ${summary}`,
526
- description: "Write the complete profile atomically.",
527
- },
528
- { key: "__cancel__", value: "cancel", label: "Cancel", description: "Leave the previous preset unchanged." },
529
- ],
530
- selectedKey: "__save__",
531
- };
532
- }
533
- function createCognitiveRoutingProfileWizard(
534
- currentValue,
535
- models,
536
- allowInherit,
537
- inheritChoice = {
538
- label: "Inherit repository preset",
539
- description: "Remove the personal override without changing the repository preset.",
540
- summary: "inherit repository preset",
541
- },
542
- ) {
543
- const currentProfile = isCognitiveRoutingProfile(currentValue) ? currentValue : undefined;
544
- const currentModelKey = currentProfile
545
- ? cognitiveRoutingModelKey(currentProfile.provider, currentProfile.model)
546
- : undefined;
547
- const firstChoices = [
548
- ...(allowInherit
549
- ? [
550
- {
551
- key: LOCAL_INHERIT,
552
- value: LOCAL_INHERIT,
553
- label: inheritChoice.label,
554
- description: inheritChoice.description,
555
- },
556
- ]
557
- : []),
558
- ...models.map((model) => ({
559
- key: model.key,
560
- value: model,
561
- label: model.label,
562
- description: model.description,
563
- })),
564
- ];
565
- if (firstChoices.length === 0) {
566
- firstChoices.push({
567
- key: "__cancel__",
568
- value: "cancel",
569
- label: "No authenticated models available",
570
- description: "Authenticate a provider before configuring this preset.",
571
- });
572
- }
573
- return {
574
- firstStep: () => ({
575
- title: "Choose model",
576
- choices: firstChoices,
577
- selectedKey:
578
- currentValue === LOCAL_INHERIT
579
- ? LOCAL_INHERIT
580
- : firstChoices.some((choice) => choice.key === currentModelKey)
581
- ? currentModelKey
582
- : firstChoices[0]?.key,
583
- }),
584
- nextStep: (selectedValues) => {
585
- if (selectedValues.length === 1) {
586
- const selected = selectedValues[0];
587
- if (selected === LOCAL_INHERIT) {
588
- return cognitiveRoutingConfirmStep(inheritChoice.summary);
589
- }
590
- const model = selected;
591
- if (!model?.key || model.thinkingLevels.length === 0) return undefined;
592
- const currentEffort = currentProfile && currentModelKey === model.key ? currentProfile.thinking : undefined;
593
- return {
594
- title: `Choose effort · ${model.label}`,
595
- choices: model.thinkingLevels.map((level) => ({
596
- key: level,
597
- value: level,
598
- label: level,
599
- description: COGNITIVE_ROUTING_EFFORT_DESCRIPTIONS[level],
600
- })),
601
- selectedKey:
602
- currentEffort && model.thinkingLevels.includes(currentEffort) ? currentEffort : model.thinkingLevels[0],
603
- };
604
- }
605
- if (selectedValues.length === 2) {
606
- const model = selectedValues[0];
607
- const effort = selectedValues[1];
608
- return cognitiveRoutingConfirmStep(`${model.label} · ${effort}`);
609
- }
610
- return undefined;
611
- },
612
- valueFromSelections: (selectedValues) => {
613
- if (selectedValues[0] === LOCAL_INHERIT) return undefined;
614
- const model = selectedValues[0];
615
- return {
616
- provider: model.provider,
617
- model: model.model,
618
- thinking: selectedValues[1],
619
- };
620
- },
621
- };
622
- }
623
- function cognitiveRoutingProfileItem(options) {
624
- const path = ["cognitiveRouting", "profiles", options.name];
625
- const repositoryProfile = getPath(options.rawConfig, path);
626
- const localProfile = getPath(options.localConfig, path);
627
- const configuredProfile = options.capabilityState?.profiles?.[options.name] ?? repositoryProfile;
628
- const sessionPair = options.sessionProfiles?.[options.name];
629
- const sessionProfile = sessionPair
630
- ? { provider: sessionPair.provider, model: sessionPair.modelId, thinking: sessionPair.thinking }
631
- : undefined;
632
- const effectiveProfile = sessionProfile ?? configuredProfile;
633
- const localValue = isCognitiveRoutingProfile(localProfile) ? localProfile : LOCAL_INHERIT;
634
- const value =
635
- options.scope === "session"
636
- ? (sessionProfile ?? LOCAL_INHERIT)
637
- : options.scope === "local"
638
- ? localValue
639
- : repositoryProfile;
640
- const configuredSource =
641
- options.capabilityState?.profileSources?.[options.name] ??
642
- (isCognitiveRoutingProfile(repositoryProfile) ? "repository" : undefined);
643
- const source = options.scope === "session" ? (sessionProfile ? "session" : configuredSource) : configuredSource;
644
- const models = cognitiveRoutingModelOptions(options.ctx);
645
- const inactive = options.scope !== "repository" && models.length === 0 && value !== LOCAL_INHERIT;
646
- const inheritChoice =
647
- options.scope === "session"
648
- ? {
649
- label: "Inherit configured preset",
650
- description: "Remove the session override without changing local or repository configuration.",
651
- summary: "inherit configured preset",
652
- }
653
- : undefined;
654
- return {
655
- id: `freeflow.cognitiveRouting.${options.name}`,
656
- label: `${options.name.charAt(0).toUpperCase()}${options.name.slice(1)} preset`,
657
- description:
658
- options.scope === "session"
659
- ? "Temporarily choose the model and effort for this profile in the current Pi session only."
660
- : "Choose an authenticated available model and one effort supported by that model. Confirming writes the complete preset; cancel leaves it unchanged.",
661
- path,
662
- kind: "string",
663
- value,
664
- format: (current) => {
665
- const inherits = current === LOCAL_INHERIT || (options.scope === "session" && current === undefined);
666
- return inherits
667
- ? options.scope === "session"
668
- ? "inherit configured preset"
669
- : "inherit repository preset"
670
- : cognitiveRoutingProfileDisplay(current);
671
- },
672
- configScope: options.scope,
673
- effectiveValue: effectiveProfile,
674
- effectiveSource: cognitiveRoutingSettingsSource(source),
675
- inheritedValue: options.scope === "session" ? configuredProfile : repositoryProfile,
676
- inheritedSource: cognitiveRoutingSettingsSource(configuredSource ?? "builtin"),
677
- inactive,
678
- displaySuffix: cognitiveRoutingProfileDisplaySuffix(source, options.scope),
679
- wizard: () => createCognitiveRoutingProfileWizard(value, models, options.scope !== "repository", inheritChoice),
680
- };
681
- }
682
- function isCognitiveRoutingRuntimeAvailable(pi) {
683
- return (
684
- !isPiFlowHost(pi?.host) &&
685
- typeof pi?.appendEntry === "function" &&
686
- typeof pi?.setModel === "function" &&
687
- typeof pi?.setThinkingLevel === "function"
688
- );
689
- }
690
- function freeflowItems(rawConfig, options = {}) {
691
- const scope = options.scope === "local" ? "local" : "repository";
692
- const layers = options.layers;
693
- const { localConfig, core, sources } = resolveSettingsCoreView(rawConfig, layers);
694
- const freeflowItem = createScopedBooleanItem({
695
- scope,
696
- rawConfig,
697
- localConfig,
698
- id: "freeflow.enabled",
699
- label: "Freeflow",
700
- description: "Master switch for Freeflow's core guidance, skills, and optional capabilities in this checkout.",
701
- path: ["enabled"],
702
- effectiveValue: core.enabled,
703
- effectiveSource: sources.enabled,
704
- defaultValue: DEFAULT_FREEFLOW_ENABLED,
705
- });
706
- const contextVirtualizationItem = createScopedBooleanItem({
707
- scope,
708
- rawConfig,
709
- localConfig,
710
- id: "freeflow.contextVirtualization",
711
- label: "Context Virtualization",
712
- description: "Let the model archive consumed tool results from future context while preserving session history.",
713
- path: ["contextVirtualization"],
714
- effectiveValue: core.contextVirtualization,
715
- effectiveSource: sources.contextVirtualization,
716
- defaultValue: DEFAULT_CONTEXT_VIRTUALIZATION_ENABLED,
717
- });
718
- const conversationHistoryItem = createScopedBooleanItem({
719
- scope,
720
- rawConfig,
721
- localConfig,
722
- id: "freeflow.conversationHistory",
723
- label: "Conversation History",
724
- description: "Let the model search and retrieve hidden conversation history on the active branch.",
725
- path: ["conversationHistory"],
726
- effectiveValue: core.conversationHistory,
727
- effectiveSource: sources.conversationHistory,
728
- defaultValue: DEFAULT_CONVERSATION_HISTORY_ENABLED,
729
- });
730
- const freeflowInactive = !core.enabled;
731
- contextVirtualizationItem.inactive = freeflowInactive;
732
- conversationHistoryItem.inactive = freeflowInactive;
733
- const cognitiveRoutingState = options.cognitiveRouting;
734
- const cognitiveRoutingRuntimeDisabled = options.runtimeAvailable !== true;
735
- const cognitiveRoutingGroup = (() => {
736
- const cognitiveRoutingEnabledItem = createScopedBooleanItem({
737
- scope,
738
- rawConfig,
739
- localConfig,
740
- id: "freeflow.cognitiveRouting.enabled",
741
- label: "Enabled",
742
- description: cognitiveRoutingRuntimeDisabled
743
- ? "Requires a host model-state control API; configuration is read-only on this host."
744
- : "Allow Cognitive Routing to manage explicit assignments and request native profile transitions.",
745
- path: ["cognitiveRouting", "enabled"],
746
- effectiveValue: cognitiveRoutingState?.enabled ?? false,
747
- effectiveSource: cognitiveRoutingSettingsSource(cognitiveRoutingState?.enabledSource),
748
- defaultValue: false,
749
- });
750
- cognitiveRoutingEnabledItem.inactive = freeflowInactive || cognitiveRoutingRuntimeDisabled;
751
- cognitiveRoutingEnabledItem.runtimeInactive = cognitiveRoutingRuntimeDisabled;
752
- const cognitiveRoutingDelegationItem = createScopedDelegationItem({
753
- scope,
754
- rawConfig,
755
- localConfig,
756
- effectiveValue: cognitiveRoutingState?.delegation ?? "executor",
757
- effectiveSource: cognitiveRoutingSettingsSource(cognitiveRoutingState?.delegationSource),
758
- });
759
- cognitiveRoutingDelegationItem.inactive = freeflowInactive || cognitiveRoutingRuntimeDisabled;
760
- cognitiveRoutingDelegationItem.runtimeInactive = cognitiveRoutingRuntimeDisabled;
761
- const cognitiveRoutingProjectionItem = createScopedBooleanItem({
762
- scope,
763
- rawConfig,
764
- localConfig,
765
- id: "freeflow.cognitiveRouting.projection",
766
- label: "Context projection",
767
- description:
768
- "Select worker evidence for Coordinator; disable projection to keep ordinary Pi context in all enabled profiles.",
769
- path: ["cognitiveRouting", "projection"],
770
- effectiveValue: cognitiveRoutingState?.projection ?? false,
771
- effectiveSource: cognitiveRoutingSettingsSource(cognitiveRoutingState?.projectionSource),
772
- defaultValue: false,
773
- });
774
- cognitiveRoutingProjectionItem.inactive = freeflowInactive || cognitiveRoutingRuntimeDisabled;
775
- cognitiveRoutingProjectionItem.runtimeInactive = cognitiveRoutingRuntimeDisabled;
776
- const cognitiveRoutingProfiles = ["coordinator", "helper", "executor"].map((name) =>
777
- cognitiveRoutingProfileItem({
778
- name: name,
779
- scope,
780
- rawConfig,
781
- localConfig,
782
- capabilityState: cognitiveRoutingState,
783
- ctx: options.ctx,
784
- }),
785
- );
786
- for (const item of cognitiveRoutingProfiles) {
787
- item.inactive ||= freeflowInactive || cognitiveRoutingRuntimeDisabled;
788
- item.runtimeInactive = cognitiveRoutingRuntimeDisabled;
789
- }
790
- const cognitiveRoutingStatus = cognitiveRoutingRuntimeDisabled
791
- ? "unavailable · host unsupported"
792
- : cognitiveRoutingState
793
- ? cognitiveRoutingState.effective
794
- ? "active"
795
- : cognitiveRoutingState.blockingReason?.code === "profile_missing"
796
- ? "not configured"
797
- : (cognitiveRoutingState.blockingReason?.code ?? "inactive")
798
- : "unavailable";
799
- return {
800
- id: "freeflow.cognitiveRouting",
801
- label: "Cognitive Routing",
802
- description: cognitiveRoutingRuntimeDisabled
803
- ? "Cognitive Routing configuration is visible for inspection but requires a host model-state control API."
804
- : "Configure Coordinator, Helper, and Executor profiles plus the workers available for delegation.",
805
- kind: "group",
806
- value: cognitiveRoutingRuntimeDisabled ? false : (cognitiveRoutingState?.enabled ?? false),
807
- inactive: freeflowInactive,
808
- displaySuffix: cognitiveRoutingStatus,
809
- children: [
810
- cognitiveRoutingEnabledItem,
811
- cognitiveRoutingDelegationItem,
812
- ...cognitiveRoutingProfiles,
813
- cognitiveRoutingProjectionItem,
814
- ],
815
- };
816
- })();
817
- return [
818
- freeflowItem,
819
- ...(cognitiveRoutingGroup ? [cognitiveRoutingGroup] : []),
820
- {
821
- id: "freeflow.context",
822
- label: "Freeflow Context",
823
- description: "Choose which context projection and conversation-history operations are available to the model.",
824
- kind: "group",
825
- value: contextVirtualizationItem.effectiveValue === true || conversationHistoryItem.effectiveValue === true,
826
- displaySuffix: `${[contextVirtualizationItem, conversationHistoryItem].filter((item) => item.effectiveValue === true).length}/2 enabled`,
827
- children: [contextVirtualizationItem, conversationHistoryItem],
828
- },
829
- ];
830
- }
831
- function pruneKnownDefaults(config) {
832
- const defaultPaths = [
833
- { path: ["enabled"], value: DEFAULT_FREEFLOW_ENABLED },
834
- { path: ["contextVirtualization"], value: DEFAULT_CONTEXT_VIRTUALIZATION_ENABLED },
835
- { path: ["conversationHistory"], value: DEFAULT_CONVERSATION_HISTORY_ENABLED },
836
- { path: ["cognitiveRouting", "delegation"], value: "executor" },
837
- ];
838
- for (const item of defaultPaths) {
839
- if (valuesEqual(getPath(config, item.path), item.value)) {
840
- deletePath(config, item.path);
841
- }
842
- }
843
- }
844
- async function ensureLocalConfigIgnored(cwd) {
845
- let gitPath;
846
- try {
847
- const result = await execFileAsync("git", ["-C", cwd, "rev-parse", "--git-path", "info/exclude"]);
848
- gitPath = result.stdout.trim();
849
- } catch {
850
- return;
851
- }
852
- const tracked = await execFileAsync("git", ["-C", cwd, "ls-files", "--", ".freeflow/local.json"]);
853
- if (tracked.stdout.trim()) {
854
- throw new Error(
855
- ".freeflow/local.json is tracked by git; remove it from the index before writing personal overrides.",
856
- );
857
- }
858
- try {
859
- await execFileAsync("git", ["-C", cwd, "check-ignore", "-q", "--", ".freeflow/local.json"]);
860
- return;
861
- } catch {
862
- // Add a local exclude when the repository does not already ignore the file.
863
- }
864
- const excludePath = isAbsolute(gitPath) ? gitPath : resolve(cwd, gitPath);
865
- let existing = "";
866
- try {
867
- existing = await readFile(excludePath, "utf8");
868
- } catch {
869
- // The git metadata path may not exist yet in a minimal repository.
870
- }
871
- const rule = ".freeflow/local.json";
872
- if (existing.split(/\r?\n/).includes(rule)) return;
873
- await mkdir(dirname(excludePath), { recursive: true });
874
- const prefix = existing && !existing.endsWith("\n") ? "\n" : "";
875
- await appendFile(excludePath, `${prefix}${rule}\n`, "utf8");
876
- }
877
- async function updateConfig(cwd, item, value, scope = item.configScope ?? "repository") {
878
- if (scope === "local") {
879
- if (!item.path?.length) {
880
- throw new Error(`${item.label} is a settings group, not a writable setting.`);
881
- }
882
- const current = await readFreeflowLocalConfig(cwd);
883
- const next = cloneJson(current);
884
- const configValue = configValueForChoice(item, value);
885
- const previousValue = getPath(current, item.path);
886
- if (configValue === undefined || isEmptyValue(configValue)) {
887
- if (previousValue === undefined) return;
888
- deletePath(next, item.path);
889
- } else {
890
- setPath(next, item.path, configValue);
891
- }
892
- const path = join(cwd, ".freeflow/local.json");
893
- await ensureLocalConfigIgnored(cwd);
894
- if (Object.keys(next).length === 0) {
895
- await rm(path, { force: true });
896
- return;
897
- }
898
- await mkdir(join(cwd, ".freeflow"), { recursive: true });
899
- await writeFile(path, `${JSON.stringify(next, null, 2)}\n`, "utf8");
900
- return;
901
- }
902
- const current = await readFreeflowConfig(cwd);
903
- const next = cloneJson(current);
904
- setConfigValue(next, item, value);
905
- pruneKnownDefaults(next);
906
- await mkdir(join(cwd, ".freeflow"), { recursive: true });
907
- await writeFile(join(cwd, ".freeflow/config.json"), `${JSON.stringify(next, null, 2)}\n`, "utf8");
908
- }
909
- function isCognitiveRoutingProfileItem(item) {
910
- return ["coordinator", "helper", "executor"].some((profile) => item.id === `freeflow.cognitiveRouting.${profile}`);
911
- }
912
- function valueForDisplay(item) {
913
- let value;
914
- if (isCognitiveRoutingProfileItem(item) && item.format) {
915
- value = item.format(effectiveItemValue(item));
916
- } else if (item.configScope === "local" || item.configScope === "session") {
917
- value = formatCoreValue(effectiveItemValue(item));
918
- } else if (item.kind === "boolean") {
919
- value = booleanValue(item.value);
920
- } else if (item.kind === "group") {
921
- const status = typeof item.value === "boolean" ? booleanValue(item.value) : String(item.value ?? "");
922
- const count = item.children?.length ?? 0;
923
- value = count > 0 ? `${status} (${count})` : status;
924
- } else if (item.format) {
925
- value = item.format(item.value);
926
- } else {
927
- value = String(item.value ?? "");
928
- }
929
- return item.displaySuffix ? `${value} ${item.displaySuffix}` : value;
930
- }
931
- function walkSettingsItems(items, visitor) {
932
- for (const item of items) {
933
- visitor(item);
934
- if (item.children) walkSettingsItems(item.children, visitor);
935
- }
936
- }
937
- function findSettingsItem(items, id) {
938
- for (const item of items) {
939
- if (item.id === id) return item;
940
- const child = item.children ? findSettingsItem(item.children, id) : undefined;
941
- if (child) return child;
942
- }
943
- return undefined;
944
- }
945
- function refreshSettingsDerivedState(items) {
946
- const freeflowItem = findSettingsItem(items, "freeflow.enabled");
947
- const freeflowInactive = freeflowItem ? effectiveItemValue(freeflowItem) !== true : false;
948
- const cognitiveRoutingGroup = findSettingsItem(items, "freeflow.cognitiveRouting");
949
- const cognitiveRoutingEnabledItem = findSettingsItem(items, "freeflow.cognitiveRouting.enabled");
950
- const cognitiveRoutingDelegationItem = findSettingsItem(items, "freeflow.cognitiveRouting.delegation");
951
- const delegation = cognitiveRoutingDelegationItem ? effectiveItemValue(cognitiveRoutingDelegationItem) : "executor";
952
- const cognitiveRoutingProfiles = ["coordinator", ...workersForDelegation(delegation)].map((profile) =>
953
- findSettingsItem(items, `freeflow.cognitiveRouting.${profile}`),
954
- );
955
- if (cognitiveRoutingGroup && cognitiveRoutingEnabledItem) {
956
- const enabled = effectiveItemValue(cognitiveRoutingEnabledItem) === true;
957
- const profilesConfigured = cognitiveRoutingProfiles.every((item) =>
958
- item ? isCognitiveRoutingProfile(effectiveItemValue(item)) : false,
959
- );
960
- cognitiveRoutingGroup.value = enabled;
961
- cognitiveRoutingGroup.displaySuffix = enabled
962
- ? profilesConfigured
963
- ? cognitiveRoutingGroup.displaySuffix === "active"
964
- ? "active"
965
- : "configured"
966
- : "not configured"
967
- : "disabled";
968
- cognitiveRoutingGroup.inactive = freeflowInactive;
969
- }
970
- const contextGroup = findSettingsItem(items, "freeflow.context");
971
- if (contextGroup?.children?.length) {
972
- const enabledCount = contextGroup.children.filter((item) => effectiveItemValue(item) === true).length;
973
- contextGroup.value = enabledCount > 0;
974
- contextGroup.displaySuffix = `${enabledCount}/${contextGroup.children.length} enabled`;
975
- }
976
- walkSettingsItems(items, (candidate) => {
977
- if (candidate.id === "freeflow.session.reset") {
978
- candidate.inactive = false;
979
- } else if (candidate.configScope) {
980
- const inactive =
981
- candidate.id === "freeflow.enabled" ? false : candidate.runtimeInactive === true || freeflowInactive;
982
- candidate.inactive = inactive;
983
- candidate.displaySuffix = coreDisplaySuffix(candidate, inactive);
984
- } else {
985
- candidate.inactive = candidate.runtimeInactive === true || freeflowInactive;
986
- }
987
- });
988
- }
989
- function settingsChoices(item) {
990
- if (item.kind === "boolean") {
991
- return [
992
- { key: "true", value: true, label: "enabled", description: "Enable this setting." },
993
- { key: "false", value: false, label: "disabled", description: "Disable this setting." },
994
- ];
995
- }
996
- if (item.kind !== "enum") return undefined;
997
- return (item.values ?? []).map((value) => ({
998
- key: value,
999
- value,
1000
- label: item.valueLabels?.[value] ?? value,
1001
- description: item.valueDescriptions?.[value],
1002
- }));
1003
- }
1004
- function resetSessionItemState(items) {
1005
- walkSettingsItems(items, (item) => {
1006
- if (item.configScope === "session") {
1007
- item.value = LOCAL_INHERIT;
1008
- item.effectiveValue = item.inheritedValue;
1009
- item.effectiveSource = item.inheritedSource ?? "builtin";
1010
- } else if (item.id === "freeflow.sessionMode") {
1011
- item.value = "default";
1012
- }
1013
- });
1014
- }
1015
- function settingsEntries(items, rootItems, onChange) {
1016
- return items.map((item) => ({
1017
- id: item.id,
1018
- label: item.label,
1019
- description: item.description,
1020
- currentValue: () => valueForDisplay(item),
1021
- inactive: () => item.inactive === true,
1022
- currentChoiceKey: () => String(item.value),
1023
- choices: settingsChoices(item),
1024
- children: item.children ? () => settingsEntries(item.children, rootItems, onChange) : undefined,
1025
- wizard: item.wizard ? () => item.wizard() : undefined,
1026
- edit:
1027
- !item.children && !["boolean", "enum", "group"].includes(item.kind)
1028
- ? {
1029
- initialValue: () => valueForDisplay(item),
1030
- parse: (text) => (item.parse ? item.parse(text) : text),
1031
- }
1032
- : undefined,
1033
- commit:
1034
- item.kind === "group"
1035
- ? undefined
1036
- : async (value) => {
1037
- if (valuesEqual(item.value, value)) return { changed: false, reloadRequired: false };
1038
- const outcome = await onChange(item, value);
1039
- if (outcome.changed) {
1040
- updateScopedItemState(item, value);
1041
- if (item.id === "freeflow.session.reset") {
1042
- resetSessionItemState(rootItems);
1043
- } else if (!item.transient) {
1044
- item.value = value;
1045
- }
1046
- refreshSettingsDerivedState(rootItems);
1047
- }
1048
- return outcome;
1049
- },
1050
- }));
1051
- }
1052
- async function openSettings(options) {
1053
- if (typeof options.ctx?.ui?.custom !== "function") {
1054
- options.ctx?.ui?.notify?.(
1055
- `${options.title} requires Pi TUI mode. Use the status command for a compact summary.`,
1056
- "warning",
1057
- );
1058
- return { changed: false, configChanged: false, failed: false };
1059
- }
1060
- const entries = settingsEntries(options.items, options.items, options.onChange);
1061
- const initialChoice = options.initialChoice
1062
- ? entries.find((entry) => entry.id === options.initialChoice?.id)
1063
- : undefined;
1064
- let component;
1065
- await options.ctx.ui.custom((tui, theme, _keybindings, done) => {
1066
- component = new PiSettingsComponent({
1067
- title: options.title,
1068
- entries,
1069
- initialChoice,
1070
- theme: theme ?? {},
1071
- requestRender: () => tui.requestRender(),
1072
- notify: (message, level) => options.ctx?.ui?.notify?.(message, level),
1073
- done,
1074
- });
1075
- return component;
1076
- });
1077
- await component?.waitForWrites();
1078
- return component?.sessionResult() ?? { changed: false, configChanged: false, failed: false };
1079
- }
1080
- function freeflowStatusText(state, cognitiveRoutingController) {
1081
- if (!state.configured) {
1082
- return state.configExists
1083
- ? `Freeflow: inactive (invalid config: ${state.parseError ?? "unknown parse error"}); run /setup-freeflow or fix .freeflow/config.json`
1084
- : "Freeflow: inactive (repo not set up); run /setup-freeflow";
1085
- }
1086
- const sessionSuffix = (source) => (source === "session" ? " (session override)" : "");
1087
- const routingState = cognitiveRoutingController?.state();
1088
- const cognitiveRouting = state.cognitiveRouting;
1089
- const cognitiveRoutingStatus = cognitiveRouting
1090
- ? cognitiveRouting.blockingReason?.code === "runtime_disabled"
1091
- ? "unavailable (host unsupported)"
1092
- : cognitiveRouting.effective
1093
- ? routingState?.effective
1094
- ? `active (${routingState.activeProfile ?? "unknown"}, ${routingState.controlMode})`
1095
- : "effective (inactive)"
1096
- : cognitiveRouting.enabled
1097
- ? `blocked (${cognitiveRouting.blockingReason.code})`
1098
- : "disabled"
1099
- : undefined;
1100
- const contextEnabled = state.contextVirtualization?.effective || state.conversationHistory?.effective;
1101
- return [
1102
- `Freeflow: ${state.enabled ? "enabled" : "disabled"}${sessionSuffix(state.configSources.enabled)}`,
1103
- `context: ${contextEnabled ? "enabled" : "disabled"} (virtualization ${state.contextVirtualization?.effective ? "enabled" : "disabled"}, history ${state.conversationHistory?.effective ? "enabled" : "disabled"})`,
1104
- ...(cognitiveRoutingStatus ? [`cognitive routing: ${cognitiveRoutingStatus}`] : []),
1105
- ].join("; ");
1106
- }
1107
- const NON_TUI_SETTINGS_GUIDANCE =
1108
- "Freeflow settings require Pi TUI mode. Use /freeflow status to inspect current state; supported non-TUI changes are /freeflow enable and /freeflow disable.";
1109
- function ensureSettingsIdle(ctx) {
1110
- if (typeof ctx?.isIdle !== "function" || ctx.isIdle()) return true;
1111
- ctx.ui?.notify?.("Freeflow settings and profile changes are available only while Pi is idle.", "warning");
1112
- return false;
1113
- }
1114
- function nonTuiGuidance(ctx, message) {
1115
- if (ctx?.hasUI === false) throw new Error(message);
1116
- ctx?.ui?.notify?.(message, "warning");
1117
- return { changed: false, reloaded: false, error: "tui_required" };
1118
- }
1119
- async function finalizeSettingsSession(
1120
- session,
1121
- ctx,
1122
- afterChange,
1123
- savedMessage,
1124
- reloadWarning = "Run /reload for Freeflow changes to fully apply.",
1125
- afterChangeOptions = {},
1126
- ) {
1127
- if (!session.configChanged) return false;
1128
- await afterChange(true, afterChangeOptions);
1129
- if (session.failed) return false;
1130
- ctx.ui.notify(savedMessage, "info");
1131
- if (typeof ctx.reload !== "function") {
1132
- ctx.ui.notify(reloadWarning, "warning");
1133
- return false;
1134
- }
1135
- await ctx.reload();
1136
- return true;
1137
- }
1138
- async function finalizeSessionSettings(session, ctx, afterChange) {
1139
- if (!session.changed) return false;
1140
- await afterChange(true);
1141
- if (session.failed) return false;
1142
- if (!session.configChanged) {
1143
- ctx.ui.notify("Freeflow session overrides updated.", "info");
1144
- return false;
1145
- }
1146
- ctx.ui.notify("Freeflow session overrides updated. Reloading skills and resources...", "info");
1147
- if (typeof ctx.reload !== "function") {
1148
- ctx.ui.notify("Run /reload for Freeflow session overrides to fully apply.", "warning");
1149
- return false;
1150
- }
1151
- await ctx.reload();
1152
- return true;
1153
- }
1154
- export async function handleFreeflowCommand(args, ctx, afterChange, pi, cognitiveRoutingController) {
1155
- const input = (args ?? "settings").trim().toLowerCase() || "settings";
1156
- const [action, ...rest] = input.split(/\s+/);
1157
- const actionValue = rest.join(" ");
1158
- const nonTui = ctx?.mode && ctx.mode !== "tui";
1159
- const settingsSelector =
1160
- action === "settings" &&
1161
- (!actionValue || ["session", "local", "personal", "repo", "repository", "shared"].includes(actionValue));
1162
- if (nonTui && settingsSelector) {
1163
- return nonTuiGuidance(ctx, NON_TUI_SETTINGS_GUIDANCE);
1164
- }
1165
- const [layers, state] = await Promise.all([
1166
- readFreeflowConfigLayers(ctx.cwd),
1167
- readCapabilityState(ctx.cwd, ctx, pi?.host),
1168
- ]);
1169
- const configState = layers.repository;
1170
- const raw = configState.valid ? configState.parsed : {};
1171
- if (action === "status") {
1172
- ctx.ui.notify(freeflowStatusText(state, cognitiveRoutingController), "info");
1173
- return { changed: false, reloaded: false };
1174
- }
1175
- if (!configState.valid) {
1176
- ctx.ui.notify(freeflowStatusText(state, cognitiveRoutingController), "warning");
1177
- return { changed: false, reloaded: false, error: "not_configured" };
1178
- }
1179
- if (layers.local.exists && !layers.local.valid) {
1180
- ctx.ui.notify(
1181
- `.freeflow/local.json is invalid; repair or remove it before changing Freeflow settings. ${layers.local.parseError ?? ""}`.trim(),
1182
- "warning",
1183
- );
1184
- return { changed: false, reloaded: false, error: "invalid_local_config" };
1185
- }
1186
- if (["enable", "on", "true", "disable", "off", "false"].includes(action)) {
1187
- if (!ensureSettingsIdle(ctx)) return { changed: false, reloaded: false, error: "busy" };
1188
- const enabled = ["enable", "on", "true"].includes(action);
1189
- const item = freeflowItems(raw, {
1190
- scope: "repository",
1191
- layers,
1192
- cognitiveRouting: state.cognitiveRouting,
1193
- ctx,
1194
- runtimeAvailable: isCognitiveRoutingRuntimeAvailable(pi),
1195
- }).find((candidate) => candidate.id === "freeflow.enabled");
1196
- await updateConfig(ctx.cwd, item, enabled, "repository");
1197
- await afterChange(true);
1198
- ctx.ui.notify(`Freeflow ${enabled ? "enabled" : "disabled"}. Reloading Freeflow runtime...`, "info");
1199
- if (typeof ctx.reload === "function") {
1200
- await ctx.reload();
1201
- return { changed: true, reloaded: true };
1202
- }
1203
- ctx.ui.notify("Run /reload for Freeflow changes to fully apply.", "warning");
1204
- return { changed: true, reloaded: false };
1205
- }
1206
- if (action && action !== "settings") {
1207
- ctx.ui.notify(
1208
- "Usage: /freeflow, /freeflow settings [local|repo], /freeflow status, /freeflow enable, or /freeflow disable",
1209
- "warning",
1210
- );
1211
- return { changed: false, reloaded: false, error: "invalid_action" };
1212
- }
1213
- let settingsScope = "local";
1214
- if (actionValue === "session") {
1215
- settingsScope = "session";
1216
- } else if (["repo", "repository", "shared"].includes(actionValue)) {
1217
- settingsScope = "repository";
1218
- } else if (actionValue && !["local", "personal"].includes(actionValue)) {
1219
- ctx.ui.notify(
1220
- "Usage: /freeflow settings, /freeflow settings session, /freeflow settings local, or /freeflow settings repo",
1221
- "warning",
1222
- );
1223
- return { changed: false, reloaded: false, error: "invalid_scope" };
1224
- }
1225
- if (!ensureSettingsIdle(ctx)) return { changed: false, reloaded: false, error: "busy" };
1226
- let reconcileCognitiveRouting = settingsScope === "session";
1227
- const items =
1228
- settingsScope === "session"
1229
- ? sessionFreeflowItems(state, cognitiveRoutingController, ctx)
1230
- : freeflowItems(raw, {
1231
- scope: settingsScope,
1232
- layers,
1233
- cognitiveRouting: state.cognitiveRouting,
1234
- ctx,
1235
- runtimeAvailable: isCognitiveRoutingRuntimeAvailable(pi),
1236
- });
1237
- const session = await openSettings({
1238
- title:
1239
- settingsScope === "session"
1240
- ? "Freeflow Settings · Session overrides"
1241
- : settingsScope === "local"
1242
- ? "Freeflow Settings · Personal overrides"
1243
- : "Freeflow Repository Settings · modifies .freeflow/config.json",
1244
- items,
1245
- ctx,
1246
- onChange: async (item, value) => {
1247
- if (!ensureSettingsIdle(ctx)) return { changed: false, reloadRequired: false };
1248
- if (!isCognitiveRoutingRuntimeAvailable(pi) && item.id.startsWith("freeflow.cognitiveRouting.")) {
1249
- ctx.ui.notify("Cognitive Routing is unavailable because this host lacks model-state controls.", "warning");
1250
- return { changed: false, reloadRequired: false };
1251
- }
1252
- if (item.id === "freeflow.cognitiveRouting.profile") {
1253
- if (!cognitiveRoutingController) {
1254
- ctx.ui.notify("Cognitive Routing is unavailable for this session.", "warning");
1255
- return { changed: false, reloadRequired: false };
1256
- }
1257
- const result =
1258
- value === "auto"
1259
- ? await cognitiveRoutingController.setAutomaticControl("profile-settings")
1260
- : await cognitiveRoutingController.setManualProfile(value, "profile-settings");
1261
- if ((result.status !== "automatic" && result.status !== "active") || result.reason) {
1262
- ctx.ui.notify(
1263
- `Cognitive Routing settings could not be applied: ${result.reason ?? result.status}.`,
1264
- "warning",
1265
- );
1266
- return { changed: false, reloadRequired: false };
1267
- }
1268
- await afterChange(false);
1269
- return { changed: true, reloadRequired: false };
1270
- }
1271
- if (item.id === "freeflow.session.reset") {
1272
- const routingResult = cognitiveRoutingController
1273
- ? await cognitiveRoutingController.resetSessionProfileOverrides("Reset session overrides")
1274
- : { status: "unchanged" };
1275
- if (routingResult.status === "blocked" || routingResult.reason) {
1276
- ctx.ui.notify(
1277
- `Cognitive Routing session presets could not be reset: ${routingResult.reason ?? routingResult.status}.`,
1278
- "warning",
1279
- );
1280
- return { changed: false, reloadRequired: false };
1281
- }
1282
- try {
1283
- const result = await resetSessionOverrides(ctx, pi);
1284
- return {
1285
- changed: result.changed || routingResult.status !== "unchanged",
1286
- reloadRequired: result.reloadRequired,
1287
- };
1288
- } catch (error) {
1289
- ctx.ui.notify(
1290
- `Routing presets were reset, but core/context session overrides could not be reset: ${error instanceof Error ? error.message : String(error)}`,
1291
- "warning",
1292
- );
1293
- return {
1294
- changed: routingResult.status !== "unchanged",
1295
- reloadRequired: false,
1296
- };
1297
- }
1298
- }
1299
- if (item.configScope === "session" && isCognitiveRoutingProfileItem(item)) {
1300
- if (!cognitiveRoutingController) {
1301
- ctx.ui.notify("Cognitive Routing is unavailable for this session.", "warning");
1302
- return { changed: false, reloadRequired: false };
1303
- }
1304
- const profile = item.id.split(".").at(-1);
1305
- const override =
1306
- value === undefined || value === LOCAL_INHERIT
1307
- ? null
1308
- : {
1309
- provider: value.provider,
1310
- modelId: value.model,
1311
- thinking: value.thinking,
1312
- };
1313
- const result = await cognitiveRoutingController.setSessionProfileOverride(
1314
- profile,
1315
- override,
1316
- "Session profile settings",
1317
- );
1318
- if (result.status === "blocked" || result.reason) {
1319
- ctx.ui.notify(
1320
- `Cognitive Routing session preset could not be applied: ${result.reason ?? result.status}.`,
1321
- "warning",
1322
- );
1323
- return { changed: false, reloadRequired: false };
1324
- }
1325
- await afterChange(false);
1326
- return { changed: result.status !== "unchanged", reloadRequired: false };
1327
- }
1328
- if (item.configScope === "session") {
1329
- const keyById = {
1330
- "freeflow.enabled": "enabled",
1331
- "freeflow.contextVirtualization": "contextVirtualization",
1332
- "freeflow.conversationHistory": "conversationHistory",
1333
- };
1334
- const key = keyById[item.id];
1335
- const override = value === LOCAL_INHERIT ? null : value === "true";
1336
- const result = await setSessionCoreOverride(key, override, ctx, pi);
1337
- return { changed: result.changed, reloadRequired: result.reloadRequired === true };
1338
- }
1339
- await updateConfig(ctx.cwd, item, value, item.configScope ?? "repository");
1340
- if (!item.id.startsWith("freeflow.cognitiveRouting.sessionStart.")) {
1341
- reconcileCognitiveRouting = true;
1342
- }
1343
- return { changed: true, reloadRequired: true };
1344
- },
1345
- });
1346
- if (settingsScope === "session") {
1347
- const reloaded = await finalizeSessionSettings(session, ctx, afterChange);
1348
- return { changed: session.changed, reloaded, error: session.failed ? "write_failed" : undefined };
1349
- }
1350
- const savedTarget = settingsScope === "local" ? "personal overrides" : "repository settings";
1351
- const reloaded = await finalizeSettingsSession(
1352
- session,
1353
- ctx,
1354
- afterChange,
1355
- `Freeflow ${savedTarget} saved. Reloading Freeflow runtime...`,
1356
- "Run /reload for Freeflow changes to fully apply.",
1357
- { reconcileCognitiveRouting },
1358
- );
1359
- return { changed: session.changed, reloaded, error: session.failed ? "write_failed" : undefined };
1360
- }