aegiscode 7.0.24 → 7.0.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/package.json +7 -3
  2. package/scripts/check.mjs +52 -1
  3. package/scripts/demo.mjs +94 -1
  4. package/scripts/predist.mjs +75 -1
  5. package/scripts/runtests.mjs +56 -1
  6. package/scripts/seal-gate.mjs +74 -1
  7. package/src/agents.js +139 -1
  8. package/src/app.js +2957 -1
  9. package/src/art.js +289 -1
  10. package/src/chatflow.js +3023 -1
  11. package/src/checkpoint.js +90 -1
  12. package/src/clipboard.js +424 -1
  13. package/src/cloudsync.js +528 -1
  14. package/src/commands.js +4089 -1
  15. package/src/config.js +581 -1
  16. package/src/connect.js +349 -1
  17. package/src/credentials.js +33 -1
  18. package/src/deps.js +232 -1
  19. package/src/devrun.js +187 -1
  20. package/src/diff.js +333 -1
  21. package/src/diffview.js +296 -1
  22. package/src/engine.js +297 -1
  23. package/src/entitlement.js +355 -1
  24. package/src/events.js +707 -1
  25. package/src/export.js +67 -1
  26. package/src/filepreview.js +153 -1
  27. package/src/fingerprint.js +592 -1
  28. package/src/format.js +259 -1
  29. package/src/fuzzy.js +119 -1
  30. package/src/history.js +423 -1
  31. package/src/init.js +175 -1
  32. package/src/input.js +139 -1
  33. package/src/keys.js +183 -1
  34. package/src/markdown.js +306 -1
  35. package/src/models.js +507 -1
  36. package/src/naming.js +57 -1
  37. package/src/overlays.js +462 -1
  38. package/src/panels.js +1418 -1
  39. package/src/ping.js +226 -1
  40. package/src/presence.js +238 -1
  41. package/src/render.js +516 -1
  42. package/src/screen.js +518 -1
  43. package/src/screens.js +896 -1
  44. package/src/secret.js +59 -1
  45. package/src/securefs.js +359 -1
  46. package/src/settings.js +155 -1
  47. package/src/shared.js +52 -1
  48. package/src/sharedpaths.js +53 -1
  49. package/src/signup.js +156 -1
  50. package/src/summarize.js +95 -1
  51. package/src/sysdiag.js +585 -1
  52. package/src/system.js +40 -1
  53. package/src/theme.js +570 -1
  54. package/src/title.js +220 -1
  55. package/src/todos.js +115 -1
  56. package/src/tokens.js +263 -1
  57. package/src/topup.js +210 -1
  58. package/src/update.js +191 -1
  59. package/vendor/client/aegis.js +2441 -1
  60. package/vendor/client/attest.js +518 -1
  61. package/vendor/client/authorship-key.js +410 -1
  62. package/vendor/client/auto-provision.js +134 -1
  63. package/vendor/client/brain-catalog.js +268 -1
  64. package/vendor/client/byok-catalog.js +199 -1
  65. package/vendor/client/catalog-client.js +487 -1
  66. package/vendor/client/conversation-export.js +177 -1
  67. package/vendor/client/credentials.js +494 -1
  68. package/vendor/client/device-fingerprint.js +141 -1
  69. package/vendor/client/drive-connect.js +110 -1
  70. package/vendor/client/drive-upload.js +234 -1
  71. package/vendor/client/env-file.js +1273 -1
  72. package/vendor/client/fingerprint.js +1064 -1
  73. package/vendor/client/foreign-memory.js +669 -1
  74. package/vendor/client/google-signin.js +133 -1
  75. package/vendor/client/hooks.js +430 -1
  76. package/vendor/client/model-discovery.js +373 -1
  77. package/vendor/client/naming.js +283 -1
  78. package/vendor/client/platform.js +937 -1
  79. package/vendor/client/prefs.js +351 -1
  80. package/vendor/client/presence-constants.js +107 -1
  81. package/vendor/client/presence.js +438 -1
  82. package/vendor/client/record-vault.js +1055 -3
  83. package/vendor/client/session-store.js +575 -1
  84. package/vendor/client/topup.js +297 -1
  85. package/vendor/client/touch.js +458 -1
  86. package/vendor/client/update.js +763 -1
  87. package/vendor/client/user-models.js +381 -1
  88. package/vendor/desktop/lib/local/agents.js +105 -1
  89. package/vendor/desktop/lib/local/attachments.js +276 -1
  90. package/vendor/desktop/lib/local/autonomous.js +1045 -1
  91. package/vendor/desktop/lib/local/claude-pro.js +1028 -1
  92. package/vendor/desktop/lib/local/context.js +125 -1
  93. package/vendor/desktop/lib/local/engine.js +3666 -1
  94. package/vendor/desktop/lib/local/entitlement.js +660 -1
  95. package/vendor/desktop/lib/local/git-scope.js +228 -1
  96. package/vendor/desktop/lib/local/local.js +2145 -1
  97. package/vendor/desktop/lib/local/prompt.js +280 -1
  98. package/vendor/desktop/lib/local/queue.js +560 -1
  99. package/vendor/desktop/lib/local/session-rounds.js +238 -1
  100. package/vendor/desktop/lib/local/spill.js +75 -1
  101. package/vendor/desktop/lib/local/turn-guard.js +300 -1
  102. package/vendor/desktop/lib/local/worktree-lock.js +235 -1
  103. package/vendor/desktop/lib/settings.js +890 -1
  104. package/vendor/desktop/renderer/usage.js +1239 -1
  105. package/vendor/hosts/install.js +638 -1
  106. package/vendor/hosts/openai-shim.js +515 -1
  107. package/vendor/hosts/spec.js +164 -1
  108. package/vendor/hosts/targets.js +346 -1
  109. package/vendor/mcp/server.js +221 -1
  110. package/vendor/mcp/tools.js +408 -1
  111. package/vendor/one/src/child.js +285 -1
  112. package/vendor/one/src/permissions.js +383 -1
  113. package/SOURCE-OFFER.txt +0 -9
