@hassangameryt/freeflow 0.5.0 → 0.7.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 (301) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +2 -2
  3. package/.codex-plugin/plugin.json +4 -5
  4. package/README.md +141 -163
  5. package/capabilities/cognitive-routing/SKILL.md +387 -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 -37
  9. package/hooks/freeflow-runtime-context.mjs +50 -541
  10. package/hooks/hooks.json +1 -26
  11. package/hooks/tests/check-runtime-context-hook.sh +114 -308
  12. package/package.json +27 -17
  13. package/pi-extension/dist/cognitive-routing/commands.js +96 -0
  14. package/pi-extension/dist/cognitive-routing/config.js +232 -0
  15. package/pi-extension/dist/cognitive-routing/controller.js +1292 -0
  16. package/pi-extension/dist/cognitive-routing/history.js +451 -0
  17. package/pi-extension/dist/cognitive-routing/host.js +188 -0
  18. package/pi-extension/dist/cognitive-routing/pi-routing-session.js +414 -0
  19. package/pi-extension/dist/cognitive-routing/pi-session-control.js +320 -0
  20. package/pi-extension/dist/cognitive-routing/runtime.js +43 -0
  21. package/pi-extension/dist/cognitive-routing/tool.js +212 -0
  22. package/pi-extension/dist/cognitive-routing/types.js +6 -0
  23. package/pi-extension/dist/context-virtualization/commands.js +89 -0
  24. package/pi-extension/dist/context-virtualization/projector.js +42 -0
  25. package/pi-extension/dist/context-virtualization/runtime.js +356 -0
  26. package/pi-extension/dist/context-virtualization/state.js +57 -0
  27. package/pi-extension/dist/context-virtualization/types.js +10 -0
  28. package/pi-extension/dist/conversation-history/passages.js +66 -0
  29. package/pi-extension/dist/conversation-history/ranking.js +105 -0
  30. package/pi-extension/dist/conversation-history/runtime.js +226 -0
  31. package/pi-extension/dist/conversation-history/search.js +56 -0
  32. package/pi-extension/dist/conversation-history/types.js +1 -0
  33. package/pi-extension/dist/freeflow-context/resolver.js +120 -0
  34. package/pi-extension/dist/freeflow-context/runtime.js +80 -0
  35. package/pi-extension/dist/freeflow-context/source-projector.js +95 -0
  36. package/pi-extension/dist/freeflow-context/tool.js +308 -0
  37. package/pi-extension/dist/freeflow-context/types.js +12 -0
  38. package/pi-extension/dist/freeflow-context/visibility.js +28 -0
  39. package/pi-extension/dist/index.js +564 -129
  40. package/pi-extension/dist/runtime/runtime-context.js +357 -470
  41. package/pi-extension/dist/runtime/runtime-identity.js +5 -0
  42. package/pi-extension/dist/settings/settings-tui.js +78 -0
  43. package/pi-extension/dist/settings/settings-ui.js +572 -826
  44. package/pi-extension/dist/ui/text-component.js +57 -0
  45. package/pi-extension/src/cognitive-routing/commands.ts +129 -0
  46. package/pi-extension/src/cognitive-routing/config.ts +303 -0
  47. package/pi-extension/src/cognitive-routing/controller.ts +1628 -0
  48. package/pi-extension/src/cognitive-routing/history.ts +650 -0
  49. package/pi-extension/src/cognitive-routing/host.ts +266 -0
  50. package/pi-extension/src/cognitive-routing/pi-routing-session.ts +538 -0
  51. package/pi-extension/src/cognitive-routing/pi-session-control.ts +444 -0
  52. package/pi-extension/src/cognitive-routing/runtime.ts +57 -0
  53. package/pi-extension/src/cognitive-routing/tool.ts +273 -0
  54. package/pi-extension/src/cognitive-routing/types.ts +89 -0
  55. package/pi-extension/src/context-virtualization/commands.ts +111 -0
  56. package/pi-extension/src/context-virtualization/projector.ts +62 -0
  57. package/pi-extension/src/context-virtualization/runtime.ts +406 -0
  58. package/pi-extension/src/context-virtualization/state.ts +79 -0
  59. package/pi-extension/src/context-virtualization/types.ts +92 -0
  60. package/pi-extension/src/conversation-history/passages.ts +81 -0
  61. package/pi-extension/src/conversation-history/ranking.ts +155 -0
  62. package/pi-extension/src/conversation-history/runtime.ts +250 -0
  63. package/pi-extension/src/conversation-history/search.ts +79 -0
  64. package/pi-extension/src/conversation-history/types.ts +31 -0
  65. package/pi-extension/src/freeflow-context/resolver.ts +139 -0
  66. package/pi-extension/src/freeflow-context/runtime.ts +100 -0
  67. package/pi-extension/src/freeflow-context/source-projector.ts +106 -0
  68. package/pi-extension/src/freeflow-context/tool.ts +360 -0
  69. package/pi-extension/src/freeflow-context/types.ts +70 -0
  70. package/pi-extension/src/freeflow-context/visibility.ts +53 -0
  71. package/pi-extension/src/index.ts +597 -135
  72. package/pi-extension/src/runtime/runtime-context.ts +373 -491
  73. package/pi-extension/src/runtime/runtime-identity.ts +8 -0
  74. package/pi-extension/src/settings/settings-tui.ts +93 -0
  75. package/pi-extension/src/settings/settings-ui.ts +679 -910
  76. package/pi-extension/src/ui/text-component.ts +66 -0
  77. package/pi-extension/tests/cognitive-routing/commands.test.js +134 -0
  78. package/pi-extension/tests/cognitive-routing/controller.test.js +1128 -0
  79. package/pi-extension/tests/cognitive-routing/extension-lifecycle.test.js +1142 -0
  80. package/pi-extension/tests/cognitive-routing/history.test.js +274 -0
  81. package/pi-extension/tests/cognitive-routing/host-fixture.js +4 -0
  82. package/pi-extension/tests/cognitive-routing/host-identity.test.js +63 -0
  83. package/pi-extension/tests/cognitive-routing/pi-normal-lifecycle.test.js +434 -0
  84. package/pi-extension/tests/cognitive-routing/pi-session-control.test.js +174 -0
  85. package/pi-extension/tests/cognitive-routing/pi-session-history.test.js +91 -0
  86. package/pi-extension/tests/cognitive-routing/profile-resolution.test.js +279 -0
  87. package/pi-extension/tests/cognitive-routing/tool.test.js +230 -0
  88. package/pi-extension/tests/context-virtualization/extension.test.js +749 -0
  89. package/pi-extension/tests/context-virtualization/projector.test.js +110 -0
  90. package/pi-extension/tests/context-virtualization/runtime.test.js +216 -0
  91. package/pi-extension/tests/conversation-history/runtime.test.js +98 -0
  92. package/pi-extension/tests/conversation-history/search.test.js +97 -0
  93. package/pi-extension/tests/integration/mode-free-core.test.js +218 -0
  94. package/pi-extension/tests/integration/pi-extension.test.js +532 -3701
  95. package/pi-extension/tests/integration/prompt-architecture.test.js +350 -0
  96. package/pi-extension/tests/integration/unaffected-regressions.test.js +411 -0
  97. package/runtime/prompts/cognitive-routing.md +10 -0
  98. package/runtime/prompts/context-virtualization.md +3 -0
  99. package/runtime/prompts/conversation-history.md +3 -0
  100. package/runtime/prompts/core.md +84 -0
  101. package/runtime/prompts/interaction-contract.md +11 -0
  102. package/skills/action-selection/SKILL.md +140 -0
  103. package/skills/action-selection/references/trajectory-stalls.md +71 -0
  104. package/skills/bypass/SKILL.md +109 -38
  105. package/skills/commit-work/SKILL.md +94 -55
  106. package/skills/commit-work/references/git-state-edges.md +94 -0
  107. package/skills/commit-work/references/simple-push.md +92 -0
  108. package/skills/commit-work/references/staging-decisions.md +79 -46
  109. package/skills/decision-gate/SKILL.md +80 -22
  110. package/skills/design-for-depth/SKILL.md +206 -60
  111. package/skills/design-for-depth/references/design-pressure-signals.md +108 -240
  112. package/skills/design-for-depth/references/interface-design-loop.md +77 -97
  113. package/skills/design-for-depth/references/module-and-dependency-design.md +147 -0
  114. package/skills/design-for-depth/references/software-design-philosophy.md +128 -174
  115. package/skills/design-for-depth/references/state-and-failure-boundaries.md +136 -0
  116. package/skills/diagnose-failure/SKILL.md +200 -48
  117. package/skills/diagnose-failure/references/diagnostic-loop-catalog.md +18 -6
  118. package/skills/diagnose-failure/references/{flaky-and-performance.md → flaky-and-performance-diagnosis.md} +13 -5
  119. package/skills/discuss/SKILL.md +119 -65
  120. package/skills/discuss/references/discussion-continuity.md +123 -0
  121. package/skills/evaluate-skill/SKILL.md +166 -52
  122. package/skills/evaluate-skill/references/{definition-schema.md → evaluation-definition-schema.md} +43 -3
  123. package/skills/evaluate-skill/references/evaluation-design.md +56 -30
  124. package/skills/evaluate-skill/references/execution-and-evidence.md +8 -3
  125. package/skills/evaluate-skill/references/review-and-revision.md +62 -21
  126. package/skills/evaluate-skill/scripts/lib/definitions.mjs +114 -3
  127. package/skills/evaluate-skill/scripts/lib/grade-interaction.mjs +156 -1
  128. package/skills/evaluate-skill/scripts/lib/grade.mjs +9 -1
  129. package/skills/evaluate-skill/scripts/lib/pi.mjs +147 -32
  130. package/skills/evaluate-skill/scripts/lib/rpc.mjs +4 -4
  131. package/skills/evaluate-skill/scripts/lib/runner.mjs +36 -14
  132. package/skills/evaluate-skill/scripts/lib/sandbox.mjs +92 -0
  133. package/skills/evaluate-skill/scripts/pi-guard.mjs +1 -1
  134. package/skills/evaluate-skill/scripts/pi-observer.mjs +66 -0
  135. package/skills/evaluate-skill/scripts/skill-eval.mjs +6 -5
  136. package/skills/execute-work/SKILL.md +99 -57
  137. package/skills/execute-work/references/code-practices.md +4 -4
  138. package/skills/execute-work/references/execute-work-edges.md +62 -0
  139. package/skills/finish-branch/SKILL.md +2 -2
  140. package/skills/finish-branch/references/integration-options.md +1 -1
  141. package/skills/handoff/SKILL.md +3 -3
  142. package/skills/launch-work/SKILL.md +1 -1
  143. package/skills/launch-work/references/launch-readiness.md +2 -2
  144. package/skills/migration-work/SKILL.md +2 -2
  145. package/skills/migration-work/references/migration-lifecycle.md +1 -1
  146. package/skills/release-work/SKILL.md +1 -1
  147. package/skills/release-work/references/release-evidence.md +1 -1
  148. package/skills/review-artifact/SKILL.md +129 -66
  149. package/skills/review-artifact/references/adjudicate-artifact-review.md +101 -0
  150. package/skills/review-artifact/references/independent-artifact-reviewer-contract.md +159 -0
  151. package/skills/review-work/SKILL.md +113 -68
  152. package/skills/review-work/references/adjudicate-work-review.md +97 -0
  153. package/skills/review-work/references/independent-work-reviewer-contract.md +139 -0
  154. package/skills/review-work/references/security-risk-lens.md +18 -16
  155. package/skills/setup-freeflow/SKILL.md +16 -17
  156. package/skills/setup-freeflow/references/activation-contract.md +24 -30
  157. package/skills/setup-freeflow/references/host-setup.md +6 -7
  158. package/skills/simplify-code/SKILL.md +97 -39
  159. package/skills/simplify-code/references/simplification-patterns.md +1 -1
  160. package/skills/tdd/SKILL.md +100 -53
  161. package/skills/tdd/references/test-design.md +3 -3
  162. package/skills/track-work/SKILL.md +195 -58
  163. package/skills/track-work/references/working-record-format.md +515 -0
  164. package/skills/track-work/scripts/lib/document.mjs +713 -0
  165. package/skills/track-work/scripts/lib/format.mjs +166 -0
  166. package/skills/track-work/scripts/lib/store.mjs +233 -0
  167. package/skills/track-work/scripts/lib/transitions.mjs +790 -0
  168. package/skills/track-work/scripts/lib/views.mjs +40 -0
  169. package/skills/track-work/scripts/working-record.mjs +316 -0
  170. package/skills/verify-work/SKILL.md +57 -19
  171. package/skills/verify-work/references/browser-runtime-evidence.md +2 -2
  172. package/skills/verify-work/references/integration-evidence.md +1 -7
  173. package/skills/verify-work/references/performance-evidence.md +2 -2
  174. package/skills/workflow/SKILL.md +137 -55
  175. package/skills/workflow/references/domain-skill-composition.md +26 -40
  176. package/skills/write-plan/SKILL.md +1 -1
  177. package/skills/write-skill/SKILL.md +218 -61
  178. package/skills/write-skill/references/activation-boundaries.md +63 -21
  179. package/skills/write-skill/references/agent-first-instructions.md +61 -27
  180. package/skills/write-skill/references/progressive-disclosure.md +97 -33
  181. package/skills/write-skill/references/skill-dependency-graphs.md +190 -0
  182. package/capabilities/output-router/SKILL.md +0 -206
  183. package/capabilities/output-router/references/safety-policy.md +0 -40
  184. package/capabilities/output-router/references/setup.md +0 -110
  185. package/pi-extension/dist/output-router/host-producer-identification.js +0 -232
  186. package/pi-extension/dist/output-router/native-safety-net.js +0 -216
  187. package/pi-extension/dist/output-router/observed-tool-routing.js +0 -122
  188. package/pi-extension/dist/output-router/renderers.js +0 -1023
  189. package/pi-extension/dist/output-router/router-tools.js +0 -554
  190. package/pi-extension/dist/output-router/schemas.js +0 -383
  191. package/pi-extension/dist/output-router/status.js +0 -744
  192. package/pi-extension/dist/output-router/utils.js +0 -502
  193. package/pi-extension/src/output-router/host-producer-identification.ts +0 -256
  194. package/pi-extension/src/output-router/native-safety-net.ts +0 -248
  195. package/pi-extension/src/output-router/observed-tool-routing.ts +0 -134
  196. package/pi-extension/src/output-router/renderers.ts +0 -1108
  197. package/pi-extension/src/output-router/router-tools.ts +0 -579
  198. package/pi-extension/src/output-router/schemas.ts +0 -387
  199. package/pi-extension/src/output-router/status.ts +0 -791
  200. package/pi-extension/src/output-router/utils.ts +0 -554
  201. package/pi-extension/tests/output-router/observed-producers.test.js +0 -132
  202. package/pi-extension/tests/output-router/search.test.js +0 -722
  203. package/router/dist/benchmarks/benchmark-harness.d.ts +0 -35
  204. package/router/dist/benchmarks/benchmark-harness.js +0 -92
  205. package/router/dist/benchmarks/benchmarks.d.ts +0 -109
  206. package/router/dist/benchmarks/benchmarks.js +0 -979
  207. package/router/dist/benchmarks/codex-qa-benchmarks.d.ts +0 -95
  208. package/router/dist/benchmarks/codex-qa-benchmarks.js +0 -500
  209. package/router/dist/benchmarks/command-benchmarks.d.ts +0 -143
  210. package/router/dist/benchmarks/command-benchmarks.js +0 -698
  211. package/router/dist/benchmarks/context-mode-normalized-benchmarks.d.ts +0 -82
  212. package/router/dist/benchmarks/context-mode-normalized-benchmarks.js +0 -773
  213. package/router/dist/benchmarks/context-mode-real-deep-benchmark.d.ts +0 -132
  214. package/router/dist/benchmarks/context-mode-real-deep-benchmark.js +0 -1380
  215. package/router/dist/benchmarks/context-saving-baseline.d.ts +0 -60
  216. package/router/dist/benchmarks/context-saving-baseline.js +0 -470
  217. package/router/dist/benchmarks/index-benchmarks.d.ts +0 -103
  218. package/router/dist/benchmarks/index-benchmarks.js +0 -862
  219. package/router/dist/benchmarks/storage-policy-benchmarks.d.ts +0 -101
  220. package/router/dist/benchmarks/storage-policy-benchmarks.js +0 -618
  221. package/router/dist/benchmarks/vault-index-benchmarks.d.ts +0 -56
  222. package/router/dist/benchmarks/vault-index-benchmarks.js +0 -322
  223. package/router/dist/config/config.d.ts +0 -103
  224. package/router/dist/config/config.js +0 -632
  225. package/router/dist/config/router-contract.d.ts +0 -10
  226. package/router/dist/config/router-contract.js +0 -54
  227. package/router/dist/config/schema.d.ts +0 -27
  228. package/router/dist/config/schema.js +0 -648
  229. package/router/dist/config/types.d.ts +0 -573
  230. package/router/dist/config/types.js +0 -41
  231. package/router/dist/evidence/bounded-evidence.d.ts +0 -40
  232. package/router/dist/evidence/bounded-evidence.js +0 -323
  233. package/router/dist/evidence/evidence-range-selector.d.ts +0 -24
  234. package/router/dist/evidence/evidence-range-selector.js +0 -232
  235. package/router/dist/evidence/evidence-search.d.ts +0 -27
  236. package/router/dist/evidence/evidence-search.js +0 -490
  237. package/router/dist/evidence/evidence.d.ts +0 -38
  238. package/router/dist/evidence/evidence.js +0 -200
  239. package/router/dist/evidence/failure-contracts.d.ts +0 -37
  240. package/router/dist/evidence/failure-contracts.js +0 -166
  241. package/router/dist/evidence/line-ranges.d.ts +0 -24
  242. package/router/dist/evidence/line-ranges.js +0 -22
  243. package/router/dist/experiments/local-index.d.ts +0 -64
  244. package/router/dist/experiments/local-index.js +0 -581
  245. package/router/dist/index.d.ts +0 -30
  246. package/router/dist/index.js +0 -32
  247. package/router/dist/local/local-traversal.d.ts +0 -18
  248. package/router/dist/local/local-traversal.js +0 -334
  249. package/router/dist/processing/engine.d.ts +0 -132
  250. package/router/dist/processing/engine.js +0 -533
  251. package/router/dist/processing/reducers.d.ts +0 -280
  252. package/router/dist/processing/reducers.js +0 -1673
  253. package/router/dist/processing/renderers.d.ts +0 -31
  254. package/router/dist/processing/renderers.js +0 -195
  255. package/router/dist/processing/scripts.d.ts +0 -91
  256. package/router/dist/processing/scripts.js +0 -386
  257. package/router/dist/repo/repo-traversal.d.ts +0 -18
  258. package/router/dist/repo/repo-traversal.js +0 -245
  259. package/router/dist/routing/observed-reducers.d.ts +0 -41
  260. package/router/dist/routing/observed-reducers.js +0 -661
  261. package/router/dist/routing/observed-routing.d.ts +0 -26
  262. package/router/dist/routing/observed-routing.js +0 -378
  263. package/router/dist/routing/parsers.d.ts +0 -16
  264. package/router/dist/routing/parsers.js +0 -521
  265. package/router/dist/routing/run-filters.d.ts +0 -60
  266. package/router/dist/routing/run-filters.js +0 -238
  267. package/router/dist/routing/run-reducers.d.ts +0 -49
  268. package/router/dist/routing/run-reducers.js +0 -122
  269. package/router/dist/sandbox/adapter-roots.d.ts +0 -46
  270. package/router/dist/sandbox/adapter-roots.js +0 -66
  271. package/router/dist/sandbox/eryx-python-adapter.d.ts +0 -13
  272. package/router/dist/sandbox/eryx-python-adapter.js +0 -868
  273. package/router/dist/sandbox/jq-wasm-adapter.d.ts +0 -9
  274. package/router/dist/sandbox/jq-wasm-adapter.js +0 -429
  275. package/router/dist/sandbox/quickjs-wasi-adapter.d.ts +0 -13
  276. package/router/dist/sandbox/quickjs-wasi-adapter.js +0 -384
  277. package/router/dist/sandbox/script-sandbox.d.ts +0 -134
  278. package/router/dist/sandbox/script-sandbox.js +0 -337
  279. package/router/dist/setup/script-transform-adapters.d.ts +0 -32
  280. package/router/dist/setup/script-transform-adapters.js +0 -278
  281. package/router/dist/tools/batch.d.ts +0 -33
  282. package/router/dist/tools/batch.js +0 -586
  283. package/router/dist/tools/run.d.ts +0 -62
  284. package/router/dist/tools/run.js +0 -1304
  285. package/router/dist/tools/search.d.ts +0 -66
  286. package/router/dist/tools/search.js +0 -1364
  287. package/router/dist/transform/engine.d.ts +0 -168
  288. package/router/dist/transform/engine.js +0 -2072
  289. package/router/dist/vault/vault-index.d.ts +0 -125
  290. package/router/dist/vault/vault-index.js +0 -416
  291. package/router/dist/vault/vault.d.ts +0 -138
  292. package/router/dist/vault/vault.js +0 -630
  293. package/runtime/interaction-contract.md +0 -16
  294. package/skills/discuss/references/checkpoints.md +0 -66
  295. package/skills/execute-work/references/execution-loop.md +0 -77
  296. package/skills/mode-contract/SKILL.md +0 -104
  297. package/skills/review-artifact/references/reviewer-prompt.md +0 -148
  298. package/skills/review-work/references/reviewer-prompt.md +0 -134
  299. package/skills/track-work/references/working-record-schema.md +0 -378
  300. package/skills/workflow/references/workflow-loop.md +0 -92
  301. /package/skills/handoff/references/{templates.md → handoff-templates.md} +0 -0
