@alexeiled/claude-router 1.15.0 → 1.17.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,255 @@
1
+ // Routing decisions kept per session, so a later look can tell why a turn ran where it did: the prompt's origin, the
2
+ // classifier's answer, the tier and activity chosen, the reason, the route, and at the turn's end what its tools did and
3
+ // whether its replies were priced. Counts, labels and routes only, never text. Pure: the hook collects a turn's rows and
4
+ // writes them at turn.complete to the session's own $.store key under DECISIONS_PREFIX.
5
+
6
+ import { afterResetOf, isRecord } from './records.mjs';
7
+
8
+ export const DECISIONS_PREFIX = 'decisions:v1:';
9
+ // The newest rows a session keeps, and the sessions kept: $.store holds 4 MiB for every key together, and a row is about
10
+ // 300 bytes, so the records stay under 400 KB. Upgrade trigger: a review needs more history than this, or the store nears its limit; then roll rows into
11
+ // per-day counts.
12
+ export const MAX_ROWS = 60;
13
+ export const MAX_RECORDS = 20;
14
+ export const RETAIN_MS = 30 * 24 * 60 * 60 * 1000;
15
+ export const ROW_KINDS = ['start', 'review', 'observed', 'end'];
16
+
17
+ // Where a prompt came from, as the engine stamps it (prompt.submit's PromptOrigin.kind). Progress origins report on the
18
+ // running work, so their turn is the same task: the classifier judges the active goal with the report as dialogue, and a
19
+ // cheaper route still waits for the checkpoint. Goal origins are a person's or another agent's request, which may start
20
+ // a new task. Anything else (unclassified, a kind a later engine adds, or none seen) routes as before and leaves the
21
+ // goal as it was.
22
+ export const PROGRESS_ORIGINS = ['task-notification', 'observer', 'observer-activity', 'auto-continuation'];
23
+ export const GOAL_ORIGINS = [
24
+ 'composer',
25
+ 'bridge',
26
+ 'sdk',
27
+ 'slack-ping',
28
+ 'channel',
29
+ 'scheduled-trigger',
30
+ 'plugin',
31
+ 'peer',
32
+ 'peer-send-message',
33
+ 'projects-relay',
34
+ 'coordinator',
35
+ ];
36
+ const ORIGIN = /^[a-z][a-z-]{0,39}$/;
37
+ export const originKind = (origin) =>
38
+ typeof origin?.kind === 'string' && ORIGIN.test(origin.kind) ? origin.kind : 'unknown';
39
+ export const isProgressOrigin = (kind) => PROGRESS_ORIGINS.includes(kind);
40
+ export const isGoalOrigin = (kind) => GOAL_ORIGINS.includes(kind);
41
+
42
+ // Submissions waiting for their turn: a prompt typed or delivered while a turn runs starts its own turn later, or never
43
+ // (one delivered into the running turn). Each waits at most QUEUE_MS, and at most QUEUE_MAX wait.
44
+ export const QUEUE_MS = 10 * 60 * 1000;
45
+ export const QUEUE_MAX = 16;
46
+ const sameText = (a, b) => typeof a === 'string' && typeof b === 'string' && a.trim() === b.trim();
47
+
48
+ // The queue with one more submission, the expired and the oldest past the bound dropped.
49
+ export function queueOrigin(queue, { kind, text, at }) {
50
+ return [...queue.filter((entry) => at - entry.at < QUEUE_MS), { kind, text, at }].slice(-QUEUE_MAX);
51
+ }
52
+
53
+ // The origin of a turn that starts with `text` at `at`, taken from the queue: the oldest waiting submission with that
54
+ // text. Returns { kind, queue }; kind 'unknown' when none matches.
55
+ export function takeOrigin(queue, text, at) {
56
+ const live = queue.filter((entry) => at - entry.at < QUEUE_MS);
57
+ const i = live.findIndex((entry) => sameText(entry.text, text));
58
+ if (i === -1) return { kind: 'unknown', queue: live };
59
+ return { kind: live[i].kind, queue: [...live.slice(0, i), ...live.slice(i + 1)] };
60
+ }
61
+
62
+ const round = (n, digits = 2) => (Number.isFinite(n) ? Math.round(n * 10 ** digits) / 10 ** digits : null);
63
+ const label = (value) => (typeof value === 'string' && value.length > 0 && value.length <= 80 ? value : null);
64
+ const count = (n) => (Number.isSafeInteger(n) && n > 0 ? n : 0);
65
+
66
+ // One routing decision as a row: `kind` start (the turn's first step), review (a classifier review applied inside the
67
+ // turn) or observed (a move on the turn's own tool calls). `advice` is the classifier's answer or null, `error` why
68
+ // there is none, `decision` the route chosen (chooseRoute's), `facts` what it was chosen on, `sameTask` sameTaskOf.
69
+ export function decisionRow({
70
+ at,
71
+ kind,
72
+ origin = null,
73
+ mode = null,
74
+ advice = null,
75
+ error = null,
76
+ decision,
77
+ facts = {},
78
+ sameTask = null,
79
+ }) {
80
+ const activity = advice?.activity ?? null;
81
+ const { downAllowed, contextTokens } = /** @type {{ downAllowed?: boolean, contextTokens?: number }} */ (facts);
82
+ return {
83
+ at,
84
+ kind,
85
+ origin: label(origin),
86
+ mode: label(mode),
87
+ cls: label(advice?.choice),
88
+ p: round(advice?.probabilities?.[advice?.choice]),
89
+ cont: round(advice?.continuation),
90
+ act: label(activity?.choice),
91
+ actP: round(activity?.probabilities?.[activity?.choice]),
92
+ err: label(error),
93
+ tier: label(decision?.tier),
94
+ activity: label(decision?.activity),
95
+ reason: label(decision?.reason),
96
+ route: decision?.model ? label(`${decision.model}@${decision.effort ?? 'session'}`) : null,
97
+ lateral: label(decision?.lateral),
98
+ pinned: Boolean(decision?.pinned),
99
+ same: typeof sameTask === 'boolean' ? sameTask : null,
100
+ down: typeof downAllowed === 'boolean' ? downAllowed : null,
101
+ ctx: Number.isFinite(contextTokens) ? Math.round(contextTokens / 1000) : null,
102
+ };
103
+ }
104
+
105
+ // The turn's end: the bucket its tools fall in (observedActivity), its routed requests, how many were priced, and the
106
+ // unpriced ones by cause (UNPRICED_CAUSES in activity-stats.mjs).
107
+ export function endRow({ at, observed = null, requests = 0, priced = 0, unpriced = {} }) {
108
+ const causes = Object.fromEntries(
109
+ Object.entries(unpriced ?? {}).filter(([cause, n]) => label(cause) && Number.isSafeInteger(n) && n > 0),
110
+ );
111
+ return {
112
+ at,
113
+ kind: 'end',
114
+ observed: label(observed),
115
+ requests: count(requests),
116
+ priced: count(priced),
117
+ unpriced: causes,
118
+ };
119
+ }
120
+
121
+ // A turn keeps its first row (the start) and its newest others up to MAX_TURN_ROWS: a long turn reviewed every few
122
+ // requests must not push the session's earlier turns out of MAX_ROWS.
123
+ export const MAX_TURN_ROWS = 10;
124
+ export function addTurnRow(rows, row) {
125
+ const next = [...rows, row];
126
+ return next.length > MAX_TURN_ROWS ? [next[0], ...next.slice(-(MAX_TURN_ROWS - 1))] : next;
127
+ }
128
+
129
+ // What the classifier reads on a progress turn: the active goal as the request, and the report as the newest line of
130
+ // the dialogue, so it judges the work still to do rather than the report's wording. Without a goal it reads the turn as
131
+ // before. `recentTurns` bounds the dialogue as extractFacts does.
132
+ export function progressInput({ prompt, turns }, { goal = null, note = null }, recentTurns) {
133
+ if (!goal || !note) return { prompt, turns };
134
+ return { prompt: goal, turns: [...turns, { role: 'user', text: note }].slice(-recentTurns) };
135
+ }
136
+
137
+ export function emptyDecisions() {
138
+ return { version: 1, since: null, rows: [] };
139
+ }
140
+
141
+ const nullable = (check) => (v) => v === null || Boolean(check(v));
142
+ const ROW_FIELDS = {
143
+ at: Number.isFinite,
144
+ kind: (v) => ROW_KINDS.includes(v),
145
+ origin: nullable(label),
146
+ mode: nullable(label),
147
+ cls: nullable(label),
148
+ p: nullable(Number.isFinite),
149
+ cont: nullable(Number.isFinite),
150
+ act: nullable(label),
151
+ actP: nullable(Number.isFinite),
152
+ err: nullable(label),
153
+ tier: nullable(label),
154
+ activity: nullable(label),
155
+ reason: nullable(label),
156
+ route: nullable(label),
157
+ lateral: nullable(label),
158
+ pinned: (v) => typeof v === 'boolean',
159
+ same: nullable((v) => typeof v === 'boolean'),
160
+ down: nullable((v) => typeof v === 'boolean'),
161
+ ctx: nullable(Number.isFinite),
162
+ observed: nullable(label),
163
+ requests: Number.isSafeInteger,
164
+ priced: Number.isSafeInteger,
165
+ unpriced: (v) => isRecord(v) && Object.values(v).every((n) => Number.isSafeInteger(n) && n >= 0),
166
+ };
167
+
168
+ // A row with only its known fields of the right type, or null when its time or kind does not read. A row a later
169
+ // version wrote keeps what reads.
170
+ function readRow(row) {
171
+ if (!isRecord(row) || !ROW_FIELDS.at(row.at) || !ROW_FIELDS.kind(row.kind)) return null;
172
+ const out = {};
173
+ for (const [field, check] of Object.entries(ROW_FIELDS))
174
+ if (Object.hasOwn(row, field) && check(row[field])) out[field] = row[field];
175
+ return out;
176
+ }
177
+
178
+ // The stored value with the rows that read, else an empty record: a hand edit never breaks a turn.
179
+ export function readDecisions(value) {
180
+ if (!isRecord(value) || value.version !== 1 || !Array.isArray(value.rows)) return emptyDecisions();
181
+ if (!(value.since === null || Number.isFinite(value.since))) return emptyDecisions();
182
+ return { version: 1, since: value.since, rows: value.rows.map(readRow).filter(Boolean).slice(-MAX_ROWS) };
183
+ }
184
+
185
+ // A record whose first row came before the last reset at `resetAt` (ms) reads as empty.
186
+ export const decisionsAfterReset = (record, resetAt) => afterResetOf(record, resetAt, emptyDecisions);
187
+
188
+ // The record with a finished turn's rows added at `now`, the oldest dropped past MAX_ROWS. No rows: the record itself.
189
+ export function appendDecisions(record, rows, now) {
190
+ if (!rows.length) return record;
191
+ return { version: 1, since: record.since ?? now, rows: [...record.rows, ...rows].slice(-MAX_ROWS) };
192
+ }
193
+
194
+ // Which of the stored `[key, value]` records the store can let go at `now`: those whose newest row is older than
195
+ // RETAIN_MS, then past `max` records the ones whose newest row is oldest. A value that does not read as version 1 keeps
196
+ // its key: a later version may have written it.
197
+ export function prunedDecisions(entries, now, max = MAX_RECORDS) {
198
+ const dated = entries
199
+ .filter(([, value]) => isRecord(value) && value.version === 1)
200
+ .map(([key, value]) => {
201
+ const record = readDecisions(value);
202
+ return [key, record.rows.at(-1)?.at ?? record.since ?? 0];
203
+ });
204
+ const gone = new Set(dated.filter(([, last]) => now - last > RETAIN_MS).map(([key]) => key));
205
+ const kept = dated.filter(([key]) => !gone.has(key)).sort((a, b) => b[1] - a[1]);
206
+ for (const [key] of kept.slice(max)) gone.add(key);
207
+ return gone;
208
+ }
209
+
210
+ const pad2 = (n) => String(n).padStart(2, '0');
211
+ const clock = (ms) => {
212
+ const d = new Date(ms);
213
+ return `${pad2(d.getHours())}:${pad2(d.getMinutes())}:${pad2(d.getSeconds())}`;
214
+ };
215
+ const share = (p) => (Number.isFinite(p) ? ` ${Math.round(p * 100)}%` : '');
216
+
217
+ function endLine(row) {
218
+ const unpriced = Object.entries(row.unpriced ?? {})
219
+ .filter(([cause]) => cause !== 'comparison')
220
+ .map(([cause, k]) => `${cause} ${k}`);
221
+ return [
222
+ clock(row.at),
223
+ 'end ',
224
+ `tools ${row.observed ?? '?'}`,
225
+ `${row.requests} request${row.requests === 1 ? '' : 's'}`,
226
+ `${row.priced} priced`,
227
+ unpriced.length ? `unpriced ${unpriced.join(', ')}` : null,
228
+ row.unpriced?.comparison ? `comparison unavailable ${row.unpriced.comparison}` : null,
229
+ ]
230
+ .filter(Boolean)
231
+ .join(' ');
232
+ }
233
+
234
+ // The newest `n` rows as lines for `/router decisions`, oldest first.
235
+ export function decisionLines(rows, n = 20) {
236
+ if (!rows.length) return ['No routing decisions recorded in this session yet.'];
237
+ return rows.slice(-n).map((row) => {
238
+ if (row.kind === 'end') return endLine(row);
239
+ const activity = row.act ? ` ${row.act}${share(row.actP)}` : '';
240
+ const asked = row.cls ? `${row.cls}${share(row.p)}${activity}` : (row.err ?? 'no answer');
241
+ const task = row.same === true ? 'same task' : row.same === false ? 'new task' : null;
242
+ return [
243
+ clock(row.at),
244
+ row.kind.padEnd(8),
245
+ row.origin ?? 'unknown',
246
+ `asked ${asked}`,
247
+ task,
248
+ `-> ${row.tier ?? '-'}${row.activity ? ` ${row.activity}` : ''} ${row.route ?? ''}`.trimEnd(),
249
+ `(${row.reason ?? '?'})`,
250
+ row.pinned ? 'pinned' : null,
251
+ ]
252
+ .filter(Boolean)
253
+ .join(' ');
254
+ });
255
+ }
package/lib/display.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import { acceptActivity } from './activity.mjs';
2
- import { readStore, storeSummary } from './activity-stats.mjs';
2
+ import { readMetrics, readStore, storeSummary, UNPRICED_CAUSES } from './activity-stats.mjs';
3
3
  import {
4
4
  activeClassifier,
5
5
  CLASSIFIER_OPTIONS,
@@ -7,9 +7,10 @@ import {
7
7
  resolveRoute,
8
8
  routeSpec,
9
9
  sameRoute,
10
+ TIERS,
10
11
  } from './config.mjs';
11
12
  import { ratesAt } from './cost.mjs';
12
- import { applyMode, modeLabel } from './modes.mjs';
13
+ import { applyMode, modeLabel, modeRoute } from './modes.mjs';
13
14
  import { PROBE_RESULTS } from './probe-results.mjs';
14
15
  import { cellForModel } from './route.mjs';
15
16
  import { emptyTotals, readout } from './savings.mjs';
@@ -30,6 +31,40 @@ export const shownConfig = (config, view) => applyMode(config, routingModeOf(vie
30
31
  // `cost (session)`; the status band and the Now tab show it while routing is on.
31
32
  export const routingModeText = (view) => modeLabel(routingModeOf(view));
32
33
 
34
+ // What the routing mode changed on the cell the band shows, against its configured route: 'effort only' when the mode
35
+ // kept the model and moved the effort. The cost estimates price the same tokens on each route, so an effort change
36
+ // shows no difference there; real output length and billing can differ. Null in balanced, without a tier, or when the
37
+ // mode moved the model or nothing.
38
+ export function modeLever(config, view) {
39
+ const { mode } = routingModeOf(view);
40
+ if (mode === 'balanced' || !TIERS.includes(view.tier)) return null;
41
+ const activity = config.activityRouting === 'on' ? (view.activity ?? null) : null;
42
+ const configured = resolveRoute(config, view.tier, activity);
43
+ const routed = modeRoute(config, mode, view.tier, activity);
44
+ return configured.model === routed.model && !sameRoute(configured, routed) ? 'effort only' : null;
45
+ }
46
+
47
+ // The routed replies the usage record left out, by cause (UNPRICED_CAUSES), as one line, or null when there are none.
48
+ const UNPRICED_LABEL = { usage: 'no usage', model: 'no price', ttl: 'cache lifetime unknown', error: 'error' };
49
+ export function unpricedLine(metrics) {
50
+ const { unpriced } = readMetrics(metrics);
51
+ const missing = UNPRICED_CAUSES.filter((cause) => cause !== 'comparison');
52
+ const total = missing.reduce((n, cause) => n + unpriced[cause], 0);
53
+ const comparison = unpriced.comparison
54
+ ? `Comparison unavailable: ${unpriced.comparison} routed repl${unpriced.comparison === 1 ? 'y' : 'ies'}; observed costs are in activity stats`
55
+ : null;
56
+ if (!total) return comparison;
57
+ const causes = missing
58
+ .filter((cause) => unpriced[cause] > 0)
59
+ .map((cause) => `${UNPRICED_LABEL[cause]} ${unpriced[cause]}`);
60
+ return [
61
+ `Unpriced ${total} routed repl${total === 1 ? 'y' : 'ies'} left out of usage: ${causes.join(' · ')}`,
62
+ comparison,
63
+ ]
64
+ .filter(Boolean)
65
+ .join(' · ');
66
+ }
67
+
33
68
  // Why routing starts off: the session's model is no tier's model. Set at session start, read by the band.
34
69
  export const NOT_A_TIER_REASON = 'not a routing tier';
35
70
 
@@ -74,7 +109,7 @@ export const REASONS = {
74
109
  downgrade: 'enough support for a cheaper model',
75
110
  'upgrade-pending': 'waiting before upgrading',
76
111
  'downgrade-pending': 'switching is not justified yet',
77
- 'downgrade-held': 'a cheaper model waits for a passed check on this task',
112
+ 'downgrade-held': 'a cheaper model waits for a checkpoint on this task',
78
113
  hold: 'staying after an escalation',
79
114
  escalation: 'repeated tool failures need a stronger model',
80
115
  'cash-gate': 'estimated cold cache write exceeds the cap',
@@ -144,7 +179,7 @@ export const SHORT_REASONS = {
144
179
  downgrade: '↓ downgrade',
145
180
  'upgrade-pending': '… waiting to go up',
146
181
  'downgrade-pending': '… waiting to go down',
147
- 'downgrade-held': '… down after a passed check',
182
+ 'downgrade-held': '… down after a checkpoint',
148
183
  hold: '= holding',
149
184
  escalation: '↑ tool errors',
150
185
  'cash-gate': '= cash cap',
package/lib/facts.mjs CHANGED
@@ -7,6 +7,15 @@ const REMINDER = /<system-reminder>[\s\S]*?<\/system-reminder>/g;
7
7
  const CLIP_MARKER = ' […] ';
8
8
  const ANSI_ESCAPE = new RegExp(`${String.fromCharCode(0x1b)}\\[[0-?]*[ -/]*[@-~]`, 'g');
9
9
 
10
+ // Images can arrive inside a tool result, not just a user message.
11
+ export function hasImages(messages) {
12
+ const contains = (content) =>
13
+ blocks(content).some(
14
+ (block) => block.type === 'image' || (block.type === 'tool_result' && contains(block.content)),
15
+ );
16
+ return messages.some((message) => contains(message.content));
17
+ }
18
+
10
19
  export function extractFacts(body, memory, { recentTurns, maxTextChars }) {
11
20
  const messages = Array.isArray(body.messages) ? body.messages : [];
12
21
  // Claude Code puts hook output and tool additions in `system` messages after the user message, and keeps them in
@@ -35,6 +44,7 @@ export function extractFacts(body, memory, { recentTurns, maxTextChars }) {
35
44
  turns.push({ role: message.role, text: clip(text, maxTextChars) });
36
45
  });
37
46
  return {
47
+ hasImages: hasImages(messages),
38
48
  turns: turns.slice(-recentTurns),
39
49
  prompt: current === -1 ? '' : clip(textOf(lastBlocks), maxTextChars),
40
50
  continuation: last?.role === 'user' && lastBlocks.some((b) => b.type === 'tool_result'),
@@ -108,6 +118,12 @@ const SEPARATORS = /&&|\|\||[;|&\n]/;
108
118
  // find can run or delete what it finds.
109
119
  const WRITING_FIND = /\s-(?:exec|execdir|ok|okdir|delete)\b/;
110
120
 
121
+ // A command as the classifiers read it: quoted text blanked, so a `;` or `>` inside a pattern is not shell syntax, and
122
+ // redirects of a stream into another stream or into /dev/null dropped, as they write no file. Every classifier below
123
+ // reads this one form, so they agree on what a command is.
124
+ const bareCommand = (command) =>
125
+ command.replace(/'[^']*'|"[^"]*"/g, '""').replace(/\d?>\s*&\d|\d?>\s*\/dev\/null/g, '');
126
+
111
127
  // The index of the last user prompt, a user message that is not a tool result: where the latest turn starts. -1 when
112
128
  // there is none.
113
129
  export function promptIndex(messages) {
@@ -117,7 +133,10 @@ export function promptIndex(messages) {
117
133
  }
118
134
 
119
135
  // The bucket of a finished turn, from the tool calls the assistant made after the user message at `fromIndex`:
120
- // code, docs, ops, read or talk. First match wins; only names and paths are read, no text is kept.
136
+ // code, docs, shell, ops, check, read or talk. First match wins; only names and paths are read, no text is kept.
137
+ // `shell` is a candidate, not proven code: a command that writes a file's content (a redirect, `tee`, `sed -i`, a
138
+ // patch), which may be code, docs or routine work. `check` is a turn whose only commands that are not reads are
139
+ // checks (`npm test`, `tsc`): a review or a verification. Routine file commands (`rm`, `mv`, `mkdir`) stay `ops`.
121
140
  export function observedActivity(messages, fromIndex) {
122
141
  const calls = [];
123
142
  for (let i = fromIndex + 1; i < messages.length; i += 1)
@@ -125,10 +144,55 @@ export function observedActivity(messages, fromIndex) {
125
144
  for (const block of blocks(messages[i].content)) if (block.type === 'tool_use') calls.push(block);
126
145
  const edited = calls.filter((c) => FILE_EDIT_TOOLS.has(c.name));
127
146
  if (edited.length > 0) return edited.every((c) => DOC_PATH.test(editPath(c))) ? 'docs' : 'code';
128
- if (calls.some((c) => c.name === 'Bash' && !readsOnly(c.input?.command))) return 'ops';
147
+ const commands = calls.filter((c) => c.name === 'Bash').map((c) => commandKind(c.input?.command));
148
+ if (commands.includes('shell')) return 'shell';
149
+ if (commands.includes('ops')) return 'ops';
150
+ if (commands.includes('check')) return 'check';
129
151
  return calls.length > 0 ? 'read' : 'talk';
130
152
  }
131
153
 
154
+ // The activity routing reads from a bucket: `shell` and `check` route as `ops`, the commands they are. The finer
155
+ // buckets serve the agreement counts only, so they change no route.
156
+ export const routingBucket = (bucket) => (bucket === 'shell' || bucket === 'check' ? 'ops' : bucket);
157
+
158
+ // One Bash command as `read`, `shell` (writes a file's content), `check` (a checker whose status is its own) or
159
+ // `ops` (anything else that runs).
160
+ function commandKind(command) {
161
+ if (readsOnly(command)) return 'read';
162
+ if (writesFile(command)) return 'shell';
163
+ return verifies(command) && checksOnly(command) ? 'check' : 'ops';
164
+ }
165
+
166
+ // Some command of the pipeline or list runs a check, whatever its status reports: `npm test | tail`, `npm test; true`.
167
+ function runsAnyCheck(command) {
168
+ if (typeof command !== 'string') return false;
169
+ return bareCommand(command)
170
+ .split(SEPARATORS)
171
+ .some((part) => part.trim() !== '' && runsCheck(part.trim().split(/\s+/)));
172
+ }
173
+
174
+ // Every step of an `&&` list is a check or a read: `npm test && git commit` runs something besides the check.
175
+ function checksOnly(command) {
176
+ const bare = bareCommand(command);
177
+ return bare.split('&&').every((step) => runsCheck(step.trim().split(/\s+/)) || readsOnly(step));
178
+ }
179
+
180
+ // A command that writes a file's content: an output redirect to a file, `tee`, an in-place `sed` or `perl`, `patch`
181
+ // or `git apply`. Quoted text is blanked first, as readsOnly does, so a `>` inside a pattern is not a redirect.
182
+ const SHELL_WRITERS = [
183
+ /(?:^|[^<>&\d])\d?>>?\s*[^\s&|>]/,
184
+ /(?:^|[\s;&|(])tee\b/,
185
+ /(?:^|[\s;&|(])sed\b[^;&|]*\s(?:-[a-zA-Z]*i|--in-place)\b/,
186
+ /(?:^|[\s;&|(])perl\b[^;&|]*\s-[a-zA-Z]*i/,
187
+ /(?:^|[\s;&|(])patch\b/,
188
+ /(?:^|[\s;&|(])git\s+apply\b/,
189
+ ];
190
+ function writesFile(command) {
191
+ if (typeof command !== 'string') return false;
192
+ const bare = bareCommand(command);
193
+ return SHELL_WRITERS.some((pattern) => pattern.test(bare));
194
+ }
195
+
132
196
  function editPath(call) {
133
197
  const path = call.input?.file_path ?? call.input?.notebook_path;
134
198
  return typeof path === 'string' ? path : '';
@@ -139,7 +203,7 @@ function editPath(call) {
139
203
  // a pattern is not taken for shell syntax. Anything unrecognised counts as running something.
140
204
  function readsOnly(command) {
141
205
  if (typeof command !== 'string' || /`|\$\(/.test(command)) return false;
142
- const bare = command.replace(/'[^']*'|"[^"]*"/g, '""').replace(/\d?>\s*&\d|\d?>\s*\/dev\/null/g, '');
206
+ const bare = bareCommand(command);
143
207
  if (/[<>]/.test(bare) || WRITING_FIND.test(bare)) return false;
144
208
  return bare.split(SEPARATORS).every((part) => {
145
209
  if (!part.trim()) return true;
@@ -184,7 +248,7 @@ const CHECK_WORD =
184
248
 
185
249
  function verifies(command) {
186
250
  if (typeof command !== 'string') return false;
187
- const bare = command.replace(/'[^']*'|"[^"]*"/g, '""').replace(/\d?>\s*&\d|\d?>\s*\/dev\/null/g, '');
251
+ const bare = bareCommand(command);
188
252
  const steps = bare.split('&&');
189
253
  if (steps.some((step) => /\|\||[;|&\n]/.test(step))) return false;
190
254
  return steps.some((step) => runsCheck(step.trim().split(/\s+/)));
@@ -229,3 +293,70 @@ export function verifiedSince(messages, fromIndex) {
229
293
 
230
294
  // What Claude Code's Bash tool returns for a command it moved to the background.
231
295
  const BACKGROUNDED = /running in background|moved to the background/i;
296
+
297
+ const DELEGATING = new Set(['Agent', 'Task']);
298
+ const READ_ONLY_ACTIVITIES = new Set(['explore', 'plan', 'review']);
299
+
300
+ // Positive evidence that the work since message `fromIndex` reached a checkpoint, by the activity the running route
301
+ // serves: the checkpoint a move to a cheaper route on the same task waits for. A passed check (verifiedSince) always
302
+ // counts. Without one:
303
+ // - `ops`: the last command that ran something succeeded, and no edit or delegation happened.
304
+ // - `docs`: the last edit succeeded and touched only doc paths, with no other command writing or running.
305
+ // - `explore`, `plan`, `review`: a turn finished since (a newer prompt), nothing was changed or delegated, and the last
306
+ // tool result was not an error.
307
+ // Any other activity, none, or work outside the activity's shape needs the passed check, and so does work where a check
308
+ // ran without passing last: failed, or in a form whose status is not the check's (`npm test && git push`,
309
+ // `npm test > log`, `npm test | tail`, `; `, `||`, the background). The absence of an edit alone is never evidence:
310
+ // each rule asks for a success it can see.
311
+ export function completedSince(messages, fromIndex, activity) {
312
+ if (verifiedSince(messages, fromIndex)) return true;
313
+ const calls = callsSince(messages, fromIndex);
314
+ if (calls.some(({ block }) => DELEGATING.has(block.name))) return false;
315
+ const lastResult = lastResultSince(messages, fromIndex);
316
+ // A check that ran, in any form, and did not pass last (verifiedSince is false) blocks every shortcut.
317
+ if (calls.some(({ block }) => block.name === 'Bash' && runsAnyCheck(block.input?.command))) return false;
318
+ const edits = calls.filter(({ block }) => FILE_EDIT_TOOLS.has(block.name));
319
+ const runs = calls.filter(
320
+ ({ block }) => block.name === 'Bash' && ['ops', 'shell'].includes(commandKind(block.input?.command)),
321
+ );
322
+ if (activity === 'ops') {
323
+ if (edits.length > 0 || runs.length === 0) return false;
324
+ return succeeded(messages, runs.at(-1));
325
+ }
326
+ if (activity === 'docs') {
327
+ if (runs.length > 0 || edits.length === 0) return false;
328
+ if (!edits.every(({ block }) => DOC_PATH.test(editPath(block)))) return false;
329
+ return succeeded(messages, edits.at(-1));
330
+ }
331
+ if (READ_ONLY_ACTIVITIES.has(activity)) {
332
+ if (edits.length > 0 || runs.length > 0) return false;
333
+ return promptIndex(messages) >= fromIndex && fromIndex >= 0 && lastResult?.is_error !== true;
334
+ }
335
+ return false;
336
+ }
337
+
338
+ function callsSince(messages, fromIndex) {
339
+ const calls = [];
340
+ for (let i = Math.max(0, fromIndex); i < messages.length; i += 1)
341
+ if (messages[i]?.role === 'assistant')
342
+ for (const block of blocks(messages[i].content)) if (block.type === 'tool_use') calls.push({ block, index: i });
343
+ return calls;
344
+ }
345
+
346
+ function lastResultSince(messages, fromIndex) {
347
+ let last = null;
348
+ for (let i = Math.max(0, fromIndex); i < messages.length; i += 1)
349
+ if (messages[i]?.role === 'user')
350
+ for (const block of blocks(messages[i].content)) if (block.type === 'tool_result') last = block;
351
+ return last;
352
+ }
353
+
354
+ // Whether the call's result came back without an error, and not as a launch into the background.
355
+ function succeeded(messages, call) {
356
+ if (call.block.input?.run_in_background === true) return false;
357
+ for (let i = call.index + 1; i < messages.length; i += 1)
358
+ for (const block of blocks(messages[i]?.content))
359
+ if (block.type === 'tool_result' && block.tool_use_id === call.block.id)
360
+ return !block.is_error && !BACKGROUNDED.test(textOf(blocks(block.content)));
361
+ return false;
362
+ }
package/lib/panel.mjs CHANGED
@@ -4,7 +4,7 @@ import {
4
4
  ACTIVITIES,
5
5
  ACTIVITY_MODES,
6
6
  activeClassifier,
7
- DEFAULTS,
7
+ defaultsFor,
8
8
  effectiveActivities,
9
9
  effectiveRoutes,
10
10
  ROUTING_MODES,
@@ -41,6 +41,7 @@ import {
41
41
  sparkline,
42
42
  TIER_COLOR,
43
43
  unavailableReason,
44
+ unpricedLine,
44
45
  usageMetrics,
45
46
  usd,
46
47
  whyText,
@@ -113,6 +114,7 @@ const EFFORT_SHORT = { low: 'low', medium: 'med', high: 'high', xhigh: 'xh', max
113
114
  export function routeDraftOf(config, view) {
114
115
  if (view.routeDraft) return view.routeDraft;
115
116
  const base = structuredClone({
117
+ ...(config.provider && config.provider !== 'anthropic' ? { provider: config.provider } : {}),
116
118
  routes: config.routes,
117
119
  baselineTier: config.baselineTier,
118
120
  activities: config.activities,
@@ -184,6 +186,9 @@ export function renderPanel(
184
186
  flexDirection: 'column',
185
187
  children: [
186
188
  ...header(ui, config, view, tab, actions),
189
+ ...(config.provider && config.provider !== 'anthropic'
190
+ ? [ui.dim(`Provider: ${config.provider} · ${view.configPath ?? config.nativePath ?? ''}`)]
191
+ : []),
187
192
  ...body(ui, config, view, usage, actions, modelOptions, columns, now),
188
193
  ...(view.help ? helpLines(ui) : []),
189
194
  ...statusBar(ui, config, view, tab, actions),
@@ -633,7 +638,7 @@ function shortRoute(config, route, narrow) {
633
638
  return `${route.model}·${narrow ? (EFFORT_SHORT[effort] ?? effort) : effort}`;
634
639
  }
635
640
  const routeKey = (route) => `${route.model}@${route.effort ?? ''}`;
636
- const builtIn = (activity, tier) => DEFAULTS.activities[activity]?.[tier] ?? null;
641
+ const builtIn = (config, activity, tier) => defaultsFor(config.provider).activities[activity]?.[tier] ?? null;
637
642
  const sharesEffort = (config, route) => effortSharesCache(config, config.models[route.model]?.id);
638
643
  // The cache a route runs on: one per model on a model that keeps one cache across efforts, else one per route.
639
644
  const cacheOf = (config, route) => (sharesEffort(config, route) ? route.model : routeKey(route));
@@ -646,7 +651,9 @@ function overrideWarnings(config, uses, activity, tier) {
646
651
  return [
647
652
  above && compareRoutes(config, route, above) > 0 ? 'stronger than the tier above' : null,
648
653
  uses.get(cacheOf(config, route)) === 1
649
- ? `${sharesEffort(config, route) ? 'a model' : 'a model + effort'} only this cell uses: one more cache`
654
+ ? config.cache.mode === 'automatic'
655
+ ? 'a route only this cell uses; cache sharing is unknown'
656
+ : `${sharesEffort(config, route) ? 'a model' : 'a model + effort'} only this cell uses: one more cache`
650
657
  : null,
651
658
  ].filter(Boolean);
652
659
  }
@@ -769,7 +776,7 @@ function routesTab(ui, config, view, _usage, actions, modelOptions, columns) {
769
776
  const route = resolveRoute(draft, tier, activity);
770
777
  const edited = changes.cells.some(([a, t]) => a === activity && t === tier) ? '●' : '';
771
778
  if (sameRoute(route, draft.routes[tier])) return cellButton(activity, tier, `·${edited}`, true);
772
- const preset = builtIn(activity, tier);
779
+ const preset = builtIn(draft, activity, tier);
773
780
  const mark = preset && sameRoute(route, { model: preset.model, effort: preset.effort ?? null }) ? '°' : '';
774
781
  return cellButton(activity, tier, `${shortRoute(draft, route, narrow)}${mark}${edited}`, mode !== 'on');
775
782
  }),
@@ -780,7 +787,15 @@ function routesTab(ui, config, view, _usage, actions, modelOptions, columns) {
780
787
  ui.text(' '),
781
788
  ...cellEditor(ui, draft, changes, selected, cacheUses(draft, true).uses, actions, modelOptions),
782
789
  ui.text(' '),
783
- ...cacheLines(ui, uses.size, shared, mode, columns),
790
+ ...(config.cache.mode === 'automatic'
791
+ ? [
792
+ ui.dim(
793
+ 'Automatic prefix cache: hits are observed; lifetime and sharing across efforts are unknown. No cache-write premium.',
794
+ ),
795
+ ]
796
+ : config.cache.mode === 'disabled'
797
+ ? [ui.dim('Prompt caching disabled: input is priced at the uncached rate.')]
798
+ : cacheLines(ui, uses.size, shared, mode, columns)),
784
799
  ...LADDER.slice(0, -1)
785
800
  .filter((upper, i) => sameRoute(draft.routes[upper], draft.routes[LADDER[i + 1]]))
786
801
  .map((upper) =>
@@ -790,7 +805,7 @@ function routesTab(ui, config, view, _usage, actions, modelOptions, columns) {
790
805
  ),
791
806
  ),
792
807
  ui.Button({ key: 'reset-routes', label: 'Reset routes to defaults', hotkey: 'r', onPress: actions.resetRoutes }),
793
- ui.dim('A new model ID needs router.json → models: price, window, efforts.'),
808
+ ui.dim('A new model ID needs the active file → models: price, window, efforts.'),
794
809
  );
795
810
  return out;
796
811
  }
@@ -842,7 +857,7 @@ function cellEditor(ui, draft, changes, selected, uses, actions, modelOptions) {
842
857
  const activity = row;
843
858
  const route = resolveRoute(draft, tier, activity);
844
859
  const base = draft.routes[tier];
845
- const preset = builtIn(activity, tier);
860
+ const preset = builtIn(draft, activity, tier);
846
861
  const presetRoute = preset ? { model: preset.model, effort: preset.effort ?? null } : null;
847
862
  const edited = changes.cells.some(([a, t]) => a === activity && t === tier);
848
863
  const own = !sameRoute(route, base);
@@ -947,7 +962,8 @@ const MODE_HINT = {
947
962
  function policyTab(ui, config, view, _usage, actions) {
948
963
  const changes = routingChanges(config, view);
949
964
  const { draft, tuning, policy } = changes;
950
- const defaults = tuningOf(DEFAULTS);
965
+ const preset = defaultsFor(config.provider);
966
+ const defaults = tuningOf(preset);
951
967
  const label = classifierLabel(config);
952
968
  const pad = ''.padEnd(13);
953
969
  const tune = (key) => choice(ui, key, tuning[key], POLICY_FORMAT[key], (value) => actions.tune(key, value));
@@ -990,7 +1006,7 @@ function policyTab(ui, config, view, _usage, actions) {
990
1006
  : draft.baselineTier,
991
1007
  ' ',
992
1008
  marker(ui, changes.baseline),
993
- draft.baselineTier === DEFAULTS.baselineTier ? null : ui.dim(`default ${DEFAULTS.baselineTier}`),
1009
+ draft.baselineTier === preset.baselineTier ? null : ui.dim(`default ${preset.baselineTier}`),
994
1010
  ),
995
1011
  ui.dim(`${pad}when the session’s model is no tier’s model`),
996
1012
  ui.line(
@@ -1220,6 +1236,8 @@ function storeUsage(ui, store, metrics) {
1220
1236
  out.push(
1221
1237
  ui.text(`Escalations after a cheaper activity move: ${escalations} in ${moves} move${moves === 1 ? '' : 's'}`),
1222
1238
  );
1239
+ const unpriced = unpricedLine(metrics);
1240
+ if (unpriced) out.push(ui.text(unpriced));
1223
1241
  return out;
1224
1242
  }
1225
1243
 
package/lib/policy.mjs CHANGED
@@ -2,11 +2,14 @@
2
2
  import { rank, resolveRoute, routeSpec, TIERS } from './config.mjs';
3
3
  import * as nativeCosts from './cost.mjs';
4
4
 
5
- // Whether an answer is about the task already running: a review inside a turn (facts.midTurn), or a new prompt the
6
- // classifier scores as a continuation. On the same task either way is open, but a cheaper route waits for
7
- // facts.downAllowed: the dwell since the last model change and a passed verification.
5
+ // Whether an answer is about the task already running: a review inside a turn (facts.midTurn), a turn the engine
6
+ // started from progress on the running work (facts.progress: a task notification, an observer's report), or a new
7
+ // prompt the classifier scores as a continuation. On the same task either way is open, but a cheaper route waits for
8
+ // facts.downAllowed: the dwell since the last model change and a checkpoint the activity can show (completedSince).
8
9
  export function sameTaskOf(config, advice, facts) {
9
- return Boolean(facts.midTurn) || (advice?.continuation ?? 0) >= config.policy.continuationMass;
10
+ return (
11
+ Boolean(facts.midTurn) || Boolean(facts.progress) || (advice?.continuation ?? 0) >= config.policy.continuationMass
12
+ );
10
13
  }
11
14
 
12
15
  export function initialState() {