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