@alexeiled/claude-router 1.22.0 → 1.23.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.
@@ -1,9 +1,11 @@
1
1
  import {
2
+ ACTIVITY_CONTRACT,
2
3
  advanceDown,
3
4
  advanceRun,
4
5
  emptyMetrics,
5
6
  emptySession,
6
7
  emptyStore,
8
+ LEGACY_STORE_PREFIX,
7
9
  METRICS_PREFIX,
8
10
  mergeMetrics,
9
11
  mergeStores,
@@ -47,6 +49,7 @@ import { changedLeaves, notSaved, restored, rewrittenConfig } from '../lib/confi
47
49
  import {
48
50
  addTurnRow,
49
51
  appendDecisions,
52
+ continuedGoal,
50
53
  DECISIONS_PREFIX,
51
54
  decisionLines,
52
55
  decisionRow,
@@ -75,7 +78,16 @@ import {
75
78
  unavailableReason,
76
79
  unpricedLine,
77
80
  } from '../lib/display.mjs';
78
- import { clip, hasImages, observedActivity, promptIndex, routingBucket } from '../lib/facts.mjs';
81
+ import {
82
+ clip,
83
+ currentStepText,
84
+ hasImages,
85
+ historySignature,
86
+ observedActivity,
87
+ promptIndex,
88
+ routingBucket,
89
+ stripReminders,
90
+ } from '../lib/facts.mjs';
79
91
  import { applyMode, modeLabel, readProjectMode, resolveRoutingMode } from '../lib/modes.mjs';
80
92
  import { renderPanel, routeDraftOf, routingChanges } from '../lib/panel.mjs';
81
93
  import { sameTaskOf } from '../lib/policy.mjs';
@@ -239,6 +251,9 @@ function createRouter(options) {
239
251
  // The session's active goal, the last prompt from a goal origin, clipped, `{ sessionId, text }`, in memory only;
240
252
  // and each progress turn's report (`progressNotes`), which the classifier reads as dialogue (progressInput).
241
253
  goal: null,
254
+ goalTurnId: null,
255
+ goalEpoch: 0,
256
+ turnGoals: new Map(),
242
257
  progressNotes: new Map(),
243
258
  // Each turn's decision rows until turn.complete writes them, with the turn's end, to the session's record, held as
244
259
  // `{ sessionId, record }` once read (`decisionRecord`).
@@ -728,8 +743,11 @@ function detailText(config, view, usage) {
728
743
  ...(view.routingMode ? [`Mode: ${modeLabel(view.routingMode)}`] : []),
729
744
  ...(view.projectError ? [`Ignored: ${view.projectError}`] : []),
730
745
  `Native model: ${view.nativeModel}`,
731
- `Selected: ${view.selectedModel ?? 'not selected'}`,
732
- `Observed: ${view.actualModel ?? 'no response yet'}`,
746
+ `Selected: ${view.selectedModel ?? 'not selected'} · effort ${view.effort ?? 'session/default'}`,
747
+ `Last recorded completed engine request: ${view.delegatedModel ?? 'none'} · effort ${view.delegatedEffort ?? 'session/default'}`,
748
+ `Response-reported model: ${view.actualModel ?? 'no response yet'}`,
749
+ 'API-transmitted and served effort: unknown (engine delegation is not wire evidence).',
750
+ 'Cost basis: configured API-rate estimates (list/custom), not bills or measured quota savings.',
733
751
  `Reason: ${view.reason}`,
734
752
  ...activityDetailLines(config, view),
735
753
  storeAgreementLine(view),
@@ -788,7 +806,12 @@ async function* passMain($, e, next, loop, version, nativeModel, reason, router)
788
806
  const compared = await compareYours($, router, loop, response, e.effort ?? null, nativeModel);
789
807
  if (compared) observed.yoursBy = compared.states;
790
808
  const written = await $.state.set(ref, observed, { ifVersion: version });
791
- if (written.isSet) await updateView($, router, responseMetrics(router.view, response, null, Date.now()));
809
+ if (written.isSet)
810
+ await updateView($, router, {
811
+ ...responseMetrics(router.view, response, null, Date.now()),
812
+ delegatedModel: e.model,
813
+ delegatedEffort: e.effort ?? null,
814
+ });
792
815
  }
793
816
  return response;
794
817
  }
@@ -816,6 +839,7 @@ async function decideTurn($, router, e, signal, step) {
816
839
  $.session.messages({ as: 'api' }),
817
840
  ]);
818
841
  if (!(await live())) return null;
842
+ validateGoal(router, e.turnId, messages);
819
843
  const origin = router.turnOrigins.get(e.turnId) ?? 'unknown';
820
844
  // A progress turn is the same task (sameTaskOf).
821
845
  const facts = {
@@ -825,6 +849,7 @@ async function decideTurn($, router, e, signal, step) {
825
849
  effort: e.effort,
826
850
  turnId: e.turnId,
827
851
  contextTokens: context.tokens,
852
+ progress: isProgressOrigin(origin),
828
853
  }),
829
854
  progress: isProgressOrigin(origin),
830
855
  };
