aegis-desktop 1.0.19 → 1.0.21

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.
@@ -1,3 +1,1330 @@
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
+ // AEGIS Code (aegiscode) — source: https://github.com/aegisinfo/aegiscode-plugin
4
+ // Conveying a modified copy, or running one as a network service, owes the
5
+ // corresponding source under this licence (§5/§13) — see LICENSING.md.
6
+ 'use strict';
7
+
8
+ /**
9
+ * tools.js — the local tool layer for the desktop agent loop (client half of
10
+ * the upstream engine's tool calling).
11
+ *
12
+ * Two jobs, mirroring the upstream engine reference:
13
+ * 1. Tool schemas in the wire format each API family expects — Anthropic's
14
+ * `{name, description, input_schema}` vs OpenAI-compatible
15
+ * `{type:'function', function:{name, description, parameters}}`.
16
+ * 2. Local execution of the builtin tools (readFile, writeFile, editFile,
17
+ * listDir, glob, grep, exec), so a chat turn in the desktop app can
18
+ * actually touch the machine instead of only talking about it.
19
+ *
20
+ * `exec` runs in a persistent shell session (shell.js) when the caller
21
+ * supplies `ctx.getShell` — cd/export/env state then carries across calls
22
+ * within one turn, same as the CLI's Bash tool. `task` is advertised here
23
+ * (SUBAGENT_TOOL) but has no local executor: it needs to run the model, so
24
+ * engine.js's chat loop handles it directly as a nested subagent turn.
25
+ *
26
+ * Path note: this lives under desktop/lib/local/ (not desktop/lib/) because
27
+ * the CI thin-shell guard (.github/workflows/ci.yml, step 4) allowlists only
28
+ * `desktop/lib/local/`, `desktop/lib/sync/` and `desktop/lib/settings.js` as
29
+ * transport paths — a new file directly under desktop/lib/ fails that guard.
30
+ *
31
+ * Everything here is self-contained (node:child_process + node:fs + node:path
32
+ * only, no new dependencies) and NEVER throws: each executor resolves either
33
+ * `{ ok: true, output }` or `{ ok: false, error }`, so a bad path, a dead
34
+ * command or a hostile arg string can only ever become a tool error handed
35
+ * back to the model — never a rejected IPC call or a crashed main process.
36
+ *
37
+ * SECURITY: this is a deliberate widening of the app's sandbox. The renderer
38
+ * stays contextIsolated + sandboxed with no fs/child_process of its own; the
39
+ * executor lives in the MAIN process and is reachable from the renderer only
40
+ * through the whitelisted `tools:` IPC surface (see main.js/preload.js and
41
+ * docs/desktop-tools.md). There is no path jail: the tools deliberately run
42
+ * with the user's own privileges, exactly like the CLI does. Treat any future
43
+ * renderer-side input that reaches these args as privileged.
44
+ */
45
+
46
+ const { spawn } = require('node:child_process');
47
+ const crypto = require('node:crypto');
48
+ const fs = require('node:fs');
49
+ const os = require('node:os');
50
+ const path = require('node:path');
51
+ const { pathToFileURL } = require('node:url');
52
+ const { agentRoles } = require('./agents.js');
53
+
54
+ // The ONE platform module (client/platform.js, Phase 30.1). This file used to
55
+ // carry a private `shellSpec()` that read `process.platform` directly, which
56
+ // meant the Windows half of the decision could only ever be exercised on a
57
+ // Windows host — and this project has no Windows runner. Resolved the same two
58
+ // ways this repo resolves every shared module (see engine.js): repo-relative in
59
+ // a checkout and in the CLI's mirrored vendor tree, then the staged app-dir
60
+ // copy a packaged desktop build carries. A missing copy would leave `exec` with
61
+ // no shell at all, so the failure is loud here rather than lazily deferred: the
62
+ // fallback loads or this module does not.
63
+ let platform;
64
+ try {
65
+ platform = require('../../../client/platform.js');
66
+ } catch (err) {
67
+ try {
68
+ platform = require('../../vendor/platform.js');
69
+ } catch {
70
+ throw new Error(
71
+ `tools.js: cannot load the shared platform module (client/platform.js, ` +
72
+ `or its staged copy): ${err && err.message ? err.message : err}`
73
+ );
74
+ }
75
+ }
76
+
77
+ const OUTPUT_CAP = 30_000; // chars fed back to the model per tool result
78
+
79
+ /**
80
+ * What every path argument accepts, stated ONCE so the ten schemas below cannot
81
+ * drift from each other or from what normalizeArgs actually does.
82
+ *
83
+ * It names the platform requirement explicitly because the failure it prevents
84
+ * was a model guessing posix on a Windows host (see client/platform.js
85
+ * resolvePath): `/home/you/Desktop/x.txt` there is drive-relative, so the write
86
+ * SUCCEEDED at `C:\home\you\Desktop\x.txt` and the user found nothing on their
87
+ * Desktop. The schema is the first place to say so — a refusal after the fact
88
+ * costs the model a round, a correct description costs it nothing.
89
+ */
90
+ // Kept SHORT on purpose. This sentence is repeated in the description of every
91
+ // path argument (9 of the 10 tools), so its length is paid once per tool, every
92
+ // round, and the tool schemas are part of the wire prefix the provider is asked
93
+ // to cache. The long form spelled out win32 examples and the Environment-block
94
+ // cross-reference — 267 chars, ~68 tokens, ~616 tokens per round once
95
+ // multiplied across the nine. That instruction is NOT lost: prompt.js's
96
+ // TOOL_LINE states the same rule once, in the system prompt where it belongs
97
+ // and where it costs one copy instead of nine. `test/tool-paths.test.mjs`
98
+ // asserts this constant appears in each path argument, so it must stay the
99
+ // single shared string rather than being inlined per tool.
100
+ const PATH_ARG_DESC =
101
+ 'Absolute path on THIS machine; "~"/"~/…" = home. Relative resolves against the working directory.';
102
+
103
+ /** `<what>. <the path rules>` — the shape every path argument's description takes. */
104
+ const pathDesc = (what) => `${what}. ${PATH_ARG_DESC}`;
105
+
106
+ // The dialect probe (Phase 30.3), from the same module the session lives in: a
107
+ // one-shot `exec` must run the command in a shell that was PROBED to speak the
108
+ // dialect the command is written in, never in an unprobed `$SHELL`. Lives next
109
+ // to this file in every tree that has it (repo, CLI vendor, packaged app dir).
110
+ const shells = require('./shell.js');
111
+ // The second gate (see lib/local/integrity.js). Asked here because this module
112
+ // is what HANDS the model its tool surface: a build whose own bytes have been
113
+ // rewritten must not be given tools, and it must ask for itself rather than
114
+ // rely on main.js or shell.js having asked first.
115
+ const integrity = require('./integrity.js');
116
+ const READ_LINE_CAP = 2000; // default line limit for readFile
117
+ const MATCH_CAP = 100; // max glob/grep hits per call
118
+ // readFileSync loads the whole file before `limit` ever truncates — refuse
119
+ // oversized reads outright instead of freezing the turn on a multi-GB log.
120
+ const READ_SIZE_CAP = 25 * 1024 * 1024;
121
+ const GREP_SIZE_CAP = 10 * 1024 * 1024; // grep silently skips files above this
122
+ const EXEC_TIMEOUT_DEFAULT = 120_000;
123
+ const EXEC_TIMEOUT_CAP = 600_000; // 10 minutes, matches the CLI's cap
124
+ const EXEC_MAX_BUFFER = 1_048_576; // 1 MB of combined stdout+stderr
125
+ // The LCS diff below is O(lines_before * lines_after); past this many cells
126
+ // (or this many lines on either side) the diff is skipped in favor of a
127
+ // one-line summary rather than freezing the approval flow on a huge file.
128
+ const DIFF_MAX_CELLS = 4_000_000;
129
+ const DIFF_MAX_LINES = 20_000;
130
+
131
+ // ── Oversized output spills to a file instead of being destroyed ────────────
132
+ //
133
+ // Truncating to OUTPUT_CAP used to be the whole story: the model got the first
134
+ // 30 000 chars and the rest ceased to exist. That is lossy in the one case that
135
+ // matters — a wide grep, a long test log, a `find` over a big tree — where the
136
+ // answer is usually PAST the cap, so the model's only recovery was to re-run a
137
+ // narrower command and pay for the round again. Spilling the full text to a
138
+ // temp file keeps the round count and the token bill where they were: the model
139
+ // reads the slice it actually wants with readFile/grep against a real path.
140
+ //
141
+ // The mechanism lives in ./spill.js rather than here because shell.js (the
142
+ // persistent session `exec`, which is where most output is produced) needs the
143
+ // identical behaviour and may not require this file. This wrapper only binds
144
+ // the shared helper to OUTPUT_CAP.
145
+ const spill = require('./spill.js');
146
+ /** Truncate oversized tool output, keeping the full text reachable on disk. */
147
+ function cap(s) {
148
+ return spill.cap(s, OUTPUT_CAP);
149
+ }
150
+
151
+ const ok = (output) => ({ ok: true, output: cap(output) });
152
+ const fail = (error) => ({ ok: false, error: cap(error) });
153
+
154
+ // ── Schemas ─────────────────────────────────────────────────────────────────
155
+
156
+ /**
157
+ * Canonical descriptions + parameters, in one place per tool. The two wire
158
+ * formats below are pure projections of this map, so a schema can never drift
159
+ * between providers (see the conversion test in test/local-tools.test.mjs).
160
+ */
161
+ const SCHEMAS = {
162
+ readFile: {
163
+ name: 'readFile',
164
+ description: 'Read a file. Returns line-numbered content.',
165
+ parameters: {
166
+ type: 'object',
167
+ properties: {
168
+ file_path: { type: 'string', description: pathDesc('The file to read') },
169
+ offset: { type: 'number', description: 'Start line (0-based)' },
170
+ limit: { type: 'number', description: `The number of lines to read (max 10000, default ${READ_LINE_CAP})` },
171
+ },
172
+ required: ['file_path'],
173
+ additionalProperties: false,
174
+ },
175
+ },
176
+ writeFile: {
177
+ name: 'writeFile',
178
+ description:
179
+ 'Write a whole file, overwriting it. Parent dirs are created. Use editFile to change part of one.',
180
+ parameters: {
181
+ type: 'object',
182
+ properties: {
183
+ file_path: { type: 'string', description: pathDesc('The file to write') },
184
+ content: { type: 'string', description: 'Full file contents' },
185
+ },
186
+ required: ['file_path', 'content'],
187
+ additionalProperties: false,
188
+ },
189
+ },
190
+ editFile: {
191
+ name: 'editFile',
192
+ description:
193
+ 'Exact string replacement. old_string must be unique unless replace_all. Fails loudly on a ' +
194
+ 'missing or ambiguous match rather than guessing. Pass `edits` to apply several hunks to ' +
195
+ 'one file in ONE call — they are applied in order, each against the result of the last, ' +
196
+ 'which is cheaper than one call per hunk.',
197
+ parameters: {
198
+ type: 'object',
199
+ properties: {
200
+ file_path: { type: 'string', description: pathDesc('The file to edit') },
201
+ old_string: { type: 'string', description: 'Text to replace; must be unique unless replace_all' },
202
+ new_string: { type: 'string', description: 'Replacement text' },
203
+ replace_all: { type: 'boolean', description: 'Replace every occurrence' },
204
+ edits: {
205
+ type: 'array',
206
+ description: 'Several hunks for this one file, applied in order. Use instead of old_string/new_string.',
207
+ items: {
208
+ type: 'object',
209
+ properties: {
210
+ old_string: { type: 'string', description: 'Text to replace; must be unique unless replace_all' },
211
+ new_string: { type: 'string', description: 'Replacement text' },
212
+ replace_all: { type: 'boolean', description: 'Replace every occurrence' },
213
+ },
214
+ required: ['old_string', 'new_string'],
215
+ additionalProperties: false,
216
+ },
217
+ },
218
+ },
219
+ required: ['file_path'],
220
+ additionalProperties: false,
221
+ },
222
+ },
223
+ listDir: {
224
+ name: 'listDir',
225
+ description: 'List one directory (non-recursive). Skips node_modules, .git, dist.',
226
+ parameters: {
227
+ type: 'object',
228
+ properties: {
229
+ path: { type: 'string', description: pathDesc('The directory to list (default: the working directory)') },
230
+ },
231
+ required: [],
232
+ additionalProperties: false,
233
+ },
234
+ },
235
+ glob: {
236
+ name: 'glob',
237
+ description:
238
+ 'Find files by glob (**, *, ?). Skips node_modules, .git, dist.',
239
+ parameters: {
240
+ type: 'object',
241
+ properties: {
242
+ pattern: { type: 'string', description: 'Glob, e.g. "**/*.test.js"' },
243
+ path: { type: 'string', description: pathDesc('Search root (default: the working directory)') },
244
+ },
245
+ required: ['pattern'],
246
+ additionalProperties: false,
247
+ },
248
+ },
249
+ grep: {
250
+ name: 'grep',
251
+ description: 'Search file contents by regex. Returns file:line matches. Skips node_modules, .git, dist.',
252
+ parameters: {
253
+ type: 'object',
254
+ properties: {
255
+ pattern: { type: 'string', description: 'The regular expression to search for' },
256
+ path: { type: 'string', description: pathDesc('The directory to search in (default: the working directory)') },
257
+ },
258
+ required: ['pattern'],
259
+ additionalProperties: false,
260
+ },
261
+ },
262
+ exec: {
263
+ name: 'exec',
264
+ description:
265
+ 'Run a shell command in a PERSISTENT session: cd and exported env carry across calls in ' +
266
+ 'this turn. Returns stdout+stderr and the exit code. Use for git, packages, system ops.',
267
+ parameters: {
268
+ type: 'object',
269
+ properties: {
270
+ command: { type: 'string', description: 'Command to run' },
271
+ cwd: { type: 'string', description: pathDesc('Run this one command elsewhere; session cwd unchanged') },
272
+ timeout: { type: 'number', description: `Timeout in milliseconds (max ${EXEC_TIMEOUT_CAP}, default ${EXEC_TIMEOUT_DEFAULT})` },
273
+ description: { type: 'string', description: 'A brief description of what the command does (for display)' },
274
+ },
275
+ required: ['command'],
276
+ additionalProperties: false,
277
+ },
278
+ },
279
+ hooks: {
280
+ name: 'hooks',
281
+ description:
282
+ 'Hook status for this machine, from the same shared implementation the CLI\'s /hooks uses: ' +
283
+ 'the merged settings.json hook config (~/.aegis, ./.aegis, ~/.aegiscode, ./.aegiscode, ~/.claude) ' +
284
+ 'and whether this repo\'s .githooks/ guard hooks are actually installed (core.hooksPath). ' +
285
+ 'Read-only. Use installHooks to install them.',
286
+ parameters: {
287
+ type: 'object',
288
+ properties: {
289
+ sub: { type: 'string', enum: ['status', 'list'], description: 'status (default) or the full config listing' },
290
+ cwd: { type: 'string', description: pathDesc('Repo to inspect (default: the working directory)') },
291
+ },
292
+ required: [],
293
+ additionalProperties: false,
294
+ },
295
+ },
296
+ installHooks: {
297
+ name: 'installHooks',
298
+ description:
299
+ 'Install this repo\'s guard hooks: point git\'s core.hooksPath at .githooks/ (the agent-key ' +
300
+ 'gate, the secret scan, the invariant lock) and make them executable. Idempotent, and verified ' +
301
+ 'by reading the config back. Pass dry_run to see the exact commands without running them. ' +
302
+ 'Without this, a fresh clone runs NO guard hooks.',
303
+ parameters: {
304
+ type: 'object',
305
+ properties: {
306
+ cwd: { type: 'string', description: pathDesc('Repo to install into (default: the working directory)') },
307
+ dry_run: { type: 'boolean', description: 'Print the commands instead of running them' },
308
+ },
309
+ required: [],
310
+ additionalProperties: false,
311
+ },
312
+ },
313
+ task: {
314
+ name: 'task',
315
+ description:
316
+ 'Delegate a focused multi-step sub-task to a subagent with its own tool loop; it returns a ' +
317
+ 'final report. Give it a complete, self-contained prompt — it cannot ask follow-ups.',
318
+ parameters: {
319
+ type: 'object',
320
+ properties: {
321
+ description: { type: 'string', description: 'Short label (3-5 words)' },
322
+ subagent_type: {
323
+ type: 'string',
324
+ enum: [...agentRoles(), 'general'],
325
+ description: 'Which specialist preset to spawn (general = a capable all-purpose agent)',
326
+ },
327
+ prompt: { type: 'string', description: 'The full, self-contained task instructions for the subagent' },
328
+ },
329
+ required: ['description', 'prompt'],
330
+ additionalProperties: false,
331
+ },
332
+ },
333
+ };
334
+
335
+ // task is executed by the chat loop (it needs to run the model), not by the
336
+ // local executors below — advertised in the schemas but handled in
337
+ // engine.js's chat(). Subagents get task too, so delegation can nest —
338
+ // engine.js drops it (via includeSubagent) once the delegation chain passes
339
+ // MAX_SUBAGENT_DEPTH, hard-bounding runaway recursion.
340
+ const SUBAGENT_TOOL = 'task';
341
+
342
+ /**
343
+ * The hook layer (`hooks`, `installHooks`) is the ONE part of this registry that
344
+ * is not agent work, and it is the one part the benchmark never touches.
345
+ *
346
+ * Measured on `benchmarks/raw/beat-pi-20261022-2318` (three tasks, the same wire
347
+ * model, nine trials): the advertised schemas are re-sent as a wire PREFIX on
348
+ * every round, and these two are 427 of its ~1,757 tokens. On the round that
349
+ * misses the prefix cache they are billed at the miss rate; on every later round
350
+ * they are billed at the cheap hit rate but are still tokens the model reads
351
+ * before it reads the task. Pi ships seven tools and no hook surface at all.
352
+ *
353
+ * So they stay RUNNABLE (`isTool`, `executeTool`, `toolList`, the CLI's `/hooks`)
354
+ * and stay on the schema list for a caller that asks for them, but they are no
355
+ * longer advertised to the model by default. Capability is unchanged; the
356
+ * prefix it was paying for is gone.
357
+ */
358
+ const HOOK_TOOLS = new Set(['hooks', 'installHooks']);
359
+
360
+ /** Tool names in advertisement order. `includeSubagent: false` drops task (depth cap). */
361
+ function toolNames({ includeSubagent = true, includeHooks = false } = {}) {
362
+ return schemaList({ includeSubagent, includeHooks }).map((s) => s.name);
363
+ }
364
+
365
+ function schemaList({ includeSubagent = true, includeHooks = false } = {}) {
366
+ return Object.values(SCHEMAS).filter(
367
+ (s) =>
368
+ (includeSubagent || s.name !== SUBAGENT_TOOL) &&
369
+ (includeHooks || !HOOK_TOOLS.has(s.name))
370
+ );
371
+ }
372
+
373
+ /**
374
+ * OpenAI-compatible /chat/completions tool definitions ({type:'function', function}).
375
+ * `includeHooks: true` re-advertises the hook tools; the default is the agent
376
+ * set, because a hook install is a thing the USER asks the CLI for, not a step
377
+ * in a coding task.
378
+ */
379
+ function openaiTools({ includeSubagent = true, includeHooks = false } = {}) {
380
+ return schemaList({ includeSubagent, includeHooks }).map((s) => ({
381
+ type: 'function',
382
+ function: { name: s.name, description: s.description, parameters: s.parameters },
383
+ }));
384
+ }
385
+
386
+ /**
387
+ * The advertised tool list. There is exactly ONE wire format now — every turn
388
+ * goes through the AEGIS relay, which speaks the OpenAI shape — so this takes
389
+ * no `wire` argument. The Anthropic-shaped variant went away with the
390
+ * direct-dial transport. `includeSubagent: false` drops the task tool
391
+ * (subagent depth cap); `includeHooks: true` re-adds hooks/installHooks.
392
+ */
393
+ function toolsFor({ includeSubagent = true, includeHooks = false } = {}) {
394
+ return openaiTools({ includeSubagent, includeHooks });
395
+ }
396
+
397
+ // ── Path normalisation ──────────────────────────────────────────────────────
398
+
399
+ /**
400
+ * Which argument of each tool is a path on this machine. `task` has none (its
401
+ * argument is a prompt), and `exec`'s `command` is deliberately absent: a shell
402
+ * command is not a path and its contents are the shell's business, not ours.
403
+ */
404
+ const TOOL_PATH_ARGS = Object.freeze({
405
+ readFile: ['file_path'],
406
+ writeFile: ['file_path'],
407
+ editFile: ['file_path'],
408
+ listDir: ['path'],
409
+ glob: ['path'],
410
+ grep: ['path'],
411
+ exec: ['cwd'],
412
+ hooks: ['cwd'],
413
+ installHooks: ['cwd'],
414
+ });
415
+
416
+ /**
417
+ * Resolve every path argument of one tool call against THIS machine, returning
418
+ * `{ ok, args, error }` — `args` is a copy with each path replaced by its real
419
+ * absolute form, and a single refusal fails the whole call.
420
+ *
421
+ * Three reasons this is one function applied to the call, rather than a
422
+ * `resolvePath` sprinkled through each executor:
423
+ *
424
+ * 1. The GUARDS read the path too. tools/agent-gate.mjs does
425
+ * `path.resolve(cwd, args.file_path)` to decide whether the target sits in
426
+ * an agent-gated tree, and engine.js's covenant check inspects `args`
427
+ * before anything runs. A `~/…` reaching them unexpanded means they rule on
428
+ * `<cwd>/~/…` — a different file than the one that would be written. The
429
+ * only way the guard and the write can agree is for the path to be real
430
+ * BEFORE either looks at it.
431
+ * 2. The approval gate shows a diff for one path and then writes to another
432
+ * otherwise: previewMutation and applyChecked must resolve identically, and
433
+ * sharing this function is what makes that true by construction.
434
+ * 3. An absent or empty argument is left ALONE, so each executor keeps its own
435
+ * "required" error and its own default (listDir with no `path` still means
436
+ * the working directory). Normalising only what was actually supplied is
437
+ * what keeps this a path fix and not a behaviour change.
438
+ *
439
+ * Idempotent, because resolvePath is: engine.js normalises early for the guards
440
+ * and executeTool normalises again for a direct caller, and the second pass is a
441
+ * no-op rather than a second resolution.
442
+ */
443
+ function normalizeArgs(name, args, ctx = {}) {
444
+ const input = args && typeof args === 'object' ? args : {};
445
+ const keys = TOOL_PATH_ARGS[name];
446
+ if (!keys) return { ok: true, args: input, error: null };
447
+
448
+ let out = input;
449
+ for (const key of keys) {
450
+ const value = input[key];
451
+ if (typeof value !== 'string' || !value.trim()) continue; // absent → the executor's default
452
+ const res = platform.resolvePath(value, {
453
+ // The tool layer's platform seam, the same one `client/platform.js`
454
+ // takes on every function and `shell.js` already passes at its call
455
+ // site: `ctx.platform` names the host whose path rules apply. Absent
456
+ // (every existing caller), `resolvePath` falls back to
457
+ // `process.platform`, so this changes nothing at runtime — but it is
458
+ // what lets the win32 and darwin branches of THIS layer be exercised
459
+ // from a Linux CI, instead of being reachable only on a foreign host.
460
+ // See test/platform-parity.test.mjs.
461
+ platform: ctx && ctx.platform ? ctx.platform : undefined,
462
+ cwd: ctx && ctx.cwd ? ctx.cwd : undefined,
463
+ desktopdir: ctx && ctx.desktopdir ? ctx.desktopdir : undefined,
464
+ });
465
+ if (!res.ok) return { ok: false, args: input, error: `${name}: ${key} — ${res.error}` };
466
+ if (res.path !== value) {
467
+ if (out === input) out = { ...input };
468
+ out[key] = res.path;
469
+ }
470
+ }
471
+ return { ok: true, args: out, error: null };
472
+ }
473
+
474
+ /**
475
+ * The directory a tool with no explicit `path` works in: this TURN's working
476
+ * directory, not the host process's.
477
+ *
478
+ * `process.cwd()` is wrong here and was visibly wrong off Linux: the Electron
479
+ * main process inherits whatever the OS launched the app from — `/` from a .desktop
480
+ * entry, `C:\Program Files\AEGIS Desktop` from a Windows shortcut — so a bare
481
+ * `listDir`/`glob`/`grep` searched the install directory instead of the user's
482
+ * repo. It stays the fallback for a direct call that supplies no ctx.
483
+ */
484
+ function baseDir(ctx) {
485
+ return (ctx && typeof ctx.cwd === 'string' && ctx.cwd) || process.cwd();
486
+ }
487
+
488
+ // ── Executors ───────────────────────────────────────────────────────────────
489
+
490
+ function readFile({ file_path, offset = 0, limit } = {}) {
491
+ try {
492
+ if (!file_path) return fail('file_path is required');
493
+ const stat = fs.statSync(file_path);
494
+ if (stat.isDirectory()) return fail(`${file_path} is a directory (use listDir)`);
495
+ if (stat.size > READ_SIZE_CAP) {
496
+ const mb = (stat.size / 1048576).toFixed(1);
497
+ return fail(
498
+ `${file_path} is ${mb} MB — too large to read (limit ${READ_SIZE_CAP / 1048576} MB). ` +
499
+ 'Use exec with grep/head to inspect it instead.'
500
+ );
501
+ }
502
+ const lines = fs.readFileSync(file_path, 'utf8').split('\n');
503
+ const start = Math.max(0, Number(offset) || 0);
504
+ const count = Math.max(1, Math.min(Number(limit) || READ_LINE_CAP, 10_000));
505
+ const picked = lines.slice(start, start + count);
506
+ const numbered = picked.map((l, i) => `${i + start + 1}| ${l}`).join('\n');
507
+ const tail =
508
+ start + picked.length < lines.length
509
+ ? `\n… (${lines.length - start - picked.length} more lines)`
510
+ : '';
511
+ return ok(numbered + tail);
512
+ } catch (e) {
513
+ return fail(e && e.message ? e.message : String(e));
514
+ }
515
+ }
516
+
517
+ function writeFile({ file_path, content } = {}) {
518
+ try {
519
+ if (!file_path) return fail('file_path is required');
520
+ fs.mkdirSync(path.dirname(file_path), { recursive: true });
521
+ fs.writeFileSync(file_path, String(content == null ? '' : content), 'utf8');
522
+ return ok(`Wrote ${String(content == null ? '' : content).length} bytes to ${file_path}`);
523
+ } catch (e) {
524
+ return fail(e && e.message ? e.message : String(e));
525
+ }
526
+ }
527
+
528
+ function editFile(args = {}) {
529
+ try {
530
+ const preview = previewEditFile(args);
531
+ if (!preview.ok) return fail(preview.error);
532
+ fs.writeFileSync(args.file_path, preview.after, 'utf8');
533
+ const hunks = Array.isArray(args.edits) ? args.edits.length : 1;
534
+ const scope = hunks > 1
535
+ ? `${hunks} hunks, ${preview.count} occurrence${preview.count > 1 ? 's' : ''} replaced`
536
+ : `${preview.count} occurrence${preview.count > 1 ? 's' : ''} replaced`;
537
+ return ok(`Edited ${args.file_path} (${scope})`);
538
+ } catch (e) {
539
+ return fail(e && e.message ? e.message : String(e));
540
+ }
541
+ }
542
+
543
+ // ── Approval-gate helpers ───────────────────────────────────────────────────
544
+ //
545
+ // The renderer approval gate (desktop/lib/local/engine.js gatedExecuteTool)
546
+ // needs to show the user a diff BEFORE a mutating call runs, then re-verify
547
+ // the file hasn't moved out from under it before actually writing. Everything
548
+ // below is pure preparation: it never writes to disk on its own except
549
+ // applyWriteChecked/applyEditChecked, which are the only functions engine.js
550
+ // calls once the user has approved.
551
+
552
+ /** exec/writeFile/editFile/installHooks change machine state (installHooks
553
+ * writes git config); listDir/glob/grep/readFile/hooks never do — this is the
554
+ * set the approval gate checks against. */
555
+ const MUTATING_TOOLS = new Set(['exec', 'writeFile', 'editFile', 'installHooks']);
556
+
557
+ function sha256(text) {
558
+ return crypto.createHash('sha256').update(text == null ? '' : text, 'utf8').digest('hex');
559
+ }
560
+
561
+ /** Read a file for a preview/hash snapshot. Distinguishes "doesn't exist yet"
562
+ * (ok, exists:false) from a real read failure (permissions, is a directory —
563
+ * ok:false), so callers can tell a brand-new file from a broken path. */
564
+ function readForPreview(file_path) {
565
+ try {
566
+ if (!fs.existsSync(file_path)) return { ok: true, exists: false, content: null };
567
+ if (fs.statSync(file_path).isDirectory()) {
568
+ return { ok: false, error: `${file_path} is a directory` };
569
+ }
570
+ return { ok: true, exists: true, content: fs.readFileSync(file_path, 'utf8') };
571
+ } catch (e) {
572
+ return { ok: false, error: e && e.message ? e.message : String(e) };
573
+ }
574
+ }
575
+
576
+ /** Classic LCS line diff: returns the {type:'equal'|'delete'|'insert', a, b}
577
+ * op list turning array `a` into array `b`, indices into each array. */
578
+ function diffLines(a, b) {
579
+ const n = a.length;
580
+ const m = b.length;
581
+ const dp = new Array(n + 1);
582
+ for (let i = 0; i <= n; i++) dp[i] = new Int32Array(m + 1);
583
+ for (let i = n - 1; i >= 0; i--) {
584
+ for (let j = m - 1; j >= 0; j--) {
585
+ dp[i][j] = a[i] === b[j] ? dp[i + 1][j + 1] + 1 : Math.max(dp[i + 1][j], dp[i][j + 1]);
586
+ }
587
+ }
588
+ const ops = [];
589
+ let i = 0;
590
+ let j = 0;
591
+ while (i < n && j < m) {
592
+ if (a[i] === b[j]) {
593
+ ops.push({ type: 'equal', a: i, b: j });
594
+ i++;
595
+ j++;
596
+ } else if (dp[i + 1][j] >= dp[i][j + 1]) {
597
+ ops.push({ type: 'delete', a: i });
598
+ i++;
599
+ } else {
600
+ ops.push({ type: 'insert', b: j });
601
+ j++;
602
+ }
603
+ }
604
+ while (i < n) ops.push({ type: 'delete', a: i++ });
605
+ while (j < m) ops.push({ type: 'insert', b: j++ });
606
+ return ops;
607
+ }
608
+
609
+ /** Group an op list into unified-diff hunks (git diff -Ucontext style) and
610
+ * render them as text with a/b line numbers in the @@ headers. */
611
+ function formatUnifiedDiff(ops, a, b, { label, context }) {
612
+ const n = ops.length;
613
+ const keep = new Array(n).fill(false);
614
+ for (let i = 0; i < n; i++) {
615
+ if (ops[i].type === 'equal') continue;
616
+ keep[i] = true;
617
+ for (let k = 1; k <= context; k++) {
618
+ if (i - k >= 0) keep[i - k] = true;
619
+ if (i + k < n) keep[i + k] = true;
620
+ }
621
+ }
622
+ const hunkRanges = [];
623
+ let start = -1;
624
+ for (let i = 0; i <= n; i++) {
625
+ if (i < n && keep[i]) {
626
+ if (start === -1) start = i;
627
+ } else if (start !== -1) {
628
+ hunkRanges.push([start, i - 1]);
629
+ start = -1;
630
+ }
631
+ }
632
+ if (!hunkRanges.length) return `--- ${label}\n+++ ${label}\n(no changes)`;
633
+
634
+ const out = [`--- ${label}`, `+++ ${label}`];
635
+ for (const [s, e] of hunkRanges) {
636
+ let aLine = 1;
637
+ let bLine = 1;
638
+ for (let i = 0; i < s; i++) {
639
+ if (ops[i].type !== 'insert') aLine++;
640
+ if (ops[i].type !== 'delete') bLine++;
641
+ }
642
+ let aCount = 0;
643
+ let bCount = 0;
644
+ const body = [];
645
+ for (let i = s; i <= e; i++) {
646
+ const op = ops[i];
647
+ if (op.type === 'equal') {
648
+ body.push(` ${a[op.a]}`);
649
+ aCount++;
650
+ bCount++;
651
+ } else if (op.type === 'delete') {
652
+ body.push(`-${a[op.a]}`);
653
+ aCount++;
654
+ } else {
655
+ body.push(`+${b[op.b]}`);
656
+ bCount++;
657
+ }
658
+ }
659
+ out.push(`@@ -${aLine},${aCount} +${bLine},${bCount} @@`);
660
+ out.push(...body);
661
+ }
662
+ return out.join('\n');
663
+ }
664
+
665
+ /** Unified diff between two whole-file strings (`before` may be null — a new
666
+ * file). Falls back to a one-line summary for files too large to diff cheaply. */
667
+ function unifiedDiff(before, after, { label = 'file', context = 3 } = {}) {
668
+ const a = before == null ? [] : String(before).split('\n');
669
+ const b = after == null ? [] : String(after).split('\n');
670
+ if (a.length > DIFF_MAX_LINES || b.length > DIFF_MAX_LINES || a.length * b.length > DIFF_MAX_CELLS) {
671
+ const added = Math.max(0, b.length - a.length);
672
+ const removed = Math.max(0, a.length - b.length);
673
+ return `--- ${label}\n+++ ${label}\n@@ file too large to preview — approx +${added}/-${removed} lines @@`;
674
+ }
675
+ return formatUnifiedDiff(diffLines(a, b), a, b, { label, context });
676
+ }
677
+
678
+ /** Build the {before, after, diff, hash} preview for a writeFile call without
679
+ * touching disk. `hash` is the sha256 of the CURRENT on-disk content (null
680
+ * for a not-yet-existing file) — the snapshot applyWriteChecked re-verifies
681
+ * against before actually writing. */
682
+ function previewWriteFile({ file_path, content } = {}) {
683
+ if (!file_path) return { ok: false, error: 'file_path is required' };
684
+ const read = readForPreview(file_path);
685
+ if (!read.ok) return { ok: false, error: read.error };
686
+ const before = read.exists ? read.content : null;
687
+ const after = String(content == null ? '' : content);
688
+ return {
689
+ ok: true,
690
+ before,
691
+ after,
692
+ diff: unifiedDiff(before, after, { label: file_path }),
693
+ hash: before == null ? null : sha256(before),
694
+ };
695
+ }
696
+
697
+ /** Same shape as previewWriteFile, for editFile — shares its validation with
698
+ * the executor above so there is exactly one place that knows how to apply
699
+ * an edit.
700
+ *
701
+ * Accepts either ONE `{old_string, new_string, replace_all}` pair or an
702
+ * `edits: [...]` array of them, applied in order against the in-memory
703
+ * result of the previous one. The array form exists because a model that has
704
+ * just read a file usually knows every hunk it wants at once; making it spend
705
+ * one round per hunk re-sends the whole prefix and pays output for text it
706
+ * already wrote (measured on the SWE-bench head-to-head: pi batches, this loop
707
+ * did not). Nothing about the single-pair path changes — an absent `edits` is
708
+ * a one-element list. */
709
+ function editPairList({ edits, old_string, new_string, replace_all } = {}) {
710
+ if (edits === undefined || edits === null) {
711
+ return { ok: true, edits: [{ old_string, new_string, replace_all }] };
712
+ }
713
+ if (!Array.isArray(edits) || !edits.length) {
714
+ return { ok: false, error: 'edits must be a non-empty array of {old_string, new_string, replace_all?}' };
715
+ }
716
+ const out = [];
717
+ for (let i = 0; i < edits.length; i++) {
718
+ const e = edits[i];
719
+ if (!e || typeof e !== 'object') return { ok: false, error: `edits[${i}] must be an object` };
720
+ if (typeof e.old_string !== 'string' || e.old_string === '') {
721
+ return { ok: false, error: `edits[${i}].old_string is required and must be non-empty` };
722
+ }
723
+ out.push({ old_string: e.old_string, new_string: e.new_string, replace_all: e.replace_all });
724
+ }
725
+ return { ok: true, edits: out };
726
+ }
727
+
728
+ function previewEditFile({ file_path, old_string, new_string, replace_all, edits } = {}) {
729
+ if (!file_path) return { ok: false, error: 'file_path is required' };
730
+ const list = editPairList({ edits, old_string, new_string, replace_all });
731
+ if (!list.ok) return { ok: false, error: list.error };
732
+ if (!edits && (old_string === undefined || old_string === '')) {
733
+ return { ok: false, error: 'old_string is required and must be non-empty' };
734
+ }
735
+ const read = readForPreview(file_path);
736
+ if (!read.ok) return { ok: false, error: read.error };
737
+ if (!read.exists) return { ok: false, error: `${file_path} does not exist` };
738
+ const before = read.content;
739
+ let after = before;
740
+ let count = 0;
741
+ for (let i = 0; i < list.edits.length; i++) {
742
+ const e = list.edits[i];
743
+ const n = after.split(e.old_string).length - 1;
744
+ const where = list.edits.length > 1 ? `edits[${i}]: ` : '';
745
+ if (n === 0) return { ok: false, error: `${where}old_string not found in ${file_path}` };
746
+ if (n > 1 && !e.replace_all) {
747
+ return { ok: false, error: `${where}old_string is not unique (${n} matches) — use replace_all or more context` };
748
+ }
749
+ after = e.replace_all
750
+ ? after.split(e.old_string).join(e.new_string == null ? '' : e.new_string)
751
+ : after.replace(e.old_string, e.new_string == null ? '' : e.new_string);
752
+ count += n;
753
+ }
754
+ return {
755
+ ok: true,
756
+ before,
757
+ after,
758
+ diff: unifiedDiff(before, after, { label: file_path }),
759
+ hash: sha256(before),
760
+ count,
761
+ };
762
+ }
763
+
764
+ /** Dispatch a preview by tool name. Only writeFile/editFile have one — exec
765
+ * has nothing to diff, and the approval gate skips this call for it. */
766
+ function previewMutation(name, args, ctx = {}) {
767
+ const norm = normalizeArgs(name, args, ctx);
768
+ if (!norm.ok) return { ok: false, error: norm.error };
769
+ if (name === 'writeFile') return previewWriteFile(norm.args);
770
+ if (name === 'editFile') return previewEditFile(norm.args);
771
+ return { ok: false, error: `no diff preview for ${name}` };
772
+ }
773
+
774
+ /** Apply a writeFile the user has approved, but only if the file on disk
775
+ * still matches the hash captured at preview time — otherwise something
776
+ * else changed it while the approval card was open, and applying blind
777
+ * would silently clobber that change. */
778
+ function applyWriteChecked({ file_path, content } = {}, expectedHash) {
779
+ try {
780
+ if (!file_path) return fail('file_path is required');
781
+ const read = readForPreview(file_path);
782
+ if (!read.ok) return fail(read.error);
783
+ const currentHash = read.exists ? sha256(read.content) : null;
784
+ if (currentHash !== expectedHash) {
785
+ return fail(
786
+ `${file_path} changed on disk since the diff was shown — refusing to apply a stale write. Re-run writeFile to get an updated diff.`
787
+ );
788
+ }
789
+ fs.mkdirSync(path.dirname(file_path), { recursive: true });
790
+ fs.writeFileSync(file_path, String(content == null ? '' : content), 'utf8');
791
+ return ok(`Wrote ${String(content == null ? '' : content).length} bytes to ${file_path}`);
792
+ } catch (e) {
793
+ return fail(e && e.message ? e.message : String(e));
794
+ }
795
+ }
796
+
797
+ /** Same guard as applyWriteChecked, for an already-computed editFile result
798
+ * (`after` — the preview's replacement, not recomputed here since a hash
799
+ * match means the source it was computed from is still exactly on disk). */
800
+ function applyEditChecked({ file_path, after } = {}, expectedHash) {
801
+ try {
802
+ if (!file_path) return fail('file_path is required');
803
+ const read = readForPreview(file_path);
804
+ if (!read.ok) return fail(read.error);
805
+ const currentHash = read.exists ? sha256(read.content) : null;
806
+ if (currentHash !== expectedHash) {
807
+ return fail(
808
+ `${file_path} changed on disk since the diff was shown — refusing to apply a stale edit. Re-run editFile to get an updated diff.`
809
+ );
810
+ }
811
+ fs.writeFileSync(file_path, after, 'utf8');
812
+ return ok(`Edited ${file_path}`);
813
+ } catch (e) {
814
+ return fail(e && e.message ? e.message : String(e));
815
+ }
816
+ }
817
+
818
+ /** Apply an approved writeFile/editFile call using the hash captured in its
819
+ * `preview` (see previewMutation) — the single entry point engine.js calls
820
+ * once the user has said yes. */
821
+ function applyChecked(name, args, preview, ctx = {}) {
822
+ const norm = normalizeArgs(name, args, ctx);
823
+ if (!norm.ok) return fail(norm.error);
824
+ if (name === 'writeFile') return applyWriteChecked(norm.args, preview.hash);
825
+ return applyEditChecked({ file_path: norm.args.file_path, after: preview.after }, preview.hash);
826
+ }
827
+
828
+ const IGNORED_DIRS = new Set(['node_modules', '.git', 'dist', '.aegiscode']);
829
+
830
+ function listDir({ path: dir } = {}, ctx = {}) {
831
+ try {
832
+ const base = dir || baseDir(ctx);
833
+ const entries = fs.readdirSync(base, { withFileTypes: true });
834
+ const rows = entries
835
+ .filter((e) => !IGNORED_DIRS.has(e.name))
836
+ .map((e) => (e.isDirectory() ? `${e.name}/` : e.name))
837
+ .sort((a, b) => a.localeCompare(b));
838
+ return ok(rows.join('\n') || '(empty directory)');
839
+ } catch (e) {
840
+ return fail(e && e.message ? e.message : String(e));
841
+ }
842
+ }
843
+
844
+ /** Translate a glob into a regex over '/'-separated relative paths. */
845
+ function globToRegex(pattern) {
846
+ let re = '^';
847
+ for (let i = 0; i < pattern.length; i++) {
848
+ const c = pattern[i];
849
+ if (c === '*') {
850
+ if (pattern[i + 1] === '*') {
851
+ re += '.*';
852
+ i++;
853
+ } else re += '[^/]*';
854
+ } else if (c === '?') re += '[^/]';
855
+ else if (/[.+^${}()|[\]\\]/.test(c)) re += `\\${c}`;
856
+ else re += c;
857
+ }
858
+ return new RegExp(re + '$');
859
+ }
860
+
861
+ function walk(dir, fn, depth = 0) {
862
+ if (depth > 12) return; // hard bound: never crawl an unbounded tree
863
+ let entries;
864
+ try {
865
+ entries = fs.readdirSync(dir, { withFileTypes: true });
866
+ } catch {
867
+ return;
868
+ }
869
+ for (const e of entries) {
870
+ if (IGNORED_DIRS.has(e.name)) continue;
871
+ const full = path.join(dir, e.name);
872
+ if (e.isDirectory()) walk(full, fn, depth + 1);
873
+ else fn(full);
874
+ }
875
+ }
876
+
877
+ function glob({ pattern, path: root } = {}, ctx = {}) {
878
+ try {
879
+ if (!pattern) return fail('pattern is required');
880
+ const base = root || baseDir(ctx);
881
+ const re = globToRegex(String(pattern));
882
+ const hits = [];
883
+ walk(base, (full) => {
884
+ if (hits.length >= MATCH_CAP) return;
885
+ const rel = path.relative(base, full).split(path.sep).join('/');
886
+ if (re.test(rel)) hits.push(rel);
887
+ });
888
+ return ok(hits.join('\n') || '(no matches)');
889
+ } catch (e) {
890
+ return fail(e && e.message ? e.message : String(e));
891
+ }
892
+ }
893
+
894
+ function grep({ pattern, path: root } = {}, ctx = {}) {
895
+ try {
896
+ if (!pattern) return fail('pattern is required');
897
+ const re = new RegExp(pattern);
898
+ const base = root || baseDir(ctx);
899
+ const hits = [];
900
+ walk(base, (full) => {
901
+ if (hits.length >= MATCH_CAP) return;
902
+ let text;
903
+ try {
904
+ // Skip oversized files (logs, dumps, binaries) instead of slurping
905
+ // them — a 10 GB log would otherwise stall the whole tool loop.
906
+ if (fs.statSync(full).size > GREP_SIZE_CAP) return;
907
+ text = fs.readFileSync(full, 'utf8');
908
+ } catch {
909
+ return;
910
+ }
911
+ const rel = path.relative(base, full).split(path.sep).join('/');
912
+ for (const [i, line] of text.split('\n').entries()) {
913
+ if (hits.length >= MATCH_CAP) return;
914
+ if (re.test(line)) hits.push(`${rel}:${i + 1}: ${line.slice(0, 160)}`);
915
+ }
916
+ });
917
+ return ok(hits.join('\n') || '(no matches)');
918
+ } catch (e) {
919
+ return fail(e && e.message ? e.message : String(e));
920
+ }
921
+ }
922
+
923
+ /**
924
+ * Run a shell command as a fresh one-shot process (no state carried to the
925
+ * next call). Never rejects: spawn failures, a stalled child, a non-zero
926
+ * exit and output overflow all resolve as `{ ok:false, error }` (a non-zero
927
+ * exit is reported as an error so the model sees the failure, with whatever
928
+ * the command printed attached).
929
+ */
930
+ function execOneShot({ command, cwd, timeout, maxBuffer } = {}) {
931
+ return new Promise((resolve) => {
932
+ const limit = Math.min(Number(maxBuffer) || EXEC_MAX_BUFFER, EXEC_MAX_BUFFER);
933
+ const ms = Math.min(Number(timeout) || EXEC_TIMEOUT_DEFAULT, EXEC_TIMEOUT_CAP);
934
+ // Shell to run `exec` in: PowerShell on Windows (both the persistent
935
+ // session AND the one-shot path — they must agree, or a session that dies
936
+ // mid-turn silently switches the quoting contract; see shell.js
937
+ // resolveSessionShell), a PROBED POSIX sh/bash elsewhere. The choice, the
938
+ // platform seam that makes its win32 half testable on Linux and the
939
+ // fish/csh/nu refusal all live in client/platform.js + shell.js (Phase
940
+ // 30.1/30.3) — there is no second copy of that decision here, and an
941
+ // unverifiable shell is REPORTED rather than used.
942
+ const spec = shells.oneShotShellSpec();
943
+ if (!spec.ok) {
944
+ resolve(fail(spec.error));
945
+ return;
946
+ }
947
+ const { cmd, arg } = spec;
948
+
949
+ let child;
950
+ try {
951
+ child = spawn(cmd, [arg, command], {
952
+ cwd: cwd || process.cwd(),
953
+ timeout: ms,
954
+ killSignal: 'SIGKILL',
955
+ windowsHide: true,
956
+ });
957
+ } catch (e) {
958
+ resolve(fail(`spawn failed: ${e && e.message ? e.message : e}`));
959
+ return;
960
+ }
961
+
962
+ let out = '';
963
+ let bytes = 0;
964
+ let overflow = false;
965
+ let timedOut = false;
966
+ let settled = false;
967
+
968
+ const timer = setTimeout(() => {
969
+ timedOut = true;
970
+ try {
971
+ child.kill('SIGKILL');
972
+ } catch {
973
+ /* already gone */
974
+ }
975
+ }, ms);
976
+
977
+ const collect = (chunk) => {
978
+ bytes += chunk.length;
979
+ if (bytes > limit) {
980
+ overflow = true;
981
+ try {
982
+ child.kill('SIGKILL');
983
+ } catch {
984
+ /* already gone */
985
+ }
986
+ return;
987
+ }
988
+ out += chunk;
989
+ };
990
+
991
+ if (child.stdout) child.stdout.on('data', collect);
992
+ if (child.stderr) child.stderr.on('data', collect);
993
+
994
+ const done = (res) => {
995
+ if (settled) return;
996
+ settled = true;
997
+ clearTimeout(timer);
998
+ resolve(res);
999
+ };
1000
+
1001
+ child.on('error', (e) => done(fail(`spawn failed: ${e && e.message ? e.message : e}`)));
1002
+ child.on('close', (code, signal) => {
1003
+ const body = out.trim();
1004
+ if (timedOut) {
1005
+ done(fail(`command timed out after ${ms}ms${body ? `\n${body}` : ''}`));
1006
+ return;
1007
+ }
1008
+ if (overflow) {
1009
+ // The buffer cap is what the model should see: trimming to OUTPUT_CAP
1010
+ // below would hide the fact that output was dropped.
1011
+ done(fail(`output exceeded ${limit} bytes and was truncated\n${body}`));
1012
+ return;
1013
+ }
1014
+ const label = `exit ${code == null ? `signal ${signal}` : code}`;
1015
+ if (code === 0) done(ok(body || `(${label}, no output)`));
1016
+ else done(fail(`${label}${body ? `\n${body}` : ''}`));
1017
+ });
1018
+ });
1019
+ }
1020
+
1021
+ /**
1022
+ * Run a persistent-session command and translate the session's { content,
1023
+ * isError } shape into this file's { ok, output } / { ok:false, error }
1024
+ * convention. An abort signal disposes the session immediately instead of
1025
+ * waiting out the command's own timeout.
1026
+ */
1027
+ function execInShell(shell, { command, cwd, timeout }, signal) {
1028
+ if (signal && signal.aborted) {
1029
+ shell.dispose();
1030
+ return Promise.resolve(fail('aborted'));
1031
+ }
1032
+ return new Promise((resolve) => {
1033
+ const onAbort = () => shell.dispose();
1034
+ if (signal) signal.addEventListener('abort', onAbort, { once: true });
1035
+ const release = () => { if (signal) signal.removeEventListener('abort', onAbort); };
1036
+ shell.run(command, { timeout, working_directory: cwd }).then(
1037
+ (r) => { release(); resolve(r.isError ? fail(r.content) : ok(r.content)); },
1038
+ (e) => { release(); resolve(fail(`shell session failed: ${e && e.message ? e.message : e}`)); }
1039
+ );
1040
+ });
1041
+ }
1042
+
1043
+ /**
1044
+ * Execute a shell command. When the caller supplies `ctx.getShell` (the
1045
+ * chat loop always does — see engine.js), the command runs in that turn's
1046
+ * persistent session so cd/export/env state carries to the next call. Without
1047
+ * one (e.g. a direct executeTool call in tests) it falls back to a one-shot
1048
+ * spawn — same output shape, no persisted state. Never rejects.
1049
+ */
1050
+ function exec({ command, cwd, timeout, maxBuffer } = {}, ctx = {}) {
1051
+ if (!command || typeof command !== 'string') {
1052
+ return Promise.resolve(fail('command is required'));
1053
+ }
1054
+ // `oneShotExec` is set by the engine for a call its exec-plan classifier
1055
+ // proved SELF-CONTAINED (see exec-plan.js): a read-shaped command whose only
1056
+ // shell dependency is a leading absolute `cd`, which becomes `cwd` here. Such
1057
+ // a call may run CONCURRENTLY with the turn's other reads, which a persistent
1058
+ // shell command cannot — two execs through one shell would interleave into a
1059
+ // single stdin and both parses would read the wrong exit sentinel. The
1060
+ // classifier is the only thing that sets this flag; a plain tool call never
1061
+ // does, so the persistent session stays the default.
1062
+ if (ctx.oneShotExec) {
1063
+ return execOneShot({ command, cwd: cwd || ctx.cwd, timeout, maxBuffer });
1064
+ }
1065
+ const shell = typeof ctx.getShell === 'function' ? ctx.getShell() : null;
1066
+ if (shell) return execInShell(shell, { command, cwd, timeout }, ctx.signal);
1067
+ return execOneShot({ command, cwd, timeout, maxBuffer });
1068
+ }
1069
+
1070
+ // ── hooks / installHooks ────────────────────────────────────────────────────
1071
+ //
1072
+ // The hook layer is SHARED with the CLI (`client/hooks.js`, the same file
1073
+ // `aegiscode /hooks` reads and `agent-gate.mjs install-hooks` installs), loaded
1074
+ // exactly like the other cross-host modules: the repo-relative path first,
1075
+ // then the flattened staged copy inside the app dir. Two implementations of
1076
+ // "which settings files count" is how the GUI and the terminal end up
1077
+ // describing one machine differently — which is what this replaced.
1078
+ //
1079
+ // Before this, the desktop had NO hook surface at all: the app could open a
1080
+ // guarded tree and never mention that the git-side half of the same lock was
1081
+ // not installed, so a fresh clone committed with no gate and nothing said so.
1082
+ let hooksLib = null;
1083
+ try {
1084
+ hooksLib = require('../../../client/hooks.js');
1085
+ } catch {
1086
+ try { hooksLib = require('../../vendor/hooks.js'); } catch { hooksLib = null; }
1087
+ }
1088
+
1089
+ const HOOKS_LIB_MISSING =
1090
+ 'the shared hook module could not be loaded (tried client/hooks.js beside the app and '
1091
+ + 'vendor/hooks.js inside it) — run scripts/predist.mjs before packaging.';
1092
+
1093
+ function hooksListing(config) {
1094
+ const lines = [];
1095
+ const hooks = config && config.hooks ? config.hooks : {};
1096
+ for (const [event, matchers] of Object.entries(hooks)) {
1097
+ lines.push(`${event} (${matchers.length})`);
1098
+ for (const matcher of matchers) {
1099
+ if (!matcher) continue;
1100
+ lines.push(` - ${matcher.name || '(unnamed)'}`);
1101
+ const m = matcher.matcher;
1102
+ if (m && m.tools) lines.push(` tools: ${m.tools}`);
1103
+ if (m && m.paths) lines.push(` paths: ${m.paths}`);
1104
+ if (m && m.commands) lines.push(` commands: ${m.commands}`);
1105
+ }
1106
+ }
1107
+ return lines.length ? lines.join('\n') : '(no hooks declared in any settings file)';
1108
+ }
1109
+
1110
+ /** Read-only: hook config + whether this repo's guard hooks are installed. */
1111
+ function hooks({ sub, cwd } = {}) {
1112
+ if (!hooksLib) return fail(HOOKS_LIB_MISSING);
1113
+ try {
1114
+ const opts = { cwd: cwd || process.cwd() };
1115
+ const config = hooksLib.readHookConfig(opts);
1116
+ if (String(sub || 'status').toLowerCase() === 'list') return ok(hooksListing(config));
1117
+ const stats = hooksLib.hookStats(config.hooks);
1118
+ return ok(hooksLib.hooksSummary({ ...opts, config, stats }));
1119
+ } catch (e) {
1120
+ return fail(e && e.message ? e.message : String(e));
1121
+ }
1122
+ }
1123
+
1124
+ /** Mutating: install the repo's guard hooks (core.hooksPath -> .githooks/). */
1125
+ function installHooks({ cwd, dry_run } = {}) {
1126
+ if (!hooksLib) return fail(HOOKS_LIB_MISSING);
1127
+ let res;
1128
+ try {
1129
+ res = hooksLib.installRepoHooks({ cwd: cwd || process.cwd(), dryRun: Boolean(dry_run) });
1130
+ } catch (e) {
1131
+ return fail(e && e.message ? e.message : String(e));
1132
+ }
1133
+ const plan = res.actions.length ? `\n ${res.actions.join('\n ')}` : '';
1134
+ if (!res.ok) return fail(`${res.error}${plan}`);
1135
+ if (dry_run) {
1136
+ return ok(`would install the guard hooks in ${res.status.repo}${plan || '\n (already installed — nothing to do)'}`
1137
+ + (res.status.installed ? '' : '\n re-run without dry_run to apply'));
1138
+ }
1139
+ if (!res.changed) {
1140
+ return ok(`guard hooks already installed in ${res.status.repo}: core.hooksPath = .githooks\n ${res.status.execNote}`);
1141
+ }
1142
+ return ok(`guard hooks installed in ${res.status.repo}\n core.hooksPath = .githooks (verified by reading it back)`
1143
+ + `${plan}\n ${res.status.execNote}\n a commit and a push in this tree are now gated.`);
1144
+ }
1145
+
1146
+ const EXECUTORS = { readFile, writeFile, editFile, listDir, glob, grep, exec, hooks, installHooks };
1147
+
1148
+ /** True when `name` is a tool this layer can run (task is excluded — see SUBAGENT_TOOL). */
1149
+ function isTool(name) {
1150
+ return Object.prototype.hasOwnProperty.call(EXECUTORS, name);
1151
+ }
1152
+
1153
+ /**
1154
+ * Execute one tool call. Always resolves `{ ok, output }` or `{ ok, error }`
1155
+ * — an unknown tool name, a non-object args payload and an exploding executor
1156
+ * all land on the error branch rather than rejecting. `ctx` carries per-turn
1157
+ * state (getShell, signal); omit it and exec falls back to a one-shot spawn.
1158
+ */
1159
+ /**
1160
+ * `tools/agent-gate.mjs` is ESM and this module is CJS, so it is imported
1161
+ * dynamically and once. The candidates are tried in order; the first that
1162
+ * resolves wins:
1163
+ *
1164
+ * 1. `../../../tools/agent-gate.mjs` — the repo checkout (dev / CI). This is
1165
+ * the SAME file the git hooks execute, so "what is allowed" is computed
1166
+ * once, by one implementation.
1167
+ * 2. `<process.resourcesPath>/tools/agent-gate.mjs` — where electron-builder's
1168
+ * `extraResources` puts it in a packaged build, as a real file OUTSIDE the
1169
+ * asar. That placement is load-bearing, not cosmetic: the gate is loaded
1170
+ * with dynamic `import()`, and Node's ESM loader does not go through
1171
+ * Electron's asar-aware fs patch (electron/asar#249), so a copy living only
1172
+ * inside the archive can fail to resolve — leaving the packaged app with no
1173
+ * gate at all. This is the app's only dynamic ESM import, so nothing else
1174
+ * here exercises that path. Conveniently this is also what candidate (1)
1175
+ * resolves to from `resources/app.asar/lib/local/`, so dev and packaged
1176
+ * builds agree on one file.
1177
+ * 3. `../../vendor/agent-gate.mjs` — the staged copy inside the app dir, kept
1178
+ * as the last resort for a build that is not archived (`asar: false`) or an
1179
+ * npm-installed tree. It is the candidate that fails inside an asar, hence
1180
+ * third and not first.
1181
+ *
1182
+ * Before (2) existed a packaged build had no gate at all: the manifest is found
1183
+ * by climbing from the working directory, so the packaged app would open a
1184
+ * guarded tree and every write through it succeeded while the same call through
1185
+ * the repo copy was refused.
1186
+ *
1187
+ * If nothing resolves, that is a broken gate rather than a permissive one, and
1188
+ * executeTool refuses mutating calls into a tree that declares a manifest.
1189
+ */
1190
+ let agentGatePromise;
1191
+
1192
+ function agentGateCandidates({ resourcesPath = process.resourcesPath, dirname = __dirname } = {}) {
1193
+ const candidates = ['../../../tools/agent-gate.mjs'];
1194
+ // process.resourcesPath is an Electron-provided value and is absent under
1195
+ // plain node, so this is guarded rather than assumed. An absolute path must
1196
+ // be a file URL to be imported.
1197
+ if (typeof resourcesPath === 'string' && resourcesPath) {
1198
+ candidates.push(pathToFileURL(path.join(resourcesPath, 'tools', 'agent-gate.mjs')).href);
1199
+ }
1200
+ candidates.push('../../vendor/agent-gate.mjs');
1201
+ return candidates;
1202
+ }
1203
+
1204
+ function loadAgentGate() {
1205
+ if (!agentGatePromise) {
1206
+ const candidates = agentGateCandidates();
1207
+ const tryNext = (i) => (i >= candidates.length
1208
+ ? null
1209
+ : import(candidates[i]).catch(() => tryNext(i + 1)));
1210
+ agentGatePromise = tryNext(0);
1211
+ }
1212
+ return agentGatePromise;
1213
+ }
1214
+
1215
+ /**
1216
+ * The nearest `.aegis/guard.json` at or above `start`, or null. The identical
1217
+ * climb as findManifest() in tools/agent-gate.mjs and src/repoguard.js. It is
1218
+ * used ONLY to decide whether a call that could not load the gate module is
1219
+ * unsafe; when the module loads it is the sole authority.
1220
+ */
1221
+ function nearestManifest(start) {
1222
+ let dir = path.resolve(start || process.cwd());
1223
+ try { if (fs.statSync(dir).isFile()) dir = path.dirname(dir); } catch { /* keep as-is */ }
1224
+ for (;;) {
1225
+ const candidate = path.join(dir, '.aegis', 'guard.json');
1226
+ if (fs.existsSync(candidate)) return candidate;
1227
+ const parent = path.dirname(dir);
1228
+ if (parent === dir) return null;
1229
+ dir = parent;
1230
+ }
1231
+ }
1232
+
1233
+ async function executeTool(name, args, ctx) {
1234
+ // The second gate, before any tool runs (see lib/local/integrity.js). Same
1235
+ // shape as every other refusal here — a result, not a throw — so a refused
1236
+ // build degrades visibly instead of crashing mid-turn.
1237
+ if (integrity.armed()) return fail('exec: unavailable in this build');
1238
+ if (!isTool(name)) return fail(`unknown tool "${name}" (known: ${toolNames().join(', ')})`);
1239
+ // Paths become real BEFORE the agent-key gate below resolves them itself —
1240
+ // see normalizeArgs. A `~/…` that reached the gate unexpanded was ruled on as
1241
+ // `<cwd>/~/…`, i.e. a different file than the one about to be written.
1242
+ const norm = normalizeArgs(name, args, ctx || {});
1243
+ if (!norm.ok) return fail(norm.error);
1244
+ const input = norm.args;
1245
+ // ── agent-key gate (tools/agent-gate.mjs) ──────────────────────────────
1246
+ // The in-process half of the lock whose other half is .githooks/. A tree
1247
+ // that declares .aegis/guard.json must not be mutated through this app
1248
+ // without the key, exactly as it cannot be mutated by the engine or
1249
+ // committed by git. Reads are never gated. Refused — not warned — when the
1250
+ // key is absent, the manifest is unreadable, or the key file is
1251
+ // world-readable; AEGIS_GATE_SKIP=1 is the one bypass, and it is refused in
1252
+ // an unattended run. The module is required lazily so a packaged app whose
1253
+ // tree has no tools/ directory still starts and simply has no gate.
1254
+ let gate = null;
1255
+ try {
1256
+ gate = await loadAgentGate();
1257
+ } catch { /* not running from the repo: no manifest to honour */ }
1258
+ if (gate) {
1259
+ const verdict = gate.guardTool({
1260
+ tool: name, args: input, cwd: (ctx && ctx.cwd) || process.cwd(),
1261
+ env: process.env, unattended: Boolean(ctx && ctx.autonomous),
1262
+ });
1263
+ if (!verdict.allowed) return fail(gate.refusalText(verdict));
1264
+ if (verdict.code === 'skipped') {
1265
+ const res = await EXECUTORS[name](input, ctx || {});
1266
+ return res && typeof res === 'object' ? { ...res, output: `⚠ ${verdict.reason}\n${res.output || ''}` } : res;
1267
+ }
1268
+ } else if (MUTATING_TOOLS.has(name)) {
1269
+ // Neither the repo copy nor the staged one loaded. A broken gate must
1270
+ // never silently allow (the hooks exit 4 for exactly this reason), so a
1271
+ // mutating call into a tree that declares a manifest is refused with the
1272
+ // path of the manifest that could not be honoured.
1273
+ const man = nearestManifest((ctx && ctx.cwd) || process.cwd());
1274
+ if (man) {
1275
+ return fail(
1276
+ `error: refused — ${man} declares an agent-gated tree, but the agent-key gate module could not be loaded `
1277
+ + '(tried tools/agent-gate.mjs beside the app and vendor/agent-gate.mjs inside it), so this '
1278
+ + `${name} cannot be authorised. A build that missed the staged copy is the usual cause: `
1279
+ + 'run scripts/predist.mjs before packaging.',
1280
+ );
1281
+ }
1282
+ }
1283
+ try {
1284
+ return await EXECUTORS[name](input, ctx || {});
1285
+ } catch (e) {
1286
+ return fail(e && e.message ? e.message : String(e));
1287
+ }
1288
+ }
1289
+
1290
+ /**
1291
+ * The string a tool result contributes to the conversation: the output on
1292
+ * success, `error: …` on failure — the same shape the CLI feeds back.
1293
+ */
1294
+ function toolResultText(result) {
1295
+ if (!result) return 'error: tool produced no result';
1296
+ return result.ok ? String(result.output == null ? '' : result.output) : `error: ${result.error}`;
1297
+ }
1298
+
1299
+ module.exports = {
1300
+ // schemas
1301
+ SCHEMAS,
1302
+ SUBAGENT_TOOL,
1303
+ HOOK_TOOLS,
1304
+ toolNames,
1305
+ openaiTools,
1306
+ toolsFor,
1307
+ // execution
1308
+ executeTool,
1309
+ isTool,
1310
+ toolResultText,
1311
+ // approval gate (desktop/lib/local/engine.js gatedExecuteTool)
1312
+ MUTATING_TOOLS,
1313
+ previewMutation,
1314
+ applyChecked,
1315
+ // path handling (client/platform.js resolvePath applied to a tool call)
1316
+ normalizeArgs,
1317
+ TOOL_PATH_ARGS,
1318
+ PATH_ARG_DESC,
1319
+ // limits (unit tests assert against them instead of hard-coding numbers)
1320
+ OUTPUT_CAP,
1321
+ READ_LINE_CAP,
1322
+ MATCH_CAP,
1323
+ READ_SIZE_CAP,
1324
+ GREP_SIZE_CAP,
1325
+ EXEC_TIMEOUT_DEFAULT,
1326
+ EXEC_TIMEOUT_CAP,
1327
+ EXEC_MAX_BUFFER,
1328
+ DIFF_MAX_CELLS,
1329
+ DIFF_MAX_LINES,
1330
+ };