@pi-kode/permissions 0.0.0-init → 0.1.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,136 @@
1
+ import { Type } from 'typebox';
2
+ import { join, resolve } from 'node:path';
3
+ import type { GovernanceRuntime } from '../runtime/governance.ts';
4
+ import { canonical, hash, optionalText, textResult, humanReadable } from '../runtime/utils.ts';
5
+ import { object } from '../runtime/schema.ts';
6
+
7
+ export function registerPlanning(runtime: GovernanceRuntime): void {
8
+ runtime.register(
9
+ object({}),
10
+ 'EnterPlanMode',
11
+ 'Enter read-only planning. Shell/unknown tools are blocked. Only the designated plan file may be edited. ExitPlanMode requires explicit UI approval of its content hash.',
12
+ true,
13
+ async () => {
14
+ if (runtime.state.mode !== 'plan') {
15
+ const path = await canonical(join(runtime.store, 'plans', 'plan.md'));
16
+ runtime.state.plan = { path, previousMode: runtime.state.mode, status: 'draft' };
17
+ runtime.state.mode = 'plan';
18
+ runtime.persist();
19
+ } else if (!runtime.state.plan) {
20
+ runtime.state.plan = {
21
+ path: await canonical(join(runtime.store, 'plans', 'plan.md')),
22
+ previousMode: 'safe',
23
+ status: 'draft',
24
+ };
25
+ runtime.persist();
26
+ }
27
+ return textResult(
28
+ `Plan mode active. Write the plan to ${runtime.state.plan!.path}. Source edits and shell execution are blocked.`,
29
+ { plan: runtime.state.plan },
30
+ );
31
+ },
32
+ );
33
+
34
+ runtime.register(
35
+ object({}),
36
+ 'ExitPlanMode',
37
+ 'Present the current plan for explicit approval through the user UI. Approval is bound to the plan SHA-256; denial keeps plan mode active.',
38
+ true,
39
+ async (_input, ctx, signal) => {
40
+ const plan = runtime.state.plan;
41
+ if (runtime.state.mode !== 'plan' || !plan) throw new Error('Enter plan mode first');
42
+ const text = await optionalText(plan.path);
43
+ if (!text?.trim()) throw new Error('Write a non-empty plan before requesting approval');
44
+ const revision = hash(text);
45
+ const approved = await runtime.approvals.request(
46
+ ctx,
47
+ `Approve plan ${revision.slice(0, 12)}?`,
48
+ `${plan.path}\n\n${text}`,
49
+ signal,
50
+ );
51
+ const current = await optionalText(plan.path);
52
+ if (current === undefined || hash(current) !== revision) {
53
+ throw new Error('Plan changed during approval; review the revised plan');
54
+ }
55
+ plan.status = approved ? 'approved' : 'rejected';
56
+ if (approved) {
57
+ plan.approvedHash = revision;
58
+ runtime.state.mode = plan.previousMode;
59
+ }
60
+ runtime.persist();
61
+ return textResult(
62
+ approved
63
+ ? `Approved plan ${revision}. Mode restored to ${runtime.state.mode}.`
64
+ : 'Plan was not approved. Remain in plan mode.',
65
+ { approved, revision },
66
+ );
67
+ },
68
+ );
69
+
70
+ runtime.register(
71
+ object({
72
+ questions: Type.Array(
73
+ object({
74
+ question: Type.String({ minLength: 1 }),
75
+ header: Type.String(),
76
+ options: Type.Array(object({ label: Type.String(), description: Type.String() }), { minItems: 2, maxItems: 4 }),
77
+ multiSelect: Type.Optional(Type.Literal(false)),
78
+ }),
79
+ { minItems: 1, maxItems: 4 },
80
+ ),
81
+ }),
82
+ 'AskUserQuestion',
83
+ 'Ask up to four questions via TUI/RPC. Single-select options and a free-text answer are supported. Unattended execution fails explicitly.',
84
+ true,
85
+ async (input, ctx, signal) => {
86
+ if (!ctx.hasUI) throw new Error('AskUserQuestion requires a connected TUI or RPC UI');
87
+ const answers: Record<string, string> = {};
88
+ for (const question of input.questions) {
89
+ const other = '[Enter a custom answer]';
90
+ const selected = await ctx.ui.select(
91
+ question.question,
92
+ [...question.options.map((o: any) => `${o.label}: ${o.description}`), other],
93
+ { signal },
94
+ );
95
+ if (!selected) throw new Error('Question cancelled');
96
+ const answer = selected === other ? await ctx.ui.input(question.question, '', { signal }) : selected;
97
+ if (answer === undefined) throw new Error('Question cancelled');
98
+ answers[question.question] = answer;
99
+ }
100
+ return textResult(humanReadable({ answers }), { answers });
101
+ },
102
+ );
103
+
104
+ runtime.pi.on('before_agent_start', () => {
105
+ if (!runtime.ready || runtime.state.mode !== 'plan') return;
106
+ return {
107
+ message: {
108
+ customType: 'code-compat:plan',
109
+ content: `Plan mode is active. Do not mutate source files or run shell commands. Write only the designated plan artifact (${runtime.state.plan?.path ?? 'plan.md'}) and request approval with ExitPlanMode.`,
110
+ display: false,
111
+ },
112
+ };
113
+ });
114
+
115
+ runtime.pi.on('tool_call', async (e, ctx) => {
116
+ if (runtime.state.mode !== 'plan' || runtime.tools.has(e.toolName)) return;
117
+ if (['read', 'Read', 'grep', 'Grep', 'find', 'Glob', 'ls', 'TaskGet', 'TaskList', 'TaskOutput'].includes(e.toolName)) {
118
+ return;
119
+ }
120
+ const input = e.input as any;
121
+ const rawPath = input.file_path ?? input.path;
122
+ if (['write', 'Write', 'edit', 'Edit'].includes(e.toolName) && typeof rawPath === 'string') {
123
+ if ((await canonical(resolve(ctx.cwd, rawPath))) === runtime.state.plan?.path) return;
124
+ }
125
+ return {
126
+ block: true,
127
+ reason: 'Plan mode restricts mutations to the designated plan file. Approve the plan with ExitPlanMode.',
128
+ };
129
+ });
130
+
131
+ runtime.pi.on('user_bash', () =>
132
+ runtime.state.mode === 'plan'
133
+ ? { result: { output: 'Shell is blocked during planning.', exitCode: 1, cancelled: false, truncated: false } }
134
+ : undefined,
135
+ );
136
+ }
@@ -0,0 +1,192 @@
1
+ import { isAbsolute, matchesGlob, resolve } from 'node:path';
2
+ import type { Settings, Mode } from '../runtime/config.ts';
3
+ import { canonical, within } from '../runtime/utils.ts';
4
+
5
+ export interface Decision {
6
+ action: 'allow' | 'ask' | 'deny';
7
+ reason: string;
8
+ }
9
+
10
+ const readonly = new Set(['Read', 'Glob', 'Grep', 'TaskGet', 'TaskList', 'TaskOutput']);
11
+ const workflow = new Set(['EnterPlanMode', 'ExitPlanMode', 'AskUserQuestion', 'TaskCreate', 'TaskUpdate', 'TodoWrite', 'TaskStop']);
12
+
13
+ export async function decide(
14
+ name: string,
15
+ input: Record<string, any>,
16
+ mode: Mode,
17
+ config: Settings,
18
+ cwd: string,
19
+ planPath?: string,
20
+ ): Promise<Decision> {
21
+ const originalName = name;
22
+ if (name === 'TaskRun') name = 'Bash';
23
+ if (name === 'AgentBatch') name = 'Agent';
24
+ if (name === 'NotebookEdit') {
25
+ name = 'Edit';
26
+ input = { ...input, file_path: input.notebook_path };
27
+ }
28
+ const readAgent =
29
+ name === 'Agent' &&
30
+ (input.agents
31
+ ? input.agents.every((a: any) => ['Explore', 'Plan'].includes(a.subagent_type))
32
+ : ['Explore', 'Plan'].includes(input.subagent_type));
33
+ const file =
34
+ typeof (input.file_path ?? input.notebook_path) === 'string'
35
+ ? await canonical(resolve(cwd, input.file_path ?? input.notebook_path))
36
+ : undefined;
37
+
38
+ if (mode === 'plan' && !readAgent && !readonly.has(name) && !workflow.has(name)) {
39
+ if (!(name === 'Write' || name === 'Edit' || name === 'NotebookEdit') || !file || file !== planPath) {
40
+ return {
41
+ action: 'deny',
42
+ reason: 'Plan mode permits only reads, workflow tools and the designated plan artifact. Shell and alternate tools are blocked.',
43
+ };
44
+ }
45
+ }
46
+ if (mode === 'ask' || mode === 'fullAccess') {
47
+ for (const rule of config.permissions.deny) {
48
+ if (
49
+ (await matchesRule(rule, name, input, cwd, file, 'deny')) ||
50
+ (originalName !== name && (await matchesRule(rule, originalName, input, cwd, file, 'deny')))
51
+ ) {
52
+ return { action: 'deny', reason: `deny rule: ${rule}` };
53
+ }
54
+ }
55
+ return mode === 'ask'
56
+ ? { action: 'ask', reason: 'Ask Everything mode requires approval for every call' }
57
+ : { action: 'allow', reason: 'Full Access mode' };
58
+ }
59
+ for (const kind of ['deny', 'ask', 'allow'] as const) {
60
+ for (const rule of config.permissions[kind]) {
61
+ if (
62
+ (await matchesRule(rule, name, input, cwd, file, kind)) ||
63
+ (originalName !== name && (await matchesRule(rule, originalName, input, cwd, file, kind)))
64
+ ) {
65
+ return {
66
+ action: kind === 'deny' || (kind === 'ask' && mode === 'dontAsk') ? 'deny' : kind === 'ask' ? 'ask' : 'allow',
67
+ reason: `${kind} rule: ${rule}`,
68
+ };
69
+ }
70
+ }
71
+ }
72
+ if (mode === 'bypassPermissions') return { action: 'allow', reason: 'Explicit bypassPermissions mode (no sandbox)' };
73
+ if (readonly.has(name)) {
74
+ const target = file ?? (await canonical(resolve(cwd, input.path ?? '.')));
75
+ if (within(await canonical(cwd), target)) return { action: 'allow', reason: 'Read inside workspace' };
76
+ }
77
+ if (readAgent) return { action: 'allow', reason: 'Read-only child context' };
78
+ if (workflow.has(name)) return { action: 'allow', reason: 'Workflow operation; approvals are enforced by its state machine' };
79
+ if (
80
+ (name === 'Write' || name === 'Edit' || name === 'NotebookEdit') &&
81
+ file &&
82
+ ((mode === 'acceptEdits' && within(await canonical(cwd), file)) || (mode === 'plan' && file === planPath))
83
+ ) {
84
+ return { action: 'allow', reason: 'Allowed file edit in current mode' };
85
+ }
86
+ if (mode === 'dontAsk') return { action: 'deny', reason: 'dontAsk denies operations without an allow decision' };
87
+ return { action: 'ask', reason: 'Operation needs explicit approval' };
88
+ }
89
+
90
+ export async function matchesRule(
91
+ rule: string,
92
+ name: string,
93
+ input: Record<string, any>,
94
+ cwd: string,
95
+ canonicalFile?: string,
96
+ kind: 'allow' | 'ask' | 'deny' = 'allow',
97
+ ): Promise<boolean> {
98
+ const match = /^([A-Za-z][\w]*)(?:\((.*)\))?$/.exec(rule);
99
+ if (!match || match[1] !== name) return false;
100
+ if (match[2] === undefined || match[2] === '*') return true;
101
+ const pattern = match[2];
102
+ if (['Read', 'Write', 'Edit', 'Glob', 'Grep', 'NotebookEdit'].includes(name)) {
103
+ const supplied = resolve(cwd, input.file_path ?? input.path ?? '.');
104
+ const resolved = canonicalFile ?? (await canonical(supplied));
105
+ const absolutePattern = isAbsolute(pattern) ? pattern : resolve(cwd, pattern);
106
+ const lexicalMatch = matchesGlob(supplied, absolutePattern);
107
+ const resolvedMatch = matchesGlob(resolved, absolutePattern);
108
+ return kind === 'allow' ? lexicalMatch && resolvedMatch : lexicalMatch || resolvedMatch;
109
+ }
110
+ if (name === 'Bash') {
111
+ const variants = commandVariants(String(input.command ?? ''), cwd);
112
+ if (pattern.endsWith(':*')) {
113
+ const prefix = shellWords(pattern.slice(0, -2));
114
+ if (!prefix) return kind !== 'allow';
115
+ const parsed = variants.map(command => shellWords(command));
116
+ if (!parsed.some(tokens => tokens)) return kind !== 'allow';
117
+ return parsed.some(
118
+ tokens => !!tokens && tokens.length >= prefix.length && prefix.every((word, index) => tokens[index] === word),
119
+ );
120
+ }
121
+ if (pattern.includes('*') || pattern.includes(':')) return kind !== 'allow';
122
+ return variants.includes(pattern);
123
+ }
124
+ return kind !== 'allow';
125
+ }
126
+
127
+ export function withoutRedundantCd(command: string, cwd: string): string | undefined {
128
+ const match = /^\s*cd\s+([^\r\n]+?)\s*&&\s*([^\r\n]*)$/.exec(command);
129
+ if (!match) return;
130
+ const words = shellWords(`cd ${match[1]}`);
131
+ if (!words || words.length !== 2 || words[0] !== 'cd') return;
132
+ if (resolve(cwd, words[1]) !== resolve(cwd)) return;
133
+ return match[2].trim() || undefined;
134
+ }
135
+
136
+ function commandVariants(command: string, cwd: string): string[] {
137
+ const variants = [command];
138
+ let next = withoutRedundantCd(command, cwd);
139
+ while (next && !variants.includes(next)) {
140
+ variants.push(next);
141
+ next = withoutRedundantCd(next, cwd);
142
+ }
143
+ return variants;
144
+ }
145
+
146
+ export function shellWords(command: string): string[] | undefined {
147
+ if (/[\r\n]/.test(command)) return;
148
+ const words: string[] = [];
149
+ let word = '';
150
+ let quote = '';
151
+ let started = false;
152
+ for (let i = 0; i < command.length; i++) {
153
+ const c = command[i];
154
+ if (quote === "'") {
155
+ if (c === "'") quote = '';
156
+ else word += c;
157
+ continue;
158
+ }
159
+ if (c === '\\') {
160
+ if (quote === '"') return;
161
+ if (i + 1 >= command.length) return;
162
+ word += command[++i];
163
+ started = true;
164
+ continue;
165
+ }
166
+ if (c === '$' || c === '`') return;
167
+ if (quote === '"') {
168
+ if (c === '"') quote = '';
169
+ else word += c;
170
+ continue;
171
+ }
172
+ if (c === "'" || c === '"') {
173
+ quote = c;
174
+ started = true;
175
+ continue;
176
+ }
177
+ if (/[;&|<>(){}*?!~#]/.test(c)) return;
178
+ if (/\s/.test(c)) {
179
+ if (started) {
180
+ words.push(word);
181
+ word = '';
182
+ started = false;
183
+ }
184
+ continue;
185
+ }
186
+ word += c;
187
+ started = true;
188
+ }
189
+ if (quote) return;
190
+ if (started) words.push(word);
191
+ return words.length ? words : undefined;
192
+ }
@@ -0,0 +1,265 @@
1
+ import type { ExtensionAPI } from '@earendil-works/pi-coding-agent';
2
+ import { createAgentSession } from '@earendil-works/pi-coding-agent';
3
+ import { dirname, join, resolve } from 'node:path';
4
+ import { GovernanceRuntime } from '../runtime/governance.ts';
5
+ import { modes } from '../runtime/config.ts';
6
+ import { atomicWrite, canonical, hash, humanReadable, optionalText } from '../runtime/utils.ts';
7
+ import { decide, shellWords, withoutRedundantCd } from '../extensions/policy.ts';
8
+ import { registerStopHook } from '../extensions/hooks.ts';
9
+ import { registerPlanning } from '../extensions/planning.ts';
10
+ import { registerAgents } from '../extensions/agents.ts';
11
+
12
+ const CHANNEL = 'pi-ko:governance:v1';
13
+
14
+ export function installGovernance(pi: ExtensionAPI, createSession = createAgentSession): GovernanceRuntime | undefined {
15
+ let existing: GovernanceRuntime | undefined;
16
+ pi.events.emit(CHANNEL, { accept: (value: GovernanceRuntime) => { existing = value; } });
17
+ if (existing) {
18
+ existing.pi = pi;
19
+ return undefined;
20
+ }
21
+
22
+ const r = new GovernanceRuntime(pi);
23
+ const unsubscribe = pi.events.on(CHANNEL, (request: any) => request.accept(r));
24
+
25
+ const grants = new Set<string>();
26
+ const sessionRules = new Set<string>();
27
+
28
+ const restoreSessionGrants = (ctx: any) => {
29
+ grants.clear();
30
+ sessionRules.clear();
31
+ for (const e of ctx.sessionManager.getBranch()) {
32
+ if (e.type === 'custom') {
33
+ if ((e.customType === 'pk:permission-grant' || e.customType === 'cc:permission-grant') && typeof e.data?.key === 'string') {
34
+ grants.add(e.data.key);
35
+ }
36
+ if ((e.customType === 'pk:permission-rule' || e.customType === 'cc:permission-rule') && typeof e.data?.rule === 'string') {
37
+ sessionRules.add(e.data.rule);
38
+ }
39
+ }
40
+ }
41
+ };
42
+
43
+ pi.on('session_start', async (_e, ctx) => {
44
+ restoreSessionGrants(ctx);
45
+ await r.start(ctx);
46
+ });
47
+ pi.on('session_tree', async (_e, ctx) => {
48
+ restoreSessionGrants(ctx);
49
+ await r.start(ctx);
50
+ });
51
+ pi.on('session_shutdown', async (e, ctx) => {
52
+ if (r.ready) await r.hooks.run('SessionEnd', {}, r.config, ctx.cwd);
53
+ r.ready = false;
54
+ if (e.reason === 'reload' || e.reason === 'quit') unsubscribe();
55
+ });
56
+
57
+ registerAgents(r, createSession);
58
+ registerStopHook(r);
59
+
60
+ const choices = [
61
+ 'Safe — allow workspace reads and workflow operations',
62
+ 'Ask Everything — approve every tool call',
63
+ 'Full Access — allow all operations except explicit deny rules',
64
+ ];
65
+ const selectableModes = ['safe', 'ask', 'fullAccess'] as const;
66
+
67
+ const wildcards = (aliased: string, input: any, target?: string, cwd = ''): string[] => {
68
+ const out: string[] = [];
69
+ if (aliased === 'Bash' && typeof input.command === 'string') {
70
+ const words = shellWords(withoutRedundantCd(input.command, cwd) ?? input.command);
71
+ if (words?.length) {
72
+ if (words.length > 1) out.push(`Bash(${words.slice(0, 2).join(' ')}:*)`);
73
+ out.push(`Bash(${words[0]}:*)`);
74
+ }
75
+ } else if (['Read', 'Write', 'Edit', 'NotebookEdit'].includes(aliased) && target) {
76
+ out.push(`${aliased}(${dirname(target)}/**)`);
77
+ } else if (['Grep', 'Glob'].includes(aliased) && target) {
78
+ out.push(`${aliased}(${target}/**)`);
79
+ }
80
+ return [...new Set(out)];
81
+ };
82
+
83
+ const truncate = (value: any) =>
84
+ typeof value === 'string' && value.length > 600
85
+ ? value.slice(0, 600) + `… (${value.length - 600} more chars)`
86
+ : value;
87
+
88
+ const formatDetail = (input: any): string => {
89
+ if (typeof input?.code === 'string') {
90
+ const lines = (input.code as string).split('\n');
91
+ const reached = [...new Set([...(input.code as string).matchAll(/\btools\.([A-Za-z]\w*)/g)].map(match => match[1]))];
92
+ return `code:\n${lines.slice(0, 15).map(line => ` ${line}`).join('\n')}${
93
+ lines.length > 15 ? `\n … (${lines.length - 15} more lines)` : ''
94
+ }${reached.length ? `\nreaches tools: ${reached.join(', ')}` : ''}`;
95
+ }
96
+ if (typeof input?.command === 'string') return `command:\n ${truncate(input.command)}`;
97
+ const path = input.file_path ?? input.path;
98
+ const rest = Object.fromEntries(
99
+ Object.entries(input)
100
+ .filter(([key]) => !['file_path', 'path'].includes(key))
101
+ .map(([key, value]) => [key, truncate(value)]),
102
+ );
103
+ return `${typeof path === 'string' ? `path: ${path}\n` : ''}${Object.keys(rest).length ? humanReadable(rest) : ''}`.trim();
104
+ };
105
+
106
+ pi.registerCommand('permissions', {
107
+ description:
108
+ 'Select Safe, Ask Everything, or Full Access; /permissions mode safe|ask|fullAccess; /permissions allow|ask|deny Tool',
109
+ handler: async (args, ctx) => {
110
+ let [operation, ...rest] = args.trim().split(/\s+/);
111
+ let value = rest.join(' ');
112
+ if (!operation || (operation === 'mode' && !value)) {
113
+ if (r.state.mode === 'plan') throw Error('ExitPlanMode approval is required');
114
+ if (!ctx.hasUI) throw Error('Use /permissions mode safe, ask or fullAccess');
115
+ const selected = await ctx.ui.select('Permission mode', choices);
116
+ if (!selected) return;
117
+ operation = 'mode';
118
+ value = selectableModes[choices.indexOf(selected)];
119
+ }
120
+ if (operation === 'mode') {
121
+ if (!modes.includes(value as any) || value === 'plan') {
122
+ throw Error('Use safe, ask or fullAccess (legacy modes: acceptEdits, dontAsk, bypassPermissions); enter planning with EnterPlanMode');
123
+ }
124
+ if (r.state.mode === 'plan') throw Error('ExitPlanMode approval is required');
125
+ r.state.mode = value as any;
126
+ grants.clear();
127
+ r.persist();
128
+ r.status(ctx);
129
+ } else if (['allow', 'ask', 'deny'].includes(operation)) {
130
+ if (!/^[A-Za-z][\w]*(?:\(.*\))?$/.test(value)) throw Error('Invalid tool rule');
131
+ if (!ctx.isProjectTrusted()) throw Error('Trust project configuration before writing project policy');
132
+ const file = join(ctx.cwd, '.pi/settings.local.json');
133
+ const data = JSON.parse((await optionalText(file)) ?? '{}');
134
+ data.permissions ??= {};
135
+ data.permissions[operation] = [...new Set([...(data.permissions[operation] ?? []), value])];
136
+ await atomicWrite(file, JSON.stringify(data, null, 2) + '\n');
137
+ r.message(`Saved ${operation} rule to ${file}`);
138
+ }
139
+ await r.reload(ctx);
140
+ r.message(
141
+ humanReadable({
142
+ mode: r.state.mode,
143
+ rules: r.config.permissions,
144
+ sessionApprovals: grants.size,
145
+ sessionRules: [...sessionRules],
146
+ }),
147
+ );
148
+ },
149
+ });
150
+
151
+ pi.on('tool_call', async (e, ctx) => {
152
+ if (r.tools.has(e.toolName)) return;
153
+ if (!r.ready) return { block: true, reason: 'Permission runtime unavailable' };
154
+ await r.reload(ctx);
155
+
156
+ const hookResult = await r.hooks.run(
157
+ 'PreToolUse',
158
+ { tool_name: e.toolName, tool_input: e.input, tool_use_id: e.toolCallId },
159
+ r.config,
160
+ ctx.cwd,
161
+ ctx.signal,
162
+ );
163
+ if (hookResult.deny || hookResult.updatedInput) {
164
+ return {
165
+ block: true,
166
+ reason: hookResult.deny ?? 'Tool hook rewrites are not supported on native tools.',
167
+ };
168
+ }
169
+
170
+ const aliases: Record<string, string> = {
171
+ read: 'Read',
172
+ write: 'Write',
173
+ edit: 'Edit',
174
+ bash: 'Bash',
175
+ grep: 'Grep',
176
+ find: 'Glob',
177
+ ls: 'Glob',
178
+ };
179
+ const input = { ...e.input } as any;
180
+ if (input.path && ['read', 'write', 'edit'].includes(e.toolName)) input.file_path = input.path;
181
+ const aliased = aliases[e.toolName] ?? e.toolName;
182
+ const effective = {
183
+ ...r.config,
184
+ permissions: { ...r.config.permissions, allow: [...r.config.permissions.allow, ...sessionRules] },
185
+ };
186
+ const decision = await decide(aliased, input, r.state.mode, effective, ctx.cwd, r.state.plan?.path);
187
+ if (decision.action === 'deny') return { block: true, reason: decision.reason };
188
+
189
+ const fingerprint = JSON.stringify(r.config.permissions);
190
+ const inputHash = hash(JSON.stringify(e.input));
191
+ const path = input.file_path ?? input.path;
192
+ const target = typeof path === 'string' ? await canonical(resolve(ctx.cwd, path)) : undefined;
193
+ const key = hash(JSON.stringify([e.toolName, inputHash, target, fingerprint, r.state.mode]));
194
+
195
+ if (decision.action === 'ask' && (r.state.mode === 'ask' || !grants.has(key))) {
196
+ if (!ctx.hasUI) return { block: true, reason: 'Approval requires TUI/RPC UI' };
197
+ const sessionOptions =
198
+ r.state.mode === 'ask'
199
+ ? []
200
+ : [
201
+ 'Allow this exact call for session',
202
+ ...wildcards(aliased, input, target, ctx.cwd).map(rule => `Allow ${rule} for session`),
203
+ ];
204
+ const answer = await ctx.ui.select(
205
+ `${e.toolName}: ${decision.reason}\n${formatDetail(input)}`,
206
+ ['Allow once', ...sessionOptions, 'Deny'],
207
+ { signal: ctx.signal },
208
+ );
209
+ if (!answer || answer === 'Deny') return { block: true, reason: 'Permission denied' };
210
+ await r.reload(ctx);
211
+ if (
212
+ key !== hash(JSON.stringify([e.toolName, inputHash, target, fingerprint, r.state.mode])) ||
213
+ fingerprint !== JSON.stringify(r.config.permissions) ||
214
+ inputHash !== hash(JSON.stringify(e.input)) ||
215
+ (typeof path === 'string' && target !== (await canonical(resolve(ctx.cwd, path))))
216
+ ) {
217
+ return { block: true, reason: 'Policy or call target changed during approval; retry' };
218
+ }
219
+ if (answer === 'Allow this exact call for session') {
220
+ grants.add(key);
221
+ pi.appendEntry('pk:permission-grant', { key });
222
+ } else if (answer.startsWith('Allow ') && answer.endsWith(' for session')) {
223
+ const rule = answer.slice(6, -12);
224
+ if (/^[A-Za-z][\w]*\(.*\)$/.test(rule)) {
225
+ sessionRules.add(rule);
226
+ pi.appendEntry('pk:permission-rule', { rule });
227
+ }
228
+ }
229
+ }
230
+ });
231
+
232
+ pi.on('tool_result', async (e, ctx) => {
233
+ if (r.tools.has(e.toolName)) return;
234
+ const result = await r.hooks.run(
235
+ e.isError ? 'PostToolUseFailure' : 'PostToolUse',
236
+ { tool_name: e.toolName, tool_input: e.input, tool_response: e.content },
237
+ r.config,
238
+ ctx.cwd,
239
+ ctx.signal,
240
+ );
241
+ if (result.context.length) {
242
+ return { content: [...e.content, ...result.context.map(text => ({ type: 'text' as const, text }))] };
243
+ }
244
+ });
245
+
246
+ pi.on('input', async (e, ctx) => {
247
+ await r.reload(ctx);
248
+ const outcome = await r.hooks.run('UserPromptSubmit', { prompt: e.text }, r.config, ctx.cwd, ctx.signal);
249
+ if (outcome.deny) {
250
+ r.message(outcome.deny);
251
+ return { action: 'handled' as const };
252
+ }
253
+ if (outcome.context.length) {
254
+ return { action: 'transform' as const, text: e.text + '\n' + outcome.context.join('\n'), images: e.images };
255
+ }
256
+ });
257
+
258
+ registerPlanning(r);
259
+
260
+ return r;
261
+ }
262
+
263
+ export default function (pi: ExtensionAPI): void {
264
+ installGovernance(pi);
265
+ }
@@ -0,0 +1,14 @@
1
+ import type { ExtensionContext } from '@earendil-works/pi-coding-agent';
2
+
3
+ export class Approvals {
4
+ private tail: Promise<unknown> = Promise.resolve();
5
+ async request(ctx: ExtensionContext, title: string, detail: string, signal?: AbortSignal): Promise<boolean> {
6
+ const action = async () => {
7
+ if (!ctx.hasUI || signal?.aborted) return false;
8
+ return (await ctx.ui.select(`${title}\n${detail}`, ['Allow once', 'Deny'], { signal })) === 'Allow once';
9
+ };
10
+ const next = this.tail.then(action, action);
11
+ this.tail = next.catch(() => {});
12
+ return next;
13
+ }
14
+ }