Skip to content
Back to search

token-tv

MarketplaceWorks with Claude CodeGitHub

TokenTV: your AI usage limits and your agents' moments on a $5 desk clock

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked yesterday

Check it deeper on your machine

It has changed since its scan on 18 Nov 2026.

As a Claude Code plugin, install it and then ask Claude Code:

/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/click6067-ship-it/token-tv with scanskillsafety

Or from a terminal, clone it and run it:

git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/click6067-ship-it/token-tv'

It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.

Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/click6067-ship-it--token-tv/badge.svg)](/listings/click6067-ship-it--token-tv)

HTML

<a href="/listings/click6067-ship-it--token-tv"><img src="/api/listings/click6067-ship-it--token-tv/badge.svg" alt="findsafeskills safety rating" /></a>

Install

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

.claude-plugin/marketplace.json · Manifest · 12 lines
  1. {
  2. "name": "token-tv",
  3. "description": "TokenTV: your AI usage limits and your agents' moments on a $5 desk clock",
  4. "owner": { "name": "click6067-ship-it" },
  5. "plugins": [
  6. {
  7. "name": "tokentv",
  8. "source": "./claude-plugin",
  9. "description": "Clawd on your TokenTV clock raises a hand while Claude Code waits for your permission, bows when a turn is done, takes a pat or a snack (/tokentv pet, /tokentv snack), and reacts to risky commands, deleted files, rude prompts, failed tools, compactions and Claude Code's thinking word"
  10. }
  11. ]
  12. }
