@hassangameryt/freeflow 0.7.0 → 0.7.2

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 (136) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +2 -1
  3. package/.codex-plugin/plugin.json +2 -2
  4. package/.cursor-plugin/plugin.json +25 -0
  5. package/README.md +57 -26
  6. package/capabilities/cognitive-routing/SKILL.md +94 -311
  7. package/com.github.copilot/hooks/hooks.json +11 -0
  8. package/command-surface.json +7 -1
  9. package/gemini-extension.json +5 -0
  10. package/hooks/adapters/claude-session-start.mjs +16 -0
  11. package/hooks/adapters/codex-session-start.mjs +16 -0
  12. package/hooks/adapters/copilot-session-start.mjs +13 -0
  13. package/hooks/adapters/cursor-session-start.mjs +13 -0
  14. package/hooks/adapters/gemini-session-start.mjs +15 -0
  15. package/hooks/claude/hooks.json +18 -0
  16. package/hooks/codex/hooks.json +18 -0
  17. package/hooks/cursor/hooks.json +9 -0
  18. package/hooks/freeflow-runtime-context.mjs +3 -215
  19. package/hooks/hooks.json +4 -5
  20. package/hooks/shared/runtime-context.mjs +210 -0
  21. package/hooks/tests/check-host-adapters.test.mjs +82 -0
  22. package/hooks/tests/check-runtime-context-hook.sh +34 -3
  23. package/package.json +20 -6
  24. package/pi-extension/dist/cognitive-routing-v2/budget.js +42 -0
  25. package/pi-extension/dist/cognitive-routing-v2/config.js +120 -0
  26. package/pi-extension/dist/cognitive-routing-v2/projection.js +321 -0
  27. package/pi-extension/dist/cognitive-routing-v2/render.js +231 -0
  28. package/pi-extension/dist/cognitive-routing-v2/runtime.js +1585 -0
  29. package/pi-extension/dist/cognitive-routing-v2/schemas.js +107 -0
  30. package/pi-extension/dist/cognitive-routing-v2/state.js +612 -0
  31. package/pi-extension/dist/cognitive-routing-v2/tools.js +91 -0
  32. package/pi-extension/dist/cognitive-routing-v2/types.js +44 -0
  33. package/pi-extension/dist/freeflow-context/tool.js +5 -0
  34. package/pi-extension/dist/index.js +279 -624
  35. package/pi-extension/dist/runtime/runtime-context.js +63 -13
  36. package/pi-extension/dist/session-sources/events.js +195 -0
  37. package/pi-extension/dist/session-sources/read-only-session.js +148 -0
  38. package/pi-extension/dist/session-sources/sources.js +233 -0
  39. package/pi-extension/dist/settings/settings-ui.js +44 -117
  40. package/pi-extension/src/cognitive-routing-v2/budget.ts +42 -0
  41. package/pi-extension/src/cognitive-routing-v2/config.ts +143 -0
  42. package/pi-extension/src/cognitive-routing-v2/projection.ts +365 -0
  43. package/pi-extension/src/cognitive-routing-v2/render.ts +256 -0
  44. package/pi-extension/src/cognitive-routing-v2/runtime.ts +1634 -0
  45. package/pi-extension/src/cognitive-routing-v2/schemas.ts +109 -0
  46. package/pi-extension/src/cognitive-routing-v2/state.ts +622 -0
  47. package/pi-extension/src/cognitive-routing-v2/tools.ts +93 -0
  48. package/pi-extension/src/cognitive-routing-v2/types.ts +222 -0
  49. package/pi-extension/src/freeflow-context/tool.ts +5 -0
  50. package/pi-extension/src/index.ts +285 -674
  51. package/pi-extension/src/runtime/runtime-context.ts +75 -14
  52. package/pi-extension/src/session-sources/events.ts +208 -0
  53. package/pi-extension/src/session-sources/read-only-session.ts +170 -0
  54. package/pi-extension/src/session-sources/sources.ts +263 -0
  55. package/pi-extension/src/settings/settings-ui.ts +54 -131
  56. package/pi-extension/tests/cognitive-routing-v2/communication.test.js +484 -0
  57. package/pi-extension/tests/cognitive-routing-v2/compaction-input.test.js +183 -0
  58. package/pi-extension/tests/cognitive-routing-v2/native.test.js +441 -0
  59. package/pi-extension/tests/cognitive-routing-v2/performance.test.js +87 -0
  60. package/pi-extension/tests/cognitive-routing-v2/persistence.test.js +245 -0
  61. package/pi-extension/tests/cognitive-routing-v2/projection.test.js +241 -0
  62. package/pi-extension/tests/cognitive-routing-v2/recovery.test.js +236 -0
  63. package/pi-extension/tests/cognitive-routing-v2/render.test.js +230 -0
  64. package/pi-extension/tests/cognitive-routing-v2/runtime.test.js +153 -0
  65. package/pi-extension/tests/cognitive-routing-v2/stabilization.test.js +521 -0
  66. package/pi-extension/tests/cognitive-routing-v2/state.test.js +275 -0
  67. package/pi-extension/tests/context-virtualization/extension.test.js +16 -0
  68. package/pi-extension/tests/fixtures/routing-native.js +188 -0
  69. package/pi-extension/tests/integration/mode-free-core.test.js +3 -2
  70. package/pi-extension/tests/integration/pi-extension.test.js +154 -37
  71. package/pi-extension/tests/integration/prompt-architecture.test.js +87 -6
  72. package/pi-extension/tests/integration/unaffected-regressions.test.js +77 -10
  73. package/plugin.json +33 -0
  74. package/runtime/prompts/cognitive-routing.md +4 -5
  75. package/runtime/prompts/core.md +51 -45
  76. package/runtime/prompts/interaction-contract.md +5 -5
  77. package/skills/action-selection/SKILL.md +57 -97
  78. package/skills/design-for-depth/SKILL.md +58 -193
  79. package/skills/design-for-depth/references/implementation-decisions.md +76 -0
  80. package/skills/diagnose-failure/SKILL.md +64 -196
  81. package/skills/discuss/SKILL.md +64 -123
  82. package/skills/discuss/references/discussion-continuity.md +7 -3
  83. package/skills/execute-work/SKILL.md +69 -88
  84. package/skills/execute-work/references/execute-work-edges.md +9 -3
  85. package/skills/handoff/SKILL.md +44 -54
  86. package/skills/handoff/references/handoff-templates.md +15 -6
  87. package/skills/review-artifact/SKILL.md +80 -127
  88. package/skills/review-artifact/references/independent-artifact-reviewer-contract.md +1 -1
  89. package/skills/review-work/SKILL.md +65 -115
  90. package/skills/review-work/references/independent-work-reviewer-contract.md +1 -1
  91. package/skills/simplify-code/SKILL.md +47 -100
  92. package/skills/track-work/SKILL.md +128 -119
  93. package/skills/track-work/references/working-record-format.md +14 -2
  94. package/skills/verify-work/SKILL.md +58 -62
  95. package/skills/verify-work/references/integration-evidence.md +4 -2
  96. package/skills/verify-work/references/test-design.md +89 -0
  97. package/skills/workflow/SKILL.md +73 -119
  98. package/skills/write-plan/SKILL.md +46 -77
  99. package/skills/write-plan/references/plan-shapes.md +5 -5
  100. package/skills/write-spec/SKILL.md +51 -63
  101. package/skills/write-spec/references/artifact-standards.md +2 -2
  102. package/skills/write-spec/references/decision-records.md +3 -2
  103. package/skills/write-spec/references/spec-shapes.md +15 -0
  104. package/pi-extension/dist/cognitive-routing/commands.js +0 -96
  105. package/pi-extension/dist/cognitive-routing/config.js +0 -232
  106. package/pi-extension/dist/cognitive-routing/controller.js +0 -1292
  107. package/pi-extension/dist/cognitive-routing/history.js +0 -451
  108. package/pi-extension/dist/cognitive-routing/host.js +0 -188
  109. package/pi-extension/dist/cognitive-routing/pi-routing-session.js +0 -414
  110. package/pi-extension/dist/cognitive-routing/pi-session-control.js +0 -320
  111. package/pi-extension/dist/cognitive-routing/runtime.js +0 -43
  112. package/pi-extension/dist/cognitive-routing/tool.js +0 -212
  113. package/pi-extension/dist/cognitive-routing/types.js +0 -6
  114. package/pi-extension/src/cognitive-routing/commands.ts +0 -129
  115. package/pi-extension/src/cognitive-routing/config.ts +0 -303
  116. package/pi-extension/src/cognitive-routing/controller.ts +0 -1628
  117. package/pi-extension/src/cognitive-routing/history.ts +0 -650
  118. package/pi-extension/src/cognitive-routing/host.ts +0 -266
  119. package/pi-extension/src/cognitive-routing/pi-routing-session.ts +0 -538
  120. package/pi-extension/src/cognitive-routing/pi-session-control.ts +0 -444
  121. package/pi-extension/src/cognitive-routing/runtime.ts +0 -57
  122. package/pi-extension/src/cognitive-routing/tool.ts +0 -273
  123. package/pi-extension/src/cognitive-routing/types.ts +0 -89
  124. package/pi-extension/tests/cognitive-routing/commands.test.js +0 -134
  125. package/pi-extension/tests/cognitive-routing/controller.test.js +0 -1128
  126. package/pi-extension/tests/cognitive-routing/extension-lifecycle.test.js +0 -1142
  127. package/pi-extension/tests/cognitive-routing/history.test.js +0 -274
  128. package/pi-extension/tests/cognitive-routing/host-identity.test.js +0 -63
  129. package/pi-extension/tests/cognitive-routing/pi-normal-lifecycle.test.js +0 -434
  130. package/pi-extension/tests/cognitive-routing/pi-session-control.test.js +0 -174
  131. package/pi-extension/tests/cognitive-routing/pi-session-history.test.js +0 -91
  132. package/pi-extension/tests/cognitive-routing/profile-resolution.test.js +0 -279
  133. package/pi-extension/tests/cognitive-routing/tool.test.js +0 -230
  134. package/skills/tdd/SKILL.md +0 -143
  135. package/skills/tdd/references/test-design.md +0 -96
  136. /package/pi-extension/tests/{cognitive-routing/host-fixture.js → fixtures/pi-host.js} +0 -0
