sprag-cli 3.101.1 → 3.102.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/bin/cli.js CHANGED
@@ -42,7 +42,7 @@ import {
42
42
  extractTranscriptPath,
43
43
  } from '../src/stdin-payload.js';
44
44
 
45
- import { effortChipLevel } from '../src/ultracode.js';
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 chip does
704
- // not change its mind about the level when the analysis window empties.
705
- const effort = effortChipLevel(extractEffort(stdinJson), extractTranscriptPath(stdinJson));
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
- // `ultracode` is the one level the payload cannot name — Claude Code raises it
777
- // to xhigh and reports that — so the transcript settles which of the two this
778
- // session is on. Only an xhigh payload can resolve to ultracode, so a session
779
- // on any other level pays nothing for the check (see src/ultracode.js).
780
- const effort = isStatusline
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).
@@ -1076,6 +1085,7 @@ async function main() {
1076
1085
  // Raw payload model id for the compact-window chip's `modelSettings` lookup.
1077
1086
  liveModel: isStatusline ? liveModelIdOf(stdinJson) : undefined,
1078
1087
  effort,
1088
+ ultra,
1079
1089
  delegationSaved,
1080
1090
  delegationTotals,
1081
1091
  doc2mdTotals,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sprag-cli",
3
- "version": "3.101.1",
3
+ "version": "3.102.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": {
@@ -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 `ultracode` share a color once the shimmer that
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), or `ultracode` when the entry point
302
- * resolved that from the transcript (see effortChipLevel).
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);
@@ -1294,7 +1323,7 @@ export const DEFAULT_SEGMENT_ORDER = [
1294
1323
  'cap-warn', 'spike',
1295
1324
  'usage', 'ctx',
1296
1325
  'ttl',
1297
- 'model', 'effort',
1326
+ 'model', 'effort', 'ultra',
1298
1327
  // Grouped by the timeframe each figure covers, because mixing them was the
1299
1328
  // problem: a lifetime total, a windowed rate and a calendar-month estimate sat
1300
1329
  // interleaved, with one window label at the end of the line that appeared to
@@ -1347,6 +1376,7 @@ function segmentsNamed(name, s, usageByKey) {
1347
1376
  case 'team': return [s.team];
1348
1377
  case 'model': return [s.model];
1349
1378
  case 'effort': return [s.effort];
1379
+ case 'ultra': return [s.ultra];
1350
1380
  // The routing chips (already empty when a headline line owns the story), then
1351
1381
  // the session's own subagent runs.
1352
1382
  case 'delegated': return [...s.delegated, s.subagents];
@@ -1461,13 +1491,13 @@ function buildHeadlines(delegated, doc2md, want, eol, columns = 0, c = (v) => v)
1461
1491
  * @param {boolean} [opts.verbose=false] - longer layout with labels
1462
1492
  * @param {boolean} [opts.timer=true] - show TTL countdown segment
1463
1493
  * @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.
1494
+ * @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
1495
  * @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
1496
  * @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
1497
  * @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
1498
  */
1469
1499
  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;
1500
+ const { summary, ttl, cost, options, lastActivity, contextWindow, ctxLive, spikeChip, caps, model, effort, ultra, liveModel } = data;
1471
1501
 
1472
1502
  const c = (v) => (color ? v : '');
1473
1503
  // narrow shares the icon layout and swaps only the glyphs, so both modes take
@@ -1517,6 +1547,8 @@ export function formatReport(data, { color = true, verbose = false, timer = true
1517
1547
  // differently at `low` and at `max`, and the pair is one glance.
1518
1548
  model: buildModelSeg(model, c, isIcon, g),
1519
1549
  effort: buildEffortSeg(effort, c, isIcon, g),
1550
+ // Its own chip, not a level: ultracode works at any effort (see buildUltraSeg).
1551
+ ultra: buildUltraSeg(ultra, c, isIcon, g),
1520
1552
  delegated: delegated.chips,
1521
1553
  // The inline chip steps aside when a headline line owns the story.
1522
1554
  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
@@ -305,6 +305,9 @@ export function renderModelRatchet(rules, lang = userLanguage(), { root } = {})
305
305
  ' 절감이 발생하지 않기 때문입니다.',
306
306
  '- 설계 판단이나 되돌릴 수 없는 작업(배포·릴리스·머지·제출)이 섞여 있으면',
307
307
  ' 위임하지 않습니다.',
308
+ '- 웹에서 뉴스나 대안, 후보를 찾는 열린 조사는 위임하지 않습니다. 하위 모델이',
309
+ ' 몇 번 검색하고 멈춰도 무엇을 빠뜨렸는지 드러나지 않기 때문입니다. 조사를',
310
+ ' 위임한 결과를 전달할 때는 어디까지 찾았는지 먼저 확인합니다.',
308
311
  '',
309
312
  '## 티어 판별 기준 (모든 룰에 공통 적용)',
310
313
  '',
@@ -373,6 +376,9 @@ export function renderModelRatchet(rules, lang = userLanguage(), { root } = {})
373
376
  ' tier: there is nothing to save.',
374
377
  '- Skip it when the request mixes in design judgement or irreversible work',
375
378
  ' (deploy, release, merge, submission).',
379
+ '- Do not delegate open research on the web (news, alternatives, candidates):',
380
+ ' a cheaper model stops after a few searches and nothing shows what it missed.',
381
+ ' Before relaying any delegated research, check how far it actually searched.',
376
382
  '',
377
383
  '## Tier criteria (apply to every rule below)',
378
384
  '',
@@ -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) || (t.length > SPEC_LEN && !looksPasted(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
  /**
@@ -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 effort chip's ultracode check, which the payload
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/ultracode.js CHANGED
@@ -1,18 +1,17 @@
1
1
  /**
2
- * Ultracode detection — the one effort level Claude Code does not put in the
2
+ * Ultracode detection — the one session state Claude Code does not put in the
3
3
  * statusline payload.
4
4
  *
5
- * `/effort ultracode` is "xhigh + dynamic workflow orchestration, this session
6
- * only". Claude Code stores it as two things: the effort level, which it raises
7
- * to `xhigh`, and a session flag for the orchestration half. Only the level
8
- * reaches the statusline contract (2.1.276 builds the payload as
9
- * `...modelHasEffort(model) && { effort: { level: resolved } }`, where `resolved`
10
- * is validated against the level list and so can never read "ultracode"), so a
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 distinguish them is in the transcript. Claude Code injects a
14
- * system-reminder when ultracode turns on and another when it turns off, and
15
- * both are recorded as attachment entries:
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: you run `/effort ultracode`, nothing has been
27
- * recorded yet, and the chip still says xhigh until you send something. The
28
- * command's own output closes that gap, because Claude Code writes it to the
29
- * transcript the moment the command returns:
30
- *
31
- * {"type":"user","message":{"content":"<local-command-stdout>Set effort level to
32
- * ultracode (this session only): xhigh + dynamic workflow orchestration</local-command-stdout>"}}
33
- *
34
- * measured 7s, 34s and 72s ahead of the matching attachment in one session. Both
35
- * directions are legible there: the ultracode row is the only one that names the
36
- * level, and every other `/effort <level>` clears the flag as it sets the level
37
- * (`effortUpdate:{value:e,ultracode:!1}`), so those rows mean "off". The bare
38
- * query prints `Current effort level: …`, which reads the same way.
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 "not ultracode", which is what the chip showed before this
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 other
61
- * two are the shapes `/effort` prints. Cheap prefilters only — every hit is
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 = ['ultra_effort_', 'Set effort level to', 'Current effort level:'];
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
- /** The levels Claude Code accepts; any of them being SET means ultracode is off. */
67
- const PLAIN_LEVELS = /Set effort level to (?:low|medium|high|xhigh|max)\b/;
68
- /** The bare query's answer, which names ultracode when it is on. */
69
- const QUERY_LEVEL = /Current effort level: (\w+)/;
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 `/effort` command output reports, or null when the entry is not
99
- * one.
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
- * this was built in, "Set effort level to …" appears six times outside a real
103
- * command output: three times in assistant text that quoted it and three in tool
104
- * results that printed it. Requiring a user entry whose content is a plain
105
- * string carrying the `<local-command-stdout>` wrapper excluded all six and kept
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
- if (content.includes('Set effort level to ultracode')) return true;
117
- const query = content.match(QUERY_LEVEL);
118
- if (query) return query[1] === 'ultracode';
119
- if (PLAIN_LEVELS.test(content)) return false;
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
- * Is ultracode on, according to this transcript?
125
- *
126
- * @param {string|null|undefined} transcriptPath - `transcript_path` from the statusline payload.
127
- * @param {object} [opts]
128
- * @param {number} [opts.scanBytes=SCAN_BYTES] - how many trailing bytes to search.
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 null;
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 null;
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
- * The level the effort chip should name.
199
+ * Is ultracode on, according to this transcript?
184
200
  *
185
- * Reads the transcript only when the payload says `xhigh`, since that is the
186
- * only level ultracode can present as — which keeps every other session, and
187
- * every non-statusline caller, at zero extra I/O.
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
- * The `xhigh` guard is also what keeps a stale marker honest. Dropping effort
190
- * (say `/effort medium`) turns ultracode off, but the `exit` marker is only
191
- * written when the next turn is assembled, so between those two moments the
192
- * newest marker still says `enter` while the payload already says `medium`.
193
- * Trusting the level here means the chip follows the payload, not the lag.
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 {string|null} `'ultracode'`, or `level` unchanged.
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 effortChipLevel(level, transcriptPath) {
200
- if (level !== 'xhigh') return level;
201
- return ultracodeFromTranscript(transcriptPath) === true ? 'ultracode' : level;
226
+ export function ultracodeChipState(transcriptPath) {
227
+ const state = readState(transcriptPath, SCAN_BYTES);
228
+ if (state === UNREADABLE) return null;
229
+ return state === true;
202
230
  }