@hassangameryt/freeflow 0.7.3 → 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 (276) 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 +26 -31
  7. package/capabilities/cognitive-routing/SKILL.md +106 -161
  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 +5 -2
  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/{session-sources/events.js → cognitive-routing/event-store.js} +103 -40
  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-v2 → cognitive-routing}/projection.js +229 -56
  29. package/pi-extension/dist/cognitive-routing/provenance.js +81 -0
  30. package/pi-extension/dist/cognitive-routing/runtime.js +396 -0
  31. package/pi-extension/dist/{cognitive-routing-v2 → cognitive-routing}/schemas.js +43 -7
  32. package/pi-extension/dist/cognitive-routing/session.js +221 -0
  33. package/pi-extension/dist/{session-sources → cognitive-routing}/sources.js +99 -85
  34. package/pi-extension/dist/{cognitive-routing-v2 → cognitive-routing}/state.js +37 -378
  35. package/pi-extension/dist/cognitive-routing/status.js +80 -0
  36. package/pi-extension/dist/{cognitive-routing-v2 → cognitive-routing}/tools.js +12 -12
  37. package/pi-extension/dist/{cognitive-routing-v2 → cognitive-routing}/types.js +5 -11
  38. package/pi-extension/dist/compaction/carry.js +191 -0
  39. package/pi-extension/dist/compaction/config.js +22 -0
  40. package/pi-extension/dist/compaction/controller.js +471 -0
  41. package/pi-extension/dist/compaction/harness.js +77 -0
  42. package/pi-extension/dist/compaction/results.js +158 -0
  43. package/pi-extension/dist/compaction/thresholds.js +35 -0
  44. package/pi-extension/dist/compaction/tool.js +57 -0
  45. package/pi-extension/dist/host/branch.js +13 -0
  46. package/pi-extension/dist/host/canonical.js +12 -0
  47. package/pi-extension/dist/host/catalog.js +77 -0
  48. package/pi-extension/dist/host/config.js +374 -0
  49. package/pi-extension/dist/host/projection-tags.js +60 -0
  50. package/pi-extension/dist/host/prompts.js +82 -0
  51. package/pi-extension/dist/{session-sources → host}/read-only-session.js +112 -1
  52. package/pi-extension/dist/{runtime → host}/request-history.js +121 -39
  53. package/pi-extension/dist/host/runtime-state.js +189 -0
  54. package/pi-extension/dist/{settings/settings-ui.js → host/settings/freeflow-command.js} +620 -410
  55. package/pi-extension/dist/{settings/settings-tui.js → host/settings/settings-view.js} +186 -73
  56. package/pi-extension/dist/host/staging.js +28 -0
  57. package/pi-extension/dist/host/status.js +101 -0
  58. package/pi-extension/dist/index.js +423 -173
  59. package/pi-extension/dist/provider-support/cache/anchor.js +21 -0
  60. package/pi-extension/dist/provider-support/cache/anthropic.js +102 -0
  61. package/pi-extension/dist/provider-support/cache/health.js +73 -0
  62. package/pi-extension/dist/provider-support/cache/index.js +58 -0
  63. package/pi-extension/dist/provider-support/cache/keepalive.js +210 -0
  64. package/pi-extension/dist/provider-support/cache/monitor.js +17 -0
  65. package/pi-extension/dist/provider-support/cache/openai-responses.js +48 -0
  66. package/pi-extension/dist/provider-support/effort.js +13 -0
  67. package/pi-extension/dist/provider-support/index.js +44 -3
  68. package/pi-extension/dist/provider-support/{astra → openai}/adapter.js +46 -29
  69. package/pi-extension/dist/provider-support/{astra → openai}/history.js +10 -8
  70. package/pi-extension/dist/provider-support/{astra → openai}/index.js +8 -4
  71. package/pi-extension/dist/provider-support/{astra → openai}/session-state.js +29 -38
  72. package/pi-extension/dist/provider-support/routes.js +17 -0
  73. package/pi-extension/dist/tool-execution/apply-patch/grammar.js +23 -0
  74. package/pi-extension/dist/tool-execution/apply-patch/match.js +38 -0
  75. package/pi-extension/dist/tool-execution/apply-patch/parser.js +177 -0
  76. package/pi-extension/dist/tool-execution/apply-patch/plan.js +201 -0
  77. package/pi-extension/dist/tool-execution/apply-patch/tool.js +84 -0
  78. package/pi-extension/dist/tool-execution/background.js +238 -0
  79. package/pi-extension/dist/tool-execution/bash-guard.js +23 -0
  80. package/pi-extension/dist/tool-execution/config.js +22 -0
  81. package/pi-extension/dist/tool-execution/edit-messages.js +120 -0
  82. package/pi-extension/dist/tool-execution/file-state.js +138 -0
  83. package/pi-extension/dist/tool-execution/file-tracking.js +143 -0
  84. package/pi-extension/dist/tool-execution/prompt.js +54 -0
  85. package/pi-extension/dist/tool-execution/tools.js +16 -0
  86. package/pi-extension/freeflow/README.md +9 -0
  87. package/plugin.json +1 -1
  88. package/runtime/prompts/cognitive-routing.md +4 -4
  89. package/runtime/prompts/core.md +22 -75
  90. package/runtime/prompts/interaction-contract.md +15 -8
  91. package/runtime/prompts/tool-execution.md +38 -0
  92. package/runtime/prompts/working-method.md +108 -0
  93. package/skills/action-selection/SKILL.md +39 -47
  94. package/skills/action-selection/references/trajectory-stalls.md +2 -0
  95. package/skills/bypass/SKILL.md +2 -2
  96. package/skills/commit-work/SKILL.md +31 -83
  97. package/skills/commit-work/references/git-state-edges.md +1 -1
  98. package/skills/commit-work/references/simple-push.md +2 -0
  99. package/skills/commit-work/references/staging-decisions.md +1 -1
  100. package/skills/decision-gate/SKILL.md +31 -50
  101. package/skills/design-for-depth/SKILL.md +44 -53
  102. package/skills/design-for-depth/references/design-pressure-signals.md +46 -144
  103. package/skills/design-for-depth/references/implementation-decisions.md +1 -1
  104. package/skills/design-for-depth/references/interface-design-loop.md +5 -36
  105. package/skills/design-for-depth/references/module-and-dependency-design.md +2 -32
  106. package/skills/design-for-depth/references/state-and-failure-boundaries.md +2 -13
  107. package/skills/diagnose-failure/SKILL.md +39 -24
  108. package/skills/diagnose-failure/references/diagnostic-loop-catalog.md +2 -0
  109. package/skills/diagnose-failure/references/flaky-and-performance-diagnosis.md +2 -2
  110. package/skills/discuss/SKILL.md +35 -11
  111. package/skills/discuss/references/discussion-continuity.md +7 -27
  112. package/skills/evaluate-skill/SKILL.md +49 -80
  113. package/skills/evaluate-skill/references/evaluation-definition-schema.md +35 -5
  114. package/skills/evaluate-skill/references/evaluation-design.md +14 -14
  115. package/skills/evaluate-skill/references/execution-and-evidence.md +26 -5
  116. package/skills/evaluate-skill/references/review-and-revision.md +3 -1
  117. package/skills/evaluate-skill/scripts/lib/definitions.mjs +49 -8
  118. package/skills/evaluate-skill/scripts/lib/pi.mjs +14 -7
  119. package/skills/evaluate-skill/scripts/lib/review.mjs +196 -0
  120. package/skills/evaluate-skill/scripts/lib/runner.mjs +45 -8
  121. package/skills/evaluate-skill/scripts/lib/sandbox.mjs +2 -0
  122. package/skills/evaluate-skill/scripts/lib/trials.mjs +103 -0
  123. package/skills/evaluate-skill/scripts/lib/view.mjs +67 -1
  124. package/skills/evaluate-skill/scripts/pi-command-tool.mjs +144 -0
  125. package/skills/evaluate-skill/scripts/pi-guard.mjs +30 -13
  126. package/skills/evaluate-skill/scripts/skill-eval.mjs +114 -34
  127. package/skills/execute-work/SKILL.md +41 -9
  128. package/skills/execute-work/references/code-practices.md +2 -0
  129. package/skills/execute-work/references/execute-work-edges.md +11 -1
  130. package/skills/handoff/SKILL.md +1 -1
  131. package/skills/handoff/references/handoff-templates.md +1 -1
  132. package/skills/review-artifact/SKILL.md +42 -41
  133. package/skills/review-artifact/references/adjudicate-artifact-review.md +1 -1
  134. package/skills/review-artifact/references/independent-artifact-reviewer-contract.md +1 -1
  135. package/skills/review-work/SKILL.md +38 -32
  136. package/skills/review-work/references/adjudicate-work-review.md +1 -1
  137. package/skills/review-work/references/independent-work-reviewer-contract.md +1 -1
  138. package/skills/review-work/references/security-risk-lens.md +2 -4
  139. package/skills/setup-freeflow/SKILL.md +3 -1
  140. package/skills/setup-freeflow/references/activation-contract.md +7 -13
  141. package/skills/setup-freeflow/references/host-setup.md +3 -3
  142. package/skills/track-work/SKILL.md +113 -161
  143. package/skills/track-work/references/working-record-format.md +189 -350
  144. package/skills/track-work/scripts/lib/document.mjs +62 -6
  145. package/skills/track-work/scripts/lib/format.mjs +16 -1
  146. package/skills/track-work/scripts/lib/store.mjs +9 -8
  147. package/skills/track-work/scripts/lib/transitions.mjs +79 -4
  148. package/skills/track-work/scripts/working-record.mjs +34 -12
  149. package/skills/verify-work/SKILL.md +29 -20
  150. package/skills/verify-work/references/browser-runtime-evidence.md +1 -5
  151. package/skills/verify-work/references/integration-evidence.md +2 -0
  152. package/skills/verify-work/references/performance-evidence.md +3 -1
  153. package/skills/verify-work/references/test-design.md +3 -1
  154. package/skills/workflow/SKILL.md +65 -21
  155. package/skills/workflow/references/domain-skill-composition.md +5 -3
  156. package/skills/write-docs/SKILL.md +83 -0
  157. package/skills/write-docs/references/documentation-shapes.md +119 -0
  158. package/skills/write-docs/scripts/docs-check.mjs +139 -0
  159. package/skills/write-plan/SKILL.md +40 -40
  160. package/skills/write-plan/references/plan-shapes.md +1 -1
  161. package/skills/write-skill/SKILL.md +107 -147
  162. package/skills/write-skill/references/activation-boundaries.md +2 -0
  163. package/skills/write-skill/references/agent-first-instructions.md +22 -10
  164. package/skills/write-skill/references/progressive-disclosure.md +4 -2
  165. package/skills/write-skill/references/skill-dependency-graphs.md +2 -0
  166. package/skills/write-skill/scripts/lib/similarity.mjs +56 -0
  167. package/skills/write-skill/scripts/skill-author.mjs +18 -2
  168. package/skills/write-spec/SKILL.md +34 -41
  169. package/skills/write-spec/references/artifact-standards.md +1 -1
  170. package/skills/write-spec/references/decision-records.md +2 -0
  171. package/skills/write-spec/references/spec-shapes.md +1 -1
  172. package/capabilities/context-virtualization/SKILL.md +0 -103
  173. package/capabilities/conversation-history/SKILL.md +0 -53
  174. package/hooks/tests/check-host-adapters.test.mjs +0 -82
  175. package/hooks/tests/check-runtime-context-hook.sh +0 -212
  176. package/pi-extension/dist/cognitive-routing-v2/runtime.js +0 -2181
  177. package/pi-extension/dist/context-virtualization/commands.js +0 -89
  178. package/pi-extension/dist/context-virtualization/projector.js +0 -42
  179. package/pi-extension/dist/context-virtualization/runtime.js +0 -378
  180. package/pi-extension/dist/context-virtualization/state.js +0 -57
  181. package/pi-extension/dist/context-virtualization/types.js +0 -10
  182. package/pi-extension/dist/conversation-history/passages.js +0 -66
  183. package/pi-extension/dist/conversation-history/ranking.js +0 -105
  184. package/pi-extension/dist/conversation-history/runtime.js +0 -226
  185. package/pi-extension/dist/conversation-history/search.js +0 -56
  186. package/pi-extension/dist/conversation-history/types.js +0 -1
  187. package/pi-extension/dist/freeflow-context/resolver.js +0 -120
  188. package/pi-extension/dist/freeflow-context/runtime.js +0 -80
  189. package/pi-extension/dist/freeflow-context/source-projector.js +0 -95
  190. package/pi-extension/dist/freeflow-context/tool.js +0 -314
  191. package/pi-extension/dist/freeflow-context/types.js +0 -12
  192. package/pi-extension/dist/freeflow-context/visibility.js +0 -28
  193. package/pi-extension/dist/integrations/mcp-config.js +0 -29
  194. package/pi-extension/dist/runtime/runtime-context.js +0 -754
  195. package/pi-extension/dist/runtime/runtime-identity.js +0 -5
  196. package/pi-extension/dist/session-sources/provenance.js +0 -32
  197. package/pi-extension/dist/ui/text-component.js +0 -57
  198. package/pi-extension/src/cognitive-routing-v2/budget.ts +0 -42
  199. package/pi-extension/src/cognitive-routing-v2/config.ts +0 -173
  200. package/pi-extension/src/cognitive-routing-v2/projection.ts +0 -375
  201. package/pi-extension/src/cognitive-routing-v2/render.ts +0 -277
  202. package/pi-extension/src/cognitive-routing-v2/runtime.ts +0 -2241
  203. package/pi-extension/src/cognitive-routing-v2/schemas.ts +0 -180
  204. package/pi-extension/src/cognitive-routing-v2/state.ts +0 -839
  205. package/pi-extension/src/cognitive-routing-v2/tools.ts +0 -62
  206. package/pi-extension/src/cognitive-routing-v2/types.ts +0 -254
  207. package/pi-extension/src/context-virtualization/commands.ts +0 -111
  208. package/pi-extension/src/context-virtualization/projector.ts +0 -62
  209. package/pi-extension/src/context-virtualization/runtime.ts +0 -428
  210. package/pi-extension/src/context-virtualization/state.ts +0 -79
  211. package/pi-extension/src/context-virtualization/types.ts +0 -92
  212. package/pi-extension/src/conversation-history/passages.ts +0 -81
  213. package/pi-extension/src/conversation-history/ranking.ts +0 -155
  214. package/pi-extension/src/conversation-history/runtime.ts +0 -250
  215. package/pi-extension/src/conversation-history/search.ts +0 -79
  216. package/pi-extension/src/conversation-history/types.ts +0 -31
  217. package/pi-extension/src/freeflow-context/resolver.ts +0 -139
  218. package/pi-extension/src/freeflow-context/runtime.ts +0 -100
  219. package/pi-extension/src/freeflow-context/source-projector.ts +0 -106
  220. package/pi-extension/src/freeflow-context/tool.ts +0 -366
  221. package/pi-extension/src/freeflow-context/types.ts +0 -70
  222. package/pi-extension/src/freeflow-context/visibility.ts +0 -53
  223. package/pi-extension/src/index.ts +0 -390
  224. package/pi-extension/src/integrations/mcp-config.ts +0 -32
  225. package/pi-extension/src/provider-support/astra/adapter.ts +0 -108
  226. package/pi-extension/src/provider-support/astra/history.ts +0 -145
  227. package/pi-extension/src/provider-support/astra/index.ts +0 -12
  228. package/pi-extension/src/provider-support/astra/session-state.ts +0 -113
  229. package/pi-extension/src/provider-support/index.ts +0 -5
  230. package/pi-extension/src/runtime/request-history.ts +0 -243
  231. package/pi-extension/src/runtime/runtime-context.ts +0 -860
  232. package/pi-extension/src/runtime/runtime-identity.ts +0 -8
  233. package/pi-extension/src/session-sources/events.ts +0 -230
  234. package/pi-extension/src/session-sources/provenance.ts +0 -39
  235. package/pi-extension/src/session-sources/read-only-session.ts +0 -170
  236. package/pi-extension/src/session-sources/sources.ts +0 -334
  237. package/pi-extension/src/settings/settings-tui.ts +0 -501
  238. package/pi-extension/src/settings/settings-ui.ts +0 -1652
  239. package/pi-extension/src/ui/text-component.ts +0 -66
  240. package/pi-extension/tests/cache-reuse/history.test.js +0 -117
  241. package/pi-extension/tests/cache-reuse/native.test.js +0 -91
  242. package/pi-extension/tests/cache-reuse/settings.test.js +0 -211
  243. package/pi-extension/tests/cognitive-routing-v2/communication.test.js +0 -577
  244. package/pi-extension/tests/cognitive-routing-v2/compaction-input.test.js +0 -183
  245. package/pi-extension/tests/cognitive-routing-v2/delegation.test.js +0 -557
  246. package/pi-extension/tests/cognitive-routing-v2/native.test.js +0 -474
  247. package/pi-extension/tests/cognitive-routing-v2/performance.test.js +0 -87
  248. package/pi-extension/tests/cognitive-routing-v2/persistence.test.js +0 -300
  249. package/pi-extension/tests/cognitive-routing-v2/projection.test.js +0 -241
  250. package/pi-extension/tests/cognitive-routing-v2/recovery.test.js +0 -1034
  251. package/pi-extension/tests/cognitive-routing-v2/render.test.js +0 -244
  252. package/pi-extension/tests/cognitive-routing-v2/runtime.test.js +0 -423
  253. package/pi-extension/tests/cognitive-routing-v2/stabilization.test.js +0 -521
  254. package/pi-extension/tests/cognitive-routing-v2/state.test.js +0 -586
  255. package/pi-extension/tests/context-virtualization/extension.test.js +0 -775
  256. package/pi-extension/tests/context-virtualization/projector.test.js +0 -110
  257. package/pi-extension/tests/context-virtualization/runtime.test.js +0 -230
  258. package/pi-extension/tests/conversation-history/runtime.test.js +0 -98
  259. package/pi-extension/tests/conversation-history/search.test.js +0 -97
  260. package/pi-extension/tests/fixtures/pi-host.js +0 -4
  261. package/pi-extension/tests/fixtures/routing-native.js +0 -191
  262. package/pi-extension/tests/integration/mode-free-core.test.js +0 -220
  263. package/pi-extension/tests/integration/pi-extension.test.js +0 -1447
  264. package/pi-extension/tests/integration/prompt-architecture.test.js +0 -447
  265. package/pi-extension/tests/integration/unaffected-regressions.test.js +0 -478
  266. package/pi-extension/tests/provider-support/astra-boundaries.test.js +0 -75
  267. package/pi-extension/tests/provider-support/astra.test.js +0 -306
  268. package/pi-extension/tests/provider-support/cli.test.js +0 -92
  269. package/pi-extension/tests/provider-support/native.test.js +0 -183
  270. package/pi-extension/tests/settings/settings-tui.test.js +0 -243
  271. package/pi-extension/tsconfig.json +0 -16
  272. package/runtime/prompts/context-virtualization.md +0 -3
  273. package/runtime/prompts/conversation-history.md +0 -3
  274. package/skills/design-for-depth/references/software-design-philosophy.md +0 -202
  275. /package/pi-extension/dist/{cognitive-routing-v2 → cognitive-routing}/budget.js +0 -0
  276. /package/pi-extension/dist/{cognitive-routing-v2 → cognitive-routing}/render.js +0 -0