@@ -0,0 +1,1292 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { readCognitiveRoutingHistory } from "./history.js";
3
+ import { PI_SESSION_MODEL_STATE_ENTRY, parsePiSessionModelStateCommit } from "./pi-session-control.js";
4
+ export const COGNITIVE_ROUTING_INTENT_ENTRY = "freeflow-cognitive-routing-intent";
5
+ export const COGNITIVE_ROUTING_CONTROL_ENTRY = "freeflow-cognitive-routing-control";
6
+ export const COGNITIVE_ROUTING_INACTIVE_ENTRY = "freeflow-cognitive-routing-inactive";
7
+ function isProfileName(value) {
8
+ return value === "standard" || value === "reasoning";
9
+ }
10
+ function isMechanism(value) {
11
+ return [
12
+ "agent-tool",
13
+ "profile-command",
14
+ "profile-shortcut",
15
+ "profile-settings",
16
+ "session-tree",
17
+ "session-compact",
18
+ "activation",
19
+ "reload-restore",
20
+ "recovery",
21
+ "shutdown-restore",
22
+ ].includes(value);
23
+ }
24
+ function asIntentSource(value) {
25
+ if (value === "user" || value === "agent") return value;
26
+ return "system";
27
+ }
28
+ function pairEquals(a, b) {
29
+ return a?.provider === b?.provider && a?.modelId === b?.modelId && a?.thinkingLevel === b?.thinkingLevel;
30
+ }
31
+ function asPair(value) {
32
+ if (!value || typeof value !== "object") return undefined;
33
+ const candidate = value;
34
+ if (
35
+ typeof candidate.provider !== "string" ||
36
+ typeof candidate.modelId !== "string" ||
37
+ typeof candidate.thinkingLevel !== "string"
38
+ ) {
39
+ return undefined;
40
+ }
41
+ return {
42
+ provider: candidate.provider,
43
+ modelId: candidate.modelId,
44
+ thinkingLevel: candidate.thinkingLevel,
45
+ };
46
+ }
47
+ function hostPairFromEntry(entry) {
48
+ if (entry.type === "model_state_change") {
49
+ return asPair({
50
+ provider: entry.provider,
51
+ modelId: entry.modelId,
52
+ thinkingLevel: entry.thinkingLevel,
53
+ });
54
+ }
55
+ if (entry.type !== "custom" || entry.customType !== PI_SESSION_MODEL_STATE_ENTRY) return undefined;
56
+ const commit = parsePiSessionModelStateCommit(entry.data);
57
+ if (!commit || commit.phase !== "committed" || commit.status !== "applied") return undefined;
58
+ return commit.target;
59
+ }
60
+ function hostCorrelationIdFromEntry(entry) {
61
+ if (entry.type === "model_state_change") {
62
+ return typeof entry.correlationId === "string" ? entry.correlationId : undefined;
63
+ }
64
+ if (entry.type !== "custom" || entry.customType !== PI_SESSION_MODEL_STATE_ENTRY) return undefined;
65
+ const commit = parsePiSessionModelStateCommit(entry.data);
66
+ return commit?.phase === "committed" && commit.status === "applied" ? commit.correlationId : undefined;
67
+ }
68
+ function latestPiSessionCommit(entries, correlationId) {
69
+ for (let index = entries.length - 1; index >= 0; index -= 1) {
70
+ const entry = entries[index];
71
+ if (!entry || typeof entry !== "object") continue;
72
+ const candidate = entry;
73
+ if (candidate.type !== "custom" || candidate.customType !== PI_SESSION_MODEL_STATE_ENTRY) continue;
74
+ const commit = parsePiSessionModelStateCommit(candidate.data);
75
+ if (commit?.correlationId === correlationId) return commit;
76
+ }
77
+ return undefined;
78
+ }
79
+ function latestHostPair(context) {
80
+ const entries = branchEntriesFrom(context);
81
+ for (let index = entries.length - 1; index >= 0; index -= 1) {
82
+ const entry = entries[index];
83
+ if (!entry || typeof entry !== "object") continue;
84
+ const pair = hostPairFromEntry(entry);
85
+ if (pair) return pair;
86
+ }
87
+ return undefined;
88
+ }
89
+ function profileNameForPair(capabilityState, pair) {
90
+ if (!pair) return undefined;
91
+ for (const [name, profile] of Object.entries(capabilityState.resolvedProfiles)) {
92
+ if (!profile) continue;
93
+ if (
94
+ pairEquals(pair, {
95
+ provider: profile.provider,
96
+ modelId: profile.model,
97
+ thinkingLevel: profile.effectiveThinkingLevel,
98
+ })
99
+ ) {
100
+ return isProfileName(name) ? name : undefined;
101
+ }
102
+ }
103
+ return undefined;
104
+ }
105
+ function pairMatchesProfile(capabilityState, pair, profileName) {
106
+ const profile = capabilityState.resolvedProfiles[profileName];
107
+ return Boolean(
108
+ profile &&
109
+ pairEquals(pair, {
110
+ provider: profile.provider,
111
+ modelId: profile.model,
112
+ thinkingLevel: profile.effectiveThinkingLevel,
113
+ }),
114
+ );
115
+ }
116
+ function asIntent(value) {
117
+ if (!value || typeof value !== "object") return undefined;
118
+ const candidate = value;
119
+ if (
120
+ (candidate.version !== 1 && candidate.version !== 2) ||
121
+ (candidate.kind !== "activation" && candidate.kind !== "profile" && candidate.kind !== "closing") ||
122
+ (candidate.phase !== "prepared" && candidate.phase !== "abandoned") ||
123
+ typeof candidate.epoch !== "string" ||
124
+ typeof candidate.correlationId !== "string"
125
+ ) {
126
+ return undefined;
127
+ }
128
+ const target = asPair(candidate.target);
129
+ const returnTarget = asPair(candidate.returnTarget);
130
+ const fromPair = asPair(candidate.fromPair);
131
+ if (!target || !returnTarget) return undefined;
132
+ return {
133
+ version: candidate.version,
134
+ kind: candidate.kind,
135
+ phase: candidate.phase,
136
+ control: candidate.control === "manual" ? "manual" : "automatic",
137
+ source: asIntentSource(candidate.source),
138
+ ...(isMechanism(candidate.mechanism) ? { mechanism: candidate.mechanism } : {}),
139
+ ...(typeof candidate.decisionCorrelationId === "string"
140
+ ? { decisionCorrelationId: candidate.decisionCorrelationId }
141
+ : {}),
142
+ ...(fromPair ? { fromPair } : {}),
143
+ ...(isProfileName(candidate.fromProfile) ? { fromProfile: candidate.fromProfile } : {}),
144
+ ...(candidate.fromControl === "automatic" || candidate.fromControl === "manual"
145
+ ? { fromControl: candidate.fromControl }
146
+ : {}),
147
+ ...(typeof candidate.reason === "string" ? { reason: candidate.reason } : {}),
148
+ ...(typeof candidate.branchId === "string" || candidate.branchId === null ? { branchId: candidate.branchId } : {}),
149
+ epoch: candidate.epoch,
150
+ correlationId: candidate.correlationId,
151
+ ...(isProfileName(candidate.profile) ? { profile: candidate.profile } : {}),
152
+ ...(isProfileName(candidate.resumeProfile) ? { resumeProfile: candidate.resumeProfile } : {}),
153
+ ...(candidate.resumeControl === "automatic" || candidate.resumeControl === "manual"
154
+ ? { resumeControl: candidate.resumeControl }
155
+ : {}),
156
+ ...(typeof candidate.resumeReason === "string" ? { resumeReason: candidate.resumeReason } : {}),
157
+ target,
158
+ returnTarget,
159
+ };
160
+ }
161
+ function asInactiveEntry(value) {
162
+ if (!value || typeof value !== "object") return undefined;
163
+ const candidate = value;
164
+ const pair = asPair(candidate.pair);
165
+ if (
166
+ candidate.version !== 1 ||
167
+ candidate.source !== "user" ||
168
+ typeof candidate.reason !== "string" ||
169
+ candidate.reason.length === 0 ||
170
+ !pair
171
+ ) {
172
+ return undefined;
173
+ }
174
+ return {
175
+ version: 1,
176
+ source: "user",
177
+ reason: candidate.reason,
178
+ ...(typeof candidate.branchId === "string" || candidate.branchId === null ? { branchId: candidate.branchId } : {}),
179
+ pair,
180
+ };
181
+ }
182
+ function latestInactiveEntry(entries) {
183
+ for (let index = entries.length - 1; index >= 0; index -= 1) {
184
+ const candidate = entries[index];
185
+ if (!candidate || typeof candidate !== "object") continue;
186
+ const record = candidate;
187
+ if (record.type !== "custom" || record.customType !== COGNITIVE_ROUTING_INACTIVE_ENTRY) continue;
188
+ const entry = asInactiveEntry(record.data);
189
+ if (entry) return { entry, position: index };
190
+ }
191
+ return undefined;
192
+ }
193
+ function entriesFrom(context) {
194
+ try {
195
+ const entries = context.sessionManager?.getEntries?.();
196
+ return Array.isArray(entries) ? entries : [];
197
+ } catch {
198
+ return [];
199
+ }
200
+ }
201
+ function branchEntriesFrom(context) {
202
+ try {
203
+ const entries = context.sessionManager?.getBranch?.();
204
+ return Array.isArray(entries) ? entries : entriesFrom(context);
205
+ } catch {
206
+ return entriesFrom(context);
207
+ }
208
+ }
209
+ function latestIntent(entries, predicate = () => true) {
210
+ const abandonedCorrelations = new Set();
211
+ for (let index = entries.length - 1; index >= 0; index -= 1) {
212
+ const entry = entries[index];
213
+ if (!entry || typeof entry !== "object") continue;
214
+ const candidate = entry;
215
+ if (candidate.type !== "custom" || candidate.customType !== COGNITIVE_ROUTING_INTENT_ENTRY) continue;
216
+ const intent = asIntent(candidate.data);
217
+ if (!intent) continue;
218
+ if (intent.phase === "abandoned") {
219
+ abandonedCorrelations.add(intent.correlationId);
220
+ continue;
221
+ }
222
+ if (!abandonedCorrelations.has(intent.correlationId) && predicate(intent)) return intent;
223
+ }
224
+ return undefined;
225
+ }
226
+ function controlModeForIntent(intent) {
227
+ if (intent.control === "manual" && intent.profile) return `manual-${intent.profile}`;
228
+ return "automatic";
229
+ }
230
+ function decisionCorrelationForIntent(intent) {
231
+ if (intent.decisionCorrelationId) return intent.decisionCorrelationId;
232
+ return intent.source === "user" || intent.source === "agent" ? intent.correlationId : undefined;
233
+ }
234
+ function latestControlMode(entries, intent) {
235
+ for (let index = entries.length - 1; index >= 0; index -= 1) {
236
+ const entry = entries[index];
237
+ if (!entry || typeof entry !== "object") continue;
238
+ const candidate = entry;
239
+ if (candidate.type !== "custom") continue;
240
+ if (candidate.customType === COGNITIVE_ROUTING_CONTROL_ENTRY) {
241
+ const data = candidate.data;
242
+ if (
243
+ data &&
244
+ typeof data === "object" &&
245
+ (data.version === 1 || data.version === 2) &&
246
+ data.epoch === intent.epoch &&
247
+ data.control === "automatic"
248
+ ) {
249
+ return "automatic";
250
+ }
251
+ }
252
+ if (candidate.customType !== COGNITIVE_ROUTING_INTENT_ENTRY) continue;
253
+ const candidateIntent = asIntent(candidate.data);
254
+ if (!candidateIntent || candidateIntent.epoch !== intent.epoch) continue;
255
+ if (candidateIntent.phase === "abandoned") {
256
+ if (candidateIntent.fromControl === "manual" && candidateIntent.fromProfile) {
257
+ return `manual-${candidateIntent.fromProfile}`;
258
+ }
259
+ if (candidateIntent.fromControl === "automatic") return "automatic";
260
+ continue;
261
+ }
262
+ if (candidateIntent.kind === "profile" || candidateIntent.kind === "activation") {
263
+ return controlModeForIntent(candidateIntent);
264
+ }
265
+ }
266
+ return "automatic";
267
+ }
268
+ function intentEntryIndex(entries, intent) {
269
+ for (let index = 0; index < entries.length; index += 1) {
270
+ const entry = entries[index];
271
+ if (!entry || typeof entry !== "object") continue;
272
+ const candidate = entry;
273
+ if (candidate.type !== "custom" || candidate.customType !== COGNITIVE_ROUTING_INTENT_ENTRY) continue;
274
+ const parsed = asIntent(candidate.data);
275
+ if (parsed?.correlationId === intent.correlationId && parsed.phase === "prepared") return index;
276
+ }
277
+ return entries.length;
278
+ }
279
+ function matchesBaseline(candidate, failed) {
280
+ if (failed.fromPair && !pairEquals(candidate.target, failed.fromPair)) return false;
281
+ if (failed.fromProfile && candidate.profile !== failed.fromProfile) return false;
282
+ return true;
283
+ }
284
+ export function resolveControlBeforeIntent(entries, intent) {
285
+ if (intent.fromControl === "automatic") return "automatic";
286
+ if (intent.fromControl === "manual") {
287
+ return intent.fromProfile ? `manual-${intent.fromProfile}` : undefined;
288
+ }
289
+ const priorEntries = entries.slice(0, intentEntryIndex(entries, intent));
290
+ const abandonedCorrelations = new Set();
291
+ for (const entry of priorEntries) {
292
+ if (!entry || typeof entry !== "object") continue;
293
+ const candidate = entry;
294
+ if (candidate.type !== "custom" || candidate.customType !== COGNITIVE_ROUTING_INTENT_ENTRY) continue;
295
+ const parsed = asIntent(candidate.data);
296
+ if (parsed?.phase === "abandoned") abandonedCorrelations.add(parsed.correlationId);
297
+ }
298
+ let resolved;
299
+ for (const entry of priorEntries) {
300
+ if (!entry || typeof entry !== "object") continue;
301
+ const candidate = entry;
302
+ if (candidate.type !== "custom") continue;
303
+ if (candidate.customType === COGNITIVE_ROUTING_CONTROL_ENTRY) {
304
+ const data = candidate.data;
305
+ if (
306
+ data &&
307
+ typeof data === "object" &&
308
+ (data.version === 1 || data.version === 2) &&
309
+ data.epoch === intent.epoch &&
310
+ data.control === "automatic"
311
+ ) {
312
+ resolved = "automatic";
313
+ }
314
+ continue;
315
+ }
316
+ if (candidate.customType !== COGNITIVE_ROUTING_INTENT_ENTRY) continue;
317
+ const parsed = asIntent(candidate.data);
318
+ if (
319
+ !parsed ||
320
+ parsed.phase !== "prepared" ||
321
+ parsed.epoch !== intent.epoch ||
322
+ abandonedCorrelations.has(parsed.correlationId) ||
323
+ (parsed.kind !== "profile" && parsed.kind !== "activation") ||
324
+ !hasMatchingHostEntry(priorEntries, parsed) ||
325
+ !matchesBaseline(parsed, intent)
326
+ ) {
327
+ continue;
328
+ }
329
+ resolved = controlModeForIntent(parsed);
330
+ }
331
+ return resolved;
332
+ }
333
+ function hasMatchingHostEntry(entries, intent) {
334
+ return entries.some((entry) => {
335
+ if (!entry || typeof entry !== "object") return false;
336
+ const candidate = entry;
337
+ return (
338
+ hostCorrelationIdFromEntry(candidate) === intent.correlationId &&
339
+ pairEquals(hostPairFromEntry(candidate), intent.target)
340
+ );
341
+ });
342
+ }
343
+ export class CognitiveRoutingController {
344
+ capabilityState;
345
+ pi;
346
+ ctx;
347
+ initialSessionStart;
348
+ label;
349
+ idFactory;
350
+ liveStateAuthoritative;
351
+ lease;
352
+ activeProfile;
353
+ epoch;
354
+ returnTarget;
355
+ controlMode = "automatic";
356
+ nativeInactiveReason;
357
+ nativeBlockedReason;
358
+ transitionInFlight = false;
359
+ branchPending = false;
360
+ operation = Promise.resolve();
361
+ constructor(options) {
362
+ this.capabilityState = options.capabilityState;
363
+ this.pi = options.pi;
364
+ this.ctx = options.ctx;
365
+ this.initialSessionStart = options.initialSessionStart;
366
+ this.label = options.label ?? "Cognitive Routing";
367
+ this.idFactory = options.idFactory ?? randomUUID;
368
+ this.liveStateAuthoritative = options.liveStateAuthoritative === true;
369
+ }
370
+ state() {
371
+ const hostPair = this.liveStateAuthoritative ? undefined : latestHostPair(this.ctx);
372
+ const observedPair = this.liveStateAuthoritative ? this.currentPair() : (hostPair ?? this.currentPair());
373
+ const observedProfile = this.activeProfile ? profileNameForPair(this.capabilityState, observedPair) : undefined;
374
+ const activeProfile = this.liveStateAuthoritative
375
+ ? observedProfile
376
+ : hostPair
377
+ ? observedProfile
378
+ : (observedProfile ?? this.activeProfile);
379
+ const effective = this.lease !== undefined && activeProfile !== undefined && !this.branchPending;
380
+ return {
381
+ effective,
382
+ controlMode: this.controlMode,
383
+ ...(this.nativeBlockedReason
384
+ ? { runtimeStatus: "blocked", runtimeReason: this.nativeBlockedReason }
385
+ : this.nativeInactiveReason
386
+ ? { runtimeStatus: "inactive", runtimeReason: this.nativeInactiveReason }
387
+ : effective
388
+ ? { runtimeStatus: "active" }
389
+ : {}),
390
+ ...(activeProfile ? { activeProfile } : {}),
391
+ ...(this.epoch ? { epoch: this.epoch } : {}),
392
+ ...(this.returnTarget ? { returnTarget: { ...this.returnTarget } } : {}),
393
+ };
394
+ }
395
+ history(options = {}) {
396
+ const state = this.state();
397
+ const current = {
398
+ control: state.effective ? (state.controlMode === "automatic" ? "automatic" : "manual") : "unavailable",
399
+ profile: state.effective && state.activeProfile ? state.activeProfile : "unavailable",
400
+ };
401
+ const profilePairs = {
402
+ ...(this.capabilityState.resolvedProfiles.standard
403
+ ? {
404
+ standard: {
405
+ provider: this.capabilityState.resolvedProfiles.standard.provider,
406
+ modelId: this.capabilityState.resolvedProfiles.standard.model,
407
+ thinkingLevel: this.capabilityState.resolvedProfiles.standard.effectiveThinkingLevel,
408
+ },
409
+ }
410
+ : {}),
411
+ ...(this.capabilityState.resolvedProfiles.reasoning
412
+ ? {
413
+ reasoning: {
414
+ provider: this.capabilityState.resolvedProfiles.reasoning.provider,
415
+ modelId: this.capabilityState.resolvedProfiles.reasoning.model,
416
+ thinkingLevel: this.capabilityState.resolvedProfiles.reasoning.effectiveThinkingLevel,
417
+ },
418
+ }
419
+ : {}),
420
+ };
421
+ return readCognitiveRoutingHistory(this.ctx, { ...options, current, profilePairs });
422
+ }
423
+ async activate() {
424
+ return this.enqueue(() => this._activate());
425
+ }
426
+ async deactivate() {
427
+ return this.enqueue(() => this._deactivate());
428
+ }
429
+ async shutdown(reason) {
430
+ return this.enqueue(() =>
431
+ reason === "quit" ? this._releaseWithoutRestore() : this._deactivate(reason === "reload"),
432
+ );
433
+ }
434
+ async recover() {
435
+ return this.enqueue(() => this._recover());
436
+ }
437
+ async reconcileBranch(mechanism = "session-tree") {
438
+ return this.enqueue(() => this._reconcileBranch(mechanism));
439
+ }
440
+ async observeNativeChange(reason, source = undefined) {
441
+ if (this.transitionInFlight || source === "restore") return { status: "ignored" };
442
+ return this.enqueue(() => this._observeNativeChange(reason, source));
443
+ }
444
+ async reconcileLiveState(reason = "Pi model state diverged") {
445
+ if (this.transitionInFlight) return { status: "ignored" };
446
+ return this.enqueue(() => this._observeNativeChange(reason));
447
+ }
448
+ recordNativeInactive(reason, pair) {
449
+ try {
450
+ this.pi.appendEntryDurable(COGNITIVE_ROUTING_INACTIVE_ENTRY, {
451
+ version: 1,
452
+ source: "user",
453
+ reason,
454
+ branchId: this.currentBranchId(),
455
+ pair,
456
+ });
457
+ } catch {
458
+ this.nativeInactiveReason = undefined;
459
+ this.nativeBlockedReason = "inactive_state_persistence_failed";
460
+ return { status: "blocked", reason: this.nativeBlockedReason };
461
+ }
462
+ this.nativeInactiveReason = reason;
463
+ this.nativeBlockedReason = undefined;
464
+ return { status: "inactive", reason };
465
+ }
466
+ async _observeNativeChange(reason, source = undefined) {
467
+ if (!this.lease || !this.activeProfile) return { status: "ignored" };
468
+ const profile = this.capabilityState.resolvedProfiles[this.activeProfile];
469
+ const current = this.currentPair();
470
+ const expected = profile
471
+ ? {
472
+ provider: profile.provider,
473
+ modelId: profile.model,
474
+ thinkingLevel: profile.effectiveThinkingLevel,
475
+ }
476
+ : undefined;
477
+ if (current && expected && pairEquals(current, expected) && source !== "set") return { status: "ignored" };
478
+ const lease = this.lease;
479
+ if (!current) {
480
+ await this.releaseLease(lease);
481
+ this.clearActiveState();
482
+ this.nativeBlockedReason = "native_state_unavailable";
483
+ return { status: "blocked", reason: this.nativeBlockedReason };
484
+ }
485
+ const result = this.recordNativeInactive(reason, current);
486
+ await this.releaseLease(lease);
487
+ this.clearActiveState();
488
+ return result;
489
+ }
490
+ async _activate(allowInactive = false, requestedProfile, requestedControlMode) {
491
+ if (this.state().effective && this.activeProfile) {
492
+ return { status: "active", profile: this.activeProfile };
493
+ }
494
+ if (!this.capabilityState.effective) {
495
+ return { status: "inactive", reason: "not_effective" };
496
+ }
497
+ if ((this.nativeInactiveReason || this.nativeBlockedReason) && !allowInactive) {
498
+ return {
499
+ status: "inactive",
500
+ reason: this.nativeBlockedReason ? "runtime_blocked" : "native_override",
501
+ };
502
+ }
503
+ const sessionEntries = entriesFrom(this.ctx);
504
+ const lifecycleIntent = latestIntent(
505
+ sessionEntries,
506
+ (intent) => intent.kind === "activation" || intent.kind === "closing",
507
+ );
508
+ if (lifecycleIntent && !hasMatchingHostEntry(sessionEntries, lifecycleIntent)) {
509
+ return { status: "inactive", reason: "pending_intent" };
510
+ }
511
+ if (
512
+ lifecycleIntent?.kind === "activation" &&
513
+ !(allowInactive && (this.nativeInactiveReason || this.nativeBlockedReason))
514
+ ) {
515
+ return { status: "inactive", reason: "recover_required" };
516
+ }
517
+ const preservedReload = lifecycleIntent?.kind === "closing" && lifecycleIntent.resumeProfile !== undefined;
518
+ if (preservedReload && !lifecycleIntent.resumeControl) {
519
+ return { status: "inactive", reason: "resume_state_invalid" };
520
+ }
521
+ const returnTarget = this.currentPair();
522
+ if (!returnTarget) {
523
+ return { status: "inactive", reason: "current_state_unavailable" };
524
+ }
525
+ const epoch = this.epoch ?? this.idFactory();
526
+ const branchId = this.currentBranchId();
527
+ const sessionStart = this.initialSessionStart ??
528
+ this.capabilityState.sessionStart ?? {
529
+ control: "automatic",
530
+ profile: "reasoning",
531
+ };
532
+ let profileName;
533
+ if (requestedProfile) {
534
+ profileName = requestedProfile;
535
+ } else if (preservedReload) {
536
+ profileName = lifecycleIntent.resumeProfile;
537
+ } else if (sessionStart.control === "automatic") {
538
+ profileName = "reasoning";
539
+ } else {
540
+ profileName = sessionStart.profile;
541
+ }
542
+ const profile = this.capabilityState.resolvedProfiles[profileName];
543
+ if (!profile) {
544
+ return { status: "inactive", reason: preservedReload ? "resume_profile_unavailable" : "profile_unavailable" };
545
+ }
546
+ let controlMode;
547
+ if (requestedControlMode) {
548
+ controlMode = requestedControlMode;
549
+ } else if (preservedReload) {
550
+ controlMode = lifecycleIntent.resumeControl === "manual" ? `manual-${profileName}` : "automatic";
551
+ } else {
552
+ controlMode = sessionStart.control === "manual" ? `manual-${profileName}` : "automatic";
553
+ }
554
+ const target = {
555
+ provider: profile.provider,
556
+ modelId: profile.model,
557
+ thinkingLevel: profile.effectiveThinkingLevel,
558
+ };
559
+ return this.activatePrepared({
560
+ kind: "activation",
561
+ controlMode,
562
+ source: "system",
563
+ mechanism: preservedReload ? "reload-restore" : "activation",
564
+ ...(preservedReload && lifecycleIntent.resumeReason ? { reason: lifecycleIntent.resumeReason } : {}),
565
+ epoch,
566
+ branchId,
567
+ returnTarget,
568
+ target,
569
+ profile: profileName,
570
+ });
571
+ }
572
+ async _releaseWithoutRestore() {
573
+ const lease = this.lease;
574
+ if (!lease) {
575
+ this.clearActiveState();
576
+ return { status: "inactive", reason: "not_active" };
577
+ }
578
+ await this.releaseLease(lease);
579
+ this.clearActiveState();
580
+ return { status: "inactive", reason: "released_on_quit" };
581
+ }
582
+ async _deactivate(preserveSemanticState = false) {
583
+ const lease = this.lease;
584
+ const returnTarget = this.returnTarget;
585
+ if (!lease || !returnTarget || !this.epoch) {
586
+ this.clearActiveState();
587
+ return { status: "inactive", reason: "not_active" };
588
+ }
589
+ const currentState = preserveSemanticState ? this.state() : undefined;
590
+ const resumeProfile = currentState?.effective ? currentState.activeProfile : undefined;
591
+ let resumeControl;
592
+ if (resumeProfile && currentState?.controlMode === "automatic") {
593
+ resumeControl = "automatic";
594
+ } else if (resumeProfile && currentState?.controlMode === `manual-${resumeProfile}`) {
595
+ resumeControl = "manual";
596
+ }
597
+ const resumeIntent = resumeProfile
598
+ ? latestIntent(
599
+ branchEntriesFrom(this.ctx),
600
+ (candidate) => candidate.kind === "profile" && candidate.epoch === this.epoch,
601
+ )
602
+ : undefined;
603
+ const fromPair = this.observedHostPair();
604
+ const fromProfile = this.activeProfile ?? profileNameForPair(this.capabilityState, fromPair);
605
+ const intent = this.prepareIntent({
606
+ kind: "closing",
607
+ control: "automatic",
608
+ source: "system",
609
+ mechanism: "shutdown-restore",
610
+ ...(fromPair ? { fromPair } : {}),
611
+ ...(fromProfile ? { fromProfile } : {}),
612
+ ...(resumeProfile ? { resumeProfile } : {}),
613
+ ...(resumeControl ? { resumeControl } : {}),
614
+ ...(resumeIntent?.reason ? { resumeReason: resumeIntent.reason } : {}),
615
+ epoch: this.epoch,
616
+ correlationId: this.idFactory(),
617
+ branchId: this.currentBranchId(),
618
+ target: returnTarget,
619
+ returnTarget,
620
+ });
621
+ try {
622
+ this.pi.appendEntryDurable(COGNITIVE_ROUTING_INTENT_ENTRY, intent);
623
+ } catch {
624
+ await this.releaseLease(lease);
625
+ this.clearActiveState();
626
+ return { status: "inactive", reason: "prepare_failed" };
627
+ }
628
+ this.clearActiveState(false);
629
+ try {
630
+ const result = await this.setState(lease, { ...returnTarget, correlationId: intent.correlationId });
631
+ if (result.status !== "applied" && result.status !== "unchanged") {
632
+ return { status: "inactive", reason: "restore_rejected" };
633
+ }
634
+ return { status: "inactive", reason: "restored" };
635
+ } catch {
636
+ return { status: "inactive", reason: "restore_failed" };
637
+ } finally {
638
+ await this.releaseLease(lease);
639
+ }
640
+ }
641
+ async recoverTerminalIntent(intent) {
642
+ const commit = latestPiSessionCommit(branchEntriesFrom(this.ctx), intent.correlationId);
643
+ if (!commit) return undefined;
644
+ if (commit.phase === "prepared") {
645
+ if (!this.pi.recoverPreparedModelState) {
646
+ return { status: "pending", reason: "prepared_recovery_unsupported" };
647
+ }
648
+ let recovery;
649
+ try {
650
+ recovery = await this.pi.recoverPreparedModelState({
651
+ fromPair: commit.fromPair,
652
+ target: commit.target,
653
+ correlationId: commit.correlationId,
654
+ });
655
+ } catch {
656
+ return { status: "pending", reason: "prepared_recovery_failed" };
657
+ }
658
+ if (recovery.status === "rollback-failed") {
659
+ return { status: "pending", reason: "rollback_failed" };
660
+ }
661
+ if (recovery.status !== "restored") {
662
+ return { status: "pending", reason: "prepared_recovery_failed" };
663
+ }
664
+ try {
665
+ this.abandonPreparedIntent(intent, "Pi session transition interrupted.");
666
+ } catch {
667
+ return { status: "pending", reason: "intent_abandon_failed" };
668
+ }
669
+ const recovered = await this._recover();
670
+ return recovered.status === "inactive" && recovered.reason === "no_pending_intent"
671
+ ? { status: "inactive", reason: "intent_abandoned" }
672
+ : recovered;
673
+ }
674
+ if (commit.phase !== "aborted") return undefined;
675
+ if (commit.status === "rollback-failed") {
676
+ return { status: "pending", reason: "rollback_failed" };
677
+ }
678
+ try {
679
+ this.abandonPreparedIntent(intent, "Pi session transition rolled back.");
680
+ } catch {
681
+ return { status: "pending", reason: "intent_abandon_failed" };
682
+ }
683
+ return this._recover();
684
+ }
685
+ async recoverTerminalProfileIntent(intent) {
686
+ const commit = latestPiSessionCommit(branchEntriesFrom(this.ctx), intent.correlationId);
687
+ if (!commit || commit.phase === "committed") return undefined;
688
+ if (commit.phase === "aborted" && commit.status === "rollback-failed") {
689
+ return { status: "pending", reason: "rollback_failed" };
690
+ }
691
+ const controlMode = resolveControlBeforeIntent(branchEntriesFrom(this.ctx), intent);
692
+ if (
693
+ !controlMode ||
694
+ !intent.fromPair ||
695
+ !intent.fromProfile ||
696
+ !pairMatchesProfile(this.capabilityState, intent.fromPair, intent.fromProfile)
697
+ ) {
698
+ return { status: "pending", reason: "baseline_control_unknown" };
699
+ }
700
+ if (commit.phase === "prepared") {
701
+ if (!this.pi.recoverPreparedModelState) {
702
+ return { status: "pending", reason: "prepared_recovery_unsupported" };
703
+ }
704
+ let recovery;
705
+ try {
706
+ recovery = await this.pi.recoverPreparedModelState({
707
+ fromPair: commit.fromPair,
708
+ target: commit.target,
709
+ correlationId: commit.correlationId,
710
+ });
711
+ } catch {
712
+ return { status: "pending", reason: "prepared_recovery_failed" };
713
+ }
714
+ if (recovery.status === "rollback-failed") {
715
+ return { status: "pending", reason: "rollback_failed" };
716
+ }
717
+ if (recovery.status !== "restored") {
718
+ return { status: "pending", reason: "prepared_recovery_failed" };
719
+ }
720
+ }
721
+ try {
722
+ this.abandonPreparedIntent(intent, "Pi session transition interrupted or rolled back.");
723
+ } catch {
724
+ return { status: "pending", reason: "intent_abandon_failed" };
725
+ }
726
+ const recovered = await this.activatePrepared({
727
+ kind: "profile",
728
+ controlMode,
729
+ source: "system",
730
+ mechanism: "recovery",
731
+ ...(decisionCorrelationForIntent(intent) ? { decisionCorrelationId: decisionCorrelationForIntent(intent) } : {}),
732
+ branchId: this.currentBranchId(),
733
+ epoch: intent.epoch,
734
+ returnTarget: intent.returnTarget,
735
+ target: intent.fromPair,
736
+ profile: intent.fromProfile,
737
+ });
738
+ return recovered.status === "active" ? recovered : { status: "pending", reason: "baseline_recovery_failed" };
739
+ }
740
+ async _recover() {
741
+ const sessionEntries = entriesFrom(this.ctx);
742
+ const branchEntries = branchEntriesFrom(this.ctx);
743
+ const inactive = latestInactiveEntry(branchEntries);
744
+ const branchLifecycleIntent = latestIntent(
745
+ branchEntries,
746
+ (intent) => intent.kind === "activation" || intent.kind === "closing",
747
+ );
748
+ if (
749
+ inactive &&
750
+ (!branchLifecycleIntent || intentEntryIndex(branchEntries, branchLifecycleIntent) <= inactive.position)
751
+ ) {
752
+ this.nativeInactiveReason = inactive.entry.reason;
753
+ this.nativeBlockedReason = undefined;
754
+ this.clearActiveState();
755
+ return { status: "inactive", reason: "native_override" };
756
+ }
757
+ const lifecycleIntent = latestIntent(
758
+ sessionEntries,
759
+ (intent) => intent.kind === "activation" || intent.kind === "closing",
760
+ );
761
+ if (!lifecycleIntent) {
762
+ return { status: "inactive", reason: "no_pending_intent" };
763
+ }
764
+ if (lifecycleIntent.kind === "activation") {
765
+ const lifecycleTerminal = await this.recoverTerminalIntent(lifecycleIntent);
766
+ if (lifecycleTerminal) return lifecycleTerminal;
767
+ }
768
+ if (lifecycleIntent.kind === "closing") {
769
+ return hasMatchingHostEntry(sessionEntries, lifecycleIntent)
770
+ ? { status: "inactive", reason: "closed" }
771
+ : this.recoverClosingIntent(lifecycleIntent);
772
+ }
773
+ const currentActivationProfile = this.capabilityState.resolvedProfiles[lifecycleIntent.profile ?? "standard"];
774
+ if (!this.capabilityState.effective) {
775
+ return hasMatchingHostEntry(sessionEntries, lifecycleIntent)
776
+ ? { status: "inactive", reason: "not_effective" }
777
+ : this.abandonIntent(lifecycleIntent, "Cognitive Routing is not effective.");
778
+ }
779
+ if (!currentActivationProfile) {
780
+ return this.abandonIntent(lifecycleIntent, "Prepared profile is unavailable.");
781
+ }
782
+ const activationTarget = {
783
+ provider: currentActivationProfile.provider,
784
+ modelId: currentActivationProfile.model,
785
+ thinkingLevel: currentActivationProfile.effectiveThinkingLevel,
786
+ };
787
+ const activationMatched = hasMatchingHostEntry(sessionEntries, lifecycleIntent);
788
+ if (this.liveStateAuthoritative && activationMatched) {
789
+ const livePair = this.currentPair();
790
+ if (!livePair) {
791
+ this.clearActiveState();
792
+ this.nativeBlockedReason = "native_state_unavailable";
793
+ return { status: "inactive", reason: "native_override" };
794
+ }
795
+ if (!pairEquals(livePair, activationTarget)) {
796
+ this.recordNativeInactive("Pi model state diverged during recovery", livePair);
797
+ this.clearActiveState();
798
+ return { status: "inactive", reason: "native_override" };
799
+ }
800
+ }
801
+ if (activationMatched && !pairEquals(activationTarget, lifecycleIntent.target)) {
802
+ return { status: "pending", reason: "applied_target_changed" };
803
+ }
804
+ if (!activationMatched && !pairEquals(activationTarget, lifecycleIntent.target)) {
805
+ return this.abandonIntent(lifecycleIntent, "Prepared profile target changed.");
806
+ }
807
+ if (!activationMatched) {
808
+ const retried = await this.activatePrepared({
809
+ kind: "activation",
810
+ controlMode: latestControlMode(branchEntries, lifecycleIntent),
811
+ source: "system",
812
+ mechanism: "recovery",
813
+ branchId: this.currentBranchId(),
814
+ epoch: lifecycleIntent.epoch,
815
+ returnTarget: lifecycleIntent.returnTarget,
816
+ target: lifecycleIntent.target,
817
+ profile: lifecycleIntent.profile ?? "standard",
818
+ });
819
+ return retried.status === "active" ? retried : { status: "pending", reason: "activation_recovery_failed" };
820
+ }
821
+ const profileIntent = latestIntent(
822
+ branchEntries,
823
+ (intent) => intent.kind === "profile" && intent.epoch === lifecycleIntent.epoch,
824
+ );
825
+ if (profileIntent) {
826
+ const terminal = await this.recoverTerminalProfileIntent(profileIntent);
827
+ if (terminal) return terminal;
828
+ const currentProfile = this.capabilityState.resolvedProfiles[profileIntent.profile ?? "standard"];
829
+ if (!currentProfile) {
830
+ return this.abandonIntent(profileIntent, "Prepared profile is unavailable.");
831
+ }
832
+ const profileTarget = {
833
+ provider: currentProfile.provider,
834
+ modelId: currentProfile.model,
835
+ thinkingLevel: currentProfile.effectiveThinkingLevel,
836
+ };
837
+ if (!pairEquals(profileTarget, profileIntent.target)) {
838
+ return hasMatchingHostEntry(branchEntries, profileIntent)
839
+ ? { status: "pending", reason: "applied_target_changed" }
840
+ : this.abandonIntent(profileIntent, "Prepared profile target changed.");
841
+ }
842
+ const profileMatched = hasMatchingHostEntry(branchEntries, profileIntent);
843
+ const retried = await this.activatePrepared({
844
+ kind: "profile",
845
+ controlMode: latestControlMode(branchEntries, profileIntent),
846
+ source: "system",
847
+ mechanism: "recovery",
848
+ ...(decisionCorrelationForIntent(profileIntent)
849
+ ? { decisionCorrelationId: decisionCorrelationForIntent(profileIntent) }
850
+ : {}),
851
+ branchId: this.currentBranchId(),
852
+ epoch: lifecycleIntent.epoch,
853
+ returnTarget: lifecycleIntent.returnTarget,
854
+ target: profileMatched ? profileTarget : profileIntent.target,
855
+ profile: profileIntent.profile ?? "standard",
856
+ });
857
+ return retried.status === "active" ? retried : { status: "pending", reason: "profile_recovery_failed" };
858
+ }
859
+ return this.activatePrepared({
860
+ kind: "activation",
861
+ controlMode: latestControlMode(branchEntries, lifecycleIntent),
862
+ source: "system",
863
+ mechanism: "recovery",
864
+ branchId: this.currentBranchId(),
865
+ epoch: lifecycleIntent.epoch,
866
+ returnTarget: lifecycleIntent.returnTarget,
867
+ target: activationTarget,
868
+ profile: lifecycleIntent.profile ?? "standard",
869
+ });
870
+ }
871
+ async recoverClosingIntent(intent) {
872
+ const fromPair = this.observedHostPair();
873
+ const fromProfile = intent.fromProfile ?? profileNameForPair(this.capabilityState, fromPair);
874
+ const retryIntent = this.prepareIntent({
875
+ kind: "closing",
876
+ control: "automatic",
877
+ source: "system",
878
+ mechanism: "shutdown-restore",
879
+ ...(fromPair ? { fromPair } : {}),
880
+ ...(fromProfile ? { fromProfile } : {}),
881
+ reason: "Closing recovery",
882
+ ...(intent.resumeProfile ? { resumeProfile: intent.resumeProfile } : {}),
883
+ ...(intent.resumeControl ? { resumeControl: intent.resumeControl } : {}),
884
+ ...(intent.resumeReason ? { resumeReason: intent.resumeReason } : {}),
885
+ branchId: this.currentBranchId(),
886
+ epoch: intent.epoch,
887
+ correlationId: this.idFactory(),
888
+ target: intent.target,
889
+ returnTarget: intent.returnTarget,
890
+ });
891
+ try {
892
+ this.pi.appendEntryDurable(COGNITIVE_ROUTING_INTENT_ENTRY, retryIntent);
893
+ } catch {
894
+ return { status: "pending", reason: "closing_recovery_prepare_failed" };
895
+ }
896
+ let acquisition;
897
+ try {
898
+ acquisition = await this.pi.acquireModelStateControl({ label: this.label });
899
+ } catch {
900
+ return { status: "pending", reason: "closing_recovery_acquire_failed" };
901
+ }
902
+ if (acquisition.status !== "acquired") {
903
+ return { status: "pending", reason: `closing_recovery_acquire_${acquisition.status}` };
904
+ }
905
+ try {
906
+ const result = await this.setState(acquisition.lease, {
907
+ ...intent.target,
908
+ correlationId: retryIntent.correlationId,
909
+ });
910
+ return result.status === "applied" || result.status === "unchanged"
911
+ ? { status: "inactive", reason: "restored" }
912
+ : { status: "pending", reason: "closing_recovery_rejected" };
913
+ } catch {
914
+ return { status: "pending", reason: "closing_recovery_failed" };
915
+ } finally {
916
+ await this.releaseLease(acquisition.lease);
917
+ }
918
+ }
919
+ abandonPreparedIntent(intent, reason) {
920
+ const fromPair = intent.fromPair ?? this.observedHostPair();
921
+ const fromProfile = intent.fromProfile ?? profileNameForPair(this.capabilityState, fromPair);
922
+ this.pi.appendEntryDurable(COGNITIVE_ROUTING_INTENT_ENTRY, {
923
+ ...intent,
924
+ version: 2,
925
+ phase: "abandoned",
926
+ source: "system",
927
+ mechanism: intent.mechanism ?? "recovery",
928
+ ...(fromPair ? { fromPair } : {}),
929
+ ...(fromProfile ? { fromProfile } : {}),
930
+ reason,
931
+ });
932
+ }
933
+ async abandonIntent(intent, reason) {
934
+ try {
935
+ this.abandonPreparedIntent(intent, reason);
936
+ const recovered = await this._recover();
937
+ return recovered.status === "inactive" && recovered.reason === "no_pending_intent"
938
+ ? { status: "inactive", reason: "intent_abandoned" }
939
+ : recovered;
940
+ } catch {
941
+ return { status: "pending", reason: "intent_abandon_failed" };
942
+ }
943
+ }
944
+ async _reconcileBranch(mechanism) {
945
+ if (!this.capabilityState.effective) return { status: "inactive", reason: "not_effective" };
946
+ if (!this.activeProfile || !this.lease) {
947
+ return { status: "inactive", reason: "not_active" };
948
+ }
949
+ const currentProfile = this.activeProfile;
950
+ const sessionEntries = entriesFrom(this.ctx);
951
+ const lifecycleIntent = latestIntent(
952
+ sessionEntries,
953
+ (intent) => intent.kind === "activation" || intent.kind === "closing",
954
+ );
955
+ if (lifecycleIntent?.kind === "closing") {
956
+ this.branchPending = true;
957
+ return hasMatchingHostEntry(sessionEntries, lifecycleIntent)
958
+ ? { status: "inactive", reason: "closed" }
959
+ : { status: "pending", reason: "closing_intent_unmatched" };
960
+ }
961
+ if (lifecycleIntent && !hasMatchingHostEntry(sessionEntries, lifecycleIntent)) {
962
+ this.branchPending = true;
963
+ return { status: "pending", reason: "activation_intent_unmatched" };
964
+ }
965
+ const entries = branchEntriesFrom(this.ctx);
966
+ const intent = latestIntent(
967
+ entries,
968
+ (candidate) => candidate.kind === "profile" && candidate.epoch === lifecycleIntent?.epoch,
969
+ );
970
+ if (!intent) {
971
+ this.branchPending = false;
972
+ return { status: "active", profile: currentProfile };
973
+ }
974
+ if (!hasMatchingHostEntry(entries, intent)) {
975
+ this.branchPending = true;
976
+ return { status: "pending", reason: "branch_intent_unmatched" };
977
+ }
978
+ const decisionCorrelationId = decisionCorrelationForIntent(intent);
979
+ if (intent.source === "system" && !decisionCorrelationId) {
980
+ this.branchPending = false;
981
+ return { status: "active", profile: currentProfile };
982
+ }
983
+ if (!intent.profile) {
984
+ this.branchPending = false;
985
+ return { status: "active", profile: currentProfile };
986
+ }
987
+ const controlMode = latestControlMode(entries, intent);
988
+ if (this.activeProfile === intent.profile && this.controlMode === controlMode) {
989
+ this.branchPending = false;
990
+ return { status: "active", profile: intent.profile };
991
+ }
992
+ const result = await this._setProfile(intent.profile, {
993
+ controlMode,
994
+ source: "system",
995
+ mechanism,
996
+ ...(decisionCorrelationId ? { decisionCorrelationId } : {}),
997
+ reason: "Branch reconciliation",
998
+ });
999
+ this.branchPending = result.status !== "active";
1000
+ return result;
1001
+ }
1002
+ async setManualProfile(profile, mechanism = "profile-command") {
1003
+ return this.enqueue(() => this._setManualProfile(profile, mechanism));
1004
+ }
1005
+ async setAutomaticControl(mechanism = "profile-command") {
1006
+ return this.enqueue(() => this._setAutomaticControl(mechanism));
1007
+ }
1008
+ async switchAutomaticProfile(profile, reason, source = "agent", mechanism = "agent-tool") {
1009
+ return this.enqueue(() => this._switchAutomaticProfile(profile, reason, source, mechanism));
1010
+ }
1011
+ async _setManualProfile(profile, mechanism) {
1012
+ if (!this.capabilityState.effective) {
1013
+ return { status: "inactive", reason: "not_effective" };
1014
+ }
1015
+ if (!this.state().effective) {
1016
+ return this._activate(true, profile, `manual-${profile}`);
1017
+ }
1018
+ return this._setProfile(profile, {
1019
+ controlMode: `manual-${profile}`,
1020
+ source: "user",
1021
+ mechanism,
1022
+ reason: "manual profile command",
1023
+ });
1024
+ }
1025
+ async _switchAutomaticProfile(profile, reason, source, mechanism) {
1026
+ if (!this.capabilityState.effective) return { status: "blocked", reason: "not_effective" };
1027
+ const current = this.state();
1028
+ if (!current.effective) return { status: "blocked", reason: "not_active" };
1029
+ if (this.controlMode !== "automatic") return { status: "blocked", reason: "manual_hold" };
1030
+ const from = current.activeProfile;
1031
+ if (!from) return { status: "blocked", reason: "profile_unknown" };
1032
+ if (from === profile) return { status: "active", changed: false, from, to: profile, profile };
1033
+ const transition = await this._setProfile(profile, { controlMode: "automatic", source, reason, mechanism });
1034
+ if (transition.status !== "active") return transition;
1035
+ return { status: "active", changed: true, from, to: transition.profile, profile: transition.profile };
1036
+ }
1037
+ async _setProfile(profile, options) {
1038
+ const resolvedProfile = this.capabilityState.resolvedProfiles[profile];
1039
+ const lease = this.lease;
1040
+ if (!resolvedProfile || !lease || !this.epoch || !this.returnTarget) {
1041
+ return { status: "inactive", reason: "profile_unavailable" };
1042
+ }
1043
+ const target = {
1044
+ provider: resolvedProfile.provider,
1045
+ modelId: resolvedProfile.model,
1046
+ thinkingLevel: resolvedProfile.effectiveThinkingLevel,
1047
+ };
1048
+ const fromPair = this.observedHostPair();
1049
+ if (!fromPair) return { status: "inactive", reason: "current_state_unavailable" };
1050
+ const fromProfile = this.activeProfile ?? profileNameForPair(this.capabilityState, fromPair);
1051
+ const correlationId = this.idFactory();
1052
+ const decisionCorrelationId =
1053
+ options.decisionCorrelationId ??
1054
+ (options.source === "user" || options.source === "agent" ? correlationId : undefined);
1055
+ const intent = this.prepareIntent({
1056
+ kind: "profile",
1057
+ control: options.controlMode === "automatic" ? "automatic" : "manual",
1058
+ source: options.source,
1059
+ mechanism: options.mechanism,
1060
+ ...(decisionCorrelationId ? { decisionCorrelationId } : {}),
1061
+ ...(fromPair ? { fromPair } : {}),
1062
+ ...(fromProfile ? { fromProfile } : {}),
1063
+ fromControl: options.controlMode === "automatic" ? "automatic" : "manual",
1064
+ reason: options.reason,
1065
+ branchId: this.currentBranchId(),
1066
+ epoch: this.epoch,
1067
+ correlationId,
1068
+ profile,
1069
+ target,
1070
+ returnTarget: this.returnTarget,
1071
+ });
1072
+ const sessionEntries = entriesFrom(this.ctx);
1073
+ const lifecycleIntent = latestIntent(
1074
+ sessionEntries,
1075
+ (candidate) => candidate.kind === "activation" || candidate.kind === "closing",
1076
+ );
1077
+ if (lifecycleIntent && !hasMatchingHostEntry(sessionEntries, lifecycleIntent)) {
1078
+ return { status: "inactive", reason: "pending_intent" };
1079
+ }
1080
+ const entries = branchEntriesFrom(this.ctx);
1081
+ const latest = latestIntent(entries, (candidate) => candidate.kind === "profile" && candidate.epoch === this.epoch);
1082
+ if (latest && !hasMatchingHostEntry(entries, latest)) {
1083
+ return { status: "inactive", reason: "pending_intent" };
1084
+ }
1085
+ try {
1086
+ this.pi.appendEntryDurable(COGNITIVE_ROUTING_INTENT_ENTRY, intent);
1087
+ this.branchPending = true;
1088
+ } catch {
1089
+ return { status: "inactive", reason: "prepare_failed" };
1090
+ }
1091
+ try {
1092
+ const result = await this.setState(lease, { ...target, correlationId: intent.correlationId });
1093
+ if (result.status !== "applied" && result.status !== "unchanged") {
1094
+ const commit = latestPiSessionCommit(branchEntriesFrom(this.ctx), intent.correlationId);
1095
+ if (result.status === "rejected" && commit?.phase === "aborted" && commit.status === "rollback-failed") {
1096
+ try {
1097
+ this.abandonPreparedIntent(intent, "Pi session rollback failed.");
1098
+ } catch {
1099
+ // Fail closed even when the terminal abandonment cannot be persisted.
1100
+ }
1101
+ await this.releaseLease(lease);
1102
+ this.clearActiveState();
1103
+ return { status: "inactive", reason: "rollback_failed" };
1104
+ }
1105
+ if (result.status === "rejected" && commit?.phase === "aborted" && commit.status === "rolled-back") {
1106
+ try {
1107
+ this.abandonPreparedIntent(intent, "Pi session transition rolled back.");
1108
+ this.branchPending = false;
1109
+ } catch {
1110
+ // Preserve the pending boundary when the terminal abandonment cannot be persisted.
1111
+ }
1112
+ }
1113
+ return { status: "inactive", reason: "transition_rejected" };
1114
+ }
1115
+ this.activeProfile = profile;
1116
+ this.controlMode = options.controlMode;
1117
+ this.branchPending = false;
1118
+ return { status: "active", profile };
1119
+ } catch {
1120
+ return { status: "inactive", reason: "transition_failed" };
1121
+ }
1122
+ }
1123
+ async _setAutomaticControl(mechanism) {
1124
+ if (!this.lease || !this.epoch) {
1125
+ if (!this.nativeInactiveReason && !this.nativeBlockedReason) return { status: "rejected", reason: "not_active" };
1126
+ const activation = await this._activate(true, this.profileForCurrentPair(), "automatic");
1127
+ return activation.status === "active"
1128
+ ? { status: "automatic" }
1129
+ : { status: "rejected", reason: activation.reason };
1130
+ }
1131
+ const current = this.state();
1132
+ if (!current.activeProfile) {
1133
+ return { status: "rejected", reason: "profile_unknown" };
1134
+ }
1135
+ if (current.activeProfile !== "reasoning") {
1136
+ const transition = await this._setProfile("reasoning", {
1137
+ controlMode: "automatic",
1138
+ source: "user",
1139
+ mechanism,
1140
+ reason: "automatic control selects the Reasoning profile",
1141
+ });
1142
+ if (transition.status !== "active") return { status: "rejected", reason: transition.reason };
1143
+ return { status: "automatic" };
1144
+ }
1145
+ if (this.controlMode === "automatic") return { status: "automatic" };
1146
+ try {
1147
+ this.pi.appendEntryDurable(COGNITIVE_ROUTING_CONTROL_ENTRY, {
1148
+ version: 2,
1149
+ control: "automatic",
1150
+ source: "user",
1151
+ mechanism,
1152
+ reason: "manual hold release",
1153
+ branchId: this.currentBranchId(),
1154
+ epoch: this.epoch,
1155
+ });
1156
+ } catch {
1157
+ return { status: "rejected", reason: "prepare_failed" };
1158
+ }
1159
+ this.controlMode = "automatic";
1160
+ return { status: "automatic" };
1161
+ }
1162
+ currentBranchId() {
1163
+ const leafId = this.ctx.sessionManager?.getLeafId?.();
1164
+ if (typeof leafId === "string" || leafId === null) return leafId;
1165
+ try {
1166
+ const branch = this.ctx.sessionManager?.getBranch?.();
1167
+ const last = Array.isArray(branch) ? branch.at(-1) : undefined;
1168
+ return last && typeof last === "object" && typeof last.id === "string" ? last.id : undefined;
1169
+ } catch {
1170
+ return undefined;
1171
+ }
1172
+ }
1173
+ observedHostPair() {
1174
+ const livePair = this.currentPair();
1175
+ return this.liveStateAuthoritative ? livePair : (latestHostPair(this.ctx) ?? livePair);
1176
+ }
1177
+ profileForCurrentPair() {
1178
+ return profileNameForPair(this.capabilityState, this.currentPair());
1179
+ }
1180
+ currentPair() {
1181
+ const model = this.ctx.model;
1182
+ if (
1183
+ !model ||
1184
+ typeof model.provider !== "string" ||
1185
+ typeof model.id !== "string" ||
1186
+ typeof this.ctx.thinkingLevel !== "string"
1187
+ ) {
1188
+ return undefined;
1189
+ }
1190
+ return {
1191
+ provider: model.provider,
1192
+ modelId: model.id,
1193
+ thinkingLevel: this.ctx.thinkingLevel,
1194
+ };
1195
+ }
1196
+ prepareIntent(input) {
1197
+ return { version: 2, phase: "prepared", ...input };
1198
+ }
1199
+ async activatePrepared(options) {
1200
+ const fromPair = this.observedHostPair();
1201
+ if (!fromPair) return { status: "inactive", reason: "current_state_unavailable" };
1202
+ const fromProfile = profileNameForPair(this.capabilityState, fromPair);
1203
+ const correlationId = this.idFactory();
1204
+ const decisionCorrelationId =
1205
+ options.decisionCorrelationId ??
1206
+ (options.source === "user" || options.source === "agent" ? correlationId : undefined);
1207
+ const intent = this.prepareIntent({
1208
+ kind: options.kind,
1209
+ control: options.controlMode === "automatic" ? "automatic" : "manual",
1210
+ source: options.source,
1211
+ mechanism: options.mechanism,
1212
+ ...(decisionCorrelationId ? { decisionCorrelationId } : {}),
1213
+ ...(fromPair ? { fromPair } : {}),
1214
+ ...(fromProfile ? { fromProfile } : {}),
1215
+ ...(options.reason ? { reason: options.reason } : {}),
1216
+ ...(options.branchId === undefined ? {} : { branchId: options.branchId }),
1217
+ epoch: options.epoch,
1218
+ correlationId,
1219
+ profile: options.profile,
1220
+ target: options.target,
1221
+ returnTarget: options.returnTarget,
1222
+ });
1223
+ try {
1224
+ this.pi.appendEntryDurable(COGNITIVE_ROUTING_INTENT_ENTRY, intent);
1225
+ } catch {
1226
+ return { status: "inactive", reason: "prepare_failed" };
1227
+ }
1228
+ let acquisition;
1229
+ try {
1230
+ acquisition = await this.pi.acquireModelStateControl({ label: this.label });
1231
+ } catch {
1232
+ return { status: "inactive", reason: "acquire_failed" };
1233
+ }
1234
+ if (acquisition.status !== "acquired") {
1235
+ return { status: "inactive", reason: `acquire_${acquisition.status}` };
1236
+ }
1237
+ this.lease = acquisition.lease;
1238
+ try {
1239
+ const result = await this.setState(acquisition.lease, { ...options.target, correlationId: intent.correlationId });
1240
+ if (result.status !== "applied" && result.status !== "unchanged") {
1241
+ await this.releaseLease(acquisition.lease);
1242
+ this.clearActiveState();
1243
+ return { status: "inactive", reason: "transition_rejected" };
1244
+ }
1245
+ this.epoch = options.epoch;
1246
+ this.returnTarget = options.returnTarget;
1247
+ this.activeProfile = options.profile;
1248
+ this.controlMode = options.controlMode;
1249
+ this.nativeInactiveReason = undefined;
1250
+ this.nativeBlockedReason = undefined;
1251
+ return { status: "active", profile: options.profile };
1252
+ } catch {
1253
+ await this.releaseLease(acquisition.lease);
1254
+ this.clearActiveState();
1255
+ return { status: "inactive", reason: "transition_failed" };
1256
+ }
1257
+ }
1258
+ enqueue(operation) {
1259
+ const next = this.operation.then(operation, operation);
1260
+ this.operation = next.then(
1261
+ () => undefined,
1262
+ () => undefined,
1263
+ );
1264
+ return next;
1265
+ }
1266
+ async setState(lease, request) {
1267
+ this.transitionInFlight = true;
1268
+ try {
1269
+ return await lease.setState(request);
1270
+ } finally {
1271
+ this.transitionInFlight = false;
1272
+ }
1273
+ }
1274
+ async releaseLease(lease) {
1275
+ try {
1276
+ await lease.release();
1277
+ } catch {
1278
+ // The host invalidates stale leases independently; do not retain local ownership after cleanup.
1279
+ }
1280
+ if (this.lease === lease) this.lease = undefined;
1281
+ }
1282
+ clearActiveState(clearReturnTarget = true) {
1283
+ this.lease = undefined;
1284
+ this.activeProfile = undefined;
1285
+ this.controlMode = "automatic";
1286
+ this.branchPending = false;
1287
+ if (clearReturnTarget) {
1288
+ this.epoch = undefined;
1289
+ this.returnTarget = undefined;
1290
+ }
1291
+ }
1292
+ }