README.md · README · 31 lines
  1. <h1 align="center">TokenTV</h1>
  2. <p align="center">
  3. <a href="https://github.com/click6067-ship-it/token-tv/releases/latest"><img alt="Release" src="https://img.shields.io/github/v/release/click6067-ship-it/token-tv"></a>
  4. <a href="https://github.com/click6067-ship-it/token-tv/blob/main/LICENSE"><img alt="License: MIT" src="https://img.shields.io/badge/license-MIT-blue"></a>
  5. <a href="https://hackaday.com/2026/10/06/smalltv-hacking-with-surprisingly-little-fuss/"><img alt="Featured on Hackaday" src="https://img.shields.io/badge/featured%20on-Hackaday-1a1a1a"></a>
  6. <a href="https://github.com/steipete/CodexBar#desk-display"><img alt="Listed in CodexBar" src="https://img.shields.io/badge/listed%20in-CodexBar-555555"></a>
  7. </p>
  8. <p align="center"><a href="https://token-tv.vercel.app/meet/"><img src="https://raw.githubusercontent.com/click6067-ship-it/token-tv/main/docs/images/real-reactions.gif" width="320" alt="A real TokenTV clock: Claude finishes its task and Clawd bows, Claude runs rm -rf and it goes on trial, I swear at Claude and it turns its back"></a></p>
  9. <p align="center"><img src="https://raw.githubusercontent.com/click6067-ship-it/token-tv/main/docs/images/real-photos.jpg" width="600" alt="Digital, Sci-Fi HUD, Neon and Arcade on the real clock"> <a href="https://youtube.com/shorts/FN5DLILYiI0"><img src="https://raw.githubusercontent.com/click6067-ship-it/token-tv/main/docs/images/real-clock.gif" width="146" alt="TokenTV on a real clock (16 seconds; the full video is on YouTube)"></a></p>
  10. <p align="center"><img src="https://raw.githubusercontent.com/click6067-ship-it/token-tv/main/docs/images/main-faces.png" width="600" alt="The four main faces: Digital, Sci-Fi HUD, Neon and Arcade (sample data)"></p>
  11. Turn a ~$5 AliExpress clock (GeekMagic SmallTV) into pixel pets for Claude Code and Codex. They react to your agents and keep your usage limits in sight. No firmware flashing.
  12. **Live demo:** [token-tv.vercel.app](https://token-tv.vercel.app)
  13. **YouTube:** [https://www.youtube.com/shorts/FN5DLILYiI0](https://youtube.com/shorts/FN5DLILYiI0)
  14. **Try it:** [live demo](https://token-tv.vercel.app) or `npx token-tv demo`, no clock or login needed.
  15. **Set it up:** run `npx token-tv start` (or `uvx token-tv start`) on a computer that stays on. It finds your signed-in tools and the clock on your Wi-Fi, keeps running in the background and opens your dashboard. Or tell your AI *"Set up TokenTV for me"* ([AGENTS.md](https://github.com/click6067-ship-it/token-tv/blob/main/AGENTS.md)).
  16. **New: Claude Code mode.** Clawd raises a hand when Claude Code needs you, bows when a turn ends, holds court over risky commands and sulks when you shout ([set it up](https://github.com/click6067-ship-it/token-tv/blob/main/docs/claude-code-mod.md)).
  17. **New: Arcade.** When you're coding, the bots get busy too. Codex, for example, rains code to grow flowers while it spends tokens: the more it spends, the fuller the garden. Grok refuels its rocket and, resting, gazes up at Earth, and Copilot and Anti are the newest friends.
  18. <p align="center"><img src="https://raw.githubusercontent.com/click6067-ship-it/token-tv/main/docs/images/highlight-claude.gif" width="150" alt="Clawd breakdancing"> <img src="https://raw.githubusercontent.com/click6067-ship-it/token-tv/main/docs/images/highlight-codex.gif" width="150" alt="The Codex cloud raining code on its flowers"> <img src="https://raw.githubusercontent.com/click6067-ship-it/token-tv/main/docs/images/highlight-grok.gif" width="150" alt="Grok's rocket losing a side booster"> <img src="https://raw.githubusercontent.com/click6067-ship-it/token-tv/main/docs/images/highlight-copilot.gif" width="150" alt="Copilot drawing a heart in the sky"> <img src="https://raw.githubusercontent.com/click6067-ship-it/token-tv/main/docs/images/highlight-anti.gif" width="150" alt="Anti floating in zero gravity"></p>
  19. **Each reacts in its own way.** With little left, one rushes and another frets.
  20. **And a few secret scenes.** Some come only at certain hours, some only after a bot has really worked, and some almost never. Each lasts only a moment, and we're not telling you which. [The collection](https://token-tv.vercel.app/collection/) shows how much is out there.
  21. Simple numbers at a glance, and cute while it's at it. Coding alone at 3 a.m.? Your bots are still up with you, and someone might even make you coffee. Ideas, suggestions and PRs are welcome. *Cuteness is a feature.*
  22. **More:** [TokenTV in the wild](https://github.com/click6067-ship-it/token-tv/blob/main/docs/in-the-wild.md) (press, lists, builds by others, clips you may reuse) · [Which clock to buy](https://github.com/click6067-ship-it/token-tv/blob/main/docs/hardware-compatibility.md#buying-a-clock)
claude-plugin/hooks/register.ts · Bundled script · 976 lines · 1 finding marked
  1. // TokenTV's mod for Claude Code. While Claude Code waits for you to answer a permission prompt, Clawd on your
  2. // TokenTV clock raises a hand (then hops, then holds up a sign); when a turn is done, it bows. `/tokentv pet` and
  3. // `/tokentv snack` give Clawd a pat or a snack, one loop of hearts or munching. A risky command puts Clawd in the
  4. // courtroom, a deleted file leaves a ghost about, a rude prompt turns its back, a failed tool makes it dizzy, a
  5. // compaction makes it squeeze its head, and the readout says Claude Code's own thinking word while a turn runs.
  6. // `/tokentv sound on` plays a short sound on this computer when a prompt waits for you and when a turn is done.
  7. //
  8. // It tells the TokenTV running on this computer a name and nothing else: `claude.ask` (a prompt is now waiting for
  9. // you: a permission dialog, a question, a plan to approve), `claude.answered` (you answered it, or it is over), `claude.end` (a turn ended), `claude.stop`
  10. // (a turn that showed a thinking word was cut short), `claude.pet` and `claude.snack` (the two commands),
  11. // `claude.risky`, `claude.deleted`, `claude.rude`, `claude.calm`, `claude.failed`, `claude.compact`, and
  12. // `claude.word:` with one word of letters (Claude Code's spinner word, `claude.word:PONDERING`). Prompts, commands,
  13. // their words, paths, outputs and ids stay in this file, and are read only to decide which name it is: nothing of
  14. // them is kept. TokenTV counts the waits of every session, so each session says once that its prompt opened and
  15. // once that it closed. Sounds go to TokenTV not at all.
  16. //
  17. // Nothing here is awaited on Claude Code's path, nor changes or blocks anything there: the requests go out in the
  18. // background, one after another so they arrive in the order they happened, and when no TokenTV runs (or it does not
  19. // answer) nothing happens at all. What is below lives as long as the session (one per session); the sound setting
  20. // alone is kept, in Claude Code's own store for this plugin.
  21. // TokenTV lets every wait go 30 minutes after the continuous wait began, at this ask or before it (its answer to the
  22. // ask says how long that wait had lasted: TokenTV-Wait-Age). An answer after that would close another, newer wait
  23. // there, so it is not sent; nor one that would come this close to it (it might land just after).
  24. const EXPIRE_MS = 30 * 60 * 1000
  25. const MARGIN_MS = 5000
  26. const KEEP = 256 // calls already answered, remembered so a late repeat of one is not a new wait
  27. const PATIENCE_MS = 2000 // the longest one request holds the next back (TokenTV answers in milliseconds)
  28. const STALE_MS = 5000 // a moment that could not go out within this is dropped: news, not history
  29. const WORD = 'claude.word:' // and the spinner's word: one word of 1 to 14 letters A-Z, sent in capitals
  30. const SAY_AGAIN_MS = 5 * 60 * 1000 // a word still on is said again this often (TokenTV lets a word go unheard 30 min)
  31. const SOUNDS = { wait: 'sounds/wait.wav', done: 'sounds/done.wav' } // the plugin's own two short clips
  32. const STORE_MS = 1000 // the longest the sound setting's store may take, read or written
  33. // The most of a prompt and of a command read to tell which name it is (their head): a paste of megabytes would take
  34. // a tenth of a second or more, and a shout or a risky command is short.
  35. const PROMPT_READ = 64 * 1024
  36. const COMMAND_READ = 128 * 1024
  37. // `to` names the running TokenTV that counted the wait's ask; its answer goes to that one only, never to another
  38. // (one started since, which never saw the ask, would close a wait of someone else's). `sent` is the ask's own
  39. // request, which the answer waits for: TokenTV may count the ask however late it says so. `waited` is how long
  40. // TokenTV's continuous wait had lasted when it took the ask (ms; none from a TokenTV that does not say).
  41. type Wait = { agent: string | undefined; at: number; to?: string; sent?: Promise<unknown>; waited?: number }
  42. const waits = new Map<string, Wait>() // tool_use_id -> a prompt this session announced and has not closed
  43. // Calls whose check said `ask` and that are still going: tool_use_id -> the tool, its arguments and its loop. The
  44. // prompt Claude Code then raises names the tool and the arguments, not the call. Held as they came (never copied),
  45. // read only to tell which call a prompt is for, and let go as the call ends.
  46. type Asked = { tool: unknown; input: unknown; agent: string | undefined }
  47. const asked = new Map<string, Asked>()
  48. const callers = new Map<string, string | undefined>() // tool_use_id -> the subagent making a call now, if one is
  49. const answered: string[] = []
  50. let interactive = true // false in `claude -p` and the SDK: nobody sits at a dialog there
  51. let mode: string | undefined // the permission mode, where Claude Code says it (2.1.289 did; 2.1.321 does not)
  52. let lastTurn: string | undefined
  53. let queue: Promise<void> = Promise.resolve() // what is told goes out in the order it happened
  54. // What a call that is still going has shown of itself, kept only till it ends: whether it asked you, ran (drawn
  55. // running, or Claude Code's PostToolUseFailure for it), was cut short, or refused by a rule, a hook or auto mode.
  56. const prompted = new Set<string>()
  57. const ran = new Set<string>()
  58. const cut = new Set<string>()
  59. const denied = new Set<string>()
  60. let turning = false // a main turn is going (turn.start to its turn.complete): the spinner's word is its
  61. let said: string | undefined // the word this turn last sent...
  62. let saidAt: number | undefined // ...and when
  63. let sound = false // the sound setting as this session knows it (the store's, when it answers, wins)
  64. export function register(on: any) {
  65. on('session.start', async ($: any, e: any, next: any) => {
  66. interactive = e?.isInteractive !== false
  67. try {
  68. // `immediate`: a pat typed while Claude works goes at once, not after the turn (it touches nothing of it)
  69. await $.command.register({ name: 'tokentv',
  70. description: 'Pet Clawd on your TokenTV clock, give it a snack, or turn its sounds on or off',
  71. argumentHint: 'pet | snack | sound on | sound off', immediate: true })
  72. } catch {}
  73. return next(e)
  74. })
  75. // `/tokentv pet` and `/tokentv snack`: one name each to TokenTV, sent as the other moments are (in the
  76. // background: the command never waits for it). `/tokentv sound on` and `/tokentv sound off`: this computer's
  77. // sounds, nothing to TokenTV. Anything else after /tokentv sends nothing; its words go nowhere.
  78. on('command.run', { command: 'tokentv' }, async ($: any, e: any) => {
  79. const word = String(e?.args ?? '').trim().toLowerCase()
  80. const setting = /^sound\s+(on|off)$/.exec(word)
  81. if (setting) {
  82. sound = setting[1] === 'on'
  83. try {
  84. await within($, Promise.resolve($.store.set('sound', sound)), STORE_MS)
  85. } catch {}
  86. return { text: sound ? 'Sounds on: a short sound on this computer when Claude Code waits for you and when a ' +
  87. 'turn is done (Claude Code plays it on macOS; a Linux or Windows terminal stays silent).'
  88. : 'Sounds off.' }
  89. }
  90. const moment = word === 'pet' ? 'claude.pet' : word === 'snack' ? 'claude.snack' : undefined
  91. if (!moment) return { text: 'Try /tokentv pet, /tokentv snack, or /tokentv sound on|off.' }
  92. if (await onWindows($)) return { text: 'On Windows the TokenTV mod sends nothing for now.' }
  93. if (!(await findTokenTV($).catch(() => undefined))) {
  94. return { text: 'No TokenTV is running on this computer: nothing was sent.' }
  95. }
  96. send($, moment)
  97. return { text: word === 'pet' ? 'A pat for Clawd, on its way to TokenTV.' : 'A snack for Clawd, on its way to TokenTV.' }
  98. })
  99. // Read only for the permission mode, where Claude Code says it: as the session starts and again before each tool
  100. // call (2.1.289). Claude Code 2.1.321 says neither; there the prompt itself tells (PermissionRequest, below).
  101. on('classic.SessionStart', noteMode)
  102. on('classic.PreToolUse', async ($: any, e: any, next: any) => {
  103. if (typeof e?.permission_mode === 'string') mode = e.permission_mode
  104. const verdict = await next(e)
  105. try {
  106. if (typeof verdict?.deny === 'string') note(denied, e?.tool_use_id) // a settings hook refused the call
  107. } catch {}
  108. return verdict
  109. })
  110. // A call that failed: one loop of Clawd dizzy, if it ran (not one you refused, nor one cut short). Claude Code
  111. // says which of its failures were interruptions; and when auto mode's classifier (or a rule) refused one.
  112. on('classic.PostToolUseFailure', async ($: any, e: any, next: any) => {
  113. try {
  114. note(e?.is_interrupt === true ? cut : ran, e?.tool_use_id)
  115. } catch {}
  116. return next(e)
  117. })
  118. on('classic.PermissionDenied', async ($: any, e: any, next: any) => {
  119. try {
  120. note(denied, e?.tool_use_id)
  121. } catch {}
  122. return next(e)
  123. })
  124. // The decision on a call, with Claude Code's verdict passed on untouched. `ask` is put to the mode's decider, and
  125. // that is you only sometimes: in auto mode (the default from Claude Code 2.1.3xx) the classifier settles most
  126. // asks within a second (measured in 2.1.321, 2026-11-11: every Bash call's check said `ask`, approver `person`,
  127. // and no dialog came). So an ask is only remembered here, till the call ends; the prompt is told below. An older
  128. // Claude Code that says its mode instead of who answers (2.1.289) is taken at its word, as before.
  129. on('tool.check', async ($: any, e: any, next: any) => {
  130. const decided = await next(e)
  131. try {
  132. const id = e?.tool_use_id
  133. if (decided?.decision === 'deny') note(denied, id)
  134. if (mayAskYou(decided, e) && callers.has(id)) {
  135. const agent = e.agentId ?? callers.get(id)
  136. asked.set(id, { tool: e.tool, input: e.input, agent })
  137. if (mode !== undefined && e.approver === undefined && asksYou(decided)) open($, id, agent)
  138. }
  139. } catch {}
  140. return decided
  141. })
  142. // The prompt itself: Claude Code raises PermissionRequest as it puts a call to you, a permission dialog, a
  143. // question (AskUserQuestion) or a plan to approve, in every mode, and never for a call the classifier settles
  144. // (measured in 2.1.321: about 20 ms after the check; its settings hooks answer nothing and the dialog stays
  145. // yours). One wait, once per call however often it is raised. The request passes on untouched.
  146. on('classic.PermissionRequest', async ($: any, e: any, next: any) => {
  147. try {
  148. const id = raisedFor(e)
  149. if (id !== undefined) open($, id, asked.get(id)?.agent)
  150. } catch {}
  151. return next(e)
  152. })
  153. // Your answer, as it happens: Claude Code draws the asked call's row again the moment you answer, running (you
  154. // said yes) or with its result (you said no). Measured in Claude Code 2.1.289 (2026-11-01): the asked call's
  155. // `isRunning` turns true in the first ToolGroup drawing after "Yes", while the tool.call around it settles only
  156. // once the tool is done. Drawings come often: with no prompt open they are handed straight on, and none is changed.
  157. on('ui.render', { component: ['ToolGroup', 'ToolUse'] }, async ($: any, e: any, next: any) => {
  158. if (waits.size === 0 && callers.size === 0) return next(e)
  159. try {
  160. const calls = e?.component === 'ToolGroup' ? e.props?.calls ?? [] : [e?.props] // a ToolUse row is one call
  161. for (const call of calls) {
  162. if (call?.isRunning === true) note(ran, call.tool_use_id) // (it ran: a failure now is the tool's own)
  163. if (call?.isInterrupted === true) note(cut, call.tool_use_id)
  164. if (waits.has(call?.tool_use_id) && (call.isRunning === true || call.output != null)) {
  165. answer($, call.tool_use_id)
  166. }
  167. }
  168. } catch {}
  169. return next(e)
  170. })
  171. // The spinner's word while a turn runs (`Pondering`, as Claude Code samples it for the turn): one word of up to
  172. // 14 letters goes to TokenTV, once (and again every SAY_AGAIN_MS while it stays); anything else is left out. The
  173. // drawing passes on untouched.
  174. on('ui.render', { component: 'Spinner' }, async ($: any, e: any, next: any) => {
  175. try {
  176. const word = e?.props?.word
  177. if (turning && typeof word === 'string' && /^[A-Za-z]{1,14}$/.test(word)) say($, word.toUpperCase())
  178. } catch {}
  179. return next(e)
  180. })
  181. on('turn.start', async ($: any, e: any, next: any) => {
  182. turning = true // (a subagent's run raises no turn.start)
  183. said = saidAt = undefined
  184. return next(e)
  185. })
  186. // A prompt you typed (here, or from your phone through Remote Control): in capitals, or with a swear in it, Clawd
  187. // turns its back (`claude.rude`); any other turns it round (`claude.calm`). The prompt is read for that and
  188. // passed on untouched; nothing of it is kept or sent.
  189. on('prompt.submit', async ($: any, e: any, next: any) => {
  190. try {
  191. const from = e?.origin?.kind
  192. if (typeof e?.text === 'string' && (from === undefined || from === 'composer' || from === 'bridge')) {
  193. send($, rude(e.text.slice(0, PROMPT_READ)) ? 'claude.rude' : 'claude.calm')
  194. }
  195. } catch {}
  196. return next(e)
  197. })
  198. // A compaction of the main conversation, once done (not one computed ahead to keep, nor a subagent's): one loop
  199. // of Clawd squeezing its head. What was compacted passes on untouched.
  200. on('session.compact', async ($: any, e: any, next: any) => {
  201. const done = await next(e)
  202. try {
  203. if (!e?.agentId && e?.trigger !== 'precompute' && Array.isArray(done?.messages)) send($, 'claude.compact')
  204. } catch {}
  205. return done
  206. })
  207. // The permission check, your answer and the tool all happen inside `next`: once it is back, the prompt is over
  208. // (the tool ran, or was refused, or the turn was cut short), if no drawing said so before. A Bash command is read
  209. // as it is called, for its risk (the courtroom, said at once) and whether it deletes files (a ghost, said once it
  210. // succeeded); a call of any tool that ran and failed is a dizzy Clawd. The call and its result pass through
  211. // untouched.
  212. on('tool.call', async ($: any, e: any, next: any) => {
  213. const id = e?.tool_use_id
  214. if (typeof id === 'string') callers.set(id, e.agentId) // tool.check carries it only from Claude Code 2.1.290
  215. let kinds: Kinds | undefined
  216. try {
  217. kinds = e?.tool === 'Bash' && typeof e?.command === 'string' ? judged(e.command.slice(0, COMMAND_READ)) : undefined
  218. if (kinds?.risky) send($, 'claude.risky')
  219. } catch {}
  220. let result: any
  221. try {
  222. result = await next(e)
  223. return result
  224. } finally {
  225. callers.delete(id)
  226. asked.delete(id)
  227. answer($, id)
  228. try {
  229. finished($, id, kinds, result, next?.signal)
  230. } catch {}
  231. }
  232. })
  233. // A turn's end closes its open prompts; the main turn's end, when it was not cut short, is a bow (and its sound,
  234. // if on). One cut short that showed a word says so, so its word goes too.
  235. on('turn.complete', async ($: any, e: any, next: any) => {
  236. try {
  237. for (const [id, wait] of [...waits]) if (wait.agent === e?.agentId) answer($, id)
  238. const id = e?.turnId
  239. if (!e?.agentId) {
  240. const spoke = said !== undefined
  241. turning = false
  242. said = saidAt = undefined
  243. if (id === undefined || id !== lastTurn) {
  244. if (!e?.isAborted) {
  245. lastTurn = id
  246. send($, 'claude.end')
  247. cue($, 'done')
  248. } else if (spoke) {
  249. lastTurn = id
  250. send($, 'claude.stop')
  251. }
  252. }
  253. }
  254. } catch {}
  255. return next(e)
  256. })
  257. on('session.end', async ($: any, e: any, next: any) => {
  258. try {
  259. for (const id of [...waits.keys()]) answer($, id) // sent as the rest are; TokenTV lets go of any left
  260. if (turning && said !== undefined) send($, 'claude.stop') // ended mid-turn: its word goes
  261. turning = false
  262. said = saidAt = undefined
  263. } catch {}
  264. return next(e)
  265. })
  266. }
  267. // A call still going (tool.call has it): what it showed of itself, till it ends.
  268. function note(set: Set<string>, id: unknown) {
  269. if (typeof id === 'string' && callers.has(id)) set.add(id)
  270. }
  271. // A call is over with `result`: a Bash call that deleted files and succeeded leaves a ghost; any call that ran and
  272. // failed (Claude Code says isError) makes Clawd dizzy, but not one refused (by you, a rule, a hook or auto mode),
  273. // cut short or abandoned. What the call showed of itself is let go here.
  274. function finished($: any, id: unknown, kinds: Kinds | undefined, result: any, signal: any) {
  275. const key = typeof id === 'string' ? id : ''
  276. const shown = { asked: prompted.has(key), ran: ran.has(key), cut: cut.has(key), denied: denied.has(key) }
  277. for (const set of [prompted, ran, cut, denied]) set.delete(key)
  278. if (!result || typeof result !== 'object' || typeof result.deny === 'string' || signal?.aborted === true) return
  279. if (result.isError === true) {
  280. if (!shown.cut && !shown.denied && (!shown.asked || shown.ran)) send($, 'claude.failed')
  281. } else if (kinds?.deletes) {
  282. send($, 'claude.deleted')
  283. }
  284. }
  285. // The spinner's word: sent when it is new this turn, and again only once SAY_AGAIN_MS has gone by.
  286. function say($: any, word: string) {
  287. if (word !== said) {
  288. said = word
  289. saidAt = undefined
  290. send($, WORD + word)
  291. clockNow($).then((now) => { if (said === word) saidAt = now }, () => {})
  292. return
  293. }
  294. clockNow($).then((now) => {
  295. if (said === word && saidAt !== undefined && now - saidAt >= SAY_AGAIN_MS) {
  296. saidAt = now
  297. send($, WORD + word)
  298. }
  299. }, () => {})
  300. }
  301. // A short sound on this computer (`wait` or `done`), if the setting is on: Claude Code's own player plays the
  302. // plugin's clip; nothing goes to TokenTV for it, and nothing waits for it. Where there is no player (a Linux or
  303. // Windows terminal), or it fails, nothing sounds.
  304. function cue($: any, which: 'wait' | 'done') {
  305. soundOn($)
  306. .then((on) => (on ? $.audio.play({ asset: SOUNDS[which] }) : undefined))
  307. .catch(() => {})
  308. }
  309. // The sound setting: the store's (so a change in one session holds in the others), else this session's.
  310. async function soundOn($: any) {
  311. try {
  312. const kept = await within($, Promise.resolve($.store.get('sound')), STORE_MS)
  313. if (typeof kept === 'boolean') return kept
  314. } catch {}
  315. return sound
  316. }
  317. async function noteMode($: any, e: any, next: any) {
  318. if (typeof e?.permission_mode === 'string') mode = e.permission_mode
  319. return next(e)
  320. }
  321. // An ask a person could be put: not one a host program answers, nor in a run with nobody at a dialog.
  322. function mayAskYou(decided: any, e: any) {
  323. if (!decided || decided.decision !== 'ask' || decided.decider || e?.approver === 'host') return false
  324. const id = e?.tool_use_id
  325. return typeof id === 'string' && id !== '' && interactive && mode !== 'dontAsk'
  326. }
  327. // Where Claude Code says its mode (2.1.289): in auto mode the classifier settles an ask, unless an ask rule or a
  328. // PreToolUse hook asked for you; in any other the ask is yours.
  329. function asksYou(decided: any) {
  330. return mode !== 'auto' || Boolean(decided.rule || decided.hook)
  331. }
  332. // A prompt is open for the call: one wait, once per call (its sound, if on, when it is this session's first open).
  333. function open($: any, id: string, agent: string | undefined) {
  334. if (waits.has(id) || answered.includes(id)) return
  335. const wait = { agent, at: 0 }
  336. const first = waits.size === 0
  337. waits.set(id, wait)
  338. note(prompted, id)
  339. send($, 'claude.ask', wait)
  340. if (first) cue($, 'wait')
  341. }
  342. // The call a prompt is for. Among the calls whose check asked and that are still going, of that tool and loop: the
  343. // earliest with these arguments that has no prompt yet (two calls alike each get their own); none, if those with
  344. // these arguments all have theirs (raised again: nothing new); and if the arguments tell none apart, the earliest
  345. // that has no prompt yet.
  346. function raisedFor(e: any): string | undefined {
  347. if (!interactive) return undefined
  348. let earliest: string | undefined
  349. let again = false
  350. for (const [id, call] of asked) {
  351. if (call.tool !== e?.tool_name) continue
  352. if (call.agent !== undefined && e?.agent_id !== undefined && call.agent !== e.agent_id) continue
  353. const prompted = waits.has(id) || answered.includes(id)
  354. if (alike(call.input, e?.tool_input)) {
  355. if (!prompted) return id
  356. again = true
  357. } else if (earliest === undefined && !prompted) {
  358. earliest = id
  359. }
  360. }
  361. return again ? undefined : earliest
  362. }
  363. // The same arguments as far as both say: every field both have is equal, and they share one (a prompt's arguments
  364. // may carry more fields than the check's). Strings are compared where they are, never copied.
  365. function alike(a: any, b: any) {
  366. if (a === b) return true
  367. if (!a || !b || typeof a !== 'object' || typeof b !== 'object') return false
  368. let shared = 0
  369. for (const key of Object.keys(a)) {
  370. if (!(key in b)) continue
  371. shared++
  372. const one = a[key]
  373. const other = b[key]
  374. if (one === other) continue
  375. if (!one || !other || typeof one !== 'object' || typeof other !== 'object') return false
  376. if (JSON.stringify(one) !== JSON.stringify(other)) return false
  377. }
  378. return shared > 0 || (Object.keys(a).length === 0 && Object.keys(b).length === 0)
  379. }
  380. function answer($: any, id: unknown) {
  381. if (typeof id !== 'string') return
  382. const wait = waits.get(id)
  383. if (!wait) return
  384. waits.delete(id)
  385. answered.push(id)
  386. if (answered.length > KEEP) answered.shift()
  387. send($, 'claude.answered', wait)
  388. }
  389. // In the background, never awaited by a hook: each moment waits for the one before it to be answered (or for
  390. // PATIENCE_MS), so TokenTV takes them in the order they happened; one held up past STALE_MS is dropped.
  391. function send($: any, moment: string, wait?: Wait) {
  392. const asked = clockNow($)
  393. asked.catch(() => {})
  394. queue = queue.then(() => deliver($, moment, asked, wait)).catch(() => {})
  395. }
  396. async function deliver($: any, moment: string, asked: Promise<number>, wait?: Wait) {
  397. if (wait && moment === 'claude.answered') {
  398. // The ask's own request first: TokenTV may say late that it counted it. Not past STALE_MS: a TokenTV that
  399. // never answers holds nothing up for long (and an ask it never confirmed is not answered).
  400. if (wait.sent) await within($, wait.sent, STALE_MS)
  401. if (wait.to === undefined) return // TokenTV never took the ask: nothing of it to close
  402. const began = wait.at - (wait.waited ?? 0) // the continuous wait at TokenTV, which this ask joined
  403. if ((await clockNow($)) - began >= EXPIRE_MS - MARGIN_MS) return // TokenTV has let this wait go by now
  404. // An answer whose ask was counted goes however late, or the wait would stay on the clock.
  405. } else if ((await clockNow($)) - (await asked) > STALE_MS) {
  406. return
  407. }
  408. const place = await findTokenTV($)
  409. if (!place) return
  410. if (wait && moment === 'claude.answered' && wait.to !== place.id) return // another TokenTV run never saw the ask
  411. const init = { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ moment }),
  412. socketPath: place.socket }
  413. const sent = $.http.fetch(place.url, init).then((response: any) => {
  414. if (!wait || moment !== 'claude.ask' || !response?.ok) return
  415. wait.to = place.id
  416. const waited = Number(response.headers?.['tokentv-wait-age']) // seconds; absent from an older TokenTV
  417. if (Number.isFinite(waited) && waited >= 0) wait.waited = waited * 1000
  418. })
  419. const settled = sent.catch(() => {})
  420. if (wait && moment === 'claude.ask') {
  421. wait.at = await clockNow($)
  422. wait.sent = settled
  423. }
  424. await within($, settled, PATIENCE_MS)
  425. }
  426. // `work`, or nothing after `ms`: the host's clock, else the runtime's own timer where there is one, else `work`.
  427. function within($: any, work: Promise<unknown>, ms: number) {
  428. const later = () =>
  429. typeof (globalThis as any).setTimeout === 'function'
  430. ? new Promise((done) => (globalThis as any).setTimeout(done, ms))
  431. : work
  432. let timer: Promise<unknown>
  433. try {
  434. timer = Promise.resolve($.clock.sleep(ms)).catch(later)
  435. } catch {
  436. timer = later()
  437. }
  438. return Promise.race([work, timer])
  439. }
  440. async function clockNow($: any) {
  441. try {
  442. return await $.clock.now()
  443. } catch {
  444. return Date.now()
  445. }
  446. }
  447. // Where the running TokenTV listens: its state folder beside the config `token-tv start` uses
  448. // (<XDG_CONFIG_HOME or ~/.config>/token-tv/state), or beside TOKEN_TV_CONFIG for another config. TokenTV writes its
  449. // address there while it runs (live.url) and, on Linux and macOS, a socket of its own (live.sock). A moment goes
  450. // only over that socket, where it meets no proxy and cannot be redirected anywhere else (Claude Code 2.1.289,
  451. // measured 2026-11-01: Content-Length, Host 127.0.0.1:port). Over TCP the same fetch takes a proxy set in its
  452. // environment, even to 127.0.0.1, and follows a redirect wherever it points, whatever its options say (measured the
  453. // same day): so with no socket nothing is sent, and a live.url alone, perhaps left from a TokenTV that stopped, its
  454. // port another program's now, is never tried. TokenTV makes no socket on Windows: there nothing is sent for now,
  455. // whatever the folder holds.
  456. async function onWindows($: any) {
  457. return (await Promise.resolve().then(() => $.env.get('OS')).catch(() => undefined)) === 'Windows_NT'
  458. }
  459. async function findTokenTV($: any) {
  460. if ((await $.env.get('OS')) === 'Windows_NT') return undefined
  461. const home = (await $.env.get('HOME')) || (await $.env.get('USERPROFILE'))
  462. const config = await $.env.get('TOKEN_TV_CONFIG')
  463. let state: string | undefined
  464. if (config) {
  465. const path = /^~[\\/]/.test(config) && home ? home + config.slice(1) : config
  466. const cut = Math.max(path.lastIndexOf('/'), path.lastIndexOf('\\'))
  467. state = (cut < 0 ? '' : path.slice(0, cut + 1)) + 'state'
  468. } else {
  469. const base = (await $.env.get('XDG_CONFIG_HOME')) || (home ? home + '/.config' : undefined)
  470. state = base ? base + '/token-tv/state' : undefined
  471. }
  472. if (!state) return undefined
  473. if (!absolute(state)) {
  474. // Claude Code takes a socket only by an absolute path (2.1.289 refuses `./state/live.sock`): a relative one is
  475. // made absolute from the folder the session started in, where the relative TOKEN_TV_CONFIG was set. Not the
  476. // session's current folder, which follows a `cd` the model runs. With no absolute folder: nothing is sent.
  477. const root = await Promise.resolve().then(() => $.session.root()).catch(() => undefined)
  478. if (!absolute(root)) return undefined
  479. state = root.replace(/[\\/]+$/, '') + '/' + state.replace(/^(\.[\\/])+/, '')
  480. }
  481. const text = await $.fs.read(state + '/live.url')
  482. const url = loopback(text)
  483. if (!url) return undefined
  484. // Which run of TokenTV this is: it writes live.url anew each time it starts.
  485. const stat = await $.fs.stat(state + '/live.url').catch(() => undefined)
  486. const id = String(text).trim() + '@' + (stat?.mtimeMs ?? '')
  487. const socket = state + '/live.sock'
  488. if (!(await $.fs.exists(socket))) return undefined
  489. return { url: url + '/moment', socket, id }
  490. }
  491. // A path from the root of a drive: /…, C:\… or C:/…, or \\server\share.
  492. function absolute(path: unknown): path is string {
  493. return typeof path === 'string' && /^(\/|[A-Za-z]:[\\/]|\\\\)/.test(path)
  494. }
  495. // Only this computer: http to 127.0.0.1, localhost (sent as 127.0.0.1, never looked up) or [::1] with a port,
  496. // and nothing else. Any other address, a user, a path or a query: not ours to send to.
  497. function loopback(text: unknown) {
  498. const found = /^http:\/\/(127\.0\.0\.1|localhost|\[::1\]):(\d{1,5})$/.exec(String(text ?? '').trim())
  499. if (!found || Number(found[2]) < 1 || Number(found[2]) > 65535) return undefined
  500. return 'http://' + (found[1] === 'localhost' ? '127.0.0.1' : found[1]) + ':' + Number(found[2])
  501. }
  502. // --- Which name: the prompt and the Bash command, read here and kept nowhere -------------------------------------
  503. // e7: a prompt in capitals (at least CAPS_MIN letters, four in five or more of them capitals; a letter of a script
  504. // without capitals, Hangul say, counts as a letter that is not one) or with a swear in it: SWEAR_EN, whole words in
  505. // any case; SWEAR_KO, words starting so, but not the everyday words in SWEAR_KO_NOT. The owner's lists, one place.
  506. const CAPS_MIN = 8
  507. const SWEAR_EN = new Set(['fuck', 'fucks', 'fucked', 'fucking', 'fucker', 'motherfucker', 'shit', 'shitty', 'bullshit',
  508. 'damn', 'dammit', 'damnit', 'goddamn', 'wtf', 'stfu', 'bitch', 'asshole', 'bastard'])
  509. const SWEAR_KO = ['씨발', '시발', '씨팔', 'ㅅㅂ', 'ㅆㅂ', '개새끼', '병신', '지랄', '존나', '좆']
  510. const SWEAR_KO_NOT = ['시발점', '시발역', '병신년']
  511. function rude(text: string) {
  512. const letters = text.match(/\p{L}/gu) ?? []
  513. const capitals = letters.filter((c) => /\p{Lu}|\p{Lt}/u.test(c)).length
  514. if (letters.length >= CAPS_MIN && capitals * 5 >= letters.length * 4) return true
  515. return (text.match(/[\p{L}\p{M}]+/gu) ?? []).some((word) => SWEAR_EN.has(word.toLowerCase()) ||
  516. (SWEAR_KO.some((stem) => word.startsWith(stem)) && !SWEAR_KO_NOT.some((benign) => word.startsWith(benign))))
  517. }
  518. // e3, e4: what a Bash command does, read as a shell would (quotes, comments, here-documents and redirections are
  519. // data; `;`, `&&`, `|`, `$(…)`, backquotes, `bash -c`, `eval`, `find -exec` and wrappers such as `sudo` or `env`
  520. // lead to commands; `command -v` and the like only look one up). Risky: `rm` recursive and forced, `git push
  521. // --force` (`-f`, `--force-with-lease`, a `+refspec`), `git reset --hard`, `git clean` forced with directories (not
  522. // a dry run), `DROP TABLE` or `DROP DATABASE` given to a database client as SQL (not in a string or a comment),
  523. // `mkfs`, `dd of=/dev/…`, `chmod -R 777 /`. Deleting: `rm`, `git rm` (not `--cached`, not a dry run), `find …
    • Note: Quoted as data in code: Sets world-writable permissions on a root path (chmod 777 /)
    • Line 564 on GitHub
  524. // -delete` (or `-exec rm`), `unlink`, each with something to delete. Read in one pass: a command of many parts takes
  525. // no longer than its length says.
  526. type Kinds = { risky: boolean; deletes: boolean }
  527. type Command = { words: string[]; input: string[]; pipe: number }
  528. const PREFIXES = new Set(['if', 'then', 'else', 'elif', 'do', 'while', 'until', '!', '{'])
  529. // A wrapper runs the command after it: its options that take a value, and the words it takes before the command;
  530. // with an option `looks` matches, it only looks the command up (`command -v rm`) and runs nothing.
  531. const WRAPPERS = new Map<string, { takes: string[]; operands: number; looks?: RegExp }>(Object.entries({
  532. sudo: { takes: ['-u', '-g', '-C', '-D', '-h', '-p', '-r', '-t', '-U', '-T', '--user', '--group', '--chdir', '--host',
  533. '--prompt', '--role', '--type', '--other-user', '--command-timeout', '--close-from'], operands: 0 },
  534. doas: { takes: ['-u', '-C'], operands: 0 },
  535. env: { takes: ['-u', '-C', '-S', '--unset', '--chdir', '--split-string'], operands: 0 },
  536. command: { takes: [], operands: 0, looks: /^-[A-Za-z]*[vV]/ },
  537. builtin: { takes: [], operands: 0 },
  538. exec: { takes: ['-a'], operands: 0 },
  539. nohup: { takes: [], operands: 0 },
  540. time: { takes: ['-f', '-o', '--format', '--output'], operands: 0 },
  541. nice: { takes: ['-n', '--adjustment'], operands: 0 },
  542. ionice: { takes: ['-c', '-n', '-p', '-P', '-u'], operands: 0 },
  543. timeout: { takes: ['-s', '-k', '--signal', '--kill-after'], operands: 1 },
  544. setsid: { takes: [], operands: 0 },
  545. stdbuf: { takes: ['-i', '-o', '-e'], operands: 0 },
  546. xargs: { takes: ['-I', '-n', '-P', '-L', '-s', '-d', '-E', '-a', '--max-args', '--max-procs', '--max-lines',
  547. '--max-chars', '--delimiter', '--eof', '--arg-file', '--replace'], operands: 0 },
  548. }))
  549. const SHELLS = new Set(['bash', 'sh', 'zsh', 'dash', 'ksh'])
  550. // The commands judge() reads (with mkfs.<kind> and the shells): any other runs nothing of the lists.
  551. const JUDGED = new Set(['rm', 'unlink', 'git', 'find', 'dd', 'chmod', 'eval', ...SHELLS])
  552. const SQL = new Set(['psql', 'mysql', 'mariadb', 'sqlite3', 'sqlcmd', 'duckdb', 'clickhouse', 'clickhouse-client',
  553. 'cockroach', 'pgcli', 'mycli', 'litecli', 'usql', 'sqlplus', 'snowsql', 'bq', 'trino', 'beeline'])
  554. const HASH_COMMENTS = new Set(['mysql', 'mariadb', 'mycli']) // `#` starts a comment there (elsewhere an operator)
  555. const CLIENT = 1 // a pipeline's marks (judged)
  556. const HASH = 2
  557. const DROPS = 4
  558. const OPEN_ALL = new Set(['777', '0777', 'a+rwx', 'a=rwx', 'ugo+rwx', 'ugo=rwx'])
  559. const GIT_VALUED = new Set(['-C', '-c', '--git-dir', '--work-tree', '--namespace', '--super-prefix', '--config-env'])
  560. // find's tests and actions that take the next word as their value (a pattern, a name, a format, a file): never an
  561. // action itself, as `-name '-delete'` is not one. (`-fprintf` takes two, `-newerXY` one.)
  562. const FIND_VALUED = new Set(['-name', '-iname', '-path', '-ipath', '-wholename', '-iwholename', '-regex', '-iregex',
  563. '-lname', '-ilname', '-newer', '-anewer', '-cnewer', '-samefile', '-perm', '-type', '-xtype', '-user', '-group',
  564. '-uid', '-gid', '-size', '-mtime', '-atime', '-ctime', '-mmin', '-amin', '-cmin', '-used', '-links', '-inum',
  565. '-maxdepth', '-mindepth', '-fstype', '-context', '-printf', '-fprint', '-fprint0', '-fls', '-regextype',
  566. '-files0-from'])
  567. function judged(source: string, depth = 0): Kinds {
  568. const kinds = { risky: false, deletes: false }
  569. if (depth > 4) return kinds // (`bash -c` within `bash -c` within …: enough)
  570. const commands: Command[] = []
  571. const pipes = { n: 0 }
  572. parse(source, { i: 0 }, '', commands, pipes)
  573. // Each pipeline's marks: a database client is in it (CLIENT; HASH when `#` starts a comment there), it says "drop"
  574. // somewhere (DROPS). A DROP counts only in a pipeline with both, as SQL one of its clients reads.
  575. const marks = new Uint8Array(pipes.n)
  576. for (const command of commands) {
  577. const found = unwrapped(command.words)
  578. if (found && SQL.has(found.name)) marks[command.pipe] |= CLIENT | (HASH_COMMENTS.has(found.name) ? HASH : 0)
  579. if (command.words.some(saysDrop) || command.input.some(saysDrop)) marks[command.pipe] |= DROPS
  580. judge(found, kinds, depth)
  581. }
  582. const texts = new Map<number, string[]>()
  583. for (const command of commands) {
  584. if ((marks[command.pipe] & (CLIENT | DROPS)) !== (CLIENT | DROPS)) continue
  585. let parts = texts.get(command.pipe)
  586. if (!parts) texts.set(command.pipe, (parts = []))
  587. for (const word of command.words) parts.push(given(word))
  588. for (const text of command.input) parts.push(text)
  589. }
  590. for (const [pipe, parts] of texts) {
  591. if (drops(parts.map((text) => sqlRead(text, (marks[pipe] & HASH) !== 0)))) kinds.risky = true
  592. }
  593. return kinds
  594. }
  595. function saysDrop(text: string) {
  596. return text.length >= 4 && /drop/i.test(text)
  597. }
  598. // What of a word in a database client's pipeline may be SQL: an option's value (`--command=…`), not the option.
  599. function given(word: string) {
  600. if (word[0] !== '-') return word
  601. const valued = /^--?[A-Za-z][\w-]*=/.exec(word)
  602. return valued ? word.slice(valued[0].length) : /^-\S*$/.test(word) ? '' : word
  603. }
  604. // DROP TABLE or DROP DATABASE as SQL in the texts read (sqlRead), not in a string or a comment; but where the SQL
  605. // runs a string as a statement (EXECUTE, PREPARE, a DO block), a DROP in its strings counts too.
  606. function drops(read: [string, string][]) {
  607. const dynamic = read.some(([bare]) => /\b(EXECUTE|PREPARE)\b|(^|;)\s*DO\b/i.test(bare))
  608. return /\bDROP\s+(TABLE|DATABASE)\b/i.test(read.map((both) => both[dynamic ? 1 : 0]).join(' '))
  609. }
  610. // `text` read as SQL, its comments left out (`-- …`, `/* … */`, and `# …` where `hash`): [without its string
  611. // literals and quoted names, with them]. Those are `'…'` and `"…"` (a backslash escapes in them), `` `…` `` and
  612. // `$tag$…$tag$`. One pass: each literal or comment is skipped whole.
  613. const DOLLAR_TAG = /\$(?:[A-Za-z_]\w{0,62})?\$/y
  614. function sqlRead(text: string, hash: boolean): [string, string] {
  615. if (!/['"`$#/-]/.test(text)) return [text, text] // (nothing of the kind in it)
  616. const bare: string[] = []
  617. const full: string[] = []
  618. let from = 0 // the SQL not yet kept starts here
  619. let i = 0
  620. while (i < text.length) {
  621. const c = text[i]
  622. let end = -1 // where the literal or comment starting at `i` ends
  623. let literal = false
  624. if (c === "'" || c === '"' || c === '`') {
  625. let j = i + 1
  626. while (j < text.length && text[j] !== c) j += text[j] === '\\' && c !== '`' ? 2 : 1
  627. end = Math.min(j + 1, text.length)
  628. literal = true
  629. } else if ((c === '-' && text[i + 1] === '-') || (c === '#' && hash)) {
  630. end = text.indexOf('\n', i)
  631. if (end < 0) end = text.length
  632. } else if (c === '/' && text[i + 1] === '*') {
  633. end = text.indexOf('*/', i + 2)
  634. end = end < 0 ? text.length : end + 2
  635. } else if (c === '$' && !/[\w$]/.test(text[i - 1] ?? ' ')) {
  636. DOLLAR_TAG.lastIndex = i
  637. const tag = DOLLAR_TAG.exec(text)?.[0]
  638. if (tag) {
  639. const close = text.indexOf(tag, i + tag.length)
  640. end = close < 0 ? text.length : close + tag.length
  641. literal = true
  642. }
  643. }
  644. if (end < 0) {
  645. i++
  646. continue
  647. }
  648. const sql = text.slice(from, i)
  649. bare.push(sql, ' ')
  650. full.push(sql, literal ? text.slice(i, end) : ' ')
  651. from = i = end
  652. }
  653. bare.push(text.slice(from))
  654. full.push(text.slice(from))
  655. return [bare.join(''), full.join('')]
  656. }
  657. // What the command `found` (unwrapped) runs, into `kinds`.
  658. function judge(found: Found | undefined, kinds: Kinds, depth: number) {
  659. if (!found) return
  660. const name = found.name
  661. const mkfs = name.startsWith('mkfs') && /^mkfs(\.[A-Za-z0-9]+)?$/.test(name)
  662. if (!JUDGED.has(name) && !mkfs) return // (most commands)
  663. const args = found.words.slice(1)
  664. const either = (more: Kinds) => {
  665. kinds.risky ||= more.risky
  666. kinds.deletes ||= more.deletes
  667. }
  668. if (SHELLS.has(name)) {
  669. const at = args.findIndex((a) => /^-[A-Za-z]*c[A-Za-z]*$/.test(a))
  670. if (at >= 0 && typeof args[at + 1] === 'string') either(judged(args[at + 1], depth + 1))
  671. return
  672. }
  673. if (name === 'eval') return either(judged(args.join(' '), depth + 1))
  674. if (name === 'git') return git(args, kinds)
  675. if (name === 'dd') {
  676. if (args.some((a) => a.startsWith('of=/dev/'))) kinds.risky = true
  677. return
  678. }
  679. if (name === 'find') {
  680. for (let k = 0; k < args.length; k++) {
  681. const a = args[k]
  682. if (a === '-delete') kinds.deletes = true
  683. else if (a === '-fprintf') k += 2
  684. else if (FIND_VALUED.has(a) || /^-newer[aBcmt]{2}$/.test(a)) k++ // (its value, whatever it says)
  685. else if (['-exec', '-execdir', '-ok', '-okdir'].includes(a)) {
  686. let end = k + 1
  687. while (end < args.length && args[end] !== ';' && args[end] !== '+') end++
  688. judge(unwrapped(args.slice(k + 1, end)), kinds, depth)
  689. k = end
  690. }
  691. }
  692. return
  693. }
  694. const opts = options(args)
  695. const has = (short: string, long: string) => opts.short.has(short) || opts.long.has(long)
  696. const something = opts.operands.length > 0 || found.fed // (xargs gives it what to work on)
  697. if (name === 'rm' && something && !opts.long.has('help') && !opts.long.has('version')) {
  698. kinds.deletes = true
  699. if ((has('r', 'recursive') || opts.short.has('R')) && has('f', 'force')) kinds.risky = true
  700. } else if (name === 'unlink' && something) {
  701. kinds.deletes = true
  702. } else if (name === 'chmod') {
  703. const [mode, ...targets] = opts.operands
  704. if (has('R', 'recursive') && OPEN_ALL.has(mode ?? '') && targets.some((t) => t === '/' || t === '/*')) kinds.risky = true
  705. } else if (mkfs && opts.operands.length > 0) {
  706. kinds.risky = true
  707. }
  708. }
  709. function git(args: string[], kinds: Kinds) {
  710. let k = 0
  711. while (k < args.length && args[k].startsWith('-')) k += GIT_VALUED.has(args[k]) ? 2 : 1 // git's own options
  712. const sub = args[k]
  713. const opts = options(args.slice(k + 1))
  714. if (sub === 'push') {
  715. // forced by an option, or by a refspec after the remote that starts with `+` (`git push origin +main`)
  716. const plus = opts.operands.slice(1).some((ref) => ref.length > 1 && ref.startsWith('+'))
  717. if (opts.short.has('f') || opts.long.has('force') || opts.long.has('force-with-lease') || plus) kinds.risky = true
  718. } else if (sub === 'reset') {
  719. if (opts.long.has('hard')) kinds.risky = true
  720. } else if (sub === 'clean') {
  721. const force = opts.short.has('f') || opts.long.has('force')
  722. const dry = opts.short.has('n') || opts.long.has('dry-run')
  723. if (force && opts.short.has('d') && !dry) kinds.risky = true
  724. } else if (sub === 'rm') {
  725. const dry = opts.short.has('n') || opts.long.has('dry-run')
  726. if (!dry && !opts.long.has('cached') && opts.operands.length > 0) kinds.deletes = true
  727. }
  728. }
  729. // The words before `--` as short options (each letter) and long ones (name before any `=`), and the operands.
  730. function options(args: string[]) {
  731. const short = new Set<string>()
  732. const long = new Set<string>()
  733. const operands: string[] = []
  734. let ended = false
  735. for (const a of args) {
  736. if (ended || a === '-' || !a.startsWith('-')) operands.push(a)
  737. else if (a === '--') ended = true
  738. else if (a.startsWith('--')) long.add(a.slice(2).split('=')[0])
  739. else for (const c of a.slice(1)) short.add(c)
  740. }
  741. return { short, long, operands }
  742. }
  743. // The command a simple command runs: past its variable assignments, the shell's words before a command (`if`,
  744. // `then`, `!`, …) and wrappers with their options. `fed`: xargs gives it what to work on. None when it runs none
  745. // (`command -v rm` only looks rm up).
  746. type Found = { words: string[]; fed: boolean; name: string } // (name: the command's, its folder left out)
  747. function unwrapped(words: string[]): Found | undefined {
  748. let k = 0
  749. let fed = false
  750. for (let guard = 0; guard < 32 && k < words.length; guard++) {
  751. const word = words[k]
  752. if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(word) || PREFIXES.has(word)) {
  753. k++
  754. continue
  755. }
  756. const name = basename(word)
  757. const wrapper = WRAPPERS.get(name)
  758. if (!wrapper) break
  759. fed ||= name === 'xargs'
  760. k++
  761. while (k < words.length && words[k].startsWith('-') && words[k] !== '-') {
  762. const opt = words[k++]
  763. if (opt === '--') break
  764. if (wrapper.looks?.test(opt)) return undefined
  765. if (wrapper.takes.includes(opt)) k++
  766. }
  767. k += wrapper.operands
  768. }
  769. return k < words.length ? { words: k ? words.slice(k) : words, fed, name: basename(words[k]) } : undefined
  770. }
  771. function basename(word: string) {
  772. return word.slice(word.lastIndexOf('/') + 1)
  773. }
  774. // A shell's reading of `source` from `at.i` up to `stop` (`)` closing `$(`, a backquote) or its end: each simple
  775. // command's words (unquoted), what it is fed (here-documents, here-strings) and its pipeline, into `out`.
  776. function parse(source: string, at: { i: number }, stop: string, out: Command[], pipes: { n: number }) {
  777. let words: string[] = []
  778. let input: string[] = []
  779. let word = ''
  780. let has = false // a word has begun (an empty quoted one is a word)
  781. let route: 'arg' | 'file' | 'heredoc' | 'herestring' = 'arg' // where the next word goes, after a redirection
  782. let strip = false // `<<-`: the here-document's lines lose their leading tabs
  783. let depth = 0 // subshells open, `( … )`
  784. let pipe = pipes.n++
  785. const heredocs: { end: string; strip: boolean; into: string[] }[] = []
  786. const endWord = () => {
  787. if (!has) return
  788. if (route === 'arg') words.push(word)
  789. else if (route === 'heredoc') heredocs.push({ end: word, strip, into: input })
  790. else if (route === 'herestring') input.push(word)
  791. route = 'arg'
  792. word = ''
  793. has = false
  794. }
  795. const endCommand = (piped: boolean) => {
  796. endWord()
  797. route = 'arg'
  798. if (words.length || input.length) out.push({ words, input, pipe })
  799. words = []
  800. input = []
  801. if (!piped) pipe = pipes.n++
  802. }
  803. const bodies = () => { // after a line's end: the here-documents it began, each up to its own end line
  804. for (const doc of heredocs.splice(0)) {
  805. const lines: string[] = []
  806. while (at.i < source.length) {
  807. const end = source.indexOf('\n', at.i)
  808. const line = source.slice(at.i, end < 0 ? source.length : end)
  809. at.i = end < 0 ? source.length : end + 1
  810. if ((doc.strip ? line.replace(/^\t+/, '') : line) === doc.end) break
  811. lines.push(line)
  812. }
  813. doc.into.push(lines.join('\n'))
  814. }
  815. }
  816. const substitution = (close: string) => { // `$( … )` or a backquote's: commands of their own
  817. parse(source, at, close, out, pipes)
  818. word += close === ')' ? '$()' : '``'
  819. has = true
  820. }
  821. const quoted = () => { // "…": a backslash keeps only $ ` " \ and a newline; $( … ) and backquotes still run
  822. while (at.i < source.length) {
  823. const c = source[at.i]
  824. if (c === '"') {
  825. at.i++
  826. return
  827. }
  828. if (c === '\\' && '$`"\\\n'.includes(source[at.i + 1] ?? 'x')) {
  829. if (source[at.i + 1] !== '\n') word += source[at.i + 1]
  830. at.i += 2
  831. } else if (c === '$' && source[at.i + 1] === '(') {
  832. at.i += 2
  833. substitution(')')
  834. } else if (c === '`') {
  835. at.i++
  836. substitution('`')
  837. } else {
  838. word += c
  839. at.i++
  840. }
  841. }
  842. }
  843. while (at.i < source.length) {
  844. const c = source[at.i]
  845. const next = source[at.i + 1]
  846. if (stop === '`' && c === '`') {
  847. at.i++
  848. break
  849. }
  850. if (c === '\\') {
  851. if (next !== '\n') {
  852. word += next ?? ''
  853. has = true
  854. }
  855. at.i += 2
  856. } else if (c === "'") {
  857. const end = source.indexOf("'", at.i + 1)
  858. word += source.slice(at.i + 1, end < 0 ? source.length : end)
  859. has = true
  860. at.i = end < 0 ? source.length : end + 1
  861. } else if (c === '"') {
  862. at.i++
  863. has = true
  864. quoted()
  865. } else if (c === '$' && next === '(') {
  866. at.i += 2
  867. substitution(')')
  868. } else if (c === '`') {
  869. at.i++
  870. substitution('`')
  871. } else if ((c === '<' || c === '>') && next === '(') { // <( … ): a command, its output a file
  872. endWord()
  873. at.i += 2
  874. parse(source, at, ')', out, pipes)
  875. } else if (c === '#' && !has) { // a comment, to the line's end
  876. const end = source.indexOf('\n', at.i)
  877. at.i = end < 0 ? source.length : end
  878. } else if (c === ' ' || c === '\t') {
  879. endWord()
  880. at.i++
  881. } else if (c === '\n') {
  882. endCommand(false)
  883. at.i++
  884. bodies()
  885. } else if (c === '&' && next === '>') { // &> and &>>: both outputs to a file
  886. endWord()
  887. route = 'file'
  888. at.i += source[at.i + 2] === '>' ? 3 : 2
  889. } else if (c === ';' || c === '&' || c === '|') {
  890. endCommand(c === '|' && next !== '|') // `|` and `|&` go on in the same pipeline
  891. at.i += (c === '&' && next === '&') || (c === '|' && (next === '|' || next === '&')) ||
  892. (c === ';' && (next === ';' || next === '&')) ? 2 : 1 // (&&, ||, |&, ;;, ;&)
  893. } else if (c === '(') {
  894. endCommand(false)
  895. depth++
  896. at.i++
  897. } else if (c === ')') {
  898. at.i++
  899. if (depth === 0 && stop === ')') break
  900. endCommand(false)
  901. depth = Math.max(0, depth - 1)
  902. } else if (c === '<' || c === '>') { // a redirection: a word of digits before it is its descriptor
  903. if (has && route === 'arg' && /^\d+$/.test(word)) {
  904. word = ''
  905. has = false
  906. } else {
  907. endWord()
  908. }
  909. let op = c
  910. at.i++
  911. while (at.i < source.length && op.length < 3 && '<>&|-'.includes(source[at.i])) op += source[at.i++]
  912. route = op === '<<' || op === '<<-' ? 'heredoc' : op === '<<<' ? 'herestring' : 'file'
  913. strip = op === '<<-'
  914. } else {
  915. word += c
  916. has = true
  917. at.i++
  918. }
  919. }
  920. endCommand(false)
  921. }

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.