pi-code-core 0.0.0-stage → 0.5.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.
Files changed (46) hide show
  1. package/README.md +21 -2
  2. package/dist/backends/process.d.ts +19 -0
  3. package/dist/backends/process.js +79 -0
  4. package/dist/extensions/checkpoints.d.ts +3 -0
  5. package/dist/extensions/checkpoints.js +34 -0
  6. package/dist/extensions/hooks.d.ts +7 -0
  7. package/dist/extensions/hooks.js +83 -0
  8. package/dist/extensions/memory.d.ts +17 -0
  9. package/dist/extensions/memory.js +131 -0
  10. package/dist/extensions/permissions.d.ts +8 -0
  11. package/dist/extensions/permissions.js +130 -0
  12. package/dist/extensions/prompts.d.ts +17 -0
  13. package/dist/extensions/prompts.js +58 -0
  14. package/dist/features/shared.d.ts +10 -0
  15. package/dist/features/shared.js +33 -0
  16. package/dist/runtime/approvals.d.ts +5 -0
  17. package/dist/runtime/approvals.js +14 -0
  18. package/dist/runtime/capabilities.d.ts +18 -0
  19. package/dist/runtime/capabilities.js +3 -0
  20. package/dist/runtime/config.d.ts +22 -0
  21. package/dist/runtime/config.js +62 -0
  22. package/dist/runtime/events.d.ts +7 -0
  23. package/dist/runtime/events.js +1 -0
  24. package/dist/runtime/runtime.d.ts +35 -0
  25. package/dist/runtime/runtime.js +154 -0
  26. package/dist/runtime/scheduler.d.ts +7 -0
  27. package/dist/runtime/scheduler.js +35 -0
  28. package/dist/runtime/schema.d.ts +2 -0
  29. package/dist/runtime/schema.js +2 -0
  30. package/dist/runtime/state.d.ts +32 -0
  31. package/dist/runtime/state.js +8 -0
  32. package/dist/runtime/utils.d.ts +13 -0
  33. package/dist/runtime/utils.js +52 -0
  34. package/lib/profiles/claude-code-2.1.310.json +28 -0
  35. package/lib/prompts/NOTICE.md +9 -0
  36. package/lib/prompts/manifest.json +65 -0
  37. package/lib/prompts/original/agent-prompt-conversation-summarization.md +22 -0
  38. package/lib/prompts/original/agent-prompt-explore.md +45 -0
  39. package/lib/prompts/original/agent-prompt-plan-mode-enhanced.md +76 -0
  40. package/lib/prompts/original/system-prompt-system-section.md +6 -0
  41. package/lib/prompts/original/system-reminder-plan-mode-is-active-5-phase.md +18 -0
  42. package/lib/prompts/original/tool-description-edit.md +16 -0
  43. package/lib/prompts/original/tool-description-exitplanmode.md +30 -0
  44. package/lib/prompts/original/tool-description-readfile.md +26 -0
  45. package/lib/prompts/source-tree.json +1 -0
  46. package/package.json +101 -4