@@ -850,6 +875,8 @@ async function decideTurn($, router, e, signal, step) {
850
875
  endpoint: credentials.endpoint,
851
876
  prompt: asked.prompt,
852
877
  turns: asked.turns,
878
+ activeGoal: router.turnGoals.get(e.turnId)?.goal,
879
+ currentStep: router.progressNotes.get(e.turnId) ?? facts.prompt,
853
880
  signal: controller.signal,
854
881
  });
855
882
  // The wait for advice alone, comparable with the activity probe's p95; the routing after it is not the classifier's.
@@ -874,6 +901,7 @@ async function decideTurn($, router, e, signal, step) {
874
901
  if (written.isSet && pin) router.turnPins.set(e.turnId, pinPresses);
875
902
  // Manual, /clear and turn completion abort the controller; one may land during the write.
876
903
  if (!written.isSet || controller.signal.aborted) return null;
904
+ rememberGoal(router, e.turnId, result.advice, cfg.policy.continuationMass, messages);
877
905
  if (previous?.model && previous.model !== selected.decision.model && !selected.decision.pinned)
878
906
  $.ui.toast(switchToast(cfg, previous, selected.decision, selected.decision.estimate));
879
907
  const activity = turnActivity(cfg, result.advice, previous, selected.decision);
@@ -939,6 +967,10 @@ async function decideTurn($, router, e, signal, step) {
939
967
  effort: selected.decision.effort,
940
968
  reason: selected.decision.reason,
941
969
  activity: activity.label,
970
+ goal: selected.decision.goal,
971
+ taskPhase: selected.decision.taskPhase,
972
+ phaseChoice: result.advice?.phase?.choice ?? null,
973
+ phaseProbabilities: result.advice?.phase?.probabilities ?? null,
942
974
  contextTokens: context.tokens,
943
975
  contextKnown: context.known,
944
976
  comparison: selected.decision.comparison,
@@ -973,6 +1005,7 @@ function stepFacts(cfg, router, loop, e, messages, context) {
973
1005
  effort: e.effort,
974
1006
  turnId: e.turnId,
975
1007
  contextTokens: context.tokens,
1008
+ progress: isProgressOrigin(router.turnOrigins.get(e.turnId)),
976
1009
  });
977
1010
  }
978
1011
 
