@pi-kode/permissions 0.0.0-stage → 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.
- package/README.md +120 -2
- package/index.ts +1 -0
- package/lib/src/backends/process.ts +121 -0
- package/lib/src/extensions/agents.ts +209 -0
- package/lib/src/extensions/hooks.ts +98 -0
- package/lib/src/extensions/planning.ts +136 -0
- package/lib/src/extensions/policy.ts +192 -0
- package/lib/src/features/permissions.ts +265 -0
- package/lib/src/runtime/approvals.ts +14 -0
- package/lib/src/runtime/config.ts +89 -0
- package/lib/src/runtime/events.ts +19 -0
- package/lib/src/runtime/governance.ts +132 -0
- package/lib/src/runtime/schema.ts +2 -0
- package/lib/src/runtime/utils.ts +89 -0
- package/package.json +40 -4
- package/tests/agents.test.ts +130 -0
- package/tests/helper.ts +80 -0
- package/tests/policy.test.ts +149 -0
- package/tsconfig.json +19 -0
package/README.md
CHANGED
|
@@ -1,3 +1,121 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @pi-kode/permissions
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Standalone `pi` governance extension providing tool permissions, planning mode, lifecycle hooks, and policy-enforced subagents.
|
|
4
|
+
|
|
5
|
+
## Capabilities
|
|
6
|
+
|
|
7
|
+
### 1. Permissions and policy rules
|
|
8
|
+
|
|
9
|
+
Intercepts tool calls and evaluates them against the active permission mode and configured `allow`, `ask`, and `deny` rules.
|
|
10
|
+
|
|
11
|
+
#### Permission modes
|
|
12
|
+
|
|
13
|
+
Run `/permissions` or `/permissions mode` to open the mode picker, or switch directly with `/permissions mode <mode>`:
|
|
14
|
+
|
|
15
|
+
- **Safe** (`safe`, default): automatically allows workspace reads (`Read`, `Glob`, `Grep`, `TaskGet`, `TaskList`, `TaskOutput` within the workspace), read-only subagents (`Explore`, `Plan`), and workflow tools. File mutations, shell commands, and other operations require approval unless matched by an `allow` rule.
|
|
16
|
+
- **Ask Everything** (`ask`): requires approval before every tool call, including reads and calls covered by `allow` rules. Session approvals are not reused. Explicit `deny` rules still block.
|
|
17
|
+
- **Full Access** (`fullAccess`): allows operations without approval, including those covered by `ask` rules. Explicit `deny` rules still apply. Full Access does not grant operating-system privileges or bypass external sandboxes.
|
|
18
|
+
|
|
19
|
+
Legacy modes (`acceptEdits`, `dontAsk`, `bypassPermissions`) remain supported; legacy `default` session state is normalized to `safe` on restore. Mode selection is persisted per session branch.
|
|
20
|
+
|
|
21
|
+
Use `/permissions status` (or any `/permissions` command) to inspect the active mode, loaded rules, session approval count, and session wildcard rules.
|
|
22
|
+
|
|
23
|
+
#### Interactive approvals and session grants
|
|
24
|
+
|
|
25
|
+
When a tool call requires approval, the UI prompts with:
|
|
26
|
+
|
|
27
|
+
- `Allow once`
|
|
28
|
+
- `Allow this exact call for session` (bound to tool name, input hash, canonical target path, policy fingerprint, and mode; not offered in `ask` mode)
|
|
29
|
+
- Session wildcard rules where applicable, such as `Bash(<prefix>:*)`, `Edit(<dir>/**)`, or `Grep(<dir>/**)` (not offered in `ask` mode)
|
|
30
|
+
- `Deny`
|
|
31
|
+
|
|
32
|
+
Before allowing execution after an approval prompt, the extension re-checks the policy fingerprint, input hash, and canonical path so changes during approval are rejected. Session grants and session rules persist in the session branch and are restored on session load or tree navigation.
|
|
33
|
+
|
|
34
|
+
#### Policy rules and tool aliasing
|
|
35
|
+
|
|
36
|
+
Add persistent project rules with `/permissions allow <Rule>`, `/permissions ask <Rule>`, or `/permissions deny <Rule>` (saved to `.pi/settings.local.json`; requires project trust).
|
|
37
|
+
|
|
38
|
+
Rules are evaluated in order: `deny`, then `ask`, then `allow`.
|
|
39
|
+
|
|
40
|
+
- **Tool rules**: `Bash`, `Edit`, `Write`, `Read`, `Glob`, `Grep`, `NotebookEdit`, `Agent`, etc.
|
|
41
|
+
- **Path globs**: e.g. `Edit(src/**)` or `Read(/path/to/file)`. Both lexical and canonical (symlink-resolved) paths are checked.
|
|
42
|
+
- **Shell rules**: exact commands (`Bash(npm test)`) or safe command prefixes (`Bash(npm test:*)`). Shell prefix parsing rejects compound operators (`;`, `&&`, `||`, `|`), redirections, expansions (`$`, backticks), and newlines, and normalizes redundant `cd <cwd> && ...` prefixes.
|
|
43
|
+
- **Tool aliases**: native `pi` tools (`read`, `write`, `edit`, `bash`, `grep`, `find`, `ls`) map to `Read`, `Write`, `Edit`, `Bash`, `Grep`, `Glob`. `TaskRun` shares `Bash` policy, `AgentBatch` shares `Agent` policy, and `NotebookEdit` shares `Edit` policy.
|
|
44
|
+
|
|
45
|
+
### 2. Planning mode and user clarification
|
|
46
|
+
|
|
47
|
+
- **`EnterPlanMode`**: switches the session to read-only `plan` mode, remembers the previous mode, and designates a session-scoped plan file (`plan.md`). While in `plan` mode, source edits, shell tools, and `user_bash` are blocked; only workspace reads, read-only subagents, workflow tools, and edits to the designated plan file are allowed. Mode cannot be changed via `/permissions mode` until exited through `ExitPlanMode`.
|
|
48
|
+
- **`ExitPlanMode`**: displays the plan content and SHA-256 hash prefix for explicit UI approval. Verifies the plan file did not change during approval and restores the previous permission mode only if approved.
|
|
49
|
+
- **`AskUserQuestion`**: asks 1–4 structured single-select questions (each with 2–4 options plus a custom free-text option) via TUI/RPC UI. Fails explicitly in unattended/non-UI sessions.
|
|
50
|
+
|
|
51
|
+
### 3. Lifecycle hooks
|
|
52
|
+
|
|
53
|
+
Runs configured shell command hooks from `hooks.<Event>` in `.pi/settings.json` / `.pi/settings.local.json` (project hooks require project trust).
|
|
54
|
+
|
|
55
|
+
Supported events wired in this extension:
|
|
56
|
+
|
|
57
|
+
- `SessionStart` / `SessionEnd`
|
|
58
|
+
- `UserPromptSubmit` (can block prompts or append context)
|
|
59
|
+
- `PreToolUse` (can block tool calls; input rewrites on native tools are rejected)
|
|
60
|
+
- `PostToolUse` / `PostToolUseFailure` (can append additional context to tool results)
|
|
61
|
+
- `Stop` (can keep the agent working when a stop hook blocks settling)
|
|
62
|
+
|
|
63
|
+
Hooks receive a JSON payload on stdin and `CLAUDE_PROJECT_DIR` in their environment. Tool hooks support `*` or pipe-separated matchers (e.g. `Bash|Edit`) and configurable timeouts (default 30s, max 120s). Exit code `2` denies/blocks the operation; JSON stdout can return `decision`, `continue`, and `hookSpecificOutput` (`permissionDecision`, `additionalContext`).
|
|
64
|
+
|
|
65
|
+
### 4. Subagents
|
|
66
|
+
|
|
67
|
+
- **`Agent`**: launches an isolated child `pi` session with role `Explore`, `Plan`, or `general-purpose`, inheriting the parent model, thinking level, and permission policy.
|
|
68
|
+
- `Explore` and `Plan` (and any subagent while in `plan` mode) receive read-only tools (`read`, `grep`, `find`, `ls`).
|
|
69
|
+
- `general-purpose` (outside `plan` mode) receives `read`, `grep`, `find`, `ls`, `bash`, `edit`, `write`.
|
|
70
|
+
- Recursive delegation is disabled. Child tool calls are evaluated against the parent policy, and approvals route through the parent UI.
|
|
71
|
+
- Supports `resume` by saved agent UUID (keeping the original role), `max_turns` (default 20, max 100), and `timeout` (default 600s, max 3600s).
|
|
72
|
+
- **`AgentBatch`**: runs 1–8 independent subagent requests concurrently with a cap of 4 active children at once, preserving individual reports even when a sibling fails.
|
|
73
|
+
|
|
74
|
+
## Configuration
|
|
75
|
+
|
|
76
|
+
Settings are loaded from:
|
|
77
|
+
|
|
78
|
+
1. `~/.pi/settings.json`
|
|
79
|
+
2. `<workspace>/.pi/settings.json` (when project trust is granted)
|
|
80
|
+
3. `<workspace>/.pi/settings.local.json` (when project trust is granted)
|
|
81
|
+
|
|
82
|
+
Example `.pi/settings.json`:
|
|
83
|
+
|
|
84
|
+
```json
|
|
85
|
+
{
|
|
86
|
+
"permissions": {
|
|
87
|
+
"defaultMode": "safe",
|
|
88
|
+
"allow": ["Bash(npm test:*)"],
|
|
89
|
+
"ask": ["Write(src/**)"],
|
|
90
|
+
"deny": ["Bash(rm -rf:*)"]
|
|
91
|
+
},
|
|
92
|
+
"hooks": {
|
|
93
|
+
"PreToolUse": [
|
|
94
|
+
{
|
|
95
|
+
"matcher": "Bash",
|
|
96
|
+
"hooks": [
|
|
97
|
+
{
|
|
98
|
+
"type": "command",
|
|
99
|
+
"command": "./scripts/check-command.sh",
|
|
100
|
+
"timeout": 15
|
|
101
|
+
}
|
|
102
|
+
]
|
|
103
|
+
}
|
|
104
|
+
]
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
## Installing from npm
|
|
110
|
+
|
|
111
|
+
The committed `.npmrc` routes `@pi-kode` packages to the public npm registry. The package is published publicly at [npmjs.com/settings/pi-kode/packages](https://www.npmjs.com/settings/pi-kode/packages) and requires no authentication to install:
|
|
112
|
+
|
|
113
|
+
```sh
|
|
114
|
+
npm install @pi-kode/permissions
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
Or install `@pi-kode/permissions` through `pi`'s package manager.
|
|
118
|
+
|
|
119
|
+
## Contributing & Development
|
|
120
|
+
|
|
121
|
+
See [CONTRIBUTING.md](./CONTRIBUTING.md) for local setup, running tests and type checks, architecture guidelines, and the release process.
|
package/index.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { default } from './lib/src/features/permissions.ts';
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import type { FileHandle } from 'node:fs/promises';
|
|
3
|
+
import { mkdir, open } from 'node:fs/promises';
|
|
4
|
+
import { dirname } from 'node:path';
|
|
5
|
+
|
|
6
|
+
export interface ProcessResult {
|
|
7
|
+
output: string;
|
|
8
|
+
stdout: string;
|
|
9
|
+
stderr: string;
|
|
10
|
+
exitCode: number | null;
|
|
11
|
+
cancelled: boolean;
|
|
12
|
+
timedOut: boolean;
|
|
13
|
+
truncated: boolean;
|
|
14
|
+
outputPath?: string;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export async function runProcess(
|
|
18
|
+
command: string,
|
|
19
|
+
args: string[],
|
|
20
|
+
options: {
|
|
21
|
+
cwd: string;
|
|
22
|
+
signal?: AbortSignal;
|
|
23
|
+
timeout?: number;
|
|
24
|
+
input?: string;
|
|
25
|
+
outputPath?: string;
|
|
26
|
+
maxBytes?: number;
|
|
27
|
+
env?: NodeJS.ProcessEnv;
|
|
28
|
+
},
|
|
29
|
+
): Promise<ProcessResult> {
|
|
30
|
+
options.signal?.throwIfAborted();
|
|
31
|
+
const maxBytes = options.maxBytes ?? 64_000;
|
|
32
|
+
let sink: FileHandle | undefined;
|
|
33
|
+
if (options.outputPath) {
|
|
34
|
+
await mkdir(dirname(options.outputPath), { recursive: true });
|
|
35
|
+
sink = await open(options.outputPath, 'wx', 0o600);
|
|
36
|
+
}
|
|
37
|
+
try {
|
|
38
|
+
return await new Promise<ProcessResult>((resolve, reject) => {
|
|
39
|
+
options.signal?.throwIfAborted();
|
|
40
|
+
const child = spawn(command, args, {
|
|
41
|
+
cwd: options.cwd,
|
|
42
|
+
env: options.env ?? process.env,
|
|
43
|
+
detached: true,
|
|
44
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
45
|
+
});
|
|
46
|
+
let stdout = Buffer.alloc(0);
|
|
47
|
+
let stderr = Buffer.alloc(0);
|
|
48
|
+
let output = Buffer.alloc(0);
|
|
49
|
+
let size = 0;
|
|
50
|
+
let diskSize = 0;
|
|
51
|
+
let timedOut = false;
|
|
52
|
+
let cancelled = false;
|
|
53
|
+
let settled = false;
|
|
54
|
+
let diskWrites = Promise.resolve();
|
|
55
|
+
let killTimer: ReturnType<typeof setTimeout> | undefined;
|
|
56
|
+
const stop = () => {
|
|
57
|
+
try { process.kill(-child.pid!, 'SIGTERM'); } catch {}
|
|
58
|
+
killTimer ??= setTimeout(() => { try { process.kill(-child.pid!, 'SIGKILL'); } catch {} }, 250);
|
|
59
|
+
};
|
|
60
|
+
const onAbort = () => { cancelled = true; stop(); };
|
|
61
|
+
const timer = setTimeout(() => { timedOut = true; stop(); }, options.timeout ?? 120_000);
|
|
62
|
+
options.signal?.addEventListener('abort', onAbort, { once: true });
|
|
63
|
+
const cleanup = () => {
|
|
64
|
+
clearTimeout(timer);
|
|
65
|
+
options.signal?.removeEventListener('abort', onAbort);
|
|
66
|
+
};
|
|
67
|
+
const receive = (chunk: Buffer, stream: 'stdout' | 'stderr') => {
|
|
68
|
+
if (stream === 'stdout' && stdout.length < maxBytes) {
|
|
69
|
+
stdout = Buffer.concat([stdout, chunk.subarray(0, maxBytes - stdout.length)]);
|
|
70
|
+
}
|
|
71
|
+
if (stream === 'stderr' && stderr.length < maxBytes) {
|
|
72
|
+
stderr = Buffer.concat([stderr, chunk.subarray(0, maxBytes - stderr.length)]);
|
|
73
|
+
}
|
|
74
|
+
size += chunk.length;
|
|
75
|
+
if (output.length < maxBytes) {
|
|
76
|
+
output = Buffer.concat([output, chunk.subarray(0, maxBytes - output.length)]);
|
|
77
|
+
}
|
|
78
|
+
if (sink && diskSize < 16_000_000) {
|
|
79
|
+
const bytes = chunk.subarray(0, 16_000_000 - diskSize);
|
|
80
|
+
diskSize += bytes.length;
|
|
81
|
+
diskWrites = diskWrites.then(async () => { await sink!.write(bytes); });
|
|
82
|
+
diskWrites.catch(() => stop());
|
|
83
|
+
}
|
|
84
|
+
if (size > 16_000_000) stop();
|
|
85
|
+
};
|
|
86
|
+
child.stdout.on('data', chunk => receive(chunk, 'stdout'));
|
|
87
|
+
child.stderr.on('data', chunk => receive(chunk, 'stderr'));
|
|
88
|
+
child.stdin.on('error', () => {});
|
|
89
|
+
child.stdin.end(options.input);
|
|
90
|
+
child.on('error', error => {
|
|
91
|
+
if (settled) return;
|
|
92
|
+
settled = true;
|
|
93
|
+
cleanup();
|
|
94
|
+
reject(error);
|
|
95
|
+
});
|
|
96
|
+
child.on('close', async code => {
|
|
97
|
+
if (settled) return;
|
|
98
|
+
settled = true;
|
|
99
|
+
cleanup();
|
|
100
|
+
if (timedOut || cancelled) stop();
|
|
101
|
+
try {
|
|
102
|
+
await diskWrites;
|
|
103
|
+
resolve({
|
|
104
|
+
output: output.toString('utf8'),
|
|
105
|
+
stdout: stdout.toString('utf8'),
|
|
106
|
+
stderr: stderr.toString('utf8'),
|
|
107
|
+
exitCode: code,
|
|
108
|
+
timedOut,
|
|
109
|
+
cancelled,
|
|
110
|
+
truncated: size > maxBytes,
|
|
111
|
+
outputPath: options.outputPath,
|
|
112
|
+
});
|
|
113
|
+
} catch (error) {
|
|
114
|
+
reject(error);
|
|
115
|
+
}
|
|
116
|
+
});
|
|
117
|
+
});
|
|
118
|
+
} finally {
|
|
119
|
+
await sink?.close();
|
|
120
|
+
}
|
|
121
|
+
}
|
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
import type { ExtensionContext } from '@earendil-works/pi-coding-agent';
|
|
2
|
+
import { createAgentSession, DefaultResourceLoader, SessionManager, SettingsManager } from '@earendil-works/pi-coding-agent';
|
|
3
|
+
import { Type } from 'typebox';
|
|
4
|
+
import { basename, join, resolve } from 'node:path';
|
|
5
|
+
import { homedir } from 'node:os';
|
|
6
|
+
import { mkdir, readFile } from 'node:fs/promises';
|
|
7
|
+
import { randomUUID } from 'node:crypto';
|
|
8
|
+
import type { GovernanceRuntime } from '../runtime/governance.ts';
|
|
9
|
+
import { decide } from './policy.ts';
|
|
10
|
+
import { atomicWrite, textResult, canonical, agentSummary, humanReadable } from '../runtime/utils.ts';
|
|
11
|
+
|
|
12
|
+
const spec = Type.Object(
|
|
13
|
+
{
|
|
14
|
+
prompt: Type.String({ minLength: 1 }),
|
|
15
|
+
subagent_type: Type.Optional(
|
|
16
|
+
Type.Union([Type.Literal('Explore'), Type.Literal('Plan'), Type.Literal('general-purpose')]),
|
|
17
|
+
),
|
|
18
|
+
resume: Type.Optional(Type.String({ pattern: '^[0-9a-f-]{36}$' })),
|
|
19
|
+
max_turns: Type.Optional(Type.Integer({ minimum: 1, maximum: 100 })),
|
|
20
|
+
timeout: Type.Optional(Type.Integer({ minimum: 1, maximum: 3600000 })),
|
|
21
|
+
},
|
|
22
|
+
{ additionalProperties: false },
|
|
23
|
+
);
|
|
24
|
+
|
|
25
|
+
export function registerAgents(runtime: GovernanceRuntime, createSession = createAgentSession): void {
|
|
26
|
+
let active = 0;
|
|
27
|
+
const waiters: (() => void)[] = [];
|
|
28
|
+
|
|
29
|
+
async function run(input: any, ctx: ExtensionContext, signal?: AbortSignal) {
|
|
30
|
+
signal = AbortSignal.any([...(signal ? [signal] : []), AbortSignal.timeout(input.timeout ?? 600000)]);
|
|
31
|
+
if (active >= 4) await new Promise<void>(resolve => waiters.push(resolve));
|
|
32
|
+
else active++;
|
|
33
|
+
let child: any;
|
|
34
|
+
let remove = () => {};
|
|
35
|
+
const id = input.resume ?? randomUUID();
|
|
36
|
+
try {
|
|
37
|
+
ctx.ui.setStatus('compat-agents', `${active} subagent${active === 1 ? '' : 's'} running`);
|
|
38
|
+
signal?.throwIfAborted();
|
|
39
|
+
if (!ctx.model) throw Error('Select a parent model before delegating');
|
|
40
|
+
const sessions = join(runtime.store, 'agents', 'sessions');
|
|
41
|
+
await mkdir(sessions, { recursive: true });
|
|
42
|
+
const previous = input.resume
|
|
43
|
+
? JSON.parse(await readFile(join(runtime.store, 'agents', id + '.json'), 'utf8'))
|
|
44
|
+
: undefined;
|
|
45
|
+
if (previous && input.subagent_type && input.subagent_type !== previous.role) {
|
|
46
|
+
throw Error('A resumed agent must keep its original role');
|
|
47
|
+
}
|
|
48
|
+
if (previous && (typeof previous.sessionFile !== 'string' || !/^[-a-zA-Z0-9_.]+\.jsonl$/.test(previous.sessionFile))) {
|
|
49
|
+
throw Error('Invalid saved child session');
|
|
50
|
+
}
|
|
51
|
+
const role = previous?.role ?? input.subagent_type ?? 'general-purpose';
|
|
52
|
+
const manager = previous
|
|
53
|
+
? SessionManager.open(join(sessions, previous.sessionFile))
|
|
54
|
+
: SessionManager.create(ctx.cwd, sessions);
|
|
55
|
+
const allowed =
|
|
56
|
+
role === 'general-purpose' && runtime.state.mode !== 'plan'
|
|
57
|
+
? ['read', 'grep', 'find', 'ls', 'bash', 'edit', 'write']
|
|
58
|
+
: ['read', 'grep', 'find', 'ls'];
|
|
59
|
+
const settings = SettingsManager.inMemory();
|
|
60
|
+
const loader = new DefaultResourceLoader({
|
|
61
|
+
cwd: ctx.cwd,
|
|
62
|
+
agentDir: join(homedir(), '.pi/agent'),
|
|
63
|
+
settingsManager: settings,
|
|
64
|
+
noExtensions: true,
|
|
65
|
+
noSkills: true,
|
|
66
|
+
noPromptTemplates: true,
|
|
67
|
+
noThemes: true,
|
|
68
|
+
noContextFiles: true,
|
|
69
|
+
extensionFactories: [
|
|
70
|
+
api => {
|
|
71
|
+
api.on('before_agent_start', () => ({
|
|
72
|
+
systemPrompt: `${ctx.getSystemPrompt()}\n\nYou are a ${role} subagent. Work only on the delegated request. Available tools: ${allowed.join(', ')}. No recursive delegation. Return findings, changed files and verification results. Parent permission policy applies.`,
|
|
73
|
+
}));
|
|
74
|
+
api.on('tool_call', async e => {
|
|
75
|
+
if (!allowed.includes(e.toolName)) return { block: true, reason: 'Tool is outside child allowlist' };
|
|
76
|
+
await runtime.reload(ctx);
|
|
77
|
+
const aliases: Record<string, string> = {
|
|
78
|
+
read: 'Read',
|
|
79
|
+
grep: 'Grep',
|
|
80
|
+
find: 'Glob',
|
|
81
|
+
ls: 'Glob',
|
|
82
|
+
bash: 'Bash',
|
|
83
|
+
write: 'Write',
|
|
84
|
+
edit: 'Edit',
|
|
85
|
+
};
|
|
86
|
+
const normalized = { ...e.input } as any;
|
|
87
|
+
if (['read', 'write', 'edit'].includes(e.toolName)) normalized.file_path = normalized.path;
|
|
88
|
+
const fingerprint = JSON.stringify(runtime.config.permissions);
|
|
89
|
+
const path = normalized.file_path ?? normalized.path;
|
|
90
|
+
const target = typeof path === 'string' ? await canonical(resolve(ctx.cwd, path)) : undefined;
|
|
91
|
+
const decision = await decide(
|
|
92
|
+
aliases[e.toolName],
|
|
93
|
+
normalized,
|
|
94
|
+
runtime.state.mode,
|
|
95
|
+
runtime.config,
|
|
96
|
+
ctx.cwd,
|
|
97
|
+
runtime.state.plan?.path,
|
|
98
|
+
);
|
|
99
|
+
if (
|
|
100
|
+
decision.action === 'deny' ||
|
|
101
|
+
(decision.action === 'ask' &&
|
|
102
|
+
!(await runtime.approvals.request(ctx, `Subagent ${role}: ${e.toolName}`, humanReadable(normalized), signal)))
|
|
103
|
+
) {
|
|
104
|
+
return { block: true, reason: decision.reason };
|
|
105
|
+
}
|
|
106
|
+
await runtime.reload(ctx);
|
|
107
|
+
if (
|
|
108
|
+
fingerprint !== JSON.stringify(runtime.config.permissions) ||
|
|
109
|
+
(typeof path === 'string' && target !== (await canonical(resolve(ctx.cwd, path))))
|
|
110
|
+
) {
|
|
111
|
+
return { block: true, reason: 'Parent policy or child target changed during approval' };
|
|
112
|
+
}
|
|
113
|
+
});
|
|
114
|
+
},
|
|
115
|
+
],
|
|
116
|
+
});
|
|
117
|
+
await loader.reload();
|
|
118
|
+
const created = await createSession({
|
|
119
|
+
cwd: ctx.cwd,
|
|
120
|
+
model: ctx.model,
|
|
121
|
+
thinkingLevel: ctx.thinkingLevel,
|
|
122
|
+
settingsManager: settings,
|
|
123
|
+
resourceLoader: loader,
|
|
124
|
+
sessionManager: manager,
|
|
125
|
+
tools: allowed,
|
|
126
|
+
});
|
|
127
|
+
child = created.session;
|
|
128
|
+
await child.bindExtensions({
|
|
129
|
+
mode: 'print',
|
|
130
|
+
onError: (error: any) => {
|
|
131
|
+
throw new Error(`Child extension failed: ${String(error.message ?? error)}`);
|
|
132
|
+
},
|
|
133
|
+
});
|
|
134
|
+
const cancel = () => {
|
|
135
|
+
void child.abort();
|
|
136
|
+
};
|
|
137
|
+
signal?.addEventListener('abort', cancel, { once: true });
|
|
138
|
+
remove = () => signal?.removeEventListener('abort', cancel);
|
|
139
|
+
let turns = 0;
|
|
140
|
+
let limited = false;
|
|
141
|
+
const unsubscribe = child.subscribe((e: any) => {
|
|
142
|
+
if (
|
|
143
|
+
e.type === 'turn_end' &&
|
|
144
|
+
++turns >= (input.max_turns ?? 20) &&
|
|
145
|
+
(e.message?.content ?? []).some((c: any) => c.type === 'toolCall')
|
|
146
|
+
) {
|
|
147
|
+
limited = true;
|
|
148
|
+
void child.abort();
|
|
149
|
+
}
|
|
150
|
+
});
|
|
151
|
+
try {
|
|
152
|
+
signal?.throwIfAborted();
|
|
153
|
+
await child.prompt(input.prompt);
|
|
154
|
+
} finally {
|
|
155
|
+
unsubscribe();
|
|
156
|
+
}
|
|
157
|
+
signal?.throwIfAborted();
|
|
158
|
+
const assistants = child.messages.filter((m: any) => m.role === 'assistant');
|
|
159
|
+
const last = assistants.at(-1);
|
|
160
|
+
if (last?.stopReason === 'error') throw new Error(last.errorMessage ?? 'Child model failed');
|
|
161
|
+
const output = assistants
|
|
162
|
+
.flatMap((m: any) => m.content.filter((c: any) => c.type === 'text').map((c: any) => c.text))
|
|
163
|
+
.join('\n')
|
|
164
|
+
.slice(-64000);
|
|
165
|
+
const record = {
|
|
166
|
+
id,
|
|
167
|
+
role,
|
|
168
|
+
sessionFile: basename(manager.getSessionFile()!),
|
|
169
|
+
status: limited ? 'turn_limit' : 'completed',
|
|
170
|
+
turns,
|
|
171
|
+
output,
|
|
172
|
+
};
|
|
173
|
+
await atomicWrite(join(runtime.store, 'agents', id + '.json'), JSON.stringify(record));
|
|
174
|
+
return record;
|
|
175
|
+
} finally {
|
|
176
|
+
remove();
|
|
177
|
+
child?.dispose();
|
|
178
|
+
const next = waiters.shift();
|
|
179
|
+
if (next) next();
|
|
180
|
+
else active--;
|
|
181
|
+
ctx.ui.setStatus('compat-agents', active ? `${active} subagent${active === 1 ? '' : 's'} running` : undefined);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
runtime.register(
|
|
186
|
+
spec,
|
|
187
|
+
'Agent',
|
|
188
|
+
'Run an isolated-context Explore, Plan or general-purpose child pi session. Inherits parent model and permissions; child approvals use the parent UI. No recursive delegation. Four children maximum at once.',
|
|
189
|
+
false,
|
|
190
|
+
async (input, ctx, signal) => {
|
|
191
|
+
const result = await run(input, ctx, signal);
|
|
192
|
+
return textResult(agentSummary(result), result);
|
|
193
|
+
},
|
|
194
|
+
);
|
|
195
|
+
|
|
196
|
+
runtime.register(
|
|
197
|
+
Type.Object({ agents: Type.Array(spec, { minItems: 1, maxItems: 8 }) }, { additionalProperties: false }),
|
|
198
|
+
'AgentBatch',
|
|
199
|
+
'Run independent delegated requests concurrently; preserve reports when a sibling fails.',
|
|
200
|
+
false,
|
|
201
|
+
async (input, ctx, signal) => {
|
|
202
|
+
const results = await Promise.allSettled(input.agents.map((a: any) => run(a, ctx, signal)));
|
|
203
|
+
const reports = results.map((v: any) =>
|
|
204
|
+
v.status === 'fulfilled' ? v.value : { status: 'failed', error: String(v.reason) },
|
|
205
|
+
);
|
|
206
|
+
return textResult(reports.map(agentSummary).join('\n\n────────\n\n'), { reports });
|
|
207
|
+
},
|
|
208
|
+
);
|
|
209
|
+
}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import type { GovernanceRuntime } from '../runtime/governance.ts';
|
|
2
|
+
import { runProcess } from '../backends/process.ts';
|
|
3
|
+
import type { CompatEvent, HookOutcome } from '../runtime/events.ts';
|
|
4
|
+
import type { Settings } from '../runtime/config.ts';
|
|
5
|
+
|
|
6
|
+
export class Hooks {
|
|
7
|
+
async run(
|
|
8
|
+
event: CompatEvent,
|
|
9
|
+
payload: Record<string, unknown>,
|
|
10
|
+
config: Settings,
|
|
11
|
+
cwd: string,
|
|
12
|
+
signal?: AbortSignal,
|
|
13
|
+
): Promise<HookOutcome> {
|
|
14
|
+
const outcome: HookOutcome = { context: [] };
|
|
15
|
+
for (const group of config.hooks[event] ?? []) {
|
|
16
|
+
if (!group || !Array.isArray(group.hooks)) throw new Error(`Invalid ${event} hook group`);
|
|
17
|
+
if (group.matcher && group.matcher !== '*') {
|
|
18
|
+
const names = group.matcher.split('|');
|
|
19
|
+
if (names.some(x => !/^[\w]+$/.test(x))) throw new Error(`Unsupported hook matcher: ${group.matcher}`);
|
|
20
|
+
if (!names.includes(String(payload.tool_name ?? ''))) continue;
|
|
21
|
+
}
|
|
22
|
+
for (const hook of group.hooks) {
|
|
23
|
+
if (hook.type !== 'command' || !hook.command) throw new Error(`Unsupported ${event} hook type: ${hook.type}`);
|
|
24
|
+
const result = await runProcess('/bin/sh', ['-c', hook.command], {
|
|
25
|
+
cwd,
|
|
26
|
+
signal,
|
|
27
|
+
timeout: Math.min(Math.max((hook.timeout ?? 30) * 1000, 1), 120_000),
|
|
28
|
+
input: JSON.stringify({ ...payload, hook_event_name: event, cwd }) + '\n',
|
|
29
|
+
env: { ...process.env, CLAUDE_PROJECT_DIR: cwd },
|
|
30
|
+
});
|
|
31
|
+
if (result.timedOut || result.cancelled || result.truncated) {
|
|
32
|
+
throw new Error(`${event} hook timed out, was cancelled, or exceeded output limit`);
|
|
33
|
+
}
|
|
34
|
+
if (result.exitCode === 2) {
|
|
35
|
+
outcome.deny = (result.stderr || result.stdout).trim() || `${event} hook blocked the operation`;
|
|
36
|
+
continue;
|
|
37
|
+
}
|
|
38
|
+
if (result.exitCode !== 0) throw new Error(`${event} hook failed (${result.exitCode}): ${result.output}`);
|
|
39
|
+
if (!result.stdout.trim()) continue;
|
|
40
|
+
let json: any;
|
|
41
|
+
try {
|
|
42
|
+
json = JSON.parse(result.stdout);
|
|
43
|
+
} catch {
|
|
44
|
+
if (/^\s*[\[{]/.test(result.stdout)) throw new Error(`Invalid ${event} hook JSON`);
|
|
45
|
+
outcome.context.push(result.stdout);
|
|
46
|
+
continue;
|
|
47
|
+
}
|
|
48
|
+
if (!json || typeof json !== 'object' || Array.isArray(json)) throw new Error(`Invalid ${event} hook response`);
|
|
49
|
+
if (['PreToolUse', 'PermissionRequest'].includes(event) && json.decision === 'block') {
|
|
50
|
+
outcome.deny = json.reason ?? 'Hook blocked the operation';
|
|
51
|
+
}
|
|
52
|
+
if (json.continue === false) outcome.deny = json.stopReason ?? 'Hook requested stop';
|
|
53
|
+
const specific = json.hookSpecificOutput;
|
|
54
|
+
if (specific?.hookEventName && specific.hookEventName !== event) throw new Error('Hook response event mismatch');
|
|
55
|
+
if (specific?.permissionDecision === 'deny') {
|
|
56
|
+
outcome.deny = specific.permissionDecisionReason ?? 'Hook denied operation';
|
|
57
|
+
}
|
|
58
|
+
if (specific?.updatedInput) {
|
|
59
|
+
if (typeof specific.updatedInput !== 'object' || Array.isArray(specific.updatedInput)) {
|
|
60
|
+
throw new Error('Invalid hook updatedInput');
|
|
61
|
+
}
|
|
62
|
+
outcome.updatedInput = specific.updatedInput;
|
|
63
|
+
payload.tool_input = specific.updatedInput;
|
|
64
|
+
}
|
|
65
|
+
if (specific?.additionalContext) outcome.context.push(String(specific.additionalContext));
|
|
66
|
+
if (event === 'Stop' && json.decision === 'block') {
|
|
67
|
+
outcome.continueReason = json.reason ?? 'Continue working.';
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
return outcome;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export function registerStopHook(runtime: GovernanceRuntime): void {
|
|
76
|
+
let stopActive = false;
|
|
77
|
+
runtime.pi.on('agent_before_settle', async (_event, ctx) => {
|
|
78
|
+
if (!runtime.ready) return;
|
|
79
|
+
const result = await runtime.hooks.run('Stop', { stop_hook_active: stopActive }, runtime.config, ctx.cwd, ctx.signal);
|
|
80
|
+
if ((result.continueReason || result.deny) && !stopActive) {
|
|
81
|
+
stopActive = true;
|
|
82
|
+
return {
|
|
83
|
+
continue: true,
|
|
84
|
+
entries: [
|
|
85
|
+
{
|
|
86
|
+
type: 'custom_message' as const,
|
|
87
|
+
customType: 'code-compat:stop',
|
|
88
|
+
content: result.continueReason ?? result.deny!,
|
|
89
|
+
display: false,
|
|
90
|
+
},
|
|
91
|
+
],
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
});
|
|
95
|
+
runtime.pi.on('agent_settled', () => {
|
|
96
|
+
stopActive = false;
|
|
97
|
+
});
|
|
98
|
+
}
|