/mode readonly, research, prototype and build: a working mode enforced for the whole session

A mod (a plugin that adds hooks to Claude Code) that adds the /mode command. A mode sets a working rule for the whole session, and the mod blocks any tool call that breaks the rule.
An instruction in a prompt can fade in a long session. With /mode readonly, Claude cannot edit a file, even if you forget to repeat the rule. With /mode build, Claude cannot push or open a pull request.
Each mode also adds one sentence to the system prompt (the instructions Claude reads each turn). Claude knows the rule before the hook has to block anything.
/plugin marketplace add cpeaustriajc/cj-stack
/plugin install session-modes@cj-stack
To see that it is on, run claude plugin list and look for session-modes. The mod is optional: cj-stack does not install it.
/mode readonly. The mod answers "Mode readonly on."src/app.ts. The mod blocks the call./mode off to leave.The mode for code changes is build, not edit, so it is not confused with the Edit tool. The modes form a ladder, from the strictest to the loosest: readonly, research, prototype, build, off. Each tool call needs one level. A mode blocks a call that needs a higher level than the mode.
| Mode | Allows | Blocks |
|---|---|---|
readonly | Reading, git status, git log, redirects to /dev/null | Everything in the rows below |
research | Edits to .md and .markdown files, a redirect to such a file, git commit, tracker writes, an Artifact publish | Edits to any other file, a redirect to any other file, git push, pull requests |
prototype | Edits to any file under .claude/work/, a redirect to such a file, and the Claude Design artifacts Claude publishes there | Edits to app code, the rows below |
build | Edits to any file, redirects to any file | git push, gh pr create, gh pr merge, pull request writes through gh api or an MCP tool |
A tracker write is an MCP tool with a write word in its name, such as save_issue or createJiraIssue. It is also gh issue create, a gh api call with -X POST, or acli jira workitem create. A pull request write is an MCP tool such as create_pull_request, or a gh api call on a /pulls path with -X POST or a field flag. An MCP tool with push in its name needs /mode off. The desktop app's own bookkeeping tools need only readonly, whatever their names. These are mcp__ccd_turn__* (the task list, such as update_plan), mcp__ccd_view__*, mcp__ccd_window__*, mcp__ccd_sidebar__* and this mod's agent_mode. Other mcp__ccd_* tools, such as set_setting or delete_session, are judged by their names. The Artifact tool needs research to publish; reading, listing and opening an artifact need readonly.
A Bash command with several parts, such as git commit -m x && git push, needs the highest level of its parts.
Other commands:
/mode alone shows "Current mode: off. Modes: readonly, research, prototype, build, off. Also: clear, agents on, agents off."/mode off removes the mode and shows "Mode off."/mode clear clears the modes Claude set./mode agents off and /mode agents on block and allow the agent_mode tool. See "Your overrides".Unknown mode "<name>" and changes nothing./mode lists the five names, clear and agents in the prompt suggestions. Typing /mode agents lists on and off.While a mode is on, a band above the prompt shows it in the terminal and in the desktop app. The band has the mode name in bold and in the mode's colour, the rule in one line and a "Turn off" button. For readonly it reads "Read only Read and report only. Edits, commits, pushes, PRs and tracker writes are blocked." The "Turn off" button does what /mode off does. In a band narrower than 60 columns, the band shows the first sentence only. The band hides while a survey is on screen and when no mode is set.
When the mode changes, also by "Turn off", the mod adds a hidden note to your next message. The note says the current mode, for example "Session mode: off. Read only mode has ended; its rules no longer apply". The mod also puts the mode in the system prompt each turn, but the desktop app does not pass that text to the model. A subagent started while a mode is on gets the rule at the top of its task. The mod blocks its tool calls like the main thread's. Workflow agents get it too, from Claude Code 2.1.300. A resumed agent does not, because a hook cannot change a resumed agent's prompt.
The mod adds a tool, agent_mode. Claude can call it to set a mode for itself (scope self) or for its subagents (scope subagents). The mode also reaches subagents that are already running. Example: with your mode off, Claude sets readonly for subagents and starts three Explore subagents. Each one gets the Read only rule at the top of its task, and any Edit it makes is denied. The main thread can still edit.
A call is denied when any rule that applies to the caller denies it, so the stricter rule always wins. Claude cannot loosen your /mode: its off clears only the modes it set itself. A subagent can set modes for itself and for its own subagents in the same way. /mode off and the band's "Turn off" clear every mode Claude set. /mode readonly does not.
Claude also picks its own mode for each message you send. The mod adds a hidden note that asks for the pick and names Claude's current mode. Claude calls agent_mode with scope self when the pick differs. The note goes on messages you type in the terminal, in the desktop app or through Remote Control. It does not go on task notifications, scheduled prompts or messages from other sessions. The mod skips the note while your own mode is readonly.
Example: you type "why does the band hide at 50 columns? do not change anything". Claude sets readonly for itself, and a later Edit is denied. You type "how would a wider band look?". Claude sets prototype and builds a Claude Design artifact. You type "ok, fix it". Claude sets build. You type "fix it and open a PR". Claude sets off.
The band shows the modes Claude set on a second row, for example "Set by Claude: Read only for itself and Build for subagents". Each mode name has the same colour as on your own row. With your mode off, that row is all the band shows. The row leaves out a mode that is not stricter than yours, because your mode already covers it. Example: you type /mode readonly and Claude sets readonly for itself; the band shows only your row. If you then type /mode build, Claude's Read only shows again. /mode alone adds the same text to its report.
You can always take control back from a mode Claude set.
/mode clear does the same. It shows "Cleared Claude's modes." or, with nothing set, "Claude has no modes set."/mode agents off clears the modes Claude set and blocks the agent_mode tool. It also stops the hidden note that asks for Claude's pick. While it is off, the mod denies a call with any mode except off. The reason is "The user turned off agent modes with /mode agents off." /mode alone then ends with "Agent modes: off."/mode agents on turns the tool back on.agents shows "Use /mode agents off or /mode agents on." and changes nothing.Claude is told on your next message. For example, after "Clear" it reads "Session mode: the user cleared the modes you set (Read only for itself). They no longer apply." /mode off and the band's "Turn off" send the same note when Claude had set a mode. Each note is sent once.
The mod writes { "v": 1, "mode": "readonly" } to ~/.claude/mod-state/<session id>.session-modes.json for a custom status line to read. With no mode, mode is null. If CLAUDE_CONFIG_DIR is set, the file goes to $CLAUDE_CONFIG_DIR/mod-state. At session start, the mod deletes its state files older than seven days.
No settings. To turn the mod off, run claude plugin disable session-modes@cj-stack.
readonly does not block a Bash command that writes without a redirect, such as sed -i.mcp__ccd_host__sync_with_base_branch. The bookkeeping tools pass too, also mcp__ccd_sidebar__delete_group.> inside quotes is not a redirect, but one inside a heredoc is, and the commands above inside quotes or a heredoc are blocked.hooks/register.tsx 335 lines1import { atom, read, update } from 'claude-code'
2import type { Hook, Register } from 'claude-code'
3import {
4 AGENTS_OFF_DENY,
5 AGENTS_OFF_NOTE,
6 AGENTS_ON_NOTE,
7 AGENT_TOOL,
8 AGENT_TOOL_DESCRIPTION,
9 AGENT_TOOL_SCHEMA,
10 CHECK_NOTE,
11 CLEARED_NOTE,
12 INHERITED_NOTE,
13 LADDER,
14 MODE_NOTE,
15 MODES,
16 OFF_SECTION,
17 SUBAGENT_NOTE,
18 agentModeText,
19 claudeParts,
20 holdsAny,
21 parseMode,
22 parseOverride,
23 parseScope,
24 report,
25 reword,
26 uncovered,
27 verdict,
28} from './modes'
29import type { Active, Held, Mode } from './modes'
30import { modeSuggestions } from './suggest'
31
32type Api = Parameters<Hook<'session.start'>>[0]
33
34const MOD = 'session-modes'
35const WEEK = 7 * 86_400_000
36
37async function stateDir($: Api): Promise<string | undefined> {
38 const config = await $.env.get('CLAUDE_CONFIG_DIR')
39 if (config) return `${config}/mod-state`
40 const home = (await $.env.get('HOME')) || (await $.env.get('USERPROFILE'))
41 return home ? `${home}/.claude/mod-state` : undefined
42}
43
44async function remove($: Api, paths: string[]): Promise<void> {
45 if (paths.length === 0) return
46 await $.process.run(['rm', '-f', '--', ...paths])
47}
48
49export async function publishState($: Api, mode: string): Promise<void> {
50 try {
51 const dir = await stateDir($)
52 if (!dir) return
53 const path = `${dir}/${await $.session.id()}.${MOD}.json`
54 await $.fs.write(path, JSON.stringify({ v: 1, mode: mode === 'off' ? null : mode }))
55 } catch (cause) {
56 throw new Error(`${MOD}: could not publish state for the status line`, { cause })
57 }
58}
59
60export async function pruneState($: Api): Promise<void> {
61 try {
62 const dir = await stateDir($)
63 if (!dir || !(await $.fs.exists(dir))) return
64 const now = await $.clock.now()
65 const stale = (await $.fs.list(dir)).filter(
66 f => f.kind === 'file' && f.name.endsWith(`.${MOD}.json`) && now - f.mtimeMs > WEEK,
67 )
68 await remove($, stale.map(f => `${dir}/${f.name}`))
69 } catch (cause) {
70 throw new Error(`${MOD}: could not prune old state files`, { cause })
71 }
72}
73
74const mode = atom({ plugin: 'session-modes', key: 'mode' } as const, 'off' as Mode)
75const ended = atom({ plugin: 'session-modes', key: 'ended' } as const, null as Active | null)
76const told = atom({ plugin: 'session-modes', key: 'told' } as const, 'off' as Mode)
77const agentModes = atom({ plugin: 'session-modes', key: 'agentModes' } as const, {} as Record<string, Held>)
78const parents = atom({ plugin: 'session-modes', key: 'parents' } as const, {} as Record<string, string>)
79const pending = atom({ plugin: 'session-modes', key: 'pending' } as const, [] as string[])
80const agentsAllowed = atom({ plugin: 'session-modes', key: 'agentsAllowed' } as const, true)
81const SECTION_ID = 'session-modes:mode'
82
83const NARROW = 60
84const MAIN = 'main'
85const NONE: Held = { self: null, subagents: null }
86
87const tell = ($: Api, note: string) => update($, pending, all => [...all, note])
88
89async function clearAgentModes($: Api): Promise<boolean> {
90 const all = await read($, agentModes)
91 if (!holdsAny(all)) return false
92 await update($, agentModes, () => ({}))
93 await tell($, CLEARED_NOTE(claudeParts(all[MAIN]) ?? 'modes set by subagents'))
94 return true
95}
96
97async function setMode($: Api, wanted: Mode): Promise<void> {
98 const old = await read($, mode)
99 await update($, mode, () => wanted)
100 if (wanted === 'off') await clearAgentModes($)
101 if (wanted !== 'off') await update($, ended, () => null)
102 else if (old !== 'off') await update($, ended, () => old)
103 await publishState($, wanted)
104}
105
106export const register: Register = on => {
107 on('session.start', async ($, e, next) => {
108 const result = await next(e)
109 // The desktop app runs sessions through the SDK, so isInteractive is false there.
110 await $.tool.register({
111 name: 'agent_mode',
112 description: AGENT_TOOL_DESCRIPTION,
113 inputSchema: AGENT_TOOL_SCHEMA,
114 isDeferred: false,
115 })
116 await $.command.register({
117 name: 'mode',
118 description: 'Set the session mode: readonly, research, prototype, build or off',
119 argumentHint: 'readonly | research | prototype | build | off',
120 })
121 const current = await read($, mode)
122 if (current !== 'off') await publishState($, current)
123 await pruneState($)
124 return result
125 })
126
127 on('command.run', { command: 'mode' }, async ($, e) => {
128 const wanted = e.args.trim() === '' ? undefined : parseMode(e.args)
129 if (e.args.trim() === '') {
130 const held = claudeParts(uncovered((await read($, agentModes))[MAIN], await read($, mode)))
131 const agentsOff = (await read($, agentsAllowed)) ? '' : ' Agent modes: off.'
132 return { text: report(await read($, mode)) + (held ? ` Set by Claude: ${held}.` : '') + agentsOff }
133 }
134 const override = parseOverride(e.args)
135 if (override === 'clear') {
136 return { text: (await clearAgentModes($)) ? "Cleared Claude's modes." : 'Claude has no modes set.' }
137 }
138 if (override === 'agents-invalid') return { text: 'Use /mode agents off or /mode agents on.' }
139 if (override === 'agents-off') {
140 await update($, agentsAllowed, () => false)
141 await clearAgentModes($)
142 await tell($, AGENTS_OFF_NOTE)
143 return { text: 'Agent modes off. Claude cannot set modes.' }
144 }
145 if (override === 'agents-on') {
146 await update($, agentsAllowed, () => true)
147 await tell($, AGENTS_ON_NOTE)
148 return { text: 'Agent modes on.' }
149 }
150 if (!wanted) return { text: `Unknown mode "${e.args.trim()}". ${report(await read($, mode))}` }
151 await setMode($, wanted)
152 return { text: wanted === 'off' ? 'Mode off.' : `Mode ${wanted} on.` }
153 })
154
155 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
156 const current = await read($, mode)
157 const held = uncovered((await read($, agentModes))[MAIN], current)
158 const claude = claudeParts(held)
159 if ((current === 'off' && !claude) || e.props.hasSurvey) return next(e)
160 const { Box, Text, Button } = $.ui.resolve(e)
161 const claudeRow = claude ? (
162 <Box flexDirection="row" gap={1}>
163 <Box flexGrow={1} flexShrink={1}>
164 <Text wrap="truncate-end">
165 <Text dimColor>Set by Claude: </Text>
166 {(['self', 'subagents'] as const)
167 .filter(scope => held?.[scope])
168 .map((scope, i) => (
169 <Text key={scope}>
170 {i ? <Text dimColor> and </Text> : null}
171 <Text weight="semibold" color={LADDER[held![scope]!].chip}>
172 {LADDER[held![scope]!].label}
173 </Text>
174 <Text dimColor>{scope === 'self' ? ' for itself' : ' for subagents'}</Text>
175 </Text>
176 ))}
177 </Text>
178 </Box>
179 <Button
180 key="clear-agents"
181 label="Clear"
182 onPress={async () => {
183 await clearAgentModes($)
184 await $.ui.toast("Claude's modes cleared.")
185 }}
186 />
187 </Box>
188 ) : null
189 if (current === 'off') return <Box flexDirection="column">{claudeRow}</Box>
190 const { label, chip, lead, detail } = LADDER[current]
191 return (
192 <Box flexDirection="column">
193 <Box flexDirection="row" gap={1}>
194 <Text weight="semibold" color={chip}>
195 {label}
196 </Text>
197 <Box flexGrow={1} flexShrink={1}>
198 <Text wrap="truncate-end">
199 {lead}
200 {e.props.bodyColumns < NARROW ? null : <Text dimColor>{' ' + detail}</Text>}
201 </Text>
202 </Box>
203 <Button
204 key="off"
205 label="Turn off"
206 onPress={async () => {
207 await setMode($, 'off')
208 await $.ui.toast('Mode off.')
209 }}
210 />
211 </Box>
212 {claudeRow}
213 </Box>
214 )
215 })
216
217 on('tool.call', async ($, e, next) => {
218 const input = e as { command?: unknown; file_path?: unknown; notebook_path?: unknown; mode?: unknown; scope?: unknown }
219 const caller = e.agentId ?? MAIN
220 if (e.tool === AGENT_TOOL) {
221 const wanted = typeof input.mode === 'string' ? parseMode(input.mode) : undefined
222 const scope = parseScope(input.scope)
223 if (!wanted || !scope) {
224 return { deny: `agent_mode needs a mode (${MODES.join(', ')}) and a scope (self or subagents).` }
225 }
226 if (wanted !== 'off' && !(await read($, agentsAllowed))) return { deny: AGENTS_OFF_DENY }
227 const held = (await read($, agentModes))[caller] ?? NONE
228 const user = await read($, mode)
229 const text = agentModeText(wanted, scope, held[scope], user)
230 await update($, agentModes, all => ({
231 ...all,
232 [caller]: { ...(all[caller] ?? NONE), [scope]: wanted === 'off' ? null : wanted },
233 }))
234 return { result: text } as never
235 }
236 const command = e.tool === 'Bash' && typeof input.command === 'string' ? input.command : ''
237 const rawPath = input.file_path ?? input.notebook_path
238 const path = typeof rawPath === 'string' ? rawPath : ''
239 const action = (e as { action?: unknown }).action
240 const call = { tool: e.tool, command, path, action: typeof action === 'string' ? action : '' }
241 const user = verdict(await read($, mode), call)
242 if (user) return { deny: user }
243 const held = await read($, agentModes)
244 const own = held[caller]?.self
245 const ownDeny = own ? verdict(own, call) : undefined
246 if (ownDeny) return { deny: reword(ownDeny, 'agent_mode off with scope self to leave.') }
247 const links = await read($, parents)
248 const seen = new Set<string>([caller])
249 for (let at = links[caller]; at !== undefined && !seen.has(at); at = links[at]) {
250 seen.add(at)
251 const above = held[at]?.subagents
252 const aboveDeny = above ? verdict(above, call) : undefined
253 if (aboveDeny) return { deny: reword(aboveDeny, 'set by the agent that started you.') }
254 }
255 return next(e)
256 }).catch(($, e, next) =>
257 next.called ? next(e) : { deny: `session-modes: could not check this call, so it is denied (${next.error.message ?? next.error.kind}).` },
258 )
259
260 on('prompt.compose', async ($, e, next) => {
261 const result = await next(e)
262 const current = await read($, mode)
263 const last = await read($, ended)
264 const text = current !== 'off' ? LADDER[current].section : last ? OFF_SECTION(last) : undefined
265 if (text === undefined) return result
266 return { sections: [...result.sections, { id: SECTION_ID, text, scope: 'session' }] }
267 })
268
269 on('prompt.submit', async ($, e, next) => {
270 const current = await read($, mode)
271 const extra = await read($, pending)
272 const added: string[] = []
273 if (current !== (await read($, told))) {
274 added.push(MODE_NOTE(current, await read($, ended)))
275 await update($, told, () => current)
276 }
277 if (extra.length) {
278 added.push(...extra)
279 await update($, pending, () => [])
280 }
281 const kind = e.origin.kind
282 if (
283 (kind === 'composer' || kind === 'bridge' || kind === 'sdk') &&
284 e.isMeta !== true &&
285 (await read($, agentsAllowed)) &&
286 current !== 'readonly'
287 ) {
288 added.push(CHECK_NOTE((await read($, agentModes))[MAIN]?.self ?? null))
289 }
290 if (added.length === 0) return next(e)
291 return next({ ...e, context: [...(e.context ?? []), ...added] })
292 })
293
294 on('agent.spawn', async ($, e, next) => {
295 const parent = e.parentAgentId ?? MAIN
296 if (e.resume) {
297 // The engine ignores a prompt rewrite on a resume, so pass the event on unchanged.
298 const resumed = await next(e)
299 const id = resumed.agentId
300 if (id) await update($, parents, all => (id in all ? all : { ...all, [id]: parent }))
301 return resumed
302 }
303 const current = await read($, mode)
304 const notes: string[] = []
305 if (current !== 'off') notes.push(SUBAGENT_NOTE(current))
306 const held = await read($, agentModes)
307 const links = await read($, parents)
308 const inherited: Active[] = []
309 const seen = new Set<string>()
310 for (let at: string | undefined = parent; at !== undefined && !seen.has(at); at = links[at]) {
311 seen.add(at)
312 const m = held[at]?.subagents
313 if (m && m !== current && !inherited.includes(m)) inherited.push(m)
314 }
315 notes.push(...inherited.map(INHERITED_NOTE))
316 const result = await next(notes.length ? { ...e, prompt: `${notes.join(' ')}\n\n${e.prompt}` } : e)
317 if (result.agentId) {
318 const child = result.agentId
319 await update($, parents, all => ({ ...all, [child]: parent }))
320 }
321 return result
322 }).catch(async ($, e, next) => {
323 if (next.error.kind !== 're-entry') {
324 await $.ui.toast(`session-modes: the agent.spawn hook failed (${next.error.message ?? next.error.kind}); mode notes may be missing.`)
325 }
326 return next(e)
327 })
328
329 on('prompt.autocomplete', async ($, e, next) => {
330 const rows = modeSuggestions(e.text, e.cursor, await read($, mode))
331 const out = await next(e)
332 return rows.length ? { suggestions: [...out.suggestions, ...rows] } : out
333 })
334}
335hooks/modes.ts 243 lines1type Row = {
2 label: string
3 chip: string
4 section: string
5 instead: string
6 lead: string
7 detail: string
8 hint: string
9}
10
11// Key order is the ladder, strictest first: need() compares positions.
12export const LADDER = {
13 readonly: {
14 label: 'Read only',
15 chip: 'planMode',
16 section:
17 'Read only mode: read and report only. Do not edit files, commit, push, open pull requests or write to trackers; list findings instead.',
18 instead: 'report the change instead of making it',
19 lead: 'Read and report only.',
20 detail: 'Edits, commits, pushes, PRs and tracker writes are blocked.',
21 hint: 'read and report only',
22 },
23 research: {
24 label: 'Research',
25 chip: 'merged',
26 section:
27 'Research mode: write no code. Put findings and plans in Markdown files or the tracker, and commit them if the work needs it. Do not push or open pull requests.',
28 instead: 'put the finding or plan in a Markdown file or the tracker instead',
29 lead: 'Notes, plans and tracker items only.',
30 detail: 'Code edits, pushes and PRs are blocked.',
31 hint: 'notes and plans, no code',
32 },
33 prototype: {
34 label: 'Prototype',
35 chip: 'suggestion',
36 section:
37 'Prototype mode: show the design before any app code. Build it as a Claude Design artifact (Artifact quickstart, intent design) or as HTML in .claude/work/<topic>/. Do not edit app code, push or open pull requests.',
38 instead: 'build it in a Claude Design artifact or in .claude/work/ instead',
39 lead: 'Designs and prototypes only.',
40 detail: 'App code edits, pushes and PRs are blocked.',
41 hint: 'designs and prototypes, no app code',
42 },
43 build: {
44 label: 'Build',
45 chip: 'ide',
46 section:
47 'Build mode: edit and commit locally. Do not push or open pull requests; report the result in the reply and leave the push and the pull request to the user.',
48 instead: 'commit locally and leave the push and the pull request to the user',
49 lead: 'Edits and commits are allowed.',
50 detail: 'Pushes and PRs are blocked.',
51 hint: 'edit and commit, no push or PR',
52 },
53} as const satisfies Record<string, Row>
54
55export type Active = keyof typeof LADDER
56
57export type Mode = Active | 'off'
58
59export const MODES: readonly Mode[] = [...(Object.keys(LADDER) as Active[]), 'off']
60
61export function parseMode(args: string): Mode | undefined {
62 const name = args.trim().toLowerCase()
63 return (MODES as readonly string[]).includes(name) ? (name as Mode) : undefined
64}
65
66export const OFF_SECTION = (ended: Active): string =>
67 `Session mode: off. ${LADDER[ended].label} mode has ended; its rules no longer apply, even if the conversation still shows it on.`
68
69export const MODE_NOTE = (current: Mode, ended: Active | null): string =>
70 current !== 'off'
71 ? `Session mode: ${LADDER[current].label} is on. ${LADDER[current].section}`
72 : ended
73 ? OFF_SECTION(ended)
74 : 'Session mode: off.'
75
76export const SUBAGENT_NOTE = (mode: Active): string =>
77 `The main session is in ${LADDER[mode].label} mode, and it applies to you too. ${LADDER[mode].section} Tool calls that break it are denied.`
78
79export type Scope = 'self' | 'subagents'
80
81export type Held = { self: Active | null; subagents: Active | null }
82
83export const AGENT_TOOL = 'mcp__session-modes__agent_mode'
84
85export const AGENT_TOOL_DESCRIPTION =
86 'Set a working mode for yourself (scope "self") or for your subagents (scope "subagents"); it applies at once, also to subagents already running, and subagents you start later get it in their task text. Modes: readonly (read and report only), research (notes, plans and tracker items; no code), prototype (a Claude Design artifact or files in .claude/work/; no app code), build (edit and commit; no push or PR). "off" clears the mode you set in that scope. You can only add limits: a mode the user set with /mode stays in force, and the stricter rule always wins. Pick your own mode at the start of each user message, read with the conversation: readonly for a question, a review, an explanation or "do not change anything"; research for a plan, a spec, notes or tickets; prototype for a UI idea, a layout choice or a design to see before the build; build for a code or config change; off only when the message asks you to push, or to open or merge a pull request. A short reply such as "yes" or "go ahead" takes the mode of the work it approves.'
87
88export const CHECK_NOTE = (own: Active | null): string =>
89 `Session mode check: pick your own mode for this message, as agent_mode describes. Now: ${own ?? 'off'}. If your pick differs, call agent_mode with that mode and scope self before any other tool call.`
90
91export const AGENT_TOOL_SCHEMA = {
92 type: 'object',
93 properties: {
94 mode: { type: 'string', enum: [...MODES] },
95 scope: { type: 'string', enum: ['self', 'subagents'] },
96 },
97 required: ['mode', 'scope'],
98}
99
100export function parseScope(raw: unknown): Scope | undefined {
101 return raw === 'self' || raw === 'subagents' ? raw : undefined
102}
103
104export const INHERITED_NOTE = (mode: Active): string =>
105 `The agent that started you set ${LADDER[mode].label} mode for its subagents, and it applies to you. ${LADDER[mode].section} Tool calls that break it are denied.`
106
107export const agentModeText = (wanted: Mode, scope: Scope, before: Active | null, user: Mode): string => {
108 const kept = scope === 'self' && user !== 'off' ? ` The user's ${LADDER[user].label} mode stays on.` : ''
109 if (wanted === 'off') {
110 if (!before) return `No mode was set for that scope.${kept}`
111 return `Cleared the ${LADDER[before].label} mode you set for ${scope === 'self' ? 'yourself' : 'your subagents'}.${kept}`
112 }
113 if (scope === 'self') return `You are now in ${LADDER[wanted].label} mode. ${LADDER[wanted].section}${kept}`
114 return `Your subagents are now in ${LADDER[wanted].label} mode, also those already running.`
115}
116
117export function uncovered(held: Held | undefined, user: Mode): Held | undefined {
118 if (!held) return undefined
119 const keep = (m: Active | null) => (m && MODES.indexOf(m) < MODES.indexOf(user) ? m : null)
120 return { self: keep(held.self), subagents: keep(held.subagents) }
121}
122
123export function claudeParts(held: Held | undefined): string | undefined {
124 if (!held) return undefined
125 const parts = [
126 held.self ? `${LADDER[held.self].label} for itself` : null,
127 held.subagents ? `${LADDER[held.subagents].label} for subagents` : null,
128 ].filter((p): p is string => p !== null)
129 return parts.length ? parts.join(' and ') : undefined
130}
131
132export const reword = (text: string, tail: string): string => text.replace('/mode off to leave.', tail)
133
134const COMMIT = /\bgit\s+commit\b/
135const PUBLISH = /\bgit\s+push\b|\bgh\s+pr\s+(create|merge)\b/
136const GH_API = /\bgh\s+api\b/
137const PULLS_PATH = /\/pulls\b/
138const API_WRITE = /(?:-X|--method)[\s=]*(?:POST|PATCH|PUT|DELETE)\b|\s(?:-f|-F|--field|--raw-field|--input)(?=[\s=]|$)/i
139const API_GET = /(?:-X|--method)[\s=]*GET\b/i
140const WRITE_VERB =
141 /^(create|save|update|delete|add|remove|set|edit|write|post|move|archive|close|reopen|assign|link|unlink|merge|upsert|patch|put|push|transition|submit|publish|batch)$/
142// Tracker CLIs the shape adapters name; an MCP tool is judged by its name alone.
143const TRACKER_CLI =
144 /\bgh\s+(issue|project|label|milestone)\s+(create|edit|close|reopen|delete|comment|transfer|item-add|item-edit|item-archive|field-create|link)\b|\bgh\s+api\b.*(-X|--method)\s*(POST|PATCH|PUT|DELETE)\b|\bacli\s+jira\s+\S+\s+(create|edit|delete|transition|assign|comment|link)\b/
145// App UI bookkeeping only: ccd_settings, ccd_pr, ccd_session_mgmt and ccd_host make real changes and stay judged by name.
146const HARNESS_TOOL = /^mcp__(ccd_(turn|view|window|sidebar)|session-modes)__/
147const PLAN_FILE = /\.(md|markdown)$/i
148const WORK_FILE = /(^|[\\/])\.claude[\\/]work[\\/]/
149const ARTIFACT_READS = new Set(['read', 'list', 'quickstart', 'open', 'pin', 'unpin'])
150const HARMLESS_REDIRECT = /\d*>&\d+|\d*>>?\s*\/dev\/null/g
151const REDIRECT_TARGET = />>?\s*([^\s>&|;]+)/g
152const PART_SPLIT = /&&|\|\|?|;|\n/
153
154// An unterminated quote masks nothing, so a broken command stays judged strictly.
155function maskQuotedRedirects(command: string): string {
156 const out = [...command]
157 let quote: "'" | '"' | null = null
158 let start = 0
159 const masked: number[] = []
160 for (let i = 0; i < out.length; i++) {
161 const c = out[i]
162 if (quote === "'") {
163 if (c === "'") quote = null
164 else if (c === '>') masked.push(i)
165 } else if (c === '\\') {
166 if (out[i + 1] === '>') masked.push(i + 1)
167 i++
168 } else if (quote === '"') {
169 if (c === '"') quote = null
170 else if (c === '>') masked.push(i)
171 } else if (c === "'" || c === '"') {
172 quote = c
173 start = masked.length
174 }
175 }
176 if (quote) masked.length = start
177 for (const i of masked) out[i] = '_'
178 return out.join('')
179}
180
181const top = (needs: Mode[]): Mode => needs.reduce((a, b) => (MODES.indexOf(b) > MODES.indexOf(a) ? b : a), 'readonly')
182
183function bashPartNeed(part: string): Mode {
184 const pullsWrite = GH_API.test(part) && PULLS_PATH.test(part) && API_WRITE.test(part) && !API_GET.test(part)
185 if (PUBLISH.test(part) || pullsWrite) return 'off'
186 const targets = [...part.replace(HARMLESS_REDIRECT, '').matchAll(REDIRECT_TARGET)].map(m => m[1])
187 if (targets.some(t => !PLAN_FILE.test(t) && !WORK_FILE.test(t))) return 'build'
188 if (targets.some(t => !PLAN_FILE.test(t))) return 'prototype'
189 return targets.length > 0 || COMMIT.test(part) || TRACKER_CLI.test(part) ? 'research' : 'readonly'
190}
191
192// mcp__server__create_issue or mcp__server__createIssue: any word of the tool's own name is a verb.
193function mcpNeed(tool: string): Mode {
194 const name = /^mcp__.+?__(.+)$/.exec(tool)?.[1]
195 if (!name || HARNESS_TOOL.test(tool)) return 'readonly'
196 const words = name.replace(/([a-z0-9])([A-Z])/g, '$1_$2').toLowerCase().split(/[_\-.]+/)
197 const writes = words.some(w => WRITE_VERB.test(w))
198 if (words.includes('push') || (writes && words.includes('pull') && words.includes('request'))) return 'off'
199 return writes ? 'research' : 'readonly'
200}
201
202export type Call = { tool: string; command?: string; path?: string; action?: string }
203
204export function need({ tool, command = '', path = '', action = '' }: Call): Mode {
205 if (tool === 'Edit' || tool === 'Write' || tool === 'NotebookEdit')
206 return PLAN_FILE.test(path) ? 'research' : WORK_FILE.test(path) ? 'prototype' : 'build'
207 if (tool === 'Artifact') return ARTIFACT_READS.has(action) ? 'readonly' : 'research'
208 if (tool === 'Bash') return top(maskQuotedRedirects(command.replace(/\\\n/g, ' ')).split(PART_SPLIT).map(bashPartNeed))
209 return mcpNeed(tool)
210}
211
212export function verdict(mode: Mode, call: Call): string | undefined {
213 if (mode === 'off' || MODES.indexOf(need(call)) <= MODES.indexOf(mode)) return undefined
214 return `${mode} mode is on: ${LADDER[mode].instead}; /mode off to leave.`
215}
216
217export function report(mode: Mode): string {
218 return `Current mode: ${mode}. Modes: ${MODES.join(', ')}. Also: clear, agents on, agents off.`
219}
220
221export const CLEARED_NOTE = (parts: string): string =>
222 `Session mode: the user cleared the modes you set (${parts}). They no longer apply.`
223
224export const AGENTS_OFF_NOTE = 'Session mode: the user turned off agent_mode. Do not call it.'
225
226export const AGENTS_ON_NOTE = 'Session mode: the user turned agent_mode back on.'
227
228export const AGENTS_OFF_DENY = 'The user turned off agent modes with /mode agents off.'
229
230export type Override = 'clear' | 'agents-on' | 'agents-off' | 'agents-invalid'
231
232export function parseOverride(args: string): Override | undefined {
233 const words = args.trim().toLowerCase().split(/\s+/)
234 if (words.length === 1 && words[0] === 'clear') return 'clear'
235 if (words[0] !== 'agents') return undefined
236 if (words.length === 2 && words[1] === 'on') return 'agents-on'
237 if (words.length === 2 && words[1] === 'off') return 'agents-off'
238 return 'agents-invalid'
239}
240
241export const holdsAny = (all: Record<string, Held>): boolean =>
242 Object.values(all).some(h => h.self !== null || h.subagents !== null)
243hooks/suggest.ts 36 lines1import type { PromptAutocompleteSuggestion } from 'claude-code'
2import { LADDER, MODES } from './modes'
3import type { Mode } from './modes'
4
5const hint = (m: Mode): string => (m === 'off' ? 'lift the current mode' : LADDER[m].hint)
6
7const EXTRA = [
8 { text: 'clear', description: 'clear the modes Claude set' },
9 { text: 'agents', description: 'turn agent_mode on or off' },
10]
11
12const AGENT_VALUES = [
13 { text: 'on', description: 'let Claude set modes' },
14 { text: 'off', description: 'stop Claude setting modes' },
15]
16
17const PARTIAL = /^\/mode ([^\s]*)$/
18const AGENTS_PARTIAL = /^\/mode agents ([^\s]*)$/i
19
20export function modeSuggestions(text: string, cursor: number, current: Mode): PromptAutocompleteSuggestion[] {
21 if (cursor !== text.length) return []
22 const agents = AGENTS_PARTIAL.exec(text)
23 if (agents) {
24 const partial = agents[1].toLowerCase()
25 return AGENT_VALUES.filter(v => v.text.startsWith(partial))
26 }
27 const found = PARTIAL.exec(text)
28 if (!found) return []
29 const partial = found[1].toLowerCase()
30 const modes = MODES.filter(m => m.startsWith(partial)).map(m => ({
31 text: m,
32 description: m !== current ? hint(m) : m === 'off' ? 'no mode is on' : `${hint(m)} (on)`,
33 }))
34 return [...modes, ...EXTRA.filter(x => x.text.startsWith(partial))]
35}
36types/index.d.ts 20 lines1export type Mode = 'off' | 'readonly' | 'research' | 'prototype' | 'build'
2
3export type Active = Exclude<Mode, 'off'>
4
5export type Held = { self: Active | null; subagents: Active | null }
6
7declare module 'claude-code' {
8 interface PluginState {
9 'session-modes': {
10 mode: Mode
11 ended: Active | null
12 told: Mode
13 agentModes: Record<string, Held>
14 parents: Record<string, string>
15 pending: string[]
16 agentsAllowed: boolean
17 }
18 }
19}
20