@@ -1,754 +0,0 @@
1
- import { readFile } from "node:fs/promises";
2
- import { join } from "node:path";
3
- import { fileURLToPath } from "node:url";
4
- import { resolveCognitiveRoutingState } from "../cognitive-routing-v2/config.js";
5
- import { supportsCognitiveRoutingModelRegistry } from "../cognitive-routing-v2/config.js";
6
- export const WORKFLOW_COMMANDS = [
7
- { command: "discuss", skill: "discuss" },
8
- { command: "action-selection", skill: "action-selection" },
9
- { command: "track-work", skill: "track-work" },
10
- { command: "write-spec", skill: "write-spec" },
11
- { command: "review-artifact", skill: "review-artifact" },
12
- { command: "write-plan", skill: "write-plan" },
13
- { command: "execute-work", skill: "execute-work" },
14
- { command: "simplify-code", skill: "simplify-code" },
15
- { command: "migration-work", skill: "migration-work" },
16
- { command: "diagnose-failure", skill: "diagnose-failure" },
17
- { command: "verify-work", skill: "verify-work" },
18
- { command: "review-work", skill: "review-work" },
19
- { command: "commit-work", skill: "commit-work" },
20
- { command: "handoff", skill: "handoff" },
21
- { command: "finish-branch", skill: "finish-branch" },
22
- { command: "release-work", skill: "release-work" },
23
- { command: "launch-work", skill: "launch-work" },
24
- { command: "bypass", skill: "bypass" },
25
- ];
26
- export const CONTRIBUTOR_COMMANDS = ["setup-freeflow", "write-skill", "evaluate-skill"];
27
- export const FREEFLOW_MODEL_SKILL_NAMES = [
28
- "action-selection",
29
- "bypass",
30
- "commit-work",
31
- "decision-gate",
32
- "migration-work",
33
- "design-for-depth",
34
- "diagnose-failure",
35
- "discuss",
36
- "evaluate-skill",
37
- "execute-work",
38
- "finish-branch",
39
- "handoff",
40
- "release-work",
41
- "review-artifact",
42
- "review-work",
43
- "setup-freeflow",
44
- "launch-work",
45
- "simplify-code",
46
- "track-work",
47
- "verify-work",
48
- "workflow",
49
- "write-plan",
50
- "write-skill",
51
- "write-spec",
52
- ];
53
- export const STABLE_FREEFLOW_SURFACE = Object.freeze({
54
- enabled: true,
55
- cognitiveRouting: { effective: true },
56
- contextVirtualization: { effective: true },
57
- conversationHistory: { effective: true },
58
- });
59
- export const FREEFLOW_CAPABILITY_SKILL_NAMES = ["cognitive-routing", "context-virtualization", "conversation-history"];
60
- export function freeflowSkillPath(skillName) {
61
- return fileURLToPath(new URL(`../../../skills/${skillName}/SKILL.md`, import.meta.url));
62
- }
63
- export function freeflowCapabilitySkillPath(skillName) {
64
- return fileURLToPath(new URL(`../../../capabilities/${skillName}/SKILL.md`, import.meta.url));
65
- }
66
- export function freeflowModelSkillPaths(capabilityState = undefined) {
67
- const paths = FREEFLOW_MODEL_SKILL_NAMES.map((skillName) => freeflowSkillPath(skillName));
68
- const capabilityStates = {
69
- "cognitive-routing": capabilityState?.cognitiveRouting,
70
- "context-virtualization": capabilityState?.contextVirtualization,
71
- "conversation-history": capabilityState?.conversationHistory,
72
- };
73
- for (const skillName of FREEFLOW_CAPABILITY_SKILL_NAMES) {
74
- if (capabilityStates[skillName]?.effective === true) {
75
- paths.push(freeflowCapabilitySkillPath(skillName));
76
- }
77
- }
78
- return paths;
79
- }
80
- const SESSION_OVERRIDES_ENTRY = "freeflow-session-overrides";
81
- const SESSION_CORE_KEYS = new Set(["enabled", "contextVirtualization", "conversationHistory"]);
82
- export const FREEFLOW_RUNTIME_STATE_MESSAGE_TYPE = "freeflow-runtime-state";
83
- export const COGNITIVE_ROUTING_RUNTIME_STATE_MESSAGE_TYPE = "freeflow-cognitive-routing-runtime-state";
84
- export const WORKFLOW_BOOTSTRAP_MESSAGE_TYPE = "freeflow-workflow-bootstrap";
85
- export const COGNITIVE_ROUTING_BOOTSTRAP_MESSAGE_TYPE = "freeflow-cognitive-routing-bootstrap";
86
- export const FREEFLOW_BOOTSTRAP_MESSAGE_TYPE = "freeflow-bootstrap";
87
- let runtimeContextCache = null;
88
- let currentSessionOverrides = {};
89
- export function isPromptAvailable(value) {
90
- return typeof value === "string" && value.trim().length > 0;
91
- }
92
- // pi-subagents stamps child system prompts with this tag before binding extensions.
93
- // Keeping detection at the prompt boundary avoids a process-global child flag.
94
- export const SUBAGENT_AGENT_TAG = /<active_agent\s+name="[^"]+"\s*\/>/;
95
- export const FREEFLOW_SUBAGENT_CAPABILITIES_DISABLED_MARKER = "<!-- freeflow-subagent-capabilities: disabled -->";
96
- const SUBAGENT_OPTIONAL_CAPABILITIES_MESSAGE = "Optional Freeflow capabilities are disabled for subagents.";
97
- export function isSubagentContext(context) {
98
- try {
99
- const systemPrompt = context?.getSystemPrompt?.();
100
- return (
101
- typeof systemPrompt === "string" &&
102
- (SUBAGENT_AGENT_TAG.test(systemPrompt) || systemPrompt.includes(FREEFLOW_SUBAGENT_CAPABILITIES_DISABLED_MARKER))
103
- );
104
- } catch {
105
- return false;
106
- }
107
- }
108
- function disableSubagentCapability(capability) {
109
- return {
110
- ...capability,
111
- enabled: false,
112
- effective: false,
113
- blockingReason: { code: "disabled", message: SUBAGENT_OPTIONAL_CAPABILITIES_MESSAGE },
114
- };
115
- }
116
- export function hasUsableMandatoryPrompts(freeflowContext) {
117
- return (
118
- isPromptAvailable(freeflowContext?.corePrompt) && isPromptAvailable(freeflowContext?.interactionContractPrompt)
119
- );
120
- }
121
- async function readPromptFile(url) {
122
- try {
123
- const prompt = await readFile(url, "utf8");
124
- return isPromptAvailable(prompt) ? prompt.trim() : null;
125
- } catch {
126
- return null;
127
- }
128
- }
129
- async function loadRuntimeContext(capabilityState = undefined) {
130
- const freeflowEnabled = capabilityState?.enabled === true;
131
- const contextVirtualizationEnabled = capabilityState?.contextVirtualization?.effective === true;
132
- const conversationHistoryEnabled = capabilityState?.conversationHistory?.effective === true;
133
- const cognitiveRoutingEnabled = capabilityState?.cognitiveRouting?.effective === true;
134
- const [
135
- corePrompt,
136
- interactionContractPrompt,
137
- cognitiveRoutingPrompt,
138
- contextVirtualizationPrompt,
139
- conversationHistoryPrompt,
140
- ] = await Promise.all([
141
- freeflowEnabled
142
- ? readPromptFile(new URL("../../../runtime/prompts/core.md", import.meta.url))
143
- : Promise.resolve(null),
144
- freeflowEnabled
145
- ? readPromptFile(new URL("../../../runtime/prompts/interaction-contract.md", import.meta.url))
146
- : Promise.resolve(null),
147
- cognitiveRoutingEnabled
148
- ? readPromptFile(new URL("../../../runtime/prompts/cognitive-routing.md", import.meta.url))
149
- : Promise.resolve(null),
150
- contextVirtualizationEnabled
151
- ? readPromptFile(new URL("../../../runtime/prompts/context-virtualization.md", import.meta.url))
152
- : Promise.resolve(null),
153
- conversationHistoryEnabled
154
- ? readPromptFile(new URL("../../../runtime/prompts/conversation-history.md", import.meta.url))
155
- : Promise.resolve(null),
156
- ]);
157
- return {
158
- corePrompt,
159
- interactionContractPrompt,
160
- cognitiveRoutingPrompt,
161
- contextVirtualizationPrompt,
162
- conversationHistoryPrompt,
163
- };
164
- }
165
- function runtimeContextCacheSatisfies(capabilityState) {
166
- if (!runtimeContextCache) return false;
167
- const expected = {
168
- corePrompt: capabilityState?.enabled === true,
169
- interactionContractPrompt: capabilityState?.enabled === true,
170
- cognitiveRoutingPrompt: capabilityState?.cognitiveRouting?.effective === true,
171
- contextVirtualizationPrompt: capabilityState?.contextVirtualization?.effective === true,
172
- conversationHistoryPrompt: capabilityState?.conversationHistory?.effective === true,
173
- };
174
- return Object.entries(expected).every(([key, required]) => !required || isPromptAvailable(runtimeContextCache[key]));
175
- }
176
- export async function refreshRuntimeContext(capabilityState = undefined) {
177
- runtimeContextCache = await loadRuntimeContext(capabilityState);
178
- return runtimeContextCache;
179
- }
180
- export async function getRuntimeContext(capabilityState = undefined) {
181
- if (runtimeContextCacheSatisfies(capabilityState)) {
182
- return runtimeContextCache;
183
- }
184
- return refreshRuntimeContext(capabilityState);
185
- }
186
- const BOOTSTRAP_COMPONENTS = Object.freeze({
187
- workflow: "workflow",
188
- cognitiveRouting: "cognitive-routing",
189
- });
190
- function bootstrapEntryComponents(entry) {
191
- const isCustomMessage = entry?.role === "custom" || entry?.type === "custom_message" || entry?.type === "custom";
192
- if (!isCustomMessage) return [];
193
- if (entry.customType === FREEFLOW_BOOTSTRAP_MESSAGE_TYPE) {
194
- if (Array.isArray(entry.details?.components)) return entry.details.components;
195
- return [
196
- ...(entry.content?.includes("<!-- freeflow-bootstrap:workflow -->") ? [BOOTSTRAP_COMPONENTS.workflow] : []),
197
- ...(entry.content?.includes("<!-- freeflow-bootstrap:cognitive-routing -->")
198
- ? [BOOTSTRAP_COMPONENTS.cognitiveRouting]
199
- : []),
200
- ];
201
- }
202
- if (entry.customType === WORKFLOW_BOOTSTRAP_MESSAGE_TYPE) {
203
- return [BOOTSTRAP_COMPONENTS.workflow];
204
- }
205
- if (entry.customType === COGNITIVE_ROUTING_BOOTSTRAP_MESSAGE_TYPE) {
206
- return [BOOTSTRAP_COMPONENTS.cognitiveRouting];
207
- }
208
- return [];
209
- }
210
- export function filterBootstrapMessage(message) {
211
- return bootstrapEntryComponents(message).length === 0 ? message : undefined;
212
- }
213
- function isRecord(value) {
214
- return typeof value === "object" && value !== null && !Array.isArray(value);
215
- }
216
- function validateCoreConfigFields(value) {
217
- if (value.enabled !== undefined && typeof value.enabled !== "boolean") {
218
- return "enabled must be a boolean";
219
- }
220
- if (value.contextVirtualization !== undefined && typeof value.contextVirtualization !== "boolean") {
221
- return "contextVirtualization must be a boolean";
222
- }
223
- if (value.conversationHistory !== undefined && typeof value.conversationHistory !== "boolean") {
224
- return "conversationHistory must be a boolean";
225
- }
226
- return null;
227
- }
228
- function validateFreeflowConfigShape(value) {
229
- if (!isRecord(value)) {
230
- return "config must be a JSON object";
231
- }
232
- // Keep retired capability keys shape-tolerated so existing repositories remain activated; runtime behavior ignores them.
233
- const allowedKeys = new Set([
234
- "enabled",
235
- "outputRouter",
236
- "observedRouting",
237
- "scriptTransform",
238
- "cognitiveRouting",
239
- "contextVirtualization",
240
- "conversationHistory",
241
- ]);
242
- for (const key of Object.keys(value)) {
243
- if (!allowedKeys.has(key)) {
244
- return `unsupported top-level config key: ${key}`;
245
- }
246
- }
247
- const coreError = validateCoreConfigFields(value);
248
- if (coreError) return coreError;
249
- for (const key of ["outputRouter", "observedRouting", "scriptTransform"]) {
250
- if (value[key] !== undefined && !isRecord(value[key])) {
251
- return `${key} must be an object`;
252
- }
253
- }
254
- return null;
255
- }
256
- function validateFreeflowLocalConfigShape(value) {
257
- if (!isRecord(value)) {
258
- return "local config must be a JSON object";
259
- }
260
- const allowedKeys = new Set([
261
- "enabled",
262
- "processing",
263
- "cognitiveRouting",
264
- "contextVirtualization",
265
- "conversationHistory",
266
- ]);
267
- for (const key of Object.keys(value)) {
268
- if (!allowedKeys.has(key)) {
269
- return `unsupported top-level local config key: ${key}`;
270
- }
271
- }
272
- return validateCoreConfigFields(value);
273
- }
274
- async function readConfigFileState(path, validate) {
275
- try {
276
- const raw = await readFile(path, "utf8");
277
- const parsed = JSON.parse(raw);
278
- const validationError = validate(parsed);
279
- if (validationError) {
280
- return {
281
- path,
282
- exists: true,
283
- valid: false,
284
- parsed: {},
285
- parseError: validationError,
286
- };
287
- }
288
- return { path, exists: true, valid: true, parsed, parseError: null };
289
- } catch (error) {
290
- const code = error && typeof error === "object" ? error.code : undefined;
291
- if (code === "ENOENT") {
292
- return {
293
- path,
294
- exists: false,
295
- valid: false,
296
- parsed: {},
297
- parseError: null,
298
- };
299
- }
300
- const message = error instanceof Error ? error.message : String(error);
301
- return {
302
- path,
303
- exists: true,
304
- valid: false,
305
- parsed: {},
306
- parseError: message,
307
- };
308
- }
309
- }
310
- export function readFreeflowConfigState(cwd) {
311
- return readConfigFileState(join(cwd, ".freeflow/config.json"), validateFreeflowConfigShape);
312
- }
313
- export function readFreeflowLocalConfigState(cwd) {
314
- return readConfigFileState(join(cwd, ".freeflow/local.json"), validateFreeflowLocalConfigShape);
315
- }
316
- export async function readFreeflowConfig(cwd) {
317
- const state = await readFreeflowConfigState(cwd);
318
- return state.valid ? state.parsed : {};
319
- }
320
- export async function readFreeflowLocalConfig(cwd) {
321
- const state = await readFreeflowLocalConfigState(cwd);
322
- return state.valid ? state.parsed : {};
323
- }
324
- function resolveLayeredValue(repository, local, key, fallback) {
325
- if (Object.hasOwn(local, key)) {
326
- return { value: local[key], source: "local" };
327
- }
328
- if (Object.hasOwn(repository, key)) {
329
- return { value: repository[key], source: "repository" };
330
- }
331
- return { value: fallback, source: "builtin" };
332
- }
333
- function resolveCoreConfig(repository, local) {
334
- const enabled = resolveLayeredValue(repository, local, "enabled", true);
335
- const contextVirtualization = resolveLayeredValue(repository, local, "contextVirtualization", false);
336
- const conversationHistory = resolveLayeredValue(repository, local, "conversationHistory", false);
337
- return {
338
- config: {
339
- enabled: enabled.value,
340
- contextVirtualization: contextVirtualization.value,
341
- conversationHistory: conversationHistory.value,
342
- },
343
- sources: {
344
- enabled: enabled.source,
345
- contextVirtualization: contextVirtualization.source,
346
- conversationHistory: conversationHistory.source,
347
- },
348
- };
349
- }
350
- function normalizeSessionOverrides(value) {
351
- if (!isRecord(value)) return {};
352
- const overrides = {};
353
- for (const key of SESSION_CORE_KEYS) {
354
- if (typeof value[key] === "boolean") {
355
- overrides[key] = value[key];
356
- }
357
- }
358
- return overrides;
359
- }
360
- function resolveSessionCoreConfig(layers) {
361
- const configured = layers.coreConfig;
362
- const sources = layers.sources;
363
- const enabled = currentSessionOverrides.enabled;
364
- const contextVirtualization = currentSessionOverrides.contextVirtualization;
365
- const conversationHistory = currentSessionOverrides.conversationHistory;
366
- return {
367
- config: {
368
- enabled: typeof enabled === "boolean" ? enabled : configured.enabled,
369
- contextVirtualization:
370
- typeof contextVirtualization === "boolean" ? contextVirtualization : configured.contextVirtualization,
371
- conversationHistory:
372
- typeof conversationHistory === "boolean" ? conversationHistory : configured.conversationHistory,
373
- },
374
- sources: {
375
- enabled: typeof enabled === "boolean" ? "session" : sources.enabled,
376
- contextVirtualization: typeof contextVirtualization === "boolean" ? "session" : sources.contextVirtualization,
377
- conversationHistory: typeof conversationHistory === "boolean" ? "session" : sources.conversationHistory,
378
- },
379
- };
380
- }
381
- export async function readFreeflowConfigLayers(cwd) {
382
- const [repository, local] = await Promise.all([readFreeflowConfigState(cwd), readFreeflowLocalConfigState(cwd)]);
383
- const repositoryConfig = repository.valid ? repository.parsed : {};
384
- const localConfig = local.valid ? local.parsed : {};
385
- const core = resolveCoreConfig(repositoryConfig, localConfig);
386
- const localValid = !local.exists || local.valid;
387
- const configured = repository.valid && localValid;
388
- let blockingState = null;
389
- if (!repository.valid) {
390
- blockingState = repository;
391
- } else if (local.exists && !local.valid) {
392
- blockingState = local;
393
- }
394
- return {
395
- configured,
396
- repositoryConfigured: repository.valid,
397
- repository,
398
- local,
399
- coreConfig: core.config,
400
- sources: core.sources,
401
- blockingConfigPath: blockingState?.path ?? null,
402
- parseError: blockingState?.parseError ?? null,
403
- };
404
- }
405
- export async function readCapabilityState(cwd, host = undefined, extensionHost = undefined) {
406
- const layers = await readFreeflowConfigLayers(cwd);
407
- const effectiveCore = resolveSessionCoreConfig(layers);
408
- const enabled = layers.configured && effectiveCore.config.enabled;
409
- const contextVirtualizationConfigEnabled = effectiveCore.config.contextVirtualization;
410
- const conversationHistoryConfigEnabled = effectiveCore.config.conversationHistory;
411
- const subagentContext = isSubagentContext(host);
412
- const hostSupportsCognitiveRouting = !subagentContext && supportsCognitiveRoutingModelRegistry(host);
413
- const configuredCognitiveRouting = await resolveCognitiveRoutingState(
414
- layers.repository.parsed,
415
- layers.local.parsed,
416
- hostSupportsCognitiveRouting ? host : undefined,
417
- );
418
- const disabledReason = enabled ? undefined : { code: "disabled", message: "Freeflow is disabled" };
419
- const childCapability = (configuredEnabled) => ({
420
- enabled: configuredEnabled,
421
- effective: enabled && configuredEnabled,
422
- ...(disabledReason ? { blockingReason: disabledReason } : {}),
423
- });
424
- const cognitiveRouting = enabled
425
- ? configuredCognitiveRouting
426
- : {
427
- ...configuredCognitiveRouting,
428
- enabled: false,
429
- effective: false,
430
- blockingReason: disabledReason,
431
- };
432
- const capabilityState = {
433
- configured: layers.configured,
434
- repositoryConfigured: layers.repositoryConfigured,
435
- configExists: layers.repository.exists,
436
- configValid: layers.configured,
437
- configPath: layers.blockingConfigPath ?? layers.repository.path,
438
- parseError: layers.parseError,
439
- localConfigExists: layers.local.exists,
440
- localConfigValid: !layers.local.exists || layers.local.valid,
441
- localConfigPath: layers.local.path,
442
- localConfigParseError: layers.local.parseError,
443
- configuredCoreConfig: layers.coreConfig,
444
- configuredSources: layers.sources,
445
- sessionOverrides: { ...currentSessionOverrides },
446
- configSources: effectiveCore.sources,
447
- enabled,
448
- contextVirtualization: childCapability(contextVirtualizationConfigEnabled),
449
- conversationHistory: childCapability(conversationHistoryConfigEnabled),
450
- hostSupportsCognitiveRouting,
451
- cognitiveRouting,
452
- };
453
- if (!subagentContext) return capabilityState;
454
- return {
455
- ...capabilityState,
456
- contextVirtualization: disableSubagentCapability(capabilityState.contextVirtualization),
457
- conversationHistory: disableSubagentCapability(capabilityState.conversationHistory),
458
- cognitiveRouting: disableSubagentCapability(capabilityState.cognitiveRouting),
459
- };
460
- }
461
- export const readRuntimeState = readCapabilityState;
462
- export function restoreSessionOverrides(ctx) {
463
- currentSessionOverrides = {};
464
- const entries = ctx.sessionManager?.getBranch?.() ?? ctx.sessionManager?.getEntries?.() ?? [];
465
- for (const entry of entries) {
466
- if (entry.type === "custom" && entry.customType === SESSION_OVERRIDES_ENTRY) {
467
- currentSessionOverrides = normalizeSessionOverrides(entry.data?.overrides);
468
- }
469
- }
470
- }
471
- export function setFreeflowStatus(
472
- ctx,
473
- capabilityState = undefined,
474
- cognitiveRoutingRuntime = undefined,
475
- freeflowContext = undefined,
476
- options = {},
477
- ) {
478
- if (capabilityState && !capabilityState.configured) {
479
- ctx.ui.setStatus("freeflow", capabilityState.configExists ? "freeflow: config error" : "freeflow: setup needed");
480
- return;
481
- }
482
- if (capabilityState && !capabilityState.enabled) {
483
- const source = capabilityState.configSources?.enabled === "session" ? " (session)" : "";
484
- ctx.ui.setStatus("freeflow", `freeflow: off${source}`);
485
- return;
486
- }
487
- if (capabilityState?.enabled === true && !hasUsableMandatoryPrompts(freeflowContext)) {
488
- ctx.ui.setStatus("freeflow", "freeflow: unavailable");
489
- return;
490
- }
491
- const active = [];
492
- const cognitiveRouting = capabilityState?.cognitiveRouting;
493
- const cognitiveRoutingInactive =
494
- cognitiveRouting?.enabled === true && cognitiveRoutingRuntime?.runtimeStatus === "inactive";
495
- const cognitiveRoutingBlocked =
496
- cognitiveRouting?.enabled === true &&
497
- (cognitiveRouting?.blockingReason?.code === "runtime_blocked" ||
498
- cognitiveRoutingRuntime?.runtimeStatus === "blocked");
499
- const cognitiveRoutingActive = cognitiveRouting?.effective === true && cognitiveRoutingRuntime?.effective === true;
500
- const startupSelectionSuppressesCognitiveRouting = options.startupSelectionSuppressed === true;
501
- if (cognitiveRoutingInactive) {
502
- active.push("cognitive inactive");
503
- } else if (cognitiveRoutingBlocked) {
504
- active.push(`cognitive blocked · ${cognitiveRoutingRuntime?.runtimeReason ?? "runtime_blocked"}`);
505
- } else if (cognitiveRoutingActive) {
506
- const profile = cognitiveRoutingRuntime.activeProfile;
507
- const control = String(cognitiveRoutingRuntime.controlMode).startsWith("manual-") ? "manual hold" : "automatic";
508
- active.push(`${profile} · ${control}`);
509
- } else if (cognitiveRouting?.enabled === true) {
510
- if (cognitiveRouting.blockingReason?.code === "runtime_disabled") {
511
- active.push("cognitive blocked · runtime_disabled");
512
- } else if (
513
- cognitiveRouting.effective === true &&
514
- cognitiveRoutingRuntime === undefined &&
515
- options.cognitiveRoutingStartupPending === true &&
516
- !startupSelectionSuppressesCognitiveRouting
517
- ) {
518
- const startupProfile =
519
- cognitiveRouting.sessionStart?.control === "manual"
520
- ? (cognitiveRouting.sessionStart.profile ?? "coordinator")
521
- : "coordinator";
522
- active.push(`${startupProfile} · pending`);
523
- } else {
524
- const reason =
525
- cognitiveRouting.effective === true
526
- ? (cognitiveRoutingRuntime?.blockingReason?.code ?? "runtime_inactive")
527
- : (cognitiveRouting.blockingReason?.code ?? "unavailable");
528
- active.push(`cognitive blocked · ${reason}`);
529
- }
530
- }
531
- if (capabilityState?.contextVirtualization?.effective || capabilityState?.conversationHistory?.effective) {
532
- active.push("context");
533
- }
534
- ctx.ui.setStatus("freeflow", `freeflow: ${active.length > 0 ? active.join(" · ") : "active"}`);
535
- }
536
- export function skillPrompt(skill, args) {
537
- const trimmed = args?.trim();
538
- return trimmed ? `/skill:${skill}\n\n${trimmed}` : `/skill:${skill}`;
539
- }
540
- function publicCognitiveRoutingControl(controlMode) {
541
- if (controlMode === "automatic") return "automatic";
542
- if (["manual-helper", "manual-executor", "manual-coordinator"].includes(controlMode)) return "manual";
543
- return "unavailable";
544
- }
545
- function publicCognitiveRoutingProfile(activeProfile, effective) {
546
- if (effective !== true) return "unavailable";
547
- return ["helper", "executor", "coordinator"].includes(activeProfile) ? activeProfile : "unavailable";
548
- }
549
- function publicCapabilityStatus(capability) {
550
- if (capability?.effective === true) return "active";
551
- if (!capability) return "unavailable";
552
- const blockingCode = capability.blockingReason?.code;
553
- if (blockingCode && blockingCode !== "disabled") return "unavailable";
554
- return "inactive";
555
- }
556
- function publicCognitiveRoutingStatus(capability, runtime) {
557
- if (runtime?.runtimeStatus === "inactive") return "inactive";
558
- return publicCapabilityStatus(capability);
559
- }
560
- function publicCognitiveRoutingProjectionMode(capability, runtime, projectionFailure) {
561
- if (capability?.projection !== true) return "disabled";
562
- if (capability?.effective !== true) return "unavailable";
563
- if (String(runtime?.controlMode).startsWith("manual-")) return "manual-bypass";
564
- if (projectionFailure) return "blocked";
565
- if (runtime?.runtimeStatus === "inactive" || runtime?.runtimeStatus === "blocked") return "unavailable";
566
- if (runtime?.effective === true && runtime.controlMode === "automatic") return "enabled";
567
- return "pending";
568
- }
569
- export function freeflowRuntimeStateMessage(
570
- capabilityState,
571
- cognitiveRoutingRuntime = undefined,
572
- freeflowContext = undefined,
573
- options = {},
574
- ) {
575
- const cognitiveRoutingEffective = capabilityState?.cognitiveRouting?.effective === true;
576
- const profile = publicCognitiveRoutingProfile(
577
- cognitiveRoutingRuntime?.activeProfile,
578
- cognitiveRoutingEffective && cognitiveRoutingRuntime?.effective === true,
579
- );
580
- const control =
581
- profile === "unavailable" ? "unavailable" : publicCognitiveRoutingControl(cognitiveRoutingRuntime?.controlMode);
582
- const projectionMode = publicCognitiveRoutingProjectionMode(
583
- capabilityState?.cognitiveRouting,
584
- cognitiveRoutingRuntime,
585
- options.projectionFailure,
586
- );
587
- const mandatoryPromptAvailable = capabilityState?.enabled !== true || hasUsableMandatoryPrompts(freeflowContext);
588
- const freeflowStatus = capabilityState?.configured
589
- ? capabilityState.enabled
590
- ? mandatoryPromptAvailable
591
- ? "active"
592
- : "unavailable"
593
- : "inactive"
594
- : capabilityState?.configExists
595
- ? "config error"
596
- : "setup needed";
597
- return {
598
- role: "custom",
599
- customType: FREEFLOW_RUNTIME_STATE_MESSAGE_TYPE,
600
- content: [
601
- "# Freeflow Runtime State",
602
- "",
603
- "This is extension-generated runtime state. Use it to interpret the stable Freeflow guidance.",
604
- "",
605
- `Freeflow: ${freeflowStatus}`,
606
- "",
607
- "Capabilities:",
608
- `- Context Virtualization: ${publicCapabilityStatus(capabilityState?.contextVirtualization)}`,
609
- `- Conversation History: ${publicCapabilityStatus(capabilityState?.conversationHistory)}`,
610
- `- Cognitive Routing: ${publicCognitiveRoutingStatus(capabilityState?.cognitiveRouting, cognitiveRoutingRuntime)}`,
611
- "",
612
- "Cognitive Routing:",
613
- `- Control: \`${control}\``,
614
- `- Profile: \`${profile}\``,
615
- `- Delegation: \`${capabilityState?.cognitiveRouting?.delegation ?? "executor"}\``,
616
- `- Projection: \`${projectionMode}\``,
617
- ].join("\n"),
618
- display: false,
619
- details: { source: "provider-request-runtime-state" },
620
- };
621
- }
622
- export function withoutFreeflowRuntimeState(messages) {
623
- return (Array.isArray(messages) ? messages : []).filter(
624
- (message) =>
625
- message?.customType !== FREEFLOW_RUNTIME_STATE_MESSAGE_TYPE &&
626
- message?.customType !== COGNITIVE_ROUTING_RUNTIME_STATE_MESSAGE_TYPE,
627
- );
628
- }
629
- function lastUserMessageIndex(messages) {
630
- for (let index = messages.length - 1; index >= 0; index -= 1) {
631
- if (messages[index]?.role === "user") return index;
632
- }
633
- return -1;
634
- }
635
- function insertRuntimeStateBeforeLatestUser(messages, runtimeState) {
636
- const latestUserIndex = lastUserMessageIndex(messages);
637
- if (latestUserIndex < 0) return [...messages, runtimeState];
638
- return [...messages.slice(0, latestUserIndex), runtimeState, ...messages.slice(latestUserIndex)];
639
- }
640
- export function withFreeflowRuntimeState(
641
- messages,
642
- capabilityState,
643
- cognitiveRoutingRuntime = undefined,
644
- freeflowContext = undefined,
645
- options = {},
646
- ) {
647
- const source = Array.isArray(messages) ? messages : [];
648
- const runtimeState = freeflowRuntimeStateMessage(capabilityState, cognitiveRoutingRuntime, freeflowContext, {
649
- projectionFailure: options.projectionFailure,
650
- });
651
- const runtimeStateMessages = source.filter(
652
- (message) =>
653
- message?.customType === FREEFLOW_RUNTIME_STATE_MESSAGE_TYPE ||
654
- message?.customType === COGNITIVE_ROUTING_RUNTIME_STATE_MESSAGE_TYPE,
655
- );
656
- const withoutRuntimeState = withoutFreeflowRuntimeState(source);
657
- const expectedRuntimeStateIndex = lastUserMessageIndex(withoutRuntimeState);
658
- const runtimeStateIndex = source.findIndex((message) => message?.customType === FREEFLOW_RUNTIME_STATE_MESSAGE_TYPE);
659
- const unchanged =
660
- options.force !== true &&
661
- runtimeStateMessages.length === 1 &&
662
- runtimeStateMessages[0]?.customType === FREEFLOW_RUNTIME_STATE_MESSAGE_TYPE &&
663
- runtimeStateMessages[0]?.content === runtimeState.content &&
664
- runtimeStateIndex === (expectedRuntimeStateIndex < 0 ? withoutRuntimeState.length : expectedRuntimeStateIndex);
665
- if (unchanged) return source;
666
- return insertRuntimeStateBeforeLatestUser(withoutRuntimeState, runtimeState);
667
- }
668
- export function stableRuntimeContext(context) {
669
- const sections = [
670
- ["Freeflow core", context?.corePrompt],
671
- ["Freeflow core", context?.interactionContractPrompt],
672
- ["Cognitive Routing", context?.cognitiveRoutingPrompt],
673
- ["Context Virtualization", context?.contextVirtualizationPrompt],
674
- ["Conversation History", context?.conversationHistoryPrompt],
675
- ];
676
- return [
677
- "# Freeflow availability contract",
678
- "Freeflow keeps a fixed reference catalog of its instructions, skills, and tools to preserve prompt caching. Presence in this catalog does not mean a feature is active or an operation is permitted.",
679
- "Apply the following guidance and Freeflow skills only when the latest extension-generated Freeflow Runtime State marks the corresponding feature active. When Freeflow is inactive, unavailable, or not configured, its core and capability guidance is dormant; do not bootstrap or follow it merely because it is listed. Explicit user instructions retain their normal authority.",
680
- "For Cognitive Routing, follow the latest control/profile/responsibility snapshots on this branch. Earlier snapshots and notices are historical; they grant no current permission. Tool permissions are checked by the runtime, even though all definitions remain visible. Never call a disabled operation.",
681
- ...sections
682
- .filter(([, text]) => isPromptAvailable(text))
683
- .map(([feature, text]) => `## Reference guidance: ${feature}\n\n${text.trim()}`),
684
- ].join("\n\n");
685
- }
686
- export function runtimeContext(freeflowContext, capabilityState) {
687
- if (
688
- capabilityState?.configured !== true ||
689
- capabilityState?.enabled !== true ||
690
- !hasUsableMandatoryPrompts(freeflowContext)
691
- ) {
692
- return "";
693
- }
694
- const blocks = [freeflowContext.corePrompt.trim(), freeflowContext.interactionContractPrompt.trim()];
695
- if (
696
- capabilityState.cognitiveRouting?.effective === true &&
697
- isPromptAvailable(freeflowContext.cognitiveRoutingPrompt)
698
- ) {
699
- blocks.push(freeflowContext.cognitiveRoutingPrompt.trim());
700
- }
701
- if (
702
- capabilityState.contextVirtualization?.effective === true &&
703
- isPromptAvailable(freeflowContext.contextVirtualizationPrompt)
704
- ) {
705
- blocks.push(freeflowContext.contextVirtualizationPrompt.trim());
706
- }
707
- if (
708
- capabilityState.conversationHistory?.effective === true &&
709
- isPromptAvailable(freeflowContext.conversationHistoryPrompt)
710
- ) {
711
- blocks.push(freeflowContext.conversationHistoryPrompt.trim());
712
- }
713
- return blocks.filter(Boolean).join("\n\n");
714
- }
715
- export async function setSessionCoreOverride(key, value, ctx, pi) {
716
- if (!SESSION_CORE_KEYS.has(key)) {
717
- throw new Error(`Invalid Freeflow session override: ${String(key)}`);
718
- }
719
- if (value !== null && typeof value !== "boolean") {
720
- throw new Error(`Invalid Freeflow session override value for ${key}: ${String(value)}`);
721
- }
722
- const hasOverride = Object.hasOwn(currentSessionOverrides, key);
723
- if ((value === null && !hasOverride) || (value !== null && hasOverride && currentSessionOverrides[key] === value)) {
724
- return { changed: false, sessionOverrides: { ...currentSessionOverrides } };
725
- }
726
- const next = { ...currentSessionOverrides };
727
- if (value === null) {
728
- delete next[key];
729
- } else {
730
- next[key] = value;
731
- }
732
- currentSessionOverrides = next;
733
- pi?.appendEntry?.(SESSION_OVERRIDES_ENTRY, { overrides: { ...currentSessionOverrides } });
734
- return {
735
- changed: true,
736
- reloadRequired: key === "enabled",
737
- sessionOverrides: { ...currentSessionOverrides },
738
- capabilityState: await readCapabilityState(ctx.cwd, ctx, pi?.host),
739
- };
740
- }
741
- export async function resetSessionOverrides(ctx, pi) {
742
- const hadCoreOverrides = Object.keys(currentSessionOverrides).length > 0;
743
- const reloadRequired = Object.hasOwn(currentSessionOverrides, "enabled");
744
- if (hadCoreOverrides) {
745
- currentSessionOverrides = {};
746
- pi?.appendEntry?.(SESSION_OVERRIDES_ENTRY, { overrides: {} });
747
- }
748
- return {
749
- changed: hadCoreOverrides,
750
- reloadRequired,
751
- sessionOverrides: { ...currentSessionOverrides },
752
- capabilityState: await readCapabilityState(ctx.cwd, ctx, pi?.host),
753
- };
754
- }