aegisone 1.0.58 → 1.0.60

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. package/README.md +4 -2
  2. package/bin/aegis.js +1 -1
  3. package/package.json +3 -2
  4. package/scripts/predist.mjs +1 -1
  5. package/src/doctor.js +1 -1
  6. package/vendor/cli/package.json +1 -1
  7. package/vendor/cli/vendor/desktop/lib/local/integrity.js +1 -1
  8. package/vendor/cli/vendor/desktop/main.js +130 -2
  9. package/vendor/cli/vendor/one/src/iface/pty.js +3 -0
  10. package/vendor/cli/vendor/one/src/protocol.js +3 -0
  11. package/vendor/desktop/lib/local/cli-face.js +1 -1
  12. package/vendor/desktop/lib/local/integrity.js +1 -1
  13. package/vendor/desktop/lib/local/pty-host.js +3 -0
  14. package/vendor/desktop/main.js +130 -2
  15. package/vendor/desktop/package.json +4 -3
  16. package/vendor/desktop/preload.js +1 -1
  17. package/vendor/desktop/renderer/app.js +1 -1
  18. package/vendor/desktop/renderer/index.html +3 -0
  19. package/vendor/desktop/renderer/pty-panel.js +3 -0
  20. package/vendor/desktop/renderer/style.css +55 -0
  21. package/vendor/desktop/renderer/vendor/NOTICE.md +10 -2
  22. package/vendor/desktop/renderer/vendor/xterm.css +285 -0
  23. package/vendor/desktop/renderer/vendor/xterm.js +1 -0
  24. package/vendor/desktop/vendor/faces/cli/package.json +1 -1
  25. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/integrity.js +1 -1
  26. package/vendor/desktop/vendor/faces/cli/vendor/desktop/main.js +3 -3
  27. package/vendor/desktop/vendor/faces/cli/vendor/one/src/iface/pty.js +3 -0
  28. package/vendor/desktop/vendor/faces/cli/vendor/one/src/protocol.js +3 -0
  29. package/vendor/desktop/vendor/protocol.js +3 -0
  30. package/vendor/desktop/vendor/pty.js +3 -0
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # AEGISONE
2
2
 
3
- Product version: **1.0.58**
3
+ Product version: **1.0.60**
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.
@@ -60,7 +60,9 @@ fails, and it never leaves you with "nothing happened". Afterwards: `aegis`
60
60
 
61
61
  ## Size, measured not claimed
62
62
 
