aegisone 1.0.78 → 1.0.80

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # AEGISONE
2
2
 
3
- Product version: **1.0.78**
3
+ Product version: **1.0.80**
4
4
 
5
5
  One product, two faces: the terminal (`aegiscode`) and the window (`aegis-desktop`),
6
6
  reached through one command — `aegis` — and released as one version.
package/bin/aegis.js CHANGED
@@ -1,4 +1,4 @@
1
1
  #!/usr/bin/env node
2
2
  // SPDX-License-Identifier: AGPL-3.0-or-later
3
3
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
4
- "use strict";const fs=require("node:fs"),path=require("node:path"),{spawnSync:spawnSync,spawn:spawn}=require("node:child_process"),{decide:decide,FACE:FACE}=require("../src/dispatch.js"),WIN=require("../src/iface/window.js"),probes=require("../src/probes.js"),electronRepair=require("../src/electron-repair.js"),release=require("../src/release.js"),productHelp=require("../src/producthelp.js"),productUpdate=require("../src/productupdate.js"),EXIT_USAGE=2,PRODUCT=require("../package.json");function faceManifestPaths(e,t){const r=t||__dirname;return[path.join(r,"..","vendor",e.dir,"package.json"),path.join(r,"..","..",e.dir,"package.json")]}function readFaceVersions(e){return release.FACE_LINES.map(t=>{for(const r of faceManifestPaths(t,e))try{return{package:t.package,version:JSON.parse(fs.readFileSync(r,"utf8")).version,source:r}}catch{}return{package:t.package,version:null,source:null}})}function write(e,t){try{e.write(t.endsWith("\n")?t:t+"\n")}catch{}}function runUpdate(e,t,r){const n=t||{},{stdout:s,stderr:i,input:o}=r,a=void 0!==n.installed?n.installed:isInstalledLayout(n.binDir),c=n.updatePlan?n.updatePlan():productUpdate.plan({installed:a,env:o&&o.env||{}});if(!c.ok)return write(i,`aegis: ${c.msg}`),2;const u=n.fetchLatest||defaultFetchLatest(n.binDir);return productUpdate.check({current:PRODUCT.version,action:e.action},{fetchImpl:u}).then(t=>{for(const e of t.lines)write(s,e);if("apply"!==e.action)return!0===t.upToDate?0:1;const r=productUpdate.apply(c,t,{runImpl:n.runInstall||defaultRunInstall,spawnSpec:n.spawnSpec||defaultSpawnSpec(n.binDir)});if(r.ok){write(s,r.lines?r.lines[0]:"Installed.");for(const e of String(r.output||"").split("\n").slice(-6))e.trim()&&write(s,` ${e}`);return 0}return r.skipped?(write(s,` ${r.msg}`),!0===t.upToDate?0:1):(write(i,`aegis: ${r.msg||"the install failed"}`),r.error&&write(i,`aegis: ${r.error}`),r.command&&write(i,`aegis: run it yourself: ${r.command}`),3)})}function isInstalledLayout(e){const t=e||__dirname,r=path.join(t,"..");try{return!fs.existsSync(path.join(r,"..","one","package.json"))}catch{return!0}}function defaultFetchLatest(e){const t=e||__dirname,r=path.join(t,".."),n=[path.join(r,"client","update.js"),path.join(r,"vendor","cli","vendor","client","update.js")];for(const e of n)try{const t=require(e);if("function"==typeof t.fetchLatestDetailed)return e=>t.fetchLatestDetailed({...e||{},pkg:productUpdate.PRODUCT_PKG});if("function"==typeof t.fetchLatest)return e=>t.fetchLatest({...e||{},pkg:productUpdate.PRODUCT_PKG})}catch{}return null}function defaultSpawnSpec(e){const t=e||__dirname,r=path.join(t,".."),n=[path.join(r,"client","update.js"),path.join(r,"vendor","cli","vendor","client","update.js")],s={command:"npm",args:["i","-g",`${productUpdate.PRODUCT_PKG}@latest`]};for(const e of n)try{const t=require(e);if("function"==typeof t.installSpawn){const e=t.installSpawn(s,{env:process.env});if(e&&e.command)return e}}catch{}return null}function defaultRunInstall(e){try{const t=spawnSync(e.command,e.args,{encoding:"utf8",timeout:18e4,stdio:["ignore","pipe","pipe"],shell:!0===e.shell,windowsHide:!0});return t.error?{ok:!1,error:String(t.error.message||t.error)}:0!==t.status?{ok:!1,error:String((t.stderr||t.stdout||"").trim()||`exited ${t.status}`)}:{ok:!0,output:String(t.stdout||"")}}catch(e){return{ok:!1,error:String(e&&e.message||e)}}}const WINDOW_STDERR_NOISE=[/libva (error|warning)/i,/^libva:/i,/vaGetDriverNameByIndex|vaInitialize/,/gpu_init\.cc.*Passthrough is not supported/i,/gpu_persistent_cache\.cc.*Persistent cache error/i,/ERROR:gpu\/command_buffer\/service\/gles2_cmd_decoder/,/swiftshader|llvmpipe|MESA-LOADER|libGL error|DRI3|MESA-VULKAN/i,/^MESA-(VOID|DRI|LOADER)/,/vulkan.*(incomplete|not supported|failed)/i];function forwardWindowStderr(e,t){let r="";e.setEncoding("utf8"),e.on("data",e=>{r+=e;const n=r.split("\n");r=n.pop()||"";for(const e of n)e.trim()&&(WINDOW_STDERR_NOISE.some(t=>t.test(e))||write(t,e))});const n=()=>{r.trim()&&!WINDOW_STDERR_NOISE.some(e=>e.test(r))&&write(t,r),r=""};e.on("end",n),e.on("close",n),e.on("error",()=>{})}function statusOf(e){return"number"==typeof e.status?e.status:"SIGINT"===e.signal?130:"SIGTERM"===e.signal?143:1}function run(e,t){const r=t||{},n=r.stderr||process.stderr,s=r.stdout||process.stdout,i=r.repair||electronRepair.repairElectron;if(!r.input&&"function"==typeof i)try{i({})}catch{}const o=r.input||probes.collect({argv:e}),a=Array.isArray(e)?{...o,argv:e}:o,c=release.versionRequest(a.argv);if(c){const e=c.verbose?r.readFaceVersions?r.readFaceVersions():readFaceVersions(r.binDir):null;return write(s,release.renderVersion({product:{name:PRODUCT.name,version:PRODUCT.version},faces:e})),0}if((r.helpRequest||productHelp.helpRequest)(a.argv))return write(s,productHelp.renderHelp({version:PRODUCT.version})),0;const u=(r.updateRequest||productUpdate.updateRequest)(a.argv);if(u&&"help"===u.action)return write(s,productUpdate.renderUsage(PRODUCT.version)),0;if(u)return runUpdate(u,r,{stdout:s,stderr:n,input:a});const d=(a.argv||[]).indexOf("doctor");if(-1!==d&&!(a.argv||[]).slice(0,d).some(e=>!e.startsWith("-"))){const e=r.doctor||require("../src/doctor.js"),t=Object.assign({env:a.env,stdout:s,electron:a._electron||r.electron||null},r.doctorDeps||{}),n=e.main((a.argv||[]).slice(d+1),t);return"number"==typeof n?n:2}const p=decide(a);if(p.face===FACE.TUI&&!a._cliBin&&!r.cliBin)return write(n,"aegis: the terminal face is not installed beside aegisone."),write(n,"aegis: reinstall aegisone, or set AEGISONE_CLI_BIN to bin/aegiscode.js."),127;const l=r.permissions||require("../src/permissions.js"),f=(a.argv||[]).indexOf(l.SKIP_FLAG||"--dangerously-skip-permissions"),g=Boolean(a.tty&&a.tty.stdin&&a.tty.stdout),m=g?"interactive":"headless",h=r.stored||l.storedPermissionFacts(r.storedOpts||{}),w=l.resolvePosture({rules:void 0!==r.rules?r.rules:h.rules,gate:void 0!==r.gate?r.gate:h.confirmationsOn,permissionMode:void 0!==r.permissionMode?r.permissionMode:h.permissionMode,flag:-1!==f,env:a.env,interactive:g,childKind:m});w.warning&&write(n,`aegis: ${w.warning}`),w.skip&&w.skipFromFlag&&write(n,l.skipReport(w));const v=-1===f?p.args:p.args.filter(e=>e!==(l.SKIP_FLAG||"--dangerously-skip-permissions")),S=w.skipFromFlag?{AEGISONE_SKIP_PERMISSIONS:"1"}:{},I={AEGIS_INSTALL_METHOD:"npm"};if("1"===(a.env||{}).AEGISONE_PRINT_DECISION&&write(n,"aegis: decision "+JSON.stringify({face:p.face,kind:p.kind,reason:p.reason,args:v,skip:w.skip})),null===p.face)return write(n,`aegis: ${p.error}`),p.hint&&write(n,`aegis: ${p.hint}`),p.code||2;p.notice&&write(n,`aegis: ${p.notice} — running the terminal face.`);const _=r.spawnSync||spawnSync,O=r.spawn||spawn,E=Object.assign({},process.env,r.env||{});if(p.face===FACE.TUI){const e=a._cliBin||r.cliBin;return e?statusOf(_(process.execPath,[e,...v],{stdio:"inherit",env:Object.assign({},E,S,I),argv0:"aegiscode"})||{}):(write(n,"aegis: the terminal face is not installed beside aegisone."),write(n,"aegis: reinstall aegisone, or set AEGISONE_CLI_BIN to bin/aegiscode.js."),127)}const y=a._electron||r.electron,R=a._desktopMain||r.desktopMain,k=WIN.plan({decision:p,electron:Boolean(y),target:r.target||a.target});if(!k||!R)return write(n,"aegis: cannot open the window — Electron or the desktop entry point went missing after the check."),write(n,"aegis: Use --tui for the terminal face."),2;delete E.ELECTRON_RUN_AS_NODE;const j=WIN.open(k,{main:R,args:v,env:Object.assign({},E,S,I)},{openElectron:e=>{const t=O(process.execPath,[e.main,...e.args],{stdio:["ignore","ignore","pipe"],env:e.env,detached:!1});return t&&t.stderr&&forwardWindowStderr(t.stderr,n),t}});if(!j||!j.ok)return write(n,`aegis: cannot open the window — ${j&&j.msg||"no usable window plan"}.`),write(n,"aegis: Use --tui for the terminal face."),2;const D=j.handle;return new Promise(e=>{D.on("error",t=>{write(n,`aegis: could not start the window: ${t&&t.message}`),e(1)}),D.on("exit",(t,r)=>e(statusOf({status:t,signal:r})))})}function main(e){const t=run(e);return"number"==typeof t?(process.exitCode=t,t):t.then(e=>(process.exitCode=e,e))}if(module.exports={main:main,run:run,statusOf:statusOf,EXIT_USAGE:2,isInstalledLayout:isInstalledLayout,defaultFetchLatest:defaultFetchLatest},require.main===module){const e=main(process.argv.slice(2));e&&"function"==typeof e.then&&e.catch(e=>{write(process.stderr,`aegis: ${e&&e.stack||e}`),process.exitCode=1})}
4
+ "use strict";const fs=require("node:fs"),path=require("node:path"),{spawnSync:spawnSync,spawn:spawn}=require("node:child_process"),{decide:decide,FACE:FACE}=require("../src/dispatch.js"),WIN=require("../src/iface/window.js"),probes=require("../src/probes.js"),electronRepair=require("../src/electron-repair.js"),release=require("../src/release.js"),productHelp=require("../src/producthelp.js"),productUpdate=require("../src/productupdate.js"),EXIT_USAGE=2,PRODUCT=require("../package.json");function faceManifestPaths(e,t){const r=t||__dirname;return[path.join(r,"..","vendor",e.dir,"package.json"),path.join(r,"..","..",e.dir,"package.json")]}function readFaceVersions(e){return release.FACE_LINES.map(t=>{for(const r of faceManifestPaths(t,e))try{return{package:t.package,version:JSON.parse(fs.readFileSync(r,"utf8")).version,source:r}}catch{}return{package:t.package,version:null,source:null}})}function write(e,t){try{e.write(t.endsWith("\n")?t:t+"\n")}catch{}}function runUpdate(e,t,r){const n=t||{},{stdout:s,stderr:i,input:o}=r,a=void 0!==n.installed?n.installed:isInstalledLayout(n.binDir),c=n.updatePlan?n.updatePlan():productUpdate.plan({installed:a,env:o&&o.env||{}});if(!c.ok)return write(i,`aegis: ${c.msg}`),2;const d=n.fetchLatest||defaultFetchLatest(n.binDir);return productUpdate.check({current:PRODUCT.version,action:e.action},{fetchImpl:d}).then(t=>{for(const e of t.lines)write(s,e);if("apply"!==e.action)return!0===t.upToDate?0:1;const r=productUpdate.apply(c,t,{runImpl:n.runInstall||defaultRunInstall,spawnSpec:n.spawnSpec||defaultSpawnSpec(n.binDir)});if(r.ok){write(s,r.lines?r.lines[0]:"Installed.");for(const e of String(r.output||"").split("\n").slice(-6))e.trim()&&write(s,` ${e}`);return 0}return r.skipped?(write(s,` ${r.msg}`),!0===t.upToDate?0:1):(write(i,`aegis: ${r.msg||"the install failed"}`),r.error&&write(i,`aegis: ${r.error}`),r.command&&write(i,`aegis: run it yourself: ${r.command}`),3)})}function isInstalledLayout(e){const t=e||__dirname,r=path.join(t,"..");try{return!fs.existsSync(path.join(r,"..","one","package.json"))}catch{return!0}}function defaultFetchLatest(e){const t=e||__dirname,r=path.join(t,".."),n=[path.join(r,"client","update.js"),path.join(r,"vendor","cli","vendor","client","update.js")];for(const e of n)try{const t=require(e);if("function"==typeof t.fetchLatestDetailed)return e=>t.fetchLatestDetailed({...e||{},pkg:productUpdate.PRODUCT_PKG});if("function"==typeof t.fetchLatest)return e=>t.fetchLatest({...e||{},pkg:productUpdate.PRODUCT_PKG})}catch{}return null}function defaultSpawnSpec(e){const t=e||__dirname,r=path.join(t,".."),n=[path.join(r,"client","update.js"),path.join(r,"vendor","cli","vendor","client","update.js")],s={command:"npm",args:["i","-g",`${productUpdate.PRODUCT_PKG}@latest`]};for(const e of n)try{const t=require(e);if("function"==typeof t.installSpawn){const e=t.installSpawn(s,{env:process.env});if(e&&e.command)return e}}catch{}return null}function defaultRunInstall(e){try{const t=spawnSync(e.command,e.args,{encoding:"utf8",timeout:18e4,stdio:["ignore","pipe","pipe"],shell:!0===e.shell,windowsHide:!0});return t.error?{ok:!1,error:String(t.error.message||t.error)}:0!==t.status?{ok:!1,error:String((t.stderr||t.stdout||"").trim()||`exited ${t.status}`)}:{ok:!0,output:String(t.stdout||"")}}catch(e){return{ok:!1,error:String(e&&e.message||e)}}}const WINDOW_STDERR_NOISE=[/libva (error|warning)/i,/^libva:/i,/vaGetDriverNameByIndex|vaInitialize/,/gpu_init\.cc.*Passthrough is not supported/i,/gpu_persistent_cache\.cc.*Persistent cache error/i,/ERROR:gpu\/command_buffer\/service\/gles2_cmd_decoder/,/swiftshader|llvmpipe|MESA-LOADER|libGL error|DRI3|MESA-VULKAN/i,/^MESA-(VOID|DRI|LOADER)/,/vulkan.*(incomplete|not supported|failed)/i];function forwardWindowStderr(e,t){let r="";e.setEncoding("utf8"),e.on("data",e=>{r+=e;const n=r.split("\n");r=n.pop()||"";for(const e of n)e.trim()&&(WINDOW_STDERR_NOISE.some(t=>t.test(e))||write(t,e))});const n=()=>{r.trim()&&!WINDOW_STDERR_NOISE.some(e=>e.test(r))&&write(t,r),r=""};e.on("end",n),e.on("close",n),e.on("error",()=>{})}function statusOf(e){return"number"==typeof e.status?e.status:"SIGINT"===e.signal?130:"SIGTERM"===e.signal?143:1}function run(e,t){const r=t||{},n=r.stderr||process.stderr,s=r.stdout||process.stdout,i=r.repair||electronRepair.repairElectron;if(!r.input&&"function"==typeof i)try{i({})}catch{}const o=r.input||probes.collect({argv:e}),a=Array.isArray(e)?{...o,argv:e}:o,c=release.versionRequest(a.argv);if(c){const e=c.verbose?r.readFaceVersions?r.readFaceVersions():readFaceVersions(r.binDir):null;return write(s,release.renderVersion({product:{name:PRODUCT.name,version:PRODUCT.version},faces:e})),0}if((r.helpRequest||productHelp.helpRequest)(a.argv))return write(s,productHelp.renderHelp({version:PRODUCT.version})),0;const d=(r.updateRequest||productUpdate.updateRequest)(a.argv);if(d&&"help"===d.action)return write(s,productUpdate.renderUsage(PRODUCT.version)),0;if(d)return runUpdate(d,r,{stdout:s,stderr:n,input:a});const p=(a.argv||[]).indexOf("doctor");if(-1!==p&&!(a.argv||[]).slice(0,p).some(e=>!e.startsWith("-"))){const e=r.doctor||require("../src/doctor.js"),t=Object.assign({env:a.env,stdout:s,electron:a._electron||r.electron||null,appBundle:a._appBundle||r.appBundle||null},r.doctorDeps||{}),n=e.main((a.argv||[]).slice(p+1),t);return"number"==typeof n?n:2}const u=decide(a);if(u.face===FACE.TUI&&!a._cliBin&&!r.cliBin)return write(n,"aegis: the terminal face is not installed beside aegisone."),write(n,"aegis: reinstall aegisone, or set AEGISONE_CLI_BIN to bin/aegiscode.js."),127;const l=r.permissions||require("../src/permissions.js"),f=(a.argv||[]).indexOf(l.SKIP_FLAG||"--dangerously-skip-permissions"),g=Boolean(a.tty&&a.tty.stdin&&a.tty.stdout),m=g?"interactive":"headless",h=r.stored||l.storedPermissionFacts(r.storedOpts||{}),w=l.resolvePosture({rules:void 0!==r.rules?r.rules:h.rules,gate:void 0!==r.gate?r.gate:h.confirmationsOn,permissionMode:void 0!==r.permissionMode?r.permissionMode:h.permissionMode,flag:-1!==f,env:a.env,interactive:g,childKind:m});w.warning&&write(n,`aegis: ${w.warning}`),w.skip&&w.skipFromFlag&&write(n,l.skipReport(w));const v=-1===f?u.args:u.args.filter(e=>e!==(l.SKIP_FLAG||"--dangerously-skip-permissions")),S=w.skipFromFlag?{AEGISONE_SKIP_PERMISSIONS:"1"}:{},I={AEGIS_INSTALL_METHOD:"npm"};if("1"===(a.env||{}).AEGISONE_PRINT_DECISION&&write(n,"aegis: decision "+JSON.stringify({face:u.face,kind:u.kind,reason:u.reason,args:v,skip:w.skip})),null===u.face)return write(n,`aegis: ${u.error}`),u.hint&&write(n,`aegis: ${u.hint}`),u.code||2;u.notice&&write(n,`aegis: ${u.notice} — running the terminal face.`);const _=r.spawnSync||spawnSync,O=r.spawn||spawn,E=Object.assign({},process.env,r.env||{});if(u.face===FACE.TUI){const e=a._cliBin||r.cliBin;return e?statusOf(_(process.execPath,[e,...v],{stdio:"inherit",env:Object.assign({},E,S,I),argv0:"aegiscode"})||{}):(write(n,"aegis: the terminal face is not installed beside aegisone."),write(n,"aegis: reinstall aegisone, or set AEGISONE_CLI_BIN to bin/aegiscode.js."),127)}const y=a._electron||r.electron,R=a._desktopMain||r.desktopMain,k=a._appBundle||r.appBundle||null,j=WIN.plan({decision:u,electron:Boolean(y)||Boolean(k),target:r.target||a.target});if(!j||!R&&!k)return write(n,"aegis: cannot open the window — Electron or the desktop entry point went missing after the check."),write(n,"aegis: Use --tui for the terminal face."),2;delete E.ELECTRON_RUN_AS_NODE;const D=WIN.open(j,{main:R,args:v,env:Object.assign({},E,S,I)},{openElectron:e=>{if(k&&!R){const t=O(k,e.args||[],{stdio:["ignore","ignore","pipe"],env:e.env,detached:!1});return t&&t.stderr&&forwardWindowStderr(t.stderr,n),t}const t=O(process.execPath,[e.main,...e.args],{stdio:["ignore","ignore","pipe"],env:e.env,detached:!1});return t&&t.stderr&&forwardWindowStderr(t.stderr,n),t}});if(!D||!D.ok)return write(n,`aegis: cannot open the window — ${D&&D.msg||"no usable window plan"}.`),write(n,"aegis: Use --tui for the terminal face."),2;const U=D.handle;return new Promise(e=>{U.on("error",t=>{write(n,`aegis: could not start the window: ${t&&t.message}`),e(1)}),U.on("exit",(t,r)=>e(statusOf({status:t,signal:r})))})}function main(e){const t=run(e);return"number"==typeof t?(process.exitCode=t,t):t.then(e=>(process.exitCode=e,e))}if(module.exports={main:main,run:run,statusOf:statusOf,EXIT_USAGE:2,isInstalledLayout:isInstalledLayout,defaultFetchLatest:defaultFetchLatest},require.main===module){const e=main(process.argv.slice(2));e&&"function"==typeof e.then&&e.catch(e=>{write(process.stderr,`aegis: ${e&&e.stack||e}`),process.exitCode=1})}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "aegisone",
3
3
  "productName": "AEGISONE",
4
- "version": "1.0.78",
4
+ "version": "1.0.80",
5
5
  "description": "AEGISONE — one product, two faces. `aegis` opens the window when there is nothing else to do and runs the terminal otherwise; `aegiscode` keeps behaving exactly as it always has.",
