Counts permission dialogs per rule and, after repeated approvals, offers to add the rule to permissions.allow, asking before it writes

Counts the permission dialogs you answer, per rule, and offers the rules you keep approving. It writes nothing until you pick a file to add the rule to in a dialog.
●●●○○ 3/5, and how many are left. No line for a rule under permissions.ask or permissions.deny, or already allowed: no offer is coming.Bash(./mvnw test:*) 5 times here. /allowlist to add it to permissions.allow."/allowlist opens a pane with every rule, numbered: ready ones first, then by approvals. Each rule shows its status, approvals and refusals (or ●●●○○ 3/5 while it counts), and under it the last call that asked and when (e.g. ./mvnw test -pl core · 12 min ago). A risky rule says why: (runs rm), (the whole tool), (a broad wildcard).all · ready · counting · refused, each with its count) and a filter that matches the rule or the call that asked narrow the list. The numbers stay those of the whole list, so /allowlist allow 3 names the same rule whatever shows. The list scrolls with the wheel or ▲ up / ▼ down, under a 11–20 of 34 range.allow on a ready rule; dismiss and reset count on the others; remove from allow on a rule the coach added..claude/settings.local.json (just you), add to .claude/settings.json (shared with the team, committed with the code), or Never offer it. The rest of the file stays as it was./allowlist allow 1, dismiss 1 and remove 1 take the pane's number or the rule written out. /allowlist allow refuses a risky or refused rule, and one under ask or deny, whatever number it is given. /allowlist reset 1 sets one rule's count back to zero; /allowlist reset clears this project's counts. Both ask first, with Cancel first, so a stray Enter keeps them. /allowlist help lists them.allow, dismiss, remove and reset put the command in the prompt for you to finish and send; help answers at once.In /config:
| Option | Default | What it does |
|---|---|---|
language | auto | pt-BR or en for the pane, the line under the dialog, the questions and the toasts. auto follows LANG: Portuguese for pt_*, English otherwise |
threshold | 5 | Approvals, with no refusal, before a rule is offered: 2 to 20 |
The rule is the one the engine itself suggests for "Yes, and don't ask again" (so ./mvnw test -Dtest=A and ./mvnw test -Dtest=B count as one Bash(./mvnw test:*)). When the engine suggests none, the rule is the exact command, or WebFetch(domain:<host>).
Bash, Edit, Write, Read, WebFetch) or a broad wildcard: Bash(), Read(/), a path wildcard that starts at //, ~, .. or (Read(~/), Edit(/)), and a command with a * anywhere but at its end (Bash(ls *.txt)).rm, sudo, chmod, curl, ssh, git push, git reset, bash -c, node, node *, python3 -m *, … | sh, --force, and the like. These are counted and shown as risky.permissions.ask or permissions.deny.PGPASSWORD=…, --password …, an Authorization header, a URL with a password, a known key prefix): it is not counted, so its command is never stored.Dialogs that a settings hook answered, and decisions made in auto, dontAsk or bypassPermissions mode, are not counted: they are not your answer.
/plugin install allowlist-coach --marketplace ice-lfernandes/claude-code-mods
Or for one session: claude --plugin-dir ./allowlist-coach
| Mod | Network | Runs processes | Files | Calls a model | Sends data anywhere |
|---|---|---|---|---|---|
| allowlist-coach | No | No | Reads and writes .claude/settings.local.json, or .claude/settings.json when you pick it, after you confirm | No | No |
It keeps the counts in its plugin store, per project root, across sessions: the rule, approvals, refusals, the last command or path that asked, and when. Up to 200 rules per project. It reads LANG for the auto language. It writes only a plain file in the project's own .claude/ folder: when the settings file or that folder is a symbolic link, it leaves it as it was.
hooks/register.tsx 468 lines1// allowlist-coach: counts permission dialogs per rule and offers the ones you keep approving.
2//
3// counting tool.call opens a record for each call; classic.PermissionRequest marks the ones
4// whose dialog the person answers (a classic hook's own decision, or auto mode,
5// is not the person); classic.PostToolUse(Failure) marks the ones that ran. When
6// the call resolves, an asked call that ran is an approval, one that did not, a
7// refusal. Counts live in $.store per project root, across sessions.
8// dialog a line under the open dialog: approvals so far, `●●●○○ 3/5`, toward the offer.
9// toast once, when a rule reaches `threshold` approvals (5 by default) with no refusal.
10// /allowlist pane with every rule, numbered, ready ones first, each with the last call that
11// asked and when, and its actions: allow, dismiss, reset count, remove from allow.
12// Tabs and a filter narrow the list; it scrolls. /allowlist allow <n> | dismiss <n>
13// | remove <n> | reset [<n>] | help, where <n> is the pane's number or the rule.
14//
15// It writes the project's .claude/settings.local.json, or its .claude/settings.json when the
16// person picks that file, and only after the person picks one in a dialog. It takes a rule
17// out of allow only after the person picks "Remove". Reset clears counts only after the person
18// picks "Clear" or "Reset". It never offers or adds a rule that is a whole tool, a broad
19// wildcard, or a command that deletes, escalates or reaches the network (tally.riskOf), and
20// never one the person refused or put under ask or deny.
21
22import { atom, read, update } from 'claude-code'
23import type { EngineInterface, Register } from 'claude-code'
24
25import type { Configured, Entry, Tab } from '../types'
26import {
27 addAllow,
28 exampleOf,
29 holdsSecret,
30 keyAt,
31 keyOf,
32 noticeFor,
33 progress,
34 record,
35 removeAllow,
36 riskOfEntry,
37 rulesFor,
38 setState,
39 setThreshold,
40 SETTINGS_FILE,
41 SHARED_FILE,
42 shows,
43 sorted,
44 stable,
45 status,
46 summary,
47 TABS,
48 thresholdNow,
49 toConfigured,
50 zero,
51} from './tally'
52import type { Lang, Verb } from './ui'
53import { clip, fillArgs, langOf, linesOf, verbRow, windowOf } from './ui'
54import { COMMAND, WORDS } from './words'
55
56const PANE = 'allowlist'
57/** Modes where a dialog is not the person's answer, or is not shown at all. */
58const NOT_THE_PERSON = new Set(['auto', 'dontAsk', 'bypassPermissions'])
59
60const entries = atom({ plugin: 'allowlist-coach', key: 'entries' } as const, {} as Record<string, Entry>)
61const configured = atom({ plugin: 'allowlist-coach', key: 'configured' } as const, { allow: [], ask: [], deny: [] } as Configured)
62const offset = atom({ plugin: 'allowlist-coach', key: 'offset' } as const, 0)
63const tab = atom({ plugin: 'allowlist-coach', key: 'tab' } as const, 'all' as Tab)
64const filter = atom({ plugin: 'allowlist-coach', key: 'filter' } as const, '')
65
66type Open = { tool: string; input: string; agentId?: string; rules: string[] | null; ran: boolean; example: string }
67const open = new Map<string, Open>()
68let root = ''
69// The last first row the list can start at, from the last render: the wheel stops there.
70let lastStart = 0
71// Set by register from the options, and by session.start from the system's LANG.
72let lang: Lang = 'en'
73
74const storeKey = () => `entries:${root}`
75
76const save = async ($: EngineInterface, change: (list: Record<string, Entry>) => Record<string, Entry>) => {
77 await update($, entries, change)
78 await $.store.set(storeKey(), await read($, entries))
79}
80
81const refresh = async ($: EngineInterface) => {
82 try {
83 const settings = await $.settings.read()
84 await update($, configured, () => toConfigured(settings as never))
85 } catch {
86 // Keep the lists read last.
87 }
88}
89
90const argsOf = (e: Record<string, unknown>) => {
91 const { tool, tool_use_id, agentId, consent, ...args } = e
92 return args
93}
94
95/** Asks with Cancel first, so a stray Enter changes nothing; true only on `yes`. */
96const confirm = async ($: EngineInterface, question: string, yes: string) => {
97 try {
98 return (await $.ui.ask(question, { header: 'allowlist', options: [WORDS[lang].cancel, yes] })) === yes
99 } catch {
100 return false
101 }
102}
103
104const where = ($: EngineInterface, path: string) => $.fs.stat(path, { resolve: true }).then(s => s, () => null)
105
106/**
107 * Throws unless the file is a plain file, or nothing yet, in the project's own .claude folder:
108 * a link there, which a cloned repository can hold, would send the rule to another file.
109 */
110const guard = async ($: EngineInterface, file: string) => {
111 const [top, dir, at] = await Promise.all([where($, root), where($, `${root}/.claude`), where($, `${root}/${file}`)])
112 if (dir && (dir.isLink || !top?.realPath || dir.realPath !== `${top.realPath}/.claude`)) throw new Error('.claude is a link; the coach writes only a plain file')
113 if (at && (at.isLink || at.kind !== 'file')) throw new Error(`${file} is a link or not a file; the coach writes only a plain file`)
114}
115
116/** A settings file's text through `change`, written back unless `change` returns null. Throws as addAllow does, and on a link. */
117const edit = async ($: EngineInterface, file: string, change: (text: string) => string | null) => {
118 await guard($, file)
119 const path = `${root}/${file}`
120 const text = (await $.fs.exists(path)) ? String(await $.fs.read(path)) : ''
121 const next = change(text)
122 if (next !== null) await $.fs.write(path, next)
123 return next !== null
124}
125
126/**
127 * Asks, showing the line it adds, then adds the entry's rules to settings.local.json or, when
128 * the person picks it, the shared settings.json. Returns what to tell the person.
129 */
130const allow = async ($: EngineInterface, key: string): Promise<string> => {
131 const w = WORDS[lang]
132 const entry = (await read($, entries))[key]
133 if (!entry) return w.noRule(key)
134 // The command takes any number, and the list re-sorts as calls are counted: check it again here.
135 const s = status(entry, await read($, configured))
136 if (s === 'risky' || s === 'refused' || s === 'pinned') {
137 const risk = s === 'risky' ? riskOfEntry(entry) : null
138 return w.notOffered(key, risk ? `${w.status[s]} (${w.risk(risk)})` : w.status[s])
139 }
140 const what = entry.rules.join(' and ')
141 let answer: string
142 try {
143 // Not now first, so a stray Enter writes nothing.
144 answer = await $.ui.ask(`${w.askAdd(what, entry.approved)}\n${w.preview(entry.rules)}`, { header: 'allowlist', options: [w.notNow, w.addLocal, w.addShared, w.never] })
145 } catch {
146 return w.nothingChanged
147 }
148 if (answer === w.never) {
149 await save($, list => setState(list, key, 'dismissed'))
150 return w.neverAgain(what)
151 }
152 const file = answer === w.addLocal ? SETTINGS_FILE : answer === w.addShared ? SHARED_FILE : null
153 if (!file) return w.nothingChanged
154 try {
155 await edit($, file, text => addAllow(text, entry.rules, file))
156 } catch (error) {
157 return w.leftAsIs(file, error instanceof Error ? error.message : String(error))
158 }
159 await save($, list => setState(list, key, 'added', file))
160 await refresh($)
161 return w.added(what, file)
162}
163
164/** Asks, then takes the rules the coach added out of the file it added them to; the rule is not offered again. */
165const remove = async ($: EngineInterface, key: string): Promise<string> => {
166 const w = WORDS[lang]
167 const entry = (await read($, entries))[key]
168 if (!entry) return w.noRule(key)
169 if (entry.state !== 'added') return w.notAdded(key)
170 const what = entry.rules.join(' and ')
171 const file = entry.file ?? SETTINGS_FILE
172 if (!(await confirm($, w.askRemove(what, file), w.removeOpt))) return w.nothingChanged
173 let changed: boolean
174 try {
175 changed = await edit($, file, text => removeAllow(text, entry.rules, file))
176 } catch (error) {
177 return w.leftAsIs(file, error instanceof Error ? error.message : String(error))
178 }
179 if (!changed) return w.notInFile(what, file)
180 await save($, list => setState(list, key, 'dismissed'))
181 await refresh($)
182 return w.removed(what, file)
183}
184
185/** Asks, then sets one rule's counts back to zero. */
186const zeroOne = async ($: EngineInterface, key: string): Promise<string> => {
187 const w = WORDS[lang]
188 const entry = (await read($, entries))[key]
189 if (!entry) return w.noRule(key)
190 if (!(await confirm($, w.askZero(key, entry.approved, entry.denied), w.zeroOpt))) return w.nothingChanged
191 await save($, list => zero(list, key))
192 return w.zeroed(key)
193}
194
195const dismiss = async ($: EngineInterface, key: string) => {
196 const w = WORDS[lang]
197 if (!(await read($, entries))[key]) return w.noRule(key)
198 await save($, list => setState(list, key, 'dismissed'))
199 return w.neverAgain(key)
200}
201
202/** Asks, with Cancel first so a stray Enter keeps the counts, then clears them. */
203const reset = async ($: EngineInterface) => {
204 const w = WORDS[lang]
205 const n = Object.keys(await read($, entries)).length
206 if (n === 0) return w.noDialogs
207 if (!(await confirm($, w.askReset(n), w.clear))) return w.nothingChanged
208 await save($, () => ({}))
209 return w.cleared
210}
211
212/** /allowlist and its arguments: what the command answers, and what the pane's verbs run. */
213const runCommand = async ($: EngineInterface, args: string): Promise<{ text?: string }> => {
214 const w = WORDS[lang]
215 const [verb = '', ...rest] = args.trim().split(/\s+/)
216 const arg = rest.join(' ')
217 const key = async () => keyAt(await read($, entries), await read($, configured), arg)
218 switch (verb.toLowerCase()) {
219 case 'allow':
220 if (arg) return { text: await allow($, await key()) }
221 break
222 case 'dismiss':
223 if (arg) return { text: await dismiss($, await key()) }
224 break
225 case 'remove':
226 if (arg) return { text: await remove($, await key()) }
227 break
228 case 'reset':
229 return { text: arg ? await zeroOne($, await key()) : await reset($) }
230 case 'help':
231 return { text: w.help }
232 case '': {
233 await refresh($)
234 const opened = await $.ui.open({ id: PANE, title: w.pane, focus: true, closeOnEscape: true }).catch(() => null)
235 if (opened?.isPlaced) return {}
236 return { text: summary(await read($, entries), await read($, configured), lang) }
237 }
238 }
239 return { text: w.help }
240}
241
242/** Puts a text in the prompt for the person to send; runs nothing. */
243const fill = async ($: EngineInterface, text: string) => {
244 await $.prompt.fill(fillArgs(text))
245}
246
247/** The pane's verbs: those that take a number, and reset, wait in the prompt. */
248const verbs = (l: Lang): readonly Verb[] => {
249 const n = l === 'en' ? '[number]' : '[número]'
250 return [
251 { verb: 'allow', fill: `/${COMMAND} allow ${n}` },
252 { verb: 'dismiss', fill: `/${COMMAND} dismiss ${n}` },
253 { verb: 'remove', fill: `/${COMMAND} remove ${n}` },
254 { verb: 'reset', fill: `/${COMMAND} reset` },
255 { verb: 'help' },
256 ]
257}
258
259/** A verb pressed in the pane: fills the prompt, or runs and writes its answer to the transcript. */
260const pressVerb = async ($: EngineInterface, v: Verb) => {
261 try {
262 if (v.fill) return await fill($, v.fill)
263 const { text } = await runCommand($, v.verb)
264 for (const line of linesOf(text)) $.ui.log(line)
265 } catch {
266 $.ui.toast(WORDS[lang].failedToRun(`/${COMMAND} ${v.verb}`))
267 }
268}
269
270export const register: Register = (on, options) => {
271 lang = langOf(options.language)
272 setThreshold(options.threshold)
273
274 on('session.start', async ($, e, next) => {
275 const result = await next(e)
276 lang = langOf(options.language, await $.env.get('LANG').catch(() => undefined))
277 await $.command.register({
278 name: COMMAND,
279 description: WORDS[lang].description,
280 argumentHint: '[allow <n>|dismiss <n>|remove <n>|reset [<n>]|help]',
281 immediate: true,
282 })
283 root = await $.session.root()
284 const stored = (await $.store.get(storeKey())) as Record<string, Entry> | undefined
285 await update($, entries, () => stored ?? {})
286 await refresh($)
287 return result
288 })
289
290 on('tool.call', async ($, e, next) => {
291 const id = e.tool_use_id
292 if (!id) return next(e)
293 const input = argsOf(e as never)
294 open.set(id, { tool: e.tool, input: stable(input), agentId: e.agentId, rules: null, ran: false, example: exampleOf(e.tool, input) })
295 let result
296 try {
297 result = await next(e)
298 } catch (error) {
299 open.delete(id)
300 throw error
301 }
302 const call = open.get(id)
303 open.delete(id)
304 if (!call?.rules) return result
305 const key = keyOf(call.rules)
306 const was = (await read($, entries))[key]
307 const before = was ? status(was, await read($, configured)) : 'counting'
308 const now = await $.clock.now()
309 await save($, list => record(list, call.rules!, call.ran, call.example, now))
310 await refresh($)
311 const entry = (await read($, entries))[key]!
312 if (before !== 'ready' && entry.state === 'counting' && status(entry, await read($, configured)) === 'ready') {
313 await save($, list => setState(list, key, 'offered'))
314 $.ui.toast(WORDS[lang].offered(key, entry.approved), { timeoutMs: 10000 })
315 }
316 return result
317 }).catch(($, e, next) => next(e))
318
319 on('classic.PermissionRequest', async ($, e, next) => {
320 const result = await next(e)
321 if (result.decision) return result
322 if (e.permission_mode && NOT_THE_PERSON.has(e.permission_mode)) return result
323 const input = stable(e.tool_input)
324 for (const [id, call] of open) {
325 if (call.rules || call.tool !== e.tool_name || call.input !== input || call.agentId !== e.agent_id) continue
326 const rules = rulesFor(e.tool_name, e.tool_input, e.permission_suggestions)
327 // A call that carries a credential is left uncounted, so it is never stored.
328 if (holdsSecret(call.input) || rules.some(holdsSecret)) break
329 call.rules = rules
330 const text = noticeFor((await read($, entries))[keyOf(call.rules)], await read($, configured), lang)
331 if (text) {
332 try {
333 $.ui.notice(id, text)
334 } catch {
335 // No dialog open for it on this host.
336 }
337 }
338 break
339 }
340 return result
341 }).catch(($, e, next) => next(e))
342
343 on('classic.PostToolUse', async ($, e, next) => {
344 const call = open.get(e.tool_use_id)
345 if (call) call.ran = true
346 return next(e)
347 }).catch(($, e, next) => next(e))
348
349 on('classic.PostToolUseFailure', async ($, e, next) => {
350 const call = open.get(e.tool_use_id)
351 if (call) call.ran = true
352 return next(e)
353 }).catch(($, e, next) => next(e))
354
355 on('command.run', { command: COMMAND }, ($, e) => runCommand($, e.args))
356
357 // The wheel over the pane moves the list.
358 on('ui.scroll', { component: 'Pane', requestId: PANE }, async ($, e) => {
359 await update($, offset, o => Math.max(0, Math.min(lastStart, o + e.by)))
360 return {}
361 }).catch(($, e, next) => next(e))
362
363 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
364 const els = $.ui.resolve(e)
365 const { Box, Text, Button } = els
366 // The mobile app draws no field yet: there the list shows unfiltered.
367 const Input = 'Input' in els ? els.Input : null
368 const w = WORDS[lang]
369 const now = await $.clock.now()
370 const rows = sorted(await read($, entries), await read($, configured))
371 const width = Math.max(40, (e.props.bodyColumns || e.viewport?.columns || 80) - 2)
372 const picked = await read($, tab)
373 const query = Input ? await read($, filter) : ''
374 // Numbered over every rule, as /allowlist allow <n> reads the number, whatever shows.
375 const numbered = rows.map((r, i) => ({ ...r, n: i + 1 }))
376 const found = numbered.filter(r => shows(r, picked, query))
377 // Two lines a rule. The rest of the pane: hint, tabs, filter, scroll row, footer, gaps.
378 const fixed = 11
379 const listRows = Math.max(2, Math.floor(((e.props.scroll?.bodyRows ?? e.viewport?.rows ?? 30) - fixed) / 2))
380 const view = windowOf(found.length, await read($, offset), listRows)
381 lastStart = Math.max(0, found.length - listRows)
382 const scrollList = (by: number) => update($, offset, o => windowOf(found.length, o + by, listRows).start)
383 const pickTab = async (t: Tab) => {
384 await update($, tab, () => t)
385 await update($, offset, () => 0)
386 }
387 const toast = (text: Promise<string>) => text.then(t => $.ui.toast(t))
388 const count = (t: Tab) => (t === 'all' ? rows.length : rows.filter(r => r.status === t).length)
389
390 return (
391 <Box flexDirection="column" paddingX={1} gap={1}>
392 <Text dimColor>{w.hint(root || '.', thresholdNow())}</Text>
393 {rows.length === 0 && <Text dimColor>{w.empty}</Text>}
394 {rows.length > 0 && (
395 <Box flexDirection="column">
396 <Box flexDirection="row" flexWrap="wrap" gap={2}>
397 {TABS.map(t => (
398 <Button key={`tab:${t}`} plain dimColor={t !== picked} label={`${t === picked ? '▸ ' : ''}${w.tabs[t]} ${count(t)}`} onPress={() => pickTab(t)} />
399 ))}
400 </Box>
401 {Input && (
402 <Input
403 key="filter"
404 label={w.filter}
405 placeholder={w.placeholder}
406 value={query}
407 onInput={async (value: string) => {
408 await update($, filter, () => value)
409 await update($, offset, () => 0)
410 }}
411 onSubmit={(value: string) => update($, filter, () => value)}
412 />
413 )}
414 </Box>
415 )}
416 {rows.length > 0 && (
417 <Box flexDirection="column">
418 {found.length === 0 && <Text dimColor>{w.noMatch}</Text>}
419 {found.slice(view.start, view.end).map(r => {
420 const risk = r.status === 'risky' ? riskOfEntry(r.entry) : null
421 const canDismiss = r.status === 'ready' || r.status === 'counting' || r.status === 'refused' || r.status === 'risky'
422 const hasCounts = r.entry.approved + r.entry.denied > 0 && r.entry.state !== 'added'
423 return (
424 <Box key={`row:${r.key}`} flexDirection="column">
425 <Box flexDirection="row" gap={1}>
426 <Text dimColor>{String(r.n).padStart(2)}</Text>
427 <Text color={r.status === 'ready' ? 'success' : r.status === 'risky' || r.status === 'refused' ? 'warning' : undefined} dimColor={r.status !== 'ready' && r.status !== 'risky' && r.status !== 'refused'}>
428 {w.status[r.status].padEnd(10)}
429 </Text>
430 {r.status === 'counting' ? (
431 <Text color="claude">{progress(r.entry.approved)}</Text>
432 ) : (
433 <Text>
434 <Text>{`✓${String(r.entry.approved).padStart(3)} `}</Text>
435 <Text color={r.entry.denied > 0 ? 'warning' : undefined}>{`✗${String(r.entry.denied).padStart(3)}`}</Text>
436 </Text>
437 )}
438 <Text wrap="truncate-end">{r.key}</Text>
439 {risk && <Text color="warning" wrap="truncate-end">{`(${w.risk(risk)})`}</Text>}
440 {r.status === 'ready' && <Button key={`allow-${r.n}`} label={w.allow} onPress={() => toast(allow($, r.key))} />}
441 </Box>
442 <Box flexDirection="row" gap={2}>
443 <Text dimColor wrap="truncate-end">{` ${clip(w.example(r.entry.example, w.ago(now - r.entry.lastAt)), Math.max(20, width - 44))}`}</Text>
444 {canDismiss && <Button key={`dismiss-${r.n}`} label={w.dismiss} plain dimColor onPress={() => toast(dismiss($, r.key))} />}
445 {hasCounts && <Button key={`zero-${r.n}`} label={w.resetCount} plain dimColor onPress={() => toast(zeroOne($, r.key))} />}
446 {r.entry.state === 'added' && <Button key={`remove-${r.n}`} label={w.remove} plain dimColor onPress={() => toast(remove($, r.key))} />}
447 </Box>
448 </Box>
449 )
450 })}
451 {found.length > listRows && (
452 <Box flexDirection="row" gap={2}>
453 <Button key="list:up" plain dimColor={view.start === 0} label={w.up} onPress={() => scrollList(-listRows + 1)} />
454 <Button key="list:down" plain dimColor={view.end === found.length} label={w.down} onPress={() => scrollList(listRows - 1)} />
455 <Text dimColor>{w.range(view.start + 1, view.end, found.length)}</Text>
456 </Box>
457 )}
458 </Box>
459 )}
460 <Box flexDirection="row" flexWrap="wrap" gap={2}>
461 {verbRow({ Box, Text, Button }, COMMAND, verbs(lang), v => pressVerb($, v))}
462 <Button key="close" role="dismiss" label={w.close} onPress={() => $.ui.close({ id: PANE })} />
463 </Box>
464 </Box>
465 )
466 })
467}
468hooks/tally.ts 293 lines1import type { Configured, Entry, Tab } from '../types'
2import type { Lang } from './ui'
3import { clip } from './ui'
4import { WORDS } from './words'
5
6/** Approvals, with no refusal, before the coach offers a rule: the default of the `threshold` option. */
7export const THRESHOLD = 5
8
9let threshold = THRESHOLD
10
11/** Sets the approvals an offer takes, from the `threshold` option: a whole number from 2 to 20. */
12export const setThreshold = (option: unknown) => {
13 const n = Math.round(Number(option))
14 threshold = Number.isFinite(n) && option !== undefined && option !== null && option !== '' ? Math.max(2, Math.min(20, n)) : THRESHOLD
15}
16
17/** The approvals an offer takes now. */
18export const thresholdNow = () => threshold
19/** Entries kept per project; the least recent go first. */
20export const ENTRIES_KEPT = 200
21
22export const SETTINGS_FILE = '.claude/settings.local.json'
23/** The project's shared settings, committed with the code. */
24export const SHARED_FILE = '.claude/settings.json'
25
26type Suggestion = { type: string; behavior?: string; rules?: readonly { toolName: string; ruleContent?: string }[] }
27
28export const formatRule = (toolName: string, content?: string) => (content ? `${toolName}(${content})` : toolName)
29
30const host = (url: unknown) => {
31 try {
32 return new URL(String(url)).hostname
33 } catch {
34 return ''
35 }
36}
37
38/**
39 * The rules that would have skipped this dialog: the engine's own suggestion when it made one
40 * (what "Yes, and don't ask again" would save), else a narrow rule of our own.
41 */
42export const rulesFor = (tool: string, input: unknown, suggestions?: readonly Suggestion[]): string[] => {
43 const offered = (suggestions ?? [])
44 .filter(s => s.type === 'addRules' && s.behavior === 'allow')
45 .flatMap(s => s.rules ?? [])
46 .map(r => formatRule(r.toolName, r.ruleContent))
47 if (offered.length > 0) return [...new Set(offered)]
48 const args = (input ?? {}) as Record<string, unknown>
49 if (tool === 'Bash' && typeof args.command === 'string') return [formatRule('Bash', args.command.trim())]
50 if (tool === 'WebFetch' && host(args.url)) return [formatRule('WebFetch', `domain:${host(args.url)}`)]
51 return [tool]
52}
53
54const SECRET = [
55 /\b[\w.-]*(token|secret|passw(or)?d|pwd|api[_-]?key|access[_-]?key|private[_-]?key|credentials?)[\w.-]*\s*[=:]\s*\S/i,
56 /--?(password|passwd|token|secret|api-?key)\s+\S/i,
57 /\bauthorization\s*:|\bbearer\s+\S{8}/i,
58 /[a-z][\w+.-]*:\/\/[^\s/@:]+:[^\s/@]+@/i,
59 /\b(sk-[\w-]{16}|gh[pousr]_\w{20}|github_pat_|AKIA[0-9A-Z]{16}|xox[abprs]-|AIza[\w-]{20})/,
60]
61
62/**
63 * Whether a call's input looks like it holds a credential: a token, password or key set or
64 * passed, an Authorization header, a URL with a password, a known key prefix. Such a call is
65 * not counted, so its command is never stored nor offered for a settings file.
66 */
67export const holdsSecret = (text: string) => SECRET.some(re => re.test(text))
68
69/** One short line for the call that asked. */
70export const exampleOf = (tool: string, input: unknown) => {
71 const args = (input ?? {}) as Record<string, unknown>
72 const text = String(args.command ?? args.file_path ?? args.notebook_path ?? args.url ?? args.pattern ?? args.query ?? tool)
73 const line = text.split('\n')[0]!.trim()
74 return line.length > 80 ? `${line.slice(0, 79)}…` : line
75}
76
77const BROAD_TOOLS = new Set(['Bash', 'PowerShell', 'Edit', 'Write', 'MultiEdit', 'NotebookEdit', 'Read', 'Glob', 'Grep', 'WebFetch'])
78const PATH_TOOLS = new Set(['Edit', 'Write', 'MultiEdit', 'NotebookEdit', 'Read', 'Glob', 'Grep'])
79
80/** Why a rule is never offered: the whole tool, a broad wildcard, a risky command, or a rule it cannot read. */
81export type Risk = { kind: 'tool' } | { kind: 'wildcard' } | { kind: 'command'; what: string } | { kind: 'unreadable' }
82
83const RISKY_COMMAND = [
84 /^(sudo|su|doas)\b/,
85 /^(rm|rmdir|dd|mkfs\S*|shred|truncate|chmod|chown|kill|pkill|killall|shutdown|reboot)\b/,
86 /^(curl|wget|ssh|scp|rsync|nc|eval|exec|source)\b/,
87 // An interpreter alone, with -c or -e, or with only flags before a wildcard (`node *`, `python3 -m :*`).
88 /^(bash|sh|zsh|fish|python\d*|node|deno|bun|ruby|perl)(\s+-[ce]\b|\s*$|(\s+-\S+)*\s*:?\*)/,
89 /^git\s+(push|reset|clean|rebase|filter-branch|update-ref)\b/,
90 /^git\s+(checkout|restore)\s+(--\s+)?\.\s*$/,
91 /^git\s+branch\s+-D\b/,
92 /^(docker|kubectl|helm|terraform|aws|gcloud|az)\b.*\b(rm|delete|destroy|prune|apply)\b/,
93 /^(npm|pnpm|yarn)\s+publish\b/,
94 /--force\b|\s-f\b.*\bpush\b/,
95 /\|\s*(sudo\s+)?(sh|bash|zsh)\b/,
96]
97
98/**
99 * Why a rule lets through more than one familiar command, or null when it does not: a whole
100 * tool, a broad wildcard, or a command that deletes, escalates, reaches the network or runs
101 * arbitrary code (`what` is the part that matched). Such a rule is counted and shown, never
102 * offered.
103 */
104export const riskOf = (rule: string): Risk | null => {
105 const match = /^([^(]+)(?:\((.*)\))?$/s.exec(rule)
106 if (!match) return { kind: 'unreadable' }
107 const [, toolName, content] = match
108 if (content === undefined) return BROAD_TOOLS.has(toolName!) ? { kind: 'tool' } : null
109 const body = content.trim()
110 if (body === '' || body === '*' || body === ':*' || body === '**' || body.startsWith('/**')) return { kind: 'wildcard' }
111 // A path wildcard that starts outside the project: the filesystem root, home, a parent, or any folder.
112 if (PATH_TOOLS.has(toolName!)) return body.includes('*') && /^(\/\/|~|\.\.|\*\*)/.test(body) ? { kind: 'wildcard' } : null
113 if (toolName !== 'Bash' && toolName !== 'PowerShell') return null
114 for (const re of RISKY_COMMAND) {
115 const hit = re.exec(body)
116 if (hit) return { kind: 'command', what: clip(hit[0].replace(/\s+/g, ' ').trim(), 24) }
117 }
118 // A command takes one wildcard only, at the end after a space or a colon (`npm run test:*`).
119 const star = body.indexOf('*')
120 if (star !== -1 && !(star === body.length - 1 && /[\s:]\*$/.test(body))) return { kind: 'wildcard' }
121 return null
122}
123
124export const isRisky = (rule: string) => riskOf(rule) !== null
125
126/** The first risk among an entry's rules. */
127export const riskOfEntry = (entry: Entry) => entry.rules.map(riskOf).find(r => r !== null) ?? null
128
129const sameRule = (a: string, b: string) => a.replace(/\s+/g, ' ') === b.replace(/\s+/g, ' ')
130const listed = (list: readonly string[], rule: string) => list.some(r => sameRule(r, rule))
131
132export type Status = 'ready' | 'counting' | 'refused' | 'risky' | 'allowed' | 'pinned' | 'dismissed'
133
134/**
135 * Where an entry stands. `allowed`: every rule is in permissions.allow already. `pinned`: one
136 * sits in ask or deny, a choice the coach never argues with. `ready`: offer it.
137 */
138export const status = (entry: Entry, configured: Configured): Status => {
139 if (entry.state === 'added' || entry.rules.every(r => listed(configured.allow, r))) return 'allowed'
140 if (entry.rules.some(r => listed(configured.ask, r) || listed(configured.deny, r))) return 'pinned'
141 if (entry.state === 'dismissed') return 'dismissed'
142 if (entry.rules.some(isRisky)) return 'risky'
143 if (entry.denied > 0) return 'refused'
144 return entry.approved >= threshold ? 'ready' : 'counting'
145}
146
147export const keyOf = (rules: readonly string[]) => rules.join(', ')
148
149/** Counts one answered dialog; drops the least recent entries past ENTRIES_KEPT. */
150export const record = (
151 entries: Record<string, Entry>,
152 rules: readonly string[],
153 approved: boolean,
154 example: string,
155 now: number,
156): Record<string, Entry> => {
157 const key = keyOf(rules)
158 const was = entries[key]
159 const entry: Entry = {
160 rules: [...rules],
161 approved: (was?.approved ?? 0) + (approved ? 1 : 0),
162 denied: (was?.denied ?? 0) + (approved ? 0 : 1),
163 example,
164 lastAt: now,
165 state: was?.state ?? 'counting',
166 }
167 const next = { ...entries, [key]: entry }
168 const keys = Object.keys(next)
169 if (keys.length <= ENTRIES_KEPT) return next
170 const keep = keys.sort((a, b) => next[b]!.lastAt - next[a]!.lastAt).slice(0, ENTRIES_KEPT)
171 return Object.fromEntries(keep.map(k => [k, next[k]!]))
172}
173
174export const setState = (entries: Record<string, Entry>, key: string, state: Entry['state'], file?: string) =>
175 entries[key] ? { ...entries, [key]: { ...entries[key]!, state, ...(file ? { file } : {}) } } : entries
176
177/** An entry's counts back to zero, as if its dialog had never been answered; the rest is kept. */
178export const zero = (entries: Record<string, Entry>, key: string) =>
179 entries[key] ? { ...entries, [key]: { ...entries[key]!, approved: 0, denied: 0, state: 'counting' as const } } : entries
180
181/** Approvals toward the offer: `●●●○○ 3/5`. */
182export const progress = (approved: number) => {
183 const done = Math.max(0, Math.min(threshold, approved))
184 return `${'●'.repeat(done)}${'○'.repeat(threshold - done)} ${done}/${threshold}`
185}
186
187/** The line shown under an open dialog, or undefined when there is nothing to say yet. */
188export const noticeFor = (entry: Entry | undefined, configured: Configured, lang: Lang = 'en') => {
189 if (!entry || entry.approved === 0) return undefined
190 const w = WORDS[lang]
191 const s = status(entry, configured)
192 // Under ask or deny, or allowed already: no offer is coming, so a countdown would mislead.
193 if (s === 'pinned' || s === 'allowed') return undefined
194 if (s === 'risky') return w.noticeRisky(entry.approved)
195 if (s === 'refused') return w.noticeRefused(entry.approved, entry.denied)
196 if (s === 'ready' || s === 'dismissed') return w.noticeReady(entry.approved)
197 return w.noticeCounting(progress(entry.approved), threshold - entry.approved, keyOf(entry.rules))
198}
199
200/** A settings file's permissions, read whole; throws on text that is not a JSON object. */
201const permissionsOf = (text: string, file: string) => {
202 const parsed: unknown = text.trim() === '' ? {} : JSON.parse(text)
203 if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) throw new Error(`${file} is not a JSON object`)
204 const settings = parsed as Record<string, unknown>
205 const permissions = (settings.permissions ?? {}) as Record<string, unknown>
206 if (typeof permissions !== 'object' || Array.isArray(permissions)) throw new Error(`permissions in ${file} is not an object`)
207 if (permissions.allow !== undefined && !Array.isArray(permissions.allow)) throw new Error(`permissions.allow in ${file} is not a list`)
208 return { settings, permissions, allow: [...((permissions.allow as string[] | undefined) ?? [])] }
209}
210
211const write = (settings: Record<string, unknown>, permissions: Record<string, unknown>, allow: string[]) =>
212 `${JSON.stringify({ ...settings, permissions: { ...permissions, allow } }, null, 2)}\n`
213
214/**
215 * The settings file's text with `rules` added to permissions.allow, or null when every rule is
216 * there already. Throws on text that is not a JSON object, so a file it cannot read whole is
217 * never rewritten.
218 */
219export const addAllow = (text: string, rules: readonly string[], file = SETTINGS_FILE): string | null => {
220 const { settings, permissions, allow } = permissionsOf(text, file)
221 const missing = rules.filter(r => !listed(allow, r))
222 if (missing.length === 0) return null
223 return write(settings, permissions, [...allow, ...missing])
224}
225
226/**
227 * The settings file's text with `rules` taken out of permissions.allow, or null when none of
228 * them is there. Throws as addAllow does.
229 */
230export const removeAllow = (text: string, rules: readonly string[], file = SETTINGS_FILE): string | null => {
231 const { settings, permissions, allow } = permissionsOf(text, file)
232 const kept = allow.filter(a => !rules.some(r => sameRule(a, r)))
233 if (kept.length === allow.length) return null
234 return write(settings, permissions, kept)
235}
236
237export const toConfigured = (settings: { permissions?: { allow?: unknown; ask?: unknown; deny?: unknown } } | undefined): Configured => {
238 const list = (v: unknown) => (Array.isArray(v) ? v.filter((r): r is string => typeof r === 'string') : [])
239 return { allow: list(settings?.permissions?.allow), ask: list(settings?.permissions?.ask), deny: list(settings?.permissions?.deny) }
240}
241
242/** JSON with sorted keys, so two copies of one tool input compare equal. */
243export const stable = (value: unknown): string => {
244 if (Array.isArray(value)) return `[${value.map(stable).join(',')}]`
245 if (value !== null && typeof value === 'object') {
246 const obj = value as Record<string, unknown>
247 return `{${Object.keys(obj)
248 .filter(k => obj[k] !== undefined)
249 .sort()
250 .map(k => `${JSON.stringify(k)}:${stable(obj[k])}`)
251 .join(',')}}`
252 }
253 return JSON.stringify(value) ?? 'null'
254}
255
256const ORDER: Status[] = ['ready', 'counting', 'refused', 'risky', 'dismissed', 'pinned', 'allowed']
257
258/** Entries in the order the pane lists them: ready first, then by approvals. */
259export const sorted = (entries: Record<string, Entry>, configured: Configured) =>
260 Object.entries(entries)
261 .map(([key, entry]) => ({ key, entry, status: status(entry, configured) }))
262 .sort((a, b) => ORDER.indexOf(a.status) - ORDER.indexOf(b.status) || b.entry.approved - a.entry.approved || b.entry.lastAt - a.entry.lastAt)
263
264export const TABS: readonly Tab[] = ['all', 'ready', 'counting', 'refused']
265
266/** A sorted row the pane shows under a tab and a typed filter, which matches the rule or the call that asked. */
267export const shows = (row: { key: string; entry: Entry; status: Status }, tab: Tab, query: string) => {
268 if (tab !== 'all' && row.status !== tab) return false
269 const q = query.trim().toLowerCase()
270 return q === '' || row.key.toLowerCase().includes(q) || row.entry.example.toLowerCase().includes(q)
271}
272
273/**
274 * The key an argument of /allowlist allow or dismiss names: a number as the pane numbers the
275 * rules (1 is the first), else the rule written out.
276 */
277export const keyAt = (entries: Record<string, Entry>, configured: Configured, arg: string): string => {
278 if (!/^\d+$/.test(arg)) return arg
279 return sorted(entries, configured)[Number(arg) - 1]?.key ?? arg
280}
281
282/** A text summary, for the command's answer where no pane can open; numbered as the pane is. */
283export const summary = (entries: Record<string, Entry>, configured: Configured, lang: Lang = 'en') => {
284 const w = WORDS[lang]
285 const rows = sorted(entries, configured)
286 if (rows.length === 0) return w.noDialogs
287 return rows
288 .slice(0, 15)
289 .map((r, i) => `${String(i + 1).padStart(2)} ${w.status[r.status].padEnd(10)} ✓${r.entry.approved} ✗${r.entry.denied} ${r.key}`)
290 .concat(rows.some(r => r.status === 'ready') ? ['', w.addHint] : [])
291 .join('\n')
292}
293hooks/ui.tsx 114 lines1// Shared UI helpers, after launchpad's patterns. The same file in every mod that has one: a mod
2// installs alone and cannot import another's code, so scripts/check-shared.sh keeps the copies
3// equal. Change one, copy it to the others.
4//
5// Nothing here takes `$`: the engine follows `$` only into functions of the file that uses it,
6// never across an import. A call on `$` stays in register.tsx; this file gives it its arguments.
7//
8// language and icons the `language` and `icons` options, else the system's LANG and terminal.
9// prompt the arguments of $.prompt.fill: a text with its first `[blank]` marked.
10// lists the window of a long list a pane shows, for ui.scroll.
11// verbs a row of a command's arguments, one press each.
12// numbers tokens, elapsed time, clipped text and short model names.
13
14import type { Elements, PromptFillArgs } from 'claude-code'
15
16export type Lang = 'pt-BR' | 'en'
17export type IconStyle = 'emoji' | 'symbol'
18
19/** The language: the `language` option when it names one, else Portuguese for a pt LANG, else English. */
20export const langOf = (option: unknown, systemLang?: string | null): Lang =>
21 option === 'en' || option === 'pt-BR' ? option : /^pt([_.@-]|$)/i.test(systemLang ?? '') ? 'pt-BR' : 'en'
22
23/**
24 * The icon style: the `icons` option when it names one; on `auto` (or none), symbols in a
25 * JetBrains IDE's terminal (TERMINAL_EMULATOR=JetBrains-JediTerm), which gives many emoji one
26 * column where Claude Code counts two, and emoji everywhere else.
27 */
28export const styleOf = (option: unknown, terminal?: string | null): IconStyle =>
29 option === 'emoji' || option === 'symbol' ? option : /^JetBrains/i.test(terminal ?? '') ? 'symbol' : 'emoji'
30
31/** An icon in the style: its emoji, or the one-cell symbol that stands in for it. */
32export const glyph = (style: IconStyle, icon: { emoji: string; symbol: string }) => icon[style]
33
34const BLANK = /\[[^\]\n]+\]/
35
36/** The first `[blank]` in a text, as offsets, so the prompt can mark what to replace. */
37export const blankIn = (text: string): { start: number; end: number } | null => {
38 const m = BLANK.exec(text)
39 return m ? { start: m.index, end: m.index + m[0].length } : null
40}
41
42/** What `$.prompt.fill` takes to put a text in the prompt, its `[blank]` marked to replace. */
43export const fillArgs = (text: string): PromptFillArgs => {
44 const blank = blankIn(text)
45 return blank ? { text, decorations: [{ ...blank, bold: true, underline: true }] } : { text }
46}
47
48/** The rows of a list of `total` a pane shows from `offset`, kept inside the list. */
49export const windowOf = (total: number, offset: number, rows: number): { start: number; end: number } => {
50 const size = Math.max(1, rows)
51 const start = Math.max(0, Math.min(offset, total - size))
52 return { start, end: Math.min(total, start + size) }
53}
54
55/**
56 * One of a command's arguments in a verb row. `fill` is the text the prompt waits with, for a
57 * verb that takes an argument or undoes something: a stray click then loses nothing. A verb with
58 * no `fill` runs, and its answer goes to the transcript a line at a time (`linesOf`).
59 */
60export type Verb = { verb: string; label?: string; fill?: string }
61
62/** A command's answer as the lines `$.ui.log` writes, one row each; blank lines dropped. */
63export const linesOf = (text: string | undefined) => (text ?? '').split('\n').filter(line => line.trim() !== '')
64
65/** `/command verb · verb · verb`, each verb a plain button; `lead` goes dim before the command. */
66export function verbRow(
67 ui: Pick<Elements[keyof Elements], 'Box' | 'Text' | 'Button'>,
68 command: string,
69 verbs: readonly Verb[],
70 onPress: (v: Verb) => void,
71 lead = '',
72) {
73 const { Box, Text, Button } = ui
74 return (
75 <Box flexDirection="row" flexWrap="wrap">
76 {lead !== '' && <Text dimColor>{`${lead} · `}</Text>}
77 <Text dimColor>{`/${command} `}</Text>
78 {verbs.map((v, i) => (
79 <Box key={`verbrow:${v.verb}`} flexDirection="row">
80 {i > 0 && <Text dimColor> · </Text>}
81 <Button key={`verb:${v.verb}`} plain dimColor label={v.label ?? v.verb} onPress={() => onPress(v)} />
82 </Box>
83 ))}
84 </Box>
85 )
86}
87
88/** 950, 1.2k, 46k, 1.2M. */
89export const tokens = (n: number) => {
90 if (n < 1000) return String(n)
91 if (n < 1_000_000) return `${(n / 1000).toFixed(n < 10_000 ? 1 : 0)}k`
92 return `${(n / 1_000_000).toFixed(1)}M`
93}
94
95/** 42s, 6m 05s, 1h 02m. */
96export const elapsed = (ms: number) => {
97 const s = Math.max(0, Math.round(ms / 1000))
98 if (s < 60) return `${s}s`
99 const m = Math.floor(s / 60)
100 if (m < 60) return `${m}m ${String(s % 60).padStart(2, '0')}s`
101 return `${Math.floor(m / 60)}h ${String(m % 60).padStart(2, '0')}m`
102}
103
104/** The text cut to `n` characters, an ellipsis last when it was longer. */
105export const clip = (s: string, n: number) => (s.length > n ? `${s.slice(0, n - 1)}…` : s)
106
107/** claude-haiku-4-5-20251001 -> haiku 4.5 */
108export const shortModel = (m?: string) => {
109 if (!m) return ''
110 const hit = /(opus|sonnet|haiku|fable)[-\s]?(\d+(?:[-.]\d+)?)?/i.exec(m)
111 if (!hit) return m.length > 14 ? `${m.slice(0, 13)}…` : m
112 return `${hit[1]!.toLowerCase()}${hit[2] ? ` ${hit[2].replace('-', '.')}` : ''}`
113}
114hooks/words.ts 221 lines1// What allowlist-coach says, in Portuguese and English. The language comes from the `language`
2// option, else the system's LANG (ui.tsx's langOf).
3
4import type { Tab } from '../types'
5import type { Risk, Status } from './tally'
6import type { Lang } from './ui'
7
8export const COMMAND = 'allowlist'
9
10type Words = {
11 description: string
12 pane: string
13 hint: (root: string, threshold: number) => string
14 empty: string
15 status: Record<Status, string>
16 tabs: Record<Tab, string>
17 filter: string
18 placeholder: string
19 noMatch: string
20 /** The scroll row under the list: which rules show, of how many. */
21 range: (from: number, to: number, of: number) => string
22 up: string
23 down: string
24 /** Why a risky rule is never offered. */
25 risk: (r: Risk) => string
26 allow: string
27 dismiss: string
28 close: string
29 /** The line under a rule: the last call that asked, and when. */
30 example: (example: string, ago: string) => string
31 ago: (ms: number) => string
32 /** Lines under an open permission dialog. */
33 noticeRisky: (approved: number) => string
34 noticeRefused: (approved: number, denied: number) => string
35 noticeReady: (approved: number) => string
36 noticeCounting: (progress: string, left: number, rule: string) => string
37 offered: (rule: string, approved: number) => string
38 /** The question before a rule is written, with the line it adds, and its answers. */
39 askAdd: (what: string, approved: number) => string
40 preview: (rules: readonly string[]) => string
41 addLocal: string
42 addShared: string
43 notNow: string
44 never: string
45 /** The question before the counts are cleared, and its answers: Cancel first. */
46 askReset: (n: number) => string
47 cancel: string
48 clear: string
49 /** Undoing an added rule: the button, the question, its answer and the outcomes. */
50 remove: string
51 askRemove: (what: string, file: string) => string
52 removeOpt: string
53 removed: (what: string, file: string) => string
54 notInFile: (what: string, file: string) => string
55 notAdded: (key: string) => string
56 /** One rule's counts back to zero: the button, the question, its answer and the outcome. */
57 resetCount: string
58 askZero: (key: string, approved: number, denied: number) => string
59 zeroOpt: string
60 zeroed: (key: string) => string
61 noRule: (key: string) => string
62 /** Why /allowlist allow refuses a rule: its status, and for a risky one the reason. */
63 notOffered: (key: string, why: string) => string
64 nothingChanged: string
65 neverAgain: (what: string) => string
66 added: (what: string, file: string) => string
67 leftAsIs: (file: string, why: string) => string
68 cleared: string
69 noDialogs: string
70 addHint: string
71 help: string
72 failedToRun: (what: string) => string
73}
74
75const minutes = (ms: number) => Math.floor(ms / 60_000)
76
77export const WORDS: Record<Lang, Words> = {
78 'pt-BR': {
79 description: 'Diálogos de permissão por regra: /allowlist abre o painel; allow <n>, dismiss <n>, remove <n>, reset [<n>], help',
80 pane: 'Allowlist',
81 hint: (root, t) => `Diálogos de permissão respondidos em ${root}. Uma regra é oferecida depois de ${t} aprovações sem recusa.`,
82 empty: 'Nenhum diálogo de permissão respondido neste projeto ainda.',
83 status: { ready: 'pronta', counting: 'contando', refused: 'recusada', risky: 'arriscada', allowed: 'liberada', pinned: 'fixada', dismissed: 'dispensada' },
84 tabs: { all: 'todas', ready: 'prontas', counting: 'contando', refused: 'recusadas' },
85 filter: 'Filtrar',
86 placeholder: 'regra ou comando',
87 noMatch: 'Nenhuma regra corresponde.',
88 range: (from, to, of) => `${from}–${to} de ${of}`,
89 up: '▲ acima',
90 down: '▼ abaixo',
91 risk: r => (r.kind === 'tool' ? 'a ferramenta inteira' : r.kind === 'wildcard' ? 'curinga amplo' : r.kind === 'command' ? `roda ${r.what}` : 'regra ilegível'),
92 allow: 'liberar',
93 dismiss: 'dispensar',
94 close: 'Fechar',
95 example: (ex, ago) => `ex.: ${ex} · ${ago}`,
96 ago: ms => {
97 const m = minutes(ms)
98 if (m < 1) return 'agora'
99 if (m < 60) return `há ${m} min`
100 const h = Math.floor(m / 60)
101 if (h < 24) return `há ${h} h`
102 const d = Math.floor(h / 24)
103 return d === 1 ? 'ontem' : `há ${d} dias`
104 },
105 noticeRisky: a => `allowlist-coach: aprovada ${a} ${a === 1 ? 'vez' : 'vezes'} aqui; ampla demais para virar regra`,
106 noticeRefused: (a, d) => `allowlist-coach: aprovada ${a} ${a === 1 ? 'vez' : 'vezes'}, recusada ${d} aqui`,
107 noticeReady: a => `allowlist-coach: aprovada ${a} ${a === 1 ? 'vez' : 'vezes'} aqui · /allowlist`,
108 noticeCounting: (progress, left, rule) => `allowlist-coach: ${progress} aprovações · ${left === 1 ? 'falta 1' : `faltam ${left}`} para /allowlist oferecer ${rule}`,
109 offered: (rule, a) => `Você aprovou ${rule} ${a} vezes aqui. /allowlist para adicionar ao permissions.allow.`,
110 askAdd: (what, a) => `Adicionar ${what} ao permissions.allow? Você aprovou ${a} ${a === 1 ? 'vez' : 'vezes'} aqui.`,
111 preview: rules => `Linha que entra em permissions.allow: ${rules.map(r => JSON.stringify(r)).join(', ')}`,
112 addLocal: 'Adicionar ao settings.local.json (só você)',
113 addShared: 'Adicionar ao settings.json (o time todo)',
114 notNow: 'Agora não',
115 never: 'Nunca oferecer',
116 askReset: n => `Apagar as contagens ${n === 1 ? 'da regra' : `das ${n} regras`} deste projeto? As regras já liberadas continuam em permissions.allow.`,
117 cancel: 'Cancelar',
118 clear: 'Apagar',
119 remove: 'tirar do allow',
120 askRemove: (what, file) => `Tirar ${what} do permissions.allow em ${file}? O diálogo de permissão volta a aparecer.`,
121 removeOpt: 'Tirar',
122 removed: (what, file) => `allowlist-coach: ${what} saiu do permissions.allow em ${file}; não será mais oferecida.`,
123 notInFile: (what, file) => `allowlist-coach: ${what} não está no permissions.allow de ${file}; nada mudou.`,
124 notAdded: key => `allowlist-coach: ${key} não foi adicionada pelo allowlist-coach; tire-a do arquivo de settings onde está.`,
125 resetCount: 'zerar contagem',
126 askZero: (key, a, d) => `Zerar a contagem de ${key} (${a} ${a === 1 ? 'aprovação' : 'aprovações'}, ${d} ${d === 1 ? 'recusa' : 'recusas'})?`,
127 zeroOpt: 'Zerar',
128 zeroed: key => `allowlist-coach: contagem de ${key} zerada.`,
129 noRule: key => `allowlist-coach: nenhuma regra ${key} contada neste projeto. /allowlist mostra os números.`,
130 notOffered: (key, why) => `allowlist-coach: ${key} está ${why}; o coach não a adiciona. Se quiser mesmo, adicione-a ao permissions.allow à mão.`,
131 nothingChanged: 'allowlist-coach: nada mudou.',
132 neverAgain: what => `allowlist-coach: ${what} não será mais oferecida.`,
133 added: (what, file) => `allowlist-coach: ${what} adicionada ao permissions.allow em ${file}.`,
134 leftAsIs: (file, why) => `allowlist-coach: ${file} ficou como estava: ${why}`,
135 cleared: 'allowlist-coach: contagens deste projeto apagadas.',
136 noDialogs: 'allowlist-coach: nenhum diálogo de permissão respondido neste projeto ainda.',
137 addHint: 'Adicione uma com: /allowlist allow 1',
138 help: [
139 '/allowlist abre o painel',
140 '/allowlist allow 1 libera a regra 1 (pergunta antes)',
141 '/allowlist dismiss 1 para de oferecer a regra 1',
142 '/allowlist remove 1 tira do allow a regra 1 que o coach adicionou (pergunta antes)',
143 '/allowlist reset 1 zera a contagem da regra 1 (pergunta antes)',
144 '/allowlist reset apaga as contagens deste projeto (pergunta antes)',
145 'O número é o do painel. A regra escrita por extenso também vale.',
146 ].join('\n'),
147 failedToRun: what => `Não deu para rodar: ${what}`,
148 },
149 en: {
150 description: 'Permission dialogs per rule: /allowlist opens the pane; allow <n>, dismiss <n>, remove <n>, reset [<n>], help',
151 pane: 'Allowlist',
152 hint: (root, t) => `Permission dialogs answered in ${root}. A rule is offered after ${t} approvals and no refusal.`,
153 empty: 'No dialogs answered in this project yet.',
154 status: { ready: 'ready', counting: 'counting', refused: 'refused', risky: 'risky', allowed: 'allowed', pinned: 'pinned', dismissed: 'dismissed' },
155 tabs: { all: 'all', ready: 'ready', counting: 'counting', refused: 'refused' },
156 filter: 'Filter',
157 placeholder: 'rule or command',
158 noMatch: 'No rule matches.',
159 range: (from, to, of) => `${from}–${to} of ${of}`,
160 up: '▲ up',
161 down: '▼ down',
162 risk: r => (r.kind === 'tool' ? 'the whole tool' : r.kind === 'wildcard' ? 'a broad wildcard' : r.kind === 'command' ? `runs ${r.what}` : 'unreadable rule'),
163 allow: 'allow',
164 dismiss: 'dismiss',
165 close: 'Close',
166 example: (ex, ago) => `e.g. ${ex} · ${ago}`,
167 ago: ms => {
168 const m = minutes(ms)
169 if (m < 1) return 'just now'
170 if (m < 60) return `${m} min ago`
171 const h = Math.floor(m / 60)
172 if (h < 24) return `${h} h ago`
173 const d = Math.floor(h / 24)
174 return d === 1 ? 'yesterday' : `${d} days ago`
175 },
176 noticeRisky: a => `allowlist-coach: approved ${a} time${a === 1 ? '' : 's'} here; too broad to offer as a rule`,
177 noticeRefused: (a, d) => `allowlist-coach: approved ${a} time${a === 1 ? '' : 's'}, refused ${d} here`,
178 noticeReady: a => `allowlist-coach: approved ${a} time${a === 1 ? '' : 's'} here · /allowlist`,
179 noticeCounting: (progress, left, rule) => `allowlist-coach: ${progress} approvals · ${left} more and /allowlist offers ${rule}`,
180 offered: (rule, a) => `You approved ${rule} ${a} times here. /allowlist to add it to permissions.allow.`,
181 askAdd: (what, a) => `Add ${what} to permissions.allow? You approved it ${a} time${a === 1 ? '' : 's'} here.`,
182 preview: rules => `The line it adds to permissions.allow: ${rules.map(r => JSON.stringify(r)).join(', ')}`,
183 addLocal: 'Add to settings.local.json (just you)',
184 addShared: 'Add to settings.json (the whole team)',
185 notNow: 'Not now',
186 never: 'Never offer it',
187 askReset: n => `Clear the counts of this project's ${n === 1 ? 'rule' : `${n} rules`}? Rules already allowed stay in permissions.allow.`,
188 cancel: 'Cancel',
189 clear: 'Clear',
190 remove: 'remove from allow',
191 askRemove: (what, file) => `Remove ${what} from permissions.allow in ${file}? Its permission dialog comes back.`,
192 removeOpt: 'Remove',
193 removed: (what, file) => `allowlist-coach: removed ${what} from permissions.allow in ${file}; it will not be offered again.`,
194 notInFile: (what, file) => `allowlist-coach: ${what} is not in permissions.allow in ${file}; nothing changed.`,
195 notAdded: key => `allowlist-coach: allowlist-coach did not add ${key}; remove it from the settings file that has it.`,
196 resetCount: 'reset count',
197 askZero: (key, a, d) => `Reset the count of ${key} (${a} approval${a === 1 ? '' : 's'}, ${d} refusal${d === 1 ? '' : 's'})?`,
198 zeroOpt: 'Reset',
199 zeroed: key => `allowlist-coach: count of ${key} reset.`,
200 noRule: key => `allowlist-coach: no rule ${key} counted in this project. /allowlist shows the numbers.`,
201 notOffered: (key, why) => `allowlist-coach: ${key} is ${why}; the coach does not add it. Add it to permissions.allow by hand if you mean it.`,
202 nothingChanged: 'allowlist-coach: nothing changed.',
203 neverAgain: what => `allowlist-coach: ${what} will not be offered again.`,
204 added: (what, file) => `allowlist-coach: added ${what} to permissions.allow in ${file}.`,
205 leftAsIs: (file, why) => `allowlist-coach: ${file} left as it was: ${why}`,
206 cleared: "allowlist-coach: this project's counts cleared.",
207 noDialogs: 'allowlist-coach: no permission dialogs answered in this project yet.',
208 addHint: 'Add one with: /allowlist allow 1',
209 help: [
210 '/allowlist open the pane',
211 '/allowlist allow 1 allow rule 1 (asks first)',
212 '/allowlist dismiss 1 stop offering rule 1',
213 '/allowlist remove 1 take rule 1 out of allow, when the coach added it (asks first)',
214 "/allowlist reset 1 reset rule 1's count (asks first)",
215 "/allowlist reset clear this project's counts (asks first)",
216 'The number is the one in the pane. The rule written out works too.',
217 ].join('\n'),
218 failedToRun: what => `Could not run: ${what}`,
219 },
220}
221types/index.d.ts 42 lines1/** What the person did with an entry, beyond counting it. */
2export type EntryState = 'counting' | 'offered' | 'added' | 'dismissed'
3
4/** One permission rule and how often its dialog was answered in this project. */
5export type Entry = {
6 /** The rules that would have skipped the dialog, as settings write them (`Bash(./mvnw test:*)`). */
7 rules: string[]
8 approved: number
9 denied: number
10 /** The last call that asked, short: a command, a path, a URL. */
11 example: string
12 /** When the last dialog was answered, in epoch milliseconds. */
13 lastAt: number
14 state: EntryState
15 /** The settings file the coach added the rules to, project-relative; set with `added`. */
16 file?: string
17}
18
19/** The pane's tabs: one status each, and all of them. */
20export type Tab = 'all' | 'ready' | 'counting' | 'refused'
21
22/** The permission lists as the merged settings hold them. */
23export type Configured = {
24 allow: string[]
25 ask: string[]
26 deny: string[]
27}
28
29declare module 'claude-code' {
30 interface PluginState {
31 'allowlist-coach': {
32 /** Keyed by `rules.join(', ')`. */
33 entries: Record<string, Entry>
34 configured: Configured
35 /** The pane: the first row of its list, its tab, and the text typed in its filter. */
36 offset: number
37 tab: Tab
38 filter: string
39 }
40 }
41}
42