sprag-cli 3.101.1 → 3.103.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.
- package/README.ko.md +1 -1
- package/README.md +1 -1
- package/bin/cli.js +26 -12
- package/package.json +1 -1
- package/src/agents.js +1 -1
- package/src/commands/saved.js +25 -1
- package/src/delegation-guard.js +54 -4
- package/src/formatters/statusline.js +61 -17
- package/src/glyphs.js +6 -0
- package/src/model-rules.js +26 -0
- package/src/route-inject.js +17 -1
- package/src/route-scan.js +20 -0
- package/src/stdin-payload.js +1 -1
- package/src/subagent-records.js +43 -0
- package/src/ultracode.js +103 -75
package/README.ko.md
CHANGED
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
|
|
16
16
|
[English](https://github.com/rootstudioyaml/sprag/blob/main/README.md) · [한국어](https://github.com/rootstudioyaml/sprag/blob/main/README.ko.md)
|
|
17
17
|
|
|
18
|
-
[sprag.io](https://sprag.io) · [벤치마크](https://github.com/rootstudioyaml/sprag/blob/main/docs/BENCHMARK.md)
|
|
18
|
+
[sprag.io](https://sprag.io) · [벤치마크](https://github.com/rootstudioyaml/sprag/blob/main/docs/BENCHMARK.md) · [검증 사례](https://sprag.io/proof/)
|
|
19
19
|
|
|
20
20
|
<a href="https://github.com/rootstudioyaml/sprag/blob/main/README.ko.md#팀"><img src="https://raw.githubusercontent.com/rootstudioyaml/sprag/main/docs/plan-pro-ko.gif" width="640" alt="팀원마다 동물 캐릭터로 앉아 있는 가상 사무실, 지출과 절감액, 좌석, 30일 차트가 있는 조직 대시보드, 한 번 승인하면 모든 컴퓨터에 적용되는 팀 규칙을 차례로 보여 줍니다."></a>
|
|
21
21
|
|
package/README.md
CHANGED
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
|
|
16
16
|
[English](https://github.com/rootstudioyaml/sprag/blob/main/README.md) · [한국어](https://github.com/rootstudioyaml/sprag/blob/main/README.ko.md)
|
|
17
17
|
|
|
18
|
-
[sprag.io](https://sprag.io) · [Benchmark](https://github.com/rootstudioyaml/sprag/blob/main/docs/BENCHMARK.md)
|
|
18
|
+
[sprag.io](https://sprag.io) · [Benchmark](https://github.com/rootstudioyaml/sprag/blob/main/docs/BENCHMARK.md) · [Proof](https://sprag.io/proof/)
|
|
19
19
|
|
|
20
20
|
<a href="https://github.com/rootstudioyaml/sprag#teams"><img src="https://raw.githubusercontent.com/rootstudioyaml/sprag/main/docs/plan-pro-en.gif" width="640" alt="A virtual office where every teammate sits as an animal character, then the organization dashboard with spend, savings, seats and a 30-day chart, then team rules approved once and picked up by every machine."></a>
|
|
21
21
|
|
package/bin/cli.js
CHANGED
|
@@ -42,7 +42,7 @@ import {
|
|
|
42
42
|
extractTranscriptPath,
|
|
43
43
|
} from '../src/stdin-payload.js';
|
|
44
44
|
|
|
45
|
-
import {
|
|
45
|
+
import { ultracodeChipState } from '../src/ultracode.js';
|
|
46
46
|
|
|
47
47
|
import { parseAllSessions, sessionsSince, getLastUserMessageTime } from '../src/parser.js';
|
|
48
48
|
import {
|
|
@@ -95,6 +95,16 @@ function tableColor() {
|
|
|
95
95
|
return !hasFlag('--no-color') && !process.env.NO_COLOR && !!process.stdout.isTTY;
|
|
96
96
|
}
|
|
97
97
|
|
|
98
|
+
/**
|
|
99
|
+
* The ultra chip's state for a live statusline render: true/false when the
|
|
100
|
+
* payload names a `transcript_path`, null (no chip) when it does not. Off covers
|
|
101
|
+
* "turned off", "never touched" and an unreadable transcript alike.
|
|
102
|
+
*/
|
|
103
|
+
function ultraChipFor(stdinJson) {
|
|
104
|
+
const path = extractTranscriptPath(stdinJson);
|
|
105
|
+
return path ? ultracodeChipState(path) === true : null;
|
|
106
|
+
}
|
|
107
|
+
|
|
98
108
|
// Subcommands this build knows how to run. Used only by the guard below.
|
|
99
109
|
/**
|
|
100
110
|
* `--segments a,b,c` as a list, or null for the default order. One parser for
|
|
@@ -700,9 +710,10 @@ async function main() {
|
|
|
700
710
|
const stdinJson = readStdinJson();
|
|
701
711
|
const caps = extractCaps(stdinJson);
|
|
702
712
|
const model = extractModel(stdinJson);
|
|
703
|
-
// Resolved the same way as on the populated line below, so the
|
|
704
|
-
// not change
|
|
705
|
-
const effort =
|
|
713
|
+
// Resolved the same way as on the populated line below, so the chips do
|
|
714
|
+
// not change their minds when the analysis window empties.
|
|
715
|
+
const effort = extractEffort(stdinJson);
|
|
716
|
+
const ultra = ultraChipFor(stdinJson);
|
|
706
717
|
// Recorded here too: a fresh session can render before it has any request
|
|
707
718
|
// in the analysis window, and its first prompt is briefed from this.
|
|
708
719
|
const ctxLive = extractContextUsage(stdinJson);
|
|
@@ -720,7 +731,7 @@ async function main() {
|
|
|
720
731
|
}
|
|
721
732
|
const { withBaseStatusline } = await import('../src/statusline-base.js');
|
|
722
733
|
const noSessionOut = withBaseStatusline(formatNoSession(
|
|
723
|
-
{ caps, model, effort, windowLabel, version: PKG_VERSION, update: readUpdateChip(PKG_VERSION), team: (await import('../src/team-sync.js')).readTeamChip() },
|
|
734
|
+
{ caps, model, effort, ultra, windowLabel, version: PKG_VERSION, update: readUpdateChip(PKG_VERSION), team: (await import('../src/team-sync.js')).readTeamChip() },
|
|
724
735
|
{ color: colorOk, mode: labelMode, segments: segmentsFromArgs(), columns: columnsFromArgs() },
|
|
725
736
|
), { input: readStdinRaw() });
|
|
726
737
|
if (guard) guard.finish(noSessionOut);
|
|
@@ -773,13 +784,11 @@ async function main() {
|
|
|
773
784
|
// user has since changed would be worse there than no chip at all. The effort
|
|
774
785
|
// chip is a live-statusline reading only.
|
|
775
786
|
//
|
|
776
|
-
//
|
|
777
|
-
//
|
|
778
|
-
//
|
|
779
|
-
|
|
780
|
-
const
|
|
781
|
-
? effortChipLevel(extractEffort(stdinJson), extractTranscriptPath(stdinJson))
|
|
782
|
-
: extractEffort(stdinJson);
|
|
787
|
+
// Ultracode is a separate toggle the payload cannot name, so the transcript
|
|
788
|
+
// settles it (see src/ultracode.js). Only a live statusline render that was
|
|
789
|
+
// handed a transcript path asks; every other caller gets no ultra chip.
|
|
790
|
+
const effort = extractEffort(stdinJson);
|
|
791
|
+
const ultra = isStatusline ? ultraChipFor(stdinJson) : null;
|
|
783
792
|
const ctxLive = extractContextUsage(stdinJson);
|
|
784
793
|
// The prompt-submit briefing has no payload field for the window, so it reads
|
|
785
794
|
// back what this render was told (see src/ctx-window-cache.js).
|
|
@@ -996,10 +1005,13 @@ async function main() {
|
|
|
996
1005
|
// The same cached scan says how old the savings figures are: the ledger is
|
|
997
1006
|
// filled by route-scan, so a stale scan means a stale total.
|
|
998
1007
|
let routeScanAt = null;
|
|
1008
|
+
// Sonnet delegations sprag ran at high effort (see buildDelegatedSeg).
|
|
1009
|
+
let effortRaises = null;
|
|
999
1010
|
try {
|
|
1000
1011
|
const { readRouteScan } = await import('../src/route-scan.js');
|
|
1001
1012
|
const scan = readRouteScan();
|
|
1002
1013
|
unresolvedRuns = Number(scan?.unresolvedRuns) || 0;
|
|
1014
|
+
if (scan?.effortRaises && typeof scan.effortRaises === 'object') effortRaises = scan.effortRaises;
|
|
1003
1015
|
const scannedAt = Date.parse(scan?.scannedAt);
|
|
1004
1016
|
routeScanAt = Number.isFinite(scannedAt) ? scannedAt : null;
|
|
1005
1017
|
} catch (e) {
|
|
@@ -1076,12 +1088,14 @@ async function main() {
|
|
|
1076
1088
|
// Raw payload model id for the compact-window chip's `modelSettings` lookup.
|
|
1077
1089
|
liveModel: isStatusline ? liveModelIdOf(stdinJson) : undefined,
|
|
1078
1090
|
effort,
|
|
1091
|
+
ultra,
|
|
1079
1092
|
delegationSaved,
|
|
1080
1093
|
delegationTotals,
|
|
1081
1094
|
doc2mdTotals,
|
|
1082
1095
|
unresolvedRuns,
|
|
1083
1096
|
// Statusline-only; left undefined elsewhere so --format json keeps its shape.
|
|
1084
1097
|
routeScanAt: isStatusline ? routeScanAt : undefined,
|
|
1098
|
+
effortRaises: isStatusline ? effortRaises : undefined,
|
|
1085
1099
|
sessionDelegation,
|
|
1086
1100
|
ruleStats,
|
|
1087
1101
|
ttlBucket,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "sprag-cli",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.103.0",
|
|
4
4
|
"description": "Model-delegation router for Claude Code and Codex: lookups, checks and test runs go to cheaper models, documents go in as compact Markdown, and a live statusline shows spend and savings.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
package/src/agents.js
CHANGED
|
@@ -97,7 +97,7 @@ export function agentForRule(rule, { agents = agentDefinitions() } = {}) {
|
|
|
97
97
|
}
|
|
98
98
|
|
|
99
99
|
/** Model alias an agent (or a legacy agent name) is pinned to, or undefined. */
|
|
100
|
-
const modelOf = (name) => AGENT_MODEL[Object.hasOwn(LEGACY_AGENT_NAMES, name) ? LEGACY_AGENT_NAMES[name] : name];
|
|
100
|
+
export const modelOf = (name) => AGENT_MODEL[Object.hasOwn(LEGACY_AGENT_NAMES, name) ? LEGACY_AGENT_NAMES[name] : name];
|
|
101
101
|
|
|
102
102
|
/** Agent a bare tier name stands for when that agent's file exists. */
|
|
103
103
|
const TIER_AGENT = { sonnet: 't1-worker', opus: 't1h-worker', haiku: 't2-explore' };
|
package/src/commands/saved.js
CHANGED
|
@@ -70,6 +70,28 @@ async function refreshRuleSavings(ko, rescan) {
|
|
|
70
70
|
}
|
|
71
71
|
}
|
|
72
72
|
|
|
73
|
+
/**
|
|
74
|
+
* Sonnet delegations the guard ran at high effort because the call passed none
|
|
75
|
+
* (src/delegation-guard.js), from the last route-scan. The statusline shows only
|
|
76
|
+
* the count; the cost is said here, along with the fact that the saving above
|
|
77
|
+
* already paid for it. Silent when nothing was raised or the scan is unreadable.
|
|
78
|
+
*/
|
|
79
|
+
function printEffortRaises({ ko, money, readScan }) {
|
|
80
|
+
let r;
|
|
81
|
+
try {
|
|
82
|
+
r = readScan()?.effortRaises;
|
|
83
|
+
} catch (e) {
|
|
84
|
+
debug('saved:effort-raises', e);
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
const count = Number(r?.count) || 0;
|
|
88
|
+
if (count <= 0) return;
|
|
89
|
+
const cost = money(Number(r.cost) || 0);
|
|
90
|
+
console.log(ko
|
|
91
|
+
? `effort 상향: ${count}회 · 실행 비용 ${cost} (effort 없이 Sonnet에 보낸 위임을 high로 올렸습니다. 절감액에는 이미 반영돼 있습니다)`
|
|
92
|
+
: `Effort raised: ${count} runs · run cost ${cost} (sonnet delegations sent without an effort were run at high; the saving above is already net of it)`);
|
|
93
|
+
}
|
|
94
|
+
|
|
73
95
|
const FAMILY_NAMES = { opus: 'Opus', sonnet: 'Sonnet', haiku: 'Haiku', fable: 'Fable', mythos: 'Mythos' };
|
|
74
96
|
|
|
75
97
|
/**
|
|
@@ -118,7 +140,7 @@ async function printModelShare({ ko, dir, money }) {
|
|
|
118
140
|
}
|
|
119
141
|
}
|
|
120
142
|
|
|
121
|
-
export async function run({ args, hasFlag, agent = 'claude', dir: dirArg, rescan }) {
|
|
143
|
+
export async function run({ args, hasFlag, agent = 'claude', dir: dirArg, rescan, readScan: readScanArg }) {
|
|
122
144
|
const { userLanguage } = await import('../config.js');
|
|
123
145
|
const { userDataDir } = await import('../paths.js');
|
|
124
146
|
const { readResetMarks, resetSaved, undoReset } = await import('../saved-reset.cjs');
|
|
@@ -150,12 +172,14 @@ export async function run({ args, hasFlag, agent = 'claude', dir: dirArg, rescan
|
|
|
150
172
|
|
|
151
173
|
if (sub === undefined) {
|
|
152
174
|
const marks = readResetMarks(dir);
|
|
175
|
+
const readScan = readScanArg || (await import('../route-scan.js')).readRouteScan;
|
|
153
176
|
for (const s of scopes) {
|
|
154
177
|
const t = await currentTotals(s, dir);
|
|
155
178
|
const since = marks[s] === null
|
|
156
179
|
? (ko ? '초기화한 적 없음' : 'not reset')
|
|
157
180
|
: (ko ? `${fmtTime(marks[s])} 이후` : `since ${fmtTime(marks[s])}`);
|
|
158
181
|
console.log(`${label(s)}: ${fmtTotal(t)} (${since})`);
|
|
182
|
+
if (s === 'routing') printEffortRaises({ ko, money, readScan });
|
|
159
183
|
}
|
|
160
184
|
if (agent !== 'codex') {
|
|
161
185
|
console.log(ko
|
package/src/delegation-guard.js
CHANGED
|
@@ -27,6 +27,7 @@ import { homedir } from 'node:os';
|
|
|
27
27
|
import { loadConfig, saveConfig } from './config.js';
|
|
28
28
|
import { recentToolPaths } from './session-paths.js';
|
|
29
29
|
import { routeCapsFor } from './route-caps.js';
|
|
30
|
+
import { modelOf } from './agents.js';
|
|
30
31
|
|
|
31
32
|
const packageRoot = join(dirname(fileURLToPath(import.meta.url)), '..');
|
|
32
33
|
|
|
@@ -120,8 +121,12 @@ export async function buildAppendix(payload, { cfg = loadConfig(), home = homedi
|
|
|
120
121
|
|
|
121
122
|
// Read from `model` first — it is the more specific field when both are set
|
|
122
123
|
// — falling back to `subagent_type`. Hoisted out of the bounds section
|
|
123
|
-
// because the Korean section below weighs the same answer.
|
|
124
|
-
|
|
124
|
+
// because the Korean section below weighs the same answer. The preset agents
|
|
125
|
+
// are named by tier (t2-explore, t1h-worker), so a bare subagent_type says
|
|
126
|
+
// nothing about the model until it is looked up; without that every
|
|
127
|
+
// tier-named delegation got the 20-call / 8,000-token sonnet cap.
|
|
128
|
+
const agentName = String(payload?.tool_input?.subagent_type || '');
|
|
129
|
+
const modelHint = String(payload?.tool_input?.model || modelOf(agentName) || agentName);
|
|
125
130
|
const isHaiku = /haiku/i.test(modelHint);
|
|
126
131
|
const isOpus = /opus/i.test(modelHint);
|
|
127
132
|
|
|
@@ -253,10 +258,55 @@ export async function decideForDelegation(payload, { cfg = loadConfig(), home =
|
|
|
253
258
|
// same tool_name, must not stack the appendix onto itself.
|
|
254
259
|
if (prompt.includes(DELEGATION_MARKER)) return null;
|
|
255
260
|
|
|
261
|
+
const raise = wantsEffortRaise(toolInput);
|
|
256
262
|
const appendix = await buildAppendix(payload, { cfg, home, routeCaps });
|
|
257
|
-
if (!appendix) return null;
|
|
263
|
+
if (!appendix && !raise) return null;
|
|
258
264
|
|
|
259
|
-
|
|
265
|
+
const parts = [prompt];
|
|
266
|
+
if (appendix) parts.push(appendix);
|
|
267
|
+
// The marker line goes into the prompt as well as the input: the prompt is
|
|
268
|
+
// what the subagent transcript keeps, so route-scan can later tell a raise
|
|
269
|
+
// this hook made from an effort the caller chose (see src/route-scan.js).
|
|
270
|
+
if (raise) parts.push(EFFORT_RAISE_MARKER);
|
|
271
|
+
const updatedInput = { ...toolInput, prompt: parts.join('\n\n') };
|
|
272
|
+
if (raise) updatedInput.effort = RAISED_EFFORT;
|
|
273
|
+
return { updatedInput };
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/** Effort a sonnet delegation runs at when the call passed none. */
|
|
277
|
+
export const RAISED_EFFORT = 'high';
|
|
278
|
+
|
|
279
|
+
/**
|
|
280
|
+
* Line appended to the prompt of a delegation whose effort this hook set.
|
|
281
|
+
* route-scan greps subagent transcripts for it, so the text is part of the
|
|
282
|
+
* ledger's contract: change it and the count of raises resets to zero.
|
|
283
|
+
*/
|
|
284
|
+
export const EFFORT_RAISE_MARKER = 'Effort for this delegation: high (set by sprag; the call did not pass one).';
|
|
285
|
+
|
|
286
|
+
/**
|
|
287
|
+
* True when the call hands work to a sonnet target that pins no effort of
|
|
288
|
+
* its own, and the caller passed none.
|
|
289
|
+
*
|
|
290
|
+
* Why sonnet, and why high. A `general-purpose` call with `model: sonnet` is
|
|
291
|
+
* the route the rules give a lookup that spans several files or a delegated
|
|
292
|
+
* investigation, and without an effort argument Claude Code runs it at
|
|
293
|
+
* medium. Replayed on fixed cases (2026-11-07, blind-graded): the multi-file
|
|
294
|
+
* lookup was relayable at medium in 0 of 3 runs and at high in 2 of 3, for
|
|
295
|
+
* about 25% more cost; across six new cases sonnet at high was relayable in
|
|
296
|
+
* 5 at 30–60% of the Opus cost. Medium was where the silent losses came
|
|
297
|
+
* from, so high is the floor this hook sets.
|
|
298
|
+
*
|
|
299
|
+
* Left alone: the preset agents (t1-worker is high, the t2 agents low —
|
|
300
|
+
* their files pin it, and the haiku agents were fine at low on the work the
|
|
301
|
+
* rules send them), a call that names an effort (the caller's choice,
|
|
302
|
+
* including the escalation step that passes the next level up), and haiku or
|
|
303
|
+
* opus targets, where no measurement backs a change.
|
|
304
|
+
*/
|
|
305
|
+
export function wantsEffortRaise(toolInput) {
|
|
306
|
+
if (!toolInput || typeof toolInput !== 'object') return false;
|
|
307
|
+
if (typeof toolInput.effort === 'string' && toolInput.effort !== '') return false;
|
|
308
|
+
if (modelOf(String(toolInput.subagent_type || ''))) return false;
|
|
309
|
+
return /sonnet/i.test(String(toolInput.model || ''));
|
|
260
310
|
}
|
|
261
311
|
|
|
262
312
|
/**
|
|
@@ -279,8 +279,8 @@ function buildKoreanSeg(c, isIcon, verbose, g, explicit = false) {
|
|
|
279
279
|
* Effort tones are not this palette's to choose: they are Claude Code's own, so
|
|
280
280
|
* the chip shows a level in the color its `/effort` picker showed when the level
|
|
281
281
|
* was set. src/effort-palette.js holds the values and the evidence for them,
|
|
282
|
-
* including why `xhigh` and
|
|
283
|
-
* separates them in the app is dropped.
|
|
282
|
+
* including why `xhigh` and the ultra chip's glow share a hue once the shimmer
|
|
283
|
+
* that separates them in the app is dropped.
|
|
284
284
|
*
|
|
285
285
|
* This replaced a scheme of this tool's own devising (gray below default, the
|
|
286
286
|
* model chip's violet at default, bold above it). That scheme was internally
|
|
@@ -298,8 +298,8 @@ const EFFORT_TONES = effortTones({ truecolor: TRUECOLOR });
|
|
|
298
298
|
|
|
299
299
|
/**
|
|
300
300
|
* Effort chip builder — the level from Claude Code's stdin payload
|
|
301
|
-
* (`effort.level`, see extractEffort),
|
|
302
|
-
*
|
|
301
|
+
* (`effort.level`, see extractEffort), shown as it arrives. Ultracode is not a
|
|
302
|
+
* level any more and has its own chip (see buildUltraSeg).
|
|
303
303
|
*
|
|
304
304
|
* The level is a word ("high"), so icon modes need no label beside the glyph:
|
|
305
305
|
* `🔬 high` already reads. Text mode names the field, because a bare "high"
|
|
@@ -321,17 +321,44 @@ function buildEffortSeg(effort, c, isIcon, g) {
|
|
|
321
321
|
// cycling would show only the first three stops — red, orange, yellow, which
|
|
322
322
|
// reads as a warm gradient and not as a rainbow. Spreading walks the whole
|
|
323
323
|
// arc whatever the word's length.
|
|
324
|
-
if (Array.isArray(tone)) {
|
|
325
|
-
const chars = [...effort];
|
|
326
|
-
const last = Math.max(1, chars.length - 1);
|
|
327
|
-
const word = chars
|
|
328
|
-
.map((ch, i) => `${c(tone[Math.round((i * (tone.length - 1)) / last)])}${ch}`)
|
|
329
|
-
.join('');
|
|
330
|
-
return `${c(tone[0])}${head}${word}${c(RESET)}`;
|
|
331
|
-
}
|
|
324
|
+
if (Array.isArray(tone)) return `${c(tone[0])}${head}${spreadTone(tone, effort, c)}${c(RESET)}`;
|
|
332
325
|
return `${c(tone)}${head}${effort}${c(RESET)}`;
|
|
333
326
|
}
|
|
334
327
|
|
|
328
|
+
/** A word painted with a ramp of escapes spread evenly across its characters. */
|
|
329
|
+
function spreadTone(tone, text, c) {
|
|
330
|
+
const chars = [...text];
|
|
331
|
+
const last = Math.max(1, chars.length - 1);
|
|
332
|
+
return chars
|
|
333
|
+
.map((ch, i) => `${c(tone[Math.round((i * (tone.length - 1)) / last)])}${ch}`)
|
|
334
|
+
.join('');
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
/**
|
|
338
|
+
* Ultracode chip builder — a separate chip from effort because ultracode is a
|
|
339
|
+
* session toggle that works at any level (Claude Code 2.1.302), not a level.
|
|
340
|
+
*
|
|
341
|
+
* `ultra` is true/false from the transcript (see ultracodeChipState), or
|
|
342
|
+
* null/undefined when this render has no transcript to ask — the table view, a
|
|
343
|
+
* payload without `transcript_path` — in which case no chip is drawn rather than
|
|
344
|
+
* guessing "off". On is the `max` rainbow in bold, spread across the label:
|
|
345
|
+
* ultracode multiplies what a turn spends, so the chip has to be the loudest
|
|
346
|
+
* thing on the line rather than a tint the eye slides past. The purple glow it
|
|
347
|
+
* first used read as one more colored chip. Bold keeps it apart from a `max`
|
|
348
|
+
* effort chip beside it, which uses the same seven stops without weight. The
|
|
349
|
+
* stops are an array in the 8-color form too, so both terminals get a rainbow.
|
|
350
|
+
* Off is gray.
|
|
351
|
+
*/
|
|
352
|
+
function buildUltraSeg(ultra, c, isIcon, g) {
|
|
353
|
+
if (typeof ultra !== 'boolean') return null;
|
|
354
|
+
const state = ultra ? 'on' : 'off';
|
|
355
|
+
const label = isIcon ? `ultra ${state}` : `Ultra ${state}`;
|
|
356
|
+
const head = isIcon ? `${g.ultra} ` : '';
|
|
357
|
+
if (!ultra) return `${c(GRAY)}${head}${label}${c(RESET)}`;
|
|
358
|
+
const tone = EFFORT_TONES.max;
|
|
359
|
+
return `${c(BOLD)}${c(tone[0])}${head}${spreadTone(tone, label, c)}${c(RESET)}`;
|
|
360
|
+
}
|
|
361
|
+
|
|
335
362
|
/**
|
|
336
363
|
* Version segment builder — "which copy of this tool am I looking at", plus
|
|
337
364
|
* the upgrade nudge when a newer one has been published.
|
|
@@ -675,7 +702,7 @@ function fitChips(segs, { columns, maxLines = 3, eol = '', protectedSegs = new S
|
|
|
675
702
|
* note. With `columns` the chips wrap onto at most `maxLines` lines (see
|
|
676
703
|
* layoutChips).
|
|
677
704
|
*/
|
|
678
|
-
export function formatNoSession({ caps = null, model = null, effort = null, windowLabel = '', version = '', update = null, team = null } = {}, { color = true, mode = 'icon', segments = null, columns = 0, maxLines = 3 } = {}) {
|
|
705
|
+
export function formatNoSession({ caps = null, model = null, effort = null, ultra = null, windowLabel = '', version = '', update = null, team = null } = {}, { color = true, mode = 'icon', segments = null, columns = 0, maxLines = 3 } = {}) {
|
|
679
706
|
const c = (v) => (color ? v : '');
|
|
680
707
|
// narrow shares the icon layout and swaps only the glyphs, so both modes take
|
|
681
708
|
// the same branches from here on.
|
|
@@ -696,6 +723,8 @@ export function formatNoSession({ caps = null, model = null, effort = null, wind
|
|
|
696
723
|
if (modelSeg) segs.push(modelSeg);
|
|
697
724
|
const effortSeg = buildEffortSeg(effort, c, isIcon, g);
|
|
698
725
|
if (effortSeg) segs.push(effortSeg);
|
|
726
|
+
const ultraSeg = buildUltraSeg(ultra, c, isIcon, g);
|
|
727
|
+
if (ultraSeg) segs.push(ultraSeg);
|
|
699
728
|
segs.push(`${c(GRAY)}${g.hit} no session data${windowLabel ? ` · ${windowLabel}` : ''}${c(RESET)}`);
|
|
700
729
|
const teamSeg = buildTeamSeg(team, c, mode);
|
|
701
730
|
if (teamSeg) segs.push(teamSeg);
|
|
@@ -1117,6 +1146,15 @@ function buildDelegatedSeg(data, singleLine, c, isIcon, verbose, g) {
|
|
|
1117
1146
|
const delegateSeg = savingsChip || (delegationSaved === 0 ? unresolvedSeg : null);
|
|
1118
1147
|
const delegateExtra = savingsChip && delegationSaved === 0 ? unresolvedSeg : null;
|
|
1119
1148
|
|
|
1149
|
+
// Sonnet delegations the guard ran at high effort because the call passed
|
|
1150
|
+
// none. Gray, since it is a cost and not a saving: the savings beside it are
|
|
1151
|
+
// already net of it, and `sprag saved` prints what the runs cost.
|
|
1152
|
+
// icon: "🔬↑3" | text: "effort↑3" | verbose: "effort raised ×3"
|
|
1153
|
+
const raised = Number(data.effortRaises && data.effortRaises.count) || 0;
|
|
1154
|
+
const raisedSeg = raised > 0
|
|
1155
|
+
? `${c(GRAY)}${verbose ? `effort raised ×${raised}` : isIcon ? `${g.effort}↑${raised}` : `effort↑${raised}`}${c(RESET)}`
|
|
1156
|
+
: null;
|
|
1157
|
+
|
|
1120
1158
|
// Routing-savings headline line (multi-line layout). The lifetime sum from
|
|
1121
1159
|
// the delegation ledger — the number the whole tool exists to grow, so it
|
|
1122
1160
|
// gets line 1 to itself while the diagnostics move to line 2.
|
|
@@ -1165,7 +1203,10 @@ function buildDelegatedSeg(data, singleLine, c, isIcon, verbose, g) {
|
|
|
1165
1203
|
// would otherwise repeat it on line 2. The unresolved-runs chip survives the
|
|
1166
1204
|
// headline when that headline is a dated zero, since a zero is exactly when
|
|
1167
1205
|
// the dropped runs matter.
|
|
1168
|
-
|
|
1206
|
+
// The raise count is not part of that story, so it stays on line 2 either way.
|
|
1207
|
+
chips: totalsLine
|
|
1208
|
+
? (totalsNum === 0 ? [unresolvedSeg, raisedSeg] : [raisedSeg])
|
|
1209
|
+
: [delegateSeg, raisedSeg, delegateExtra],
|
|
1169
1210
|
headline: totalsLine ? { usd: Number(totals && totals.total) || 0, line: totalsLine } : null,
|
|
1170
1211
|
};
|
|
1171
1212
|
}
|
|
@@ -1294,7 +1335,7 @@ export const DEFAULT_SEGMENT_ORDER = [
|
|
|
1294
1335
|
'cap-warn', 'spike',
|
|
1295
1336
|
'usage', 'ctx',
|
|
1296
1337
|
'ttl',
|
|
1297
|
-
'model', 'effort',
|
|
1338
|
+
'model', 'effort', 'ultra',
|
|
1298
1339
|
// Grouped by the timeframe each figure covers, because mixing them was the
|
|
1299
1340
|
// problem: a lifetime total, a windowed rate and a calendar-month estimate sat
|
|
1300
1341
|
// interleaved, with one window label at the end of the line that appeared to
|
|
@@ -1347,6 +1388,7 @@ function segmentsNamed(name, s, usageByKey) {
|
|
|
1347
1388
|
case 'team': return [s.team];
|
|
1348
1389
|
case 'model': return [s.model];
|
|
1349
1390
|
case 'effort': return [s.effort];
|
|
1391
|
+
case 'ultra': return [s.ultra];
|
|
1350
1392
|
// The routing chips (already empty when a headline line owns the story), then
|
|
1351
1393
|
// the session's own subagent runs.
|
|
1352
1394
|
case 'delegated': return [...s.delegated, s.subagents];
|
|
@@ -1461,13 +1503,13 @@ function buildHeadlines(delegated, doc2md, want, eol, columns = 0, c = (v) => v)
|
|
|
1461
1503
|
* @param {boolean} [opts.verbose=false] - longer layout with labels
|
|
1462
1504
|
* @param {boolean} [opts.timer=true] - show TTL countdown segment
|
|
1463
1505
|
* @param {'text'|'icon'} [opts.mode='text'] - label style. 'icon' uses 🧠 ⏳ 💰 instead of word labels.
|
|
1464
|
-
* @param {string[]|null} [opts.segments] - segments to render, in the order given. Names: cap-warn, spike, version, harness (a full score with no warning draws only when named here), korean (draws only when named here), team (member id and office animal; joined machines only), model, effort, hit, ttl, month, saved, delegated, doc2md, share (Model used by family, dated), star, ctx, period, `subagents` (this session's subagent runs; also rides with `delegated`), `rules` (only when named here), `usage` (every rate-limit window), plus per-window keys (`five_hour`, `seven_day`, …). `5h`/`7d` are kept as aliases for back-compat. cap-warn and spike keep the lead regardless of where they appear. Null/undefined = all, in the default order.
|
|
1506
|
+
* @param {string[]|null} [opts.segments] - segments to render, in the order given. Names: cap-warn, spike, version, harness (a full score with no warning draws only when named here), korean (draws only when named here), team (member id and office animal; joined machines only), model, effort, ultra (ultracode on/off; live statusline only), hit, ttl, month, saved, delegated, doc2md, share (Model used by family, dated), star, ctx, period, `subagents` (this session's subagent runs; also rides with `delegated`), `rules` (only when named here), `usage` (every rate-limit window), plus per-window keys (`five_hour`, `seven_day`, …). `5h`/`7d` are kept as aliases for back-compat. cap-warn and spike keep the lead regardless of where they appear. Null/undefined = all, in the default order.
|
|
1465
1507
|
* @param {boolean} [opts.singleLine=false] - force the legacy one-line layout. By default, when the delegation ledger has lifetime savings, the routing totals lead on their own first line and everything else moves to line 2 (Claude Code renders multi-line statuslines; `--single-line` is the escape hatch for terminals that only show the first line). It also ignores `columns`.
|
|
1466
1508
|
* @param {number} [opts.columns=0] - terminal width in cells (Claude Code exports it as COLUMNS). When set, the chips wrap at chip boundaries instead of being truncated by the terminal; 0 keeps one unbounded line. A verbose layout that would need chips dropped is re-rendered once in the compact layout first.
|
|
1467
1509
|
* @param {number} [opts.maxLines=3] - most chip lines when `columns` is set; lower-priority tail chips collapse into a `+N` chip beyond that. Counts the chip lines only: the headline lines above them wrap at their own `|` and `·` joints and are not included. Cap, usage, ctx, spike chips are never dropped.
|
|
1468
1510
|
*/
|
|
1469
1511
|
export function formatReport(data, { color = true, verbose = false, timer = true, mode = 'text', segments = null, singleLine = false, columns = 0, maxLines = 3 } = {}) {
|
|
1470
|
-
const { summary, ttl, cost, options, lastActivity, contextWindow, ctxLive, spikeChip, caps, model, effort, liveModel } = data;
|
|
1512
|
+
const { summary, ttl, cost, options, lastActivity, contextWindow, ctxLive, spikeChip, caps, model, effort, ultra, liveModel } = data;
|
|
1471
1513
|
|
|
1472
1514
|
const c = (v) => (color ? v : '');
|
|
1473
1515
|
// narrow shares the icon layout and swaps only the glyphs, so both modes take
|
|
@@ -1517,6 +1559,8 @@ export function formatReport(data, { color = true, verbose = false, timer = true
|
|
|
1517
1559
|
// differently at `low` and at `max`, and the pair is one glance.
|
|
1518
1560
|
model: buildModelSeg(model, c, isIcon, g),
|
|
1519
1561
|
effort: buildEffortSeg(effort, c, isIcon, g),
|
|
1562
|
+
// Its own chip, not a level: ultracode works at any effort (see buildUltraSeg).
|
|
1563
|
+
ultra: buildUltraSeg(ultra, c, isIcon, g),
|
|
1520
1564
|
delegated: delegated.chips,
|
|
1521
1565
|
// The inline chip steps aside when a headline line owns the story.
|
|
1522
1566
|
doc2md: doc2md.headline ? [] : [doc2md.chip],
|
package/src/glyphs.js
CHANGED
|
@@ -46,6 +46,11 @@ const ICON = {
|
|
|
46
46
|
// cells while being counted as one, and the line shifts on every repaint. 🔬
|
|
47
47
|
// is W, so it measures the same as its neighbours.
|
|
48
48
|
effort: '🔬',
|
|
49
|
+
// Ultracode: many arms working at once, which is what it turns on (every task
|
|
50
|
+
// fans out to parallel subagents). U+1F419, East Asian Width W like the rest
|
|
51
|
+
// of this set. 🎼 (orchestration) was the first pick but did not read as
|
|
52
|
+
// parallel at a glance.
|
|
53
|
+
ultra: '🐙',
|
|
49
54
|
routing: '🔀',
|
|
50
55
|
doc: '📄',
|
|
51
56
|
hit: '🧠',
|
|
@@ -76,6 +81,7 @@ const NARROW = {
|
|
|
76
81
|
korean: '⌨', // an input/typing convention rather than a hand
|
|
77
82
|
model: '◈',
|
|
78
83
|
effort: '▲', // a magnitude: how hard the turn is being worked
|
|
84
|
+
ultra: '◕', // a nearly full dial; shared with the unknown-window icon, the only ◕ in the line
|
|
79
85
|
routing: '⇉', // sent down a different path
|
|
80
86
|
doc: '≣', // stacked lines: a page of text
|
|
81
87
|
hit: '◉', // bullseye: a cache hit
|
package/src/model-rules.js
CHANGED
|
@@ -305,6 +305,15 @@ export function renderModelRatchet(rules, lang = userLanguage(), { root } = {})
|
|
|
305
305
|
' 절감이 발생하지 않기 때문입니다.',
|
|
306
306
|
'- 설계 판단이나 되돌릴 수 없는 작업(배포·릴리스·머지·제출)이 섞여 있으면',
|
|
307
307
|
' 위임하지 않습니다.',
|
|
308
|
+
'- 웹에서 뉴스나 대안, 후보를 찾는 열린 조사는 위임하지 않습니다. 하위 모델이',
|
|
309
|
+
' 몇 번 검색하고 멈춰도 무엇을 빠뜨렸는지 드러나지 않기 때문입니다. 조사를',
|
|
310
|
+
' 위임한 결과를 전달할 때는 어디까지 찾았는지 먼저 확인합니다. 사용자가 그래도',
|
|
311
|
+
' 위임을 원하면 sonnet에 effort xhigh로 보냅니다(실측: 최근 뉴스 조사에서 medium과',
|
|
312
|
+
' high는 6회 중 한 번도 핵심 소식을 찾지 못했고 xhigh는 3회 모두 찾았으며 비용은',
|
|
313
|
+
' Opus의 약 80%였습니다).',
|
|
314
|
+
'- 사용자만 아는 맥락(이미 반려된 후보, 앞서 정한 조건)은 위임 지시문에 적습니다.',
|
|
315
|
+
' 서브에이전트는 그 맥락을 볼 수 없어서 effort를 올려도 찾지 못합니다(실측: effort를',
|
|
316
|
+
' 바꿔 9회 돌렸고 9회 모두 반려된 후보를 다시 추천했습니다).',
|
|
308
317
|
'',
|
|
309
318
|
'## 티어 판별 기준 (모든 룰에 공통 적용)',
|
|
310
319
|
'',
|
|
@@ -324,6 +333,9 @@ export function renderModelRatchet(rules, lang = userLanguage(), { root } = {})
|
|
|
324
333
|
' 구현하는 위임(sonnet 워커)과 범위가 큰 구현·디버깅 위임(opus 워커)은 high다.',
|
|
325
334
|
' 두 워커는 effort가 아니라 모델 티어로 나뉜다. 메인 세션의 effort는 바꾸지 않고,',
|
|
326
335
|
' CLAUDE_CODE_EFFORT_LEVEL은 서브에이전트의 effort를 덮어쓰므로 설정하지 않는다.',
|
|
336
|
+
' 여러 파일을 뒤져야 답이 나오는 조회는 effort high 이상에서 맡긴다. t1-worker는',
|
|
337
|
+
' 이미 high이고, general-purpose로 보낼 때는 Agent 호출의 effort 인자에 high를',
|
|
338
|
+
' 넘긴다(실측: medium은 3회 모두 일부를 놓쳤고 high는 3회 중 2회 모두 찾았다).',
|
|
327
339
|
'- **고난도 구현(T1H)**: 설계는 메인이 확정하고, 범위가 크거나 sonnet 이 틀린',
|
|
328
340
|
' 적 있는 구현·디버깅은 opus 에 위임한다. Fable·Mythos 세션에서만 적용되며,',
|
|
329
341
|
' 설계 판단과 되돌릴 수 없는 작업은 메인 모델에 남긴다.',
|
|
@@ -373,6 +385,16 @@ export function renderModelRatchet(rules, lang = userLanguage(), { root } = {})
|
|
|
373
385
|
' tier: there is nothing to save.',
|
|
374
386
|
'- Skip it when the request mixes in design judgement or irreversible work',
|
|
375
387
|
' (deploy, release, merge, submission).',
|
|
388
|
+
'- Do not delegate open research on the web (news, alternatives, candidates):',
|
|
389
|
+
' a cheaper model stops after a few searches and nothing shows what it missed.',
|
|
390
|
+
' Before relaying any delegated research, check how far it actually searched.',
|
|
391
|
+
' If the user still wants it delegated, send it to sonnet at effort xhigh',
|
|
392
|
+
' (measured: on a recent-news search, medium and high found the key story in',
|
|
393
|
+
' 0 of 6 runs, xhigh in 3 of 3, at about 80% of the Opus cost).',
|
|
394
|
+
'- Write context only the user knows (candidates already rejected, conditions',
|
|
395
|
+
' settled earlier) into the delegation prompt. The subagent cannot see it, and',
|
|
396
|
+
' no effort level makes up for that (measured: 9 runs across efforts, all 9',
|
|
397
|
+
' recommended the rejected candidate again).',
|
|
376
398
|
'',
|
|
377
399
|
'## Tier criteria (apply to every rule below)',
|
|
378
400
|
'',
|
|
@@ -395,6 +417,10 @@ export function renderModelRatchet(rules, lang = userLanguage(), { root } = {})
|
|
|
395
417
|
' sonnet worker) and for large implementation or debugging (the opus',
|
|
396
418
|
' worker); the tier, not the effort, separates the two workers. Leave the main session\'s effort alone, and never set',
|
|
397
419
|
' CLAUDE_CODE_EFFORT_LEVEL: it overrides every subagent\'s own value.',
|
|
420
|
+
' A lookup that has to search across many files runs at effort high or',
|
|
421
|
+
' above. t1-worker already is; through general-purpose, pass high in the',
|
|
422
|
+
' Agent call\'s effort argument (measured: medium missed part of the answer',
|
|
423
|
+
' in 3 of 3 runs, high found all of it in 2 of 3).',
|
|
398
424
|
'- **Heavy implementation (T1H)**: the main model fixes the design; large-scope',
|
|
399
425
|
' implementation or debugging, or work sonnet has already got wrong, goes to',
|
|
400
426
|
' opus. Applies in Fable/Mythos sessions only; design judgement and',
|
package/src/route-inject.js
CHANGED
|
@@ -64,6 +64,11 @@ export function looksPasted(text) {
|
|
|
64
64
|
const SYSTEM_PROMPT_PREFIXES = [
|
|
65
65
|
'<task-notification>', '<system-reminder>', '<command-name>', '<command-message>', '<command-args>',
|
|
66
66
|
'<local-command-', '<bash-input>', '<bash-stdout>', '<bash-stderr>', '[Request interrupted',
|
|
67
|
+
// A background subagent's report and the summary that opens a compacted
|
|
68
|
+
// session arrive as user turns too. A hint there told the main model to
|
|
69
|
+
// delegate the checking of a subagent's own result (#16 follow-up).
|
|
70
|
+
'Another Claude session sent a message', '<agent-message', '[SYSTEM NOTIFICATION',
|
|
71
|
+
'This session is being continued from a previous conversation',
|
|
67
72
|
];
|
|
68
73
|
|
|
69
74
|
/** True for a message the harness wrote rather than the user (see SYSTEM_PROMPT_PREFIXES). */
|
|
@@ -107,6 +112,16 @@ const SELF_CHECK_RE = /확인(?:할게|해\s*볼게|하겠|해볼께|할께)|확
|
|
|
107
112
|
* deleting, paying. A plain `git push` stays with the run category, as before.
|
|
108
113
|
*/
|
|
109
114
|
const OUTWARD_RE = /업로드|게시해|게시하|발송|올려\s*(?:줘|주|줄)|보내\s*(?:줘|주|줄)|삭제|지워\s*(?:줘|주)|결제/;
|
|
115
|
+
/**
|
|
116
|
+
* Open research on the web: news, communities, alternatives, candidates,
|
|
117
|
+
* trends. A cheaper model stops after a few searches and nothing shows what it
|
|
118
|
+
* missed. In the #16 follow-up review, two of the three hinted delegations
|
|
119
|
+
* that lost quality without anyone noticing were of this kind (a news roundup
|
|
120
|
+
* that missed the week's main story, an asset search that never opened the
|
|
121
|
+
* main marketplace), and neither prompt tripped any other gate.
|
|
122
|
+
*/
|
|
123
|
+
const OPEN_RESEARCH_RE = /인터넷|웹\s*(?:에서|으로|검색)|뉴스|소식|레딧|reddit|해커뉴스|hacker\s*news|오픈\s*소스|대안|후보|사례|트렌드|동향/i;
|
|
124
|
+
|
|
110
125
|
/** Edit asks EDIT_RE misses: change, remove, set up, add, polish, generate. */
|
|
111
126
|
const EDIT_MORE_RE = /변경해|변경하|바꾸고|없애|빼\s*(?:줘|주|고|자)|[셋세]팅하자|설정하자|구성해|구성하|추가해|다듬|넣고|처리해\s*(?:줘|주)|만들어\s*(?:줘|주|봐)|생성해|적용해|적용하자/;
|
|
112
127
|
/**
|
|
@@ -120,7 +135,8 @@ const SPEC_LEN = 100;
|
|
|
120
135
|
export function looksLikeContextOrSpec(text) {
|
|
121
136
|
const t = String(text || '').trim();
|
|
122
137
|
return CONTINUATION_RE.test(t) || FEEDBACK_RE.test(t) || SELF_CHECK_RE.test(t)
|
|
123
|
-
|| OUTWARD_RE.test(t) || EDIT_MORE_RE.test(t) ||
|
|
138
|
+
|| OUTWARD_RE.test(t) || EDIT_MORE_RE.test(t) || OPEN_RESEARCH_RE.test(t)
|
|
139
|
+
|| (t.length > SPEC_LEN && !looksPasted(t));
|
|
124
140
|
}
|
|
125
141
|
|
|
126
142
|
/**
|
package/src/route-scan.js
CHANGED
|
@@ -724,6 +724,12 @@ export async function runRouteScan({ days = 14, trace = null } = {}) {
|
|
|
724
724
|
const delegatedStats = new Map(); // "tier|category|project" → outcome aggregate
|
|
725
725
|
let unresolvedRuns = 0; // delegated runs dropped for an unpriceable model id
|
|
726
726
|
const unresolvedModels = new Set();
|
|
727
|
+
// Sonnet delegations the guard ran at high effort because the call passed
|
|
728
|
+
// none (src/delegation-guard.js). Counted whether or not a rule covers the
|
|
729
|
+
// run: the raise is sprag's own action, so its price is shown even where no
|
|
730
|
+
// saving is claimed. The figure is what those runs cost on their own model,
|
|
731
|
+
// priced the way the ledger prices `cost`; the savings already include it.
|
|
732
|
+
const effortRaises = { count: 0, cost: 0, since: null };
|
|
727
733
|
// `sprag saved reset routing` zeroes the money, not the rule-health sample:
|
|
728
734
|
// see tallyDelegatedRun. readResetMarks never throws (no file = no reset).
|
|
729
735
|
const routingMark = readResetMarks(userDataDir()).routing;
|
|
@@ -765,6 +771,18 @@ export async function runRouteScan({ days = 14, trace = null } = {}) {
|
|
|
765
771
|
// registry credit a run to the same rule.
|
|
766
772
|
const ruleForRun = (tier, catId, projectDir) => ruleForProject(ledgerRules, tier, catId, projectDir);
|
|
767
773
|
for (const [sessionPath, index] of runIndexBySession) {
|
|
774
|
+
// Every run of the session, not only those joined to a categorized episode
|
|
775
|
+
// and past the tier gate: a sonnet run under a sonnet main session saves
|
|
776
|
+
// nothing, yet the guard raised it all the same. The reset mark applies as
|
|
777
|
+
// it does to savings (tallyDelegatedRun).
|
|
778
|
+
for (const run of index.all) {
|
|
779
|
+
if (!run.effortRaised || isBeforeReset(run.endedAt ?? run.startedAt, routingMark)) continue;
|
|
780
|
+
effortRaises.count += 1;
|
|
781
|
+
const cost = isRecognizedModelId(run.model) ? exactCost(runTotals(run), run.model, { at: runTime(run) }) : null;
|
|
782
|
+
if (Number.isFinite(cost)) effortRaises.cost += cost;
|
|
783
|
+
const at = run.startedAt ?? run.endedAt;
|
|
784
|
+
if (Number.isFinite(at) && (effortRaises.since === null || at < effortRaises.since)) effortRaises.since = at;
|
|
785
|
+
}
|
|
768
786
|
const used = new Set();
|
|
769
787
|
const eps = all.filter((x) => x.sessionPath === sessionPath);
|
|
770
788
|
// Two passes over the session, not one per episode: every exact tool_use
|
|
@@ -909,6 +927,8 @@ export async function runRouteScan({ days = 14, trace = null } = {}) {
|
|
|
909
927
|
resolved: [...resolved],
|
|
910
928
|
unresolvedRuns,
|
|
911
929
|
unresolvedModels: [...unresolvedModels].slice(0, 5),
|
|
930
|
+
// `since` is the earliest counted run (ms), so a reader can date the count.
|
|
931
|
+
effortRaises: { ...effortRaises, cost: Math.round(effortRaises.cost * 100) / 100 },
|
|
912
932
|
};
|
|
913
933
|
try {
|
|
914
934
|
const dir = stateDir();
|
package/src/stdin-payload.js
CHANGED
|
@@ -221,7 +221,7 @@ export function extractEffort(stdinJson) {
|
|
|
221
221
|
/**
|
|
222
222
|
* The current session's transcript path, as Claude Code reports it.
|
|
223
223
|
*
|
|
224
|
-
* Read for one thing only: the
|
|
224
|
+
* Read for one thing only: the ultra chip's ultracode check, which the payload
|
|
225
225
|
* cannot answer on its own (see src/ultracode.js). Everything else about the
|
|
226
226
|
* current session comes from the analysis window, so a missing or non-string
|
|
227
227
|
* path is not worth a fallback — the caller simply skips the check.
|
package/src/subagent-records.js
CHANGED
|
@@ -31,6 +31,8 @@ import { readdir, readFile, stat } from 'node:fs/promises';
|
|
|
31
31
|
import { join, dirname, basename } from 'node:path';
|
|
32
32
|
import { collectSessionRecords, normalizeModelId } from './session-records.js';
|
|
33
33
|
import { LONG_PROMPT_THRESHOLD } from './cost.js';
|
|
34
|
+
import { transcriptLines } from './transcript-lines.js';
|
|
35
|
+
import { EFFORT_RAISE_MARKER } from './delegation-guard.js';
|
|
34
36
|
|
|
35
37
|
/** Directory holding a session's subagent transcripts (may not exist). */
|
|
36
38
|
export function subagentDirFor(sessionPath) {
|
|
@@ -45,6 +47,44 @@ async function readMeta(metaPath) {
|
|
|
45
47
|
}
|
|
46
48
|
}
|
|
47
49
|
|
|
50
|
+
function messageText(content) {
|
|
51
|
+
if (typeof content === 'string') return content;
|
|
52
|
+
if (!Array.isArray(content)) return '';
|
|
53
|
+
return content.map((b) => (b && b.type === 'text' && typeof b.text === 'string' ? b.text : '')).join('\n');
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* What the run was told about its effort: whether the delegation guard raised
|
|
58
|
+
* it (the marker line it appends to the prompt), and the level the transcript
|
|
59
|
+
* records on its entries.
|
|
60
|
+
*
|
|
61
|
+
* collectSessionRecords runs with content off for subagent transcripts, since
|
|
62
|
+
* the text of every turn is never needed here, so the prompt is read on its own.
|
|
63
|
+
* Only the head of the file is: the prompt is the first user entry and the first
|
|
64
|
+
* assistant entry carries the effort, so the read stops after a few lines. A
|
|
65
|
+
* transcript that records no effort at all is read to the end, and the
|
|
66
|
+
* substring test keeps those lines from being parsed.
|
|
67
|
+
*/
|
|
68
|
+
async function readRunEffort(jsonlPath) {
|
|
69
|
+
let raised = null;
|
|
70
|
+
let effort = null;
|
|
71
|
+
try {
|
|
72
|
+
for await (const line of transcriptLines(jsonlPath)) {
|
|
73
|
+
const wantsPrompt = raised === null && line.includes('"type":"user"');
|
|
74
|
+
const wantsEffort = effort === null && line.includes('"effort"');
|
|
75
|
+
if (!wantsPrompt && !wantsEffort) continue;
|
|
76
|
+
let entry;
|
|
77
|
+
try { entry = JSON.parse(line); } catch { continue; }
|
|
78
|
+
if (effort === null && typeof entry.effort === 'string' && entry.effort) effort = entry.effort;
|
|
79
|
+
if (raised === null && entry.type === 'user' && entry.message) {
|
|
80
|
+
raised = messageText(entry.message.content).includes(EFFORT_RAISE_MARKER);
|
|
81
|
+
}
|
|
82
|
+
if (raised !== null && effort !== null) break;
|
|
83
|
+
}
|
|
84
|
+
} catch { /* unreadable here means unreadable above too; report no raise */ }
|
|
85
|
+
return { effortRaised: raised === true, effort };
|
|
86
|
+
}
|
|
87
|
+
|
|
48
88
|
/**
|
|
49
89
|
* A run's model when several appear in one transcript (a harness retry can
|
|
50
90
|
* switch tiers mid-run): the one that produced the most output, since that is
|
|
@@ -139,6 +179,9 @@ export async function collectSubagentRun(jsonlPath) {
|
|
|
139
179
|
run.toolUseId = meta.toolUseId ?? null;
|
|
140
180
|
run.spawnDepth = meta.spawnDepth ?? null;
|
|
141
181
|
}
|
|
182
|
+
// A raise is sprag's own doing, so route-scan counts these runs and their
|
|
183
|
+
// cost apart from any rule (see effortRaises there).
|
|
184
|
+
Object.assign(run, await readRunEffort(jsonlPath));
|
|
142
185
|
try {
|
|
143
186
|
run.bytes = (await stat(jsonlPath)).size;
|
|
144
187
|
} catch { /* size only feeds the rescan gate — 0 is a safe under-estimate */ }
|
package/src/ultracode.js
CHANGED
|
@@ -1,18 +1,17 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Ultracode detection — the one
|
|
2
|
+
* Ultracode detection — the one session state Claude Code does not put in the
|
|
3
3
|
* statusline payload.
|
|
4
4
|
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
* session on ultracode and a session on plain xhigh arrive here identical.
|
|
5
|
+
* Since 2.1.302 ultracode is not an effort level. It is an independent toggle,
|
|
6
|
+
* "dynamic workflows on every task", that can be on at any level, and the
|
|
7
|
+
* payload still carries only `effort.level`; there is no ultracode field. (The
|
|
8
|
+
* older builds raised the level to `xhigh` and reported that, so the two
|
|
9
|
+
* arrived identical. The new ones leave the level alone, so there is nothing in
|
|
10
|
+
* the payload to recover it from at all.)
|
|
12
11
|
*
|
|
13
|
-
* What does
|
|
14
|
-
*
|
|
15
|
-
*
|
|
12
|
+
* What does carry it is the transcript. Claude Code injects a system-reminder
|
|
13
|
+
* when ultracode turns on and another when it turns off, and both are recorded
|
|
14
|
+
* as attachment entries:
|
|
16
15
|
*
|
|
17
16
|
* {"type":"attachment","attachment":{"type":"ultra_effort_enter","reminderType":"full"}}
|
|
18
17
|
* {"type":"attachment","attachment":{"type":"ultra_effort_exit"}}
|
|
@@ -21,29 +20,40 @@
|
|
|
21
20
|
* is switched on ("full"), then every tenth user turn as a reminder ("sparse",
|
|
22
21
|
* TURNS_BETWEEN_MAINTENANCE = 10) — so the most recent of the two markers is
|
|
23
22
|
* the current state, and an active session keeps refreshing it near the tail.
|
|
23
|
+
* (A keyword in the prompt can switch it on for one turn only; that writes a
|
|
24
|
+
* different attachment and is deliberately not a session state here.)
|
|
24
25
|
*
|
|
25
26
|
* A marker is only written when the NEXT turn is assembled, though, so on its own
|
|
26
|
-
* it leaves the chip a turn behind
|
|
27
|
-
*
|
|
28
|
-
*
|
|
29
|
-
*
|
|
30
|
-
*
|
|
31
|
-
*
|
|
32
|
-
*
|
|
33
|
-
*
|
|
34
|
-
*
|
|
35
|
-
*
|
|
36
|
-
*
|
|
37
|
-
*
|
|
38
|
-
*
|
|
27
|
+
* it leaves the chip a turn behind. The command's own output closes that gap,
|
|
28
|
+
* because Claude Code writes it to the transcript the moment the command returns:
|
|
29
|
+
*
|
|
30
|
+
* {"type":"user","message":{"content":"<local-command-stdout>Ultracode on (this
|
|
31
|
+
* session only): dynamic workflows on every task. Effort stays high.</local-command-stdout>"}}
|
|
32
|
+
*
|
|
33
|
+
* The strings below are the ones the 2.1.302 binary builds in its `k()` function:
|
|
34
|
+
*
|
|
35
|
+
* on Ultracode on (this session only): dynamic workflows on every task. Effort stays high.
|
|
36
|
+
* off Ultracode off. Effort stays high.
|
|
37
|
+
* query Current effort level: high (…) or Effort level: auto (currently high),
|
|
38
|
+
* with ` · Ultracode on` appended while it is on; no suffix means off.
|
|
39
|
+
* level Set effort level to high: … — changes only the level, so it says nothing
|
|
40
|
+
* about ultracode locally. A remote session appends ` · Ultracode off`
|
|
41
|
+
* (U+00B7) when the level change switched it off, and `Effort level set
|
|
42
|
+
* to auto…` can carry the same suffix.
|
|
43
|
+
*
|
|
44
|
+
* Builds before 2.1.302 phrase it as a level instead: `Set effort level to
|
|
45
|
+
* ultracode …` and `Current effort level: ultracode (…)` turn it on. Their
|
|
46
|
+
* `Set effort level to <level>` rows used to mean "off", but that is no longer
|
|
47
|
+
* true of the new builds and the two cannot be told apart, so those rows decide
|
|
48
|
+
* nothing; the old builds' next-turn exit attachment clears the state, which
|
|
49
|
+
* costs one turn of lag.
|
|
39
50
|
*
|
|
40
51
|
* Hence the read below: walk backwards from the end of the transcript and take
|
|
41
52
|
* whichever of the two signals comes last. The scan is capped (see SCAN_BYTES)
|
|
42
53
|
* because the statusline re-renders every few seconds and most sessions carry
|
|
43
54
|
* neither signal — an uncapped backwards scan would read the whole transcript,
|
|
44
55
|
* every render, to answer "no". The cap makes the failure one-directional: past
|
|
45
|
-
* it we report "
|
|
46
|
-
* existed.
|
|
56
|
+
* it we report "off", which is what the line showed before this existed.
|
|
47
57
|
*/
|
|
48
58
|
|
|
49
59
|
import { openSync, readSync, closeSync, statSync } from 'node:fs';
|
|
@@ -57,16 +67,21 @@ import { openSync, readSync, closeSync, statSync } from 'node:fs';
|
|
|
57
67
|
*/
|
|
58
68
|
const SCAN_BYTES = 4 * 1024 * 1024;
|
|
59
69
|
/**
|
|
60
|
-
* Substrings worth parsing a line for. The first is the attachment; the
|
|
61
|
-
*
|
|
62
|
-
* parsed and checked before it counts.
|
|
70
|
+
* Substrings worth parsing a line for. The first is the attachment; the rest are
|
|
71
|
+
* the shapes the toggle and the `/effort` query print. Cheap prefilters only —
|
|
72
|
+
* every hit is parsed and checked before it counts. A `Set effort level to` /
|
|
73
|
+
* `Effort level set to` row matters only when it carries the ` · Ultracode off`
|
|
74
|
+
* suffix, which the `Ultracode off` entry already catches.
|
|
63
75
|
*/
|
|
64
|
-
const MARKERS = [
|
|
76
|
+
const MARKERS = [
|
|
77
|
+
'ultra_effort_', 'Ultracode on (', 'Ultracode off', 'Effort level: auto', 'Current effort level:',
|
|
78
|
+
'Set effort level to ultracode',
|
|
79
|
+
];
|
|
65
80
|
const NEWLINE = 0x0a;
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
const
|
|
81
|
+
const COMMAND_STDOUT = /<local-command-stdout>([\s\S]*?)<\/local-command-stdout>/;
|
|
82
|
+
/** A query answer or level change that ends in the ultracode suffix. */
|
|
83
|
+
const SUFFIX_ON = /\s·\sUltracode on\s*$/;
|
|
84
|
+
const SUFFIX_OFF = /\s·\sUltracode off\s*$/;
|
|
70
85
|
|
|
71
86
|
/**
|
|
72
87
|
* The state one transcript line carries, or null when it carries none.
|
|
@@ -95,49 +110,50 @@ function markerState(line) {
|
|
|
95
110
|
}
|
|
96
111
|
|
|
97
112
|
/**
|
|
98
|
-
* The state one
|
|
99
|
-
*
|
|
113
|
+
* The state one command output reports, or null when the entry is not one or
|
|
114
|
+
* says nothing about ultracode.
|
|
100
115
|
*
|
|
101
116
|
* The filter is narrow on purpose, because these phrases travel. In the session
|
|
102
|
-
*
|
|
103
|
-
* command output: three times in assistant text that quoted it and
|
|
104
|
-
* results that printed it. Requiring a user entry whose content is a
|
|
105
|
-
* string carrying the `<local-command-stdout>` wrapper excluded all six and
|
|
106
|
-
* all twelve real ones — a tool result's content is an array of blocks, and
|
|
117
|
+
* the first version was built in, "Set effort level to …" appears six times
|
|
118
|
+
* outside a real command output: three times in assistant text that quoted it and
|
|
119
|
+
* three in tool results that printed it. Requiring a user entry whose content is a
|
|
120
|
+
* plain string carrying the `<local-command-stdout>` wrapper excluded all six and
|
|
121
|
+
* kept all twelve real ones — a tool result's content is an array of blocks, and
|
|
107
122
|
* quoted prose is not a user entry at all.
|
|
108
123
|
*
|
|
109
124
|
* A cancelled picker writes `<local-command-stdout>Cancelled</local-command-stdout>`,
|
|
110
|
-
* which matches nothing here and correctly changes no state
|
|
125
|
+
* which matches nothing here and correctly changes no state, and so does a plain
|
|
126
|
+
* `Set effort level to high: …` row.
|
|
111
127
|
*/
|
|
112
128
|
function commandState(entry) {
|
|
113
129
|
if (entry.type !== 'user') return null;
|
|
114
130
|
const content = entry.message && entry.message.content;
|
|
115
131
|
if (typeof content !== 'string' || !content.includes('<local-command-stdout>')) return null;
|
|
116
|
-
|
|
117
|
-
const
|
|
118
|
-
if (
|
|
119
|
-
if (
|
|
132
|
+
const wrapped = content.match(COMMAND_STDOUT);
|
|
133
|
+
const text = (wrapped ? wrapped[1] : content).trim();
|
|
134
|
+
if (text.startsWith('Ultracode on (')) return true;
|
|
135
|
+
if (text.startsWith('Ultracode off')) return false;
|
|
136
|
+
// Before 2.1.302 ultracode was a level, and naming it meant on.
|
|
137
|
+
if (/^Set effort level to ultracode\b/.test(text)) return true;
|
|
138
|
+
if (/^Current effort level: ultracode\b/.test(text)) return true;
|
|
139
|
+
// The query answers in both directions: the suffix is present only while on.
|
|
140
|
+
if (/^(?:Current effort level:|Effort level: auto)/.test(text)) return SUFFIX_ON.test(text);
|
|
141
|
+
// A level change leaves ultracode alone locally; only the remote suffix says off.
|
|
142
|
+
if (/^(?:Set effort level to|Effort level set to)\b/.test(text)) return SUFFIX_OFF.test(text) ? false : null;
|
|
120
143
|
return null;
|
|
121
144
|
}
|
|
122
145
|
|
|
123
|
-
/**
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
* @returns {boolean|null} true/false from the newest marker, null when there is
|
|
130
|
-
* none in range or the file cannot be read. Callers treat null as "not
|
|
131
|
-
* ultracode"; it is kept distinct from false so a caller can tell "the
|
|
132
|
-
* session turned it off" from "nothing said".
|
|
133
|
-
*/
|
|
134
|
-
export function ultracodeFromTranscript(transcriptPath, { scanBytes = SCAN_BYTES } = {}) {
|
|
135
|
-
if (typeof transcriptPath !== 'string' || transcriptPath === '') return null;
|
|
146
|
+
/** Returned by readState when the transcript cannot be read at all. */
|
|
147
|
+
const UNREADABLE = Symbol('unreadable');
|
|
148
|
+
|
|
149
|
+
/** The newest marker in the trailing window: true/false, null for none, UNREADABLE for no file. */
|
|
150
|
+
function readState(transcriptPath, scanBytes) {
|
|
151
|
+
if (typeof transcriptPath !== 'string' || transcriptPath === '') return UNREADABLE;
|
|
136
152
|
let size;
|
|
137
153
|
try {
|
|
138
154
|
size = statSync(transcriptPath).size;
|
|
139
155
|
} catch {
|
|
140
|
-
return
|
|
156
|
+
return UNREADABLE;
|
|
141
157
|
}
|
|
142
158
|
if (size === 0) return null;
|
|
143
159
|
|
|
@@ -148,7 +164,7 @@ export function ultracodeFromTranscript(transcriptPath, { scanBytes = SCAN_BYTES
|
|
|
148
164
|
fd = openSync(transcriptPath, 'r');
|
|
149
165
|
readSync(fd, buf, 0, buf.length, start);
|
|
150
166
|
} catch {
|
|
151
|
-
return
|
|
167
|
+
return UNREADABLE;
|
|
152
168
|
} finally {
|
|
153
169
|
if (fd !== undefined) try { closeSync(fd); } catch { /* already closed */ }
|
|
154
170
|
}
|
|
@@ -180,23 +196,35 @@ export function ultracodeFromTranscript(transcriptPath, { scanBytes = SCAN_BYTES
|
|
|
180
196
|
}
|
|
181
197
|
|
|
182
198
|
/**
|
|
183
|
-
*
|
|
199
|
+
* Is ultracode on, according to this transcript?
|
|
184
200
|
*
|
|
185
|
-
*
|
|
186
|
-
*
|
|
187
|
-
*
|
|
201
|
+
* @param {string|null|undefined} transcriptPath - `transcript_path` from the statusline payload.
|
|
202
|
+
* @param {object} [opts]
|
|
203
|
+
* @param {number} [opts.scanBytes=SCAN_BYTES] - how many trailing bytes to search.
|
|
204
|
+
* @returns {boolean|null} true/false from the newest marker, null when there is
|
|
205
|
+
* none in range or the file cannot be read. It is kept distinct from false so a
|
|
206
|
+
* caller can tell "the session turned it off" from "nothing said".
|
|
207
|
+
*/
|
|
208
|
+
export function ultracodeFromTranscript(transcriptPath, { scanBytes = SCAN_BYTES } = {}) {
|
|
209
|
+
const state = readState(transcriptPath, scanBytes);
|
|
210
|
+
return state === UNREADABLE ? null : state;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/**
|
|
214
|
+
* The state the ultra chip should show.
|
|
188
215
|
*
|
|
189
|
-
*
|
|
190
|
-
*
|
|
191
|
-
*
|
|
192
|
-
*
|
|
193
|
-
*
|
|
216
|
+
* Unlike the level it replaced, ultracode no longer rides on any effort level, so
|
|
217
|
+
* there is no payload value to gate the read on and no stale-marker guard to
|
|
218
|
+
* apply: the transcript is the only source and the newest marker is the answer.
|
|
219
|
+
* The caller still decides whether to ask at all (a live statusline render that
|
|
220
|
+
* was handed a transcript path), which keeps every other caller at zero I/O.
|
|
194
221
|
*
|
|
195
|
-
* @param {string|null} level - the level from the payload (see extractEffort).
|
|
196
222
|
* @param {string|null|undefined} transcriptPath
|
|
197
|
-
* @returns {
|
|
223
|
+
* @returns {boolean|null} true while on; false when off or when nothing in range
|
|
224
|
+
* says otherwise; null when there is no readable transcript.
|
|
198
225
|
*/
|
|
199
|
-
export function
|
|
200
|
-
|
|
201
|
-
|
|
226
|
+
export function ultracodeChipState(transcriptPath) {
|
|
227
|
+
const state = readState(transcriptPath, SCAN_BYTES);
|
|
228
|
+
if (state === UNREADABLE) return null;
|
|
229
|
+
return state === true;
|
|
202
230
|
}
|