sprag-cli 3.109.1 → 3.110.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 CHANGED
@@ -190,6 +190,8 @@ LLMRouterBench(Findings of ACL 2026)에서 오프라인으로 측정했습니다
190
190
 
191
191
  JetBrains IDE 내장 터미널에서는 이모지 대신 한 칸 글리프로 표시합니다(`◉ Cache hit 98.8% · ◧ Ctx 47% of 1M`). IDE 기본 폰트에 이모지 글리프가 없어서, 이모지를 그대로 두면 `Cache expires 4:545` 처럼 이전 프레임 문자가 화면에 남습니다. 모드 종류와 `sprag mode narrow` · `mode icon-force` 사용법은 [statusline 문서의 라벨 모드](https://github.com/rootstudioyaml/sprag/blob/main/docs/STATUSLINE.ko.md#라벨-모드)에 있습니다.
192
192
 
193
+ Agent SDK로 Claude Code를 실행하는 호스트(T3 Code 등)는 `statusLine` 명령을 실행하지 않아서 이 줄이 보이지 않습니다. 그 호스트의 내장 터미널에서 `sprag panel` 을 실행하면 해당 프로젝트의 가장 최근 세션을 따라가는 실시간 사본이 뜹니다(`--once` 는 한 프레임만 출력합니다). Orca는 Claude Code를 실제 터미널에서 실행하므로 기본 statusline이 그대로 보이고 패널이 필요하지 않습니다. Orca가 자기 statusLine을 먼저 넣어 두었다면 `sprag install` 이 그 명령을 sprag 아래에서 계속 실행해 Orca의 사용량 표시도 유지합니다.
194
+
193
195
  ## 같은 프롬프트를 저가 등급에 돌리면
194
196
 
195
197
  벤치마크는 공개 데이터를 씁니다. 이 절은 같은 질문을 제 작업에 던진 결과입니다. 이 저장소의 실제 세션에서 질문 여덟 개를 골라 두 등급에 보내고, 실행 전에 적어 둔 정답과 맞춰 봤습니다(2026-09-17, 원자료 `video/out/measure2.json`).
package/README.md CHANGED
@@ -239,6 +239,8 @@ When something is wrong the warning chip leads the line: `🚨 5H/7D NN%`, `⚠
239
239
 
240
240
  Inside a JetBrains IDE terminal the chips render as single-cell glyphs instead of emoji (`◉ Cache hit 98.8% · ◧ Ctx 47% of 1M`). The IDE's default font has no emoji glyphs, so emoji leave characters from the previous frame on screen, like `Cache expires 4:545`. [Label modes](https://github.com/rootstudioyaml/sprag/blob/main/docs/STATUSLINE.md#label-modes) covers the detail, plus `sprag mode narrow` and `mode icon-force`.
241
241
 
242
+ Hosts that run Claude Code through the Agent SDK, such as T3 Code, never run the `statusLine` command, so the line does not appear there. Run `sprag panel` in the host's integrated terminal to get a live copy that follows the newest session of that project (`--once` prints a single frame). Orca runs Claude Code in a real terminal, so the normal statusline shows there and needs no panel. When Orca wrote its own statusLine first, `sprag install` keeps it running underneath sprag's, which keeps Orca's usage display fed.
243
+
242
244
  ## The cheap tier on the same prompts
243
245
 
244
246
  The benchmark uses public data. This asks the same question of my own work: eight
package/bin/cli.js CHANGED
@@ -134,6 +134,7 @@ const KNOWN_SUBCOMMANDS = new Set([
134
134
  'last', 'brief', 'history', 'handoff', 'install', 'uninstall', 'mode', 'korean', 'cohesion',
135
135
  'doc2md', 'delegate', 'proof', 'harness', 'route-scan', 'compact-window', 'update-check', 'upgrade',
136
136
  'seed', 'litellm-budget', 'oauth-budget', 'profile-map', 'feedback', 'saved', 'cowork', 'team', 'presets', 'routing', 'secrets',
137
+ 'panel',
137
138
  ]);
138
139
 
139
140
  // Flags each entry path reads, collected from the hasFlag/getArg/numArg calls in
@@ -156,6 +157,11 @@ const FLAG_SPECS = {
156
157
  // --yes and --no-input are the explicit spelling of "do not ask", and
157
158
  // uninstall never asks, so they are accepted as no-ops.
158
159
  uninstall: { value: [], bool: ['--purge', '--yes', '--no-input', '--help', '-h'] },
160
+ // The Claude-side panel. The Codex panel is routed away before any spec applies.
161
+ panel: {
162
+ value: ['--project', '--session', '--interval'],
163
+ bool: ['--once', '--no-color', '--icon', '--verbose', '--single-line', '--help', '-h'],
164
+ },
159
165
  };
160
166
 
161
167
  /** Which spec applies to this invocation, or null for a subcommand that parses its own arguments. */
@@ -248,6 +254,8 @@ Usage:
248
254
  sprag upgrade install the latest release
249
255
  sprag --install-hook install cache-monitor PostToolUse hook
250
256
  sprag --uninstall-hook remove that hook
257
+ sprag panel live statusline in a terminal pane, for hosts that do not draw it (T3 Code, Agent SDK)
258
+ --once / --interval <sec> / --project <dir> / --session <id> / --no-color
251
259
  sprag --statusline one-line output for Claude Code statusline
252
260
  --verbose / --no-color / --icon / --no-timer / --single-line
253
261
  --columns N fit lines to N cells (default: $COLUMNS, which Claude Code sets, else 120)
@@ -306,6 +314,12 @@ async function main() {
306
314
  }
307
315
  }
308
316
 
317
+ // Subcommand: panel — live statusline for hosts that never run the statusLine
318
+ // command (T3 Code and other Agent SDK hosts). The Codex panel is handled above.
319
+ if (args[0] === 'panel') {
320
+ return (await import('../src/commands/panel.js')).run({ getArg, hasFlag });
321
+ }
322
+
309
323
  // Subcommand: last — print the most recent warning + how to handle it.
310
324
  // Designed for the auto-trigger skill so the user immediately sees
311
325
  // "what just fired and how to fix it" without having to read the whole
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sprag-cli",
3
- "version": "3.109.1",
3
+ "version": "3.110.0",
4
4
  "description": "The delegation layer for Claude Code and Codex: each task goes to the model and effort that fits it, down to cheaper models for lookups and up to higher effort when a cheaper run would miss, backed by public replay cases, with a live statusline and team rules for Pro and Enterprise.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -0,0 +1,232 @@
1
+ /**
2
+ * Subcommand: panel (Claude Code side) -- a live copy of the statusline in a
3
+ * terminal pane.
4
+ *
5
+ * Hosts that run Claude Code headless through the Agent SDK `query()` (T3 Code)
6
+ * never execute settings.json `statusLine.command`, so the statusline is
7
+ * invisible there. Those hosts do ship a terminal whose cwd is the thread's
8
+ * project, so `sprag panel` finds the newest transcript for that project and
9
+ * re-renders the real `sprag --statusline` against it every few seconds.
10
+ *
11
+ * `sprag panel --agent codex` is a different panel and never reaches this file.
12
+ */
13
+
14
+ import { execFile } from 'node:child_process';
15
+ import { existsSync, readdirSync, realpathSync, statSync } from 'node:fs';
16
+ import { basename, join } from 'node:path';
17
+ import { claudeUserDir } from '../paths.js';
18
+ import { CLI_ENTRY } from '../cli-entry.js';
19
+
20
+ const RENDER_TIMEOUT_MS = 4000;
21
+ const DEFAULT_INTERVAL_S = 5;
22
+ const MIN_INTERVAL_S = 1;
23
+ const PASSTHROUGH_FLAGS = ['--no-color', '--icon', '--verbose', '--single-line'];
24
+
25
+ /**
26
+ * Where Claude Code keeps its config. paths.js claudeUserDir() ignores
27
+ * CLAUDE_CONFIG_DIR, but a host that sets it (Cowork, T3 profiles) writes its
28
+ * transcripts there, so the panel has to look there first.
29
+ */
30
+ export function claudeConfigDir(env = process.env) {
31
+ return env.CLAUDE_CONFIG_DIR || claudeUserDir();
32
+ }
33
+
34
+ /** Claude Code names a project's transcript directory after its cwd, every non-alphanumeric char turned into '-'. */
35
+ export function encodeProjectDir(cwd) {
36
+ return String(cwd).replace(/[^A-Za-z0-9]/g, '-');
37
+ }
38
+
39
+ /**
40
+ * The transcript directory for `cwd`. The realpath is tried as well because the
41
+ * terminal may report /tmp while Claude Code recorded /private/tmp (macOS). When
42
+ * neither exists the directory for the given cwd is returned so callers see "no
43
+ * session yet" rather than an error.
44
+ */
45
+ export function projectTranscriptDir(cwd, { claudeDir = claudeConfigDir() } = {}) {
46
+ const candidates = [cwd];
47
+ try {
48
+ const real = realpathSync(cwd);
49
+ if (real !== cwd) candidates.push(real);
50
+ } catch { /* cwd may not exist (yet) */ }
51
+ const dirs = candidates.map((c) => join(claudeDir, 'projects', encodeProjectDir(c)));
52
+ return dirs.find((d) => existsSync(d)) || dirs[0];
53
+ }
54
+
55
+ /**
56
+ * The session to show: `session` when pinned, otherwise the newest *.jsonl by
57
+ * mtime. Only files directly in the directory count; subdirectories hold
58
+ * subagent transcripts, which must not displace the main session.
59
+ *
60
+ * @returns {{ sessionId: string, transcriptPath: string | null } | null}
61
+ */
62
+ export function latestSession(cwd, { claudeDir = claudeConfigDir(), session } = {}) {
63
+ const dir = projectTranscriptDir(cwd, { claudeDir });
64
+ if (session) {
65
+ const file = join(dir, `${session}.jsonl`);
66
+ return { sessionId: session, transcriptPath: existsSync(file) ? file : null };
67
+ }
68
+ let best = null;
69
+ let entries;
70
+ try {
71
+ entries = readdirSync(dir, { withFileTypes: true });
72
+ } catch {
73
+ return null;
74
+ }
75
+ for (const e of entries) {
76
+ if (!e.isFile() || !e.name.endsWith('.jsonl')) continue;
77
+ const path = join(dir, e.name);
78
+ let mtime;
79
+ try { mtime = statSync(path).mtimeMs; } catch { continue; }
80
+ if (!best || mtime > best.mtime) best = { mtime, path };
81
+ }
82
+ if (!best) return null;
83
+ return { sessionId: basename(best.path, '.jsonl'), transcriptPath: best.path };
84
+ }
85
+
86
+ /**
87
+ * The stdin JSON for one statusline render. Only what the panel knows: an
88
+ * absent field means "no data" to the statusline, a 0 means 0%, so rate limits,
89
+ * model and context are never invented here.
90
+ */
91
+ export function panelPayload({ cwd, session }) {
92
+ const payload = { cwd, workspace: { current_dir: cwd, project_dir: cwd } };
93
+ if (session) {
94
+ payload.session_id = session.sessionId;
95
+ if (session.transcriptPath) payload.transcript_path = session.transcriptPath;
96
+ }
97
+ return payload;
98
+ }
99
+
100
+ /** The argv of the child that renders one frame. CLI_ENTRY, never process.argv[1]: under the test runner that is the test file and forks without end. */
101
+ export function renderArgs({ cols, passthrough = [], cliEntry = CLI_ENTRY }) {
102
+ return [cliEntry, '--statusline', '--columns', String(cols), ...passthrough];
103
+ }
104
+
105
+ /** Default spawner: run `cmd args` with `input` on stdin, never throw. */
106
+ export function defaultSpawner(cmd, args, { input, timeout, cwd }) {
107
+ return new Promise((resolve) => {
108
+ let child;
109
+ try {
110
+ child = execFile(cmd, args, { timeout, windowsHide: true, cwd, maxBuffer: 1024 * 1024 },
111
+ (err, stdout) => resolve({ ok: !err, stdout: String(stdout || '') }));
112
+ } catch {
113
+ resolve({ ok: false, stdout: '' });
114
+ return;
115
+ }
116
+ child.stdin.on('error', () => { /* the child exited before reading; the callback reports it */ });
117
+ child.stdin.end(input);
118
+ });
119
+ }
120
+
121
+ /** One rendered frame, or null when the render failed or timed out (the caller keeps the last frame). */
122
+ export async function renderFrame({
123
+ payload, cols, passthrough = [], spawner = defaultSpawner, execPath = process.execPath,
124
+ cliEntry = CLI_ENTRY, timeoutMs = RENDER_TIMEOUT_MS, cwd,
125
+ }) {
126
+ const res = await spawner(execPath, renderArgs({ cols, passthrough, cliEntry }), {
127
+ input: JSON.stringify(payload), timeout: timeoutMs, cwd,
128
+ });
129
+ if (!res || !res.ok) return null;
130
+ const text = String(res.stdout).replace(/\s+$/, '');
131
+ return text === '' ? null : text;
132
+ }
133
+
134
+ /** Repaint only when the frame text changed; a redraw every tick makes the pane flicker. */
135
+ export function createScreen(write) {
136
+ let last = null;
137
+ return {
138
+ draw(frame) {
139
+ if (frame === last) return false;
140
+ last = frame;
141
+ write(`\x1b[H\x1b[2J${frame}\n`);
142
+ return true;
143
+ },
144
+ };
145
+ }
146
+
147
+ export const waitingHint = (cwd) => `sprag panel: waiting for a Claude Code session in ${cwd}`;
148
+
149
+ function passthroughOf(hasFlag) {
150
+ return PASSTHROUGH_FLAGS.filter((f) => hasFlag(f));
151
+ }
152
+
153
+ /**
154
+ * @param {object} p
155
+ * @param {(name: string) => string | undefined} p.getArg
156
+ * @param {(name: string) => boolean} p.hasFlag
157
+ * @param {object} [p.deps] injection points for tests
158
+ */
159
+ export async function run({ getArg, hasFlag, deps = {} }) {
160
+ const {
161
+ spawner = defaultSpawner,
162
+ stdout = process.stdout,
163
+ stderr = process.stderr,
164
+ env = process.env,
165
+ setTimeoutFn = setTimeout,
166
+ onStop,
167
+ } = deps;
168
+ const write = (s) => stdout.write(s);
169
+ const cwd = getArg('--project') || process.cwd();
170
+ const pinned = getArg('--session') || undefined;
171
+ const claudeDir = claudeConfigDir(env);
172
+ const passthrough = passthroughOf(hasFlag);
173
+ const cols = () => stdout.columns || 120;
174
+ const renderCwd = existsSync(cwd) ? cwd : undefined;
175
+
176
+ const intervalRaw = getArg('--interval');
177
+ let intervalS = DEFAULT_INTERVAL_S;
178
+ if (intervalRaw !== undefined) {
179
+ const n = Number(intervalRaw);
180
+ if (!Number.isFinite(n)) throw new Error(`--interval expects a number, got "${intervalRaw}"`);
181
+ intervalS = Math.max(MIN_INTERVAL_S, n);
182
+ }
183
+
184
+ const frameFor = async () => {
185
+ const session = latestSession(cwd, { claudeDir, session: pinned });
186
+ const frame = await renderFrame({
187
+ payload: panelPayload({ cwd, session }), cols: cols(), passthrough, spawner, cwd: renderCwd,
188
+ });
189
+ return { session, frame };
190
+ };
191
+
192
+ if (hasFlag('--once') || !stdout.isTTY) {
193
+ const { session, frame } = await frameFor();
194
+ if (frame !== null) write(`${frame}\n`);
195
+ if (!session) stderr.write(`${waitingHint(cwd)}\n`);
196
+ else if (frame === null) process.exitCode = 1;
197
+ return;
198
+ }
199
+
200
+ const screen = createScreen(write);
201
+ let lastFrame = null;
202
+ let stopped = false;
203
+ let timer = null;
204
+ const stop = () => {
205
+ if (stopped) return;
206
+ stopped = true;
207
+ if (timer) clearTimeout(timer);
208
+ write('\x1b[?25h');
209
+ if (onStop) onStop(); else process.exit(0);
210
+ };
211
+ process.once('SIGINT', stop);
212
+ process.once('SIGTERM', stop);
213
+ write('\x1b[?25l');
214
+
215
+ // The next tick is scheduled only after this one finishes, so a slow render
216
+ // can never stack a second child on top of the first.
217
+ const tick = async () => {
218
+ try {
219
+ const { session, frame } = await frameFor();
220
+ if (frame !== null) lastFrame = frame;
221
+ if (lastFrame !== null) {
222
+ screen.draw(session ? lastFrame : `${lastFrame}\n${waitingHint(cwd)}`);
223
+ } else if (!session) {
224
+ screen.draw(waitingHint(cwd));
225
+ }
226
+ } catch { /* keep the last frame on screen */ }
227
+ if (!stopped) {
228
+ timer = setTimeoutFn(tick, intervalS * 1000);
229
+ }
230
+ };
231
+ await tick();
232
+ }
package/src/installer.js CHANGED
@@ -416,10 +416,28 @@ function detectStatuslineWrapper(command) {
416
416
  return { script, name, deprecatedFallback: body.includes(`${LEGACY_CLI}@latest`) };
417
417
  }
418
418
 
419
+ /**
420
+ * Whether a statusLine command is the one Orca installs for itself.
421
+ *
422
+ * Orca (stablyai/orca) runs Claude Code in a real terminal and, when the slot is
423
+ * empty, writes a statusLine that runs `~/.orca/agent-hooks/claude-statusline.sh`
424
+ * (`.cmd` on Windows) inside a shell wrapper. That script prints nothing: it only
425
+ * forwards the payload's rate limits to the Orca app. Left in place it blanks the
426
+ * statusline, and Orca never replaces a statusLine it did not write, so whichever
427
+ * tool installs first keeps the slot. Treating it as someone's own statusline made
428
+ * a machine that had Orca first skip ours on every install, with nothing drawn in
429
+ * any terminal.
430
+ */
431
+ export function isOrcaStatusline(command) {
432
+ return typeof command === 'string' && /\.orca[\\/]agent-hooks[\\/]claude-statusline\b/.test(command);
433
+ }
434
+
419
435
  // Registers/repairs the Claude Code statusLine entry in ~/.claude/settings.json.
420
436
  // - No statusLine yet: insert ours with refreshInterval:STATUSLINE_REFRESH_INTERVAL.
421
437
  // - statusLine already points at sprag: ensure that refreshInterval
422
438
  // (this is the bit that makes the TTL countdown tick every second while idle).
439
+ // - statusLine is Orca's usage feed: merge without asking. It draws nothing, and
440
+ // running it as the base keeps Orca's rate-limit display fed.
423
441
  // - statusLine points at a different command: leave it alone unless --force,
424
442
  // or `merge`, which keeps their command running underneath ours (the original
425
443
  // object is saved as config `statuslineBase` so uninstall can restore it).
@@ -460,6 +478,8 @@ export function installStatusline({ force = false, merge = false } = {}) {
460
478
  return { path: file, action: 'updated', reason: `set refreshInterval=${STATUSLINE_REFRESH_INTERVAL}` };
461
479
  }
462
480
 
481
+ if (!force && isOrcaStatusline(cur.command)) merge = true;
482
+
463
483
  if (!force && !merge) {
464
484
  // `conflict` lets the interactive install distinguish "someone else's
465
485
  // statusline is here" (worth asking about) from other skip reasons
@@ -498,7 +518,10 @@ export function installStatusline({ force = false, merge = false } = {}) {
498
518
  if (merge) {
499
519
  cfg.statuslineBase = base;
500
520
  saveConfig(cfg);
501
- return { path: file, action: 'updated', reason: 'merged with previous statusLine', merged: true };
521
+ const reason = isOrcaStatusline(base.command)
522
+ ? "merged with Orca's statusLine, which keeps running underneath"
523
+ : 'merged with previous statusLine';
524
+ return { path: file, action: 'updated', reason, merged: true };
502
525
  }
503
526
  // Replace means the old one is gone for good; a stale base would resurrect it
504
527
  // (or keep running it) later.