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