@hassangameryt/freeflow 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (284) 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/README.md +148 -154
  5. package/capabilities/cognitive-routing/SKILL.md +229 -0
  6. package/capabilities/context-virtualization/SKILL.md +103 -0
  7. package/capabilities/conversation-history/SKILL.md +53 -0
  8. package/command-surface.json +6 -13
  9. package/hooks/freeflow-runtime-context.mjs +35 -91
  10. package/hooks/tests/check-runtime-context-hook.sh +56 -39
  11. package/package.json +24 -16
  12. package/pi-extension/dist/cognitive-routing/commands.js +96 -0
  13. package/pi-extension/dist/cognitive-routing/config.js +236 -0
  14. package/pi-extension/dist/cognitive-routing/controller.js +862 -0
  15. package/pi-extension/dist/cognitive-routing/history.js +439 -0
  16. package/pi-extension/dist/cognitive-routing/host.js +126 -0
  17. package/pi-extension/dist/cognitive-routing/runtime.js +43 -0
  18. package/pi-extension/dist/cognitive-routing/tool.js +211 -0
  19. package/pi-extension/dist/cognitive-routing/types.js +6 -0
  20. package/pi-extension/dist/context-virtualization/commands.js +89 -0
  21. package/pi-extension/dist/context-virtualization/projector.js +42 -0
  22. package/pi-extension/dist/context-virtualization/runtime.js +356 -0
  23. package/pi-extension/dist/context-virtualization/state.js +57 -0
  24. package/pi-extension/dist/context-virtualization/types.js +10 -0
  25. package/pi-extension/dist/conversation-history/passages.js +66 -0
  26. package/pi-extension/dist/conversation-history/ranking.js +105 -0
  27. package/pi-extension/dist/conversation-history/runtime.js +226 -0
  28. package/pi-extension/dist/conversation-history/search.js +56 -0
  29. package/pi-extension/dist/conversation-history/types.js +1 -0
  30. package/pi-extension/dist/freeflow-context/resolver.js +120 -0
  31. package/pi-extension/dist/freeflow-context/runtime.js +80 -0
  32. package/pi-extension/dist/freeflow-context/source-projector.js +95 -0
  33. package/pi-extension/dist/freeflow-context/tool.js +308 -0
  34. package/pi-extension/dist/freeflow-context/types.js +12 -0
  35. package/pi-extension/dist/freeflow-context/visibility.js +28 -0
  36. package/pi-extension/dist/index.js +516 -98
  37. package/pi-extension/dist/runtime/runtime-context.js +318 -271
  38. package/pi-extension/dist/runtime/runtime-identity.js +5 -0
  39. package/pi-extension/dist/settings/settings-tui.js +78 -0
  40. package/pi-extension/dist/settings/settings-ui.js +593 -563
  41. package/pi-extension/dist/ui/text-component.js +57 -0
  42. package/pi-extension/src/cognitive-routing/commands.ts +119 -0
  43. package/pi-extension/src/cognitive-routing/config.ts +307 -0
  44. package/pi-extension/src/cognitive-routing/controller.ts +1118 -0
  45. package/pi-extension/src/cognitive-routing/history.ts +638 -0
  46. package/pi-extension/src/cognitive-routing/host.ts +172 -0
  47. package/pi-extension/src/cognitive-routing/runtime.ts +57 -0
  48. package/pi-extension/src/cognitive-routing/tool.ts +272 -0
  49. package/pi-extension/src/cognitive-routing/types.ts +89 -0
  50. package/pi-extension/src/context-virtualization/commands.ts +111 -0
  51. package/pi-extension/src/context-virtualization/projector.ts +62 -0
  52. package/pi-extension/src/context-virtualization/runtime.ts +406 -0
  53. package/pi-extension/src/context-virtualization/state.ts +79 -0
  54. package/pi-extension/src/context-virtualization/types.ts +92 -0
  55. package/pi-extension/src/conversation-history/passages.ts +81 -0
  56. package/pi-extension/src/conversation-history/ranking.ts +155 -0
  57. package/pi-extension/src/conversation-history/runtime.ts +250 -0
  58. package/pi-extension/src/conversation-history/search.ts +79 -0
  59. package/pi-extension/src/conversation-history/types.ts +31 -0
  60. package/pi-extension/src/freeflow-context/resolver.ts +139 -0
  61. package/pi-extension/src/freeflow-context/runtime.ts +100 -0
  62. package/pi-extension/src/freeflow-context/source-projector.ts +106 -0
  63. package/pi-extension/src/freeflow-context/tool.ts +360 -0
  64. package/pi-extension/src/freeflow-context/types.ts +70 -0
  65. package/pi-extension/src/freeflow-context/visibility.ts +53 -0
  66. package/pi-extension/src/index.ts +553 -101
  67. package/pi-extension/src/runtime/runtime-context.ts +339 -281
  68. package/pi-extension/src/runtime/runtime-identity.ts +8 -0
  69. package/pi-extension/src/settings/settings-tui.ts +93 -0
  70. package/pi-extension/src/settings/settings-ui.ts +700 -613
  71. package/pi-extension/src/ui/text-component.ts +66 -0
  72. package/pi-extension/tests/cognitive-routing/commands.test.js +134 -0
  73. package/pi-extension/tests/cognitive-routing/controller.test.js +1099 -0
  74. package/pi-extension/tests/cognitive-routing/extension-lifecycle.test.js +1071 -0
  75. package/pi-extension/tests/cognitive-routing/history.test.js +274 -0
  76. package/pi-extension/tests/cognitive-routing/host-fixture.js +4 -0
  77. package/pi-extension/tests/cognitive-routing/host-identity.test.js +63 -0
  78. package/pi-extension/tests/cognitive-routing/profile-resolution.test.js +236 -0
  79. package/pi-extension/tests/cognitive-routing/tool.test.js +230 -0
  80. package/pi-extension/tests/context-virtualization/extension.test.js +749 -0
  81. package/pi-extension/tests/context-virtualization/projector.test.js +110 -0
  82. package/pi-extension/tests/context-virtualization/runtime.test.js +216 -0
  83. package/pi-extension/tests/conversation-history/runtime.test.js +98 -0
  84. package/pi-extension/tests/conversation-history/search.test.js +97 -0
  85. package/pi-extension/tests/integration/pi-extension.test.js +927 -2048
  86. package/pi-extension/tests/integration/prompt-architecture.test.js +305 -0
  87. package/runtime/prompts/cognitive-routing.md +9 -0
  88. package/runtime/prompts/context-virtualization.md +3 -0
  89. package/runtime/prompts/conversation-history.md +3 -0
  90. package/runtime/prompts/core.md +13 -0
  91. package/runtime/prompts/interaction-contract.md +7 -0
  92. package/runtime/prompts/skills.md +65 -0
  93. package/skills/action-selection/SKILL.md +91 -0
  94. package/skills/bypass/SKILL.md +3 -2
  95. package/skills/commit-work/SKILL.md +1 -1
  96. package/skills/commit-work/references/staging-decisions.md +1 -1
  97. package/skills/decision-gate/SKILL.md +1 -1
  98. package/skills/design-for-depth/SKILL.md +14 -33
  99. package/skills/design-for-depth/references/design-pressure-signals.md +1 -1
  100. package/skills/design-for-depth/references/interface-design-loop.md +1 -1
  101. package/skills/design-for-depth/references/software-design-philosophy.md +1 -1
  102. package/skills/diagnose-failure/SKILL.md +20 -14
  103. package/skills/diagnose-failure/references/diagnostic-loop-catalog.md +1 -3
  104. package/skills/diagnose-failure/references/{flaky-and-performance.md → flaky-and-performance-diagnosis.md} +1 -1
  105. package/skills/discuss/SKILL.md +34 -22
  106. package/skills/discuss/references/discussion-continuity.md +71 -0
  107. package/skills/evaluate-skill/SKILL.md +5 -5
  108. package/skills/evaluate-skill/references/{definition-schema.md → evaluation-definition-schema.md} +42 -2
  109. package/skills/evaluate-skill/references/execution-and-evidence.md +8 -3
  110. package/skills/evaluate-skill/scripts/lib/definitions.mjs +114 -3
  111. package/skills/evaluate-skill/scripts/lib/grade-interaction.mjs +156 -1
  112. package/skills/evaluate-skill/scripts/lib/grade.mjs +9 -1
  113. package/skills/evaluate-skill/scripts/lib/pi.mjs +147 -32
  114. package/skills/evaluate-skill/scripts/lib/rpc.mjs +4 -4
  115. package/skills/evaluate-skill/scripts/lib/runner.mjs +36 -14
  116. package/skills/evaluate-skill/scripts/lib/sandbox.mjs +92 -0
  117. package/skills/evaluate-skill/scripts/pi-guard.mjs +1 -1
  118. package/skills/evaluate-skill/scripts/pi-observer.mjs +66 -0
  119. package/skills/evaluate-skill/scripts/skill-eval.mjs +6 -5
  120. package/skills/execute-work/SKILL.md +18 -15
  121. package/skills/execute-work/references/code-practices.md +1 -1
  122. package/skills/execute-work/references/execute-work-edges.md +42 -0
  123. package/skills/finish-branch/SKILL.md +2 -2
  124. package/skills/finish-branch/references/integration-options.md +1 -1
  125. package/skills/handoff/SKILL.md +3 -3
  126. package/skills/launch-work/SKILL.md +1 -1
  127. package/skills/launch-work/references/launch-readiness.md +2 -2
  128. package/skills/migration-work/SKILL.md +2 -2
  129. package/skills/migration-work/references/migration-lifecycle.md +1 -1
  130. package/skills/mode-contract/SKILL.md +4 -4
  131. package/skills/release-work/SKILL.md +1 -1
  132. package/skills/release-work/references/release-evidence.md +1 -1
  133. package/skills/review-artifact/SKILL.md +28 -26
  134. package/skills/review-work/SKILL.md +28 -26
  135. package/skills/review-work/references/{reviewer-prompt.md → independent-work-reviewer-contract.md} +1 -1
  136. package/skills/review-work/references/security-risk-lens.md +1 -1
  137. package/skills/setup-freeflow/SKILL.md +3 -1
  138. package/skills/setup-freeflow/references/activation-contract.md +2 -2
  139. package/skills/setup-freeflow/references/host-setup.md +2 -2
  140. package/skills/simplify-code/SKILL.md +1 -1
  141. package/skills/simplify-code/references/simplification-patterns.md +1 -1
  142. package/skills/tdd/SKILL.md +18 -38
  143. package/skills/tdd/references/test-design.md +2 -2
  144. package/skills/track-work/SKILL.md +362 -58
  145. package/skills/track-work/scripts/lib/codec.mjs +570 -0
  146. package/skills/track-work/scripts/lib/commands.mjs +568 -0
  147. package/skills/track-work/scripts/lib/contract.mjs +303 -0
  148. package/skills/track-work/scripts/lib/model.mjs +506 -0
  149. package/skills/track-work/scripts/lib/operations.mjs +965 -0
  150. package/skills/track-work/scripts/lib/record-store.mjs +264 -0
  151. package/skills/track-work/scripts/lib/result.mjs +37 -0
  152. package/skills/track-work/scripts/lib/rewrites.mjs +740 -0
  153. package/skills/track-work/scripts/lib/schema.mjs +277 -0
  154. package/skills/track-work/scripts/lib/source-inventory.mjs +162 -0
  155. package/skills/track-work/scripts/lib/views.mjs +443 -0
  156. package/skills/track-work/scripts/lib/workspace.mjs +134 -0
  157. package/skills/track-work/scripts/working-record.mjs +122 -0
  158. package/skills/verify-work/SKILL.md +14 -2
  159. package/skills/verify-work/references/browser-runtime-evidence.md +1 -1
  160. package/skills/verify-work/references/integration-evidence.md +1 -1
  161. package/skills/verify-work/references/performance-evidence.md +1 -1
  162. package/skills/workflow/SKILL.md +105 -53
  163. package/skills/workflow/references/domain-skill-composition.md +22 -42
  164. package/skills/write-plan/SKILL.md +1 -1
  165. package/skills/write-skill/SKILL.md +3 -2
  166. package/skills/write-skill/references/progressive-disclosure.md +17 -3
  167. package/capabilities/output-router/SKILL.md +0 -206
  168. package/capabilities/output-router/references/safety-policy.md +0 -40
  169. package/capabilities/output-router/references/setup.md +0 -110
  170. package/pi-extension/dist/output-router/host-producer-identification.js +0 -232
  171. package/pi-extension/dist/output-router/native-safety-net.js +0 -216
  172. package/pi-extension/dist/output-router/observed-tool-routing.js +0 -122
  173. package/pi-extension/dist/output-router/renderers.js +0 -1023
  174. package/pi-extension/dist/output-router/router-tools.js +0 -554
  175. package/pi-extension/dist/output-router/schemas.js +0 -383
  176. package/pi-extension/dist/output-router/status.js +0 -744
  177. package/pi-extension/dist/output-router/utils.js +0 -502
  178. package/pi-extension/src/output-router/host-producer-identification.ts +0 -256
  179. package/pi-extension/src/output-router/native-safety-net.ts +0 -248
  180. package/pi-extension/src/output-router/observed-tool-routing.ts +0 -134
  181. package/pi-extension/src/output-router/renderers.ts +0 -1108
  182. package/pi-extension/src/output-router/router-tools.ts +0 -579
  183. package/pi-extension/src/output-router/schemas.ts +0 -387
  184. package/pi-extension/src/output-router/status.ts +0 -791
  185. package/pi-extension/src/output-router/utils.ts +0 -554
  186. package/pi-extension/tests/output-router/observed-producers.test.js +0 -132
  187. package/pi-extension/tests/output-router/search.test.js +0 -722
  188. package/router/dist/benchmarks/benchmark-harness.d.ts +0 -35
  189. package/router/dist/benchmarks/benchmark-harness.js +0 -92
  190. package/router/dist/benchmarks/benchmarks.d.ts +0 -109
  191. package/router/dist/benchmarks/benchmarks.js +0 -979
  192. package/router/dist/benchmarks/codex-qa-benchmarks.d.ts +0 -95
  193. package/router/dist/benchmarks/codex-qa-benchmarks.js +0 -500
  194. package/router/dist/benchmarks/command-benchmarks.d.ts +0 -143
  195. package/router/dist/benchmarks/command-benchmarks.js +0 -698
  196. package/router/dist/benchmarks/context-mode-normalized-benchmarks.d.ts +0 -82
  197. package/router/dist/benchmarks/context-mode-normalized-benchmarks.js +0 -773
  198. package/router/dist/benchmarks/context-mode-real-deep-benchmark.d.ts +0 -132
  199. package/router/dist/benchmarks/context-mode-real-deep-benchmark.js +0 -1380
  200. package/router/dist/benchmarks/context-saving-baseline.d.ts +0 -60
  201. package/router/dist/benchmarks/context-saving-baseline.js +0 -470
  202. package/router/dist/benchmarks/index-benchmarks.d.ts +0 -103
  203. package/router/dist/benchmarks/index-benchmarks.js +0 -862
  204. package/router/dist/benchmarks/storage-policy-benchmarks.d.ts +0 -101
  205. package/router/dist/benchmarks/storage-policy-benchmarks.js +0 -618
  206. package/router/dist/benchmarks/vault-index-benchmarks.d.ts +0 -56
  207. package/router/dist/benchmarks/vault-index-benchmarks.js +0 -322
  208. package/router/dist/config/config.d.ts +0 -103
  209. package/router/dist/config/config.js +0 -632
  210. package/router/dist/config/router-contract.d.ts +0 -10
  211. package/router/dist/config/router-contract.js +0 -54
  212. package/router/dist/config/schema.d.ts +0 -27
  213. package/router/dist/config/schema.js +0 -648
  214. package/router/dist/config/types.d.ts +0 -573
  215. package/router/dist/config/types.js +0 -41
  216. package/router/dist/evidence/bounded-evidence.d.ts +0 -40
  217. package/router/dist/evidence/bounded-evidence.js +0 -323
  218. package/router/dist/evidence/evidence-range-selector.d.ts +0 -24
  219. package/router/dist/evidence/evidence-range-selector.js +0 -232
  220. package/router/dist/evidence/evidence-search.d.ts +0 -27
  221. package/router/dist/evidence/evidence-search.js +0 -490
  222. package/router/dist/evidence/evidence.d.ts +0 -38
  223. package/router/dist/evidence/evidence.js +0 -200
  224. package/router/dist/evidence/failure-contracts.d.ts +0 -37
  225. package/router/dist/evidence/failure-contracts.js +0 -166
  226. package/router/dist/evidence/line-ranges.d.ts +0 -24
  227. package/router/dist/evidence/line-ranges.js +0 -22
  228. package/router/dist/experiments/local-index.d.ts +0 -64
  229. package/router/dist/experiments/local-index.js +0 -581
  230. package/router/dist/index.d.ts +0 -30
  231. package/router/dist/index.js +0 -32
  232. package/router/dist/local/local-traversal.d.ts +0 -18
  233. package/router/dist/local/local-traversal.js +0 -334
  234. package/router/dist/processing/engine.d.ts +0 -132
  235. package/router/dist/processing/engine.js +0 -533
  236. package/router/dist/processing/reducers.d.ts +0 -280
  237. package/router/dist/processing/reducers.js +0 -1673
  238. package/router/dist/processing/renderers.d.ts +0 -31
  239. package/router/dist/processing/renderers.js +0 -195
  240. package/router/dist/processing/scripts.d.ts +0 -91
  241. package/router/dist/processing/scripts.js +0 -386
  242. package/router/dist/repo/repo-traversal.d.ts +0 -18
  243. package/router/dist/repo/repo-traversal.js +0 -245
  244. package/router/dist/routing/observed-reducers.d.ts +0 -41
  245. package/router/dist/routing/observed-reducers.js +0 -661
  246. package/router/dist/routing/observed-routing.d.ts +0 -26
  247. package/router/dist/routing/observed-routing.js +0 -378
  248. package/router/dist/routing/parsers.d.ts +0 -16
  249. package/router/dist/routing/parsers.js +0 -521
  250. package/router/dist/routing/run-filters.d.ts +0 -60
  251. package/router/dist/routing/run-filters.js +0 -238
  252. package/router/dist/routing/run-reducers.d.ts +0 -49
  253. package/router/dist/routing/run-reducers.js +0 -122
  254. package/router/dist/sandbox/adapter-roots.d.ts +0 -46
  255. package/router/dist/sandbox/adapter-roots.js +0 -66
  256. package/router/dist/sandbox/eryx-python-adapter.d.ts +0 -13
  257. package/router/dist/sandbox/eryx-python-adapter.js +0 -868
  258. package/router/dist/sandbox/jq-wasm-adapter.d.ts +0 -9
  259. package/router/dist/sandbox/jq-wasm-adapter.js +0 -429
  260. package/router/dist/sandbox/quickjs-wasi-adapter.d.ts +0 -13
  261. package/router/dist/sandbox/quickjs-wasi-adapter.js +0 -384
  262. package/router/dist/sandbox/script-sandbox.d.ts +0 -134
  263. package/router/dist/sandbox/script-sandbox.js +0 -337
  264. package/router/dist/setup/script-transform-adapters.d.ts +0 -32
  265. package/router/dist/setup/script-transform-adapters.js +0 -278
  266. package/router/dist/tools/batch.d.ts +0 -33
  267. package/router/dist/tools/batch.js +0 -586
  268. package/router/dist/tools/run.d.ts +0 -62
  269. package/router/dist/tools/run.js +0 -1304
  270. package/router/dist/tools/search.d.ts +0 -66
  271. package/router/dist/tools/search.js +0 -1364
  272. package/router/dist/transform/engine.d.ts +0 -168
  273. package/router/dist/transform/engine.js +0 -2072
  274. package/router/dist/vault/vault-index.d.ts +0 -125
  275. package/router/dist/vault/vault-index.js +0 -416
  276. package/router/dist/vault/vault.d.ts +0 -138
  277. package/router/dist/vault/vault.js +0 -630
  278. package/runtime/interaction-contract.md +0 -16
  279. package/skills/discuss/references/checkpoints.md +0 -66
  280. package/skills/execute-work/references/execution-loop.md +0 -77
  281. package/skills/track-work/references/working-record-schema.md +0 -378
  282. package/skills/workflow/references/workflow-loop.md +0 -92
  283. /package/skills/handoff/references/{templates.md → handoff-templates.md} +0 -0
  284. /package/skills/review-artifact/references/{reviewer-prompt.md → independent-artifact-reviewer-contract.md} +0 -0
