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