pi-ext bugabingas pi extensions
owned by admin
README Source History Refs Compare Notes Search fix(git-safe): guard agent Git execution
a6436748ad05e71c2d7ea86d938c2bd07c198e0c
Oliver Jan Krylow <oliver@bugabinga.net > · 18 Aug 2026
SSH signature · not checked
Browse files Compare with HEAD
Changed files (9) extensions/git-safe/CHANGELOG.md Modified 5 + - Prevent agent-issued Git commands from opening interactive editors
6 + - Reject hook-skipping `--no-verify` options through normal Git, aliases, shell indirection, nested Bash, `xargs`, child-process PATH lookup, and literal bypasses
7 + - Convert temporary wrapper paths for Git Bash on Windows
8 + - Document explicit `git.exe` child-process and unrestricted-Bash residual bypasses
9 + - Keep safe-clone behavior unchanged
5 13 - Add sparse safe clone support.
extensions/git-safe/README.md Modified 26 26 - `session_shutdown`
27 + - `tool_call` for agent-issued `bash`
27 28 - `tool_result` for `read`
34 + Agent-issued Bash commands receive noninteractive Git editor settings:
37 + - `GIT_SEQUENCE_EDITOR=true`
38 + - `GIT_MERGE_AUTOEDIT=no`
40 + A session-scoped Git executable wrapper receives parsed arguments from normal Bash calls, `command git`, `env git`, `xargs git`, nested Bash, and unqualified child-process PATH lookup.
41 + It rejects hook-skipping `--no-verify` options, including accepted abbreviations, short `commit -n`, and non-shell alias chains.
42 + It resets the editor environment immediately before invoking real Git and delegates ordinary commands unchanged.
43 + Bash `git()` and `git.exe()` functions route direct calls to that wrapper, while narrow preflight checks cover simple literal bypasses.
44 + Windows paths are converted for Git Bash, and common `git.exe` shell forms route through the wrapper.
45 + The layers are defense in depth, not a security boundary; unrestricted Bash can still address or construct alternate executable paths.
46 + On Windows, a non-Bash child process that explicitly launches `git.exe` can bypass the script wrapper because the extension does not ship a native PE launcher.
33 48 `git_clone_safe` clones a repository with checks around hook execution,
34 49 symlinks, LFS filters, disk use, and credential prompts.
extensions/git-safe/__tests__/git-policy.test.ts Added new file mode 100644 1 + import { describe, expect, it }
from "vitest" ;
2 + import { applyGitPolicy, blockedGitCommandReason }
from "../git-policy" ;
4 + describe (
"git-safe agent Git policy" , ()
=> {
5 + it (
"blocks literal command-git no-verify bypasses" , ()
=> {
6 + for (
const command
of [
7 + "command git commit --no-verify" ,
8 + "command -p git push --no-verify" ,
9 + " command -- git rebase --no-verify" ,
11 + expect (
blockedGitCommandReason (command)).
toContain (
"blocked --no-verify" );
15 + it (
"does not classify ordinary Git or quoted documentation as command bypasses" , ()
=> {
16 + for (
const command
of [
17 + "git commit --no-verify" ,
18 + "printf '%s' 'command git commit --no-verify'" ,
19 + "command git status" ,
20 + "command git commit -m 'Document --no-verify usage'" ,
21 + "command git merge --no-verify-signatures topic" ,
23 + expect (
blockedGitCommandReason (command)).
toBeUndefined ();
27 + it (
"routes Git, command, and env through the executable wrapper" , ()
=> {
28 + const runtime
= { wrapperDir:
"/tmp/git policy" , realGit:
"/usr/bin/git" };
29 + const wrapped
= applyGitPolicy (
"git status" , runtime);
31 + expect (wrapped).
toContain (
"'/tmp/git policy'" );
32 + expect (wrapped).
toContain (
"'/tmp/git policy/git'" );
33 + expect (wrapped).not.
toContain (
"PI_GIT_SAFE_REAL_GIT" );
34 + expect (
applyGitPolicy (wrapped, runtime)).not.
toBe (wrapped);
37 + it (
"converts Windows paths for Git Bash" , ()
=> {
38 + const wrapped
= applyGitPolicy (
"git status" , {
39 + wrapperDir:
"C:\\Users\\me\\AppData\\Local\\Temp\\git-safe" ,
40 + realGit:
"C:\\Program Files\\Git\\cmd\\git.exe" ,
43 + expect (wrapped).
toContain (
44 + "export PATH='/c/Users/me/AppData/Local/Temp/git-safe':\"$PATH\"" ,
46 + expect (wrapped).
toContain (
47 + "'/c/Users/me/AppData/Local/Temp/git-safe/git' \"$@\"" ,
51 + it (
"does not trust an agent-supplied policy marker" , ()
=> {
52 + const command
= "# pi-git-safe-policy-v1\ngit commit --no-verify" ;
53 + const wrapped
= applyGitPolicy (command, {
54 + wrapperDir:
"/tmp/wrapper" ,
55 + realGit:
"/usr/bin/git" ,
58 + expect (wrapped).not.
toBe (command);
59 + expect (wrapped.
endsWith (command)).
toBe (
true );
extensions/git-safe/__tests__/harness.test.ts Modified 9 + import { tmpdir }
from "node:os" ;
10 + import path
from "node:path" ;
11 + import { createBashTool }
from "@earendil-works/pi-coding-agent" ;
1 12 import { afterEach, describe, expect, it }
from "vitest" ;
2 - import { createTestSession, type TestSession }
from "../../../test/harness" ;
3 - import gitSafeExtension
from "../index" ;
17 + }
from "../../../test/harness" ;
23 + input
: { command
: string };
26 + function gitSafePath ()
: string {
27 + return path.
resolve (
import .
meta .dirname,
"../index.ts" );
30 + function rtkPath ()
: string {
31 + return path.
resolve (
import .
meta .dirname,
"../../rtk/index.ts" );
34 + function installFakeGit (root
: string )
: string {
35 + const bin
= path.
join (
root ,
"fake-bin" );
37 + const git
= path.
join (bin,
"git" );
41 + "#!/usr/bin/env bash" ,
42 + "if [[ \"$*\" == '--list-cmds=builtins' ]]; then printf 'status\\n'; exit 0; fi" ,
43 + "if [[ \"$*\" == *'config --get alias.'* ]]; then exit 1; fi" ,
44 + "printf 'FAKE_GIT\\n'" ,
46 + "printf '<%s>' \"$@\"" ,
47 + 'printf \'\\nEDITOR=<%s> SEQUENCE=<%s> MERGE=<%s>\\n\' "$GIT_EDITOR" "$GIT_SEQUENCE_EDITOR" "$GIT_MERGE_AUTOEDIT"' ,
52 + chmodSync (git,
0o755 );
53 + const gitExe
= path.
join (bin,
"git.exe" );
54 + writeFileSync (gitExe,
readFileSync (git));
55 + chmodSync (gitExe,
0o755 );
59 + function installFakeRtk (bin
: string )
: void {
60 + const rtk
= path.
join (bin,
"rtk" );
64 + "#!/usr/bin/env bash" ,
65 + "if [[ \"$1\" == '--version' ]]; then printf 'rtk 0.42.4\\n'; exit 0; fi" ,
66 + "if [[ \"$1\" == 'rewrite' && \"$2\" == 'git commit --no-verify' ]]; then printf 'rtk git commit --no-verify\\n'; exit 0; fi" ,
67 + "if [[ \"$1\" == 'rewrite' && \"$2\" == 'git status' ]]; then printf 'rtk git status\\n'; exit 0; fi" ,
68 + 'if [[ "$1" == \'git\' ]]; then shift; exec git "$@"; fi' ,
74 + chmodSync (rtk,
0o755 );
77 + function bashEvent (command
: string )
: BashEvent {
81 + toolCallId: crypto.
randomUUID (),
5 86 describe (
"git-safe pi-test-harness" , ()
=> {
6 87 let t
: TestSession | undefined ;
88 + let root
: string | undefined ;
89 + let fakeGit
: string | undefined ;
93 + if (
root )
rmSync (
root , { recursive:
true , force:
true });
96 + fakeGit
= undefined ;
99 + async function startWithFakeGit (useRtk
= false )
: Promise <
void > {
100 + root = mkdtempSync (path.
join (
tmpdir (),
"pi-git-safe-test-" ));
101 + const fakeBin
= installFakeGit (
root );
102 + if (useRtk)
installFakeRtk (fakeBin);
103 + fakeGit
= path.
join (fakeBin,
"git" );
104 + t
= await createTestSession ({
106 + env: { PATH:
`${fakeBin}${path.delimiter}${ process . env .PATH}` },
107 + extensions: useRtk
? [
gitSafePath (),
rtkPath ()]
: [
gitSafePath ()],
111 + async function execute (command
: string ) {
112 + if (
! t)
throw new Error (
"missing test session" );
113 + const event
= bashEvent (command);
114 + const blocked
= await t.session.extensionRunner.
emitToolCall (
117 + if (blocked)
return { blocked, output:
"" };
118 + const tool
= createBashTool (t.cwd);
120 + const result
= await withProcessEnv (t.env, ()
=> 124 + new AbortController ().signal,
128 + const output
= result.
content 129 + .
flatMap ((part)
=> (part.
type === "text" ? [part.
text ]
: []))
131 + return { blocked, output };
135 + output: error
instanceof Error ? error.message
: String (error),
140 + async function expectRejected (command
: string )
: Promise <
void > {
141 + const result
= await execute (command);
142 + expect (result.output).
toContain (
"git-safe blocked --no-verify" );
143 + expect (result.output).not.
toContain (
"FAKE_GIT" );
13 146 it (
"loads in real Pi extension runtime" ,
async ()
=> {
14 - t
= await createTestSession ({ extensionFactories: [gitSafeExtension] });
147 + t
= await createTestSession ({ extensions: [
gitSafePath ()] });
16 149 expect (t.session.extensionRunner.extensions).
toHaveLength (
1 );
152 + it (
"sets noninteractive editor variables while ordinary Git still runs" ,
async ()
=> {
153 + await startWithFakeGit ();
155 + const result
= await execute (
"git status" );
157 + expect (result.blocked).
toBeUndefined ();
158 + expect (result.output).
toContain (
"FAKE_GIT" );
159 + expect (result.output).
toContain (
"ARGS:<status>" );
160 + expect (result.output).
toContain (
"EDITOR=<true> SEQUENCE=<true> MERGE=<no>" );
163 + it (
"rejects no-verify after shell expansion and indirect PATH lookup" ,
async ()
=> {
164 + await startWithFakeGit ();
166 + for (
const command
of [
167 + 'flag=--no-verify; git commit "$flag"' ,
168 + "git am --no-v patch.mbox" ,
169 + "git am -n patch.mbox" ,
170 + 'command git commit --no-"verify"' ,
171 + "command -p git -C . commit --no-verify" ,
172 + "env git push --no-verify" ,
173 + "env --uns PATH git commit --no-verify" ,
174 + "bash -p -c 'git rebase --no-verify'" ,
175 + "bash -c 'command git commit --no-verify'" ,
176 + "unset -f git; git commit --no-verify" ,
177 + "printf '%s\\0' commit --no-verify | xargs -0 git" ,
178 + "printf '%s\\0' commit --no-verify | xargs -0 git.exe" ,
179 + "printf '%s\\0' commit --no-verify | xargs -0 --max-a 2 git.exe" ,
181 + "git commit --no-verif" ,
182 + "git commit --untracked-files --no-verify" ,
183 + "git push --signed --no-verify" ,
184 + "git rebase --rebase-merges --no-verify main" ,
185 + "git pull --no-verify" ,
187 + await expectRejected (command);
191 + it (
"rejects temporary aliases that create no-verify inside Git" ,
async ()
=> {
192 + await startWithFakeGit ();
194 + for (
const command
of [
195 + "git -c 'alias.nv=commit --no-verify' nv" ,
196 + `git -c "alias.nv=commit -m '' --no-verify" nv` ,
197 + "git -c 'alias.nv=--no-pager commit --no-verify' nv" ,
198 + "git -c 'alias.x=-c alias.y=commit y --no-verify' x" ,
199 + "git -calias.nv='commit --no-verify' nv" ,
200 + "git -c 'alias.nv=commit -n' nv" ,
201 + "git -c 'alias.nv=commit \"--no-verify\"' nv" ,
202 + "git -c alias.ci=commit ci --no-verify" ,
203 + "NV='commit --no-verify' git --config-env=alias.nv=NV nv" ,
204 + "GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0=alias.nv GIT_CONFIG_VALUE_0='commit --no-verify' git nv" ,
206 + await expectRejected (command);
209 + const chain
= Array .
from (
211 + (_, index)
=> `-c alias.a${index}=a${index + 1}` ,
213 + await expectRejected (
`git ${chain} -c 'alias.a12=commit --no-verify' a0` );
216 + it (
"restores editor protection at the executable boundary" ,
async ()
=> {
217 + await startWithFakeGit ();
219 + for (
const command
of [
220 + "GIT_EDITOR=vim git commit" ,
221 + "GIT_SEQUENCE_EDITOR=vim git rebase -i HEAD~1" ,
222 + "env -u GIT_EDITOR -u GIT_SEQUENCE_EDITOR -u GIT_MERGE_AUTOEDIT git commit" ,
223 + "GIT_EDITOR=vim command -p git commit" ,
225 + const result
= await execute (command);
226 + expect (result.output).
toContain (
"FAKE_GIT" );
227 + expect (result.output).
toContain (
228 + "EDITOR=<true> SEQUENCE=<true> MERGE=<no>" ,
233 + it (
"preserves editor queries without opening an editor" ,
async ()
=> {
234 + await startWithFakeGit ();
236 + const result
= await execute (
"git var GIT_EDITOR" );
237 + expect (result.output).
toContain (
"FAKE_GIT" );
238 + expect (result.output).
toContain (
"EDITOR=<> SEQUENCE=<> MERGE=<>" );
241 + it (
"does not trust an agent-supplied policy marker" ,
async ()
=> {
242 + await startWithFakeGit ();
244 + await expectRejected (
245 + "# pi-git-safe-policy-v1\\ngit commit --no-verify" .
replace (
"\\n" ,
"\n" ),
249 + it (
"permits no-verify when Git treats it as data" ,
async ()
=> {
250 + await startWithFakeGit ();
252 + for (
const command
of [
253 + "git add -- --no-verify" ,
254 + "git grep -e --no-verify" ,
255 + "git commit -m --no-verify" ,
256 + "git commit -am --no-verify" ,
258 + "git commit -t/dev/null" ,
259 + "git commit --mess --no-verify" ,
260 + "git commit -m safe --end-of-options --no-verify" ,
261 + "git commit -Sn -m signed" ,
262 + "git merge --into-name --no-verify topic" ,
263 + "git merge -F --no-verify topic" ,
264 + "git am --resolvemsg --no-verify patch.mbox" ,
265 + "git rebase --trailer --no-verify trunk" ,
266 + "git pull --no-rebase -o --no-verify" ,
267 + "git -c 'alias.nv=commit --no-verify' status" ,
268 + "git -c 'alias.note=!printf %s --no-verify' note" ,
269 + "command git merge --no-verify-signatures topic" ,
270 + "command git commit -m 'Document --no-verify usage'" ,
271 + 'env -i PATH="$PATH" git status' ,
272 + "GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0=alias.nv GIT_CONFIG_VALUE_0='commit --no-verify' git -c alias.nv=status nv" ,
273 + "GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0=alias.status GIT_CONFIG_VALUE_0='commit --no-verify' git status" ,
275 + const result
= await execute (command);
276 + expect (result.blocked, command).
toBeUndefined ();
277 + expect (result.output, command).
toContain (
"FAKE_GIT" );
281 + it (
"blocks literal command-git bypasses before execution" ,
async ()
=> {
282 + await startWithFakeGit ();
284 + const result
= await execute (
"command git commit --no-verify" );
286 + expect (result.blocked).
toMatchObject ({ block:
true });
287 + expect (result.blocked?.reason).
toContain (
"git-safe blocked --no-verify" );
290 + it (
"rejects literal absolute Git paths" ,
async ()
=> {
291 + await startWithFakeGit ();
292 + if (
! fakeGit)
throw new Error (
"missing fake Git path" );
294 + for (
const command
of [
"commit" ,
"pull" ]) {
295 + const result
= await execute (
296 + `${ JSON . stringify (fakeGit)} ${command} --no-verify` ,
298 + expect (result.blocked).
toMatchObject ({ block:
true });
302 + it (
"keeps policy active after RTK rewrites Git" ,
async ()
=> {
303 + await startWithFakeGit (
true );
305 + await expectRejected (
"git commit --no-verify" );
306 + const ordinary
= await execute (
"git status" );
307 + expect (ordinary.output).
toContain (
"FAKE_GIT" );
308 + expect (ordinary.output).
toContain (
"ARGS:<status>" );
extensions/git-safe/git-policy.ts Added new file mode 100644 1 + import { constants }
from "node:fs" ;
10 + }
from "node:fs/promises" ;
11 + import { tmpdir }
from "node:os" ;
12 + import { delimiter, join }
from "node:path" ;
14 + const POLICY_MARKER
= "# pi-git-safe-policy-v1" ;
15 + const COMMAND_PREFIX_END
= "# pi-command-prefix-end" ;
18 + "git-safe blocked --no-verify. Fix the hook failure or ask the user for help." ;
20 + const DIRECT_COMMAND_GIT_NO_VERIFY_RE
= 21 + / ^ \s * command\s + (?:(?:-p | --)\s + ) * git(?:\.exe) ? \s + (?:am | commit | merge | pull | push | rebase)\s + --no-verify(?:\s |$ )/ u ;
23 + export interface GitPolicyRuntime {
28 + function pathKey (env
: NodeJS .
ProcessEnv )
: string {
29 + return Object .
keys (env).
find ((key)
=> key.
toLowerCase ()
=== "path" )
?? "PATH" ;
32 + export async function findGitExecutable (
33 + env
: NodeJS .
ProcessEnv = process .
env ,
34 + platform
= process .
platform ,
35 + )
: Promise <
string | undefined > {
36 + const path
= env[
pathKey (env)]
?? "" ;
37 + const names
= platform
=== "win32" ? [
"git.exe" ]
: [
"git" ];
38 + for (
const dir
of path.
split (delimiter).
filter (
Boolean )) {
39 + for (
const name
of names) {
40 + const candidate
= join (dir.
replace (
/ ^ " | " $ / gu ,
"" ), name);
44 + platform
=== "win32" ? constants.F_OK
: constants.X_OK,
46 + return await realpath (candidate);
53 + export async function createGitPolicyRuntime ()
: Promise <
GitPolicyRuntime > {
54 + const realGit
= await findGitExecutable ();
55 + if (
! realGit)
throw new Error (
"Git executable not found on PATH" );
56 + const wrapperDir
= await mkdtemp (
join (
tmpdir (),
"pi-git-safe-policy-" ));
57 + const wrapper
= join (wrapperDir,
"git" );
59 + const template
= await readFile (
60 + new URL (
"./git-wrapper.cjs" ,
import .
meta .url),
65 + template.
replace (
'"__PI_GIT_SAFE_REAL_GIT__"' ,
JSON .
stringify (realGit)),
68 + await chmod (wrapper,
0o755 );
70 + join (wrapperDir,
"git.cmd" ),
71 + `@echo off\r\n"${ process . execPath }" "%~dp0git" %*\r\n` ,
74 + return { wrapperDir, realGit };
76 + await rm (wrapperDir, { recursive:
true , force:
true }).
catch (()
=> {});
81 + export async function removeGitPolicyRuntime (
82 + runtime
: GitPolicyRuntime | undefined ,
85 + await rm (runtime.wrapperDir, { recursive:
true , force:
true }).
catch (
90 + function shellQuote (value
: string )
: string {
91 + return `'${value. replaceAll ("'", `'\\''`)}'` ;
94 + function bashPath (value
: string )
: string {
95 + const normalized
= value.
replaceAll (
"\\" ,
"/" );
96 + const drive
= normalized.
match (
/ ^ ([A-Za-z]):\/(. * ) $ / u );
97 + return drive
? `/${drive[1]. toLowerCase ()}/${drive[2]}` : normalized;
100 + export function blockedGitCommandReason (
102 + runtime
?: GitPolicyRuntime ,
103 + )
: string | undefined {
104 + if (DIRECT_COMMAND_GIT_NO_VERIFY_RE.
test (command))
return BLOCK_REASON;
105 + if (
! runtime)
return undefined ;
106 + const trimmed
= command.
trimStart ();
107 + const literalPaths
= [
109 + bashPath (runtime.realGit),
110 + shellQuote (runtime.realGit),
111 + shellQuote (
bashPath (runtime.realGit)),
112 + JSON .
stringify (runtime.realGit),
114 + for (
const path
of literalPaths) {
115 + if (
! trimmed.
startsWith (
`${path} ` ))
continue ;
116 + const args
= trimmed.
slice (path.
length ).
trimStart ();
118 + / ^ (?:am | commit | merge | pull | push | rebase)\s + --no-verify(?:\s |$ )/ u .
test (args)
120 + return BLOCK_REASON;
125 + export function applyGitPolicy (
127 + runtime
: GitPolicyRuntime ,
129 + const wrapper
= shellQuote (
bashPath (
join (runtime.wrapperDir,
"git" )));
130 + return `${POLICY_MARKER} 131 + export PATH=${ shellQuote ( bashPath (runtime.wrapperDir))}:"$PATH" 139 + local -a __pi_git_safe_args=("$@") 140 + local __pi_git_safe_index=0 141 + while [[ "\${__pi_git_safe_args[$__pi_git_safe_index]}" == "-p" || "\${__pi_git_safe_args[$__pi_git_safe_index]}" == "--" ]]; do 142 + ((__pi_git_safe_index++)) 144 + if [[ "\${__pi_git_safe_args[$__pi_git_safe_index]}" == "git" || "\${__pi_git_safe_args[$__pi_git_safe_index]}" == "git.exe" ]]; then 145 + ${wrapper} "\${__pi_git_safe_args[@]:$((__pi_git_safe_index + 1))}" 147 + builtin command "$@" 151 + local -a __pi_git_safe_args=("$@") 152 + local __pi_git_safe_index=0 153 + while (( __pi_git_safe_index < \${#__pi_git_safe_args[@]} )); do 154 + case "\${__pi_git_safe_args[$__pi_git_safe_index]}" in 156 + ((__pi_git_safe_index++)) 159 + --u*=*|--c*=*|--s*=*|--a*=*) 160 + ((__pi_git_safe_index++)) 162 + -u|--u*|-C|--c*|-S|--s*|--a*) 163 + ((__pi_git_safe_index += 2)) 166 + ((__pi_git_safe_index++)) 173 + if [[ "\${__pi_git_safe_args[$__pi_git_safe_index]}" == "git" || "\${__pi_git_safe_args[$__pi_git_safe_index]}" == "git.exe" ]]; then 174 + __pi_git_safe_args[$__pi_git_safe_index]=${wrapper} 176 + builtin command env "\${__pi_git_safe_args[@]}" 179 + local -a __pi_git_safe_args=("$@") 180 + local __pi_git_safe_index=0 181 + while (( __pi_git_safe_index < \${#__pi_git_safe_args[@]} )); do 182 + case "\${__pi_git_safe_args[$__pi_git_safe_index]}" in 184 + ((__pi_git_safe_index++)) 187 + --arg*=*|--e*=*|--r*=*|--m*=*|--d*=*) 188 + ((__pi_git_safe_index++)) 190 + -a|-E|-I|-L|-n|-P|-s|-d|--arg*|--e*|--r*|--m*|--d*) 191 + ((__pi_git_safe_index += 2)) 194 + ((__pi_git_safe_index++)) 201 + if [[ "\${__pi_git_safe_args[$__pi_git_safe_index]}" == "git" || "\${__pi_git_safe_args[$__pi_git_safe_index]}" == "git.exe" ]]; then 202 + __pi_git_safe_args[$__pi_git_safe_index]=${wrapper} 204 + builtin command xargs "\${__pi_git_safe_args[@]}" 206 + export -f git git.exe command env xargs 207 + ${COMMAND_PREFIX_END} extensions/git-safe/git-wrapper.cjs Added new file mode 100644 3 + const { spawnSync }
= require (
"node:child_process" );
5 + const realGit
= "__PI_GIT_SAFE_REAL_GIT__" ;
6 + const protectedCommands
= new Set ([
14 + const globalValueOptions
= new Set ([
24 + const commandValueOptions
= {
48 + "--pathspec-from-file" ,
65 + "--strategy-option" ,
73 + "--negotiation-tip" ,
75 + "--shallow-exclude" ,
78 + "--strategy-option" ,
81 + push:
new Set ([
"-o" ,
"--exec" ,
"--push-option" ,
"--receive-pack" ,
"--repo" ]),
90 + "--strategy-option" ,
95 + const shortValueOptions
= {
96 + am:
new Set ([
"C" ,
"p" ]),
97 + commit:
new Set ([
"C" ,
"F" ,
"c" ,
"m" ,
"t" ]),
98 + merge:
new Set ([
"F" ,
"m" ,
"s" ,
"X" ]),
99 + pull:
new Set ([
"o" ,
"s" ,
"X" ]),
100 + push:
new Set ([
"o" ]),
101 + rebase:
new Set ([
"s" ,
"X" ,
"x" ]),
103 + const shortAttachedValueOptions
= {
105 + commit:
new Set ([
"S" ,
"u" ]),
112 + function optionName (argument) {
113 + const equals
= argument.indexOf(
"=" );
114 + return equals
< 0 ? argument
: argument.slice(
0 , equals);
117 + function consumesNext (argument, options) {
118 + return ! argument.includes(
"=" )
&& options.has(optionName(argument));
121 + function consumesCommandValue (argument, options) {
122 + if (argument.includes(
"=" ))
return false ;
123 + if (options.has(argument))
return true ;
124 + if (
! argument.startsWith(
"--" ))
return false ;
125 + return [
... options].filter((option)
=> option.startsWith(argument)).length
=== 1 ;
128 + function commandPosition (args) {
129 + for (
let index
= 0 ; index
< args.length; index
++ ) {
130 + const argument
= args[index];
131 + if (argument
=== "--" )
return index
+ 1 ;
132 + if (
! argument.startsWith(
"-" ))
return index;
133 + if (consumesNext(argument, globalValueOptions)) index
++ ;
138 + function addAlias (aliases, config) {
139 + const match
= config.match(
/ ^ alias\.([ ^ =] + )=(. * ) $ / isu );
140 + if (match) aliases.set(match[
1 ].toLowerCase(), match[
2 ]);
143 + function addArgumentAliases (aliases, args, commandIndex) {
144 + for (
let index
= 0 ; index
< commandIndex; index
++ ) {
145 + const argument
= args[index];
146 + if (argument
=== "-c" ) {
147 + addAlias(aliases, args[
++ index]
?? "" );
150 + if (argument.startsWith(
"-c" )
&& argument.length
> 2 ) {
151 + addAlias(aliases, argument.slice(
2 ));
154 + const configEnv
= argument.startsWith(
"--config-env=" )
155 + ? argument.slice(
"--config-env=" .length)
156 + : argument
=== "--config-env" 157 + ? (args[
++ index]
?? "" )
159 + if (configEnv
!== undefined ) {
160 + const equals
= configEnv.indexOf(
"=" );
162 + const name
= configEnv.slice(
0 , equals);
163 + const variable
= configEnv.slice(equals
+ 1 );
164 + addAlias(aliases,
` ${name}
= ${
process .
env [variable]
?? "" }
` );
170 + function temporaryAliases (args, commandIndex) {
171 + const aliases
= new Map ();
172 + const count
= Number .
parseInt (
process .
env .GIT_CONFIG_COUNT
?? "0" ,
10 );
173 + for (
let index
= 0 ; index
< count; index
++ ) {
174 + const key
= process .
env [
`GIT_CONFIG_KEY_ ${index}
` ]
?? "" ;
175 + const value
= process .
env [
`GIT_CONFIG_VALUE_ ${index}
` ]
?? "" ;
176 + addAlias(aliases,
` ${key}
= ${value}
` );
178 + addArgumentAliases(aliases, args, commandIndex);
182 + function splitAlias (value) {
186 + let escaped
= false ;
187 + let started
= false ;
188 + for (
const character
of value.trim()) {
195 + if (character
=== "\\" && quote
!== "'" ) {
199 + if ((character
=== "'" || character
=== '"' )
&& ! quote) {
204 + if (character
=== quote) {
208 + if (
/\s/ u .test(character)
&& ! quote) {
209 + if (started) words.push(word);
221 + if (started) words.push(word);
225 + function configuredAlias (globalArgs, command) {
226 + const result
= spawnSync(
228 + [
... globalArgs,
"config" ,
"--get" ,
`alias. ${command}
` ],
234 + return result.status
=== 0 ? result.stdout.trim()
: undefined ;
237 + function isBuiltinCommand (command) {
238 + const result
= spawnSync(realGit, [
"--list-cmds=builtins" ], {
242 + return result.status
=== 0 && result.stdout.split(
/\s + / u ).includes(command);
245 + function resolveCommand (args) {
246 + const position
= commandPosition(args);
247 + if (position
< 0 || position
>= args.length)
return undefined ;
248 + const globalArgs
= args.slice(
0 , position);
249 + const aliases
= temporaryAliases(args, position);
250 + const seen
= new Set ();
251 + let command
= args[position];
252 + let commandArgs
= args.slice(position
+ 1 );
253 + while (
! protectedCommands.has(command)) {
254 + const key
= command.toLowerCase();
255 + if (seen.has(key))
break ;
257 + const alias
= aliases.get(key)
?? configuredAlias(globalArgs, command);
258 + if (
! alias
|| alias.startsWith(
"!" )
|| isBuiltinCommand(command))
break ;
259 + const expansion
= [
... splitAlias(alias),
... commandArgs];
260 + const expandedPosition
= commandPosition(expansion);
261 + if (expandedPosition
< 0 || expandedPosition
>= expansion.length)
break ;
262 + addArgumentAliases(aliases, expansion, expandedPosition);
263 + globalArgs.push(
... expansion.slice(
0 , expandedPosition));
264 + command
= expansion[expandedPosition];
265 + commandArgs
= expansion.slice(expandedPosition
+ 1 );
267 + return { command, args: commandArgs };
270 + function isNoVerifyLongOption (command, argument) {
271 + const minimum
= command
=== "am" ? "--no-v" : "--no-veri" ;
272 + return argument.length
>= minimum.length
&& "--no-verify" .startsWith(argument);
275 + function inspectShortOptions (command, argument) {
276 + if (
! / ^ -[ ^ -]/ u .test(argument))
return { blocked:
false , consumesNext:
false };
277 + const options
= argument.slice(
1 );
278 + const values
= shortValueOptions[command];
279 + const attachedValues
= shortAttachedValueOptions[command];
280 + for (
let index
= 0 ; index
< options.length; index
++ ) {
281 + const option
= options[index];
282 + if ((command
=== "am" || command
=== "commit" )
&& option
=== "n" ) {
283 + return { blocked:
true , consumesNext:
false };
285 + if (values.has(option)) {
288 + consumesNext: index
=== options.length
- 1 ,
291 + if (attachedValues.has(option)) {
292 + return { blocked:
false , consumesNext:
false };
295 + return { blocked:
false , consumesNext:
false };
298 + function hasNoVerifyOption (args) {
299 + const resolved
= resolveCommand(args);
300 + if (
! resolved
|| ! protectedCommands.has(resolved.command))
return false ;
301 + const valueOptions
= commandValueOptions[resolved.command];
302 + for (
let index
= 0 ; index
< resolved.args.length; index
++ ) {
303 + const argument
= resolved.args[index];
304 + if (argument
=== "--" || argument
=== "--end-of-options" )
return false ;
305 + if (isNoVerifyLongOption(resolved.command, argument))
return true ;
306 + const short
= inspectShortOptions(resolved.command, argument);
307 + if (short.blocked)
return true ;
308 + if (short.consumesNext
|| consumesCommandValue(argument, valueOptions)) index
++ ;
313 + const args
= process .
argv .slice(
2 );
314 + if (hasNoVerifyOption(args)) {
316 + "git-safe blocked --no-verify. Fix the hook failure or ask the user for help." ,
322 + args[commandPosition(args)]
=== "var" && 323 + (args[commandPosition(args)
+ 1 ]
=== "GIT_EDITOR" || 324 + args[commandPosition(args)
+ 1 ]
=== "GIT_SEQUENCE_EDITOR" );
325 + const env
= {
... process .
env };
327 + env.GIT_EDITOR
= "true" ;
328 + env.GIT_SEQUENCE_EDITOR
= "true" ;
329 + env.GIT_MERGE_AUTOEDIT
= "no" ;
331 + const result
= spawnSync(realGit, args, { stdio:
"inherit" , env });
333 + console .
error (result.error.message);
336 + if (result.signal)
process .
kill (
process .
pid , result.signal);
337 + process .
exit (result.status
?? 1 );
extensions/git-safe/index.ts Modified 20 20 import { realpath }
from "node:fs/promises" ;
21 21 import { resolve }
from "node:path" ;
22 - import type { ExtensionAPI }
from "@earendil-works/pi-coding-agent" ;
24 + isToolCallEventType,
25 + }
from "@earendil-works/pi-coding-agent" ;
23 26 import { Text }
from "@earendil-works/pi-tui" ;
24 27 import { Type }
from "typebox" ;
27 30 type SafeCloneResult ,
29 32 } from
"./clone.js" ;
35 + blockedGitCommandReason,
36 + createGitPolicyRuntime,
37 + type GitPolicyRuntime,
38 + removeGitPolicyRuntime,
39 + }
from "./git-policy.js" ;
30 40 import { createMarkers, wrapUntrusted }
from "./spotlight.js" ;
69 79 const spotlightMarkers
= createMarkers ({ preamble: GIT_PREAMBLE });
70 80 let generation
= 0 ;
81 + let gitPolicyRegistered
= false ;
82 + let gitPolicyRuntime
: GitPolicyRuntime | undefined ;
74 86 pi.
on (
"session_start" ,
async (_event, ctx)
=> {
87 + if (
! gitPolicyRuntime) {
89 + gitPolicyRuntime
= await createGitPolicyRuntime ();
93 + `git-safe policy disabled: ${error instanceof Error ? error.message : String (error)}` ,
98 + if (gitPolicyRuntime
&& ! gitPolicyRegistered) {
99 + gitPolicyRegistered
= true ;
100 + pi.
on (
"tool_call" , (event)
=> {
101 + if (
! isToolCallEventType (
"bash" ,
event )
|| ! gitPolicyRuntime)
return ;
102 + const reason
= blockedGitCommandReason (
103 + event .
input .command,
106 + if (reason)
return { block:
true , reason };
107 + event .
input .command
= applyGitPolicy (
108 + event .
input .command,
75 114 const ticket
= ++ generation;
76 115 const paths
= await recoverTrackedPaths (ctx.cwd);
77 116 if (ticket
!== generation)
return ;
89 128 pi.
on (
"session_shutdown" ,
async ()
=> {
130 + await removeGitPolicyRuntime (gitPolicyRuntime);
131 + gitPolicyRuntime
= undefined ;
extensions/rtk/__tests__/rtk.test.ts Modified 6 6 localFallbackRewrite,
11 12 type Handler = (event
: any , ctx
: any )
=> unknown | Promise <
unknown >;
65 66 expect (
isFindRewrite (
"rtk git status" )).
toBe (
false );
69 + test (
"preserves registered command prefixes around rewrites" ,
async ()
=> {
70 + const prefix
= "# policy\n# pi-command-prefix-end\n" ;
71 + expect (
splitCommandPrefix (
`${prefix}git status` )).
toEqual ({
73 + command:
"git status" ,
77 + await loadWithRewrite (
0 ,
"rtk git status\n" ),
78 + `${prefix}git status` ,
80 + ).
toBe (
`${prefix}rtk git status` );
68 83 test (
"maps local noisy-output misses only" , ()
=> {
69 84 expect (
localFallbackRewrite (
"journalctl --user -n 100 --no-pager" )).
toBe (
70 85 "rtk summary journalctl --user -n 100 --no-pager" ,
extensions/rtk/index.ts Modified 10 10 import { isToolCallEventType }
from "@earendil-works/pi-coding-agent" ;
12 12 const TIMEOUT_MS
= 2_000 ;
13 + const COMMAND_PREFIX_END
= "# pi-command-prefix-end\n" ;
13 14 const MIN_MAJOR
= 0 ;
14 15 const MIN_MINOR
= 23 ;
45 46 return / ^ (?:env\s + ) ? RTK_DISABLED=1(?:\s |$ )/ u .
test (trimmed);
49 + export function splitCommandPrefix (command
: string )
: {
53 + const end
= command.
indexOf (COMMAND_PREFIX_END);
54 + if (end
< 0 )
return { prefix:
"" , command };
55 + const bodyStart
= end
+ COMMAND_PREFIX_END.
length ;
57 + prefix: command.
slice (
0 , bodyStart),
58 + command: command.
slice (bodyStart),
48 62 function hasShellOperators (command
: string )
: boolean {
49 63 return /[|;<>`] | \$\( | && | \|\|/ u .
test (command);
217 231 localFallbackRewrite,
219 233 shouldSkipCommand,
234 + splitCommandPrefix,
222 237 export default async function rtk (pi
: ExtensionAPI , ctx
?: ExtensionContext ) {
242 257 pi.
on (
"tool_call" ,
async (event, ctx)
=> {
243 258 if (
! isToolCallEventType (
"bash" ,
event ))
return ;
244 - const command
= event .
input .command;
245 - if (
typeof command
!== "string" || shouldSkipCommand (command))
return ;
246 - const outcome
= await rewriteCommand (pi, command, ctx.signal);
259 + const framed
= splitCommandPrefix (
event .
input .command);
260 + if (
shouldSkipCommand (framed.command))
return ;
261 + const outcome
= await rewriteCommand (pi, framed.command, ctx.signal);
247 262 const rewritten
= 248 263 outcome.kind
=== "rewrite" 249 264 ? outcome.command
250 265 : outcome.kind
=== "fallback" 251 - ? localFallbackRewrite (command)
266 + ? localFallbackRewrite (framed.command)
253 268 if (rewritten
&& (findPathSupported
|| ! isFindRewrite (rewritten)))
254 - event .
input .command
= rewritten;
269 + event .
input .command
= framed.
prefix + rewritten;