@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.
- package/README.md +121 -0
- 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 +39 -2
- 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
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { homedir } from 'node:os';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { optionalText } from './utils.ts';
|
|
4
|
+
|
|
5
|
+
export type Mode =
|
|
6
|
+
| 'safe'
|
|
7
|
+
| 'ask'
|
|
8
|
+
| 'fullAccess'
|
|
9
|
+
| 'acceptEdits'
|
|
10
|
+
| 'plan'
|
|
11
|
+
| 'dontAsk'
|
|
12
|
+
| 'bypassPermissions';
|
|
13
|
+
|
|
14
|
+
export const modes: Mode[] = [
|
|
15
|
+
'safe',
|
|
16
|
+
'ask',
|
|
17
|
+
'fullAccess',
|
|
18
|
+
'acceptEdits',
|
|
19
|
+
'plan',
|
|
20
|
+
'dontAsk',
|
|
21
|
+
'bypassPermissions',
|
|
22
|
+
];
|
|
23
|
+
|
|
24
|
+
export interface HookGroup {
|
|
25
|
+
matcher?: string;
|
|
26
|
+
hooks: { type: string; command?: string; timeout?: number }[];
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface Settings {
|
|
30
|
+
permissions: { allow: string[]; ask: string[]; deny: string[]; defaultMode?: Mode };
|
|
31
|
+
hooks: Record<string, HookGroup[]>;
|
|
32
|
+
provenance: Record<string, string[]>;
|
|
33
|
+
diagnostics: string[];
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export async function loadConfig(cwd: string, trusted: boolean, home = homedir()): Promise<Settings> {
|
|
37
|
+
const result: Settings = { permissions: { allow: [], ask: [], deny: [] }, hooks: {}, provenance: {}, diagnostics: [] };
|
|
38
|
+
const files = [
|
|
39
|
+
join(home, '.pi/settings.json'),
|
|
40
|
+
...(trusted ? [join(cwd, '.pi/settings.json'), join(cwd, '.pi/settings.local.json')] : []),
|
|
41
|
+
];
|
|
42
|
+
if (!trusted) result.diagnostics.push('Project executable configuration is disabled until pi project trust is granted.');
|
|
43
|
+
for (const file of files) {
|
|
44
|
+
const raw = await optionalText(file);
|
|
45
|
+
if (raw === undefined) continue;
|
|
46
|
+
let data: any;
|
|
47
|
+
try {
|
|
48
|
+
data = JSON.parse(raw);
|
|
49
|
+
} catch {
|
|
50
|
+
throw new Error(`Invalid JSON in ${file}`);
|
|
51
|
+
}
|
|
52
|
+
if (!data || typeof data !== 'object' || Array.isArray(data)) throw new Error(`Expected settings object: ${file}`);
|
|
53
|
+
for (const [key, value] of Object.entries(data)) {
|
|
54
|
+
(result.provenance[key] ??= []).push(file);
|
|
55
|
+
if (key === 'permissions') {
|
|
56
|
+
if (!value || typeof value !== 'object') throw new Error(`Invalid permissions in ${file}`);
|
|
57
|
+
const p = value as any;
|
|
58
|
+
for (const kind of ['allow', 'ask', 'deny'] as const) {
|
|
59
|
+
if (p[kind] === undefined) continue;
|
|
60
|
+
if (!Array.isArray(p[kind]) || p[kind].some((x: unknown) => typeof x !== 'string')) {
|
|
61
|
+
throw new Error(`Invalid permissions.${kind}: ${file}`);
|
|
62
|
+
}
|
|
63
|
+
for (const rule of p[kind]) {
|
|
64
|
+
if (!/^[A-Za-z][\w]*(?:\(.*\))?$/.test(rule)) throw new Error(`Invalid permission rule ${rule}: ${file}`);
|
|
65
|
+
}
|
|
66
|
+
result.permissions[kind] = [...new Set([...result.permissions[kind], ...p[kind]])];
|
|
67
|
+
}
|
|
68
|
+
if (p.defaultMode !== undefined) {
|
|
69
|
+
if (!modes.includes(p.defaultMode)) throw new Error(`Unsupported permission mode: ${p.defaultMode}`);
|
|
70
|
+
result.permissions.defaultMode = p.defaultMode;
|
|
71
|
+
}
|
|
72
|
+
for (const name of Object.keys(p)) {
|
|
73
|
+
if (!['allow', 'ask', 'deny', 'defaultMode'].includes(name)) {
|
|
74
|
+
result.diagnostics.push(`Unsupported permissions.${name}: ${file}`);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
} else if (key === 'hooks') {
|
|
78
|
+
if (!value || typeof value !== 'object') throw new Error(`Invalid hooks: ${file}`);
|
|
79
|
+
for (const [event, groups] of Object.entries(value)) {
|
|
80
|
+
if (!Array.isArray(groups)) throw new Error(`Invalid hooks.${event}: ${file}`);
|
|
81
|
+
result.hooks[event] = [...(result.hooks[event] ?? []), ...groups];
|
|
82
|
+
}
|
|
83
|
+
} else {
|
|
84
|
+
result.diagnostics.push(`Unsupported setting ${key}: ${file}`);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
return result;
|
|
89
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
export type CompatEvent =
|
|
2
|
+
| 'SessionStart'
|
|
3
|
+
| 'SessionEnd'
|
|
4
|
+
| 'UserPromptSubmit'
|
|
5
|
+
| 'PreToolUse'
|
|
6
|
+
| 'PermissionRequest'
|
|
7
|
+
| 'PostToolUse'
|
|
8
|
+
| 'PostToolUseFailure'
|
|
9
|
+
| 'Stop'
|
|
10
|
+
| 'PreCompact'
|
|
11
|
+
| 'PostCompact'
|
|
12
|
+
| 'TaskCompleted';
|
|
13
|
+
|
|
14
|
+
export interface HookOutcome {
|
|
15
|
+
deny?: string;
|
|
16
|
+
updatedInput?: Record<string, unknown>;
|
|
17
|
+
context: string[];
|
|
18
|
+
continueReason?: string;
|
|
19
|
+
}
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import type { ExtensionAPI, ExtensionContext, ToolDefinition } from '@earendil-works/pi-coding-agent';
|
|
2
|
+
import type { TSchema } from 'typebox';
|
|
3
|
+
import { Check } from 'typebox/value';
|
|
4
|
+
import { homedir } from 'node:os';
|
|
5
|
+
import { join } from 'node:path';
|
|
6
|
+
import { Approvals } from './approvals.ts';
|
|
7
|
+
import { loadConfig, type Mode, type Settings } from './config.ts';
|
|
8
|
+
import { hash, textResult } from './utils.ts';
|
|
9
|
+
import { Hooks } from '../extensions/hooks.ts';
|
|
10
|
+
|
|
11
|
+
export interface PlanState {
|
|
12
|
+
path: string;
|
|
13
|
+
previousMode: Mode;
|
|
14
|
+
approvedHash?: string;
|
|
15
|
+
status: 'draft' | 'approved' | 'rejected';
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export interface GovernanceState {
|
|
19
|
+
version: 1;
|
|
20
|
+
mode: Mode;
|
|
21
|
+
plan?: PlanState;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export const initialState = (): GovernanceState => ({ version: 1, mode: 'safe' });
|
|
25
|
+
|
|
26
|
+
function normalizeMode(mode: unknown): Mode {
|
|
27
|
+
return typeof mode === 'string' && mode !== 'default' ? (mode as Mode) : 'safe';
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function restoreState(entries: readonly any[]): GovernanceState {
|
|
31
|
+
let state = initialState();
|
|
32
|
+
for (const entry of entries) {
|
|
33
|
+
if (entry.type === 'custom' && entry.customType === 'code-compat:state' && entry.data?.version === 1) {
|
|
34
|
+
const plan = entry.data.plan ? structuredClone(entry.data.plan) : undefined;
|
|
35
|
+
if (plan) plan.previousMode = normalizeMode(plan.previousMode);
|
|
36
|
+
state = {
|
|
37
|
+
version: 1,
|
|
38
|
+
mode: normalizeMode(entry.data.mode),
|
|
39
|
+
...(plan ? { plan } : {}),
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
return state;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export class GovernanceRuntime {
|
|
47
|
+
pi: ExtensionAPI;
|
|
48
|
+
readonly approvals = new Approvals();
|
|
49
|
+
readonly hooks = new Hooks();
|
|
50
|
+
readonly tools = new Set<string>();
|
|
51
|
+
state: GovernanceState = initialState();
|
|
52
|
+
config: Settings = { permissions: { allow: [], ask: [], deny: [] }, hooks: {}, provenance: {}, diagnostics: [] };
|
|
53
|
+
cwd = '';
|
|
54
|
+
store = '';
|
|
55
|
+
ready = false;
|
|
56
|
+
private uiContext?: ExtensionContext;
|
|
57
|
+
|
|
58
|
+
constructor(pi: ExtensionAPI) {
|
|
59
|
+
this.pi = pi;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
async start(ctx: ExtensionContext): Promise<void> {
|
|
63
|
+
this.ready = false;
|
|
64
|
+
this.cwd = ctx.cwd;
|
|
65
|
+
this.state = restoreState(ctx.sessionManager.getBranch());
|
|
66
|
+
this.store = join(
|
|
67
|
+
homedir(),
|
|
68
|
+
'.local/share/pi-code-compat',
|
|
69
|
+
hash(ctx.cwd).slice(0, 24),
|
|
70
|
+
hash(ctx.sessionManager.getSessionId()).slice(0, 24),
|
|
71
|
+
);
|
|
72
|
+
await this.reload(ctx);
|
|
73
|
+
if (!ctx.sessionManager.getBranch().some((e: any) => e.customType === 'code-compat:state')) {
|
|
74
|
+
this.state.mode = this.config.permissions.defaultMode ?? 'safe';
|
|
75
|
+
}
|
|
76
|
+
const startup = await this.hooks.run(
|
|
77
|
+
'SessionStart',
|
|
78
|
+
{ source: 'startup', session_id: ctx.sessionManager.getSessionId() },
|
|
79
|
+
this.config,
|
|
80
|
+
this.cwd,
|
|
81
|
+
ctx.signal,
|
|
82
|
+
);
|
|
83
|
+
if (startup.deny) throw new Error(startup.deny);
|
|
84
|
+
this.ready = true;
|
|
85
|
+
this.status(ctx);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
async reload(ctx: ExtensionContext): Promise<void> {
|
|
89
|
+
this.config = await loadConfig(ctx.cwd, ctx.isProjectTrusted());
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
persist(): void {
|
|
93
|
+
this.pi.appendEntry('code-compat:state', structuredClone(this.state));
|
|
94
|
+
if (this.uiContext) this.status(this.uiContext);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
status(ctx: ExtensionContext): void {
|
|
98
|
+
this.uiContext = ctx;
|
|
99
|
+
ctx.ui.setStatus('code-compat', `PK ${this.state.mode}`);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
message(content: string): void {
|
|
103
|
+
this.pi.sendMessage({ customType: 'code-compat', content, display: true });
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
register(
|
|
107
|
+
schema: TSchema,
|
|
108
|
+
name: string,
|
|
109
|
+
description: string,
|
|
110
|
+
write: boolean,
|
|
111
|
+
backend: (input: any, ctx: ExtensionContext, signal?: AbortSignal) => Promise<ReturnType<typeof textResult>>,
|
|
112
|
+
): void {
|
|
113
|
+
this.tools.add(name);
|
|
114
|
+
const tool: ToolDefinition<any, any> = {
|
|
115
|
+
name,
|
|
116
|
+
label: name,
|
|
117
|
+
description,
|
|
118
|
+
parameters: schema,
|
|
119
|
+
executionMode: write ? 'sequential' : 'parallel',
|
|
120
|
+
execute: async (_id, raw, signal, _update, ctx) => {
|
|
121
|
+
if (!this.ready) throw new Error('Governance runtime is unavailable');
|
|
122
|
+
const input: any = structuredClone(raw);
|
|
123
|
+
if (!Check(schema, input)) throw new Error(`Invalid ${name} input`);
|
|
124
|
+
await this.reload(ctx);
|
|
125
|
+
const result = await backend(input, ctx, signal);
|
|
126
|
+
this.status(ctx);
|
|
127
|
+
return result;
|
|
128
|
+
},
|
|
129
|
+
};
|
|
130
|
+
this.pi.registerTool(tool);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
2
|
+
import { mkdir, readFile, rename, rm, writeFile, realpath, stat } from 'node:fs/promises';
|
|
3
|
+
import { dirname, resolve, relative, isAbsolute, sep } from 'node:path';
|
|
4
|
+
|
|
5
|
+
export const hash = (value: string | Buffer) => createHash('sha256').update(value).digest('hex');
|
|
6
|
+
|
|
7
|
+
export function within(root: string, file: string): boolean {
|
|
8
|
+
const rel = relative(root, file);
|
|
9
|
+
return rel === '' || (!isAbsolute(rel) && rel !== '..' && !rel.startsWith(`..${sep}`));
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export async function canonical(file: string): Promise<string> {
|
|
13
|
+
try {
|
|
14
|
+
return await realpath(file);
|
|
15
|
+
} catch (error: any) {
|
|
16
|
+
if (error.code !== 'ENOENT') throw error;
|
|
17
|
+
const parent = dirname(file);
|
|
18
|
+
if (parent === file) return file;
|
|
19
|
+
return resolve(await canonical(parent), relative(parent, file));
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export async function atomicWrite(file: string, contents: string | Buffer): Promise<void> {
|
|
24
|
+
await mkdir(dirname(file), { recursive: true });
|
|
25
|
+
const temp = `${file}.${randomUUID()}.tmp`;
|
|
26
|
+
let mode = 0o600;
|
|
27
|
+
try {
|
|
28
|
+
mode = (await stat(file)).mode & 0o777;
|
|
29
|
+
} catch (error: any) {
|
|
30
|
+
if (error.code !== 'ENOENT') throw error;
|
|
31
|
+
}
|
|
32
|
+
try {
|
|
33
|
+
await writeFile(temp, contents, { mode, flag: 'wx' });
|
|
34
|
+
await rename(temp, file);
|
|
35
|
+
} finally {
|
|
36
|
+
await rm(temp, { force: true });
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export async function optionalText(file: string): Promise<string | undefined> {
|
|
41
|
+
try {
|
|
42
|
+
return await readFile(file, 'utf8');
|
|
43
|
+
} catch (error: any) {
|
|
44
|
+
if (error.code === 'ENOENT') return;
|
|
45
|
+
throw error;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export const textResult = (text: string, details: Record<string, unknown> = {}) => ({
|
|
50
|
+
content: [{ type: 'text' as const, text }],
|
|
51
|
+
details,
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
export function humanReadable(value: unknown, indent = ''): string {
|
|
55
|
+
if (value === null || value === undefined) return 'None';
|
|
56
|
+
if (typeof value === 'boolean') return value ? 'Yes' : 'No';
|
|
57
|
+
if (typeof value !== 'object') return String(value);
|
|
58
|
+
const entries = Array.isArray(value)
|
|
59
|
+
? value.map((item, index) => [String(index + 1), item] as const)
|
|
60
|
+
: Object.entries(value);
|
|
61
|
+
if (!entries.length) return 'None';
|
|
62
|
+
return entries
|
|
63
|
+
.map(([key, item]) => {
|
|
64
|
+
const label = key.replace(/([a-z])([A-Z])/g, '$1 $2').replace(/_/g, ' ');
|
|
65
|
+
return item !== null && typeof item === 'object'
|
|
66
|
+
? `${indent}${label}:\n${humanReadable(item, indent + ' ')}`
|
|
67
|
+
: `${indent}${label}: ${humanReadable(item)}`;
|
|
68
|
+
})
|
|
69
|
+
.join('\n');
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export function agentSummary(report: {
|
|
73
|
+
id?: string;
|
|
74
|
+
role?: string;
|
|
75
|
+
status: string;
|
|
76
|
+
turns?: number;
|
|
77
|
+
output?: string;
|
|
78
|
+
error?: string;
|
|
79
|
+
}): string {
|
|
80
|
+
return [
|
|
81
|
+
`${report.role ?? 'Subagent'} — ${report.status.replace(/_/g, ' ')}`,
|
|
82
|
+
report.id ? `Agent ID: ${report.id}` : '',
|
|
83
|
+
report.turns !== undefined ? `Turns: ${report.turns}` : '',
|
|
84
|
+
report.error ? `Error: ${report.error}` : '',
|
|
85
|
+
report.output || '',
|
|
86
|
+
]
|
|
87
|
+
.filter(Boolean)
|
|
88
|
+
.join('\n');
|
|
89
|
+
}
|
package/package.json
CHANGED
|
@@ -1,5 +1,42 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@pi-kode/permissions",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"pi-package"
|
|
7
|
+
],
|
|
8
|
+
"description": "Standalone pi governance extension: permissions, planning mode, hooks, and subagents",
|
|
9
|
+
"files": [
|
|
10
|
+
"index.ts",
|
|
11
|
+
"lib",
|
|
12
|
+
"tests",
|
|
13
|
+
"tsconfig.json"
|
|
14
|
+
],
|
|
15
|
+
"pi": {
|
|
16
|
+
"extensions": [
|
|
17
|
+
"./index.ts"
|
|
18
|
+
]
|
|
19
|
+
},
|
|
20
|
+
"peerDependencies": {
|
|
21
|
+
"@earendil-works/pi-coding-agent": "1.5.2",
|
|
22
|
+
"typebox": "1.3.27"
|
|
23
|
+
},
|
|
24
|
+
"scripts": {
|
|
25
|
+
"test": "node --experimental-strip-types --test tests/*.test.ts",
|
|
26
|
+
"typecheck": "tsc --noEmit",
|
|
27
|
+
"prepublishOnly": "npm test && npm run typecheck"
|
|
28
|
+
},
|
|
29
|
+
"devDependencies": {
|
|
30
|
+
"@types/node": "22.19.19",
|
|
31
|
+
"typescript": "5.9.3"
|
|
32
|
+
},
|
|
33
|
+
"repository": {
|
|
34
|
+
"type": "git",
|
|
35
|
+
"url": "git+https://github.com/pi-kode/permissions.git"
|
|
36
|
+
},
|
|
37
|
+
"homepage": "https://github.com/pi-kode/permissions#readme",
|
|
38
|
+
"bugs": "https://github.com/pi-kode/permissions/issues",
|
|
39
|
+
"publishConfig": {
|
|
40
|
+
"access": "public"
|
|
41
|
+
}
|
|
5
42
|
}
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import { test } from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import { installGovernance } from '../lib/src/features/permissions.ts';
|
|
4
|
+
import { harness } from './helper.ts';
|
|
5
|
+
|
|
6
|
+
test('separate child sessions, bounded concurrency, sibling failures retained and cleanup', async t => {
|
|
7
|
+
let active = 0;
|
|
8
|
+
let peak = 0;
|
|
9
|
+
let disposed = 0;
|
|
10
|
+
const create: any = async (options: any) => {
|
|
11
|
+
assert.ok(options.tools.includes('read'));
|
|
12
|
+
assert.ok(!options.tools.includes('Agent'));
|
|
13
|
+
const session: any = {
|
|
14
|
+
messages: [],
|
|
15
|
+
bindExtensions: async () => {},
|
|
16
|
+
subscribe: () => () => {},
|
|
17
|
+
abort: async () => {},
|
|
18
|
+
dispose: () => disposed++,
|
|
19
|
+
prompt: async (prompt: string) => {
|
|
20
|
+
active++;
|
|
21
|
+
peak = Math.max(peak, active);
|
|
22
|
+
try {
|
|
23
|
+
await new Promise(r => setTimeout(r, 10));
|
|
24
|
+
if (prompt === 'fail') throw Error('child failure');
|
|
25
|
+
session.messages = [{ role: 'assistant', content: [{ type: 'text', text: prompt }], stopReason: 'stop' }];
|
|
26
|
+
} finally {
|
|
27
|
+
active--;
|
|
28
|
+
}
|
|
29
|
+
},
|
|
30
|
+
};
|
|
31
|
+
return { session };
|
|
32
|
+
};
|
|
33
|
+
const h = await harness(pi => installGovernance(pi, create));
|
|
34
|
+
t.after(() => h.close());
|
|
35
|
+
const result = await h.call('AgentBatch', {
|
|
36
|
+
agents: Array.from({ length: 8 }, (_, i) => ({
|
|
37
|
+
prompt: i === 3 ? 'fail' : 'child ' + i,
|
|
38
|
+
subagent_type: 'Explore',
|
|
39
|
+
})),
|
|
40
|
+
});
|
|
41
|
+
assert.equal(result.details.reports.length, 8);
|
|
42
|
+
assert.equal(result.details.reports.filter((r: any) => r.status === 'failed').length, 1);
|
|
43
|
+
assert.ok(peak <= 4);
|
|
44
|
+
assert.equal(disposed, 8);
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
test('Explore child receives read-only tools and cancellation releases its session', async t => {
|
|
48
|
+
let disposed = false;
|
|
49
|
+
const create: any = async (options: any) => {
|
|
50
|
+
assert.ok(!options.tools.includes('bash'));
|
|
51
|
+
return {
|
|
52
|
+
session: {
|
|
53
|
+
messages: [],
|
|
54
|
+
bindExtensions: async () => {},
|
|
55
|
+
subscribe: () => () => {},
|
|
56
|
+
prompt: async () => {},
|
|
57
|
+
abort: async () => {},
|
|
58
|
+
dispose: () => {
|
|
59
|
+
disposed = true;
|
|
60
|
+
},
|
|
61
|
+
},
|
|
62
|
+
};
|
|
63
|
+
};
|
|
64
|
+
const h = await harness(pi => installGovernance(pi, create));
|
|
65
|
+
t.after(() => h.close());
|
|
66
|
+
await h.call('Agent', { prompt: 'inspect', subagent_type: 'Explore' });
|
|
67
|
+
assert.equal(disposed, true);
|
|
68
|
+
const controller = new AbortController();
|
|
69
|
+
controller.abort();
|
|
70
|
+
await assert.rejects(h.call('Agent', { prompt: 'inspect' }, controller.signal));
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
test('real SDK child binds policy extension and denies forbidden child tool calls', async t => {
|
|
74
|
+
const { createAgentSession } = await import('@earendil-works/pi-coding-agent');
|
|
75
|
+
let blocked = false;
|
|
76
|
+
const create: any = async (options: any) => {
|
|
77
|
+
const extension = options.resourceLoader.getExtensions().extensions[0];
|
|
78
|
+
const gate = extension.handlers.get('tool_call')[0];
|
|
79
|
+
blocked = (await gate({ toolName: 'bash', input: { command: 'echo forbidden' } }))?.block === true;
|
|
80
|
+
const result = await createAgentSession(options);
|
|
81
|
+
result.session.prompt = async () => {};
|
|
82
|
+
return result;
|
|
83
|
+
};
|
|
84
|
+
const h = await harness(pi => installGovernance(pi, create));
|
|
85
|
+
t.after(() => h.close());
|
|
86
|
+
h.ctx.model = {
|
|
87
|
+
id: 'offline-test',
|
|
88
|
+
name: 'Offline test',
|
|
89
|
+
provider: 'anthropic',
|
|
90
|
+
api: 'anthropic-messages',
|
|
91
|
+
baseUrl: 'https://api.anthropic.com',
|
|
92
|
+
reasoning: false,
|
|
93
|
+
input: ['text'],
|
|
94
|
+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
|
95
|
+
contextWindow: 200000,
|
|
96
|
+
maxTokens: 8192,
|
|
97
|
+
};
|
|
98
|
+
await h.call('Agent', { prompt: 'inspect', subagent_type: 'Explore' });
|
|
99
|
+
assert.equal(blocked, true);
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
test('saved child ID resumes its session and cannot change role', async t => {
|
|
103
|
+
let invocations = 0;
|
|
104
|
+
const create: any = async (options: any) => {
|
|
105
|
+
if (invocations++) {
|
|
106
|
+
assert.ok(options.sessionManager.getEntries().some((e: any) => e.type === 'message' && e.message.role === 'user'));
|
|
107
|
+
}
|
|
108
|
+
const session: any = {
|
|
109
|
+
messages: [],
|
|
110
|
+
bindExtensions: async () => {},
|
|
111
|
+
subscribe: () => () => {},
|
|
112
|
+
abort: async () => {},
|
|
113
|
+
dispose: () => {},
|
|
114
|
+
prompt: async (prompt: string) => {
|
|
115
|
+
options.sessionManager.appendMessage({ role: 'user', content: prompt, timestamp: Date.now() });
|
|
116
|
+
session.messages = [{ role: 'assistant', content: [{ type: 'text', text: 'done' }], stopReason: 'stop' }];
|
|
117
|
+
},
|
|
118
|
+
};
|
|
119
|
+
return { session };
|
|
120
|
+
};
|
|
121
|
+
const h = await harness(pi => installGovernance(pi, create));
|
|
122
|
+
t.after(() => h.close());
|
|
123
|
+
const first = await h.call('Agent', { prompt: 'inspect', subagent_type: 'Explore' });
|
|
124
|
+
const next = await h.call('Agent', { prompt: 'continue', resume: first.details.id });
|
|
125
|
+
assert.equal(next.details.id, first.details.id);
|
|
126
|
+
await assert.rejects(
|
|
127
|
+
h.call('Agent', { prompt: 'change role', resume: first.details.id, subagent_type: 'general-purpose' }),
|
|
128
|
+
/original role/,
|
|
129
|
+
);
|
|
130
|
+
});
|
package/tests/helper.ts
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { mkdtemp, rm } from 'node:fs/promises';
|
|
2
|
+
import { tmpdir } from 'node:os';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import type { ExtensionAPI } from '@earendil-works/pi-coding-agent';
|
|
5
|
+
|
|
6
|
+
export async function harness(install: (pi: ExtensionAPI) => void) {
|
|
7
|
+
const root = await mkdtemp(join(tmpdir(), 'pi-feature-'));
|
|
8
|
+
const handlers = new Map<string, any[]>();
|
|
9
|
+
const tools = new Map<string, any>();
|
|
10
|
+
const commands = new Map<string, any>();
|
|
11
|
+
const listeners = new Map<string, any[]>();
|
|
12
|
+
const entries: any[] = [];
|
|
13
|
+
const answers: any[] = [];
|
|
14
|
+
const pi: any = {
|
|
15
|
+
events: {
|
|
16
|
+
emit: (name: string, data: any) => {
|
|
17
|
+
for (const fn of listeners.get(name) ?? []) fn(data);
|
|
18
|
+
},
|
|
19
|
+
on: (name: string, fn: any) => {
|
|
20
|
+
listeners.set(name, [...(listeners.get(name) ?? []), fn]);
|
|
21
|
+
return () => {};
|
|
22
|
+
},
|
|
23
|
+
},
|
|
24
|
+
on: (name: string, fn: any) => {
|
|
25
|
+
handlers.set(name, [...(handlers.get(name) ?? []), fn]);
|
|
26
|
+
return () => {};
|
|
27
|
+
},
|
|
28
|
+
registerTool: (tool: any) => tools.set(tool.name, tool),
|
|
29
|
+
registerCommand: (name: string, value: any) => commands.set(name, value),
|
|
30
|
+
appendEntry: (customType: string, data: any) =>
|
|
31
|
+
entries.push({ type: 'custom', customType, data: structuredClone(data) }),
|
|
32
|
+
sendMessage: () => {},
|
|
33
|
+
getActiveTools: () => ['read', 'bash'],
|
|
34
|
+
getAllTools: () => [],
|
|
35
|
+
};
|
|
36
|
+
install(pi);
|
|
37
|
+
let runtime: any;
|
|
38
|
+
pi.events.emit('pi-ko:governance:v1', { accept: (s: any) => (runtime = s) });
|
|
39
|
+
const ctx: any = {
|
|
40
|
+
model: { provider: 'mock', id: 'mock' },
|
|
41
|
+
cwd: root,
|
|
42
|
+
hasUI: true,
|
|
43
|
+
mode: 'tui',
|
|
44
|
+
isProjectTrusted: () => true,
|
|
45
|
+
getSystemPrompt: () => 'Test assistant',
|
|
46
|
+
sessionManager: { getBranch: () => entries, getSessionId: () => 'test' },
|
|
47
|
+
ui: { select: async () => answers.shift() ?? 'Allow once', setStatus: () => {}, notify: () => {} },
|
|
48
|
+
};
|
|
49
|
+
runtime.store = join(root, '.runtime');
|
|
50
|
+
runtime.cwd = root;
|
|
51
|
+
runtime.ready = true;
|
|
52
|
+
runtime.reload = async () => {
|
|
53
|
+
runtime.config = { permissions: { allow: [], deny: [], ask: [] }, hooks: {}, provenance: {}, diagnostics: [] };
|
|
54
|
+
};
|
|
55
|
+
await runtime.reload();
|
|
56
|
+
runtime.start = async () => {
|
|
57
|
+
runtime.ready = true;
|
|
58
|
+
};
|
|
59
|
+
return {
|
|
60
|
+
root,
|
|
61
|
+
tools,
|
|
62
|
+
commands,
|
|
63
|
+
runtime,
|
|
64
|
+
ctx,
|
|
65
|
+
entries,
|
|
66
|
+
handlers,
|
|
67
|
+
answers,
|
|
68
|
+
pi,
|
|
69
|
+
call: (name: string, input: any, signal?: AbortSignal) => tools.get(name).execute('call', input, signal, undefined, ctx),
|
|
70
|
+
async emit(name: string, event: any = {}) {
|
|
71
|
+
const results = [];
|
|
72
|
+
for (const fn of handlers.get(name) ?? []) results.push(await fn(event, ctx));
|
|
73
|
+
return results;
|
|
74
|
+
},
|
|
75
|
+
async close() {
|
|
76
|
+
for (const fn of handlers.get('session_shutdown') ?? []) await fn({ reason: 'quit' }, ctx);
|
|
77
|
+
await rm(root, { recursive: true, force: true });
|
|
78
|
+
},
|
|
79
|
+
};
|
|
80
|
+
}
|