aegisone 1.0.65 → 1.0.67
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 +1 -1
- package/bin/aegis.js +1 -1
- package/package.json +1 -1
- package/vendor/cli/bin/aegiscode.js +47 -5
- package/vendor/cli/package.json +1 -1
- package/vendor/cli/src/app.js +1 -1
- package/vendor/cli/src/autonomous.js +574 -10
- package/vendor/cli/src/commands.js +1 -1
- package/vendor/cli/src/dream-cmd.js +3 -0
- package/vendor/cli/src/limits.js +1 -1
- package/vendor/cli/src/provenance.lock.json +3 -3
- package/vendor/cli/src/screen.js +1 -1
- package/vendor/cli/vendor/desktop/lib/local/autonomous.js +1 -1
- package/vendor/cli/vendor/desktop/lib/local/integrity.js +1 -1
- package/vendor/cli/vendor/desktop/lib/local/queue.js +1 -1
- package/vendor/cli/vendor/desktop/main.js +82 -1
- package/vendor/cli/vendor/mcp/tools.js +1 -1
- package/vendor/desktop/lib/local/autonomous.js +1 -1
- package/vendor/desktop/lib/local/integrity.js +1 -1
- package/vendor/desktop/lib/local/queue.js +1 -1
- package/vendor/desktop/main.js +82 -1
- package/vendor/desktop/package.json +1 -1
- package/vendor/desktop/preload.js +1 -1
- package/vendor/desktop/renderer/app.js +3 -3
- package/vendor/desktop/renderer/pty-panel.js +1 -1
- package/vendor/desktop/renderer/pty-window.html +72 -0
- package/vendor/desktop/renderer/pty-window.js +3 -0
- package/vendor/desktop/renderer/stream-policy.js +1 -1
- package/vendor/desktop/renderer/style.css +55 -3
- package/vendor/desktop/vendor/faces/cli/bin/aegiscode.js +2 -2
- 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/autonomous.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/commands.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/dream-cmd.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/limits.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/provenance.lock.json +3 -3
- package/vendor/desktop/vendor/faces/cli/src/screen.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/autonomous.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/integrity.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/queue.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/main.js +3 -3
- package/vendor/desktop/vendor/faces/cli/vendor/mcp/tools.js +1 -1
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
2
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
-
"use strict";const path=require("node:path"),{queue:queue,autonomous:autonomous}=require("./deps.js"),{createEngine:createEngine,proEnabled:proEnabled}=require("./engine.js"),{loadConfig:loadConfig}=require("./config.js"),{fmtElapsed:fmtElapsed}=require("./format.js"),limits=require("./limits.js"),SUBCOMMANDS=new Set(["add","list","run","proceed","reconcile","clear","retry","help"]),EXECUTES=new Set(["run","proceed","retry","reconcile"]);function parseFlags(e){const t={terms:[],json:!1,flags:{}},n=new Set(["cwd","model","effort","workers","max","max-rounds","source","class"]);for(let o=0;o<e.length;o++){const r=e[o];if("--json"!==r){if(r.startsWith("--")){const[s,i]=r.slice(2).split("="),a=s.trim();if(new Set(["commit","all","auto","stop-on-error","single-pass","help"]).has(a)){t.flags[a]=!0;continue}if(!n.has(a))throw new Error(`unknown option: --${a}`);const u=void 0!==i?i:e[++o];if(void 0===u)throw new Error(`--${a} needs a value`);t.flags[a]=u;continue}t.terms.push(r)}else t.json=!0}return t}function intFlag(e,t){const n=e[t];if(void 0===n||""===n)return null;const o=Number.parseInt(n,10);return Number.isFinite(o)&&o>0?o:null}function taskLine(e){const t=e.model||"(default)",n=String(e.status||"?").padEnd(7),o=`#${e.id}`.padEnd(4),r=String(e.task||"").replace(/\s+/g," ").trim();return`${o} ${n} ${t} ${r.length>72?`${r.slice(0,71)}…`:r}`}function describeCounts(e){const t={pending:0,running:0,done:0,error:0};for(const n of e)void 0!==t[n.status]&&(t[n.status]+=1);return t}function printRunReport(e,t){for(const n of e){const e=Boolean(n.ok&&n.stoppedOnRounds),o=e?"⏸":n.ok?"✓":"✗",r=e?"paused — will resume":n.ok?"done":"failed";if(t.stdout.write(`aegiscode: ${o} #${n.id} ${r} (${fmtElapsed(n.ms)})`),n.commit&&n.commit.ok&&n.commit.staged?t.stdout.write(` — committed ${n.commit.staged} path(s)`):n.commit&&n.commit.skipped&&n.commit.reason&&t.stdout.write(` — no commit (${n.commit.reason})`),t.stdout.write("\n"),!n.ok&&n.error&&t.stderr.write(`aegiscode: #${n.id}: ${n.error}\n`),n.ok&&n.output){const e=String(n.output).trim();t.stdout.write(`${e.length>4e3?`${e.slice(0,4e3)}\n… [output clipped]`:e}\n`)}}}function buildEngine({io:e,quiet:t=!1}){const n=require("./credentials.js"),o=require("./deps.js").createClient(n.clientOptions({channel:"cli"}));if(!o.apiKey)return{error:`no AEGIS account key — ${n.HOW_TO_SET}, or set ${n.KEY_ENV}`};const r=createEngine({client:o,getConfirmMode:()=>!1,getProEnabled:()=>{try{return proEnabled(loadConfig())}catch{return!1}}});let s=null;try{s=require("./entitlement.js").createCliEntitlement({aegis:o})}catch{s=null}return{client:o,engine:r,entitlement:s}}function progressSink(e,{json:t}){return t?()=>{}:t=>{if(t&&"object"==typeof t)if("start"!==t.type){if("tool"===t.type&&t.tool&&"run"===t.tool.phase){const n=t.tool.args||{},o=n.command||n.pattern||autonomous.writtenPath(t.tool)||"",r=String(o).slice(0,100);return void e.stderr.write(` ⚙ ${t.tool.name}${r?` ${r}`:""}\n`)}"healed"!==t.type?"note"===t.type&&t.note?e.stderr.write(` ⓘ ${t.note}\n`):"recovered"===t.type&&e.stdout.write(`aegiscode: re-queued task(s) ${t.ids.join(", ")} from a dead worker\n`):e.stdout.write(`aegiscode: PLAN.md status list healed for phase(s) ${t.phases.join(", ")}\n`)}else e.stdout.write(`aegiscode: #${t.taskId} running on ${t.model} in ${t.cwd}\n`)}}async function runQueueCommand(e,t,n={}){const o=n.stdout||process.stdout,r=n.stderr||process.stderr,s={stdout:o,stderr:r};let i;try{i=parseFlags(t||[])}catch(e){return r.write(`aegiscode autonomous: ${e.message}\n`),2}const a=Boolean(n.json||i.json),u=(e,t)=>{a?o.write(`${JSON.stringify(e,null,2)}\n`):void 0!==t&&o.write(t.endsWith("\n")?t:`${t}\n`)};if("help"===e||!SUBCOMMANDS.has(e))return o.write(usageText()),"help"===e?0:2;if(EXECUTES.has(e)&&limits.armed())return limits.refuse();const d=i.flags.cwd?path.resolve(String(i.flags.cwd)):process.cwd();if("add"===e){const t=i.terms.join(" ").trim();if(!t)return r.write('aegiscode autonomous add: a task needs text — `aegiscode autonomous add "…"`\n'),2;let n;try{n=queue.addTask(process.env,{task:t,cwd:d,class:i.flags.class||null,model:i.flags.model||null,effort:i.flags.effort||null,workers:intFlag(i.flags,"workers"),maxRounds:intFlag(i.flags,"max-rounds"),singlePass:Boolean(i.flags["single-pass"]),commit:Boolean(i.flags.commit),source:i.flags.source||"cli"})}catch(e){return r.write(`aegiscode autonomous add: ${e.message}\n`),2}return u({ok:!0,id:n.id,item:n,queue:queue.queuePath(process.env)},`aegiscode: queued #${n.id} — ${queue.pendingCount(queue.loadQueue(process.env))} pending`),0}if("list"===e){const e=queue.loadQueue(process.env),t=describeCounts(e);if(a)u({ok:!0,file:queue.queuePath(process.env),counts:t,tasks:e,runs:queue.readRuns(process.env,{limit:10})});else{o.write(`queue: ${queue.queuePath(process.env)}\n`),o.write(`tasks: ${e.length} (${t.pending} pending, ${t.running} running, ${t.done} done, ${t.error} error)\n`);for(const t of e)o.write(`${taskLine(t)}\n`);e.length||o.write("(empty)\n")}return 0}if("clear"===e){const e=queue.clearQueue(process.env,{all:Boolean(i.flags.all)});return u({ok:!0,...e},`aegiscode: removed ${e.removed} finished task(s); ${e.kept} kept`),0}if("retry"===e){const e=i.terms[0];if(!e)return r.write("aegiscode autonomous retry: which task? `aegiscode autonomous retry <id>`\n"),2;const t=queue.retryTask(process.env,e);return t?(u({ok:!0,id:t.id,item:t},`aegiscode: #${t.id} is pending again`),0):(r.write(`aegiscode autonomous retry: no task #${e}\n`),1)}const l=buildEngine({io:n});if(l.error)return r.write(`aegiscode autonomous: ${l.error}\n`),2;if(l.entitlement)try{await l.entitlement.refresh()}catch{}const c=autonomous.createQueueWorker({engine:l.engine,env:process.env,log:progressSink(s,{json:a}),canFanOut:()=>{if(!l.entitlement)return!1;try{const e=l.entitlement.current();return Boolean(e&&!0===e.entitled)}catch{return!1}}});if(l.entitlement)try{const e=l.entitlement.current();e&&!1===e.entitled&&!1===e.degraded&&e.refusal&&(r.write(`aegiscode autonomous: ${e.refusal}\n`),r.write(" ↳ write tasks like: Do X autonomously\n"),r.write("balance"===e.wall?" ↳ unlock: top up the Token Bank, or upgrade to Unlimited\n":" ↳ unlock: Unlimited, or any Token Bank balance\n"),e.upgradeUrl&&r.write(` ${e.upgradeUrl}\n`))}catch{}const m=!!i.flags.commit||void 0,g=()=>{const e=queue.loadQueue(process.env).find(e=>"running"===e.status&&e.pid===process.pid);e&&c.cancel(e.id)};process.on("SIGINT",g);try{if("reconcile"===e){const e=await c.reconcile({cwd:d,auto:Boolean(i.flags.auto),commit:m,max:intFlag(i.flags,"max")||0,stopOnError:Boolean(i.flags["stop-on-error"])});return e.ok?(a||printRunReport(e.ran||[],s),u(e,e.exhausted?"aegiscode: every phase in PLAN.md is done — nothing to queue":`aegiscode: phase ${e.phase} queued${e.ran?` — ${e.ran.length} task(s) run`:""}`),0):(r.write(`aegiscode autonomous reconcile: ${e.error||"reconcile failed"}\n`),u(e,void 0),1)}if("proceed"===e||"run"===e){const t="run"===e?1:intFlag(i.flags,"max")||0,n=await c.proceed({commit:m,max:t,stopOnError:Boolean(i.flags["stop-on-error"])});if(n.locked)return r.write(`aegiscode autonomous: another drain holds the queue lock (pid ${n.holder&&n.holder.pid})\n`),u({ok:!1,locked:!0,holder:n.holder},void 0),1;a||printRunReport(n.ran,s);const o=n.ran.filter(e=>!e.ok).length;return u({ok:0===o,ran:n.ran.map(e=>({id:e.id,ok:e.ok,error:e.error||null,ms:e.ms})),failed:o},n.ran.length?`aegiscode: ${n.ran.length} task(s) run${o?`, ${o} failed`:""}`:"aegiscode: nothing pending"),o?1:0}}finally{process.removeListener("SIGINT",g)}return o.write(usageText()),2}function usageText(){return["aegiscode autonomous <command> — the unattended work queue","","Commands:",' add "<task>" queue a task (--cwd, --class, --model, --effort, --commit,'," --single-pass, --workers N, --max-rounds N)"," --class aegis|byok|local|pro (default aegis); --model must"," match the class (pro takes a claude alias, or none at all)"," list show queued tasks and the tail of the runs log"," run drain ONE task, then stop"," proceed drain every pending task (--max N, --stop-on-error, --commit)"," reconcile queue the next unfinished PLAN.md phase (--auto drains it)"," retry <id> put a finished task back in the queue"," clear drop finished tasks (--all empties the queue)","","Options:"," --json emit JSON instead of text (also on add/list/clear/retry)","","A drain runs with tool approval DISABLED (nobody is there to click a card),","one task at a time, and commits only the paths the task itself changed."].join("\n")+"\n"}module.exports={runQueueCommand:runQueueCommand,parseFlags:parseFlags,taskLine:taskLine,usageText:usageText,SUBCOMMANDS:SUBCOMMANDS};
|
|
3
|
+
"use strict";const{spawn:spawn,spawnSync:spawnSync}=require("node:child_process"),os=require("node:os"),fs=require("node:fs"),path=require("node:path"),{queue:queue,autonomous:autonomous}=require("./deps.js"),{createEngine:createEngine,proEnabled:proEnabled}=require("./engine.js"),{loadConfig:loadConfig}=require("./config.js"),{fmtElapsed:fmtElapsed}=require("./format.js"),limits=require("./limits.js"),SUBCOMMANDS=new Set(["add","list","run","proceed","start","tick","timer","report","reconcile","clear","retry","help"]),EXECUTES=new Set(["run","proceed","start","tick","timer","retry","reconcile"]),DEFAULT_MAX_LOAD=4;function parseFlags(e){const t={terms:[],json:!1,flags:{}},r=new Set(["cwd","model","effort","workers","max","max-rounds","source","class","since","max-load","every"]);for(let n=0;n<e.length;n++){const s=e[n];if("--json"!==s){if(s.startsWith("--")){const[o,i]=s.slice(2).split("="),a=o.trim();if(new Set(["commit","all","auto","stop-on-error","single-pass","help","wait"]).has(a)){t.flags[a]=!0;continue}if(!r.has(a))throw new Error(`unknown option: --${a}`);const u=void 0!==i?i:e[++n];if(void 0===u)throw new Error(`--${a} needs a value`);t.flags[a]=u;continue}t.terms.push(s)}else t.json=!0}return t}function intFlag(e,t){const r=e[t];if(void 0===r||""===r)return null;const n=Number.parseInt(r,10);return Number.isFinite(n)&&n>0?n:null}function taskLine(e){const t=e.model||"(default)",r=String(e.status||"?").padEnd(7),n=`#${e.id}`.padEnd(4),s=String(e.task||"").replace(/\s+/g," ").trim();return`${n} ${r} ${t} ${s.length>72?`${s.slice(0,71)}…`:s}`}function describeCounts(e){const t={pending:0,running:0,done:0,error:0};for(const r of e)void 0!==t[r.status]&&(t[r.status]+=1);return t}function printRunReport(e,t){for(const r of e){const e=Boolean(r.ok&&r.stoppedOnRounds),n=e?"⏸":r.ok?"✓":"✗",s=e?"paused — will resume":r.ok?"done":"failed";if(t.stdout.write(`aegiscode: ${n} #${r.id} ${s} (${fmtElapsed(r.ms)})`),r.commit&&r.commit.ok&&r.commit.staged?t.stdout.write(` — committed ${r.commit.staged} path(s)`):r.commit&&r.commit.skipped&&r.commit.reason&&t.stdout.write(` — no commit (${r.commit.reason})`),t.stdout.write("\n"),!r.ok&&r.error&&t.stderr.write(`aegiscode: #${r.id}: ${r.error}\n`),r.ok&&r.output){const e=String(r.output).trim();t.stdout.write(`${e.length>4e3?`${e.slice(0,4e3)}\n… [output clipped]`:e}\n`)}}}function buildEngine({io:e,quiet:t=!1}){const r=require("./credentials.js"),n=require("./deps.js").createClient(r.clientOptions({channel:"cli"}));if(!n.apiKey)return{error:`no AEGIS account key — ${r.HOW_TO_SET}, or set ${r.KEY_ENV}`};const s=createEngine({client:n,getConfirmMode:()=>!1,getProEnabled:()=>{try{return proEnabled(loadConfig())}catch{return!1}}});let o=null;try{o=require("./entitlement.js").createCliEntitlement({aegis:n})}catch{o=null}return{client:n,engine:s,entitlement:o}}function progressSink(e,{json:t}){return t?()=>{}:t=>{if(t&&"object"==typeof t)if("start"!==t.type){if("tool"===t.type&&t.tool&&"run"===t.tool.phase){const r=t.tool.args||{},n=r.command||r.pattern||autonomous.writtenPath(t.tool)||"",s=String(n).slice(0,100);return void e.stderr.write(` ⚙ ${t.tool.name}${s?` ${s}`:""}\n`)}"healed"!==t.type?"note"===t.type&&t.note?e.stderr.write(` ⓘ ${t.note}\n`):"recovered"===t.type&&e.stdout.write(`aegiscode: re-queued task(s) ${t.ids.join(", ")} from a dead worker\n`):e.stdout.write(`aegiscode: PLAN.md status list healed for phase(s) ${t.phases.join(", ")}\n`)}else e.stdout.write(`aegiscode: #${t.taskId} running on ${t.model} in ${t.cwd}\n`)}}async function runQueueCommand(e,t,r={}){const n=r.stdout||process.stdout,s=r.stderr||process.stderr,o={stdout:n,stderr:s};let i;try{i=parseFlags(t||[])}catch(e){return s.write(`aegiscode autonomous: ${e.message}\n`),2}const a=Boolean(r.json||i.json),u=(e,t)=>{a?n.write(`${JSON.stringify(e,null,2)}\n`):void 0!==t&&n.write(t.endsWith("\n")?t:`${t}\n`)};if("help"===e||!SUBCOMMANDS.has(e))return n.write(usageText()),"help"===e?0:2;if(EXECUTES.has(e)&&limits.armed())return limits.refuse();const l=i.flags.cwd?path.resolve(String(i.flags.cwd)):process.cwd();if("add"===e){const t=i.terms.join(" ").trim();if(!t)return s.write('aegiscode autonomous add: a task needs text — `aegiscode autonomous add "…"`\n'),2;let r;try{r=queue.addTask(process.env,{task:t,cwd:l,class:i.flags.class||null,model:i.flags.model||null,effort:i.flags.effort||null,workers:intFlag(i.flags,"workers"),maxRounds:intFlag(i.flags,"max-rounds"),singlePass:Boolean(i.flags["single-pass"]),commit:Boolean(i.flags.commit),source:i.flags.source||"cli"})}catch(e){return s.write(`aegiscode autonomous add: ${e.message}\n`),2}return u({ok:!0,id:r.id,item:r,queue:queue.queuePath(process.env)},`aegiscode: queued #${r.id} — ${queue.pendingCount(queue.loadQueue(process.env))} pending`),0}if("list"===e){const e=queue.loadQueue(process.env),t=describeCounts(e);if(a)u({ok:!0,file:queue.queuePath(process.env),counts:t,tasks:e,runs:queue.readRuns(process.env,{limit:10})});else{n.write(`queue: ${queue.queuePath(process.env)}\n`),n.write(`tasks: ${e.length} (${t.pending} pending, ${t.running} running, ${t.done} done, ${t.error} error)\n`);for(const t of e)n.write(`${taskLine(t)}\n`);e.length||n.write("(empty)\n")}return 0}if("report"===e){const e=void 0!==i.flags.since?Number.parseInt(String(i.flags.since),10):null,t=intFlag(i.flags,"max")||20,r=queue.readRuns(process.env,{limit:t}),s=describeCounts(queue.loadQueue(process.env)),o=Number.isFinite(e)&&null!==e?r.filter(t=>Number(t.id)>e):r;if(a)return u({ok:!0,file:queue.runsPath(process.env),counts:s,runs:o}),0;n.write(`runs: ${queue.runsPath(process.env)}\n`),o.length||n.write(Number.isFinite(e)&&null!==e?`(nothing finished after #${e})\n`:"(no finished runs yet)\n");for(const e of o){const t="done"===e.status?"✓":"stopped"===e.status?"⏸":"✗";n.write(`${t} #${e.id} ${String(e.status||"?").padEnd(7)} ${e.model||"(default)"} ${fmtElapsed(e.ms)}\n`),n.write(` ${String(e.task||"").replace(/\s+/g," ").trim().slice(0,160)}\n`),e.error&&n.write(` error: ${String(e.error).split("\n")[0]}\n`),e.files&&e.files.length&&n.write(` files: ${e.files.slice(0,8).join(", ")}\n`)}return n.write(`queue: ${s.pending} pending, ${s.running} running, ${s.done} done, ${s.error} error\n`),0}if("clear"===e){const e=queue.clearQueue(process.env,{all:Boolean(i.flags.all)});return u({ok:!0,...e},`aegiscode: removed ${e.removed} finished task(s); ${e.kept} kept`),0}if("retry"===e){const e=i.terms[0];if(!e)return s.write("aegiscode autonomous retry: which task? `aegiscode autonomous retry <id>`\n"),2;const t=queue.retryTask(process.env,e);return t?(u({ok:!0,id:t.id,item:t},`aegiscode: #${t.id} is pending again`),0):(s.write(`aegiscode autonomous retry: no task #${e}\n`),1)}if("start"===e){const t=queue.loadQueue(process.env).filter(e=>"running"===e.status&&e.pid);if(t.length)return s.write(`aegiscode autonomous start: #${t[0].id} is already running (pid ${t[0].pid})\n`),1;const r=["autonomous","proceed"];i.flags.commit&&r.push("--commit"),intFlag(i.flags,"max")&&r.push("--max",String(intFlag(i.flags,"max"))),i.flags["stop-on-error"]&&r.push("--stop-on-error");const n=process.argv[1];if(!n)return s.write("aegiscode autonomous start: cannot locate the CLI entry point to detach\n"),2;let o;try{o=spawn(process.execPath,[n,...r],{cwd:l,env:process.env,detached:!0,stdio:"ignore"})}catch(e){return s.write(`aegiscode autonomous start: could not spawn the drain — ${e.message}\n`),1}return o.unref(),u({ok:!0,pid:o.pid,log:queue.dataDir(process.env)},`aegiscode: drain started in the background (pid ${o.pid})\n it writes ~/.aegiscode/runs.jsonl as tasks settle — read it back with \`aegiscode autonomous report\``),0}if("timer"===e){const t=(i.terms[0]||"status").toLowerCase(),r=intFlag(i.flags,"every")||5,o=void 0!==i.flags["max-load"]?Number(i.flags["max-load"]):4;if(!Number.isFinite(o)||o<0)return s.write("aegiscode autonomous timer: --max-load needs a number >= 0 (0 disables the gate)\n"),2;const c=process.argv[1]?path.resolve(process.argv[1]):null;if(!c)return s.write("aegiscode autonomous timer: cannot locate the CLI entry point to schedule\n"),2;const d=timerPlan({every:r,maxLoad:o,self:c,tickArgs:["autonomous","tick","--commit","--max-load",String(o)],cwd:l});if("status"===t){const e="unsupported"!==d.kind&&d.paths.every(e=>fs.existsSync(e)),t=d.state(),s=e&&("active"===t||"loaded"===t||"registered"===t||"schtasks"===d.kind),i=e&&"function"==typeof d.read?d.read():null,l=Boolean(i&&(null!=i.every||null!=i.maxLoad)),c=i&&null!=i.every?i.every:r,m=i&&null!=i.maxLoad?i.maxLoad:o;if(a)return u({ok:!0,installed:s,written:e,kind:d.kind,paths:d.paths,every:c,maxLoad:m,fromUnit:l,state:t}),0;n.write(`timer: ${d.kind} — ${s?"installed and armed":e?"WRITTEN BUT NOT ARMED":"not installed"}\n`);for(const e of d.paths)n.write(` ${fs.existsSync(e)?"✓":"·"} ${e}\n`);return n.write(` every ${c} min, load gate ${m>0?m:"off"}`+(l?" (from the installed unit)":"")+"\n"),l||e||n.write(" (requested values — nothing is installed, so nothing fires)\n"),t&&n.write(` state: ${t}\n`),s||n.write(e?"\n the units exist but the scheduler has not loaded them. finish it:\n systemctl --user daemon-reload && systemctl --user enable --now aegiscode-queue.timer\n":"\n install it: aegiscode autonomous timer install\n"),0}if("install"===t){if("unsupported"===d.kind)return s.write(`aegiscode autonomous timer: this platform (${process.platform}) has no supported scheduler\n`),2;try{d.install()}catch(e){return s.write(`aegiscode autonomous timer: install failed — ${e.message}\n`),1}return u({ok:!0,kind:d.kind,paths:d.paths,every:r,maxLoad:o},`aegiscode: timer installed — every ${r} min, load gate ${o>0?o:"off"}\n it runs: aegiscode autonomous tick --max-load ${o}\n collect what it did with \`aegiscode autonomous report\``),0}if("remove"===t){try{d.remove()}catch(e){return s.write(`aegiscode autonomous timer: remove failed — ${e.message}\n`),1}return u({ok:!0,kind:d.kind,paths:d.paths},"aegiscode: timer removed"),0}return s.write(`aegiscode autonomous timer: unknown action \`${t}\` — install | status | remove\n`),2}if("tick"===e){const e=void 0!==i.flags["max-load"]?Number(i.flags["max-load"]):4;if(!Number.isFinite(e)||e<0)return s.write("aegiscode autonomous tick: --max-load needs a number >= 0 (0 disables the gate)\n"),2;const t=os.loadavg()[0];if(e>0&&t>e)return u({ok:!0,skipped:"load",load:Number(t.toFixed(2)),maxLoad:e},`aegiscode: tick skipped — load ${t.toFixed(2)} > ${e}\n`),0}const c=buildEngine({io:r});if(c.error)return s.write(`aegiscode autonomous: ${c.error}\n`),2;if(c.entitlement)try{await c.entitlement.refresh()}catch{}const d=autonomous.createQueueWorker({engine:c.engine,env:process.env,log:progressSink(o,{json:a}),canFanOut:()=>{if(!c.entitlement)return!1;try{const e=c.entitlement.current();return Boolean(e&&!0===e.entitled)}catch{return!1}}});if(c.entitlement)try{const e=c.entitlement.current();e&&!1===e.entitled&&!1===e.degraded&&e.refusal&&(s.write(`aegiscode autonomous: ${e.refusal}\n`),s.write(" ↳ write tasks like: Do X autonomously\n"),s.write("balance"===e.wall?" ↳ unlock: top up the Token Bank, or upgrade to Unlimited\n":" ↳ unlock: Unlimited, or any Token Bank balance\n"),e.upgradeUrl&&s.write(` ${e.upgradeUrl}\n`))}catch{}const m=!!i.flags.commit||void 0;let g=0;const p=e=>()=>{g+=1,g>1&&(process.removeListener("SIGINT",f),process.removeListener("SIGTERM",h),process.removeListener("SIGHUP",k),process.exit(130));const t=queue.loadQueue(process.env).find(e=>"running"===e.status&&e.pid===process.pid);t&&d.cancel(t.id),"SIGINT"!==e&&(process.exitCode=130)},f=p("SIGINT"),h=p("SIGTERM"),k=p("SIGHUP");process.on("SIGINT",f),process.on("SIGTERM",h),process.on("SIGHUP",k);try{if("reconcile"===e){const e=await d.reconcile({cwd:l,auto:Boolean(i.flags.auto),commit:m,max:intFlag(i.flags,"max")||0,stopOnError:Boolean(i.flags["stop-on-error"])});return e.ok?(a||printRunReport(e.ran||[],o),u(e,e.exhausted?"aegiscode: every phase in PLAN.md is done — nothing to queue":`aegiscode: phase ${e.phase} queued${e.ran?` — ${e.ran.length} task(s) run`:""}`),0):(s.write(`aegiscode autonomous reconcile: ${e.error||"reconcile failed"}\n`),u(e,void 0),1)}if("proceed"===e||"run"===e||"tick"===e){const t="run"===e?1:intFlag(i.flags,"max")||0,r=await d.proceed({commit:m,max:t,stopOnError:Boolean(i.flags["stop-on-error"])});if(r.locked)return s.write(`aegiscode autonomous: another drain holds the queue lock (pid ${r.holder&&r.holder.pid})\n`),u({ok:!1,locked:!0,holder:r.holder},void 0),1;a||printRunReport(r.ran,o);const n=r.ran.filter(e=>!e.ok).length;return u({ok:0===n,ran:r.ran.map(e=>({id:e.id,ok:e.ok,error:e.error||null,ms:e.ms})),failed:n},r.ran.length?`aegiscode: ${r.ran.length} task(s) run${n?`, ${n} failed`:""}`:"aegiscode: nothing pending"),n?1:0}}finally{process.removeListener("SIGINT",f),process.removeListener("SIGTERM",h),process.removeListener("SIGHUP",k)}return n.write(usageText()),2}function timerPlan({every:e,maxLoad:t,self:r,tickArgs:n,cwd:s}){const o=Math.max(1,Math.floor(e)),i=[process.execPath,r,...n].map(shellQuote).join(" "),a=s||process.cwd();if("linux"===process.platform){const e=path.join(os.homedir(),".config","systemd","user"),t=path.join(e,"aegiscode-queue.service"),r=path.join(e,"aegiscode-queue.timer"),n=["[Unit]","Description=AEGIS Code — drain the unattended work queue (one gated tick)","","[Service]","Type=oneshot",`WorkingDirectory=${a}`,`ExecStart=${i}`,"Nice=10","TimeoutStartSec=6h",""].join("\n"),s=["[Unit]","Description=AEGIS Code — the queue tick timer","","[Timer]","OnActiveSec=1min",`OnUnitActiveSec=${o}min`,"Persistent=true","AccuracySec=30s","","[Install]","WantedBy=timers.target",""].join("\n");return{kind:"systemd-user",paths:[t,r],install(){fs.mkdirSync(e,{recursive:!0}),fs.writeFileSync(t,n),fs.writeFileSync(r,s),runScheduler(["systemctl","--user","daemon-reload"],{ignore:!0});const a=runScheduler(["systemctl","--user","enable","--now","aegiscode-queue.timer"],{ignore:!0});if(a.error||0!==a.status){const t=a.error?a.error.message:String(a.stderr||"").trim();throw new Error(`units were written to ${e}, but the scheduler refused to load them: ${t}\n finish it yourself: systemctl --user daemon-reload && systemctl --user enable --now aegiscode-queue.timer\n or use cron instead: */${o} * * * * ${i}`)}},remove(){try{runScheduler(["systemctl","--user","disable","--now","aegiscode-queue.timer"])}catch{}for(const e of[r,t])try{fs.unlinkSync(e)}catch{}try{runScheduler(["systemctl","--user","daemon-reload"])}catch{}},state(){try{const e=spawnSync("systemctl",["--user","is-active","aegiscode-queue.timer"],{encoding:"utf8"});return String(e.stdout||"").trim()||null}catch{return null}},read(){let e=null,n=null;try{const t=fs.readFileSync(r,"utf8"),n=/OnUnitActiveSec=(\d+)\s*min/.exec(t);n&&(e=Number(n[1]))}catch{}try{const e=fs.readFileSync(t,"utf8"),r=/--max-load\s+(\S+)/.exec(e);r&&(n=Number(r[1]))}catch{}return{every:e,maxLoad:n}}}}if("darwin"===process.platform){const e=path.join(os.homedir(),"Library","LaunchAgents"),t=path.join(e,"org.aegiscloud.aegiscode-queue.plist"),s="org.aegiscloud.aegiscode-queue",i=['<?xml version="1.0" encoding="UTF-8"?>','<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">','<plist version="1.0">',"<dict>"," <key>Label</key>",` <string>${s}</string>`," <key>ProgramArguments</key>"," <array>",` <string>${xmlEscape(process.execPath)}</string>`,` <string>${xmlEscape(r)}</string>`,...n.map(e=>` <string>${xmlEscape(e)}</string>`)," </array>"," <key>WorkingDirectory</key>",` <string>${xmlEscape(a)}</string>`," <key>StartInterval</key>",` <integer>${60*o}</integer>`," <key>RunAtLoad</key>"," <true/>"," <key>StandardErrorPath</key>",` <string>${xmlEscape(path.join(os.homedir(),".aegiscode","timer.log"))}</string>`,"</dict>","</plist>",""].join("\n");return{kind:"launchd",paths:[t],install(){fs.mkdirSync(e,{recursive:!0}),fs.writeFileSync(t,i),runScheduler(["launchctl","unload",t],{ignore:!0}),runScheduler(["launchctl","load","-w",t])},remove(){try{runScheduler(["launchctl","unload","-w",t])}catch{}try{fs.unlinkSync(t)}catch{}},state(){try{return 0===spawnSync("launchctl",["list",s],{encoding:"utf8"}).status?"loaded":"not loaded"}catch{return null}},read(){try{const e=fs.readFileSync(t,"utf8"),r=/<key>StartInterval<\/key>\s*<integer>(\d+)<\/integer>/.exec(e),n=/<string>--max-load<\/string>\s*<string>([^<]+)<\/string>/.exec(e);return{every:r?Math.round(Number(r[1])/60):null,maxLoad:n?Number(n[1]):null}}catch{return{every:null,maxLoad:null}}}}}if("win32"===process.platform){const e="AegisCodeQueue";return{kind:"schtasks",paths:[],install(){runScheduler(["schtasks","/Create","/tn",e,"/tr",i,"/sc","minute","/mo",String(o),"/f","/rl","LIMITED"])},remove(){try{runScheduler(["schtasks","/Delete","/tn",e,"/f"])}catch{}},state(){try{return 0===spawnSync("schtasks",["/Query","/tn",e],{encoding:"utf8"}).status?"registered":"not registered"}catch{return null}},read(){try{const t=spawnSync("schtasks",["/Query","/tn",e,"/XML"],{encoding:"utf8"}),r=String(t.stdout||""),n=/<Interval>PT(\d+)M<\/Interval>/i.exec(r),s=/--max-load\s+(\d+(?:\.\d+)?)/.exec(r);return{every:n?Number(n[1]):null,maxLoad:s?Number(s[1]):null}}catch{return{every:null,maxLoad:null}}}}}return{kind:"unsupported",paths:[],install(){},remove(){},state:()=>null,read:()=>({every:null,maxLoad:null})}}function runScheduler(e,{ignore:t=!1}={}){const[r,...n]=e,s=spawnSync(r,n,{encoding:"utf8"});if(t)return s;if(s.error)throw new Error(`${r}: ${s.error.message}`);if(0!==s.status)throw new Error(`${r} ${n.join(" ")} exited ${s.status}: ${String(s.stderr||"").trim()}`);return s}function shellQuote(e){const t=String(e);return/[\s"']/.test(t)?'"'+t.replace(/"/g,'\\"')+'"':t}function xmlEscape(e){return String(e).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function usageText(){return["aegiscode autonomous <command> — the unattended work queue","","Commands:",' add "<task>" queue a task (--cwd, --class, --model, --effort, --commit,'," --single-pass, --workers N, --max-rounds N)"," --class aegis|byok|local|pro (default aegis); --model must"," match the class (pro takes a claude alias, or none at all)"," list show queued tasks and the tail of the runs log"," run drain ONE task, then stop"," proceed drain every pending task (--max N, --stop-on-error, --commit)"," start drain in the BACKGROUND (detached) and return its pid at once"," use this instead of `proceed` when nothing is waiting for the"," output — a long drain outlives a harness timeout this way"," (--max N, --stop-on-error, --commit)"," tick ONE drain, skipped when the machine is busy — the timer body"," (--max-load N, default 4.0; 0 disables the gate)"," timer install|status|remove the repeating timer that calls `tick`"," (--every MIN default 5, --max-load N default 4.0)"," report what finished: settled runs from the log (+ queue counts)"," --since <id> for only what happened after that task,"," --max N for more of the log"," reconcile queue the next unfinished PLAN.md phase (--auto drains it)"," retry <id> put a finished task back in the queue"," clear drop finished tasks (--all empties the queue)","","Options:"," --json emit JSON instead of text (also on add/list/clear/retry)","","A drain runs with tool approval DISABLED (nobody is there to click a card),","one task at a time, and commits only the paths the task itself changed."].join("\n")+"\n"}module.exports={runQueueCommand:runQueueCommand,parseFlags:parseFlags,taskLine:taskLine,usageText:usageText,SUBCOMMANDS:SUBCOMMANDS,timerPlan:timerPlan,DEFAULT_MAX_LOAD:4};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
2
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
-
"use strict";const fs=require("node:fs"),os=require("node:os"),path=require("node:path"),{execSync:execSync}=require("node:child_process"),{span:span}=require("./screen.js"),{C:C,BOLD:BOLD,BOLD_OFF:BOLD_OFF,THEME_TABLE:THEME_TABLE,themeContradicts:themeContradicts}=require("./theme.js"),{caps:caps,setCaps:setCaps,resetCaps:resetCaps,describe:describe,probeTerminalBackground:probeTerminalBackground}=require("./caps.js"),panels=require("./panels.js"),overlays=require("./overlays.js"),{updateConfig:updateConfig,loadConfig:loadConfig,loadPermissions:loadPermissions,savePermissions:savePermissions,addPermissionRule:addPermissionRule,DEFAULT_PERMISSIONS:DEFAULT_PERMISSIONS,permissionsPath:permissionsPath,configPath:configPath,aegisDir:aegisDir,setConfirmPosture:setConfirmPosture,setPermissionDefaultMode:setPermissionDefaultMode,confirmPosture:confirmPosture,permissionMode:permissionMode,setPermissionMode:setPermissionMode,PERMISSION_MODES_LOCAL:PERMISSION_MODES_LOCAL,memoryPersistState:memoryPersistState,setMemoryPersist:setMemoryPersist,getModelAutoSync:getModelAutoSync,setModelAutoSync:setModelAutoSync}=require("./config.js"),{auditExposure:auditExposure,repairExposure:repairExposure}=require("./securefs.js"),{copyToClipboard:copyToClipboard}=require("./clipboard.js"),{snapshotCheckpoint:snapshotCheckpoint,listCheckpoints:listCheckpoints,loadCheckpoint:loadCheckpoint}=require("./checkpoint.js"),{signupUrl:signupUrl,goUrl:goUrl}=require("./signup.js"),screens=require("./screens.js"),{summarizeTranscript:summarizeTranscript,recapLine:recapLine}=require("./summarize.js"),{sessionAccounting:sessionAccounting,accountingFromUsage:accountingFromUsage,estimateTokens:estimateTokens}=require("./tokens.js"),{effortRung:effortRung}=require("./engine.js"),{transcriptToMarkdown:transcriptToMarkdown,transcriptToJSON:transcriptToJSON,writeExportFile:writeExportFile,lastAssistantText:lastAssistantText}=require("./export.js"),{detectDevCommand:detectDevCommand,runDevServer:runDevServer}=require("./devrun.js"),{PING_MODES:PING_MODES,DEFAULT_PING_MODE:DEFAULT_PING_MODE,normalizePingMode:normalizePingMode,normalizePingSeconds:normalizePingSeconds,buildPing:buildPing,writePing:writePing}=require("./ping.js"),{addTodo:addTodo,completeTodo:completeTodo,clearTodos:clearTodos,formatTodos:formatTodos,todosFile:todosFile}=require("./todos.js"),{configRows:configRows,formatConfigRows:formatConfigRows,setConfigValue:setConfigValue,resetConfigValue:resetConfigValue,fullValue:fullValue,summarizeValue:summarizeValue,configStore:configStore}=require("./settings.js"),credentials=require("./credentials.js"),cloudsync=require("./cloudsync.js"),{maskKey:maskKey,fmtTokens:fmtTokens,shortCwd:shortCwd}=require("./format.js"),{pickerEntries:pickerEntries}=require("./models.js"),{resolveShared:resolveShared}=require("./sharedpaths.js"),sandboxLib=require(resolveShared(path.join("desktop","lib","local","sandbox.js"))),{createCliEntitlement:createCliEntitlement,paymentView:paymentView,probeFee:probeFee}=require("./entitlement.js"),{openUrl:openUrl,URLS:URLS}=require("./system.js"),sysdiag=require("./sysdiag.js"),{sniffProject:sniffProject,buildAegisMd:buildAegisMd}=require("./init.js"),{upgradeAdvice:upgradeAdvice,latestPublishedVersion:latestPublishedVersion,applyUpgrade:applyUpgrade,installMethod:installMethod}=require("./update.js"),{AGENT_PRESETS:AGENT_PRESETS,agentRoles:agentRoles,composeAgentPrompt:composeAgentPrompt,composeResearchPrompt:composeResearchPrompt,composeDebatePrompt:composeDebatePrompt}=require("./agents.js"),{aggregateSessionUsage:aggregateSessionUsage,pruneSessionHistory:pruneSessionHistory,readResumeList:readResumeList}=require("./history.js"),naming=require("./naming.js"),{sessionStore:sessionStore}=require("./shared.js"),RESUME_SEARCH_LIMIT=200,namingBackfillAttempted=new Set,NAMING_BACKFILL_MAX=25;function backfillSessionNames(e){let t,n=25;try{t=sessionStore.listSessions(aegisDir())}catch{return}for(const o of t){if(n<=0)break;if(!o||!o.id||namingBackfillAttempted.has(o.id))continue;const t=(Array.isArray(o.messages)?o.messages:[]).find(e=>e&&"user"===e.role&&e.content);t&&(!0!==o.named||naming.isSeedTitle(o.title,t.content))&&(namingBackfillAttempted.add(o.id),n-=1,naming.nameSession(sessionStore,aegisDir(),o.id,t.content,{callModel:(t,n)=>e.ask(t,{system:n&&n.system||naming.TITLE_SYSTEM,maxTokens:64,signal:n&&n.signal}).then(e=>e&&e.text||null).catch(()=>null)}).catch(()=>{}))}}let markdownModule=null;try{markdownModule=require("./markdown.js")}catch{markdownModule=null}const VERSION=require("../package.json").version,CATEGORIES=[{id:"session",label:"Session & context"},{id:"workspace",label:"Workspace"},{id:"model",label:"Model & behavior"},{id:"data",label:"Data"},{id:"auth",label:"Auth"},{id:"support",label:"Support"},{id:"fun",label:"Fun"},{id:"aegis",label:"Aegis plugin"},{id:"custom",label:"Custom"}],categoryLabel=e=>(CATEGORIES.find(t=>t.id===e)||{}).label||e,EFFORT_LEVELS=overlays.EFFORT_VALUES,note=(e,t)=>e.push({role:"note",text:t}),panel=(e,t)=>e.push({role:"panel",lines:t}),tip=(e,t)=>e.push({role:"tip",text:t});function askTierNote(e){note(e,"Note: 'ask' rules aren't enforced by any session in this build yet — only allow/deny rules take effect. The rule is saved and will apply once that wiring ships.")}const done=(e,t)=>e.push({role:"done",text:t});function composeMultiFanoutPrompt(e){return["Execute this task as a multi-agent fan-out.","",`Task: ${e}`,"",`Workspace: ${process.cwd()}`,"","Use the task tool to delegate the independent parts to specialist subagents. Delegations run CONCURRENTLY when you emit them as multiple task calls in ONE assistant message, so put independent ones in the same message rather than one per message:","- reconnaissance first (scanner for secrets/unsafe patterns, analyzer for refactor targets),","- then design (architect, or planner when the work is a change to existing code),","- then an implementer subagent to make the change.","Finally review the result (reviewer subagent), fix what it finds, and verify with the repository's real commands.","","Return one consolidated report: what each subagent found, the files you changed, the exact commands you ran and their real output, and anything still blocked. No preamble."].join("\n")}async function multiData(e,t){const n=composeMultiFanoutPrompt(t),o=e&&e.withWorking?t=>e.withWorking(t):e=>e();if(!e||"function"!=typeof e.ask&&"function"!=typeof e.runPrompt)return{error:"No agent loop in this context — the fan-out prompt was composed, not run."};try{if("function"==typeof e.ask){const t=await o(t=>e.ask(n,{signal:t})),r=t&&t.text||"";return t&&t.interrupted&&!r?{cancelled:!0}:r?{result:r,model:t&&t.model||e.ctx&&e.ctx.model||null,provider:"aegis"}:{error:"The multi-agent fan-out returned nothing (the turn failed before it could delegate)."}}return await o(()=>e.runPrompt(n)),{streamed:!0}}catch(e){return{error:`ÆGIS multi failed — ${e&&e.message||e}`}}}async function runMultiCommand(e,t,{yolo:n=!1,title:o="ÆGIS Multi"}={}){n&&(setConfirmPosture(!1),panel(e,panels.buildAutomode(e.state(),e.ctx))),note(e,"Running the multi-agent fan-out — the engine delegates to specialist subagents (headless: this skips aegis-cli's own confirmation step)."),e.render();const r=await multiData(e,t);return r.cancelled?(note(e,"ÆGIS multi cancelled."),e.render(),!0):r.error?(note(e,r.error),panel(e,panels.buildAegisMulti(t,e.ctx)),e.render(),!0):(r.streamed||(panel(e,panels.buildAegisPrint(o,r,e.ctx)),e.render()),!0)}const upgradePanelLines=e=>e.map(e=>[span(C.white,e)]);async function billingPayment(e){if(!e||!e.client)return;let t;try{t=createCliEntitlement({aegis:e.client})}catch{return}const n=e.withWorking?t=>e.withWorking(t):e=>e();try{await n(()=>t.refresh({force:!0}))}catch{}const o=await probeFee();return paymentView(t.current(),{host:"cli",fee:o})}async function loadModels(e){try{return await e.loadModels()||[]}catch{return[]}}async function mergedPickerModels(e){const t=e.ctx&&e.ctx.modelClass||"aegis",n=pickerEntries(await loadModelsFor(e,"aegis",t)).map(e=>({...e,cls:"aegis"})),o=pickerEntries(await loadModelsFor(e,"byok",t)).map(e=>({...e,cls:e.cls||"byok"})),r=pickerEntries(await loadModelsFor(e,"pro",t)).map(e=>({...e,cls:"pro"})),s=[],a=new Set;for(const e of[...n,...o,...r]){const t=String(e&&e.id||"");t&&!a.has(t)&&(a.add(t),s.push(e))}return s}async function loadModelsFor(e,t,n){if("function"==typeof e.listModelsFor)try{return await e.listModelsFor(t)||[]}catch{return[]}if(t!==n||"function"!=typeof e.loadModels)return[];try{return await e.loadModels()||[]}catch{return[]}}const cloudReady=()=>credentials.hasApiKey(),{withByokAdditions:withByokAdditions}=require(resolveShared(path.join("client","byok-catalog.js"))),{withUserModels:withUserModels,addUserModel:addUserModel,removeUserModel:removeUserModel,userModelIdsFor:userModelIdsFor,userModelsPath:userModelsPath}=require(resolveShared(path.join("client","user-models.js"))),catalogClient=require(resolveShared(path.join("client","catalog-client.js"))),{withCatalog:withCatalog}=catalogClient,{discoverModels:discoverVendorModels,endpointFor:vendorEndpointFor,discoverableProviders:discoverableProviders}=require(resolveShared(path.join("client","model-discovery.js"))),modelSync=require(resolveShared(path.join("client","model-sync.js"))),{createModelAutoSync:createModelAutoSync}=require(resolveShared(path.join("client","model-autosync.js")));let autoSyncScheduler=null;function shellAutoSync(e){return autoSyncScheduler||(autoSyncScheduler=createModelAutoSync({getPref:()=>getModelAutoSync(),plan:async t=>{const n=await byokCatalog(e&&e.client);if(!n)return{ok:!1,providers:[],missing:0,stale:0,error:"no provider catalog (offline, or no relay yet)"};const o={};for(const r of modelSync.askableProviders(n,t)){const t=byokKeyForProvider(e,r);t&&(o[r]=t)}return modelSync.plan(n,{keys:o,only:t})},apply:(e,t)=>modelSync.apply(e,{only:t})}),autoSyncScheduler)}async function runAutoModelSync(e){try{return await shellAutoSync(e).runIfDue()}catch{return{ran:!1,reason:"error",added:0,missing:0}}}function byokKeyForProvider(e,t){const n=String(t||"").trim().toLowerCase();if(!n)return"";try{const t=e&&e.settings&&e.settings();if(t&&"function"==typeof t.rawKey&&"function"==typeof e.byokNamespace){const o=t.rawKey(e.byokNamespace(n));if("string"==typeof o&&o.trim())return o.trim()}}catch{}try{const{providerKeyFromEnv:e}=require(resolveShared(path.join("client","env-file.js")));return(e(n)||{}).key||""}catch{return""}}async function discoverProviderModels(e,t,n){try{return await discoverVendorModels(t,{key:n,fetchImpl:e&&e.fetchImpl})}catch(e){return{ok:!1,provider:t,supported:!0,error:e&&e.message||String(e)}}}async function offeredModelIds(e,t,n){const o=await discoverProviderModels(e,t,n);return o&&o.ok&&Array.isArray(o.ids)&&o.ids.length?o.ids:void 0}function splitCommandWords(e){const t=[];let n="",o=null,r=!1;for(const s of String(null==e?"":e))o?s===o?o=null:n+=s:'"'!==s&&"'"!==s?/\s/.test(s)?(n||r)&&(t.push(n),n="",r=!1):(n+=s,r=!0):(o=s,r=!0);return(n||r)&&t.push(n),t}function savedByokBaseURL(e,t){try{const n=e&&e.settings&&e.settings();if(!n||"function"!=typeof n.get||"function"!=typeof e.byokNamespace)return"";const o=n.get(e.byokNamespace(t))||{};return String(o.baseURL||"").trim()}catch{return""}}function addManyUserModels(e,t){let n=0,o=0;const r=[],s=[];for(const a of t)try{addUserModel(e,a).added?n+=1:r.push(a)}catch(e){const i=e&&e.message||String(e);if(/the cap/.test(i)){o=t.length-n-r.length-s.length;break}s.push({id:a,reason:i})}return{added:n,already:r,failed:s,capped:o}}async function byokCatalog(e){if(!e||"function"!=typeof e.byokProviders)return null;try{const t=await e.byokProviders();refreshCatalogInBackground(e);const n=withUserModels(withCatalog(withByokAdditions(t&&t.providers||[])));return n.length?n:null}catch{return null}}function refreshCatalogInBackground(e){try{let t=!0;try{const e=catalogClient.read();t=!e||e.stale}catch{t=!0}if(!t)return null;if("function"!=typeof e.catalog)return null;let n=null;try{const e=catalogClient.read();n=e&&e.data&&e.data.snapshot&&e.data.snapshot.etag||null}catch{n=null}const o=catalogClient.refresh(async({cursor:t,limit:n,etag:o})=>{try{return await e.catalog("models",{cursor:t,limit:n},{etag:o||void 0})}catch(e){if(e&&304===e.status)return{notModified:!0};throw e}},{etag:n});return o&&"function"==typeof o.catch&&o.catch(()=>{}),o}catch{return null}}function findByokProvider(e,t){const n=String(t||"").trim().toLowerCase();if(!e)return{provider:null,exact:!1};const o=e.find(e=>e.id===n);if(o)return{provider:o,exact:!0};const r=e.filter(e=>[e.id,e.label,...e.aliases||[]].filter(Boolean).some(e=>String(e).toLowerCase()===n));return 1===r.length?{provider:r[0],exact:!1}:r.length>1?{ambiguous:r.map(e=>e.id)}:{provider:null,exact:!1}}function byokProviderLines(e){const t=[];for(const n of e){const e=n.configured?span(C.green,"set"+(n.masked?` (${n.masked})`:"")):span(C.gray,"not set"),o=[span(C.gold+BOLD,` ${n.id}`)];n.label&&o.push(span(C.gray,` — ${n.label}`)),o.push(span(""," "),e),t.push(o);const r=(n.models||[]).map(e=>"string"==typeof e?e:e&&e.id).filter(Boolean);r.length&&t.push([span(C.gray,` models: ${r.join(", ")}`)]),n.key_prefix&&t.push([span(C.gray,` key starts with ${n.key_prefix}`)]),n.key_url&&t.push([span(C.gray,` ${n.key_url}`)])}return t}function keyPanelLines(e,t="AEGIS account key"){const n=e.keyStatus(),o=[[span(C.gold+BOLD,t),span(BOLD_OFF,"")],[span(C.gray,"─".repeat(34))],[span(n.configured?C.green:C.coral," "+(n.configured?"✔":"⚠")),span(C.white," key: "),span(n.configured?C.white:C.gray,n.configured?maskKey(n.key):"not set"),span(C.gray,` (${credentials.sourceLabel(n.source)})`)],[span(C.gray,` stored in: ${n.path}${n.fileMode?` ${n.fileMode}`:""}`)]];return n.verifiedAt&&o.push([span(C.gray,` verified: ${n.verifiedAt}`)]),n.account&&(n.account.plan||n.account.email)&&o.push([span(C.gray," account: "),span(C.white,[n.account.plan,n.account.email].filter(Boolean).join(" · "))]),o.push([span(C.gray," memory: "),span(n.memoryToken?C.green:C.gray,n.memoryToken?"token held (cloud sync ready)":"no token yet")]),n.configured||(o.push([span(C.gray,"")]),o.push([span(C.white," Set one with /key <api_key>, or press Enter on /key to paste it.")]),o.push([span(C.gray,` Free key: ${signupUrl("key_status")}`)])),n.legacyPlaintext&&(o.push([span(C.gray,"")]),o.push([span(C.coral," ⚠ a plaintext copy of the key is still in config.json (another AEGIS CLI wrote it).")]),o.push([span(C.gray," Re-save with /key <api_key> and delete that block when convenient.")])),o}async function applyAccountKey(e,t,{label:n="AEGIS API key"}={}){let o=String(t||"").trim();if(o||(o=await e.readSecret(`${n} (kept off screen, Enter to cancel): `)),!o)return note(e,"no key given — /key <api_key> takes it inline, or press Enter on a bare /key to paste it"),{ok:!1};const r=await e.setApiKey(o);if(!r.ok)return note(e,r.message||"that key could not be saved"),r;if(r.error)return note(e,`saved, but the account check failed: ${r.error.message}`),note(e,"the key is stored — /key status shows it; re-run /key <api_key> if it was mistyped"),r;const s=r.account&&(r.account.email||r.account.plan)||null;done(e,`AEGIS key saved to ${r.path}${s?` — signed in as ${s}`:" and verified"}`);try{const t=pickerEntries(await loadModels(e)).length;t&¬e(e,`${t} pinnable model${1===t?"":"s"} available — /model to pin one`)}catch{}return r}function fmtQuotaTokens(e){const t=Number(e);return Number.isFinite(t)?t>=1e6?`${(t/1e6).toFixed(t%1e6==0?0:1)}M`:t>=1e4?`${Math.round(t/1e3)}k`:fmtTokens(t):"?"}function memoryGate(e){if(e&&"function"==typeof e.cloudSyncState)try{return e.cloudSyncState()}catch{}return{enabled:!e||"function"!=typeof e.cloudSyncEnabled||!0===e.cloudSyncEnabled(),source:"default"}}function setMemoryGate(e,t){if(e&&"function"==typeof e.setCloudSync)return e.setCloudSync(t);try{return setMemoryPersist(t)}catch{return null}}function memoryStatusLines(e){const t=memoryGate(e),n=cloudsync.status(),o=n.quota,r=o&&null!=o.used?fmtQuotaTokens(o.used):null,s=o&&null!=o.limit?fmtQuotaTokens(o.limit):null,a="legacy"===t.source?" (kept from your old cloudSync setting)":"default"===t.source?" (default)":"",i=[[span(C.white+BOLD,"Cloud sync"),span(BOLD_OFF,"")],[span(C.gray,"─".repeat(34))],[span(C.white," "+(t.enabled?"on":"off")),span(C.gray,`${a} · ${t.enabled?"each session is stored so an interrupted turn can be resumed":"nothing new is stored"}`)]];return s?i.push([span(C.gray," quota: "),span(C.white,`${r} of ${s} tokens synced`),span(C.gray," (aegis1 charges writes; reads are always served)")]):i.push([span(C.gray," quota: not reported yet — /sync now asks the server for the current numbers")]),n.overQuota&&(i.push([span(C.coral," writes: paused — the plan’s ceiling is reached, so new memory is not being stored")]),i.push([span(C.green," reads: still work — everything already stored stays readable (/aegis-recall <topic>)")]),i.push([span(C.gray,` free room at ${goUrl("upgrade","cloud_quota")}`)]),i.push([span(C.gray," or /cloud memory off to stop trying")])),t.enabled&&n.pending>0&&i.push([span(C.gray,` pending: ${n.pending} session(s) waiting to sync`)]),i.push([span(C.gray," /cloud memory on | off · /sync now pushes once by hand")]),i}async function runCloudSync(e,t={}){if(!e.client.apiKey)return note(e,`no key — ${credentials.HOW_TO_SET}`),null;const n=await e.withWorking(()=>cloudsync.syncNow(e.client,t)),o=n.push&&n.push.pushed||[],r=[...n.push&&n.push.failed||[],...n.pull&&n.pull.failed||[]],s=n.pull&&n.pull.imported||0;o.length?done(e,`pushed ${o.length} session${1===o.length?"":"s"} (${o[0].messages} messages in the first)`):n.push&&n.push.skipped&&n.push.skipped.length?note(e,`${n.push.skipped.length} session(s) had nothing to send`):note(e,"nothing to push — every local session is already in the cloud"),s?done(e,`pulled ${s} record${1===s?"":"s"} into the local store — /resume lists them`):n.pull&&n.pull.ok&¬e(e,`cloud has ${n.pull.remote||0} session(s); nothing newer locally`);for(const t of r)note(e,`${"quota"===t.kind?"quota":"failed"}: ${t.message}`),t.hint&¬e(e,t.hint);return n}const hooksLib=require(resolveShared(path.join("client","hooks.js")));function loadCredits(){try{return require(resolveShared(path.join("client","credits.js"))).creditsFromDisk()}catch(e){return{program:{licence:"AGPL-3.0-or-later",name:"GNU Affero General Public License v3.0 or later",url:"https://www.gnu.org/licenses/agpl-3.0.html",source:"https://github.com/aegisinfo/aegiscode-plugin",copyright:"Copyright (C) 2026 Niklas Borneklint",notice:null},documents:[],code:[],fonts:[],missing:["licensing","vendor","fonts"],error:String(e&&e.message||e)}}}function readHooks(){return hooksLib.readHookConfig()}function hookStats(e){return hooksLib.hookStats(e)}const skillsLib=require(resolveShared(path.join("client","skills.js")));function scanSkills(){const{entries:e}=skillsLib.scan();return e.map(e=>({source:e.scope,name:e.name,namespace:null,description:e.description,path:e.path,warning:e.warning,content:readSkillText(e.path)}))}function readSkillText(e){try{return fs.readFileSync(e,"utf8")}catch{return""}}const COMMANDS=[{name:"run",hint:"",category:"workspace",desc:"Launch and drive this project's app to see a change working",handler:async e=>{const t=detectDevCommand(process.cwd());if(!t)return note(e,"No dev command detected (no package.json scripts, go.mod, Cargo.toml or Makefile). Try /init first."),e.render(),!0;note(e,`Running ${t} in ${shortCwd()} — output streams below, Esc stops it.`);const n=runDevServer(t,{cwd:process.cwd(),onLine:t=>e.push({role:"note",text:` ${t}`})});return n.label||(n.label=t),e.openStream(n),n.done.then(({code:o,stopped:r})=>{e.closeStream(n),done(e,r?`${t} stopped`:`${t} exited (code ${o})`),e.render()}),e.render(),!0}},{name:"schedule",hint:"",category:"session",desc:"Create, update, list, or run scheduled cloud agents (routines)",handler:async e=>(note(e,"Scheduled routines run on the AEGIS cloud. Sign in with `aegis login`, then manage routines at aegiscloud.org."),e.render(),!0)},{name:"build",aliases:["forge"],args:["task"],hint:"<description>",category:"workspace",desc:"Build an app with the agent loop — /build <what to build>",handler:async(e,t)=>{const n=(t._rest||t.task||"").trim();return n?(note(e,"⬡ AEGIS BUILD"),note(e,`Task: ${n}`),e.render(),await e.runPrompt(`Build the following, creating every file it needs and running the build to verify it works: ${n}`),!0):(note(e,"Usage: /build <what to build>"),note(e,"Example: /build a REST API for a todo app"),e.render(),!0)}},{name:"cd",args:["path"],hint:"<path>",category:"workspace",desc:"Move this session to a new working directory",handler:async(e,t)=>{const n=t.path||(t._rest||"").trim();if(!n)return note(e,"Usage: /cd <path>"),e.render(),!0;try{process.chdir(n),e.ctx.cwd=process.cwd(),updateConfig({lastCwd:process.cwd()}),note(e,`Changed directory to ${process.cwd()}`)}catch(t){note(e,`/cd: ${t.message}`)}return e.render(),!0}},{name:"copy",aliases:["cp"],args:["n"],hint:"[N]",category:"data",desc:"Copy the last response to the clipboard",handler:async(e,t)=>{const n=parseInt(t.n||"1",10)||1,o=lastAssistantText(e.transcript,n);if(!o)return note(e,"Nothing to copy yet."),e.render(),!0;const r=copyToClipboard(o);return r.ok?note(e,r.via.startsWith("tool:")?`Copied the last response to the clipboard (${r.via.split(":")[1]}).`:`No clipboard tool found — response saved to ${r.path}`):note(e,"Clipboard unavailable; nothing copied."),e.render(),!0}},{name:"clear",aliases:["cls"],hint:"",category:"session",desc:"Start a new session with empty context",handler:async e=>(e.transcript.length=0,pruneSessionHistory(e.sessionId),"function"==typeof e.clearConversationMemory&&e.clearConversationMemory(),note(e,"Session cleared — transcript empty."),e.render(),!0)},{name:"undo",args:["which"],hint:"[list|<id>]",category:"session",desc:"Reverse a file edit the agent made this conversation",handler:async(e,t)=>{const n=(t._rest||"").trim();if("list"===n){const t="function"==typeof e.listUndoable?e.listUndoable():[];if(!t.length)return note(e,"Nothing to undo in this conversation."),e.render(),!0;note(e,`${t.length} undoable mutation${1===t.length?"":"s"}, newest first:`);for(const n of t){const t=Math.max(0,Math.round((Date.now()-n.at)/1e3));note(e,` ${n.id.slice(0,8)} ${n.tool} ${path.relative(process.cwd(),n.path)||n.path} (${t}s ago)`)}return note(e,"Undo one with: /undo <id> (first 8 characters are enough), or /undo for the most recent."),e.render(),!0}if("function"!=typeof e.undoMutation)return note(e,"Undo is not available on this engine."),e.render(),!0;let o=n||void 0;if(o){const t=("function"==typeof e.listUndoable?e.listUndoable():[]).find(e=>e.id===o||e.id.startsWith(o));if(!t)return note(e,`No undo record starts with "${o}". Try /undo list.`),e.render(),!0;o=t.id}const r=e.undoMutation(o);return note(e,r.ok?`Undone — ${path.relative(process.cwd(),r.path)||r.path} ${"deleted"===r.restored?"deleted (it was a new file)":"restored to its prior content"}.`:r.error),e.render(),!0}},{name:"compact",hint:"",category:"session",desc:"Compact the conversation history",handler:async e=>{if(!e.transcript.some(e=>"user"===e.role||"assistant"===e.role))return note(e,"Nothing to compact yet."),e.render(),!0;note(e,"Compacting conversation history…"),e.render();const t=await e.withWorking(t=>summarizeTranscript(e.transcript,{callModel:(t,n)=>e.ask(t,n).then(e=>e.text),model:e.ctx.model,signal:t}));return null===t?(note(e,"Compaction cancelled."),e.render(),!0):(e.transcript.length=0,note(e,"Compacted. Earlier context summarized into the message below."),e.transcript.push({role:"user",text:t}),e.render(),!0)}},{name:"cost",hint:"",category:"data",desc:"Show the cost of the current session",handler:async e=>{const t=aggregateSessionUsage(e.sessionId),n=t.entries?accountingFromUsage(t.usage,e.ctx.model,{exchanges:t.entries,real:t.real,costUsd:t.real&&t.costUsd?t.costUsd:void 0}):sessionAccounting(e.transcript,e.ctx.model);return panel(e,panels.buildCost({...e.state(),contextWindow:n.contextWindow,costEur:n.cost},e.ctx)),e.render(),!0}},{name:"context",hint:"",category:"session",desc:"Show context usage for the current session",handler:async e=>{const t=sessionAccounting(e.transcript,e.ctx.model);return panel(e,panels.buildContext({...e.state(),contextWindow:t.contextWindow},e.ctx)),e.render(),!0}},{name:"ping",args:["mode","seconds"],hint:"[off|bell|notify|both] [seconds] | test",category:"model",desc:"Alert me when a long turn finishes, if I am looking elsewhere",handler:async(e,t)=>{const n=loadConfig(),o=(t._rest||"").trim().split(/\s+/).filter(Boolean),r=(o[0]||"").toLowerCase(),s=normalizePingMode(n.ping),a=normalizePingSeconds(n.pingMinSeconds);if(!r)return note(e,`[ping] ${s} — a turn longer than ${a}s raises a terminal notification.`),note(e,` /ping ${PING_MODES.filter(e=>e!==s).join("|")} ${"off"===s?"turn it back on":"change the channel"}`),note(e," /ping <mode> <seconds> move the threshold (0 pings every turn)"),note(e," /ping test fire one now, to check this terminal supports it"),e.render(),!0;if("test"===r){const t=buildPing({mode:"off"===s?DEFAULT_PING_MODE:s}),n=!!process.stdout.isTTY&&writePing(process.stdout,t);return note(e,n?"[ping] sent one just now. If nothing appeared or sounded, this terminal implements neither OSC 9 nor OSC 777 — /ping bell is the fallback.":"[ping] nothing sent: stdout is not a TTY (a piped or headless run has no one to notify)."),e.render(),!0}if(!PING_MODES.includes(r))return note(e,`Unknown ping mode "${o[0]}". Use ${PING_MODES.join(", ")}.`),e.render(),!0;const i={ping:r};if(null!=o[1]){const t=Number(o[1]);if(!Number.isFinite(t)||t<0)return note(e,`"${o[1]}" is not a number of seconds. Use /ping ${r} 30.`),e.render(),!0;i.pingMinSeconds=normalizePingSeconds(t)}return updateConfig(i),"off"===r?note(e,"[ping] off — no notice will be raised, and nothing is reported as sent."):(note(e,`[ping] ${r} — turns longer than ${normalizePingSeconds(i.pingMinSeconds??n.pingMinSeconds)}s will notify you.`),note(e," Escape never pings (you were watching), and neither does a piped or headless run.")),e.render(),!0}},{name:"todos",aliases:["todo"],args:["sub","text"],hint:"[add <text> | done <n|text> | clear]",category:"session",desc:"A session todo list that survives compaction",handler:async(e,t)=>{const n=(t.sub||"").toLowerCase(),o=(t._rest||"").trim().replace(/^\S+\s*/,"");if(!n)return panel(e,formatTodos()),note(e,` ${todosFile()}`),note(e," /todos add <text> · /todos done <n|text> · /todos clear"),e.render(),!0;if("add"===n){const t=addTodo(o);return t.error?(note(e,t.error),e.render(),!0):(panel(e,formatTodos(t.list)),e.render(),!0)}if("done"===n||"do"===n){const t=completeTodo(o);return t.error?(note(e,t.error),e.render(),!0):(note(e,`[todos] "${t.item.text}" is now ${t.item.done?"done":"open"}.`),panel(e,formatTodos(t.list)),e.render(),!0)}return"clear"===n?(clearTodos(),note(e,"[todos] cleared."),e.render(),!0):(note(e,`Unknown /todos subcommand "${t.sub}". Use add, done or clear.`),e.render(),!0)}},{name:"config",args:["key","value"],hint:"[<key> | <key> <value> | reset <key>]",category:"session",desc:"Show or change any setting, and say which store holds it",handler:async(e,t)=>{const n=(t._rest||"").trim(),o=(t.key||"").trim(),r=n.replace(/^\S+\s*/,"");if(!o)return panel(e,formatConfigRows(configRows())),note(e," /config <key> show one value in full"),note(e," /config <key> <value> set it (true/false/null, numbers, JSON, or text)"),note(e," /config reset <key> back to the shipped value"),note(e,' "shared" keys live in the store AEGIS Desktop writes too; "host" keys are this shell\'s own.'),e.render(),!0;if("reset"===o){const t=resetConfigValue(r);return t.error?(note(e,t.error),e.render(),!0):(note(e,`[config] ${t.key} reset to ${summarizeValue(t.value)} (${t.store}).`),e.render(),!0)}if(!r){const t=loadConfig();return Object.prototype.hasOwnProperty.call(t,o)?(note(e,`${o} (${configStore(o)}):`),e.push({role:"panel",lines:fullValue(t[o]).split("\n").map(e=>` ${e}`)}),e.render(),!0):(note(e,`unknown config key "${o}" — run /config to list the keys`),e.render(),!0)}const s=setConfigValue(o,r);return s.error?(note(e,s.error),e.render(),!0):(note(e,`[config] ${s.key} = ${summarizeValue(s.value)} (${s.store}).`),["model","currentModelId","modelClass","effort","themeIndex","vim"].includes(s.key)&&("effort"===s.key&&(e.ctx.effort=effortRung(s.value),e.ctx.effort!==String(s.value).toLowerCase()&&(e.saveConfig({effort:e.ctx.effort}),note(e,` "${s.value}" is not a level this build sends — recorded as ${e.ctx.effort}.`))),note(e,` This takes effect on the next turn; /${"currentModelId"===s.key?"model":s.key} shows the live session value.`)),e.render(),!0)}},{name:"effort",args:["level"],hint:"[low|medium|high]",category:"model",desc:"Set the token budget the pool sizes each turn from",handler:async(e,t)=>{const n=(t.level||"").toLowerCase();if(n&&"auto"!==n&&!EFFORT_LEVELS.includes(n))return note(e,`Unknown effort level "${t.level}". Use ${EFFORT_LEVELS.join(", ")}.`),e.render(),!0;if(!n)return e.openOverlay({type:"effort",sel:Math.max(0,EFFORT_LEVELS.indexOf(e.ctx.effort||"high"))}),!0;const o="auto"===n?"high":n;return e.ctx.effort=o,e.saveConfig({effort:o}),note(e,"auto"===n?"effort: auto is retired — high is the default, and it is what this session now sends":`Effort level: ${o} — the pool sizes this turn's token budget from it`),e.render(),!0}},{name:"sandbox",args:["sub","value"],hint:"[on|off|read-only|workspace-write | network <open|restricted> | grant <path> | block <path> | clear]",category:"workspace",desc:"Confine shell commands to a kernel-enforced policy (paths — for command rules see /permissions)",handler:async(e,t)=>{const n=e.settings&&e.settings(),o=n&&"function"==typeof n.getSandboxPolicy,r=n&&"function"==typeof n.setSandboxPolicy,s=()=>o?n.getSandboxPolicy():null,a=t=>r?n.setSandboxPolicy(t):(e.push({role:"error",text:"this client has no settings store to hold a sandbox policy."}),null),i=()=>{sandboxLib.supported()||note(e,`WARNING: no sandbox mechanism is implemented for ${process.platform} yet — this policy will NOT be enforced; commands run with full user access regardless of mode.`)},l=process.cwd(),d=(t.sub||"").toLowerCase(),c=t.value;if(!d){const t=s(),n=sandboxLib.detect({appDir:void 0});if(t){note(e,sandboxLib.describe(n,t));const o=t.fileSystem&&t.fileSystem.entries||[],r=t.fileSystem&&t.fileSystem.denies||[];for(const t of o){const n=t&&t.path;n&&"path"===n.type&¬e(e,` ${t.access.padEnd(5)} ${n.path}`)}for(const t of r)note(e,` deny ${t.path}`);note(e," network restricted is skipped for local models — a local turn cannot reach ollama from a fresh netns.")}else note(e,"sandbox: not configured — shell commands run with your full user access."),note(e,`Turn it on with: /sandbox on (or pick a mode: ${sandboxLib.MODES.filter(e=>"off"!==e).join(", ")})`);return e.render(),!0}if("clear"===d||"off"===d)return a(null),note(e,"off"===d?"sandbox: off — policy cleared; shell commands run unconfined.":"sandbox: policy cleared — shell commands run unconfined."),e.render(),!0;if("on"===d)return a(sandboxLib.defaultPolicy(l)),note(e,`sandbox: workspace-write in ${shortCwd()} — check the shell row says "via bwrap" when a command runs.`),i(),e.render(),!0;const u=s();if(!u)return note(e,"No sandbox policy is set — run /sandbox on first (or /sandbox <mode>)."),e.render(),!0;if(sandboxLib.MODES.includes(d)&&"off"!==d)return a({...u,mode:d}),note(e,`sandbox mode: ${d}`),i(),e.render(),!0;if("network"===d){const t=String(c||"").toLowerCase();return"open"!==t&&"restricted"!==t?(note(e,"usage: /sandbox network <open|restricted>"),e.render(),!0):(a({...u,network:t}),note(e,`sandbox network: ${t}${"restricted"===t?" — note that local models still run with the network open, since a fresh netns cannot reach the ollama daemon":""}`),e.render(),!0)}if("allow"===d||"deny"===d||"grant"===d||"block"===d){const t="deny"===d||"block"===d,n=String(c||"").trim();if(!n)return note(e,`usage: /sandbox ${d} <path>`),e.render(),!0;const o=path.resolve(n);if(t){let t=null;try{t=fs.statSync(o)}catch{return note(e,`No such path: ${o}`),e.render(),!0}if(!t.isDirectory())return note(e,`A deny must name a directory, not a file: ${o}`),e.render(),!0}const r=Array.isArray(u.fileSystem&&u.fileSystem.entries)?u.fileSystem.entries.slice():[],s=Array.isArray(u.fileSystem&&u.fileSystem.denies)?u.fileSystem.denies.slice():[];return t?s.push({path:o}):r.push({path:{type:"path",path:o},access:"write",missingPathBehavior:"skip"}),a({...u,fileSystem:{entries:r,denies:s}}),note(e,t?`sandbox: denying ${o} — emptied inside the sandbox, unchanged outside it`:`sandbox: write granted on ${o}`),e.render(),!0}return note(e,`Unknown /sandbox argument "${t.sub}". Try: on, off, ${sandboxLib.MODES.filter(e=>"off"!==e).join(", ")}, network, grant, block, clear`),e.render(),!0}},{name:"exit",aliases:["quit"],hint:"",category:"session",desc:"Exit the CLI",handler:async()=>!1},{name:"export",args:["format","target"],hint:"[markdown|json] [file|clipboard]",category:"data",desc:"Export the current conversation to a file or clipboard",handler:async(e,t)=>{const n=(t.format||"markdown").toLowerCase(),o=(t.target||"file").toLowerCase();if(!["markdown","md","json"].includes(n)||!["file","clipboard"].includes(o))return note(e,"Usage: /export [markdown|json] [file|clipboard]"),e.render(),!0;const r="json"===n,s=r?transcriptToJSON(e.transcript):transcriptToMarkdown(e.transcript);if("clipboard"===o){const t=copyToClipboard(s);note(e,t.ok?`Exported conversation (${r?"json":"markdown"}) to the clipboard.`:"Clipboard unavailable; nothing copied.")}else try{const t=writeExportFile(s,r?"json":"md",e.ctx.cwd||process.cwd());note(e,`Exported conversation to ${t}`)}catch(t){note(e,`/export: ${t.message}`)}return e.render(),!0}},{name:"help",aliases:["?","h"],hint:"",category:"support",desc:"Show help",handler:async e=>(panel(e,panels.buildHelp(visibleCommands(),e.ctx)),e.render(),!0)},{name:"init",args:["file"],hint:"[file]",category:"workspace",desc:"Create an AEGIS.md file in the project",handler:async(e,t)=>{const n=(t.file||"AEGIS.md").trim(),o=e.ctx.cwd||process.cwd(),r=path.resolve(o,n),s=o.endsWith(path.sep)?o:o+path.sep;if(r!==o&&!r.startsWith(s))return note(e,`/init: refusing to write outside the project directory (${r}).`),e.render(),!0;if(fs.existsSync(r))return note(e,`${n} already exists — not overwriting.`),e.render(),!0;const a=sniffProject(o);try{fs.writeFileSync(r,buildAegisMd(a)+"\n")}catch(t){return note(e,`/init: ${t.message}`),e.render(),!0}return note(e,`Created ${r} (${a.lang})`),fs.existsSync(path.join(o,"node_modules"))&&!fs.existsSync(path.join(o,".gitignore"))&&tip(e,'Add "node_modules/" to a .gitignore before committing.'),e.render(),!0}},{name:"login",aliases:["signin"],args:["value"],hint:"[<api_key>]",category:"auth",desc:"Save your AEGIS API key",handler:async(e,t)=>{const n=String(t.value||t._rest||"").trim();return await applyAccountKey(e,n,{label:"AEGIS API key"}),e.render(),!0}},{name:"logout",args:[],hint:"",category:"auth",desc:"Remove the saved AEGIS API key",handler:async e=>{const t=e.forgetApiKey();return done(e,t.cleared?`key removed from ${t.path}`:"there was no saved key to remove"),credentials.legacyKeyOnDisk()&¬e(e,`a copy is still in ${configPath()} (another AEGIS CLI wrote it) — delete its "aegiscloud" block too`),e.render(),!0}},{name:"model",aliases:["m"],args:["sub"],hint:"[id|-]",category:"model",desc:'Switch AI model — pin an id ("-" clears it)',handler:async(e,t)=>{const n=(t.sub||"").trim(),o=e.ctx&&e.ctx.modelClass||"aegis",r="byok"===o;if(!n){note(e,`model: ${e.ctx.model||"server default"}`);const t=await mergedPickerModels(e);return t.length?(t.some(e=>"aegis"===e.cls||"byok"===e.cls)||note(e,e.state().online?"Could not read the AEGIS Cloud catalog (offline, or the server refused it) — showing Claude Code Pro only; /models retries.":`No AEGIS API key set, so the AEGIS Cloud catalog cannot be read (free key: ${signupUrl("model_blocked")}) — showing Claude Code Pro only.`),e.ctx.model&&!t.some(t=>t.id===e.ctx.model)&¬e(e,r?`pinned model "${e.ctx.model}" is not one this machine can relay — pick from the list below.`:`pinned model "${e.ctx.model}" is not in the catalog — the pool will answer with its own default; pick one below.`),note(e,"/model <id> pins one for this session; picking a direct-provider row prompts for its key if this machine has none saved."),e.openOverlay({type:"model",items:t,sel:0,current:e.ctx.model,cls:o}),!0):(note(e,e.state().online?"Could not read the model catalog (offline, or the server refused it) — /models retries.":`No API key set, so the model catalog cannot be read — export AEGIS_API_KEY (free key: ${signupUrl("model_blocked")}), then retry /model.`),e.render(),!0)}if("list"===n){const t=await mergedPickerModels(e);return t.length?panel(e,panels.buildModelList(e.ctx.model,t,e.ctx)):note(e,"No pinnable models advertised — /models lists the server's ids."),e.render(),!0}if("-"===n)return e.ctx.model=null,e.saveConfig({model:null,currentModelId:null}),note(e,r?"Model pin cleared. The byok class has no server default — the next turn needs <provider>:<model>, so pin one from /models before sending.":"Model pin cleared — the server will choose."),e.render(),!0;e.ctx.model=n,e.saveConfig({model:n,currentModelId:n}),note(e,`Pinned model: ${n}`);const s=await loadModels(e)||[];return s.length&&!s.some(e=>e.id===n)&¬e(e,r?`"${n}" is not one this machine can relay — a byok id is "<provider>:<model>", and the relay will refuse anything else. /models lists the real ids.`:`"${n}" is not in the AEGIS Cloud catalog — the pool will answer with its own default. /models lists the real ids.`),e.render(),!0}},{name:"radio",hint:"",category:"fun",desc:"Listen to AEGIS FM lo-fi radio",handler:async e=>(note(e,"Opening AEGIS FM lo-fi radio in your browser…"),openUrl(URLS.radio)||note(e,`AEGIS FM: ${URLS.radio}`),e.render(),!0)},{name:"recap",hint:"",category:"session",desc:"Generate a one-line session recap now",handler:async e=>{if(!e.transcript.some(e=>"user"===e.role||"assistant"===e.role))return note(e,"No exchanges yet — send a prompt first."),e.render(),!0;note(e,"Recapping session…"),e.render();const t=await e.withWorking(t=>recapLine(e.transcript,{callModel:(t,n)=>e.ask(t,n).then(e=>e.text),model:e.ctx.model,signal:t}));return null===t?(note(e,"Recap cancelled."),e.render(),!0):(e.ctx.lastRecap={sessionId:e.sessionId,ts:(new Date).toISOString(),text:t},e.saveConfig({lastRecap:e.ctx.lastRecap}),note(e,`Session recap: ${t}`),e.render(),!0)}},{name:"resume",args:["query"],hint:"[query]",category:"session",desc:"Switch to a previous session — /resume <text> searches titles, paths and what you typed",handler:async(e,t)=>{const n=readResumeList(200,200,200);if(!n.length)return note(e,"No previous sessions found — conversations from this host and from AEGIS Desktop both land in ~/.aegiscode/sessions.json"),e.render(),!0;backfillSessionNames(e);const o=String(t&&t.query?t.query:"").trim(),r=require(resolveShared(path.join("client","session-search.js"))).rankSessions(o,n);return o&&!r.length?(note(e,`No session matches “${o}” — /resume with no argument lists them all.`),e.render(),!0):(e.openOverlay({type:"resume",items:r,all:n,query:o,sel:0}),!0)}},{name:"rewind",args:["n"],hint:"[N]",category:"session",desc:"Revert the conversation to a checkpoint",handler:async(e,t)=>{const n=listCheckpoints(e.sessionId);if(!t.n)return n.length?(panel(e,panels.buildRewindList(n,e.ctx)),e.render(),!0):(note(e,"No checkpoints yet — snapshots are taken after each exchange."),e.render(),!0);const o=parseInt(t.n,10);if(Number.isNaN(o)||o<0||o>=n.length)return note(e,`Unknown checkpoint ${t.n}. /rewind shows the list (indices 0..${Math.max(0,n.length-1)}).`),e.render(),!0;snapshotCheckpoint(e.sessionId,e.transcript);const r=loadCheckpoint(e.sessionId,o);if(!r)return note(e,"Checkpoint unreadable — nothing restored."),e.render(),!0;e.transcript.length=0;for(const t of r)e.transcript.push(t);return note(e,`Rewound to checkpoint ${o} (${r.length} messages). /rewind N again to undo.`),e.render(),!0}},{name:"agents",aliases:["sessions"],args:["role","task"],hint:"[role] [task]",category:"session",desc:"Show the agents panel, or run a sub-agent role preset — /agents <role> <task>",handler:async(e,t)=>{const n=(t.role||"").trim().toLowerCase();if(n){const o=(t._rest||"").trim().replace(/^\S+\s*/,"").trim();if(!o)return note(e,`Usage: /agents <role> <task> — roles: ${agentRoles().join(", ")}`),e.render(),!0;if(!AGENT_PRESETS[n])return note(e,`Unknown agent role "${n}". Roles: ${agentRoles().join(", ")}`),e.render(),!0;const r=composeAgentPrompt(n,o);return e.runPrompt?(await e.runPrompt(r),!0):(note(e,`Composed ${n} prompt (${r.length} chars) — run in the TUI to send it.`),e.render(),!0)}return panel(e,panels.buildAgents(e.state(),e.ctx)),e.render(),!0}},{name:"status",aliases:["st"],hint:"",category:"session",desc:"Show account and session status",handler:async e=>(await e.runTool("aegis_status",{}),panel(e,panels.buildStatus(e.state(),Object.assign({},e.ctx,{caps:describe()}))),e.render(),!0)},{name:"teleport",hint:"",category:"session",desc:"Resume a session from aegiscloud.org",handler:async e=>(note(e,"Teleport requires an AEGIS cloud account with sessions. Sign in with `aegis login`, then run aegiscloud.org/teleport."),e.render(),!0)},{name:"theme",aliases:["t"],args:["mode"],hint:"[dark|light]",category:"model",desc:"Change the color theme",handler:async(e,t)=>{const n=(t.mode||"").toLowerCase();if("dark"===n||"light"===n){const t="light"===n?2:1;screens.applyTheme(e.ctx,t)}else await e.showThemePicker();if(e.saveConfig({themeIndex:e.ctx.themeIndex}),note(e,"Theme: "+(e.ctx.light?"light":"dark")),themeContradicts(e.ctx.themeIndex)){const t=caps().background;note(e,`warning: this ${t} terminal is not what "${THEME_TABLE[e.ctx.themeIndex].name}" is drawn for — body text may be unreadable.`),note(e,` /terminal background ${t} pins the palette to this terminal, or /terminal background ${"dark"===t?"light":"dark"} if it reads you wrong.`)}return e.render(),!0}},{name:"terminal",aliases:["tty"],args:["mode","mode2"],hint:"[ascii|unicode|color|no-color|background <dark|light>|probe|star <native|narrow>|width <cols>|auto|status]",category:"model",desc:"Show or override how this terminal is drawn (mark, colour, width)",handler:async(e,t)=>{const n=(t.mode||"").toLowerCase(),o=null!=t.mode2?String(t.mode2).trim():"";if(""===n||"status"===n)return panel(e,panels.buildTerminalCaps(describe(),{pinned:!!caps().pinned})),e.render(),!0;const r=caps(),s={glyphs:r.glyphs,face:r.face,star:r.star,depth:r.depth,vt:r.vt,wideRunes:r.wideRunes,background:r.background,backgroundKnown:r.backgroundKnown,reasons:Object.assign({},r.reasons)};if("auto"===n)return resetCaps(),note(e,"Terminal: auto — capabilities re-probed from the environment."),e.render(),!0;if("probe"===n){const t=await probeTerminalBackground();return screens.applyTheme(e.ctx,e.ctx.themeIndex),note(e,t.known?`Terminal: background ${t.background} (${t.reason}) — /theme auto follows it.`:`Terminal: no answer to the background query (${t.reason}).`),note(e," /terminal background dark|light pins it without asking."),panel(e,panels.buildTerminalCaps(describe(),{pinned:!!caps().pinned})),e.render(),!0}if("ascii"===n||"unicode"===n)s.glyphs="ascii"===n?"ascii":"unicode",s.face="ascii"===n?"edges":"native",s.star="ascii"===n?"narrow":"native",s.reasons&&(s.reasons.glyphs=`/terminal ${n}`);else if("color"===n||"no-color"===n||"nocolor"===n)s.depth="color"===n?24:0,s.reasons&&(s.reasons.depth=`/terminal ${n}`);else{if("star"!==n){if("background"===n||"bg"===n){const t=o.toLowerCase();return["dark","light"].includes(t)?(s.background=t,s.backgroundKnown=!0,s.reasons&&(s.reasons.background=`/terminal background ${t}`),setCaps(Object.assign({},s)),screens.applyTheme(e.ctx,e.ctx.themeIndex),note(e,`Terminal: background pinned to ${t} — /theme auto follows it.`),panel(e,panels.buildTerminalCaps(describe(),{pinned:!!caps().pinned})),e.render(),!0):(note(e,"Usage: /terminal background <dark|light>"),e.render(),!0)}if("width"===n){const t=Number(o);return!Number.isFinite(t)||t<20?(note(e,"Usage: /terminal width <cols> (>= 20)"),e.render(),!0):(setCaps(Object.assign({},s,{cols:Math.round(t)})),note(e,`Terminal: width pinned to ${Math.round(t)} columns.`),panel(e,panels.buildTerminalCaps(describe(),{pinned:!!caps().pinned})),e.render(),!0)}return note(e,"Usage: /terminal [ascii|unicode|color|no-color|background <dark|light>|probe|star <native|narrow>|width <cols>|auto|status]"),e.render(),!0}{const t=o.toLowerCase();if(!["native","narrow"].includes(t))return note(e,"Usage: /terminal star <native|narrow>"),e.render(),!0;s.star=t,s.reasons&&(s.reasons.star=`/terminal star ${t}`)}}return setCaps(s),panel(e,panels.buildTerminalCaps(describe(),{pinned:!!caps().pinned})),note(e,"Terminal updated — the current viewport is redrawn; text already scrolled past keeps its old glyphs."),e.render(),!0}},{name:"version",aliases:["v"],hint:"",category:"session",desc:"Show version",handler:async e=>(note(e,`aegiscode v${VERSION}`),e.render(),!0)},{
|
|
3
|
+
"use strict";const fs=require("node:fs"),os=require("node:os"),path=require("node:path"),{execSync:execSync}=require("node:child_process"),{span:span}=require("./screen.js"),{C:C,BOLD:BOLD,BOLD_OFF:BOLD_OFF,THEME_TABLE:THEME_TABLE,themeContradicts:themeContradicts}=require("./theme.js"),{caps:caps,setCaps:setCaps,resetCaps:resetCaps,describe:describe,probeTerminalBackground:probeTerminalBackground}=require("./caps.js"),panels=require("./panels.js"),overlays=require("./overlays.js"),{updateConfig:updateConfig,loadConfig:loadConfig,loadPermissions:loadPermissions,savePermissions:savePermissions,addPermissionRule:addPermissionRule,DEFAULT_PERMISSIONS:DEFAULT_PERMISSIONS,permissionsPath:permissionsPath,configPath:configPath,aegisDir:aegisDir,setConfirmPosture:setConfirmPosture,setPermissionDefaultMode:setPermissionDefaultMode,confirmPosture:confirmPosture,permissionMode:permissionMode,setPermissionMode:setPermissionMode,PERMISSION_MODES_LOCAL:PERMISSION_MODES_LOCAL,memoryPersistState:memoryPersistState,setMemoryPersist:setMemoryPersist,getModelAutoSync:getModelAutoSync,setModelAutoSync:setModelAutoSync}=require("./config.js"),{auditExposure:auditExposure,repairExposure:repairExposure}=require("./securefs.js"),{copyToClipboard:copyToClipboard}=require("./clipboard.js"),{snapshotCheckpoint:snapshotCheckpoint,listCheckpoints:listCheckpoints,loadCheckpoint:loadCheckpoint}=require("./checkpoint.js"),{signupUrl:signupUrl,goUrl:goUrl}=require("./signup.js"),screens=require("./screens.js"),{summarizeTranscript:summarizeTranscript,recapLine:recapLine}=require("./summarize.js"),{sessionAccounting:sessionAccounting,accountingFromUsage:accountingFromUsage,estimateTokens:estimateTokens}=require("./tokens.js"),{effortRung:effortRung}=require("./engine.js"),{transcriptToMarkdown:transcriptToMarkdown,transcriptToJSON:transcriptToJSON,writeExportFile:writeExportFile,lastAssistantText:lastAssistantText}=require("./export.js"),{detectDevCommand:detectDevCommand,runDevServer:runDevServer}=require("./devrun.js"),{PING_MODES:PING_MODES,DEFAULT_PING_MODE:DEFAULT_PING_MODE,normalizePingMode:normalizePingMode,normalizePingSeconds:normalizePingSeconds,buildPing:buildPing,writePing:writePing}=require("./ping.js"),{addTodo:addTodo,completeTodo:completeTodo,clearTodos:clearTodos,formatTodos:formatTodos,todosFile:todosFile}=require("./todos.js"),{configRows:configRows,formatConfigRows:formatConfigRows,setConfigValue:setConfigValue,resetConfigValue:resetConfigValue,fullValue:fullValue,summarizeValue:summarizeValue,configStore:configStore}=require("./settings.js"),credentials=require("./credentials.js"),cloudsync=require("./cloudsync.js"),{maskKey:maskKey,fmtTokens:fmtTokens,shortCwd:shortCwd}=require("./format.js"),{pickerEntries:pickerEntries}=require("./models.js"),{resolveShared:resolveShared}=require("./sharedpaths.js"),sandboxLib=require(resolveShared(path.join("desktop","lib","local","sandbox.js"))),{createCliEntitlement:createCliEntitlement,paymentView:paymentView,probeFee:probeFee}=require("./entitlement.js"),{openUrl:openUrl,URLS:URLS}=require("./system.js"),sysdiag=require("./sysdiag.js"),{sniffProject:sniffProject,buildAegisMd:buildAegisMd}=require("./init.js"),{upgradeAdvice:upgradeAdvice,latestPublishedVersion:latestPublishedVersion,applyUpgrade:applyUpgrade,installMethod:installMethod}=require("./update.js"),{AGENT_PRESETS:AGENT_PRESETS,agentRoles:agentRoles,composeAgentPrompt:composeAgentPrompt,composeResearchPrompt:composeResearchPrompt,composeDebatePrompt:composeDebatePrompt}=require("./agents.js"),{aggregateSessionUsage:aggregateSessionUsage,pruneSessionHistory:pruneSessionHistory,readResumeList:readResumeList}=require("./history.js"),naming=require("./naming.js"),{sessionStore:sessionStore}=require("./shared.js"),RESUME_SEARCH_LIMIT=200,namingBackfillAttempted=new Set,NAMING_BACKFILL_MAX=25;function backfillSessionNames(e){let t,n=25;try{t=sessionStore.listSessions(aegisDir())}catch{return}for(const o of t){if(n<=0)break;if(!o||!o.id||namingBackfillAttempted.has(o.id))continue;const t=(Array.isArray(o.messages)?o.messages:[]).find(e=>e&&"user"===e.role&&e.content);t&&(!0!==o.named||naming.isSeedTitle(o.title,t.content))&&(namingBackfillAttempted.add(o.id),n-=1,naming.nameSession(sessionStore,aegisDir(),o.id,t.content,{callModel:(t,n)=>e.ask(t,{system:n&&n.system||naming.TITLE_SYSTEM,maxTokens:64,signal:n&&n.signal}).then(e=>e&&e.text||null).catch(()=>null)}).catch(()=>{}))}}let markdownModule=null;try{markdownModule=require("./markdown.js")}catch{markdownModule=null}const VERSION=require("../package.json").version,CATEGORIES=[{id:"session",label:"Session & context"},{id:"workspace",label:"Workspace"},{id:"model",label:"Model & behavior"},{id:"data",label:"Data"},{id:"auth",label:"Auth"},{id:"support",label:"Support"},{id:"fun",label:"Fun"},{id:"aegis",label:"Aegis plugin"},{id:"custom",label:"Custom"}],categoryLabel=e=>(CATEGORIES.find(t=>t.id===e)||{}).label||e,EFFORT_LEVELS=overlays.EFFORT_VALUES,note=(e,t)=>e.push({role:"note",text:t}),panel=(e,t)=>e.push({role:"panel",lines:t}),tip=(e,t)=>e.push({role:"tip",text:t});function askTierNote(e){note(e,"Note: 'ask' rules aren't enforced by any session in this build yet — only allow/deny rules take effect. The rule is saved and will apply once that wiring ships.")}const done=(e,t)=>e.push({role:"done",text:t});function composeMultiFanoutPrompt(e){return["Execute this task as a multi-agent fan-out.","",`Task: ${e}`,"",`Workspace: ${process.cwd()}`,"","Use the task tool to delegate the independent parts to specialist subagents. Delegations run CONCURRENTLY when you emit them as multiple task calls in ONE assistant message, so put independent ones in the same message rather than one per message:","- reconnaissance first (scanner for secrets/unsafe patterns, analyzer for refactor targets),","- then design (architect, or planner when the work is a change to existing code),","- then an implementer subagent to make the change.","Finally review the result (reviewer subagent), fix what it finds, and verify with the repository's real commands.","","Return one consolidated report: what each subagent found, the files you changed, the exact commands you ran and their real output, and anything still blocked. No preamble."].join("\n")}async function multiData(e,t){const n=composeMultiFanoutPrompt(t),o=e&&e.withWorking?t=>e.withWorking(t):e=>e();if(!e||"function"!=typeof e.ask&&"function"!=typeof e.runPrompt)return{error:"No agent loop in this context — the fan-out prompt was composed, not run."};try{if("function"==typeof e.ask){const t=await o(t=>e.ask(n,{signal:t})),r=t&&t.text||"";return t&&t.interrupted&&!r?{cancelled:!0}:r?{result:r,model:t&&t.model||e.ctx&&e.ctx.model||null,provider:"aegis"}:{error:"The multi-agent fan-out returned nothing (the turn failed before it could delegate)."}}return await o(()=>e.runPrompt(n)),{streamed:!0}}catch(e){return{error:`ÆGIS multi failed — ${e&&e.message||e}`}}}async function runMultiCommand(e,t,{yolo:n=!1,title:o="ÆGIS Multi"}={}){n&&(setConfirmPosture(!1),panel(e,panels.buildAutomode(e.state(),e.ctx))),note(e,"Running the multi-agent fan-out — the engine delegates to specialist subagents (headless: this skips aegis-cli's own confirmation step)."),e.render();const r=await multiData(e,t);return r.cancelled?(note(e,"ÆGIS multi cancelled."),e.render(),!0):r.error?(note(e,r.error),panel(e,panels.buildAegisMulti(t,e.ctx)),e.render(),!0):(r.streamed||(panel(e,panels.buildAegisPrint(o,r,e.ctx)),e.render()),!0)}const upgradePanelLines=e=>e.map(e=>[span(C.white,e)]);async function billingPayment(e){if(!e||!e.client)return;let t;try{t=createCliEntitlement({aegis:e.client})}catch{return}const n=e.withWorking?t=>e.withWorking(t):e=>e();try{await n(()=>t.refresh({force:!0}))}catch{}const o=await probeFee();return paymentView(t.current(),{host:"cli",fee:o})}async function loadModels(e){try{return await e.loadModels()||[]}catch{return[]}}async function mergedPickerModels(e){const t=e.ctx&&e.ctx.modelClass||"aegis",n=pickerEntries(await loadModelsFor(e,"aegis",t)).map(e=>({...e,cls:"aegis"})),o=pickerEntries(await loadModelsFor(e,"byok",t)).map(e=>({...e,cls:e.cls||"byok"})),r=pickerEntries(await loadModelsFor(e,"pro",t)).map(e=>({...e,cls:"pro"})),s=[],a=new Set;for(const e of[...n,...o,...r]){const t=String(e&&e.id||"");t&&!a.has(t)&&(a.add(t),s.push(e))}return s}async function loadModelsFor(e,t,n){if("function"==typeof e.listModelsFor)try{return await e.listModelsFor(t)||[]}catch{return[]}if(t!==n||"function"!=typeof e.loadModels)return[];try{return await e.loadModels()||[]}catch{return[]}}const cloudReady=()=>credentials.hasApiKey(),{withByokAdditions:withByokAdditions}=require(resolveShared(path.join("client","byok-catalog.js"))),{withUserModels:withUserModels,addUserModel:addUserModel,removeUserModel:removeUserModel,userModelIdsFor:userModelIdsFor,userModelsPath:userModelsPath}=require(resolveShared(path.join("client","user-models.js"))),catalogClient=require(resolveShared(path.join("client","catalog-client.js"))),{withCatalog:withCatalog}=catalogClient,{discoverModels:discoverVendorModels,endpointFor:vendorEndpointFor,discoverableProviders:discoverableProviders}=require(resolveShared(path.join("client","model-discovery.js"))),modelSync=require(resolveShared(path.join("client","model-sync.js"))),{createModelAutoSync:createModelAutoSync}=require(resolveShared(path.join("client","model-autosync.js")));let autoSyncScheduler=null;function shellAutoSync(e){return autoSyncScheduler||(autoSyncScheduler=createModelAutoSync({getPref:()=>getModelAutoSync(),plan:async t=>{const n=await byokCatalog(e&&e.client);if(!n)return{ok:!1,providers:[],missing:0,stale:0,error:"no provider catalog (offline, or no relay yet)"};const o={};for(const r of modelSync.askableProviders(n,t)){const t=byokKeyForProvider(e,r);t&&(o[r]=t)}return modelSync.plan(n,{keys:o,only:t})},apply:(e,t)=>modelSync.apply(e,{only:t})}),autoSyncScheduler)}async function runAutoModelSync(e){try{return await shellAutoSync(e).runIfDue()}catch{return{ran:!1,reason:"error",added:0,missing:0}}}function byokKeyForProvider(e,t){const n=String(t||"").trim().toLowerCase();if(!n)return"";try{const t=e&&e.settings&&e.settings();if(t&&"function"==typeof t.rawKey&&"function"==typeof e.byokNamespace){const o=t.rawKey(e.byokNamespace(n));if("string"==typeof o&&o.trim())return o.trim()}}catch{}try{const{providerKeyFromEnv:e}=require(resolveShared(path.join("client","env-file.js")));return(e(n)||{}).key||""}catch{return""}}async function discoverProviderModels(e,t,n){try{return await discoverVendorModels(t,{key:n,fetchImpl:e&&e.fetchImpl})}catch(e){return{ok:!1,provider:t,supported:!0,error:e&&e.message||String(e)}}}async function offeredModelIds(e,t,n){const o=await discoverProviderModels(e,t,n);return o&&o.ok&&Array.isArray(o.ids)&&o.ids.length?o.ids:void 0}function splitCommandWords(e){const t=[];let n="",o=null,r=!1;for(const s of String(null==e?"":e))o?s===o?o=null:n+=s:'"'!==s&&"'"!==s?/\s/.test(s)?(n||r)&&(t.push(n),n="",r=!1):(n+=s,r=!0):(o=s,r=!0);return(n||r)&&t.push(n),t}function savedByokBaseURL(e,t){try{const n=e&&e.settings&&e.settings();if(!n||"function"!=typeof n.get||"function"!=typeof e.byokNamespace)return"";const o=n.get(e.byokNamespace(t))||{};return String(o.baseURL||"").trim()}catch{return""}}function addManyUserModels(e,t){let n=0,o=0;const r=[],s=[];for(const a of t)try{addUserModel(e,a).added?n+=1:r.push(a)}catch(e){const i=e&&e.message||String(e);if(/the cap/.test(i)){o=t.length-n-r.length-s.length;break}s.push({id:a,reason:i})}return{added:n,already:r,failed:s,capped:o}}async function byokCatalog(e){if(!e||"function"!=typeof e.byokProviders)return null;try{const t=await e.byokProviders();refreshCatalogInBackground(e);const n=withUserModels(withCatalog(withByokAdditions(t&&t.providers||[])));return n.length?n:null}catch{return null}}function refreshCatalogInBackground(e){try{let t=!0;try{const e=catalogClient.read();t=!e||e.stale}catch{t=!0}if(!t)return null;if("function"!=typeof e.catalog)return null;let n=null;try{const e=catalogClient.read();n=e&&e.data&&e.data.snapshot&&e.data.snapshot.etag||null}catch{n=null}const o=catalogClient.refresh(async({cursor:t,limit:n,etag:o})=>{try{return await e.catalog("models",{cursor:t,limit:n},{etag:o||void 0})}catch(e){if(e&&304===e.status)return{notModified:!0};throw e}},{etag:n});return o&&"function"==typeof o.catch&&o.catch(()=>{}),o}catch{return null}}function findByokProvider(e,t){const n=String(t||"").trim().toLowerCase();if(!e)return{provider:null,exact:!1};const o=e.find(e=>e.id===n);if(o)return{provider:o,exact:!0};const r=e.filter(e=>[e.id,e.label,...e.aliases||[]].filter(Boolean).some(e=>String(e).toLowerCase()===n));return 1===r.length?{provider:r[0],exact:!1}:r.length>1?{ambiguous:r.map(e=>e.id)}:{provider:null,exact:!1}}function byokProviderLines(e){const t=[];for(const n of e){const e=n.configured?span(C.green,"set"+(n.masked?` (${n.masked})`:"")):span(C.gray,"not set"),o=[span(C.gold+BOLD,` ${n.id}`)];n.label&&o.push(span(C.gray,` — ${n.label}`)),o.push(span(""," "),e),t.push(o);const r=(n.models||[]).map(e=>"string"==typeof e?e:e&&e.id).filter(Boolean);r.length&&t.push([span(C.gray,` models: ${r.join(", ")}`)]),n.key_prefix&&t.push([span(C.gray,` key starts with ${n.key_prefix}`)]),n.key_url&&t.push([span(C.gray,` ${n.key_url}`)])}return t}function keyPanelLines(e,t="AEGIS account key"){const n=e.keyStatus(),o=[[span(C.gold+BOLD,t),span(BOLD_OFF,"")],[span(C.gray,"─".repeat(34))],[span(n.configured?C.green:C.coral," "+(n.configured?"✔":"⚠")),span(C.white," key: "),span(n.configured?C.white:C.gray,n.configured?maskKey(n.key):"not set"),span(C.gray,` (${credentials.sourceLabel(n.source)})`)],[span(C.gray,` stored in: ${n.path}${n.fileMode?` ${n.fileMode}`:""}`)]];return n.verifiedAt&&o.push([span(C.gray,` verified: ${n.verifiedAt}`)]),n.account&&(n.account.plan||n.account.email)&&o.push([span(C.gray," account: "),span(C.white,[n.account.plan,n.account.email].filter(Boolean).join(" · "))]),o.push([span(C.gray," memory: "),span(n.memoryToken?C.green:C.gray,n.memoryToken?"token held (cloud sync ready)":"no token yet")]),n.configured||(o.push([span(C.gray,"")]),o.push([span(C.white," Set one with /key <api_key>, or press Enter on /key to paste it.")]),o.push([span(C.gray,` Free key: ${signupUrl("key_status")}`)])),n.legacyPlaintext&&(o.push([span(C.gray,"")]),o.push([span(C.coral," ⚠ a plaintext copy of the key is still in config.json (another AEGIS CLI wrote it).")]),o.push([span(C.gray," Re-save with /key <api_key> and delete that block when convenient.")])),o}async function applyAccountKey(e,t,{label:n="AEGIS API key"}={}){let o=String(t||"").trim();if(o||(o=await e.readSecret(`${n} (kept off screen, Enter to cancel): `)),!o)return note(e,"no key given — /key <api_key> takes it inline, or press Enter on a bare /key to paste it"),{ok:!1};const r=await e.setApiKey(o);if(!r.ok)return note(e,r.message||"that key could not be saved"),r;if(r.error)return note(e,`saved, but the account check failed: ${r.error.message}`),note(e,"the key is stored — /key status shows it; re-run /key <api_key> if it was mistyped"),r;const s=r.account&&(r.account.email||r.account.plan)||null;done(e,`AEGIS key saved to ${r.path}${s?` — signed in as ${s}`:" and verified"}`);try{const t=pickerEntries(await loadModels(e)).length;t&¬e(e,`${t} pinnable model${1===t?"":"s"} available — /model to pin one`)}catch{}return r}function fmtQuotaTokens(e){const t=Number(e);return Number.isFinite(t)?t>=1e6?`${(t/1e6).toFixed(t%1e6==0?0:1)}M`:t>=1e4?`${Math.round(t/1e3)}k`:fmtTokens(t):"?"}function memoryGate(e){if(e&&"function"==typeof e.cloudSyncState)try{return e.cloudSyncState()}catch{}return{enabled:!e||"function"!=typeof e.cloudSyncEnabled||!0===e.cloudSyncEnabled(),source:"default"}}function setMemoryGate(e,t){if(e&&"function"==typeof e.setCloudSync)return e.setCloudSync(t);try{return setMemoryPersist(t)}catch{return null}}function memoryStatusLines(e){const t=memoryGate(e),n=cloudsync.status(),o=n.quota,r=o&&null!=o.used?fmtQuotaTokens(o.used):null,s=o&&null!=o.limit?fmtQuotaTokens(o.limit):null,a="legacy"===t.source?" (kept from your old cloudSync setting)":"default"===t.source?" (default)":"",i=[[span(C.white+BOLD,"Cloud sync"),span(BOLD_OFF,"")],[span(C.gray,"─".repeat(34))],[span(C.white," "+(t.enabled?"on":"off")),span(C.gray,`${a} · ${t.enabled?"each session is stored so an interrupted turn can be resumed":"nothing new is stored"}`)]];return s?i.push([span(C.gray," quota: "),span(C.white,`${r} of ${s} tokens synced`),span(C.gray," (aegis1 charges writes; reads are always served)")]):i.push([span(C.gray," quota: not reported yet — /sync now asks the server for the current numbers")]),n.overQuota&&(i.push([span(C.coral," writes: paused — the plan’s ceiling is reached, so new memory is not being stored")]),i.push([span(C.green," reads: still work — everything already stored stays readable (/aegis-recall <topic>)")]),i.push([span(C.gray,` free room at ${goUrl("upgrade","cloud_quota")}`)]),i.push([span(C.gray," or /cloud memory off to stop trying")])),t.enabled&&n.pending>0&&i.push([span(C.gray,` pending: ${n.pending} session(s) waiting to sync`)]),i.push([span(C.gray," /cloud memory on | off · /sync now pushes once by hand")]),i}async function runCloudSync(e,t={}){if(!e.client.apiKey)return note(e,`no key — ${credentials.HOW_TO_SET}`),null;const n=await e.withWorking(()=>cloudsync.syncNow(e.client,t)),o=n.push&&n.push.pushed||[],r=[...n.push&&n.push.failed||[],...n.pull&&n.pull.failed||[]],s=n.pull&&n.pull.imported||0;o.length?done(e,`pushed ${o.length} session${1===o.length?"":"s"} (${o[0].messages} messages in the first)`):n.push&&n.push.skipped&&n.push.skipped.length?note(e,`${n.push.skipped.length} session(s) had nothing to send`):note(e,"nothing to push — every local session is already in the cloud"),s?done(e,`pulled ${s} record${1===s?"":"s"} into the local store — /resume lists them`):n.pull&&n.pull.ok&¬e(e,`cloud has ${n.pull.remote||0} session(s); nothing newer locally`);for(const t of r)note(e,`${"quota"===t.kind?"quota":"failed"}: ${t.message}`),t.hint&¬e(e,t.hint);return n}const hooksLib=require(resolveShared(path.join("client","hooks.js")));function loadCredits(){try{return require(resolveShared(path.join("client","credits.js"))).creditsFromDisk()}catch(e){return{program:{licence:"AGPL-3.0-or-later",name:"GNU Affero General Public License v3.0 or later",url:"https://www.gnu.org/licenses/agpl-3.0.html",source:"https://github.com/aegisinfo/aegiscode-plugin",copyright:"Copyright (C) 2026 Niklas Borneklint",notice:null},documents:[],code:[],fonts:[],missing:["licensing","vendor","fonts"],error:String(e&&e.message||e)}}}function readHooks(){return hooksLib.readHookConfig()}function hookStats(e){return hooksLib.hookStats(e)}const skillsLib=require(resolveShared(path.join("client","skills.js")));function scanSkills(){const{entries:e}=skillsLib.scan();return e.map(e=>({source:e.scope,name:e.name,namespace:null,description:e.description,path:e.path,warning:e.warning,content:readSkillText(e.path)}))}function readSkillText(e){try{return fs.readFileSync(e,"utf8")}catch{return""}}const COMMANDS=[{name:"run",hint:"",category:"workspace",desc:"Launch and drive this project's app to see a change working",handler:async e=>{const t=detectDevCommand(process.cwd());if(!t)return note(e,"No dev command detected (no package.json scripts, go.mod, Cargo.toml or Makefile). Try /init first."),e.render(),!0;note(e,`Running ${t} in ${shortCwd()} — output streams below, Esc stops it.`);const n=runDevServer(t,{cwd:process.cwd(),onLine:t=>e.push({role:"note",text:` ${t}`})});return n.label||(n.label=t),e.openStream(n),n.done.then(({code:o,stopped:r})=>{e.closeStream(n),done(e,r?`${t} stopped`:`${t} exited (code ${o})`),e.render()}),e.render(),!0}},{name:"schedule",hint:"[task | status | stop | report | list]",category:"session",desc:"Set a timer that drains the work queue — queue a task and arm it",handler:async(e,t)=>{const n=e.ctx&&e.ctx.cwd||process.cwd(),o=(t._rest||"").trim(),r=o.toLowerCase(),{runQueueCommand:s}=require("./autonomous.js"),a=async e=>{let t="",n="";const o={write:e=>(t+=String(e),!0)},r={write:e=>(n+=String(e),!0)};let a;try{a=await s(e[0],e.slice(1),{stdout:o,stderr:r})}catch(e){return{code:1,out:t,err:n+String(e&&e.message?e.message:e)}}return{code:a,out:t,err:n}},i=t=>{const n=String(t.out).split("\n").filter(e=>""!==e);for(const t of n)note(e,t);for(const n of String(t.err).split("\n").filter(e=>""!==e))note(e,n);return t.code};if(!o)return i(await a(["timer","status"])),note(e,""),note(e,"/schedule <task> queue the task and arm the timer that drains it"),note(e,"/schedule status is the timer written, and is it actually armed?"),note(e,"/schedule report what finished since you last looked"),note(e,"/schedule list what is still queued"),note(e,"/schedule stop remove the timer (queued work stays queued)"),note(e,"Every minute the timer fires `autonomous tick`: it drains when the machine"),note(e,"is idle enough, and skips otherwise. Ground truth also on the command line:"),note(e," aegiscode autonomous timer status"),e.render(),!0;if("status"===r){const t=await a(["timer","status"]);return i(t),0!==t.code&¬e(e,"The timer could not be inspected — see the message above."),e.render(),!0}if("stop"===r||"remove"===r||"off"===r)return i(await a(["timer","remove"])),note(e,"Queued work is untouched — it stays in the queue until something drains it."),e.render(),!0;if("report"===r||"list"===r)return i(await a(["report"===r?"report":"list"])),e.render(),!0;if("run"===r||"tick"===r)return i(await a(["tick","--commit","--max-load","0"])),e.render(),!0;const l=await a(["add",o,"--cwd",n,"--commit"]);if(0!==l.code)return i(l),note(e,"Nothing was queued, so the timer was left alone."),e.render(),!0;i(l);const d=await a(["timer","install"]);return i(d),0===d.code?(note(e,""),note(e,"The timer will drain this when the machine is idle enough. Come back with"),note(e,"/schedule report — it reads the runs log, so it answers in a later turn or"),note(e,"a different session, and it does not depend on this conversation.")):(note(e,""),note(e,"The task IS queued, but the timer did not arm. Until it does, nothing"),note(e,"will drain it on its own. Run aegiscode autonomous timer install to see why.")),e.render(),!0}},{name:"build",aliases:["forge"],args:["task"],hint:"<description>",category:"workspace",desc:"Build an app with the agent loop — /build <what to build>",handler:async(e,t)=>{const n=(t._rest||t.task||"").trim();return n?(note(e,"⬡ AEGIS BUILD"),note(e,`Task: ${n}`),e.render(),await e.runPrompt(`Build the following, creating every file it needs and running the build to verify it works: ${n}`),!0):(note(e,"Usage: /build <what to build>"),note(e,"Example: /build a REST API for a todo app"),e.render(),!0)}},{name:"cd",args:["path"],hint:"<path>",category:"workspace",desc:"Move this session to a new working directory",handler:async(e,t)=>{const n=t.path||(t._rest||"").trim();if(!n)return note(e,"Usage: /cd <path>"),e.render(),!0;try{process.chdir(n),e.ctx.cwd=process.cwd(),updateConfig({lastCwd:process.cwd()}),note(e,`Changed directory to ${process.cwd()}`)}catch(t){note(e,`/cd: ${t.message}`)}return e.render(),!0}},{name:"copy",aliases:["cp"],args:["n"],hint:"[N]",category:"data",desc:"Copy the last response to the clipboard",handler:async(e,t)=>{const n=parseInt(t.n||"1",10)||1,o=lastAssistantText(e.transcript,n);if(!o)return note(e,"Nothing to copy yet."),e.render(),!0;const r=copyToClipboard(o);return r.ok?note(e,r.via.startsWith("tool:")?`Copied the last response to the clipboard (${r.via.split(":")[1]}).`:`No clipboard tool found — response saved to ${r.path}`):note(e,"Clipboard unavailable; nothing copied."),e.render(),!0}},{name:"clear",aliases:["cls"],hint:"",category:"session",desc:"Start a new session with empty context",handler:async e=>(e.transcript.length=0,pruneSessionHistory(e.sessionId),"function"==typeof e.clearConversationMemory&&e.clearConversationMemory(),note(e,"Session cleared — transcript empty."),e.render(),!0)},{name:"undo",args:["which"],hint:"[list|<id>]",category:"session",desc:"Reverse a file edit the agent made this conversation",handler:async(e,t)=>{const n=(t._rest||"").trim();if("list"===n){const t="function"==typeof e.listUndoable?e.listUndoable():[];if(!t.length)return note(e,"Nothing to undo in this conversation."),e.render(),!0;note(e,`${t.length} undoable mutation${1===t.length?"":"s"}, newest first:`);for(const n of t){const t=Math.max(0,Math.round((Date.now()-n.at)/1e3));note(e,` ${n.id.slice(0,8)} ${n.tool} ${path.relative(process.cwd(),n.path)||n.path} (${t}s ago)`)}return note(e,"Undo one with: /undo <id> (first 8 characters are enough), or /undo for the most recent."),e.render(),!0}if("function"!=typeof e.undoMutation)return note(e,"Undo is not available on this engine."),e.render(),!0;let o=n||void 0;if(o){const t=("function"==typeof e.listUndoable?e.listUndoable():[]).find(e=>e.id===o||e.id.startsWith(o));if(!t)return note(e,`No undo record starts with "${o}". Try /undo list.`),e.render(),!0;o=t.id}const r=e.undoMutation(o);return note(e,r.ok?`Undone — ${path.relative(process.cwd(),r.path)||r.path} ${"deleted"===r.restored?"deleted (it was a new file)":"restored to its prior content"}.`:r.error),e.render(),!0}},{name:"compact",hint:"",category:"session",desc:"Compact the conversation history",handler:async e=>{if(!e.transcript.some(e=>"user"===e.role||"assistant"===e.role))return note(e,"Nothing to compact yet."),e.render(),!0;note(e,"Compacting conversation history…"),e.render();const t=await e.withWorking(t=>summarizeTranscript(e.transcript,{callModel:(t,n)=>e.ask(t,n).then(e=>e.text),model:e.ctx.model,signal:t}));return null===t?(note(e,"Compaction cancelled."),e.render(),!0):(e.transcript.length=0,note(e,"Compacted. Earlier context summarized into the message below."),e.transcript.push({role:"user",text:t}),e.render(),!0)}},{name:"cost",hint:"",category:"data",desc:"Show the cost of the current session",handler:async e=>{const t=aggregateSessionUsage(e.sessionId),n=t.entries?accountingFromUsage(t.usage,e.ctx.model,{exchanges:t.entries,real:t.real,costUsd:t.real&&t.costUsd?t.costUsd:void 0}):sessionAccounting(e.transcript,e.ctx.model);return panel(e,panels.buildCost({...e.state(),contextWindow:n.contextWindow,costEur:n.cost},e.ctx)),e.render(),!0}},{name:"context",hint:"",category:"session",desc:"Show context usage for the current session",handler:async e=>{const t=sessionAccounting(e.transcript,e.ctx.model);return panel(e,panels.buildContext({...e.state(),contextWindow:t.contextWindow},e.ctx)),e.render(),!0}},{name:"ping",args:["mode","seconds"],hint:"[off|bell|notify|both] [seconds] | test",category:"model",desc:"Alert me when a long turn finishes, if I am looking elsewhere",handler:async(e,t)=>{const n=loadConfig(),o=(t._rest||"").trim().split(/\s+/).filter(Boolean),r=(o[0]||"").toLowerCase(),s=normalizePingMode(n.ping),a=normalizePingSeconds(n.pingMinSeconds);if(!r)return note(e,`[ping] ${s} — a turn longer than ${a}s raises a terminal notification.`),note(e,` /ping ${PING_MODES.filter(e=>e!==s).join("|")} ${"off"===s?"turn it back on":"change the channel"}`),note(e," /ping <mode> <seconds> move the threshold (0 pings every turn)"),note(e," /ping test fire one now, to check this terminal supports it"),e.render(),!0;if("test"===r){const t=buildPing({mode:"off"===s?DEFAULT_PING_MODE:s}),n=!!process.stdout.isTTY&&writePing(process.stdout,t);return note(e,n?"[ping] sent one just now. If nothing appeared or sounded, this terminal implements neither OSC 9 nor OSC 777 — /ping bell is the fallback.":"[ping] nothing sent: stdout is not a TTY (a piped or headless run has no one to notify)."),e.render(),!0}if(!PING_MODES.includes(r))return note(e,`Unknown ping mode "${o[0]}". Use ${PING_MODES.join(", ")}.`),e.render(),!0;const i={ping:r};if(null!=o[1]){const t=Number(o[1]);if(!Number.isFinite(t)||t<0)return note(e,`"${o[1]}" is not a number of seconds. Use /ping ${r} 30.`),e.render(),!0;i.pingMinSeconds=normalizePingSeconds(t)}return updateConfig(i),"off"===r?note(e,"[ping] off — no notice will be raised, and nothing is reported as sent."):(note(e,`[ping] ${r} — turns longer than ${normalizePingSeconds(i.pingMinSeconds??n.pingMinSeconds)}s will notify you.`),note(e," Escape never pings (you were watching), and neither does a piped or headless run.")),e.render(),!0}},{name:"todos",aliases:["todo"],args:["sub","text"],hint:"[add <text> | done <n|text> | clear]",category:"session",desc:"A session todo list that survives compaction",handler:async(e,t)=>{const n=(t.sub||"").toLowerCase(),o=(t._rest||"").trim().replace(/^\S+\s*/,"");if(!n)return panel(e,formatTodos()),note(e,` ${todosFile()}`),note(e," /todos add <text> · /todos done <n|text> · /todos clear"),e.render(),!0;if("add"===n){const t=addTodo(o);return t.error?(note(e,t.error),e.render(),!0):(panel(e,formatTodos(t.list)),e.render(),!0)}if("done"===n||"do"===n){const t=completeTodo(o);return t.error?(note(e,t.error),e.render(),!0):(note(e,`[todos] "${t.item.text}" is now ${t.item.done?"done":"open"}.`),panel(e,formatTodos(t.list)),e.render(),!0)}return"clear"===n?(clearTodos(),note(e,"[todos] cleared."),e.render(),!0):(note(e,`Unknown /todos subcommand "${t.sub}". Use add, done or clear.`),e.render(),!0)}},{name:"config",args:["key","value"],hint:"[<key> | <key> <value> | reset <key>]",category:"session",desc:"Show or change any setting, and say which store holds it",handler:async(e,t)=>{const n=(t._rest||"").trim(),o=(t.key||"").trim(),r=n.replace(/^\S+\s*/,"");if(!o)return panel(e,formatConfigRows(configRows())),note(e," /config <key> show one value in full"),note(e," /config <key> <value> set it (true/false/null, numbers, JSON, or text)"),note(e," /config reset <key> back to the shipped value"),note(e,' "shared" keys live in the store AEGIS Desktop writes too; "host" keys are this shell\'s own.'),e.render(),!0;if("reset"===o){const t=resetConfigValue(r);return t.error?(note(e,t.error),e.render(),!0):(note(e,`[config] ${t.key} reset to ${summarizeValue(t.value)} (${t.store}).`),e.render(),!0)}if(!r){const t=loadConfig();return Object.prototype.hasOwnProperty.call(t,o)?(note(e,`${o} (${configStore(o)}):`),e.push({role:"panel",lines:fullValue(t[o]).split("\n").map(e=>` ${e}`)}),e.render(),!0):(note(e,`unknown config key "${o}" — run /config to list the keys`),e.render(),!0)}const s=setConfigValue(o,r);return s.error?(note(e,s.error),e.render(),!0):(note(e,`[config] ${s.key} = ${summarizeValue(s.value)} (${s.store}).`),["model","currentModelId","modelClass","effort","themeIndex","vim"].includes(s.key)&&("effort"===s.key&&(e.ctx.effort=effortRung(s.value),e.ctx.effort!==String(s.value).toLowerCase()&&(e.saveConfig({effort:e.ctx.effort}),note(e,` "${s.value}" is not a level this build sends — recorded as ${e.ctx.effort}.`))),note(e,` This takes effect on the next turn; /${"currentModelId"===s.key?"model":s.key} shows the live session value.`)),e.render(),!0)}},{name:"effort",args:["level"],hint:"[low|medium|high]",category:"model",desc:"Set the token budget the pool sizes each turn from",handler:async(e,t)=>{const n=(t.level||"").toLowerCase();if(n&&"auto"!==n&&!EFFORT_LEVELS.includes(n))return note(e,`Unknown effort level "${t.level}". Use ${EFFORT_LEVELS.join(", ")}.`),e.render(),!0;if(!n)return e.openOverlay({type:"effort",sel:Math.max(0,EFFORT_LEVELS.indexOf(e.ctx.effort||"high"))}),!0;const o="auto"===n?"high":n;return e.ctx.effort=o,e.saveConfig({effort:o}),note(e,"auto"===n?"effort: auto is retired — high is the default, and it is what this session now sends":`Effort level: ${o} — the pool sizes this turn's token budget from it`),e.render(),!0}},{name:"sandbox",args:["sub","value"],hint:"[on|off|read-only|workspace-write | network <open|restricted> | grant <path> | block <path> | clear]",category:"workspace",desc:"Confine shell commands to a kernel-enforced policy (paths — for command rules see /permissions)",handler:async(e,t)=>{const n=e.settings&&e.settings(),o=n&&"function"==typeof n.getSandboxPolicy,r=n&&"function"==typeof n.setSandboxPolicy,s=()=>o?n.getSandboxPolicy():null,a=t=>r?n.setSandboxPolicy(t):(e.push({role:"error",text:"this client has no settings store to hold a sandbox policy."}),null),i=()=>{sandboxLib.supported()||note(e,`WARNING: no sandbox mechanism is implemented for ${process.platform} yet — this policy will NOT be enforced; commands run with full user access regardless of mode.`)},l=process.cwd(),d=(t.sub||"").toLowerCase(),c=t.value;if(!d){const t=s(),n=sandboxLib.detect({appDir:void 0});if(t){note(e,sandboxLib.describe(n,t));const o=t.fileSystem&&t.fileSystem.entries||[],r=t.fileSystem&&t.fileSystem.denies||[];for(const t of o){const n=t&&t.path;n&&"path"===n.type&¬e(e,` ${t.access.padEnd(5)} ${n.path}`)}for(const t of r)note(e,` deny ${t.path}`);note(e," network restricted is skipped for local models — a local turn cannot reach ollama from a fresh netns.")}else note(e,"sandbox: not configured — shell commands run with your full user access."),note(e,`Turn it on with: /sandbox on (or pick a mode: ${sandboxLib.MODES.filter(e=>"off"!==e).join(", ")})`);return e.render(),!0}if("clear"===d||"off"===d)return a(null),note(e,"off"===d?"sandbox: off — policy cleared; shell commands run unconfined.":"sandbox: policy cleared — shell commands run unconfined."),e.render(),!0;if("on"===d)return a(sandboxLib.defaultPolicy(l)),note(e,`sandbox: workspace-write in ${shortCwd()} — check the shell row says "via bwrap" when a command runs.`),i(),e.render(),!0;const u=s();if(!u)return note(e,"No sandbox policy is set — run /sandbox on first (or /sandbox <mode>)."),e.render(),!0;if(sandboxLib.MODES.includes(d)&&"off"!==d)return a({...u,mode:d}),note(e,`sandbox mode: ${d}`),i(),e.render(),!0;if("network"===d){const t=String(c||"").toLowerCase();return"open"!==t&&"restricted"!==t?(note(e,"usage: /sandbox network <open|restricted>"),e.render(),!0):(a({...u,network:t}),note(e,`sandbox network: ${t}${"restricted"===t?" — note that local models still run with the network open, since a fresh netns cannot reach the ollama daemon":""}`),e.render(),!0)}if("allow"===d||"deny"===d||"grant"===d||"block"===d){const t="deny"===d||"block"===d,n=String(c||"").trim();if(!n)return note(e,`usage: /sandbox ${d} <path>`),e.render(),!0;const o=path.resolve(n);if(t){let t=null;try{t=fs.statSync(o)}catch{return note(e,`No such path: ${o}`),e.render(),!0}if(!t.isDirectory())return note(e,`A deny must name a directory, not a file: ${o}`),e.render(),!0}const r=Array.isArray(u.fileSystem&&u.fileSystem.entries)?u.fileSystem.entries.slice():[],s=Array.isArray(u.fileSystem&&u.fileSystem.denies)?u.fileSystem.denies.slice():[];return t?s.push({path:o}):r.push({path:{type:"path",path:o},access:"write",missingPathBehavior:"skip"}),a({...u,fileSystem:{entries:r,denies:s}}),note(e,t?`sandbox: denying ${o} — emptied inside the sandbox, unchanged outside it`:`sandbox: write granted on ${o}`),e.render(),!0}return note(e,`Unknown /sandbox argument "${t.sub}". Try: on, off, ${sandboxLib.MODES.filter(e=>"off"!==e).join(", ")}, network, grant, block, clear`),e.render(),!0}},{name:"exit",aliases:["quit"],hint:"",category:"session",desc:"Exit the CLI",handler:async()=>!1},{name:"export",args:["format","target"],hint:"[markdown|json] [file|clipboard]",category:"data",desc:"Export the current conversation to a file or clipboard",handler:async(e,t)=>{const n=(t.format||"markdown").toLowerCase(),o=(t.target||"file").toLowerCase();if(!["markdown","md","json"].includes(n)||!["file","clipboard"].includes(o))return note(e,"Usage: /export [markdown|json] [file|clipboard]"),e.render(),!0;const r="json"===n,s=r?transcriptToJSON(e.transcript):transcriptToMarkdown(e.transcript);if("clipboard"===o){const t=copyToClipboard(s);note(e,t.ok?`Exported conversation (${r?"json":"markdown"}) to the clipboard.`:"Clipboard unavailable; nothing copied.")}else try{const t=writeExportFile(s,r?"json":"md",e.ctx.cwd||process.cwd());note(e,`Exported conversation to ${t}`)}catch(t){note(e,`/export: ${t.message}`)}return e.render(),!0}},{name:"help",aliases:["?","h"],hint:"",category:"support",desc:"Show help",handler:async e=>(panel(e,panels.buildHelp(visibleCommands(),e.ctx)),e.render(),!0)},{name:"init",args:["file"],hint:"[file]",category:"workspace",desc:"Create an AEGIS.md file in the project",handler:async(e,t)=>{const n=(t.file||"AEGIS.md").trim(),o=e.ctx.cwd||process.cwd(),r=path.resolve(o,n),s=o.endsWith(path.sep)?o:o+path.sep;if(r!==o&&!r.startsWith(s))return note(e,`/init: refusing to write outside the project directory (${r}).`),e.render(),!0;if(fs.existsSync(r))return note(e,`${n} already exists — not overwriting.`),e.render(),!0;const a=sniffProject(o);try{fs.writeFileSync(r,buildAegisMd(a)+"\n")}catch(t){return note(e,`/init: ${t.message}`),e.render(),!0}return note(e,`Created ${r} (${a.lang})`),fs.existsSync(path.join(o,"node_modules"))&&!fs.existsSync(path.join(o,".gitignore"))&&tip(e,'Add "node_modules/" to a .gitignore before committing.'),e.render(),!0}},{name:"login",aliases:["signin"],args:["value"],hint:"[<api_key>]",category:"auth",desc:"Save your AEGIS API key",handler:async(e,t)=>{const n=String(t.value||t._rest||"").trim();return await applyAccountKey(e,n,{label:"AEGIS API key"}),e.render(),!0}},{name:"logout",args:[],hint:"",category:"auth",desc:"Remove the saved AEGIS API key",handler:async e=>{const t=e.forgetApiKey();return done(e,t.cleared?`key removed from ${t.path}`:"there was no saved key to remove"),credentials.legacyKeyOnDisk()&¬e(e,`a copy is still in ${configPath()} (another AEGIS CLI wrote it) — delete its "aegiscloud" block too`),e.render(),!0}},{name:"model",aliases:["m"],args:["sub"],hint:"[id|-]",category:"model",desc:'Switch AI model — pin an id ("-" clears it)',handler:async(e,t)=>{const n=(t.sub||"").trim(),o=e.ctx&&e.ctx.modelClass||"aegis",r="byok"===o;if(!n){note(e,`model: ${e.ctx.model||"server default"}`);const t=await mergedPickerModels(e);return t.length?(t.some(e=>"aegis"===e.cls||"byok"===e.cls)||note(e,e.state().online?"Could not read the AEGIS Cloud catalog (offline, or the server refused it) — showing Claude Code Pro only; /models retries.":`No AEGIS API key set, so the AEGIS Cloud catalog cannot be read (free key: ${signupUrl("model_blocked")}) — showing Claude Code Pro only.`),e.ctx.model&&!t.some(t=>t.id===e.ctx.model)&¬e(e,r?`pinned model "${e.ctx.model}" is not one this machine can relay — pick from the list below.`:`pinned model "${e.ctx.model}" is not in the catalog — the pool will answer with its own default; pick one below.`),note(e,"/model <id> pins one for this session; picking a direct-provider row prompts for its key if this machine has none saved."),e.openOverlay({type:"model",items:t,sel:0,current:e.ctx.model,cls:o}),!0):(note(e,e.state().online?"Could not read the model catalog (offline, or the server refused it) — /models retries.":`No API key set, so the model catalog cannot be read — export AEGIS_API_KEY (free key: ${signupUrl("model_blocked")}), then retry /model.`),e.render(),!0)}if("list"===n){const t=await mergedPickerModels(e);return t.length?panel(e,panels.buildModelList(e.ctx.model,t,e.ctx)):note(e,"No pinnable models advertised — /models lists the server's ids."),e.render(),!0}if("-"===n)return e.ctx.model=null,e.saveConfig({model:null,currentModelId:null}),note(e,r?"Model pin cleared. The byok class has no server default — the next turn needs <provider>:<model>, so pin one from /models before sending.":"Model pin cleared — the server will choose."),e.render(),!0;e.ctx.model=n,e.saveConfig({model:n,currentModelId:n}),note(e,`Pinned model: ${n}`);const s=await loadModels(e)||[];return s.length&&!s.some(e=>e.id===n)&¬e(e,r?`"${n}" is not one this machine can relay — a byok id is "<provider>:<model>", and the relay will refuse anything else. /models lists the real ids.`:`"${n}" is not in the AEGIS Cloud catalog — the pool will answer with its own default. /models lists the real ids.`),e.render(),!0}},{name:"radio",hint:"",category:"fun",desc:"Listen to AEGIS FM lo-fi radio",handler:async e=>(note(e,"Opening AEGIS FM lo-fi radio in your browser…"),openUrl(URLS.radio)||note(e,`AEGIS FM: ${URLS.radio}`),e.render(),!0)},{name:"recap",hint:"",category:"session",desc:"Generate a one-line session recap now",handler:async e=>{if(!e.transcript.some(e=>"user"===e.role||"assistant"===e.role))return note(e,"No exchanges yet — send a prompt first."),e.render(),!0;note(e,"Recapping session…"),e.render();const t=await e.withWorking(t=>recapLine(e.transcript,{callModel:(t,n)=>e.ask(t,n).then(e=>e.text),model:e.ctx.model,signal:t}));return null===t?(note(e,"Recap cancelled."),e.render(),!0):(e.ctx.lastRecap={sessionId:e.sessionId,ts:(new Date).toISOString(),text:t},e.saveConfig({lastRecap:e.ctx.lastRecap}),note(e,`Session recap: ${t}`),e.render(),!0)}},{name:"resume",args:["query"],hint:"[query]",category:"session",desc:"Switch to a previous session — /resume <text> searches titles, paths and what you typed",handler:async(e,t)=>{const n=readResumeList(200,200,200);if(!n.length)return note(e,"No previous sessions found — conversations from this host and from AEGIS Desktop both land in ~/.aegiscode/sessions.json"),e.render(),!0;backfillSessionNames(e);const o=String(t&&t.query?t.query:"").trim(),r=require(resolveShared(path.join("client","session-search.js"))).rankSessions(o,n);return o&&!r.length?(note(e,`No session matches “${o}” — /resume with no argument lists them all.`),e.render(),!0):(e.openOverlay({type:"resume",items:r,all:n,query:o,sel:0}),!0)}},{name:"rewind",args:["n"],hint:"[N]",category:"session",desc:"Revert the conversation to a checkpoint",handler:async(e,t)=>{const n=listCheckpoints(e.sessionId);if(!t.n)return n.length?(panel(e,panels.buildRewindList(n,e.ctx)),e.render(),!0):(note(e,"No checkpoints yet — snapshots are taken after each exchange."),e.render(),!0);const o=parseInt(t.n,10);if(Number.isNaN(o)||o<0||o>=n.length)return note(e,`Unknown checkpoint ${t.n}. /rewind shows the list (indices 0..${Math.max(0,n.length-1)}).`),e.render(),!0;snapshotCheckpoint(e.sessionId,e.transcript);const r=loadCheckpoint(e.sessionId,o);if(!r)return note(e,"Checkpoint unreadable — nothing restored."),e.render(),!0;e.transcript.length=0;for(const t of r)e.transcript.push(t);return note(e,`Rewound to checkpoint ${o} (${r.length} messages). /rewind N again to undo.`),e.render(),!0}},{name:"agents",aliases:["sessions"],args:["role","task"],hint:"[role] [task]",category:"session",desc:"Show the agents panel, or run a sub-agent role preset — /agents <role> <task>",handler:async(e,t)=>{const n=(t.role||"").trim().toLowerCase();if(n){const o=(t._rest||"").trim().replace(/^\S+\s*/,"").trim();if(!o)return note(e,`Usage: /agents <role> <task> — roles: ${agentRoles().join(", ")}`),e.render(),!0;if(!AGENT_PRESETS[n])return note(e,`Unknown agent role "${n}". Roles: ${agentRoles().join(", ")}`),e.render(),!0;const r=composeAgentPrompt(n,o);return e.runPrompt?(await e.runPrompt(r),!0):(note(e,`Composed ${n} prompt (${r.length} chars) — run in the TUI to send it.`),e.render(),!0)}return panel(e,panels.buildAgents(e.state(),e.ctx)),e.render(),!0}},{name:"status",aliases:["st"],hint:"",category:"session",desc:"Show account and session status",handler:async e=>(await e.runTool("aegis_status",{}),panel(e,panels.buildStatus(e.state(),Object.assign({},e.ctx,{caps:describe()}))),e.render(),!0)},{name:"teleport",hint:"",category:"session",desc:"Resume a session from aegiscloud.org",handler:async e=>(note(e,"Teleport requires an AEGIS cloud account with sessions. Sign in with `aegis login`, then run aegiscloud.org/teleport."),e.render(),!0)},{name:"theme",aliases:["t"],args:["mode"],hint:"[dark|light]",category:"model",desc:"Change the color theme",handler:async(e,t)=>{const n=(t.mode||"").toLowerCase();if("dark"===n||"light"===n){const t="light"===n?2:1;screens.applyTheme(e.ctx,t)}else await e.showThemePicker();if(e.saveConfig({themeIndex:e.ctx.themeIndex}),note(e,"Theme: "+(e.ctx.light?"light":"dark")),themeContradicts(e.ctx.themeIndex)){const t=caps().background;note(e,`warning: this ${t} terminal is not what "${THEME_TABLE[e.ctx.themeIndex].name}" is drawn for — body text may be unreadable.`),note(e,` /terminal background ${t} pins the palette to this terminal, or /terminal background ${"dark"===t?"light":"dark"} if it reads you wrong.`)}return e.render(),!0}},{name:"terminal",aliases:["tty"],args:["mode","mode2"],hint:"[ascii|unicode|color|no-color|background <dark|light>|probe|star <native|narrow>|width <cols>|auto|status]",category:"model",desc:"Show or override how this terminal is drawn (mark, colour, width)",handler:async(e,t)=>{const n=(t.mode||"").toLowerCase(),o=null!=t.mode2?String(t.mode2).trim():"";if(""===n||"status"===n)return panel(e,panels.buildTerminalCaps(describe(),{pinned:!!caps().pinned})),e.render(),!0;const r=caps(),s={glyphs:r.glyphs,face:r.face,star:r.star,depth:r.depth,vt:r.vt,wideRunes:r.wideRunes,background:r.background,backgroundKnown:r.backgroundKnown,reasons:Object.assign({},r.reasons)};if("auto"===n)return resetCaps(),note(e,"Terminal: auto — capabilities re-probed from the environment."),e.render(),!0;if("probe"===n){const t=await probeTerminalBackground();return screens.applyTheme(e.ctx,e.ctx.themeIndex),note(e,t.known?`Terminal: background ${t.background} (${t.reason}) — /theme auto follows it.`:`Terminal: no answer to the background query (${t.reason}).`),note(e," /terminal background dark|light pins it without asking."),panel(e,panels.buildTerminalCaps(describe(),{pinned:!!caps().pinned})),e.render(),!0}if("ascii"===n||"unicode"===n)s.glyphs="ascii"===n?"ascii":"unicode",s.face="ascii"===n?"edges":"native",s.star="ascii"===n?"narrow":"native",s.reasons&&(s.reasons.glyphs=`/terminal ${n}`);else if("color"===n||"no-color"===n||"nocolor"===n)s.depth="color"===n?24:0,s.reasons&&(s.reasons.depth=`/terminal ${n}`);else{if("star"!==n){if("background"===n||"bg"===n){const t=o.toLowerCase();return["dark","light"].includes(t)?(s.background=t,s.backgroundKnown=!0,s.reasons&&(s.reasons.background=`/terminal background ${t}`),setCaps(Object.assign({},s)),screens.applyTheme(e.ctx,e.ctx.themeIndex),note(e,`Terminal: background pinned to ${t} — /theme auto follows it.`),panel(e,panels.buildTerminalCaps(describe(),{pinned:!!caps().pinned})),e.render(),!0):(note(e,"Usage: /terminal background <dark|light>"),e.render(),!0)}if("width"===n){const t=Number(o);return!Number.isFinite(t)||t<20?(note(e,"Usage: /terminal width <cols> (>= 20)"),e.render(),!0):(setCaps(Object.assign({},s,{cols:Math.round(t)})),note(e,`Terminal: width pinned to ${Math.round(t)} columns.`),panel(e,panels.buildTerminalCaps(describe(),{pinned:!!caps().pinned})),e.render(),!0)}return note(e,"Usage: /terminal [ascii|unicode|color|no-color|background <dark|light>|probe|star <native|narrow>|width <cols>|auto|status]"),e.render(),!0}{const t=o.toLowerCase();if(!["native","narrow"].includes(t))return note(e,"Usage: /terminal star <native|narrow>"),e.render(),!0;s.star=t,s.reasons&&(s.reasons.star=`/terminal star ${t}`)}}return setCaps(s),panel(e,panels.buildTerminalCaps(describe(),{pinned:!!caps().pinned})),note(e,"Terminal updated — the current viewport is redrawn; text already scrolled past keeps its old glyphs."),e.render(),!0}},{name:"version",aliases:["v"],hint:"",category:"session",desc:"Show version",handler:async e=>(note(e,`aegiscode v${VERSION}`),e.render(),!0)},{
|
|
4
4
|
// The licence surface this face did not have. `AGPL-3.0-or-later` was in the
|
|
5
5
|
name:"license",aliases:["licence"],hint:"",category:"support",desc:"Show this program's licence (AGPL-3.0-or-later) and where to read it",handler:async e=>{const t=loadCredits(),n=t.program||{},o=[];if(o.push("Licence"),o.push(" "+(n.name||"GNU Affero General Public License v3.0 or later")),o.push(" "+(n.licence||"AGPL-3.0-or-later")),o.push(""),n.copyright&&o.push(" "+n.copyright),n.url&&o.push(" Full text: "+n.url),n.source&&o.push(" Source: "+n.source),o.push(""),o.push(" /credits lists the vendored third-party code and fonts."),n.notice){o.push("");for(const e of String(n.notice).split("\n"))o.push(e?" "+e:"")}Array.isArray(t.missing)&&t.missing.length&&(o.push(""),o.push(" Could not read: "+t.missing.join(", ")));for(const t of o)note(e,t);return e.render(),!0}},{name:"credits",hint:"",category:"support",desc:"Show third-party attributions and the licence the bundled fonts carry",handler:async e=>{const t=loadCredits(),n=[],o=Array.isArray(t.code)?t.code:[],r=Array.isArray(t.fonts)?t.fonts:[];if(n.push("Credits"),n.push(" "+(t.program&&t.program.copyright||"")),o.length){n.push(""),n.push(" Vendored third-party code");for(const e of o)n.push(" "+e.name+(e.version?" v"+e.version:"")+(e.licence?" "+e.licence:"")),e.url&&n.push(" "+e.url)}if(r.length){n.push(""),n.push(" Vendored webfonts");for(const e of r)n.push(" "+e.name+" "+(e.copyright||"")+(e.licence?" "+e.licence:"")),e.url&&n.push(" "+e.url)}o.length||r.length||(n.push(""),n.push(" No attribution files could be read from this installation.")),n.push(""),n.push(" /license shows the licence this program itself is under.");for(const t of n)note(e,t);return e.render(),!0}},{name:"doctor",args:["action"],hint:"[fix|system]",category:"support",desc:"Run diagnostic checks on this environment",handler:async(e,t)=>{const n=(t&&t.action||"").toLowerCase();if(n&&"fix"!==n&&"system"!==n)return note(e,'Usage: /doctor [fix|system] — "fix" re-tightens the data dir to 0700/0600, "system" checks the machine itself'),e.render(),!0;const o=[],r=(e,t,n)=>o.push([t,e,n]);r("Node",!0,process.version),r("CWD",fs.existsSync(process.cwd()),process.cwd());let s=!1;try{execSync("git rev-parse --git-dir",{cwd:process.cwd(),stdio:["ignore","ignore","ignore"],timeout:4e3}),s=!0}catch{}r("git repo",s,s?"inside a work tree":"not a git repository");const a=credentials.keyStatus();r("AEGIS key",a.configured,a.configured?`${maskKey(a.key)} via ${credentials.sourceLabel(a.source)}`:`not set — ${credentials.HOW_TO_SET} (free key: ${signupUrl("doctor")})`),r("credentials",!0,`${a.path}${a.fileMode?` (${a.fileMode})`:""}`),r("cloud memory",a.memoryToken,a.memoryToken?"token held":"no memory token — /cloud activate"),a.legacyPlaintext&&r("plaintext key",!1,`a copy also sits in ${configPath()} (another AEGIS CLI) — /key re-saves it to ${a.path}`),r("config path",!0,configPath());const i=aegisDir();let l=null;"fix"===n&&(l=repairExposure(i));const d=auditExposure(i);if(d.exists)if(d.modesMeaningful){const e=d.exposed.slice(0,4).map(e=>`${e.rel} ${e.mode}`).join(", ");r("data dir",0===d.exposed.length,0===d.exposed.length?`${i} (${d.rootMode}, all private)`:`${i} (${d.rootMode}) — ${d.exposed.length} path(s) group/world-accessible: ${e}${d.exposed.length>4?", …":""} — run /doctor fix`)}else r("data dir",!0,`${i} (${d.total} path(s)) — this filesystem has no POSIX permission bits; access is governed by the profile directory's own ACL`);else r("data dir",!0,`${i} (not created yet)`);if(l&&!l.modesMeaningful)r("repair",!0,"nothing to tighten — this filesystem has no POSIX permission bits");else if(l){const e=l.fixed.slice(0,3).map(e=>`${e.rel} ${e.from}→${e.to}`).join(", ");r("repair",0===l.remaining.length,0===l.remaining.length?l.fixed.length?`tightened ${l.fixed.length} path(s) — ${e}${l.fixed.length>3?", …":""}`:"already private, nothing to tighten":`${l.remaining.length} path(s) still exposed — `+l.failed.map(e=>`${e.rel}: ${e.reason}`).join(", "))}let c=null;if("system"===n){const e=sysdiag.collect();if(e.ok){c=sysdiag.assess(e.data);for(const e of c.findings)r(`${e.title} (${e.severity})`,!1,`${e.detail} → ${e.remedyText}`);for(const e of c.clean)r(e.title,!0,e.detail);for(const e of c.unassessed)r(`${e.title} (unassessed)`,!1,e.reason)}else r("machine checks",!1,"not-windows"===e.reason?"not available on this platform — the machine audit is Windows-only (cli/src/sysdiag.js)":`could not run: ${e.reason}`)}const u=[[span(C.gold+BOLD,"Doctor"),span(BOLD_OFF,"")],[span(C.gray,"─".repeat(30))]];for(const[e,t,n]of o)u.push([span(e?C.green:C.coral," "+(e?"✔":"⚠")),span(C.white,` ${t}: `),span(C.gray,String(n))]);if(c&&c.findings.length){const e=c.summary;u.push([span(C.gold," Remedy"),span(C.gray,` — ${e.findings} finding(s) across ${e.assessed}/${e.total} measured checks.`)]),u.push([span(C.gray," Run in an ELEVATED PowerShell. AEGIS diagnoses this; it does not change your machine.")]);for(const e of sysdiag.remedyScript().split("\n"))u.push([span(C.gray,` ${e}`)])}return panel(e,u),e.render(),!0}},{name:"upgrade",args:["action"],hint:"[check|apply]",category:"support",desc:"Check for a newer published version (apply: install it now)",handler:async(e,t)=>{const n=String(t&&t.action||"check").toLowerCase();if(!["check","apply"].includes(n))return note(e,"Usage: /upgrade [check|apply]"),e.render(),!0;const o=installMethod();note(e,"Checking the npm registry…"),e.render();const r=e&&e.withWorking?t=>e.withWorking(t):e=>e(),s=e.ctx&&e.ctx.demo?null:await r(()=>Promise.resolve(latestPublishedVersion())),a=upgradeAdvice({latest:s,method:o});if(panel(e,upgradePanelLines(a.lines)),e.render(),"apply"!==n)return!0;if(!a.plan||!a.plan.apply)return note(e,a.plan?`Nothing to install: ${a.plan.instruction}`:"Nothing to install."),e.render(),!0;note(e,`Running: ${a.plan.instruction}`),e.render();const i=applyUpgrade({method:o,latest:s,current:a.plan.current});if(i.ok&&!i.skipped){if(note(e,`Installed ${a.plan.latest}. Restart aegiscode to use it.`),i.output)for(const t of i.output.split("\n").slice(-6))note(e,` ${t}`)}else i.skipped?note(e,`Not applied: ${i.instruction}`):(note(e,`Upgrade failed: ${i.error}`),note(e,`Run it yourself: ${i.command}`));return e.render(),!0}},{name:"vim",args:["mode"],hint:"[on|off]",category:"model",desc:"Toggle vim keymap",handler:async(e,t)=>{const n=(t.mode||"").toLowerCase();if(n&&!["on","off"].includes(n))return note(e,"Usage: /vim [on|off]"),e.render(),!0;const o="on"===n||"off"!==n&&!e.ctx.vim;return e.ctx.vim=o,e.saveConfig({vim:o}),note(e,"Vim keymap: "+(o?"on":"off")),e.render(),!0}},{name:"permissions",args:["mode","pattern"],hint:'[allow|deny|ask "<pattern>" | default <ask|allow|deny> | mode <m> | clear]',category:"model",desc:"Set rules for tool/command use (globs — for filesystem path confinement see /sandbox)",handler:async(e,t)=>{const n=loadPermissions(),o=(t.mode||"").toLowerCase(),r=t.pattern;if(!o){const t=permissionMode();return panel(e,panels.buildPermissions({...n,_path:permissionsPath(),_permissionMode:t},null,e.ctx)),e.render(),!0}if("mode"===o){const n=(r||"").toLowerCase();if(!n){const t=permissionMode();return note(e,`Child permission mode: ${t||"unset (no --permission-mode is passed)"}`),note(e,`Set with: /permissions mode <${PERMISSION_MODES_LOCAL.join("|")}|off>`),e.render(),!0}if("off"===n||"none"===n)return setPermissionMode(null),note(e,"Child permission mode cleared — the child is spawned with no --permission-mode."),e.render(),!0;try{const t=setPermissionMode(n);note(e,`Child permission mode: ${t}`),confirmPosture().enabled||note(e,"Note: confirmations are OFF, so --dangerously-skip-permissions wins and the mode is recorded but not passed. Run /confirm to let the mode take effect.")}catch(t){note(e,t&&t.message||String(t))}return e.render(),!0}if("clear"===o)return setPermissionDefaultMode(DEFAULT_PERMISSIONS.defaultMode),savePermissions({...DEFAULT_PERMISSIONS,allow:[],deny:[],ask:[]}),note(e,"Permissions reset to defaults (no rules)."),e.render(),!0;if("default"===o&&["ask","allow","deny"].includes(r))return setPermissionDefaultMode(r),note(e,`Default permission mode: ${r}`),"ask"===r&&askTierNote(e),e.render(),!0;if(["allow","deny","ask"].includes(o)&&r){const{added:t,rules:s}=addPermissionRule(o,r,n);return savePermissions(s),note(e,t?`Added ${o} rule: ${r}`:`Rule already present: ${r}`),"ask"===o&&askTierNote(e),e.render(),!0}return note(e,'Usage: /permissions [allow|deny|ask "<pattern>" | default <ask|allow|deny> | mode <m> | clear]'),e.render(),!0}},{name:"hooks",args:["sub"],hint:"[status|list|install]",category:"model",desc:"View hooks configuration status, list configured hooks, or install this repo's guard hooks",handler:async(e,t)=>{const n=(t.sub||"").toLowerCase();if("install"===n){const n=/--dry-run|\bdry-?run\b/.test(String(t._rest||"")),o=hooksLib.installRepoHooks({cwd:process.cwd(),dryRun:n});if(o.ok)if(n){note(e,`would install the guard hooks in ${o.status.repo}`);for(const t of o.actions)note(e,` ${t}`);o.status.installed&¬e(e,"core.hooksPath is already .githooks — nothing to change")}else if(o.changed){done(e,"installed the guard hooks — core.hooksPath = .githooks (verified)");for(const t of o.actions)note(e,` ${t}`)}else done(e,"guard hooks already installed (core.hooksPath = .githooks)");else if(note(e,o.error),o.actions.length)for(const t of o.actions)note(e,` ${t}`);return o.ok&¬e(e,o.status.execNote),e.render(),!0}const{hooks:o,from:r}=readHooks();return"list"===n?(panel(e,panels.buildHooksList({hooks:o},e.ctx)),e.render(),!0):""===n||"status"===n?(panel(e,panels.buildHooksStatus({...hookStats(o),fromPaths:r},e.ctx)),e.render(),!0):(note(e,`unknown subcommand: ${t.sub}`),note(e,"available: status, list, install [--dry-run]"),e.render(),!0)}},{name:"credentials",hint:"",category:"model",desc:"Show where credentials are stored",handler:async e=>{const t=path.join(os.homedir(),".claude",".credentials.json"),n=t.replace(os.homedir(),"~");return fs.existsSync(t)?note(e,`Credentials live in ${n} (managed by the Claude Code CLI). aegiscode reads them but never writes them.`):note(e,"No credential file found. The Claude Code CLI manages auth (OS keychain or ~/.claude/.credentials.json)."),e.render(),!0}},{name:"install-github-app",hint:"",category:"model",desc:"Install the GitHub App for PR workflows",handler:async e=>(note(e,"The GitHub App is installed through the Claude Code CLI: run `claude --install-github-app` once."),e.render(),!0)},{name:"troubleshooting",hint:"",category:"support",desc:"Troubleshoot common issues",handler:async e=>(panel(e,panels.buildTroubleshooting(e.state(),e.ctx)),e.render(),!0)},{name:"feedback",hint:"",category:"support",desc:"Send feedback to the AEGIS team",handler:async e=>(note(e,"Opening the feedback form…"),openUrl(URLS.feedback)||note(e,`Feedback: ${URLS.feedback}`),e.render(),!0)},{name:"bug",hint:"",category:"support",desc:"Report a bug (opens a GitHub issue)",handler:async e=>(note(e,`Opening a GitHub issue… (aegiscode v${VERSION}, ${process.version}, ${os.platform()})`),openUrl(URLS.issues)||note(e,`Issues: ${URLS.issues}`),e.render(),!0)},{name:"issue",aliases:["bugs"],hint:"",category:"support",desc:"Report an issue",handler:async e=>(note(e,"Opening a GitHub issue…"),openUrl(URLS.issues)||note(e,`Issues: ${URLS.issues}`),e.render(),!0)},{name:"onboarding",hint:"",category:"support",desc:"Show getting-started tips",handler:async e=>(panel(e,panels.buildOnboarding(e.state(),e.ctx)),e.render(),!0)},{name:"shell-completion",hint:"",category:"support",desc:"Set up shell completion",handler:async e=>(panel(e,panels.buildShellCompletion(e.state(),e.ctx)),e.render(),!0)},{name:"terminal-setup",hint:"",category:"support",desc:"Check and fix terminal setup",handler:async e=>(panel(e,panels.buildTerminalSetup(e.state(),e.ctx)),e.render(),!0)},{name:"pr-comments",hint:"",category:"support",desc:"Review and reply to pull request comments",handler:async e=>(note(e,"PR comments need GitHub auth. Run /prs to check connectivity, then use the `gh` CLI or the GitHub web UI."),e.render(),!0)},{name:"prs",hint:"",category:"support",desc:"List pull requests in this repo",handler:async e=>{try{const t=execSync("gh pr list --limit 8",{encoding:"utf8",timeout:15e3,stdio:["ignore","pipe","ignore"]});panel(e,panels.buildPRs(t.toString(),e.ctx))}catch{note(e,"gh not authenticated (or not installed) — run `gh auth login` first.")}return e.render(),!0}},{name:"review",hint:"",category:"support",desc:"Review a pull request",handler:async e=>(note(e,"/review needs GitHub auth via gh. Run /prs to list open PRs, then open one in the browser."),e.render(),!0)},{name:"benchmark",hint:"",category:"support",desc:"Run in-app micro-benchmarks",handler:async e=>{const t=e=>{const t=process.hrtime.bigint();return e(),(Number(process.hrtime.bigint()-t)/1e6).toFixed(2)},n=[["2,000 span() calls",t(()=>{for(let e=0;e<2e3;e++)span(C.white,"x")})],["estimateTokens × 20 (500 chars)",t(()=>{for(let e=0;e<20;e++)estimateTokens("x".repeat(500))})]];return markdownModule&&"function"==typeof markdownModule.renderMarkdown&&n.push(["renderMarkdown × 200",t(()=>{for(let e=0;e<200;e++)markdownModule.renderMarkdown("# Heading\n\nSome **bold** and `code` with a [link](https://x.test).\n\n- a\n- b\n- c\n",80)})]),panel(e,panels.buildBenchmark(n,e.ctx)),e.render(),!0}},{name:"waifu",hint:"",category:"fun",desc:"Summon a waifu",handler:async e=>(panel(e,panels.buildWaifu(e.ctx)),e.render(),!0)},{name:"new",aliases:["start"],hint:"",category:"session",desc:"Start a new session (clears the transcript, fresh session id)",handler:async e=>{e.transcript.length=0,"function"==typeof e.clearConversationMemory&&e.clearConversationMemory();const t="aegis-"+Math.random().toString(36).slice(2,10);return e.sessionId=t,e.ctx.sessionId=t,note(e,`New session started (${t}) — earlier context cleared.`),e.render(),!0}},{name:"tokens",aliases:["tok"],hint:"",category:"data",desc:"Show token usage breakdown and estimated spend",handler:async e=>{const t=sessionAccounting(e.transcript,e.ctx.model);return panel(e,panels.buildTokens({...e.state(),contextWindow:t.contextWindow,costEur:t.cost},e.ctx)),e.render(),!0}},{name:"skills",aliases:["sk"],args:["sub"],hint:"[new <name> [description]|import <url> [name]|rm <name>|<name>]",category:"session",desc:"List, create, import and remove skills (SKILL.md in the standard skill dirs)",handler:async(e,t)=>{const n=(t.sub||"").trim().toLowerCase(),o=String(t._rest||"").trim().replace(/^(?:new|rm|remove|delete|import)\s+/i,"").trim(),r=scanSkills(),s=skillsLib.scan(),a=s.roots.map(e=>e.replace(os.homedir(),"~"));if("refresh"===n||"reload"===n){note(e,`Skills refreshed — ${r.length} found (${s.roots.length} dirs scanned).`);for(const t of s.missing)note(e,` not yet created: ${t.replace(os.homedir(),"~")}`);return e.render(),!0}if("new"===n||"create"===n){const t=o.split(/\s+/)[0]||"";if(!t)return note(e,"Usage: /skills new <name> [when to use it]"),note(e," The name becomes the directory and the slash word: lowercase letters, digits, single hyphens."),note(e,` Default location: ${skillsLib.defaultCreateDir().replace(os.homedir(),"~")}`),e.render(),!0;const n=o.slice(t.length).trim(),r=skillsLib.create({name:t,description:n});return r.ok?(note(e,`Created skill "${r.name}" at ${r.dir.replace(os.homedir(),"~")}`),note(e," Edit it to describe when the model should reach for it: /skills "+r.name),e.render(),!0):(note(e,r.reason),r.exists||note(e," Names: lowercase letters, digits and single hyphens (for example: release-notes)."),e.render(),!0)}if("import"===n){const t=o.split(/\s+/).filter(Boolean),n=t[0]||"",r=t[1]||"";if(!n)return note(e,"Usage: /skills import <url> [name]"),note(e," Fetches a SKILL.md and writes it like /skills new. Only http:// and https:// URLs are accepted."),e.render(),!0;note(e,`Fetching ${n}…`),e.render();const s=await skillsLib.importFromUrl({url:n,name:r});return s.ok?(note(e,`Imported skill "${s.name}" at ${s.dir.replace(os.homedir(),"~")}`),note(e," Review it before relying on it — it came from the network: /skills "+s.name),e.render(),!0):(note(e,s.reason),e.render(),!0)}if("rm"===n||"remove"===n||"delete"===n){const t=o.split(/\s+/)[0]||"";if(!t)return note(e,"Usage: /skills rm <name> — deletes that skill directory."),e.render(),!0;const n=r.find(e=>e.name===t);if(!n)return note(e,`No skill named "${t}" was found. /skills lists what exists on disk.`),e.render(),!0;const s=await e.askInput(`Delete skill "${t}" at ${n.path.replace(os.homedir(),"~")}? (y/N) `);if(!/^y(es)?$/i.test(String(null==s?"":s).trim()))return note(e,`Kept "${t}".`),e.render(),!0;const a=skillsLib.remove(t);return note(e,a.ok?`Removed skill "${a.name}".`:a.reason),e.render(),!0}if(n){const t=r.find(e=>e.name===n);return t?(panel(e,panels.buildSkillDetail(t,e.ctx)),e.render(),!0):(note(e,`Unknown skill "${n}". /skills lists what exists on disk.`),note(e,` Create it: /skills new ${n} [when to use it]`),e.render(),!0)}panel(e,panels.buildSkills(r,a,e.ctx));for(const t of s.missing)note(e,` not yet created: ${t.replace(os.homedir(),"~")}`);return e.render(),!0}},{name:"thinking",args:["mode"],hint:"[on|off]",category:"model",desc:"Toggle thinking blocks expanded/collapsed",handler:async(e,t)=>{const n=(t.mode||"").toLowerCase();if(n&&!["on","off"].includes(n))return note(e,"Usage: /thinking [on|off]"),e.render(),!0;const o="on"===n||"off"!==n&&!(!0===e.ctx.thinking);return e.ctx.thinking=o,e.saveConfig({thinking:o}),note(e,"Thinking blocks: "+(o?"expanded":"collapsed")),e.render(),!0}},{name:"mcp",args:["sub","name","command"],hint:"[add <name> <command> [args…]|remove <name>|<name>]",category:"model",desc:"Show MCP server configuration",handler:async(e,t)=>{const n=loadConfig().mcpServers||{},o=(t.sub||"").toLowerCase();if("add"===o){const o=(t.name||"").trim(),r=(t.command||"").trim();if(!o||!r)return note(e,'Usage: /mcp add <name> "<command with args>"'),e.render(),!0;const s=r.split(/\s+/).filter(Boolean);return updateConfig({mcpServers:{...n,[o]:{command:s[0],args:s.slice(1)}}}),note(e,`Added MCP server "${o}" (${s[0]}). Configuration only — this build has no MCP runtime.`),e.render(),!0}if("remove"===o||"rm"===o){const o=(t.name||"").trim();if(!o)return note(e,"Usage: /mcp remove <name>"),e.render(),!0;if(!n[o])return note(e,`No MCP server "${o}". /mcp lists the configured ones.`),e.render(),!0;const r={...n};return delete r[o],updateConfig({mcpServers:r}),note(e,`Removed MCP server "${o}".`),e.render(),!0}if(o&&n[o]){const t=n[o];return panel(e,[[span(C.gold,`MCP server: ${o}`)],[span(C.gray,"─".repeat(30))],[span(C.white,` command: ${`${t.command||""} ${(t.args||[]).join(" ")}`.trim()}`)],[span("","")],[span(C.gray,"Configuration only — this build has no MCP runtime.")]]),e.render(),!0}return panel(e,panels.buildMcp(n,[configPath(),permissionsPath()],e.ctx)),e.render(),!0}},{name:"memory",aliases:["memories"],hint:"",category:"model",desc:"List the most recent AEGIS cloud-memory entries",tool:"aegis_memory_list",build:()=>({})},{name:"memory-deep",aliases:["recall-deep"],args:["mode"],hint:"[on|off]",category:"model",desc:"Toggle DEEP recall for this session — brain corrections + cached answers (metered: one embedding per turn)",handler:async(e,t)=>{const n=(t.mode||"").toLowerCase();if(n&&!["on","off"].includes(n))return note(e,"Usage: /memory-deep [on|off]"),e.render(),!0;const o="on"===n||"off"!==n&&!(!0===e.ctx.recallDeep);return e.ctx.recallDeep=o,note(e,`Deep recall: ${o?"on — brain corrections + cached answers, one embedding per turn":"off (only the cheap recall read)"}${o?" · this session only":""}`),e.render(),!0}},{name:"confirm",aliases:["confirmations"],args:["mode"],hint:"[on|off]",category:"model",desc:"Toggle tool-call confirmation prompts",handler:async(e,t)=>{const n=(t.mode||"").toLowerCase();if(n&&!["on","off"].includes(n))return note(e,"Usage: /confirm [on|off]"),e.render(),!0;const o="on"===n||"off"!==n&&!confirmPosture().enabled;return setConfirmPosture(o),note(e,`Confirmation prompts: ${o?"on":"off"} (default permission mode: ${o?"ask":"allow"})`),e.render(),!0}},{name:"automode",aliases:["yolo"],args:["mode"],hint:"[on|off]",category:"model",desc:"Toggle automode — auto-approve all tool executions",handler:async(e,t)=>{const n=(t.mode||"").toLowerCase();if(n&&!["on","off"].includes(n))return note(e,"Usage: /automode [on|off]"),e.render(),!0;const o="on"===n||"off"!==n&&confirmPosture().enabled;return setConfirmPosture(!o),"function"==typeof e.setAutoRounds&&e.setAutoRounds(o),o?panel(e,panels.buildAutomode(e.state(),e.ctx)):note(e,"automode off — confirmations restored."),e.render(),!0}},{name:"multiyolo",aliases:["multiauto"],args:["task"],hint:"<task>",category:"session",desc:"Multi-agent orchestration with automode — /multiyolo <task>",handler:async(e,t)=>{const n=(t._rest||t.task||"").trim();return n?runMultiCommand(e,n,{yolo:!0}):(note(e,"Usage: /multiyolo <task>"),e.render(),!0)}},{name:"router",args:["sub","tier","modelId"],hint:"[on|off|set <tier> <modelId>|stats]",category:"model",desc:"Show or manage the model router config",handler:async(e,t)=>{const n=loadConfig(),o=n.autoRouter||{enabled:!1,tiers:{}},r=(t.sub||"").toLowerCase(),s=e=>updateConfig({autoRouter:e});if("on"===r)return s({...o,enabled:!0}),note(e,"Auto-router: on."),e.render(),!0;if("off"===r)return s({...o,enabled:!1}),note(e,"Auto-router: off."),e.render(),!0;if("set"===r){const n=(t.tier||"").toLowerCase(),r=(t.modelId||"").trim();return["simple","medium","complex"].includes(n)&&r?(s({...o,tiers:{...o.tiers||{},[n]:r}}),note(e,`Auto-router: ${n} -> ${r}`),e.render(),!0):(note(e,"Usage: /router set <simple|medium|complex> <modelId>"),e.render(),!0)}return"stats"===r?(panel(e,[[span(C.gold+BOLD,"Router stats"),span(BOLD_OFF,"")],[span(C.gray,"─".repeat(30))],[span(C.gray,"No learned outcomes yet — this build does not auto-route.")],[span(C.gray,"Tiers: simple/medium/complex via /router set.")]]),e.render(),!0):(panel(e,panels.buildRouter(n,e.ctx)),e.render(),!0)}},{name:"multi",args:["task","mode"],hint:"<task> [run]",category:"session",desc:'Compose a multi-agent task (add "run" to execute)',handler:async(e,t)=>{let n=(t._rest||t.task||"").trim(),o=(t.mode||"").toLowerCase();return"run"!==o&&/\s+run$/i.test(n)&&(o="run",n=n.replace(/\s+run$/i,"").trim()),n?"run"!==o?(panel(e,panels.buildAegisMulti(n,e.ctx)),e.render(),!0):runMultiCommand(e,n):(note(e,"Usage: /multi <task> [run]"),e.render(),!0)}},{name:"research",args:["question"],hint:"<question>",category:"session",desc:"Research a topic with a multi-perspective council prompt",handler:async(e,t)=>{const n=(t._rest||t.question||"").trim();if(!n)return note(e,"Usage: /research <question>"),e.render(),!0;const o=composeResearchPrompt(n,process.cwd());return e.runPrompt?(await e.runPrompt(o),!0):(note(e,`Composed research prompt (${o.length} chars) — run in the TUI to send it.`),e.render(),!0)}},{name:"debate",aliases:["db"],args:["topic"],hint:"<topic>",category:"session",desc:"Run a structured debate on the current model",handler:async(e,t)=>{const n=(t._rest||t.topic||"").trim();if(!n)return note(e,"Usage: /debate <topic>"),e.render(),!0;const o=composeDebatePrompt(n,e.ctx.model||"");return e.runPrompt?(await e.runPrompt(o),!0):(note(e,`Composed debate prompt (${o.length} chars) — run in the TUI to send it.`),e.render(),!0)}},{name:"billing",aliases:["balance","spend"],hint:"",category:"support",desc:"Show billing info — token-bank balance and recent spend",handler:async e=>{await e.runTool("aegis_balance",{});const t=await e.refreshSpend(),n=e.state();return panel(e,panels.buildBilling({...n,balance:t&&null!=t.balance?t.balance:n.balance,payment:await billingPayment(e)},e.ctx)),e.render(),!0}},{name:"topup",aliases:["fund"],args:["amount"],hint:"[EUR]",category:"support",desc:"Top up the token bank — opens the payment page and confirms the credit here",handler:async(e,t)=>{const n=String(t.amount||t._rest||"").trim();let o;try{o=require(require("./sharedpaths.js").resolveShared("client/topup.js"))}catch(t){return note(e,`top-up is unavailable in this build — ${t.message}`),e.render(),!0}const r=o.parseTopupAmount(n);if(!r.ok)return note(e,r.message),e.render(),!0;if(!e.client.apiKey)return note(e,`no AEGIS key on this machine — ${credentials.HOW_TO_SET}, then /topup ${r.amount}`),e.render(),!0;const s=e.withWorking?await e.withWorking(()=>o.startTopup(e.client,r.amount)):await o.startTopup(e.client,r.amount);if(!s.ok)return note(e,`the top-up could not be started — ${s.message}`),s.hint&¬e(e,s.hint),e.render(),!0;note(e,`opening the payment page — ${r.amount} EUR`),note(e,s.url);const a=Math.round(o.TOPUP_POLL_MS*o.TOPUP_POLL_TRIES/1e3);note(e,`watching this account's bank for up to ${a}s; the credit is confirmed here, not in the browser`),e.render(),openUrl(s.url)||note(e,"could not open a browser — use the URL above");const i=o.createCreditWatch(e.client);let l=null,d=!1;const c=()=>{d=!0,l&&clearTimeout(l)},u=async()=>{if(d)return;const t=await i.tick();return"credited"===t.state?(c(),note(e,`credit confirmed — the bank is now ${t.amount.toFixed(2)} EUR`),void e.render()):"expired"===t.state?(c(),note(e,"no credit observed within the watch window — if you completed the payment it may still land; /billing shows the bank"),void e.render()):(l=setTimeout(u,o.TOPUP_POLL_MS),void(l&&"function"==typeof l.unref&&l.unref()))};return l=setTimeout(u,o.TOPUP_POLL_MS),l&&"function"==typeof l.unref&&l.unref(),!0}},{name:"cloud",args:["sub","value"],hint:"[status|key <api_key>|activate|deactivate|sync [on|off|now]]",category:"support",desc:"Show and control ÆGIS cloud sync",handler:async(e,t)=>{const n=(t.sub||"").toLowerCase(),o=(t.value||t._rest||"").trim();if("key"===n)return await applyAccountKey(e,o),e.render(),!0;if("activate"===n){if(!e.client.apiKey)return note(e,`no key — ${credentials.HOW_TO_SET}`),e.render(),!0;try{const t=await e.withWorking(()=>e.client.memoryActivate()),n=await e.client.getMemoryToken();n&&credentials.saveMemoryToken(n,{memorySubscribed:!0}),done(e,t&&!1===t.ok?"the server refused activation":"cloud memory activated for this account"),t&&t.token_limit&¬e(e,`quota: ${t.tokens_used||0} / ${t.token_limit} synced tokens`)}catch(t){note(e,`activation failed: ${t.message}`)}return e.render(),!0}if("deactivate"===n)return credentials.clearMemoryToken(),e.client.setApiKey(e.client.apiKey),note(e,"cloud memory token cleared locally — sync stops until /cloud activate re-issues one"),note(e,"the account itself is still subscribed; manage the subscription here:"),note(e,goUrl("upgrade","cloud_deactivate")),e.render(),!0;if("memory"===n||"persist"===n||"memory-persist"===n){const t=(o||"status").toLowerCase();if("on"===t||"off"===t){const n="on"===t;return setMemoryGate(e,n),n?(done(e,"cloud sync on — sessions are stored to your account so an interrupted turn can be resumed"),note(e,"/cloud sync shows the quota; past the plan’s ceiling reads keep working and only new writes pause")):(note(e,"cloud sync off — nothing new is stored"),note(e,"everything already in the cloud stays readable (/aegis-recall <topic>), and /sync now still pushes once by hand")),e.render(),!0}return panel(e,memoryStatusLines(e)),e.render(),!0}if("sync"===n||"push"===n||"pull"===n){const t="sync"===n?(o||"status").toLowerCase():n;if("on"===t||"off"===t){const n="on"===t;return setMemoryGate(e,n),note(e,n?"cloud sync on — sessions are stored after each turn":"cloud sync off — nothing new is stored; /sync now still runs a manual pass"),e.render(),!0}if("now"===t)return await runCloudSync(e),e.render(),!0;const r=cloudsync.status();panel(e,[...memoryStatusLines(e),[span(C.gray,"")],[span(C.white+BOLD,"Sync ledger"),span(BOLD_OFF,"")],[span(C.gray,` local sessions: ${r.local} · pending push: ${r.pending} · in sync: ${r.synced}`)],[span(C.gray,` last push: ${r.lastPushAt?new Date(r.lastPushAt).toLocaleString():"never"} · last pull: ${r.lastPullAt?new Date(r.lastPullAt).toLocaleString():"never"}`)],[span(C.gray,` state: ${r.path}`)]]);for(const t of r.errors.slice(0,3))panel(e,[[span(C.coral,` ⚠ ${t.error}`)]]);return e.render(),!0}const r=cloudsync.status();return panel(e,[...keyPanelLines(e,"AEGIS cloud"),[span(C.gray,"")],...memoryStatusLines(e),[span(C.gray,"")],[span(C.white+BOLD," Sync"),span(BOLD_OFF,"")],[span(C.gray,` ${r.pending} pending · ${r.synced} in sync · ${r.importedRemote} pulled from cloud`)],[span(C.gray," /cloud sync on | off · /sync now")]]),e.render(),!0}},{name:"key",aliases:["apikey","api-key"],args:["value"],hint:"[<api_key>|status|clear|register]",category:"auth",desc:"Save or show the AEGIS account key",handler:async(e,t)=>{const n=String(t.value||t._rest||"").trim(),o=n.toLowerCase();if("status"===o)return panel(e,keyPanelLines(e)),e.render(),!0;if("register"===o){const t=await e.registerAccount();return t.alreadyKeyed?note(e,"this machine already has an AEGIS key — /key status shows it. Re-registering cannot mint a new welcome trial: that is granted once per machine, ever. For a fresh trial, sign up at aegiscloud.org; to point this session at a different key, /key clear first."):t.key&&t.ok?done(e,"AEGIS account key provisioned and saved"):t.key?note(e,"the account was created but its key could not be saved — run /key <api_key> with the key from aegiscloud.org"):note(e,`could not register this machine: ${t.error?t.error.message:"the server returned no account key"}`),e.render(),!0}if("clear"===o||"remove"===o||"rm"===o){const t=e.forgetApiKey();return done(e,t.cleared?`key removed from ${t.path}`:"there was no saved key to remove"),credentials.legacyKeyOnDisk()&¬e(e,`a copy is still in ${configPath()} (written by another AEGIS CLI) — delete the "aegiscloud" block to finish the job`),e.render(),!0}return await applyAccountKey(e,n),e.render(),!0}},{name:"sync",aliases:["cloudsync","cloud-sync"],args:["mode"],hint:"[now|on|off|status]",category:"data",desc:"Store sessions in AEGIS Cloud (cross-session memory)",hidden:e=>!cloudReady(),handler:async(e,t)=>{const n=(t.mode||"").toLowerCase();if("on"===n||"off"===n)return setMemoryGate(e,"on"===n),note(e,"on"===n?"cloud sync on — sessions are stored so an interrupted turn can be resumed":"cloud sync off — nothing new is stored; /sync now still runs a manual pass"),e.render(),!0;if("status"===n){const t=cloudsync.status(),n=memoryStatusLines(e);return n.push([span(C.gray,"")]),n.push([span(C.gray,` local ${t.local} · pending ${t.pending} · in sync ${t.synced}`)]),panel(e,n),e.render(),!0}return await runCloudSync(e),e.render(),!0}},{name:"drive",aliases:["gdrive","google-drive"],args:["mode"],hint:"[status|connect]",category:"data",desc:"Connect Google Drive as a memory store, alongside AEGIS Cloud",handler:async(e,t)=>{const n=String(t&&t.mode||"").toLowerCase();if(!e.client)return note(e,"Google Drive needs an AEGIS account — this client has none."),e.render(),!0;if("function"!=typeof e.client.driveToken)return note(e,"Google Drive is not reachable from this client — it needs an AEGIS API key and a build with drive-connect support."),e.render(),!0;const o=require(resolveShared(path.join("client","drive-connect.js"))),r=async()=>{const t=await o.driveStatus(e.client),n=[];return n.push([span(C.gray," Google Drive — memory you can hold yourself")]),n.push([span(t.connected?C.green:C.gray,` ${t.connected?"connected":"not connected"}${t.email&&t.connected?` as ${t.email}`:""}`)]),t.connected||(n.push([span(C.gray,` connect: /drive connect (opens ${o.driveConnectUrl(e.client.apiBase)})`)]),t.googleLinkedKnown&&!t.googleLinked&&n.push([span(C.gold," this account has no Google identity yet — sign in with Google first, or the consent screen will attach Drive elsewhere")])),panel(e,n),t};if(!n||"status"===n)return await r(),e.render(),!0;if("connect"===n){const n=await o.driveStatus(e.client);if(n.connected)return note(e,`Google Drive is already connected${n.email?` as ${n.email}`:""}.`),await r(),e.render(),!0;const s=o.driveConnectUrl(e.client.apiBase),a=openUrl(s);note(e,a?`Opening Google's consent screen — finish it in the browser: ${s}`:`Open this in a browser: ${s}`),note(e,"Waiting for the account to report connected (3 minutes)…"),e.render();try{const t=await o.waitForDriveConnected(e.client,{timeoutMs:18e4,pollMs:2e3});note(e,`Google Drive connected${t.email?` as ${t.email}`:""} — /sync now stores sessions in AEGIS Cloud, Drive is the alternative store.`)}catch(t){note(e,t&&"AbortError"===t.name?"cancelled — nothing was changed.":`not connected: ${t&&t.message||t}. If you finished the consent screen, check that the browser's Google account is the one this AEGIS account was linked to.`)}return e.render(),!0}return note(e,"Usage: /drive [status|connect] — status is the default."),e.render(),!0}},{name:"gmail",hint:"",category:"support",desc:"Link Gmail to conversations",handler:async e=>(note(e,"Gmail integration needs Google OAuth — not available in this build. Use /export to save conversations to files instead."),e.render(),!0)},{name:"clone",aliases:["fetch-site","websnap"],args:["url"],hint:"<url>",category:"workspace",desc:"Clone a website into a local project",handler:async(e,t)=>{const n=(t._rest||t.url||"").trim();return n?(note(e,`/clone needs a web-fetch tool and a chat service — not available in this build. Use /init to scaffold a fresh project instead of ${n}.`),e.render(),!0):(note(e,"Usage: /clone <url>"),e.render(),!0)}},{name:"release-notes",hint:"",category:"support",desc:"What's new",handler:async e=>(panel(e,panels.buildReleaseNotes(e.state(),e.ctx)),e.render(),!0)},{name:"aegis-status",hint:"",category:"aegis",desc:"Show account status — API key, plan, account and cloud memory",tool:"aegis_status",build:()=>({})},{name:"aegis-ask",aliases:["ask"],args:["question"],hint:"<question>",category:"aegis",desc:"Ask ÆGIS pooled inference a question (auto-routed)",tool:"aegis_ask",build:e=>({prompt:e})},{name:"aegis-recall",aliases:["recall"],args:["topic"],hint:"<topic>",category:"aegis",desc:"Recall cross-session memory about a topic (cloud)",tool:"aegis_memory_search",build:e=>({query:e})},{name:"aegis-remember",aliases:["remember"],args:["note"],hint:"<note>",category:"aegis",desc:"Save a note or decision to cross-session memory",tool:"aegis_memory_save",build:e=>({content:e})},{name:"aegis-council",aliases:["council"],args:["question"],hint:"<question>",category:"aegis",desc:"Put a question to the ÆGIS council (multi-perspective deliberation)",hidden:()=>!cloudReady(),handler:async(e,t)=>{const n=(t._rest||t.question||"").trim();if(!n)return note(e,"Usage: /aegis-council <question>"),e.render(),!0;const o=composeResearchPrompt(`Deliberate as a council and vote on: ${n}`,process.cwd());return e.runPrompt?(await e.runPrompt(o),!0):(note(e,`Composed council prompt (${o.length} chars) — run in the TUI to send it.`),e.render(),!0)}},{name:"aegis-print",args:["question"],hint:"<question>",category:"aegis",desc:"Ask pooled inference and print the answer cleanly",hidden:()=>!cloudReady(),handler:async(e,t)=>{const n=(t._rest||t.question||"").trim();if(!n)return note(e,"Usage: /aegis-print <question>"),e.render(),!0;const o=await e.ask(n);return panel(e,panels.buildAegisPrint("ÆGIS",{result:o.text,model:o.model,provider:"aegis"},e.ctx)),e.render(),!0}},{name:"aegis-multi",args:["task","mode"],hint:"<task> [run]",category:"aegis",desc:'Compose an ÆGIS /multi multi-agent task (add "run" to execute)',hidden:()=>!cloudReady(),handler:async(e,t)=>{let n=(t._rest||t.task||"").trim(),o=(t.mode||"").toLowerCase();return"run"!==o&&/\s+run$/i.test(n)&&(o="run",n=n.replace(/\s+run$/i,"").trim()),n?"run"!==o?(panel(e,panels.buildAegisMulti(n,e.ctx)),e.render(),!0):runMultiCommand(e,n):(note(e,"Usage: /aegis-multi <task> [run]"),e.render(),!0)}},{name:"byok",hint:"",category:"auth",desc:"List every provider you can bring your own key for, and which are set",handler:async e=>{const t=await byokCatalog(e.client);if(!t)return await e.runTool("aegis_byok_status",{}),!0;const n=t.filter(e=>e.configured).length,o=[[span(C.gold+BOLD,"Bring your own key"),span(BOLD_OFF,"")],[span(C.gray,"─".repeat(34))],[span(n?C.green:C.gray,` ${n} of ${t.length} providers set`),span(C.gray," — /byok-list picks one, or /byok-key <provider>")],"",...byokProviderLines(t)];return panel(e,o),e.render(),!0}},{name:"byok-set",args:["provider"],hint:"<provider>",category:"auth",desc:"Store your provider key on your AEGIS ACCOUNT (pooled route) — for the byok class use /byok-key",tool:"aegis_byok_set",secret:"key",build:e=>({provider:String(e||"").trim()}),async secretDescribe(e,t){const n=String(e.provider||"").trim(),o=await byokCatalog(t);if(!o)return n?null:{note:"Usage: /byok-set <provider> — /byok lists them.",prompt:"provider key: "};const r=findByokProvider(o,n);if(r.ambiguous)return{note:`"${n}" matches ${r.ambiguous.join(", ")} — retype the exact id. Nothing was sent.`,prompt:null};const s=r.provider;if(!s)return{note:`unknown provider "${n}". Known ids: ${o.map(e=>e.id).join(", ")}`,prompt:null};if(s.configured)return{note:`${s.id} already has a key${s.masked?` (${s.masked})`:""} — pasting a new one replaces it.`,prompt:`new ${s.label||s.id} key: `,provider:s.id};const a=[`${s.label||s.id}`],i=(s.models||[]).map(e=>"string"==typeof e?e:e&&e.id).filter(Boolean);return i.length&&a.push(`unlocks ${i.join(", ")}`),s.key_prefix&&a.push(`key starts with ${s.key_prefix}`),s.key_url&&a.push(`create one at ${s.key_url}`),{note:a.join(" · "),prompt:`${s.id} key: `,provider:s.id}}},{name:"byok-rm",args:["provider"],hint:"<provider>",category:"auth",desc:"Remove a stored provider key",tool:"aegis_byok_set",build:e=>({provider:String(e||"").trim()})},{name:"class",args:["class","mode"],hint:"[aegis|byok|local|pro [on|off]]",category:"model",desc:'Show or switch which class turns run on; pro (your Claude subscription) needs a one-time "on"',handler:async(e,t)=>{const n=t||{},o=e.ctx&&e.ctx.modelClass||"aegis",r=t=>e.classLabel?e.classLabel(t):t,s=String(n.class||"").trim().toLowerCase();if("pro"===s&&n.mode){const t=String(n.mode).trim().toLowerCase();if("on"!==t&&"off"!==t)return e.push({role:"error",text:`usage: /class pro [on|off] — got "${n.mode}"`}),!0;const s="on"===t;if(e.saveConfig({proEnabled:s}),e.push({role:s?"done":"note",text:s?"pro class enabled — /class pro switches to your Claude Code subscription. It runs only if that subscription has Claude Code access.":"pro class disabled — it is no longer offered by /class or the model picker."}),!s&&"pro"===o){const t=e.switchClass("aegis");t.ok&&e.push({role:"note",text:`class: ${t.class} — ${r(t.class)}`})}return!0}if(!s){const t=await Promise.resolve(e.classes?e.classes():[]).catch(()=>[]),n=t.length?t:[{class:"aegis"},{class:"byok"}],r=n.findIndex(e=>e.class===o);return e.openOverlay({type:"class",items:n,sel:r<0?0:r,current:o}),!0}const a=e.switchClass(s);if(!a.ok)return e.push({role:"error",text:a.error}),!0;if(e.push({role:"done",text:`class: ${a.class} — ${r(a.class)}`}),a.cleared&&e.push({role:"note",text:`cleared the pin "${a.cleared}" — it does not belong to this class. /models lists what fits.`}),!("byok"!==a.class||e.ctx&&e.ctx.model)){const t=(await e.listModelsFor("byok")||[]).filter(e=>!e.cls||"byok"===e.cls),n=t.find(e=>e.configured)||t[0];n?(e.ctx.model=n.id,e.saveConfig({model:n.id,currentModelId:n.id}),e.push({role:"note",text:n.configured?`using ${n.id} — /models lists the rest.`:`using ${n.id}, but no ${n.provider} key is saved yet — /byok-key ${n.provider}.`})):0===t.length&&e.push({role:"note",text:"nothing to relay yet — save a provider key with /byok-key <provider>, then /models."})}return!0}},{name:"models",aliases:["model-list"],hint:"",category:"model",desc:"Pick a model to pin, for the class you are on — opens the same picker as /model",handler:async e=>{const t=e.ctx&&e.ctx.modelClass||"aegis",n=await e.listModelsFor(t)||[];if(!n.length)return note(e,"byok"===t?"nothing to relay yet — save a provider key with /byok-key <provider>":"no models advertised — check the account with /status, then retry"),e.render(),!0;const o=e.ctx&&e.ctx.model,r=n.map(e=>e.cls&&e.cls!==t?{...e,note:`${e.note||e.label||""} · pooled lane — /class ${e.cls}`}:e),s=r.findIndex(e=>e.id===o);return e.openOverlay({type:"model",items:r,sel:s<0?0:s,current:o,cls:t}),!0}},{name:"byok-list",aliases:["byok-pick"],hint:"",category:"auth",desc:"Pick a provider to set a key for, then its models appear in /model",handler:async e=>{const t=await byokCatalog(e.client);if(!t||!t.length)return e.push({role:"error",text:"Could not read the provider catalog (offline, or no AEGIS key) — /byok lists what is known."}),!0;if("function"!=typeof e.openOverlay)return e.push({role:"note",text:"/byok-key <provider> — /byok lists the providers."}),!0;const n=(t.find(e=>e.configured)||{}).id||null,o=Math.max(0,t.findIndex(e=>e.configured));return e.openOverlay({type:"provider",command:"byok-key",items:t,sel:o,current:n,hint:"↑↓ or tab move · enter picks · the key is stored on this machine"}),!0}},{name:"byok-key",args:["provider"],hint:"<provider> [key]",category:"auth",desc:"Save YOUR provider key on THIS MACHINE — the key the byok class sends",handler:async(e,t)=>{const n=t||{},o=String(n.provider||"").trim().toLowerCase();if(!o){const t=await byokCatalog(e.client);if(!t||!t.length)return e.push({role:"error",text:"Usage: /byok-key <provider> — /byok lists the providers."}),!0;if("function"!=typeof e.openOverlay)return e.push({role:"error",text:"Usage: /byok-key <provider> — /byok lists the providers."}),!0;const n=(t.find(e=>e.configured)||{}).id||null,o=Math.max(0,t.findIndex(e=>e.configured));return e.openOverlay({type:"provider",command:"byok-key",items:t,sel:o,current:n,hint:"↑↓ or tab move · enter picks · the key is stored on this machine"}),!0}const r=e.settings&&e.settings();if(!r||"function"!=typeof r.set)return e.push({role:"error",text:"this client has no provider-key store."}),!0;const s=await byokCatalog(e.client),a=s?findByokProvider(s,o):null;if(a&&a.ambiguous)return e.push({role:"error",text:`"${o}" matches ${a.ambiguous.join(", ")} — retype the exact id.`}),!0;if(s&&!a?.provider){const t=s.map(e=>e.id).join(", ");return e.push({role:"error",text:`unknown provider "${o}". Known ids: ${t} — nothing was saved.`}),!0}const i=a&&a.provider,l=i&&i.id||o,d=String(n._rest||"").trim(),c=d.indexOf(" ");let u=-1===c?"":d.slice(c+1).trim();if(u||(i&&i.key_url&&e.push({role:"note",text:`create a ${i.label||l} key at ${i.key_url}`}),u=String(await e.readSecret(`${l} key: `)||"").trim()),!u)return e.push({role:"note",text:"nothing saved."}),!0;if(i&&i.key_prefix&&!u.startsWith(i.key_prefix)&&e.push({role:"note",text:`heads up: ${l} keys normally start with "${i.key_prefix}" — saved anyway.`}),"custom"===l&&!savedByokBaseURL(e,l))return e.push({role:"error",text:`the "custom" provider needs an endpoint as well as a key — a key alone dials nothing. Use: /model-add custom <https-base-url> ${u} <model-id> (saves endpoint, key and model together) — nothing was saved.`}),!0;r.set(e.byokNamespace(l),{key:u});let p="";try{const{envVarFor:t,setEnvValue:n}=require(resolveShared(path.join("client","env-file.js"))),o=t(l);if(o){const t=n(o,u);t.ok?p=o:e.push({role:"note",text:`heads up: could not write ${o} to ~/.aegiscode/.env (${t.error}).`})}}catch{}let h=[];if("function"==typeof e.refreshByokModels)try{h=await e.refreshByokModels()||[]}catch{h=[]}if(!h.length&&"function"==typeof e.listModelsFor)try{h=(await e.listModelsFor("byok")||[]).filter(e=>!e.cls||"byok"===e.cls)}catch{h=[]}const m=h.filter(e=>e&&(e.provider===l||String(e.id||"").startsWith(`${l}:`))),g=e.ctx&&e.ctx.modelClass||"aegis";let y="byok"===g;if(!y&&"aegis"===g&&"function"==typeof e.switchClass){const t=e.switchClass("byok");t&&t.ok&&(y=!0,e.push({role:"note",text:`class: byok — ${e.classLabel?e.classLabel("byok"):"your own key"}`}))}y||"aegis"===g||e.push({role:"note",text:`staying on class: ${g} — the ${l} key is saved, and /class byok spends it.`});const f=y&&m.length?String(m[0].id):"";return f&&e.ctx&&(e.ctx.model=f,e.saveConfig({model:f,currentModelId:f,modelClass:"byok"})),e.push({role:"done",text:f?`saved a ${l} key on this machine${p?` (${p} in ~/.aegiscode/.env, so it is there next time)`:""} — model ${f} pinned, /model lists the rest.`:y||"aegis"===g?`saved a ${l} key on this machine${p?` (${p} in ~/.aegiscode/.env, so it is there next time)`:""} — /models lists its models, /class byok runs on it.`:`saved a ${l} key on this machine${p?` (${p} in ~/.aegiscode/.env, so it is there next time)`:""} — class is still ${g}; /class byok switches to it whenever you want.`}),!0}},{name:"byok-rm-key",args:["provider"],hint:"<provider>",category:"auth",desc:"Forget the provider key saved on this machine",handler:async(e,t)=>{const n=String((t||{}).provider||"").trim().toLowerCase();if(!n)return e.push({role:"error",text:"Usage: /byok-rm-key <provider> — /byok lists the providers."}),!0;const o=e.settings&&e.settings();if(!o||"function"!=typeof o.remove)return e.push({role:"error",text:"this client has no provider-key store."}),!0;const r=e.byokNamespace(n),s="function"==typeof o.rawKey?o.rawKey(r):null;return o.remove(r),e.push({role:s?"done":"note",text:s?`removed the ${n} key from this machine.`:`no ${n} key was saved on this machine.`}),!0}},{name:"model-add",aliases:["add-model"],args:["provider"],hint:"<provider> [api-key] [model-id|*] (custom: <base-url> <api-key> [model-id|*])",category:"model",desc:"Save a provider key and offer a model id in one step (asks the vendor when it can)",handler:async(e,t)=>{const n=t||{},o=String(n.provider||"").trim();if(!o)return e.push({role:"error",text:"Usage: /model-add <provider> [api-key] <model-id> — /byok lists the providers. A vendor this catalog does not name yet: /model-add custom <https-base-url> <api-key> <model-id>. Example: /model-add deepseek sk-xxxxxxxx deepseek-v4.3-preview"}),!0;const r=splitCommandWords(String(n._rest||"").trim());let s=r.length&&r[0].toLowerCase()===o.toLowerCase()?r.slice(1):r;const a=await byokCatalog(e.client),i=a?findByokProvider(a,o):null;if(i&&i.ambiguous)return e.push({role:"error",text:`"${o}" matches ${i.ambiguous.join(", ")} — retype the exact id.`}),!0;if(a&&(!i||!i.provider))return e.push({role:"error",text:`no provider "${o}" in the relay's catalog — /byok lists the ones it takes a key for.`}),!0;const l=i&&i.provider&&i.provider.id||o.toLowerCase();let d="",c="";if("custom"===l){if(1===s.length&&!savedByokBaseURL(e,l))return e.push({role:"error",text:"one word cannot say whether it is the URL or the model id — nothing was saved. Type the endpoint first: /model-add custom <https-base-url> <api-key> [model-id]"}),!0;s.length>=2&&(d=s.shift(),c=s.shift())}else s.length>=2&&(c=s.shift());let u=s.join(" ").trim();if(c){const t=e.settings&&e.settings();if(!t||"function"!=typeof t.set)return e.push({role:"error",text:"this client has no provider-key store."}),!0;const n=i&&i.provider;n&&n.key_prefix&&!c.startsWith(n.key_prefix)&&e.push({role:"note",text:`heads up: ${l} keys normally start with "${n.key_prefix}" — saved anyway.`}),d&&!/^https:\/\//i.test(d)&&e.push({role:"note",text:"heads up: aegis1 only dials an https:// base_url — saved anyway, but calls on it will be refused."}),t.set(e.byokNamespace(l),{key:c,...d?{baseURL:d}:{}});try{const{envVarFor:t,setEnvValue:n}=require(resolveShared(path.join("client","env-file.js"))),o=t(l);if(o){const t=n(o,c);t.ok||e.push({role:"note",text:`heads up: could not mirror the key into ~/.aegiscode/.env (${t.error}).`})}}catch{}e.push({role:"done",text:d?`saved a ${l} key and base URL (${d}) on this machine.`:`saved a ${l} key on this machine.`})}const p=byokKeyForProvider(e,l),h=await offeredModelIds(e,l,p);if("*"===u){if(!h){const t=await discoverProviderModels(e,l,p);return e.push({role:"error",text:`cannot list ${l}: ${t&&t.error||"no list available"} — type the ids instead: /model-add ${l} <model-id>`}),!0}const t=addManyUserModels(l,h);if("function"==typeof e.refreshByokModels)try{await e.refreshByokModels()}catch{}return e.push({role:"done",text:`added ${t.added} of the ${h.length} model ids ${l} serves${t.already.length?` (${t.already.length} were already declared)`:""}.`}),t.capped&&e.push({role:"note",text:`stopped at the store's per-provider cap (32) — ${t.capped} more id(s) were left out; /model-add ${l} <model-id> stores a specific one, /model-rm frees a slot.`}),t.failed.length&&e.push({role:"note",text:`${t.failed.length} id(s) were refused: ${t.failed.map(e=>e.id).join(", ")}`}),e.push({role:"note",text:`stored in ${userModelsPath()} — the desktop reads the same file. /model-discover ${l} lists what the vendor serves.`}),!0}if(!u){h&&e.push({role:"note",text:`${l} serves ${h.length} model ids — ${h.slice(0,12).join(", ")}${h.length>12?", …":""}`});const t=String(await e.askInput(h?`model id for ${l} (1-${h.length}, or type one): `:`model id for ${l}: `)||"").trim(),n=h&&/^\d+$/.test(t)?Number(t):0;u=h&&n>=1&&n<=h.length?h[n-1]:t}if(!u)return e.push({role:"note",text:"nothing saved."}),!0;let m;try{m=addUserModel(l,u)}catch(t){return e.push({role:"error",text:t&&t.message||String(t)}),!0}if("function"==typeof e.refreshByokModels)try{await e.refreshByokModels()}catch{}const g=(("function"==typeof e.listModelsFor?await e.listModelsFor("byok"):[])||[]).find(e=>e&&e.id===`${l}:${u}`);return e.push({role:m.added?"done":"note",text:m.added?`added ${l}:${u} — offered on this machine now, in the CLI and the desktop.`:`${l}:${u} was already declared.`}),a||e.push({role:"note",text:`the relay's catalog could not be read, so "${l}" is unverified — if it does not appear in /models, /byok lists the provider ids it takes.`}),m.added&&!g&&e.push({role:"note",text:`saved, but no row will be offered for "${l}" yet — the relay lists no provider of that id (or that provider lists no models).`}),m.added&&h&&e.push({role:"note",text:`${l} currently serves ${h.length} model ids — /model-discover ${l} lists them, /model-add ${l} '*' takes them all.`}),e.push({role:"note",text:`stored in ${m.file} — the desktop reads the same file.`}),!0}},{name:"model-discover",aliases:["discover-models","vendor-models"],args:["provider"],hint:"<provider>",category:"model",desc:"List the model ids your provider's own API serves",handler:async(e,t)=>{const n=String((t||{}).provider||"").trim();if(!n)return e.push({role:"error",text:`Usage: /model-discover <provider> — this client can ask: ${discoverableProviders().join(", ")}`}),!0;const o=await byokCatalog(e.client),r=o?findByokProvider(o,n):null,s=(r&&r.provider&&r.provider.id||n).toLowerCase(),a=vendorEndpointFor(s);if(!a)return e.push({role:"error",text:`no list endpoint for "${s}" in this client — /model-add ${s} <model-id> stores an id you already know. Providers it can ask: ${discoverableProviders().join(", ")}`}),!0;const i=byokKeyForProvider(e,s);if(!i)return e.push({role:"error",text:`no ${s} key on this machine — /byok-key ${s} saves one (or put it in ~/.aegiscode/.env), then this lists what the key reaches.`}),!0;const l=await discoverProviderModels(e,s,i);if(!l||!l.ok)return e.push({role:"error",text:`could not list ${s}: ${l&&l.error||"no answer"}`}),!0;const d=new Set(userModelIdsFor(s)),c=new Set((r&&r.provider&&r.provider.models||[]).map(e=>String(e)));e.push({role:"note",text:`${s} at ${a.url}${a.note?` (${a.note})`:""}`}),e.push({role:"note",text:`${l.count} chat model id(s) the vendor serves — mark: [seen] the relay already lists it, [your] you declared it, [new] this machine does not offer it yet.`});const u=l.ids.map((e,t)=>{const n=d.has(e)?"[your]":c.has(e)?"[seen]":"[new]";return`${String(t+1).padStart(3)}. ${n} ${e}`});u.length&&e.push({role:"panel",lines:u}),u.length||e.push({role:"note",text:`the vendor answered with no chat models — /model-add ${s} <model-id> stores one by hand.`}),l.others.length&&e.push({role:"note",text:`${l.others.length} id(s) are not chat models (embeddings, audio, moderation or an unsupported method) and are left out: ${l.others.slice(0,8).join(", ")}${l.others.length>8?", …":""}`});const p=l.ids.filter(e=>!d.has(e)&&!c.has(e));return p.length&&e.push({role:"note",text:`${p.length} of them are not offered on this machine yet — /model-add ${s} '<model-id>' stores one, /model-add ${s} '*' stores every chat model the vendor serves.`}),!0}},{name:"models-sync",aliases:["sync-models","model-sync"],args:["provider"],hint:"[provider|all] [apply] | auto on|off",category:"model",desc:"Check the models AEGIS promotes against what each vendor's own API issues",handler:async(e,t)=>{const n=t||{},o=splitCommandWords(String(n._rest||"")).map(e=>e.toLowerCase());if("auto"===o[0]){const t=o[1]||"",n=()=>getModelAutoSync();if("on"!==t&&"off"!==t&&"status"!==t){const t=n();return e.push({role:"note",text:`model auto-sync is ${t?"on":"off"} — /models-sync auto on turns it on, /models-sync auto off turns it off.`}),!0}if("status"===t){const t=n();return e.push({role:"note",text:t?"model auto-sync is on — whichever host is open checks the vendors about once a day and adds what they issue but this machine does not offer.":"model auto-sync is off — /models-sync auto on enables it; /models-sync all apply does one run now."}),!0}const r="on"===t;return setModelAutoSync(r),e.push({role:"done",text:r?"model auto-sync on — checks run about once a day in whichever host is open, adding ids a vendor issues that nothing here offers. Nothing is ever removed, and /model-rm undoes any addition.":"model auto-sync off — nothing runs in the background; /models-sync all apply still works by hand."}),!0}const r=o.includes("apply"),s=String(n.provider||"").trim(),a=s&&"all"!==s.toLowerCase()&&"apply"!==s.toLowerCase()?s:"",i=await byokCatalog(e.client);if(!i)return e.push({role:"error",text:"could not read the BYOK provider catalog (offline, or the account has no relay yet) — /models-sync needs that list to know which vendors to ask."}),!0;const l={};for(const t of modelSync.askableProviders(i,a)){const n=byokKeyForProvider(e,t);n&&(l[t]=n)}const d=await modelSync.plan(i,{keys:l,fetchImpl:e&&e.fetchImpl,only:a});for(const t of d.failed||[])e.push({role:"note",text:`${t.provider}: ${t.error}`});for(const t of d.skipped||[])e.push({role:"note",text:`${t.provider}: ${t.reason} — /byok-key ${t.provider} saves one (or put it in ~/.aegiscode/.env).`});if(!d.ok)return e.push({role:"error",text:`${modelSync.summary(d)}. Providers this client can ask: ${discoverableProviders().join(", ")}.`}),!0;for(const t of d.providers)t.missing.length?(e.push({role:"note",text:`${t.provider} at ${t.endpoint}: ${t.missing.length} id(s) the vendor issues that this machine does not offer${t.notChat?` (${t.notChat} non-chat id(s) left out of the vendor's answer)`:""}.`}),e.push({role:"panel",lines:t.missing.map((e,t)=>`${String(t+1).padStart(3)}. ${e}`)}),t.stale.length&&e.push({role:"note",text:`${t.provider}: ${t.stale.length} id(s) listed here that the vendor's list no longer carries — left in place (a de-listed id usually still runs): ${t.stale.slice(0,8).join(", ")}${t.stale.length>8?", …":""}`})):e.push({role:"note",text:`${t.provider}: in sync — ${t.issued} id(s) issued, all offered here${t.stale.length?` (${t.stale.length} listed here the vendor no longer issues)`:""}.`});if(!d.missing)return e.push({role:"done",text:modelSync.summary(d)}),!0;if(!r)return e.push({role:"note",text:`${modelSync.summary(d)} Nothing was changed — /models-sync ${a||"all"} apply stores ${d.missing} id(s), or /model-add <provider> '<model-id>' picks one.`}),!0;const c=modelSync.apply(d,{only:a});if("function"==typeof e.refreshByokModels)try{await e.refreshByokModels()}catch{}e.push({role:"done",text:`added ${c.added} model id(s)${c.already?` (${c.already} were already declared)`:""}${c.failed.length?` — ${c.failed.length} refused`:""}.`});for(const t of c.failed.slice(0,8))e.push({role:"note",text:`${t.provider} ${t.id}: ${t.reason}`});return c.capped&&e.push({role:"note",text:`stopped at the store's per-provider cap (32) — ${c.capped} more id(s) were left out; /model-rm frees a slot.`}),!0}},{name:"model-rm",aliases:["rm-model"],args:["provider"],hint:"<provider> <model-id>",category:"model",desc:"Forget a model id you added with /model-add",handler:async(e,t)=>{const n=t||{},o=String(n.provider||"").trim(),r=String(n._rest||"").trim(),s=r.indexOf(" "),a=-1===s?"":r.slice(s+1).trim();if(!o||!a)return e.push({role:"error",text:"Usage: /model-rm <provider> <model-id> — /model-add lists what you added."}),!0;let i;try{i=removeUserModel(o,a)}catch(t){return e.push({role:"error",text:t&&t.message||String(t)}),!0}if("function"==typeof e.refreshByokModels)try{await e.refreshByokModels()}catch{}return e.push({role:i.removed?"done":"note",text:i.removed?`removed ${i.provider}:${i.model} — the picker stops offering it on the next refresh.`:`${i.provider}:${i.model} was not declared on this machine.`}),!0}},{name:"tool",args:["name","json"],hint:"<name> [json]",category:"aegis",desc:"Call any registry tool directly (escape hatch for new tools)",generic:!0,build:e=>{const t=String(e||""),n=t.indexOf(" "),o=(-1===n?t:t.slice(0,n)).trim(),r=-1===n?"":t.slice(n+1).trim();let s={};if(r)try{s=JSON.parse(r)}catch(e){throw new Error(`/tool: arguments must be JSON — ${e.message}`)}return{tool:o,args:s}}},{name:"aegis-import",aliases:["import"],hint:"[--confirm]",category:"aegis",desc:"Import memory from other AI tools on this machine (dry run unless --confirm)",tool:"aegis_memory_import",build:e=>({confirm:/--confirm\b/.test(String(e||""))})}],BY_NAME=new Map;for(const e of COMMANDS)for(const t of[e.name,...e.aliases||[]]){if(BY_NAME.has(t))throw new Error(`aegiscode: command name or alias /${t} is registered twice`);BY_NAME.set(t,e)}function allCommands(){return COMMANDS.map(e=>({...e,categoryLabel:categoryLabel(e.category)}))}function visibleCommands(){return allCommands().filter(e=>!("function"==typeof e.hidden?e.hidden():e.hidden))}function findCommand(e){return BY_NAME.get(String(e||"").toLowerCase())||null}function canonicalName(e){const t=findCommand(e);return t?t.name:e}function parseLine(e){const t=String(null==e?"":e).trim();if(!t)return{kind:"empty"};if("/"!==t[0])return{kind:"prompt",text:t};const n=t.indexOf(" "),o=(-1===n?t.slice(1):t.slice(1,n)).trim(),r=-1===n?"":t.slice(n+1).trim(),s=findCommand(o);return s?s.unavailable?{kind:"unavailable",command:s,arg:r}:{kind:"command",command:s,arg:r}:{kind:"unknown",name:o,text:t}}function toolBackedCommands(){return COMMANDS.filter(e=>e.tool)}module.exports={CATEGORIES:CATEGORIES,categoryLabel:categoryLabel,EFFORT_LEVELS:EFFORT_LEVELS,COMMANDS:COMMANDS,allCommands:allCommands,visibleCommands:visibleCommands,findCommand:findCommand,canonicalName:canonicalName,parseLine:parseLine,toolBackedCommands:toolBackedCommands,runAutoModelSync:runAutoModelSync,backfillSessionNames:backfillSessionNames};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
|
+
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
+
"use strict";const path=require("node:path"),fs=require("node:fs"),{aegisDir:aegisDir,memoryPersistEnabled:memoryPersistEnabled}=require("./config.js"),{ensurePrivateDir:ensurePrivateDir,writePrivateFile:writePrivateFile}=require("./securefs.js"),{readHistoryEntries:readHistoryEntries}=require("./history.js"),{buildWikiPages:buildWikiPages,pagesToStagedEntries:pagesToStagedEntries}=require("./dream.js"),DAY_MS=864e5,DURATION_UNITS={s:1e3,m:6e4,h:36e5,d:DAY_MS,w:7*DAY_MS};function durationMs(e){const t=String(e||"").trim().toLowerCase();if(!t)return null;const r=/^(\d+(?:\.\d+)?)([smhdw]?)$/.exec(t);if(!r)return null;const n=Number.parseFloat(r[1]);if(!Number.isFinite(n)||n<=0)return null;const i=r[2]||"d";return n*DURATION_UNITS[i]}function parseDreamFlags(e){const t={json:!1,dryRun:!1,promote:!1,since:null,instructions:null,help:!1},r=e||[];for(let e=0;e<r.length;e++){const n=r[e];if("--json"!==n)if("--dry-run"!==n)if("--promote"!==n)if("--help"!==n&&"-h"!==n)if("--since"!==n)if(n.startsWith("--since="))t.since=n.slice(8);else if("--instructions"!==n){if(!n.startsWith("--instructions="))throw new Error(`unknown option: ${n}`);t.instructions=n.slice(15)}else t.instructions=r[++e];else t.since=r[++e];else t.help=!0;else t.promote=!0;else t.dryRun=!0;else t.json=!0}return t}const USAGE="aegiscode dream [--since 7d] [--instructions \"...\"] [--dry-run] [--promote] [--json]\n\nBuild (or extend) the local wiki over this machine's own transcripts and this\naccount's cloud memory notes. Offline, deterministic by default — no cloud\nwrite unless --promote is given.\n\n --since <dur> how far back to read (default 7d; also 24h, 30m, 2w)\n --instructions <txt> accepted and echoed back; has no effect yet — Phase 1/2\n run no model, so there is nothing for it to steer\n --dry-run print the report, write nothing to dream-wiki.json\n (cannot be combined with --promote)\n --promote push the current pages to cloud memory via\n memorySaveBatch (upsert by id — safe to re-run).\n Refused if cloud memory sync is off (/cloud memory on\n to enable) or there is no account key. Nothing is ever\n deleted from the cloud: a bad dream is only\n discardable before it was promoted.\n --json machine-readable report instead of text\n";function wikiStorePath(){return path.join(aegisDir(),"dream-wiki.json")}function readStagedWiki(){try{const e=fs.readFileSync(wikiStorePath(),"utf8"),t=JSON.parse(e);return{pages:Array.isArray(t.pages)?t.pages:[],updatedAt:t.updatedAt||null}}catch{return{pages:[],updatedAt:null}}}function writeStagedWiki(e,{now:t=Date.now()}={}){const r=wikiStorePath();try{ensurePrivateDir(path.dirname(r));try{fs.unlinkSync(r)}catch{}return writePrivateFile(r,`${JSON.stringify({pages:e,updatedAt:t},null,2)}\n`,{atomic:!1}),{ok:!0,file:r}}catch(e){return{ok:!1,reason:e.message}}}function gatherTranscripts(e){const t=[];for(const r of readHistoryEntries()){const n=Date.parse(r.ts||"")||0;n<e||r.sessionId&&(r.prompt&&t.push({sessionId:r.sessionId,role:"user",text:r.prompt,ts:n}),r.reply&&t.push({sessionId:r.sessionId,role:"assistant",text:r.reply,ts:n}))}return t}async function gatherNotes(e,t){if(!t||!t.apiKey)return[];try{const r=await t.memoryPull(e);return(r&&r.entries||[]).map(e=>({id:String(e.id||""),body:String(e.content||e.body||e.text||""),updated:Number(e.updated??e.updated_at)||Date.parse(e.timestamp||"")||0}))}catch{return[]}}async function promoteToCloud(e,t){if(!memoryPersistEnabled())return{ok:!1,reason:"cloud memory sync is off (memoryPersist=false). A dream only reads local transcripts until --promote; promoting would be the first upload of them. Enable it first with /cloud memory on (or the memoryPersist config key) if this is wanted."};if(!t||!t.apiKey){const e=require("./credentials.js");return{ok:!1,reason:`no AEGIS account key — ${e.HOW_TO_SET}, or set ${e.KEY_ENV}`}}const r=pagesToStagedEntries(e);if(!r.length)return{ok:!0,saved:0};try{const e=await t.memorySaveBatch(r);return{ok:!0,saved:e&&e.saved||r.length}}catch(e){return{ok:!1,reason:e.message}}}function searchStagedWiki(e,t,r=5){const n=String(t||"").trim().toLowerCase();return n?e.filter(e=>`${e.title}\n${e.body}`.toLowerCase().includes(n)).slice(0,r):[]}function createLocalWiki(){return{search(e,t){const{pages:r}=readStagedWiki();return searchStagedWiki(r,e,t)}}}async function runDreamCommand(e,t={}){const r=t.stdout||process.stdout,n=t.stderr||process.stderr;let i;try{i=parseDreamFlags(e)}catch(e){return n.write(`aegiscode dream: ${e.message}\n`),2}if(i.help)return r.write(USAGE),0;if(i.promote&&i.dryRun)return n.write("aegiscode dream: --promote and --dry-run are contradictory — a dry run writes nothing, promote writes to the cloud\n"),2;const s=i.since||"7d",o=durationMs(s);if(null===o)return n.write(`aegiscode dream: bad --since value "${s}" (try 7d, 24h, 30m)\n`),2;const a=Date.now()-o,d=require("./credentials.js"),u=require("./deps.js").createClient(d.clientOptions({channel:"cli"})),c=gatherTranscripts(a),l=await gatherNotes(a,u),m=readStagedWiki().pages,{pages:p,report:g}=buildWikiPages({notes:l,transcripts:c,existingPages:m});let h={ok:!1};i.dryRun||(h=writeStagedWiki(p));let f=null;if(i.promote&&(f=await promoteToCloud(p,u)),i.json)return r.write(`${JSON.stringify({since:s,instructions:i.instructions||null,report:g,pages:p.map(e=>({title:e.title,value:e.value,links:e.links})),dryRun:i.dryRun,written:i.dryRun?null:h,promoted:f},null,2)}\n`),f&&!f.ok?1:0;if(r.write(`aegiscode dream: ${c.length} local turn(s), ${l.length} cloud note(s) since ${s}\n`),r.write(` pages: ${g.pagesCreated} created, ${g.pagesExtended} extended, ${g.linksAdded} link(s) added (${p.length} total)\n`),i.instructions&&r.write(" --instructions was given but has no effect yet (no model call in this phase)\n"),i.dryRun)r.write(" dry run — nothing written\n");else{if(!h.ok)return n.write(`aegiscode dream: could not stage the wiki: ${h.reason}\n`),1;r.write(` staged to ${h.file}\n`)}if(f){if(!f.ok)return n.write(`aegiscode dream: --promote refused: ${f.reason}\n`),1;r.write(` promoted ${f.saved} entr${1===f.saved?"y":"ies"} to cloud memory\n`)}return 0}module.exports={parseDreamFlags:parseDreamFlags,durationMs:durationMs,wikiStorePath:wikiStorePath,readStagedWiki:readStagedWiki,writeStagedWiki:writeStagedWiki,gatherTranscripts:gatherTranscripts,gatherNotes:gatherNotes,promoteToCloud:promoteToCloud,searchStagedWiki:searchStagedWiki,createLocalWiki:createLocalWiki,runDreamCommand:runDreamCommand,USAGE:USAGE};
|
|
@@ -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{createHash:createHash}=require("node:crypto"),{existsSync:existsSync,readFileSync:readFileSync}=require("node:fs"),path=require("node:path"),PACKAGE_ROOT=path.join(__dirname,".."),SALT="aegiscode-interlock-v1",PAD="aegis-interlock-pad-v1",sha256=e=>createHash("sha256").update(e).digest("hex"),PAD_HEX=sha256(PAD);function unmask(e){let t="";for(let r=0;r<e.length;r++){const n=parseInt(e[r],16),i=parseInt(PAD_HEX[r%PAD_HEX.length],16);if(Number.isNaN(n)||Number.isNaN(i))return null;t+=(n^i).toString(16)}return t}const UNITS=Object.freeze([{id:"p1",rel:Buffer.from("YmluL2FlZ2lzY29kZS5qcw==","base64").toString("utf8")},{id:"p2",rel:Buffer.from("c3JjL3Byb3ZlbmFuY2UuanM=","base64").toString("utf8")},{id:"p3",rel:Buffer.from("c3JjL2dhdGUuanM=","base64").toString("utf8")},{id:"p4",rel:Buffer.from("c3JjL3Blcm1pc3Npb25zLmpz","base64").toString("utf8")},{id:"p5",rel:Buffer.from("c3JjL2NhcHMuanM=","base64").toString("utf8")},{id:"p6",rel:Buffer.from("c3JjL2F1dG9ub21vdXMuanM=","base64").toString("utf8")},{id:"p8",rel:Buffer.from("c3JjL21jcC5qcw==","base64").toString("utf8")}]),SEALED="
|
|
3
|
+
"use strict";const{createHash:createHash}=require("node:crypto"),{existsSync:existsSync,readFileSync:readFileSync}=require("node:fs"),path=require("node:path"),PACKAGE_ROOT=path.join(__dirname,".."),SALT="aegiscode-interlock-v1",PAD="aegis-interlock-pad-v1",sha256=e=>createHash("sha256").update(e).digest("hex"),PAD_HEX=sha256(PAD);function unmask(e){let t="";for(let r=0;r<e.length;r++){const n=parseInt(e[r],16),i=parseInt(PAD_HEX[r%PAD_HEX.length],16);if(Number.isNaN(n)||Number.isNaN(i))return null;t+=(n^i).toString(16)}return t}const UNITS=Object.freeze([{id:"p1",rel:Buffer.from("YmluL2FlZ2lzY29kZS5qcw==","base64").toString("utf8")},{id:"p2",rel:Buffer.from("c3JjL3Byb3ZlbmFuY2UuanM=","base64").toString("utf8")},{id:"p3",rel:Buffer.from("c3JjL2dhdGUuanM=","base64").toString("utf8")},{id:"p4",rel:Buffer.from("c3JjL3Blcm1pc3Npb25zLmpz","base64").toString("utf8")},{id:"p5",rel:Buffer.from("c3JjL2NhcHMuanM=","base64").toString("utf8")},{id:"p6",rel:Buffer.from("c3JjL2F1dG9ub21vdXMuanM=","base64").toString("utf8")},{id:"p8",rel:Buffer.from("c3JjL21jcC5qcw==","base64").toString("utf8")}]),SEALED="42b7689fd5fd8cad4ee0070866c7bc9b68f04c0b324c32431d71c958331350fd",PRIVILEGED=Object.freeze(["gate","provenance","mcp"]);function check(){const e=[];for(const t of UNITS){const r=path.join(PACKAGE_ROOT,t.rel);if(!existsSync(r))return{tripped:!0,code:"p1",units:UNITS.length};try{e.push(sha256(readFileSync(r)))}catch{return{tripped:!0,code:"p1",units:UNITS.length}}}const t=sha256(`${SALT}\n${e.join("\n")}`),r=SEALED.trim();return 64!==r.length?{tripped:!0,code:"p2",units:UNITS.length}:unmask(r)!==t?{tripped:!0,code:"p3",units:UNITS.length}:{tripped:!1,code:null,units:UNITS.length}}function line(e){return e&&e.tripped?`aegiscode: reduced mode (${e.code}) — this build is not the one that was published.\n`:null}let ARMED=null;function armed(){if(null!==ARMED)return ARMED;let e;try{e=check()}catch{e={tripped:!0,code:"p2",units:UNITS.length}}if(ARMED=Boolean(e.tripped),ARMED){process.env.AEGIS_REDUCED_MODE="1";const t=line(e);t&&process.stderr.write(t)}return ARMED}function isPrivileged(e){return PRIVILEGED.includes(e)}function refuse(){return 1}function sealOf(e){const t=e.map(e=>sha256(readFileSync(e)));return sha256(`${SALT}\n${t.join("\n")}`)}module.exports={UNITS:UNITS,PRIVILEGED:PRIVILEGED,SALT:SALT,PAD:PAD,check:check,armed:armed,line:line,isPrivileged:isPrivileged,refuse:refuse,sealOf:sealOf,mask:e=>unmask(e)};
|
|
@@ -24,13 +24,13 @@
|
|
|
24
24
|
"license": "AGPL-3.0-or-later",
|
|
25
25
|
"source": "https://github.com/aegisinfo/aegiscode-plugin",
|
|
26
26
|
"units": {
|
|
27
|
-
"p1": "
|
|
27
|
+
"p1": "49709650e67546d1a3d9d6c173bb9e5b1bb1fd6a59f0b04ac754ab72a8f0d04c",
|
|
28
28
|
"p2": "d63d147de5455eea111d000b748d7eef9572a11a08d31f2471d5ff146701342c",
|
|
29
29
|
"p3": "ff962ac8dbf42cecb2477e2f77bf5ec61f88aa1751b0d4e506bf030fbc5fc6c6",
|
|
30
30
|
"p4": "43851f41ff482c7a185b75bbb55f9ce8f31af8e9a3adccbfaf57a8d570adbfbf",
|
|
31
31
|
"p5": "408d67f78f31f6d637a26d2852e0c809a260544e613afdc64b731401c0ba3801",
|
|
32
|
-
"p6": "
|
|
33
|
-
"p7": "
|
|
32
|
+
"p6": "1fe9af1a50ba43713bcd780a9993933af52eb0a9acfdab1e9880fc86a4dcfd55",
|
|
33
|
+
"p7": "5db6653343b2268c3c6fcd375b67a081a4253cd7a685b57c06909fede9cf7aba",
|
|
34
34
|
"p8": "3cc054d06715e065fe635b37b7d1bb98bf7989d64453a572ddbb77cec5b830e7"
|
|
35
35
|
}
|
|
36
36
|
}
|