@@ -1037,8 +1070,10 @@ async function reviewMidTurn($, router, cfg, loop, e, { context, nativeModel, av
1037
1070
  if (!review.answer.advice || loop.decision?.pinned || review.generation !== loop.generation) return loop;
1038
1071
  // Only the advice is from the review; the checkpoint, context and cache facts are read now.
1039
1072
  const messages = await transcript($);
1040
- if (!messages) return loop;
1041
- const advice = review.answer.advice;
1073
+ if (!messages || historySignature(messages, review.observedUpTo) !== review.prefix) return loop;
1074
+ // Appends preserve the task evidence, but a command-only phase cannot authorize work after its snapshot.
1075
+ const advice =
1076
+ messages.length === review.observedUpTo ? review.answer.advice : { ...review.answer.advice, phase: null };
1042
1077
  const facts = { ...stepFacts(cfg, router, loop, e, messages, context), midTurn: true };
1043
1078
  const selected = chooseRoute(cfg, loop, {
1044
1079
  facts,
@@ -1083,6 +1118,10 @@ async function reviewMidTurn($, router, cfg, loop, e, { context, nativeModel, av
1083
1118
  estimate: selected.decision.estimate ?? null,
1084
1119
  activityChoice: advice.activity?.choice ?? null,
1085
1120
  activityProbabilities: advice.activity?.probabilities ?? null,
1121
+ goal: selected.decision.goal,
1122
+ taskPhase: selected.decision.taskPhase,
1123
+ phaseChoice: advice.phase?.choice ?? null,
1124
+ phaseProbabilities: advice.phase?.probabilities ?? null,
1086
1125
  });
1087
1126
  // Tool calls up to the review's snapshot were judged by it; later ones can still move the route up.
1088
1127
  return { ...selected, observedFrom: review.observedUpTo };
@@ -1090,7 +1129,13 @@ async function reviewMidTurn($, router, cfg, loop, e, { context, nativeModel, av
1090
1129
  const every = cfg.policy.reviewEveryRequests;
1091
1130
  if (review || every === 0 || !loop.decision?.tier || loop.decision.pinned) return loop;
1092
1131
  if ((loop.requests ?? 0) - (loop.reviewedAt ?? 0) < every) return loop;
1093
- const job = { controller: new AbortController(), generation: loop.generation, observedUpTo: 0, answer: null };
1132
+ const job = {
1133
+ controller: new AbortController(),
1134
+ generation: loop.generation,
1135
+ observedUpTo: 0,
1136
+ prefix: null,
1137
+ answer: null,
1138
+ };
1094
1139
  router.reviews.set(e.turnId, job);
1095
1140
  try {
1096
1141
  const [credentials, messages] = await Promise.all([
@@ -1098,6 +1143,7 @@ async function reviewMidTurn($, router, cfg, loop, e, { context, nativeModel, av
1098
1143
  $.session.messages({ as: 'api' }),
1099
1144
  ]);
1100
1145
  job.observedUpTo = messages.length;
1146
+ job.prefix = historySignature(messages);
1101
1147
  const facts = stepFacts(cfg, router, loop, e, messages, context);
1102
1148
  clientOf(router, cfg.classifier)
1103
1149
  .ask({
@@ -1108,6 +1154,8 @@ async function reviewMidTurn($, router, cfg, loop, e, { context, nativeModel, av
1108
1154
  endpoint: credentials.endpoint,
1109
1155
  prompt: facts.prompt,
1110
1156
  turns: facts.turns,
1157
+ activeGoal: router.turnGoals.get(e.turnId)?.goal,
1158
+ currentStep: currentStepText(messages, facts.prompt, cfg.context.maxTextChars),
1111
1159
  signal: job.controller.signal,
1112
1160
  })
1113
1161
  .then((answer) => {
@@ -1124,10 +1172,14 @@ async function reviewMidTurn($, router, cfg, loop, e, { context, nativeModel, av
1124
1172
  }
1125
1173
 
1126
1174
  // A routed reply's metrics in the view, with the tier that served it, and added to the turn's activity record with its list price (`routedUsd`, null when unpriced) and, when its tier served it, its route.
1127
- async function publishReply($, router, turnId, response, tier, route, routedUsd, cause = null) {
1175
+ async function publishReply($, router, turnId, request, response, tier, route, routedUsd, cause = null) {
1128
1176
  const turn = router.turnActivities.get(turnId);
1129
1177
  const metrics = responseMetrics(router.view, response, tier, Date.now());
1130
- await updateView($, router, metrics);
1178
+ await updateView($, router, {
1179
+ ...metrics,
1180
+ delegatedModel: request.model,
1181
+ delegatedEffort: request.effort ?? null,
1182
+ });
1131
1183
  if (turn)
1132
1184
  router.turnActivities.set(turnId, {
1133
1185
  ...turn,
@@ -1177,7 +1229,7 @@ async function observeRouted($, router, { turnId, cfg, loop, loopVersion, reques
1177
1229
  yours: { model: nativeModel },
1178
1230
  ttl: compared.ttl,
1179
1231
  }) ?? 'error');
1180
- await publishReply($, router, turnId, response, tier, route, observedUsd, cause);
1232
+ await publishReply($, router, turnId, request, response, tier, route, observedUsd, cause);
1181
1233
  // Kept by model id, under the model that served it: a substitute's cost is not the requested model's, and a models
1182
1234
  // key can name another model later.
1183
1235
  const idOf = (model) => modelSpec(cfg, model)?.id ?? model;
@@ -1286,17 +1338,70 @@ async function flushUsage($, router, turnId, switched) {
1286
1338
  // its report as dialogue (progressInput); without a goal from this session it reads as before. A goal origin's prompt
1287
1339
  // becomes the goal.
1288
1340
  async function startTurn($, router, e) {
1289
- const text = clip(e.text, router.config.context.maxTextChars);
1341
+ const epoch = ++router.goalEpoch;
1342
+ router.goalTurnId = e.turnId;
1343
+ await fixTurnConfig($, router, e.turnId);
1344
+ const text = clip(stripReminders(e.text), router.config.context.maxTextChars);
1290
1345
  const origin = originOfTurn(router, e.text);
1291
1346
  router.turnOrigins.set(e.turnId, origin);
1292
1347
  const sessionId = await $.session.id();
1293
- if (isProgressOrigin(origin) && router.goal?.sessionId === sessionId) {
1348
+ if (router.goalEpoch !== epoch || router.goalTurnId !== e.turnId) return;
1349
+ const previous = router.goal?.sessionId === sessionId ? router.goal.text : null;
1350
+ const candidate = isGoalOrigin(origin) ? text : null;
1351
+ router.turnGoals.set(e.turnId, {
1352
+ sessionId,
1353
+ previous,
1354
+ previousRecord: previous ? router.goal : null,
1355
+ candidate,
1356
+ goal: previous,
1357
+ });
1358
+ if (isProgressOrigin(origin) && previous) {
1294
1359
  router.prompts.set(e.turnId, router.goal.text);
1295
1360
  router.progressNotes.set(e.turnId, text);
1296
1361
  return;
1297
1362
  }
1298
1363
  router.prompts.set(e.turnId, text);
1299
- if (isGoalOrigin(origin)) router.goal = { sessionId, text };
1364
+ }
1365
+
1366
+ function validateGoal(router, turnId, messages) {
1367
+ const pending = router.turnGoals.get(turnId);
1368
+ const record = pending?.previousRecord;
1369
+ if (!record || historySignature(messages, record.prefixCount) === record.prefix) return;
1370
+ if (router.goal === record) router.goal = null;
1371
+ const note = router.progressNotes.get(turnId);
1372
+ if (note) {
1373
+ router.prompts.set(turnId, note);
1374
+ router.progressNotes.delete(turnId);
1375
+ }
1376
+ router.turnGoals.set(turnId, { ...pending, previous: null, previousRecord: null, goal: null });
1377
+ }
1378
+
1379
+ function rememberGoal(router, turnId, advice, threshold, messages) {
1380
+ const pending = router.turnGoals.get(turnId);
1381
+ if (!pending?.candidate || router.goalTurnId !== turnId) return;
1382
+ const text = continuedGoal(pending.previous, pending.candidate, advice?.continuation, threshold);
1383
+ const retained = text && text === pending.previous && advice?.continuation > 0.5;
1384
+ router.goal = text
1385
+ ? retained
1386
+ ? pending.previousRecord
1387
+ : {
1388
+ sessionId: pending.sessionId,
1389
+ text,
1390
+ prefixCount: messages.length,
1391
+ prefix: historySignature(messages),
1392
+ }
1393
+ : null;
1394
+ router.turnGoals.set(turnId, { ...pending, goal: text });
1395
+ }
1396
+
1397
+ function clearGoal(router) {
1398
+ router.goal = null;
1399
+ router.goalTurnId = null;
1400
+ router.goalEpoch += 1;
1401
+ router.turnGoals.clear();
1402
+ // A notification must not keep a goal that a rewind/compaction invalidated.
1403
+ for (const [turnId, note] of router.progressNotes) router.prompts.set(turnId, note);
1404
+ router.progressNotes.clear();
1300
1405
  }
1301
1406
 
1302
1407
  // The engine stamps each prompt with where it came from (PromptOrigin); turn.start does not carry it. An idle
@@ -1342,6 +1447,7 @@ async function flushDecisions($, router, turnId, turn) {
1342
1447
  router.turnDecisions.delete(turnId);
1343
1448
  router.turnOrigins.delete(turnId);
1344
1449
  router.progressNotes.delete(turnId);
1450
+ router.turnGoals.delete(turnId);
1345
1451
  if (!rows.length) return;
1346
1452
  try {
1347
1453
  const resets = router.statsResets;
@@ -1868,6 +1974,8 @@ function paneActions($, router, view) {
1868
1974
  const keys = (await $.store.keys()).filter(
1869
1975
  (key) =>
1870
1976
  key.startsWith(DECISIONS_PREFIX) ||
1977
+ key === LEGACY_STORE_PREFIX ||
1978
+ key.startsWith(`${LEGACY_STORE_PREFIX}:`) ||
1871
1979
  Object.values(LEDGERS).some(({ prefix, legacy }) => key.startsWith(prefix) || key === legacy),
1872
1980
  );
1873
1981
  await Promise.all(keys.map((key) => $.store.delete(key)));
@@ -1953,6 +2061,7 @@ function paneActions($, router, view) {
1953
2061
  async function endSession($, router) {
1954
2062
  for (const controller of router.controllers) controller.abort();
1955
2063
  router.decisions.clear();
2064
+ clearGoal(router);
1956
2065
  router.prompts.clear();
1957
2066
  router.turnOrigins.clear();
1958
2067
  router.progressNotes.clear();
@@ -2037,6 +2146,9 @@ export function register(on, options) {
2037
2146
  Boolean(base?.includes('127.0.0.1:43170') || base?.includes('localhost:43170'));
2038
2147
  await updateView($, router, {
2039
2148
  nativeModel: model,
2149
+ ...(existing.activityContract !== ACTIVITY_CONTRACT
2150
+ ? { activityContract: ACTIVITY_CONTRACT, activityStats: null }
2151
+ : {}),
2040
2152
  ...(await startView($, router, model)),
2041
2153
  phase: gateway || !supported ? 'unavailable' : 'ready',
2042
2154
  error: !supported ? 'requires Claude Code 2.1.289 or newer' : gateway ? GATEWAY_SETTINGS : null,
@@ -2085,7 +2197,6 @@ export function register(on, options) {
2085
2197
  on('command.run', { command: 'router' }, ($, e) => routerCommand($, router, e.args));
2086
2198
 
2087
2199
  on('turn.start', async ($, e, next) => {
2088
- await fixTurnConfig($, router, e.turnId);
2089
2200
  await startTurn($, router, e);
2090
2201
  return next(e);
2091
2202
  });
@@ -2117,6 +2228,7 @@ export function register(on, options) {
2117
2228
  let loopVersion = loaded.version;
2118
2229
  // The session's model names its tier in the configured routes: a mode's table can run it at another tier.
2119
2230
  let loop = prepareLoop(loaded.value ?? emptyLoop(turn.configured, e.model), e.messageCount);
2231
+ if (loaded.value && loop.generation !== loaded.value.generation) clearGoal(router);
2120
2232
  if (view.phase === 'unavailable' || mode === 'manual') {
2121
2233
  return yield* passMain($, e, next, loop, loopVersion, nativeModel, 'manual', router);
2122
2234
  }
@@ -2216,6 +2328,7 @@ export function register(on, options) {
2216
2328
  const ref = { ...LOOP, id: 'main' };
2217
2329
  const loop = (await $.state.get(ref)).value;
2218
2330
  if (loop) await $.state.set(ref, resetHistory(loop));
2331
+ clearGoal(router);
2219
2332
  for (const controller of router.controllers) controller.abort();
2220
2333
  }
2221
2334
  return result;
@@ -9,10 +9,12 @@ import { afterResetOf, earlierSince, isRecord } from './records.mjs';
9
9
  // A turn's bucket from its tools (observedActivity in facts.mjs). `shell` and `check` came in 1.16: a version before
10
10
  // reads a store that holds them as empty.
11
11
  export const OBSERVED = ['code', 'docs', 'shell', 'ops', 'check', 'read', 'talk'];
12
- // The one stats key every session shared before 1.10.3: it reads as another session's record until a reset deletes it.
13
- export const STORE_KEY = 'activity:stats:v1';
12
+ // Goal labels must not pool with the old turn-activity contract. Legacy records remain until Delete history.
13
+ export const ACTIVITY_CONTRACT = 'goal-phase-v1';
14
+ export const LEGACY_STORE_PREFIX = 'activity:stats:v1';
15
+ export const STORE_KEY = 'activity:goals:v1';
14
16
  // Each session keeps its own stats under this prefix and its session id, as the metrics do.
15
- export const STORE_PREFIX = 'activity:stats:v1:';
17
+ export const STORE_PREFIX = 'activity:goals:v1:';
16
18
  // Each session keeps its own metrics under this prefix and its session id, as savings does (SAVINGS_PREFIX): sessions
17
19
  // finishing turns at the same moment do not overwrite each other. The readout is their sum (mergeMetrics).
18
20
  export const METRICS_PREFIX = 'activity:metrics:v1:';
package/lib/activity.mjs CHANGED
@@ -1,5 +1,7 @@
1
1
  // Activity routing (docs/plans/2026-10-09-activity-routing-plan.md §5): which activity a turn applies, how two routes
2
2
  // compare, and when a route change inside one tier is worth it. Pure.
3
+
4
+ import { PHASE_VALUES } from './classifier-contract.mjs';
3
5
  import { ACTIVITIES, EFFORTS, resolveRoute, routeSpec } from './config.mjs';
4
6
  import { routeEffort } from './cost.mjs';
5
7
  import { cashGate, sameTaskOf } from './policy.mjs';
@@ -12,20 +14,49 @@ export function acceptActivity(config, advice) {
12
14
  return answer.probabilities?.[answer.choice] >= config.policy.activityMass ? answer.choice : null;
13
15
  }
14
16
 
15
- // 1 when route `a` is stronger than `b`, -1 when cheaper, 0 when equal in strength, null when they cannot be ordered.
16
- // Models with explicit strength order by that rank; otherwise by configured output price, then effort. A null effort is `sentEffort`, the one Claude Code sends, as
17
- // the request would carry it; without a named effort on both sides (none sent, or a numeric budget) two different
18
- // efforts do not order. A missing output price orders only against the same model.
17
+ export function acceptPhase(config, advice) {
18
+ const answer = advice?.phase;
19
+ if (!answer || answer.choice === 'uncertain' || !PHASE_VALUES.includes(answer.choice)) return null;
20
+ return answer.probabilities?.[answer.choice] >= config.policy.activityMass ? answer.choice : null;
21
+ }
22
+
23
+ export function opsWorkActivity(config, advice) {
24
+ if (acceptActivity(config, advice) !== 'ops') return null;
25
+ const phase = acceptPhase(config, advice);
26
+ return phase === 'reason' ? 'debug' : phase === 'produce' ? 'code' : null;
27
+ }
28
+
29
+ // Phase chooses a work preference, never a new durable goal. Ops discounts require positive bounded evidence;
30
+ // adaptive ops uses the profile's same-tier engineering floor, not its potentially weaker generic row.
31
+ // The minimum is a conservative support floor, not a multiplied or calibrated joint probability.
32
+ export function routingActivity(config, advice) {
33
+ const answer = advice?.activity;
34
+ if (!answer) return null;
35
+ const phase = acceptPhase(config, advice);
36
+ const mass = answer.probabilities?.[answer.choice] ?? 0;
37
+ const goal = acceptActivity(config, advice);
38
+ const supported = phase ? Math.min(mass, advice.phase.probabilities[phase]) : mass;
39
+ if (goal && (phase === 'verify' || phase === 'execute')) return { choice: 'ops', mass: supported };
40
+ if (goal === 'ops') {
41
+ const floor = opsWorkActivity(config, advice);
42
+ return floor ? { choice: floor, mass: supported } : null;
43
+ }
44
+ return { choice: answer.choice, mass };
45
+ }
46
+
47
+ const acceptRoutingActivity = (config, advice) => {
48
+ const signal = routingActivity(config, advice);
49
+ return ACTIVITIES.includes(signal?.choice) && signal.mass >= config.policy.activityMass ? signal.choice : null;
50
+ };
51
+
52
+ // 1 when route `a` is stronger than `b`, -1 when weaker, 0 when equal in declared strength, null when unordered.
53
+ // Different models require declared strength ranks; tariffs are economics, not capability evidence. Equal declared
54
+ // ranks compare by effort. A null effort is the one handed to Claude Code; absent or numeric efforts do not order.
19
55
  export function compareRoutes(config, a, b, sentEffort) {
20
56
  if (a.model !== b.model) {
21
- const [pa, pb] = [routeSpec(config, a).output, routeSpec(config, b).output];
22
57
  const [sa, sb] = [routeSpec(config, a).strength, routeSpec(config, b).strength];
23
- if (Number.isFinite(sa) && Number.isFinite(sb)) {
24
- if (sa !== sb) return Math.sign(sa - sb);
25
- } else {
26
- if (!Number.isFinite(pa) || !Number.isFinite(pb)) return null;
27
- if (pa !== pb) return Math.sign(pa - pb);
28
- }
58
+ if (!Number.isFinite(sa) || !Number.isFinite(sb)) return null;
59
+ if (sa !== sb) return Math.sign(sa - sb);
29
60
  }
30
61
  const [ea, eb] = [routeEffort(config, a, sentEffort), routeEffort(config, b, sentEffort)];
31
62
  if (ea === eb) return 0;
@@ -42,23 +73,35 @@ export const sameRequest = (config, a, b, sentEffort) =>
42
73
  // stays: a flaky step must not move the route every turn. On the same task (sameTaskOf: a review inside a turn, a turn
43
74
  // with a progress origin, or a continuation prompt) a stronger label is taken at once (explore, then code), and a weaker
44
75
  // one only with at least `downgradeMass` probability once facts.downAllowed holds: the dwell has passed and a checkpoint
45
- // (completedSince) since the last model change. An unclear label keeps the running activity.
76
+ // (completedSince) since the last model change. An unclear label keeps the running activity. The nomination carries
77
+ // its floor provenance; a later physical refusal must restore the incumbent's accepted provenance.
46
78
  export function chooseActivity(config, advice, incumbent, sentEffort, facts = {}) {
47
- if (!advice?.activity) return incumbent.activity;
48
- if (!sameTaskOf(config, advice, facts)) return acceptActivity(config, advice);
49
- const label = advice.activity.choice;
50
- if (!ACTIVITIES.includes(label)) return incumbent.activity;
51
- const order = compareRoutes(config, resolveRoute(config, incumbent.tier, label), incumbent.route, sentEffort);
52
- if (order > 0) return label;
53
- const mass = advice.activity.probabilities?.[label] ?? 0;
54
- if (order < 0 && facts.downAllowed && mass >= config.policy.downgradeMass) return label;
55
- return incumbent.activity;
79
+ const floor = opsWorkActivity(config, advice);
80
+ const stay = { activity: incumbent.activity, floorActivity: floor ? (incumbent.floorActivity ?? null) : null };
81
+ const nominate = (activity) => ({ activity, floorActivity: activity === floor ? floor : null });
82
+ if (!advice?.activity) return stay;
83
+ if (!sameTaskOf(config, advice, facts)) return nominate(acceptRoutingActivity(config, advice));
84
+ const signal = routingActivity(config, advice);
85
+ const label = signal?.choice;
86
+ if (!ACTIVITIES.includes(label)) return stay;
87
+ const candidate = resolveRoute(config, incumbent.tier, label);
88
+ const order = compareRoutes(config, candidate, incumbent.route, sentEffort);
89
+ if (order > 0) return nominate(label);
90
+ // An explicitly declared ops work floor may be nominated without inventing a physical-model ranking.
91
+ // The lateral confidence/cache/hold/cash gates still decide; inherited generic cells get no exception.
92
+ // Equal requests can adopt the semantic work preference without a model/effort switch. Higher tiers may differ.
93
+ if (label === floor && sameRequest(config, candidate, incumbent.route, sentEffort)) return nominate(label);
94
+ const declared = config.configuredActivities ?? config.activities;
95
+ if (order === null && label === floor && declared[label]?.[incumbent.tier]) return nominate(label);
96
+ const mass = signal.mass;
97
+ if (order < 0 && facts.downAllowed && mass >= config.policy.downgradeMass) return nominate(label);
98
+ return stay;
56
99
  }
57
100
 
58
101
  // A route change inside the incumbent's tier, `from` → `to`. Up on evidence: `mass`, the label's probability (1 for
59
102
  // the base route), must clear the tier upgrade bar for this switching tax. Down on economics: the move must pay back
60
- // its cache write within the downgrade horizon. A pair that does not order (an unpriced model, a numeric effort, two
61
- // models at one price) counts as up: it needs evidence, and the base route is always reachable. Labels alone never
103
+ // its cache write within the downgrade horizon. A pair that does not order (unknown strength or a numeric effort)
104
+ // counts as up: it needs evidence, and the base route is always reachable. Labels alone never
62
105
  // switch, so one vote is enough. During an escalation hold only a stronger route may be taken. A cheaper route on the
63
106
  // same task (`sameTask`) waits for facts.downAllowed, as a tier downgrade does: a routing mode changes the route
64
107
  // without a new label, and a free switch must still wait out the dwell. A model with a lower input price also counts
package/lib/band.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  import { activeClassifier, resolveRoute, TIERS } from './config.mjs';
2
2
  import { resetText } from './costs.mjs';
3
3
  import {
4
- BILLING_WORDS,
4
+ API_ESTIMATE,
5
5
  baselineName,
6
6
  classifierLabel,
7
7
  classifierStatus,
@@ -230,9 +230,14 @@ export function bandSegments(config, view, usage, actions) {
230
230
  routeParts(view.actualModel ?? view.selectedModel ?? view.nativeModel, view.effort),
231
231
  served(view) ? part(' fallback', { color: 'yellow' }) : null,
232
232
  );
233
+ const activityText = view.goal
234
+ ? `${view.goal}${view.taskPhase ? ` / ${view.taskPhase}` : ''}${view.activity && view.activity !== view.goal ? ` → ${view.activity}` : ''}`
235
+ : view.activity;
233
236
  const activity =
234
- view.activity && config.activityRouting !== 'off' && !reasonNamesActivity(view.reason)
235
- ? segment(2, part(view.activity, { color: COLOR.activity, italic: true }))
237
+ activityText &&
238
+ config.activityRouting !== 'off' &&
239
+ ((view.goal && (view.taskPhase || view.goal !== view.activity)) || !reasonNamesActivity(view.reason))
240
+ ? segment(2, part(activityText, { color: COLOR.activity, italic: true }))
236
241
  : null;
237
242
  const reason = segment(1, dim(shortReason(view.reason, reasonActivity(config, view))));
238
243
  // The warning leads and the route yields: when the band is narrow, what to fix matters more than the model kept.
@@ -263,7 +268,7 @@ export function bandSegments(config, view, usage, actions) {
263
268
 
264
269
  // The second row: the plan windows on a Claude plan, then this session's cost with its subagents, and how it compares
265
270
  // with your /model (or `unrouted` with subagents):
266
- // "plan 5h ▰▰▰▱▱▱▱▱ 37% ↻17:00 7d 62% session ≈$7.60 API value −$1.76 (−19%) vs Sonnet 5.5 24 replies".
271
+ // "plan 5h ▰▰▰▱▱▱▱▱ 37% ↻17:00 7d 62% session ≈$7.60 API estimate −$1.76 (−19%) vs Sonnet 5.5 24 replies".
267
272
  // An effort-only profile shows its effort mix instead of a saving. When the band is narrow the reset time, the
268
273
  // counts and the words go first; the 5h window and the session total stay.
269
274
  export function sessionSegments(config, view, usage, now = Date.now()) {
@@ -291,11 +296,11 @@ export function sessionSegments(config, view, usage, now = Date.now()) {
291
296
  if (!cost.replies && !cost.agents) return [...out, segment(2, dim('session · no replies yet'))].filter(Boolean);
292
297
  out.push(
293
298
  segment(0, dim('session '), part(costText(cost.totalUsd, cost.billing), { bold: true }), {
294
- ...dim(` ${BILLING_WORDS[cost.billing]}`),
299
+ ...dim(` ${API_ESTIMATE}`),
295
300
  priority: 5,
296
301
  }),
297
302
  );
298
- if (cost.billing === 'mixed') out.push(segment(1, part(`billed ${usd(cost.creditsUsd)}`)));
303
+ if (cost.billing === 'mixed') out.push(segment(1, part(`credits ${costText(cost.creditsUsd, cost.billing)}`)));
299
304
  if (cost.effortOnly && cost.effortMix.length)
300
305
  out.push(segment(2, dim('effort '), part(cost.effortMix.map(([effort, n]) => `${effort} ${n}`).join(' · '))));
301
306
  else if (cost.diffUsd !== null)