Shows whether Claude is working, waiting on you or done, and context, rate-limit and cost usage, above the prompt

Claude Code 입력창 위에 지금 작업 상태와 사용량을 보여주는 모드입니다.
● 작업 중 · 1분 23초 · 도구 7회
지금 (15초째): 명령 실행 — Run tests
컨텍스트 ███░░░░░░░ [ 압축 ] 5시간 ██░░░░░░░░ 7일 █░░░░░░░░░ 초기화까지 3일 0시간
| 상태 | 보이는 모습 |
|---|---|
| 작업 중 | ● 작업 중 · 1분 23초 · 도구 7회 / 지금 (15초째): 명령 실행 — Run tests. 점(●○)이 1초마다 바뀌면 일하는 중입니다. 도구를 쓰지 않을 때는 생각하거나 답을 쓰는 중…이라고 나옵니다. 뒤에서 도는 작업이나 예약이 있으면 흐린 셋째 줄이 붙습니다: ◌ 백그라운드 (3분째): 명령 실행 — Run dev server, ◌ 백그라운드: 명령 2개 · 모니터 1개 · 예약 1개 (3분 후). |
| 나를 기다림 | ! 나를 기다리는 중 · 5초째 / 질문에 답해 주세요, 계획을 확인해 주세요. 노란색이고 점이 멈춥니다. 시간은 기다리기 시작한 때부터 잽니다. |
| 승인 요청 | ! 승인 요청이 떴어요 · 3초 전 / 명령 실행 — npm install · 승인했다면 실행 중이에요. 도우미(서브에이전트)가 띄운 승인 요청도 ! 도우미가 승인 요청을 띄웠어요로 보여 줍니다. |
| 끝남 | ✓ 끝났어요 · 2분 5초 걸림 · 도구 12회 · 다음 지시를 기다려요 |
| 중단·오류 | ■ 중단했어요 · …, ✕ 오류로 멈췄어요 · 대화에 뜬 안내를 확인해 주세요, ✕ 요청을 거절했어요 · 다르게 말해 보세요 |
| 백그라운드 남음 | 본 작업이 끝나도 뒤에서 도는 것이 있으면 한 줄이 붙습니다. 명령·모니터·워크플로 하나면 ◌ 백그라운드 (12분째): 명령 실행 — Run dev server, 여럿이면 ◌ 백그라운드에서 아직 일하는 중 · 명령 2개 · 모니터 1개입니다. 도우미(서브에이전트)가 함께 일하면 ● 백그라운드에서 아직 일하는 중 · 도우미 1명 · 명령 2개, 도우미만 남았으면 ○ 백그라운드 도우미 2명은 아직 일하는 중입니다. |
| 예약 | /loop, 예약 만들기(CronCreate), 다음 실행 예약(ScheduleWakeup)이 걸려 있으면 ◷ 4분 후 실행 · 배포 상태 확인, 여럿이면 ◷ 예약 3개 · 다음은 곧 실행이 붙습니다. |
| 알림·예약으로 시작 | 백그라운드 작업이 끝났다는 알림으로 Claude가 일을 시작하면 ● 알림 받고 작업 중 · …, 예약한 시각이 되어 시작하면 ● 예약 작업 중 · …입니다. 예약으로 시작한 작업은 오래 걸려도 끝났다고 알리지 않습니다. |
작업 중…만 보이고, 다음 작업부터 자세히 보입니다.지금 (37초째, 승인 요청이 떴었어요): …라고 흐리게 보여 줍니다.✓ 끝났어요 줄을 보면 됩니다.◌와 ◷ 줄은 깜빡이지 않습니다. Claude가 일하는 것이 아니라, 명령이 돌거나 예약이 기다리고 있다는 뜻이기 때문입니다.◷ 반복 예약 · …처럼 시각 없이 보입니다./clear를 하면 백그라운드·예약 줄이 비었다가, 다음 답변이 끝날 때 아직 남은 것이 다시 채워집니다.23% · 2시간 13분 후 초기화처럼 초기화까지 남은 시간도 함께 보입니다. 데스크톱 앱에서는 막대 위에 뜨는 카드에 글자로, 터미널에서는 막대 자리에 반전 글자로 보입니다.[ 압축 ] 버튼은 답변이 끝났고 컨텍스트에 내용이 있을 때만 켜집니다. 꺼져 있을 때는 흐리게 보이고, 누르면 왜 안 되는지 알려 줍니다. 켜졌을 때 누르면 "압축하시겠습니까? 예 / 아니오"를 묻고, 예를 고르면 /compact와 같이 압축합니다.22시간 47분, 한 시간 미만이면 13분으로 바뀌고 1분마다 갱신됩니다.$0.50)을 보여 줍니다. 구독 계정에서는 실제로 청구되는 돈이 아니라서 보이지 않습니다.버전마다 바뀐 내용은 CHANGELOG.md에 있습니다.
터미널에서 Claude Code를 열고 입력합니다.
/plugin install usage-mods --marketplace akixi-maison/usage-mods
Add marketplace?에 y, 설치 범위는 User를 고르면 모든 프로젝트에 적용됩니다.
hooks/register.tsx 1368 lines1import { atom, read, update } from 'claude-code'
2import type {
3 AgentInfo,
4 AgentStatus,
5 EngineInterface,
6 Register,
7 SessionMeasureInput,
8 Timer,
9 ToolCallInput,
10 ToolCallResult,
11 TurnCompleteInput,
12} from 'claude-code'
13
14import type { BackgroundKind, BackgroundTask, HelperAsk, Phase, RunningTool, Schedule, Trigger, Usage, Work } from '../types'
15
16const IDLE_WORK: Work = { phase: 'idle', startedAt: 0, durationMs: 0, tools: 0, running: [], stopReason: '' }
17
18const usage = atom({ plugin: 'usage-mods', key: 'usage' } as const, null)
19const isCompacting = atom({ plugin: 'usage-mods', key: 'isCompacting' } as const, false)
20const isTurnRunning = atom({ plugin: 'usage-mods', key: 'isTurnRunning' } as const, false)
21const clockNow = atom({ plugin: 'usage-mods', key: 'now' } as const, 0)
22const work = atom({ plugin: 'usage-mods', key: 'work' } as const, IDLE_WORK)
23const beat = atom({ plugin: 'usage-mods', key: 'beat' } as const, false)
24const helpers = atom({ plugin: 'usage-mods', key: 'helpers' } as const, [] as string[])
25const helperTurns = atom({ plugin: 'usage-mods', key: 'helperTurns' } as const, [] as string[])
26const helperAsks = atom({ plugin: 'usage-mods', key: 'helperAsks' } as const, [] as HelperAsk[])
27const tasks = atom({ plugin: 'usage-mods', key: 'tasks' } as const, [] as BackgroundTask[])
28const schedules = atom({ plugin: 'usage-mods', key: 'schedules' } as const, [] as Schedule[])
29
30const LABELS: Record<string, string> = { five_hour: '5시간', seven_day: '7일', spend_limit: '한도' }
31
32const toUsage = (m: Pick<SessionMeasureInput, 'context' | 'rateLimits' | 'cost'>): Usage => ({
33 contextPercent: m.context.percent,
34 limits: m.rateLimits.map(r => ({ kind: r.kind, percentUsed: r.percentUsed, resetsAt: r.resetsAt })),
35 usd: m.cost?.usd,
36})
37
38const BAR_WIDTH = 10
39
40export type Meter = { key: string; label: string; percent: number }
41
42export const meters = (u: Usage): Meter[] => [
43 { key: 'context', label: '컨텍스트', percent: u.contextPercent ?? 0 },
44 ...u.limits.map(l => ({ key: l.kind, label: LABELS[l.kind] ?? l.kind, percent: l.percentUsed })),
45]
46
47export const bar = (percent: number): string => {
48 const filled = Math.round((Math.min(Math.max(percent, 0), 100) / 100) * BAR_WIDTH)
49 return '█'.repeat(filled) + '░'.repeat(BAR_WIDTH - filled)
50}
51
52/** The theme's own colors for a meter, so the band follows the person's theme. */
53export const meterColor = (percent: number): 'error' | 'warning' | 'success' =>
54 percent >= 90 ? 'error' : percent >= 80 ? 'warning' : 'success'
55
56// Off the terminal a bar is a picture: a rounded track and its fill, in CSS pixels. A picture cannot
57// follow the theme, so the track is a see-through grey and the fills read on light and dark alike.
58export const BAR_PX = { width: 96, height: 6 }
59const BAR_FILL: Record<ReturnType<typeof meterColor>, string> = { success: '#2f9e57', warning: '#c27c0e', error: '#d93f3f' }
60
61/** The bar as SVG: the fill in proportion, clamped, never thinner than its own height once above 0. */
62export const barSvg = (percent: number, color: ReturnType<typeof meterColor>): string => {
63 const { width, height } = BAR_PX
64 const p = Math.min(Math.max(percent, 0), 100)
65 const filled = p === 0 ? 0 : Math.max((p / 100) * width, height)
66 const rect = (w: number, paint: string) =>
67 `<rect width="${Number(w.toFixed(1))}" height="${height}" rx="${height / 2}" ${paint}/>`
68 return (
69 `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}">` +
70 rect(width, 'fill="#808080" fill-opacity="0.25"') +
71 (filled === 0 ? '' : rect(filled, `fill="${BAR_FILL[color]}"`)) +
72 '</svg>'
73 )
74}
75
76const center = (text: string): string => {
77 const pad = Math.max(BAR_WIDTH - text.length, 0)
78 const left = Math.floor(pad / 2)
79 return ' '.repeat(left) + text + ' '.repeat(pad - left)
80}
81
82/** `$.session.compact` refuses in a headless (SDK) session, which is how the desktop app runs Claude Code. */
83export const isHeadlessRefusal = (message: string): boolean => /headless/i.test(message)
84
85/**
86 * Whether a refused compaction is sent as a /compact prompt instead: in a session with no person at
87 * the prompt (the desktop app, an SDK host) whatever the reason, or when the refusal says headless.
88 */
89export const shouldSendCompact = (message: string, isInteractive: boolean): boolean =>
90 !isInteractive || isHeadlessRefusal(message)
91
92/**
93 * Compaction runs between turns over a conversation the model has answered:
94 * not while a turn runs, not while one is under way, and not before the live
95 * window's first response (a fresh or just-compacted session has no fill yet).
96 */
97export const canCompact = (u: Usage, isWorking: boolean, compacting: boolean): boolean =>
98 !isWorking && !compacting && (u.contextPercent ?? 0) > 0
99
100const MINUTE = 60_000
101const HOUR = 60 * MINUTE
102const DAY = 24 * HOUR
103
104/** `3일 0시간` from a day out, `2시간 13분` within one, `13분` within the hour. */
105export const timeLeft = (resetsAt: string, now: number): string => timeLeftMs(Date.parse(resetsAt) - now)
106
107/** The same words for a span of milliseconds. */
108export const timeLeftMs = (span: number): string => {
109 const ms = Math.max(0, span)
110 const days = Math.floor(ms / DAY)
111 const hours = Math.floor((ms % DAY) / HOUR)
112 const minutes = Math.floor((ms % HOUR) / MINUTE)
113 return days > 0 ? `${days}일 ${hours}시간` : hours > 0 ? `${hours}시간 ${minutes}분` : `${minutes}분`
114}
115
116/** `초기화까지 3일 0시간`; null while the 7-day window has no reset time. */
117export const weeklyReset = (u: Usage, now: number): string | null => {
118 const resetsAt = u.limits.find(l => l.kind === 'seven_day')?.resetsAt
119 return resetsAt === undefined ? null : `초기화까지 ${timeLeft(resetsAt, now)}`
120}
121
122/** Whether the account has a subscription's 5-hour or 7-day limits, which are what bound its use. */
123export const isSubscription = (u: Usage): boolean =>
124 u.limits.some(l => l.kind === 'five_hour' || l.kind === 'seven_day')
125
126/** `$0.50`, the session's cost at API prices; null on a subscription, which is not billed by it. */
127export const costText = (u: Usage): string | null =>
128 u.usd === undefined || isSubscription(u) ? null : `$${u.usd.toFixed(2)}`
129
130export type Hover = { percent: string; reset?: string }
131
132/** What hovering a meter shows: the percent, and when its window resets where it has a reset time. */
133export const hoverParts = (u: Usage, m: Meter, now: number): Hover => {
134 const resetsAt = u.limits.find(l => l.kind === m.key)?.resetsAt
135 return { percent: `${m.percent}%`, reset: resetsAt === undefined ? undefined : `${timeLeft(resetsAt, now)} 후 초기화` }
136}
137
138/** The hover as one line, `23% · 2시간 13분 후 초기화`. */
139export const hoverText = (u: Usage, m: Meter, now: number): string => {
140 const { percent, reset } = hoverParts(u, m, now)
141 return reset === undefined ? percent : `${percent} · ${reset}`
142}
143
144// Moves the clock the countdown reads, so the band redraws once a minute.
145const tick = async ($: EngineInterface) => {
146 const now = await $.clock.now()
147 await update($, clockNow, () => now)
148}
149
150// --- Work status -------------------------------------------------------------------------------
151// The rows above the meters: whether the main turn is at work, waits on the person, or has ended,
152// and how many helpers (subagents) still work.
153
154/** A permission prompt counts as waiting on the person this long; past it the call may well run. */
155export const ASK_FRESH_MS = 30_000
156/** An ended turn at least this long is announced: a notification, or a toast where none can be sent. */
157export const ANNOUNCE_AFTER_MS = 30_000
158
159type ToolWords = { label: string; needsMe?: boolean; detail?: (pick: (key: string) => string) => string }
160
161const fileName = (path: string) => path.split(/[\\/]/).filter(Boolean).pop() ?? path
162const hostOf = (url: string) => url.replace(/^[a-z]+:\/\//i, '').split('/')[0] ?? url
163
164const TOOL_WORDS: Record<string, ToolWords> = {
165 Bash: { label: '명령 실행', detail: pick => pick('description') || pick('command') },
166 PowerShell: { label: '명령 실행', detail: pick => pick('description') || pick('command') },
167 Read: { label: '파일 읽기', detail: pick => fileName(pick('file_path')) },
168 Edit: { label: '파일 고치기', detail: pick => fileName(pick('file_path')) },
169 Write: { label: '파일 쓰기', detail: pick => fileName(pick('file_path')) },
170 NotebookEdit: { label: '노트 파일 고치기', detail: pick => fileName(pick('notebook_path')) },
171 Grep: { label: '내용 찾기', detail: pick => pick('pattern') },
172 Glob: { label: '파일 찾기', detail: pick => pick('pattern') },
173 WebFetch: { label: '웹 페이지 읽기', detail: pick => hostOf(pick('url')) },
174 WebSearch: { label: '웹 검색', detail: pick => pick('query') },
175 Agent: { label: '도우미에게 맡기기', detail: pick => pick('description') },
176 Task: { label: '도우미에게 맡기기', detail: pick => pick('description') },
177 Workflow: { label: '도우미 여러 명 돌리기' },
178 Monitor: { label: '지켜보기 시작', detail: pick => pick('description') },
179 TaskStop: { label: '백그라운드 작업 멈추기', detail: pick => pick('task_id') || pick('shell_id') },
180 CronCreate: { label: '예약 만들기', detail: pick => promptWords(pick('prompt')) },
181 CronDelete: { label: '예약 지우기', detail: pick => pick('id') },
182 CronList: { label: '예약 확인' },
183 ScheduleWakeup: { label: '다음 실행 예약', detail: pick => pick('reason') || promptWords(pick('prompt')) },
184 Skill: { label: '스킬 불러오기', detail: pick => pick('skill') },
185 ToolSearch: { label: '도구 찾기' },
186 TodoWrite: { label: '할 일 정리' },
187 AskUserQuestion: { label: '질문에 답해 주세요', needsMe: true },
188 ExitPlanMode: { label: '계획을 확인해 주세요', needsMe: true },
189}
190
191/** Plain words for a tool call: what it does, and what it works on. */
192export const describeTool = (tool: string, input: unknown): Pick<RunningTool, 'label' | 'detail' | 'needsMe'> => {
193 const args = typeof input === 'object' && input !== null ? (input as Record<string, unknown>) : {}
194 const pick = (key: string) => {
195 const value = args[key]
196 return typeof value === 'string' ? value : ''
197 }
198 const words = TOOL_WORDS[tool]
199 const isBackground = (tool === 'Bash' || tool === 'PowerShell') && args['run_in_background'] === true
200 const label = isBackground
201 ? '백그라운드로 명령 실행'
202 : tool === 'ScheduleWakeup' && args['stop'] === true
203 ? '반복 멈추기'
204 : words?.label ?? `도구 사용: ${/^mcp__.+?__(.+)$/.exec(tool)?.[1] ?? tool}`
205 const detail = (words?.detail?.(pick) ?? '').replace(/\s+/g, ' ').trim().slice(0, 80)
206 return { label, detail, needsMe: words?.needsMe === true }
207}
208
209/** `45초`, `1분 23초`, `1시간 2분`. */
210export const elapsed = (ms: number): string => {
211 const s = Math.max(0, Math.round(ms / 1000))
212 if (s < 60) return `${s}초`
213 const m = Math.floor(s / 60)
214 if (m < 60) return s % 60 > 0 ? `${m}분 ${s % 60}초` : `${m}분`
215 return m % 60 > 0 ? `${Math.floor(m / 60)}시간 ${m % 60}분` : `${Math.floor(m / 60)}시간`
216}
217
218export type StatusTone = 'claude' | 'warning' | 'success' | 'error' | 'dim'
219export type StatusRow = { text: string; tone: StatusTone; bold: boolean }
220export type StatusInput = {
221 work: Work
222 isWorking: boolean
223 now: number
224 beat: boolean
225 helpers: number
226 helperAsks: readonly HelperAsk[]
227 isViewingHelper: boolean
228 /** Background commands, monitors and workflow runs still at work. */
229 tasks?: readonly BackgroundTask[]
230 /** Cron jobs and wakeups that will start a turn later. */
231 schedules?: readonly Schedule[]
232}
233
234const what = (one: { label: string; detail: string }) => (one.detail ? `${one.label} — ${one.detail}` : one.label)
235
236/** Background tasks the band keeps at most; the oldest go first. */
237const MAX_TASKS = 50
238/** A snapshot taken this soon after the mod recorded a task may not list it yet. */
239export const SNAPSHOT_GRACE_MS = 2000
240
241const KIND_WORDS: Record<BackgroundKind, string> = { shell: '명령', monitor: '모니터', workflow: '워크플로' }
242const KIND_LABELS: Record<BackgroundKind, string> = { shell: '명령 실행', monitor: '지켜보기', workflow: '워크플로' }
243
244const asRecord = (value: unknown): Record<string, unknown> =>
245 typeof value === 'object' && value !== null ? (value as Record<string, unknown>) : {}
246const str = (value: unknown) => (typeof value === 'string' ? value : '')
247/** One line, cut short, without the engine's `... [+N chars]` clipping mark. */
248const clip = (text: string) => text.replace(/\.\.\. \[\+\d+ chars\]$/, '').replace(/\s+/g, ' ').trim().slice(0, 80)
249
250/** The background task a settled call started, read from the tool's own record; null for any other call. */
251export const taskFromCall = (tool: string, input: unknown, record: unknown, startedAt: number, now: number): BackgroundTask | null => {
252 const r = asRecord(record)
253 const { detail } = describeTool(tool, input)
254 const base = { detail, startedAt, endsBy: 0, seenAt: now }
255 if (tool === 'Bash' || tool === 'PowerShell') {
256 // Run in the background from the start, by Ctrl+B or past its timeout: the record says which, the id is the same.
257 const id = str(r['backgroundTaskId'])
258 // One that ends with its caller's final response sends no notification: it is not left running.
259 return id === '' || r['backgroundEndsWithFinalResponse'] === true ? null : { ...base, id, kind: 'shell', label: KIND_LABELS.shell }
260 }
261 if (tool === 'Monitor') {
262 const id = str(r['taskId'])
263 const timeoutMs = typeof r['timeoutMs'] === 'number' ? r['timeoutMs'] : 0
264 const endsBy = r['persistent'] === true || timeoutMs <= 0 ? 0 : startedAt + timeoutMs
265 return id === '' ? null : { ...base, id, kind: 'monitor', label: KIND_LABELS.monitor, endsBy }
266 }
267 if (tool === 'Workflow') {
268 const id = str(r['taskId'])
269 const isRemote = r['status'] === 'remote_launched' || r['taskType'] === 'remote_agent'
270 const label = isRemote ? '원격 워크플로' : KIND_LABELS.workflow
271 return id === '' ? null : { ...base, id, kind: 'workflow', label, detail: clip(str(r['workflowName'])) }
272 }
273 return null
274}
275
276/** The task a settled TaskStop stopped; null for any other call. */
277export const stoppedTaskId = (tool: string, record: unknown): string | null =>
278 tool === 'TaskStop' ? str(asRecord(record)['task_id']) || null : null
279
280const ENDED = new Set(['completed', 'failed', 'killed', 'stopped', 'cancelled', 'canceled', 'error'])
281
282/**
283 * Ids of the tasks a notification says have ended: each `<task-notification>` block's `<task-id>`
284 * whose `<status>` is an ending one. A monitor's events carry none and end nothing.
285 */
286export const endedTaskIds = (text: string): string[] =>
287 text
288 .split('<task-notification>')
289 .slice(1)
290 .flatMap(block => {
291 const id = /<task-id>([^<]+)<\/task-id>/.exec(block)?.[1]?.trim() ?? ''
292 const status = /<status>([^<]+)<\/status>/.exec(block)?.[1]?.trim().toLowerCase() ?? ''
293 return id !== '' && ENDED.has(status) ? [id] : []
294 })
295
296/** The in-flight background work a stop's snapshot lists (`background_tasks`), as much of it as the mod reads. */
297export type TaskSnapshot = { id: string; type: string; description: string; command?: string; name?: string }
298
299const SNAPSHOT_KINDS: Record<string, BackgroundKind> = { shell: 'shell', monitor: 'monitor', workflow: 'workflow' }
300
301/**
302 * The tracked tasks as a stop's snapshot leaves them: those it no longer lists are dropped (unless
303 * recorded too recently for it), and the commands, monitors and workflows it lists that the mod did
304 * not see start (a helper's, one from before a /clear) are added without a start time.
305 *
306 * The snapshot reports a command-run monitor as a 'shell': `kinds`, the kinds of ids the mod saw
307 * started (a helper's included), says which it is.
308 */
309export const reconcileTasks = (
310 tracked: readonly BackgroundTask[],
311 snapshot: readonly TaskSnapshot[],
312 at: number,
313 kinds: ReadonlyMap<string, BackgroundKind> = new Map(),
314): BackgroundTask[] => {
315 const listed = new Set(snapshot.map(one => one.id))
316 const kept = tracked
317 .filter(task => listed.has(task.id) || at - task.seenAt < SNAPSHOT_GRACE_MS)
318 .map(task => {
319 // One first seen in a snapshot, before the mod learned its kind from its start: corrected now.
320 const kind = task.startedAt === 0 ? kinds.get(task.id) : undefined
321 return kind === undefined || kind === task.kind ? task : { ...task, kind, label: KIND_LABELS[kind] }
322 })
323 const known = new Set(kept.map(task => task.id))
324 const added = snapshot.flatMap((one): BackgroundTask[] => {
325 const kind = SNAPSHOT_KINDS[one.type] === undefined ? undefined : kinds.get(one.id) ?? SNAPSHOT_KINDS[one.type]
326 if (kind === undefined || known.has(one.id)) return []
327 const detail = clip(kind === 'workflow' ? one.name || one.description : one.description || one.command || '')
328 return [{ id: one.id, kind, label: KIND_LABELS[kind], detail, startedAt: 0, endsBy: 0, seenAt: at }]
329 })
330 return [...kept, ...added].slice(-MAX_TASKS)
331}
332
333/** `12분째` once a minute has passed, by the minute: between turns the band redraws once a minute. */
334export const runningFor = (ms: number): string => (ms < MINUTE ? '' : `${elapsed(Math.floor(ms / MINUTE) * MINUTE)}째`)
335
336const taskNote = (task: BackgroundTask, now: number) =>
337 task.kind === 'monitor' && task.endsBy > 0 && now >= task.endsBy ? '곧 끝나요' : task.startedAt > 0 ? runningFor(now - task.startedAt) : ''
338
339/** `도우미 2명 · 명령 1개 · 모니터 1개`: what is still at work, kind by kind. */
340export const backgroundParts = (helpers: number, list: readonly BackgroundTask[]): string[] => [
341 ...(helpers > 0 ? [`도우미 ${helpers}명`] : []),
342 ...(['shell', 'monitor', 'workflow'] as const).flatMap(kind => {
343 const n = list.filter(task => task.kind === kind).length
344 return n > 0 ? [`${KIND_WORDS[kind]} ${n}개`] : []
345 }),
346]
347
348// The time goes ahead of the words, which are what a narrow band cuts.
349const oneTask = (task: BackgroundTask, now: number) => {
350 const note = taskNote(task, now)
351 return `◌ 백그라운드${note ? ` (${note})` : ''}: ${what(task)}`
352}
353
354// --- Schedules ---
355
356/** The sentinels /loop stores in place of a prompt; the prompt that fires is the loop's own text. */
357const LOOP_SENTINEL = /^<<(autonomous-loop|loop\.md)(-dynamic)?>>$/
358
359const isLoop = (prompt: string) => LOOP_SENTINEL.test(prompt.trim())
360
361/** A stored prompt in a few words; a /loop's sentinel reads as the command. */
362export const promptWords = (prompt: string): string => (isLoop(prompt) ? '/loop' : clip(prompt))
363
364/** The cron job or wakeup a settled call stored; null for any other call, and for a wakeup's stop. */
365export const scheduleFromCall = (tool: string, input: unknown, record: unknown, now: number): Schedule | null => {
366 const r = asRecord(record)
367 const args = asRecord(input)
368 const prompt = str(args['prompt'])
369 if (tool === 'CronCreate') {
370 const id = str(r['id'])
371 const nextAt = typeof r['nextFireAt'] === 'number' ? r['nextFireAt'] : 0
372 const recurring = r['recurring'] !== false
373 return id === '' ? null : { id, kind: 'cron', recurring, nextAt, detail: promptWords(prompt), prompt: clip(prompt), seenAt: now }
374 }
375 if (tool === 'ScheduleWakeup') {
376 const at = typeof r['scheduledFor'] === 'number' ? r['scheduledFor'] : 0
377 if (r['stopped'] === true || at <= 0) return null
378 const detail = clip(str(args['reason'])) || promptWords(prompt)
379 return { id: `wakeup@${at}`, kind: 'wakeup', recurring: false, nextAt: at, detail, prompt: clip(prompt), seenAt: now }
380 }
381 return null
382}
383
384/** The cron job a settled CronDelete removed; null for any other call. */
385export const deletedScheduleId = (tool: string, record: unknown): string | null =>
386 tool === 'CronDelete' ? str(asRecord(record)['id']) || null : null
387
388/** Whether a settled call ended the /loop: its pending wakeups go, a recurring cron stays. */
389export const stopsWakeups = (tool: string, record: unknown): boolean => tool === 'ScheduleWakeup' && asRecord(record)['stopped'] === true
390
391/**
392 * The schedules once a stored prompt fired: the one with that prompt, else the earliest one due
393 * within the minute that could have fired with other words (a one-shot, or a /loop, whose stored
394 * sentinel fires as the loop's text). A one-shot goes; a recurring one stays, its next run unknown.
395 */
396export const fireSchedule = (list: readonly Schedule[], text: string, now: number): Schedule[] => {
397 const head = clip(text)
398 const due = list
399 .filter(one => (!one.recurring || isLoop(one.prompt)) && one.nextAt > 0 && one.nextAt <= now + MINUTE)
400 .sort((a, b) => a.nextAt - b.nextAt)
401 const fired = list.find(one => one.prompt !== '' && one.prompt === head) ?? due[0]
402 if (fired === undefined) return [...list]
403 return fired.recurring ? list.map(one => (one === fired ? { ...one, nextAt: 0 } : one)) : list.filter(one => one !== fired)
404}
405
406/** The cron jobs a stop's snapshot lists (`session_crons`). */
407export type CronSnapshot = { id: string; schedule: string; recurring: boolean; prompt: string }
408
409/**
410 * The tracked schedules as a stop's snapshot leaves them: listed ones kept, a wakeup the mod named by
411 * its time takes the id of the one-shot job with its prompt, missing ones dropped (unless recorded too
412 * recently), and jobs it did not see made (a helper's, one from before a /clear) added without a time.
413 */
414export const reconcileSchedules = (tracked: readonly Schedule[], snapshot: readonly CronSnapshot[], at: number): Schedule[] => {
415 const listed = new Map(snapshot.map(one => [one.id, one]))
416 const claimed = new Set(tracked.map(one => one.id).filter(id => listed.has(id)))
417 const kept = tracked.flatMap((one): Schedule[] => {
418 const job = listed.get(one.id)
419 // A past time stays: a job due while a turn ran fires right after it, and fireSchedule finds it
420 // by that time. The rows stop showing a recurring job's time once it is a minute past (nextAtOf).
421 if (job !== undefined) return [{ ...one, recurring: job.recurring }]
422 if (one.kind === 'wakeup' && one.id.startsWith('wakeup@')) {
423 const twin = snapshot.find(job => !job.recurring && !claimed.has(job.id) && clip(job.prompt) === one.prompt)
424 if (twin !== undefined) {
425 claimed.add(twin.id)
426 return [{ ...one, id: twin.id }]
427 }
428 }
429 return at - one.seenAt < SNAPSHOT_GRACE_MS ? [one] : []
430 })
431 const added = snapshot
432 .filter(job => !claimed.has(job.id))
433 .map((job): Schedule => ({
434 id: job.id,
435 kind: job.recurring ? 'cron' : 'wakeup',
436 recurring: job.recurring,
437 nextAt: 0,
438 detail: promptWords(job.prompt),
439 prompt: clip(job.prompt),
440 seenAt: at,
441 }))
442 return [...kept, ...added].slice(-MAX_TASKS)
443}
444
445/** `4분 후`, `1시간 2분 후`; `곧` within the minute or past due; '' when not known. */
446export const timeTo = (at: number, now: number): string => (at <= 0 ? '' : at - now < MINUTE ? '곧' : `${timeLeftMs(at - now)} 후`)
447
448/** A schedule's next run as far as the band can tell: a recurring one a minute past its time has run unseen. */
449const nextAtOf = (one: Schedule, now: number) => (one.recurring && one.nextAt > 0 && one.nextAt < now - MINUTE ? 0 : one.nextAt)
450
451const nextRun = (list: readonly Schedule[], now: number) => {
452 const known = list.map(one => nextAtOf(one, now)).filter(at => at > 0).sort((a, b) => a - b)[0]
453 return known === undefined ? '' : timeTo(known, now)
454}
455
456/** `◷ 4분 후 실행 · 배포 상태 확인`, `◷ 예약 3개 · 다음은 곧 실행`; null with none. */
457export const scheduleRow = (list: readonly Schedule[], now: number): StatusRow | null => {
458 if (list.length === 0) return null
459 if (list.length === 1) {
460 const one = list[0]!
461 const when = timeTo(nextAtOf(one, now), now)
462 const head = when !== '' ? `${when} 실행` : one.recurring ? '반복 예약' : '예약'
463 return { text: `◷ ${head}${one.detail ? ` · ${one.detail}` : ''}`, tone: 'dim', bold: false }
464 }
465 const next = nextRun(list, now)
466 return { text: `◷ 예약 ${list.length}개${next === '' ? '' : ` · 다음은 ${next === '곧' ? '곧 실행' : next}`}`, tone: 'dim', bold: false }
467}
468
469/**
470 * The one dim row of background work and schedules beside a turn at work, or below a helper's ask;
471 * null with neither.
472 */
473export const backgroundNote = (list: readonly BackgroundTask[], planned: readonly Schedule[], now: number): StatusRow | null => {
474 if (list.length === 0) return scheduleRow(planned, now)
475 if (planned.length === 0 && list.length === 1) return { text: oneTask(list[0]!, now), tone: 'dim', bold: false }
476 const next = nextRun(planned, now)
477 const later = planned.length === 0 ? [] : [`예약 ${planned.length}개${next === '' ? '' : ` (${next === '곧' ? '곧 실행' : next})`}`]
478 return { text: `◌ 백그라운드: ${[...backgroundParts(0, list), ...later].join(' · ')}`, tone: 'dim', bold: false }
479}
480
481/**
482 * The row of what still works once the main turn has ended: helpers blink their dot, as before; a
483 * command or monitor alone is dim, since only a process runs and Claude does not.
484 */
485export const backgroundRow = (helpers: number, asked: boolean, list: readonly BackgroundTask[], now: number, dot: string): StatusRow | null => {
486 const asking = asked ? ' · 승인 요청이 떴었어요' : ''
487 if (list.length === 0) {
488 return helpers > 0 ? { text: `${dot} 백그라운드 도우미 ${helpers}명은 아직 일하는 중${asking}`, tone: 'claude', bold: false } : null
489 }
490 if (helpers === 0) {
491 const text = list.length === 1 ? oneTask(list[0]!, now) : `◌ 백그라운드에서 아직 일하는 중 · ${backgroundParts(0, list).join(' · ')}`
492 return { text, tone: 'dim', bold: false }
493 }
494 return { text: `${dot} 백그라운드에서 아직 일하는 중 · ${backgroundParts(helpers, list).join(' · ')}${asking}`, tone: 'claude', bold: false }
495}
496
497/** The status rows, top first: none before the session's first turn. */
498export const statusRows = (s: StatusInput): StatusRow[] => {
499 const { work: w } = s
500 const list = s.tasks ?? []
501 const planned = s.schedules ?? []
502 const dot = s.beat ? '●' : '○'
503 const lead = s.isViewingHelper ? '메인 대화 · ' : ''
504 const isFresh = (at: number) => s.now - at < ASK_FRESH_MS
505 const ago = (at: number) => (s.now - at < 1000 ? '방금' : `${elapsed(s.now - at)} 전`)
506 const helperAsk = s.helperAsks.filter(ask => isFresh(ask.at)).at(-1)
507
508 if (s.isWorking || w.phase === 'working') {
509 if (w.phase !== 'working') {
510 // Loaded mid-turn: the engine says it works; the clock and the dot start with the next turn.
511 return [{ text: `${lead}작업 중…`, tone: 'claude', bold: true }]
512 }
513
514 const needsMe = w.running.find(one => one.needsMe)
515 if (needsMe !== undefined) {
516 return [
517 { text: `${lead}! 나를 기다리는 중 · ${elapsed(s.now - needsMe.startedAt)}째`, tone: 'warning', bold: true },
518 { text: what(needsMe), tone: 'warning', bold: false },
519 ]
520 }
521
522 // The prompt shows until the person answers, and an approved call runs on: the band cannot tell
523 // the two apart, so its words hold for both.
524 const asked = w.running.find(one => one.askedAt !== null && isFresh(one.askedAt))
525 if (asked !== undefined || helperAsk !== undefined) {
526 const [head, at, one] =
527 asked !== undefined
528 ? (['승인 요청이 떴어요', asked.askedAt ?? s.now, asked] as const)
529 : (['도우미가 승인 요청을 띄웠어요', helperAsk!.at, helperAsk!] as const)
530 return [
531 { text: `${lead}! ${head} · ${ago(at)}`, tone: 'warning', bold: true },
532 { text: `${what(one)} · 승인했다면 실행 중이에요`, tone: 'warning', bold: false },
533 ]
534 }
535
536 const doing = w.trigger === 'task' ? '알림 받고 작업 중' : w.trigger === 'schedule' ? '예약 작업 중' : '작업 중'
537 const head = [
538 `${lead}${dot} ${doing}`,
539 w.startedAt > 0 ? elapsed(s.now - w.startedAt) : '',
540 w.tools > 0 ? `도구 ${w.tools}회` : '',
541 s.helpers > 0 ? `도우미 ${s.helpers}명 일하는 중` : '',
542 ]
543 .filter(Boolean)
544 .join(' · ')
545 const first = w.running[0]
546 let line = '생각하거나 답을 쓰는 중…'
547 if (first !== undefined) {
548 // Notes go before the call's words, which are what a narrow band cuts.
549 const notes = [
550 s.now - first.startedAt >= 3000 ? `${elapsed(s.now - first.startedAt)}째` : '',
551 first.askedAt !== null ? '승인 요청이 떴었어요' : '',
552 ]
553 .filter(Boolean)
554 .join(', ')
555 const more = w.running.length > 1 ? ` 외 ${w.running.length - 1}개` : ''
556 line = `지금${notes ? ` (${notes})` : ''}: ${what(first)}${more}`
557 }
558 const note = backgroundNote(list, planned, s.now)
559 return [
560 { text: head, tone: 'claude', bold: true },
561 { text: line, tone: 'dim', bold: false },
562 ...(note === null ? [] : [note]),
563 ]
564 }
565
566 const tools = w.tools > 0 ? ` · 도구 ${w.tools}회` : ''
567 const rows: StatusRow[] = []
568 if (w.phase === 'done') {
569 rows.push({ text: `${lead}✓ 끝났어요 · ${elapsed(w.durationMs)} 걸림${tools} · 다음 지시를 기다려요`, tone: 'success', bold: true })
570 } else if (w.phase === 'aborted') {
571 rows.push({ text: `${lead}■ 중단했어요 · ${elapsed(w.durationMs)} 동안 작업함${tools}`, tone: 'warning', bold: true })
572 } else if (w.phase === 'error') {
573 // A full context, a usage limit or a network error all end here: the transcript says which.
574 const text = w.stopReason === 'refusal' ? '✕ 요청을 거절했어요 · 다르게 말해 보세요' : '✕ 오류로 멈췄어요 · 대화에 뜬 안내를 확인해 주세요'
575 rows.push({ text: `${lead}${text}`, tone: 'error', bold: true })
576 }
577 // At most two rows below the head: a fresh ask from a helper over one dim row of the rest, else
578 // what still works in the background over what is scheduled.
579 const below: Array<StatusRow | null> =
580 helperAsk !== undefined
581 ? [{ text: `! 도우미가 승인 요청을 띄웠어요 · ${ago(helperAsk.at)} · ${what(helperAsk)}`, tone: 'warning', bold: true }, backgroundNote(list, planned, s.now)]
582 : [backgroundRow(s.helpers, s.helperAsks.length > 0, list, s.now, dot), scheduleRow(planned, s.now)]
583 return [...rows, ...below.filter((row): row is StatusRow => row !== null)]
584}
585
586const BUSY: ReadonlySet<AgentStatus> = new Set(['pending', 'running', 'waiting'])
587
588/** At work as the tasks list says; a teammate in a terminal pane of its own keeps its last word there, so it is left out. */
589export const isBusyAgent = (agent: Pick<AgentInfo, 'id' | 'status' | 'teammateId'>): boolean =>
590 BUSY.has(agent.status) && !(agent.teammateId !== undefined && agent.id === agent.teammateId)
591
592const withId = (list: string[], id: string) => (list.includes(id) ? list : [...list, id])
593const sameIds = (a: string[], b: string[]) => a.length === b.length && a.every(id => b.includes(id))
594
595// The status only feeds the band: work that fails must never fail the hook it rides on.
596const quietly = (task: Promise<unknown>) => task.then(() => undefined, () => undefined)
597
598// The module's own, so a reload cancels it with the old environment; session.start starts it again.
599let workTicker: Timer | undefined
600let isWorkTicking = false
601
602const stopWorkTicker = () => {
603 workTicker?.cancel()
604 workTicker = undefined
605}
606
607// Once a second while the main turn or a helper works: moves the clock and the dot, recounts the
608// helpers, and lets go of their stale asks. Stops once nothing works; the next turn starts it again.
609const workTick = async ($: EngineInterface) => {
610 if (isWorkTicking) return
611 isWorkTicking = true
612 try {
613 const [w, known] = await Promise.all([read($, work), read($, helpers)])
614 if (w.phase !== 'working' && known.length === 0) {
615 stopWorkTicker()
616 return
617 }
618 const listed = (await $.agent.list()).filter(isBusyAgent).map(agent => agent.id)
619 const busy = [...new Set([...listed, ...(await read($, helperTurns))])]
620 if (!sameIds(busy, known)) await update($, helpers, () => busy)
621 await update($, helperAsks, list => (list.every(ask => busy.includes(ask.agentId)) ? list : list.filter(ask => busy.includes(ask.agentId))))
622 const at = await $.clock.now()
623 await update($, clockNow, () => at)
624 await update($, beat, on => !on)
625 } catch {
626 // The next tick tries again.
627 } finally {
628 isWorkTicking = false
629 }
630}
631
632const startWorkTicker = ($: EngineInterface) => {
633 workTicker ??= $.clock.every(1000, () => void workTick($))
634}
635
636// What started the turn about to start, between the prompt's submission and the turn's start; the
637// module's own, so a reload mid-way only loses the words.
638let pendingTrigger: Trigger = ''
639
640/** The trigger for a prompt that opens a turn of its own (none while one runs): a notification or a stored prompt. */
641export const triggerOf = (kind: string, turnId: string | undefined): Trigger =>
642 turnId !== undefined ? '' : kind === 'task-notification' ? 'task' : kind === 'scheduled-trigger' ? 'schedule' : ''
643
644const takeTrigger = (): Trigger => {
645 const trigger = pendingTrigger
646 pendingTrigger = ''
647 return trigger
648}
649
650const startMainTurn = async ($: EngineInterface, trigger: Trigger) => {
651 const at = await $.clock.now()
652 await update($, clockNow, () => at)
653 await update($, work, () => ({ ...IDLE_WORK, phase: 'working', startedAt: at, trigger }))
654 startWorkTicker($)
655}
656
657const startHelperTurn = async ($: EngineInterface, agentId: string) => {
658 await update($, helperTurns, list => withId(list, agentId))
659 await update($, helpers, list => withId(list, agentId))
660 startWorkTicker($)
661}
662
663// A helper's turn can end while it still waits on background work of its own: the tasks list keeps
664// it busy, and it stays counted (and the ticker running) until the list lets go of it.
665const endHelperTurn = async ($: EngineInterface, agentId: string) => {
666 await update($, helperTurns, list => list.filter(id => id !== agentId))
667 await update($, helperAsks, list => list.filter(ask => ask.agentId !== agentId))
668 const isStillBusy = await $.agent.list().then(
669 list => list.some(agent => agent.id === agentId && isBusyAgent(agent)),
670 () => false,
671 )
672 if (!isStillBusy) {
673 await update($, helpers, list => list.filter(id => id !== agentId))
674 }
675}
676
677// Waits a moment first: a turn that starts right away (a queued prompt) makes the news stale.
678const announceEnd = async ($: EngineInterface, text: string) => {
679 if ((await read($, work)).phase === 'working') return
680 const [waiting, left] = await Promise.all([read($, helpers).then(list => list.length), read($, tasks)])
681 const full =
682 left.length > 0
683 ? `${text} · 백그라운드에서 아직 일하는 중 (${backgroundParts(waiting, left).join(', ')})`
684 : waiting > 0
685 ? `${text} · 도우미 ${waiting}명은 아직 일하는 중`
686 : text
687 // The desktop app has no terminal to notify through (`no-surface`), and a bell shows no words.
688 const sent = await $.ui.notify(full, { title: 'Claude Code' }).catch(() => undefined)
689 if (sent === undefined || !sent.isSent || sent.channel === 'terminal_bell') {
690 $.ui.toast(full, { timeoutMs: 10_000 })
691 }
692}
693
694const endMainTurn = async ($: EngineInterface, e: TurnCompleteInput) => {
695 const phase: Phase = e.reason === 'answer' ? 'done' : e.reason === 'aborted' ? 'aborted' : 'error'
696 const stopReason: Work['stopReason'] = e.reason === 'refusal' ? 'refusal' : e.reason === 'error' ? 'error' : ''
697 const { trigger } = await read($, work)
698 await update($, work, w => ({ ...w, phase, durationMs: e.durationMs, running: [], stopReason }))
699 // A schedule's turns come every few minutes on their own: none is announced.
700 if (phase !== 'aborted' && e.durationMs >= ANNOUNCE_AFTER_MS && trigger !== 'schedule') {
701 const text = phase === 'done' ? `작업이 끝났어요 (${elapsed(e.durationMs)} 걸림)` : '작업이 멈췄어요'
702 $.clock.after(2000, () => void announceEnd($, text))
703 }
704}
705
706const openCall = async ($: EngineInterface, e: ToolCallInput): Promise<Pick<RunningTool, 'id' | 'startedAt'>> => {
707 const startedAt = await $.clock.now()
708 const tool = String(e.tool)
709 const call: RunningTool = {
710 id: e.tool_use_id ?? `${tool}@${startedAt}`,
711 tool,
712 ...describeTool(tool, e),
713 startedAt,
714 askedAt: null,
715 }
716 await update($, work, w => (w.phase === 'working' ? { ...w, tools: w.tools + 1, running: [...w.running, call] } : w))
717 return { id: call.id, startedAt }
718}
719
720const closeCall = async ($: EngineInterface, id: string) => {
721 await update($, work, w => ({ ...w, running: w.running.filter(one => one.id !== id) }))
722}
723
724const dropTasks = async ($: EngineInterface, ids: readonly string[]) => {
725 if (ids.length > 0) await update($, tasks, list => (list.some(task => ids.includes(task.id)) ? list.filter(task => !ids.includes(task.id)) : list))
726}
727
728// The module's own, as the work ticker is: a reload drops it, and session.start arms it again.
729let scheduleTimer: Timer | undefined
730
731// Redraws the moment the nearest schedule turns `곧`, which the minute clock may miss by most of a minute.
732// A wait past about 24.9 days does not fit the host's timer, which fires it at once: it wakes within
733// the hour at most and looks again.
734const armScheduleClock = async ($: EngineInterface) => {
735 scheduleTimer?.cancel()
736 scheduleTimer = undefined
737 const [list, now] = await Promise.all([read($, schedules), $.clock.now()])
738 // Another call may have armed one meanwhile.
739 scheduleTimer?.cancel()
740 scheduleTimer = undefined
741 const turns = list.map(one => one.nextAt - MINUTE).filter(at => at >= now)
742 if (turns.length > 0) {
743 const wait = Math.min(Math.min(...turns) - now + 1, HOUR)
744 scheduleTimer = $.clock.after(wait, () => void tick($).then(() => armScheduleClock($)))
745 }
746}
747
748const changeSchedules = async ($: EngineInterface, change: (list: Schedule[]) => Schedule[]) => {
749 await update($, schedules, change)
750 await armScheduleClock($)
751}
752
753// A call that stores, deletes or ends a schedule; false for any other.
754const noteSchedule = async ($: EngineInterface, tool: string, input: unknown, record: unknown, now: number): Promise<boolean> => {
755 const deleted = deletedScheduleId(tool, record)
756 if (deleted !== null) {
757 await changeSchedules($, list => list.filter(one => one.id !== deleted))
758 return true
759 }
760 if (stopsWakeups(tool, record)) {
761 await changeSchedules($, list => list.filter(one => one.kind !== 'wakeup'))
762 return true
763 }
764 const planned = scheduleFromCall(tool, input, record, now)
765 if (planned === null) return false
766 await changeSchedules($, list => [...list.filter(one => one.id !== planned.id), planned].slice(-MAX_TASKS))
767 return true
768}
769
770// The kinds of background tasks the mod saw start, whichever loop started them, for reading a
771// stop's snapshot; the module's own, so a reload forgets them and a monitor reads as a command.
772const taskKinds = new Map<string, BackgroundKind>()
773const TASK_KINDS_KEPT = 100
774
775const rememberKind = (task: BackgroundTask) => {
776 taskKinds.delete(task.id)
777 taskKinds.set(task.id, task.kind)
778 for (const id of taskKinds.keys()) {
779 if (taskKinds.size <= TASK_KINDS_KEPT) break
780 taskKinds.delete(id)
781 }
782}
783
784// A settled call may have left work in the background, stopped some, or stored a schedule: its record says which.
785const noteCall = async ($: EngineInterface, e: ToolCallInput, result: ToolCallResult, startedAt: number | undefined) => {
786 if (result.deny !== undefined || result.isError === true) return
787 const tool = String(e.tool)
788 const now = await $.clock.now()
789 // Schedules are the session's, whichever loop stored them.
790 if (await noteSchedule($, tool, e, result.result, now)) return
791 const stopped = stoppedTaskId(tool, result.result)
792 if (stopped !== null) return dropTasks($, [stopped])
793 const task = taskFromCall(tool, e, result.result, startedAt ?? now, now)
794 if (task === null) return
795 rememberKind(task)
796 // A helper's background work is the helper's: its notification goes to the helper, so it shows from a stop's snapshot.
797 if (e.agentId === undefined) await update($, tasks, list => [...list.filter(one => one.id !== task.id), task].slice(-MAX_TASKS))
798}
799
800// A stored prompt fired: its schedule has run.
801const fireStored = async ($: EngineInterface, text: string) => {
802 const now = await $.clock.now()
803 await changeSchedules($, list => fireSchedule(list, text, now))
804}
805
806// The main loop stopped and listed what is still in flight and scheduled: the source of truth for
807// what ended, expired or was made unseen. A field the engine left out changes nothing.
808const applySnapshot = async ($: EngineInterface, snapshot: readonly TaskSnapshot[] | undefined, crons: readonly CronSnapshot[] | undefined) => {
809 const at = await $.clock.now()
810 if (snapshot !== undefined) await update($, tasks, list => reconcileTasks(list, snapshot, at, taskKinds))
811 if (crons !== undefined) await changeSchedules($, list => reconcileSchedules(list, crons, at))
812}
813
814// A prompt the person must answer: the main loop's call it belongs to, or a helper's ask.
815const markAsked = async ($: EngineInterface, agentId: string | undefined, tool: string, input: unknown) => {
816 const at = await $.clock.now()
817 const { label, detail } = describeTool(tool, input)
818 if (agentId !== undefined) {
819 await update($, helperAsks, list => [...list, { agentId, tool, label, detail, at }].slice(-20))
820 return
821 }
822 await update($, work, w => {
823 const open = w.running.filter(one => one.askedAt === null && one.tool === tool)
824 const target = open.find(one => one.detail === detail) ?? open[0]
825 return target === undefined
826 ? w
827 : { ...w, running: w.running.map(one => (one.id === target.id ? { ...one, askedAt: at } : one)) }
828 })
829}
830
831// The prompt carries no call id, so a settled call lets go of the one ask with its own words: a
832// helper's other call of the same tool may still be asking.
833const dropHelperAsk = async ($: EngineInterface, agentId: string, tool: string, input: unknown) => {
834 const { detail } = describeTool(tool, input)
835 await update($, helperAsks, list => {
836 const index = list.findIndex(ask => ask.agentId === agentId && ask.tool === tool && ask.detail === detail)
837 return index === -1 ? list : [...list.slice(0, index), ...list.slice(index + 1)]
838 })
839}
840
841const resetWork = async ($: EngineInterface) => {
842 stopWorkTicker()
843 await update($, work, () => IDLE_WORK)
844 await update($, helpers, () => [])
845 await update($, helperTurns, () => [])
846 await update($, helperAsks, () => [])
847 // What still runs, or is still scheduled, comes back with the next stop's snapshot.
848 await update($, tasks, () => [])
849 await update($, schedules, () => [])
850 scheduleTimer?.cancel()
851 scheduleTimer = undefined
852 pendingTrigger = ''
853}
854
855// After a reload mid-turn the stored status stands, and its ticker starts again.
856const resumeWork = async ($: EngineInterface) => {
857 const [w, known] = await Promise.all([read($, work), read($, helpers)])
858 if (w.phase === 'working' || known.length > 0) startWorkTicker($)
859}
860// --- end of work status ------------------------------------------------------------------------
861
862const errorMessage = (error: unknown): string => (error instanceof Error ? error.message : String(error))
863
864// --- Compaction trace (temporary) -------------------------------------------------------------
865// Kept while checking that the compact button really compacts in the desktop app, where the
866// debug log is out of reach: each step is also appended to ~/.claude/usage-mods-compact.log.
867// Remove this block and the trace() calls once compaction is confirmed.
868
869export const LOG_FILE = '.claude/usage-mods-compact.log'
870const LOG_LIMIT = 300
871
872export const logLine = (time: number, session: string, text: string): string =>
873 `${new Date(time).toISOString()} [${session.slice(0, 8)}] ${text}`
874
875/** The log's text with `line` added, keeping the newest `limit` lines. */
876export const appendLine = (text: string, line: string, limit = LOG_LIMIT): string =>
877 [...text.split('\n').filter(l => l !== ''), line].slice(-limit).join('\n') + '\n'
878
879/** A prompt as the trace names it: `/compact` itself, otherwise only its length. */
880export const describePrompt = (text: string): string =>
881 text.trim() === '/compact' ? '/compact' : `prompt of ${text.length} chars`
882
883// One write at a time, so one session's lines keep their order; every session shares the file.
884let traceQueue: Promise<void> = Promise.resolve()
885
886const writeTrace = async ($: EngineInterface, text: string) => {
887 const home = await $.env.get('HOME')
888 if (home === undefined || home === '') {
889 return
890 }
891 const path = `${home}/${LOG_FILE}`
892 const [now, session, before] = await Promise.all([
893 $.clock.now(),
894 $.session.id().catch(() => '?'),
895 $.fs.read(path).catch(() => ''),
896 ])
897 await $.fs.write(path, appendLine(before, logLine(now, session, text)))
898}
899
900const trace = ($: EngineInterface, text: string) => {
901 $.ui.log(`usage-mods: ${text}`, { to: 'debug' })
902 traceQueue = traceQueue.then(() => writeTrace($, text)).catch(() => {})
903}
904
905// The band's isWorking as last drawn, for the trace to set beside the plugin's own turn tracking.
906let lastIsWorking: boolean | undefined
907// --- end of compaction trace -------------------------------------------------------------------
908
909export const QUESTION = '압축하시겠습니까?'
910export const YES = '예'
911export const NO = '아니오'
912
913/** What pressing the button says while it is off. */
914export const OFF_HINT = '답변이 끝나면 압축할 수 있어요'
915export const COMPACTING_HINT = '압축하는 중이에요'
916
917/** How long the /compact the band ran may wait for its compaction before the band lets go. */
918export const QUEUE_TIMEOUT = 10 * MINUTE
919
920// Dismissing the dialog counts as 아니오.
921const confirmCompact = async ($: EngineInterface): Promise<boolean> => {
922 try {
923 return (await $.ui.ask(QUESTION, { header: '압축', options: [YES, NO] })) === YES
924 } catch {
925 return false
926 }
927}
928
929// One compaction at a time across redraws and repeated presses; the module's own, so a reload clears it.
930let isBusy = false
931
932// Whether a person is at the prompt, as session.start said: false in the desktop app.
933let isInteractive = true
934
935// A /compact the band sent, waiting for the compaction it asked for; `timer` lets go of it.
936let waiting: { timer: Timer | null } | null = null
937
938const finishWaiting = async ($: EngineInterface, toast: string) => {
939 if (waiting === null) {
940 return
941 }
942 waiting.timer?.cancel()
943 waiting = null
944 await update($, isCompacting, () => false)
945 $.ui.toast(toast)
946}
947
948/**
949 * After the /compact command: whether it compacted, read from the context fill (it drops, or is
950 * unknown until the next answer) in case no `session.compact` reached this plugin.
951 */
952export const hasCompacted = (before: number, after: number | undefined): boolean => (after ?? 0) < before
953
954const endCompactCommand = async ($: EngineInterface, before: number, output: string) => {
955 const now = await $.session.usage()
956 await update($, usage, () => toUsage(now))
957 trace($, `/compact command ended, context ${before}% → ${now.context.percent}%: ${output || '(no output)'}`)
958 if (hasCompacted(before, now.context.percent)) {
959 await finishWaiting($, '컨텍스트를 압축했어요')
960 } else {
961 await finishWaiting($, output ? `압축되지 않았어요: ${output}` : '압축되지 않았어요')
962 }
963}
964
965/**
966 * The desktop app and other SDK hosts compact only inside a turn: runs /compact as if the person
967 * typed it (`$.prompt.submit` refuses a text that starts with `/`), queued until the session is idle.
968 * The band keeps compacting until the compaction lands (`session.compact`), the command ends
969 * (compacted or not), or the wait runs out.
970 */
971const sendCompact = ($: EngineInterface, before: number) => {
972 waiting = {
973 timer: $.clock.after(QUEUE_TIMEOUT, () => {
974 trace($, `no compaction within ${QUEUE_TIMEOUT / MINUTE} minutes; letting go`)
975 void finishWaiting($, '압축되지 않았어요. 입력창에 /compact를 보내 주세요')
976 }),
977 }
978 $.ui.toast('압축을 요청했어요')
979 void (async () => {
980 try {
981 const result = await $.command.run({ command: 'compact' })
982 await endCompactCommand($, before, result.text ?? '')
983 } catch (error) {
984 const message = errorMessage(error)
985 trace($, `/compact command failed: ${message}`)
986 await finishWaiting($, `압축하지 못했어요: ${message}`)
987 }
988 })()
989}
990
991/**
992 * Asks, then compacts. Runs on a timer, not inside the press: the band redraws often (usage updates,
993 * the minute clock), and work tied to the drawn Button or its press dispatch is lost with it.
994 */
995const runCompact = async ($: EngineInterface) => {
996 let isWaiting = false
997 try {
998 const [u, turnRunning] = await Promise.all([read($, usage), read($, isTurnRunning)])
999 trace($, `pressed: band isWorking=${lastIsWorking}, turn running=${turnRunning}, context=${u?.contextPercent}%`)
1000 if (!(await confirmCompact($))) {
1001 trace($, 'declined')
1002 return
1003 }
1004 await update($, isCompacting, () => true)
1005 try {
1006 const result = await $.session.compact()
1007 if (result.skip !== undefined) {
1008 trace($, `compact skipped: ${result.skip}`)
1009 $.ui.toast(`압축하지 않았어요: ${result.skip}`)
1010 } else {
1011 trace($, 'compacted')
1012 const after = await $.session.usage()
1013 await update($, usage, () => toUsage(after))
1014 $.ui.toast('컨텍스트를 압축했어요')
1015 }
1016 } catch (error) {
1017 const message = errorMessage(error)
1018 trace($, `compact refused: ${message}`)
1019 if (shouldSendCompact(message, isInteractive)) {
1020 sendCompact($, u?.contextPercent ?? 0)
1021 isWaiting = true
1022 } else {
1023 $.ui.toast(`압축하지 못했어요: ${message}`)
1024 }
1025 }
1026 } finally {
1027 if (!isWaiting) {
1028 await update($, isCompacting, () => false)
1029 }
1030 isBusy = false
1031 }
1032}
1033
1034const startCompact = ($: EngineInterface) => {
1035 if (isBusy || waiting !== null) {
1036 return
1037 }
1038 isBusy = true
1039 try {
1040 $.clock.after(0, () => void runCompact($))
1041 } catch (error) {
1042 isBusy = false
1043 throw error
1044 }
1045}
1046
1047export const register: Register = on => {
1048 // Takes the press by its key, before the drawn Button's own onPress: a redraw replaces that handler.
1049 on('ui.press', { plugin: 'usage-mods', element: 'compact' }, ($, e) => {
1050 startCompact($)
1051 return { element: e.element }
1052 })
1053
1054 // The button while it is off: a press only says why.
1055 on('ui.press', { plugin: 'usage-mods', element: 'compact-off' }, async ($, e) => {
1056 $.ui.toast((await read($, isCompacting)) ? COMPACTING_HINT : OFF_HINT)
1057 return { element: e.element }
1058 })
1059
1060 on('session.start', async ($, e, next) => {
1061 const result = await next(e)
1062 isInteractive = e.isInteractive
1063 trace($, `session started: surface ${e.surface}, interactive ${e.isInteractive}`)
1064 // A reload drops the module's waiting /compact, so the band starts out of it.
1065 await update($, isCompacting, () => false)
1066 await update($, isTurnRunning, () => false)
1067 const u = await $.session.usage()
1068 await update($, usage, () => toUsage(u))
1069 await tick($)
1070 $.clock.every(MINUTE, () => void tick($))
1071 await quietly(resumeWork($))
1072 await quietly(armScheduleClock($))
1073 return result
1074 })
1075
1076 // A /clear or a resume starts the conversation over: no turn of it has run yet.
1077 on('session.end', async ($, e, next) => {
1078 if (e.reason === 'clear' || e.reason === 'resume') {
1079 await quietly(resetWork($))
1080 }
1081 return next(e)
1082 })
1083
1084 // What the main loop runs now, for the status rows; a helper's call settling lets go of its ask.
1085 // A settled call's record also says what it left running in the background, or stopped.
1086 on('tool.call', async ($, e, next) => {
1087 if (e.agentId !== undefined) {
1088 const { agentId } = e
1089 try {
1090 const result = await next(e)
1091 await quietly(noteCall($, e, result, undefined))
1092 return result
1093 } finally {
1094 await quietly(dropHelperAsk($, agentId, String(e.tool), e))
1095 }
1096 }
1097 const opened = await openCall($, e).catch(() => undefined)
1098 try {
1099 const result = await next(e)
1100 // Timed from the call's start: one moved to the background by Ctrl+B or its timeout ran before it returned.
1101 await quietly(noteCall($, e, result, opened?.startedAt))
1102 return result
1103 } finally {
1104 if (opened !== undefined) {
1105 await quietly(closeCall($, opened.id))
1106 }
1107 }
1108 })
1109
1110 // Raised before the permission prompt shows. A hook beneath may decide it, and then nobody is asked.
1111 on('classic.PermissionRequest', async ($, e, next) => {
1112 const result = await next(e)
1113 if (result.decision === undefined) {
1114 await quietly(markAsked($, e.agent_id, e.tool_name, e.tool_input))
1115 }
1116 return result
1117 })
1118
1119 // A helper's call has run (or failed): its prompt, if it had one, was answered.
1120 on('classic.PostToolUse', async ($, e, next) => {
1121 if (e.agent_id !== undefined) {
1122 await quietly(dropHelperAsk($, e.agent_id, e.tool_name, e.tool_input))
1123 }
1124 return next(e)
1125 })
1126
1127 on('classic.PostToolUseFailure', async ($, e, next) => {
1128 if (e.agent_id !== undefined) {
1129 await quietly(dropHelperAsk($, e.agent_id, e.tool_name, e.tool_input))
1130 }
1131 return next(e)
1132 })
1133
1134 // Each time the main loop stops it lists the session's background work still in flight: what
1135 // ended without a notification the band saw drops out here. The list is taken before the stop
1136 // hooks run, so it is read as of now, before they take their time; their result passes on untouched.
1137 on('classic.Stop', async ($, e, next) => {
1138 if (e.agent_id === undefined) {
1139 await quietly(applySnapshot($, e.background_tasks, e.session_crons))
1140 }
1141 return next(e)
1142 }).catch(($, e, next) => next(e))
1143
1144 on('session.measure', async ($, e, next) => {
1145 await update($, usage, () => toUsage(e))
1146 return next(e)
1147 })
1148
1149 // The plugin's own record of a running turn, beside the band's isWorking: the button is off while either says so.
1150 on('turn.start', async ($, e, next) => {
1151 // Taken before anything waits: the prompt that started the turn may settle meanwhile.
1152 const trigger = e.agentId === undefined ? takeTrigger() : ''
1153 // A helper's turn is not the main one: turn.complete clears this for the main loop alone.
1154 if (e.agentId === undefined) {
1155 await update($, isTurnRunning, () => true)
1156 }
1157 if (waiting !== null) {
1158 trace($, `turn started while /compact waits: ${describePrompt(e.text)}`)
1159 }
1160 await quietly(e.agentId === undefined ? startMainTurn($, trigger) : startHelperTurn($, e.agentId))
1161 return next(e)
1162 })
1163
1164 on('turn.complete', async ($, e, next) => {
1165 const result = await next(e)
1166 if (e.agentId === undefined) {
1167 await update($, isTurnRunning, () => false)
1168 if (waiting !== null) {
1169 trace($, `turn ended (${e.reason}) while /compact waits`)
1170 }
1171 await quietly(endMainTurn($, e))
1172 } else {
1173 await quietly(endHelperTurn($, e.agentId))
1174 }
1175 return result
1176 })
1177
1178 // Every compaction of the main conversation: the one a /compact the band sent waits for.
1179 on('session.compact', async ($, e, next) => {
1180 if (e.agentId !== undefined || e.trigger === 'precompute') {
1181 return next(e)
1182 }
1183 trace($, `compaction starting (trigger ${e.trigger})`)
1184 const result = await next(e).catch(async error => {
1185 const message = errorMessage(error)
1186 trace($, `compaction failed (trigger ${e.trigger}): ${message}`)
1187 await finishWaiting($, `압축하지 못했어요: ${message}`)
1188 throw error
1189 })
1190 if (result.skip !== undefined) {
1191 trace($, `compaction skipped (trigger ${e.trigger}): ${result.skip}`)
1192 await finishWaiting($, `압축하지 않았어요: ${result.skip}`)
1193 } else {
1194 trace($, `compaction done (trigger ${e.trigger}): ${result.tokensBefore} → ${result.tokensAfter} tokens`)
1195 await finishWaiting($, '컨텍스트를 압축했어요')
1196 }
1197 return result
1198 }).catch(($, e, next) => next(e))
1199
1200 // A background task's notification says which tasks ended. The rest is trace only: what became oftypes/index.d.ts 103 lines1export type Usage = {
2 contextPercent?: number
3 limits: { kind: string; percentUsed: number; resetsAt?: string }[]
4 usd?: number
5}
6
7/** Where the main conversation's turn stands. */
8export type Phase = 'idle' | 'working' | 'done' | 'aborted' | 'error'
9
10/** A main-loop tool call that has started and not yet settled. */
11export type RunningTool = {
12 id: string
13 tool: string
14 /** Plain words for what it does (`명령 실행`). */
15 label: string
16 /** The file, command or query it works on, cut short; '' when none. */
17 detail: string
18 /** A tool that waits on the person by itself: a question, a plan to approve. */
19 needsMe: boolean
20 startedAt: number
21 /** When a permission prompt was raised for it, else null. */
22 askedAt: number | null
23}
24
25/** A permission prompt a subagent raised, until its call settles or it stops. */
26export type HelperAsk = { agentId: string; tool: string; label: string; detail: string; at: number }
27
28export type BackgroundKind = 'shell' | 'monitor' | 'workflow'
29
30/** Background work running beside the conversation: a command, a monitor, a workflow run. */
31export type BackgroundTask = {
32 /** The task's id: the call's `backgroundTaskId` or `taskId`, or a stop snapshot's. */
33 id: string
34 kind: BackgroundKind
35 /** Plain words for what it runs (`명령 실행`). */
36 label: string
37 /** The command, description or name, cut short; '' when none. */
38 detail: string
39 /** Epoch ms the call that started it began; 0 when known only from a snapshot. */
40 startedAt: number
41 /** Epoch ms a monitor's deadline passes; 0 when it has none. */
42 endsBy: number
43 /** Epoch ms the mod recorded it: a snapshot taken a moment earlier may not list it yet. */
44 seenAt: number
45}
46
47/** A stored prompt that will start a turn later: a cron job, or a /loop wakeup. */
48export type Schedule = {
49 /** The cron job's id; a wakeup is `wakeup@<epoch ms>` until a stop's snapshot names it. */
50 id: string
51 kind: 'cron' | 'wakeup'
52 recurring: boolean
53 /** Epoch ms of its next run; 0 when not known (a recurring job after it ran, one seen only in a snapshot). */
54 nextAt: number
55 /** What it will do, in a few words: the wakeup's reason, else the prompt. */
56 detail: string
57 /** The prompt's head, one line, to match it when it fires. */
58 prompt: string
59 /** Epoch ms the mod recorded it: a snapshot taken a moment earlier may not list it yet. */
60 seenAt: number
61}
62
63/** What started the main turn when not the person: a notification ('task'), a stored prompt ('schedule'). */
64export type Trigger = '' | 'task' | 'schedule'
65
66export type Work = {
67 phase: Phase
68 /** Epoch ms the main turn started; 0 when not known. */
69 startedAt: number
70 /** The ended turn's length in ms. */
71 durationMs: number
72 /** Tool calls the main turn has started. */
73 tools: number
74 running: RunningTool[]
75 /** Why a turn that stopped short stopped. */
76 stopReason: '' | 'refusal' | 'error'
77 /** What started the turn; absent in a status stored before it was kept, and read as ''. */
78 trigger?: Trigger
79}
80
81declare module 'claude-code' {
82 interface PluginState {
83 'usage-mods': {
84 usage: Usage | null
85 isCompacting: boolean
86 isTurnRunning: boolean
87 now: number
88 work: Work
89 /** Flips on each second tick while work runs: the blinking dot. */
90 beat: boolean
91 /** Ids of subagents seen at work (listed agents and agent turns alike). */
92 helpers: string[]
93 /** Ids of subagent loops whose turn started and has not ended. */
94 helperTurns: string[]
95 helperAsks: HelperAsk[]
96 /** Background commands, monitors and workflow runs still at work, oldest first. */
97 tasks: BackgroundTask[]
98 /** Cron jobs and wakeups that will start a turn later. */
99 schedules: Schedule[]
100 }
101 }
102}
103