sprag-cli 3.130.0 → 3.132.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 +11 -1
- package/mac/SpragBar.swift +3141 -0
- package/mod/sprag-statusline/hooks/register.tsx +58 -3
- package/package.json +2 -1
- package/src/agent-activity.js +485 -0
- package/src/agent-detail.js +266 -0
- package/src/agent-usage.js +410 -0
- package/src/agent-warnings.js +128 -0
- package/src/bar-app.js +330 -0
- package/src/bar-rules.js +133 -0
- package/src/bar-settings.js +78 -0
- package/src/brief.js +40 -13
- package/src/caps-cache.js +4 -3
- package/src/claude-version.js +38 -0
- package/src/codex/budget.js +1 -1
- package/src/codex/delegation-diagnostics.js +1 -1
- package/src/codex/panel.js +1 -7
- package/src/commands/bar.js +370 -0
- package/src/commands/delegate.js +1 -0
- package/src/commands/feedback.js +2 -2
- package/src/commands/install.js +4 -1
- package/src/commands/last.js +1 -1
- package/src/commands/route-scan.js +39 -1
- package/src/commands/team.js +1 -1
- package/src/commands/uninstall.js +2 -0
- package/src/commands/upgrade.js +1 -1
- package/src/compact-window.js +1 -1
- package/src/cowork-sync.js +1 -1
- package/src/ctx-window-cache.js +11 -8
- package/src/delegation-agents.js +41 -2
- package/src/doc2md.cjs +1 -0
- package/src/gateway-auth.js +1 -0
- package/src/handoff.js +1 -0
- package/src/history.js +18 -1
- package/src/installer.js +43 -0
- package/src/korean-style.js +1 -1
- package/src/permission-secrets.js +1 -1
- package/src/session-cache.js +19 -0
- package/src/statusline-guard.js +17 -0
- package/src/team-sync.js +1 -1
- package/src/transcript-lines.js +1 -1
- package/src/window-labels.js +11 -0
package/src/brief.js
CHANGED
|
@@ -168,6 +168,12 @@ function ctxTierOf(pct) {
|
|
|
168
168
|
return t;
|
|
169
169
|
}
|
|
170
170
|
|
|
171
|
+
export const BRIEF_HEADER = '✇ [sprag 브리핑] 아래 상태 변화를 사용자에게 알려주세요. 진행 중인 답변 흐름을 끊지 말고, 답변 말미에 `✇ [sprag]` 라벨을 달아 각 항목을 1~2줄로 요약해 전달하면 됩니다 (이 브리핑은 항목당 한 번만 주입됩니다):';
|
|
172
|
+
export const URGENT_BRIEF_HEADER = '✇ [sprag 브리핑, 지금 전달] 아래 항목은 시간이 지나면 틀린 정보가 됩니다. 이번 답변의 첫 줄에 `✇ [sprag]` 라벨을 달아 한 줄로 전하고 그다음에 작업을 이어가십시오. 도구 호출이 끝날 때까지 미루지 마십시오. 대화 앞부분이 이미 요약으로 바뀌었다면 압축이 끝난 것이니 이 항목은 전하지 마십시오:';
|
|
173
|
+
|
|
174
|
+
const COMPACTION_NOTICE_KO = '✇ [sprag] 방금 이 세션의 대화가 압축됐습니다. 압축 전에 받은 컨텍스트 경고(컨텍스트가 창의 80%나 95%를 넘었다는 sprag 브리핑)는 이제 지난 정보입니다. 아직 사용자에게 전하지 않았다면 전하지 마십시오. 대신 이번 답변 끝에 `✇ [sprag]` 라벨로 압축이 돌아 컨텍스트가 줄었다는 것만 한 줄로 알리십시오.';
|
|
175
|
+
const COMPACTION_NOTICE_EN = "✇ [sprag] This session's conversation was just compacted. Any context warning received before that (a sprag briefing that the context passed 80% or 95% of the window) is now out of date: if you have not relayed it to the user yet, do not. Instead add one line at the end of this reply, under a `✇ [sprag]` label, saying that compaction ran and the context is smaller now.";
|
|
176
|
+
|
|
171
177
|
const fmtK = (n) => `${Math.round(n / 1000)}k`;
|
|
172
178
|
|
|
173
179
|
// A session left open for days re-reads everything it ever loaded on every
|
|
@@ -244,6 +250,7 @@ export async function runBrief({ sessionId, transcriptPath, root = process.cwd()
|
|
|
244
250
|
const state = loadState();
|
|
245
251
|
const s = state.sessions[sessionId] || { ctxTier: 0, briefed: [] };
|
|
246
252
|
const items = [];
|
|
253
|
+
const urgent = [];
|
|
247
254
|
|
|
248
255
|
// ── context tier crossing (per-session) ──
|
|
249
256
|
const ctx = transcriptPath ? sessionCtx(transcriptPath, { root, liveWindow }) : null;
|
|
@@ -266,13 +273,18 @@ export async function runBrief({ sessionId, transcriptPath, root = process.cwd()
|
|
|
266
273
|
// With autoCompactWindow set, crossing the threshold means compaction is
|
|
267
274
|
// about to run on its own. Telling the user to start a new session there
|
|
268
275
|
// would be advice for a problem the setting already handles.
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
+
// The 95% item goes into its own block that tells the model to relay it
|
|
277
|
+
// first: in a turn with many tool calls, compaction can run before the
|
|
278
|
+
// answer ends, and an item delivered at the end would then be false.
|
|
279
|
+
const cap = ctx.compactCapped;
|
|
280
|
+
const item = tier === 2
|
|
281
|
+
? (cap
|
|
282
|
+
? `이 세션의 컨텍스트가 자동 압축 창(${winLabel})의 95%를 넘었습니다(직전 요청 입력 ${fmtK(ctx.input)}${capNote}). 이 답변이 끝나기 전에 자동 압축이 돌 수 있습니다. 이어서 할 일을 지금 파일에 적어 두면 압축 뒤에도 안전합니다.`
|
|
283
|
+
: `이 세션의 컨텍스트가 ${winLabel} 창의 95%를 넘었습니다(직전 요청 입력 ${fmtK(ctx.input)}). 이 답변이 끝나기 전에 자동 압축이 돌 수 있고 그때 앞부분 맥락이 요약으로 줄어듭니다. 진행 중인 작업을 일단락하고 새 세션을 시작하는 편이 좋습니다.`)
|
|
284
|
+
: (cap
|
|
285
|
+
? `이 세션의 컨텍스트가 자동 압축 창(${winLabel})의 80%를 넘었습니다(직전 요청 입력 ${fmtK(ctx.input)}${capNote}). 설정해 둔 압축 지점이 가까워졌습니다. 압축은 알아서 돌아가니 새 세션을 서두를 필요는 없습니다. 여기까지의 결정과 다음 할 일만 파일에 남겨 두면 됩니다.`
|
|
286
|
+
: `이 세션의 컨텍스트가 ${winLabel} 창의 80%를 넘었습니다(직전 요청 입력 ${fmtK(ctx.input)}). 이후 요청은 비용이 커지는 구간입니다. 작업이 일단락되면 새 세션 시작을 권합니다.`);
|
|
287
|
+
(tier === 2 ? urgent : items).push(item);
|
|
276
288
|
s.ctxTier = tier;
|
|
277
289
|
}
|
|
278
290
|
}
|
|
@@ -346,10 +358,25 @@ export async function runBrief({ sessionId, transcriptPath, root = process.cwd()
|
|
|
346
358
|
state.sessions[sessionId] = s;
|
|
347
359
|
saveState(state, now);
|
|
348
360
|
|
|
349
|
-
if (items.length === 0) return null;
|
|
350
|
-
const
|
|
351
|
-
|
|
352
|
-
];
|
|
353
|
-
|
|
354
|
-
|
|
361
|
+
if (items.length === 0 && urgent.length === 0) return null;
|
|
362
|
+
const blocks = [];
|
|
363
|
+
if (urgent.length > 0) blocks.push([URGENT_BRIEF_HEADER, ...urgent.map((it) => `- ${it}`)].join('\n'));
|
|
364
|
+
if (items.length > 0) blocks.push([BRIEF_HEADER, ...items.map((it) => `- ${it}`)].join('\n'));
|
|
365
|
+
return blocks.join('\n\n');
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
/**
|
|
369
|
+
* Text for the SessionStart hook that runs after a compaction, or null when no
|
|
370
|
+
* context warning was injected in this fill cycle (ctxTier >= 1).
|
|
371
|
+
*
|
|
372
|
+
* Read-only on purpose. Right after a compaction the transcript's last recorded
|
|
373
|
+
* usage can still be the pre-compaction one, so resetting the tier here would
|
|
374
|
+
* make the next prompt fire the 95% warning again. The lazy drop in runBrief
|
|
375
|
+
* lowers the tier once a smaller reading arrives.
|
|
376
|
+
*/
|
|
377
|
+
export function compactionNotice({ sessionId, lang } = {}) {
|
|
378
|
+
if (!sessionId) return null;
|
|
379
|
+
const s = loadState().sessions[sessionId];
|
|
380
|
+
if (!s || !((s.ctxTier || 0) >= 1)) return null;
|
|
381
|
+
return lang === 'ko' ? COMPACTION_NOTICE_KO : COMPACTION_NOTICE_EN;
|
|
355
382
|
}
|
package/src/caps-cache.js
CHANGED
|
@@ -77,12 +77,13 @@ function normalizeCaps(caps) {
|
|
|
77
77
|
/**
|
|
78
78
|
* @param {object} [opts]
|
|
79
79
|
* @param {number} [opts.maxAgeMs=5*60*1000] - drop snapshots older than this.
|
|
80
|
+
* @param {string} [opts.path] - snapshot file; `sprag bar` passes its own data folder's copy.
|
|
80
81
|
* @returns {{ caps: object|null, model: string|null }|null}
|
|
81
82
|
*/
|
|
82
|
-
export function loadRecentSnapshot({ maxAgeMs = 5 * 60 * 1000 } = {}) {
|
|
83
|
+
export function loadRecentSnapshot({ maxAgeMs = 5 * 60 * 1000, path = CACHE_PATH } = {}) {
|
|
83
84
|
try {
|
|
84
|
-
if (!existsSync(
|
|
85
|
-
const raw = readFileSync(
|
|
85
|
+
if (!existsSync(path)) return null;
|
|
86
|
+
const raw = readFileSync(path, 'utf8');
|
|
86
87
|
const data = JSON.parse(raw);
|
|
87
88
|
if (!data || typeof data.capturedAt !== 'number') return null;
|
|
88
89
|
if (Date.now() - data.capturedAt > maxAgeMs) return null;
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Which Claude Code is running this hook or command, read without spawning it.
|
|
3
|
+
*
|
|
4
|
+
* Measured on Claude Code 2.1.319: the SessionStart and UserPromptSubmit hook
|
|
5
|
+
* processes carry AI_AGENT=claude-code_2-1-319_harness, and the Bash tool's
|
|
6
|
+
* children carry claude-code_2-1-319_agent. The Claude process's own
|
|
7
|
+
* environment does not have it, so the value exists only in hook and tool
|
|
8
|
+
* children. That is enough here, because the callers are hooks and CLI
|
|
9
|
+
* commands that a session runs. `claude --version` is deliberately not used: it
|
|
10
|
+
* would slow the hook path and make tests depend on the machine.
|
|
11
|
+
*
|
|
12
|
+
* Why the version matters: before 2.1.326 a session did not find an agent file
|
|
13
|
+
* first created while it was running ("Fixed a first skill, command or agent
|
|
14
|
+
* created during a session not being found right away").
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import { isNewer } from './update-check.js';
|
|
18
|
+
|
|
19
|
+
export const AGENTS_LIVE_MIN_VERSION = '2.1.326';
|
|
20
|
+
|
|
21
|
+
const AI_AGENT_RE = /^claude-code_(\d+)-(\d+)-(\d+)(?:_|$)/;
|
|
22
|
+
|
|
23
|
+
/** Claude Code version from AI_AGENT ("claude-code_2-1-319_harness" -> "2.1.319"), or null. */
|
|
24
|
+
export function sessionClaudeVersion(env = process.env) {
|
|
25
|
+
const hit = AI_AGENT_RE.exec(String((env && env.AI_AGENT) || '').trim());
|
|
26
|
+
return hit ? `${hit[1]}.${hit[2]}.${hit[3]}` : null;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* True when this Claude Code finds an agent first created mid-session; false
|
|
31
|
+
* when it is older; null when the version is unknown (callers treat null like
|
|
32
|
+
* false, so an old Claude Code is never assumed to be new).
|
|
33
|
+
*/
|
|
34
|
+
export function agentsLoadMidSession(version) {
|
|
35
|
+
if (!version) return null;
|
|
36
|
+
if (!/^\d+\.\d+\.\d+$/.test(String(version))) return null;
|
|
37
|
+
return version === AGENTS_LIVE_MIN_VERSION || isNewer(version, AGENTS_LIVE_MIN_VERSION);
|
|
38
|
+
}
|
package/src/codex/budget.js
CHANGED
|
@@ -30,7 +30,7 @@ export async function codexProviderKey(provider, { execute = run } = {}) {
|
|
|
30
30
|
let key = provider.key;
|
|
31
31
|
if (!key && typeof provider.command === 'string') {
|
|
32
32
|
try {
|
|
33
|
-
const result = await execute(provider.command, provider.args, { encoding: 'utf8', timeout: 10000, maxBuffer: 64 * 1024 });
|
|
33
|
+
const result = await execute(provider.command, provider.args, { encoding: 'utf8', timeout: 10000, maxBuffer: 64 * 1024, windowsHide: true });
|
|
34
34
|
key = result.stdout.trim().split(/\r?\n/).filter(Boolean).pop();
|
|
35
35
|
} catch { throw new Error('Codex provider authentication helper failed'); }
|
|
36
36
|
}
|
|
@@ -18,7 +18,7 @@ export function codexDelegationDiagnostics({ home = codexUserDir(), model = code
|
|
|
18
18
|
(profile?.features?.multi_agent ?? cfg.features?.multi_agent) === false;
|
|
19
19
|
} catch (e) { if (e.code !== 'ENOENT') result.errors.push('Cannot parse user config.'); }
|
|
20
20
|
const run = (args) => exec('codex', args, { encoding: 'utf8', timeout: 5000, maxBuffer: 20 * 1024 * 1024,
|
|
21
|
-
env: { ...process.env, CODEX_HOME: home }, stdio: ['ignore', 'pipe', 'pipe'] });
|
|
21
|
+
env: { ...process.env, CODEX_HOME: home }, stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true });
|
|
22
22
|
try { result.version = run(['--version']).trim().slice(0, 100); } catch { result.errors.push('Codex version unavailable.'); }
|
|
23
23
|
try {
|
|
24
24
|
for (const line of run(['features', 'list']).split('\n')) {
|
package/src/codex/panel.js
CHANGED
|
@@ -12,7 +12,7 @@ import { gaugeBar, formatMoney, DEFAULT_SEGMENT_ORDER } from '../formatters/stat
|
|
|
12
12
|
import { codexCacheTimer } from './cache.js';
|
|
13
13
|
import { readCodexCachePolicy, readCodexPrices, isDirectOpenAI } from './cache-policy.js';
|
|
14
14
|
import { codexIssues } from './brief.js';
|
|
15
|
-
import { labelForKey } from '../window-labels.js';
|
|
15
|
+
import { labelForKey, windowLabel } from '../window-labels.js';
|
|
16
16
|
import { resolveLabelMode } from '../statusline-mode.js';
|
|
17
17
|
import { formatResetIn } from '../format-time.js';
|
|
18
18
|
import { codexDocumentTotals } from './doc2md-ledger.js';
|
|
@@ -192,12 +192,6 @@ function age(date, now) {
|
|
|
192
192
|
if (seconds < 3600) return `${Math.floor(seconds / 60)}m ago`;
|
|
193
193
|
return `${Math.floor(seconds / 3600)}h ago`;
|
|
194
194
|
}
|
|
195
|
-
function windowLabel(minutes, fallback) {
|
|
196
|
-
if (!Number.isFinite(minutes) || minutes <= 0) return fallback;
|
|
197
|
-
if (minutes % 1440 === 0) return `${minutes / 1440}D`;
|
|
198
|
-
if (minutes % 60 === 0) return `${minutes / 60}H`;
|
|
199
|
-
return `${minutes}m`;
|
|
200
|
-
}
|
|
201
195
|
|
|
202
196
|
export function effortLabel(value) {
|
|
203
197
|
return value === 'none' ? 'Reasoning off' : value ? terminalText(value) : 'Effort unknown';
|
|
@@ -0,0 +1,370 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Subcommand: bar -- what each running Claude Code and Codex session is doing,
|
|
3
|
+
* with its model, context use, cost, CPU and memory, and the account limits of
|
|
4
|
+
* each agent, printed once.
|
|
5
|
+
*
|
|
6
|
+
* Three outputs share one snapshot from collectActivity():
|
|
7
|
+
* sprag bar a terminal table
|
|
8
|
+
* sprag bar --json the snapshot as JSON, for a menu bar app or a desktop pet
|
|
9
|
+
* sprag bar --json --detail the same, with each session's request, last reply, recent tool calls and child processes
|
|
10
|
+
* sprag bar --swiftbar SwiftBar/xbar menu bar text
|
|
11
|
+
* sprag bar --plugin the shell script to save as sprag.5s.sh in the plugin folder
|
|
12
|
+
* sprag bar --settings the settings a menu bar app shows, as JSON (src/bar-settings.js)
|
|
13
|
+
* sprag bar --rules every ratchet, preset, model-fitting and team rule, as JSON (src/bar-rules.js)
|
|
14
|
+
*
|
|
15
|
+
* Four subcommands manage the macOS menu bar app (src/bar-app.js), which is
|
|
16
|
+
* compiled from mac/SpragBar.swift once per change to that file and started at session start:
|
|
17
|
+
* sprag bar on turn it on, compile it when needed and start it
|
|
18
|
+
* sprag bar off turn it off and stop it
|
|
19
|
+
* sprag bar status on or off, running, built, toolchain, last build error
|
|
20
|
+
* sprag bar build [--then-launch] compile it now, and start it after a good build
|
|
21
|
+
*
|
|
22
|
+
* The plugin script names the node binary and the CLI by absolute path because
|
|
23
|
+
* SwiftBar runs plugins with a short PATH that does not find `sprag`.
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
import { collectActivity } from '../agent-activity.js';
|
|
27
|
+
import { cellWidth } from '../cell-width.js';
|
|
28
|
+
import { CLI_ENTRY } from '../cli-entry.js';
|
|
29
|
+
|
|
30
|
+
const NAME_WIDTH = 28;
|
|
31
|
+
const ACTIVITY_WIDTH = 16;
|
|
32
|
+
const BRAND = '✇';
|
|
33
|
+
const MONO = 'font=Menlo size=12';
|
|
34
|
+
|
|
35
|
+
/** 12s under a minute, 18m under an hour, 5h under 48 hours, then 3d. '' for a negative or missing span. */
|
|
36
|
+
export function formatDuration(ms) {
|
|
37
|
+
if (!Number.isFinite(ms) || ms < 0) return '';
|
|
38
|
+
const s = Math.floor(ms / 1000);
|
|
39
|
+
if (s < 60) return `${s}s`;
|
|
40
|
+
const m = Math.floor(s / 60);
|
|
41
|
+
if (m < 60) return `${m}m`;
|
|
42
|
+
const h = Math.floor(m / 60);
|
|
43
|
+
if (h < 48) return `${h}h`;
|
|
44
|
+
return `${Math.floor(h / 24)}d`;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function formatMem(mb) {
|
|
48
|
+
if (!Number.isFinite(mb)) return '';
|
|
49
|
+
return mb < 1024 ? `${mb} MB` : `${(mb / 1024).toFixed(1)} GB`;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** 842, 166k, 1.2M. '' for a missing count. */
|
|
53
|
+
export function formatTokens(n) {
|
|
54
|
+
if (!Number.isFinite(n)) return '';
|
|
55
|
+
if (n < 1000) return String(n);
|
|
56
|
+
if (n < 1e6) return `${Math.round(n / 1000)}k`;
|
|
57
|
+
return `${(n / 1e6).toFixed(1)}M`;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function formatUsd(n) {
|
|
61
|
+
return Number.isFinite(n) ? `$${n.toFixed(2)}` : '';
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** The tool a session is in the middle of, how many more are pending, and its running subagents. */
|
|
65
|
+
export function activityLabel(row) {
|
|
66
|
+
const tools = Array.isArray(row?.tools) ? row.tools : [];
|
|
67
|
+
const parts = [];
|
|
68
|
+
if (tools.length > 0) parts.push(tools.length > 1 ? `${tools[0]} +${tools.length - 1}` : tools[0]);
|
|
69
|
+
if (row?.subagents > 0) parts.push(`⤷${row.subagents}`);
|
|
70
|
+
return parts.join(' ');
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const dot = (state) => (state === 'busy' ? '●' : state === 'idle' ? '○' : '◌');
|
|
74
|
+
|
|
75
|
+
/** `state` and how long it has held, or '-' when the state is unknown. */
|
|
76
|
+
function stateText(row, at) {
|
|
77
|
+
if (typeof row.state !== 'string') return '-';
|
|
78
|
+
const since = Number.isFinite(row.stateSince) ? formatDuration(at - row.stateSince) : '';
|
|
79
|
+
return since ? `${row.state} ${since}` : row.state;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function fit(text, width) {
|
|
83
|
+
const s = String(text ?? '');
|
|
84
|
+
if (cellWidth(s) <= width) return s;
|
|
85
|
+
let out = '';
|
|
86
|
+
for (const ch of Array.from(s)) {
|
|
87
|
+
if (cellWidth(out + ch) + 1 > width) break;
|
|
88
|
+
out += ch;
|
|
89
|
+
}
|
|
90
|
+
return `${out}…`;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const padEnd = (s, w) => s + ' '.repeat(Math.max(0, w - cellWidth(s)));
|
|
94
|
+
const padStart = (s, w) => ' '.repeat(Math.max(0, w - cellWidth(s))) + s;
|
|
95
|
+
const mark = (snapshot) => snapshot.animal?.emoji ?? BRAND;
|
|
96
|
+
// CPU is shown as a share of the whole machine (cpuPct): `ps` reports a share of
|
|
97
|
+
// one core, which adds up past 100% and read as an error.
|
|
98
|
+
const cpuText = (pct) => (Number.isFinite(pct) ? `${pct.toFixed(1)}%` : '');
|
|
99
|
+
const AGENT_NAMES = { claude: 'Claude', codex: 'Codex' };
|
|
100
|
+
|
|
101
|
+
/** `Claude Fable 5.2 xhigh`: the agent, then the model and the effort when they are known. */
|
|
102
|
+
function agentText(row) {
|
|
103
|
+
const name = AGENT_NAMES[row.agent] ?? String(row.agent ?? '');
|
|
104
|
+
return [name, row.modelName, row.effort].filter((part) => typeof part === 'string' && part !== '').join(' ');
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** `ctx 17%` when the window is known, `ctx 166k` when only the size of the prompt is, else ''. */
|
|
108
|
+
function ctxText(row) {
|
|
109
|
+
const c = row.context;
|
|
110
|
+
if (Number.isFinite(c?.pct)) return `ctx ${c.pct}%`;
|
|
111
|
+
return Number.isFinite(c?.tokens) ? `ctx ${formatTokens(c.tokens)}` : '';
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
const costText = (row) => formatUsd(row.usage?.costUsd);
|
|
115
|
+
|
|
116
|
+
/** Agents that have account limits, Claude first, with their windows as `5H 12%` words. */
|
|
117
|
+
function limitGroups(snapshot) {
|
|
118
|
+
const groups = [];
|
|
119
|
+
// Codex limits are read from rollout files that outlive the process, so they
|
|
120
|
+
// would show for a user who runs no Codex at all.
|
|
121
|
+
const hasCodex = (snapshot.sessions ?? []).some((r) => r.agent === 'codex');
|
|
122
|
+
for (const key of ['claude', 'codex']) {
|
|
123
|
+
if (key === 'codex' && !hasCodex) continue;
|
|
124
|
+
const windows = snapshot.usage?.[key]?.windows;
|
|
125
|
+
const words = (Array.isArray(windows) ? windows : [])
|
|
126
|
+
.filter((w) => w && Number.isFinite(w.usedPct))
|
|
127
|
+
.map((w) => `${w.label ?? w.key} ${Math.round(w.usedPct)}%`);
|
|
128
|
+
if (words.length) groups.push({ name: AGENT_NAMES[key], words });
|
|
129
|
+
}
|
|
130
|
+
return groups;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const warningsOf = (snapshot) => (Array.isArray(snapshot.warnings) ? snapshot.warnings : []);
|
|
134
|
+
|
|
135
|
+
export function renderText(snapshot) {
|
|
136
|
+
const { totals, sessions } = snapshot;
|
|
137
|
+
const lead = mark(snapshot);
|
|
138
|
+
const warningLines = warningsOf(snapshot).map((w) => `${w.chip} ${w.advice?.[0]?.title ?? ''}`.replace(/\s+$/, ''));
|
|
139
|
+
if (!sessions.length) return [`${lead} no agent sessions running`, ...warningLines].join('\n');
|
|
140
|
+
let head = `${lead} ${totals.busy}/${totals.sessions} busy`;
|
|
141
|
+
if (snapshot.resources) {
|
|
142
|
+
if (Number.isFinite(totals.cpuPct)) head += ` · CPU ${Math.round(totals.cpuPct)}%`;
|
|
143
|
+
head += ` · ${formatMem(totals.rssMb)}`;
|
|
144
|
+
}
|
|
145
|
+
for (const g of limitGroups(snapshot)) head += ` · ${g.name} ${g.words.join(' ')}`;
|
|
146
|
+
const cells = sessions.map((r) => ({
|
|
147
|
+
dot: dot(r.state),
|
|
148
|
+
name: fit(r.name, NAME_WIDTH),
|
|
149
|
+
agent: agentText(r),
|
|
150
|
+
state: stateText(r, snapshot.at),
|
|
151
|
+
activity: fit(activityLabel(r), ACTIVITY_WIDTH),
|
|
152
|
+
ctx: ctxText(r),
|
|
153
|
+
cost: costText(r),
|
|
154
|
+
cpu: snapshot.resources ? cpuText(r.cpuPct) : '',
|
|
155
|
+
mem: snapshot.resources ? formatMem(r.rssMb) : '',
|
|
156
|
+
}));
|
|
157
|
+
const w = (key) => Math.max(0, ...cells.map((c) => cellWidth(c[key])));
|
|
158
|
+
// ctx and cost take no room when no row has one.
|
|
159
|
+
const columns = [
|
|
160
|
+
{ key: 'name', pad: padEnd }, { key: 'agent', pad: padEnd }, { key: 'state', pad: padEnd }, { key: 'activity', pad: padEnd },
|
|
161
|
+
...(w('ctx') > 0 ? [{ key: 'ctx', pad: padEnd }] : []),
|
|
162
|
+
...(w('cost') > 0 ? [{ key: 'cost', pad: padStart }] : []),
|
|
163
|
+
...(snapshot.resources ? [{ key: 'cpu', pad: padStart }, { key: 'mem', pad: padStart }] : []),
|
|
164
|
+
];
|
|
165
|
+
const widths = Object.fromEntries(columns.map((col) => [col.key, w(col.key)]));
|
|
166
|
+
const lines = cells.map((c) => [c.dot, ...columns.map((col) => col.pad(c[col.key], widths[col.key]))]
|
|
167
|
+
.join(' ').replace(/\s+$/, ''));
|
|
168
|
+
return [head, ...warningLines, ...lines].join('\n');
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** SwiftBar reads `|` as the start of parameters, so a `|` or a newline inside text must not reach it. */
|
|
172
|
+
const clean = (s) => String(s).replace(/\|/g, '¦').replace(/\r?\n|\r/g, ' ');
|
|
173
|
+
|
|
174
|
+
export function renderSwiftBar(snapshot) {
|
|
175
|
+
const { totals, sessions } = snapshot;
|
|
176
|
+
const cpu = snapshot.resources && Number.isFinite(totals.cpuPct) ? ` · ${Math.round(totals.cpuPct)}%` : '';
|
|
177
|
+
const warnings = warningsOf(snapshot);
|
|
178
|
+
const alert = warnings.some((w) => w.level === 'critical') ? '🚨 ' : warnings.length ? '⚠ ' : '';
|
|
179
|
+
const title = `${alert}${mark(snapshot)} ${totals.busy}/${totals.sessions}${cpu}`;
|
|
180
|
+
const out = [clean(title), '---'];
|
|
181
|
+
if (!sessions.length) {
|
|
182
|
+
out.push('No agent sessions running');
|
|
183
|
+
} else {
|
|
184
|
+
for (const r of sessions) {
|
|
185
|
+
const parts = [r.name, agentText(r), stateText(r, snapshot.at)];
|
|
186
|
+
const label = activityLabel(r);
|
|
187
|
+
if (label) parts.push(label);
|
|
188
|
+
for (const extra of [ctxText(r), costText(r)]) if (extra) parts.push(extra);
|
|
189
|
+
if (snapshot.resources) parts.push(...[cpuText(r.cpuPct), formatMem(r.rssMb)].filter(Boolean));
|
|
190
|
+
out.push(`${clean(`${dot(r.state)} ${parts.join(' · ')}`)} | ${MONO}`);
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
out.push('---');
|
|
194
|
+
for (const w of warnings) {
|
|
195
|
+
const advice = w.advice?.[0];
|
|
196
|
+
out.push(`${clean(advice?.title ? `${w.chip} · ${advice.title}` : w.chip)} | ${MONO}`);
|
|
197
|
+
if (advice?.tip) out.push(`--${clean(advice.tip)} | ${MONO}`);
|
|
198
|
+
}
|
|
199
|
+
if (snapshot.resources) {
|
|
200
|
+
const cpuPart = Number.isFinite(totals.cpuPct) ? `CPU ${Math.round(totals.cpuPct)}% · ` : '';
|
|
201
|
+
out.push(`${cpuPart}${formatMem(totals.rssMb)} · ${totals.procs} processes | ${MONO}`);
|
|
202
|
+
}
|
|
203
|
+
for (const g of limitGroups(snapshot)) out.push(`${clean(`${g.name} limits: ${g.words.join(' · ')}`)} | ${MONO}`);
|
|
204
|
+
out.push('Refresh | refresh=true');
|
|
205
|
+
return out.join('\n');
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
const shQuote = (s) => `'${String(s).replace(/'/g, `'\\''`)}'`;
|
|
209
|
+
|
|
210
|
+
/** The SwiftBar/xbar plugin: a shell script that runs this CLI by absolute path. */
|
|
211
|
+
export function pluginScript({ execPath = process.execPath, cliEntry = CLI_ENTRY } = {}) {
|
|
212
|
+
return [
|
|
213
|
+
'#!/bin/sh',
|
|
214
|
+
'# sprag menu bar plugin for SwiftBar or xbar. Save it as sprag.5s.sh in the plugin folder and make it executable.',
|
|
215
|
+
`exec ${shQuote(execPath)} ${shQuote(cliEntry)} bar --swiftbar`,
|
|
216
|
+
'',
|
|
217
|
+
].join('\n');
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
const BAR_SUBCOMMANDS = new Set(['on', 'off', 'status', 'build']);
|
|
221
|
+
|
|
222
|
+
/** The last lines of a build error, indented under the message that names it. */
|
|
223
|
+
const indent = (text) => String(text ?? '').trim().split('\n').map((l) => ` ${l}`).join('\n');
|
|
224
|
+
|
|
225
|
+
/** `sprag bar on|off|status|build`: the menu bar app's switch, state and compile step. */
|
|
226
|
+
async function runSubcommand(sub, { hasFlag, deps }) {
|
|
227
|
+
const { stdout = process.stdout, stderr = process.stderr } = deps;
|
|
228
|
+
const ko = (deps.lang ?? (await import('../config.js')).userLanguage()) === 'ko';
|
|
229
|
+
const bar = deps.bar ?? (await import('../bar-app.js'));
|
|
230
|
+
const platform = deps.platform ?? process.platform;
|
|
231
|
+
const barDeps = deps.barDeps ?? {};
|
|
232
|
+
const say = (en, kor) => stdout.write(`${ko ? kor : en}\n`);
|
|
233
|
+
const fail = (en, kor) => { stderr.write(`${ko ? kor : en}\n`); process.exitCode = 1; };
|
|
234
|
+
const macOnly = () => say('The menu bar app only works on macOS.', '메뉴 막대 앱은 macOS에서만 동작합니다.');
|
|
235
|
+
const needTools = () => fail(
|
|
236
|
+
'Compiling the menu bar app needs the Xcode command line tools. Install them with: xcode-select --install',
|
|
237
|
+
'메뉴 막대 앱을 컴파일하려면 Xcode 명령줄 도구가 필요합니다. 설치: xcode-select --install',
|
|
238
|
+
);
|
|
239
|
+
const buildFailed = (r) => fail(
|
|
240
|
+
`Could not compile the menu bar app:\n${indent(r.error)}`,
|
|
241
|
+
`메뉴 막대 앱을 컴파일하지 못했습니다:\n${indent(r.error)}`,
|
|
242
|
+
);
|
|
243
|
+
|
|
244
|
+
if (sub === 'off') {
|
|
245
|
+
bar.setBarEnabled(false);
|
|
246
|
+
bar.stopBar(barDeps);
|
|
247
|
+
say('✓ The menu bar app is off and will not be started again. `sprag bar on` brings it back.',
|
|
248
|
+
'✓ 메뉴 막대 앱을 껐고 다시 시작하지 않습니다. 다시 켜려면 `sprag bar on` 을 실행하십시오.');
|
|
249
|
+
return;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
if (sub === 'on') {
|
|
253
|
+
bar.setBarEnabled(true);
|
|
254
|
+
if (platform !== 'darwin') { macOnly(); return; }
|
|
255
|
+
const paths = bar.barPaths(barDeps);
|
|
256
|
+
const running = bar.barRunning(barDeps);
|
|
257
|
+
if (running && running.version === paths.version) {
|
|
258
|
+
say(`✓ The menu bar app is already running (pid ${running.pid}, build ${running.version}).`,
|
|
259
|
+
`✓ 메뉴 막대 앱이 이미 실행 중입니다 (pid ${running.pid}, 빌드 ${running.version}).`);
|
|
260
|
+
return;
|
|
261
|
+
}
|
|
262
|
+
if (running) bar.stopBar(barDeps);
|
|
263
|
+
const exists = barDeps.exists ?? (await import('node:fs')).existsSync;
|
|
264
|
+
if (!exists(paths.binary)) {
|
|
265
|
+
if (!bar.findSwiftc(barDeps)) { needTools(); return; }
|
|
266
|
+
say('Compiling the menu bar app, which takes about half a minute...',
|
|
267
|
+
'메뉴 막대 앱을 컴파일합니다. 30초쯤 걸립니다...');
|
|
268
|
+
const r = bar.buildBar(barDeps);
|
|
269
|
+
if (r.skipped) {
|
|
270
|
+
say('Another build is already running. The app starts when it finishes.',
|
|
271
|
+
'다른 컴파일이 이미 진행 중입니다. 끝나면 앱이 시작됩니다.');
|
|
272
|
+
return;
|
|
273
|
+
}
|
|
274
|
+
if (!r.ok) {
|
|
275
|
+
if (r.error === 'no-toolchain') needTools();
|
|
276
|
+
else buildFailed(r);
|
|
277
|
+
return;
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
bar.launchBar(barDeps);
|
|
281
|
+
say('✓ The menu bar app is in the menu bar.', '✓ 메뉴 막대에 앱을 띄웠습니다.');
|
|
282
|
+
return;
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
if (sub === 'build') {
|
|
286
|
+
if (platform !== 'darwin') { macOnly(); return; }
|
|
287
|
+
const r = bar.buildBar(barDeps);
|
|
288
|
+
if (r.skipped) {
|
|
289
|
+
say('Another build is already running.', '다른 컴파일이 이미 진행 중입니다.');
|
|
290
|
+
return;
|
|
291
|
+
}
|
|
292
|
+
if (!r.ok) {
|
|
293
|
+
if (r.error === 'no-toolchain') needTools();
|
|
294
|
+
else buildFailed(r);
|
|
295
|
+
return;
|
|
296
|
+
}
|
|
297
|
+
say(`✓ Compiled the menu bar app in ${(r.ms / 1000).toFixed(1)}s.`, `✓ 메뉴 막대 앱을 ${(r.ms / 1000).toFixed(1)}초 만에 컴파일했습니다.`);
|
|
298
|
+
if (hasFlag('--then-launch') && bar.barEnabled() && !bar.barRunning(barDeps)) {
|
|
299
|
+
bar.launchBar(barDeps);
|
|
300
|
+
say('✓ The menu bar app is in the menu bar.', '✓ 메뉴 막대에 앱을 띄웠습니다.');
|
|
301
|
+
}
|
|
302
|
+
return;
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
// status
|
|
306
|
+
const paths = bar.barPaths(barDeps);
|
|
307
|
+
const on = bar.barEnabled();
|
|
308
|
+
say(`Menu bar app: ${on ? 'on' : 'off'}`, `메뉴 막대 앱: ${on ? '켜짐' : '꺼짐'}`);
|
|
309
|
+
const running = bar.barRunning(barDeps);
|
|
310
|
+
if (running) {
|
|
311
|
+
say(`Running: yes (pid ${running.pid}, build ${running.version ?? 'unknown'})`,
|
|
312
|
+
`실행 중: 예 (pid ${running.pid}, 빌드 ${running.version ?? '알 수 없음'})`);
|
|
313
|
+
} else {
|
|
314
|
+
say('Running: no', '실행 중: 아니요');
|
|
315
|
+
}
|
|
316
|
+
const exists = barDeps.exists ?? (await import('node:fs')).existsSync;
|
|
317
|
+
if (exists(paths.binary)) {
|
|
318
|
+
say(`Compiled (build ${paths.version}): yes (${paths.binary})`, `컴파일 (빌드 ${paths.version}): 있음 (${paths.binary})`);
|
|
319
|
+
} else {
|
|
320
|
+
say(`Compiled (build ${paths.version}): no`, `컴파일 (빌드 ${paths.version}): 없음`);
|
|
321
|
+
}
|
|
322
|
+
if (platform === 'darwin') {
|
|
323
|
+
const swiftc = bar.findSwiftc(barDeps);
|
|
324
|
+
say(swiftc ? `Swift toolchain: found (${swiftc})` : 'Swift toolchain: missing (xcode-select --install)',
|
|
325
|
+
swiftc ? `Swift 도구: 있음 (${swiftc})` : 'Swift 도구: 없음 (xcode-select --install)');
|
|
326
|
+
} else {
|
|
327
|
+
say('Swift toolchain: not needed, the app only works on macOS', 'Swift 도구: 필요 없음, 앱은 macOS에서만 동작합니다');
|
|
328
|
+
}
|
|
329
|
+
const state = bar.readBuildState(barDeps);
|
|
330
|
+
if (state?.error) {
|
|
331
|
+
say(`Last build error (${state.version ?? 'unknown build'}):\n${indent(state.error)}`,
|
|
332
|
+
`마지막 컴파일 오류 (${state.version ?? '알 수 없는 빌드'}):\n${indent(state.error)}`);
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
export async function run({ args = [], hasFlag, deps = {} }) {
|
|
337
|
+
const { collect = collectActivity, stdout = process.stdout, stderr = process.stderr } = deps;
|
|
338
|
+
if (BAR_SUBCOMMANDS.has(args[1])) return runSubcommand(args[1], { hasFlag, deps });
|
|
339
|
+
if (hasFlag('--plugin')) {
|
|
340
|
+
stdout.write(pluginScript());
|
|
341
|
+
return;
|
|
342
|
+
}
|
|
343
|
+
if (hasFlag('--settings')) {
|
|
344
|
+
// Loaded only here: the snapshot path runs every few seconds and needs none of it.
|
|
345
|
+
const settings = deps.settings ?? (await import('../bar-settings.js')).collectSettings;
|
|
346
|
+
stdout.write(`${JSON.stringify(settings(), null, 2)}\n`);
|
|
347
|
+
return;
|
|
348
|
+
}
|
|
349
|
+
if (hasFlag('--rules')) {
|
|
350
|
+
const rules = deps.rules ?? (await import('../bar-rules.js')).collectRules;
|
|
351
|
+
stdout.write(`${JSON.stringify(rules(), null, 2)}\n`);
|
|
352
|
+
return;
|
|
353
|
+
}
|
|
354
|
+
const json = hasFlag('--json');
|
|
355
|
+
const swiftbar = hasFlag('--swiftbar');
|
|
356
|
+
if (json && swiftbar) {
|
|
357
|
+
stderr.write('sprag bar: --json and --swiftbar cannot be combined\n');
|
|
358
|
+
process.exitCode = 2;
|
|
359
|
+
return;
|
|
360
|
+
}
|
|
361
|
+
const detail = hasFlag('--detail');
|
|
362
|
+
if (detail && !json) {
|
|
363
|
+
stderr.write('sprag bar: --detail needs --json\n');
|
|
364
|
+
process.exitCode = 2;
|
|
365
|
+
return;
|
|
366
|
+
}
|
|
367
|
+
const snapshot = detail ? collect({ detail: true }) : collect();
|
|
368
|
+
const text = json ? JSON.stringify(snapshot, null, 2) : swiftbar ? renderSwiftBar(snapshot) : renderText(snapshot);
|
|
369
|
+
stdout.write(`${text}\n`);
|
|
370
|
+
}
|
package/src/commands/delegate.js
CHANGED
|
@@ -190,6 +190,7 @@ async function agentsCommand(action, lang) {
|
|
|
190
190
|
const r = action === 'on' ? da.syncDelegationAgents() : da.removeDelegationAgents();
|
|
191
191
|
await rerender();
|
|
192
192
|
report(r);
|
|
193
|
+
if (r.createdDir) console.log(da.firstInstallCliLine({ lang: ko ? 'ko' : 'en' }));
|
|
193
194
|
console.log(action === 'on'
|
|
194
195
|
? (ko ? '위임 전용 에이전트를 켰습니다. 래칫 문구가 에이전트 이름으로 다시 만들어졌습니다.' : 'Delegation agents are on. The ratchet wording was re-rendered with the agent names.')
|
|
195
196
|
: (ko ? '위임 전용 에이전트를 껐습니다. 래칫 문구가 model 지정 방식으로 다시 만들어졌습니다.' : 'Delegation agents are off. The ratchet wording was re-rendered with plain model tiers.'));
|
package/src/commands/feedback.js
CHANGED
|
@@ -53,10 +53,10 @@ function metadata(version) {
|
|
|
53
53
|
|
|
54
54
|
function tryGhCli(title, body) {
|
|
55
55
|
try {
|
|
56
|
-
const auth = spawnSync('gh', ['auth', 'status'], { encoding: 'utf8', timeout: 10_000 });
|
|
56
|
+
const auth = spawnSync('gh', ['auth', 'status'], { encoding: 'utf8', timeout: 10_000, windowsHide: true });
|
|
57
57
|
if (auth.status !== 0) return null;
|
|
58
58
|
const res = spawnSync('gh', ['issue', 'create', '-R', REPO, '--title', title, '--body', body],
|
|
59
|
-
{ encoding: 'utf8', timeout: 30_000 });
|
|
59
|
+
{ encoding: 'utf8', timeout: 30_000, windowsHide: true });
|
|
60
60
|
if (res.status !== 0) { debug('feedback:gh', res.stderr); return null; }
|
|
61
61
|
const url = String(res.stdout).trim().split('\n').pop();
|
|
62
62
|
return { transport: 'gh', url };
|
package/src/commands/install.js
CHANGED
|
@@ -85,6 +85,7 @@ export async function run({ hasFlag }) {
|
|
|
85
85
|
const r = installAll({ force });
|
|
86
86
|
print('skill', r.skill);
|
|
87
87
|
print('SessionStart hook (route-scan)', r.sessionStartHook);
|
|
88
|
+
print('SessionStart hook (compaction notice)', r.compactNoticeHook);
|
|
88
89
|
print('PostToolUse hook (delegation rescan)', r.delegationHook);
|
|
89
90
|
print('mod (delegation meter, Claude Code 2.1.287+)', r.delegationMeterMod);
|
|
90
91
|
if (r.delegationMeterMod.reason) console.log(` ${r.delegationMeterMod.reason}`);
|
|
@@ -420,11 +421,13 @@ export async function run({ hasFlag }) {
|
|
|
420
421
|
// Presets now live in ratchet-preset.md. Moving the ones older versions
|
|
421
422
|
// appended to ratchet.md comes first, so they are not offered again below.
|
|
422
423
|
try {
|
|
423
|
-
const
|
|
424
|
+
const da = await import('../delegation-agents.js');
|
|
425
|
+
const d = da.syncDelegationAgents();
|
|
424
426
|
if (d.written.length) {
|
|
425
427
|
console.log(lang === 'ko'
|
|
426
428
|
? ` agents: 위임 전용 에이전트 ${d.written.length}개를 ~/.claude/agents 에 설치했습니다 (MCP 도구 없음).`
|
|
427
429
|
: ` agents: installed ${d.written.length} delegation-only agent(s) in ~/.claude/agents (no MCP tools).`);
|
|
430
|
+
if (d.createdDir) console.log(da.firstInstallCliLine({ lang }));
|
|
428
431
|
}
|
|
429
432
|
} catch (e) {
|
|
430
433
|
debug('install:delegation-agents', e);
|
package/src/commands/last.js
CHANGED
|
@@ -21,7 +21,7 @@
|
|
|
21
21
|
* - HH:MM:SS ✓ 5H cap warning resolved ← skip
|
|
22
22
|
* - HH:MM:SS 📝 handoff written: ... ← skip
|
|
23
23
|
*/
|
|
24
|
-
function findLatestWarning(historyEntries, chipToCodes) {
|
|
24
|
+
export function findLatestWarning(historyEntries, chipToCodes) {
|
|
25
25
|
const warnings = [];
|
|
26
26
|
for (const { date, content } of historyEntries) {
|
|
27
27
|
const lines = content.split('\n');
|