@@ -0,0 +1,862 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { readCognitiveRoutingHistory } from "./history.js";
3
+ export const COGNITIVE_ROUTING_INTENT_ENTRY = "freeflow-cognitive-routing-intent";
4
+ export const COGNITIVE_ROUTING_CONTROL_ENTRY = "freeflow-cognitive-routing-control";
5
+ function isProfileName(value) {
6
+ return value === "standard" || value === "reasoning";
7
+ }
8
+ function isMechanism(value) {
9
+ return [
10
+ "agent-tool",
11
+ "profile-command",
12
+ "profile-shortcut",
13
+ "profile-settings",
14
+ "session-tree",
15
+ "session-compact",
16
+ "activation",
17
+ "reload-restore",
18
+ "recovery",
19
+ "shutdown-restore",
20
+ ].includes(value);
21
+ }
22
+ function asIntentSource(value) {
23
+ if (value === "user" || value === "agent") return value;
24
+ return "system";
25
+ }
26
+ function pairEquals(a, b) {
27
+ return a?.provider === b?.provider && a?.modelId === b?.modelId && a?.thinkingLevel === b?.thinkingLevel;
28
+ }
29
+ function asPair(value) {
30
+ if (!value || typeof value !== "object") return undefined;
31
+ const candidate = value;
32
+ if (
33
+ typeof candidate.provider !== "string" ||
34
+ typeof candidate.modelId !== "string" ||
35
+ typeof candidate.thinkingLevel !== "string"
36
+ ) {
37
+ return undefined;
38
+ }
39
+ return {
40
+ provider: candidate.provider,
41
+ modelId: candidate.modelId,
42
+ thinkingLevel: candidate.thinkingLevel,
43
+ };
44
+ }
45
+ function latestHostPair(context) {
46
+ const entries = branchEntriesFrom(context);
47
+ for (let index = entries.length - 1; index >= 0; index -= 1) {
48
+ const entry = entries[index];
49
+ if (!entry || typeof entry !== "object") continue;
50
+ const candidate = entry;
51
+ if (candidate.type !== "model_state_change") continue;
52
+ const pair = asPair({
53
+ provider: candidate.provider,
54
+ modelId: candidate.modelId,
55
+ thinkingLevel: candidate.thinkingLevel,
56
+ });
57
+ if (pair) return pair;
58
+ }
59
+ return undefined;
60
+ }
61
+ function profileNameForPair(capabilityState, pair) {
62
+ if (!pair) return undefined;
63
+ for (const [name, profile] of Object.entries(capabilityState.resolvedProfiles)) {
64
+ if (!profile) continue;
65
+ if (
66
+ pairEquals(pair, {
67
+ provider: profile.provider,
68
+ modelId: profile.model,
69
+ thinkingLevel: profile.effectiveThinkingLevel,
70
+ })
71
+ ) {
72
+ return isProfileName(name) ? name : undefined;
73
+ }
74
+ }
75
+ return undefined;
76
+ }
77
+ function asIntent(value) {
78
+ if (!value || typeof value !== "object") return undefined;
79
+ const candidate = value;
80
+ if (
81
+ (candidate.version !== 1 && candidate.version !== 2) ||
82
+ (candidate.kind !== "activation" && candidate.kind !== "profile" && candidate.kind !== "closing") ||
83
+ (candidate.phase !== "prepared" && candidate.phase !== "abandoned") ||
84
+ typeof candidate.epoch !== "string" ||
85
+ typeof candidate.correlationId !== "string"
86
+ ) {
87
+ return undefined;
88
+ }
89
+ const target = asPair(candidate.target);
90
+ const returnTarget = asPair(candidate.returnTarget);
91
+ const fromPair = asPair(candidate.fromPair);
92
+ if (!target || !returnTarget) return undefined;
93
+ return {
94
+ version: candidate.version,
95
+ kind: candidate.kind,
96
+ phase: candidate.phase,
97
+ control: candidate.control === "manual" ? "manual" : "automatic",
98
+ source: asIntentSource(candidate.source),
99
+ ...(isMechanism(candidate.mechanism) ? { mechanism: candidate.mechanism } : {}),
100
+ ...(typeof candidate.decisionCorrelationId === "string"
101
+ ? { decisionCorrelationId: candidate.decisionCorrelationId }
102
+ : {}),
103
+ ...(fromPair ? { fromPair } : {}),
104
+ ...(isProfileName(candidate.fromProfile) ? { fromProfile: candidate.fromProfile } : {}),
105
+ ...(typeof candidate.reason === "string" ? { reason: candidate.reason } : {}),
106
+ ...(typeof candidate.branchId === "string" || candidate.branchId === null ? { branchId: candidate.branchId } : {}),
107
+ epoch: candidate.epoch,
108
+ correlationId: candidate.correlationId,
109
+ ...(isProfileName(candidate.profile) ? { profile: candidate.profile } : {}),
110
+ ...(isProfileName(candidate.resumeProfile) ? { resumeProfile: candidate.resumeProfile } : {}),
111
+ ...(candidate.resumeControl === "automatic" || candidate.resumeControl === "manual"
112
+ ? { resumeControl: candidate.resumeControl }
113
+ : {}),
114
+ ...(typeof candidate.resumeReason === "string" ? { resumeReason: candidate.resumeReason } : {}),
115
+ target,
116
+ returnTarget,
117
+ };
118
+ }
119
+ function entriesFrom(context) {
120
+ try {
121
+ const entries = context.sessionManager?.getEntries?.();
122
+ return Array.isArray(entries) ? entries : [];
123
+ } catch {
124
+ return [];
125
+ }
126
+ }
127
+ function branchEntriesFrom(context) {
128
+ try {
129
+ const entries = context.sessionManager?.getBranch?.();
130
+ return Array.isArray(entries) ? entries : entriesFrom(context);
131
+ } catch {
132
+ return entriesFrom(context);
133
+ }
134
+ }
135
+ function latestIntent(entries, predicate = () => true) {
136
+ const abandonedCorrelations = new Set();
137
+ for (let index = entries.length - 1; index >= 0; index -= 1) {
138
+ const entry = entries[index];
139
+ if (!entry || typeof entry !== "object") continue;
140
+ const candidate = entry;
141
+ if (candidate.type !== "custom" || candidate.customType !== COGNITIVE_ROUTING_INTENT_ENTRY) continue;
142
+ const intent = asIntent(candidate.data);
143
+ if (!intent) continue;
144
+ if (intent.phase === "abandoned") {
145
+ abandonedCorrelations.add(intent.correlationId);
146
+ continue;
147
+ }
148
+ if (!abandonedCorrelations.has(intent.correlationId) && predicate(intent)) return intent;
149
+ }
150
+ return undefined;
151
+ }
152
+ function controlModeForIntent(intent) {
153
+ if (intent.control === "manual" && intent.profile) return `manual-${intent.profile}`;
154
+ return "automatic";
155
+ }
156
+ function decisionCorrelationForIntent(intent) {
157
+ if (intent.decisionCorrelationId) return intent.decisionCorrelationId;
158
+ return intent.source === "user" || intent.source === "agent" ? intent.correlationId : undefined;
159
+ }
160
+ function latestControlMode(entries, intent) {
161
+ for (let index = entries.length - 1; index >= 0; index -= 1) {
162
+ const entry = entries[index];
163
+ if (!entry || typeof entry !== "object") continue;
164
+ const candidate = entry;
165
+ if (candidate.type !== "custom") continue;
166
+ if (candidate.customType === COGNITIVE_ROUTING_CONTROL_ENTRY) {
167
+ const data = candidate.data;
168
+ if (
169
+ data &&
170
+ typeof data === "object" &&
171
+ (data.version === 1 || data.version === 2) &&
172
+ data.epoch === intent.epoch &&
173
+ data.control === "automatic"
174
+ ) {
175
+ return "automatic";
176
+ }
177
+ }
178
+ if (candidate.customType !== COGNITIVE_ROUTING_INTENT_ENTRY) continue;
179
+ const candidateIntent = asIntent(candidate.data);
180
+ if (!candidateIntent || candidateIntent.phase !== "prepared" || candidateIntent.epoch !== intent.epoch) continue;
181
+ if (candidateIntent.kind === "profile" || candidateIntent.kind === "activation") {
182
+ return controlModeForIntent(candidateIntent);
183
+ }
184
+ }
185
+ return "automatic";
186
+ }
187
+ function hasMatchingHostEntry(entries, intent) {
188
+ return entries.some((entry) => {
189
+ if (!entry || typeof entry !== "object") return false;
190
+ const candidate = entry;
191
+ return (
192
+ candidate.type === "model_state_change" &&
193
+ candidate.correlationId === intent.correlationId &&
194
+ pairEquals(asPair(candidate), intent.target)
195
+ );
196
+ });
197
+ }
198
+ export class CognitiveRoutingController {
199
+ capabilityState;
200
+ pi;
201
+ ctx;
202
+ label;
203
+ idFactory;
204
+ lease;
205
+ activeProfile;
206
+ epoch;
207
+ returnTarget;
208
+ controlMode = "automatic";
209
+ branchPending = false;
210
+ operation = Promise.resolve();
211
+ constructor(options) {
212
+ this.capabilityState = options.capabilityState;
213
+ this.pi = options.pi;
214
+ this.ctx = options.ctx;
215
+ this.label = options.label ?? "Cognitive Routing";
216
+ this.idFactory = options.idFactory ?? randomUUID;
217
+ }
218
+ state() {
219
+ const hostPair = latestHostPair(this.ctx);
220
+ const observedPair = hostPair ?? this.currentPair();
221
+ const observedProfile = this.activeProfile ? profileNameForPair(this.capabilityState, observedPair) : undefined;
222
+ const activeProfile = hostPair ? observedProfile : (observedProfile ?? this.activeProfile);
223
+ return {
224
+ effective: this.lease !== undefined && activeProfile !== undefined && !this.branchPending,
225
+ controlMode: this.controlMode,
226
+ ...(activeProfile ? { activeProfile } : {}),
227
+ ...(this.epoch ? { epoch: this.epoch } : {}),
228
+ ...(this.returnTarget ? { returnTarget: { ...this.returnTarget } } : {}),
229
+ };
230
+ }
231
+ history(options = {}) {
232
+ const state = this.state();
233
+ const current = {
234
+ control: state.effective ? (state.controlMode === "automatic" ? "automatic" : "manual") : "unavailable",
235
+ profile: state.effective && state.activeProfile ? state.activeProfile : "unavailable",
236
+ };
237
+ const profilePairs = {
238
+ ...(this.capabilityState.resolvedProfiles.standard
239
+ ? {
240
+ standard: {
241
+ provider: this.capabilityState.resolvedProfiles.standard.provider,
242
+ modelId: this.capabilityState.resolvedProfiles.standard.model,
243
+ thinkingLevel: this.capabilityState.resolvedProfiles.standard.effectiveThinkingLevel,
244
+ },
245
+ }
246
+ : {}),
247
+ ...(this.capabilityState.resolvedProfiles.reasoning
248
+ ? {
249
+ reasoning: {
250
+ provider: this.capabilityState.resolvedProfiles.reasoning.provider,
251
+ modelId: this.capabilityState.resolvedProfiles.reasoning.model,
252
+ thinkingLevel: this.capabilityState.resolvedProfiles.reasoning.effectiveThinkingLevel,
253
+ },
254
+ }
255
+ : {}),
256
+ };
257
+ return readCognitiveRoutingHistory(this.ctx, { ...options, current, profilePairs });
258
+ }
259
+ async activate() {
260
+ return this.enqueue(() => this._activate());
261
+ }
262
+ async deactivate() {
263
+ return this.enqueue(() => this._deactivate());
264
+ }
265
+ async shutdown(reason) {
266
+ return this.enqueue(() =>
267
+ reason === "quit" ? this._releaseWithoutRestore() : this._deactivate(reason === "reload"),
268
+ );
269
+ }
270
+ async recover() {
271
+ return this.enqueue(() => this._recover());
272
+ }
273
+ async reconcileBranch(mechanism = "session-tree") {
274
+ return this.enqueue(() => this._reconcileBranch(mechanism));
275
+ }
276
+ async _activate() {
277
+ if (this.state().effective && this.activeProfile) {
278
+ return { status: "active", profile: this.activeProfile };
279
+ }
280
+ if (!this.capabilityState.effective) {
281
+ return { status: "inactive", reason: "not_effective" };
282
+ }
283
+ const sessionEntries = entriesFrom(this.ctx);
284
+ const lifecycleIntent = latestIntent(
285
+ sessionEntries,
286
+ (intent) => intent.kind === "activation" || intent.kind === "closing",
287
+ );
288
+ if (lifecycleIntent && !hasMatchingHostEntry(sessionEntries, lifecycleIntent)) {
289
+ return { status: "inactive", reason: "pending_intent" };
290
+ }
291
+ if (lifecycleIntent?.kind === "activation") {
292
+ return { status: "inactive", reason: "recover_required" };
293
+ }
294
+ const preservedReload = lifecycleIntent?.kind === "closing" && lifecycleIntent.resumeProfile !== undefined;
295
+ if (preservedReload && !lifecycleIntent.resumeControl) {
296
+ return { status: "inactive", reason: "resume_state_invalid" };
297
+ }
298
+ const returnTarget = this.currentPair();
299
+ if (!returnTarget) {
300
+ return { status: "inactive", reason: "current_state_unavailable" };
301
+ }
302
+ const epoch = this.epoch ?? this.idFactory();
303
+ const branchId = this.currentBranchId();
304
+ const sessionStart = this.capabilityState.sessionStart ?? {
305
+ control: "automatic",
306
+ profile: "standard",
307
+ };
308
+ const profileName = preservedReload ? lifecycleIntent.resumeProfile : sessionStart.profile;
309
+ const profile = this.capabilityState.resolvedProfiles[profileName];
310
+ if (!profile) {
311
+ return { status: "inactive", reason: preservedReload ? "resume_profile_unavailable" : "profile_unavailable" };
312
+ }
313
+ let controlMode;
314
+ if (preservedReload) {
315
+ controlMode = lifecycleIntent.resumeControl === "manual" ? `manual-${profileName}` : "automatic";
316
+ } else {
317
+ controlMode = sessionStart.control === "manual" ? `manual-${profileName}` : "automatic";
318
+ }
319
+ const target = {
320
+ provider: profile.provider,
321
+ modelId: profile.model,
322
+ thinkingLevel: profile.effectiveThinkingLevel,
323
+ };
324
+ return this.activatePrepared({
325
+ kind: "activation",
326
+ controlMode,
327
+ source: "system",
328
+ mechanism: preservedReload ? "reload-restore" : "activation",
329
+ ...(preservedReload && lifecycleIntent.resumeReason ? { reason: lifecycleIntent.resumeReason } : {}),
330
+ epoch,
331
+ branchId,
332
+ returnTarget,
333
+ target,
334
+ profile: profileName,
335
+ });
336
+ }
337
+ async _releaseWithoutRestore() {
338
+ const lease = this.lease;
339
+ if (!lease) {
340
+ this.clearActiveState();
341
+ return { status: "inactive", reason: "not_active" };
342
+ }
343
+ await this.releaseLease(lease);
344
+ this.clearActiveState();
345
+ return { status: "inactive", reason: "released_on_quit" };
346
+ }
347
+ async _deactivate(preserveSemanticState = false) {
348
+ const lease = this.lease;
349
+ const returnTarget = this.returnTarget;
350
+ if (!lease || !returnTarget || !this.epoch) {
351
+ this.clearActiveState();
352
+ return { status: "inactive", reason: "not_active" };
353
+ }
354
+ const currentState = preserveSemanticState ? this.state() : undefined;
355
+ const resumeProfile = currentState?.effective ? currentState.activeProfile : undefined;
356
+ let resumeControl;
357
+ if (resumeProfile && currentState?.controlMode === "automatic") {
358
+ resumeControl = "automatic";
359
+ } else if (resumeProfile && currentState?.controlMode === `manual-${resumeProfile}`) {
360
+ resumeControl = "manual";
361
+ }
362
+ const resumeIntent = resumeProfile
363
+ ? latestIntent(
364
+ branchEntriesFrom(this.ctx),
365
+ (candidate) => candidate.kind === "profile" && candidate.epoch === this.epoch,
366
+ )
367
+ : undefined;
368
+ const fromPair = latestHostPair(this.ctx) ?? this.currentPair();
369
+ const fromProfile = this.activeProfile ?? profileNameForPair(this.capabilityState, fromPair);
370
+ const intent = this.prepareIntent({
371
+ kind: "closing",
372
+ control: "automatic",
373
+ source: "system",
374
+ mechanism: "shutdown-restore",
375
+ ...(fromPair ? { fromPair } : {}),
376
+ ...(fromProfile ? { fromProfile } : {}),
377
+ ...(resumeProfile ? { resumeProfile } : {}),
378
+ ...(resumeControl ? { resumeControl } : {}),
379
+ ...(resumeIntent?.reason ? { resumeReason: resumeIntent.reason } : {}),
380
+ epoch: this.epoch,
381
+ correlationId: this.idFactory(),
382
+ branchId: this.currentBranchId(),
383
+ target: returnTarget,
384
+ returnTarget,
385
+ });
386
+ try {
387
+ this.pi.appendEntryDurable(COGNITIVE_ROUTING_INTENT_ENTRY, intent);
388
+ } catch {
389
+ await this.releaseLease(lease);
390
+ this.clearActiveState();
391
+ return { status: "inactive", reason: "prepare_failed" };
392
+ }
393
+ this.clearActiveState(false);
394
+ try {
395
+ const result = await lease.setState({ ...returnTarget, correlationId: intent.correlationId });
396
+ if (result.status !== "applied" && result.status !== "unchanged") {
397
+ return { status: "inactive", reason: "restore_rejected" };
398
+ }
399
+ return { status: "inactive", reason: "restored" };
400
+ } catch {
401
+ return { status: "inactive", reason: "restore_failed" };
402
+ } finally {
403
+ await this.releaseLease(lease);
404
+ }
405
+ }
406
+ async _recover() {
407
+ const sessionEntries = entriesFrom(this.ctx);
408
+ const branchEntries = branchEntriesFrom(this.ctx);
409
+ const lifecycleIntent = latestIntent(
410
+ sessionEntries,
411
+ (intent) => intent.kind === "activation" || intent.kind === "closing",
412
+ );
413
+ if (!lifecycleIntent) {
414
+ return { status: "inactive", reason: "no_pending_intent" };
415
+ }
416
+ if (lifecycleIntent.kind === "closing") {
417
+ return hasMatchingHostEntry(sessionEntries, lifecycleIntent)
418
+ ? { status: "inactive", reason: "closed" }
419
+ : this.recoverClosingIntent(lifecycleIntent);
420
+ }
421
+ const currentActivationProfile = this.capabilityState.resolvedProfiles[lifecycleIntent.profile ?? "standard"];
422
+ if (!this.capabilityState.effective) {
423
+ return hasMatchingHostEntry(sessionEntries, lifecycleIntent)
424
+ ? { status: "inactive", reason: "not_effective" }
425
+ : this.abandonIntent(lifecycleIntent, "Cognitive Routing is not effective.");
426
+ }
427
+ if (!currentActivationProfile) {
428
+ return this.abandonIntent(lifecycleIntent, "Prepared profile is unavailable.");
429
+ }
430
+ const activationTarget = {
431
+ provider: currentActivationProfile.provider,
432
+ modelId: currentActivationProfile.model,
433
+ thinkingLevel: currentActivationProfile.effectiveThinkingLevel,
434
+ };
435
+ const activationMatched = hasMatchingHostEntry(sessionEntries, lifecycleIntent);
436
+ if (activationMatched && !pairEquals(activationTarget, lifecycleIntent.target)) {
437
+ return { status: "pending", reason: "applied_target_changed" };
438
+ }
439
+ if (!activationMatched && !pairEquals(activationTarget, lifecycleIntent.target)) {
440
+ return this.abandonIntent(lifecycleIntent, "Prepared profile target changed.");
441
+ }
442
+ if (!activationMatched) {
443
+ const retried = await this.activatePrepared({
444
+ kind: "activation",
445
+ controlMode: "automatic",
446
+ source: "system",
447
+ mechanism: "recovery",
448
+ branchId: this.currentBranchId(),
449
+ epoch: lifecycleIntent.epoch,
450
+ returnTarget: lifecycleIntent.returnTarget,
451
+ target: lifecycleIntent.target,
452
+ profile: lifecycleIntent.profile ?? "standard",
453
+ });
454
+ return retried.status === "active" ? retried : { status: "pending", reason: "activation_recovery_failed" };
455
+ }
456
+ const profileIntent = latestIntent(
457
+ branchEntries,
458
+ (intent) => intent.kind === "profile" && intent.epoch === lifecycleIntent.epoch,
459
+ );
460
+ if (profileIntent) {
461
+ const currentProfile = this.capabilityState.resolvedProfiles[profileIntent.profile ?? "standard"];
462
+ if (!currentProfile) {
463
+ return this.abandonIntent(profileIntent, "Prepared profile is unavailable.");
464
+ }
465
+ const profileTarget = {
466
+ provider: currentProfile.provider,
467
+ modelId: currentProfile.model,
468
+ thinkingLevel: currentProfile.effectiveThinkingLevel,
469
+ };
470
+ if (!pairEquals(profileTarget, profileIntent.target)) {
471
+ return hasMatchingHostEntry(branchEntries, profileIntent)
472
+ ? { status: "pending", reason: "applied_target_changed" }
473
+ : this.abandonIntent(profileIntent, "Prepared profile target changed.");
474
+ }
475
+ const profileMatched = hasMatchingHostEntry(branchEntries, profileIntent);
476
+ const retried = await this.activatePrepared({
477
+ kind: "profile",
478
+ controlMode: latestControlMode(branchEntries, profileIntent),
479
+ source: "system",
480
+ mechanism: "recovery",
481
+ ...(decisionCorrelationForIntent(profileIntent)
482
+ ? { decisionCorrelationId: decisionCorrelationForIntent(profileIntent) }
483
+ : {}),
484
+ branchId: this.currentBranchId(),
485
+ epoch: lifecycleIntent.epoch,
486
+ returnTarget: lifecycleIntent.returnTarget,
487
+ target: profileMatched ? profileTarget : profileIntent.target,
488
+ profile: profileIntent.profile ?? "standard",
489
+ });
490
+ return retried.status === "active" ? retried : { status: "pending", reason: "profile_recovery_failed" };
491
+ }
492
+ return this.activatePrepared({
493
+ kind: "activation",
494
+ controlMode: "automatic",
495
+ source: "system",
496
+ mechanism: "recovery",
497
+ branchId: this.currentBranchId(),
498
+ epoch: lifecycleIntent.epoch,
499
+ returnTarget: lifecycleIntent.returnTarget,
500
+ target: activationTarget,
501
+ profile: lifecycleIntent.profile ?? "standard",
502
+ });
503
+ }
504
+ async recoverClosingIntent(intent) {
505
+ const fromPair = latestHostPair(this.ctx) ?? this.currentPair();
506
+ const fromProfile = intent.fromProfile ?? profileNameForPair(this.capabilityState, fromPair);
507
+ const retryIntent = this.prepareIntent({
508
+ kind: "closing",
509
+ control: "automatic",
510
+ source: "system",
511
+ mechanism: "shutdown-restore",
512
+ ...(fromPair ? { fromPair } : {}),
513
+ ...(fromProfile ? { fromProfile } : {}),
514
+ reason: "Closing recovery",
515
+ ...(intent.resumeProfile ? { resumeProfile: intent.resumeProfile } : {}),
516
+ ...(intent.resumeControl ? { resumeControl: intent.resumeControl } : {}),
517
+ ...(intent.resumeReason ? { resumeReason: intent.resumeReason } : {}),
518
+ branchId: this.currentBranchId(),
519
+ epoch: intent.epoch,
520
+ correlationId: this.idFactory(),
521
+ target: intent.target,
522
+ returnTarget: intent.returnTarget,
523
+ });
524
+ try {
525
+ this.pi.appendEntryDurable(COGNITIVE_ROUTING_INTENT_ENTRY, retryIntent);
526
+ } catch {
527
+ return { status: "pending", reason: "closing_recovery_prepare_failed" };
528
+ }
529
+ let acquisition;
530
+ try {
531
+ acquisition = await this.pi.acquireModelStateControl({ label: this.label });
532
+ } catch {
533
+ return { status: "pending", reason: "closing_recovery_acquire_failed" };
534
+ }
535
+ if (acquisition.status !== "acquired") {
536
+ return { status: "pending", reason: `closing_recovery_acquire_${acquisition.status}` };
537
+ }
538
+ try {
539
+ const result = await acquisition.lease.setState({ ...intent.target, correlationId: retryIntent.correlationId });
540
+ return result.status === "applied" || result.status === "unchanged"
541
+ ? { status: "inactive", reason: "restored" }
542
+ : { status: "pending", reason: "closing_recovery_rejected" };
543
+ } catch {
544
+ return { status: "pending", reason: "closing_recovery_failed" };
545
+ } finally {
546
+ await this.releaseLease(acquisition.lease);
547
+ }
548
+ }
549
+ async abandonIntent(intent, reason) {
550
+ try {
551
+ const fromPair = intent.fromPair ?? latestHostPair(this.ctx) ?? this.currentPair();
552
+ const fromProfile = intent.fromProfile ?? profileNameForPair(this.capabilityState, fromPair);
553
+ this.pi.appendEntryDurable(COGNITIVE_ROUTING_INTENT_ENTRY, {
554
+ ...intent,
555
+ version: 2,
556
+ phase: "abandoned",
557
+ source: "system",
558
+ mechanism: intent.mechanism ?? "recovery",
559
+ ...(fromPair ? { fromPair } : {}),
560
+ ...(fromProfile ? { fromProfile } : {}),
561
+ reason,
562
+ });
563
+ const recovered = await this._recover();
564
+ return recovered.status === "inactive" && recovered.reason === "no_pending_intent"
565
+ ? { status: "inactive", reason: "intent_abandoned" }
566
+ : recovered;
567
+ } catch {
568
+ return { status: "pending", reason: "intent_abandon_failed" };
569
+ }
570
+ }
571
+ async _reconcileBranch(mechanism) {
572
+ if (!this.capabilityState.effective) return { status: "inactive", reason: "not_effective" };
573
+ if (!this.activeProfile || !this.lease) {
574
+ return { status: "inactive", reason: "not_active" };
575
+ }
576
+ const currentProfile = this.activeProfile;
577
+ const sessionEntries = entriesFrom(this.ctx);
578
+ const lifecycleIntent = latestIntent(
579
+ sessionEntries,
580
+ (intent) => intent.kind === "activation" || intent.kind === "closing",
581
+ );
582
+ if (lifecycleIntent?.kind === "closing") {
583
+ this.branchPending = true;
584
+ return hasMatchingHostEntry(sessionEntries, lifecycleIntent)
585
+ ? { status: "inactive", reason: "closed" }
586
+ : { status: "pending", reason: "closing_intent_unmatched" };
587
+ }
588
+ if (lifecycleIntent && !hasMatchingHostEntry(sessionEntries, lifecycleIntent)) {
589
+ this.branchPending = true;
590
+ return { status: "pending", reason: "activation_intent_unmatched" };
591
+ }
592
+ const entries = branchEntriesFrom(this.ctx);
593
+ const intent = latestIntent(
594
+ entries,
595
+ (candidate) => candidate.kind === "profile" && candidate.epoch === lifecycleIntent?.epoch,
596
+ );
597
+ if (!intent) {
598
+ this.branchPending = false;
599
+ return { status: "active", profile: currentProfile };
600
+ }
601
+ if (!hasMatchingHostEntry(entries, intent)) {
602
+ this.branchPending = true;
603
+ return { status: "pending", reason: "branch_intent_unmatched" };
604
+ }
605
+ const decisionCorrelationId = decisionCorrelationForIntent(intent);
606
+ if (intent.source === "system" && !decisionCorrelationId) {
607
+ this.branchPending = false;
608
+ return { status: "active", profile: currentProfile };
609
+ }
610
+ if (!intent.profile) {
611
+ this.branchPending = false;
612
+ return { status: "active", profile: currentProfile };
613
+ }
614
+ const controlMode = latestControlMode(entries, intent);
615
+ if (this.activeProfile === intent.profile && this.controlMode === controlMode) {
616
+ this.branchPending = false;
617
+ return { status: "active", profile: intent.profile };
618
+ }
619
+ const result = await this._setProfile(intent.profile, {
620
+ controlMode,
621
+ source: "system",
622
+ mechanism,
623
+ ...(decisionCorrelationId ? { decisionCorrelationId } : {}),
624
+ reason: "Branch reconciliation",
625
+ });
626
+ this.branchPending = result.status !== "active";
627
+ return result;
628
+ }
629
+ async setManualProfile(profile, mechanism = "profile-command") {
630
+ return this.enqueue(() => this._setManualProfile(profile, mechanism));
631
+ }
632
+ async setAutomaticControl(mechanism = "profile-command") {
633
+ return this.enqueue(() => this._setAutomaticControl(mechanism));
634
+ }
635
+ async switchAutomaticProfile(profile, reason, source = "agent", mechanism = "agent-tool") {
636
+ return this.enqueue(() => this._switchAutomaticProfile(profile, reason, source, mechanism));
637
+ }
638
+ async _setManualProfile(profile, mechanism) {
639
+ if (!this.capabilityState.effective) {
640
+ return { status: "inactive", reason: "not_effective" };
641
+ }
642
+ const activation = this.state().effective ? { status: "active" } : await this._activate();
643
+ if (activation.status !== "active") return activation;
644
+ return this._setProfile(profile, {
645
+ controlMode: `manual-${profile}`,
646
+ source: "user",
647
+ mechanism,
648
+ reason: "manual profile command",
649
+ });
650
+ }
651
+ async _switchAutomaticProfile(profile, reason, source, mechanism) {
652
+ if (!this.capabilityState.effective) return { status: "blocked", reason: "not_effective" };
653
+ const current = this.state();
654
+ if (!current.effective) return { status: "blocked", reason: "not_active" };
655
+ if (this.controlMode !== "automatic") return { status: "blocked", reason: "manual_hold" };
656
+ const from = current.activeProfile;
657
+ if (!from) return { status: "blocked", reason: "profile_unknown" };
658
+ if (from === profile) return { status: "active", changed: false, from, to: profile, profile };
659
+ const transition = await this._setProfile(profile, { controlMode: "automatic", source, reason, mechanism });
660
+ if (transition.status !== "active") return transition;
661
+ return { status: "active", changed: true, from, to: transition.profile, profile: transition.profile };
662
+ }
663
+ async _setProfile(profile, options) {
664
+ const resolvedProfile = this.capabilityState.resolvedProfiles[profile];
665
+ const lease = this.lease;
666
+ if (!resolvedProfile || !lease || !this.epoch || !this.returnTarget) {
667
+ return { status: "inactive", reason: "profile_unavailable" };
668
+ }
669
+ const target = {
670
+ provider: resolvedProfile.provider,
671
+ modelId: resolvedProfile.model,
672
+ thinkingLevel: resolvedProfile.effectiveThinkingLevel,
673
+ };
674
+ const fromPair = latestHostPair(this.ctx) ?? this.currentPair();
675
+ if (!fromPair) return { status: "inactive", reason: "current_state_unavailable" };
676
+ const fromProfile = this.activeProfile ?? profileNameForPair(this.capabilityState, fromPair);
677
+ const correlationId = this.idFactory();
678
+ const decisionCorrelationId =
679
+ options.decisionCorrelationId ??
680
+ (options.source === "user" || options.source === "agent" ? correlationId : undefined);
681
+ const intent = this.prepareIntent({
682
+ kind: "profile",
683
+ control: options.controlMode === "automatic" ? "automatic" : "manual",
684
+ source: options.source,
685
+ mechanism: options.mechanism,
686
+ ...(decisionCorrelationId ? { decisionCorrelationId } : {}),
687
+ ...(fromPair ? { fromPair } : {}),
688
+ ...(fromProfile ? { fromProfile } : {}),
689
+ reason: options.reason,
690
+ branchId: this.currentBranchId(),
691
+ epoch: this.epoch,
692
+ correlationId,
693
+ profile,
694
+ target,
695
+ returnTarget: this.returnTarget,
696
+ });
697
+ const sessionEntries = entriesFrom(this.ctx);
698
+ const lifecycleIntent = latestIntent(
699
+ sessionEntries,
700
+ (candidate) => candidate.kind === "activation" || candidate.kind === "closing",
701
+ );
702
+ if (lifecycleIntent && !hasMatchingHostEntry(sessionEntries, lifecycleIntent)) {
703
+ return { status: "inactive", reason: "pending_intent" };
704
+ }
705
+ const entries = branchEntriesFrom(this.ctx);
706
+ const latest = latestIntent(entries, (candidate) => candidate.kind === "profile" && candidate.epoch === this.epoch);
707
+ if (latest && !hasMatchingHostEntry(entries, latest)) {
708
+ return { status: "inactive", reason: "pending_intent" };
709
+ }
710
+ try {
711
+ this.pi.appendEntryDurable(COGNITIVE_ROUTING_INTENT_ENTRY, intent);
712
+ this.branchPending = true;
713
+ } catch {
714
+ return { status: "inactive", reason: "prepare_failed" };
715
+ }
716
+ try {
717
+ const result = await lease.setState({ ...target, correlationId: intent.correlationId });
718
+ if (result.status !== "applied" && result.status !== "unchanged") {
719
+ return { status: "inactive", reason: "transition_rejected" };
720
+ }
721
+ this.activeProfile = profile;
722
+ this.controlMode = options.controlMode;
723
+ this.branchPending = false;
724
+ return { status: "active", profile };
725
+ } catch {
726
+ return { status: "inactive", reason: "transition_failed" };
727
+ }
728
+ }
729
+ async _setAutomaticControl(mechanism) {
730
+ if (!this.lease || !this.epoch) {
731
+ return { status: "rejected", reason: "not_active" };
732
+ }
733
+ try {
734
+ this.pi.appendEntryDurable(COGNITIVE_ROUTING_CONTROL_ENTRY, {
735
+ version: 2,
736
+ control: "automatic",
737
+ source: "user",
738
+ mechanism,
739
+ reason: "manual hold release",
740
+ branchId: this.currentBranchId(),
741
+ epoch: this.epoch,
742
+ });
743
+ } catch {
744
+ return { status: "rejected", reason: "prepare_failed" };
745
+ }
746
+ this.controlMode = "automatic";
747
+ return { status: "automatic" };
748
+ }
749
+ currentBranchId() {
750
+ const leafId = this.ctx.sessionManager?.getLeafId?.();
751
+ if (typeof leafId === "string" || leafId === null) return leafId;
752
+ try {
753
+ const branch = this.ctx.sessionManager?.getBranch?.();
754
+ const last = Array.isArray(branch) ? branch.at(-1) : undefined;
755
+ return last && typeof last === "object" && typeof last.id === "string" ? last.id : undefined;
756
+ } catch {
757
+ return undefined;
758
+ }
759
+ }
760
+ currentPair() {
761
+ const model = this.ctx.model;
762
+ if (
763
+ !model ||
764
+ typeof model.provider !== "string" ||
765
+ typeof model.id !== "string" ||
766
+ typeof this.ctx.thinkingLevel !== "string"
767
+ ) {
768
+ return undefined;
769
+ }
770
+ return {
771
+ provider: model.provider,
772
+ modelId: model.id,
773
+ thinkingLevel: this.ctx.thinkingLevel,
774
+ };
775
+ }
776
+ prepareIntent(input) {
777
+ return { version: 2, phase: "prepared", ...input };
778
+ }
779
+ async activatePrepared(options) {
780
+ const fromPair = latestHostPair(this.ctx) ?? this.currentPair();
781
+ if (!fromPair) return { status: "inactive", reason: "current_state_unavailable" };
782
+ const fromProfile = profileNameForPair(this.capabilityState, fromPair);
783
+ const correlationId = this.idFactory();
784
+ const decisionCorrelationId =
785
+ options.decisionCorrelationId ??
786
+ (options.source === "user" || options.source === "agent" ? correlationId : undefined);
787
+ const intent = this.prepareIntent({
788
+ kind: options.kind,
789
+ control: options.controlMode === "automatic" ? "automatic" : "manual",
790
+ source: options.source,
791
+ mechanism: options.mechanism,
792
+ ...(decisionCorrelationId ? { decisionCorrelationId } : {}),
793
+ ...(fromPair ? { fromPair } : {}),
794
+ ...(fromProfile ? { fromProfile } : {}),
795
+ ...(options.reason ? { reason: options.reason } : {}),
796
+ ...(options.branchId === undefined ? {} : { branchId: options.branchId }),
797
+ epoch: options.epoch,
798
+ correlationId,
799
+ profile: options.profile,
800
+ target: options.target,
801
+ returnTarget: options.returnTarget,
802
+ });
803
+ try {
804
+ this.pi.appendEntryDurable(COGNITIVE_ROUTING_INTENT_ENTRY, intent);
805
+ } catch {
806
+ return { status: "inactive", reason: "prepare_failed" };
807
+ }
808
+ let acquisition;
809
+ try {
810
+ acquisition = await this.pi.acquireModelStateControl({ label: this.label });
811
+ } catch {
812
+ return { status: "inactive", reason: "acquire_failed" };
813
+ }
814
+ if (acquisition.status !== "acquired") {
815
+ return { status: "inactive", reason: `acquire_${acquisition.status}` };
816
+ }
817
+ this.lease = acquisition.lease;
818
+ try {
819
+ const result = await acquisition.lease.setState({ ...options.target, correlationId: intent.correlationId });
820
+ if (result.status !== "applied" && result.status !== "unchanged") {
821
+ await this.releaseLease(acquisition.lease);
822
+ this.clearActiveState();
823
+ return { status: "inactive", reason: "transition_rejected" };
824
+ }
825
+ this.epoch = options.epoch;
826
+ this.returnTarget = options.returnTarget;
827
+ this.activeProfile = options.profile;
828
+ this.controlMode = options.controlMode;
829
+ return { status: "active", profile: options.profile };
830
+ } catch {
831
+ await this.releaseLease(acquisition.lease);
832
+ this.clearActiveState();
833
+ return { status: "inactive", reason: "transition_failed" };
834
+ }
835
+ }
836
+ enqueue(operation) {
837
+ const next = this.operation.then(operation, operation);
838
+ this.operation = next.then(
839
+ () => undefined,
840
+ () => undefined,
841
+ );
842
+ return next;
843
+ }
844
+ async releaseLease(lease) {
845
+ try {
846
+ await lease.release();
847
+ } catch {
848
+ // The host invalidates stale leases independently; do not retain local ownership after cleanup.
849
+ }
850
+ if (this.lease === lease) this.lease = undefined;
851
+ }
852
+ clearActiveState(clearReturnTarget = true) {
853
+ this.lease = undefined;
854
+ this.activeProfile = undefined;
855
+ this.controlMode = "automatic";
856
+ this.branchPending = false;
857
+ if (clearReturnTarget) {
858
+ this.epoch = undefined;
859
+ this.returnTarget = undefined;
860
+ }
861
+ }
862
+ }