package/README.md CHANGED
@@ -1,3 +1,22 @@
1
- # Temporary Holding Version
1
+ # pi-code-core
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Shared library for the independently installable pi extensions. This is a dependency, not a pi extension: it has no `pi.extensions` entry.
4
+
5
+ Build with `npm run build`. `npm pack` and `npm publish` build automatically. The package contains compiled JavaScript, TypeScript declarations, and the single shared prompt/profile asset collection.
6
+
7
+ The root export provides `acquire(pi, feature)` and `shared(pi)`. These coordinate one runtime through pi's session event bus, including when multiple physical copies of this library are installed. Internal helpers have explicit package exports grouped under `runtime`, `extensions`, and `backends`; their contracts are versioned with core. Extensions pin the same exact core version.
8
+
9
+ Prompt assets retain their provenance in `lib/prompts/NOTICE.md`. Existing compatibility/session identifiers are intentionally retained to preserve user data.
10
+
11
+ ## Multi-repository workspace
12
+
13
+ The `workspace/` directory preserves the development workspace manifest, documentation, and cross-extension tests. With all package repositories checked out as siblings and this repository named `core`, restore the workspace files from the parent directory:
14
+
15
+ ```sh
16
+ cp -R core/workspace/. .
17
+ npm install
18
+ npm test
19
+ npm run typecheck
20
+ ```
21
+
22
+ These workspace files are not shipped in the npm library.
@@ -0,0 +1,19 @@
1
+ export interface ProcessResult {
2
+ output: string;
3
+ stdout: string;
4
+ stderr: string;
5
+ exitCode: number | null;
6
+ cancelled: boolean;
7
+ timedOut: boolean;
8
+ truncated: boolean;
9
+ outputPath?: string;
10
+ }
11
+ export declare function runProcess(command: string, args: string[], options: {
12
+ cwd: string;
13
+ signal?: AbortSignal;
14
+ timeout?: number;
15
+ input?: string;
16
+ outputPath?: string;
17
+ maxBytes?: number;
18
+ env?: NodeJS.ProcessEnv;
19
+ }): Promise<ProcessResult>;
@@ -0,0 +1,79 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { mkdir, open } from 'node:fs/promises';
3
+ import { dirname } from 'node:path';
4
+ export async function runProcess(command, args, options) {
5
+ options.signal?.throwIfAborted();
6
+ const maxBytes = options.maxBytes ?? 64_000;
7
+ let sink;
8
+ if (options.outputPath) {
9
+ await mkdir(dirname(options.outputPath), { recursive: true });
10
+ sink = await open(options.outputPath, 'wx', 0o600);
11
+ }
12
+ try {
13
+ return await new Promise((resolve, reject) => {
14
+ options.signal?.throwIfAborted();
15
+ const child = spawn(command, args, { cwd: options.cwd, env: options.env ?? process.env, detached: true, stdio: ['pipe', 'pipe', 'pipe'] });
16
+ let stdout = Buffer.alloc(0), stderr = Buffer.alloc(0);
17
+ let output = Buffer.alloc(0), size = 0, diskSize = 0, timedOut = false, cancelled = false, settled = false;
18
+ let diskWrites = Promise.resolve();
19
+ let killTimer;
20
+ const stop = () => {
21
+ try {
22
+ process.kill(-child.pid, 'SIGTERM');
23
+ }
24
+ catch { }
25
+ killTimer ??= setTimeout(() => { try {
26
+ process.kill(-child.pid, 'SIGKILL');
27
+ }
28
+ catch { } }, 250);
29
+ };
30
+ const onAbort = () => { cancelled = true; stop(); };
31
+ const timer = setTimeout(() => { timedOut = true; stop(); }, options.timeout ?? 120_000);
32
+ options.signal?.addEventListener('abort', onAbort, { once: true });
33
+ const cleanup = () => { clearTimeout(timer); options.signal?.removeEventListener('abort', onAbort); };
34
+ const receive = (chunk, stream) => {
35
+ if (stream === 'stdout' && stdout.length < maxBytes)
36
+ stdout = Buffer.concat([stdout, chunk.subarray(0, maxBytes - stdout.length)]);
37
+ if (stream === 'stderr' && stderr.length < maxBytes)
38
+ stderr = Buffer.concat([stderr, chunk.subarray(0, maxBytes - stderr.length)]);
39
+ size += chunk.length;
40
+ if (output.length < maxBytes)
41
+ output = Buffer.concat([output, chunk.subarray(0, maxBytes - output.length)]);
42
+ // Keep disk use bounded, including for hostile/unbounded output.
43
+ if (sink && diskSize < 16_000_000) {
44
+ const bytes = chunk.subarray(0, 16_000_000 - diskSize);
45
+ diskSize += bytes.length;
46
+ diskWrites = diskWrites.then(async () => { await sink.write(bytes); });
47
+ diskWrites.catch(() => stop());
48
+ }
49
+ if (size > 16_000_000)
50
+ stop();
51
+ };
52
+ child.stdout.on('data', chunk => receive(chunk, 'stdout'));
53
+ child.stderr.on('data', chunk => receive(chunk, 'stderr'));
54
+ child.stdin.on('error', () => { });
55
+ child.stdin.end(options.input);
56
+ child.on('error', error => { if (settled)
57
+ return; settled = true; cleanup(); reject(error); });
58
+ child.on('close', async (code) => {
59
+ if (settled)
60
+ return;
61
+ settled = true;
62
+ cleanup();
63
+ // Kill remaining descendants even if the shell exited before them.
64
+ if (timedOut || cancelled)
65
+ stop();
66
+ try {
67
+ await diskWrites;
68
+ resolve({ output: output.toString('utf8'), stdout: stdout.toString('utf8'), stderr: stderr.toString('utf8'), exitCode: code, timedOut, cancelled, truncated: size > maxBytes, outputPath: options.outputPath });
69
+ }
70
+ catch (error) {
71
+ reject(error);
72
+ }
73
+ });
74
+ });
75
+ }
76
+ finally {
77
+ await sink?.close();
78
+ }
79
+ }
@@ -0,0 +1,3 @@
1
+ import type { Runtime } from '../runtime/runtime.ts';
2
+ export declare function trackedWrite(runtime: Runtime, path: string, content: string): Promise<void>;
3
+ export declare function rewindFile(runtime: Runtime): Promise<string>;
@@ -0,0 +1,34 @@
1
+ import { readFile, rm } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+ import { atomicWrite, hash, optionalText } from "../runtime/utils.js";
4
+ export async function trackedWrite(runtime, path, content) {
5
+ const before = await optionalText(path);
6
+ const digest = before === undefined ? null : hash(before);
7
+ const after = hash(content);
8
+ if (before !== undefined)
9
+ await atomicWrite(join(runtime.store, 'blobs', digest), before);
10
+ await atomicWrite(path, content);
11
+ runtime.state.checkpoints.push({ path, before: digest, after });
12
+ runtime.persist();
13
+ runtime.readVersions.set(path, after);
14
+ }
15
+ export async function rewindFile(runtime) {
16
+ const checkpoint = runtime.state.checkpoints.at(-1);
17
+ if (!checkpoint)
18
+ throw new Error('No file checkpoint to rewind');
19
+ const current = await optionalText(checkpoint.path);
20
+ if (current === undefined || hash(current) !== checkpoint.after)
21
+ throw new Error('Rewind conflict: file changed outside the tracked edit');
22
+ if (checkpoint.before === null)
23
+ await rm(checkpoint.path);
24
+ else {
25
+ const bytes = await readFile(join(runtime.store, 'blobs', checkpoint.before));
26
+ if (hash(bytes) !== checkpoint.before)
27
+ throw new Error('Checkpoint integrity failure');
28
+ await atomicWrite(checkpoint.path, bytes);
29
+ }
30
+ runtime.state.checkpoints.pop();
31
+ runtime.readVersions.delete(checkpoint.path);
32
+ runtime.persist();
33
+ return `Restored ${checkpoint.path}. Shell and external edits are not tracked.`;
34
+ }
@@ -0,0 +1,7 @@
1
+ import type { Runtime } from '../runtime/runtime.ts';
2
+ import type { CompatEvent, HookOutcome } from '../runtime/events.ts';
3
+ import type { Settings } from '../runtime/config.ts';
4
+ export declare class Hooks {
5
+ run(event: CompatEvent, payload: Record<string, unknown>, config: Settings, cwd: string, signal?: AbortSignal): Promise<HookOutcome>;
6
+ }
7
+ export declare function registerStopHook(runtime: Runtime): void;
@@ -0,0 +1,83 @@
1
+ import { runProcess } from "../backends/process.js";
2
+ export class Hooks {
3
+ async run(event, payload, config, cwd, signal) {
4
+ const outcome = { context: [] };
5
+ for (const group of config.hooks[event] ?? []) {
6
+ if (!group || !Array.isArray(group.hooks))
7
+ throw new Error(`Invalid ${event} hook group`);
8
+ if (group.matcher && group.matcher !== '*') {
9
+ // Exact-name alternatives only. Reject regex features instead of misinterpreting them.
10
+ const names = group.matcher.split('|');
11
+ if (names.some(x => !/^[\w]+$/.test(x)))
12
+ throw new Error(`Unsupported hook matcher: ${group.matcher}`);
13
+ if (!names.includes(String(payload.tool_name ?? '')))
14
+ continue;
15
+ }
16
+ for (const hook of group.hooks) {
17
+ if (hook.type !== 'command' || !hook.command)
18
+ throw new Error(`Unsupported ${event} hook type: ${hook.type}`);
19
+ const result = await runProcess('/bin/sh', ['-c', hook.command], {
20
+ cwd, signal, timeout: Math.min(Math.max((hook.timeout ?? 30) * 1000, 1), 120_000),
21
+ input: JSON.stringify({ ...payload, hook_event_name: event, cwd }) + '\n',
22
+ env: { ...process.env, CLAUDE_PROJECT_DIR: cwd },
23
+ });
24
+ if (result.timedOut || result.cancelled || result.truncated)
25
+ throw new Error(`${event} hook timed out, was cancelled, or exceeded output limit`);
26
+ if (result.exitCode === 2) {
27
+ outcome.deny = (result.stderr || result.stdout).trim() || `${event} hook blocked the operation`;
28
+ continue;
29
+ }
30
+ if (result.exitCode !== 0)
31
+ throw new Error(`${event} hook failed (${result.exitCode}): ${result.output}`);
32
+ if (!result.stdout.trim())
33
+ continue;
34
+ let json;
35
+ try {
36
+ json = JSON.parse(result.stdout);
37
+ }
38
+ catch {
39
+ if (/^\s*[\[{]/.test(result.stdout))
40
+ throw new Error(`Invalid ${event} hook JSON`);
41
+ outcome.context.push(result.stdout);
42
+ continue;
43
+ }
44
+ if (!json || typeof json !== 'object' || Array.isArray(json))
45
+ throw new Error(`Invalid ${event} hook response`);
46
+ if (['PreToolUse', 'PermissionRequest'].includes(event) && json.decision === 'block')
47
+ outcome.deny = json.reason ?? 'Hook blocked the operation';
48
+ if (json.continue === false)
49
+ outcome.deny = json.stopReason ?? 'Hook requested stop';
50
+ const specific = json.hookSpecificOutput;
51
+ if (specific?.hookEventName && specific.hookEventName !== event)
52
+ throw new Error('Hook response event mismatch');
53
+ if (specific?.permissionDecision === 'deny')
54
+ outcome.deny = specific.permissionDecisionReason ?? 'Hook denied operation';
55
+ // Hook allow never overrides policy. Input is validated and policy is recomputed by dispatch.
56
+ if (specific?.updatedInput) {
57
+ if (typeof specific.updatedInput !== 'object' || Array.isArray(specific.updatedInput))
58
+ throw new Error('Invalid hook updatedInput');
59
+ outcome.updatedInput = specific.updatedInput;
60
+ payload.tool_input = specific.updatedInput;
61
+ }
62
+ if (specific?.additionalContext)
63
+ outcome.context.push(String(specific.additionalContext));
64
+ if (event === 'Stop' && json.decision === 'block')
65
+ outcome.continueReason = json.reason ?? 'Continue working.';
66
+ }
67
+ }
68
+ return outcome;
69
+ }
70
+ }
71
+ export function registerStopHook(runtime) {
72
+ let stopActive = false;
73
+ runtime.pi.on('agent_before_settle', async (_event, ctx) => {
74
+ if (!runtime.ready)
75
+ return;
76
+ const result = await runtime.hooks.run('Stop', { stop_hook_active: stopActive }, runtime.config, ctx.cwd, ctx.signal);
77
+ if ((result.continueReason || result.deny) && !stopActive) {
78
+ stopActive = true;
79
+ return { continue: true, entries: [{ type: 'custom_message', customType: 'claude-compat:stop', content: result.continueReason ?? result.deny, display: false }] };
80
+ }
81
+ });
82
+ runtime.pi.on('agent_settled', () => { stopActive = false; });
83
+ }
@@ -0,0 +1,17 @@
1
+ export interface MemorySource {
2
+ path: string;
3
+ text: string;
4
+ importedBy?: string;
5
+ scope?: string[];
6
+ }
7
+ export declare class Memory {
8
+ sources: MemorySource[];
9
+ diagnostics: string[];
10
+ private cwd;
11
+ private seen;
12
+ load(cwd: string, home?: string): Promise<void>;
13
+ descendant(file: string): Promise<MemorySource[]>;
14
+ private rules;
15
+ private add;
16
+ format(sources?: MemorySource[]): string;
17
+ }
@@ -0,0 +1,131 @@
1
+ import { readdir } from 'node:fs/promises';
2
+ import { dirname, join, resolve, matchesGlob } from 'node:path';
3
+ import { homedir } from 'node:os';
4
+ import { canonical, optionalText, within } from "../runtime/utils.js";
5
+ export class Memory {
6
+ sources = [];
7
+ diagnostics = [];
8
+ cwd = '';
9
+ seen = new Set();
10
+ async load(cwd, home = homedir()) {
11
+ this.cwd = await canonical(cwd);
12
+ this.sources = [];
13
+ this.diagnostics = [];
14
+ this.seen.clear();
15
+ await this.add(join(home, '.claude/CLAUDE.md'));
16
+ const ancestors = [];
17
+ let dir = this.cwd;
18
+ while (true) {
19
+ ancestors.unshift(dir);
20
+ const parent = dirname(dir);
21
+ if (parent === dir)
22
+ break;
23
+ dir = parent;
24
+ }
25
+ for (const root of ancestors) {
26
+ for (const file of ['CLAUDE.md', '.claude/CLAUDE.md', 'CLAUDE.local.md'])
27
+ await this.add(join(root, file));
28
+ }
29
+ await this.rules(join(this.cwd, '.claude/rules'));
30
+ }
31
+ async descendant(file) {
32
+ file = await canonical(file);
33
+ const start = this.sources.length;
34
+ if (!within(this.cwd, file))
35
+ return [];
36
+ const dirs = [];
37
+ let dir = dirname(file);
38
+ while (within(this.cwd, dir) && dir !== this.cwd) {
39
+ dirs.unshift(dir);
40
+ dir = dirname(dir);
41
+ }
42
+ for (const root of dirs)
43
+ for (const name of ['CLAUDE.md', '.claude/CLAUDE.md'])
44
+ await this.add(join(root, name));
45
+ await this.rules(join(this.cwd, '.claude/rules'), file);
46
+ return this.sources.filter((source, index) => source.scope ? source.scope.some(p => matchesGlob(file.slice(this.cwd.length + 1), p)) : index >= start);
47
+ }
48
+ async rules(root, target) {
49
+ let entries;
50
+ try {
51
+ entries = await readdir(root, { withFileTypes: true });
52
+ }
53
+ catch (e) {
54
+ if (e.code === 'ENOENT')
55
+ return;
56
+ throw e;
57
+ }
58
+ for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
59
+ if (entry.isDirectory()) {
60
+ await this.rules(join(root, entry.name), target);
61
+ continue;
62
+ }
63
+ if (!entry.name.endsWith('.md') || entry.isSymbolicLink())
64
+ continue;
65
+ const file = join(root, entry.name), text = (await optionalText(file));
66
+ if (/^---\r?\n/.test(text)) {
67
+ // A deliberately bounded frontmatter subset; unsupported selectors never become global.
68
+ const normalized = text.replace(/\r\n/g, '\n');
69
+ const match = /^---\npaths:\s*\n((?:\s+-\s+[^\n]+\n)+)---\n/.exec(normalized);
70
+ if (!match) {
71
+ this.diagnostics.push(`Unsupported rule frontmatter: ${file}`);
72
+ continue;
73
+ }
74
+ const patterns = [...match[1].matchAll(/-\s+["']?([^\n"']+)["']?/g)].map(m => m[1].trim());
75
+ if (!target || !patterns.some(p => matchesGlob(target.slice(this.cwd.length + 1), p)))
76
+ continue;
77
+ const importedStart = this.sources.length;
78
+ await this.add(file, undefined, 0, normalized.slice(match[0].length));
79
+ for (const imported of this.sources.slice(importedStart))
80
+ imported.scope = patterns;
81
+ const rulePath = await canonical(file);
82
+ const source = this.sources.find(s => s.path === rulePath);
83
+ if (source)
84
+ source.scope = patterns;
85
+ }
86
+ else
87
+ await this.add(file);
88
+ }
89
+ }
90
+ async add(file, importedBy, depth = 0, override) {
91
+ if (depth > 5) {
92
+ this.diagnostics.push(`Memory import depth exceeded: ${file}`);
93
+ return;
94
+ }
95
+ const path = await canonical(resolve(file));
96
+ if (this.seen.has(path))
97
+ return;
98
+ const text = override ?? await optionalText(path);
99
+ if (text === undefined)
100
+ return;
101
+ if (Buffer.byteLength(text) > 200_000) {
102
+ this.diagnostics.push(`Memory file exceeds 200 KB: ${path}`);
103
+ return;
104
+ }
105
+ this.seen.add(path);
106
+ this.sources.push({ path, text, importedBy });
107
+ let fence;
108
+ for (const line of text.split('\n')) {
109
+ const mark = /^\s*(`{3,}|~{3,})/.exec(line)?.[1];
110
+ if (mark) {
111
+ if (!fence)
112
+ fence = mark[0];
113
+ else if (fence === mark[0])
114
+ fence = undefined;
115
+ continue;
116
+ }
117
+ if (fence)
118
+ continue;
119
+ for (const match of line.matchAll(/(?:^|\s)@([^\s`]+)/g)) {
120
+ const target = await canonical(resolve(dirname(path), match[1]));
121
+ // External imports need an approval UX not yet provided. Fail closed instead of silently trusting them.
122
+ if (!within(this.cwd, target)) {
123
+ this.diagnostics.push(`External memory import skipped: ${target}`);
124
+ continue;
125
+ }
126
+ await this.add(target, path, depth + 1);
127
+ }
128
+ }
129
+ }
130
+ format(sources = this.sources.filter(s => !s.scope)) { return sources.map(s => `<project-instructions source=${JSON.stringify(s.path)}>\n${s.text}\n</project-instructions>`).join('\n\n'); }
131
+ }
@@ -0,0 +1,8 @@
1
+ import type { Settings, Mode } from '../runtime/config.ts';
2
+ export interface Decision {
3
+ action: 'allow' | 'ask' | 'deny';
4
+ reason: string;
5
+ }
6
+ export declare function decide(name: string, input: Record<string, any>, mode: Mode, config: Settings, cwd: string, planPath?: string): Promise<Decision>;
7
+ export declare function matchesRule(rule: string, name: string, input: Record<string, any>, cwd: string, canonicalFile?: string, kind?: 'allow' | 'ask' | 'deny'): Promise<boolean>;
8
+ export declare function shellWords(command: string): string[] | undefined;
@@ -0,0 +1,130 @@
1
+ import { isAbsolute, matchesGlob, resolve } from 'node:path';
2
+ import { canonical, within } from "../runtime/utils.js";
3
+ const readonly = new Set(['Read', 'Glob', 'Grep', 'TaskGet', 'TaskList', 'TaskOutput']);
4
+ const workflow = new Set(['EnterPlanMode', 'ExitPlanMode', 'AskUserQuestion', 'TaskCreate', 'TaskUpdate', 'TodoWrite', 'TaskStop']);
5
+ export async function decide(name, input, mode, config, cwd, planPath) {
6
+ const originalName = name;
7
+ if (name === 'TaskRun')
8
+ name = 'Bash';
9
+ if (name === 'AgentBatch')
10
+ name = 'Agent';
11
+ if (name === 'NotebookEdit') {
12
+ name = 'Edit';
13
+ input = { ...input, file_path: input.notebook_path };
14
+ }
15
+ const readAgent = name === 'Agent' && (input.agents ? input.agents.every((a) => ['Explore', 'Plan'].includes(a.subagent_type)) : ['Explore', 'Plan'].includes(input.subagent_type));
16
+ const file = typeof (input.file_path ?? input.notebook_path) === 'string' ? await canonical(resolve(cwd, input.file_path ?? input.notebook_path)) : undefined;
17
+ // Enforced plan constraints take precedence over every configurable rule/mode.
18
+ if (mode === 'plan' && !readAgent && !readonly.has(name) && !workflow.has(name)) {
19
+ if (!(name === 'Write' || name === 'Edit' || name === 'NotebookEdit') || !file || file !== planPath)
20
+ return { action: 'deny', reason: 'Plan mode permits only reads, workflow tools and the designated plan artifact. Shell and alternate tools are blocked.' };
21
+ }
22
+ for (const kind of ['deny', 'ask', 'allow'])
23
+ for (const rule of config.permissions[kind]) {
24
+ if (await matchesRule(rule, name, input, cwd, file, kind) || (originalName !== name && await matchesRule(rule, originalName, input, cwd, file, kind)))
25
+ return { action: kind === 'deny' || (kind === 'ask' && mode === 'dontAsk') ? 'deny' : kind === 'ask' ? 'ask' : 'allow', reason: `${kind} rule: ${rule}` };
26
+ }
27
+ if (mode === 'bypassPermissions')
28
+ return { action: 'allow', reason: 'Explicit bypassPermissions mode (no sandbox)' };
29
+ if (readonly.has(name)) {
30
+ const target = file ?? await canonical(resolve(cwd, input.path ?? '.'));
31
+ if (within(await canonical(cwd), target))
32
+ return { action: 'allow', reason: 'Read inside workspace' };
33
+ }
34
+ if (readAgent)
35
+ return { action: 'allow', reason: 'Read-only child context' };
36
+ if (workflow.has(name))
37
+ return { action: 'allow', reason: 'Workflow operation; approvals are enforced by its state machine' };
38
+ if ((name === 'Write' || name === 'Edit' || name === 'NotebookEdit') && file && ((mode === 'acceptEdits' && within(await canonical(cwd), file)) || (mode === 'plan' && file === planPath)))
39
+ return { action: 'allow', reason: 'Allowed file edit in current mode' };
40
+ if (mode === 'dontAsk')
41
+ return { action: 'deny', reason: 'dontAsk denies operations without an allow decision' };
42
+ return { action: 'ask', reason: 'Operation needs explicit approval' };
43
+ }
44
+ export async function matchesRule(rule, name, input, cwd, canonicalFile, kind = 'allow') {
45
+ const match = /^([A-Za-z][\w]*)(?:\((.*)\))?$/.exec(rule);
46
+ if (!match || match[1] !== name)
47
+ return false;
48
+ if (match[2] === undefined || match[2] === '*')
49
+ return true;
50
+ const pattern = match[2];
51
+ if (['Read', 'Write', 'Edit', 'Glob', 'Grep', 'NotebookEdit'].includes(name)) {
52
+ const supplied = resolve(cwd, input.file_path ?? input.path ?? '.');
53
+ const resolved = canonicalFile ?? await canonical(supplied);
54
+ const absolutePattern = isAbsolute(pattern) ? pattern : resolve(cwd, pattern);
55
+ // Both lexical and resolved paths must match, preventing symlink rule escapes.
56
+ const lexicalMatch = matchesGlob(supplied, absolutePattern), resolvedMatch = matchesGlob(resolved, absolutePattern);
57
+ return kind === 'allow' ? lexicalMatch && resolvedMatch : lexicalMatch || resolvedMatch;
58
+ }
59
+ if (name === 'Bash') {
60
+ // Deliberately support exact commands only. Prefix/compound syntax needs a shell parser.
61
+ if (pattern.endsWith(':*')) {
62
+ const tokens = shellWords(String(input.command ?? ''));
63
+ const prefix = shellWords(pattern.slice(0, -2));
64
+ if (!tokens || !prefix)
65
+ return kind !== 'allow';
66
+ return tokens.length >= prefix.length && prefix.every((word, index) => tokens[index] === word);
67
+ }
68
+ if (pattern.includes('*') || pattern.includes(':'))
69
+ return kind !== 'allow';
70
+ return input.command === pattern;
71
+ }
72
+ return kind !== 'allow';
73
+ }
74
+ // Classify a simple shell invocation only; compound syntax and expansion never get prefix approval.
75
+ export function shellWords(command) {
76
+ if (/[\r\n]/.test(command))
77
+ return;
78
+ const words = [];
79
+ let word = '', quote = '', started = false;
80
+ for (let i = 0; i < command.length; i++) {
81
+ const c = command[i];
82
+ if (quote === "'") {
83
+ if (c === "'")
84
+ quote = '';
85
+ else
86
+ word += c;
87
+ continue;
88
+ }
89
+ if (c === '\\') {
90
+ if (quote === '"')
91
+ return;
92
+ if (i + 1 >= command.length)
93
+ return;
94
+ word += command[++i];
95
+ started = true;
96
+ continue;
97
+ }
98
+ if (c === '$' || c === '`')
99
+ return;
100
+ if (quote === '"') {
101
+ if (c === '"')
102
+ quote = '';
103
+ else
104
+ word += c;
105
+ continue;
106
+ }
107
+ if (c === "'" || c === '"') {
108
+ quote = c;
109
+ started = true;
110
+ continue;
111
+ }
112
+ if (/[;&|<>(){}*?!~#]/.test(c))
113
+ return;
114
+ if (/\s/.test(c)) {
115
+ if (started) {
116
+ words.push(word);
117
+ word = '';
118
+ started = false;
119
+ }
120
+ continue;
121
+ }
122
+ word += c;
123
+ started = true;
124
+ }
125
+ if (quote)
126
+ return;
127
+ if (started)
128
+ words.push(word);
129
+ return words.length ? words : undefined;
130
+ }
@@ -0,0 +1,17 @@
1
+ export declare function render(template: string, bindings: Record<string, string>): string;
2
+ export declare class PromptPack {
3
+ readonly manifest: any;
4
+ private originals;
5
+ constructor(root?: URL);
6
+ fragment(name: string, bindings?: Record<string, string>): string;
7
+ system(model: string, cwd: string, tools: string[], memory: string): string;
8
+ description(name: string): string | undefined;
9
+ inspect(): {
10
+ manifest: any;
11
+ slots: {
12
+ system: string[];
13
+ Edit: string;
14
+ };
15
+ patches: string[];
16
+ };
17
+ }
@@ -0,0 +1,58 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { hash } from "../runtime/utils.js";
3
+ import { profile } from "../runtime/capabilities.js";
4
+ export function render(template, bindings) {
5
+ // Expressions are opaque keys with explicit values, never executable JavaScript.
6
+ return template.replace(/\$\{([^{}]+)\}/g, (_, key) => {
7
+ if (!Object.hasOwn(bindings, key))
8
+ throw new Error(`Unresolved prompt binding: ${key}`);
9
+ return bindings[key];
10
+ });
11
+ }
12
+ export class PromptPack {
13
+ manifest;
14
+ originals = new Map();
15
+ constructor(root = new URL('../../lib/prompts/', import.meta.url)) {
16
+ this.manifest = JSON.parse(readFileSync(new URL('manifest.json', root), 'utf8'));
17
+ if (this.manifest.commit !== profile.promptCommit)
18
+ throw new Error('Prompt pack target mismatch');
19
+ for (const entry of this.manifest.fragments) {
20
+ if (!/^original\/[a-z0-9-]+\.md$/.test(entry.path))
21
+ throw new Error('Invalid prompt manifest path');
22
+ const bytes = readFileSync(new URL(entry.path, root));
23
+ if (hash(bytes) !== entry.sha256)
24
+ throw new Error(`Prompt integrity failure: ${entry.path}`);
25
+ this.originals.set(entry.path.slice(9), bytes.toString('utf8'));
26
+ }
27
+ }
28
+ fragment(name, bindings = {}) {
29
+ const raw = this.originals.get(name);
30
+ if (!raw)
31
+ throw new Error(`Missing prompt: ${name}`);
32
+ const result = render(raw.replace(/^<!--[\s\S]*?-->\s*/, ''), bindings);
33
+ if (result.includes('${'))
34
+ throw new Error(`Unresolved prompt expression: ${name}`);
35
+ return result;
36
+ }
37
+ system(model, cwd, tools, memory) {
38
+ return [
39
+ `You are a coding assistant running in pi with a Claude Code ${profile.target} compatibility profile. Actual model: ${model}.`,
40
+ 'Help the user complete software engineering tasks. Read relevant code before editing. Make focused changes and verify the resulting behavior. Report outcomes truthfully and concisely.',
41
+ this.fragment('system-prompt-system-section.md'),
42
+ `Working directory: ${cwd}\nAvailable tools: ${tools.join(', ')}. Only claim capabilities of these tools.`,
43
+ 'This profile uses an incomplete pinned prompt pack. Subagents, hosted services, background jobs, and OS sandboxing are unavailable.',
44
+ memory,
45
+ ].filter(Boolean).join('\n\n');
46
+ }
47
+ description(name) {
48
+ if (name === 'Edit')
49
+ return this.fragment('tool-description-edit.md', {
50
+ 'READ_BEFORE_EDIT_NOTE_FN()': '\n- Read the file before editing. A changed file must be read again.',
51
+ LINE_NUMBER_PREFIX_FORMAT: 'line_number followed by a tab', ADDITIONAL_EDIT_GUIDELINES_NOTE: '',
52
+ });
53
+ // The original Read describes unsupported PDF/notebook rendering. Keep it inspectable;
54
+ // a deliberately adapted description is registered instead of making false claims.
55
+ return undefined;
56
+ }
57
+ inspect() { return { manifest: this.manifest, slots: { system: ['local identity/environment adaptation', 'system-prompt-system-section.md', 'project memory'], Edit: 'tool-description-edit.md' }, patches: ['Main instruction stack is an approximation; full inventory is unavailable.', 'Read uses local text-only description; PDF/notebook rendering is unsupported.', 'Agent/compaction/plan fragments are archived but inactive until their capabilities are validated.'] }; }
58
+ }
@@ -0,0 +1,10 @@
1
+ import type { ExtensionAPI } from '@earendil-works/pi-coding-agent';
2
+ import { Runtime } from '../runtime/runtime.ts';
3
+ export type Feature = string;
4
+ interface Shared {
5
+ runtime: Runtime;
6
+ features: Set<Feature>;
7
+ }
8
+ export declare function shared(pi: ExtensionAPI): Shared;
9
+ export declare function acquire(pi: ExtensionAPI, feature: string): Shared | undefined;
10
+ export {};