aegiscode 7.0.25 → 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
@@ -1,3 +1,1275 @@
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"),path=require("node:path"),credentials=require("./credentials.js"),platform=require("./platform.js"),ENV_FILE=".env",SECRETS_FILE="secrets.env",FOREIGN_SECRET_PREFIXES=Object.freeze(["STRIPE_"]),FOREIGN_SECRET_NAMES=Object.freeze(["STRIPE_SECRET_KEY","STRIPE_WEBHOOK_SECRET","STRIPE_PRODUCT","STRIPE_PRO_PRICE_ID","STRIPE_S_PRICE_ID","STRIPE_MEMORY_PRICE_ID","PYPI_API_TOKEN","TWINE_PASSWORD","CLAUDE_CODE_OAUTH_TOKEN"]);function isForeignSecret(e){const r=String(null==e?"":e).trim();return!!r&&(!!FOREIGN_SECRET_NAMES.includes(r)||FOREIGN_SECRET_PREFIXES.some((e=>r.startsWith(e))))}const SECRET_FILE_MODE=384,SECRET_DIR_MODE=448,ALIASES=Object.freeze({google:"GEMINI_API_KEY",gemini:"GEMINI_API_KEY","google-ai":"GEMINI_API_KEY",xai:"XAI_API_KEY","x-ai":"XAI_API_KEY",grok:"XAI_API_KEY",huggingface:"HF_TOKEN",together:"TOGETHER_API_KEY","together-ai":"TOGETHER_API_KEY",fireworks:"FIREWORKS_API_KEY","azure-openai":"AZURE_OPENAI_API_KEY","voyage-ai":"VOYAGE_API_KEY"}),ACCOUNT_ENV_VAR="AEGIS_API_KEY";function envFileFor(e){return path.join(e||credentials.aegisHome(),ENV_FILE)}function secretEnvFileFor(e){return path.join(e||credentials.aegisHome(),SECRETS_FILE)}function envVarFor(e){const r=String(e||"").trim().toLowerCase();if(!r)return"";const t=r.startsWith("byok:")?r.slice(5).trim():r;if(!t)return"";if(ALIASES[t])return ALIASES[t];const n=t.toUpperCase().replace(/[^A-Z0-9]+/g,"_").replace(/^_+|_+$/g,"");return n?`${n}_API_KEY`:""}const ENV_TOKENISH=/^[A-Za-z0-9_+/.-]+$/,ENV_WRAP_MIN_VALUE=32;function foldWrappedEnvValue(e,r,t){let n=t;if(n.startsWith('"')||n.startsWith("'"))return{value:n,i:r};for(;r+1<e.length;){const t=e[r+1],o=t.trim();if(!o||o.startsWith("#")||o.includes("="))break;if(!ENV_TOKENISH.test(o))break;if(!/^[ \t]/.test(t)&&(n.length<ENV_WRAP_MIN_VALUE||!ENV_TOKENISH.test(n)))break;n+=o,r+=1}return{value:n,i:r}}function parseEnvText(e){const r={},t=String(null==e?"":e).split(/\r?\n/);for(let e=0;e<t.length;e++){const n=t[e].trim();if(!n||n.startsWith("#"))continue;const o=n.indexOf("=");if(o<=0)continue;let i=n.slice(0,o).trim();if(i.startsWith("export ")&&(i=i.slice(7).trim()),!/^[A-Za-z_][A-Za-z0-9_]*$/.test(i))continue;const s=foldWrappedEnvValue(t,e,n.slice(o+1).trim());let c=s.value;e=s.i;const E=c.startsWith('"')&&c.endsWith('"')&&c.length>=2,a=c.startsWith("'")&&c.endsWith("'")&&c.length>=2;if(E)c=c.slice(1,-1).replace(/\\(["\\])/g,"$1");else if(a)c=c.slice(1,-1);else{const e=c.indexOf(" #");-1!==e&&(c=c.slice(0,e).trim())}r[i]=c}return r}const ENV_SOURCED=new WeakMap;function sourcedFrom(e){let r=ENV_SOURCED.get(e);return r||(r=new Map,ENV_SOURCED.set(e,r)),r}function isFromEnvFile(e,r,t={}){const n=t.env||process.env,o=ENV_SOURCED.get(n);return!(!o||!o.has(e)||void 0!==r&&o.get(e)!==String(r))}function loadEnvFile(e={}){const r=e.env||process.env,t=e.file||envFileFor(e.dir),n=sourcedFrom(r),o={ok:!1,file:t,loaded:[],kept:[],refused:[],reason:"",loose:!1,mode:0};let i;try{i=fs.readFileSync(t,"utf8")}catch(e){return o.reason=e&&"ENOENT"===e.code?"absent":"unreadable",o}try{const e=fs.statSync(t);o.mode=511&e.mode,o.loose=platform.hasPosixModes()&&0!=(63&e.mode)}catch{}const s=parseEnvText(i);for(const[e,t]of Object.entries(s))isForeignSecret(e)?o.refused.push(e):void 0===r[e]||""===r[e]?(r[e]=t,n.set(e,t),o.loaded.push(e)):o.kept.push(e);return o.ok=!0,o}function loadForeignSecrets(e={}){const r=e.env||process.env,t=e.file||secretEnvFileFor(e.dir),n={ok:!1,file:t,loaded:[],reason:"",mode:0,loose:!1},o=Array.isArray(e.only)&&e.only.length?e.only.filter(isForeignSecret):null;let i;try{i=fs.readFileSync(t,"utf8")}catch(e){return n.reason=e&&"ENOENT"===e.code?"absent":"unreadable",n}try{const e=fs.statSync(t);n.mode=511&e.mode,n.loose=platform.hasPosixModes()&&0!=(63&e.mode)}catch{}const s=parseEnvText(i);for(const[e,t]of Object.entries(s))o&&!o.includes(e)||(r[e]=t,n.loaded.push(e));return n.ok=!0,n}function foreignSecretValue(e,r={}){if(!isForeignSecret(e))return"";const t=r.file||secretEnvFileFor(r.dir);try{const r=parseEnvText(fs.readFileSync(t,"utf8"))[String(e)];return"string"==typeof r?r:""}catch{return""}}function resolveForeignSecret(e,r={}){if(!isForeignSecret(e))return"";const t=r.env||process.env,n=t&&t[e];if("string"==typeof n&&n.trim())return n.trim();const o=foreignSecretValue(e,r);if(o&&o.trim())return o.trim();try{const t=parseEnvText(fs.readFileSync(envFileFor(r.dir),"utf8"))[String(e)];return"string"==typeof t?t.trim():""}catch{return""}}function writeSecretFile(e,r){fs.mkdirSync(path.dirname(e),{recursive:!0,mode:SECRET_DIR_MODE});const t=`${e}.tmp-${process.pid}-${Date.now()}`;fs.writeFileSync(t,r,{mode:SECRET_FILE_MODE}),fs.renameSync(t,e),fs.chmodSync(e,SECRET_FILE_MODE)}function setForeignSecret(e,r,t={}){const n=t.file||secretEnvFileFor(t.dir),o={ok:!1,file:n,name:String(e||""),changed:!1,created:!1,replaced:!1,mode:0,tightened:!1,error:""};if(!isWritableName(e))return o.error=`refusing to write "${e}" — an env var name is [A-Za-z_][A-Za-z0-9_]*`,o;if(!isForeignSecret(e))return o.error=`refusing to write ${e} to ${SECRETS_FILE} — it is a host credential, not a foreign secret; use setEnvValue (${ENV_FILE}) instead`,o;const i=String(null==r?"":r).trim();if(!i)return o.error=`refusing to write an empty ${e}`,o;if(/[\r\n]/.test(String(r)))return o.error=`refusing to write ${e} — the value contains a line break`,o;let s="",c=0;o.created=!0;try{s=fs.readFileSync(n,"utf8"),o.created=!1;try{c=511&fs.statSync(n).mode}catch{}}catch(e){if(e&&"ENOENT"!==e.code)return o.error=`could not read ${n}: ${e.code||e.message}`,o}const E=String(s).replace(/\r\n/g,"\n");if(!o.created&&parseEnvText(E)[e]===i)return o.ok=!0,o.changed=!1,o.replaced=!0,o.mode=c||SECRET_FILE_MODE,o;const{text:a,replaced:l}=upsertEnvText(E,e,i);try{writeSecretFile(n,a)}catch(e){return o.error=`could not write ${n}: ${e.code||e.message}`,o}return o.ok=!0,o.changed=!0,o.replaced=l,o.mode=SECRET_FILE_MODE,o.tightened=platform.hasPosixModes()&&!o.created&&0!==c&&0!=(63&c),o}function splitForeignSecrets(e={}){const r=e.env||process.env,t=e.file||envFileFor(e.dir),n=e.secretsFile||secretEnvFileFor(e.dir),o=!0===e.apply,i={ok:!1,moved:[],kept:[],envFile:t,secretsFile:n,apply:o};let s;try{s=fs.readFileSync(t,"utf8")}catch(e){return i.reason=e&&"ENOENT"===e.code?"absent":"unreadable",i}const c=parseEnvText(s),E=Object.keys(c).filter(isForeignSecret).sort();if(!E.length)return i.ok=!0,i;let a="";try{a=fs.readFileSync(n,"utf8")}catch{}const l=parseEnvText(a);for(const e of E)Object.prototype.hasOwnProperty.call(l,e)?i.kept.push(e):(a=upsertEnvText(a,e,c[e]).text,i.moved.push(e));if(o){for(const e of E)s=removeEnvText(s,e).text;i.moved.length&&writeSecretFile(n,a),writeSecretFile(t,s);for(const e of E)r[e]===c[e]&&delete r[e]}else i.moved.length&&(i.secretsFile=n);return i.ok=!0,i}const MIN_CREDENTIAL_LEN=8;function credentialLooksUsable(e){return"string"==typeof e&&e.trim().length>=MIN_CREDENTIAL_LEN}function providerKeyFromEnv(e,r){const t=envVarFor(e);if(!t)return{key:"",env:"",rejected:null};const n=(r||process.env)[t],o="string"==typeof n?n.trim():"";return""===o?{key:"",env:t,rejected:null}:credentialLooksUsable(o)?{key:o,env:t,rejected:null}:{key:"",env:t,rejected:`${t} holds ${o.length} character${1===o.length?"":"s"}, which cannot be a credential`}}function isWritableName(e){return"string"==typeof e&&/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)}function quoteEnvValue(e){const r=String(e);return""===r?"":/[\s"'#\\]/.test(r)?`"${r.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:r}function upsertEnvText(e,r,t){const n=String(null==e?"":e),o=""===n||n.endsWith("\n"),i=""!==n&&""===n.split("\n").slice(-1)[0],s=""===n?[]:n.split("\n");i&&s.pop();const c=new RegExp(`^(\\s*(?:export\\s+)?)${r}\\s*=`),E=[];let a=!1;for(const e of s){const n=c.exec(e);n?a||(E.push(`${n[1]}${r}=${quoteEnvValue(t)}`),a=!0):E.push(e)}a||E.push(`${r}=${quoteEnvValue(t)}`);let l=E.join("\n");return""!==l&&(o||i)&&(l+="\n"),{text:l,replaced:a}}function setEnvValue(e,r,t={}){const n=t.env||process.env,o=t.file||envFileFor(t.dir),i={ok:!1,file:o,name:String(e||""),changed:!1,created:!1,replaced:!1,mode:0,tightened:!1,error:""};if(!isWritableName(e))return i.error=`refusing to write "${e}" — an env var name is [A-Za-z_][A-Za-z0-9_]*`,i;if(isForeignSecret(e))return i.error=`refusing to write ${e} to ${ENV_FILE} — it is a production secret, not a host key; put it in ${SECRETS_FILE} (or use loadForeignSecrets)`,i;const s=String(null==r?"":r).trim();if(!s)return i.error=`refusing to write an empty ${e}`,i;if(/[\r\n]/.test(String(r)))return i.error=`refusing to write ${e} — the value contains a line break`,i;let c="",E=0;i.created=!0;try{c=fs.readFileSync(o,"utf8"),i.created=!1;try{E=511&fs.statSync(o).mode}catch{}}catch(e){if(e&&"ENOENT"!==e.code)return i.error=`could not read ${o}: ${e.code||e.message}`,i}const a=String(c).replace(/\r\n/g,"\n");if(!i.created&&parseEnvText(a)[e]===s)return i.ok=!0,i.changed=!1,i.replaced=!0,i.mode=E||SECRET_FILE_MODE,!1!==t.apply&&(n[e]=s,sourcedFrom(n).set(e,s)),i;const{text:l,replaced:d}=upsertEnvText(a,e,s),u=`${o}.tmp-${process.pid}`;try{fs.mkdirSync(path.dirname(o),{recursive:!0,mode:SECRET_DIR_MODE}),fs.writeFileSync(u,l,{encoding:"utf8",mode:SECRET_FILE_MODE}),fs.chmodSync(u,SECRET_FILE_MODE),fs.renameSync(u,o)}catch(e){try{fs.unlinkSync(u)}catch{}return i.error=`could not write ${o}: ${e.code||e.message}`,i}return i.ok=!0,i.changed=!0,i.replaced=d,i.mode=SECRET_FILE_MODE,i.tightened=platform.hasPosixModes()&&!i.created&&0!==E&&0!=(63&E),!1!==t.apply&&(n[e]=s,sourcedFrom(n).set(e,s)),i}function removeEnvText(e,r){const t=String(null==e?"":e),n=""===t||t.endsWith("\n"),o=""!==t&&""===t.split("\n").slice(-1)[0],i=""===t?[]:t.split("\n");o&&i.pop();const s=new RegExp(`^(\\s*(?:export\\s+)?)${r}\\s*=`),c=[];let E=0;for(const e of i)s.test(e)?E+=1:c.push(e);let a=c.join("\n");return""!==a&&(n||o)&&(a+="\n"),{text:a,removed:E,changed:E>0}}function clearEnvValue(e,r={}){const t=r.env||process.env,n=r.file||envFileFor(r.dir),o={ok:!1,file:n,name:String(e||""),changed:!1,removed:0,mode:0,error:""};if(!isWritableName(e))return o.error=`refusing to clear "${e}" — an env var name is [A-Za-z_][A-Za-z0-9_]*`,o;let i="",s=!1,c=0;try{i=fs.readFileSync(n,"utf8");try{c=511&fs.statSync(n).mode}catch{}}catch(e){if(!e||"ENOENT"!==e.code)return o.error=`could not read ${n}: ${e.code||e.message}`,o;s=!0}const{text:E,removed:a,changed:l}=s?{text:"",removed:0,changed:!1}:removeEnvText(i,e);if(!l)return o.ok=!0,o.mode=c||SECRET_FILE_MODE,!1!==r.apply&&delete t[String(e)],o;const d=`${n}.tmp-${process.pid}`;try{fs.mkdirSync(path.dirname(n),{recursive:!0,mode:SECRET_DIR_MODE}),fs.writeFileSync(d,E,{encoding:"utf8",mode:SECRET_FILE_MODE}),fs.chmodSync(d,SECRET_FILE_MODE),fs.renameSync(d,n)}catch(e){try{fs.unlinkSync(d)}catch{}return o.error=`could not write ${n}: ${e.code||e.message}`,o}return o.ok=!0,o.changed=!0,o.removed=a,o.mode=SECRET_FILE_MODE,!1!==r.apply&&delete t[String(e)],o}function keyStatus(e,r={}){const t=r.env||process.env,n=r.file||envFileFor(r.dir),o=String(e||""),i={name:o,present:!1,inFile:!1,source:"none"};if(!isWritableName(o))return i;const s=t[o],c="string"==typeof s&&""!==s.trim();let E=!1;try{const e=parseEnvText(fs.readFileSync(n,"utf8"));E="string"==typeof e[o]&&""!==e[o].trim()}catch{}return i.present=c||E,i.inFile=E,i.source=c&&E?"both":c?"shell":E?"file":"none",i}function keyForModelId(e,r){const t=String(null==e?"":e).trim();if("pro"===String(r||"").toLowerCase())return{env:"CLAUDE_CODE_OAUTH_TOKEN",provider:"",vendor:"",pooled:!1,foreign:!0};if(("byok"===String(r||"").toLowerCase()||t.includes(":"))&&t.includes(":")){const e=t.slice(0,t.indexOf(":")).trim();return{env:envVarFor(e),provider:e,vendor:e,pooled:!1}}return{env:"AEGIS_API_KEY",provider:"",vendor:providerForModelId(t,r),pooled:!0}}const VENDOR_SLUGS=Object.freeze(["openai","anthropic","deepseek","google","gemini","groq","mistral","openrouter","together","together-ai","xai","x-ai","grok","huggingface","fireworks","voyage-ai","azure-openai"]),VENDOR_COMPOUNDS=Object.freeze(VENDOR_SLUGS.filter((e=>e.includes("-"))).sort(((e,r)=>r.length-e.length)));function providerForModelId(e,r){const t=String(null==e?"":e).trim().toLowerCase();if(!t)return"";if(t.includes(":"))return t.slice(0,t.indexOf(":")).trim();for(const e of VENDOR_COMPOUNDS)if(t===e||t.startsWith(e+"-"))return e;const n=t.split("-")[0];return VENDOR_SLUGS.includes(n)?n:""}module.exports={ENV_FILE:ENV_FILE,ALIASES:ALIASES,ACCOUNT_ENV_VAR:"AEGIS_API_KEY",SECRET_FILE_MODE:SECRET_FILE_MODE,envFileFor:envFileFor,envVarFor:envVarFor,parseEnvText:parseEnvText,loadEnvFile:loadEnvFile,isFromEnvFile:isFromEnvFile,providerKeyFromEnv:providerKeyFromEnv,MIN_CREDENTIAL_LEN:MIN_CREDENTIAL_LEN,credentialLooksUsable:credentialLooksUsable,providerForModelId:providerForModelId,VENDOR_SLUGS:VENDOR_SLUGS,isWritableName:isWritableName,quoteEnvValue:quoteEnvValue,upsertEnvText:upsertEnvText,removeEnvText:removeEnvText,setEnvValue:setEnvValue,clearEnvValue:clearEnvValue,keyStatus:keyStatus,keyForModelId:keyForModelId,SECRETS_FILE:SECRETS_FILE,FOREIGN_SECRET_NAMES:FOREIGN_SECRET_NAMES,FOREIGN_SECRET_PREFIXES:FOREIGN_SECRET_PREFIXES,isForeignSecret:isForeignSecret,secretEnvFileFor:secretEnvFileFor,loadForeignSecrets:loadForeignSecrets,foreignSecretValue:foreignSecretValue,resolveForeignSecret:resolveForeignSecret,setForeignSecret:setForeignSecret,splitForeignSecrets:splitForeignSecrets};
3
+ // AEGIS Code (aegiscode) — source: https://github.com/aegisinfo/aegiscode-plugin
4
+ // Conveying a modified copy, or running one as a network service, owes the
5
+ // corresponding source under this licence (§5/§13) — see LICENSING.md.
6
+ 'use strict';
7
+
8
+ /**
9
+ * The shared `~/.aegiscode/.env` store — the one file holding every key this
10
+ * product family can use, for every host:
11
+ *
12
+ * AEGIS_API_KEY=aegis_…
13
+ * OPENAI_API_KEY=sk-…
14
+ * DEEPSEEK_API_KEY=sk-…
15
+ *
16
+ * Before this module each host read `process.env` only, which meant a key was
17
+ * configured if — and only if — the user had exported it in the shell that
18
+ * happened to launch the app. That is why the byok flow needed a separate
19
+ * `/byok-key <provider>` step and an encrypted per-provider store: the file was
20
+ * never read. Reading it into `process.env` at startup makes the instruction
21
+ * the same in the CLI and the desktop — "put it in ~/.aegiscode/.env" — and it
22
+ * needs no other change in either, because `AEGIS_API_KEY` is already the FIRST
23
+ * entry in `client/credentials.js`'s documented resolution order.
24
+ *
25
+ * READING still obeys two rules this module started with:
26
+ *
27
+ * 1. A variable already present in the environment is never overwritten. The
28
+ * file is a convenience for the common case, not a way for a stale file to
29
+ * shadow an explicit `AEGIS_API_KEY=… aegiscode` in CI.
30
+ * 2. A load never rewrites anything. If the file the user made is readable by
31
+ * other accounts we say so rather than fixing it silently.
32
+ *
33
+ * WRITING was added later, because the file being read-only was the reason the
34
+ * key a user typed at the model picker did not survive the session: the only
35
+ * place a host could put it was its own encrypted store, so the CLI and the
36
+ * desktop each held a private key for the same provider and the user had to
37
+ * enter it twice. The demand is one key, entered once at the model picker,
38
+ * stored where BOTH hosts already look. So `setEnvValue` is the single writer:
39
+ *
40
+ * - the variable name is validated (`/^[A-Za-z_][A-Za-z0-9_]*$/`) and the
41
+ * value may not contain a newline, so a key can never inject a second line
42
+ * (or an unrelated variable) into a file every host sources at start-up;
43
+ * - an existing line with the same name is REPLACED in place — including its
44
+ * `export ` prefix, which is preserved — so comments, ordering and every
45
+ * other key in the file survive untouched, and a hand-written file is not
46
+ * reformatted;
47
+ * - duplicate definitions of the same name are collapsed to the one that was
48
+ * just written. Two `OPENAI_API_KEY=` lines is the "which one won?" bug,
49
+ * and the answer would otherwise depend on the reader's merge order;
50
+ * - the file is created 0600 and written through a same-directory temp file
51
+ * + rename, so a crash mid-write cannot leave a half-written key file, and
52
+ * a write never widens permissions on a file that was already tighter. A
53
+ * file that WAS group/world-readable is tightened, and the caller is told
54
+ * (`tightened: true`) rather than the change going unmentioned;
55
+ * - the value is applied to `process.env` as well, so the selection that
56
+ * triggered the write runs on the key it just stored;
57
+ * - the value is never returned, logged or echoed by anything in here.
58
+ *
59
+ * THE SECOND FILE — `~/.aegiscode/secrets.env`, and why the split exists.
60
+ *
61
+ * One file for every key the family can use was right while the keys were all
62
+ * HOST credentials: a provider key or the account key is read by the CLI, the
63
+ * desktop and the MCP plugin, so one file is what makes "enter the key once"
64
+ * true. It was never right for the variables that are not host credentials at
65
+ * all — `STRIPE_SECRET_KEY` (the billing rail of the aegis1/server product),
66
+ * `PYPI_API_TOKEN`, `CLAUDE_CODE_OAUTH_TOKEN` — which had been poured into the
67
+ * same file by hand. Those are loaded into `process.env` by every host at
68
+ * start-up, so they were inherited by every child process and visible to any
69
+ * account that can read `/proc/<pid>/environ`, for a key no host ever reads.
70
+ * That is exposure with no function behind it.
71
+ *
72
+ * The split keeps the sharing that matters and removes the sharing that does
73
+ * not:
74
+ *
75
+ * - `.env` still holds every host credential, still loaded by every host,
76
+ * still written by `setEnvValue`, still the answer to "where do I put my
77
+ * API key". Nothing about that changed.
78
+ * - `secrets.env` holds the foreign production secrets. It is NOT read at
79
+ * host start-up. `loadForeignSecrets()` reads it explicitly, for the one
80
+ * process that genuinely needs a billing token, so the value is available
81
+ * without being ambient. `setEnvValue` refuses to write a foreign name at
82
+ * all (see FOREIGN_SECRET_NAMES below), so the file cannot silently
83
+ * re-acquire one.
84
+ * - `splitForeignSecrets()` performs the migration: it moves the foreign
85
+ * names out of `.env` into `secrets.env` (0600), preserving comments,
86
+ * ordering and every other line, and is idempotent — a second run moves
87
+ * nothing. `tools/split-env-secrets.mjs` is its command line.
88
+ *
89
+ * Reading is what changed, and only for the names on that list.
90
+ */
91
+
92
+ const fs = require('node:fs');
93
+ const path = require('node:path');
94
+ const credentials = require('./credentials.js');
95
+ // `hasPosixModes()` — on Windows fs.stat's mode is synthesised from the read-only
96
+ // attribute, so 0o666 comes back for every file and the group/other test below is
97
+ // always true. Reporting a Windows user's .env as world-readable on every single
98
+ // load is a false alarm they cannot act on.
99
+ const platform = require('./platform.js');
100
+
101
+ const ENV_FILE = '.env';
102
+
103
+ /**
104
+ * The file for production secrets that are NOT host credentials. Read only by
105
+ * an explicit `loadForeignSecrets()` call — never at host start-up — so a
106
+ * billing or publishing token stops being ambient in every process.
107
+ */
108
+ const SECRETS_FILE = 'secrets.env';
109
+
110
+ /**
111
+ * Names that belong to another product and are never loaded into a host's
112
+ * environment, however they got into the file.
113
+ *
114
+ * The list is deliberately a *deny* list and not an allow list. An allow list
115
+ * would have to be updated every time a provider is added, and a key missing
116
+ * from it would stop working — the failure mode of the one feature this module
117
+ * exists to provide. A deny list can only ever make a host *less* exposed, so
118
+ * it fails in the safe direction: the worst case is a foreign secret that stays
119
+ * in `.env` and keeps being loaded, which is exactly today's behaviour.
120
+ *
121
+ * `STRIPE_` is a prefix rather than four names because the rail has grown a
122
+ * price id per plan; a new one must not be able to re-enter the shared file by
123
+ * being new.
124
+ */
125
+ const FOREIGN_SECRET_PREFIXES = Object.freeze(['STRIPE_']);
126
+
127
+ const FOREIGN_SECRET_NAMES = Object.freeze([
128
+ // Billing — the aegis1/server product's rail, not a host credential.
129
+ 'STRIPE_SECRET_KEY',
130
+ 'STRIPE_WEBHOOK_SECRET',
131
+ 'STRIPE_PRODUCT',
132
+ 'STRIPE_PRO_PRICE_ID',
133
+ 'STRIPE_S_PRICE_ID',
134
+ 'STRIPE_MEMORY_PRICE_ID',
135
+ // Publishing.
136
+ 'PYPI_API_TOKEN',
137
+ 'TWINE_PASSWORD',
138
+ // Claude Code's own OAuth token: a credential for a different CLI, which
139
+ // reads it from its own environment. No host in this repo does.
140
+ 'CLAUDE_CODE_OAUTH_TOKEN',
141
+ ]);
142
+
143
+ /**
144
+ * Is this variable one that must never be loaded into a host process?
145
+ *
146
+ * @param {string} name
147
+ * @returns {boolean}
148
+ */
149
+ function isForeignSecret(name) {
150
+ const n = String(name == null ? '' : name).trim();
151
+ if (!n) return false;
152
+ if (FOREIGN_SECRET_NAMES.includes(n)) return true;
153
+ return FOREIGN_SECRET_PREFIXES.some((p) => n.startsWith(p));
154
+ }
155
+
156
+ /** Permissions for a file holding secrets: owner read/write, nothing else. */
157
+ const SECRET_FILE_MODE = 0o600;
158
+
159
+ /** A directory we create for a secret file: owner only. */
160
+ const SECRET_DIR_MODE = 0o700;
161
+
162
+ /**
163
+ * provider id -> the env var a BYOK key is conventionally exported as, for the
164
+ * ids where the generic rule below would spell the wrong name. The generic rule
165
+ * is `ID_API_KEY` in upper snake case, which already covers openai, anthropic,
166
+ * deepseek, groq, mistral, openrouter, together and most of the catalogue — so
167
+ * this table is only the exceptions, kept short on purpose.
168
+ */
169
+ const ALIASES = Object.freeze({
170
+ google: 'GEMINI_API_KEY',
171
+ gemini: 'GEMINI_API_KEY',
172
+ 'google-ai': 'GEMINI_API_KEY',
173
+ xai: 'XAI_API_KEY',
174
+ 'x-ai': 'XAI_API_KEY',
175
+ grok: 'XAI_API_KEY',
176
+ huggingface: 'HF_TOKEN',
177
+ together: 'TOGETHER_API_KEY',
178
+ 'together-ai': 'TOGETHER_API_KEY',
179
+ fireworks: 'FIREWORKS_API_KEY',
180
+ 'azure-openai': 'AZURE_OPENAI_API_KEY',
181
+ 'voyage-ai': 'VOYAGE_API_KEY',
182
+ });
183
+
184
+ /** The variable that carries an AEGIS Cloud account key (see credentials.js). */
185
+ const ACCOUNT_ENV_VAR = 'AEGIS_API_KEY';
186
+
187
+ /** The file this host would read, honouring `$AEGISCODE_HOME`. */
188
+ function envFileFor(dir) {
189
+ return path.join(dir || credentials.aegisHome(), ENV_FILE);
190
+ }
191
+
192
+ /**
193
+ * The foreign-secrets file beside `envFileFor()`, honouring the same
194
+ * `$AEGISCODE_HOME`. Never read implicitly.
195
+ */
196
+ function secretEnvFileFor(dir) {
197
+ return path.join(dir || credentials.aegisHome(), SECRETS_FILE);
198
+ }
199
+
200
+ /**
201
+ * The env var one BYOK provider's key is read from.
202
+ *
203
+ * @param {string} providerId e.g. 'openai', 'deepseek', 'Google'
204
+ * @returns {string} e.g. 'OPENAI_API_KEY' — '' when there is no usable id
205
+ */
206
+ function envVarFor(providerId) {
207
+ const id = String(providerId || '').trim().toLowerCase();
208
+ if (!id) return '';
209
+ // A `byok:` prefixed row is the same provider — accept it so callers can pass
210
+ // whatever spelling they hold without stripping it first.
211
+ const bare = id.startsWith('byok:') ? id.slice('byok:'.length).trim() : id;
212
+ if (!bare) return '';
213
+ if (ALIASES[bare]) return ALIASES[bare];
214
+ const name = bare.toUpperCase().replace(/[^A-Z0-9]+/g, '_').replace(/^_+|_+$/g, '');
215
+ return name ? `${name}_API_KEY` : '';
216
+ }
217
+
218
+ /** A fragment of a token/secret: no whitespace, no dotenv punctuation around it. */
219
+ const ENV_TOKENISH = /^[A-Za-z0-9_+/.-]+$/;
220
+
221
+ /** A value long enough that a keyless line after it is a wrap, not junk. */
222
+ const ENV_WRAP_MIN_VALUE = 32;
223
+
224
+ /**
225
+ * Fold a hard-wrapped value back onto its `KEY=` line.
226
+ *
227
+ * A long secret pasted into a wrapping editor leaves its tail on the next
228
+ * physical line. Dotenv semantics would keep the head as the value and discard
229
+ * the keyless tail, so the credential loads as a TRUNCATED string that looks
230
+ * present and fails deep in a provider call — a 108-char Claude Code OAuth
231
+ * token lost its last 9 chars this way and every request 401'd with "OAuth
232
+ * access token is invalid" while the env var looked set.
233
+ *
234
+ * A fold requires the tail to be unambiguously a token fragment: no whitespace,
235
+ * no `=`, not a comment, and either indented (the wrap signature a wrapped paste
236
+ * leaves behind) or following a value already long enough to be a secret. The
237
+ * head must itself be a plain unquoted token, so an inline ` # comment` can
238
+ * never be glued to the next line. A short value plus a bare word ("x" then
239
+ * "NOEQ") is left alone — that is a junk line, and gluing it on would corrupt
240
+ * the real value.
241
+ *
242
+ * @param {string[]} lines every physical line of the file
243
+ * @param {number} i index of the `KEY=` line
244
+ * @param {string} head the trimmed value on that line
245
+ * @returns {{value:string, i:number}} the folded value and the last line consumed
246
+ */
247
+ function foldWrappedEnvValue(lines, i, head) {
248
+ let value = head;
249
+ // Only an unquoted, comment-free, token-shaped head may absorb a tail: any
250
+ // other head is a value with structure worth preserving verbatim.
251
+ if (value.startsWith('"') || value.startsWith("'")) return { value, i };
252
+ while (i + 1 < lines.length) {
253
+ const nextRaw = lines[i + 1];
254
+ const next = nextRaw.trim();
255
+ if (!next || next.startsWith('#') || next.includes('=')) break;
256
+ if (!ENV_TOKENISH.test(next)) break;
257
+ const indented = /^[ \t]/.test(nextRaw);
258
+ // The non-indented branch is the risky one (a bare word after a value), so
259
+ // it additionally demands the head be one unbroken token AND long enough to
260
+ // be a secret before it is allowed to swallow the line.
261
+ if (!indented && (value.length < ENV_WRAP_MIN_VALUE || !ENV_TOKENISH.test(value))) break;
262
+ value += next;
263
+ i += 1;
264
+ // Once a tail has been absorbed the head is only longer, so a further
265
+ // indented fragment keeps folding; a non-indented one now clears the length
266
+ // bar on its own.
267
+ }
268
+ return { value, i };
269
+ }
270
+
271
+ /**
272
+ * Parse dotenv text. Deliberately small and total: an unparseable line is
273
+ * skipped rather than thrown, so one bad line cannot stop the rest of the file
274
+ * (and a stray `#` comment or a blank line is normal, not an error).
275
+ *
276
+ * Handles `export `, `KEY=value`, `KEY="value"`, `KEY='value'` and a trailing
277
+ * ` # comment` on an unquoted value. A double-quoted value is unescaped (`\"`,
278
+ * `\\`) because that is what `quoteEnvValue` writes and what dotenv readers do;
279
+ * a single-quoted value is literal.
280
+ *
281
+ * A hard-wrapped paste is folded back together (see `foldWrappedEnvValue`).
282
+ * This is not cosmetic: a 108-char Claude Code OAuth token pasted into a
283
+ * wrapping editor landed as a 99-char head plus an indented keyless tail, and
284
+ * the head loaded as a TRUNCATED credential that looked present and 401'd deep
285
+ * in a provider call. The same fold exists in `src/env.js` of the engine repo
286
+ * (`parseEnvFile`) so both readers agree on a wrapped file.
287
+ */
288
+ function parseEnvText(text) {
289
+ const out = {};
290
+ const lines = String(text == null ? '' : text).split(/\r?\n/);
291
+ for (let i = 0; i < lines.length; i++) {
292
+ const line = lines[i].trim();
293
+ if (!line || line.startsWith('#')) continue;
294
+ const eq = line.indexOf('=');
295
+ if (eq <= 0) continue;
296
+ let name = line.slice(0, eq).trim();
297
+ if (name.startsWith('export ')) name = name.slice('export '.length).trim();
298
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) continue;
299
+ const folded = foldWrappedEnvValue(lines, i, line.slice(eq + 1).trim());
300
+ let value = folded.value;
301
+ i = folded.i;
302
+ const doubleQuoted = value.startsWith('"') && value.endsWith('"') && value.length >= 2;
303
+ const singleQuoted = value.startsWith("'") && value.endsWith("'") && value.length >= 2;
304
+ if (doubleQuoted) {
305
+ // Double quotes are the one form that carries escapes, so they are the
306
+ // one form that must be unescaped — `\"` and `\\`, exactly what
307
+ // `quoteEnvValue` writes and what every dotenv reader does. Without this
308
+ // the writer's escaping was one-way: a value containing a quote or a
309
+ // backslash was stored doubled and read back mangled, so a key survived
310
+ // the session it was typed in but not the next one. Single quotes stay
311
+ // literal (`'C:\keys'` is a backslash, not an escape), which is the
312
+ // convention that makes the two quote styles mean something different.
313
+ value = value.slice(1, -1).replace(/\\(["\\])/g, '$1');
314
+ } else if (singleQuoted) {
315
+ value = value.slice(1, -1);
316
+ } else {
317
+ const hash = value.indexOf(' #');
318
+ if (hash !== -1) value = value.slice(0, hash).trim();
319
+ }
320
+ out[name] = value;
321
+ }
322
+ return out;
323
+ }
324
+
325
+ /**
326
+ * Read the env file into `process.env` (or `o.env`), without overwriting
327
+ * anything already set.
328
+ *
329
+ * @param {object} [o]
330
+ * @param {object} [o.env] defaults to process.env
331
+ * @param {string} [o.dir] defaults to aegisHome()
332
+ * @param {string} [o.file] an explicit path, for tests
333
+ * @returns {{ok:boolean, file:string, loaded:string[], kept:string[],
334
+ * reason:string, loose:boolean, mode:number}}
335
+ * `loaded` — names taken from the file. `kept` — names the environment
336
+ * already had, left alone (a real export always wins).
337
+ */
338
+ /**
339
+ * Provenance of every value this process took from `~/.aegiscode/.env`.
340
+ *
341
+ * Keyed off the env object itself (a WeakMap, so an injected `{ env }` in a
342
+ * test is tracked without leaking and `process.env` needs no extra property).
343
+ * See `isFromEnvFile`.
344
+ */
345
+ const ENV_SOURCED = new WeakMap();
346
+
347
+ function sourcedFrom(env) {
348
+ let map = ENV_SOURCED.get(env);
349
+ if (!map) {
350
+ map = new Map();
351
+ ENV_SOURCED.set(env, map);
352
+ }
353
+ return map;
354
+ }
355
+
356
+ /**
357
+ * Was `name`'s CURRENT value in `env` one this process took from the shared env
358
+ * file, rather than something the launching shell exported?
359
+ *
360
+ * This is the distinction the file's own rule 1 depends on and could not
361
+ * previously express. The file is documented as a *convenience for the common
362
+ * case, not a way for a stale file to shadow an explicit export* — but once a
363
+ * value is copied into `process.env` the two are the same thing, so every
364
+ * env-first reader (`client/credentials.js`) treated a line in the file exactly
365
+ * like a deliberate export and let it win forever. Concretely: a user runs
366
+ * `aegiscode login`, the key is written to `credentials.json` (0600) and
367
+ * reported as saved, and every request since then authenticates with whatever
368
+ * `AEGIS_API_KEY=` line the file still carries — the "it says saved but the key
369
+ * is wrong" report. A real export still wins; a file value is a fallback.
370
+ *
371
+ * `value` is checked as well as the name: a shell export that replaced the
372
+ * loaded value is no longer file-sourced, and neither is a later `setEnvValue`
373
+ * (which applies the value it just wrote and marks it accordingly).
374
+ *
375
+ * @param {string} name
376
+ * @param {string} [value] the current value, to confirm it is still the one the
377
+ * file provided. Omit to ask about the name alone.
378
+ * @param {object} [o] `env`, for tests and injected environments
379
+ */
380
+ function isFromEnvFile(name, value, o = {}) {
381
+ const env = o.env || process.env;
382
+ const map = ENV_SOURCED.get(env);
383
+ if (!map || !map.has(name)) return false;
384
+ if (value === undefined) return true;
385
+ return map.get(name) === String(value);
386
+ }
387
+
388
+ function loadEnvFile(o = {}) {
389
+ const env = o.env || process.env;
390
+ const file = o.file || envFileFor(o.dir);
391
+ // Names this process took from the FILE, with the value it took. Kept so a
392
+ // consumer can tell the two sources apart: rule 1 above makes the file a
393
+ // fallback, but the moment its value lands in `process.env` it is otherwise
394
+ // indistinguishable from an explicit `AEGIS_API_KEY=… aegiscode` export, and
395
+ // `client/credentials.js`'s resolution order is env-first. Without this
396
+ // marker a leftover line in a file every host sources at start-up outranks
397
+ // the key the user explicitly saved — see `isFromEnvFile()` below.
398
+ const sourced = sourcedFrom(env);
399
+ const result = {
400
+ ok: false, file, loaded: [], kept: [], refused: [], reason: '', loose: false, mode: 0,
401
+ };
402
+
403
+ let text;
404
+ try {
405
+ text = fs.readFileSync(file, 'utf8');
406
+ } catch (e) {
407
+ result.reason = e && e.code === 'ENOENT' ? 'absent' : 'unreadable';
408
+ return result;
409
+ }
410
+
411
+ try {
412
+ const st = fs.statSync(file);
413
+ result.mode = st.mode & 0o777;
414
+ // Group- or world-readable: worth one line to the user, never a rewrite of
415
+ // a file we did not create. Only asked where the answer can be true or false
416
+ // (see the platform require above).
417
+ result.loose = platform.hasPosixModes() && (st.mode & 0o077) !== 0;
418
+ } catch { /* stat is advisory only */ }
419
+
420
+ const parsed = parseEnvText(text);
421
+ for (const [name, value] of Object.entries(parsed)) {
422
+ // A foreign secret is neither loaded nor "kept": it is refused, and named
423
+ // in `refused` so a caller can tell the user it is in the wrong file
424
+ // instead of silently ignoring it.
425
+ if (isForeignSecret(name)) {
426
+ result.refused.push(name);
427
+ continue;
428
+ }
429
+ if (env[name] === undefined || env[name] === '') {
430
+ env[name] = value;
431
+ // Provenance: this value is the FILE's, not the launching shell's. An
432
+ // env-first reader must treat it as the fallback the file is documented
433
+ // to be, not as an explicit export that outranks a saved key.
434
+ sourced.set(name, value);
435
+ result.loaded.push(name);
436
+ } else {
437
+ // A real export wins (rule 1) and is deliberately NOT marked: it is the
438
+ // one source allowed to outrank `credentials.json`.
439
+ result.kept.push(name);
440
+ }
441
+ }
442
+ result.ok = true;
443
+ return result;
444
+ }
445
+
446
+ /**
447
+ * Read the foreign-secrets file into an environment, on purpose.
448
+ *
449
+ * The counterpart of the refusal inside `loadEnvFile`: a process that actually
450
+ * needs a billing or publishing token asks for it by name, and it is documented
451
+ * at the call site. Nothing calls this at host start-up — that is the point of
452
+ * the split — and unlike `loadEnvFile` it does NOT treat an already-set variable
453
+ * as a reason to skip: a caller who asks for the secrets file gets the file's
454
+ * values, in a fresh object unless one is passed.
455
+ *
456
+ * @param {object} [o]
457
+ * @param {object} [o.env]
458
+ * @param {string} [o.dir]
459
+ * @param {string} [o.file]
460
+ * @param {string[]} [o.only] restrict to these names
461
+ * @returns {{ok:boolean, file:string, loaded:string[], reason:string,
462
+ * mode:number, loose:boolean}}
463
+ */
464
+ function loadForeignSecrets(o = {}) {
465
+ const env = o.env || process.env;
466
+ const file = o.file || secretEnvFileFor(o.dir);
467
+ const result = { ok: false, file, loaded: [], reason: '', mode: 0, loose: false };
468
+ const only = Array.isArray(o.only) && o.only.length
469
+ ? o.only.filter(isForeignSecret)
470
+ : null;
471
+
472
+ let text;
473
+ try {
474
+ text = fs.readFileSync(file, 'utf8');
475
+ } catch (e) {
476
+ result.reason = e && e.code === 'ENOENT' ? 'absent' : 'unreadable';
477
+ return result;
478
+ }
479
+
480
+ try {
481
+ const st = fs.statSync(file);
482
+ result.mode = st.mode & 0o777;
483
+ result.loose = platform.hasPosixModes() && (st.mode & 0o077) !== 0;
484
+ } catch { /* advisory */ }
485
+
486
+ const parsed = parseEnvText(text);
487
+ for (const [name, value] of Object.entries(parsed)) {
488
+ if (only && !only.includes(name)) continue;
489
+ env[name] = value;
490
+ result.loaded.push(name);
491
+ }
492
+ result.ok = true;
493
+ return result;
494
+ }
495
+
496
+ /**
497
+ * One foreign secret, read without exporting it into an environment.
498
+ *
499
+ * @returns {string} '' when the file does not exist or does not hold the name
500
+ */
501
+ function foreignSecretValue(name, o = {}) {
502
+ if (!isForeignSecret(name)) return '';
503
+ const file = o.file || secretEnvFileFor(o.dir);
504
+ try {
505
+ const parsed = parseEnvText(fs.readFileSync(file, 'utf8'));
506
+ const v = parsed[String(name)];
507
+ return typeof v === 'string' ? v : '';
508
+ } catch {
509
+ return '';
510
+ }
511
+ }
512
+
513
+ /**
514
+ * One foreign secret's value, from every place a user might actually have put
515
+ * it — built for `CLAUDE_CODE_OAUTH_TOKEN`, which lived in plain `.env` before
516
+ * this split existed and is not necessarily migrated on any given machine.
517
+ *
518
+ * Checked in the order that keeps an explicit export authoritative, same as
519
+ * `loadEnvFile`'s rule 1:
520
+ *
521
+ * 1. `o.env` (default `process.env`) — a real shell export is the user's own
522
+ * doing and always wins, exactly as it does for a host key.
523
+ * 2. `secrets.env` (`foreignSecretValue`) — the file the split moves this
524
+ * name to, and the only one `setForeignSecret` below ever writes.
525
+ * 3. `.env`, parsed directly — covers a name that has not been migrated yet.
526
+ *
527
+ * Never applies the value to any env object: the whole point of the split is
528
+ * that this name stays OUT of `process.env` unless the caller that actually
529
+ * needs it (the Claude Code Pro transport) asks for it by name, right before
530
+ * it is used.
531
+ *
532
+ * @param {string} name
533
+ * @param {object} [o] `env`, `dir`, `file` — same meaning as `foreignSecretValue`
534
+ * @returns {string} '' when no source has it, or `name` is not a foreign secret
535
+ */
536
+ function resolveForeignSecret(name, o = {}) {
537
+ if (!isForeignSecret(name)) return '';
538
+ const env = o.env || process.env;
539
+ const direct = env && env[name];
540
+ if (typeof direct === 'string' && direct.trim()) return direct.trim();
541
+ const fromSecrets = foreignSecretValue(name, o);
542
+ if (fromSecrets && fromSecrets.trim()) return fromSecrets.trim();
543
+ try {
544
+ const parsed = parseEnvText(fs.readFileSync(envFileFor(o.dir), 'utf8'));
545
+ const v = parsed[String(name)];
546
+ return typeof v === 'string' ? v.trim() : '';
547
+ } catch {
548
+ return '';
549
+ }
550
+ }
551
+
552
+ /** Write a secrets file with the right permissions and no half-written state. */
553
+ function writeSecretFile(file, text) {
554
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: SECRET_DIR_MODE });
555
+ const tmp = `${file}.tmp-${process.pid}-${Date.now()}`;
556
+ fs.writeFileSync(tmp, text, { mode: SECRET_FILE_MODE });
557
+ fs.renameSync(tmp, file);
558
+ // rename preserves the temp file's mode, which the umask may have loosened on
559
+ // a machine with a permissive one — so the mode is asserted after the move.
560
+ fs.chmodSync(file, SECRET_FILE_MODE);
561
+ }
562
+
563
+ /**
564
+ * Store one foreign secret in `~/.aegiscode/secrets.env` — the counterpart of
565
+ * `setEnvValue`, for the file that one exists to keep out of.
566
+ *
567
+ * The guard is the mirror image of `setEnvValue`'s: that function refuses a
568
+ * foreign name so `.env` cannot re-acquire one, and this one refuses anything
569
+ * that is NOT a foreign name, so `secrets.env` cannot become a second place a
570
+ * host credential is written (and therefore a second place to look for one).
571
+ *
572
+ * Deliberately has no `apply` option and never touches any env object: a
573
+ * foreign secret's whole point is staying out of `process.env` until the one
574
+ * caller that needs it asks by name (`resolveForeignSecret`), right before use.
575
+ *
576
+ * @param {string} name one of FOREIGN_SECRET_NAMES (or a FOREIGN_SECRET_PREFIXES match)
577
+ * @param {string} value the secret. Never returned, never logged.
578
+ * @param {object} [o]
579
+ * @param {string} [o.dir] defaults to aegisHome()
580
+ * @param {string} [o.file] an explicit path, for tests
581
+ * @returns {{ok:boolean, file:string, name:string, changed:boolean,
582
+ * created:boolean, replaced:boolean, mode:number, tightened:boolean,
583
+ * error:string}}
584
+ */
585
+ function setForeignSecret(name, value, o = {}) {
586
+ const file = o.file || secretEnvFileFor(o.dir);
587
+ const out = {
588
+ ok: false, file, name: String(name || ''), changed: false, created: false,
589
+ replaced: false, mode: 0, tightened: false, error: '',
590
+ };
591
+
592
+ if (!isWritableName(name)) {
593
+ out.error = `refusing to write "${name}" — an env var name is [A-Za-z_][A-Za-z0-9_]*`;
594
+ return out;
595
+ }
596
+ if (!isForeignSecret(name)) {
597
+ out.error = `refusing to write ${name} to ${SECRETS_FILE} — it is a host credential, not a `
598
+ + `foreign secret; use setEnvValue (${ENV_FILE}) instead`;
599
+ return out;
600
+ }
601
+ const secret = String(value == null ? '' : value).trim();
602
+ if (!secret) {
603
+ out.error = `refusing to write an empty ${name}`;
604
+ return out;
605
+ }
606
+ if (/[\r\n]/.test(String(value))) {
607
+ out.error = `refusing to write ${name} — the value contains a line break`;
608
+ return out;
609
+ }
610
+
611
+ let before = '';
612
+ let previousMode = 0;
613
+ out.created = true;
614
+ try {
615
+ before = fs.readFileSync(file, 'utf8');
616
+ out.created = false;
617
+ try {
618
+ previousMode = fs.statSync(file).mode & 0o777;
619
+ } catch { /* advisory */ }
620
+ } catch (e) {
621
+ if (e && e.code !== 'ENOENT') {
622
+ out.error = `could not read ${file}: ${e.code || e.message}`;
623
+ return out;
624
+ }
625
+ }
626
+
627
+ const aligned = String(before).replace(/\r\n/g, '\n');
628
+ if (!out.created && parseEnvText(aligned)[name] === secret) {
629
+ // Same value already stored: leave the file (its mtime, its mode) alone.
630
+ out.ok = true;
631
+ out.changed = false;
632
+ out.replaced = true;
633
+ out.mode = previousMode || SECRET_FILE_MODE;
634
+ return out;
635
+ }
636
+
637
+ const { text, replaced } = upsertEnvText(aligned, name, secret);
638
+ try {
639
+ writeSecretFile(file, text);
640
+ } catch (e) {
641
+ out.error = `could not write ${file}: ${e.code || e.message}`;
642
+ return out;
643
+ }
644
+
645
+ out.ok = true;
646
+ out.changed = true;
647
+ out.replaced = replaced;
648
+ out.mode = SECRET_FILE_MODE;
649
+ out.tightened =
650
+ platform.hasPosixModes() && !out.created && previousMode !== 0 && (previousMode & 0o077) !== 0;
651
+ return out;
652
+ }
653
+
654
+ /**
655
+ * Move every foreign secret out of `~/.aegiscode/.env` into `secrets.env`.
656
+ *
657
+ * Idempotent by construction: the names moved are the ones the parse finds in
658
+ * `.env`, and a second run finds none. A name already present in `secrets.env`
659
+ * is not overwritten — the destination is the authority once it exists, so a
660
+ * migration can never silently revert a value someone rotated there.
661
+ *
662
+ * Every other line of `.env` — comments, order, unrelated keys, `export`
663
+ * prefixes — survives verbatim, because both edits go through the same
664
+ * `upsertEnvText`/`removeEnvText` pair the writers use.
665
+ *
666
+ * @param {object} [o]
667
+ * @param {boolean} [o.apply=false] without it, nothing is written (dry run)
668
+ * @returns {{ok:boolean, moved:string[], kept:string[], envFile:string,
669
+ * secretsFile:string, apply:boolean, reason?:string}}
670
+ */
671
+ function splitForeignSecrets(o = {}) {
672
+ const env = o.env || process.env;
673
+ const envFile = o.file || envFileFor(o.dir);
674
+ const secretsFile = o.secretsFile || secretEnvFileFor(o.dir);
675
+ const apply = o.apply === true;
676
+ const out = { ok: false, moved: [], kept: [], envFile, secretsFile, apply };
677
+
678
+ let envText;
679
+ try {
680
+ envText = fs.readFileSync(envFile, 'utf8');
681
+ } catch (e) {
682
+ out.reason = e && e.code === 'ENOENT' ? 'absent' : 'unreadable';
683
+ return out;
684
+ }
685
+
686
+ const parsed = parseEnvText(envText);
687
+ const names = Object.keys(parsed).filter(isForeignSecret).sort();
688
+ if (!names.length) {
689
+ out.ok = true;
690
+ return out;
691
+ }
692
+
693
+ let secretsText = '';
694
+ try {
695
+ secretsText = fs.readFileSync(secretsFile, 'utf8');
696
+ } catch { /* the file is created below */ }
697
+ const already = parseEnvText(secretsText);
698
+
699
+ for (const name of names) {
700
+ if (Object.prototype.hasOwnProperty.call(already, name)) {
701
+ out.kept.push(name);
702
+ continue;
703
+ }
704
+ secretsText = upsertEnvText(secretsText, name, parsed[name]).text;
705
+ out.moved.push(name);
706
+ }
707
+
708
+ if (apply) {
709
+ for (const name of names) {
710
+ envText = removeEnvText(envText, name).text;
711
+ }
712
+ if (out.moved.length) writeSecretFile(secretsFile, secretsText);
713
+ writeSecretFile(envFile, envText);
714
+ // And out of the live environment of THIS process, or a running host would
715
+ // keep the value it had already loaded until it restarted.
716
+ for (const name of names) {
717
+ if (env[name] === parsed[name]) delete env[name];
718
+ }
719
+ } else if (out.moved.length) {
720
+ // A dry run still shows the destination, without creating it.
721
+ out.secretsFile = secretsFile;
722
+ }
723
+
724
+ out.ok = true;
725
+ return out;
726
+ }
727
+
728
+ /**
729
+ * The shortest value that can be a real vendor credential.
730
+ *
731
+ * Not a shape check on any one vendor's format — deliberately. The vendors this
732
+ * file serves disagree about their prefixes (`sk-ant-api03-`, `sk-proj-`,
733
+ * `aegis_`, `gsk_`, a bare opaque string for a custom gateway), and a prefix
734
+ * allow-list here would refuse a valid key for a provider added tomorrow. What
735
+ * every one of them agrees on is the FLOOR: no vendor issues a credential that
736
+ * is a handful of characters. A value below this is not a key somebody typed
737
+ * wrongly-shaped, it is a paste that lost its payload or an answer typed into
738
+ * the wrong prompt, and the difference matters because the two failure modes
739
+ * look nothing alike to the user (see `providerKeyFromEnv`, and the upstream
740
+ * 401 that a 2-character value produced).
741
+ *
742
+ * Eight is the floor rather than something larger on purpose: it is below every
743
+ * real credential by orders of magnitude, so it can only ever reject values
744
+ * that are provably not keys, and it cannot reject one that is.
745
+ */
746
+ const MIN_CREDENTIAL_LEN = 8;
747
+
748
+ /** Whether `value` is long enough to be a credential at all. See the floor above. */
749
+ function credentialLooksUsable(value) {
750
+ return typeof value === 'string' && value.trim().length >= MIN_CREDENTIAL_LEN;
751
+ }
752
+
753
+ /**
754
+ * The BYOK key for a provider out of the environment, if the env file (or the
755
+ * shell) supplies one. Returns '' when it does not — the encrypted store then
756
+ * remains the only source, exactly as before.
757
+ */
758
+ function providerKeyFromEnv(providerId, env) {
759
+ const name = envVarFor(providerId);
760
+ if (!name) return { key: '', env: '', rejected: null };
761
+ const raw = (env || process.env)[name];
762
+ const key = typeof raw === 'string' ? raw.trim() : '';
763
+ if (key === '') return { key: '', env: name, rejected: null };
764
+ if (!credentialLooksUsable(key)) {
765
+ // A value that CANNOT be a vendor credential is not one, and returning it
766
+ // as `key` is how a junk entry became an upstream 401 instead of a prompt.
767
+ // Measured on this machine 2026-10-14: `~/.aegiscode/.env` held
768
+ // `ANTHROPIC_API_KEY=he` (2 characters — a paste that lost its value, or an
769
+ // answer typed into the wrong prompt). Every reader below took it as a key,
770
+ // the picker painted the `anthropic:*` rows as `configured`, the turn
771
+ // forwarded `X-Provider-Key: he` to the relay, and Anthropic answered
772
+ // `{"type":"error","error":{"type":"authentication_error","message":
773
+ // "Invalid bearer token"}}` — surfaced to the user as "Anthropic auth
774
+ // failed", which reads as "your Anthropic account is broken" when the
775
+ // truth is "this file holds two characters". Rejecting it here makes the
776
+ // row read as keyless, so `/model` prompts for the key again and the engine
777
+ // raises its own actionable "No key for …" instead of echoing a vendor 401.
778
+ return { key: '', env: name, rejected: `${name} holds ${key.length} character${key.length === 1 ? '' : 's'}, which cannot be a credential` };
779
+ }
780
+ return { key, env: name, rejected: null };
781
+ }
782
+
783
+ /** A variable name this module is willing to write. */
784
+ function isWritableName(name) {
785
+ return typeof name === 'string' && /^[A-Za-z_][A-Za-z0-9_]*$/.test(name);
786
+ }
787
+
788
+ /**
789
+ * Quote a value the way `parseEnvText` (and every dotenv reader) will read back
790
+ * byte-identically. Unquoted when it is safe; double-quoted with backslashes and
791
+ * quotes escaped when it is not. A newline is refused by the caller, never
792
+ * escaped here: escaping it would hide a malformed key behind a file that
793
+ * still looks right.
794
+ */
795
+ function quoteEnvValue(value) {
796
+ const s = String(value);
797
+ if (s === '') return '';
798
+ if (!/[\s"'#\\]/.test(s)) return s;
799
+ return `"${s.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
800
+ }
801
+
802
+ /**
803
+ * Apply `name=value` to dotenv text: replace the first existing definition in
804
+ * place (keeping an `export ` prefix and any trailing comment-less formatting),
805
+ * drop later duplicates, and append when the name is new. Every other line —
806
+ * comments, blanks, unrelated keys, their order — is preserved verbatim.
807
+ *
808
+ * Pure, and exported for tests: this is the part worth pinning, because a bug
809
+ * here silently destroys a file the user also edits by hand.
810
+ *
811
+ * @returns {{text:string, replaced:boolean}}
812
+ */
813
+ function upsertEnvText(text, name, value) {
814
+ const src = String(text == null ? '' : text);
815
+ // Split without keeping the terminator, then re-join with '\n' and restore a
816
+ // final newline only if the file had one — so a write never adds a dangling
817
+ // blank line to a file that ended cleanly.
818
+ const hadFinalNewline = src === '' ? true : src.endsWith('\n');
819
+ const trailingBlank = src === '' ? false : src.split('\n').slice(-1)[0] === '';
820
+ // An EMPTY file is zero lines, not one empty line: `''.split('\n')` is `['']`,
821
+ // and that stray element survives to `out` because the pop above only fires
822
+ // when `trailingBlank` is true (forced false for an empty source). The result
823
+ // was a first-ever write that opened the file with a leading blank line —
824
+ // `'\nNAME=secret\n'` — breaking the contract the comment two lines up
825
+ // states and the round-trip guarantee below. The common case is exactly this
826
+ // one: a fresh ~/.aegiscode/.env on a new machine.
827
+ const lines = src === '' ? [] : src.split('\n');
828
+ if (trailingBlank) lines.pop();
829
+
830
+ const re = new RegExp(`^(\\s*(?:export\\s+)?)${name}\\s*=`);
831
+ const out = [];
832
+ let replaced = false;
833
+ for (const line of lines) {
834
+ const m = re.exec(line);
835
+ if (!m) {
836
+ out.push(line);
837
+ continue;
838
+ }
839
+ if (replaced) continue; // a second definition of the same name: collapse it
840
+ out.push(`${m[1]}${name}=${quoteEnvValue(value)}`);
841
+ replaced = true;
842
+ }
843
+ if (!replaced) out.push(`${name}=${quoteEnvValue(value)}`);
844
+
845
+ let joined = out.join('\n');
846
+ if (joined !== '' && (hadFinalNewline || trailingBlank)) joined += '\n';
847
+ return { text: joined, replaced };
848
+ }
849
+
850
+ /**
851
+ * Store one variable in `~/.aegiscode/.env`, creating the file (0600) and the
852
+ * directory (0700) when needed, and apply it to the live environment so the
853
+ * action that triggered the write runs on it.
854
+ *
855
+ * The one writer for every host: the CLI calls it when a model is selected and
856
+ * its key is missing, and the desktop calls the same function through the same
857
+ * staged file, which is what makes a key entered once usable in both.
858
+ *
859
+ * @param {string} name an env var name, e.g. 'OPENAI_API_KEY'
860
+ * @param {string} value the secret. Never returned, never logged.
861
+ * @param {object} [o]
862
+ * @param {string} [o.dir] defaults to aegisHome()
863
+ * @param {string} [o.file] an explicit path, for tests
864
+ * @param {object} [o.env] defaults to process.env
865
+ * @param {boolean} [o.apply=true] set it in `o.env`/process.env as well
866
+ * @returns {{ok:boolean, file:string, name:string, changed:boolean,
867
+ * created:boolean, replaced:boolean, mode:number, tightened:boolean,
868
+ * error:string}}
869
+ * `changed` is false when the file already held that exact value — a re-save
870
+ * of an unchanged key must not rewrite the file.
871
+ */
872
+ function setEnvValue(name, value, o = {}) {
873
+ const env = o.env || process.env;
874
+ const file = o.file || envFileFor(o.dir);
875
+ const out = {
876
+ ok: false, file, name: String(name || ''), changed: false, created: false,
877
+ replaced: false, mode: 0, tightened: false, error: '',
878
+ };
879
+
880
+ if (!isWritableName(name)) {
881
+ out.error = `refusing to write "${name}" — an env var name is [A-Za-z_][A-Za-z0-9_]*`;
882
+ return out;
883
+ }
884
+ // The lock on the split: this file holds host keys, so a name that is not a
885
+ // host key is refused rather than written. Saying so is the point — the
886
+ // alternative (writing it and declining to load it) would recreate the exact
887
+ // state the split removed, with the value still on disk in the shared file.
888
+ if (isForeignSecret(name)) {
889
+ out.error = `refusing to write ${name} to ${ENV_FILE} — it is a production secret, not a host key;`
890
+ + ` put it in ${SECRETS_FILE} (or use loadForeignSecrets)`;
891
+ return out;
892
+ }
893
+ const secret = String(value == null ? '' : value).trim();
894
+ if (!secret) {
895
+ out.error = `refusing to write an empty ${name}`;
896
+ return out;
897
+ }
898
+ // The one injection this file must not accept: a value carrying a newline
899
+ // would append a line, and the file is sourced by every host at start-up.
900
+ if (/[\r\n]/.test(String(value))) {
901
+ out.error = `refusing to write ${name} — the value contains a line break`;
902
+ return out;
903
+ }
904
+
905
+ let before = '';
906
+ let previousMode = 0;
907
+ out.created = true;
908
+ try {
909
+ before = fs.readFileSync(file, 'utf8');
910
+ out.created = false;
911
+ try {
912
+ previousMode = fs.statSync(file).mode & 0o777;
913
+ } catch { /* advisory */ }
914
+ } catch (e) {
915
+ if (e && e.code !== 'ENOENT') {
916
+ out.error = `could not read ${file}: ${e.code || e.message}`;
917
+ return out;
918
+ }
919
+ }
920
+
921
+ const aligned = String(before).replace(/\r\n/g, '\n');
922
+ if (!out.created && parseEnvText(aligned)[name] === secret) {
923
+ // Same key already stored: leave the file (its mtime, its mode) alone.
924
+ out.ok = true;
925
+ out.changed = false;
926
+ out.replaced = true;
927
+ out.mode = previousMode || SECRET_FILE_MODE;
928
+ if (o.apply !== false) {
929
+ env[name] = secret;
930
+ // Applied, and the file carries it: file-sourced, so an env-first reader
931
+ // treats it as the fallback it is (see isFromEnvFile).
932
+ sourcedFrom(env).set(name, secret);
933
+ }
934
+ return out;
935
+ }
936
+
937
+ const { text, replaced } = upsertEnvText(aligned, name, secret);
938
+ const tmp = `${file}.tmp-${process.pid}`;
939
+ try {
940
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: SECRET_DIR_MODE });
941
+ fs.writeFileSync(tmp, text, { encoding: 'utf8', mode: SECRET_FILE_MODE });
942
+ // The rename carries the temp file's 0600 onto the destination, so a file
943
+ // that was group-readable ends up owner-only. Say so rather than tightening
944
+ // a file behind the user's back.
945
+ fs.chmodSync(tmp, SECRET_FILE_MODE);
946
+ fs.renameSync(tmp, file);
947
+ } catch (e) {
948
+ try { fs.unlinkSync(tmp); } catch {}
949
+ out.error = `could not write ${file}: ${e.code || e.message}`;
950
+ return out;
951
+ }
952
+
953
+ out.ok = true;
954
+ out.changed = true;
955
+ out.replaced = replaced;
956
+ out.mode = SECRET_FILE_MODE;
957
+ out.tightened =
958
+ platform.hasPosixModes() && !out.created && previousMode !== 0 && (previousMode & 0o077) !== 0;
959
+ if (o.apply !== false) {
960
+ env[name] = secret;
961
+ // Just written to the file and applied here: file-sourced (see above).
962
+ sourcedFrom(env).set(name, secret);
963
+ }
964
+ return out;
965
+ }
966
+
967
+ /**
968
+ * Delete every definition of `name` from an env file's text, leaving every
969
+ * other line — comments, blanks, unrelated keys, their order, `export `
970
+ * prefixes — byte-identical.
971
+ *
972
+ * Removing a key is NOT the same as storing an empty one: `parseEnvText` reads
973
+ * `NAME=""` back as a present-but-empty variable, so an empty write leaves the
974
+ * old value's line in the file and a stale key can still win later. A remover
975
+ * has to delete the line.
976
+ *
977
+ * Pure, and exported for tests: like `upsertEnvText`, a bug here silently
978
+ * damages a file the user also edits by hand.
979
+ *
980
+ * @returns {{text:string, removed:number, changed:boolean}}
981
+ */
982
+ function removeEnvText(text, name) {
983
+ const src = String(text == null ? '' : text);
984
+ const hadFinalNewline = src === '' ? true : src.endsWith('\n');
985
+ const trailingBlank = src === '' ? false : src.split('\n').slice(-1)[0] === '';
986
+ // Zero lines for an empty source — see upsertEnvText. Here it is defensive
987
+ // rather than observable (a remover on an empty file writes nothing either
988
+ // way), but the two functions must split identically or a later change to one
989
+ // starts disagreeing with the other about what a line is.
990
+ const lines = src === '' ? [] : src.split('\n');
991
+ if (trailingBlank) lines.pop();
992
+
993
+ // Same definition matcher as upsertEnvText, so the two can never disagree
994
+ // about which lines count as this variable.
995
+ const re = new RegExp(`^(\\s*(?:export\\s+)?)${name}\\s*=`);
996
+ const out = [];
997
+ let removed = 0;
998
+ for (const line of lines) {
999
+ if (re.test(line)) {
1000
+ removed += 1; // every definition goes, so duplicates cannot survive
1001
+ continue;
1002
+ }
1003
+ out.push(line);
1004
+ }
1005
+
1006
+ let joined = out.join('\n');
1007
+ if (joined !== '' && (hadFinalNewline || trailingBlank)) joined += '\n';
1008
+ return { text: joined, removed, changed: removed > 0 };
1009
+ }
1010
+
1011
+ /**
1012
+ * Remove one variable from `~/.aegiscode/.env` and from the live environment.
1013
+ *
1014
+ * The counterpart of `setEnvValue`, and the reason a provider key deleted in
1015
+ * the desktop app stops being in force: without it, the key survives in the
1016
+ * shared file and the desktop's own "removed" state disagrees with what the CLI
1017
+ * reads next session.
1018
+ *
1019
+ * A file that never mentioned the name is left untouched — no stray empty
1020
+ * variable, no rewritten mtime.
1021
+ *
1022
+ * @returns {{ok:boolean, file:string, name:string, changed:boolean,
1023
+ * removed:number, mode:number, error:string}}
1024
+ */
1025
+ function clearEnvValue(name, o = {}) {
1026
+ const env = o.env || process.env;
1027
+ const file = o.file || envFileFor(o.dir);
1028
+ const out = {
1029
+ ok: false, file, name: String(name || ''), changed: false, removed: 0,
1030
+ mode: 0, error: '',
1031
+ };
1032
+
1033
+ if (!isWritableName(name)) {
1034
+ out.error = `refusing to clear "${name}" — an env var name is [A-Za-z_][A-Za-z0-9_]*`;
1035
+ return out;
1036
+ }
1037
+
1038
+ let before = '';
1039
+ let missing = false;
1040
+ let previousMode = 0;
1041
+ try {
1042
+ before = fs.readFileSync(file, 'utf8');
1043
+ try {
1044
+ previousMode = fs.statSync(file).mode & 0o777;
1045
+ } catch { /* advisory */ }
1046
+ } catch (e) {
1047
+ if (e && e.code === 'ENOENT') missing = true;
1048
+ else {
1049
+ out.error = `could not read ${file}: ${e.code || e.message}`;
1050
+ return out;
1051
+ }
1052
+ }
1053
+
1054
+ const { text, removed, changed } = missing
1055
+ ? { text: '', removed: 0, changed: false }
1056
+ : removeEnvText(before, name);
1057
+
1058
+ if (!changed) {
1059
+ // Nothing in the file to remove. Still unset the live variable: the caller
1060
+ // asked for the key to stop being used, and a shell export would otherwise
1061
+ // keep serving it for the rest of this process.
1062
+ out.ok = true;
1063
+ out.mode = previousMode || SECRET_FILE_MODE;
1064
+ if (o.apply !== false) delete env[String(name)];
1065
+ return out;
1066
+ }
1067
+
1068
+ const tmp = `${file}.tmp-${process.pid}`;
1069
+ try {
1070
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: SECRET_DIR_MODE });
1071
+ fs.writeFileSync(tmp, text, { encoding: 'utf8', mode: SECRET_FILE_MODE });
1072
+ fs.chmodSync(tmp, SECRET_FILE_MODE);
1073
+ fs.renameSync(tmp, file);
1074
+ } catch (e) {
1075
+ try { fs.unlinkSync(tmp); } catch {}
1076
+ out.error = `could not write ${file}: ${e.code || e.message}`;
1077
+ return out;
1078
+ }
1079
+
1080
+ out.ok = true;
1081
+ out.changed = true;
1082
+ out.removed = removed;
1083
+ out.mode = SECRET_FILE_MODE;
1084
+ if (o.apply !== false) delete env[String(name)];
1085
+ return out;
1086
+ }
1087
+
1088
+ /**
1089
+ * Whether the key a route needs is already stored, and where that answer came
1090
+ * from. Read-only; the caller uses it to decide whether to prompt.
1091
+ *
1092
+ * `inFile` is the distinction that matters for the model picker: a key in the
1093
+ * process environment belongs to the shell that launched this host and is gone
1094
+ * next session (and invisible to the desktop), where a key in the file is the
1095
+ * durable, cross-host one.
1096
+ *
1097
+ * @returns {{name:string, present:boolean, inFile:boolean, source:string}}
1098
+ * `source` — 'shell' | 'file' | 'both' | 'none'
1099
+ */
1100
+ function keyStatus(name, o = {}) {
1101
+ const env = o.env || process.env;
1102
+ const file = o.file || envFileFor(o.dir);
1103
+ const varName = String(name || '');
1104
+ const out = { name: varName, present: false, inFile: false, source: 'none' };
1105
+ if (!isWritableName(varName)) return out;
1106
+
1107
+ const raw = env[varName];
1108
+ const shell = typeof raw === 'string' && raw.trim() !== '';
1109
+ let file_ = false;
1110
+ try {
1111
+ const parsed = parseEnvText(fs.readFileSync(file, 'utf8'));
1112
+ file_ = typeof parsed[varName] === 'string' && parsed[varName].trim() !== '';
1113
+ } catch { /* absent or unreadable is simply "not in the file" */ }
1114
+
1115
+ out.present = shell || file_;
1116
+ out.inFile = file_;
1117
+ out.source = shell && file_ ? 'both' : shell ? 'shell' : file_ ? 'file' : 'none';
1118
+ return out;
1119
+ }
1120
+
1121
+ /**
1122
+ * The env var a model id's key belongs in — the question the model picker asks
1123
+ * to know what to collect, and the reason one key is not collected twice.
1124
+ *
1125
+ * A byok id is `<provider>:<model>` and its key is that provider's variable. A
1126
+ * pooled id (`deepseek`, `anthropic-haiku`, `nexus-brain`, …) is served by the
1127
+ * pool, which holds the provider keys itself, so the credential such a route
1128
+ * needs is the AEGIS ACCOUNT key — one variable, `AEGIS_API_KEY`, however many
1129
+ * providers the picker lists. The Claude Code Pro class is neither: it bills
1130
+ * nobody through AEGIS and reaches no vendor API, so the credential its route
1131
+ * needs is the subscription's own OAuth token — `foreign: true` marks that this
1132
+ * is a `secrets.env` name (`setForeignSecret`/`resolveForeignSecret`), not a
1133
+ * `.env` one (`setEnvValue`/`keyStatus`), so `modelKeyPlan`/`modelKeyQueue`/
1134
+ * `storeModelKey` in cli/src/models.js know which store to read and write.
1135
+ *
1136
+ * @param {string} modelId
1137
+ * @param {string} [cls] 'byok' | 'aegis' | 'pro' | anything else
1138
+ * @returns {{env:string, provider:string, vendor:string, pooled:boolean, foreign?:boolean}}
1139
+ */
1140
+ function keyForModelId(modelId, cls) {
1141
+ const id = String(modelId == null ? '' : modelId).trim();
1142
+ if (String(cls || '').toLowerCase() === 'pro') {
1143
+ return {
1144
+ env: 'CLAUDE_CODE_OAUTH_TOKEN', provider: '', vendor: '', pooled: false, foreign: true,
1145
+ };
1146
+ }
1147
+ const byok = String(cls || '').toLowerCase() === 'byok' || id.includes(':');
1148
+ if (byok && id.includes(':')) {
1149
+ const provider = id.slice(0, id.indexOf(':')).trim();
1150
+ return { env: envVarFor(provider), provider, vendor: provider, pooled: false };
1151
+ }
1152
+ // A pooled id is served by the pool, so the credential the ROUTE needs is the
1153
+ // account key — but the id may still NAME the vendor underneath it
1154
+ // (`deepseek`, `anthropic-haiku`, `openai-gpt4o-mini`). That vendor is what
1155
+ // `vendor` reports, and it is not the same question as `env`: it is the
1156
+ // provider key a user may also want on this machine, which the picker asks
1157
+ // for after the account key. `provider` stays '' for pooled on purpose — the
1158
+ // byok call path reads it as "which provider's settings row to address", and
1159
+ // a pooled row has none.
1160
+ return { env: ACCOUNT_ENV_VAR, provider: '', vendor: providerForModelId(id, cls), pooled: true };
1161
+ }
1162
+
1163
+ /**
1164
+ * Vendors whose slug is a namespace a model id may be spelled under.
1165
+ *
1166
+ * Deliberately a *table* and not a pattern: the derivation below is a claim that
1167
+ * a key for this vendor exists, so an id whose first segment is not on this list
1168
+ * derives NO vendor (and the picker asks only for the account key) rather than
1169
+ * inventing a variable name like `NEXUS_API_KEY` for the pool's own namespace.
1170
+ * The list is the platform's providers as its own BYOK catalog spells them
1171
+ * (aegis1 services/nexus_provider/catalog.py MODEL_CATALOG) plus the ids this
1172
+ * module already re-spells in ALIASES above — keep it in step with that catalog,
1173
+ * not with whatever vendor a user might mention.
1174
+ */
1175
+ const VENDOR_SLUGS = Object.freeze([
1176
+ 'openai',
1177
+ 'anthropic',
1178
+ 'deepseek',
1179
+ 'google',
1180
+ 'gemini',
1181
+ 'groq',
1182
+ 'mistral',
1183
+ 'openrouter',
1184
+ 'together',
1185
+ 'together-ai',
1186
+ 'xai',
1187
+ 'x-ai',
1188
+ 'grok',
1189
+ 'huggingface',
1190
+ 'fireworks',
1191
+ 'voyage-ai',
1192
+ 'azure-openai',
1193
+ ]);
1194
+
1195
+ /** The multi-segment slugs, longest first, so `azure-openai-x` matches the full slug. */
1196
+ const VENDOR_COMPOUNDS = Object.freeze(
1197
+ VENDOR_SLUGS.filter((s) => s.includes('-')).sort((a, b) => b.length - a.length)
1198
+ );
1199
+
1200
+ /**
1201
+ * The vendor a model id names, or '' — `deepseek-flash` → `deepseek`,
1202
+ * `nexus-brain` → '', `deepseek:deepseek-v4-flash` → `deepseek`.
1203
+ *
1204
+ * The one question the picker needs to answer "is there a SECOND key worth
1205
+ * asking for on this row?" A pooled row is billed to the AEGIS account, so its
1206
+ * route needs the account key and nothing else — but when the row is named
1207
+ * after a vendor whose key this machine could hold (`deepseek`), asking for that
1208
+ * key too is what lets the account actually call the model instead of the pool
1209
+ * failing a turn with "no provider key". That is the gap this closes:
1210
+ * aegis-key present, models listed, and every turn still failing because the
1211
+ * vendor key the models route through was never collected.
1212
+ *
1213
+ * @param {string} modelId
1214
+ * @param {string} [cls] unused by the derivation; accepted so a caller can pass
1215
+ * the same (id, cls) pair it passes `keyForModelId` without branching.
1216
+ * @returns {string} the vendor slug, or '' when the id names none this module
1217
+ * knows a variable for.
1218
+ */
1219
+ function providerForModelId(modelId, cls) { // eslint-disable-line no-unused-vars
1220
+ const id = String(modelId == null ? '' : modelId).trim().toLowerCase();
1221
+ if (!id) return '';
1222
+ if (id.includes(':')) return id.slice(0, id.indexOf(':')).trim();
1223
+ for (const slug of VENDOR_COMPOUNDS) {
1224
+ if (id === slug || id.startsWith(slug + '-')) return slug;
1225
+ }
1226
+ const first = id.split('-')[0];
1227
+ return VENDOR_SLUGS.includes(first) ? first : '';
1228
+ }
1229
+
1230
+ module.exports = {
1231
+ ENV_FILE,
1232
+ ALIASES,
1233
+ ACCOUNT_ENV_VAR,
1234
+ SECRET_FILE_MODE,
1235
+ envFileFor,
1236
+ envVarFor,
1237
+ parseEnvText,
1238
+ loadEnvFile,
1239
+ // Provenance of what loadEnvFile put in the environment: a value taken from
1240
+ // the FILE is a fallback, not an explicit export, and the env-first readers
1241
+ // (client/credentials.js) must be able to tell the two apart.
1242
+ isFromEnvFile,
1243
+ providerKeyFromEnv,
1244
+ // The floor a value must clear to be a credential at all, and the predicate
1245
+ // built on it — exported so a host can say WHY a row is keyless instead of
1246
+ // only that it is (see providerKeyFromEnv's `rejected`).
1247
+ MIN_CREDENTIAL_LEN,
1248
+ credentialLooksUsable,
1249
+ // The vendor half of "what key does this model id need": the account key is
1250
+ // the route's credential, this is the provider key underneath it.
1251
+ providerForModelId,
1252
+ VENDOR_SLUGS,
1253
+ isWritableName,
1254
+ quoteEnvValue,
1255
+ upsertEnvText,
1256
+ removeEnvText,
1257
+ setEnvValue,
1258
+ clearEnvValue,
1259
+ keyStatus,
1260
+ keyForModelId,
1261
+ // The split: the second file, the list that decides what may not be loaded,
1262
+ // and the reader a process that genuinely needs a billing token calls.
1263
+ SECRETS_FILE,
1264
+ FOREIGN_SECRET_NAMES,
1265
+ FOREIGN_SECRET_PREFIXES,
1266
+ isForeignSecret,
1267
+ secretEnvFileFor,
1268
+ loadForeignSecrets,
1269
+ foreignSecretValue,
1270
+ // The two the Claude Code Pro class reads/writes through — a value from
1271
+ // every place a user might have the token, and the one writer for the name.
1272
+ resolveForeignSecret,
1273
+ setForeignSecret,
1274
+ splitForeignSecrets,
1275
+ };