aegisone 1.0.38 → 1.0.39
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/package.json +1 -1
- package/scripts/predist.mjs +1 -1
- package/vendor/cli/package.json +1 -1
- package/vendor/cli/src/app.js +1 -1
- package/vendor/cli/src/chatflow.js +1 -1
- package/vendor/cli/src/commands.js +1 -1
- package/vendor/cli/vendor/client/byok-catalog.js +1 -1
- package/vendor/desktop/package.json +4 -3
- package/vendor/desktop/vendor/byok-catalog.js +1 -1
- package/vendor/desktop/vendor/faces/cli/package.json +1 -1
- package/vendor/desktop/vendor/faces/cli/src/app.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/chatflow.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/commands.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/byok-catalog.js +1 -1
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# AEGISONE
|
|
2
2
|
|
|
3
|
-
Product version: **1.0.
|
|
3
|
+
Product version: **1.0.39**
|
|
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.
|
|
63
|
+
Measured size: **2.53 MB** (2,651,423 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.
|
|
4
|
+
"version": "1.0.39",
|
|
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",
|
package/scripts/predist.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
3
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
4
|
-
import e from"node:fs";import r from"node:path";import{spawnSync as s}from"node:child_process";import{fileURLToPath as t,pathToFileURL as o}from"node:url";import{createRequire as n}from"node:module";const i=r.dirname(t(import.meta.url)),a=n(import.meta.url);export const ONE_DIR=r.join(i,"..");export const REPO_DIR=r.join(ONE_DIR,"..");export const CLI_DIR=r.join(REPO_DIR,"cli");export const DESKTOP_DIR=r.join(REPO_DIR,"desktop");export const CLI_VENDOR=r.join(CLI_DIR,"vendor");export const DESKTOP_VENDOR=r.join(DESKTOP_DIR,"vendor");export const ONE_VENDOR=r.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/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/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:"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/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/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 s=[];for(const t of MANIFEST){if(!t.shapes.includes(e))continue;let o;if("mirror"===e)o=r.join(CLI_VENDOR,t.src);else if("flat"===e)o=r.join(DESKTOP_VENDOR,r.basename(t.src));else{if("nested"!==e)throw new Error(`predist: unknown shape ${e}`);o=r.join(DESKTOP_VENDOR,t.src)}s.push({src:t.src,dest:o,from:r.join(REPO_DIR,t.src)})}return s}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"]);function d(s,t){const o=e=>l.has(e)||e.endsWith(".log"),n=(s,t)=>{if(e.mkdirSync(r.dirname(t),{recursive:!0}),e.copyFileSync(s,t),!e.readFileSync(s).equals(e.readFileSync(t)))throw new Error(`predist: bundle copy differs from source: ${r.relative(REPO_DIR,s)}`)},i=(s,a)=>{const c=e.lstatSync(s);if(!c.isSymbolicLink())if(c.isFile())n(s,r.join(t,a));else for(const t of e.readdirSync(s))o(t)||i(r.join(s,t),a?r.join(a,t):t)};e.lstatSync(s).isFile()?n(s,t):i(s,"")}const h=12e4,p=6e5,u=50,m="AEGISONE_PREDIST_LOCK_TOKEN";let f=null,g=!1,j=0;function y(e){try{return process.kill(e,0),!0}catch(e){return Boolean(e)&&"EPERM"===e.code}}const v=e=>new Promise((r=>setTimeout(r,e)));function w(){if(j>0)return void j--;const r=f,s=g,t=process.env[m];if(f=null,g=!1,r&&s){t&&delete process.env[m];try{e.unlinkSync(r)}catch{}}}export async function acquireStageLock(s){if(f)return j++,w;const t=s&&s.stdout||process.stdout;return await async function(s){const t=function(){const s=r.join(REPO_DIR,".git");let t=s;try{if(!e.lstatSync(s).isDirectory()){const o=/^gitdir:\s*(.+)$/m.exec(e.readFileSync(s,"utf8"));o&&(t=r.resolve(REPO_DIR,o[1].trim()))}}catch{t=s}return r.join(t,"aegisone-predist.lock")}(),o=Date.now()+h,n=process.env[m]||null;let i=null,a=!1;for(;;){if(n)try{const r=String(e.readFileSync(t,"utf8")).split("\n")[1];if(r&&r.trim()===n)return f=t,void(g=!1)}catch{}try{i=`${Date.now().toString(36)}-${process.pid}-${Math.random().toString(36).slice(2,10)}`;const r=e.openSync(t,"wx");return e.writeSync(r,`${process.pid}\n${i}\n`),e.closeSync(r),f=t,g=!0,void(process.env[m]=i)}catch(e){if(!e||"EEXIST"!==e.code)throw e}let r=null,c=0;try{r=e.statSync(t),c=Number(String(e.readFileSync(t,"utf8")).split("\n")[0].trim())}catch{continue}if(Date.now()-r.mtimeMs>p||Number.isFinite(c)&&c>0&&!y(c)){s(`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,s(`predist: another stager (pid ${c||"unknown"}) is running — waiting for it (concurrent staging would read a vendor tree the peer is rewriting)`)),await v(u+Math.floor(Math.random()*u))}}}((e=>t.write(`${e}\n`))),w}function b(s,t){t&&e.rmSync(t,{recursive:!0,force:!0});const o=[];for(const t of s){if(!e.existsSync(t.from))throw new Error(`predist: missing shared module: ${t.src} (expected at ${t.from})`);if(e.mkdirSync(r.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"]),p=e=>h.includes(e),u=e=>l.write(`${e}\n`),m=await acquireStageLock(i);try{return await async function({want:t,log:n}){const i={mirror:null,flat:null,nested:null,bundle:null};if(t("mirror")){const e=b(entriesFor("mirror"),CLI_VENDOR);n(`predist: staged ${e.length} shared modules into cli/vendor/`);for(const r of e)n(` ${r.src} -> vendor/${r.src}`);i.mirror={staged:e.length}}if(t("nested")&&(i.nested={staged:b(entriesFor("nested"),null).length}),t("flat")){const e=b(entriesFor("flat"),null);for(const r of e)n(`staged ${r.dest}`);i.flat={staged:e.length}}if(t("mirror")&&t("flat"))for(const s of MANIFEST){if(!s.shapes.includes("mirror")||!s.shapes.includes("flat"))continue;const t=r.join(CLI_VENDOR,s.src),o=r.join(DESKTOP_VENDOR,r.basename(s.src));if(!e.readFileSync(t).equals(e.readFileSync(o)))throw new Error(`predist: the two shapes disagree for ${s.src}`)}if(t("mirror")){const s=function(s){const t=r.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=r.join(CLI_VENDOR,"mcp","server.js");new i.Script(e.readFileSync(c,"utf8"),{filename:c});const l=r.join(CLI_VENDOR,"hosts"),d=a(r.join(l,"spec.js")),h=a(r.join(l,"install.js")),p=a(r.join(l,"targets.js")),u=d.resolveServer({AEGIS_MCP_SERVER:""});if(!u.exists||u.path!==c)throw new Error(`predist: staged hosts/spec.js resolves the server as ${u.path} (exists: ${u.exists}), expected ${c}. An installed aegiscode would write editor configs pointing at a file the package never shipped. Candidates were:\n ${u.candidates.join("\n ")}`);const m=p.getTarget("vscode"),f=h.planTarget(m,"user",{ctx:h.hostCtx({home:r.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(r.join(l,"openai-shim.js")).createShimServer)throw new Error("predist: staged hosts/openai-shim.js exposes no createShimServer");return{count:n,targets:p.targetIds().length,staged:s.length}}(entriesFor("mirror"));n(`predist: staged registry loads standalone (${s.count} tools)`),n(`predist: editor layer verified (${s.targets} host targets, server resolves to vendor/mcp/server.js, shim loads)`);const t=await async function(){const e=r.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: ${r.relative(REPO_DIR,t)} loads standalone and exposes run()`),i.mirror.proof=s}if(t("flat")){const s=function(s){const t=new Set(s.map((e=>r.basename(e.dest))));for(const o of s){const s=e.readFileSync(o.dest,"utf8").replace(/\/\*[\s\S]*?\*\//g,"").replace(/(^|[^:])\/\/.*$/gm,"$1");for(const e of s.matchAll(/require\(\s*'((?:\.\.?\/)[^']+)'\s*\)/g)){const s=e[1];if(r.basename(s).replace(/\.[cm]?js$/,""),s.replace(/^\.\//,"").startsWith("../"))throw new Error(`predist: flat-staged ${r.basename(o.dest)} requires '${s}', which escapes vendor/ — flattening only works for same-directory requires (add the target to the manifest, or stop staging this file flat)`);const n=s.replace(/^\.\//,"");if(!t.has(n))throw new Error(`predist: flat-staged ${r.basename(o.dest)} requires '${s}', which is not staged into desktop/vendor/ — the packaged app would throw MODULE_NOT_FOUND before the window could open`)}}const o=a(r.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:s.length,exports:Object.keys(o).length}}(entriesFor("flat"));n(`predist: flattened tree is self-contained (${s.files} files, ${s.exports} transport exports) — no staged module escapes vendor/`),i.flat.proof=s}if(t("bundle")){for(const[s,t,o]of c){const i=r.join(ONE_VENDOR,s);e.rmSync(i,{recursive:!0,force:!0});for(const s of o){const o=r.join(t,s);if(!e.existsSync(o)){if("LICENSE"===s||"README.md"===s)continue;throw new Error(`predist: bundle source missing: ${r.relative(REPO_DIR,o)}`)}d(o,r.join(i,s))}n(`staged the ${s} face into one/vendor/${s}/`)}const t=function(){const t=r.join(ONE_VENDOR,"cli"),o=r.join(t,"src","deps.js"),n=s(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,s]of Object.entries(i)){const t=r.relative(ONE_VENDOR,s);t.startsWith("..")||r.isAbsolute(t)?a.push(`${e} -> ${s}`):"cli"!==t.split(r.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(r.join(t,"bin","aegiscode.js")))throw new Error("predist: the bundle has no cli/bin/aegiscode.js");const d=[];for(const[s,t,o]of c)for(const n of o){const o=r.join(ONE_VENDOR,s,n);let i=null,a=null;try{i=e.lstatSync(r.join(t,n))}catch{continue}try{a=e.lstatSync(o)}catch{d.push(`${s}/${n} -> missing`);continue}i.isFile()&&!a.isFile()&&d.push(`${s}/${n} -> not a regular file`),i.isDirectory()&&!a.isDirectory()&&d.push(`${s}/${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=r.join(DESKTOP_VENDOR,"faces");e.rmSync(o,{recursive:!0,force:!0}),d(r.join(ONE_VENDOR,"cli"),r.join(o,"cli"));const a=r.join(o,"cli","bin","aegiscode.js");if(!e.existsSync(a))throw new Error(`predist: the packaged terminal face has no entry point at ${r.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/ (${r.basename(a)})`),i.faces={entry:r.relative(REPO_DIR,a)}}return i}({want:p,log:u})}finally{m()}}export async function main(e,r){const s=r||{},t=Array.isArray(e)?e:[],o=t.includes("--quiet")?{write:()=>!0}:s.stdout||process.stdout,n=s.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 s=!1;if(e)try{s=r.resolve(e)===t(import.meta.url)}catch{s=!1}s&&main(process.argv.slice(2)).then((e=>{process.exitCode=e}))}();
|
|
4
|
+
import e from"node:fs";import r from"node:path";import{spawnSync as s}from"node:child_process";import{fileURLToPath as t,pathToFileURL as o}from"node:url";import{createRequire as n}from"node:module";const i=r.dirname(t(import.meta.url)),a=n(import.meta.url);export const ONE_DIR=r.join(i,"..");export const REPO_DIR=r.join(ONE_DIR,"..");export const CLI_DIR=r.join(REPO_DIR,"cli");export const DESKTOP_DIR=r.join(REPO_DIR,"desktop");export const CLI_VENDOR=r.join(CLI_DIR,"vendor");export const DESKTOP_VENDOR=r.join(DESKTOP_DIR,"vendor");export const ONE_VENDOR=r.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/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/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:"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/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/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 s=[];for(const t of MANIFEST){if(!t.shapes.includes(e))continue;let o;if("mirror"===e)o=r.join(CLI_VENDOR,t.src);else if("flat"===e)o=r.join(DESKTOP_VENDOR,r.basename(t.src));else{if("nested"!==e)throw new Error(`predist: unknown shape ${e}`);o=r.join(DESKTOP_VENDOR,t.src)}s.push({src:t.src,dest:o,from:r.join(REPO_DIR,t.src)})}return s}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"])]]);function h(s,t,o){const n=o||new Set,i=(e,r)=>l.has(e)||e.endsWith(".log")||n.has(r),a=(s,t)=>{if(e.mkdirSync(r.dirname(t),{recursive:!0}),e.copyFileSync(s,t),!e.readFileSync(s).equals(e.readFileSync(t)))throw new Error(`predist: bundle copy differs from source: ${r.relative(REPO_DIR,s)}`)},c=(s,o)=>{const n=e.lstatSync(s);if(!n.isSymbolicLink())if(n.isFile())a(s,r.join(t,o));else for(const t of e.readdirSync(s)){const e=o?r.join(o,t):t;i(t,e)||c(r.join(s,t),e)}};e.lstatSync(s).isFile()?a(s,t):c(s,"")}const p=12e4,u=6e5,f=50,m="AEGISONE_PREDIST_LOCK_TOKEN";let g=null,j=!1,y=0;function v(e){try{return process.kill(e,0),!0}catch(e){return Boolean(e)&&"EPERM"===e.code}}const w=e=>new Promise((r=>setTimeout(r,e)));function b(){if(y>0)return void y--;const r=g,s=j,t=process.env[m];if(g=null,j=!1,r&&s){t&&delete process.env[m];try{e.unlinkSync(r)}catch{}}}export async function acquireStageLock(s){if(g)return y++,b;const t=s&&s.stdout||process.stdout;return await async function(s){const t=function(){const s=r.join(REPO_DIR,".git");let t=s;try{if(!e.lstatSync(s).isDirectory()){const o=/^gitdir:\s*(.+)$/m.exec(e.readFileSync(s,"utf8"));o&&(t=r.resolve(REPO_DIR,o[1].trim()))}}catch{t=s}return r.join(t,"aegisone-predist.lock")}(),o=Date.now()+p,n=process.env[m]||null;let i=null,a=!1;for(;;){if(n)try{const r=String(e.readFileSync(t,"utf8")).split("\n")[1];if(r&&r.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 r=e.openSync(t,"wx");return e.writeSync(r,`${process.pid}\n${i}\n`),e.closeSync(r),g=t,j=!0,void(process.env[m]=i)}catch(e){if(!e||"EEXIST"!==e.code)throw e}let r=null,c=0;try{r=e.statSync(t),c=Number(String(e.readFileSync(t,"utf8")).split("\n")[0].trim())}catch{continue}if(Date.now()-r.mtimeMs>u||Number.isFinite(c)&&c>0&&!v(c)){s(`predist: breaking an abandoned staging lock (pid ${c||"unknown"})`);try{e.unlinkSync(t)}catch{}}else{if(Date.now()>o)throw new Error(`predist: another stager (pid ${c||"unknown"}) has held ${t} for over ${Math.round(p/1e3)}s. Staging is destructive — it removes and rewrites cli/vendor, desktop/vendor and one/vendor — so it will not run concurrently with a peer. Wait for it, or delete the lock if that process is gone.`);a||(a=!0,s(`predist: another stager (pid ${c||"unknown"}) is running — waiting for it (concurrent staging would read a vendor tree the peer is rewriting)`)),await w(f+Math.floor(Math.random()*f))}}}((e=>t.write(`${e}\n`))),b}function E(s,t){t&&e.rmSync(t,{recursive:!0,force:!0});const o=[];for(const t of s){if(!e.existsSync(t.from))throw new Error(`predist: missing shared module: ${t.src} (expected at ${t.from})`);if(e.mkdirSync(r.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,p=(i.stderr||process.stderr,Array.isArray(n.shapes)?n.shapes:[...SHAPES,"bundle"]),u=e=>p.includes(e),f=e=>l.write(`${e}\n`),m=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 r of e)n(` ${r.src} -> vendor/${r.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 r of e)n(`staged ${r.dest}`);i.flat={staged:e.length}}if(t("mirror")&&t("flat"))for(const s of MANIFEST){if(!s.shapes.includes("mirror")||!s.shapes.includes("flat"))continue;const t=r.join(CLI_VENDOR,s.src),o=r.join(DESKTOP_VENDOR,r.basename(s.src));if(!e.readFileSync(t).equals(e.readFileSync(o)))throw new Error(`predist: the two shapes disagree for ${s.src}`)}if(t("mirror")){const s=function(s){const t=r.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=r.join(CLI_VENDOR,"mcp","server.js");new i.Script(e.readFileSync(c,"utf8"),{filename:c});const l=r.join(CLI_VENDOR,"hosts"),d=a(r.join(l,"spec.js")),h=a(r.join(l,"install.js")),p=a(r.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 f=p.getTarget("vscode"),m=h.planTarget(f,"user",{ctx:h.hostCtx({home:r.join(CLI_VENDOR,".predist-home"),env:{},cwd:REPO_DIR}),specOpts:{env:{AEGIS_MCP_SERVER:""}}}),g=JSON.stringify(m.after||"");if(m.error||!m.changed||!g.includes(JSON.stringify(c).slice(1,-1)))throw new Error(`predist: a planned vscode install does not name the staged server (error: ${m.error&&m.error.message}, changed: ${m.changed})`);if("function"!=typeof a(r.join(l,"openai-shim.js")).createShimServer)throw new Error("predist: staged hosts/openai-shim.js exposes no createShimServer");return{count:n,targets:p.targetIds().length,staged:s.length}}(entriesFor("mirror"));n(`predist: staged registry loads standalone (${s.count} tools)`),n(`predist: editor layer verified (${s.targets} host targets, server resolves to vendor/mcp/server.js, shim loads)`);const t=await async function(){const e=r.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: ${r.relative(REPO_DIR,t)} loads standalone and exposes run()`),i.mirror.proof=s}if(t("flat")){const s=function(s){const t=new Set(s.map((e=>r.basename(e.dest))));for(const o of s){const s=e.readFileSync(o.dest,"utf8").replace(/\/\*[\s\S]*?\*\//g,"").replace(/(^|[^:])\/\/.*$/gm,"$1");for(const e of s.matchAll(/require\(\s*'((?:\.\.?\/)[^']+)'\s*\)/g)){const s=e[1];if(r.basename(s).replace(/\.[cm]?js$/,""),s.replace(/^\.\//,"").startsWith("../"))throw new Error(`predist: flat-staged ${r.basename(o.dest)} requires '${s}', which escapes vendor/ — flattening only works for same-directory requires (add the target to the manifest, or stop staging this file flat)`);const n=s.replace(/^\.\//,"");if(!t.has(n))throw new Error(`predist: flat-staged ${r.basename(o.dest)} requires '${s}', which is not staged into desktop/vendor/ — the packaged app would throw MODULE_NOT_FOUND before the window could open`)}}const o=a(r.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:s.length,exports:Object.keys(o).length}}(entriesFor("flat"));n(`predist: flattened tree is self-contained (${s.files} files, ${s.exports} transport exports) — no staged module escapes vendor/`),i.flat.proof=s}if(t("bundle")){for(const[s,t,o]of c){const i=r.join(ONE_VENDOR,s);e.rmSync(i,{recursive:!0,force:!0});for(const n of o){const o=r.join(t,n);if(!e.existsSync(o)){if("LICENSE"===n||"README.md"===n)continue;throw new Error(`predist: bundle source missing: ${r.relative(REPO_DIR,o)}`)}h(o,r.join(i,n),d.get(`${s}/${n}`))}n(`staged the ${s} face into one/vendor/${s}/`)}const t=function(){const t=r.join(ONE_VENDOR,"cli"),o=r.join(t,"src","deps.js"),n=s(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,s]of Object.entries(i)){const t=r.relative(ONE_VENDOR,s);t.startsWith("..")||r.isAbsolute(t)?a.push(`${e} -> ${s}`):"cli"!==t.split(r.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(r.join(t,"bin","aegiscode.js")))throw new Error("predist: the bundle has no cli/bin/aegiscode.js");const d=[];for(const[s,t,o]of c)for(const n of o){const o=r.join(ONE_VENDOR,s,n);let i=null,a=null;try{i=e.lstatSync(r.join(t,n))}catch{continue}try{a=e.lstatSync(o)}catch{d.push(`${s}/${n} -> missing`);continue}i.isFile()&&!a.isFile()&&d.push(`${s}/${n} -> not a regular file`),i.isDirectory()&&!a.isDirectory()&&d.push(`${s}/${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=r.join(DESKTOP_VENDOR,"faces");e.rmSync(o,{recursive:!0,force:!0}),h(r.join(ONE_VENDOR,"cli"),r.join(o,"cli"));const a=r.join(o,"cli","bin","aegiscode.js");if(!e.existsSync(a))throw new Error(`predist: the packaged terminal face has no entry point at ${r.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/ (${r.basename(a)})`),i.faces={entry:r.relative(REPO_DIR,a)}}return i}({want:u,log:f})}finally{m()}}export async function main(e,r){const s=r||{},t=Array.isArray(e)?e:[],o=t.includes("--quiet")?{write:()=>!0}:s.stdout||process.stdout,n=s.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 s=!1;if(e)try{s=r.resolve(e)===t(import.meta.url)}catch{s=!1}s&&main(process.argv.slice(2)).then((e=>{process.exitCode=e}))}();
|
package/vendor/cli/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "aegiscode",
|
|
3
3
|
"productName": "AEGIS Code",
|
|
4
|
-
"version": "7.0.
|
|
4
|
+
"version": "7.0.31",
|
|
5
5
|
"description": "aegiscode — the command-line version of AEGIS Desktop. The shared tool surface in your shell, over the same thin transport and tool registry as the MCP plugin and the desktop app. Ships transport + UI only; no brain.",
|
|
6
6
|
"author": {
|
|
7
7
|
"name": "AEGIS Code",
|
package/vendor/cli/src/app.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 readline=require("node:readline"),os=require("node:os"),{randomUUID:randomUUID}=require("node:crypto"),{createTools:createTools,createClient:createClient,usageTokens:usageTokens,usageBuckets:usageBuckets,buildSystemPrompt:buildSystemPrompt,autoProvisionApiKey:autoProvisionApiKey,provisionFailureText:provisionFailureText,trialNote:trialNote,hostEnv:hostEnv,autonomous:autonomous,claudePro:claudePro}=require("./deps.js"),{createEngine:createEngine,HOST_CLASSES:HOST_CLASSES,DEFAULT_CLASS:DEFAULT_CLASS,byokNamespace:byokNamespace,effortRung:effortRung,offeredClasses:offeredClasses,proEnabled:proEnabled}=require("./engine.js"),{GLYPH:GLYPH,VERBS:VERBS,themeOf:themeOf,RESET:RESET,THEME_TABLE:THEME_TABLE,AUTO_THEME_INDEX:AUTO_THEME_INDEX,themeIsLight:themeIsLight,reconcileThemeIndex:reconcileThemeIndex}=require("./theme.js"),{probeTerminalBackground:probeTerminalBackground}=require("./caps.js"),{LiveRegion:LiveRegion,termWidth:termWidth,w:w}=require("./screen.js"),{estimateTokensFromCells:estimateTokensFromCells}=require("./tokens.js"),{editPreview:editPreview}=require("./diff.js"),{defaultOpen:defaultOpen}=require("./diffview.js"),{parseLine:parseLine,COMMANDS:COMMANDS,visibleCommands:visibleCommands}=require("./commands.js"),{updateConfig:updateConfig,loadPermissions:loadPermissions,loadConfig:loadConfig,configExists:configExists,memoryPersistState:memoryPersistState,memoryPersistEnabled:memoryPersistEnabled,setMemoryPersist:setMemoryPersist,confirmPosture:confirmPosture}=require("./config.js"),credentials=require("./credentials.js"),events=require("./events.js"),cloudsync=require("./cloudsync.js"),{readSecret:readSecret}=require("./secret.js"),{normalizeModelCatalog:normalizeModelCatalog,pickerEntries:pickerEntries,catalogIds:catalogIds,providerForModel:providerForModel}=require("./models.js"),{appendHistory:appendHistory,readSessionTranscript:readSessionTranscript,readOwnSessions:readOwnSessions,setSessionTitle:setSessionTitle}=require("./history.js"),naming=require("./naming.js"),{snapshotCheckpoint:snapshotCheckpoint}=require("./checkpoint.js"),screens=require("./screens.js"),chatflow=require("./chatflow.js"),overlays=require("./overlays.js"),render=require("./render.js"),{fmtTokens:fmtTokens,fmtEur:fmtEur,maskKey:maskKey,feeBillable:feeBillable}=require("./format.js"),{resolveSkip:resolveSkip}=require("./permissions.js"),VERSION=require("../package.json").version;let _defaultSystem=null;function defaultSystemPrompt(){if(null===_defaultSystem)try{_defaultSystem=buildSystemPrompt(hostEnv({},{},null))}catch{_defaultSystem=""}return _defaultSystem||void 0}function normalizeDecision(e){const t="string"==typeof e?e.trim().toLowerCase():"";return"session"===t?"session":"once"===t||"allow"===t||"yes"===t||"approve"===t||"approved"===t?"once":"deny"}const PROVIDER_REFUSAL_PATTERNS=Object.freeze([/^invalid api key\b/i,/^fix external api key\b/i,/^you've hit your session limit\b/i,/^you have hit your session limit\b/i,/^provider request timed out\b/i,/^insufficient (?:credit|balance|quota)\b/i,/^rate limit(?:ed)?\b/i,/^unauthorized\b/i]);function providerRefusal(e,t){if("string"!=typeof e)return null;const n=t&&(t.total_tokens||0),r=t&&(t.output_tokens||t.completion_tokens||0);if(n>0||r>0)return null;const o=e.trim();if(!o||o.length>160||o.includes("\n"))return null;for(const e of PROVIDER_REFUSAL_PATTERNS)if(e.test(o))return o;return null}function briefArgs(e){let t;try{t="string"==typeof e?e:JSON.stringify(e??"")}catch{t=String(e)}return t=String(t).replace(/\s+/g," ").trim(),t.length>140?`${t.slice(0,137)}...`:t}function createApp(e={}){const t={model:null,stream:!0,light:!1,maxTokens:void 0,system:void 0,interactive:!0,...e},n=e.out||process.stdout,r=e.err||process.stderr,o=e.client||createClient(credentials.clientOptions({channel:"cli"})),{TOOLS:s,toolList:i}=e.tools||createTools(o);let a=!1,l="";async function c(){const e=await autoProvisionApiKey(o,credentials,{app:"cli"});return l=e.key?"":provisionFailureText(e),e}async function d(){if(o.apiKey||a)return;a=!0;const e=await c();e.key&&Y(render.renderNotice(b(),"info","auto-provisioned a free account"+(e.ok?` (saved to ${credentials.credentialsPath()})`:" (could not save it — reconfigure with /key)")+trialNote(e)+`. Fund it at ${o.promptUrl("topup","device_autoprovision")} or run /byok to use your own key.`))}let u=!1!==e.confirmMode,m=(()=>{try{return autonomous.autoRoundsDefault(process.env)}catch{return!0}})();const f=e.engine||createEngine({client:o,getClass:()=>g.modelClass,getProEnabled:()=>{try{return proEnabled(loadConfig())}catch{return!1}},getConfirmMode:()=>{if(void 0!==e.confirmMode)return u;try{const e=resolveSkip({env:process.env,interactive:Boolean(process.stdin.isTTY&&process.stdout.isTTY)});if(e.warned&&!skipEnvWarned&&(skipEnvWarned=!0,process.stderr.write(`aegiscode: ${e.warning}\n`)),e.skip)return!1}catch{}try{return confirmPosture().enabled}catch{return u}}}),p=e=>"function"==typeof f.classLabel?f.classLabel(e):String(e||"");let y=null;const h=()=>e.width?e.width():termWidth(),g={light:t.light,model:t.model,modelClass:DEFAULT_CLASS,effort:null,thinking:!1,recallDeep:!1,themeIndex:t.light?2:AUTO_THEME_INDEX,vim:!1,stream:t.stream,cwd:process.cwd(),lastRecap:null,sessionId:randomUUID()};g.themeIndex===AUTO_THEME_INDEX&&(g.light=themeIsLight(AUTO_THEME_INDEX));const k=[];let v=!1;const b=()=>({light:g.light}),S={turns:0,calls:0,tokens:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,cost:0,balance:null,seenLedgerRows:new Map,ledgerBaselined:!1,startedAt:Date.now()};let T=null,E=!1;function C(e){if(!e||"object"!=typeof e)return null;if("usage"!==e.kind)return null;const t=null!=e.amount_eur?Number(e.amount_eur):-Number(e.charged_micros||0)/1e6;return Number.isFinite(t)?Math.abs(t):null}function I(e){return[e.created_at||"",e.kind||"",null!=e.amount_eur?e.amount_eur:"",null!=e.charged_micros?e.charged_micros:"",null!=e.id?e.id:"",null!=e.note?e.note:""].join("|")}async function N(){try{const e=await o.tokenBankBalance(),t=Number(e.balance_eur);Number.isFinite(t)&&(S.balance=t);let n=null;const r=Array.isArray(e.ledger)?e.ledger:[],s=new Map;for(const e of r){const t=I(e),n=s.get(t);n?n.n+=1:s.set(t,{n:1,row:e})}for(const[e,{n:t,row:r}]of s){const o=S.seenLedgerRows.get(e)||0;if(S.seenLedgerRows.set(e,t),!S.ledgerBaselined)continue;const s=t-o;if(s<=0)continue;const i=C(r);null!=i&&i>0&&(S.cost+=i*s,null==n&&(n=i))}return S.ledgerBaselined=!0,{balance:S.balance,lastCost:n}}catch{return null}}async function P(e,{verify:t=!0}={}){const n=credentials.saveApiKey(e);if(!n.ok)return n;o.setApiKey(n.key),R.models=[],R.at=0;let r=null,s=null;if(t)try{const e=await o.verifyApiKey()||{};r=e;const t={verifiedAt:(new Date).toISOString()};e.memory_token&&(t.memoryToken=e.memory_token),e.plan&&(t.plan=e.plan),t.account={plan:e.plan||null,email:e.email||null,valid:!1!==e.valid},credentials.writeCredentials(t),e.plan&&(S.plan=e.plan),e.email&&(S.account={...S.account||{},email:e.email})}catch(e){s=e}return{...n,account:r,error:s}}function x(){const e=credentials.clearApiKey();return o.setApiKey(""),R.models=[],R.at=0,e}function A(){try{return memoryPersistEnabled()}catch{return!0}}function L(){try{return memoryPersistState()}catch{return{enabled:!0,source:"default",explicit:!1}}}function O(e){return setMemoryPersist(e)}function _(){try{return"config"!==credentials.resolveApiKey().source?[]:credentials.adoptLegacy().adopted}catch{return[]}}const M=3e5,R={at:0,models:[]},$={at:0,models:[],declared:""};async function K({force:e=!1}={}){const t=function(){try{if("function"!=typeof f.userModels)return"";const e=(f.userModels()||{}).map||{};return JSON.stringify(Object.keys(e).sort().map((t=>[t,e[t]])))}catch{return""}}(),n=$.models.length&&Date.now()-$.at<M&&t===$.declared;if(!e&&n)return $.models;if("function"!=typeof f.listModels)return[];const r=await f.listModels("byok");return $.models=(r&&r.models||[]).map((e=>({...e,note:e.configured?"key on this machine":`no key — /byok-key ${e.provider}`}))),$.at=Date.now(),$.declared=t,$.models}async function D(e){const t=H();if(e&&!t.includes(e)&&HOST_CLASSES.includes(e))return[];const n=t.includes(e)?e:g.modelClass;try{if("byok"===n){const e=await K();if(!R.models.length)try{await F()}catch{}return q(e,n)}if("pro"===n){const e=await f.listModels("pro");return e&&e.models||[]}if("aegis"!==n){const e=await f.listModels(n);return e&&e.models||[]}return await F()}catch{return[]}}function j(){return pickerEntries(R.models).map((e=>({...e,cls:"aegis"})))}function q(e,t){const n=H(),r=n.includes(t)?t:g.modelClass;if("pro"===t&&!n.includes("pro"))return[];if("pro"===r)return pickerEntries(claudePro.PRO_MODELS.map((e=>({id:e.id,label:e.label,note:e.note})))).map((e=>({...e,cls:"pro"})));if("byok"!==r)return j();const o=Array.isArray(e)?e.map((e=>({...e,cls:"byok"}))):pickerEntries($.models).map((e=>({...e,cls:"byok"})));return[...j(),...o]}function B(){return new Set(claudePro.PRO_MODELS.map((e=>String(e.id).toLowerCase())))}function H(){try{return offeredClasses(proEnabled(loadConfig()))}catch{return offeredClasses(!1)}}async function F({force:e=!1}={}){const t=R.models.length&&Date.now()-R.at<M;if(!e&&t)return R.models;const n=await o.listModels();return R.models=normalizeModelCatalog(n&&n.models),R.at=Date.now(),R.models}async function U(){const e=g.model;if(!e)return null;if("byok"===g.modelClass)return String(e).includes(":")?null:(g.model=null,updateConfig({model:null,currentModelId:null}),Y(render.renderNotice(b(),"warn",`pinned model "${e}" belongs to the pooled class — on BYOK an id is "<provider>:<model>"; pin cleared, /models lists what this machine can relay.`)),e);if("pro"===g.modelClass){if(!B().has(String(e).toLowerCase()))return g.model=null,updateConfig({model:null,currentModelId:null}),Y(render.renderNotice(b(),"warn",`pinned model "${e}" is not one the Claude Code CLI resolves — pin cleared, the CLI will choose; /models lists the aliases (${claudePro.PRO_MODELS.map((e=>e.id)).join(", ")}).`)),e;let t=!0;try{t=!!claudePro.claudeProStatus({env:process.env}).credentialPresent}catch{t=!0}return t?null:(g.model=null,updateConfig({model:null,currentModelId:null}),Y(render.renderNotice(b(),"warn",`pinned model "${e}" needs a Claude Pro subscription or an ANTHROPIC_API_KEY, and this host has neither — pin cleared. Run \`claude /login\`, export a console key, or \`/class pro off\`.`)),e)}let t;try{t=await F()}catch{return null}return t.length?catalogIds(t).has(String(e).toLowerCase())?null:(g.model=null,updateConfig({model:null,currentModelId:null}),Y(render.renderNotice(b(),"warn",`pinned model "${e}" is not advertised by AEGIS Cloud — pin cleared, the pool will choose; /models lists what you can pin.`)),e):null}function W(){return render.renderBanner(b(),{width:h(),version:VERSION,model:g.model||"server default",base:o.apiBase,key:maskKey(o.apiKey),stream:g.stream})}function Y(e){const t="string"==typeof e?[e]:e;for(const e of t)n.write(e+"\n")}async function V(e,{history:o=[],presenter:s=null,signal:i=null}={}){const a=Date.now(),l=!s&&t.interactive&&t.stream&&n.isTTY?new LiveRegion(n):null;let c=0,d=0,u="",m=0,p=0,k=VERBS[Math.floor(Math.random()*VERBS.length)],v=!1,S=!1;const E=()=>{l&&l.update([render.renderWorking(b(),{tick:c++,verb:k,elapsedMs:Date.now()-a,streamed:estimateTokensFromCells(d+m)+p,streamedFloor:p>0})])},C=l?setInterval(E,90):null;C&&C.unref&&C.unref(),E();const I=s||{},N=new Map,P=randomUUID();T=P;let x=!1;const A=()=>{x=!0,f.cancel(P)},L=()=>A();process.once("SIGINT",L),i&&(i.aborted?A():i.addEventListener("abort",A,{once:!0}));const O=e=>(r.write(`aegiscode: ${e.tool} needs confirmation but this run has no prompt for it — denied (pass --automode (alias --yolo) to auto-approve mutating tools).\n`),Promise.resolve("deny")),_=()=>Promise.resolve(!1),M=e=>{if(e){if(e.thinkingTokens&&(p+=e.thinkingTokens,v||(v=!0,k="Reasoning"),(e=>{I.thinkingTokens&&I.thinkingTokens(e)})(e.thinkingTokens),E()),e.reasoning&&(m+=w(e.reasoning),v||(v=!0,k="Reasoning",E()),(e=>{I.reasoning&&I.reasoning(e)})(e.reasoning)),e.delta&&(d+=w(e.delta),u+=e.delta,(e=>{if(I.text)return I.text(e);l&&c%2==0&&E()})(e.delta)),e.tool&&(S=!0,(e=>{if(I.tool)return I.tool(e);l&&l.clear();const t=(e=>{const t=e&&void 0!==e.id?`id:${e.id}`:`${e&&e.name}:${JSON.stringify(e&&e.args)}`;return N.has(t)||N.set(t,editPreview(e&&e.name,e&&e.args,{cwd:process.cwd()})),N.get(t)})(e);Y(render.renderTurn(b(),{role:"tool",label:e.name,args:e.args,ok:e.ok,diff:t,diffOpen:defaultOpen(t)},h())),E()})(e.tool)),e.approval){const t=e.approval;l&&l.clear();const n=I.approval||y||O;Promise.resolve(n(t)).catch((()=>"deny")).then((e=>f.respondApproval(t.id,normalizeDecision(e))))}if(e.rounds){const t=e.rounds;l&&l.clear();const n=I.rounds||_;Promise.resolve(n(t)).catch((()=>!1)).then((e=>f.respondRoundsAsk(t.id,!0===e)))}}};try{const n=await f.chat({prompt:e,messages:o,model:g.model||void 0,system:t.system||defaultSystemPrompt(),maxTokens:t.maxTokens,effort:effortRung(g.effort),recallDeep:!0===g.recallDeep||void 0,stream:!1!==g.stream,sessionId:P,sessionKey:g.sessionId,roundsAsk:Boolean(I.rounds)},M),r=n.choices&&n.choices[0]||{};return{text:r.message&&r.message.content||u,usage:n.usage||null,model:n.model||g.model||null,ms:Date.now()-a,interrupted:x,reasoningChars:m,usedTools:S}}catch(e){if(x&&u)return{text:u,usage:null,model:g.model||null,ms:Date.now()-a,interrupted:!0,reasoningChars:m,usedTools:S};throw e}finally{C&&clearInterval(C),process.removeListener("SIGINT",L),i&&i.removeEventListener("abort",A),l&&l.clear(),T=null}}function G(e){Y(render.renderTurn(b(),e,h()))}async function z(e,{label:t="you"}={}){if(!e)return void Y(render.renderNotice(b(),"warn","nothing to ask — give /ask a prompt"));if(o.apiKey||await d(),!o.apiKey)return void Y(render.renderNotice(b(),"error",`no AEGIS account key — ${credentials.HOW_TO_SET} (or set $${credentials.KEY_ENV})`));const n=k.filter((e=>"user"===e.role||"assistant"===e.role)).map((e=>({role:e.role,content:e.text})));let r;G({role:"user",text:e,label:t}),k.push({role:"user",text:e});try{r=await V(e,{history:n})}catch(t){return ae(e,{text:"",error:t.message},"error"),void Y(render.renderTurn(b(),{role:"error",text:t.message},h()))}r.text&&k.push({role:"assistant",text:r.text});const s=ie(r);let i=null;try{const e=await N();i=e?e.lastCost:null}catch{}ae(e,r,r.interrupted?"stopped":r.error?"error":"done",i),G({role:"assistant",text:r.text||"(the pool returned no text — see /balance for what it charged)",meta:{model:r.model,tokens:s,usage:null==r.usage?null:usageBuckets(r.usage),eur:i,ms:r.ms,calls:1}}),r.interrupted&&Y(render.renderNotice(b(),"warn","interrupted — the pool may still be running and billing this call"))}async function X(e,t){const n=s[e];if(!n)throw new Error(`unknown tool: ${e}`);if(o.apiKey||await d(),!o.apiKey)throw new Error(`no AEGIS account key — ${credentials.HOW_TO_SET}`);const r=await n.run(t||{});Y(render.renderToolResult(b(),e,r,h()))}function J(e){const t=String(e||"").toLowerCase();if(!t)return null;let n=null;for(const e of COMMANDS)for(const r of[e.name,...e.aliases||[]])r!==t&&(r.startsWith(t)||t.startsWith(r))&&(null==n||Math.abs(r.length-t.length)<Math.abs(n.length-t.length))&&(n=r);return n}function Q(){const e=loadPermissions(),t=confirmPosture();return{version:VERSION,model:g.model||"server default",class:g.modelClass,effort:g.effort,thinking:g.thinking,theme:g.light?"light":"dark",themeIndex:g.themeIndex,vim:g.vim,stream:g.stream,cwd:g.cwd,home:os.homedir(),sessionId:g.sessionId,base:o.apiBase,keyMask:maskKey(o.apiKey),online:!!o.apiKey,turns:S.turns,calls:S.calls,startedAt:S.startedAt,tokens:{input:S.inputTokens,output:S.outputTokens,cacheRead:S.cacheReadTokens,cacheWrite:S.cacheWriteTokens,total:S.tokens},costEur:S.cost,balance:S.balance,plan:S.plan||null,account:S.account||null,permissions:{mode:t.enabled?e.defaultMode:"allow",confirm:t.enabled,source:t.source,rules:e},models:q(),commands:visibleCommands(),transcript:k.slice(),sessions:[],memory:{},lastRecap:g.lastRecap,backend:g.modelClass,url:o.apiBase}}function Z(e){return Array.isArray(e)?e.map((e=>e&&(e.s||"")+(null==e.t?"":e.t)||"")).join(""):String(null==e?"":e)}function ee(e){if(!e||"object"!=typeof e)return;const t=h();switch(e.role){case"panel":{const t=Array.isArray(e.lines)?e.lines:[];for(const e of t)Y(Z(e));return}case"note":case"tip":return void Y(render.renderNotice(b(),"info",e.text));case"done":return void Y(render.renderNotice(b(),"ok",e.text));case"error":return void Y(render.renderNotice(b(),"error",e.text));case"user":return void Y(render.renderTurn(b(),{role:"user",text:e.text,label:e.label},t));case"assistant":return void Y(render.renderTurn(b(),{role:"assistant",text:e.text},t));case"tool":return void 0===e.diff&&(e.diff=editPreview(e.name||e.label,e.args,{cwd:process.cwd()}),e.diffOpen=defaultOpen(e.diff)),void Y(render.renderTurn(b(),{role:"tool",label:e.label||e.name,args:e.args,ok:e.ok,diff:e.diff,diffOpen:!!e.diffOpen},t));default:return void Y(render.renderNotice(b(),"info",null==e.text?"":String(e.text)))}}function te(e){return{t:e,s:"",w:w(e)}}async function ne(){return!e.readline&&process.stdin.isTTY&&process.stdout.isTTY&&!1!==e.chatflow?screens.showThemePicker(g):(g.light=!g.light,g.themeIndex=g.light?2:1,Y(render.renderNotice(b(),"ok","theme: "+(g.light?"light":"dark"))),g.themeIndex)}function re(){const e={ctx:g,transcript:k,push:e=>ee(e),note:e=>ee({role:"note",text:e}),panel:e=>ee({role:"panel",lines:e}),render:()=>{},openOverlay:e=>function(e){if(!e||"object"!=typeof e)return;const t=h(),n=Math.max(5,process.stdout&&process.stdout.rows||24);let r=null;if("panel"===e.type?r=e.lines:"palette"===e.type?r=overlays.renderPalette(visibleCommands(),{query:e.query||"",sel:e.sel||0},t,n):"model"===e.type?r=overlays.renderModelPicker(e.items||[],e.sel||0,t,n,null!=e.current?e.current:g.model,e.cls||g.modelClass,p):"effort"===e.type?r=overlays.renderEffortPicker(e.sel||0,t,g.effort):"class"===e.type?r=overlays.renderClassPicker(e.items||[],e.sel||0,t,e.current||g.modelClass,p):"provider"===e.type?r=overlays.renderProviderPicker(e.items||[],e.sel||0,t,e.current,e.hint):"resume"===e.type?r=overlays.renderResumeList(e.items||[],e.sel||0,t,n):"confirm"===e.type&&(r=render.renderApproval(b(),e.info||{},t).map((e=>[te(e)]))),r)for(const e of r)Y(Z(e))}(e),closeOverlay:()=>{},setAutoRounds:e=>{m=Boolean(e)},askInput:()=>Promise.resolve(null),withWorking:e=>async function(e){const r=new AbortController,o=t.interactive&&n.isTTY?new LiveRegion(n):null;let s=null;if(o){let e=0;const t=Date.now(),n=()=>o.update([render.renderWorking(b(),{tick:e++,verb:VERBS[0],elapsedMs:Date.now()-t})]);n(),s=setInterval(n,90),s.unref&&s.unref()}try{return await e(r.signal)}finally{s&&clearInterval(s),o&&o.clear()}}(e),runPrompt:e=>z(e),ask:e=>V(e),runTool:(e,t)=>X(e,t),loadModels:()=>D(g.modelClass),settings:()=>f.settings||null,byokNamespace:e=>byokNamespace(e),listModelsFor:e=>D(e),refreshByokModels:()=>K({force:!0}),switchClass:e=>function(e){const t=String(null==e?"":e).trim().toLowerCase(),n=H();if(!n.includes(t))return"pro"===t?{ok:!1,error:"the pro class (your Claude Code subscription) is off by default — enable it once with `/class pro on`"}:{ok:!1,error:`unknown class "${e}" — classes: ${n.join(", ")}`};const r=g.modelClass;g.modelClass=t;let o=null;return r!==t&&g.model&&(function(e,t){const n=String(null==t?"":t);return"byok"===e?n.includes(":"):"pro"===e?B().has(n.toLowerCase()):!n.includes(":")}(t,g.model)||(o=g.model,g.model=null)),updateConfig({modelClass:t,model:g.model,currentModelId:g.model}),{ok:!0,class:t,prev:r,cleared:o}}(e),classLabel:e=>p(e),classes:()=>"function"==typeof f.listClasses?f.listClasses():[],refreshSpend:()=>N(),state:()=>Q(),setInput:()=>{},exit:()=>{v=!0},client:o,TOOLS:s,saveConfig:e=>updateConfig(e),showThemePicker:()=>ne(),keyStatus:()=>credentials.keyStatus(),setApiKey:(e,t)=>P(e,t),forgetApiKey:()=>x(),registerAccount:()=>async function(){return o.apiKey?{alreadyKeyed:!0}:c()}(),readSecret:e=>readSecret(e,{stdin:process.stdin,stdout:n}),cloudsync:cloudsync,cloudSyncEnabled:()=>A(),cloudSyncState:()=>L(),setCloudSync:e=>O(e),adoptLegacyKey:()=>_()};return Object.defineProperty(e,"sessionId",{enumerable:!0,get:()=>g.sessionId,set:e=>{g.sessionId=e}}),e.clearConversationMemory=()=>{f&&"function"==typeof f.clearSessionApprovals&&f.clearSessionApprovals(g.sessionId)},e}async function oe(e,t=null){const r=parseLine(e);if("empty"===r.kind)return!0;if("prompt"===r.kind)return await z(r.text),!0;if("unknown"===r.kind){const e=J(r.name);return Y(render.renderNotice(b(),"error",`unknown command: /${r.name}${e?` — did you mean /${e}?`:" — try /help"}`)),!0}if("unavailable"===r.kind){const e=r.command;if(Y(render.renderNotice(b(),"warn",`/${e.name} is not available in aegiscode — ${e.unavailable}`)),e.alt)Y(render.renderNotice(b(),"info",`try ${e.alt} instead`));else{const t=J(e.name);t&&Y(render.renderNotice(b(),"info",`try /${t} instead`))}return!0}const s=r.command,i=r.arg;if(s.generic){let t;try{t=s.build(i)}catch(e){return Y(render.renderNotice(b(),"error",e.message)),!0}const{tool:n,args:r}=t;if(!n)return Y(render.renderNotice(b(),"error","/tool needs a tool name — see /help")),!0;try{await X(n,r)}catch(e){Y(render.renderNotice(b(),"error",e.message))}return!0}if("function"==typeof s.handler){const n=function(e,t){const n=String(null==t?"":t),r=Array.isArray(e.args)?e.args:[],o=function(e){const t=[];let n="",r=null,o=!1;for(const s of String(e||""))r?s===r?r=null:n+=s:'"'!==s&&"'"!==s?/\s/.test(s)?(n||o)&&(t.push(n),n="",o=!1):(n+=s,o=!0):(r=s,o=!0);return(n||o)&&t.push(n),t}(n),s={_rest:n.trim()};return r.forEach(((e,t)=>{void 0!==o[t]&&(s[e]=o[t])})),s}(s,i),r=t||re();try{return!1!==await s.handler(r,n)}catch(e){return Y(render.renderNotice(b(),"error",e&&e.message?e.message:String(e))),!0}}try{let e=s.build(i);if(s.secret){const t=await async function(e,t){if("function"!=typeof e.secretDescribe)return null;try{const n=await e.secretDescribe(t,o);return n&&"object"==typeof n?n:null}catch{return null}}(s,e);if(t&&t.note&&Y(render.renderNotice(b(),"info",t.note)),t&&null===t.prompt)return!0;t&&t.provider&&(e={...e,provider:t.provider});const r=await function(e){const t=themeOf(b());return readSecret(t.gray+e+RESET,{stdin:process.stdin,stdout:n})}(t&&t.prompt||`provider key for ${e.provider}: `);if(!r)return Y(render.renderNotice(b(),"warn","empty key — nothing sent")),!0;e={...e,api_key:r}}if("aegis_ask"===s.tool)return await z(e.prompt);await X(s.tool,e),"aegis_memory_list"!==s.tool&&"aegis_memory_search"!==s.tool||function(){let e;try{e=cloudsync.status()}catch{return}const t=e.quota;if(!t)return;const n=fmtTokens(t.used||0),r=fmtTokens(t.limit||0);e.overQuota?Y(render.renderNotice(b(),"warn",`cloud memory: ${n} of ${r} synced tokens — at the plan's ceiling. Everything stored stays readable; new writes are paused until there is room. /cloud memory for the full state.`)):Y(render.renderNotice(b(),"info",`cloud memory: ${n} of ${r} synced tokens — /cloud memory for the full state`))}()}catch(e){Y(render.renderNotice(b(),"error",e.message))}return!0}async function se(){if(f&&"function"==typeof f.unloadLocalModels)try{await f.unloadLocalModels()}catch{}}function ie(e){S.turns++,S.calls+=Number(e&&e.calls||1)||1;const t=e&&e.usage,n=usageTokens(t);if(null!=n){S.tokens+=n;const e=usageBuckets(t);S.inputTokens+=e.input,S.outputTokens+=e.output,S.cacheReadTokens+=e.cacheRead,S.cacheWriteTokens+=e.cacheWrite}return n}function ae(e,t,n="done",r=null){try{const o=t&&t.usage,s="number"==typeof r&&Number.isFinite(r)?r:null,i=String(t&&t.model||g.model||"").trim();appendHistory({sessionId:g.sessionId,prompt:e,reply:t&&t.text||"",status:n,model:i||void 0,provider:i&&providerForModel({id:i,cls:g.modelClass})||void 0,usage:o?{...usageBuckets(o),...null!=s?{costUsd:s}:{}}:null!=s?{input:0,output:0,cacheRead:0,cacheWrite:0,costUsd:s}:null}),snapshotCheckpoint(g.sessionId,k)}catch{}A()&&o.apiKey&&Promise.resolve().then((()=>cloudsync.push(o))).then((e=>{if(e&&e.failed&&e.failed.length){const t=e.failed[0];if(le.has(t.kind))return;if(le.add(t.kind),"quota"===t.kind)return void Y(render.renderNotice(b(),"warn","cloud memory: the plan's synced-token ceiling is reached — earlier sessions stay readable, only NEW writes pause. /cloud memory shows the quota; /cloud memory off stops trying."));const n=t.hint?` — ${t.hint}`:"";Y(render.renderNotice(b(),"error",`cloud sync: ${t.message}${n}`))}})).catch((()=>{}))}let le=new Set;function ce(){const e=[S.outputTokens>0?`${fmtTokens(S.outputTokens)} tokens`:`${fmtTokens(S.tokens)} tokens`,`${S.calls} call${1===S.calls?"":"s"}`];return feeBillable()&&(e.push(fmtEur(S.cost)),null!=S.balance&&e.push(`balance ${fmtEur(S.balance)}`)),e.join(" · ")}async function de(e){if(!e||!e.id)return;const t=readSessionTranscript(e.id);if(t.length){k.length=0;for(const e of t)k.push(e);g.sessionId=e.id,Y(render.renderNotice(b(),"ok",`resumed ${e.id} — ${t.length} turn(s)`))}else Y(render.renderNotice(b(),"warn",`no stored turns for ${e.id}`))}function ue(){return{ctx:g,version:VERSION,transcript:k,session:S,client:o,TOOLS:s,ask:(e,t)=>V(e,t),makeCommandContext:()=>re(),accountConfigured:()=>!!(credentials.keyStatus()||{}).configured,hasProviderKey:e=>{const t=f.settings;if(!t||!e)return!1;const n=byokNamespace(e);return"function"==typeof t.rawKey?!!String(t.rawKey(n)||"").trim():"function"==typeof t.get&&!!(t.get(n)||{}).configured},loadModels:e=>F(e),buildState:()=>Q(),dispatchLine:(e,t)=>oe(e,t),refreshSpend:()=>N(),updateConfig:e=>updateConfig(e),showThemePicker:()=>ne(),persistTurn:(e,t,n,r)=>ae(e,t,n,r),nameConversation:(e,t)=>async function(e,{signal:t=null}={}){const n=await naming.nameConversation(e,{signal:t,callModel:(e,n)=>V(e,{system:n&&n.system||naming.TITLE_SYSTEM,maxTokens:64,signal:n&&n.signal||t}).then((e=>e&&e.text||null))}),r=String(n||"").trim();return r&&setSessionTitle(g.sessionId,r),r}(e,t),visibleCommands:()=>visibleCommands(),tokensFor:e=>usageTokens(e),recordTurn:e=>ie(e),tokenSummary:()=>ce(),resumeSession:e=>de(e),requestExit:()=>{v=!0},wantsExit:()=>v,keyNotice:()=>o.apiKey?"":l,isYolo:()=>{if(!m)return!1;try{return!1===confirmPosture().enabled}catch{return!1}},setAutoRounds:e=>{m=Boolean(e)}}}async function me(){Y(W()),await N(),n.write("\n");const t=e.readline||readline.createInterface({input:process.stdin,output:n,terminal:!0}),r=themeOf(b()).gold+GLYPH.cursor+" "+RESET;return t.setPrompt(r),t.prompt(),new Promise((e=>{t.on("line",(async e=>{t.pause();let n=!0;try{n=await oe(e)}catch(e){Y(render.renderNotice(b(),"error",e.message))}if(!n||v)return E=!0,void t.close();t.resume(),t.prompt()})),t.on("close",(()=>{E||n.write("\n"),e(0)}))}))}function fe(){if(e.readline)return;if(!configExists())return;let n;try{n=loadConfig()}catch{return}if(H().includes(n.modelClass)&&(g.modelClass=n.modelClass),t.class){const e=String(t.class).trim().toLowerCase();if(!H().includes(e))throw new Error(`--class ${t.class}: not available on this host (offered: ${H().join(", ")})`);g.modelClass=e}if(!t.model&&n.model&&(g.model=n.model),g.effort=effortRung(t.effort||n.effort),"boolean"==typeof n.vim&&(g.vim=n.vim),n.lastRecap&&(g.lastRecap=n.lastRecap),!t.light&&"number"==typeof n.themeIndex&&THEME_TABLE[n.themeIndex]){g.themeIndex=n.themeIndex,g.light=themeIsLight(n.themeIndex);const e=reconcileThemeIndex(g.themeIndex);if(e.changed){g.themeIndex=e.index,g.light=themeIsLight(e.index),g.themeNotice=e.reason;try{updateConfig({themeIndex:e.index,light:themeIsLight(e.index)})}catch{g.themeNotice+=" (could not save it)"}}}}return{opts:t,session:S,client:o,TOOLS:s,toolList:i,ctx:g,transcript:k,ask:V,runPrompt:z,handleLine:oe,runOnce:async function(e,t={}){try{return await async function(e,{json:t=!1}={}){if(fe(),_(),!o.apiKey&&!a){a=!0;const e=await autoProvisionApiKey(o,credentials,{app:"cli"});e.key&&r.write("aegiscode: auto-provisioned a free account"+(e.ok?` (saved to ${credentials.credentialsPath()})`:" (could not save it — reconfigure with /key)")+trialNote(e)+`. Fund it at ${o.promptUrl("topup","device_autoprovision")} or run /byok to use your own key.\n`)}if(!o.apiKey)return r.write(`aegiscode: no AEGIS account key. ${credentials.HOW_TO_SET}, or set $${credentials.KEY_ENV}.\n`),2;await N();const s=[],i=[],l=t?{tool:e=>{if("done"===(e&&e.phase)){const t=e.id&&i.find((t=>t.id===e.id&&!0!==t.settled))||(e.id?null:i[i.length-1]);t?(t.settled=!0,t.ok=!1!==e.ok):(e&&e.name&&s.push(e.name),i.push({name:e&&e.name||null,id:e&&e.id||null,args:briefArgs(e&&e.args),settled:!0,ok:!1!==e.ok}))}else e&&e.name&&s.push(e.name),i.push({name:e&&e.name||null,id:e&&e.id||null,args:briefArgs(e&&e.args),settled:!1,ok:null});const t=e&&void 0!==e.preview?e.preview:null,n=render.renderTurn(b(),{role:"tool",label:e.name,args:e.args,ok:e.ok,diff:t,diffOpen:!1},h());for(const e of Array.isArray(n)?n:[n])r.write(e+"\n")}}:null,c=await V(e,l?{presenter:l}:{});await N();const d=usageTokens(c.usage),u=providerRefusal(c.text,c.usage);if(t)n.write(JSON.stringify({text:c.text,model:c.model,class:g.modelClass,rounds:c.usage&&Number(c.usage.calls)||null,usage:c.usage,reasoning_chars:"number"==typeof c.reasoningChars?c.reasoningChars:null,tokens:d,ms:c.ms,interrupted:c.interrupted,...s.length?{tools:s}:{},...i.length?{tool_log:i}:{},...u?{error:u}:{},balance_eur:S.balance},null,2)+"\n");else if(n.write(c.text+"\n"),u&&r.write(`aegiscode: the provider refused this turn — ${u}\n`),null!=d){const e=themeOf(b());n.write(e.dim+GLYPH.hook+" "+e.blue+(c.model||"aegis")+RESET+e.dim+" "+GLYPH.bullet+" "+RESET+e.white+`${fmtTokens(d)} tokens`+RESET+"\n")}return c.interrupted?130:u?1:0}(e,t)}finally{await se()}},runInteractive:async function(){try{return await async function(){if(!e.readline&&!1!==e.chatflow&&process.stdin.isTTY&&process.stdout.isTTY){await probeTerminalBackground({onLeftover:e=>events.feedKeys(e,{keystrokes:!0})}),fe(),function(){if(!g.themeNotice)return;const e=g.themeNotice;g.themeNotice="",Y(render.renderNotice(b(),"warn",`theme: ${e} (saved)`))}(),_(),o.apiKey||await d();const t=await screens.runOnboarding(g,{continue:!!e.continue,seen:e.seen||configExists,save:e=>updateConfig(e),needsKey:()=>!o.apiKey,submitKey:e=>P(e)});if(!t.ok)return 0;if(t.key&&t.key.set&&Y(render.renderNotice(b(),"info",`key saved to ${credentials.credentialsPath()} — no export needed from now on`)),t.key&&t.key.skipped&&!o.apiKey&&Y(render.renderNotice(b(),"warn","no key saved — /key <api_key> or `aegiscode login` whenever you are ready")),t.firstRun&&function(){if(!L().enabled)return void Y(render.renderNotice(b(),"info","cross-session memory: off (you turned it off) — /cloud memory on stores sessions so an interrupted turn can be picked up later"));const e=cloudsync.status().quota,t=e&&e.limit?` (used ${fmtTokens(e.used||0)} of ${fmtTokens(e.limit)} tokens)`:"";Y(render.renderNotice(b(),"info",`cross-session memory: on${t} — sessions are stored to your account so a turn that is interrupted can be resumed. /cloud memory shows the quota; /cloud memory off stops it. Past the ceiling, saved memory stays readable and only new writes pause.`))}(),await U(),e.continue){const e=readOwnSessions(1)[0];e&&(g.continueSession=e.id,await de({id:e.id}))}return await N(),await chatflow.runSession(ue()),0}return fe(),_(),me()}()}finally{await se()}},runLinearRepl:me,refreshSpend:N,bannerLines:W,makeHost:ue,loadModels:F,validatePinnedModel:U,recordTurn:ie,persistTurn:ae,restorePrefs:fe,setApiKey:P,forgetApiKey:x,adoptLegacyKeyOnce:_,cloudSyncEnabled:A,cloudSyncState:L,setCloudSync:O,cloudsync:cloudsync,keyStatus:()=>credentials.keyStatus(),accountConfigured:()=>!!(credentials.keyStatus()||{}).configured,hasProviderKey:e=>{const t=f.settings;if(!t||!e)return!1;const n=byokNamespace(e);return"function"==typeof t.rawKey?!!String(t.rawKey(n)||"").trim():"function"==typeof t.get&&!!(t.get(n)||{}).configured},sessionId:()=>g.sessionId,tokenSummary:ce,resumeSession:de,makeCommandContext:re,buildState:Q,get aborted(){return!1}}}module.exports={createApp:createApp,VERSION:VERSION,normalizeDecision:normalizeDecision};
|
|
3
|
+
"use strict";const readline=require("node:readline"),os=require("node:os"),{randomUUID:randomUUID}=require("node:crypto"),{createTools:createTools,createClient:createClient,usageTokens:usageTokens,usageBuckets:usageBuckets,buildSystemPrompt:buildSystemPrompt,autoProvisionApiKey:autoProvisionApiKey,provisionFailureText:provisionFailureText,trialNote:trialNote,hostEnv:hostEnv,autonomous:autonomous,claudePro:claudePro}=require("./deps.js"),{createEngine:createEngine,HOST_CLASSES:HOST_CLASSES,DEFAULT_CLASS:DEFAULT_CLASS,byokNamespace:byokNamespace,effortRung:effortRung,offeredClasses:offeredClasses,proEnabled:proEnabled}=require("./engine.js"),{GLYPH:GLYPH,VERBS:VERBS,themeOf:themeOf,RESET:RESET,THEME_TABLE:THEME_TABLE,AUTO_THEME_INDEX:AUTO_THEME_INDEX,themeIsLight:themeIsLight,reconcileThemeIndex:reconcileThemeIndex}=require("./theme.js"),{probeTerminalBackground:probeTerminalBackground}=require("./caps.js"),{LiveRegion:LiveRegion,termWidth:termWidth,w:w}=require("./screen.js"),{estimateTokensFromCells:estimateTokensFromCells}=require("./tokens.js"),{editPreview:editPreview}=require("./diff.js"),{defaultOpen:defaultOpen}=require("./diffview.js"),{parseLine:parseLine,COMMANDS:COMMANDS,visibleCommands:visibleCommands}=require("./commands.js"),{updateConfig:updateConfig,loadPermissions:loadPermissions,loadConfig:loadConfig,configExists:configExists,memoryPersistState:memoryPersistState,memoryPersistEnabled:memoryPersistEnabled,setMemoryPersist:setMemoryPersist,confirmPosture:confirmPosture}=require("./config.js"),credentials=require("./credentials.js"),events=require("./events.js"),cloudsync=require("./cloudsync.js"),{readSecret:readSecret}=require("./secret.js"),{normalizeModelCatalog:normalizeModelCatalog,pickerEntries:pickerEntries,catalogIds:catalogIds,providerForModel:providerForModel}=require("./models.js"),{appendHistory:appendHistory,readSessionTranscript:readSessionTranscript,readOwnSessions:readOwnSessions,setSessionTitle:setSessionTitle}=require("./history.js"),naming=require("./naming.js"),{snapshotCheckpoint:snapshotCheckpoint}=require("./checkpoint.js"),screens=require("./screens.js"),chatflow=require("./chatflow.js"),overlays=require("./overlays.js"),render=require("./render.js"),{fmtTokens:fmtTokens,fmtEur:fmtEur,maskKey:maskKey,feeBillable:feeBillable}=require("./format.js"),{resolveSkip:resolveSkip}=require("./permissions.js"),VERSION=require("../package.json").version;let _defaultSystem=null;function defaultSystemPrompt(){if(null===_defaultSystem)try{_defaultSystem=buildSystemPrompt(hostEnv({},{},null))}catch{_defaultSystem=""}return _defaultSystem||void 0}function normalizeDecision(e){const t="string"==typeof e?e.trim().toLowerCase():"";return"session"===t?"session":"once"===t||"allow"===t||"yes"===t||"approve"===t||"approved"===t?"once":"deny"}const PROVIDER_REFUSAL_PATTERNS=Object.freeze([/^invalid api key\b/i,/^fix external api key\b/i,/^you've hit your session limit\b/i,/^you have hit your session limit\b/i,/^provider request timed out\b/i,/^insufficient (?:credit|balance|quota)\b/i,/^rate limit(?:ed)?\b/i,/^unauthorized\b/i]);function providerRefusal(e,t){if("string"!=typeof e)return null;const n=t&&(t.total_tokens||0),r=t&&(t.output_tokens||t.completion_tokens||0);if(n>0||r>0)return null;const o=e.trim();if(!o||o.length>160||o.includes("\n"))return null;for(const e of PROVIDER_REFUSAL_PATTERNS)if(e.test(o))return o;return null}function briefArgs(e){let t;try{t="string"==typeof e?e:JSON.stringify(e??"")}catch{t=String(e)}return t=String(t).replace(/\s+/g," ").trim(),t.length>140?`${t.slice(0,137)}...`:t}function createApp(e={}){const t={model:null,stream:!0,light:!1,maxTokens:void 0,system:void 0,interactive:!0,...e},n=e.out||process.stdout,r=e.err||process.stderr,o=e.client||createClient(credentials.clientOptions({channel:"cli"})),{TOOLS:s,toolList:i}=e.tools||createTools(o);let a=!1,l="";async function c(){const e=await autoProvisionApiKey(o,credentials,{app:"cli"});return l=e.key?"":provisionFailureText(e),e}async function d(){if(o.apiKey||a)return;a=!0;const e=await c();e.key&&Y(render.renderNotice(b(),"info","auto-provisioned a free account"+(e.ok?` (saved to ${credentials.credentialsPath()})`:" (could not save it — reconfigure with /key)")+trialNote(e)+`. Fund it at ${o.promptUrl("topup","device_autoprovision")} or run /byok to use your own key.`))}let u=!1!==e.confirmMode,m=(()=>{try{return autonomous.autoRoundsDefault(process.env)}catch{return!0}})();const f=e.engine||createEngine({client:o,getClass:()=>g.modelClass,getProEnabled:()=>{try{return proEnabled(loadConfig())}catch{return!1}},getConfirmMode:()=>{if(void 0!==e.confirmMode)return u;try{const e=resolveSkip({env:process.env,interactive:Boolean(process.stdin.isTTY&&process.stdout.isTTY)});if(e.warned&&!skipEnvWarned&&(skipEnvWarned=!0,process.stderr.write(`aegiscode: ${e.warning}\n`)),e.skip)return!1}catch{}try{return confirmPosture().enabled}catch{return u}}}),p=e=>"function"==typeof f.classLabel?f.classLabel(e):String(e||"");let y=null;const h=()=>e.width?e.width():termWidth(),g={light:t.light,model:t.model,modelClass:DEFAULT_CLASS,effort:null,thinking:!1,recallDeep:!1,themeIndex:t.light?2:AUTO_THEME_INDEX,vim:!1,stream:t.stream,cwd:process.cwd(),lastRecap:null,sessionId:randomUUID()};g.themeIndex===AUTO_THEME_INDEX&&(g.light=themeIsLight(AUTO_THEME_INDEX));const k=[];let v=!1;const b=()=>({light:g.light}),S={turns:0,calls:0,tokens:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,cost:0,balance:null,seenLedgerRows:new Map,ledgerBaselined:!1,startedAt:Date.now()};let T=null,E=!1;function C(e){if(!e||"object"!=typeof e)return null;if("usage"!==e.kind)return null;const t=null!=e.amount_eur?Number(e.amount_eur):-Number(e.charged_micros||0)/1e6;return Number.isFinite(t)?Math.abs(t):null}function I(e){return[e.created_at||"",e.kind||"",null!=e.amount_eur?e.amount_eur:"",null!=e.charged_micros?e.charged_micros:"",null!=e.id?e.id:"",null!=e.note?e.note:""].join("|")}async function N(){try{const e=await o.tokenBankBalance(),t=Number(e.balance_eur);Number.isFinite(t)&&(S.balance=t);let n=null;const r=Array.isArray(e.ledger)?e.ledger:[],s=new Map;for(const e of r){const t=I(e),n=s.get(t);n?n.n+=1:s.set(t,{n:1,row:e})}for(const[e,{n:t,row:r}]of s){const o=S.seenLedgerRows.get(e)||0;if(S.seenLedgerRows.set(e,t),!S.ledgerBaselined)continue;const s=t-o;if(s<=0)continue;const i=C(r);null!=i&&i>0&&(S.cost+=i*s,null==n&&(n=i))}return S.ledgerBaselined=!0,{balance:S.balance,lastCost:n}}catch{return null}}async function P(e,{verify:t=!0}={}){const n=credentials.saveApiKey(e);if(!n.ok)return n;o.setApiKey(n.key),R.models=[],R.at=0;let r=null,s=null;if(t)try{const e=await o.verifyApiKey()||{};r=e;const t={verifiedAt:(new Date).toISOString()};e.memory_token&&(t.memoryToken=e.memory_token),e.plan&&(t.plan=e.plan),t.account={plan:e.plan||null,email:e.email||null,valid:!1!==e.valid},credentials.writeCredentials(t),e.plan&&(S.plan=e.plan),e.email&&(S.account={...S.account||{},email:e.email})}catch(e){s=e}return{...n,account:r,error:s}}function x(){const e=credentials.clearApiKey();return o.setApiKey(""),R.models=[],R.at=0,e}function A(){try{return memoryPersistEnabled()}catch{return!0}}function L(){try{return memoryPersistState()}catch{return{enabled:!0,source:"default",explicit:!1}}}function O(e){return setMemoryPersist(e)}function _(){try{return"config"!==credentials.resolveApiKey().source?[]:credentials.adoptLegacy().adopted}catch{return[]}}const M=3e5,R={at:0,models:[]},$={at:0,models:[],declared:""};async function K({force:e=!1}={}){const t=function(){try{if("function"!=typeof f.userModels)return"";const e=(f.userModels()||{}).map||{};return JSON.stringify(Object.keys(e).sort().map((t=>[t,e[t]])))}catch{return""}}(),n=$.models.length&&Date.now()-$.at<M&&t===$.declared;if(!e&&n)return $.models;if("function"!=typeof f.listModels)return[];const r=await f.listModels("byok");return $.models=(r&&r.models||[]).map((e=>({...e,note:e.configured?"key on this machine":`no key — /byok-key ${e.provider}`}))),$.at=Date.now(),$.declared=t,$.models}async function D(e){const t=H();if(e&&!t.includes(e)&&HOST_CLASSES.includes(e))return[];const n=t.includes(e)?e:g.modelClass;try{if("byok"===n){const e=await K();if(!R.models.length)try{await F()}catch{}return q(e,n)}if("pro"===n){const e=await f.listModels("pro");return(e&&e.models||[]).map((e=>({...e,cls:"pro"})))}if("aegis"!==n){const e=await f.listModels(n);return e&&e.models||[]}return await F()}catch{return[]}}function j(){return pickerEntries(R.models).map((e=>({...e,cls:"aegis"})))}function q(e,t){const n=H(),r=n.includes(t)?t:g.modelClass;if("pro"===t&&!n.includes("pro"))return[];if("pro"===r)return pickerEntries(claudePro.PRO_MODELS.map((e=>({id:e.id,label:e.label,note:e.note})))).map((e=>({...e,cls:"pro"})));if("byok"!==r)return j();const o=Array.isArray(e)?e.map((e=>({...e,cls:"byok"}))):pickerEntries($.models).map((e=>({...e,cls:"byok"})));return[...j(),...o]}function B(){return new Set(claudePro.PRO_MODELS.map((e=>String(e.id).toLowerCase())))}function H(){try{return offeredClasses(proEnabled(loadConfig()))}catch{return offeredClasses(!1)}}async function F({force:e=!1}={}){const t=R.models.length&&Date.now()-R.at<M;if(!e&&t)return R.models;const n=await o.listModels();return R.models=normalizeModelCatalog(n&&n.models),R.at=Date.now(),R.models}async function U(){const e=g.model;if(!e)return null;if("byok"===g.modelClass)return String(e).includes(":")?null:(g.model=null,updateConfig({model:null,currentModelId:null}),Y(render.renderNotice(b(),"warn",`pinned model "${e}" belongs to the pooled class — on BYOK an id is "<provider>:<model>"; pin cleared, /models lists what this machine can relay.`)),e);if("pro"===g.modelClass){if(!B().has(String(e).toLowerCase()))return g.model=null,updateConfig({model:null,currentModelId:null}),Y(render.renderNotice(b(),"warn",`pinned model "${e}" is not one the Claude Code CLI resolves — pin cleared, the CLI will choose; /models lists the aliases (${claudePro.PRO_MODELS.map((e=>e.id)).join(", ")}).`)),e;let t=!0;try{t=!!claudePro.claudeProStatus({env:process.env}).credentialPresent}catch{t=!0}return t?null:(g.model=null,updateConfig({model:null,currentModelId:null}),Y(render.renderNotice(b(),"warn",`pinned model "${e}" needs a Claude Pro subscription or an ANTHROPIC_API_KEY, and this host has neither — pin cleared. Run \`claude /login\`, export a console key, or \`/class pro off\`.`)),e)}let t;try{t=await F()}catch{return null}return t.length?catalogIds(t).has(String(e).toLowerCase())?null:(g.model=null,updateConfig({model:null,currentModelId:null}),Y(render.renderNotice(b(),"warn",`pinned model "${e}" is not advertised by AEGIS Cloud — pin cleared, the pool will choose; /models lists what you can pin.`)),e):null}function W(){return render.renderBanner(b(),{width:h(),version:VERSION,model:g.model||"server default",base:o.apiBase,key:maskKey(o.apiKey),stream:g.stream})}function Y(e){const t="string"==typeof e?[e]:e;for(const e of t)n.write(e+"\n")}async function V(e,{history:o=[],presenter:s=null,signal:i=null}={}){const a=Date.now(),l=!s&&t.interactive&&t.stream&&n.isTTY?new LiveRegion(n):null;let c=0,d=0,u="",m=0,p=0,k=VERBS[Math.floor(Math.random()*VERBS.length)],v=!1,S=!1;const E=()=>{l&&l.update([render.renderWorking(b(),{tick:c++,verb:k,elapsedMs:Date.now()-a,streamed:estimateTokensFromCells(d+m)+p,streamedFloor:p>0})])},C=l?setInterval(E,90):null;C&&C.unref&&C.unref(),E();const I=s||{},N=new Map,P=randomUUID();T=P;let x=!1;const A=()=>{x=!0,f.cancel(P)},L=()=>A();process.once("SIGINT",L),i&&(i.aborted?A():i.addEventListener("abort",A,{once:!0}));const O=e=>(r.write(`aegiscode: ${e.tool} needs confirmation but this run has no prompt for it — denied (pass --automode (alias --yolo) to auto-approve mutating tools).\n`),Promise.resolve("deny")),_=()=>Promise.resolve(!1),M=e=>{if(e){if(e.thinkingTokens&&(p+=e.thinkingTokens,v||(v=!0,k="Reasoning"),(e=>{I.thinkingTokens&&I.thinkingTokens(e)})(e.thinkingTokens),E()),e.reasoning&&(m+=w(e.reasoning),v||(v=!0,k="Reasoning",E()),(e=>{I.reasoning&&I.reasoning(e)})(e.reasoning)),e.delta&&(d+=w(e.delta),u+=e.delta,(e=>{if(I.text)return I.text(e);l&&c%2==0&&E()})(e.delta)),e.tool&&(S=!0,(e=>{if(I.tool)return I.tool(e);l&&l.clear();const t=(e=>{const t=e&&void 0!==e.id?`id:${e.id}`:`${e&&e.name}:${JSON.stringify(e&&e.args)}`;return N.has(t)||N.set(t,editPreview(e&&e.name,e&&e.args,{cwd:process.cwd()})),N.get(t)})(e);Y(render.renderTurn(b(),{role:"tool",label:e.name,args:e.args,ok:e.ok,diff:t,diffOpen:defaultOpen(t)},h())),E()})(e.tool)),e.approval){const t=e.approval;l&&l.clear();const n=I.approval||y||O;Promise.resolve(n(t)).catch((()=>"deny")).then((e=>f.respondApproval(t.id,normalizeDecision(e))))}if(e.rounds){const t=e.rounds;l&&l.clear();const n=I.rounds||_;Promise.resolve(n(t)).catch((()=>!1)).then((e=>f.respondRoundsAsk(t.id,!0===e)))}}};try{const n=await f.chat({prompt:e,messages:o,model:g.model||void 0,system:t.system||defaultSystemPrompt(),maxTokens:t.maxTokens,effort:effortRung(g.effort),recallDeep:!0===g.recallDeep||void 0,stream:!1!==g.stream,sessionId:P,sessionKey:g.sessionId,roundsAsk:Boolean(I.rounds)},M),r=n.choices&&n.choices[0]||{};return{text:r.message&&r.message.content||u,usage:n.usage||null,model:n.model||g.model||null,ms:Date.now()-a,interrupted:x,reasoningChars:m,usedTools:S}}catch(e){if(x&&u)return{text:u,usage:null,model:g.model||null,ms:Date.now()-a,interrupted:!0,reasoningChars:m,usedTools:S};throw e}finally{C&&clearInterval(C),process.removeListener("SIGINT",L),i&&i.removeEventListener("abort",A),l&&l.clear(),T=null}}function G(e){Y(render.renderTurn(b(),e,h()))}async function z(e,{label:t="you"}={}){if(!e)return void Y(render.renderNotice(b(),"warn","nothing to ask — give /ask a prompt"));if(o.apiKey||await d(),!o.apiKey)return void Y(render.renderNotice(b(),"error",`no AEGIS account key — ${credentials.HOW_TO_SET} (or set $${credentials.KEY_ENV})`));const n=k.filter((e=>"user"===e.role||"assistant"===e.role)).map((e=>({role:e.role,content:e.text})));let r;G({role:"user",text:e,label:t}),k.push({role:"user",text:e});try{r=await V(e,{history:n})}catch(t){return ae(e,{text:"",error:t.message},"error"),void Y(render.renderTurn(b(),{role:"error",text:t.message},h()))}r.text&&k.push({role:"assistant",text:r.text});const s=ie(r);let i=null;try{const e=await N();i=e?e.lastCost:null}catch{}ae(e,r,r.interrupted?"stopped":r.error?"error":"done",i),G({role:"assistant",text:r.text||"(the pool returned no text — see /balance for what it charged)",meta:{model:r.model,tokens:s,usage:null==r.usage?null:usageBuckets(r.usage),eur:i,ms:r.ms,calls:1}}),r.interrupted&&Y(render.renderNotice(b(),"warn","interrupted — the pool may still be running and billing this call"))}async function X(e,t){const n=s[e];if(!n)throw new Error(`unknown tool: ${e}`);if(o.apiKey||await d(),!o.apiKey)throw new Error(`no AEGIS account key — ${credentials.HOW_TO_SET}`);const r=await n.run(t||{});Y(render.renderToolResult(b(),e,r,h()))}function J(e){const t=String(e||"").toLowerCase();if(!t)return null;let n=null;for(const e of COMMANDS)for(const r of[e.name,...e.aliases||[]])r!==t&&(r.startsWith(t)||t.startsWith(r))&&(null==n||Math.abs(r.length-t.length)<Math.abs(n.length-t.length))&&(n=r);return n}function Q(){const e=loadPermissions(),t=confirmPosture();return{version:VERSION,model:g.model||"server default",class:g.modelClass,effort:g.effort,thinking:g.thinking,theme:g.light?"light":"dark",themeIndex:g.themeIndex,vim:g.vim,stream:g.stream,cwd:g.cwd,home:os.homedir(),sessionId:g.sessionId,base:o.apiBase,keyMask:maskKey(o.apiKey),online:!!o.apiKey,turns:S.turns,calls:S.calls,startedAt:S.startedAt,tokens:{input:S.inputTokens,output:S.outputTokens,cacheRead:S.cacheReadTokens,cacheWrite:S.cacheWriteTokens,total:S.tokens},costEur:S.cost,balance:S.balance,plan:S.plan||null,account:S.account||null,permissions:{mode:t.enabled?e.defaultMode:"allow",confirm:t.enabled,source:t.source,rules:e},models:q(),commands:visibleCommands(),transcript:k.slice(),sessions:[],memory:{},lastRecap:g.lastRecap,backend:g.modelClass,url:o.apiBase}}function Z(e){return Array.isArray(e)?e.map((e=>e&&(e.s||"")+(null==e.t?"":e.t)||"")).join(""):String(null==e?"":e)}function ee(e){if(!e||"object"!=typeof e)return;const t=h();switch(e.role){case"panel":{const t=Array.isArray(e.lines)?e.lines:[];for(const e of t)Y(Z(e));return}case"note":case"tip":return void Y(render.renderNotice(b(),"info",e.text));case"done":return void Y(render.renderNotice(b(),"ok",e.text));case"error":return void Y(render.renderNotice(b(),"error",e.text));case"user":return void Y(render.renderTurn(b(),{role:"user",text:e.text,label:e.label},t));case"assistant":return void Y(render.renderTurn(b(),{role:"assistant",text:e.text},t));case"tool":return void 0===e.diff&&(e.diff=editPreview(e.name||e.label,e.args,{cwd:process.cwd()}),e.diffOpen=defaultOpen(e.diff)),void Y(render.renderTurn(b(),{role:"tool",label:e.label||e.name,args:e.args,ok:e.ok,diff:e.diff,diffOpen:!!e.diffOpen},t));default:return void Y(render.renderNotice(b(),"info",null==e.text?"":String(e.text)))}}function te(e){return{t:e,s:"",w:w(e)}}async function ne(){return!e.readline&&process.stdin.isTTY&&process.stdout.isTTY&&!1!==e.chatflow?screens.showThemePicker(g):(g.light=!g.light,g.themeIndex=g.light?2:1,Y(render.renderNotice(b(),"ok","theme: "+(g.light?"light":"dark"))),g.themeIndex)}function re(){const e={ctx:g,transcript:k,push:e=>ee(e),note:e=>ee({role:"note",text:e}),panel:e=>ee({role:"panel",lines:e}),render:()=>{},openOverlay:e=>function(e){if(!e||"object"!=typeof e)return;const t=h(),n=Math.max(5,process.stdout&&process.stdout.rows||24);let r=null;if("panel"===e.type?r=e.lines:"palette"===e.type?r=overlays.renderPalette(visibleCommands(),{query:e.query||"",sel:e.sel||0},t,n):"model"===e.type?r=overlays.renderModelPicker(e.items||[],e.sel||0,t,n,null!=e.current?e.current:g.model,e.cls||g.modelClass,p):"effort"===e.type?r=overlays.renderEffortPicker(e.sel||0,t,g.effort):"class"===e.type?r=overlays.renderClassPicker(e.items||[],e.sel||0,t,e.current||g.modelClass,p):"provider"===e.type?r=overlays.renderProviderPicker(e.items||[],e.sel||0,t,e.current,e.hint):"resume"===e.type?r=overlays.renderResumeList(e.items||[],e.sel||0,t,n):"confirm"===e.type&&(r=render.renderApproval(b(),e.info||{},t).map((e=>[te(e)]))),r)for(const e of r)Y(Z(e))}(e),closeOverlay:()=>{},setAutoRounds:e=>{m=Boolean(e)},askInput:()=>Promise.resolve(null),withWorking:e=>async function(e){const r=new AbortController,o=t.interactive&&n.isTTY?new LiveRegion(n):null;let s=null;if(o){let e=0;const t=Date.now(),n=()=>o.update([render.renderWorking(b(),{tick:e++,verb:VERBS[0],elapsedMs:Date.now()-t})]);n(),s=setInterval(n,90),s.unref&&s.unref()}try{return await e(r.signal)}finally{s&&clearInterval(s),o&&o.clear()}}(e),runPrompt:e=>z(e),ask:e=>V(e),runTool:(e,t)=>X(e,t),loadModels:()=>D(g.modelClass),settings:()=>f.settings||null,byokNamespace:e=>byokNamespace(e),listModelsFor:e=>D(e),refreshByokModels:()=>K({force:!0}),switchClass:e=>function(e){const t=String(null==e?"":e).trim().toLowerCase(),n=H();if(!n.includes(t))return"pro"===t?{ok:!1,error:"the pro class (your Claude Code subscription) is off by default — enable it once with `/class pro on`"}:{ok:!1,error:`unknown class "${e}" — classes: ${n.join(", ")}`};const r=g.modelClass;g.modelClass=t;let o=null;return r!==t&&g.model&&(function(e,t){const n=String(null==t?"":t);return"byok"===e?n.includes(":"):"pro"===e?B().has(n.toLowerCase()):!n.includes(":")}(t,g.model)||(o=g.model,g.model=null)),updateConfig({modelClass:t,model:g.model,currentModelId:g.model}),{ok:!0,class:t,prev:r,cleared:o}}(e),classLabel:e=>p(e),classes:()=>"function"==typeof f.listClasses?f.listClasses():[],refreshSpend:()=>N(),state:()=>Q(),setInput:()=>{},exit:()=>{v=!0},client:o,TOOLS:s,saveConfig:e=>updateConfig(e),showThemePicker:()=>ne(),keyStatus:()=>credentials.keyStatus(),setApiKey:(e,t)=>P(e,t),forgetApiKey:()=>x(),registerAccount:()=>async function(){return o.apiKey?{alreadyKeyed:!0}:c()}(),readSecret:e=>readSecret(e,{stdin:process.stdin,stdout:n}),cloudsync:cloudsync,cloudSyncEnabled:()=>A(),cloudSyncState:()=>L(),setCloudSync:e=>O(e),adoptLegacyKey:()=>_()};return Object.defineProperty(e,"sessionId",{enumerable:!0,get:()=>g.sessionId,set:e=>{g.sessionId=e}}),e.clearConversationMemory=()=>{f&&"function"==typeof f.clearSessionApprovals&&f.clearSessionApprovals(g.sessionId)},e}async function oe(e,t=null){const r=parseLine(e);if("empty"===r.kind)return!0;if("prompt"===r.kind)return await z(r.text),!0;if("unknown"===r.kind){const e=J(r.name);return Y(render.renderNotice(b(),"error",`unknown command: /${r.name}${e?` — did you mean /${e}?`:" — try /help"}`)),!0}if("unavailable"===r.kind){const e=r.command;if(Y(render.renderNotice(b(),"warn",`/${e.name} is not available in aegiscode — ${e.unavailable}`)),e.alt)Y(render.renderNotice(b(),"info",`try ${e.alt} instead`));else{const t=J(e.name);t&&Y(render.renderNotice(b(),"info",`try /${t} instead`))}return!0}const s=r.command,i=r.arg;if(s.generic){let t;try{t=s.build(i)}catch(e){return Y(render.renderNotice(b(),"error",e.message)),!0}const{tool:n,args:r}=t;if(!n)return Y(render.renderNotice(b(),"error","/tool needs a tool name — see /help")),!0;try{await X(n,r)}catch(e){Y(render.renderNotice(b(),"error",e.message))}return!0}if("function"==typeof s.handler){const n=function(e,t){const n=String(null==t?"":t),r=Array.isArray(e.args)?e.args:[],o=function(e){const t=[];let n="",r=null,o=!1;for(const s of String(e||""))r?s===r?r=null:n+=s:'"'!==s&&"'"!==s?/\s/.test(s)?(n||o)&&(t.push(n),n="",o=!1):(n+=s,o=!0):(r=s,o=!0);return(n||o)&&t.push(n),t}(n),s={_rest:n.trim()};return r.forEach(((e,t)=>{void 0!==o[t]&&(s[e]=o[t])})),s}(s,i),r=t||re();try{return!1!==await s.handler(r,n)}catch(e){return Y(render.renderNotice(b(),"error",e&&e.message?e.message:String(e))),!0}}try{let e=s.build(i);if(s.secret){const t=await async function(e,t){if("function"!=typeof e.secretDescribe)return null;try{const n=await e.secretDescribe(t,o);return n&&"object"==typeof n?n:null}catch{return null}}(s,e);if(t&&t.note&&Y(render.renderNotice(b(),"info",t.note)),t&&null===t.prompt)return!0;t&&t.provider&&(e={...e,provider:t.provider});const r=await function(e){const t=themeOf(b());return readSecret(t.gray+e+RESET,{stdin:process.stdin,stdout:n})}(t&&t.prompt||`provider key for ${e.provider}: `);if(!r)return Y(render.renderNotice(b(),"warn","empty key — nothing sent")),!0;e={...e,api_key:r}}if("aegis_ask"===s.tool)return await z(e.prompt);await X(s.tool,e),"aegis_memory_list"!==s.tool&&"aegis_memory_search"!==s.tool||function(){let e;try{e=cloudsync.status()}catch{return}const t=e.quota;if(!t)return;const n=fmtTokens(t.used||0),r=fmtTokens(t.limit||0);e.overQuota?Y(render.renderNotice(b(),"warn",`cloud memory: ${n} of ${r} synced tokens — at the plan's ceiling. Everything stored stays readable; new writes are paused until there is room. /cloud memory for the full state.`)):Y(render.renderNotice(b(),"info",`cloud memory: ${n} of ${r} synced tokens — /cloud memory for the full state`))}()}catch(e){Y(render.renderNotice(b(),"error",e.message))}return!0}async function se(){if(f&&"function"==typeof f.unloadLocalModels)try{await f.unloadLocalModels()}catch{}}function ie(e){S.turns++,S.calls+=Number(e&&e.calls||1)||1;const t=e&&e.usage,n=usageTokens(t);if(null!=n){S.tokens+=n;const e=usageBuckets(t);S.inputTokens+=e.input,S.outputTokens+=e.output,S.cacheReadTokens+=e.cacheRead,S.cacheWriteTokens+=e.cacheWrite}return n}function ae(e,t,n="done",r=null){try{const o=t&&t.usage,s="number"==typeof r&&Number.isFinite(r)?r:null,i=String(t&&t.model||g.model||"").trim();appendHistory({sessionId:g.sessionId,prompt:e,reply:t&&t.text||"",status:n,model:i||void 0,provider:i&&providerForModel({id:i,cls:g.modelClass})||void 0,usage:o?{...usageBuckets(o),...null!=s?{costUsd:s}:{}}:null!=s?{input:0,output:0,cacheRead:0,cacheWrite:0,costUsd:s}:null}),snapshotCheckpoint(g.sessionId,k)}catch{}A()&&o.apiKey&&Promise.resolve().then((()=>cloudsync.push(o))).then((e=>{if(e&&e.failed&&e.failed.length){const t=e.failed[0];if(le.has(t.kind))return;if(le.add(t.kind),"quota"===t.kind)return void Y(render.renderNotice(b(),"warn","cloud memory: the plan's synced-token ceiling is reached — earlier sessions stay readable, only NEW writes pause. /cloud memory shows the quota; /cloud memory off stops trying."));const n=t.hint?` — ${t.hint}`:"";Y(render.renderNotice(b(),"error",`cloud sync: ${t.message}${n}`))}})).catch((()=>{}))}let le=new Set;function ce(){const e=[S.outputTokens>0?`${fmtTokens(S.outputTokens)} tokens`:`${fmtTokens(S.tokens)} tokens`,`${S.calls} call${1===S.calls?"":"s"}`];return feeBillable()&&(e.push(fmtEur(S.cost)),null!=S.balance&&e.push(`balance ${fmtEur(S.balance)}`)),e.join(" · ")}async function de(e){if(!e||!e.id)return;const t=readSessionTranscript(e.id);if(t.length){k.length=0;for(const e of t)k.push(e);g.sessionId=e.id,Y(render.renderNotice(b(),"ok",`resumed ${e.id} — ${t.length} turn(s)`))}else Y(render.renderNotice(b(),"warn",`no stored turns for ${e.id}`))}function ue(){return{ctx:g,version:VERSION,transcript:k,session:S,client:o,TOOLS:s,ask:(e,t)=>V(e,t),makeCommandContext:()=>re(),accountConfigured:()=>!!(credentials.keyStatus()||{}).configured,hasProviderKey:e=>{const t=f.settings;if(!t||!e)return!1;const n=byokNamespace(e);return"function"==typeof t.rawKey?!!String(t.rawKey(n)||"").trim():"function"==typeof t.get&&!!(t.get(n)||{}).configured},loadModels:e=>F(e),buildState:()=>Q(),dispatchLine:(e,t)=>oe(e,t),refreshSpend:()=>N(),updateConfig:e=>updateConfig(e),showThemePicker:()=>ne(),persistTurn:(e,t,n,r)=>ae(e,t,n,r),nameConversation:(e,t)=>async function(e,{signal:t=null}={}){const n=await naming.nameConversation(e,{signal:t,callModel:(e,n)=>V(e,{system:n&&n.system||naming.TITLE_SYSTEM,maxTokens:64,signal:n&&n.signal||t}).then((e=>e&&e.text||null))}),r=String(n||"").trim();return r&&setSessionTitle(g.sessionId,r),r}(e,t),visibleCommands:()=>visibleCommands(),tokensFor:e=>usageTokens(e),recordTurn:e=>ie(e),tokenSummary:()=>ce(),resumeSession:e=>de(e),requestExit:()=>{v=!0},wantsExit:()=>v,keyNotice:()=>o.apiKey?"":l,isYolo:()=>{if(!m)return!1;try{return!1===confirmPosture().enabled}catch{return!1}},setAutoRounds:e=>{m=Boolean(e)}}}async function me(){Y(W()),await N(),n.write("\n");const t=e.readline||readline.createInterface({input:process.stdin,output:n,terminal:!0}),r=themeOf(b()).gold+GLYPH.cursor+" "+RESET;return t.setPrompt(r),t.prompt(),new Promise((e=>{t.on("line",(async e=>{t.pause();let n=!0;try{n=await oe(e)}catch(e){Y(render.renderNotice(b(),"error",e.message))}if(!n||v)return E=!0,void t.close();t.resume(),t.prompt()})),t.on("close",(()=>{E||n.write("\n"),e(0)}))}))}function fe(){if(e.readline)return;if(!configExists())return;let n;try{n=loadConfig()}catch{return}if(H().includes(n.modelClass)&&(g.modelClass=n.modelClass),t.class){const e=String(t.class).trim().toLowerCase();if(!H().includes(e))throw new Error(`--class ${t.class}: not available on this host (offered: ${H().join(", ")})`);g.modelClass=e}if(!t.model&&n.model&&(g.model=n.model),g.effort=effortRung(t.effort||n.effort),"boolean"==typeof n.vim&&(g.vim=n.vim),n.lastRecap&&(g.lastRecap=n.lastRecap),!t.light&&"number"==typeof n.themeIndex&&THEME_TABLE[n.themeIndex]){g.themeIndex=n.themeIndex,g.light=themeIsLight(n.themeIndex);const e=reconcileThemeIndex(g.themeIndex);if(e.changed){g.themeIndex=e.index,g.light=themeIsLight(e.index),g.themeNotice=e.reason;try{updateConfig({themeIndex:e.index,light:themeIsLight(e.index)})}catch{g.themeNotice+=" (could not save it)"}}}}return{opts:t,session:S,client:o,TOOLS:s,toolList:i,ctx:g,transcript:k,ask:V,runPrompt:z,handleLine:oe,runOnce:async function(e,t={}){try{return await async function(e,{json:t=!1}={}){if(fe(),_(),!o.apiKey&&!a){a=!0;const e=await autoProvisionApiKey(o,credentials,{app:"cli"});e.key&&r.write("aegiscode: auto-provisioned a free account"+(e.ok?` (saved to ${credentials.credentialsPath()})`:" (could not save it — reconfigure with /key)")+trialNote(e)+`. Fund it at ${o.promptUrl("topup","device_autoprovision")} or run /byok to use your own key.\n`)}if(!o.apiKey)return r.write(`aegiscode: no AEGIS account key. ${credentials.HOW_TO_SET}, or set $${credentials.KEY_ENV}.\n`),2;await N();const s=[],i=[],l=t?{tool:e=>{if("done"===(e&&e.phase)){const t=e.id&&i.find((t=>t.id===e.id&&!0!==t.settled))||(e.id?null:i[i.length-1]);t?(t.settled=!0,t.ok=!1!==e.ok):(e&&e.name&&s.push(e.name),i.push({name:e&&e.name||null,id:e&&e.id||null,args:briefArgs(e&&e.args),settled:!0,ok:!1!==e.ok}))}else e&&e.name&&s.push(e.name),i.push({name:e&&e.name||null,id:e&&e.id||null,args:briefArgs(e&&e.args),settled:!1,ok:null});const t=e&&void 0!==e.preview?e.preview:null,n=render.renderTurn(b(),{role:"tool",label:e.name,args:e.args,ok:e.ok,diff:t,diffOpen:!1},h());for(const e of Array.isArray(n)?n:[n])r.write(e+"\n")}}:null,c=await V(e,l?{presenter:l}:{});await N();const d=usageTokens(c.usage),u=providerRefusal(c.text,c.usage);if(t)n.write(JSON.stringify({text:c.text,model:c.model,class:g.modelClass,rounds:c.usage&&Number(c.usage.calls)||null,usage:c.usage,reasoning_chars:"number"==typeof c.reasoningChars?c.reasoningChars:null,tokens:d,ms:c.ms,interrupted:c.interrupted,...s.length?{tools:s}:{},...i.length?{tool_log:i}:{},...u?{error:u}:{},balance_eur:S.balance},null,2)+"\n");else if(n.write(c.text+"\n"),u&&r.write(`aegiscode: the provider refused this turn — ${u}\n`),null!=d){const e=themeOf(b());n.write(e.dim+GLYPH.hook+" "+e.blue+(c.model||"aegis")+RESET+e.dim+" "+GLYPH.bullet+" "+RESET+e.white+`${fmtTokens(d)} tokens`+RESET+"\n")}return c.interrupted?130:u?1:0}(e,t)}finally{await se()}},runInteractive:async function(){try{return await async function(){if(!e.readline&&!1!==e.chatflow&&process.stdin.isTTY&&process.stdout.isTTY){await probeTerminalBackground({onLeftover:e=>events.feedKeys(e,{keystrokes:!0})}),fe(),function(){if(!g.themeNotice)return;const e=g.themeNotice;g.themeNotice="",Y(render.renderNotice(b(),"warn",`theme: ${e} (saved)`))}(),_(),o.apiKey||await d();const t=await screens.runOnboarding(g,{continue:!!e.continue,seen:e.seen||configExists,save:e=>updateConfig(e),needsKey:()=>!o.apiKey,submitKey:e=>P(e)});if(!t.ok)return 0;if(t.key&&t.key.set&&Y(render.renderNotice(b(),"info",`key saved to ${credentials.credentialsPath()} — no export needed from now on`)),t.key&&t.key.skipped&&!o.apiKey&&Y(render.renderNotice(b(),"warn","no key saved — /key <api_key> or `aegiscode login` whenever you are ready")),t.firstRun&&function(){if(!L().enabled)return void Y(render.renderNotice(b(),"info","cross-session memory: off (you turned it off) — /cloud memory on stores sessions so an interrupted turn can be picked up later"));const e=cloudsync.status().quota,t=e&&e.limit?` (used ${fmtTokens(e.used||0)} of ${fmtTokens(e.limit)} tokens)`:"";Y(render.renderNotice(b(),"info",`cross-session memory: on${t} — sessions are stored to your account so a turn that is interrupted can be resumed. /cloud memory shows the quota; /cloud memory off stops it. Past the ceiling, saved memory stays readable and only new writes pause.`))}(),await U(),e.continue){const e=readOwnSessions(1)[0];e&&(g.continueSession=e.id,await de({id:e.id}))}return await N(),await chatflow.runSession(ue()),0}return fe(),_(),me()}()}finally{await se()}},runLinearRepl:me,refreshSpend:N,bannerLines:W,makeHost:ue,loadModels:F,validatePinnedModel:U,recordTurn:ie,persistTurn:ae,restorePrefs:fe,setApiKey:P,forgetApiKey:x,adoptLegacyKeyOnce:_,cloudSyncEnabled:A,cloudSyncState:L,setCloudSync:O,cloudsync:cloudsync,keyStatus:()=>credentials.keyStatus(),accountConfigured:()=>!!(credentials.keyStatus()||{}).configured,hasProviderKey:e=>{const t=f.settings;if(!t||!e)return!1;const n=byokNamespace(e);return"function"==typeof t.rawKey?!!String(t.rawKey(n)||"").trim():"function"==typeof t.get&&!!(t.get(n)||{}).configured},sessionId:()=>g.sessionId,tokenSummary:ce,resumeSession:de,makeCommandContext:re,buildState:Q,get aborted(){return!1}}}module.exports={createApp:createApp,VERSION:VERSION,normalizeDecision:normalizeDecision};
|
|
@@ -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"))),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 T=new Map;let v=null,L=null,C=[],b=!1,k=0,P="",$=null,x=null,O=0,Y=null,I="",K="",R=!1,M=!0;try{M=titleEnabled(process.env,e.loadConfig?e.loadConfig():e.config||{})}catch{M=!0}let A=!1,_=0;const N=e=>{if(!M)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,T.clear();for(let e=0;e<p.lines.length;e++)T.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&&j(a,p,i),C=a,paint(v?applySelection(a,selectionRange(v.anchor,v.head),i):a),_=Date.now(),s?hideCursor():$||!l?(moveTo(m,u),showCursor()):hideCursor()},H=()=>{if(A)return;A=!0;const e=Math.max(0,33-(Date.now()-_));setTimeout((()=>{A=!1,B()}),e)},j=(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):"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()},q=(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=>q({role:"note",text:e},{follow:!1});let z=0,V=0;const W=()=>z,Q=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),q({role:"user",text:t});const n=q({role:"assistant",text:"",streaming:!0});let o=!1;const i={text:e=>{n.text+=e,z+=w(e),H()},reasoning:e=>{o=!0,z+=w(e)},thinkingTokens:e=>{o=!0,V+=e,H()},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)}H()},approval:e=>(e=>new Promise((t=>{s={type:"confirm",name:e.tool||e.name||"tool",args:e.args||{},sel:0,info:e},B(),(async()=>{const e=e=>{s=null,B(),t(e)};for(;;){const t=await nextKey();if(t.name===KEY.UP||t.name===KEY.DOWN||t.name===KEY.TAB){const e=t.name===KEY.UP?-1:1;s.sel=(s.sel+e+APPROVAL_CHOICES.length)%APPROVAL_CHOICES.length,B()}else{if(t.name===KEY.ENTER)return void e(APPROVAL_DECISIONS[s.sel]||"deny");if(t.name===KEY.ESC||t.name===KEY.CTRL_C)return void e("deny");if("char"===t.name){const n=String(t.ch).trim(),r=Number(n)-1;if(Number.isInteger(r)&&r>=0&&r<APPROVAL_DECISIONS.length)return void e(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()),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(),(async()=>{const e=e=>{s=null,B(),n(e)};for(;;){const t=await nextKey();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}),q({role:"done",text:`${h>0?DONE_VERBS[1]:DONE_VERBS[0]} for ${r}s`},{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&&q({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;q({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&&q({role:"summary",counts:w},{follow:0===E}),B()}},X=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 L=t,!1;if("drag"===e.name)return v?v.head=t:v={anchor:L||t,head:t},L=null,!0;const n=L;L=null;const r=v?selectionRange(v.anchor,v.head):null,o=!(!r||r.startRow===r.endRow&&r.startCol===r.endCol);if(v=null,!o)return(e=>{const t=T.get(e);return!(!t||!t.diff||(t.diffOpen=!t.diffOpen,0))})((n||t).row);const s=selectionText(C,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)||(H(),!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,H(),!0)},J=()=>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,Z=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)}n.cls&&"aegis"!==n.cls&&t.modelClass!==n.cls&&await re(`/class ${n.cls}`),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)}},ee=async e=>{e&&e.class&&await re(`/class ${e.class}`)},te=n=>{const r=overlays.EFFORT_VALUES[n||0];s=null,t.effort=r||"high",e.updateConfig({effort:t.effort}),U(`effort: ${t.effort}`),B()},ne=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 re(t?`/${e.name} ${t}`:`/${e.name}`))}if("model"===n){const e=(s.items||[])[s.sel||0];return s=null,B(),await Z(e),void B()}if("effort"===n)return void te(s.sel||0);if("class"===n){const e=(s.items||[])[s.sel||0];return s=null,B(),await ee(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 re(`/${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,J()-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 Z(e),void B()}if("class"===n){const e=(s.items||[])[s.sel||0];return s=null,B(),await ee(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 re(`/${t} ${e.id}`))}return"effort"===n?void te(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 re(`/${e.name}`))}if("model"===n){const e=(s.items||[])[s.sel||0];return s=null,B(),await Z(e),void B()}if("class"===n){const e=(s.items||[])[s.sel||0];return s=null,B(),await ee(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 re(`/${t} ${e.id}`))}return"effort"===n?void te(s.sel||0):void 0}if(t.name===KEY.UP||t.name===KEY.DOWN){const e=(s.items||[]).length||J(),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("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||"resume"===n||"class"===n||"provider"===n){const e=parseInt(t.ch,10),n=J();return void(Number.isFinite(e)&&e>=1&&e<=n&&(s.sel=e-1,B()))}}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(X(o))return}if(o.name===KEY.ENTER){const e=n.submit();return Y=null,b=!1,e?void await re(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 ie():void(o.name!==KEY.CTRL_D||n.buf||await ie());n.buf&&(n.buf="",n.cursor=0,B())}else await re("/model");else X(o);else X(o);else await re("/permissions");else await re("/resume")}else await re(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`)})()}},re=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 X(e)||n.push(e)}if(requeueKeys(n),o)throw o;return r})()})(e(),(()=>u))}catch(e){return q({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)=>{q(e,t),B()},note:e=>{q({role:"note",text:e}),B()},panel:e=>{q({role:"panel",lines:e||[]}),B()},render:()=>B(),openOverlay:e=>{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 Q(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 Q(r),!0}))||e.wantsExit())&&await ie()};let oe=!1,se=null;const ie=()=>{oe||(oe=!0,se&&se(0))},ae=()=>{hideCursor(),paint([]);try{process.stdout.write("[0m")}catch{}try{M&&writeTitle("",process.stdout)}catch{}try{process.stdin.setRawMode(!1)}catch{}disableBracketedPaste(),disableMouseTracking(),leaveAltScreen()};let le=!1;const ue=()=>{if(!le){le=!0;try{ae()}catch{}}};process.once("exit",ue);const ce=e.stdin||process.stdin;markSessionStart(),attachKeyStream(ce),enableBracketedPaste(),enableMouseTracking(),enterAltScreen(),clearScreen(),hideCursor(),N(!1);const pe=()=>B();"win32"!==process.platform?process.on("SIGWINCH",pe):process.stdout.on("resize",pe);const de=()=>{l&&u?u.abort():ie()};process.on("SIGINT",de);const fe=e=>{ae();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",fe),process.on("unhandledRejection",fe),B();try{return await new Promise((e=>{se=e,(async()=>{for(;!oe;){const e=await nextKey();if(oe)break;if(e===STREAM_END||!e){ie();break}try{await ne(e)}catch(e){q({role:"note",text:`Error: ${e&&e.message||String(e)}`},{follow:!1}),B()}}})()}))}finally{oe=!0,process.off("SIGINT",de),"win32"!==process.platform?process.off("SIGWINCH",pe):process.stdout.off("resize",pe),process.off("uncaughtException",fe),process.off("unhandledRejection",fe),process.off("exit",ue),ue(),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"))),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 T=new Map;let v=null,C=null,L=[],b=!1,k=0,P="",$=null,x=null,O=0,Y=null,I="",K="",R=!1,M=!0;try{M=titleEnabled(process.env,e.loadConfig?e.loadConfig():e.config||{})}catch{M=!0}let A=!1,_=0;const N=e=>{if(!M)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,T.clear();for(let e=0;e<p.lines.length;e++)T.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&&j(a,p,i),L=a,paint(v?applySelection(a,selectionRange(v.anchor,v.head),i):a),_=Date.now(),s?hideCursor():$||!l?(moveTo(m,u),showCursor()):hideCursor()},H=()=>{if(A)return;A=!0;const e=Math.max(0,33-(Date.now()-_));setTimeout((()=>{A=!1,B()}),e)},j=(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):"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()},q=(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=>q({role:"note",text:e},{follow:!1});let z=0,V=0;const W=()=>z,Q=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),q({role:"user",text:t});const n=q({role:"assistant",text:"",streaming:!0});let o=!1;const i={text:e=>{n.text+=e,z+=w(e),H()},reasoning:e=>{o=!0,z+=w(e)},thinkingTokens:e=>{o=!0,V+=e,H()},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)}H()},approval:e=>(e=>new Promise((t=>{s={type:"confirm",name:e.tool||e.name||"tool",args:e.args||{},sel:0,info:e},B(),(async()=>{const e=e=>{s=null,B(),t(e)};for(;;){const t=await nextKey();if(t.name===KEY.UP||t.name===KEY.DOWN||t.name===KEY.TAB){const e=t.name===KEY.UP?-1:1;s.sel=(s.sel+e+APPROVAL_CHOICES.length)%APPROVAL_CHOICES.length,B()}else{if(t.name===KEY.ENTER)return void e(APPROVAL_DECISIONS[s.sel]||"deny");if(t.name===KEY.ESC||t.name===KEY.CTRL_C)return void e("deny");if("char"===t.name){const n=String(t.ch).trim(),r=Number(n)-1;if(Number.isInteger(r)&&r>=0&&r<APPROVAL_DECISIONS.length)return void e(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()),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(),(async()=>{const e=e=>{s=null,B(),n(e)};for(;;){const t=await nextKey();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}),q({role:"done",text:`${h>0?DONE_VERBS[1]:DONE_VERBS[0]} for ${r}s`},{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&&q({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;q({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&&q({role:"summary",counts:w},{follow:0===E}),B()}},X=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 v?v.head=t:v={anchor:C||t,head:t},C=null,!0;const n=C;C=null;const r=v?selectionRange(v.anchor,v.head):null,o=!(!r||r.startRow===r.endRow&&r.startCol===r.endCol);if(v=null,!o)return(e=>{const t=T.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)||(H(),!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,H(),!0)},J=()=>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,Z=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 re(`/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)}},ee=async e=>{e&&e.class&&await re(`/class ${e.class}`)},te=n=>{const r=overlays.EFFORT_VALUES[n||0];s=null,t.effort=r||"high",e.updateConfig({effort:t.effort}),U(`effort: ${t.effort}`),B()},ne=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 re(t?`/${e.name} ${t}`:`/${e.name}`))}if("model"===n){const e=(s.items||[])[s.sel||0];return s=null,B(),await Z(e),void B()}if("effort"===n)return void te(s.sel||0);if("class"===n){const e=(s.items||[])[s.sel||0];return s=null,B(),await ee(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 re(`/${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,J()-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 Z(e),void B()}if("class"===n){const e=(s.items||[])[s.sel||0];return s=null,B(),await ee(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 re(`/${t} ${e.id}`))}return"effort"===n?void te(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 re(`/${e.name}`))}if("model"===n){const e=(s.items||[])[s.sel||0];return s=null,B(),await Z(e),void B()}if("class"===n){const e=(s.items||[])[s.sel||0];return s=null,B(),await ee(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 re(`/${t} ${e.id}`))}return"effort"===n?void te(s.sel||0):void 0}if(t.name===KEY.UP||t.name===KEY.DOWN){const e=(s.items||[]).length||J(),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("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||"resume"===n||"class"===n||"provider"===n){const e=parseInt(t.ch,10),n=J();return void(Number.isFinite(e)&&e>=1&&e<=n&&(s.sel=e-1,B()))}}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(X(o))return}if(o.name===KEY.ENTER){const e=n.submit();return Y=null,b=!1,e?void await re(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 ie():void(o.name!==KEY.CTRL_D||n.buf||await ie());n.buf&&(n.buf="",n.cursor=0,B())}else await re("/model");else X(o);else X(o);else await re("/permissions");else await re("/resume")}else await re(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`)})()}},re=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 X(e)||n.push(e)}if(requeueKeys(n),o)throw o;return r})()})(e(),(()=>u))}catch(e){return q({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)=>{q(e,t),B()},note:e=>{q({role:"note",text:e}),B()},panel:e=>{q({role:"panel",lines:e||[]}),B()},render:()=>B(),openOverlay:e=>{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 Q(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 Q(r),!0}))||e.wantsExit())&&await ie()};let oe=!1,se=null;const ie=()=>{oe||(oe=!0,se&&se(0))},ae=()=>{hideCursor(),paint([]);try{process.stdout.write("[0m")}catch{}try{M&&writeTitle("",process.stdout)}catch{}try{process.stdin.setRawMode(!1)}catch{}disableBracketedPaste(),disableMouseTracking(),leaveAltScreen()};let le=!1;const ue=()=>{if(!le){le=!0;try{ae()}catch{}}};process.once("exit",ue);const ce=e.stdin||process.stdin;markSessionStart(),attachKeyStream(ce),enableBracketedPaste(),enableMouseTracking(),enterAltScreen(),clearScreen(),hideCursor(),N(!1);const pe=()=>B();"win32"!==process.platform?process.on("SIGWINCH",pe):process.stdout.on("resize",pe);const de=()=>{l&&u?u.abort():ie()};process.on("SIGINT",de);const fe=e=>{ae();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",fe),process.on("unhandledRejection",fe),B();try{return await new Promise((e=>{se=e,(async()=>{for(;!oe;){const e=await nextKey();if(oe)break;if(e===STREAM_END||!e){ie();break}try{await ne(e)}catch(e){q({role:"note",text:`Error: ${e&&e.message||String(e)}`},{follow:!1}),B()}}})()}))}finally{oe=!0,process.off("SIGINT",de),"win32"!==process.platform?process.off("SIGWINCH",pe):process.stdout.off("resize",pe),process.off("uncaughtException",fe),process.off("unhandledRejection",fe),process.off("exit",ue),ue(),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};
|