@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,735 +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 FREEFLOW_CAPABILITY_SKILL_NAMES = ["cognitive-routing", "context-virtualization", "conversation-history"];
54
- export function freeflowSkillPath(skillName) {
55
- return fileURLToPath(new URL(`../../../skills/${skillName}/SKILL.md`, import.meta.url));
56
- }
57
- export function freeflowCapabilitySkillPath(skillName) {
58
- return fileURLToPath(new URL(`../../../capabilities/${skillName}/SKILL.md`, import.meta.url));
59
- }
60
- export function freeflowModelSkillPaths(capabilityState = undefined) {
61
- const paths = FREEFLOW_MODEL_SKILL_NAMES.map((skillName) => freeflowSkillPath(skillName));
62
- const capabilityStates = {
63
- "cognitive-routing": capabilityState?.cognitiveRouting,
64
- "context-virtualization": capabilityState?.contextVirtualization,
65
- "conversation-history": capabilityState?.conversationHistory,
66
- };
67
- for (const skillName of FREEFLOW_CAPABILITY_SKILL_NAMES) {
68
- if (capabilityStates[skillName]?.effective === true) {
69
- paths.push(freeflowCapabilitySkillPath(skillName));
70
- }
71
- }
72
- return paths;
73
- }
74
- const SESSION_OVERRIDES_ENTRY = "freeflow-session-overrides";
75
- const SESSION_CORE_KEYS = new Set(["enabled", "contextVirtualization", "conversationHistory"]);
76
- export const FREEFLOW_RUNTIME_STATE_MESSAGE_TYPE = "freeflow-runtime-state";
77
- export const COGNITIVE_ROUTING_RUNTIME_STATE_MESSAGE_TYPE = "freeflow-cognitive-routing-runtime-state";
78
- export const WORKFLOW_BOOTSTRAP_MESSAGE_TYPE = "freeflow-workflow-bootstrap";
79
- export const COGNITIVE_ROUTING_BOOTSTRAP_MESSAGE_TYPE = "freeflow-cognitive-routing-bootstrap";
80
- export const FREEFLOW_BOOTSTRAP_MESSAGE_TYPE = "freeflow-bootstrap";
81
- let runtimeContextCache = null;
82
- let currentSessionOverrides = {};
83
- export function isPromptAvailable(value) {
84
- return typeof value === "string" && value.trim().length > 0;
85
- }
86
- // pi-subagents stamps child system prompts with this tag before binding extensions.
87
- // Keeping detection at the prompt boundary avoids a process-global child flag.
88
- export const SUBAGENT_AGENT_TAG = /<active_agent\s+name="[^"]+"\s*\/>/;
89
- export const FREEFLOW_SUBAGENT_CAPABILITIES_DISABLED_MARKER = "<!-- freeflow-subagent-capabilities: disabled -->";
90
- const SUBAGENT_OPTIONAL_CAPABILITIES_MESSAGE = "Optional Freeflow capabilities are disabled for subagents.";
91
- export function isSubagentContext(context) {
92
- try {
93
- const systemPrompt = context?.getSystemPrompt?.();
94
- return (
95
- typeof systemPrompt === "string" &&
96
- (SUBAGENT_AGENT_TAG.test(systemPrompt) || systemPrompt.includes(FREEFLOW_SUBAGENT_CAPABILITIES_DISABLED_MARKER))
97
- );
98
- } catch {
99
- return false;
100
- }
101
- }
102
- function disableSubagentCapability(capability) {
103
- return {
104
- ...capability,
105
- enabled: false,
106
- effective: false,
107
- blockingReason: { code: "disabled", message: SUBAGENT_OPTIONAL_CAPABILITIES_MESSAGE },
108
- };
109
- }
110
- export function hasUsableMandatoryPrompts(freeflowContext) {
111
- return (
112
- isPromptAvailable(freeflowContext?.corePrompt) && isPromptAvailable(freeflowContext?.interactionContractPrompt)
113
- );
114
- }
115
- async function readPromptFile(url) {
116
- try {
117
- const prompt = await readFile(url, "utf8");
118
- return isPromptAvailable(prompt) ? prompt.trim() : null;
119
- } catch {
120
- return null;
121
- }
122
- }
123
- async function loadRuntimeContext(capabilityState = undefined) {
124
- const freeflowEnabled = capabilityState?.enabled === true;
125
- const contextVirtualizationEnabled = capabilityState?.contextVirtualization?.effective === true;
126
- const conversationHistoryEnabled = capabilityState?.conversationHistory?.effective === true;
127
- const cognitiveRoutingEnabled = capabilityState?.cognitiveRouting?.effective === true;
128
- const [
129
- corePrompt,
130
- interactionContractPrompt,
131
- cognitiveRoutingPrompt,
132
- contextVirtualizationPrompt,
133
- conversationHistoryPrompt,
134
- ] = await Promise.all([
135
- freeflowEnabled
136
- ? readPromptFile(new URL("../../../runtime/prompts/core.md", import.meta.url))
137
- : Promise.resolve(null),
138
- freeflowEnabled
139
- ? readPromptFile(new URL("../../../runtime/prompts/interaction-contract.md", import.meta.url))
140
- : Promise.resolve(null),
141
- cognitiveRoutingEnabled
142
- ? readPromptFile(new URL("../../../runtime/prompts/cognitive-routing.md", import.meta.url))
143
- : Promise.resolve(null),
144
- contextVirtualizationEnabled
145
- ? readPromptFile(new URL("../../../runtime/prompts/context-virtualization.md", import.meta.url))
146
- : Promise.resolve(null),
147
- conversationHistoryEnabled
148
- ? readPromptFile(new URL("../../../runtime/prompts/conversation-history.md", import.meta.url))
149
- : Promise.resolve(null),
150
- ]);
151
- return {
152
- corePrompt,
153
- interactionContractPrompt,
154
- cognitiveRoutingPrompt,
155
- contextVirtualizationPrompt,
156
- conversationHistoryPrompt,
157
- };
158
- }
159
- function runtimeContextCacheSatisfies(capabilityState) {
160
- if (!runtimeContextCache) return false;
161
- const expected = {
162
- corePrompt: capabilityState?.enabled === true,
163
- interactionContractPrompt: capabilityState?.enabled === true,
164
- cognitiveRoutingPrompt: capabilityState?.cognitiveRouting?.effective === true,
165
- contextVirtualizationPrompt: capabilityState?.contextVirtualization?.effective === true,
166
- conversationHistoryPrompt: capabilityState?.conversationHistory?.effective === true,
167
- };
168
- return Object.entries(expected).every(([key, required]) => !required || isPromptAvailable(runtimeContextCache[key]));
169
- }
170
- export async function refreshRuntimeContext(capabilityState = undefined) {
171
- runtimeContextCache = await loadRuntimeContext(capabilityState);
172
- return runtimeContextCache;
173
- }
174
- export async function getRuntimeContext(capabilityState = undefined) {
175
- if (runtimeContextCacheSatisfies(capabilityState)) {
176
- return runtimeContextCache;
177
- }
178
- return refreshRuntimeContext(capabilityState);
179
- }
180
- const BOOTSTRAP_COMPONENTS = Object.freeze({
181
- workflow: "workflow",
182
- cognitiveRouting: "cognitive-routing",
183
- });
184
- function bootstrapEntryComponents(entry) {
185
- const isCustomMessage = entry?.role === "custom" || entry?.type === "custom_message" || entry?.type === "custom";
186
- if (!isCustomMessage) return [];
187
- if (entry.customType === FREEFLOW_BOOTSTRAP_MESSAGE_TYPE) {
188
- if (Array.isArray(entry.details?.components)) return entry.details.components;
189
- return [
190
- ...(entry.content?.includes("<!-- freeflow-bootstrap:workflow -->") ? [BOOTSTRAP_COMPONENTS.workflow] : []),
191
- ...(entry.content?.includes("<!-- freeflow-bootstrap:cognitive-routing -->")
192
- ? [BOOTSTRAP_COMPONENTS.cognitiveRouting]
193
- : []),
194
- ];
195
- }
196
- if (entry.customType === WORKFLOW_BOOTSTRAP_MESSAGE_TYPE) {
197
- return [BOOTSTRAP_COMPONENTS.workflow];
198
- }
199
- if (entry.customType === COGNITIVE_ROUTING_BOOTSTRAP_MESSAGE_TYPE) {
200
- return [BOOTSTRAP_COMPONENTS.cognitiveRouting];
201
- }
202
- return [];
203
- }
204
- export function filterBootstrapMessage(message) {
205
- return bootstrapEntryComponents(message).length === 0 ? message : undefined;
206
- }
207
- function isRecord(value) {
208
- return typeof value === "object" && value !== null && !Array.isArray(value);
209
- }
210
- function validateCoreConfigFields(value) {
211
- if (value.enabled !== undefined && typeof value.enabled !== "boolean") {
212
- return "enabled must be a boolean";
213
- }
214
- if (value.contextVirtualization !== undefined && typeof value.contextVirtualization !== "boolean") {
215
- return "contextVirtualization must be a boolean";
216
- }
217
- if (value.conversationHistory !== undefined && typeof value.conversationHistory !== "boolean") {
218
- return "conversationHistory must be a boolean";
219
- }
220
- return null;
221
- }
222
- function validateFreeflowConfigShape(value) {
223
- if (!isRecord(value)) {
224
- return "config must be a JSON object";
225
- }
226
- // Keep retired capability keys shape-tolerated so existing repositories remain activated; runtime behavior ignores them.
227
- const allowedKeys = new Set([
228
- "enabled",
229
- "outputRouter",
230
- "observedRouting",
231
- "scriptTransform",
232
- "cognitiveRouting",
233
- "contextVirtualization",
234
- "conversationHistory",
235
- ]);
236
- for (const key of Object.keys(value)) {
237
- if (!allowedKeys.has(key)) {
238
- return `unsupported top-level config key: ${key}`;
239
- }
240
- }
241
- const coreError = validateCoreConfigFields(value);
242
- if (coreError) return coreError;
243
- for (const key of ["outputRouter", "observedRouting", "scriptTransform"]) {
244
- if (value[key] !== undefined && !isRecord(value[key])) {
245
- return `${key} must be an object`;
246
- }
247
- }
248
- return null;
249
- }
250
- function validateFreeflowLocalConfigShape(value) {
251
- if (!isRecord(value)) {
252
- return "local config must be a JSON object";
253
- }
254
- const allowedKeys = new Set([
255
- "enabled",
256
- "processing",
257
- "cognitiveRouting",
258
- "contextVirtualization",
259
- "conversationHistory",
260
- ]);
261
- for (const key of Object.keys(value)) {
262
- if (!allowedKeys.has(key)) {
263
- return `unsupported top-level local config key: ${key}`;
264
- }
265
- }
266
- return validateCoreConfigFields(value);
267
- }
268
- async function readConfigFileState(path, validate) {
269
- try {
270
- const raw = await readFile(path, "utf8");
271
- const parsed = JSON.parse(raw);
272
- const validationError = validate(parsed);
273
- if (validationError) {
274
- return {
275
- path,
276
- exists: true,
277
- valid: false,
278
- parsed: {},
279
- parseError: validationError,
280
- };
281
- }
282
- return { path, exists: true, valid: true, parsed, parseError: null };
283
- } catch (error) {
284
- const code = error && typeof error === "object" ? error.code : undefined;
285
- if (code === "ENOENT") {
286
- return {
287
- path,
288
- exists: false,
289
- valid: false,
290
- parsed: {},
291
- parseError: null,
292
- };
293
- }
294
- const message = error instanceof Error ? error.message : String(error);
295
- return {
296
- path,
297
- exists: true,
298
- valid: false,
299
- parsed: {},
300
- parseError: message,
301
- };
302
- }
303
- }
304
- export function readFreeflowConfigState(cwd) {
305
- return readConfigFileState(join(cwd, ".freeflow/config.json"), validateFreeflowConfigShape);
306
- }
307
- export function readFreeflowLocalConfigState(cwd) {
308
- return readConfigFileState(join(cwd, ".freeflow/local.json"), validateFreeflowLocalConfigShape);
309
- }
310
- export async function readFreeflowConfig(cwd) {
311
- const state = await readFreeflowConfigState(cwd);
312
- return state.valid ? state.parsed : {};
313
- }
314
- export async function readFreeflowLocalConfig(cwd) {
315
- const state = await readFreeflowLocalConfigState(cwd);
316
- return state.valid ? state.parsed : {};
317
- }
318
- function resolveLayeredValue(repository, local, key, fallback) {
319
- if (Object.hasOwn(local, key)) {
320
- return { value: local[key], source: "local" };
321
- }
322
- if (Object.hasOwn(repository, key)) {
323
- return { value: repository[key], source: "repository" };
324
- }
325
- return { value: fallback, source: "builtin" };
326
- }
327
- function resolveCoreConfig(repository, local) {
328
- const enabled = resolveLayeredValue(repository, local, "enabled", true);
329
- const contextVirtualization = resolveLayeredValue(repository, local, "contextVirtualization", false);
330
- const conversationHistory = resolveLayeredValue(repository, local, "conversationHistory", false);
331
- return {
332
- config: {
333
- enabled: enabled.value,
334
- contextVirtualization: contextVirtualization.value,
335
- conversationHistory: conversationHistory.value,
336
- },
337
- sources: {
338
- enabled: enabled.source,
339
- contextVirtualization: contextVirtualization.source,
340
- conversationHistory: conversationHistory.source,
341
- },
342
- };
343
- }
344
- function normalizeSessionOverrides(value) {
345
- if (!isRecord(value)) return {};
346
- const overrides = {};
347
- for (const key of SESSION_CORE_KEYS) {
348
- if (typeof value[key] === "boolean") {
349
- overrides[key] = value[key];
350
- }
351
- }
352
- return overrides;
353
- }
354
- function resolveSessionCoreConfig(layers) {
355
- const configured = layers.coreConfig;
356
- const sources = layers.sources;
357
- const enabled = currentSessionOverrides.enabled;
358
- const contextVirtualization = currentSessionOverrides.contextVirtualization;
359
- const conversationHistory = currentSessionOverrides.conversationHistory;
360
- return {
361
- config: {
362
- enabled: typeof enabled === "boolean" ? enabled : configured.enabled,
363
- contextVirtualization:
364
- typeof contextVirtualization === "boolean" ? contextVirtualization : configured.contextVirtualization,
365
- conversationHistory:
366
- typeof conversationHistory === "boolean" ? conversationHistory : configured.conversationHistory,
367
- },
368
- sources: {
369
- enabled: typeof enabled === "boolean" ? "session" : sources.enabled,
370
- contextVirtualization: typeof contextVirtualization === "boolean" ? "session" : sources.contextVirtualization,
371
- conversationHistory: typeof conversationHistory === "boolean" ? "session" : sources.conversationHistory,
372
- },
373
- };
374
- }
375
- export async function readFreeflowConfigLayers(cwd) {
376
- const [repository, local] = await Promise.all([readFreeflowConfigState(cwd), readFreeflowLocalConfigState(cwd)]);
377
- const repositoryConfig = repository.valid ? repository.parsed : {};
378
- const localConfig = local.valid ? local.parsed : {};
379
- const core = resolveCoreConfig(repositoryConfig, localConfig);
380
- const localValid = !local.exists || local.valid;
381
- const configured = repository.valid && localValid;
382
- let blockingState = null;
383
- if (!repository.valid) {
384
- blockingState = repository;
385
- } else if (local.exists && !local.valid) {
386
- blockingState = local;
387
- }
388
- return {
389
- configured,
390
- repositoryConfigured: repository.valid,
391
- repository,
392
- local,
393
- coreConfig: core.config,
394
- sources: core.sources,
395
- blockingConfigPath: blockingState?.path ?? null,
396
- parseError: blockingState?.parseError ?? null,
397
- };
398
- }
399
- export async function readCapabilityState(cwd, host = undefined, extensionHost = undefined) {
400
- const layers = await readFreeflowConfigLayers(cwd);
401
- const effectiveCore = resolveSessionCoreConfig(layers);
402
- const enabled = layers.configured && effectiveCore.config.enabled;
403
- const contextVirtualizationConfigEnabled = effectiveCore.config.contextVirtualization;
404
- const conversationHistoryConfigEnabled = effectiveCore.config.conversationHistory;
405
- const subagentContext = isSubagentContext(host);
406
- const hostSupportsCognitiveRouting = !subagentContext && supportsCognitiveRoutingModelRegistry(host);
407
- const configuredCognitiveRouting = await resolveCognitiveRoutingState(
408
- layers.repository.parsed,
409
- layers.local.parsed,
410
- hostSupportsCognitiveRouting ? host : undefined,
411
- );
412
- const disabledReason = enabled ? undefined : { code: "disabled", message: "Freeflow is disabled" };
413
- const childCapability = (configuredEnabled) => ({
414
- enabled: configuredEnabled,
415
- effective: enabled && configuredEnabled,
416
- ...(disabledReason ? { blockingReason: disabledReason } : {}),
417
- });
418
- const cognitiveRouting = enabled
419
- ? configuredCognitiveRouting
420
- : {
421
- ...configuredCognitiveRouting,
422
- enabled: false,
423
- effective: false,
424
- blockingReason: disabledReason,
425
- };
426
- const capabilityState = {
427
- configured: layers.configured,
428
- repositoryConfigured: layers.repositoryConfigured,
429
- configExists: layers.repository.exists,
430
- configValid: layers.configured,
431
- configPath: layers.blockingConfigPath ?? layers.repository.path,
432
- parseError: layers.parseError,
433
- localConfigExists: layers.local.exists,
434
- localConfigValid: !layers.local.exists || layers.local.valid,
435
- localConfigPath: layers.local.path,
436
- localConfigParseError: layers.local.parseError,
437
- configuredCoreConfig: layers.coreConfig,
438
- configuredSources: layers.sources,
439
- sessionOverrides: { ...currentSessionOverrides },
440
- configSources: effectiveCore.sources,
441
- enabled,
442
- contextVirtualization: childCapability(contextVirtualizationConfigEnabled),
443
- conversationHistory: childCapability(conversationHistoryConfigEnabled),
444
- hostSupportsCognitiveRouting,
445
- cognitiveRouting,
446
- };
447
- if (!subagentContext) return capabilityState;
448
- return {
449
- ...capabilityState,
450
- contextVirtualization: disableSubagentCapability(capabilityState.contextVirtualization),
451
- conversationHistory: disableSubagentCapability(capabilityState.conversationHistory),
452
- cognitiveRouting: disableSubagentCapability(capabilityState.cognitiveRouting),
453
- };
454
- }
455
- export const readRuntimeState = readCapabilityState;
456
- export function restoreSessionOverrides(ctx) {
457
- currentSessionOverrides = {};
458
- const entries = ctx.sessionManager?.getBranch?.() ?? ctx.sessionManager?.getEntries?.() ?? [];
459
- for (const entry of entries) {
460
- if (entry.type === "custom" && entry.customType === SESSION_OVERRIDES_ENTRY) {
461
- currentSessionOverrides = normalizeSessionOverrides(entry.data?.overrides);
462
- }
463
- }
464
- }
465
- export function setFreeflowStatus(
466
- ctx,
467
- capabilityState = undefined,
468
- cognitiveRoutingRuntime = undefined,
469
- freeflowContext = undefined,
470
- options = {},
471
- ) {
472
- if (capabilityState && !capabilityState.configured) {
473
- ctx.ui.setStatus("freeflow", capabilityState.configExists ? "freeflow: config error" : "freeflow: setup needed");
474
- return;
475
- }
476
- if (capabilityState && !capabilityState.enabled) {
477
- const source = capabilityState.configSources?.enabled === "session" ? " (session)" : "";
478
- ctx.ui.setStatus("freeflow", `freeflow: off${source}`);
479
- return;
480
- }
481
- if (capabilityState?.enabled === true && !hasUsableMandatoryPrompts(freeflowContext)) {
482
- ctx.ui.setStatus("freeflow", "freeflow: unavailable");
483
- return;
484
- }
485
- const active = [];
486
- const cognitiveRouting = capabilityState?.cognitiveRouting;
487
- const cognitiveRoutingInactive =
488
- cognitiveRouting?.enabled === true && cognitiveRoutingRuntime?.runtimeStatus === "inactive";
489
- const cognitiveRoutingBlocked =
490
- cognitiveRouting?.enabled === true &&
491
- (cognitiveRouting?.blockingReason?.code === "runtime_blocked" ||
492
- cognitiveRoutingRuntime?.runtimeStatus === "blocked");
493
- const cognitiveRoutingActive = cognitiveRouting?.effective === true && cognitiveRoutingRuntime?.effective === true;
494
- const startupSelectionSuppressesCognitiveRouting = options.startupSelectionSuppressed === true;
495
- if (cognitiveRoutingInactive) {
496
- active.push("cognitive inactive");
497
- } else if (cognitiveRoutingBlocked) {
498
- active.push(`cognitive blocked · ${cognitiveRoutingRuntime?.runtimeReason ?? "runtime_blocked"}`);
499
- } else if (cognitiveRoutingActive) {
500
- const profile = cognitiveRoutingRuntime.activeProfile;
501
- const control =
502
- cognitiveRoutingRuntime.controlMode === "manual-executor" ||
503
- cognitiveRoutingRuntime.controlMode === "manual-coordinator"
504
- ? "manual hold"
505
- : "automatic";
506
- active.push(`${profile} · ${control}`);
507
- } else if (cognitiveRouting?.enabled === true) {
508
- if (cognitiveRouting.blockingReason?.code === "runtime_disabled") {
509
- active.push("cognitive blocked · runtime_disabled");
510
- } else if (
511
- cognitiveRouting.effective === true &&
512
- cognitiveRoutingRuntime === undefined &&
513
- options.cognitiveRoutingStartupPending === true &&
514
- !startupSelectionSuppressesCognitiveRouting
515
- ) {
516
- const startupProfile =
517
- cognitiveRouting.sessionStart?.control === "manual"
518
- ? (cognitiveRouting.sessionStart.profile ?? "coordinator")
519
- : "coordinator";
520
- active.push(`${startupProfile} · pending`);
521
- } else {
522
- const reason =
523
- cognitiveRouting.effective === true
524
- ? (cognitiveRoutingRuntime?.blockingReason?.code ?? "runtime_inactive")
525
- : (cognitiveRouting.blockingReason?.code ?? "unavailable");
526
- active.push(`cognitive blocked · ${reason}`);
527
- }
528
- }
529
- if (capabilityState?.contextVirtualization?.effective || capabilityState?.conversationHistory?.effective) {
530
- active.push("context");
531
- }
532
- ctx.ui.setStatus("freeflow", `freeflow: ${active.length > 0 ? active.join(" · ") : "active"}`);
533
- }
534
- export function skillPrompt(skill, args) {
535
- const trimmed = args?.trim();
536
- return trimmed ? `/skill:${skill}\n\n${trimmed}` : `/skill:${skill}`;
537
- }
538
- function publicCognitiveRoutingControl(controlMode) {
539
- if (controlMode === "automatic") return "automatic";
540
- if (controlMode === "manual-executor" || controlMode === "manual-coordinator") return "manual";
541
- return "unavailable";
542
- }
543
- function publicCognitiveRoutingProfile(activeProfile, effective) {
544
- if (effective !== true) return "unavailable";
545
- return activeProfile === "executor" || activeProfile === "coordinator" ? activeProfile : "unavailable";
546
- }
547
- function publicCapabilityStatus(capability) {
548
- if (capability?.effective === true) return "active";
549
- if (!capability) return "unavailable";
550
- const blockingCode = capability.blockingReason?.code;
551
- if (blockingCode && blockingCode !== "disabled") return "unavailable";
552
- return "inactive";
553
- }
554
- function publicCognitiveRoutingStatus(capability, runtime) {
555
- if (runtime?.runtimeStatus === "inactive") return "inactive";
556
- return publicCapabilityStatus(capability);
557
- }
558
- function publicCognitiveRoutingProjectionMode(capability, runtime, projectionFailure) {
559
- if (capability?.projection !== true) return "disabled";
560
- if (capability?.effective !== true) return "unavailable";
561
- if (runtime?.controlMode === "manual-executor" || runtime?.controlMode === "manual-coordinator") {
562
- return "manual-bypass";
563
- }
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
- `- Projection: \`${projectionMode}\``,
616
- ].join("\n"),
617
- display: false,
618
- details: { source: "provider-request-runtime-state" },
619
- };
620
- }
621
- export function withoutFreeflowRuntimeState(messages) {
622
- return (Array.isArray(messages) ? messages : []).filter(
623
- (message) =>
624
- message?.customType !== FREEFLOW_RUNTIME_STATE_MESSAGE_TYPE &&
625
- message?.customType !== COGNITIVE_ROUTING_RUNTIME_STATE_MESSAGE_TYPE,
626
- );
627
- }
628
- function lastUserMessageIndex(messages) {
629
- for (let index = messages.length - 1; index >= 0; index -= 1) {
630
- if (messages[index]?.role === "user") return index;
631
- }
632
- return -1;
633
- }
634
- function insertRuntimeStateBeforeLatestUser(messages, runtimeState) {
635
- const latestUserIndex = lastUserMessageIndex(messages);
636
- if (latestUserIndex < 0) return [...messages, runtimeState];
637
- return [...messages.slice(0, latestUserIndex), runtimeState, ...messages.slice(latestUserIndex)];
638
- }
639
- export function withFreeflowRuntimeState(
640
- messages,
641
- capabilityState,
642
- cognitiveRoutingRuntime = undefined,
643
- freeflowContext = undefined,
644
- options = {},
645
- ) {
646
- const source = Array.isArray(messages) ? messages : [];
647
- const runtimeState = freeflowRuntimeStateMessage(capabilityState, cognitiveRoutingRuntime, freeflowContext, {
648
- projectionFailure: options.projectionFailure,
649
- });
650
- const runtimeStateMessages = source.filter(
651
- (message) =>
652
- message?.customType === FREEFLOW_RUNTIME_STATE_MESSAGE_TYPE ||
653
- message?.customType === COGNITIVE_ROUTING_RUNTIME_STATE_MESSAGE_TYPE,
654
- );
655
- const withoutRuntimeState = withoutFreeflowRuntimeState(source);
656
- const expectedRuntimeStateIndex = lastUserMessageIndex(withoutRuntimeState);
657
- const runtimeStateIndex = source.findIndex((message) => message?.customType === FREEFLOW_RUNTIME_STATE_MESSAGE_TYPE);
658
- const unchanged =
659
- options.force !== true &&
660
- runtimeStateMessages.length === 1 &&
661
- runtimeStateMessages[0]?.customType === FREEFLOW_RUNTIME_STATE_MESSAGE_TYPE &&
662
- runtimeStateMessages[0]?.content === runtimeState.content &&
663
- runtimeStateIndex === (expectedRuntimeStateIndex < 0 ? withoutRuntimeState.length : expectedRuntimeStateIndex);
664
- if (unchanged) return source;
665
- return insertRuntimeStateBeforeLatestUser(withoutRuntimeState, runtimeState);
666
- }
667
- export function runtimeContext(freeflowContext, capabilityState) {
668
- if (
669
- capabilityState?.configured !== true ||
670
- capabilityState?.enabled !== true ||
671
- !hasUsableMandatoryPrompts(freeflowContext)
672
- ) {
673
- return "";
674
- }
675
- const blocks = [freeflowContext.corePrompt.trim(), freeflowContext.interactionContractPrompt.trim()];
676
- if (
677
- capabilityState.cognitiveRouting?.effective === true &&
678
- isPromptAvailable(freeflowContext.cognitiveRoutingPrompt)
679
- ) {
680
- blocks.push(freeflowContext.cognitiveRoutingPrompt.trim());
681
- }
682
- if (
683
- capabilityState.contextVirtualization?.effective === true &&
684
- isPromptAvailable(freeflowContext.contextVirtualizationPrompt)
685
- ) {
686
- blocks.push(freeflowContext.contextVirtualizationPrompt.trim());
687
- }
688
- if (
689
- capabilityState.conversationHistory?.effective === true &&
690
- isPromptAvailable(freeflowContext.conversationHistoryPrompt)
691
- ) {
692
- blocks.push(freeflowContext.conversationHistoryPrompt.trim());
693
- }
694
- return blocks.filter(Boolean).join("\n\n");
695
- }
696
- export async function setSessionCoreOverride(key, value, ctx, pi) {
697
- if (!SESSION_CORE_KEYS.has(key)) {
698
- throw new Error(`Invalid Freeflow session override: ${String(key)}`);
699
- }
700
- if (value !== null && typeof value !== "boolean") {
701
- throw new Error(`Invalid Freeflow session override value for ${key}: ${String(value)}`);
702
- }
703
- const hasOverride = Object.hasOwn(currentSessionOverrides, key);
704
- if ((value === null && !hasOverride) || (value !== null && hasOverride && currentSessionOverrides[key] === value)) {
705
- return { changed: false, sessionOverrides: { ...currentSessionOverrides } };
706
- }
707
- const next = { ...currentSessionOverrides };
708
- if (value === null) {
709
- delete next[key];
710
- } else {
711
- next[key] = value;
712
- }
713
- currentSessionOverrides = next;
714
- pi?.appendEntry?.(SESSION_OVERRIDES_ENTRY, { overrides: { ...currentSessionOverrides } });
715
- return {
716
- changed: true,
717
- reloadRequired: key === "enabled",
718
- sessionOverrides: { ...currentSessionOverrides },
719
- capabilityState: await readCapabilityState(ctx.cwd, ctx, pi?.host),
720
- };
721
- }
722
- export async function resetSessionOverrides(ctx, pi) {
723
- const hadCoreOverrides = Object.keys(currentSessionOverrides).length > 0;
724
- const reloadRequired = Object.hasOwn(currentSessionOverrides, "enabled");
725
- if (hadCoreOverrides) {
726
- currentSessionOverrides = {};
727
- pi?.appendEntry?.(SESSION_OVERRIDES_ENTRY, { overrides: {} });
728
- }
729
- return {
730
- changed: hadCoreOverrides,
731
- reloadRequired,
732
- sessionOverrides: { ...currentSessionOverrides },
733
- capabilityState: await readCapabilityState(ctx.cwd, ctx, pi?.host),
734
- };
735
- }