Live dashboard pane (Korean UI): top tabs for every Claude Code session on the machine by folder and for this session's folder, this one and its folder marked…

Claude Code 세션에서 지금 돌아가는 모든 작업을 한 창에서 보여 주는 mod입니다. 같은 폴더의 다른 세션과, 한 단계 위로 올라가면 이 컴퓨터의 모든 Claude Code 세션도 폴더별로 보고 메시지를 보내거나 끝낼 수 있습니다. 메인 세션, 서브에이전트, 에이전트 팀, 워크플로와 그 에이전트마다 무엇을 하고 있는지, 진행 상황(완료/전체), 쓴 토큰과 실행 시간을 표시하고, 프롬프트 위 세 줄에는 5시간·주간 한도 막대와 남은 %, 모델·effort 버튼, 워크플로·울트라코드 버튼을 띄웁니다. (화면 문구는 한국어)
설치 안내 페이지: https://comdoly-life.github.io/claude-session-dashboard/
A Claude Code mod: a list of the Claude Code sessions running in this folder (one level up, every session on the machine by folder, with this session marked, each one messaged or ended from its tab), and a live pane of everything running in the session — the main session, subagents, agent teams and workflows — with what each is doing, progress (done/total), tokens and run time, detail tabs, and three rows above the prompt: the 5-hour / weekly limit bars with what is left, chips for the model and effort, and toggles for workflows and ultracode. The UI text is in Korean.
대시보드 · 3개 실행 중 ↑입력 ↓출력 · 시간
☐ 메인 세션 (2/5) ↑230k ↓4.1k
대시보드 탭 구현 중
☐ 에이전트 팀 alpha (1/4) ↑80k ↓6k · 4m10s
1명 작업 중
☐ researcher · 자료 조사 (0/2) ↑40k ↓3k · 4m10s
☐ 탐색 에이전트 · 코드 구조 탐색 (0/1) ↑41k ↓2k · 1m20s
코드 찾는 중
☐ 워크플로 · review-changes (1/3) ↑50k ↓4k · 1m20s
2개 실행 중
☑ review:bugs (1/1) ↑20k ↓2k · 40s
☐ review:perf (0/1) ↑30k ↓2k · 1m20s
plan.ts 읽는 중
완료
☑ 범용 에이전트 · 문서 조사 (1/1) ↑20k ↓1k · 40s
프롬프트 위 세 줄(대괄호는 버튼, 선택된 것은 밝은 색 배경):
5시간 ████████████░░░░░░░░░░░░ 잔여 52% 주간 ███████████████████░░░░░ 잔여 19%
모델 [페이블] [오푸스 5.5] [소넷] [하이쿠] effort [low] [med] [high] [xhigh] [max]
워크플로 [ON] 울트라코드 [OFF]
공식 마켓플레이스에는 올라가 있지 않습니다. 저장소를 받아 내 컴퓨터의 마켓플레이스로 등록한 뒤 설치합니다. 셸(터미널)에서 차례로 실행하세요. Claude Code 2.1.300 이상과 git 이 필요합니다.
git clone https://github.com/comdoly-life/claude-session-dashboard.git ~/claude-session-dashboard
claude plugin marketplace add ~/claude-session-dashboard
claude plugin install session-dashboard@claude-session-dashboard
이미 열려 있는 Claude Code 세션에서는 /reload-plugins 로 불러오고, 아니면 새 세션을 시작합니다.
업데이트(새 코드를 받은 뒤 열린 세션에서 /reload-plugins):
git -C ~/claude-session-dashboard pull
claude plugin update session-dashboard@claude-session-dashboard
삭제:
claude plugin uninstall session-dashboard@claude-session-dashboard
claude plugin marketplace remove claude-session-dashboard
Not on the official marketplace: clone the repository, add the clone as a local marketplace, then install (the three commands above, run in a shell).
모든 세션 · 현재 세션): 맨 위에 늘 두 탭이 있고, 대시보드는 현재 세션 탭에서 시작합니다. 같은 폴더에서 실행 중인 Claude Code 세션을 한 줄씩 보여 주고, 그 아래에 이 세션의 작업 보드가 이어집니다. [모든 세션] [현재 세션]
~/work/my-app · 세션 2개
● my-app-38 [작업 세션] 작업 중 · 1m00s
● my-app-41 대기 중 · 3m00s
이 세션의 작업 · 1개 실행 중 ↑입력 ↓출력 · 시간
☐ 메인 세션 (2/5) ↑230k ↓4.1k
[작업 세션] 표시로 구분합니다. 앞의 점은 작업 중(초록), 대기 중(회색), 응답 기다림(노랑). 셸 명령을 돌리는 세션(명령 실행 중)처럼 쉬지 않는 상태는 모두 작업 중(초록)으로 셉니다.[ 메시지 ] [ 종료 ] 로 탭을 열지 않고 바로 메시지를 보내거나 끝낼 수 있습니다 (종료는 [ 한 번 더 ] 로 바뀐 뒤 다시 눌러야 합니다).모든 세션 탭은 이 컴퓨터에서 실행 중인 모든 세션을 폴더별로 보여 줍니다. 이 세션이 있는 폴더가 맨 위에 하늘색과 [작업폴더] 로 표시되고, 폴더 줄을 누르면 그 폴더의 세션 목록으로(← 모든 세션 으로 돌아옴), 현재 세션 탭은 이 세션의 폴더와 작업 보드로 돌아갑니다. [모든 세션] [현재 세션]
폴더 2개 · 세션 3개
▸ ~/work/my-app · 2개 (1개 작업 중) [작업폴더]
● my-app-38 [작업 세션] 작업 중 · 1m00s
● my-app-41 대기 중 · 3m00s
▸ ~/claude-mods · 1개 (1개 작업 중)
● claude-mods-2 작업 중 · 5s
메시지 보내기: 프롬프트에 /dash-send <세션 이름> 을 채워 줍니다. 메시지를 이어 쓰고 Enter 를 누르면 그 세션이 다음 차례에 읽습니다. 직접 /dash-send <세션 이름 또는 ID> <메시지> 로 보내도 됩니다.세션 종료: 한 번 더 눌러야 끝냅니다(창을 닫은 것과 같은 SIGTERM). 대화 기록은 남아 그 폴더에서 claude --resume <세션 ID> 로 다시 열 수 있습니다. 이 세션 자신은 끝낼 수 없습니다.(완료/전체): 워크플로는 스크립트를 미리 읽어 센 에이전트 수(결과에 따라 늘어나면 +), 메인 세션·서브에이전트는 할 일 목록, 팀은 작업 목록, 목록이 없는 에이전트는 0/1 → 1/1.↑입력 ↓출력)과 실행 시간, 실행 중인 항목 아래 줄에 지금 하는 일을 짧게 (도구 이름이나 실행 경로 대신 "plan.ts 읽는 중", "코드 찾는 중"처럼).모든 세션 · 현재 세션 옆에 붙습니다. 탭의 × 나 맨 위 [ × 닫기 ] 로 닫고, ← 목록 이나 맨 위 두 탭으로 목록으로 돌아갑니다.Read 3/3 ✓ › Summarize 0/1), 에이전트 목록(클릭하면 그 에이전트 탭).5시간 ████░░░░ 잔여 52% 주간 …: 5시간·주간(·지출) 한도. 막대는 전체 중 쓴 만큼을 색으로 칠하고, 뒤에 남은 비율을 %로 씁니다. 색은 남은 양이 60% 이상이면 초록, 그 아래로 내려갈수록 주황 → 주홍 → 진한 빨강. 터미널이 좁으면 막대를 줄이거나 빼고 숫자만 남깁니다.모델 페이블 오푸스 소넷 하이쿠: 누르면 그 계열의 최신 모델(별칭 fable·opus·sonnet·haiku)로 바꾸고, 고른 모델은 버전과 함께(오푸스 5.5) 표시합니다. Fable 처럼 동의가 먼저 필요한 모델은 /model 로 넘깁니다.effort low med high xhigh max: /effort <level> 과 같습니다. 모델이 지원하지 않는 단계면 그 안내가 뜹니다.워크플로 ON/OFF: /config 의 Dynamic workflows. 켜져 있으면 "워크플로로 해 줘"처럼 직접 요청할 때 워크플로 (여러 에이전트에게 나눠 맡기는 방식)를 쓸 수 있고, 끄면 워크플로도 울트라코드도 쓰지 않습니다.울트라코드 ON/OFF: /effort ultracode on|off (이 세션만). 요청하지 않아도 모든 작업을 워크플로로 돌립니다. 워크플로가 꺼져 있으면 그것부터 켜고, 울트라코드를 끌 때는 워크플로를 그대로 둡니다.… 이 붙고, 결과는 토스트로 알립니다. 실행 중인 턴이 있으면 /effort 는 그 턴이 끝난 뒤 적용됩니다./model·/effort·/config 로 바꿔도 따라갑니다./clear 뒤에는 지금 모델과 그 모델의 effort 를 바로 표시합니다. effort 는 설정에 모델별로 저장된 값 (modelSettings.<모델>.effortLevel), 없으면 effortLevel, CLAUDE_CODE_EFFORT_LEVEL 이 있으면 그 값이고, 첫 요청이 나가면 그 요청에 실제로 쓰인 effort 로 맞춥니다./dash 로 대시보드 창을 열고 닫습니다. 세션이 시작되면 자동으로 열립니다.SubagentStart/SubagentStop, 작업 목록)를 받아 세션 메모리에만 기록합니다.~/.claude/projects/<프로젝트>/<세션>/subagents/workflows/<run>/journal.jsonl)과 저장된 스크립트를 5초마다 읽어, 플러그인을 다시 불러오기 전에 시작한 실행도 보여 줍니다 (HOME, CLAUDE_CONFIG_DIR 환경 변수로 위치를 찾습니다).~/.claude/sessions/<pid>.json: 세션 ID, 폴더, 이름, 상태)을 읽고, ps 로 그 프로세스가 아직 살아 있는지 확인해 비정상 종료로 남은 파일은 뺍니다. 메시지는 엔진의 $.session.send(SendMessage 와 같은 전달), 종료는 kill -TERM <pid> 이며, 그 전에 PID 가 여전히 Claude Code 인지 확인합니다.$.store)에는 한도 기록과 최근 훅 오류만 남깁니다.$.config.set, effort·울트라코드 버튼은 $.command.run 으로 엔진의 기본 동작을 그대로 씁니다 (/model·/effort 처럼 모델과 effort 는 새 세션의 기본값으로도 저장됩니다). 울트라코드를 켤 때 Dynamic workflows 가 꺼져 있으면 $.config.set 으로 먼저 켭니다.⚠ 줄로 보여 줍니다.while 반복 등)는 최소값과 + 로 표시하고 실제로 늘어나면 따라갑니다.ps 가 없으면 남은 등록 파일을 걸러내지 못합니다.claude plugin validate .
claude plugin test .
hooks/register.tsx 가 훅과 그리기를, hooks/board.ts 가 보드 모델, hooks/view.tsx 가 화면, hooks/workflow.ts·hooks/plan.ts 가 워크플로 추적과 스크립트 분석, hooks/sessions.ts 가 세션 목록, hooks/controls.ts 가 모델·effort 버튼, hooks/format.ts 가 표기를 맡습니다. docs/index.html 은 GitHub Pages 로 내보내는 설치 안내 페이지입니다.
hooks/register.tsx 976 lines1import { atom, read, update } from 'claude-code'
2import type { AgentInfo, ConfigRow, EngineInterface, Register, SessionUsage, Settings } from 'claude-code'
3
4import type { Activity, Controls, EffortLevel, LimitWindow, Meter, ModelFamily, Peer, Tabs, TaskItem, Todo, WorkflowCall } from '../types'
5import { ALL, buildBoard, closeTab, openTab, showTab } from './board'
6import { CHIP, EFFORTS, MODELS, NO_CONTROLS, afterCommand, effortOf, familyOf, isEffortLevel, isRefusal, modelText, savedEffort } from './controls'
7import {
8 MAIN,
9 activityOf,
10 addUsage,
11 brief,
12 describeCall,
13 fit,
14 freshActivity,
15 isCurrent,
16 recordLimit,
17 limitBar,
18 sumTokens,
19 tokenText,
20} from './format'
21import { addressOf, alivePids, findPeer, folderKey, ownRow, peerName, peerOf, sendArgs } from './sessions'
22import { drawPane } from './view'
23import {
24 bindAgent,
25 callOfScript,
26 endWorkflow,
27 finishTask,
28 keepCall,
29 readJournal,
30 readNotice,
31 readWorkflowCall,
32 refuseTask,
33 scriptPaths,
34 startTask,
35 syncRun,
36 taskLabel,
37} from './workflow'
38
39const PANE = 'session-dashboard'
40const TITLE = '대시보드'
41const STORE_KEY = 'limit-windows'
42const FAULTS_KEY = 'faults'
43const TICK_MS = 5000
44const MAX_FINISHED = 6
45const MAX_TASKS = 6
46const MAX_RECENT = 12
47const MAX_FAULTS = 5
48const MAX_RUNS = 12
49/** A run whose journal and agents have been still this long has stopped unseen. */
50const STALE_MS = 15 * 60_000
51const BAND_GAP = 2
52const LIMIT_GAP = ' '
53const MODEL_ROW = 'model'
54const WORKFLOWS_ROW = 'workflows'
55// The Agent tool's own call spans a foreground subagent's run, and the
56// Workflow tool's launches a run's agents: a tool.call hook on either would
57// sit above those runs, and a hook is never run beneath its own frame.
58const NOT_AGENT = /^(?!(?:Agent|Task|Workflow)$)/
59
60const activity = atom({ plugin: 'session-dashboard', key: 'activity' } as const, {})
61const meter = atom({ plugin: 'session-dashboard', key: 'meter' } as const, { limits: [] })
62const tick = atom({ plugin: 'session-dashboard', key: 'tick' } as const, 0)
63const calls = atom({ plugin: 'session-dashboard', key: 'calls' } as const, {})
64const workflows = atom({ plugin: 'session-dashboard', key: 'workflows' } as const, [])
65const tasks = atom({ plugin: 'session-dashboard', key: 'tasks' } as const, {})
66const tabs = atom({ plugin: 'session-dashboard', key: 'tabs' } as const, { open: [], active: ALL })
67const faults = atom({ plugin: 'session-dashboard', key: 'faults' } as const, [])
68const controls = atom({ plugin: 'session-dashboard', key: 'controls' } as const, NO_CONTROLS)
69const peers = atom({ plugin: 'session-dashboard', key: 'peers' } as const, { list: [] })
70const scope = atom({ plugin: 'session-dashboard', key: 'scope' } as const, { level: 'folder' })
71
72type Engine = EngineInterface
73
74/** Where this session keeps its transcript folder, once found. */
75const place: { id?: string; dir?: string } = {}
76/** Each run's journal time when last read, and what its saved script said. */
77const journals = new Map<string, number>()
78const scripts = new Map<string, WorkflowCall | null>()
79let isSyncing = false
80let isReadingPeers = false
81/** This session's process, once its registry row is found: it keeps the row through a /clear. */
82let minePid: number | undefined
83
84/**
85 * This session's process id: the nearest ancestor of a child process it starts that has a row
86 * in the registry (the engine runs the child, maybe through a shell). Undefined where no `sh`
87 * or `ps` answers; the row is then known by its id in its folder.
88 */
89async function ownPid($: Engine, registered: ReadonlySet<number>): Promise<number | undefined> {
90 if (minePid !== undefined && registered.has(minePid)) return minePid
91 const climb = 'p=$PPID; for i in 1 2 3 4 5 6; do echo $p; p=$(ps -o ppid= -p $p | tr -d " "); [ -z "$p" ] && break; done'
92 const ran = await $.process.run(['sh', '-c', climb], { timeoutMs: 5000 })
93 for (const line of ran.stdout.split('\n')) {
94 const pid = Number(line.trim())
95 if (registered.has(pid)) return pid
96 }
97 return undefined
98}
99
100async function touch($: Engine, key: string, fn: (one: Activity, now: number) => Activity) {
101 const now = await $.clock.now()
102 await update($, activity, all => ({ ...all, [key]: { ...fn(all[key] ?? freshActivity(now), now), lastAt: now } }))
103}
104
105/** Keeps what failed where the board shows it, the store and the debug log. */
106async function fault($: Engine, where: string, error: unknown) {
107 const message = (error instanceof Error ? error.message : String(error)).slice(0, 200)
108 try {
109 $.ui.log(`session-dashboard ${where}: ${message}`, { to: 'debug' })
110 const at = await $.clock.now()
111 await update($, faults, list => [...list, { at, where, message }].slice(-MAX_FAULTS))
112 await $.store.set(FAULTS_KEY, await read($, faults))
113 } catch {
114 // Nowhere left to say it.
115 }
116}
117
118/** Runs a piece of bookkeeping; a failure costs the board a figure, never the event. */
119async function safe($: Engine, where: string, work: () => Promise<unknown>) {
120 try {
121 await work()
122 } catch (error) {
123 await fault($, where, error)
124 }
125}
126
127/** Moves the list up to every session or down to a folder's, and reads the registry again. */
128function look($: Engine, next: { level: 'folder' | 'all'; folder?: string }) {
129 void (async () => {
130 await update($, scope, () => next)
131 await update($, tabs, state => showTab(state, ALL))
132 await syncPeers($)
133 })().catch(error => fault($, 'scope', error))
134}
135
136async function recordMeter($: Engine, usage: Pick<SessionUsage, 'rateLimits' | 'cost' | 'context'>) {
137 const now = await $.clock.now()
138 const prev = await read($, meter)
139 const saved = prev.limits.length > 0 ? [] : await loadSaved($)
140 const known = [...prev.limits, ...saved]
141 const fresh = usage.rateLimits.map(reading =>
142 recordLimit(known.find(one => one.kind === reading.kind), reading, now),
143 )
144 const kept = known.filter(one => isCurrent(one, now) && !fresh.some(f => f.kind === one.kind))
145 const limits = [...fresh, ...kept].sort((a, b) => order(a.kind) - order(b.kind))
146 const next: Meter = { limits }
147 if (usage.cost !== undefined) next.costUsd = usage.cost.usd
148 if (usage.context.percent !== undefined) next.contextPercent = usage.context.percent
149 await update($, meter, () => next)
150 if (fresh.length > 0) await $.store.set(STORE_KEY, limits)
151}
152
153async function loadSaved($: Engine): Promise<LimitWindow[]> {
154 const saved = await $.store.get(STORE_KEY)
155 return Array.isArray(saved) ? (saved as LimitWindow[]) : []
156}
157
158function order(kind: string): number {
159 const at = ['five_hour', 'seven_day'].indexOf(kind)
160 return at === -1 ? 9 : at
161}
162
163/** The first of `paths` that reads: the script a call names instead of sending. */
164async function scriptFile($: Engine, paths: readonly string[]): Promise<string | undefined> {
165 for (const path of paths) {
166 const text = await $.fs.read(path).catch(() => undefined)
167 if (typeof text === 'string') return text
168 }
169 return undefined
170}
171
172/** A classic event's transcript path names the session's folder exactly. */
173function noteTranscript(path: unknown) {
174 if (typeof path !== 'string' || !path.endsWith('.jsonl')) return
175 place.dir = path.slice(0, -'.jsonl'.length)
176 place.id = place.dir.split('/').pop()
177}
178
179/** Where the engine keeps its files: `CLAUDE_CONFIG_DIR`, else `~/.claude`. */
180async function configDir($: Engine): Promise<string | undefined> {
181 const home = await $.env.get('HOME')
182 return (await $.env.get('CLAUDE_CONFIG_DIR')) ?? (home === undefined ? undefined : `${home}/.claude`)
183}
184
185/**
186 * Reads every Claude Code session running on this machine off the engine's registry
187 * (`<config>/sessions/<pid>.json`), dropping the files a crashed process left behind;
188 * this session is always listed, from its own answers when the registry lacks it.
189 */
190async function syncPeers($: Engine) {
191 if (isReadingPeers) return
192 isReadingPeers = true
193 try {
194 const mine = await $.session.id()
195 const cwd = folderKey(await $.session.cwd())
196 const homeDir = await $.env.get('HOME')
197 const config = await configDir($)
198 let list: Peer[] = []
199 let error: string | undefined
200 if (config !== undefined) {
201 const dir = `${config}/sessions`
202 const entries = (await $.fs.exists(dir).catch(() => false)) ? await $.fs.list(dir) : []
203 const files = entries.filter(entry => entry.kind === 'file' && /^\d+\.json$/.test(entry.name))
204 const found = await Promise.all(
205 files.map(async entry => {
206 const source = await $.fs.read(`${dir}/${entry.name}`).catch(() => undefined)
207 return typeof source === 'string' ? peerOf(source) : undefined
208 }),
209 )
210 list = found.filter((peer): peer is Peer => peer !== undefined)
211 }
212 if (list.length > 0) {
213 const pids = list.map(peer => peer.pid).join(',')
214 const alive = await $.process
215 .run(['ps', '-o', 'pid=,comm=', '-p', pids], { timeoutMs: 5000 })
216 .then(ran => alivePids(ran.stdout))
217 .catch((reason: unknown) => {
218 error = `프로세스를 확인하지 못했습니다 (${reason instanceof Error ? reason.message : String(reason)})`
219 return undefined
220 })
221 if (alive !== undefined) list = list.filter(peer => alive.has(peer.pid))
222 }
223 // Two processes can carry one session id (a conversation resumed in another folder): this
224 // session's row is its own process's, never the first row with its id.
225 const pid = await ownPid($, new Set(list.map(peer => peer.pid))).catch(() => undefined)
226 let own = ownRow(list, mine, cwd, pid ?? minePid)
227 if (own !== undefined) {
228 minePid = own.pid
229 if (own.sessionId !== mine) {
230 // Its own row still names the id it had before a /clear.
231 const renamed: Peer = { ...own, sessionId: mine }
232 list = list.map(peer => (peer === own ? renamed : peer))
233 own = renamed
234 }
235 } else {
236 const busy = (await read($, activity))[MAIN]?.isBusy === true
237 own = { pid: 0, sessionId: mine, cwd, status: busy ? 'busy' : 'idle' }
238 list = [own, ...list]
239 }
240 const now = await $.clock.now()
241 await update($, peers, () => ({
242 list,
243 mine,
244 minePid: own.pid,
245 folder: own.cwd,
246 readAt: now,
247 ...(homeDir !== undefined && { homeDir }),
248 ...(error !== undefined && { error }),
249 }))
250 } finally {
251 isReadingPeers = false
252 }
253}
254
255/** Whether a process id is still a Claude Code process: a pid freed by a crash may be another program's now. */
256async function isClaude($: Engine, pid: number): Promise<boolean> {
257 const ran = await $.process.run(['ps', '-o', 'comm=', '-p', String(pid)], { timeoutMs: 5000 })
258 return /claude|node|bun/i.test(ran.stdout)
259}
260
261/** Ends another session as closing its terminal would (SIGTERM): the transcript stays, to resume. */
262async function endPeer($: Engine, peer: Peer): Promise<string> {
263 if (peer.pid === 0 || peer.pid === minePid) return '이 세션은 여기서 끝낼 수 없습니다.'
264 if (!(await isClaude($, peer.pid))) return `${peerName(peer)} 세션은 이미 끝났습니다.`
265 const ran = await $.process.run(['kill', '-TERM', String(peer.pid)], { timeoutMs: 5000 })
266 if (ran.exitCode !== 0) return `끝내지 못했습니다: ${ran.stderr.trim() || `exit ${ran.exitCode}`}`
267 return `${peerName(peer)} 세션을 끝냈습니다.`
268}
269
270/** The session's own folder (`<config>/projects/<project>/<session id>`), where runs keep their journals. */
271async function sessionDir($: Engine): Promise<string | undefined> {
272 const id = await $.session.id()
273 if (place.id === id && place.dir !== undefined) return place.dir
274 const config = await configDir($)
275 if (config === undefined) return undefined
276 for (const where of new Set([await $.session.root(), await $.session.cwd()])) {
277 const dir = `${config}/projects/${where.replace(/[^A-Za-z0-9]/g, '-')}/${id}`
278 if (await $.fs.exists(`${dir}.jsonl`).catch(() => false)) {
279 place.id = id
280 place.dir = dir
281 return dir
282 }
283 }
284 return undefined
285}
286
287/**
288 * Reads the session's workflow runs off disk: each run's journal (which
289 * agent it started, under what label and phase, and which returned) and its
290 * saved script (name, phases, plan). A run is shown whether or not a hook saw
291 * it start: one started before this plugin loaded, or while it reloaded.
292 */
293async function syncRuns($: Engine) {
294 if (isSyncing) return
295 isSyncing = true
296 try {
297 const dir = await sessionDir($)
298 if (dir === undefined) return
299 const root = `${dir}/subagents/workflows`
300 if (!(await $.fs.exists(root).catch(() => false))) return
301 const runs = (await $.fs.list(root).catch(() => [])).filter(entry => entry.kind === 'dir' && entry.name.startsWith('wf_'))
302 if (runs.length === 0) return
303 const saved = await $.fs.list(`${dir}/workflows/scripts`).catch(() => [])
304 const stamped = await Promise.all(
305 runs.map(async run => ({ run, stat: await $.fs.stat(`${root}/${run.name}/journal.jsonl`).catch(() => undefined) })),
306 )
307 const newest = stamped
308 .filter((one): one is { run: (typeof runs)[number]; stat: NonNullable<typeof one.stat> } => one.stat !== undefined)
309 .sort((a, b) => b.stat.mtimeMs - a.stat.mtimeMs)
310 .slice(0, MAX_RUNS)
311 for (const { run, stat } of newest) {
312 const runId = run.name
313 if (journals.get(runId) === stat.mtimeMs) continue
314 const entries = readJournal(await $.fs.read(`${root}/${runId}/journal.jsonl`))
315 const script = saved.find(entry => entry.kind === 'file' && entry.name.endsWith(`-${runId}.js`))
316 if (!scripts.has(runId)) {
317 const text = script === undefined ? undefined : await $.fs.read(`${dir}/workflows/scripts/${script.name}`).catch(() => undefined)
318 scripts.set(runId, typeof text === 'string' ? (callOfScript(text, await read($, calls)) ?? null) : null)
319 }
320 const call = scripts.get(runId) ?? undefined
321 const at = Math.min(stat.mtimeMs, await $.clock.now())
322 const startedAt = script?.mtimeMs !== undefined && script.mtimeMs > 0 ? script.mtimeMs : at
323 await update($, workflows, list => syncRun(list, { runId, entries, startedAt, at, ...(call !== undefined && { call }) }))
324 journals.set(runId, stat.mtimeMs)
325 }
326 await settleStale($, newest.map(one => ({ runId: one.run.name, at: one.stat.mtimeMs })))
327 } catch (error) {
328 await fault($, 'workflow sync', error)
329 } finally {
330 isSyncing = false
331 }
332}
333
334/** A run still open whose journal and agents have all been still for long stopped without a word. */
335async function settleStale($: Engine, runs: readonly { runId: string; at: number }[]) {
336 const now = await $.clock.now()
337 const all = await read($, activity)
338 const flows = await read($, workflows)
339 for (const { runId, at } of runs) {
340 const flow = flows.find(one => one.runId === runId)
341 if (flow === undefined || flow.status !== 'running' || now - at < STALE_MS) continue
342 const heard = Math.max(at, ...flow.tasks.map(t => (t.agentId === undefined ? 0 : (all[t.agentId]?.lastAt ?? 0))))
343 if (now - heard < STALE_MS) continue
344 await update($, workflows, list => endWorkflow(list, { runId, status: 'stopped' }, now))
345 }
346}
347
348function todosOf(value: unknown): Todo[] | undefined {
349 if (!Array.isArray(value)) return undefined
350 return value.flatMap((row): Todo[] => {
351 if (typeof row !== 'object' || row === null) return []
352 const { content, status, activeForm } = row as Record<string, unknown>
353 if (typeof content !== 'string' || (status !== 'pending' && status !== 'in_progress' && status !== 'completed')) return []
354 return [{ content, status, ...(typeof activeForm === 'string' && { activeForm }) }]
355 })
356}
357
358/** Follows the session's task list through the calls that change it. */
359async function noteTasks($: Engine, tool: string, input: Record<string, unknown>, output: unknown, by: string) {
360 const now = await $.clock.now()
361 const text = (key: string) => (typeof input[key] === 'string' ? (input[key] as string) : undefined)
362 if (tool === 'TaskCreate') {
363 const created = (output as { task?: { id?: unknown; subject?: unknown } } | undefined)?.task
364 if (typeof created?.id !== 'string') return
365 const id = created.id
366 const subject = typeof created.subject === 'string' ? created.subject : (text('subject') ?? id)
367 const activeForm = text('activeForm')
368 await update($, tasks, all => ({
369 ...all,
370 [id]: { id, subject, status: all[id]?.status ?? 'pending', by, at: now, ...(activeForm !== undefined && { activeForm }) },
371 }))
372 } else if (tool === 'TaskUpdate') {
373 const id = text('taskId')
374 if (id === undefined) return
375 const status = text('status')
376 await update($, tasks, all => {
377 const { [id]: known, ...rest } = all
378 if (status === 'deleted') return rest
379 const base: TaskItem = known ?? { id, subject: text('subject') ?? id, status: 'pending', at: now }
380 const next: TaskItem = { ...base }
381 if (status === 'pending' || status === 'in_progress' || status === 'completed') next.status = status
382 const subject = text('subject')
383 if (subject !== undefined) next.subject = subject
384 const owner = text('owner')
385 if (owner !== undefined) next.owner = owner
386 const activeForm = text('activeForm')
387 if (activeForm !== undefined) next.activeForm = activeForm
388 return { ...rest, [id]: next }
389 })
390 }
391}
392
393/**
394 * The effort a session on this model starts with: `CLAUDE_CODE_EFFORT_LEVEL` over what
395 * settings keep for the model. A request's own effort (`turn.step`) tells better once one is sent.
396 */
397async function startingEffort($: Engine, model: string) {
398 const forced = await $.env.get('CLAUDE_CODE_EFFORT_LEVEL').catch(() => undefined)
399 const settings = await $.settings.read().catch((): Settings => ({}))
400 return effortOf(forced) ?? savedEffort(settings, model)
401}
402
403/**
404 * Reads what the band's buttons show: the main loop's model, the workflows row and the
405 * model's effort; an effort already known for the same model (a reload, a /clear) is kept.
406 */
407async function readControls($: Engine) {
408 const model = await $.session.model()
409 const rows = await $.config.list().catch((): ConfigRow[] => [])
410 const workflows = rows.find(row => row.key === WORKFLOWS_ROW)?.value
411 const effort = await startingEffort($, model)
412 await update($, controls, now => {
413 const next: Controls = { ...now, model }
414 if (typeof workflows === 'boolean') next.workflows = workflows
415 if (effort !== undefined && (now.effort === undefined || now.model !== model)) next.effort = effort
416 return next
417 })
418}
419
420/** Follows the main loop's model; another model starts on the effort settings keep for it. */
421async function noteModel($: Engine): Promise<string> {
422 const model = await $.session.model()
423 if ((await read($, controls)).model === model) return model
424 const effort = await startingEffort($, model)
425 await update($, controls, now => (effort === undefined ? { ...now, model } : { ...now, model, effort }))
426 return model
427}
428
429/** Runs a button's change in the background: the button drawn pending meanwhile, the outcome a toast. */
430function act($: Engine, key: string, work: () => Promise<string>) {
431 const run = async () => {
432 await update($, controls, now => ({ ...now, pending: key }))
433 try {
434 $.ui.toast(await work())
435 } catch (error) {
436 await fault($, `control ${key}`, error)
437 $.ui.toast(`바꾸지 못했습니다: ${error instanceof Error ? error.message : String(error)}`)
438 } finally {
439 await update($, controls, now => {
440 if (now.pending !== key) return now
441 const { pending: _, ...rest } = now
442 return rest
443 })
444 }
445 }
446 void run().catch(error => fault($, 'control', error))
447}
448
449/** The family's alias names its latest model; a pick the `/config` row refuses (one asking consent first) goes through `/model`. */
450async function chooseModel($: Engine, family: ModelFamily): Promise<string> {
451 const set = await $.config.set({ key: MODEL_ROW, value: family }).catch((error: unknown) => ({ deny: String(error) }))
452 let refused: string | undefined
453 if (set.deny !== undefined) {
454 const ran = await $.command.run({ command: 'model', args: family })
455 if (isRefusal(ran.text)) refused = ran.text
456 }
457 const model = await noteModel($)
458 return refused ?? `모델: ${modelText(model)}`
459}
460
461async function chooseEffort($: Engine, level: EffortLevel): Promise<string> {
462 const ran = await $.command.run({ command: 'effort', args: level })
463 await update($, controls, now => afterCommand(now, 'effort', level, ran.text))
464 const effort = (await read($, controls)).effort
465 return effort === level ? `effort: ${level}` : (ran.text ?? `effort: ${effort ?? '?'}`)
466}
467
468/** Whether the band draws ultracode on: it runs on dynamic workflows, so with them off it is off. */
469function isUltracodeOn(state: Controls): boolean {
470 return state.ultracode && state.workflows !== false
471}
472
473/**
474 * Ultracode on or off. On needs the `/config` row `workflows` (Dynamic workflows), which
475 * it turns on first where it is off; off leaves workflows on, for a workflow asked for by name.
476 */
477async function toggleUltracode($: Engine): Promise<string> {
478 const now = await read($, controls)
479 const wasOn = isUltracodeOn(now)
480 let hasOpened = false
481 if (!wasOn && now.workflows === false) {
482 const set = await $.config.set({ key: WORKFLOWS_ROW, value: true })
483 if (set.deny !== undefined) return `워크플로를 켜지 못해 울트라코드를 켤 수 없습니다: ${set.deny}`
484 await update($, controls, current => ({ ...current, workflows: true }))
485 hasOpened = true
486 }
487 const args = `ultracode ${wasOn ? 'off' : 'on'}`
488 const ran = await $.command.run({ command: 'effort', args })
489 await update($, controls, current => afterCommand(current, 'effort', args, ran.text))
490 const isOn = isUltracodeOn(await read($, controls))
491 if (isOn === wasOn) return ran.text ?? '울트라코드를 바꾸지 못했습니다.'
492 if (!isOn) return '울트라코드 끔'
493 return hasOpened ? '워크플로를 켜고 울트라코드 켬 (이 세션만)' : '울트라코드 켬 (이 세션만)'
494}
495
496/** The `/config` row `workflows` (Dynamic workflows): off takes ultracode down with it. */
497async function toggleWorkflows($: Engine): Promise<string> {
498 const isOn = (await read($, controls)).workflows !== true
499 const set = await $.config.set({ key: WORKFLOWS_ROW, value: isOn })
500 if (set.deny !== undefined) return `워크플로를 바꾸지 못했습니다: ${set.deny}`
501 const workflows = set.value === true
502 await update($, controls, now => ({ ...now, workflows }))
503 return workflows ? '워크플로 켬' : '워크플로 끔 (울트라코드도 쓸 수 없음)'
504}
505
506export const register: Register = on => {
507 on('session.start', async ($, e, next) => {
508 await $.command.register({
509 name: 'dash',
510 description: '세션 대시보드(서브에이전트·팀·워크플로·토큰)를 열거나 닫습니다',
511 })
512 await $.command.register({
513 name: 'dash-send',
514 description: '다른 Claude Code 세션에 메시지를 보냅니다: /dash-send <세션 이름 또는 ID> <메시지>',
515 })
516 await safe($, 'sessions', () => syncPeers($))
517 await safe($, 'meter', async () => recordMeter($, await $.session.usage()))
518 await safe($, 'controls', () => readControls($))
519 $.clock.every(TICK_MS, () => {
520 void update($, tick, n => n + 1)
521 void syncRuns($)
522 void safe($, 'sessions', async () => {
523 const pane = (await $.ui.panes()).find(one => one.id === PANE)
524 if (pane?.isShown === true) await syncPeers($)
525 })
526 })
527 void syncRuns($)
528 void $.ui.open({ id: PANE, title: TITLE })
529
530 return next(e)
531 })
532
533 on('command.run', { command: 'dash' }, async $ => {
534 const pane = (await $.ui.panes()).find(one => one.id === PANE)
535 if (pane?.isShown === true) {
536 await $.ui.close({ id: PANE })
537 return { text: '대시보드를 닫았습니다.' }
538 }
539 await $.ui.open({ id: PANE, title: TITLE })
540
541 return { text: '대시보드를 열었습니다.' }
542 })
543
544 on('command.run', { command: 'dash-send' }, async ($, e) => {
545 const asked = sendArgs(e.args)
546 if (asked === undefined) return { text: '사용법: /dash-send <세션 이름 또는 ID> <메시지>' }
547 await safe($, 'sessions', () => syncPeers($))
548 const { list, minePid: own } = await read($, peers)
549 const peer = findPeer(
550 list.filter(one => one.pid !== own),
551 asked.to,
552 )
553 if (peer === undefined) return { text: `'${asked.to}' 세션을 찾지 못했습니다. 대시보드의 모든 세션 목록에서 이름을 확인하세요.` }
554 const sent = await $.session.send({ to: addressOf(peer), text: asked.text })
555 return { text: sent.isDelivered ? `${peerName(peer)} 세션에 보냈습니다.` : `보내지 못했습니다: ${sent.reason}` }
556 })
557
558 // The person's own /model and /effort, typed or picked: the band follows what they left in force.
559 on('command.run', { command: /^(?:model|effort)$/ }, async ($, e, next) => {
560 const result = await next(e)
561 await safe($, 'controls', async () => {
562 await update($, controls, now => afterCommand(now, e.command, e.args, result.text))
563 if (e.command === 'model') await noteModel($)
564 })
565
566 return result
567 })
568
569 // The same rows changed in /config; this plugin's own $.config.set never passes here.
570 on('config.set', { key: /^(?:model|workflows)$/ }, async ($, e, next) => {
571 const result = await next(e)
572 if (result.deny === undefined) {
573 const workflows = result.value === true
574 await safe($, 'controls', () =>
575 e.key === WORKFLOWS_ROW ? update($, controls, now => ({ ...now, workflows })) : noteModel($),
576 )
577 }
578
579 return result
580 })
581
582 // A /clear goes on under a new session id and fires no session.start: the band reads its model, effort and limits again.
583 on('classic.SessionStart', async ($, e, next) => {
584 if (e.source === 'clear') {
585 await safe($, 'meter', async () => recordMeter($, await $.session.usage()))
586 await safe($, 'controls', () => readControls($))
587 }
588
589 return next(e)
590 })
591
592 on('session.measure', async ($, e, next) => {
593 await safe($, 'meter', () => recordMeter($, e))
594
595 return next(e)
596 })
597
598 on('turn.start', async ($, e, next) => {
599 await safe($, 'turn.start', () =>
600 touch($, e.agentId ?? MAIN, one => {
601 const { endedAt: _, ...rest } = one
602 return { ...rest, isBusy: true }
603 }),
604 )
605
606 return next(e)
607 })
608
609 on('turn.step', async function* ($, e, next) {
610 const effort = e.effort
611 if (e.agentId === undefined && isEffortLevel(effort)) {
612 await safe($, 'controls', async () => {
613 if ((await read($, controls)).effort !== effort) await update($, controls, now => ({ ...now, effort }))
614 })
615 }
616 const result = yield* next(e)
617 const usage = result.usage
618 if (usage !== null) {
619 await safe($, 'turn.step', () => touch($, e.agentId ?? MAIN, one => ({ ...one, tokens: addUsage(one.tokens, usage) })))
620 }
621
622 return result
623 })
624
625 on('turn.complete', async ($, e, next) => {
626 const agentId = e.agentId
627 const usage = e.usage
628 await safe($, 'turn.complete', async () => {
629 // A loop whose steps passed this plugin by is counted at its end.
630 await touch($, agentId ?? MAIN, (one, now) => ({
631 ...one,
632 isBusy: false,
633 running: [],
634 endedAt: now,
635 tokens: one.tokens.requests === 0 && usage !== undefined ? addUsage(one.tokens, usage) : one.tokens,
636 }))
637 if (agentId === undefined) return noteModel($)
638 const isTask = (await read($, workflows)).some(flow => flow.tasks.some(t => t.agentId === agentId))
639 if (!isTask) return
640 const now = await $.clock.now()
641 const tokens = (await read($, activity))[agentId]?.tokens ?? freshActivity(now).tokens
642 await update($, workflows, list => finishTask(list, agentId, { isFailed: e.reason !== 'answer', tokens, now }))
643 })
644
645 return next(e)
646 })
647
648 on('classic.SubagentStart', async ($, e, next) => {
649 await safe($, 'SubagentStart', async () => {
650 noteTranscript(e.transcript_path)
651 await touch($, e.agent_id, (one, now) => {
652 const { stoppedAt: _, ...rest } = one
653 return { ...rest, kind: e.agent_type, firstSeen: Math.min(one.firstSeen, now) }
654 })
655 if (e.agent_type === 'workflow-subagent') await syncRuns($)
656 })
657
658 return next(e)
659 })
660
661 on('classic.SubagentStop', async ($, e, next) => {
662 await safe($, 'SubagentStop', async () => {
663 noteTranscript(e.transcript_path)
664 const reply = typeof e.last_assistant_message === 'string' ? e.last_assistant_message.slice(0, 600) : undefined
665 await touch($, e.agent_id, (one, now) => ({
666 ...one,
667 isBusy: false,
668 running: [],
669 stoppedAt: now,
670 ...(reply !== undefined && { reply }),
671 }))
672 })
673
674 return next(e)
675 })
676
677 on('classic.TaskCreated', async ($, e, next) => {
678 await safe($, 'TaskCreated', async () => {
679 const at = await $.clock.now()
680 const id = e.task_id
681 await update($, tasks, all => ({
682 ...all,
683 [id]: { ...all[id], id, subject: e.task_subject, status: all[id]?.status ?? 'pending', at: all[id]?.at ?? at },
684 }))
685 })
686
687 return next(e)
688 })
689
690 on('classic.TaskCompleted', async ($, e, next) => {
691 await safe($, 'TaskCompleted', async () => {
692 const at = await $.clock.now()
693 const id = e.task_id
694 await update($, tasks, all => ({
695 ...all,
696 [id]: { ...all[id], id, subject: all[id]?.subject ?? e.task_subject, status: 'completed' as const, at: all[id]?.at ?? at },
697 }))
698 })
699
700 return next(e)
701 })
702
703 on('tool.check', { tool: 'Workflow' }, async ($, e, next) => {
704 const verdict = await next(e)
705 const id = e.tool_use_id
706 if (id === undefined || verdict.decision === 'deny') return verdict
707 await safe($, 'Workflow check', async () => {
708 const call = readWorkflowCall(e.input, await scriptFile($, scriptPaths(e.input)))
709 if (call !== undefined) await update($, calls, all => keepCall(all, id, call))
710 })
711
712 return verdict
713 })
714
715 // 서브에이전트·팀원·워크플로 에이전트가 받은 지시를 한 줄로: 세부 탭의 "맡은 일"
716 on('agent.spawn', async ($, e, next) => {
717 const result = await next(e)
718 const agentId = result.agentId
719 const task = brief(String(e.prompt ?? ''))
720 if (agentId !== undefined && task !== '') {
721 await safe($, 'agent.spawn', () => touch($, agentId, one => ({ ...one, task })))
722 }
723
724 return result
725 })
726
727 // 메인 세션의 "맡은 일": 사람이 직접(터미널·원격·SDK) 보낸 마지막 요청. 슬래시 명령, 보이지 않는 알림,
728 // 다른 세션이 보낸 메시지는 덮어쓰지 않는다.
729 on('prompt.submit', async ($, e, next) => {
730 const kind = e.origin.kind
731 const isOwn = kind === 'composer' || kind === 'bridge' || kind === 'sdk'
732 if (isOwn && e.command === undefined && e.isMeta !== true) {
733 const task = brief(e.text)
734 if (task !== '') await safe($, 'prompt.submit', () => touch($, MAIN, one => ({ ...one, task })))
735 }
736
737 return next(e)
738 })
739
740 on('agent.spawn', { workflow: { runId: /^wf_/ } }, async ($, e, next) => {
741 const run = e.workflow
742 if (run === undefined) return next(e)
743 const key = e.tool_use_id ?? ''
744 const { runId, agentIndex: index } = run
745 await safe($, 'workflow spawn', async () => {
746 const now = await $.clock.now()
747 const call = key === '' ? undefined : (await read($, calls))[key]
748 const label = taskLabel(String(e.description ?? ''), String(e.prompt ?? ''))
749 await update($, workflows, list => startTask(list, { key, runId, index, label, now, ...(call && { call }) }))
750 })
751 const result = await next(e)
752 await safe($, 'workflow spawn', async () => {
753 if (result.agentId !== undefined) {
754 const agentId = result.agentId
755 await update($, workflows, list => bindAgent(list, runId, key, index, agentId))
756 } else if (result.deny !== undefined) {
757 const now = await $.clock.now()
758 await update($, workflows, list => refuseTask(list, runId, key, index, now))
759 }
760 })
761
762 return result
763 })
764
765 on('session.append', { origin: { kind: 'task-notification' } }, async ($, e, next) => {
766 const stored = await next(e)
767 await safe($, 'task notification', async () => {
768 const text = e.message.content.map(block => (block.type === 'text' ? block.text : '')).join('\n')
769 const notice = readNotice(text)
770 if (notice === undefined) return
771 if (notice.runId !== undefined) journals.delete(notice.runId)
772 await syncRuns($)
773 const now = await $.clock.now()
774 await update($, workflows, list => endWorkflow(list, notice, now))
775 })
776
777 return stored
778 })
779
780 on('tool.call', { tool: NOT_AGENT }, async ($, e, next) => {
781 const key = e.agentId ?? MAIN
782 const input = e as unknown as Record<string, unknown>
783 const call = { id: e.tool_use_id, text: describeCall(e.tool, input), doing: activityOf(e.tool, input) }
784 const todos = e.tool === 'TodoWrite' ? todosOf(input.todos) : undefined
785 await safe($, 'tool.call', () =>
786 touch($, key, one => ({
787 ...one,
788 isBusy: true,
789 running: [...one.running, call].slice(-8),
790 ...(todos !== undefined && { todos }),
791 })),
792 )
793 let output: unknown
794 try {
795 const result = await next(e)
796 if (result.deny === undefined && result.isError !== true) output = result.result
797 return result
798 } finally {
799 await safe($, 'tool.call', async () => {
800 await touch($, key, one => ({
801 ...one,
802 running: one.running.filter(c => c.id !== call.id),
803 last: call.text,
804 recent: [...(one.recent ?? []), call.text].slice(-MAX_RECENT),
805 tools: one.tools + 1,
806 }))
807 if (output !== undefined) await noteTasks($, e.tool, input, output, key)
808 })
809 }
810 })
811
812 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
813 const kit = $.ui.resolve(e)
814 const { Box, Text } = kit
815 try {
816 await read($, tick)
817 const now = await $.clock.now()
818 const all = await read($, activity)
819 const { costUsd, contextPercent } = await read($, meter)
820 const agents = await $.agent.list().catch((): AgentInfo[] => [])
821 const flows = await read($, workflows)
822 const taskList = await read($, tasks)
823 const tabState = await read($, tabs)
824 const faultList = await read($, faults)
825 const peerState = await read($, peers)
826 const scopeState = await read($, scope)
827 if (peerState.readAt === undefined) void safe($, 'sessions', () => syncPeers($))
828 const board = buildBoard({ now, agents, activity: all, flows, tasks: taskList, maxTasks: MAX_TASKS, maxFinished: MAX_FINISHED })
829 const total = sumTokens(Object.values(all).map(one => one.tokens))
830 const totals = [
831 `합계 ${tokenText(total) || '0'}`,
832 costUsd === undefined ? '' : `$${costUsd.toFixed(2)}`,
833 contextPercent === undefined ? '' : `컨텍스트 ${contextPercent}%`,
834 ]
835 .filter(Boolean)
836 .join(' · ')
837 const press = (change: (state: Tabs) => Tabs) => {
838 void update($, tabs, change).catch(error => fault($, 'tab', error))
839 }
840 return drawPane({
841 kit,
842 now,
843 width: e.props.bodyColumns,
844 board,
845 tabs: tabState,
846 agents,
847 activity: all,
848 flows,
849 tasks: taskList,
850 faults: faultList,
851 totals,
852 open: (key, title) => press(state => openTab(state, { key, title: fit(title, 24) })),
853 close: key => press(state => closeTab(state, key)),
854 show: key => press(state => showTab(state, key)),
855 peers: peerState,
856 scope: scopeState,
857 goAll: () => look($, { level: 'all' }),
858 goFolder: path => look($, path === undefined ? { level: 'folder' } : { level: 'folder', folder: path }),
859 openPeer: peer => {
860 if (peer.pid === peerState.minePid) press(state => openTab(state, { key: 'main', title: '메인 세션' }))
861 else press(state => openTab(state, { key: `peer:${peer.pid}`, title: fit(peerName(peer), 24) }))
862 },
863 message: peer => {
864 const to = peer.name !== undefined && !/\s/.test(peer.name) ? peer.name : String(peer.pid)
865 void $.prompt
866 .fill({ text: `/dash-send ${to} ` })
867 .then(() => $.ui.toast('프롬프트에 메시지를 이어 쓰고 Enter를 누르세요.'))
868 .catch(error => fault($, 'message', error))
869 },
870 end: peer => {
871 void (async () => {
872 if (scopeState.ending !== peer.pid) {
873 await update($, scope, now => ({ ...now, ending: peer.pid }))
874 $.ui.toast(`한 번 더 누르면 ${peerName(peer)} 세션을 끝냅니다.`)
875 return
876 }
877 await update($, scope, ({ ending: _, ...rest }) => rest)
878 $.ui.toast(await endPeer($, peer))
879 await syncPeers($)
880 })().catch(error => fault($, 'end', error))
881 },
882 })
883 } catch (error) {
884 const message = error instanceof Error ? error.message : String(error)
885 void $.store.set(FAULTS_KEY, [{ at: Date.now(), where: 'render', message }]).catch(() => undefined)
886 return (
887 <Box flexDirection="column">
888 <Text color="error">대시보드를 그리지 못했습니다.</Text>
889 <Text dimColor wrap="wrap">
890 {message}
891 </Text>
892 </Box>
893 )
894 }
895 })
896
897 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
898 if (e.props.hasSurvey) return next(e)
899 await read($, tick)
900 const now = await $.clock.now()
901 const windows = (await read($, meter)).limits.filter(one => isCurrent(one, now))
902 const state = await read($, controls)
903
904 const { Box, Text, Button } = $.ui.resolve(e)
905 const press = (key: string, work: () => Promise<string>) => () => act($, key, work)
906 const family = familyOf(state.model)
907 const room = Math.floor((e.props.bodyColumns - LIMIT_GAP.length * (windows.length - 1)) / Math.max(1, windows.length))
908 // A chip: the gray of an idle button, or its group's bright color once picked.
909 const chip = (key: string, label: string, picked: string | undefined, onPress: () => void) => (
910 <Button plain key={key} onPress={onPress}>
911 {picked === undefined ? (
912 <Text backgroundColor={CHIP.idle} color="text">{` ${label}${state.pending === key ? '…' : ''} `}</Text>
913 ) : (
914 <Text backgroundColor={picked} color={CHIP.ink} weight="bold">{` ${label}${state.pending === key ? '…' : ''} `}</Text>
915 )}
916 </Button>
917 )
918
919 // The blank row above keeps the band apart from the transcript's output; the limits, the
920 // model and effort, and workflows with ultracode keep a row each; a narrow terminal wraps groups.
921 return (
922 <Box flexDirection="column" marginTop={1}>
923 {windows.length > 0 && (
924 <Text wrap="truncate-end">
925 {windows.map((window, index) => {
926 const bar = limitBar(window, room)
927 return (
928 <Text>
929 {index > 0 ? LIMIT_GAP : ''}
930 <Text weight="bold">{bar.label}</Text>{' '}
931 {bar.used !== '' && <Text color={bar.color}>{bar.used}</Text>}
932 {bar.free !== '' && <Text dimColor>{bar.free}</Text>}
933 {bar.used !== '' || bar.free !== '' ? ' ' : ''}
934 <Text dimColor>잔여 </Text>
935 <Text color={bar.color} weight="bold">{`${bar.left}%`}</Text>
936 </Text>
937 )
938 })}
939 </Text>
940 )}
941 <Box flexDirection="row" flexWrap="wrap" columnGap={BAND_GAP}>
942 <Box flexDirection="row" columnGap={1}>
943 <Text dimColor>모델</Text>
944 {MODELS.map(one => {
945 const key = `model:${one.family}`
946 const isPicked = one.family === family
947 return chip(key, isPicked ? modelText(state.model) : one.label, isPicked ? CHIP.model : undefined, press(key, () => chooseModel($, one.family)))
948 })}
949 </Box>
950 <Box flexDirection="row" columnGap={1}>
951 <Text dimColor>effort</Text>
952 {EFFORTS.map(one => {
953 const key = `effort:${one.level}`
954 return chip(key, one.label, one.level === state.effort ? CHIP.effort : undefined, press(key, () => chooseEffort($, one.level)))
955 })}
956 </Box>
957 </Box>
958 <Box flexDirection="row" flexWrap="wrap" columnGap={BAND_GAP}>
959 <Box flexDirection="row" columnGap={1}>
960 <Text dimColor>워크플로</Text>
961 {state.workflows === true
962 ? chip('workflows', 'ON', CHIP.workflows, press('workflows', () => toggleWorkflows($)))
963 : chip('workflows', state.workflows === false ? 'OFF' : '—', undefined, press('workflows', () => toggleWorkflows($)))}
964 </Box>
965 <Box flexDirection="row" columnGap={1}>
966 <Text dimColor>울트라코드</Text>
967 {isUltracodeOn(state)
968 ? chip('ultracode', 'ON', CHIP.ultracode, press('ultracode', () => toggleUltracode($)))
969 : chip('ultracode', 'OFF', undefined, press('ultracode', () => toggleUltracode($)))}
970 </Box>
971 </Box>
972 </Box>
973 )
974 })
975}
976hooks/board.ts 343 lines1import type { AgentInfo, AgentStatus } from 'claude-code'
2
3import type { Activity, Tab, Tabs, TaskItem, Todo, Tokens, Workflow, WorkflowTask } from '../types'
4import { MAIN, ZERO_TOKENS, sumTokens } from './format'
5import { finishedAt, progress, standing, visibleTasks } from './workflow'
6
7/** Where an item of the board stands: `idle` is alive but waiting (a teammate, the main session). */
8export type ItemStatus = 'running' | 'idle' | 'done' | 'failed'
9
10export type ItemKind = 'main' | 'agent' | 'team' | 'teammate' | 'flow' | 'task'
11
12export type Count = { done: number; total: number; isOpen?: boolean }
13
14/** One row of the board and what its detail tab opens on. */
15export type Item = {
16 /** The tab key: `main`, `agent:<id>`, `team`, `flow:<key>` or `task:<flow key>:<index>`. */
17 key: string
18 kind: ItemKind
19 title: string
20 sub?: string
21 status: ItemStatus
22 progress?: Count
23 tokens: Tokens
24 startedAt?: number
25 endedAt?: number
26 /** What it is doing now, in plain words. */
27 doing?: string
28 children: Item[]
29 /** Settled children left off the board. */
30 folded?: number
31 /** A shorter label for its tab, when the title leads with its kind. */
32 tab?: string
33}
34
35export type Board = { main: Item; running: Item[]; finished: Item[]; hidden: number }
36
37export type BoardInput = {
38 now: number
39 agents: readonly AgentInfo[]
40 activity: Readonly<Record<string, Activity>>
41 flows: readonly Workflow[]
42 tasks: Readonly<Record<string, TaskItem>>
43 /** Rows a running workflow lists before it folds its settled agents. */
44 maxTasks: number
45 /** Settled items the board keeps before it counts the rest. */
46 maxFinished: number
47}
48
49const MAX_DEPTH = 4
50
51/** The engine's agent types in Korean; a plugin's or a custom one keeps its own name. */
52const TYPE_LABELS: Record<string, string> = {
53 'general-purpose': '범용 에이전트',
54 claude: '범용 에이전트',
55 Explore: '탐색 에이전트',
56 Plan: '계획 에이전트',
57 'claude-code-guide': 'Claude Code 안내',
58 'statusline-setup': '상태 줄 설정',
59 'workflow-subagent': '워크플로 에이전트',
60 teammate: '팀원',
61 fork: '포크',
62}
63
64export function typeLabel(type: string): string {
65 return TYPE_LABELS[type] ?? type
66}
67
68/**
69 * The board: the main session, then everything that runs (the agent team,
70 * subagents and their children, workflows and their agents, agents only a
71 * SubagentStart named), then what settled, newest first.
72 */
73export function buildBoard(input: BoardInput): Board {
74 const { now, agents, activity, flows, tasks } = input
75 const allTasks = Object.values(tasks)
76 const linked = new Set(flows.flatMap(flow => flow.tasks.map(t => t.agentId ?? '')))
77 const listed = new Set(agents.map(agent => agent.id))
78 const live = (id: string | undefined, fallback: Tokens = ZERO_TOKENS) => {
79 const tokens = id === undefined ? undefined : activity[id]?.tokens
80 return tokens !== undefined && tokens.requests > 0 ? tokens : fallback
81 }
82
83 const mainOne = activity[MAIN]
84 const main: Item = {
85 key: 'main',
86 kind: 'main',
87 title: '메인 세션',
88 status: mainOne?.isBusy === true ? 'running' : 'idle',
89 tokens: mainOne?.tokens ?? ZERO_TOKENS,
90 doing: doingOf(mainOne, allTasks.find(t => t.status === 'in_progress' && (t.by === MAIN || t.owner === undefined))) ??
91 (mainOne?.isBusy === true ? '생각 중' : '대기 중'),
92 children: [],
93 }
94 const mainCount = todoCount(mainOne?.todos) ?? taskCount(allTasks)
95 if (mainCount !== undefined) main.progress = mainCount
96
97 const tops: Item[] = []
98
99 const teammates = agents.filter(isTeammate)
100 if (teammates.length > 0) tops.push(teamItem(teammates, allTasks, activity))
101
102 const subagents = agents.filter(agent => !isTeammate(agent))
103 const ids = new Set(subagents.map(agent => agent.id))
104 const childrenOf = new Map<string, AgentInfo[]>()
105 for (const agent of subagents) {
106 const parent = agent.parentId !== undefined && ids.has(agent.parentId) ? agent.parentId : ''
107 childrenOf.set(parent, [...(childrenOf.get(parent) ?? []), agent])
108 }
109 const agentItem = (agent: AgentInfo, depth: number): Item => {
110 const one = activity[agent.id]
111 const status = statusOf(agent.status)
112 const item: Item = {
113 key: `agent:${agent.id}`,
114 kind: 'agent',
115 title: agent.name ?? typeLabel(agent.type),
116 sub: agent.description,
117 status,
118 progress: todoCount(one?.todos) ?? single(status),
119 tokens: one?.tokens ?? ZERO_TOKENS,
120 children: depth >= MAX_DEPTH ? [] : (childrenOf.get(agent.id) ?? []).map(child => agentItem(child, depth + 1)),
121 }
122 if (one !== undefined) item.startedAt = one.firstSeen
123 const end = one?.stoppedAt ?? one?.endedAt
124 if (isSettled(status) && end !== undefined) item.endedAt = end
125 const doing = status === 'running' ? (doingOf(one) ?? '생각 중') : undefined
126 if (doing !== undefined) item.doing = doing
127 return item
128 }
129 tops.push(...(childrenOf.get('') ?? []).map(agent => agentItem(agent, 0)))
130
131 for (const flow of flows) tops.push(flowItem(flow, now, input.maxTasks, activity, live))
132
133 // A loop only a SubagentStart named: a workflow agent before its run's
134 // journal is read, or one of a run this session never filed.
135 for (const [id, one] of Object.entries(activity)) {
136 if (id === MAIN || listed.has(id) || linked.has(id) || one.kind === undefined) continue
137 const status: ItemStatus = one.stoppedAt !== undefined ? 'done' : 'running'
138 const item: Item = {
139 key: `agent:${id}`,
140 kind: 'agent',
141 title: typeLabel(one.kind),
142 status,
143 progress: todoCount(one.todos) ?? single(status),
144 tokens: one.tokens,
145 startedAt: one.firstSeen,
146 children: [],
147 }
148 if (one.stoppedAt !== undefined) item.endedAt = one.stoppedAt
149 const doing = status === 'running' ? (doingOf(one) ?? '생각 중') : undefined
150 if (doing !== undefined) item.doing = doing
151 tops.push(item)
152 }
153
154 const running = tops
155 .filter(item => !isSettled(item.status))
156 .sort((a, b) => (a.startedAt ?? 0) - (b.startedAt ?? 0))
157 const settled = tops
158 .filter(item => isSettled(item.status))
159 .sort((a, b) => (b.endedAt ?? b.startedAt ?? 0) - (a.endedAt ?? a.startedAt ?? 0))
160 return {
161 main,
162 running,
163 finished: settled.slice(0, input.maxFinished),
164 hidden: Math.max(0, settled.length - input.maxFinished),
165 }
166}
167
168function flowItem(
169 flow: Workflow,
170 now: number,
171 maxTasks: number,
172 activity: Readonly<Record<string, Activity>>,
173 live: (id: string | undefined, fallback?: Tokens) => Tokens,
174): Item {
175 const standingNow = standing(flow, now)
176 const count = progress(flow, standingNow)
177 const status: ItemStatus = standingNow === 'running' ? 'running' : standingNow === 'done' ? 'done' : 'failed'
178 const { shown, folded } = visibleTasks(flow, maxTasks)
179 const item: Item = {
180 key: `flow:${flow.key}`,
181 kind: 'flow',
182 title: `워크플로 · ${flow.name}`,
183 tab: flow.name,
184 status,
185 progress: { done: count.done, total: count.total, isOpen: count.isOpen },
186 tokens: sumTokens(flow.tasks.map(task => live(task.agentId, task.tokens))),
187 startedAt: flow.startedAt,
188 children: status === 'running' ? shown.map(task => taskItem(flow, task, activity, live)) : [],
189 folded: status === 'running' ? folded : 0,
190 }
191 if (status !== 'running') {
192 const end = finishedAt(flow)
193 if (end !== undefined) item.endedAt = end
194 } else {
195 item.doing = [
196 count.running > 0 ? `${count.running}개 실행 중` : '',
197 count.waiting > 0 ? `${count.waiting}개 대기` : '',
198 count.failed > 0 ? `${count.failed}개 실패` : '',
199 ]
200 .filter(Boolean)
201 .join(' · ')
202 }
203 return item
204}
205
206export function taskItem(
207 flow: Workflow,
208 task: WorkflowTask,
209 activity: Readonly<Record<string, Activity>>,
210 live: (id: string | undefined, fallback?: Tokens) => Tokens,
211): Item {
212 const status: ItemStatus = task.status === 'running' ? 'running' : task.status === 'done' ? 'done' : 'failed'
213 const item: Item = {
214 key: `task:${flow.key}:${task.index}`,
215 kind: 'task',
216 title: task.label,
217 status,
218 progress: single(status),
219 tokens: live(task.agentId, task.tokens),
220 startedAt: task.startedAt,
221 children: [],
222 }
223 if (task.phase !== undefined) item.sub = task.phase
224 if (task.endedAt !== undefined) item.endedAt = task.endedAt
225 if (status === 'running') item.doing = doingOf(task.agentId === undefined ? undefined : activity[task.agentId]) ?? '생각 중'
226 return item
227}
228
229function teamItem(members: readonly AgentInfo[], tasks: readonly TaskItem[], activity: Readonly<Record<string, Activity>>): Item {
230 const names = (agent: AgentInfo) => [agent.name, agent.teammateId?.split('@')[0]].filter((n): n is string => n !== undefined)
231 const children = members.map((agent): Item => {
232 const one = activity[agent.id]
233 const status = statusOf(agent.status)
234 const owned = tasks.filter(t => t.owner !== undefined && names(agent).includes(t.owner))
235 const item: Item = {
236 key: `agent:${agent.id}`,
237 kind: 'teammate',
238 title: agent.name ?? agent.teammateId ?? typeLabel(agent.type),
239 sub: agent.description,
240 status,
241 progress: taskCount(owned) ?? todoCount(one?.todos) ?? single(status),
242 tokens: one?.tokens ?? ZERO_TOKENS,
243 children: [],
244 }
245 if (one !== undefined) item.startedAt = one.firstSeen
246 const end = one?.stoppedAt ?? one?.endedAt
247 if (isSettled(status) && end !== undefined) item.endedAt = end
248 const doing =
249 status === 'running'
250 ? (doingOf(one, owned.find(t => t.status === 'in_progress')) ?? '생각 중')
251 : status === 'idle'
252 ? '대기 중'
253 : undefined
254 if (doing !== undefined) item.doing = doing
255 return item
256 })
257 const status: ItemStatus = children.some(c => c.status === 'running')
258 ? 'running'
259 : children.some(c => c.status === 'idle')
260 ? 'idle'
261 : children.every(c => c.status === 'done')
262 ? 'done'
263 : 'failed'
264 const team = members.map(agent => agent.teammateId?.split('@')[1]).find((name): name is string => name !== undefined)
265 const starts = children.map(c => c.startedAt).filter((at): at is number => at !== undefined)
266 const ends = children.map(c => c.endedAt).filter((at): at is number => at !== undefined)
267 const item: Item = {
268 key: 'team',
269 kind: 'team',
270 title: team === undefined ? '에이전트 팀' : `에이전트 팀 ${team}`,
271 status,
272 progress: taskCount(tasks) ?? { done: children.filter(c => isSettled(c.status)).length, total: children.length },
273 tokens: sumTokens(children.map(c => c.tokens)),
274 children,
275 }
276 if (starts.length > 0) item.startedAt = Math.min(...starts)
277 if (isSettled(status) && ends.length > 0) item.endedAt = Math.max(...ends)
278 const busy = children.filter(c => c.status === 'running').length
279 item.doing = busy > 0 ? `${busy}명 작업 중` : '모두 대기 중'
280 return item
281}
282
283/**
284 * What a loop is doing: the task or todo it marked in progress, then the
285 * call it has in flight, both in plain words.
286 */
287export function doingOf(one: Activity | undefined, task?: TaskItem): string | undefined {
288 const todo = one?.todos?.find(t => t.status === 'in_progress')
289 const plan = task?.activeForm ?? task?.subject ?? todo?.activeForm ?? todo?.content
290 const call = one?.running.at(-1)?.doing
291 const parts = [plan, call].filter((part): part is string => part !== undefined && part !== '')
292 return parts.length === 0 ? undefined : parts.join(' · ')
293}
294
295export function todoCount(todos: readonly Todo[] | undefined): Count | undefined {
296 if (todos === undefined || todos.length === 0) return undefined
297 return { done: todos.filter(t => t.status === 'completed').length, total: todos.length }
298}
299
300export function taskCount(tasks: readonly TaskItem[]): Count | undefined {
301 if (tasks.length === 0) return undefined
302 return { done: tasks.filter(t => t.status === 'completed').length, total: tasks.length }
303}
304
305/** An agent with no list of its own is one task: 0/1 until it settles. */
306function single(status: ItemStatus): Count {
307 return { done: status === 'done' ? 1 : 0, total: 1 }
308}
309
310export function statusOf(status: AgentStatus): ItemStatus {
311 if (status === 'completed') return 'done'
312 if (status === 'failed' || status === 'killed') return 'failed'
313 return status === 'idle' ? 'idle' : 'running'
314}
315
316export function isSettled(status: ItemStatus): boolean {
317 return status === 'done' || status === 'failed'
318}
319
320export function isTeammate(agent: AgentInfo): boolean {
321 return agent.teammateId !== undefined || agent.type === 'teammate'
322}
323
324/** The tab key of the board itself. */
325export const ALL = 'all'
326const MAX_TABS = 6
327
328/** Opens (or retitles) a detail tab and shows it; the oldest of too many goes. */
329export function openTab(tabs: Tabs, tab: Tab): Tabs {
330 const isOpen = tabs.open.some(one => one.key === tab.key)
331 const open = isOpen ? tabs.open.map(one => (one.key === tab.key ? tab : one)) : [...tabs.open, tab].slice(-MAX_TABS)
332 return { open, active: tab.key }
333}
334
335/** Closes a tab; closing the one shown goes back to the board. */
336export function closeTab(tabs: Tabs, key: string): Tabs {
337 return { open: tabs.open.filter(one => one.key !== key), active: tabs.active === key ? ALL : tabs.active }
338}
339
340export function showTab(tabs: Tabs, key: string): Tabs {
341 return key === ALL || tabs.open.some(one => one.key === key) ? { ...tabs, active: key } : tabs
342}
343hooks/controls.ts 128 lines1import type { Settings } from 'claude-code'
2
3import type { Controls, EffortLevel, ModelFamily } from '../types'
4
5/** The band's model buttons, each set by its family's alias, which names the latest model. */
6export const MODELS: readonly { family: ModelFamily; label: string }[] = [
7 { family: 'fable', label: '페이블' },
8 { family: 'opus', label: '오푸스' },
9 { family: 'sonnet', label: '소넷' },
10 { family: 'haiku', label: '하이쿠' },
11]
12
13export const EFFORTS: readonly { level: EffortLevel; label: string }[] = [
14 { level: 'low', label: 'low' },
15 { level: 'medium', label: 'med' },
16 { level: 'high', label: 'high' },
17 { level: 'xhigh', label: 'xhigh' },
18 { level: 'max', label: 'max' },
19]
20
21const LEVELS = new Set<string>(EFFORTS.map(one => one.level))
22
23export const NO_CONTROLS: Controls = { ultracode: false }
24
25/**
26 * The band's chips: an idle one on the theme's gray, a group's pick on that group's own
27 * bright color in dark ink, so the model, the effort, workflows and ultracode tell apart at a glance.
28 */
29export const CHIP = {
30 idle: 'subtle',
31 ink: '#000000',
32 model: '#ffa36c',
33 effort: '#7cc4ff',
34 workflows: '#7ee0a1',
35 ultracode: '#c49bff',
36} as const
37
38export function isEffortLevel(value: unknown): value is EffortLevel {
39 return typeof value === 'string' && LEVELS.has(value)
40}
41
42/** A level, or `auto`, out of a settings value or an environment variable. */
43export function effortOf(value: unknown): EffortLevel | 'auto' | undefined {
44 const level = typeof value === 'string' ? value.trim().toLowerCase() : undefined
45 return level === 'auto' || isEffortLevel(level) ? level : undefined
46}
47
48/** A model id or alias without its context suffix: `claude-opus-5-5[1m]` is `claude-opus-5-5`. */
49function baseOf(model: string): string {
50 return model.trim().toLowerCase().replace(/\[[^\]]*\]$/, '')
51}
52
53/**
54 * The effort settings keep for a model, the one a session on it starts with: its own
55 * `modelSettings` entry (where `/effort` saves it, under the id or the family's alias),
56 * else the top-level `effortLevel`; undefined when neither names one (the model's default).
57 */
58export function savedEffort(settings: Settings, model: string | undefined): EffortLevel | 'auto' | undefined {
59 const table = settings['modelSettings']
60 const entries = typeof table === 'object' && table !== null && !Array.isArray(table) ? Object.entries(table) : []
61 const id = baseOf(model ?? '')
62 const family = familyOf(model)
63 let byFamily: EffortLevel | 'auto' | undefined
64 for (const [key, entry] of entries) {
65 const level = typeof entry === 'object' && entry !== null ? effortOf((entry as Record<string, unknown>)['effortLevel']) : undefined
66 if (level === undefined) continue
67 const name = baseOf(key)
68 if (name === id) return level
69 if (name === family) byFamily ??= level
70 }
71 return byFamily ?? effortOf(settings['effortLevel'])
72}
73
74/** The family a model id or alias belongs to: `claude-opus-5-5` and `opus[1m]` are `opus`. */
75export function familyOf(model: string | undefined): ModelFamily | undefined {
76 const name = (model ?? '').toLowerCase()
77 return MODELS.find(one => name.includes(one.family))?.family
78}
79
80/** A model id's version as people write it: `claude-fable-5-1` is `5.1`, `claude-opus-5` is `5`. */
81export function versionOf(model: string | undefined): string | undefined {
82 const match = /claude-[a-z]+-(\d{1,2})(?:-(\d{1,2}))?(?!\d)/.exec(model ?? '')
83 if (match === null) return undefined
84 return match[2] === undefined ? match[1] : `${match[1]}.${match[2]}`
85}
86
87/** A model as the band and its toasts name it: `오푸스 5.5`, or the id itself when it is no family's. */
88export function modelText(model: string | undefined): string {
89 const family = familyOf(model)
90 const label = MODELS.find(one => one.family === family)?.label
91 if (label === undefined) return model ?? '?'
92 const version = versionOf(model)
93 return version === undefined ? label : `${label} ${version}`
94}
95
96/**
97 * The effort a `/effort` answer left in force: `Set effort level to high`,
98 * the capped `set to 'xhigh' instead`, or `set to auto`; undefined otherwise.
99 */
100export function effortIn(text: string | undefined): EffortLevel | 'auto' | undefined {
101 const match = /(?:set|level) to '?(low|medium|high|xhigh|max|auto)\b/i.exec(text ?? '')
102 const level = match?.[1]?.toLowerCase()
103 return level === 'auto' || isEffortLevel(level) ? level : undefined
104}
105
106/** Whether a `/effort` answer turned ultracode on or off; undefined when it says neither. */
107export function ultracodeIn(text: string | undefined): boolean | undefined {
108 const match = /ultracode (on|off)\b/i.exec(text ?? '')
109 return match === null ? undefined : match[1]?.toLowerCase() === 'on'
110}
111
112/** Whether a command's answer reads as a refusal rather than a change made. */
113export function isRefusal(text: string | undefined): boolean {
114 return /invalid|isn't available|not available|needs|cannot|can't|couldn't|blocked|denied/i.test(text ?? '')
115}
116
117/** What a `/model` or `/effort` run left in force, folded into the controls. */
118export function afterCommand(controls: Controls, command: string, args: string, text: string | undefined): Controls {
119 if (command !== 'effort') return controls
120 const next = { ...controls }
121 const asked = args.trim().toLowerCase()
122 const effort = effortIn(text) ?? (text === undefined && (asked === 'auto' || isEffortLevel(asked)) ? asked : undefined)
123 if (effort !== undefined) next.effort = effort
124 const ultracode = ultracodeIn(text) ?? (text === undefined && /^ultracode (on|off)$/.test(asked) ? asked.endsWith('on') : undefined)
125 if (ultracode !== undefined && !(ultracode && isRefusal(text))) next.ultracode = ultracode
126 return next
127}
128hooks/format.ts 280 lines1import type { Color, ModelUsage } from 'claude-code'
2
3import type { Activity, LimitWindow, Tokens } from '../types'
4
5export const MAIN = 'main'
6
7const HOUR = 3_600_000
8const WINDOW_MS: Record<string, number> = { five_hour: 5 * HOUR, seven_day: 168 * HOUR }
9const WINDOW_LABEL: Record<string, string> = {
10 five_hour: '5시간',
11 seven_day: '주간',
12 spend_limit: '지출',
13}
14const MAX_SAMPLES = 600
15const SAME_RESET_MS = 5 * 60_000
16/** Remaining limit at or above this is drawn green; below it, ever redder. */
17const SAFE_REMAINING = 60
18/** A limit's bar, in cells: none where less room is left, never longer. */
19const MIN_BAR = 6
20const MAX_BAR = 24
21const DETAIL_KEYS = ['command', 'file_path', 'notebook_path', 'pattern', 'url', 'query', 'skill', 'description', 'prompt']
22
23export const ZERO_TOKENS: Tokens = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, requests: 0 }
24
25export function freshActivity(now: number): Activity {
26 return { running: [], tools: 0, tokens: ZERO_TOKENS, firstSeen: now, isBusy: false }
27}
28
29export function addUsage(tokens: Tokens, usage: ModelUsage): Tokens {
30 return {
31 input: tokens.input + usage.input_tokens,
32 output: tokens.output + usage.output_tokens,
33 cacheRead: tokens.cacheRead + usage.cache_read_input_tokens,
34 cacheWrite: tokens.cacheWrite + usage.cache_creation_input_tokens,
35 requests: tokens.requests + 1,
36 }
37}
38
39export function sumTokens(list: readonly Tokens[]): Tokens {
40 return list.reduce(
41 (sum, t) => ({
42 input: sum.input + t.input,
43 output: sum.output + t.output,
44 cacheRead: sum.cacheRead + t.cacheRead,
45 cacheWrite: sum.cacheWrite + t.cacheWrite,
46 requests: sum.requests + t.requests,
47 }),
48 ZERO_TOKENS,
49 )
50}
51
52/** Every input token the model read: uncached, cache-written and cache-read. */
53export function inputTotal(t: Tokens): number {
54 return t.input + t.cacheRead + t.cacheWrite
55}
56
57export function tokenText(t: Tokens): string {
58 return t.requests === 0 ? '' : `↑${compact(inputTotal(t))} ↓${compact(t.output)}`
59}
60
61export function compact(n: number): string {
62 const scaled = (x: number) => (x >= 100 ? String(Math.round(x)) : x.toFixed(1).replace(/\.0$/, ''))
63 if (n < 1000) return String(n)
64 if (n < 1e6) return `${scaled(n / 1e3)}k`
65 if (n < 1e9) return `${scaled(n / 1e6)}M`
66 return `${scaled(n / 1e9)}B`
67}
68
69export function duration(ms: number): string {
70 const s = Math.max(0, Math.floor(ms / 1000))
71 const d = Math.floor(s / 86_400)
72 const h = Math.floor((s % 86_400) / 3600)
73 const m = Math.floor((s % 3600) / 60)
74 if (d > 0) return `${d}d${h}h`
75 if (h > 0) return `${h}h${String(m).padStart(2, '0')}m`
76 if (m > 0) return `${m}m${String(s % 60).padStart(2, '0')}s`
77 return `${s}s`
78}
79
80export function toolLabel(tool: string): string {
81 const mcp = /^mcp__(.+?)__(.+)$/.exec(tool)
82 return mcp ? `${mcp[1]}·${mcp[2]}` : tool
83}
84
85/** One line naming a tool call: the tool and its most telling argument, paths cut to their last part. */
86export function describeCall(tool: string, input: Readonly<Record<string, unknown>>): string {
87 for (const key of DETAIL_KEYS) {
88 const value = input[key]
89 if (typeof value !== 'string' || value.trim() === '') continue
90 const detail = key.endsWith('path') ? lastPart(value) : shortPaths(value.trim().split('\n')[0] ?? '')
91 return `${toolLabel(tool)} ${detail}`.slice(0, 200)
92 }
93 return toolLabel(tool)
94}
95
96/** A path as its last part: `/repo/src/game.ts` is `game.ts`. */
97export function lastPart(path: string): string {
98 const trimmed = path.replace(/\/+$/, '')
99 return trimmed.slice(trimmed.lastIndexOf('/') + 1) || path
100}
101
102/**
103 * A line with each absolute or home path in it cut to its last part; a URL,
104 * a path built on a variable and `/dev/...` are left whole.
105 */
106export function shortPaths(text: string): string {
107 return text.replace(/(?<![\w.:/~$})-])~?\/(?!dev\/)[^\s'"`;|&()<>]+/g, lastPart)
108}
109
110const EDITS = new Set(['Edit', 'MultiEdit', 'NotebookEdit'])
111const PLANS = new Set(['TodoWrite', 'TaskCreate', 'TaskUpdate', 'TaskList', 'TaskGet'])
112
113/**
114 * What a loop is doing, in plain words for the board: no tool names or
115 * paths, a file named by its last part; a Bash call by its own description.
116 */
117export function activityOf(tool: string, input: Readonly<Record<string, unknown>>): string {
118 const text = (key: string) => (typeof input[key] === 'string' ? (input[key] as string).trim() : '')
119 const file = lastPart(text('file_path') || text('notebook_path'))
120 if (tool === 'Bash' || tool === 'PowerShell') return firstLine(text('description')) || '명령 실행 중'
121 if (tool === 'Read') return file === '' ? '파일 읽는 중' : `${file} 읽는 중`
122 if (EDITS.has(tool)) return file === '' ? '파일 수정 중' : `${file} 수정 중`
123 if (tool === 'Write') return file === '' ? '파일 작성 중' : `${file} 작성 중`
124 if (tool === 'Grep' || tool === 'Glob' || tool === 'LSP') return '코드 찾는 중'
125 if (tool === 'WebSearch') return '웹 검색 중'
126 if (tool === 'WebFetch') return '웹 페이지 읽는 중'
127 if (PLANS.has(tool)) return '작업 목록 정리 중'
128 if (tool === 'Skill') return '스킬 불러오는 중'
129 if (tool === 'ToolSearch') return '도구 준비 중'
130 if (tool === 'SendMessage') return '메시지 보내는 중'
131 if (tool === 'AskUserQuestion') return '질문에 답 기다리는 중'
132 if (tool === 'Artifact') return '페이지 게시 중'
133 const mcp = /^mcp__(.+?)__/.exec(tool)
134 return mcp === null ? '작업 중' : `${mcp[1]} 작업 중`
135}
136
137function firstLine(text: string): string {
138 return shortPaths(text.split('\n')[0] ?? '').slice(0, 120)
139}
140
141/**
142 * A request or an agent's instructions in one line: its first sentence (or
143 * line), a leading `[tag]` left off, paths cut to their last part (a relative
144 * one too when it names a file, `src/a/b.ts` being `b.ts`), at most `width` cells.
145 */
146export function brief(text: string, width = 120): string {
147 const body = text.replace(/^\s*\[[^\]\n]{1,80}\]\s*/, '')
148 const line = (body.split('\n').find(one => one.trim() !== '') ?? '').trim().replace(/\s+/g, ' ')
149 const sentence = /^.+?[.!?。!?](?=\s|$)/.exec(line)?.[0] ?? line
150 const short = shortPaths(sentence.length >= 12 ? sentence : line).replace(
151 /(?<![\w./~$-])(?:[\w.-]+\/)+([\w-]+\.[A-Za-z]\w{0,7})(?![\w/])/g,
152 '$1',
153 )
154 return fit(short, width)
155}
156
157/** `text` cut to `width` terminal cells, an ellipsis marking the cut. */
158export function fit(text: string, width: number): string {
159 if (cells(text) <= width) return text
160 let out = ''
161 for (const char of text) {
162 if (cells(out + char) > width - 1) break
163 out += char
164 }
165 return `${out}…`
166}
167
168/** A short hash of a text (djb2), to know a script again without keeping it. */
169export function hashOf(text: string): number {
170 let hash = 5381
171 for (let i = 0; i < text.length; i += 1) hash = ((hash << 5) + hash + text.charCodeAt(i)) | 0
172 return hash >>> 0
173}
174
175export function windowLabel(kind: string): string {
176 return WINDOW_LABEL[kind] ?? kind
177}
178
179export function windowSpan(window: LimitWindow, now: number): { start: number; end: number } | undefined {
180 const span = WINDOW_MS[window.kind]
181 const end = window.resetsAt === undefined ? NaN : Date.parse(window.resetsAt)
182 if (span === undefined || Number.isNaN(end)) return undefined
183 return { start: end - span, end: Math.max(end, now) }
184}
185
186/**
187 * Folds a fresh reading into a window's history: samples from before the
188 * window began (an earlier window) are dropped, and a sample is added only
189 * when the percentage moved, since usage carries forward until it does.
190 */
191export function recordLimit(
192 prev: LimitWindow | undefined,
193 reading: { kind: string; percentUsed: number; resetsAt?: string },
194 now: number,
195): LimitWindow {
196 const next: LimitWindow = { kind: reading.kind, percentUsed: reading.percentUsed, samples: [] }
197 if (reading.resetsAt !== undefined) next.resetsAt = reading.resetsAt
198 const span = windowSpan(next, now)
199 const history = isSameWindow(prev?.resetsAt, reading.resetsAt) ? (prev?.samples ?? []) : []
200 const kept = history.filter(s => s.at <= now && (span === undefined || s.at >= span.start))
201 const last = kept[kept.length - 1]
202 next.samples = last?.percent === reading.percentUsed ? kept : [...kept, { at: now, percent: reading.percentUsed }]
203 next.samples = next.samples.slice(-MAX_SAMPLES)
204 return next
205}
206
207/** Two readings of one window name the same reset, give or take a drift. */
208function isSameWindow(a: string | undefined, b: string | undefined): boolean {
209 if (a === undefined || b === undefined) return a === b
210 return Math.abs(Date.parse(a) - Date.parse(b)) < SAME_RESET_MS
211}
212
213/** A window that has reset since it was read says nothing about now. */
214export function isCurrent(window: LimitWindow, now: number): boolean {
215 const end = window.resetsAt === undefined ? NaN : Date.parse(window.resetsAt)
216 return Number.isNaN(end) || end > now
217}
218
219export function gauge(percent: number, width: number): { filled: string; empty: string } {
220 const cells = Math.max(1, width)
221 const filled = Math.min(cells, Math.round((Math.max(0, percent) / 100) * cells))
222 return { filled: '█'.repeat(filled), empty: '░'.repeat(cells - filled) }
223}
224
225/** Terminal cells a text takes: Hangul and other wide letters take two. */
226export function cells(text: string): number {
227 let count = 0
228 for (const char of text) {
229 const code = char.codePointAt(0) ?? 0
230 const isWide =
231 (code >= 0x1100 && code <= 0x115f) ||
232 (code >= 0x2e80 && code <= 0xa4cf) ||
233 (code >= 0xac00 && code <= 0xd7a3) ||
234 (code >= 0xf900 && code <= 0xfaff) ||
235 (code >= 0xff00 && code <= 0xff60)
236 count += isWide ? 2 : 1
237 }
238 return count
239}
240
241/** What is left of a window, in whole percent. */
242export function remaining(window: LimitWindow): number {
243 return Math.max(0, Math.min(100, Math.round(100 - window.percentUsed)))
244}
245
246/**
247 * How the band paints what is left: green with room to spare, then from
248 * amber through orange to a deep red as the remainder runs out.
249 */
250export function remainingColor(left: number): Color {
251 const r = Math.max(0, Math.min(100, left))
252 if (r >= SAFE_REMAINING) return 'success'
253 const t = r / SAFE_REMAINING
254 return hsl(40 * t, 85, 45 + 12 * t)
255}
256
257/** A limit window as the band draws it: the share used as a filled bar, then what is left. */
258export type LimitBar = { label: string; used: string; free: string; left: number; color: Color }
259
260/** Fits a window into `room` cells: the bar takes what its label and `잔여 N%` leave, or nothing. */
261export function limitBar(window: LimitWindow, room: number): LimitBar {
262 const left = remaining(window)
263 const label = windowLabel(window.kind)
264 const width = Math.min(MAX_BAR, room - cells(label) - cells(`잔여 ${left}%`) - 2)
265 const bar = width >= MIN_BAR ? gauge(100 - left, width) : { filled: '', empty: '' }
266 return { label, used: bar.filled, free: bar.empty, left, color: remainingColor(left) }
267}
268
269function hsl(hue: number, saturation: number, lightness: number): string {
270 const s = saturation / 100
271 const l = lightness / 100
272 const k = (n: number) => (n + hue / 30) % 12
273 const a = s * Math.min(l, 1 - l)
274 const channel = (n: number) => {
275 const value = l - a * Math.max(-1, Math.min(k(n) - 3, 9 - k(n), 1))
276 return Math.round(value * 255).toString(16).padStart(2, '0')
277 }
278 return `#${channel(0)}${channel(8)}${channel(4)}`
279}
280hooks/sessions.ts 203 lines1import type { Peer } from '../types'
2import { cells } from './format'
3
4/** This session's own color: its row, its `[작업 세션]` tag and the folder that holds it (`[작업폴더]`). */
5export const MINE = '#5fd7ff'
6
7/** A registry status in words and the color of its dot. */
8export type PeerLook = { word: string; color: string }
9
10const LOOKS: Record<string, PeerLook> = {
11 busy: { word: '작업 중', color: 'success' },
12 shell: { word: '명령 실행 중', color: 'success' },
13 idle: { word: '대기 중', color: 'inactive' },
14 waiting: { word: '응답 기다림', color: 'warning' },
15}
16
17/** The registry's words for a session that waits rather than works. */
18const RESTING = new Set(['idle', 'waiting'])
19
20/**
21 * Whether a session is at work: the registry says `busy`, or another word for work such as
22 * `shell` (a command it runs), and it waits on nobody. Only `idle` and waiting are rest.
23 */
24export function isWorking(peer: Pick<Peer, 'status' | 'waitingFor'>): boolean {
25 return peer.status !== undefined && !RESTING.has(peer.status) && peer.waitingFor === undefined
26}
27
28/** One folder of the all-sessions view and the sessions running in it. */
29export type Folder = { path: string; sessions: Peer[]; hasMine: boolean; busy: number; lastAt: number }
30
31function text(value: unknown): string | undefined {
32 return typeof value === 'string' && value !== '' ? value : undefined
33}
34
35function number(value: unknown): number | undefined {
36 return typeof value === 'number' && Number.isFinite(value) ? value : undefined
37}
38
39/** A folder as the registry and the session answer it, without a trailing separator. */
40export function folderKey(path: string): string {
41 const trimmed = path.replace(/[\\/]+$/, '')
42 return trimmed === '' ? path : trimmed
43}
44
45/**
46 * One file of the engine's session registry (`<config>/sessions/<pid>.json`), which every
47 * running Claude Code process on this machine keeps; undefined when it is not one.
48 */
49export function peerOf(source: string): Peer | undefined {
50 let raw: unknown
51 try {
52 raw = JSON.parse(source)
53 } catch {
54 return undefined
55 }
56 if (typeof raw !== 'object' || raw === null) return undefined
57 const row = raw as Record<string, unknown>
58 const pid = number(row['pid'])
59 const sessionId = text(row['sessionId'])
60 const cwd = text(row['cwd'])
61 if (pid === undefined || sessionId === undefined || cwd === undefined) return undefined
62 const peer: Peer = { pid, sessionId, cwd: folderKey(cwd) }
63 const name = text(row['name'])
64 const status = text(row['status'])
65 const waitingFor = text(row['waitingFor'])
66 const kind = text(row['kind'])
67 const entrypoint = text(row['entrypoint'])
68 const version = text(row['version'])
69 const startedAt = number(row['startedAt'])
70 const statusAt = number(row['statusUpdatedAt']) ?? number(row['updatedAt'])
71 if (name !== undefined) peer.name = name
72 if (status !== undefined) peer.status = status
73 if (waitingFor !== undefined) peer.waitingFor = waitingFor
74 if (kind !== undefined) peer.kind = kind
75 if (entrypoint !== undefined) peer.entrypoint = entrypoint
76 if (version !== undefined) peer.version = version
77 if (startedAt !== undefined) peer.startedAt = startedAt
78 if (statusAt !== undefined) peer.statusAt = statusAt
79 return peer
80}
81
82/** The process ids `ps -o pid=,comm= -p ...` still lists: the registry's files outlive a crash. */
83export function alivePids(listing: string): Set<number> {
84 const alive = new Set<number>()
85 for (const line of listing.split('\n')) {
86 const pid = Number(/^\s*(\d+)/.exec(line)?.[1])
87 if (Number.isInteger(pid) && pid > 0) alive.add(pid)
88 }
89 return alive
90}
91
92export function lookOf(peer: Pick<Peer, 'status' | 'waitingFor'>): PeerLook {
93 if (peer.waitingFor !== undefined) return LOOKS['waiting'] as PeerLook
94 const known = peer.status === undefined ? undefined : LOOKS[peer.status]
95 if (known !== undefined) return known
96 if (peer.status === undefined) return { word: '상태 모름', color: 'inactive' }
97 // A word for work this mod has no Korean for yet: still at work, the word kept.
98 return { word: `작업 중 · ${peer.status}`, color: 'success' }
99}
100
101/** How a session is called on the board: the registry's name, else its folder's last part. */
102export function peerName(peer: Pick<Peer, 'name' | 'cwd' | 'sessionId'>): string {
103 return peer.name ?? `${baseName(peer.cwd)} · ${peer.sessionId.slice(0, 8)}`
104}
105
106export function baseName(path: string): string {
107 return path.split(/[\\/]/).filter(Boolean).at(-1) ?? path
108}
109
110/** A folder with the home folder as `~`. */
111export function homeShort(path: string, home: string | undefined): string {
112 if (home === undefined || home === '') return path
113 const base = folderKey(home)
114 return path === base ? '~' : path.startsWith(`${base}/`) ? `~${path.slice(base.length)}` : path
115}
116
117/** A path cut to `width` cells from its start, keeping the end that names it. */
118export function fitPath(path: string, width: number): string {
119 if (cells(path) <= width) return path
120 const chars = [...path]
121 let out = ''
122 for (let i = chars.length - 1; i >= 0; i--) {
123 if (cells(`…${chars[i]}${out}`) > width) break
124 out = `${chars[i]}${out}`
125 }
126 return `…${out}`
127}
128
129function lastOf(peer: Peer): number {
130 return peer.statusAt ?? peer.startedAt ?? 0
131}
132
133/**
134 * This session first, then the busy ones, then the latest to change, then by process id, so
135 * that rows keep their order while nothing about them changes. `minePid` is this session's process.
136 */
137export function rank(list: readonly Peer[], minePid: number | undefined): Peer[] {
138 const busy = (peer: Peer) => (isWorking(peer) ? 0 : 1)
139 return [...list].sort(
140 (a, b) =>
141 Number(b.pid === minePid) - Number(a.pid === minePid) || busy(a) - busy(b) || lastOf(b) - lastOf(a) || a.pid - b.pid,
142 )
143}
144
145/**
146 * Which row is this session's: its own process when that is known and listed, else the one row
147 * that carries its id in its folder, else the one row that carries its id. Never a guess between
148 * two processes that share the id.
149 */
150export function ownRow(list: readonly Peer[], sessionId: string, cwd: string, pid: number | undefined): Peer | undefined {
151 const byPid = pid === undefined ? undefined : list.find(peer => peer.pid === pid)
152 if (byPid !== undefined) return byPid
153 const here = list.filter(peer => peer.sessionId === sessionId && peer.cwd === cwd)
154 if (here.length === 1) return here[0]
155 const anywhere = list.filter(peer => peer.sessionId === sessionId)
156 return anywhere.length === 1 ? anywhere[0] : undefined
157}
158
159/** The sessions by the folder they run in: this session's folder first, then the busiest and latest. */
160export function foldersOf(list: readonly Peer[], minePid: number | undefined): Folder[] {
161 const byPath = new Map<string, Peer[]>()
162 for (const peer of list) byPath.set(peer.cwd, [...(byPath.get(peer.cwd) ?? []), peer])
163 const folders = [...byPath].map(([path, sessions]): Folder => ({
164 path,
165 sessions: rank(sessions, minePid),
166 hasMine: sessions.some(peer => peer.pid === minePid),
167 busy: sessions.filter(isWorking).length,
168 lastAt: Math.max(...sessions.map(lastOf)),
169 }))
170 return folders.sort(
171 (a, b) => Number(b.hasMine) - Number(a.hasMine) || b.busy - a.busy || b.lastAt - a.lastAt || a.path.localeCompare(b.path),
172 )
173}
174
175/**
176 * The session a `/dash-send` names: its registry name, its process id, or its session id (whole
177 * or its start); an id two processes share names neither.
178 */
179export function findPeer(list: readonly Peer[], name: string): Peer | undefined {
180 const wanted = name.trim().toLowerCase()
181 if (wanted === '') return undefined
182 const only = (found: Peer[]) => (found.length === 1 ? found[0] : undefined)
183 return (
184 only(list.filter(peer => peer.name?.toLowerCase() === wanted)) ??
185 (/^\d+$/.test(wanted) ? list.find(peer => peer.pid === Number(wanted)) : undefined) ??
186 only(list.filter(peer => peer.sessionId.toLowerCase() === wanted)) ??
187 (wanted.length >= 6 ? only(list.filter(peer => peer.sessionId.toLowerCase().startsWith(wanted))) : undefined)
188 )
189}
190
191/** How `$.session.send` reaches a session: its registry name, which is its own, else its id. */
192export function addressOf(peer: Peer): string | { sessionId: string } {
193 return peer.name !== undefined && !/\s/.test(peer.name) ? peer.name : { sessionId: peer.sessionId }
194}
195
196/** `/dash-send <session> <message>`: the session named first, the message after it. */
197export function sendArgs(args: string): { to: string; text: string } | undefined {
198 const match = /^\s*(\S+)\s+([\s\S]*\S)\s*$/.exec(args)
199 return match === null ? undefined : { to: match[1] as string, text: match[2] as string }
200}
201
202export const KINDS: Record<string, string> = { interactive: '대화형', bg: '백그라운드', background: '백그라운드', sdk: 'SDK' }
203hooks/view.tsx 819 lines1import type { AgentInfo, EngineInterface, RenderChildren } from 'claude-code'
2
3import type { Activity, Fault, Peer, Peers, Scope, Tabs, TaskItem, Tokens, Workflow } from '../types'
4import type { Board, Count, Item, ItemStatus } from './board'
5import { ALL, doingOf, isSettled, statusOf, taskCount, taskItem, todoCount, typeLabel } from './board'
6import { CHIP } from './controls'
7import { MAIN, ZERO_TOKENS, brief, cells, compact, duration, fit, gauge, inputTotal, tokenText } from './format'
8import { KINDS, MINE, fitPath, foldersOf, homeShort, lookOf, peerName, rank } from './sessions'
9import { finishedAt, progress, standing } from './workflow'
10
11/** The surface's element table, as `$.ui.resolve(e)` hands it out. */
12export type Kit = ReturnType<EngineInterface['ui']['resolve']>
13
14/** What a drawing reads, and what its presses do. */
15export type Scene = {
16 kit: Kit
17 now: number
18 width: number
19 board: Board
20 tabs: Tabs
21 agents: readonly AgentInfo[]
22 activity: Readonly<Record<string, Activity>>
23 flows: readonly Workflow[]
24 tasks: Readonly<Record<string, TaskItem>>
25 faults: readonly Fault[]
26 totals: string
27 /** Every Claude Code session on this machine, and which list of them the pane shows. */
28 peers: Peers
29 scope: Scope
30 open: (key: string, title: string) => void
31 close: (key: string) => void
32 show: (key: string) => void
33 /** Up to every session, or down to a folder's (this session's when none is named). */
34 goAll: () => void
35 goFolder: (path?: string) => void
36 /** A press on a session: this one opens its own tab, another its session tab. */
37 openPeer: (peer: Peer) => void
38 message: (peer: Peer) => void
39 end: (peer: Peer) => void
40}
41
42/** This session's folder and this session itself, as the lists tag them. */
43const FOLDER_TAG = '[작업폴더]'
44const MINE_TAG = '[작업 세션]'
45/** The message chip on a session's row. */
46const ROW_MESSAGE = '메시지'
47
48const RECENT_ROWS = 6
49const REPLY_ROWS = 4
50const SUMMARY_LABEL = 8
51const SUMMARY_NAMES = 2
52const FAULT_MS = 10 * 60_000
53const LABEL = 6
54const TAB_TITLE = 14
55const BAR = 10
56
57const LOOK: Record<ItemStatus, { box: string; color: string }> = {
58 running: { box: '☐', color: 'claude' },
59 idle: { box: '☐', color: 'inactive' },
60 done: { box: '☑', color: 'success' },
61 failed: { box: '☒', color: 'error' },
62}
63
64const WORD: Record<ItemStatus, string> = { running: '실행 중', idle: '대기 중', done: '완료', failed: '실패·중단' }
65
66/** A settled item's own color: green once done, red once failed; none while it runs. */
67function inkOf(status: ItemStatus): { color?: string } {
68 return status === 'done' ? { color: 'success' } : status === 'failed' ? { color: 'error' } : {}
69}
70
71export function countText(count: Count | undefined): string {
72 return count === undefined ? '' : ` (${count.done}/${count.total}${count.isOpen === true ? '+' : ''})`
73}
74
75/** The tokens an item spent and how long it ran: what sits right of its title. */
76export function costText(item: Pick<Item, 'tokens' | 'startedAt' | 'endedAt' | 'kind'>, now: number): string {
77 const ran = item.kind === 'main' || item.startedAt === undefined ? '' : duration((item.endedAt ?? now) - item.startedAt)
78 return [tokenText(item.tokens), ran].filter(Boolean).join(' · ')
79}
80
81/** The pane: the tab bar, then the board or the tab it shows. */
82export function drawPane(scene: Scene) {
83 const { Box } = scene.kit
84 const shown = scene.tabs.open.find(tab => tab.key === scene.tabs.active)
85 return (
86 <Box flexDirection="column">
87 {drawTabBar(scene)}
88 {shown === undefined ? drawList(scene) : drawDetail(scene, shown.key)}
89 </Box>
90 )
91}
92
93/** Whether the list shows this session's folder, where its board is, rather than every session or another folder. */
94function isHomeList(scene: Scene): boolean {
95 return scene.scope.level === 'folder' && (scene.scope.folder === undefined || scene.scope.folder === scene.peers.folder)
96}
97
98/**
99 * The tabs on top: every session and this session's own view, always there, then the detail tabs
100 * opened from them. Another folder's sessions count as the every-session view they were reached from.
101 */
102function drawTabBar(scene: Scene) {
103 const { Box, Text, Button } = scene.kit
104 const isList = scene.tabs.active === ALL || !scene.tabs.open.some(tab => tab.key === scene.tabs.active)
105 const isHome = isHomeList(scene)
106 const top = (key: string, word: string, isActive: boolean, onPress: () => void) => (
107 <Button key={key} label={word} {...(isActive && { variant: 'primary' as const })} onPress={onPress}>
108 {word}
109 </Button>
110 )
111 return (
112 <Box flexDirection="row" flexWrap="wrap" marginBottom={1}>
113 {top('top:all', '모든 세션', isList && !isHome, () => scene.goAll())}
114 <Text> </Text>
115 {top('top:mine', '현재 세션', isList && isHome, () => scene.goFolder())}
116 {scene.tabs.open.length > 0 && <Text dimColor> │</Text>}
117 {scene.tabs.open.map(tab => (
118 <Box flexDirection="row">
119 <Text> </Text>
120 <Button
121 key={`tab:${tab.key}`}
122 label={fit(tab.title, TAB_TITLE)}
123 {...(scene.tabs.active === tab.key && { variant: 'primary' as const })}
124 onPress={() => scene.show(tab.key)}
125 >
126 {fit(tab.title, TAB_TITLE)}
127 </Button>
128 <Button key={`close:${tab.key}`} plain label="×" onPress={() => scene.close(tab.key)}>
129 ×
130 </Button>
131 </Box>
132 ))}
133 </Box>
134 )
135}
136
137/**
138 * The list the pane opens on: the sessions of a folder (this session's by default) with this
139 * session's own board under them, or one level up, every session on the machine by folder.
140 */
141function drawList(scene: Scene) {
142 return scene.scope.level === 'all' ? drawAll(scene) : drawFolder(scene)
143}
144
145/** The sessions running in this machine's folders, this session's folder first. */
146function drawAll(scene: Scene) {
147 const { Box, Text, Button } = scene.kit
148 const { list, minePid, homeDir } = scene.peers
149 const folders = foldersOf(list, minePid)
150 return (
151 <Box flexDirection="column">
152 <Text dimColor>{`폴더 ${folders.length}개 · 세션 ${list.length}개`}</Text>
153 {folders.map(folder => {
154 const count = ` · ${folder.sessions.length}개${folder.busy > 0 ? ` (${folder.busy}개 작업 중)` : ''}`
155 const tag = folder.hasMine ? ` ${FOLDER_TAG}` : ''
156 const room = Math.max(8, scene.width - 2 - cells(count) - cells(tag))
157 return (
158 <Box flexDirection="column" marginTop={1}>
159 <Button key={`folder:${folder.path}`} plain label={folder.path} onPress={() => scene.goFolder(folder.path)}>
160 <Text weight="bold" {...(folder.hasMine && { color: MINE })}>
161 {`▸ ${fitPath(homeShort(folder.path, homeDir), room)}`}
162 </Text>
163 <Text dimColor>{count}</Text>
164 {folder.hasMine && (
165 <Text color={MINE} weight="bold">
166 {tag}
167 </Text>
168 )}
169 </Button>
170 {folder.sessions.map(peer => peerRow(scene, peer, 1))}
171 </Box>
172 )
173 })}
174 {folders.length === 0 && <Text dimColor> 실행 중인 세션을 찾지 못했습니다.</Text>}
175 {scene.peers.error !== undefined && (
176 <Text color="warning" wrap="truncate-end">
177 {`⚠ 세션 목록: ${scene.peers.error}`}
178 </Text>
179 )}
180 </Box>
181 )
182}
183
184/**
185 * A folder's sessions; in this session's folder, this session's board under them, and in another
186 * folder a way back up to every session.
187 */
188function drawFolder(scene: Scene) {
189 const { Box, Text, Button } = scene.kit
190 const { list, minePid, homeDir } = scene.peers
191 const folder = scene.scope.folder ?? scene.peers.folder
192 const isHome = isHomeList(scene)
193 const sessions = rank(
194 list.filter(peer => peer.cwd === folder),
195 minePid,
196 )
197 const count = ` · 세션 ${sessions.length}개`
198 return (
199 <Box flexDirection="column">
200 <Box flexDirection="row">
201 {!isHome && (
202 <Box flexShrink={0} marginRight={1}>
203 <Button key="scope:all" plain label="← 모든 세션" onPress={() => scene.goAll()}>
204 <Text backgroundColor={CHIP.idle} color="text">
205 {' ← 모든 세션 '}
206 </Text>
207 </Button>
208 </Box>
209 )}
210 <Box flexGrow={1} flexShrink={1}>
211 <Text wrap="truncate-end">
212 <Text weight="bold" {...(isHome && { color: MINE })}>
213 {fitPath(homeShort(folder ?? '', homeDir), Math.max(8, scene.width - (isHome ? 0 : 16) - cells(count)))}
214 </Text>
215 <Text dimColor>{count}</Text>
216 </Text>
217 </Box>
218 </Box>
219 {sessions.map(peer => peerRow(scene, peer, 0))}
220 {sessions.length === 0 && <Text dimColor> 이 폴더에서 실행 중인 세션이 없습니다.</Text>}
221 {isHome && <Box marginTop={1}>{drawBoard(scene)}</Box>}
222 </Box>
223 )
224}
225
226/**
227 * One session: its status dot and name (this one in its own color, tagged), how long it has stood
228 * so, and for another session a message and an end right on its row (the end asks twice).
229 */
230function peerRow(scene: Scene, peer: Peer, depth: number): RenderChildren {
231 const { Box, Text, Button } = scene.kit
232 const isMine = peer.pid === scene.peers.minePid
233 const look = lookOf(peer)
234 const pad = ' '.repeat(depth)
235 const since = peer.statusAt === undefined ? '' : ` · ${duration(scene.now - peer.statusAt)}`
236 const right = ` ${look.word}${since}`
237 const tag = isMine ? ` ${MINE_TAG}` : ''
238 const name = peerName(peer)
239 const isEnding = scene.scope.ending === peer.pid
240 const endWord = isEnding ? ' 한 번 더 ' : ' 종료 '
241 const actions = isMine ? 0 : cells(` ${ROW_MESSAGE} `) + cells(endWord) + 2
242 const room = Math.max(6, scene.width - cells(pad) - 2 - cells(tag) - cells(right) - actions)
243 return (
244 <Box flexDirection="row">
245 <Box flexGrow={1} flexShrink={1} flexDirection="row">
246 {pad !== '' && <Text>{pad}</Text>}
247 <Button key={`peer:${peer.pid}`} plain label={name} onPress={() => scene.openPeer(peer)}>
248 <Text color={look.color}>●</Text>{' '}
249 <Text {...(isMine && { color: MINE, weight: 'bold' as const })}>{fit(name, room)}</Text>
250 {isMine && (
251 <Text color={MINE} weight="bold">
252 {tag}
253 </Text>
254 )}
255 </Button>
256 </Box>
257 <Box flexShrink={0}>
258 <Text {...(isMine ? { color: MINE } : { dimColor: true })}>{right}</Text>
259 </Box>
260 {!isMine && (
261 <Box flexShrink={0} flexDirection="row" columnGap={1} marginLeft={1}>
262 <Button key={`row-message:${peer.pid}`} plain label={`${peerName(peer)}에 메시지`} onPress={() => scene.message(peer)}>
263 <Text backgroundColor={CHIP.idle} color="text">
264 {` ${ROW_MESSAGE} `}
265 </Text>
266 </Button>
267 <Button
268 key={`row-end:${peer.pid}`}
269 plain
270 label={isEnding ? `${peerName(peer)} 한 번 더 누르면 종료` : `${peerName(peer)} 종료`}
271 onPress={() => scene.end(peer)}
272 >
273 <Text
274 {...(isEnding
275 ? { backgroundColor: 'error', color: CHIP.ink, weight: 'bold' as const }
276 : { backgroundColor: CHIP.idle, color: 'text' })}
277 >
278 {endWord}
279 </Text>
280 </Button>
281 </Box>
282 )}
283 </Box>
284 )
285}
286
287/** The board: every loop of the session on one row each, running ones first. */
288function drawBoard(scene: Scene) {
289 const { Box, Text } = scene.kit
290 const { board } = scene
291 const busy = board.running.filter(item => item.status === 'running').length
292 const fault = scene.faults.at(-1)
293 return (
294 <Box flexDirection="column">
295 <Box flexDirection="row" justifyContent="space-between">
296 <Text weight="bold" color="claude">
297 이 세션의 작업{busy > 0 ? ` · ${busy}개 실행 중` : ''}
298 </Text>
299 <Text dimColor>↑입력 ↓출력 · 시간</Text>
300 </Box>
301 {itemRow(scene, board.main, 0)}
302 {board.running.map(item => itemRow(scene, item, 0))}
303 {board.running.length === 0 && <Text dimColor> 실행 중인 서브 작업 없음</Text>}
304 {board.finished.length > 0 && (
305 <Box marginTop={1}>
306 <Text dimColor>완료</Text>
307 </Box>
308 )}
309 {board.finished.map(item => itemRow(scene, item, 0))}
310 {board.hidden > 0 && <Text dimColor>{` +${board.hidden}개 더 완료`}</Text>}
311 <Box marginTop={1}>
312 <Text dimColor wrap="truncate-end">
313 {scene.totals}
314 </Text>
315 </Box>
316 {fault !== undefined && scene.now - fault.at < FAULT_MS && (
317 <Text color="warning" wrap="truncate-end">
318 {`⚠ ${fault.where}: ${fault.message}`}
319 </Text>
320 )}
321 </Box>
322 )
323}
324
325/**
326 * One item: a checkbox that ticks once it is done, its title (a press opens
327 * its tab), its progress, and on the right its tokens and time; under a
328 * running one what it is doing, then its children.
329 */
330function itemRow(scene: Scene, item: Item, depth: number): RenderChildren {
331 const { Box, Text, Button } = scene.kit
332 const pad = ' '.repeat(depth)
333 const look = LOOK[item.status]
334 const ink = inkOf(item.status)
335 const right = costText(item, scene.now)
336 const count = countText(item.progress)
337 const name = item.sub !== undefined && item.sub !== '' && item.sub !== item.title ? `${item.title} · ${item.sub}` : item.title
338 const room = Math.max(6, scene.width - cells(pad) - 2 - cells(count) - (right === '' ? 0 : cells(right) + 1))
339 return (
340 <Box flexDirection="column">
341 <Box flexDirection="row">
342 <Box flexGrow={1} flexShrink={1} flexDirection="row">
343 {pad !== '' && <Text>{pad}</Text>}
344 <Button
345 key={`open:${item.key}`}
346 plain
347 label={item.title}
348 onPress={() => scene.open(item.key, item.tab ?? item.title)}
349 >
350 <Text color={look.color}>{look.box}</Text>{' '}
351 <Text {...ink} {...(depth === 0 && { weight: 'bold' as const })}>
352 {fit(name, room)}
353 </Text>
354 <Text {...ink} {...(isSettled(item.status) ? {} : { dimColor: true })}>
355 {count}
356 </Text>
357 </Button>
358 </Box>
359 <Box flexShrink={0}>
360 <Text {...ink} {...(isSettled(item.status) ? {} : { dimColor: true })}>
361 {right === '' ? '' : ` ${right}`}
362 </Text>
363 </Box>
364 </Box>
365 {!isSettled(item.status) && item.doing !== undefined && item.doing !== '' && (
366 <Text dimColor wrap="truncate-end">
367 {`${pad} ${item.doing}`}
368 </Text>
369 )}
370 {item.children.map(child => itemRow(scene, child, depth + 1))}
371 {(item.folded ?? 0) > 0 && <Text dimColor>{`${pad} +${item.folded}개 완료`}</Text>}
372 </Box>
373 )
374}
375
376/** A detail tab: the item's header and close, then what is known of it. */
377function drawDetail(scene: Scene, key: string) {
378 const { Box, Text, Button } = scene.kit
379 const body =
380 key === 'team'
381 ? teamDetail(scene)
382 : key.startsWith('flow:')
383 ? flowDetail(scene, key.slice(5))
384 : key.startsWith('peer:')
385 ? peerDetail(scene, Number(key.slice(5)))
386 : agentDetail(scene, key)
387 return (
388 <Box flexDirection="column">
389 <Box flexDirection="row" justifyContent="space-between">
390 <Button key="back" plain label="← 목록" onPress={() => scene.show(ALL)}>
391 <Text dimColor>← 목록</Text>
392 </Button>
393 <Button key={`close-top:${key}`} label="× 닫기" onPress={() => scene.close(key)}>
394 × 닫기
395 </Button>
396 </Box>
397 {body ?? <Text dimColor>이 항목은 더 이상 세션에 없습니다.</Text>}
398 </Box>
399 )
400}
401
402function header(scene: Scene, item: Pick<Item, 'title' | 'sub' | 'status' | 'progress' | 'tokens' | 'startedAt' | 'endedAt' | 'kind'>) {
403 const { Box, Text } = scene.kit
404 const look = LOOK[item.status]
405 const right = costText(item, scene.now)
406 return (
407 <Box flexDirection="column" marginTop={1}>
408 <Box flexDirection="row">
409 <Box flexGrow={1} flexShrink={1}>
410 <Text wrap="truncate-end">
411 <Text color={look.color}>{look.box}</Text> <Text weight="bold" {...inkOf(item.status)}>{item.title}</Text>
412 <Text dimColor>{countText(item.progress)}</Text>
413 </Text>
414 </Box>
415 <Box flexShrink={0}>
416 <Text dimColor>{right === '' ? '' : ` ${right}`}</Text>
417 </Box>
418 </Box>
419 {item.sub !== undefined && item.sub !== '' && (
420 <Text dimColor wrap="wrap">
421 {` ${item.sub}`}
422 </Text>
423 )}
424 </Box>
425 )
426}
427
428/**
429 * A tab's opening lines: what the item was asked to do and what it is doing
430 * now, in a word or a sentence, before the figures below.
431 */
432function summary(scene: Scene, task: string | undefined, now: string) {
433 const { Box, Text } = scene.kit
434 const row = (label: string, value: string) => (
435 <Box flexDirection="row">
436 <Box flexShrink={0}>
437 <Text weight="bold" color="claude">
438 {label + ' '.repeat(Math.max(1, SUMMARY_LABEL - cells(label)))}
439 </Text>
440 </Box>
441 <Box flexGrow={1} flexShrink={1}>
442 <Text wrap="wrap">{value}</Text>
443 </Box>
444 </Box>
445 )
446 return (
447 <Box flexDirection="column" marginTop={1}>
448 {task !== undefined && task !== '' && row('맡은 일', task)}
449 {row('지금', now)}
450 </Box>
451 )
452}
453
454/** What a settled agent ended with: done with its last words, or why it stopped. */
455function endedText(status: ItemStatus, reply: string | undefined): string {
456 if (status === 'failed') return '실패·중단'
457 const last = reply === undefined ? '' : brief(reply, 90)
458 return last === '' ? '끝남' : `끝남 · ${last}`
459}
460
461/** A few names, then how many more. */
462function names(list: readonly string[]): string {
463 const shown = list.slice(0, SUMMARY_NAMES).join(', ')
464 return list.length > SUMMARY_NAMES ? `${shown} 외 ${list.length - SUMMARY_NAMES}개` : shown
465}
466
467function field(scene: Scene, label: string, value: RenderChildren) {
468 const { Box, Text } = scene.kit
469 return (
470 <Box flexDirection="row">
471 <Box flexShrink={0}>
472 <Text dimColor>{label + ' '.repeat(Math.max(1, LABEL + 1 - cells(label)))}</Text>
473 </Box>
474 <Box flexGrow={1} flexShrink={1}>
475 <Text wrap="truncate-end">{value}</Text>
476 </Box>
477 </Box>
478 )
479}
480
481function section(scene: Scene, title: string, rows: RenderChildren[]) {
482 const { Box, Text } = scene.kit
483 return (
484 <Box flexDirection="column" marginTop={1}>
485 <Text weight="bold">{title}</Text>
486 {rows}
487 </Box>
488 )
489}
490
491function tokenParts(tokens: Tokens): string {
492 if (tokens.requests === 0) return '아직 없음'
493 return [
494 `↑${compact(inputTotal(tokens))} ↓${compact(tokens.output)}`,
495 `새 입력 ${compact(tokens.input)}`,
496 `캐시 읽기 ${compact(tokens.cacheRead)}`,
497 `캐시 쓰기 ${compact(tokens.cacheWrite)}`,
498 `요청 ${tokens.requests}회`,
499 ].join(' · ')
500}
501
502function timeText(status: ItemStatus, startedAt: number | undefined, endedAt: number | undefined, now: number): string {
503 if (startedAt === undefined) return WORD[status]
504 return `${WORD[status]} · ${duration((isSettled(status) ? (endedAt ?? now) : now) - startedAt)}`
505}
506
507function checkRow(scene: Scene, done: boolean, text: string, note?: string) {
508 const { Text } = scene.kit
509 return (
510 <Text wrap="truncate-end">
511 {' '}
512 <Text color={done ? 'success' : 'inactive'}>{done ? '☑' : '☐'}</Text>{' '}
513 <Text {...(done ? { color: 'success' } : {})}>{text}</Text>
514 {note !== undefined && note !== '' && <Text dimColor>{` · ${note}`}</Text>}
515 </Text>
516 )
517}
518
519/** The main session, a subagent, a teammate or a workflow agent. */
520function agentDetail(scene: Scene, key: string): RenderChildren | undefined {
521 const { Text } = scene.kit
522 const { now } = scene
523 let id: string | undefined
524 let flow: Workflow | undefined
525 let item: Item | undefined
526 if (key === 'main') {
527 id = MAIN
528 item = scene.board.main
529 } else if (key.startsWith('agent:')) {
530 id = key.slice(6)
531 } else if (key.startsWith('task:')) {
532 const cut = key.lastIndexOf(':')
533 const flowKey = key.slice(5, cut)
534 const index = Number(key.slice(cut + 1))
535 flow = scene.flows.find(one => one.key === flowKey)
536 const task = flow?.tasks.find(t => t.index === index)
537 if (flow === undefined || task === undefined) return undefined
538 id = task.agentId
539 item = taskItem(flow, task, scene.activity, (agentId, fallback = ZERO_TOKENS) => {
540 const tokens = agentId === undefined ? undefined : scene.activity[agentId]?.tokens
541 return tokens !== undefined && tokens.requests > 0 ? tokens : fallback
542 })
543 }
544 const one = id === undefined ? undefined : scene.activity[id]
545 const agent = id === undefined ? undefined : scene.agents.find(a => a.id === id)
546 if (item === undefined) {
547 if (agent === undefined && one === undefined) return undefined
548 const status: ItemStatus = agent !== undefined ? statusOf(agent.status) : one?.stoppedAt !== undefined ? 'done' : 'running'
549 item = {
550 key,
551 kind: 'agent',
552 title: agent?.name ?? typeLabel(agent?.type ?? one?.kind ?? '에이전트'),
553 status,
554 tokens: one?.tokens ?? ZERO_TOKENS,
555 children: [],
556 ...(agent?.description !== undefined && { sub: agent.description }),
557 ...(one !== undefined && { startedAt: one.firstSeen }),
558 ...(isSettled(status) && (one?.stoppedAt ?? one?.endedAt) !== undefined && { endedAt: (one?.stoppedAt ?? one?.endedAt) as number }),
559 }
560 const count = todoCount(one?.todos)
561 if (count !== undefined) item.progress = count
562 }
563 const owned = Object.values(scene.tasks).filter(t =>
564 id === MAIN ? t.by === MAIN || t.owner === undefined : t.owner !== undefined && [agent?.name, agent?.teammateId?.split('@')[0]].includes(t.owner),
565 )
566 const parent = agent?.parentId === undefined ? undefined : scene.agents.find(a => a.id === agent.parentId)
567 const rawKind = agent?.type ?? one?.kind ?? (flow !== undefined ? 'workflow-subagent' : undefined)
568 const kind =
569 rawKind === undefined
570 ? key === 'main'
571 ? '메인 루프'
572 : undefined
573 : typeLabel(rawKind) === rawKind
574 ? rawKind
575 : `${typeLabel(rawKind)} (${rawKind})`
576 const doing = doingOf(one, owned.find(t => t.status === 'in_progress'))
577 const task = one?.task ?? (flow !== undefined ? item.title : agent?.description)
578 const current = isSettled(item.status)
579 ? endedText(item.status, one?.reply)
580 : (doing ?? (item.status === 'idle' ? '대기 중' : '생각 중'))
581 const todos = one?.todos ?? []
582 const recent = (one?.recent ?? []).slice(-RECENT_ROWS).reverse()
583 const reply = (one?.reply ?? '').split('\n').filter(line => line.trim() !== '').slice(0, REPLY_ROWS)
584 return [
585 header(scene, item),
586 summary(scene, task, current),
587 field(scene, '상태', timeText(item.status, item.startedAt, item.endedAt, scene.now)),
588 kind !== undefined && field(scene, '종류', kind),
589 flow !== undefined && field(scene, '소속', `워크플로 ${flow.name}${item.sub !== undefined ? ` · ${item.sub} 단계` : ''}`),
590 parent !== undefined && field(scene, '상위', parent.name ?? parent.type),
591 field(scene, '토큰', tokenParts(item.tokens)),
592 one !== undefined && field(scene, '도구', `${one.tools}회 호출`),
593 (one?.running.length ?? 0) > 0 &&
594 section(
595 scene,
596 '실행 중인 호출',
597 (one?.running ?? []).map(call => <Text wrap="truncate-end">{` ⚙ ${call.text}`}</Text>),
598 ),
599 todos.length > 0 &&
600 section(scene, `할 일${countText(todoCount(todos))}`, todos.map(t => checkRow(scene, t.status === 'completed', t.status === 'in_progress' ? (t.activeForm ?? t.content) : t.content))),
601 todos.length === 0 &&
602 owned.length > 0 &&
603 section(scene, `작업 목록${countText(taskCount(owned))}`, owned.map(t => checkRow(scene, t.status === 'completed', t.subject, t.owner))),
604 recent.length > 0 && section(scene, '최근 호출', recent.map(text => <Text dimColor wrap="truncate-end">{` ↳ ${text}`}</Text>)),
605 reply.length > 0 && section(scene, '마지막 응답', reply.map(line => <Text wrap="truncate-end">{` ${line}`}</Text>)),
606 id !== undefined && id !== MAIN && <Text dimColor>{`ID ${id}`}</Text>,
607 ]
608}
609
610/** A workflow run: its plan and phases, then every agent it started. */
611function flowDetail(scene: Scene, flowKey: string): RenderChildren | undefined {
612 const { Box, Text, Button } = scene.kit
613 const { now } = scene
614 const flow = scene.flows.find(one => one.key === flowKey)
615 if (flow === undefined) return undefined
616 const status = standing(flow, now)
617 const count = progress(flow, status)
618 const itemStatus: ItemStatus = status === 'running' ? 'running' : status === 'done' ? 'done' : 'failed'
619 const live = (agentId: string | undefined, fallback: Tokens = ZERO_TOKENS) => {
620 const tokens = agentId === undefined ? undefined : scene.activity[agentId]?.tokens
621 return tokens !== undefined && tokens.requests > 0 ? tokens : fallback
622 }
623 const tasks = flow.tasks.map(task => taskItem(flow, task, scene.activity, live))
624 const end = status === 'running' ? undefined : finishedAt(flow)
625 const tokens: Tokens = tasks.reduce(
626 (sum, t) => ({
627 input: sum.input + t.tokens.input,
628 output: sum.output + t.tokens.output,
629 cacheRead: sum.cacheRead + t.tokens.cacheRead,
630 cacheWrite: sum.cacheWrite + t.tokens.cacheWrite,
631 requests: sum.requests + t.tokens.requests,
632 }),
633 ZERO_TOKENS,
634 )
635 const item: Item = {
636 key: `flow:${flow.key}`,
637 kind: 'flow',
638 title: `워크플로 · ${flow.name}`,
639 status: itemStatus,
640 progress: { done: count.done, total: count.total, isOpen: count.isOpen },
641 tokens,
642 startedAt: flow.startedAt,
643 children: [],
644 ...(end !== undefined && { endedAt: end }),
645 }
646 // 지금: 실행 중인 에이전트들이 가장 많이 속한 단계와 그 이름들
647 const running = flow.tasks.filter(t => t.status === 'running')
648 const tally = new Map<string, number>()
649 for (const t of running) {
650 if (t.phase !== undefined) tally.set(t.phase, (tally.get(t.phase) ?? 0) + 1)
651 }
652 let phaseNow: string | undefined
653 for (const [phase, n] of tally) {
654 if (phaseNow === undefined || n > (tally.get(phaseNow) ?? 0)) phaseNow = phase
655 }
656 const current =
657 status === 'running'
658 ? running.length > 0
659 ? `${phaseNow === undefined ? '' : `${phaseNow} 단계 · `}${names(running.map(t => t.label))} 실행 중`
660 : count.waiting > 0
661 ? '다음 에이전트를 기다리는 중'
662 : '마무리 중'
663 : status === 'done'
664 ? `끝남 · 에이전트 ${count.done}개 완료`
665 : `실패·중단 · ${count.done}/${count.total} 완료`
666 const bar = gauge(count.percent, BAR)
667 const phases = phaseCounts(flow)
668 const stats = [
669 count.running > 0 ? `${count.running}개 실행 중` : '',
670 count.waiting > 0 ? `${count.waiting}개 대기` : '',
671 count.failed > 0 ? `${count.failed}개 실패` : '',
672 count.cached > 0 ? `${count.cached}개 재사용` : '',
673 ].filter(Boolean)
674 return [
675 header(scene, item),
676 summary(scene, flow.description ?? flow.name, current),
677 field(scene, '상태', timeText(itemStatus, flow.startedAt, end, now)),
678 field(
679 scene,
680 '진행',
681 <Text>
682 <Text color="claude">{bar.filled}</Text>
683 <Text dimColor>{bar.empty}</Text>
684 {` ${count.done}/${count.total}${count.isOpen ? '+' : ''}${count.isOpen ? '' : ` ${count.percent}%`}`}
685 {stats.length > 0 && <Text dimColor>{` · ${stats.join(' · ')}`}</Text>}
686 </Text>,
687 ),
688 phases.length > 0 && field(scene, '단계', phases.join(' › ')),
689 flow.plan !== undefined &&
690 field(scene, '계획', `${flow.plan.total}개${flow.plan.isOpen ? '+ (에이전트 결과에 따라 늘어남)' : ''}`),
691 field(scene, '토큰', tokenParts(tokens)),
692 section(
693 scene,
694 `에이전트${countText(item.progress)}`,
695 tasks.map(task => (
696 <Box flexDirection="row">
697 <Box flexGrow={1} flexShrink={1} flexDirection="row">
698 <Text> </Text>
699 <Button
700 key={`open:${task.key}`}
701 plain
702 label={task.title}
703 onPress={() => scene.open(task.key, task.title)}
704 >
705 <Text color={LOOK[task.status].color}>{LOOK[task.status].box}</Text>{' '}
706 <Text {...inkOf(task.status)}>{fit(task.title, Math.max(6, scene.width - 30))}</Text>
707 {task.sub !== undefined && <Text dimColor>{` ${task.sub}`}</Text>}
708 </Button>
709 </Box>
710 <Box flexShrink={0}>
711 <Text dimColor>{` ${costText(task, now)}`}</Text>
712 </Box>
713 </Box>
714 )),
715 ),
716 flow.runId !== undefined && <Text dimColor>{`실행 ID ${flow.runId}`}</Text>,
717 ]
718}
719
720/** The phases of a run with how many of each one's agents are done. */
721function phaseCounts(flow: Workflow): string[] {
722 const named = [...flow.phases, ...flow.tasks.map(t => t.phase ?? '')].filter((p, i, all) => p !== '' && all.indexOf(p) === i)
723 return named.map(phase => {
724 const tasks = flow.tasks.filter(t => t.phase === phase)
725 if (tasks.length === 0) return phase
726 const done = tasks.filter(t => t.status === 'done').length
727 return `${phase} ${done}/${tasks.length}${done === tasks.length ? ' ✓' : ''}`
728 })
729}
730
731/** The agent team: its members, then the team's task list. */
732function teamDetail(scene: Scene): RenderChildren | undefined {
733 const { Text } = scene.kit
734 const team = [...scene.board.running, ...scene.board.finished].find(item => item.key === 'team')
735 if (team === undefined) return undefined
736 const tasks = Object.values(scene.tasks)
737 const active = tasks.filter(t => t.status === 'in_progress').map(t => t.activeForm ?? t.subject)
738 const count = taskCount(tasks)
739 const task =
740 active.length > 0
741 ? names(active)
742 : count !== undefined
743 ? `작업 목록 ${count.done}/${count.total} 완료`
744 : `팀원 ${team.children.length}명`
745 const busy = team.children.filter(member => member.status === 'running')
746 const current = isSettled(team.status)
747 ? endedText(team.status, undefined)
748 : busy.length > 0
749 ? names(busy.map(member => `${member.title}: ${member.doing ?? '생각 중'}`))
750 : '모두 대기 중'
751 return [
752 header(scene, team),
753 summary(scene, task, current),
754 field(scene, '상태', timeText(team.status, team.startedAt, team.endedAt, scene.now)),
755 field(scene, '토큰', tokenParts(team.tokens)),
756 section(scene, `구성원 ${team.children.length}명`, team.children.map(member => itemRow(scene, member, 1))),
757 tasks.length > 0 &&
758 section(
759 scene,
760 `작업 목록${countText(taskCount(tasks))}`,
761 tasks.map(t => checkRow(scene, t.status === 'completed', t.status === 'in_progress' ? (t.activeForm ?? t.subject) : t.subject, t.owner)),
762 ),
763 tasks.length === 0 && <Text dimColor> 아직 작업 목록이 없습니다.</Text>,
764 ]
765}
766
767/** Another session: where it runs and how it stands, a message to it, or its end. */
768function peerDetail(scene: Scene, pid: number): RenderChildren | undefined {
769 const { Box, Text, Button } = scene.kit
770 const { now } = scene
771 const peer = scene.peers.list.find(one => one.pid === pid)
772 if (peer === undefined) {
773 const known = scene.tabs.open.find(tab => tab.key === `peer:${pid}`)
774 return [
775 <Text dimColor wrap="wrap">
776 {` ${known?.title ?? '이'} 세션은 더 이상 실행 중이 아닙니다.`}
777 </Text>,
778 ]
779 }
780 const look = lookOf(peer)
781 const since = peer.statusAt === undefined ? '' : ` · ${duration(now - peer.statusAt)}째`
782 const kind = [peer.kind === undefined ? undefined : (KINDS[peer.kind] ?? peer.kind), peer.entrypoint, peer.version === undefined ? undefined : `v${peer.version}`]
783 .filter(Boolean)
784 .join(' · ')
785 const isEnding = scene.scope.ending === peer.pid
786 return [
787 <Box flexDirection="column" marginTop={1}>
788 <Text wrap="truncate-end">
789 <Text color={look.color}>●</Text> <Text weight="bold">{peerName(peer)}</Text>
790 </Text>
791 </Box>,
792 <Box flexDirection="column" marginTop={1}>
793 {field(scene, '상태', `${look.word}${peer.waitingFor === undefined ? '' : ` (${peer.waitingFor})`}${since}`)}
794 {field(scene, '폴더', homeShort(peer.cwd, scene.peers.homeDir))}
795 {peer.startedAt !== undefined && field(scene, '시작', `${duration(now - peer.startedAt)} 전`)}
796 {kind !== '' && field(scene, '종류', kind)}
797 {field(scene, 'PID', String(peer.pid))}
798 {field(scene, 'ID', peer.sessionId)}
799 </Box>,
800 <Box flexDirection="row" flexWrap="wrap" columnGap={2} marginTop={1}>
801 <Button key={`message:${peer.pid}`} plain label="메시지 보내기" onPress={() => scene.message(peer)}>
802 <Text backgroundColor={CHIP.idle} color="text">
803 {' 메시지 보내기 '}
804 </Text>
805 </Button>
806 <Button key={`end:${peer.pid}`} plain label={isEnding ? '한 번 더 누르면 종료' : '세션 종료'} onPress={() => scene.end(peer)}>
807 <Text
808 {...(isEnding ? { backgroundColor: 'error', color: CHIP.ink, weight: 'bold' as const } : { backgroundColor: CHIP.idle, color: 'text' })}
809 >
810 {isEnding ? ' 한 번 더 누르면 종료 ' : ' 세션 종료 '}
811 </Text>
812 </Button>
813 </Box>,
814 <Text dimColor wrap="wrap">
815 {'메시지는 그 세션이 다음 차례에 읽습니다. 종료한 세션은 그 폴더에서 claude --resume 으로 다시 엽니다.'}
816 </Text>,
817 ]
818}
819hooks/workflow.ts 447 lines1import type { Tokens, Workflow, WorkflowCall, WorkflowStatus, WorkflowTask } from '../types'
2import { ZERO_TOKENS, hashOf, shortPaths, sumTokens } from './format'
3import { planOf } from './plan'
4
5const MAX_WORKFLOWS = 12
6const MAX_CALLS = 20
7const MAX_LABEL = 120
8/** A run whose agents have all settled and that starts none for this long is done. */
9export const QUIET_MS = 60_000
10
11/**
12 * What a Workflow call's input says about the run: its script's meta, or its
13 * name, and how many agents the script starts. `file` is the script a
14 * `scriptPath` or `name` call runs, when it could be read.
15 */
16export function readWorkflowCall(input: unknown, file?: string): WorkflowCall | undefined {
17 if (typeof input !== 'object' || input === null) return undefined
18 const args = input as Record<string, unknown>
19 const script = typeof args.script === 'string' ? args.script : file
20 const named = (): WorkflowCall | undefined => {
21 if (typeof args.name === 'string' && args.name !== '') return { name: args.name, phases: [] }
22 if (typeof args.scriptPath !== 'string' || args.scriptPath === '') return undefined
23 const base = args.scriptPath.split('/').pop() ?? args.scriptPath
24 return { name: base.replace(/\.[^.]+$/, ''), phases: [] }
25 }
26 const call = (script === undefined ? undefined : metaOf(script)) ?? named()
27 if (call === undefined) return undefined
28 if (script !== undefined) {
29 call.plan = planOf(script, args.args)
30 call.hash = hashOf(script)
31 }
32 if (args.args !== undefined) call.args = args.args
33 return call
34}
35
36/** What a run's saved script says about it: its meta and plan, `args` from the call that ran it. */
37export function callOfScript(script: string, calls: Readonly<Record<string, WorkflowCall>>): WorkflowCall | undefined {
38 const meta = metaOf(script)
39 if (meta === undefined) return undefined
40 const hash = hashOf(script)
41 const call = Object.values(calls).find(one => one.hash === hash)
42 return { ...meta, plan: planOf(script, call?.args), hash }
43}
44
45/** Where a call that names its script rather than sending it keeps that script. */
46export function scriptPaths(input: unknown): string[] {
47 if (typeof input !== 'object' || input === null) return []
48 const args = input as Record<string, unknown>
49 if (typeof args.script === 'string') return []
50 if (typeof args.scriptPath === 'string' && args.scriptPath !== '') return [args.scriptPath]
51 if (typeof args.name !== 'string' || !/^[\w.-]+$/.test(args.name)) return []
52 return [`.claude/workflows/${args.name}.js`, `.claude/workflows/${args.name}.mjs`]
53}
54
55/** The `export const meta = { name, description, phases }` literal a workflow script begins with. */
56export function metaOf(script: string): WorkflowCall | undefined {
57 const head = /export\s+const\s+meta\s*=\s*\{/.exec(script)
58 if (head === null) return undefined
59 const open = head.index + head[0].length - 1
60 const body = script.slice(open + 1, closing(script, open))
61 const top = topLevel(body)
62 const name = stringField(top, 'name')
63 if (name === undefined) return undefined
64 const call: WorkflowCall = { name, phases: [] }
65 const description = stringField(top, 'description')
66 if (description !== undefined) call.description = description
67 const phases = /\bphases\s*:\s*\[/.exec(body)
68 if (phases !== null) {
69 const from = phases.index + phases[0].length - 1
70 const list = body.slice(from + 1, closing(body, from))
71 call.phases = [...list.matchAll(/\btitle\s*:\s*(['"`])((?:\\.|(?!\1)[^\\])*)\1/g)].map(m => unescape(m[2] ?? ''))
72 }
73 return call
74}
75
76/** Where the bracket opened at `open` closes, strings skipped; the text's end when it never does. */
77function closing(text: string, open: number): number {
78 let depth = 0
79 let quote: string | undefined
80 for (let at = open; at < text.length; at += 1) {
81 const char = text[at]
82 if (quote !== undefined) {
83 if (char === '\\') at += 1
84 else if (char === quote) quote = undefined
85 continue
86 }
87 if (char === '"' || char === "'" || char === '`') quote = char
88 else if (char === '{' || char === '[' || char === '(') depth += 1
89 else if (char === '}' || char === ']' || char === ')') {
90 depth -= 1
91 if (depth === 0) return at
92 }
93 }
94 return text.length
95}
96
97/** An object body with its nested objects and lists left out, strings kept. */
98function topLevel(body: string): string {
99 let out = ''
100 let depth = 0
101 let quote: string | undefined
102 for (let at = 0; at < body.length; at += 1) {
103 const char = body[at] ?? ''
104 if (quote !== undefined) {
105 if (depth === 0) out += char
106 if (char === '\\') {
107 if (depth === 0) out += body[at + 1] ?? ''
108 at += 1
109 } else if (char === quote) quote = undefined
110 continue
111 }
112 if (char === '"' || char === "'" || char === '`') quote = char
113 if (char === '{' || char === '[' || char === '(') depth += 1
114 if (depth === 0) out += char
115 if (char === '}' || char === ']' || char === ')') depth = Math.max(0, depth - 1)
116 }
117 return out
118}
119
120function stringField(text: string, key: string): string | undefined {
121 const found = new RegExp(`\\b${key}\\s*:\\s*(['"\`])((?:\\\\.|(?!\\1)[^\\\\])*)\\1`).exec(text)
122 return found === null ? undefined : unescape(found[2] ?? '')
123}
124
125function unescape(text: string): string {
126 return text.replace(/\\n/g, ' ').replace(/\\(.)/g, '$1').trim()
127}
128
129/** A workflow agent's line: its description, else its prompt's first line. */
130export function taskLabel(description: string, prompt: string): string {
131 const text = description.trim() !== '' ? description : (prompt.trim().split('\n')[0] ?? '')
132 return shortPaths(text.trim()).slice(0, MAX_LABEL) || '작업'
133}
134
135export function keepCall(all: Record<string, WorkflowCall>, id: string, call: WorkflowCall): Record<string, WorkflowCall> {
136 const entries = [...Object.entries(all).filter(([key]) => key !== id), [id, call] as const]
137 return Object.fromEntries(entries.slice(-MAX_CALLS))
138}
139
140function find(list: readonly Workflow[], key: string, runId: string): number {
141 if (runId !== '') {
142 const byRun = list.findIndex(one => one.runId === runId)
143 if (byRun !== -1) return byRun
144 }
145 return key === '' ? -1 : list.findIndex(one => one.key === key)
146}
147
148/**
149 * Files an agent a run's `agent()` started: under its run, found by run id
150 * and then by the Workflow call that started it, or under a new entry.
151 * The same place in a run (a resume replaying it) takes the task over.
152 */
153export function startTask(
154 list: readonly Workflow[],
155 start: { key: string; runId: string; index: number; label: string; call?: WorkflowCall; now: number },
156): Workflow[] {
157 const { key, runId, index, label, call, now } = start
158 const at = find(list, key, runId)
159 const task: WorkflowTask = { index, label, status: 'running', startedAt: now, tokens: ZERO_TOKENS }
160 const base: Workflow =
161 at === -1
162 ? {
163 key: key !== '' ? key : runId,
164 name: call?.name ?? (runId !== '' ? runId : 'workflow'),
165 phases: call?.phases ?? [],
166 status: 'running',
167 startedAt: now,
168 tasks: [],
169 }
170 : (list[at] as Workflow)
171 const { endedAt: _, ...open } = base
172 const next: Workflow = { ...open, status: 'running', tasks: [...base.tasks.filter(t => t.index !== index), task] }
173 next.tasks.sort((a, b) => a.index - b.index)
174 if (runId !== '') next.runId = runId
175 if (call !== undefined) {
176 next.name = call.name
177 next.phases = call.phases
178 if (call.description !== undefined) next.description = call.description
179 if (call.plan !== undefined) next.plan = call.plan
180 }
181 const rest = list.filter((_one, i) => i !== at)
182 return trim([...rest, next])
183}
184
185/**
186 * Names the agent a started task runs as, so its end can find it; a row the
187 * run's journal filed for the same agent first is folded into this one.
188 */
189export function bindAgent(list: readonly Workflow[], runId: string, key: string, index: number, agentId: string): Workflow[] {
190 const at = find(list, key, runId)
191 if (at === -1) return [...list]
192 return list.map((one, i) => {
193 if (i !== at) return one
194 const twin = one.tasks.find(t => t.agentId === agentId && t.index !== index)
195 const tasks = one.tasks
196 .filter(t => t !== twin)
197 .map(t => (t.index !== index ? t : { ...t, agentId, ...(twin?.phase !== undefined && { phase: twin.phase }) }))
198 return { ...one, tasks }
199 })
200}
201
202/** Settles the task an agent ran, as done or failed, with what it cost. */
203export function finishTask(
204 list: readonly Workflow[],
205 agentId: string,
206 end: { isFailed: boolean; tokens: Tokens; now: number },
207): Workflow[] {
208 return list.map(one =>
209 one.tasks.some(t => t.agentId === agentId)
210 ? {
211 ...one,
212 tasks: one.tasks.map(t =>
213 t.agentId === agentId && t.status === 'running'
214 ? { ...t, status: end.isFailed ? 'failed' : 'done', endedAt: end.now, tokens: end.tokens }
215 : t,
216 ),
217 }
218 : one,
219 )
220}
221
222/** Fails the task a refused spawn left running. */
223export function refuseTask(list: readonly Workflow[], runId: string, key: string, index: number, now: number): Workflow[] {
224 const at = find(list, key, runId)
225 return list.map((one, i) =>
226 i !== at
227 ? one
228 : { ...one, tasks: one.tasks.map(t => (t.index === index ? { ...t, status: 'failed', endedAt: now } : t)) },
229 )
230}
231
232/** One line of a run's `journal.jsonl`: `started`, `result` and the rest. */
233export type JournalEntry = { type: string; agentId?: string; label?: string; phase?: string; result?: unknown }
234
235export function readJournal(text: string): JournalEntry[] {
236 const entries: JournalEntry[] = []
237 for (const line of text.split('\n')) {
238 if (line.trim() === '') continue
239 try {
240 const value: unknown = JSON.parse(line)
241 if (typeof value !== 'object' || value === null) continue
242 const row = value as Record<string, unknown>
243 if (typeof row.type !== 'string') continue
244 const entry: JournalEntry = { type: row.type }
245 if (typeof row.agentId === 'string') entry.agentId = row.agentId
246 if (typeof row.label === 'string') entry.label = row.label
247 if (typeof row.phase === 'string') entry.phase = row.phase
248 if ('result' in row) entry.result = row.result === null ? null : true
249 entries.push(entry)
250 } catch {
251 // A line still being written reads whole on the next pass.
252 }
253 }
254 return entries
255}
256
257/**
258 * Brings a run in line with its journal on disk: each agent it started (by
259 * agent id, with its label and phase) and each that returned, a null return
260 * being a failed or skipped one. A run the hooks never saw is filed here.
261 * What the journal shows is dated by when it was last written (`at`).
262 */
263export function syncRun(
264 list: readonly Workflow[],
265 run: { runId: string; entries: readonly JournalEntry[]; call?: WorkflowCall; startedAt: number; at: number },
266): Workflow[] {
267 const at = list.findIndex(one => one.runId === run.runId)
268 const base: Workflow =
269 at === -1
270 ? { key: run.runId, runId: run.runId, name: run.runId, phases: [], status: 'running', startedAt: run.startedAt, tasks: [] }
271 : (list[at] as Workflow)
272 const tasks = [...base.tasks]
273 for (const entry of run.entries) {
274 const agentId = entry.agentId
275 if (agentId === undefined) continue
276 const found = tasks.findIndex(t => t.agentId === agentId)
277 if (entry.type === 'started') {
278 const label = entry.label === undefined ? undefined : taskLabel(entry.label, '')
279 if (found !== -1) {
280 const task = tasks[found] as WorkflowTask
281 tasks[found] = { ...task, ...(entry.phase !== undefined && { phase: entry.phase }), ...(label !== undefined && task.label === '작업' && { label }) }
282 continue
283 }
284 const index = Math.max(0, ...tasks.map(t => t.index)) + 1
285 const task: WorkflowTask = { index, label: label ?? '작업', status: 'running', agentId, startedAt: run.at, tokens: ZERO_TOKENS }
286 if (entry.phase !== undefined) task.phase = entry.phase
287 tasks.push(task)
288 continue
289 }
290 const task = found === -1 ? undefined : tasks[found]
291 if (task === undefined || task.status !== 'running') continue
292 if (entry.type === 'result') {
293 tasks[found] = { ...task, status: entry.result === null ? 'failed' : 'done', endedAt: run.at }
294 } else if (/error|fail/i.test(entry.type)) {
295 tasks[found] = { ...task, status: 'failed', endedAt: run.at }
296 }
297 }
298 const next: Workflow = { ...base, tasks }
299 const call = run.call
300 if (call !== undefined && (next.name === run.runId || next.plan === undefined)) {
301 next.name = call.name
302 next.phases = call.phases
303 if (call.description !== undefined) next.description = call.description
304 if (call.plan !== undefined) next.plan = call.plan
305 }
306 if (at === -1) return trim([...list, next])
307 return list.map((one, i) => (i === at ? next : one))
308}
309
310export type Notice = { toolUseId?: string; runId?: string; status: WorkflowStatus }
311
312/** What a background task's notification says: which call or run, and how it ended. */
313export function readNotice(text: string): Notice | undefined {
314 const tag = (name: string) => new RegExp(`<${name}>([^<]*)</${name}>`).exec(text)?.[1]?.trim()
315 const word = tag('status')?.toLowerCase()
316 const status: WorkflowStatus | undefined =
317 word === undefined
318 ? undefined
319 : /^(completed|done|success)/.test(word)
320 ? 'done'
321 : /^(failed|error)/.test(word)
322 ? 'failed'
323 : /^(killed|stopped|cancel)/.test(word)
324 ? 'stopped'
325 : undefined
326 if (status === undefined) return undefined
327 const notice: Notice = { status }
328 const toolUseId = tag('tool-use-id')
329 if (toolUseId !== undefined && toolUseId !== '') notice.toolUseId = toolUseId
330 const runId = /\bwf_[A-Za-z0-9_-]+/.exec(text)?.[0]
331 if (runId !== undefined) notice.runId = runId
332 return notice.toolUseId === undefined && notice.runId === undefined ? undefined : notice
333}
334
335/** Ends the run a notification names; the agents it left running end with it. */
336export function endWorkflow(list: readonly Workflow[], notice: Notice, now: number): Workflow[] {
337 const at = find(list, notice.toolUseId ?? '', notice.runId ?? '')
338 if (at === -1) return [...list]
339 return list.map((one, i) =>
340 i !== at
341 ? one
342 : {
343 ...one,
344 status: notice.status,
345 endedAt: now,
346 tasks: one.tasks.map(t =>
347 t.status === 'running' ? { ...t, status: notice.status === 'done' ? 'done' : 'failed', endedAt: now } : t,
348 ),
349 },
350 )
351}
352
353/** Keeps the newest runs, dropping settled ones first. */
354function trim(list: Workflow[]): Workflow[] {
355 if (list.length <= MAX_WORKFLOWS) return list
356 const drop = new Set(
357 list
358 .filter(one => one.status !== 'running')
359 .sort((a, b) => a.startedAt - b.startedAt)
360 .slice(0, list.length - MAX_WORKFLOWS),
361 )
362 return list.filter(one => !drop.has(one)).slice(-MAX_WORKFLOWS)
363}
364
365/**
366 * Where a run stands now: its notification's word, or done once every agent
367 * it started has settled and it has started none for a while.
368 */
369export function standing(flow: Workflow, now: number): WorkflowStatus {
370 if (flow.status !== 'running' || flow.tasks.length === 0) return flow.status
371 if (flow.tasks.some(t => t.status === 'running')) return 'running'
372 const last = Math.max(...flow.tasks.map(t => t.endedAt ?? t.startedAt))
373 return now - last >= QUIET_MS ? 'done' : 'running'
374}
375
376export function finishedAt(flow: Workflow): number | undefined {
377 if (flow.endedAt !== undefined) return flow.endedAt
378 const ends = flow.tasks.map(t => t.endedAt).filter((at): at is number => at !== undefined)
379 return ends.length === 0 ? undefined : Math.max(...ends)
380}
381
382export type Progress = {
383 /** Agents that finished their work, those the journal replayed among them. */
384 done: number
385 failed: number
386 running: number
387 /** Agents the script starts that have not started yet. */
388 waiting: number
389 /** Agents replayed from a resumed run's journal: done, never raised. */
390 cached: number
391 total: number
392 /** The total is a floor: more agents hang on what the run's agents return. */
393 isOpen: boolean
394 /** How far along the run is, 0 to 100. */
395 percent: number
396 tokens: Tokens
397}
398
399/**
400 * Where a run's agents stand against all the run starts: the plan its script
401 * gave, or the agents seen, whichever is more; a done run counts the agents
402 * it did start, since a branch it skipped never comes.
403 */
404export function progress(flow: Workflow, status: WorkflowStatus): Progress {
405 const count = (state: WorkflowTask['status']) => flow.tasks.filter(t => t.status === state).length
406 const seen = Math.max(flow.tasks.length, ...flow.tasks.map(t => t.index))
407 const cached = seen - flow.tasks.length
408 const isRunning = status === 'running'
409 const total = status === 'done' ? seen : Math.max(seen, flow.plan?.total ?? 0)
410 const done = count('done') + cached
411 return {
412 done,
413 failed: count('failed'),
414 running: count('running'),
415 waiting: isRunning ? total - seen : 0,
416 cached,
417 total,
418 isOpen: isRunning && (flow.plan === undefined || flow.plan.isOpen),
419 percent: total === 0 ? 0 : Math.floor((done / total) * 100),
420 tokens: sumTokens(flow.tasks.map(t => t.tokens)),
421 }
422}
423
424/**
425 * How the pane lays the runs out, newest first: every running run open, or
426 * the newest when none runs; the settled runs before it as passing lines.
427 */
428export function arrange(list: readonly Workflow[], now: number, keep: number): { open: Workflow[]; passed: Workflow[]; hidden: number } {
429 const newest = [...list].sort((a, b) => b.startedAt - a.startedAt)
430 const running = newest.filter(one => standing(one, now) === 'running')
431 const open = running.length > 0 ? running : newest.slice(0, 1)
432 const rest = newest.filter(one => !open.includes(one))
433 return { open, passed: rest.slice(0, keep), hidden: Math.max(0, rest.length - keep) }
434}
435
436/** The tasks an open run lists in `room` rows: all that run, then the latest settled. */
437export function visibleTasks(flow: Workflow, room: number): { shown: WorkflowTask[]; folded: number } {
438 if (flow.tasks.length <= room) return { shown: flow.tasks, folded: 0 }
439 const running = flow.tasks.filter(t => t.status === 'running')
440 const settled = flow.tasks
441 .filter(t => t.status !== 'running')
442 .sort((a, b) => (b.endedAt ?? 0) - (a.endedAt ?? 0))
443 .slice(0, Math.max(0, room - running.length))
444 const shown = [...running.slice(0, room), ...settled].sort((a, b) => a.index - b.index)
445 return { shown, folded: flow.tasks.length - shown.length }
446}
447hooks/plan.ts 505 lines1import type { WorkflowPlan } from '../types'
2
3/** How deep a count follows names, helpers and their callers before it gives up. */
4const MAX_DEPTH = 8
5const OPENERS = '([{'
6const CLOSERS = ')]}'
7const NAME = /^[A-Za-z_$][\w$]*$/
8const ITERATES = new Set(['map', 'flatMap', 'forEach', 'filter', 'reduce', 'reduceRight'])
9const KEEPS_SIZE = new Set(['map', 'fill', 'reverse', 'sort', 'toSorted', 'toReversed'])
10
11/** A count, or undefined where it hangs on what the run's agents return. */
12type Count = number | undefined
13
14type Helper = { name: string; at: number; from: number; to: number }
15
16type Script = {
17 code: string
18 args: unknown
19 bindings: Map<string, string | null>
20 helpers: Helper[]
21}
22
23/**
24 * How many agents a workflow script starts, read before it runs: each
25 * `agent()` call counted as often as the lists, `args`, `Array.from` lengths
26 * and loops around it repeat it. A repeat that hangs on what agents return
27 * (their findings, a `while`) makes the count a floor, `isOpen`.
28 */
29export function planOf(script: string, args?: unknown): WorkflowPlan {
30 const code = mask(script)
31 const at = { code, args, bindings: bindingsOf(code), helpers: helpersOf(code) }
32 let total = 0
33 let isOpen = /(?<![\w$.])workflow\s*\(/.test(code)
34 for (const site of code.matchAll(/(?<![\w$.])agent\s*\(/g)) {
35 const times = repeats(at, site.index, 0)
36 if (times === undefined) isOpen = true
37 else total += times
38 }
39 return { total, isOpen }
40}
41
42/** How often the code at `p` runs: the repeats around it, times its helper's calls. */
43function repeats(at: Script, p: number, depth: number): Count {
44 if (depth > MAX_DEPTH) return undefined
45 const helper = at.helpers
46 .filter(one => one.from <= p && p < one.to)
47 .sort((a, b) => b.from - a.from)[0]
48 let times: Count = 1
49 for (const open of enclosing(at.code, p)) {
50 if (helper !== undefined && open < helper.from) break
51 const factor = factorAt(at, open, p, depth)
52 if (factor === 0) return 0
53 times = factor === undefined || times === undefined ? undefined : times * factor
54 }
55 if (helper === undefined || times === 0) return times
56 let calls: Count = 0
57 for (const use of at.code.matchAll(new RegExp(`(?<![\\w$.])${escape(helper.name)}(?![\\w$])(?!\\s*:)`, 'g'))) {
58 if (use.index === helper.at) continue
59 const each = repeats(at, use.index, depth + 1)
60 calls = each === undefined || calls === undefined ? undefined : calls + each
61 }
62 return times === undefined || calls === undefined ? (calls === 0 ? 0 : undefined) : times * calls
63}
64
65/** How often the bracket opened at `open` runs what `p` sits in. */
66function factorAt(at: Script, open: number, p: number, depth: number): Count {
67 const { code } = at
68 const before = code.slice(0, open).trimEnd()
69 if (code[open] === '(') {
70 if (/(?<![\w$])while$/.test(before)) return undefined
71 if (/\.\s*catch$/.test(before)) return 0
72 const method = /\.\s*([A-Za-z_$][\w$]*)$/.exec(before)
73 if (method !== null && ITERATES.has(method[1] ?? '')) {
74 return sizeOf(at, receiverBefore(code, method.index), depth + 1)
75 }
76 if (method !== null && /^(some|every|find|findIndex|findLast)$/.test(method[1] ?? '')) return undefined
77 const place = argIndex(code, open, p)
78 if (/(?<![\w$.])pipeline$/.test(before) && place >= 1) {
79 return sizeOf(at, argText(code, open, 0), depth + 1)
80 }
81 if (/(?<![\w$.])Array\s*\.\s*from$/.test(before) && place >= 1) {
82 return lengthOf(at, argText(code, open, 0), depth + 1)
83 }
84 return 1
85 }
86 if (code[open] === '{') {
87 if (/(?<![\w$])(do|catch)$/.test(before)) return /do$/.test(before) ? undefined : 0
88 if (!before.endsWith(')')) return 1
89 const head = matchOpen(code, before.length - 1)
90 const word = code.slice(0, head).trimEnd()
91 if (/(?<![\w$])catch$/.test(word)) return 0
92 if (/(?<![\w$])while$/.test(word)) return undefined
93 if (/(?<![\w$])for(\s+await)?$/.test(word)) return loopCount(at, code.slice(head + 1, before.length - 1), depth + 1)
94 }
95 return 1
96}
97
98/** How many times a `for` header runs its body. */
99function loopCount(at: Script, header: string, depth: number): Count {
100 const over = /^\s*(?:const|let|var)?\s*(?:[\w$]+|\[[^\]]*\]|\{[^}]*\})\s+of\s+([\s\S]+)$/.exec(header)
101 if (over !== null) return sizeOf(at, over[1] ?? '', depth)
102 const parts = splitTop(header, ';')
103 if (parts.length !== 3) return undefined
104 const [init = '', test = '', step = ''] = parts
105 const start = /^\s*(?:let|var)?\s*([\w$]+)\s*=\s*([\s\S]+)$/.exec(init)
106 const name = start?.[1]
107 if (start === null || name === undefined) return undefined
108 const from = numberOf(at, start[2] ?? '', depth)
109 const bound = new RegExp(`^\\s*${escape(name)}\\s*(<=?)\\s*([\\s\\S]+)$`).exec(test)
110 const to = bound === null ? undefined : numberOf(at, bound[2] ?? '', depth)
111 const isStep = new RegExp(`^\\s*(?:${escape(name)}\\s*\\+\\+|\\+\\+\\s*${escape(name)}|${escape(name)}\\s*\\+=\\s*1)\\s*$`).test(step)
112 if (from === undefined || to === undefined || !isStep || bound === null) return undefined
113 return Math.max(0, to - from + (bound[1] === '<=' ? 1 : 0))
114}
115
116/** How many items a list expression holds. */
117function sizeOf(at: Script, text: string, depth: number): Count {
118 if (depth > MAX_DEPTH) return undefined
119 const t = bare(text)
120 if (t === '') return undefined
121 if (t.startsWith('[') && matchClose(t, 0) === t.length - 1) {
122 let sum: Count = 0
123 const items = splitTop(t.slice(1, -1), ',')
124 if (items.length > 0 && (items[items.length - 1] ?? '').trim() === '') items.pop()
125 for (const item of items) {
126 const spread = /^\s*\.\.\.([\s\S]+)$/.exec(item)
127 const each = spread === null ? 1 : sizeOf(at, spread[1] ?? '', depth + 1)
128 sum = each === undefined || sum === undefined ? undefined : sum + each
129 }
130 return sum
131 }
132 if (isPath(t)) {
133 const value = valueAt(at, t, depth)
134 return Array.isArray(value) ? value.length : typeof value === 'string' ? sizeOf(at, value, depth + 1) : undefined
135 }
136 if (!t.endsWith(')')) return undefined
137 const open = matchOpen(t, t.length - 1)
138 const callee = t.slice(0, open).trimEnd()
139 const inner = t.slice(open + 1, -1)
140 if (/^Array\s*\.\s*from$/.test(callee)) return lengthOf(at, splitTop(inner, ',')[0] ?? '', depth + 1)
141 if (/^(new\s+)?Array$/.test(callee)) {
142 const parts = splitTop(inner, ',')
143 return parts.length === 1 ? numberOf(at, parts[0] ?? '', depth + 1) : parts.length
144 }
145 const keys = /^Object\s*\.\s*(keys|values|entries)$/.exec(callee)
146 if (keys !== null) return keysOf(at, inner, depth + 1)
147 // A run's results come back one per item, a failed one as null.
148 if (/^(parallel|pipeline|Promise\s*\.\s*all(Settled)?)$/.test(callee)) {
149 return sizeOf(at, splitTop(inner, ',')[0] ?? '', depth + 1)
150 }
151 const method = /\.\s*([A-Za-z_$][\w$]*)$/.exec(callee)
152 if (method === null) return undefined
153 const receiver = callee.slice(0, method.index)
154 const name = method[1] ?? ''
155 if (KEEPS_SIZE.has(name) || (name === 'filter' && inner.trim() === 'Boolean')) return sizeOf(at, receiver, depth + 1)
156 if (name === 'concat') {
157 let sum = sizeOf(at, receiver, depth + 1)
158 for (const part of splitTop(inner, ',')) {
159 const each = sizeOf(at, part, depth + 1)
160 sum = each === undefined || sum === undefined ? undefined : sum + each
161 }
162 return sum
163 }
164 if (name === 'slice') {
165 const size = sizeOf(at, receiver, depth + 1)
166 const [a, b] = splitTop(inner, ',')
167 const from = a === undefined || a.trim() === '' ? 0 : numberOf(at, a, depth + 1)
168 const to = b === undefined ? size : numberOf(at, b, depth + 1)
169 if (size === undefined || from === undefined || to === undefined) return undefined
170 const clamp = (n: number) => (n < 0 ? Math.max(0, size + n) : Math.min(size, n))
171 return Math.max(0, clamp(to) - clamp(from))
172 }
173 return undefined
174}
175
176/** `{ length: N }`, the first argument of `Array.from`, or a list's size. */
177function lengthOf(at: Script, text: string, depth: number): Count {
178 const t = bare(text)
179 const length = /^\{\s*length\s*:\s*([\s\S]+?)\s*,?\s*\}$/.exec(t)
180 return length === null ? sizeOf(at, t, depth) : numberOf(at, length[1] ?? '', depth)
181}
182
183function numberOf(at: Script, text: string, depth: number): Count {
184 if (depth > MAX_DEPTH) return undefined
185 const t = bare(text)
186 if (/^\d+$/.test(t)) return Number(t)
187 const pick = /^Math\s*\.\s*(min|max)\s*\(([\s\S]*)\)$/.exec(t)
188 if (pick !== null) {
189 const values = splitTop(pick[2] ?? '', ',').map(part => numberOf(at, part, depth + 1))
190 if (values.length === 0 || values.some(v => v === undefined)) return undefined
191 return pick[1] === 'min' ? Math.min(...(values as number[])) : Math.max(...(values as number[]))
192 }
193 const length = /^([\s\S]+?)\s*\.\s*length$/.exec(t)
194 if (length !== null) return sizeOf(at, length[1] ?? '', depth + 1)
195 if (!isPath(t)) return undefined
196 const value = valueAt(at, t, depth)
197 if (typeof value === 'number' && Number.isInteger(value)) return value
198 return typeof value === 'string' ? numberOf(at, value, depth + 1) : undefined
199}
200
201function keysOf(at: Script, text: string, depth: number): Count {
202 const value = isPath(bare(text)) ? valueAt(at, bare(text), depth) : bare(text)
203 if (typeof value === 'object' && value !== null && !Array.isArray(value)) return Object.keys(value).length
204 if (Array.isArray(value)) return value.length
205 if (typeof value !== 'string') return undefined
206 const t = bare(value)
207 if (!t.startsWith('{') || matchClose(t, 0) !== t.length - 1) return undefined
208 const entries = splitTop(t.slice(1, -1), ',').filter(part => part.trim() !== '')
209 return entries.some(part => part.trim().startsWith('...')) ? undefined : entries.length
210}
211
212/**
213 * What a path like `args.files` or `DIMENSIONS` stands for: a value from the
214 * call's `args`, or the source text a `const` binds, followed key by key.
215 */
216function valueAt(at: Script, path: string, depth: number): unknown {
217 if (depth > MAX_DEPTH) return undefined
218 const [root = '', ...keys] = path.replace(/\?/g, '').split(/\s*\.\s*|\s*\[\s*|\s*\]\s*/).filter(Boolean)
219 let value: unknown = root === 'args' ? at.args : at.bindings.get(root)
220 if (value === null) return undefined
221 for (const [place, key] of keys.entries()) {
222 if (typeof value === 'string') {
223 const t = bare(value)
224 if (isPath(t)) return valueAt(at, [t, ...keys.slice(place)].join('.'), depth + 1)
225 value = propertyOf(at, t, key)
226 } else if (typeof value === 'object' && value !== null) {
227 value = (value as Record<string, unknown>)[key]
228 } else {
229 return undefined
230 }
231 }
232 return value
233}
234
235/** The source text of `key` in an object literal, or undefined. */
236function propertyOf(at: Script, object: string, key: string): string | undefined {
237 if (!object.startsWith('{') || matchClose(object, 0) !== object.length - 1) return undefined
238 for (const part of splitTop(object.slice(1, -1), ',')) {
239 const entry = /^\s*([A-Za-z_$][\w$]*)\s*(?::\s*([\s\S]*))?$/.exec(part)
240 if (entry?.[1] !== key) continue
241 return entry[2] ?? (at.bindings.get(key) ?? undefined)
242 }
243 return undefined
244}
245
246/** Each `const` name and the source text it binds; a name bound twice is unknown (null). */
247function bindingsOf(code: string): Map<string, string | null> {
248 const bound = new Map<string, string | null>()
249 const bind = (name: string, text: string) => bound.set(name, bound.has(name) ? null : text)
250 for (const one of code.matchAll(/(?<![\w$.])const\s+([A-Za-z_$][\w$]*)\s*=(?![=>])/g)) {
251 const from = one.index + one[0].length
252 bind(one[1] ?? '', code.slice(from, expressionEnd(code, from)))
253 }
254 for (const one of code.matchAll(/(?<![\w$.])const\s*\{([^{}]*)\}\s*=(?![=>])/g)) {
255 const from = one.index + one[0].length
256 const source = bare(code.slice(from, expressionEnd(code, from)))
257 if (!isPath(source)) continue
258 for (const part of splitTop(one[1] ?? '', ',')) {
259 const entry = /^\s*([A-Za-z_$][\w$]*)\s*(?::\s*([A-Za-z_$][\w$]*))?\s*(?:=[\s\S]*)?$/.exec(part)
260 if (entry?.[1] !== undefined) bind(entry[2] ?? entry[1], `${source}.${entry[1]}`)
261 }
262 }
263 return bound
264}
265
266/** Every named function and arrow, with the span its body takes. */
267function helpersOf(code: string): Helper[] {
268 const helpers: Helper[] = []
269 for (const one of code.matchAll(/(?<![\w$.])function\s*\*?\s*([A-Za-z_$][\w$]*)\s*\(/g)) {
270 const params = one.index + one[0].length - 1
271 const body = code.indexOf('{', matchClose(code, params))
272 if (body === -1) continue
273 const name = one[1] ?? ''
274 helpers.push({ name, at: one.index + one[0].indexOf(name, 8), from: body + 1, to: matchClose(code, body) })
275 }
276 for (const one of code.matchAll(/(?<![\w$.])(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*(?:async\s+)?/g)) {
277 let from = one.index + one[0].length
278 if (code.startsWith('function', from)) {
279 const params = code.indexOf('(', from)
280 const body = params === -1 ? -1 : code.indexOf('{', matchClose(code, params))
281 if (body === -1) continue
282 from = body
283 } else {
284 const params = code[from] === '(' ? matchClose(code, from) + 1 : (/^[A-Za-z_$][\w$]*/.exec(code.slice(from))?.[0].length ?? -1) + from
285 const arrow = /^\s*=>\s*/.exec(code.slice(params))
286 if (params < from || arrow === null) continue
287 from = params + arrow[0].length
288 }
289 const name = one[1] ?? ''
290 const at = one.index + one[0].indexOf(name, 3)
291 if (code[from] === '{') helpers.push({ name, at, from: from + 1, to: matchClose(code, from) })
292 else helpers.push({ name, at, from, to: expressionEnd(code, from) })
293 }
294 return helpers
295}
296
297/** The open brackets around `p`, innermost first. */
298function enclosing(code: string, p: number): number[] {
299 const stack: number[] = []
300 for (let i = 0; i < p; i += 1) {
301 const char = code[i] ?? ''
302 if (OPENERS.includes(char)) stack.push(i)
303 else if (CLOSERS.includes(char)) stack.pop()
304 }
305 return stack.reverse()
306}
307
308/** Which argument of the call opened at `open` holds `p`, from 0. */
309function argIndex(code: string, open: number, p: number): number {
310 let place = 0
311 for (let i = open + 1; i < p; i += 1) {
312 const char = code[i] ?? ''
313 if (OPENERS.includes(char)) {
314 const close = matchClose(code, i)
315 if (close >= p) break
316 i = close
317 } else if (char === ',') place += 1
318 }
319 return place
320}
321
322function argText(code: string, open: number, place: number): string {
323 return splitTop(code.slice(open + 1, matchClose(code, open)), ',')[place] ?? ''
324}
325
326/** The member chain a `.method` hangs from, e.g. `Array.from({ length: 3 })`. */
327function receiverBefore(code: string, dot: number): string {
328 let i = dot - 1
329 for (;;) {
330 while (i >= 0 && /\s/.test(code[i] ?? '')) i -= 1
331 const char = code[i] ?? ''
332 if (char === ')' || char === ']') i = matchOpen(code, i) - 1
333 else if (/[\w$]/.test(char)) {
334 while (i >= 0 && /[\w$]/.test(code[i] ?? '')) i -= 1
335 } else break
336 let j = i
337 while (j >= 0 && /\s/.test(code[j] ?? '')) j -= 1
338 const link = code[j] ?? ''
339 const next = code[i + 1] ?? ''
340 if (link === '.' || ((link === ')' || link === ']' || /[\w$]/.test(link)) && /[([]/.test(next))) {
341 i = link === '.' ? j - (code[j - 1] === '?' ? 2 : 1) : j
342 continue
343 }
344 break
345 }
346 return code.slice(i + 1, dot)
347}
348
349/** Where the expression starting at `from` ends: a `;`, a `,` or a closing bracket at its level, or a line that does not go on. */
350function expressionEnd(code: string, from: number): number {
351 for (let i = from; i < code.length; i += 1) {
352 const char = code[i] ?? ''
353 if (OPENERS.includes(char)) i = matchClose(code, i)
354 else if (CLOSERS.includes(char) || char === ';' || char === ',') return i
355 else if (char === '\n') {
356 const rest = code.slice(i).trimStart()
357 if (!/^([.?:+\-*/%&|^<>]|=[=>])/.test(rest) && code.slice(from, i).trim() !== '') return i
358 }
359 }
360 return code.length
361}
362
363function splitTop(text: string, by: string): string[] {
364 const parts: string[] = []
365 let depth = 0
366 let start = 0
367 for (let i = 0; i < text.length; i += 1) {
368 const char = text[i] ?? ''
369 if (OPENERS.includes(char)) depth += 1
370 else if (CLOSERS.includes(char)) depth -= 1
371 else if (char === by && depth === 0) {
372 parts.push(text.slice(start, i))
373 start = i + 1
374 }
375 }
376 const last = text.slice(start)
377 if (parts.length > 0 || last.trim() !== '') parts.push(last)
378 return parts
379}
380
381function matchClose(text: string, open: number): number {
382 let depth = 0
383 for (let i = open; i < text.length; i += 1) {
384 const char = text[i] ?? ''
385 if (OPENERS.includes(char)) depth += 1
386 else if (CLOSERS.includes(char)) {
387 depth -= 1
388 if (depth === 0) return i
389 }
390 }
391 return text.length
392}
393
394function matchOpen(text: string, close: number): number {
395 let depth = 0
396 for (let i = close; i >= 0; i -= 1) {
397 const char = text[i] ?? ''
398 if (CLOSERS.includes(char)) depth += 1
399 else if (OPENERS.includes(char)) {
400 depth -= 1
401 if (depth === 0) return i
402 }
403 }
404 return 0
405}
406
407/** An expression with `await`, a trailing `;` and wrapping parentheses left off. */
408function bare(text: string): string {
409 let t = text.trim().replace(/;$/, '').trim().replace(/^await\s+/, '')
410 while (t.startsWith('(') && matchClose(t, 0) === t.length - 1) t = t.slice(1, -1).trim()
411 return t
412}
413
414function isPath(text: string): boolean {
415 return /^[A-Za-z_$][\w$]*(?:\s*\??\.\s*[A-Za-z_$][\w$]*|\s*\[\s*\d+\s*\])*$/.test(text) && NAME.test(text.split(/[.[?\s]/)[0] ?? '')
416}
417
418function escape(text: string): string {
419 return text.replace(/[$]/g, '\\$')
420}
421
422/**
423 * The script with every string, template and regex body and every comment
424 * blanked (quotes and newlines kept), so brackets and names read as code.
425 */
426export function mask(src: string): string {
427 const out = src.split('')
428 const blank = (from: number, to: number) => {
429 for (let i = from; i < to; i += 1) if (out[i] !== '\n') out[i] = ' '
430 }
431 const quoted = (at: number): number => {
432 const quote = src[at]
433 for (let i = at + 1; i < src.length; i += 1) {
434 if (src[i] === '\\') i += 1
435 else if (src[i] === quote || (src[i] === '\n' && quote !== '`')) return i
436 }
437 return src.length
438 }
439 // A template's `${...}` holds code that may hold more templates.
440 const template = (at: number): number => {
441 for (let i = at + 1; i < src.length; i += 1) {
442 if (src[i] === '\\') i += 1
443 else if (src[i] === '`') return i
444 else if (src[i] === '$' && src[i + 1] === '{') i = code(i + 2, true)
445 }
446 return src.length
447 }
448 const code = (from: number, isNested: boolean): number => {
449 let depth = 0
450 let last = ''
451 for (let i = from; i < src.length; i += 1) {
452 const char = src[i] ?? ''
453 if (char === '/' && src[i + 1] === '/') {
454 const end = src.indexOf('\n', i)
455 blank(i, end === -1 ? src.length : end)
456 i = end === -1 ? src.length : end - 1
457 continue
458 }
459 if (char === '/' && src[i + 1] === '*') {
460 const end = src.indexOf('*/', i + 2)
461 blank(i, end === -1 ? src.length : end + 2)
462 i = end === -1 ? src.length : end + 1
463 continue
464 }
465 if (char === '"' || char === "'") {
466 const end = quoted(i)
467 blank(i + 1, end)
468 i = end
469 last = 'x'
470 continue
471 }
472 if (char === '`') {
473 const end = template(i)
474 blank(i + 1, end)
475 i = end
476 last = 'x'
477 continue
478 }
479 if (char === '/' && (last === '' || /[(,=:[!&|?{};+\-*%<>~^]/.test(last) || /(?<![\w$])(return|typeof|case|do|else|in|of|yield|await)$/.test(src.slice(from, i).trimEnd()))) {
480 let inClass = false
481 let end = i + 1
482 for (; end < src.length && src[end] !== '\n'; end += 1) {
483 if (src[end] === '\\') end += 1
484 else if (src[end] === '[') inClass = true
485 else if (src[end] === ']') inClass = false
486 else if (src[end] === '/' && !inClass) break
487 }
488 blank(i + 1, end)
489 i = end
490 last = 'x'
491 continue
492 }
493 if (isNested && char === '{') depth += 1
494 if (isNested && char === '}') {
495 if (depth === 0) return i
496 depth -= 1
497 }
498 if (!/\s/.test(char)) last = char
499 }
500 return src.length
501 }
502 code(0, false)
503 return out.join('')
504}
505types/index.d.ts 202 lines1/** A tool call in flight: how the detail tab names it, and the plain words the board shows. */
2export type RunningCall = { id: string; text: string; doing: string }
3
4export type Tokens = {
5 input: number
6 output: number
7 cacheRead: number
8 cacheWrite: number
9 requests: number
10}
11
12/** One line of a loop's TodoWrite list. */
13export type Todo = { content: string; status: 'pending' | 'in_progress' | 'completed'; activeForm?: string }
14
15/** What one loop (the main thread, a subagent, a teammate, a workflow agent) has done this session. */
16export type Activity = {
17 running: RunningCall[]
18 last?: string
19 /** The calls it made, newest last, as the detail tab lists them. */
20 recent?: string[]
21 tools: number
22 tokens: Tokens
23 firstSeen: number
24 /** The last time any of its events came. */
25 lastAt?: number
26 isBusy: boolean
27 endedAt?: number
28 todos?: Todo[]
29 /** What it was asked to do, in one line: an agent's spawn prompt, the main session's last request. */
30 task?: string
31 /** The agent type its SubagentStart named (`Explore`, `workflow-subagent`, ...). */
32 kind?: string
33 /** When its SubagentStop came, and what it last said. */
34 stoppedAt?: number
35 reply?: string
36}
37
38/** One task of the session's task list (TaskCreate / TaskUpdate, the team's shared list). */
39export type TaskItem = {
40 id: string
41 subject: string
42 status: 'pending' | 'in_progress' | 'completed'
43 owner?: string
44 activeForm?: string
45 /** The loop that created it: `main` or an agent id. */
46 by?: string
47 at: number
48}
49
50export type LimitSample = { at: number; percent: number }
51
52export type LimitWindow = {
53 kind: string
54 percentUsed: number
55 resetsAt?: string
56 samples: LimitSample[]
57}
58
59export type Meter = {
60 limits: LimitWindow[]
61 costUsd?: number
62 contextPercent?: number
63}
64
65export type TaskStatus = 'running' | 'done' | 'failed'
66
67/** One `agent()` call of a workflow run. */
68export type WorkflowTask = {
69 index: number
70 label: string
71 status: TaskStatus
72 agentId?: string
73 phase?: string
74 startedAt: number
75 endedAt?: number
76 tokens: Tokens
77}
78
79export type WorkflowStatus = 'running' | 'done' | 'failed' | 'stopped'
80
81/**
82 * How many agents a run's script starts, read from the script before it
83 * runs; `isOpen` when more hang on what its agents return.
84 */
85export type WorkflowPlan = { total: number; isOpen: boolean }
86
87/** One Workflow tool call and the agents its run started. */
88export type Workflow = {
89 /** The Workflow call's tool_use_id, or the run id when the call is unknown. */
90 key: string
91 runId?: string
92 name: string
93 description?: string
94 phases: string[]
95 plan?: WorkflowPlan
96 status: WorkflowStatus
97 startedAt: number
98 endedAt?: number
99 tasks: WorkflowTask[]
100}
101
102/** What a Workflow call said about itself before it ran. */
103export type WorkflowCall = {
104 name: string
105 description?: string
106 phases: string[]
107 plan?: WorkflowPlan
108 /** The call's `args`, which a plan read later from the run's saved script needs. */
109 args?: unknown
110 /** A hash of the script the call runs, to know its saved copy again. */
111 hash?: number
112}
113
114/** A detail tab: what it shows, by the board's item key, and its label. */
115export type Tab = { key: string; title: string }
116
117/** The pane's tabs: `active` is `all` for the board, else an open tab's key. */
118export type Tabs = { open: Tab[]; active: string }
119
120/** A hook or a drawing that failed: shown on the board, never swallowed. */
121export type Fault = { at: number; where: string; message: string }
122
123/** A model family the band picks by its alias, which names the family's latest model. */
124export type ModelFamily = 'fable' | 'opus' | 'sonnet' | 'haiku'
125
126export type EffortLevel = 'low' | 'medium' | 'high' | 'xhigh' | 'max'
127
128/** The session's model, effort, workflows and ultracode, as the band's buttons show them. */
129export type Controls = {
130 /** The main loop's model as `$.session.model()` answers it (`claude-opus-5-5`). */
131 model?: string
132 /** `auto` once `/effort auto` handed the effort back to the model's default. */
133 effort?: EffortLevel | 'auto'
134 /** The `/config` row `workflows` (Dynamic workflows); unknown until read. */
135 workflows?: boolean
136 /** Ultracode for this session, as `/effort ultracode on|off` last left it. */
137 ultracode: boolean
138 /** The button whose change is still on its way, drawn with an ellipsis. */
139 pending?: string
140}
141
142/** A Claude Code session running on this machine, as its registry file names it. */
143export type Peer = {
144 pid: number
145 sessionId: string
146 /** The folder it runs in, without a trailing separator. */
147 cwd: string
148 name?: string
149 /** `busy`, `idle`, or what else the registry says. */
150 status?: string
151 /** What it waits on, when it waits on the person. */
152 waitingFor?: string
153 kind?: string
154 entrypoint?: string
155 version?: string
156 startedAt?: number
157 /** When its status last changed. */
158 statusAt?: number
159}
160
161/** The sessions the registry lists, and which of them is this one. */
162export type Peers = {
163 list: Peer[]
164 /** This session's id; it keeps its row while the registry lags behind a /clear. */
165 mine?: string
166 /**
167 * This session's own process: what tells its row apart. Two processes can carry one session
168 * id (the same conversation resumed in another folder), so a row is known by its pid.
169 */
170 minePid?: number
171 /** This session's folder, the one the pane opens on. */
172 folder?: string
173 /** The person's home folder, which the pane writes as `~`. */
174 homeDir?: string
175 readAt?: number
176 error?: string
177}
178
179/**
180 * Which sessions the pane lists: the folder level (this session's folder, or the one picked
181 * from the view above) or every session on the machine; `ending` a session whose end waits on a second press.
182 */
183export type Scope = { level: 'folder' | 'all'; folder?: string; ending?: number }
184
185declare module 'claude-code' {
186 interface PluginState {
187 'session-dashboard': {
188 peers: Peers
189 scope: Scope
190 activity: Record<string, Activity>
191 meter: Meter
192 tick: number
193 calls: Record<string, WorkflowCall>
194 workflows: Workflow[]
195 tasks: Record<string, TaskItem>
196 tabs: Tabs
197 faults: Fault[]
198 controls: Controls
199 }
200 }
201}
202