63
- Measured size: **3.14 MB** (3,289,564 bytes) with Electron absent — both faces inside.
63
+ Measured size: **3.27 MB** (3,426,363 bytes) with Electron absent — both faces inside.
64
+ (ON9 added the embedded terminal panel's `xterm.js`/`xterm.css` to the desktop
65
+ face's renderer, which is the bulk of this jump from the pre-ON9 3.14 MB.)
64
66
 
65
67
  The plan's "~2 MB" was a target, so it is measured here rather than published:
66
68
  `npm pack one/` on this tree, with Electron absent, produces that tarball, and it
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"),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 s=t||{},{stdout:n,stderr:i,input:o}=r,a=void 0!==s.installed?s.installed:isInstalledLayout(s.binDir),c=s.updatePlan?s.updatePlan():productUpdate.plan({installed:a,env:o&&o.env||{}});if(!c.ok)return write(i,`aegis: ${c.msg}`),EXIT_USAGE;const u=s.fetchLatest||defaultFetchLatest(s.binDir);return productUpdate.check({current:PRODUCT.version,action:e.action},{fetchImpl:u}).then((t=>{for(const e of t.lines)write(n,e);if("apply"!==e.action)return!0===t.upToDate?0:1;const r=productUpdate.apply(c,t,{runImpl:s.runInstall||defaultRunInstall});if(r.ok){write(n,r.lines?r.lines[0]:"Installed.");for(const e of String(r.output||"").split("\n").slice(-6))e.trim()&&write(n,` ${e}`);return 0}return r.skipped?(write(n,` ${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,".."),s=[path.join(r,"client","update.js"),path.join(r,"vendor","cli","vendor","client","update.js")];for(const e of s)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 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)}}}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||{},s=r.stderr||process.stderr,n=r.stdout||process.stdout,i=r.input||probes.collect({argv:e}),o=Array.isArray(e)?{...i,argv:e}:i,a=release.versionRequest(o.argv);if(a){const e=a.verbose?r.readFaceVersions?r.readFaceVersions():readFaceVersions(r.binDir):null;return write(n,release.renderVersion({product:{name:PRODUCT.name,version:PRODUCT.version},faces:e})),0}if((r.helpRequest||productHelp.helpRequest)(o.argv))return write(n,productHelp.renderHelp({version:PRODUCT.version})),0;const c=(r.updateRequest||productUpdate.updateRequest)(o.argv);if(c&&"help"===c.action)return write(n,productUpdate.renderUsage(PRODUCT.version)),0;if(c)return runUpdate(c,r,{stdout:n,stderr:s,input:o});const u=(o.argv||[]).indexOf("doctor");if(-1!==u&&!(o.argv||[]).slice(0,u).some((e=>!e.startsWith("-")))){const e=r.doctor||require("../src/doctor.js"),t=Object.assign({env:o.env,stdout:n,electron:o._electron||r.electron||null},r.doctorDeps||{}),s=e.main((o.argv||[]).slice(u+1),t);return"number"==typeof s?s:EXIT_USAGE}const d=decide(o),p=r.permissions||require("../src/permissions.js"),l=(o.argv||[]).indexOf(p.SKIP_FLAG||"--dangerously-skip-permissions"),f=Boolean(o.tty&&o.tty.stdin&&o.tty.stdout),g=f?"interactive":"headless",h=r.stored||p.storedPermissionFacts(r.storedOpts||{}),m=p.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!==l,env:o.env,interactive:f,childKind:g});m.warning&&write(s,`aegis: ${m.warning}`),m.skip&&m.skipFromFlag&&write(s,p.skipReport(m));const w=-1===l?d.args:d.args.filter((e=>e!==(p.SKIP_FLAG||"--dangerously-skip-permissions"))),v=m.skipFromFlag?{AEGISONE_SKIP_PERMISSIONS:"1"}:{},I={AEGIS_INSTALL_METHOD:"npm"};if("1"===(o.env||{}).AEGISONE_PRINT_DECISION&&write(s,"aegis: decision "+JSON.stringify({face:d.face,kind:d.kind,reason:d.reason,args:w,skip:m.skip})),null===d.face)return write(s,`aegis: ${d.error}`),d.hint&&write(s,`aegis: ${d.hint}`),d.code||EXIT_USAGE;d.notice&&write(s,`aegis: ${d.notice} — running the terminal face.`);const S=r.spawnSync||spawnSync,E=r.spawn||spawn,_=Object.assign({},process.env,r.env||{});if(d.face===FACE.TUI){const e=o._cliBin||r.cliBin;return e?statusOf(S(process.execPath,[e,...w],{stdio:"inherit",env:Object.assign({},_,v,I),argv0:"aegiscode"})||{}):(write(s,"aegis: the terminal face is not installed beside aegisone."),write(s,"aegis: reinstall aegisone, or set AEGISONE_CLI_BIN to bin/aegiscode.js."),127)}const k=o._electron||r.electron,y=o._desktopMain||r.desktopMain,O=WIN.plan({decision:d,electron:Boolean(k),target:r.target||o.target});if(!O||!y)return write(s,"aegis: cannot open the window — Electron or the desktop entry point went missing after the check."),write(s,"aegis: Use --tui for the terminal face."),EXIT_USAGE;delete _.ELECTRON_RUN_AS_NODE;const U=WIN.open(O,{main:y,args:w,env:Object.assign({},_,v,I)},{openElectron:e=>E(process.execPath,[e.main,...e.args],{stdio:"inherit",env:e.env,detached:!1})});if(!U||!U.ok)return write(s,`aegis: cannot open the window — ${U&&U.msg||"no usable window plan"}.`),write(s,"aegis: Use --tui for the terminal face."),EXIT_USAGE;const j=U.handle;return new Promise((e=>{j.on("error",(t=>{write(s,`aegis: could not start the window: ${t&&t.message}`),e(1)})),j.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:EXIT_USAGE,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"),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}`),EXIT_USAGE;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.input||probes.collect({argv:e}),o=Array.isArray(e)?{...i,argv:e}:i,a=release.versionRequest(o.argv);if(a){const e=a.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)(o.argv))return write(s,productHelp.renderHelp({version:PRODUCT.version})),0;const c=(r.updateRequest||productUpdate.updateRequest)(o.argv);if(c&&"help"===c.action)return write(s,productUpdate.renderUsage(PRODUCT.version)),0;if(c)return runUpdate(c,r,{stdout:s,stderr:n,input:o});const d=(o.argv||[]).indexOf("doctor");if(-1!==d&&!(o.argv||[]).slice(0,d).some((e=>!e.startsWith("-")))){const e=r.doctor||require("../src/doctor.js"),t=Object.assign({env:o.env,stdout:s,electron:o._electron||r.electron||null},r.doctorDeps||{}),n=e.main((o.argv||[]).slice(d+1),t);return"number"==typeof n?n:EXIT_USAGE}const u=decide(o),p=r.permissions||require("../src/permissions.js"),l=(o.argv||[]).indexOf(p.SKIP_FLAG||"--dangerously-skip-permissions"),f=Boolean(o.tty&&o.tty.stdin&&o.tty.stdout),g=f?"interactive":"headless",m=r.stored||p.storedPermissionFacts(r.storedOpts||{}),h=p.resolvePosture({rules:void 0!==r.rules?r.rules:m.rules,gate:void 0!==r.gate?r.gate:m.confirmationsOn,permissionMode:void 0!==r.permissionMode?r.permissionMode:m.permissionMode,flag:-1!==l,env:o.env,interactive:f,childKind:g});h.warning&&write(n,`aegis: ${h.warning}`),h.skip&&h.skipFromFlag&&write(n,p.skipReport(h));const w=-1===l?u.args:u.args.filter((e=>e!==(p.SKIP_FLAG||"--dangerously-skip-permissions"))),v=h.skipFromFlag?{AEGISONE_SKIP_PERMISSIONS:"1"}:{},S={AEGIS_INSTALL_METHOD:"npm"};if("1"===(o.env||{}).AEGISONE_PRINT_DECISION&&write(n,"aegis: decision "+JSON.stringify({face:u.face,kind:u.kind,reason:u.reason,args:w,skip:h.skip})),null===u.face)return write(n,`aegis: ${u.error}`),u.hint&&write(n,`aegis: ${u.hint}`),u.code||EXIT_USAGE;u.notice&&write(n,`aegis: ${u.notice} — running the terminal face.`);const I=r.spawnSync||spawnSync,E=r.spawn||spawn,_=Object.assign({},process.env,r.env||{});if(u.face===FACE.TUI){const e=o._cliBin||r.cliBin;return e?statusOf(I(process.execPath,[e,...w],{stdio:"inherit",env:Object.assign({},_,v,S),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 O=o._electron||r.electron,y=o._desktopMain||r.desktopMain,k=WIN.plan({decision:u,electron:Boolean(O),target:r.target||o.target});if(!k||!y)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."),EXIT_USAGE;delete _.ELECTRON_RUN_AS_NODE;const R=WIN.open(k,{main:y,args:w,env:Object.assign({},_,v,S)},{openElectron:e=>{const t=E(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(!R||!R.ok)return write(n,`aegis: cannot open the window — ${R&&R.msg||"no usable window plan"}.`),write(n,"aegis: Use --tui for the terminal face."),EXIT_USAGE;const U=R.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:EXIT_USAGE,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.58",
4
+ "version": "1.0.60",
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",
@@ -34,7 +34,8 @@
34
34
  "size": "node scripts/bundle.mjs --json"
35
35
  },
36
36
  "optionalDependencies": {
37
- "electron": "^44.0.0"
37
+ "electron": "^44.0.0",
38
+ "node-pty": "^1.1.0"
38
39
  },
39
40
  "keywords": [
40
41
  "aegis",
@@ -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"}];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=12e4,u=6e5,m=50,f="AEGISONE_PREDIST_LOCK_TOKEN";let g=null,j=!1,y=0;function b(e){try{return process.kill(e,0),!0}catch(e){return Boolean(e)&&"EPERM"===e.code}}const w=e=>new Promise((s=>setTimeout(s,e)));function v(){if(y>0)return void y--;const s=g,r=j,t=process.env[f];if(g=null,j=!1,s&&r){t&&delete process.env[f];try{e.unlinkSync(s)}catch{}}}export async function acquireStageLock(r){if(g)return y++,v;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()+p,n=process.env[f]||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 g=t,void(j=!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),g=t,j=!0,void(process.env[f]=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>u||Number.isFinite(c)&&c>0&&!b(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(p/1e3)}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 w(m+Math.floor(Math.random()*m))}}}((e=>t.write(`${e}\n`))),v}function k(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(E(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 E(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}}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=k(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:k(entriesFor("nested"),null).length}),t("flat")){const e=k(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=JSON.stringify(f.after||"");if(f.error||!f.changed||!g.includes(JSON.stringify(c).slice(1,-1)))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=e.readFileSync(o.dest,"utf8").replace(/\/\*[\s\S]*?\*\//g,"").replace(/(^|[^:])\/\/.*$/gm,"$1");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/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=12e4,u=6e5,m=50,f="AEGISONE_PREDIST_LOCK_TOKEN";let g=null,j=!1,y=0;function b(e){try{return process.kill(e,0),!0}catch(e){return Boolean(e)&&"EPERM"===e.code}}const w=e=>new Promise((s=>setTimeout(s,e)));function v(){if(y>0)return void y--;const s=g,r=j,t=process.env[f];if(g=null,j=!1,s&&r){t&&delete process.env[f];try{e.unlinkSync(s)}catch{}}}export async function acquireStageLock(r){if(g)return y++,v;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()+p,n=process.env[f]||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 g=t,void(j=!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),g=t,j=!0,void(process.env[f]=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>u||Number.isFinite(c)&&c>0&&!b(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(p/1e3)}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 w(m+Math.floor(Math.random()*m))}}}((e=>t.write(`${e}\n`))),v}function k(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(E(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 E(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}}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=k(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:k(entriesFor("nested"),null).length}),t("flat")){const e=k(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=e.readFileSync(o.dest,"utf8").replace(/\/\*[\s\S]*?\*\//g,"").replace(/(^|[^:])\/\/.*$/gm,"$1");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/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 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(e&&e.HOME?e.HOME:"",".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(e&&e.HOME||"",".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")),"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,k=n.filter((e=>"warn"===e.level)).length,j=b?EXIT.BROKEN:k?EXIT.WARN:EXIT.OK;return{report:{aegis:"one",status:b?"broken":k?"warn":"healthy",exitCode:j,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:j}}function render(e){const t=[];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,String(n)+" ".repeat(Math.max(0,14-String(n).length))} ${o.version||"unknown"}${e}`)}var n;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 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){const t=e||{};let n=!1;try{n=require("./host.js").hostSeams({}).win32}catch{}const r=n?t.USERPROFILE||t.HOME:t.HOME||t.USERPROFILE;if(r)return String(r);try{return String(require("node:os").homedir()||"")}catch{return""}}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=[];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,String(n)+" ".repeat(Math.max(0,14-String(n).length))} ${o.version||"unknown"}${e}`)}var n;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)));
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "aegiscode",
3
3
  "productName": "AEGIS Code",
4
- "version": "7.0.50",
4
+ "version": "7.0.52",
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",
@@ -134,7 +134,7 @@ const UNITS = Object.freeze([
134
134
  * (`tools/desktop-seal.mjs` in the source tree, `tools/obfuscate-faces.mjs`
135
135
  * after obfuscation), never by hand.
136
136
  */
137
- const SEALED = 'ff85ac21bd09e7567007ed955b28d3dd061afd601013b63906aad4a706f62645';
137
+ const SEALED = 'f2a24b8db64bbb0b88cbe663d6c7dddc15b584a68609213b4b147516dd596aec';
138
138
 
139
139
  /**
140
140
  * Ask the question. Never throws — a check that can break the program it is
@@ -352,6 +352,13 @@ const DESKTOP_CLASSES = Object.freeze(['aegis', 'byok', 'local']);
352
352
  */
353
353
  const CHAT_DELTA_CHANNEL = `${IPC_PREFIX}chatDelta`;
354
354
 
355
+ /**
356
+ * ON9 — main -> renderer push channel for the embedded terminal panel's
357
+ * data/exit frames, tagged by session id the same way CHAT_DELTA_CHANNEL is
358
+ * (see createPtyIpc below and preload.js aegis.pty.onEvent).
359
+ */
360
+ const PTY_EVENT_CHANNEL = `${IPC_PREFIX}ptyEvent`;
361
+
355
362
  /** Main -> renderer pushes for native menu accelerators (Cmd/Ctrl+N,
356
363
  * Cmd/Ctrl+K) that have no Electron role to bind to — the renderer owns
357
364
  * "new chat" and "open search" behaviour, so the menu just asks for it. */
@@ -2049,6 +2056,66 @@ function createCliFaceDispatch(deps) {
2049
2056
  };
2050
2057
  }
2051
2058
 
2059
+ /**
2060
+ * ON9 — register the embedded terminal panel's five `aegis:pty*` handlers.
2061
+ *
2062
+ * Not routed through the generic `{name: handler}` wrapper the rest of this
2063
+ * file's settings-surface dispatches use (`registerConfirmModeIpc`): that
2064
+ * wrapper drops `event`, and `ptyExec` needs `event.sender` to push streamed
2065
+ * data/exit frames the same way `chatCompletion`'s streaming branch does
2066
+ * (see `registerIpc`'s special case above). The decision logic — what counts
2067
+ * as a capable pty backend, when to refuse rather than downgrade — lives
2068
+ * entirely in `lib/local/pty-host.js`; this function is the effects: probe
2069
+ * `node-pty`, build the host once, wire five channels to it.
2070
+ */
2071
+ function createPtyIpc(ipcMain, deps) {
2072
+ const d = deps || {};
2073
+ const hostMod = d.ptyHostModule || require('./lib/local/pty-host.js');
2074
+ const nodePty = d.nodePty !== undefined ? d.nodePty : hostMod.probeNodePty();
2075
+ const host = hostMod.createPtyHost({
2076
+ nativePty: Boolean(nodePty),
2077
+ appInfo: d.appInfo,
2078
+ spawnPty: nodePty
2079
+ ? (argv, opts) =>
2080
+ nodePty.spawn(argv[0], argv.slice(1), {
2081
+ name: 'xterm-color',
2082
+ cols: opts.cols || 80,
2083
+ rows: opts.rows || 24,
2084
+ cwd: opts.cwd || process.cwd(),
2085
+ // Merged, never replaced: `command.env` from cli-face.js's
2086
+ // innerCommand() carries only the ONE switch it adds
2087
+ // (ELECTRON_RUN_AS_NODE) on the bundled branch, not a full
2088
+ // environment — `opts.env || process.env` would have handed the
2089
+ // spawned process that single variable and nothing else (no
2090
+ // PATH, no HOME), the same bug Object.assign already avoids in
2091
+ // the external-terminal path above (openCliFace's spawnChild).
2092
+ env: Object.assign({}, process.env, opts.env || {}),
2093
+ })
2094
+ : undefined,
2095
+ });
2096
+
2097
+ ipcMain.handle(`${IPC_PREFIX}ptyHello`, (_event, payload) => host.hello((payload && payload.id) || 0));
2098
+ ipcMain.handle(`${IPC_PREFIX}ptyExec`, (event, payload) => {
2099
+ const p = payload || {};
2100
+ const sender = event && event.sender;
2101
+ const emit = (frame) => {
2102
+ if (sender && !sender.isDestroyed()) sender.send(PTY_EVENT_CHANNEL, frame);
2103
+ };
2104
+ return host.exec(p.id, p.params, emit);
2105
+ });
2106
+ ipcMain.handle(`${IPC_PREFIX}ptyWrite`, (_event, payload) => {
2107
+ const p = payload || {};
2108
+ return host.write(p.id, p.data);
2109
+ });
2110
+ ipcMain.handle(`${IPC_PREFIX}ptyResize`, (_event, payload) => {
2111
+ const p = payload || {};
2112
+ return host.resize(p.id, p.cols, p.rows);
2113
+ });
2114
+ ipcMain.handle(`${IPC_PREFIX}ptyCancel`, (_event, payload) => host.cancel((payload || {}).id));
2115
+
2116
+ return host;
2117
+ }
2118
+
2052
2119
  function createSandboxPolicyDispatch(settings, sandbox, opts) {
2053
2120
  if (!settings) throw new Error('createSandboxPolicyDispatch requires a settings store');
2054
2121
  const mod = sandbox || {};
@@ -2481,7 +2548,33 @@ function createEngine(aegis, { app, safeStorage, dir: dirOverride, sessionsDir:
2481
2548
  // never as `off`. `strict` is the user's own choice and lives beside the
2482
2549
  // policy; absent means degrade-loudly, because refusing every command on an
2483
2550
  // AppArmor-restricted host would brick the product rather than protect it.
2484
- sandbox: { policy: settings.getSandboxPolicy(), strict: false, appDir: __dirname },
2551
+ //
2552
+ // A GETTER, not a captured value — the same seam the terminal face passes
2553
+ // (`cli/src/engine.js`), for the same reason, and this host had the bug that
2554
+ // comment warns about. `resolveSandbox()` in engine.js reads `policy` once
2555
+ // per turn; capturing the store's value HERE meant it read whatever existed
2556
+ // at first-window creation and never again. The visible symptom was the
2557
+ // Settings › sandbox network switch: flipping "allow network from sandboxed
2558
+ // commands" wrote to disk, repainted the caption, and left the running
2559
+ // engine enforcing the OLD axis until the app was relaunched. On Linux that
2560
+ // looked like a stale sandbox; on macOS it read as "the network approval is
2561
+ // broken", because `sandbox-seatbelt.js` is the file that turns that axis
2562
+ // into `(deny network*)` and it was being handed a policy the user had
2563
+ // already changed. Windows had the identical staleness behind an
2564
+ // unimplemented mechanism, so the toggle could never have any effect there
2565
+ // either.
2566
+ //
2567
+ // Guarded because a staged settings store may predate the accessor — the
2568
+ // same shape `cli/src/engine.js` uses. A missing accessor answers null,
2569
+ // which `resolveSandbox()` reads as "no policy was requested", i.e. the
2570
+ // pre-existing unconfined turn, never as a permissive default.
2571
+ sandbox: {
2572
+ policy: () => (typeof settings.getSandboxPolicy === 'function'
2573
+ ? settings.getSandboxPolicy()
2574
+ : null),
2575
+ strict: false,
2576
+ appDir: __dirname,
2577
+ },
2485
2578
  // Stored /permissions rules (~/plan/agent-safety-plan.md §2). The rules live
2486
2579
  // in the SHARED data dir (~/.aegiscode/permissions.json), which is the same
2487
2580
  // file the terminal face writes via `/permissions allow|deny|ask`, so a rule
@@ -5457,7 +5550,24 @@ function bootstrap() {
5457
5550
  // Settings Reads go 4 -> 2 and accent-color calls 2 -> 0 per launch. The
5458
5551
  // surviving Reads are color-scheme, which Electron 44 exposes no gate for;
5459
5552
  // left alone deliberately, since the window chrome follows light/dark.
5460
- app.commandLine.appendSwitch('disable-features', 'UsePortalAccentColor');
5553
+ //
5554
+ // VaapiVideoDecoder/Encoder ride in this SAME call on purpose: Chromium's
5555
+ // `appendSwitch` REPLACES a switch it has already seen rather than merging
5556
+ // values, so a second `disable-features` line would silently drop the accent
5557
+ // fix above. With VA-API gated off, Chromium never initialises libva — which
5558
+ // on a host with no VA-API driver is what printed, on every start and before
5559
+ // `log-level=3` applied:
5560
+ //
5561
+ // libva error: vaGetDriverNameByIndex() failed with unknown libva error
5562
+ // libva error: /usr/lib/x86_64-linux-gnu/dri/i965_drv_video.so init failed
5563
+ // [<pid>:<date>:ERROR:gpu_init.cc] Passthrough is not supported, GL is disabled,
5564
+ // not EGL
5565
+ //
5566
+ // The last line is the real defeat: Chromium tried the video path, found no
5567
+ // hardware decode and no software rasterizer (both disabled above), and gave
5568
+ // up — leaving the media path uninitialised in the window. Gating VA-API out
5569
+ // makes it choose the stated fallback up front instead of failing into it.
5570
+ app.commandLine.appendSwitch('disable-features', 'UsePortalAccentColor,VaapiVideoDecoder,VaapiVideoEncoder');
5461
5571
 
5462
5572
  // The X11 clipboard advertises its drag-and-drop target formats by looking
5463
5573
  // each MIME atom up in Chromium's atom cache, and Chromium logs an ERROR for
@@ -6112,6 +6222,22 @@ function bootstrap() {
6112
6222
  })
6113
6223
  );
6114
6224
 
6225
+ // ON9 — the same chip's OTHER outcome: the terminal face drawn INSIDE this
6226
+ // window instead of a second OS process, when `node-pty` (an
6227
+ // optionalDependency, same discipline as `electron` itself) resolves.
6228
+ // `createPtyIpc` probes it once at bootstrap; `aegis:ptyHello`'s caps tell
6229
+ // the renderer whether to open the embedded panel or fall back to the
6230
+ // `openCliFace` path above — that choice is the renderer's, not main's.
6231
+ createPtyIpc(ipcMain, {
6232
+ appInfo: {
6233
+ packaged: app.isPackaged,
6234
+ resourcesPath: process.resourcesPath,
6235
+ appDir: __dirname,
6236
+ execPath: process.execPath,
6237
+ nodePath: process.execPath,
6238
+ },
6239
+ });
6240
+
6115
6241
  // Funnel instrumentation (Phase 2 of docs/upgrade-conversion-plan.md):
6116
6242
  // aegis:telemetryEvent / aegis:telemetryReport, backed by
6117
6243
  // lib/local/telemetry.js.
@@ -7055,6 +7181,8 @@ module.exports = {
7055
7181
  TOPUP_POLL_MS,
7056
7182
  TOPUP_POLL_TRIES,
7057
7183
  CHAT_DELTA_CHANNEL,
7184
+ PTY_EVENT_CHANNEL,
7185
+ createPtyIpc,
7058
7186
  MENU_NEW_CHAT_CHANNEL,
7059
7187
  MENU_SEARCH_CHANNEL,
7060
7188
  MENU_SEARCH_MEMORY_CHANNEL,
@@ -0,0 +1,3 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
+ "use strict";const path=require("node:path"),KIND=Object.freeze({PTY:"pty",PIPE:"pipe"}),CAP="pty",CODE=Object.freeze({UNSUPPORTED:"unsupported",NO_SPAWN:"no_spawn",BAD_DESC:"bad_desc"});function plan(n){const e=n||{};return"wasm"===e.target?{ok:!1,code:CODE.UNSUPPORTED,msg:"this target has no child processes: a WASM core cannot run exec"}:e.nativePty?{ok:!0,kind:KIND.PTY,cap:CAP,reason:"a PTY backend is available, so the child gets a real terminal"}:{ok:!0,kind:KIND.PIPE,cap:null,reason:"no PTY backend: stdio works, but resize, signals and line discipline do not"}}function caps(n){return n&&n.ok&&n.cap?[n.cap]:[]}function spawn(n,e,a){const s=a||{};if(!n||!n.ok)return{ok:!1,code:n&&n.code||CODE.UNSUPPORTED,msg:n&&n.msg||"no usable process plan"};const o=e||{},t=Array.isArray(o.argv)?o.argv.map(String):[];if(!t.length)return{ok:!1,code:CODE.BAD_DESC,msg:"exec needs a non-empty argv"};const c={cwd:o.cwd,env:o.env,cols:o.cols,rows:o.rows};return n.kind===KIND.PTY?"function"!=typeof s.spawnPty?{ok:!1,code:CODE.NO_SPAWN,msg:"pty was negotiated but no PTY spawner was injected"}:{ok:!0,kind:KIND.PTY,handle:s.spawnPty(t,c)}:"function"!=typeof s.spawnChild?{ok:!1,code:CODE.NO_SPAWN,msg:"no child-process spawner was injected"}:{ok:!0,kind:KIND.PIPE,handle:s.spawnChild(t,c)}}function sameCommand(n,e){return path.basename(String(n||""))===path.basename(String(e||""))}module.exports={KIND:KIND,CAP:CAP,CODE:CODE,plan:plan,caps:caps,spawn:spawn,sameCommand:sameCommand};
@@ -0,0 +1,3 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
+ "use strict";const PROTO=1,METHODS=Object.freeze(["hello","exec","event","cancel"]),CAPS=Object.freeze({EXEC:"exec",EVENT:"event",CANCEL:"cancel",PTY:"pty"}),CODE=Object.freeze({BAD_JSON:"bad_json",BAD_FRAME:"bad_frame",UNKNOWN_METHOD:"unknown_method",PROTO_MISMATCH:"proto_mismatch",HELLO_REQUIRED:"hello_required",CAPABILITY_MISSING:"capability_missing",UNSUPPORTED:"unsupported"});function request(e,o,t){return{id:e,m:String(o),p:t&&"object"==typeof t?t:{}}}function ok(e,o){return{id:e,ok:!0,r:o&&"object"==typeof o?o:{}}}function err(e,o,t){return{id:e,ok:!1,e:{code:String(o||CODE.UNSUPPORTED),msg:String(t||"")}}}function isObject(e){return Boolean(e)&&"object"==typeof e&&!Array.isArray(e)}function validate(e){return isObject(e)?void 0===e.id||null===e.id?{ok:!1,code:CODE.BAD_FRAME,msg:"frame has no id"}:void 0!==e.ok?!0===e.ok?void 0!==e.e?{ok:!1,code:CODE.BAD_FRAME,msg:"reply carries both r and e"}:{ok:!0}:!1===e.ok?isObject(e.e)&&e.e.code?{ok:!0}:{ok:!1,code:CODE.BAD_FRAME,msg:"a failed reply must name a code"}:{ok:!1,code:CODE.BAD_FRAME,msg:"ok must be true or false"}:"string"==typeof e.m&&METHODS.includes(e.m)?void 0===e.p||isObject(e.p)?{ok:!0}:{ok:!1,code:CODE.BAD_FRAME,msg:"params must be an object"}:{ok:!1,code:CODE.UNKNOWN_METHOD,msg:`unknown method: ${String(e.m)}`}:{ok:!1,code:CODE.BAD_FRAME,msg:"frame must be an object"}}function negotiate(e,o){const t=o||{},r=validate(e);if(!r.ok)return{ok:!1,code:r.code,msg:r.msg};if("hello"!==e.m)return{ok:!1,code:CODE.HELLO_REQUIRED,msg:`the first frame must be hello, got ${String(e.m)}`};const n=e.p||{};if(1!==n.proto)return{ok:!1,code:CODE.PROTO_MISMATCH,msg:`peer speaks protocol ${String(n.proto)}, this build speaks 1`};const i=Array.isArray(n.caps)?n.caps.map(String):[],s=(Array.isArray(t.requireCaps)?t.requireCaps.map(String):[]).filter((e=>!i.includes(e)));return s.length?{ok:!1,code:CODE.CAPABILITY_MISSING,msg:`peer does not offer: ${s.join(", ")}`}:{ok:!0,proto:1,caps:i}}function hello(e){return request(void 0===e?0:e,"hello",{proto:1,caps:[CAPS.EXEC,CAPS.EVENT,CAPS.CANCEL]})}function encode(e){return`${JSON.stringify(e)}\n`}function decodeLine(e){const o=String(null==e?"":e).trim();if(!o)return{ok:!1,id:null,code:CODE.BAD_JSON,msg:"empty line"};let t;try{t=JSON.parse(o)}catch(e){return{ok:!1,id:null,code:CODE.BAD_JSON,msg:`not JSON: ${e.message}`}}const r=validate(t);return r.ok?{ok:!0,frame:t}:{ok:!1,id:isObject(t)&&void 0!==t.id?t.id:null,code:r.code,msg:r.msg}}function splitLines(e){const o=String(null==e?"":e).split("\n"),t=o.pop();return{lines:o.filter((e=>""!==e.trim())),rest:void 0===t?"":t}}module.exports={PROTO:1,METHODS:METHODS,CAPS:CAPS,CODE:CODE,request:request,ok:ok,err:err,hello:hello,validate:validate,negotiate:negotiate,encode:encode,decodeLine:decodeLine,splitLines:splitLines};
@@ -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"),CLI_BIN="aegiscode",EMULATORS=Object.freeze({linux:[{cmd:"x-terminal-emulator",style:"-e"},{cmd:"gnome-terminal",style:"-e"},{cmd:"konsole",style:"-e"},{cmd:"xfce4-terminal",style:"-e"},{cmd:"mate-terminal",style:"-e"},{cmd:"lxterminal",style:"-e"},{cmd:"kitty",style:"--"},{cmd:"alacritty",style:"--"},{cmd:"xterm",style:"-e"}],darwin:[{cmd:"osascript",style:"termapp"}],win32:[{cmd:"wt.exe",style:"exec"},{cmd:"cmd.exe",style:"exec"}]}),VENDOR_FACE=Object.freeze(["vendor","faces","cli","bin",`${CLI_BIN}.js`]);function cliEntry({packaged:e,resourcesPath:t,appDir:r,entryExists:n}={}){if(e)return t?path.join(t,"faces","cli","bin",`${CLI_BIN}.js`):null;if(!r)return null;const c=path.join(r,...VENDOR_FACE);let a=!1;try{a=Boolean(n&&n(c))}catch{a=!1}return a?c:path.join(r,"..","cli","bin",`${CLI_BIN}.js`)}function isBundledEntry(e){return/[\\/]faces[\\/]cli[\\/]bin[\\/]/.test(String(e||""))}function cliArgv(e,t){const r=Array.isArray(t)?t.map(String):[];return e?[e,...r]:r}function pickEmulator({platform:e,exists:t,candidates:r}={}){const n=r||EMULATORS[e]||[];if(!n.length)return{ok:!1,reason:`no terminal emulator known for ${e||"this host"}`};for(const e of n){let r=!1;try{r=Boolean(t&&t(e.cmd))}catch{r=!1}if(r)return{ok:!0,emulator:e}}return{ok:!1,reason:`no terminal emulator found (tried ${n.map((e=>e.cmd)).join(", ")}) — run the command in the plan by hand`}}function emulatorArgv(e,t){const r=t&&t.exec||"",n=t&&t.args||[];if(!e||!r)return[];switch(e.style){case"-e":return["-e",r,...n];case"--":return["--",r,...n];case"exec":return"cmd.exe"===e.cmd?["/c","start",'""',r,...n]:[r,...n];default:return[r,...n]}}function macScript(e){return`tell application "Terminal"\n activate\n do script "${[e&&e.exec||"",...e&&e.args||[]].map((e=>shellQuote(e))).join(" ").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"\nend tell`}function shellQuote(e){const t=String(null==e?"":e);return t?`'${t.replace(/'/g,"'\\''")}'`:"''"}function plan(e){const t=e||{},r=cliEntry(t);if(!r)return{ok:!1,reason:"could not locate the aegiscode entry point for this build",command:CLI_BIN};const n=Boolean(t.packaged)||isBundledEntry(r),c={exec:n?t.execPath:t.nodePath||"node",args:cliArgv(r,t.args)},a=n?{ELECTRON_RUN_AS_NODE:"1"}:void 0,l=[c.exec,...c.args].map((e=>shellQuote(e))).join(" "),o=pickEmulator({platform:t.platform,exists:t.exists,candidates:t.candidates});return o.ok?"termapp"===o.emulator.style?{ok:!0,exec:o.emulator.cmd,args:["-e",macScript(c)],env:a,command:l}:{ok:!0,exec:o.emulator.cmd,args:emulatorArgv(o.emulator,c),env:a,command:l}:{ok:!1,reason:o.reason,command:l}}module.exports={CLI_BIN:CLI_BIN,EMULATORS:EMULATORS,VENDOR_FACE:VENDOR_FACE,cliEntry:cliEntry,isBundledEntry:isBundledEntry,cliArgv:cliArgv,pickEmulator:pickEmulator,emulatorArgv:emulatorArgv,macScript:macScript,shellQuote:shellQuote,plan:plan};
3
+ "use strict";const path=require("node:path"),CLI_BIN="aegiscode",EMULATORS=Object.freeze({linux:[{cmd:"x-terminal-emulator",style:"-e"},{cmd:"gnome-terminal",style:"-e"},{cmd:"konsole",style:"-e"},{cmd:"xfce4-terminal",style:"-e"},{cmd:"mate-terminal",style:"-e"},{cmd:"lxterminal",style:"-e"},{cmd:"kitty",style:"--"},{cmd:"alacritty",style:"--"},{cmd:"xterm",style:"-e"}],darwin:[{cmd:"osascript",style:"termapp"}],win32:[{cmd:"wt.exe",style:"exec"},{cmd:"cmd.exe",style:"exec"}]}),VENDOR_FACE=Object.freeze(["vendor","faces","cli","bin",`${CLI_BIN}.js`]);function cliEntry({packaged:e,resourcesPath:t,appDir:n,entryExists:r}={}){if(e)return t?path.join(t,"faces","cli","bin",`${CLI_BIN}.js`):null;if(!n)return null;const a=path.join(n,...VENDOR_FACE);let c=!1;try{c=Boolean(r&&r(a))}catch{c=!1}return c?a:path.join(n,"..","cli","bin",`${CLI_BIN}.js`)}function isBundledEntry(e){return/[\\/]faces[\\/]cli[\\/]bin[\\/]/.test(String(e||""))}function cliArgv(e,t){const n=Array.isArray(t)?t.map(String):[];return e?[e,...n]:n}function pickEmulator({platform:e,exists:t,candidates:n}={}){const r=n||EMULATORS[e]||[];if(!r.length)return{ok:!1,reason:`no terminal emulator known for ${e||"this host"}`};for(const e of r){let n=!1;try{n=Boolean(t&&t(e.cmd))}catch{n=!1}if(n)return{ok:!0,emulator:e}}return{ok:!1,reason:`no terminal emulator found (tried ${r.map((e=>e.cmd)).join(", ")}) — run the command in the plan by hand`}}function emulatorArgv(e,t){const n=t&&t.exec||"",r=t&&t.args||[];if(!e||!n)return[];switch(e.style){case"-e":return["-e",n,...r];case"--":return["--",n,...r];case"exec":return"cmd.exe"===e.cmd?["/c","start",'""',n,...r]:[n,...r];default:return[n,...r]}}function macScript(e){return`tell application "Terminal"\n activate\n do script "${[e&&e.exec||"",...e&&e.args||[]].map((e=>shellQuote(e))).join(" ").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"\nend tell`}function shellQuote(e){const t=String(null==e?"":e);return t?`'${t.replace(/'/g,"'\\''")}'`:"''"}function innerCommand(e){const t=e||{},n=cliEntry(t);if(!n)return{ok:!1,reason:"could not locate the aegiscode entry point for this build",command:CLI_BIN};const r=Boolean(t.packaged)||isBundledEntry(n),a=r?t.execPath:t.nodePath||"node",c=cliArgv(n,t.args),o=r?{ELECTRON_RUN_AS_NODE:"1"}:void 0,l=[a,...c].map((e=>shellQuote(e))).join(" ");return{ok:!0,exec:a,args:c,env:o,command:l}}function plan(e){const t=e||{},n=innerCommand(t);if(!n.ok)return n;const r=pickEmulator({platform:t.platform,exists:t.exists,candidates:t.candidates});return r.ok?"termapp"===r.emulator.style?{ok:!0,exec:r.emulator.cmd,args:["-e",macScript(n)],env:n.env,command:n.command}:{ok:!0,exec:r.emulator.cmd,args:emulatorArgv(r.emulator,n),env:n.env,command:n.command}:{ok:!1,reason:r.reason,command:n.command}}module.exports={CLI_BIN:CLI_BIN,EMULATORS:EMULATORS,VENDOR_FACE:VENDOR_FACE,cliEntry:cliEntry,isBundledEntry:isBundledEntry,cliArgv:cliArgv,pickEmulator:pickEmulator,emulatorArgv:emulatorArgv,macScript:macScript,shellQuote:shellQuote,innerCommand:innerCommand,plan:plan};
@@ -134,7 +134,7 @@ const UNITS = Object.freeze([
134
134
  * (`tools/desktop-seal.mjs` in the source tree, `tools/obfuscate-faces.mjs`
135
135
  * after obfuscation), never by hand.
136
136
  */
137
- const SEALED = 'ff85ac21bd09e7567007ed955b28d3dd061afd601013b63906aad4a706f62645';
137
+ const SEALED = 'f2a24b8db64bbb0b88cbe663d6c7dddc15b584a68609213b4b147516dd596aec';
138
138
 
139
139
  /**
140
140
  * Ask the question. Never throws — a check that can break the program it is
@@ -0,0 +1,3 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
+ "use strict";const path=require("node:path"),fs=require("node:fs");function resolveOneModule(e,o,n){const t=n||{},r=t.exists||fs.existsSync,s=t.load||require,i=[path.join(__dirname,"..","..","..",e),path.join(__dirname,"..","..","vendor",o)];for(const e of i)if(r(e))return s(e);throw new Error(`pty-host: cannot find ${e}. Expected it beside desktop/ (repo checkout) or flattened at desktop/vendor/${o} (published package) — run \`node one/scripts/predist.mjs --flat-only\` if this is a source checkout.`)}function loadSeam(e){const o=e||{};return{protocol:o.protocol||resolveOneModule("one/src/protocol.js","protocol.js",o),pty:o.pty||resolveOneModule("one/src/iface/pty.js","pty.js",o)}}function probeNodePty(e){const o=e||require;try{return o("node-pty")}catch{return null}}function createPtyHost(e){const o=e||{},{protocol:n,pty:t}=loadSeam(o),r=o.cliFace||require("./cli-face.js"),s=Boolean(o.nativePty),i=t.plan({nativePty:s}),c=new Map;function u(e){return c.get(e)||null}return{hello:function(e){const o=[n.CAPS.EXEC,n.CAPS.EVENT,n.CAPS.CANCEL,...t.caps(i)];return n.ok(e,{proto:n.PROTO,caps:o})},exec:function(e,s,u){const a=s||{},l="function"==typeof u?u:()=>{},p=r.innerCommand(o.appInfo||{});if(!p.ok)return n.err(e,"no_spawn",p.reason);const d=t.spawn(i,{argv:[p.exec,...p.args],env:p.env,cols:a.cols,rows:a.rows},{spawnPty:o.spawnPty});if(!d.ok)return n.err(e,d.code,d.msg);const f=d.handle;return c.set(e,f),"function"==typeof f.onData&&f.onData((o=>l(n.request(e,"event",{kind:"data",chunk:o})))),"function"==typeof f.onExit&&f.onExit((o=>{c.delete(e),l(n.request(e,"event",{kind:"exit",exitCode:o&&"number"==typeof o.exitCode?o.exitCode:null,signal:o&&o.signal||null}))})),n.ok(e,{kind:d.kind})},write:function(e,o){const r=u(e);return r&&"function"==typeof r.write?(r.write(String(null==o?"":o)),n.ok(e,{})):n.err(e,t.CODE.NO_SPAWN,"no session for this id")},resize:function(e,o,r){const s=u(e);return s&&"function"==typeof s.resize?(s.resize(o,r),n.ok(e,{})):n.err(e,t.CODE.NO_SPAWN,"no session for this id")},cancel:function(e){const o=u(e);return o?("function"==typeof o.kill&&o.kill(),c.delete(e),n.ok(e,{})):n.err(e,n.CODE.UNSUPPORTED,"no session for this id")},sessionCount:function(){return c.size}}}module.exports={createPtyHost:createPtyHost,probeNodePty:probeNodePty,resolveOneModule:resolveOneModule};