霧読み:すべてのターミナルの会話・道具・使用量を、localhost のブラウザ画面にまとめて映す

Claude Code を何本ものターミナルで動かしているときに、すべての会話・道具の呼び出し・使用量を、ブラウザの 1 画面(http://127.0.0.1:4317)にまとめて映す Mod です。
詳しい使い方は取扱説明書(hub/guide.html。画面の歯車(設定)の「使い方」や http://127.0.0.1:4317/guide からも開けます)にまとめています。画面には説明の文をほとんど出さず、操作のしかたは取扱説明書にまとめています。
/resume・/model・/effort は画面に選ぶ画面が開きます。/resume はそのフォルダの前の会話を一覧から選んで再開し(チャンネルは終わらずに続き、その会話の最後の 20 往復までが出ます)、モデルと effort はチャンネルの見出しからも切り替えられます。/context などの結果や、ターミナルで打ったコマンドの結果の 1 行も会話に出ますclaude --resume で戻れます.claude にあるスキルとエージェントは読み込んだときに、~/.claude・プラグイン・組み込みのものは呼び出されたときに加わります.claude/skills)とグローバル(~/.claude/skills・プラグイン・組み込み)に分けてタブでFogcast ch.1 · ctx 41% · 5h 44% → 予報 71% · 7d 68% · $1.23 のように出ますzip で受け取ったときは、先に解凍してホームフォルダに置きます(marketplace add はフォルダを指定します)。
unzip ~/Downloads/fogcast-0.6.3.zip -d ~ # ~/fogcast ができます
まず試す(そのセッションだけ):
claude --plugin-dir /path/to/fogcast
ずっと使う(このフォルダをマーケットプレイスとして追加):
claude plugin marketplace add /path/to/fogcast
claude plugin install fogcast@fogcast
入れたあとは、動いている claude を一度終了して起動し直します。~/fogcast は起動のたびに読み込まれるので、消したり移したりしないでください。
GitHub に置いた場合は、Claude Code のプロンプトで:
/plugin install fogcast --marketplace <owner>/<repo>
Claude Code を WSL の中で動かしているなら、すべて WSL のターミナルで行います。置き場所は WSL の中のホームフォルダ(/home/<WSLのユーザー名>/fogcast)で、Windows 側(C:\Users\…)には置きません。Node.js 18 以上も WSL の中に必要です。
unzip "/mnt/c/Users/<Windowsのユーザー名>/Downloads/fogcast-0.6.3.zip" -d ~
画面は Windows のブラウザで見ます。/fog は Windows の既定のブラウザを開きます(WSL2 は localhost を Windows に転送するので、http://127.0.0.1:4317 で届きます)。
claude を起動します。最初のターミナルが受け皿(localhost:4317)を裏で起動し、以降のターミナルはそこにつながります。ステータスラインに Fogcast ch.1 … と出ればつながっています。/fog を実行すると、ブラウザで画面が開きます(鍵つきの URL。2 回目からは http://127.0.0.1:4317 だけで開けます)。/fog の結果の下には鍵つきの URL も 1 行で出るので、開かなかったときはそれを押します(あなたの画面にだけ出て、Claude が読む会話には入りません)。claude を起動するだけです。同じリポジトリで並行して作業するなら、git worktree で作業フォルダを分けるとファイルの変更がぶつかりません。キー操作:0〜9 でチャンネル切り替え、/ でコマンドの一覧。カードの画面は ↑ ↓・ホイール・ドラッグで回し、Esc で戻ります。
VS Code のターミナルで起動した claude は VS Code とつながり、依頼を受けるたびに VS Code が(隠していても)ターミナルを表に出します。Claude Code の VS Code 連携の動きなので、Fogcast の側からは止められません。画面だけで使うときに気になるなら、CLAUDE_CODE_AUTO_CONNECT_IDE=false claude で起動します(そのあいだは VS Code での差分の表示や、選んでいる行の受け渡しが使えません)。
1234-5678 の形、5 分間有効)が出ます。入力欄の下のステータスラインにも出ます。それを画面に入力すると、そのブラウザだけが承認できるようになります。心当たりのない合言葉は、枠の「取り消す」で無効にできます。127.0.0.1 だけで待ち受けます。ほかのホスト名やほかのサイトからの呼び出しは断ります(DNS リバインディング対策を含む)。~/.fogcast/token の鍵で受け皿とやりとりします(本人だけが読めるファイルです)。鍵は URL の # の後ろで画面に渡すので、サーバーのログや Referer には残りません。/fog の結果(モデルが読む 1 行)には鍵を含めません。鍵つきの URL は、その行の下に画面の表示としてだけ出し、会話の記録には残しません。Mod は会話や道具の結果を書き換えず、毎回のコンテキストにも何も足しません(claude plugin details の Always-on は ~0 tok)。増えるのは、コマンド一覧に /fog が 1 行加わることと、/fog を実行したときの 1 行の結果だけです。
| 名前 | 既定 | 内容 |
|---|---|---|
FOGCAST_PORT | 4317 | 受け皿のポート |
FOGCAST_NODE | node | Node.js の場所(PATH にないとき) |
FOGCAST_HOME | ~/.fogcast | 鍵と記録の置き場所 |
FOGCAST_HEADLESS | なし | 1 にすると claude -p の実行も映します |
unzip -o ~/Downloads/fogcast-<版>.zip -d ~ # ~/fogcast を上書き
claude plugin update fogcast@fogcast
そのあと各ターミナルの claude を起動し直します。前の版の受け皿が動いていたら、新しい版のターミナルが止めて、新しい受け皿を起動します。
ターミナルも画面もつながっていない状態が 20 分続くと、自動で終了します。すぐ止めたいときは:
node /path/to/fogcast/hub/hub.mjs --stop
~/.fogcast/ に、鍵(token)、state.json(コミュの使用回数と最近の使用、使用枠の読み取り、日ごとの記録(ターン数・トークン・料金、チャンネル名ごとの内訳、使ったものの回数。35 日ぶん)、ステータス(EXP・能力・記録)、終わったセッションの再開 ID と最初の依頼の書き出し)、hub.log、uploads/(画面で添付した画像。7 日で消えます)を置きます。会話の本文は受け皿のメモリにだけ置き、ファイルには書きません。Claude Code の会話のファイル(~/.claude/projects の中)は、/resume の一覧を開いたときと会話を再開したときにだけ、そのチャンネルのフォルダの分を読みます。
| ファイル | 役割 |
|---|---|
hooks/register.ts | Mod 本体。会話・道具・使用量を受け皿へ送り、画面からの操作をターミナルで実行します |
hooks/shape.ts | 道具の呼び出しや結果を 1 行にまとめる整形 |
hub/hub.mjs | 受け皿(localhost のサーバー)。Node.js だけで動きます |
hub/ui.html | 画面(ui-src/ から組み立てたもの) |
hub/guide.html | 取扱説明書(ui-src/guide.html から組み立てたもの。/guide で開けます) |
ui-src/ | 画面の部品と build.sh。demo.html は受け皿なしで動くデモです |
test/ | 受け皿のテスト、2 つのターミナルを流すシミュレーター |
claude plugin validate .
claude plugin test . # Mod のテスト
node --test test/hub.test.mjs # 受け皿のテスト
node test/simulate.mjs # 受け皿に 2 つのターミナルを流して画面を試すhooks/register.ts 989 lines1// Fogcast (霧読み): reports this terminal's conversation, tool calls and usage to the
2// localhost hub, and carries out what the Fogcast screen asks of this terminal.
3//
4// Nothing here adds to the model's context: the hooks watch and pass everything on as
5// it was. The one exception is /fog's one-line answer, which says where the screen is.
6import type { Register } from 'claude-code'
7import { linkFor, verb, summarize, outline, fileChange, todosOf, textOf, srcLabel, statusLine, older, isLocalSrc, midTurnText, clip, str, keepText, questionsOf, answersFor, commandRow, effortLevels, modelKey, settingOf, effortSet, mentionsOf, mentionCandidates, numbered, cutText, type Reading } from './shape'
8
9// eslint-disable-next-line @typescript-eslint/no-explicit-any
10type Any = any
11
12/** Keep in step with .claude-plugin/plugin.json and hub/hub.mjs (a test checks). */
13export const VERSION = '0.6.3'
14const DEFAULT_PORT = 4317
15/** Claude Code drops a toast asked to stay longer than this (0.1.0 lost its pairing notice that way). */
16const TOAST_MAX = 60000
17const SYNC_MS = 700
18const RELOADS = new Set(['reload-skills', 'reload-plugins', 'mcp', 'plugin', 'agents', 'skills', 'memory', 'add-dir'])
19const SKIP_CMDS = new Set(['compact', 'clear', 'exit', 'quit', 'fog'])
20
21function rid(): string {
22 try { const b = new Uint8Array(8); crypto.getRandomValues(b); return Array.from(b, x => x.toString(16).padStart(2, '0')).join('') }
23 catch { return (Math.random().toString(16).slice(2) + Math.random().toString(16).slice(2)).slice(0, 16) }
24}
25/** This terminal, for as long as the module is loaded: kept across /clear and resumes. */
26const CHAN = rid()
27
28/** A command run here: its row on the screen is told once, unless what it did is told instead (a turn, a resume, a model switch). */
29type CmdRun = { id: string; name: string; args: string; via?: 'screen'; text: string; t: number; told: boolean; settled: boolean; shown: boolean }
30
31const st = {
32 on: false,
33 port: DEFAULT_PORT, base: `http://127.0.0.1:${DEFAULT_PORT}`, dir: '', token: '',
34 ready: false, lastTry: 0, startedHubAt: 0, warned: new Set<string>(),
35 num: 0, approvals: false, forecast: null as Any,
36 measure: null as Any, limits: [] as Reading[], ctx: undefined as number | undefined, usd: undefined as number | undefined,
37 sid: '', cwd: '', model: '', branch: '', startedAt: 0,
38 busy: false, ticks: 0, lastLine: '', turnsDone: 0,
39 turnId: '', turnText: '', turnHasOutput: false,
40 midTyped: [] as string[], // typed at the terminal while a turn ran, until it reaches the model
41 lastCmd: null as null | { name: string; args: string; t: number; screen?: boolean },
42 /** the last command run here, until its row is told: the line it prints joins it, and one that starts a turn is told by the turn */
43 cmdRun: null as null | CmdRun,
44 afterTurn: [] as Array<() => void>,
45 tools: new Map<string, { name: string; input: string; agent?: string; waiting?: boolean }>(),
46 ceil: new Set<string>(),
47 agents: new Map<string, string>(),
48 recentSkill: null as null | { name: string; t: number },
49 mode: '',
50 band: null as null | { id: string; tool: string; input: string; until: number },
51 /** the code a browser must type to approve from the screen; shown above the prompt and in the status line, never to the model */
52 pair: null as null | { code: string; until: number },
53 replacedAt: 0,
54 /** where each loaded skill and agent comes from, and what it costs each request: given to its コミュ card when it is first used */
55 srcOf: new Map<string, { src: string; dt?: number; desc?: string }>(),
56 /** the address with its key, drawn under /fog's row when no browser could be opened (the stored row, which the model reads, never has it) */
57 fogShow: '',
58 /** prompts the screen sent, until their turn starts: the hub's id rides along so the screen can swap its pending bubble for the turn */
59 submitted: [] as Array<{ text: string; cid: string; files?: Attached[]; imgs?: string[] }>,
60 /** images the person attached on the screen, kept where Fogcast keeps them: the files Claude may read without a dialog */
61 imgOk: new Set<string>(),
62 /** each command's argument hint (`[model]`), as the engine lists it for the typeahead */
63 hints: new Map<string, string>(),
64 /** what each agent type is for (its definition's description), as the engine offers it to the model */
65 agentDesc: new Map<string, string>(),
66 /** the prompt box's dim suggestion for the next prompt (Tab takes it), while it stands */
67 suggest: '',
68 /** questions Claude is asking (AskUserQuestion): an answer from the screen settles the one waiting here */
69 qWait: new Map<string, (sent: unknown) => void>(),
70 /** this conversation's file (the engine's transcript): its folder holds the project's other conversations, which /resume can return to */
71 tp: '',
72 /** the effort as it is set (/effort, or what the settings keep for the model); a request's own level until one is known */
73 effort: '',
74 /** the level the last request went with: what `auto` came to, for one */
75 effortUsed: '',
76 /** the model choices last told to the hub, with the one /config holds (the picker marks it) */
77 modelsSent: '',
78 /** the conversation a /resume in this terminal is leaving, until the one it returns to has started */
79 resumeFrom: '',
80 /** the command the conversation's last command row named: what its printed line belongs to */
81 appendCmd: '',
82 /** built-in commands that turned out to be skills (they start a turn) */
83 skillRan: new Set<string>(),
84 /** commands the typeahead leaves out (`isHidden`): the screen's list does too */
85 hiddenCmds: new Set<string>(),
86 /** when the screen last asked for a model: the switch that follows is told as the screen's */
87 modelAsked: 0,
88 /** where Claude Code keeps its conversations (CLAUDE_CONFIG_DIR, else ~/.claude): the resume list's fallback */
89 cfg: '',
90 /** a screen is open: what it asks for is picked up at every tick */
91 watched: false,
92}
93const outbox: Any[] = []
94const ring: Any[] = [] // what is replayed if the hub restarts
95
96function push(ev: Any) {
97 if (!st.on) return
98 ev.t = ev.t ?? Date.now()
99 outbox.push(ev)
100 if (outbox.length > 2000) outbox.splice(0, outbox.length - 2000)
101 if (ev.k !== 'measure' && ev.k !== 'mode' && ev.k !== 'suggest') { ring.push(ev); if (ring.length > 500) ring.splice(0, ring.length - 500) }
102}
103
104/* ---------------- the hub ---------------- */
105async function get($: Any, path: string): Promise<Any> {
106 try { const r = await $.http.fetch(st.base + path); return r.ok ? JSON.parse(r.text || 'null') : null } catch { return null }
107}
108async function post($: Any, path: string, body: unknown): Promise<Any> {
109 if (!st.token) return null
110 try {
111 const r = await $.http.fetch(st.base + path, { method: 'POST', headers: { 'content-type': 'application/json', 'x-fogcast-token': st.token }, body: JSON.stringify(body) })
112 if (r.status === 401) { st.token = ''; st.ready = false; return null }
113 if (r.status >= 500) return null
114 return JSON.parse(r.text || 'null')
115 } catch { return null }
116}
117function warnOnce($: Any, key: string, text: string) {
118 if (st.warned.has(key)) return
119 st.warned.add(key)
120 try { $.ui.toast(text, { timeoutMs: 15000 }) } catch {}
121}
122async function paths($: Any) {
123 const port = Number(await $.env.get('FOGCAST_PORT')) || DEFAULT_PORT
124 st.port = port; st.base = `http://127.0.0.1:${port}`
125 const custom = await $.env.get('FOGCAST_HOME')
126 const home = (await $.env.get('HOME')) || (await $.env.get('USERPROFILE')) || ''
127 st.dir = custom || (home ? `${home}/.fogcast` : '')
128 st.cfg = (await $.env.get('CLAUDE_CONFIG_DIR')) || (home ? `${home}/.claude` : '')
129}
130async function readToken($: Any): Promise<string> {
131 if (!st.dir) return ''
132 try { return String(await $.fs.read(`${st.dir}/token`)).trim() } catch { return '' }
133}
134/** The hub this mod talks to: same port and home folder, whatever the host's environment says. */
135function hubEnv(): Record<string, string> {
136 return st.dir ? { FOGCAST_PORT: String(st.port), FOGCAST_HOME: st.dir } : { FOGCAST_PORT: String(st.port) }
137}
138async function startHub($: Any) {
139 st.startedHubAt = Date.now()
140 const node = (await $.env.get('FOGCAST_NODE')) || 'node'
141 try {
142 const r = await $.process.run([node, `${$.plugin.root}/hub/hub.mjs`, '--daemon'], { timeoutMs: 15000, env: hubEnv() })
143 if (r.exitCode !== 0) warnOnce($, 'start', `Fogcast: 受け皿を起動できませんでした(${clip(r.stderr || `終了コード ${r.exitCode}`, 120)})`)
144 } catch {
145 warnOnce($, 'node', 'Fogcast: Node.js が見つからないため、受け皿(localhost の画面)を起動できませんでした。Node.js 18 以上を入れるか、環境変数 FOGCAST_NODE に node のパスを指定してください。')
146 }
147}
148/** After an update, a hub of an older version may still be running: it is stopped once, and this mod starts its own. */
149async function stopHub($: Any) {
150 const node = (await $.env.get('FOGCAST_NODE')) || 'node'
151 try { await $.process.run([node, `${$.plugin.root}/hub/hub.mjs`, '--stop'], { timeoutMs: 10000, env: hubEnv() }) } catch {}
152}
153async function branch($: Any): Promise<string> {
154 try { const r = await $.process.run(['git', 'rev-parse', '--abbrev-ref', 'HEAD'], { timeoutMs: 4000 }); return r.exitCode === 0 ? r.stdout.trim() : '' } catch { return '' }
155}
156/**
157 * Skills only the person can run (`disable-model-invocation: true`): Claude is never told of them, so they
158 * cost nothing each turn and /context leaves them out. The command list has them, and the project's own
159 * folders say which are its; the rest are everywhere's (~/.claude).
160 */
161async function manualSkills($: Any, shown: Set<string>, list: Any[]): Promise<Any[]> {
162 try {
163 const own = new Set<string>()
164 try { for (const e of await $.fs.list('.claude/skills')) if (e.kind !== 'file') own.add(e.name) } catch {}
165 try { for (const e of await $.fs.list('.claude/commands')) if (e.kind === 'file' && e.name.endsWith('.md')) own.add(e.name.slice(0, -3)) } catch {}
166 return list.filter((c: Any) => c.source === 'user' && !shown.has(c.name))
167 .map((c: Any) => ({ n: c.name, src: own.has(c.name) ? '.claude' : '~/.claude', dt: 0, manual: true }))
168 } catch { return [] }
169}
170/**
171 * Each skill's description (its SKILL.md `description`), from the command list: read here, never sent to the
172 * model by Fogcast. A name listed twice (a skill of the person's and a built-in) takes the one of its own source.
173 */
174function descOf(list: Any[]): (name: string, builtin?: boolean) => string {
175 const own = new Map<string, string>(), core = new Map<string, string>()
176 for (const c of list) if (c && typeof c.name === 'string' && typeof c.description === 'string' && c.description.trim()) (c.source === 'builtin' ? core : own).set(c.name, c.description)
177 return (name, builtin) => keepText((builtin ? core.get(name) ?? own.get(name) : own.get(name) ?? core.get(name)) ?? '', 1500)
178}
179async function commandList($: Any): Promise<Any[]> { try { const l = await $.command.list(); return Array.isArray(l) ? l : [] } catch { return [] } }
180/** What the session loaded at start, as /context counts it (estimated locally: no request is sent). */
181async function loaded($: Any, list: Any[]): Promise<Any> {
182 try {
183 const u = await $.session.usage({ breakdown: 'summary' })
184 st.startedAt = u.startedAt
185 const b = u.context.breakdown
186 if (!b) return {}
187 const desc = descOf(list)
188 const listed = (b.skills?.skillFrontmatter ?? []).map((s: Any) => ({ n: s.name, src: srcLabel(s.source, s.pluginName), dt: s.tokens, desc: desc(s.name, /built-?in|bundled/.test(String(s.source))) }))
189 const skills = [...listed, ...(await manualSkills($, new Set(listed.map((s: Any) => s.n)), list)).map((s: Any) => ({ ...s, desc: desc(s.n) }))]
190 const servers = new Map<string, number>()
191 for (const t of b.mcpTools ?? []) servers.set(t.serverName, (servers.get(t.serverName) ?? 0) + (t.isLoaded ? t.tokens : 0))
192 const agents = (b.agents ?? []).map((a: Any) => ({ n: a.agentType, src: srcLabel(a.source), dt: a.tokens, desc: st.agentDesc.get(a.agentType) ?? '' }))
193 const memory = (b.memoryFiles ?? []).map((m: Any) => ({ path: m.path, type: m.type, dt: m.tokens }))
194 st.srcOf = new Map([...skills.map((s: Any) => [`skill:${s.n}`, { src: s.src, dt: s.dt, desc: s.desc }]), ...agents.map((a: Any) => [`agent:${a.n}`, { src: a.src, dt: a.dt, desc: a.desc }])] as Any)
195 return {
196 loaded: {
197 md: memory.length > 0, memory, skills: skills.map(({ desc: _d, ...s }: Any) => s), agents: agents.map(({ desc: _d, ...a }: Any) => a), mcp: [...servers.keys()], mods: ['fogcast'],
198 totalSkills: b.skills?.totalSkills ?? skills.length, includedSkills: b.skills?.includedSkills ?? skills.length,
199 window: b.rawMaxTokens, autoCompactAt: b.autoCompactThreshold ?? null,
200 },
201 breakdown: (b.categories ?? []).filter((c: Any) => c.kind === 'used' && c.tokens > 0).map((c: Any) => ({ n: c.name, v: c.tokens })),
202 // コミュ: a project's own skills and agents join when loaded; everywhere's join when first called
203 links: [
204 ...skills.filter((s: Any) => isLocalSrc(s.src)).map((s: Any) => ({ id: `skill:${s.n}`, kind: 'skill', label: s.n, src: s.src, dt: s.dt, desc: s.desc || undefined })),
205 ...agents.filter((a: Any) => isLocalSrc(a.src)).map((a: Any) => ({ id: `agent:${a.n}`, kind: 'agent', label: a.n, src: a.src, dt: a.dt, desc: a.desc || undefined })),
206 ...[...servers].map(([n, dt]) => ({ id: `mcp:${n}`, kind: 'mcp', label: n, src: 'MCP', dt })),
207 ],
208 }
209 } catch { return {} }
210}
211/**
212 * The commands for the screen's "/" list: one line each, with the hint the terminal draws after the name.
213 * A skill is marked: run from the screen it starts a turn, even one Claude Code lists as built-in.
214 */
215function commands(list: Any[]): Any[] {
216 return list.map((c: Any) => ({
217 name: c.name, description: clip(c.description || '', 160), source: c.source, plugin: c.plugin, hint: st.hints.get(c.name) || undefined,
218 ...(st.srcOf.has(`skill:${c.name}`) || st.skillRan.has(c.name) ? { skill: true } : {}),
219 ...(st.hiddenCmds.has(c.name) ? { hidden: true } : {}),
220 }))
221}
222/** The models the /config Model row offers, and the one chosen there: what the screen's model picker lists. */
223async function modelChoices($: Any): Promise<Any> {
224 try {
225 const row = ((await $.config.list()) || []).find((x: Any) => x && x.key === 'model')
226 if (!row) return null
227 const options = (Array.isArray(row.options) ? row.options : []).filter((o: unknown) => typeof o === 'string').slice(0, 40)
228 return { options, value: settingOf(row.value, options) }
229 } catch { return null }
230}
231/** The model setting as /config holds it now, told to the hub when it changed: after the screen's pick, /model, /config, a switch. */
232async function syncModels($: Any) {
233 if (!st.on) return
234 const m = await modelChoices($); if (!m) return
235 const k = JSON.stringify(m); if (k === st.modelsSent) return
236 st.modelsSent = k; push({ k: 'models', ...m })
237}
238/** The effort the settings keep for a model (what `/effort` saved as its default): shown until a request says otherwise. */
239async function savedEffort($: Any, model: string): Promise<string> {
240 try { const v = (await $.settings.read())?.modelSettings?.[modelKey(model)]?.effortLevel; return typeof v === 'string' ? v : '' } catch { return '' }
241}
242/** The effort as now set, told to the hub when it changed. */
243function effortIs(level: string) { if (level && level !== st.effort) { st.effort = level; push({ k: 'info', effort: level }) } }
244const dirOf = (p: string) => p.replace(/[\\/][^\\/]*$/, '')
245async function hello($: Any) {
246 const list = await commandList($)
247 const [sid, cwd, model, version, info, br, models] = await Promise.all([
248 $.session.id().catch(() => ''), $.session.cwd().catch(() => st.cwd), $.session.model().catch(() => ''),
249 $.session.version().catch(() => null), loaded($, list), branch($), modelChoices($),
250 ])
251 const cmds = commands(list)
252 st.sid = sid; st.cwd = cwd; st.model = model; st.branch = br; st.modelsSent = models ? JSON.stringify(models) : ''
253 if (!st.effort) st.effort = await savedEffort($, model)
254 return {
255 chan: CHAN, mod: VERSION, sid, cwd, branch: br, model, version: version?.version ?? '', startedAt: st.startedAt || Date.now(), commands: cmds, ...info,
256 tp: st.tp, tdir: st.tp ? dirOf(st.tp) : '', cfg: st.cfg, effort: st.effort, effortUsed: st.effortUsed, models, efforts: effortLevels(st.hints.get('effort')), replay: ring,
257 }
258}
259async function connect($: Any): Promise<boolean> {
260 st.lastTry = Date.now()
261 const h = await get($, '/api/health')
262 if (!h) { if (Date.now() - st.startedHubAt > 20000) await startHub($); return false }
263 if (h.app !== 'fogcast') { warnOnce($, 'port', `Fogcast: ポート ${st.port} は別のプログラムが使っています。環境変数 FOGCAST_PORT で別の番号にできます。`); return false }
264 if (older(h.version, VERSION) && Date.now() - st.replacedAt > 60000) {
265 // an update left the older hub running: stop it, give it a moment to let go of the port, start this version's
266 st.replacedAt = Date.now()
267 await stopHub($)
268 await $.clock.sleep(800)
269 await startHub($)
270 return false
271 }
272 if (!st.token) st.token = await readToken($)
273 if (!st.token) return false
274 const r = await post($, '/api/mod/hello', await hello($))
275 if (!r || !r.ok) return false
276 st.ready = true; st.num = r.num; st.approvals = !!r.approvals?.on; st.forecast = r.forecast ?? null
277 outbox.length = 0 // the replay carried them
278 if (st.measure) push({ ...st.measure, t: Date.now() })
279 applyPair($, r.pair)
280 line($)
281 return true
282}
283/** The hub hands every terminal the code while a browser is being paired, and null once it is used, taken back or out of time. */
284function applyPair($: Any, p: Any) {
285 const next = p && typeof p.code === 'string' && Number(p.exp) > Date.now() ? { code: p.code, until: Number(p.exp) } : null
286 if ((next?.code ?? null) === (st.pair?.code ?? null)) { if (next && st.pair) st.pair.until = next.until; return }
287 st.pair = next
288 // the notice only points at the band: a code in a notice could outlive the code itself
289 if (next) { try { $.ui.toast('Fogcast: ブラウザ承認の合言葉を、入力欄のすぐ上に出しました', { timeoutMs: 12000 }) } catch {} }
290 try { $.ui.invalidate('ui.render') } catch {}
291 line($)
292}
293function pairLeft(): string {
294 const s = st.pair ? Math.max(0, Math.round((st.pair.until - Date.now()) / 1000)) : 0
295 return s > 60 ? `あと約 ${Math.ceil(s / 60)} 分` : `あと ${s} 秒`
296}
297async function reload($: Any) {
298 const list = await commandList($)
299 push({ k: 'loaded', ...await loaded($, list), commands: commands(list) })
300}
301function line($: Any) {
302 if (!st.on) return
303 const pair = st.pair && st.pair.until > Date.now() ? st.pair.code : undefined
304 const text = statusLine({ num: st.num, ready: st.ready, ctx: st.ctx, limits: st.limits, usd: st.usd, forecast: st.forecast, pair })
305 if (text === st.lastLine) return
306 st.lastLine = text
307 try { $.ui.status(text) } catch {}
308}
309async function tick($: Any) {
310 if (st.busy) return
311 st.busy = true
312 try {
313 st.ticks++
314 if (st.pair && st.pair.until <= Date.now()) applyPair($, null) // out of time, whether or not the hub said so yet
315 if (!st.ready) { if (Date.now() - st.lastTry > 2000) { await connect($); line($) } return }
316 if (st.ticks % 8 === 0) {
317 const [sid, model] = await Promise.all([$.session.id().catch(() => st.sid), $.session.model().catch(() => st.model)])
318 if (sid !== st.sid || model !== st.model) { st.sid = sid; st.model = model; push({ k: 'info', sid, model }) }
319 if (st.ticks % 24 === 0) await syncModels($)
320 }
321 if ((st.band || st.pair) && st.ticks % 2 === 0) $.ui.invalidate('ui.render') // the band's countdown
322 if (!outbox.length && !st.turnId && !st.watched && st.ticks % 3 !== 0) return // quiet: every ~2 s is enough, unless a screen is open
323 const events = outbox.splice(0, 400)
324 const r = await post($, '/api/mod/sync', { chan: CHAN, events })
325 if (!r) { outbox.unshift(...events); st.ready = false; line($); return }
326 if (r.ok === false) { st.ready = false; return } // the hub restarted: say hello again, with the replay
327 st.num = r.num ?? st.num; st.approvals = !!r.approvals?.on; st.forecast = r.forecast ?? null; st.watched = !!r.watch
328 applyPair($, r.pair)
329 for (const c of r.commands ?? []) perform($, c)
330 line($)
331 } catch {} finally { st.busy = false }
332}
333
334/* ---------------- what the screen asks of this terminal ---------------- */
335function perform($: Any, c: Any) {
336 const fail = (err: unknown) => push({ k: 'did', cid: c.id, what: c.type, ok: false, error: clip(String((err as Any)?.message ?? err), 200) })
337 try {
338 if (c.type === 'prompt') {
339 const text = String(c.text), entry: { text: string; cid: string; files?: Attached[]; imgs?: string[] } = { text, cid: String(c.id) }
340 const imgs: Pic[] = (Array.isArray(c.imgs) ? c.imgs : []).slice(0, 5).map((x: Any) => ({ id: String(x?.id ?? ''), path: String(x?.path ?? '') })).filter((x: Pic) => /^[0-9a-f]{16}$/.test(x.id) && x.path)
341 if (imgs.length) entry.imgs = imgs.map(x => x.id)
342 st.submitted.push(entry); if (st.submitted.length > 8) st.submitted.shift()
343 if (!mentionsOf(text).length && !imgs.length) void $.prompt.submit({ text, asUser: true }).catch(fail) // starts once the session is idle
344 // with files named by @: while a turn runs, the files and the prompt wait for it together, so the row lands right before the prompt
345 else if (st.turnId) st.afterTurn.push(() => { void sendPrompt($, text, entry, imgs).catch(fail) })
346 else void sendPrompt($, text, entry, imgs).catch(fail)
347 } else if (c.type === 'answer') {
348 st.qWait.get(String(c.qid))?.(c.answers) // a question still open here takes it
349 } else if (c.type === 'command') {
350 // like a command typed while Claude works, it waits for the turn to end (the screen says it is booked)
351 const go = () => { void runCommand($, String(c.name), String(c.args || '')).catch(fail) }
352 if (st.turnId) st.afterTurn.push(go); else go()
353 } else if (c.type === 'stop') {
354 if (st.turnId) void $.turn.abort({ turnId: st.turnId }).catch(fail)
355 } else if (c.type === 'compact') {
356 // this module's own compaction runs through every hook but its own (session.compact): it is told here.
357 // A hook that vetoed it says why in the terminal; the screen hears it did not happen
358 const go = () => {
359 push({ k: 'compacting', trigger: 'manual', via: 'screen' })
360 void $.session.compact(c.instructions ? { instructions: String(c.instructions) } : undefined).then((r: Any) => {
361 if (r?.skip) { push({ k: 'compactOff', reason: clip(String(r.skip), 200) }); push({ k: 'did', cid: c.id, what: 'compact', ok: false, error: clip(String(r.skip), 200) }) }
362 else push({ k: 'compact', trigger: 'manual', via: 'screen' })
363 }).catch((err: unknown) => { push({ k: 'compactOff', reason: clip(String((err as Any)?.message ?? err), 200) }); fail(err) })
364 }
365 if (st.turnId) st.afterTurn.push(go); else go()
366 } else if (c.type === 'toast') {
367 $.ui.toast(String(c.text || ''), { timeoutMs: Math.min(TOAST_MAX, Math.max(1, Math.round(Number(c.timeoutMs) || 15000))) })
368 } else if (c.type === 'resume') {
369 // a conversation of this project, by its id: the terminal switches to it without its own list, once the turn is over
370 const go = () => { void runCommand($, 'resume', String(c.sid)).catch(fail) }
371 if (st.turnId) st.afterTurn.push(go); else go()
372 } else if (c.type === 'model') {
373 // through the /config Model row: /model would stop at the terminal's "switch model?" question mid-conversation.
374 // Like /model, it waits for a running turn to end
375 // the switch it brings is told as the screen's (PostModelSwitch); a pick of the model already in use brings none,
376 // so the mark is let go a moment after the write, and the setting itself is read back from /config
377 const go = () => {
378 st.modelAsked = Date.now()
379 void $.config.set({ key: 'model', value: String(c.value) }).then((r: Any) => { if (r?.deny) fail(r.deny) }).catch(fail)
380 .finally(() => { $.clock.after(1500, () => { st.modelAsked = 0 }); void syncModels($) })
381 }
382 if (st.turnId) st.afterTurn.push(go); else go()
383 } else if (c.type === 'effort') {
384 const go = () => { void runCommand($, 'effort', String(c.value)).catch(fail) }
385 if (st.turnId) st.afterTurn.push(go); else go()
386 }
387 } catch (err) { fail(err) }
388}
389
390/* ---------------- commands: the row each run gets on the screen ---------------- */
391// This module's own `$.command.run` does not pass through its command.run hook (no hook runs under its own call),
392// so a run from the screen is followed here; one typed in the terminal, in the hook. Both end in cmdDone.
393async function runCommand($: Any, name: string, args: string) {
394 st.lastCmd = { name, args, t: Date.now(), screen: true }
395 const run = cmdBegin(name, args, true)
396 const r = await $.command.run({ command: name, args })
397 if (typeof r?.text === 'string' && !st.turnId && st.lastCmd?.name === name) st.lastCmd = null
398 cmdDone($, run, r)
399 return r
400}
401function cmdBegin(name: string, args: string, screen: boolean): CmdRun {
402 const run: CmdRun = { id: rid(), name, args, via: screen ? 'screen' : undefined, text: '', t: Date.now(), told: false, settled: false, shown: false }
403 st.cmdRun = run
404 return run
405}
406/** What the command answered: a moment later its row is told, with the line it printed if that came by then. */
407function cmdDone($: Any, run: CmdRun, r: Any) {
408 // most commands hand back no text: their printed line comes as a row of the conversation (session.append).
409 // /context's grid is drawn for the terminal; the table it leaves for the model reads better here
410 const text = typeof r?.text === 'string' ? r.text : run.name === 'context' && Array.isArray(r?.context) ? r.context.join('\n\n') : ''
411 if (text.trim() && !run.text) run.text = text
412 if (run.name === 'effort') effortIs(effortSet(text))
413 if (run.name === 'model' || run.name === 'config') $.clock.after(400, () => { void syncModels($) })
414 if (RELOADS.has(run.name)) void reload($)
415 $.clock.after(800, () => {
416 run.settled = true
417 // it started no turn: the next prompt is the person's own, not this command's (a prompt typed right after /effort
418 // would otherwise be told as "/effort auto")
419 if (!run.shown && !st.turnId && st.lastCmd && st.lastCmd.name === run.name && st.lastCmd.args === run.args) st.lastCmd = null
420 cmdTell(run)
421 })
422}
423function cmdTell(run: CmdRun) {
424 if (run.told || run.shown || SKIP_CMDS.has(run.name)) return
425 // a resume that went through is told by the conversation it brings back (resumed); one that did not, by the line it printed
426 if (run.name === 'resume' && !run.text.trim()) return
427 run.told = true
428 push({ k: 'cmd', name: run.name, args: run.args, text: keepText(run.text, 5000), via: run.via, run: run.id })
429}
430
431/* ---------------- files named with @ in a prompt from the screen ---------------- */
432// The terminal attaches what a typed prompt names with @; a plugin's prompt gets no such expansion. So the files go in
433// here, as a row the model reads (the person does not see it) right before the prompt, read as the Read tool shows
434// them. Only what lies inside this terminal's folder is read; anything else stays a name, for Claude to read or not.
435// The row can carry text only: an Excel, Word or PowerPoint file goes in as the text the hub takes out of it, a text
436// saved in Shift_JIS (a CSV from Excel) as the hub decodes it, and an image or a PDF is named for Claude to open itself.
437type Attached = { p: string; kind?: 'file' | 'dir'; lines?: number; shown?: number; err?: string; as?: string }
438const PER_FILE = 100_000, ALL_FILES = 200_000, MAX_LINES = 2000, MAX_BYTES = 1 << 20
439const DOCS = /\.(xlsx|xlsm|xltx|xltm|docx|docm|dotx|dotm|pptx|pptm|potx|potm)$/i
440const READS = /\.(png|jpe?g|gif|webp|pdf)$/i // what the Read tool shows Claude as it is
441const OLD_DOCS = /\.(xls|doc|ppt)$/i // Office's older binary files: not read
442const NOT_TEXT = /\.(bmp|ico|tiff?|heic|avif|psd|zip|gz|tgz|bz2|xz|7z|rar|jar|exe|dll|so|dylib|bin|class|wasm|woff2?|ttf|otf|eot|mp[34]|m4a|aac|ogg|flac|mov|avi|mkv|webm|wav|sqlite3?)$/i
443const CONVERTED: Record<string, string> = {
444 xlsx: 'Excel workbook: each sheet under ## and its name, its rows as tab-separated cell values led by the row number, under the column letters; values as last saved (a formula shows only where no value was saved)',
445 docx: 'Word document: its paragraphs, table cells separated by tabs',
446 pptx: 'PowerPoint deck: each slide\'s text under ## Slide and its number, with its speaker notes',
447}
448/** An image the screen attached: kept by the hub as a file, which Claude is told to open with Read. */
449type Pic = { id: string; path: string }
450async function pictures($: Any, imgs: Pic[]): Promise<string> {
451 const home = String(st.dir || '').replace(/\/+$/, ''), ok: string[] = []
452 for (const x of imgs) {
453 // only a file where the hub keeps them, by the name it gave it
454 if (!home || !x.path.startsWith(`${home}/uploads/`) || !/\/[0-9a-f]{16}\.(png|jpg|gif|webp)$/.test(x.path)) continue
455 const s = await $.fs.stat(x.path).catch(() => null)
456 if (s?.kind !== 'file') continue
457 ok.push(x.path); st.imgOk.add(x.path)
458 }
459 while (st.imgOk.size > 60) st.imgOk.delete(st.imgOk.values().next().value!)
460 if (!ok.length) return ''
461 const many = ok.length > 1
462 return `The user attached ${many ? `${ok.length} images` : 'an image'} to the message that follows, on the Fogcast screen (where Claude Code cannot attach images itself). ${many ? 'They are' : 'It is'} saved as ${many ? 'files' : 'a file'}: open ${many ? 'each' : 'it'} with the Read tool to see what the user means.\n${ok.map(p => `- ${p}`).join('\n')}`
463}
464async function attachments($: Any, text: string, imgs: Pic[] = []): Promise<{ row: string; items: Attached[] }> {
465 const names = mentionsOf(text)
466 const items: Attached[] = [], parts: string[] = [], reads: string[] = []
467 const pics = imgs.length ? await pictures($, imgs) : ''
468 if (!names.length) return { row: pics, items }
469 // every path is read from this terminal's folder (what the terminal's @ resolves against), and must land inside it
470 const base = String(st.cwd || '').replace(/[\\/]+$/, '')
471 const at = (p: string) => `${base}/${p}`
472 const root = (await $.fs.stat(base || '.', { resolve: true }).catch(() => null))?.realPath || base
473 const inside = (real: string) => !!real && (real === root || real.startsWith(root.endsWith('/') ? root : root + '/'))
474 const hubRead = (real: string) => post($, '/api/mod/doc', { chan: CHAN, path: real })
475 let budget = ALL_FILES
476 for (const name of names) {
477 if (/^(~|\/|[A-Za-z]:[\\/]|\\\\)/.test(name)) { items.push({ p: name, err: 'outside' }); continue }
478 let hit: { p: string; s: Any } | null = null
479 for (const p of mentionCandidates(name)) {
480 const s = await $.fs.stat(at(p), { resolve: true }).catch(() => null)
481 if (s && s.realPath) { hit = { p, s }; break }
482 }
483 if (!hit) { items.push({ p: name, err: 'missing' }); continue }
484 const { p, s } = hit
485 if (!inside(s.realPath)) { items.push({ p, err: 'outside' }); continue }
486 if (s.kind !== 'file' && s.kind !== 'dir') { items.push({ p, err: 'missing' }); continue }
487 if (s.kind === 'dir') {
488 const list = ((await $.fs.list(at(p)).catch(() => [])) as Any[]).filter(x => x && x.name)
489 const names2 = list.map(x => x.kind === 'dir' ? `${x.name}/` : x.name).sort((a: string, b: string) => Number(b.endsWith('/')) - Number(a.endsWith('/')) || a.localeCompare(b))
490 const body = names2.slice(0, 300).join('\n') + (names2.length > 300 ? `\n… (${names2.length - 300} more)` : '')
491 if (body.length > budget) { items.push({ p, kind: 'dir', err: 'budget' }); continue }
492 budget -= body.length
493 parts.push(`<directory path="${p.replace(/\/?$/, '/')}">\n${body}\n</directory>`)
494 items.push({ p: p.replace(/\/?$/, '/'), kind: 'dir', lines: names2.length })
495 continue
496 }
497 if (READS.test(p)) { reads.push(p); items.push({ p, kind: 'file', err: 'read' }); continue }
498 if (OLD_DOCS.test(p)) { items.push({ p, kind: 'file', err: 'legacy' }); continue }
499 if (NOT_TEXT.test(p)) { items.push({ p, kind: 'file', err: 'binary' }); continue }
500 if (DOCS.test(p)) {
501 if (budget < 2000) { items.push({ p, kind: 'file', err: 'budget' }); continue }
502 const d = await hubRead(s.realPath)
503 if (!d?.ok || typeof d.text !== 'string' || !CONVERTED[d.kind]) { items.push({ p, kind: 'file', err: d?.error === 'large' ? 'large' : 'unread' }); continue }
504 const t = cutText(d.text, Math.min(PER_FILE, budget))
505 budget -= t.body.length
506 parts.push(`<file path="${p}" converted="${CONVERTED[d.kind]}">\n${t.body}\n</file>${t.cut ? `\n(Only the start of ${p} is shown here; open the file with a script when the rest is needed.)` : ''}`)
507 items.push({ p, kind: 'file', lines: t.lines, shown: t.shown, as: d.kind })
508 continue
509 }
510 if (Number(s.size) > MAX_BYTES) { items.push({ p, kind: 'file', err: 'large' }); continue }
511 const read: unknown = await $.fs.read(at(p)).catch(() => null)
512 let raw = typeof read === 'string' ? read : '', enc = ''
513 // not UTF-8 (a Shift_JIS CSV, a UTF-16 text): the hub tries the encodings it knows; a NUL with none of them is a binary
514 if (typeof read !== 'string' || raw.includes('\u0000') || raw.includes('\uFFFD')) {
515 const d = await hubRead(s.realPath)
516 if (d?.ok && typeof d.text === 'string') { raw = d.text; if (d.enc && d.enc !== 'utf-8') enc = String(d.enc) }
517 else if (typeof read !== 'string') { items.push({ p, kind: 'file', err: 'missing' }); continue }
518 else if (raw.includes('\u0000') || d?.error === 'binary') { items.push({ p, kind: 'file', err: 'binary' }); continue }
519 }
520 if (budget < 2000) { items.push({ p, kind: 'file', err: 'budget' }); continue }
521 const n = numbered(raw, MAX_LINES, Math.min(PER_FILE, budget))
522 budget -= n.body.length
523 const range = n.shown < n.lines ? `1-${n.shown} of ${n.lines}` : String(n.lines)
524 parts.push(`<file path="${p}" lines="${range}"${enc ? ` encoding="${enc}"` : ''}>\n${n.body}\n</file>${n.shown < n.lines ? `\n(The rest of ${p} is not shown here; read it with the Read tool when needed.)` : ''}`)
525 items.push({ p, kind: 'file', lines: n.lines, shown: n.shown, ...(enc ? { as: enc } : {}) })
526 }
527 if (!parts.length && !reads.length) return { row: pics, items }
528 const them = reads.length > 1
529 const row = [
530 'The user named these with @ in the message that follows, sent from the Fogcast screen (where Claude Code does not attach @ mentions itself).',
531 parts.length ? ` Here is what they held when it was sent, as the terminal's @ would have attached them${parts.some(x => x.includes(' converted="')) ? ' (an Office file as the text taken out of it)' : ''}:\n\n${parts.join('\n\n')}` : '',
532 reads.length ? `${parts.length ? '\n\n' : ' '}${reads.join(', ')} ${them ? 'are images or PDFs' : /\.pdf$/i.test(reads[0]!) ? 'is a PDF' : 'is an image'}, which this screen cannot attach: read ${them ? 'them' : 'it'} with the Read tool to see what the user means.` : '',
533 ].join('')
534 return { row: pics ? `${row}\n\n${pics}` : row, items }
535}
536/** A prompt from the screen: the files it names and the images it carries go in first, then the prompt, as the person's own words. */
537async function sendPrompt($: Any, text: string, entry: { files?: Attached[] }, imgs: Pic[] = []) {
538 const a = await attachments($, text, imgs)
539 if (a.items.length) entry.files = a.items
540 if (a.row) {
541 const r = await $.session.append({ message: { type: 'user', content: [{ type: 'text', text: a.row }] } }).catch(() => null)
542 if (!r || r.deny) entry.files = a.items.map(x => (x.err && x.err !== 'read' ? x : { p: x.p, kind: x.kind, err: 'refused' }))
543 }
544 await $.prompt.submit({ text, asUser: true })
545}
546
547/* ---------------- approving from the screen (only when it was turned on and paired there) ---------------- */
548async function waitDecision($: Any, id: string, signal?: AbortSignal): Promise<string> {
549 const until = Date.now() + 125000
550 while (Date.now() < until) {
551 if (signal?.aborted) { void post($, '/api/mod/ask/answer', { id, decision: 'cancel' }); return 'cancel' }
552 const t0 = Date.now()
553 const r = await post($, '/api/mod/ask/wait', { id }) // the hub holds this up to 25 s
554 if (!r) return 'terminal'
555 if (r.decision) return r.decision
556 if (Date.now() - t0 < 1000) await $.clock.sleep(1000) // a hub that answers at once is not holding: do not spin
557 }
558 return 'terminal'
559}
560
561/* ---------------- a question Claude asks (AskUserQuestion), answerable from the screen ---------------- */
562/**
563 * The terminal's own dialog opens as usual (next). The screen gets the question too; whichever answers first
564 * is the answer. One from the screen is handed to Claude in the tool's own terms, and returning it while the
565 * dialog is still open closes the dialog.
566 */
567async function question($: Any, e: Any, next: Any, id: string, args: Any): Promise<Any> {
568 const qs = questionsOf(args)
569 if (!st.on || !qs.length) return next(e)
570 push({ k: 'question', id, qs })
571 const inTerminal = next(e)
572 let settle: (v: Any) => void = () => {}
573 const fromScreen = new Promise<Any>(res => { settle = res })
574 st.qWait.set(id, sent => { const answers = answersFor(args, sent); if (answers) settle(answers) })
575 try {
576 const first = await Promise.race([inTerminal.then((r: Any) => ({ r })), fromScreen.then(answers => ({ answers }))])
577 if ('answers' in first) {
578 inTerminal.catch(() => {}) // the dialog, closed by this answer, settles as refused: not Claude's answer
579 push({ k: 'questionEnd', id, by: 'screen', answers: first.answers })
580 return { result: { questions: e.questions, answers: first.answers } }
581 }
582 const a = first.r?.result?.answers
583 push({ k: 'questionEnd', id, by: 'terminal', answers: a && typeof a === 'object' && !first.r?.isError ? a : undefined, err: !!(first.r?.isError || first.r?.deny) })
584 return first.r
585 } finally { st.qWait.delete(id) }
586}
587
588/* ---------------- /fog ---------------- */
589/** Under WSL the browser is Windows': this terminal opens it through interop itself. The hub may have been
590 * started from a terminal that has since closed, and Windows programs cannot be run from a session that is gone. */
591async function openFromWsl($: Any, url: string): Promise<boolean> {
592 if (!((await $.env.get('WSL_DISTRO_NAME')) || (await $.env.get('WSL_INTEROP')))) return false
593 for (const argv of [['rundll32.exe', 'url.dll,FileProtocolHandler', url], ['/mnt/c/Windows/System32/rundll32.exe', 'url.dll,FileProtocolHandler', url], ['wslview', url]]) {
594 try { if ((await $.process.run(argv, { timeoutMs: 8000 })).exitCode === 0) return true } catch {}
595 }
596 return false
597}
598async function fog($: Any) {
599 if (!st.ready) await connect($)
600 if (!st.ready) return { text: '受け皿にまだ接続できていません。数秒待ってから、もう一度 /fog を実行してください。' }
601 const url = `${st.base}/#k=${st.token}`
602 const opened = (await openFromWsl($, url)) || !!(await post($, '/api/mod/open', {}))?.opened
603 // the address with its key goes to the person only: drawn under this row (never stored) and pointed at by a toast
604 st.fogShow = url
605 try { $.ui.toast(opened ? 'Fogcast: 画面をブラウザで開きました。開かないときは /fog の下の URL から' : 'Fogcast: ブラウザを開けませんでした。/fog の下の URL を開いてください', { timeoutMs: TOAST_MAX }) } catch {}
606 // the one link to press is the keyed one drawn below, on a line of its own (a terminal takes punctuation
607 // that touches a URL as part of it); the line the model reads has none
608 return { text: opened ? 'Fogcast の画面をブラウザで開きました。開いていなければ、この下の URL を開いてください。' : 'ブラウザを開けませんでした。この下の URL を開いてください。' }
609}
610
611export const register: Register = (on) => {
612 on('session.start', async ($: Any, e: Any, next: Any) => {
613 const r = await next(e)
614 try {
615 st.on = e.isInteractive === true || (await $.env.get('FOGCAST_HEADLESS')) === '1'
616 if (!st.on) return r
617 st.cwd = e.cwd
618 await paths($)
619 await $.command.register({ name: 'fog', description: 'Fogcast の画面(全ターミナルの会話と使用量)をブラウザで開く' }).catch(() => {})
620 $.clock.every(SYNC_MS, () => tick($))
621 line($)
622 } catch {}
623 return r
624 })
625
626 on('session.measure', async ($: Any, e: Any, next: Any) => {
627 try {
628 st.ctx = e.context.percent; st.limits = e.rateLimits ?? []; st.usd = e.cost?.usd
629 st.measure = {
630 k: 'measure', ctx: { tokens: e.context.tokens ?? 0, window: e.context.window, percent: e.context.percent ?? 0 },
631 limits: st.limits.map((w: Reading) => ({ kind: w.kind, pc: w.percentUsed, resetsAt: w.resetsAt })), usd: e.cost?.usd,
632 }
633 push({ ...st.measure })
634 line($)
635 } catch {}
636 return next(e)
637 })
638
639 // typed over a running turn: Claude Code hands it to the model inside that turn at its next step (with no step left, it starts the next turn)
640 on('prompt.submit', async ($: Any, e: Any, next: Any) => {
641 const r = await next(e)
642 try {
643 const who = e.origin?.kind
644 if (st.on && e.turnId && (who === 'composer' || who === 'bridge') && typeof e.text === 'string' && e.text.trim()) {
645 st.midTyped.push(e.text.trim()); if (st.midTyped.length > 5) st.midTyped.shift()
646 }
647 } catch {}
648 return r
649 })
650
651 on('turn.start', async ($: Any, e: Any, next: Any) => {
652 try {
653 st.turnId = e.turnId; st.turnText = e.text || ''; st.turnHasOutput = false
654 { const i = st.midTyped.indexOf(String(e.text || '').trim()); if (i >= 0) st.midTyped.splice(i, 1) } // typed too late for the last one: a turn of its own
655 if (st.suggest) { st.suggest = ''; push({ k: 'suggest', text: '' }) }
656 const lc = st.lastCmd && Date.now() - st.lastCmd.t < 4000 ? st.lastCmd : null
657 // a command that starts a turn (a skill, /goal) is told by that turn, not by a row of its own
658 if (lc && st.cmdRun && st.cmdRun.name === lc.name && !st.cmdRun.told) st.cmdRun.shown = true
659 const text = lc ? `/${lc.name}${lc.args ? ' ' + lc.args : ''}` : e.text
660 const i = st.submitted.findIndex(x => x.text === e.text)
661 const via = i >= 0 || lc?.screen ? 'screen' : undefined
662 const sent = i >= 0 ? st.submitted.splice(i, 1)[0]! : undefined
663 st.lastCmd = null
664 push({ k: 'turn', id: e.turnId, text, via, cid: sent?.cid, ...(sent?.files ? { files: sent.files } : {}), ...(sent?.imgs ? { imgs: sent.imgs } : {}) })
665 } catch {}
666 return next(e)
667 })
668
669 on('turn.complete', async ($: Any, e: Any, next: Any) => {
670 try {
671 if (e.agentId) {
672 const id = st.agents.get(e.agentId)
673 if (id) { push({ k: 'agentEnd', id, stopped: !!e.isAborted }); st.agents.delete(e.agentId) }
674 } else {
675 const u = e.usage
676 push({ k: 'turnEnd', id: e.turnId, ms: e.durationMs, aborted: !!e.isAborted, reason: e.reason, usage: u ? { in: u.input_tokens, out: u.output_tokens, cw: u.cache_creation_input_tokens, cr: u.cache_read_input_tokens } : undefined })
677 st.turnId = ''; st.turnText = ''; st.lastCmd = null; st.tools.clear(); st.ceil.clear()
678 for (const f of st.afterTurn.splice(0)) $.clock.after(400, f)
679 if (++st.turnsDone % 5 === 0) void reload($)
680 void branch($).then(b => { if (b !== st.branch) { st.branch = b; push({ k: 'info', branch: b }) } })
681 }
682 } catch {}
683 return next(e)
684 })
685
686 // the model's words, anything typed while it works, and what a command printed; everything else passes untouched
687 on('session.append', async ($: Any, e: Any, next: Any) => {
688 const r = await next(e)
689 try {
690 if (st.on && !e.agentId) {
691 if (e.door === 'command') {
692 // a command's rows: the one naming it, then the line it printed ("Set model to …"), which no plugin is handed
693 const row = commandRow(e.message?.content)
694 if (row.name) st.appendCmd = row.name
695 if (row.out !== undefined && st.appendCmd && !SKIP_CMDS.has(st.appendCmd)) {
696 const run = st.cmdRun && st.cmdRun.name === st.appendCmd && Date.now() - st.cmdRun.t < 10 * 60e3 ? st.cmdRun : null
697 if (row.out && run) {
698 // the line joins its run's row: before the row is told it rides in it, after it fills it (unless the command answered with text)
699 if (!run.told) { if (!run.text.trim()) run.text = row.out; if (run.settled) cmdTell(run) }
700 else if (!run.text.trim()) { run.text = row.out; push({ k: 'cmdOut', name: run.name, text: keepText(row.out, 5000), run: run.id }) }
701 } else if (row.out) push({ k: 'cmdOut', name: st.appendCmd, text: keepText(row.out, 5000) })
702 if (st.appendCmd === 'effort') effortIs(effortSet(row.out))
703 st.appendCmd = ''
704 }
705 } else if (e.door === 'response' && e.message?.type === 'assistant') {
706 const t = textOf(e.message.content)
707 if (t.trim()) { push({ k: 'say', text: t }); st.turnHasOutput = true }
708 } else if (e.door === 'delivery' && st.turnId) {
709 // what the person typed while the model worked, reaching it inside this turn: shown there, as they typed it
710 const t = midTurnText(e.message, e.origin?.kind, st.midTyped)
711 if (t) push({ k: 'user', text: t, mid: true })
712 } else if (e.door === 'prompt' && e.message?.role === 'user' && !e.message.isMeta && st.turnId && st.turnHasOutput) {
713 const t = textOf(e.message.content).trim()
714 if (t && t !== st.turnText.trim()) push({ k: 'user', text: t, mid: true })
715 }
716 }
717 } catch {}
718 return r
719 })
720
721 on('tool.call', async ($: Any, e: Any, next: Any) => {
722 if (!st.on) return next(e)
723 const id: string = e.tool_use_id, name = String(e.tool), agent: string | undefined = e.agentId
724 const { tool: _t, tool_use_id: _i, agentId: _a, ...args } = e
725 try {
726 const link = linkFor(name, args)
727 const known = st.srcOf.get(link.id); if (known) { link.src = link.src || known.src; if (known.dt != null) link.dt = known.dt; if (known.desc) link.desc = known.desc }
728 if (link.kind === 'agent' && !link.desc && st.agentDesc.has(link.label)) link.desc = st.agentDesc.get(link.label)
729 const ev: Any = { k: 'tool', id, name: verb(name), input: summarize(name, args, st.cwd), link, agent }
730 const fc = fileChange(name, args, st.cwd); if (fc) ev.file = fc
731 const todos = todosOf(name, args); if (todos) ev.todos = todos
732 if (name === 'TaskUpdate') ev.task = { op: 'update', id: String(args.taskId ?? ''), st: str(args.status), t: str(args.subject) }
733 push(ev)
734 st.tools.set(id, { name, input: ev.input, agent })
735 if (!agent) st.turnHasOutput = true
736 if (name === 'Skill') st.recentSkill = { name: link.label, t: Date.now() }
737 } catch {}
738 let r: Any
739 try { r = name === 'AskUserQuestion' && !agent ? await question($, e, next, id, args) : await next(e) }
740 catch (err) { push({ k: 'toolEnd', id, err: true, out: '中断' }); st.tools.delete(id); throw err }
741 try {
742 st.tools.delete(id); st.ceil.delete(id)
743 // a picture or a PDF read comes back as itself, not as lines
744 const seen = name === 'Read' && r && !r.deny && !r.isError && !String(r.text ?? '').trim() ? (/\.(png|jpe?g|gif|webp)$/i.test(String(args.file_path ?? '')) ? '画像' : /\.pdf$/i.test(String(args.file_path ?? '')) ? 'PDF' : '') : ''
745 const end: Any = { k: 'toolEnd', id, err: !!(r && (r.deny || r.isError)), out: seen || outline(name, r) }
746 if (name === 'TaskCreate' && !end.err) { const m = /#(\d+)/.exec(str(r?.text)) ?? /\b(\d+)\b/.exec(str(r?.text)); end.task = { op: 'create', id: m ? m[1] : id, t: clip(str(args.subject) || str(args.description), 200) } }
747 push(end)
748 } catch {}
749 return r
750 })
751
752 // an organization that requires the dialog for a tool keeps it: those calls are never offered to the screen
753 on('tool.check', async ($: Any, e: Any, next: Any) => {
754 const v = await next(e)
755 try { if (e.tool_use_id && (v?.ceiling || e.ceiling)) st.ceil.add(e.tool_use_id) } catch {}
756 // an image the person attached on the screen, where Fogcast keeps it: Claude opens it without a dialog. Only that file,
757 // only to read it; a deny stands, and so does an organization that wants the dialog
758 try {
759 if (e.tool === 'Read' && v?.decision === 'ask' && !v.ceiling && !e.ceiling && st.imgOk.has(String(e.input?.file_path ?? '')))
760 return { ...v, decision: 'allow', reason: 'Fogcast の画面で添付された画像' }
761 } catch {}
762 return v
763 })
764
765 // the moment a permission dialog would open
766 on('classic.PermissionRequest', async ($: Any, e: Any, next: Any) => {
767 const r = await next(e)
768 if (!st.on || r?.decision || e.tool_name === 'AskUserQuestion') return r // a question is answered, not approved: see question()
769 try {
770 const name = String(e.tool_name)
771 let id = ''
772 const running = [...st.tools].reverse()
773 for (const [tid, t] of running) if (t.name === name && !t.waiting && (t.agent ?? '') === (e.agent_id ?? '')) { id = tid; break }
774 if (!id) for (const [tid, t] of running) if (t.name === name && !t.waiting) { id = tid; break }
775 const input = summarize(name, (e.tool_input ?? {}) as Any, st.cwd)
776 if (id) st.tools.get(id)!.waiting = true
777 push({ k: 'wait', id: id || `perm-${Date.now()}`, name: verb(name), input })
778 if (!st.ready || !st.approvals || !id || st.ceil.has(id)) return r
779 const ask = await post($, '/api/mod/ask', { chan: CHAN, id, tool: verb(name), input })
780 if (ask?.mode !== 'screen') return r
781 st.band = { id, tool: verb(name), input, until: ask.exp || Date.now() + 120000 }
782 $.ui.invalidate('ui.render')
783 const decision = await waitDecision($, id, next.signal)
784 st.band = null; $.ui.invalidate('ui.render')
785 if (decision === 'allow') { push({ k: 'run', id, how: 'screen' }); return { decision: { behavior: 'allow' } } }
786 if (decision === 'deny') return { decision: { behavior: 'deny', message: 'Fogcast の画面で拒否されました。' } }
787 } catch { st.band = null }
788 return r
789 })
790
791 on('agent.spawn', async ($: Any, e: Any, next: Any) => {
792 const r = await next(e)
793 try { if (st.on && r?.agentId) { st.agents.set(r.agentId, e.tool_use_id); push({ k: 'agent', id: e.tool_use_id, type: e.subagentType, desc: clip(e.description || '', 160) }) } } catch {}
794 return r
795 })
796
797 on('skill.prompt', async ($: Any, e: Any, next: Any) => {
798 try {
799 const rs = st.recentSkill
800 const known = st.srcOf.get(`skill:${e.skill}`)
801 if (!(rs && rs.name === e.skill && Date.now() - rs.t < 15000)) push({ k: 'skill', name: e.skill, link: { id: `skill:${e.skill}`, kind: 'skill', label: e.skill, src: known?.src, dt: known?.dt, desc: known?.desc || undefined } })
802 st.recentSkill = null
803 // a command the "/" list could not tell from the built-in panels: from now on the screen runs it as a turn
804 const name = String(e.skill || '')
805 if (name && !st.skillRan.has(name)) { st.skillRan.add(name); if (!st.srcOf.has(`skill:${name}`)) push({ k: 'skillCmd', name }) }
806 } catch {}
807 return next(e)
808 })
809
810 // what each agent type is for, as the engine offers it to the model before a request: kept for its コミュ card
811 on('agent.offer', async ($: Any, e: Any, next: Any) => {
812 const r = await next(e)
813 try {
814 const d = keepText(str(e.description), 1500), id = `agent:${e.agent}`
815 if (st.on && d && e.source !== 'built-in' && st.agentDesc.get(e.agent) !== d) {
816 st.agentDesc.set(e.agent, d)
817 const known = st.srcOf.get(id); if (known) known.desc = d
818 push({ k: 'desc', id, desc: d })
819 }
820 } catch {}
821 return r
822 })
823 // each command's argument hint (`/model [model]`), as the engine lists it for the typeahead at start
824 on('command.describe', async ($: Any, e: Any, next: Any) => {
825 const r = await next(e)
826 try {
827 const h = str(r?.argumentHint) || str(e.argumentHint); if (h) st.hints.set(String(e.command), clip(h, 120)); else st.hints.delete(String(e.command))
828 if (r?.isHidden ?? e.isHidden) st.hiddenCmds.add(String(e.command)); else st.hiddenCmds.delete(String(e.command))
829 } catch {}
830 return r
831 })
832 // the dim guess at the next prompt that Claude Code shows after a turn (Tab takes it): the screen shows it too
833 on('prompt.suggest', async ($: Any, e: Any, next: Any) => {
834 const r = await next(e)
835 try { const t = str(e.text).trim(); if (st.on && r?.isShown && t) { st.suggest = t; push({ k: 'suggest', text: clip(t, 400) }) } } catch {}
836 return r
837 })
838 // typing in the terminal's box (or taking the suggestion there) puts the suggestion away
839 on('prompt.edit', async ($: Any, e: Any, next: Any) => {
840 if (st.suggest) { st.suggest = ''; push({ k: 'suggest', text: '' }) }
841 return next(e)
842 })
843
844 on('command.run', { command: 'fog' }, async ($: Any) => fog($))
845 on('command.run', async ($: Any, e: Any, next: Any) => {
846 if (!st.on || e.command === 'fog') return next(e)
847 // typed in the terminal (or run by another plugin); the screen's own runs are followed in runCommand
848 st.lastCmd = { name: e.command, args: e.args || '', t: Date.now() }
849 const run = cmdBegin(e.command, e.args || '', false)
850 const r = await next(e)
851 try {
852 if (typeof r?.text === 'string' && !st.turnId) st.lastCmd = null // it printed: no turn follows
853 cmdDone($, run, r)
854 } catch {}
855 return r
856 })
857
858 // the screen says the conversation is being compacted while it is (a summary made ahead of time is not shown)
859 on('session.compact', async ($: Any, e: Any, next: Any) => {
860 const shown = st.on && !e.agentId && e.trigger !== 'precompute'
861 if (shown) push({ k: 'compacting', trigger: e.trigger })
862 let r: Any
863 try { r = await next(e) } catch (err) { if (shown) push({ k: 'compactOff', reason: clip(String((err as Any)?.message ?? err), 200) }); throw err }
864 try { if (shown) push(r?.skip ? { k: 'compactOff', reason: clip(String(r.skip), 200) } : { k: 'compact', trigger: e.trigger }) } catch {}
865 return r
866 })
867
868 on('session.end', async ($: Any, e: Any, next: Any) => {
869 try {
870 if (st.on) {
871 if (e.reason === 'clear') { push({ k: 'clear', prev: e.sessionId }); st.turnId = ''; st.tools.clear() }
872 // /resume in this terminal: the conversation is swapped, the terminal goes on (classic.SessionStart says for which)
873 else if (e.reason === 'resume') { st.resumeFrom = String(e.sessionId || st.sid); st.turnId = ''; st.tools.clear(); st.ceil.clear(); st.suggest = '' }
874 else {
875 push({ k: 'end', reason: e.reason, resume: e.resume?.id ?? e.sessionId })
876 if (st.ready) await post($, '/api/mod/sync', { chan: CHAN, events: outbox.splice(0) })
877 }
878 }
879 } catch {}
880 return next(e)
881 })
882
883 // which conversation this terminal is on: at start (its file tells the hub where the project's conversations are),
884 // and after /clear or /resume, which swap it while the terminal goes on
885 on('classic.SessionStart', async ($: Any, e: Any, next: Any) => {
886 try {
887 const sid = str(e.session_id), tp = str(e.transcript_path)
888 if (tp) st.tp = tp
889 if (st.on && sid && (e.source === 'resume' || e.source === 'fork')) {
890 push({ k: 'resumed', from: st.resumeFrom || st.sid, sid, title: clip(str(e.session_title), 200), tp, source: e.source })
891 st.resumeFrom = ''; st.turnId = ''; st.turnText = ''; st.tools.clear(); st.lastCmd = null
892 if (st.cmdRun?.name === 'resume') st.cmdRun.shown = true
893 if (str(e.model) && e.model !== st.model) { st.model = e.model; push({ k: 'info', model: e.model }) }
894 } else if (st.on && sid && e.source === 'clear') push({ k: 'info', sid, tp })
895 if (sid) st.sid = sid
896 } catch {}
897 return next(e)
898 })
899 // /model, the /config Model row, the screen's picker or a fallback: the switch shows in the conversation
900 on('classic.PostModelSwitch', async ($: Any, e: Any, next: Any) => {
901 try {
902 // a switch is one from a model to another (st.model may already have caught up through the periodic check)
903 const to = str(e.to_model), from = str(e.from_model)
904 if (st.on && to && to !== (from || st.model)) {
905 // a resume restores the conversation's own model: that is part of the resume, not a switch to tell of
906 const screen = Date.now() - st.modelAsked < 15000; if (screen) st.modelAsked = 0
907 push(e.source === 'resume' ? { k: 'info', model: to } : { k: 'model', from: from || st.model, to, src: screen ? 'screen' : str(e.source) })
908 $.clock.after(300, () => { void syncModels($) })
909 // `/model sonnet`: the switch says it, with the model it left; the command's own row would say it again
910 if (st.cmdRun?.name === 'model' && !st.cmdRun.told && Date.now() - st.cmdRun.t < 60000) st.cmdRun.shown = true
911 st.model = to
912 effortIs(await savedEffort($, to))
913 }
914 } catch {}
915 return next(e)
916 })
917 // the Model row changed in the terminal's /config (this module's own writes are not seen here): the picker's mark follows
918 on('config.set', async ($: Any, e: Any, next: Any) => {
919 const r = await next(e)
920 try { if (st.on && e.key === 'model' && !r?.deny) $.clock.after(300, () => { void syncModels($) }) } catch {}
921 return r
922 })
923 // each request of the main conversation: the effort it really goes with (a model without effort sends none)
924 on('turn.step', async function* ($: Any, e: Any, next: Any) {
925 try {
926 if (st.on && !e.agentId) {
927 const eff = e.effort == null ? '' : String(e.effort)
928 if (eff && eff !== st.effortUsed) { st.effortUsed = eff; push({ k: 'info', effortUsed: eff }) }
929 if (eff && !st.effort) effortIs(eff) // nothing set that this terminal saw: the model's own level stands for it
930 }
931 } catch {}
932 return yield* next(e)
933 })
934
935 // what the turn is doing right now, for the screen's status line
936 on('ui.render', { component: 'Spinner' }, async ($: Any, e: Any, next: Any) => {
937 try { const m = e.props?.mode; if (st.on && m && m !== st.mode) { st.mode = m; push({ k: 'mode', mode: m }) } } catch {}
938 return next(e)
939 })
940 // a call that shows progress has been let through its dialog
941 on('ui.render', { component: 'ToolProgress' }, async ($: Any, e: Any, next: Any) => {
942 try { const t = st.tools.get(e.props?.tool_use_id); if (t?.waiting) { t.waiting = false; push({ k: 'run', id: e.props.tool_use_id }) } } catch {}
943 return next(e)
944 })
945 // /fog's row, as the person sees it: with the address and its key when no browser could be opened
946 on('ui.render', { component: 'CommandOutput', props: { command: 'fog' } }, async ($: Any, e: Any, next: Any) => {
947 if (!st.fogShow || e.props?.isErrored) return next(e)
948 return next({ ...e, props: { ...e.props, text: `${e.props.text}\n\n鍵つきの URL(この画面にだけ出ています):\n\n${st.fogShow}` } })
949 })
950
951 // above the prompt: the code a browser is being paired with, and an approval the screen holds
952 on('ui.render', { component: 'AbovePrompt' }, async ($: Any, e: Any, next: Any) => {
953 const b = st.band, p = st.pair && st.pair.until > Date.now() ? st.pair : null
954 if ((!b && !p) || e.props?.hasSurvey) return next(e)
955 const ui = $.ui.resolve(e) as Any
956 const parts: Any[] = []
957 if (p) parts.push(pairBand($, ui, p))
958 if (b) parts.push(askBand($, ui, b))
959 return parts.length === 1 ? parts[0] : h(ui.Box, { flexDirection: 'column' }, ...parts)
960 })
961}
962
963/** The pairing code, framed in yellow right above the prompt, where the person is already looking. */
964function pairBand($: Any, ui: Any, p: { code: string; until: number }) {
965 const { Box, Text, Button } = ui
966 const cancel = () => {
967 st.pair = null; $.ui.invalidate('ui.render'); line($)
968 void post($, '/api/mod/pair/cancel', { chan: CHAN, code: p.code })
969 }
970 return h(Box, { key: 'fogcast-pair', flexDirection: 'column', borderStyle: 'round', borderColor: 'warning', paddingX: 1 },
971 h(Box, { flexDirection: 'row', gap: 2 },
972 h(Text, { color: 'warning', bold: true }, 'Fogcast ブラウザ承認の合言葉'),
973 h(Text, { color: 'warning', bold: true, inverse: true }, ` ${p.code} `)),
974 h(Text, { wrap: 'wrap' }, `ブラウザの Fogcast の画面(設定 → ブラウザから承認)に入力してください。${pairLeft()}で使えなくなります。`),
975 h(Box, { flexDirection: 'row', gap: 1 },
976 h(Text, { dimColor: true }, '心当たりがなければ'),
977 h(Button, { key: 'fogcast-pair-cancel', label: '取り消す', onPress: cancel })))
978}
979
980/** While the screen holds an approval, the terminal says so and can take it back. */
981function askBand($: Any, ui: Any, b: { id: string; tool: string; input: string; until: number }) {
982 const { Box, Text, Button } = ui
983 const left = Math.max(0, Math.round((b.until - Date.now()) / 1000))
984 return h(Box, { key: 'fogcast-ask', flexDirection: 'column' },
985 h(Text, { color: 'yellow', bold: true }, `Fogcast の画面で承認を待っています(あと ${left} 秒でここの確認に切り替わります)`),
986 h(Text, { dimColor: true, wrap: 'truncate-end' }, `${b.tool}: ${b.input}`),
987 h(Button, { key: 'fogcast-here', hotkey: 't', label: 'ここで確認する', onPress: () => { void post($, '/api/mod/ask/answer', { id: b.id, decision: 'terminal' }) } }))
988}
989hooks/shape.ts 355 lines1// How a tool call, a row or a reading is described on the Fogcast screen.
2// Pure functions, no `$`: register.ts calls them and the tests check them.
3
4export type LinkKind = 'core' | 'tool' | 'skill' | 'agent' | 'mcp'
5export type Link = { id: string; kind: LinkKind; label: string; src?: string; dt?: number; desc?: string }
6export type FileChange = { path: string; add: number; del: number }
7export type Todo = { t: string; st: 'todo' | 'doing' | 'done' }
8type Args = Record<string, unknown>
9
10export const str = (v: unknown): string => (typeof v === 'string' ? v : '')
11export const clip = (s: string, n: number): string => {
12 const one = s.replace(/\s+/g, ' ').trim()
13 return one.length > n ? one.slice(0, n - 1) + '…' : one
14}
15const lines = (s: unknown): number => {
16 const t = str(s)
17 if (!t) return 0
18 return t.split('\n').length - (t.endsWith('\n') ? 1 : 0)
19}
20
21/** A path as the screen shows it: relative to the session's folder when it is inside it. */
22export function rel(path: string, cwd: string): string {
23 if (!path) return ''
24 const c = cwd.replace(/[\\/]+$/, '')
25 if (c && (path.startsWith(c + '/') || path.startsWith(c + '\\'))) return path.slice(c.length + 1)
26 return path
27}
28
29const TASK_TOOLS = new Set(['TodoWrite', 'TaskCreate', 'TaskUpdate', 'TaskList', 'TaskGet'])
30const MCP = /^mcp__(.+?)__(.+)$/
31
32/** Which コミュ card a tool call counts toward. */
33export function linkFor(tool: string, a: Args): Link {
34 if (tool === 'Skill') {
35 const s = str(a.skill) || str(a.command) || str(a.name)
36 if (s) return { id: `skill:${s.replace(/^\//, '')}`, kind: 'skill', label: s.replace(/^\//, '') }
37 }
38 if (tool === 'Agent' || tool === 'Task') {
39 const t = str(a.subagent_type) || 'general-purpose'
40 return { id: `agent:${t}`, kind: 'agent', label: t }
41 }
42 if (TASK_TOOLS.has(tool)) return { id: 'Tasks', kind: 'tool', label: 'Tasks', src: '組み込み' }
43 const m = MCP.exec(tool)
44 if (m) return { id: `mcp:${m[1]}`, kind: 'mcp', label: m[1]!, src: 'MCP' }
45 return { id: tool, kind: 'tool', label: tool, src: '組み込み' }
46}
47
48/** The verb of the row: the tool, or for an MCP tool its server. */
49export function verb(tool: string): string {
50 const m = MCP.exec(tool)
51 return m ? m[1]! : tool
52}
53
54function firstString(a: Args): string {
55 for (const v of Object.values(a)) if (typeof v === 'string' && v.trim()) return v
56 return ''
57}
58function host(url: string): string {
59 try { const u = new URL(url); return u.host + (u.pathname === '/' ? '' : u.pathname) } catch { return url }
60}
61
62/** One line saying what the call does. */
63export function summarize(tool: string, a: Args, cwd: string): string {
64 const p = (k: string) => rel(str(a[k]), cwd)
65 switch (tool) {
66 case 'Bash': return clip(str(a.command).split('\n')[0] ?? '', 160)
67 case 'Read': return clip(p('file_path'), 160)
68 case 'Edit': case 'Write': case 'MultiEdit': return clip(p('file_path'), 160)
69 case 'NotebookEdit': return clip(p('notebook_path'), 160)
70 case 'Grep': return clip(`"${str(a.pattern)}" in ${p('path') || '.'}`, 160)
71 case 'Glob': return clip(str(a.pattern) + (a.path ? ` in ${p('path')}` : ''), 160)
72 case 'WebFetch': return clip(host(str(a.url)), 160)
73 case 'WebSearch': return clip(str(a.query), 160)
74 case 'Agent': case 'Task': return clip(`${str(a.subagent_type) || 'general-purpose'}:${str(a.description)}`, 160)
75 case 'Skill': return clip(`${str(a.skill) || str(a.command)}${a.args ? ' ' + str(a.args) : ''}`, 160)
76 case 'TodoWrite': return `${Array.isArray(a.todos) ? a.todos.length : 0} 件のタスク`
77 case 'TaskCreate': return clip(str(a.subject) || str(a.description), 160)
78 case 'TaskUpdate': return clip(`#${str(a.taskId) || String(a.taskId ?? '')}${a.status ? ' → ' + str(a.status) : ''}${a.subject ? ' ' + str(a.subject) : ''}`, 160)
79 case 'AskUserQuestion': {
80 const q = Array.isArray(a.questions) ? (a.questions[0] as Args | undefined) : undefined
81 return clip(str(q?.question) || str(a.question), 160)
82 }
83 case 'ExitPlanMode': return '計画の確認'
84 }
85 const m = MCP.exec(tool)
86 if (m) return clip(`${m[2]}${firstString(a) ? ' ' + firstString(a) : ''}`, 160)
87 return clip(firstString(a), 160)
88}
89
90/** What a finished call came to, in a few words. */
91export function outline(tool: string, r: { deny?: string; isError?: boolean; text?: string } | undefined): string {
92 if (!r) return ''
93 if (r.deny) return '拒否'
94 const text = str(r.text)
95 const first = (text.split('\n').find(x => x.trim()) ?? '').trim()
96 if (r.isError) return clip(`エラー:${first}`, 60)
97 switch (tool) {
98 case 'Read': return `${lines(text)} 行`
99 case 'Grep': case 'Glob': return text.trim() ? `${lines(text.trim())} 件` : '0 件'
100 case 'Edit': case 'MultiEdit': case 'Write': case 'NotebookEdit': return '保存'
101 case 'Bash': {
102 const last = text.trim().split('\n').reverse().find(x => x.trim()) ?? ''
103 return clip(last || '完了', 60)
104 }
105 case 'TodoWrite': case 'TaskCreate': case 'TaskUpdate': return '更新'
106 case 'Agent': case 'Task': return '完了'
107 case 'WebSearch': return '検索結果'
108 case 'WebFetch': return '取得'
109 }
110 return clip(first || '完了', 60)
111}
112
113/** Lines a file-writing call adds and removes, roughly. */
114export function fileChange(tool: string, a: Args, cwd: string): FileChange | null {
115 const path = rel(str(a.file_path) || str(a.notebook_path), cwd)
116 if (!path) return null
117 if (tool === 'Write') return { path, add: lines(a.content), del: 0 }
118 if (tool === 'Edit') return { path, add: lines(a.new_string), del: lines(a.old_string) }
119 if (tool === 'MultiEdit' && Array.isArray(a.edits)) {
120 let add = 0, del = 0
121 for (const e of a.edits as Args[]) { add += lines(e.new_string); del += lines(e.old_string) }
122 return { path, add, del }
123 }
124 if (tool === 'NotebookEdit') return { path, add: lines(a.new_source), del: 0 }
125 return null
126}
127
128/** The task list as TodoWrite hands it over. */
129export function todosOf(tool: string, a: Args): Todo[] | null {
130 if (tool !== 'TodoWrite' || !Array.isArray(a.todos)) return null
131 return (a.todos as Args[]).slice(0, 40).map(t => ({
132 t: clip(str(t.content) || str(t.activeForm), 200),
133 st: t.status === 'completed' ? 'done' : t.status === 'in_progress' ? 'doing' : 'todo',
134 }))
135}
136
137/** The text blocks of a row, joined. */
138export function textOf(content: unknown): string {
139 if (typeof content === 'string') return content
140 if (!Array.isArray(content)) return ''
141 return content.map(b => (b && typeof b === 'object' && (b as Args).type === 'text' ? str((b as Args).text) : '')).filter(Boolean).join('\n')
142}
143
144/**
145 * What the person typed while a turn ran, as it reaches the model inside that turn (a `queued_command`
146 * row the engine delivers), or ''. `typed` holds what they submitted over the turn: the one this row
147 * carries is taken out of it, word for word; failing that, the row's own wording is read.
148 */
149export function midTurnText(row: { name?: string; content?: unknown } | undefined, origin: string | undefined, typed: string[]): string {
150 if (row?.name !== 'queued_command') return ''
151 const body = textOf(row.content)
152 const i = typed.findIndex(t => body.includes(t))
153 if (i >= 0) return typed.splice(i, 1)[0]!
154 if (origin && origin !== 'composer' && origin !== 'bridge') return '' // a task's notice, another session's message
155 return (/while you were working:\n([\s\S]*?)\n\n/.exec(body)?.[1] ?? '').trim()
156}
157
158/**
159 * A slash command's rows as the conversation keeps them (`session.append`, door `command`): the row that names
160 * the command (`<command-name>/model</command-name>`) and the row with what it printed
161 * (`<local-command-stdout>…</local-command-stdout>`). The plugin that ran a command is handed no text for most
162 * of them; the printed line reaches the screen this way.
163 */
164export function commandRow(content: unknown): { name?: string; out?: string } {
165 const body = textOf(content)
166 const name = /<command-name>\/?([^<\s]+)<\/command-name>/.exec(body)?.[1]
167 const m = /<local-command-stdout>([\s\S]*?)<\/local-command-stdout>/.exec(body)
168 const out = m ? m[1]!.replace(/\x1b\[[0-9;]*[A-Za-z]/g, '').replace(/\r\n?/g, '\n').trim() : undefined
169 return { ...(name ? { name } : {}), ...(out !== undefined ? { out } : {}) }
170}
171
172/** The effort levels `/effort` takes, read off its argument hint (`[low|medium|…|auto|ultracode [on|off]]`). */
173export function effortLevels(hint: string | undefined): string[] {
174 const inner = String(hint ?? '').trim().replace(/^\[/, '')
175 const words = inner.split(/\[/)[0]!.split('|').map(w => w.replace(/[\]\s]/g, '')).filter(w => /^[a-z]+$/.test(w) && w !== 'ultracode')
176 return words.length ? [...new Set(words)] : ['low', 'medium', 'high', 'xhigh', 'max']
177}
178
179/** A model id as its key in the settings' `modelSettings` (`claude-opus-5-5[1m]` → `claude-opus-5-5`). */
180export function modelKey(model: string): string { return String(model || '').replace(/\[[^\]]*\]$/, '') }
181
182/**
183 * The /config Model row's value as one of the row's own choices. The row can hold a label rather than a choice
184 * (`Default (recommended)` before anything is set) or a model id; the screen's picker marks the choice.
185 */
186export function settingOf(value: unknown, options: readonly string[]): string {
187 const v = typeof value === 'string' ? value.trim() : ''
188 if (!v) return ''
189 if (options.includes(v)) return v
190 const lo = v.toLowerCase(), bare = lo.replace(/\s*\([^)]*\)\s*$/, '').trim()
191 const same = options.find(o => o.toLowerCase() === bare); if (same) return same
192 // a model id or a longer label (claude-sonnet-5-5[1m], "Opus (1M context)"): its family, long-context when it says so
193 const fam = options.find(o => /^[a-z]+$/.test(o) && new RegExp(`(^|[^a-z])${o}([^a-z]|$)`).test(bare))
194 if (!fam) return v
195 const long = `${fam}[1m]`
196 return /\[1m\]|\b1m\b/.test(lo) && options.includes(long) ? long : fam
197}
198
199/** The level an /effort run set, read off the line it printed (`Set effort level to high …`, `Effort level set to auto`). */
200export function effortSet(text: string): string {
201 return /(?:set effort level to|effort level set to)\s+([a-z]+)/i.exec(String(text || ''))?.[1]?.toLowerCase() ?? ''
202}
203
204/**
205 * The files a prompt names with @ (`@src/a.ts`, `@"notes/my file.md"`), as the terminal takes them: at the start or
206 * after a space, an opening bracket or Japanese punctuation (not inside a word, so mail@example.com is no mention),
207 * ten at most, each once.
208 */
209export function mentionsOf(text: string): string[] {
210 const out: string[] = []
211 const re = /(^|[\s((「『【、。,.:;])@(?:"([^"\n]+)"|([^\s"]+))/g
212 // a quoted line (one the screen quoted from the conversation, or any "> ") names nothing: it is what was said then
213 const said = String(text || '').split('\n').filter(l => !/^\s*>/.test(l)).join('\n')
214 let m: RegExpExecArray | null
215 while ((m = re.exec(said)) && out.length < 10) {
216 let p = (m[2] ?? m[3] ?? '').trim()
217 // 「@a.ts、@b.ts」: a mark of Japanese punctuation right before another @ ends this one, and the next starts there
218 const k = m[3] ? p.search(/[、。,.:;)」』】]@/) : -1
219 if (k > 0) { p = p.slice(0, k); re.lastIndex = m.index + m[1]!.length + 1 + k }
220 if (p && !out.includes(p)) out.push(p)
221 }
222 return out
223}
224
225/**
226 * The spellings a mention may stand for, longest first: as written, without the punctuation that follows it in a
227 * sentence, and its plain-path head (`@src/a.tsを直して` names src/a.ts; a path with Japanese in it is tried whole first).
228 */
229export function mentionCandidates(p: string): string[] {
230 const out = [p]
231 const trimmed = p.replace(/[,.;:!?)\]}」』】、。,.!?)]+$/u, ''); if (trimmed && !out.includes(trimmed)) out.push(trimmed)
232 // a name in Japanese runs into the sentence (`@売上.xlsxを見て`): it ends after an extension
233 const ends = [...p.matchAll(/\.[A-Za-z0-9]{1,10}(?=[^A-Za-z0-9]|$)/g)].map(m => m.index! + m[0].length).reverse()
234 for (const e of ends) { const c = p.slice(0, e); if (!out.includes(c)) out.push(c) }
235 const head = /^[\w./~@+#%=,-]+/.exec(p)?.[0]?.replace(/[,.]+$/, ''); if (head && !out.includes(head)) out.push(head)
236 return out
237}
238
239/** A file's text as the Read tool shows it to the model: numbered lines, long ones cut, at most `maxLines` and `maxChars`. */
240export function numbered(text: string, maxLines: number, maxChars: number): { body: string; lines: number; shown: number } {
241 const all = String(text).replace(/\r\n?/g, '\n').replace(/\n$/, '').split('\n')
242 const out: string[] = []
243 let size = 0
244 for (let i = 0; i < all.length && i < maxLines; i++) {
245 const l = all[i]!.length > 2000 ? all[i]!.slice(0, 2000) + '…' : all[i]!
246 const row = `${String(i + 1).padStart(6)}\t${l}`
247 if (size + row.length > maxChars && out.length) break
248 out.push(row); size += row.length + 1
249 }
250 return { body: out.join('\n'), lines: all.length, shown: out.length }
251}
252
253/** A converted file's text (a workbook, a document) as it goes to the model: whole lines up to `maxChars`, unnumbered. */
254export function cutText(text: string, maxChars: number): { body: string; lines: number; shown: number; cut: boolean } {
255 const all = String(text).replace(/\r\n?/g, '\n').replace(/\n+$/, '').split('\n')
256 const out: string[] = []
257 let size = 0, cut = false
258 for (const l of all) {
259 if (size + l.length + 1 > maxChars) { if (!out.length) out.push(l.slice(0, Math.max(0, maxChars - 1)) + '…'); cut = true; break }
260 out.push(l); size += l.length + 1
261 }
262 return { body: out.join('\n'), lines: all.length, shown: out.length, cut }
263}
264
265/** A longer text kept with its line breaks (a skill's description): trimmed, blank runs closed up, cut at `n`. */
266export function keepText(s: string, n: number): string {
267 const t = s.replace(/\r\n?/g, '\n').replace(/[ \t]+\n/g, '\n').replace(/\n{3,}/g, '\n\n').trim()
268 return t.length > n ? t.slice(0, n - 1) + '…' : t
269}
270
271/** A question Claude asks with AskUserQuestion, as the screen draws it. Options keep their places, so a pick is an index. */
272export type Question = { q: string; h: string; multi: boolean; opts: { l: string; d: string }[] }
273export function questionsOf(a: Args): Question[] {
274 const qs = Array.isArray(a.questions) ? (a.questions as Args[]) : []
275 return qs.slice(0, 4).map(x => ({
276 q: keepText(str(x?.question), 600), h: clip(str(x?.header), 40), multi: x?.multiSelect === true,
277 opts: (Array.isArray(x?.options) ? (x.options as Args[]) : []).slice(0, 8).map(o => ({ l: clip(str(o?.label), 120), d: clip(str(o?.description), 300) })),
278 }))
279}
280/**
281 * The answers a screen sent for a question, in the tool's own terms: each question's text → the chosen
282 * label (several joined with ", ", as the terminal's dialog joins them) or what was typed. Every question
283 * must be answered and every pick must be one of its options; anything else is null.
284 */
285export function answersFor(a: Args, sent: unknown): Record<string, string> | null {
286 const qs = Array.isArray(a.questions) ? (a.questions as Args[]).slice(0, 4) : []
287 if (!qs.length || !Array.isArray(sent) || sent.length !== qs.length) return null
288 const out: Record<string, string> = {}
289 for (let i = 0; i < qs.length; i++) {
290 const x = qs[i]!, s = sent[i] as Args | undefined, q = str(x.question)
291 const opts = Array.isArray(x.options) ? (x.options as Args[]) : []
292 const pick = Array.isArray(s?.pick) ? [...new Set(s.pick as unknown[])] : []
293 if (pick.some(n => !Number.isInteger(n) || (n as number) < 0 || (n as number) >= Math.min(opts.length, 8))) return null
294 if (!x.multiSelect && pick.length > 1) return null
295 const labels = (pick as number[]).sort((m, n) => m - n).map(n => str(opts[n]?.label)).filter(Boolean)
296 const typed = str(s?.text).trim().slice(0, 4000)
297 const v = x.multiSelect ? [...labels, ...(typed ? [typed] : [])].join(', ') : typed || labels[0] || ''
298 if (!q || !v) return null
299 out[q] = v
300 }
301 return out
302}
303
304/** Where a skill or an agent was defined, in the screen's words. */
305export function srcLabel(source: string, plugin?: string): string {
306 if (plugin) return `プラグイン ${plugin}`
307 switch (source) {
308 case 'userSettings': case 'user': return '~/.claude'
309 case 'projectSettings': case 'project': return '.claude'
310 case 'localSettings': return '.claude(ローカル)'
311 case 'policySettings': case 'managed': case 'policy': return '組織'
312 case 'plugin': return 'プラグイン'
313 case 'bundled': case 'builtin': case 'built-in': return '組み込み'
314 default: return source || '—'
315 }
316}
317
318/** A project's own (.claude in the repository) as against everywhere's (~/.claude, plugins, built in, the organization). */
319export function isLocalSrc(src: unknown): boolean { return /^\.claude/.test(String(src ?? '')) }
320
321export type Reading = { kind: string; percentUsed: number; resetsAt?: string }
322export type Forecast = { pc: number; proj?: number; hit?: number | null } | null
323
324function hhmm(t: number): string {
325 const d = new Date(t)
326 return `${d.getHours()}:${String(d.getMinutes()).padStart(2, '0')}`
327}
328
329/** The terminal's status line. */
330export function statusLine(o: { num: number; ready: boolean; ctx?: number; limits: Reading[]; usd?: number; forecast: Forecast; pair?: string }): string {
331 const parts: string[] = [o.ready ? `Fogcast ch.${o.num}` : 'Fogcast 未接続']
332 // while a browser is being paired, its code leads the line (the band above the prompt shows it too)
333 if (o.ready && o.pair) parts.push(`合言葉 ${o.pair}(Fogcast の画面に入力)`)
334 if (o.ctx !== undefined) parts.push(`ctx ${o.ctx}%`)
335 for (const w of o.limits) {
336 if (w.kind === 'five_hour') {
337 const f = o.forecast
338 const tail = f && f.hit ? ` → ${hhmm(f.hit)} に上限` : f && f.proj !== undefined ? ` → 予報 ${Math.min(100, f.proj)}%` : ''
339 parts.push(`5h ${w.percentUsed}%${tail}`)
340 } else if (w.kind === 'seven_day') parts.push(`7d ${w.percentUsed}%`)
341 }
342 if (o.usd !== undefined) parts.push(`$${o.usd.toFixed(2)}`)
343 parts.push('/fog で画面')
344 return parts.join(' · ')
345}
346
347/** Whether a version string is older than another (x.y.z); anything unreadable is not, so it is left alone. */
348export function older(v: unknown, than: string): boolean {
349 const p = (s: string) => s.split('.').map(n => parseInt(n, 10) || 0)
350 if (typeof v !== 'string' || !/^\d+\.\d+\.\d+/.test(v)) return false
351 const a = p(v), b = p(than)
352 for (let i = 0; i < 3; i++) if (a[i] !== b[i]) return (a[i] ?? 0) < (b[i] ?? 0)
353 return false
354}
355