aegisone 1.0.42 → 1.0.44

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 (78) hide show
  1. package/README.md +2 -2
  2. package/package.json +1 -1
  3. package/scripts/predist.mjs +1 -1
  4. package/src/doctor.js +1 -1
  5. package/vendor/cli/README.md +5 -5
  6. package/vendor/cli/package.json +2 -2
  7. package/vendor/cli/src/chatflow.js +1 -1
  8. package/vendor/cli/src/commands.js +2 -2
  9. package/vendor/cli/src/deps.js +1 -1
  10. package/vendor/cli/src/limits.js +1 -1
  11. package/vendor/cli/src/permissions.js +4 -0
  12. package/vendor/cli/src/provenance.lock.json +2 -2
  13. package/vendor/cli/vendor/desktop/lib/local/check-command.js +3 -0
  14. package/vendor/cli/vendor/desktop/lib/local/engine.js +1 -1
  15. package/vendor/cli/vendor/desktop/lib/local/integrity.js +1 -1
  16. package/vendor/cli/vendor/desktop/lib/local/perm-store.js +7 -2
  17. package/vendor/cli/vendor/desktop/lib/local/prompt.js +1 -1
  18. package/vendor/cli/vendor/desktop/lib/local/repeat-guard.js +3 -0
  19. package/vendor/cli/vendor/desktop/lib/local/tools.js +186 -2
  20. package/vendor/cli/vendor/desktop/lib/local/verify-stop.js +3 -0
  21. package/vendor/cli/vendor/desktop/lib/settings.js +1 -1
  22. package/vendor/cli/vendor/desktop/main.js +802 -54
  23. package/vendor/desktop/README.md +3 -3
  24. package/vendor/desktop/bin/aegis.js +1 -1
  25. package/vendor/desktop/lib/avatar/events.js +1 -1
  26. package/vendor/desktop/lib/avatar/persona.js +1 -1
  27. package/vendor/desktop/lib/avatar/store.js +1 -1
  28. package/vendor/desktop/lib/local/check-command.js +3 -0
  29. package/vendor/desktop/lib/local/cli-face.js +3 -0
  30. package/vendor/desktop/lib/local/engine.js +1 -1
  31. package/vendor/desktop/lib/local/integrity.js +1 -1
  32. package/vendor/desktop/lib/local/perm-store.js +7 -2
  33. package/vendor/desktop/lib/local/prompt.js +1 -1
  34. package/vendor/desktop/lib/local/repeat-guard.js +3 -0
  35. package/vendor/desktop/lib/local/tools.js +186 -2
  36. package/vendor/desktop/lib/local/verify-stop.js +3 -0
  37. package/vendor/desktop/lib/settings.js +1 -1
  38. package/vendor/desktop/lib/sync/persist-gate.js +1 -1
  39. package/vendor/desktop/lib/sync/sessions.js +1 -1
  40. package/vendor/desktop/main.js +802 -54
  41. package/vendor/desktop/package.json +8 -4
  42. package/vendor/desktop/preload.js +1 -1
  43. package/vendor/desktop/renderer/app.js +3 -3
  44. package/vendor/desktop/renderer/avatar/pane.js +1 -1
  45. package/vendor/desktop/renderer/avatar/parts.js +1 -1
  46. package/vendor/desktop/renderer/commands.js +3 -0
  47. package/vendor/desktop/renderer/composer-triggers.js +3 -0
  48. package/vendor/desktop/renderer/find-in-conversation.js +3 -0
  49. package/vendor/desktop/renderer/fonts/fonts.css +42 -0
  50. package/vendor/desktop/renderer/fonts/ubuntu-vf-italic.woff2 +0 -0
  51. package/vendor/desktop/renderer/fonts/ubuntu-vf.woff2 +0 -0
  52. package/vendor/desktop/renderer/index.html +941 -484
  53. package/vendor/desktop/renderer/library.js +3 -0
  54. package/vendor/desktop/renderer/nav-history.js +3 -0
  55. package/vendor/desktop/renderer/palette-filter.js +3 -0
  56. package/vendor/desktop/renderer/shortcuts.js +3 -0
  57. package/vendor/desktop/renderer/style.css +2602 -380
  58. package/vendor/desktop/renderer/transcript-view.js +1 -1
  59. package/vendor/desktop/renderer/welcome-rows.js +3 -0
  60. package/vendor/desktop/vendor/faces/cli/README.md +5 -5
  61. package/vendor/desktop/vendor/faces/cli/package.json +2 -2
  62. package/vendor/desktop/vendor/faces/cli/src/chatflow.js +1 -1
  63. package/vendor/desktop/vendor/faces/cli/src/commands.js +2 -2
  64. package/vendor/desktop/vendor/faces/cli/src/deps.js +1 -1
  65. package/vendor/desktop/vendor/faces/cli/src/limits.js +1 -1
  66. package/vendor/desktop/vendor/faces/cli/src/permissions.js +1 -1
  67. package/vendor/desktop/vendor/faces/cli/src/provenance.lock.json +2 -2
  68. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/check-command.js +3 -0
  69. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/engine.js +1 -1
  70. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/integrity.js +1 -1
  71. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/perm-store.js +1 -1
  72. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/prompt.js +1 -1
  73. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/repeat-guard.js +3 -0
  74. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/tools.js +1 -1
  75. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/verify-stop.js +3 -0
  76. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/settings.js +1 -1
  77. package/vendor/desktop/vendor/faces/cli/vendor/desktop/main.js +3 -3
  78. package/vendor/desktop/vendor/sandbox/provenance.json +7 -7
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # AEGISONE
2
2
 
3
- Product version: **1.0.42**
3
+ Product version: **1.0.44**
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,7 @@ fails, and it never leaves you with "nothing happened". Afterwards: `aegis`
60
60
 
61
61
  ## Size, measured not claimed
62
62
 
63
- Measured size: **2.71 MB** (2,844,939 bytes) with Electron absent — both faces inside.
63
+ Measured size: **3.04 MB** (3,186,448 bytes) with Electron absent — both faces inside.
64
64
 
65
65
  The plan's "~2 MB" was a target, so it is measured here rather than published:
66
66
  `npm pack one/` on this tree, with Electron absent, produces that tarball, and it
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "aegisone",
3
3
  "productName": "AEGISONE",
4
- "version": "1.0.42",
4
+ "version": "1.0.44",
5
5
  "description": "AEGISONE — one product, two faces. `aegis` opens the window when there is nothing else to do and runs the terminal otherwise; `aegiscode` keeps behaving exactly as it always has.",
