Judge pending permission requests with Jev before the permission dialog

<h1>auto-mode</h1> <a href="https://www.npmjs.com/package/auto-mode"><img src="https://img.shields.io/npm/v/auto-mode" alt="npm version"></a> <a href="./LICENSE"><img src="https://img.shields.io/badge/license-MIT-blue" alt="MIT license"></a>
auto-mode tries to mitigate the risk of unattended non-Claude agents inside Claude Code.
auto-mode runs as a Claude Code mod, and its operating model is loosely modelled on Anthropic's native auto mode. Instead of one model, it pairs a fast decision model (such as Jev) with a traditional classifier-judge model (such as Haiku) to cover the first one's shortcomings.
auto-mode needs node 24 or later, Claude Code, and a TypeSafe API key for Jev.
npm i -g auto-mode
claude --plugin-dir "$(auto-mode mod-path)"
Export your key as TYPESAFE_API_KEY, or point the configuration at a command that prints it. Claude permission mod covers the mod and a trial session you can undo.
Read the rules before you enable the mod. Writing a policy covers how the rules clear and how to change them.
You can call auto-mode's core APIs from your own code. parseActionRequest reads the request the mod sends the CLI (the contract), and classifyAction runs it through the stages from the local rules to the judge. The two options in the example apply the denial budget and write the action log, as the CLI does.
import { classifyAction, loadConfig, parseActionRequest } from 'auto-mode';
const request = parseActionRequest(body);
if (request !== null) {
const outcome = await classifyAction(request, await loadConfig(), {
budget: true,
actionLog: true,
});
}
Read the configuration guide, which covers every field and the credentials.
docs/ covers the architecture and the user guides.
MIT.
hooks/register.ts 211 lines1import { CLI_LIMITS } from '../contract/cli-limits.ts';
2import type { ModScopeRecord } from '../contract/types.ts';
3import { buildActionRequest } from './build-action-request.ts';
4import { buildPromptContext } from './build-prompt-context.ts';
5import { isScopeCommand } from './is-scope-command.ts';
6import { isToolInput } from './is-tool-input.ts';
7import { parseDecision } from './parse-decision.ts';
8import type { ModOn, ModOptions, PromptContext } from './types.ts';
9
10const RECORD_TIMEOUT_MS = 8000;
11
12export function register(on: ModOn, options: ModOptions): void {
13 let sessionID: string | null = null;
14
15 const activeCalls = new Map<string, string | null>();
16 const delegatedTasks = new Map<string, string>();
17
18 let prompts: PromptContext = buildPromptContext(null, { source: 'reload' });
19
20 on('classic.SessionStart', (_api, event, next) => {
21 if (event.agent_id === undefined) {
22 const isCompact = event.source === 'compact' && sessionID === event.session_id;
23
24 sessionID = event.session_id;
25
26 const previousPrompts = isCompact ? prompts : null;
27
28 prompts = buildPromptContext(previousPrompts, { source: event.source ?? 'unknown' });
29
30 if (!isCompact) {
31 delegatedTasks.clear();
32 }
33 }
34
35 return next(event);
36 });
37
38 on('classic.UserPromptSubmit', (_api, event, next) => {
39 if (event.agent_id === undefined) {
40 sessionID = event.session_id;
41 }
42
43 return next(event);
44 });
45
46 on('prompt.submit', (_api, event, next) => {
47 prompts = buildPromptContext(prompts, event);
48
49 return next(event);
50 });
51
52 on('agent.spawn', async (_api, event, next) => {
53 const result = await next(event);
54
55 if (result.agentId !== undefined && !delegatedTasks.has(result.agentId)) {
56 delegatedTasks.set(result.agentId, event.prompt);
57 }
58
59 return result;
60 });
61
62 on('tool.call', async ($, event, next) => {
63 if (event.tool_use_id === undefined) {
64 return next(event);
65 }
66
67 activeCalls.set(event.tool_use_id, event.agentId ?? null);
68
69 const command =
70 event.tool === 'Bash' && typeof event.command === 'string' && isScopeCommand(event.command)
71 ? event.command
72 : null;
73
74 const startedAt = Date.now();
75 const cwd = command === null || sessionID === null ? null : await $.session.cwd();
76 let result;
77
78 try {
79 result = await next(event);
80 } finally {
81 activeCalls.delete(event.tool_use_id);
82 }
83
84 if (command !== null && cwd !== null && sessionID !== null && result.deny === undefined) {
85 const executable = typeof options.command === 'string' ? options.command : 'auto-mode';
86
87 const request: ModScopeRecord = {
88 sessionID,
89 cwd,
90 startedAt,
91 command,
92 resultText: result.text ?? '',
93 };
94
95 try {
96 await $.process.run([executable, 'record'], {
97 timeoutMs: RECORD_TIMEOUT_MS,
98 stdin: JSON.stringify(request),
99 });
100 } catch {
101 $.ui.log('auto-mode: session scope not recorded; subprocess failure', { to: 'debug' });
102 }
103 }
104
105 return result;
106 });
107
108 on('tool.check', async ($, event, next) => {
109 const decided = await next(event);
110
111 const actionID =
112 event.tool_use_id !== undefined && /^call_[\da-f]{24,32}$/u.test(event.tool_use_id)
113 ? event.tool_use_id
114 : 'unavailable';
115
116 const logPrefix = `auto-mode action ${actionID}:`;
117
118 if (decided.decision !== 'ask') {
119 return decided;
120 }
121
122 if (next.signal.aborted || sessionID === null) {
123 const status = next.signal.aborted ? 'cancelled' : 'missing session context';
124
125 $.ui.log(`${logPrefix} evaluation skipped; ${status}`, { to: 'debug' });
126
127 return decided;
128 }
129
130 if (next.budget.remainingMs < 750) {
131 $.ui.log(`${logPrefix} evaluation skipped; insufficient budget`, { to: 'debug' });
132
133 return decided;
134 }
135
136 try {
137 const cwd = await $.session.cwd();
138
139 const agentID = event.tool_use_id === undefined ? null : activeCalls.get(event.tool_use_id);
140
141 if (agentID === undefined) {
142 $.ui.log(`${logPrefix} evaluation skipped; untracked tool call`, { to: 'debug' });
143
144 return decided;
145 }
146
147 if (!isToolInput(event.input)) {
148 $.ui.log(`${logPrefix} evaluation skipped; tool input is not an object`, { to: 'debug' });
149
150 return decided;
151 }
152
153 const command = typeof options.command === 'string' ? options.command : 'auto-mode';
154 const childTimeoutMs = CLI_LIMITS.evaluationMs;
155 const deadlineAt = Date.now() + childTimeoutMs - 500;
156
157 $.ui.log(`${logPrefix} evaluator invoked`, { to: 'debug' });
158
159 const request = buildActionRequest({
160 sessionID,
161 toolUseID: event.tool_use_id,
162 cwd,
163 toolName: event.tool,
164 toolInput: event.input,
165 agentID,
166 delegatedText: agentID === null ? undefined : delegatedTasks.get(agentID),
167 prompts,
168 });
169
170 const result = await $.process.run(
171 [command, 'run', '--jev-only', '--evaluation-deadline', String(deadlineAt)],
172 { timeoutMs: childTimeoutMs, stdin: JSON.stringify(request) },
173 );
174
175 if (result.exitCode !== 0 || result.isStdoutTruncated || next.signal.aborted) {
176 let status = 'nonzero exit';
177
178 if (next.signal.aborted) {
179 status = 'cancelled';
180 } else if (result.isStdoutTruncated) {
181 status = 'truncated verdict';
182 }
183
184 $.ui.log(`${logPrefix} manual approval retained; ${status}`, { to: 'debug' });
185
186 return decided;
187 }
188
189 const verdict = parseDecision(result.stdout);
190
191 const message =
192 verdict === null
193 ? 'manual approval retained; no usable verdict; inspect action diagnostics'
194 : `evaluator verdict ${verdict.decision}`;
195
196 $.ui.log(`${logPrefix} ${message}`, { to: 'debug' });
197
198 return verdict ?? decided;
199 } catch (error) {
200 const status =
201 error instanceof Error && /aborted: still running after \d+ms$/u.test(error.message)
202 ? 'subprocess timeout'
203 : 'subprocess failure';
204
205 $.ui.log(`${logPrefix} manual approval retained; ${status}`, { to: 'debug' });
206
207 return decided;
208 }
209 });
210}
211contract/cli-limits.ts 12 lines1const KEY_COMMAND_MS = 5000;
2const JEV_MS = 5000;
3const JUDGE_MS = 120_000;
4const STARTUP_MS = 5000;
5
6export const CLI_LIMITS = {
7 keyCommandMs: KEY_COMMAND_MS,
8 jevMs: JEV_MS,
9 judgeMs: JUDGE_MS,
10 evaluationMs: STARTUP_MS + 3 * KEY_COMMAND_MS + JEV_MS + 2 * JUDGE_MS,
11} as const;
12contract/types.ts 52 lines1import type { MESSAGE_ORIGINS } from './message-origins.ts';
2
3export type MessageOrigin = (typeof MESSAGE_ORIGINS)[number];
4
5export interface UserTask {
6 readonly text: string;
7 readonly origin: MessageOrigin;
8}
9
10export interface DirectUserMessage extends UserTask {
11 readonly freshness?: 'stale' | undefined;
12}
13
14interface DelegatedTask {
15 readonly text: string;
16 readonly origin: 'agent.spawn';
17}
18
19export interface TaskOmission {
20 readonly field: 'originalUserTask' | 'delegatedTask';
21 readonly reason: 'unavailable' | 'budget';
22}
23
24export interface ModContext {
25 readonly agentID: string | null;
26 readonly originalUserTask: UserTask | null;
27 readonly delegatedTask: DelegatedTask | null;
28 readonly lastDirectUserMessage: DirectUserMessage | null;
29 readonly omittedTaskContext: TaskOmission[];
30}
31
32export interface ModRequest {
33 readonly sessionID: string;
34 readonly toolUseID?: string | undefined;
35 readonly cwd: string;
36 readonly toolName: string;
37 readonly toolInput: Readonly<Record<string, unknown>>;
38 readonly context: ModContext;
39}
40
41export interface ModScopeRecord {
42 readonly sessionID: string;
43 readonly cwd: string;
44 readonly startedAt: number;
45 readonly command: string;
46 readonly resultText: string;
47}
48
49export type ModVerdict =
50 | { readonly decision: 'allow' }
51 | { readonly decision: 'deny'; readonly reason: string };
52hooks/build-action-request.ts 47 lines1import type { ModRequest, TaskOmission } from '../contract/types.ts';
2import type { PromptContext } from './types.ts';
3
4interface ActionRequestInput {
5 readonly sessionID: string;
6 readonly toolUseID: string | undefined;
7 readonly cwd: string;
8 readonly toolName: string;
9 readonly toolInput: Readonly<Record<string, unknown>>;
10 readonly agentID: string | null;
11 readonly delegatedText: string | undefined;
12 readonly prompts: PromptContext;
13}
14
15export function buildActionRequest(input: Readonly<ActionRequestInput>): ModRequest {
16 const isChild = input.agentID !== null;
17
18 const delegatedTask =
19 input.delegatedText === undefined
20 ? null
21 : { text: input.delegatedText, origin: 'agent.spawn' as const };
22
23 const omittedTaskContext: TaskOmission[] = [
24 ...(input.prompts.originalUserTask === null
25 ? [{ field: 'originalUserTask' as const, reason: 'unavailable' as const }]
26 : []),
27 ...(isChild && delegatedTask === null
28 ? [{ field: 'delegatedTask' as const, reason: 'unavailable' as const }]
29 : []),
30 ];
31
32 return {
33 sessionID: input.sessionID,
34 ...(input.toolUseID === undefined ? {} : { toolUseID: input.toolUseID }),
35 cwd: input.cwd,
36 toolName: input.toolName,
37 toolInput: input.toolInput,
38 context: {
39 agentID: input.agentID,
40 originalUserTask: input.prompts.originalUserTask,
41 delegatedTask,
42 lastDirectUserMessage: input.prompts.lastDirectUserMessage,
43 omittedTaskContext,
44 },
45 };
46}
47hooks/build-prompt-context.ts 48 lines1import { isMessageOrigin } from '../contract/is-message-origin.ts';
2import type { DirectUserMessage, UserTask } from '../contract/types.ts';
3import type { PromptContext } from './types.ts';
4
5export function buildPromptContext(
6 previous: PromptContext | null,
7 input:
8 | { readonly source: string }
9 | { readonly text: string; readonly origin: { readonly kind: string } },
10): PromptContext {
11 if ('source' in input) {
12 if (input.source === 'compact' && previous !== null) {
13 return previous;
14 }
15
16 return {
17 originalUserTask: null,
18 lastDirectUserMessage: null,
19 canCaptureOriginal: input.source === 'startup' || input.source === 'clear',
20 };
21 }
22
23 const origin = input.origin.kind;
24
25 if (!isMessageOrigin(origin)) {
26 return {
27 originalUserTask: previous?.originalUserTask ?? null,
28 lastDirectUserMessage: buildStaleMessage(previous?.lastDirectUserMessage ?? null),
29 canCaptureOriginal: previous?.canCaptureOriginal ?? false,
30 };
31 }
32
33 const message: UserTask = { text: input.text, origin };
34
35 return {
36 originalUserTask:
37 previous?.originalUserTask ?? (previous?.canCaptureOriginal === true ? message : null),
38 lastDirectUserMessage: message,
39 canCaptureOriginal: previous?.canCaptureOriginal ?? false,
40 };
41}
42
43function buildStaleMessage(message: DirectUserMessage | null): DirectUserMessage | null {
44 return message === null
45 ? null
46 : { text: message.text, origin: message.origin, freshness: 'stale' };
47}
48hooks/is-scope-command.ts 18 lines1import { SCOPE_COMMANDS } from '../contract/scope-commands.ts';
2
3// Options may sit between the program and its subcommand on a command line.
4const SCOPE_COMMAND_PATTERN = new RegExp(
5 Object.entries(SCOPE_COMMANDS)
6 .map(([program, commands]) => {
7 const alternatives = commands.map((command) => command.split(' ').join(String.raw`\s+`));
8
9 return String.raw`\b${program}\s[^\n]*?\b(?:${alternatives.join('|')})\b`;
10 })
11 .join('|'),
12 'u',
13);
14
15export function isScopeCommand(command: string): boolean {
16 return SCOPE_COMMAND_PATTERN.test(command);
17}
18hooks/is-tool-input.ts 4 lines1export function isToolInput(value: unknown): value is Readonly<Record<string, unknown>> {
2 return typeof value === 'object' && value !== null && !Array.isArray(value);
3}
4hooks/parse-decision.ts 35 lines1import type { ModVerdict } from '../contract/types.ts';
2
3export function parseDecision(stdout: string): ModVerdict | null {
4 let body: unknown;
5
6 try {
7 body = JSON.parse(stdout);
8 } catch {
9 return null;
10 }
11
12 if (typeof body !== 'object' || body === null || Array.isArray(body)) {
13 return null;
14 }
15
16 const keys = Object.keys(body).toSorted().join(',');
17
18 if (keys === 'decision' && 'decision' in body && body.decision === 'allow') {
19 return { decision: 'allow' };
20 }
21
22 if (
23 keys === 'decision,reason' &&
24 'decision' in body &&
25 body.decision === 'deny' &&
26 'reason' in body &&
27 typeof body.reason === 'string' &&
28 body.reason.trim() !== ''
29 ) {
30 return { decision: 'deny', reason: body.reason };
31 }
32
33 return null;
34}
35hooks/types.ts 148 lines1import type { DirectUserMessage, UserTask } from '../contract/types.ts';
2
3export interface PermissionDecision {
4 readonly decision: 'allow' | 'ask' | 'deny';
5 readonly reason?: string;
6 readonly rule?: string;
7 readonly hook?: string;
8}
9
10export interface SessionContext {
11 readonly cwd: string;
12 readonly session_id: string;
13 readonly transcript_path: string;
14 readonly agent_id?: string;
15}
16
17export interface ProcessInput {
18 readonly argv: readonly string[];
19 readonly init?: { readonly stdin?: string; readonly timeoutMs?: number };
20}
21
22export interface ProcessResult {
23 readonly exitCode: number;
24 readonly stdout: string;
25 readonly stderr: string;
26 readonly isStdoutTruncated: boolean;
27 readonly isStderrTruncated: boolean;
28}
29
30interface CheckInput {
31 readonly tool: string;
32 readonly input: unknown;
33 readonly tool_use_id?: string;
34}
35
36interface CallInput {
37 readonly tool: string;
38 readonly tool_use_id?: string;
39 readonly agentId?: string;
40 readonly command?: unknown;
41}
42
43export interface CallResult {
44 readonly result?: unknown;
45 readonly deny?: string;
46 readonly text?: string;
47 readonly isError?: true;
48}
49
50export interface PromptContext {
51 readonly originalUserTask: UserTask | null;
52 readonly lastDirectUserMessage: DirectUserMessage | null;
53 readonly canCaptureOriginal: boolean;
54}
55
56interface PromptInput {
57 readonly text: string;
58 readonly origin: { readonly kind: string };
59}
60
61interface SpawnInput {
62 readonly prompt: string;
63 readonly cwd?: string;
64 readonly parentAgentId?: string;
65}
66
67interface ModEvents {
68 readonly 'classic.SessionStart': {
69 readonly input: SessionContext & { readonly source?: string };
70 readonly result: object;
71 };
72 readonly 'classic.UserPromptSubmit': { readonly input: SessionContext; readonly result: object };
73 readonly 'prompt.submit': { readonly input: PromptInput; readonly result: object };
74 readonly 'agent.spawn': {
75 readonly input: SpawnInput;
76 readonly result: { readonly agentId?: string; readonly model?: string; readonly deny?: string };
77 };
78 readonly 'tool.call': { readonly input: CallInput; readonly result: CallResult };
79 readonly 'tool.check': { readonly input: CheckInput; readonly result: PermissionDecision };
80 readonly 'process.run': {
81 readonly input: ProcessInput;
82 readonly result: { readonly value: ProcessResult };
83 };
84 readonly 'session.cwd': { readonly input: object; readonly result: { readonly value: string } };
85 readonly 'ui.log': {
86 readonly input: { readonly text: string; readonly to?: 'debug' | 'transcript' };
87 readonly result: object;
88 };
89}
90
91interface Next<E extends keyof ModEvents> {
92 (input: ModEvents[E]['input']): Promise<ModEvents[E]['result']>;
93 readonly signal: Pick<AbortSignal, 'aborted'>;
94 readonly budget: { readonly remainingMs: number };
95}
96
97interface LogOptions {
98 readonly to: 'debug';
99}
100
101// The call a mod makes differs from the event a hook receives: the host adds the
102// parent agent to the event, and the call takes the spawn options.
103interface AgentSpawnArgs {
104 readonly prompt: string;
105 readonly description?: string;
106 readonly subagentType?: string;
107 readonly model?: string;
108 readonly name?: string;
109 readonly cwd?: string;
110}
111
112export interface ModAPI {
113 readonly ui: { readonly log: (text: string, options?: LogOptions) => void };
114 readonly session: { readonly cwd: () => Promise<string> };
115 readonly process: {
116 readonly run: (argv: readonly string[], init?: ProcessInput['init']) => Promise<ProcessResult>;
117 };
118 readonly prompt: { readonly submit: (input: PromptInput) => Promise<object> };
119 readonly agent: {
120 readonly spawn: (input: AgentSpawnArgs) => Promise<ModEvents['agent.spawn']['result']>;
121 };
122 readonly tool: {
123 readonly check: (input: CheckInput) => Promise<PermissionDecision>;
124 readonly call: (input: CallInput) => Promise<CallResult>;
125 };
126 readonly classic: {
127 readonly SessionStart: (
128 input: Partial<SessionContext> & { readonly source: string },
129 ) => Promise<object>;
130 readonly UserPromptSubmit: (
131 input: Partial<SessionContext> & { readonly prompt: string },
132 ) => Promise<object>;
133 };
134}
135
136export type ModOn = <E extends keyof ModEvents>(
137 event: E,
138 hook: (
139 api: ModAPI,
140 input: ModEvents[E]['input'],
141 next: Next<E>,
142 ) => ModEvents[E]['result'] | Promise<ModEvents[E]['result']>,
143) => void;
144
145export interface ModOptions {
146 readonly command?: unknown;
147}
148contract/message-origins.ts 4 lines1// Composer, Remote Control and the SDK are the prompt origins a person types
2// into; any other origin is a delivery from a tool.
3export const MESSAGE_ORIGINS = ['composer', 'bridge', 'sdk'] as const;
4contract/is-message-origin.ts 7 lines1import { MESSAGE_ORIGINS } from './message-origins.ts';
2import type { MessageOrigin } from './types.ts';
3
4export function isMessageOrigin(value: string): value is MessageOrigin {
5 return MESSAGE_ORIGINS.some((origin) => origin === value);
6}
7contract/scope-commands.ts 5 lines1export const SCOPE_COMMANDS = {
2 git: ['worktree add', 'checkout', 'switch', 'branch'],
3 gh: ['pr create'],
4} as const;
5