sprag-cli 3.131.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/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/codex/panel.js +1 -7
- package/src/commands/bar.js +370 -0
- package/src/commands/install.js +1 -0
- package/src/commands/last.js +1 -1
- package/src/commands/route-scan.js +29 -0
- package/src/commands/uninstall.js +2 -0
- package/src/ctx-window-cache.js +11 -8
- package/src/history.js +18 -1
- package/src/installer.js +43 -0
- package/src/session-cache.js +19 -0
- package/src/statusline-guard.js +17 -0
- 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;
|
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/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}`);
|
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');
|
|
@@ -48,6 +48,17 @@ function readPackageVersion() {
|
|
|
48
48
|
}
|
|
49
49
|
}
|
|
50
50
|
|
|
51
|
+
/**
|
|
52
|
+
* macOS menu bar app: start it, or start building it, when a session starts.
|
|
53
|
+
* Called after the hook has printed everything, and it can neither throw nor
|
|
54
|
+
* delay the hook past a few file reads: the compile runs in a detached child.
|
|
55
|
+
*/
|
|
56
|
+
async function startBarApp() {
|
|
57
|
+
try {
|
|
58
|
+
(await import('../bar-app.js')).ensureBar();
|
|
59
|
+
} catch (e) { debug('route-scan:bar-app', e); }
|
|
60
|
+
}
|
|
61
|
+
|
|
51
62
|
export async function run({ args, hasFlag, numArg }) {
|
|
52
63
|
const rs = await import('../route-scan.js');
|
|
53
64
|
const { userLanguage } = await import('../config.js');
|
|
@@ -292,6 +303,22 @@ export async function run({ args, hasFlag, numArg }) {
|
|
|
292
303
|
return;
|
|
293
304
|
}
|
|
294
305
|
|
|
306
|
+
// --hook-compact: SessionStart hook for source "compact". Tells the model
|
|
307
|
+
// that a context warning it received before the compaction is out of date.
|
|
308
|
+
// Read-only and instant: no scan, no cache read, no child process.
|
|
309
|
+
if (hasFlag('--hook-compact')) {
|
|
310
|
+
try {
|
|
311
|
+
const payload = readStdinJson() || {};
|
|
312
|
+
if (payload.source !== undefined && payload.source !== 'compact') return;
|
|
313
|
+
const { compactionNotice } = await import('../brief.js');
|
|
314
|
+
const text = compactionNotice({ sessionId: payload.session_id, lang });
|
|
315
|
+
if (text) console.log(text);
|
|
316
|
+
} catch (e) {
|
|
317
|
+
debug('route-scan:compact-notice', e);
|
|
318
|
+
}
|
|
319
|
+
return;
|
|
320
|
+
}
|
|
321
|
+
|
|
295
322
|
// --hook: SessionStart hook mode. Never scans inline (session start must
|
|
296
323
|
// stay fast) — reads the cache, kicks a detached refresh when stale, and
|
|
297
324
|
// prints delegation-candidate context for the new session.
|
|
@@ -461,6 +488,7 @@ export async function run({ args, hasFlag, numArg }) {
|
|
|
461
488
|
if (doc2mdBlock) console.log(doc2mdBlock);
|
|
462
489
|
if (koreanBlock) console.log(koreanBlock);
|
|
463
490
|
if (cohesionBlock) console.log(cohesionBlock);
|
|
491
|
+
await startBarApp();
|
|
464
492
|
return; // nothing else to inject
|
|
465
493
|
}
|
|
466
494
|
if (secretsBlock) console.log(secretsBlock);
|
|
@@ -550,6 +578,7 @@ export async function run({ args, hasFlag, numArg }) {
|
|
|
550
578
|
...reviewRules.map((r) => `health|${r.signature}|${r.scope}`),
|
|
551
579
|
]);
|
|
552
580
|
} catch (e) { debug('route-scan:seed-briefed', e); /* worst case is one duplicate brief */ }
|
|
581
|
+
await startBarApp();
|
|
553
582
|
return;
|
|
554
583
|
}
|
|
555
584
|
|
|
@@ -29,6 +29,8 @@ export async function run({ hasFlag, args = [] }) {
|
|
|
29
29
|
// The Cowork copies and the settings.json exclude entry are ours too.
|
|
30
30
|
try { (await import('../cowork-sync.js')).removeCoworkRatchets(); } catch { /* uninstall goes on */ }
|
|
31
31
|
try { (await import('../delegation-agents.js')).removeDelegationAgents(); } catch { /* uninstall goes on */ }
|
|
32
|
+
// The menu bar app and what it compiled into the data directory.
|
|
33
|
+
try { (await import('../bar-app.js')).removeBarFiles(); } catch { /* uninstall goes on */ }
|
|
32
34
|
|
|
33
35
|
if (r.removed.length === 0) {
|
|
34
36
|
console.log(lang === 'ko' ? '설치된 항목이 없습니다.' : 'Nothing was installed.');
|
package/src/ctx-window-cache.js
CHANGED
|
@@ -32,9 +32,9 @@ export function ctxWindowCachePath() {
|
|
|
32
32
|
return join(userDataDir(), 'ctx-window.json');
|
|
33
33
|
}
|
|
34
34
|
|
|
35
|
-
function load() {
|
|
35
|
+
function load(path = ctxWindowCachePath()) {
|
|
36
36
|
try {
|
|
37
|
-
const s = JSON.parse(readFileSync(
|
|
37
|
+
const s = JSON.parse(readFileSync(path, 'utf8'));
|
|
38
38
|
return s && s.sessions && typeof s.sessions === 'object' && !Array.isArray(s.sessions) ? s : { sessions: {} };
|
|
39
39
|
} catch {
|
|
40
40
|
return { sessions: {} };
|
|
@@ -58,10 +58,13 @@ export function recordLiveWindow(sessionId, size, now = Date.now(), model = null
|
|
|
58
58
|
return true;
|
|
59
59
|
}
|
|
60
60
|
|
|
61
|
-
/**
|
|
62
|
-
|
|
61
|
+
/**
|
|
62
|
+
* The recorded window for a session, or null when the statusline never reported one.
|
|
63
|
+
* `file` reads another copy of the state file (`sprag bar` passes its own data folder's).
|
|
64
|
+
*/
|
|
65
|
+
export function liveWindowFor(sessionId, file = ctxWindowCachePath()) {
|
|
63
66
|
if (typeof sessionId !== 'string' || sessionId === '') return null;
|
|
64
|
-
const s = load().sessions[sessionId];
|
|
67
|
+
const s = load(file).sessions[sessionId];
|
|
65
68
|
return s && validSize(s.size) ? s.size : null;
|
|
66
69
|
}
|
|
67
70
|
|
|
@@ -98,10 +101,10 @@ export function liveWindowsByModel() {
|
|
|
98
101
|
.map((s) => ({ model: s.model, size: s.size, ts: s.ts }));
|
|
99
102
|
}
|
|
100
103
|
|
|
101
|
-
/** The model id a session's statusline payload reported, or null. */
|
|
102
|
-
export function liveModelFor(sessionId) {
|
|
104
|
+
/** The model id a session's statusline payload reported, or null. `file` is as in liveWindowFor. */
|
|
105
|
+
export function liveModelFor(sessionId, file = ctxWindowCachePath()) {
|
|
103
106
|
if (typeof sessionId !== 'string' || sessionId === '') return null;
|
|
104
|
-
const s = load().sessions[sessionId];
|
|
107
|
+
const s = load(file).sessions[sessionId];
|
|
105
108
|
return s && typeof s.model === 'string' && s.model !== '' ? s.model : null;
|
|
106
109
|
}
|
|
107
110
|
|
package/src/history.js
CHANGED
|
@@ -57,6 +57,23 @@ function loadState() {
|
|
|
57
57
|
}
|
|
58
58
|
}
|
|
59
59
|
|
|
60
|
+
/**
|
|
61
|
+
* The chip the statusline last announced and when, for readers outside this
|
|
62
|
+
* module (the menu bar snapshot). Missing or broken file gives both null.
|
|
63
|
+
* loadState() keeps its own shape: it also carries the cap_* slots.
|
|
64
|
+
*/
|
|
65
|
+
export function readChipState(dir = BASE_DIR) {
|
|
66
|
+
try {
|
|
67
|
+
const s = JSON.parse(readFileSync(join(dir, 'last-chip.json'), 'utf8'));
|
|
68
|
+
return {
|
|
69
|
+
chip: typeof s?.chip === 'string' ? s.chip : null,
|
|
70
|
+
ts: typeof s?.ts === 'string' ? s.ts : null,
|
|
71
|
+
};
|
|
72
|
+
} catch {
|
|
73
|
+
return { chip: null, ts: null };
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
60
77
|
function saveState(state) {
|
|
61
78
|
ensureDir(BASE_DIR);
|
|
62
79
|
writeFileSync(STATE_PATH, JSON.stringify(state) + '\n');
|
|
@@ -93,7 +110,7 @@ function chipKo(chip) {
|
|
|
93
110
|
* "session {ID}: CODE_A, CODE_B"
|
|
94
111
|
* Anything else falls through unchanged.
|
|
95
112
|
*/
|
|
96
|
-
function detailKo(detail) {
|
|
113
|
+
export function detailKo(detail) {
|
|
97
114
|
if (!detail) return detail;
|
|
98
115
|
// The threshold moved from 200k to 500k in v3.32, so both spellings have to
|
|
99
116
|
// resolve: history files written by older versions still carry the old one.
|