@@ -1,15 +1,5 @@
1
- import {
2
- COGNITIVE_ROUTING_CONTROL_ENTRY,
3
- COGNITIVE_ROUTING_INACTIVE_ENTRY,
4
- COGNITIVE_ROUTING_INTENT_ENTRY,
5
- } from "./cognitive-routing/controller.js";
6
- import { PiRoutingSession } from "./cognitive-routing/pi-routing-session.js";
7
- import {
8
- cognitiveRoutingProfileCompletions,
9
- handleCognitiveRoutingProfileCommand,
10
- } from "./cognitive-routing/commands.js";
11
- import { registerCognitiveRoutingHistoryTool, registerCognitiveRoutingTool } from "./cognitive-routing/tool.js";
12
- import { readCognitiveRoutingHistory } from "./cognitive-routing/history.js";
1
+ import { RoutingRuntime } from "./cognitive-routing-v2/runtime.js";
2
+ import { applyRoutingToolVisibility, registerRoutingTools } from "./cognitive-routing-v2/tools.js";
13
3
  import { ConversationHistoryRuntime } from "./conversation-history/runtime.js";
14
4
  import { FreeflowContextRuntime } from "./freeflow-context/runtime.js";
15
5
  import { CONTEXT_VIRTUALIZATION_TOOL_NAME, registerFreeflowContextTool } from "./freeflow-context/tool.js";
@@ -19,7 +9,6 @@ import { handleFreeflowCommand } from "./settings/settings-ui.js";
19
9
  import { isPiFlowHost } from "./runtime/runtime-identity.js";
