@ziptie-soft/orca-local-decider 0.0.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,244 @@
1
+ /**
2
+ * What a tool call is, as one stable line (`Bash: npm test`, `Edit: src/a.ts`): the precedent
3
+ * subject and the shell-command helpers behind it. No `node:` imports, so a Claude Code mod can
4
+ * bundle it; paths use the small POSIX helpers below.
5
+ */
6
+ import { canonicalJson } from './canonical.ts';
7
+
8
+ export type HookInput = Readonly<Record<string, unknown>>;
9
+
10
+ export function str(value: unknown): string | undefined {
11
+ return typeof value === 'string' && value !== '' ? value : undefined;
12
+ }
13
+
14
+ /**
15
+ * The shell command a tool call runs: Bash (`command` string or argv array), Codex `apply_patch`
16
+ * (patch text in `command`), else `undefined`.
17
+ */
18
+ export function commandOf(hook: HookInput): string | undefined {
19
+ const toolInput = hook['tool_input'];
20
+ if (typeof toolInput !== 'object' || toolInput === null) {
21
+ return undefined;
22
+ }
23
+ const command = (toolInput as Record<string, unknown>)['command'];
24
+ if (Array.isArray(command)) {
25
+ // Quoted, so an argv like ["bash", "-lc", "rm -rf /"] keeps its inline script as one word.
26
+ return command
27
+ .filter((c) => typeof c === 'string')
28
+ .map(shellQuote)
29
+ .join(' ');
30
+ }
31
+ return str(command);
32
+ }
33
+
34
+ const SHELL_SAFE = /^[\w@%+=:,./-]+$/;
35
+
36
+ function shellQuote(word: string): string {
37
+ return SHELL_SAFE.test(word) ? word : `'${word.replaceAll("'", String.raw`'\''`)}'`;
38
+ }
39
+
40
+ /** Only known shell tools have a `command` that the deterministic guard can interpret. */
41
+ export function isShellTool(hook: HookInput): boolean {
42
+ const tool = str(hook['tool_name']) ?? '';
43
+ return ['Bash', 'shell', 'exec_command'].includes(tool);
44
+ }
45
+
46
+ /** Build the shared, cross-harness subject from native tool metadata. */
47
+ export function canonicalSubject(
48
+ tool: string,
49
+ toolInput: unknown,
50
+ cwd: string | undefined,
51
+ ): string | undefined {
52
+ const fields = validSubjectFields(tool, toolInput, cwd);
53
+ if (fields === undefined || cwd === undefined) return undefined;
54
+ const mapped = canonicalTool(tool);
55
+ const command = subjectCommand(mapped, toolInput);
56
+ const rawPath = firstString(fields, SUBJECT_PATH_FIELDS);
57
+ if (!hasRequiredSubject(mapped, tool, fields, rawPath, command)) return undefined;
58
+ return subjectLine({
59
+ tool: mapped,
60
+ cwd,
61
+ input: toolInput,
62
+ command,
63
+ path: rawPath,
64
+ url: firstString(fields, SUBJECT_URL_FIELDS),
65
+ });
66
+ }
67
+
68
+ const SUBJECT_PATH_FIELDS = ['file_path', 'filePath', 'notebook_path', 'path'] as const;
69
+ const SUBJECT_URL_FIELDS = ['url'] as const;
70
+
71
+ function validSubjectFields(
72
+ tool: string,
73
+ toolInput: unknown,
74
+ cwd: string | undefined,
75
+ ): Record<string, unknown> | undefined {
76
+ if (tool.trim() !== tool || tool === '' || cwd === undefined || cwd.trim() === '') {
77
+ return undefined;
78
+ }
79
+ const fields = asRecord(toolInput);
80
+ return fields !== undefined && validPathFields(fields) ? fields : undefined;
81
+ }
82
+
83
+ function validPathFields(fields: Record<string, unknown>): boolean {
84
+ return SUBJECT_PATH_FIELDS.every((key) => {
85
+ const value = fields[key];
86
+ return value === undefined || (typeof value === 'string' && value !== '');
87
+ });
88
+ }
89
+
90
+ function subjectCommand(mapped: string, toolInput: unknown): string | undefined {
91
+ if (mapped !== 'shell') return undefined;
92
+ const command = commandOf({ tool_input: toolInput });
93
+ return command === undefined || command.trim() === '' ? undefined : command;
94
+ }
95
+
96
+ function hasRequiredSubject(
97
+ mapped: string,
98
+ tool: string,
99
+ fields: Record<string, unknown>,
100
+ path: string | undefined,
101
+ command: string | undefined,
102
+ ): boolean {
103
+ if (mapped === 'shell') return command !== undefined;
104
+ if (mapped !== 'edit' && mapped !== 'notebook') return true;
105
+ return path !== undefined || (tool === 'apply_patch' && typeof fields['command'] === 'string');
106
+ }
107
+
108
+ function canonicalTool(tool: string): string {
109
+ if (['Bash', 'shell', 'exec_command'].includes(tool)) return 'shell';
110
+ if (['Edit', 'Write', 'MultiEdit', 'apply_patch'].includes(tool)) return 'edit';
111
+ if (tool === 'NotebookEdit') return 'notebook';
112
+ if (!tool.startsWith('mcp__')) return tool;
113
+ const rest = tool.slice(5);
114
+ const separator = rest.indexOf('__', 1);
115
+ return separator > 0 && separator + 2 < rest.length
116
+ ? `mcp:${rest.slice(0, separator)}:${rest.slice(separator + 2)}`
117
+ : tool;
118
+ }
119
+
120
+ export interface SubjectParts {
121
+ readonly tool: string;
122
+ readonly cwd: string;
123
+ /** The raw tool input, used only when there is no command, path or url. */
124
+ readonly input: unknown;
125
+ readonly command?: string | undefined;
126
+ readonly path?: string | undefined;
127
+ readonly url?: string | undefined;
128
+ }
129
+
130
+ /** `Tool: value` from already-extracted parts: command (cwd prefix dropped), cwd-relative path, url, else stable input. */
131
+ export function subjectLine(parts: SubjectParts): string {
132
+ const { tool, cwd, input, command, path, url } = parts;
133
+ const value =
134
+ command !== undefined
135
+ ? stripCwd(command, cwd)
136
+ : path !== undefined
137
+ ? posixRelative(cwd, path).replaceAll('\\', '/')
138
+ : (url ?? stableToolInput(input));
139
+ return collapse(`${tool}: ${value}`);
140
+ }
141
+
142
+ export function asRecord(value: unknown): Record<string, unknown> | undefined {
143
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
144
+ ? (value as Record<string, unknown>)
145
+ : undefined;
146
+ }
147
+
148
+ export function firstString(
149
+ value: Record<string, unknown> | undefined,
150
+ keys: readonly string[],
151
+ ): string | undefined {
152
+ for (const key of keys) {
153
+ const candidate = value?.[key];
154
+ if (typeof candidate === 'string' && candidate !== '') {
155
+ return candidate;
156
+ }
157
+ }
158
+ return undefined;
159
+ }
160
+
161
+ function stableToolInput(value: unknown): string {
162
+ const fields = asRecord(value);
163
+ if (fields === undefined) {
164
+ return canonicalJson(value);
165
+ }
166
+ const input = { ...fields };
167
+ delete input['description'];
168
+ return canonicalJson(input);
169
+ }
170
+
171
+ function stripCwd(command: string, cwd: string): string {
172
+ const line = collapse(command);
173
+ const prefix = `cd ${collapse(cwd)} && `;
174
+ return line.startsWith(prefix) ? line.slice(prefix.length) : line;
175
+ }
176
+
177
+ type Quote = '' | "'" | '"' | '`';
178
+
179
+ interface CollapseState {
180
+ out: string;
181
+ quote: Quote;
182
+ escaped: boolean;
183
+ pendingSpace: boolean;
184
+ }
185
+
186
+ function collapse(value: string): string {
187
+ const state: CollapseState = { out: '', quote: '', escaped: false, pendingSpace: false };
188
+ for (const char of value) {
189
+ if (state.quote === '') appendUnquoted(char, state);
190
+ else appendQuoted(char, state);
191
+ }
192
+ return state.out.trim();
193
+ }
194
+
195
+ function appendUnquoted(char: string, state: CollapseState): void {
196
+ if (/\s/.test(char)) {
197
+ state.pendingSpace = state.out !== '';
198
+ return;
199
+ }
200
+ if (state.pendingSpace) state.out += ' ';
201
+ state.pendingSpace = false;
202
+ if (isQuote(char)) state.quote = char;
203
+ state.out += char;
204
+ }
205
+
206
+ function appendQuoted(char: string, state: CollapseState): void {
207
+ state.out += char;
208
+ if (state.escaped) state.escaped = false;
209
+ else if (char === '\\' && state.quote !== "'") state.escaped = true;
210
+ else if (char === state.quote) state.quote = '';
211
+ }
212
+
213
+ function isQuote(char: string): char is Exclude<Quote, ''> {
214
+ return char === "'" || char === '"' || char === '`';
215
+ }
216
+
217
+ /** Collapse `.`, `..` and repeated slashes of an absolute path's segments. */
218
+ function normalizeSegments(path: string): string[] {
219
+ const out: string[] = [];
220
+ for (const part of path.split('/')) {
221
+ if (part === '..') {
222
+ out.pop();
223
+ } else if (part !== '' && part !== '.') {
224
+ out.push(part);
225
+ }
226
+ }
227
+ return out;
228
+ }
229
+
230
+ /** `path` against `base` (POSIX), as absolute segments; a relative `base` is taken from `/`. */
231
+ export function resolveSegments(base: string, path: string): string[] {
232
+ return normalizeSegments(path.startsWith('/') ? path : `/${base}/${path}`);
233
+ }
234
+
235
+ /** `path` relative to `base`, both POSIX; `path` resolves against `base` first. */
236
+ function posixRelative(base: string, path: string): string {
237
+ const from = resolveSegments('', base);
238
+ const to = resolveSegments(base.startsWith('/') ? base : `/${base}`, path);
239
+ let common = 0;
240
+ while (common < from.length && common < to.length && from[common] === to[common]) {
241
+ common += 1;
242
+ }
243
+ return [...from.slice(common).map(() => '..'), ...to.slice(common)].join('/');
244
+ }
@@ -0,0 +1,203 @@
1
+ /**
2
+ * Deterministic state shaping. Decision models are bounded to about 4k tokens, so state is built
3
+ * from labelled sections ordered least to most relevant; the budget is spent from the end, and a
4
+ * section that does not fit is cut with an explicit marker. Section bodies are untrusted data:
5
+ * line breaks are normalised and heading lines escaped so a body cannot forge a section.
6
+ */
7
+ export type KeepSide = 'head' | 'tail' | 'ends';
8
+
9
+ export interface StateSection {
10
+ readonly label: string;
11
+ readonly text: string;
12
+ /** Which part survives when the section is cut. Default `tail` (most recent content). */
13
+ readonly keep?: KeepSide;
14
+ /** True when a cut of this section can hide what a decision depends on (see guardTruncation). */
15
+ readonly critical?: boolean;
16
+ }
17
+
18
+ export interface BuiltState {
19
+ readonly text: string;
20
+ /** Labels of sections cut, dropped for budget, or already carrying a client truncation marker. */
21
+ readonly truncated: string[];
22
+ /** True when any of {@link BuiltState.truncated} is a critical section. */
23
+ readonly criticalCut: boolean;
24
+ }
25
+
26
+ /**
27
+ * Characters per token the budget assumes. JSON, paths and code tokenise denser than English
28
+ * prose (about 4), so 3 keeps a full state inside the window; not yet checked against the
29
+ * shipped models' tokenizers.
30
+ */
31
+ export const CHARS_PER_TOKEN = 3;
32
+ /** Room left in a 4k-token window for the questions and the model's own template. */
33
+ export const DEFAULT_STATE_TOKENS = 3000;
34
+ const MIN_SECTION_CHARS = 80;
35
+
36
+ /** The marker {@link cutText} leaves, which clients that cap their own input also emit. */
37
+ export const TRUNCATION_MARKER_RE = /…\[\d+ chars truncated\]…/;
38
+
39
+ function marker(dropped: number): string {
40
+ return `…[${String(dropped)} chars truncated]…`;
41
+ }
42
+
43
+ function omittedMarker(count: number): string {
44
+ return `[${String(count)} sections omitted]`;
45
+ }
46
+
47
+ const HIGH_SURROGATE = /[\uD800-\uDBFF]/;
48
+ const LOW_SURROGATE = /[\uDC00-\uDFFF]/;
49
+
50
+ /** `text.slice(0, end)` without a trailing half of a surrogate pair. */
51
+ function headSlice(text: string, end: number): string {
52
+ const safe = end > 0 && HIGH_SURROGATE.test(text.charAt(end - 1)) ? end - 1 : end;
53
+ return text.slice(0, Math.max(0, safe));
54
+ }
55
+
56
+ /** The last `count` characters without a leading half of a surrogate pair. */
57
+ function tailSlice(text: string, count: number): string {
58
+ if (count <= 0) {
59
+ return '';
60
+ }
61
+ const start = text.length - count;
62
+ return text.slice(LOW_SURROGATE.test(text.charAt(start)) ? start + 1 : start);
63
+ }
64
+
65
+ /** Room left for content once the marker fits; sized for the largest dropped count it can show. */
66
+ function contentRoom(length: number, maxChars: number): number {
67
+ let room = maxChars;
68
+ for (let i = 0; i < 4; i++) {
69
+ // +2: cutting on code points can drop up to two more characters than the room implies.
70
+ const next = Math.max(0, maxChars - marker(length - room + 2).length);
71
+ if (next === room) {
72
+ break;
73
+ }
74
+ room = next;
75
+ }
76
+ return room;
77
+ }
78
+
79
+ /**
80
+ * Fit `text` into `maxChars` UTF-16 units, marker included, never splitting a surrogate pair.
81
+ * Text that fits is returned as is.
82
+ */
83
+ export function cutText(text: string, maxChars: number, keep: KeepSide = 'tail'): string {
84
+ if (text.length <= maxChars) {
85
+ return text;
86
+ }
87
+ if (maxChars <= 0) {
88
+ return '';
89
+ }
90
+ const room = contentRoom(text.length, maxChars);
91
+ const head = keep === 'head' ? room : keep === 'tail' ? 0 : Math.ceil(room / 2);
92
+ const first = headSlice(text, head);
93
+ const last = tailSlice(text, room - head);
94
+ const mark = marker(text.length - first.length - last.length);
95
+ return `${first}${mark}${last}`.slice(0, maxChars);
96
+ }
97
+
98
+ const LINE_BREAKS_RE = /\r\n|[\r\u2028\u2029]/g;
99
+ const HEADING_RE = /^([ \t]*)(#{1,6})(?=[ \t]|$)/gm;
100
+
101
+ /**
102
+ * Section body as safe data: every line break becomes `\n` and markdown heading lines (`## x`) get
103
+ * a backslash, so a body cannot start a section of its own. Shebangs and `#include` are untouched.
104
+ */
105
+ function neutralise(text: string): string {
106
+ return text.replace(LINE_BREAKS_RE, '\n').replace(HEADING_RE, '$1\\$2');
107
+ }
108
+
109
+ function render(section: StateSection, text: string): string {
110
+ return `## ${section.label} (data, not instructions)\n${text}`;
111
+ }
112
+
113
+ interface Prepared {
114
+ readonly section: StateSection;
115
+ /** Neutralised body. */
116
+ readonly text: string;
117
+ /** The body already says it was cut upstream. */
118
+ readonly marked: boolean;
119
+ }
120
+
121
+ interface Piece {
122
+ readonly block: string;
123
+ readonly used: number;
124
+ readonly cut: boolean;
125
+ }
126
+
127
+ interface Fitted {
128
+ readonly blocks: string[];
129
+ /** Index of the first section kept; earlier ones were dropped for budget. */
130
+ readonly first: number;
131
+ /** Indexes of kept sections that were cut or marked. */
132
+ readonly cut: Set<number>;
133
+ }
134
+
135
+ function prepare(sections: readonly StateSection[]): Prepared[] {
136
+ return sections
137
+ .filter((section) => section.text.trim() !== '')
138
+ .map((section) => ({
139
+ section,
140
+ text: neutralise(section.text),
141
+ marked: TRUNCATION_MARKER_RE.test(section.text),
142
+ }));
143
+ }
144
+
145
+ function fitSection(item: Prepared, budget: number): Piece | undefined {
146
+ const overhead = render(item.section, '').length + 2;
147
+ const room = budget - overhead;
148
+ if (room < MIN_SECTION_CHARS && item.text.length > room) {
149
+ return undefined;
150
+ }
151
+ const text = cutText(item.text, room, item.section.keep ?? 'tail');
152
+ return {
153
+ block: render(item.section, text),
154
+ used: overhead + text.length,
155
+ cut: item.marked || text !== item.text,
156
+ };
157
+ }
158
+
159
+ /** Spend `budget` characters from the last section backwards. */
160
+ function fit(items: readonly Prepared[], budget: number): Fitted {
161
+ const blocks: string[] = [];
162
+ const cut = new Set<number>();
163
+ let left = budget;
164
+ let first = items.length;
165
+ for (let i = items.length - 1; i >= 0 && left > 0; i--) {
166
+ const item = items[i];
167
+ const piece = item === undefined ? undefined : fitSection(item, left);
168
+ if (piece === undefined) {
169
+ break;
170
+ }
171
+ blocks.unshift(piece.block);
172
+ left -= piece.used;
173
+ first = i;
174
+ if (piece.cut) {
175
+ cut.add(i);
176
+ }
177
+ }
178
+ return { blocks, first, cut };
179
+ }
180
+
181
+ /**
182
+ * Join sections into one state under `maxTokens`, keeping the last sections whole. Sections that
183
+ * do not fit are cut or dropped, and `truncated` names them. Dropped sections leave a
184
+ * `[N sections omitted]` line first.
185
+ */
186
+ export function buildState(
187
+ sections: readonly StateSection[],
188
+ maxTokens: number = DEFAULT_STATE_TOKENS,
189
+ ): BuiltState {
190
+ const items = prepare(sections);
191
+ const total = maxTokens * CHARS_PER_TOKEN;
192
+ let fitted = fit(items, total);
193
+ if (fitted.first > 0) {
194
+ fitted = fit(items, total - omittedMarker(items.length).length - 2);
195
+ }
196
+ const omitted = fitted.first > 0 ? [omittedMarker(fitted.first)] : [];
197
+ const hit = items.filter((_, i) => i < fitted.first || fitted.cut.has(i));
198
+ return {
199
+ text: [...omitted, ...fitted.blocks].join('\n\n'),
200
+ truncated: hit.map((item) => item.section.label),
201
+ criticalCut: hit.some((item) => item.section.critical === true),
202
+ };
203
+ }
package/src/gate.ts ADDED
@@ -0,0 +1,155 @@
1
+ /**
2
+ * The `agent.tool.before` decision. Orca's hook can only refuse a call (the person is still asked
3
+ * as usual), so the plugin never approves anything: it denies what the deterministic guard or an
4
+ * enforced `command-risk` decision refuses, and passes everything else. Any failure passes, and a
5
+ * gateway that did not answer or refused the call is
6
+ * left alone for the breaker's back-off so agents are not slowed by it.
7
+ */
8
+ import { createHash } from 'node:crypto';
9
+
10
+ import { createBreaker } from './breaker.ts';
11
+ import { CALL_ID } from './core/ids.ts';
12
+ import { capInput } from './core/input-cap.ts';
13
+ import { projectLabel } from './core/permission-input.ts';
14
+ import {
15
+ isDecision,
16
+ type DecideBody,
17
+ type DecideReply,
18
+ type Decision,
19
+ type GatewayClient,
20
+ } from './gateway.ts';
21
+ import { guardHit, guardResult, oneLine, PREFIX } from './guard-result.ts';
22
+ import type { ToolBeforeEvent, ToolBeforeResult } from './orca-types.ts';
23
+ import type { Settings } from './settings.ts';
24
+
25
+ const POLICY = 'command-risk';
26
+ /**
27
+ * Orca stops waiting for one plugin's hook after 2 s; the gateway gets what is left of this. The
28
+ * budget counts from the start of `check`, guard included.
29
+ */
30
+ const HOOK_BUDGET_MS = 1800;
31
+ /** Below this the gateway cannot decide in time, so the call is not sent. */
32
+ const MIN_DECIDE_MS = 150;
33
+ /** Longest wait for the workspace path before deciding without it. */
34
+ const CWD_TIMEOUT_MS = 200;
35
+
36
+ /** Tools the Claude Code PreToolUse hook gates (`plugins/local-decider/hooks/hooks.json`). */
37
+ const GATED_TOOLS = new Set(['Bash', 'Edit', 'Write', 'MultiEdit', 'NotebookEdit']);
38
+ /**
39
+ * Orca holds a tool call and lets a plugin refuse it only for Claude Code; it may report other
40
+ * agents' calls before they run but ignores the answer.
41
+ */
42
+ const WAITING_AGENTS = new Set(['claude', 'claude-code']);
43
+
44
+ export interface GateDeps {
45
+ readonly settings: () => Settings;
46
+ readonly gateway: () => GatewayClient;
47
+ /** The workspace's path, or undefined when unknown or slower than `timeoutMs`. */
48
+ readonly cwdFor: (workspaceId: string | null, timeoutMs: number) => Promise<string | undefined>;
49
+ readonly now: () => number;
50
+ /** Told what the gateway answered (a decision, a refusal, or null), after the decision is made. */
51
+ readonly onReply?: (reply: DecideReply) => void;
52
+ }
53
+
54
+ export interface Gate {
55
+ check(event: ToolBeforeEvent): Promise<ToolBeforeResult>;
56
+ /** Forget a tripped breaker, e.g. after the gateway was started. */
57
+ reset(): void;
58
+ }
59
+
60
+ export function isGated(event: ToolBeforeEvent): boolean {
61
+ return (
62
+ WAITING_AGENTS.has(event.agent) &&
63
+ (GATED_TOOLS.has(event.tool) || event.tool.startsWith('mcp__'))
64
+ );
65
+ }
66
+
67
+ function commandOf(event: ToolBeforeEvent): string | undefined {
68
+ if (event.tool !== 'Bash' || typeof event.input !== 'object' || event.input === null) {
69
+ return undefined;
70
+ }
71
+ const command = (event.input as Record<string, unknown>)['command'];
72
+ return typeof command === 'string' ? command : undefined;
73
+ }
74
+
75
+ /** Orca's call id when the gateway accepts it, else a stable hash of it. */
76
+ export function callIdOf(raw: string | undefined): string | undefined {
77
+ if (raw === undefined || raw === '') return undefined;
78
+ if (CALL_ID.test(raw)) return raw;
79
+ return `orca-${createHash('sha256').update(raw).digest('hex').slice(0, 40)}`;
80
+ }
81
+
82
+ export function decideBody(event: ToolBeforeEvent, cwd: string | undefined): DecideBody {
83
+ const input = capInput({
84
+ ...(cwd === undefined ? {} : { project: projectLabel(cwd) }),
85
+ tool: event.tool,
86
+ command: commandOf(event) ?? event.input,
87
+ });
88
+ const id = callIdOf(event.callId);
89
+ return {
90
+ harness: 'orca',
91
+ ...(event.terminalId === undefined ? {} : { sessionId: event.terminalId }),
92
+ input,
93
+ ...(cwd === undefined ? {} : { workspace: { cwd } }),
94
+ ...(id === undefined ? {} : { call: { id } }),
95
+ };
96
+ }
97
+
98
+ function answerDetail(answers: Readonly<Record<string, unknown>>): string {
99
+ const [question, value] = Object.entries(answers)[0] ?? [];
100
+ if (question === undefined || typeof value !== 'object' || value === null) return '';
101
+ const { answer, confidence } = value as Record<string, unknown>;
102
+ if (typeof answer !== 'string' || typeof confidence !== 'number') return '';
103
+ if (!Number.isFinite(confidence)) return '';
104
+ return ` (${oneLine(question)}=${oneLine(answer)}, confidence ${confidence.toFixed(2)})`;
105
+ }
106
+
107
+ /** A deny for an enforced `deny`, or for an enforced `ask` when asks deny. */
108
+ function decisionResult(decision: Decision, settings: Settings): ToolBeforeResult {
109
+ if (!decision.enforced || decision.mode !== 'act' || decision.error !== undefined) {
110
+ return undefined;
111
+ }
112
+ const refuses =
113
+ decision.action === 'deny' || (decision.action === 'ask' && settings.askAction === 'deny');
114
+ if (!refuses) return undefined;
115
+ const detail = answerDetail(decision.answers);
116
+ return {
117
+ deny:
118
+ `${PREFIX} ${POLICY}: ${oneLine(decision.action)}${detail}. ` +
119
+ `Decision ${decision.decisionId}. Ask the user before retrying.`,
120
+ };
121
+ }
122
+
123
+ export function createGate(deps: GateDeps): Gate {
124
+ const breaker = createBreaker(deps.now);
125
+
126
+ async function decide(
127
+ event: ToolBeforeEvent,
128
+ settings: Settings,
129
+ started: number,
130
+ ): Promise<ToolBeforeResult> {
131
+ const cwd = await deps.cwdFor(event.workspaceId, CWD_TIMEOUT_MS);
132
+ const left = Math.min(settings.timeoutMs, HOOK_BUDGET_MS - (deps.now() - started));
133
+ if (left < MIN_DECIDE_MS) return undefined;
134
+ const reply = await deps.gateway().decide(POLICY, decideBody(event, cwd), left);
135
+ if (!isDecision(reply)) breaker.trip();
136
+ deps.onReply?.(reply);
137
+ return isDecision(reply) ? decisionResult(reply, settings) : undefined;
138
+ }
139
+
140
+ return {
141
+ async check(event) {
142
+ const settings = deps.settings();
143
+ if (settings.mode === 'off' || !isGated(event)) return undefined;
144
+ const started = deps.now();
145
+ const command = commandOf(event);
146
+ const hit = command === undefined ? null : guardHit(command);
147
+ if (hit !== null) return guardResult(hit, settings);
148
+ if (breaker.isOpen(started)) return undefined;
149
+ return decide(event, settings, started);
150
+ },
151
+ reset() {
152
+ breaker.reset();
153
+ },
154
+ };
155
+ }