@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,1292 +0,0 @@
|
|
|
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
|
-
}
|