@hassangameryt/freeflow 0.7.1 → 0.7.3
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.
- package/.claude-plugin/marketplace.json +1 -1
- package/.claude-plugin/plugin.json +1 -1
- package/.codex-plugin/plugin.json +1 -1
- package/.cursor-plugin/plugin.json +1 -1
- package/README.md +153 -128
- package/capabilities/cognitive-routing/SKILL.md +126 -274
- package/command-surface.json +7 -1
- package/gemini-extension.json +1 -1
- package/package.json +4 -4
- package/pi-extension/dist/cognitive-routing-v2/budget.js +42 -0
- package/pi-extension/dist/cognitive-routing-v2/config.js +136 -0
- package/pi-extension/dist/cognitive-routing-v2/projection.js +330 -0
- package/pi-extension/dist/cognitive-routing-v2/render.js +252 -0
- package/pi-extension/dist/cognitive-routing-v2/runtime.js +2181 -0
- package/pi-extension/dist/cognitive-routing-v2/schemas.js +173 -0
- package/pi-extension/dist/cognitive-routing-v2/state.js +828 -0
- package/pi-extension/dist/cognitive-routing-v2/tools.js +60 -0
- package/pi-extension/dist/cognitive-routing-v2/types.js +48 -0
- package/pi-extension/dist/context-virtualization/runtime.js +29 -7
- package/pi-extension/dist/freeflow-context/tool.js +12 -6
- package/pi-extension/dist/index.js +302 -626
- package/pi-extension/dist/provider-support/astra/adapter.js +110 -0
- package/pi-extension/dist/provider-support/astra/history.js +125 -0
- package/pi-extension/dist/provider-support/astra/index.js +11 -0
- package/pi-extension/dist/provider-support/astra/session-state.js +114 -0
- package/pi-extension/dist/provider-support/index.js +4 -0
- package/pi-extension/dist/runtime/request-history.js +216 -0
- package/pi-extension/dist/runtime/runtime-context.js +85 -16
- package/pi-extension/dist/session-sources/events.js +217 -0
- package/pi-extension/dist/session-sources/provenance.js +32 -0
- package/pi-extension/dist/session-sources/read-only-session.js +148 -0
- package/pi-extension/dist/session-sources/sources.js +277 -0
- package/pi-extension/dist/settings/settings-ui.js +274 -147
- package/pi-extension/src/cognitive-routing-v2/budget.ts +42 -0
- package/pi-extension/src/cognitive-routing-v2/config.ts +173 -0
- package/pi-extension/src/cognitive-routing-v2/projection.ts +375 -0
- package/pi-extension/src/cognitive-routing-v2/render.ts +277 -0
- package/pi-extension/src/cognitive-routing-v2/runtime.ts +2241 -0
- package/pi-extension/src/cognitive-routing-v2/schemas.ts +180 -0
- package/pi-extension/src/cognitive-routing-v2/state.ts +839 -0
- package/pi-extension/src/cognitive-routing-v2/tools.ts +62 -0
- package/pi-extension/src/cognitive-routing-v2/types.ts +254 -0
- package/pi-extension/src/context-virtualization/runtime.ts +30 -8
- package/pi-extension/src/freeflow-context/tool.ts +12 -6
- package/pi-extension/src/index.ts +308 -675
- package/pi-extension/src/provider-support/astra/adapter.ts +108 -0
- package/pi-extension/src/provider-support/astra/history.ts +145 -0
- package/pi-extension/src/provider-support/astra/index.ts +12 -0
- package/pi-extension/src/provider-support/astra/session-state.ts +113 -0
- package/pi-extension/src/provider-support/index.ts +5 -0
- package/pi-extension/src/runtime/request-history.ts +243 -0
- package/pi-extension/src/runtime/runtime-context.ts +100 -17
- package/pi-extension/src/session-sources/events.ts +230 -0
- package/pi-extension/src/session-sources/provenance.ts +39 -0
- package/pi-extension/src/session-sources/read-only-session.ts +170 -0
- package/pi-extension/src/session-sources/sources.ts +334 -0
- package/pi-extension/src/settings/settings-ui.ts +311 -158
- package/pi-extension/tests/cache-reuse/history.test.js +117 -0
- package/pi-extension/tests/cache-reuse/native.test.js +91 -0
- package/pi-extension/tests/cache-reuse/settings.test.js +211 -0
- package/pi-extension/tests/cognitive-routing-v2/communication.test.js +577 -0
- package/pi-extension/tests/cognitive-routing-v2/compaction-input.test.js +183 -0
- package/pi-extension/tests/cognitive-routing-v2/delegation.test.js +557 -0
- package/pi-extension/tests/cognitive-routing-v2/native.test.js +474 -0
- package/pi-extension/tests/cognitive-routing-v2/performance.test.js +87 -0
- package/pi-extension/tests/cognitive-routing-v2/persistence.test.js +300 -0
- package/pi-extension/tests/cognitive-routing-v2/projection.test.js +241 -0
- package/pi-extension/tests/cognitive-routing-v2/recovery.test.js +1034 -0
- package/pi-extension/tests/cognitive-routing-v2/render.test.js +244 -0
- package/pi-extension/tests/cognitive-routing-v2/runtime.test.js +423 -0
- package/pi-extension/tests/cognitive-routing-v2/stabilization.test.js +521 -0
- package/pi-extension/tests/cognitive-routing-v2/state.test.js +586 -0
- package/pi-extension/tests/context-virtualization/extension.test.js +33 -7
- package/pi-extension/tests/context-virtualization/runtime.test.js +17 -3
- package/pi-extension/tests/fixtures/routing-native.js +191 -0
- package/pi-extension/tests/integration/mode-free-core.test.js +6 -4
- package/pi-extension/tests/integration/pi-extension.test.js +655 -59
- package/pi-extension/tests/integration/prompt-architecture.test.js +127 -30
- package/pi-extension/tests/integration/unaffected-regressions.test.js +78 -11
- package/pi-extension/tests/provider-support/astra-boundaries.test.js +75 -0
- package/pi-extension/tests/provider-support/astra.test.js +306 -0
- package/pi-extension/tests/provider-support/cli.test.js +92 -0
- package/pi-extension/tests/provider-support/native.test.js +183 -0
- package/plugin.json +1 -1
- package/runtime/prompts/cognitive-routing.md +4 -5
- package/runtime/prompts/core.md +51 -45
- package/runtime/prompts/interaction-contract.md +5 -5
- package/skills/action-selection/SKILL.md +57 -97
- package/skills/design-for-depth/SKILL.md +58 -193
- package/skills/design-for-depth/references/implementation-decisions.md +76 -0
- package/skills/diagnose-failure/SKILL.md +64 -196
- package/skills/discuss/SKILL.md +64 -123
- package/skills/discuss/references/discussion-continuity.md +7 -3
- package/skills/execute-work/SKILL.md +69 -88
- package/skills/execute-work/references/execute-work-edges.md +9 -3
- package/skills/handoff/SKILL.md +44 -54
- package/skills/handoff/references/handoff-templates.md +15 -6
- package/skills/review-artifact/SKILL.md +80 -127
- package/skills/review-artifact/references/independent-artifact-reviewer-contract.md +1 -1
- package/skills/review-work/SKILL.md +65 -115
- package/skills/review-work/references/independent-work-reviewer-contract.md +1 -1
- package/skills/simplify-code/SKILL.md +47 -100
- package/skills/track-work/SKILL.md +128 -119
- package/skills/track-work/references/working-record-format.md +14 -2
- package/skills/verify-work/SKILL.md +58 -62
- package/skills/verify-work/references/integration-evidence.md +4 -2
- package/skills/verify-work/references/test-design.md +89 -0
- package/skills/workflow/SKILL.md +73 -119
- package/skills/write-plan/SKILL.md +46 -77
- package/skills/write-plan/references/plan-shapes.md +5 -5
- package/skills/write-spec/SKILL.md +51 -63
- package/skills/write-spec/references/artifact-standards.md +2 -2
- package/skills/write-spec/references/decision-records.md +3 -2
- package/skills/write-spec/references/spec-shapes.md +15 -0
- package/pi-extension/dist/cognitive-routing/commands.js +0 -96
- package/pi-extension/dist/cognitive-routing/config.js +0 -232
- package/pi-extension/dist/cognitive-routing/controller.js +0 -1292
- package/pi-extension/dist/cognitive-routing/history.js +0 -451
- package/pi-extension/dist/cognitive-routing/host.js +0 -188
- package/pi-extension/dist/cognitive-routing/pi-routing-session.js +0 -414
- package/pi-extension/dist/cognitive-routing/pi-session-control.js +0 -320
- package/pi-extension/dist/cognitive-routing/runtime.js +0 -43
- package/pi-extension/dist/cognitive-routing/tool.js +0 -212
- package/pi-extension/dist/cognitive-routing/types.js +0 -6
- package/pi-extension/src/cognitive-routing/commands.ts +0 -129
- package/pi-extension/src/cognitive-routing/config.ts +0 -303
- package/pi-extension/src/cognitive-routing/controller.ts +0 -1628
- package/pi-extension/src/cognitive-routing/history.ts +0 -650
- package/pi-extension/src/cognitive-routing/host.ts +0 -266
- package/pi-extension/src/cognitive-routing/pi-routing-session.ts +0 -538
- package/pi-extension/src/cognitive-routing/pi-session-control.ts +0 -444
- package/pi-extension/src/cognitive-routing/runtime.ts +0 -57
- package/pi-extension/src/cognitive-routing/tool.ts +0 -273
- package/pi-extension/src/cognitive-routing/types.ts +0 -89
- package/pi-extension/tests/cognitive-routing/commands.test.js +0 -134
- package/pi-extension/tests/cognitive-routing/controller.test.js +0 -1128
- package/pi-extension/tests/cognitive-routing/extension-lifecycle.test.js +0 -1142
- package/pi-extension/tests/cognitive-routing/history.test.js +0 -274
- package/pi-extension/tests/cognitive-routing/host-identity.test.js +0 -63
- package/pi-extension/tests/cognitive-routing/pi-normal-lifecycle.test.js +0 -434
- package/pi-extension/tests/cognitive-routing/pi-session-control.test.js +0 -174
- package/pi-extension/tests/cognitive-routing/pi-session-history.test.js +0 -91
- package/pi-extension/tests/cognitive-routing/profile-resolution.test.js +0 -279
- package/pi-extension/tests/cognitive-routing/tool.test.js +0 -230
- package/skills/tdd/SKILL.md +0 -143
- package/skills/tdd/references/test-design.md +0 -96
- /package/pi-extension/tests/{cognitive-routing/host-fixture.js → fixtures/pi-host.js} +0 -0
|
@@ -1,1628 +0,0 @@
|
|
|
1
|
-
import { randomUUID } from "node:crypto";
|
|
2
|
-
import {
|
|
3
|
-
readCognitiveRoutingHistory,
|
|
4
|
-
type CognitiveRoutingHistoryCurrent,
|
|
5
|
-
type CognitiveRoutingHistoryOptions,
|
|
6
|
-
type CognitiveRoutingHistoryResult,
|
|
7
|
-
} from "./history.js";
|
|
8
|
-
import { PI_SESSION_MODEL_STATE_ENTRY, parsePiSessionModelStateCommit } from "./pi-session-control.js";
|
|
9
|
-
import type {
|
|
10
|
-
CognitiveRoutingCapabilityState,
|
|
11
|
-
CognitiveRoutingProfileName,
|
|
12
|
-
CognitiveRoutingSessionStart,
|
|
13
|
-
CognitiveRoutingThinkingLevel,
|
|
14
|
-
} from "./types.js";
|
|
15
|
-
|
|
16
|
-
export const COGNITIVE_ROUTING_INTENT_ENTRY = "freeflow-cognitive-routing-intent";
|
|
17
|
-
export const COGNITIVE_ROUTING_CONTROL_ENTRY = "freeflow-cognitive-routing-control";
|
|
18
|
-
export const COGNITIVE_ROUTING_INACTIVE_ENTRY = "freeflow-cognitive-routing-inactive";
|
|
19
|
-
|
|
20
|
-
export type CognitiveRoutingMechanism =
|
|
21
|
-
| "agent-tool"
|
|
22
|
-
| "profile-command"
|
|
23
|
-
| "profile-shortcut"
|
|
24
|
-
| "profile-settings"
|
|
25
|
-
| "session-tree"
|
|
26
|
-
| "session-compact"
|
|
27
|
-
| "activation"
|
|
28
|
-
| "reload-restore"
|
|
29
|
-
| "recovery"
|
|
30
|
-
| "shutdown-restore";
|
|
31
|
-
|
|
32
|
-
type CognitiveRoutingPair = {
|
|
33
|
-
provider: string;
|
|
34
|
-
modelId: string;
|
|
35
|
-
thinkingLevel: CognitiveRoutingThinkingLevel;
|
|
36
|
-
};
|
|
37
|
-
|
|
38
|
-
type CognitiveRoutingIntent = {
|
|
39
|
-
version: 1 | 2;
|
|
40
|
-
kind: "activation" | "profile" | "closing";
|
|
41
|
-
phase: "prepared" | "abandoned";
|
|
42
|
-
control: "automatic" | "manual";
|
|
43
|
-
source: "system" | "user" | "agent";
|
|
44
|
-
reason?: string;
|
|
45
|
-
branchId?: string | null;
|
|
46
|
-
epoch: string;
|
|
47
|
-
correlationId: string;
|
|
48
|
-
mechanism?: CognitiveRoutingMechanism;
|
|
49
|
-
decisionCorrelationId?: string;
|
|
50
|
-
fromPair?: CognitiveRoutingPair;
|
|
51
|
-
fromProfile?: CognitiveRoutingProfileName;
|
|
52
|
-
fromControl?: "automatic" | "manual";
|
|
53
|
-
profile?: CognitiveRoutingProfileName;
|
|
54
|
-
resumeProfile?: CognitiveRoutingProfileName;
|
|
55
|
-
resumeControl?: "automatic" | "manual";
|
|
56
|
-
resumeReason?: string;
|
|
57
|
-
target: CognitiveRoutingPair;
|
|
58
|
-
returnTarget: CognitiveRoutingPair;
|
|
59
|
-
};
|
|
60
|
-
|
|
61
|
-
type CognitiveRoutingControlEntry = {
|
|
62
|
-
version: 1 | 2;
|
|
63
|
-
control: "automatic";
|
|
64
|
-
source: "user";
|
|
65
|
-
mechanism?: CognitiveRoutingMechanism;
|
|
66
|
-
reason?: string;
|
|
67
|
-
branchId?: string | null;
|
|
68
|
-
epoch: string;
|
|
69
|
-
};
|
|
70
|
-
|
|
71
|
-
type CognitiveRoutingInactiveEntry = {
|
|
72
|
-
version: 1;
|
|
73
|
-
source: "user";
|
|
74
|
-
reason: string;
|
|
75
|
-
branchId?: string | null;
|
|
76
|
-
pair: CognitiveRoutingPair;
|
|
77
|
-
};
|
|
78
|
-
|
|
79
|
-
type CognitiveRoutingPersistedData =
|
|
80
|
-
CognitiveRoutingIntent | CognitiveRoutingControlEntry | CognitiveRoutingInactiveEntry;
|
|
81
|
-
|
|
82
|
-
type ModelStateLease = {
|
|
83
|
-
setState(request: CognitiveRoutingPair & { correlationId: string }): Promise<{ status: string }>;
|
|
84
|
-
release(): Promise<unknown>;
|
|
85
|
-
};
|
|
86
|
-
|
|
87
|
-
type ModelStateAcquisition =
|
|
88
|
-
{ status: "acquired"; lease: ModelStateLease } | { status: "conflict"; owner: string } | { status: "busy" };
|
|
89
|
-
|
|
90
|
-
type ControllerPi = {
|
|
91
|
-
appendEntryDurable(customType: string, data: CognitiveRoutingPersistedData): void;
|
|
92
|
-
acquireModelStateControl(options: { label: string }): Promise<ModelStateAcquisition>;
|
|
93
|
-
recoverPreparedModelState?: (request: {
|
|
94
|
-
fromPair: CognitiveRoutingPair;
|
|
95
|
-
target: CognitiveRoutingPair;
|
|
96
|
-
correlationId: string;
|
|
97
|
-
}) => Promise<{ status: "restored" | "rollback-failed" | "rejected" }>;
|
|
98
|
-
};
|
|
99
|
-
|
|
100
|
-
type ControllerContext = {
|
|
101
|
-
model?: { provider?: string; id?: string };
|
|
102
|
-
thinkingLevel?: CognitiveRoutingThinkingLevel;
|
|
103
|
-
sessionManager?: {
|
|
104
|
-
getEntries?: () => readonly unknown[];
|
|
105
|
-
getBranch?: () => readonly unknown[];
|
|
106
|
-
getLeafId?: () => string | null;
|
|
107
|
-
};
|
|
108
|
-
};
|
|
109
|
-
|
|
110
|
-
type ControllerOptions = {
|
|
111
|
-
capabilityState: CognitiveRoutingCapabilityState;
|
|
112
|
-
pi: ControllerPi;
|
|
113
|
-
ctx: ControllerContext;
|
|
114
|
-
initialSessionStart?: CognitiveRoutingSessionStart;
|
|
115
|
-
label?: string;
|
|
116
|
-
idFactory?: () => string;
|
|
117
|
-
liveStateAuthoritative?: boolean;
|
|
118
|
-
};
|
|
119
|
-
|
|
120
|
-
export type CognitiveRoutingControlMode = "automatic" | "manual-standard" | "manual-reasoning";
|
|
121
|
-
|
|
122
|
-
export type CognitiveRoutingRuntimeStatus = "active" | "inactive" | "blocked";
|
|
123
|
-
|
|
124
|
-
export type CognitiveRoutingNativeChangeResult =
|
|
125
|
-
{ status: "ignored" } | { status: "inactive"; reason: string } | { status: "blocked"; reason: string };
|
|
126
|
-
|
|
127
|
-
export type CognitiveRoutingControllerState = {
|
|
128
|
-
effective: boolean;
|
|
129
|
-
controlMode: CognitiveRoutingControlMode;
|
|
130
|
-
runtimeStatus?: CognitiveRoutingRuntimeStatus;
|
|
131
|
-
runtimeReason?: string;
|
|
132
|
-
activeProfile?: CognitiveRoutingProfileName;
|
|
133
|
-
epoch?: string;
|
|
134
|
-
returnTarget?: CognitiveRoutingPair;
|
|
135
|
-
};
|
|
136
|
-
|
|
137
|
-
export type CognitiveRoutingActivationResult =
|
|
138
|
-
{ status: "active"; profile: CognitiveRoutingProfileName } | { status: "inactive"; reason: string };
|
|
139
|
-
|
|
140
|
-
export type CognitiveRoutingDeactivationResult = { status: "inactive"; reason: string };
|
|
141
|
-
export type CognitiveRoutingShutdownReason = "quit" | "reload" | "new" | "resume" | "fork" | undefined;
|
|
142
|
-
|
|
143
|
-
export type CognitiveRoutingManualResult =
|
|
144
|
-
{ status: "active"; profile: CognitiveRoutingProfileName } | { status: "inactive"; reason: string };
|
|
145
|
-
|
|
146
|
-
export type CognitiveRoutingAutomaticResult = { status: "automatic" } | { status: "rejected"; reason: string };
|
|
147
|
-
|
|
148
|
-
export type CognitiveRoutingSwitchResult =
|
|
149
|
-
| {
|
|
150
|
-
status: "active";
|
|
151
|
-
changed: boolean;
|
|
152
|
-
from: CognitiveRoutingProfileName;
|
|
153
|
-
to: CognitiveRoutingProfileName;
|
|
154
|
-
profile: CognitiveRoutingProfileName;
|
|
155
|
-
}
|
|
156
|
-
| { status: "blocked"; reason: string }
|
|
157
|
-
| { status: "inactive"; reason: string };
|
|
158
|
-
|
|
159
|
-
type CognitiveRoutingProfileTransitionResult =
|
|
160
|
-
{ status: "active"; profile: CognitiveRoutingProfileName } | { status: "inactive"; reason: string };
|
|
161
|
-
|
|
162
|
-
export type CognitiveRoutingRecoveryResult =
|
|
163
|
-
| { status: "active"; profile: CognitiveRoutingProfileName }
|
|
164
|
-
| { status: "pending"; reason: string }
|
|
165
|
-
| { status: "inactive"; reason: string };
|
|
166
|
-
|
|
167
|
-
export type CognitiveRoutingBranchResult =
|
|
168
|
-
| { status: "active"; profile: CognitiveRoutingProfileName }
|
|
169
|
-
| { status: "pending"; reason: string }
|
|
170
|
-
| { status: "inactive"; reason: string };
|
|
171
|
-
|
|
172
|
-
function isProfileName(value: unknown): value is CognitiveRoutingProfileName {
|
|
173
|
-
return value === "standard" || value === "reasoning";
|
|
174
|
-
}
|
|
175
|
-
|
|
176
|
-
function isMechanism(value: unknown): value is CognitiveRoutingMechanism {
|
|
177
|
-
return [
|
|
178
|
-
"agent-tool",
|
|
179
|
-
"profile-command",
|
|
180
|
-
"profile-shortcut",
|
|
181
|
-
"profile-settings",
|
|
182
|
-
"session-tree",
|
|
183
|
-
"session-compact",
|
|
184
|
-
"activation",
|
|
185
|
-
"reload-restore",
|
|
186
|
-
"recovery",
|
|
187
|
-
"shutdown-restore",
|
|
188
|
-
].includes(value as CognitiveRoutingMechanism);
|
|
189
|
-
}
|
|
190
|
-
|
|
191
|
-
function asIntentSource(value: unknown): "system" | "user" | "agent" {
|
|
192
|
-
if (value === "user" || value === "agent") return value;
|
|
193
|
-
return "system";
|
|
194
|
-
}
|
|
195
|
-
|
|
196
|
-
function pairEquals(a: CognitiveRoutingPair | undefined, b: CognitiveRoutingPair | undefined): boolean {
|
|
197
|
-
return a?.provider === b?.provider && a?.modelId === b?.modelId && a?.thinkingLevel === b?.thinkingLevel;
|
|
198
|
-
}
|
|
199
|
-
|
|
200
|
-
function asPair(value: unknown): CognitiveRoutingPair | undefined {
|
|
201
|
-
if (!value || typeof value !== "object") return undefined;
|
|
202
|
-
const candidate = value as Record<string, unknown>;
|
|
203
|
-
if (
|
|
204
|
-
typeof candidate.provider !== "string" ||
|
|
205
|
-
typeof candidate.modelId !== "string" ||
|
|
206
|
-
typeof candidate.thinkingLevel !== "string"
|
|
207
|
-
) {
|
|
208
|
-
return undefined;
|
|
209
|
-
}
|
|
210
|
-
return {
|
|
211
|
-
provider: candidate.provider,
|
|
212
|
-
modelId: candidate.modelId,
|
|
213
|
-
thinkingLevel: candidate.thinkingLevel as CognitiveRoutingThinkingLevel,
|
|
214
|
-
};
|
|
215
|
-
}
|
|
216
|
-
|
|
217
|
-
function hostPairFromEntry(entry: Record<string, unknown>): CognitiveRoutingPair | undefined {
|
|
218
|
-
if (entry.type === "model_state_change") {
|
|
219
|
-
return asPair({
|
|
220
|
-
provider: entry.provider,
|
|
221
|
-
modelId: entry.modelId,
|
|
222
|
-
thinkingLevel: entry.thinkingLevel,
|
|
223
|
-
});
|
|
224
|
-
}
|
|
225
|
-
if (entry.type !== "custom" || entry.customType !== PI_SESSION_MODEL_STATE_ENTRY) return undefined;
|
|
226
|
-
const commit = parsePiSessionModelStateCommit(entry.data);
|
|
227
|
-
if (!commit || commit.phase !== "committed" || commit.status !== "applied") return undefined;
|
|
228
|
-
return commit.target;
|
|
229
|
-
}
|
|
230
|
-
|
|
231
|
-
function hostCorrelationIdFromEntry(entry: Record<string, unknown>): string | undefined {
|
|
232
|
-
if (entry.type === "model_state_change") {
|
|
233
|
-
return typeof entry.correlationId === "string" ? entry.correlationId : undefined;
|
|
234
|
-
}
|
|
235
|
-
if (entry.type !== "custom" || entry.customType !== PI_SESSION_MODEL_STATE_ENTRY) return undefined;
|
|
236
|
-
const commit = parsePiSessionModelStateCommit(entry.data);
|
|
237
|
-
return commit?.phase === "committed" && commit.status === "applied" ? commit.correlationId : undefined;
|
|
238
|
-
}
|
|
239
|
-
|
|
240
|
-
function latestPiSessionCommit(entries: readonly unknown[], correlationId: string) {
|
|
241
|
-
for (let index = entries.length - 1; index >= 0; index -= 1) {
|
|
242
|
-
const entry = entries[index];
|
|
243
|
-
if (!entry || typeof entry !== "object") continue;
|
|
244
|
-
const candidate = entry as Record<string, unknown>;
|
|
245
|
-
if (candidate.type !== "custom" || candidate.customType !== PI_SESSION_MODEL_STATE_ENTRY) continue;
|
|
246
|
-
const commit = parsePiSessionModelStateCommit(candidate.data);
|
|
247
|
-
if (commit?.correlationId === correlationId) return commit;
|
|
248
|
-
}
|
|
249
|
-
return undefined;
|
|
250
|
-
}
|
|
251
|
-
|
|
252
|
-
function latestHostPair(context: ControllerContext): CognitiveRoutingPair | undefined {
|
|
253
|
-
const entries = branchEntriesFrom(context);
|
|
254
|
-
for (let index = entries.length - 1; index >= 0; index -= 1) {
|
|
255
|
-
const entry = entries[index];
|
|
256
|
-
if (!entry || typeof entry !== "object") continue;
|
|
257
|
-
const pair = hostPairFromEntry(entry as Record<string, unknown>);
|
|
258
|
-
if (pair) return pair;
|
|
259
|
-
}
|
|
260
|
-
return undefined;
|
|
261
|
-
}
|
|
262
|
-
|
|
263
|
-
function profileNameForPair(
|
|
264
|
-
capabilityState: CognitiveRoutingCapabilityState,
|
|
265
|
-
pair: CognitiveRoutingPair | undefined,
|
|
266
|
-
): CognitiveRoutingProfileName | undefined {
|
|
267
|
-
if (!pair) return undefined;
|
|
268
|
-
for (const [name, profile] of Object.entries(capabilityState.resolvedProfiles)) {
|
|
269
|
-
if (!profile) continue;
|
|
270
|
-
if (
|
|
271
|
-
pairEquals(pair, {
|
|
272
|
-
provider: profile.provider,
|
|
273
|
-
modelId: profile.model,
|
|
274
|
-
thinkingLevel: profile.effectiveThinkingLevel,
|
|
275
|
-
})
|
|
276
|
-
) {
|
|
277
|
-
return isProfileName(name) ? name : undefined;
|
|
278
|
-
}
|
|
279
|
-
}
|
|
280
|
-
return undefined;
|
|
281
|
-
}
|
|
282
|
-
|
|
283
|
-
function pairMatchesProfile(
|
|
284
|
-
capabilityState: CognitiveRoutingCapabilityState,
|
|
285
|
-
pair: CognitiveRoutingPair,
|
|
286
|
-
profileName: CognitiveRoutingProfileName,
|
|
287
|
-
): boolean {
|
|
288
|
-
const profile = capabilityState.resolvedProfiles[profileName];
|
|
289
|
-
return Boolean(
|
|
290
|
-
profile &&
|
|
291
|
-
pairEquals(pair, {
|
|
292
|
-
provider: profile.provider,
|
|
293
|
-
modelId: profile.model,
|
|
294
|
-
thinkingLevel: profile.effectiveThinkingLevel,
|
|
295
|
-
}),
|
|
296
|
-
);
|
|
297
|
-
}
|
|
298
|
-
|
|
299
|
-
function asIntent(value: unknown): CognitiveRoutingIntent | undefined {
|
|
300
|
-
if (!value || typeof value !== "object") return undefined;
|
|
301
|
-
const candidate = value as Record<string, unknown>;
|
|
302
|
-
if (
|
|
303
|
-
(candidate.version !== 1 && candidate.version !== 2) ||
|
|
304
|
-
(candidate.kind !== "activation" && candidate.kind !== "profile" && candidate.kind !== "closing") ||
|
|
305
|
-
(candidate.phase !== "prepared" && candidate.phase !== "abandoned") ||
|
|
306
|
-
typeof candidate.epoch !== "string" ||
|
|
307
|
-
typeof candidate.correlationId !== "string"
|
|
308
|
-
) {
|
|
309
|
-
return undefined;
|
|
310
|
-
}
|
|
311
|
-
const target = asPair(candidate.target);
|
|
312
|
-
const returnTarget = asPair(candidate.returnTarget);
|
|
313
|
-
const fromPair = asPair(candidate.fromPair);
|
|
314
|
-
if (!target || !returnTarget) return undefined;
|
|
315
|
-
return {
|
|
316
|
-
version: candidate.version,
|
|
317
|
-
kind: candidate.kind,
|
|
318
|
-
phase: candidate.phase,
|
|
319
|
-
control: candidate.control === "manual" ? "manual" : "automatic",
|
|
320
|
-
source: asIntentSource(candidate.source),
|
|
321
|
-
...(isMechanism(candidate.mechanism) ? { mechanism: candidate.mechanism } : {}),
|
|
322
|
-
...(typeof candidate.decisionCorrelationId === "string"
|
|
323
|
-
? { decisionCorrelationId: candidate.decisionCorrelationId }
|
|
324
|
-
: {}),
|
|
325
|
-
...(fromPair ? { fromPair } : {}),
|
|
326
|
-
...(isProfileName(candidate.fromProfile) ? { fromProfile: candidate.fromProfile } : {}),
|
|
327
|
-
...(candidate.fromControl === "automatic" || candidate.fromControl === "manual"
|
|
328
|
-
? { fromControl: candidate.fromControl }
|
|
329
|
-
: {}),
|
|
330
|
-
...(typeof candidate.reason === "string" ? { reason: candidate.reason } : {}),
|
|
331
|
-
...(typeof candidate.branchId === "string" || candidate.branchId === null
|
|
332
|
-
? { branchId: candidate.branchId as string | null }
|
|
333
|
-
: {}),
|
|
334
|
-
epoch: candidate.epoch,
|
|
335
|
-
correlationId: candidate.correlationId,
|
|
336
|
-
...(isProfileName(candidate.profile) ? { profile: candidate.profile } : {}),
|
|
337
|
-
...(isProfileName(candidate.resumeProfile) ? { resumeProfile: candidate.resumeProfile } : {}),
|
|
338
|
-
...(candidate.resumeControl === "automatic" || candidate.resumeControl === "manual"
|
|
339
|
-
? { resumeControl: candidate.resumeControl }
|
|
340
|
-
: {}),
|
|
341
|
-
...(typeof candidate.resumeReason === "string" ? { resumeReason: candidate.resumeReason } : {}),
|
|
342
|
-
target,
|
|
343
|
-
returnTarget,
|
|
344
|
-
};
|
|
345
|
-
}
|
|
346
|
-
|
|
347
|
-
function asInactiveEntry(value: unknown): CognitiveRoutingInactiveEntry | undefined {
|
|
348
|
-
if (!value || typeof value !== "object") return undefined;
|
|
349
|
-
const candidate = value as Record<string, unknown>;
|
|
350
|
-
const pair = asPair(candidate.pair);
|
|
351
|
-
if (
|
|
352
|
-
candidate.version !== 1 ||
|
|
353
|
-
candidate.source !== "user" ||
|
|
354
|
-
typeof candidate.reason !== "string" ||
|
|
355
|
-
candidate.reason.length === 0 ||
|
|
356
|
-
!pair
|
|
357
|
-
) {
|
|
358
|
-
return undefined;
|
|
359
|
-
}
|
|
360
|
-
return {
|
|
361
|
-
version: 1,
|
|
362
|
-
source: "user",
|
|
363
|
-
reason: candidate.reason,
|
|
364
|
-
...(typeof candidate.branchId === "string" || candidate.branchId === null
|
|
365
|
-
? { branchId: candidate.branchId as string | null }
|
|
366
|
-
: {}),
|
|
367
|
-
pair,
|
|
368
|
-
};
|
|
369
|
-
}
|
|
370
|
-
|
|
371
|
-
function latestInactiveEntry(
|
|
372
|
-
entries: readonly unknown[],
|
|
373
|
-
): { entry: CognitiveRoutingInactiveEntry; position: number } | undefined {
|
|
374
|
-
for (let index = entries.length - 1; index >= 0; index -= 1) {
|
|
375
|
-
const candidate = entries[index];
|
|
376
|
-
if (!candidate || typeof candidate !== "object") continue;
|
|
377
|
-
const record = candidate as Record<string, unknown>;
|
|
378
|
-
if (record.type !== "custom" || record.customType !== COGNITIVE_ROUTING_INACTIVE_ENTRY) continue;
|
|
379
|
-
const entry = asInactiveEntry(record.data);
|
|
380
|
-
if (entry) return { entry, position: index };
|
|
381
|
-
}
|
|
382
|
-
return undefined;
|
|
383
|
-
}
|
|
384
|
-
|
|
385
|
-
function entriesFrom(context: ControllerContext): readonly unknown[] {
|
|
386
|
-
try {
|
|
387
|
-
const entries = context.sessionManager?.getEntries?.();
|
|
388
|
-
return Array.isArray(entries) ? entries : [];
|
|
389
|
-
} catch {
|
|
390
|
-
return [];
|
|
391
|
-
}
|
|
392
|
-
}
|
|
393
|
-
|
|
394
|
-
function branchEntriesFrom(context: ControllerContext): readonly unknown[] {
|
|
395
|
-
try {
|
|
396
|
-
const entries = context.sessionManager?.getBranch?.();
|
|
397
|
-
return Array.isArray(entries) ? entries : entriesFrom(context);
|
|
398
|
-
} catch {
|
|
399
|
-
return entriesFrom(context);
|
|
400
|
-
}
|
|
401
|
-
}
|
|
402
|
-
|
|
403
|
-
function latestIntent(
|
|
404
|
-
entries: readonly unknown[],
|
|
405
|
-
predicate: (intent: CognitiveRoutingIntent) => boolean = () => true,
|
|
406
|
-
): CognitiveRoutingIntent | undefined {
|
|
407
|
-
const abandonedCorrelations = new Set<string>();
|
|
408
|
-
for (let index = entries.length - 1; index >= 0; index -= 1) {
|
|
409
|
-
const entry = entries[index];
|
|
410
|
-
if (!entry || typeof entry !== "object") continue;
|
|
411
|
-
const candidate = entry as Record<string, unknown>;
|
|
412
|
-
if (candidate.type !== "custom" || candidate.customType !== COGNITIVE_ROUTING_INTENT_ENTRY) continue;
|
|
413
|
-
const intent = asIntent(candidate.data);
|
|
414
|
-
if (!intent) continue;
|
|
415
|
-
if (intent.phase === "abandoned") {
|
|
416
|
-
abandonedCorrelations.add(intent.correlationId);
|
|
417
|
-
continue;
|
|
418
|
-
}
|
|
419
|
-
if (!abandonedCorrelations.has(intent.correlationId) && predicate(intent)) return intent;
|
|
420
|
-
}
|
|
421
|
-
return undefined;
|
|
422
|
-
}
|
|
423
|
-
|
|
424
|
-
function controlModeForIntent(intent: CognitiveRoutingIntent): CognitiveRoutingControlMode {
|
|
425
|
-
if (intent.control === "manual" && intent.profile) return `manual-${intent.profile}` as CognitiveRoutingControlMode;
|
|
426
|
-
return "automatic";
|
|
427
|
-
}
|
|
428
|
-
|
|
429
|
-
function decisionCorrelationForIntent(intent: CognitiveRoutingIntent): string | undefined {
|
|
430
|
-
if (intent.decisionCorrelationId) return intent.decisionCorrelationId;
|
|
431
|
-
return intent.source === "user" || intent.source === "agent" ? intent.correlationId : undefined;
|
|
432
|
-
}
|
|
433
|
-
|
|
434
|
-
function latestControlMode(entries: readonly unknown[], intent: CognitiveRoutingIntent): CognitiveRoutingControlMode {
|
|
435
|
-
for (let index = entries.length - 1; index >= 0; index -= 1) {
|
|
436
|
-
const entry = entries[index];
|
|
437
|
-
if (!entry || typeof entry !== "object") continue;
|
|
438
|
-
const candidate = entry as Record<string, unknown>;
|
|
439
|
-
if (candidate.type !== "custom") continue;
|
|
440
|
-
if (candidate.customType === COGNITIVE_ROUTING_CONTROL_ENTRY) {
|
|
441
|
-
const data = candidate.data;
|
|
442
|
-
if (
|
|
443
|
-
data &&
|
|
444
|
-
typeof data === "object" &&
|
|
445
|
-
((data as Record<string, unknown>).version === 1 || (data as Record<string, unknown>).version === 2) &&
|
|
446
|
-
(data as Record<string, unknown>).epoch === intent.epoch &&
|
|
447
|
-
(data as Record<string, unknown>).control === "automatic"
|
|
448
|
-
) {
|
|
449
|
-
return "automatic";
|
|
450
|
-
}
|
|
451
|
-
}
|
|
452
|
-
if (candidate.customType !== COGNITIVE_ROUTING_INTENT_ENTRY) continue;
|
|
453
|
-
const candidateIntent = asIntent(candidate.data);
|
|
454
|
-
if (!candidateIntent || candidateIntent.epoch !== intent.epoch) continue;
|
|
455
|
-
if (candidateIntent.phase === "abandoned") {
|
|
456
|
-
if (candidateIntent.fromControl === "manual" && candidateIntent.fromProfile) {
|
|
457
|
-
return `manual-${candidateIntent.fromProfile}` as CognitiveRoutingControlMode;
|
|
458
|
-
}
|
|
459
|
-
if (candidateIntent.fromControl === "automatic") return "automatic";
|
|
460
|
-
continue;
|
|
461
|
-
}
|
|
462
|
-
if (candidateIntent.kind === "profile" || candidateIntent.kind === "activation") {
|
|
463
|
-
return controlModeForIntent(candidateIntent);
|
|
464
|
-
}
|
|
465
|
-
}
|
|
466
|
-
return "automatic";
|
|
467
|
-
}
|
|
468
|
-
|
|
469
|
-
function intentEntryIndex(entries: readonly unknown[], intent: CognitiveRoutingIntent): number {
|
|
470
|
-
for (let index = 0; index < entries.length; index += 1) {
|
|
471
|
-
const entry = entries[index];
|
|
472
|
-
if (!entry || typeof entry !== "object") continue;
|
|
473
|
-
const candidate = entry as Record<string, unknown>;
|
|
474
|
-
if (candidate.type !== "custom" || candidate.customType !== COGNITIVE_ROUTING_INTENT_ENTRY) continue;
|
|
475
|
-
const parsed = asIntent(candidate.data);
|
|
476
|
-
if (parsed?.correlationId === intent.correlationId && parsed.phase === "prepared") return index;
|
|
477
|
-
}
|
|
478
|
-
return entries.length;
|
|
479
|
-
}
|
|
480
|
-
|
|
481
|
-
function matchesBaseline(candidate: CognitiveRoutingIntent, failed: CognitiveRoutingIntent): boolean {
|
|
482
|
-
if (failed.fromPair && !pairEquals(candidate.target, failed.fromPair)) return false;
|
|
483
|
-
if (failed.fromProfile && candidate.profile !== failed.fromProfile) return false;
|
|
484
|
-
return true;
|
|
485
|
-
}
|
|
486
|
-
|
|
487
|
-
export function resolveControlBeforeIntent(
|
|
488
|
-
entries: readonly unknown[],
|
|
489
|
-
intent: CognitiveRoutingIntent,
|
|
490
|
-
): CognitiveRoutingControlMode | undefined {
|
|
491
|
-
if (intent.fromControl === "automatic") return "automatic";
|
|
492
|
-
if (intent.fromControl === "manual") {
|
|
493
|
-
return intent.fromProfile ? (`manual-${intent.fromProfile}` as CognitiveRoutingControlMode) : undefined;
|
|
494
|
-
}
|
|
495
|
-
|
|
496
|
-
const priorEntries = entries.slice(0, intentEntryIndex(entries, intent));
|
|
497
|
-
const abandonedCorrelations = new Set<string>();
|
|
498
|
-
for (const entry of priorEntries) {
|
|
499
|
-
if (!entry || typeof entry !== "object") continue;
|
|
500
|
-
const candidate = entry as Record<string, unknown>;
|
|
501
|
-
if (candidate.type !== "custom" || candidate.customType !== COGNITIVE_ROUTING_INTENT_ENTRY) continue;
|
|
502
|
-
const parsed = asIntent(candidate.data);
|
|
503
|
-
if (parsed?.phase === "abandoned") abandonedCorrelations.add(parsed.correlationId);
|
|
504
|
-
}
|
|
505
|
-
|
|
506
|
-
let resolved: CognitiveRoutingControlMode | undefined;
|
|
507
|
-
for (const entry of priorEntries) {
|
|
508
|
-
if (!entry || typeof entry !== "object") continue;
|
|
509
|
-
const candidate = entry as Record<string, unknown>;
|
|
510
|
-
if (candidate.type !== "custom") continue;
|
|
511
|
-
if (candidate.customType === COGNITIVE_ROUTING_CONTROL_ENTRY) {
|
|
512
|
-
const data = candidate.data;
|
|
513
|
-
if (
|
|
514
|
-
data &&
|
|
515
|
-
typeof data === "object" &&
|
|
516
|
-
((data as Record<string, unknown>).version === 1 || (data as Record<string, unknown>).version === 2) &&
|
|
517
|
-
(data as Record<string, unknown>).epoch === intent.epoch &&
|
|
518
|
-
(data as Record<string, unknown>).control === "automatic"
|
|
519
|
-
) {
|
|
520
|
-
resolved = "automatic";
|
|
521
|
-
}
|
|
522
|
-
continue;
|
|
523
|
-
}
|
|
524
|
-
if (candidate.customType !== COGNITIVE_ROUTING_INTENT_ENTRY) continue;
|
|
525
|
-
const parsed = asIntent(candidate.data);
|
|
526
|
-
if (
|
|
527
|
-
!parsed ||
|
|
528
|
-
parsed.phase !== "prepared" ||
|
|
529
|
-
parsed.epoch !== intent.epoch ||
|
|
530
|
-
abandonedCorrelations.has(parsed.correlationId) ||
|
|
531
|
-
(parsed.kind !== "profile" && parsed.kind !== "activation") ||
|
|
532
|
-
!hasMatchingHostEntry(priorEntries, parsed) ||
|
|
533
|
-
!matchesBaseline(parsed, intent)
|
|
534
|
-
) {
|
|
535
|
-
continue;
|
|
536
|
-
}
|
|
537
|
-
resolved = controlModeForIntent(parsed);
|
|
538
|
-
}
|
|
539
|
-
return resolved;
|
|
540
|
-
}
|
|
541
|
-
|
|
542
|
-
function hasMatchingHostEntry(entries: readonly unknown[], intent: CognitiveRoutingIntent): boolean {
|
|
543
|
-
return entries.some((entry) => {
|
|
544
|
-
if (!entry || typeof entry !== "object") return false;
|
|
545
|
-
const candidate = entry as Record<string, unknown>;
|
|
546
|
-
return (
|
|
547
|
-
hostCorrelationIdFromEntry(candidate) === intent.correlationId &&
|
|
548
|
-
pairEquals(hostPairFromEntry(candidate), intent.target)
|
|
549
|
-
);
|
|
550
|
-
});
|
|
551
|
-
}
|
|
552
|
-
|
|
553
|
-
export class CognitiveRoutingController {
|
|
554
|
-
private readonly capabilityState: CognitiveRoutingCapabilityState;
|
|
555
|
-
private readonly pi: ControllerPi;
|
|
556
|
-
private readonly ctx: ControllerContext;
|
|
557
|
-
private readonly initialSessionStart: CognitiveRoutingSessionStart | undefined;
|
|
558
|
-
private readonly label: string;
|
|
559
|
-
private readonly idFactory: () => string;
|
|
560
|
-
private readonly liveStateAuthoritative: boolean;
|
|
561
|
-
private lease: ModelStateLease | undefined;
|
|
562
|
-
private activeProfile: CognitiveRoutingProfileName | undefined;
|
|
563
|
-
private epoch: string | undefined;
|
|
564
|
-
private returnTarget: CognitiveRoutingPair | undefined;
|
|
565
|
-
private controlMode: CognitiveRoutingControlMode = "automatic";
|
|
566
|
-
private nativeInactiveReason: string | undefined;
|
|
567
|
-
private nativeBlockedReason: string | undefined;
|
|
568
|
-
private transitionInFlight = false;
|
|
569
|
-
private branchPending = false;
|
|
570
|
-
private operation: Promise<unknown> = Promise.resolve();
|
|
571
|
-
|
|
572
|
-
constructor(options: ControllerOptions) {
|
|
573
|
-
this.capabilityState = options.capabilityState;
|
|
574
|
-
this.pi = options.pi;
|
|
575
|
-
this.ctx = options.ctx;
|
|
576
|
-
this.initialSessionStart = options.initialSessionStart;
|
|
577
|
-
this.label = options.label ?? "Cognitive Routing";
|
|
578
|
-
this.idFactory = options.idFactory ?? randomUUID;
|
|
579
|
-
this.liveStateAuthoritative = options.liveStateAuthoritative === true;
|
|
580
|
-
}
|
|
581
|
-
|
|
582
|
-
state(): CognitiveRoutingControllerState {
|
|
583
|
-
const hostPair = this.liveStateAuthoritative ? undefined : latestHostPair(this.ctx);
|
|
584
|
-
const observedPair = this.liveStateAuthoritative ? this.currentPair() : (hostPair ?? this.currentPair());
|
|
585
|
-
const observedProfile = this.activeProfile ? profileNameForPair(this.capabilityState, observedPair) : undefined;
|
|
586
|
-
const activeProfile = this.liveStateAuthoritative
|
|
587
|
-
? observedProfile
|
|
588
|
-
: hostPair
|
|
589
|
-
? observedProfile
|
|
590
|
-
: (observedProfile ?? this.activeProfile);
|
|
591
|
-
const effective = this.lease !== undefined && activeProfile !== undefined && !this.branchPending;
|
|
592
|
-
return {
|
|
593
|
-
effective,
|
|
594
|
-
controlMode: this.controlMode,
|
|
595
|
-
...(this.nativeBlockedReason
|
|
596
|
-
? { runtimeStatus: "blocked" as const, runtimeReason: this.nativeBlockedReason }
|
|
597
|
-
: this.nativeInactiveReason
|
|
598
|
-
? { runtimeStatus: "inactive" as const, runtimeReason: this.nativeInactiveReason }
|
|
599
|
-
: effective
|
|
600
|
-
? { runtimeStatus: "active" as const }
|
|
601
|
-
: {}),
|
|
602
|
-
...(activeProfile ? { activeProfile } : {}),
|
|
603
|
-
...(this.epoch ? { epoch: this.epoch } : {}),
|
|
604
|
-
...(this.returnTarget ? { returnTarget: { ...this.returnTarget } } : {}),
|
|
605
|
-
};
|
|
606
|
-
}
|
|
607
|
-
|
|
608
|
-
history(options: CognitiveRoutingHistoryOptions = {}): CognitiveRoutingHistoryResult {
|
|
609
|
-
const state = this.state();
|
|
610
|
-
const current: CognitiveRoutingHistoryCurrent = {
|
|
611
|
-
control: state.effective
|
|
612
|
-
? state.controlMode === "automatic"
|
|
613
|
-
? "automatic"
|
|
614
|
-
: "manual"
|
|
615
|
-
: ("unavailable" as const),
|
|
616
|
-
profile: state.effective && state.activeProfile ? state.activeProfile : ("unavailable" as const),
|
|
617
|
-
};
|
|
618
|
-
const profilePairs = {
|
|
619
|
-
...(this.capabilityState.resolvedProfiles.standard
|
|
620
|
-
? {
|
|
621
|
-
standard: {
|
|
622
|
-
provider: this.capabilityState.resolvedProfiles.standard.provider,
|
|
623
|
-
modelId: this.capabilityState.resolvedProfiles.standard.model,
|
|
624
|
-
thinkingLevel: this.capabilityState.resolvedProfiles.standard.effectiveThinkingLevel,
|
|
625
|
-
},
|
|
626
|
-
}
|
|
627
|
-
: {}),
|
|
628
|
-
...(this.capabilityState.resolvedProfiles.reasoning
|
|
629
|
-
? {
|
|
630
|
-
reasoning: {
|
|
631
|
-
provider: this.capabilityState.resolvedProfiles.reasoning.provider,
|
|
632
|
-
modelId: this.capabilityState.resolvedProfiles.reasoning.model,
|
|
633
|
-
thinkingLevel: this.capabilityState.resolvedProfiles.reasoning.effectiveThinkingLevel,
|
|
634
|
-
},
|
|
635
|
-
}
|
|
636
|
-
: {}),
|
|
637
|
-
};
|
|
638
|
-
return readCognitiveRoutingHistory(this.ctx, { ...options, current, profilePairs });
|
|
639
|
-
}
|
|
640
|
-
|
|
641
|
-
async activate(): Promise<CognitiveRoutingActivationResult> {
|
|
642
|
-
return this.enqueue(() => this._activate());
|
|
643
|
-
}
|
|
644
|
-
|
|
645
|
-
async deactivate(): Promise<CognitiveRoutingDeactivationResult> {
|
|
646
|
-
return this.enqueue(() => this._deactivate());
|
|
647
|
-
}
|
|
648
|
-
|
|
649
|
-
async shutdown(reason: CognitiveRoutingShutdownReason): Promise<CognitiveRoutingDeactivationResult> {
|
|
650
|
-
return this.enqueue(() =>
|
|
651
|
-
reason === "quit" ? this._releaseWithoutRestore() : this._deactivate(reason === "reload"),
|
|
652
|
-
);
|
|
653
|
-
}
|
|
654
|
-
|
|
655
|
-
async recover(): Promise<CognitiveRoutingRecoveryResult> {
|
|
656
|
-
return this.enqueue(() => this._recover());
|
|
657
|
-
}
|
|
658
|
-
|
|
659
|
-
async reconcileBranch(mechanism: CognitiveRoutingMechanism = "session-tree"): Promise<CognitiveRoutingBranchResult> {
|
|
660
|
-
return this.enqueue(() => this._reconcileBranch(mechanism));
|
|
661
|
-
}
|
|
662
|
-
|
|
663
|
-
async observeNativeChange(
|
|
664
|
-
reason: string,
|
|
665
|
-
source: "set" | "cycle" | "restore" | undefined = undefined,
|
|
666
|
-
): Promise<CognitiveRoutingNativeChangeResult> {
|
|
667
|
-
if (this.transitionInFlight || source === "restore") return { status: "ignored" };
|
|
668
|
-
return this.enqueue(() => this._observeNativeChange(reason, source));
|
|
669
|
-
}
|
|
670
|
-
|
|
671
|
-
async reconcileLiveState(reason = "Pi model state diverged"): Promise<CognitiveRoutingNativeChangeResult> {
|
|
672
|
-
if (this.transitionInFlight) return { status: "ignored" };
|
|
673
|
-
return this.enqueue(() => this._observeNativeChange(reason));
|
|
674
|
-
}
|
|
675
|
-
|
|
676
|
-
private recordNativeInactive(reason: string, pair: CognitiveRoutingPair): CognitiveRoutingNativeChangeResult {
|
|
677
|
-
try {
|
|
678
|
-
this.pi.appendEntryDurable(COGNITIVE_ROUTING_INACTIVE_ENTRY, {
|
|
679
|
-
version: 1,
|
|
680
|
-
source: "user",
|
|
681
|
-
reason,
|
|
682
|
-
branchId: this.currentBranchId(),
|
|
683
|
-
pair,
|
|
684
|
-
});
|
|
685
|
-
} catch {
|
|
686
|
-
this.nativeInactiveReason = undefined;
|
|
687
|
-
this.nativeBlockedReason = "inactive_state_persistence_failed";
|
|
688
|
-
return { status: "blocked", reason: this.nativeBlockedReason };
|
|
689
|
-
}
|
|
690
|
-
|
|
691
|
-
this.nativeInactiveReason = reason;
|
|
692
|
-
this.nativeBlockedReason = undefined;
|
|
693
|
-
return { status: "inactive", reason };
|
|
694
|
-
}
|
|
695
|
-
|
|
696
|
-
private async _observeNativeChange(
|
|
697
|
-
reason: string,
|
|
698
|
-
source: "set" | "cycle" | "restore" | undefined = undefined,
|
|
699
|
-
): Promise<CognitiveRoutingNativeChangeResult> {
|
|
700
|
-
if (!this.lease || !this.activeProfile) return { status: "ignored" };
|
|
701
|
-
|
|
702
|
-
const profile = this.capabilityState.resolvedProfiles[this.activeProfile];
|
|
703
|
-
const current = this.currentPair();
|
|
704
|
-
const expected = profile
|
|
705
|
-
? {
|
|
706
|
-
provider: profile.provider,
|
|
707
|
-
modelId: profile.model,
|
|
708
|
-
thinkingLevel: profile.effectiveThinkingLevel,
|
|
709
|
-
}
|
|
710
|
-
: undefined;
|
|
711
|
-
if (current && expected && pairEquals(current, expected) && source !== "set") return { status: "ignored" };
|
|
712
|
-
const lease = this.lease;
|
|
713
|
-
if (!current) {
|
|
714
|
-
await this.releaseLease(lease);
|
|
715
|
-
this.clearActiveState();
|
|
716
|
-
this.nativeBlockedReason = "native_state_unavailable";
|
|
717
|
-
return { status: "blocked", reason: this.nativeBlockedReason };
|
|
718
|
-
}
|
|
719
|
-
|
|
720
|
-
const result = this.recordNativeInactive(reason, current);
|
|
721
|
-
await this.releaseLease(lease);
|
|
722
|
-
this.clearActiveState();
|
|
723
|
-
return result;
|
|
724
|
-
}
|
|
725
|
-
|
|
726
|
-
private async _activate(
|
|
727
|
-
allowInactive = false,
|
|
728
|
-
requestedProfile?: CognitiveRoutingProfileName,
|
|
729
|
-
requestedControlMode?: CognitiveRoutingControlMode,
|
|
730
|
-
): Promise<CognitiveRoutingActivationResult> {
|
|
731
|
-
if (this.state().effective && this.activeProfile) {
|
|
732
|
-
return { status: "active", profile: this.activeProfile };
|
|
733
|
-
}
|
|
734
|
-
if (!this.capabilityState.effective) {
|
|
735
|
-
return { status: "inactive", reason: "not_effective" };
|
|
736
|
-
}
|
|
737
|
-
if ((this.nativeInactiveReason || this.nativeBlockedReason) && !allowInactive) {
|
|
738
|
-
return {
|
|
739
|
-
status: "inactive",
|
|
740
|
-
reason: this.nativeBlockedReason ? "runtime_blocked" : "native_override",
|
|
741
|
-
};
|
|
742
|
-
}
|
|
743
|
-
|
|
744
|
-
const sessionEntries = entriesFrom(this.ctx);
|
|
745
|
-
const lifecycleIntent = latestIntent(
|
|
746
|
-
sessionEntries,
|
|
747
|
-
(intent) => intent.kind === "activation" || intent.kind === "closing",
|
|
748
|
-
);
|
|
749
|
-
if (lifecycleIntent && !hasMatchingHostEntry(sessionEntries, lifecycleIntent)) {
|
|
750
|
-
return { status: "inactive", reason: "pending_intent" };
|
|
751
|
-
}
|
|
752
|
-
if (
|
|
753
|
-
lifecycleIntent?.kind === "activation" &&
|
|
754
|
-
!(allowInactive && (this.nativeInactiveReason || this.nativeBlockedReason))
|
|
755
|
-
) {
|
|
756
|
-
return { status: "inactive", reason: "recover_required" };
|
|
757
|
-
}
|
|
758
|
-
const preservedReload = lifecycleIntent?.kind === "closing" && lifecycleIntent.resumeProfile !== undefined;
|
|
759
|
-
if (preservedReload && !lifecycleIntent.resumeControl) {
|
|
760
|
-
return { status: "inactive", reason: "resume_state_invalid" };
|
|
761
|
-
}
|
|
762
|
-
const returnTarget = this.currentPair();
|
|
763
|
-
if (!returnTarget) {
|
|
764
|
-
return { status: "inactive", reason: "current_state_unavailable" };
|
|
765
|
-
}
|
|
766
|
-
const epoch = this.epoch ?? this.idFactory();
|
|
767
|
-
const branchId = this.currentBranchId();
|
|
768
|
-
const sessionStart = this.initialSessionStart ??
|
|
769
|
-
this.capabilityState.sessionStart ?? {
|
|
770
|
-
control: "automatic" as const,
|
|
771
|
-
profile: "reasoning" as const,
|
|
772
|
-
};
|
|
773
|
-
let profileName: CognitiveRoutingProfileName;
|
|
774
|
-
if (requestedProfile) {
|
|
775
|
-
profileName = requestedProfile;
|
|
776
|
-
} else if (preservedReload) {
|
|
777
|
-
profileName = lifecycleIntent.resumeProfile;
|
|
778
|
-
} else if (sessionStart.control === "automatic") {
|
|
779
|
-
profileName = "reasoning";
|
|
780
|
-
} else {
|
|
781
|
-
profileName = sessionStart.profile;
|
|
782
|
-
}
|
|
783
|
-
const profile = this.capabilityState.resolvedProfiles[profileName];
|
|
784
|
-
if (!profile) {
|
|
785
|
-
return { status: "inactive", reason: preservedReload ? "resume_profile_unavailable" : "profile_unavailable" };
|
|
786
|
-
}
|
|
787
|
-
let controlMode: CognitiveRoutingControlMode;
|
|
788
|
-
if (requestedControlMode) {
|
|
789
|
-
controlMode = requestedControlMode;
|
|
790
|
-
} else if (preservedReload) {
|
|
791
|
-
controlMode = lifecycleIntent.resumeControl === "manual" ? `manual-${profileName}` : "automatic";
|
|
792
|
-
} else {
|
|
793
|
-
controlMode = sessionStart.control === "manual" ? `manual-${profileName}` : "automatic";
|
|
794
|
-
}
|
|
795
|
-
const target = {
|
|
796
|
-
provider: profile.provider,
|
|
797
|
-
modelId: profile.model,
|
|
798
|
-
thinkingLevel: profile.effectiveThinkingLevel,
|
|
799
|
-
};
|
|
800
|
-
return this.activatePrepared({
|
|
801
|
-
kind: "activation",
|
|
802
|
-
controlMode,
|
|
803
|
-
source: "system",
|
|
804
|
-
mechanism: preservedReload ? "reload-restore" : "activation",
|
|
805
|
-
...(preservedReload && lifecycleIntent.resumeReason ? { reason: lifecycleIntent.resumeReason } : {}),
|
|
806
|
-
epoch,
|
|
807
|
-
branchId,
|
|
808
|
-
returnTarget,
|
|
809
|
-
target,
|
|
810
|
-
profile: profileName,
|
|
811
|
-
});
|
|
812
|
-
}
|
|
813
|
-
|
|
814
|
-
private async _releaseWithoutRestore(): Promise<CognitiveRoutingDeactivationResult> {
|
|
815
|
-
const lease = this.lease;
|
|
816
|
-
if (!lease) {
|
|
817
|
-
this.clearActiveState();
|
|
818
|
-
return { status: "inactive", reason: "not_active" };
|
|
819
|
-
}
|
|
820
|
-
await this.releaseLease(lease);
|
|
821
|
-
this.clearActiveState();
|
|
822
|
-
return { status: "inactive", reason: "released_on_quit" };
|
|
823
|
-
}
|
|
824
|
-
|
|
825
|
-
private async _deactivate(preserveSemanticState = false): Promise<CognitiveRoutingDeactivationResult> {
|
|
826
|
-
const lease = this.lease;
|
|
827
|
-
const returnTarget = this.returnTarget;
|
|
828
|
-
if (!lease || !returnTarget || !this.epoch) {
|
|
829
|
-
this.clearActiveState();
|
|
830
|
-
return { status: "inactive", reason: "not_active" };
|
|
831
|
-
}
|
|
832
|
-
|
|
833
|
-
const currentState = preserveSemanticState ? this.state() : undefined;
|
|
834
|
-
const resumeProfile = currentState?.effective ? currentState.activeProfile : undefined;
|
|
835
|
-
let resumeControl: "automatic" | "manual" | undefined;
|
|
836
|
-
if (resumeProfile && currentState?.controlMode === "automatic") {
|
|
837
|
-
resumeControl = "automatic";
|
|
838
|
-
} else if (resumeProfile && currentState?.controlMode === `manual-${resumeProfile}`) {
|
|
839
|
-
resumeControl = "manual";
|
|
840
|
-
}
|
|
841
|
-
const resumeIntent = resumeProfile
|
|
842
|
-
? latestIntent(
|
|
843
|
-
branchEntriesFrom(this.ctx),
|
|
844
|
-
(candidate) => candidate.kind === "profile" && candidate.epoch === this.epoch,
|
|
845
|
-
)
|
|
846
|
-
: undefined;
|
|
847
|
-
const fromPair = this.observedHostPair();
|
|
848
|
-
const fromProfile = this.activeProfile ?? profileNameForPair(this.capabilityState, fromPair);
|
|
849
|
-
const intent = this.prepareIntent({
|
|
850
|
-
kind: "closing",
|
|
851
|
-
control: "automatic",
|
|
852
|
-
source: "system",
|
|
853
|
-
mechanism: "shutdown-restore",
|
|
854
|
-
...(fromPair ? { fromPair } : {}),
|
|
855
|
-
...(fromProfile ? { fromProfile } : {}),
|
|
856
|
-
...(resumeProfile ? { resumeProfile } : {}),
|
|
857
|
-
...(resumeControl ? { resumeControl } : {}),
|
|
858
|
-
...(resumeIntent?.reason ? { resumeReason: resumeIntent.reason } : {}),
|
|
859
|
-
epoch: this.epoch,
|
|
860
|
-
correlationId: this.idFactory(),
|
|
861
|
-
branchId: this.currentBranchId(),
|
|
862
|
-
target: returnTarget,
|
|
863
|
-
returnTarget,
|
|
864
|
-
});
|
|
865
|
-
try {
|
|
866
|
-
this.pi.appendEntryDurable(COGNITIVE_ROUTING_INTENT_ENTRY, intent);
|
|
867
|
-
} catch {
|
|
868
|
-
await this.releaseLease(lease);
|
|
869
|
-
this.clearActiveState();
|
|
870
|
-
return { status: "inactive", reason: "prepare_failed" };
|
|
871
|
-
}
|
|
872
|
-
|
|
873
|
-
this.clearActiveState(false);
|
|
874
|
-
try {
|
|
875
|
-
const result = await this.setState(lease, { ...returnTarget, correlationId: intent.correlationId });
|
|
876
|
-
if (result.status !== "applied" && result.status !== "unchanged") {
|
|
877
|
-
return { status: "inactive", reason: "restore_rejected" };
|
|
878
|
-
}
|
|
879
|
-
return { status: "inactive", reason: "restored" };
|
|
880
|
-
} catch {
|
|
881
|
-
return { status: "inactive", reason: "restore_failed" };
|
|
882
|
-
} finally {
|
|
883
|
-
await this.releaseLease(lease);
|
|
884
|
-
}
|
|
885
|
-
}
|
|
886
|
-
|
|
887
|
-
private async recoverTerminalIntent(
|
|
888
|
-
intent: CognitiveRoutingIntent,
|
|
889
|
-
): Promise<CognitiveRoutingRecoveryResult | undefined> {
|
|
890
|
-
const commit = latestPiSessionCommit(branchEntriesFrom(this.ctx), intent.correlationId);
|
|
891
|
-
if (!commit) return undefined;
|
|
892
|
-
if (commit.phase === "prepared") {
|
|
893
|
-
if (!this.pi.recoverPreparedModelState) {
|
|
894
|
-
return { status: "pending", reason: "prepared_recovery_unsupported" };
|
|
895
|
-
}
|
|
896
|
-
let recovery: { status: "restored" | "rollback-failed" | "rejected" };
|
|
897
|
-
try {
|
|
898
|
-
recovery = await this.pi.recoverPreparedModelState({
|
|
899
|
-
fromPair: commit.fromPair,
|
|
900
|
-
target: commit.target,
|
|
901
|
-
correlationId: commit.correlationId,
|
|
902
|
-
});
|
|
903
|
-
} catch {
|
|
904
|
-
return { status: "pending", reason: "prepared_recovery_failed" };
|
|
905
|
-
}
|
|
906
|
-
if (recovery.status === "rollback-failed") {
|
|
907
|
-
return { status: "pending", reason: "rollback_failed" };
|
|
908
|
-
}
|
|
909
|
-
if (recovery.status !== "restored") {
|
|
910
|
-
return { status: "pending", reason: "prepared_recovery_failed" };
|
|
911
|
-
}
|
|
912
|
-
try {
|
|
913
|
-
this.abandonPreparedIntent(intent, "Pi session transition interrupted.");
|
|
914
|
-
} catch {
|
|
915
|
-
return { status: "pending", reason: "intent_abandon_failed" };
|
|
916
|
-
}
|
|
917
|
-
const recovered = await this._recover();
|
|
918
|
-
return recovered.status === "inactive" && recovered.reason === "no_pending_intent"
|
|
919
|
-
? { status: "inactive", reason: "intent_abandoned" }
|
|
920
|
-
: recovered;
|
|
921
|
-
}
|
|
922
|
-
if (commit.phase !== "aborted") return undefined;
|
|
923
|
-
if (commit.status === "rollback-failed") {
|
|
924
|
-
return { status: "pending", reason: "rollback_failed" };
|
|
925
|
-
}
|
|
926
|
-
|
|
927
|
-
try {
|
|
928
|
-
this.abandonPreparedIntent(intent, "Pi session transition rolled back.");
|
|
929
|
-
} catch {
|
|
930
|
-
return { status: "pending", reason: "intent_abandon_failed" };
|
|
931
|
-
}
|
|
932
|
-
return this._recover();
|
|
933
|
-
}
|
|
934
|
-
|
|
935
|
-
private async recoverTerminalProfileIntent(
|
|
936
|
-
intent: CognitiveRoutingIntent,
|
|
937
|
-
): Promise<CognitiveRoutingRecoveryResult | undefined> {
|
|
938
|
-
const commit = latestPiSessionCommit(branchEntriesFrom(this.ctx), intent.correlationId);
|
|
939
|
-
if (!commit || commit.phase === "committed") return undefined;
|
|
940
|
-
if (commit.phase === "aborted" && commit.status === "rollback-failed") {
|
|
941
|
-
return { status: "pending", reason: "rollback_failed" };
|
|
942
|
-
}
|
|
943
|
-
|
|
944
|
-
const controlMode = resolveControlBeforeIntent(branchEntriesFrom(this.ctx), intent);
|
|
945
|
-
if (
|
|
946
|
-
!controlMode ||
|
|
947
|
-
!intent.fromPair ||
|
|
948
|
-
!intent.fromProfile ||
|
|
949
|
-
!pairMatchesProfile(this.capabilityState, intent.fromPair, intent.fromProfile)
|
|
950
|
-
) {
|
|
951
|
-
return { status: "pending", reason: "baseline_control_unknown" };
|
|
952
|
-
}
|
|
953
|
-
|
|
954
|
-
if (commit.phase === "prepared") {
|
|
955
|
-
if (!this.pi.recoverPreparedModelState) {
|
|
956
|
-
return { status: "pending", reason: "prepared_recovery_unsupported" };
|
|
957
|
-
}
|
|
958
|
-
let recovery: { status: "restored" | "rollback-failed" | "rejected" };
|
|
959
|
-
try {
|
|
960
|
-
recovery = await this.pi.recoverPreparedModelState({
|
|
961
|
-
fromPair: commit.fromPair,
|
|
962
|
-
target: commit.target,
|
|
963
|
-
correlationId: commit.correlationId,
|
|
964
|
-
});
|
|
965
|
-
} catch {
|
|
966
|
-
return { status: "pending", reason: "prepared_recovery_failed" };
|
|
967
|
-
}
|
|
968
|
-
if (recovery.status === "rollback-failed") {
|
|
969
|
-
return { status: "pending", reason: "rollback_failed" };
|
|
970
|
-
}
|
|
971
|
-
if (recovery.status !== "restored") {
|
|
972
|
-
return { status: "pending", reason: "prepared_recovery_failed" };
|
|
973
|
-
}
|
|
974
|
-
}
|
|
975
|
-
|
|
976
|
-
try {
|
|
977
|
-
this.abandonPreparedIntent(intent, "Pi session transition interrupted or rolled back.");
|
|
978
|
-
} catch {
|
|
979
|
-
return { status: "pending", reason: "intent_abandon_failed" };
|
|
980
|
-
}
|
|
981
|
-
|
|
982
|
-
const recovered = await this.activatePrepared({
|
|
983
|
-
kind: "profile",
|
|
984
|
-
controlMode,
|
|
985
|
-
source: "system",
|
|
986
|
-
mechanism: "recovery",
|
|
987
|
-
...(decisionCorrelationForIntent(intent) ? { decisionCorrelationId: decisionCorrelationForIntent(intent) } : {}),
|
|
988
|
-
branchId: this.currentBranchId(),
|
|
989
|
-
epoch: intent.epoch,
|
|
990
|
-
returnTarget: intent.returnTarget,
|
|
991
|
-
target: intent.fromPair,
|
|
992
|
-
profile: intent.fromProfile,
|
|
993
|
-
});
|
|
994
|
-
return recovered.status === "active" ? recovered : { status: "pending", reason: "baseline_recovery_failed" };
|
|
995
|
-
}
|
|
996
|
-
|
|
997
|
-
private async _recover(): Promise<CognitiveRoutingRecoveryResult> {
|
|
998
|
-
const sessionEntries = entriesFrom(this.ctx);
|
|
999
|
-
const branchEntries = branchEntriesFrom(this.ctx);
|
|
1000
|
-
const inactive = latestInactiveEntry(branchEntries);
|
|
1001
|
-
const branchLifecycleIntent = latestIntent(
|
|
1002
|
-
branchEntries,
|
|
1003
|
-
(intent) => intent.kind === "activation" || intent.kind === "closing",
|
|
1004
|
-
);
|
|
1005
|
-
if (
|
|
1006
|
-
inactive &&
|
|
1007
|
-
(!branchLifecycleIntent || intentEntryIndex(branchEntries, branchLifecycleIntent) <= inactive.position)
|
|
1008
|
-
) {
|
|
1009
|
-
this.nativeInactiveReason = inactive.entry.reason;
|
|
1010
|
-
this.nativeBlockedReason = undefined;
|
|
1011
|
-
this.clearActiveState();
|
|
1012
|
-
return { status: "inactive", reason: "native_override" };
|
|
1013
|
-
}
|
|
1014
|
-
const lifecycleIntent = latestIntent(
|
|
1015
|
-
sessionEntries,
|
|
1016
|
-
(intent) => intent.kind === "activation" || intent.kind === "closing",
|
|
1017
|
-
);
|
|
1018
|
-
if (!lifecycleIntent) {
|
|
1019
|
-
return { status: "inactive", reason: "no_pending_intent" };
|
|
1020
|
-
}
|
|
1021
|
-
if (lifecycleIntent.kind === "activation") {
|
|
1022
|
-
const lifecycleTerminal = await this.recoverTerminalIntent(lifecycleIntent);
|
|
1023
|
-
if (lifecycleTerminal) return lifecycleTerminal;
|
|
1024
|
-
}
|
|
1025
|
-
if (lifecycleIntent.kind === "closing") {
|
|
1026
|
-
return hasMatchingHostEntry(sessionEntries, lifecycleIntent)
|
|
1027
|
-
? { status: "inactive", reason: "closed" }
|
|
1028
|
-
: this.recoverClosingIntent(lifecycleIntent);
|
|
1029
|
-
}
|
|
1030
|
-
|
|
1031
|
-
const currentActivationProfile = this.capabilityState.resolvedProfiles[lifecycleIntent.profile ?? "standard"];
|
|
1032
|
-
if (!this.capabilityState.effective) {
|
|
1033
|
-
return hasMatchingHostEntry(sessionEntries, lifecycleIntent)
|
|
1034
|
-
? { status: "inactive", reason: "not_effective" }
|
|
1035
|
-
: this.abandonIntent(lifecycleIntent, "Cognitive Routing is not effective.");
|
|
1036
|
-
}
|
|
1037
|
-
if (!currentActivationProfile) {
|
|
1038
|
-
return this.abandonIntent(lifecycleIntent, "Prepared profile is unavailable.");
|
|
1039
|
-
}
|
|
1040
|
-
const activationTarget = {
|
|
1041
|
-
provider: currentActivationProfile.provider,
|
|
1042
|
-
modelId: currentActivationProfile.model,
|
|
1043
|
-
thinkingLevel: currentActivationProfile.effectiveThinkingLevel,
|
|
1044
|
-
};
|
|
1045
|
-
const activationMatched = hasMatchingHostEntry(sessionEntries, lifecycleIntent);
|
|
1046
|
-
if (this.liveStateAuthoritative && activationMatched) {
|
|
1047
|
-
const livePair = this.currentPair();
|
|
1048
|
-
if (!livePair) {
|
|
1049
|
-
this.clearActiveState();
|
|
1050
|
-
this.nativeBlockedReason = "native_state_unavailable";
|
|
1051
|
-
return { status: "inactive", reason: "native_override" };
|
|
1052
|
-
}
|
|
1053
|
-
if (!pairEquals(livePair, activationTarget)) {
|
|
1054
|
-
this.recordNativeInactive("Pi model state diverged during recovery", livePair);
|
|
1055
|
-
this.clearActiveState();
|
|
1056
|
-
return { status: "inactive", reason: "native_override" };
|
|
1057
|
-
}
|
|
1058
|
-
}
|
|
1059
|
-
if (activationMatched && !pairEquals(activationTarget, lifecycleIntent.target)) {
|
|
1060
|
-
return { status: "pending", reason: "applied_target_changed" };
|
|
1061
|
-
}
|
|
1062
|
-
if (!activationMatched && !pairEquals(activationTarget, lifecycleIntent.target)) {
|
|
1063
|
-
return this.abandonIntent(lifecycleIntent, "Prepared profile target changed.");
|
|
1064
|
-
}
|
|
1065
|
-
if (!activationMatched) {
|
|
1066
|
-
const retried = await this.activatePrepared({
|
|
1067
|
-
kind: "activation",
|
|
1068
|
-
controlMode: latestControlMode(branchEntries, lifecycleIntent),
|
|
1069
|
-
source: "system",
|
|
1070
|
-
mechanism: "recovery",
|
|
1071
|
-
branchId: this.currentBranchId(),
|
|
1072
|
-
epoch: lifecycleIntent.epoch,
|
|
1073
|
-
returnTarget: lifecycleIntent.returnTarget,
|
|
1074
|
-
target: lifecycleIntent.target,
|
|
1075
|
-
profile: lifecycleIntent.profile ?? "standard",
|
|
1076
|
-
});
|
|
1077
|
-
return retried.status === "active" ? retried : { status: "pending", reason: "activation_recovery_failed" };
|
|
1078
|
-
}
|
|
1079
|
-
|
|
1080
|
-
const profileIntent = latestIntent(
|
|
1081
|
-
branchEntries,
|
|
1082
|
-
(intent) => intent.kind === "profile" && intent.epoch === lifecycleIntent.epoch,
|
|
1083
|
-
);
|
|
1084
|
-
if (profileIntent) {
|
|
1085
|
-
const terminal = await this.recoverTerminalProfileIntent(profileIntent);
|
|
1086
|
-
if (terminal) return terminal;
|
|
1087
|
-
const currentProfile = this.capabilityState.resolvedProfiles[profileIntent.profile ?? "standard"];
|
|
1088
|
-
if (!currentProfile) {
|
|
1089
|
-
return this.abandonIntent(profileIntent, "Prepared profile is unavailable.");
|
|
1090
|
-
}
|
|
1091
|
-
const profileTarget = {
|
|
1092
|
-
provider: currentProfile.provider,
|
|
1093
|
-
modelId: currentProfile.model,
|
|
1094
|
-
thinkingLevel: currentProfile.effectiveThinkingLevel,
|
|
1095
|
-
};
|
|
1096
|
-
if (!pairEquals(profileTarget, profileIntent.target)) {
|
|
1097
|
-
return hasMatchingHostEntry(branchEntries, profileIntent)
|
|
1098
|
-
? { status: "pending", reason: "applied_target_changed" }
|
|
1099
|
-
: this.abandonIntent(profileIntent, "Prepared profile target changed.");
|
|
1100
|
-
}
|
|
1101
|
-
const profileMatched = hasMatchingHostEntry(branchEntries, profileIntent);
|
|
1102
|
-
const retried = await this.activatePrepared({
|
|
1103
|
-
kind: "profile",
|
|
1104
|
-
controlMode: latestControlMode(branchEntries, profileIntent),
|
|
1105
|
-
source: "system",
|
|
1106
|
-
mechanism: "recovery",
|
|
1107
|
-
...(decisionCorrelationForIntent(profileIntent)
|
|
1108
|
-
? { decisionCorrelationId: decisionCorrelationForIntent(profileIntent) }
|
|
1109
|
-
: {}),
|
|
1110
|
-
branchId: this.currentBranchId(),
|
|
1111
|
-
epoch: lifecycleIntent.epoch,
|
|
1112
|
-
returnTarget: lifecycleIntent.returnTarget,
|
|
1113
|
-
target: profileMatched ? profileTarget : profileIntent.target,
|
|
1114
|
-
profile: profileIntent.profile ?? "standard",
|
|
1115
|
-
});
|
|
1116
|
-
return retried.status === "active" ? retried : { status: "pending", reason: "profile_recovery_failed" };
|
|
1117
|
-
}
|
|
1118
|
-
|
|
1119
|
-
return this.activatePrepared({
|
|
1120
|
-
kind: "activation",
|
|
1121
|
-
controlMode: latestControlMode(branchEntries, lifecycleIntent),
|
|
1122
|
-
source: "system",
|
|
1123
|
-
mechanism: "recovery",
|
|
1124
|
-
branchId: this.currentBranchId(),
|
|
1125
|
-
epoch: lifecycleIntent.epoch,
|
|
1126
|
-
returnTarget: lifecycleIntent.returnTarget,
|
|
1127
|
-
target: activationTarget,
|
|
1128
|
-
profile: lifecycleIntent.profile ?? "standard",
|
|
1129
|
-
});
|
|
1130
|
-
}
|
|
1131
|
-
|
|
1132
|
-
private async recoverClosingIntent(intent: CognitiveRoutingIntent): Promise<CognitiveRoutingRecoveryResult> {
|
|
1133
|
-
const fromPair = this.observedHostPair();
|
|
1134
|
-
const fromProfile = intent.fromProfile ?? profileNameForPair(this.capabilityState, fromPair);
|
|
1135
|
-
const retryIntent = this.prepareIntent({
|
|
1136
|
-
kind: "closing",
|
|
1137
|
-
control: "automatic",
|
|
1138
|
-
source: "system",
|
|
1139
|
-
mechanism: "shutdown-restore",
|
|
1140
|
-
...(fromPair ? { fromPair } : {}),
|
|
1141
|
-
...(fromProfile ? { fromProfile } : {}),
|
|
1142
|
-
reason: "Closing recovery",
|
|
1143
|
-
...(intent.resumeProfile ? { resumeProfile: intent.resumeProfile } : {}),
|
|
1144
|
-
...(intent.resumeControl ? { resumeControl: intent.resumeControl } : {}),
|
|
1145
|
-
...(intent.resumeReason ? { resumeReason: intent.resumeReason } : {}),
|
|
1146
|
-
branchId: this.currentBranchId(),
|
|
1147
|
-
epoch: intent.epoch,
|
|
1148
|
-
correlationId: this.idFactory(),
|
|
1149
|
-
target: intent.target,
|
|
1150
|
-
returnTarget: intent.returnTarget,
|
|
1151
|
-
});
|
|
1152
|
-
try {
|
|
1153
|
-
this.pi.appendEntryDurable(COGNITIVE_ROUTING_INTENT_ENTRY, retryIntent);
|
|
1154
|
-
} catch {
|
|
1155
|
-
return { status: "pending", reason: "closing_recovery_prepare_failed" };
|
|
1156
|
-
}
|
|
1157
|
-
|
|
1158
|
-
let acquisition: ModelStateAcquisition;
|
|
1159
|
-
try {
|
|
1160
|
-
acquisition = await this.pi.acquireModelStateControl({ label: this.label });
|
|
1161
|
-
} catch {
|
|
1162
|
-
return { status: "pending", reason: "closing_recovery_acquire_failed" };
|
|
1163
|
-
}
|
|
1164
|
-
if (acquisition.status !== "acquired") {
|
|
1165
|
-
return { status: "pending", reason: `closing_recovery_acquire_${acquisition.status}` };
|
|
1166
|
-
}
|
|
1167
|
-
|
|
1168
|
-
try {
|
|
1169
|
-
const result = await this.setState(acquisition.lease, {
|
|
1170
|
-
...intent.target,
|
|
1171
|
-
correlationId: retryIntent.correlationId,
|
|
1172
|
-
});
|
|
1173
|
-
return result.status === "applied" || result.status === "unchanged"
|
|
1174
|
-
? { status: "inactive", reason: "restored" }
|
|
1175
|
-
: { status: "pending", reason: "closing_recovery_rejected" };
|
|
1176
|
-
} catch {
|
|
1177
|
-
return { status: "pending", reason: "closing_recovery_failed" };
|
|
1178
|
-
} finally {
|
|
1179
|
-
await this.releaseLease(acquisition.lease);
|
|
1180
|
-
}
|
|
1181
|
-
}
|
|
1182
|
-
|
|
1183
|
-
private abandonPreparedIntent(intent: CognitiveRoutingIntent, reason: string): void {
|
|
1184
|
-
const fromPair = intent.fromPair ?? this.observedHostPair();
|
|
1185
|
-
const fromProfile = intent.fromProfile ?? profileNameForPair(this.capabilityState, fromPair);
|
|
1186
|
-
this.pi.appendEntryDurable(COGNITIVE_ROUTING_INTENT_ENTRY, {
|
|
1187
|
-
...intent,
|
|
1188
|
-
version: 2,
|
|
1189
|
-
phase: "abandoned",
|
|
1190
|
-
source: "system",
|
|
1191
|
-
mechanism: intent.mechanism ?? "recovery",
|
|
1192
|
-
...(fromPair ? { fromPair } : {}),
|
|
1193
|
-
...(fromProfile ? { fromProfile } : {}),
|
|
1194
|
-
reason,
|
|
1195
|
-
});
|
|
1196
|
-
}
|
|
1197
|
-
|
|
1198
|
-
private async abandonIntent(intent: CognitiveRoutingIntent, reason: string): Promise<CognitiveRoutingRecoveryResult> {
|
|
1199
|
-
try {
|
|
1200
|
-
this.abandonPreparedIntent(intent, reason);
|
|
1201
|
-
const recovered = await this._recover();
|
|
1202
|
-
return recovered.status === "inactive" && recovered.reason === "no_pending_intent"
|
|
1203
|
-
? { status: "inactive", reason: "intent_abandoned" }
|
|
1204
|
-
: recovered;
|
|
1205
|
-
} catch {
|
|
1206
|
-
return { status: "pending", reason: "intent_abandon_failed" };
|
|
1207
|
-
}
|
|
1208
|
-
}
|
|
1209
|
-
|
|
1210
|
-
private async _reconcileBranch(mechanism: CognitiveRoutingMechanism): Promise<CognitiveRoutingBranchResult> {
|
|
1211
|
-
if (!this.capabilityState.effective) return { status: "inactive", reason: "not_effective" };
|
|
1212
|
-
if (!this.activeProfile || !this.lease) {
|
|
1213
|
-
return { status: "inactive", reason: "not_active" };
|
|
1214
|
-
}
|
|
1215
|
-
|
|
1216
|
-
const currentProfile = this.activeProfile;
|
|
1217
|
-
const sessionEntries = entriesFrom(this.ctx);
|
|
1218
|
-
const lifecycleIntent = latestIntent(
|
|
1219
|
-
sessionEntries,
|
|
1220
|
-
(intent) => intent.kind === "activation" || intent.kind === "closing",
|
|
1221
|
-
);
|
|
1222
|
-
if (lifecycleIntent?.kind === "closing") {
|
|
1223
|
-
this.branchPending = true;
|
|
1224
|
-
return hasMatchingHostEntry(sessionEntries, lifecycleIntent)
|
|
1225
|
-
? { status: "inactive", reason: "closed" }
|
|
1226
|
-
: { status: "pending", reason: "closing_intent_unmatched" };
|
|
1227
|
-
}
|
|
1228
|
-
if (lifecycleIntent && !hasMatchingHostEntry(sessionEntries, lifecycleIntent)) {
|
|
1229
|
-
this.branchPending = true;
|
|
1230
|
-
return { status: "pending", reason: "activation_intent_unmatched" };
|
|
1231
|
-
}
|
|
1232
|
-
|
|
1233
|
-
const entries = branchEntriesFrom(this.ctx);
|
|
1234
|
-
const intent = latestIntent(
|
|
1235
|
-
entries,
|
|
1236
|
-
(candidate) => candidate.kind === "profile" && candidate.epoch === lifecycleIntent?.epoch,
|
|
1237
|
-
);
|
|
1238
|
-
if (!intent) {
|
|
1239
|
-
this.branchPending = false;
|
|
1240
|
-
return { status: "active", profile: currentProfile };
|
|
1241
|
-
}
|
|
1242
|
-
if (!hasMatchingHostEntry(entries, intent)) {
|
|
1243
|
-
this.branchPending = true;
|
|
1244
|
-
return { status: "pending", reason: "branch_intent_unmatched" };
|
|
1245
|
-
}
|
|
1246
|
-
|
|
1247
|
-
const decisionCorrelationId = decisionCorrelationForIntent(intent);
|
|
1248
|
-
if (intent.source === "system" && !decisionCorrelationId) {
|
|
1249
|
-
this.branchPending = false;
|
|
1250
|
-
return { status: "active", profile: currentProfile };
|
|
1251
|
-
}
|
|
1252
|
-
if (!intent.profile) {
|
|
1253
|
-
this.branchPending = false;
|
|
1254
|
-
return { status: "active", profile: currentProfile };
|
|
1255
|
-
}
|
|
1256
|
-
|
|
1257
|
-
const controlMode = latestControlMode(entries, intent);
|
|
1258
|
-
if (this.activeProfile === intent.profile && this.controlMode === controlMode) {
|
|
1259
|
-
this.branchPending = false;
|
|
1260
|
-
return { status: "active", profile: intent.profile };
|
|
1261
|
-
}
|
|
1262
|
-
const result = await this._setProfile(intent.profile, {
|
|
1263
|
-
controlMode,
|
|
1264
|
-
source: "system",
|
|
1265
|
-
mechanism,
|
|
1266
|
-
...(decisionCorrelationId ? { decisionCorrelationId } : {}),
|
|
1267
|
-
reason: "Branch reconciliation",
|
|
1268
|
-
});
|
|
1269
|
-
this.branchPending = result.status !== "active";
|
|
1270
|
-
return result;
|
|
1271
|
-
}
|
|
1272
|
-
|
|
1273
|
-
async setManualProfile(
|
|
1274
|
-
profile: CognitiveRoutingProfileName,
|
|
1275
|
-
mechanism: CognitiveRoutingMechanism = "profile-command",
|
|
1276
|
-
): Promise<CognitiveRoutingManualResult> {
|
|
1277
|
-
return this.enqueue(() => this._setManualProfile(profile, mechanism));
|
|
1278
|
-
}
|
|
1279
|
-
|
|
1280
|
-
async setAutomaticControl(
|
|
1281
|
-
mechanism: CognitiveRoutingMechanism = "profile-command",
|
|
1282
|
-
): Promise<CognitiveRoutingAutomaticResult> {
|
|
1283
|
-
return this.enqueue(() => this._setAutomaticControl(mechanism));
|
|
1284
|
-
}
|
|
1285
|
-
|
|
1286
|
-
async switchAutomaticProfile(
|
|
1287
|
-
profile: CognitiveRoutingProfileName,
|
|
1288
|
-
reason: string,
|
|
1289
|
-
source: "agent" | "system" | "user" = "agent",
|
|
1290
|
-
mechanism: CognitiveRoutingMechanism = "agent-tool",
|
|
1291
|
-
): Promise<CognitiveRoutingSwitchResult> {
|
|
1292
|
-
return this.enqueue(() => this._switchAutomaticProfile(profile, reason, source, mechanism));
|
|
1293
|
-
}
|
|
1294
|
-
|
|
1295
|
-
private async _setManualProfile(
|
|
1296
|
-
profile: CognitiveRoutingProfileName,
|
|
1297
|
-
mechanism: CognitiveRoutingMechanism,
|
|
1298
|
-
): Promise<CognitiveRoutingManualResult> {
|
|
1299
|
-
if (!this.capabilityState.effective) {
|
|
1300
|
-
return { status: "inactive", reason: "not_effective" };
|
|
1301
|
-
}
|
|
1302
|
-
|
|
1303
|
-
if (!this.state().effective) {
|
|
1304
|
-
return this._activate(true, profile, `manual-${profile}`);
|
|
1305
|
-
}
|
|
1306
|
-
return this._setProfile(profile, {
|
|
1307
|
-
controlMode: `manual-${profile}`,
|
|
1308
|
-
source: "user",
|
|
1309
|
-
mechanism,
|
|
1310
|
-
reason: "manual profile command",
|
|
1311
|
-
});
|
|
1312
|
-
}
|
|
1313
|
-
|
|
1314
|
-
private async _switchAutomaticProfile(
|
|
1315
|
-
profile: CognitiveRoutingProfileName,
|
|
1316
|
-
reason: string,
|
|
1317
|
-
source: "agent" | "system" | "user",
|
|
1318
|
-
mechanism: CognitiveRoutingMechanism,
|
|
1319
|
-
): Promise<CognitiveRoutingSwitchResult> {
|
|
1320
|
-
if (!this.capabilityState.effective) return { status: "blocked", reason: "not_effective" };
|
|
1321
|
-
const current = this.state();
|
|
1322
|
-
if (!current.effective) return { status: "blocked", reason: "not_active" };
|
|
1323
|
-
if (this.controlMode !== "automatic") return { status: "blocked", reason: "manual_hold" };
|
|
1324
|
-
const from = current.activeProfile;
|
|
1325
|
-
if (!from) return { status: "blocked", reason: "profile_unknown" };
|
|
1326
|
-
if (from === profile) return { status: "active", changed: false, from, to: profile, profile };
|
|
1327
|
-
|
|
1328
|
-
const transition = await this._setProfile(profile, { controlMode: "automatic", source, reason, mechanism });
|
|
1329
|
-
if (transition.status !== "active") return transition;
|
|
1330
|
-
return { status: "active", changed: true, from, to: transition.profile, profile: transition.profile };
|
|
1331
|
-
}
|
|
1332
|
-
|
|
1333
|
-
private async _setProfile(
|
|
1334
|
-
profile: CognitiveRoutingProfileName,
|
|
1335
|
-
options: {
|
|
1336
|
-
controlMode: CognitiveRoutingControlMode;
|
|
1337
|
-
source: "system" | "user" | "agent";
|
|
1338
|
-
mechanism: CognitiveRoutingMechanism;
|
|
1339
|
-
decisionCorrelationId?: string;
|
|
1340
|
-
reason: string;
|
|
1341
|
-
},
|
|
1342
|
-
): Promise<CognitiveRoutingProfileTransitionResult> {
|
|
1343
|
-
const resolvedProfile = this.capabilityState.resolvedProfiles[profile];
|
|
1344
|
-
const lease = this.lease;
|
|
1345
|
-
if (!resolvedProfile || !lease || !this.epoch || !this.returnTarget) {
|
|
1346
|
-
return { status: "inactive", reason: "profile_unavailable" };
|
|
1347
|
-
}
|
|
1348
|
-
const target = {
|
|
1349
|
-
provider: resolvedProfile.provider,
|
|
1350
|
-
modelId: resolvedProfile.model,
|
|
1351
|
-
thinkingLevel: resolvedProfile.effectiveThinkingLevel,
|
|
1352
|
-
};
|
|
1353
|
-
const fromPair = this.observedHostPair();
|
|
1354
|
-
if (!fromPair) return { status: "inactive", reason: "current_state_unavailable" };
|
|
1355
|
-
const fromProfile = this.activeProfile ?? profileNameForPair(this.capabilityState, fromPair);
|
|
1356
|
-
const correlationId = this.idFactory();
|
|
1357
|
-
const decisionCorrelationId =
|
|
1358
|
-
options.decisionCorrelationId ??
|
|
1359
|
-
(options.source === "user" || options.source === "agent" ? correlationId : undefined);
|
|
1360
|
-
const intent = this.prepareIntent({
|
|
1361
|
-
kind: "profile",
|
|
1362
|
-
control: options.controlMode === "automatic" ? "automatic" : "manual",
|
|
1363
|
-
source: options.source,
|
|
1364
|
-
mechanism: options.mechanism,
|
|
1365
|
-
...(decisionCorrelationId ? { decisionCorrelationId } : {}),
|
|
1366
|
-
...(fromPair ? { fromPair } : {}),
|
|
1367
|
-
...(fromProfile ? { fromProfile } : {}),
|
|
1368
|
-
fromControl: options.controlMode === "automatic" ? "automatic" : "manual",
|
|
1369
|
-
reason: options.reason,
|
|
1370
|
-
branchId: this.currentBranchId(),
|
|
1371
|
-
epoch: this.epoch,
|
|
1372
|
-
correlationId,
|
|
1373
|
-
profile,
|
|
1374
|
-
target,
|
|
1375
|
-
returnTarget: this.returnTarget,
|
|
1376
|
-
});
|
|
1377
|
-
const sessionEntries = entriesFrom(this.ctx);
|
|
1378
|
-
const lifecycleIntent = latestIntent(
|
|
1379
|
-
sessionEntries,
|
|
1380
|
-
(candidate) => candidate.kind === "activation" || candidate.kind === "closing",
|
|
1381
|
-
);
|
|
1382
|
-
if (lifecycleIntent && !hasMatchingHostEntry(sessionEntries, lifecycleIntent)) {
|
|
1383
|
-
return { status: "inactive", reason: "pending_intent" };
|
|
1384
|
-
}
|
|
1385
|
-
const entries = branchEntriesFrom(this.ctx);
|
|
1386
|
-
const latest = latestIntent(entries, (candidate) => candidate.kind === "profile" && candidate.epoch === this.epoch);
|
|
1387
|
-
if (latest && !hasMatchingHostEntry(entries, latest)) {
|
|
1388
|
-
return { status: "inactive", reason: "pending_intent" };
|
|
1389
|
-
}
|
|
1390
|
-
try {
|
|
1391
|
-
this.pi.appendEntryDurable(COGNITIVE_ROUTING_INTENT_ENTRY, intent);
|
|
1392
|
-
this.branchPending = true;
|
|
1393
|
-
} catch {
|
|
1394
|
-
return { status: "inactive", reason: "prepare_failed" };
|
|
1395
|
-
}
|
|
1396
|
-
|
|
1397
|
-
try {
|
|
1398
|
-
const result = await this.setState(lease, { ...target, correlationId: intent.correlationId });
|
|
1399
|
-
if (result.status !== "applied" && result.status !== "unchanged") {
|
|
1400
|
-
const commit = latestPiSessionCommit(branchEntriesFrom(this.ctx), intent.correlationId);
|
|
1401
|
-
if (result.status === "rejected" && commit?.phase === "aborted" && commit.status === "rollback-failed") {
|
|
1402
|
-
try {
|
|
1403
|
-
this.abandonPreparedIntent(intent, "Pi session rollback failed.");
|
|
1404
|
-
} catch {
|
|
1405
|
-
// Fail closed even when the terminal abandonment cannot be persisted.
|
|
1406
|
-
}
|
|
1407
|
-
await this.releaseLease(lease);
|
|
1408
|
-
this.clearActiveState();
|
|
1409
|
-
return { status: "inactive", reason: "rollback_failed" };
|
|
1410
|
-
}
|
|
1411
|
-
if (result.status === "rejected" && commit?.phase === "aborted" && commit.status === "rolled-back") {
|
|
1412
|
-
try {
|
|
1413
|
-
this.abandonPreparedIntent(intent, "Pi session transition rolled back.");
|
|
1414
|
-
this.branchPending = false;
|
|
1415
|
-
} catch {
|
|
1416
|
-
// Preserve the pending boundary when the terminal abandonment cannot be persisted.
|
|
1417
|
-
}
|
|
1418
|
-
}
|
|
1419
|
-
return { status: "inactive", reason: "transition_rejected" };
|
|
1420
|
-
}
|
|
1421
|
-
this.activeProfile = profile;
|
|
1422
|
-
this.controlMode = options.controlMode;
|
|
1423
|
-
this.branchPending = false;
|
|
1424
|
-
return { status: "active", profile };
|
|
1425
|
-
} catch {
|
|
1426
|
-
return { status: "inactive", reason: "transition_failed" };
|
|
1427
|
-
}
|
|
1428
|
-
}
|
|
1429
|
-
|
|
1430
|
-
private async _setAutomaticControl(mechanism: CognitiveRoutingMechanism): Promise<CognitiveRoutingAutomaticResult> {
|
|
1431
|
-
if (!this.lease || !this.epoch) {
|
|
1432
|
-
if (!this.nativeInactiveReason && !this.nativeBlockedReason) return { status: "rejected", reason: "not_active" };
|
|
1433
|
-
const activation = await this._activate(true, this.profileForCurrentPair(), "automatic");
|
|
1434
|
-
return activation.status === "active"
|
|
1435
|
-
? { status: "automatic" }
|
|
1436
|
-
: { status: "rejected", reason: activation.reason };
|
|
1437
|
-
}
|
|
1438
|
-
const current = this.state();
|
|
1439
|
-
if (!current.activeProfile) {
|
|
1440
|
-
return { status: "rejected", reason: "profile_unknown" };
|
|
1441
|
-
}
|
|
1442
|
-
if (current.activeProfile !== "reasoning") {
|
|
1443
|
-
const transition = await this._setProfile("reasoning", {
|
|
1444
|
-
controlMode: "automatic",
|
|
1445
|
-
source: "user",
|
|
1446
|
-
mechanism,
|
|
1447
|
-
reason: "automatic control selects the Reasoning profile",
|
|
1448
|
-
});
|
|
1449
|
-
if (transition.status !== "active") return { status: "rejected", reason: transition.reason };
|
|
1450
|
-
return { status: "automatic" };
|
|
1451
|
-
}
|
|
1452
|
-
if (this.controlMode === "automatic") return { status: "automatic" };
|
|
1453
|
-
try {
|
|
1454
|
-
this.pi.appendEntryDurable(COGNITIVE_ROUTING_CONTROL_ENTRY, {
|
|
1455
|
-
version: 2,
|
|
1456
|
-
control: "automatic",
|
|
1457
|
-
source: "user",
|
|
1458
|
-
mechanism,
|
|
1459
|
-
reason: "manual hold release",
|
|
1460
|
-
branchId: this.currentBranchId(),
|
|
1461
|
-
epoch: this.epoch,
|
|
1462
|
-
});
|
|
1463
|
-
} catch {
|
|
1464
|
-
return { status: "rejected", reason: "prepare_failed" };
|
|
1465
|
-
}
|
|
1466
|
-
this.controlMode = "automatic";
|
|
1467
|
-
return { status: "automatic" };
|
|
1468
|
-
}
|
|
1469
|
-
|
|
1470
|
-
private currentBranchId(): string | null | undefined {
|
|
1471
|
-
const leafId = this.ctx.sessionManager?.getLeafId?.();
|
|
1472
|
-
if (typeof leafId === "string" || leafId === null) return leafId;
|
|
1473
|
-
try {
|
|
1474
|
-
const branch = this.ctx.sessionManager?.getBranch?.();
|
|
1475
|
-
const last = Array.isArray(branch) ? branch.at(-1) : undefined;
|
|
1476
|
-
return last && typeof last === "object" && typeof (last as Record<string, unknown>).id === "string"
|
|
1477
|
-
? ((last as Record<string, unknown>).id as string)
|
|
1478
|
-
: undefined;
|
|
1479
|
-
} catch {
|
|
1480
|
-
return undefined;
|
|
1481
|
-
}
|
|
1482
|
-
}
|
|
1483
|
-
|
|
1484
|
-
private observedHostPair(): CognitiveRoutingPair | undefined {
|
|
1485
|
-
const livePair = this.currentPair();
|
|
1486
|
-
return this.liveStateAuthoritative ? livePair : (latestHostPair(this.ctx) ?? livePair);
|
|
1487
|
-
}
|
|
1488
|
-
|
|
1489
|
-
private profileForCurrentPair(): CognitiveRoutingProfileName | undefined {
|
|
1490
|
-
return profileNameForPair(this.capabilityState, this.currentPair());
|
|
1491
|
-
}
|
|
1492
|
-
|
|
1493
|
-
private currentPair(): CognitiveRoutingPair | undefined {
|
|
1494
|
-
const model = this.ctx.model;
|
|
1495
|
-
if (
|
|
1496
|
-
!model ||
|
|
1497
|
-
typeof model.provider !== "string" ||
|
|
1498
|
-
typeof model.id !== "string" ||
|
|
1499
|
-
typeof this.ctx.thinkingLevel !== "string"
|
|
1500
|
-
) {
|
|
1501
|
-
return undefined;
|
|
1502
|
-
}
|
|
1503
|
-
return {
|
|
1504
|
-
provider: model.provider,
|
|
1505
|
-
modelId: model.id,
|
|
1506
|
-
thinkingLevel: this.ctx.thinkingLevel,
|
|
1507
|
-
};
|
|
1508
|
-
}
|
|
1509
|
-
|
|
1510
|
-
private prepareIntent(input: Omit<CognitiveRoutingIntent, "version" | "phase">): CognitiveRoutingIntent {
|
|
1511
|
-
return { version: 2, phase: "prepared", ...input };
|
|
1512
|
-
}
|
|
1513
|
-
|
|
1514
|
-
private async activatePrepared(options: {
|
|
1515
|
-
kind: "activation" | "profile";
|
|
1516
|
-
controlMode: CognitiveRoutingControlMode;
|
|
1517
|
-
source: "system" | "user" | "agent";
|
|
1518
|
-
mechanism: CognitiveRoutingMechanism;
|
|
1519
|
-
decisionCorrelationId?: string;
|
|
1520
|
-
branchId?: string | null;
|
|
1521
|
-
reason?: string;
|
|
1522
|
-
epoch: string;
|
|
1523
|
-
returnTarget: CognitiveRoutingPair;
|
|
1524
|
-
target: CognitiveRoutingPair;
|
|
1525
|
-
profile: CognitiveRoutingProfileName;
|
|
1526
|
-
}): Promise<CognitiveRoutingActivationResult> {
|
|
1527
|
-
const fromPair = this.observedHostPair();
|
|
1528
|
-
if (!fromPair) return { status: "inactive", reason: "current_state_unavailable" };
|
|
1529
|
-
const fromProfile = profileNameForPair(this.capabilityState, fromPair);
|
|
1530
|
-
const correlationId = this.idFactory();
|
|
1531
|
-
const decisionCorrelationId =
|
|
1532
|
-
options.decisionCorrelationId ??
|
|
1533
|
-
(options.source === "user" || options.source === "agent" ? correlationId : undefined);
|
|
1534
|
-
const intent = this.prepareIntent({
|
|
1535
|
-
kind: options.kind,
|
|
1536
|
-
control: options.controlMode === "automatic" ? "automatic" : "manual",
|
|
1537
|
-
source: options.source,
|
|
1538
|
-
mechanism: options.mechanism,
|
|
1539
|
-
...(decisionCorrelationId ? { decisionCorrelationId } : {}),
|
|
1540
|
-
...(fromPair ? { fromPair } : {}),
|
|
1541
|
-
...(fromProfile ? { fromProfile } : {}),
|
|
1542
|
-
...(options.reason ? { reason: options.reason } : {}),
|
|
1543
|
-
...(options.branchId === undefined ? {} : { branchId: options.branchId }),
|
|
1544
|
-
epoch: options.epoch,
|
|
1545
|
-
correlationId,
|
|
1546
|
-
profile: options.profile,
|
|
1547
|
-
target: options.target,
|
|
1548
|
-
returnTarget: options.returnTarget,
|
|
1549
|
-
});
|
|
1550
|
-
try {
|
|
1551
|
-
this.pi.appendEntryDurable(COGNITIVE_ROUTING_INTENT_ENTRY, intent);
|
|
1552
|
-
} catch {
|
|
1553
|
-
return { status: "inactive", reason: "prepare_failed" };
|
|
1554
|
-
}
|
|
1555
|
-
|
|
1556
|
-
let acquisition: ModelStateAcquisition;
|
|
1557
|
-
try {
|
|
1558
|
-
acquisition = await this.pi.acquireModelStateControl({ label: this.label });
|
|
1559
|
-
} catch {
|
|
1560
|
-
return { status: "inactive", reason: "acquire_failed" };
|
|
1561
|
-
}
|
|
1562
|
-
if (acquisition.status !== "acquired") {
|
|
1563
|
-
return { status: "inactive", reason: `acquire_${acquisition.status}` };
|
|
1564
|
-
}
|
|
1565
|
-
|
|
1566
|
-
this.lease = acquisition.lease;
|
|
1567
|
-
try {
|
|
1568
|
-
const result = await this.setState(acquisition.lease, { ...options.target, correlationId: intent.correlationId });
|
|
1569
|
-
if (result.status !== "applied" && result.status !== "unchanged") {
|
|
1570
|
-
await this.releaseLease(acquisition.lease);
|
|
1571
|
-
this.clearActiveState();
|
|
1572
|
-
return { status: "inactive", reason: "transition_rejected" };
|
|
1573
|
-
}
|
|
1574
|
-
this.epoch = options.epoch;
|
|
1575
|
-
this.returnTarget = options.returnTarget;
|
|
1576
|
-
this.activeProfile = options.profile;
|
|
1577
|
-
this.controlMode = options.controlMode;
|
|
1578
|
-
this.nativeInactiveReason = undefined;
|
|
1579
|
-
this.nativeBlockedReason = undefined;
|
|
1580
|
-
return { status: "active", profile: options.profile };
|
|
1581
|
-
} catch {
|
|
1582
|
-
await this.releaseLease(acquisition.lease);
|
|
1583
|
-
this.clearActiveState();
|
|
1584
|
-
return { status: "inactive", reason: "transition_failed" };
|
|
1585
|
-
}
|
|
1586
|
-
}
|
|
1587
|
-
|
|
1588
|
-
private enqueue<T>(operation: () => Promise<T>): Promise<T> {
|
|
1589
|
-
const next = this.operation.then(operation, operation);
|
|
1590
|
-
this.operation = next.then(
|
|
1591
|
-
() => undefined,
|
|
1592
|
-
() => undefined,
|
|
1593
|
-
);
|
|
1594
|
-
return next;
|
|
1595
|
-
}
|
|
1596
|
-
|
|
1597
|
-
private async setState(
|
|
1598
|
-
lease: ModelStateLease,
|
|
1599
|
-
request: CognitiveRoutingPair & { correlationId: string },
|
|
1600
|
-
): Promise<{ status: string }> {
|
|
1601
|
-
this.transitionInFlight = true;
|
|
1602
|
-
try {
|
|
1603
|
-
return await lease.setState(request);
|
|
1604
|
-
} finally {
|
|
1605
|
-
this.transitionInFlight = false;
|
|
1606
|
-
}
|
|
1607
|
-
}
|
|
1608
|
-
|
|
1609
|
-
private async releaseLease(lease: ModelStateLease): Promise<void> {
|
|
1610
|
-
try {
|
|
1611
|
-
await lease.release();
|
|
1612
|
-
} catch {
|
|
1613
|
-
// The host invalidates stale leases independently; do not retain local ownership after cleanup.
|
|
1614
|
-
}
|
|
1615
|
-
if (this.lease === lease) this.lease = undefined;
|
|
1616
|
-
}
|
|
1617
|
-
|
|
1618
|
-
private clearActiveState(clearReturnTarget = true): void {
|
|
1619
|
-
this.lease = undefined;
|
|
1620
|
-
this.activeProfile = undefined;
|
|
1621
|
-
this.controlMode = "automatic";
|
|
1622
|
-
this.branchPending = false;
|
|
1623
|
-
if (clearReturnTarget) {
|
|
1624
|
-
this.epoch = undefined;
|
|
1625
|
-
this.returnTarget = undefined;
|
|
1626
|
-
}
|
|
1627
|
-
}
|
|
1628
|
-
}
|