package/src/app.js CHANGED
@@ -1,3 +1,2959 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- "use strict";const readline=require("node:readline"),os=require("node:os"),{randomUUID:randomUUID}=require("node:crypto"),{createTools:createTools,createClient:createClient,usageTokens:usageTokens,usageBuckets:usageBuckets,buildSystemPrompt:buildSystemPrompt,autoProvisionApiKey:autoProvisionApiKey,provisionFailureText:provisionFailureText,trialNote:trialNote,hostEnv:hostEnv,autonomous:autonomous,claudePro:claudePro}=require("./deps.js"),{createEngine:createEngine,HOST_CLASSES:HOST_CLASSES,DEFAULT_CLASS:DEFAULT_CLASS,byokNamespace:byokNamespace,effortRung:effortRung,offeredClasses:offeredClasses,proEnabled:proEnabled}=require("./engine.js"),{GLYPH:GLYPH,VERBS:VERBS,themeOf:themeOf,RESET:RESET,THEME_TABLE:THEME_TABLE,AUTO_THEME_INDEX:AUTO_THEME_INDEX,themeIsLight:themeIsLight,reconcileThemeIndex:reconcileThemeIndex}=require("./theme.js"),{probeTerminalBackground:probeTerminalBackground}=require("./caps.js"),{LiveRegion:LiveRegion,termWidth:termWidth,w:w}=require("./screen.js"),{estimateTokensFromCells:estimateTokensFromCells}=require("./tokens.js"),{editPreview:editPreview}=require("./diff.js"),{defaultOpen:defaultOpen}=require("./diffview.js"),{parseLine:parseLine,COMMANDS:COMMANDS,visibleCommands:visibleCommands}=require("./commands.js"),{updateConfig:updateConfig,loadPermissions:loadPermissions,loadConfig:loadConfig,configExists:configExists,memoryPersistState:memoryPersistState,memoryPersistEnabled:memoryPersistEnabled,setMemoryPersist:setMemoryPersist,confirmPosture:confirmPosture}=require("./config.js"),credentials=require("./credentials.js"),events=require("./events.js"),cloudsync=require("./cloudsync.js"),{readSecret:readSecret}=require("./secret.js"),{normalizeModelCatalog:normalizeModelCatalog,pickerEntries:pickerEntries,catalogIds:catalogIds,providerForModel:providerForModel}=require("./models.js"),{appendHistory:appendHistory,readSessionTranscript:readSessionTranscript,readOwnSessions:readOwnSessions,setSessionTitle:setSessionTitle}=require("./history.js"),naming=require("./naming.js"),{snapshotCheckpoint:snapshotCheckpoint}=require("./checkpoint.js"),screens=require("./screens.js"),chatflow=require("./chatflow.js"),overlays=require("./overlays.js"),render=require("./render.js"),{fmtTokens:fmtTokens,fmtEur:fmtEur,maskKey:maskKey,feeBillable:feeBillable}=require("./format.js"),{resolveSkip:resolveSkip}=require("./permissions.js"),VERSION=require("../package.json").version;let _defaultSystem=null;function defaultSystemPrompt(){if(null===_defaultSystem)try{_defaultSystem=buildSystemPrompt(hostEnv({},{},null))}catch{_defaultSystem=""}return _defaultSystem||void 0}function normalizeDecision(e){const t="string"==typeof e?e.trim().toLowerCase():"";return"session"===t?"session":"once"===t||"allow"===t||"yes"===t||"approve"===t||"approved"===t?"once":"deny"}const PROVIDER_REFUSAL_PATTERNS=Object.freeze([/^invalid api key\b/i,/^fix external api key\b/i,/^you've hit your session limit\b/i,/^you have hit your session limit\b/i,/^provider request timed out\b/i,/^insufficient (?:credit|balance|quota)\b/i,/^rate limit(?:ed)?\b/i,/^unauthorized\b/i]);function providerRefusal(e,t){if("string"!=typeof e)return null;const n=t&&(t.total_tokens||0),r=t&&(t.output_tokens||t.completion_tokens||0);if(n>0||r>0)return null;const o=e.trim();if(!o||o.length>160||o.includes("\n"))return null;for(const e of PROVIDER_REFUSAL_PATTERNS)if(e.test(o))return o;return null}function briefArgs(e){let t;try{t="string"==typeof e?e:JSON.stringify(e??"")}catch{t=String(e)}return t=String(t).replace(/\s+/g," ").trim(),t.length>140?`${t.slice(0,137)}...`:t}function createApp(e={}){const t={model:null,stream:!0,light:!1,maxTokens:void 0,system:void 0,interactive:!0,...e},n=e.out||process.stdout,r=e.err||process.stderr,o=e.client||createClient(credentials.clientOptions({channel:"cli"})),{TOOLS:s,toolList:i}=e.tools||createTools(o);let a=!1,l="";async function c(){const e=await autoProvisionApiKey(o,credentials,{app:"cli"});return l=e.key?"":provisionFailureText(e),e}async function d(){if(o.apiKey||a)return;a=!0;const e=await c();e.key&&Y(render.renderNotice(b(),"info","auto-provisioned a free account"+(e.ok?` (saved to ${credentials.credentialsPath()})`:" (could not save it — reconfigure with /key)")+trialNote(e)+`. Fund it at ${o.promptUrl("topup","device_autoprovision")} or run /byok to use your own key.`))}let u=!1!==e.confirmMode,m=(()=>{try{return autonomous.autoRoundsDefault(process.env)}catch{return!0}})();const f=e.engine||createEngine({client:o,getClass:()=>g.modelClass,getProEnabled:()=>{try{return proEnabled(loadConfig())}catch{return!1}},getConfirmMode:()=>{if(void 0!==e.confirmMode)return u;try{const e=resolveSkip({env:process.env,interactive:Boolean(process.stdin.isTTY&&process.stdout.isTTY)});if(e.warned&&!skipEnvWarned&&(skipEnvWarned=!0,process.stderr.write(`aegiscode: ${e.warning}\n`)),e.skip)return!1}catch{}try{return confirmPosture().enabled}catch{return u}}}),p=e=>"function"==typeof f.classLabel?f.classLabel(e):String(e||"");let y=null;const h=()=>e.width?e.width():termWidth(),g={light:t.light,model:t.model,modelClass:DEFAULT_CLASS,effort:null,thinking:!1,recallDeep:!1,themeIndex:t.light?2:AUTO_THEME_INDEX,vim:!1,stream:t.stream,cwd:process.cwd(),lastRecap:null,sessionId:randomUUID()};g.themeIndex===AUTO_THEME_INDEX&&(g.light=themeIsLight(AUTO_THEME_INDEX));const k=[];let v=!1;const b=()=>({light:g.light}),S={turns:0,calls:0,tokens:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,cost:0,balance:null,seenLedgerRows:new Map,ledgerBaselined:!1,startedAt:Date.now()};let T=null,E=!1;function C(e){if(!e||"object"!=typeof e)return null;if("usage"!==e.kind)return null;const t=null!=e.amount_eur?Number(e.amount_eur):-Number(e.charged_micros||0)/1e6;return Number.isFinite(t)?Math.abs(t):null}function I(e){return[e.created_at||"",e.kind||"",null!=e.amount_eur?e.amount_eur:"",null!=e.charged_micros?e.charged_micros:"",null!=e.id?e.id:"",null!=e.note?e.note:""].join("|")}async function N(){try{const e=await o.tokenBankBalance(),t=Number(e.balance_eur);Number.isFinite(t)&&(S.balance=t);let n=null;const r=Array.isArray(e.ledger)?e.ledger:[],s=new Map;for(const e of r){const t=I(e),n=s.get(t);n?n.n+=1:s.set(t,{n:1,row:e})}for(const[e,{n:t,row:r}]of s){const o=S.seenLedgerRows.get(e)||0;if(S.seenLedgerRows.set(e,t),!S.ledgerBaselined)continue;const s=t-o;if(s<=0)continue;const i=C(r);null!=i&&i>0&&(S.cost+=i*s,null==n&&(n=i))}return S.ledgerBaselined=!0,{balance:S.balance,lastCost:n}}catch{return null}}async function P(e,{verify:t=!0}={}){const n=credentials.saveApiKey(e);if(!n.ok)return n;o.setApiKey(n.key),R.models=[],R.at=0;let r=null,s=null;if(t)try{const e=await o.verifyApiKey()||{};r=e;const t={verifiedAt:(new Date).toISOString()};e.memory_token&&(t.memoryToken=e.memory_token),e.plan&&(t.plan=e.plan),t.account={plan:e.plan||null,email:e.email||null,valid:!1!==e.valid},credentials.writeCredentials(t),e.plan&&(S.plan=e.plan),e.email&&(S.account={...S.account||{},email:e.email})}catch(e){s=e}return{...n,account:r,error:s}}function x(){const e=credentials.clearApiKey();return o.setApiKey(""),R.models=[],R.at=0,e}function A(){try{return memoryPersistEnabled()}catch{return!0}}function L(){try{return memoryPersistState()}catch{return{enabled:!0,source:"default",explicit:!1}}}function O(e){return setMemoryPersist(e)}function _(){try{return"config"!==credentials.resolveApiKey().source?[]:credentials.adoptLegacy().adopted}catch{return[]}}const M=3e5,R={at:0,models:[]},$={at:0,models:[],declared:""};async function K({force:e=!1}={}){const t=function(){try{if("function"!=typeof f.userModels)return"";const e=(f.userModels()||{}).map||{};return JSON.stringify(Object.keys(e).sort().map((t=>[t,e[t]])))}catch{return""}}(),n=$.models.length&&Date.now()-$.at<M&&t===$.declared;if(!e&&n)return $.models;if("function"!=typeof f.listModels)return[];const r=await f.listModels("byok");return $.models=(r&&r.models||[]).map((e=>({...e,note:e.configured?"key on this machine":`no key — /byok-key ${e.provider}`}))),$.at=Date.now(),$.declared=t,$.models}async function D(e){const t=H();if(e&&!t.includes(e)&&HOST_CLASSES.includes(e))return[];const n=t.includes(e)?e:g.modelClass;try{if("byok"===n){const e=await K();if(!R.models.length)try{await F()}catch{}return q(e,n)}if("pro"===n){const e=await f.listModels("pro");return e&&e.models||[]}if("aegis"!==n){const e=await f.listModels(n);return e&&e.models||[]}return await F()}catch{return[]}}function j(){return pickerEntries(R.models).map((e=>({...e,cls:"aegis"})))}function q(e,t){const n=H(),r=n.includes(t)?t:g.modelClass;if("pro"===t&&!n.includes("pro"))return[];if("pro"===r)return pickerEntries(claudePro.PRO_MODELS.map((e=>({id:e.id,label:e.label,note:e.note})))).map((e=>({...e,cls:"pro"})));if("byok"!==r)return j();const o=Array.isArray(e)?e.map((e=>({...e,cls:"byok"}))):pickerEntries($.models).map((e=>({...e,cls:"byok"})));return[...j(),...o]}function B(){return new Set(claudePro.PRO_MODELS.map((e=>String(e.id).toLowerCase())))}function H(){try{return offeredClasses(proEnabled(loadConfig()))}catch{return offeredClasses(!1)}}async function F({force:e=!1}={}){const t=R.models.length&&Date.now()-R.at<M;if(!e&&t)return R.models;const n=await o.listModels();return R.models=normalizeModelCatalog(n&&n.models),R.at=Date.now(),R.models}async function U(){const e=g.model;if(!e)return null;if("byok"===g.modelClass)return String(e).includes(":")?null:(g.model=null,updateConfig({model:null,currentModelId:null}),Y(render.renderNotice(b(),"warn",`pinned model "${e}" belongs to the pooled class — on BYOK an id is "<provider>:<model>"; pin cleared, /models lists what this machine can relay.`)),e);if("pro"===g.modelClass){if(!B().has(String(e).toLowerCase()))return g.model=null,updateConfig({model:null,currentModelId:null}),Y(render.renderNotice(b(),"warn",`pinned model "${e}" is not one the Claude Code CLI resolves — pin cleared, the CLI will choose; /models lists the aliases (${claudePro.PRO_MODELS.map((e=>e.id)).join(", ")}).`)),e;let t=!0;try{t=!!claudePro.claudeProStatus({env:process.env}).credentialPresent}catch{t=!0}return t?null:(g.model=null,updateConfig({model:null,currentModelId:null}),Y(render.renderNotice(b(),"warn",`pinned model "${e}" needs a Claude Pro subscription or an ANTHROPIC_API_KEY, and this host has neither — pin cleared. Run \`claude /login\`, export a console key, or \`/class pro off\`.`)),e)}let t;try{t=await F()}catch{return null}return t.length?catalogIds(t).has(String(e).toLowerCase())?null:(g.model=null,updateConfig({model:null,currentModelId:null}),Y(render.renderNotice(b(),"warn",`pinned model "${e}" is not advertised by AEGIS Cloud — pin cleared, the pool will choose; /models lists what you can pin.`)),e):null}function W(){return render.renderBanner(b(),{width:h(),version:VERSION,model:g.model||"server default",base:o.apiBase,key:maskKey(o.apiKey),stream:g.stream})}function Y(e){const t="string"==typeof e?[e]:e;for(const e of t)n.write(e+"\n")}async function V(e,{history:o=[],presenter:s=null,signal:i=null}={}){const a=Date.now(),l=!s&&t.interactive&&t.stream&&n.isTTY?new LiveRegion(n):null;let c=0,d=0,u="",m=0,p=0,k=VERBS[Math.floor(Math.random()*VERBS.length)],v=!1,S=!1;const E=()=>{l&&l.update([render.renderWorking(b(),{tick:c++,verb:k,elapsedMs:Date.now()-a,streamed:estimateTokensFromCells(d+m)+p,streamedFloor:p>0})])},C=l?setInterval(E,90):null;C&&C.unref&&C.unref(),E();const I=s||{},N=new Map,P=randomUUID();T=P;let x=!1;const A=()=>{x=!0,f.cancel(P)},L=()=>A();process.once("SIGINT",L),i&&(i.aborted?A():i.addEventListener("abort",A,{once:!0}));const O=e=>(r.write(`aegiscode: ${e.tool} needs confirmation but this run has no prompt for it — denied (pass --automode (alias --yolo) to auto-approve mutating tools).\n`),Promise.resolve("deny")),_=()=>Promise.resolve(!1),M=e=>{if(e){if(e.thinkingTokens&&(p+=e.thinkingTokens,v||(v=!0,k="Reasoning"),(e=>{if(I.thinkingTokens)I.thinkingTokens(e)})(e.thinkingTokens),E()),e.reasoning&&(m+=w(e.reasoning),v||(v=!0,k="Reasoning",E()),(e=>{if(I.reasoning)I.reasoning(e)})(e.reasoning)),e.delta&&(d+=w(e.delta),u+=e.delta,(e=>{if(I.text)return I.text(e);l&&c%2==0&&E()})(e.delta)),e.tool&&(S=!0,(e=>{if(I.tool)return I.tool(e);l&&l.clear();const t=(e=>{const t=e&&void 0!==e.id?`id:${e.id}`:`${e&&e.name}:${JSON.stringify(e&&e.args)}`;return N.has(t)||N.set(t,editPreview(e&&e.name,e&&e.args,{cwd:process.cwd()})),N.get(t)})(e);Y(render.renderTurn(b(),{role:"tool",label:e.name,args:e.args,ok:e.ok,diff:t,diffOpen:defaultOpen(t)},h())),E()})(e.tool)),e.approval){const t=e.approval;l&&l.clear();const n=I.approval||y||O;Promise.resolve(n(t)).catch((()=>"deny")).then((e=>f.respondApproval(t.id,normalizeDecision(e))))}if(e.rounds){const t=e.rounds;l&&l.clear();const n=I.rounds||_;Promise.resolve(n(t)).catch((()=>!1)).then((e=>f.respondRoundsAsk(t.id,!0===e)))}}};try{const n=await f.chat({prompt:e,messages:o,model:g.model||void 0,system:t.system||defaultSystemPrompt(),maxTokens:t.maxTokens,effort:effortRung(g.effort),recallDeep:!0===g.recallDeep||void 0,stream:!1!==g.stream,sessionId:P,sessionKey:g.sessionId,roundsAsk:Boolean(I.rounds)},M),r=n.choices&&n.choices[0]||{};return{text:r.message&&r.message.content||u,usage:n.usage||null,model:n.model||g.model||null,ms:Date.now()-a,interrupted:x,reasoningChars:m,usedTools:S}}catch(e){if(x&&u)return{text:u,usage:null,model:g.model||null,ms:Date.now()-a,interrupted:!0,reasoningChars:m,usedTools:S};throw e}finally{C&&clearInterval(C),process.removeListener("SIGINT",L),i&&i.removeEventListener("abort",A),l&&l.clear(),T=null}}function G(e){Y(render.renderTurn(b(),e,h()))}async function z(e,{label:t="you"}={}){if(!e)return void Y(render.renderNotice(b(),"warn","nothing to ask — give /ask a prompt"));if(o.apiKey||await d(),!o.apiKey)return void Y(render.renderNotice(b(),"error",`no AEGIS account key — ${credentials.HOW_TO_SET} (or set $${credentials.KEY_ENV})`));const n=k.filter((e=>"user"===e.role||"assistant"===e.role)).map((e=>({role:e.role,content:e.text})));let r;G({role:"user",text:e,label:t}),k.push({role:"user",text:e});try{r=await V(e,{history:n})}catch(t){return ae(e,{text:"",error:t.message},"error"),void Y(render.renderTurn(b(),{role:"error",text:t.message},h()))}r.text&&k.push({role:"assistant",text:r.text});const s=ie(r);let i=null;try{const e=await N();i=e?e.lastCost:null}catch{}ae(e,r,r.interrupted?"stopped":r.error?"error":"done",i),G({role:"assistant",text:r.text||"(the pool returned no text — see /balance for what it charged)",meta:{model:r.model,tokens:s,usage:null==r.usage?null:usageBuckets(r.usage),eur:i,ms:r.ms,calls:1}}),r.interrupted&&Y(render.renderNotice(b(),"warn","interrupted — the pool may still be running and billing this call"))}async function X(e,t){const n=s[e];if(!n)throw new Error(`unknown tool: ${e}`);if(o.apiKey||await d(),!o.apiKey)throw new Error(`no AEGIS account key — ${credentials.HOW_TO_SET}`);const r=await n.run(t||{});Y(render.renderToolResult(b(),e,r,h()))}function J(e){const t=String(e||"").toLowerCase();if(!t)return null;let n=null;for(const e of COMMANDS)for(const r of[e.name,...e.aliases||[]])r!==t&&(r.startsWith(t)||t.startsWith(r))&&(null==n||Math.abs(r.length-t.length)<Math.abs(n.length-t.length))&&(n=r);return n}function Q(){const e=loadPermissions(),t=confirmPosture();return{version:VERSION,model:g.model||"server default",class:g.modelClass,effort:g.effort,thinking:g.thinking,theme:g.light?"light":"dark",themeIndex:g.themeIndex,vim:g.vim,stream:g.stream,cwd:g.cwd,home:os.homedir(),sessionId:g.sessionId,base:o.apiBase,keyMask:maskKey(o.apiKey),online:!!o.apiKey,turns:S.turns,calls:S.calls,startedAt:S.startedAt,tokens:{input:S.inputTokens,output:S.outputTokens,cacheRead:S.cacheReadTokens,cacheWrite:S.cacheWriteTokens,total:S.tokens},costEur:S.cost,balance:S.balance,plan:S.plan||null,account:S.account||null,permissions:{mode:t.enabled?e.defaultMode:"allow",confirm:t.enabled,source:t.source,rules:e},models:q(),commands:visibleCommands(),transcript:k.slice(),sessions:[],memory:{},lastRecap:g.lastRecap,backend:g.modelClass,url:o.apiBase}}function Z(e){return Array.isArray(e)?e.map((e=>e&&(e.s||"")+(null==e.t?"":e.t)||"")).join(""):String(null==e?"":e)}function ee(e){if(!e||"object"!=typeof e)return;const t=h();switch(e.role){case"panel":{const t=Array.isArray(e.lines)?e.lines:[];for(const e of t)Y(Z(e));return}case"note":case"tip":return void Y(render.renderNotice(b(),"info",e.text));case"done":return void Y(render.renderNotice(b(),"ok",e.text));case"error":return void Y(render.renderNotice(b(),"error",e.text));case"user":return void Y(render.renderTurn(b(),{role:"user",text:e.text,label:e.label},t));case"assistant":return void Y(render.renderTurn(b(),{role:"assistant",text:e.text},t));case"tool":return void 0===e.diff&&(e.diff=editPreview(e.name||e.label,e.args,{cwd:process.cwd()}),e.diffOpen=defaultOpen(e.diff)),void Y(render.renderTurn(b(),{role:"tool",label:e.label||e.name,args:e.args,ok:e.ok,diff:e.diff,diffOpen:!!e.diffOpen},t));default:return void Y(render.renderNotice(b(),"info",null==e.text?"":String(e.text)))}}function te(e){return{t:e,s:"",w:w(e)}}async function ne(){return!e.readline&&process.stdin.isTTY&&process.stdout.isTTY&&!1!==e.chatflow?screens.showThemePicker(g):(g.light=!g.light,g.themeIndex=g.light?2:1,Y(render.renderNotice(b(),"ok","theme: "+(g.light?"light":"dark"))),g.themeIndex)}function re(){const e={ctx:g,transcript:k,push:e=>ee(e),note:e=>ee({role:"note",text:e}),panel:e=>ee({role:"panel",lines:e}),render:()=>{},openOverlay:e=>function(e){if(!e||"object"!=typeof e)return;const t=h(),n=Math.max(5,process.stdout&&process.stdout.rows||24);let r=null;if("panel"===e.type?r=e.lines:"palette"===e.type?r=overlays.renderPalette(visibleCommands(),{query:e.query||"",sel:e.sel||0},t,n):"model"===e.type?r=overlays.renderModelPicker(e.items||[],e.sel||0,t,n,null!=e.current?e.current:g.model,e.cls||g.modelClass,p):"effort"===e.type?r=overlays.renderEffortPicker(e.sel||0,t,g.effort):"class"===e.type?r=overlays.renderClassPicker(e.items||[],e.sel||0,t,e.current||g.modelClass,p):"provider"===e.type?r=overlays.renderProviderPicker(e.items||[],e.sel||0,t,e.current,e.hint):"resume"===e.type?r=overlays.renderResumeList(e.items||[],e.sel||0,t,n):"confirm"===e.type&&(r=render.renderApproval(b(),e.info||{},t).map((e=>[te(e)]))),r)for(const e of r)Y(Z(e))}(e),closeOverlay:()=>{},setAutoRounds:e=>{m=Boolean(e)},askInput:()=>Promise.resolve(null),withWorking:e=>async function(e){const r=new AbortController,o=t.interactive&&n.isTTY?new LiveRegion(n):null;let s=null;if(o){let e=0;const t=Date.now(),n=()=>o.update([render.renderWorking(b(),{tick:e++,verb:VERBS[0],elapsedMs:Date.now()-t})]);n(),s=setInterval(n,90),s.unref&&s.unref()}try{return await e(r.signal)}finally{s&&clearInterval(s),o&&o.clear()}}(e),runPrompt:e=>z(e),ask:e=>V(e),runTool:(e,t)=>X(e,t),loadModels:()=>D(g.modelClass),settings:()=>f.settings||null,byokNamespace:e=>byokNamespace(e),listModelsFor:e=>D(e),refreshByokModels:()=>K({force:!0}),switchClass:e=>function(e){const t=String(null==e?"":e).trim().toLowerCase(),n=H();if(!n.includes(t))return"pro"===t?{ok:!1,error:"the pro class (your Claude Code subscription) is off by default — enable it once with `/class pro on`"}:{ok:!1,error:`unknown class "${e}" — classes: ${n.join(", ")}`};const r=g.modelClass;g.modelClass=t;let o=null;return r!==t&&g.model&&(function(e,t){const n=String(null==t?"":t);return"byok"===e?n.includes(":"):"pro"===e?B().has(n.toLowerCase()):!n.includes(":")}(t,g.model)||(o=g.model,g.model=null)),updateConfig({modelClass:t,model:g.model,currentModelId:g.model}),{ok:!0,class:t,prev:r,cleared:o}}(e),classLabel:e=>p(e),classes:()=>"function"==typeof f.listClasses?f.listClasses():[],refreshSpend:()=>N(),state:()=>Q(),setInput:()=>{},exit:()=>{v=!0},client:o,TOOLS:s,saveConfig:e=>updateConfig(e),showThemePicker:()=>ne(),keyStatus:()=>credentials.keyStatus(),setApiKey:(e,t)=>P(e,t),forgetApiKey:()=>x(),registerAccount:()=>async function(){return o.apiKey?{alreadyKeyed:!0}:c()}(),readSecret:e=>readSecret(e,{stdin:process.stdin,stdout:n}),cloudsync:cloudsync,cloudSyncEnabled:()=>A(),cloudSyncState:()=>L(),setCloudSync:e=>O(e),adoptLegacyKey:()=>_()};return Object.defineProperty(e,"sessionId",{enumerable:!0,get:()=>g.sessionId,set:e=>{g.sessionId=e}}),e.clearConversationMemory=()=>{f&&"function"==typeof f.clearSessionApprovals&&f.clearSessionApprovals(g.sessionId)},e}async function oe(e,t=null){const r=parseLine(e);if("empty"===r.kind)return!0;if("prompt"===r.kind)return await z(r.text),!0;if("unknown"===r.kind){const e=J(r.name);return Y(render.renderNotice(b(),"error",`unknown command: /${r.name}${e?` — did you mean /${e}?`:" — try /help"}`)),!0}if("unavailable"===r.kind){const e=r.command;if(Y(render.renderNotice(b(),"warn",`/${e.name} is not available in aegiscode — ${e.unavailable}`)),e.alt)Y(render.renderNotice(b(),"info",`try ${e.alt} instead`));else{const t=J(e.name);t&&Y(render.renderNotice(b(),"info",`try /${t} instead`))}return!0}const s=r.command,i=r.arg;if(s.generic){let e;try{e=s.build(i)}catch(e){return Y(render.renderNotice(b(),"error",e.message)),!0}const{tool:t,args:n}=e;if(!t)return Y(render.renderNotice(b(),"error","/tool needs a tool name — see /help")),!0;try{await X(t,n)}catch(e){Y(render.renderNotice(b(),"error",e.message))}return!0}if("function"==typeof s.handler){const e=function(e,t){const n=String(null==t?"":t),r=Array.isArray(e.args)?e.args:[],o=function(e){const t=[];let n="",r=null,o=!1;for(const s of String(e||""))r?s===r?r=null:n+=s:'"'!==s&&"'"!==s?/\s/.test(s)?(n||o)&&(t.push(n),n="",o=!1):(n+=s,o=!0):(r=s,o=!0);return(n||o)&&t.push(n),t}(n),s={_rest:n.trim()};return r.forEach(((e,t)=>{void 0!==o[t]&&(s[e]=o[t])})),s}(s,i),n=t||re();try{return!1!==await s.handler(n,e)}catch(e){return Y(render.renderNotice(b(),"error",e&&e.message?e.message:String(e))),!0}}try{let e=s.build(i);if(s.secret){const t=await async function(e,t){if("function"!=typeof e.secretDescribe)return null;try{const n=await e.secretDescribe(t,o);return n&&"object"==typeof n?n:null}catch{return null}}(s,e);if(t&&t.note&&Y(render.renderNotice(b(),"info",t.note)),t&&null===t.prompt)return!0;t&&t.provider&&(e={...e,provider:t.provider});const r=await function(e){const t=themeOf(b());return readSecret(t.gray+e+RESET,{stdin:process.stdin,stdout:n})}(t&&t.prompt||`provider key for ${e.provider}: `);if(!r)return Y(render.renderNotice(b(),"warn","empty key — nothing sent")),!0;e={...e,api_key:r}}if("aegis_ask"===s.tool)return await z(e.prompt);await X(s.tool,e),"aegis_memory_list"!==s.tool&&"aegis_memory_search"!==s.tool||function(){let e;try{e=cloudsync.status()}catch{return}const t=e.quota;if(!t)return;const n=fmtTokens(t.used||0),r=fmtTokens(t.limit||0);e.overQuota?Y(render.renderNotice(b(),"warn",`cloud memory: ${n} of ${r} synced tokens — at the plan's ceiling. Everything stored stays readable; new writes are paused until there is room. /cloud memory for the full state.`)):Y(render.renderNotice(b(),"info",`cloud memory: ${n} of ${r} synced tokens — /cloud memory for the full state`))}()}catch(e){Y(render.renderNotice(b(),"error",e.message))}return!0}async function se(){if(f&&"function"==typeof f.unloadLocalModels)try{await f.unloadLocalModels()}catch{}}function ie(e){S.turns++,S.calls+=Number(e&&e.calls||1)||1;const t=e&&e.usage,n=usageTokens(t);if(null!=n){S.tokens+=n;const e=usageBuckets(t);S.inputTokens+=e.input,S.outputTokens+=e.output,S.cacheReadTokens+=e.cacheRead,S.cacheWriteTokens+=e.cacheWrite}return n}function ae(e,t,n="done",r=null){try{const o=t&&t.usage,s="number"==typeof r&&Number.isFinite(r)?r:null,i=String(t&&t.model||g.model||"").trim();appendHistory({sessionId:g.sessionId,prompt:e,reply:t&&t.text||"",status:n,model:i||void 0,provider:i&&providerForModel({id:i,cls:g.modelClass})||void 0,usage:o?{...usageBuckets(o),...null!=s?{costUsd:s}:{}}:null!=s?{input:0,output:0,cacheRead:0,cacheWrite:0,costUsd:s}:null}),snapshotCheckpoint(g.sessionId,k)}catch{}A()&&o.apiKey&&Promise.resolve().then((()=>cloudsync.push(o))).then((e=>{if(e&&e.failed&&e.failed.length){const t=e.failed[0];if(le.has(t.kind))return;if(le.add(t.kind),"quota"===t.kind)return void Y(render.renderNotice(b(),"warn","cloud memory: the plan's synced-token ceiling is reached — earlier sessions stay readable, only NEW writes pause. /cloud memory shows the quota; /cloud memory off stops trying."));const n=t.hint?` — ${t.hint}`:"";Y(render.renderNotice(b(),"error",`cloud sync: ${t.message}${n}`))}})).catch((()=>{}))}let le=new Set;function ce(){const e=[S.outputTokens>0?`${fmtTokens(S.outputTokens)} tokens`:`${fmtTokens(S.tokens)} tokens`,`${S.calls} call${1===S.calls?"":"s"}`];return feeBillable()&&(e.push(fmtEur(S.cost)),null!=S.balance&&e.push(`balance ${fmtEur(S.balance)}`)),e.join(" · ")}async function de(e){if(!e||!e.id)return;const t=readSessionTranscript(e.id);if(t.length){k.length=0;for(const e of t)k.push(e);g.sessionId=e.id,Y(render.renderNotice(b(),"ok",`resumed ${e.id} — ${t.length} turn(s)`))}else Y(render.renderNotice(b(),"warn",`no stored turns for ${e.id}`))}function ue(){return{ctx:g,version:VERSION,transcript:k,session:S,client:o,TOOLS:s,ask:(e,t)=>V(e,t),makeCommandContext:()=>re(),accountConfigured:()=>!!(credentials.keyStatus()||{}).configured,hasProviderKey:e=>{const t=f.settings;if(!t||!e)return!1;const n=byokNamespace(e);return"function"==typeof t.rawKey?!!String(t.rawKey(n)||"").trim():"function"==typeof t.get&&!!(t.get(n)||{}).configured},loadModels:e=>F(e),buildState:()=>Q(),dispatchLine:(e,t)=>oe(e,t),refreshSpend:()=>N(),updateConfig:e=>updateConfig(e),showThemePicker:()=>ne(),persistTurn:(e,t,n,r)=>ae(e,t,n,r),nameConversation:(e,t)=>async function(e,{signal:t=null}={}){const n=await naming.nameConversation(e,{signal:t,callModel:(e,n)=>V(e,{system:n&&n.system||naming.TITLE_SYSTEM,maxTokens:64,signal:n&&n.signal||t}).then((e=>e&&e.text||null))}),r=String(n||"").trim();return r&&setSessionTitle(g.sessionId,r),r}(e,t),visibleCommands:()=>visibleCommands(),tokensFor:e=>usageTokens(e),recordTurn:e=>ie(e),tokenSummary:()=>ce(),resumeSession:e=>de(e),requestExit:()=>{v=!0},wantsExit:()=>v,keyNotice:()=>o.apiKey?"":l,isYolo:()=>{if(!m)return!1;try{return!1===confirmPosture().enabled}catch{return!1}},setAutoRounds:e=>{m=Boolean(e)}}}async function me(){Y(W()),await N(),n.write("\n");const t=e.readline||readline.createInterface({input:process.stdin,output:n,terminal:!0}),r=themeOf(b()).gold+GLYPH.cursor+" "+RESET;return t.setPrompt(r),t.prompt(),new Promise((e=>{t.on("line",(async e=>{t.pause();let n=!0;try{n=await oe(e)}catch(e){Y(render.renderNotice(b(),"error",e.message))}if(!n||v)return E=!0,void t.close();t.resume(),t.prompt()})),t.on("close",(()=>{E||n.write("\n"),e(0)}))}))}function fe(){if(e.readline)return;if(!configExists())return;let n;try{n=loadConfig()}catch{return}if(H().includes(n.modelClass)&&(g.modelClass=n.modelClass),t.class){const e=String(t.class).trim().toLowerCase();if(!H().includes(e))throw new Error(`--class ${t.class}: not available on this host (offered: ${H().join(", ")})`);g.modelClass=e}if(!t.model&&n.model&&(g.model=n.model),g.effort=effortRung(t.effort||n.effort),"boolean"==typeof n.vim&&(g.vim=n.vim),n.lastRecap&&(g.lastRecap=n.lastRecap),!t.light&&"number"==typeof n.themeIndex&&THEME_TABLE[n.themeIndex]){g.themeIndex=n.themeIndex,g.light=themeIsLight(n.themeIndex);const e=reconcileThemeIndex(g.themeIndex);if(e.changed){g.themeIndex=e.index,g.light=themeIsLight(e.index),g.themeNotice=e.reason;try{updateConfig({themeIndex:e.index,light:themeIsLight(e.index)})}catch{g.themeNotice+=" (could not save it)"}}}}return{opts:t,session:S,client:o,TOOLS:s,toolList:i,ctx:g,transcript:k,ask:V,runPrompt:z,handleLine:oe,runOnce:async function(e,t={}){try{return await async function(e,{json:t=!1}={}){if(fe(),_(),!o.apiKey&&!a){a=!0;const e=await autoProvisionApiKey(o,credentials,{app:"cli"});e.key&&r.write("aegiscode: auto-provisioned a free account"+(e.ok?` (saved to ${credentials.credentialsPath()})`:" (could not save it — reconfigure with /key)")+trialNote(e)+`. Fund it at ${o.promptUrl("topup","device_autoprovision")} or run /byok to use your own key.\n`)}if(!o.apiKey)return r.write(`aegiscode: no AEGIS account key. ${credentials.HOW_TO_SET}, or set $${credentials.KEY_ENV}.\n`),2;await N();const s=[],i=[],l=t?{tool:e=>{if("done"===(e&&e.phase)){const t=e.id&&i.find((t=>t.id===e.id&&!0!==t.settled))||(e.id?null:i[i.length-1]);t?(t.settled=!0,t.ok=!1!==e.ok):(e&&e.name&&s.push(e.name),i.push({name:e&&e.name||null,id:e&&e.id||null,args:briefArgs(e&&e.args),settled:!0,ok:!1!==e.ok}))}else e&&e.name&&s.push(e.name),i.push({name:e&&e.name||null,id:e&&e.id||null,args:briefArgs(e&&e.args),settled:!1,ok:null});const t=e&&void 0!==e.preview?e.preview:null,n=render.renderTurn(b(),{role:"tool",label:e.name,args:e.args,ok:e.ok,diff:t,diffOpen:!1},h());for(const e of Array.isArray(n)?n:[n])r.write(e+"\n")}}:null,c=await V(e,l?{presenter:l}:{});await N();const d=usageTokens(c.usage),u=providerRefusal(c.text,c.usage);if(t)n.write(JSON.stringify({text:c.text,model:c.model,class:g.modelClass,rounds:c.usage&&Number(c.usage.calls)||null,usage:c.usage,reasoning_chars:"number"==typeof c.reasoningChars?c.reasoningChars:null,tokens:d,ms:c.ms,interrupted:c.interrupted,...s.length?{tools:s}:{},...i.length?{tool_log:i}:{},...u?{error:u}:{},balance_eur:S.balance},null,2)+"\n");else if(n.write(c.text+"\n"),u&&r.write(`aegiscode: the provider refused this turn — ${u}\n`),null!=d){const e=themeOf(b());n.write(e.dim+GLYPH.hook+" "+e.blue+(c.model||"aegis")+RESET+e.dim+" "+GLYPH.bullet+" "+RESET+e.white+`${fmtTokens(d)} tokens`+RESET+"\n")}return c.interrupted?130:u?1:0}(e,t)}finally{await se()}},runInteractive:async function(){try{return await async function(){if(!e.readline&&!1!==e.chatflow&&process.stdin.isTTY&&process.stdout.isTTY){await probeTerminalBackground({onLeftover:e=>events.feedKeys(e,{keystrokes:!0})}),fe(),function(){if(!g.themeNotice)return;const e=g.themeNotice;g.themeNotice="",Y(render.renderNotice(b(),"warn",`theme: ${e} (saved)`))}(),_(),o.apiKey||await d();const t=await screens.runOnboarding(g,{continue:!!e.continue,seen:e.seen||configExists,save:e=>updateConfig(e),needsKey:()=>!o.apiKey,submitKey:e=>P(e)});if(!t.ok)return 0;if(t.key&&t.key.set&&Y(render.renderNotice(b(),"info",`key saved to ${credentials.credentialsPath()} — no export needed from now on`)),t.key&&t.key.skipped&&!o.apiKey&&Y(render.renderNotice(b(),"warn","no key saved — /key <api_key> or `aegiscode login` whenever you are ready")),t.firstRun&&function(){if(!L().enabled)return void Y(render.renderNotice(b(),"info","cross-session memory: off (you turned it off) — /cloud memory on stores sessions so an interrupted turn can be picked up later"));const e=cloudsync.status().quota,t=e&&e.limit?` (used ${fmtTokens(e.used||0)} of ${fmtTokens(e.limit)} tokens)`:"";Y(render.renderNotice(b(),"info",`cross-session memory: on${t} — sessions are stored to your account so a turn that is interrupted can be resumed. /cloud memory shows the quota; /cloud memory off stops it. Past the ceiling, saved memory stays readable and only new writes pause.`))}(),await U(),e.continue){const e=readOwnSessions(1)[0];e&&(g.continueSession=e.id,await de({id:e.id}))}return await N(),await chatflow.runSession(ue()),0}return fe(),_(),me()}()}finally{await se()}},runLinearRepl:me,refreshSpend:N,bannerLines:W,makeHost:ue,loadModels:F,validatePinnedModel:U,recordTurn:ie,persistTurn:ae,restorePrefs:fe,setApiKey:P,forgetApiKey:x,adoptLegacyKeyOnce:_,cloudSyncEnabled:A,cloudSyncState:L,setCloudSync:O,cloudsync:cloudsync,keyStatus:()=>credentials.keyStatus(),accountConfigured:()=>!!(credentials.keyStatus()||{}).configured,hasProviderKey:e=>{const t=f.settings;if(!t||!e)return!1;const n=byokNamespace(e);return"function"==typeof t.rawKey?!!String(t.rawKey(n)||"").trim():"function"==typeof t.get&&!!(t.get(n)||{}).configured},sessionId:()=>g.sessionId,tokenSummary:ce,resumeSession:de,makeCommandContext:re,buildState:Q,get aborted(){return!1}}}module.exports={createApp:createApp,VERSION:VERSION,normalizeDecision:normalizeDecision};
3
+ // AEGIS Code (aegiscode) — source: https://github.com/aegisinfo/aegiscode-plugin
4
+ // Conveying a modified copy, or running one as a network service, owes the
5
+ // corresponding source under this licence (§5/§13) — see LICENSING.md.
6
+ 'use strict';
7
+
8
+ /**
9
+ * The CLI application: session state, the ask/stream path, and the command
10
+ * dispatcher.
11
+ *
12
+ * Split from `bin/aegiscode.js` so the whole app is constructible with injected
13
+ * IO (`out`, `err`, `readline`) and a stub client — the tests drive real turns,
14
+ * real streaming and real command dispatch without a TTY and without a child
15
+ * process. Bin entry = argument parsing and process lifecycle; everything else
16
+ * lives here.
17
+ *
18
+ * Commands come from `./commands.js`. Each entry is either handler-backed
19
+ * (`cmd.handler(c, args)`, the upstream engine contract), tool-backed
20
+ * (`cmd.tool` + `cmd.build`), a generic escape hatch (`cmd.generic`, `/tool`),
21
+ * or `unavailable` (a Claude Code auth-loop command this client cannot honour).
22
+ * Handlers run against the FROZEN command context built below; the tool path
23
+ * and the `/tool` escape hatch are unchanged from the previous revision.
24
+ */
25
+
26
+ const readline = require('node:readline');
27
+ const os = require('node:os');
28
+ const { randomUUID } = require('node:crypto');
29
+ const { createTools, createClient, usageTokens, usageBuckets, buildSystemPrompt, autoProvisionApiKey, provisionFailureText, trialNote, hostEnv, autonomous, claudePro } = require('./deps.js');
30
+ const { createEngine, HOST_CLASSES, DEFAULT_CLASS, byokNamespace, effortRung, offeredClasses, proEnabled } = require('./engine.js');
31
+ const { GLYPH, VERBS, themeOf, RESET, THEME_TABLE, AUTO_THEME_INDEX, themeIsLight, reconcileThemeIndex } = require('./theme.js');
32
+ const { probeTerminalBackground } = require('./caps.js');
33
+ const { LiveRegion, termWidth, w } = require('./screen.js');
34
+ // The live spinner tail is a token count, so the cell→token rule comes from the
35
+ // one module that owns it rather than a `/4` written inline at the call site
36
+ // (tokens.js explains why the count form has to sit beside the text form).
37
+ const { estimateTokensFromCells } = require('./tokens.js');
38
+ const { editPreview } = require('./diff.js');
39
+ const { defaultOpen } = require('./diffview.js');
40
+ const { parseLine, COMMANDS, visibleCommands } = require('./commands.js');
41
+ const {
42
+ updateConfig,
43
+ loadPermissions,
44
+ loadConfig,
45
+ configExists,
46
+ memoryPersistState,
47
+ memoryPersistEnabled,
48
+ setMemoryPersist,
49
+ confirmPosture,
50
+ } = require('./config.js');
51
+ const credentials = require('./credentials.js');
52
+ // The key pump, so the startup background query can hand back a keystroke that
53
+ // raced its answer (see the `probeTerminalBackground` call in `runInteractive`).
54
+ const events = require('./events.js');
55
+ const cloudsync = require('./cloudsync.js');
56
+ const { readSecret } = require('./secret.js');
57
+ const { normalizeModelCatalog, pickerEntries, catalogIds, providerForModel } = require('./models.js');
58
+ const { appendHistory, readSessionTranscript, readOwnSessions, setSessionTitle } = require('./history.js');
59
+ const naming = require('./naming.js');
60
+ const { snapshotCheckpoint } = require('./checkpoint.js');
61
+ const screens = require('./screens.js');
62
+ const chatflow = require('./chatflow.js');
63
+ const overlays = require('./overlays.js');
64
+ const render = require('./render.js');
65
+ const { fmtTokens, fmtEur, maskKey, feeBillable } = require('./format.js');
66
+ // The rule-5 skip resolver the gate below calls. It was CALLED and never
67
+ // imported: `const skip = resolveSkip({…})` at the top of the `getConfirmMode`
68
+ // callback threw a ReferenceError on every invocation, the surrounding `catch`
69
+ // swallowed it as "the store could not be read", and the whole skip arm was
70
+ // therefore dead in shipped code — `AEGISONE_SKIP_PERMISSIONS` (what the
71
+ // `aegis` bin forwards once it has resolved `--dangerously-skip-permissions`)
72
+ // and the CI/queue spelling both fell through to the store and were ignored,
73
+ // with nothing on screen to say a decision had been discarded. Imported here,
74
+ // beside the other module-level requires, so the two faces resolve a skip
75
+ // through the one function (D8 rule 1) instead of one of them not at all.
76
+ const { resolveSkip } = require('./permissions.js');
77
+
78
+ const VERSION = require('../package.json').version;
79
+
80
+ /**
81
+ * The persona for a turn this host did not get an explicit system prompt for.
82
+ *
83
+ * Built once and cached: it is the stable head of every request, and a prompt
84
+ * that changed between turns would defeat the provider's prompt cache for the
85
+ * whole conversation behind it.
86
+ */
87
+ let _defaultSystem = null;
88
+ function defaultSystemPrompt() {
89
+ if (_defaultSystem === null) {
90
+ try {
91
+ // The SAME environment block the desktop engine builds (engine.js
92
+ // hostEnv): platform, the real home and Desktop directories, the working
93
+ // directory, and — the field this host was missing — the shell `exec`
94
+ // really runs in. Building a three-field subset here is what let a
95
+ // Windows CLI session be told it was on linux and reach for `ls`, `cat`
96
+ // and `mkdir -p`: nothing in the prompt said otherwise.
97
+ _defaultSystem = buildSystemPrompt(hostEnv({}, {}, null));
98
+ } catch {
99
+ _defaultSystem = ''; // never let persona construction break a turn
100
+ }
101
+ }
102
+ return _defaultSystem || undefined;
103
+ }
104
+
105
+ // The engine accepts exactly 'once' | 'session' and coerces anything else to
106
+ // 'deny' (vendor/desktop/lib/local/engine.js → respondApproval). Bridging the
107
+ // vocabularies here, rather than trusting every prompter to speak the engine's
108
+ // dialect, is what stops an approval from silently becoming a denial. The
109
+ // failure mode is invisible from the outside: the tool is refused, the model
110
+ // is told the user declined, and it retries against a gate that can only ever
111
+ // say no — the turn burns its whole budget.
112
+ //
113
+ // Module scope on purpose: this must exist before createApp() runs, because it
114
+ // is re-exported for the conformance tests. A nested copy here previously left
115
+ // the export binding undefined and threw on require.
116
+ function normalizeDecision(decision) {
117
+ const v = typeof decision === 'string' ? decision.trim().toLowerCase() : '';
118
+ if (v === 'session') return 'session';
119
+ if (v === 'once' || v === 'allow' || v === 'yes' || v === 'approve' || v === 'approved') {
120
+ return 'once';
121
+ }
122
+ return 'deny';
123
+ }
124
+
125
+ // ── "that was not an answer" ────────────────────────────────────────────────
126
+ //
127
+ // A provider-side refusal can arrive shaped exactly like a completion: HTTP
128
+ // 200, an assistant message, `usage` absent or zero. Measured 2026-10-21 on
129
+ // this CLI, twice, from live runs:
130
+ //
131
+ // {"text":"Invalid API key · Fix external API key","tokens":0,"balance_eur":1.54}
132
+ // {"text":"You've hit your session limit · resets 9:50pm (Europe/Stockholm)"}
133
+ //
134
+ // Both exited 0. Nothing about the process told a caller that the turn had
135
+ // failed: a shell script, a CI job, or the harness adapter reading `--json`
136
+ // sees a non-empty `text` and calls it success. The harness did exactly that
137
+ // and scored a *broken* run as a scored zero rather than an error.
138
+ //
139
+ // The engine already treats this class as a diagnosed failure mode — see
140
+ // `phantomPin()` and the `session limit` notes in aegiscodex-dev's
141
+ // src/backend.js, where a spent OAuth session "reads like a provider outage
142
+ // rather than a bad pin". This host ships the transport and the CLI, not that
143
+ // brain, so it cannot prevent the misroute; what it *can* do is refuse to pass
144
+ // the resulting sentence off as an answer.
145
+ //
146
+ // Deliberately narrow, because calling a real answer an error is its own bug:
147
+ // - Only when the turn produced NO tokens. A billed turn did work; whatever
148
+ // it says is the model's output, even if it reads oddly.
149
+ // - Only when the whole reply is one short line. A long answer that happens
150
+ // to discuss API keys must not be caught by a substring match.
151
+ // - Only known provider-refusal shapes. Not "any sentence with 'error'".
152
+ const PROVIDER_REFUSAL_PATTERNS = Object.freeze([
153
+ /^invalid api key\b/i,
154
+ /^fix external api key\b/i,
155
+ /^you've hit your session limit\b/i,
156
+ /^you have hit your session limit\b/i,
157
+ /^provider request timed out\b/i,
158
+ /^insufficient (?:credit|balance|quota)\b/i,
159
+ /^rate limit(?:ed)?\b/i,
160
+ /^unauthorized\b/i,
161
+ ]);
162
+
163
+ /**
164
+ * Whether `text` is a provider refusal that arrived dressed as a completion.
165
+ *
166
+ * @param {unknown} text the assistant content `ask()` returned
167
+ * @param {unknown} usage the turn's usage record, if any
168
+ * @returns {string|null} the matched refusal, or null when it is a real answer
169
+ */
170
+ function providerRefusal(text, usage) {
171
+ if (typeof text !== 'string') return null;
172
+ // A billed turn is not a refusal, whatever it says.
173
+ const total = usage && (usage.total_tokens || 0);
174
+ const out = usage && (usage.output_tokens || usage.completion_tokens || 0);
175
+ if (total > 0 || out > 0) return null;
176
+ const line = text.trim();
177
+ if (!line || line.length > 160 || line.includes('\n')) return null;
178
+ for (const re of PROVIDER_REFUSAL_PATTERNS) {
179
+ if (re.test(line)) return line;
180
+ }
181
+ return null;
182
+ }
183
+
184
+ /**
185
+ * One tool call, readable — the arg summary published in `--json`'s `tool_log`.
186
+ *
187
+ * Truncated on a character boundary so a row stays a record a person can read
188
+ * while still showing WHAT each call was. A list of tool names cannot tell
189
+ * "read four files" apart from "ran the same test twelve times", and the
190
+ * archived AEGIS rows carried only names.
191
+ *
192
+ * @param {unknown} a the call's arguments
193
+ * @returns {string} a single line, at most 140 characters
194
+ */
195
+ function briefArgs(a) {
196
+ let s;
197
+ try { s = typeof a === 'string' ? a : JSON.stringify(a ?? ''); } catch { s = String(a); }
198
+ s = String(s).replace(/\s+/g, ' ').trim();
199
+ return s.length > 140 ? `${s.slice(0, 137)}...` : s;
200
+ }
201
+
202
+ function createApp(options = {}) {
203
+ const opts = {
204
+ model: null,
205
+ stream: true,
206
+ light: false,
207
+ maxTokens: undefined,
208
+ system: undefined,
209
+ interactive: true,
210
+ ...options,
211
+ };
212
+ const out = options.out || process.stdout;
213
+ const err = options.err || process.stderr;
214
+ // The key comes from the credential store (env → credentials.json →
215
+ // config.json) rather than from the environment alone: an export does not
216
+ // survive a new shell, and until it is *stored* every one of those launches
217
+ // is "no key" with no in-band way to set one. An injected client keeps
218
+ // whatever key it was built with.
219
+ const client = options.client || createClient(credentials.clientOptions({ channel: 'cli' }));
220
+ const { TOOLS, toolList } = options.tools || createTools(client);
221
+
222
+ // With no key configured anywhere, ask aegis1 for a free device key before
223
+ // ever showing "no key" — same shared helper (client/auto-provision.js) the
224
+ // MCP plugin and the desktop app use, so all three ask for the same account
225
+ // on the same machine. One provisioning per `createApp()` instance, not one
226
+ // per call: register-device is rate-limited server-side, and a session that
227
+ // fires several turns before noticing a failure must not retry the same
228
+ // failing call each time. A transient failure gets a few bounded retries
229
+ // inside that one provisioning. A brand-new fingerprint comes back with aegis1's
230
+ // one-time 30-day welcome-trial `unlimited` entitlement (token-bank credit
231
+ // plus a `subscriptions` row) granted in the same request — aegis1 commit
232
+ // 4372830 — so the account is usable pooled right away rather than starting
233
+ // at zero. The credit is finite: once it is spent or the trial lapses, the
234
+ // usual plan/balance gate applies.
235
+ let provisionAttempted = false;
236
+ let keyFailure = '';
237
+ async function provisionDeviceKey() {
238
+ const result = await autoProvisionApiKey(client, credentials, { app: 'cli' });
239
+ keyFailure = result.key ? '' : provisionFailureText(result);
240
+ return result;
241
+ }
242
+ async function ensureApiKey() {
243
+ if (client.apiKey || provisionAttempted) return;
244
+ provisionAttempted = true;
245
+ const result = await provisionDeviceKey();
246
+ if (result.key) {
247
+ emit(
248
+ render.renderNotice(
249
+ ctx(),
250
+ 'info',
251
+ `auto-provisioned a free account` +
252
+ (result.ok ? ` (saved to ${credentials.credentialsPath()})` : ' (could not save it — reconfigure with /key)') +
253
+ // Shared clause: covers the withheld case AND the reused one (a
254
+ // returning fingerprint gets its old account, never a second
255
+ // trial). Inline here it only knew `trialGranted`, so a
256
+ // re-registered machine read as a clean first install.
257
+ trialNote(result) +
258
+ `. Fund it at ${client.promptUrl('topup', 'device_autoprovision')} or run /byok to use your own key.`
259
+ )
260
+ );
261
+ }
262
+ }
263
+
264
+ // Tool-approval gate (exec/writeFile/editFile confirm before running).
265
+ // Read per call, so /permissions and /automode take effect on the very next tool
266
+ // round rather than needing a restart. The mode is read LIVE from the
267
+ // permission store rather than from a boolean captured at construction:
268
+ // `/automode` and `/confirm` write the store, so a captured flag made both
269
+ // commands cosmetic — the panel changed while the engine kept asking.
270
+ let confirmMode = options.confirmMode !== false;
271
+ // ── Auto mode's session start state ────────────────────────────────────────
272
+ // The upstream engine (aegiscodex-dev src/autonomous.js) starts an attended
273
+ // session in auto mode unless AEGIS_AUTO_ROUNDS=0 (false/off/no), and the
274
+ // `←`/`→` chord toggles it freely from there: the env var is a STARTING
275
+ // POINT, not a veto. Same contract here, held in a local rather than
276
+ // re-derived per call, because the two are not the same statement:
277
+ //
278
+ // · re-deriving the env var on every read (a `!autoRoundsDefault(env)`
279
+ // guard inside isYolo) makes the opt-out absolute — `/automode on`,
280
+ // the `→` chord and the window's switch all become no-ops that still
281
+ // write the shared posture OFF, so the CLI chip reads "manual mode on"
282
+ // while the desktop's approvals are off. That is the three-surfaces
283
+ // drift (command, store, engine) this file exists to prevent,
284
+ // reintroduced by an environment variable.
285
+ // · a session flag honours the operator's "start me in manual" without
286
+ // disarming the toggle.
287
+ //
288
+ // `/automode on|off` moves it (commands.js writes `setAutoRounds`), so the
289
+ // chord stays live in both directions and the posture keeps exactly one home.
290
+ let autoRoundsSession = (() => {
291
+ try {
292
+ return autonomous.autoRoundsDefault(process.env);
293
+ } catch {
294
+ return true;
295
+ }
296
+ })();
297
+ const engine =
298
+ options.engine ||
299
+ createEngine({
300
+ client,
301
+ // The live class — read per turn rather than captured, for the same
302
+ // reason confirmMode is a callback: a captured value made `/class`
303
+ // cosmetic, changing the panel and not what the next turn ran on.
304
+ getClass: () => commandCtx.modelClass,
305
+ // Whether the `pro` class is enabled (config.js `proEnabled`, off by
306
+ // default). Read per call for the same reason getClass is: `/class pro
307
+ // off` must remove it from the picker and stop the very next turn, not
308
+ // the next launch. A read failure answers "off" — fail closed, because
309
+ // the alternative spends a subscription nobody opted into.
310
+ getProEnabled: () => {
311
+ try {
312
+ return proEnabled(loadConfig());
313
+ } catch {
314
+ return false;
315
+ }
316
+ },
317
+ getConfirmMode: () => {
318
+ if (options.confirmMode !== undefined) return confirmMode;
319
+ // AEGISONE D8 rule 5 — the skip posture, resolved by the SAME function
320
+ // the product uses (cli/src/permissions.js resolveSkip), so the two
321
+ // faces cannot disagree about what a flag or an environment variable
322
+ // means. Two sources only:
323
+ //
324
+ // AEGISONE_SKIP_PERMISSIONS the `aegis` bin's forwarded decision,
325
+ // already checked against rule 5 upstream;
326
+ // AEGIS_SKIP_PERMISSIONS the CI/queue spelling, honored only when
327
+ // this process is NON-interactive. A stray
328
+ // `export` in a shell profile warns and is
329
+ // ignored here, which is the whole point:
330
+ // it must not be able to disarm a human's
331
+ // own gate.
332
+ //
333
+ // A rule-5 refusal is reported once per session, not per tool call —
334
+ // the gate is read on every round and a warning per round would be
335
+ // noise the user learns to scroll past.
336
+ try {
337
+ const skip = resolveSkip({
338
+ env: process.env,
339
+ interactive: Boolean(process.stdin.isTTY && process.stdout.isTTY),
340
+ });
341
+ if (skip.warned && !skipEnvWarned) {
342
+ skipEnvWarned = true;
343
+ process.stderr.write(`aegiscode: ${skip.warning}\n`);
344
+ }
345
+ if (skip.skip) return false;
346
+ } catch {
347
+ /* fall through to the store: a broken skip resolver must not skip */
348
+ }
349
+ try {
350
+ // ON8 / D8 rule 1: the posture is read from the SHARED store first
351
+ // (config.js confirmPosture), which is the same store the desktop's
352
+ // "confirm before running tools" switch writes. Before this, the shell
353
+ // read only its own rule file, so the switch and `/automode` were two
354
+ // postures for one question — the drift D8 names. The rule file is
355
+ // still the answer for an install that never touched the switch, so
356
+ // nothing changes for it.
357
+ return confirmPosture().enabled;
358
+ } catch {
359
+ return confirmMode;
360
+ }
361
+ },
362
+ });
363
+ // How a class is named in every surface that shows one (the status line, the
364
+ // class panel, the model picker's title). One definition, because the engine
365
+ // owns the label table (CLASS_LABELS) and re-spelling it here would let the
366
+ // picker and /class disagree about what the user is about to run on. Guarded
367
+ // because an injected engine (tests, embedding) may predate the class surface.
368
+ const classLabelOf = (cls) =>
369
+ typeof engine.classLabel === 'function' ? engine.classLabel(cls) : String(cls || '');
370
+
371
+ // Set by runInteractive: a question/answer channel for the engine's
372
+ // tool-approval requests. Left null in one-shot (-p) runs, where there is
373
+ // no one to ask — see the approval branch in ask() below.
374
+ let approvalPrompter = null;
375
+
376
+ const width = () => (options.width ? options.width() : termWidth());
377
+
378
+ // ── live session/command state ─────────────────────────────────────────────
379
+ // `commandCtx` is the FROZEN `c.ctx` a handler receives: the mutable slice of
380
+ // session state a command may set (model, effort, thinking, theme, vim, stream,
381
+ // cwd, lastRecap). The renderers read their colours from it via ctx().
382
+ const commandCtx = {
383
+ light: opts.light,
384
+ model: opts.model,
385
+ // Which class the next turn runs on. 'aegis' is the default because it is
386
+ // the one class an account key alone can run — BYOK additionally needs a
387
+ // provider key, so defaulting to it would break a fresh install.
388
+ modelClass: DEFAULT_CLASS,
389
+ // The budget rung the next turn travels with. `null` here means "nothing
390
+ // restored yet", not "auto": the rung actually sent is resolved by
391
+ // effortRung() at the request, which floors to 'high' — the same default
392
+ // the config file seeds and the desktop select offers. Retiring "auto" is
393
+ // the point: it was the default, so the default turn sent no effort at all
394
+ // and low/medium/high only moved the status line.
395
+ effort: null,
396
+ thinking: false,
397
+ // Deep recall (`aegis_recall_deep`) — the metered tier of the read: brain
398
+ // corrections plus the semantic answer cache, and the answer cache costs
399
+ // one provider embedding per turn (aegis1 app.py:8367 →
400
+ // services/brain_memory.py find_cached_answer). This host recalls on every
401
+ // turn already and pays per turn, so the deep tier is NEVER inferred: it is
402
+ // false here, `/memory-deep on` is the only thing that flips it, and that
403
+ // choice is deliberately NOT persisted — a flag that meters every turn must
404
+ // not survive into a session where nobody asked for it.
405
+ recallDeep: false,
406
+ // "Auto (match terminal)" is the default row, not "Dark mode": the row's
407
+ // whole purpose is that it resolves against the terminal's reported
408
+ // background, and leaving the default on explicit Dark drew the dark
409
+ // palette's white body text over a light terminal — an invisible UI — for
410
+ // every user who never opened the picker.
411
+ themeIndex: opts.light ? 2 : AUTO_THEME_INDEX,
412
+ vim: false,
413
+ stream: opts.stream,
414
+ cwd: process.cwd(),
415
+ lastRecap: null,
416
+ sessionId: randomUUID(),
417
+ };
418
+ // The light flag must start consistent with the default row above, or the
419
+ // ctx and the palette disagree until the first `/theme`: with `AUTO_THEME_INDEX`
420
+ // as the default, a light-background terminal gets the light palette *and*
421
+ // the "light" label, a dark one is byte-identical to before.
422
+ if (commandCtx.themeIndex === AUTO_THEME_INDEX) commandCtx.light = themeIsLight(AUTO_THEME_INDEX);
423
+ // The transcript rows a handler reads/pushes (user/assistant/note/panel/…).
424
+ // It is also the source of the engine's conversation history, so /clear and
425
+ // /new genuinely reset context.
426
+ const transcript = [];
427
+ let wantExit = false;
428
+ // When non-null, `emit` appends here instead of writing to `out`. Used by the
429
+ // one-shot path to run a command and report its output as one JSON document
430
+ // (`--json`) rather than as loose human text on stdout. Every command's output
431
+ // funnels through `emit` (pushRow's panel/note/turn branches all call it), so
432
+ // one switch here covers the whole command surface.
433
+ let capture = null;
434
+
435
+ const ctx = () => ({ light: commandCtx.light });
436
+
437
+ const session = {
438
+ turns: 0,
439
+ calls: 0,
440
+ tokens: 0,
441
+ inputTokens: 0,
442
+ outputTokens: 0,
443
+ cacheReadTokens: 0,
444
+ cacheWriteTokens: 0,
445
+ cost: 0, // € spent, from the ledger rows that landed AFTER the baseline
446
+ balance: null,
447
+ // How many times each ledger-row identity is already accounted for.
448
+ // A COUNT, not a Set — see ledgerRowKey for why identity is content-based
449
+ // and refreshSpend for why the multiplicity matters.
450
+ seenLedgerRows: new Map(),
451
+ // Whether the account's existing ledger has been snapshotted as history.
452
+ // The balance endpoint returns the ACCOUNT's ledger, so the rows visible on
453
+ // the first refresh are everything the customer ever spent. Until this is
454
+ // true, no row may be folded into `cost`: session.cost is rendered as
455
+ // "This session" and would otherwise print the account's lifetime spend
456
+ // under it. See refreshSpend.
457
+ ledgerBaselined: false,
458
+ startedAt: Date.now(),
459
+ };
460
+
461
+ let activeSessionId = null;
462
+ let closed = false;
463
+
464
+ // --- helpers --------------------------------------------------------------
465
+
466
+ /**
467
+ * How much one ledger row is worth to the customer, in EUR (always >= 0).
468
+ *
469
+ * `amount_eur` is signed from the user's side (negative = spent) and is what
470
+ * /api/token-bank/balance actually returns. `charged_micros` is the raw
471
+ * column with the OPPOSITE sign, kept only as a fallback for a server build
472
+ * that drops amount_eur — which is why it is negated here.
473
+ *
474
+ * Returns null for a row that is not a charge at all, or that carries no
475
+ * usable number. Anything non-finite is null rather than NaN: a NaN that
476
+ * reaches a tally poisons it for the rest of the session, and a NaN written
477
+ * into history.jsonl is invisible until /cost renders it.
478
+ */
479
+ function ledgerRowEur(row) {
480
+ if (!row || typeof row !== 'object') return null;
481
+ // A top-up is money IN, not a charge. Folding one into the spend tally
482
+ // would report a customer who just added €20 as having spent €20.
483
+ if (row.kind !== 'usage') return null;
484
+ const raw = row.amount_eur != null ? Number(row.amount_eur) : -Number(row.charged_micros || 0) / 1e6;
485
+ if (!Number.isFinite(raw)) return null;
486
+ // The magnitude is the charge either way; the server's sign convention for
487
+ // a spend row is not something this client should depend on.
488
+ return Math.abs(raw);
489
+ }
490
+
491
+ /**
492
+ * The identity of a ledger row, used to decide "is this new?".
493
+ *
494
+ * Deliberately NOT `created_at`. That column is stamped to the second, so two
495
+ * turns inside the same second collide: the second row compared equal to the
496
+ * first, was skipped as "already counted", and — because chatflow persists the
497
+ * turn with whatever this returned — the exchange was written to history.jsonl
498
+ * with NO charge attached. /cost then fell back to the local rate table for
499
+ * that turn and reported a figure that was not the bill. Every column the
500
+ * endpoint returns that can distinguish two rows is folded in here.
501
+ *
502
+ * The endpoint returns no unique row id (see mcp/tools.js, which reads the
503
+ * same columns), so this is content-based and two genuinely identical charges
504
+ * — same model, same token counts, same second — hash the same. That is why
505
+ * callers count occurrences rather than merely testing membership: a Set
506
+ * would treat the second identical charge as already-counted and silently
507
+ * under-bill it, which is the original defect wearing a different hat.
508
+ */
509
+ function ledgerRowKey(row) {
510
+ return [
511
+ row.created_at || '',
512
+ row.kind || '',
513
+ row.amount_eur != null ? row.amount_eur : '',
514
+ row.charged_micros != null ? row.charged_micros : '',
515
+ row.id != null ? row.id : '',
516
+ row.note != null ? row.note : '',
517
+ ].join('|');
518
+ }
519
+
520
+ /** Refresh the balance and fold any *new* usage row into the session tally.
521
+ *
522
+ * The first successful refresh of a session is a BASELINE: it observes the
523
+ * account's whole ledger and folds nothing. Each entry point therefore calls
524
+ * this once at session start, so the baseline can never swallow a real
525
+ * turn's charge. Best-effort: an accounting refresh must never break a turn.
526
+ *
527
+ * @returns {Promise<{balance:number, lastCost:number|null}|null>} */
528
+ async function refreshSpend() {
529
+ try {
530
+ const data = await client.tokenBankBalance();
531
+ const balance = Number(data.balance_eur);
532
+ if (Number.isFinite(balance)) session.balance = balance;
533
+ let lastCost = null;
534
+ const ledger = Array.isArray(data.ledger) ? data.ledger : [];
535
+
536
+ // Fold every row that is new since the last refresh, not just the head of
537
+ // the list. A single refresh can legitimately see more than one unseen
538
+ // charge — a refresh skipped while the balance endpoint was down, a long
539
+ // tool turn that dispatched two billed provider calls, or the first
540
+ // refresh after /billing already consumed the head — and taking only
541
+ // ledger[0] silently dropped the rest from the session tally.
542
+ //
543
+ // Count occurrences within the pass BEFORE folding, so two identical rows
544
+ // are billed twice. Testing membership one row at a time cannot tell the
545
+ // first occurrence from the second and under-charges by one.
546
+ const seenHere = new Map(); // key -> { n, row }
547
+ for (const row of ledger) {
548
+ const key = ledgerRowKey(row);
549
+ const hit = seenHere.get(key);
550
+ if (hit) hit.n += 1;
551
+ else seenHere.set(key, { n: 1, row });
552
+ }
553
+
554
+ for (const [key, { n, row }] of seenHere) {
555
+ const already = session.seenLedgerRows.get(key) || 0;
556
+ session.seenLedgerRows.set(key, n);
557
+
558
+ // This endpoint returns the ACCOUNT's ledger, so on the opening refresh
559
+ // it holds everything the customer has ever spent. Those rows are
560
+ // history — mark them seen and fold nothing, so `cost` starts at zero.
561
+ //
562
+ // Reaching this loop at all means the endpoint answered, so this pass
563
+ // really did observe the full ledger and it is safe to call it the
564
+ // baseline. That is deliberately self-healing: if the session-start
565
+ // call failed (offline, no balance rights) the NEXT successful refresh
566
+ // becomes the baseline, and the worst case is one turn under-reported.
567
+ // The reverse — folding an unobserved ledger — would report the
568
+ // customer's lifetime spend as "This session", a number they already
569
+ // paid and are not being charged again.
570
+ if (!session.ledgerBaselined) continue;
571
+
572
+ // Only the occurrences beyond those already accounted for are new.
573
+ const fresh = n - already;
574
+ if (fresh <= 0) continue;
575
+
576
+ const eur = ledgerRowEur(row);
577
+ if (eur != null && eur > 0) {
578
+ session.cost += eur * fresh;
579
+ // The charge to attribute to this turn. The endpoint returns the
580
+ // ledger NEWEST-FIRST (mcp/tools.js takes `.slice(0, 5)` as "Recent
581
+ // activity" and renders those as the latest rows), and the folds above
582
+ // run in that order, so the first charge seen here is the newest —
583
+ // i.e. the row this turn just produced. Taking the first rather than
584
+ // the largest matters when one pass sees several: the max would
585
+ // report an older, pricier call as this turn's cost.
586
+ if (lastCost == null) lastCost = eur;
587
+ }
588
+ }
589
+ session.ledgerBaselined = true;
590
+
591
+ return { balance: session.balance, lastCost };
592
+ } catch {
593
+ return null; // no balance rights / offline: keep showing tokens
594
+ }
595
+ }
596
+
597
+ // ── the AEGIS account key ─────────────────────────────────────────────────
598
+ //
599
+ // Set/forget at runtime, for `/key` and `aegiscode login`. Both paths are the
600
+ // same three steps — persist, apply to the live client, invalidate the model
601
+ // catalog — because a key that is stored but not applied leaves the current
602
+ // session failing, and one that is applied but not stored is gone next launch.
603
+
604
+ /**
605
+ * Persist an account key and start using it immediately.
606
+ *
607
+ * `verify` spends one `/api/verify-api-key` round trip to catch a bad key at
608
+ * the moment it is entered rather than at the first prompt, and is also how
609
+ * the memory token (cloud sync's credential) is obtained — so a successful
610
+ * login leaves both credentials in the store.
611
+ */
612
+ async function setApiKey(raw, { verify = true } = {}) {
613
+ const saved = credentials.saveApiKey(raw);
614
+ if (!saved.ok) return saved;
615
+ client.setApiKey(saved.key);
616
+ modelCache.models = [];
617
+ modelCache.at = 0;
618
+ let account = null;
619
+ let error = null;
620
+ if (verify) {
621
+ try {
622
+ const info = (await client.verifyApiKey()) || {};
623
+ account = info;
624
+ const patch = { verifiedAt: new Date().toISOString() };
625
+ if (info.memory_token) patch.memoryToken = info.memory_token;
626
+ if (info.plan) patch.plan = info.plan;
627
+ patch.account = { plan: info.plan || null, email: info.email || null, valid: info.valid !== false };
628
+ credentials.writeCredentials(patch);
629
+ if (info.plan) session.plan = info.plan;
630
+ if (info.email) session.account = { ...(session.account || {}), email: info.email };
631
+ } catch (e) {
632
+ error = e;
633
+ }
634
+ }
635
+ return { ...saved, account, error };
636
+ }
637
+
638
+ /** Drop the stored key and stop authenticating this session. */
639
+ function forgetApiKey() {
640
+ const res = credentials.clearApiKey();
641
+ client.setApiKey('');
642
+ modelCache.models = [];
643
+ modelCache.at = 0;
644
+ return res;
645
+ }
646
+
647
+ /** Explicit `/key register`: unlike the automatic path, this runs again after a failure. */
648
+ async function registerAccount() {
649
+ if (client.apiKey) return { alreadyKeyed: true };
650
+ return provisionDeviceKey();
651
+ }
652
+
653
+ /**
654
+ * The persisting-memory gate — the WRITE half of aegis_memory, and now ON by
655
+ * default for every account (see config.js `memoryPersistState` for the
656
+ * migration and the reasoning). The name is historical: `/sync`, `/cloud sync`
657
+ * and `cloudSyncEnabled()` predate the flip, and they all mean this one gate,
658
+ * so there is exactly one boolean behind every switch and status line.
659
+ */
660
+ function cloudSyncEnabled() {
661
+ try {
662
+ return memoryPersistEnabled();
663
+ } catch {
664
+ return true; // default on: a corrupt config must not silently stop storage
665
+ }
666
+ }
667
+
668
+ /** Where that answer came from — 'config' | 'legacy' | 'default'. */
669
+ function cloudSyncState() {
670
+ try {
671
+ return memoryPersistState();
672
+ } catch {
673
+ return { enabled: true, source: 'default', explicit: false };
674
+ }
675
+ }
676
+
677
+ function setCloudSync(on) {
678
+ return setMemoryPersist(on);
679
+ }
680
+
681
+ /**
682
+ * Copy a key found in config.json into the 0600 store, once, so the next run
683
+ * reads the tight copy. Never deletes the original — that file belongs to
684
+ * another product and holds the user's key.
685
+ */
686
+ function adoptLegacyKeyOnce() {
687
+ try {
688
+ const resolved = credentials.resolveApiKey();
689
+ if (resolved.source !== 'config') return [];
690
+ return credentials.adoptLegacy().adopted;
691
+ } catch {
692
+ return [];
693
+ }
694
+ }
695
+
696
+ // ── the AEGIS Cloud model catalog ──────────────────────────────────────────
697
+ //
698
+ // `/model` (and the alt+p chord that dispatches it) reads the pinnable ids
699
+ // from the server, and `state().models` is where it looks. That path had no
700
+ // source at all: `commands.js` calls `c.loadModels()` inside a `try {} catch
701
+ // {}`, `c.loadModels` was never defined on either command context, and
702
+ // `buildState()` hardcoded `models: []` — so the TypeError was swallowed and
703
+ // both `/model` and the picker reported "no models advertised" on a perfectly
704
+ // healthy account, forever. The ids themselves are the server's (see
705
+ // models.js), fetched here and cached, because the pool adds and retires
706
+ // providers without a client release.
707
+ const MODEL_CACHE_MS = 5 * 60_000;
708
+ const modelCache = { at: 0, models: [] };
709
+ // The BYOK half of the same question. A BYOK model id is `provider:model`
710
+ // (the engine's splitByokModel), built from the server's provider catalog
711
+ // plus the provider rows this machine actually holds a key for — so this list
712
+ // is per-machine, not per-account, and cannot be served by the pooled catalog.
713
+ const byokCache = { at: 0, models: [], declared: '' };
714
+
715
+ /**
716
+ * The user-model declarations (`$AEGISCODE_HOME/models.json`) as one
717
+ * comparable string, or '' when they cannot be read.
718
+ *
719
+ * The byok list is not only the server's: `engine.listModels('byok')` folds
720
+ * the USER's own declarations into each provider row (`client/user-models.js`
721
+ * `withUserModels`), so the id set can change with no network call and no
722
+ * provider catalog change. A custom provider in particular has NO catalog
723
+ * model at all — its rows exist solely because someone declared them — so a
724
+ * cache keyed only on time shows an empty provider for up to five minutes
725
+ * after the declaration was written.
726
+ *
727
+ * That is the cross-host case this exists for: the desktop's Custom provider
728
+ * card, `/model-add` in another terminal, and a hand-edited file all write
729
+ * the SAME file, and none of them can reach this process's `byokCache`. So
730
+ * the file's content is part of the cache key: a declaration made elsewhere
731
+ * is visible the next time the picker is opened, not five minutes later.
732
+ *
733
+ * Read through `engine.userModels()` rather than the path, so this stays one
734
+ * store and one implementation (the CLI's engine is the same module the
735
+ * desktop uses). A store that throws is treated as unchanged — the time
736
+ * window still expires the cache, so a broken read cannot pin stale rows
737
+ * forever.
738
+ */
739
+ function declaredModelsKey() {
740
+ try {
741
+ if (typeof engine.userModels !== 'function') return '';
742
+ const map = (engine.userModels() || {}).map || {};
743
+ return JSON.stringify(Object.keys(map).sort().map((p) => [p, map[p]]));
744
+ } catch {
745
+ return '';
746
+ }
747
+ }
748
+
749
+ async function loadByokModels({ force = false } = {}) {
750
+ const declared = declaredModelsKey();
751
+ const fresh =
752
+ byokCache.models.length &&
753
+ Date.now() - byokCache.at < MODEL_CACHE_MS &&
754
+ // The declarations are part of the key: see declaredModelsKey().
755
+ declared === byokCache.declared;
756
+ if (!force && fresh) return byokCache.models;
757
+ // An injected engine (tests, embedding) may predate the class surface; an
758
+ // empty list is the honest answer then, not a fabricated one.
759
+ if (typeof engine.listModels !== 'function') return [];
760
+ const res = await engine.listModels('byok');
761
+ // The engine's row is `{id: "provider:model", label, provider, configured}`.
762
+ // `note` is added here because it is the field both renderers actually paint
763
+ // (the picker draws `m.note || m.model`, /models draws `m.note || m.label`)
764
+ // and because "openai:gpt-4o" alone does not say whether this machine holds
765
+ // the key the relay would ask for — a row without one is a turn that 400s,
766
+ // so it names the command that fixes it.
767
+ byokCache.models = ((res && res.models) || []).map((m) => ({
768
+ ...m,
769
+ note: m.configured ? 'key on this machine' : `no key — /byok-key ${m.provider}`,
770
+ }));
771
+ byokCache.at = Date.now();
772
+ byokCache.declared = declared;
773
+ return byokCache.models;
774
+ }
775
+
776
+ /**
777
+ * The ids pinnable on one class — the ONE function `/model`, alt+p and
778
+ * `/models` all read, so the picker cannot offer something the class the turn
779
+ * runs on would reject. Both branches swallow their failure into "nothing to
780
+ * offer": a catalog is a convenience, and an offline client must still be
781
+ * able to chat on the server's own default.
782
+ */
783
+ async function listModelsFor(cls) {
784
+ // The OFFERED set, not HOST_CLASSES: a class that is not selectable (a
785
+ // disabled `pro`) yields NOTHING rather than the live class's rows. The
786
+ // merged picker tags whatever comes back as belonging to the class it
787
+ // asked about, so substituting pooled rows here would paint pooled ids as
788
+ // Pro rows — and pinning one would move the session onto the subscription.
789
+ const allowed = selectableClasses();
790
+ if (cls && !allowed.includes(cls) && HOST_CLASSES.includes(cls)) return [];
791
+ const want = allowed.includes(cls) ? cls : commandCtx.modelClass;
792
+ try {
793
+ if (want === 'byok') {
794
+ const byok = await loadByokModels();
795
+ // The pooled catalog may never have been fetched on a byok-only session
796
+ // (`/model` alone on a fresh install), and the Nexus row below can only
797
+ // come from it — so read it here, best-effort. A failed read (offline,
798
+ // or no account key) leaves the byok rows, which is the honest list: no
799
+ // pooled row, rather than one this process cannot name.
800
+ if (!modelCache.models.length) {
801
+ try {
802
+ await loadModels();
803
+ } catch {
804
+ /* no pooled catalog to read — byok rows stand alone */
805
+ }
806
+ }
807
+ // `want`, not the live class: this call is answering for the class it
808
+ // was ASKED about. See classScopedModels.
809
+ return classScopedModels(byok, want);
810
+ }
811
+ if (want === 'pro') {
812
+ // The Claude Code Pro class' rows come from the engine itself (the
813
+ // CLI's own aliases, claude-pro.js PRO_MODELS) rather than from a
814
+ // fetched catalog, so they are read straight off listModels('pro') —
815
+ // one source, the same one the desktop's picker reads.
816
+ //
817
+ // NOT gated on the subscription already being present — that gate used
818
+ // to hide every pro row until `~/.claude/.credentials.json` (or
819
+ // CLAUDE_CODE_OAUTH_TOKEN) already existed, which made the row
820
+ // impossible to ever reach from THIS picker: there was no way to pick
821
+ // "Claude Code Pro" to set the credential up in the first place, only
822
+ // to confirm one that was already there. A byok row offers exactly the
823
+ // same way with no key either, and picking it is what collects one
824
+ // (`collectKeyFor`, chatflow.js) — a pro row now does the same,
825
+ // through the very token `modelKeyQueue` asks for (client/env-file.js
826
+ // keyForModelId's `foreign: true` branch). `configured` on each row
827
+ // still states whether a turn would succeed RIGHT NOW; listing is a
828
+ // separate question from being ready.
829
+ const info = await engine.listModels('pro');
830
+ return (info && info.models) || [];
831
+ }
832
+ // Anything else is asked of the engine by name — 'local' especially,
833
+ // which used to fall through to the pooled catalog below and so answered
834
+ // "here are the AEGIS Cloud models" to a question about the free local
835
+ // class. Only 'aegis' (the pool) is read from the cached client fetch.
836
+ if (want !== 'aegis') {
837
+ const info = await engine.listModels(want);
838
+ return (info && info.models) || [];
839
+ }
840
+ return await loadModels();
841
+ } catch {
842
+ return [];
843
+ }
844
+ }
845
+
846
+ /** The pooled class's pickable rows, each tagged with the class it runs on. */
847
+ function pooledRows() {
848
+ return pickerEntries(modelCache.models).map((m) => ({ ...m, cls: 'aegis' }));
849
+ }
850
+
851
+ /** The byok class's own `provider:model` rows, tagged the same way. */
852
+ function byokRows() {
853
+ return pickerEntries(byokCache.models).map((m) => ({ ...m, cls: 'byok' }));
854
+ }
855
+
856
+ /**
857
+ * The Claude Code Pro class' rows, tagged the same way as the two above. The
858
+ * list is the CLI's own aliases (PRO_MODELS), which is why there is no cache
859
+ * here: nothing is fetched, so nothing can go stale or be missing offline.
860
+ */
861
+ function proRows() {
862
+ return pickerEntries(claudePro.PRO_MODELS.map((m) => ({
863
+ id: m.id,
864
+ label: m.label,
865
+ note: m.note,
866
+ }))).map((m) => ({ ...m, cls: 'pro' }));
867
+ }
868
+
869
+ /**
870
+ * The class-scoped model list — `state().models`, `/models`, the alt+p chord
871
+ * and the `/class` auto-pick all read it, so it is one list and not four.
872
+ *
873
+ * On the POOLED class it is just the catalog's pickable rows. On the BYOK
874
+ * class it is those rows PLUS the pooled Nexus row, which the server's
875
+ * `provider:model` listing can never contain: the two id spaces are disjoint
876
+ * (`models.js` documents it, and `pinBelongsToClass` enforces it), so a
877
+ * session sitting on byok used to see a list with no way back to the pooled
878
+ * lane in it — the same "correct list, undiscoverable half" defect
879
+ * `mergedPickerModels` in commands.js fixes for the `/model` picker, fixed
880
+ * here for the list the other surfaces read, so the panel, the chord and the
881
+ * picker cannot disagree about whether Nexus is an option.
882
+ *
883
+ * Each row carries its own `cls`, which is what the picker's ENTER handler
884
+ * switches on and what `/models` paints its "pooled lane" marker from:
885
+ * picking Nexus from the byok list moves the session to the pooled class
886
+ * BEFORE the pin applies, because a pooled id pinned under byok is parsed as
887
+ * a provider name and 400s at the relay. Tagging is not decoration — it is
888
+ * why this row is safe to offer from a class that cannot run it.
889
+ *
890
+ * The pooled row comes from the same `pickerEntries` shaping the pooled class
891
+ * uses (`filterAegisCatalog`'s single-row collapse), never a hand-built
892
+ * literal: a second spelling of "the brain's id and label" is exactly the
893
+ * drift `client/brain-catalog.js` exists to end. Its absence is not an error
894
+ * — no account key means no pooled catalog to read, and a byok-only session
895
+ * must still list its own models.
896
+ *
897
+ * @param {Array<object>} [byokOverride] rows already fetched by an async
898
+ * caller, so an awaiting caller does not re-read a cache it just filled.
899
+ * @param {string} [cls] the class to answer FOR. Defaults to the live class,
900
+ * which is what `state().models` wants — but not what `/model` wants.
901
+ *
902
+ * THE CLASS ASKED IS NOT THE CLASS LIVE, and conflating them is what emptied
903
+ * the picker. `mergedPickerModels` (commands.js) asks this module for all
904
+ * three classes in one turn — it opens ONE list containing pooled, byok and
905
+ * Pro rows so a model in another class is reachable without knowing to run
906
+ * `/class` first. Answering every one of those asks from the LIVE class made
907
+ * that merge a lie: on the default `aegis` class the byok ask came back with
908
+ * the pooled rows again (tagged `byok`, so the picker painted Nexus and
909
+ * deepseek twice and the provider ids never at all), and on the `pro` class
910
+ * the pooled ask came back with Pro's aliases — the list a user reads as
911
+ * "only pool and sonnet, where are the rest of my models?". The requested
912
+ * class is the parameter precisely so a caller may ask about a class it is
913
+ * not on; only an absent/unknown `cls` may fall back to the live one.
914
+ */
915
+ function classScopedModels(byokOverride, cls) {
916
+ const allowed = selectableClasses();
917
+ const want = allowed.includes(cls) ? cls : commandCtx.modelClass;
918
+ // A disabled `pro` yields no rows at all — not the pooled ones either,
919
+ // because the caller asked for pro's id space and answering with pooled ids
920
+ // is the cross-class mix-up this branch exists to prevent (the merged
921
+ // picker would tag them `pro`).
922
+ if (cls === 'pro' && !allowed.includes('pro')) return [];
923
+ // The Pro class' list is its own alias set, never the pooled catalog: a
924
+ // pooled id pinned under pro would be sent to `claude --model`, which
925
+ // resolves aliases and real model names, not AEGIS ids — the same
926
+ // cross-class mismatch the byok branch below is shaped to prevent. It is
927
+ // checked before the pooled default for exactly that reason.
928
+ if (want === 'pro') return proRows();
929
+ if (want !== 'byok') return pooledRows();
930
+ const byok = Array.isArray(byokOverride)
931
+ ? byokOverride.map((m) => ({ ...m, cls: 'byok' }))
932
+ : byokRows();
933
+ return [...pooledRows(), ...byok];
934
+ }
935
+
936
+ /**
937
+ * The ids the Pro class can address: claude-pro.js's PRO_MODELS, lowercased
938
+ * once. Read from the module rather than re-listed, because the transport
939
+ * spawns `claude --model <id>` with these exact strings — a second list here
940
+ * could offer a row the child rejects, which is the cross-class defect the
941
+ * byok rule below is shaped to prevent.
942
+ */
943
+ function proModelIds() {
944
+ return new Set(claudePro.PRO_MODELS.map((m) => String(m.id).toLowerCase()));
945
+ }
946
+
947
+ /**
948
+ * Whether a pinned id can run on `cls`, decided synchronously (switchClass is
949
+ * not async). byok ids are `provider:model`; aegis and local take anything
950
+ * that is not — the pooled catalog is validated separately, at launch, by
951
+ * validatePinnedModel. pro takes ONLY its own aliases.
952
+ */
953
+ function pinBelongsToClass(cls, id) {
954
+ const s = String(id == null ? '' : id);
955
+ if (cls === 'byok') return s.includes(':');
956
+ // pro: `claude --model` resolves these aliases and full model names, and
957
+ // AEGIS ids are neither. Without this rule a pooled id ("deepseek") pinned
958
+ // under pro is handed to the child, which fails the turn with a message
959
+ // about a model rather than about the class the user is on.
960
+ if (cls === 'pro') return proModelIds().has(s.toLowerCase());
961
+ // aegis/local: not a byok id.
962
+ return !s.includes(':');
963
+ }
964
+
965
+ /**
966
+ * The classes selectable right now. `pro` is behind the `proEnabled` gate
967
+ * (config.js, default off): HOST_CLASSES says this host CAN run it, this says
968
+ * whether it has been opted into. Every surface that lists or validates a
969
+ * class reads this, so the gate cannot be honoured in one place and ignored
970
+ * in another. A config read failure answers "pro is off" (fail closed).
971
+ */
972
+ function selectableClasses() {
973
+ try {
974
+ return offeredClasses(proEnabled(loadConfig()));
975
+ } catch {
976
+ return offeredClasses(false);
977
+ }
978
+ }
979
+
980
+ /**
981
+ * Switch the live class. Refuses anything this host cannot run (engine.js's
982
+ * HOST_CLASSES is the authority) and anything it does not offer — `pro` needs
983
+ * a one-time `/class pro on` first.
984
+ *
985
+ * A pin is cleared when it does not belong to the class being entered: a
986
+ * pooled id pinned under byok would be parsed as provider `<pooled id>` and
987
+ * fail at the relay with a confusing "no key saved for …" instead of here,
988
+ * with a reason. Symmetrically, `anthropic:claude-…` under aegis is an id the
989
+ * pooled catalog does not advertise, which is the silent-fallback case
990
+ * validatePinnedModel exists to prevent.
991
+ */
992
+ function switchClass(next) {
993
+ const want = String(next == null ? '' : next).trim().toLowerCase();
994
+ const allowed = selectableClasses();
995
+ if (!allowed.includes(want)) {
996
+ if (want === 'pro') {
997
+ return {
998
+ ok: false,
999
+ error:
1000
+ 'the pro class (your Claude Code subscription) is off by default — ' +
1001
+ 'enable it once with `/class pro on`',
1002
+ };
1003
+ }
1004
+ return { ok: false, error: `unknown class "${next}" — classes: ${allowed.join(', ')}` };
1005
+ }
1006
+ const prev = commandCtx.modelClass;
1007
+ commandCtx.modelClass = want;
1008
+ let cleared = null;
1009
+ if (prev !== want && commandCtx.model) {
1010
+ if (!pinBelongsToClass(want, commandCtx.model)) {
1011
+ cleared = commandCtx.model;
1012
+ commandCtx.model = null;
1013
+ }
1014
+ }
1015
+ updateConfig({
1016
+ modelClass: want,
1017
+ model: commandCtx.model,
1018
+ currentModelId: commandCtx.model,
1019
+ });
1020
+ return { ok: true, class: want, prev, cleared };
1021
+ }
1022
+
1023
+ /**
1024
+ * Fetch (or return the cached) model catalog. Rejects when the account cannot
1025
+ * read it at all — no key, offline, or a server error — which callers treat as
1026
+ * "nothing to offer" rather than retrying per keystroke.
1027
+ * @returns {Promise<Array<{id:string,label:string,note:string}>>}
1028
+ */
1029
+ async function loadModels({ force = false } = {}) {
1030
+ const fresh = modelCache.models.length && Date.now() - modelCache.at < MODEL_CACHE_MS;
1031
+ if (!force && fresh) return modelCache.models;
1032
+ const data = await client.listModels();
1033
+ modelCache.models = normalizeModelCatalog(data && data.models);
1034
+ modelCache.at = Date.now();
1035
+ return modelCache.models;
1036
+ }
1037
+
1038
+ /**
1039
+ * A pinned model id the server does not advertise is a *silent* fallback: the
1040
+ * pool answers from its own default with no error, so the pin looks honoured
1041
+ * while the reply came from another model — and the cost is attributed to the
1042
+ * model that was pinned. Two shipped defaults did exactly that: `sonnet`
1043
+ * (written into config.json by onboarding, merged in from DEFAULT_CONFIG, and
1044
+ * never advertised by AEGIS Cloud) and any `provider/model` spelling a user
1045
+ * typed by hand. Clears such a pin once, says so, and leaves the server's own
1046
+ * default in its place.
1047
+ *
1048
+ * Best-effort and offline-safe: a catalog that cannot be read clears nothing.
1049
+ */
1050
+ async function validatePinnedModel() {
1051
+ const pinned = commandCtx.model;
1052
+ if (!pinned) return null;
1053
+ // A BYOK pin is validated by shape, not by the pooled catalog: the catalog
1054
+ // can never contain a `provider:model` id, so checking it here would clear
1055
+ // every legitimate BYOK pin on every launch.
1056
+ if (commandCtx.modelClass === 'byok') {
1057
+ if (String(pinned).includes(':')) return null;
1058
+ commandCtx.model = null;
1059
+ updateConfig({ model: null, currentModelId: null });
1060
+ emit(
1061
+ render.renderNotice(
1062
+ ctx(),
1063
+ 'warn',
1064
+ `pinned model "${pinned}" belongs to the pooled class — on BYOK an id is ` +
1065
+ '"<provider>:<model>"; pin cleared, /models lists what this machine can relay.'
1066
+ )
1067
+ );
1068
+ return pinned;
1069
+ }
1070
+ // A Pro pin is validated against the child's OWN alias list, locally, and
1071
+ // never against the pooled catalog: that catalogue cannot contain these
1072
+ // aliases, so checking it here would clear every legitimate Pro pin on every
1073
+ // launch. There is no fetch on this path either — the list is a constant, so
1074
+ // this is the one class whose validation cannot be defeated by being offline.
1075
+ if (commandCtx.modelClass === 'pro') {
1076
+ if (!proModelIds().has(String(pinned).toLowerCase())) {
1077
+ commandCtx.model = null;
1078
+ updateConfig({ model: null, currentModelId: null });
1079
+ emit(
1080
+ render.renderNotice(
1081
+ ctx(),
1082
+ 'warn',
1083
+ `pinned model "${pinned}" is not one the Claude Code CLI resolves — pin cleared, ` +
1084
+ `the CLI will choose; /models lists the aliases (${claudePro.PRO_MODELS.map((m) => m.id).join(', ')}).`
1085
+ )
1086
+ );
1087
+ return pinned;
1088
+ }
1089
+ // The alias resolves — but resolving an alias is not the same as having
1090
+ // anything to spend on it. This is the phantom-pin case aegiscodex-dev
1091
+ // learned first (phantomPin() in its src/backend.js): when the host has
1092
+ // no subscription and no console key, the `claude` child has no usable
1093
+ // credential, and the turn does not fail loudly here — it fails after a
1094
+ // round-trip with "Invalid API key" or "You've hit your session limit",
1095
+ // which reads like a provider outage rather than a missing credential.
1096
+ // Checked before the turn, so the user is told why and the pin stops
1097
+ // re-creating the problem on the next launch.
1098
+ let proCallable = true;
1099
+ try {
1100
+ const st = claudePro.claudeProStatus({ env: process.env });
1101
+ // `credentialPresent` — not `subscriptionPresent`, and not a fresh read
1102
+ // of `process.env` here. Three different questions live in this area and
1103
+ // conflating them is how the pin went unchecked in the first place:
1104
+ // - "is there a subscription to shadow?" → subscriptionPresent
1105
+ // (excludes a bare console key on disk, by design)
1106
+ // - "can this host serve a pro turn?" → credentialPresent (this one)
1107
+ // - "is this env value a credential?" → childEnvPlan's verdict
1108
+ // The third is why this reads a field instead of testing
1109
+ // `process.env.ANTHROPIC_API_KEY` directly: the planner REFUSES a value
1110
+ // that would be dropped from the child, so an env var alone is not
1111
+ // evidence of a route. See childEnvPlan / isAnthropicConsoleKey.
1112
+ proCallable = !!st.credentialPresent;
1113
+ } catch {
1114
+ // An unprovable credential is not a proven absence: leave the pin alone.
1115
+ proCallable = true;
1116
+ }
1117
+ if (!proCallable) {
1118
+ commandCtx.model = null;
1119
+ updateConfig({ model: null, currentModelId: null });
1120
+ emit(
1121
+ render.renderNotice(
1122
+ ctx(),
1123
+ 'warn',
1124
+ `pinned model "${pinned}" needs a Claude Pro subscription or an ` +
1125
+ `ANTHROPIC_API_KEY, and this host has neither — pin cleared. ` +
1126
+ `Run \`claude /login\`, export a console key, or \`/class pro off\`.`
1127
+ )
1128
+ );
1129
+ return pinned;
1130
+ }
1131
+ return null;
1132
+ }
1133
+ let models;
1134
+ try {
1135
+ models = await loadModels();
1136
+ } catch {
1137
+ return null;
1138
+ }
1139
+ if (!models.length) return null;
1140
+ if (catalogIds(models).has(String(pinned).toLowerCase())) return null;
1141
+ commandCtx.model = null;
1142
+ updateConfig({ model: null, currentModelId: null });
1143
+ emit(
1144
+ render.renderNotice(
1145
+ ctx(),
1146
+ 'warn',
1147
+ `pinned model "${pinned}" is not advertised by AEGIS Cloud — pin cleared, ` +
1148
+ 'the pool will choose; /models lists what you can pin.'
1149
+ )
1150
+ );
1151
+ return pinned;
1152
+ }
1153
+
1154
+ function bannerLines() {
1155
+ return render.renderBanner(ctx(), {
1156
+ width: width(),
1157
+ version: VERSION,
1158
+ model: commandCtx.model || 'server default',
1159
+ base: client.apiBase,
1160
+ key: maskKey(client.apiKey),
1161
+ stream: commandCtx.stream,
1162
+ });
1163
+ }
1164
+
1165
+ /**
1166
+ * Write lines out. Accepts a single line as well as a block — a bare string
1167
+ * would otherwise be iterated as characters, which renders a notice one
1168
+ * character per line.
1169
+ */
1170
+ function emit(lines) {
1171
+ const block = typeof lines === 'string' ? [lines] : lines;
1172
+ for (const l of block) out.write(l + '\n');
1173
+ }
1174
+
1175
+ // --- the ask path ---------------------------------------------------------
1176
+
1177
+ /**
1178
+ * One turn through the agent-loop engine (persistent-shell exec,
1179
+ * readFile/writeFile/editFile/listDir/glob/grep, Task subagents), streamed
1180
+ * into the live region. `history` is every prior turn's user/assistant pair
1181
+ * — never that turn's own tool-call scratchpad, which the engine keeps
1182
+ * internally and never returns (see engine.js's `chat()`).
1183
+ * @returns {Promise<{text:string, usage:object|null, model:string|null, ms:number, interrupted:boolean}>}
1184
+ */
1185
+ async function ask(prompt, { history = [], presenter = null, signal = null } = {}) {
1186
+ const started = Date.now();
1187
+ // A presenter takes over ALL presentation (the chatflow's frame paints the
1188
+ // streaming answer into a transcript row), so the linear/inline live region
1189
+ // is only built when there is none.
1190
+ const live =
1191
+ !presenter && opts.interactive && opts.stream && out.isTTY ? new LiveRegion(out) : null;
1192
+ let tick = 0;
1193
+ let chars = 0;
1194
+ let partial = '';
1195
+ let reasoning = 0;
1196
+ // Thinking tokens the PROVIDER measured, added verbatim. A subscription
1197
+ // turn withholds its deliberation text (`thinking_delta.thinking` is the
1198
+ // empty string), so the `reasoning` char count above stays 0 for the whole
1199
+ // thinking phase and the spinner read `↓0 tokens` while thousands of
1200
+ // thinking tokens were billed. Not routed through `w()`/4: this is already
1201
+ // a token count, and dividing it would print a quarter of the truth.
1202
+ let thinkingTokens = 0;
1203
+ let verb = VERBS[Math.floor(Math.random() * VERBS.length)];
1204
+ let sawReasoning = false;
1205
+ let usedTools = false;
1206
+
1207
+ const paint = () => {
1208
+ if (!live) return;
1209
+ live.update([
1210
+ render.renderWorking(ctx(), {
1211
+ tick: tick++,
1212
+ verb,
1213
+ elapsedMs: Date.now() - started,
1214
+ // `chars` accumulates `w(chunk.delta)` — a display width, not a token
1215
+ // count — and render.js prints this field as `↓N tokens`. Converted at
1216
+ // the producer so both spinner renderers receive the same unit.
1217
+ //
1218
+ // `+ reasoning` because the live figure is the turn's BILLED output:
1219
+ // the answer plus the thinking trace it is charged for, which is what
1220
+ // the desktop's bubble sums (`desktop/renderer/app.js`: reply +
1221
+ // reasoning cells at this same ratio). Reasoning is accumulated in its
1222
+ // own variable above so the "reasoned but wrote nothing" case stays
1223
+ // distinguishable — but leaving it out of the figure here stalled the
1224
+ // spinner on `↓0 tokens` for the whole thinking phase of every turn,
1225
+ // which is the row that exists to show the turn is moving.
1226
+ streamed: estimateTokensFromCells(chars + reasoning) + thinkingTokens,
1227
+ // See render.js: any contribution from `thinkingTokens` is Anthropic's
1228
+ // own under-counting running estimate, not the real billed figure.
1229
+ streamedFloor: thinkingTokens > 0,
1230
+ }),
1231
+ ]);
1232
+ };
1233
+
1234
+ const timer = live ? setInterval(paint, 90) : null;
1235
+ if (timer && timer.unref) timer.unref();
1236
+ paint();
1237
+
1238
+ // Presentation hooks. With no presenter these reproduce the linear
1239
+ // behaviour exactly (live-region spinner, tool rows written to scrollback).
1240
+ const p = presenter || {};
1241
+ // The engine opens a tool with a `phase: 'run'` frame BEFORE the executor
1242
+ // runs, so a writeFile preview built here still reads the pre-edit file.
1243
+ // Cached per tool id so the later `done` frame reuses the same preview
1244
+ // instead of re-reading a file the tool has already overwritten (which
1245
+ // would diff clean and show nothing).
1246
+ const diffCache = new Map();
1247
+ const previewFor = (tool) => {
1248
+ const key =
1249
+ tool && tool.id !== undefined
1250
+ ? `id:${tool.id}`
1251
+ : `${tool && tool.name}:${JSON.stringify(tool && tool.args)}`;
1252
+ if (!diffCache.has(key)) {
1253
+ diffCache.set(key, editPreview(tool && tool.name, tool && tool.args, { cwd: process.cwd() }));
1254
+ }
1255
+ return diffCache.get(key);
1256
+ };
1257
+ const present = {
1258
+ text: (d) => {
1259
+ if (p.text) return p.text(d);
1260
+ if (live && tick % 2 === 0) paint();
1261
+ return undefined;
1262
+ },
1263
+ reasoning: (r) => {
1264
+ if (p.reasoning) return p.reasoning(r);
1265
+ return undefined;
1266
+ },
1267
+ // Token-count channel, distinct from `reasoning` above (which is text).
1268
+ // A presenter drives its own spinner, so it must receive this or the live
1269
+ // figure stays at 0 for the whole thinking phase of a subscription turn.
1270
+ thinkingTokens: (n) => {
1271
+ if (p.thinkingTokens) return p.thinkingTokens(n);
1272
+ return undefined;
1273
+ },
1274
+ tool: (tool) => {
1275
+ if (p.tool) return p.tool(tool);
1276
+ if (live) live.clear();
1277
+ const diff = previewFor(tool);
1278
+ emit(
1279
+ render.renderTurn(
1280
+ ctx(),
1281
+ { role: 'tool', label: tool.name, args: tool.args, ok: tool.ok, diff, diffOpen: defaultOpen(diff) },
1282
+ width()
1283
+ )
1284
+ );
1285
+ paint();
1286
+ return undefined;
1287
+ },
1288
+ };
1289
+
1290
+ const sessionId = randomUUID();
1291
+ activeSessionId = sessionId;
1292
+ let interrupted = false;
1293
+ // One cancel path for both callers: a SIGINT from the process, and the
1294
+ // chatflow's Esc, which aborts the controller it handed in. Without this
1295
+ // second source the full-screen loop's Esc had nothing listening to it —
1296
+ // the turn kept running and billing while the UI said "stopped".
1297
+ const cancel = () => {
1298
+ interrupted = true;
1299
+ engine.cancel(sessionId);
1300
+ };
1301
+ const onSigint = () => cancel();
1302
+ process.once('SIGINT', onSigint);
1303
+ if (signal) {
1304
+ if (signal.aborted) cancel();
1305
+ else signal.addEventListener('abort', cancel, { once: true });
1306
+ }
1307
+
1308
+ // A denial with no one to ask it of: -p and any other run with no
1309
+ // approvalPrompter set. Fails safe (deny) rather than hanging the tool
1310
+ // round forever waiting for an answer nobody can give.
1311
+ const denyNoPrompter = (info) => {
1312
+ err.write(
1313
+ `aegiscode: ${info.tool} needs confirmation but this run has no prompt for it — denied ` +
1314
+ '(pass --automode (alias --yolo) to auto-approve mutating tools).\n'
1315
+ );
1316
+ return Promise.resolve('deny');
1317
+ };
1318
+
1319
+ // The round-horizon ask's own no-one-to-answer fallback. Unreachable in
1320
+ // practice — `roundsAsk` below is only sent `true` when `p.rounds` exists,
1321
+ // so the engine never raises the ask without a prompter — but kept so a
1322
+ // future caller that forgets the guard fails safe (stop) instead of
1323
+ // hanging the tool loop on an unanswerable promise.
1324
+ const denyRoundsNoPrompter = () => Promise.resolve(false);
1325
+
1326
+ // Vocabulary bridging lives at module scope (see normalizeDecision) so the
1327
+ // same function the tests import is the one the live path calls.
1328
+ const onDelta = (chunk) => {
1329
+ if (!chunk) return;
1330
+ // Provider-measured thinking progress — the ONLY live signal on a
1331
+ // subscription turn, whose deliberation text is withheld. Counted and
1332
+ // repainted, but never handed to `present.reasoning`: that channel is
1333
+ // text and its consumers accumulate display width from it.
1334
+ if (chunk.thinkingTokens) {
1335
+ thinkingTokens += chunk.thinkingTokens;
1336
+ if (!sawReasoning) {
1337
+ sawReasoning = true;
1338
+ verb = 'Reasoning';
1339
+ }
1340
+ present.thinkingTokens(chunk.thinkingTokens);
1341
+ paint();
1342
+ }
1343
+ if (chunk.reasoning) {
1344
+ reasoning += w(chunk.reasoning);
1345
+ // The pool's worker findings arrive on the reasoning channel before
1346
+ // the answer; say so rather than looking stalled.
1347
+ if (!sawReasoning) {
1348
+ sawReasoning = true;
1349
+ verb = 'Reasoning';
1350
+ paint();
1351
+ }
1352
+ present.reasoning(chunk.reasoning);
1353
+ }
1354
+ if (chunk.delta) { chars += w(chunk.delta);
1355
+ partial += chunk.delta;
1356
+ present.text(chunk.delta);
1357
+ }
1358
+ if (chunk.tool) {
1359
+ usedTools = true;
1360
+ present.tool(chunk.tool);
1361
+ }
1362
+ if (chunk.approval) {
1363
+ const info = chunk.approval;
1364
+ if (live) live.clear();
1365
+ const decide = p.approval || approvalPrompter || denyNoPrompter;
1366
+ Promise.resolve(decide(info))
1367
+ .catch(() => 'deny')
1368
+ .then((decision) => engine.respondApproval(info.id, normalizeDecision(decision)));
1369
+ }
1370
+ if (chunk.rounds) {
1371
+ const info = chunk.rounds;
1372
+ if (live) live.clear();
1373
+ const decide = p.rounds || denyRoundsNoPrompter;
1374
+ Promise.resolve(decide(info))
1375
+ .catch(() => false)
1376
+ .then((decision) => engine.respondRoundsAsk(info.id, decision === true));
1377
+ }
1378
+ };
1379
+
1380
+ try {
1381
+ const res = await engine.chat(
1382
+ {
1383
+ prompt,
1384
+ messages: history,
1385
+ model: commandCtx.model || undefined,
1386
+ // A caller-supplied system wins; otherwise the shared persona. Sent
1387
+ // explicitly rather than left to the server, because the pooled
1388
+ // route takes the system prompt from the request and the CLI was
1389
+ // sending none — the model got tool schemas and no rule about when
1390
+ // to use them.
1391
+ system: opts.system || defaultSystemPrompt(),
1392
+ maxTokens: opts.maxTokens,
1393
+ // `effort` is the budget rung, and it travels on EVERY turn for every
1394
+ // model — this host only ever runs the 'aegis' class, whose calls are
1395
+ // sized server-side from it (aegis1 services/pool_brain.py), and BYOK
1396
+ // turns translate it per vendor in cli/src/engine.js. A stored `null`
1397
+ // or a value this build no longer offers resolves to `high` — the
1398
+ // same rung the desktop and the engine apply — instead of being
1399
+ // omitted, because omitting it was the defect: `auto` was the
1400
+ // default, so nothing reached the wire and the levels changed the
1401
+ // status line and nothing else.
1402
+ effort: effortRung(commandCtx.effort),
1403
+ // The deep-recall opt-in travels only when this session turned it on
1404
+ // (`/memory-deep on`). Sent as a literal `true` or not at all: the
1405
+ // engine treats anything but `true` as off, and an omitted field is
1406
+ // what keeps a stray value from ever buying a per-turn embedding.
1407
+ recallDeep: commandCtx.recallDeep === true ? true : undefined,
1408
+ // false asks the engine for the buffered (non-stream) wire form, so
1409
+ // `--no-stream` and piped runs get a single body rather than SSE.
1410
+ stream: commandCtx.stream !== false,
1411
+ sessionId,
1412
+ // The CONVERSATION id, which `sessionId` above is not — that one is
1413
+ // minted fresh for THIS turn so a cancel can target it. Memory that
1414
+ // has to outlive a turn (the Pro class's `claude` child session) is
1415
+ // keyed by this one instead, so a thread keeps its context and
1416
+ // `/new` or `/resume` genuinely starts/continues a different one.
1417
+ sessionKey: commandCtx.sessionId,
1418
+ // Opt-in to the round-horizon dialog (see engine.js requestRoundsAsk)
1419
+ // only when there is actually a `rounds` prompter to answer it — a
1420
+ // one-shot `-p` run or any other caller with no presenter keeps the
1421
+ // engine's old stop-and-record-session behaviour untouched.
1422
+ roundsAsk: Boolean(p.rounds),
1423
+ },
1424
+ onDelta
1425
+ );
1426
+
1427
+ const choice = (res.choices && res.choices[0]) || {};
1428
+ const text = (choice.message && choice.message.content) || partial;
1429
+ return {
1430
+ text,
1431
+ usage: res.usage || null,
1432
+ model: res.model || commandCtx.model || null,
1433
+ ms: Date.now() - started,
1434
+ interrupted,
1435
+ reasoningChars: reasoning,
1436
+ usedTools,
1437
+ };
1438
+ } catch (e) {
1439
+ // A user interrupt is not a failure: keep what already streamed.
1440
+ if (interrupted && partial) {
1441
+ return {
1442
+ text: partial,
1443
+ usage: null,
1444
+ model: commandCtx.model || null,
1445
+ ms: Date.now() - started,
1446
+ interrupted: true,
1447
+ reasoningChars: reasoning,
1448
+ usedTools,
1449
+ };
1450
+ }
1451
+ throw e;
1452
+ } finally {
1453
+ if (timer) clearInterval(timer);
1454
+ process.removeListener('SIGINT', onSigint);
1455
+ if (signal) signal.removeEventListener('abort', cancel);
1456
+ if (live) live.clear();
1457
+ activeSessionId = null;
1458
+ }
1459
+ }
1460
+
1461
+ /** Print a completed turn: role block, then the accounting line. */
1462
+ function printTurn(turn) {
1463
+ emit(render.renderTurn(ctx(), turn, width()));
1464
+ }
1465
+
1466
+ /** Prior user/assistant pairs from the live transcript, for the engine. */
1467
+ function historyPairs() {
1468
+ return transcript
1469
+ .filter((m) => m.role === 'user' || m.role === 'assistant')
1470
+ .map((m) => ({ role: m.role, content: m.text }));
1471
+ }
1472
+
1473
+ /** Ask, then account for it. Shared by plain prompts and `/ask`. */
1474
+ async function runPrompt(prompt, { label = 'you' } = {}) {
1475
+ if (!prompt) {
1476
+ emit(render.renderNotice(ctx(), 'warn', 'nothing to ask — give /ask a prompt'));
1477
+ return;
1478
+ }
1479
+ if (!client.apiKey) await ensureApiKey();
1480
+ if (!client.apiKey) {
1481
+ emit(
1482
+ render.renderNotice(
1483
+ ctx(),
1484
+ 'error',
1485
+ `no AEGIS account key — ${credentials.HOW_TO_SET} (or set $${credentials.KEY_ENV})`
1486
+ )
1487
+ );
1488
+ return;
1489
+ }
1490
+
1491
+ const history = historyPairs();
1492
+ printTurn({ role: 'user', text: prompt, label });
1493
+ transcript.push({ role: 'user', text: prompt });
1494
+
1495
+ let res;
1496
+ try {
1497
+ res = await ask(prompt, { history });
1498
+ } catch (e) {
1499
+ persistTurn(prompt, { text: '', error: e.message }, 'error');
1500
+ emit(render.renderTurn(ctx(), { role: 'error', text: e.message }, width()));
1501
+ return;
1502
+ }
1503
+
1504
+ if (res.text) transcript.push({ role: 'assistant', text: res.text });
1505
+
1506
+ const tokens = recordTurn(res);
1507
+
1508
+ // Ask the ledger what this call settled at BEFORE persisting it. The order
1509
+ // is the whole point: the charge is the server's number (pool margin and
1510
+ // prompt-cache discount included) and only the ledger knows it. Persisting
1511
+ // first wrote the exchange with no charge attached, so /cost recomputed it
1512
+ // from a local rate table that knows about neither — and the figure the
1513
+ // customer read did not match the bill they paid. Same ordering as the
1514
+ // chatflow session loop.
1515
+ let settledCost = null;
1516
+ try {
1517
+ const spend = await refreshSpend();
1518
+ settledCost = spend ? spend.lastCost : null;
1519
+ } catch {
1520
+ /* accounting must never break a turn */
1521
+ }
1522
+ persistTurn(prompt, res, res.interrupted ? 'stopped' : res.error ? 'error' : 'done', settledCost);
1523
+
1524
+ printTurn({
1525
+ role: 'assistant',
1526
+ text: res.text || '(the pool returned no text — see /balance for what it charged)',
1527
+ meta: {
1528
+ model: res.model,
1529
+ tokens,
1530
+ // Folded through the SHARED normaliser, for the same reason recordTurn
1531
+ // is (see its comment): the providers do not merely spell these fields
1532
+ // differently, they MEASURE them differently. Anthropic's `input_tokens`
1533
+ // EXCLUDES `cache_read_input_tokens`; OpenAI's and DeepSeek's
1534
+ // `prompt_tokens` INCLUDES `prompt_cache_hit_tokens`. Reading the raw
1535
+ // field here therefore printed the WHOLE prompt as fresh input on a
1536
+ // cached turn — the cache-hit half restated at miss price, in the one
1537
+ // row a user reads immediately after every turn. That is precisely the
1538
+ // "the CLI's live tally disagrees with its own ledger about the same
1539
+ // turn" defect recordTurn's comment names; this call site was the one
1540
+ // it did not cover, and it is why the CLI's per-turn token readout ran
1541
+ // far above the engine's for the same turn on the same model.
1542
+ usage: res.usage == null ? null : usageBuckets(res.usage),
1543
+ // What this call settled at, from the ledger row it produced — the
1544
+ // number that has to agree with the token count beside it.
1545
+ eur: settledCost,
1546
+ ms: res.ms,
1547
+ calls: 1,
1548
+ },
1549
+ });
1550
+
1551
+ if (res.interrupted) {
1552
+ emit(render.renderNotice(ctx(), 'warn', 'interrupted — the pool may still be running and billing this call'));
1553
+ }
1554
+ }
1555
+
1556
+ // --- command dispatch -----------------------------------------------------
1557
+
1558
+ async function runTool(name, args) {
1559
+ const tool = TOOLS[name];
1560
+ if (!tool) throw new Error(`unknown tool: ${name}`);
1561
+ if (!client.apiKey) await ensureApiKey();
1562
+ if (!client.apiKey) {
1563
+ throw new Error(`no AEGIS account key — ${credentials.HOW_TO_SET}`);
1564
+ }
1565
+ const text = await tool.run(args || {});
1566
+ emit(render.renderToolResult(ctx(), name, text, width()));
1567
+ }
1568
+
1569
+ /**
1570
+ * The nearest routable name to a mistyped one: a prefix of it, or a name it
1571
+ * is a prefix of. Deliberately simple — `cli/src/fuzzy.js` is a separate
1572
+ * workstream and may not exist, so this must not depend on it.
1573
+ */
1574
+ function nearest(name) {
1575
+ const n = String(name || '').toLowerCase();
1576
+ if (!n) return null;
1577
+ let best = null;
1578
+ for (const c of COMMANDS) {
1579
+ for (const cand of [c.name, ...(c.aliases || [])]) {
1580
+ if (cand === n) continue;
1581
+ if (cand.startsWith(n) || n.startsWith(cand)) {
1582
+ if (best == null || Math.abs(cand.length - n.length) < Math.abs(best.length - n.length)) {
1583
+ best = cand;
1584
+ }
1585
+ }
1586
+ }
1587
+ }
1588
+ return best;
1589
+ }
1590
+
1591
+ /** Tokenize one argument string, honouring single/double quotes. */
1592
+ function tokenize(s) {
1593
+ const out = [];
1594
+ let cur = '';
1595
+ let quote = null;
1596
+ let has = false;
1597
+ for (const ch of String(s || '')) {
1598
+ if (quote) {
1599
+ if (ch === quote) quote = null;
1600
+ else cur += ch;
1601
+ continue;
1602
+ }
1603
+ if (ch === '"' || ch === "'") { quote = ch; has = true; continue; }
1604
+ if (/\s/.test(ch)) {
1605
+ if (cur || has) { out.push(cur); cur = ''; has = false; }
1606
+ continue;
1607
+ }
1608
+ cur += ch;
1609
+ has = true;
1610
+ }
1611
+ if (cur || has) out.push(cur);
1612
+ return out;
1613
+ }
1614
+
1615
+ /** Positional args keyed by the entry's `args` names, plus `_rest`. */
1616
+ function parseArgs(cmd, arg) {
1617
+ const raw = String(arg == null ? '' : arg);
1618
+ const names = Array.isArray(cmd.args) ? cmd.args : [];
1619
+ const tokens = tokenize(raw);
1620
+ const out = { _rest: raw.trim() };
1621
+ names.forEach((n, i) => { if (tokens[i] !== undefined) out[n] = tokens[i]; });
1622
+ return out;
1623
+ }
1624
+
1625
+ /** A fresh snapshot for panels.js (the frozen `c.state()` shape). */
1626
+ function buildState() {
1627
+ const rules = loadPermissions();
1628
+ // ON8: `/status` reports the POSTURE, so a gate turned off in the window
1629
+ // shows here as `allow` rather than as a rule file that no longer decides.
1630
+ const posture = confirmPosture();
1631
+ return {
1632
+ version: VERSION,
1633
+ model: commandCtx.model || 'server default',
1634
+ class: commandCtx.modelClass,
1635
+ effort: commandCtx.effort,
1636
+ thinking: commandCtx.thinking,
1637
+ theme: commandCtx.light ? 'light' : 'dark',
1638
+ themeIndex: commandCtx.themeIndex,
1639
+ vim: commandCtx.vim,
1640
+ stream: commandCtx.stream,
1641
+ cwd: commandCtx.cwd,
1642
+ home: os.homedir(),
1643
+ sessionId: commandCtx.sessionId,
1644
+ base: client.apiBase,
1645
+ keyMask: maskKey(client.apiKey),
1646
+ online: !!client.apiKey,
1647
+ turns: session.turns,
1648
+ calls: session.calls,
1649
+ startedAt: session.startedAt,
1650
+ // The shared bucket shape `{input, output, cacheRead, cacheWrite}` — the
1651
+ // same object /cost's accounting and the ledger carry, so the panels
1652
+ // cannot render a different turn than the one that was billed. `input` is
1653
+ // the miss half; see recordTurn.
1654
+ tokens: {
1655
+ input: session.inputTokens,
1656
+ output: session.outputTokens,
1657
+ cacheRead: session.cacheReadTokens,
1658
+ cacheWrite: session.cacheWriteTokens,
1659
+ total: session.tokens,
1660
+ },
1661
+ costEur: session.cost,
1662
+ balance: session.balance,
1663
+ plan: session.plan || null,
1664
+ account: session.account || null,
1665
+ permissions: { mode: posture.enabled ? rules.defaultMode : 'allow', confirm: posture.enabled, source: posture.source, rules },
1666
+ // The selectable (pickable) catalog, not the raw payload: alias tiers are
1667
+ // dropped, live ids only (see models.js pickerEntries).
1668
+ // Whichever class is live decides what is pinnable — the pooled ids the
1669
+ // server advertises, or the `provider:model` ids this machine can relay.
1670
+ models: classScopedModels(),
1671
+ commands: visibleCommands(),
1672
+ transcript: transcript.slice(),
1673
+ sessions: [],
1674
+ memory: {},
1675
+ lastRecap: commandCtx.lastRecap,
1676
+ backend: commandCtx.modelClass,
1677
+ url: client.apiBase,
1678
+ };
1679
+ }
1680
+
1681
+ /** Flatten a span line (panels.js/overlays.js output) back to an ANSI row. */
1682
+ function flattenSpans(line) {
1683
+ if (!Array.isArray(line)) return String(line == null ? '' : line);
1684
+ return line.map((sp) => (sp && (sp.s || '') + (sp.t == null ? '' : sp.t)) || '').join('');
1685
+ }
1686
+
1687
+ /**
1688
+ * Push one transcript row. `c.push(row)`/`c.note`/`c.panel` land here; the
1689
+ * linear CLI prints each row once to scrollback (there is no alt-screen).
1690
+ */
1691
+ function pushRow(row) {
1692
+ if (!row || typeof row !== 'object') return;
1693
+ const W = width();
1694
+ switch (row.role) {
1695
+ case 'panel': {
1696
+ const lines = Array.isArray(row.lines) ? row.lines : [];
1697
+ for (const line of lines) emit(flattenSpans(line));
1698
+ return;
1699
+ }
1700
+ case 'note': emit(render.renderNotice(ctx(), 'info', row.text)); return;
1701
+ case 'tip': emit(render.renderNotice(ctx(), 'info', row.text)); return;
1702
+ case 'done': emit(render.renderNotice(ctx(), 'ok', row.text)); return;
1703
+ case 'error': emit(render.renderNotice(ctx(), 'error', row.text)); return;
1704
+ case 'user': emit(render.renderTurn(ctx(), { role: 'user', text: row.text, label: row.label }, W)); return;
1705
+ case 'assistant': emit(render.renderTurn(ctx(), { role: 'assistant', text: row.text }, W)); return;
1706
+ case 'tool': {
1707
+ // A chatflow row carries the preview it built from the run frame
1708
+ // (chatflow.js); a row pushed straight from a command handler has none,
1709
+ // so build one here rather than re-showing the gray `$ {args}` row.
1710
+ if (row.diff === undefined) {
1711
+ row.diff = editPreview(row.name || row.label, row.args, { cwd: process.cwd() });
1712
+ row.diffOpen = defaultOpen(row.diff);
1713
+ }
1714
+ emit(render.renderTurn(ctx(), { role: 'tool', label: row.label || row.name, args: row.args, ok: row.ok, diff: row.diff, diffOpen: !!row.diffOpen }, W));
1715
+ return;
1716
+ }
1717
+ default: emit(render.renderNotice(ctx(), 'info', row.text == null ? '' : String(row.text))); return;
1718
+ }
1719
+ }
1720
+
1721
+ /** A static (non-interactive) print of an overlay's contents. */
1722
+ function openOverlay(o) {
1723
+ if (!o || typeof o !== 'object') return;
1724
+ const W = width();
1725
+ const rows = Math.max(5, (process.stdout && process.stdout.rows) || 24);
1726
+ let lines = null;
1727
+ if (o.type === 'panel') lines = o.lines;
1728
+ else if (o.type === 'palette') lines = overlays.renderPalette(visibleCommands(), { query: o.query || '', sel: o.sel || 0 }, W, rows);
1729
+ else if (o.type === 'model') lines = overlays.renderModelPicker(o.items || [], o.sel || 0, W, rows, o.current != null ? o.current : commandCtx.model, o.cls || commandCtx.modelClass, classLabelOf);
1730
+ else if (o.type === 'effort') lines = overlays.renderEffortPicker(o.sel || 0, W, commandCtx.effort);
1731
+ else if (o.type === 'class') lines = overlays.renderClassPicker(o.items || [], o.sel || 0, W, o.current || commandCtx.modelClass, classLabelOf);
1732
+ else if (o.type === 'provider') lines = overlays.renderProviderPicker(o.items || [], o.sel || 0, W, o.current, o.hint);
1733
+ else if (o.type === 'resume') lines = overlays.renderResumeList(o.items || [], o.sel || 0, W, rows);
1734
+ else if (o.type === 'confirm') lines = render.renderApproval(ctx(), o.info || {}, W).map((s) => [spanRow(s)]);
1735
+ if (!lines) return;
1736
+ for (const line of lines) emit(flattenSpans(line));
1737
+ }
1738
+
1739
+ /** A single-span row for a pre-styled string (renderApproval output). */
1740
+ function spanRow(s) {
1741
+ return { t: s, s: '', w: w(s) };
1742
+ }
1743
+
1744
+ /** Run `fn(signal)` with the spinner up (interactive TTY only). */
1745
+ async function withWorking(fn) {
1746
+ const controller = new AbortController();
1747
+ const live = opts.interactive && out.isTTY ? new LiveRegion(out) : null;
1748
+ let timer = null;
1749
+ if (live) {
1750
+ let tick = 0;
1751
+ const started = Date.now();
1752
+ const paint = () => live.update([render.renderWorking(ctx(), { tick: tick++, verb: VERBS[0], elapsedMs: Date.now() - started })]);
1753
+ paint();
1754
+ timer = setInterval(paint, 90);
1755
+ if (timer.unref) timer.unref();
1756
+ }
1757
+ try {
1758
+ return await fn(controller.signal);
1759
+ } finally {
1760
+ if (timer) clearInterval(timer);
1761
+ if (live) live.clear();
1762
+ }
1763
+ }
1764
+
1765
+ /**
1766
+ * The theme picker. On a real terminal this is the onboarding screen; anywhere
1767
+ * else (`/theme` in a pipe, a test with no TTY) it stays the light/dark toggle
1768
+ * it has always been, so a non-interactive caller never blocks on a key.
1769
+ */
1770
+ async function showThemePicker() {
1771
+ if (options.readline || !process.stdin.isTTY || !process.stdout.isTTY || options.chatflow === false) {
1772
+ commandCtx.light = !commandCtx.light;
1773
+ commandCtx.themeIndex = commandCtx.light ? 2 : 1;
1774
+ emit(render.renderNotice(ctx(), 'ok', `theme: ${commandCtx.light ? 'light' : 'dark'}`));
1775
+ return commandCtx.themeIndex;
1776
+ }
1777
+ return screens.showThemePicker(commandCtx);
1778
+ }
1779
+
1780
+ /** Build the FROZEN command context `c` a handler runs against. */
1781
+ function makeCommandContext() {
1782
+ const c = {
1783
+ ctx: commandCtx,
1784
+ transcript,
1785
+ push: (row) => pushRow(row),
1786
+ note: (text) => pushRow({ role: 'note', text }),
1787
+ panel: (lines) => pushRow({ role: 'panel', lines }),
1788
+ render: () => {},
1789
+ openOverlay: (o) => openOverlay(o),
1790
+ closeOverlay: () => {},
1791
+ // Auto mode's session switch, written by `/automode on|off` (commands.js)
1792
+ // and read by makeHost's isYolo. It lives on the context for the same
1793
+ // reason `switchClass` does: the command must move the fact the status
1794
+ // line, the round-budget allowance and the approval gate all read, or the
1795
+ // command is cosmetic. See the session flag's comment near createApp's
1796
+ // gate wiring for why AEGIS_AUTO_ROUNDS=0 is a starting point and not a
1797
+ // veto.
1798
+ setAutoRounds: (v) => {
1799
+ autoRoundsSession = Boolean(v);
1800
+ },
1801
+ askInput: () => Promise.resolve(null),
1802
+ withWorking: (fn) => withWorking(fn),
1803
+ runPrompt: (text) => runPrompt(text),
1804
+ ask: (text) => ask(text),
1805
+ runTool: (name, args) => runTool(name, args),
1806
+ // The catalog `/model` and alt+p expect. Routed through listModelsFor so
1807
+ // it follows the LIVE class: on the pooled class that is the server's
1808
+ // catalog (loadModels), on byok the `provider:model` ids this machine can
1809
+ // relay. Wired on the app's context so the chatflow's `Object.assign`
1810
+ // based context inherits it too — one definition, both hosts, and the
1811
+ // picker can never offer something the class would reject.
1812
+ loadModels: () => listModelsFor(commandCtx.modelClass),
1813
+ // The provider-key store (`byok:<provider>` rows) /byok-key writes. Read
1814
+ // through a function, not captured, because an injected engine may not
1815
+ // carry one.
1816
+ settings: () => engine.settings || null,
1817
+ // The one spelling of a provider's settings row, shared with the engine
1818
+ // that reads it (`byok:<provider>`) — see engine.js byokNamespace.
1819
+ byokNamespace: (p) => byokNamespace(p),
1820
+ // The class surface: /class switches, /models lists for whichever class
1821
+ // is live (the frozen state carries the current one as c.ctx.modelClass).
1822
+ listModelsFor: (cls) => listModelsFor(cls),
1823
+ // Re-read the byok rows NOW, past the 5-minute cache. `/model-add` writes
1824
+ // the user-model file and then asks for this, because a picker that
1825
+ // answers from a cache older than the file it just wrote would report the
1826
+ // model it was told to add as missing — for five minutes.
1827
+ refreshByokModels: () => loadByokModels({ force: true }),
1828
+ switchClass: (cls) => switchClass(cls),
1829
+ classLabel: (cls) => classLabelOf(cls),
1830
+ classes: () => (typeof engine.listClasses === 'function' ? engine.listClasses() : []),
1831
+ refreshSpend: () => refreshSpend(),
1832
+ state: () => buildState(),
1833
+ setInput: () => {},
1834
+ exit: () => { wantExit = true; },
1835
+ client,
1836
+ TOOLS,
1837
+ saveConfig: (patch) => updateConfig(patch),
1838
+ showThemePicker: () => showThemePicker(),
1839
+ // Credential + cloud-sync surface for the /key, /cloud and /sync commands.
1840
+ // Defined here on the app's context so the chatflow's Object.assign-based
1841
+ // context inherits them too — one definition, both hosts.
1842
+ keyStatus: () => credentials.keyStatus(),
1843
+ setApiKey: (raw, o) => setApiKey(raw, o),
1844
+ forgetApiKey: () => forgetApiKey(),
1845
+ registerAccount: () => registerAccount(),
1846
+ readSecret: (text) => readSecret(text, { stdin: process.stdin, stdout: out }),
1847
+ cloudsync,
1848
+ cloudSyncEnabled: () => cloudSyncEnabled(),
1849
+ cloudSyncState: () => cloudSyncState(),
1850
+ setCloudSync: (on) => setCloudSync(on),
1851
+ adoptLegacyKey: () => adoptLegacyKeyOnce(),
1852
+ };
1853
+ Object.defineProperty(c, 'sessionId', {
1854
+ enumerable: true,
1855
+ get: () => commandCtx.sessionId,
1856
+ set: (v) => { commandCtx.sessionId = v; },
1857
+ });
1858
+ // Drop whatever a transport remembered ABOUT this conversation, as opposed
1859
+ // to what this host keeps in `transcript`. `/clear` empties the transcript,
1860
+ // but the Pro class's memory lives in the `claude` child's own session —
1861
+ // reattaching to it afterwards would answer from turns the user just
1862
+ // erased, which reads as the clear having failed. Keyed by session id, the
1863
+ // same id `sessionKey` travels as, so the two cannot drift.
1864
+ c.clearConversationMemory = () => {
1865
+ if (engine && typeof engine.clearSessionApprovals === 'function') {
1866
+ engine.clearSessionApprovals(commandCtx.sessionId);
1867
+ }
1868
+ };
1869
+ return c;
1870
+ }
1871
+
1872
+ /**
1873
+ * Handle one line of input. Returns false when the session should end.
1874
+ *
1875
+ * `cOverride` lets the chatflow supply the context it owns (its own `push`,
1876
+ * `render`, `openOverlay`, `askInput`, `runPrompt`) instead of the linear
1877
+ * defaults — the handlers are identical either way, which is the point.
1878
+ */
1879
+ async function handleLine(line, cOverride = null) {
1880
+ const parsed = parseLine(line);
1881
+
1882
+ if (parsed.kind === 'empty') return true;
1883
+ if (parsed.kind === 'prompt') {
1884
+ await runPrompt(parsed.text);
1885
+ return true;
1886
+ }
1887
+ if (parsed.kind === 'unknown') {
1888
+ const alt = nearest(parsed.name);
1889
+ emit(
1890
+ render.renderNotice(
1891
+ ctx(),
1892
+ 'error',
1893
+ `unknown command: /${parsed.name}${alt ? ` — did you mean /${alt}?` : ` — try /help`}`
1894
+ )
1895
+ );
1896
+ return true;
1897
+ }
1898
+ if (parsed.kind === 'unavailable') {
1899
+ const c = parsed.command;
1900
+ emit(render.renderNotice(ctx(), 'warn', `/${c.name} is not available in aegiscode — ${c.unavailable}`));
1901
+ if (c.alt) emit(render.renderNotice(ctx(), 'info', `try ${c.alt} instead`));
1902
+ else {
1903
+ const alt = nearest(c.name);
1904
+ if (alt) emit(render.renderNotice(ctx(), 'info', `try /${alt} instead`));
1905
+ }
1906
+ return true;
1907
+ }
1908
+
1909
+ const cmd = parsed.command;
1910
+ const arg = parsed.arg;
1911
+
1912
+ // The generic escape hatch (/tool <name> [json]).
1913
+ if (cmd.generic) {
1914
+ let built;
1915
+ try {
1916
+ built = cmd.build(arg);
1917
+ } catch (e) {
1918
+ emit(render.renderNotice(ctx(), 'error', e.message));
1919
+ return true;
1920
+ }
1921
+ const { tool, args } = built;
1922
+ if (!tool) {
1923
+ emit(render.renderNotice(ctx(), 'error', '/tool needs a tool name — see /help'));
1924
+ return true;
1925
+ }
1926
+ try {
1927
+ await runTool(tool, args);
1928
+ } catch (e) {
1929
+ emit(render.renderNotice(ctx(), 'error', e.message));
1930
+ }
1931
+ return true;
1932
+ }
1933
+
1934
+ // Handler-backed (the reference aegiscode-dev contract).
1935
+ if (typeof cmd.handler === 'function') {
1936
+ const args = parseArgs(cmd, arg);
1937
+ const c = cOverride || makeCommandContext();
1938
+ try {
1939
+ const keep = await cmd.handler(c, args);
1940
+ return keep === false ? false : true;
1941
+ } catch (e) {
1942
+ emit(render.renderNotice(ctx(), 'error', e && e.message ? e.message : String(e)));
1943
+ return true;
1944
+ }
1945
+ }
1946
+
1947
+ // Tool-backed command.
1948
+ try {
1949
+ let args = cmd.build(arg);
1950
+ if (cmd.secret) {
1951
+ // A bare "provider key for openai:" tells the user nothing about which
1952
+ // key to paste or where to get it, which is exactly the step people get
1953
+ // wrong. When a command can describe its own secret it does, and the
1954
+ // description is best-effort: a catalog fetch that fails must still
1955
+ // leave a working prompt rather than aborting the command.
1956
+ const spec = await describeSecret(cmd, args);
1957
+ if (spec && spec.note) emit(render.renderNotice(ctx(), 'info', spec.note));
1958
+ // An explicit `prompt: null` is a refusal, not a missing description.
1959
+ // Reading it as "no description" and falling through to the generic
1960
+ // prompt is how `/byok-set <typo>` printed "unknown provider … Nothing
1961
+ // was sent" and then asked for the key anyway and sent it: the command
1962
+ // had decided this must not be stored, and the dispatcher overrode it.
1963
+ if (spec && spec.prompt === null) return true;
1964
+ // The command may have resolved the typed word to a canonical id
1965
+ // (`together-ai` → `together`). Send that. Otherwise the prompt names
1966
+ // the real provider while the request carries the alias the server does
1967
+ // not know, and the save fails after the user has already pasted a key.
1968
+ if (spec && spec.provider) args = { ...args, provider: spec.provider };
1969
+ const key = await askSecret((spec && spec.prompt) || `provider key for ${args.provider}: `);
1970
+ if (!key) {
1971
+ emit(render.renderNotice(ctx(), 'warn', 'empty key — nothing sent'));
1972
+ return true;
1973
+ }
1974
+ args = { ...args, api_key: key };
1975
+ }
1976
+ if (cmd.tool === 'aegis_ask') return await runPrompt(args.prompt);
1977
+ await runTool(cmd.tool, args);
1978
+ // `/memory` is where a user actually looks at what is stored, so the
1979
+ // quota state belongs here as well as in /cloud: the ceiling is the one
1980
+ // fact about this feature that changes what the account can do, and it is
1981
+ // invisible from the entries themselves.
1982
+ if (cmd.tool === 'aegis_memory_list' || cmd.tool === 'aegis_memory_search') memoryQuotaNote();
1983
+ } catch (e) {
1984
+ emit(render.renderNotice(ctx(), 'error', e.message));
1985
+ }
1986
+ return true;
1987
+ }
1988
+
1989
+ /**
1990
+ * One line of quota state for the memory read commands. Quiet when the server
1991
+ * has not reported a ceiling yet (nothing useful to say), a statement when it
1992
+ * has, and — when the account is at it — the two halves spelled out: reads
1993
+ * keep working, new writes do not.
1994
+ */
1995
+ function memoryQuotaNote() {
1996
+ let st;
1997
+ try {
1998
+ st = cloudsync.status();
1999
+ } catch {
2000
+ return;
2001
+ }
2002
+ const q = st.quota;
2003
+ if (!q) return;
2004
+ const used = fmtTokens(q.used || 0);
2005
+ const limit = fmtTokens(q.limit || 0);
2006
+ if (st.overQuota) {
2007
+ emit(
2008
+ render.renderNotice(
2009
+ ctx(),
2010
+ 'warn',
2011
+ `cloud memory: ${used} of ${limit} synced tokens — at the plan's ceiling. Everything stored stays readable; new writes are paused until there is room. /cloud memory for the full state.`
2012
+ )
2013
+ );
2014
+ return;
2015
+ }
2016
+ emit(render.renderNotice(ctx(), 'info', `cloud memory: ${used} of ${limit} synced tokens — /cloud memory for the full state`));
2017
+ }
2018
+
2019
+ /**
2020
+ * Ask the command how to describe the secret it is about to collect.
2021
+ *
2022
+ * Returns `{ note, prompt }` or null. The command opts in by defining
2023
+ * `secretDescribe(args, client)`, which is awaited and therefore free to
2024
+ * consult the server. A throw here is swallowed on purpose: guidance is an
2025
+ * improvement to a prompt, and a user who typed `/byok-set openai` on a
2026
+ * flaky connection should still get the prompt.
2027
+ */
2028
+ async function describeSecret(cmd, args) {
2029
+ if (typeof cmd.secretDescribe !== 'function') return null;
2030
+ try {
2031
+ const spec = await cmd.secretDescribe(args, client);
2032
+ return spec && typeof spec === 'object' ? spec : null;
2033
+ } catch {
2034
+ return null;
2035
+ }
2036
+ }
2037
+
2038
+ /**
2039
+ * Ask for a secret on this session's streams.
2040
+ *
2041
+ * The prompt loop itself lives in secret.js, shared with `aegiscode login` in
2042
+ * the bin — one implementation, so the terminal host and the non-interactive
2043
+ * entry point cannot differ in whether a key is echoed or masked. Only the
2044
+ * prompt's colouring is the session's business.
2045
+ */
2046
+ function askSecret(promptText) {
2047
+ const t = themeOf(ctx());
2048
+ return readSecret(t.gray + promptText + RESET, { stdin: process.stdin, stdout: out });
2049
+ }
2050
+
2051
+ // --- entry points ---------------------------------------------------------
2052
+
2053
+ /**
2054
+ * Give the local lane back its hardware, on the way out.
2055
+ *
2056
+ * The desktop has done this from its quit path since the class shipped
2057
+ * (`main.js` before-quit -> `engine.unloadLocalModels` -> local.js
2058
+ * `unloadAll`): "closing the app closes the model". The CLI had no equivalent
2059
+ * at all, so exiting a session after a `local` turn left the weights resident
2060
+ * for the remainder of the pin the turn itself set — `DEFAULT_WARM_SECS` is
2061
+ * 1800 (local.js), i.e. up to thirty minutes of a loaded model on hardware
2062
+ * nobody was using anymore, which is the one cost this lane exists to not
2063
+ * have.
2064
+ *
2065
+ * Best-effort by construction: `unloadAll` never throws and each request is
2066
+ * bounded by `UNLOAD_TIMEOUT_MS` (4s) inside the transport, so a daemon that
2067
+ * is slow, wedged or already gone cannot turn a clean exit into a hang or a
2068
+ * crash. Called from every exit path of every entry point below — INCLUDING
2069
+ * `-p`, whose whole life may be one local turn.
2070
+ *
2071
+ * Deliberately not a `process.on('exit')` handler: that callback cannot
2072
+ * await, so the request would be issued into a process that is already
2073
+ * tearing the socket down. Awaiting at the end of the session is what makes
2074
+ * the eviction actually reach the daemon.
2075
+ */
2076
+ async function releaseLocalModel() {
2077
+ if (!engine || typeof engine.unloadLocalModels !== 'function') return;
2078
+ try {
2079
+ await engine.unloadLocalModels();
2080
+ } catch {
2081
+ /* the model's own keep-alive lapses; never fail an exit over cleanup */
2082
+ }
2083
+ }
2084
+
2085
+ /**
2086
+ * One-shot run: the turn itself (`runOnceTurn`), then the local lane handed
2087
+ * back even if that turn threw. A `-p` run can BE a whole local session, so
2088
+ * it needs the same closing the interactive loop gets — see
2089
+ * `releaseLocalModel`.
2090
+ */
2091
+ async function runOnce(prompt, opts = {}) {
2092
+ try {
2093
+ return await runOnceTurn(prompt, opts);
2094
+ } finally {
2095
+ await releaseLocalModel();
2096
+ }
2097
+ }
2098
+
2099
+ /** Non-interactive: one prompt, plain output, exit code. */
2100
+ async function runOnceTurn(prompt, { json = false } = {}) {
2101
+ // The one-shot path used to skip this entirely, so `-p` always ran
2102
+ // DEFAULT_CLASS ('aegis', the pooled route) no matter what the user had
2103
+ // pinned: `/class byok` (or a saved byok/byok-model pin) applied to the
2104
+ // interactive loop only. That made the documented headless entry point
2105
+ // unable to use BYOK at all — it billed the pool instead, or, on a box
2106
+ // whose pooled backend was down, failed with a provider timeout while the
2107
+ // user's own key sat unused. Same restore the REPL does, before the first
2108
+ // turn and therefore before `ask()` resolves a route.
2109
+ restorePrefs();
2110
+ adoptLegacyKeyOnce();
2111
+ // Same self-service a fresh `aegiscode -p ...` deserves as a fresh
2112
+ // interactive session (runInteractive) or a fresh `/ask` (runPrompt):
2113
+ // this path used to skip straight to the "no key" refusal below, so
2114
+ // every headless/scripted first run (CI, docker, a README one-liner)
2115
+ // left an installed-but-never-registered machine with no account row
2116
+ // and no welcome trial, instead of the free device key auto-provision
2117
+ // was built to hand it.
2118
+ //
2119
+ // Not the shared `ensureApiKey()` helper: it reports through `emit()`,
2120
+ // which writes to `out` — the same stream `--json` puts its one machine-
2121
+ // readable line on. A notice ahead of that line would break every script
2122
+ // piping `-p ... --json` into a JSON parser, so this path's own notice
2123
+ // always goes to `err` regardless of `json`.
2124
+ if (!client.apiKey && !provisionAttempted) {
2125
+ provisionAttempted = true;
2126
+ const result = await autoProvisionApiKey(client, credentials, { app: 'cli' });
2127
+ if (result.key) {
2128
+ err.write(
2129
+ `aegiscode: auto-provisioned a free account` +
2130
+ (result.ok ? ` (saved to ${credentials.credentialsPath()})` : ' (could not save it — reconfigure with /key)') +
2131
+ trialNote(result) +
2132
+ `. Fund it at ${client.promptUrl('topup', 'device_autoprovision')} or run /byok to use your own key.\n`
2133
+ );
2134
+ }
2135
+ }
2136
+ if (!client.apiKey) {
2137
+ err.write(`aegiscode: no AEGIS account key. ${credentials.HOW_TO_SET}, or set $${credentials.KEY_ENV}.\n`);
2138
+ return 2;
2139
+ }
2140
+ // Snapshot the account's existing ledger BEFORE the billed call. Without
2141
+ // this the refresh after the turn would treat every historical row as new,
2142
+ // and the reported charge would be whatever the account spent last rather
2143
+ // than what this call cost.
2144
+ await refreshSpend();
2145
+ // Under `--json`, stdout carries ONE document and nothing else. A turn that
2146
+ // uses tools renders a row per call (`ask()`'s `tool` presenter below), and
2147
+ // those rows went to `out` — so the document was preceded by ANSI-coloured
2148
+ // progress text and no parser could read it. Measured: a tool-using turn
2149
+ // emitted 1238 bytes of `Bash ⎿ ✔` rows before the JSON, which is why the
2150
+ // harness sweep recorded `tokens_in: 0` for tasks the CLI had in fact
2151
+ // SOLVED. The rows are still shown, just on stderr, where a human sees them
2152
+ // and a parser does not.
2153
+ // Every tool call this turn really made, by name. `--json` is the only
2154
+ // machine-readable surface the CLI has, and the harness measures "how much
2155
+ // work did the loop do" from it. A tool-using turn that reports no tools is
2156
+ // indistinguishable from a turn that answered from memory — the benchmark
2157
+ // scored three tasks SOLVED with `tool_calls: 0` while the workspace showed
2158
+ // genuine edits, because nothing published the count.
2159
+ const toolsUsed = [];
2160
+ const toolLog = [];
2161
+ const jsonPresenter = json
2162
+ ? {
2163
+ tool: (tool) => {
2164
+ // One entry per CALL, not per frame. The engine reports every tool
2165
+ // twice — `phase: 'run'` before it executes and `phase: 'done'`
2166
+ // with the outcome — and both arrive here. Pushing on both doubled
2167
+ // `tools` (a 6-call turn published 12-14 names), and the benchmark
2168
+ // adapters count array elements as calls, so AEGIS's tool count was
2169
+ // inflated by exactly 2x while its `tokens_per_solved` was flattered
2170
+ // by the same factor. The done frame now only settles the entry it
2171
+ // belongs to.
2172
+ const phase = tool && tool.phase;
2173
+ if (phase === 'done') {
2174
+ const match = (tool.id && toolLog.find((c) => c.id === tool.id && c.settled !== true))
2175
+ || (tool.id ? null : toolLog[toolLog.length - 1]);
2176
+ if (match) {
2177
+ match.settled = true;
2178
+ match.ok = tool.ok !== false;
2179
+ } else {
2180
+ // A `done` frame with no unsettled entry to settle is a call we
2181
+ // are learning about for the first time — the engine batched or
2182
+ // outlived the matching `run` frame (seen on the sweep: one
2183
+ // `run` then every later call arriving already `done`). Falling
2184
+ // back to "settle the last entry" silently discarded those
2185
+ // calls: a task that ran 7 tools published `tool_calls: 1`
2186
+ // while its own stderr rendered all 7. Record it, already
2187
+ // settled, so counting stays at one per call.
2188
+ if (tool && tool.name) toolsUsed.push(tool.name);
2189
+ toolLog.push({
2190
+ name: (tool && tool.name) || null,
2191
+ id: (tool && tool.id) || null,
2192
+ args: briefArgs(tool && tool.args),
2193
+ settled: true,
2194
+ ok: tool.ok !== false,
2195
+ });
2196
+ }
2197
+ } else {
2198
+ if (tool && tool.name) toolsUsed.push(tool.name);
2199
+ toolLog.push({
2200
+ name: (tool && tool.name) || null,
2201
+ id: (tool && tool.id) || null,
2202
+ // The same brief rendering a reader gets on stderr, so an
2203
+ // archived run can say WHAT the calls were rather than only how
2204
+ // many. `--json` used to publish the count and no evidence:
2205
+ // a 14-entry `tools` array was all a benchmark row could see.
2206
+ args: briefArgs(tool && tool.args),
2207
+ settled: false,
2208
+ ok: null,
2209
+ });
2210
+ }
2211
+ const diff = tool && tool.preview !== undefined ? tool.preview : null;
2212
+ const lines = render.renderTurn(
2213
+ ctx(),
2214
+ { role: 'tool', label: tool.name, args: tool.args, ok: tool.ok, diff, diffOpen: false },
2215
+ width()
2216
+ );
2217
+ for (const l of Array.isArray(lines) ? lines : [lines]) err.write(l + '\n');
2218
+ return undefined;
2219
+ },
2220
+ }
2221
+ : null;
2222
+ const res = await ask(prompt, jsonPresenter ? { presenter: jsonPresenter } : {});
2223
+ await refreshSpend();
2224
+ const tokens = usageTokens(res.usage);
2225
+ // A refusal that arrived as content: report it as a failure, not an answer.
2226
+ const refusal = providerRefusal(res.text, res.usage);
2227
+ if (json) {
2228
+ out.write(
2229
+ JSON.stringify(
2230
+ {
2231
+ text: res.text,
2232
+ model: res.model,
2233
+ // The route this turn actually took, so a run can PROVE its class
2234
+ // instead of asserting it in prose. The benchmark spent two sweeps
2235
+ // comparing a pooled-relay CLI turn against a BYOK-direct desktop
2236
+ // turn while both rows claimed `deepseek-flash`; the 3.5× cost gap
2237
+ // was the transport, and nothing in the document said so. `--json`
2238
+ // is the only machine-readable surface this CLI has.
2239
+ class: commandCtx.modelClass,
2240
+ // The engine stamps `calls` onto this accumulator (one per provider
2241
+ // dispatch), so it is the turn's real round-trip count. Republished
2242
+ // under the name every benchmark adapter already looks for:
2243
+ // `harness-bench.mjs` read `e.rounds` and, finding nothing, fell
2244
+ // back to `1`, so every archived AEGIS row claimed a single round
2245
+ // for turns that made dozens.
2246
+ rounds: (res.usage && Number(res.usage.calls)) || null,
2247
+ usage: res.usage,
2248
+ // Hidden deliberation, in CHARS, exactly as it streamed. `ask()`
2249
+ // has accumulated this on `chunk.reasoning` since the beginning and
2250
+ // returned it as `reasoningChars`, but `--json` never republished
2251
+ // it — so a benchmark row could see `output_tokens: 1,293` and had
2252
+ // no way to say how much of that was chain-of-thought. DeepSeek on
2253
+ // this transport reports no `reasoning_tokens` field at all, which
2254
+ // made every attempt at the split record null. Chars are published
2255
+ // rather than a derived token count because the chars are the
2256
+ // measurement; the ratio is an assumption and belongs to the reader.
2257
+ reasoning_chars: typeof res.reasoningChars === 'number' ? res.reasoningChars : null,
2258
+ tokens,
2259
+ ms: res.ms,
2260
+ interrupted: res.interrupted,
2261
+ // Present only when the turn actually called tools, so a reader can
2262
+ // tell "answered from memory" from "did work" without inferring it
2263
+ // from a token count.
2264
+ ...(toolsUsed.length ? { tools: toolsUsed } : {}),
2265
+ // The evidence beside the count: name + a one-line arg summary per
2266
+ // call, with the outcome written back from the matching done frame.
2267
+ // `tools` above is kept unchanged because five archived runs and a
2268
+ // test read it, and it is the field that says HOW MANY rounds
2269
+ // touched a tool; this one says which.
2270
+ ...(toolLog.length ? { tool_log: toolLog } : {}),
2271
+ // Present only when the reply was a provider refusal. A caller that
2272
+ // gates on `error` can now tell a dead turn from a working one;
2273
+ // before this field existed both were `{text, tokens: 0}` with
2274
+ // exit 0, and the harness scored a broken run as a scored zero.
2275
+ ...(refusal ? { error: refusal } : {}),
2276
+ balance_eur: session.balance,
2277
+ },
2278
+ null,
2279
+ 2
2280
+ ) + '\n'
2281
+ );
2282
+ } else {
2283
+ out.write(res.text + '\n');
2284
+ if (refusal) err.write(`aegiscode: the provider refused this turn — ${refusal}\n`);
2285
+ if (tokens != null) {
2286
+ const t = themeOf(ctx());
2287
+ out.write(
2288
+ t.dim + GLYPH.hook + ' ' + t.blue + (res.model || 'aegis') + RESET +
2289
+ t.dim + ' ' + GLYPH.bullet + ' ' + RESET +
2290
+ t.white + `${fmtTokens(tokens)} tokens` + RESET + '\n'
2291
+ );
2292
+ }
2293
+ }
2294
+ return res.interrupted ? 130 : (refusal ? 1 : 0);
2295
+ }
2296
+
2297
+ /** Fold one completed turn's usage into the session tallies.
2298
+ * @returns {number|null} the total token count for the turn, when known. */
2299
+ /**
2300
+ * Name the conversation, on this host's own turn path (naming.js).
2301
+ *
2302
+ * The model round goes through `ask()`, so it uses the same client, the same
2303
+ * key and the same model the session is already talking to — a naming round
2304
+ * cannot become a second, differently-authenticated caller, and it costs one
2305
+ * short completion. `naming.js` owns every rule about what a name is: a
2306
+ * greeting is answered locally without a call at all, an echo of the prompt
2307
+ * is not a name, and the local derivation is the floor when nothing answers.
2308
+ *
2309
+ * The name is also written onto the session's history records, so `/resume`
2310
+ * lists the conversation by what it is about instead of by its raw first
2311
+ * message. Best-effort throughout: a failure here costs a label.
2312
+ */
2313
+ async function nameConversation(prompt, { signal = null } = {}) {
2314
+ const title = await naming.nameConversation(prompt, {
2315
+ signal,
2316
+ callModel: (text, o) =>
2317
+ ask(text, {
2318
+ system: (o && o.system) || naming.TITLE_SYSTEM,
2319
+ maxTokens: 64,
2320
+ signal: (o && o.signal) || signal,
2321
+ }).then((r) => (r && r.text) || null),
2322
+ });
2323
+ const clean = String(title || '').trim();
2324
+ if (clean) setSessionTitle(commandCtx.sessionId, clean);
2325
+ return clean;
2326
+ }
2327
+
2328
+ function recordTurn(res) {
2329
+ session.turns++;
2330
+ session.calls += Number((res && res.calls) || 1) || 1;
2331
+ const usage = res && res.usage;
2332
+ const tokens = usageTokens(usage);
2333
+ if (tokens != null) {
2334
+ session.tokens += tokens;
2335
+ // The session tally is folded through the SHARED normaliser, not the raw
2336
+ // wire spellings. Reading `input_tokens ?? prompt_tokens` here is what
2337
+ // made the CLI's live tally disagree with its own ledger about the same
2338
+ // turn: the providers do not merely spell these fields differently, they
2339
+ // MEASURE them differently. Anthropic's `input_tokens` EXCLUDES
2340
+ // `cache_read_input_tokens`; OpenAI/DeepSeek's `prompt_tokens` INCLUDES
2341
+ // the hit. So `input + cacheRead` is right for the first and a
2342
+ // double-count of the prompt for the second. `usageBuckets` resolves
2343
+ // `input` to the MISS half in both cases (the same normalisation the
2344
+ // ledger row, the desktop roll and costBreakdown already use), which is
2345
+ // the only reading under which the /context prompt row means one thing on
2346
+ // every provider. Without this the CLI accumulated no cache buckets at
2347
+ // all, so /tokens drew two bars it could never fill.
2348
+ const b = usageBuckets(usage);
2349
+ session.inputTokens += b.input;
2350
+ session.outputTokens += b.output;
2351
+ session.cacheReadTokens += b.cacheRead;
2352
+ session.cacheWriteTokens += b.cacheWrite;
2353
+ }
2354
+ return tokens;
2355
+ }
2356
+
2357
+ /**
2358
+ * Persist one finished exchange: the history row and a transcript checkpoint.
2359
+ *
2360
+ * `appendHistory` and `snapshotCheckpoint` were both dead code — nothing ever
2361
+ * called them, so `history.jsonl` was never created. Every consumer of it
2362
+ * degraded silently rather than loudly: `/resume` could never find a stored
2363
+ * session, `/cost` summed zero rows, `/clear`'s prune was a no-op, and
2364
+ * `/rewind` always answered "No checkpoints yet". The session loop is the only
2365
+ * place that sees the prompt *and* its reply, so it is the place that writes.
2366
+ *
2367
+ * Best-effort by construction: the two writers swallow their own failures, and
2368
+ * accounting must never be able to break a turn.
2369
+ */
2370
+ function persistTurn(prompt, res, status = 'done', costEur = null) {
2371
+ try {
2372
+ const usage = res && res.usage;
2373
+ // What the POOL charged, straight from the ledger — margin and
2374
+ // prompt-cache discount already applied. Stored so /cost can report the
2375
+ // real bill instead of recomputing from provider rates it cannot see.
2376
+ // (The history field is historically named `costUsd`; the value here is
2377
+ // EUR, which is what every surface in this client displays.)
2378
+ const settled = typeof costEur === 'number' && Number.isFinite(costEur) ? costEur : null;
2379
+ // What this turn ran on. Two sources, one answer: the provider reports
2380
+ // the model it served (`res.model`), and a turn the wire did not label
2381
+ // falls back to the id the request was sent with (`commandCtx.model`) —
2382
+ // the same precedence the per-turn readout uses at the printTurn above, so
2383
+ // the ledger and the line the user just read cannot name different models.
2384
+ // Neither is invented: a turn on the server default writes no `model` at
2385
+ // all, which the record reads as "the log did not say".
2386
+ const turnModel = String((res && res.model) || commandCtx.model || '').trim();
2387
+ appendHistory({
2388
+ sessionId: commandCtx.sessionId,
2389
+ prompt,
2390
+ reply: (res && res.text) || '',
2391
+ status,
2392
+ model: turnModel || undefined,
2393
+ provider: turnModel ? providerForModel({ id: turnModel, cls: commandCtx.modelClass }) || undefined : undefined,
2394
+ usage: usage
2395
+ ? {
2396
+ // Not re-derived here. `usageBuckets` is the one module both
2397
+ // hosts resolve (deps.js), so the terminal and the GUI cannot
2398
+ // disagree about what a turn consumed — including whether a
2399
+ // provider's cached count sits INSIDE its prompt count
2400
+ // (OpenAI, DeepSeek) or BESIDE it (Anthropic). Reading only the
2401
+ // Anthropic spelling recorded cacheRead: 0 for every DeepSeek
2402
+ // turn, which priced the whole prompt at the miss rate.
2403
+ ...usageBuckets(usage),
2404
+ ...(settled != null ? { costUsd: settled } : {}),
2405
+ }
2406
+ : settled != null
2407
+ ? { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, costUsd: settled }
2408
+ : null,
2409
+ });
2410
+ snapshotCheckpoint(commandCtx.sessionId, transcript);
2411
+ } catch {
2412
+ /* persistence is best-effort */
2413
+ }
2414
+ // Auto-sync hook: one place, reached by both the linear REPL and the
2415
+ // chatflow's session loop. On by default — a push is billed against the
2416
+ // plan's synced-token ceiling (aegis1 charges the *growth* of a session),
2417
+ // so it is a real gate rather than an unconditional write, but the default
2418
+ // is on because a session that dies at its tool-round horizon is only
2419
+ // recoverable if the transcript exists somewhere the next session can read
2420
+ // it. `/cloud memory off` is the opt-out.
2421
+ if (cloudSyncEnabled()) autoSync();
2422
+ }
2423
+
2424
+ /**
2425
+ * Push after a turn, in the background.
2426
+ *
2427
+ * Deliberately not awaited and deliberately quiet on success: this runs after
2428
+ * every turn, and a line per turn would be noise. Failures are reported once
2429
+ * per session per session-cycle — a quota refusal that repeats forever is a
2430
+ * wall of text, not information — and never thrown, because the user's turn
2431
+ * already succeeded by the time this runs.
2432
+ *
2433
+ * The quota refusal gets its own sentence, and it is the whole point of the
2434
+ * default flip being safe: past the plan's ceiling the account does NOT lose
2435
+ * anything it already stored (reads keep working — aegis1 meters writes
2436
+ * only), and the failure is not "sync failed", it is "there is no room left
2437
+ * for new writes". Saying which half stopped is what keeps a silent stop from
2438
+ * looking like a broken feature.
2439
+ */
2440
+ let autoSyncNotes = new Set();
2441
+ function autoSync() {
2442
+ if (!client.apiKey) return;
2443
+ Promise.resolve()
2444
+ .then(() => cloudsync.push(client))
2445
+ .then((res) => {
2446
+ if (res && res.failed && res.failed.length) {
2447
+ const f = res.failed[0];
2448
+ if (autoSyncNotes.has(f.kind)) return;
2449
+ autoSyncNotes.add(f.kind);
2450
+ if (f.kind === 'quota') {
2451
+ emit(
2452
+ render.renderNotice(
2453
+ ctx(),
2454
+ 'warn',
2455
+ `cloud memory: the plan's synced-token ceiling is reached — earlier sessions stay readable, only NEW writes pause. /cloud memory shows the quota; /cloud memory off stops trying.`
2456
+ )
2457
+ );
2458
+ return;
2459
+ }
2460
+ const hint = f.hint ? ` — ${f.hint}` : '';
2461
+ emit(render.renderNotice(ctx(), 'error', `cloud sync: ${f.message}${hint}`));
2462
+ }
2463
+ })
2464
+ .catch(() => {
2465
+ /* offline is not worth interrupting a session over */
2466
+ });
2467
+ }
2468
+
2469
+ /**
2470
+ * First-run notice for the write half, printed once, right after onboarding.
2471
+ *
2472
+ * The default flip is invisible otherwise: the read half was already on for
2473
+ * everyone, so nothing about the first session looks different — the thing
2474
+ * that changed is that the transcript is now being *stored*, and that costs
2475
+ * quota on a free plan. One line at the moment the account is set up is the
2476
+ * difference between a default and a surprise.
2477
+ */
2478
+ function memoryFirstRunNotice() {
2479
+ const st = cloudSyncState();
2480
+ if (!st.enabled) {
2481
+ emit(
2482
+ render.renderNotice(
2483
+ ctx(),
2484
+ 'info',
2485
+ 'cross-session memory: off (you turned it off) — /cloud memory on stores sessions so an interrupted turn can be picked up later'
2486
+ )
2487
+ );
2488
+ return;
2489
+ }
2490
+ const quota = cloudsync.status().quota;
2491
+ const usage = quota && quota.limit ? ` (used ${fmtTokens(quota.used || 0)} of ${fmtTokens(quota.limit)} tokens)` : '';
2492
+ emit(
2493
+ render.renderNotice(
2494
+ ctx(),
2495
+ 'info',
2496
+ `cross-session memory: on${usage} — sessions are stored to your account so a turn that is interrupted can be resumed. /cloud memory shows the quota; /cloud memory off stops it. Past the ceiling, saved memory stays readable and only new writes pause.`
2497
+ )
2498
+ );
2499
+ }
2500
+
2501
+ /** One line of session accounting, for ctrl+t and the meta row. */ function tokenSummary() {
2502
+ // Output only, the same rule as the meta row this lands in (see format.js's
2503
+ // `fmtUsageSplit`): the input half is the prompt restated and the one figure
2504
+ // a reader cannot act on. A session that recorded no output figure at all
2505
+ // falls back to its total, because stating what was measured beats stating
2506
+ // nothing — and `0 tokens` is refused for the reason `fmtRoll` refuses
2507
+ // `0 tokens`: it states a figure the provider never reported. The label is
2508
+ // `tokens`, the word `fmtUsageSplit` puts on the same figure in the meta row
2509
+ // this shares a slot with: `in`/`out` is a status-line shorthand of this
2510
+ // CLI's own invention, and a reader who has to be told it reads `out` as
2511
+ // something dropped.
2512
+ const produced = session.outputTokens > 0
2513
+ ? `${fmtTokens(session.outputTokens)} tokens`
2514
+ : `${fmtTokens(session.tokens)} tokens`;
2515
+ // Tokens and calls always; money only on a tier AEGIS PROVES a fee is owed
2516
+ // to. Same rule as the meta row and the desktop's topbar roll
2517
+ // (`feeBillable`) — on Unlimited or a welcome trial there is no per-turn
2518
+ // charge and no bank draw, so a `€0.0031` and a `balance` figure here would
2519
+ // be two prices for a session that has none.
2520
+ const parts = [produced, `${session.calls} call${session.calls === 1 ? '' : 's'}`];
2521
+ if (feeBillable()) {
2522
+ parts.push(fmtEur(session.cost));
2523
+ if (session.balance != null) parts.push(`balance ${fmtEur(session.balance)}`);
2524
+ }
2525
+ return parts.join(' · ');
2526
+ }
2527
+
2528
+ /** Load a stored session back into the live transcript. */
2529
+ async function resumeSession(item) {
2530
+ if (!item || !item.id) return;
2531
+ const rows = readSessionTranscript(item.id);
2532
+ if (!rows.length) {
2533
+ emit(render.renderNotice(ctx(), 'warn', `no stored turns for ${item.id}`));
2534
+ return;
2535
+ }
2536
+ // Replace, rather than append: "resume" means continue THIS conversation,
2537
+ // and appending would put two sessions' turns in one context window.
2538
+ transcript.length = 0;
2539
+ for (const r of rows) transcript.push(r);
2540
+ commandCtx.sessionId = item.id;
2541
+ emit(render.renderNotice(ctx(), 'ok', `resumed ${item.id} — ${rows.length} turn(s)`));
2542
+ }
2543
+
2544
+ /**
2545
+ * The host the chatflow drives. Everything the loop needs from the app, with
2546
+ * no layering of its own — the loop owns the frame and the keys, this owns
2547
+ * the transport, the tools, the command table and the tallies.
2548
+ */
2549
+ function makeHost() {
2550
+ return {
2551
+ ctx: commandCtx,
2552
+ version: VERSION,
2553
+ transcript,
2554
+ session,
2555
+ client,
2556
+ TOOLS,
2557
+ ask: (prompt, o) => ask(prompt, o),
2558
+ makeCommandContext: () => makeCommandContext(),
2559
+ // The two stores that are NOT `~/.aegiscode/.env`, which the picker's key
2560
+ // queue has to consult before it may ask for a key that is already saved
2561
+ // somewhere both hosts read:
2562
+ // - `accountConfigured` — the AEGIS account key in credentials.json,
2563
+ // written by /key and by `aegiscode login`.
2564
+ // - `hasProviderKey(p)` — a `byok:<provider>` row, the store /byok-key
2565
+ // and the desktop's Provider settings share (engine.js byokNamespace).
2566
+ // Without these two the picker would re-prompt for a key the machine
2567
+ // demonstrably holds, which is how the same key got saved twice.
2568
+ accountConfigured: () => !!(credentials.keyStatus() || {}).configured,
2569
+ // `get()` is the MASKED read — it returns {provider, baseURL, configured,
2570
+ // keyMask} and never carries a `.key` field. Reading `row.key` here made
2571
+ // this predicate permanently false, so the picker re-prompted for a key
2572
+ // the machine demonstrably held: the exact bug the comment above says it
2573
+ // exists to prevent. `rawKey()` is the reader that returns the plaintext;
2574
+ // `configured` is the fallback for a store that offers only `get()`.
2575
+ hasProviderKey: (provider) => {
2576
+ const store = engine.settings;
2577
+ if (!store || !provider) return false;
2578
+ const row = byokNamespace(provider);
2579
+ if (typeof store.rawKey === 'function') {
2580
+ return !!String(store.rawKey(row) || '').trim();
2581
+ }
2582
+ if (typeof store.get !== 'function') return false;
2583
+ return !!((store.get(row) || {}).configured);
2584
+ },
2585
+ loadModels: (o) => loadModels(o),
2586
+ buildState: () => buildState(),
2587
+ dispatchLine: (line, c) => handleLine(line, c),
2588
+ refreshSpend: () => refreshSpend(),
2589
+ updateConfig: (patch) => updateConfig(patch),
2590
+ showThemePicker: () => showThemePicker(),
2591
+ // `costEur` MUST be forwarded. chatflow's session loop passes the settled
2592
+ // charge as its fourth argument, and this binding used to accept only
2593
+ // three — so the argument was dropped, persistTurn fell back to
2594
+ // costEur = null, and every interactive turn was written to
2595
+ // history.jsonl with no charge attached. /cost then recomputed each of
2596
+ // them from the local rate table (no pool margin, no prompt-cache
2597
+ // discount) and reported a number the customer never paid. The parameter
2598
+ // is the whole reason the ledger is consulted before persisting.
2599
+ persistTurn: (prompt, res, status, costEur) => persistTurn(prompt, res, status, costEur),
2600
+ nameConversation: (prompt, o) => nameConversation(prompt, o),
2601
+ visibleCommands: () => visibleCommands(),
2602
+ tokensFor: (usage) => usageTokens(usage),
2603
+ recordTurn: (res) => recordTurn(res),
2604
+ tokenSummary: () => tokenSummary(),
2605
+ resumeSession: (item) => resumeSession(item),
2606
+ requestExit: () => {
2607
+ wantExit = true;
2608
+ },
2609
+ wantsExit: () => wantExit,
2610
+ keyNotice: () => (client.apiKey ? '' : keyFailure),
2611
+ isYolo: () => {
2612
+ // Both halves, in the order the desktop host reads them
2613
+ // (main.js autoRoundsOn): "this session runs auto mode" AND "the
2614
+ // stored posture says don't ask". The first is the session flag above
2615
+ // — `AEGIS_AUTO_ROUNDS=0` starts manual, and `/automode on` (or the
2616
+ // `→` chord, which dispatches exactly that) turns it back on.
2617
+ if (!autoRoundsSession) return false;
2618
+ try {
2619
+ // The posture, not the rule file: since ON8 the window's switch is the
2620
+ // same fact, so a switch turned off there lights this chip too.
2621
+ return confirmPosture().enabled === false;
2622
+ } catch {
2623
+ return false;
2624
+ }
2625
+ },
2626
+ // `/automode on|off` moves the session flag the predicate above reads, so
2627
+ // the command and the chip can never disagree — and an env opt-out is
2628
+ // escapable at the prompt instead of for the life of the process.
2629
+ setAutoRounds: (v) => {
2630
+ autoRoundsSession = Boolean(v);
2631
+ },
2632
+ };
2633
+ }
2634
+
2635
+ /** The plain (non-alt-screen) REPL: readline, one turn written to scrollback. */
2636
+ async function runLinearRepl() {
2637
+ emit(bannerLines());
2638
+ await refreshSpend();
2639
+ out.write('\n');
2640
+
2641
+ const rl = options.readline || readline.createInterface({ input: process.stdin, output: out, terminal: true });
2642
+ const promptStr = themeOf(ctx()).gold + GLYPH.cursor + ' ' + RESET;
2643
+ rl.setPrompt(promptStr);
2644
+ rl.prompt();
2645
+
2646
+ return new Promise((resolve) => {
2647
+ rl.on('line', async (line) => {
2648
+ rl.pause();
2649
+ let keep = true;
2650
+ try {
2651
+ keep = await handleLine(line);
2652
+ } catch (e) {
2653
+ emit(render.renderNotice(ctx(), 'error', e.message));
2654
+ }
2655
+ if (!keep || wantExit) {
2656
+ closed = true;
2657
+ rl.close();
2658
+ return;
2659
+ }
2660
+ rl.resume();
2661
+ rl.prompt();
2662
+ });
2663
+ rl.on('close', () => {
2664
+ if (!closed) out.write('\n');
2665
+ resolve(0);
2666
+ });
2667
+ });
2668
+ }
2669
+
2670
+ /**
2671
+ * Restore persisted preferences into the live context. The reference does this
2672
+ * at startup (`main.js:290-296`); this client never called `loadConfig()` on
2673
+ * launch at all, so a model or effort chosen in a previous session was written
2674
+ * to disk and then ignored on the next run.
2675
+ *
2676
+ * An explicit CLI flag always wins over the stored value — `aegiscode -m x`
2677
+ * must mean `x`, not "x unless the config disagrees".
2678
+ */
2679
+ function restorePrefs() {
2680
+ // An embedded/injected readline is a programmatic caller: it gets a
2681
+ // deterministic context rather than whatever happens to be on disk.
2682
+ if (options.readline) return;
2683
+ // A fresh install has no expressed preference to restore. Applying
2684
+ // DEFAULT_CONFIG here would silently pin the user to a model they never
2685
+ // chose, which is the opposite of "remember what I picked".
2686
+ if (!configExists()) return;
2687
+ let cfg;
2688
+ try {
2689
+ cfg = loadConfig();
2690
+ } catch {
2691
+ return;
2692
+ }
2693
+ // The class first: a stored BYOK pin is only meaningful under byok, and the
2694
+ // pin check right after this reads whichever class won.
2695
+ //
2696
+ // Gated on the OFFERED set, not HOST_CLASSES: a config written while `pro`
2697
+ // was enabled must not restore a subscription session onto a machine where
2698
+ // it has been turned off, or where this install never opted in. Such a
2699
+ // stored value falls back to the live default rather than being trusted.
2700
+ if (selectableClasses().includes(cfg.modelClass)) commandCtx.modelClass = cfg.modelClass;
2701
+ // A `--class` flag outranks the stored pin, the same way `--model` outranks
2702
+ // `cfg.model` on the next line. Clamped to the OFFERED set for the reason
2703
+ // the restore above is: a class this host cannot run (or `pro` on an install
2704
+ // that never opted in) must not be honoured just because it was typed.
2705
+ // An unknown or unoffered value is refused rather than silently downgraded
2706
+ // to the pooled route — a headless turn that asked for byok and got billed
2707
+ // to the pool is the exact defect this flag exists to fix.
2708
+ if (opts.class) {
2709
+ const want = String(opts.class).trim().toLowerCase();
2710
+ if (!selectableClasses().includes(want)) {
2711
+ throw new Error(
2712
+ `--class ${opts.class}: not available on this host (offered: ${selectableClasses().join(', ')})`
2713
+ );
2714
+ }
2715
+ commandCtx.modelClass = want;
2716
+ }
2717
+ if (!opts.model && cfg.model) commandCtx.model = cfg.model;
2718
+ // Restored through effortRung(), so a config written by an older build is
2719
+ // never a value this one does not send: `null`, `''` and the retired
2720
+ // `'auto'` all come back as 'high' — the same rung the request would have
2721
+ // carried had the key been missing from the file entirely.
2722
+ //
2723
+ // A `--effort` flag outranks the stored rung for exactly the turn it was
2724
+ // passed on: it is the only way a scripted `aegiscode -p` can pin a level,
2725
+ // and silently letting a config pin win would make the flag a no-op on any
2726
+ // machine that had ever run /effort.
2727
+ commandCtx.effort = effortRung(opts.effort || cfg.effort);
2728
+ if (typeof cfg.vim === 'boolean') commandCtx.vim = cfg.vim;
2729
+ if (cfg.lastRecap) commandCtx.lastRecap = cfg.lastRecap;
2730
+ // THEME_TABLE lives in theme.js, not screens.js: reading it off the screens
2731
+ // module yielded undefined, and only on a *second* launch (the first has no
2732
+ // config to restore, so this branch never ran) — so the very first run
2733
+ // appeared to work and every run after it died on startup.
2734
+ if (!opts.light && typeof cfg.themeIndex === 'number' && THEME_TABLE[cfg.themeIndex]) {
2735
+ commandCtx.themeIndex = cfg.themeIndex;
2736
+ // `themeIsLight` and not `row.light`: row 0's own flag is the dark
2737
+ // fallback, and reading it directly is what pinned a light-terminal user
2738
+ // back to the dark palette on every launch after they chose "Auto".
2739
+ commandCtx.light = themeIsLight(cfg.themeIndex);
2740
+ // A stored row is a preference about a *terminal*, and the terminal it
2741
+ // was chosen on need not be the one it is being restored on. Row 2 is
2742
+ // "Light mode" — primary text `RGB(40,40,40)` — and restoring it onto a
2743
+ // dark terminal drew that text over `#1e1e2e`: contrast 1.11:1, a body of
2744
+ // text present and unreadable. Reading the row as a bare brightness (what
2745
+ // this line did before) is why nothing ever checked. The stored value is
2746
+ // left untouched: the correction belongs to this terminal, and moving
2747
+ // back to a light one restores the choice by itself.
2748
+ const fixed = reconcileThemeIndex(commandCtx.themeIndex);
2749
+ if (fixed.changed) {
2750
+ commandCtx.themeIndex = fixed.index;
2751
+ commandCtx.light = themeIsLight(fixed.index);
2752
+ commandCtx.themeNotice = fixed.reason;
2753
+ // And it is written back. The stored row is a choice that THIS terminal
2754
+ // cannot satisfy, so leaving it on disk would mean the correction is
2755
+ // re-applied — and re-announced — on every launch forever, with the
2756
+ // config asserting a preference the session never honours. `/theme`
2757
+ // still sets it, and the announcement says which value was saved, so
2758
+ // the file and the screen never disagree silently.
2759
+ try {
2760
+ updateConfig({ themeIndex: fixed.index, light: themeIsLight(fixed.index) });
2761
+ } catch {
2762
+ // An unwritable config is not a reason to draw unreadable text: the
2763
+ // in-memory correction above already applies, and the notice says so.
2764
+ commandCtx.themeNotice += ' (could not save it)';
2765
+ }
2766
+ }
2767
+ }
2768
+ }
2769
+
2770
+ /**
2771
+ * Say the stored theme was corrected for this terminal, once, on a real
2772
+ * screen. Emitted before the session takes the alternate screen so it lands
2773
+ * in scrollback rather than being wiped by the session's first frame, and
2774
+ * only when the correction actually happened — an unasked-for notice about an
2775
+ * unchanged setting is noise.
2776
+ */
2777
+ function themeNoticeFirstRun() {
2778
+ if (!commandCtx.themeNotice) return;
2779
+ const reason = commandCtx.themeNotice;
2780
+ commandCtx.themeNotice = '';
2781
+ emit(render.renderNotice(ctx(), 'warn', `theme: ${reason} (saved)`));
2782
+ }
2783
+
2784
+ /**
2785
+ * Interactive entry point. On a real terminal this is the full chatflow
2786
+ * (alternate screen, header, transcript viewport, spinner, effort line,
2787
+ * input line, status line, overlays). Anywhere else — a pipe, a test with an
2788
+ * injected readline, `--print` — it stays the linear loop, so output remains
2789
+ * pipeable and scriptable.
2790
+ */
2791
+ /**
2792
+ * Interactive session: the loop itself (`runInteractiveSession`), then the
2793
+ * local lane handed back. Wrapped for the same reason `runOnce` is: the loop
2794
+ * has several exits (a declined onboarding, `/quit`, a reset key stream, the
2795
+ * linear REPL), and "closing the session closes the model" must hold on all
2796
+ * of them rather than on the one path a `return` happens to reach.
2797
+ */
2798
+ async function runInteractive() {
2799
+ try {
2800
+ return await runInteractiveSession();
2801
+ } finally {
2802
+ await releaseLocalModel();
2803
+ }
2804
+ }
2805
+
2806
+ async function runInteractiveSession() {
2807
+ const tty =
2808
+ !options.readline &&
2809
+ options.chatflow !== false &&
2810
+ process.stdin.isTTY &&
2811
+ process.stdout.isTTY;
2812
+ if (tty) {
2813
+ // Ask the terminal what its background is BEFORE the stored theme is
2814
+ // restored, because the restore is a decision *about that background*.
2815
+ // Nothing in the environment answers this on the terminals people run —
2816
+ // Alacritty sets neither `COLORFGBG` nor `TERM_BACKGROUND` — so without
2817
+ // the query the palette was chosen from silence. Bounded (120ms) and
2818
+ // skipped entirely when an env var already decided, so a session that
2819
+ // reports nothing is as fast as it was.
2820
+ //
2821
+ // A keypress can race the terminal's answer into the same read, so any
2822
+ // byte that was not the answer is handed back to the key pump's own queue
2823
+ // rather than to the stream: `events.feedKeys` delivers it exactly as a
2824
+ // `data` event would have, including after stdin has ended.
2825
+ // `keystrokes: true` matters. The probe hands back a whole burst, and a
2826
+ // command issued at launch (`/exit\r`) arrives as one string containing a
2827
+ // newline — which the paste heuristic would otherwise collapse into a
2828
+ // single paste key, losing the Enter and parking the session loop forever
2829
+ // at the welcome screen. See `events.feedKeys`.
2830
+ await probeTerminalBackground({
2831
+ onLeftover: (text) => events.feedKeys(text, { keystrokes: true }),
2832
+ });
2833
+ restorePrefs();
2834
+ themeNoticeFirstRun();
2835
+ adoptLegacyKeyOnce();
2836
+ // Give aegis1 a chance to auto-provision a free device key BEFORE
2837
+ // deciding whether onboarding needs to ask for one — a fresh install
2838
+ // should never be prompted for a key it can get on its own.
2839
+ if (!client.apiKey) await ensureApiKey();
2840
+ // Onboarding runs in the normal buffer, before the session takes the
2841
+ // alternate screen — the reference's order. A declined trust check must
2842
+ // abort: the reference returns without ever reaching `session(ctx)`.
2843
+ const onboard = await screens.runOnboarding(commandCtx, {
2844
+ continue: !!options.continue,
2845
+ seen: options.seen || configExists,
2846
+ save: (patch) => updateConfig(patch),
2847
+ // With no key the session can do nothing, so ask for it here where the
2848
+ // user is already answering questions — verified on submit, and saved
2849
+ // 0600 so the next launch (and every script) has it.
2850
+ needsKey: () => !client.apiKey,
2851
+ submitKey: (key) => setApiKey(key),
2852
+ });
2853
+ if (!onboard.ok) return 0;
2854
+ if (onboard.key && onboard.key.set) {
2855
+ emit(
2856
+ render.renderNotice(
2857
+ ctx(),
2858
+ 'info',
2859
+ `key saved to ${credentials.credentialsPath()} — no export needed from now on`
2860
+ )
2861
+ );
2862
+ }
2863
+ if (onboard.key && onboard.key.skipped && !client.apiKey) {
2864
+ emit(
2865
+ render.renderNotice(
2866
+ ctx(),
2867
+ 'warn',
2868
+ `no key saved — /key <api_key> or \`aegiscode login\` whenever you are ready`
2869
+ )
2870
+ );
2871
+ }
2872
+ // The write half of cross-session memory is on by default (see
2873
+ // config.js). Say so once, on the run that sets the account up, together
2874
+ // with the ceiling and the opt-out — a default nobody is told about is a
2875
+ // setting they cannot make a decision about.
2876
+ if (onboard.firstRun) memoryFirstRunNotice();
2877
+ // A stored pin the platform does not advertise routes elsewhere in
2878
+ // silence (see validatePinnedModel) — checked once, here, where the user
2879
+ // can act on it. Not on `-p`: a network round-trip ahead of the first
2880
+ // token would be a startup cost bought for a warning no script watches.
2881
+ await validatePinnedModel();
2882
+ // `--continue` must load the last session *before* the loop starts, and
2883
+ // it has to be read here rather than captured at construction: the
2884
+ // history file is written by the loop itself.
2885
+ if (options.continue) {
2886
+ const last = readOwnSessions(1)[0];
2887
+ if (last) {
2888
+ commandCtx.continueSession = last.id;
2889
+ await resumeSession({ id: last.id });
2890
+ }
2891
+ }
2892
+ // Snapshot the account's ledger before the loop's first billed turn, so
2893
+ // the session tally cannot absorb the customer's existing spend and the
2894
+ // first turn's charge is not mistaken for pre-existing history.
2895
+ await refreshSpend();
2896
+ await chatflow.runSession(makeHost());
2897
+ return 0;
2898
+ }
2899
+ restorePrefs();
2900
+ adoptLegacyKeyOnce();
2901
+ return runLinearRepl();
2902
+ }
2903
+
2904
+ return {
2905
+ opts,
2906
+ session,
2907
+ client,
2908
+ TOOLS,
2909
+ toolList,
2910
+ ctx: commandCtx,
2911
+ transcript,
2912
+ ask,
2913
+ runPrompt,
2914
+ handleLine,
2915
+ runOnce,
2916
+ runInteractive,
2917
+ runLinearRepl,
2918
+ refreshSpend,
2919
+ bannerLines,
2920
+ makeHost,
2921
+ loadModels,
2922
+ validatePinnedModel,
2923
+ recordTurn,
2924
+ persistTurn,
2925
+ restorePrefs,
2926
+ setApiKey,
2927
+ forgetApiKey,
2928
+ adoptLegacyKeyOnce,
2929
+ cloudSyncEnabled,
2930
+ cloudSyncState,
2931
+ setCloudSync,
2932
+ cloudsync,
2933
+ keyStatus: () => credentials.keyStatus(),
2934
+ accountConfigured: () => !!(credentials.keyStatus() || {}).configured,
2935
+ // Same masked-read defect as the host binding above — see the comment
2936
+ // there. Kept identical so the two hosts cannot disagree about whether a
2937
+ // key is stored.
2938
+ hasProviderKey: (provider) => {
2939
+ const store = engine.settings;
2940
+ if (!store || !provider) return false;
2941
+ const row = byokNamespace(provider);
2942
+ if (typeof store.rawKey === 'function') {
2943
+ return !!String(store.rawKey(row) || '').trim();
2944
+ }
2945
+ if (typeof store.get !== 'function') return false;
2946
+ return !!((store.get(row) || {}).configured);
2947
+ },
2948
+ sessionId: () => commandCtx.sessionId,
2949
+ tokenSummary,
2950
+ resumeSession,
2951
+ makeCommandContext,
2952
+ buildState,
2953
+ get aborted() {
2954
+ return false;
2955
+ },
2956
+ };
2957
+ }
2958
+
2959
+ module.exports = { createApp, VERSION, normalizeDecision };