6
6
  "author": {
7
7
  "name": "AEGIS Code",
@@ -1,4 +1,4 @@
1
1
  #!/usr/bin/env node
2
2
  // SPDX-License-Identifier: AGPL-3.0-or-later
3
3
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
4
- import e from"node:fs";import s from"node:path";import{spawnSync as r}from"node:child_process";import{fileURLToPath as t,pathToFileURL as o}from"node:url";import{createRequire as n}from"node:module";const i=s.dirname(t(import.meta.url)),a=n(import.meta.url);export const ONE_DIR=s.join(i,"..");export const REPO_DIR=s.join(ONE_DIR,"..");export const CLI_DIR=s.join(REPO_DIR,"cli");export const DESKTOP_DIR=s.join(REPO_DIR,"desktop");export const CLI_VENDOR=s.join(CLI_DIR,"vendor");export const DESKTOP_VENDOR=s.join(DESKTOP_DIR,"vendor");export const ONE_VENDOR=s.join(ONE_DIR,"vendor");export const MANIFEST=[{src:"client/aegis.js",shapes:["mirror","flat"],note:"the thin transport — the one implementation of the wire format"},{src:"client/update.js",shapes:["mirror","flat"],note:"the npm update checker (the desktop own update path)"},{src:"client/foreign-memory.js",shapes:["mirror","flat"],note:"required by mcp/tools.js as ../client/foreign-memory.js"},{src:"client/foreign-sessions.js",shapes:["mirror","flat"],note:"required by desktop/main.js as ./vendor/foreign-sessions.js"},{src:"client/credentials.js",shapes:["mirror","flat"],note:"the account credential store, shared by all three hosts"},{src:"client/session-store.js",shapes:["mirror","flat"],note:"the unified session store — one list in every host"},{src:"client/session-search.js",shapes:["mirror","flat"],note:"the SESSION search ranking: the desktop sheet (Cmd/Ctrl+K) and the terminal /resume picker filter with this one module, pure and fs-free"},{src:"client/credits.js",shapes:["mirror","flat"],note:"the licence/attribution payload: parses LICENSING.md and the two NOTICE files for Help > Credits & licence and /license + /credits"},{src:"client/naming.js",shapes:["mirror","flat"],note:"the conversation-naming ladder — ONE implementation for the terminal and the window (cli/src/naming.js re-exports it)"},{src:"client/prefs.js",shapes:["mirror","flat"],note:"the shared non-secret preference store (D5) — the CLI and the desktop store both read/write it"},{src:"client/env-file.js",shapes:["mirror","flat"],note:"the shared ~/.aegiscode/.env loader, resolved before any key is read"},{src:"client/auto-provision.js",shapes:["mirror","flat"],note:"free device key on first launch; requires ./device-fingerprint.js"},{src:"client/device-fingerprint.js",shapes:["mirror","flat"],note:"the machine identity auto-provision.js and presence.js require"},{src:"client/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/hooks.js",shapes:["mirror","flat"],note:"the shared hook layer behind /hooks and the repo guard installer"},{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/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 p(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 h=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()+h,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(h/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 E(r,t){t&&e.rmSync(t,{recursive:!0,force:!0});const o=[];for(const t of r){if(!e.existsSync(t.from))throw new Error(`predist: missing shared module: ${t.src} (expected at ${t.from})`);if(e.mkdirSync(s.dirname(t.dest),{recursive:!0}),e.copyFileSync(t.from,t.dest),!e.readFileSync(t.from).equals(e.readFileSync(t.dest)))throw new Error(`predist: staged copy differs from source: ${t.src}`);o.push(t)}return o}export async function stage(t){const n=t||{},i=n.io||{},l=i.stdout||process.stdout,h=(i.stderr||process.stderr,Array.isArray(n.shapes)?n.shapes:[...SHAPES,"bundle"]),u=e=>h.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=E(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:E(entriesFor("nested"),null).length}),t("flat")){const e=E(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")),p=a(s.join(l,"install.js")),h=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=h.getTarget("vscode"),f=p.planTarget(m,"user",{ctx:p.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:h.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)}`)}p(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}),p(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/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/hooks.js",shapes:["mirror","flat"],note:"the shared hook layer behind /hooks and the repo guard installer"},{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 p(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 h=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()+h,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(h/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 E(r,t){t&&e.rmSync(t,{recursive:!0,force:!0});const o=[];for(const t of r){if(!e.existsSync(t.from))throw new Error(`predist: missing shared module: ${t.src} (expected at ${t.from})`);if(e.mkdirSync(s.dirname(t.dest),{recursive:!0}),e.copyFileSync(t.from,t.dest),!e.readFileSync(t.from).equals(e.readFileSync(t.dest)))throw new Error(`predist: staged copy differs from source: ${t.src}`);o.push(t)}return o}export async function stage(t){const n=t||{},i=n.io||{},l=i.stdout||process.stdout,h=(i.stderr||process.stderr,Array.isArray(n.shapes)?n.shapes:[...SHAPES,"bundle"]),u=e=>h.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=E(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:E(entriesFor("nested"),null).length}),t("flat")){const e=E(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")),p=a(s.join(l,"install.js")),h=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=h.getTarget("vscode"),f=p.planTarget(m,"user",{ctx:p.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:h.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)}`)}p(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}),p(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 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 s;try{s=fs.readdirSync(e,{withFileTypes:!0})}catch{return}for(const o of s){if("node_modules"===o.name||".git"===o.name)continue;const s=path.join(e,o.name);o.isDirectory()?r(s):n.push(path.relative(t,s).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(){let e=null;const t=()=>{if(e)return e;const t=[path.join(repoDir(),"client","update.js"),path.join(oneDir(),"vendor","cli","vendor","client","update.js")];for(const n of t)try{e=require(n);break}catch{}return e};return{check(e){const n=t();return n&&"function"==typeof n.updateNotice?n.updateNotice(e||{}):{latest:null,behind:!1,reason:"unavailable"}},plan(e){const n=t();return n&&"function"==typeof n.updatePlan?n.updatePlan(e||{}):null}}}function defaultStorePath(e){try{const t=require(path.join(repoDir(),"client","prefs.js"));if("function"==typeof t.prefsFile)return t.prefsFile(e)}catch{}const t=homeHint(e)||path.join(e&&e.HOME||"",".aegiscode");return path.join(t,"preferences.json")}function defaultCredentials(){let e=null;return{resolve(t){if(!e)try{e=require(path.join(repoDir(),"client","credentials.js"))}catch{e=null}if(!e||"function"!=typeof e.resolveApiKey)return{key:"",source:"none",from:""};try{return e.resolveApiKey(t||{})}catch{return{key:"",source:"none",from:""}}}}}function vendorPairs(e){const{root:t,exists:n}=e,r=[];for(const{face:s,root:o,staged:a}of BUNDLE_FACES){const i=path.join(t,a),c=e.listFiles(i,i);for(const e of c){const i=[];if(e.startsWith("vendor/")){const n=e.slice(7);if(i.push(path.join(t,n)),i.push(path.join(t,o,n)),"desktop"===s){const e=path.basename(n);for(const n of["client","mcp","covenant","commands","skills","tools","hosts"])i.push(path.join(t,n,e));i.push(path.join(t,e))}}else i.push(path.join(t,o,e)),i.push(path.join(t,e));const c=i.find((e=>n(e)))||null;r.push({face:s,staged:path.join(a,e),source:c,candidates:i})}}return r}function checkVendor(e,t){const n=t||vendorPairs(e),r=[],s=[];let o=0,a=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){s.push({staged:t.staged,source:t.source,error:String(e&&e.message||e)});continue}n===i?o+=1:s.push({staged:t.staged,source:t.source})}return{staged:a,matched:o,mismatch:s,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(),s=t||{};return{root:t.root||repoDir(),platform:t.platform||"linux",env:n,exists:s.exists||r.exists,readFile:s.readFile||r.readFile,hashFile:s.hashFile||r.hashFile,listFiles:s.listFiles||r.listFiles,credentials:t.credentials||defaultCredentials(),storePath:t.storePath||defaultStorePath(n),registry:t.registry||defaultRegistry(),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}}function diagnose(e){const t=resolveSeams(e),n=[],r=(e,t)=>n.push({level:"broken",code:e,detail:t}),s=(e,t)=>n.push({level:"warn",code:e,detail:t}),o=readJson(t,"one/package.json"),a=o.ok?{name:o.value.name||"aegisone",version:String(o.value.version||"")}:{name:"aegisone",version:""};o.ok||r("product-unreadable","one/package.json "+(o.unreadable?"is unreadable":"is missing"));let i=null;try{i=require("./release.js").deriveFaceVersions(a.version)}catch(e){i=null,o.ok&&r("product-version-invalid",`${a.version}: ${String(e&&e.message||e)}`)}const c={};for(const{dir:e,package:n}of FACE_PACKAGES){const s=readJson(t,`${e}/package.json`),o=s.ok?String(s.value.version||""):"",l=i&&i[n]?i[n].version:null;s.ok?l&&o!==l&&r("version-mismatch",`${n} is ${o}, product ${a.version} derives ${l}`):r("face-unreadable",`${e}/package.json ${s.unreadable?"is unreadable":"is missing"}`),c[n]={dir:e,version:o,expected:l,ok:Boolean(l&&o===l)}}let l={key:"",source:"none",from:""};try{l=t.credentials.resolve({env:t.env})||l}catch{l={key:"",source:"none",from:""}}const u=t.electronPaths||{};let d=l.key?"env"===l.source?"env":(l.source,"env-file"):"none";if(!l.key&&u.keychain&&t.exists(u.keychain)){const e=(()=>{try{return t.readFile(u.keychain)}catch{return null}})();e&&/encrypt|safeStorage/i.test(e)&&(d="keychain")}"none"===d&&s("no-credential","no credential found (env, credentials.json, or the OS keychain)");const h={path:t.storePath,exists:!1,readable:null,legacy:null};try{h.exists=t.exists(t.storePath)}catch{h.exists=!1}let p,f=h.path;if(h.exists){let e=null;try{e=t.readFile(h.path)}catch(e){h.readable=!1,r("store-unreadable",`${h.path}: ${String(e&&e.message||e)}`)}if(null===h.readable)if(null==e)h.readable=!1,r("store-unreadable",`${h.path} exists but could not be read`);else try{const t=JSON.parse(e);h.readable=!0,h.legacy=t&&t.version||null}catch(e){h.readable=!1,r("store-unreadable",`${h.path} is not valid JSON: ${String(e&&e.message||e)}`)}f=path.basename(h.path)}h.display=f;try{p=checkVendor(t,t.vendorPairs)}catch(e){p={staged:0,matched:0,mismatch:[],missingSource:[],stale:!1,checked:0,error:String(e&&e.message||e)},r("vendor-unreadable",p.error)}for(const e of p.mismatch)r("vendor-hash-mismatch",`${e.staged} differs from ${e.source||"its source"}`);for(const e of p.missingSource)r("vendor-source-missing",`${e} has no source to be re-derived from`);p.stale&&s("vendor-stale","the ONE bundle has never been staged (one/vendor is empty) — run `npm run predist`");const g={channel:"npm",current:a.version,latest:null,behind:!1,reason:null,checkedAt:null,cached:!0,action:"none",applier:"npm",instruction:null};try{const e=t.registry.check({current:a.version,cache:t.updateCache,save:t.saveUpdateCache,now:t.now})||{};g.latest=e.latest||null,g.behind=Boolean(e.behind),g.reason=e.reason||null}catch(e){g.reason="unavailable",g.error=String(e&&e.message||e)}try{const e=t.registry.plan({current:a.version,latest:g.latest,behind:g.behind});e&&(g.action=e.action,g.applier=e.applier,g.instruction=e.instruction)}catch{}g.behind&&s("update-available",`${g.current} → ${g.latest} (${g.instruction||"run the channel updater"})`);const v=u&&u.electron||null;t.guiRequested&&!v&&r("gui-without-electron","--gui was requested but Electron is not installed — use --tui");const m=n.filter((e=>"broken"===e.level)).length,y=n.filter((e=>"warn"===e.level)).length,b=m?EXIT.BROKEN:y?EXIT.WARN:EXIT.OK;return{report:{aegis:"one",status:m?"broken":y?"warn":"healthy",exitCode:b,product:a,faces:c,credential:{source:d,found:Boolean(l.key),from:l.key?l.from:""},store:{path:h.path,exists:h.exists,readable:h.exists?!0===h.readable:null},vendor:{staged:p.staged,matched:p.matched,mismatched:p.mismatch.length,missingSource:p.missingSource.length,stale:p.stale},update:g,gui:{requested:Boolean(t.guiRequested),electron:v||null,usable:Boolean(v)&&(!t.guiImplied||t.guiImplied)},problems:n},code:b}}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,s]of Object.entries(e.faces)){const e=s.ok?"":` (expected ${s.expected||"unknown"})`;t.push(` ${n=r,14,String(n)+" ".repeat(Math.max(0,14-String(n).length))} ${s.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(` 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:[],s=n.stdout||process.stdout,o=n.env||process.env||{},a=Object.assign({},n,{env:o,guiRequested:wantsGui(r,o)}),{report:i,code:c}=diagnose(a),l=r.includes("--json")?JSON.stringify(i)+"\n":render(i);try{s.write(l)}catch{}return c}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 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 s;try{s=fs.readdirSync(e,{withFileTypes:!0})}catch{return}for(const o of s){if("node_modules"===o.name||".git"===o.name)continue;const s=path.join(e,o.name);o.isDirectory()?r(s):n.push(path.relative(t,s).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(){let e=null;const t=()=>{if(e)return e;const t=[path.join(repoDir(),"client","update.js"),path.join(oneDir(),"vendor","cli","vendor","client","update.js")];for(const n of t)try{e=require(n);break}catch{}return e};return{check(e){const n=t();return n&&"function"==typeof n.updateNotice?n.updateNotice(e||{}):{latest:null,behind:!1,reason:"unavailable"}},plan(e){const n=t();return n&&"function"==typeof n.updatePlan?n.updatePlan(e||{}):null}}}function defaultStorePath(e){try{const t=require(path.join(repoDir(),"client","prefs.js"));if("function"==typeof t.prefsFile)return t.prefsFile(e)}catch{}const t=homeHint(e)||path.join(e&&e.HOME||"",".aegiscode");return path.join(t,"preferences.json")}function defaultCredentials(){let e=null;return{resolve(t){if(!e)try{e=require(path.join(repoDir(),"client","credentials.js"))}catch{e=null}if(!e||"function"!=typeof e.resolveApiKey)return{key:"",source:"none",from:""};try{return e.resolveApiKey(t||{})}catch{return{key:"",source:"none",from:""}}}}}function vendorPairs(e){const{exists:t}=e,n=[];for(const{face:r,root:s,staged:o}of BUNDLE_FACES){const a=path.join(e.root,o),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(s,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(s,a)),i.push(a);const c=i.find((n=>t(path.join(e.root,n))))||null;n.push({face:r,staged:path.join(o,a),source:c,candidates:i})}}return n}function checkVendor(e,t){const n=t||vendorPairs(e),r=[],s=[];let o=0,a=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){s.push({staged:t.staged,source:t.source,error:String(e&&e.message||e)});continue}n===i?o+=1:s.push({staged:t.staged,source:t.source})}return{staged:a,matched:o,mismatch:s,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(),s=t||{};return{root:t.root||repoDir(),platform:t.platform||"linux",env:n,exists:s.exists||r.exists,readFile:s.readFile||r.readFile,hashFile:s.hashFile||r.hashFile,listFiles:s.listFiles||r.listFiles,credentials:t.credentials||defaultCredentials(),storePath:t.storePath||defaultStorePath(n),registry:t.registry||defaultRegistry(),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}}function diagnose(e){const t=resolveSeams(e),n=[],r=(e,t)=>n.push({level:"broken",code:e,detail:t}),s=(e,t)=>n.push({level:"warn",code:e,detail:t}),o=readJson(t,"one/package.json"),a=o.ok?{name:o.value.name||"aegisone",version:String(o.value.version||"")}:{name:"aegisone",version:""};o.ok||r("product-unreadable","one/package.json "+(o.unreadable?"is unreadable":"is missing"));let i=null;try{i=require("./release.js").deriveFaceVersions(a.version)}catch(e){i=null,o.ok&&r("product-version-invalid",`${a.version}: ${String(e&&e.message||e)}`)}const c={};for(const{dir:e,package:n}of FACE_PACKAGES){const s=readJson(t,`${e}/package.json`),o=s.ok?String(s.value.version||""):"",l=i&&i[n]?i[n].version:null;s.ok?l&&o!==l&&r("version-mismatch",`${n} is ${o}, product ${a.version} derives ${l}`):r("face-unreadable",`${e}/package.json ${s.unreadable?"is unreadable":"is missing"}`),c[n]={dir:e,version:o,expected:l,ok:Boolean(l&&o===l)}}let l={key:"",source:"none",from:""};try{l=t.credentials.resolve({env:t.env})||l}catch{l={key:"",source:"none",from:""}}const u=t.electronPaths||{};let d=l.key?"env"===l.source?"env":(l.source,"env-file"):"none";if(!l.key&&u.keychain&&t.exists(u.keychain)){const e=(()=>{try{return t.readFile(u.keychain)}catch{return null}})();e&&/encrypt|safeStorage/i.test(e)&&(d="keychain")}"none"===d&&s("no-credential","no credential found (env, credentials.json, or the OS keychain)");const h={path:t.storePath,exists:!1,readable:null,legacy:null};try{h.exists=t.exists(t.storePath)}catch{h.exists=!1}let p,f=h.path;if(h.exists){let e=null;try{e=t.readFile(h.path)}catch(e){h.readable=!1,r("store-unreadable",`${h.path}: ${String(e&&e.message||e)}`)}if(null===h.readable)if(null==e)h.readable=!1,r("store-unreadable",`${h.path} exists but could not be read`);else try{const t=JSON.parse(e);h.readable=!0,h.legacy=t&&t.version||null}catch(e){h.readable=!1,r("store-unreadable",`${h.path} is not valid JSON: ${String(e&&e.message||e)}`)}f=path.basename(h.path)}h.display=f;try{p=checkVendor(t,t.vendorPairs)}catch(e){p={staged:0,matched:0,mismatch:[],missingSource:[],stale:!1,checked:0,error:String(e&&e.message||e)},r("vendor-unreadable",p.error)}for(const e of p.mismatch)r("vendor-hash-mismatch",`${e.staged} differs from ${e.source||"its source"}`);for(const e of p.missingSource)r("vendor-source-missing",`${e} has no source to be re-derived from`);p.stale&&s("vendor-stale","the ONE bundle has never been staged (one/vendor is empty) — run `npm run predist`");const g={channel:"npm",current:a.version,latest:null,behind:!1,reason:null,checkedAt:null,cached:!0,action:"none",applier:"npm",instruction:null};try{const e=t.registry.check({current:a.version,cache:t.updateCache,save:t.saveUpdateCache,now:t.now})||{};g.latest=e.latest||null,g.behind=Boolean(e.behind),g.reason=e.reason||null}catch(e){g.reason="unavailable",g.error=String(e&&e.message||e)}try{const e=t.registry.plan({current:a.version,latest:g.latest,behind:g.behind});e&&(g.action=e.action,g.applier=e.applier,g.instruction=e.instruction)}catch{}g.behind&&s("update-available",`${g.current} → ${g.latest} (${g.instruction||"run the channel updater"})`);const v=u&&u.electron||null;t.guiRequested&&!v&&r("gui-without-electron","--gui was requested but Electron is not installed — use --tui");const m=n.filter((e=>"broken"===e.level)).length,y=n.filter((e=>"warn"===e.level)).length,b=m?EXIT.BROKEN:y?EXIT.WARN:EXIT.OK;return{report:{aegis:"one",status:m?"broken":y?"warn":"healthy",exitCode:b,product:a,faces:c,credential:{source:d,found:Boolean(l.key),from:l.key?l.from:""},store:{path:h.path,exists:h.exists,readable:h.exists?!0===h.readable:null},vendor:{staged:p.staged,matched:p.matched,mismatched:p.mismatch.length,missingSource:p.missingSource.length,stale:p.stale},update:g,gui:{requested:Boolean(t.guiRequested),electron:v||null,usable:Boolean(v)&&(!t.guiImplied||t.guiImplied)},problems:n},code:b}}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,s]of Object.entries(e.faces)){const e=s.ok?"":` (expected ${s.expected||"unknown"})`;t.push(` ${n=r,14,String(n)+" ".repeat(Math.max(0,14-String(n).length))} ${s.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(` 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:[],s=n.stdout||process.stdout,o=n.env||process.env||{},a=Object.assign({},n,{env:o,guiRequested:wantsGui(r,o)}),{report:i,code:c}=diagnose(a),l=r.includes("--json")?JSON.stringify(i)+"\n":render(i);try{s.write(l)}catch{}return c}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,6 +1,6 @@
1
1
  # aegiscode — the terminal host
2
2
 
3
- `aegiscode` in your shell — the command-line version of AEGIS Desktop. The same
3
+ `aegiscode` in your shell — the command-line version of AEGIS One. The same
4
4
  tool surface the Claude Code plugin exposes over MCP, plus a terminal instead of
5
5
  an editor — built on the same two shared pieces and no others:
6
6
 
@@ -117,9 +117,9 @@ wins**, so a stale file can never shadow `AEGIS_API_KEY=… aegiscode` in CI; an
117
117
  the loader only ever reads. If the file is group- or world-readable you are told,
118
118
  not silently fixed — the 0600 store stays the only secret this repo writes.
119
119
 
120
- That one file is shared: the MCP plugin and AEGIS Desktop read the same store and
120
+ That one file is shared: the MCP plugin and AEGIS One read the same store and
121
121
  the same `.env`, so signing in here signs you in everywhere (see [One memory,
122
- shared with AEGIS Desktop](#one-memory-shared-with-aegis-desktop)).
122
+ shared with AEGIS One](#one-memory-shared-with-aegis-one)).
123
123
 
124
124
  ## Launch options
125
125
 
@@ -542,7 +542,7 @@ echo "why is the sky blue" | aegiscode -p -
542
542
  ```
543
543
 
544
544
  `/config` writes through the same split every other surface uses: the keys in
545
- `SHARED_PREF_KEYS` go to `preferences.json`, the file AEGIS Desktop's settings
545
+ `SHARED_PREF_KEYS` go to `preferences.json`, the file AEGIS One's settings
546
546
  window reads and writes too, and this shell's own keys (`lastCwd`,
547
547
  `updateCheck`) stay in `config.json`. It never writes a file directly, so it
548
548
  cannot leave the window and the shell holding two answers to one question.
@@ -612,7 +612,7 @@ out, not as "sync failed". Imported remote sessions land in the same store
612
612
  `/resume` reads, and are marked `imported` with estimated token counts — never
613
613
  passed off as measured here.
614
614
 
615
- ## One memory, shared with AEGIS Desktop
615
+ ## One memory, shared with AEGIS One
616
616
 
617
617
  `~/.aegiscode/` is the data dir for **every** AEGIS host — this CLI, AEGIS
618
618
  Desktop and the MCP plugin built on the same account:
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "aegiscode",
3
3
  "productName": "AEGIS Code",
4
- "version": "7.0.34",
5
- "description": "aegiscode — the command-line version of AEGIS Desktop. The shared tool surface in your shell, over the same thin transport and tool registry as the MCP plugin and the desktop app. Ships transport + UI only; no brain.",
4
+ "version": "7.0.36",
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",
8
8
  "email": "nborneklint@gmail.com"
@@ -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{getSize:getSize,span:span,padLine:padLine,paint:paint,w:w,wrapBlock:wrapBlock,hideCursor:hideCursor,showCursor:showCursor,moveTo:moveTo,clearScreen:clearScreen,enterAltScreen:enterAltScreen,leaveAltScreen:leaveAltScreen,enableBracketedPaste:enableBracketedPaste,disableBracketedPaste:disableBracketedPaste,enableMouseTracking:enableMouseTracking,disableMouseTracking:disableMouseTracking,selectionRange:selectionRange,selectionText:selectionText,applySelection:applySelection}=require("./screen.js"),{KEY:KEY,STREAM_END:STREAM_END,attachKeyStream:attachKeyStream,nextKey:nextKey,nextKeyTimeout:nextKeyTimeout,requeueKeys:requeueKeys,resetKeyStream:resetKeyStream,markSessionStart:markSessionStart,isKeyStreamSuspended:isKeyStreamSuspended}=require("./events.js"),{GLYPH:GLYPH,VERBS:VERBS,DONE_VERBS:DONE_VERBS,BOLD:BOLD,BOLD_OFF:BOLD_OFF,themeOf:themeOf,RGB:RGB}=require("./theme.js"),{LineEditor:LineEditor}=require("./input.js"),{renderMarkdown:renderMarkdown}=require("./markdown.js"),overlays=require("./overlays.js"),models=require("./models.js"),{resolveShared:resolveShared}=require("./sharedpaths.js"),{validateApiKey:validateApiKey}=require(resolveShared(require("node:path").join("client","credentials.js"))),sessionSearch=require(resolveShared(require("node:path").join("client","session-search.js"))),claudePro=require(resolveShared(require("node:path").join("desktop","lib","local","claude-pro.js"))),fuzzy=require("./fuzzy.js"),{fmtTokens:fmtTokens,fmtEur:fmtEur,fmtElapsed:fmtElapsed,fmtUsageSplit:fmtUsageSplit,displayTokens:displayTokens,pathName:pathName,feeBillable:feeBillable}=require("./format.js"),{editPreview:editPreview}=require("./diff.js"),{renderDiffBlock:renderDiffBlock,defaultOpen:defaultOpen}=require("./diffview.js"),{copyToClipboard:copyToClipboard,describeCopy:describeCopy,readClipboardText:readClipboardText,readClipboardImage:readClipboardImage}=require("./clipboard.js"),{transcriptToMarkdown:transcriptToMarkdown}=require("./export.js"),fs=require("node:fs"),path=require("node:path"),{aegisDir:aegisDir,loadConfig:loadConfig}=require("./config.js"),{effortRung:effortRung}=require("./engine.js"),{usageBuckets:usageBuckets,estimateTokensFromCells:estimateTokensFromCells}=require("./tokens.js"),{pingTurn:pingTurn}=require("./ping.js"),SUGGESTIONS=["edit <filepath> to...","refactor <filepath>","how do I log an error?","write a test for <filepath>","create a util logging.py that..."],{TITLE_SPIN:TITLE_SPIN,titleText:titleText,topicFrom:topicFrom,adoptTopic:adoptTopic,titleEnabled:titleEnabled,writeTitle:writeTitle}=require("./title.js"),{GENERIC_TITLE:GENERIC_TITLE,isGenericTitle:isGenericTitle}=require("./naming.js"),FRAME_MS=33;function isShellTool(e){return"exec"===e||"Bash"===e}function isAgentTool(e){return"task"===e||"Task"===e}function toolLabel(e,t){const n=isShellTool(e)?"shell command":isAgentTool(e)?"subagent":`${String(e).toLowerCase()} command`;return t>1?n+"s":n}function resolveToolDone(e,t){let n=-1;if(void 0!==t.id)for(let r=e.length-1;r>=0;r--){const o=e[r];if("tool"===o.role&&"run"===o.phase&&o.id===t.id){n=r;break}}if(-1===n)for(let r=e.length-1;r>=0;r--){const o=e[r];if("tool"===o.role&&"run"===o.phase&&o.name===t.name&&o.agent===t.agent){n=r;break}}if(-1===n)return null;const r=e[n],o=e.filter(((e,r)=>"tool"===e.role&&e.name===t.name&&e.agent===t.agent&&r<=n)).length;return r.phase="done",r.elapsed=t.elapsed,r.ok=t.ok,r.label=`Ran ${o} ${r.agent?`${r.agent} ▸ `:""}${toolLabel(t.name,o)}`,r}const MUTATING_FILES=new Set(["Edit","Write","MultiEdit","NotebookEdit","editFile","writeFile"]);function summarizeTurnTools(e,{maxNames:t=3}={}){const n=[],r=[];let o=0;for(const t of e||[]){if(!t)continue;!1===t.ok&&(o+=1);const e=t.args;if(!e||"object"!=typeof e)continue;const s=MUTATING_FILES.has(t.name)?e.file_path||e.path||e.notebook_path:null;"string"==typeof s&&s&&!n.includes(s)&&n.push(s);const i=e.command;if("string"==typeof i&&i.trim()){const e=pathName(i.trim().split(/\s+/)[0]);e&&!r.includes(e)&&r.push(e)}}return{tools:(e||[]).length,failed:o,files:n,names:n.slice(0,t).map((e=>pathName(e))),more:Math.max(0,n.length-t),commands:r}}function finalizeTurnText(e,{aborted:t,error:n,reasoned:r}={}){let o=String(null==e?"":e);if(n&&!t&&"stopped"!==n){const e=`(backend error: ${n})`;o=o.trim()?`${o.trimEnd()}\n\n${e}`:e}return t&&(o=o.trim()?`${o.trimEnd()} (stopped)`:"(stopped)"),o.trim()||(o=r?"(no answer — the model used its whole budget on hidden reasoning before writing one; retry, or raise the budget with /effort)":"(no response)"),o}function historyPairs(e){return e.filter((e=>"user"===e.role||"assistant"===e.role)).map((e=>({role:e.role,content:e.text})))}const PRO_ALIAS_KEYWORDS=Object.freeze(["opus","haiku","sonnet","fable"]);function overrideAnthropicByokWithPro(e,t={}){if(!e||"byok"!==e.cls)return{row:e,message:null};const n=String(e.id||""),r=n.indexOf(":");if(r<0||"anthropic"!==n.slice(0,r).trim().toLowerCase())return{row:e,message:null};if(!t.needsKey)return{row:e,message:null};if(!t.proLoggedIn)return{row:e,message:null};if(!0!==t.proEnabled)return{row:e,message:null};const o=n.slice(r+1).toLowerCase(),s=Array.isArray(t.proModels)&&t.proModels.length?t.proModels:[{id:"default",label:"Default",note:""}],i=PRO_ALIAS_KEYWORDS.find((e=>o.includes(e)))||"default",a=s.find((e=>e.id===i))||s[0];return{row:{id:a.id,label:a.label,note:a.note,cls:"pro"},message:`${n} has no Anthropic console key on this machine, but Claude Code Pro is signed in — using the subscription instead (claude --model ${a.id}). Add a real console key any time with /byok-key anthropic <key> to run this row directly.`}}function paletteQuery(e){const t=String(e||"").trim();return t.includes(" ")?t.split(/\s+/)[0]:t}function headerLine(e,t,n){const r=themeOf(n),o=` AEGIS Code v${e} `,s=Math.max(0,t-[...o].length-2),i=Math.floor(s/2);return[span(r.coral,`╭${"─".repeat(i)}${o}${"─".repeat(s-i)}╮`)]}const separatorLine=(e,t)=>[span(themeOf(t).dim,"─".repeat(e))];function effortLine(e,t){const n=themeOf(e),r=`● ${effortRung(e.effort)} · /effort`,o=" ".repeat(Math.max(0,t-[...r].length-4));return[span(n.gray,o+r)]}const SPINNER_TINT=RGB(235,159,127);function spinnerLine(e,t){const n=themeOf(t),r=Math.max(1,Math.round((e.elapsedMs||0)/1e3)),o=[...e.verb||VERBS[0]],s=Math.floor((e.frame||0)/2)%3,i=o.map(((e,t)=>span((t+s)%3==0?n.coral:SPINNER_TINT,e))),a=t&&t.thinking?span(n.gray,` (${r}s · thinking)`):span(n.gray,` (${r}s · ↓${e.streamedFloor?"≥":""}${fmtTokens(e.streamed||0)} tokens)`),l=GLYPH.spin[(e.frame||0)%GLYPH.spin.length];return[span(n.coral,l),...i,span(n.white,"… "),a]}function statusLine(e,t,n){const r=themeOf(n);let o;return o=e.inputPrompt?[span(r.gray,"enter to confirm · esc to cancel")]:e.working?[span(r.gray,` ${GLYPH.bullet} esc to interrupt`)]:e.streamJob?[span(r.gray,`${GLYPH.bullet} esc to stop`)]:e.keyNotice?[span(r.gray,` ${GLYPH.bullet} no AEGIS key: ${e.keyNotice} ${GLYPH.bullet} /key register to retry`)]:e.yolo?[span(r.gray,`${GLYPH.bullet} automode on ${GLYPH.bullet} ${autoContinueLimit()} rounds then it asks ${GLYPH.bullet} ? for shortcuts ${GLYPH.bullet} ${GLYPH.rightarrow} for manual mode`)]:[span(r.gray,`${GLYPH.pause} manual mode on ${GLYPH.bullet} ? for shortcuts ${GLYPH.bullet} ${GLYPH.rightarrow} for auto mode`)],padLine(o,t)}function shortcutsGrid(e,t){const n=themeOf(t),r=(e,t,r,o)=>[span(""," "),span(n.white,e),span(n.gray," "+t),span(""," "),span(n.white,r),span(n.gray," "+o)];return[r("/","for commands","?","for shortcuts"),r("ctrl + c","to quit","ctrl + o","for permissions"),r("alt + p","to switch model","alt + t","to toggle thinking"),r("shift + ↑/↓","pins as it moves","shift + enter","runs the row"),r("esc","to interrupt a turn","ctrl + l","to clear the screen"),r("ctrl + t","to show tokens","ctrl + r","to resume a session"),r("↑ / ↓","for history","tab","to complete a command")]}const APPROVE_ONCE="once",APPROVE_SESSION="session",DENY_TOKEN="deny",APPROVAL_CHOICES=["Yes","Yes, allow for this session","No"],APPROVAL_DECISIONS=["once","session","deny"];function confirmLines(e,t,n){const r=themeOf(n),o=[];o.push([span(r.gray,"─".repeat(Math.min(Math.max(10,t-4),80)))]),o.push([span(r.white,`${isShellTool(e.name)?"shell":e.name} command`)]),o.push([span("","")]);const s=isShellTool(e.name)?String(e.args&&e.args.command||""):String(e.args&&(e.args.file_path||e.args.pattern)||"");for(const e of wrapBlock(s,Math.max(8,t-4)))o.push([span(r.gray,e)]);o.push([span("","")]),o.push([span(r.white,"Do you want to proceed?")]);const i=e.name||"this tool";return APPROVAL_CHOICES.forEach(((t,n)=>{const s=1===n?`Yes, and allow ${i} for this session`:t;o.push(((t,n)=>{const o=e.sel===t;return[o?span(r.lavender,GLYPH.cursor):span(""," "),span(r.gray,` ${t+1}. `),span(o?r.lavender:r.white,n)]})(n,s))})),o.push([span("","")]),o.push([span(r.gray,"Esc to cancel")]),o}const AUTO_CONTINUE_LIMIT=3;function autoContinueLimit(e=process.env){const t=Number.parseInt(e&&e.AEGIS_AUTO_CONTINUE_MAX,10);return Number.isFinite(t)&&t>0?t:AUTO_CONTINUE_LIMIT}function autoContinuePlan({on:e=!1,used:t=0,limit:n=autoContinueLimit()}={}){const r=Number.isFinite(n)&&n>0?Math.floor(n):AUTO_CONTINUE_LIMIT,o=Number.isFinite(t)&&t>0?Math.floor(t):0;return e?o>=r?{auto:!1,used:0,cap:r}:{auto:!0,used:o+1,cap:r}:{auto:!1,used:o,cap:r}}function roundsLines(e,t,n){const r=themeOf(n),o=[];o.push([span(r.gray,"─".repeat(Math.min(Math.max(10,t-4),80)))]),o.push([span(r.white,`${e.spent}-round tool limit reached`)]),o.push([span("","")]);for(const e of wrapBlock("The turn is still working — it ended its last round on a tool call instead of an answer.",Math.max(8,t-4)))o.push([span(r.gray,e)]);o.push([span("","")]);const s=(t,n)=>{const o=e.sel===t;return[o?span(r.lavender,GLYPH.cursor):span(""," "),span(r.gray,` ${t+1}. `),span(o?r.lavender:r.white,n)]};return o.push(s(0,`Yes, continue with ${e.size} more rounds`)),o.push(s(1,"No, stop here and answer with what I have")),o.push([span("","")]),o.push([span(r.gray,`extension ${e.extensions} of ${e.max} · Esc to stop`)]),o}function metaBits(e,t,{omitMs:n=!1}={}){const r=[];e.model&&r.push(span(t.blue,e.model));const o=fmtUsageSplit(e);if(o)r.push(span(t.white,o.output));else{const n=displayTokens(e);null!=n&&r.push(span(t.white,`${fmtTokens(n)} tokens`))}return null!=e.eur&&feeBillable()&&r.push(span(e.eur>0?t.coral:t.green,fmtEur(e.eur))),null==e.ms||n||r.push(span(t.gray,fmtElapsed(e.ms))),e.calls>1&&r.push(span(t.gray,`${e.calls} calls`)),r}function joinBits(e,t){const n=[];return e.forEach(((e,r)=>{r&&n.push(span(t.dim,` ${GLYPH.bullet} `)),n.push(e)})),n}const DIR_MAX=40;function shortDir(e){let t=String(null==e?"":e).trim().replace(/\/+$/,"");if(!t)return"";const n=String(process.env.HOME||process.env.USERPROFILE||"").replace(/\/+$/,"");return n&&(t===n||t.startsWith(`${n}/`))&&(t=`~${t.slice(n.length)}`),t.length>DIR_MAX&&(t=`${GLYPH.ellipse}${t.slice(-(DIR_MAX-1))}`),t}function rowLines(e,t,n,r=Date.now()){const o=themeOf(n),s=[];if("tool"===e.role){const i=String(e.label||"").replace(/(?:…|\.\.\.)+$/,""),a=e.cwd?` · ${shortDir(e.cwd)}`:"";if("run"===e.phase){const t=e.start?Math.max(1,Math.round((r-e.start)/1e3)):0;s.push([span(o.gray,`${i}${GLYPH.ellipse} · ${t}s${a}`)])}else s.push([span(o.gray,`${i}${a}`)]);if(e.diff){for(const r of renderDiffBlock(e.diff,n,t,{open:!!e.diffOpen}))s.push([span("",r)]);return s}const l="string"==typeof e.args?e.args:e.args&&"object"==typeof e.args?e.args.command??e.args.file_path??e.args.description??Object.values(e.args).find((e=>"string"==typeof e))??"":"";return l&&s.push([span(o.gray,` ${GLYPH.hook} $ ${String(l)}`)]),s}if("note"===e.role)return s.push([span(o.gray,`· ${e.text}`)]),s;if("tip"===e.role){for(const n of wrapBlock(String(e.text),t))s.push([span(o.gray,n)]);return s}if("done"===e.role){const t=[span(o.gray,GLYPH.bloom),span(o.gray,` ${e.text}`)];if(e.meta){const n=metaBits(e.meta,o,{omitMs:!0});n.length&&t.push(span(o.dim," "),...joinBits(n,o))}return s.push(t),s}if("summary"===e.role){const t=e.counts||{};if(!t.tools)return s;const n=[span(o.dim,GLYPH.hook),span(""," ")],r=[span(o.white,String(t.tools)),span(o.gray," "+(1===t.tools?"command":"commands"))];if(t.files&&t.files.length&&(r.push(span(o.gray,` ${GLYPH.bullet} `)),r.push(span(o.white,String(t.files.length)),span(o.gray," "+(1===t.files.length?"file changed":"files changed")))),t.failed&&(r.push(span(o.gray,` ${GLYPH.bullet} `)),r.push(span(o.coral,`${t.failed} failed`))),t.names&&t.names.length){const e=t.more?` +${t.more}`:"";r.push(span(o.dim,` ${t.names.join(", ")}${e}`))}return n.push(...r),s.push(n),s}if("meta"===e.role){const t=metaBits(e.meta||{},o);return t.length&&s.push([span(o.dim,`${GLYPH.hook} `),...joinBits(t,o)]),s}if("panel"===e.role){for(const n of e.lines||[])s.push(padLine(n,t));return s.push([span("","")]),s}if("error"===e.role)return s.push([span(o.red,`✗ ${e.text}`)]),s;if("user"===e.role)return wrapBlock(String(e.text),Math.max(8,t-2)).forEach(((e,t)=>{0===t?s.push([span(o.gray,GLYPH.cursor),span(""," "),span(o.white,e)]):s.push([span(""," "),span(o.white,e)])})),s;const i="assistant"===e.role?renderMarkdown(String(null==e.text?"":e.text),t,n):wrapBlock(String(null==e.text?"":e.text),t).map((e=>[span(o.white,e)])),a=i.length?i:[[span("","")]];for(let e=0;e<a.length;e++){const t=a[e].slice();0===e&&t.unshift(span(o.white,GLYPH.block),span(""," ")),s.push(t)}return s}function transcriptLines(e,t,n,r=Date.now(),o=null){const{cols:s,rows:i}=t,a=Math.max(1,i-6),l=[],u=[];for(const t of e){const e=o||null,i="assistant"===t.role&&t.streaming||"tool"===t.role&&"run"===t.phase;if(!e||i)for(const e of rowLines(t,s,n,r))l.push(e),u.push(t);else{const o=e.get(t);if(o&&o.text===t.text&&o.cols===s&&o.diffOpen===t.diffOpen){for(const e of o.segment)l.push(e),u.push(t);continue}const i=rowLines(t,s,n,r);e.set(t,{text:t.text,cols:s,diffOpen:t.diffOpen,segment:i});for(const e of i)l.push(e),u.push(t)}}let c=t.scroll||0,p=null==t.anchorEnd?null:t.anchorEnd;const d=l.length,f=Math.max(0,d-a);let m;c>f&&(c=f),0===c?(p=null,m=d):(null===p&&(p=Math.max(0,d-c)),m=Math.min(p,d)),d<=a&&(c=0,p=null,m=d);const h=Math.max(0,m-a);return{lines:l.slice(h,m),owners:u.slice(h,m),scroll:c,anchorEnd:p}}function inputPreviewText(e){const t=e.indexOf("\n");if(-1===t)return e;const n=e.split("\n").length-1;return`${e.slice(0,t)} … (+${n} line${1===n?"":"s"})`}const inputRowCells=e=>Math.max(1,e-3),bufCells=e=>[...e].reduce(((e,t)=>e+w(t)),0);function cursorCells(e,t){const n=[...e];let r=0;for(let e=0;e<Math.min(t,n.length);e++)r+=w(n[e]);return r}function inputScroll(e,t,n){const r=inputRowCells(n),o=bufCells(e);if(o<=r)return 0;const s=r-1;return Math.max(0,Math.min(cursorCells(e,t)-s,o-s))}function inputStart(e,t){const n=[...e];let r=0;for(let e=0;e<n.length;e++){if(r>=t)return e;r+=w(n[e])}return n.length}function inputLine(e,t,n){const r=themeOf(n),o=[span(r.gray,GLYPH.cursor),span(""," ")];if(e.inputPrompt){o.push(span(r.white,`${e.inputPrompt.title}: `));for(const t of[...e.inputPrompt.buf])o.push(span(r.white,t));const n=Math.min(3+w(e.inputPrompt.title)+2+w(e.inputPrompt.buf),t);return{line:padLine(o,t),cursorCol:n}}if(e.working)return{line:padLine(o,t),cursorCol:3};const s=e.buf||"";if(!s.length){if(e.insertMode)return{line:padLine(o,t),cursorCol:3};const n=SUGGESTIONS[(e.suggestionIdx||0)%SUGGESTIONS.length];return o.push(span(r.white+BOLD,`Try "${n}"`),span(BOLD_OFF,"")),{line:padLine(o,t),cursorCol:3}}if(s.includes("\n")){const e=inputPreviewText(s);for(const t of[...e])o.push(span(r.white,t));return{line:padLine(o,t),cursorCol:Math.min(3+w(e),t)}}const i=inputScroll(s,e.cursor,t),a=inputStart(s,i);i>0&&o.push(span(r.dim,"…"));const l=[...s];for(let e=a;e<l.length;e++)o.push(span(r.white,l[e]));const u=l.slice(a,Math.min(e.cursor,l.length)).join(""),c=Math.min(3+(i>0?1:0)+w(u),t);return{line:padLine(o,t),cursorCol:c}}async function runSession(e){const t=e.ctx,n=new LineEditor,r=e.transcript,o=new WeakMap;let s=null;function i(t){const n=paletteQuery(null==t?s&&s.query||"":t);return fuzzy.fuzzyRankWithAliases(n,e.visibleCommands(),(e=>e.name),(e=>e.aliases||[]))}let a=0,l=!1,u=null,c=0,p=null,d=0,f=VERBS[0],m=0,h=0,g=[],y=0,E=0,S=null;const v=new Map;let T=null,C=null,L=[],b=!1,k=0,P="",$=null,x=null,O=0,Y=null,I="",K="",R=!1,A=!0;try{A=titleEnabled(process.env,e.loadConfig?e.loadConfig():e.config||{})}catch{A=!0}let M=!1,_=0;const N=e=>{if(!A)return;const t=e?TITLE_SPIN[Math.floor(c/2)%TITLE_SPIN.length]:null;writeTitle(titleText({topic:I,frame:t}),process.stdout)},D=t=>{if("function"!=typeof e.nameConversation)return;let n;R=!0;try{n=Promise.resolve(e.nameConversation(t,{signal:u?u.signal:null}))}catch{return}n.then((e=>{const t=String(e||"").trim();t&&(K=t,I=t,N(!!l),B())})).catch((()=>{}))},G=e=>{P=e,k=Date.now()+2500,setTimeout((()=>{Date.now()>=k&&B()}),2600),B()},B=()=>{if(isKeyStreamSuspended())return;const i=getSize().cols,{lines:a,inputCol:u,rows:p,inputRow:m}=(()=>{const{cols:s,rows:i}=getSize(),a=[];a.push(headerLine(e.version,s,t));const u=Math.max(1,i-6),p=transcriptLines(r,{cols:s,rows:i,scroll:E,anchorEnd:S},t,Date.now(),o);E=p.scroll,S=p.anchorEnd,v.clear();for(let e=0;e<p.lines.length;e++)v.set(1+e,p.owners[e]);for(const e of p.lines)a.push(e);for(;a.length<u+1;)a.push([span("","")]);const m=themeOf(t);if(l)a.push(spinnerLine({verb:f,frame:c,elapsedMs:Date.now()-d,streamed:estimateTokensFromCells(W())+V,streamedFloor:V>0},t));else if(Date.now()<k)a.push([span(m.gray,` ${P}`)]);else if(x){const e=Math.max(1,Math.round((Date.now()-O)/1e3));a.push([span(m.gray,` ${x.label||"running"}… (${e}s · esc to stop)`)])}else a.push(effortLine(t,s));a.push(separatorLine(s,t));const h=inputLine({buf:n.buf,cursor:n.cursor,working:l,insertMode:b,suggestionIdx:y,inputPrompt:$},s,t);return a.push(h.line),a.push(separatorLine(s,t)),a.push(statusLine({working:l,inputPrompt:$,streamJob:x,yolo:e.isYolo&&e.isYolo(),keyNotice:e.keyNotice&&e.keyNotice()},s,t)),{lines:a,inputCol:h.cursorCol,rows:i,inputRow:i-2}})();s&&H(a,p,i),L=a,paint(T?applySelection(a,selectionRange(T.anchor,T.head),i):a),_=Date.now(),s?hideCursor():$||!l?(moveTo(m,u),showCursor()):hideCursor()},q=()=>{if(M)return;M=!0;const e=Math.max(0,33-(Date.now()-_));setTimeout((()=>{M=!1,B()}),e)},H=(n,r,o)=>{if(!s)return;let i=null;if("palette"===s.type?i=overlays.renderPalette(e.visibleCommands(),{query:paletteQuery(s.query),sel:s.sel},o,r):"model"===s.type?i=overlays.renderModelPicker(s.items||[],s.sel||0,o,r,s.current,s.cls||t.modelClass,"function"==typeof e.classLabel?e.classLabel:null):"effort"===s.type?i=overlays.renderEffortPicker(s.sel||0,o,t.effort):"class"===s.type?i=overlays.renderClassPicker(s.items||[],s.sel||0,o,s.current||t.modelClass,"function"==typeof e.classLabel?e.classLabel:null):"provider"===s.type?i=overlays.renderProviderPicker(s.items||[],s.sel||0,o,s.current,s.hint):"resume"===s.type?i=overlays.renderResumeList(s.items||[],s.sel||0,o,r,s.query||""):"shortcuts"===s.type?i=shortcutsGrid(o,t):"confirm"===s.type?i=confirmLines(s,o,t):"rounds"===s.type?i=roundsLines(s,o,t):"panel"===s.type&&(i=s.lines||[]),!i)return;if("shortcuts"===s.type){const e=Math.max(2,r-i.length-1);for(let t=0;t<i.length;t++)n[e+t]=padLine(i[t],o);return void hideCursor()}const a=Math.max(2,Math.floor((r-i.length)/2));for(let e=0;e<i.length;e++)n[a+e]=padLine(i[e],o);hideCursor()},j=(e,t)=>(r.push(e),t&&!1===t.follow||(E=0,S=null),e),F=(e,t)=>{const n=t?r.indexOf(t):-1;return n<0?r.push(e):r.splice(n,0,e),e},U=e=>j({role:"note",text:e},{follow:!1});let z=0,V=0;const W=()=>z;let Q=Promise.resolve();const X=e=>{const t=Q.then(e,e);return Q=t.then((()=>{}),(()=>{})),t},J=async t=>{l=!0,c=0,d=Date.now(),z=0,V=0,h=0,g=[],f=VERBS[m%VERBS.length],I=K||adoptTopic(I,t),(e=>{K?isGenericTitle(K)&&D(e):R||D(e)})(t),u=new AbortController,p=setInterval((()=>{c++,N(!0),c%3==0&&B()}),100),p.unref&&p.unref(),N(!0),j({role:"user",text:t});const n=j({role:"assistant",text:"",streaming:!0});let o=!1;const i={text:e=>{n.text+=e,z+=w(e),q()},reasoning:e=>{o=!0,z+=w(e)},thinkingTokens:e=>{o=!0,V+=e,q()},tool:e=>{if(e&&void 0!==e.id){const t=g.findIndex((t=>t&&void 0!==t.id&&t.id===e.id));t>=0?g[t]=e:g.push(e)}else g.push(e);if("run"===e.phase){const t=++h,r=e.agent?`${e.agent} ▸ `:"",o=editPreview(e.name,e.args,{cwd:e.cwd});F({role:"tool",phase:"run",name:e.name,args:e.args,agent:e.agent,id:e.id,label:`Running ${t} ${r}${toolLabel(e.name,t)}…`,start:Date.now(),diff:o,diffOpen:defaultOpen(o)},n)}else if(!resolveToolDone(r,e)){const t=++h,r=editPreview(e.name,e.args,{cwd:e.cwd});F({role:"tool",phase:"done",name:e.name,args:e.args,agent:e.agent,id:e.id,ok:e.ok,label:`Ran ${t} ${e.agent?`${e.agent} ▸ `:""}${toolLabel(e.name,t)}`,diff:r,diffOpen:defaultOpen(r)},n)}q()},approval:e=>(e=>new Promise((t=>{X((async()=>{s={type:"confirm",name:e.tool||e.name||"tool",args:e.args||{},sel:0,info:e},B();const n=e=>{s=null,B(),t(e)};for(;;){const e=await nextKey();if(e===STREAM_END||!e)return void n("deny");if(e.name===KEY.UP||e.name===KEY.DOWN||e.name===KEY.TAB){const t=e.name===KEY.UP?-1:1;s.sel=(s.sel+t+APPROVAL_CHOICES.length)%APPROVAL_CHOICES.length,B()}else{if(e.name===KEY.ENTER)return void n(APPROVAL_DECISIONS[s.sel]||"deny");if(e.name===KEY.ESC||e.name===KEY.CTRL_C)return void n("deny");if("char"===e.name){const t=String(e.ch).trim(),r=Number(t)-1;if(Number.isInteger(r)&&r>=0&&r<APPROVAL_DECISIONS.length)return void n(APPROVAL_DECISIONS[r])}}}}))})))(e),rounds:t=>(t=>new Promise((n=>{const r=Boolean(e.isYolo&&e.isYolo()),o=autoContinuePlan({on:r,used:a});if(a=o.used,o.auto)return U(`auto: ${t.spent}-round limit reached — continuing automatically (${o.used}/${o.cap}, then it asks).`),B(),void n(!0);r&&(U(`auto: ${o.cap} automatic continuations used — asking you now (answering restarts the block).`),B()),X((async()=>{s={type:"rounds",spent:Number(t.spent)||0,extensions:Number(t.extensions)||1,max:Number(t.max)||8,size:Number(t.size)||Number(t.spent)||0,sel:1},B();const e=e=>{s=null,B(),n(e)};for(;;){const t=await nextKey();if(t===STREAM_END||!t)return void e(!1);if(t.name===KEY.UP||t.name===KEY.DOWN||t.name===KEY.TAB)s.sel=1-s.sel,B();else{if(t.name===KEY.ENTER)return void e(0===s.sel);if(t.name===KEY.ESC||t.name===KEY.CTRL_C)return void e(!1);if("char"===t.name){const n=String(t.ch).trim();if("1"===n)return void e(!0);if("2"===n)return void e(!1)}}}}))})))(t)};let S=null;try{S=await e.ask(t,{history:historyPairs(r),presenter:i,signal:u.signal})}catch(e){S={error:e&&e.message||String(e)}}finally{n.streaming=!1,!String(n.text||"").trim()&&S&&"string"==typeof S.text&&S.text.trim()&&(n.text=S.text),l=!1,clearInterval(p),p=null,N(!1);const r=Math.max(1,Math.round((Date.now()-d)/1e3)),s=!(!u||!u.signal.aborted);n.text=finalizeTurnText(n.text,{aborted:s,error:S&&S.error,reasoned:o}),j({role:"done",text:`${h>0?DONE_VERBS[1]:DONE_VERBS[0]} for ${r}s`},{follow:!1}),S&&S.pooled_notice&&j({role:"note",text:S.pooled_notice},{follow:!1}),y=m+1,m++,u=null;try{const e=loadConfig(),t=pingTurn({stream:process.stdout,mode:e.ping,minSeconds:e.pingMinSeconds,elapsedMs:Date.now()-d,isTTY:!!process.stdout.isTTY,aborted:s});t&&j({role:"note",text:t},{follow:!1})}catch{}e.recordTurn(S);let i=null;try{const t=await e.refreshSpend();i=t?t.lastCost:null}catch{}e.persistTurn&&e.persistTurn(t,S,s?"stopped":S&&S.error?"error":"done",i);const a=S&&S.usage,c=e.tokensFor?e.tokensFor(a):null,f=a?usageBuckets(a):null;j({role:"meta",meta:{model:S&&S.model,tokens:c,input:f?f.input:null,output:f?f.output:null,eur:i,ms:S&&S.ms,calls:S&&S.calls||1}},{follow:!1});const w=summarizeTurnTools(g);w.tools>0&&j({role:"summary",counts:w},{follow:0===E}),B()}},Z=e=>{let r=null;if(e.name===KEY.PAGE_UP)r=5;else if(e.name===KEY.PAGE_DOWN)r=-5;else if("wheel"===e.name)r="up"===e.dir?3:-3;else{if("click"===e.name||"drag"===e.name||"release"===e.name)return!(e=>{const t={col:e.col-1,row:e.row-1};if("click"===e.name)return C=t,!1;if("drag"===e.name)return T?T.head=t:T={anchor:C||t,head:t},C=null,!0;const n=C;C=null;const r=T?selectionRange(T.anchor,T.head):null,o=!(!r||r.startRow===r.endRow&&r.startCol===r.endCol);if(T=null,!o)return(e=>{const t=v.get(e);return!(!t||!t.diff||(t.diffOpen=!t.diffOpen,0))})((n||t).row);const s=selectionText(L,r);if(!s)return!0;const i=copyToClipboard(s,{stdout:process.stdout,env:process.env}),a=s.split("\n").length;return P=describeCopy(i,`Marked ${a} line${1===a?"":"s"}`),k=Date.now()+2500,setTimeout((()=>{Date.now()>=k&&B()}),2600),!0})(e)||(q(),!0);"char"!==e.name||!t.vim||b||n.buf||("j"===e.ch?r=1:"k"===e.ch&&(r=-1))}return null!==r&&(E=Math.max(0,E+r),S=null,q(),!0)},ee=()=>{if(!s||"resume"!==s.type)return;const e=Array.isArray(s.all)?s.all:[];s.items=sessionSearch.rankSessions(s.query||"",e),s.sel=0,B()},te=()=>s?"palette"===s.type?fuzzy.fuzzyRankWithAliases(paletteQuery(s.query),e.visibleCommands(),(e=>e.name),(e=>e.aliases||[])).length:"model"===s.type||"resume"===s.type||"class"===s.type||"provider"===s.type?(s.items||[]).length:"effort"===s.type?overlays.EFFORT_VALUES.length:0:0,ne=async n=>{if(n){{const t=models.modelKeyPlan(n,{hasStored:!!e.hasProviderKey&&!!e.hasProviderKey("anthropic")}),{row:r,message:o}=overrideAnthropicByokWithPro(n,{needsKey:!(!t||!t.needed),proLoggedIn:models.claudeProLoggedIn(),proEnabled:(()=>{try{return!0===loadConfig().proEnabled}catch{return!1}})(),proModels:claudePro.PRO_MODELS});n=r,o&&U(o)}if(n.cls&&"aegis"!==n.cls&&t.modelClass!==n.cls){const e="string"==typeof t.modelClass;if(await ie(`/class ${n.cls}`),e&&t.modelClass!==n.cls)return void U(`${n.id} runs on the ${n.cls} class, and this session is on ${t.modelClass} — run /class ${n.cls}${"pro"===n.cls?" on":""}, then pick it again.`)}t.model=n.id,e.updateConfig({model:n.id,currentModelId:n.id,modelClass:t.modelClass}),U(`model: ${n.id}${"byok"===n.cls?" (byok)":"pro"===n.cls?" (Claude Code Pro)":""}`),await(async t=>{const n=models.modelKeyQueue(t,{accountConfigured:!!e.accountConfigured&&!!e.accountConfigured(),hasStoredFor:t=>!!e.hasProviderKey&&!!e.hasProviderKey(t)});if(!n.length)return;let r=null;try{r=e.makeCommandContext()}catch{r=null}if(r&&"function"==typeof r.readSecret)for(const e of n){const n="account"===e.role?"AEGIS account key":"claude-pro"===e.role?"Claude Code OAuth token (`claude setup-token` mints one)":`${e.provider} key`,o=String(await r.readSecret(`${n} → ${e.env} (kept off screen, Enter to skip): `)||"").trim();if(!o){U(`no key given — ${e.env} is still unset, so ${t.id} will fail until it is.`);continue}const s="account"===e.role?"AEGIS":"claude-pro"===e.role?"Claude Code OAuth":e.provider||"that provider",i=validateApiKey(o,{label:s});if(!i.ok){U(`not saved — ${i.message}. ${e.env} is still unset.`);continue}const a=models.storeModelKey(t,i.key,{env:e.env});a.ok?U(a.changed?a.foreign?`${e.env} saved to ${a.file} (0600) — read only by the Claude Code Pro transport, never exported.`:`${e.env} saved to ${a.file} (0600) — both hosts read that file; nothing to export.`:`${e.env} was already set in ${a.file}.`):U(`could not save the key: ${a.error||"unknown error"}`)}else{const e=n.map((e=>`${e.env}: ${e.why}`)).join(" · ");U(`${t.id} has no key: ${e}. Set the ones above and pick it again.`)}})(n)}},re=async e=>{e&&e.class&&await ie(`/class ${e.class}`)},oe=n=>{const r=overlays.EFFORT_VALUES[n||0];s=null,t.effort=r||"high",e.updateConfig({effort:t.effort}),U(`effort: ${t.effort}`),B()},se=async o=>{if(o)if(s)await(async t=>{const n=s.type;if(t.name===KEY.ESC||t.name===KEY.CTRL_C)return s=null,void B();if("shortcuts"===n||"panel"===n)return s=null,void B();if(t.name!==KEY.TAB||"palette"!==n)if(t.name!==KEY.TAB||"model"!==n&&"effort"!==n&&"class"!==n&&"provider"!==n){if(t.name===KEY.ENTER){if("palette"===n){const e=i()[s.sel||0],t=String(s.query||"").trim().split(/\s+/).slice(1).join(" ");return s=null,B(),void(e&&await ie(t?`/${e.name} ${t}`:`/${e.name}`))}if("model"===n){const e=(s.items||[])[s.sel||0];return s=null,B(),await ne(e),void B()}if("effort"===n)return void oe(s.sel||0);if("class"===n){const e=(s.items||[])[s.sel||0];return s=null,B(),await re(e),void B()}if("provider"===n){const e=(s.items||[])[s.sel||0],t=s.command||"byok-key";return s=null,B(),void(e&&e.id&&await ie(`/${t} ${e.id}`))}if("resume"===n){const t=(s.items||[])[s.sel||0];return s=null,B(),void(t&&e.resumeSession&&await e.resumeSession(t))}return s=null,void B()}if(t.name===KEY.SHIFT_UP||t.name===KEY.SHIFT_DOWN){const e=t.name===KEY.SHIFT_UP?-1:1,r=Math.max(0,te()-1);if(s.sel=Math.min(r,Math.max(0,(s.sel||0)+e)),"model"===n){const e=(s.items||[])[s.sel||0];return s=null,B(),await ne(e),void B()}if("class"===n){const e=(s.items||[])[s.sel||0];return s=null,B(),await re(e),void B()}if("provider"===n){const e=(s.items||[])[s.sel||0],t=s.command||"byok-key";return s=null,B(),void(e&&e.id&&await ie(`/${t} ${e.id}`))}return"effort"===n?void oe(s.sel||0):void B()}if(t.name===KEY.SHIFT_ENTER){if("palette"===n){const e=i()[s.sel||0];return s=null,B(),void(e&&await ie(`/${e.name}`))}if("model"===n){const e=(s.items||[])[s.sel||0];return s=null,B(),await ne(e),void B()}if("class"===n){const e=(s.items||[])[s.sel||0];return s=null,B(),await re(e),void B()}if("provider"===n){const e=(s.items||[])[s.sel||0],t=s.command||"byok-key";return s=null,B(),void(e&&e.id&&await ie(`/${t} ${e.id}`))}return"effort"===n?void oe(s.sel||0):void 0}if(t.name===KEY.UP||t.name===KEY.DOWN){const e=(s.items||[]).length||te(),n=t.name===KEY.UP?-1:1;return s.sel=Math.min(Math.max(0,e-1),Math.max(0,(s.sel||0)+n)),void B()}if("char"===t.name){if("palette"===n)return s.query=(s.query||"")+t.ch,s.sel=0,void B();if("resume"===n)return s.query=(s.query||"")+t.ch,void ee();if("model"===n){const e=parseInt(t.ch,10),n=s.items||[];return void(Number.isFinite(e)&&e>=1&&e<=n.length&&(s.sel=e-1,B()))}if("effort"===n||"class"===n||"provider"===n){const e=parseInt(t.ch,10),n=te();return void(Number.isFinite(e)&&e>=1&&e<=n&&(s.sel=e-1,B()))}}if(t.name===KEY.BACKSPACE&&"resume"===n)return s.query=String(s.query||"").slice(0,-1),void ee();t.name===KEY.BACKSPACE&&"palette"===n&&(s.query=String(s.query||"").slice(0,-1),B())}else{const e="model"===n||"class"===n||"provider"===n?(s.items||[]).length:overlays.EFFORT_VALUES.length;e&&(s.sel=((s.sel||0)+1)%e,B())}else{const e=i()[s.sel||0];e&&(s.query=e.name,s.sel=0,B())}})(o);else{if("char"===o.name&&!n.buf){if("/"===o.ch)return s={type:"palette",query:"",sel:0},void B();if("?"===o.ch)return s={type:"shortcuts"},void B()}if(!t.vim||b||n.buf||"char"!==o.name){if(t.vim&&b&&o.name===KEY.ESC)return b=!1,n.cursor>0&&n.cursor--,void B()}else{const e=o.ch;if("i"===e||"a"===e||"o"===e||"s"===e||"S"===e)return"s"===e&&n.substChar(),"S"===e&&n.substLine(),"a"===e&&n.right(),b=!0,void B();if("h"===e)return n.left(),void B();if("l"===e)return n.right(),void B();if("0"===e)return n.home(),void B();if("$"===e)return n.end(),void B();if("x"===e)return n.delete(),void B();if("D"===e)return n.killToEnd(),void B();if("A"===e)return n.end(),b=!0,void B();if(Z(o))return}if(o.name===KEY.ENTER){const e=n.submit();return Y=null,b=!1,e?void await ie(e):void B()}if(o.name!==KEY.CTRL_V)if(o.name!==KEY.CTRL_B){if("paste"===o.name)return t.vim&&(b=!0),n.insert(String(o.text)),void B();if("char"===o.name)return t.vim&&!b||n.insert(o.ch),void B();if(o.name===KEY.BACKSPACE)return n.backspace(),void B();if(o.name===KEY.DELETE)return n.delete(),void B();if(o.name===KEY.LEFT||o.name===KEY.CTRL_LEFT)return o.name===KEY.CTRL_LEFT?n.wordBack():n.left(),void B();if(o.name!==KEY.RIGHT||n.buf){if(o.name===KEY.RIGHT||o.name===KEY.CTRL_RIGHT)return n.right(),void B();if(o.name===KEY.HOME||o.name===KEY.CTRL_A)return n.home(),void B();if(o.name===KEY.END||o.name===KEY.CTRL_E)return n.end(),void B();if(o.name===KEY.UP)return n.historyUp(),void B();if(o.name===KEY.DOWN)return n.historyDown(),void B();if(o.name===KEY.TAB)return(()=>{const t=n.buf;if(!t.startsWith("/")||t.includes(" "))return!1;const r=t.slice(1),o=e.visibleCommands().flatMap((e=>[e.name,...e.aliases||[]])).filter((e=>e.startsWith(r))).sort();return!!o.length&&(Y&&Y.q===r||(Y={q:r,i:-1}),Y.i=(Y.i+1)%o.length,n.buf="/"+o[Y.i],n.end(),!0)})()||(P=n.buf?"Tab completes commands":"Use alt+t to toggle thinking",k=Date.now()+2500,setTimeout((()=>{Date.now()>=k&&B()}),2600)),void B();if(o.name===KEY.CTRL_U)return n.buf="",n.cursor=0,void B();if(o.name===KEY.CTRL_K)return n.killToEnd(),void B();if(o.name===KEY.CTRL_W)return n.wordBack(),void B();if(o.name===KEY.CTRL_L)return clearScreen(),void B();if(o.name===KEY.CTRL_T)return U(e.tokenSummary?e.tokenSummary():"no token usage yet this session"),void B();if(o.name!==KEY.CTRL_R)if(o.name!==KEY.CTRL_O)if("click"!==o.name&&"drag"!==o.name&&"release"!==o.name)if(o.name!==KEY.PAGE_UP&&o.name!==KEY.PAGE_DOWN&&"wheel"!==o.name)if("alt"!==o.name||"p"!==o.ch){if("alt"===o.name&&"t"===o.ch){const n=!(!0===t.thinking);return t.thinking=n,e.updateConfig({thinking:n}),U("Thinking blocks: "+(n?"expanded":"collapsed")),void B()}if(o.name!==KEY.ESC)return o.name===KEY.CTRL_C?n.buf?(n.buf="",n.cursor=0,void B()):void await ue():void(o.name!==KEY.CTRL_D||n.buf||await ue());n.buf&&(n.buf="",n.cursor=0,B())}else await ie("/model");else Z(o);else Z(o);else await ie("/permissions");else await ie("/resume")}else await ie(e.isYolo&&e.isYolo()?"/automode off":"/automode on")}else(()=>{if(!r.length)return void G("Nothing to copy yet");const e=copyToClipboard(transcriptToMarkdown(r),{stdout:process.stdout,env:process.env});G(describeCopy(e,"Copied the conversation"))})();else(()=>{const e=readClipboardImage({env:process.env});if(e.ok)try{const t=path.join(aegisDir(),"clipboard");fs.mkdirSync(t,{recursive:!0});const r="image/jpeg"===e.mime?"jpg":"png",o=path.join(t,`pasted-${(new Date).toISOString().replace(/[:.]/g,"-")}.${r}`);fs.writeFileSync(o,e.data,{mode:384});const s=n.buf&&!/\s$/.test(n.buf)?" ":"";return n.insert(s+o),void G(`Pasted image → ${o}`)}catch(e){return void G(`Could not save the pasted image: ${e&&e.message||e}`)}const t=readClipboardText({env:process.env});if(t.ok&&t.text)return n.insert(t.text),void G(`Pasted ${t.text.length} character${1===t.text.length?"":"s"} from the clipboard`);G(t.ok?"Clipboard is empty — nothing to paste":`Cannot read the clipboard here (${t.error}) — use your terminal's own paste shortcut instead`)})()}},ie=async t=>{const r=String(t||"").trim();if("?"===r)return s={type:"shortcuts"},void B();(!1===await(async(e,t)=>{try{return await((e,t)=>{const n=[];let r,o,i=!1;return e.then((e=>{i=!0,r=e}),(e=>{i=!0,o=e})),(async()=>{for(;!i;){if(!l||s&&"confirm"===s.type){await new Promise((e=>setTimeout(e,60)));continue}const e=await nextKeyTimeout(120);if(null!==e)if(e.name===KEY.ESC||e.name===KEY.CTRL_C){const e=t&&t();e&&e.abort()}else Z(e)||n.push(e)}if(requeueKeys(n),o)throw o;return r})()})(e(),(()=>u))}catch(e){return j({role:"note",text:`Error: ${e&&e.message||String(e)}`},{follow:!1}),void B()}})((async()=>{if(r.startsWith("/")){const t=(()=>{const t=e.makeCommandContext();return Object.assign(t,{push:(e,t)=>{j(e,t),B()},note:e=>{j({role:"note",text:e}),B()},panel:e=>{j({role:"panel",lines:e||[]}),B()},render:()=>B(),openOverlay:e=>{if(e&&"resume"===e.type){const t=Array.isArray(e.items)?e.items:[];return s={...e,all:t,query:"string"==typeof e.query?e.query:"",items:sessionSearch.rankSessions("string"==typeof e.query?e.query:"",t),sel:0},void B()}s=e,B()},closeOverlay:()=>{s=null,showCursor(),B()},askInput:e=>(e=>new Promise((t=>{$={title:e,buf:""},B(),(async()=>{for(;;){const e=await nextKey();if(!$)return void t(null);if(e.name===KEY.ESC||e.name===KEY.CTRL_C||e.name===KEY.CTRL_D)return $=null,B(),void t(null);if(e.name===KEY.ENTER){const e=$.buf;return $=null,B(),void t(e)}e.name===KEY.BACKSPACE?$.buf=[...$.buf].slice(0,-1).join(""):"char"===e.name?$.buf+=e.ch:"paste"===e.name&&($.buf+=String(e.text).replace(/\n/g," ")),B()}})()})))(e),withWorking:e=>(async e=>{const t=u;l=!0,c=0,d=Date.now(),f=VERBS[m%VERBS.length],u=new AbortController,p=setInterval((()=>{c++,N(!0),c%3==0&&B()}),100),p.unref&&p.unref(),N(!0);try{return await e(u.signal)}finally{l=!1,clearInterval(p),p=null,u=t,N(!1),B()}})(e),runPrompt:async e=>{await J(e)},state:()=>e.buildState(),setInput:e=>{n.buf=String(null==e?"":e),n.end(),B()},exit:()=>e.requestExit(),openStream:e=>{x=e||null,O=Date.now(),B()},closeStream:e=>{e&&x!==e||(x=null),B()},showThemePicker:()=>{e.showThemePicker&&e.showThemePicker(),B()}}),t})();return e.dispatchLine(r,t)}return await J(r),!0}))||e.wantsExit())&&await ue()};let ae=!1,le=null;const ue=()=>{ae||(ae=!0,le&&le(0))},ce=()=>{hideCursor(),paint([]);try{process.stdout.write("")}catch{}try{A&&writeTitle("",process.stdout)}catch{}try{process.stdin.setRawMode(!1)}catch{}disableBracketedPaste(),disableMouseTracking(),leaveAltScreen()};let pe=!1;const de=()=>{if(!pe){pe=!0;try{ce()}catch{}}};process.once("exit",de);const fe=e.stdin||process.stdin;markSessionStart(),attachKeyStream(fe),enableBracketedPaste(),enableMouseTracking(),enterAltScreen(),clearScreen(),hideCursor(),N(!1);const me=()=>B();"win32"!==process.platform?process.on("SIGWINCH",me):process.stdout.on("resize",me);const he=()=>{l&&u?u.abort():ue()};process.on("SIGINT",he);const ge=e=>{ce();try{process.stderr.write(`\nAEGIS Code hit an unexpected error. Your transcript is saved; rerun to continue.\n${e&&e.stack||e}\n`)}catch{}process.exit(1)};process.on("uncaughtException",ge),process.on("unhandledRejection",ge),B();try{return await new Promise((e=>{le=e,(async()=>{for(;!ae;){const e=await nextKey();if(ae)break;if(e===STREAM_END||!e){ue();break}try{await se(e)}catch(e){j({role:"note",text:`Error: ${e&&e.message||String(e)}`},{follow:!1}),B()}}})()}))}finally{ae=!0,process.off("SIGINT",he),"win32"!==process.platform?process.off("SIGWINCH",me):process.stdout.off("resize",me),process.off("uncaughtException",ge),process.off("unhandledRejection",ge),process.off("exit",de),de(),resetKeyStream()}}module.exports={SUGGESTIONS:SUGGESTIONS,TITLE_SPIN:TITLE_SPIN,FRAME_MS:33,toolLabel:toolLabel,resolveToolDone:resolveToolDone,summarizeTurnTools:summarizeTurnTools,finalizeTurnText:finalizeTurnText,historyPairs:historyPairs,overrideAnthropicByokWithPro:overrideAnthropicByokWithPro,paletteQuery:paletteQuery,headerLine:headerLine,separatorLine:separatorLine,effortLine:effortLine,spinnerLine:spinnerLine,statusLine:statusLine,shortcutsGrid:shortcutsGrid,confirmLines:confirmLines,APPROVAL_CHOICES:APPROVAL_CHOICES,APPROVAL_DECISIONS:APPROVAL_DECISIONS,roundsLines:roundsLines,autoContinuePlan:autoContinuePlan,autoContinueLimit:autoContinueLimit,AUTO_CONTINUE_LIMIT:AUTO_CONTINUE_LIMIT,rowLines:rowLines,transcriptLines:transcriptLines,inputPreviewText:inputPreviewText,inputRowCells:inputRowCells,inputScroll:inputScroll,inputStart:inputStart,inputLine:inputLine,runSession:runSession};
3
+ "use strict";const{getSize:getSize,span:span,padLine:padLine,paint:paint,w:w,wrapBlock:wrapBlock,hideCursor:hideCursor,showCursor:showCursor,moveTo:moveTo,clearScreen:clearScreen,enterAltScreen:enterAltScreen,leaveAltScreen:leaveAltScreen,enableBracketedPaste:enableBracketedPaste,disableBracketedPaste:disableBracketedPaste,enableMouseTracking:enableMouseTracking,disableMouseTracking:disableMouseTracking,selectionRange:selectionRange,selectionText:selectionText,applySelection:applySelection}=require("./screen.js"),{KEY:KEY,STREAM_END:STREAM_END,attachKeyStream:attachKeyStream,nextKey:nextKey,nextKeyTimeout:nextKeyTimeout,requeueKeys:requeueKeys,resetKeyStream:resetKeyStream,markSessionStart:markSessionStart,isKeyStreamSuspended:isKeyStreamSuspended}=require("./events.js"),{GLYPH:GLYPH,VERBS:VERBS,DONE_VERBS:DONE_VERBS,BOLD:BOLD,BOLD_OFF:BOLD_OFF,themeOf:themeOf,RGB:RGB}=require("./theme.js"),{LineEditor:LineEditor}=require("./input.js"),{renderMarkdown:renderMarkdown}=require("./markdown.js"),overlays=require("./overlays.js"),models=require("./models.js"),{resolveShared:resolveShared}=require("./sharedpaths.js"),{validateApiKey:validateApiKey}=require(resolveShared(require("node:path").join("client","credentials.js"))),sessionSearch=require(resolveShared(require("node:path").join("client","session-search.js"))),claudePro=require(resolveShared(require("node:path").join("desktop","lib","local","claude-pro.js"))),fuzzy=require("./fuzzy.js"),{fmtTokens:fmtTokens,fmtEur:fmtEur,fmtElapsed:fmtElapsed,fmtUsageSplit:fmtUsageSplit,displayTokens:displayTokens,pathName:pathName,feeBillable:feeBillable}=require("./format.js"),{editPreview:editPreview}=require("./diff.js"),{renderDiffBlock:renderDiffBlock,defaultOpen:defaultOpen}=require("./diffview.js"),{copyToClipboard:copyToClipboard,describeCopy:describeCopy,readClipboardText:readClipboardText,readClipboardImage:readClipboardImage}=require("./clipboard.js"),{transcriptToMarkdown:transcriptToMarkdown}=require("./export.js"),fs=require("node:fs"),path=require("node:path"),{aegisDir:aegisDir,loadConfig:loadConfig}=require("./config.js"),{effortRung:effortRung}=require("./engine.js"),{usageBuckets:usageBuckets,estimateTokensFromCells:estimateTokensFromCells}=require("./tokens.js"),{pingTurn:pingTurn}=require("./ping.js"),SUGGESTIONS=["edit <filepath> to...","refactor <filepath>","how do I log an error?","write a test for <filepath>","create a util logging.py that..."],{TITLE_SPIN:TITLE_SPIN,titleText:titleText,topicFrom:topicFrom,adoptTopic:adoptTopic,titleEnabled:titleEnabled,writeTitle:writeTitle}=require("./title.js"),{GENERIC_TITLE:GENERIC_TITLE,isGenericTitle:isGenericTitle}=require("./naming.js"),FRAME_MS=33;function isShellTool(e){return"exec"===e||"Bash"===e}function isAgentTool(e){return"task"===e||"Task"===e}function toolLabel(e,t){const n=isShellTool(e)?"shell command":isAgentTool(e)?"subagent":`${String(e).toLowerCase()} command`;return t>1?n+"s":n}function resolveToolDone(e,t){let n=-1;if(void 0!==t.id)for(let r=e.length-1;r>=0;r--){const o=e[r];if("tool"===o.role&&"run"===o.phase&&o.id===t.id){n=r;break}}if(-1===n)for(let r=e.length-1;r>=0;r--){const o=e[r];if("tool"===o.role&&"run"===o.phase&&o.name===t.name&&o.agent===t.agent){n=r;break}}if(-1===n)return null;const r=e[n],o=e.filter(((e,r)=>"tool"===e.role&&e.name===t.name&&e.agent===t.agent&&r<=n)).length;return r.phase="done",r.elapsed=t.elapsed,r.ok=t.ok,r.label=`Ran ${o} ${r.agent?`${r.agent} ▸ `:""}${toolLabel(t.name,o)}`,r}const MUTATING_FILES=new Set(["Edit","Write","MultiEdit","NotebookEdit","editFile","writeFile"]);function summarizeTurnTools(e,{maxNames:t=3}={}){const n=[],r=[];let o=0;for(const t of e||[]){if(!t)continue;!1===t.ok&&(o+=1);const e=t.args;if(!e||"object"!=typeof e)continue;const s=MUTATING_FILES.has(t.name)?e.file_path||e.path||e.notebook_path:null;"string"==typeof s&&s&&!n.includes(s)&&n.push(s);const i=e.command;if("string"==typeof i&&i.trim()){const e=pathName(i.trim().split(/\s+/)[0]);e&&!r.includes(e)&&r.push(e)}}return{tools:(e||[]).length,failed:o,files:n,names:n.slice(0,t).map((e=>pathName(e))),more:Math.max(0,n.length-t),commands:r}}function finalizeTurnText(e,{aborted:t,error:n,reasoned:r}={}){let o=String(null==e?"":e);if(n&&!t&&"stopped"!==n){const e=`(backend error: ${n})`;o=o.trim()?`${o.trimEnd()}\n\n${e}`:e}return t&&(o=o.trim()?`${o.trimEnd()} (stopped)`:"(stopped)"),o.trim()||(o=r?"(no answer — the model used its whole budget on hidden reasoning before writing one; retry, or raise the budget with /effort)":"(no response)"),o}function historyPairs(e){return e.filter((e=>"user"===e.role||"assistant"===e.role)).map((e=>({role:e.role,content:e.text})))}const PRO_ALIAS_KEYWORDS=Object.freeze(["opus","haiku","sonnet","fable"]);function overrideAnthropicByokWithPro(e,t={}){if(!e||"byok"!==e.cls)return{row:e,message:null};const n=String(e.id||""),r=n.indexOf(":");if(r<0||"anthropic"!==n.slice(0,r).trim().toLowerCase())return{row:e,message:null};if(!t.needsKey)return{row:e,message:null};if(!t.proLoggedIn)return{row:e,message:null};if(!0!==t.proEnabled)return{row:e,message:null};const o=n.slice(r+1).toLowerCase(),s=Array.isArray(t.proModels)&&t.proModels.length?t.proModels:[{id:"default",label:"Default",note:""}],i=PRO_ALIAS_KEYWORDS.find((e=>o.includes(e)))||"default",a=s.find((e=>e.id===i))||s[0];return{row:{id:a.id,label:a.label,note:a.note,cls:"pro"},message:`${n} has no Anthropic console key on this machine, but Claude Code Pro is signed in — using the subscription instead (claude --model ${a.id}). Add a real console key any time with /byok-key anthropic <key> to run this row directly.`}}function paletteQuery(e){const t=String(e||"").trim();return t.includes(" ")?t.split(/\s+/)[0]:t}function headerLine(e,t,n){const r=themeOf(n),o=` AEGIS Code v${e} `,s=Math.max(0,t-[...o].length-2),i=Math.floor(s/2);return[span(r.coral,`╭${"─".repeat(i)}${o}${"─".repeat(s-i)}╮`)]}const separatorLine=(e,t)=>[span(themeOf(t).dim,"─".repeat(e))];function effortLine(e,t){const n=themeOf(e),r=`● ${effortRung(e.effort)} · /effort`,o=" ".repeat(Math.max(0,t-[...r].length-4));return[span(n.gray,o+r)]}const SPINNER_TINT=RGB(235,159,127);function spinnerLine(e,t){const n=themeOf(t),r=Math.max(1,Math.round((e.elapsedMs||0)/1e3)),o=[...e.verb||VERBS[0]],s=Math.floor((e.frame||0)/2)%3,i=o.map(((e,t)=>span((t+s)%3==0?n.coral:SPINNER_TINT,e))),a=t&&t.thinking?span(n.gray,` (${r}s · thinking)`):span(n.gray,` (${r}s · ↓${e.streamedFloor?"≥":""}${fmtTokens(e.streamed||0)} tokens)`),l=GLYPH.spin[(e.frame||0)%GLYPH.spin.length];return[span(n.coral,l),...i,span(n.white,"… "),a]}function statusLine(e,t,n){const r=themeOf(n);let o;return o=e.inputPrompt?[span(r.gray,"enter to confirm · esc to cancel")]:e.working?[span(r.gray,` ${GLYPH.bullet} esc to interrupt`)]:e.streamJob?[span(r.gray,`${GLYPH.bullet} esc to stop`)]:e.keyNotice?[span(r.gray,` ${GLYPH.bullet} no AEGIS key: ${e.keyNotice} ${GLYPH.bullet} /key register to retry`)]:e.yolo?[span(r.gray,`${GLYPH.bullet} automode on ${GLYPH.bullet} ${autoContinueLimit()} rounds then it asks ${GLYPH.bullet} ? for shortcuts ${GLYPH.bullet} ${GLYPH.rightarrow} for manual mode`)]:[span(r.gray,`${GLYPH.pause} manual mode on ${GLYPH.bullet} ? for shortcuts ${GLYPH.bullet} ${GLYPH.rightarrow} for auto mode`)],padLine(o,t)}function shortcutsGrid(e,t){const n=themeOf(t),r=(e,t,r,o)=>[span(""," "),span(n.white,e),span(n.gray," "+t),span(""," "),span(n.white,r),span(n.gray," "+o)];return[r("/","for commands","?","for shortcuts"),r("ctrl + c","to quit","ctrl + o","for permissions"),r("alt + p","to switch model","alt + t","to toggle thinking"),r("shift + ↑/↓","pins as it moves","shift + enter","runs the row"),r("esc","to interrupt a turn","ctrl + l","to clear the screen"),r("ctrl + t","to show tokens","ctrl + r","to resume a session"),r("↑ / ↓","for history","tab","to complete a command")]}const APPROVE_ONCE="once",APPROVE_SESSION="session",DENY_TOKEN="deny",APPROVAL_CHOICES=["Yes","Yes, allow for this session","No"],APPROVAL_DECISIONS=["once","session","deny"];function confirmLines(e,t,n){const r=themeOf(n),o=[];o.push([span(r.gray,"─".repeat(Math.min(Math.max(10,t-4),80)))]),o.push([span(r.white,`${isShellTool(e.name)?"shell":e.name} command`)]),o.push([span("","")]);const s=isShellTool(e.name)?String(e.args&&e.args.command||""):String(e.args&&(e.args.file_path||e.args.pattern)||"");for(const e of wrapBlock(s,Math.max(8,t-4)))o.push([span(r.gray,e)]);o.push([span("","")]),o.push([span(r.white,"Do you want to proceed?")]);const i=e.name||"this tool";return APPROVAL_CHOICES.forEach(((t,n)=>{const s=1===n?`Yes, and allow ${i} for this session`:t;o.push(((t,n)=>{const o=e.sel===t;return[o?span(r.lavender,GLYPH.cursor):span(""," "),span(r.gray,` ${t+1}. `),span(o?r.lavender:r.white,n)]})(n,s))})),o.push([span("","")]),o.push([span(r.gray,"Esc to cancel")]),o}const AUTO_CONTINUE_LIMIT=3;function autoContinueLimit(e=process.env){const t=Number.parseInt(e&&e.AEGIS_AUTO_CONTINUE_MAX,10);return Number.isFinite(t)&&t>0?t:AUTO_CONTINUE_LIMIT}function autoContinuePlan({on:e=!1,used:t=0,limit:n=autoContinueLimit()}={}){const r=Number.isFinite(n)&&n>0?Math.floor(n):AUTO_CONTINUE_LIMIT,o=Number.isFinite(t)&&t>0?Math.floor(t):0;return e?o>=r?{auto:!1,used:0,cap:r}:{auto:!0,used:o+1,cap:r}:{auto:!1,used:o,cap:r}}function roundsLines(e,t,n){const r=themeOf(n),o=[];o.push([span(r.gray,"─".repeat(Math.min(Math.max(10,t-4),80)))]),o.push([span(r.white,`${e.spent}-round tool limit reached`)]),o.push([span("","")]);for(const e of wrapBlock("The turn is still working — it ended its last round on a tool call instead of an answer.",Math.max(8,t-4)))o.push([span(r.gray,e)]);o.push([span("","")]);const s=(t,n)=>{const o=e.sel===t;return[o?span(r.lavender,GLYPH.cursor):span(""," "),span(r.gray,` ${t+1}. `),span(o?r.lavender:r.white,n)]};return o.push(s(0,`Yes, continue with ${e.size} more rounds`)),o.push(s(1,"No, stop here and answer with what I have")),o.push([span("","")]),o.push([span(r.gray,`extension ${e.extensions} of ${e.max} · Esc to stop`)]),o}function metaBits(e,t,{omitMs:n=!1}={}){const r=[];e.model&&r.push(span(t.blue,e.model));const o=fmtUsageSplit(e);if(o)r.push(span(t.white,o.output));else{const n=displayTokens(e);null!=n&&r.push(span(t.white,`${fmtTokens(n)} tokens`))}return null!=e.eur&&feeBillable()&&r.push(span(e.eur>0?t.coral:t.green,fmtEur(e.eur))),null==e.ms||n||r.push(span(t.gray,fmtElapsed(e.ms))),e.calls>1&&r.push(span(t.gray,`${e.calls} calls`)),r}function joinBits(e,t){const n=[];return e.forEach(((e,r)=>{r&&n.push(span(t.dim,` ${GLYPH.bullet} `)),n.push(e)})),n}const DIR_MAX=40;function shortDir(e){let t=String(null==e?"":e).trim().replace(/\/+$/,"");if(!t)return"";const n=String(process.env.HOME||process.env.USERPROFILE||"").replace(/\/+$/,"");return n&&(t===n||t.startsWith(`${n}/`))&&(t=`~${t.slice(n.length)}`),t.length>DIR_MAX&&(t=`${GLYPH.ellipse}${t.slice(-(DIR_MAX-1))}`),t}function rowLines(e,t,n,r=Date.now()){const o=themeOf(n),s=[];if("tool"===e.role){const i=String(e.label||"").replace(/(?:…|\.\.\.)+$/,""),a=e.cwd?` · ${shortDir(e.cwd)}`:"";if("run"===e.phase){const t=e.start?Math.max(1,Math.round((r-e.start)/1e3)):0;s.push([span(o.gray,`${i}${GLYPH.ellipse} · ${t}s${a}`)])}else s.push([span(o.gray,`${i}${a}`)]);if(e.diff){for(const r of renderDiffBlock(e.diff,n,t,{open:!!e.diffOpen}))s.push([span("",r)]);return s}const l="string"==typeof e.args?e.args:e.args&&"object"==typeof e.args?e.args.command??e.args.file_path??e.args.description??Object.values(e.args).find((e=>"string"==typeof e))??"":"";return l&&s.push([span(o.gray,` ${GLYPH.hook} $ ${String(l)}`)]),s}if("note"===e.role)return s.push([span(o.gray,`· ${e.text}`)]),s;if("tip"===e.role){for(const n of wrapBlock(String(e.text),t))s.push([span(o.gray,n)]);return s}if("done"===e.role){const t=[span(o.gray,GLYPH.bloom),span(o.gray,` ${e.text}`)];if(e.meta){const n=metaBits(e.meta,o,{omitMs:!0});n.length&&t.push(span(o.dim," "),...joinBits(n,o))}return s.push(t),s}if("summary"===e.role){const t=e.counts||{};if(!t.tools)return s;const n=[span(o.dim,GLYPH.hook),span(""," ")],r=[span(o.white,String(t.tools)),span(o.gray," "+(1===t.tools?"command":"commands"))];if(t.files&&t.files.length&&(r.push(span(o.gray,` ${GLYPH.bullet} `)),r.push(span(o.white,String(t.files.length)),span(o.gray," "+(1===t.files.length?"file changed":"files changed")))),t.failed&&(r.push(span(o.gray,` ${GLYPH.bullet} `)),r.push(span(o.coral,`${t.failed} failed`))),t.names&&t.names.length){const e=t.more?` +${t.more}`:"";r.push(span(o.dim,` ${t.names.join(", ")}${e}`))}return n.push(...r),s.push(n),s}if("meta"===e.role){const t=metaBits(e.meta||{},o);return t.length&&s.push([span(o.dim,`${GLYPH.hook} `),...joinBits(t,o)]),s}if("panel"===e.role){for(const n of e.lines||[])s.push(padLine(n,t));return s.push([span("","")]),s}if("error"===e.role)return s.push([span(o.red,`✗ ${e.text}`)]),s;if("user"===e.role)return wrapBlock(String(e.text),Math.max(8,t-2)).forEach(((e,t)=>{0===t?s.push([span(o.gray,GLYPH.cursor),span(""," "),span(o.white,e)]):s.push([span(""," "),span(o.white,e)])})),s;const i="assistant"===e.role?renderMarkdown(String(null==e.text?"":e.text),t,n):wrapBlock(String(null==e.text?"":e.text),t).map((e=>[span(o.white,e)])),a=i.length?i:[[span("","")]];for(let e=0;e<a.length;e++){const t=a[e].slice();0===e&&t.unshift(span(o.white,GLYPH.block),span(""," ")),s.push(t)}return s}function transcriptLines(e,t,n,r=Date.now(),o=null){const{cols:s,rows:i}=t,a=Math.max(1,i-6),l=[],u=[];for(const t of e){const e=o||null,i="assistant"===t.role&&t.streaming||"tool"===t.role&&"run"===t.phase;if(!e||i)for(const e of rowLines(t,s,n,r))l.push(e),u.push(t);else{const o=e.get(t);if(o&&o.text===t.text&&o.cols===s&&o.diffOpen===t.diffOpen){for(const e of o.segment)l.push(e),u.push(t);continue}const i=rowLines(t,s,n,r);e.set(t,{text:t.text,cols:s,diffOpen:t.diffOpen,segment:i});for(const e of i)l.push(e),u.push(t)}}let c=t.scroll||0,p=null==t.anchorEnd?null:t.anchorEnd;const d=l.length,f=Math.max(0,d-a);let m;c>f&&(c=f),0===c?(p=null,m=d):(null===p&&(p=Math.max(0,d-c)),m=Math.min(p,d)),d<=a&&(c=0,p=null,m=d);const h=Math.max(0,m-a);return{lines:l.slice(h,m),owners:u.slice(h,m),scroll:c,anchorEnd:p}}function inputPreviewText(e){const t=e.indexOf("\n");if(-1===t)return e;const n=e.split("\n").length-1;return`${e.slice(0,t)} … (+${n} line${1===n?"":"s"})`}const inputRowCells=e=>Math.max(1,e-3),bufCells=e=>[...e].reduce(((e,t)=>e+w(t)),0);function cursorCells(e,t){const n=[...e];let r=0;for(let e=0;e<Math.min(t,n.length);e++)r+=w(n[e]);return r}function inputScroll(e,t,n){const r=inputRowCells(n),o=bufCells(e);if(o<=r)return 0;const s=r-1;return Math.max(0,Math.min(cursorCells(e,t)-s,o-s))}function inputStart(e,t){const n=[...e];let r=0;for(let e=0;e<n.length;e++){if(r>=t)return e;r+=w(n[e])}return n.length}function inputLine(e,t,n){const r=themeOf(n),o=[span(r.gray,GLYPH.cursor),span(""," ")];if(e.inputPrompt){o.push(span(r.white,`${e.inputPrompt.title}: `));for(const t of[...e.inputPrompt.buf])o.push(span(r.white,t));const n=Math.min(3+w(e.inputPrompt.title)+2+w(e.inputPrompt.buf),t);return{line:padLine(o,t),cursorCol:n}}if(e.working)return{line:padLine(o,t),cursorCol:3};const s=e.buf||"";if(!s.length){if(e.insertMode)return{line:padLine(o,t),cursorCol:3};const n=SUGGESTIONS[(e.suggestionIdx||0)%SUGGESTIONS.length];return o.push(span(r.white+BOLD,`Try "${n}"`),span(BOLD_OFF,"")),{line:padLine(o,t),cursorCol:3}}if(s.includes("\n")){const e=inputPreviewText(s);for(const t of[...e])o.push(span(r.white,t));return{line:padLine(o,t),cursorCol:Math.min(3+w(e),t)}}const i=inputScroll(s,e.cursor,t),a=inputStart(s,i);i>0&&o.push(span(r.dim,"…"));const l=[...s];for(let e=a;e<l.length;e++)o.push(span(r.white,l[e]));const u=l.slice(a,Math.min(e.cursor,l.length)).join(""),c=Math.min(3+(i>0?1:0)+w(u),t);return{line:padLine(o,t),cursorCol:c}}async function runSession(e){const t=e.ctx,n=new LineEditor,r=e.transcript,o=new WeakMap;let s=null;function i(t){const n=paletteQuery(null==t?s&&s.query||"":t);return fuzzy.fuzzyRankWithAliases(n,e.visibleCommands(),(e=>e.name),(e=>e.aliases||[]))}let a=0,l=!1,u=null,c=0,p=null,d=0,f=VERBS[0],m=0,h=0,g=[],y=0,E=0,S=null;const v=new Map;let T=null,C=null,L=[],b=!1,k=0,P="",$=null,x=null,O=0,Y=null,I="",K="",R=!1,A=!0;try{A=titleEnabled(process.env,e.loadConfig?e.loadConfig():e.config||{})}catch{A=!0}let M=!1,_=0;const N=e=>{if(!A)return;const t=e?TITLE_SPIN[Math.floor(c/2)%TITLE_SPIN.length]:null;writeTitle(titleText({topic:I,frame:t}),process.stdout)},D=t=>{if("function"!=typeof e.nameConversation)return;let n;R=!0;try{n=Promise.resolve(e.nameConversation(t,{signal:u?u.signal:null}))}catch{return}n.then((e=>{const t=String(e||"").trim();t&&(K=t,I=t,N(!!l),B())})).catch((()=>{}))},G=e=>{P=e,k=Date.now()+2500,setTimeout((()=>{Date.now()>=k&&B()}),2600),B()},B=()=>{if(isKeyStreamSuspended())return;const i=getSize().cols,{lines:a,inputCol:u,rows:p,inputRow:m}=(()=>{const{cols:s,rows:i}=getSize(),a=[];a.push(headerLine(e.version,s,t));const u=Math.max(1,i-6),p=transcriptLines(r,{cols:s,rows:i,scroll:E,anchorEnd:S},t,Date.now(),o);E=p.scroll,S=p.anchorEnd,v.clear();for(let e=0;e<p.lines.length;e++)v.set(1+e,p.owners[e]);for(const e of p.lines)a.push(e);for(;a.length<u+1;)a.push([span("","")]);const m=themeOf(t);if(l)a.push(spinnerLine({verb:f,frame:c,elapsedMs:Date.now()-d,streamed:estimateTokensFromCells(W())+V,streamedFloor:V>0},t));else if(Date.now()<k)a.push([span(m.gray,` ${P}`)]);else if(x){const e=Math.max(1,Math.round((Date.now()-O)/1e3));a.push([span(m.gray,` ${x.label||"running"}… (${e}s · esc to stop)`)])}else a.push(effortLine(t,s));a.push(separatorLine(s,t));const h=inputLine({buf:n.buf,cursor:n.cursor,working:l,insertMode:b,suggestionIdx:y,inputPrompt:$},s,t);return a.push(h.line),a.push(separatorLine(s,t)),a.push(statusLine({working:l,inputPrompt:$,streamJob:x,yolo:e.isYolo&&e.isYolo(),keyNotice:e.keyNotice&&e.keyNotice()},s,t)),{lines:a,inputCol:h.cursorCol,rows:i,inputRow:i-2}})();s&&H(a,p,i),L=a,paint(T?applySelection(a,selectionRange(T.anchor,T.head),i):a),_=Date.now(),s?hideCursor():$||!l?(moveTo(m,u),showCursor()):hideCursor()},q=()=>{if(M)return;M=!0;const e=Math.max(0,33-(Date.now()-_));setTimeout((()=>{M=!1,B()}),e)},H=(n,r,o)=>{if(!s)return;let i=null;if("palette"===s.type?i=overlays.renderPalette(e.visibleCommands(),{query:paletteQuery(s.query),sel:s.sel},o,r):"model"===s.type?i=overlays.renderModelPicker(s.items||[],s.sel||0,o,r,s.current,s.cls||t.modelClass,"function"==typeof e.classLabel?e.classLabel:null):"effort"===s.type?i=overlays.renderEffortPicker(s.sel||0,o,t.effort):"class"===s.type?i=overlays.renderClassPicker(s.items||[],s.sel||0,o,s.current||t.modelClass,"function"==typeof e.classLabel?e.classLabel:null):"provider"===s.type?i=overlays.renderProviderPicker(s.items||[],s.sel||0,o,s.current,s.hint):"resume"===s.type?i=overlays.renderResumeList(s.items||[],s.sel||0,o,r,s.query||""):"shortcuts"===s.type?i=shortcutsGrid(o,t):"confirm"===s.type?i=confirmLines(s,o,t):"rounds"===s.type?i=roundsLines(s,o,t):"panel"===s.type&&(i=s.lines||[]),!i)return;if("shortcuts"===s.type){const e=Math.max(2,r-i.length-1);for(let t=0;t<i.length;t++)n[e+t]=padLine(i[t],o);return void hideCursor()}const a=Math.max(2,Math.floor((r-i.length)/2));for(let e=0;e<i.length;e++)n[a+e]=padLine(i[e],o);hideCursor()},j=(e,t)=>(r.push(e),t&&!1===t.follow||(E=0,S=null),e),F=(e,t)=>{const n=t?r.indexOf(t):-1;return n<0?r.push(e):r.splice(n,0,e),e},U=e=>j({role:"note",text:e},{follow:!1});let z=0,V=0;const W=()=>z;let Q=Promise.resolve();const X=e=>{const t=Q.then(e,e);return Q=t.then((()=>{}),(()=>{})),t},J=async t=>{l=!0,c=0,d=Date.now(),z=0,V=0,h=0,g=[],f=VERBS[m%VERBS.length],I=K||adoptTopic(I,t),(e=>{K?isGenericTitle(K)&&D(e):R||D(e)})(t),u=new AbortController,p=setInterval((()=>{c++,N(!0),c%3==0&&B()}),100),p.unref&&p.unref(),N(!0),j({role:"user",text:t});const n=j({role:"assistant",text:"",streaming:!0});let o=!1;const i={text:e=>{n.text+=e,z+=w(e),q()},reasoning:e=>{o=!0,z+=w(e)},thinkingTokens:e=>{o=!0,V+=e,q()},tool:e=>{if(e&&void 0!==e.id){const t=g.findIndex((t=>t&&void 0!==t.id&&t.id===e.id));t>=0?g[t]=e:g.push(e)}else g.push(e);if("run"===e.phase){const t=++h,r=e.agent?`${e.agent} ▸ `:"",o=editPreview(e.name,e.args,{cwd:e.cwd});F({role:"tool",phase:"run",name:e.name,args:e.args,agent:e.agent,id:e.id,label:`Running ${t} ${r}${toolLabel(e.name,t)}…`,start:Date.now(),diff:o,diffOpen:defaultOpen(o)},n)}else if(!resolveToolDone(r,e)){const t=++h,r=editPreview(e.name,e.args,{cwd:e.cwd});F({role:"tool",phase:"done",name:e.name,args:e.args,agent:e.agent,id:e.id,ok:e.ok,label:`Ran ${t} ${e.agent?`${e.agent} ▸ `:""}${toolLabel(e.name,t)}`,diff:r,diffOpen:defaultOpen(r)},n)}q()},approval:e=>(e=>new Promise((t=>{X((async()=>{s={type:"confirm",name:e.tool||e.name||"tool",args:e.args||{},sel:0,info:e},B();const n=e=>{s=null,B(),t(e)};for(;;){const e=await nextKey();if(e===STREAM_END||!e)return void n("deny");if(e.name===KEY.UP||e.name===KEY.DOWN||e.name===KEY.TAB){const t=e.name===KEY.UP?-1:1;s.sel=(s.sel+t+APPROVAL_CHOICES.length)%APPROVAL_CHOICES.length,B()}else{if(e.name===KEY.ENTER)return void n(APPROVAL_DECISIONS[s.sel]||"deny");if(e.name===KEY.ESC||e.name===KEY.CTRL_C)return void n("deny");if("char"===e.name){const t=String(e.ch).trim(),r=Number(t)-1;if(Number.isInteger(r)&&r>=0&&r<APPROVAL_DECISIONS.length)return void n(APPROVAL_DECISIONS[r])}}}}))})))(e),rounds:t=>(t=>new Promise((n=>{const r=Boolean(e.isYolo&&e.isYolo()),o=autoContinuePlan({on:r,used:a});if(a=o.used,o.auto)return U(`auto: ${t.spent}-round limit reached — continuing automatically (${o.used}/${o.cap}, then it asks).`),B(),void n(!0);r&&(U(`auto: ${o.cap} automatic continuations used — asking you now (answering restarts the block).`),B()),X((async()=>{s={type:"rounds",spent:Number(t.spent)||0,extensions:Number(t.extensions)||1,max:Number(t.max)||8,size:Number(t.size)||Number(t.spent)||0,sel:1},B();const e=e=>{s=null,B(),n(e)};for(;;){const t=await nextKey();if(t===STREAM_END||!t)return void e(!1);if(t.name===KEY.UP||t.name===KEY.DOWN||t.name===KEY.TAB)s.sel=1-s.sel,B();else{if(t.name===KEY.ENTER)return void e(0===s.sel);if(t.name===KEY.ESC||t.name===KEY.CTRL_C)return void e(!1);if("char"===t.name){const n=String(t.ch).trim();if("1"===n)return void e(!0);if("2"===n)return void e(!1)}}}}))})))(t)};let S=null;try{S=await e.ask(t,{history:historyPairs(r),presenter:i,signal:u.signal})}catch(e){S={error:e&&e.message||String(e)}}finally{n.streaming=!1,!String(n.text||"").trim()&&S&&"string"==typeof S.text&&S.text.trim()&&(n.text=S.text),l=!1,clearInterval(p),p=null,N(!1);const r=Math.max(1,Math.round((Date.now()-d)/1e3)),s=!(!u||!u.signal.aborted);n.text=finalizeTurnText(n.text,{aborted:s,error:S&&S.error,reasoned:o}),j({role:"done",text:`${h>0?DONE_VERBS[1]:DONE_VERBS[0]} for ${r}s`},{follow:!1}),S&&S.pooled_notice&&j({role:"note",text:S.pooled_notice},{follow:!1}),y=m+1,m++,u=null;try{const e=loadConfig(),t=pingTurn({stream:process.stdout,mode:e.ping,minSeconds:e.pingMinSeconds,elapsedMs:Date.now()-d,isTTY:!!process.stdout.isTTY,aborted:s});t&&j({role:"note",text:t},{follow:!1})}catch{}e.recordTurn(S);let i=null;try{const t=await e.refreshSpend();i=t?t.lastCost:null}catch{}e.persistTurn&&e.persistTurn(t,S,s?"stopped":S&&S.error?"error":"done",i);const a=S&&S.usage,c=e.tokensFor?e.tokensFor(a):null,f=a?usageBuckets(a):null;j({role:"meta",meta:{model:S&&S.model,tokens:c,input:f?f.input:null,output:f?f.output:null,eur:i,ms:S&&S.ms,calls:S&&S.calls||1}},{follow:!1});const w=summarizeTurnTools(g);w.tools>0&&j({role:"summary",counts:w},{follow:0===E}),B()}},Z=e=>{let r=null;if(e.name===KEY.PAGE_UP)r=5;else if(e.name===KEY.PAGE_DOWN)r=-5;else if("wheel"===e.name)r="up"===e.dir?3:-3;else{if("click"===e.name||"drag"===e.name||"release"===e.name)return!(e=>{const t={col:e.col-1,row:e.row-1};if("click"===e.name)return C=t,!1;if("drag"===e.name)return T?T.head=t:T={anchor:C||t,head:t},C=null,!0;const n=C;C=null;const r=T?selectionRange(T.anchor,T.head):null,o=!(!r||r.startRow===r.endRow&&r.startCol===r.endCol);if(T=null,!o)return(e=>{const t=v.get(e);return!(!t||!t.diff||(t.diffOpen=!t.diffOpen,0))})((n||t).row);const s=selectionText(L,r);if(!s)return!0;const i=copyToClipboard(s,{stdout:process.stdout,env:process.env}),a=s.split("\n").length;return P=describeCopy(i,`Marked ${a} line${1===a?"":"s"}`),k=Date.now()+2500,setTimeout((()=>{Date.now()>=k&&B()}),2600),!0})(e)||(q(),!0);"char"!==e.name||!t.vim||b||n.buf||("j"===e.ch?r=1:"k"===e.ch&&(r=-1))}return null!==r&&(E=Math.max(0,E+r),S=null,q(),!0)},ee=()=>{if(!s||"resume"!==s.type)return;const e=Array.isArray(s.all)?s.all:[];s.items=sessionSearch.rankSessions(s.query||"",e),s.sel=0,B()},te=()=>s?"palette"===s.type?fuzzy.fuzzyRankWithAliases(paletteQuery(s.query),e.visibleCommands(),(e=>e.name),(e=>e.aliases||[])).length:"model"===s.type||"resume"===s.type||"class"===s.type||"provider"===s.type?(s.items||[]).length:"effort"===s.type?overlays.EFFORT_VALUES.length:0:0,ne=async n=>{if(n){{const t=models.modelKeyPlan(n,{hasStored:!!e.hasProviderKey&&!!e.hasProviderKey("anthropic")}),{row:r,message:o}=overrideAnthropicByokWithPro(n,{needsKey:!(!t||!t.needed),proLoggedIn:models.claudeProLoggedIn(),proEnabled:(()=>{try{return!0===loadConfig().proEnabled}catch{return!1}})(),proModels:claudePro.PRO_MODELS});n=r,o&&U(o)}if(n.cls&&"aegis"!==n.cls&&t.modelClass!==n.cls){const e="string"==typeof t.modelClass;if(await ie(`/class ${n.cls}`),e&&t.modelClass!==n.cls)return void U(`${n.id} runs on the ${n.cls} class, and this session is on ${t.modelClass} — run /class ${n.cls}${"pro"===n.cls?" on":""}, then pick it again.`)}t.model=n.id,e.updateConfig({model:n.id,currentModelId:n.id,modelClass:t.modelClass}),U(`model: ${n.id}${"byok"===n.cls?" (byok)":"pro"===n.cls?" (Claude Code Pro)":""}`),await(async t=>{const n=models.modelKeyQueue(t,{accountConfigured:!!e.accountConfigured&&!!e.accountConfigured(),hasStoredFor:t=>!!e.hasProviderKey&&!!e.hasProviderKey(t)});if(!n.length)return;let r=null;try{r=e.makeCommandContext()}catch{r=null}if(r&&"function"==typeof r.readSecret)for(const e of n){const n="account"===e.role?"AEGIS account key":"claude-pro"===e.role?"Claude Code OAuth token (`claude setup-token` mints one)":`${e.provider} key`,o=String(await r.readSecret(`${n} → ${e.env} (kept off screen, Enter to skip): `)||"").trim();if(!o){U(`no key given — ${e.env} is still unset, so ${t.id} will fail until it is.`);continue}const s="account"===e.role?"AEGIS":"claude-pro"===e.role?"Claude Code OAuth":e.provider||"that provider",i=validateApiKey(o,{label:s});if(!i.ok){U(`not saved — ${i.message}. ${e.env} is still unset.`);continue}const a=models.storeModelKey(t,i.key,{env:e.env});a.ok?U(a.changed?a.foreign?`${e.env} saved to ${a.file} (0600) — read only by the Claude Code Pro transport, never exported.`:`${e.env} saved to ${a.file} (0600) — both hosts read that file; nothing to export.`:`${e.env} was already set in ${a.file}.`):U(`could not save the key: ${a.error||"unknown error"}`)}else{const e=n.map((e=>`${e.env}: ${e.why}`)).join(" · ");U(`${t.id} has no key: ${e}. Set the ones above and pick it again.`)}})(n)}},re=async e=>{e&&e.class&&await ie(`/class ${e.class}`)},oe=n=>{const r=overlays.EFFORT_VALUES[n||0];s=null,t.effort=r||"high",e.updateConfig({effort:t.effort}),U(`effort: ${t.effort}`),B()},se=async o=>{if(o)if(s)await(async t=>{const n=s.type;if(t.name===KEY.ESC||t.name===KEY.CTRL_C)return s=null,void B();if("shortcuts"===n||"panel"===n)return s=null,void B();if(t.name!==KEY.TAB||"palette"!==n)if(t.name!==KEY.TAB||"model"!==n&&"effort"!==n&&"class"!==n&&"provider"!==n){if(t.name===KEY.ENTER){if("palette"===n){const e=i()[s.sel||0],t=String(s.query||"").trim().split(/\s+/).slice(1).join(" ");return s=null,B(),void(e&&await ie(t?`/${e.name} ${t}`:`/${e.name}`))}if("model"===n){const e=(s.items||[])[s.sel||0];return s=null,B(),await ne(e),void B()}if("effort"===n)return void oe(s.sel||0);if("class"===n){const e=(s.items||[])[s.sel||0];return s=null,B(),await re(e),void B()}if("provider"===n){const e=(s.items||[])[s.sel||0],t=s.command||"byok-key";return s=null,B(),void(e&&e.id&&await ie(`/${t} ${e.id}`))}if("resume"===n){const t=(s.items||[])[s.sel||0];return s=null,B(),void(t&&e.resumeSession&&await e.resumeSession(t))}return s=null,void B()}if(t.name===KEY.SHIFT_UP||t.name===KEY.SHIFT_DOWN){const e=t.name===KEY.SHIFT_UP?-1:1,r=Math.max(0,te()-1);if(s.sel=Math.min(r,Math.max(0,(s.sel||0)+e)),"model"===n){const e=(s.items||[])[s.sel||0];return s=null,B(),await ne(e),void B()}if("class"===n){const e=(s.items||[])[s.sel||0];return s=null,B(),await re(e),void B()}if("provider"===n){const e=(s.items||[])[s.sel||0],t=s.command||"byok-key";return s=null,B(),void(e&&e.id&&await ie(`/${t} ${e.id}`))}return"effort"===n?void oe(s.sel||0):void B()}if(t.name===KEY.SHIFT_ENTER){if("palette"===n){const e=i()[s.sel||0];return s=null,B(),void(e&&await ie(`/${e.name}`))}if("model"===n){const e=(s.items||[])[s.sel||0];return s=null,B(),await ne(e),void B()}if("class"===n){const e=(s.items||[])[s.sel||0];return s=null,B(),await re(e),void B()}if("provider"===n){const e=(s.items||[])[s.sel||0],t=s.command||"byok-key";return s=null,B(),void(e&&e.id&&await ie(`/${t} ${e.id}`))}return"effort"===n?void oe(s.sel||0):void 0}if(t.name===KEY.UP||t.name===KEY.DOWN){const e=(s.items||[]).length||te(),n=t.name===KEY.UP?-1:1;return s.sel=Math.min(Math.max(0,e-1),Math.max(0,(s.sel||0)+n)),void B()}if("char"===t.name){if("palette"===n)return s.query=(s.query||"")+t.ch,s.sel=0,void B();if("resume"===n)return s.query=(s.query||"")+t.ch,void ee();if("model"===n){const e=parseInt(t.ch,10),n=s.items||[];return void(Number.isFinite(e)&&e>=1&&e<=n.length&&(s.sel=e-1,B()))}if("effort"===n||"class"===n||"provider"===n){const e=parseInt(t.ch,10),n=te();return void(Number.isFinite(e)&&e>=1&&e<=n&&(s.sel=e-1,B()))}}if(t.name===KEY.BACKSPACE&&"resume"===n)return s.query=String(s.query||"").slice(0,-1),void ee();t.name===KEY.BACKSPACE&&"palette"===n&&(s.query=String(s.query||"").slice(0,-1),B())}else{const e="model"===n||"class"===n||"provider"===n?(s.items||[]).length:overlays.EFFORT_VALUES.length;e&&(s.sel=((s.sel||0)+1)%e,B())}else{const e=i()[s.sel||0];e&&(s.query=e.name,s.sel=0,B())}})(o);else{if("char"===o.name&&!n.buf){if("/"===o.ch)return s={type:"palette",query:"",sel:0},void B();if("?"===o.ch)return s={type:"shortcuts"},void B()}if(!t.vim||b||n.buf||"char"!==o.name){if(t.vim&&b&&o.name===KEY.ESC)return b=!1,n.cursor>0&&n.cursor--,void B()}else{const e=o.ch;if("i"===e||"a"===e||"o"===e||"s"===e||"S"===e)return"s"===e&&n.substChar(),"S"===e&&n.substLine(),"a"===e&&n.right(),b=!0,void B();if("h"===e)return n.left(),void B();if("l"===e)return n.right(),void B();if("0"===e)return n.home(),void B();if("$"===e)return n.end(),void B();if("x"===e)return n.delete(),void B();if("D"===e)return n.killToEnd(),void B();if("A"===e)return n.end(),b=!0,void B();if(Z(o))return}if(o.name===KEY.ENTER){const e=n.submit();return Y=null,b=!1,e?void await ie(e):void B()}if(o.name!==KEY.CTRL_V)if(o.name!==KEY.CTRL_B){if("paste"===o.name)return t.vim&&(b=!0),n.insert(String(o.text)),void B();if("char"===o.name)return t.vim&&!b||n.insert(o.ch),void B();if(o.name===KEY.BACKSPACE)return n.backspace(),void B();if(o.name===KEY.DELETE)return n.delete(),void B();if(o.name===KEY.LEFT||o.name===KEY.CTRL_LEFT)return o.name===KEY.CTRL_LEFT?n.wordBack():n.left(),void B();if(o.name!==KEY.RIGHT||n.buf){if(o.name===KEY.RIGHT||o.name===KEY.CTRL_RIGHT)return n.right(),void B();if(o.name===KEY.HOME||o.name===KEY.CTRL_A)return n.home(),void B();if(o.name===KEY.END||o.name===KEY.CTRL_E)return n.end(),void B();if(o.name===KEY.UP)return n.historyUp(),void B();if(o.name===KEY.DOWN)return n.historyDown(),void B();if(o.name===KEY.TAB)return(()=>{const t=n.buf;if(!t.startsWith("/")||t.includes(" "))return!1;const r=t.slice(1),o=e.visibleCommands().flatMap((e=>[e.name,...e.aliases||[]])).filter((e=>e.startsWith(r))).sort();return!!o.length&&(Y&&Y.q===r||(Y={q:r,i:-1}),Y.i=(Y.i+1)%o.length,n.buf="/"+o[Y.i],n.end(),!0)})()||(P=n.buf?"Tab completes commands":"Use alt+t to toggle thinking",k=Date.now()+2500,setTimeout((()=>{Date.now()>=k&&B()}),2600)),void B();if(o.name===KEY.CTRL_U)return n.buf="",n.cursor=0,void B();if(o.name===KEY.CTRL_K)return n.killToEnd(),void B();if(o.name===KEY.CTRL_W)return n.wordBack(),void B();if(o.name===KEY.CTRL_L)return clearScreen(),void B();if(o.name===KEY.CTRL_T)return U(e.tokenSummary?e.tokenSummary():"no token usage yet this session"),void B();if(o.name!==KEY.CTRL_R)if(o.name!==KEY.CTRL_O)if("click"!==o.name&&"drag"!==o.name&&"release"!==o.name)if(o.name!==KEY.PAGE_UP&&o.name!==KEY.PAGE_DOWN&&"wheel"!==o.name)if("alt"!==o.name||"p"!==o.ch){if("alt"===o.name&&"t"===o.ch){const n=!(!0===t.thinking);return t.thinking=n,e.updateConfig({thinking:n}),U("Thinking blocks: "+(n?"expanded":"collapsed")),void B()}if(o.name!==KEY.ESC)return o.name===KEY.CTRL_C?n.buf?(n.buf="",n.cursor=0,void B()):void await ue():void(o.name!==KEY.CTRL_D||n.buf||await ue());n.buf&&(n.buf="",n.cursor=0,B())}else await ie("/model");else Z(o);else Z(o);else await ie("/permissions");else await ie("/resume")}else await ie(e.isYolo&&e.isYolo()?"/automode off":"/automode on")}else(()=>{if(!r.length)return void G("Nothing to copy yet");const e=copyToClipboard(transcriptToMarkdown(r),{stdout:process.stdout,env:process.env});G(describeCopy(e,"Copied the conversation"))})();else(()=>{const e=readClipboardImage({env:process.env});if(e.ok)try{const t=path.join(aegisDir(),"clipboard");fs.mkdirSync(t,{recursive:!0});const r="image/jpeg"===e.mime?"jpg":"png",o=path.join(t,`pasted-${(new Date).toISOString().replace(/[:.]/g,"-")}.${r}`);fs.writeFileSync(o,e.data,{mode:384});const s=n.buf&&!/\s$/.test(n.buf)?" ":"";return n.insert(s+o),void G(`Pasted image → ${o}`)}catch(e){return void G(`Could not save the pasted image: ${e&&e.message||e}`)}const t=readClipboardText({env:process.env});if(t.ok&&t.text)return n.insert(t.text),void G(`Pasted ${t.text.length} character${1===t.text.length?"":"s"} from the clipboard`);G(t.ok?"Clipboard is empty — nothing to paste":`Cannot read the clipboard here (${t.error}) — use your terminal's own paste shortcut instead`)})()}},ie=async t=>{const r=String(t||"").trim();if("?"===r)return s={type:"shortcuts"},void B();(!1===await(async(e,t)=>{try{return await((e,t)=>{const n=[];let r,o,i=!1;return e.then((e=>{i=!0,r=e}),(e=>{i=!0,o=e})),(async()=>{for(;!i;){if(await Promise.resolve(),!l||s&&"confirm"===s.type){await new Promise((e=>setTimeout(e,60)));continue}const e=await nextKeyTimeout(120);if(null!==e)if(e.name===KEY.ESC||e.name===KEY.CTRL_C){const e=t&&t();e&&e.abort()}else Z(e)||n.push(e)}if(requeueKeys(n),o)throw o;return r})()})(e(),(()=>u))}catch(e){return j({role:"note",text:`Error: ${e&&e.message||String(e)}`},{follow:!1}),void B()}})((async()=>{if(r.startsWith("/")){const t=(()=>{const t=e.makeCommandContext();return Object.assign(t,{push:(e,t)=>{j(e,t),B()},note:e=>{j({role:"note",text:e}),B()},panel:e=>{j({role:"panel",lines:e||[]}),B()},render:()=>B(),openOverlay:e=>{if(e&&"resume"===e.type){const t=Array.isArray(e.items)?e.items:[];return s={...e,all:t,query:"string"==typeof e.query?e.query:"",items:sessionSearch.rankSessions("string"==typeof e.query?e.query:"",t),sel:0},void B()}s=e,B()},closeOverlay:()=>{s=null,showCursor(),B()},askInput:e=>(e=>new Promise((t=>{$={title:e,buf:""},B(),(async()=>{for(;;){const e=await nextKey();if(!$)return void t(null);if(e.name===KEY.ESC||e.name===KEY.CTRL_C||e.name===KEY.CTRL_D)return $=null,B(),void t(null);if(e.name===KEY.ENTER){const e=$.buf;return $=null,B(),void t(e)}e.name===KEY.BACKSPACE?$.buf=[...$.buf].slice(0,-1).join(""):"char"===e.name?$.buf+=e.ch:"paste"===e.name&&($.buf+=String(e.text).replace(/\n/g," ")),B()}})()})))(e),withWorking:e=>(async e=>{const t=u;l=!0,c=0,d=Date.now(),f=VERBS[m%VERBS.length],u=new AbortController,p=setInterval((()=>{c++,N(!0),c%3==0&&B()}),100),p.unref&&p.unref(),N(!0);try{return await e(u.signal)}finally{l=!1,clearInterval(p),p=null,u=t,N(!1),B()}})(e),runPrompt:async e=>{await J(e)},state:()=>e.buildState(),setInput:e=>{n.buf=String(null==e?"":e),n.end(),B()},exit:()=>e.requestExit(),openStream:e=>{x=e||null,O=Date.now(),B()},closeStream:e=>{e&&x!==e||(x=null),B()},showThemePicker:()=>{e.showThemePicker&&e.showThemePicker(),B()}}),t})();return e.dispatchLine(r,t)}return await J(r),!0}))||e.wantsExit())&&await ue()};let ae=!1,le=null;const ue=()=>{ae||(ae=!0,le&&le(0))},ce=()=>{hideCursor(),paint([]);try{process.stdout.write("")}catch{}try{A&&writeTitle("",process.stdout)}catch{}try{process.stdin.setRawMode(!1)}catch{}disableBracketedPaste(),disableMouseTracking(),leaveAltScreen()};let pe=!1;const de=()=>{if(!pe){pe=!0;try{ce()}catch{}}};process.once("exit",de);const fe=e.stdin||process.stdin;markSessionStart(),attachKeyStream(fe),enableBracketedPaste(),enableMouseTracking(),enterAltScreen(),clearScreen(),hideCursor(),N(!1);const me=()=>B();"win32"!==process.platform?process.on("SIGWINCH",me):process.stdout.on("resize",me);const he=()=>{l&&u?u.abort():ue()};process.on("SIGINT",he);const ge=e=>{ce();try{process.stderr.write(`\nAEGIS Code hit an unexpected error. Your transcript is saved; rerun to continue.\n${e&&e.stack||e}\n`)}catch{}process.exit(1)};process.on("uncaughtException",ge),process.on("unhandledRejection",ge),B();try{return await new Promise((e=>{le=e,(async()=>{for(;!ae;){const e=await nextKey();if(ae)break;if(e===STREAM_END||!e){ue();break}try{await se(e)}catch(e){j({role:"note",text:`Error: ${e&&e.message||String(e)}`},{follow:!1}),B()}}})()}))}finally{ae=!0,process.off("SIGINT",he),"win32"!==process.platform?process.off("SIGWINCH",me):process.stdout.off("resize",me),process.off("uncaughtException",ge),process.off("unhandledRejection",ge),process.off("exit",de),de(),resetKeyStream()}}module.exports={SUGGESTIONS:SUGGESTIONS,TITLE_SPIN:TITLE_SPIN,FRAME_MS:33,toolLabel:toolLabel,resolveToolDone:resolveToolDone,summarizeTurnTools:summarizeTurnTools,finalizeTurnText:finalizeTurnText,historyPairs:historyPairs,overrideAnthropicByokWithPro:overrideAnthropicByokWithPro,paletteQuery:paletteQuery,headerLine:headerLine,separatorLine:separatorLine,effortLine:effortLine,spinnerLine:spinnerLine,statusLine:statusLine,shortcutsGrid:shortcutsGrid,confirmLines:confirmLines,APPROVAL_CHOICES:APPROVAL_CHOICES,APPROVAL_DECISIONS:APPROVAL_DECISIONS,roundsLines:roundsLines,autoContinuePlan:autoContinuePlan,autoContinueLimit:autoContinueLimit,AUTO_CONTINUE_LIMIT:AUTO_CONTINUE_LIMIT,rowLines:rowLines,transcriptLines:transcriptLines,inputPreviewText:inputPreviewText,inputRowCells:inputRowCells,inputScroll:inputScroll,inputStart:inputStart,inputLine:inputLine,runSession:runSession};