@alexeiled/claude-router 1.23.1 → 1.24.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,407 @@
1
+ // Pure demand → target → move engine. No controller or host calls; table routing does not import this module.
2
+ import { TIERS } from './config.mjs';
3
+ import * as costs from './cost.mjs';
4
+ import { CONTEXT_FILL, sameTaskOf } from './policy.mjs';
5
+ import { canonicalModel } from './providers.mjs';
6
+ import { isModelAllowed } from './route.mjs';
7
+
8
+ const MODES = { cost: -0.5, balanced: 0, quality: 0.5 };
9
+ const clamp = (n) => Math.max(0, Math.min(3, n));
10
+ const sameRoute = (a, b) => a?.model === b?.model && a?.effort === b?.effort;
11
+ const samePhysical = (a, b) =>
12
+ a.requestKey && b.requestKey ? a.requestKey === b.requestKey : sameRoute(a.route, b.route);
13
+ const validLevel = (n) => Number.isFinite(n) && n >= 0 && n <= 3 && Number.isInteger(n * 2);
14
+
15
+ export function initialAutoState({ demand = 2, routedDemand = demand, cause = 'classifier' } = {}) {
16
+ if (!Number.isInteger(demand) || !validLevel(demand) || !validLevel(routedDemand))
17
+ throw new RangeError('demand must be an integer 0..3; routedDemand must be a half-step 0..3');
18
+ return {
19
+ demand,
20
+ routedDemand,
21
+ routeCause: cause,
22
+ demandCause: 'classifier',
23
+ turn: 0,
24
+ votes: [],
25
+ holdUntilTurn: 0,
26
+ escalatedSignature: null,
27
+ escalatedIndex: null,
28
+ headroom: false,
29
+ };
30
+ }
31
+
32
+ const massAbove = (p, level) => TIERS.reduce((sum, tier, i) => sum + (i > level ? (p?.[tier] ?? 0) : 0), 0);
33
+ const massAtOrBelow = (p, level) => TIERS.reduce((sum, tier, i) => sum + (i <= level ? (p?.[tier] ?? 0) : 0), 0);
34
+ function trailing(votes, predicate) {
35
+ let count = 0;
36
+ for (let i = votes.length - 1; i >= 0 && predicate(votes[i]); i -= 1) count += 1;
37
+ return count;
38
+ }
39
+
40
+ // Only vote/hold policy fields are read here: no route, cache, price, checkpoint or dwell evidence.
41
+ // Raw demand is integer; the accepted bounded execute discount never accumulates or discounts a pin/escalation.
42
+ export function advanceDemand({ config, state, advice = null, facts, pin = null, boundedExecute = false }) {
43
+ const pinned = pin === null ? null : typeof pin === 'string' ? TIERS.indexOf(pin) : pin;
44
+ if (pinned !== null && (!Number.isInteger(pinned) || !validLevel(pinned)))
45
+ throw new RangeError('pin must name a tier or integer demand 0..3');
46
+ if (pinned !== null)
47
+ return { raw: pinned, level: pinned, reason: 'pinned', headroom: false, escalated: false, state };
48
+ const next = { ...state, turn: state.turn + 1, votes: [...state.votes] };
49
+ let reason = 'same-demand';
50
+ let escalated = false;
51
+ const failure = facts.failure;
52
+ const freshFailure =
53
+ failure && (failure.signature !== next.escalatedSignature || (failure.index ?? null) !== next.escalatedIndex);
54
+ if (freshFailure) {
55
+ next.escalatedSignature = failure.signature;
56
+ next.escalatedIndex = failure.index ?? null;
57
+ next.headroom = next.demand === 3;
58
+ next.demand = Math.min(3, next.demand + 1);
59
+ next.demandCause = 'escalation';
60
+ next.holdUntilTurn = next.turn + config.policy.escalationHoldTurns;
61
+ next.votes = [];
62
+ reason = 'escalation';
63
+ escalated = true;
64
+ } else if (next.turn <= next.holdUntilTurn) {
65
+ reason = 'hold';
66
+ } else if (!advice || !TIERS.includes(advice.choice)) {
67
+ reason = advice ? 'uncertain' : 'no-advice';
68
+ } else {
69
+ const choice = TIERS.indexOf(advice.choice);
70
+ next.votes = [...next.votes, choice].slice(-Math.max(config.policy.upgradeVotes, config.policy.downgradeVotes));
71
+ const fresh = facts.historyMeasured === false;
72
+ if (choice > next.demand) {
73
+ const mass = massAbove(advice.probabilities, next.demand);
74
+ const jump = choice - next.demand >= 2 && mass >= config.policy.jumpConfidence;
75
+ const votes = fresh ? 1 : config.policy.upgradeVotes;
76
+ if (jump || (trailing(next.votes, (v) => v > next.demand) >= votes && mass >= config.policy.upgradeBase)) {
77
+ next.demand = choice;
78
+ next.demandCause = 'classifier';
79
+ next.headroom = false;
80
+ reason = jump ? 'jump' : 'upgrade';
81
+ } else reason = 'upgrade-pending';
82
+ } else if (choice < next.demand) {
83
+ reason = 'downgrade-pending';
84
+ for (let target = choice; target < next.demand; target += 1) {
85
+ const votes = fresh ? 1 : config.policy.downgradeVotes;
86
+ if (
87
+ massAtOrBelow(advice.probabilities, target) < config.policy.downgradeMass ||
88
+ trailing(next.votes, (v) => v <= target) < votes
89
+ )
90
+ continue;
91
+ next.demand = target;
92
+ next.demandCause = 'classifier';
93
+ next.headroom = false;
94
+ reason = 'downgrade';
95
+ break;
96
+ }
97
+ }
98
+ }
99
+ const protectedDemand = escalated || next.turn <= next.holdUntilTurn || next.headroom;
100
+ const discount = boundedExecute && !protectedDemand ? 0.5 : 0;
101
+ return {
102
+ raw: next.demand,
103
+ level: clamp(next.demand - discount),
104
+ reason,
105
+ headroom: next.headroom,
106
+ escalated,
107
+ state: next,
108
+ };
109
+ }
110
+
111
+ function effectiveIncumbent(config, incumbent, facts) {
112
+ const model = config.models[incumbent.model];
113
+ if (!model) return incumbent;
114
+ // An unresolved native null effort is legal but unknown. Never silently clamp an unsupported explicit effort.
115
+ if (incumbent.effort == null && (model.efforts.includes(facts.effort) || Number.isFinite(facts.effort)))
116
+ return { ...incumbent, effort: facts.effort };
117
+ return { ...incumbent, effort: incumbent.effort ?? null };
118
+ }
119
+
120
+ // cost.routeEffort represents native numeric effort through sentEffort, not the configured effort slot.
121
+ const pricedRoute = (route) => (typeof route.effort === 'number' ? { ...route, effort: null } : route);
122
+ const pricedFacts = (route, facts) => (typeof route.effort === 'number' ? { ...facts, effort: route.effort } : facts);
123
+
124
+ function capabilityOf(model, route) {
125
+ const key = route.effort === null && model.efforts.length === 0 ? 'default' : route.effort;
126
+ const value = key === null ? undefined : model.capability?.[key];
127
+ return validLevel(value) ? value : null;
128
+ }
129
+
130
+ // Only the actual supported effort can establish accepted startup demand; unknown capability keeps the baseline.
131
+ export function initialIncumbentState({ config, incumbent, facts }) {
132
+ const demand = TIERS.indexOf(config.baselineTier);
133
+ const current = effectiveIncumbent(config, incumbent, facts);
134
+ const model = config.models[current.model];
135
+ const capability =
136
+ model && (current.effort === null || model.efforts.includes(current.effort)) ? capabilityOf(model, current) : null;
137
+ return initialAutoState({ demand, routedDemand: capability ?? demand });
138
+ }
139
+
140
+ // Each supported pair is assessed independently before any fallback. The incumbent is also assessed, even if its
141
+ // model/effort left the catalog; an unresolved native effort can only be retained, never nominated as a new candidate.
142
+ export function assessCandidates({
143
+ config,
144
+ facts,
145
+ now,
146
+ incumbent,
147
+ contextKnown = Number.isFinite(facts.contextTokens),
148
+ availableModels,
149
+ nativeModel,
150
+ }) {
151
+ const current = effectiveIncumbent(config, incumbent, facts);
152
+ const currentSpec = config.models[current.model];
153
+ const routes = Object.entries(config.models).flatMap(([model, spec]) =>
154
+ (spec.efforts.length ? spec.efforts : [null]).map((effort) => ({ model, effort })),
155
+ );
156
+ const listed = routes.some((route) => sameRoute(route, current));
157
+ if (!listed) routes.push(current);
158
+ const tokens = costs.nextContextTokens(facts);
159
+ return routes.map((route, index) => {
160
+ const model = config.models[route.model];
161
+ const reasons = [];
162
+ const isIncumbent = sameRoute(route, current);
163
+ const selectable = index < routes.length - (listed ? 0 : 1);
164
+ if (!model)
165
+ return {
166
+ route,
167
+ capability: null,
168
+ eligible: false,
169
+ reasons: ['model-missing'],
170
+ incumbent: isIncumbent,
171
+ selectable,
172
+ cache: 'unknown',
173
+ coldWriteUsd: null,
174
+ estimate: null,
175
+ };
176
+ if (
177
+ route.effort !== null &&
178
+ !model.efforts.includes(route.effort) &&
179
+ !(isIncumbent && Number.isFinite(route.effort))
180
+ )
181
+ reasons.push('effort-unsupported');
182
+ if (
183
+ !isModelAllowed(model.id, availableModels, nativeModel) ||
184
+ (facts.ineligible ?? []).some((id) => canonicalModel(id) === canonicalModel(model.id))
185
+ )
186
+ reasons.push('unavailable');
187
+ // A missing fresh estimate does not erase the observed transcript's token lower bound.
188
+ if (tokens > model.contextWindow * CONTEXT_FILL) reasons.push('context-full');
189
+ if (
190
+ (!contextKnown || facts.historyMeasured === false) &&
191
+ currentSpec &&
192
+ model.contextWindow < currentSpec.contextWindow
193
+ )
194
+ reasons.push('context-unknown');
195
+ if (facts.hasImages && model.imageInput === false) reasons.push('images');
196
+ const pricingFacts = pricedFacts(route, facts);
197
+ const pricingRoute = pricedRoute(route);
198
+ const cache = costs.cacheState(
199
+ facts.models[costs.routeCacheKey(config, pricingRoute, pricingFacts.effort)],
200
+ now,
201
+ config.cache,
202
+ );
203
+ const coldWriteUsd = costs.coldWriteUsd(config, route.model, tokens, now);
204
+ if (model.billing === 'credits' && cache !== 'fresh' && coldWriteUsd > config.policy.cashCapUsd)
205
+ reasons.push('cash-cap');
206
+ const input = costs.inputBounds(config, pricingRoute, tokens, pricingFacts, now);
207
+ const output = ((costs.ratesAt(model, tokens, now).output ?? 0) * (facts.lastRequest?.outputTokens ?? 0)) / 1e6;
208
+ return {
209
+ route,
210
+ requestKey: JSON.stringify([canonicalModel(model.id), model.efforts.length ? route.effort : null]),
211
+ capability: capabilityOf(model, route),
212
+ eligible: reasons.length === 0,
213
+ reasons,
214
+ incumbent: isIncumbent,
215
+ selectable,
216
+ cache,
217
+ coldWriteUsd,
218
+ estimate: { minUsd: input.min + output, maxUsd: input.max + output },
219
+ };
220
+ });
221
+ }
222
+
223
+ // Uniform ordering is essential: mode changes only the required capability, never the incumbent tie preference.
224
+ export function selectTarget({ candidates, demand, mode = 'balanced', headroom = false, escalation = false }) {
225
+ if (!validLevel(demand)) throw new RangeError('demand must be a half-step 0..3');
226
+ if (!Object.hasOwn(MODES, mode)) throw new RangeError('unknown automatic routing mode');
227
+ const requirement = clamp(demand + MODES[mode]);
228
+ const eligible = candidates.filter(
229
+ (candidate) => candidate.eligible && (candidate.selectable || candidate.incumbent),
230
+ );
231
+ const current = candidates.find((candidate) => candidate.incumbent);
232
+ const escalating = (escalation || headroom) && current?.eligible;
233
+ const choices = escalating ? eligible.filter((candidate) => !samePhysical(candidate, current)) : eligible;
234
+ const declared = choices.filter(
235
+ (candidate) =>
236
+ candidate.capability !== null &&
237
+ (!escalating ||
238
+ (current.capability === null
239
+ ? candidate.capability >= requirement
240
+ : candidate.capability > current.capability)),
241
+ );
242
+ let pool = declared.filter((candidate) => candidate.capability >= requirement);
243
+ let outcome = 'meets-demand';
244
+ let reason = escalating ? 'escalation' : null;
245
+ if (!pool.length) {
246
+ if (declared.length) {
247
+ const highest = Math.max(...declared.map((candidate) => candidate.capability));
248
+ pool = declared.filter((candidate) => candidate.capability === highest);
249
+ outcome = highest >= requirement ? 'meets-demand' : 'declared-below-demand';
250
+ } else {
251
+ pool = choices.filter((candidate) => candidate.capability === null);
252
+ outcome = 'unknown-only';
253
+ if (escalating) reason = pool.length ? 'escalation-unknown' : 'escalation-exhausted';
254
+ }
255
+ }
256
+ pool = [...pool].sort(
257
+ (a, b) =>
258
+ a.estimate.maxUsd - b.estimate.maxUsd ||
259
+ Number(b.incumbent) - Number(a.incumbent) ||
260
+ (a.capability ?? -1) - (b.capability ?? -1),
261
+ );
262
+ const winner = pool[0] ?? (current?.eligible ? current : null);
263
+ if (!winner)
264
+ return {
265
+ outcome: 'no-route',
266
+ route: null,
267
+ capability: null,
268
+ requirement,
269
+ estimate: null,
270
+ reason: null,
271
+ headroom: false,
272
+ };
273
+ if (!pool.length) outcome = 'incumbent';
274
+ return {
275
+ outcome,
276
+ route: winner.route,
277
+ capability: winner.capability,
278
+ requirement,
279
+ estimate: winner.estimate,
280
+ reason,
281
+ headroom: reason === 'escalation-exhausted',
282
+ };
283
+ }
284
+
285
+ function bar(base, slope, tax, pivot) {
286
+ return base + slope * (tax / (tax + pivot));
287
+ }
288
+
289
+ // Demand votes are NOT read here. Pending moves compare against the demand accepted by the incumbent.
290
+ export function decideMove({
291
+ config,
292
+ state,
293
+ demandResult,
294
+ target,
295
+ candidates,
296
+ advice = null,
297
+ facts,
298
+ now,
299
+ changeCause = null,
300
+ startup = false,
301
+ incumbentOrigin = null,
302
+ }) {
303
+ const current = candidates.find((candidate) => candidate.incumbent);
304
+ const proposed = candidates.find((candidate) => sameRoute(candidate.route, target.route));
305
+ const stay = (reason, evidence = null) => ({
306
+ move: false,
307
+ route: current?.eligible ? current.route : null,
308
+ reason,
309
+ evidence,
310
+ estimate: target.estimate,
311
+ // The selected physical request can accept new demand without a switch or new route provenance.
312
+ state: reason === 'same-route' ? { ...state, routedDemand: demandResult.level } : state,
313
+ });
314
+ const move = (reason, cause, evidence = null) => ({
315
+ move: true,
316
+ route: target.route,
317
+ reason,
318
+ evidence,
319
+ estimate: target.estimate,
320
+ state: { ...state, routedDemand: demandResult.level, routeCause: cause },
321
+ });
322
+ if (!target.route || !proposed?.eligible) return stay('no-route');
323
+ if (incumbentOrigin === 'external-fallback')
324
+ return current && samePhysical(current, proposed) ? stay('same-route') : move('reentry', 'reentry');
325
+ if (!current?.eligible) return move('forced', 'forced');
326
+ if (target.reason === 'escalation-exhausted') return stay('escalation-exhausted');
327
+ if (samePhysical(current, proposed)) return stay('same-route');
328
+ if (
329
+ demandResult.escalated ||
330
+ demandResult.headroom ||
331
+ target.reason === 'escalation' ||
332
+ target.reason === 'escalation-unknown'
333
+ )
334
+ return move(target.reason === 'escalation-unknown' ? 'escalation-unknown' : 'escalation', 'escalation');
335
+ const p = config.policy;
336
+ const from = pricedRoute(current.route);
337
+ const to = pricedRoute(target.route);
338
+ const pricingFacts = pricedFacts(current.route, facts);
339
+ const stronger =
340
+ target.capability !== null && (current.capability === null || target.capability > current.capability);
341
+ const upgrade = (mass, reason, cause) => {
342
+ const taxUsd = Math.max(0, costs.switchingTaxUsd(config, to, from, pricingFacts, now));
343
+ const threshold = bar(p.upgradeBase, p.upgradeSlope, taxUsd, p.upgradePivotUsd);
344
+ const evidence = { mass, threshold, taxUsd };
345
+ return mass >= threshold ? move(reason, cause, evidence) : stay('upgrade-pending', evidence);
346
+ };
347
+ // Startup fits a native route the user never selected, before classifier move evidence; demand votes are unchanged.
348
+ if (
349
+ startup &&
350
+ current.capability !== null &&
351
+ current.capability < target.requirement &&
352
+ target.capability !== null &&
353
+ target.capability >= target.requirement
354
+ )
355
+ return upgrade(1, 'startup', 'startup');
356
+ if (demandResult.level > state.routedDemand)
357
+ return upgrade(massAbove(advice?.probabilities, state.routedDemand), 'upgrade', 'classifier');
358
+ if (demandResult.level < state.routedDemand) {
359
+ const taxUsd = costs.downgradeTaxUsd(config, to, from, pricingFacts, now, p.downgradeHorizonTurns);
360
+ const threshold = bar(p.downgradeMass, p.downgradeSlope, taxUsd, p.downgradePivotUsd);
361
+ const mass = massAtOrBelow(advice?.probabilities, demandResult.level);
362
+ const evidence = { mass, threshold, taxUsd };
363
+ if (mass < threshold) return stay('downgrade-pending', evidence);
364
+ if (!facts.dwellAllowed) return stay('dwell-held', evidence);
365
+ if (sameTaskOf(config, advice, facts) && !facts.downAllowed) return stay('downgrade-held', evidence);
366
+ return move('downgrade', 'classifier', evidence);
367
+ }
368
+ if (stronger || (target.capability === null && current.capability !== null)) {
369
+ if (!['mode', 'catalog'].includes(changeCause)) return stay('no-evidence');
370
+ return upgrade(1, 'explicit-up', changeCause);
371
+ }
372
+ if (target.estimate.maxUsd < current.estimate.maxUsd) {
373
+ if (state.turn <= state.holdUntilTurn) return stay('hold');
374
+ const taxUsd = costs.downgradeTaxUsd(config, to, from, pricingFacts, now, p.downgradeHorizonTurns);
375
+ const evidence = { taxUsd };
376
+ if (!facts.dwellAllowed) return stay('dwell-held', evidence);
377
+ if (sameTaskOf(config, advice, facts) && !facts.downAllowed) return stay('downgrade-held', evidence);
378
+ if (taxUsd > 0 && facts.historyMeasured !== false) return stay('economics-pending', evidence);
379
+ return move('cheaper', changeCause ?? 'classifier', evidence);
380
+ }
381
+ return stay('no-evidence');
382
+ }
383
+
384
+ // Shadow uses demand/filter/target helpers only and retains demand.state (not proposal route history). Stateful
385
+ // replay/auto consumes accepted same-route demand too, without counting a move. Pins are one-turn overrides;
386
+ // the caller restores both pre-pin incumbent and state afterwards. This function never performs a physical move.
387
+ export function proposeAutoRoute(input) {
388
+ const state = input.state ?? initialIncumbentState(input);
389
+ const demand = advanceDemand({ ...input, state });
390
+ const candidates = assessCandidates(input);
391
+ const pinned = input.pin != null;
392
+ const target = selectTarget({
393
+ candidates,
394
+ demand: demand.level,
395
+ mode: pinned ? 'balanced' : input.mode,
396
+ headroom: demand.headroom,
397
+ escalation: demand.escalated,
398
+ });
399
+ if (!pinned && (demand.escalated || demand.headroom)) {
400
+ demand.headroom = target.headroom;
401
+ demand.state = { ...demand.state, headroom: target.headroom };
402
+ }
403
+ const move = pinned
404
+ ? { move: false, route: target.route, reason: 'pinned', evidence: null, estimate: target.estimate, state }
405
+ : decideMove({ ...input, state: demand.state, demandResult: demand, target, candidates });
406
+ return { state: move.state, demand, candidates, target, move };
407
+ }
@@ -0,0 +1,247 @@
1
+ // Stateful main-turn adapter. Table/shadow never enter this path.
2
+ import { acceptActivity, acceptPhase, routingActivity } from './activity.mjs';
3
+ import { assessCandidates, decideMove, initialIncumbentState, proposeAutoRoute, selectTarget } from './auto-engine.mjs';
4
+ import { TIERS } from './config.mjs';
5
+ import { economicConfig, hasRoutedDecision, isModelAllowed, isSameModel } from './route.mjs';
6
+
7
+ const aliasRoute = (config, model, effort) => ({
8
+ model:
9
+ Object.keys(config.models).find(
10
+ (key) => isSameModel(config.models[key].id, model) || isSameModel(model, config.models[key].id),
11
+ ) ?? model,
12
+ effort: effort ?? null,
13
+ });
14
+ // An external response owns physical incumbent identity, but never changes demand evidence.
15
+ // A substituted response does not report the actual effort; null is unknown, not an inferred preset.
16
+ export function externalIncumbent(config, { requestedModel, effort, usage }) {
17
+ const served = usage?.model ?? requestedModel;
18
+ const actualEffort = isSameModel(requestedModel, served) ? (effort ?? null) : null;
19
+ return {
20
+ incumbent: aliasRoute(config, served, actualEffort),
21
+ incumbentId: served,
22
+ incumbentOrigin: 'external-fallback',
23
+ };
24
+ }
25
+
26
+ export function observeAutoFallback(config, loop, response) {
27
+ if (!loop.auto) return loop;
28
+ const external = externalIncumbent(config, response);
29
+ return {
30
+ ...loop,
31
+ auto: loop.auto.savedPin
32
+ ? { ...loop.auto, fallback: { ...external, switchedAt: loop.switchedAt, servedRoute: loop.servedRoute } }
33
+ : { ...loop.auto, ...external },
34
+ };
35
+ }
36
+
37
+ // Availability is operator catalog evidence; cache warmth, failures and the clock are not.
38
+ // Fingerprint allowed aliases, not raw allowlist order or routine response-ID resolutions.
39
+ export function autoCatalogKey(config, { availableModels, nativeModel, models = config.models }) {
40
+ const allowed = Object.keys(models).filter((alias) => isModelAllowed(models[alias].id, availableModels, nativeModel));
41
+ return JSON.stringify([config.models, config.policy, config.cache, config.activityRouting, allowed]);
42
+ }
43
+ const level = (n) => Number.isFinite(n) && n >= 0 && n <= 3 && Number.isInteger(n * 2);
44
+
45
+ const validSwitch = (value) =>
46
+ value === null ||
47
+ (Number.isSafeInteger(value?.requests) &&
48
+ value.requests >= 0 &&
49
+ Number.isSafeInteger(value.messageCount) &&
50
+ value.messageCount >= 0);
51
+ const validServed = (value) => value === null || typeof value === 'string';
52
+ const validPin = (value) =>
53
+ value == null || (TIERS.includes(value.pin) && validSwitch(value.switchedAt) && validServed(value.servedRoute));
54
+ const validFallback = (value) =>
55
+ value == null ||
56
+ (typeof value.incumbent?.model === 'string' &&
57
+ typeof value.incumbentId === 'string' &&
58
+ value.incumbentOrigin === 'external-fallback' &&
59
+ validSwitch(value.switchedAt) &&
60
+ validServed(value.servedRoute));
61
+
62
+ function validAuto(saved) {
63
+ const s = saved?.state;
64
+ return (
65
+ saved?.version === 1 &&
66
+ level(s?.demand) &&
67
+ Number.isInteger(s.demand) &&
68
+ level(s.routedDemand) &&
69
+ Number.isSafeInteger(s.turn) &&
70
+ s.turn >= 0 &&
71
+ Number.isSafeInteger(s.holdUntilTurn) &&
72
+ Array.isArray(s.votes) &&
73
+ s.votes.every((n) => level(n) && Number.isInteger(n)) &&
74
+ typeof saved.incumbent?.model === 'string' &&
75
+ typeof saved.incumbentId === 'string' &&
76
+ validPin(saved.savedPin) &&
77
+ validFallback(saved.fallback)
78
+ );
79
+ }
80
+
81
+ function stateFor(projected, loop, input, mode, catalog) {
82
+ const valid = validAuto(loop.auto);
83
+ if (valid && loop.auto.generation === loop.generation) return { ...loop.auto };
84
+ // A history reset preserves a running pin's underlying incumbent, not its temporary request.
85
+ const restore = valid && loop.auto.savedPin;
86
+ const model = loop.decision?.model ?? input.engineModel ?? input.nativeModel;
87
+ const incumbent = restore
88
+ ? loop.auto.incumbent
89
+ : aliasRoute(projected, model, loop.decision?.effort ?? input.facts.effort);
90
+ return {
91
+ version: 1,
92
+ generation: loop.generation,
93
+ state: initialIncumbentState({ config: projected, incumbent, facts: input.facts }),
94
+ incumbent,
95
+ incumbentId: restore ? loop.auto.incumbentId : model,
96
+ advice: null,
97
+ boundedExecute: false,
98
+ activity: null,
99
+ demandResult: null,
100
+ savedPin: restore ? loop.auto.savedPin : null,
101
+ fallback: restore ? loop.auto.fallback : null,
102
+ mode,
103
+ catalog,
104
+ };
105
+ }
106
+
107
+ function continueProposal(args, auto) {
108
+ const { state } = auto;
109
+ const discount = auto.boundedExecute && !state.headroom && state.turn > state.holdUntilTurn ? 0.5 : 0;
110
+ const demand = {
111
+ ...auto.demandResult,
112
+ level: Math.max(0, state.demand - discount),
113
+ state,
114
+ escalated: false,
115
+ headroom: state.headroom,
116
+ };
117
+ const candidates = assessCandidates(args);
118
+ const target = selectTarget({ candidates, demand: demand.level, mode: args.mode, headroom: state.headroom });
119
+ const next = state.headroom ? { ...state, headroom: target.headroom } : state;
120
+ const move = decideMove({ ...args, state: next, demandResult: demand, candidates, target });
121
+ return { demand, target, move, state: move.state };
122
+ }
123
+
124
+ function decisionFor(config, auto, input, proposal, pin) {
125
+ const { demand, target, move } = proposal;
126
+ const route = move.route;
127
+ const model = route ? (config.models[route.model]?.id ?? route.model) : (input.engineModel ?? input.nativeModel);
128
+ // Candidate effort is already native: do not clamp numeric effort or invent a declaration for null.
129
+ const effort = route
130
+ ? (route.effort ?? (config.models[route.model]?.efforts.length ? (input.facts.effort ?? null) : null))
131
+ : (input.facts.effort ?? null);
132
+ const reason = route ? move.reason : 'no-route-native';
133
+ return {
134
+ tier: TIERS[demand.raw ?? auto.state.demand],
135
+ route,
136
+ model,
137
+ effort,
138
+ reason,
139
+ pinned: Boolean(pin),
140
+ requestedPin: pin ?? null,
141
+ escalated: !pin && (demand.escalated || (move.move && ['escalation', 'escalation-unknown'].includes(move.reason))),
142
+ activity: pin ? null : auto.activity,
143
+ goal: pin ? null : acceptActivity(config, auto.advice),
144
+ taskPhase: pin ? null : acceptPhase(config, auto.advice),
145
+ comparison: null,
146
+ estimate: null,
147
+ auto: {
148
+ demand: demand.level,
149
+ reason: demand.reason,
150
+ headroom: target.headroom,
151
+ targetReason: target.reason,
152
+ requirement: target.requirement,
153
+ outcome: target.outcome,
154
+ route: target.route ? `${target.route.model}@${target.route.effort ?? 'session'}` : null,
155
+ capability: target.capability,
156
+ minUsd: target.estimate?.minUsd,
157
+ maxUsd: target.estimate?.maxUsd,
158
+ move: reason,
159
+ },
160
+ };
161
+ }
162
+
163
+ // Only versioned state is authoritative; resets never restore old demand votes or pending moves.
164
+ // Cache and resolution observations belong to the shared physical loop, not the engine state.
165
+ export function autoRoute(config, previous, input, { continuation = false, observed = null } = {}) {
166
+ const { facts, now, nativeModel, availableModels, contextKnown } = input;
167
+ const mode = config.routingMode?.mode ?? config.mode ?? 'balanced';
168
+ const projected = economicConfig(config, previous);
169
+ const catalog = autoCatalogKey(config, { availableModels, nativeModel, models: projected.models });
170
+ const auto = stateFor(projected, previous, input, mode, catalog);
171
+ let loop = previous;
172
+ if (!continuation && loop.turnId !== facts.turnKey && auto.savedPin) {
173
+ loop = { ...loop, switchedAt: auto.savedPin.switchedAt, servedRoute: auto.savedPin.servedRoute };
174
+ auto.savedPin = null;
175
+ if (auto.fallback) {
176
+ const { switchedAt, servedRoute, ...external } = auto.fallback;
177
+ loop = { ...loop, switchedAt, servedRoute };
178
+ Object.assign(auto, external);
179
+ auto.fallback = null;
180
+ }
181
+ }
182
+ // An alias edit must not silently replace the incumbent with the alias's newly assigned model.
183
+ const id = projected.models[auto.incumbent.model]?.id;
184
+ if (!isSameModel(id, auto.incumbentId) && !isSameModel(auto.incumbentId, id))
185
+ auto.incumbent = aliasRoute(projected, auto.incumbentId, auto.incumbent.effort);
186
+ const changeCause = mode !== auto.mode ? 'mode' : catalog !== auto.catalog ? 'catalog' : (auto.changeCause ?? null);
187
+ const pin = continuation ? (auto.savedPin?.pin ?? null) : input.pin;
188
+ if (!pin && !continuation) {
189
+ auto.advice = input.advice;
190
+ const accepted = config.activityRouting === 'on' ? acceptActivity(config, input.advice) : null;
191
+ const signal = routingActivity(config, input.advice);
192
+ if (accepted) auto.activity = signal?.mass >= config.policy.activityMass ? signal.choice : accepted;
193
+ auto.boundedExecute = accepted !== null && acceptPhase(config, input.advice) === 'execute';
194
+ }
195
+ if (!pin && ['code', 'docs', 'ops'].includes(observed)) auto.activity = observed;
196
+ if (!pin && ['code', 'docs'].includes(observed)) auto.boundedExecute = false;
197
+ const args = {
198
+ config: projected,
199
+ facts: {
200
+ ...facts,
201
+ ...(auto.incumbentOrigin === 'external-fallback' && auto.incumbent.effort === null ? { effort: null } : {}),
202
+ ineligible: loop.ineligible.map((model) => loop.resolutions[model] ?? model),
203
+ dwellAllowed: !loop.switchedAt || loop.requests - loop.switchedAt.requests >= config.policy.minDwellRequests,
204
+ },
205
+ now,
206
+ nativeModel,
207
+ availableModels,
208
+ contextKnown,
209
+ incumbent: continuation && pin ? aliasRoute(projected, loop.decision.model, loop.decision.effort) : auto.incumbent,
210
+ state: auto.state,
211
+ advice: auto.advice,
212
+ mode,
213
+ changeCause,
214
+ startup: !hasRoutedDecision(previous),
215
+ pin,
216
+ boundedExecute: auto.boundedExecute,
217
+ incumbentOrigin: !continuation && !facts.midTurn ? auto.incumbentOrigin : null,
218
+ };
219
+ const proposal = !continuation || pin ? proposeAutoRoute(args) : continueProposal(args, auto);
220
+ const { demand, move } = proposal;
221
+ if (pin) auto.savedPin ??= { pin, switchedAt: loop.switchedAt, servedRoute: loop.servedRoute };
222
+ else {
223
+ auto.state = proposal.state;
224
+ auto.demandResult = demand;
225
+ if (['reentry', 'same-route'].includes(move.reason) && args.incumbentOrigin) auto.incumbentOrigin = null;
226
+ if (move.route) {
227
+ auto.incumbent = move.route;
228
+ auto.incumbentId = projected.models[move.route.model]?.id ?? move.route.model;
229
+ }
230
+ auto.mode = mode;
231
+ auto.catalog = catalog;
232
+ auto.changeCause =
233
+ !move.move && move.reason !== 'same-route' && demand.level === auto.state.routedDemand ? changeCause : null;
234
+ }
235
+ return {
236
+ ...loop,
237
+ hasRoutedDecision: true,
238
+ auto,
239
+ turnId: facts.turnKey,
240
+ suspended: false,
241
+ route: auto.incumbent,
242
+ lastRoute: pin ? loop.lastRoute : TIERS[auto.state.demand],
243
+ lastActivity: pin ? loop.lastActivity : auto.activity,
244
+ reviewedAt: continuation ? loop.reviewedAt : loop.requests,
245
+ decision: decisionFor(config, auto, input, proposal, pin),
246
+ };
247
+ }