A pane listing the files Claude has read this session, grouped by where they came from, with a lock that keeps reads inside the project folder.

Small TypeScript mods that live inside Claude Code: a pane that knows your next step, one-click replies, a rate-limit countdown that resumes for you, your repo's pull requests and issues beside the conversation, a shelf of paths you use every day, presets that switch the model and the effort with one press, a chime when a long turn ends, a guard for the Office file you left open, a question before a commit or push on the default branch, a question before Claude reads a
.envor key file, a list of the files this session made, a list of the ones it read, a check that keeps banned claims out of a pull request, a gate that runs your checks and hands back only the failures, a nudge to fetch fresh tab IDs when a browser tab is gone, a name for the session from its first prompt, and one dialog for every mod's settings.
claude-mods is one developer's personal toolbox of Claude Code mods, shared as a plugin marketplace so anyone can install them. The mods are built for the author's own workflow first, and you are a welcome guest: install one, install all twenty, or read the source and write your own.
A mod is a plugin of function hooks: TypeScript that runs inside Claude Code and changes what it shows (a pane in the side panel, a band of buttons above the prompt, the status line) or what it does between turns. The mod's own code decides when to act, even when what it does is send the model a prompt.
| Runs as | Who decides when it acts | |
|---|---|---|
| Mod | TypeScript function hooks inside Claude Code | The mod's own code |
| Skill | Instructions the model reads | The model |
| Plain plugin | Commands, agents or shell hooks | You, or a shell script |
| Mod | Where it shows | What it does |
|---|---|---|
| 🧭 whats-next | Pane in the side panel | Lists the next steps of your workflow, each with a prompt ready to paste |
| ⚡ quick-reply | Band above the prompt | One-click replies, including the options Claude just offered, Pass, Fail and Skip for a verdict, and the next wayfinder ticket |
| ⏳ auto-resume | Band and status line | Counts down to a rate limit's reset, then sends "continue" |
| 🐙 github-panel | Pane in the side panel | The repo's open pull requests and issues, one click from the browser or from /implement and /wayfinder in the prompt; the issue a /wayfinder run works on, pinned with its next ticket; a toast when your branch's checks turn green or red |
| 📚 shelf | Band above the prompt | Named folders and files; one click drops a path into what you are typing |
| 🔔 turn-chime | Sound and toast | Tells you when a long turn ends or Claude stops to ask you something |
| 🔒 open-file-guard | Question dialog | Asks you to close a Word, Excel or PowerPoint file before Claude uses it |
| 🌿 branch-guard | Question dialog | Asks you before Claude commits or pushes on the default branch |
| 🔑 env-guard | Question dialog | Asks you before Claude reads a .env or key file, and refuses when no one is there to answer |
| 🩹 bash-quoting-rescue | Refused tool call | Stops a shell command that does not parse, such as an unclosed quote, before any of it runs |
| 📂 outputs | Pane in the side panel | The files this session made or changed, newest first; click one to open it |
| 🔎 sources | Pane in the side panel | The files Claude read, grouped by where they came from, with a lock to the project folder |
| 📊 hud | Two lines under the prompt | Model, effort, context window, rate limits, turn timer, tool calls, agents, git state, worktree, cost, session length and folder, each named and in colour |
| 🧹 post-merge-cleanup | Question dialog and toast | After a PR merges, /cleanup switches to the default branch, pulls and deletes the branch |
| 🧾 pre-pr-claims-check | Refusal Claude reads | Refuses gh pr create and gh pr edit while the pull request cites a file and line, holds a placeholder, or spells out a count |
| 🚦 lint-test-gate | Band above the prompt | Runs your checks on a press and before Claude's git commit, and hands back only the failures |
| 🔄 chrome-tab-self-heal | Note after a browser tool's error | When a Claude in Chrome tab is gone, tells Claude to fetch the current tab IDs before it tries again |
| 🏷 session-auto-namer | Band above the prompt | Suggests a name for the session from its first prompt; one press renames it |
| 🧠 model-effort-presets | Band above the prompt | Plan and execute presets: one press switches the model and the effort together |
| ⚙ mod-settings | Gear on each pane; a dialog | Change and save any mod's settings without leaving the session |
When more than one mod has a pane open, Claude Code shows them as tabs in the side panel.
A pane listing the next steps of your workflow for the project folder, kept between sessions. A skill of your choosing answers "what's next" in a headless run beside your session, and the mod turns the answer into steps.
What's next refresh
updated 3 min ago
Fix the failing parse test
working on it done
The check is red, so nothing else can merge.
Open a pull request for the fix
Review comes before the next feature starts.
Triage the two new issues
They arrived while you were heads-down.
flowchart LR
A[Skill answers<br/>what's next] --> B[Steps in the pane]
B --> C[You read a step's prompt<br/>and send it yourself]
C --> D[Step glows:<br/>working on it]
D --> E{Laya, Jev or Haiku:<br/>is the step finished?}
E -- not yet --> D
E -- yes --> F[Step leaves the list]
d to drop it yourself.git push, git config, git -c, gh api and --output are always denied.| Command or key | What it does |
|---|---|
/whats-next | Bring the pane to the front |
/whats-next refresh | Ask the skill again |
r | Refresh |
1 to 9 | Show that step's prompt in the pane |
p, n, c | Paste the shown prompt, paste it after /clear (and the prime command, once its turn ends), or copy it |
b | Back to the list |
d | Mark the active step done |
| Setting | Key | Default | Meaning |
|---|---|---|---|
| Skill | skill | /ask-sean | The skill that answers "what's next", written as you would run it: / followed by letters, digits, _, :, . or - |
| Most steps | maxSteps | 5 | How many steps to ask for (1-9) |
| Refresh on start | refreshOnStart | on | Ask for a fresh list when a session starts in a git repository |
| Tools the headless run may use | allowedTools | empty: the read-only set | Comma-separated permission rules for the headless run |
| Model | model | empty: your default | Model for the headless run, as an alias (haiku) or a full id |
| Prime command | primeCommand | empty: none | A slash command, with any arguments, run after /clear and before the paste (/lril:prime); the prompt is filled once the turn it starts ends, finished or not. A value that is not one slash command on one line is never run, and the step view says so |
| System One models | modelChoice | local only | Which System One model judges whether a turn finished the active step: local only (Laya on this machine, or Haiku as before), local first (Laya, and TypeSafe's hosted Jev while Laya is unavailable) or hosted first (Jev, and Laya while Jev is unavailable) |
| Jev API key | jevApiKey | empty | Your key for Jev, from console.typesafe.ai, kept in secure storage. Sent only to https://api.typesafe.ai, and only while System One models allows Jev |
| Laya port | layaPort | 8000 | The port your laya-serve listens on at 127.0.0.1 (1-65535) |
/ask-sean is the author's own skill, so point the Skill setting at a skill of yours that answers "what should I do next?" (how to set it):
echo '{"skill": "/next-steps", "maxSteps": "3", "model": "haiku"}' | claude plugin configure whats-next@claude-mods --values-stdin
The read-only set, used while Tools is empty, is Bash(git status:*), Bash(git log:*), Bash(git diff:*), Bash(git show:*), Bash(git rev-parse:*), Bash(git branch --show-current), Bash(git branch -vv), Bash(git remote -v), Bash(gh issue list:*), Bash(gh issue view:*), Bash(gh pr list:*), Bash(gh pr view:*), Bash(gh pr checks:*), Bash(gh run list:*), Read, Glob and Grep.
(...). One rule that is not, such as one starting with -, discards your whole list and the read-only set is used.Skill, so a skill that calls another still works. MCP servers load only when a rule names an mcp__ tool.What the judge sends to a System One model, once after each answered turn while a step is active:
Needs: the claude CLI on the PATH, and the skill named in the Skill setting. Laya and a Jev key are optional: with neither, the judge is Haiku, as before.
One row of buttons above the prompt after each answer. When Claude ends on a question, the band offers the choices Claude asked you to pick from, then your replies to a question. After any other answer it offers your other replies. You set both lists in the settings below.
Reply: [a: Keep the copies] [b: Add a sync script] [Yes] [Go with your recommendation] [No]
Verdicts. When Claude asks for a pass/fail verdict on a test or a check, as a UAT or /gsd:verify-work step does ("Pass or fail?", "Did it pass?", "Type pass or describe what's wrong"), the band offers a verdict in place of your replies:
Reply: [Pass] [Fail…] [Skip]
Pass sends "pass" and Skip sends "skip", as your own message. Fail… sends nothing: it puts "Fail: " in the prompt, where you say what went wrong and can paste a screenshot. A test's numbered steps are not offered as choices, and a question that only mentions passing ("Shall I make the tests pass?") gets your usual replies.
Next ticket. When you work a map with the wayfinder skill, the band leads with the next ticket after each turn that closes one or charts the map:
Reply: [Next ticket: /wayfinder 135] [Continue] [Commit and push]
One press runs /clear and then /wayfinder 135, the loop you would otherwise type. It is offered only in a session that ran the wayfinder skill, after a turn whose gh issue close worked; after charting it names the map the turn created. A close made some other way (gh api, the web) is not seen, so no button shows, and once a turn closes the map itself the loop ends.
| Setting | Key | Default | Meaning | |||
|---|---|---|---|---|---|---|
| Replies to a question | questionReplies | `Yes\ | Go with your recommendation\ | No` | Shown after Claude asks something, separated by `\ | `; empty shows only the choices Claude offered |
| Replies otherwise | idleReplies | `Continue\ | Commit and push` | Shown after any other answer; empty hides the band then, except for Next ticket | ||
| Offer the next wayfinder ticket | wayfinderNext | true | After a wayfinder turn closes a ticket or charts a map, offer Next ticket | |||
| System One models | modelChoice | local only | Which System One model reads how each answer ends: local only (Laya on this machine, or the band's own reading as before), local first (Laya, and TypeSafe's hosted Jev while Laya is unavailable) or hosted first (Jev, and Laya while Jev is unavailable) | |||
| Jev API key | jevApiKey | empty | Your key for Jev, from console.typesafe.ai, kept in secure storage. Sent only to https://api.typesafe.ai, and only while System One models allows Jev | |||
| Laya port | layaPort | 8000 | The port your laya-serve listens on at 127.0.0.1 (1-65535) |
Each list holds up to six replies. A reply longer than 120 characters is cut short, and a repeat is dropped. For example, to answer questions with your own three replies and hide the band after other answers (how to set it):
echo '{"questionReplies": "Yes|No|Explain that first", "idleReplies": ""}' | claude plugin configure quick-reply@claude-mods --values-stdin
What the band sends to a System One model, once after each answered turn:
Laya and a Jev key are optional: with neither, the band reads each answer as before.
When a turn dies on a rate limit or an overloaded API, auto-resume counts down to the reset and sends "continue" for you. Go to lunch, and come back to finished work.
⏳ rate limited: sending "continue" in 1 h 12 min [Resume now] [Cancel]
| Command | What it does |
|---|---|
/auto-resume | Say what is waiting, if anything |
/auto-resume now | Send the resume now |
/auto-resume cancel | Cancel the wait |
/auto-resume in <minutes> | Schedule a resume yourself (1 to 1440) |
| Setting | Key | Default | Meaning |
|---|---|---|---|
| Resume prompt | text | continue | What is sent when the wait is over; empty sends continue |
| Grace after reset (s) | graceSeconds | 60 | Extra seconds to wait past the limit's reset time (0-900) |
| Retry overloaded/server errors | retryOverloaded | on | Also resume after an overloaded or server error, backing off from one minute |
| Most retries in a row | maxRetries | 5 | Give up after this many resumes without a successful answer (1-20) |
For example, to send a longer prompt and wait two minutes past the reset (how to set it):
echo '{"text": "continue where you left off", "graceSeconds": "120"}' | claude plugin configure auto-resume@claude-mods --values-stdin
A GitHub pane beside What's next listing the repo's open pull requests and issues. Click one to open it in the browser. Under each issue, implement and wayfinder put /implement or /wayfinder and the issue's URL in the prompt. Nothing is sent. While a /wayfinder effort is under way, its issue is pinned at the top, with the next ticket to take.
octocat/hello-world refresh
updated just now
Decide how shared code is copied unpin
3 done · 1 takeable · 1 claimed · 2 blocked
next: Pick the drift check decision
work next
Pull requests 2 all
#41 Add a drift check for copied guards
draft · @octocat
#40 Bring the asked pane to the front
✗ checks failing · @hubot fix
Issues 2 all
#39 Share the headless-session check
blocked by #12 · ready… implement wayfinder
#12 Decide how shared code is copied
needs-triage · @hubot implement wayfinder
implement and wayfinder buttons take a line of their own.r.fix button. It fills the prompt box with the failed checks' names, the last 40 lines of the failed run's log, and "Fix it." Nothing is sent: you read it and send it yourself. The log is fetched only when you press fix; when gh cannot fetch it, such as while the run is still going, the prompt holds the names alone./wayfinder on an issue of this repo (/wayfinder 12, /wayfinder #12 or the issue's URL) pins that issue and brings the pane to the front. Anything else, such as prose or another repo's issue, pins nothing. The pin is kept for the repo across sessions, one at a time: a run on another issue replaces it. It goes when you press unpin, or once the issue is closed.next is the first takeable ticket in the order the issue lists its sub-issues, with its wayfinder: type label; click it to open it on GitHub. With nothing takeable it says so; an issue with no sub-issues yet says no tickets yet.work next fills /wayfinder and the pinned issue's URL into the prompt, without sending it, so the skill takes the frontier ticket fresh when it runs.| Command or key | What it does |
|---|---|
/github | Bring the pane to the front and refresh it |
r | Refresh |
all | Open the whole list on GitHub |
implement, wayfinder | Fill the command and the issue's URL into the prompt, without sending it |
fix | Fill a request to fix the current branch's failing checks into the prompt box |
unpin | Drop the pinned issue |
work next | Fill /wayfinder and the pinned issue's URL into the prompt, without sending it |
| Setting | Key | Default | Meaning |
|---|---|---|---|
| Most items per list | limit | 30 | How many open pull requests and issues to list each (1-100) |
| Refresh every (minutes) | refreshMinutes | 5 | How often to refresh (0-120); 0 refreshes only on open, after turns and on r |
| Implement button fills | implementCommand | /implement | The slash command the implement button fills before the issue's URL; empty hides the button |
| Wayfinder button fills | wayfinderCommand | /wayfinder | The slash command the wayfinder and work next buttons fill before the issue's URL, and the skill whose runs pin an issue; empty hides the button and turns pinning off |
A command must start with / and hold no spaces. Any other value falls back to the default, and a message says so when the session starts. A button is labelled with its command, without the /.
For example, to list fifty of each and stop the timer (how to set it):
echo '{"limit": "50", "refreshMinutes": "0"}' | claude plugin configure github-panel@claude-mods --values-stdin
Needs: the GitHub CLI, logged in, and a folder with a GitHub remote.
A row of named folders and files above the prompt, for the paths you type again and again. Click a name and its path lands at the cursor in what you are typing. Nothing is sent.
Shelf: [brand] [records] [kb]
/shelf always lists them all.| Command | What it does |
|---|---|
/shelf | List the shelf with each path |
/shelf add <name> [path] | Put a path on the shelf; with no path, the project folder |
/shelf remove <name> | Take one off |
The shelf has no settings: you fill it with /shelf add.
/shelf add brand "N:/Marketing/Brand Kit"
/shelf add records N:/RECORDS
/shelf add kb
/shelf remove brand
hooks/register.tsx 143 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { SourcesView } from '../types'
5import { fullPath, grouped, isAllowed, named, normal, parseRequest, reached, refusal, shown, USAGE, withSource } from './paths'
6import type { Reach } from './paths'
7
8const PANE = 'sources'
9const TITLE = 'Sources'
10/** The settings dialog's command and its gear's key (ADR-0007). mod-settings takes the press; the gear's onPress is the fallback. */
11const SETTINGS = 'mod-settings'
12/** The most files a group lists before it counts the rest. */
13const MOST_ROWS = 8
14
15const EMPTY: SourcesView = { sources: [], isLocked: false, allowed: [] }
16const view = atom({ plugin: 'sources', key: 'view' } as const, EMPTY)
17
18// Each mod carries its own copy (ADR-0001): a session shown on no surface is headless.
19async function isShown($: EngineInterface): Promise<boolean> {
20 return (await $.session.surfaces()).length > 0
21}
22
23function report($: EngineInterface): (error: unknown) => void {
24 return error => $.ui.toast(`Sources: ${error instanceof Error ? error.message : String(error)}`)
25}
26
27/** Where a full path lands, symlinks and junctions followed, when it exists and can be looked at; else the path as folded. */
28async function landed($: EngineInterface, path: string): Promise<string> {
29 const stat = await $.fs.stat(path, { resolve: true }).catch(() => undefined)
30 return normal(stat?.realPath ?? path)
31}
32
33/**
34 * The first place the call reaches outside the project folder and the allowed folders, or undefined when
35 * all are inside. Each place is compared where it lands; each folder both as folded and where it lands,
36 * so a place not there yet still counts as inside a folder that is itself a link.
37 */
38async function outside($: EngineInterface, reach: Reach, folders: readonly string[]): Promise<string | undefined> {
39 if (reach.kind === 'unplaced') return reach.spelling
40 const bounds = (await Promise.all(folders.map(async folder => [normal(folder), await landed($, normal(folder))]))).flat()
41 for (const place of reach.places) {
42 const real = await landed($, place)
43 if (!isAllowed(real, bounds)) return real
44 }
45 return undefined
46}
47
48/** Whether mod-settings is installed: the gear shows only then. A command list that cannot be read shows none. */
49async function isSettingsInstalled($: EngineInterface): Promise<boolean> {
50 return (await $.command.list().catch(() => [])).some(command => command.name === SETTINGS)
51}
52
53export const register: Register = on => {
54 on('session.start', async ($, e, next) => {
55 const started = await next(e)
56 await $.command.register({ name: 'sources', description: 'Open the Sources pane: the files read this session. allow <path> lets reads into a folder while the lock is on' })
57 return started
58 })
59
60 // Matched by pattern: which read tools a session has depends on the machine.
61 on('tool.call', { tool: /^(Read|Grep|Glob)$/ }, async ($, e, next) => {
62 // Quiet in a headless session: nothing is refused and nothing is kept.
63 if (!(await isShown($).catch(() => false))) return next(e)
64 const cwd = await $.session.cwd()
65 const path = fullPath(named(e), cwd)
66 const current = await read($, view)
67 if (current.isLocked) {
68 const refused = await outside($, reached(e.tool, e, cwd), [cwd, ...current.allowed])
69 if (refused !== undefined) return { deny: refusal(refused) }
70 }
71 const called = await next(e)
72 if (called.deny === undefined) {
73 const at = await $.clock.now()
74 await update($, view, (held): SourcesView => ({ ...held, sources: withSource(held.sources, path, at) })).catch(() => undefined)
75 }
76 return called
77 })
78
79 on('command.run', { command: 'sources' }, async ($, e) => {
80 const request = parseRequest(e.args)
81 if (request.kind === 'usage') return { text: USAGE }
82 if (request.kind === 'allowed') {
83 const { allowed } = await read($, view)
84 return { text: allowed.length === 0 ? 'No folder outside the project folder is allowed.' : `Allowed besides the project folder:\n${allowed.join('\n')}` }
85 }
86 if (request.kind === 'allow') {
87 const folder = fullPath(request.path, await $.session.cwd())
88 await update($, view, (held): SourcesView => ({
89 ...held,
90 allowed: held.allowed.some(each => each.toLowerCase() === folder.toLowerCase()) ? held.allowed : [...held.allowed, folder],
91 }))
92 return { text: `Reads are allowed in ${folder} for this session.` }
93 }
94 // Asked, the pane comes in front of the others and takes the keyboard, which Esc hands back.
95 await $.ui.open({ id: PANE, title: TITLE, focus: true })
96 return { text: 'Sources pane opened.' }
97 })
98
99 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
100 const { Box, Text, Button } = $.ui.resolve(e)
101 const hasSettings = await isSettingsInstalled($)
102 const current = await read($, view)
103 const cwd = normal(await $.session.cwd())
104 const width = Math.max(16, e.props.bodyColumns)
105 const room = width - 3
106 const groups = grouped(current.sources, cwd)
107
108 return (
109 <Box flexDirection="column" width={width}>
110 <Box flexDirection="row" justifyContent="space-between">
111 <Text bold={current.isLocked} color={current.isLocked ? 'yellow' : undefined}>
112 {current.isLocked ? 'Reads: this folder only' : 'Reads: anywhere'}
113 </Text>
114 <Box flexDirection="row" columnGap={1}>
115 <Button
116 key="lock"
117 plain
118 dimColor
119 hotkey="l"
120 label={current.isLocked ? 'unlock' : 'lock'}
121 onPress={() => void update($, view, (held): SourcesView => ({ ...held, isLocked: !held.isLocked })).catch(report($))}
122 />
123 {hasSettings && <Button key={SETTINGS} plain dimColor label="⚙️" onPress={() => void $.command.run({ command: SETTINGS }).catch(report($))} />}
124 </Box>
125 </Box>
126 {current.isLocked && current.allowed.map((folder, index) => (
127 <Text key={`allowed-${index}`} dimColor wrap="truncate-start">{` also ${folder}`}</Text>
128 ))}
129 {groups.length === 0 && <Text dimColor wrap="wrap">Nothing read yet this session.</Text>}
130 {groups.map((group, at) => (
131 <Box key={`group-${at}`} flexDirection="column" marginTop={1}>
132 <Text key={`group-title-${at}`} bold wrap="truncate-start">{`${group.label} ${group.sources.length}`}</Text>
133 {group.sources.slice(0, MOST_ROWS).map((source, index) => (
134 <Text key={`source-${at}-${index}`} dimColor>{` ${shown(source.path, group.isProject ? cwd : group.label, room)}`}</Text>
135 ))}
136 {group.sources.length > MOST_ROWS && <Text dimColor>{` +${group.sources.length - MOST_ROWS} more`}</Text>}
137 </Box>
138 ))}
139 </Box>
140 )
141 })
142}
143hooks/paths.ts 154 lines1import type { Source } from '../types'
2
3/** The most sources the pane keeps. */
4export const MOST_SOURCES = 300
5
6export type Group = { label: string; isProject: boolean; sources: Source[] }
7
8/** What `/sources` was asked to do, read from everything typed after the name. */
9export type Request = { kind: 'open' } | { kind: 'allowed' } | { kind: 'allow'; path: string } | { kind: 'usage' }
10
11export const USAGE = 'Usage: /sources, /sources allow, /sources allow <path>'
12
13/**
14 * The path with forward slashes, its `.` and `..` segments folded and no trailing slash, so two spellings
15 * of a place compare equal. A `..` at a drive, share or root stays there, as the file system has it;
16 * one at the start of a relative path is kept.
17 */
18export function normal(path: string): string {
19 const slashed = path.replace(/\\/g, '/')
20 const [, head = '', rest = ''] = /^(\/\/[^/]+\/[^/]+|[A-Za-z]:(?=\/|$)|\/?)(.*)$/.exec(slashed) ?? []
21 const parts: string[] = []
22 for (const part of rest.split('/')) {
23 if (part === '' || part === '.') continue
24 if (part !== '..') parts.push(part)
25 else if (parts.length > 0 && parts[parts.length - 1] !== '..') parts.pop()
26 else if (head === '') parts.push(part)
27 }
28 const body = parts.join('/')
29 if (head === '') return body === '' ? '.' : body
30 // A bare drive or the root keeps its slash; a share has none of its own.
31 if (head.startsWith('//')) return body === '' ? head : `${head}/${body}`
32 return head === '/' ? `/${body}` : `${head}/${body}`
33}
34
35function isAbsolute(path: string): boolean {
36 return /^([A-Za-z]:[\\/]|[\\/])/.test(path)
37}
38
39/**
40 * Whether the tool reads the path from somewhere its spelling does not say: `~` is the home folder to it,
41 * and `D:x` is relative to that drive's own current folder.
42 */
43function isUnplaceable(path: string): boolean {
44 return /^~\w*(?:[\\/]|$)/.test(path) || /^[A-Za-z]:(?![\\/])/.test(path)
45}
46
47/** The full path of what a tool named, which may be given from the project folder, with its `.` and `..` folded. */
48export function fullPath(path: string, cwd: string): string {
49 return normal(isAbsolute(path) ? path : `${cwd}/${path}`)
50}
51
52/** Whether `path` is the folder or lies inside it, once both are folded. Letter case is passed over, as Windows does. */
53export function isUnder(path: string, folder: string): boolean {
54 const inner = normal(path).toLowerCase()
55 const outer = normal(folder).toLowerCase()
56 return inner === outer || inner.startsWith(outer.endsWith('/') ? outer : `${outer}/`)
57}
58
59/** Whether `path` is one of the folders or lies inside one. */
60export function isAllowed(path: string, folders: readonly string[]): boolean {
61 return folders.some(folder => isUnder(path, folder))
62}
63
64/** What a read tool's call names: a file for Read, the folder searched for Grep and Glob (the project folder when none is given). */
65export function named(input: object): string {
66 const { file_path: file, path } = input as { file_path?: unknown; path?: unknown }
67 if (typeof file === 'string') return file
68 return typeof path === 'string' ? path : '.'
69}
70
71/** Where a read tool's call reaches: full paths, or the spelling no folder bounds. */
72export type Reach = { kind: 'places'; places: string[] } | { kind: 'unplaced'; spelling: string }
73
74/**
75 * The places a read tool's call reaches, each a full path: the file Read names; for Grep and Glob, the folder
76 * searched and, for Glob's `pattern` or Grep's `glob`, the folder before its first wildcard (the whole
77 * pattern when it has none). Grep's own
78 * `pattern` is a regex, not a path. A spelling no folder bounds is given back instead: `~`, `D:x`, or a `..`
79 * after a wildcard or among braces.
80 */
81export function reached(tool: string, input: object, cwd: string): Reach {
82 const { pattern, glob } = input as { pattern?: unknown; glob?: unknown }
83 const filter = tool === 'Glob' ? pattern : tool === 'Grep' ? glob : undefined
84 const spellings = [named(input), ...(typeof filter === 'string' ? [filter] : [])]
85 const unplaced = spellings.find(isUnplaceable)
86 if (unplaced !== undefined) return { kind: 'unplaced', spelling: unplaced }
87 const [searched = '.', ...filters] = spellings
88 const folder = fullPath(searched, cwd)
89 const places = [folder]
90 for (const each of filters) {
91 const slashed = each.replace(/\\/g, '/')
92 const parts = slashed.split('/')
93 const wild = parts.findIndex(part => /[*?[\]{}]/.test(part))
94 const literal = wild === -1 ? parts : parts.slice(0, wild)
95 if (wild !== -1 && parts.slice(wild).some(part => /(?:^|[{,])\.\.(?:$|[},])/.test(part))) return { kind: 'unplaced', spelling: each }
96 // A pattern that starts at the root keeps it.
97 places.push(fullPath(literal.join('/') || (slashed.startsWith('/') ? '/' : '.'), folder))
98 }
99 return { kind: 'places', places }
100}
101
102/** Where a path outside the project folder came from: its drive or share with its first two folders. */
103export function rootOf(path: string): string {
104 const clean = normal(path)
105 const [, head = '', rest = ''] = /^([A-Za-z]:|\/\/[^/]+\/[^/]+|)\/?(.*)$/.exec(clean) ?? []
106 // The last part is the file itself.
107 const folders = rest.split('/').slice(0, -1).slice(0, 2)
108 return `${head}/${folders.join('/')}`.replace(/\/$/, '') || '/'
109}
110
111/** The sources with `path` newest, each path once, within the bound. */
112export function withSource(sources: readonly Source[], path: string, at: number): Source[] {
113 const key = path.toLowerCase()
114 return [{ path, at }, ...sources.filter(held => held.path.toLowerCase() !== key)].slice(0, MOST_SOURCES)
115}
116
117/** The project folder's group first, then each other root in the order it was last read. */
118export function grouped(sources: readonly Source[], cwd: string): Group[] {
119 const groups = new Map<string, Group>()
120 const project: Group = { label: 'This folder', isProject: true, sources: [] }
121 for (const source of sources) {
122 if (isUnder(source.path, cwd)) {
123 project.sources.push(source)
124 continue
125 }
126 const label = rootOf(source.path)
127 const group = groups.get(label.toLowerCase()) ?? { label, isProject: false, sources: [] }
128 group.sources.push(source)
129 groups.set(label.toLowerCase(), group)
130 }
131 return [...(project.sources.length > 0 ? [project] : []), ...groups.values()]
132}
133
134/** The path as a group's line shows it: without the group's own folder, cut from the front to fit. */
135export function shown(path: string, folder: string, max: number): string {
136 const inner = isUnder(path, folder) && normal(path).length > normal(folder).length ? normal(path).slice(normal(folder).replace(/\/$/, '').length + 1) : normal(path)
137 const chars = Array.from(inner)
138 return chars.length <= max ? inner : `…${chars.slice(chars.length - Math.max(1, max - 1)).join('')}`
139}
140
141export function parseRequest(args: string): Request {
142 const trimmed = args.trim()
143 if (trimmed === '') return { kind: 'open' }
144 const [, verb = '', rest = ''] = /^(\S+)\s*(.*)$/.exec(trimmed) ?? []
145 if (verb !== 'allow') return { kind: 'usage' }
146 const path = (/^"(.*)"$/.exec(rest) ?? /^'(.*)'$/.exec(rest))?.[1] ?? rest
147 return path === '' ? { kind: 'allowed' } : { kind: 'allow', path }
148}
149
150/** Why a read outside the allowed folders is refused, for the model to pass on. */
151export function refusal(path: string): string {
152 return `sources: reads are kept to the project folder while the lock is on, and ${path} is outside it. The person can allow a folder with /sources allow <path>, or turn the lock off with l in the Sources pane.`
153}
154types/index.d.ts 18 lines1/** One file read or folder searched: its full path with forward slashes, and when it was last read. */
2export type Source = { path: string; at: number }
3
4export type SourcesView = {
5 /** Newest first, each path once. */
6 sources: Source[]
7 /** True while reads are kept to the project folder and the allowed folders. */
8 isLocked: boolean
9 /** Folders outside the project folder that the person allowed for this session. */
10 allowed: string[]
11}
12
13declare module 'claude-code' {
14 interface PluginState {
15 sources: { view: SourcesView }
16 }
17}
18