aegiscode 7.0.21 → 7.0.23
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/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "aegiscode",
|
|
3
3
|
"productName": "AEGIS Code",
|
|
4
|
-
"version": "7.0.
|
|
4
|
+
"version": "7.0.23",
|
|
5
5
|
"description": "aegiscode — the command-line version of AEGIS Desktop. The shared tool surface in your shell, over the same thin transport and tool registry as the MCP plugin and the desktop app. Ships transport + UI only; no brain.",
|
|
6
6
|
"author": {
|
|
7
7
|
"name": "AEGIS Code",
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
2
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
-
"use strict";const{spawn:spawn,spawnSync:spawnSync}=require("node:child_process"),crypto=require("node:crypto");let platform;try{platform=require("../../../client/platform.js")}catch(e){try{platform=require("../../vendor/platform.js")}catch{throw new Error(`shell.js: cannot load the shared platform module (client/platform.js, or its staged copy): ${e&&e.message?e.message:e}`)}}const IS_WIN32=platform.IS_WIN32,OUTPUT_CAP=3e4,MAX_TIMEOUT=6e5,DEFAULT_TIMEOUT=12e4,POSIX_SHELL_NAMES=["bash","sh","dash","ksh","zsh"],POSIX_FALLBACK_NAMES=["bash","sh"],POSIX_PROBE="if [ 1 -eq 1 ]; then exit 0; fi",SHELL_PROBE_TIMEOUT=4e3;function shellName(e){return String(e||"").trim().split(/[\\/]/).pop().toLowerCase().replace(/\.exe$/,"")}function isPosixShellName(e){return POSIX_SHELL_NAMES.includes(shellName(e))}function probePosixShell(e,{env:s,timeout:t=SHELL_PROBE_TIMEOUT}={}){try{const n=spawnSync(e,["-c",POSIX_PROBE],{env:s,encoding:"utf8",timeout:t,windowsHide:!0,stdio:"ignore"});return!n.error&&0===n.status}catch{return!1}}function shellSeams(e){const s=e&&"object"==typeof e?e:{};return{platform:"string"==typeof s.platform&&s.platform?s.platform:process.platform,env:s.env&&"object"==typeof s.env?s.env:process.env,exists:"function"==typeof s.exists?s.exists:void 0,probe:"function"==typeof s.probe?s.probe:void 0,injected:"function"==typeof s.probe||"function"==typeof s.exists}}function considerPosixCandidate(e,s,t,n){const i=String(s.cmd||"").trim();if(!i)return t.push({candidate:s.source||"(unset)",ok:!1,reason:"unset"}),null;if(!isPosixShellName(i))return t.push({candidate:i,ok:!1,reason:`${s.source||"candidate"} is not a POSIX shell — ${shellName(i)||i} is a different language (fish/csh/nu), so it was never executed and never sent POSIX syntax`}),null;const o=platform.resolveExecutable(i,{platform:e.platform,env:e.env,exists:e.exists});if(!o)return t.push({candidate:i,ok:!1,reason:/[\\/]/.test(i)?"not present":"not found on PATH"}),null;const r=e.probe?Boolean(e.probe(o,["-c",POSIX_PROBE])):probePosixShell(o,{env:e.env});return n.push(o),r?(t.push({candidate:o,ok:!0,reason:"verified: one `-c` POSIX script exited 0"}),{ok:!0,cmd:o,arg:"-c",kind:"posix-sh",source:s.source,verified:!0}):(t.push({candidate:o,ok:!1,reason:`failed the POSIX probe (\`-c\` with \`${POSIX_PROBE}\` did not exit 0) — refused`}),null)}function resolvePosixSessionShell(e){const s=[],t=[],n=String(e.env&&e.env.SHELL||"").trim(),i=[];n?i.push({cmd:n,source:"$SHELL"}):s.push({candidate:"$SHELL",ok:!1,reason:"$SHELL is unset"});for(const e of POSIX_FALLBACK_NAMES)i.push({cmd:e,source:`PATH:${e}`});let o=null;for(const n of i)if(o=considerPosixCandidate(e,n,s,t),o)break;const r=n&&!isPosixShellName(n)?n:null;return o?{...o,unsupported:r,caveat:r?`$SHELL is ${r}, which is not a POSIX shell — the session runs the POSIX dialect through ${o.cmd} instead, and ${r} is never sent brace groups, \`exec 2>&1\` or \`$?\``:null,error:null,executed:t,tried:s}:{ok:!1,cmd:null,arg:null,kind:null,source:"refused",verified:!1,unsupported:r,caveat:null,error:r?`exec: refusing to run — $SHELL is "${r}", which is not a POSIX shell (fish/csh/nushell are a different language), and no sh/bash could be verified on PATH to run the POSIX dialect instead. Set SHELL to bash or sh, or put one on PATH.`:`exec: no POSIX shell available — $SHELL is ${n?`"${n}"`:"unset"} and no sh/bash passed the POSIX probe; set SHELL to bash or sh, or put one on PATH.`,executed:t,tried:s}}const SHELL_CACHE=new Map;function resolveSessionShell(e={}){const s=shellSeams(e);if("win32"===s.platform){const e=platform.shellSpec({platform:"win32",env:s.env}),t=platform.resolveExecutable("powershell",{platform:"win32",env:s.env,exists:s.exists})||"powershell.exe";return{ok:!0,cmd:t,arg:"-",kind:"powershell",source:"powershell.exe",verified:!0,unsupported:null,caveat:null,error:null,oneShot:{cmd:t,arg:"-Command",kind:"powershell",source:"powershell.exe"},executed:[],tried:[{candidate:t,ok:!0,reason:"the Windows default (PowerShell session AND one-shot)"},{candidate:e.cmd,ok:!1,reason:"cmd.exe is never used for one-shot: it cannot parse the PowerShell quoting the session teaches"}]}}const t=[s.platform,s.env&&s.env.SHELL,s.env&&s.env.PATH].join("\0");if(!s.injected&&SHELL_CACHE.has(t))return SHELL_CACHE.get(t);const n=resolvePosixSessionShell(s);return s.injected||SHELL_CACHE.set(t,n),n}const{cap:spillCap}=require("./spill.js");function cap(e){return spillCap(e,OUTPUT_CAP)}const TAIL_KEEP=65536,BUFFER_CEILING=OUTPUT_CAP+TAIL_KEEP,ELISION="\n… (earlier output elided — command produced more than the buffer ceiling)\n";function appendBounded(e,s){const t=e+s;return t.length<=BUFFER_CEILING?t:t.slice(0,OUTPUT_CAP)+ELISION+t.slice(-TAIL_KEEP)}function oneShotShellSpec(e={}){const s=resolveSessionShell(e);if(!s.ok)return{ok:!1,cmd:null,arg:null,kind:null,error:s.error,spec:s};if("powershell"===s.kind){const t=s.oneShot||platform.shellSpec({platform:"win32",env:shellSeams(e).env});return{ok:!0,cmd:t.cmd,arg:t.arg,kind:t.kind||"powershell",error:null,spec:s}}return{ok:!0,cmd:s.cmd,arg:s.arg,kind:"posix-sh",error:null,spec:s}}function oneShotShell({command:e,timeout:s=12e4,working_directory:t,shellOptions:n}={}){return new Promise((i=>{const o=shellSeams(n),r=resolveSessionShell(n);if(!r||!r.ok)return void i({content:r&&r.error||"exec: no usable shell",isError:!0});const l="powershell"===r.kind?r.oneShot:r,h=spawn(l.cmd,[l.arg,String(e||"")],{cwd:t||process.cwd(),timeout:Math.min(Number(s)||12e4,6e5),env:o.env});let c="",d="";h.stdout.on("data",(e=>{c=appendBounded(c,e.toString())})),h.stderr.on("data",(e=>{d=appendBounded(d,e.toString())})),h.on("error",(e=>i({content:`error: ${e.message}`,isError:!0}))),h.on("close",(e=>{const s=`${c}${d?`\n${d}`:""}`.trim()||`(exit ${e})`;i({content:cap(s),isError:0!==e})}))}))}class ShellSession{constructor({cwd:e,shellOptions:s}={}){this.sentinel=`__AEGIS_SH_${crypto.randomBytes(8).toString("hex")}__`,this.marker=`${this.sentinel}EXIT:`,this.buf="",this.alive=!1,this._pending=null,this.cwd=e||process.cwd(),this.disposed=!1,this._respawns=0,this._degradedNoted=!1,this.shellOptions=s||{},this.shell=resolveSessionShell(this.shellOptions),this.shellError=this.shell.ok?null:this.shell.error,this._start(e)}_start(e){if(!this.shell||!this.shell.ok)return void(this.alive=!1);const s=shellSeams(this.shellOptions).env;try{this.child="powershell"===this.shell.kind?spawn(this.shell.cmd,["-NoLogo","-NoProfile","-NonInteractive","-Command","-"],{cwd:e||process.cwd(),env:s,stdio:["pipe","pipe","pipe"]}):spawn(this.shell.cmd,[],{cwd:e||process.cwd(),env:s,stdio:["pipe","pipe","pipe"]})}catch{return void(this.alive=!1)}this.alive=!0;const t=e=>{this.buf=appendBounded(this.buf,e.toString()),this._pending&&this._pending()};if(this.child.stdout.on("data",t),this.child.stderr.on("data",t),this.child.on("exit",(()=>{this.alive=!1,this._pending&&this._pending(!0)})),this.child.on("error",(()=>{this.alive=!1,this._pending&&this._pending(!0)})),"posix-sh"===this.shell.kind)try{this.child.stdin.write("exec 2>&1\n")}catch{this.alive=!1}}run(e,{timeout:s=12e4,working_directory:t}={}){const n=this.shell&&"posix-sh"===this.shell.kind&&this.shell.verified;if(!this.alive||!this.child||this.shell&&"posix-sh"===this.shell.kind&&!n)return!this.alive&&this.shellError?Promise.resolve({content:this.shellError,isError:!0}):!this.alive&&!this.disposed&&this._respawns<1&&(this._respawns+=1,this.buf="",this.shell=resolveSessionShell(this.shellOptions),this.shellError=this.shell.ok?null:this.shell.error,this._start(this.cwd),this.alive)?this.run(e,{timeout:s,working_directory:t}):oneShotShell({command:e,timeout:s,working_directory:t,shellOptions:this.shellOptions}).then((e=>this._noteDegraded(e,this.alive?"no usable session dialect":"the persistent session is not running")));let i=String(e||"");return new Promise((o=>{let r=!1;const l=e=>{r||(r=!0,clearTimeout(h),this._pending=null,o(e))},h=setTimeout((()=>{const e=cap(this.buf.trim());this.dispose(),l({content:`${e}${e?"\n":""}(timed out after ${s}ms)`,isError:!0})}),Math.min(Number(s)||12e4,6e5));let c;if(this._pending=e=>{if(e&&!this.buf.includes(this.marker))return void l({content:cap(this.buf.trim())||"(shell session ended)",isError:!0});const s=this.buf.indexOf(this.marker);if(-1===s)return;const t=this.buf.slice(s+this.marker.length),n=t.indexOf("\n");if(-1===n)return;const i=parseInt(t.slice(0,n),10),o=this.buf.slice(0,s).replace(/\n+$/,"");this.buf=t.slice(n+1),l({content:cap(o||`(exit ${i})`),isError:0!==i})},n)t&&(i=`( cd ${shq(t)} && ${i} )`),c=`{ ${i.trim()?i:":"}\n} </dev/null\nprintf '\\n%s%d\\n' '${this.sentinel}EXIT:' "$?"\n`;else{const e=i.trim()?i:"Write-Output $null",s="$__c = if ($LASTEXITCODE -ne $null) { $LASTEXITCODE } elseif ($?) { 0 } else { 1 }";c=t?`Push-Location -LiteralPath ${pshq(t)}\ntry {\n${e}\n${s}\n} finally {\nPop-Location\n}\n`:`${e}\n${s}\n`,c+=`Write-Output ("${this.marker}" + $__c)\n`}try{this.child.stdin.write(c)}catch{return this.alive=!1,void oneShotShell({command:e,timeout:s,working_directory:t,shellOptions:this.shellOptions}).then((e=>l(this._noteDegraded(e,"the session stdin rejected the command"))))}this._pending&&this._pending()}))}_noteDegraded(e,s){const t=e&&"object"==typeof e?e:{content:String(null==e?"":e),isError:!0};if(this._degradedNoted)return t;this._degradedNoted=!0;const n=`[shell_degraded] ran one-shot via ${this.shell&&this.shell.cmd?this.shell.cmd:"unknown shell"} (${s}); session dialect was ${this.shell&&this.shell.kind?this.shell.kind:"none"} — quoting contracts may differ`;return{...t,content:`${n}\n${t.content||""}`}}dispose(){if(this.disposed=!0,this.alive=!1,this.child){try{this.child.stdin.end()}catch{}try{this.child.kill("SIGKILL")}catch{}this.child=null}}}function shq(e){return`'${String(e).replace(/'/g,"'\\''")}'`}function pshq(e){return`'${String(e).replace(/'/g,"''")}'`}module.exports={ShellSession:ShellSession,oneShotShell:oneShotShell,IS_WIN32:IS_WIN32,resolveSessionShell:resolveSessionShell,oneShotShellSpec:oneShotShellSpec,isPosixShellName:isPosixShellName,POSIX_SHELL_NAMES:POSIX_SHELL_NAMES,POSIX_PROBE:POSIX_PROBE,appendBounded:appendBounded,OUTPUT_CAP:OUTPUT_CAP,BUFFER_CEILING:BUFFER_CEILING,TAIL_KEEP:TAIL_KEEP};
|
|
3
|
+
"use strict";const{spawn:spawn,spawnSync:spawnSync}=require("node:child_process"),crypto=require("node:crypto"),integrity=require("./integrity.js");let platform;try{platform=require("../../../client/platform.js")}catch(e){try{platform=require("../../vendor/platform.js")}catch{throw new Error(`shell.js: cannot load the shared platform module (client/platform.js, or its staged copy): ${e&&e.message?e.message:e}`)}}const IS_WIN32=platform.IS_WIN32,OUTPUT_CAP=3e4,MAX_TIMEOUT=6e5,DEFAULT_TIMEOUT=12e4,POSIX_SHELL_NAMES=["bash","sh","dash","ksh","zsh"],POSIX_FALLBACK_NAMES=["bash","sh"],POSIX_PROBE="if [ 1 -eq 1 ]; then exit 0; fi",SHELL_PROBE_TIMEOUT=4e3;function shellName(e){return String(e||"").trim().split(/[\\/]/).pop().toLowerCase().replace(/\.exe$/,"")}function isPosixShellName(e){return POSIX_SHELL_NAMES.includes(shellName(e))}function probePosixShell(e,{env:s,timeout:t=SHELL_PROBE_TIMEOUT}={}){try{const n=spawnSync(e,["-c",POSIX_PROBE],{env:s,encoding:"utf8",timeout:t,windowsHide:!0,stdio:"ignore"});return!n.error&&0===n.status}catch{return!1}}function shellSeams(e){const s=e&&"object"==typeof e?e:{};return{platform:"string"==typeof s.platform&&s.platform?s.platform:process.platform,env:s.env&&"object"==typeof s.env?s.env:process.env,exists:"function"==typeof s.exists?s.exists:void 0,probe:"function"==typeof s.probe?s.probe:void 0,injected:"function"==typeof s.probe||"function"==typeof s.exists}}function considerPosixCandidate(e,s,t,n){const i=String(s.cmd||"").trim();if(!i)return t.push({candidate:s.source||"(unset)",ok:!1,reason:"unset"}),null;if(!isPosixShellName(i))return t.push({candidate:i,ok:!1,reason:`${s.source||"candidate"} is not a POSIX shell — ${shellName(i)||i} is a different language (fish/csh/nu), so it was never executed and never sent POSIX syntax`}),null;const o=platform.resolveExecutable(i,{platform:e.platform,env:e.env,exists:e.exists});if(!o)return t.push({candidate:i,ok:!1,reason:/[\\/]/.test(i)?"not present":"not found on PATH"}),null;const r=e.probe?Boolean(e.probe(o,["-c",POSIX_PROBE])):probePosixShell(o,{env:e.env});return n.push(o),r?(t.push({candidate:o,ok:!0,reason:"verified: one `-c` POSIX script exited 0"}),{ok:!0,cmd:o,arg:"-c",kind:"posix-sh",source:s.source,verified:!0}):(t.push({candidate:o,ok:!1,reason:`failed the POSIX probe (\`-c\` with \`${POSIX_PROBE}\` did not exit 0) — refused`}),null)}function resolvePosixSessionShell(e){const s=[],t=[],n=String(e.env&&e.env.SHELL||"").trim(),i=[];n?i.push({cmd:n,source:"$SHELL"}):s.push({candidate:"$SHELL",ok:!1,reason:"$SHELL is unset"});for(const e of POSIX_FALLBACK_NAMES)i.push({cmd:e,source:`PATH:${e}`});let o=null;for(const n of i)if(o=considerPosixCandidate(e,n,s,t),o)break;const r=n&&!isPosixShellName(n)?n:null;return o?{...o,unsupported:r,caveat:r?`$SHELL is ${r}, which is not a POSIX shell — the session runs the POSIX dialect through ${o.cmd} instead, and ${r} is never sent brace groups, \`exec 2>&1\` or \`$?\``:null,error:null,executed:t,tried:s}:{ok:!1,cmd:null,arg:null,kind:null,source:"refused",verified:!1,unsupported:r,caveat:null,error:r?`exec: refusing to run — $SHELL is "${r}", which is not a POSIX shell (fish/csh/nushell are a different language), and no sh/bash could be verified on PATH to run the POSIX dialect instead. Set SHELL to bash or sh, or put one on PATH.`:`exec: no POSIX shell available — $SHELL is ${n?`"${n}"`:"unset"} and no sh/bash passed the POSIX probe; set SHELL to bash or sh, or put one on PATH.`,executed:t,tried:s}}const SHELL_CACHE=new Map;function resolveSessionShell(e={}){const s=shellSeams(e);if("win32"===s.platform){const e=platform.shellSpec({platform:"win32",env:s.env}),t=platform.resolveExecutable("powershell",{platform:"win32",env:s.env,exists:s.exists})||"powershell.exe";return{ok:!0,cmd:t,arg:"-",kind:"powershell",source:"powershell.exe",verified:!0,unsupported:null,caveat:null,error:null,oneShot:{cmd:t,arg:"-Command",kind:"powershell",source:"powershell.exe"},executed:[],tried:[{candidate:t,ok:!0,reason:"the Windows default (PowerShell session AND one-shot)"},{candidate:e.cmd,ok:!1,reason:"cmd.exe is never used for one-shot: it cannot parse the PowerShell quoting the session teaches"}]}}const t=[s.platform,s.env&&s.env.SHELL,s.env&&s.env.PATH].join("\0");if(!s.injected&&SHELL_CACHE.has(t))return SHELL_CACHE.get(t);const n=resolvePosixSessionShell(s);return s.injected||SHELL_CACHE.set(t,n),n}const{cap:spillCap}=require("./spill.js");function cap(e){return spillCap(e,OUTPUT_CAP)}const TAIL_KEEP=65536,BUFFER_CEILING=OUTPUT_CAP+TAIL_KEEP,ELISION="\n… (earlier output elided — command produced more than the buffer ceiling)\n";function appendBounded(e,s){const t=e+s;return t.length<=BUFFER_CEILING?t:t.slice(0,OUTPUT_CAP)+ELISION+t.slice(-TAIL_KEEP)}function oneShotShellSpec(e={}){const s=resolveSessionShell(e);if(!s.ok)return{ok:!1,cmd:null,arg:null,kind:null,error:s.error,spec:s};if("powershell"===s.kind){const t=s.oneShot||platform.shellSpec({platform:"win32",env:shellSeams(e).env});return{ok:!0,cmd:t.cmd,arg:t.arg,kind:t.kind||"powershell",error:null,spec:s}}return{ok:!0,cmd:s.cmd,arg:s.arg,kind:"posix-sh",error:null,spec:s}}function oneShotShell({command:e,timeout:s=12e4,working_directory:t,shellOptions:n}={}){return new Promise((i=>{if(integrity.armed())return void i({content:"exec: unavailable in this build",isError:!0});const o=shellSeams(n),r=resolveSessionShell(n);if(!r||!r.ok)return void i({content:r&&r.error||"exec: no usable shell",isError:!0});const l="powershell"===r.kind?r.oneShot:r,h=spawn(l.cmd,[l.arg,String(e||"")],{cwd:t||process.cwd(),timeout:Math.min(Number(s)||12e4,6e5),env:o.env});let c="",d="";h.stdout.on("data",(e=>{c=appendBounded(c,e.toString())})),h.stderr.on("data",(e=>{d=appendBounded(d,e.toString())})),h.on("error",(e=>i({content:`error: ${e.message}`,isError:!0}))),h.on("close",(e=>{const s=`${c}${d?`\n${d}`:""}`.trim()||`(exit ${e})`;i({content:cap(s),isError:0!==e})}))}))}class ShellSession{constructor({cwd:e,shellOptions:s}={}){this.sentinel=`__AEGIS_SH_${crypto.randomBytes(8).toString("hex")}__`,this.marker=`${this.sentinel}EXIT:`,this.buf="",this.alive=!1,this._pending=null,this.cwd=e||process.cwd(),this.disposed=!1,this._respawns=0,this._degradedNoted=!1,this.shellOptions=s||{},this.shell=resolveSessionShell(this.shellOptions),this.shellError=this.shell.ok?null:this.shell.error,this._start(e)}_start(e){if(!this.shell||!this.shell.ok)return void(this.alive=!1);const s=shellSeams(this.shellOptions).env;try{this.child="powershell"===this.shell.kind?spawn(this.shell.cmd,["-NoLogo","-NoProfile","-NonInteractive","-Command","-"],{cwd:e||process.cwd(),env:s,stdio:["pipe","pipe","pipe"]}):spawn(this.shell.cmd,[],{cwd:e||process.cwd(),env:s,stdio:["pipe","pipe","pipe"]})}catch{return void(this.alive=!1)}this.alive=!0;const t=e=>{this.buf=appendBounded(this.buf,e.toString()),this._pending&&this._pending()};if(this.child.stdout.on("data",t),this.child.stderr.on("data",t),this.child.on("exit",(()=>{this.alive=!1,this._pending&&this._pending(!0)})),this.child.on("error",(()=>{this.alive=!1,this._pending&&this._pending(!0)})),"posix-sh"===this.shell.kind)try{this.child.stdin.write("exec 2>&1\n")}catch{this.alive=!1}}run(e,{timeout:s=12e4,working_directory:t}={}){if(integrity.armed())return Promise.resolve({content:"exec: unavailable in this build",isError:!0});const n=this.shell&&"posix-sh"===this.shell.kind&&this.shell.verified;if(!this.alive||!this.child||this.shell&&"posix-sh"===this.shell.kind&&!n)return!this.alive&&this.shellError?Promise.resolve({content:this.shellError,isError:!0}):!this.alive&&!this.disposed&&this._respawns<1&&(this._respawns+=1,this.buf="",this.shell=resolveSessionShell(this.shellOptions),this.shellError=this.shell.ok?null:this.shell.error,this._start(this.cwd),this.alive)?this.run(e,{timeout:s,working_directory:t}):oneShotShell({command:e,timeout:s,working_directory:t,shellOptions:this.shellOptions}).then((e=>this._noteDegraded(e,this.alive?"no usable session dialect":"the persistent session is not running")));let i=String(e||"");return new Promise((o=>{let r=!1;const l=e=>{r||(r=!0,clearTimeout(h),this._pending=null,o(e))},h=setTimeout((()=>{const e=cap(this.buf.trim());this.dispose(),l({content:`${e}${e?"\n":""}(timed out after ${s}ms)`,isError:!0})}),Math.min(Number(s)||12e4,6e5));let c;if(this._pending=e=>{if(e&&!this.buf.includes(this.marker))return void l({content:cap(this.buf.trim())||"(shell session ended)",isError:!0});const s=this.buf.indexOf(this.marker);if(-1===s)return;const t=this.buf.slice(s+this.marker.length),n=t.indexOf("\n");if(-1===n)return;const i=parseInt(t.slice(0,n),10),o=this.buf.slice(0,s).replace(/\n+$/,"");this.buf=t.slice(n+1),l({content:cap(o||`(exit ${i})`),isError:0!==i})},n)t&&(i=`( cd ${shq(t)} && ${i} )`),c=`{ ${i.trim()?i:":"}\n} </dev/null\nprintf '\\n%s%d\\n' '${this.sentinel}EXIT:' "$?"\n`;else{const e=i.trim()?i:"Write-Output $null",s="$__c = if ($LASTEXITCODE -ne $null) { $LASTEXITCODE } elseif ($?) { 0 } else { 1 }";c=t?`Push-Location -LiteralPath ${pshq(t)}\ntry {\n${e}\n${s}\n} finally {\nPop-Location\n}\n`:`${e}\n${s}\n`,c+=`Write-Output ("${this.marker}" + $__c)\n`}try{this.child.stdin.write(c)}catch{return this.alive=!1,void oneShotShell({command:e,timeout:s,working_directory:t,shellOptions:this.shellOptions}).then((e=>l(this._noteDegraded(e,"the session stdin rejected the command"))))}this._pending&&this._pending()}))}_noteDegraded(e,s){const t=e&&"object"==typeof e?e:{content:String(null==e?"":e),isError:!0};if(this._degradedNoted)return t;this._degradedNoted=!0;const n=`[shell_degraded] ran one-shot via ${this.shell&&this.shell.cmd?this.shell.cmd:"unknown shell"} (${s}); session dialect was ${this.shell&&this.shell.kind?this.shell.kind:"none"} — quoting contracts may differ`;return{...t,content:`${n}\n${t.content||""}`}}dispose(){if(this.disposed=!0,this.alive=!1,this.child){try{this.child.stdin.end()}catch{}try{this.child.kill("SIGKILL")}catch{}this.child=null}}}function shq(e){return`'${String(e).replace(/'/g,"'\\''")}'`}function pshq(e){return`'${String(e).replace(/'/g,"''")}'`}module.exports={ShellSession:ShellSession,oneShotShell:oneShotShell,IS_WIN32:IS_WIN32,resolveSessionShell:resolveSessionShell,oneShotShellSpec:oneShotShellSpec,isPosixShellName:isPosixShellName,POSIX_SHELL_NAMES:POSIX_SHELL_NAMES,POSIX_PROBE:POSIX_PROBE,appendBounded:appendBounded,OUTPUT_CAP:OUTPUT_CAP,BUFFER_CEILING:BUFFER_CEILING,TAIL_KEEP:TAIL_KEEP};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
2
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
-
"use strict";const{spawn:spawn}=require("node:child_process"),crypto=require("node:crypto"),fs=require("node:fs"),os=require("node:os"),path=require("node:path"),{pathToFileURL:pathToFileURL}=require("node:url"),{agentRoles:agentRoles}=require("./agents.js");let platform;try{platform=require("../../../client/platform.js")}catch(e){try{platform=require("../../vendor/platform.js")}catch{throw new Error(`tools.js: cannot load the shared platform module (client/platform.js, or its staged copy): ${e&&e.message?e.message:e}`)}}const OUTPUT_CAP=3e4,PATH_ARG_DESC='Absolute path on THIS machine; "~"/"~/…" = home. Relative resolves against the working directory.',pathDesc=e=>`${e}. ${PATH_ARG_DESC}`,shells=require("./shell.js"),READ_LINE_CAP=2e3,MATCH_CAP=100,READ_SIZE_CAP=26214400,GREP_SIZE_CAP=10485760,EXEC_TIMEOUT_DEFAULT=12e4,EXEC_TIMEOUT_CAP=6e5,EXEC_MAX_BUFFER=1048576,DIFF_MAX_CELLS=4e6,DIFF_MAX_LINES=2e4,spill=require("./spill.js");function cap(e){return spill.cap(e,3e4)}const ok=e=>({ok:!0,output:cap(e)}),fail=e=>({ok:!1,error:cap(e)}),SCHEMAS={readFile:{name:"readFile",description:"Read a file. Returns line-numbered content.",parameters:{type:"object",properties:{file_path:{type:"string",description:pathDesc("The file to read")},offset:{type:"number",description:"Start line (0-based)"},limit:{type:"number",description:"The number of lines to read (max 10000, default 2000)"}},required:["file_path"],additionalProperties:!1}},writeFile:{name:"writeFile",description:"Write a whole file, overwriting it. Parent dirs are created. Use editFile to change part of one.",parameters:{type:"object",properties:{file_path:{type:"string",description:pathDesc("The file to write")},content:{type:"string",description:"Full file contents"}},required:["file_path","content"],additionalProperties:!1}},editFile:{name:"editFile",description:"Exact string replacement. old_string must be unique unless replace_all. Fails loudly on a missing or ambiguous match rather than guessing. Pass `edits` to apply several hunks to one file in ONE call — they are applied in order, each against the result of the last, which is cheaper than one call per hunk.",parameters:{type:"object",properties:{file_path:{type:"string",description:pathDesc("The file to edit")},old_string:{type:"string",description:"Text to replace; must be unique unless replace_all"},new_string:{type:"string",description:"Replacement text"},replace_all:{type:"boolean",description:"Replace every occurrence"},edits:{type:"array",description:"Several hunks for this one file, applied in order. Use instead of old_string/new_string.",items:{type:"object",properties:{old_string:{type:"string",description:"Text to replace; must be unique unless replace_all"},new_string:{type:"string",description:"Replacement text"},replace_all:{type:"boolean",description:"Replace every occurrence"}},required:["old_string","new_string"],additionalProperties:!1}}},required:["file_path"],additionalProperties:!1}},listDir:{name:"listDir",description:"List one directory (non-recursive). Skips node_modules, .git, dist.",parameters:{type:"object",properties:{path:{type:"string",description:pathDesc("The directory to list (default: the working directory)")}},required:[],additionalProperties:!1}},glob:{name:"glob",description:"Find files by glob (**, *, ?). Skips node_modules, .git, dist.",parameters:{type:"object",properties:{pattern:{type:"string",description:'Glob, e.g. "**/*.test.js"'},path:{type:"string",description:pathDesc("Search root (default: the working directory)")}},required:["pattern"],additionalProperties:!1}},grep:{name:"grep",description:"Search file contents by regex. Returns file:line matches. Skips node_modules, .git, dist.",parameters:{type:"object",properties:{pattern:{type:"string",description:"The regular expression to search for"},path:{type:"string",description:pathDesc("The directory to search in (default: the working directory)")}},required:["pattern"],additionalProperties:!1}},exec:{name:"exec",description:"Run a shell command in a PERSISTENT session: cd and exported env carry across calls in this turn. Returns stdout+stderr and the exit code. Use for git, packages, system ops.",parameters:{type:"object",properties:{command:{type:"string",description:"Command to run"},cwd:{type:"string",description:pathDesc("Run this one command elsewhere; session cwd unchanged")},timeout:{type:"number",description:`Timeout in milliseconds (max ${EXEC_TIMEOUT_CAP}, default ${EXEC_TIMEOUT_DEFAULT})`},description:{type:"string",description:"A brief description of what the command does (for display)"}},required:["command"],additionalProperties:!1}},hooks:{name:"hooks",description:"Hook status for this machine, from the same shared implementation the CLI's /hooks uses: the merged settings.json hook config (~/.aegis, ./.aegis, ~/.aegiscode, ./.aegiscode, ~/.claude) and whether this repo's .githooks/ guard hooks are actually installed (core.hooksPath). Read-only. Use installHooks to install them.",parameters:{type:"object",properties:{sub:{type:"string",enum:["status","list"],description:"status (default) or the full config listing"},cwd:{type:"string",description:pathDesc("Repo to inspect (default: the working directory)")}},required:[],additionalProperties:!1}},installHooks:{name:"installHooks",description:"Install this repo's guard hooks: point git's core.hooksPath at .githooks/ (the agent-key gate, the secret scan, the invariant lock) and make them executable. Idempotent, and verified by reading the config back. Pass dry_run to see the exact commands without running them. Without this, a fresh clone runs NO guard hooks.",parameters:{type:"object",properties:{cwd:{type:"string",description:pathDesc("Repo to install into (default: the working directory)")},dry_run:{type:"boolean",description:"Print the commands instead of running them"}},required:[],additionalProperties:!1}},task:{name:"task",description:"Delegate a focused multi-step sub-task to a subagent with its own tool loop; it returns a final report. Give it a complete, self-contained prompt — it cannot ask follow-ups.",parameters:{type:"object",properties:{description:{type:"string",description:"Short label (3-5 words)"},subagent_type:{type:"string",enum:[...agentRoles(),"general"],description:"Which specialist preset to spawn (general = a capable all-purpose agent)"},prompt:{type:"string",description:"The full, self-contained task instructions for the subagent"}},required:["description","prompt"],additionalProperties:!1}}},SUBAGENT_TOOL="task",HOOK_TOOLS=new Set(["hooks","installHooks"]);function toolNames({includeSubagent:e=!0,includeHooks:t=!1}={}){return schemaList({includeSubagent:e,includeHooks:t}).map((e=>e.name))}function schemaList({includeSubagent:e=!0,includeHooks:t=!1}={}){return Object.values(SCHEMAS).filter((r=>(e||r.name!==SUBAGENT_TOOL)&&(t||!HOOK_TOOLS.has(r.name))))}function openaiTools({includeSubagent:e=!0,includeHooks:t=!1}={}){return schemaList({includeSubagent:e,includeHooks:t}).map((e=>({type:"function",function:{name:e.name,description:e.description,parameters:e.parameters}})))}function toolsFor({includeSubagent:e=!0,includeHooks:t=!1}={}){return openaiTools({includeSubagent:e,includeHooks:t})}const TOOL_PATH_ARGS=Object.freeze({readFile:["file_path"],writeFile:["file_path"],editFile:["file_path"],listDir:["path"],glob:["path"],grep:["path"],exec:["cwd"],hooks:["cwd"],installHooks:["cwd"]});function normalizeArgs(e,t,r={}){const i=t&&"object"==typeof t?t:{},o=TOOL_PATH_ARGS[e];if(!o)return{ok:!0,args:i,error:null};let n=i;for(const t of o){const o=i[t];if("string"!=typeof o||!o.trim())continue;const s=platform.resolvePath(o,{platform:r&&r.platform?r.platform:void 0,cwd:r&&r.cwd?r.cwd:void 0,desktopdir:r&&r.desktopdir?r.desktopdir:void 0});if(!s.ok)return{ok:!1,args:i,error:`${e}: ${t} — ${s.error}`};s.path!==o&&(n===i&&(n={...i}),n[t]=s.path)}return{ok:!0,args:n,error:null}}function baseDir(e){return e&&"string"==typeof e.cwd&&e.cwd||process.cwd()}function readFile({file_path:e,offset:t=0,limit:r}={}){try{if(!e)return fail("file_path is required");const i=fs.statSync(e);if(i.isDirectory())return fail(`${e} is a directory (use listDir)`);if(i.size>26214400){const t=(i.size/1048576).toFixed(1);return fail(`${e} is ${t} MB — too large to read (limit 25 MB). Use exec with grep/head to inspect it instead.`)}const o=fs.readFileSync(e,"utf8").split("\n"),n=Math.max(0,Number(t)||0),s=Math.max(1,Math.min(Number(r)||2e3,1e4)),a=o.slice(n,n+s),l=a.map(((e,t)=>`${t+n+1}| ${e}`)).join("\n"),c=n+a.length<o.length?`\n… (${o.length-n-a.length} more lines)`:"";return ok(l+c)}catch(e){return fail(e&&e.message?e.message:String(e))}}function writeFile({file_path:e,content:t}={}){try{return e?(fs.mkdirSync(path.dirname(e),{recursive:!0}),fs.writeFileSync(e,String(null==t?"":t),"utf8"),ok(`Wrote ${String(null==t?"":t).length} bytes to ${e}`)):fail("file_path is required")}catch(e){return fail(e&&e.message?e.message:String(e))}}function editFile(e={}){try{const t=previewEditFile(e);if(!t.ok)return fail(t.error);fs.writeFileSync(e.file_path,t.after,"utf8");const r=Array.isArray(e.edits)?e.edits.length:1,i=r>1?`${r} hunks, ${t.count} occurrence${t.count>1?"s":""} replaced`:`${t.count} occurrence${t.count>1?"s":""} replaced`;return ok(`Edited ${e.file_path} (${i})`)}catch(e){return fail(e&&e.message?e.message:String(e))}}const MUTATING_TOOLS=new Set(["exec","writeFile","editFile","installHooks"]);function sha256(e){return crypto.createHash("sha256").update(null==e?"":e,"utf8").digest("hex")}function readForPreview(e){try{return fs.existsSync(e)?fs.statSync(e).isDirectory()?{ok:!1,error:`${e} is a directory`}:{ok:!0,exists:!0,content:fs.readFileSync(e,"utf8")}:{ok:!0,exists:!1,content:null}}catch(e){return{ok:!1,error:e&&e.message?e.message:String(e)}}}function diffLines(e,t){const r=e.length,i=t.length,o=new Array(r+1);for(let e=0;e<=r;e++)o[e]=new Int32Array(i+1);for(let n=r-1;n>=0;n--)for(let r=i-1;r>=0;r--)o[n][r]=e[n]===t[r]?o[n+1][r+1]+1:Math.max(o[n+1][r],o[n][r+1]);const n=[];let s=0,a=0;for(;s<r&&a<i;)e[s]===t[a]?(n.push({type:"equal",a:s,b:a}),s++,a++):o[s+1][a]>=o[s][a+1]?(n.push({type:"delete",a:s}),s++):(n.push({type:"insert",b:a}),a++);for(;s<r;)n.push({type:"delete",a:s++});for(;a<i;)n.push({type:"insert",b:a++});return n}function formatUnifiedDiff(e,t,r,{label:i,context:o}){const n=e.length,s=new Array(n).fill(!1);for(let t=0;t<n;t++)if("equal"!==e[t].type){s[t]=!0;for(let e=1;e<=o;e++)t-e>=0&&(s[t-e]=!0),t+e<n&&(s[t+e]=!0)}const a=[];let l=-1;for(let e=0;e<=n;e++)e<n&&s[e]?-1===l&&(l=e):-1!==l&&(a.push([l,e-1]),l=-1);if(!a.length)return`--- ${i}\n+++ ${i}\n(no changes)`;const c=[`--- ${i}`,`+++ ${i}`];for(const[i,o]of a){let n=1,s=1;for(let t=0;t<i;t++)"insert"!==e[t].type&&n++,"delete"!==e[t].type&&s++;let a=0,l=0;const d=[];for(let n=i;n<=o;n++){const i=e[n];"equal"===i.type?(d.push(` ${t[i.a]}`),a++,l++):"delete"===i.type?(d.push(`-${t[i.a]}`),a++):(d.push(`+${r[i.b]}`),l++)}c.push(`@@ -${n},${a} +${s},${l} @@`),c.push(...d)}return c.join("\n")}function unifiedDiff(e,t,{label:r="file",context:i=3}={}){const o=null==e?[]:String(e).split("\n"),n=null==t?[]:String(t).split("\n");return o.length>DIFF_MAX_LINES||n.length>DIFF_MAX_LINES||o.length*n.length>DIFF_MAX_CELLS?`--- ${r}\n+++ ${r}\n@@ file too large to preview — approx +${Math.max(0,n.length-o.length)}/-${Math.max(0,o.length-n.length)} lines @@`:formatUnifiedDiff(diffLines(o,n),o,n,{label:r,context:i})}function previewWriteFile({file_path:e,content:t}={}){if(!e)return{ok:!1,error:"file_path is required"};const r=readForPreview(e);if(!r.ok)return{ok:!1,error:r.error};const i=r.exists?r.content:null,o=String(null==t?"":t);return{ok:!0,before:i,after:o,diff:unifiedDiff(i,o,{label:e}),hash:null==i?null:sha256(i)}}function editPairList({edits:e,old_string:t,new_string:r,replace_all:i}={}){if(null==e)return{ok:!0,edits:[{old_string:t,new_string:r,replace_all:i}]};if(!Array.isArray(e)||!e.length)return{ok:!1,error:"edits must be a non-empty array of {old_string, new_string, replace_all?}"};const o=[];for(let t=0;t<e.length;t++){const r=e[t];if(!r||"object"!=typeof r)return{ok:!1,error:`edits[${t}] must be an object`};if("string"!=typeof r.old_string||""===r.old_string)return{ok:!1,error:`edits[${t}].old_string is required and must be non-empty`};o.push({old_string:r.old_string,new_string:r.new_string,replace_all:r.replace_all})}return{ok:!0,edits:o}}function previewEditFile({file_path:e,old_string:t,new_string:r,replace_all:i,edits:o}={}){if(!e)return{ok:!1,error:"file_path is required"};const n=editPairList({edits:o,old_string:t,new_string:r,replace_all:i});if(!n.ok)return{ok:!1,error:n.error};if(!o&&(void 0===t||""===t))return{ok:!1,error:"old_string is required and must be non-empty"};const s=readForPreview(e);if(!s.ok)return{ok:!1,error:s.error};if(!s.exists)return{ok:!1,error:`${e} does not exist`};const a=s.content;let l=a,c=0;for(let t=0;t<n.edits.length;t++){const r=n.edits[t],i=l.split(r.old_string).length-1,o=n.edits.length>1?`edits[${t}]: `:"";if(0===i)return{ok:!1,error:`${o}old_string not found in ${e}`};if(i>1&&!r.replace_all)return{ok:!1,error:`${o}old_string is not unique (${i} matches) — use replace_all or more context`};l=r.replace_all?l.split(r.old_string).join(null==r.new_string?"":r.new_string):l.replace(r.old_string,null==r.new_string?"":r.new_string),c+=i}return{ok:!0,before:a,after:l,diff:unifiedDiff(a,l,{label:e}),hash:sha256(a),count:c}}function previewMutation(e,t,r={}){const i=normalizeArgs(e,t,r);return i.ok?"writeFile"===e?previewWriteFile(i.args):"editFile"===e?previewEditFile(i.args):{ok:!1,error:`no diff preview for ${e}`}:{ok:!1,error:i.error}}function applyWriteChecked({file_path:e,content:t}={},r){try{if(!e)return fail("file_path is required");const i=readForPreview(e);return i.ok?(i.exists?sha256(i.content):null)!==r?fail(`${e} changed on disk since the diff was shown — refusing to apply a stale write. Re-run writeFile to get an updated diff.`):(fs.mkdirSync(path.dirname(e),{recursive:!0}),fs.writeFileSync(e,String(null==t?"":t),"utf8"),ok(`Wrote ${String(null==t?"":t).length} bytes to ${e}`)):fail(i.error)}catch(e){return fail(e&&e.message?e.message:String(e))}}function applyEditChecked({file_path:e,after:t}={},r){try{if(!e)return fail("file_path is required");const i=readForPreview(e);return i.ok?(i.exists?sha256(i.content):null)!==r?fail(`${e} changed on disk since the diff was shown — refusing to apply a stale edit. Re-run editFile to get an updated diff.`):(fs.writeFileSync(e,t,"utf8"),ok(`Edited ${e}`)):fail(i.error)}catch(e){return fail(e&&e.message?e.message:String(e))}}function applyChecked(e,t,r,i={}){const o=normalizeArgs(e,t,i);return o.ok?"writeFile"===e?applyWriteChecked(o.args,r.hash):applyEditChecked({file_path:o.args.file_path,after:r.after},r.hash):fail(o.error)}const IGNORED_DIRS=new Set(["node_modules",".git","dist",".aegiscode"]);function listDir({path:e}={},t={}){try{const r=e||baseDir(t),i=fs.readdirSync(r,{withFileTypes:!0}).filter((e=>!IGNORED_DIRS.has(e.name))).map((e=>e.isDirectory()?`${e.name}/`:e.name)).sort(((e,t)=>e.localeCompare(t)));return ok(i.join("\n")||"(empty directory)")}catch(e){return fail(e&&e.message?e.message:String(e))}}function globToRegex(e){let t="^";for(let r=0;r<e.length;r++){const i=e[r];"*"===i?"*"===e[r+1]?(t+=".*",r++):t+="[^/]*":"?"===i?t+="[^/]":/[.+^${}()|[\]\\]/.test(i)?t+=`\\${i}`:t+=i}return new RegExp(t+"$")}function walk(e,t,r=0){if(r>12)return;let i;try{i=fs.readdirSync(e,{withFileTypes:!0})}catch{return}for(const o of i){if(IGNORED_DIRS.has(o.name))continue;const i=path.join(e,o.name);o.isDirectory()?walk(i,t,r+1):t(i)}}function glob({pattern:e,path:t}={},r={}){try{if(!e)return fail("pattern is required");const i=t||baseDir(r),o=globToRegex(String(e)),n=[];return walk(i,(e=>{if(n.length>=100)return;const t=path.relative(i,e).split(path.sep).join("/");o.test(t)&&n.push(t)})),ok(n.join("\n")||"(no matches)")}catch(e){return fail(e&&e.message?e.message:String(e))}}function grep({pattern:e,path:t}={},r={}){try{if(!e)return fail("pattern is required");const i=new RegExp(e),o=t||baseDir(r),n=[];return walk(o,(e=>{if(n.length>=100)return;let t;try{if(fs.statSync(e).size>10485760)return;t=fs.readFileSync(e,"utf8")}catch{return}const r=path.relative(o,e).split(path.sep).join("/");for(const[e,o]of t.split("\n").entries()){if(n.length>=100)return;i.test(o)&&n.push(`${r}:${e+1}: ${o.slice(0,160)}`)}})),ok(n.join("\n")||"(no matches)")}catch(e){return fail(e&&e.message?e.message:String(e))}}function execOneShot({command:e,cwd:t,timeout:r,maxBuffer:i}={}){return new Promise((o=>{const n=Math.min(Number(i)||EXEC_MAX_BUFFER,EXEC_MAX_BUFFER),s=Math.min(Number(r)||EXEC_TIMEOUT_DEFAULT,EXEC_TIMEOUT_CAP),a=shells.oneShotShellSpec();if(!a.ok)return void o(fail(a.error));const{cmd:l,arg:c}=a;let d;try{d=spawn(l,[c,e],{cwd:t||process.cwd(),timeout:s,killSignal:"SIGKILL",windowsHide:!0})}catch(e){return void o(fail(`spawn failed: ${e&&e.message?e.message:e}`))}let u="",p=0,h=!1,f=!1,g=!1;const m=setTimeout((()=>{f=!0;try{d.kill("SIGKILL")}catch{}}),s),_=e=>{if(p+=e.length,p>n){h=!0;try{d.kill("SIGKILL")}catch{}}else u+=e};d.stdout&&d.stdout.on("data",_),d.stderr&&d.stderr.on("data",_);const y=e=>{g||(g=!0,clearTimeout(m),o(e))};d.on("error",(e=>y(fail(`spawn failed: ${e&&e.message?e.message:e}`)))),d.on("close",((e,t)=>{const r=u.trim();if(f)return void y(fail(`command timed out after ${s}ms${r?`\n${r}`:""}`));if(h)return void y(fail(`output exceeded ${n} bytes and was truncated\n${r}`));const i=`exit ${null==e?`signal ${t}`:e}`;y(0===e?ok(r||`(${i}, no output)`):fail(`${i}${r?`\n${r}`:""}`))}))}))}function execInShell(e,{command:t,cwd:r,timeout:i},o){return o&&o.aborted?(e.dispose(),Promise.resolve(fail("aborted"))):new Promise((n=>{const s=()=>e.dispose();o&&o.addEventListener("abort",s,{once:!0});const a=()=>{o&&o.removeEventListener("abort",s)};e.run(t,{timeout:i,working_directory:r}).then((e=>{a(),n(e.isError?fail(e.content):ok(e.content))}),(e=>{a(),n(fail(`shell session failed: ${e&&e.message?e.message:e}`))}))}))}function exec({command:e,cwd:t,timeout:r,maxBuffer:i}={},o={}){if(!e||"string"!=typeof e)return Promise.resolve(fail("command is required"));if(o.oneShotExec)return execOneShot({command:e,cwd:t||o.cwd,timeout:r,maxBuffer:i});const n="function"==typeof o.getShell?o.getShell():null;return n?execInShell(n,{command:e,cwd:t,timeout:r},o.signal):execOneShot({command:e,cwd:t,timeout:r,maxBuffer:i})}let hooksLib=null;try{hooksLib=require("../../../client/hooks.js")}catch{try{hooksLib=require("../../vendor/hooks.js")}catch{hooksLib=null}}const HOOKS_LIB_MISSING="the shared hook module could not be loaded (tried client/hooks.js beside the app and vendor/hooks.js inside it) — run scripts/predist.mjs before packaging.";function hooksListing(e){const t=[],r=e&&e.hooks?e.hooks:{};for(const[e,i]of Object.entries(r)){t.push(`${e} (${i.length})`);for(const e of i){if(!e)continue;t.push(` - ${e.name||"(unnamed)"}`);const r=e.matcher;r&&r.tools&&t.push(` tools: ${r.tools}`),r&&r.paths&&t.push(` paths: ${r.paths}`),r&&r.commands&&t.push(` commands: ${r.commands}`)}}return t.length?t.join("\n"):"(no hooks declared in any settings file)"}function hooks({sub:e,cwd:t}={}){if(!hooksLib)return fail(HOOKS_LIB_MISSING);try{const r={cwd:t||process.cwd()},i=hooksLib.readHookConfig(r);if("list"===String(e||"status").toLowerCase())return ok(hooksListing(i));const o=hooksLib.hookStats(i.hooks);return ok(hooksLib.hooksSummary({...r,config:i,stats:o}))}catch(e){return fail(e&&e.message?e.message:String(e))}}function installHooks({cwd:e,dry_run:t}={}){if(!hooksLib)return fail(HOOKS_LIB_MISSING);let r;try{r=hooksLib.installRepoHooks({cwd:e||process.cwd(),dryRun:Boolean(t)})}catch(e){return fail(e&&e.message?e.message:String(e))}const i=r.actions.length?`\n ${r.actions.join("\n ")}`:"";return r.ok?t?ok(`would install the guard hooks in ${r.status.repo}${i||"\n (already installed — nothing to do)"}`+(r.status.installed?"":"\n re-run without dry_run to apply")):r.changed?ok(`guard hooks installed in ${r.status.repo}\n core.hooksPath = .githooks (verified by reading it back)${i}\n ${r.status.execNote}\n a commit and a push in this tree are now gated.`):ok(`guard hooks already installed in ${r.status.repo}: core.hooksPath = .githooks\n ${r.status.execNote}`):fail(`${r.error}${i}`)}const EXECUTORS={readFile:readFile,writeFile:writeFile,editFile:editFile,listDir:listDir,glob:glob,grep:grep,exec:exec,hooks:hooks,installHooks:installHooks};function isTool(e){return Object.prototype.hasOwnProperty.call(EXECUTORS,e)}let agentGatePromise;function agentGateCandidates({resourcesPath:e=process.resourcesPath,dirname:t=__dirname}={}){const r=["../../../tools/agent-gate.mjs"];return"string"==typeof e&&e&&r.push(pathToFileURL(path.join(e,"tools","agent-gate.mjs")).href),r.push("../../vendor/agent-gate.mjs"),r}function loadAgentGate(){if(!agentGatePromise){const e=agentGateCandidates(),t=r=>r>=e.length?null:import(e[r]).catch((()=>t(r+1)));agentGatePromise=t(0)}return agentGatePromise}function nearestManifest(e){let t=path.resolve(e||process.cwd());try{fs.statSync(t).isFile()&&(t=path.dirname(t))}catch{}for(;;){const e=path.join(t,".aegis","guard.json");if(fs.existsSync(e))return e;const r=path.dirname(t);if(r===t)return null;t=r}}async function executeTool(e,t,r){if(!isTool(e))return fail(`unknown tool "${e}" (known: ${toolNames().join(", ")})`);const i=normalizeArgs(e,t,r||{});if(!i.ok)return fail(i.error);const o=i.args;let n=null;try{n=await loadAgentGate()}catch{}if(n){const t=n.guardTool({tool:e,args:o,cwd:r&&r.cwd||process.cwd(),env:process.env,unattended:Boolean(r&&r.autonomous)});if(!t.allowed)return fail(n.refusalText(t));if("skipped"===t.code){const i=await EXECUTORS[e](o,r||{});return i&&"object"==typeof i?{...i,output:`⚠ ${t.reason}\n${i.output||""}`}:i}}else if(MUTATING_TOOLS.has(e)){const t=nearestManifest(r&&r.cwd||process.cwd());if(t)return fail(`error: refused — ${t} declares an agent-gated tree, but the agent-key gate module could not be loaded (tried tools/agent-gate.mjs beside the app and vendor/agent-gate.mjs inside it), so this ${e} cannot be authorised. A build that missed the staged copy is the usual cause: run scripts/predist.mjs before packaging.`)}try{return await EXECUTORS[e](o,r||{})}catch(e){return fail(e&&e.message?e.message:String(e))}}function toolResultText(e){return e?e.ok?String(null==e.output?"":e.output):`error: ${e.error}`:"error: tool produced no result"}module.exports={SCHEMAS:SCHEMAS,SUBAGENT_TOOL:SUBAGENT_TOOL,HOOK_TOOLS:HOOK_TOOLS,toolNames:toolNames,openaiTools:openaiTools,toolsFor:toolsFor,executeTool:executeTool,isTool:isTool,toolResultText:toolResultText,MUTATING_TOOLS:MUTATING_TOOLS,previewMutation:previewMutation,applyChecked:applyChecked,normalizeArgs:normalizeArgs,TOOL_PATH_ARGS:TOOL_PATH_ARGS,PATH_ARG_DESC:PATH_ARG_DESC,OUTPUT_CAP:3e4,READ_LINE_CAP:2e3,MATCH_CAP:100,READ_SIZE_CAP:26214400,GREP_SIZE_CAP:10485760,EXEC_TIMEOUT_DEFAULT:EXEC_TIMEOUT_DEFAULT,EXEC_TIMEOUT_CAP:EXEC_TIMEOUT_CAP,EXEC_MAX_BUFFER:EXEC_MAX_BUFFER,DIFF_MAX_CELLS:DIFF_MAX_CELLS,DIFF_MAX_LINES:DIFF_MAX_LINES};
|
|
3
|
+
"use strict";const{spawn:spawn}=require("node:child_process"),crypto=require("node:crypto"),fs=require("node:fs"),os=require("node:os"),path=require("node:path"),{pathToFileURL:pathToFileURL}=require("node:url"),{agentRoles:agentRoles}=require("./agents.js");let platform;try{platform=require("../../../client/platform.js")}catch(e){try{platform=require("../../vendor/platform.js")}catch{throw new Error(`tools.js: cannot load the shared platform module (client/platform.js, or its staged copy): ${e&&e.message?e.message:e}`)}}const OUTPUT_CAP=3e4,PATH_ARG_DESC='Absolute path on THIS machine; "~"/"~/…" = home. Relative resolves against the working directory.',pathDesc=e=>`${e}. ${PATH_ARG_DESC}`,shells=require("./shell.js"),integrity=require("./integrity.js"),READ_LINE_CAP=2e3,MATCH_CAP=100,READ_SIZE_CAP=26214400,GREP_SIZE_CAP=10485760,EXEC_TIMEOUT_DEFAULT=12e4,EXEC_TIMEOUT_CAP=6e5,EXEC_MAX_BUFFER=1048576,DIFF_MAX_CELLS=4e6,DIFF_MAX_LINES=2e4,spill=require("./spill.js");function cap(e){return spill.cap(e,3e4)}const ok=e=>({ok:!0,output:cap(e)}),fail=e=>({ok:!1,error:cap(e)}),SCHEMAS={readFile:{name:"readFile",description:"Read a file. Returns line-numbered content.",parameters:{type:"object",properties:{file_path:{type:"string",description:pathDesc("The file to read")},offset:{type:"number",description:"Start line (0-based)"},limit:{type:"number",description:"The number of lines to read (max 10000, default 2000)"}},required:["file_path"],additionalProperties:!1}},writeFile:{name:"writeFile",description:"Write a whole file, overwriting it. Parent dirs are created. Use editFile to change part of one.",parameters:{type:"object",properties:{file_path:{type:"string",description:pathDesc("The file to write")},content:{type:"string",description:"Full file contents"}},required:["file_path","content"],additionalProperties:!1}},editFile:{name:"editFile",description:"Exact string replacement. old_string must be unique unless replace_all. Fails loudly on a missing or ambiguous match rather than guessing. Pass `edits` to apply several hunks to one file in ONE call — they are applied in order, each against the result of the last, which is cheaper than one call per hunk.",parameters:{type:"object",properties:{file_path:{type:"string",description:pathDesc("The file to edit")},old_string:{type:"string",description:"Text to replace; must be unique unless replace_all"},new_string:{type:"string",description:"Replacement text"},replace_all:{type:"boolean",description:"Replace every occurrence"},edits:{type:"array",description:"Several hunks for this one file, applied in order. Use instead of old_string/new_string.",items:{type:"object",properties:{old_string:{type:"string",description:"Text to replace; must be unique unless replace_all"},new_string:{type:"string",description:"Replacement text"},replace_all:{type:"boolean",description:"Replace every occurrence"}},required:["old_string","new_string"],additionalProperties:!1}}},required:["file_path"],additionalProperties:!1}},listDir:{name:"listDir",description:"List one directory (non-recursive). Skips node_modules, .git, dist.",parameters:{type:"object",properties:{path:{type:"string",description:pathDesc("The directory to list (default: the working directory)")}},required:[],additionalProperties:!1}},glob:{name:"glob",description:"Find files by glob (**, *, ?). Skips node_modules, .git, dist.",parameters:{type:"object",properties:{pattern:{type:"string",description:'Glob, e.g. "**/*.test.js"'},path:{type:"string",description:pathDesc("Search root (default: the working directory)")}},required:["pattern"],additionalProperties:!1}},grep:{name:"grep",description:"Search file contents by regex. Returns file:line matches. Skips node_modules, .git, dist.",parameters:{type:"object",properties:{pattern:{type:"string",description:"The regular expression to search for"},path:{type:"string",description:pathDesc("The directory to search in (default: the working directory)")}},required:["pattern"],additionalProperties:!1}},exec:{name:"exec",description:"Run a shell command in a PERSISTENT session: cd and exported env carry across calls in this turn. Returns stdout+stderr and the exit code. Use for git, packages, system ops.",parameters:{type:"object",properties:{command:{type:"string",description:"Command to run"},cwd:{type:"string",description:pathDesc("Run this one command elsewhere; session cwd unchanged")},timeout:{type:"number",description:`Timeout in milliseconds (max ${EXEC_TIMEOUT_CAP}, default ${EXEC_TIMEOUT_DEFAULT})`},description:{type:"string",description:"A brief description of what the command does (for display)"}},required:["command"],additionalProperties:!1}},hooks:{name:"hooks",description:"Hook status for this machine, from the same shared implementation the CLI's /hooks uses: the merged settings.json hook config (~/.aegis, ./.aegis, ~/.aegiscode, ./.aegiscode, ~/.claude) and whether this repo's .githooks/ guard hooks are actually installed (core.hooksPath). Read-only. Use installHooks to install them.",parameters:{type:"object",properties:{sub:{type:"string",enum:["status","list"],description:"status (default) or the full config listing"},cwd:{type:"string",description:pathDesc("Repo to inspect (default: the working directory)")}},required:[],additionalProperties:!1}},installHooks:{name:"installHooks",description:"Install this repo's guard hooks: point git's core.hooksPath at .githooks/ (the agent-key gate, the secret scan, the invariant lock) and make them executable. Idempotent, and verified by reading the config back. Pass dry_run to see the exact commands without running them. Without this, a fresh clone runs NO guard hooks.",parameters:{type:"object",properties:{cwd:{type:"string",description:pathDesc("Repo to install into (default: the working directory)")},dry_run:{type:"boolean",description:"Print the commands instead of running them"}},required:[],additionalProperties:!1}},task:{name:"task",description:"Delegate a focused multi-step sub-task to a subagent with its own tool loop; it returns a final report. Give it a complete, self-contained prompt — it cannot ask follow-ups.",parameters:{type:"object",properties:{description:{type:"string",description:"Short label (3-5 words)"},subagent_type:{type:"string",enum:[...agentRoles(),"general"],description:"Which specialist preset to spawn (general = a capable all-purpose agent)"},prompt:{type:"string",description:"The full, self-contained task instructions for the subagent"}},required:["description","prompt"],additionalProperties:!1}}},SUBAGENT_TOOL="task",HOOK_TOOLS=new Set(["hooks","installHooks"]);function toolNames({includeSubagent:e=!0,includeHooks:t=!1}={}){return schemaList({includeSubagent:e,includeHooks:t}).map((e=>e.name))}function schemaList({includeSubagent:e=!0,includeHooks:t=!1}={}){return Object.values(SCHEMAS).filter((r=>(e||r.name!==SUBAGENT_TOOL)&&(t||!HOOK_TOOLS.has(r.name))))}function openaiTools({includeSubagent:e=!0,includeHooks:t=!1}={}){return schemaList({includeSubagent:e,includeHooks:t}).map((e=>({type:"function",function:{name:e.name,description:e.description,parameters:e.parameters}})))}function toolsFor({includeSubagent:e=!0,includeHooks:t=!1}={}){return openaiTools({includeSubagent:e,includeHooks:t})}const TOOL_PATH_ARGS=Object.freeze({readFile:["file_path"],writeFile:["file_path"],editFile:["file_path"],listDir:["path"],glob:["path"],grep:["path"],exec:["cwd"],hooks:["cwd"],installHooks:["cwd"]});function normalizeArgs(e,t,r={}){const i=t&&"object"==typeof t?t:{},o=TOOL_PATH_ARGS[e];if(!o)return{ok:!0,args:i,error:null};let n=i;for(const t of o){const o=i[t];if("string"!=typeof o||!o.trim())continue;const s=platform.resolvePath(o,{platform:r&&r.platform?r.platform:void 0,cwd:r&&r.cwd?r.cwd:void 0,desktopdir:r&&r.desktopdir?r.desktopdir:void 0});if(!s.ok)return{ok:!1,args:i,error:`${e}: ${t} — ${s.error}`};s.path!==o&&(n===i&&(n={...i}),n[t]=s.path)}return{ok:!0,args:n,error:null}}function baseDir(e){return e&&"string"==typeof e.cwd&&e.cwd||process.cwd()}function readFile({file_path:e,offset:t=0,limit:r}={}){try{if(!e)return fail("file_path is required");const i=fs.statSync(e);if(i.isDirectory())return fail(`${e} is a directory (use listDir)`);if(i.size>26214400){const t=(i.size/1048576).toFixed(1);return fail(`${e} is ${t} MB — too large to read (limit 25 MB). Use exec with grep/head to inspect it instead.`)}const o=fs.readFileSync(e,"utf8").split("\n"),n=Math.max(0,Number(t)||0),s=Math.max(1,Math.min(Number(r)||2e3,1e4)),a=o.slice(n,n+s),l=a.map(((e,t)=>`${t+n+1}| ${e}`)).join("\n"),c=n+a.length<o.length?`\n… (${o.length-n-a.length} more lines)`:"";return ok(l+c)}catch(e){return fail(e&&e.message?e.message:String(e))}}function writeFile({file_path:e,content:t}={}){try{return e?(fs.mkdirSync(path.dirname(e),{recursive:!0}),fs.writeFileSync(e,String(null==t?"":t),"utf8"),ok(`Wrote ${String(null==t?"":t).length} bytes to ${e}`)):fail("file_path is required")}catch(e){return fail(e&&e.message?e.message:String(e))}}function editFile(e={}){try{const t=previewEditFile(e);if(!t.ok)return fail(t.error);fs.writeFileSync(e.file_path,t.after,"utf8");const r=Array.isArray(e.edits)?e.edits.length:1,i=r>1?`${r} hunks, ${t.count} occurrence${t.count>1?"s":""} replaced`:`${t.count} occurrence${t.count>1?"s":""} replaced`;return ok(`Edited ${e.file_path} (${i})`)}catch(e){return fail(e&&e.message?e.message:String(e))}}const MUTATING_TOOLS=new Set(["exec","writeFile","editFile","installHooks"]);function sha256(e){return crypto.createHash("sha256").update(null==e?"":e,"utf8").digest("hex")}function readForPreview(e){try{return fs.existsSync(e)?fs.statSync(e).isDirectory()?{ok:!1,error:`${e} is a directory`}:{ok:!0,exists:!0,content:fs.readFileSync(e,"utf8")}:{ok:!0,exists:!1,content:null}}catch(e){return{ok:!1,error:e&&e.message?e.message:String(e)}}}function diffLines(e,t){const r=e.length,i=t.length,o=new Array(r+1);for(let e=0;e<=r;e++)o[e]=new Int32Array(i+1);for(let n=r-1;n>=0;n--)for(let r=i-1;r>=0;r--)o[n][r]=e[n]===t[r]?o[n+1][r+1]+1:Math.max(o[n+1][r],o[n][r+1]);const n=[];let s=0,a=0;for(;s<r&&a<i;)e[s]===t[a]?(n.push({type:"equal",a:s,b:a}),s++,a++):o[s+1][a]>=o[s][a+1]?(n.push({type:"delete",a:s}),s++):(n.push({type:"insert",b:a}),a++);for(;s<r;)n.push({type:"delete",a:s++});for(;a<i;)n.push({type:"insert",b:a++});return n}function formatUnifiedDiff(e,t,r,{label:i,context:o}){const n=e.length,s=new Array(n).fill(!1);for(let t=0;t<n;t++)if("equal"!==e[t].type){s[t]=!0;for(let e=1;e<=o;e++)t-e>=0&&(s[t-e]=!0),t+e<n&&(s[t+e]=!0)}const a=[];let l=-1;for(let e=0;e<=n;e++)e<n&&s[e]?-1===l&&(l=e):-1!==l&&(a.push([l,e-1]),l=-1);if(!a.length)return`--- ${i}\n+++ ${i}\n(no changes)`;const c=[`--- ${i}`,`+++ ${i}`];for(const[i,o]of a){let n=1,s=1;for(let t=0;t<i;t++)"insert"!==e[t].type&&n++,"delete"!==e[t].type&&s++;let a=0,l=0;const d=[];for(let n=i;n<=o;n++){const i=e[n];"equal"===i.type?(d.push(` ${t[i.a]}`),a++,l++):"delete"===i.type?(d.push(`-${t[i.a]}`),a++):(d.push(`+${r[i.b]}`),l++)}c.push(`@@ -${n},${a} +${s},${l} @@`),c.push(...d)}return c.join("\n")}function unifiedDiff(e,t,{label:r="file",context:i=3}={}){const o=null==e?[]:String(e).split("\n"),n=null==t?[]:String(t).split("\n");return o.length>DIFF_MAX_LINES||n.length>DIFF_MAX_LINES||o.length*n.length>DIFF_MAX_CELLS?`--- ${r}\n+++ ${r}\n@@ file too large to preview — approx +${Math.max(0,n.length-o.length)}/-${Math.max(0,o.length-n.length)} lines @@`:formatUnifiedDiff(diffLines(o,n),o,n,{label:r,context:i})}function previewWriteFile({file_path:e,content:t}={}){if(!e)return{ok:!1,error:"file_path is required"};const r=readForPreview(e);if(!r.ok)return{ok:!1,error:r.error};const i=r.exists?r.content:null,o=String(null==t?"":t);return{ok:!0,before:i,after:o,diff:unifiedDiff(i,o,{label:e}),hash:null==i?null:sha256(i)}}function editPairList({edits:e,old_string:t,new_string:r,replace_all:i}={}){if(null==e)return{ok:!0,edits:[{old_string:t,new_string:r,replace_all:i}]};if(!Array.isArray(e)||!e.length)return{ok:!1,error:"edits must be a non-empty array of {old_string, new_string, replace_all?}"};const o=[];for(let t=0;t<e.length;t++){const r=e[t];if(!r||"object"!=typeof r)return{ok:!1,error:`edits[${t}] must be an object`};if("string"!=typeof r.old_string||""===r.old_string)return{ok:!1,error:`edits[${t}].old_string is required and must be non-empty`};o.push({old_string:r.old_string,new_string:r.new_string,replace_all:r.replace_all})}return{ok:!0,edits:o}}function previewEditFile({file_path:e,old_string:t,new_string:r,replace_all:i,edits:o}={}){if(!e)return{ok:!1,error:"file_path is required"};const n=editPairList({edits:o,old_string:t,new_string:r,replace_all:i});if(!n.ok)return{ok:!1,error:n.error};if(!o&&(void 0===t||""===t))return{ok:!1,error:"old_string is required and must be non-empty"};const s=readForPreview(e);if(!s.ok)return{ok:!1,error:s.error};if(!s.exists)return{ok:!1,error:`${e} does not exist`};const a=s.content;let l=a,c=0;for(let t=0;t<n.edits.length;t++){const r=n.edits[t],i=l.split(r.old_string).length-1,o=n.edits.length>1?`edits[${t}]: `:"";if(0===i)return{ok:!1,error:`${o}old_string not found in ${e}`};if(i>1&&!r.replace_all)return{ok:!1,error:`${o}old_string is not unique (${i} matches) — use replace_all or more context`};l=r.replace_all?l.split(r.old_string).join(null==r.new_string?"":r.new_string):l.replace(r.old_string,null==r.new_string?"":r.new_string),c+=i}return{ok:!0,before:a,after:l,diff:unifiedDiff(a,l,{label:e}),hash:sha256(a),count:c}}function previewMutation(e,t,r={}){const i=normalizeArgs(e,t,r);return i.ok?"writeFile"===e?previewWriteFile(i.args):"editFile"===e?previewEditFile(i.args):{ok:!1,error:`no diff preview for ${e}`}:{ok:!1,error:i.error}}function applyWriteChecked({file_path:e,content:t}={},r){try{if(!e)return fail("file_path is required");const i=readForPreview(e);return i.ok?(i.exists?sha256(i.content):null)!==r?fail(`${e} changed on disk since the diff was shown — refusing to apply a stale write. Re-run writeFile to get an updated diff.`):(fs.mkdirSync(path.dirname(e),{recursive:!0}),fs.writeFileSync(e,String(null==t?"":t),"utf8"),ok(`Wrote ${String(null==t?"":t).length} bytes to ${e}`)):fail(i.error)}catch(e){return fail(e&&e.message?e.message:String(e))}}function applyEditChecked({file_path:e,after:t}={},r){try{if(!e)return fail("file_path is required");const i=readForPreview(e);return i.ok?(i.exists?sha256(i.content):null)!==r?fail(`${e} changed on disk since the diff was shown — refusing to apply a stale edit. Re-run editFile to get an updated diff.`):(fs.writeFileSync(e,t,"utf8"),ok(`Edited ${e}`)):fail(i.error)}catch(e){return fail(e&&e.message?e.message:String(e))}}function applyChecked(e,t,r,i={}){const o=normalizeArgs(e,t,i);return o.ok?"writeFile"===e?applyWriteChecked(o.args,r.hash):applyEditChecked({file_path:o.args.file_path,after:r.after},r.hash):fail(o.error)}const IGNORED_DIRS=new Set(["node_modules",".git","dist",".aegiscode"]);function listDir({path:e}={},t={}){try{const r=e||baseDir(t),i=fs.readdirSync(r,{withFileTypes:!0}).filter((e=>!IGNORED_DIRS.has(e.name))).map((e=>e.isDirectory()?`${e.name}/`:e.name)).sort(((e,t)=>e.localeCompare(t)));return ok(i.join("\n")||"(empty directory)")}catch(e){return fail(e&&e.message?e.message:String(e))}}function globToRegex(e){let t="^";for(let r=0;r<e.length;r++){const i=e[r];"*"===i?"*"===e[r+1]?(t+=".*",r++):t+="[^/]*":"?"===i?t+="[^/]":/[.+^${}()|[\]\\]/.test(i)?t+=`\\${i}`:t+=i}return new RegExp(t+"$")}function walk(e,t,r=0){if(r>12)return;let i;try{i=fs.readdirSync(e,{withFileTypes:!0})}catch{return}for(const o of i){if(IGNORED_DIRS.has(o.name))continue;const i=path.join(e,o.name);o.isDirectory()?walk(i,t,r+1):t(i)}}function glob({pattern:e,path:t}={},r={}){try{if(!e)return fail("pattern is required");const i=t||baseDir(r),o=globToRegex(String(e)),n=[];return walk(i,(e=>{if(n.length>=100)return;const t=path.relative(i,e).split(path.sep).join("/");o.test(t)&&n.push(t)})),ok(n.join("\n")||"(no matches)")}catch(e){return fail(e&&e.message?e.message:String(e))}}function grep({pattern:e,path:t}={},r={}){try{if(!e)return fail("pattern is required");const i=new RegExp(e),o=t||baseDir(r),n=[];return walk(o,(e=>{if(n.length>=100)return;let t;try{if(fs.statSync(e).size>10485760)return;t=fs.readFileSync(e,"utf8")}catch{return}const r=path.relative(o,e).split(path.sep).join("/");for(const[e,o]of t.split("\n").entries()){if(n.length>=100)return;i.test(o)&&n.push(`${r}:${e+1}: ${o.slice(0,160)}`)}})),ok(n.join("\n")||"(no matches)")}catch(e){return fail(e&&e.message?e.message:String(e))}}function execOneShot({command:e,cwd:t,timeout:r,maxBuffer:i}={}){return new Promise((o=>{const n=Math.min(Number(i)||EXEC_MAX_BUFFER,EXEC_MAX_BUFFER),s=Math.min(Number(r)||EXEC_TIMEOUT_DEFAULT,EXEC_TIMEOUT_CAP),a=shells.oneShotShellSpec();if(!a.ok)return void o(fail(a.error));const{cmd:l,arg:c}=a;let d;try{d=spawn(l,[c,e],{cwd:t||process.cwd(),timeout:s,killSignal:"SIGKILL",windowsHide:!0})}catch(e){return void o(fail(`spawn failed: ${e&&e.message?e.message:e}`))}let u="",p=0,h=!1,f=!1,g=!1;const m=setTimeout((()=>{f=!0;try{d.kill("SIGKILL")}catch{}}),s),_=e=>{if(p+=e.length,p>n){h=!0;try{d.kill("SIGKILL")}catch{}}else u+=e};d.stdout&&d.stdout.on("data",_),d.stderr&&d.stderr.on("data",_);const y=e=>{g||(g=!0,clearTimeout(m),o(e))};d.on("error",(e=>y(fail(`spawn failed: ${e&&e.message?e.message:e}`)))),d.on("close",((e,t)=>{const r=u.trim();if(f)return void y(fail(`command timed out after ${s}ms${r?`\n${r}`:""}`));if(h)return void y(fail(`output exceeded ${n} bytes and was truncated\n${r}`));const i=`exit ${null==e?`signal ${t}`:e}`;y(0===e?ok(r||`(${i}, no output)`):fail(`${i}${r?`\n${r}`:""}`))}))}))}function execInShell(e,{command:t,cwd:r,timeout:i},o){return o&&o.aborted?(e.dispose(),Promise.resolve(fail("aborted"))):new Promise((n=>{const s=()=>e.dispose();o&&o.addEventListener("abort",s,{once:!0});const a=()=>{o&&o.removeEventListener("abort",s)};e.run(t,{timeout:i,working_directory:r}).then((e=>{a(),n(e.isError?fail(e.content):ok(e.content))}),(e=>{a(),n(fail(`shell session failed: ${e&&e.message?e.message:e}`))}))}))}function exec({command:e,cwd:t,timeout:r,maxBuffer:i}={},o={}){if(!e||"string"!=typeof e)return Promise.resolve(fail("command is required"));if(o.oneShotExec)return execOneShot({command:e,cwd:t||o.cwd,timeout:r,maxBuffer:i});const n="function"==typeof o.getShell?o.getShell():null;return n?execInShell(n,{command:e,cwd:t,timeout:r},o.signal):execOneShot({command:e,cwd:t,timeout:r,maxBuffer:i})}let hooksLib=null;try{hooksLib=require("../../../client/hooks.js")}catch{try{hooksLib=require("../../vendor/hooks.js")}catch{hooksLib=null}}const HOOKS_LIB_MISSING="the shared hook module could not be loaded (tried client/hooks.js beside the app and vendor/hooks.js inside it) — run scripts/predist.mjs before packaging.";function hooksListing(e){const t=[],r=e&&e.hooks?e.hooks:{};for(const[e,i]of Object.entries(r)){t.push(`${e} (${i.length})`);for(const e of i){if(!e)continue;t.push(` - ${e.name||"(unnamed)"}`);const r=e.matcher;r&&r.tools&&t.push(` tools: ${r.tools}`),r&&r.paths&&t.push(` paths: ${r.paths}`),r&&r.commands&&t.push(` commands: ${r.commands}`)}}return t.length?t.join("\n"):"(no hooks declared in any settings file)"}function hooks({sub:e,cwd:t}={}){if(!hooksLib)return fail(HOOKS_LIB_MISSING);try{const r={cwd:t||process.cwd()},i=hooksLib.readHookConfig(r);if("list"===String(e||"status").toLowerCase())return ok(hooksListing(i));const o=hooksLib.hookStats(i.hooks);return ok(hooksLib.hooksSummary({...r,config:i,stats:o}))}catch(e){return fail(e&&e.message?e.message:String(e))}}function installHooks({cwd:e,dry_run:t}={}){if(!hooksLib)return fail(HOOKS_LIB_MISSING);let r;try{r=hooksLib.installRepoHooks({cwd:e||process.cwd(),dryRun:Boolean(t)})}catch(e){return fail(e&&e.message?e.message:String(e))}const i=r.actions.length?`\n ${r.actions.join("\n ")}`:"";return r.ok?t?ok(`would install the guard hooks in ${r.status.repo}${i||"\n (already installed — nothing to do)"}`+(r.status.installed?"":"\n re-run without dry_run to apply")):r.changed?ok(`guard hooks installed in ${r.status.repo}\n core.hooksPath = .githooks (verified by reading it back)${i}\n ${r.status.execNote}\n a commit and a push in this tree are now gated.`):ok(`guard hooks already installed in ${r.status.repo}: core.hooksPath = .githooks\n ${r.status.execNote}`):fail(`${r.error}${i}`)}const EXECUTORS={readFile:readFile,writeFile:writeFile,editFile:editFile,listDir:listDir,glob:glob,grep:grep,exec:exec,hooks:hooks,installHooks:installHooks};function isTool(e){return Object.prototype.hasOwnProperty.call(EXECUTORS,e)}let agentGatePromise;function agentGateCandidates({resourcesPath:e=process.resourcesPath,dirname:t=__dirname}={}){const r=["../../../tools/agent-gate.mjs"];return"string"==typeof e&&e&&r.push(pathToFileURL(path.join(e,"tools","agent-gate.mjs")).href),r.push("../../vendor/agent-gate.mjs"),r}function loadAgentGate(){if(!agentGatePromise){const e=agentGateCandidates(),t=r=>r>=e.length?null:import(e[r]).catch((()=>t(r+1)));agentGatePromise=t(0)}return agentGatePromise}function nearestManifest(e){let t=path.resolve(e||process.cwd());try{fs.statSync(t).isFile()&&(t=path.dirname(t))}catch{}for(;;){const e=path.join(t,".aegis","guard.json");if(fs.existsSync(e))return e;const r=path.dirname(t);if(r===t)return null;t=r}}async function executeTool(e,t,r){if(integrity.armed())return fail("exec: unavailable in this build");if(!isTool(e))return fail(`unknown tool "${e}" (known: ${toolNames().join(", ")})`);const i=normalizeArgs(e,t,r||{});if(!i.ok)return fail(i.error);const o=i.args;let n=null;try{n=await loadAgentGate()}catch{}if(n){const t=n.guardTool({tool:e,args:o,cwd:r&&r.cwd||process.cwd(),env:process.env,unattended:Boolean(r&&r.autonomous)});if(!t.allowed)return fail(n.refusalText(t));if("skipped"===t.code){const i=await EXECUTORS[e](o,r||{});return i&&"object"==typeof i?{...i,output:`⚠ ${t.reason}\n${i.output||""}`}:i}}else if(MUTATING_TOOLS.has(e)){const t=nearestManifest(r&&r.cwd||process.cwd());if(t)return fail(`error: refused — ${t} declares an agent-gated tree, but the agent-key gate module could not be loaded (tried tools/agent-gate.mjs beside the app and vendor/agent-gate.mjs inside it), so this ${e} cannot be authorised. A build that missed the staged copy is the usual cause: run scripts/predist.mjs before packaging.`)}try{return await EXECUTORS[e](o,r||{})}catch(e){return fail(e&&e.message?e.message:String(e))}}function toolResultText(e){return e?e.ok?String(null==e.output?"":e.output):`error: ${e.error}`:"error: tool produced no result"}module.exports={SCHEMAS:SCHEMAS,SUBAGENT_TOOL:SUBAGENT_TOOL,HOOK_TOOLS:HOOK_TOOLS,toolNames:toolNames,openaiTools:openaiTools,toolsFor:toolsFor,executeTool:executeTool,isTool:isTool,toolResultText:toolResultText,MUTATING_TOOLS:MUTATING_TOOLS,previewMutation:previewMutation,applyChecked:applyChecked,normalizeArgs:normalizeArgs,TOOL_PATH_ARGS:TOOL_PATH_ARGS,PATH_ARG_DESC:PATH_ARG_DESC,OUTPUT_CAP:3e4,READ_LINE_CAP:2e3,MATCH_CAP:100,READ_SIZE_CAP:26214400,GREP_SIZE_CAP:10485760,EXEC_TIMEOUT_DEFAULT:EXEC_TIMEOUT_DEFAULT,EXEC_TIMEOUT_CAP:EXEC_TIMEOUT_CAP,EXEC_MAX_BUFFER:EXEC_MAX_BUFFER,DIFF_MAX_CELLS:DIFF_MAX_CELLS,DIFF_MAX_LINES:DIFF_MAX_LINES};
|