20
10
  import {
21
11
  CONTRIBUTOR_COMMANDS,
22
- COGNITIVE_ROUTING_SWITCH_TOOL_NAME,
23
12
  WORKFLOW_COMMANDS,
24
13
  freeflowModelSkillPaths,
25
14
  freeflowSkillPath,
@@ -35,670 +24,336 @@ import {
35
24
  skillPrompt,
36
25
  withFreeflowRuntimeState,
37
26
  } from "./runtime/runtime-context.js";
38
- function unavailableCapability(capability, code, message) {
39
- return {
40
- ...capability,
41
- effective: false,
42
- blockingReason: { code, message },
43
- };
44
- }
45
- function modelFacingCapabilityState(
46
- capabilityState,
47
- freeflowContext,
48
- routingSnapshot,
49
- cognitiveRoutingActivationFailed = false,
50
- ) {
51
- const surfaceState = {
52
- ...capabilityState,
53
- contextVirtualization: { ...capabilityState?.contextVirtualization },
54
- conversationHistory: { ...capabilityState?.conversationHistory },
55
- cognitiveRouting: { ...capabilityState?.cognitiveRouting },
56
- };
57
- if (surfaceState.enabled !== true) return surfaceState;
58
- const markUnavailable = (key, message) => {
59
- if (surfaceState[key]?.effective === true) {
60
- surfaceState[key] = unavailableCapability(surfaceState[key], "unavailable", message);
61
- }
62
- };
63
- if (!hasUsableMandatoryPrompts(freeflowContext)) {
64
- for (const key of ["contextVirtualization", "conversationHistory", "cognitiveRouting"]) {
65
- markUnavailable(key, "Mandatory Freeflow prompt is unavailable.");
66
- }
67
- return surfaceState;
68
- }
69
- if (
70
- surfaceState.contextVirtualization?.effective === true &&
71
- !isPromptAvailable(freeflowContext.contextVirtualizationPrompt)
72
- ) {
73
- markUnavailable("contextVirtualization", "Context Virtualization prompt is unavailable.");
74
- }
75
- if (
76
- surfaceState.conversationHistory?.effective === true &&
77
- !isPromptAvailable(freeflowContext.conversationHistoryPrompt)
78
- ) {
79
- markUnavailable("conversationHistory", "Conversation History prompt is unavailable.");
80
- }
81
- if (surfaceState.cognitiveRouting?.effective === true) {
82
- const controllerState = routingSnapshot.runtimeState;
83
- if (routingSnapshot.disposition === "blocked") {
84
- surfaceState.cognitiveRouting = unavailableCapability(
85
- surfaceState.cognitiveRouting,
86
- "runtime_blocked",
87
- routingSnapshot.reason ?? "Cognitive Routing is blocked because its inactive state could not be persisted.",
88
- );
89
- } else if (routingSnapshot.startupSelectionSuppressed || routingSnapshot.disposition === "inactive") {
90
- surfaceState.cognitiveRouting = unavailableCapability(
91
- surfaceState.cognitiveRouting,
92
- "runtime_inactive",
93
- "Cognitive Routing is inactive because Pi owns the startup model or thinking level.",
94
- );
95
- } else if (controllerState?.runtimeStatus === "inactive") {
96
- surfaceState.cognitiveRouting = unavailableCapability(
97
- surfaceState.cognitiveRouting,
98
- "runtime_inactive",
99
- controllerState.runtimeReason ?? "Cognitive Routing is inactive because Pi owns the current model state.",
100
- );
101
- } else if (controllerState?.runtimeStatus === "blocked") {
102
- surfaceState.cognitiveRouting = unavailableCapability(
103
- surfaceState.cognitiveRouting,
104
- "runtime_blocked",
105
- controllerState.runtimeReason ?? "Cognitive Routing is blocked because its state is not proven.",
106
- );
107
- } else if (cognitiveRoutingActivationFailed || controllerState?.effective === false) {
108
- surfaceState.cognitiveRouting = unavailableCapability(
109
- surfaceState.cognitiveRouting,
110
- "unavailable",
111
- "Cognitive Routing could not activate for this session.",
112
- );
113
- } else if (!isPromptAvailable(freeflowContext.cognitiveRoutingPrompt)) {
114
- markUnavailable("cognitiveRouting", "Cognitive Routing prompt is unavailable.");
115
- }
116
- }
117
- return surfaceState;
118
- }
119
- function sessionHasConversationOrRoutingState(ctx) {
120
- try {
121
- const entries = ctx?.sessionManager?.getBranch?.() ?? ctx?.sessionManager?.getEntries?.() ?? [];
122
- if (!Array.isArray(entries)) return false;
123
- return entries.some((entry) => {
124
- if (!entry || typeof entry !== "object") return false;
125
- const record = entry;
126
- if (
127
- typeof record.type === "string" &&
128
- ["message", "custom_message", "compaction", "branch_summary"].includes(record.type)
129
- ) {
130
- return true;
131
- }
132
- return (
133
- record.type === "custom" &&
134
- (record.customType === COGNITIVE_ROUTING_INTENT_ENTRY ||
135
- record.customType === COGNITIVE_ROUTING_CONTROL_ENTRY ||
136
- record.customType === COGNITIVE_ROUTING_INACTIVE_ENTRY)
137
- );
138
- });
139
- } catch {
140
- return false;
141
- }
142
- }
143
- async function applyCapabilityToolVisibility(
144
- pi,
145
- ctx,
146
- capabilityState = undefined,
147
- routingSnapshot = {
148
- status: "available",
149
- disposition: "available",
150
- startupSelectionSuppressed: false,
151
- },
152
- ) {
153
- if (typeof pi?.setActiveTools !== "function" || typeof pi?.getAllTools !== "function") return;
154
- const state = capabilityState ?? (await readCapabilityState(ctx.cwd, ctx, pi?.host));
155
- const allToolNames = pi
156
- .getAllTools()
157
- .map((tool) => tool?.name)
158
- .filter(Boolean);
159
- const allToolNameSet = new Set(allToolNames);
160
- const currentActive = typeof pi.getActiveTools === "function" ? pi.getActiveTools() : undefined;
161
- const active = new Set(
162
- (Array.isArray(currentActive) ? currentActive : allToolNames).filter((name) => allToolNameSet.has(name)),
163
- );
164
- if (allToolNameSet.has(COGNITIVE_ROUTING_SWITCH_TOOL_NAME)) {
165
- const controllerState = routingSnapshot.runtimeState;
166
- const routingToolActive =
167
- state.cognitiveRouting?.effective === true &&
168
- controllerState?.effective === true &&
169
- controllerState.controlMode === "automatic";
170
- if (routingToolActive) active.add(COGNITIVE_ROUTING_SWITCH_TOOL_NAME);
171
- else active.delete(COGNITIVE_ROUTING_SWITCH_TOOL_NAME);
172
- }
173
- if (allToolNameSet.has(CONTEXT_VIRTUALIZATION_TOOL_NAME)) {
174
- if (state.contextVirtualization?.effective === true || state.conversationHistory?.effective === true) {
175
- active.add(CONTEXT_VIRTUALIZATION_TOOL_NAME);
176
- } else {
177
- active.delete(CONTEXT_VIRTUALIZATION_TOOL_NAME);
178
- }
179
- }
180
- pi.setActiveTools([...active]);
181
- }
182
- function disabledToolCall(toolName, capability) {
183
- const command = capability === "freeflow" ? "/freeflow settings" : `/${capability} settings`;
184
- return {
185
- block: true,
186
- reason: `${toolName} is disabled by Freeflow config. Configure ${capability} with ${command}.`,
187
- };
188
- }
189
- function freeflowCompletions(prefix, cognitiveRoutingAvailable = false) {
190
- const query = prefix ?? "";
191
- if (query.startsWith("settings ")) {
192
- const settingsQuery = query.slice("settings ".length);
193
- return [
194
- { value: "session", label: "session", description: "Override Freeflow for this Pi session" },
195
- { value: "local", label: "local", description: "Edit personal overrides for this repository" },
196
- { value: "repo", label: "repo", description: "Edit shared repository settings" },
197
- ]
198
- .filter((item) => item.value.startsWith(settingsQuery))
199
- .map((item) => ({ ...item, value: `settings ${item.value}` }));
200
- }
201
- if (cognitiveRoutingAvailable && query.startsWith("profile ")) {
202
- return cognitiveRoutingProfileCompletions(query.slice("profile ".length)).map((item) => ({
203
- ...item,
204
- value: `profile ${item.value}`,
205
- }));
206
- }
207
- if (query.startsWith("context ")) {
208
- const contextQuery = query.slice("context ".length);
209
- return [
210
- { value: "status", label: "status", description: "Show Freeflow Context state" },
211
- { value: "list", label: "list", description: "List archived context projections" },
212
- { value: "restore", label: "restore", description: "Restore one or more context references" },
213
- { value: "reset all", label: "reset all", description: "Reset projection decisions on the active branch" },
214
- ]
215
- .filter((item) => item.value.startsWith(contextQuery))
216
- .map((item) => ({ ...item, value: `context ${item.value}` }));
217
- }
218
- return [
219
- { value: "settings", label: "settings", description: "Open personal override settings" },
220
- { value: "status", label: "status", description: "Show effective Freeflow state" },
221
- { value: "context", label: "context", description: "Inspect Freeflow Context" },
222
- ...(cognitiveRoutingAvailable
223
- ? [{ value: "profile", label: "profile", description: "Hold or release Cognitive Routing profile control" }]
224
- : []),
225
- { value: "enable", label: "enable", description: "Enable Freeflow for this repository" },
226
- { value: "disable", label: "disable", description: "Disable Freeflow for this repository" },
227
- ].filter((item) => item.value.startsWith(query));
228
- }
229
- function bypassCompletions(prefix) {
230
- const query = prefix ?? "";
231
- return [
232
- { value: "next", label: "next", description: "Skip one optional step" },
233
- { value: "task", label: "task", description: "Reduce optional pressure for the current task" },
234
- ].filter((item) => item.value.startsWith(query));
235
- }
236
27
  async function sendSkillCommand(pi, ctx, skill, args) {
237
- const state = await readCapabilityState(ctx.cwd, ctx, pi?.host);
28
+ const state = await readCapabilityState(ctx.cwd, ctx, pi.host);
238
29
  if (skill === "setup-freeflow" && !state.configured) {
239
30
  await pi.sendUserMessage(skillPrompt(skill, args), { expandPromptTemplates: true });
240
31
  return;
241
32
  }
242
- if (!state.configured) {
243
- ctx.ui.notify("Freeflow is installed but this repo is not set up. Run /setup-freeflow first.", "warning");
244
- return;
245
- }
246
- if (!state.enabled) {
247
- ctx.ui.notify(
248
- "Freeflow is disabled for this repo. Use /freeflow enable or /freeflow settings to re-enable it.",
249
- "warning",
250
- );
33
+ if (!state.configured || !state.enabled) {
34
+ ctx.ui.notify("Run /setup-freeflow or enable Freeflow before dispatching this skill.", "warning");
251
35
  return;
252
36
  }
253
- const freeflowContext = await getRuntimeContext(state);
254
- if (!hasUsableMandatoryPrompts(freeflowContext)) {
37
+ const prompts = await getRuntimeContext(state);
38
+ if (!hasUsableMandatoryPrompts(prompts)) {
255
39
  ctx.ui.notify("Freeflow core prompts are unavailable; the requested skill cannot be dispatched.", "warning");
256
40
  return;
257
41
  }
258
42
  await pi.sendUserMessage(skillPrompt(skill, args), { expandPromptTemplates: true });
259
43
  }
44
+ function freeflowCompletions(prefix, routingAvailable) {
45
+ const query = prefix ?? "";
46
+ const choices = query.startsWith("settings ")
47
+ ? [
48
+ ["settings session", "session", "Override Freeflow for this Pi session"],
49
+ ["settings local", "local", "Edit personal overrides for this repository"],
50
+ ["settings repo", "repo", "Edit shared repository settings"],
51
+ ]
52
+ : query.startsWith("profile ") && routingAvailable
53
+ ? [
54
+ ["profile coordinator", "coordinator", "Hold Coordinator manually"],
55
+ ["profile executor", "executor", "Hold Executor manually"],
56
+ ["profile auto", "auto", "Return to automatic Coordinator reconciliation"],
57
+ ["profile history", "history", "Read routing observations"],
58
+ ]
59
+ : query.startsWith("context ")
60
+ ? [
61
+ ["context status", "status", "Show Freeflow Context state"],
62
+ ["context list", "list", "List archived context projections"],
63
+ ["context restore", "restore", "Restore one or more context references"],
64
+ ["context reset all", "reset all", "Reset projection decisions on the active branch"],
65
+ ]
66
+ : [
67
+ ["settings", "settings", "Open personal override settings"],
68
+ ["status", "status", "Show effective Freeflow state"],
69
+ ["context", "context", "Inspect Freeflow Context"],
70
+ ...(routingAvailable
71
+ ? [
72
+ ["profile", "profile", "Hold or release Cognitive Routing profile control"],
73
+ ["resume", "resume", "Resume the current saved routing responsibility"],
74
+ ]
75
+ : []),
76
+ ["enable", "enable", "Enable Freeflow for this repository"],
77
+ ["disable", "disable", "Disable Freeflow for this repository"],
78
+ ];
79
+ return choices
80
+ .filter(([value]) => value.startsWith(query))
81
+ .map(([value, label, description]) => ({ value, label, description }));
82
+ }
260
83
  export default function freeflow(pi) {
261
- // SAFETY: These helpers register complete Pi tool definitions but retain legacy structural typing for PiFlow compatibility.
262
- const toolRegistrar = pi;
263
- const routingSession = new PiRoutingSession({ pi, stockPi: !isPiFlowHost(pi?.host) });
264
- let latestCognitiveRoutingContext;
265
- let providerSurfaceSnapshot;
266
- let runtimeStateRefreshRequired = true;
267
- let freeflowContextRuntime;
268
- let contextVirtualizationRuntime;
269
- let conversationHistoryRuntime;
270
- const registerContextToolForState = (capabilityState) => {
84
+ const api = pi;
85
+ const routing = new RoutingRuntime(api);
86
+ let capability;
87
+ let prompts;
88
+ let context;
89
+ let virtualization;
90
+ let history;
91
+ let refreshState = true;
92
+ let sessionContext;
93
+ let surfaceGeneration = 0;
94
+ const unavailable = (state, message) => ({
95
+ ...state,
96
+ effective: false,
97
+ blockingReason: { code: "unavailable", message },
98
+ });
99
+ async function loadSurface(ctx) {
100
+ const generation = surfaceGeneration;
101
+ const next = await readCapabilityState(ctx.cwd, ctx, pi.host);
102
+ const loaded = await getRuntimeContext(next);
103
+ if (generation !== surfaceGeneration) throw new Error("Discarded surface preparation for a replaced session.");
104
+ if (!hasUsableMandatoryPrompts(loaded)) {
105
+ for (const key of ["cognitiveRouting", "contextVirtualization", "conversationHistory"])
106
+ next[key] = unavailable(next[key], "Mandatory Freeflow prompts are unavailable.");
107
+ }
108
+ if (next.cognitiveRouting.effective && !isPromptAvailable(loaded.cognitiveRoutingPrompt))
109
+ next.cognitiveRouting = unavailable(next.cognitiveRouting, "Routing bootstrap cue is unavailable.");
110
+ if (next.contextVirtualization.effective && !isPromptAvailable(loaded.contextVirtualizationPrompt))
111
+ next.contextVirtualization = unavailable(
112
+ next.contextVirtualization,
113
+ "Context Virtualization guidance is unavailable.",
114
+ );
115
+ if (next.conversationHistory.effective && !isPromptAvailable(loaded.conversationHistoryPrompt))
116
+ next.conversationHistory = unavailable(next.conversationHistory, "Conversation History guidance is unavailable.");
117
+ // The existing reduction engine is not the future Context Control port. Do not pretend
118
+ // its independent transform ordering has been qualified with the new projection.
119
+ if (
120
+ next.cognitiveRouting.effective &&
121
+ next.cognitiveRouting.projection &&
122
+ (next.contextVirtualization.effective || next.conversationHistory.effective)
123
+ )
124
+ next.cognitiveRouting = unavailable(
125
+ next.cognitiveRouting,
126
+ "New routing projection with legacy context transforms is not qualified. Disable that combination explicitly.",
127
+ );
128
+ if (next.cognitiveRouting.enabled && isPiFlowHost(pi.host))
129
+ next.cognitiveRouting = unavailable(
130
+ next.cognitiveRouting,
131
+ "The redesigned PiFlow adapter requires separate qualification.",
132
+ );
133
+ capability = next;
134
+ prompts = loaded;
135
+ sessionContext = ctx;
136
+ return next;
137
+ }
138
+ function contextTools() {
271
139
  registerFreeflowContextTool(
272
- toolRegistrar,
273
- () => contextVirtualizationRuntime,
274
- () => conversationHistoryRuntime,
140
+ api,
141
+ () => virtualization,
142
+ () => history,
275
143
  {
276
- contextVirtualization: capabilityState?.contextVirtualization?.effective === true,
277
- conversationHistory: capabilityState?.conversationHistory?.effective === true,
144
+ contextVirtualization: capability?.contextVirtualization?.effective === true,
145
+ conversationHistory: capability?.conversationHistory?.effective === true,
278
146
  },
279
147
  );
280
- };
281
- const buildProviderSurface = async (ctx, activateCognitiveRouting = false) => {
282
- const capabilityState = await readCapabilityState(ctx.cwd, ctx, pi?.host);
283
- const freeflowContext = await getRuntimeContext(capabilityState);
284
- const promptCapabilityState = modelFacingCapabilityState(
285
- capabilityState,
286
- freeflowContext,
287
- routingSession.snapshot(),
288
- );
289
- let activationAttempted = false;
290
- if (
291
- activateCognitiveRouting &&
292
- routingSession.canAutoActivate() &&
293
- (!routingSession.hasController() || promptCapabilityState.cognitiveRouting?.effective !== true)
294
- ) {
295
- activationAttempted = promptCapabilityState.cognitiveRouting?.effective === true;
296
- try {
297
- await routingSession.reconcileController(
298
- ctx,
299
- promptCapabilityState,
300
- routingSession.armed ? { ...routingSession.armed } : undefined,
301
- );
302
- if (routingSession.hasController()) {
303
- routingSession.clearArmed();
304
- if (routingSession.snapshot().status === "active") routingSession.markActive();
305
- }
306
- } catch {
307
- routingSession.clearController();
308
- }
148
+ if (api.getActiveTools && api.setActiveTools) {
149
+ const current = new Set(api.getActiveTools());
150
+ if (capability?.contextVirtualization?.effective || capability?.conversationHistory?.effective)
151
+ current.add(CONTEXT_VIRTUALIZATION_TOOL_NAME);
152
+ else current.delete(CONTEXT_VIRTUALIZATION_TOOL_NAME);
153
+ const next = [...current];
154
+ if (JSON.stringify(next) !== JSON.stringify(api.getActiveTools())) api.setActiveTools(next);
309
155
  }
310
- const surfaceCapabilityState = modelFacingCapabilityState(
311
- promptCapabilityState,
312
- freeflowContext,
313
- routingSession.snapshot(),
314
- activationAttempted && !routingSession.hasController(),
315
- );
316
- const routingSnapshot = routingSession.snapshot();
317
- return {
318
- capabilityState: surfaceCapabilityState,
319
- freeflowContext,
320
- cognitiveRoutingRuntime: routingSnapshot.runtimeState,
321
- configuredCapabilityState: capabilityState,
322
- };
323
- };
324
- const applyLiveCapabilityStateForSession = async (ctx, options = {}) => {
325
- providerSurfaceSnapshot = undefined;
326
- await routingSession.applyLiveCapabilityState(ctx, options);
327
- const capabilityState = await readCapabilityState(ctx.cwd, ctx, pi?.host);
328
- const freeflowContext = await getRuntimeContext(capabilityState);
329
- const surfaceCapabilityState = modelFacingCapabilityState(
330
- capabilityState,
331
- freeflowContext,
332
- routingSession.snapshot(),
333
- );
334
- const routingSnapshot = routingSession.snapshot();
335
- setFreeflowStatus(ctx, surfaceCapabilityState, routingSnapshot.runtimeState, freeflowContext, {
336
- startupSelectionSuppressed: routingSnapshot.startupSelectionSuppressed,
337
- });
338
- await applyCapabilityToolVisibility(pi, ctx, surfaceCapabilityState, routingSnapshot);
339
- registerContextToolForState(surfaceCapabilityState);
340
- };
341
- if (routingSession.supportsCognitiveRoutingRuntime()) {
342
- registerCognitiveRoutingTool(toolRegistrar, () => routingSession.controllerForTool());
343
- registerCognitiveRoutingHistoryTool(toolRegistrar, (options, context) => {
344
- return (
345
- routingSession.history(options) ??
346
- readCognitiveRoutingHistory(context ?? latestCognitiveRoutingContext, options)
347
- );
348
- });
349
156
  }
157
+ function status(ctx) {
158
+ applyRoutingToolVisibility(api, routing, capability?.cognitiveRouting?.effective === true);
159
+ setFreeflowStatus(ctx, capability, routing.state(), prompts);
160
+ }
161
+ async function update(ctx) {
162
+ const next = await loadSurface(ctx);
163
+ await routing.refresh(ctx, next.cognitiveRouting);
164
+ contextTools();
165
+ status(ctx);
166
+ refreshState = true;
167
+ }
168
+ registerRoutingTools(api, routing);
350
169
  registerFreeflowContextTool(
351
- toolRegistrar,
352
- () => contextVirtualizationRuntime,
353
- () => conversationHistoryRuntime,
170
+ api,
171
+ () => virtualization,
172
+ () => history,
354
173
  { contextVirtualization: false, conversationHistory: false },
355
174
  );
356
- if (routingSession.supportsCognitiveRoutingRuntime() && typeof pi.registerShortcut === "function") {
357
- pi.registerShortcut("ctrl+shift+r", {
358
- description: "Cycle the Cognitive Routing manual standard/reasoning hold",
359
- handler: async (ctx) => {
360
- if (typeof ctx?.isIdle === "function" && !ctx.isIdle()) {
361
- ctx.ui?.notify?.("Freeflow settings and profile changes are available only while Pi is idle.", "warning");
362
- return;
363
- }
364
- const armedCycle = routingSession.hasController() ? undefined : routingSession.cycleArmedManual();
365
- if (armedCycle) {
366
- routingSession.beginExplicitReactivation();
367
- ctx.ui?.notify?.(`Cognitive Routing manual hold set to ${armedCycle.target}.`, "info");
368
- await applyLiveCapabilityStateForSession(ctx, {
369
- reconcileCognitiveRouting: true,
370
- materializeCognitiveRouting: !isPiFlowHost(pi?.host),
371
- });
372
- return;
373
- }
374
- if (!routingSession.hasController()) {
375
- routingSession.beginExplicitReactivation();
376
- await applyLiveCapabilityStateForSession(ctx, { reconcileCognitiveRouting: true });
377
- }
378
- const state = routingSession.snapshot().runtimeState;
379
- if (!state) {
380
- ctx.ui?.notify?.("Cognitive Routing is unavailable for this session.", "warning");
381
- return;
382
- }
383
- const target = state.activeProfile === "reasoning" ? "standard" : "reasoning";
384
- const result = await routingSession.setManualProfile(target, "profile-shortcut");
385
- if (result.status === "active") {
386
- ctx.ui?.notify?.(`Cognitive Routing manual hold set to ${target}.`, "info");
387
- } else {
388
- ctx.ui?.notify?.(`Cognitive Routing could not set the manual profile: ${result.reason}.`, "warning");
389
- }
390
- await applyLiveCapabilityStateForSession(ctx);
391
- },
392
- });
393
- pi.registerShortcut("ctrl+shift+a", {
394
- description: "Set Cognitive Routing to automatic Reasoning control",
395
- handler: async (ctx) => {
396
- if (typeof ctx?.isIdle === "function" && !ctx.isIdle()) {
397
- ctx.ui?.notify?.("Freeflow settings and profile changes are available only while Pi is idle.", "warning");
398
- return;
399
- }
400
- const armedCycle = routingSession.hasController() ? undefined : routingSession.cycleArmedAutomatic();
401
- if (armedCycle) {
402
- if (!armedCycle.changed) {
403
- ctx.ui?.notify?.("Cognitive Routing automatic control active.", "info");
404
- return;
405
- }
406
- ctx.ui?.notify?.("Cognitive Routing automatic control active.", "info");
407
- routingSession.beginExplicitReactivation();
408
- await applyLiveCapabilityStateForSession(ctx, {
409
- reconcileCognitiveRouting: true,
410
- materializeCognitiveRouting: !isPiFlowHost(pi?.host),
411
- });
412
- return;
413
- }
414
- if (!routingSession.hasController()) {
415
- routingSession.beginExplicitReactivation();
416
- await applyLiveCapabilityStateForSession(ctx, { reconcileCognitiveRouting: true });
417
- }
418
- const result = await routingSession.setAutomaticControl("profile-shortcut");
419
- if (result.status === "automatic") {
420
- ctx.ui?.notify?.("Cognitive Routing automatic control active.", "info");
421
- } else {
422
- ctx.ui?.notify?.(`Cognitive Routing could not change control: ${result.reason}.`, "warning");
423
- }
424
- await applyLiveCapabilityStateForSession(ctx);
425
- },
426
- });
427
- }
428
- if (!isPiFlowHost(pi?.host) && routingSession.supportsCognitiveRoutingRuntime()) {
429
- pi.on("model_select", async (event, ctx) => {
430
- if (!routingSession.hasController()) {
431
- if (!routingSession.armed) return;
432
- routingSession.clearArmed();
433
- routingSession.observeArmedNativeChange(ctx, "Pi model selection");
434
- await applyLiveCapabilityStateForSession(ctx);
435
- return;
436
- }
437
- const result = await routingSession.observeNativeChange("Pi model selection", event?.source);
438
- if (result.status !== "ignored") {
439
- latestCognitiveRoutingContext = ctx;
440
- providerSurfaceSnapshot = undefined;
441
- await applyLiveCapabilityStateForSession(ctx);
442
- }
443
- });
444
- pi.on("thinking_level_select", async (_event, ctx) => {
445
- if (!routingSession.hasController()) {
446
- if (!routingSession.armed) return;
447
- routingSession.clearArmed();
448
- routingSession.observeArmedNativeChange(ctx, "Pi thinking-level selection");
449
- await applyLiveCapabilityStateForSession(ctx);
450
- return;
451
- }
452
- const result = await routingSession.observeNativeChange("Pi thinking-level selection");
453
- if (result.status !== "ignored") {
454
- latestCognitiveRoutingContext = ctx;
455
- providerSurfaceSnapshot = undefined;
456
- await applyLiveCapabilityStateForSession(ctx);
457
- }
458
- });
459
- }
460
175
  pi.on("resources_discover", async (event, ctx) => {
461
- const cwd = ctx?.cwd ?? event?.cwd ?? process.cwd();
462
- const snapshot =
463
- providerSurfaceSnapshot?.context === ctx
464
- ? providerSurfaceSnapshot.value
465
- : await buildProviderSurface(ctx ?? { cwd }, false);
466
- const state = snapshot.capabilityState;
467
- if (!state.configured) {
468
- return { skillPaths: [freeflowSkillPath("setup-freeflow")] };
469
- }
470
- if (!state.enabled || !hasUsableMandatoryPrompts(snapshot.freeflowContext)) {
471
- return { skillPaths: [] };
472
- }
473
- return { skillPaths: freeflowModelSkillPaths(state) };
176
+ const state = capability ?? (await loadSurface(ctx ?? { cwd: event?.cwd ?? process.cwd() }));
177
+ if (!state.configured) return { skillPaths: [freeflowSkillPath("setup-freeflow")] };
178
+ return { skillPaths: state.enabled && hasUsableMandatoryPrompts(prompts) ? freeflowModelSkillPaths(state) : [] };
474
179
  });
475
180
  pi.on("session_start", async (event, ctx) => {
476
- routingSession.resetForSession(ctx, event);
477
- latestCognitiveRoutingContext = ctx;
478
- providerSurfaceSnapshot = undefined;
479
- runtimeStateRefreshRequired = true;
181
+ const generation = ++surfaceGeneration;
182
+ routing.unbind();
183
+ capability = undefined;
184
+ prompts = undefined;
185
+ refreshState = true;
480
186
  restoreSessionOverrides(ctx);
481
- freeflowContextRuntime = new FreeflowContextRuntime(ctx);
482
- contextVirtualizationRuntime = new ContextVirtualizationRuntime(pi, ctx, freeflowContextRuntime);
483
- conversationHistoryRuntime = new ConversationHistoryRuntime(
187
+ const initial = await readCapabilityState(ctx.cwd, ctx, pi.host);
188
+ await refreshRuntimeContext(initial);
189
+ if (generation !== surfaceGeneration) return;
190
+ await loadSurface(ctx);
191
+ context = new FreeflowContextRuntime(ctx);
192
+ virtualization = new ContextVirtualizationRuntime(pi, ctx, context);
193
+ history = new ConversationHistoryRuntime(
484
194
  ctx,
485
- (entryId) => contextVirtualizationRuntime?.isSourceFullyProjected(entryId) ?? true,
486
- freeflowContextRuntime,
195
+ (entryId) => virtualization?.isSourceFullyProjected(entryId) ?? true,
196
+ context,
487
197
  );
488
- await contextVirtualizationRuntime.recover(ctx);
489
- const capabilityState = await readCapabilityState(ctx.cwd, ctx, pi?.host);
490
- await refreshRuntimeContext(capabilityState);
491
- routingSession.ensureStartupInactive(ctx, capabilityState.cognitiveRouting?.effective === true);
492
- routingSession.reconcileNativeEntries(ctx);
493
- const hasSessionState = sessionHasConversationOrRoutingState(ctx);
494
- const snapshot = await buildProviderSurface(ctx, hasSessionState);
495
- if (
496
- !hasSessionState &&
497
- snapshot.capabilityState?.cognitiveRouting?.effective === true &&
498
- routingSession.canAutoActivate()
499
- ) {
500
- routingSession.armFromCapability(snapshot.capabilityState.cognitiveRouting);
501
- } else {
502
- routingSession.clearArmed();
503
- }
504
- registerContextToolForState(snapshot.capabilityState);
505
- const routingSnapshot = routingSession.snapshot();
506
- setFreeflowStatus(
507
- ctx,
508
- snapshot.capabilityState,
509
- snapshot.cognitiveRoutingRuntime ?? routingSnapshot.runtimeState,
510
- snapshot.freeflowContext,
511
- { startupSelectionSuppressed: routingSnapshot.startupSelectionSuppressed },
512
- );
513
- await applyCapabilityToolVisibility(pi, ctx, snapshot.capabilityState, routingSnapshot);
198
+ await virtualization.recover(ctx);
199
+ await routing.bind(ctx, capability.cognitiveRouting, event?.reason !== "reload");
200
+ contextTools();
201
+ status(ctx);
514
202
  });
515
- pi.on("agent_settled", async (_event, ctx) => {
516
- if (!routingSession.hasController()) return undefined;
517
- await applyLiveCapabilityStateForSession(ctx);
518
- return undefined;
203
+ pi.on("session_shutdown", async () => {
204
+ surfaceGeneration++;
205
+ routing.unbind();
206
+ context = undefined;
207
+ virtualization = undefined;
208
+ history = undefined;
209
+ capability = undefined;
210
+ prompts = undefined;
211
+ sessionContext = undefined;
519
212
  });
520
- pi.on("session_shutdown", async (event) => {
521
- await routingSession.shutdown(event?.reason);
522
- providerSurfaceSnapshot = undefined;
523
- freeflowContextRuntime = undefined;
524
- contextVirtualizationRuntime = undefined;
525
- conversationHistoryRuntime = undefined;
213
+ pi.on("before_agent_start", async (event, ctx) => {
214
+ await update(ctx);
215
+ await routing.beforeRun(ctx);
216
+ status(ctx);
217
+ const text = runtimeContext(prompts, capability);
218
+ return { systemPrompt: text ? `${event.systemPrompt}\n\n${text}` : event.systemPrompt };
526
219
  });
527
- pi.on("session_tree", async (_event, ctx) => {
528
- latestCognitiveRoutingContext = ctx;
529
- providerSurfaceSnapshot = undefined;
530
- runtimeStateRefreshRequired = true;
531
- restoreSessionOverrides(ctx);
532
- await routingSession.reconcileBranch();
533
- if (contextVirtualizationRuntime) {
534
- contextVirtualizationRuntime.setContext(ctx);
535
- await contextVirtualizationRuntime.recover(ctx);
536
- }
537
- conversationHistoryRuntime?.setContext(ctx);
538
- await applyLiveCapabilityStateForSession(ctx);
220
+ pi.on("message_end", (event) => routing.messageEnd(event.message));
221
+ pi.on("tool_call", (event, ctx) => {
222
+ if (
223
+ event.toolName === CONTEXT_VIRTUALIZATION_TOOL_NAME &&
224
+ !capability?.contextVirtualization?.effective &&
225
+ !capability?.conversationHistory?.effective
226
+ )
227
+ return { block: true, reason: "Freeflow Context is disabled." };
228
+ return routing.preflight(event, ctx);
539
229
  });
540
- pi.on("session_compact", async (_event, ctx) => {
541
- latestCognitiveRoutingContext = ctx;
542
- providerSurfaceSnapshot = undefined;
543
- runtimeStateRefreshRequired = true;
544
- await routingSession.reconcileBranch("session-compact");
545
- if (contextVirtualizationRuntime) {
546
- contextVirtualizationRuntime.setContext(ctx);
547
- await contextVirtualizationRuntime.recover(ctx);
548
- }
549
- conversationHistoryRuntime?.setContext(ctx);
550
- await applyLiveCapabilityStateForSession(ctx);
230
+ pi.on("turn_end", async (event, ctx) => {
231
+ await routing.turnEnd(event, ctx);
232
+ status(ctx);
551
233
  });
552
- pi.on("before_agent_start", async (event, ctx) => {
553
- latestCognitiveRoutingContext = ctx;
554
- const snapshot = await buildProviderSurface(ctx, true);
555
- providerSurfaceSnapshot = { context: ctx, value: snapshot };
556
- registerContextToolForState(snapshot.capabilityState);
557
- const routingSnapshot = routingSession.snapshot();
558
- setFreeflowStatus(ctx, snapshot.capabilityState, snapshot.cognitiveRoutingRuntime, snapshot.freeflowContext, {
559
- startupSelectionSuppressed: routingSnapshot.startupSelectionSuppressed,
560
- });
561
- await applyCapabilityToolVisibility(pi, ctx, snapshot.capabilityState, routingSnapshot);
562
- const freeflowRuntimeContext = runtimeContext(snapshot.freeflowContext, snapshot.capabilityState);
563
- const systemPrompt = freeflowRuntimeContext
564
- ? `${event.systemPrompt}\n\n${freeflowRuntimeContext}`
565
- : event.systemPrompt;
566
- return { systemPrompt };
234
+ pi.on("agent_settled", async (_event, ctx) => {
235
+ await routing.settled(ctx);
236
+ await update(ctx);
237
+ });
238
+ pi.on("model_select", async (_event, ctx) => {
239
+ await routing.nativeChange(ctx);
240
+ status(ctx);
241
+ });
242
+ pi.on("thinking_level_select", async (_event, ctx) => {
243
+ await routing.nativeChange(ctx);
244
+ status(ctx);
567
245
  });
568
246
  pi.on("context", async (event, ctx) => {
569
- const snapshot =
570
- providerSurfaceSnapshot?.context === ctx ? providerSurfaceSnapshot.value : await buildProviderSurface(ctx, false);
571
- if (providerSurfaceSnapshot?.context === ctx) providerSurfaceSnapshot = undefined;
572
- const cognitiveRoutingRuntime = snapshot.cognitiveRoutingRuntime;
573
- const surfaceCapabilityState = snapshot.capabilityState;
574
- let changed = false;
575
- let messages = event.messages
576
- .map((message) => {
577
- const filtered = filterBootstrapMessage(message);
578
- if (filtered !== message) changed = true;
579
- return filtered;
580
- })
581
- .filter((message) => message !== undefined);
582
- if (contextVirtualizationRuntime) {
583
- contextVirtualizationRuntime.setContext(ctx);
584
- const projected = await contextVirtualizationRuntime.project(
585
- messages,
586
- surfaceCapabilityState.contextVirtualization?.effective === true,
587
- );
588
- if (projected.changed) {
589
- changed = true;
590
- messages = projected.messages;
591
- }
592
- }
593
- if (conversationHistoryRuntime && surfaceCapabilityState.conversationHistory?.effective === true) {
594
- conversationHistoryRuntime.setContext(ctx);
595
- conversationHistoryRuntime.capture(surfaceCapabilityState.contextVirtualization?.effective === true);
596
- }
597
- const forceRuntimeStateRefresh = runtimeStateRefreshRequired;
598
- const nextMessages = withFreeflowRuntimeState(
599
- messages,
600
- surfaceCapabilityState,
601
- cognitiveRoutingRuntime,
602
- snapshot.freeflowContext,
603
- { force: forceRuntimeStateRefresh },
604
- );
605
- if (nextMessages !== messages) {
606
- changed = true;
607
- messages = nextMessages;
247
+ if (!capability) await loadSurface(ctx);
248
+ let messages = event.messages.map(filterBootstrapMessage).filter(Boolean);
249
+ if (virtualization) {
250
+ virtualization.setContext(ctx);
251
+ const projected = await virtualization.project(messages, capability.contextVirtualization.effective);
252
+ messages = projected.messages;
608
253
  }
609
- if (forceRuntimeStateRefresh) runtimeStateRefreshRequired = false;
610
- return changed ? { messages } : undefined;
611
- });
612
- pi.on("tool_call", async (event, ctx) => {
613
- const capabilityState = await readCapabilityState(ctx.cwd, ctx, pi?.host);
614
- const toolName = typeof event?.toolName === "string" ? event.toolName : "";
615
- if (
616
- capabilityState.contextVirtualization?.effective !== true &&
617
- capabilityState.conversationHistory?.effective !== true &&
618
- toolName === CONTEXT_VIRTUALIZATION_TOOL_NAME
619
- ) {
620
- return disabledToolCall(toolName, "context");
254
+ if (history && capability.conversationHistory.effective) {
255
+ history.setContext(ctx);
256
+ history.capture(capability.contextVirtualization.effective);
621
257
  }
622
- return undefined;
258
+ messages = withFreeflowRuntimeState(messages, capability, routing.state(), prompts, {
259
+ force: refreshState,
260
+ projectionFailure: routing.state().projectionFailure,
261
+ });
262
+ refreshState = false;
263
+ return { messages: await routing.context(ctx, messages) };
623
264
  });
624
- pi.on("tool_result", async (event, ctx) => {
625
- const toolName = typeof event?.toolName === "string" ? event.toolName : "";
626
- if (routingSession.supportsCognitiveRoutingRuntime() && toolName === COGNITIVE_ROUTING_SWITCH_TOOL_NAME) {
627
- await applyLiveCapabilityStateForSession(ctx);
265
+ const restore = async (ctx, navigation = true) => {
266
+ restoreSessionOverrides(ctx);
267
+ refreshState = true;
268
+ if (virtualization) {
269
+ virtualization.setContext(ctx);
270
+ await virtualization.recover(ctx);
628
271
  }
629
- return undefined;
272
+ history?.setContext(ctx);
273
+ await routing.ancestryChanged(ctx, navigation);
274
+ await update(ctx);
275
+ };
276
+ pi.on("session_tree", async (_event, ctx) => restore(ctx));
277
+ pi.on("session_compact", async (_event, ctx) => restore(ctx, false));
278
+ pi.on("session_compact_failed", async (_event, ctx) => {
279
+ refreshState = true;
280
+ status(ctx);
630
281
  });
631
- for (const { command, skill } of WORKFLOW_COMMANDS) {
632
- pi.registerCommand(command, {
633
- description: command === skill ? `Run Freeflow ${skill}` : `Run Freeflow ${skill} via ${command}`,
634
- ...(command === "bypass" ? { getArgumentCompletions: bypassCompletions } : {}),
635
- handler: async (args, ctx) => {
636
- await sendSkillCommand(pi, ctx, skill, args);
282
+ if (
283
+ typeof pi.registerShortcut === "function" &&
284
+ typeof api.appendEntry === "function" &&
285
+ typeof api.setModel === "function" &&
286
+ typeof api.setThinkingLevel === "function"
287
+ ) {
288
+ pi.registerShortcut("ctrl+shift+r", {
289
+ description: "Cycle the Coordinator/Executor manual hold",
290
+ handler: async (ctx) => {
291
+ if (!ctx.isIdle()) {
292
+ ctx.ui.notify("Wait for Pi to become idle before changing control.", "warning");
293
+ return;
294
+ }
295
+ const target = routing.state().activeProfile === "coordinator" ? "executor" : "coordinator";
296
+ ctx.ui.notify(JSON.stringify(await routing.setManualProfile(target)), "info");
297
+ await update(ctx);
298
+ },
299
+ });
300
+ pi.registerShortcut("ctrl+shift+a", {
301
+ description: "Release manual hold to Automatic Coordinator",
302
+ handler: async (ctx) => {
303
+ if (!ctx.isIdle()) {
304
+ ctx.ui.notify("Wait for Pi to become idle before changing control.", "warning");
305
+ return;
306
+ }
307
+ ctx.ui.notify(JSON.stringify(await routing.setAutomaticControl()), "info");
308
+ await update(ctx);
637
309
  },
638
310
  });
639
311
  }
640
- for (const skill of CONTRIBUTOR_COMMANDS) {
312
+ for (const { command, skill } of WORKFLOW_COMMANDS)
313
+ pi.registerCommand(command, {
314
+ description: command === skill ? `Run Freeflow ${skill}` : `Run Freeflow ${skill} via ${command}`,
315
+ ...(command === "bypass"
316
+ ? {
317
+ getArgumentCompletions: (prefix) =>
318
+ [
319
+ { value: "next", label: "next", description: "Skip one optional step" },
320
+ { value: "task", label: "task", description: "Reduce optional pressure for the current task" },
321
+ ].filter((item) => item.value.startsWith(prefix ?? "")),
322
+ }
323
+ : {}),
324
+ handler: (args, ctx) => sendSkillCommand(pi, ctx, skill, args),
325
+ });
326
+ for (const skill of CONTRIBUTOR_COMMANDS)
641
327
  pi.registerCommand(skill, {
642
328
  description: `Run Freeflow ${skill}`,
643
- handler: async (args, ctx) => {
644
- await sendSkillCommand(pi, ctx, skill, args);
645
- },
329
+ handler: (args, ctx) => sendSkillCommand(pi, ctx, skill, args),
646
330
  });
647
- }
648
331
  pi.registerCommand("freeflow", {
649
- description: "Open unified Freeflow settings or print compact status",
650
- getArgumentCompletions: (prefix) => freeflowCompletions(prefix, routingSession.supportsCognitiveRoutingRuntime()),
332
+ description: "Freeflow settings, status, profile control, saved-operation resume, and context tools",
333
+ getArgumentCompletions: (prefix) =>
334
+ freeflowCompletions(
335
+ prefix,
336
+ typeof api.appendEntry === "function" &&
337
+ typeof api.setModel === "function" &&
338
+ typeof api.setThinkingLevel === "function",
339
+ ),
651
340
  handler: async (args, ctx) => {
652
- const contextInput = (args ?? "").trim();
653
- if (contextInput === "context" || contextInput.startsWith("context ")) {
654
- const capabilityState = await readCapabilityState(ctx.cwd, ctx, pi?.host);
341
+ if (await routing.command(args ?? "", ctx)) {
342
+ await update(ctx);
343
+ return;
344
+ }
345
+ const input = (args ?? "").trim();
346
+ if (input === "context" || input.startsWith("context ")) {
655
347
  await handleContextCommand(
656
- contextInput.slice("context".length).trim(),
348
+ input.slice(7).trim(),
657
349
  ctx,
658
- contextVirtualizationRuntime,
659
- capabilityState.contextVirtualization?.effective === true,
660
- capabilityState.conversationHistory?.effective === true,
350
+ virtualization,
351
+ capability?.contextVirtualization.effective,
352
+ capability?.conversationHistory.effective,
661
353
  );
662
354
  return;
663
355
  }
664
- if (routingSession.supportsCognitiveRoutingRuntime() && /^profile(?:\s|$)/i.test((args ?? "").trim())) {
665
- const profileCommandContext = {
666
- isIdle: ctx?.isIdle,
667
- ui: ctx?.ui,
668
- history: (options) => routingSession.history(options) ?? readCognitiveRoutingHistory(ctx, options),
669
- };
670
- const historyCommand = /^profile\s+history(?:\s|$)/i.test((args ?? "").trim());
671
- if (historyCommand) {
672
- await handleCognitiveRoutingProfileCommand(args, profileCommandContext, routingSession.commandController());
673
- return;
674
- }
675
- if (!routingSession.hasController() && !routingSession.armed) {
676
- routingSession.beginExplicitReactivation();
677
- await applyLiveCapabilityStateForSession(ctx, { reconcileCognitiveRouting: true });
678
- }
679
- const profileController = routingSession.commandController();
680
- if (await handleCognitiveRoutingProfileCommand(args, profileCommandContext, profileController)) {
681
- if (profileController) {
682
- routingSession.beginExplicitReactivation();
683
- await applyLiveCapabilityStateForSession(ctx, {
684
- reconcileCognitiveRouting: routingSession.armed !== undefined,
685
- materializeCognitiveRouting: routingSession.armed !== undefined && !isPiFlowHost(pi?.host),
686
- });
687
- }
688
- return;
689
- }
690
- }
691
- await handleFreeflowCommand(
692
- args,
693
- ctx,
694
- async (_changed, options = {}) => {
695
- await applyLiveCapabilityStateForSession(ctx, {
696
- reconcileCognitiveRouting: options.reconcileCognitiveRouting ?? true,
697
- });
698
- },
699
- pi,
700
- routingSession.commandController(),
701
- );
356
+ await handleFreeflowCommand(args, ctx, async () => update(ctx), pi, routing);
702
357
  },
703
358
  });
704
359
  }