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/commands.js CHANGED
@@ -1,3 +1,4091 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- "use strict";const fs=require("node:fs"),os=require("node:os"),path=require("node:path"),{execSync:execSync}=require("node:child_process"),{span:span}=require("./screen.js"),{C:C,BOLD:BOLD,BOLD_OFF:BOLD_OFF,THEME_TABLE:THEME_TABLE,themeContradicts:themeContradicts}=require("./theme.js"),{caps:caps,setCaps:setCaps,resetCaps:resetCaps,describe:describe,probeTerminalBackground:probeTerminalBackground}=require("./caps.js"),panels=require("./panels.js"),overlays=require("./overlays.js"),{updateConfig:updateConfig,loadConfig:loadConfig,loadPermissions:loadPermissions,savePermissions:savePermissions,addPermissionRule:addPermissionRule,DEFAULT_PERMISSIONS:DEFAULT_PERMISSIONS,permissionsPath:permissionsPath,configPath:configPath,aegisDir:aegisDir,setConfirmPosture:setConfirmPosture,setPermissionDefaultMode:setPermissionDefaultMode,confirmPosture:confirmPosture,memoryPersistState:memoryPersistState,setMemoryPersist:setMemoryPersist}=require("./config.js"),{auditExposure:auditExposure,repairExposure:repairExposure}=require("./securefs.js"),{copyToClipboard:copyToClipboard}=require("./clipboard.js"),{snapshotCheckpoint:snapshotCheckpoint,listCheckpoints:listCheckpoints,loadCheckpoint:loadCheckpoint}=require("./checkpoint.js"),{signupUrl:signupUrl,goUrl:goUrl}=require("./signup.js"),screens=require("./screens.js"),{summarizeTranscript:summarizeTranscript,recapLine:recapLine}=require("./summarize.js"),{sessionAccounting:sessionAccounting,accountingFromUsage:accountingFromUsage,estimateTokens:estimateTokens}=require("./tokens.js"),{effortRung:effortRung}=require("./engine.js"),{transcriptToMarkdown:transcriptToMarkdown,transcriptToJSON:transcriptToJSON,writeExportFile:writeExportFile,lastAssistantText:lastAssistantText}=require("./export.js"),{detectDevCommand:detectDevCommand,runDevServer:runDevServer}=require("./devrun.js"),{PING_MODES:PING_MODES,DEFAULT_PING_MODE:DEFAULT_PING_MODE,normalizePingMode:normalizePingMode,normalizePingSeconds:normalizePingSeconds,buildPing:buildPing,writePing:writePing}=require("./ping.js"),{addTodo:addTodo,completeTodo:completeTodo,clearTodos:clearTodos,formatTodos:formatTodos,todosFile:todosFile}=require("./todos.js"),{configRows:configRows,formatConfigRows:formatConfigRows,setConfigValue:setConfigValue,resetConfigValue:resetConfigValue,fullValue:fullValue,summarizeValue:summarizeValue,configStore:configStore}=require("./settings.js"),credentials=require("./credentials.js"),cloudsync=require("./cloudsync.js"),{maskKey:maskKey,fmtTokens:fmtTokens,shortCwd:shortCwd}=require("./format.js"),{pickerEntries:pickerEntries}=require("./models.js"),{resolveShared:resolveShared}=require("./sharedpaths.js"),{createCliEntitlement:createCliEntitlement,paymentView:paymentView,probeFee:probeFee}=require("./entitlement.js"),{openUrl:openUrl,URLS:URLS}=require("./system.js"),sysdiag=require("./sysdiag.js"),{sniffProject:sniffProject,buildAegisMd:buildAegisMd}=require("./init.js"),{upgradeAdvice:upgradeAdvice,latestPublishedVersion:latestPublishedVersion,applyUpgrade:applyUpgrade,installMethod:installMethod}=require("./update.js"),{AGENT_PRESETS:AGENT_PRESETS,agentRoles:agentRoles,composeAgentPrompt:composeAgentPrompt,composeResearchPrompt:composeResearchPrompt,composeDebatePrompt:composeDebatePrompt}=require("./agents.js"),{aggregateSessionUsage:aggregateSessionUsage,pruneSessionHistory:pruneSessionHistory,readResumeList:readResumeList}=require("./history.js");let markdownModule=null;try{markdownModule=require("./markdown.js")}catch{markdownModule=null}const VERSION=require("../package.json").version,CATEGORIES=[{id:"session",label:"Session & context"},{id:"workspace",label:"Workspace"},{id:"model",label:"Model & behavior"},{id:"data",label:"Data"},{id:"auth",label:"Auth"},{id:"support",label:"Support"},{id:"fun",label:"Fun"},{id:"aegis",label:"Aegis plugin"},{id:"custom",label:"Custom"}],categoryLabel=e=>(CATEGORIES.find((t=>t.id===e))||{}).label||e,EFFORT_LEVELS=overlays.EFFORT_VALUES,note=(e,t)=>e.push({role:"note",text:t}),panel=(e,t)=>e.push({role:"panel",lines:t}),tip=(e,t)=>e.push({role:"tip",text:t}),done=(e,t)=>e.push({role:"done",text:t});function composeMultiFanoutPrompt(e){return["Execute this task as a multi-agent fan-out.","",`Task: ${e}`,"",`Workspace: ${process.cwd()}`,"","Use the task tool to delegate the independent parts to specialist subagents, in parallel where they do not depend on each other:","- reconnaissance first (scanner for secrets/unsafe patterns, analyzer for refactor targets),","- then design (architect, or planner when the work is a change to existing code),","- then an implementer subagent to make the change.","Finally review the result (reviewer subagent), fix what it finds, and verify with the repository's real commands.","","Return one consolidated report: what each subagent found, the files you changed, the exact commands you ran and their real output, and anything still blocked. No preamble."].join("\n")}async function multiData(e,t){const n=composeMultiFanoutPrompt(t),o=e&&e.withWorking?t=>e.withWorking(t):e=>e();if(!e||"function"!=typeof e.ask&&"function"!=typeof e.runPrompt)return{error:"No agent loop in this context — the fan-out prompt was composed, not run."};try{if("function"==typeof e.ask){const t=await o((t=>e.ask(n,{signal:t}))),r=t&&t.text||"";return t&&t.interrupted&&!r?{cancelled:!0}:r?{result:r,model:t&&t.model||e.ctx&&e.ctx.model||null,provider:"aegis"}:{error:"The multi-agent fan-out returned nothing (the turn failed before it could delegate)."}}return await o((()=>e.runPrompt(n))),{streamed:!0}}catch(e){return{error:`ÆGIS multi failed — ${e&&e.message||e}`}}}async function runMultiCommand(e,t,{yolo:n=!1,title:o="ÆGIS Multi"}={}){n&&(setConfirmPosture(!1),panel(e,panels.buildAutomode(e.state(),e.ctx))),note(e,"Running the multi-agent fan-out — the engine delegates to specialist subagents (headless: this skips aegis-cli's own confirmation step)."),e.render();const r=await multiData(e,t);return r.cancelled?(note(e,"ÆGIS multi cancelled."),e.render(),!0):r.error?(note(e,r.error),panel(e,panels.buildAegisMulti(t,e.ctx)),e.render(),!0):(r.streamed||(panel(e,panels.buildAegisPrint(o,r,e.ctx)),e.render()),!0)}const upgradePanelLines=e=>e.map((e=>[span(C.white,e)]));async function billingPayment(e){if(!e||!e.client)return;let t;try{t=createCliEntitlement({aegis:e.client})}catch{return}const n=e.withWorking?t=>e.withWorking(t):e=>e();try{await n((()=>t.refresh({force:!0})))}catch{}const o=await probeFee();return paymentView(t.current(),{host:"cli",fee:o})}async function loadModels(e){try{return await e.loadModels()||[]}catch{return[]}}async function mergedPickerModels(e){const t=e.ctx&&e.ctx.modelClass||"aegis",n=pickerEntries(await loadModelsFor(e,"aegis",t)).map((e=>({...e,cls:"aegis"}))),o=pickerEntries(await loadModelsFor(e,"byok",t)).map((e=>({...e,cls:e.cls||"byok"}))),r=pickerEntries(await loadModelsFor(e,"pro",t)).map((e=>({...e,cls:"pro"}))),s=[],a=new Set;for(const e of[...n,...o,...r]){const t=String(e&&e.id||"");t&&!a.has(t)&&(a.add(t),s.push(e))}return s}async function loadModelsFor(e,t,n){if("function"==typeof e.listModelsFor)try{return await e.listModelsFor(t)||[]}catch{return[]}if(t!==n||"function"!=typeof e.loadModels)return[];try{return await e.loadModels()||[]}catch{return[]}}const cloudReady=()=>credentials.hasApiKey(),{withByokAdditions:withByokAdditions}=require(resolveShared(path.join("client","byok-catalog.js"))),{withUserModels:withUserModels,addUserModel:addUserModel,removeUserModel:removeUserModel,userModelIdsFor:userModelIdsFor,userModelsPath:userModelsPath}=require(resolveShared(path.join("client","user-models.js"))),catalogClient=require(resolveShared(path.join("client","catalog-client.js"))),{withCatalog:withCatalog}=catalogClient,{discoverModels:discoverVendorModels,endpointFor:vendorEndpointFor,discoverableProviders:discoverableProviders}=require(resolveShared(path.join("client","model-discovery.js")));function byokKeyForProvider(e,t){const n=String(t||"").trim().toLowerCase();if(!n)return"";try{const t=e&&e.settings&&e.settings();if(t&&"function"==typeof t.rawKey&&"function"==typeof e.byokNamespace){const o=t.rawKey(e.byokNamespace(n));if("string"==typeof o&&o.trim())return o.trim()}}catch{}try{const{providerKeyFromEnv:e}=require(resolveShared(path.join("client","env-file.js")));return(e(n)||{}).key||""}catch{return""}}async function discoverProviderModels(e,t,n){try{return await discoverVendorModels(t,{key:n,fetchImpl:e&&e.fetchImpl})}catch(e){return{ok:!1,provider:t,supported:!0,error:e&&e.message||String(e)}}}async function offeredModelIds(e,t,n){const o=await discoverProviderModels(e,t,n);return o&&o.ok&&Array.isArray(o.ids)&&o.ids.length?o.ids:void 0}function splitCommandWords(e){const t=[];let n="",o=null,r=!1;for(const s of String(null==e?"":e))o?s===o?o=null:n+=s:'"'!==s&&"'"!==s?/\s/.test(s)?(n||r)&&(t.push(n),n="",r=!1):(n+=s,r=!0):(o=s,r=!0);return(n||r)&&t.push(n),t}function savedByokBaseURL(e,t){try{const n=e&&e.settings&&e.settings();if(!n||"function"!=typeof n.get||"function"!=typeof e.byokNamespace)return"";const o=n.get(e.byokNamespace(t))||{};return String(o.baseURL||"").trim()}catch{return""}}function addManyUserModels(e,t){let n=0,o=0;const r=[],s=[];for(const a of t)try{addUserModel(e,a).added?n+=1:r.push(a)}catch(e){const i=e&&e.message||String(e);if(/the cap/.test(i)){o=t.length-n-r.length-s.length;break}s.push({id:a,reason:i})}return{added:n,already:r,failed:s,capped:o}}async function byokCatalog(e){if(!e||"function"!=typeof e.byokProviders)return null;try{const t=await e.byokProviders();refreshCatalogInBackground(e);const n=withUserModels(withCatalog(withByokAdditions(t&&t.providers||[])));return n.length?n:null}catch{return null}}function refreshCatalogInBackground(e){try{let t=!0;try{const e=catalogClient.read();t=!e||e.stale}catch{t=!0}if(!t)return null;if("function"!=typeof e.catalog)return null;let n=null;try{const e=catalogClient.read();n=e&&e.data&&e.data.snapshot&&e.data.snapshot.etag||null}catch{n=null}const o=catalogClient.refresh((async({cursor:t,limit:n,etag:o})=>{try{return await e.catalog("models",{cursor:t,limit:n},{etag:o||void 0})}catch(e){if(e&&304===e.status)return{notModified:!0};throw e}}),{etag:n});return o&&"function"==typeof o.catch&&o.catch((()=>{})),o}catch{return null}}function findByokProvider(e,t){const n=String(t||"").trim().toLowerCase();if(!e)return{provider:null,exact:!1};const o=e.find((e=>e.id===n));if(o)return{provider:o,exact:!0};const r=e.filter((e=>[e.id,e.label,...e.aliases||[]].filter(Boolean).some((e=>String(e).toLowerCase()===n))));return 1===r.length?{provider:r[0],exact:!1}:r.length>1?{ambiguous:r.map((e=>e.id))}:{provider:null,exact:!1}}function byokProviderLines(e){const t=[];for(const n of e){const e=n.configured?span(C.green,"set"+(n.masked?` (${n.masked})`:"")):span(C.gray,"not set"),o=[span(C.gold+BOLD,` ${n.id}`)];n.label&&o.push(span(C.gray,` — ${n.label}`)),o.push(span(""," "),e),t.push(o);const r=(n.models||[]).map((e=>"string"==typeof e?e:e&&e.id)).filter(Boolean);r.length&&t.push([span(C.gray,` models: ${r.join(", ")}`)]),n.key_prefix&&t.push([span(C.gray,` key starts with ${n.key_prefix}`)]),n.key_url&&t.push([span(C.gray,` ${n.key_url}`)])}return t}function keyPanelLines(e,t="AEGIS account key"){const n=e.keyStatus(),o=[[span(C.gold+BOLD,t),span(BOLD_OFF,"")],[span(C.gray,"─".repeat(34))],[span(n.configured?C.green:C.coral," "+(n.configured?"✔":"⚠")),span(C.white," key: "),span(n.configured?C.white:C.gray,n.configured?maskKey(n.key):"not set"),span(C.gray,` (${credentials.sourceLabel(n.source)})`)],[span(C.gray,` stored in: ${n.path}${n.fileMode?` ${n.fileMode}`:""}`)]];return n.verifiedAt&&o.push([span(C.gray,` verified: ${n.verifiedAt}`)]),n.account&&(n.account.plan||n.account.email)&&o.push([span(C.gray," account: "),span(C.white,[n.account.plan,n.account.email].filter(Boolean).join(" · "))]),o.push([span(C.gray," memory: "),span(n.memoryToken?C.green:C.gray,n.memoryToken?"token held (cloud sync ready)":"no token yet")]),n.configured||(o.push([span(C.gray,"")]),o.push([span(C.white," Set one with /key <api_key>, or press Enter on /key to paste it.")]),o.push([span(C.gray,` Free key: ${signupUrl("key_status")}`)])),n.legacyPlaintext&&(o.push([span(C.gray,"")]),o.push([span(C.coral," ⚠ a plaintext copy of the key is still in config.json (another AEGIS CLI wrote it).")]),o.push([span(C.gray," Re-save with /key <api_key> and delete that block when convenient.")])),o}async function applyAccountKey(e,t,{label:n="AEGIS API key"}={}){let o=String(t||"").trim();if(o||(o=await e.readSecret(`${n} (kept off screen, Enter to cancel): `)),!o)return note(e,"no key given — /key <api_key> takes it inline, or press Enter on a bare /key to paste it"),{ok:!1};const r=await e.setApiKey(o);if(!r.ok)return note(e,r.message||"that key could not be saved"),r;if(r.error)return note(e,`saved, but the account check failed: ${r.error.message}`),note(e,"the key is stored — /key status shows it; re-run /key <api_key> if it was mistyped"),r;const s=r.account&&(r.account.email||r.account.plan)||null;done(e,`AEGIS key saved to ${r.path}${s?` — signed in as ${s}`:" and verified"}`);try{const t=pickerEntries(await loadModels(e)).length;t&&note(e,`${t} pinnable model${1===t?"":"s"} available — /model to pin one`)}catch{}return r}function fmtQuotaTokens(e){const t=Number(e);return Number.isFinite(t)?t>=1e6?`${(t/1e6).toFixed(t%1e6==0?0:1)}M`:t>=1e4?`${Math.round(t/1e3)}k`:fmtTokens(t):"?"}function memoryGate(e){if(e&&"function"==typeof e.cloudSyncState)try{return e.cloudSyncState()}catch{}return{enabled:!e||"function"!=typeof e.cloudSyncEnabled||!0===e.cloudSyncEnabled(),source:"default"}}function setMemoryGate(e,t){if(e&&"function"==typeof e.setCloudSync)return e.setCloudSync(t);try{return setMemoryPersist(t)}catch{return null}}function memoryStatusLines(e){const t=memoryGate(e),n=cloudsync.status(),o=n.quota,r=o&&null!=o.used?fmtQuotaTokens(o.used):null,s=o&&null!=o.limit?fmtQuotaTokens(o.limit):null,a="legacy"===t.source?" (kept from your old cloudSync setting)":"default"===t.source?" (default)":"",i=[[span(C.white+BOLD,"Persisting memory"),span(C.gray," · Cloud sync"),span(BOLD_OFF,"")],[span(C.gray,"─".repeat(34))],[span(C.white," "+(t.enabled?"on":"off")),span(C.gray,`${a} · ${t.enabled?"each session is stored so an interrupted turn can be resumed":"nothing new is stored"}`)]];return s?i.push([span(C.gray," quota: "),span(C.white,`${r} of ${s} tokens synced`),span(C.gray," (aegis1 charges writes; reads are always served)")]):i.push([span(C.gray," quota: not reported yet — /sync now asks the server for the current numbers")]),n.overQuota&&(i.push([span(C.coral," writes: paused — the plan’s ceiling is reached, so new memory is not being stored")]),i.push([span(C.green," reads: still work — everything already stored stays readable (/aegis-recall <topic>)")]),i.push([span(C.gray,` free room at ${goUrl("upgrade","cloud_quota")}`)]),i.push([span(C.gray," or /cloud memory off to stop trying")])),t.enabled&&n.pending>0&&i.push([span(C.gray,` pending: ${n.pending} session(s) waiting to sync`)]),i.push([span(C.gray," /cloud memory on | off · /sync now pushes once by hand")]),i}async function runCloudSync(e,t={}){if(!e.client.apiKey)return note(e,`no key — ${credentials.HOW_TO_SET}`),null;const n=await e.withWorking((()=>cloudsync.syncNow(e.client,t))),o=n.push&&n.push.pushed||[],r=[...n.push&&n.push.failed||[],...n.pull&&n.pull.failed||[]],s=n.pull&&n.pull.imported||0;o.length?done(e,`pushed ${o.length} session${1===o.length?"":"s"} (${o[0].messages} messages in the first)`):n.push&&n.push.skipped&&n.push.skipped.length?note(e,`${n.push.skipped.length} session(s) had nothing to send`):note(e,"nothing to push — every local session is already in the cloud"),s?done(e,`pulled ${s} record${1===s?"":"s"} into the local store — /resume lists them`):n.pull&&n.pull.ok&&note(e,`cloud has ${n.pull.remote||0} session(s); nothing newer locally`);for(const t of r)note(e,`${"quota"===t.kind?"quota":"failed"}: ${t.message}`),t.hint&&note(e,t.hint);return n}const hooksLib=require(resolveShared(path.join("client","hooks.js")));function readHooks(){return hooksLib.readHookConfig()}function hookStats(e){return hooksLib.hookStats(e)}function scanSkills(){const e=[path.join(os.homedir(),".aegis","skills"),path.join(process.cwd(),".aegis","skills"),path.join(os.homedir(),".aegiscode","skills"),path.join(process.cwd(),".aegiscode","skills"),path.join(os.homedir(),".claude","skills")],t=[];for(const n of e){const e=n.startsWith(process.cwd())?"project":"user";let o=[];try{o=fs.readdirSync(n,{withFileTypes:!0}).filter((e=>e.isDirectory())).map((e=>e.name))}catch{continue}for(const r of o){const o=path.join(n,r,"SKILL.md");try{const n=fs.readFileSync(o,"utf8"),s=(/^description:\s*(.+)$/m.exec(n)||[])[1]||"";t.push({source:e,name:r,namespace:null,description:s.trim(),path:o,content:n})}catch{}}}return t}const COMMANDS=[{name:"run",hint:"",category:"workspace",desc:"Launch and drive this project's app to see a change working",handler:async e=>{const t=detectDevCommand(process.cwd());if(!t)return note(e,"No dev command detected (no package.json scripts, go.mod, Cargo.toml or Makefile). Try /init first."),e.render(),!0;note(e,`Running ${t} in ${shortCwd()} — output streams below, Esc stops it.`);const n=runDevServer(t,{cwd:process.cwd(),onLine:t=>e.push({role:"note",text:` ${t}`})});return n.label||(n.label=t),e.openStream(n),n.done.then((({code:o,stopped:r})=>{e.closeStream(n),done(e,r?`${t} stopped`:`${t} exited (code ${o})`),e.render()})),e.render(),!0}},{name:"schedule",hint:"",category:"session",desc:"Create, update, list, or run scheduled cloud agents (routines)",handler:async e=>(note(e,"Scheduled routines run on the AEGIS cloud. Sign in with `aegis login`, then manage routines at aegiscloud.org."),e.render(),!0)},{name:"build",aliases:["forge"],args:["task"],hint:"<description>",category:"workspace",desc:"Build an app with the agent loop — /build <what to build>",handler:async(e,t)=>{const n=(t._rest||t.task||"").trim();return n?(note(e,"⬡ AEGIS BUILD"),note(e,`Task: ${n}`),e.render(),await e.runPrompt(`Build the following, creating every file it needs and running the build to verify it works: ${n}`),!0):(note(e,"Usage: /build <what to build>"),note(e,"Example: /build a REST API for a todo app"),e.render(),!0)}},{name:"cd",args:["path"],hint:"<path>",category:"workspace",desc:"Move this session to a new working directory",handler:async(e,t)=>{const n=t.path||(t._rest||"").trim();if(!n)return note(e,"Usage: /cd <path>"),e.render(),!0;try{process.chdir(n),e.ctx.cwd=process.cwd(),updateConfig({lastCwd:process.cwd()}),note(e,`Changed directory to ${process.cwd()}`)}catch(t){note(e,`/cd: ${t.message}`)}return e.render(),!0}},{name:"copy",aliases:["cp"],args:["n"],hint:"[N]",category:"data",desc:"Copy the last response to the clipboard",handler:async(e,t)=>{const n=parseInt(t.n||"1",10)||1,o=lastAssistantText(e.transcript,n);if(!o)return note(e,"Nothing to copy yet."),e.render(),!0;const r=copyToClipboard(o);return r.ok?note(e,r.via.startsWith("tool:")?`Copied the last response to the clipboard (${r.via.split(":")[1]}).`:`No clipboard tool found — response saved to ${r.path}`):note(e,"Clipboard unavailable; nothing copied."),e.render(),!0}},{name:"clear",aliases:["cls"],hint:"",category:"session",desc:"Start a new session with empty context",handler:async e=>(e.transcript.length=0,pruneSessionHistory(e.sessionId),"function"==typeof e.clearConversationMemory&&e.clearConversationMemory(),note(e,"Session cleared — transcript empty."),e.render(),!0)},{name:"compact",hint:"",category:"session",desc:"Compact the conversation history",handler:async e=>{if(!e.transcript.some((e=>"user"===e.role||"assistant"===e.role)))return note(e,"Nothing to compact yet."),e.render(),!0;note(e,"Compacting conversation history…"),e.render();const t=await e.withWorking((t=>summarizeTranscript(e.transcript,{callModel:(t,n)=>e.ask(t,n).then((e=>e.text)),model:e.ctx.model,signal:t})));return null===t?(note(e,"Compaction cancelled."),e.render(),!0):(e.transcript.length=0,note(e,"Compacted. Earlier context summarized into the message below."),e.transcript.push({role:"user",text:t}),e.render(),!0)}},{name:"cost",hint:"",category:"data",desc:"Show the cost of the current session",handler:async e=>{const t=aggregateSessionUsage(e.sessionId),n=t.entries?accountingFromUsage(t.usage,e.ctx.model,{exchanges:t.entries,real:t.real,costUsd:t.real&&t.costUsd?t.costUsd:void 0}):sessionAccounting(e.transcript,e.ctx.model);return panel(e,panels.buildCost({...e.state(),contextWindow:n.contextWindow,costEur:n.cost},e.ctx)),e.render(),!0}},{name:"context",hint:"",category:"session",desc:"Show context usage for the current session",handler:async e=>{const t=sessionAccounting(e.transcript,e.ctx.model);return panel(e,panels.buildContext({...e.state(),contextWindow:t.contextWindow},e.ctx)),e.render(),!0}},{name:"ping",args:["mode","seconds"],hint:"[off|bell|notify|both] [seconds] | test",category:"model",desc:"Alert me when a long turn finishes, if I am looking elsewhere",handler:async(e,t)=>{const n=loadConfig(),o=(t._rest||"").trim().split(/\s+/).filter(Boolean),r=(o[0]||"").toLowerCase(),s=normalizePingMode(n.ping),a=normalizePingSeconds(n.pingMinSeconds);if(!r)return note(e,`[ping] ${s} — a turn longer than ${a}s raises a terminal notification.`),note(e,` /ping ${PING_MODES.filter((e=>e!==s)).join("|")} ${"off"===s?"turn it back on":"change the channel"}`),note(e," /ping <mode> <seconds> move the threshold (0 pings every turn)"),note(e," /ping test fire one now, to check this terminal supports it"),e.render(),!0;if("test"===r){const t=buildPing({mode:"off"===s?DEFAULT_PING_MODE:s}),n=!!process.stdout.isTTY&&writePing(process.stdout,t);return note(e,n?"[ping] sent one just now. If nothing appeared or sounded, this terminal implements neither OSC 9 nor OSC 777 — /ping bell is the fallback.":"[ping] nothing sent: stdout is not a TTY (a piped or headless run has no one to notify)."),e.render(),!0}if(!PING_MODES.includes(r))return note(e,`Unknown ping mode "${o[0]}". Use ${PING_MODES.join(", ")}.`),e.render(),!0;const i={ping:r};if(null!=o[1]){const t=Number(o[1]);if(!Number.isFinite(t)||t<0)return note(e,`"${o[1]}" is not a number of seconds. Use /ping ${r} 30.`),e.render(),!0;i.pingMinSeconds=normalizePingSeconds(t)}return updateConfig(i),"off"===r?note(e,"[ping] off — no notice will be raised, and nothing is reported as sent."):(note(e,`[ping] ${r} — turns longer than ${normalizePingSeconds(i.pingMinSeconds??n.pingMinSeconds)}s will notify you.`),note(e," Escape never pings (you were watching), and neither does a piped or headless run.")),e.render(),!0}},{name:"todos",aliases:["todo"],args:["sub","text"],hint:"[add <text> | done <n|text> | clear]",category:"session",desc:"A session todo list that survives compaction",handler:async(e,t)=>{const n=(t.sub||"").toLowerCase(),o=(t._rest||"").trim().replace(/^\S+\s*/,"");if(!n)return panel(e,formatTodos()),note(e,` ${todosFile()}`),note(e," /todos add <text> · /todos done <n|text> · /todos clear"),e.render(),!0;if("add"===n){const t=addTodo(o);return t.error?(note(e,t.error),e.render(),!0):(panel(e,formatTodos(t.list)),e.render(),!0)}if("done"===n||"do"===n){const t=completeTodo(o);return t.error?(note(e,t.error),e.render(),!0):(note(e,`[todos] "${t.item.text}" is now ${t.item.done?"done":"open"}.`),panel(e,formatTodos(t.list)),e.render(),!0)}return"clear"===n?(clearTodos(),note(e,"[todos] cleared."),e.render(),!0):(note(e,`Unknown /todos subcommand "${t.sub}". Use add, done or clear.`),e.render(),!0)}},{name:"config",args:["key","value"],hint:"[<key> | <key> <value> | reset <key>]",category:"session",desc:"Show or change any setting, and say which store holds it",handler:async(e,t)=>{const n=(t._rest||"").trim(),o=(t.key||"").trim(),r=n.replace(/^\S+\s*/,"");if(!o)return panel(e,formatConfigRows(configRows())),note(e," /config <key> show one value in full"),note(e," /config <key> <value> set it (true/false/null, numbers, JSON, or text)"),note(e," /config reset <key> back to the shipped value"),note(e,' "shared" keys live in the store AEGIS Desktop writes too; "host" keys are this shell\'s own.'),e.render(),!0;if("reset"===o){const t=resetConfigValue(r);return t.error?(note(e,t.error),e.render(),!0):(note(e,`[config] ${t.key} reset to ${summarizeValue(t.value)} (${t.store}).`),e.render(),!0)}if(!r){const t=loadConfig();return Object.prototype.hasOwnProperty.call(t,o)?(note(e,`${o} (${configStore(o)}):`),e.push({role:"panel",lines:fullValue(t[o]).split("\n").map((e=>` ${e}`))}),e.render(),!0):(note(e,`unknown config key "${o}" — run /config to list the keys`),e.render(),!0)}const s=setConfigValue(o,r);return s.error?(note(e,s.error),e.render(),!0):(note(e,`[config] ${s.key} = ${summarizeValue(s.value)} (${s.store}).`),["model","currentModelId","modelClass","effort","themeIndex","vim"].includes(s.key)&&("effort"===s.key&&(e.ctx.effort=effortRung(s.value),e.ctx.effort!==String(s.value).toLowerCase()&&(e.saveConfig({effort:e.ctx.effort}),note(e,` "${s.value}" is not a level this build sends — recorded as ${e.ctx.effort}.`))),note(e,` This takes effect on the next turn; /${"currentModelId"===s.key?"model":s.key} shows the live session value.`)),e.render(),!0)}},{name:"effort",args:["level"],hint:"[low|medium|high]",category:"model",desc:"Set the token budget the pool sizes each turn from",handler:async(e,t)=>{const n=(t.level||"").toLowerCase();if(n&&"auto"!==n&&!EFFORT_LEVELS.includes(n))return note(e,`Unknown effort level "${t.level}". Use ${EFFORT_LEVELS.join(", ")}.`),e.render(),!0;if(!n)return e.openOverlay({type:"effort",sel:Math.max(0,EFFORT_LEVELS.indexOf(e.ctx.effort||"high"))}),!0;const o="auto"===n?"high":n;return e.ctx.effort=o,e.saveConfig({effort:o}),note(e,"auto"===n?"effort: auto is retired — high is the default, and it is what this session now sends":`Effort level: ${o} — the pool sizes this turn's token budget from it`),e.render(),!0}},{name:"exit",aliases:["quit"],hint:"",category:"session",desc:"Exit the CLI",handler:async()=>!1},{name:"export",args:["format","target"],hint:"[markdown|json] [file|clipboard]",category:"data",desc:"Export the current conversation to a file or clipboard",handler:async(e,t)=>{const n=(t.format||"markdown").toLowerCase(),o=(t.target||"file").toLowerCase();if(!["markdown","md","json"].includes(n)||!["file","clipboard"].includes(o))return note(e,"Usage: /export [markdown|json] [file|clipboard]"),e.render(),!0;const r="json"===n,s=r?transcriptToJSON(e.transcript):transcriptToMarkdown(e.transcript);if("clipboard"===o){const t=copyToClipboard(s);note(e,t.ok?`Exported conversation (${r?"json":"markdown"}) to the clipboard.`:"Clipboard unavailable; nothing copied.")}else try{const t=writeExportFile(s,r?"json":"md",e.ctx.cwd||process.cwd());note(e,`Exported conversation to ${t}`)}catch(t){note(e,`/export: ${t.message}`)}return e.render(),!0}},{name:"help",aliases:["?","h"],hint:"",category:"support",desc:"Show help",handler:async e=>(panel(e,panels.buildHelp(visibleCommands(),e.ctx)),e.render(),!0)},{name:"init",args:["file"],hint:"[file]",category:"workspace",desc:"Create an AEGIS.md file in the project",handler:async(e,t)=>{const n=(t.file||"AEGIS.md").trim(),o=e.ctx.cwd||process.cwd(),r=path.resolve(o,n),s=o.endsWith(path.sep)?o:o+path.sep;if(r!==o&&!r.startsWith(s))return note(e,`/init: refusing to write outside the project directory (${r}).`),e.render(),!0;if(fs.existsSync(r))return note(e,`${n} already exists — not overwriting.`),e.render(),!0;const a=sniffProject(o);try{fs.writeFileSync(r,buildAegisMd(a)+"\n")}catch(t){return note(e,`/init: ${t.message}`),e.render(),!0}return note(e,`Created ${r} (${a.lang})`),fs.existsSync(path.join(o,"node_modules"))&&!fs.existsSync(path.join(o,".gitignore"))&&tip(e,'Add "node_modules/" to a .gitignore before committing.'),e.render(),!0}},{name:"login",aliases:["signin"],args:["value"],hint:"[<api_key>]",category:"auth",desc:"Save your AEGIS API key",handler:async(e,t)=>{const n=String(t.value||t._rest||"").trim();return await applyAccountKey(e,n,{label:"AEGIS API key"}),e.render(),!0}},{name:"logout",args:[],hint:"",category:"auth",desc:"Remove the saved AEGIS API key",handler:async e=>{const t=e.forgetApiKey();return done(e,t.cleared?`key removed from ${t.path}`:"there was no saved key to remove"),credentials.legacyKeyOnDisk()&&note(e,`a copy is still in ${configPath()} (another AEGIS CLI wrote it) — delete its "aegiscloud" block too`),e.render(),!0}},{name:"model",aliases:["m"],args:["sub"],hint:"[id|-]",category:"model",desc:'Switch AI model — pin an id ("-" clears it)',handler:async(e,t)=>{const n=(t.sub||"").trim(),o=e.ctx&&e.ctx.modelClass||"aegis",r="byok"===o;if(!n){note(e,`model: ${e.ctx.model||"server default"}`);const t=await mergedPickerModels(e);return t.length?(t.some((e=>"aegis"===e.cls||"byok"===e.cls))||note(e,e.state().online?"Could not read the AEGIS Cloud catalog (offline, or the server refused it) — showing Claude Code Pro only; /models retries.":`No AEGIS API key set, so the AEGIS Cloud catalog cannot be read (free key: ${signupUrl("model_blocked")}) — showing Claude Code Pro only.`),e.ctx.model&&!t.some((t=>t.id===e.ctx.model))&&note(e,r?`pinned model "${e.ctx.model}" is not one this machine can relay — pick from the list below.`:`pinned model "${e.ctx.model}" is not in the catalog — the pool will answer with its own default; pick one below.`),note(e,"/model <id> pins one for this session; picking a direct-provider row prompts for its key if this machine has none saved."),e.openOverlay({type:"model",items:t,sel:0,current:e.ctx.model,cls:o}),!0):(note(e,e.state().online?"Could not read the model catalog (offline, or the server refused it) — /models retries.":`No API key set, so the model catalog cannot be read — export AEGIS_API_KEY (free key: ${signupUrl("model_blocked")}), then retry /model.`),e.render(),!0)}if("list"===n){const t=await mergedPickerModels(e);return t.length?panel(e,panels.buildModelList(e.ctx.model,t,e.ctx)):note(e,"No pinnable models advertised — /models lists the server's ids."),e.render(),!0}if("-"===n)return e.ctx.model=null,e.saveConfig({model:null,currentModelId:null}),note(e,r?"Model pin cleared. The byok class has no server default — the next turn needs <provider>:<model>, so pin one from /models before sending.":"Model pin cleared — the server will choose."),e.render(),!0;e.ctx.model=n,e.saveConfig({model:n,currentModelId:n}),note(e,`Pinned model: ${n}`);const s=await loadModels(e)||[];return s.length&&!s.some((e=>e.id===n))&&note(e,r?`"${n}" is not one this machine can relay — a byok id is "<provider>:<model>", and the relay will refuse anything else. /models lists the real ids.`:`"${n}" is not in the AEGIS Cloud catalog — the pool will answer with its own default. /models lists the real ids.`),e.render(),!0}},{name:"radio",hint:"",category:"fun",desc:"Listen to AEGIS FM lo-fi radio",handler:async e=>(note(e,"Opening AEGIS FM lo-fi radio in your browser…"),openUrl(URLS.radio)||note(e,`AEGIS FM: ${URLS.radio}`),e.render(),!0)},{name:"recap",hint:"",category:"session",desc:"Generate a one-line session recap now",handler:async e=>{if(!e.transcript.some((e=>"user"===e.role||"assistant"===e.role)))return note(e,"No exchanges yet — send a prompt first."),e.render(),!0;note(e,"Recapping session…"),e.render();const t=await e.withWorking((t=>recapLine(e.transcript,{callModel:(t,n)=>e.ask(t,n).then((e=>e.text)),model:e.ctx.model,signal:t})));return null===t?(note(e,"Recap cancelled."),e.render(),!0):(e.ctx.lastRecap={sessionId:e.sessionId,ts:(new Date).toISOString(),text:t},e.saveConfig({lastRecap:e.ctx.lastRecap}),note(e,`Session recap: ${t}`),e.render(),!0)}},{name:"resume",hint:"",category:"session",desc:"Switch to a previous session",handler:async e=>{const t=readResumeList();return t.length?(e.openOverlay({type:"resume",items:t,sel:0}),!0):(note(e,"No previous sessions found — conversations from this host and from AEGIS Desktop both land in ~/.aegiscode/sessions.json"),e.render(),!0)}},{name:"rewind",args:["n"],hint:"[N]",category:"session",desc:"Revert the conversation to a checkpoint",handler:async(e,t)=>{const n=listCheckpoints(e.sessionId);if(!t.n)return n.length?(panel(e,panels.buildRewindList(n,e.ctx)),e.render(),!0):(note(e,"No checkpoints yet — snapshots are taken after each exchange."),e.render(),!0);const o=parseInt(t.n,10);if(Number.isNaN(o)||o<0||o>=n.length)return note(e,`Unknown checkpoint ${t.n}. /rewind shows the list (indices 0..${Math.max(0,n.length-1)}).`),e.render(),!0;snapshotCheckpoint(e.sessionId,e.transcript);const r=loadCheckpoint(e.sessionId,o);if(!r)return note(e,"Checkpoint unreadable — nothing restored."),e.render(),!0;e.transcript.length=0;for(const t of r)e.transcript.push(t);return note(e,`Rewound to checkpoint ${o} (${r.length} messages). /rewind N again to undo.`),e.render(),!0}},{name:"agents",aliases:["sessions"],args:["role","task"],hint:"[role] [task]",category:"session",desc:"Show the agents panel, or run a sub-agent role preset — /agents <role> <task>",handler:async(e,t)=>{const n=(t.role||"").trim().toLowerCase();if(n){const o=(t._rest||"").trim().replace(/^\S+\s*/,"").trim();if(!o)return note(e,`Usage: /agents <role> <task> — roles: ${agentRoles().join(", ")}`),e.render(),!0;if(!AGENT_PRESETS[n])return note(e,`Unknown agent role "${n}". Roles: ${agentRoles().join(", ")}`),e.render(),!0;const r=composeAgentPrompt(n,o);return e.runPrompt?(await e.runPrompt(r),!0):(note(e,`Composed ${n} prompt (${r.length} chars) — run in the TUI to send it.`),e.render(),!0)}return panel(e,panels.buildAgents(e.state(),e.ctx)),e.render(),!0}},{name:"status",aliases:["st"],hint:"",category:"session",desc:"Show account and session status",handler:async e=>(await e.runTool("aegis_status",{}),panel(e,panels.buildStatus(e.state(),Object.assign({},e.ctx,{caps:describe()}))),e.render(),!0)},{name:"teleport",hint:"",category:"session",desc:"Resume a session from aegiscloud.org",handler:async e=>(note(e,"Teleport requires an AEGIS cloud account with sessions. Sign in with `aegis login`, then run aegiscloud.org/teleport."),e.render(),!0)},{name:"theme",aliases:["t"],args:["mode"],hint:"[dark|light]",category:"model",desc:"Change the color theme",handler:async(e,t)=>{const n=(t.mode||"").toLowerCase();if("dark"===n||"light"===n){const t="light"===n?2:1;screens.applyTheme(e.ctx,t)}else await e.showThemePicker();if(e.saveConfig({themeIndex:e.ctx.themeIndex}),note(e,"Theme: "+(e.ctx.light?"light":"dark")),themeContradicts(e.ctx.themeIndex)){const t=caps().background;note(e,`warning: this ${t} terminal is not what "${THEME_TABLE[e.ctx.themeIndex].name}" is drawn for — body text may be unreadable.`),note(e,` /terminal background ${t} pins the palette to this terminal, or /terminal background ${"dark"===t?"light":"dark"} if it reads you wrong.`)}return e.render(),!0}},{name:"terminal",aliases:["tty"],args:["mode","mode2"],hint:"[ascii|unicode|color|no-color|background <dark|light>|probe|star <native|narrow>|width <cols>|auto|status]",category:"model",desc:"Show or override how this terminal is drawn (mark, colour, width)",handler:async(e,t)=>{const n=(t.mode||"").toLowerCase(),o=null!=t.mode2?String(t.mode2).trim():"";if(""===n||"status"===n)return panel(e,panels.buildTerminalCaps(describe(),{pinned:!!caps().pinned})),e.render(),!0;const r=caps(),s={glyphs:r.glyphs,face:r.face,star:r.star,depth:r.depth,vt:r.vt,wideRunes:r.wideRunes,background:r.background,backgroundKnown:r.backgroundKnown,reasons:Object.assign({},r.reasons)};if("auto"===n)return resetCaps(),note(e,"Terminal: auto — capabilities re-probed from the environment."),e.render(),!0;if("probe"===n){const t=await probeTerminalBackground();return screens.applyTheme(e.ctx,e.ctx.themeIndex),note(e,t.known?`Terminal: background ${t.background} (${t.reason}) — /theme auto follows it.`:`Terminal: no answer to the background query (${t.reason}).`),note(e," /terminal background dark|light pins it without asking."),panel(e,panels.buildTerminalCaps(describe(),{pinned:!!caps().pinned})),e.render(),!0}if("ascii"===n||"unicode"===n)s.glyphs="ascii"===n?"ascii":"unicode",s.face="ascii"===n?"edges":"native",s.star="ascii"===n?"narrow":"native",s.reasons&&(s.reasons.glyphs=`/terminal ${n}`);else if("color"===n||"no-color"===n||"nocolor"===n)s.depth="color"===n?24:0,s.reasons&&(s.reasons.depth=`/terminal ${n}`);else{if("star"!==n){if("background"===n||"bg"===n){const t=o.toLowerCase();return["dark","light"].includes(t)?(s.background=t,s.backgroundKnown=!0,s.reasons&&(s.reasons.background=`/terminal background ${t}`),setCaps(Object.assign({},s)),screens.applyTheme(e.ctx,e.ctx.themeIndex),note(e,`Terminal: background pinned to ${t} — /theme auto follows it.`),panel(e,panels.buildTerminalCaps(describe(),{pinned:!!caps().pinned})),e.render(),!0):(note(e,"Usage: /terminal background <dark|light>"),e.render(),!0)}if("width"===n){const t=Number(o);return!Number.isFinite(t)||t<20?(note(e,"Usage: /terminal width <cols> (>= 20)"),e.render(),!0):(setCaps(Object.assign({},s,{cols:Math.round(t)})),note(e,`Terminal: width pinned to ${Math.round(t)} columns.`),panel(e,panels.buildTerminalCaps(describe(),{pinned:!!caps().pinned})),e.render(),!0)}return note(e,"Usage: /terminal [ascii|unicode|color|no-color|background <dark|light>|probe|star <native|narrow>|width <cols>|auto|status]"),e.render(),!0}{const t=o.toLowerCase();if(!["native","narrow"].includes(t))return note(e,"Usage: /terminal star <native|narrow>"),e.render(),!0;s.star=t,s.reasons&&(s.reasons.star=`/terminal star ${t}`)}}return setCaps(s),panel(e,panels.buildTerminalCaps(describe(),{pinned:!!caps().pinned})),note(e,"Terminal updated — the current viewport is redrawn; text already scrolled past keeps its old glyphs."),e.render(),!0}},{name:"version",aliases:["v"],hint:"",category:"session",desc:"Show version",handler:async e=>(note(e,`aegiscode v${VERSION}`),e.render(),!0)},{name:"doctor",args:["action"],hint:"[fix|system]",category:"support",desc:"Run diagnostic checks on this environment",handler:async(e,t)=>{const n=(t&&t.action||"").toLowerCase();if(n&&"fix"!==n&&"system"!==n)return note(e,'Usage: /doctor [fix|system] — "fix" re-tightens the data dir to 0700/0600, "system" checks the machine itself'),e.render(),!0;const o=[],r=(e,t,n)=>o.push([t,e,n]);r("Node",!0,process.version),r("CWD",fs.existsSync(process.cwd()),process.cwd());let s=!1;try{execSync("git rev-parse --git-dir",{cwd:process.cwd(),stdio:["ignore","ignore","ignore"],timeout:4e3}),s=!0}catch{}r("git repo",s,s?"inside a work tree":"not a git repository");const a=credentials.keyStatus();r("AEGIS key",a.configured,a.configured?`${maskKey(a.key)} via ${credentials.sourceLabel(a.source)}`:`not set — ${credentials.HOW_TO_SET} (free key: ${signupUrl("doctor")})`),r("credentials",!0,`${a.path}${a.fileMode?` (${a.fileMode})`:""}`),r("cloud memory",a.memoryToken,a.memoryToken?"token held":"no memory token — /cloud activate"),a.legacyPlaintext&&r("plaintext key",!1,`a copy also sits in ${configPath()} (another AEGIS CLI) — /key re-saves it to ${a.path}`),r("config path",!0,configPath());const i=aegisDir();let d=null;"fix"===n&&(d=repairExposure(i));const l=auditExposure(i);if(l.exists)if(l.modesMeaningful){const e=l.exposed.slice(0,4).map((e=>`${e.rel} ${e.mode}`)).join(", ");r("data dir",0===l.exposed.length,0===l.exposed.length?`${i} (${l.rootMode}, all private)`:`${i} (${l.rootMode}) — ${l.exposed.length} path(s) group/world-accessible: ${e}${l.exposed.length>4?", …":""} — run /doctor fix`)}else r("data dir",!0,`${i} (${l.total} path(s)) — this filesystem has no POSIX permission bits; access is governed by the profile directory's own ACL`);else r("data dir",!0,`${i} (not created yet)`);if(d&&!d.modesMeaningful)r("repair",!0,"nothing to tighten — this filesystem has no POSIX permission bits");else if(d){const e=d.fixed.slice(0,3).map((e=>`${e.rel} ${e.from}→${e.to}`)).join(", ");r("repair",0===d.remaining.length,0===d.remaining.length?d.fixed.length?`tightened ${d.fixed.length} path(s) — ${e}${d.fixed.length>3?", …":""}`:"already private, nothing to tighten":`${d.remaining.length} path(s) still exposed — `+d.failed.map((e=>`${e.rel}: ${e.reason}`)).join(", "))}let c=null;if("system"===n){const e=sysdiag.collect();if(e.ok){c=sysdiag.assess(e.data);for(const e of c.findings)r(`${e.title} (${e.severity})`,!1,`${e.detail} → ${e.remedyText}`);for(const e of c.clean)r(e.title,!0,e.detail);for(const e of c.unassessed)r(`${e.title} (unassessed)`,!1,e.reason)}else r("machine checks",!1,"not-windows"===e.reason?"not available on this platform — the machine audit is Windows-only (cli/src/sysdiag.js)":`could not run: ${e.reason}`)}const u=[[span(C.gold+BOLD,"Doctor"),span(BOLD_OFF,"")],[span(C.gray,"─".repeat(30))]];for(const[e,t,n]of o)u.push([span(e?C.green:C.coral," "+(e?"✔":"⚠")),span(C.white,` ${t}: `),span(C.gray,String(n))]);if(c&&c.findings.length){const e=c.summary;u.push([span(C.gold," Remedy"),span(C.gray,` — ${e.findings} finding(s) across ${e.assessed}/${e.total} measured checks.`)]),u.push([span(C.gray," Run in an ELEVATED PowerShell. AEGIS diagnoses this; it does not change your machine.")]);for(const e of sysdiag.remedyScript().split("\n"))u.push([span(C.gray,` ${e}`)])}return panel(e,u),e.render(),!0}},{name:"upgrade",args:["action"],hint:"[check|apply]",category:"support",desc:"Check for a newer published version (apply: install it now)",handler:async(e,t)=>{const n=String(t&&t.action||"check").toLowerCase();if(!["check","apply"].includes(n))return note(e,"Usage: /upgrade [check|apply]"),e.render(),!0;const o=installMethod();note(e,"Checking the npm registry…"),e.render();const r=e&&e.withWorking?t=>e.withWorking(t):e=>e(),s=e.ctx&&e.ctx.demo?null:await r((()=>Promise.resolve(latestPublishedVersion()))),a=upgradeAdvice({latest:s,method:o});if(panel(e,a.lines.map((e=>[span(C.white,e)]))),e.render(),"apply"!==n)return!0;if(!a.plan||!a.plan.apply)return note(e,a.plan?`Nothing to install: ${a.plan.instruction}`:"Nothing to install."),e.render(),!0;note(e,`Running: ${a.plan.instruction}`),e.render();const i=applyUpgrade({method:o,latest:s,current:a.plan.current});if(i.ok&&!i.skipped){if(note(e,`Installed ${a.plan.latest}. Restart aegiscode to use it.`),i.output)for(const t of i.output.split("\n").slice(-6))note(e,` ${t}`)}else i.skipped?note(e,`Not applied: ${i.instruction}`):(note(e,`Upgrade failed: ${i.error}`),note(e,`Run it yourself: ${i.command}`));return e.render(),!0}},{name:"vim",args:["mode"],hint:"[on|off]",category:"model",desc:"Toggle vim keymap",handler:async(e,t)=>{const n=(t.mode||"").toLowerCase();if(n&&!["on","off"].includes(n))return note(e,"Usage: /vim [on|off]"),e.render(),!0;const o="on"===n||"off"!==n&&!e.ctx.vim;return e.ctx.vim=o,e.saveConfig({vim:o}),note(e,"Vim keymap: "+(o?"on":"off")),e.render(),!0}},{name:"permissions",args:["mode","pattern"],hint:'[allow|deny|ask "<pattern>" | default <ask|allow|deny> | clear]',category:"model",desc:"Set permissions for tool use",handler:async(e,t)=>{const n=loadPermissions(),o=(t.mode||"").toLowerCase(),r=t.pattern;if(!o)return panel(e,panels.buildPermissions({...n,_path:permissionsPath()},null,e.ctx)),e.render(),!0;if("clear"===o)return setPermissionDefaultMode(DEFAULT_PERMISSIONS.defaultMode),savePermissions({...DEFAULT_PERMISSIONS,allow:[],deny:[],ask:[]}),note(e,"Permissions reset to defaults (no rules)."),e.render(),!0;if("default"===o&&["ask","allow","deny"].includes(r))return setPermissionDefaultMode(r),note(e,`Default permission mode: ${r}`),e.render(),!0;if(["allow","deny","ask"].includes(o)&&r){const{added:t,rules:s}=addPermissionRule(o,r,n);return savePermissions(s),note(e,t?`Added ${o} rule: ${r}`:`Rule already present: ${r}`),e.render(),!0}return note(e,'Usage: /permissions [allow|deny|ask "<pattern>" | default <ask|allow|deny> | clear]'),e.render(),!0}},{name:"hooks",args:["sub"],hint:"[status|list|install]",category:"model",desc:"View hooks configuration status, list configured hooks, or install this repo's guard hooks",handler:async(e,t)=>{const n=(t.sub||"").toLowerCase();if("install"===n){const n=/--dry-run|\bdry-?run\b/.test(String(t._rest||"")),o=hooksLib.installRepoHooks({cwd:process.cwd(),dryRun:n});if(o.ok)if(n){note(e,`would install the guard hooks in ${o.status.repo}`);for(const t of o.actions)note(e,` ${t}`);o.status.installed&&note(e,"core.hooksPath is already .githooks — nothing to change")}else if(o.changed){done(e,"installed the guard hooks — core.hooksPath = .githooks (verified)");for(const t of o.actions)note(e,` ${t}`)}else done(e,"guard hooks already installed (core.hooksPath = .githooks)");else if(note(e,o.error),o.actions.length)for(const t of o.actions)note(e,` ${t}`);return o.ok&&note(e,o.status.execNote),e.render(),!0}const{hooks:o,from:r}=readHooks();return"list"===n?(panel(e,panels.buildHooksList({hooks:o},e.ctx)),e.render(),!0):""===n||"status"===n?(panel(e,panels.buildHooksStatus({...hookStats(o),fromPaths:r},e.ctx)),e.render(),!0):(note(e,`unknown subcommand: ${t.sub}`),note(e,"available: status, list, install [--dry-run]"),e.render(),!0)}},{name:"credentials",hint:"",category:"model",desc:"Show where credentials are stored",handler:async e=>{const t=path.join(os.homedir(),".claude",".credentials.json"),n=t.replace(os.homedir(),"~");return fs.existsSync(t)?note(e,`Credentials live in ${n} (managed by the Claude Code CLI). aegiscode reads them but never writes them.`):note(e,"No credential file found. The Claude Code CLI manages auth (OS keychain or ~/.claude/.credentials.json)."),e.render(),!0}},{name:"install-github-app",hint:"",category:"model",desc:"Install the GitHub App for PR workflows",handler:async e=>(note(e,"The GitHub App is installed through the Claude Code CLI: run `claude --install-github-app` once."),e.render(),!0)},{name:"troubleshooting",hint:"",category:"support",desc:"Troubleshoot common issues",handler:async e=>(panel(e,panels.buildTroubleshooting(e.state(),e.ctx)),e.render(),!0)},{name:"feedback",hint:"",category:"support",desc:"Send feedback to the AEGIS team",handler:async e=>(note(e,"Opening the feedback form…"),openUrl(URLS.feedback)||note(e,`Feedback: ${URLS.feedback}`),e.render(),!0)},{name:"bug",hint:"",category:"support",desc:"Report a bug (opens a GitHub issue)",handler:async e=>(note(e,`Opening a GitHub issue… (aegiscode v${VERSION}, ${process.version}, ${os.platform()})`),openUrl(URLS.issues)||note(e,`Issues: ${URLS.issues}`),e.render(),!0)},{name:"issue",aliases:["bugs"],hint:"",category:"support",desc:"Report an issue",handler:async e=>(note(e,"Opening a GitHub issue…"),openUrl(URLS.issues)||note(e,`Issues: ${URLS.issues}`),e.render(),!0)},{name:"onboarding",hint:"",category:"support",desc:"Show getting-started tips",handler:async e=>(panel(e,panels.buildOnboarding(e.state(),e.ctx)),e.render(),!0)},{name:"shell-completion",hint:"",category:"support",desc:"Set up shell completion",handler:async e=>(panel(e,panels.buildShellCompletion(e.state(),e.ctx)),e.render(),!0)},{name:"terminal-setup",hint:"",category:"support",desc:"Check and fix terminal setup",handler:async e=>(panel(e,panels.buildTerminalSetup(e.state(),e.ctx)),e.render(),!0)},{name:"pr-comments",hint:"",category:"support",desc:"Review and reply to pull request comments",handler:async e=>(note(e,"PR comments need GitHub auth. Run /prs to check connectivity, then use the `gh` CLI or the GitHub web UI."),e.render(),!0)},{name:"prs",hint:"",category:"support",desc:"List pull requests in this repo",handler:async e=>{try{const t=execSync("gh pr list --limit 8",{encoding:"utf8",timeout:15e3,stdio:["ignore","pipe","ignore"]});panel(e,panels.buildPRs(t.toString(),e.ctx))}catch{note(e,"gh not authenticated (or not installed) — run `gh auth login` first.")}return e.render(),!0}},{name:"review",hint:"",category:"support",desc:"Review a pull request",handler:async e=>(note(e,"/review needs GitHub auth via gh. Run /prs to list open PRs, then open one in the browser."),e.render(),!0)},{name:"benchmark",hint:"",category:"support",desc:"Run in-app micro-benchmarks",handler:async e=>{const t=e=>{const t=process.hrtime.bigint();return e(),(Number(process.hrtime.bigint()-t)/1e6).toFixed(2)},n=[["2,000 span() calls",t((()=>{for(let e=0;e<2e3;e++)span(C.white,"x")}))],["estimateTokens × 20 (500 chars)",t((()=>{for(let e=0;e<20;e++)estimateTokens("x".repeat(500))}))]];return markdownModule&&"function"==typeof markdownModule.renderMarkdown&&n.push(["renderMarkdown × 200",t((()=>{for(let e=0;e<200;e++)markdownModule.renderMarkdown("# Heading\n\nSome **bold** and `code` with a [link](https://x.test).\n\n- a\n- b\n- c\n",80)}))]),panel(e,panels.buildBenchmark(n,e.ctx)),e.render(),!0}},{name:"waifu",hint:"",category:"fun",desc:"Summon a waifu",handler:async e=>(panel(e,panels.buildWaifu(e.ctx)),e.render(),!0)},{name:"new",aliases:["start"],hint:"",category:"session",desc:"Start a new session (clears the transcript, fresh session id)",handler:async e=>{e.transcript.length=0,"function"==typeof e.clearConversationMemory&&e.clearConversationMemory();const t="aegis-"+Math.random().toString(36).slice(2,10);return e.sessionId=t,e.ctx.sessionId=t,note(e,`New session started (${t}) — earlier context cleared.`),e.render(),!0}},{name:"tokens",aliases:["tok"],hint:"",category:"data",desc:"Show token usage breakdown and estimated spend",handler:async e=>{const t=sessionAccounting(e.transcript,e.ctx.model);return panel(e,panels.buildTokens({...e.state(),contextWindow:t.contextWindow,costEur:t.cost},e.ctx)),e.render(),!0}},{name:"skills",aliases:["sk"],args:["sub"],hint:"[name|refresh]",category:"session",desc:"List skills (SKILL.md in the standard skill dirs)",handler:async(e,t)=>{const n=(t.sub||"").trim().toLowerCase(),o=scanSkills(),r=[path.join(os.homedir(),".aegis","skills"),path.join(process.cwd(),".aegis","skills"),path.join(os.homedir(),".aegiscode","skills"),path.join(process.cwd(),".aegiscode","skills"),path.join(os.homedir(),".claude","skills")].map((e=>e.replace(os.homedir(),"~")));if("refresh"===n||"reload"===n)return note(e,`Skills refreshed — ${o.length} found (${r.length} dirs scanned).`),e.render(),!0;if(n){const t=o.find((e=>e.name===n));return t?(panel(e,panels.buildSkillDetail(t,e.ctx)),e.render(),!0):(note(e,`Unknown skill "${n}". /skills lists what exists on disk.`),e.render(),!0)}return panel(e,panels.buildSkills(o,r,e.ctx)),e.render(),!0}},{name:"thinking",args:["mode"],hint:"[on|off]",category:"model",desc:"Toggle thinking blocks expanded/collapsed",handler:async(e,t)=>{const n=(t.mode||"").toLowerCase();if(n&&!["on","off"].includes(n))return note(e,"Usage: /thinking [on|off]"),e.render(),!0;const o="on"===n||"off"!==n&&!(!0===e.ctx.thinking);return e.ctx.thinking=o,e.saveConfig({thinking:o}),note(e,"Thinking blocks: "+(o?"expanded":"collapsed")),e.render(),!0}},{name:"mcp",args:["sub","name","command"],hint:"[add <name> <command> [args…]|remove <name>|<name>]",category:"model",desc:"Show MCP server configuration",handler:async(e,t)=>{const n=loadConfig().mcpServers||{},o=(t.sub||"").toLowerCase();if("add"===o){const o=(t.name||"").trim(),r=(t.command||"").trim();if(!o||!r)return note(e,'Usage: /mcp add <name> "<command with args>"'),e.render(),!0;const s=r.split(/\s+/).filter(Boolean);return updateConfig({mcpServers:{...n,[o]:{command:s[0],args:s.slice(1)}}}),note(e,`Added MCP server "${o}" (${s[0]}). Configuration only — this build has no MCP runtime.`),e.render(),!0}if("remove"===o||"rm"===o){const o=(t.name||"").trim();if(!o)return note(e,"Usage: /mcp remove <name>"),e.render(),!0;if(!n[o])return note(e,`No MCP server "${o}". /mcp lists the configured ones.`),e.render(),!0;const r={...n};return delete r[o],updateConfig({mcpServers:r}),note(e,`Removed MCP server "${o}".`),e.render(),!0}if(o&&n[o]){const t=n[o];return panel(e,[[span(C.gold,`MCP server: ${o}`)],[span(C.gray,"─".repeat(30))],[span(C.white,` command: ${`${t.command||""} ${(t.args||[]).join(" ")}`.trim()}`)],[span("","")],[span(C.gray,"Configuration only — this build has no MCP runtime.")]]),e.render(),!0}return panel(e,panels.buildMcp(n,[configPath(),permissionsPath()],e.ctx)),e.render(),!0}},{name:"memory",aliases:["memories"],hint:"",category:"model",desc:"List the most recent AEGIS cloud-memory entries",tool:"aegis_memory_list",build:()=>({})},{name:"memory-deep",aliases:["recall-deep"],args:["mode"],hint:"[on|off]",category:"model",desc:"Toggle DEEP recall for this session — brain corrections + cached answers (metered: one embedding per turn)",handler:async(e,t)=>{const n=(t.mode||"").toLowerCase();if(n&&!["on","off"].includes(n))return note(e,"Usage: /memory-deep [on|off]"),e.render(),!0;const o="on"===n||"off"!==n&&!(!0===e.ctx.recallDeep);return e.ctx.recallDeep=o,note(e,`Deep recall: ${o?"on — brain corrections + cached answers, one embedding per turn":"off (only the cheap recall read)"}${o?" · this session only":""}`),e.render(),!0}},{name:"confirm",aliases:["confirmations"],args:["mode"],hint:"[on|off]",category:"model",desc:"Toggle tool-call confirmation prompts",handler:async(e,t)=>{const n=(t.mode||"").toLowerCase();if(n&&!["on","off"].includes(n))return note(e,"Usage: /confirm [on|off]"),e.render(),!0;const o="on"===n||"off"!==n&&!confirmPosture().enabled;return setConfirmPosture(o),note(e,`Confirmation prompts: ${o?"on":"off"} (default permission mode: ${o?"ask":"allow"})`),e.render(),!0}},{name:"automode",aliases:["yolo"],args:["mode"],hint:"[on|off]",category:"model",desc:"Toggle automode — auto-approve all tool executions",handler:async(e,t)=>{const n=(t.mode||"").toLowerCase();if(n&&!["on","off"].includes(n))return note(e,"Usage: /automode [on|off]"),e.render(),!0;const o="on"===n||"off"!==n&&confirmPosture().enabled;return setConfirmPosture(!o),"function"==typeof e.setAutoRounds&&e.setAutoRounds(o),o?panel(e,panels.buildAutomode(e.state(),e.ctx)):note(e,"automode off — confirmations restored."),e.render(),!0}},{name:"multiyolo",aliases:["multiauto"],args:["task"],hint:"<task>",category:"session",desc:"Multi-agent orchestration with automode — /multiyolo <task>",handler:async(e,t)=>{const n=(t._rest||t.task||"").trim();return n?runMultiCommand(e,n,{yolo:!0}):(note(e,"Usage: /multiyolo <task>"),e.render(),!0)}},{name:"router",args:["sub","tier","modelId"],hint:"[on|off|set <tier> <modelId>|stats]",category:"model",desc:"Show or manage the model router config",handler:async(e,t)=>{const n=loadConfig(),o=n.autoRouter||{enabled:!1,tiers:{}},r=(t.sub||"").toLowerCase(),s=e=>updateConfig({autoRouter:e});if("on"===r)return s({...o,enabled:!0}),note(e,"Auto-router: on."),e.render(),!0;if("off"===r)return s({...o,enabled:!1}),note(e,"Auto-router: off."),e.render(),!0;if("set"===r){const n=(t.tier||"").toLowerCase(),r=(t.modelId||"").trim();return["simple","medium","complex"].includes(n)&&r?(s({...o,tiers:{...o.tiers||{},[n]:r}}),note(e,`Auto-router: ${n} -> ${r}`),e.render(),!0):(note(e,"Usage: /router set <simple|medium|complex> <modelId>"),e.render(),!0)}return"stats"===r?(panel(e,[[span(C.gold+BOLD,"Router stats"),span(BOLD_OFF,"")],[span(C.gray,"─".repeat(30))],[span(C.gray,"No learned outcomes yet — this build does not auto-route.")],[span(C.gray,"Tiers: simple/medium/complex via /router set.")]]),e.render(),!0):(panel(e,panels.buildRouter(n,e.ctx)),e.render(),!0)}},{name:"multi",args:["task","mode"],hint:"<task> [run]",category:"session",desc:'Compose a multi-agent task (add "run" to execute)',handler:async(e,t)=>{let n=(t._rest||t.task||"").trim(),o=(t.mode||"").toLowerCase();return"run"!==o&&/\s+run$/i.test(n)&&(o="run",n=n.replace(/\s+run$/i,"").trim()),n?"run"!==o?(panel(e,panels.buildAegisMulti(n,e.ctx)),e.render(),!0):runMultiCommand(e,n):(note(e,"Usage: /multi <task> [run]"),e.render(),!0)}},{name:"research",args:["question"],hint:"<question>",category:"session",desc:"Research a topic with a multi-perspective council prompt",handler:async(e,t)=>{const n=(t._rest||t.question||"").trim();if(!n)return note(e,"Usage: /research <question>"),e.render(),!0;const o=composeResearchPrompt(n,process.cwd());return e.runPrompt?(await e.runPrompt(o),!0):(note(e,`Composed research prompt (${o.length} chars) — run in the TUI to send it.`),e.render(),!0)}},{name:"debate",aliases:["db"],args:["topic"],hint:"<topic>",category:"session",desc:"Run a structured debate on the current model",handler:async(e,t)=>{const n=(t._rest||t.topic||"").trim();if(!n)return note(e,"Usage: /debate <topic>"),e.render(),!0;const o=composeDebatePrompt(n,e.ctx.model||"");return e.runPrompt?(await e.runPrompt(o),!0):(note(e,`Composed debate prompt (${o.length} chars) — run in the TUI to send it.`),e.render(),!0)}},{name:"billing",aliases:["balance","spend"],hint:"",category:"support",desc:"Show billing info — token-bank balance and recent spend",handler:async e=>{await e.runTool("aegis_balance",{});const t=await e.refreshSpend(),n=e.state();return panel(e,panels.buildBilling({...n,balance:t&&null!=t.balance?t.balance:n.balance,payment:await billingPayment(e)},e.ctx)),e.render(),!0}},{name:"topup",aliases:["fund"],args:["amount"],hint:"[EUR]",category:"support",desc:"Top up the token bank — opens the payment page and confirms the credit here",handler:async(e,t)=>{const n=String(t.amount||t._rest||"").trim();let o;try{o=require(require("./sharedpaths.js").resolveShared("client/topup.js"))}catch(t){return note(e,`top-up is unavailable in this build — ${t.message}`),e.render(),!0}const r=o.parseTopupAmount(n);if(!r.ok)return note(e,r.message),e.render(),!0;if(!e.client.apiKey)return note(e,`no AEGIS key on this machine — ${credentials.HOW_TO_SET}, then /topup ${r.amount}`),e.render(),!0;const s=e.withWorking?await e.withWorking((()=>o.startTopup(e.client,r.amount))):await o.startTopup(e.client,r.amount);if(!s.ok)return note(e,`the top-up could not be started — ${s.message}`),s.hint&&note(e,s.hint),e.render(),!0;note(e,`opening the payment page — ${r.amount} EUR`),note(e,s.url);const a=Math.round(o.TOPUP_POLL_MS*o.TOPUP_POLL_TRIES/1e3);note(e,`watching this account's bank for up to ${a}s; the credit is confirmed here, not in the browser`),e.render(),openUrl(s.url)||note(e,"could not open a browser — use the URL above");const i=o.createCreditWatch(e.client);let d=null,l=!1;const c=()=>{l=!0,d&&clearTimeout(d)},u=async()=>{if(l)return;const t=await i.tick();return"credited"===t.state?(c(),note(e,`credit confirmed — the bank is now ${t.amount.toFixed(2)} EUR`),void e.render()):"expired"===t.state?(c(),note(e,"no credit observed within the watch window — if you completed the payment it may still land; /billing shows the bank"),void e.render()):(d=setTimeout(u,o.TOPUP_POLL_MS),void(d&&"function"==typeof d.unref&&d.unref()))};return d=setTimeout(u,o.TOPUP_POLL_MS),d&&"function"==typeof d.unref&&d.unref(),!0}},{name:"cloud",args:["sub","value"],hint:"[status|key <api_key>|activate|deactivate|memory [on|off]|sync [on|off|now]]",category:"support",desc:"Show and control ÆGIS cloud sync",handler:async(e,t)=>{const n=(t.sub||"").toLowerCase(),o=(t.value||t._rest||"").trim();if("key"===n)return await applyAccountKey(e,o),e.render(),!0;if("activate"===n){if(!e.client.apiKey)return note(e,`no key — ${credentials.HOW_TO_SET}`),e.render(),!0;try{const t=await e.withWorking((()=>e.client.memoryActivate())),n=await e.client.getMemoryToken();n&&credentials.saveMemoryToken(n,{memorySubscribed:!0}),done(e,t&&!1===t.ok?"the server refused activation":"cloud memory activated for this account"),t&&t.token_limit&&note(e,`quota: ${t.tokens_used||0} / ${t.token_limit} synced tokens`)}catch(t){note(e,`activation failed: ${t.message}`)}return e.render(),!0}if("deactivate"===n)return credentials.clearMemoryToken(),e.client.setApiKey(e.client.apiKey),note(e,"cloud memory token cleared locally — sync stops until /cloud activate re-issues one"),note(e,"the account itself is still subscribed; manage the subscription here:"),note(e,goUrl("upgrade","cloud_deactivate")),e.render(),!0;if("memory"===n||"persist"===n||"memory-persist"===n){const t=(o||"status").toLowerCase();if("on"===t||"off"===t){const n="on"===t;return setMemoryGate(e,n),n?(done(e,"persisting memory on — sessions are stored to your account so an interrupted turn can be resumed"),note(e,"/cloud memory shows the quota; past the plan’s ceiling reads keep working and only new writes pause")):(note(e,"persisting memory off — nothing new is stored"),note(e,"everything already in the cloud stays readable (/aegis-recall <topic>), and /sync now still pushes once by hand")),e.render(),!0}return panel(e,memoryStatusLines(e)),e.render(),!0}if("sync"===n||"push"===n||"pull"===n){const t="sync"===n?(o||"status").toLowerCase():n;if("on"===t||"off"===t){const n="on"===t;return setMemoryGate(e,n),note(e,n?'persisting memory on — sessions are stored after each turn (this is the old "cloud sync")':"persisting memory off — nothing new is stored; /sync now still runs a manual pass"),e.render(),!0}if("now"===t)return await runCloudSync(e),e.render(),!0;const r=cloudsync.status();panel(e,[...memoryStatusLines(e),[span(C.gray,"")],[span(C.white+BOLD,"Sync ledger"),span(BOLD_OFF,"")],[span(C.gray,` local sessions: ${r.local} · pending push: ${r.pending} · in sync: ${r.synced}`)],[span(C.gray,` last push: ${r.lastPushAt?new Date(r.lastPushAt).toLocaleString():"never"} · last pull: ${r.lastPullAt?new Date(r.lastPullAt).toLocaleString():"never"}`)],[span(C.gray,` state: ${r.path}`)]]);for(const t of r.errors.slice(0,3))panel(e,[[span(C.coral,` ⚠ ${t.error}`)]]);return e.render(),!0}const r=cloudsync.status();return panel(e,[...keyPanelLines(e,"AEGIS cloud"),[span(C.gray,"")],...memoryStatusLines(e),[span(C.gray,"")],[span(C.white+BOLD," Sync"),span(BOLD_OFF,"")],[span(C.gray,` ${r.pending} pending · ${r.synced} in sync · ${r.importedRemote} pulled from cloud`)],[span(C.gray," /cloud memory on | off · /cloud sync on | off · /sync now")]]),e.render(),!0}},{name:"key",aliases:["apikey","api-key"],args:["value"],hint:"[<api_key>|status|clear|register]",category:"auth",desc:"Save or show the AEGIS account key",handler:async(e,t)=>{const n=String(t.value||t._rest||"").trim(),o=n.toLowerCase();if("status"===o)return panel(e,keyPanelLines(e)),e.render(),!0;if("register"===o){const t=await e.registerAccount();return t.alreadyKeyed?note(e,"this machine already has an AEGIS key — /key status shows it. Re-registering cannot mint a new welcome trial: that is granted once per machine, ever. For a fresh trial, sign up at aegiscloud.org; to point this session at a different key, /key clear first."):t.key&&t.ok?done(e,"AEGIS account key provisioned and saved"):t.key?note(e,"the account was created but its key could not be saved — run /key <api_key> with the key from aegiscloud.org"):note(e,`could not register this machine: ${t.error?t.error.message:"the server returned no account key"}`),e.render(),!0}if("clear"===o||"remove"===o||"rm"===o){const t=e.forgetApiKey();return done(e,t.cleared?`key removed from ${t.path}`:"there was no saved key to remove"),credentials.legacyKeyOnDisk()&&note(e,`a copy is still in ${configPath()} (written by another AEGIS CLI) — delete the "aegiscloud" block to finish the job`),e.render(),!0}return await applyAccountKey(e,n),e.render(),!0}},{name:"sync",aliases:["cloudsync","cloud-sync"],args:["mode"],hint:"[now|on|off|status]",category:"data",desc:"Store sessions in AEGIS Cloud (cross-session memory)",hidden:e=>!cloudReady(),handler:async(e,t)=>{const n=(t.mode||"").toLowerCase();if("on"===n||"off"===n)return setMemoryGate(e,"on"===n),note(e,"on"===n?"persisting memory on — sessions are stored so an interrupted turn can be resumed":"persisting memory off — nothing new is stored; /sync now still runs a manual pass"),e.render(),!0;if("status"===n){const t=cloudsync.status(),n=memoryStatusLines(e);return n.push([span(C.gray,"")]),n.push([span(C.gray,` local ${t.local} · pending ${t.pending} · in sync ${t.synced}`)]),panel(e,n),e.render(),!0}return await runCloudSync(e),e.render(),!0}},{name:"gmail",hint:"",category:"support",desc:"Link Gmail to conversations",handler:async e=>(note(e,"Gmail integration needs Google OAuth — not available in this build. Use /export to save conversations to files instead."),e.render(),!0)},{name:"clone",aliases:["fetch-site","websnap"],args:["url"],hint:"<url>",category:"workspace",desc:"Clone a website into a local project",handler:async(e,t)=>{const n=(t._rest||t.url||"").trim();return n?(note(e,`/clone needs a web-fetch tool and a chat service — not available in this build. Use /init to scaffold a fresh project instead of ${n}.`),e.render(),!0):(note(e,"Usage: /clone <url>"),e.render(),!0)}},{name:"release-notes",hint:"",category:"support",desc:"What's new",handler:async e=>(panel(e,panels.buildReleaseNotes(e.state(),e.ctx)),e.render(),!0)},{name:"aegis-status",hint:"",category:"aegis",desc:"Show account status — API key, plan, account and cloud memory",tool:"aegis_status",build:()=>({})},{name:"aegis-ask",aliases:["ask"],args:["question"],hint:"<question>",category:"aegis",desc:"Ask ÆGIS pooled inference a question (auto-routed)",tool:"aegis_ask",build:e=>({prompt:e})},{name:"aegis-recall",aliases:["recall"],args:["topic"],hint:"<topic>",category:"aegis",desc:"Recall cross-session memory about a topic (cloud)",tool:"aegis_memory_search",build:e=>({query:e})},{name:"aegis-remember",aliases:["remember"],args:["note"],hint:"<note>",category:"aegis",desc:"Save a note or decision to cross-session memory",tool:"aegis_memory_save",build:e=>({content:e})},{name:"aegis-council",aliases:["council"],args:["question"],hint:"<question>",category:"aegis",desc:"Put a question to the ÆGIS council (multi-perspective deliberation)",hidden:()=>!cloudReady(),handler:async(e,t)=>{const n=(t._rest||t.question||"").trim();if(!n)return note(e,"Usage: /aegis-council <question>"),e.render(),!0;const o=composeResearchPrompt(`Deliberate as a council and vote on: ${n}`,process.cwd());return e.runPrompt?(await e.runPrompt(o),!0):(note(e,`Composed council prompt (${o.length} chars) — run in the TUI to send it.`),e.render(),!0)}},{name:"aegis-print",args:["question"],hint:"<question>",category:"aegis",desc:"Ask pooled inference and print the answer cleanly",hidden:()=>!cloudReady(),handler:async(e,t)=>{const n=(t._rest||t.question||"").trim();if(!n)return note(e,"Usage: /aegis-print <question>"),e.render(),!0;const o=await e.ask(n);return panel(e,panels.buildAegisPrint("ÆGIS",{result:o.text,model:o.model,provider:"aegis"},e.ctx)),e.render(),!0}},{name:"aegis-multi",args:["task","mode"],hint:"<task> [run]",category:"aegis",desc:'Compose an ÆGIS /multi multi-agent task (add "run" to execute)',hidden:()=>!cloudReady(),handler:async(e,t)=>{let n=(t._rest||t.task||"").trim(),o=(t.mode||"").toLowerCase();return"run"!==o&&/\s+run$/i.test(n)&&(o="run",n=n.replace(/\s+run$/i,"").trim()),n?"run"!==o?(panel(e,panels.buildAegisMulti(n,e.ctx)),e.render(),!0):runMultiCommand(e,n):(note(e,"Usage: /aegis-multi <task> [run]"),e.render(),!0)}},{name:"byok",hint:"",category:"auth",desc:"List every provider you can bring your own key for, and which are set",handler:async e=>{const t=await byokCatalog(e.client);if(!t)return await e.runTool("aegis_byok_status",{}),!0;const n=t.filter((e=>e.configured)).length,o=[[span(C.gold+BOLD,"Bring your own key"),span(BOLD_OFF,"")],[span(C.gray,"─".repeat(34))],[span(n?C.green:C.gray,` ${n} of ${t.length} providers set`),span(C.gray," — /byok-list picks one, or /byok-key <provider>")],"",...byokProviderLines(t)];return panel(e,o),e.render(),!0}},{name:"byok-set",args:["provider"],hint:"<provider>",category:"auth",desc:"Store your provider key on your AEGIS ACCOUNT (pooled route) — for the byok class use /byok-key",tool:"aegis_byok_set",secret:"key",build:e=>({provider:String(e||"").trim()}),async secretDescribe(e,t){const n=String(e.provider||"").trim(),o=await byokCatalog(t);if(!o)return n?null:{note:"Usage: /byok-set <provider> — /byok lists them.",prompt:"provider key: "};const r=findByokProvider(o,n);if(r.ambiguous)return{note:`"${n}" matches ${r.ambiguous.join(", ")} — retype the exact id. Nothing was sent.`,prompt:null};const s=r.provider;if(!s)return{note:`unknown provider "${n}". Known ids: ${o.map((e=>e.id)).join(", ")}`,prompt:null};if(s.configured)return{note:`${s.id} already has a key${s.masked?` (${s.masked})`:""} — pasting a new one replaces it.`,prompt:`new ${s.label||s.id} key: `,provider:s.id};const a=[`${s.label||s.id}`],i=(s.models||[]).map((e=>"string"==typeof e?e:e&&e.id)).filter(Boolean);return i.length&&a.push(`unlocks ${i.join(", ")}`),s.key_prefix&&a.push(`key starts with ${s.key_prefix}`),s.key_url&&a.push(`create one at ${s.key_url}`),{note:a.join(" · "),prompt:`${s.id} key: `,provider:s.id}}},{name:"byok-rm",args:["provider"],hint:"<provider>",category:"auth",desc:"Remove a stored provider key",tool:"aegis_byok_set",build:e=>({provider:String(e||"").trim()})},{name:"class",args:["class","mode"],hint:"[aegis|byok|local|pro [on|off]]",category:"model",desc:'Show or switch which class turns run on; pro (your Claude subscription) needs a one-time "on"',handler:async(e,t)=>{const n=t||{},o=e.ctx&&e.ctx.modelClass||"aegis",r=t=>e.classLabel?e.classLabel(t):t,s=String(n.class||"").trim().toLowerCase();if("pro"===s&&n.mode){const t=String(n.mode).trim().toLowerCase();if("on"!==t&&"off"!==t)return e.push({role:"error",text:`usage: /class pro [on|off] — got "${n.mode}"`}),!0;const s="on"===t;if(e.saveConfig({proEnabled:s}),e.push({role:s?"done":"note",text:s?"pro class enabled — /class pro switches to your Claude Code subscription. It runs only if that subscription has Claude Code access.":"pro class disabled — it is no longer offered by /class or the model picker."}),!s&&"pro"===o){const t=e.switchClass("aegis");t.ok&&e.push({role:"note",text:`class: ${t.class} — ${r(t.class)}`})}return!0}if(!s){const t=await Promise.resolve(e.classes?e.classes():[]).catch((()=>[])),n=t.length?t:[{class:"aegis"},{class:"byok"}],r=n.findIndex((e=>e.class===o));return e.openOverlay({type:"class",items:n,sel:r<0?0:r,current:o}),!0}const a=e.switchClass(s);if(!a.ok)return e.push({role:"error",text:a.error}),!0;if(e.push({role:"done",text:`class: ${a.class} — ${r(a.class)}`}),a.cleared&&e.push({role:"note",text:`cleared the pin "${a.cleared}" — it does not belong to this class. /models lists what fits.`}),!("byok"!==a.class||e.ctx&&e.ctx.model)){const t=(await e.listModelsFor("byok")||[]).filter((e=>!e.cls||"byok"===e.cls)),n=t.find((e=>e.configured))||t[0];n?(e.ctx.model=n.id,e.saveConfig({model:n.id,currentModelId:n.id}),e.push({role:"note",text:n.configured?`using ${n.id} — /models lists the rest.`:`using ${n.id}, but no ${n.provider} key is saved yet — /byok-key ${n.provider}.`})):0===t.length&&e.push({role:"note",text:"nothing to relay yet — save a provider key with /byok-key <provider>, then /models."})}return!0}},{name:"models",aliases:["model-list"],hint:"",category:"model",desc:"Pick a model to pin, for the class you are on — opens the same picker as /model",handler:async e=>{const t=e.ctx&&e.ctx.modelClass||"aegis",n=await e.listModelsFor(t)||[];if(!n.length)return note(e,"byok"===t?"nothing to relay yet — save a provider key with /byok-key <provider>":"no models advertised — check the account with /status, then retry"),e.render(),!0;const o=e.ctx&&e.ctx.model,r=n.map((e=>e.cls&&e.cls!==t?{...e,note:`${e.note||e.label||""} · pooled lane — /class ${e.cls}`}:e)),s=r.findIndex((e=>e.id===o));return e.openOverlay({type:"model",items:r,sel:s<0?0:s,current:o,cls:t}),!0}},{name:"byok-list",aliases:["byok-pick"],hint:"",category:"auth",desc:"Pick a provider to set a key for, then its models appear in /model",handler:async e=>{const t=await byokCatalog(e.client);if(!t||!t.length)return e.push({role:"error",text:"Could not read the provider catalog (offline, or no AEGIS key) — /byok lists what is known."}),!0;if("function"!=typeof e.openOverlay)return e.push({role:"note",text:"/byok-key <provider> — /byok lists the providers."}),!0;const n=(t.find((e=>e.configured))||{}).id||null,o=Math.max(0,t.findIndex((e=>e.configured)));return e.openOverlay({type:"provider",command:"byok-key",items:t,sel:o,current:n,hint:"↑↓ or tab move · enter picks · the key is stored on this machine"}),!0}},{name:"byok-key",args:["provider"],hint:"<provider> [key]",category:"auth",desc:"Save YOUR provider key on THIS MACHINE — the key the byok class sends",handler:async(e,t)=>{const n=t||{},o=String(n.provider||"").trim().toLowerCase();if(!o){const t=await byokCatalog(e.client);if(!t||!t.length)return e.push({role:"error",text:"Usage: /byok-key <provider> — /byok lists the providers."}),!0;if("function"!=typeof e.openOverlay)return e.push({role:"error",text:"Usage: /byok-key <provider> — /byok lists the providers."}),!0;const n=(t.find((e=>e.configured))||{}).id||null,o=Math.max(0,t.findIndex((e=>e.configured)));return e.openOverlay({type:"provider",command:"byok-key",items:t,sel:o,current:n,hint:"↑↓ or tab move · enter picks · the key is stored on this machine"}),!0}const r=e.settings&&e.settings();if(!r||"function"!=typeof r.set)return e.push({role:"error",text:"this client has no provider-key store."}),!0;const s=await byokCatalog(e.client),a=s?findByokProvider(s,o):null;if(a&&a.ambiguous)return e.push({role:"error",text:`"${o}" matches ${a.ambiguous.join(", ")} — retype the exact id.`}),!0;if(s&&!a?.provider){const t=s.map((e=>e.id)).join(", ");return e.push({role:"error",text:`unknown provider "${o}". Known ids: ${t} — nothing was saved.`}),!0}const i=a&&a.provider,d=i&&i.id||o,l=String(n._rest||"").trim(),c=l.indexOf(" ");let u=-1===c?"":l.slice(c+1).trim();if(u||(i&&i.key_url&&e.push({role:"note",text:`create a ${i.label||d} key at ${i.key_url}`}),u=String(await e.readSecret(`${d} key: `)||"").trim()),!u)return e.push({role:"note",text:"nothing saved."}),!0;if(i&&i.key_prefix&&!u.startsWith(i.key_prefix)&&e.push({role:"note",text:`heads up: ${d} keys normally start with "${i.key_prefix}" — saved anyway.`}),"custom"===d&&!savedByokBaseURL(e,d))return e.push({role:"error",text:`the "custom" provider needs an endpoint as well as a key — a key alone dials nothing. Use: /model-add custom <https-base-url> ${u} <model-id> (saves endpoint, key and model together) — nothing was saved.`}),!0;r.set(e.byokNamespace(d),{key:u});let p="";try{const{envVarFor:t,setEnvValue:n}=require(resolveShared(path.join("client","env-file.js"))),o=t(d);if(o){const t=n(o,u);t.ok?p=o:e.push({role:"note",text:`heads up: could not write ${o} to ~/.aegiscode/.env (${t.error}).`})}}catch{}let h=[];if("function"==typeof e.refreshByokModels)try{h=await e.refreshByokModels()||[]}catch{h=[]}if(!h.length&&"function"==typeof e.listModelsFor)try{h=(await e.listModelsFor("byok")||[]).filter((e=>!e.cls||"byok"===e.cls))}catch{h=[]}const m=h.filter((e=>e&&(e.provider===d||String(e.id||"").startsWith(`${d}:`))));let g="byok"===(e.ctx&&e.ctx.modelClass||"");if(!g&&"function"==typeof e.switchClass){const t=e.switchClass("byok");t&&t.ok&&(g=!0,e.push({role:"note",text:`class: byok — ${e.classLabel?e.classLabel("byok"):"your own key"}`}))}const y=m.length?String(m[0].id):"";return y&&e.ctx&&(e.ctx.model=y,e.saveConfig({model:y,currentModelId:y,...g?{modelClass:"byok"}:{}})),e.push({role:"done",text:y?`saved a ${d} key on this machine${p?` (${p} in ~/.aegiscode/.env, so it is there next time)`:""} — model ${y} pinned, /model lists the rest.`:`saved a ${d} key on this machine${p?` (${p} in ~/.aegiscode/.env, so it is there next time)`:""} — /models lists its models, /class byok runs on it.`}),!0}},{name:"byok-rm-key",args:["provider"],hint:"<provider>",category:"auth",desc:"Forget the provider key saved on this machine",handler:async(e,t)=>{const n=String((t||{}).provider||"").trim().toLowerCase();if(!n)return e.push({role:"error",text:"Usage: /byok-rm-key <provider> — /byok lists the providers."}),!0;const o=e.settings&&e.settings();if(!o||"function"!=typeof o.remove)return e.push({role:"error",text:"this client has no provider-key store."}),!0;const r=e.byokNamespace(n),s="function"==typeof o.rawKey?o.rawKey(r):null;return o.remove(r),e.push({role:s?"done":"note",text:s?`removed the ${n} key from this machine.`:`no ${n} key was saved on this machine.`}),!0}},{name:"model-add",aliases:["add-model"],args:["provider"],hint:"<provider> [api-key] [model-id|*] (custom: <base-url> <api-key> [model-id|*])",category:"model",desc:"Save a provider key and offer a model id in one step (asks the vendor when it can)",handler:async(e,t)=>{const n=t||{},o=String(n.provider||"").trim();if(!o)return e.push({role:"error",text:"Usage: /model-add <provider> [api-key] <model-id> — /byok lists the providers. A vendor this catalog does not name yet: /model-add custom <https-base-url> <api-key> <model-id>. Example: /model-add deepseek sk-xxxxxxxx deepseek-v4.3-preview"}),!0;const r=splitCommandWords(String(n._rest||"").trim());let s=r.length&&r[0].toLowerCase()===o.toLowerCase()?r.slice(1):r;const a=await byokCatalog(e.client),i=a?findByokProvider(a,o):null;if(i&&i.ambiguous)return e.push({role:"error",text:`"${o}" matches ${i.ambiguous.join(", ")} — retype the exact id.`}),!0;if(a&&(!i||!i.provider))return e.push({role:"error",text:`no provider "${o}" in the relay's catalog — /byok lists the ones it takes a key for.`}),!0;const d=i&&i.provider&&i.provider.id||o.toLowerCase();let l="",c="";if("custom"===d){if(1===s.length&&!savedByokBaseURL(e,d))return e.push({role:"error",text:"one word cannot say whether it is the URL or the model id — nothing was saved. Type the endpoint first: /model-add custom <https-base-url> <api-key> [model-id]"}),!0;s.length>=2&&(l=s.shift(),c=s.shift())}else s.length>=2&&(c=s.shift());let u=s.join(" ").trim();if(c){const t=e.settings&&e.settings();if(!t||"function"!=typeof t.set)return e.push({role:"error",text:"this client has no provider-key store."}),!0;const n=i&&i.provider;n&&n.key_prefix&&!c.startsWith(n.key_prefix)&&e.push({role:"note",text:`heads up: ${d} keys normally start with "${n.key_prefix}" — saved anyway.`}),l&&!/^https:\/\//i.test(l)&&e.push({role:"note",text:"heads up: aegis1 only dials an https:// base_url — saved anyway, but calls on it will be refused."}),t.set(e.byokNamespace(d),{key:c,...l?{baseURL:l}:{}});try{const{envVarFor:t,setEnvValue:n}=require(resolveShared(path.join("client","env-file.js"))),o=t(d);if(o){const t=n(o,c);t.ok||e.push({role:"note",text:`heads up: could not mirror the key into ~/.aegiscode/.env (${t.error}).`})}}catch{}e.push({role:"done",text:l?`saved a ${d} key and base URL (${l}) on this machine.`:`saved a ${d} key on this machine.`})}const p=byokKeyForProvider(e,d),h=await offeredModelIds(e,d,p);if("*"===u){if(!h){const t=await discoverProviderModels(e,d,p);return e.push({role:"error",text:`cannot list ${d}: ${t&&t.error||"no list available"} — type the ids instead: /model-add ${d} <model-id>`}),!0}const t=addManyUserModels(d,h);if("function"==typeof e.refreshByokModels)try{await e.refreshByokModels()}catch{}return e.push({role:"done",text:`added ${t.added} of the ${h.length} model ids ${d} serves${t.already.length?` (${t.already.length} were already declared)`:""}.`}),t.capped&&e.push({role:"note",text:`stopped at the store's per-provider cap (32) — ${t.capped} more id(s) were left out; /model-add ${d} <model-id> stores a specific one, /model-rm frees a slot.`}),t.failed.length&&e.push({role:"note",text:`${t.failed.length} id(s) were refused: ${t.failed.map((e=>e.id)).join(", ")}`}),e.push({role:"note",text:`stored in ${userModelsPath()} — the desktop reads the same file. /model-discover ${d} lists what the vendor serves.`}),!0}if(!u){h&&e.push({role:"note",text:`${d} serves ${h.length} model ids — ${h.slice(0,12).join(", ")}${h.length>12?", …":""}`});const t=String(await e.askInput(h?`model id for ${d} (1-${h.length}, or type one): `:`model id for ${d}: `)||"").trim(),n=h&&/^\d+$/.test(t)?Number(t):0;u=h&&n>=1&&n<=h.length?h[n-1]:t}if(!u)return e.push({role:"note",text:"nothing saved."}),!0;let m;try{m=addUserModel(d,u)}catch(t){return e.push({role:"error",text:t&&t.message||String(t)}),!0}if("function"==typeof e.refreshByokModels)try{await e.refreshByokModels()}catch{}const g=(("function"==typeof e.listModelsFor?await e.listModelsFor("byok"):[])||[]).find((e=>e&&e.id===`${d}:${u}`));return e.push({role:m.added?"done":"note",text:m.added?`added ${d}:${u} — offered on this machine now, in the CLI and the desktop.`:`${d}:${u} was already declared.`}),a||e.push({role:"note",text:`the relay's catalog could not be read, so "${d}" is unverified — if it does not appear in /models, /byok lists the provider ids it takes.`}),m.added&&!g&&e.push({role:"note",text:`saved, but no row will be offered for "${d}" yet — the relay lists no provider of that id (or that provider lists no models).`}),m.added&&h&&e.push({role:"note",text:`${d} currently serves ${h.length} model ids — /model-discover ${d} lists them, /model-add ${d} '*' takes them all.`}),e.push({role:"note",text:`stored in ${m.file} — the desktop reads the same file.`}),!0}},{name:"model-discover",aliases:["discover-models","vendor-models"],args:["provider"],hint:"<provider>",category:"model",desc:"List the model ids your provider's own API serves",handler:async(e,t)=>{const n=String((t||{}).provider||"").trim();if(!n)return e.push({role:"error",text:`Usage: /model-discover <provider> — this client can ask: ${discoverableProviders().join(", ")}`}),!0;const o=await byokCatalog(e.client),r=o?findByokProvider(o,n):null,s=(r&&r.provider&&r.provider.id||n).toLowerCase(),a=vendorEndpointFor(s);if(!a)return e.push({role:"error",text:`no list endpoint for "${s}" in this client — /model-add ${s} <model-id> stores an id you already know. Providers it can ask: ${discoverableProviders().join(", ")}`}),!0;const i=byokKeyForProvider(e,s);if(!i)return e.push({role:"error",text:`no ${s} key on this machine — /byok-key ${s} saves one (or put it in ~/.aegiscode/.env), then this lists what the key reaches.`}),!0;const d=await discoverProviderModels(e,s,i);if(!d||!d.ok)return e.push({role:"error",text:`could not list ${s}: ${d&&d.error||"no answer"}`}),!0;const l=new Set(userModelIdsFor(s)),c=new Set((r&&r.provider&&r.provider.models||[]).map((e=>String(e))));e.push({role:"note",text:`${s} at ${a.url}${a.note?` (${a.note})`:""}`}),e.push({role:"note",text:`${d.count} chat model id(s) the vendor serves — mark: [seen] the relay already lists it, [your] you declared it, [new] this machine does not offer it yet.`});const u=d.ids.map(((e,t)=>{const n=l.has(e)?"[your]":c.has(e)?"[seen]":"[new]";return`${String(t+1).padStart(3)}. ${n} ${e}`}));u.length&&e.push({role:"panel",lines:u}),u.length||e.push({role:"note",text:`the vendor answered with no chat models — /model-add ${s} <model-id> stores one by hand.`}),d.others.length&&e.push({role:"note",text:`${d.others.length} id(s) are not chat models (embeddings, audio, moderation or an unsupported method) and are left out: ${d.others.slice(0,8).join(", ")}${d.others.length>8?", …":""}`});const p=d.ids.filter((e=>!l.has(e)&&!c.has(e)));return p.length&&e.push({role:"note",text:`${p.length} of them are not offered on this machine yet — /model-add ${s} '<model-id>' stores one, /model-add ${s} '*' stores every chat model the vendor serves.`}),!0}},{name:"model-rm",aliases:["rm-model"],args:["provider"],hint:"<provider> <model-id>",category:"model",desc:"Forget a model id you added with /model-add",handler:async(e,t)=>{const n=t||{},o=String(n.provider||"").trim(),r=String(n._rest||"").trim(),s=r.indexOf(" "),a=-1===s?"":r.slice(s+1).trim();if(!o||!a)return e.push({role:"error",text:"Usage: /model-rm <provider> <model-id> — /model-add lists what you added."}),!0;let i;try{i=removeUserModel(o,a)}catch(t){return e.push({role:"error",text:t&&t.message||String(t)}),!0}if("function"==typeof e.refreshByokModels)try{await e.refreshByokModels()}catch{}return e.push({role:i.removed?"done":"note",text:i.removed?`removed ${i.provider}:${i.model} — the picker stops offering it on the next refresh.`:`${i.provider}:${i.model} was not declared on this machine.`}),!0}},{name:"tool",args:["name","json"],hint:"<name> [json]",category:"aegis",desc:"Call any registry tool directly (escape hatch for new tools)",generic:!0,build:e=>{const t=String(e||""),n=t.indexOf(" "),o=(-1===n?t:t.slice(0,n)).trim(),r=-1===n?"":t.slice(n+1).trim();let s={};if(r)try{s=JSON.parse(r)}catch(e){throw new Error(`/tool: arguments must be JSON — ${e.message}`)}return{tool:o,args:s}}},{name:"aegis-import",aliases:["import"],hint:"[--confirm]",category:"aegis",desc:"Import memory from other AI tools on this machine (dry run unless --confirm)",tool:"aegis_memory_import",build:e=>({confirm:/--confirm\b/.test(String(e||""))})}],BY_NAME=new Map;for(const e of COMMANDS)for(const t of[e.name,...e.aliases||[]]){if(BY_NAME.has(t))throw new Error(`aegiscode: command name or alias /${t} is registered twice`);BY_NAME.set(t,e)}function allCommands(){return COMMANDS.map((e=>({...e,categoryLabel:categoryLabel(e.category)})))}function visibleCommands(){return allCommands().filter((e=>!("function"==typeof e.hidden?e.hidden():e.hidden)))}function findCommand(e){return BY_NAME.get(String(e||"").toLowerCase())||null}function canonicalName(e){const t=findCommand(e);return t?t.name:e}function parseLine(e){const t=String(null==e?"":e).trim();if(!t)return{kind:"empty"};if("/"!==t[0])return{kind:"prompt",text:t};const n=t.indexOf(" "),o=(-1===n?t.slice(1):t.slice(1,n)).trim(),r=-1===n?"":t.slice(n+1).trim(),s=findCommand(o);return s?s.unavailable?{kind:"unavailable",command:s,arg:r}:{kind:"command",command:s,arg:r}:{kind:"unknown",name:o,text:t}}function toolBackedCommands(){return COMMANDS.filter((e=>e.tool))}module.exports={CATEGORIES:CATEGORIES,categoryLabel:categoryLabel,EFFORT_LEVELS:EFFORT_LEVELS,COMMANDS:COMMANDS,allCommands:allCommands,visibleCommands:visibleCommands,findCommand:findCommand,canonicalName:canonicalName,parseLine:parseLine,toolBackedCommands:toolBackedCommands};
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
+ * Slash commands — the CLI's full command vocabulary, ported from the sibling
10
+ * the upstream engine client (`src/registry.js`), on top of the AEGIS tool registry
11
+ * (`mcp/tools.js`).
12
+ *
13
+ * Three kinds of entry live in one table:
14
+ *
15
+ * (a) handler — a local `async (c, args) => bool` that runs against the
16
+ * frozen command context `c` (see `cli/src/app.js`). It returns false to
17
+ * end the session. This is the reference's own contract, so a handler
18
+ * body reads the same here as it does in the upstream engine — only the panels
19
+ * and support modules it calls are this client's.
20
+ * (b) tool-backed — names a tool from `mcp/tools.js` and carries a
21
+ * `build(arg) -> object` that turns the typed argument into the tool's
22
+ * JSON. `test/cli-tools.test.mjs` asserts both directions: no command
23
+ * points at a tool that does not exist, and no tool in the registry is
24
+ * unreachable from the prompt (the `/tool` escape hatch keeps the latter
25
+ * true for tools with no dedicated command).
26
+ * (c) unavailable — a command whose whole premise is the Claude Code CLI's
27
+ * own auth loop (`login`, `logout`). These carry an honest `unavailable`
28
+ * reason and a working `alt`; `parseLine` returns `{ kind: 'unavailable' }`
29
+ * and `app.js` prints the reason rather than a fake success.
30
+ *
31
+ * The names, aliases, categories and descriptions come from the upstream engine's
32
+ * `COMMANDS`/`CATEGORIES`. Where this client's capability genuinely differs from
33
+ * the reference's the handler says so honestly (a note, an honest panel, or a
34
+ * real command run through the ported support modules) rather than copying a
35
+ * sentence that would be untrue.
36
+ *
37
+ * Every command is defined against the FROZEN command context `c`:
38
+ * c.ctx (mutable session context), c.sessionId, c.transcript,
39
+ * c.push/note/panel, c.render, c.openOverlay, c.closeOverlay, c.askInput,
40
+ * c.withWorking, c.runPrompt, c.ask, c.runTool, c.refreshSpend, c.state,
41
+ * c.setInput, c.exit, c.client, c.TOOLS, c.saveConfig, c.showThemePicker.
42
+ *
43
+ * Plain text (no leading `/`) is a prompt: it goes to the pooled brain.
44
+ */
45
+
46
+ const fs = require('node:fs');
47
+ const os = require('node:os');
48
+ const path = require('node:path');
49
+ const { execSync } = require('node:child_process');
50
+
51
+ const { span } = require('./screen.js');
52
+ const { C, BOLD, BOLD_OFF, THEME_TABLE, themeContradicts } = require('./theme.js');
53
+ // `caps.js` is dependency-free (it requires nothing), so this cannot cycle the
54
+ // way a `theme.js` → `art.js` → `theme.js` require would.
55
+ const { caps, setCaps, resetCaps, describe, probeTerminalBackground } = require('./caps.js');
56
+ const panels = require('./panels.js');
57
+ const overlays = require('./overlays.js');
58
+ const {
59
+ updateConfig, loadConfig, loadPermissions, savePermissions, addPermissionRule,
60
+ DEFAULT_PERMISSIONS, permissionsPath, configPath, aegisDir,
61
+ // ON8 / D8 rule 1: the posture writers. Every "confirmations on/off" command
62
+ // below goes through these rather than writing `defaultMode` itself, so the
63
+ // window's switch and this face's gate cannot end up holding two answers.
64
+ setConfirmPosture, setPermissionDefaultMode, confirmPosture,
65
+ memoryPersistState, setMemoryPersist,
66
+ } = require('./config.js');
67
+ const { auditExposure, repairExposure } = require('./securefs.js');
68
+ const { copyToClipboard } = require('./clipboard.js');
69
+ const { snapshotCheckpoint, listCheckpoints, loadCheckpoint } = require('./checkpoint.js');
70
+ const { signupUrl, goUrl } = require('./signup.js');
71
+ const screens = require('./screens.js');
72
+ const { summarizeTranscript, recapLine } = require('./summarize.js');
73
+ const { sessionAccounting, accountingFromUsage, estimateTokens } = require('./tokens.js');
74
+ // The one effort normaliser, so `/config effort <x>` writes the same rung the
75
+ // turn will send (see effortRung in engine.js — it is what app.js puts on the
76
+ // request).
77
+ const { effortRung } = require('./engine.js');
78
+ const { transcriptToMarkdown, transcriptToJSON, writeExportFile, lastAssistantText } = require('./export.js');
79
+ const { detectDevCommand, runDevServer } = require('./devrun.js');
80
+ // /ping — the terminal half of the desktop's "reply ready" alert. Pure and
81
+ // dependency-free (no config, no TTY), so it is unit-testable on its own.
82
+ const {
83
+ PING_MODES, DEFAULT_PING_MODE, normalizePingMode, normalizePingSeconds,
84
+ buildPing, writePing,
85
+ } = require('./ping.js');
86
+ // /todos — the session list. Owns its own file; shares only `aegisDir`.
87
+ const { addTodo, completeTodo, clearTodos, formatTodos, todosFile } = require('./todos.js');
88
+ // /config — the settings surface. Store-aware, so it cannot write a preference
89
+ // to the host file (or the reverse) and re-open the drift ON8/D8 closed.
90
+ const {
91
+ configRows, formatConfigRows, setConfigValue, resetConfigValue,
92
+ fullValue, summarizeValue, configStore,
93
+ } = require('./settings.js');
94
+ const credentials = require('./credentials.js');
95
+ const cloudsync = require('./cloudsync.js');
96
+ const { maskKey, fmtTokens, shortCwd } = require('./format.js');
97
+ const { pickerEntries } = require('./models.js');
98
+ const { resolveShared } = require('./sharedpaths.js');
99
+ const { createCliEntitlement, paymentView, probeFee } = require('./entitlement.js');
100
+ const { openUrl, URLS } = require('./system.js');
101
+ // The machine checks behind `/doctor system` — see cli/src/sysdiag.js for why
102
+ // they exist and why they never mutate anything.
103
+ const sysdiag = require('./sysdiag.js');
104
+ const { sniffProject, buildAegisMd } = require('./init.js');
105
+ const {
106
+ upgradeAdvice, latestPublishedVersion, applyUpgrade, installMethod,
107
+ } = require('./update.js');
108
+ const {
109
+ AGENT_PRESETS, agentRoles, composeAgentPrompt, composeResearchPrompt, composeDebatePrompt,
110
+ } = require('./agents.js');
111
+ const {
112
+ aggregateSessionUsage, pruneSessionHistory, readResumeList,
113
+ } = require('./history.js');
114
+ // Guarded: a concurrent workstream owns ./markdown.js.
115
+ let markdownModule = null;
116
+ try {
117
+ // eslint-disable-next-line global-require
118
+ markdownModule = require('./markdown.js');
119
+ } catch {
120
+ markdownModule = null;
121
+ }
122
+
123
+ const VERSION = require('../package.json').version;
124
+
125
+ // ── Categories ────────────────────────────────────────────────────────────────
126
+
127
+ const CATEGORIES = [
128
+ { id: 'session', label: 'Session & context' },
129
+ { id: 'workspace', label: 'Workspace' },
130
+ { id: 'model', label: 'Model & behavior' },
131
+ { id: 'data', label: 'Data' },
132
+ { id: 'auth', label: 'Auth' },
133
+ { id: 'support', label: 'Support' },
134
+ { id: 'fun', label: 'Fun' },
135
+ { id: 'aegis', label: 'Aegis plugin' },
136
+ { id: 'custom', label: 'Custom' },
137
+ ];
138
+
139
+ const categoryLabel = (id) => (CATEGORIES.find((cat) => cat.id === id) || {}).label || id;
140
+
141
+ // One table, shared with the picker that draws it. The two used to be separate
142
+ // lists — this one a string array, chatflow.js's own copy of the same three
143
+ // strings, and overlays.js's label/note rows — so adding a level meant editing
144
+ // three places, and the index a picker row reported was mapped back to a value
145
+ // through whichever list happened to be in scope. EFFORT_VALUES is the picker's
146
+ // own order: the three rungs, with no `auto` entry any more.
147
+ const EFFORT_LEVELS = overlays.EFFORT_VALUES;
148
+
149
+ // ── Small handler helpers ─────────────────────────────────────────────────────
150
+
151
+ const note = (c, text) => c.push({ role: 'note', text });const panel = (c, lines) => c.push({ role: 'panel', lines });
152
+ const tip = (c, text) => c.push({ role: 'tip', text });
153
+ const done = (c, text) => c.push({ role: 'done', text });
154
+
155
+ // ── The multi-agent fan-out (/multi run, /multiyolo, /aegis-multi run) ────────
156
+ //
157
+ // These three commands used to only *compose* text: /multi <task> run and
158
+ // /aegis-multi <task> run printed "Running the task through the pooled brain
159
+ // (single-model — the reference fans it out)" and handed the raw task to
160
+ // c.runPrompt — a single turn, not a fan-out — while /multiyolo printed the
161
+ // paste-ready panel and never executed anything at all, so its `savePermissions
162
+ // ({ defaultMode: 'allow' })` turned automode on and then did nothing with it.
163
+ //
164
+ // The upstream engine calls `multiData(task, { signal })`, which
165
+ // shells out to aegis-cli (`aegis --print "/multi <task>"`) because the fan-out
166
+ // lives in that binary. This host has no aegis-cli, and a shell-out that fails
167
+ // on every machine without one is not a port — so the real multi-agent runtime
168
+ // here is the engine's own `task` tool (desktop/lib/local/engine.js
169
+ // `runSubagent`: a specialist subagent with its own tool loop, session id and
170
+ // approval card, primed from agents.js). One turn drives it, and the delegation
171
+ // is executed rather than described.
172
+
173
+ /** The fan-out prompt handed to the engine — the specialists are named so the delegation actually happens. */
174
+ function composeMultiFanoutPrompt(task) {
175
+ return [
176
+ 'Execute this task as a multi-agent fan-out.',
177
+ '',
178
+ `Task: ${task}`,
179
+ '',
180
+ `Workspace: ${process.cwd()}`,
181
+ '',
182
+ 'Use the task tool to delegate the independent parts to specialist subagents, in parallel where they do not depend on each other:',
183
+ '- reconnaissance first (scanner for secrets/unsafe patterns, analyzer for refactor targets),',
184
+ '- then design (architect, or planner when the work is a change to existing code),',
185
+ '- then an implementer subagent to make the change.',
186
+ 'Finally review the result (reviewer subagent), fix what it finds, and verify with the repository\'s real commands.',
187
+ '',
188
+ 'Return one consolidated report: what each subagent found, the files you changed, the exact commands you ran and their real output, and anything still blocked. No preamble.',
189
+ ].join('\n');
190
+ }
191
+
192
+ /**
193
+ * The this-host `multiData(task, { signal })`. Returns the reference's shape —
194
+ * `{ result, model, provider }`, `{ cancelled }`, or `{ error }` — so callers
195
+ * render it through `panels.buildAegisPrint` exactly as the reference does.
196
+ * `{ error }` is the honest fallback: the caller says why and still hands the
197
+ * user a paste-ready command instead of pretending the fan-out ran.
198
+ */
199
+ async function multiData(c, task) {
200
+ const prompt = composeMultiFanoutPrompt(task);
201
+ const run = c && c.withWorking ? (fn) => c.withWorking(fn) : (fn) => fn();
202
+ // A context with no agent loop at all (no ask, no runPrompt) is the one case
203
+ // this cannot execute — say so rather than returning an empty success.
204
+ if (!c || (typeof c.ask !== 'function' && typeof c.runPrompt !== 'function')) {
205
+ return { error: 'No agent loop in this context — the fan-out prompt was composed, not run.' };
206
+ }
207
+ try {
208
+ if (typeof c.ask === 'function') {
209
+ const res = await run((signal) => c.ask(prompt, { signal }));
210
+ const text = (res && res.text) || '';
211
+ if (res && res.interrupted && !text) return { cancelled: true };
212
+ if (!text) return { error: 'The multi-agent fan-out returned nothing (the turn failed before it could delegate).' };
213
+ return { result: text, model: (res && res.model) || (c.ctx && c.ctx.model) || null, provider: 'aegis' };
214
+ }
215
+ // No captured-answer path: still execute, streamed into the transcript.
216
+ await run(() => c.runPrompt(prompt));
217
+ return { streamed: true };
218
+ } catch (e) {
219
+ return { error: `ÆGIS multi failed — ${(e && e.message) || e}` };
220
+ }
221
+ }
222
+
223
+ /**
224
+ * Drive one of the three fan-out commands end to end. `automode` is /multiyolo's
225
+ * edge: the permission mode is set to allow *and* the task then executes under
226
+ * it (previously it was set and never used).
227
+ */
228
+ async function runMultiCommand(c, task, { yolo = false, title = 'ÆGIS Multi' } = {}) {
229
+ if (yolo) {
230
+ // ON8: through the posture writer, not a bare `defaultMode` write — /multiyolo
231
+ // means "stop confirming", and that is now ONE fact in two stores rather than
232
+ // a rule-file edit the window would never see.
233
+ setConfirmPosture(false);
234
+ panel(c, panels.buildAutomode(c.state(), c.ctx));
235
+ }
236
+ note(c, 'Running the multi-agent fan-out — the engine delegates to specialist subagents (headless: this skips aegis-cli\'s own confirmation step).');
237
+ c.render();
238
+ const res = await multiData(c, task);
239
+ if (res.cancelled) { note(c, 'ÆGIS multi cancelled.'); c.render(); return true; }
240
+ if (res.error) {
241
+ note(c, res.error);
242
+ // Unreachable is not the same as useless: hand over the command that runs
243
+ // it in a real aegis-cli session.
244
+ panel(c, panels.buildAegisMulti(task, c.ctx));
245
+ c.render();
246
+ return true;
247
+ }
248
+ if (res.streamed) return true;
249
+ panel(c, panels.buildAegisPrint(title, res, c.ctx));
250
+ c.render();
251
+ return true;
252
+ }
253
+
254
+ /** /upgrade's advice as panel rows (the advice itself is plain strings). */
255
+ const upgradePanelLines = (lines) => lines.map((l) => [span(C.white, l)]);
256
+
257
+ /**
258
+ * The paid prompt `/billing` prints, or `undefined` when it cannot be earned.
259
+ *
260
+ * WHY THIS EXISTS AS A FUNCTION. `/billing` is the one screen a user opens when
261
+ * they are already thinking about money, and it was the only money surface in
262
+ * this client that did not ask the account anything: it printed the ledger and
263
+ * the line "AEGIS has no subscription of its own". Both are now answered from
264
+ * the SAME decision the drain clamps on (`desktop/lib/local/entitlement.js`,
265
+ * reached through `cli/src/entitlement.js` with `host: 'cli'`), so the terminal
266
+ * cannot sell a plan the drain would refuse, or refuse a fan-out to a bank the
267
+ * panel just called funded.
268
+ *
269
+ * `force` on the refresh, deliberately: the gate's snapshot is a 60 s cache
270
+ * built for a drain that must not probe per task, but `/billing` is an explicit
271
+ * ask — "what do I owe" answered from a minute-old read is the wrong answer at
272
+ * exactly the moment it is being asked. One probe per `/billing`, not per task.
273
+ *
274
+ * Returns undefined rather than a guess when the gate cannot be built at all
275
+ * (no client, no shared module). The panel then prints its neutral top-up row.
276
+ * The failure direction matters: inventing a wall for an account we could not
277
+ * read is the one error here that costs real money — either selling Pro to
278
+ * someone who has it or telling a funded user their bank is empty.
279
+ */
280
+ async function billingPayment(c) {
281
+ if (!c || !c.client) return undefined;
282
+ let gate;
283
+ try {
284
+ gate = createCliEntitlement({ aegis: c.client });
285
+ } catch {
286
+ return undefined;
287
+ }
288
+ // Through the spinner when the host has one: this is a network read, and an
289
+ // unannounced two-second pause after `/billing` reads as a hang.
290
+ const run = c.withWorking ? (fn) => c.withWorking(fn) : (fn) => fn();
291
+ try {
292
+ await run(() => gate.refresh({ force: true }));
293
+ } catch {
294
+ // `refresh()` is contractually non-throwing, but a broken host could still
295
+ // reject; the cached (or boot) snapshot is a real read and still usable.
296
+ }
297
+ // The relay's handling fee, published by the same server the probe just
298
+ // talked to. Fetched here rather than in the panel because the panel is pure
299
+ // (and tested as such), and fetched WITHOUT `force`: a minute-old price is
300
+ // still the price, unlike a minute-old entitlement verdict, and this keeps
301
+ // `/billing` at one probe plus one cheap GET rather than two round trips to
302
+ // the same host.
303
+ const fee = await probeFee();
304
+ return paymentView(gate.current(), { host: 'cli', fee });
305
+ }
306
+
307
+ /**
308
+ * The pinnable-model list for the class the session is on, fetched fresh.
309
+ *
310
+ * `c.loadModels()` on the command context is `() => listModelsFor(cls)` — it
311
+ * already returns the class-scoped rows (the pooled catalog on aegis, the
312
+ * `provider:model` ids this machine can relay on byok). This helper must
313
+ * RETURN that value.
314
+ *
315
+ * It used to `await` it and discard the result, leaving every caller to read
316
+ * `c.state().models` instead, which went stale the moment the live class
317
+ * changed. Best-effort on failure: offline, the caller falls through to the
318
+ * honest empty note rather than opening an empty picker.
319
+ * @returns {Promise<Array<{id:string,label:string,note:string}>>}
320
+ */
321
+ async function loadModels(c) {
322
+ try {
323
+ return (await c.loadModels()) || [];
324
+ } catch {
325
+ return [];
326
+ }
327
+ }
328
+
329
+ /**
330
+ * The full model list across BOTH classes, for the /model picker: the pooled
331
+ * Nexus entry plus every provider id this machine can relay directly (BYOK),
332
+ * each tagged with the class ENTER should apply the pin under.
333
+ *
334
+ * Before this, the picker was class-scoped: opening it on the default 'aegis'
335
+ * class showed the single collapsed Nexus row, and reaching any of the real
336
+ * per-provider models meant already knowing to run `/class byok` first — the
337
+ * BYOK half of the catalog was correct but undiscoverable. Building one merged
338
+ * list here (rather than in two places) keeps the interactive picker and the
339
+ * `/model list` panel from disagreeing about what "the full list" is.
340
+ */
341
+ async function mergedPickerModels(c) {
342
+ const live = (c.ctx && c.ctx.modelClass) || 'aegis';
343
+ const aegis = pickerEntries(await loadModelsFor(c, 'aegis', live)).map((m) => ({ ...m, cls: 'aegis' }));
344
+ // `m.cls ||` and not `cls:`: the byok list carries rows that belong to
345
+ // another class (the pooled lane's, prepended by classScopedModels), and
346
+ // their own tag is the truth about where a pick of them runs.
347
+ const byok = pickerEntries(await loadModelsFor(c, 'byok', live)).map((m) => ({ ...m, cls: m.cls || 'byok' }));
348
+ // The Pro class' aliases are a third disjoint id space — `claude --model`
349
+ // resolves them, the pooled catalog and the relay do not — so they are merged
350
+ // into the same list for the same reason byok's are: a class the picker omits
351
+ // is a class the user cannot switch to from the surface that exists to switch
352
+ // models. Each row carries its own `cls`, exactly as the other two do, which
353
+ // is what ENTER reads to move the session BEFORE the pin applies.
354
+ const pro = pickerEntries(await loadModelsFor(c, 'pro', live)).map((m) => ({ ...m, cls: 'pro' }));
355
+
356
+ // One row per id, and a row's OWN class tag wins over the group it arrived
357
+ // in. Both halves are corrections, not tidying:
358
+ //
359
+ // - The byok group is not all byok. `classScopedModels` prepends the pooled
360
+ // rows to it on purpose, so that a session sitting on byok can still see
361
+ // the way back to the pooled lane — and this function's per-group
362
+ // `.map(m => ({...m, cls}))` overwrote that tag, so the SAME Nexus row
363
+ // arrived twice (the pooled group's, and a copy tagged `byok`). ENTER
364
+ // reads `cls` to decide which class to switch to before the pin applies,
365
+ // so the copy was not merely a duplicate line: picking it pinned a pooled
366
+ // id while leaving the session on byok, where the relay parses a bare id
367
+ // as a provider name and 400s.
368
+ // - Deduping by id (first wins, so the class-scoped groups lead) is what
369
+ // keeps that copy off the screen, and what stops any other id being
370
+ // offered twice when two classes advertise it.
371
+ const out = [];
372
+ const seen = new Set();
373
+ for (const row of [...aegis, ...byok, ...pro]) {
374
+ const id = String((row && row.id) || '');
375
+ if (!id || seen.has(id)) continue;
376
+ seen.add(id);
377
+ out.push(row);
378
+ }
379
+ return out;
380
+ }
381
+
382
+ /**
383
+ * One class's catalog, read through whichever loader this host has.
384
+ *
385
+ * `c.listModelsFor(cls)` is the per-class loader app.js provides, and it is
386
+ * preferred because /model is class-scoped: reading the live class's own list
387
+ * is what stops a pin from being validated (and a row from being offered)
388
+ * against a class the next turn will not use.
389
+ *
390
+ * The fallback is not decoration. `loadModels()` is the loader every host has
391
+ * had since the context existed — including hosts and test doubles that predate
392
+ * the per-class one — so when it is the only loader present, the picker is
393
+ * populated from it for the class the session is actually on, and the other
394
+ * class yields nothing rather than a duplicated list. Skipping the fallback is
395
+ * how `/model` renders an empty picker against a healthy account: the list is
396
+ * asked for through a method the host does not have, the miss is swallowed, and
397
+ * "no models advertised" is what the user is told (§P in another guise).
398
+ */
399
+ async function loadModelsFor(c, cls, live) {
400
+ if (typeof c.listModelsFor === 'function') {
401
+ try {
402
+ return (await c.listModelsFor(cls)) || [];
403
+ } catch {
404
+ return [];
405
+ }
406
+ }
407
+ if (cls !== live || typeof c.loadModels !== 'function') return [];
408
+ try {
409
+ return (await c.loadModels()) || [];
410
+ } catch {
411
+ return [];
412
+ }
413
+ }
414
+
415
+ /**
416
+ * The ÆGIS LLM routes are gated on the pooled brain being reachable — exactly
417
+ * as the reference hides its ÆGIS routes when the backend is absent. `hidden`
418
+ * is a function so visibility follows the environment at call time.
419
+ *
420
+ * It reads the *resolved* credential, not the environment: a key saved by
421
+ * `aegiscode login` lives in credentials.json, and checking only
422
+ * `process.env.AEGIS_API_KEY` here hid every AEGIS route from a user who had
423
+ * just successfully set one.
424
+ */
425
+ const cloudReady = () => credentials.hasApiKey();
426
+
427
+ // ── BYOK provider catalog ────────────────────────────────────────────────────
428
+
429
+ /**
430
+ * The BYOK model additions (`client/byok-catalog.js`) — the ids the server's
431
+ * catalog does not name but the vendor serves and the relay forwards, resolved
432
+ * by EXISTENCE through `resolveShared`, never with a fallback copy here.
433
+ *
434
+ * `/byok` reads the server directly rather than through the engine, so without
435
+ * this the CLI's own listing would show fewer models than the CLI's own model
436
+ * picker for the same account — two screens in one program disagreeing, which
437
+ * is the failure this file's sibling brain-catalog module exists to end. The
438
+ * desktop requires the same file from `desktop/lib/local/engine.js`, so the
439
+ * terminal and the window cannot drift either.
440
+ */
441
+ const { withByokAdditions } = require(resolveShared(path.join('client', 'byok-catalog.js')));
442
+
443
+ /**
444
+ * The models the USER declares (`client/user-models.js`) — the same file the
445
+ * desktop's Settings row writes, resolved by existence through the same
446
+ * `resolveShared` path and for the same reason: one store, three writers.
447
+ *
448
+ * `/byok` and `/models` read it here, and the CLI's own engine
449
+ * (`desktop/lib/local/engine.js` `listModels('byok')`, vendored into this
450
+ * package) applies it too, so the terminal's listing and the terminal's picker
451
+ * cannot disagree about which ids this machine offers.
452
+ */
453
+ const {
454
+ withUserModels,
455
+ addUserModel,
456
+ removeUserModel,
457
+ userModelIdsFor,
458
+ userModelsPath,
459
+ } = require(resolveShared(path.join('client', 'user-models.js')));
460
+
461
+ /**
462
+ * The SERVER's full catalog, cached on disk (`client/catalog-client.js`) — the
463
+ * layering that replaces the hand-written list above once the server publishes
464
+ * one. Applied between the shipped additions and the user's overlay: the
465
+ * server's own answer is more current than the list this package was built
466
+ * with, and less specific than an id the user declared themselves.
467
+ *
468
+ * Synchronous and non-throwing by construction: a missing cache means "no
469
+ * extra ids", never a failed `/byok`.
470
+ */
471
+ const catalogClient = require(resolveShared(path.join('client', 'catalog-client.js')));
472
+ const { withCatalog } = catalogClient;
473
+
474
+ /**
475
+ * Ask the VENDOR what it serves (`client/model-discovery.js`), so `/model-add`
476
+ * can offer a list instead of asking the user to recall an id.
477
+ *
478
+ * Same `resolveShared` resolution as its two siblings above: one implementation
479
+ * of "what does this provider's key actually reach", read by both faces. It is
480
+ * loaded at module scope rather than lazily inside the handler because the
481
+ * command needs it to decide what to PROMPT with — a discovery module that
482
+ * loads only after discovery was decided to be possible would be circular.
483
+ *
484
+ * The module does no I/O at load (no key store, no network), so pulling it in
485
+ * with `/help` costs a `require` and nothing else.
486
+ */
487
+ const {
488
+ discoverModels: discoverVendorModels,
489
+ endpointFor: vendorEndpointFor,
490
+ discoverableProviders,
491
+ } = require(resolveShared(path.join('client', 'model-discovery.js')));
492
+
493
+ /**
494
+ * The vendor key for a provider, resolved the way the engine resolves it:
495
+ * the saved provider-key row first, then `~/.aegiscode/.env` (and the shell).
496
+ *
497
+ * Deliberately the same ORDER as `desktop/lib/local/engine.js`'s
498
+ * `providerKeyFromEnv` + `byok:<provider>` lookup, because discovery must use
499
+ * the key the NEXT TURN will use — a listing fetched with a different key than
500
+ * the one the call runs on is a listing of somebody else's catalog. This is
501
+ * read-only: it never writes a key, never logs one, and returns '' when the
502
+ * machine has none, which the caller reports as "no key to ask with".
503
+ */
504
+ function byokKeyForProvider(c, provider) {
505
+ const id = String(provider || '').trim().toLowerCase();
506
+ if (!id) return '';
507
+ try {
508
+ const store = c && c.settings && c.settings();
509
+ if (store && typeof store.rawKey === 'function' && typeof c.byokNamespace === 'function') {
510
+ const saved = store.rawKey(c.byokNamespace(id));
511
+ if (typeof saved === 'string' && saved.trim()) return saved.trim();
512
+ }
513
+ } catch {
514
+ /* a store that throws is a store with no key, not a reason to stop */
515
+ }
516
+ try {
517
+ const { providerKeyFromEnv } = require(resolveShared(path.join('client', 'env-file.js')));
518
+ return (providerKeyFromEnv(id) || {}).key || '';
519
+ } catch {
520
+ return '';
521
+ }
522
+ }
523
+
524
+ /**
525
+ * Ask the provider's own list endpoint, if this machine can. Never throws.
526
+ *
527
+ * `fetchImpl` is injectable through the context so the CLI tests drive a stub
528
+ * and never open a socket; `c.fetchImpl` is undefined in a real run, which is
529
+ * the module's normal `fetch`.
530
+ */
531
+ async function discoverProviderModels(c, provider, key) {
532
+ try {
533
+ return await discoverVendorModels(provider, { key, fetchImpl: c && c.fetchImpl });
534
+ } catch (err) {
535
+ return { ok: false, provider, supported: true, error: (err && err.message) || String(err) };
536
+ }
537
+ }
538
+
539
+ /**
540
+ * The provider's own catalog, best-effort, as `[ids]`. Undefined when the
541
+ * vendor could not be asked — the caller then falls back to a free-form id
542
+ * prompt, because that path works and must keep working offline.
543
+ */
544
+ async function offeredModelIds(c, provider, key) {
545
+ const res = await discoverProviderModels(c, provider, key);
546
+ return res && res.ok && Array.isArray(res.ids) && res.ids.length ? res.ids : undefined;
547
+ }
548
+
549
+ /**
550
+ * One argument string, tokenized with the SAME quote rule the app's own parser
551
+ * uses (`app.js` tokenize): a quoted run is one token and the quotes are not
552
+ * part of it.
553
+ *
554
+ * `_rest` is the raw remainder of the line (app.js parseArgs keeps it
555
+ * verbatim), so the only unambiguous way to type a base URL — `/model-add
556
+ * custom "https://my-vllm.example/v1" sk-… llama-3-70b` — arrives here still
557
+ * wrapped in its quotes. Splitting on whitespace alone stores the quote
558
+ * characters as part of the URL: the row then looks saved while every call on
559
+ * it is refused upstream, which is the silent no-op this whole command exists
560
+ * to avoid. The app's tokenizer is not reachable from here (it is a closure in
561
+ * app.js), so the rule is restated once, beside the only command that needs it.
562
+ */
563
+ function splitCommandWords(rest) {
564
+ const out = [];
565
+ let cur = '';
566
+ let quote = null;
567
+ let has = false;
568
+ for (const ch of String(rest == null ? '' : rest)) {
569
+ if (quote) {
570
+ if (ch === quote) quote = null;
571
+ else cur += ch;
572
+ continue;
573
+ }
574
+ if (ch === '"' || ch === "'") { quote = ch; has = true; continue; }
575
+ if (/\s/.test(ch)) {
576
+ if (cur || has) { out.push(cur); cur = ''; has = false; }
577
+ continue;
578
+ }
579
+ cur += ch;
580
+ has = true;
581
+ }
582
+ if (cur || has) out.push(cur);
583
+ return out;
584
+ }
585
+
586
+ /**
587
+ * The base URL this machine already holds for a provider, or ''.
588
+ *
589
+ * Only `custom` needs it, and only to answer one question: `/model-add custom
590
+ * <word>` with a single leftover word is ambiguous on a machine with no
591
+ * endpoint configured — the word could be the base URL (key and model still to
592
+ * come) or a model id for an endpoint nobody has named — and unambiguous once
593
+ * one IS configured, because then the word can be nothing but a model id.
594
+ */
595
+ function savedByokBaseURL(c, provider) {
596
+ try {
597
+ const store = c && c.settings && c.settings();
598
+ if (!store || typeof store.get !== 'function' || typeof c.byokNamespace !== 'function') return '';
599
+ const row = store.get(c.byokNamespace(provider)) || {};
600
+ return String(row.baseURL || '').trim();
601
+ } catch {
602
+ return '';
603
+ }
604
+ }
605
+
606
+ /**
607
+ * Declare ids into the store, skipping the ones already there. Returns the
608
+ * count added, plus what was skipped and WHY, so the caller can say
609
+ * "3 added, 2 already declared" instead of claiming work it did not do.
610
+ *
611
+ * The cap matters here more than anywhere else: a vendor's list endpoint
612
+ * answers with everything it serves — OpenAI currently returns 100 ids — and
613
+ * the store holds at most 32 per provider by design. Without this the bulk
614
+ * path would report sixty-eight "refused" models, which reads as sixty-eight
615
+ * broken ids rather than one deliberate ceiling. So the cap ends the batch and
616
+ * is reported as itself.
617
+ */
618
+ function addManyUserModels(provider, ids) {
619
+ let added = 0;
620
+ let capped = 0;
621
+ const already = [];
622
+ const failed = [];
623
+ for (const id of ids) {
624
+ try {
625
+ if (addUserModel(provider, id).added) added += 1;
626
+ else already.push(id);
627
+ } catch (err) {
628
+ const message = (err && err.message) || String(err);
629
+ if (/the cap/.test(message)) {
630
+ // Every remaining id would hit the same wall, so stop rather than
631
+ // loop sixty more times to collect sixty copies of one message.
632
+ capped = ids.length - added - already.length - failed.length;
633
+ break;
634
+ }
635
+ failed.push({ id, reason: message });
636
+ }
637
+ }
638
+ return { added, already, failed, capped };
639
+ }
640
+
641
+ /**
642
+ * The server's BYOK provider catalog, or null when it cannot be reached.
643
+ *
644
+ * The catalog is the *server's* answer to "which keys do you accept, for which
645
+ * models, and where do I get one". It is deliberately not key-gated, so this
646
+ * works before an account key exists — which is the whole point, since it is
647
+ * the screen that tells a user which key to go buy. Returning null rather than
648
+ * throwing keeps every caller free to fall back to the prose description it
649
+ * used before the catalog existed.
650
+ */
651
+ async function byokCatalog(client) {
652
+ if (!client || typeof client.byokProviders !== 'function') return null;
653
+ try {
654
+ const data = await client.byokProviders();
655
+ // Refresh the cached artifact in the background when it is stale, BEFORE
656
+ // `withCatalog` reads it. Deliberately not awaited: `/byok` must render on
657
+ // the live payload the call above already returned, and a slow or failing
658
+ // refresh would turn a menu into a spinner. `withCatalog` therefore uses
659
+ // the cache as it stood at the top of this call, and the next one sees the
660
+ // refreshed file — stale-while-revalidate, never stale-instead-of.
661
+ refreshCatalogInBackground(client);
662
+ // Two layers, in this order and for the same reason both exist: the
663
+ // shipped additions this repo maintains (`withByokAdditions`) and then the
664
+ // USER's own declarations (`withUserModels`). The user's layer is applied
665
+ // last because it is the most specific opinion — and because a user who
666
+ // declares an id the shipped list also carries still gets ONE row (both
667
+ // functions append only what is missing).
668
+ //
669
+ // `withCatalog` sits between them: the shipped list first (ids verified by
670
+ // this repo), then whatever the server's catalog adds, then the user. All
671
+ // three append only what is missing and never invent a provider, so the
672
+ // composition is order-independent for correctness and only decides which
673
+ // layer's id wins a collision — most specific last, as documented.
674
+ const providers = withUserModels(
675
+ withCatalog(withByokAdditions((data && data.providers) || [])),
676
+ );
677
+ return providers.length ? providers : null;
678
+ } catch {
679
+ return null;
680
+ }
681
+ }
682
+
683
+ /**
684
+ * Refresh the cached catalog artifact if it is missing or stale.
685
+ *
686
+ * Fire-and-forget by design. Every failure is already absorbed by
687
+ * `catalogClient.refresh` (which never rejects), and this wrapper additionally
688
+ * guards the call itself so a synchronous throw — a bug in a page fetcher —
689
+ * cannot surface as an unhandled rejection that kills the process. An
690
+ * unhandled rejection in a CLI is a crash on `aegiscode -p "..."`, which is a
691
+ * far worse outcome than a catalog that stays a day old.
692
+ *
693
+ * Skips entirely when the cache is fresh, so the common case costs one
694
+ * `statSync` and no network.
695
+ */
696
+ function refreshCatalogInBackground(client) {
697
+ try {
698
+ let stale = true;
699
+ try {
700
+ const hit = catalogClient.read();
701
+ stale = !hit || hit.stale;
702
+ } catch {
703
+ stale = true;
704
+ }
705
+ if (!stale) return null;
706
+ if (typeof client.catalog !== 'function') return null;
707
+
708
+ let etag = null;
709
+ try {
710
+ const hit = catalogClient.read();
711
+ // Revalidating with the last ETag lets a no-change refresh cost a 304
712
+ // instead of a full walk. Only the artifact's own stamp is used; there is
713
+ // no separate etag file to drift out of sync.
714
+ etag = (hit && hit.data && hit.data.snapshot && hit.data.snapshot.etag) || null;
715
+ } catch {
716
+ etag = null;
717
+ }
718
+
719
+ const promise = catalogClient.refresh(async ({ cursor, limit, etag: tag }) => {
720
+ try {
721
+ return await client.catalog('models', { cursor, limit }, { etag: tag || undefined });
722
+ } catch (err) {
723
+ // `apiRequest` treats every non-2xx as an error, and a 304 IS one by
724
+ // that rule — but here it is the success case: the server confirming
725
+ // our cached copy is current. Translating it is the adapter's job
726
+ // because only the caller knows a 304 is meaningful for this request.
727
+ if (err && err.status === 304) return { notModified: true };
728
+ throw err;
729
+ }
730
+ }, { etag });
731
+
732
+ // Belt and braces: `refresh` never rejects, but if that ever regresses the
733
+ // CLI must not die. Attaching a no-op catch keeps the promise "handled".
734
+ if (promise && typeof promise.catch === 'function') promise.catch(() => {});
735
+ return promise;
736
+ } catch {
737
+ return null;
738
+ }
739
+ }
740
+
741
+ /**
742
+ * Resolve a typed provider id against the catalog.
743
+ *
744
+ * Exact id first, then a unique case-insensitive match on id, label or alias, so
745
+ * `/byok-set OpenAI` and `/byok-set together-ai` both land. A non-unique match
746
+ * returns `{ ambiguous }` rather than silently picking one: storing a key
747
+ * against the wrong provider is the failure this whole path exists to prevent,
748
+ * and it is not visible until a call 401s upstream.
749
+ */
750
+ function findByokProvider(providers, typed) {
751
+ const want = String(typed || '').trim().toLowerCase();
752
+ if (!providers) return { provider: null, exact: false };
753
+ const exact = providers.find((p) => p.id === want);
754
+ if (exact) return { provider: exact, exact: true };
755
+ const loose = providers.filter((p) => {
756
+ const names = [p.id, p.label, ...(p.aliases || [])].filter(Boolean);
757
+ return names.some((n) => String(n).toLowerCase() === want);
758
+ });
759
+ if (loose.length === 1) return { provider: loose[0], exact: false };
760
+ if (loose.length > 1) return { ambiguous: loose.map((p) => p.id) };
761
+ return { provider: null, exact: false };
762
+ }
763
+
764
+ /** One catalog row: id, whether it is already set, its models, and key guidance.
765
+ *
766
+ * Every line is an array of span objects, never a plain string — panel/paint
767
+ * (`screen.js` `padLine`/`paint`) iterate a line as spans and read `.t`/`.w`
768
+ * off each entry. A plain string here gets walked character-by-character
769
+ * instead, each "span" comes out `{t: undefined, w: undefined}`, and paint's
770
+ * `sp.s + sp.t` prints the literal text "NaN" once per character.
771
+ */
772
+ function byokProviderLines(providers) {
773
+ const lines = [];
774
+ for (const p of providers) {
775
+ const state = p.configured
776
+ ? span(C.green, `set${p.masked ? ` (${p.masked})` : ''}`)
777
+ : span(C.gray, 'not set');
778
+ const row = [span(C.gold + BOLD, ` ${p.id}`)];
779
+ if (p.label) row.push(span(C.gray, ` — ${p.label}`));
780
+ row.push(span('', ' '), state);
781
+ lines.push(row);
782
+ // `models` arrives as bare ids. The catalog used to be read here as if each
783
+ // one were an object with `.id`, which silently rendered nothing — a
784
+ // provider listed with an empty model line reads as "no models", not as a
785
+ // bug, so tolerate both shapes rather than repeat the mistake.
786
+ const models = (p.models || [])
787
+ .map((m) => (typeof m === 'string' ? m : m && m.id))
788
+ .filter(Boolean);
789
+ if (models.length) lines.push([span(C.gray, ` models: ${models.join(', ')}`)]);
790
+ if (p.key_prefix) lines.push([span(C.gray, ` key starts with ${p.key_prefix}`)]);
791
+ if (p.key_url) lines.push([span(C.gray, ` ${p.key_url}`)]);
792
+ }
793
+ return lines;
794
+ }
795
+
796
+ // ── account key + cloud sync handlers ────────────────────────────────────────
797
+
798
+ /** The account-key panel body, shared by /key, /login and /cloud. */
799
+ function keyPanelLines(c, title = 'AEGIS account key') {
800
+ const st = c.keyStatus();
801
+ const lines = [
802
+ [span(C.gold + BOLD, title), span(BOLD_OFF, '')],
803
+ [span(C.gray, '─'.repeat(34))],
804
+ [
805
+ span(st.configured ? C.green : C.coral, ` ${st.configured ? '✔' : '⚠'}`),
806
+ span(C.white, ' key: '),
807
+ span(st.configured ? C.white : C.gray, st.configured ? maskKey(st.key) : 'not set'),
808
+ span(C.gray, ` (${credentials.sourceLabel(st.source)})`),
809
+ ],
810
+ [span(C.gray, ` stored in: ${st.path}${st.fileMode ? ` ${st.fileMode}` : ''}`)],
811
+ ];
812
+ if (st.verifiedAt) lines.push([span(C.gray, ` verified: ${st.verifiedAt}`)]);
813
+ if (st.account && (st.account.plan || st.account.email)) {
814
+ lines.push([
815
+ span(C.gray, ' account: '),
816
+ span(C.white, [st.account.plan, st.account.email].filter(Boolean).join(' · ')),
817
+ ]);
818
+ }
819
+ lines.push([
820
+ span(C.gray, ' memory: '),
821
+ span(st.memoryToken ? C.green : C.gray, st.memoryToken ? 'token held (cloud sync ready)' : 'no token yet'),
822
+ ]);
823
+ if (!st.configured) {
824
+ lines.push([span(C.gray, '')]);
825
+ lines.push([span(C.white, ' Set one with /key <api_key>, or press Enter on /key to paste it.')]);
826
+ lines.push([span(C.gray, ` Free key: ${signupUrl('key_status')}`)]);
827
+ }
828
+ if (st.legacyPlaintext) {
829
+ lines.push([span(C.gray, '')]);
830
+ lines.push([
831
+ span(C.coral, ' ⚠ a plaintext copy of the key is still in config.json (another AEGIS CLI wrote it).'),
832
+ ]);
833
+ lines.push([span(C.gray, ' Re-save with /key <api_key> and delete that block when convenient.')]);
834
+ }
835
+ return lines;
836
+ }
837
+
838
+ /**
839
+ * Take a key from the argument or an echo-off prompt, save it, and report what
840
+ * the account said. Shared by `/key`, `/login` and `/cloud key` so all three
841
+ * behave identically — the whole point is that there is one way to set a key.
842
+ */
843
+ async function applyAccountKey(c, raw, { label = 'AEGIS API key' } = {}) {
844
+ let key = String(raw || '').trim();
845
+ if (!key) {
846
+ key = await c.readSecret(`${label} (kept off screen, Enter to cancel): `);
847
+ }
848
+ if (!key) {
849
+ note(c, 'no key given — /key <api_key> takes it inline, or press Enter on a bare /key to paste it');
850
+ return { ok: false };
851
+ }
852
+ const res = await c.setApiKey(key);
853
+ if (!res.ok) {
854
+ note(c, res.message || 'that key could not be saved');
855
+ return res;
856
+ }
857
+ if (res.error) {
858
+ note(c, `saved, but the account check failed: ${res.error.message}`);
859
+ note(c, 'the key is stored — /key status shows it; re-run /key <api_key> if it was mistyped');
860
+ return res;
861
+ }
862
+ const acct = (res.account && (res.account.email || res.account.plan)) || null;
863
+ done(c, `AEGIS key saved to ${res.path}${acct ? ` — signed in as ${acct}` : ' and verified'}`);
864
+ // The catalog is key-gated, so a freshly authenticated session should offer
865
+ // /model's picker without the user having to know to re-run it. Counted from
866
+ // the loader's return value (through pickerEntries, the same filter the
867
+ // picker applies) rather than `c.state().models`, so the number matches what
868
+ // the picker will actually offer.
869
+ try {
870
+ const n = pickerEntries(await loadModels(c)).length;
871
+ if (n) note(c, `${n} pinnable model${n === 1 ? '' : 's'} available — /model to pin one`);
872
+ } catch {}
873
+ return res;
874
+ }
875
+
876
+ /** Human token count for the sync quota: 1000000 -> "1M", 42800 -> "43k".
877
+ * The ceiling is denominated in tokens (aegis1 FREE_SYNC_TOKENS = 1 MB,
878
+ * PRO_SYNC_TOKENS = 10 MB), which for stored prose is about one per
879
+ * character — "1000000" at a glance tells a user nothing about how close they
880
+ * are to it. */
881
+ function fmtQuotaTokens(n) {
882
+ const v = Number(n);
883
+ if (!Number.isFinite(v)) return '?';
884
+ if (v >= 1e6) return `${(v / 1e6).toFixed(v % 1e6 === 0 ? 0 : 1)}M`;
885
+ if (v >= 1e4) return `${Math.round(v / 1e3)}k`;
886
+ return fmtTokens(v);
887
+ }
888
+
889
+ /**
890
+ * The persisting-memory gate, read off the command context (the live app
891
+ * exposes `cloudSyncState()`) with a fallback for callers that only pass the
892
+ * older boolean probe — `/cloud` and `/sync` predate the rename, and a stub
893
+ * context in a test must not have to grow a method to render a panel.
894
+ */
895
+ function memoryGate(c) {
896
+ if (c && typeof c.cloudSyncState === 'function') {
897
+ try {
898
+ return c.cloudSyncState();
899
+ } catch {
900
+ /* fall through to the boolean */
901
+ }
902
+ }
903
+ const enabled =
904
+ c && typeof c.cloudSyncEnabled === 'function' ? c.cloudSyncEnabled() === true : true;
905
+ return { enabled, source: 'default' };
906
+ }
907
+
908
+ /**
909
+ * Flip the gate through the command context (app.js's `setCloudSync` is
910
+ * `config.setMemoryPersist`), which is what keeps the setting and the running
911
+ * session agreeing. Guarded because a context stub that never flips anything
912
+ * still has to be able to *run* the handler — the command smoke test drives
913
+ * every handler with no arguments.
914
+ */
915
+ function setMemoryGate(c, on) {
916
+ if (c && typeof c.setCloudSync === 'function') return c.setCloudSync(on);
917
+ try {
918
+ return setMemoryPersist(on);
919
+ } catch {
920
+ return null;
921
+ }
922
+ }
923
+
924
+ /**
925
+ * The persisting-memory block every cloud surface shows: the switch, the
926
+ * ceiling, and — the part that was missing — what a stopped write does and
927
+ * does not cost.
928
+ *
929
+ * The honesty requirement is not cosmetic. aegis1 meters WRITES only
930
+ * (`_memory_sync_access`), so a free account that passes ~1 MB of transcript
931
+ * keeps every entry it stored and simply stops accumulating new ones. The old
932
+ * rollout printed nothing at all, so "memory is free with any account" and
933
+ * "nothing is being stored any more" were both true and indistinguishable.
934
+ * These lines make the ceiling a state the user can see: the number, whose
935
+ * limit it is, and the one sentence that separates the working half (reads)
936
+ * from the stopped half (new writes).
937
+ */
938
+ function memoryStatusLines(c) {
939
+ const gate = memoryGate(c);
940
+ const st = cloudsync.status();
941
+ const q = st.quota;
942
+ const used = q && q.used != null ? fmtQuotaTokens(q.used) : null;
943
+ const limit = q && q.limit != null ? fmtQuotaTokens(q.limit) : null;
944
+ const how =
945
+ gate.source === 'legacy'
946
+ ? ' (kept from your old cloudSync setting)'
947
+ : gate.source === 'default'
948
+ ? ' (default)'
949
+ : '';
950
+ const rows = [
951
+ // Both names, one gate. The commit that flipped the default renamed the
952
+ // panel to say what is being stored, but `/sync`, `/cloud sync` and the
953
+ // docs all still call it cloud sync — a panel that only answers to its new
954
+ // name makes the setting unfindable to anyone who learned the old one.
955
+ [span(C.white + BOLD, 'Persisting memory'), span(C.gray, ' · Cloud sync'), span(BOLD_OFF, '')],
956
+ [span(C.gray, '─'.repeat(34))],
957
+ [
958
+ span(C.white, ` ${gate.enabled ? 'on' : 'off'}`),
959
+ span(C.gray, `${how} · ${gate.enabled ? 'each session is stored so an interrupted turn can be resumed' : 'nothing new is stored'}`),
960
+ ],
961
+ ];
962
+ if (limit) {
963
+ rows.push([
964
+ span(C.gray, ' quota: '),
965
+ span(C.white, `${used} of ${limit} tokens synced`),
966
+ span(C.gray, ' (aegis1 charges writes; reads are always served)'),
967
+ ]);
968
+ } else {
969
+ rows.push([span(C.gray, ' quota: not reported yet — /sync now asks the server for the current numbers')]);
970
+ }
971
+ if (st.overQuota) {
972
+ rows.push([span(C.coral, ' writes: paused — the plan’s ceiling is reached, so new memory is not being stored')]);
973
+ rows.push([span(C.green, ' reads: still work — everything already stored stays readable (/aegis-recall <topic>)')]);
974
+ // Two rows, not one. This was a single 92-cell line ending in
975
+ // "or /cloud memory off to stop trying", and panel rows go through
976
+ // `padLine()`, which TRUNCATES at `cols` instead of wrapping — so at 80
977
+ // columns the escape hatch was cut off the end and never rendered. The URL
978
+ // gets its own row for the same reason: it is the actionable half, and
979
+ // truncation is survivable in prose and fatal in a URL. The rows are 76 and
980
+ // 45 cells of 80, both asserted by test/cli-commands.test.mjs.
981
+ rows.push([span(C.gray, ` free room at ${goUrl('upgrade', 'cloud_quota')}`)]);
982
+ rows.push([span(C.gray, ' or /cloud memory off to stop trying')]);
983
+ }
984
+ if (gate.enabled && st.pending > 0) {
985
+ rows.push([span(C.gray, ` pending: ${st.pending} session(s) waiting to sync`)]);
986
+ }
987
+ rows.push([span(C.gray, ` /cloud memory on | off · /sync now pushes once by hand`)]);
988
+ return rows;
989
+ }
990
+
991
+ /** Push + pull once, and report the counts (or the quota refusal). */
992
+ async function runCloudSync(c, o = {}) {
993
+ if (!c.client.apiKey) {
994
+ note(c, `no key — ${credentials.HOW_TO_SET}`);
995
+ return null;
996
+ }
997
+ const res = await c.withWorking(() => cloudsync.syncNow(c.client, o));
998
+ const pushed = (res.push && res.push.pushed) || [];
999
+ const failed = [...((res.push && res.push.failed) || []), ...((res.pull && res.pull.failed) || [])];
1000
+ const pulled = (res.pull && res.pull.imported) || 0;
1001
+ if (pushed.length) {
1002
+ done(c, `pushed ${pushed.length} session${pushed.length === 1 ? '' : 's'} (${pushed[0].messages} messages in the first)`);
1003
+ } else if (res.push && res.push.skipped && res.push.skipped.length) {
1004
+ note(c, `${res.push.skipped.length} session(s) had nothing to send`);
1005
+ } else {
1006
+ note(c, 'nothing to push — every local session is already in the cloud');
1007
+ }
1008
+ if (pulled) done(c, `pulled ${pulled} record${pulled === 1 ? '' : 's'} into the local store — /resume lists them`);
1009
+ else if (res.pull && res.pull.ok) note(c, `cloud has ${res.pull.remote || 0} session(s); nothing newer locally`);
1010
+ for (const f of failed) {
1011
+ note(c, `${f.kind === 'quota' ? 'quota' : 'failed'}: ${f.message}`);
1012
+ if (f.hint) note(c, f.hint);
1013
+ }
1014
+ return res;
1015
+ }
1016
+
1017
+ /**
1018
+ * Hook config and repo-hook install come from the SHARED module
1019
+ * (`client/hooks.js`, staged to vendor/client/hooks.js in a package), because
1020
+ * the desktop app reads the same files and installs the same `.githooks/`.
1021
+ *
1022
+ * This file used to carry a private `readHooks()`/`hookStats()`. Two copies of
1023
+ * "which settings files count" is how the terminal and the GUI end up
1024
+ * describing one machine differently, and the private copy was joined with the
1025
+ * HOST's separator — so a Windows path was handled correctly and could not be
1026
+ * tested anywhere but Windows.
1027
+ */
1028
+ const hooksLib = require(resolveShared(path.join('client', 'hooks.js')));
1029
+
1030
+ function readHooks() {
1031
+ return hooksLib.readHookConfig();
1032
+ }
1033
+
1034
+ function hookStats(hooks) {
1035
+ return hooksLib.hookStats(hooks);
1036
+ }
1037
+
1038
+ /** Scan the standard skill dirs for SKILL.md files. */
1039
+ function scanSkills() {
1040
+ const dirs = [
1041
+ path.join(os.homedir(), '.aegis', 'skills'),
1042
+ path.join(process.cwd(), '.aegis', 'skills'),
1043
+ path.join(os.homedir(), '.aegiscode', 'skills'),
1044
+ path.join(process.cwd(), '.aegiscode', 'skills'),
1045
+ path.join(os.homedir(), '.claude', 'skills'),
1046
+ ];
1047
+ const found = [];
1048
+ for (const dir of dirs) {
1049
+ const source = dir.startsWith(process.cwd()) ? 'project' : 'user';
1050
+ let names = [];
1051
+ try {
1052
+ names = fs.readdirSync(dir, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => d.name);
1053
+ } catch { continue; }
1054
+ for (const name of names) {
1055
+ const skillPath = path.join(dir, name, 'SKILL.md');
1056
+ try {
1057
+ const raw = fs.readFileSync(skillPath, 'utf8');
1058
+ const desc = (/^description:\s*(.+)$/m.exec(raw) || [])[1] || '';
1059
+ found.push({ source, name, namespace: null, description: desc.trim(), path: skillPath, content: raw });
1060
+ } catch {}
1061
+ }
1062
+ }
1063
+ return found;
1064
+ }
1065
+
1066
+ // ── Command definitions ───────────────────────────────────────────────────────
1067
+ // Order here is the palette order.
1068
+
1069
+ const COMMANDS = [
1070
+ // ── session & context ───────────────────────────────────────────────────────
1071
+ {
1072
+ name: 'run', hint: '', category: 'workspace',
1073
+ desc: "Launch and drive this project's app to see a change working",
1074
+ handler: async (c) => {
1075
+ const cmd = detectDevCommand(process.cwd());
1076
+ if (!cmd) {
1077
+ note(c, 'No dev command detected (no package.json scripts, go.mod, Cargo.toml or Makefile). Try /init first.');
1078
+ c.render();
1079
+ return true;
1080
+ }
1081
+ note(c, `Running ${cmd} in ${shortCwd()} — output streams below, Esc stops it.`);
1082
+ const job = runDevServer(cmd, {
1083
+ cwd: process.cwd(),
1084
+ onLine: (line) => c.push({ role: 'note', text: ` ${line}` }),
1085
+ });
1086
+ // Bind the job to the session so the status line draws "esc to stop" and
1087
+ // Esc actually stops it (the reference's openStream/closeStream contract).
1088
+ if (!job.label) job.label = cmd;
1089
+ c.openStream(job);
1090
+ job.done.then(({ code, stopped }) => {
1091
+ c.closeStream(job);
1092
+ done(c, stopped ? `${cmd} stopped` : `${cmd} exited (code ${code})`);
1093
+ c.render();
1094
+ });
1095
+ c.render();
1096
+ return true;
1097
+ },
1098
+ },
1099
+ {
1100
+ name: 'schedule', hint: '', category: 'session',
1101
+ desc: 'Create, update, list, or run scheduled cloud agents (routines)',
1102
+ handler: async (c) => {
1103
+ note(c, 'Scheduled routines run on the AEGIS cloud. Sign in with `aegis login`, then manage routines at aegiscloud.org.');
1104
+ c.render();
1105
+ return true;
1106
+ },
1107
+ },
1108
+ {
1109
+ name: 'build', aliases: ['forge'], args: ['task'], hint: '<description>', category: 'workspace',
1110
+ desc: 'Build an app with the agent loop — /build <what to build>',
1111
+ handler: async (c, args) => {
1112
+ const task = (args._rest || args.task || '').trim();
1113
+ if (!task) {
1114
+ note(c, 'Usage: /build <what to build>');
1115
+ note(c, 'Example: /build a REST API for a todo app');
1116
+ c.render();
1117
+ return true;
1118
+ }
1119
+ note(c, '⬡ AEGIS BUILD');
1120
+ note(c, `Task: ${task}`);
1121
+ c.render();
1122
+ await c.runPrompt(`Build the following, creating every file it needs and running the build to verify it works: ${task}`);
1123
+ return true;
1124
+ },
1125
+ },
1126
+ {
1127
+ name: 'cd', args: ['path'], hint: '<path>', category: 'workspace',
1128
+ desc: 'Move this session to a new working directory',
1129
+ handler: async (c, args) => {
1130
+ const dir = args.path || (args._rest || '').trim();
1131
+ if (!dir) { note(c, 'Usage: /cd <path>'); c.render(); return true; }
1132
+ try {
1133
+ process.chdir(dir);
1134
+ c.ctx.cwd = process.cwd();
1135
+ updateConfig({ lastCwd: process.cwd() });
1136
+ note(c, `Changed directory to ${process.cwd()}`);
1137
+ } catch (e) {
1138
+ note(c, `/cd: ${e.message}`);
1139
+ }
1140
+ c.render();
1141
+ return true;
1142
+ },
1143
+ },
1144
+ {
1145
+ name: 'copy', aliases: ['cp'], args: ['n'], hint: '[N]', category: 'data',
1146
+ desc: "Copy the last response to the clipboard",
1147
+ handler: async (c, args) => {
1148
+ const n = parseInt(args.n || '1', 10) || 1;
1149
+ const text = lastAssistantText(c.transcript, n);
1150
+ if (!text) { note(c, 'Nothing to copy yet.'); c.render(); return true; }
1151
+ const r = copyToClipboard(text);
1152
+ if (r.ok) {
1153
+ note(c, r.via.startsWith('tool:')
1154
+ ? `Copied the last response to the clipboard (${r.via.split(':')[1]}).`
1155
+ : `No clipboard tool found — response saved to ${r.path}`);
1156
+ } else {
1157
+ note(c, 'Clipboard unavailable; nothing copied.');
1158
+ }
1159
+ c.render();
1160
+ return true;
1161
+ },
1162
+ },
1163
+ {
1164
+ name: 'clear', aliases: ['cls'], hint: '', category: 'session',
1165
+ desc: 'Start a new session with empty context',
1166
+ handler: async (c) => {
1167
+ c.transcript.length = 0;
1168
+ // Prune the session's history rows so /cost resets with /clear.
1169
+ pruneSessionHistory(c.sessionId);
1170
+ // Emptying the transcript is only half a clear: a transport that keeps
1171
+ // its own memory of this conversation (the Pro class's `claude` child
1172
+ // session) still holds the turns that were just erased, and would answer
1173
+ // from them on the next turn. Clearing the transcript our loop reads is
1174
+ // exactly the case where the other half must be dropped too.
1175
+ if (typeof c.clearConversationMemory === 'function') c.clearConversationMemory();
1176
+ note(c, 'Session cleared — transcript empty.');
1177
+ c.render();
1178
+ return true;
1179
+ },
1180
+ },
1181
+ {
1182
+ name: 'compact', hint: '', category: 'session',
1183
+ desc: 'Compact the conversation history',
1184
+ handler: async (c) => {
1185
+ const has = c.transcript.some((m) => m.role === 'user' || m.role === 'assistant');
1186
+ if (!has) { note(c, 'Nothing to compact yet.'); c.render(); return true; }
1187
+ note(c, 'Compacting conversation history…');
1188
+ c.render();
1189
+ const summary = await c.withWorking((signal) =>
1190
+ summarizeTranscript(c.transcript, {
1191
+ callModel: (p, opts) => c.ask(p, opts).then((r) => r.text),
1192
+ model: c.ctx.model,
1193
+ signal,
1194
+ }));
1195
+ if (summary === null) { note(c, 'Compaction cancelled.'); c.render(); return true; }
1196
+ c.transcript.length = 0;
1197
+ note(c, 'Compacted. Earlier context summarized into the message below.');
1198
+ c.transcript.push({ role: 'user', text: summary });
1199
+ c.render();
1200
+ return true;
1201
+ },
1202
+ },
1203
+ {
1204
+ name: 'cost', hint: '', category: 'data',
1205
+ desc: 'Show the cost of the current session',
1206
+ handler: async (c) => {
1207
+ const agg = aggregateSessionUsage(c.sessionId);
1208
+ const acct = agg.entries
1209
+ ? accountingFromUsage(agg.usage, c.ctx.model, {
1210
+ exchanges: agg.entries,
1211
+ real: agg.real,
1212
+ costUsd: agg.real && agg.costUsd ? agg.costUsd : undefined,
1213
+ })
1214
+ : sessionAccounting(c.transcript, c.ctx.model);
1215
+ panel(c, panels.buildCost({ ...c.state(), contextWindow: acct.contextWindow, costEur: acct.cost }, c.ctx));
1216
+ c.render();
1217
+ return true;
1218
+ },
1219
+ },
1220
+ {
1221
+ name: 'context', hint: '', category: 'session',
1222
+ desc: 'Show context usage for the current session',
1223
+ handler: async (c) => {
1224
+ const acct = sessionAccounting(c.transcript, c.ctx.model);
1225
+ panel(c, panels.buildContext({ ...c.state(), contextWindow: acct.contextWindow }, c.ctx));
1226
+ c.render();
1227
+ return true;
1228
+ },
1229
+ },
1230
+ {
1231
+ name: 'ping', args: ['mode', 'seconds'], hint: '[off|bell|notify|both] [seconds] | test', category: 'model',
1232
+ desc: 'Alert me when a long turn finishes, if I am looking elsewhere',
1233
+ handler: async (c, args) => {
1234
+ const cfg = loadConfig();
1235
+ const raw = ((args._rest || '').trim()).split(/\s+/).filter(Boolean);
1236
+ const first = (raw[0] || '').toLowerCase();
1237
+ const mode = normalizePingMode(cfg.ping);
1238
+ const seconds = normalizePingSeconds(cfg.pingMinSeconds);
1239
+
1240
+ // No argument: report the state AND the vocabulary, so the command is its
1241
+ // own help. Silence here would be indistinguishable from a broken config.
1242
+ if (!first) {
1243
+ note(c, `[ping] ${mode} — a turn longer than ${seconds}s raises a terminal notification.`);
1244
+ note(c, ` /ping ${PING_MODES.filter((m) => m !== mode).join('|')} ${mode === 'off' ? 'turn it back on' : 'change the channel'}`);
1245
+ note(c, ` /ping <mode> <seconds> move the threshold (0 pings every turn)`);
1246
+ note(c, ' /ping test fire one now, to check this terminal supports it');
1247
+ c.render();
1248
+ return true;
1249
+ }
1250
+
1251
+ if (first === 'test') {
1252
+ const text = buildPing({ mode: mode === 'off' ? DEFAULT_PING_MODE : mode });
1253
+ // The test deliberately ignores the threshold and the abort rule — it is
1254
+ // the user asking "does this terminal show anything?", and the only
1255
+ // condition worth keeping is the one that makes the answer meaningful.
1256
+ const wrote = process.stdout.isTTY ? writePing(process.stdout, text) : false;
1257
+ note(c, wrote
1258
+ ? '[ping] sent one just now. If nothing appeared or sounded, this terminal implements neither OSC 9 nor OSC 777 — /ping bell is the fallback.'
1259
+ : '[ping] nothing sent: stdout is not a TTY (a piped or headless run has no one to notify).');
1260
+ c.render();
1261
+ return true;
1262
+ }
1263
+
1264
+ if (!PING_MODES.includes(first)) {
1265
+ note(c, `Unknown ping mode "${raw[0]}". Use ${PING_MODES.join(', ')}.`);
1266
+ c.render();
1267
+ return true;
1268
+ }
1269
+
1270
+ const patch = { ping: first };
1271
+ if (raw[1] != null) {
1272
+ const n = Number(raw[1]);
1273
+ if (!Number.isFinite(n) || n < 0) {
1274
+ note(c, `"${raw[1]}" is not a number of seconds. Use /ping ${first} 30.`);
1275
+ c.render();
1276
+ return true;
1277
+ }
1278
+ patch.pingMinSeconds = normalizePingSeconds(n);
1279
+ }
1280
+ updateConfig(patch);
1281
+
1282
+ if (first === 'off') {
1283
+ note(c, '[ping] off — no notice will be raised, and nothing is reported as sent.');
1284
+ } else {
1285
+ note(c, `[ping] ${first} — turns longer than ${normalizePingSeconds(patch.pingMinSeconds ?? cfg.pingMinSeconds)}s will notify you.`);
1286
+ note(c, ' Escape never pings (you were watching), and neither does a piped or headless run.');
1287
+ }
1288
+ c.render();
1289
+ return true;
1290
+ },
1291
+ },
1292
+ {
1293
+ name: 'todos', aliases: ['todo'], args: ['sub', 'text'], hint: '[add <text> | done <n|text> | clear]', category: 'session',
1294
+ desc: 'A session todo list that survives compaction',
1295
+ handler: async (c, args) => {
1296
+ const sub = (args.sub || '').toLowerCase();
1297
+ const rest = (args._rest || '').trim();
1298
+ // Everything after the subcommand. `_rest` is the whole line, so
1299
+ // `/todos add buy milk` would otherwise store the literal string
1300
+ // "add buy milk" — the subcommand has to come off first.
1301
+ const tail = rest.replace(/^\S+\s*/, '');
1302
+
1303
+ if (!sub) {
1304
+ panel(c, formatTodos());
1305
+ note(c, ` ${todosFile()}`);
1306
+ note(c, ' /todos add <text> · /todos done <n|text> · /todos clear');
1307
+ c.render();
1308
+ return true;
1309
+ }
1310
+
1311
+ if (sub === 'add') {
1312
+ const res = addTodo(tail);
1313
+ if (res.error) { note(c, res.error); c.render(); return true; }
1314
+ panel(c, formatTodos(res.list));
1315
+ c.render();
1316
+ return true;
1317
+ }
1318
+
1319
+ if (sub === 'done' || sub === 'do') {
1320
+ const res = completeTodo(tail);
1321
+ if (res.error) { note(c, res.error); c.render(); return true; }
1322
+ note(c, `[todos] "${res.item.text}" is now ${res.item.done ? 'done' : 'open'}.`);
1323
+ panel(c, formatTodos(res.list));
1324
+ c.render();
1325
+ return true;
1326
+ }
1327
+
1328
+ if (sub === 'clear') {
1329
+ clearTodos();
1330
+ note(c, '[todos] cleared.');
1331
+ c.render();
1332
+ return true;
1333
+ }
1334
+
1335
+ note(c, `Unknown /todos subcommand "${args.sub}". Use add, done or clear.`);
1336
+ c.render();
1337
+ return true;
1338
+ },
1339
+ },
1340
+ {
1341
+ name: 'config', args: ['key', 'value'], hint: '[<key> | <key> <value> | reset <key>]', category: 'session',
1342
+ desc: 'Show or change any setting, and say which store holds it',
1343
+ handler: async (c, args) => {
1344
+ const rest = (args._rest || '').trim();
1345
+ const key = (args.key || '').trim();
1346
+ // The value is everything after the key, not the next token: a string
1347
+ // setting may contain spaces, and `_rest` is the whole line.
1348
+ const value = rest.replace(/^\S+\s*/, '');
1349
+
1350
+ if (!key) {
1351
+ // The list summarizes structured values rather than dumping them —
1352
+ // `models` is a model table and `updateCheck` is an object, and printing
1353
+ // them whole is how this command becomes unreadable.
1354
+ panel(c, formatConfigRows(configRows()));
1355
+ note(c, ' /config <key> show one value in full');
1356
+ note(c, ' /config <key> <value> set it (true/false/null, numbers, JSON, or text)');
1357
+ note(c, ' /config reset <key> back to the shipped value');
1358
+ note(c, ' "shared" keys live in the store AEGIS Desktop writes too; "host" keys are this shell\'s own.');
1359
+ c.render();
1360
+ return true;
1361
+ }
1362
+
1363
+ if (key === 'reset') {
1364
+ const res = resetConfigValue(value);
1365
+ if (res.error) { note(c, res.error); c.render(); return true; }
1366
+ note(c, `[config] ${res.key} reset to ${summarizeValue(res.value)} (${res.store}).`);
1367
+ c.render();
1368
+ return true;
1369
+ }
1370
+
1371
+ if (!value) {
1372
+ const cfg = loadConfig();
1373
+ if (!Object.prototype.hasOwnProperty.call(cfg, key)) {
1374
+ note(c, `unknown config key "${key}" — run /config to list the keys`);
1375
+ c.render();
1376
+ return true;
1377
+ }
1378
+ note(c, `${key} (${configStore(key)}):`);
1379
+ c.push({ role: 'panel', lines: fullValue(cfg[key]).split('\n').map((l) => ` ${l}`) });
1380
+ c.render();
1381
+ return true;
1382
+ }
1383
+
1384
+ const res = setConfigValue(key, value);
1385
+ if (res.error) { note(c, res.error); c.render(); return true; }
1386
+ note(c, `[config] ${res.key} = ${summarizeValue(res.value)} (${res.store}).`);
1387
+ // A model/class/effort change is a live session decision, not just a file
1388
+ // write; say so rather than leaving the user to wonder when it applies.
1389
+ if (['model', 'currentModelId', 'modelClass', 'effort', 'themeIndex', 'vim'].includes(res.key)) {
1390
+ // ...and for `effort` the session value is written here, not just
1391
+ // promised. `setConfigValue` touches the file only, so the note used to
1392
+ // announce a change that the very next turn did NOT make: the session
1393
+ // kept its old rung until a relaunch, which is one more way `/effort`
1394
+ // appeared to do nothing. Floored through effortRung, so a hand-written
1395
+ // `/config effort ultra` cannot put a rung on the wire that the engine
1396
+ // does not know.
1397
+ if (res.key === 'effort') {
1398
+ c.ctx.effort = effortRung(res.value);
1399
+ // Persist the FLOORED rung, not the raw argument: `effort` is a
1400
+ // shared key AEGIS Desktop reads too, and writing `bogus` would put a
1401
+ // level in that file which every reader has to floor again. rungTaken
1402
+ // reports the correction rather than letting the note claim a value
1403
+ // the turn did not take.
1404
+ if (c.ctx.effort !== String(res.value).toLowerCase()) {
1405
+ c.saveConfig({ effort: c.ctx.effort });
1406
+ note(c, ` "${res.value}" is not a level this build sends — recorded as ${c.ctx.effort}.`);
1407
+ }
1408
+ }
1409
+ note(c, ` This takes effect on the next turn; /${res.key === 'currentModelId' ? 'model' : res.key} shows the live session value.`);
1410
+ }
1411
+ c.render();
1412
+ return true;
1413
+ },
1414
+ },
1415
+ {
1416
+ name: 'effort', args: ['level'], hint: '[low|medium|high]', category: 'model',
1417
+ desc: 'Set the token budget the pool sizes each turn from',
1418
+ handler: async (c, args) => {
1419
+ const level = (args.level || '').toLowerCase();
1420
+ // Validated against EFFORT_LEVELS, which IS the picker's value list
1421
+ // (overlays.EFFORT_VALUES, aliased above) — the same array the rows are
1422
+ // drawn from, so a level the picker offers can never be rejected here.
1423
+ if (level && level !== 'auto' && !EFFORT_LEVELS.includes(level)) {
1424
+ note(c, `Unknown effort level "${args.level}". Use ${EFFORT_LEVELS.join(', ')}.`);
1425
+ c.render();
1426
+ return true;
1427
+ }
1428
+ if (!level) {
1429
+ // The picker opens on the rung actually in force; a session whose
1430
+ // config predates the default lands on high, which is what the engine
1431
+ // applies to an unstored value.
1432
+ c.openOverlay({ type: 'effort', sel: Math.max(0, EFFORT_LEVELS.indexOf(c.ctx.effort || 'high')) });
1433
+ return true;
1434
+ }
1435
+ // `auto` is retired, not a fourth rung: it pinned nothing, and a fresh
1436
+ // install therefore sent no effort and the knob did nothing. It is still
1437
+ // ACCEPTED so an old habit (or a script) is not a hard error — it now
1438
+ // resolves to the default rung, and says so.
1439
+ const pinned = level === 'auto' ? 'high' : level;
1440
+ c.ctx.effort = pinned;
1441
+ c.saveConfig({ effort: pinned });
1442
+ note(c, level === 'auto'
1443
+ ? `effort: auto is retired — high is the default, and it is what this session now sends`
1444
+ : `Effort level: ${pinned} — the pool sizes this turn's token budget from it`);
1445
+ c.render();
1446
+ return true;
1447
+ },
1448
+ },
1449
+ {
1450
+ name: 'exit', aliases: ['quit'], hint: '', category: 'session',
1451
+ desc: 'Exit the CLI',
1452
+ handler: async () => false,
1453
+ },
1454
+ {
1455
+ name: 'export', args: ['format', 'target'], hint: '[markdown|json] [file|clipboard]', category: 'data',
1456
+ desc: 'Export the current conversation to a file or clipboard',
1457
+ handler: async (c, args) => {
1458
+ const fmt = (args.format || 'markdown').toLowerCase();
1459
+ const target = (args.target || 'file').toLowerCase();
1460
+ if (!['markdown', 'md', 'json'].includes(fmt) || !['file', 'clipboard'].includes(target)) {
1461
+ note(c, 'Usage: /export [markdown|json] [file|clipboard]');
1462
+ c.render();
1463
+ return true;
1464
+ }
1465
+ const isJson = fmt === 'json';
1466
+ const body = isJson ? transcriptToJSON(c.transcript) : transcriptToMarkdown(c.transcript);
1467
+ if (target === 'clipboard') {
1468
+ const r = copyToClipboard(body);
1469
+ note(c, r.ok
1470
+ ? `Exported conversation (${isJson ? 'json' : 'markdown'}) to the clipboard.`
1471
+ : 'Clipboard unavailable; nothing copied.');
1472
+ } else {
1473
+ try {
1474
+ // Honour the command context's cwd. The handler used to fall through
1475
+ // to writeExportFile's own `process.cwd()` default, so /export wrote
1476
+ // into whatever directory the process happened to be in — which meant
1477
+ // running the command smoke test (it invokes every handler) littered
1478
+ // the repository root with aegiscodex-export-*.md files.
1479
+ const p = writeExportFile(body, isJson ? 'json' : 'md', c.ctx.cwd || process.cwd());
1480
+ note(c, `Exported conversation to ${p}`);
1481
+ } catch (e) {
1482
+ note(c, `/export: ${e.message}`);
1483
+ }
1484
+ }
1485
+ c.render();
1486
+ return true;
1487
+ },
1488
+ },
1489
+ {
1490
+ name: 'help', aliases: ['?', 'h'], hint: '', category: 'support',
1491
+ desc: 'Show help',
1492
+ handler: async (c) => {
1493
+ panel(c, panels.buildHelp(visibleCommands(), c.ctx));
1494
+ c.render();
1495
+ return true;
1496
+ },
1497
+ },
1498
+ {
1499
+ name: 'init', args: ['file'], hint: '[file]', category: 'workspace',
1500
+ desc: 'Create an AEGIS.md file in the project',
1501
+ handler: async (c, args) => {
1502
+ const file = (args.file || 'AEGIS.md').trim();
1503
+ // The command context's cwd, not process.cwd(): /cd moves the session to
1504
+ // another directory, and a handler that reads process.cwd() then writes
1505
+ // the file into the directory the user just left. It also means the
1506
+ // command smoke test (which invokes every handler) no longer drops an
1507
+ // AEGIS.md into the repository root.
1508
+ const cwd = c.ctx.cwd || process.cwd();
1509
+ const p = path.resolve(cwd, file);
1510
+ // Refuse a path that resolves outside the project — the reference's /init
1511
+ // takes no argument, and `path.join(cwd, '../../x')` writes outside it.
1512
+ const root = cwd.endsWith(path.sep) ? cwd : cwd + path.sep;
1513
+ if (p !== cwd && !p.startsWith(root)) {
1514
+ note(c, `/init: refusing to write outside the project directory (${p}).`);
1515
+ c.render();
1516
+ return true;
1517
+ }
1518
+ if (fs.existsSync(p)) { note(c, `${file} already exists — not overwriting.`); c.render(); return true; }
1519
+ const sniff = sniffProject(cwd);
1520
+ try {
1521
+ fs.writeFileSync(p, buildAegisMd(sniff) + '\n');
1522
+ } catch (e) {
1523
+ note(c, `/init: ${e.message}`);
1524
+ c.render();
1525
+ return true;
1526
+ }
1527
+ note(c, `Created ${p} (${sniff.lang})`);
1528
+ if (fs.existsSync(path.join(cwd, 'node_modules')) && !fs.existsSync(path.join(cwd, '.gitignore'))) {
1529
+ tip(c, 'Add "node_modules/" to a .gitignore before committing.');
1530
+ }
1531
+ c.render();
1532
+ return true;
1533
+ },
1534
+ },
1535
+ {
1536
+ name: 'login', aliases: ['signin'], args: ['value'], hint: '[<api_key>]', category: 'auth',
1537
+ desc: 'Save your AEGIS API key',
1538
+ handler: async (c, args) => {
1539
+ // This used to be `unavailable` with `/byok-set` as its alternative —
1540
+ // which was worse than useless: /byok-set stores a *provider* key
1541
+ // server-side, so a user following that advice pasted their AEGIS key
1542
+ // into a BYOK provider slot. Signing in to AEGIS Cloud *is* handing over
1543
+ // an API key, and this is now where you give it one.
1544
+ const arg = String(args.value || args._rest || '').trim();
1545
+ await applyAccountKey(c, arg, { label: 'AEGIS API key' });
1546
+ c.render();
1547
+ return true;
1548
+ },
1549
+ },
1550
+ {
1551
+ name: 'logout', args: [], hint: '', category: 'auth',
1552
+ desc: 'Remove the saved AEGIS API key',
1553
+ handler: async (c) => {
1554
+ const res = c.forgetApiKey();
1555
+ done(c, res.cleared ? `key removed from ${res.path}` : 'there was no saved key to remove');
1556
+ if (credentials.legacyKeyOnDisk()) {
1557
+ note(c, `a copy is still in ${configPath()} (another AEGIS CLI wrote it) — delete its "aegiscloud" block too`);
1558
+ }
1559
+ c.render();
1560
+ return true;
1561
+ },
1562
+ },
1563
+ {
1564
+ name: 'model', aliases: ['m'], args: ['sub'], hint: '[id|-]', category: 'model',
1565
+ desc: 'Switch AI model — pin an id ("-" clears it)',
1566
+ handler: async (c, args) => {
1567
+ const id = (args.sub || '').trim();
1568
+ // Which class the pin applies to — /model is class-scoped, because the
1569
+ // id spaces are disjoint: the pooled catalog is server-advertised ids,
1570
+ // byok is `provider:model`. Every branch below reads the live class, so
1571
+ // the copy and the picker's contents describe the route the next turn
1572
+ // will actually take (app.js's buildState().models is class-scoped too).
1573
+ const cls = (c.ctx && c.ctx.modelClass) || 'aegis';
1574
+ const byok = cls === 'byok';
1575
+ if (!id) {
1576
+ note(c, `model: ${c.ctx.model || 'server default'}`);
1577
+ // The full list across BOTH classes — pooled Nexus plus every
1578
+ // provider this machine can relay directly — not just the class the
1579
+ // session happens to be on. Selecting one of the direct-provider rows
1580
+ // (below) switches to byok and, if this machine holds no key for its
1581
+ // provider yet, prompts for one right there — see the picker's ENTER
1582
+ // handler in chatflow.js.
1583
+ const models = await mergedPickerModels(c);
1584
+ if (!models.length) {
1585
+ // Say why, and what unblocks it: an unreachable catalog is almost
1586
+ // always a missing key or no network, and "no models advertised"
1587
+ // read as "the platform has none" rather than "this client could not
1588
+ // ask". Reachable only when even Claude Code Pro's static alias rows
1589
+ // are absent — PRO_MODELS is a non-empty constant, so in practice
1590
+ // this is the full-outage fallback, not the common "no AEGIS key"
1591
+ // case that used to land here (see the branch just below).
1592
+ note(c, c.state().online
1593
+ ? 'Could not read the model catalog (offline, or the server refused it) — /models retries.'
1594
+ : // The key travels in the environment only (client/aegis.js reads
1595
+ // AEGIS_API_KEY); /login is an unavailable command here, so
1596
+ // pointing at it would send the user to a refusal.
1597
+ `No API key set, so the model catalog cannot be read — export AEGIS_API_KEY (free key: ${signupUrl('model_blocked')}), then retry /model.`);
1598
+ c.render();
1599
+ return true;
1600
+ }
1601
+ // AEGIS Cloud and byok both need a key this machine does not have:
1602
+ // almost always a missing AEGIS_API_KEY or no network. Claude Code Pro
1603
+ // needs neither (it is the subscription's own OAuth token, collected
1604
+ // when a pro row is picked), so its rows still show — the picker opens
1605
+ // with what IS available rather than blocking on what is not.
1606
+ if (!models.some((m) => m.cls === 'aegis' || m.cls === 'byok')) {
1607
+ note(c, c.state().online
1608
+ ? 'Could not read the AEGIS Cloud catalog (offline, or the server refused it) — showing Claude Code Pro only; /models retries.'
1609
+ : `No AEGIS API key set, so the AEGIS Cloud catalog cannot be read (free key: ${signupUrl('model_blocked')}) — showing Claude Code Pro only.`);
1610
+ }
1611
+ // A pin that is not in the catalog is not honoured — the pool answers
1612
+ // from its own default with no error. Say so where the pin is visible
1613
+ // rather than letting the reply look like the pinned model. On byok the
1614
+ // failure mode is different and louder (the relay 400s on a provider it
1615
+ // has no key for).
1616
+ if (c.ctx.model && !models.some((m) => m.id === c.ctx.model)) {
1617
+ note(c, byok
1618
+ ? `pinned model "${c.ctx.model}" is not one this machine can relay — pick from the list below.`
1619
+ : `pinned model "${c.ctx.model}" is not in the catalog — the pool will answer with its own default; pick one below.`);
1620
+ }
1621
+ note(c, '/model <id> pins one for this session; picking a direct-provider row prompts for its key if this machine has none saved.');
1622
+ // `cls` rides on the overlay so the picker's subtitle renders for the
1623
+ // class the session is on right now; each row also carries its own
1624
+ // `cls` so ENTER knows which class a pick switches to.
1625
+ c.openOverlay({ type: 'model', items: models, sel: 0, current: c.ctx.model, cls });
1626
+ return true;
1627
+ }
1628
+ if (id === 'list') {
1629
+ // Same merged list as the picker above, so the static panel and the
1630
+ // interactive one never disagree about what "the full list" is.
1631
+ const models = await mergedPickerModels(c);
1632
+ if (!models.length) note(c, 'No pinnable models advertised — /models lists the server\'s ids.');
1633
+ else panel(c, panels.buildModelList(c.ctx.model, models, c.ctx));
1634
+ c.render();
1635
+ return true;
1636
+ }
1637
+ if (id === '-') {
1638
+ c.ctx.model = null;
1639
+ c.saveConfig({ model: null, currentModelId: null });
1640
+ note(c, byok
1641
+ // There is no such thing as a byok default: the relay addresses a
1642
+ // provider by the id itself, so "nothing pinned" is not a fallback
1643
+ // here, it is a turn that will 400 with "model must be
1644
+ // <provider>:<model>". Said now rather than at the next send.
1645
+ ? 'Model pin cleared. The byok class has no server default — the next turn needs <provider>:<model>, so pin one from /models before sending.'
1646
+ : 'Model pin cleared — the server will choose.');
1647
+ c.render();
1648
+ return true;
1649
+ }
1650
+ c.ctx.model = id;
1651
+ // Persist, so the next launch restores it. app.js's restorePrefs() reads
1652
+ // this on startup; without the write it had nothing to restore and the
1653
+ // pin silently evaporated at exit. Tests point AEGISCODE_HOME at a temp
1654
+ // dir, so the write stays inside that dir.
1655
+ c.saveConfig({ model: id, currentModelId: id });
1656
+ note(c, `Pinned model: ${id}`);
1657
+ // A pin the class cannot honour is the same problem on both classes and
1658
+ // only the consequence differs, so both branches say the consequence.
1659
+ // Pooled: the server accepts an id it does not advertise and answers from
1660
+ // its own default — no error, a different model, and the spend attributed
1661
+ // to the id that was pinned. Byok: the id is parsed as a provider name,
1662
+ // so a pooled id becomes "no key saved for <that id>" at the relay.
1663
+ // Warn, never refuse: the catalog is cached, and refusing would break a
1664
+ // pin made against a server that is briefly unreachable.
1665
+ const models = (await loadModels(c)) || [];
1666
+ if (models.length && !models.some((m) => m.id === id)) {
1667
+ note(c, byok
1668
+ ? `"${id}" is not one this machine can relay — a byok id is "<provider>:<model>", and the relay will refuse anything else. /models lists the real ids.`
1669
+ : `"${id}" is not in the AEGIS Cloud catalog — the pool will answer with its own default. /models lists the real ids.`);
1670
+ }
1671
+ c.render();
1672
+ return true;
1673
+ },
1674
+ },
1675
+ {
1676
+ name: 'radio', hint: '', category: 'fun',
1677
+ desc: 'Listen to AEGIS FM lo-fi radio',
1678
+ handler: async (c) => {
1679
+ note(c, 'Opening AEGIS FM lo-fi radio in your browser…');
1680
+ if (!openUrl(URLS.radio)) note(c, `AEGIS FM: ${URLS.radio}`);
1681
+ c.render();
1682
+ return true;
1683
+ },
1684
+ },
1685
+ {
1686
+ name: 'recap', hint: '', category: 'session',
1687
+ desc: 'Generate a one-line session recap now',
1688
+ handler: async (c) => {
1689
+ if (!c.transcript.some((m) => m.role === 'user' || m.role === 'assistant')) {
1690
+ note(c, 'No exchanges yet — send a prompt first.');
1691
+ c.render();
1692
+ return true;
1693
+ }
1694
+ note(c, 'Recapping session…');
1695
+ c.render();
1696
+ const line = await c.withWorking((signal) =>
1697
+ recapLine(c.transcript, {
1698
+ callModel: (p, opts) => c.ask(p, opts).then((r) => r.text),
1699
+ model: c.ctx.model,
1700
+ signal,
1701
+ }));
1702
+ if (line === null) { note(c, 'Recap cancelled.'); c.render(); return true; }
1703
+ c.ctx.lastRecap = { sessionId: c.sessionId, ts: new Date().toISOString(), text: line };
1704
+ c.saveConfig({ lastRecap: c.ctx.lastRecap });
1705
+ note(c, `Session recap: ${line}`);
1706
+ c.render();
1707
+ return true;
1708
+ },
1709
+ },
1710
+ {
1711
+ name: 'resume', hint: '', category: 'session',
1712
+ desc: 'Switch to a previous session',
1713
+ handler: async (c) => {
1714
+ const items = readResumeList();
1715
+ if (!items.length) { note(c, 'No previous sessions found — conversations from this host and from AEGIS Desktop both land in ~/.aegiscode/sessions.json'); c.render(); return true; }
1716
+ c.openOverlay({ type: 'resume', items, sel: 0 });
1717
+ return true;
1718
+ },
1719
+ },
1720
+ {
1721
+ name: 'rewind', args: ['n'], hint: '[N]', category: 'session',
1722
+ desc: 'Revert the conversation to a checkpoint',
1723
+ handler: async (c, args) => {
1724
+ const items = listCheckpoints(c.sessionId);
1725
+ if (!args.n) {
1726
+ if (!items.length) { note(c, 'No checkpoints yet — snapshots are taken after each exchange.'); c.render(); return true; }
1727
+ panel(c, panels.buildRewindList(items, c.ctx));
1728
+ c.render();
1729
+ return true;
1730
+ }
1731
+ const n = parseInt(args.n, 10);
1732
+ if (Number.isNaN(n) || n < 0 || n >= items.length) {
1733
+ note(c, `Unknown checkpoint ${args.n}. /rewind shows the list (indices 0..${Math.max(0, items.length - 1)}).`);
1734
+ c.render();
1735
+ return true;
1736
+ }
1737
+ snapshotCheckpoint(c.sessionId, c.transcript); // make the rewind undoable
1738
+ const restored = loadCheckpoint(c.sessionId, n);
1739
+ if (!restored) { note(c, 'Checkpoint unreadable — nothing restored.'); c.render(); return true; }
1740
+ c.transcript.length = 0;
1741
+ for (const m of restored) c.transcript.push(m);
1742
+ note(c, `Rewound to checkpoint ${n} (${restored.length} messages). /rewind N again to undo.`);
1743
+ c.render();
1744
+ return true;
1745
+ },
1746
+ },
1747
+ {
1748
+ name: 'agents', aliases: ['sessions'], args: ['role', 'task'], hint: '[role] [task]', category: 'session',
1749
+ desc: 'Show the agents panel, or run a sub-agent role preset — /agents <role> <task>',
1750
+ handler: async (c, args) => {
1751
+ const role = (args.role || '').trim().toLowerCase();
1752
+ if (role) {
1753
+ const task = (args._rest || '').trim().replace(/^\S+\s*/, '').trim();
1754
+ if (!task) { note(c, `Usage: /agents <role> <task> — roles: ${agentRoles().join(', ')}`); c.render(); return true; }
1755
+ if (!AGENT_PRESETS[role]) { note(c, `Unknown agent role "${role}". Roles: ${agentRoles().join(', ')}`); c.render(); return true; }
1756
+ const prompt = composeAgentPrompt(role, task);
1757
+ if (c.runPrompt) {
1758
+ await c.runPrompt(prompt);
1759
+ return true;
1760
+ }
1761
+ note(c, `Composed ${role} prompt (${prompt.length} chars) — run in the TUI to send it.`);
1762
+ c.render();
1763
+ return true;
1764
+ }
1765
+ panel(c, panels.buildAgents(c.state(), c.ctx));
1766
+ c.render();
1767
+ return true;
1768
+ },
1769
+ },
1770
+ {
1771
+ name: 'status', aliases: ['st'], hint: '', category: 'session',
1772
+ desc: 'Show account and session status',
1773
+ handler: async (c) => {
1774
+ // This client's /status surface is the account-status tool (the same
1775
+ // tool /aegis-status names) plus the local session panel below it.
1776
+ await c.runTool('aegis_status', {});
1777
+ panel(c, panels.buildStatus(c.state(), Object.assign({}, c.ctx, { caps: describe() })));
1778
+ c.render();
1779
+ return true;
1780
+ },
1781
+ },
1782
+ {
1783
+ name: 'teleport', hint: '', category: 'session',
1784
+ desc: 'Resume a session from aegiscloud.org',
1785
+ handler: async (c) => {
1786
+ note(c, 'Teleport requires an AEGIS cloud account with sessions. Sign in with `aegis login`, then run aegiscloud.org/teleport.');
1787
+ c.render();
1788
+ return true;
1789
+ },
1790
+ },
1791
+ {
1792
+ name: 'theme', aliases: ['t'], args: ['mode'], hint: '[dark|light]', category: 'model',
1793
+ desc: 'Change the color theme',
1794
+ handler: async (c, args) => {
1795
+ const m = (args.mode || '').toLowerCase();
1796
+ if (m === 'dark' || m === 'light') {
1797
+ // Resolve through the theme table rather than hardcoding an index, so
1798
+ // "light" names the same row the picker would have named: index 2
1799
+ // ("Light mode"), not index 0 ("Auto"). themeIndex is what the
1800
+ // colorblind/ANSI palettes key off, so a wrong index silently selects
1801
+ // the wrong palette rather than merely displaying a wrong label.
1802
+ const want = m === 'light' ? 2 : 1;
1803
+ screens.applyTheme(c.ctx, want);
1804
+ } else {
1805
+ await c.showThemePicker();
1806
+ }
1807
+ c.saveConfig({ themeIndex: c.ctx.themeIndex });
1808
+ note(c, `Theme: ${c.ctx.light ? 'light' : 'dark'}`);
1809
+ // An explicit row is a real preference — the whole point of `/theme dark`
1810
+ // — so it is NOT overridden here, even on a terminal that will draw it
1811
+ // badly. It is only reported, because "my text vanished" is otherwise
1812
+ // indistinguishable from a crash and this is the one moment the user is
1813
+ // looking at the setting that caused it.
1814
+ const clash = themeContradicts(c.ctx.themeIndex);
1815
+ if (clash) {
1816
+ const background = caps().background;
1817
+ note(c, `warning: this ${background} terminal is not what "${THEME_TABLE[c.ctx.themeIndex].name}" is drawn for — body text may be unreadable.`);
1818
+ note(c, ` /terminal background ${background} pins the palette to this terminal, or /terminal background ${background === 'dark' ? 'light' : 'dark'} if it reads you wrong.`);
1819
+ }
1820
+ c.render();
1821
+ return true;
1822
+ },
1823
+ },
1824
+ {
1825
+ name: 'terminal', aliases: ['tty'], args: ['mode', 'mode2'],
1826
+ hint: '[ascii|unicode|color|no-color|background <dark|light>|probe|star <native|narrow>|width <cols>|auto|status]', category: 'model',
1827
+ desc: 'Show or override how this terminal is drawn (mark, colour, width)',
1828
+ handler: async (c, args) => {
1829
+ // The same report `aegiscode --terminal` prints, and the same switch the
1830
+ // `--ascii` flag sets — so a session can be re-styled without restarting
1831
+ // when a paste from PowerShell turns out to render badly in this host.
1832
+ // `args` is positional (app.js `parseArgs`), so the second token is
1833
+ // `mode2` for both `star narrow` and `width 100`.
1834
+ const sub = (args.mode || '').toLowerCase();
1835
+ const second = args.mode2 != null ? String(args.mode2).trim() : '';
1836
+
1837
+ if (sub === '' || sub === 'status') {
1838
+ panel(c, panels.buildTerminalCaps(describe(), { pinned: !!caps().pinned }));
1839
+ c.render();
1840
+ return true;
1841
+ }
1842
+
1843
+ // The patch pins every *axis* but never the frame: `cols`/`rows` must stay
1844
+ // absent so `setCaps` leaves `sizePinned` false and a live resize keeps
1845
+ // re-reading the stream (see caps.js). Copying the whole caps object here
1846
+ // would freeze the width at the moment the command ran.
1847
+ const cur = caps();
1848
+ const axes = {
1849
+ glyphs: cur.glyphs, face: cur.face, star: cur.star,
1850
+ depth: cur.depth, vt: cur.vt, wideRunes: cur.wideRunes,
1851
+ background: cur.background,
1852
+ backgroundKnown: cur.backgroundKnown,
1853
+ reasons: Object.assign({}, cur.reasons),
1854
+ };
1855
+
1856
+ if (sub === 'auto') {
1857
+ // Drop every override, including any the session inherited from the
1858
+ // flags/env it was started with — "auto" means "probe again", not
1859
+ // "restore what you were launched with".
1860
+ resetCaps();
1861
+ note(c, 'Terminal: auto — capabilities re-probed from the environment.');
1862
+ c.render();
1863
+ return true;
1864
+ }
1865
+ if (sub === 'probe') {
1866
+ // Ask the terminal outright (OSC 11) and use its own answer. This is
1867
+ // the same query the session runs once at startup, exposed because the
1868
+ // one case it cannot handle is a terminal that started reporting
1869
+ // differently afterwards — a terminal theme switched mid-session — and
1870
+ // because "what does my terminal say it is?" is the first question a
1871
+ // mis-rendered screen raises.
1872
+ const probed = await probeTerminalBackground();
1873
+ screens.applyTheme(c.ctx, c.ctx.themeIndex);
1874
+ note(c, probed.known
1875
+ ? `Terminal: background ${probed.background} (${probed.reason}) — /theme auto follows it.`
1876
+ : `Terminal: no answer to the background query (${probed.reason}).`);
1877
+ note(c, ' /terminal background dark|light pins it without asking.');
1878
+ panel(c, panels.buildTerminalCaps(describe(), { pinned: !!caps().pinned }));
1879
+ c.render();
1880
+ return true;
1881
+ }
1882
+ // `why` in the report must describe what the session is actually doing,
1883
+ // not the probe it started from: after `/terminal ascii` on a truecolor
1884
+ // host, `why: TERM=xterm-256color` would contradict `mark: ascii`.
1885
+ if (sub === 'ascii' || sub === 'unicode') {
1886
+ axes.glyphs = sub === 'ascii' ? 'ascii' : 'unicode';
1887
+ axes.face = sub === 'ascii' ? 'edges' : 'native';
1888
+ axes.star = sub === 'ascii' ? 'narrow' : 'native';
1889
+ if (axes.reasons) axes.reasons.glyphs = `/terminal ${sub}`;
1890
+ } else if (sub === 'color' || sub === 'no-color' || sub === 'nocolor') {
1891
+ axes.depth = sub === 'color' ? 24 : 0;
1892
+ if (axes.reasons) axes.reasons.depth = `/terminal ${sub}`;
1893
+ } else if (sub === 'star') {
1894
+ const want = second.toLowerCase();
1895
+ if (!['native', 'narrow'].includes(want)) { note(c, 'Usage: /terminal star <native|narrow>'); c.render(); return true; }
1896
+ axes.star = want;
1897
+ if (axes.reasons) axes.reasons.star = `/terminal star ${want}`;
1898
+ } else if (sub === 'background' || sub === 'bg') {
1899
+ // The one axis that is not about drawing: it says which of the two
1900
+ // legible palettes "Auto (match terminal)" resolves to, for a terminal
1901
+ // that reports nothing about itself (or reports it wrong). Pinning it
1902
+ // here is the same decision `AEGIS_BACKGROUND` makes at launch, so a
1903
+ // user on a light terminal can fix an invisible UI without restarting.
1904
+ const want = second.toLowerCase();
1905
+ if (!['dark', 'light'].includes(want)) { note(c, 'Usage: /terminal background <dark|light>'); c.render(); return true; }
1906
+ axes.background = want;
1907
+ axes.backgroundKnown = true;
1908
+ if (axes.reasons) axes.reasons.background = `/terminal background ${want}`;
1909
+ setCaps(Object.assign({}, axes));
1910
+ screens.applyTheme(c.ctx, c.ctx.themeIndex);
1911
+ note(c, `Terminal: background pinned to ${want} — /theme auto follows it.`);
1912
+ panel(c, panels.buildTerminalCaps(describe(), { pinned: !!caps().pinned }));
1913
+ c.render();
1914
+ return true;
1915
+ } else if (sub === 'width') {
1916
+ // A pinned width is a frame override, so it goes in as cols — the one
1917
+ // key that deliberately trips `sizePinned`.
1918
+ const width = Number(second);
1919
+ if (!Number.isFinite(width) || width < 20) { note(c, 'Usage: /terminal width <cols> (>= 20)'); c.render(); return true; }
1920
+ setCaps(Object.assign({}, axes, { cols: Math.round(width) }));
1921
+ note(c, `Terminal: width pinned to ${Math.round(width)} columns.`);
1922
+ panel(c, panels.buildTerminalCaps(describe(), { pinned: !!caps().pinned }));
1923
+ c.render();
1924
+ return true;
1925
+ } else {
1926
+ note(c, 'Usage: /terminal [ascii|unicode|color|no-color|background <dark|light>|probe|star <native|narrow>|width <cols>|auto|status]');
1927
+ c.render();
1928
+ return true;
1929
+ }
1930
+
1931
+ setCaps(axes);
1932
+ panel(c, panels.buildTerminalCaps(describe(), { pinned: !!caps().pinned }));
1933
+ // Already-painted scrollback keeps the glyphs it was drawn with — a
1934
+ // terminal has no way to rewrite what it has scrolled past. Everything
1935
+ // from here on (and this viewport) uses the new mark.
1936
+ note(c, 'Terminal updated — the current viewport is redrawn; text already scrolled past keeps its old glyphs.');
1937
+ c.render();
1938
+ return true;
1939
+ },
1940
+ },
1941
+ {
1942
+ name: 'version', aliases: ['v'], hint: '', category: 'session',
1943
+ desc: 'Show version',
1944
+ handler: async (c) => {
1945
+ note(c, `aegiscode v${VERSION}`);
1946
+ c.render();
1947
+ return true;
1948
+ },
1949
+ },
1950
+ {
1951
+ name: 'doctor', args: ['action'], hint: '[fix|system]', category: 'support',
1952
+ desc: 'Run diagnostic checks on this environment',
1953
+ handler: async (c, args) => {
1954
+ const action = ((args && args.action) || '').toLowerCase();
1955
+ if (action && action !== 'fix' && action !== 'system') {
1956
+ note(c, 'Usage: /doctor [fix|system] — "fix" re-tightens the data dir to 0700/0600, "system" checks the machine itself');
1957
+ c.render();
1958
+ return true;
1959
+ }
1960
+ const checks = [];
1961
+ const ok = (label, good, detail) => checks.push([good, label, detail]);
1962
+ ok('Node', true, process.version);
1963
+ ok('CWD', fs.existsSync(process.cwd()), process.cwd());
1964
+ let git = false;
1965
+ try { execSync('git rev-parse --git-dir', { cwd: process.cwd(), stdio: ['ignore', 'ignore', 'ignore'], timeout: 4000 }); git = true; } catch {}
1966
+ ok('git repo', git, git ? 'inside a work tree' : 'not a git repository');
1967
+ const ks = credentials.keyStatus();
1968
+ ok(
1969
+ 'AEGIS key',
1970
+ ks.configured,
1971
+ ks.configured
1972
+ ? `${maskKey(ks.key)} via ${credentials.sourceLabel(ks.source)}`
1973
+ : `not set — ${credentials.HOW_TO_SET} (free key: ${signupUrl('doctor')})`
1974
+ );
1975
+ ok('credentials', true, `${ks.path}${ks.fileMode ? ` (${ks.fileMode})` : ''}`);
1976
+ ok('cloud memory', ks.memoryToken, ks.memoryToken ? 'token held' : 'no memory token — /cloud activate');
1977
+ if (ks.legacyPlaintext) {
1978
+ ok('plaintext key', false, `a copy also sits in ${configPath()} (another AEGIS CLI) — /key re-saves it to ${ks.path}`);
1979
+ }
1980
+ ok('config path', true, configPath());
1981
+ // The store sits at 0775/0664 on any install older than securefs.js —
1982
+ // every file that has not happened to be rewritten since. Report that
1983
+ // always, but repair only when asked: a diagnostic that silently rewrites
1984
+ // the user's directory is a surprise, not a fix.
1985
+ const dataDir = aegisDir();
1986
+ let repaired = null;
1987
+ if (action === 'fix') repaired = repairExposure(dataDir);
1988
+ const audit = auditExposure(dataDir);
1989
+ if (!audit.exists) {
1990
+ ok('data dir', true, `${dataDir} (not created yet)`);
1991
+ } else if (!audit.modesMeaningful) {
1992
+ // Windows: fs.stat's mode is synthesised from the read-only attribute, so
1993
+ // there are no group/other bits to audit (securefs.js hasPosixModes).
1994
+ // Saying so beats the old output, which listed every file in the store as
1995
+ // world-accessible and then could not fix a single one.
1996
+ ok(
1997
+ 'data dir',
1998
+ true,
1999
+ `${dataDir} (${audit.total} path(s)) — this filesystem has no POSIX permission bits; ` +
2000
+ 'access is governed by the profile directory\'s own ACL',
2001
+ );
2002
+ } else {
2003
+ const shown = audit.exposed.slice(0, 4).map((e) => `${e.rel} ${e.mode}`).join(', ');
2004
+ ok(
2005
+ 'data dir',
2006
+ audit.exposed.length === 0,
2007
+ audit.exposed.length === 0
2008
+ ? `${dataDir} (${audit.rootMode}, all private)`
2009
+ : `${dataDir} (${audit.rootMode}) — ${audit.exposed.length} path(s) group/world-accessible: ` +
2010
+ `${shown}${audit.exposed.length > 4 ? ', …' : ''} — run /doctor fix`
2011
+ );
2012
+ }
2013
+ if (repaired && !repaired.modesMeaningful) {
2014
+ ok('repair', true, 'nothing to tighten — this filesystem has no POSIX permission bits');
2015
+ } else if (repaired) {
2016
+ const sample = repaired.fixed
2017
+ .slice(0, 3)
2018
+ .map((f) => `${f.rel} ${f.from}→${f.to}`)
2019
+ .join(', ');
2020
+ ok(
2021
+ 'repair',
2022
+ repaired.remaining.length === 0,
2023
+ repaired.remaining.length === 0
2024
+ ? repaired.fixed.length
2025
+ ? `tightened ${repaired.fixed.length} path(s) — ${sample}${repaired.fixed.length > 3 ? ', …' : ''}`
2026
+ : 'already private, nothing to tighten'
2027
+ : `${repaired.remaining.length} path(s) still exposed — ` +
2028
+ repaired.failed.map((f) => `${f.rel}: ${f.reason}`).join(', ')
2029
+ );
2030
+ }
2031
+ // `/doctor system` — the machine, not the checkout. Read-only by design:
2032
+ // cli/src/sysdiag.js holds the nine checks and each one's remedy, and
2033
+ // nothing here executes a remedy, because all of them need elevation and
2034
+ // the ordering matters (VSS has to survive DoSnapshotSet before a restore
2035
+ // point can exist). An unread probe is its own state, never a ✔.
2036
+ let systemReport = null;
2037
+ if (action === 'system') {
2038
+ const probe = sysdiag.collect();
2039
+ if (!probe.ok) {
2040
+ ok(
2041
+ 'machine checks',
2042
+ false,
2043
+ probe.reason === 'not-windows'
2044
+ ? 'not available on this platform — the machine audit is Windows-only (cli/src/sysdiag.js)'
2045
+ : `could not run: ${probe.reason}`,
2046
+ );
2047
+ } else {
2048
+ systemReport = sysdiag.assess(probe.data);
2049
+ for (const f of systemReport.findings) ok(`${f.title} (${f.severity})`, false, `${f.detail} → ${f.remedyText}`);
2050
+ for (const p of systemReport.clean) ok(p.title, true, p.detail);
2051
+ for (const u of systemReport.unassessed) ok(`${u.title} (unassessed)`, false, u.reason);
2052
+ }
2053
+ }
2054
+ const lines = [[span(C.gold + BOLD, 'Doctor'), span(BOLD_OFF, '')], [span(C.gray, '─'.repeat(30))]];
2055
+ for (const [good, label, detail] of checks) {
2056
+ lines.push([
2057
+ span(good ? C.green : C.coral, ` ${good ? '✔' : '⚠'}`),
2058
+ span(C.white, ` ${label}: `),
2059
+ span(C.gray, String(detail)),
2060
+ ]);
2061
+ }
2062
+ if (systemReport && systemReport.findings.length) {
2063
+ const s = systemReport.summary;
2064
+ lines.push([
2065
+ span(C.gold, ' Remedy'),
2066
+ span(C.gray, ` — ${s.findings} finding(s) across ${s.assessed}/${s.total} measured checks.`),
2067
+ ]);
2068
+ lines.push([span(C.gray, ' Run in an ELEVATED PowerShell. AEGIS diagnoses this; it does not change your machine.')]);
2069
+ for (const line of sysdiag.remedyScript().split('\n')) lines.push([span(C.gray, ` ${line}`)]);
2070
+ }
2071
+ panel(c, lines);
2072
+ c.render();
2073
+ return true;
2074
+ },
2075
+ },
2076
+ {
2077
+ name: 'upgrade', args: ['action'], hint: '[check|apply]', category: 'support',
2078
+ desc: 'Check for a newer published version (apply: install it now)',
2079
+ handler: async (c, args) => {
2080
+ const action = String((args && args.action) || 'check').toLowerCase();
2081
+ if (!['check', 'apply'].includes(action)) {
2082
+ note(c, 'Usage: /upgrade [check|apply]');
2083
+ c.render();
2084
+ return true;
2085
+ }
2086
+ // The channel is what THIS process was installed from — npm, pip, npx or
2087
+ // a git checkout — so /upgrade never tells a pip install to run npm and
2088
+ // then report success for a second copy that nothing is running from.
2089
+ const method = installMethod();
2090
+ note(c, 'Checking the npm registry…');
2091
+ c.render();
2092
+ // The registry lookup is a blocking `npm view`, so it runs inside the
2093
+ // spinner when the context offers one (and is skipped entirely in demo
2094
+ // mode, where a network answer would be a lie).
2095
+ const run = c && c.withWorking ? (fn) => c.withWorking(fn) : (fn) => fn();
2096
+ const latest = c.ctx && c.ctx.demo ? null : await run(() => Promise.resolve(latestPublishedVersion()));
2097
+ const advice = upgradeAdvice({ latest, method });
2098
+ panel(c, upgradePanelLines(advice.lines));
2099
+ c.render();
2100
+ if (action !== 'apply') return true;
2101
+
2102
+ // Applying is opt-in and never inferred: it replaces the binaries under
2103
+ // a running process, which is a different promise from "a release
2104
+ // exists". A channel with nothing to install says so instead of running
2105
+ // a command that would be a no-op.
2106
+ if (!advice.plan || !advice.plan.apply) {
2107
+ note(c, advice.plan ? `Nothing to install: ${advice.plan.instruction}` : 'Nothing to install.');
2108
+ c.render();
2109
+ return true;
2110
+ }
2111
+ note(c, `Running: ${advice.plan.instruction}`);
2112
+ c.render();
2113
+ const res = applyUpgrade({ method, latest, current: advice.plan.current });
2114
+ if (res.ok && !res.skipped) {
2115
+ // A global install does not touch the process already running, so the
2116
+ // honest last line is "installed, restart to use it" — not "upgraded",
2117
+ // which would claim this session is now on the new version.
2118
+ note(c, `Installed ${advice.plan.latest}. Restart aegiscode to use it.`);
2119
+ if (res.output) for (const line of res.output.split('\n').slice(-6)) note(c, ` ${line}`);
2120
+ } else if (res.skipped) {
2121
+ note(c, `Not applied: ${res.instruction}`);
2122
+ } else {
2123
+ note(c, `Upgrade failed: ${res.error}`);
2124
+ note(c, `Run it yourself: ${res.command}`);
2125
+ }
2126
+ c.render();
2127
+ return true;
2128
+ },
2129
+ },
2130
+ {
2131
+ name: 'vim', args: ['mode'], hint: '[on|off]', category: 'model',
2132
+ desc: 'Toggle vim keymap',
2133
+ handler: async (c, args) => {
2134
+ const mode = (args.mode || '').toLowerCase();
2135
+ if (mode && !['on', 'off'].includes(mode)) { note(c, 'Usage: /vim [on|off]'); c.render(); return true; }
2136
+ const want = mode === 'on' ? true : mode === 'off' ? false : !c.ctx.vim;
2137
+ c.ctx.vim = want;
2138
+ c.saveConfig({ vim: want });
2139
+ note(c, `Vim keymap: ${want ? 'on' : 'off'}`);
2140
+ c.render();
2141
+ return true;
2142
+ },
2143
+ },
2144
+ {
2145
+ name: 'permissions', args: ['mode', 'pattern'],
2146
+ hint: '[allow|deny|ask "<pattern>" | default <ask|allow|deny> | clear]', category: 'model',
2147
+ desc: 'Set permissions for tool use',
2148
+ handler: async (c, args) => {
2149
+ const rules = loadPermissions();
2150
+ const mode = (args.mode || '').toLowerCase();
2151
+ const pattern = args.pattern;
2152
+ if (!mode) {
2153
+ panel(c, panels.buildPermissions({ ...rules, _path: permissionsPath() }, null, c.ctx));
2154
+ c.render();
2155
+ return true;
2156
+ }
2157
+ if (mode === 'clear') {
2158
+ // A reset is a posture change too: DEFAULT_PERMISSIONS' residual is
2159
+ // `ask`, i.e. confirmations ON, and leaving the shared key where it was
2160
+ // would keep the gate off in the window while this face asks.
2161
+ setPermissionDefaultMode(DEFAULT_PERMISSIONS.defaultMode);
2162
+ savePermissions({ ...DEFAULT_PERMISSIONS, allow: [], deny: [], ask: [] });
2163
+ note(c, 'Permissions reset to defaults (no rules).');
2164
+ c.render();
2165
+ return true;
2166
+ }
2167
+ if (mode === 'default' && ['ask', 'allow', 'deny'].includes(pattern)) {
2168
+ // ON8: `ask`/`allow` are the posture, so this moves the shared gate too
2169
+ // (a `/permissions default ask` in the shell must close the window's
2170
+ // switch, which is the whole point of rule 1). `deny` is not a posture:
2171
+ // it writes the rule residual and leaves the gate UP.
2172
+ setPermissionDefaultMode(pattern);
2173
+ note(c, `Default permission mode: ${pattern}`);
2174
+ c.render();
2175
+ return true;
2176
+ }
2177
+ if (['allow', 'deny', 'ask'].includes(mode) && pattern) {
2178
+ const { added, rules: next } = addPermissionRule(mode, pattern, rules);
2179
+ savePermissions(next);
2180
+ note(c, added ? `Added ${mode} rule: ${pattern}` : `Rule already present: ${pattern}`);
2181
+ c.render();
2182
+ return true;
2183
+ }
2184
+ note(c, 'Usage: /permissions [allow|deny|ask "<pattern>" | default <ask|allow|deny> | clear]');
2185
+ c.render();
2186
+ return true;
2187
+ },
2188
+ },
2189
+ {
2190
+ name: 'hooks', args: ['sub'], hint: '[status|list|install]', category: 'model',
2191
+ desc: 'View hooks configuration status, list configured hooks, or install this repo\'s guard hooks',
2192
+ handler: async (c, args) => {
2193
+ const sub = (args.sub || '').toLowerCase();
2194
+ if (sub === 'install') {
2195
+ // The one mutating branch, and the one that makes the guards real: a
2196
+ // fresh clone has .githooks/ present and core.hooksPath unset, so a
2197
+ // commit runs NO guard at all (`.githooks/lib-gate.sh` says so itself).
2198
+ const dryRun = /--dry-run|\bdry-?run\b/.test(String(args._rest || ''));
2199
+ const res = hooksLib.installRepoHooks({ cwd: process.cwd(), dryRun });
2200
+ if (!res.ok) {
2201
+ note(c, res.error);
2202
+ if (res.actions.length) for (const a of res.actions) note(c, ` ${a}`);
2203
+ } else if (dryRun) {
2204
+ note(c, `would install the guard hooks in ${res.status.repo}`);
2205
+ for (const a of res.actions) note(c, ` ${a}`);
2206
+ if (res.status.installed) note(c, 'core.hooksPath is already .githooks — nothing to change');
2207
+ } else if (!res.changed) {
2208
+ done(c, `guard hooks already installed (core.hooksPath = .githooks)`);
2209
+ } else {
2210
+ done(c, `installed the guard hooks — core.hooksPath = .githooks (verified)`);
2211
+ for (const a of res.actions) note(c, ` ${a}`);
2212
+ }
2213
+ if (res.ok) note(c, res.status.execNote);
2214
+ c.render();
2215
+ return true;
2216
+ }
2217
+ const { hooks, from } = readHooks();
2218
+ if (sub === 'list') {
2219
+ panel(c, panels.buildHooksList({ hooks }, c.ctx));
2220
+ c.render();
2221
+ return true;
2222
+ }
2223
+ if (sub === '' || sub === 'status') {
2224
+ panel(c, panels.buildHooksStatus({ ...hookStats(hooks), fromPaths: from }, c.ctx));
2225
+ c.render();
2226
+ return true;
2227
+ }
2228
+ note(c, `unknown subcommand: ${args.sub}`);
2229
+ note(c, 'available: status, list, install [--dry-run]');
2230
+ c.render();
2231
+ return true;
2232
+ },
2233
+ },
2234
+ {
2235
+ name: 'credentials', hint: '', category: 'model',
2236
+ desc: 'Show where credentials are stored',
2237
+ handler: async (c) => {
2238
+ const p = path.join(os.homedir(), '.claude', '.credentials.json');
2239
+ const loc = p.replace(os.homedir(), '~');
2240
+ if (!fs.existsSync(p)) {
2241
+ note(c, 'No credential file found. The Claude Code CLI manages auth (OS keychain or ~/.claude/.credentials.json).');
2242
+ } else {
2243
+ note(c, `Credentials live in ${loc} (managed by the Claude Code CLI). aegiscode reads them but never writes them.`);
2244
+ }
2245
+ c.render();
2246
+ return true;
2247
+ },
2248
+ },
2249
+ {
2250
+ name: 'install-github-app', hint: '', category: 'model',
2251
+ desc: 'Install the GitHub App for PR workflows',
2252
+ handler: async (c) => {
2253
+ note(c, 'The GitHub App is installed through the Claude Code CLI: run `claude --install-github-app` once.');
2254
+ c.render();
2255
+ return true;
2256
+ },
2257
+ },
2258
+ {
2259
+ name: 'troubleshooting', hint: '', category: 'support',
2260
+ desc: 'Troubleshoot common issues',
2261
+ handler: async (c) => {
2262
+ panel(c, panels.buildTroubleshooting(c.state(), c.ctx));
2263
+ c.render();
2264
+ return true;
2265
+ },
2266
+ },
2267
+ {
2268
+ name: 'feedback', hint: '', category: 'support',
2269
+ desc: 'Send feedback to the AEGIS team',
2270
+ handler: async (c) => {
2271
+ note(c, 'Opening the feedback form…');
2272
+ if (!openUrl(URLS.feedback)) note(c, `Feedback: ${URLS.feedback}`);
2273
+ c.render();
2274
+ return true;
2275
+ },
2276
+ },
2277
+ {
2278
+ name: 'bug', hint: '', category: 'support',
2279
+ desc: 'Report a bug (opens a GitHub issue)',
2280
+ handler: async (c) => {
2281
+ note(c, `Opening a GitHub issue… (aegiscode v${VERSION}, ${process.version}, ${os.platform()})`);
2282
+ if (!openUrl(URLS.issues)) note(c, `Issues: ${URLS.issues}`);
2283
+ c.render();
2284
+ return true;
2285
+ },
2286
+ },
2287
+ {
2288
+ name: 'issue', aliases: ['bugs'], hint: '', category: 'support',
2289
+ desc: 'Report an issue',
2290
+ handler: async (c) => {
2291
+ note(c, 'Opening a GitHub issue…');
2292
+ if (!openUrl(URLS.issues)) note(c, `Issues: ${URLS.issues}`);
2293
+ c.render();
2294
+ return true;
2295
+ },
2296
+ },
2297
+ {
2298
+ name: 'onboarding', hint: '', category: 'support',
2299
+ desc: 'Show getting-started tips',
2300
+ handler: async (c) => {
2301
+ panel(c, panels.buildOnboarding(c.state(), c.ctx));
2302
+ c.render();
2303
+ return true;
2304
+ },
2305
+ },
2306
+ {
2307
+ name: 'shell-completion', hint: '', category: 'support',
2308
+ desc: 'Set up shell completion',
2309
+ handler: async (c) => {
2310
+ panel(c, panels.buildShellCompletion(c.state(), c.ctx));
2311
+ c.render();
2312
+ return true;
2313
+ },
2314
+ },
2315
+ {
2316
+ name: 'terminal-setup', hint: '', category: 'support',
2317
+ desc: 'Check and fix terminal setup',
2318
+ handler: async (c) => {
2319
+ panel(c, panels.buildTerminalSetup(c.state(), c.ctx));
2320
+ c.render();
2321
+ return true;
2322
+ },
2323
+ },
2324
+ {
2325
+ name: 'pr-comments', hint: '', category: 'support',
2326
+ desc: 'Review and reply to pull request comments',
2327
+ handler: async (c) => {
2328
+ note(c, 'PR comments need GitHub auth. Run /prs to check connectivity, then use the `gh` CLI or the GitHub web UI.');
2329
+ c.render();
2330
+ return true;
2331
+ },
2332
+ },
2333
+ {
2334
+ name: 'prs', hint: '', category: 'support',
2335
+ desc: 'List pull requests in this repo',
2336
+ handler: async (c) => {
2337
+ try {
2338
+ const out = execSync('gh pr list --limit 8', { encoding: 'utf8', timeout: 15000, stdio: ['ignore', 'pipe', 'ignore'] });
2339
+ panel(c, panels.buildPRs(out.toString(), c.ctx));
2340
+ } catch {
2341
+ note(c, 'gh not authenticated (or not installed) — run `gh auth login` first.');
2342
+ }
2343
+ c.render();
2344
+ return true;
2345
+ },
2346
+ },
2347
+ {
2348
+ name: 'review', hint: '', category: 'support',
2349
+ desc: 'Review a pull request',
2350
+ handler: async (c) => {
2351
+ note(c, '/review needs GitHub auth via gh. Run /prs to list open PRs, then open one in the browser.');
2352
+ c.render();
2353
+ return true;
2354
+ },
2355
+ },
2356
+ {
2357
+ name: 'benchmark', hint: '', category: 'support',
2358
+ desc: 'Run in-app micro-benchmarks',
2359
+ handler: async (c) => {
2360
+ const t = (fn) => {
2361
+ const s = process.hrtime.bigint();
2362
+ fn();
2363
+ return (Number(process.hrtime.bigint() - s) / 1e6).toFixed(2);
2364
+ };
2365
+ const sample = '# Heading\n\nSome **bold** and `code` with a [link](https://x.test).\n\n- a\n- b\n- c\n';
2366
+ const results = [
2367
+ ['2,000 span() calls', t(() => { for (let i = 0; i < 2000; i++) span(C.white, 'x'); })],
2368
+ ['estimateTokens × 20 (500 chars)', t(() => { for (let i = 0; i < 20; i++) estimateTokens('x'.repeat(500)); })],
2369
+ ];
2370
+ if (markdownModule && typeof markdownModule.renderMarkdown === 'function') {
2371
+ results.push(['renderMarkdown × 200', t(() => { for (let i = 0; i < 200; i++) markdownModule.renderMarkdown(sample, 80); })]);
2372
+ }
2373
+ panel(c, panels.buildBenchmark(results, c.ctx));
2374
+ c.render();
2375
+ return true;
2376
+ },
2377
+ },
2378
+ {
2379
+ name: 'waifu', hint: '', category: 'fun',
2380
+ desc: 'Summon a waifu',
2381
+ handler: async (c) => {
2382
+ panel(c, panels.buildWaifu(c.ctx));
2383
+ c.render();
2384
+ return true;
2385
+ },
2386
+ },
2387
+
2388
+ // ── additional command families ─────────────────────────────────────────────
2389
+ {
2390
+ name: 'new', aliases: ['start'], hint: '', category: 'session',
2391
+ desc: 'Start a new session (clears the transcript, fresh session id)',
2392
+ handler: async (c) => {
2393
+ c.transcript.length = 0;
2394
+ // Release the conversation being left behind BEFORE the id changes — a
2395
+ // new session id is a new key, so the old entry would otherwise sit in
2396
+ // the engine's map for the life of the process, holding a `claude` child
2397
+ // session nobody can reach or clear again.
2398
+ if (typeof c.clearConversationMemory === 'function') c.clearConversationMemory();
2399
+ const id = 'aegis-' + Math.random().toString(36).slice(2, 10);
2400
+ c.sessionId = id;
2401
+ c.ctx.sessionId = id;
2402
+ note(c, `New session started (${id}) — earlier context cleared.`);
2403
+ c.render();
2404
+ return true;
2405
+ },
2406
+ },
2407
+ {
2408
+ name: 'tokens', aliases: ['tok'], hint: '', category: 'data',
2409
+ desc: 'Show token usage breakdown and estimated spend',
2410
+ handler: async (c) => {
2411
+ const acct = sessionAccounting(c.transcript, c.ctx.model);
2412
+ panel(c, panels.buildTokens({ ...c.state(), contextWindow: acct.contextWindow, costEur: acct.cost }, c.ctx));
2413
+ c.render();
2414
+ return true;
2415
+ },
2416
+ },
2417
+ {
2418
+ name: 'skills', aliases: ['sk'], args: ['sub'], hint: '[name|refresh]', category: 'session',
2419
+ desc: 'List skills (SKILL.md in the standard skill dirs)',
2420
+ handler: async (c, args) => {
2421
+ const sub = (args.sub || '').trim().toLowerCase();
2422
+ const found = scanSkills();
2423
+ const dirs = [
2424
+ path.join(os.homedir(), '.aegis', 'skills'),
2425
+ path.join(process.cwd(), '.aegis', 'skills'),
2426
+ path.join(os.homedir(), '.aegiscode', 'skills'),
2427
+ path.join(process.cwd(), '.aegiscode', 'skills'),
2428
+ path.join(os.homedir(), '.claude', 'skills'),
2429
+ ].map((d) => d.replace(os.homedir(), '~'));
2430
+ if (sub === 'refresh' || sub === 'reload') {
2431
+ note(c, `Skills refreshed — ${found.length} found (${dirs.length} dirs scanned).`);
2432
+ c.render();
2433
+ return true;
2434
+ }
2435
+ if (sub) {
2436
+ const skill = found.find((s) => s.name === sub);
2437
+ if (!skill) { note(c, `Unknown skill "${sub}". /skills lists what exists on disk.`); c.render(); return true; }
2438
+ panel(c, panels.buildSkillDetail(skill, c.ctx));
2439
+ c.render();
2440
+ return true;
2441
+ }
2442
+ panel(c, panels.buildSkills(found, dirs, c.ctx));
2443
+ c.render();
2444
+ return true;
2445
+ },
2446
+ },
2447
+ {
2448
+ name: 'thinking', args: ['mode'], hint: '[on|off]', category: 'model',
2449
+ desc: 'Toggle thinking blocks expanded/collapsed',
2450
+ handler: async (c, args) => {
2451
+ const mode = (args.mode || '').toLowerCase();
2452
+ if (mode && !['on', 'off'].includes(mode)) { note(c, 'Usage: /thinking [on|off]'); c.render(); return true; }
2453
+ const want = mode === 'on' ? true : mode === 'off' ? false : !(c.ctx.thinking === true);
2454
+ c.ctx.thinking = want;
2455
+ c.saveConfig({ thinking: want });
2456
+ note(c, `Thinking blocks: ${want ? 'expanded' : 'collapsed'}`);
2457
+ c.render();
2458
+ return true;
2459
+ },
2460
+ },
2461
+ {
2462
+ name: 'mcp', args: ['sub', 'name', 'command'], hint: '[add <name> <command> [args…]|remove <name>|<name>]', category: 'model',
2463
+ desc: 'Show MCP server configuration',
2464
+ handler: async (c, args) => {
2465
+ const cfg = loadConfig();
2466
+ const servers = cfg.mcpServers || {};
2467
+ const sub = (args.sub || '').toLowerCase();
2468
+ if (sub === 'add') {
2469
+ const name = (args.name || '').trim();
2470
+ const command = (args.command || '').trim();
2471
+ if (!name || !command) { note(c, 'Usage: /mcp add <name> "<command with args>"'); c.render(); return true; }
2472
+ const parts = command.split(/\s+/).filter(Boolean);
2473
+ updateConfig({ mcpServers: { ...servers, [name]: { command: parts[0], args: parts.slice(1) } } });
2474
+ note(c, `Added MCP server "${name}" (${parts[0]}). Configuration only — this build has no MCP runtime.`);
2475
+ c.render();
2476
+ return true;
2477
+ }
2478
+ if (sub === 'remove' || sub === 'rm') {
2479
+ const name = (args.name || '').trim();
2480
+ if (!name) { note(c, 'Usage: /mcp remove <name>'); c.render(); return true; }
2481
+ if (!servers[name]) { note(c, `No MCP server "${name}". /mcp lists the configured ones.`); c.render(); return true; }
2482
+ const next = { ...servers };
2483
+ delete next[name];
2484
+ updateConfig({ mcpServers: next });
2485
+ note(c, `Removed MCP server "${name}".`);
2486
+ c.render();
2487
+ return true;
2488
+ }
2489
+ if (sub && servers[sub]) {
2490
+ const srv = servers[sub];
2491
+ panel(c, [
2492
+ [span(C.gold, `MCP server: ${sub}`)],
2493
+ [span(C.gray, '─'.repeat(30))],
2494
+ [span(C.white, ` command: ${`${srv.command || ''} ${(srv.args || []).join(' ')}`.trim()}`)],
2495
+ [span('', '')],
2496
+ [span(C.gray, 'Configuration only — this build has no MCP runtime.')],
2497
+ ]);
2498
+ c.render();
2499
+ return true;
2500
+ }
2501
+ panel(c, panels.buildMcp(servers, [configPath(), permissionsPath()], c.ctx));
2502
+ c.render();
2503
+ return true;
2504
+ },
2505
+ },
2506
+ {
2507
+ name: 'memory', aliases: ['memories'], hint: '', category: 'model',
2508
+ desc: 'List the most recent AEGIS cloud-memory entries',
2509
+ tool: 'aegis_memory_list',
2510
+ build: () => ({}),
2511
+ },
2512
+ {
2513
+ name: 'memory-deep', aliases: ['recall-deep'], args: ['mode'], hint: '[on|off]', category: 'model',
2514
+ desc: 'Toggle DEEP recall for this session — brain corrections + cached answers (metered: one embedding per turn)',
2515
+ handler: async (c, args) => {
2516
+ const mode = (args.mode || '').toLowerCase();
2517
+ if (mode && !['on', 'off'].includes(mode)) { note(c, 'Usage: /memory-deep [on|off]'); c.render(); return true; }
2518
+ const want = mode === 'on' ? true : mode === 'off' ? false : !(c.ctx.recallDeep === true);
2519
+ c.ctx.recallDeep = want;
2520
+ // Deliberately session-scoped: nothing is written to config.json, because
2521
+ // this flag meters every turn (aegis1 services/brain_memory.py embeds the
2522
+ // query once per turn) and a silent restore on a later launch would bill
2523
+ // for a decision made in a session that has ended. Contrast /thinking,
2524
+ // which persists — it costs nothing. The cheap read half (`aegis_recall`)
2525
+ // is always on and has no toggle.
2526
+ note(c, `Deep recall: ${want ? 'on — brain corrections + cached answers, one embedding per turn' : 'off (only the cheap recall read)'}${want ? ' · this session only' : ''}`);
2527
+ c.render();
2528
+ return true;
2529
+ },
2530
+ },
2531
+ {
2532
+ name: 'confirm', aliases: ['confirmations'], args: ['mode'], hint: '[on|off]', category: 'model',
2533
+ desc: 'Toggle tool-call confirmation prompts',
2534
+ handler: async (c, args) => {
2535
+ const mode = (args.mode || '').toLowerCase();
2536
+ if (mode && !['on', 'off'].includes(mode)) { note(c, 'Usage: /confirm [on|off]'); c.render(); return true; }
2537
+ // ON8: the bare toggle reads the POSTURE (the shared `confirmMode` key
2538
+ // both faces write), never the rule file's `defaultMode`.
2539
+ //
2540
+ // Two reasons, and the second one is the user-visible bug. (1) Since ON8
2541
+ // the rule file holds the *residual* (`ask`/`allow`/`deny`) and the shared
2542
+ // key holds the posture — reading the residual would answer a question the
2543
+ // user did not ask, and `defaultMode: 'deny'` would read as "on". (2) The
2544
+ // old spelling (`rules.defaultMode !== 'allow'`) could be turned ON and
2545
+ // never OFF from the keyboard: `defaultMode` ships as 'ask', so a fresh
2546
+ // install already read as "on" and a bare `/confirm` wrote `ask` — the
2547
+ // same state it had just read — leaving prompts on with no way to toggle
2548
+ // them off. `confirmPosture()` is the one read, exactly like the engine's.
2549
+ const want = mode === 'on' ? true : mode === 'off' ? false : !confirmPosture().enabled;
2550
+ // ON8: one writer for the posture — the shared key the window's switch
2551
+ // reads, plus the rule residual this face's gate reads.
2552
+ setConfirmPosture(want);
2553
+ note(c, `Confirmation prompts: ${want ? 'on' : 'off'} (default permission mode: ${want ? 'ask' : 'allow'})`);
2554
+ c.render();
2555
+ return true;
2556
+ },
2557
+ },
2558
+ {
2559
+ name: 'automode', aliases: ['yolo'], args: ['mode'], hint: '[on|off]', category: 'model',
2560
+ desc: 'Toggle automode — auto-approve all tool executions',
2561
+ handler: async (c, args) => {
2562
+ const mode = (args.mode || '').toLowerCase();
2563
+ if (mode && !['on', 'off'].includes(mode)) { note(c, 'Usage: /automode [on|off]'); c.render(); return true; }
2564
+ // Same one read as `/confirm` above, with the polarity this command's
2565
+ // label implies: "automode" IS confirmations-off, so the bare toggle is
2566
+ // `!automode` == the posture itself. Reading the rule file here wrongly
2567
+ // reported automode as already-on for a fresh install (whose residual
2568
+ // ships as 'ask'), so the first bare `/automode` turned it OFF — the
2569
+ // opposite of what the word means to the person typing it — and the
2570
+ // inverse mistake (`!confirmPosture().enabled`) made the first press a
2571
+ // no-op with confirmations on. Both spellings are gone.
2572
+ const want = mode === 'on' ? true : mode === 'off' ? false : confirmPosture().enabled;
2573
+ // ON8: `/automode` (alias `/yolo`) is the posture's OFF state, written
2574
+ // through the one writer, so the window's switch shows it and the two
2575
+ // faces cannot disagree.
2576
+ setConfirmPosture(!want);
2577
+ // …and the SESSION's own half. The posture answers "does the window's
2578
+ // switch say don't ask"; the session flag answers "did this sitting start
2579
+ // in auto mode". They are two facts (the upstream engine keeps them apart:
2580
+ // AEGIS_AUTO_ROUNDS=0 starts manual without touching any stored posture),
2581
+ // and with an env opt-out standing, writing only the posture made this
2582
+ // command — and the `→` chord that dispatches it — a no-op that reported
2583
+ // success: the store said "off", the chip still read "manual mode on", and
2584
+ // the tool gate in app.js's isYolo kept asking. Moving both here is what
2585
+ // makes the opt-out escapable at the prompt instead of for the life of the
2586
+ // process. Guarded because an injected/older context may not carry it.
2587
+ if (typeof c.setAutoRounds === 'function') c.setAutoRounds(want);
2588
+ if (want) panel(c, panels.buildAutomode(c.state(), c.ctx));
2589
+ else note(c, 'automode off — confirmations restored.');
2590
+ c.render();
2591
+ return true;
2592
+ },
2593
+ },
2594
+ {
2595
+ name: 'multiyolo', aliases: ['multiauto'], args: ['task'], hint: '<task>', category: 'session',
2596
+ desc: 'Multi-agent orchestration with automode — /multiyolo <task>',
2597
+ handler: async (c, args) => {
2598
+ const task = (args._rest || args.task || '').trim();
2599
+ if (!task) { note(c, 'Usage: /multiyolo <task>'); c.render(); return true; }
2600
+ // automode is the point of this alias: auto-approve, then actually run the
2601
+ // fan-out. Composing the text and stopping (what this used to do) left the
2602
+ // user with an enabled automode and an unexecuted task.
2603
+ return runMultiCommand(c, task, { yolo: true });
2604
+ },
2605
+ },
2606
+ {
2607
+ name: 'router', args: ['sub', 'tier', 'modelId'], hint: '[on|off|set <tier> <modelId>|stats]', category: 'model',
2608
+ desc: 'Show or manage the model router config',
2609
+ handler: async (c, args) => {
2610
+ const cfg = loadConfig();
2611
+ const router = cfg.autoRouter || { enabled: false, tiers: {} };
2612
+ const sub = (args.sub || '').toLowerCase();
2613
+ const persist = (next) => updateConfig({ autoRouter: next });
2614
+ if (sub === 'on') { persist({ ...router, enabled: true }); note(c, 'Auto-router: on.'); c.render(); return true; }
2615
+ if (sub === 'off') { persist({ ...router, enabled: false }); note(c, 'Auto-router: off.'); c.render(); return true; }
2616
+ if (sub === 'set') {
2617
+ const tier = (args.tier || '').toLowerCase();
2618
+ const modelId = (args.modelId || '').trim();
2619
+ if (!['simple', 'medium', 'complex'].includes(tier) || !modelId) {
2620
+ note(c, 'Usage: /router set <simple|medium|complex> <modelId>');
2621
+ c.render();
2622
+ return true;
2623
+ }
2624
+ persist({ ...router, tiers: { ...(router.tiers || {}), [tier]: modelId } });
2625
+ note(c, `Auto-router: ${tier} -> ${modelId}`);
2626
+ c.render();
2627
+ return true;
2628
+ }
2629
+ if (sub === 'stats') {
2630
+ panel(c, [
2631
+ [span(C.gold + BOLD, 'Router stats'), span(BOLD_OFF, '')],
2632
+ [span(C.gray, '─'.repeat(30))],
2633
+ [span(C.gray, 'No learned outcomes yet — this build does not auto-route.')],
2634
+ [span(C.gray, 'Tiers: simple/medium/complex via /router set.')],
2635
+ ]);
2636
+ c.render();
2637
+ return true;
2638
+ }
2639
+ panel(c, panels.buildRouter(cfg, c.ctx));
2640
+ c.render();
2641
+ return true;
2642
+ },
2643
+ },
2644
+ {
2645
+ name: 'multi', args: ['task', 'mode'], hint: '<task> [run]', category: 'session',
2646
+ desc: 'Compose a multi-agent task (add "run" to execute)',
2647
+ handler: async (c, args) => {
2648
+ let task = (args._rest || args.task || '').trim();
2649
+ let mode = (args.mode || '').toLowerCase();
2650
+ if (mode !== 'run' && /\s+run$/i.test(task)) { mode = 'run'; task = task.replace(/\s+run$/i, '').trim(); }
2651
+ if (!task) { note(c, 'Usage: /multi <task> [run]'); c.render(); return true; }
2652
+ if (mode !== 'run') { panel(c, panels.buildAegisMulti(task, c.ctx)); c.render(); return true; }
2653
+ return runMultiCommand(c, task);
2654
+ },
2655
+ },
2656
+ {
2657
+ name: 'research', args: ['question'], hint: '<question>', category: 'session',
2658
+ desc: 'Research a topic with a multi-perspective council prompt',
2659
+ handler: async (c, args) => {
2660
+ const q = (args._rest || args.question || '').trim();
2661
+ if (!q) { note(c, 'Usage: /research <question>'); c.render(); return true; }
2662
+ const prompt = composeResearchPrompt(q, process.cwd());
2663
+ // Unguarded, `c.runPrompt` made this throw on any context without one
2664
+ // (the command smoke test caught the class of bug; the reference guards
2665
+ // it the same way). Composed-but-unrunnable is reported, not swallowed.
2666
+ if (c.runPrompt) {
2667
+ await c.runPrompt(prompt);
2668
+ return true;
2669
+ }
2670
+ note(c, `Composed research prompt (${prompt.length} chars) — run in the TUI to send it.`);
2671
+ c.render();
2672
+ return true;
2673
+ },
2674
+ },
2675
+ {
2676
+ name: 'debate', aliases: ['db'], args: ['topic'], hint: '<topic>', category: 'session',
2677
+ desc: 'Run a structured debate on the current model',
2678
+ handler: async (c, args) => {
2679
+ const topic = (args._rest || args.topic || '').trim();
2680
+ if (!topic) { note(c, 'Usage: /debate <topic>'); c.render(); return true; }
2681
+ const prompt = composeDebatePrompt(topic, c.ctx.model || '');
2682
+ if (c.runPrompt) {
2683
+ await c.runPrompt(prompt);
2684
+ return true;
2685
+ }
2686
+ note(c, `Composed debate prompt (${prompt.length} chars) — run in the TUI to send it.`);
2687
+ c.render();
2688
+ return true;
2689
+ },
2690
+ },
2691
+ {
2692
+ name: 'billing', aliases: ['balance', 'spend'], hint: '', category: 'support',
2693
+ desc: 'Show billing info — token-bank balance and recent spend',
2694
+ handler: async (c) => {
2695
+ // The account is the source of truth for the balance and ledger; the
2696
+ // session panel below adds this session's spend.
2697
+ await c.runTool('aegis_balance', {});
2698
+ const spend = await c.refreshSpend();
2699
+ const st = c.state();
2700
+ panel(c, panels.buildBilling({
2701
+ ...st,
2702
+ balance: spend && spend.balance != null ? spend.balance : st.balance,
2703
+ // The paid prompt, from the SAME gate that decides the fan-out. This is
2704
+ // the whole reason `/billing` can be trusted to say what Pro costs: the
2705
+ // verdict and the ceiling come from one decision (`is_pro` mirrored by
2706
+ // the shared module) instead of a second, panel-local guess about the
2707
+ // account — two readings is how a screen ends up selling Pro to someone
2708
+ // who owns it, or telling a paying customer their bank is empty.
2709
+ //
2710
+ // A probe that cannot be built (no shared module, no client) leaves the
2711
+ // field unset: the panel then prints its plain top-up row rather than an
2712
+ // unverified pitch. Never the reverse — a failure here must not invent
2713
+ // a wall.
2714
+ payment: await billingPayment(c),
2715
+ }, c.ctx));
2716
+ c.render();
2717
+ return true;
2718
+ },
2719
+ },
2720
+ {
2721
+ // The in-session top-up. `/billing` printed a link and that was the whole
2722
+ // funding story in the terminal; the link is real but it lands on `/topup`,
2723
+ // which is `@login_required` against a browser SESSION, and the account this
2724
+ // product auto-provisions is a device key with no password anyone holds and
2725
+ // an email at `@device.aegiscloud`. So the user who needs to fund a free
2726
+ // account could not sign in to the page that funds it — they paid a visit to
2727
+ // a login wall and read it as "my payment failed".
2728
+ //
2729
+ // This does what the desktop does, over the SAME shared core
2730
+ // (`client/topup.js`): the credential that creates the checkout is the one
2731
+ // that can read the bank, so the confirmation comes from the API rather than
2732
+ // from a page the account cannot open. Bounds and payload reading are shared,
2733
+ // never re-derived here.
2734
+ name: 'topup', aliases: ['fund'], args: ['amount'], hint: '[EUR]', category: 'support',
2735
+ desc: 'Top up the token bank — opens the payment page and confirms the credit here',
2736
+ handler: async (c, args) => {
2737
+ const raw = String(args.amount || args._rest || '').trim();
2738
+ let shared;
2739
+ try {
2740
+ // Lazy: the TUI pays for this only when someone asks to pay.
2741
+ shared = require(require('./sharedpaths.js').resolveShared('client/topup.js'));
2742
+ } catch (e) {
2743
+ note(c, `top-up is unavailable in this build — ${e.message}`);
2744
+ c.render();
2745
+ return true;
2746
+ }
2747
+ const parsed = shared.parseTopupAmount(raw);
2748
+ if (!parsed.ok) {
2749
+ note(c, parsed.message);
2750
+ c.render();
2751
+ return true;
2752
+ }
2753
+ if (!c.client.apiKey) {
2754
+ // Same honest refusal the rest of the account surfaces give, and the
2755
+ // same fix: the key is what pays. Auto-provisioning happens on session
2756
+ // start (app.js ensureApiKey), so this is the offline/failed case.
2757
+ note(c, `no AEGIS key on this machine — ${credentials.HOW_TO_SET}, then /topup ${parsed.amount}`);
2758
+ c.render();
2759
+ return true;
2760
+ }
2761
+ const started = c.withWorking
2762
+ ? await c.withWorking(() => shared.startTopup(c.client, parsed.amount))
2763
+ : await shared.startTopup(c.client, parsed.amount);
2764
+ if (!started.ok) {
2765
+ note(c, `the top-up could not be started — ${started.message}`);
2766
+ if (started.hint) note(c, started.hint);
2767
+ c.render();
2768
+ return true;
2769
+ }
2770
+ // The URL rides its own row: `note` rows are a single unwrapped span
2771
+ // (chatflow.js), so appending it to that sentence pushes the tail past
2772
+ // `cols` where `padLine()` cuts it — and the tail is the URL.
2773
+ note(c, `opening the payment page — ${parsed.amount} EUR`);
2774
+ note(c, started.url);
2775
+ const seconds = Math.round((shared.TOPUP_POLL_MS * shared.TOPUP_POLL_TRIES) / 1000);
2776
+ note(c, `watching this account's bank for up to ${seconds}s; the credit is confirmed here, not in the browser`);
2777
+ c.render();
2778
+ const open = openUrl(started.url);
2779
+ if (!open) note(c, 'could not open a browser — use the URL above');
2780
+
2781
+ // A recursive timeout rather than an interval: the balance call can take
2782
+ // longer than one period on a slow link, and an interval would start a
2783
+ // second read on top of the first — two reads, two announcements of one
2784
+ // credit. Unref'd so an unfinished payment never keeps the TUI alive.
2785
+ const watch = shared.createCreditWatch(c.client);
2786
+ let timer = null;
2787
+ let done = false;
2788
+ const settle = () => {
2789
+ done = true;
2790
+ if (timer) clearTimeout(timer);
2791
+ };
2792
+ const step = async () => {
2793
+ if (done) return;
2794
+ const res = await watch.tick();
2795
+ if (res.state === 'credited') {
2796
+ settle();
2797
+ note(c, `credit confirmed — the bank is now ${res.amount.toFixed(2)} EUR`);
2798
+ c.render();
2799
+ return;
2800
+ }
2801
+ if (res.state === 'expired') {
2802
+ settle();
2803
+ note(c, 'no credit observed within the watch window — if you completed the payment it may still land; /billing shows the bank');
2804
+ c.render();
2805
+ return;
2806
+ }
2807
+ timer = setTimeout(step, shared.TOPUP_POLL_MS);
2808
+ if (timer && typeof timer.unref === 'function') timer.unref();
2809
+ };
2810
+ timer = setTimeout(step, shared.TOPUP_POLL_MS);
2811
+ if (timer && typeof timer.unref === 'function') timer.unref();
2812
+ return true;
2813
+ },
2814
+ },
2815
+ {
2816
+ name: 'cloud', args: ['sub', 'value'], hint: '[status|key <api_key>|activate|deactivate|memory [on|off]|sync [on|off|now]]', category: 'support',
2817
+ desc: 'Show and control ÆGIS cloud sync',
2818
+ handler: async (c, args) => {
2819
+ const sub = (args.sub || '').toLowerCase();
2820
+ const rest = (args.value || args._rest || '').trim();
2821
+
2822
+ if (sub === 'key') {
2823
+ await applyAccountKey(c, rest);
2824
+ c.render();
2825
+ return true;
2826
+ }
2827
+
2828
+ if (sub === 'activate') {
2829
+ if (!c.client.apiKey) {
2830
+ note(c, `no key — ${credentials.HOW_TO_SET}`);
2831
+ c.render();
2832
+ return true;
2833
+ }
2834
+ try {
2835
+ const res = await c.withWorking(() => c.client.memoryActivate());
2836
+ const token = await c.client.getMemoryToken();
2837
+ if (token) credentials.saveMemoryToken(token, { memorySubscribed: true });
2838
+ done(c, res && res.ok === false ? 'the server refused activation' : 'cloud memory activated for this account');
2839
+ if (res && res.token_limit) note(c, `quota: ${res.tokens_used || 0} / ${res.token_limit} synced tokens`);
2840
+ } catch (e) {
2841
+ note(c, `activation failed: ${e.message}`);
2842
+ }
2843
+ c.render();
2844
+ return true;
2845
+ }
2846
+
2847
+ if (sub === 'deactivate') {
2848
+ // There is no /api/memory/deactivate on the server, so this clears the
2849
+ // credential this host holds rather than pretending to unenrol the
2850
+ // account. Saying which one it did is the difference between a control
2851
+ // and a lie.
2852
+ credentials.clearMemoryToken();
2853
+ c.client.setApiKey(c.client.apiKey);
2854
+ note(c, 'cloud memory token cleared locally — sync stops until /cloud activate re-issues one');
2855
+ // The URL rides its own note: `note` rows are a single unwrapped span
2856
+ // (chatflow.js), so appending it to that sentence would push the tail
2857
+ // past `cols` where `padLine()` cuts it — and the tail is the URL.
2858
+ note(c, 'the account itself is still subscribed; manage the subscription here:');
2859
+ note(c, goUrl('upgrade', 'cloud_deactivate'));
2860
+ c.render();
2861
+ return true;
2862
+ }
2863
+
2864
+ if (sub === 'memory' || sub === 'persist' || sub === 'memory-persist') {
2865
+ // The write half's one switch. `/cloud sync on|off` and `/sync on|off`
2866
+ // still work (they always meant "should this host store my sessions"),
2867
+ // but this is the name that says what is actually being flipped.
2868
+ const mode = (rest || 'status').toLowerCase();
2869
+ if (mode === 'on' || mode === 'off') {
2870
+ const on = mode === 'on';
2871
+ setMemoryGate(c, on);
2872
+ if (on) {
2873
+ done(c, 'persisting memory on — sessions are stored to your account so an interrupted turn can be resumed');
2874
+ note(c, '/cloud memory shows the quota; past the plan’s ceiling reads keep working and only new writes pause');
2875
+ } else {
2876
+ note(c, 'persisting memory off — nothing new is stored');
2877
+ note(c, 'everything already in the cloud stays readable (/aegis-recall <topic>), and /sync now still pushes once by hand');
2878
+ }
2879
+ c.render();
2880
+ return true;
2881
+ }
2882
+ panel(c, memoryStatusLines(c));
2883
+ c.render();
2884
+ return true;
2885
+ }
2886
+
2887
+ if (sub === 'sync' || sub === 'push' || sub === 'pull') {
2888
+ const mode = sub === 'sync' ? (rest || 'status').toLowerCase() : sub;
2889
+ if (mode === 'on' || mode === 'off') {
2890
+ const on = mode === 'on';
2891
+ setMemoryGate(c, on);
2892
+ note(c, on ? 'persisting memory on — sessions are stored after each turn (this is the old "cloud sync")' : 'persisting memory off — nothing new is stored; /sync now still runs a manual pass');
2893
+ c.render();
2894
+ return true;
2895
+ }
2896
+ if (mode === 'now') {
2897
+ await runCloudSync(c);
2898
+ c.render();
2899
+ return true;
2900
+ }
2901
+ const st = cloudsync.status();
2902
+ panel(c, [
2903
+ ...memoryStatusLines(c),
2904
+ [span(C.gray, '')],
2905
+ [span(C.white + BOLD, 'Sync ledger'), span(BOLD_OFF, '')],
2906
+ [span(C.gray, ` local sessions: ${st.local} · pending push: ${st.pending} · in sync: ${st.synced}`)],
2907
+ [span(C.gray, ` last push: ${st.lastPushAt ? new Date(st.lastPushAt).toLocaleString() : 'never'} · last pull: ${st.lastPullAt ? new Date(st.lastPullAt).toLocaleString() : 'never'}`)],
2908
+ [span(C.gray, ` state: ${st.path}`)],
2909
+ ]);
2910
+ for (const e of st.errors.slice(0, 3)) {
2911
+ panel(c, [[span(C.coral, ` ⚠ ${e.error}`)]]);
2912
+ }
2913
+ c.render();
2914
+ return true;
2915
+ }
2916
+
2917
+ // Default: the whole picture — key plus sync state.
2918
+ const st = cloudsync.status();
2919
+ panel(c, [
2920
+ ...keyPanelLines(c, 'AEGIS cloud'),
2921
+ [span(C.gray, '')],
2922
+ ...memoryStatusLines(c),
2923
+ [span(C.gray, '')],
2924
+ [span(C.white + BOLD, ' Sync'), span(BOLD_OFF, '')],
2925
+ [span(C.gray, ` ${st.pending} pending · ${st.synced} in sync · ${st.importedRemote} pulled from cloud`)],
2926
+ // Both names, because both work: `/cloud memory` is the new one that
2927
+ // says what is being flipped, and `/cloud sync` is what every user who
2928
+ // has ever turned this off typed (it dispatched here before the flip
2929
+ // renamed the panel, and still does — see the `sub === 'sync'` branch).
2930
+ // Advertising only the new name hides a working control behind a
2931
+ // rename, which is how a setting becomes a rumour.
2932
+ [span(C.gray, ' /cloud memory on | off · /cloud sync on | off · /sync now')],
2933
+ ]);
2934
+ c.render();
2935
+ return true;
2936
+ },
2937
+ },
2938
+ {
2939
+ name: 'key', aliases: ['apikey', 'api-key'], args: ['value'], hint: '[<api_key>|status|clear|register]', category: 'auth',
2940
+ desc: 'Save or show the AEGIS account key',
2941
+ handler: async (c, args) => {
2942
+ const arg = String(args.value || args._rest || '').trim();
2943
+ const lower = arg.toLowerCase();
2944
+ if (lower === 'status') {
2945
+ panel(c, keyPanelLines(c));
2946
+ c.render();
2947
+ return true;
2948
+ }
2949
+ if (lower === 'register') {
2950
+ const res = await c.registerAccount();
2951
+ if (res.alreadyKeyed) {
2952
+ // Registration is per machine fingerprint and the welcome trial is
2953
+ // granted once per machine, ever, so this branch can never produce a
2954
+ // new trial however many times it is run — and a user who wiped their
2955
+ // credential store lands here precisely expecting one. Say so, and
2956
+ // name the two paths that actually do something, rather than a
2957
+ // no-op notice that reads like a refusal for no reason.
2958
+ note(c, 'this machine already has an AEGIS key — /key status shows it. Re-registering cannot mint a new welcome trial: that is granted once per machine, ever. For a fresh trial, sign up at aegiscloud.org; to point this session at a different key, /key clear first.');
2959
+ } else if (res.key && res.ok) {
2960
+ done(c, 'AEGIS account key provisioned and saved');
2961
+ } else if (res.key) {
2962
+ note(c, 'the account was created but its key could not be saved — run /key <api_key> with the key from aegiscloud.org');
2963
+ } else {
2964
+ note(c, `could not register this machine: ${res.error ? res.error.message : 'the server returned no account key'}`);
2965
+ }
2966
+ c.render();
2967
+ return true;
2968
+ }
2969
+ if (lower === 'clear' || lower === 'remove' || lower === 'rm') {
2970
+ const res = c.forgetApiKey();
2971
+ done(c, res.cleared ? `key removed from ${res.path}` : 'there was no saved key to remove');
2972
+ if (credentials.legacyKeyOnDisk()) {
2973
+ note(c, `a copy is still in ${configPath()} (written by another AEGIS CLI) — delete the "aegiscloud" block to finish the job`);
2974
+ }
2975
+ c.render();
2976
+ return true;
2977
+ }
2978
+ await applyAccountKey(c, arg);
2979
+ c.render();
2980
+ return true;
2981
+ },
2982
+ },
2983
+ {
2984
+ name: 'sync', aliases: ['cloudsync', 'cloud-sync'], args: ['mode'], hint: '[now|on|off|status]', category: 'data',
2985
+ desc: 'Store sessions in AEGIS Cloud (cross-session memory)',
2986
+ hidden: (c) => !cloudReady(),
2987
+ handler: async (c, args) => {
2988
+ const mode = (args.mode || '').toLowerCase();
2989
+ if (mode === 'on' || mode === 'off') {
2990
+ setMemoryGate(c, mode === 'on');
2991
+ note(c, mode === 'on' ? 'persisting memory on — sessions are stored so an interrupted turn can be resumed' : 'persisting memory off — nothing new is stored; /sync now still runs a manual pass');
2992
+ c.render();
2993
+ return true;
2994
+ }
2995
+ if (mode === 'status') {
2996
+ const st = cloudsync.status();
2997
+ const rows = memoryStatusLines(c);
2998
+ rows.push([span(C.gray, '')]);
2999
+ rows.push([span(C.gray, ` local ${st.local} · pending ${st.pending} · in sync ${st.synced}`)]);
3000
+ panel(c, rows);
3001
+ c.render();
3002
+ return true;
3003
+ }
3004
+ // Bare /sync and /sync now both do the thing: this is the command a user
3005
+ // reaches for when they want their sessions in the cloud right now.
3006
+ await runCloudSync(c);
3007
+ c.render();
3008
+ return true;
3009
+ },
3010
+ },
3011
+ {
3012
+ name: 'gmail', hint: '', category: 'support',
3013
+ desc: 'Link Gmail to conversations',
3014
+ handler: async (c) => {
3015
+ note(c, 'Gmail integration needs Google OAuth — not available in this build. Use /export to save conversations to files instead.');
3016
+ c.render();
3017
+ return true;
3018
+ },
3019
+ },
3020
+ {
3021
+ name: 'clone', aliases: ['fetch-site', 'websnap'], args: ['url'], hint: '<url>', category: 'workspace',
3022
+ desc: 'Clone a website into a local project',
3023
+ handler: async (c, args) => {
3024
+ const url = (args._rest || args.url || '').trim();
3025
+ if (!url) { note(c, 'Usage: /clone <url>'); c.render(); return true; }
3026
+ note(c, `/clone needs a web-fetch tool and a chat service — not available in this build. Use /init to scaffold a fresh project instead of ${url}.`);
3027
+ c.render();
3028
+ return true;
3029
+ },
3030
+ },
3031
+ {
3032
+ name: 'release-notes', hint: '', category: 'support',
3033
+ desc: "What's new",
3034
+ handler: async (c) => {
3035
+ panel(c, panels.buildReleaseNotes(c.state(), c.ctx));
3036
+ c.render();
3037
+ return true;
3038
+ },
3039
+ },
3040
+
3041
+ // ── /aegis-* family ───────────────────────────────────────────────────────
3042
+ {
3043
+ name: 'aegis-status', hint: '', category: 'aegis',
3044
+ desc: 'Show account status — API key, plan, account and cloud memory',
3045
+ tool: 'aegis_status',
3046
+ build: () => ({}),
3047
+ },
3048
+ {
3049
+ name: 'aegis-ask', aliases: ['ask'], args: ['question'], hint: '<question>', category: 'aegis',
3050
+ desc: 'Ask ÆGIS pooled inference a question (auto-routed)',
3051
+ tool: 'aegis_ask',
3052
+ build: (arg) => ({ prompt: arg }),
3053
+ },
3054
+ {
3055
+ name: 'aegis-recall', aliases: ['recall'], args: ['topic'], hint: '<topic>', category: 'aegis',
3056
+ desc: 'Recall cross-session memory about a topic (cloud)',
3057
+ tool: 'aegis_memory_search',
3058
+ build: (arg) => ({ query: arg }),
3059
+ },
3060
+ {
3061
+ name: 'aegis-remember', aliases: ['remember'], args: ['note'], hint: '<note>', category: 'aegis',
3062
+ desc: 'Save a note or decision to cross-session memory',
3063
+ tool: 'aegis_memory_save',
3064
+ build: (arg) => ({ content: arg }),
3065
+ },
3066
+ {
3067
+ name: 'aegis-council', aliases: ['council'], args: ['question'], hint: '<question>', category: 'aegis',
3068
+ desc: 'Put a question to the ÆGIS council (multi-perspective deliberation)',
3069
+ hidden: () => !cloudReady(),
3070
+ handler: async (c, args) => {
3071
+ const q = (args._rest || args.question || '').trim();
3072
+ if (!q) { note(c, 'Usage: /aegis-council <question>'); c.render(); return true; }
3073
+ const prompt = composeResearchPrompt(`Deliberate as a council and vote on: ${q}`, process.cwd());
3074
+ if (c.runPrompt) {
3075
+ await c.runPrompt(prompt);
3076
+ return true;
3077
+ }
3078
+ note(c, `Composed council prompt (${prompt.length} chars) — run in the TUI to send it.`);
3079
+ c.render();
3080
+ return true;
3081
+ },
3082
+ },
3083
+ {
3084
+ name: 'aegis-print', args: ['question'], hint: '<question>', category: 'aegis',
3085
+ desc: 'Ask pooled inference and print the answer cleanly',
3086
+ hidden: () => !cloudReady(),
3087
+ handler: async (c, args) => {
3088
+ const q = (args._rest || args.question || '').trim();
3089
+ if (!q) { note(c, 'Usage: /aegis-print <question>'); c.render(); return true; }
3090
+ const res = await c.ask(q);
3091
+ panel(c, panels.buildAegisPrint('ÆGIS', { result: res.text, model: res.model, provider: 'aegis' }, c.ctx));
3092
+ c.render();
3093
+ return true;
3094
+ },
3095
+ },
3096
+ {
3097
+ name: 'aegis-multi', args: ['task', 'mode'], hint: '<task> [run]', category: 'aegis',
3098
+ desc: 'Compose an ÆGIS /multi multi-agent task (add "run" to execute)',
3099
+ hidden: () => !cloudReady(),
3100
+ handler: async (c, args) => {
3101
+ let task = (args._rest || args.task || '').trim();
3102
+ let mode = (args.mode || '').toLowerCase();
3103
+ if (mode !== 'run' && /\s+run$/i.test(task)) { mode = 'run'; task = task.replace(/\s+run$/i, '').trim(); }
3104
+ if (!task) { note(c, 'Usage: /aegis-multi <task> [run]'); c.render(); return true; }
3105
+ if (mode !== 'run') { panel(c, panels.buildAegisMulti(task, c.ctx)); c.render(); return true; }
3106
+ return runMultiCommand(c, task);
3107
+ },
3108
+ },
3109
+
3110
+ // ── cloud-only additions (not in the reference vocabulary) ────────────────
3111
+ {
3112
+ // A bare `provider -> info` map is the wrong shape for a picker: it can only
3113
+ // describe providers you have ALREADY set, and the question this command
3114
+ // answers is "which key should I go buy". A command is either handler- or
3115
+ // tool-backed, never both (`cli-commands.test.mjs` enforces exactly one), so
3116
+ // this is handler-backed and reaches for the tool by name only as the
3117
+ // fallback for a server that predates the catalog — the command still works,
3118
+ // just with the older, sparser answer.
3119
+ name: 'byok', hint: '', category: 'auth',
3120
+ desc: 'List every provider you can bring your own key for, and which are set',
3121
+ handler: async (c) => {
3122
+ const providers = await byokCatalog(c.client);
3123
+ if (!providers) {
3124
+ await c.runTool('aegis_byok_status', {});
3125
+ return true;
3126
+ }
3127
+ const set = providers.filter((p) => p.configured).length;
3128
+ const lines = [
3129
+ [span(C.gold + BOLD, 'Bring your own key'), span(BOLD_OFF, '')],
3130
+ [span(C.gray, '─'.repeat(34))],
3131
+ [
3132
+ span(set ? C.green : C.gray, ` ${set} of ${providers.length} providers set`),
3133
+ // Name the PICKER first: the id is the one thing this screen was
3134
+ // asking the reader to copy by eye, and `/byok-list` removes that
3135
+ // step. The typed form stays beside it for scripts and for anyone who
3136
+ // already knows the id.
3137
+ span(C.gray, ' — /byok-list picks one, or /byok-key <provider>'),
3138
+ ],
3139
+ '',
3140
+ ...byokProviderLines(providers),
3141
+ ];
3142
+ panel(c, lines);
3143
+ c.render();
3144
+ return true;
3145
+ },
3146
+ },
3147
+ {
3148
+ name: 'byok-set', args: ['provider'], hint: '<provider>', category: 'auth',
3149
+ desc: 'Store your provider key on your AEGIS ACCOUNT (pooled route) — for the byok class use /byok-key',
3150
+ tool: 'aegis_byok_set',
3151
+ secret: 'key',
3152
+ build: (arg) => ({ provider: String(arg || '').trim() }),
3153
+ /**
3154
+ * Say which key this is and where to get it, before the prompt.
3155
+ *
3156
+ * The old prompt was `provider key for openai:` — which assumes the reader
3157
+ * already knows that a provider id is a company, and leaves them nothing to
3158
+ * check a pasted key against. Here the catalog names the provider, lists the
3159
+ * models the key unlocks, links the place to create it, and states the
3160
+ * prefix a valid key begins with, so a key for the wrong vendor is visible
3161
+ * before it is stored rather than as an upstream 401 later.
3162
+ *
3163
+ * Resolved against aliases too, so the prompt agrees with the id that will
3164
+ * actually be sent (`/byok-set OpenAI` → `openai`, not `OpenAI`).
3165
+ */
3166
+ async secretDescribe(args, client) {
3167
+ const typed = String(args.provider || '').trim();
3168
+ const providers = await byokCatalog(client);
3169
+ if (!providers) {
3170
+ // No catalog: still refuse to prompt for an empty provider, and keep the
3171
+ // words "provider key" so the request is intelligible on its own.
3172
+ return typed ? null : { note: 'Usage: /byok-set <provider> — /byok lists them.', prompt: 'provider key: ' };
3173
+ }
3174
+ const match = findByokProvider(providers, typed);
3175
+ if (match.ambiguous) {
3176
+ return {
3177
+ note: `"${typed}" matches ${match.ambiguous.join(', ')} — retype the exact id. Nothing was sent.`,
3178
+ prompt: null,
3179
+ };
3180
+ }
3181
+ const p = match.provider;
3182
+ if (!p) {
3183
+ const ids = providers.map((x) => x.id).join(', ');
3184
+ return { note: `unknown provider "${typed}". Known ids: ${ids}`, prompt: null };
3185
+ }
3186
+ if (p.configured) {
3187
+ return {
3188
+ note: `${p.id} already has a key${p.masked ? ` (${p.masked})` : ''} — pasting a new one replaces it.`,
3189
+ prompt: `new ${p.label || p.id} key: `,
3190
+ provider: p.id,
3191
+ };
3192
+ }
3193
+ const bits = [`${p.label || p.id}`];
3194
+ const models = (p.models || [])
3195
+ .map((m) => (typeof m === 'string' ? m : m && m.id))
3196
+ .filter(Boolean);
3197
+ if (models.length) bits.push(`unlocks ${models.join(', ')}`);
3198
+ if (p.key_prefix) bits.push(`key starts with ${p.key_prefix}`);
3199
+ if (p.key_url) bits.push(`create one at ${p.key_url}`);
3200
+ return { note: bits.join(' · '), prompt: `${p.id} key: `, provider: p.id };
3201
+ },
3202
+ },
3203
+ {
3204
+ name: 'byok-rm', args: ['provider'], hint: '<provider>', category: 'auth',
3205
+ desc: 'Remove a stored provider key',
3206
+ tool: 'aegis_byok_set',
3207
+ build: (arg) => ({ provider: String(arg || '').trim() }),
3208
+ },
3209
+ {
3210
+ name: 'class', args: ['class', 'mode'], hint: '[aegis|byok|local|pro [on|off]]', category: 'model',
3211
+ desc: 'Show or switch which class turns run on; pro (your Claude subscription) needs a one-time "on"',
3212
+ handler: async (c, a) => {
3213
+ const args = a || {};
3214
+ const cur = (c.ctx && c.ctx.modelClass) || 'aegis';
3215
+ const label = (id) => (c.classLabel ? c.classLabel(id) : id);
3216
+ const want = String(args.class || '').trim().toLowerCase();
3217
+ // `/class pro on|off` — the one-time opt-in for the subscription class.
3218
+ //
3219
+ // `pro` spends a real Claude Code Pro/Max subscription by spawning the
3220
+ // `claude` CLI, and an account whose organization has disabled Claude
3221
+ // Code answers every such turn with `oauth_org_not_allowed`, which this
3222
+ // repo cannot fix. So `pro` ships DISABLED (config.js `proEnabled: false`)
3223
+ // and this is the only way in: an explicit, deliberate word from the
3224
+ // user. Written through saveConfig so it survives a restart — an opt-in
3225
+ // that reverted on the next launch would put the class back out of reach
3226
+ // with no way to tell why.
3227
+ if (want === 'pro' && args.mode) {
3228
+ const mode = String(args.mode).trim().toLowerCase();
3229
+ if (mode !== 'on' && mode !== 'off') {
3230
+ c.push({ role: 'error', text: `usage: /class pro [on|off] — got "${args.mode}"` });
3231
+ return true;
3232
+ }
3233
+ const on = mode === 'on';
3234
+ c.saveConfig({ proEnabled: on });
3235
+ c.push({
3236
+ role: on ? 'done' : 'note',
3237
+ text: on
3238
+ ? 'pro class enabled — /class pro switches to your Claude Code subscription. ' +
3239
+ 'It runs only if that subscription has Claude Code access.'
3240
+ : 'pro class disabled — it is no longer offered by /class or the model picker.',
3241
+ });
3242
+ // Turning it off while sitting on it would leave the session pointing
3243
+ // at a class that can no longer run: fall back to the default class
3244
+ // through the same path `/class aegis` takes, so the pin rules and the
3245
+ // stored config are updated rather than only the panel.
3246
+ if (!on && cur === 'pro') {
3247
+ const back = c.switchClass('aegis');
3248
+ if (back.ok) c.push({ role: 'note', text: `class: ${back.class} — ${label(back.class)}` });
3249
+ }
3250
+ return true;
3251
+ }
3252
+ if (!want) {
3253
+ // Awaited: the engine's listClasses() is async (it probes for a local
3254
+ // Ollama before answering), and a context that offers no class surface
3255
+ // at all falls back to the two static rows below.
3256
+ const classes = await Promise.resolve(c.classes ? c.classes() : []).catch(() => []);
3257
+ const rows = classes.length ? classes : [{ class: 'aegis' }, { class: 'byok' }];
3258
+ const sel = rows.findIndex((k) => k.class === cur);
3259
+ // An interactive picker, not a static panel — the same tab/arrow/enter
3260
+ // overlay machinery /model already uses (chatflow.js handleOverlayKey),
3261
+ // so a class is switched by moving the highlight and hitting enter
3262
+ // rather than retyping its name after reading it off this list.
3263
+ c.openOverlay({ type: 'class', items: rows, sel: sel < 0 ? 0 : sel, current: cur });
3264
+ return true;
3265
+ }
3266
+ const res = c.switchClass(want);
3267
+ if (!res.ok) {
3268
+ c.push({ role: 'error', text: res.error });
3269
+ return true;
3270
+ }
3271
+ c.push({ role: 'done', text: `class: ${res.class} — ${label(res.class)}` });
3272
+ if (res.cleared) {
3273
+ c.push({
3274
+ role: 'note',
3275
+ text: `cleared the pin "${res.cleared}" — it does not belong to this class. /models lists what fits.`,
3276
+ });
3277
+ }
3278
+ // Entering byok with nothing pinned fails the very next turn: the relay's
3279
+ // model id must be "<provider>:<model>" and there is no server default to
3280
+ // fall back to (engine.js chatCompletion throws a 400 on a bare id). So
3281
+ // land on one this machine can actually run — a provider it holds a key
3282
+ // for wins, since the alternative 400s on the key rather than the id.
3283
+ if (res.class === 'byok' && !(c.ctx && c.ctx.model)) {
3284
+ // The byok list carries the pooled Nexus row too (app.js
3285
+ // classScopedModels) so the lane is discoverable — but this host cannot
3286
+ // RUN it under byok: the relay reads a pinned id as a provider name, so
3287
+ // auto-pinning Nexus here would fail the very next turn, which is the
3288
+ // failure this whole branch exists to avoid. Pick from this class's own
3289
+ // rows only.
3290
+ const models = ((await c.listModelsFor('byok')) || [])
3291
+ .filter((m) => !m.cls || m.cls === 'byok');
3292
+ const pick = models.find((m) => m.configured) || models[0];
3293
+ if (pick) {
3294
+ c.ctx.model = pick.id;
3295
+ c.saveConfig({ model: pick.id, currentModelId: pick.id });
3296
+ c.push({
3297
+ role: 'note',
3298
+ text: pick.configured
3299
+ ? `using ${pick.id} — /models lists the rest.`
3300
+ : `using ${pick.id}, but no ${pick.provider} key is saved yet — /byok-key ${pick.provider}.`,
3301
+ });
3302
+ } else if (models.length === 0) {
3303
+ c.push({
3304
+ role: 'note',
3305
+ text: 'nothing to relay yet — save a provider key with /byok-key <provider>, then /models.',
3306
+ });
3307
+ }
3308
+ }
3309
+ return true;
3310
+ },
3311
+ },
3312
+ {
3313
+ name: 'models', aliases: ['model-list'], hint: '', category: 'model',
3314
+ desc: 'Pick a model to pin, for the class you are on — opens the same picker as /model',
3315
+ handler: async (c) => {
3316
+ const cls = (c.ctx && c.ctx.modelClass) || 'aegis';
3317
+ const models = (await c.listModelsFor(cls)) || [];
3318
+ if (!models.length) {
3319
+ note(c, cls === 'byok'
3320
+ ? 'nothing to relay yet — save a provider key with /byok-key <provider>'
3321
+ : 'no models advertised — check the account with /status, then retry');
3322
+ c.render();
3323
+ return true;
3324
+ }
3325
+ const pinned = c.ctx && c.ctx.model;
3326
+ // A row from the OTHER class rides on this list on purpose — the pooled
3327
+ // Nexus row is what makes the byok list able to show a way back to the
3328
+ // pooled lane (app.js classScopedModels). It is not a row of THIS
3329
+ // class's own ids, so its note says which class it actually runs on
3330
+ // instead of looking like a byok id that would 400 at the relay.
3331
+ const items = models.map((m) => (m.cls && m.cls !== cls
3332
+ ? { ...m, note: `${m.note || m.label || ''} · pooled lane — /class ${m.cls}` }
3333
+ : m));
3334
+ const sel = items.findIndex((m) => m.id === pinned);
3335
+ // Same overlay /model opens (tab/arrow to move, enter to pin — see
3336
+ // chatflow.js handleOverlayKey), just scoped to this class's own rows
3337
+ // rather than /model's merged cross-class catalog. Picking the other
3338
+ // class's row switches class first, the same cross-class pin
3339
+ // applyModelRow already does for /model's own rows.
3340
+ c.openOverlay({ type: 'model', items, sel: sel < 0 ? 0 : sel, current: pinned, cls });
3341
+ return true;
3342
+ },
3343
+ },
3344
+ {
3345
+ // `/byok-list` — pick a provider from the catalog and store its key on THIS
3346
+ // machine, the same route `/byok-key` takes once a provider is named. The
3347
+ // picker is the point: the provider id was the one thing this flow asked
3348
+ // the user to recall and retype, and a retyped or alias-matched id either
3349
+ // matched nothing or matched another vendor. Arrow or Tab moves the
3350
+ // highlight, Enter picks, and the id dispatched is the catalog's own — so
3351
+ // the key lands under the id the relay will be asked for, and that
3352
+ // provider's models then show up in `/model`.
3353
+ name: 'byok-list', aliases: ['byok-pick'], hint: '', category: 'auth',
3354
+ desc: 'Pick a provider to set a key for, then its models appear in /model',
3355
+ handler: async (c) => {
3356
+ const providers = await byokCatalog(c.client);
3357
+ if (!providers || !providers.length) {
3358
+ c.push({
3359
+ role: 'error',
3360
+ text: 'Could not read the provider catalog (offline, or no AEGIS key) — /byok lists what is known.',
3361
+ });
3362
+ return true;
3363
+ }
3364
+ if (typeof c.openOverlay !== 'function') {
3365
+ // No interactive host: fall back to the printable list rather than a
3366
+ // picker nothing can draw.
3367
+ c.push({ role: 'note', text: '/byok-key <provider> — /byok lists the providers.' });
3368
+ return true;
3369
+ }
3370
+ const cur = (providers.find((p) => p.configured) || {}).id || null;
3371
+ const sel = Math.max(0, providers.findIndex((p) => p.configured));
3372
+ c.openOverlay({
3373
+ type: 'provider',
3374
+ command: 'byok-key',
3375
+ items: providers,
3376
+ sel,
3377
+ current: cur,
3378
+ hint: '↑↓ or tab move · enter picks · the key is stored on this machine',
3379
+ });
3380
+ return true;
3381
+ },
3382
+ },
3383
+ {
3384
+ name: 'byok-key', args: ['provider'], hint: '<provider> [key]', category: 'auth',
3385
+ desc: 'Save YOUR provider key on THIS MACHINE — the key the byok class sends',
3386
+ handler: async (c, a) => {
3387
+ const args = a || {};
3388
+ const typed = String(args.provider || '').trim().toLowerCase();
3389
+ if (!typed) {
3390
+ // No provider typed: open the picker instead of printing a usage line.
3391
+ // The id was the one thing this flow asked the user to RECALL, and a
3392
+ // mistyped or alias-matched id either matched nothing or — worse —
3393
+ // matched another vendor's row. Arrow or Tab moves, Enter picks, and
3394
+ // the id Enter dispatches is the catalog's own, so the key lands under
3395
+ // the id the relay will actually be asked for.
3396
+ const providers = await byokCatalog(c.client);
3397
+ if (!providers || !providers.length) {
3398
+ c.push({ role: 'error', text: 'Usage: /byok-key <provider> — /byok lists the providers.' });
3399
+ return true;
3400
+ }
3401
+ if (typeof c.openOverlay !== 'function') {
3402
+ // No interactive host (a piped run): the old usage line, which at
3403
+ // least names the command that lists the ids.
3404
+ c.push({ role: 'error', text: 'Usage: /byok-key <provider> — /byok lists the providers.' });
3405
+ return true;
3406
+ }
3407
+ const cur = (providers.find((p) => p.configured) || {}).id || null;
3408
+ const sel = Math.max(0, providers.findIndex((p) => p.configured));
3409
+ c.openOverlay({
3410
+ type: 'provider',
3411
+ command: 'byok-key',
3412
+ items: providers,
3413
+ sel,
3414
+ current: cur,
3415
+ hint: '↑↓ or tab move · enter picks · the key is stored on this machine',
3416
+ });
3417
+ return true;
3418
+ }
3419
+ const store = c.settings && c.settings();
3420
+ if (!store || typeof store.set !== 'function') {
3421
+ c.push({ role: 'error', text: 'this client has no provider-key store.' });
3422
+ return true;
3423
+ }
3424
+ // Resolve the alias against the server's catalog so the row is written
3425
+ // under the id the relay will actually be asked for (`/byok-key OpenAI`
3426
+ // and `/byok-key openai` must be one key, not two).
3427
+ const providers = await byokCatalog(c.client);
3428
+ const match = providers ? findByokProvider(providers, typed) : null;
3429
+ if (match && match.ambiguous) {
3430
+ c.push({ role: 'error', text: `"${typed}" matches ${match.ambiguous.join(', ')} — retype the exact id.` });
3431
+ return true;
3432
+ }
3433
+ // A key written under a provider the relay does not serve is unusable and
3434
+ // invisible: the catalog never lists the row it created, so the user sees
3435
+ // "saved" and then no models, with nothing naming the typo. `byok-set`
3436
+ // already refuses this; the command it redirects users TO must refuse it
3437
+ // too, or the redirect trades one silent failure for another.
3438
+ //
3439
+ // Only refused when the catalog actually answered. `byokCatalog` returns
3440
+ // null on an unreachable server, and refusing on null would turn a
3441
+ // network blip into "unknown provider" — a wrong reason for a right-looking
3442
+ // stop. With no catalog the typed id is trusted, as before.
3443
+ if (providers && !match?.provider) {
3444
+ const ids = providers.map((x) => x.id).join(', ');
3445
+ c.push({
3446
+ role: 'error',
3447
+ text: `unknown provider "${typed}". Known ids: ${ids} — nothing was saved.`,
3448
+ });
3449
+ return true;
3450
+ }
3451
+ const p = match && match.provider;
3452
+ const id = (p && p.id) || typed;
3453
+ // A second token is the scriptable path (`/byok-key openai sk-…`); with
3454
+ // none we prompt — readSecret never echoes and never enters history.
3455
+ const rest = String(args._rest || '').trim();
3456
+ const sp = rest.indexOf(' ');
3457
+ let key = sp === -1 ? '' : rest.slice(sp + 1).trim();
3458
+ if (!key) {
3459
+ if (p && p.key_url) c.push({ role: 'note', text: `create a ${p.label || id} key at ${p.key_url}` });
3460
+ key = String((await c.readSecret(`${id} key: `)) || '').trim();
3461
+ }
3462
+ if (!key) {
3463
+ c.push({ role: 'note', text: 'nothing saved.' });
3464
+ return true;
3465
+ }
3466
+ if (p && p.key_prefix && !key.startsWith(p.key_prefix)) {
3467
+ c.push({ role: 'note', text: `heads up: ${id} keys normally start with "${p.key_prefix}" — saved anyway.` });
3468
+ }
3469
+ // Saving a KEY with no ADDRESS is the one way to build a `custom` row that
3470
+ // looks configured and cannot be spent: the catalog descriptor pins no
3471
+ // base URL for that id, so nothing can be guessed, and the turn is
3472
+ // refused later with a 400 that never mentions what is missing. Refuse it
3473
+ // here instead — where the user is typing, and where the fix can be named.
3474
+ // If an endpoint is already saved, a re-key is legitimate and proceeds.
3475
+ if (id === 'custom' && !savedByokBaseURL(c, id)) {
3476
+ c.push({
3477
+ role: 'error',
3478
+ text:
3479
+ `the "custom" provider needs an endpoint as well as a key — a key alone dials nothing. ` +
3480
+ `Use: /model-add custom <https-base-url> ${key} <model-id> (saves endpoint, key and ` +
3481
+ `model together) — nothing was saved.`,
3482
+ });
3483
+ return true;
3484
+ }
3485
+ store.set(c.byokNamespace(id), { key });
3486
+
3487
+ // MIRROR IT INTO ~/.aegiscode/.env — the file every host (this CLI, the
3488
+ // desktop, the MCP plugin) loads at start-up, and the one the shared
3489
+ // engine's `providerKeyFromEnv` reads. The settings store alone made the
3490
+ // key a private fact of this process's data dir: the next launch of the
3491
+ // SAME host found it, but nothing else did, and the byok model list is
3492
+ // built from a key the engine resolves through both. `/model-add` writes
3493
+ // both stores for this exact reason (see its `setEnvValue` call), and a
3494
+ // key entered here must not be the one row that behaves differently.
3495
+ // Best-effort: the store row above is the row of record, so a failure to
3496
+ // write the file is reported and never undoes the save.
3497
+ let envWritten = '';
3498
+ try {
3499
+ const { envVarFor, setEnvValue } = require(resolveShared(path.join('client', 'env-file.js')));
3500
+ const name = envVarFor(id);
3501
+ if (name) {
3502
+ const res = setEnvValue(name, key);
3503
+ if (res.ok) envWritten = name;
3504
+ else c.push({ role: 'note', text: `heads up: could not write ${name} to ~/.aegiscode/.env (${res.error}).` });
3505
+ }
3506
+ } catch {
3507
+ /* the settings-store save is the row of record; this mirror is best-effort */
3508
+ }
3509
+
3510
+ // Then make the models it unlocks VISIBLE where the user asked for them:
3511
+ // the byok model list is cached for five minutes (app.js MODEL_CACHE_MS),
3512
+ // so without this the key is saved and `/model` keeps offering the list
3513
+ // computed before it existed — the "I set a key and nothing new appeared"
3514
+ // report. The refresh is forced, and its rows are what get pinned below.
3515
+ let rows = [];
3516
+ if (typeof c.refreshByokModels === 'function') {
3517
+ try { rows = (await c.refreshByokModels()) || []; } catch { rows = []; }
3518
+ }
3519
+ if (!rows.length && typeof c.listModelsFor === 'function') {
3520
+ // Hosts that expose the class surface but not the cache invalidation
3521
+ // (an embedding) still get an answer: ask for the byok class directly.
3522
+ try {
3523
+ rows = ((await c.listModelsFor('byok')) || []).filter((m) => !m.cls || m.cls === 'byok');
3524
+ } catch { rows = []; }
3525
+ }
3526
+ const mine = rows.filter((m) => m && (m.provider === id || String(m.id || '').startsWith(`${id}:`)));
3527
+
3528
+ // Move onto the byok class — the key just saved can only be spent there,
3529
+ // and a session sitting on `aegis` would show these rows in /model and
3530
+ // then send the pinned `provider:model` id to the pool. Before the pin,
3531
+ // so switchClass's own pin rules run on the id we are about to store.
3532
+ let onByok = ((c.ctx && c.ctx.modelClass) || '') === 'byok';
3533
+ if (!onByok && typeof c.switchClass === 'function') {
3534
+ const sw = c.switchClass('byok');
3535
+ if (sw && sw.ok) {
3536
+ onByok = true;
3537
+ c.push({ role: 'note', text: `class: byok — ${c.classLabel ? c.classLabel('byok') : 'your own key'}` });
3538
+ }
3539
+ }
3540
+
3541
+ // Pin it and PERSIST it, which is what makes the pick survive a restart:
3542
+ // app.js's restorePrefs() reads config.model/modelClass back. Only on
3543
+ // success — this whole block is the success path, after the key landed.
3544
+ const pickId = mine.length ? String(mine[0].id) : '';
3545
+ if (pickId && c.ctx) {
3546
+ c.ctx.model = pickId;
3547
+ c.saveConfig({ model: pickId, currentModelId: pickId, ...(onByok ? { modelClass: 'byok' } : {}) });
3548
+ }
3549
+
3550
+ c.push({
3551
+ role: 'done',
3552
+ text: pickId
3553
+ ? `saved a ${id} key on this machine${envWritten ? ` (${envWritten} in ~/.aegiscode/.env, so it is there next time)` : ''} — model ${pickId} pinned, /model lists the rest.`
3554
+ : `saved a ${id} key on this machine${envWritten ? ` (${envWritten} in ~/.aegiscode/.env, so it is there next time)` : ''} — /models lists its models, /class byok runs on it.`,
3555
+ });
3556
+ return true;
3557
+ },
3558
+ },
3559
+ {
3560
+ name: 'byok-rm-key', args: ['provider'], hint: '<provider>', category: 'auth',
3561
+ desc: 'Forget the provider key saved on this machine',
3562
+ handler: async (c, a) => {
3563
+ const args = a || {};
3564
+ const id = String(args.provider || '').trim().toLowerCase();
3565
+ if (!id) {
3566
+ c.push({ role: 'error', text: 'Usage: /byok-rm-key <provider> — /byok lists the providers.' });
3567
+ return true;
3568
+ }
3569
+ const store = c.settings && c.settings();
3570
+ if (!store || typeof store.remove !== 'function') {
3571
+ c.push({ role: 'error', text: 'this client has no provider-key store.' });
3572
+ return true;
3573
+ }
3574
+ const row = c.byokNamespace(id);
3575
+ const had = typeof store.rawKey === 'function' ? store.rawKey(row) : null;
3576
+ store.remove(row);
3577
+ c.push({
3578
+ role: had ? 'done' : 'note',
3579
+ text: had ? `removed the ${id} key from this machine.` : `no ${id} key was saved on this machine.`,
3580
+ });
3581
+ return true;
3582
+ },
3583
+ },
3584
+ {
3585
+ // ── the user's own model declarations ──────────────────────────────────
3586
+ //
3587
+ // The ONE thing this repo could not do before: a provider ships a model on
3588
+ // Tuesday and the user can call it from a BYOK key that same day. The BYOK
3589
+ // relay is a stateless pass-through — the caller's own vendor key
3590
+ // authenticates upstream and AEGIS forwards whatever model string it was
3591
+ // given — so any id the vendor serves is callable the moment this machine
3592
+ // offers it as a row, and this command is how it becomes one without a
3593
+ // release.
3594
+ //
3595
+ // Written through `client/user-models.js`, which is also what the desktop's
3596
+ // Settings row writes and what the shared engine applies to
3597
+ // `listModels('byok')`, so `/models` and the alt+p picker show the row on
3598
+ // the next refresh and the window shows it on ITS next refresh. The file is
3599
+ // printed on success, because a hand-edit is the bulk path and a store the
3600
+ // user cannot find is a store they will not use.
3601
+ name: 'model-add', aliases: ['add-model'], args: ['provider'],
3602
+ hint: '<provider> [api-key] [model-id|*] (custom: <base-url> <api-key> [model-id|*])',
3603
+ category: 'model',
3604
+ desc: 'Save a provider key and offer a model id in one step (asks the vendor when it can)',
3605
+ handler: async (c, a) => {
3606
+ const args = a || {};
3607
+ const typed = String(args.provider || '').trim();
3608
+ if (!typed) {
3609
+ c.push({
3610
+ role: 'error',
3611
+ text: 'Usage: /model-add <provider> [api-key] <model-id> — /byok lists the providers. '
3612
+ + 'A vendor this catalog does not name yet: /model-add custom <https-base-url> <api-key> <model-id>. '
3613
+ + 'Example: /model-add deepseek sk-xxxxxxxx deepseek-v4.3-preview',
3614
+ });
3615
+ return true;
3616
+ }
3617
+ const rest = String(args._rest || '').trim();
3618
+ // Quote-aware, because the one word on this line that MAY need quoting is
3619
+ // the base URL — see splitCommandWords.
3620
+ const words = splitCommandWords(rest);
3621
+ // `words[0]` is the provider token itself, echoed into `_rest` the same
3622
+ // way `/byok-key` reads it — everything after it is ours to read. A
3623
+ // `_rest` without it (a caller that passes only the trailing words) is
3624
+ // tolerated rather than misread as the provider being the model id.
3625
+ let extra = words.length && words[0].toLowerCase() === typed.toLowerCase()
3626
+ ? words.slice(1)
3627
+ : words;
3628
+ // Resolve the provider against the relay's catalog first. A slug the
3629
+ // server does not list can never be attached to a key, so storing it
3630
+ // would produce a declaration that is invisible in every picker — the
3631
+ // silent no-op this whole path is meant to avoid. When the catalog is
3632
+ // unreachable the declaration is kept and SAID to be unverified, because
3633
+ // refusing to work offline is worse than a row that appears later.
3634
+ const providers = await byokCatalog(c.client);
3635
+ const match = providers ? findByokProvider(providers, typed) : null;
3636
+ if (match && match.ambiguous) {
3637
+ c.push({ role: 'error', text: `"${typed}" matches ${match.ambiguous.join(', ')} — retype the exact id.` });
3638
+ return true;
3639
+ }
3640
+ if (providers && !(match && match.provider)) {
3641
+ c.push({
3642
+ role: 'error',
3643
+ text: `no provider "${typed}" in the relay's catalog — /byok lists the ones it takes a key for.`,
3644
+ });
3645
+ return true;
3646
+ }
3647
+ const id = (match && match.provider && match.provider.id) || typed.toLowerCase();
3648
+ // ── fold the key-save step in, so one command does both ──────────────
3649
+ //
3650
+ // Before this, a never-configured provider needed /byok-key THEN
3651
+ // /model-add — two commands for one outcome the user has in mind as
3652
+ // one. Two extra words can only mean key-then-model (the one-word shape
3653
+ // just below is already the model-id-alone case this command always
3654
+ // had, and guessing "key or model id" from a single token is the
3655
+ // ambiguity this rule avoids rather than resolves): `/model-add
3656
+ // deepseek sk-… deepseek-v4.3-preview` saves the key and declares the
3657
+ // model in the same breath, and shows up in the picker right after —
3658
+ // no separate /byok-key round trip.
3659
+ //
3660
+ // "custom" (a vendor this catalog does not name, or a self-hosted
3661
+ // OpenAI-compatible endpoint) reads one word EARLIER than every other
3662
+ // provider: the base URL aegis1 has no constant for and must be told
3663
+ // per call (`_byok_custom_base_url` there validates it — https, no
3664
+ // loopback/private/link-local target). It gets its own branch rather
3665
+ // than folding into the generic rule below, because with the base URL
3666
+ // in play a lone leftover word is still ambiguous between "no model"
3667
+ // and "no key" in a way the generic one-word-is-the-model-id rule
3668
+ // cannot resolve.
3669
+ let typedBaseURL = '';
3670
+ let typedKey = '';
3671
+ if (id === 'custom') {
3672
+ // ONE leftover word for `custom` is genuinely ambiguous, so it is
3673
+ // refused rather than guessed: with no endpoint on this machine the
3674
+ // word could be the base URL (key and model still to come) or a model
3675
+ // id for an endpoint nobody has named — and the guess that writes a
3676
+ // model row against no endpoint is a row that cannot be called. Once an
3677
+ // endpoint IS saved the ambiguity is gone, because a second endpoint
3678
+ // needs its key with it (the two-word branch below), so a lone word can
3679
+ // only be a model id. Named, not silently dropped.
3680
+ if (extra.length === 1 && !savedByokBaseURL(c, id)) {
3681
+ c.push({
3682
+ role: 'error',
3683
+ text: 'one word cannot say whether it is the URL or the model id — nothing was saved. '
3684
+ + 'Type the endpoint first: /model-add custom <https-base-url> <api-key> [model-id]',
3685
+ });
3686
+ return true;
3687
+ }
3688
+ if (extra.length >= 2) {
3689
+ typedBaseURL = extra.shift();
3690
+ typedKey = extra.shift();
3691
+ }
3692
+ } else if (extra.length >= 2) {
3693
+ typedKey = extra.shift();
3694
+ }
3695
+ let model = extra.join(' ').trim();
3696
+ if (typedKey) {
3697
+ const keyStore = c.settings && c.settings();
3698
+ if (!keyStore || typeof keyStore.set !== 'function') {
3699
+ c.push({ role: 'error', text: 'this client has no provider-key store.' });
3700
+ return true;
3701
+ }
3702
+ const p = match && match.provider;
3703
+ if (p && p.key_prefix && !typedKey.startsWith(p.key_prefix)) {
3704
+ c.push({ role: 'note', text: `heads up: ${id} keys normally start with "${p.key_prefix}" — saved anyway.` });
3705
+ }
3706
+ if (typedBaseURL && !/^https:\/\//i.test(typedBaseURL)) {
3707
+ c.push({ role: 'note', text: `heads up: aegis1 only dials an https:// base_url — saved anyway, but calls on it will be refused.` });
3708
+ }
3709
+ keyStore.set(c.byokNamespace(id), { key: typedKey, ...(typedBaseURL ? { baseURL: typedBaseURL } : {}) });
3710
+ // Mirror it into ~/.aegiscode/.env too — the same file the model picker
3711
+ // writes (models.js storeModelKey) and byokKeyForProvider() already
3712
+ // falls back to reading. Without this a key saved here was invisible to
3713
+ // anything that only reads process.env/.env (a shell, the other host
3714
+ // before its settings store syncs), even though the two files name the
3715
+ // same provider through the identical envVarFor() mapping. Best-effort:
3716
+ // the settings-store save above is the row of record, so a failure here
3717
+ // (e.g. an unwritable .env) is reported but never undoes it.
3718
+ try {
3719
+ const { envVarFor, setEnvValue } = require(resolveShared(path.join('client', 'env-file.js')));
3720
+ const envName = envVarFor(id);
3721
+ if (envName) {
3722
+ const res = setEnvValue(envName, typedKey);
3723
+ if (!res.ok) {
3724
+ c.push({ role: 'note', text: `heads up: could not mirror the key into ~/.aegiscode/.env (${res.error}).` });
3725
+ }
3726
+ }
3727
+ } catch {
3728
+ /* the settings-store save is the row of record; this mirror is best-effort */
3729
+ }
3730
+ c.push({
3731
+ role: 'done',
3732
+ text: typedBaseURL
3733
+ ? `saved a ${id} key and base URL (${typedBaseURL}) on this machine.`
3734
+ : `saved a ${id} key on this machine.`,
3735
+ });
3736
+ }
3737
+ // ── what the vendor says, before we ask the user to remember it ──────
3738
+ //
3739
+ // The whole cost of this feature used to be "know the vendor's model id",
3740
+ // which is the release-lag problem handed to the user instead of solved.
3741
+ // When this machine holds a key for the provider, its own list endpoint
3742
+ // answers that in one request. Best-effort by construction: no key, no
3743
+ // endpoint, no network or an unparseable reply all fall through to the
3744
+ // free-form prompt below, which is the path that already worked offline.
3745
+ const key = byokKeyForProvider(c, id);
3746
+ const offered = await offeredModelIds(c, id, key);
3747
+
3748
+ // `*` is the bulk path: declare everything the vendor currently serves.
3749
+ // Only the CHAT rows are declared (an embeddings or TTS id in a model
3750
+ // picker is a row nobody can run), and only after the vendor answered —
3751
+ // with no list there is nothing to take all of, and saying so is the
3752
+ // honest outcome rather than an empty success.
3753
+ if (model === '*') {
3754
+ if (!offered) {
3755
+ const why = await discoverProviderModels(c, id, key);
3756
+ c.push({
3757
+ role: 'error',
3758
+ text: `cannot list ${id}: ${(why && why.error) || 'no list available'} — type the ids instead: /model-add ${id} <model-id>`,
3759
+ });
3760
+ return true;
3761
+ }
3762
+ const bulk = addManyUserModels(id, offered);
3763
+ if (typeof c.refreshByokModels === 'function') {
3764
+ try { await c.refreshByokModels(); } catch { /* the next refresh reads the file anyway */ }
3765
+ }
3766
+ c.push({
3767
+ role: 'done',
3768
+ text: `added ${bulk.added} of the ${offered.length} model ids ${id} serves${bulk.already.length ? ` (${bulk.already.length} were already declared)` : ''}.`,
3769
+ });
3770
+ if (bulk.capped) {
3771
+ // The store's per-provider ceiling, named as a ceiling. A vendor list
3772
+ // is a hundred rows; this is one deliberate limit, not sixty broken
3773
+ // ids, and the two must not read the same in the transcript.
3774
+ c.push({
3775
+ role: 'note',
3776
+ text: `stopped at the store's per-provider cap (32) — ${bulk.capped} more id(s) were left out; /model-add ${id} <model-id> stores a specific one, /model-rm frees a slot.`,
3777
+ });
3778
+ }
3779
+ if (bulk.failed.length) {
3780
+ c.push({ role: 'note', text: `${bulk.failed.length} id(s) were refused: ${bulk.failed.map((f) => f.id).join(', ')}` });
3781
+ }
3782
+ c.push({ role: 'note', text: `stored in ${userModelsPath()} — the desktop reads the same file. /model-discover ${id} lists what the vendor serves.` });
3783
+ return true;
3784
+ }
3785
+
3786
+ if (!model) {
3787
+ // Plain inline input, NOT readSecret: a model id is not a secret, and
3788
+ // hiding it would make a typo unreviewable before it is stored.
3789
+ if (offered) {
3790
+ c.push({ role: 'note', text: `${id} serves ${offered.length} model ids — ${offered.slice(0, 12).join(', ')}${offered.length > 12 ? ', …' : ''}` });
3791
+ }
3792
+ const typedId = String((await c.askInput(
3793
+ offered
3794
+ ? `model id for ${id} (1-${offered.length}, or type one): `
3795
+ : `model id for ${id}: `
3796
+ )) || '').trim();
3797
+ // A bare number picks the row it is listed under. Only an in-range
3798
+ // integer is read that way, so an id that happens to start with a digit
3799
+ // is still stored verbatim unless it is exactly a listed position.
3800
+ // `offered` is undefined whenever the vendor could not be asked (no
3801
+ // key, no endpoint, no network) — reading `.length` off it here threw a
3802
+ // TypeError out of the handler, which reads to the user as the command
3803
+ // crashing rather than as the id being stored, so the position rule is
3804
+ // applied only when there is a list to be a position IN.
3805
+ const n = offered && /^\d+$/.test(typedId) ? Number(typedId) : 0;
3806
+ model = offered && n >= 1 && n <= offered.length ? offered[n - 1] : typedId;
3807
+ }
3808
+ if (!model) {
3809
+ c.push({ role: 'note', text: 'nothing saved.' });
3810
+ return true;
3811
+ }
3812
+ let res;
3813
+ try {
3814
+ res = addUserModel(id, model);
3815
+ } catch (err) {
3816
+ c.push({ role: 'error', text: (err && err.message) || String(err) });
3817
+ return true;
3818
+ }
3819
+ // The picker's cache (app.js `byokCache`, 5 minutes) is older than the
3820
+ // file the instant it is written, so refresh it here: a user who adds a
3821
+ // model and types `/models` must see it, not "already listed" five
3822
+ // minutes later.
3823
+ if (typeof c.refreshByokModels === 'function') {
3824
+ try {
3825
+ await c.refreshByokModels();
3826
+ } catch {
3827
+ /* the next refresh reads the file anyway */
3828
+ }
3829
+ }
3830
+ const rows = (typeof c.listModelsFor === 'function' ? (await c.listModelsFor('byok')) : []) || [];
3831
+ const row = rows.find((m) => m && m.id === `${id}:${model}`);
3832
+ c.push({
3833
+ role: res.added ? 'done' : 'note',
3834
+ text: res.added
3835
+ ? `added ${id}:${model} — offered on this machine now, in the CLI and the desktop.`
3836
+ : `${id}:${model} was already declared.`,
3837
+ });
3838
+ if (!providers) {
3839
+ c.push({
3840
+ role: 'note',
3841
+ text: `the relay's catalog could not be read, so "${id}" is unverified — if it does not appear in /models, /byok lists the provider ids it takes.`,
3842
+ });
3843
+ }
3844
+ if (res.added && !row) {
3845
+ c.push({
3846
+ role: 'note',
3847
+ text: `saved, but no row will be offered for "${id}" yet — the relay lists no provider of that id (or that provider lists no models).`,
3848
+ });
3849
+ }
3850
+ if (res.added && offered) {
3851
+ // The vendor was asked and it lists more than the one id just stored.
3852
+ // Naming the size of that list is the difference between "the picker has
3853
+ // four models" and "this vendor ships forty and you have one of them".
3854
+ c.push({
3855
+ role: 'note',
3856
+ text: `${id} currently serves ${offered.length} model ids — /model-discover ${id} lists them, /model-add ${id} '*' takes them all.`,
3857
+ });
3858
+ }
3859
+ c.push({ role: 'note', text: `stored in ${res.file} — the desktop reads the same file.` });
3860
+ return true;
3861
+ },
3862
+ },
3863
+ {
3864
+ // ── what the vendor serves, right now ─────────────────────────────────
3865
+ //
3866
+ // `/model-add` answers "store THIS id"; this answers "which ids are there",
3867
+ // which is the question a user actually has when a vendor ships something
3868
+ // on a Tuesday. It reads the same key `client/env-file.js` and the provider
3869
+ // CRUD share (saved row first, `~/.aegiscode/.env` second) and hits the
3870
+ // vendor's own list endpoint, so the answer cannot be stale by
3871
+ // construction — that is the whole point of asking instead of shipping
3872
+ // another hand-copied list.
3873
+ //
3874
+ // Offline, keyless and shape-changed are all REPORTED, never thrown: this
3875
+ // command sits beside a manual path that works, so its worst case has to be
3876
+ // a sentence, not a stack trace.
3877
+ name: 'model-discover', aliases: ['discover-models', 'vendor-models'], args: ['provider'], hint: '<provider>',
3878
+ category: 'model',
3879
+ desc: "List the model ids your provider's own API serves",
3880
+ handler: async (c, a) => {
3881
+ const args = a || {};
3882
+ const typed = String(args.provider || '').trim();
3883
+ if (!typed) {
3884
+ c.push({
3885
+ role: 'error',
3886
+ text: `Usage: /model-discover <provider> — this client can ask: ${discoverableProviders().join(', ')}`,
3887
+ });
3888
+ return true;
3889
+ }
3890
+ // Resolve the alias against the relay's catalog when it is reachable, so
3891
+ // `/model-discover xai` and `/model-discover grok` are one request.
3892
+ const providers = await byokCatalog(c.client);
3893
+ const match = providers ? findByokProvider(providers, typed) : null;
3894
+ const id = ((match && match.provider && match.provider.id) || typed).toLowerCase();
3895
+ const entry = vendorEndpointFor(id);
3896
+ if (!entry) {
3897
+ c.push({
3898
+ role: 'error',
3899
+ text: `no list endpoint for "${id}" in this client — /model-add ${id} <model-id> stores an id you already know. Providers it can ask: ${discoverableProviders().join(', ')}`,
3900
+ });
3901
+ return true;
3902
+ }
3903
+ const key = byokKeyForProvider(c, id);
3904
+ if (!key) {
3905
+ c.push({
3906
+ role: 'error',
3907
+ text: `no ${id} key on this machine — /byok-key ${id} saves one (or put it in ~/.aegiscode/.env), then this lists what the key reaches.`,
3908
+ });
3909
+ return true;
3910
+ }
3911
+ const res = await discoverProviderModels(c, id, key);
3912
+ if (!res || !res.ok) {
3913
+ c.push({ role: 'error', text: `could not list ${id}: ${(res && res.error) || 'no answer'}` });
3914
+ return true;
3915
+ }
3916
+ // Where the user stands: which of these are already offered here.
3917
+ const declared = new Set(userModelIdsFor(id));
3918
+ const known = new Set(
3919
+ ((match && match.provider && match.provider.models) || []).map((m) => String(m))
3920
+ );
3921
+ c.push({ role: 'note', text: `${id} at ${entry.url}${entry.note ? ` (${entry.note})` : ''}` });
3922
+ c.push({
3923
+ role: 'note',
3924
+ text: `${res.count} chat model id(s) the vendor serves — mark: [seen] the relay already lists it, [your] you declared it, [new] this machine does not offer it yet.`,
3925
+ });
3926
+ const lines = res.ids.map((m, i) => {
3927
+ const mark = declared.has(m) ? '[your]' : known.has(m) ? '[seen]' : '[new]';
3928
+ return `${String(i + 1).padStart(3)}. ${mark} ${m}`;
3929
+ });
3930
+ if (lines.length) c.push({ role: 'panel', lines });
3931
+ if (!lines.length) {
3932
+ c.push({ role: 'note', text: `the vendor answered with no chat models — /model-add ${id} <model-id> stores one by hand.` });
3933
+ }
3934
+ if (res.others.length) {
3935
+ // Named, not hidden. "the vendor lists 60 and you were shown 12" is a
3936
+ // fact the user is owed; a silent filter is how a picker looks empty
3937
+ // for a reason nobody can see.
3938
+ c.push({
3939
+ role: 'note',
3940
+ text: `${res.others.length} id(s) are not chat models (embeddings, audio, moderation or an unsupported method) and are left out: ${res.others.slice(0, 8).join(', ')}${res.others.length > 8 ? ', …' : ''}`,
3941
+ });
3942
+ }
3943
+ const fresh = res.ids.filter((m) => !declared.has(m) && !known.has(m));
3944
+ if (fresh.length) {
3945
+ c.push({
3946
+ role: 'note',
3947
+ text: `${fresh.length} of them are not offered on this machine yet — /model-add ${id} '<model-id>' stores one, /model-add ${id} '*' stores every chat model the vendor serves.`,
3948
+ });
3949
+ }
3950
+ return true;
3951
+ },
3952
+ },
3953
+ {
3954
+ name: 'model-rm', aliases: ['rm-model'], args: ['provider'], hint: '<provider> <model-id>',
3955
+ category: 'model',
3956
+ desc: 'Forget a model id you added with /model-add',
3957
+ handler: async (c, a) => {
3958
+ const args = a || {};
3959
+ const typed = String(args.provider || '').trim();
3960
+ const rest = String(args._rest || '').trim();
3961
+ const sp = rest.indexOf(' ');
3962
+ const model = sp === -1 ? '' : rest.slice(sp + 1).trim();
3963
+ if (!typed || !model) {
3964
+ c.push({ role: 'error', text: 'Usage: /model-rm <provider> <model-id> — /model-add lists what you added.' });
3965
+ return true;
3966
+ }
3967
+ let res;
3968
+ try {
3969
+ res = removeUserModel(typed, model);
3970
+ } catch (err) {
3971
+ c.push({ role: 'error', text: (err && err.message) || String(err) });
3972
+ return true;
3973
+ }
3974
+ if (typeof c.refreshByokModels === 'function') {
3975
+ try {
3976
+ await c.refreshByokModels();
3977
+ } catch {
3978
+ /* the next refresh reads the file anyway */
3979
+ }
3980
+ }
3981
+ c.push({
3982
+ role: res.removed ? 'done' : 'note',
3983
+ text: res.removed
3984
+ ? `removed ${res.provider}:${res.model} — the picker stops offering it on the next refresh.`
3985
+ : `${res.provider}:${res.model} was not declared on this machine.`,
3986
+ });
3987
+ return true;
3988
+ },
3989
+ },
3990
+ {
3991
+ name: 'tool', args: ['name', 'json'], hint: '<name> [json]', category: 'aegis',
3992
+ desc: 'Call any registry tool directly (escape hatch for new tools)',
3993
+ generic: true,
3994
+ build: (arg) => {
3995
+ const s = String(arg || '');
3996
+ const sp = s.indexOf(' ');
3997
+ const name = (sp === -1 ? s : s.slice(0, sp)).trim();
3998
+ const rest = sp === -1 ? '' : s.slice(sp + 1).trim();
3999
+ let args = {};
4000
+ if (rest) {
4001
+ try {
4002
+ args = JSON.parse(rest);
4003
+ } catch (err) {
4004
+ throw new Error(`/tool: arguments must be JSON — ${err.message}`);
4005
+ }
4006
+ }
4007
+ return { tool: name, args };
4008
+ },
4009
+ },
4010
+ {
4011
+ name: 'aegis-import', aliases: ['import'], hint: '[--confirm]', category: 'aegis',
4012
+ desc: 'Import memory from other AI tools on this machine (dry run unless --confirm)',
4013
+ tool: 'aegis_memory_import',
4014
+ build: (arg) => ({ confirm: /--confirm\b/.test(String(arg || '')) }),
4015
+ },
4016
+ ];
4017
+
4018
+ // ── Index + the one invariant a table like this must hold ─────────────────────
4019
+ // A name or alias registered twice would silently shadow the earlier entry, so
4020
+ // the collision is a module-load error rather than a runtime surprise.
4021
+
4022
+ const BY_NAME = new Map();
4023
+ for (const c of COMMANDS) {
4024
+ for (const n of [c.name, ...(c.aliases || [])]) {
4025
+ if (BY_NAME.has(n)) {
4026
+ throw new Error(`aegiscode: command name or alias /${n} is registered twice`);
4027
+ }
4028
+ BY_NAME.set(n, c);
4029
+ }
4030
+ }
4031
+
4032
+ /** Every builtin entry, in palette order, with its category label attached. */
4033
+ function allCommands() {
4034
+ return COMMANDS.map((entry) => ({ ...entry, categoryLabel: categoryLabel(entry.category) }));
4035
+ }
4036
+
4037
+ /** Commands shown in the palette, /help and Tab completion. */
4038
+ function visibleCommands() {
4039
+ return allCommands().filter((c) => !(typeof c.hidden === 'function' ? c.hidden() : c.hidden));
4040
+ }
4041
+
4042
+ /** Find by name or alias, case-insensitive. Returns the entry or null. */
4043
+ function findCommand(name) {
4044
+ return BY_NAME.get(String(name || '').toLowerCase()) || null;
4045
+ }
4046
+
4047
+ /** The canonical name of a command, resolving aliases. */
4048
+ function canonicalName(name) {
4049
+ const e = findCommand(name);
4050
+ return e ? e.name : name;
4051
+ }
4052
+
4053
+ /**
4054
+ * Classify one input line.
4055
+ * @returns {{kind:'empty'}
4056
+ * |{kind:'command',command:object,arg:string}
4057
+ * |{kind:'unavailable',command:object,arg:string}
4058
+ * |{kind:'unknown',name:string,text:string}
4059
+ * |{kind:'prompt',text:string}}
4060
+ */
4061
+ function parseLine(line) {
4062
+ const raw = String(line == null ? '' : line);
4063
+ const trimmed = raw.trim();
4064
+ if (!trimmed) return { kind: 'empty' };
4065
+ if (trimmed[0] !== '/') return { kind: 'prompt', text: trimmed };
4066
+ const sp = trimmed.indexOf(' ');
4067
+ const name = (sp === -1 ? trimmed.slice(1) : trimmed.slice(1, sp)).trim();
4068
+ const arg = sp === -1 ? '' : trimmed.slice(sp + 1).trim();
4069
+ const command = findCommand(name);
4070
+ if (!command) return { kind: 'unknown', name, text: trimmed };
4071
+ if (command.unavailable) return { kind: 'unavailable', command, arg };
4072
+ return { kind: 'command', command, arg };
4073
+ }
4074
+
4075
+ /** Commands that map to a registry tool, for the coverage test. */
4076
+ function toolBackedCommands() {
4077
+ return COMMANDS.filter((c) => c.tool);
4078
+ }
4079
+
4080
+ module.exports = {
4081
+ CATEGORIES,
4082
+ categoryLabel,
4083
+ EFFORT_LEVELS,
4084
+ COMMANDS,
4085
+ allCommands,
4086
+ visibleCommands,
4087
+ findCommand,
4088
+ canonicalName,
4089
+ parseLine,
4090
+ toolBackedCommands,
4091
+ };