6
6
  "author": {
7
7
  "name": "AEGIS Code",
@@ -1,4 +1,4 @@
1
1
  #!/usr/bin/env node
2
2
  // SPDX-License-Identifier: AGPL-3.0-or-later
3
3
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
4
- import e from"node:fs";import s from"node:path";import{spawnSync as r}from"node:child_process";import{fileURLToPath as t,pathToFileURL as o}from"node:url";import{createRequire as n}from"node:module";const i=s.dirname(t(import.meta.url)),a=n(import.meta.url);export const ONE_DIR=s.join(i,"..");export const REPO_DIR=s.join(ONE_DIR,"..");export const CLI_DIR=s.join(REPO_DIR,"cli");export const DESKTOP_DIR=s.join(REPO_DIR,"desktop");export const CLI_VENDOR=s.join(CLI_DIR,"vendor");export const DESKTOP_VENDOR=s.join(DESKTOP_DIR,"vendor");export const ONE_VENDOR=s.join(ONE_DIR,"vendor");export const MANIFEST=[{src:"client/aegis.js",shapes:["mirror","flat"],note:"the thin transport — the one implementation of the wire format"},{src:"client/update.js",shapes:["mirror","flat"],note:"the npm update checker (the desktop own update path)"},{src:"client/foreign-memory.js",shapes:["mirror","flat"],note:"required by mcp/tools.js as ../client/foreign-memory.js"},{src:"client/foreign-sessions.js",shapes:["mirror","flat"],note:"required by desktop/main.js as ./vendor/foreign-sessions.js"},{src:"client/credentials.js",shapes:["mirror","flat"],note:"the account credential store, shared by all three hosts"},{src:"client/session-store.js",shapes:["mirror","flat"],note:"the unified session store — one list in every host"},{src:"client/session-search.js",shapes:["mirror","flat"],note:"the SESSION search ranking: the desktop sheet (Cmd/Ctrl+K) and the terminal /resume picker filter with this one module, pure and fs-free"},{src:"client/credits.js",shapes:["mirror","flat"],note:"the licence/attribution payload: parses LICENSING.md and the two NOTICE files for Help > Credits & licence and /license + /credits"},{src:"client/naming.js",shapes:["mirror","flat"],note:"the conversation-naming ladder — ONE implementation for the terminal and the window (cli/src/naming.js re-exports it)"},{src:"client/prefs.js",shapes:["mirror","flat"],note:"the shared non-secret preference store (D5) — the CLI and the desktop store both read/write it"},{src:"client/env-file.js",shapes:["mirror","flat"],note:"the shared ~/.aegiscode/.env loader, resolved before any key is read"},{src:"client/auto-provision.js",shapes:["mirror","flat"],note:"free device key on first launch; requires ./device-fingerprint.js"},{src:"client/device-fingerprint.js",shapes:["mirror","flat"],note:"the machine identity auto-provision.js and presence.js require"},{src:"client/install-register.js",shapes:["mirror","flat"],note:"register-at-install; the shared body behind both postinstall hooks"},{src:"client/presence.js",shapes:["mirror","flat"],note:"the heartbeat beacon; requires ./presence-constants.js and ./device-fingerprint.js"},{src:"client/presence-constants.js",shapes:["mirror","flat"],note:"the beacon constants — a package without them loses the beacon silently"},{src:"client/touch.js",shapes:["mirror","flat"],note:"phi(alpha): the digest module fingerprint.js requires as ./touch.js"},{src:"client/fingerprint.js",shapes:["mirror","flat"],note:"phi(alpha): the sealed session record, resolved by src/fingerprint.js"},{src:"client/authorship-key.js",shapes:["mirror","flat"],note:"phi(alpha): the authorship key, required by ./attest.js and ./record-vault.js"},{src:"client/attest.js",shapes:["mirror","flat"],note:"phi(alpha): attestation, requires ./fingerprint.js and ./authorship-key.js"},{src:"client/record-vault.js",shapes:["mirror","flat"],note:"the vault, and its refusal to copy the key with the record"},{src:"client/brain-catalog.js",shapes:["mirror","flat"],note:"the pooled-brain rule, required at load time by the engine and src/models.js"},{src:"client/byok-catalog.js",shapes:["mirror","flat"],note:"the BYOK model additions the server catalog does not name"},{src:"client/catalog-client.js",shapes:["mirror","flat"],note:"the server's cached catalog, layered between the shipped additions and the user's own models"},{src:"client/user-models.js",shapes:["mirror","flat"],note:"the models the USER declares, in one file both hosts read (requires ./credentials.js)"},{src:"client/model-discovery.js",shapes:["mirror","flat"],note:"asks the vendor what it serves, so adding a new model is not a memory test (requires ./user-models.js)"},{src:"client/model-sync.js",shapes:["mirror","flat"],note:"reconciles the ids AEGIS promotes against the ids each vendor issues, and writes the difference through ./user-models.js (requires ./model-discovery.js)"},{src:"client/model-autosync.js",shapes:["mirror","flat"],note:"the scheduler that turns the modelAutoSync preference into work: runs ./model-sync.js on a cadence in whichever host is open (requires ./model-sync.js)"},{src:"client/hooks.js",shapes:["mirror","flat"],note:"the shared hook layer behind /hooks and the repo guard installer"},{src:"client/skills.js",shapes:["mirror","flat"],note:"the ONE skill registry: /skills lists and creates through it and the window's Settings > Skills card reads the same scan, so a packaged CLI that loses this row and the desktop that keeps it would disagree about which skills exist"},{src:"client/speech.js",shapes:["mirror","flat"],note:"the pure dictation decision (may we dictate, with what argv) behind the composer mic; desktop/lib/speech-resolve.js requires it as ../vendor/speech.js in a packaged build"},{src:"client/platform.js",shapes:["mirror","flat"],note:"the ONE place that decides which OS this is (Phase 30.1)"},{src:"client/topup.js",shapes:["mirror","flat"],note:"the token-bank top-up: amount bounds, the balance reading, and the credit watch every host drives"},{src:"client/google-signin.js",shapes:["mirror","flat"],note:"the localhost half of aegis1's desktop Google OAuth round-trip; `connect --google` drives it"},{src:"client/drive-connect.js",shapes:["mirror","flat"],note:"the desktop half of aegis1's Drive OAuth (/connect/drive, /api/drive/token); requires ./aegis.js only via the caller"},{src:"client/drive-upload.js",shapes:["mirror","flat"],note:"the Drive v3 REST wrapper that uploads the memory backup and one conversation per save"},{src:"client/conversation-export.js",shapes:["mirror","flat"],note:"the authorship stamp at the top of every uploaded file, and the two backup scope names"},{src:"mcp/tools.js",shapes:["mirror"],note:"the shared tool registry; requires ../client/foreign-memory.js"},{src:"mcp/server.js",shapes:["mirror"],note:"the stdio MCP server every installed editor config names (compiled, never required)"},{src:"mcp/admission.js",shapes:["mirror"],note:"the admission gate server.js requires at load (`./admission.js`): which harness may call the bridge, and what it may run — omitted from the manifest when 2066f82 added it, so both staged trees shipped a server that could not load"},{src:"hosts/spec.js",shapes:["mirror"],note:"the canonical server spec, staged under its own directory so it finds vendor/mcp/server.js"},{src:"hosts/targets.js",shapes:["mirror"],note:"the editor target registry"},{src:"hosts/install.js",shapes:["mirror"],note:"the merge-only installer behind aegiscode mcp install"},{src:"hosts/openai-shim.js",shapes:["mirror"],note:"the loopback OpenAI-compatible shim"},{src:"desktop/renderer/usage.js",shapes:["mirror"],note:"the pure usage mapping shared by the window and the terminal"},{src:"desktop/lib/local/engine.js",shapes:["mirror"],note:"the agent loop, reused as-is (one loop, not a second one drifting)"},{src:"desktop/lib/local/claude-pro.js",shapes:["mirror"],note:"the Claude Code Pro transport; requires ./../../one/src/child.js at call time"},{src:"one/src/child.js",shapes:["mirror"],note:"the ONE claude-child argv builder (rule 4); resolved by claude-pro.js at call time"},{src:"one/src/permissions.js",shapes:["mirror"],note:"resolvePosture() — the permission half of the argv, resolved at call time"},{src:"desktop/lib/local/local.js",shapes:["mirror"],note:"the local model transport and its fail-closed base-URL check"},{src:"desktop/lib/local/context.js",shapes:["mirror"],note:"the token-budget trimmer local.js requires at load"},{src:"desktop/lib/local/attachments.js",shapes:["mirror"],note:"content-part builder for dropped files; required at load by engine.js and local.js"},{src:"desktop/lib/local/session-rounds.js",shapes:["mirror"],note:"interrupted-turn bookkeeping; required at load by engine.js"},{src:"desktop/lib/local/pro-sessions.js",shapes:["mirror"],note:"durable Claude-Pro conversation session ids; required at load by engine.js"},{src:"desktop/lib/local/tools.js",shapes:["mirror"],note:"the tool implementations (persistent shell, editFile, grep, exec)"},{src:"desktop/lib/local/shell.js",shapes:["mirror"],note:"the persistent shell, required by tools.js"},{src:"desktop/lib/local/sandbox.js",shapes:["mirror"],note:"the outcome bound (agent-safety-plan §1b), required by shell.js + tools.js"},{src:"desktop/lib/local/sandbox-bwrap.js",shapes:["mirror"],note:"bubblewrap mechanism behind sandbox.js (agent-safety-plan §1d)"},{src:"desktop/lib/local/sandbox-seatbelt.js",shapes:["mirror"],note:"Seatbelt mechanism behind sandbox.js (agent-safety-plan §1d)"},{src:"desktop/lib/local/sandbox-appcontainer.js",shapes:["mirror"],note:"AppContainer mechanism behind sandbox.js (agent-safety-plan §1e)"},{src:"desktop/lib/local/perm-rules.js",shapes:["mirror"],note:"stored /permissions rules for the desktop gate (agent-safety-plan §2), required by engine.js"},{src:"desktop/lib/local/perm-write.js",shapes:["mirror"],note:'the durable "always allow this command" answer (agent-safety-plan §3), required by main.js'},{src:"desktop/lib/local/perm-store.js",shapes:["mirror"],note:"the Settings rules editor (agent-safety-plan §4), required by main.js"},{src:"desktop/lib/local/integrity.js",shapes:["mirror"],note:"the desktop second gate; required at load by shell.js and tools.js, and the seal over its own four units"},{src:"desktop/main.js",shapes:["mirror"],bytesOnly:!0,note:"seal unit d1 — hashed by integrity.js as BYTES and never required from the mirror, so its own requires (the whole Electron main-process closure) are not staged behind it"},{src:"desktop/lib/local/spill.js",shapes:["mirror"],note:"oversized-output spill, required at load by tools.js and shell.js"},{src:"desktop/lib/local/exec-plan.js",shapes:["mirror"],note:"exec one-shot eligibility classifier, required at load by engine.js"},{src:"desktop/lib/local/agents.js",shapes:["mirror"],note:"Task subagents"},{src:"desktop/lib/local/prompt.js",shapes:["mirror"],note:"the system prompt builder"},{src:"desktop/lib/settings.js",shapes:["mirror"],note:"the provider-config store (base URL + key per provider)"},{src:"desktop/lib/local/turn-guard.js",shapes:["mirror"],note:"engine.js requires it at load; it requires ./git-scope.js"},{src:"desktop/lib/local/repeat-guard.js",shapes:["mirror"],note:"engine.js requires it at load — identical-call detection, no deps of its own"},{src:"desktop/lib/local/verify-stop.js",shapes:["mirror"],note:"engine.js requires it at load — edited-but-unchecked nudge, no deps of its own"},{src:"desktop/lib/local/check-command.js",shapes:["mirror"],note:"verify-stop.js requires it lazily — which command would check this repo; no deps"},{src:"desktop/lib/local/worktree-lock.js",shapes:["mirror"],note:"engine.js requires it at load"},{src:"desktop/lib/local/git-scope.js",shapes:["mirror"],note:"the write-scope rule turn-guard.js and the queues share"},{src:"desktop/lib/local/queue.js",shapes:["mirror"],note:"the autonomous work queue"},{src:"desktop/lib/local/autonomous.js",shapes:["mirror"],note:"the unattended worker; requires ./queue.js and ./git-scope.js"},{src:"desktop/lib/local/entitlement.js",shapes:["mirror"],note:"the shared Pro gate (account probe injected by the caller)"},{src:"desktop/lib/local/covenant.js",shapes:["mirror"],note:"the pre-action gate engine.js requires unconditionally at load"},{src:"desktop/lib/local/aegis-seal.mjs",shapes:["mirror"],note:"the codec covenant.js requires the first time it decodes"},{src:"covenant/aegis.seal",shapes:["mirror","nested"],note:"the sealed covenant (AES/1 container) — path shape is load-bearing"},{src:"covenant/README.md",shapes:["mirror","nested"],note:"the decode notice shipped beside the artifact"},{src:"tools/agent-gate.mjs",shapes:["mirror","flat"],note:"the in-process half of the lock; without it a packaged app had NO gate"},{src:"one/src/selfhost.js",shapes:["mirror","flat"],note:"the packaged launcher decision — which face this artifact was asked for"},{src:"one/src/protocol.js",shapes:["mirror","flat"],note:"the core/frontend seam; desktop/lib/local/pty-host.js speaks it over Electron IPC"},{src:"one/src/iface/pty.js",shapes:["mirror","flat"],note:"plans pty|refuse and spawns the native pty; required by desktop/lib/local/pty-host.js at call time"}];export function entriesFor(e){const r=[];for(const t of MANIFEST){if(!t.shapes.includes(e))continue;let o;if("mirror"===e)o=s.join(CLI_VENDOR,t.src);else if("flat"===e)o=s.join(DESKTOP_VENDOR,s.basename(t.src));else{if("nested"!==e)throw new Error(`predist: unknown shape ${e}`);o=s.join(DESKTOP_VENDOR,t.src)}r.push({src:t.src,dest:o,from:s.join(REPO_DIR,t.src)})}return r}export const SHAPES=["mirror","flat","nested"];const c=[["cli",CLI_DIR,["bin","src","vendor","scripts","package.json","README.md","LICENSE"]],["desktop",DESKTOP_DIR,["main.js","preload.js","lib","renderer","bin","vendor","package.json","README.md"]]],l=new Set(["node_modules","release",".git",".cache","out"]),d=new Map([["desktop/vendor",new Set(["faces","sandbox"])]]);function h(r,t,o){const n=o||new Set,i=(e,s)=>l.has(e)||e.endsWith(".log")||n.has(s),a=(r,t)=>{if(e.mkdirSync(s.dirname(t),{recursive:!0}),e.copyFileSync(r,t),!e.readFileSync(r).equals(e.readFileSync(t)))throw new Error(`predist: bundle copy differs from source: ${s.relative(REPO_DIR,r)}`)},c=(r,o)=>{const n=e.lstatSync(r);if(!n.isSymbolicLink())if(n.isFile())a(r,s.join(t,o));else for(const t of e.readdirSync(r)){const e=o?s.join(o,t):t;i(t,e)||c(s.join(r,t),e)}};e.lstatSync(r).isFile()?a(r,t):c(r,"")}const p="AEGISONE_PREDIST_LOCK_TOKEN";let u=null,m=!1,f=0;function g(e){try{return process.kill(e,0),!0}catch(e){return Boolean(e)&&"EPERM"===e.code}}const j=e=>new Promise(s=>setTimeout(s,e));function y(){if(f>0)return void f--;const s=u,r=m,t=process.env[p];if(u=null,m=!1,s&&r){t&&delete process.env[p];try{e.unlinkSync(s)}catch{}}}export async function acquireStageLock(r){if(u)return f++,y;const t=r&&r.stdout||process.stdout;return await async function(r){const t=function(){const r=s.join(REPO_DIR,".git");let t=r;try{if(!e.lstatSync(r).isDirectory()){const o=/^gitdir:\s*(.+)$/m.exec(e.readFileSync(r,"utf8"));o&&(t=s.resolve(REPO_DIR,o[1].trim()))}}catch{t=r}return s.join(t,"aegisone-predist.lock")}(),o=Date.now()+12e4,n=process.env[p]||null;let i=null,a=!1;for(;;){if(n)try{const s=String(e.readFileSync(t,"utf8")).split("\n")[1];if(s&&s.trim()===n)return u=t,void(m=!1)}catch{}try{i=`${Date.now().toString(36)}-${process.pid}-${Math.random().toString(36).slice(2,10)}`;const s=e.openSync(t,"wx");return e.writeSync(s,`${process.pid}\n${i}\n`),e.closeSync(s),u=t,m=!0,void(process.env[p]=i)}catch(e){if(!e||"EEXIST"!==e.code)throw e}let s=null,c=0;try{s=e.statSync(t),c=Number(String(e.readFileSync(t,"utf8")).split("\n")[0].trim())}catch{continue}if(Date.now()-s.mtimeMs>6e5||Number.isFinite(c)&&c>0&&!g(c)){r(`predist: breaking an abandoned staging lock (pid ${c||"unknown"})`);try{e.unlinkSync(t)}catch{}}else{if(Date.now()>o)throw new Error(`predist: another stager (pid ${c||"unknown"}) has held ${t} for over ${Math.round(120)}s. Staging is destructive — it removes and rewrites cli/vendor, desktop/vendor and one/vendor — so it will not run concurrently with a peer. Wait for it, or delete the lock if that process is gone.`);a||(a=!0,r(`predist: another stager (pid ${c||"unknown"}) is running — waiting for it (concurrent staging would read a vendor tree the peer is rewriting)`)),await j(50+Math.floor(50*Math.random()))}}}(e=>t.write(`${e}\n`)),y}function b(r,t){const o=[];for(const s of r){if(!e.existsSync(s.from))throw new Error(`predist: missing shared module: ${s.src} (expected at ${s.from})`);if(w(s.from,s.dest),!e.readFileSync(s.from).equals(e.readFileSync(s.dest)))throw new Error(`predist: staged copy differs from source: ${s.src}`);o.push(s)}return t&&function(r,t){if(!e.existsSync(r))return 0;const o=r=>{for(const n of e.readdirSync(r,{withFileTypes:!0})){const i=s.join(r,n.name);if(n.isDirectory()){o(i);try{e.rmdirSync(i)}catch{}}else t.has(i)||e.unlinkSync(i)}};o(r)}(t,new Set(o.map(e=>e.dest))),o}function w(r,t){e.mkdirSync(s.dirname(t),{recursive:!0});const o=`${t}.tmp-${process.pid}-${Math.random().toString(36).slice(2,10)}`;e.copyFileSync(r,o);try{e.renameSync(o,t)}catch(s){try{e.unlinkSync(o)}catch{}throw s}}function v(e){return e.replace(/\/\*[\s\S]*?\*\//g,"").replace(/(^|[^:])\/\/.*$/gm,"$1")}export async function stage(t){const n=t||{},i=n.io||{},l=i.stdout||process.stdout,p=(i.stderr||process.stderr,Array.isArray(n.shapes)?n.shapes:[...SHAPES,"bundle"]),u=e=>p.includes(e),m=e=>l.write(`${e}\n`),f=await acquireStageLock(i);try{return await async function({want:t,log:n}){const i={mirror:null,flat:null,nested:null,bundle:null};if(t("mirror")){const e=b(entriesFor("mirror"),CLI_VENDOR);n(`predist: staged ${e.length} shared modules into cli/vendor/`);for(const s of e)n(` ${s.src} -> vendor/${s.src}`);i.mirror={staged:e.length}}if(t("nested")&&(i.nested={staged:b(entriesFor("nested"),null).length}),t("flat")){const e=b(entriesFor("flat"),null);for(const s of e)n(`staged ${s.dest}`);i.flat={staged:e.length}}if(t("mirror")&&t("flat"))for(const r of MANIFEST){if(!r.shapes.includes("mirror")||!r.shapes.includes("flat"))continue;const t=s.join(CLI_VENDOR,r.src),o=s.join(DESKTOP_VENDOR,s.basename(r.src));if(!e.readFileSync(t).equals(e.readFileSync(o)))throw new Error(`predist: the two shapes disagree for ${r.src}`)}if(t("mirror")){const r=function(r){const t=s.join(CLI_VENDOR,"mcp","tools.js");delete a.cache[a.resolve(t)];const{createTools:o}=a(t),n=o({apiBase:"http://127.0.0.1",apiKey:"predist-probe",randomUUID:()=>"id"}).toolList().length;if(0===n)throw new Error("predist: staged registry exposes no tools");const i=a("node:vm"),c=s.join(CLI_VENDOR,"mcp","server.js");new i.Script(e.readFileSync(c,"utf8"),{filename:c});const l=s.join(CLI_VENDOR,"hosts"),d=a(s.join(l,"spec.js")),h=a(s.join(l,"install.js")),p=a(s.join(l,"targets.js")),u=d.resolveServer({AEGIS_MCP_SERVER:""});if(!u.exists||u.path!==c)throw new Error(`predist: staged hosts/spec.js resolves the server as ${u.path} (exists: ${u.exists}), expected ${c}. An installed aegiscode would write editor configs pointing at a file the package never shipped. Candidates were:\n ${u.candidates.join("\n ")}`);const m=p.getTarget("vscode"),f=h.planTarget(m,"user",{ctx:h.hostCtx({home:s.join(CLI_VENDOR,".predist-home"),env:{},cwd:REPO_DIR}),specOpts:{env:{AEGIS_MCP_SERVER:""}}}),g=[];!function e(s){"string"==typeof s?g.push(s):Array.isArray(s)?s.forEach(e):s&&"object"==typeof s&&Object.values(s).forEach(e)}(f.after?JSON.parse(f.after):{});const j=g.some(e=>e===c);if(f.error||!f.changed||!j)throw new Error(`predist: a planned vscode install does not name the staged server (error: ${f.error&&f.error.message}, changed: ${f.changed})`);if("function"!=typeof a(s.join(l,"openai-shim.js")).createShimServer)throw new Error("predist: staged hosts/openai-shim.js exposes no createShimServer");return{count:n,targets:p.targetIds().length,staged:r.length}}(entriesFor("mirror"));n(`predist: staged registry loads standalone (${r.count} tools)`),n(`predist: editor layer verified (${r.targets} host targets, server resolves to vendor/mcp/server.js, shim loads)`);const t=await async function(){const e=s.join(CLI_VENDOR,"tools","agent-gate.mjs");if("function"!=typeof(await(import(o(e).href))).run)throw new Error("predist: staged tools/agent-gate.mjs exposes no run()");return e}();n(`predist: ${s.relative(REPO_DIR,t)} loads standalone and exposes run()`),i.mirror.proof=r}if(t("flat")){const r=function(r){const t=new Set(r.map(e=>s.basename(e.dest)));for(const o of r){const r=v(e.readFileSync(o.dest,"utf8"));for(const e of r.matchAll(/require\(\s*'((?:\.\.?\/)[^']+)'\s*\)/g)){const r=e[1];if(s.basename(r).replace(/\.[cm]?js$/,""),r.replace(/^\.\//,"").startsWith("../"))throw new Error(`predist: flat-staged ${s.basename(o.dest)} requires '${r}', which escapes vendor/ — flattening only works for same-directory requires (add the target to the manifest, or stop staging this file flat)`);const n=r.replace(/^\.\//,"");if(!t.has(n))throw new Error(`predist: flat-staged ${s.basename(o.dest)} requires '${r}', which is not staged into desktop/vendor/ — the packaged app would throw MODULE_NOT_FOUND before the window could open`)}}const o=a(s.join(DESKTOP_VENDOR,"aegis.js"));if(!o||0===Object.keys(o).length)throw new Error("predist: staged desktop/vendor/aegis.js loads but exports nothing");return{files:r.length,exports:Object.keys(o).length}}(entriesFor("flat"));n(`predist: flattened tree is self-contained (${r.files} files, ${r.exports} transport exports) — no staged module escapes vendor/`),i.flat.proof=r}if(t("bundle")){for(const[r,t,o]of c){const i=s.join(ONE_VENDOR,r);e.rmSync(i,{recursive:!0,force:!0});for(const n of o){const o=s.join(t,n);if(!e.existsSync(o)){if("LICENSE"===n||"README.md"===n)continue;throw new Error(`predist: bundle source missing: ${s.relative(REPO_DIR,o)}`)}h(o,s.join(i,n),d.get(`${r}/${n}`))}n(`staged the ${r} face into one/vendor/${r}/`)}const t=function(){const t=s.join(ONE_VENDOR,"cli"),o=s.join(t,"src","deps.js"),n=r(process.execPath,["-e","const d=require(process.argv[1]);console.log(JSON.stringify(d.paths))",o],{cwd:t,encoding:"utf8"});if(0!==n.status)throw new Error(`predist: the bundled CLI does not load: ${n.stderr||n.stdout}`);const i=JSON.parse(n.stdout),a=[];let l=0;for(const[e,r]of Object.entries(i)){const t=s.relative(ONE_VENDOR,r);t.startsWith("..")||s.isAbsolute(t)?a.push(`${e} -> ${r}`):"cli"!==t.split(s.sep)[0]&&l++}if(a.length)throw new Error(`predist: the bundled CLI resolves these shared modules OUTSIDE the bundle (${ONE_VENDOR}) — the product tarball would depend on a repo checkout:\n `+a.join("\n "));if(!e.existsSync(s.join(t,"bin","aegiscode.js")))throw new Error("predist: the bundle has no cli/bin/aegiscode.js");const d=[];for(const[r,t,o]of c)for(const n of o){const o=s.join(ONE_VENDOR,r,n);let i=null,a=null;try{i=e.lstatSync(s.join(t,n))}catch{continue}try{a=e.lstatSync(o)}catch{d.push(`${r}/${n} -> missing`);continue}i.isFile()&&!a.isFile()&&d.push(`${r}/${n} -> not a regular file`),i.isDirectory()&&!a.isDirectory()&&d.push(`${r}/${n} -> not a directory`)}if(d.length)throw new Error(`predist: the bundle staged these in the wrong shape:\n ${d.join("\n ")}`);return{modules:Object.keys(i).length,inSiblingFace:l}}();n(`predist: the bundled CLI resolves ${t.modules} shared modules from inside one/vendor/ (${t.inSiblingFace} through the bundled desktop face) — no repo checkout needed`),i.bundle=t;const o=s.join(DESKTOP_VENDOR,"faces");e.rmSync(o,{recursive:!0,force:!0}),h(s.join(ONE_VENDOR,"cli"),s.join(o,"cli"));const a=s.join(o,"cli","bin","aegiscode.js");if(!e.existsSync(a))throw new Error(`predist: the packaged terminal face has no entry point at ${s.relative(REPO_DIR,a)} — the artifact would open a window for every \`aegiscode\`/\`--tui\` invocation`);n(`staged the terminal face into desktop/vendor/faces/cli/ (${s.basename(a)})`),i.faces={entry:s.relative(REPO_DIR,a)}}return i}({want:u,log:m})}finally{f()}}export async function main(e,s){const r=s||{},t=Array.isArray(e)?e:[],o=t.includes("--quiet")?{write:()=>!0}:r.stdout||process.stdout,n=r.stderr||process.stderr;let i;t.includes("--mirror-only")?i=["mirror"]:t.includes("--flat-only")?i=["flat","nested"]:t.includes("--bundle-only")&&(i=["bundle"]);try{return await stage({shapes:i,io:{stdout:o,stderr:n}}),0}catch(e){return n.write(`${e&&e.message}\n`),1}}!function(){const e=process.argv[1];let r=!1;if(e)try{r=s.resolve(e)===t(import.meta.url)}catch{r=!1}r&&main(process.argv.slice(2)).then(e=>{process.exitCode=e})}();
4
+ import e from"node:fs";import s from"node:path";import{spawnSync as r}from"node:child_process";import{fileURLToPath as t,pathToFileURL as o}from"node:url";import{createRequire as n}from"node:module";const i=s.dirname(t(import.meta.url)),a=n(import.meta.url);export const ONE_DIR=s.join(i,"..");export const REPO_DIR=s.join(ONE_DIR,"..");export const CLI_DIR=s.join(REPO_DIR,"cli");export const DESKTOP_DIR=s.join(REPO_DIR,"desktop");export const CLI_VENDOR=s.join(CLI_DIR,"vendor");export const DESKTOP_VENDOR=s.join(DESKTOP_DIR,"vendor");export const ONE_VENDOR=s.join(ONE_DIR,"vendor");export const MANIFEST=[{src:"client/aegis.js",shapes:["mirror","flat"],note:"the thin transport — the one implementation of the wire format"},{src:"client/update.js",shapes:["mirror","flat"],note:"the npm update checker (the desktop own update path)"},{src:"client/foreign-memory.js",shapes:["mirror","flat"],note:"required by mcp/tools.js as ../client/foreign-memory.js"},{src:"client/foreign-sessions.js",shapes:["mirror","flat"],note:"required by desktop/main.js as ./vendor/foreign-sessions.js"},{src:"client/credentials.js",shapes:["mirror","flat"],note:"the account credential store, shared by all three hosts"},{src:"client/session-store.js",shapes:["mirror","flat"],note:"the unified session store — one list in every host"},{src:"client/session-search.js",shapes:["mirror","flat"],note:"the SESSION search ranking: the desktop sheet (Cmd/Ctrl+K) and the terminal /resume picker filter with this one module, pure and fs-free"},{src:"client/credits.js",shapes:["mirror","flat"],note:"the licence/attribution payload: parses LICENSING.md and the two NOTICE files for Help > Credits & licence and /license + /credits"},{src:"client/naming.js",shapes:["mirror","flat"],note:"the conversation-naming ladder — ONE implementation for the terminal and the window (cli/src/naming.js re-exports it)"},{src:"client/prefs.js",shapes:["mirror","flat"],note:"the shared non-secret preference store (D5) — the CLI and the desktop store both read/write it"},{src:"client/env-file.js",shapes:["mirror","flat"],note:"the shared ~/.aegiscode/.env loader, resolved before any key is read"},{src:"client/auto-provision.js",shapes:["mirror","flat"],note:"free device key on first launch; requires ./device-fingerprint.js"},{src:"client/device-fingerprint.js",shapes:["mirror","flat"],note:"the machine identity auto-provision.js and presence.js require"},{src:"client/install-register.js",shapes:["mirror","flat"],note:"register-at-install; the shared body behind both postinstall hooks"},{src:"client/presence.js",shapes:["mirror","flat"],note:"the heartbeat beacon; requires ./presence-constants.js and ./device-fingerprint.js"},{src:"client/presence-constants.js",shapes:["mirror","flat"],note:"the beacon constants — a package without them loses the beacon silently"},{src:"client/touch.js",shapes:["mirror","flat"],note:"phi(alpha): the digest module fingerprint.js requires as ./touch.js"},{src:"client/fingerprint.js",shapes:["mirror","flat"],note:"phi(alpha): the sealed session record, resolved by src/fingerprint.js"},{src:"client/authorship-key.js",shapes:["mirror","flat"],note:"phi(alpha): the authorship key, required by ./attest.js and ./record-vault.js"},{src:"client/attest.js",shapes:["mirror","flat"],note:"phi(alpha): attestation, requires ./fingerprint.js and ./authorship-key.js"},{src:"client/record-vault.js",shapes:["mirror","flat"],note:"the vault, and its refusal to copy the key with the record"},{src:"client/brain-catalog.js",shapes:["mirror","flat"],note:"the pooled-brain rule, required at load time by the engine and src/models.js"},{src:"client/byok-catalog.js",shapes:["mirror","flat"],note:"the BYOK model additions the server catalog does not name"},{src:"client/catalog-client.js",shapes:["mirror","flat"],note:"the server's cached catalog, layered between the shipped additions and the user's own models"},{src:"client/user-models.js",shapes:["mirror","flat"],note:"the models the USER declares, in one file both hosts read (requires ./credentials.js)"},{src:"client/model-discovery.js",shapes:["mirror","flat"],note:"asks the vendor what it serves, so adding a new model is not a memory test (requires ./user-models.js)"},{src:"client/model-sync.js",shapes:["mirror","flat"],note:"reconciles the ids AEGIS promotes against the ids each vendor issues, and writes the difference through ./user-models.js (requires ./model-discovery.js)"},{src:"client/model-autosync.js",shapes:["mirror","flat"],note:"the scheduler that turns the modelAutoSync preference into work: runs ./model-sync.js on a cadence in whichever host is open (requires ./model-sync.js)"},{src:"client/hooks.js",shapes:["mirror","flat"],note:"the shared hook layer behind /hooks and the repo guard installer"},{src:"client/skills.js",shapes:["mirror","flat"],note:"the ONE skill registry: /skills lists and creates through it and the window's Settings > Skills card reads the same scan, so a packaged CLI that loses this row and the desktop that keeps it would disagree about which skills exist"},{src:"client/speech.js",shapes:["mirror","flat"],note:"the pure dictation decision (may we dictate, with what argv) behind the composer mic; desktop/lib/speech-resolve.js requires it as ../vendor/speech.js in a packaged build"},{src:"client/platform.js",shapes:["mirror","flat"],note:"the ONE place that decides which OS this is (Phase 30.1)"},{src:"client/topup.js",shapes:["mirror","flat"],note:"the token-bank top-up: amount bounds, the balance reading, and the credit watch every host drives"},{src:"client/google-signin.js",shapes:["mirror","flat"],note:"the localhost half of aegis1's desktop Google OAuth round-trip; `connect --google` drives it"},{src:"client/drive-connect.js",shapes:["mirror","flat"],note:"the desktop half of aegis1's Drive OAuth (/connect/drive, /api/drive/token); requires ./aegis.js only via the caller"},{src:"client/drive-upload.js",shapes:["mirror","flat"],note:"the Drive v3 REST wrapper that uploads the memory backup and one conversation per save"},{src:"client/conversation-export.js",shapes:["mirror","flat"],note:"the authorship stamp at the top of every uploaded file, and the two backup scope names"},{src:"mcp/tools.js",shapes:["mirror"],note:"the shared tool registry; requires ../client/foreign-memory.js"},{src:"mcp/server.js",shapes:["mirror"],note:"the stdio MCP server every installed editor config names (compiled, never required)"},{src:"mcp/admission.js",shapes:["mirror"],note:"the admission gate server.js requires at load (`./admission.js`): which harness may call the bridge, and what it may run — omitted from the manifest when 2066f82 added it, so both staged trees shipped a server that could not load"},{src:"hosts/spec.js",shapes:["mirror"],note:"the canonical server spec, staged under its own directory so it finds vendor/mcp/server.js"},{src:"hosts/targets.js",shapes:["mirror"],note:"the editor target registry"},{src:"hosts/install.js",shapes:["mirror"],note:"the merge-only installer behind aegiscode mcp install"},{src:"hosts/openai-shim.js",shapes:["mirror"],note:"the loopback OpenAI-compatible shim"},{src:"desktop/renderer/usage.js",shapes:["mirror"],note:"the pure usage mapping shared by the window and the terminal"},{src:"desktop/lib/local/engine.js",shapes:["mirror"],note:"the agent loop, reused as-is (one loop, not a second one drifting)"},{src:"desktop/lib/local/claude-pro.js",shapes:["mirror"],note:"the Claude Code Pro transport; requires ./../../one/src/child.js at call time"},{src:"one/src/child.js",shapes:["mirror"],note:"the ONE claude-child argv builder (rule 4); resolved by claude-pro.js at call time"},{src:"one/src/permissions.js",shapes:["mirror"],note:"resolvePosture() — the permission half of the argv, resolved at call time"},{src:"desktop/lib/local/local.js",shapes:["mirror"],note:"the local model transport and its fail-closed base-URL check"},{src:"desktop/lib/local/context.js",shapes:["mirror"],note:"the token-budget trimmer local.js requires at load"},{src:"desktop/lib/local/attachments.js",shapes:["mirror"],note:"content-part builder for dropped files; required at load by engine.js and local.js"},{src:"desktop/lib/local/session-rounds.js",shapes:["mirror"],note:"interrupted-turn bookkeeping; required at load by engine.js"},{src:"desktop/lib/local/pro-sessions.js",shapes:["mirror"],note:"durable Claude-Pro conversation session ids; required at load by engine.js"},{src:"desktop/lib/local/tools.js",shapes:["mirror"],note:"the tool implementations (persistent shell, editFile, grep, exec)"},{src:"desktop/lib/local/shell.js",shapes:["mirror"],note:"the persistent shell, required by tools.js"},{src:"desktop/lib/local/sandbox.js",shapes:["mirror"],note:"the outcome bound (agent-safety-plan §1b), required by shell.js + tools.js"},{src:"desktop/lib/local/sandbox-bwrap.js",shapes:["mirror"],note:"bubblewrap mechanism behind sandbox.js (agent-safety-plan §1d)"},{src:"desktop/lib/local/sandbox-seatbelt.js",shapes:["mirror"],note:"Seatbelt mechanism behind sandbox.js (agent-safety-plan §1d)"},{src:"desktop/lib/local/sandbox-appcontainer.js",shapes:["mirror"],note:"AppContainer mechanism behind sandbox.js (agent-safety-plan §1e)"},{src:"desktop/lib/local/perm-rules.js",shapes:["mirror"],note:"stored /permissions rules for the desktop gate (agent-safety-plan §2), required by engine.js"},{src:"desktop/lib/local/perm-write.js",shapes:["mirror"],note:'the durable "always allow this command" answer (agent-safety-plan §3), required by main.js'},{src:"desktop/lib/local/perm-store.js",shapes:["mirror"],note:"the Settings rules editor (agent-safety-plan §4), required by main.js"},{src:"desktop/lib/local/integrity.js",shapes:["mirror"],note:"the desktop second gate; required at load by shell.js and tools.js, and the seal over its own four units"},{src:"desktop/main.js",shapes:["mirror"],bytesOnly:!0,note:"seal unit d1 — hashed by integrity.js as BYTES and never required from the mirror, so its own requires (the whole Electron main-process closure) are not staged behind it"},{src:"desktop/lib/local/spill.js",shapes:["mirror"],note:"oversized-output spill, required at load by tools.js and shell.js"},{src:"desktop/lib/local/exec-plan.js",shapes:["mirror"],note:"exec one-shot eligibility classifier, required at load by engine.js"},{src:"desktop/lib/local/agents.js",shapes:["mirror"],note:"Task subagents"},{src:"desktop/lib/local/prompt.js",shapes:["mirror"],note:"the system prompt builder"},{src:"desktop/lib/local/tool-brief.js",shapes:["mirror"],note:'the local lane\'s per-tool "when to use it" brief, derived from the schemas; required at load by prompt.js'},{src:"desktop/lib/settings.js",shapes:["mirror"],note:"the provider-config store (base URL + key per provider)"},{src:"desktop/lib/local/turn-guard.js",shapes:["mirror"],note:"engine.js requires it at load; it requires ./git-scope.js"},{src:"desktop/lib/local/repeat-guard.js",shapes:["mirror"],note:"engine.js requires it at load — identical-call detection, no deps of its own"},{src:"desktop/lib/local/verify-stop.js",shapes:["mirror"],note:"engine.js requires it at load — edited-but-unchecked nudge, no deps of its own"},{src:"desktop/lib/local/check-command.js",shapes:["mirror"],note:"verify-stop.js requires it lazily — which command would check this repo; no deps"},{src:"desktop/lib/local/worktree-lock.js",shapes:["mirror"],note:"engine.js requires it at load"},{src:"desktop/lib/local/git-scope.js",shapes:["mirror"],note:"the write-scope rule turn-guard.js and the queues share"},{src:"desktop/lib/local/queue.js",shapes:["mirror"],note:"the autonomous work queue"},{src:"desktop/lib/local/autonomous.js",shapes:["mirror"],note:"the unattended worker; requires ./queue.js and ./git-scope.js"},{src:"desktop/lib/local/entitlement.js",shapes:["mirror"],note:"the shared Pro gate (account probe injected by the caller)"},{src:"desktop/lib/local/covenant.js",shapes:["mirror"],note:"the pre-action gate engine.js requires unconditionally at load"},{src:"desktop/lib/local/aegis-seal.mjs",shapes:["mirror"],note:"the codec covenant.js requires the first time it decodes"},{src:"covenant/aegis.seal",shapes:["mirror","nested"],note:"the sealed covenant (AES/1 container) — path shape is load-bearing"},{src:"covenant/README.md",shapes:["mirror","nested"],note:"the decode notice shipped beside the artifact"},{src:"tools/agent-gate.mjs",shapes:["mirror","flat"],note:"the in-process half of the lock; without it a packaged app had NO gate"},{src:"one/src/selfhost.js",shapes:["mirror","flat"],note:"the packaged launcher decision — which face this artifact was asked for"},{src:"one/src/protocol.js",shapes:["mirror","flat"],note:"the core/frontend seam; desktop/lib/local/pty-host.js speaks it over Electron IPC"},{src:"one/src/iface/pty.js",shapes:["mirror","flat"],note:"plans pty|refuse and spawns the native pty; required by desktop/lib/local/pty-host.js at call time"}];export function entriesFor(e){const r=[];for(const t of MANIFEST){if(!t.shapes.includes(e))continue;let o;if("mirror"===e)o=s.join(CLI_VENDOR,t.src);else if("flat"===e)o=s.join(DESKTOP_VENDOR,s.basename(t.src));else{if("nested"!==e)throw new Error(`predist: unknown shape ${e}`);o=s.join(DESKTOP_VENDOR,t.src)}r.push({src:t.src,dest:o,from:s.join(REPO_DIR,t.src)})}return r}export const SHAPES=["mirror","flat","nested"];const c=[["cli",CLI_DIR,["bin","src","vendor","scripts","package.json","README.md","LICENSE"]],["desktop",DESKTOP_DIR,["main.js","preload.js","lib","renderer","bin","vendor","package.json","README.md"]]],l=new Set(["node_modules","release",".git",".cache","out"]),d=new Map([["desktop/vendor",new Set(["faces","sandbox"])]]);function h(r,t,o){const n=o||new Set,i=(e,s)=>l.has(e)||e.endsWith(".log")||n.has(s),a=(r,t)=>{if(e.mkdirSync(s.dirname(t),{recursive:!0}),e.copyFileSync(r,t),!e.readFileSync(r).equals(e.readFileSync(t)))throw new Error(`predist: bundle copy differs from source: ${s.relative(REPO_DIR,r)}`)},c=(r,o)=>{const n=e.lstatSync(r);if(!n.isSymbolicLink())if(n.isFile())a(r,s.join(t,o));else for(const t of e.readdirSync(r)){const e=o?s.join(o,t):t;i(t,e)||c(s.join(r,t),e)}};e.lstatSync(r).isFile()?a(r,t):c(r,"")}const p="AEGISONE_PREDIST_LOCK_TOKEN";let u=null,m=!1,f=0;function g(e){try{return process.kill(e,0),!0}catch(e){return Boolean(e)&&"EPERM"===e.code}}const j=e=>new Promise(s=>setTimeout(s,e));function y(){if(f>0)return void f--;const s=u,r=m,t=process.env[p];if(u=null,m=!1,s&&r){t&&delete process.env[p];try{e.unlinkSync(s)}catch{}}}export async function acquireStageLock(r){if(u)return f++,y;const t=r&&r.stdout||process.stdout;return await async function(r){const t=function(){const r=s.join(REPO_DIR,".git");let t=r;try{if(!e.lstatSync(r).isDirectory()){const o=/^gitdir:\s*(.+)$/m.exec(e.readFileSync(r,"utf8"));o&&(t=s.resolve(REPO_DIR,o[1].trim()))}}catch{t=r}return s.join(t,"aegisone-predist.lock")}(),o=Date.now()+12e4,n=process.env[p]||null;let i=null,a=!1;for(;;){if(n)try{const s=String(e.readFileSync(t,"utf8")).split("\n")[1];if(s&&s.trim()===n)return u=t,void(m=!1)}catch{}try{i=`${Date.now().toString(36)}-${process.pid}-${Math.random().toString(36).slice(2,10)}`;const s=e.openSync(t,"wx");return e.writeSync(s,`${process.pid}\n${i}\n`),e.closeSync(s),u=t,m=!0,void(process.env[p]=i)}catch(e){if(!e||"EEXIST"!==e.code)throw e}let s=null,c=0;try{s=e.statSync(t),c=Number(String(e.readFileSync(t,"utf8")).split("\n")[0].trim())}catch{continue}if(Date.now()-s.mtimeMs>6e5||Number.isFinite(c)&&c>0&&!g(c)){r(`predist: breaking an abandoned staging lock (pid ${c||"unknown"})`);try{e.unlinkSync(t)}catch{}}else{if(Date.now()>o)throw new Error(`predist: another stager (pid ${c||"unknown"}) has held ${t} for over ${Math.round(120)}s. Staging is destructive — it removes and rewrites cli/vendor, desktop/vendor and one/vendor — so it will not run concurrently with a peer. Wait for it, or delete the lock if that process is gone.`);a||(a=!0,r(`predist: another stager (pid ${c||"unknown"}) is running — waiting for it (concurrent staging would read a vendor tree the peer is rewriting)`)),await j(50+Math.floor(50*Math.random()))}}}(e=>t.write(`${e}\n`)),y}function b(r,t){const o=[];for(const s of r){if(!e.existsSync(s.from))throw new Error(`predist: missing shared module: ${s.src} (expected at ${s.from})`);if(w(s.from,s.dest),!e.readFileSync(s.from).equals(e.readFileSync(s.dest)))throw new Error(`predist: staged copy differs from source: ${s.src}`);o.push(s)}return t&&function(r,t){if(!e.existsSync(r))return 0;const o=r=>{for(const n of e.readdirSync(r,{withFileTypes:!0})){const i=s.join(r,n.name);if(n.isDirectory()){o(i);try{e.rmdirSync(i)}catch{}}else t.has(i)||e.unlinkSync(i)}};o(r)}(t,new Set(o.map(e=>e.dest))),o}function w(r,t){e.mkdirSync(s.dirname(t),{recursive:!0});const o=`${t}.tmp-${process.pid}-${Math.random().toString(36).slice(2,10)}`;e.copyFileSync(r,o);try{e.renameSync(o,t)}catch(s){try{e.unlinkSync(o)}catch{}throw s}}function v(e){return e.replace(/\/\*[\s\S]*?\*\//g,"").replace(/(^|[^:])\/\/.*$/gm,"$1")}export async function stage(t){const n=t||{},i=n.io||{},l=i.stdout||process.stdout,p=(i.stderr||process.stderr,Array.isArray(n.shapes)?n.shapes:[...SHAPES,"bundle"]),u=e=>p.includes(e),m=e=>l.write(`${e}\n`),f=await acquireStageLock(i);try{return await async function({want:t,log:n}){const i={mirror:null,flat:null,nested:null,bundle:null};if(t("mirror")){const e=b(entriesFor("mirror"),CLI_VENDOR);n(`predist: staged ${e.length} shared modules into cli/vendor/`);for(const s of e)n(` ${s.src} -> vendor/${s.src}`);i.mirror={staged:e.length}}if(t("nested")&&(i.nested={staged:b(entriesFor("nested"),null).length}),t("flat")){const e=b(entriesFor("flat"),null);for(const s of e)n(`staged ${s.dest}`);i.flat={staged:e.length}}if(t("mirror")&&t("flat"))for(const r of MANIFEST){if(!r.shapes.includes("mirror")||!r.shapes.includes("flat"))continue;const t=s.join(CLI_VENDOR,r.src),o=s.join(DESKTOP_VENDOR,s.basename(r.src));if(!e.readFileSync(t).equals(e.readFileSync(o)))throw new Error(`predist: the two shapes disagree for ${r.src}`)}if(t("mirror")){const r=function(r){const t=s.join(CLI_VENDOR,"mcp","tools.js");delete a.cache[a.resolve(t)];const{createTools:o}=a(t),n=o({apiBase:"http://127.0.0.1",apiKey:"predist-probe",randomUUID:()=>"id"}).toolList().length;if(0===n)throw new Error("predist: staged registry exposes no tools");const i=a("node:vm"),c=s.join(CLI_VENDOR,"mcp","server.js");new i.Script(e.readFileSync(c,"utf8"),{filename:c});const l=s.join(CLI_VENDOR,"hosts"),d=a(s.join(l,"spec.js")),h=a(s.join(l,"install.js")),p=a(s.join(l,"targets.js")),u=d.resolveServer({AEGIS_MCP_SERVER:""});if(!u.exists||u.path!==c)throw new Error(`predist: staged hosts/spec.js resolves the server as ${u.path} (exists: ${u.exists}), expected ${c}. An installed aegiscode would write editor configs pointing at a file the package never shipped. Candidates were:\n ${u.candidates.join("\n ")}`);const m=p.getTarget("vscode"),f=h.planTarget(m,"user",{ctx:h.hostCtx({home:s.join(CLI_VENDOR,".predist-home"),env:{},cwd:REPO_DIR}),specOpts:{env:{AEGIS_MCP_SERVER:""}}}),g=[];!function e(s){"string"==typeof s?g.push(s):Array.isArray(s)?s.forEach(e):s&&"object"==typeof s&&Object.values(s).forEach(e)}(f.after?JSON.parse(f.after):{});const j=g.some(e=>e===c);if(f.error||!f.changed||!j)throw new Error(`predist: a planned vscode install does not name the staged server (error: ${f.error&&f.error.message}, changed: ${f.changed})`);if("function"!=typeof a(s.join(l,"openai-shim.js")).createShimServer)throw new Error("predist: staged hosts/openai-shim.js exposes no createShimServer");return{count:n,targets:p.targetIds().length,staged:r.length}}(entriesFor("mirror"));n(`predist: staged registry loads standalone (${r.count} tools)`),n(`predist: editor layer verified (${r.targets} host targets, server resolves to vendor/mcp/server.js, shim loads)`);const t=await async function(){const e=s.join(CLI_VENDOR,"tools","agent-gate.mjs");if("function"!=typeof(await(import(o(e).href))).run)throw new Error("predist: staged tools/agent-gate.mjs exposes no run()");return e}();n(`predist: ${s.relative(REPO_DIR,t)} loads standalone and exposes run()`),i.mirror.proof=r}if(t("flat")){const r=function(r){const t=new Set(r.map(e=>s.basename(e.dest)));for(const o of r){const r=v(e.readFileSync(o.dest,"utf8"));for(const e of r.matchAll(/require\(\s*'((?:\.\.?\/)[^']+)'\s*\)/g)){const r=e[1];if(s.basename(r).replace(/\.[cm]?js$/,""),r.replace(/^\.\//,"").startsWith("../"))throw new Error(`predist: flat-staged ${s.basename(o.dest)} requires '${r}', which escapes vendor/ — flattening only works for same-directory requires (add the target to the manifest, or stop staging this file flat)`);const n=r.replace(/^\.\//,"");if(!t.has(n))throw new Error(`predist: flat-staged ${s.basename(o.dest)} requires '${r}', which is not staged into desktop/vendor/ — the packaged app would throw MODULE_NOT_FOUND before the window could open`)}}const o=a(s.join(DESKTOP_VENDOR,"aegis.js"));if(!o||0===Object.keys(o).length)throw new Error("predist: staged desktop/vendor/aegis.js loads but exports nothing");return{files:r.length,exports:Object.keys(o).length}}(entriesFor("flat"));n(`predist: flattened tree is self-contained (${r.files} files, ${r.exports} transport exports) — no staged module escapes vendor/`),i.flat.proof=r}if(t("bundle")){for(const[r,t,o]of c){const i=s.join(ONE_VENDOR,r);e.rmSync(i,{recursive:!0,force:!0});for(const n of o){const o=s.join(t,n);if(!e.existsSync(o)){if("LICENSE"===n||"README.md"===n)continue;throw new Error(`predist: bundle source missing: ${s.relative(REPO_DIR,o)}`)}h(o,s.join(i,n),d.get(`${r}/${n}`))}n(`staged the ${r} face into one/vendor/${r}/`)}const t=function(){const t=s.join(ONE_VENDOR,"cli"),o=s.join(t,"src","deps.js"),n=r(process.execPath,["-e","const d=require(process.argv[1]);console.log(JSON.stringify(d.paths))",o],{cwd:t,encoding:"utf8"});if(0!==n.status)throw new Error(`predist: the bundled CLI does not load: ${n.stderr||n.stdout}`);const i=JSON.parse(n.stdout),a=[];let l=0;for(const[e,r]of Object.entries(i)){const t=s.relative(ONE_VENDOR,r);t.startsWith("..")||s.isAbsolute(t)?a.push(`${e} -> ${r}`):"cli"!==t.split(s.sep)[0]&&l++}if(a.length)throw new Error(`predist: the bundled CLI resolves these shared modules OUTSIDE the bundle (${ONE_VENDOR}) — the product tarball would depend on a repo checkout:\n `+a.join("\n "));if(!e.existsSync(s.join(t,"bin","aegiscode.js")))throw new Error("predist: the bundle has no cli/bin/aegiscode.js");const d=[];for(const[r,t,o]of c)for(const n of o){const o=s.join(ONE_VENDOR,r,n);let i=null,a=null;try{i=e.lstatSync(s.join(t,n))}catch{continue}try{a=e.lstatSync(o)}catch{d.push(`${r}/${n} -> missing`);continue}i.isFile()&&!a.isFile()&&d.push(`${r}/${n} -> not a regular file`),i.isDirectory()&&!a.isDirectory()&&d.push(`${r}/${n} -> not a directory`)}if(d.length)throw new Error(`predist: the bundle staged these in the wrong shape:\n ${d.join("\n ")}`);return{modules:Object.keys(i).length,inSiblingFace:l}}();n(`predist: the bundled CLI resolves ${t.modules} shared modules from inside one/vendor/ (${t.inSiblingFace} through the bundled desktop face) — no repo checkout needed`),i.bundle=t;const o=s.join(DESKTOP_VENDOR,"faces");e.rmSync(o,{recursive:!0,force:!0}),h(s.join(ONE_VENDOR,"cli"),s.join(o,"cli"));const a=s.join(o,"cli","bin","aegiscode.js");if(!e.existsSync(a))throw new Error(`predist: the packaged terminal face has no entry point at ${s.relative(REPO_DIR,a)} — the artifact would open a window for every \`aegiscode\`/\`--tui\` invocation`);n(`staged the terminal face into desktop/vendor/faces/cli/ (${s.basename(a)})`),i.faces={entry:s.relative(REPO_DIR,a)}}return i}({want:u,log:m})}finally{f()}}export async function main(e,s){const r=s||{},t=Array.isArray(e)?e:[],o=t.includes("--quiet")?{write:()=>!0}:r.stdout||process.stdout,n=r.stderr||process.stderr;let i;t.includes("--mirror-only")?i=["mirror"]:t.includes("--flat-only")?i=["flat","nested"]:t.includes("--bundle-only")&&(i=["bundle"]);try{return await stage({shapes:i,io:{stdout:o,stderr:n}}),0}catch(e){return n.write(`${e&&e.message}\n`),1}}!function(){const e=process.argv[1];let r=!1;if(e)try{r=s.resolve(e)===t(import.meta.url)}catch{r=!1}r&&main(process.argv.slice(2)).then(e=>{process.exitCode=e})}();
package/src/dispatch.js CHANGED
@@ -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 FACE=Object.freeze({TUI:"tui",GUI:"gui"}),FACE_ENV="AEGISONE_FACE",TUI_VERBS=new Set(["login","connect","logout","key","mcp","fingerprint","gate","autonomous","permissions","doctor","update","models","config","init","signup","help","version","status","resume"]),SCRIPT_FLAGS=new Set(["-p","--print","--json"]),FORCE_GUI_FLAGS=["--gui"],FORCE_TUI_FLAGS=["--tui"],SPELLING_GUI="desktop",SPELLING_TUI="code";function flagIndex(e,t){for(let n=0;n<e.length;n++)if(t.includes(e[n]))return n;return-1}function without(e,t){return e.filter(e=>!t.includes(e))}function has(e,t){return e.some(e=>t.includes(e))}function guiBlockers(e,t){const n=[];return e||n.push("no display (DISPLAY / WAYLAND_DISPLAY are unset)"),t||n.push("Electron is not installed beside this package"),n}function decide(e){const t=e||{},n=Array.isArray(t.argv)?t.argv.map(String):[],i=t.env||{},s=t.tty||{},o=Boolean(t.hasDisplay),r=Boolean(t.electronResolvable),a=String(t.invokedAs||"aegis").replace(/\.js$/,""),l=guiBlockers(o,r),c=0===l.length,u=(e,t,n)=>({face:FACE.GUI,kind:e,reason:t,args:n,notice:null}),d=(e,t,n,i)=>({face:FACE.TUI,kind:e,reason:t,args:n,notice:i||null}),g=e=>({face:null,kind:"error",code:2,reason:`${e} cannot open the window`,error:`${e}: cannot open the window — ${l.join(", ")}.`,hint:"Use --tui for the terminal face.",args:[],notice:null});if("aegiscode"===a)return d("compat","aegiscode is the compatibility bin",n);const E=String(null==i[FACE_ENV]?"":i[FACE_ENV]).trim().toLowerCase();if(E)return E===FACE.GUI?c?u("forced",`${FACE_ENV}=gui`,n):g(`${FACE_ENV}=gui`):"cli"===E||E===FACE.TUI?d("forced",`${FACE_ENV}=${E}`,n):{face:null,kind:"error",code:2,reason:`${FACE_ENV}=${E} is not a face`,error:`${FACE_ENV}=${E} is not a face. Set cli or gui.`,hint:"Unset it to let aegis decide from the arguments.",args:[],notice:null};if(has(n,FORCE_GUI_FLAGS)){const e=without(n,FORCE_GUI_FLAGS);return c?u("explicit","--gui was passed",e):g("--gui")}if(has(n,FORCE_TUI_FLAGS))return d("explicit","--tui was passed",without(n,FORCE_TUI_FLAGS));const f=n.filter(e=>!e.startsWith("-")),p=f.length?f[0]:null;if("desktop"===p){const e=n.filter(e=>"desktop"!==e);return c?u("spelling","aegis desktop",e):g("aegis desktop")}if("code"===p)return d("spelling","aegis code",n.filter(e=>"code"!==e));const A=n.find(e=>SCRIPT_FLAGS.has(e));return A?d("script",`${A} means this call is a script`,n):p?d("argument",TUI_VERBS.has(p)?`'${p}' is a terminal verb`:`'${p}' is a prompt, not a window request`,n):n.length?d("flags","options were passed; the window takes none",n):!1===s.stdin||!1===s.stdout?d("default","stdio is not a terminal",[],"stdio is not a terminal"):l.length?d("default",l[0],[],l[0]):u("default","nothing else was asked for",[])}module.exports={decide:decide,FACE:FACE,FACE_ENV:FACE_ENV,TUI_VERBS:TUI_VERBS};
3
+ "use strict";const FACE=Object.freeze({TUI:"tui",GUI:"gui"}),FACE_ENV="AEGISONE_FACE",TUI_VERBS=new Set(["login","connect","logout","key","mcp","fingerprint","gate","autonomous","permissions","doctor","update","models","config","init","signup","help","version","status","resume"]),SCRIPT_FLAGS=new Set(["-p","--print","--json"]),FORCE_GUI_FLAGS=["--gui"],FORCE_TUI_FLAGS=["--tui"],SPELLING_GUI="desktop",SPELLING_TUI="code";function flagIndex(e,t){for(let n=0;n<e.length;n++)if(t.includes(e[n]))return n;return-1}function without(e,t){return e.filter(e=>!t.includes(e))}function has(e,t){return e.some(e=>t.includes(e))}function guiBlockers(e,t){const n=[];return e||n.push("no display (DISPLAY / WAYLAND_DISPLAY are unset)"),t||n.push("Electron is not installed beside this package"),n}function decide(e){const t=e||{},n=Array.isArray(t.argv)?t.argv.map(String):[],i=t.env||{},o=t.tty||{},s=Boolean(t.hasDisplay),r=Boolean(t.electronResolvable),a=String(t.invokedAs||"aegis").replace(/\.js$/,""),l=String(t.platform||""),c="darwin"===l||"win32"===l,u=Boolean(t.ci),d=guiBlockers(s,r),g=0===d.length,E=(e,t,n)=>({face:FACE.GUI,kind:e,reason:t,args:n,notice:null}),p=(e,t,n,i)=>({face:FACE.TUI,kind:e,reason:t,args:n,notice:i||null}),f=e=>({face:null,kind:"error",code:2,reason:`${e} cannot open the window`,error:`${e}: cannot open the window — ${d.join(", ")}.`,hint:"Use --tui for the terminal face.",args:[],notice:null});if("aegiscode"===a)return p("compat","aegiscode is the compatibility bin",n);const A=String(null==i[FACE_ENV]?"":i[FACE_ENV]).trim().toLowerCase();if(A)return A===FACE.GUI?g?E("forced",`${FACE_ENV}=gui`,n):f(`${FACE_ENV}=gui`):"cli"===A||A===FACE.TUI?p("forced",`${FACE_ENV}=${A}`,n):{face:null,kind:"error",code:2,reason:`${FACE_ENV}=${A} is not a face`,error:`${FACE_ENV}=${A} is not a face. Set cli or gui.`,hint:"Unset it to let aegis decide from the arguments.",args:[],notice:null};if(has(n,FORCE_GUI_FLAGS)){const e=without(n,FORCE_GUI_FLAGS);return g?E("explicit","--gui was passed",e):f("--gui")}if(has(n,FORCE_TUI_FLAGS))return p("explicit","--tui was passed",without(n,FORCE_TUI_FLAGS));const h=n.filter(e=>!e.startsWith("-")),F=h.length?h[0]:null;if("desktop"===F){const e=n.filter(e=>"desktop"!==e);return g?E("spelling","aegis desktop",e):f("aegis desktop")}if("code"===F)return p("spelling","aegis code",n.filter(e=>"code"!==e));const _=n.find(e=>SCRIPT_FLAGS.has(e));return _?p("script",`${_} means this call is a script`,n):F?p("argument",TUI_VERBS.has(F)?`'${F}' is a terminal verb`:`'${F}' is a prompt, not a window request`,n):n.length?p("flags","options were passed; the window takes none",n):!1===o.stdin||!1===o.stdout?c&&!u&&g?E("launcher","a desktop launch on a platform that always has a display",[]):p("default","stdio is not a terminal",[],"stdio is not a terminal"):d.length?p("default",d[0],[],d[0]):E("default","nothing else was asked for",[])}module.exports={decide:decide,FACE:FACE,FACE_ENV:FACE_ENV,TUI_VERBS:TUI_VERBS};
package/src/doctor.js CHANGED
@@ -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 path=require("node:path"),fs=require("node:fs"),crypto=require("node:crypto"),EXIT=Object.freeze({OK:0,WARN:1,BROKEN:2}),FACE_PACKAGES=Object.freeze([Object.freeze({dir:"cli",package:"aegiscode"}),Object.freeze({dir:"desktop",package:"aegis-desktop"})]),BUNDLE_FACES=Object.freeze([Object.freeze({face:"cli",root:"cli",staged:"one/vendor/cli"}),Object.freeze({face:"desktop",root:"desktop",staged:"one/vendor/desktop"})]);function oneDir(){return path.resolve(__dirname,"..")}function repoDir(){return path.resolve(__dirname,"..","..")}function layoutOf(e,t){const n=t=>{try{return Boolean(e.exists(t))}catch{return!1}};if(t){const e=!n(path.join(t,"one","package.json"));return{root:t,installed:e,facePrefix:e?["vendor"]:[]}}const r=repoDir(),o=!n(path.join(r,"one","package.json"));return{root:o?oneDir():r,installed:o,facePrefix:o?["vendor"]:[]}}function inLayout(e,t){if(!e.installed)return t;const n=t.split("/");if("one"===n[0]){const e=n.slice(1).join("/");return"src/selfhost.js"===e?"vendor/desktop/vendor/selfhost.js":("vendor/cli"===e||e.startsWith("vendor/"),e)}return"cli"===n[0]||"desktop"===n[0]?path.posix.join("vendor",t).split(path.sep).join("/"):path.posix.join("vendor","cli","vendor",t).split(path.sep).join("/")}function homeHint(e){const t=e||{};return t.AEGISCODE_HOME||t.AEGIS_HOME||null}function homeDir(e){try{return require("./host.js").hostHome(e||{})}catch{const t=e||{},n=t.USERPROFILE||t.HOME;return n?String(n).trim():""}}function defaultFs(){return{exists:e=>{try{return fs.existsSync(e)}catch{return!1}},readFile:e=>{try{return fs.readFileSync(e,"utf8")}catch(e){if(e&&("ENOENT"===e.code||"EISDIR"===e.code))return null;throw e}},hashFile:e=>crypto.createHash("sha256").update(fs.readFileSync(e)).digest("hex"),listFiles:(e,t)=>listFiles(e,void 0===t?e:t)}}function listFiles(e,t){const n=[],r=e=>{let o;try{o=fs.readdirSync(e,{withFileTypes:!0})}catch{return}for(const s of o){if("node_modules"===s.name||".git"===s.name)continue;const o=path.join(e,s.name);s.isDirectory()?r(o):n.push(path.relative(t,o).split(path.sep).join("/"))}};return r(e),n.sort()}function defaultElectronPaths(e,t){const n=t||{},r=homeHint(e)||path.join(homeDir(e),".aegiscode");return{electron:void 0!==n.electron?n.electron:null,desktopMain:void 0!==n.desktopMain?n.desktopMain:null,userData:void 0!==n.userData?n.userData:r,keychain:void 0!==n.keychain?n.keychain:path.join(r,"settings.json")}}function defaultRegistry(e){let t=null;const n=()=>{if(t)return t;const n=e&&e.layout?e.layout:{root:repoDir(),installed:!1},r=[path.join(n.root,"client","update.js"),path.join(n.root,"vendor","cli","vendor","client","update.js")];for(const e of r)try{t=require(e);break}catch{}return t};return{check(e){const t=n();return t&&"function"==typeof t.updateNotice?t.updateNotice(e||{}):{latest:null,behind:!1,reason:"unavailable"}},plan(e){const t=n();return t&&"function"==typeof t.updatePlan?t.updatePlan(e||{}):null}}}function clientModuleCandidates(e){return[path.join(e.root,"client"),path.join(e.root,"vendor","cli","vendor","client")]}function loadClientModule(e,t){const n=e&&e.layout?e.layout:{root:repoDir(),installed:!1};for(const e of clientModuleCandidates(n))try{return require(path.join(e,t))}catch{}return null}function defaultStorePath(e,t){try{const n=loadClientModule(t,"prefs.js");if(n&&"function"==typeof n.prefsFile)return n.prefsFile(e)}catch{}const n=homeHint(e)||path.join(homeDir(e),".aegiscode");return path.join(n,"preferences.json")}function defaultCredentials(e){let t=null,n=!1;return{resolve(r){if(n||(n=!0,t=loadClientModule(e,"credentials.js")),!t||"function"!=typeof t.resolveApiKey)return{key:"",source:"none",from:""};try{return t.resolveApiKey(r||{})}catch{return{key:"",source:"none",from:""}}}}}function vendorPairs(e){const{exists:t}=e,n=[];if((e.layout||{installed:!1,facePrefix:[]}).installed)return n;for(const{face:r,root:o,staged:s}of BUNDLE_FACES){const a=path.join(e.root,s),i=e.listFiles(a,a);for(const a of i){const i=[];if(a.startsWith("vendor/")){const e=a.slice(7);if(i.push(e),i.push(path.join(o,e)),"selfhost.js"===e&&i.push(path.join("one","src","selfhost.js")),"protocol.js"===e&&i.push(path.join("one","src","protocol.js")),"pty.js"===e&&i.push(path.join("one","src","iface","pty.js")),"desktop"===r){const t=path.basename(e);for(const e of["client","mcp","covenant","commands","skills","tools","hosts"])i.push(path.join(e,t));i.push(t)}}else i.push(path.join(o,a)),i.push(a);const l=i.find(n=>t(path.join(e.root,n)))||null;n.push({face:r,staged:path.join(s,a),source:l,candidates:i})}}return n}function layoutsInstalled(e){return Boolean(e&&e.installed)}function checkVendor(e,t){const n=t||vendorPairs(e),r=[],o=[];let s=0,a=0;const i=e.layout||{installed:!1,facePrefix:[]};if(layoutsInstalled(i)){for(const t of BUNDLE_FACES){const n=path.join(e.root,inLayout(i,t.staged));e.exists(n)&&(a+=e.listFiles(n,n).length)}return{staged:a,matched:0,mismatch:o,missingSource:r,stale:0===a,checked:0}}for(const t of n){if(!e.exists(path.join(e.root,t.staged)))continue;if(a+=1,!t.source){r.push(t.staged);continue}let n,i;try{n=e.hashFile(path.join(e.root,t.source)),i=e.hashFile(path.join(e.root,t.staged))}catch(e){o.push({staged:t.staged,source:t.source,error:String(e&&e.message||e)});continue}n===i?s+=1:o.push({staged:t.staged,source:t.source})}return{staged:a,matched:s,mismatch:o,missingSource:r,stale:n.length>0&&0===a,checked:n.length}}function readJson(e,t){const n=path.join(e.root,t);if(!e.exists(n))return{ok:!1,missing:!0,value:null,path:t};let r;try{r=e.readFile(n)}catch(e){return{ok:!1,unreadable:!0,value:null,path:t,error:String(e&&e.message||e)}}if(null==r)return{ok:!1,missing:!0,value:null,path:t};try{return{ok:!0,value:JSON.parse(r),path:t}}catch(e){return{ok:!1,unreadable:!0,value:null,path:t,error:String(e&&e.message||e)}}}function resolveSeams(e){const t=e||{},n=t.env||{},r=defaultFs(),o=t||{},s=o.exists||r.exists,a=t.layout||layoutOf({exists:s,root:t.root},t.root),i=t.root||a.root,l={root:i,layout:Object.assign({},a,{root:i}),platform:t.platform||"linux",env:n,exists:s,readFile:o.readFile||r.readFile,hashFile:o.hashFile||r.hashFile,listFiles:o.listFiles||r.listFiles,electronPaths:t.electronPaths||defaultElectronPaths(n,t),updateCache:t.updateCache,saveUpdateCache:t.saveUpdateCache,now:"number"==typeof t.now?t.now:0,guiRequested:Boolean(t.guiRequested),guiImplied:t.guiImplied,vendorPairs:t.vendorPairs};return l.credentials=t.credentials||defaultCredentials(l),l.storePath=t.storePath||defaultStorePath(n,l),l.registry=t.registry||defaultRegistry(l),l}function diagnose(e){const t=resolveSeams(e),n=[],r=(e,t)=>n.push({level:"broken",code:e,detail:t}),o=(e,t)=>n.push({level:"warn",code:e,detail:t}),s=t.layout,a=inLayout(s,"one/package.json"),i=readJson(t,a),l=i.ok?{name:i.value.name||"aegisone",version:String(i.value.version||"")}:{name:"aegisone",version:""};i.ok||r("product-unreadable",`${a} ${i.unreadable?"is unreadable":"is missing"}`);let c=null;try{c=require("./release.js").deriveFaceVersions(l.version)}catch(e){c=null,i.ok&&r("product-version-invalid",`${l.version}: ${String(e&&e.message||e)}`)}const u={};for(const{dir:e,package:n}of FACE_PACKAGES){const o=inLayout(s,`${e}/package.json`),a=readJson(t,o),i=a.ok?String(a.value.version||""):"",d=c&&c[n]?c[n].version:null;a.ok?d&&i!==d&&r("version-mismatch",`${n} is ${i}, product ${l.version} derives ${d}`):r("face-unreadable",`${o} ${a.unreadable?"is unreadable":"is missing"}`),u[n]={dir:e,version:i,expected:d,ok:Boolean(d&&i===d)}}let d={key:"",source:"none",from:""};try{d=t.credentials.resolve({env:t.env})||d}catch{d={key:"",source:"none",from:""}}const h=t.electronPaths||{};let p=d.key?"env"===d.source?"env":(d.source,"env-file"):"none";if(!d.key&&h.keychain&&t.exists(h.keychain)){const e=(()=>{try{return t.readFile(h.keychain)}catch{return null}})();e&&/encrypt|safeStorage/i.test(e)&&(p="keychain")}"none"===p&&o("no-credential","no credential found (env, credentials.json, or the OS keychain)");const f={path:t.storePath,exists:!1,readable:null,legacy:null};try{f.exists=t.exists(t.storePath)}catch{f.exists=!1}let g,v=f.path;if(f.exists){let e=null;try{e=t.readFile(f.path)}catch(e){f.readable=!1,r("store-unreadable",`${f.path}: ${String(e&&e.message||e)}`)}if(null===f.readable)if(null==e)f.readable=!1,r("store-unreadable",`${f.path} exists but could not be read`);else try{const t=JSON.parse(e);f.readable=!0,f.legacy=t&&t.version||null}catch(e){f.readable=!1,r("store-unreadable",`${f.path} is not valid JSON: ${String(e&&e.message||e)}`)}v=path.basename(f.path)}f.display=v;try{g=checkVendor(t,t.vendorPairs)}catch(e){g={staged:0,matched:0,mismatch:[],missingSource:[],stale:!1,checked:0,error:String(e&&e.message||e)},r("vendor-unreadable",g.error)}for(const e of g.mismatch)r("vendor-hash-mismatch",`${e.staged} differs from ${e.source||"its source"}`);for(const e of g.missingSource)r("vendor-source-missing",`${e} has no source to be re-derived from`);g.stale&&(s.installed?r("vendor-missing","the ONE bundle is empty — reinstall aegisone"):o("vendor-stale","the ONE bundle has never been staged (one/vendor is empty) — run `npm run predist`"));const m={channel:"npm",current:l.version,latest:null,behind:!1,reason:null,checkedAt:null,cached:!0,action:"none",applier:"npm",instruction:null};try{const e=t.registry.check({current:l.version,cache:t.updateCache,save:t.saveUpdateCache,now:t.now})||{};m.latest=e.latest||null,m.behind=Boolean(e.behind),m.reason=e.reason||null}catch(e){m.reason="unavailable",m.error=String(e&&e.message||e)}try{const e=t.registry.plan({current:l.version,latest:m.latest,behind:m.behind});e&&(m.action=e.action,m.applier=e.applier,m.instruction=e.instruction)}catch{}m.behind&&o("update-available",`${m.current} → ${m.latest} (${m.instruction||"run the channel updater"})`);const y=h&&h.electron||null;t.guiRequested&&!y&&r("gui-without-electron","--gui was requested but Electron is not installed — use --tui");const b=n.filter(e=>"broken"===e.level).length,j=n.filter(e=>"warn"===e.level).length,k=b?EXIT.BROKEN:j?EXIT.WARN:EXIT.OK;return{report:{aegis:"one",status:b?"broken":j?"warn":"healthy",exitCode:k,product:l,faces:u,credential:{source:p,found:Boolean(d.key),from:d.key?d.from:""},store:{path:f.path,exists:f.exists,readable:f.exists?!0===f.readable:null},vendor:{staged:g.staged,matched:g.matched,mismatched:g.mismatch.length,missingSource:g.missingSource.length,stale:g.stale,verifiable:!s.installed},update:m,gui:{requested:Boolean(t.guiRequested),electron:y||null,usable:Boolean(y)&&(!t.guiImplied||t.guiImplied)},problems:n},code:k}}function render(e){const t=[],n=(e,t)=>String(e)+" ".repeat(Math.max(0,t-String(e).length));t.push(`aegis doctor — ${e.status} (exit ${e.exitCode})`),t.push(` product ${e.product.name} ${e.product.version}`);for(const[r,o]of Object.entries(e.faces)){const e=o.ok?"":` (expected ${o.expected||"unknown"})`;t.push(` ${n(r,14)} ${o.version||"unknown"}${e}`)}t.push(` credential ${e.credential.source}`),t.push(` shared store ${e.store.path} ${e.store.exists?e.store.readable?"(readable)":"(unreadable)":"(absent)"}`),t.push(!1===e.vendor.verifiable?` vendor ${e.vendor.staged} staged (sources not shipped — not re-derivable here)`:` vendor ${e.vendor.staged} staged, ${e.vendor.matched} matching, ${e.vendor.mismatched} mismatched, ${e.vendor.missingSource} without a source`+(e.vendor.stale?" (never staged)":""));const r=e.update;if(t.push(" update "+(r.behind?`${r.current} → ${r.latest}`:`${r.current} is current`)+` (next: ${r.action}${r.instruction?` — ${r.instruction}`:""})`),t.push(" window face "+(e.gui.electron?`Electron at ${e.gui.electron}`:"not installed")),e.problems.length){t.push(" problems:");for(const n of e.problems)t.push(` ${"broken"===n.level?"✗":"!"} ${n.code}: ${n.detail}`)}return t.join("\n")+"\n"}function wantsGui(e,t){return!!(Array.isArray(e)?e:[]).includes("--gui")||"gui"===(t||{}).AEGISONE_FACE}function main(e,t){const n=t||{},r=Array.isArray(e)?e:[],o=n.stdout||process.stdout,s=n.env||process.env||{},a=Object.assign({},n,{env:s,guiRequested:wantsGui(r,s)}),{report:i,code:l}=diagnose(a),c=r.includes("--json")?JSON.stringify(i)+"\n":render(i);try{o.write(c)}catch{}return l}module.exports={EXIT:EXIT,FACE_PACKAGES:FACE_PACKAGES,wantsGui:wantsGui,diagnose:diagnose,render:render,main:main,vendorPairs:vendorPairs,resolveSeams:resolveSeams},require.main===module&&(process.exitCode=main(process.argv.slice(2)));
3
+ "use strict";const path=require("node:path"),fs=require("node:fs"),crypto=require("node:crypto"),EXIT=Object.freeze({OK:0,WARN:1,BROKEN:2}),FACE_PACKAGES=Object.freeze([Object.freeze({dir:"cli",package:"aegiscode"}),Object.freeze({dir:"desktop",package:"aegis-desktop"})]),BUNDLE_FACES=Object.freeze([Object.freeze({face:"cli",root:"cli",staged:"one/vendor/cli"}),Object.freeze({face:"desktop",root:"desktop",staged:"one/vendor/desktop"})]);function oneDir(){return path.resolve(__dirname,"..")}function repoDir(){return path.resolve(__dirname,"..","..")}function layoutOf(e,t){const n=t=>{try{return Boolean(e.exists(t))}catch{return!1}};if(t){const e=!n(path.join(t,"one","package.json"));return{root:t,installed:e,facePrefix:e?["vendor"]:[]}}const o=repoDir(),r=!n(path.join(o,"one","package.json"));return{root:r?oneDir():o,installed:r,facePrefix:r?["vendor"]:[]}}function inLayout(e,t){if(!e.installed)return t;const n=t.split("/");if("one"===n[0]){const e=n.slice(1).join("/");return"src/selfhost.js"===e?"vendor/desktop/vendor/selfhost.js":("vendor/cli"===e||e.startsWith("vendor/"),e)}return"cli"===n[0]||"desktop"===n[0]?path.posix.join("vendor",t).split(path.sep).join("/"):path.posix.join("vendor","cli","vendor",t).split(path.sep).join("/")}function homeHint(e){const t=e||{};return t.AEGISCODE_HOME||t.AEGIS_HOME||null}function homeDir(e){try{return require("./host.js").hostHome(e||{})}catch{const t=e||{},n=t.USERPROFILE||t.HOME;return n?String(n).trim():""}}function defaultFs(){return{exists:e=>{try{return fs.existsSync(e)}catch{return!1}},readFile:e=>{try{return fs.readFileSync(e,"utf8")}catch(e){if(e&&("ENOENT"===e.code||"EISDIR"===e.code))return null;throw e}},hashFile:e=>crypto.createHash("sha256").update(fs.readFileSync(e)).digest("hex"),listFiles:(e,t)=>listFiles(e,void 0===t?e:t)}}function listFiles(e,t){const n=[],o=e=>{let r;try{r=fs.readdirSync(e,{withFileTypes:!0})}catch{return}for(const s of r){if("node_modules"===s.name||".git"===s.name)continue;const r=path.join(e,s.name);s.isDirectory()?o(r):n.push(path.relative(t,r).split(path.sep).join("/"))}};return o(e),n.sort()}function defaultElectronPaths(e,t){const n=t||{},o=homeHint(e)||path.join(homeDir(e),".aegiscode");return{electron:void 0!==n.electron?n.electron:null,appBundle:void 0!==n.appBundle?n.appBundle:null,desktopMain:void 0!==n.desktopMain?n.desktopMain:null,userData:void 0!==n.userData?n.userData:o,keychain:void 0!==n.keychain?n.keychain:path.join(o,"settings.json")}}function defaultRegistry(e){let t=null;const n=()=>{if(t)return t;const n=e&&e.layout?e.layout:{root:repoDir(),installed:!1},o=[path.join(n.root,"client","update.js"),path.join(n.root,"vendor","cli","vendor","client","update.js")];for(const e of o)try{t=require(e);break}catch{}return t};return{check(e){const t=n();return t&&"function"==typeof t.updateNotice?t.updateNotice(e||{}):{latest:null,behind:!1,reason:"unavailable"}},plan(e){const t=n();return t&&"function"==typeof t.updatePlan?t.updatePlan(e||{}):null}}}function clientModuleCandidates(e){return[path.join(e.root,"client"),path.join(e.root,"vendor","cli","vendor","client")]}function loadClientModule(e,t){const n=e&&e.layout?e.layout:{root:repoDir(),installed:!1};for(const e of clientModuleCandidates(n))try{return require(path.join(e,t))}catch{}return null}function defaultStorePath(e,t){try{const n=loadClientModule(t,"prefs.js");if(n&&"function"==typeof n.prefsFile)return n.prefsFile(e)}catch{}const n=homeHint(e)||path.join(homeDir(e),".aegiscode");return path.join(n,"preferences.json")}function defaultCredentials(e){let t=null,n=!1;return{resolve(o){if(n||(n=!0,t=loadClientModule(e,"credentials.js")),!t||"function"!=typeof t.resolveApiKey)return{key:"",source:"none",from:""};try{return t.resolveApiKey(o||{})}catch{return{key:"",source:"none",from:""}}}}}function vendorPairs(e){const{exists:t}=e,n=[];if((e.layout||{installed:!1,facePrefix:[]}).installed)return n;for(const{face:o,root:r,staged:s}of BUNDLE_FACES){const a=path.join(e.root,s),i=e.listFiles(a,a);for(const a of i){const i=[];if(a.startsWith("vendor/")){const e=a.slice(7);if(i.push(e),i.push(path.join(r,e)),"selfhost.js"===e&&i.push(path.join("one","src","selfhost.js")),"protocol.js"===e&&i.push(path.join("one","src","protocol.js")),"pty.js"===e&&i.push(path.join("one","src","iface","pty.js")),"desktop"===o){const t=path.basename(e);for(const e of["client","mcp","covenant","commands","skills","tools","hosts"])i.push(path.join(e,t));i.push(t)}}else i.push(path.join(r,a)),i.push(a);const l=i.find(n=>t(path.join(e.root,n)))||null;n.push({face:o,staged:path.join(s,a),source:l,candidates:i})}}return n}function layoutsInstalled(e){return Boolean(e&&e.installed)}function checkVendor(e,t){const n=t||vendorPairs(e),o=[],r=[];let s=0,a=0;const i=e.layout||{installed:!1,facePrefix:[]};if(layoutsInstalled(i)){for(const t of BUNDLE_FACES){const n=path.join(e.root,inLayout(i,t.staged));e.exists(n)&&(a+=e.listFiles(n,n).length)}return{staged:a,matched:0,mismatch:r,missingSource:o,stale:0===a,checked:0}}for(const t of n){if(!e.exists(path.join(e.root,t.staged)))continue;if(a+=1,!t.source){o.push(t.staged);continue}let n,i;try{n=e.hashFile(path.join(e.root,t.source)),i=e.hashFile(path.join(e.root,t.staged))}catch(e){r.push({staged:t.staged,source:t.source,error:String(e&&e.message||e)});continue}n===i?s+=1:r.push({staged:t.staged,source:t.source})}return{staged:a,matched:s,mismatch:r,missingSource:o,stale:n.length>0&&0===a,checked:n.length}}function readJson(e,t){const n=path.join(e.root,t);if(!e.exists(n))return{ok:!1,missing:!0,value:null,path:t};let o;try{o=e.readFile(n)}catch(e){return{ok:!1,unreadable:!0,value:null,path:t,error:String(e&&e.message||e)}}if(null==o)return{ok:!1,missing:!0,value:null,path:t};try{return{ok:!0,value:JSON.parse(o),path:t}}catch(e){return{ok:!1,unreadable:!0,value:null,path:t,error:String(e&&e.message||e)}}}function resolveSeams(e){const t=e||{},n=t.env||{},o=defaultFs(),r=t||{},s=r.exists||o.exists,a=t.layout||layoutOf({exists:s,root:t.root},t.root),i=t.root||a.root,l={root:i,layout:Object.assign({},a,{root:i}),platform:t.platform||"linux",env:n,exists:s,readFile:r.readFile||o.readFile,hashFile:r.hashFile||o.hashFile,listFiles:r.listFiles||o.listFiles,electronPaths:t.electronPaths||defaultElectronPaths(n,t),updateCache:t.updateCache,saveUpdateCache:t.saveUpdateCache,now:"number"==typeof t.now?t.now:0,guiRequested:Boolean(t.guiRequested),guiImplied:t.guiImplied,vendorPairs:t.vendorPairs};return l.credentials=t.credentials||defaultCredentials(l),l.storePath=t.storePath||defaultStorePath(n,l),l.registry=t.registry||defaultRegistry(l),l}function diagnose(e){const t=resolveSeams(e),n=[],o=(e,t)=>n.push({level:"broken",code:e,detail:t}),r=(e,t)=>n.push({level:"warn",code:e,detail:t}),s=t.layout,a=inLayout(s,"one/package.json"),i=readJson(t,a),l=i.ok?{name:i.value.name||"aegisone",version:String(i.value.version||"")}:{name:"aegisone",version:""};i.ok||o("product-unreadable",`${a} ${i.unreadable?"is unreadable":"is missing"}`);let c=null;try{c=require("./release.js").deriveFaceVersions(l.version)}catch(e){c=null,i.ok&&o("product-version-invalid",`${l.version}: ${String(e&&e.message||e)}`)}const u={};for(const{dir:e,package:n}of FACE_PACKAGES){const r=inLayout(s,`${e}/package.json`),a=readJson(t,r),i=a.ok?String(a.value.version||""):"",d=c&&c[n]?c[n].version:null;a.ok?d&&i!==d&&o("version-mismatch",`${n} is ${i}, product ${l.version} derives ${d}`):o("face-unreadable",`${r} ${a.unreadable?"is unreadable":"is missing"}`),u[n]={dir:e,version:i,expected:d,ok:Boolean(d&&i===d)}}let d={key:"",source:"none",from:""};try{d=t.credentials.resolve({env:t.env})||d}catch{d={key:"",source:"none",from:""}}const h=t.electronPaths||{};let p=d.key?"env"===d.source?"env":(d.source,"env-file"):"none";if(!d.key&&h.keychain&&t.exists(h.keychain)){const e=(()=>{try{return t.readFile(h.keychain)}catch{return null}})();e&&/encrypt|safeStorage/i.test(e)&&(p="keychain")}"none"===p&&r("no-credential","no credential found (env, credentials.json, or the OS keychain)");const f={path:t.storePath,exists:!1,readable:null,legacy:null};try{f.exists=t.exists(t.storePath)}catch{f.exists=!1}let g,v=f.path;if(f.exists){let e=null;try{e=t.readFile(f.path)}catch(e){f.readable=!1,o("store-unreadable",`${f.path}: ${String(e&&e.message||e)}`)}if(null===f.readable)if(null==e)f.readable=!1,o("store-unreadable",`${f.path} exists but could not be read`);else try{const t=JSON.parse(e);f.readable=!0,f.legacy=t&&t.version||null}catch(e){f.readable=!1,o("store-unreadable",`${f.path} is not valid JSON: ${String(e&&e.message||e)}`)}v=path.basename(f.path)}f.display=v;try{g=checkVendor(t,t.vendorPairs)}catch(e){g={staged:0,matched:0,mismatch:[],missingSource:[],stale:!1,checked:0,error:String(e&&e.message||e)},o("vendor-unreadable",g.error)}for(const e of g.mismatch)o("vendor-hash-mismatch",`${e.staged} differs from ${e.source||"its source"}`);for(const e of g.missingSource)o("vendor-source-missing",`${e} has no source to be re-derived from`);g.stale&&(s.installed?o("vendor-missing","the ONE bundle is empty — reinstall aegisone"):r("vendor-stale","the ONE bundle has never been staged (one/vendor is empty) — run `npm run predist`"));const m={channel:"npm",current:l.version,latest:null,behind:!1,reason:null,checkedAt:null,cached:!0,action:"none",applier:"npm",instruction:null};try{const e=t.registry.check({current:l.version,cache:t.updateCache,save:t.saveUpdateCache,now:t.now})||{};m.latest=e.latest||null,m.behind=Boolean(e.behind),m.reason=e.reason||null}catch(e){m.reason="unavailable",m.error=String(e&&e.message||e)}try{const e=t.registry.plan({current:l.version,latest:m.latest,behind:m.behind});e&&(m.action=e.action,m.applier=e.applier,m.instruction=e.instruction)}catch{}m.behind&&r("update-available",`${m.current} → ${m.latest} (${m.instruction||"run the channel updater"})`);const y=h&&h.electron||null,b=h&&h.appBundle||null,j=y||b||null;t.guiRequested&&!j&&o("gui-without-electron","--gui was requested but Electron is not installed — use --tui");const k=n.filter(e=>"broken"===e.level).length,$=n.filter(e=>"warn"===e.level).length,S=k?EXIT.BROKEN:$?EXIT.WARN:EXIT.OK;return{report:{aegis:"one",status:k?"broken":$?"warn":"healthy",exitCode:S,product:l,faces:u,credential:{source:p,found:Boolean(d.key),from:d.key?d.from:""},store:{path:f.path,exists:f.exists,readable:f.exists?!0===f.readable:null},vendor:{staged:g.staged,matched:g.matched,mismatched:g.mismatch.length,missingSource:g.missingSource.length,stale:g.stale,verifiable:!s.installed},update:m,gui:{requested:Boolean(t.guiRequested),electron:y||null,appBundle:b||null,usable:Boolean(j)&&(!t.guiImplied||t.guiImplied)},problems:n},code:S}}function render(e){const t=[],n=(e,t)=>String(e)+" ".repeat(Math.max(0,t-String(e).length));t.push(`aegis doctor — ${e.status} (exit ${e.exitCode})`),t.push(` product ${e.product.name} ${e.product.version}`);for(const[o,r]of Object.entries(e.faces)){const e=r.ok?"":` (expected ${r.expected||"unknown"})`;t.push(` ${n(o,14)} ${r.version||"unknown"}${e}`)}t.push(` credential ${e.credential.source}`),t.push(` shared store ${e.store.path} ${e.store.exists?e.store.readable?"(readable)":"(unreadable)":"(absent)"}`),t.push(!1===e.vendor.verifiable?` vendor ${e.vendor.staged} staged (sources not shipped — not re-derivable here)`:` vendor ${e.vendor.staged} staged, ${e.vendor.matched} matching, ${e.vendor.mismatched} mismatched, ${e.vendor.missingSource} without a source`+(e.vendor.stale?" (never staged)":""));const o=e.update;if(t.push(" update "+(o.behind?`${o.current} → ${o.latest}`:`${o.current} is current`)+` (next: ${o.action}${o.instruction?` — ${o.instruction}`:""})`),t.push(" window face "+(e.gui.electron?`Electron at ${e.gui.electron}`:e.gui.appBundle?`native app at ${e.gui.appBundle}`:"not installed")),e.problems.length){t.push(" problems:");for(const n of e.problems)t.push(` ${"broken"===n.level?"✗":"!"} ${n.code}: ${n.detail}`)}return t.join("\n")+"\n"}function wantsGui(e,t){return!!(Array.isArray(e)?e:[]).includes("--gui")||"gui"===(t||{}).AEGISONE_FACE}function main(e,t){const n=t||{},o=Array.isArray(e)?e:[],r=n.stdout||process.stdout,s=n.env||process.env||{},a=Object.assign({},n,{env:s,guiRequested:wantsGui(o,s)}),{report:i,code:l}=diagnose(a),c=o.includes("--json")?JSON.stringify(i)+"\n":render(i);try{r.write(c)}catch{}return l}module.exports={EXIT:EXIT,FACE_PACKAGES:FACE_PACKAGES,wantsGui:wantsGui,diagnose:diagnose,render:render,main:main,vendorPairs:vendorPairs,resolveSeams:resolveSeams},require.main===module&&(process.exitCode=main(process.argv.slice(2)));
package/src/probes.js CHANGED
@@ -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 fs=require("node:fs"),path=require("node:path"),{createRequire:createRequire}=require("node:module"),host=require("./host.js");function hasDisplay(e,t){const r=e||{},n=t||host.hostPlatform();return"darwin"===n||"win32"===n||Boolean(r.DISPLAY||r.WAYLAND_DISPLAY||r.MIR_SERVER_SOCKET)}function resolveFrom(e,t){if(!e)return null;try{return createRequire(path.join(e,"package.json")).resolve(t)}catch{return null}}function electronExecutable(e){const t=Array.isArray(e)?e:[e];for(const e of t){if(!e)continue;const t=packageDirOf(e,"electron");if(!t)continue;const r=unpackedBinary(t);if(r)return r}return null}function packageDirOf(e,t){const r=resolveFrom(e,t+"/package.json");if(r)return path.dirname(r);const n=resolveFrom(e,t);return n?path.dirname(n):null}function unpackedBinary(e){try{const t=fs.readFileSync(path.join(e,"path.txt"),"utf8").trim();if(!t)return null;const r=path.join(e,"dist",t);return fs.existsSync(r)?r:null}catch{return null}}function stdioTty(e,t){const r=e=>{try{return Boolean(e&&e.isTTY)}catch{return!1}};return{stdin:r(void 0===e?process.stdin:e),stdout:r(void 0===t?process.stdout:t)}}function packageDirs(e,t){const r=[path.join(e,"..",t)],n=path.join(e,"vendor",t);return fs.existsSync(n)&&r.push(n),r}function firstFile(e){for(const t of e)if(t&&fs.existsSync(t))return t;return null}function collect(e){const t=e||{},r=t.oneDir||path.resolve(__dirname,".."),n=t.env||process.env,o=t.platform||host.hostPlatform(),s=t.invokedAs||path.basename(process.argv[1]||"aegis"),i=n.AEGISONE_CLI_BIN||firstFile(packageDirs(r,"cli").map(e=>path.join(e,"bin","aegiscode.js"))),a=n.AEGISONE_DESKTOP_BIN||firstFile(packageDirs(r,"desktop").map(e=>path.join(e,"bin","aegis.js"))),c=void 0!==t.electron?t.electron:electronExecutable(packageDirs(r,"desktop"));return{argv:t.argv||process.argv.slice(2),env:n,platform:o,tty:t.tty||stdioTty(process.stdin,process.stdout),hasDisplay:void 0!==t.hasDisplay?Boolean(t.hasDisplay):hasDisplay(n,o),electronResolvable:Boolean(c),invokedAs:s,_cliBin:i,_desktopMain:a,_electron:c}}module.exports={hasDisplay:hasDisplay,resolveFrom:resolveFrom,electronExecutable:electronExecutable,packageDirOf:packageDirOf,unpackedBinary:unpackedBinary,stdioTty:stdioTty,packageDirs:packageDirs,firstFile:firstFile,collect:collect};
3
+ "use strict";const fs=require("node:fs"),path=require("node:path"),{createRequire:createRequire}=require("node:module"),host=require("./host.js");function hasDisplay(e,n){const t=e||{},o=n||host.hostPlatform();return"darwin"===o||"win32"===o||Boolean(t.DISPLAY||t.WAYLAND_DISPLAY||t.MIR_SERVER_SOCKET)}function resolveFrom(e,n){if(!e)return null;try{return createRequire(path.join(e,"package.json")).resolve(n)}catch{return null}}function electronExecutable(e){const n=Array.isArray(e)?e:[e];for(const e of n){if(!e)continue;const n=packageDirOf(e,"electron");if(!n)continue;const t=unpackedBinary(n);if(t)return t}return null}function packageDirOf(e,n){const t=resolveFrom(e,n+"/package.json");if(t)return path.dirname(t);const o=resolveFrom(e,n);return o?path.dirname(o):null}function unpackedBinary(e){try{const n=fs.readFileSync(path.join(e,"path.txt"),"utf8").trim();if(!n)return null;const t=path.join(e,"dist",n);return fs.existsSync(t)?t:null}catch{return null}}function stdioTty(e,n){const t=e=>{try{return Boolean(e&&e.isTTY)}catch{return!1}};return{stdin:t(void 0===e?process.stdin:e),stdout:t(void 0===n?process.stdout:n)}}function isCi(e){const n=e||{},t=n.AEGISONE_CI;if(void 0!==t)return"1"===t||"true"===t;const o=n.CI;return void 0!==o&&""!==o&&"0"!==o&&"false"!==o}function installedAppBundle(e,n){const t=e||{},o=n||host.hostPlatform();if("darwin"===o){const e=t.HOME||"",n=["/Applications",e?path.join(e,"Applications"):null].filter(Boolean);for(const e of n){const n=path.join(e,"aegis one.app","Contents","MacOS","aegis one");if(fs.existsSync(n))return n}return null}if("win32"===o){const e=t.LOCALAPPDATA||(t.USERPROFILE?path.join(t.USERPROFILE,"AppData","Local"):"");if(!e)return null;const n=[path.join(e,"Programs","aegis one")];t.ProgramFiles&&n.push(path.join(t.ProgramFiles,"aegis one")),t["ProgramFiles(x86)"]&&n.push(path.join(t["ProgramFiles(x86)"],"aegis one"));for(const e of n){const n=path.join(e,"aegis one.exe");if(fs.existsSync(n))return n}return null}return null}function packageDirs(e,n){const t=[path.join(e,"..",n)],o=path.join(e,"vendor",n);return fs.existsSync(o)&&t.push(o),t}function firstFile(e){for(const n of e)if(n&&fs.existsSync(n))return n;return null}function collect(e){const n=e||{},t=n.oneDir||path.resolve(__dirname,".."),o=n.env||process.env,r=n.platform||host.hostPlatform(),i=n.invokedAs||path.basename(process.argv[1]||"aegis"),s=o.AEGISONE_CLI_BIN||firstFile(packageDirs(t,"cli").map(e=>path.join(e,"bin","aegiscode.js"))),a=o.AEGISONE_DESKTOP_BIN||firstFile(packageDirs(t,"desktop").map(e=>path.join(e,"bin","aegis.js"))),l=void 0!==n.electron?n.electron:electronExecutable(packageDirs(t,"desktop")),c=void 0!==n.appBundle?n.appBundle:installedAppBundle(o,r);return{argv:n.argv||process.argv.slice(2),env:o,platform:r,tty:n.tty||stdioTty(process.stdin,process.stdout),hasDisplay:void 0!==n.hasDisplay?Boolean(n.hasDisplay):hasDisplay(o,r),electronResolvable:Boolean(l)||Boolean(c),ci:void 0!==n.ci?Boolean(n.ci):isCi(o),invokedAs:i,_cliBin:s,_desktopMain:a,_electron:l,_appBundle:c}}module.exports={hasDisplay:hasDisplay,isCi:isCi,resolveFrom:resolveFrom,electronExecutable:electronExecutable,installedAppBundle:installedAppBundle,packageDirOf:packageDirOf,unpackedBinary:unpackedBinary,stdioTty:stdioTty,packageDirs:packageDirs,firstFile:firstFile,collect:collect};
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "aegiscode",
3
3
  "productName": "AEGIS Code",
4
- "version": "7.0.70",
4
+ "version": "7.0.72",
5
5
  "description": "aegiscode — the command-line version of AEGIS One. 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{randomUUID:randomUUID}=require("node:crypto"),os=require("node:os"),fs=require("node:fs"),toolsModule=require("./tools.js"),attachmentsModule=require("./attachments.js"),{flattenContent:flattenContent}=attachmentsModule,promptModule=require("./prompt.js"),localTransport=require("./local.js"),{ShellSession:ShellSession}=require("./shell.js"),{planExec:planExec}=require("./exec-plan.js"),claudePro=require("./claude-pro.js"),{agentSystemPrompt:agentSystemPrompt,agentRoleLabel:agentRoleLabel}=require("./agents.js"),{beginTurnGuard:beginTurnGuard,recordWrite:recordWrite,blocksDestructive:blocksDestructive}=require("./turn-guard.js"),repeatGuard=require("./repeat-guard.js"),verifyGuard=require("./verify-stop.js"),{acquireWorktreeLock:acquireWorktreeLock,releaseWorktreeLock:releaseWorktreeLock}=require("./worktree-lock.js"),covenant=require("./covenant.js");let envFile=null;try{envFile=require("../../../client/env-file.js")}catch{try{envFile=require("../../vendor/env-file.js")}catch{envFile=null}}let platformLib=null;try{platformLib=require("../../../client/platform.js")}catch{try{platformLib=require("../../vendor/platform.js")}catch{platformLib=null}}let credentialsLib=null;try{credentialsLib=require("../../../client/credentials.js")}catch{try{credentialsLib=require("../../vendor/credentials.js")}catch{credentialsLib=null}}const PRO_TOOL_MAP=Object.freeze({Write:"writeFile",Edit:"editFile",MultiEdit:"editFile",NotebookEdit:"editFile",Bash:"exec",BashOutput:"exec"}),PRO_PLAN_MODE_SAFE=Object.freeze(new Set(["Read","Glob","Grep"]));function proAskArgs(e,t){const o=e&&"object"==typeof e?e:{};return"exec"===t?"string"==typeof o.command?{command:o.command}:{}:"writeFile"===t?"string"==typeof o.file_path?{file_path:o.file_path,content:o.content}:{}:"editFile"===t?Array.isArray(o.edits)?{file_path:o.file_path,edits:o.edits}:"string"==typeof o.file_path?{file_path:o.file_path,old_string:o.old_string,new_string:o.new_string,replace_all:!0===o.replace_all}:{}:o}function normalizeToolArgs(e,t,o,r){const n=e&&"function"==typeof e.normalizeArgs&&e.normalizeArgs||"function"==typeof toolsModule.normalizeArgs&&toolsModule.normalizeArgs||null;return n?n(t,o,r):{ok:!0,args:o&&"object"==typeof o?o:{},error:null}}function detectVcs(e){if(!e)return null;try{const t=require("node:fs"),o=require("node:path");let r=o.resolve(String(e));for(let e=0;e<8;e+=1){if(t.existsSync(o.join(r,".git")))return"git";const e=o.dirname(r);if(e===r)break;r=e}return""}catch{return null}}function hostEnv(e={},t={},o=null){const r=e||{},n=t||{},s=(e,t)=>null!=n[e]?n[e]:t;let a=r.homedir,i=r.cwd;try{a||(a=os.homedir()),i||(i=process.cwd())}catch{}let l=r.shell,c=r.shellKind;try{if(!l||!c){const e=require("./shell.js").resolveSessionShell();l=l||e.cmd,c=c||e.kind}}catch{}let d=r.desktopdir;try{!d&&platformLib&&(d=platformLib.desktopDir())}catch{}let u=r.dataDir;try{!u&&credentialsLib&&(u=credentialsLib.aegisHome())}catch{}let f=r.locale,p=r.localeName;try{!f&&platformLib&&"function"==typeof platformLib.appLocale&&(f=platformLib.appLocale()),f&&!p&&platformLib&&"function"==typeof platformLib.languageName&&(p=platformLib.languageName(f))}catch{}return{platform:s("platform",r.platform||process.platform),arch:s("arch",r.arch||process.arch),homedir:s("homedir",a),desktopdir:s("desktopdir",d),dataDir:s("dataDir",u),locale:s("locale",f),localeName:s("localeName",p),languages:s("languages",r.languages),cwd:s("cwd",i),vcs:s("vcs",null!=r.vcs?r.vcs:detectVcs(i)),shell:s("shell",l),shellKind:s("shellKind",c),roots:s("roots",r.roots),appVersion:s("appVersion",r.appVersion),model:s("model",o&&o.model),class:s("class",r.class||o&&o.class)}}function requireSharedBrain(){const e=[()=>require("../../../client/brain-catalog.js"),()=>require("../../vendor/brain-catalog.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}function requireSharedByokCatalog(){const e=[()=>require("../../../client/byok-catalog.js"),()=>require("../../vendor/byok-catalog.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}function requireSharedUserModels(){const e=[()=>require("../../../client/user-models.js"),()=>require("../../vendor/user-models.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}function requireSharedCatalogClient(){const e=[()=>require("../../../client/catalog-client.js"),()=>require("../../vendor/catalog-client.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}function requireSharedModelDiscovery(){const e=[()=>require("../../../client/model-discovery.js"),()=>require("../../vendor/model-discovery.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}function requireSharedModelSync(){const e=[()=>require("../../../client/model-sync.js"),()=>require("../../vendor/model-sync.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}function requireSharedModelAutoSync(){const e=[()=>require("../../../client/model-autosync.js"),()=>require("../../vendor/model-autosync.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}const WORKTREE_LOCK_WAIT_MS=1500,MAX_SUBAGENT_DEPTH=4,CLASSES=[{class:"aegis",label:"Aegis Cloud",kind:"cloud"},{class:"byok",label:"Bring your own key",kind:"cloud"},{class:"local",label:"Local model",kind:"local"},{class:"pro",label:"Claude Code Pro",kind:"subscription"}],BYOK_NAMESPACE_PREFIX="byok:";function byokNamespace(e){return`byok:${e}`}function splitByokModel(e){const t="string"==typeof e?e:"",o=t.indexOf(":");return o<0?{provider:"",model:t}:{provider:t.slice(0,o),model:t.slice(o+1)}}function providerKeyRecord(e){const t={key:"",env:"",rejected:null};if(!envFile||"function"!=typeof envFile.providerKeyFromEnv)return t;try{const o=envFile.providerKeyFromEnv(e)||t;return{key:"string"==typeof o.key?o.key:"",env:"string"==typeof o.env?o.env:"",rejected:"string"==typeof o.rejected&&o.rejected?o.rejected:null}}catch{return t}}function providerKeyFromEnv(e){if(!envFile||"function"!=typeof envFile.providerKeyFromEnv)return"";try{return envFile.providerKeyFromEnv(e).key||""}catch{return""}}const DEEPSEEK_REASONING_MODEL_RE=/^deepseek-(v4(\.\d+)?-(flash|pro)|flash|pro|reasoner)$/,EFFORT_TOKEN_BUDGET={low:8192,medium:16384,high:32768,max:32768},DEEPSEEK_EFFORT={low:"low",medium:"high",high:"high"},DEEPSEEK_EFFORT_EXTRA={max:"max"},EFFORT_IDENTITY={low:"low",medium:"medium",high:"high"},EFFORT_INERT_RE=/non-reasoning/i,EFFORT_DIALECTS=[{provider:"deepseek",re:DEEPSEEK_REASONING_MODEL_RE,field:"effort",map:DEEPSEEK_EFFORT,extra:DEEPSEEK_EFFORT_EXTRA},{provider:"openai",re:/^(gpt-5|o[0-9])/i,field:"reasoning_effort",map:EFFORT_IDENTITY},{provider:"groq",re:/^(openai\/gpt-oss|qwen\/qwen3)/i,field:"reasoning_effort",map:EFFORT_IDENTITY},{provider:"xai",re:/^grok-(4\.[5-9]|[5-9])/,field:"reasoning_effort",map:EFFORT_IDENTITY},{provider:"google",re:/^gemini-(2\.5|3|[4-9])/,field:"reasoning_effort",map:{...EFFORT_IDENTITY,medium:"high"}}],AUTONOMOUS_IDLE_TIMEOUT_MS=9e5;function reasoningBudget(e,t,o){const r=Number(t);return Number.isFinite(r)&&r>0?r:DEEPSEEK_REASONING_MODEL_RE.test(String(e||""))?EFFORT_TOKEN_BUDGET["low"===o||"medium"===o||"max"===o?o:"high"]:void 0}function nativeEffort(e,t,o){const r=String(t||"");if(EFFORT_INERT_RE.test(r))return;if(null===o)return;const n="low"===o||"medium"===o?o:"max"===o?"max":"high";for(const t of EFFORT_DIALECTS)if(t.provider===e&&t.re.test(r)){const e=Object.prototype.hasOwnProperty.call(t.map,n)?t.map[n]:t.extra&&Object.prototype.hasOwnProperty.call(t.extra,n)?t.extra[n]:void 0;if(void 0===e)return;return{field:t.field,level:e}}}function normalizeCatalog(e){return Array.isArray(e)?e.map(e=>"string"==typeof e?{id:e}:e).filter(e=>e&&e.id):[]}const{offerableCatalog:offerableCatalog}=requireSharedBrain(),{withByokAdditions:withByokAdditions,canonicalModelId:canonicalModelId,nexusFallbackModel:nexusFallbackModel}=requireSharedByokCatalog(),{withUserModels:withUserModels,unmatchedUserProviders:unmatchedUserProviders,load:loadUserModels,addUserModel:addUserModel,removeUserModel:removeUserModel}=requireSharedUserModels(),{withCatalog:withCatalog}=requireSharedCatalogClient(),{discoverModels:discoverVendorModels,canDiscover:canDiscoverVendorModels,endpointFor:vendorEndpointFor,discoverableProviders:discoverableProviders}=requireSharedModelDiscovery(),modelSync=requireSharedModelSync(),{createModelAutoSync:createModelAutoSync}=requireSharedModelAutoSync();function parseArgs(e){if(null==e)return{};if("object"==typeof e)return e;try{const t=JSON.parse(String(e));return t&&"object"==typeof t?t:{}}catch{return{}}}function extractToolCalls(e){if(!e)return[];if(Array.isArray(e.toolCalls)&&e.toolCalls.length)return e.toolCalls.map(e=>({id:e.id||"",name:e.name||"",args:parseArgs(e.args)})).filter(e=>e.name);const t=e.choices&&e.choices[0]&&e.choices[0].message,o=t&&t.tool_calls||[];return Array.isArray(o)?o.map(e=>{const t=e&&e.function||{};return{id:e&&e.id||"",name:t.name||e&&e.name||"",args:parseArgs(t.arguments)}}).filter(e=>e.name):[]}function proTurnPrompt(e){const t=Array.isArray(e.prompt)?flattenContent(e.prompt):e.prompt;if("string"==typeof t&&t.trim())return t;const o=Array.isArray(e.messages)?e.messages:[];for(let e=o.length-1;e>=0;e-=1){const t=o[e];if(!t||"user"!==t.role)continue;const r=flattenContent(t.content);if(r.trim())return r}return t}function assistantText(e){const t=e&&e.choices&&e.choices[0]&&e.choices[0].message;return t&&"string"==typeof t.content&&t.content||""}function finishReasonOf(e){const t=e&&e.choices&&e.choices[0];return t&&t.finish_reason||e&&e.stop_reason||""}function isTruncated(e){const t=finishReasonOf(e);return"length"===t||"max_tokens"===t}function reasoningTextOf(e){if(!e)return"";const t=e.choices&&e.choices[0],o=t&&t.message||{};if(Array.isArray(o.content)){const e=o.content.filter(e=>e&&("thinking"===e.type||"reasoning"===e.type)).map(e=>e.thinking||e.text||"").join("");if(e)return e}const r=o.content&&"object"==typeof o.content?o.content.reasoning_content:"",n=[o.reasoning_content,o.reasoning,t&&t.reasoning_content,e.reasoning_content,e.reasoning,r];for(const e of n)if("string"==typeof e&&e)return e;return""}function reasoningTokensOf(e){if(!e)return 0;const t=e.choices&&e.choices[0],o=t&&t.message||{},r=e.usage||{},n=r.completion_tokens_details||r.output_tokens_details||{},s=[o.thinking_tokens,o.reasoning_tokens,t&&t.thinking_tokens,e.thinking_tokens,n.reasoning_tokens,n.thinking_tokens];for(const e of s)if("number"==typeof e&&Number.isFinite(e)&&e>0)return e;return 0}function reasonedButSilent(e){return!assistantText(e)&&(""!==reasoningTextOf(e)||reasoningTokensOf(e)>0)}const REASONING_RETRY_FLOOR=32768;function retryBudgetFor(e,t){const o=doubledBudget(e.maxTokens);return t&&ladderRung(e.maxTokens)?Math.max(o,32768):o}function ladderRung(e){const t=Number(e);return Number.isFinite(t)&&Object.values(EFFORT_TOKEN_BUDGET).includes(t)}function doubledBudget(e){const t=Number(e)||0;return t>0?2*t:8192}function statedCapOf(e){const t=e=>{const t=Number(e);return Number.isFinite(t)&&t>0?t:void 0};return e&&Object.prototype.hasOwnProperty.call(e,"statedMaxTokens")?t(e.statedMaxTokens):t(e&&e.maxTokens)}const EMPTY_TURN_NUDGE="Your previous reply came back empty — it contained no answer and no tool call. Write your answer now, using only the information already gathered above. No tools are available in this reply, so do not call any: respond in plain prose or markdown.",THOUGHT_ONLY_NUDGE="Your previous round was spent entirely on hidden reasoning and produced no visible reply. Answer the user directly and briefly now. Do not reason, explain, or think first — write only the answer, no tools.",FINAL_ANSWER_NUDGE="Write your answer now, in plain prose, using only what is already in this conversation. If your information is incomplete, say what you have and what is missing — an incomplete answer is the expected outcome here and is better than none. No tools, no preface.",RECOVERY_ROUNDS=2,UNMUTATED_TURN_NUDGE="You ended the turn without changing any file, but this request asked for a change. The tools are still available in this reply: make the edit now with editFile or writeFile. If you already know what to change, change it — describing the fix is not the fix. If you genuinely cannot, say precisely what blocks you.",MUTATION_INTENT_RE=new RegExp("\\b(?:fix|implement|add|create|write|refactor|rename|remove|delete|replace|update|patch|migrate|convert|make\\s+(?:it|them|this|that|the|sure)|change|correct|resolve|repair|address|apply|introduce|support|wire\\s+up)\\b","i");function wantsMutation(e,t,o){if(t)return!1;if(!(o>0))return!1;const r=String(e||"");return!!r.trim()&&!/\?\s*$/.test(r.trim())&&MUTATION_INTENT_RE.test(r)}function emptyTurnError({cls:e,model:t,finishReason:o,reasoningChars:r,reasoningTokens:n,effort:s,recoveryRounds:a}){const i=Number(a)||0,l=Number(n)||0,c=new Error(`The model returned no answer after ${e}/${t} was asked to summarise its results`+(i?`, and ${i} extra recovery call${1===i?"":"s"} with a larger budget and a changed ask came back empty too`:"")+` (stop reason: ${o||"none"}`+(s?`, effort: ${s}`:"")+(r?`, hidden reasoning: ${r} chars and no visible text`:l>0?`, ~${l} thinking tokens billed and no visible text`:"")+"). "+(r||l>0?"Every one of those calls spent its output on hidden reasoning instead of writing a word, so this is the model rather than the budget: pick a model that answers without a thinking pass, or ask for a smaller piece of work.":"No visible text came back from any of those calls. Send the request again, in smaller pieces, or from a different model."));return c.status=502,c}function createLocalEngine({aegis:e,settings:t,tools:o,promptBuilder:r,recallProvider:n,env:s,getConfirmMode:a,getPermissionMode:i,sandbox:l,localTransport:c=localTransport,fetchImpl:d,gitScope:u,permissionRules:f}){const p=new Map,m=o||toolsModule,h=r&&r.buildSystemPrompt||promptModule.buildSystemPrompt,y=f&&"function"==typeof f.rulesVerdict?f.rulesVerdict:null,g=f&&"function"==typeof f.alwaysAllow?f.alwaysAllow:null,k=f&&"function"==typeof f.subjectFor?f.subjectFor:null,v=require("./session-rounds.js"),b=()=>{if("function"==typeof a)return!1!==a();if(t&&"function"==typeof t.getConfirmMode){const e=t.getConfirmMode();return void 0===e||Boolean(e)}return!0},w=()=>"function"==typeof i?"plan"===i():!(!t||"function"!=typeof t.getPermissionMode)&&"plan"===t.getPermissionMode();function S(e,t){return`${e} was not executed — this session is in plan mode (read-only). Plan mode may read files, search, run read-only shell commands and deploy subagents to research, but may not create, edit or delete files, run a mutating command, or install packages`+(t?` (this command: ${t})`:"")+". Do NOT retry it or attempt the same effect by another route. Finish your research and present a plan in plain text; the user exits plan mode (`/permissions mode off`) before any edit can run."}const E=new Map,_=new Map,T=new Map,x=new Map,A=require("./pro-sessions.js"),M=new Map,N=new Map;function O(e,t){if("function"!=typeof k)return e;let o="";try{o=String(k(e,t||{})||"")}catch{o=""}return`${e}\0${o}`}function F(e,t,o){E.has(e)||E.set(e,new Set),E.get(e).add(O(t,o))}function D(e,t){const o=_.get(e);return Boolean(o&&o.has(t))}function R(e,t){_.has(e)||_.set(e,new Set),_.get(e).add(t)}function U(e){if(!e)return null;try{return{existed:!0,content:fs.readFileSync(e,"utf8")}}catch(e){return e&&"ENOENT"===e.code?{existed:!1,content:null}:null}}function I(e){return`${e} was not executed — the user denied this tool for this conversation. Do NOT retry it and do NOT attempt the same effect by another route (another command, a writeFile instead of an edit, a subagent). Stop calling tools and reply in plain text: say what you were trying to do, what you need, and that the user can re-enable ${e} to let it proceed.`}function L(e,t,o,r){return new Promise(n=>{if(o&&o.aborted)return void n("cancel");const s=randomUUID();let a=!1;const i=()=>l("cancel"),l=e=>{a||(a=!0,M.delete(s),o&&o.removeEventListener("abort",i),n(e))};o&&o.addEventListener("abort",i,{once:!0}),M.set(s,{resolve:l}),"function"==typeof t?t({delta:"",approval:{id:s,sessionId:e,tool:r.tool,args:r.args,diff:r.diff||null,canPersist:"function"==typeof g}}):l("cancel")})}function P(e,t,o,r){return new Promise(n=>{if(o&&o.aborted)return void n(!1);const s=randomUUID();let a=!1;const i=()=>l(!1),l=e=>{a||(a=!0,N.delete(s),o&&o.removeEventListener("abort",i),n(e))};o&&o.addEventListener("abort",i,{once:!0}),N.set(s,{resolve:l}),"function"==typeof t?t({delta:"",rounds:{id:s,sessionId:e,spent:r.spent,extensions:r.extensions,max:r.max,size:r.size}}):l(!1)})}async function C(e,t,o,r,n){const s=normalizeToolArgs(m,e,t,o||{});if(!s.ok)return{ok:!1,error:s.error};t=s.args;const a=o&&o.guard;if(a&&"exec"===e){const e=blocksDestructive(a,t&&t.command);if(!e.ok)return{ok:!1,error:e.reason}}const i=o&&o.repeat,l=i?repeatGuard.check(i,e,t):null;if(l&&"refuse"===l.action)return{ok:!1,error:l.error};const c=covenant.preActionAssert({tool:e,args:t||{}});if(!c.allowed){const o=covenant.bindRefusal({tool:e,args:t||{}},c);return{ok:!1,error:`refused by the ÆGIS covenant — ${c.clause} (${c.label}): ${c.reason}`,covenant:o}}const d="writeFile"===e||"editFile"===e,u=d?U(t&&t.file_path):null,f=await m.executeTool(e,t,o);a&&d&&f&&!1!==f.ok&&recordWrite(a,t&&t.file_path),i&&d&&f&&!1!==f.ok&&repeatGuard.recordWrite(i,t&&t.file_path);const p=o&&o.verify;if(p&&(verifyGuard.EXEC_TOOLS.has(e)&&f&&!1!==f.ok?verifyGuard.recordExec(p):d&&f&&!1!==f.ok&&verifyGuard.recordMutation(p,t&&t.file_path)),d&&u&&f&&!1!==f.ok){const o=U(t&&t.file_path);o&&function(e,t){if(!e)return;T.has(e)||T.set(e,[]);const o=T.get(e);o.push(t),o.length>200&&o.shift()}(r,{id:n||randomUUID(),tool:e,path:t&&t.file_path,before:u,after:o,at:Date.now()})}return l&&l.note?$(f,l.note):f}function $(e,t){if(!e||"object"!=typeof e)return{ok:!0,content:`${t}\n${null==e?"":e}`};if(!1===e.ok||!0===e.isError){const o=e.error||e.content||"";return{...e,error:`${t}\n${o}`,content:`${t}\n${o}`}}const o=null!=e.content?e.content:null!=e.output?e.output:"";return{...e,content:`${t}\n${o}`}}async function q(e,{toolCtx:t,rootSessionId:o,rootOnDelta:r,signal:n}){const{name:s}=e,a=normalizeToolArgs(m,s,e.args,t||{});if(!a.ok)return{ok:!1,error:a.error};const i=a.args;if(!m.MUTATING_TOOLS.has(s))return C(s,i,t,o,e.id);if(w()){if("exec"===s){const r=planExec(i&&i.command,{baseCwd:t&&t.cwd||void 0});return r.oneShot?C(s,i,t,o,e.id):{ok:!1,error:S(s,r.reason)}}return{ok:!1,error:S(s)}}if(!b())return C(s,i,t,o,e.id);if(function(e,t,o){const r=E.get(e);return Boolean(r&&r.has(O(t,o)))}(o,s,i))return C(s,i,t,o,e.id);if("function"==typeof y){let r;try{r=y(s,i)}catch(e){r={verdict:null,source:"error",error:e&&e.message||String(e)}}if(r&&"deny"===r.verdict)return R(o,s),{ok:!1,error:I(s),permissionRule:r.rule||null};if(r&&"allow"===r.verdict)return C(s,i,t,o,e.id)}if(D(o,s))return{ok:!1,error:I(s)};let l=null;if(("writeFile"===s||"editFile"===s)&&(l=m.previewMutation(s,i,t||{}),!l.ok))return{ok:!1,error:l.error};const c=await L(o,r,n,{tool:s,args:i,diff:l&&l.diff});if("deny"===c)return R(o,s),{ok:!1,error:I(s)};if("session"!==c&&"once"!==c&&"always"!==c)return{ok:!1,error:`${s} was not executed — the request was cancelled.`};let d=null;if("always"===c){let e=null;if("function"==typeof g)try{e=g(s,i)}catch(t){e={ok:!1,reason:t&&t.message||String(t)}}else e={ok:!1,reason:"no durable store is wired on this host"};d=e&&e.ok?`[permission_rule] stored ${e.rule} — this command will not ask again`:`[permission_rule] nothing was stored — ${e&&e.reason||"unknown reason"}; this call was allowed once only`}if("session"===c&&F(o,s,i),l){const e=m.applyChecked(s,i,l,t||{});return e&&!1!==e.ok&&t&&t.guard&&recordWrite(t.guard,i&&i.file_path),d?$(e,d):e}const u=await C(s,i,t,o,e.id);return d?$(u,d):u}function j(e){return hostEnv(s||{},e&&e.env||{},e)}function B(e){const t=[],o=e=>String(e||"").replace(/[\\/]+$/,""),r=o(e),n=e=>{const n=o(e);n&&n!==r&&!t.includes(n)&&t.push(n)};let s=u;if(void 0===s)try{s=require("./git-scope.js")}catch{s=null}try{s&&"function"==typeof s.gitRoot&&n(s.gitRoot(e))}catch{}try{credentialsLib&&"function"==typeof credentialsLib.aegisHome&&n(credentialsLib.aegisHome())}catch{}return t}async function G(t,o){if("aegis"===t){const t=!o.singlePass&&(!!o.autonomous||void 0);return e.chatCompletion({prompt:o.prompt,system:o.system,messages:o.messages,model:o.model,mode:o.mode,maxTokens:o.statedMaxTokens,stream:!1!==o.stream,includeUsage:!0,onStream:o.onDelta,onReasoning:o.onReasoning,idleTimeoutMs:o.idleTimeoutMs,signal:o.signal,extra:{aegis_recall:!0,...o.recallDeep?{aegis_recall_deep:!0}:{},session:o.sessionId,...void 0===t?{}:{brain:t},...!1===t?{mode:"brain"}:{},...o.effort?{effort:o.effort}:{},...!0===t&&o.workers?{workers:o.workers}:{},...o.tools.length?{tools:o.tools}:{},...o.toolChoice?{tool_choice:o.toolChoice}:{}},agentKey:o.tools.length&&(process.env.AEGIS_AGENT_KEY||"").trim()||void 0})}if("byok"===t){const{provider:t,model:r}=splitByokModel(o.model),n=canonicalModelId(t,r),s=nativeEffort(t,n,o.effort);try{return await e.byokChatCompletion({provider:t,model:n,providerKey:o.apiKey,baseURL:o.cfg&&o.cfg.baseURL,prompt:o.prompt,system:o.system,messages:o.messages,maxTokens:o.maxTokens,tools:o.tools,toolChoice:o.toolChoice,effort:s&&"effort"===s.field?s.level:void 0,reasoningEffort:s&&"reasoning_effort"===s.field?s.level:void 0,stream:!0,onStream:o.onDelta,signal:o.signal})}catch(e){if(e&&402===e.status){const e=new Error("byok: this account has no AEGIS balance left, and the BYOK handling fee is billed there — your provider key is still valid, this is not a key problem. Top up the account, then try again (or /class aegis to use the pooled lane).");throw e.status=402,e}throw e}}if("local"===t){const e=o.cfg&&o.cfg.baseURL||c.DEFAULT_BASE,t={...Number.isFinite(o.budgetSecs)?{budgetSecs:o.budgetSecs}:{},...Number.isFinite(o.tokPerSec)?{tokPerSec:o.tokPerSec}:{}},r=r=>c.chat({baseURL:e,model:o.model,prompt:o.prompt,system:o.system,messages:o.messages,maxTokens:o.maxTokens,signal:o.signal,onDelta:o.onDelta,...t,...r&&o.tools.length?{tools:o.tools,toolChoice:o.toolChoice}:{}});try{return await r(!0)}catch(e){if(o.tools.length&&e&&400===e.status)return r(!1);throw e}}if("pro"===t){const e=o.sessionKey||o.rootSessionId||o.sessionId;let t=null;if(e&&(t=x.get(e)||null,!t)){try{t=A.get(e,s)||null}catch{}t&&x.set(e,t)}const r=B(o.cwd),n=e=>claudePro.runClaudePro({prompt:proTurnPrompt(o),model:o.model&&"default"!==o.model?o.model:void 0,system:o.system,cwd:o.cwd,addDir:r,resumeSessionId:e||void 0,gate:b(),onAsk:async e=>{if(!e||!e.requestId)return"deny";const t=o.rootSessionId,r=o.rootOnDelta,n=PRO_TOOL_MAP[String(e.toolName||"")]||null,s=n||String(e.toolName||"unknown"),a=proAskArgs(e.input||{},s),i=covenant.preActionAssert({tool:s,args:a});if(!i.allowed)return r&&r({delta:"",note:`aegis: refused by the ÆGIS covenant — ${i.clause} (${i.label}): ${i.reason}`}),"deny";if(w()){if("exec"===s){const e=planExec(a&&a.command,{baseCwd:o.cwd||void 0});return e.oneShot?"once":(r&&r({delta:"",note:S(s,e.reason)}),"deny")}if(n&&m.MUTATING_TOOLS.has(s))return r&&r({delta:"",note:S(s)}),"deny";if(!n&&!PRO_PLAN_MODE_SAFE.has(s))return r&&r({delta:"",note:S(s)}),"deny"}if(!b())return"once";if("function"==typeof y){let e;try{e=y(s,a)}catch{e=null}if(e&&"deny"===e.verdict)return r&&r({delta:"",note:I(s)}),"deny";if(e&&"allow"===e.verdict)return"once"}if(D(t,s))return r&&r({delta:"",note:I(s)}),"deny";const l=await L(t,r,o.signal,{tool:s,args:a,diff:null});if("deny"===l)return R(t,s),"deny";if("session"!==l&&"once"!==l&&"always"!==l)return"deny";if("session"===l&&F(t,s,a),"always"===l&&"function"==typeof g)try{g(s,a)}catch{}return l},signal:o.signal,onDelta:o.onDelta,onSpawn:(e,t)=>{o.onDelta&&t&&o.onDelta({delta:"",note:claudePro.childLine(t)})}});let a=await n(t);if(a&&a.resumeStale){x.delete(e);try{A.del(e,s)}catch{}o.onDelta&&o.onDelta({delta:"",note:"aegis: the remembered Claude session no longer exists on this machine — continuing as a new conversation (earlier turns are not in its context)"}),a=await n(null)}if(e&&a&&a.sessionId&&!a.error){x.set(e,a.sessionId);try{A.set(e,a.sessionId,s)}catch{}}return a}throw new Error(`dispatch: unknown model class ${JSON.stringify(t)} — this build ships 'aegis', 'byok', 'local' and 'pro' only`)}async function K(o,r){const s=o&&o.class,a=o&&o.model,i=reasoningBudget("byok"===s?splitByokModel(a).model:a,o&&o.maxTokens,o&&o.effort),d=statedCapOf(o),u="aegis"===s&&Boolean(o&&o.autonomous),f=Boolean(o&&o.roundsAsk),y=o&&o.sessionId||randomUUID(),g=Number.isInteger(o&&o.depth)?o.depth:0,k=o&&o.rootSessionId||y,b=o&&o.rootOnDelta||r,w="function"==typeof r?e=>e&&r({reasoning:e}):void 0,S=new AbortController,E=p.get(y)||null;p.set(y,S);const _=S.signal,T=!(o&&!1===o.tools),x="local"!==s&&g<4,A=T?m.toolsFor({includeSubagent:x}):[],M=o&&o.toolChoice||null,N=j(o),O=o&&o.system||h(N),F=n?await n({payload:o,env:N,system:O}):null,D="string"==typeof F?F:F&&"string"==typeof F.system?F.system:O,R=Array.isArray(o&&o.messages)?o.messages.filter(Boolean).slice():[];let U=R.length,I=o&&o.prompt||"";const L=String(I||""),C=Array.isArray(o&&o.attachments)?o.attachments.filter(e=>e&&"object"==typeof e).slice(0,attachmentsModule.MAX_ATTACHMENTS):[];let $=C.length?attachmentsModule.buildContent(I,C):I,K=null;const W=j(o),z=((e,t)=>{if(null==l)return null;const o="function"==typeof l.policy?l.policy():l.policy;if(!o)return null;const r=require("./sandbox.js"),n=e&&e.cwd||process.cwd(),s=r.normalize(o,n);if("off"===s.mode)return null;let a=[];try{let e=null;try{e=require("node:os").homedir()}catch{e=null}a=r.autoGrants(n,{home:e,addDirs:(()=>{try{return B(n)}catch{return[]}})()})}catch{a=[]}if(a.length){const e=new Set;for(const t of s.fileSystem.entries)t&&t.path&&"path"===t.path.type&&t.path.path&&e.add(`${t.access}:${t.path.path}`);for(const t of a){const o=`${t.access}:${t.path.path}`;e.has(o)||(e.add(o),s.fileSystem.entries.push(t))}}return"local"===t&&"restricted"===s.network&&(s.network="open",s.networkExempt="local"),{policy:s,state:l.state||r.detect({appDir:l.appDir}),workspace:n,appDir:l.appDir,strict:!0===l.strict}})(W,s),V=W.cwd,H={getShell:()=>K||(K=new ShellSession({cwd:W.cwd,sandbox:z})),signal:_,cwd:V,desktopdir:W.desktopdir,sandbox:z,repeat:repeatGuard.beginRepeatGuard({cwd:V}),verify:verifyGuard.beginVerifyGuard({cwd:V}),guard:beginTurnGuard(V)};try{const n="byok"===s?splitByokModel(a):null;let l=null;const p="byok"===s?t.get(byokNamespace(n.provider))||{}:"local"===s&&t.get("local")||{},h="byok"===s?t.rawKey(byokNamespace(n.provider)):null,S="byok"!==s?null:h||providerKeyFromEnv(n.provider);if(!("byok"!==s||n.provider&&n.model)){const e=new Error('byok: model must be "<provider>:<model>" (pick one from /models) — got '+JSON.stringify(a||""));throw e.status=400,e}if("byok"===s&&!S){const t="anthropic"===n.provider?claudePro.claudeProStatus({env:process.env}):null,o=providerKeyRecord(n.provider).rejected,r=nexusFallbackModel({provider:n.provider,providerKey:S,providerKeyRefused:o,aegisKey:S?"":e.apiKey});if(!r){const e=new Error(o?`${o}. That is why this turn has no ${n.provider} key: an env value that short is a paste that lost its payload, not a credential. Fix ${o.split(" ")[0]} in ~/.aegiscode/.env (or the shell that exported it) — or skip keys entirely: /byok-key ${n.provider} <key> to set one here.`:t&&t.loggedIn?`No Anthropic API key on this machine — an "anthropic:…" id is served by your own console key, which a Claude subscription is not. Use the subscription instead: /class pro (it spends your Claude Code ${t.subscription||"Pro"} plan through the claude CLI) — or add a real console key: /byok-key anthropic <key>.`:`No key for "${n.provider}" yet. Easiest fix: /class aegis (uses your AEGIS key, no setup) — or add this provider's own key: /byok-key ${n.provider} <key>.`);throw e.status=400,e}l={from:n.provider,model:r}}if("byok"===s&&!e.apiKey){const e=new Error("No AEGIS key connected yet. Easiest fix: /class aegis (skips BYOK entirely) — or add your AEGIS key with /login, then try again.");throw e.status=401,e}if("local"===s){const e=c.remoteRefusal(p.baseURL||c.DEFAULT_BASE);if(e)throw e}if("byok"===s&&"custom"===n.provider&&!(p.baseURL||"").trim()){const e=new Error('No endpoint saved for the "custom" provider — its key is on this machine but the address it dials is not, and no default exists for a vendor AEGIS does not know. Fix: /model-add custom <https-base-url> <api-key> <model-id> (writes both halves), or the endpoint field in Settings › Provider (custom).');throw e.status=400,e.code="custom_endpoint_missing",e}const E=l?"aegis":s,x={cls:E,model:l?l.model:a,mode:o&&o.mode,maxTokens:i,statedMaxTokens:d,autonomous:u,sessionId:y,signal:_,onDelta:r,cfg:p,apiKey:S,toolChoice:M,pooledFrom:l?l.from:void 0,cwd:V,rootSessionId:k,sessionKey:o&&o.sessionKey||void 0,rootOnDelta:b,effort:o&&o.effort,workers:o&&o.workers,...Number.isFinite(o&&o.budgetSecs)?{budgetSecs:o.budgetSecs}:{},...Number.isFinite(o&&o.tokPerSec)?{tokPerSec:o.tokPerSec}:{},recallDeep:o&&!0===o.recallDeep,singlePass:o&&!0===o.singlePass,onReasoning:w,idleTimeoutMs:u?9e5:void 0,stream:!o||!1!==o.stream};let N=!1,O=!1;const F=u?"AEGIS_AUTONOMOUS_MAX_ROUNDS":"AEGIS_CHAT_MAX_ROUNDS",j=(()=>{const e=Number.parseInt(process.env[F]||"",10);return Number.isFinite(e)&&e>0?e:0})(),B=j||(u?40:24);let K=v.keyFor(o,R),W=v.take(K);if(!W&&!v.isStatedKey(o)){const e=v.adopt();e&&(W=e.entry,K=e.key)}if(W){const e=v.resumePreamble(W);0===R.length?Array.isArray(W.messages)&&W.messages.length&&R.push(...W.messages):Array.isArray(W.added)&&W.added.length&&R.push(...W.added),I?(I=`${e}\n\n${I}`,$=C.length?attachmentsModule.buildContent(I,C):I):(R.push({role:"user",content:e}),$=""),b&&b({delta:`\n\n[resuming work this session left unfinished at ${W.rounds} tool rounds`+(W.interruptions>1?` (cut off ${W.interruptions}×)`:"")+"…]\n"})}let z=j||B+(W?v.bonus(B):0),X=0;const J=B,Q=8;let Z=0;const ee={calls:0},te=["input_tokens","output_tokens","prompt_tokens","completion_tokens","total_tokens","cache_read_input_tokens","cache_creation_input_tokens","prompt_cache_hit_tokens","prompt_cache_miss_tokens","reasoning_tokens","thinking_tokens"],oe=e=>{const t=e&&e.usage;if(t&&"object"==typeof t){ee.calls+=1;for(const e of te)"number"==typeof t[e]&&Number.isFinite(t[e])&&(ee[e]=(ee[e]||0)+t[e]);if("number"!=typeof t.total_tokens){const e=(t.prompt_tokens??t.input_tokens??0)+(t.completion_tokens??t.output_tokens??0);e&&(ee.total_tokens=(ee.total_tokens||0)+e)}}},re=e=>{if(!e||"object"!=typeof e)return e;const t=l?{...e,pooled_from:l.from,pooled_model:l.model,pooled_notice:requireSharedByokCatalog().nexusFallbackNotice({pooled_from:l.from,pooled_model:l.model})}:e;return ee.calls?{...t,usage:{...ee}}:t},ne=()=>{if(""===$)return;const e=R[R.length-1],t=e&&"user"===e.role?flattenContent(e.content):null;e&&"user"===e.role&&t===flattenContent($)||R.push({role:"user",content:$}),I="",$=""};U=R.length;const se=m&&m.MUTATING_TOOLS||new Set;let ae=0,ie=0,le=!1,ce=!1;for(;;){if(X>=z){if(f&&Z<Q&&!_.aborted&&await P(k,b,_,{spent:z,extensions:Z+1,max:Q,size:J})){Z+=1;const e=z;z+=J,R.push({role:"user",content:`You have used all ${e} tool rounds allowed for this turn; ${J} more have been granted (do not restart). Continue the task from exactly where you stopped — do not re-plan, do not repeat work already done, and finish with an answer.`});continue}const e=f?"":`, or raise ${F} for a longer single turn`,t=`[stopped at ${z} tool rounds`+(ee.total_tokens?`, ${ee.total_tokens.toLocaleString()} tokens`:"")+". This session holds the work: your next message here resumes it automatically"+` (with a continuation preamble)${e}.]`,o=v.record(K,{rounds:X,tokens:ee.total_tokens||0,note:t,chain:W?W.interruptions:0,messages:R,added:R.slice(U)});return b&&b({delta:`\n\n${t}`}),re({model:x.model,choices:[{message:{content:t},finish_reason:"length"}],stoppedOnRounds:!0,heldForSession:!0,heldRounds:o.rounds,sessionInterruptions:o.interruptions,resumedFrom:K})}X+=1;const e={...x,system:D,messages:R,prompt:$,tools:A,recallDeep:x.recallDeep&&1===X};let t;if(t=await G(E,e),oe(t),_.aborted)return re(t);if(!N&&!assistantText(t)&&(isTruncated(t)||reasonedButSilent(t))){N=!0;const o=reasonedButSilent(t);if(t=await G(E,{...e,singlePass:!0,recallDeep:!1,effort:o?"high":e.effort,maxTokens:retryBudgetFor(e,o),statedMaxTokens:e.statedMaxTokens?doubledBudget(e.statedMaxTokens):void 0}),oe(t),_.aborted)return re(t)}const n=A.length?extractToolCalls(t):[];if(!n.length){if(assistantText(t)||O||!T){if(!le&&T&&wantsMutation(L,ie>0,ae)){le=!0,ne(),R.push({role:"assistant",content:assistantText(t)}),R.push({role:"user",content:UNMUTATED_TURN_NUDGE}),b&&b({delta:""});continue}if(H.verify&&!ce){const e=verifyGuard.shouldNudge(H.verify);if(e.nudge){ce=!0,ne(),R.push({role:"assistant",content:assistantText(t)}),R.push({role:"user",content:e.text}),b&&b({delta:""});continue}}return re(t)}O=!0,ne(),R.push({role:"user",content:reasonedButSilent(t)?THOUGHT_ONLY_NUDGE:EMPTY_TURN_NUDGE});const o={...e,singlePass:!0,recallDeep:!1,messages:R,prompt:"",tools:[]};t=await G(E,o);let r=o.maxTokens,n=o.effort;if(oe(t),_.aborted)return re(t);if(!assistantText(t)&&(isTruncated(t)||reasonedButSilent(t))){const e=reasonedButSilent(t);if(r=retryBudgetFor(o,e),n=e?"high":o.effort,t=await G(E,{...o,effort:n,maxTokens:r,statedMaxTokens:o.statedMaxTokens?doubledBudget(o.statedMaxTokens):void 0}),oe(t),_.aborted)return re(t)}const i=(()=>{const e=Number(r)||0;if(!e)return r;const t={maxTokens:r};return o.statedMaxTokens&&(t.statedMaxTokens=o.statedMaxTokens),Math.max(e,retryBudgetFor(t,!0))})();let l=0;for(;!assistantText(t)&&l<2&&!_.aborted;){const e=reasonedButSilent(t);if(l+=1,R.push({role:"user",content:e?1===l?THOUGHT_ONLY_NUDGE:FINAL_ANSWER_NUDGE:EMPTY_TURN_NUDGE}),e&&(n="high"),r=i,t=await G(E,{...o,messages:R,effort:n,maxTokens:r,statedMaxTokens:o.statedMaxTokens?doubledBudget(o.statedMaxTokens):void 0}),oe(t),_.aborted)return re(t)}if(!assistantText(t))throw emptyTurnError({cls:s,model:a,effort:n,recoveryRounds:l,finishReason:finishReasonOf(t),reasoningChars:reasoningTextOf(t).length,reasoningTokens:reasoningTokensOf(t)});return re(t)}ne(),R.push({role:"assistant",content:assistantText(t),tool_calls:n.map(e=>({id:e.id,type:"function",function:{name:e.name,arguments:JSON.stringify(e.args)}}))});const i=new WeakMap,l=e=>{if("exec"!==e.name)return null;if(i.has(e))return i.get(e);const t=planExec(e.args&&e.args.command,{baseCwd:V});return i.set(e,t),t},c=e=>{if(!se.has(e.name))return!0;const t=l(e);return Boolean(t&&t.oneShot)},u=[];for(const e of n){const t=u[u.length-1];c(e)&&t&&t.parallel?t.calls.push(e):u.push({parallel:c(e),calls:[e]})}const p=async e=>{r&&r({delta:"",tool:{name:e.name,args:e.args,id:e.id,cwd:V,phase:"run"}});const t=l(e),n=t&&t.oneShot?{...H,oneShotExec:!0,cwd:t.cwd||H.cwd}:H,i=e.name===m.SUBAGENT_TOOL?await Y(e.args,{cls:s,model:a,statedMaxTokens:d,effort:o&&o.effort,mode:o&&o.mode,parentSignal:_,depth:g,rootSessionId:k,rootOnDelta:b}):await q(e,{toolCtx:n,rootSessionId:k,rootOnDelta:b,signal:_});return i&&i.usage&&oe({usage:i.usage}),r&&r({delta:"",tool:{name:e.name,args:e.args,ok:i.ok,id:e.id,cwd:V,phase:"done"}}),i};for(const e of u){const t=e.parallel&&e.calls.length>1?await Promise.all(e.calls.map(e=>p(e))):[await p(e.calls[0])];e.calls.forEach((e,o)=>{const r=t[o];se.has(e.name)&&(ae+=1,r&&r.ok&&(ie+=1)),R.push({role:"tool",tool_call_id:e.id,name:e.name,content:m.toolResultText(r)})})}}}catch(e){throw _.aborted&&e&&"object"==typeof e&&(e.aegisCancelled=!0),e}finally{K&&K.dispose(),p.get(y)===S&&(E&&!E.signal.aborted?p.set(y,E):p.delete(y))}}async function Y({description:e,subagent_type:t,prompt:o}={},{cls:r,model:n,statedMaxTokens:s,effort:a,mode:i,parentSignal:l,depth:c,rootSessionId:d,rootOnDelta:u}={}){const f=String(o||e||"").trim();if(!f)return{ok:!1,error:"task requires a prompt"};const p=t&&"general"!==t?agentRoleLabel(t):"general",m=agentSystemPrompt(t),h=randomUUID();let y;if(l){if(l.aborted)return{ok:!1,error:"aborted"};y=()=>W(h),l.addEventListener("abort",y,{once:!0})}try{const e=await K({class:r,model:n,mode:i,system:m,prompt:f,sessionId:h,depth:(c||0)+1,rootSessionId:d,rootOnDelta:u,statedMaxTokens:s,effort:a},()=>{}),t=assistantText(e),o=e&&e.usage?{usage:e.usage}:{};return t?{ok:!0,output:t,...o}:{ok:!1,error:`subagent (${p}) produced no output`,...o}}catch(e){return{ok:!1,error:`subagent (${p}) failed: ${e&&e.message?e.message:e}`}}finally{l&&y&&l.removeEventListener("abort",y)}}function W(e){const t=p.get(e);return t&&t.abort(),{ok:Boolean(t)}}function z(e){const o=String(null==e?"":e).trim().toLowerCase();if(!o)return"";try{if(t&&"function"==typeof t.rawKey){const e=t.rawKey(byokNamespace(o));if("string"==typeof e&&e.trim())return e.trim()}}catch{}return providerKeyFromEnv(o)}async function V(t){let o=[];try{const t=await e.byokProviders();o=withUserModels(withCatalog(withByokAdditions(t&&t.providers||[])))}catch(e){return{ok:!1,providers:[],missing:0,stale:0,skipped:[],failed:[],error:e&&e.message||String(e)}}const r={};for(const e of modelSync.askableProviders(o,t)){const t=z(e);t&&(r[e]=t)}return modelSync.plan(o,{keys:r,fetchImpl:d,only:t})}const H=createModelAutoSync({getPref:()=>{try{return t&&"function"==typeof t.getSharedPref?t.getSharedPref("modelAutoSync"):null}catch{return null}},plan:e=>V(e),apply:(e,t)=>modelSync.apply(e,{only:t})});return{CLASSES:CLASSES,listClasses:async function(){return CLASSES.map(o=>{if("aegis"===o.class)return{...o,configured:Boolean(e.apiKey)};if("byok"===o.class){const e=(t.list()||[]).some(e=>!(!e||"string"!=typeof e.provider||!e.provider.startsWith("byok:"))&&(!!e.configured||Boolean(providerKeyFromEnv(e.provider.slice(5)))));return{...o,configured:e}}if("local"===o.class)return{...o,configured:!0};if("pro"===o.class){const e=claudePro.claudeProStatus({env:process.env}),t=claudePro.seamAvailable();return{...o,configured:e.loggedIn,status:e,seam:t}}return{...o,configured:!1}})},listModels:async function(o){if("aegis"===o){if(!e.apiKey)return{class:o,models:[],needsKey:!0};const t=await e.listModels();return{class:o,models:offerableCatalog(normalizeCatalog(t&&t.models))}}if("byok"===o){let r=[],n=null,s=!1,a=null;try{const t=await e.byokProviders();r=withUserModels(withCatalog(withByokAdditions(t&&t.providers||[]))),n=t&&t.fee||null}catch(e){r=[],s=!0,a=e&&e.message||String(e)}const i=[];for(const e of r){if(!e||!e.id)continue;const o=t.get(byokNamespace(e.id))||{},r=providerKeyRecord(e.id),n=r.key||"",s=Array.isArray(e.models)?e.models:[];for(const t of s){const s="string"==typeof t?t:t&&t.id;s&&i.push({id:`${e.id}:${s}`,label:`${e.label||e.id} — ${s}`,provider:e.id,configured:Boolean(o.configured||n),keyRejected:r.rejected||null})}}return{class:o,models:i,providers:r,needsProviderKey:i.length>0&&!i.some(e=>e.configured),needsAegisKey:!e.apiKey,fee:n,providersFailed:s,providersError:a,unmatchedProviders:unmatchedUserProviders(r)}}if("local"===o){const e=(t.get("local")||{}).baseURL||c.DEFAULT_BASE,r=await c.probe(e);if(!r.running)return{class:o,models:[],baseURL:r.baseURL,needsDaemon:!0};let n=[],s=!0;try{n=await c.listTags(e)}catch{s=!1}return{class:o,models:n,baseURL:r.baseURL,listed:s}}if("pro"===o){const e=claudePro.claudeProStatus({env:process.env});return{class:o,models:claudePro.PRO_MODELS.map(t=>({id:t.id,label:t.label,note:t.note,configured:e.loggedIn})),needsProviderKey:!1,needsAegisKey:!1,subscription:e.subscription,loggedIn:e.loggedIn,credentialFile:e.file,shadowed:e.shadowed||null,seam:claudePro.seamAvailable()}}throw new Error(`listModels: unknown model class ${JSON.stringify(o)} — this build ships 'aegis', 'byok', 'local' and 'pro' only`)},chat:K,cancel:W,respondApproval:function(e,t){const o=M.get(e);return o?(M.delete(e),o.resolve("session"===t||"once"===t||"always"===t?t:"deny"),{ok:!0}):{ok:!1}},respondRoundsAsk:function(e,t){const o=N.get(e);return o?(N.delete(e),o.resolve(!0===t||"continue"===t),{ok:!0}):{ok:!1}},clearSessionApprovals:function(e){E.delete(e),_.delete(e),T.delete(e),x.delete(e);try{A.del(e,s)}catch{}return{ok:!0}},listUndoable:function(e){return(T.get(e)||[]).map(e=>({id:e.id,tool:e.tool,path:e.path,at:e.at})).reverse()},undoMutation:function(e,t){const o=T.get(e)||[],r=t?o.findIndex(e=>e.id===t):o.length-1;if(-1===r)return{ok:!1,error:t?`no undo record "${t}" for this conversation`:"nothing to undo in this conversation"};const n=o[r],s=U(n.path);if(!s||s.existed!==n.after.existed||s.content!==n.after.content)return{ok:!1,error:`${n.path} has changed since ${n.tool} ran — undo refused rather than overwriting work this session did not do. Resolve it by hand, or undo a different entry.`};try{n.before.existed?fs.writeFileSync(n.path,n.before.content,"utf8"):fs.unlinkSync(n.path)}catch(e){return{ok:!1,error:`undo failed: ${e&&e.message||e}`}}return o.splice(r,1),{ok:!0,path:n.path,restored:n.before.existed?"content":"deleted"}},settings:t,unloadLocalModels:function(){return c.unloadAll()},userModels:()=>loadUserModels(),addUserModel:(e,t)=>addUserModel(e,t),removeUserModel:(e,t)=>removeUserModel(e,t),discoverModels:async e=>{const t=String(null==e?"":e).trim().toLowerCase(),o=z(t),r=await discoverVendorModels(t,{key:o,fetchImpl:d});if(!r||!r.ok)return r;const n=[];try{const e=loadUserModels().map;for(const o of Array.isArray(e[t])?e[t]:[])n.push(o)}catch{}return{...r,declared:n,endpoint:(vendorEndpointFor(t)||{}).url||""}},modelSyncPlan:async e=>V(e),modelSyncApply:(e,t)=>modelSync.apply(e,{only:t}),modelAutoSync:H,modelAutoSyncRun:e=>H.runIfDue(e),modelAutoSyncStatus:()=>H.status(),addUserModels:(e,t)=>{const o=Array.isArray(t)?t:[],r={provider:e,added:0,already:[],failed:[],capped:0,file:""};for(const t of o)try{const o=addUserModel(e,t);r.file=o.file||r.file,o.added?r.added+=1:r.already.push(o.model)}catch(e){const n=e&&e.message||String(e);if(/the cap/.test(n)){r.capped=o.length-r.added-r.already.length-r.failed.length;break}r.failed.push({id:String(t),reason:n})}return r},canDiscoverModels:e=>canDiscoverVendorModels(e),discoverableProviders:()=>discoverableProviders()}}module.exports={CLASSES:CLASSES,createLocalEngine:createLocalEngine,extractToolCalls:extractToolCalls,parseArgs:parseArgs,reasoningBudget:reasoningBudget,nativeEffort:nativeEffort,hostEnv:hostEnv};
3
+ "use strict";const{randomUUID:randomUUID}=require("node:crypto"),os=require("node:os"),fs=require("node:fs"),toolsModule=require("./tools.js"),attachmentsModule=require("./attachments.js"),{flattenContent:flattenContent}=attachmentsModule,promptModule=require("./prompt.js"),localTransport=require("./local.js"),{ShellSession:ShellSession}=require("./shell.js"),{planExec:planExec}=require("./exec-plan.js"),claudePro=require("./claude-pro.js"),{agentSystemPrompt:agentSystemPrompt,agentRoleLabel:agentRoleLabel}=require("./agents.js"),{beginTurnGuard:beginTurnGuard,recordWrite:recordWrite,blocksDestructive:blocksDestructive}=require("./turn-guard.js"),repeatGuard=require("./repeat-guard.js"),verifyGuard=require("./verify-stop.js"),{acquireWorktreeLock:acquireWorktreeLock,releaseWorktreeLock:releaseWorktreeLock}=require("./worktree-lock.js"),covenant=require("./covenant.js");let envFile=null;try{envFile=require("../../../client/env-file.js")}catch{try{envFile=require("../../vendor/env-file.js")}catch{envFile=null}}let platformLib=null;try{platformLib=require("../../../client/platform.js")}catch{try{platformLib=require("../../vendor/platform.js")}catch{platformLib=null}}let credentialsLib=null;try{credentialsLib=require("../../../client/credentials.js")}catch{try{credentialsLib=require("../../vendor/credentials.js")}catch{credentialsLib=null}}const PRO_TOOL_MAP=Object.freeze({Write:"writeFile",Edit:"editFile",MultiEdit:"editFile",NotebookEdit:"editFile",Bash:"exec",BashOutput:"exec"}),PRO_PLAN_MODE_SAFE=Object.freeze(new Set(["Read","Glob","Grep"]));function proAskArgs(e,t){const o=e&&"object"==typeof e?e:{};return"exec"===t?"string"==typeof o.command?{command:o.command}:{}:"writeFile"===t?"string"==typeof o.file_path?{file_path:o.file_path,content:o.content}:{}:"editFile"===t?Array.isArray(o.edits)?{file_path:o.file_path,edits:o.edits}:"string"==typeof o.file_path?{file_path:o.file_path,old_string:o.old_string,new_string:o.new_string,replace_all:!0===o.replace_all}:{}:o}function normalizeToolArgs(e,t,o,r){const n=e&&"function"==typeof e.normalizeArgs&&e.normalizeArgs||"function"==typeof toolsModule.normalizeArgs&&toolsModule.normalizeArgs||null;return n?n(t,o,r):{ok:!0,args:o&&"object"==typeof o?o:{},error:null}}function detectVcs(e){if(!e)return null;try{const t=require("node:fs"),o=require("node:path");let r=o.resolve(String(e));for(let e=0;e<8;e+=1){if(t.existsSync(o.join(r,".git")))return"git";const e=o.dirname(r);if(e===r)break;r=e}return""}catch{return null}}function hostEnv(e={},t={},o=null){const r=e||{},n=t||{},s=(e,t)=>null!=n[e]?n[e]:t;let a=r.homedir,i=r.cwd;try{a||(a=os.homedir()),i||(i=process.cwd())}catch{}let l=r.shell,c=r.shellKind;try{if(!l||!c){const e=require("./shell.js").resolveSessionShell();l=l||e.cmd,c=c||e.kind}}catch{}let d=r.desktopdir;try{!d&&platformLib&&(d=platformLib.desktopDir())}catch{}let u=r.dataDir;try{!u&&credentialsLib&&(u=credentialsLib.aegisHome())}catch{}let f=r.locale,p=r.localeName;try{!f&&platformLib&&"function"==typeof platformLib.appLocale&&(f=platformLib.appLocale()),f&&!p&&platformLib&&"function"==typeof platformLib.languageName&&(p=platformLib.languageName(f))}catch{}return{platform:s("platform",r.platform||process.platform),arch:s("arch",r.arch||process.arch),homedir:s("homedir",a),desktopdir:s("desktopdir",d),dataDir:s("dataDir",u),locale:s("locale",f),localeName:s("localeName",p),languages:s("languages",r.languages),cwd:s("cwd",i),vcs:s("vcs",null!=r.vcs?r.vcs:detectVcs(i)),shell:s("shell",l),shellKind:s("shellKind",c),roots:s("roots",r.roots),appVersion:s("appVersion",r.appVersion),model:s("model",o&&o.model),class:s("class",r.class||o&&o.class)}}function requireSharedBrain(){const e=[()=>require("../../../client/brain-catalog.js"),()=>require("../../vendor/brain-catalog.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}function requireSharedByokCatalog(){const e=[()=>require("../../../client/byok-catalog.js"),()=>require("../../vendor/byok-catalog.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}function requireSharedUserModels(){const e=[()=>require("../../../client/user-models.js"),()=>require("../../vendor/user-models.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}function requireSharedCatalogClient(){const e=[()=>require("../../../client/catalog-client.js"),()=>require("../../vendor/catalog-client.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}function requireSharedModelDiscovery(){const e=[()=>require("../../../client/model-discovery.js"),()=>require("../../vendor/model-discovery.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}function requireSharedModelSync(){const e=[()=>require("../../../client/model-sync.js"),()=>require("../../vendor/model-sync.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}function requireSharedModelAutoSync(){const e=[()=>require("../../../client/model-autosync.js"),()=>require("../../vendor/model-autosync.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}const WORKTREE_LOCK_WAIT_MS=1500,MAX_SUBAGENT_DEPTH=4,CLASSES=[{class:"aegis",label:"Aegis Cloud",kind:"cloud"},{class:"byok",label:"Bring your own key",kind:"cloud"},{class:"local",label:"Local model",kind:"local"},{class:"pro",label:"Claude Code Pro",kind:"subscription"}],BYOK_NAMESPACE_PREFIX="byok:";function byokNamespace(e){return`byok:${e}`}function splitByokModel(e){const t="string"==typeof e?e:"",o=t.indexOf(":");return o<0?{provider:"",model:t}:{provider:t.slice(0,o),model:t.slice(o+1)}}function providerKeyRecord(e){const t={key:"",env:"",rejected:null};if(!envFile||"function"!=typeof envFile.providerKeyFromEnv)return t;try{const o=envFile.providerKeyFromEnv(e)||t;return{key:"string"==typeof o.key?o.key:"",env:"string"==typeof o.env?o.env:"",rejected:"string"==typeof o.rejected&&o.rejected?o.rejected:null}}catch{return t}}function providerKeyFromEnv(e){if(!envFile||"function"!=typeof envFile.providerKeyFromEnv)return"";try{return envFile.providerKeyFromEnv(e).key||""}catch{return""}}const DEEPSEEK_REASONING_MODEL_RE=/^deepseek-(v4(\.\d+)?-(flash|pro)|flash|pro|reasoner)$/,EFFORT_TOKEN_BUDGET={low:8192,medium:16384,high:32768,max:32768},DEEPSEEK_EFFORT={low:"low",medium:"high",high:"high"},DEEPSEEK_EFFORT_EXTRA={max:"max"},EFFORT_IDENTITY={low:"low",medium:"medium",high:"high"},EFFORT_INERT_RE=/non-reasoning/i,EFFORT_DIALECTS=[{provider:"deepseek",re:DEEPSEEK_REASONING_MODEL_RE,field:"effort",map:DEEPSEEK_EFFORT,extra:DEEPSEEK_EFFORT_EXTRA},{provider:"openai",re:/^(gpt-5|o[0-9])/i,field:"reasoning_effort",map:EFFORT_IDENTITY},{provider:"groq",re:/^(openai\/gpt-oss|qwen\/qwen3)/i,field:"reasoning_effort",map:EFFORT_IDENTITY},{provider:"xai",re:/^grok-(4\.[5-9]|[5-9])/,field:"reasoning_effort",map:EFFORT_IDENTITY},{provider:"google",re:/^gemini-(2\.5|3|[4-9])/,field:"reasoning_effort",map:{...EFFORT_IDENTITY,medium:"high"}}],AUTONOMOUS_IDLE_TIMEOUT_MS=9e5;function reasoningBudget(e,t,o){const r=Number(t);return Number.isFinite(r)&&r>0?r:DEEPSEEK_REASONING_MODEL_RE.test(String(e||""))?EFFORT_TOKEN_BUDGET["low"===o||"medium"===o||"max"===o?o:"high"]:void 0}function nativeEffort(e,t,o){const r=String(t||"");if(EFFORT_INERT_RE.test(r))return;if(null===o)return;const n="low"===o||"medium"===o?o:"max"===o?"max":"high";for(const t of EFFORT_DIALECTS)if(t.provider===e&&t.re.test(r)){const e=Object.prototype.hasOwnProperty.call(t.map,n)?t.map[n]:t.extra&&Object.prototype.hasOwnProperty.call(t.extra,n)?t.extra[n]:void 0;if(void 0===e)return;return{field:t.field,level:e}}}function normalizeCatalog(e){return Array.isArray(e)?e.map(e=>"string"==typeof e?{id:e}:e).filter(e=>e&&e.id):[]}const{offerableCatalog:offerableCatalog}=requireSharedBrain(),{withByokAdditions:withByokAdditions,canonicalModelId:canonicalModelId,nexusFallbackModel:nexusFallbackModel}=requireSharedByokCatalog(),{withUserModels:withUserModels,unmatchedUserProviders:unmatchedUserProviders,load:loadUserModels,addUserModel:addUserModel,removeUserModel:removeUserModel}=requireSharedUserModels(),{withCatalog:withCatalog}=requireSharedCatalogClient(),{discoverModels:discoverVendorModels,canDiscover:canDiscoverVendorModels,endpointFor:vendorEndpointFor,discoverableProviders:discoverableProviders}=requireSharedModelDiscovery(),modelSync=requireSharedModelSync(),{createModelAutoSync:createModelAutoSync}=requireSharedModelAutoSync();function parseArgs(e){if(null==e)return{};if("object"==typeof e)return e;try{const t=JSON.parse(String(e));return t&&"object"==typeof t?t:{}}catch{return{}}}function extractToolCalls(e){if(!e)return[];if(Array.isArray(e.toolCalls)&&e.toolCalls.length)return e.toolCalls.map(e=>({id:e.id||"",name:e.name||"",args:parseArgs(e.args)})).filter(e=>e.name);const t=e.choices&&e.choices[0]&&e.choices[0].message,o=t&&t.tool_calls||[];return Array.isArray(o)?o.map(e=>{const t=e&&e.function||{};return{id:e&&e.id||"",name:t.name||e&&e.name||"",args:parseArgs(t.arguments)}}).filter(e=>e.name):[]}function proTurnPrompt(e){const t=Array.isArray(e.prompt)?flattenContent(e.prompt):e.prompt;if("string"==typeof t&&t.trim())return t;const o=Array.isArray(e.messages)?e.messages:[];for(let e=o.length-1;e>=0;e-=1){const t=o[e];if(!t||"user"!==t.role)continue;const r=flattenContent(t.content);if(r.trim())return r}return t}function assistantText(e){const t=e&&e.choices&&e.choices[0]&&e.choices[0].message;return t&&"string"==typeof t.content&&t.content||""}function finishReasonOf(e){const t=e&&e.choices&&e.choices[0];return t&&t.finish_reason||e&&e.stop_reason||""}function isTruncated(e){const t=finishReasonOf(e);return"length"===t||"max_tokens"===t}function reasoningTextOf(e){if(!e)return"";const t=e.choices&&e.choices[0],o=t&&t.message||{};if(Array.isArray(o.content)){const e=o.content.filter(e=>e&&("thinking"===e.type||"reasoning"===e.type)).map(e=>e.thinking||e.text||"").join("");if(e)return e}const r=o.content&&"object"==typeof o.content?o.content.reasoning_content:"",n=[o.reasoning_content,o.reasoning,t&&t.reasoning_content,e.reasoning_content,e.reasoning,r];for(const e of n)if("string"==typeof e&&e)return e;return""}function reasoningTokensOf(e){if(!e)return 0;const t=e.choices&&e.choices[0],o=t&&t.message||{},r=e.usage||{},n=r.completion_tokens_details||r.output_tokens_details||{},s=[o.thinking_tokens,o.reasoning_tokens,t&&t.thinking_tokens,e.thinking_tokens,n.reasoning_tokens,n.thinking_tokens];for(const e of s)if("number"==typeof e&&Number.isFinite(e)&&e>0)return e;return 0}function reasonedButSilent(e){return!assistantText(e)&&(""!==reasoningTextOf(e)||reasoningTokensOf(e)>0)}const REASONING_RETRY_FLOOR=32768;function retryBudgetFor(e,t){const o=doubledBudget(e.maxTokens);return t&&ladderRung(e.maxTokens)?Math.max(o,32768):o}function ladderRung(e){const t=Number(e);return Number.isFinite(t)&&Object.values(EFFORT_TOKEN_BUDGET).includes(t)}function doubledBudget(e){const t=Number(e)||0;return t>0?2*t:8192}function statedCapOf(e){const t=e=>{const t=Number(e);return Number.isFinite(t)&&t>0?t:void 0};return e&&Object.prototype.hasOwnProperty.call(e,"statedMaxTokens")?t(e.statedMaxTokens):t(e&&e.maxTokens)}const EMPTY_TURN_NUDGE="Your previous reply came back empty — it contained no answer and no tool call. Write your answer now, using only the information already gathered above. No tools are available in this reply, so do not call any: respond in plain prose or markdown.",THOUGHT_ONLY_NUDGE="Your previous round was spent entirely on hidden reasoning and produced no visible reply. Answer the user directly and briefly now. Do not reason, explain, or think first — write only the answer, no tools.",FINAL_ANSWER_NUDGE="Write your answer now, in plain prose, using only what is already in this conversation. If your information is incomplete, say what you have and what is missing — an incomplete answer is the expected outcome here and is better than none. No tools, no preface.",RECOVERY_ROUNDS=2,UNMUTATED_TURN_NUDGE="You ended the turn without changing any file, but this request asked for a change. The tools are still available in this reply: make the edit now with editFile or writeFile. If you already know what to change, change it — describing the fix is not the fix. If you genuinely cannot, say precisely what blocks you.",MUTATION_INTENT_RE=new RegExp("\\b(?:fix|implement|add|create|write|refactor|rename|remove|delete|replace|update|patch|migrate|convert|make\\s+(?:it|them|this|that|the|sure)|change|correct|resolve|repair|address|apply|introduce|support|wire\\s+up)\\b","i");function wantsMutation(e,t,o){if(t)return!1;if(!(o>0))return!1;const r=String(e||"");return!!r.trim()&&!/\?\s*$/.test(r.trim())&&MUTATION_INTENT_RE.test(r)}function emptyTurnError({cls:e,model:t,finishReason:o,reasoningChars:r,reasoningTokens:n,effort:s,recoveryRounds:a}){const i=Number(a)||0,l=Number(n)||0,c=new Error(`The model returned no answer after ${e}/${t} was asked to summarise its results`+(i?`, and ${i} extra recovery call${1===i?"":"s"} with a larger budget and a changed ask came back empty too`:"")+` (stop reason: ${o||"none"}`+(s?`, effort: ${s}`:"")+(r?`, hidden reasoning: ${r} chars and no visible text`:l>0?`, ~${l} thinking tokens billed and no visible text`:"")+"). "+(r||l>0?"Every one of those calls spent its output on hidden reasoning instead of writing a word, so this is the model rather than the budget: pick a model that answers without a thinking pass, or ask for a smaller piece of work.":"No visible text came back from any of those calls. Send the request again, in smaller pieces, or from a different model."));return c.status=502,c}function createLocalEngine({aegis:e,settings:t,tools:o,promptBuilder:r,recallProvider:n,env:s,getConfirmMode:a,getPermissionMode:i,sandbox:l,localTransport:c=localTransport,fetchImpl:d,gitScope:u,permissionRules:f}){const p=new Map,m=o||toolsModule,h=r&&r.buildSystemPrompt||promptModule.buildSystemPrompt,y=f&&"function"==typeof f.rulesVerdict?f.rulesVerdict:null,g=f&&"function"==typeof f.alwaysAllow?f.alwaysAllow:null,k=f&&"function"==typeof f.subjectFor?f.subjectFor:null,v=require("./session-rounds.js"),b=()=>{if("function"==typeof a)return!1!==a();if(t&&"function"==typeof t.getConfirmMode){const e=t.getConfirmMode();return void 0===e||Boolean(e)}return!0},w=()=>"function"==typeof i?"plan"===i():!(!t||"function"!=typeof t.getPermissionMode)&&"plan"===t.getPermissionMode();function S(e,t){return`${e} was not executed — this session is in plan mode (read-only). Plan mode may read files, search, run read-only shell commands and deploy subagents to research, but may not create, edit or delete files, run a mutating command, or install packages`+(t?` (this command: ${t})`:"")+". Do NOT retry it or attempt the same effect by another route. Finish your research and present a plan in plain text; the user exits plan mode (`/permissions mode off`) before any edit can run."}const E=new Map,_=new Map,T=new Map,x=new Map,A=require("./pro-sessions.js"),M=new Map,N=new Map;function O(e,t){if("function"!=typeof k)return e;let o="";try{o=String(k(e,t||{})||"")}catch{o=""}return`${e}\0${o}`}function F(e,t,o){E.has(e)||E.set(e,new Set),E.get(e).add(O(t,o))}function D(e,t){const o=_.get(e);return Boolean(o&&o.has(t))}function R(e,t){_.has(e)||_.set(e,new Set),_.get(e).add(t)}function U(e){if(!e)return null;try{return{existed:!0,content:fs.readFileSync(e,"utf8")}}catch(e){return e&&"ENOENT"===e.code?{existed:!1,content:null}:null}}function I(e){return`${e} was not executed — the user denied this tool for this conversation. Do NOT retry it and do NOT attempt the same effect by another route (another command, a writeFile instead of an edit, a subagent). Stop calling tools and reply in plain text: say what you were trying to do, what you need, and that the user can re-enable ${e} to let it proceed.`}function L(e,t,o,r){return new Promise(n=>{if(o&&o.aborted)return void n("cancel");const s=randomUUID();let a=!1;const i=()=>l("cancel"),l=e=>{a||(a=!0,M.delete(s),o&&o.removeEventListener("abort",i),n(e))};o&&o.addEventListener("abort",i,{once:!0}),M.set(s,{resolve:l}),"function"==typeof t?t({delta:"",approval:{id:s,sessionId:e,tool:r.tool,args:r.args,diff:r.diff||null,canPersist:"function"==typeof g}}):l("cancel")})}function P(e,t,o,r){return new Promise(n=>{if(o&&o.aborted)return void n(!1);const s=randomUUID();let a=!1;const i=()=>l(!1),l=e=>{a||(a=!0,N.delete(s),o&&o.removeEventListener("abort",i),n(e))};o&&o.addEventListener("abort",i,{once:!0}),N.set(s,{resolve:l}),"function"==typeof t?t({delta:"",rounds:{id:s,sessionId:e,spent:r.spent,extensions:r.extensions,max:r.max,size:r.size}}):l(!1)})}async function C(e,t,o,r,n){const s=normalizeToolArgs(m,e,t,o||{});if(!s.ok)return{ok:!1,error:s.error};t=s.args;const a=o&&o.guard;if(a&&"exec"===e){const e=blocksDestructive(a,t&&t.command);if(!e.ok)return{ok:!1,error:e.reason}}const i=o&&o.repeat,l=i?repeatGuard.check(i,e,t):null;if(l&&"refuse"===l.action)return{ok:!1,error:l.error};const c=covenant.preActionAssert({tool:e,args:t||{}});if(!c.allowed){const o=covenant.bindRefusal({tool:e,args:t||{}},c);return{ok:!1,error:`refused by the ÆGIS covenant — ${c.clause} (${c.label}): ${c.reason}`,covenant:o}}const d="writeFile"===e||"editFile"===e,u=d?U(t&&t.file_path):null,f=await m.executeTool(e,t,o);a&&d&&f&&!1!==f.ok&&recordWrite(a,t&&t.file_path),i&&d&&f&&!1!==f.ok&&repeatGuard.recordWrite(i,t&&t.file_path);const p=o&&o.verify;if(p&&(verifyGuard.EXEC_TOOLS.has(e)&&f&&!1!==f.ok?verifyGuard.recordExec(p):d&&f&&!1!==f.ok&&verifyGuard.recordMutation(p,t&&t.file_path)),d&&u&&f&&!1!==f.ok){const o=U(t&&t.file_path);o&&function(e,t){if(!e)return;T.has(e)||T.set(e,[]);const o=T.get(e);o.push(t),o.length>200&&o.shift()}(r,{id:n||randomUUID(),tool:e,path:t&&t.file_path,before:u,after:o,at:Date.now()})}return l&&l.note?$(f,l.note):f}function $(e,t){if(!e||"object"!=typeof e)return{ok:!0,content:`${t}\n${null==e?"":e}`};if(!1===e.ok||!0===e.isError){const o=e.error||e.content||"";return{...e,error:`${t}\n${o}`,content:`${t}\n${o}`}}const o=null!=e.content?e.content:null!=e.output?e.output:"";return{...e,content:`${t}\n${o}`}}async function q(e,{toolCtx:t,rootSessionId:o,rootOnDelta:r,signal:n}){const{name:s}=e,a=normalizeToolArgs(m,s,e.args,t||{});if(!a.ok)return{ok:!1,error:a.error};const i=a.args;if(!m.MUTATING_TOOLS.has(s))return C(s,i,t,o,e.id);if(w()){if("exec"===s){const r=planExec(i&&i.command,{baseCwd:t&&t.cwd||void 0});return r.oneShot?C(s,i,t,o,e.id):{ok:!1,error:S(s,r.reason)}}return{ok:!1,error:S(s)}}if(!b())return C(s,i,t,o,e.id);if(function(e,t,o){const r=E.get(e);return Boolean(r&&r.has(O(t,o)))}(o,s,i))return C(s,i,t,o,e.id);if("function"==typeof y){let r;try{r=y(s,i)}catch(e){r={verdict:null,source:"error",error:e&&e.message||String(e)}}if(r&&"deny"===r.verdict)return R(o,s),{ok:!1,error:I(s),permissionRule:r.rule||null};if(r&&"allow"===r.verdict)return C(s,i,t,o,e.id)}if(D(o,s))return{ok:!1,error:I(s)};let l=null;if(("writeFile"===s||"editFile"===s)&&(l=m.previewMutation(s,i,t||{}),!l.ok))return{ok:!1,error:l.error};const c=await L(o,r,n,{tool:s,args:i,diff:l&&l.diff});if("deny"===c)return R(o,s),{ok:!1,error:I(s)};if("session"!==c&&"once"!==c&&"always"!==c)return{ok:!1,error:`${s} was not executed — the request was cancelled.`};let d=null;if("always"===c){let e=null;if("function"==typeof g)try{e=g(s,i)}catch(t){e={ok:!1,reason:t&&t.message||String(t)}}else e={ok:!1,reason:"no durable store is wired on this host"};d=e&&e.ok?`[permission_rule] stored ${e.rule} — this command will not ask again`:`[permission_rule] nothing was stored — ${e&&e.reason||"unknown reason"}; this call was allowed once only`}if("session"===c&&F(o,s,i),l){const e=m.applyChecked(s,i,l,t||{});return e&&!1!==e.ok&&t&&t.guard&&recordWrite(t.guard,i&&i.file_path),d?$(e,d):e}const u=await C(s,i,t,o,e.id);return d?$(u,d):u}function j(e){return hostEnv(s||{},e&&e.env||{},e)}function B(e){const t=[],o=e=>String(e||"").replace(/[\\/]+$/,""),r=o(e),n=e=>{const n=o(e);n&&n!==r&&!t.includes(n)&&t.push(n)};let s=u;if(void 0===s)try{s=require("./git-scope.js")}catch{s=null}try{s&&"function"==typeof s.gitRoot&&n(s.gitRoot(e))}catch{}try{credentialsLib&&"function"==typeof credentialsLib.aegisHome&&n(credentialsLib.aegisHome())}catch{}return t}async function G(t,o){if("aegis"===t){const t=!o.singlePass&&(!!o.autonomous||void 0);return e.chatCompletion({prompt:o.prompt,system:o.system,messages:o.messages,model:o.model,mode:o.mode,maxTokens:o.statedMaxTokens,stream:!1!==o.stream,includeUsage:!0,onStream:o.onDelta,onReasoning:o.onReasoning,idleTimeoutMs:o.idleTimeoutMs,signal:o.signal,extra:{aegis_recall:!0,...o.recallDeep?{aegis_recall_deep:!0}:{},session:o.sessionId,...void 0===t?{}:{brain:t},...!1===t?{mode:"brain"}:{},...o.effort?{effort:o.effort}:{},...!0===t&&o.workers?{workers:o.workers}:{},...o.tools.length?{tools:o.tools}:{},...o.toolChoice?{tool_choice:o.toolChoice}:{}},agentKey:o.tools.length&&(process.env.AEGIS_AGENT_KEY||"").trim()||void 0})}if("byok"===t){const{provider:t,model:r}=splitByokModel(o.model),n=canonicalModelId(t,r),s=nativeEffort(t,n,o.effort);try{return await e.byokChatCompletion({provider:t,model:n,providerKey:o.apiKey,baseURL:o.cfg&&o.cfg.baseURL,prompt:o.prompt,system:o.system,messages:o.messages,maxTokens:o.maxTokens,tools:o.tools,toolChoice:o.toolChoice,effort:s&&"effort"===s.field?s.level:void 0,reasoningEffort:s&&"reasoning_effort"===s.field?s.level:void 0,stream:!0,onStream:o.onDelta,signal:o.signal})}catch(e){if(e&&402===e.status){const e=new Error("byok: this account has no AEGIS balance left, and the BYOK handling fee is billed there — your provider key is still valid, this is not a key problem. Top up the account, then try again (or /class aegis to use the pooled lane).");throw e.status=402,e}throw e}}if("local"===t){const e=o.cfg&&o.cfg.baseURL||c.DEFAULT_BASE,t={...Number.isFinite(o.budgetSecs)?{budgetSecs:o.budgetSecs}:{},...Number.isFinite(o.tokPerSec)?{tokPerSec:o.tokPerSec}:{}},r=r=>c.chat({baseURL:e,model:o.model,prompt:o.prompt,system:o.system,messages:o.messages,maxTokens:o.maxTokens,signal:o.signal,onDelta:o.onDelta,...t,...r&&o.tools.length?{tools:o.tools,toolChoice:o.toolChoice}:{}});try{return await r(!0)}catch(e){if(o.tools.length&&e&&400===e.status)return r(!1);throw e}}if("pro"===t){const e=o.sessionKey||o.rootSessionId||o.sessionId;let t=null;if(e&&(t=x.get(e)||null,!t)){try{t=A.get(e,s)||null}catch{}t&&x.set(e,t)}const r=B(o.cwd),n=e=>claudePro.runClaudePro({prompt:proTurnPrompt(o),model:o.model&&"default"!==o.model?o.model:void 0,system:o.system,cwd:o.cwd,addDir:r,resumeSessionId:e||void 0,gate:b(),onAsk:async e=>{if(!e||!e.requestId)return"deny";const t=o.rootSessionId,r=o.rootOnDelta,n=PRO_TOOL_MAP[String(e.toolName||"")]||null,s=n||String(e.toolName||"unknown"),a=proAskArgs(e.input||{},s),i=covenant.preActionAssert({tool:s,args:a});if(!i.allowed)return r&&r({delta:"",note:`aegis: refused by the ÆGIS covenant — ${i.clause} (${i.label}): ${i.reason}`}),"deny";if(w()){if("exec"===s){const e=planExec(a&&a.command,{baseCwd:o.cwd||void 0});return e.oneShot?"once":(r&&r({delta:"",note:S(s,e.reason)}),"deny")}if(n&&m.MUTATING_TOOLS.has(s))return r&&r({delta:"",note:S(s)}),"deny";if(!n&&!PRO_PLAN_MODE_SAFE.has(s))return r&&r({delta:"",note:S(s)}),"deny"}if(!b())return"once";if("function"==typeof y){let e;try{e=y(s,a)}catch{e=null}if(e&&"deny"===e.verdict)return r&&r({delta:"",note:I(s)}),"deny";if(e&&"allow"===e.verdict)return"once"}if(D(t,s))return r&&r({delta:"",note:I(s)}),"deny";const l=await L(t,r,o.signal,{tool:s,args:a,diff:null});if("deny"===l)return R(t,s),"deny";if("session"!==l&&"once"!==l&&"always"!==l)return"deny";if("session"===l&&F(t,s,a),"always"===l&&"function"==typeof g)try{g(s,a)}catch{}return l},signal:o.signal,onDelta:o.onDelta,onSpawn:(e,t)=>{o.onDelta&&t&&o.onDelta({delta:"",note:claudePro.childLine(t)})}});let a=await n(t);if(a&&a.resumeStale){x.delete(e);try{A.del(e,s)}catch{}o.onDelta&&o.onDelta({delta:"",note:"aegis: the remembered Claude session no longer exists on this machine — continuing as a new conversation (earlier turns are not in its context)"}),a=await n(null)}if(e&&a&&a.sessionId&&!a.error){x.set(e,a.sessionId);try{A.set(e,a.sessionId,s)}catch{}}return a}throw new Error(`dispatch: unknown model class ${JSON.stringify(t)} — this build ships 'aegis', 'byok', 'local' and 'pro' only`)}async function K(o,r){const s=o&&o.class,a=o&&o.model,i=reasoningBudget("byok"===s?splitByokModel(a).model:a,o&&o.maxTokens,o&&o.effort),d=statedCapOf(o),u="aegis"===s&&Boolean(o&&o.autonomous),f=Boolean(o&&o.roundsAsk),y=o&&o.sessionId||randomUUID(),g=Number.isInteger(o&&o.depth)?o.depth:0,k=o&&o.rootSessionId||y,b=o&&o.rootOnDelta||r,w="function"==typeof r?e=>e&&r({reasoning:e}):void 0,S=new AbortController,E=p.get(y)||null;p.set(y,S);const _=S.signal,T=!(o&&!1===o.tools),x="local"!==s&&g<4,A=T?m.toolsFor({includeSubagent:x}):[],M=o&&o.toolChoice||null,N={...j(o),toolSchemas:A},O=o&&o.system||h(N),F=n?await n({payload:o,env:N,system:O}):null,D="string"==typeof F?F:F&&"string"==typeof F.system?F.system:O,R=Array.isArray(o&&o.messages)?o.messages.filter(Boolean).slice():[];let U=R.length,I=o&&o.prompt||"";const L=String(I||""),C=Array.isArray(o&&o.attachments)?o.attachments.filter(e=>e&&"object"==typeof e).slice(0,attachmentsModule.MAX_ATTACHMENTS):[];let $=C.length?attachmentsModule.buildContent(I,C):I,K=null;const W=j(o),z=((e,t)=>{if(null==l)return null;const o="function"==typeof l.policy?l.policy():l.policy;if(!o)return null;const r=require("./sandbox.js"),n=e&&e.cwd||process.cwd(),s=r.normalize(o,n);if("off"===s.mode)return null;let a=[];try{let e=null;try{e=require("node:os").homedir()}catch{e=null}a=r.autoGrants(n,{home:e,addDirs:(()=>{try{return B(n)}catch{return[]}})()})}catch{a=[]}if(a.length){const e=new Set;for(const t of s.fileSystem.entries)t&&t.path&&"path"===t.path.type&&t.path.path&&e.add(`${t.access}:${t.path.path}`);for(const t of a){const o=`${t.access}:${t.path.path}`;e.has(o)||(e.add(o),s.fileSystem.entries.push(t))}}return"local"===t&&"restricted"===s.network&&(s.network="open",s.networkExempt="local"),{policy:s,state:l.state||r.detect({appDir:l.appDir}),workspace:n,appDir:l.appDir,strict:!0===l.strict}})(W,s),V=W.cwd,H={getShell:()=>K||(K=new ShellSession({cwd:W.cwd,sandbox:z})),signal:_,cwd:V,desktopdir:W.desktopdir,sandbox:z,repeat:repeatGuard.beginRepeatGuard({cwd:V}),verify:verifyGuard.beginVerifyGuard({cwd:V}),guard:beginTurnGuard(V)};try{const n="byok"===s?splitByokModel(a):null;let l=null;const p="byok"===s?t.get(byokNamespace(n.provider))||{}:"local"===s&&t.get("local")||{},h="byok"===s?t.rawKey(byokNamespace(n.provider)):null,S="byok"!==s?null:h||providerKeyFromEnv(n.provider);if(!("byok"!==s||n.provider&&n.model)){const e=new Error('byok: model must be "<provider>:<model>" (pick one from /models) — got '+JSON.stringify(a||""));throw e.status=400,e}if("byok"===s&&!S){const t="anthropic"===n.provider?claudePro.claudeProStatus({env:process.env}):null,o=providerKeyRecord(n.provider).rejected,r=nexusFallbackModel({provider:n.provider,providerKey:S,providerKeyRefused:o,aegisKey:S?"":e.apiKey});if(!r){const e=new Error(o?`${o}. That is why this turn has no ${n.provider} key: an env value that short is a paste that lost its payload, not a credential. Fix ${o.split(" ")[0]} in ~/.aegiscode/.env (or the shell that exported it) — or skip keys entirely: /byok-key ${n.provider} <key> to set one here.`:t&&t.loggedIn?`No Anthropic API key on this machine — an "anthropic:…" id is served by your own console key, which a Claude subscription is not. Use the subscription instead: /class pro (it spends your Claude Code ${t.subscription||"Pro"} plan through the claude CLI) — or add a real console key: /byok-key anthropic <key>.`:`No key for "${n.provider}" yet. Easiest fix: /class aegis (uses your AEGIS key, no setup) — or add this provider's own key: /byok-key ${n.provider} <key>.`);throw e.status=400,e}l={from:n.provider,model:r}}if("byok"===s&&!e.apiKey){const e=new Error("No AEGIS key connected yet. Easiest fix: /class aegis (skips BYOK entirely) — or add your AEGIS key with /login, then try again.");throw e.status=401,e}if("local"===s){const e=c.remoteRefusal(p.baseURL||c.DEFAULT_BASE);if(e)throw e}if("byok"===s&&"custom"===n.provider&&!(p.baseURL||"").trim()){const e=new Error('No endpoint saved for the "custom" provider — its key is on this machine but the address it dials is not, and no default exists for a vendor AEGIS does not know. Fix: /model-add custom <https-base-url> <api-key> <model-id> (writes both halves), or the endpoint field in Settings › Provider (custom).');throw e.status=400,e.code="custom_endpoint_missing",e}const E=l?"aegis":s,x={cls:E,model:l?l.model:a,mode:o&&o.mode,maxTokens:i,statedMaxTokens:d,autonomous:u,sessionId:y,signal:_,onDelta:r,cfg:p,apiKey:S,toolChoice:M,pooledFrom:l?l.from:void 0,cwd:V,rootSessionId:k,sessionKey:o&&o.sessionKey||void 0,rootOnDelta:b,effort:o&&o.effort,workers:o&&o.workers,...Number.isFinite(o&&o.budgetSecs)?{budgetSecs:o.budgetSecs}:{},...Number.isFinite(o&&o.tokPerSec)?{tokPerSec:o.tokPerSec}:{},recallDeep:o&&!0===o.recallDeep,singlePass:o&&!0===o.singlePass,onReasoning:w,idleTimeoutMs:u?9e5:void 0,stream:!o||!1!==o.stream};let N=!1,O=!1;const F=u?"AEGIS_AUTONOMOUS_MAX_ROUNDS":"AEGIS_CHAT_MAX_ROUNDS",j=(()=>{const e=Number.parseInt(process.env[F]||"",10);return Number.isFinite(e)&&e>0?e:0})(),B=j||(u?40:24);let K=v.keyFor(o,R),W=v.take(K);if(!W&&!v.isStatedKey(o)){const e=v.adopt();e&&(W=e.entry,K=e.key)}if(W){const e=v.resumePreamble(W);0===R.length?Array.isArray(W.messages)&&W.messages.length&&R.push(...W.messages):Array.isArray(W.added)&&W.added.length&&R.push(...W.added),I?(I=`${e}\n\n${I}`,$=C.length?attachmentsModule.buildContent(I,C):I):(R.push({role:"user",content:e}),$=""),b&&b({delta:`\n\n[resuming work this session left unfinished at ${W.rounds} tool rounds`+(W.interruptions>1?` (cut off ${W.interruptions}×)`:"")+"…]\n"})}let z=j||B+(W?v.bonus(B):0),X=0;const J=B,Q=8;let Z=0;const ee={calls:0},te=["input_tokens","output_tokens","prompt_tokens","completion_tokens","total_tokens","cache_read_input_tokens","cache_creation_input_tokens","prompt_cache_hit_tokens","prompt_cache_miss_tokens","reasoning_tokens","thinking_tokens"],oe=e=>{const t=e&&e.usage;if(t&&"object"==typeof t){ee.calls+=1;for(const e of te)"number"==typeof t[e]&&Number.isFinite(t[e])&&(ee[e]=(ee[e]||0)+t[e]);if("number"!=typeof t.total_tokens){const e=(t.prompt_tokens??t.input_tokens??0)+(t.completion_tokens??t.output_tokens??0);e&&(ee.total_tokens=(ee.total_tokens||0)+e)}}},re=e=>{if(!e||"object"!=typeof e)return e;const t=l?{...e,pooled_from:l.from,pooled_model:l.model,pooled_notice:requireSharedByokCatalog().nexusFallbackNotice({pooled_from:l.from,pooled_model:l.model})}:e;return ee.calls?{...t,usage:{...ee}}:t},ne=()=>{if(""===$)return;const e=R[R.length-1],t=e&&"user"===e.role?flattenContent(e.content):null;e&&"user"===e.role&&t===flattenContent($)||R.push({role:"user",content:$}),I="",$=""};U=R.length;const se=m&&m.MUTATING_TOOLS||new Set;let ae=0,ie=0,le=!1,ce=!1;for(;;){if(X>=z){if(f&&Z<Q&&!_.aborted&&await P(k,b,_,{spent:z,extensions:Z+1,max:Q,size:J})){Z+=1;const e=z;z+=J,R.push({role:"user",content:`You have used all ${e} tool rounds allowed for this turn; ${J} more have been granted (do not restart). Continue the task from exactly where you stopped — do not re-plan, do not repeat work already done, and finish with an answer.`});continue}const e=f?"":`, or raise ${F} for a longer single turn`,t=`[stopped at ${z} tool rounds`+(ee.total_tokens?`, ${ee.total_tokens.toLocaleString()} tokens`:"")+". This session holds the work: your next message here resumes it automatically"+` (with a continuation preamble)${e}.]`,o=v.record(K,{rounds:X,tokens:ee.total_tokens||0,note:t,chain:W?W.interruptions:0,messages:R,added:R.slice(U)});return b&&b({delta:`\n\n${t}`}),re({model:x.model,choices:[{message:{content:t},finish_reason:"length"}],stoppedOnRounds:!0,heldForSession:!0,heldRounds:o.rounds,sessionInterruptions:o.interruptions,resumedFrom:K})}X+=1;const e={...x,system:D,messages:R,prompt:$,tools:A,recallDeep:x.recallDeep&&1===X};let t;if(t=await G(E,e),oe(t),_.aborted)return re(t);if(!N&&!assistantText(t)&&(isTruncated(t)||reasonedButSilent(t))){N=!0;const o=reasonedButSilent(t);if(t=await G(E,{...e,singlePass:!0,recallDeep:!1,effort:o?"high":e.effort,maxTokens:retryBudgetFor(e,o),statedMaxTokens:e.statedMaxTokens?doubledBudget(e.statedMaxTokens):void 0}),oe(t),_.aborted)return re(t)}const n=A.length?extractToolCalls(t):[];if(!n.length){if(assistantText(t)||O||!T){if(!le&&T&&wantsMutation(L,ie>0,ae)){le=!0,ne(),R.push({role:"assistant",content:assistantText(t)}),R.push({role:"user",content:UNMUTATED_TURN_NUDGE}),b&&b({delta:""});continue}if(H.verify&&!ce){const e=verifyGuard.shouldNudge(H.verify);if(e.nudge){ce=!0,ne(),R.push({role:"assistant",content:assistantText(t)}),R.push({role:"user",content:e.text}),b&&b({delta:""});continue}}return re(t)}O=!0,ne(),R.push({role:"user",content:reasonedButSilent(t)?THOUGHT_ONLY_NUDGE:EMPTY_TURN_NUDGE});const o={...e,singlePass:!0,recallDeep:!1,messages:R,prompt:"",tools:[]};t=await G(E,o);let r=o.maxTokens,n=o.effort;if(oe(t),_.aborted)return re(t);if(!assistantText(t)&&(isTruncated(t)||reasonedButSilent(t))){const e=reasonedButSilent(t);if(r=retryBudgetFor(o,e),n=e?"high":o.effort,t=await G(E,{...o,effort:n,maxTokens:r,statedMaxTokens:o.statedMaxTokens?doubledBudget(o.statedMaxTokens):void 0}),oe(t),_.aborted)return re(t)}const i=(()=>{const e=Number(r)||0;if(!e)return r;const t={maxTokens:r};return o.statedMaxTokens&&(t.statedMaxTokens=o.statedMaxTokens),Math.max(e,retryBudgetFor(t,!0))})();let l=0;for(;!assistantText(t)&&l<2&&!_.aborted;){const e=reasonedButSilent(t);if(l+=1,R.push({role:"user",content:e?1===l?THOUGHT_ONLY_NUDGE:FINAL_ANSWER_NUDGE:EMPTY_TURN_NUDGE}),e&&(n="high"),r=i,t=await G(E,{...o,messages:R,effort:n,maxTokens:r,statedMaxTokens:o.statedMaxTokens?doubledBudget(o.statedMaxTokens):void 0}),oe(t),_.aborted)return re(t)}if(!assistantText(t))throw emptyTurnError({cls:s,model:a,effort:n,recoveryRounds:l,finishReason:finishReasonOf(t),reasoningChars:reasoningTextOf(t).length,reasoningTokens:reasoningTokensOf(t)});return re(t)}ne(),R.push({role:"assistant",content:assistantText(t),tool_calls:n.map(e=>({id:e.id,type:"function",function:{name:e.name,arguments:JSON.stringify(e.args)}}))});const i=new WeakMap,l=e=>{if("exec"!==e.name)return null;if(i.has(e))return i.get(e);const t=planExec(e.args&&e.args.command,{baseCwd:V});return i.set(e,t),t},c=e=>{if(!se.has(e.name))return!0;const t=l(e);return Boolean(t&&t.oneShot)},u=[];for(const e of n){const t=u[u.length-1];c(e)&&t&&t.parallel?t.calls.push(e):u.push({parallel:c(e),calls:[e]})}const p=async e=>{r&&r({delta:"",tool:{name:e.name,args:e.args,id:e.id,cwd:V,phase:"run"}});const t=l(e),n=t&&t.oneShot?{...H,oneShotExec:!0,cwd:t.cwd||H.cwd}:H,i=e.name===m.SUBAGENT_TOOL?await Y(e.args,{cls:s,model:a,statedMaxTokens:d,effort:o&&o.effort,mode:o&&o.mode,parentSignal:_,depth:g,rootSessionId:k,rootOnDelta:b}):await q(e,{toolCtx:n,rootSessionId:k,rootOnDelta:b,signal:_});return i&&i.usage&&oe({usage:i.usage}),r&&r({delta:"",tool:{name:e.name,args:e.args,ok:i.ok,id:e.id,cwd:V,phase:"done"}}),i};for(const e of u){const t=e.parallel&&e.calls.length>1?await Promise.all(e.calls.map(e=>p(e))):[await p(e.calls[0])];e.calls.forEach((e,o)=>{const r=t[o];se.has(e.name)&&(ae+=1,r&&r.ok&&(ie+=1)),R.push({role:"tool",tool_call_id:e.id,name:e.name,content:m.toolResultText(r)})})}}}catch(e){throw _.aborted&&e&&"object"==typeof e&&(e.aegisCancelled=!0),e}finally{K&&K.dispose(),p.get(y)===S&&(E&&!E.signal.aborted?p.set(y,E):p.delete(y))}}async function Y({description:e,subagent_type:t,prompt:o}={},{cls:r,model:n,statedMaxTokens:s,effort:a,mode:i,parentSignal:l,depth:c,rootSessionId:d,rootOnDelta:u}={}){const f=String(o||e||"").trim();if(!f)return{ok:!1,error:"task requires a prompt"};const p=t&&"general"!==t?agentRoleLabel(t):"general",m=agentSystemPrompt(t),h=randomUUID();let y;if(l){if(l.aborted)return{ok:!1,error:"aborted"};y=()=>W(h),l.addEventListener("abort",y,{once:!0})}try{const e=await K({class:r,model:n,mode:i,system:m,prompt:f,sessionId:h,depth:(c||0)+1,rootSessionId:d,rootOnDelta:u,statedMaxTokens:s,effort:a},()=>{}),t=assistantText(e),o=e&&e.usage?{usage:e.usage}:{};return t?{ok:!0,output:t,...o}:{ok:!1,error:`subagent (${p}) produced no output`,...o}}catch(e){return{ok:!1,error:`subagent (${p}) failed: ${e&&e.message?e.message:e}`}}finally{l&&y&&l.removeEventListener("abort",y)}}function W(e){const t=p.get(e);return t&&t.abort(),{ok:Boolean(t)}}function z(e){const o=String(null==e?"":e).trim().toLowerCase();if(!o)return"";try{if(t&&"function"==typeof t.rawKey){const e=t.rawKey(byokNamespace(o));if("string"==typeof e&&e.trim())return e.trim()}}catch{}return providerKeyFromEnv(o)}async function V(t){let o=[];try{const t=await e.byokProviders();o=withUserModels(withCatalog(withByokAdditions(t&&t.providers||[])))}catch(e){return{ok:!1,providers:[],missing:0,stale:0,skipped:[],failed:[],error:e&&e.message||String(e)}}const r={};for(const e of modelSync.askableProviders(o,t)){const t=z(e);t&&(r[e]=t)}return modelSync.plan(o,{keys:r,fetchImpl:d,only:t})}const H=createModelAutoSync({getPref:()=>{try{return t&&"function"==typeof t.getSharedPref?t.getSharedPref("modelAutoSync"):null}catch{return null}},plan:e=>V(e),apply:(e,t)=>modelSync.apply(e,{only:t})});return{CLASSES:CLASSES,listClasses:async function(){return CLASSES.map(o=>{if("aegis"===o.class)return{...o,configured:Boolean(e.apiKey)};if("byok"===o.class){const e=(t.list()||[]).some(e=>!(!e||"string"!=typeof e.provider||!e.provider.startsWith("byok:"))&&(!!e.configured||Boolean(providerKeyFromEnv(e.provider.slice(5)))));return{...o,configured:e}}if("local"===o.class)return{...o,configured:!0};if("pro"===o.class){const e=claudePro.claudeProStatus({env:process.env}),t=claudePro.seamAvailable();return{...o,configured:e.loggedIn,status:e,seam:t}}return{...o,configured:!1}})},listModels:async function(o){if("aegis"===o){if(!e.apiKey)return{class:o,models:[],needsKey:!0};const t=await e.listModels();return{class:o,models:offerableCatalog(normalizeCatalog(t&&t.models))}}if("byok"===o){let r=[],n=null,s=!1,a=null;try{const t=await e.byokProviders();r=withUserModels(withCatalog(withByokAdditions(t&&t.providers||[]))),n=t&&t.fee||null}catch(e){r=[],s=!0,a=e&&e.message||String(e)}const i=[];for(const e of r){if(!e||!e.id)continue;const o=t.get(byokNamespace(e.id))||{},r=providerKeyRecord(e.id),n=r.key||"",s=Array.isArray(e.models)?e.models:[];for(const t of s){const s="string"==typeof t?t:t&&t.id;s&&i.push({id:`${e.id}:${s}`,label:`${e.label||e.id} — ${s}`,provider:e.id,configured:Boolean(o.configured||n),keyRejected:r.rejected||null})}}return{class:o,models:i,providers:r,needsProviderKey:i.length>0&&!i.some(e=>e.configured),needsAegisKey:!e.apiKey,fee:n,providersFailed:s,providersError:a,unmatchedProviders:unmatchedUserProviders(r)}}if("local"===o){const e=(t.get("local")||{}).baseURL||c.DEFAULT_BASE,r=await c.probe(e);if(!r.running)return{class:o,models:[],baseURL:r.baseURL,needsDaemon:!0};let n=[],s=!0;try{n=await c.listTags(e)}catch{s=!1}return{class:o,models:n,baseURL:r.baseURL,listed:s}}if("pro"===o){const e=claudePro.claudeProStatus({env:process.env});return{class:o,models:claudePro.PRO_MODELS.map(t=>({id:t.id,label:t.label,note:t.note,configured:e.loggedIn})),needsProviderKey:!1,needsAegisKey:!1,subscription:e.subscription,loggedIn:e.loggedIn,credentialFile:e.file,shadowed:e.shadowed||null,seam:claudePro.seamAvailable()}}throw new Error(`listModels: unknown model class ${JSON.stringify(o)} — this build ships 'aegis', 'byok', 'local' and 'pro' only`)},chat:K,cancel:W,respondApproval:function(e,t){const o=M.get(e);return o?(M.delete(e),o.resolve("session"===t||"once"===t||"always"===t?t:"deny"),{ok:!0}):{ok:!1}},respondRoundsAsk:function(e,t){const o=N.get(e);return o?(N.delete(e),o.resolve(!0===t||"continue"===t),{ok:!0}):{ok:!1}},clearSessionApprovals:function(e){E.delete(e),_.delete(e),T.delete(e),x.delete(e);try{A.del(e,s)}catch{}return{ok:!0}},listUndoable:function(e){return(T.get(e)||[]).map(e=>({id:e.id,tool:e.tool,path:e.path,at:e.at})).reverse()},undoMutation:function(e,t){const o=T.get(e)||[],r=t?o.findIndex(e=>e.id===t):o.length-1;if(-1===r)return{ok:!1,error:t?`no undo record "${t}" for this conversation`:"nothing to undo in this conversation"};const n=o[r],s=U(n.path);if(!s||s.existed!==n.after.existed||s.content!==n.after.content)return{ok:!1,error:`${n.path} has changed since ${n.tool} ran — undo refused rather than overwriting work this session did not do. Resolve it by hand, or undo a different entry.`};try{n.before.existed?fs.writeFileSync(n.path,n.before.content,"utf8"):fs.unlinkSync(n.path)}catch(e){return{ok:!1,error:`undo failed: ${e&&e.message||e}`}}return o.splice(r,1),{ok:!0,path:n.path,restored:n.before.existed?"content":"deleted"}},settings:t,unloadLocalModels:function(){return c.unloadAll()},userModels:()=>loadUserModels(),addUserModel:(e,t)=>addUserModel(e,t),removeUserModel:(e,t)=>removeUserModel(e,t),discoverModels:async e=>{const t=String(null==e?"":e).trim().toLowerCase(),o=z(t),r=await discoverVendorModels(t,{key:o,fetchImpl:d});if(!r||!r.ok)return r;const n=[];try{const e=loadUserModels().map;for(const o of Array.isArray(e[t])?e[t]:[])n.push(o)}catch{}return{...r,declared:n,endpoint:(vendorEndpointFor(t)||{}).url||""}},modelSyncPlan:async e=>V(e),modelSyncApply:(e,t)=>modelSync.apply(e,{only:t}),modelAutoSync:H,modelAutoSyncRun:e=>H.runIfDue(e),modelAutoSyncStatus:()=>H.status(),addUserModels:(e,t)=>{const o=Array.isArray(t)?t:[],r={provider:e,added:0,already:[],failed:[],capped:0,file:""};for(const t of o)try{const o=addUserModel(e,t);r.file=o.file||r.file,o.added?r.added+=1:r.already.push(o.model)}catch(e){const n=e&&e.message||String(e);if(/the cap/.test(n)){r.capped=o.length-r.added-r.already.length-r.failed.length;break}r.failed.push({id:String(t),reason:n})}return r},canDiscoverModels:e=>canDiscoverVendorModels(e),discoverableProviders:()=>discoverableProviders()}}module.exports={CLASSES:CLASSES,createLocalEngine:createLocalEngine,extractToolCalls:extractToolCalls,parseArgs:parseArgs,reasoningBudget:reasoningBudget,nativeEffort:nativeEffort,hostEnv:hostEnv};