aegiscode 7.0.25 → 7.0.27

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.
@@ -1,3 +1,3 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- "use strict";const 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
+ const e=require("node:fs"),t=require("node:path"),r=require("./credentials.js"),n=require("./platform.js"),o=".env",i="secrets.env",s=Object.freeze(["STRIPE_"]),c=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 a(e){const t=String(null==e?"":e).trim();return!!t&&(!!c.includes(t)||s.some((e=>t.startsWith(e))))}const l=384,d=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"}),u="AEGIS_API_KEY";function f(e){return t.join(e||r.aegisHome(),o)}function g(e){return t.join(e||r.aegisHome(),i)}function p(e){const t=String(e||"").trim().toLowerCase();if(!t)return"";const r=t.startsWith("byok:")?t.slice(5).trim():t;if(!r)return"";if(d[r])return d[r];const n=r.toUpperCase().replace(/[^A-Z0-9]+/g,"_").replace(/^_+|_+$/g,"");return n?`${n}_API_KEY`:""}const m=/^[A-Za-z0-9_+/.-]+$/,h=32;function E(e,t,r){let n=r;if(n.startsWith('"')||n.startsWith("'"))return{value:n,i:t};for(;t+1<e.length;){const r=e[t+1],o=r.trim();if(!o||o.startsWith("#")||o.includes("="))break;if(!m.test(o))break;if(!/^[ \t]/.test(r)&&(n.length<h||!m.test(n)))break;n+=o,t+=1}return{value:n,i:t}}function S(e){const t={},r=String(null==e?"":e).split(/\r?\n/);for(let e=0;e<r.length;e++){const n=r[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=E(r,e,n.slice(o+1).trim());let c=s.value;e=s.i;const a=c.startsWith('"')&&c.endsWith('"')&&c.length>=2,l=c.startsWith("'")&&c.endsWith("'")&&c.length>=2;if(a)c=c.slice(1,-1).replace(/\\(["\\])/g,"$1");else if(l)c=c.slice(1,-1);else{const e=c.indexOf(" #");-1!==e&&(c=c.slice(0,e).trim())}t[i]=c}return t}const y=new WeakMap;function _(e){let t=y.get(e);return t||(t=new Map,y.set(e,t)),t}function v(t,r={}){if(!a(t))return"";const n=r.file||g(r.dir);try{const r=S(e.readFileSync(n,"utf8"))[String(t)];return"string"==typeof r?r:""}catch{return""}}function I(r,n){e.mkdirSync(t.dirname(r),{recursive:!0,mode:448});const o=`${r}.tmp-${process.pid}-${Date.now()}`;e.writeFileSync(o,n,{mode:l}),e.renameSync(o,r),e.chmodSync(r,l)}function $(e){return"string"==typeof e&&e.trim().length>=8}function k(e){return"string"==typeof e&&/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)}function A(e){const t=String(e);return""===t?"":/[\s"'#\\]/.test(t)?`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:t}function F(e,t,r){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+)?)${t}\\s*=`),a=[];let l=!1;for(const e of s){const n=c.exec(e);n?l||(a.push(`${n[1]}${t}=${A(r)}`),l=!0):a.push(e)}l||a.push(`${t}=${A(r)}`);let d=a.join("\n");return""!==d&&(o||i)&&(d+="\n"),{text:d,replaced:l}}function O(e,t){const r=String(null==e?"":e),n=""===r||r.endsWith("\n"),o=""!==r&&""===r.split("\n").slice(-1)[0],i=""===r?[]:r.split("\n");o&&i.pop();const s=new RegExp(`^(\\s*(?:export\\s+)?)${t}\\s*=`),c=[];let a=0;for(const e of i)s.test(e)?a+=1:c.push(e);let l=c.join("\n");return""!==l&&(n||o)&&(l+="\n"),{text:l,removed:a,changed:a>0}}const P=Object.freeze(["openai","anthropic","deepseek","google","gemini","groq","mistral","openrouter","together","together-ai","xai","x-ai","grok","huggingface","fireworks","voyage-ai","azure-openai"]),T=Object.freeze(P.filter((e=>e.includes("-"))).sort(((e,t)=>t.length-e.length)));function R(e,t){const r=String(null==e?"":e).trim().toLowerCase();if(!r)return"";if(r.includes(":"))return r.slice(0,r.indexOf(":")).trim();for(const e of T)if(r===e||r.startsWith(e+"-"))return e;const n=r.split("-")[0];return P.includes(n)?n:""}module.exports={ENV_FILE:o,ALIASES:d,ACCOUNT_ENV_VAR:u,SECRET_FILE_MODE:l,envFileFor:f,envVarFor:p,parseEnvText:S,loadEnvFile:function(t={}){const r=t.env||process.env,o=t.file||f(t.dir),i=_(r),s={ok:!1,file:o,loaded:[],kept:[],refused:[],reason:"",loose:!1,mode:0};let c;try{c=e.readFileSync(o,"utf8")}catch(e){return s.reason=e&&"ENOENT"===e.code?"absent":"unreadable",s}try{const t=e.statSync(o);s.mode=511&t.mode,s.loose=n.hasPosixModes()&&0!=(63&t.mode)}catch{}const l=S(c);for(const[e,t]of Object.entries(l))a(e)?s.refused.push(e):void 0===r[e]||""===r[e]?(r[e]=t,i.set(e,t),s.loaded.push(e)):s.kept.push(e);return s.ok=!0,s},isFromEnvFile:function(e,t,r={}){const n=r.env||process.env,o=y.get(n);return!(!o||!o.has(e)||void 0!==t&&o.get(e)!==String(t))},providerKeyFromEnv:function(e,t){const r=p(e);if(!r)return{key:"",env:"",rejected:null};const n=(t||process.env)[r],o="string"==typeof n?n.trim():"";return""===o?{key:"",env:r,rejected:null}:$(o)?{key:o,env:r,rejected:null}:{key:"",env:r,rejected:`${r} holds ${o.length} character${1===o.length?"":"s"}, which cannot be a credential`}},MIN_CREDENTIAL_LEN:8,credentialLooksUsable:$,providerForModelId:R,VENDOR_SLUGS:P,isWritableName:k,quoteEnvValue:A,upsertEnvText:F,removeEnvText:O,setEnvValue:function(r,s,c={}){const d=c.env||process.env,u=c.file||f(c.dir),g={ok:!1,file:u,name:String(r||""),changed:!1,created:!1,replaced:!1,mode:0,tightened:!1,error:""};if(!k(r))return g.error=`refusing to write "${r}" — an env var name is [A-Za-z_][A-Za-z0-9_]*`,g;if(a(r))return g.error=`refusing to write ${r} to ${o} — it is a production secret, not a host key; put it in ${i} (or use loadForeignSecrets)`,g;const p=String(null==s?"":s).trim();if(!p)return g.error=`refusing to write an empty ${r}`,g;if(/[\r\n]/.test(String(s)))return g.error=`refusing to write ${r} — the value contains a line break`,g;let m="",h=0;g.created=!0;try{m=e.readFileSync(u,"utf8"),g.created=!1;try{h=511&e.statSync(u).mode}catch{}}catch(e){if(e&&"ENOENT"!==e.code)return g.error=`could not read ${u}: ${e.code||e.message}`,g}const E=String(m).replace(/\r\n/g,"\n");if(!g.created&&S(E)[r]===p)return g.ok=!0,g.changed=!1,g.replaced=!0,g.mode=h||l,!1!==c.apply&&(d[r]=p,_(d).set(r,p)),g;const{text:y,replaced:v}=F(E,r,p),I=`${u}.tmp-${process.pid}`;try{e.mkdirSync(t.dirname(u),{recursive:!0,mode:448}),e.writeFileSync(I,y,{encoding:"utf8",mode:l}),e.chmodSync(I,l),e.renameSync(I,u)}catch(t){try{e.unlinkSync(I)}catch{}return g.error=`could not write ${u}: ${t.code||t.message}`,g}return g.ok=!0,g.changed=!0,g.replaced=v,g.mode=l,g.tightened=n.hasPosixModes()&&!g.created&&0!==h&&0!=(63&h),!1!==c.apply&&(d[r]=p,_(d).set(r,p)),g},clearEnvValue:function(r,n={}){const o=n.env||process.env,i=n.file||f(n.dir),s={ok:!1,file:i,name:String(r||""),changed:!1,removed:0,mode:0,error:""};if(!k(r))return s.error=`refusing to clear "${r}" — an env var name is [A-Za-z_][A-Za-z0-9_]*`,s;let c="",a=!1,d=0;try{c=e.readFileSync(i,"utf8");try{d=511&e.statSync(i).mode}catch{}}catch(e){if(!e||"ENOENT"!==e.code)return s.error=`could not read ${i}: ${e.code||e.message}`,s;a=!0}const{text:u,removed:g,changed:p}=a?{text:"",removed:0,changed:!1}:O(c,r);if(!p)return s.ok=!0,s.mode=d||l,!1!==n.apply&&delete o[String(r)],s;const m=`${i}.tmp-${process.pid}`;try{e.mkdirSync(t.dirname(i),{recursive:!0,mode:448}),e.writeFileSync(m,u,{encoding:"utf8",mode:l}),e.chmodSync(m,l),e.renameSync(m,i)}catch(t){try{e.unlinkSync(m)}catch{}return s.error=`could not write ${i}: ${t.code||t.message}`,s}return s.ok=!0,s.changed=!0,s.removed=g,s.mode=l,!1!==n.apply&&delete o[String(r)],s},keyStatus:function(t,r={}){const n=r.env||process.env,o=r.file||f(r.dir),i=String(t||""),s={name:i,present:!1,inFile:!1,source:"none"};if(!k(i))return s;const c=n[i],a="string"==typeof c&&""!==c.trim();let l=!1;try{const t=S(e.readFileSync(o,"utf8"));l="string"==typeof t[i]&&""!==t[i].trim()}catch{}return s.present=a||l,s.inFile=l,s.source=a&&l?"both":a?"shell":l?"file":"none",s},keyForModelId:function(e,t){const r=String(null==e?"":e).trim();if("pro"===String(t||"").toLowerCase())return{env:"CLAUDE_CODE_OAUTH_TOKEN",provider:"",vendor:"",pooled:!1,foreign:!0};if(("byok"===String(t||"").toLowerCase()||r.includes(":"))&&r.includes(":")){const e=r.slice(0,r.indexOf(":")).trim();return{env:p(e),provider:e,vendor:e,pooled:!1}}return{env:u,provider:"",vendor:R(r),pooled:!0}},SECRETS_FILE:i,FOREIGN_SECRET_NAMES:c,FOREIGN_SECRET_PREFIXES:s,isForeignSecret:a,secretEnvFileFor:g,loadForeignSecrets:function(t={}){const r=t.env||process.env,o=t.file||g(t.dir),i={ok:!1,file:o,loaded:[],reason:"",mode:0,loose:!1},s=Array.isArray(t.only)&&t.only.length?t.only.filter(a):null;let c;try{c=e.readFileSync(o,"utf8")}catch(e){return i.reason=e&&"ENOENT"===e.code?"absent":"unreadable",i}try{const t=e.statSync(o);i.mode=511&t.mode,i.loose=n.hasPosixModes()&&0!=(63&t.mode)}catch{}const l=S(c);for(const[e,t]of Object.entries(l))s&&!s.includes(e)||(r[e]=t,i.loaded.push(e));return i.ok=!0,i},foreignSecretValue:v,resolveForeignSecret:function(t,r={}){if(!a(t))return"";const n=r.env||process.env,o=n&&n[t];if("string"==typeof o&&o.trim())return o.trim();const i=v(t,r);if(i&&i.trim())return i.trim();try{const n=S(e.readFileSync(f(r.dir),"utf8"))[String(t)];return"string"==typeof n?n.trim():""}catch{return""}},setForeignSecret:function(t,r,s={}){const c=s.file||g(s.dir),d={ok:!1,file:c,name:String(t||""),changed:!1,created:!1,replaced:!1,mode:0,tightened:!1,error:""};if(!k(t))return d.error=`refusing to write "${t}" — an env var name is [A-Za-z_][A-Za-z0-9_]*`,d;if(!a(t))return d.error=`refusing to write ${t} to ${i} — it is a host credential, not a foreign secret; use setEnvValue (${o}) instead`,d;const u=String(null==r?"":r).trim();if(!u)return d.error=`refusing to write an empty ${t}`,d;if(/[\r\n]/.test(String(r)))return d.error=`refusing to write ${t} — the value contains a line break`,d;let f="",p=0;d.created=!0;try{f=e.readFileSync(c,"utf8"),d.created=!1;try{p=511&e.statSync(c).mode}catch{}}catch(e){if(e&&"ENOENT"!==e.code)return d.error=`could not read ${c}: ${e.code||e.message}`,d}const m=String(f).replace(/\r\n/g,"\n");if(!d.created&&S(m)[t]===u)return d.ok=!0,d.changed=!1,d.replaced=!0,d.mode=p||l,d;const{text:h,replaced:E}=F(m,t,u);try{I(c,h)}catch(e){return d.error=`could not write ${c}: ${e.code||e.message}`,d}return d.ok=!0,d.changed=!0,d.replaced=E,d.mode=l,d.tightened=n.hasPosixModes()&&!d.created&&0!==p&&0!=(63&p),d},splitForeignSecrets:function(t={}){const r=t.env||process.env,n=t.file||f(t.dir),o=t.secretsFile||g(t.dir),i=!0===t.apply,s={ok:!1,moved:[],kept:[],envFile:n,secretsFile:o,apply:i};let c;try{c=e.readFileSync(n,"utf8")}catch(e){return s.reason=e&&"ENOENT"===e.code?"absent":"unreadable",s}const l=S(c),d=Object.keys(l).filter(a).sort();if(!d.length)return s.ok=!0,s;let u="";try{u=e.readFileSync(o,"utf8")}catch{}const p=S(u);for(const e of d)Object.prototype.hasOwnProperty.call(p,e)?s.kept.push(e):(u=F(u,e,l[e]).text,s.moved.push(e));if(i){for(const e of d)c=O(c,e).text;s.moved.length&&I(o,u),I(n,c);for(const e of d)r[e]===l[e]&&delete r[e]}else s.moved.length&&(s.secretsFile=o);return s.ok=!0,s}};
@@ -1,3 +1,3 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- "use strict";const GENERIC_TITLE="New conversation",TITLE_SYSTEM='You name conversations. Write a short descriptive title (2 to 6 words) that captures the topic of the conversation. Never repeat the user\'s words verbatim — if the message is just a greeting or has no clear topic, name it something like "New conversation". Sentence case, no quotes, no markdown, no trailing punctuation, no explanation.',isGenericTitle=e=>!e||String(e).trim().toLowerCase()===GENERIC_TITLE.toLowerCase(),GREETINGS=new Set(["hey","heey","heyy","heyyy","hi","hii","hello","hej","hejj","yo","sup","hola","howdy","hai","heyo","hiya","wassup","greetings","namaste","ahoy","hallo"]);function isTopicless(e){const t=String(e).trim().toLowerCase().replace(/[^a-z0-9\s]/g," ").replace(/\s+/g," ").trim();if(!t)return!0;const i=t.split(" ");return!!/^(good (morning|afternoon|evening)|whats up|wassup|hey there|hello there|hi there|how are you)\b/.test(t)||i.length<=2&&t.length<=12&&GREETINGS.has(i[0])}function looksLikeEcho(e,t){const i=e=>String(e).toLowerCase().replace(/[^a-z0-9\s]/g,"").replace(/\s+/g," ").trim(),n=i(e),o=i(t);if(!n||!o)return!1;if(n===o)return!0;if(o.length<=14&&(n.startsWith(o)||o.startsWith(n)))return!0;if(o.length<=24){const i=e=>new Set((String(e).toLowerCase().match(/[a-z0-9]+/g)||[]).filter((e=>!ECHO_STOP.has(e)))),n=i(e),o=i(t);if(n.size&&n.size===o.size&&[...n].every((e=>o.has(e))))return!0}return!1}const ECHO_STOP=new Set(["the","a","an","to","of","in","on","at","for","and","or","is","are","be","it","its","my","our","please","can","you","just","do","that","this"]);function cleanTitle(e){return String(null==e?"":e).replace(/\s+/g," ").trim().replace(/["'`“”‘’]/g,"").replace(/[*_#]/g,"").replace(/^\s*(?:title|name)\s*[:\-–]\s*/i,"").replace(/[.\s]+$/g,"").slice(0,60).trim()}const titlePromptOf=e=>`Write a short title for a conversation that begins with: "${String(e).slice(0,500)}"`,FILLER=/^(?:please|pls|plz|hey|hi|hello|ok(?:ay)?|so|now|just|also|and|then|maybe|well|um|uh|can you|could you|would you|will you|i want you to|i want to|i need you to|i need to|i'?d like you to|i would like you to|i'?d like to|help me|help|let'?s|lets|go ahead and)\b[\s,:;-]*/i,TRAILING_STOP=new Set(["the","a","an","in","on","at","to","for","of","and","or","with","is","are","my","our","this","that","please","can","you","could","would","i","we","just","do","it"]);function deriveTitle(e){let t=String(null==e?"":e).trim().replace(/\s+/g," ");if(!t)return GENERIC_TITLE;for(let e=0;e<6;e++){const e=t.replace(FILLER,"").trim();if(e===t)break;t=e}const i=t.split(" ").filter(Boolean);if(!i.length)return GENERIC_TITLE;const n=i.slice(0,6);for(;n.length>2&&TRAILING_STOP.has(n[n.length-1].toLowerCase().replace(/[^a-z0-9]/g,""));)n.pop();let o=n.join(" ").replace(/[.,!?;:]+$/,"").trim();return o?(o=o[0].toUpperCase()+o.slice(1),o.slice(0,60).trim()||GENERIC_TITLE):GENERIC_TITLE}async function nameConversation(e,{callModel:t,signal:i}={}){const n=null==e?"":String(e);if(!n.trim())return"";if(isTopicless(n))return GENERIC_TITLE;if(!("function"!=typeof t||i&&i.aborted)){let e=null;try{e=await t(titlePromptOf(n),{system:TITLE_SYSTEM,signal:i,naming:!0})}catch{e=null}const o=cleanTitle(e);if(o)return looksLikeEcho(o,n)?GENERIC_TITLE:o}return deriveTitle(n)}async function refineTitle(e,t,i={}){const n=i&&!0===i.named,o=i&&!0===i.seeded;if(n)return null;if(!o&&!isGenericTitle(e))return null;if(!String(t||"").trim()||isTopicless(t))return null;const r=cleanTitle(await nameConversation(t,i));return!r||isGenericTitle(r)?null:r}async function nameSession(e,t,i,n,o={}){if(!e||"function"!=typeof e.setTitle)return null;if(!i)return null;const r="function"==typeof e.getSession?e.getSession(t,i):null,s=r&&r.title,l={...o,seeded:!(!r||r.named)},a=await refineTitle(s,n,l);if(a){try{e.setTitle(t,i,a,{named:!0})}catch{return null}return a}if(isTopicless(n)&&r&&!r.named&&!isGenericTitle(s)){try{e.setTitle(t,i,GENERIC_TITLE)}catch{return null}return GENERIC_TITLE}return null}module.exports={GENERIC_TITLE:GENERIC_TITLE,TITLE_SYSTEM:TITLE_SYSTEM,isGenericTitle:isGenericTitle,isTopicless:isTopicless,looksLikeEcho:looksLikeEcho,cleanTitle:cleanTitle,titlePromptOf:titlePromptOf,deriveTitle:deriveTitle,nameConversation:nameConversation,refineTitle:refineTitle,nameSession:nameSession};
3
+ const e="New conversation",t='You name conversations. Write a short descriptive title (2 to 6 words) that captures the topic of the conversation. Never repeat the user\'s words verbatim — if the message is just a greeting or has no clear topic, name it something like "New conversation". Sentence case, no quotes, no markdown, no trailing punctuation, no explanation.',n=t=>!t||String(t).trim().toLowerCase()===e.toLowerCase(),i=new Set(["hey","heey","heyy","heyyy","hi","hii","hello","hej","hejj","yo","sup","hola","howdy","hai","heyo","hiya","wassup","greetings","namaste","ahoy","hallo"]);function o(e){const t=String(e).trim().toLowerCase().replace(/[^a-z0-9\s]/g," ").replace(/\s+/g," ").trim();if(!t)return!0;const n=t.split(" ");return!!/^(good (morning|afternoon|evening)|whats up|wassup|hey there|hello there|hi there|how are you)\b/.test(t)||n.length<=2&&t.length<=12&&i.has(n[0])}function r(e,t){const n=e=>String(e).toLowerCase().replace(/[^a-z0-9\s]/g,"").replace(/\s+/g," ").trim(),i=n(e),o=n(t);if(!i||!o)return!1;if(i===o)return!0;if(o.length<=14&&(i.startsWith(o)||o.startsWith(i)))return!0;if(o.length<=24){const n=e=>new Set((String(e).toLowerCase().match(/[a-z0-9]+/g)||[]).filter((e=>!s.has(e)))),i=n(e),o=n(t);if(i.size&&i.size===o.size&&[...i].every((e=>o.has(e))))return!0}return!1}const s=new Set(["the","a","an","to","of","in","on","at","for","and","or","is","are","be","it","its","my","our","please","can","you","just","do","that","this"]);function a(e){return String(null==e?"":e).replace(/\s+/g," ").trim().replace(/["'`“”‘’]/g,"").replace(/[*_#]/g,"").replace(/^\s*(?:title|name)\s*[:\-–]\s*/i,"").replace(/[.\s]+$/g,"").slice(0,60).trim()}const l=e=>`Write a short title for a conversation that begins with: "${String(e).slice(0,500)}"`,u=/^(?:please|pls|plz|hey|hi|hello|ok(?:ay)?|so|now|just|also|and|then|maybe|well|um|uh|can you|could you|would you|will you|i want you to|i want to|i need you to|i need to|i'?d like you to|i would like you to|i'?d like to|help me|help|let'?s|lets|go ahead and)\b[\s,:;-]*/i,c=new Set(["the","a","an","in","on","at","to","for","of","and","or","with","is","are","my","our","this","that","please","can","you","could","would","i","we","just","do","it"]);function h(t){let n=String(null==t?"":t).trim().replace(/\s+/g," ");if(!n)return e;for(let e=0;e<6;e++){const e=n.replace(u,"").trim();if(e===n)break;n=e}const i=n.split(" ").filter(Boolean);if(!i.length)return e;const o=i.slice(0,6);for(;o.length>2&&c.has(o[o.length-1].toLowerCase().replace(/[^a-z0-9]/g,""));)o.pop();let r=o.join(" ").replace(/[.,!?;:]+$/,"").trim();return r?(r=r[0].toUpperCase()+r.slice(1),r.slice(0,60).trim()||e):e}async function f(n,{callModel:i,signal:s}={}){const u=null==n?"":String(n);if(!u.trim())return"";if(o(u))return e;if(!("function"!=typeof i||s&&s.aborted)){let n=null;try{n=await i(l(u),{system:t,signal:s,naming:!0})}catch{n=null}const o=a(n);if(o)return r(o,u)?e:o}return h(u)}async function g(e,t,i={}){const r=i&&!0===i.named,s=i&&!0===i.seeded;if(r)return null;if(!s&&!n(e))return null;if(!String(t||"").trim()||o(t))return null;const l=a(await f(t,i));return!l||n(l)?null:l}module.exports={GENERIC_TITLE:e,TITLE_SYSTEM:t,isGenericTitle:n,isTopicless:o,looksLikeEcho:r,cleanTitle:a,titlePromptOf:l,deriveTitle:h,nameConversation:f,refineTitle:g,nameSession:async function(t,i,r,s,a={}){if(!t||"function"!=typeof t.setTitle)return null;if(!r)return null;const l="function"==typeof t.getSession?t.getSession(i,r):null,u=l&&l.title,c={...a,seeded:!(!l||l.named)},h=await g(u,s,c);if(h){try{t.setTitle(i,r,h,{named:!0})}catch{return null}return h}if(o(s)&&l&&!l.named&&!n(u)){try{t.setTitle(i,r,e)}catch{return null}return e}return null}};
@@ -1,3 +1,3 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- "use strict";const fs=require("node:fs"),os=require("node:os"),path=require("node:path"),{spawnSync:spawnSync}=require("node:child_process"),IS_WIN32="win32"===process.platform,DEFAULT_PATHEXT=".COM;.EXE;.BAT;.CMD";function defaultExists(e){try{return fs.statSync(e).isFile()}catch{return!1}}function defaultProbe(e,t=[],r={}){try{const n=spawnSync(e,t,{encoding:"utf8",timeout:r.timeout||5e3,windowsHide:!0,env:r.env});return n.error||0!==n.status?null:"string"==typeof n.stdout?n.stdout:""}catch{return null}}function defaultDirExists(e){try{return fs.statSync(e).isDirectory()}catch{return!1}}function defaultDirNonEmpty(e){try{return fs.readdirSync(e).length>0}catch{return!1}}function defaultReadText(e){try{return fs.readFileSync(e,"utf8")}catch{return null}}function defaultRun(e,t=[],r={}){try{const n=spawnSync(e,t,{encoding:"utf8",windowsHide:!0,timeout:r.timeout||1e4,env:r.env});if(n.error)return{ok:!1,error:n.error,output:""};if(0!==n.status){const t=String(n.stderr||"").trim();return{ok:!1,error:new Error(`${e} exited ${n.status}${t?`: ${t}`:""}`),status:n.status,output:String(n.stdout||"")}}return{ok:!0,error:null,output:String(n.stdout||"")}}catch(e){return{ok:!1,error:e,output:""}}}function seams(e){const t=e&&"object"==typeof e?e:{},r="string"==typeof t.platform&&t.platform?t.platform:process.platform;return{o:t,platform:r,env:t.env&&"object"==typeof t.env?t.env:process.env,win32:"win32"===r,exists:"function"==typeof t.exists?t.exists:defaultExists,probe:"function"==typeof t.probe?t.probe:defaultProbe,injectedProbe:"function"==typeof t.probe,kill:"function"==typeof t.kill?t.kill:(...e)=>process.kill(...e),run:"function"==typeof t.run?t.run:defaultRun}}function envValue(e,t,r){if(!e||"object"!=typeof e)return;const n=void 0!==e[t]?e[t]:e[t.toUpperCase()];if(void 0!==n)return n;if("win32"!==r)return;const o=t.toLowerCase();for(const t of Object.keys(e))if(t.toLowerCase()===o)return e[t]}function pathEntries(e,t,r,n){const o=String(envValue(e,"PATH",t)||"").split("win32"===t?";":":"),s=[];for(const e of o){const t=e.trim().replace(/^"|"$/g,"");t&&s.push(n.isAbsolute(t)?t:n.join(r,t))}return s}function extList(e,t){const r=String(envValue(e,"PATHEXT",t)||DEFAULT_PATHEXT).split(";").map((e=>e.trim())).filter(Boolean).map((e=>e.startsWith(".")?e:`.${e}`));return r.length?r:DEFAULT_PATHEXT.split(";")}function resolveExecutable(e,t={}){const{platform:r,env:n,exists:o,win32:s,o:i}=seams(t);if("string"!=typeof e||!e.trim())return null;const a=e.trim(),l="string"==typeof i.cwd&&i.cwd?i.cwd:process.cwd(),u=s?path.win32:path;if(s?a.includes("/")||a.includes("\\")||/^[a-zA-Z]:/.test(a):a.includes("/")){const e=u.isAbsolute(a)?a:u.join(l,a);return o(e)?e:null}const c=s?["",...extList(n,r)]:[""];for(const e of pathEntries(n,r,l,u))for(const t of c){const r=u.join(e,a+t);if(o(r))return r}return null}function shellSpec(e={}){const{platform:t,env:r,win32:n}=seams(e);return n?{cmd:envValue(r,"ComSpec",t)||envValue(r,"COMSPEC",t)||"cmd.exe",arg:"/d /s /c",kind:"cmd"}:{cmd:envValue(r,"SHELL",t)||"/bin/sh",arg:"-c",kind:"posix"}}function killTree(e,t={}){const{platform:r,env:n,win32:o,kill:s,run:i,o:a}=seams(t),l="number"==typeof e?e:e&&e.pid,u=a.signal||"SIGTERM",c=!1!==a.detached,f=a.timeout||1e4;if(!Number.isInteger(l)||l<=0)return{ok:!1,method:"none",pid:Number.isInteger(l)?l:null,error:new Error(`killTree: no usable pid (got ${JSON.stringify(e&&e.pid)})`),gone:!1};if(o){const e=i("taskkill",["/PID",String(l),"/T","/F"],{env:n,platform:r,timeout:f})||{};return!1===e.ok?{ok:!1,method:"taskkill",pid:l,error:e.error||new Error("taskkill failed"),gone:!1}:{ok:!0,method:"taskkill",pid:l,error:null,gone:!1}}let p=null;if(c)try{return s(-l,u),{ok:!0,method:"group",pid:l,error:null,gone:!1}}catch(e){p=e;const t=e&&e.code;if("ESRCH"!==t&&"EPERM"!==t)return{ok:!1,method:"group",pid:l,error:e,gone:!1}}try{return s(l,u),{ok:!0,method:"signal",pid:l,error:null,groupError:p,gone:!1}}catch(e){return{ok:!1,method:"signal",pid:l,error:e,groupError:p,gone:"ESRCH"===(e&&e.code)}}}function isAlive(e,t={}){const{platform:r,env:n,win32:o,probe:s,kill:i}=seams(t),a="number"==typeof e?e:Number(e);if(!Number.isInteger(a)||a<=0)return!1;if(o){const e=s("tasklist",["/FI",`PID eq ${a}`,"/NH","/FO","CSV"],{env:n,platform:r});if(null==e)return!1;const t=String(e).trim();return!!t&&new RegExp(`(^|[^0-9])${a}([^0-9]|$)`).test(t)}try{return i(a,0),!0}catch(e){return Boolean(e&&"EPERM"===e.code)}}function hasDisplay(e={}){const{platform:t,env:r,win32:n,probe:o,injectedProbe:s}=seams(e);return!!(n||"darwin"===t||envValue(r,"DISPLAY",t)||envValue(r,"WAYLAND_DISPLAY",t)||s&&null!==o("xdpyinfo",[],{env:r,platform:t}))}function normalizeLocale(e){if(null==e)return"";const t=String(e).trim();if(!t)return"";const r=t.split("@")[0].split(".")[0];if(/^(c|posix)$/i.test(r))return"";const n=/^([A-Za-z]{2,3})(?:[_-]([A-Za-z0-9]{2,8}))?$/.exec(r);if(!n)return"";const o=n[1].toLowerCase();return"c"===o||"posix"===o?"":n[2]?`${o}-${n[2].toUpperCase()}`:o}function appLocale(e={}){const{platform:t,env:r,o:n}=seams(e);if("string"==typeof n.locale)return normalizeLocale(n.locale);const o=n.env&&"object"==typeof n.env;for(const e of["LC_ALL","LC_CTYPE","LC_MESSAGES","LANG"]){const n=normalizeLocale(envValue(r,e,t));if(n)return n}const s=String(envValue(r,"LANGUAGE",t)||"");if(s)for(const e of s.split(":")){const t=normalizeLocale(e);if(t)return t}if(o)return"";try{return normalizeLocale((new Intl.DateTimeFormat).resolvedOptions().locale)}catch{return""}}function languageName(e,t={}){const{o:r}=seams(t);if("string"==typeof r.languageName)return r.languageName;const n=normalizeLocale(e);if(!n)return"";const o=n.split("-")[0];try{return new Intl.DisplayNames(["en"],{type:"language"}).of(o)||""}catch{return""}}function homeDir(e={}){const{platform:t,env:r,o:n}=seams(e);if("string"==typeof n.home)return n.home.trim();const o="win32"===t?["USERPROFILE","HOME"]:["HOME","USERPROFILE"];for(const e of o){const n=envValue(r,e,t);if(n&&String(n).trim())return String(n).trim()}try{return os.homedir()||""}catch{return""}}function hasPosixModes(e={}){const{win32:t}=seams(e);return!t}function winShellFolderDesktop(e,t){const r=e("reg",["query","HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders","/v","Desktop"]);if(!r)return"";const n=/^\s*Desktop\s+REG_(?:EXPAND_)?SZ\s+(.+)$/im.exec(r),o=n&&n[1].trim();return o&&t(o)?o:""}function desktopDir(e={}){const{platform:t,env:r,win32:n,probe:o,o:s}=seams(e),i=n?path.win32:path.posix,a=homeDir(e),l="function"==typeof s.dirExists?s.dirExists:defaultDirExists,u="function"==typeof s.dirNonEmpty?s.dirNonEmpty:defaultDirNonEmpty;if(n){const e=winShellFolderDesktop(o,l);if(e)return e}const c="function"==typeof s.readText?s.readText:defaultReadText,f=[],p=e=>{e&&String(e).trim()&&f.push(String(e).trim())};if(n){const e=envValue(r,"OneDrive",t)||envValue(r,"OneDriveConsumer",t);e&&p(i.join(e,"Desktop")),a&&p(i.join(a,"OneDrive","Desktop")),a&&p(i.join(a,"Desktop"));const n=a?i.join(a,"Desktop"):"",o=f.indexOf(n);o>0&&l(n)&&u(n)&&f.slice(0,o).every((e=>!l(e)||!u(e)))&&(f.splice(o,1),f.unshift(n))}else if("darwin"===t)a&&p(i.join(a,"Desktop"));else{if(p(envValue(r,"XDG_DESKTOP_DIR",t)),a){const e=c(i.join(a,".config","user-dirs.dirs")),t=e&&/^\s*XDG_DESKTOP_DIR\s*=\s*"?([^"\n]+)"?\s*$/m.exec(e);t&&p(t[1].replace(/\$HOME\b|\${HOME}/g,a))}a&&p(i.join(a,"Desktop"))}for(const e of f)if(l(e))return e;return a&&(n||"darwin"===t)?i.join(a,"Desktop"):""}function applyDesktopAlias(e,{home:t,desktopdir:r,win32:n,P:o}){if(!t||!r)return e;const s=o.join(t,"Desktop"),i=e=>n?e.toLowerCase():e;if(i(s)===i(r))return e;if(i(e)===i(s))return r;const a=s+o.sep;return i(e).startsWith(i(a))?r+o.sep+e.slice(a.length):e}const WIN_DRIVE_RE=/^[A-Za-z]:[\\/]/,WIN_BARE_DRIVE_RE=/^[A-Za-z]:$/,WIN_UNC_RE=/^\\\\[^\\?.]/;function resolvePath(e,t={}){const{platform:r,win32:n,o:o}=seams(t),s=n?path.win32:path.posix,i=e=>({ok:!1,path:null,error:e,expandedHome:!1});if("string"!=typeof e||!e.trim())return i(`a path is required (got ${JSON.stringify(e)})`);const a=e.trim();let l=a,u=!1;if("~"===a||a.startsWith("~/")||n&&a.startsWith("~\\")){const e=homeDir(t);if(!e)return i(`cannot expand "~" in ${JSON.stringify(a)}: this machine reports no home directory. Pass a full absolute path instead.`);l="~"===a?e:s.join(e,a.slice(2)),u=!0}else if(a.startsWith("~"))return i(`${JSON.stringify(a)} names another user's home directory, which cannot be resolved from here. Use "~" for this user, or pass a full absolute path.`);if(l=applyDesktopAlias(l,{home:homeDir(t),desktopdir:o.desktopdir,win32:n,P:s}),!u){const e=homeDir(t),o=e?` This machine's home directory is ${e}.`:"";if(n){if((l.startsWith("/")||l.startsWith("\\"))&&!WIN_UNC_RE.test(l))return i(`${JSON.stringify(a)} is not an absolute path on this machine, which runs ${r}. A leading slash here means "the root of the current drive", so writing to it would silently land somewhere other than where you meant. Use a drive-qualified path (C:\\Users\\you\\Desktop\\file.txt) or "~/…".${o}`)}else if(WIN_DRIVE_RE.test(l)||WIN_BARE_DRIVE_RE.test(l)||WIN_UNC_RE.test(l))return i(`${JSON.stringify(a)} is a Windows path, but this machine runs ${r}. Use a posix path (/home/you/file.txt) or "~/…".${o}`)}const c="string"==typeof o.cwd&&o.cwd.trim()?o.cwd.trim():process.cwd(),f=s.isAbsolute(l)?s.resolve(l):s.resolve(c,l);return s.isAbsolute(f)?{ok:!0,path:f,error:null,expandedHome:u}:i(`${JSON.stringify(a)} is relative and the working directory (${JSON.stringify(c)}) is not absolute, so it cannot be resolved. Pass an absolute path.`)}function baseName(e){if("string"!=typeof e)return"";const t=e.trim().replace(/[/\\]+$/,"");if(!t)return"";if(/^[A-Za-z]:$/.test(t))return"";const r=Math.max(t.lastIndexOf("/"),t.lastIndexOf("\\"));return-1===r?t:t.slice(r+1)}const api={IS_WIN32:IS_WIN32,seams:seams,resolveExecutable:resolveExecutable,shellSpec:shellSpec,killTree:killTree,isAlive:isAlive,hasDisplay:hasDisplay,homeDir:homeDir,desktopDir:desktopDir,resolvePath:resolvePath,baseName:baseName,hasPosixModes:hasPosixModes,appLocale:appLocale,languageName:languageName,normalizeLocale:normalizeLocale};module.exports=api;
3
+ const t=require("node:fs"),e=require("node:os"),r=require("node:path"),{spawnSync:n}=require("node:child_process"),o="win32"===process.platform,i=".COM;.EXE;.BAT;.CMD";function s(e){try{return t.statSync(e).isFile()}catch{return!1}}function u(t,e=[],r={}){try{const o=n(t,e,{encoding:"utf8",timeout:r.timeout||5e3,windowsHide:!0,env:r.env});return o.error||0!==o.status?null:"string"==typeof o.stdout?o.stdout:""}catch{return null}}function c(e){try{return t.statSync(e).isDirectory()}catch{return!1}}function l(e){try{return t.readdirSync(e).length>0}catch{return!1}}function f(e){try{return t.readFileSync(e,"utf8")}catch{return null}}function a(t,e=[],r={}){try{const o=n(t,e,{encoding:"utf8",windowsHide:!0,timeout:r.timeout||1e4,env:r.env});if(o.error)return{ok:!1,error:o.error,output:""};if(0!==o.status){const e=String(o.stderr||"").trim();return{ok:!1,error:new Error(`${t} exited ${o.status}${e?`: ${e}`:""}`),status:o.status,output:String(o.stdout||"")}}return{ok:!0,error:null,output:String(o.stdout||"")}}catch(t){return{ok:!1,error:t,output:""}}}function p(t){const e=t&&"object"==typeof t?t:{},r="string"==typeof e.platform&&e.platform?e.platform:process.platform;return{o:e,platform:r,env:e.env&&"object"==typeof e.env?e.env:process.env,win32:"win32"===r,exists:"function"==typeof e.exists?e.exists:s,probe:"function"==typeof e.probe?e.probe:u,injectedProbe:"function"==typeof e.probe,kill:"function"==typeof e.kill?e.kill:(...t)=>process.kill(...t),run:"function"==typeof e.run?e.run:a}}function d(t,e,r){if(!t||"object"!=typeof t)return;const n=void 0!==t[e]?t[e]:t[e.toUpperCase()];if(void 0!==n)return n;if("win32"!==r)return;const o=e.toLowerCase();for(const e of Object.keys(t))if(e.toLowerCase()===o)return t[e]}function m(t,e){const r=String(d(t,"PATHEXT",e)||i).split(";").map((t=>t.trim())).filter(Boolean).map((t=>t.startsWith(".")?t:`.${t}`));return r.length?r:i.split(";")}function h(t){if(null==t)return"";const e=String(t).trim();if(!e)return"";const r=e.split("@")[0].split(".")[0];if(/^(c|posix)$/i.test(r))return"";const n=/^([A-Za-z]{2,3})(?:[_-]([A-Za-z0-9]{2,8}))?$/.exec(r);if(!n)return"";const o=n[1].toLowerCase();return"c"===o||"posix"===o?"":n[2]?`${o}-${n[2].toUpperCase()}`:o}function g(t={}){const{platform:r,env:n,o:o}=p(t);if("string"==typeof o.home)return o.home.trim();const i="win32"===r?["USERPROFILE","HOME"]:["HOME","USERPROFILE"];for(const t of i){const e=d(n,t,r);if(e&&String(e).trim())return String(e).trim()}try{return e.homedir()||""}catch{return""}}const y=/^[A-Za-z]:[\\/]/,w=/^[A-Za-z]:$/,k=/^\\\\[^\\?.]/,S={IS_WIN32:o,seams:p,resolveExecutable:function(t,e={}){const{platform:n,env:o,exists:i,win32:s,o:u}=p(e);if("string"!=typeof t||!t.trim())return null;const c=t.trim(),l="string"==typeof u.cwd&&u.cwd?u.cwd:process.cwd(),f=s?r.win32:r;if(s?c.includes("/")||c.includes("\\")||/^[a-zA-Z]:/.test(c):c.includes("/")){const t=f.isAbsolute(c)?c:f.join(l,c);return i(t)?t:null}const a=s?["",...m(o,n)]:[""];for(const t of function(t,e,r,n){const o=String(d(t,"PATH",e)||"").split("win32"===e?";":":"),i=[];for(const t of o){const e=t.trim().replace(/^"|"$/g,"");e&&i.push(n.isAbsolute(e)?e:n.join(r,e))}return i}(o,n,l,f))for(const e of a){const r=f.join(t,c+e);if(i(r))return r}return null},shellSpec:function(t={}){const{platform:e,env:r,win32:n}=p(t);return n?{cmd:d(r,"ComSpec",e)||d(r,"COMSPEC",e)||"cmd.exe",arg:"/d /s /c",kind:"cmd"}:{cmd:d(r,"SHELL",e)||"/bin/sh",arg:"-c",kind:"posix"}},killTree:function(t,e={}){const{platform:r,env:n,win32:o,kill:i,run:s,o:u}=p(e),c="number"==typeof t?t:t&&t.pid,l=u.signal||"SIGTERM",f=!1!==u.detached,a=u.timeout||1e4;if(!Number.isInteger(c)||c<=0)return{ok:!1,method:"none",pid:Number.isInteger(c)?c:null,error:new Error(`killTree: no usable pid (got ${JSON.stringify(t&&t.pid)})`),gone:!1};if(o){const t=s("taskkill",["/PID",String(c),"/T","/F"],{env:n,platform:r,timeout:a})||{};return!1===t.ok?{ok:!1,method:"taskkill",pid:c,error:t.error||new Error("taskkill failed"),gone:!1}:{ok:!0,method:"taskkill",pid:c,error:null,gone:!1}}let d=null;if(f)try{return i(-c,l),{ok:!0,method:"group",pid:c,error:null,gone:!1}}catch(t){d=t;const e=t&&t.code;if("ESRCH"!==e&&"EPERM"!==e)return{ok:!1,method:"group",pid:c,error:t,gone:!1}}try{return i(c,l),{ok:!0,method:"signal",pid:c,error:null,groupError:d,gone:!1}}catch(t){return{ok:!1,method:"signal",pid:c,error:t,groupError:d,gone:"ESRCH"===(t&&t.code)}}},isAlive:function(t,e={}){const{platform:r,env:n,win32:o,probe:i,kill:s}=p(e),u="number"==typeof t?t:Number(t);if(!Number.isInteger(u)||u<=0)return!1;if(o){const t=i("tasklist",["/FI",`PID eq ${u}`,"/NH","/FO","CSV"],{env:n,platform:r});if(null==t)return!1;const e=String(t).trim();return!!e&&new RegExp(`(^|[^0-9])${u}([^0-9]|$)`).test(e)}try{return s(u,0),!0}catch(t){return Boolean(t&&"EPERM"===t.code)}},hasDisplay:function(t={}){const{platform:e,env:r,win32:n,probe:o,injectedProbe:i}=p(t);return!!(n||"darwin"===e||d(r,"DISPLAY",e)||d(r,"WAYLAND_DISPLAY",e)||i&&null!==o("xdpyinfo",[],{env:r,platform:e}))},homeDir:g,desktopDir:function(t={}){const{platform:e,env:n,win32:o,probe:i,o:s}=p(t),u=o?r.win32:r.posix,a=g(t),m="function"==typeof s.dirExists?s.dirExists:c,h="function"==typeof s.dirNonEmpty?s.dirNonEmpty:l;if(o){const t=function(t,e){const r=t("reg",["query","HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders","/v","Desktop"]);if(!r)return"";const n=/^\s*Desktop\s+REG_(?:EXPAND_)?SZ\s+(.+)$/im.exec(r),o=n&&n[1].trim();return o&&e(o)?o:""}(i,m);if(t)return t}const y="function"==typeof s.readText?s.readText:f,w=[],k=t=>{t&&String(t).trim()&&w.push(String(t).trim())};if(o){const t=d(n,"OneDrive",e)||d(n,"OneDriveConsumer",e);t&&k(u.join(t,"Desktop")),a&&k(u.join(a,"OneDrive","Desktop")),a&&k(u.join(a,"Desktop"));const r=a?u.join(a,"Desktop"):"",o=w.indexOf(r);o>0&&m(r)&&h(r)&&w.slice(0,o).every((t=>!m(t)||!h(t)))&&(w.splice(o,1),w.unshift(r))}else if("darwin"===e)a&&k(u.join(a,"Desktop"));else{if(k(d(n,"XDG_DESKTOP_DIR",e)),a){const t=y(u.join(a,".config","user-dirs.dirs")),e=t&&/^\s*XDG_DESKTOP_DIR\s*=\s*"?([^"\n]+)"?\s*$/m.exec(t);e&&k(e[1].replace(/\$HOME\b|\${HOME}/g,a))}a&&k(u.join(a,"Desktop"))}for(const t of w)if(m(t))return t;return a&&(o||"darwin"===e)?u.join(a,"Desktop"):""},resolvePath:function(t,e={}){const{platform:n,win32:o,o:i}=p(e),s=o?r.win32:r.posix,u=t=>({ok:!1,path:null,error:t,expandedHome:!1});if("string"!=typeof t||!t.trim())return u(`a path is required (got ${JSON.stringify(t)})`);const c=t.trim();let l=c,f=!1;if("~"===c||c.startsWith("~/")||o&&c.startsWith("~\\")){const t=g(e);if(!t)return u(`cannot expand "~" in ${JSON.stringify(c)}: this machine reports no home directory. Pass a full absolute path instead.`);l="~"===c?t:s.join(t,c.slice(2)),f=!0}else if(c.startsWith("~"))return u(`${JSON.stringify(c)} names another user's home directory, which cannot be resolved from here. Use "~" for this user, or pass a full absolute path.`);if(l=function(t,{home:e,desktopdir:r,win32:n,P:o}){if(!e||!r)return t;const i=o.join(e,"Desktop"),s=t=>n?t.toLowerCase():t;if(s(i)===s(r))return t;if(s(t)===s(i))return r;const u=i+o.sep;return s(t).startsWith(s(u))?r+o.sep+t.slice(u.length):t}(l,{home:g(e),desktopdir:i.desktopdir,win32:o,P:s}),!f){const t=g(e),r=t?` This machine's home directory is ${t}.`:"";if(o){if((l.startsWith("/")||l.startsWith("\\"))&&!k.test(l))return u(`${JSON.stringify(c)} is not an absolute path on this machine, which runs ${n}. A leading slash here means "the root of the current drive", so writing to it would silently land somewhere other than where you meant. Use a drive-qualified path (C:\\Users\\you\\Desktop\\file.txt) or "~/…".${r}`)}else if(y.test(l)||w.test(l)||k.test(l))return u(`${JSON.stringify(c)} is a Windows path, but this machine runs ${n}. Use a posix path (/home/you/file.txt) or "~/…".${r}`)}const a="string"==typeof i.cwd&&i.cwd.trim()?i.cwd.trim():process.cwd(),d=s.isAbsolute(l)?s.resolve(l):s.resolve(a,l);return s.isAbsolute(d)?{ok:!0,path:d,error:null,expandedHome:f}:u(`${JSON.stringify(c)} is relative and the working directory (${JSON.stringify(a)}) is not absolute, so it cannot be resolved. Pass an absolute path.`)},baseName:function(t){if("string"!=typeof t)return"";const e=t.trim().replace(/[/\\]+$/,"");if(!e)return"";if(/^[A-Za-z]:$/.test(e))return"";const r=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return-1===r?e:e.slice(r+1)},hasPosixModes:function(t={}){const{win32:e}=p(t);return!e},appLocale:function(t={}){const{platform:e,env:r,o:n}=p(t);if("string"==typeof n.locale)return h(n.locale);const o=n.env&&"object"==typeof n.env;for(const t of["LC_ALL","LC_CTYPE","LC_MESSAGES","LANG"]){const n=h(d(r,t,e));if(n)return n}const i=String(d(r,"LANGUAGE",e)||"");if(i)for(const t of i.split(":")){const e=h(t);if(e)return e}if(o)return"";try{return h((new Intl.DateTimeFormat).resolvedOptions().locale)}catch{return""}},languageName:function(t,e={}){const{o:r}=p(e);if("string"==typeof r.languageName)return r.languageName;const n=h(t);if(!n)return"";const o=n.split("-")[0];try{return new Intl.DisplayNames(["en"],{type:"language"}).of(o)||""}catch{return""}},normalizeLocale:h};module.exports=S;
@@ -1,3 +1,3 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- "use strict";const fs=require("node:fs"),path=require("node:path"),{aegisHome:aegisHome}=require("./credentials.js"),STORE_FILE="sessions.json",STORE_VERSION=2,MAX_MESSAGES_PER_SESSION=2e3;function storeDir(e){return e||aegisHome()}function storeFile(e){return path.join(storeDir(e),STORE_FILE)}function nextSeq(e){const t=("number"==typeof e.__seq?e.__seq:0)+1;return e.__seq=t,t}function toEpochMs(e){if("number"==typeof e&&Number.isFinite(e))return e;if("string"==typeof e&&e.trim()){const t=Date.parse(e);if(Number.isFinite(t))return t}return 0}function load(e){try{const t=JSON.parse(fs.readFileSync(storeFile(e),"utf8"));if(t&&"object"==typeof t&&!Array.isArray(t))return t}catch{}return{}}function atomicWrite(e,t){fs.mkdirSync(path.dirname(e),{recursive:!0});const n=`${e}.tmp-${process.pid}`;fs.writeFileSync(n,JSON.stringify(t,null,2),{mode:384}),fs.renameSync(n,e);try{fs.chmodSync(e,384)}catch{}}const LOCK_STALE_MS=2e3,LOCK_WAIT_MS=500;function lockFile(e){return`${storeFile(e)}.lock`}function acquireLock(e){const t=lockFile(e);try{fs.mkdirSync(path.dirname(t),{recursive:!0})}catch{return!1}const n=Date.now()+LOCK_WAIT_MS;for(let e=0;e<200;e++)try{const e=fs.openSync(t,"wx");return fs.writeSync(e,String(process.pid)),fs.closeSync(e),!0}catch{let e=null;try{e=Date.now()-fs.statSync(t).mtimeMs}catch{continue}if(e>LOCK_STALE_MS){try{fs.unlinkSync(t)}catch{}continue}if(Date.now()>=n)return!1;const s=Date.now()+5;for(;Date.now()<s;);}return!1}function releaseLock(e){try{fs.unlinkSync(lockFile(e))}catch{}}function mutate(e,t){const n=acquireLock(e);try{const n=load(e),s=t(n);return save(e,n),s}finally{n&&releaseLock(e)}}function save(e,t){atomicWrite(storeFile(e),t)}function trimMessages(e){return Array.isArray(e)?e.length<=MAX_MESSAGES_PER_SESSION?e:e.slice(e.length-MAX_MESSAGES_PER_SESSION):[]}function upsertSession(e,t){const n=t&&t.id;if(!n)throw new Error("session.id is required");return mutate(e,(e=>{const s=e[n]||{messages:[]};return e[n]={...s,...t,id:n,version:2},!0===s.named&&"string"==typeof s.title&&s.title&&(e[n].title=s.title,e[n].named=!0),!1!==t.pending&&(e[n].pending=!0),e[n].updatedAt||(e[n].updatedAt=Date.now()),e[n].seq=nextSeq(e),e[n]}))}function appendMessage(e,t,n){if(!t)throw new Error("sessionId is required");return mutate(e,(e=>{const s=e[t]||{id:t,messages:[]},r=Array.isArray(s.messages)?s.messages:[];return s.messages=trimMessages(r.concat(n)),s.updatedAt=Date.now(),s.pending=!0,s.seq=nextSeq(e),e[t]=s,s}))}function recordExchange(e,t){const n=t||{};if(!n.sessionId)return null;const s=n.sessionId;return mutate(e,(e=>{const t=e[s]||{id:s,messages:[]},r=Array.isArray(t.messages)?t.messages:[],o=n.ts||(new Date).toISOString(),i={role:"user",content:null==n.prompt?"":String(n.prompt),ts:o},a={role:"assistant",content:null==n.reply?"":String(n.reply),ts:o};return n.tokens&&(a.tokens=n.tokens),"number"==typeof n.costUsd&&(a.costUsd=n.costUsd),n.status&&(a.status=n.status),n.model&&(a.model=n.model),n.provider&&(a.provider=n.provider),n.origin&&(i.origin=n.origin,a.origin=n.origin),t.messages=trimMessages(r.concat([i,a])),t.title=t.title||String(n.prompt||"").slice(0,60),n.cwd&&(t.cwd=n.cwd),t.origin=n.origin||t.origin||"unknown",t.updatedAt=Date.now(),t.pending=!0===n.pending,t.seq=nextSeq(e),e[s]=t,t}))}function setTitle(e,t,n,s){const r=String(null==n?"":n).trim().slice(0,200);if(!t||!r)return null;const o=s&&!0===s.named;return mutate(e,(e=>{const n=e[t];return n?(n.title=r,o&&(n.named=!0),n.updatedAt=Date.now(),n.seq=nextSeq(e),n):null}))}function listSessions(e){const t=load(e);return Object.values(t).filter((e=>e&&e.id)).sort(((e,t)=>(t.updatedAt||0)-(e.updatedAt||0)||(t.seq||0)-(e.seq||0)))}function getSession(e,t){return load(e)[t]||null}function deleteSession(e,t){return mutate(e,(e=>(delete e[t],{ok:!0})))}function markSynced(e,t,n){return mutate(e,(e=>{const s=e[t];return s?(s.pending=!1,s.lastSyncedAt=Date.now(),n&&n.remoteId&&(s.remoteId=n.remoteId),s.seq=nextSeq(e),s):null}))}function markPending(e,t){return mutate(e,(e=>{const n=e[t];return n?(n.pending=!0,n.seq=nextSeq(e),n):null}))}function listPending(e){return listSessions(e).filter((e=>!1!==e.pending))}function mergeRemoteSessions(e,t){const n=Array.isArray(t)?t:[];return n.length?mutate(e,(e=>{let t=0;for(const s of n){const n=s&&(s.session_id||s.id);if(!n)continue;const r=e[n],o=toEpochMs(s.updated_at??s.updatedAt);r&&(r.pending||(r.updatedAt||0)>=o)||(e[n]={id:n,title:s.title||r&&r.title||"",messages:Array.isArray(s.messages)?s.messages:[],updatedAt:o||Date.now(),pending:!1,lastSyncedAt:Date.now(),remoteId:s.session_id||s.id,origin:s.source||r&&r.origin||"cloud",version:2},e[n].seq=nextSeq(e),t+=1)}return t})):0}function listSummaries(e,t=8){return listSessions(e).slice(0,t).map((e=>{const t=Array.isArray(e.messages)?e.messages:[],n=t.find((e=>e&&"user"===e.role));return{id:e.id,cwd:(e.cwd||"").split(/[\\/]/).filter(Boolean).pop()||"~",summary:String(e.title||n&&n.content||"").slice(0,60),time:new Date(e.updatedAt||Date.now()).toISOString(),own:!0,origin:e.origin||"unknown",messages:t.length,pending:!0===e.pending,dir:String(e.cwd||"")}}))}function readTranscript(e,t){const n=getSession(e,t);return n?(Array.isArray(n.messages)?n.messages:[]).filter((e=>e&&("user"===e.role||"assistant"===e.role))).map((e=>({role:e.role,text:null==e.content?"":String(e.content)}))):[]}function adopt(e,t){const n=storeFile(t);if(!(()=>{try{return fs.existsSync(n)}catch{return!1}})())return{adopted:!1,sessions:0,from:n,reason:"no legacy store"};const s=(()=>{try{const e=JSON.parse(fs.readFileSync(n,"utf8"));return e&&"object"==typeof e&&!Array.isArray(e)?e:{}}catch{return{}}})(),r=Object.values(s).filter((e=>e&&e.id));return r.length?listSessions(e).length?{adopted:!1,sessions:0,from:n,reason:"store already has sessions"}:(mutate(e,(e=>{for(const t of r)e[t.id]={...t,adoptedFrom:n,version:2},e[t.id].seq=nextSeq(e);return e.__seq=Math.max(e.__seq||0,s.__seq||0),e.version=2,null})),{adopted:!0,sessions:r.length,from:n}):{adopted:!1,sessions:0,from:n,reason:"legacy store empty"}}function toMarkdown(e){const t=e&&(e.title||e.id)||"session",n=e&&Array.isArray(e.messages)?e.messages:[],s=[`# ${t}`,""];for(const e of n){const t=e&&e.role||"unknown",n=t.charAt(0).toUpperCase()+t.slice(1),r=e&&(e.content||e.text)||"";s.push(`## ${n}`,"",r,"")}return s.join("\n")}function toJson(e){return JSON.stringify(e,null,2)}module.exports={STORE_FILE:STORE_FILE,STORE_VERSION:2,MAX_MESSAGES_PER_SESSION:MAX_MESSAGES_PER_SESSION,storeDir:storeDir,storeFile:storeFile,lockFile:lockFile,LOCK_STALE_MS:LOCK_STALE_MS,LOCK_WAIT_MS:LOCK_WAIT_MS,toEpochMs:toEpochMs,load:load,save:save,upsertSession:upsertSession,appendMessage:appendMessage,recordExchange:recordExchange,setTitle:setTitle,listSessions:listSessions,getSession:getSession,deleteSession:deleteSession,markSynced:markSynced,markPending:markPending,listPending:listPending,mergeRemoteSessions:mergeRemoteSessions,listSummaries:listSummaries,readTranscript:readTranscript,adopt:adopt,toMarkdown:toMarkdown,toJson:toJson};
3
+ const e=require("node:fs"),n=require("node:path"),{aegisHome:t}=require("./credentials.js"),r="sessions.json",s=2e3;function o(e){return e||t()}function i(e){return n.join(o(e),r)}function c(e){const n=("number"==typeof e.__seq?e.__seq:0)+1;return e.__seq=n,n}function a(e){if("number"==typeof e&&Number.isFinite(e))return e;if("string"==typeof e&&e.trim()){const n=Date.parse(e);if(Number.isFinite(n))return n}return 0}function u(n){try{const t=JSON.parse(e.readFileSync(i(n),"utf8"));if(t&&"object"==typeof t&&!Array.isArray(t))return t}catch{}return{}}function d(e){return`${i(e)}.lock`}function l(t,r){const s=function(t){const r=d(t);try{e.mkdirSync(n.dirname(r),{recursive:!0})}catch{return!1}const s=Date.now()+500;for(let n=0;n<200;n++)try{const n=e.openSync(r,"wx");return e.writeSync(n,String(process.pid)),e.closeSync(n),!0}catch{let n=null;try{n=Date.now()-e.statSync(r).mtimeMs}catch{continue}if(n>2e3){try{e.unlinkSync(r)}catch{}continue}if(Date.now()>=s)return!1;const t=Date.now()+5;for(;Date.now()<t;);}return!1}(t);try{const e=u(t),n=r(e);return g(t,e),n}finally{s&&function(n){try{e.unlinkSync(d(n))}catch{}}(t)}}function g(t,r){!function(t,r){e.mkdirSync(n.dirname(t),{recursive:!0});const s=`${t}.tmp-${process.pid}`;e.writeFileSync(s,JSON.stringify(r,null,2),{mode:384}),e.renameSync(s,t);try{e.chmodSync(t,384)}catch{}}(i(t),r)}function p(e){return Array.isArray(e)?e.length<=s?e:e.slice(e.length-s):[]}function f(e){const n=u(e);return Object.values(n).filter((e=>e&&e.id)).sort(((e,n)=>(n.updatedAt||0)-(e.updatedAt||0)||(n.seq||0)-(e.seq||0)))}function m(e,n){return u(e)[n]||null}module.exports={STORE_FILE:r,STORE_VERSION:2,MAX_MESSAGES_PER_SESSION:s,storeDir:o,storeFile:i,lockFile:d,LOCK_STALE_MS:2e3,LOCK_WAIT_MS:500,toEpochMs:a,load:u,save:g,upsertSession:function(e,n){const t=n&&n.id;if(!t)throw new Error("session.id is required");return l(e,(e=>{const r=e[t]||{messages:[]};return e[t]={...r,...n,id:t,version:2},!0===r.named&&"string"==typeof r.title&&r.title&&(e[t].title=r.title,e[t].named=!0),!1!==n.pending&&(e[t].pending=!0),e[t].updatedAt||(e[t].updatedAt=Date.now()),e[t].seq=c(e),e[t]}))},appendMessage:function(e,n,t){if(!n)throw new Error("sessionId is required");return l(e,(e=>{const r=e[n]||{id:n,messages:[]},s=Array.isArray(r.messages)?r.messages:[];return r.messages=p(s.concat(t)),r.updatedAt=Date.now(),r.pending=!0,r.seq=c(e),e[n]=r,r}))},recordExchange:function(e,n){const t=n||{};if(!t.sessionId)return null;const r=t.sessionId;return l(e,(e=>{const n=e[r]||{id:r,messages:[]},s=Array.isArray(n.messages)?n.messages:[],o=t.ts||(new Date).toISOString(),i={role:"user",content:null==t.prompt?"":String(t.prompt),ts:o},a={role:"assistant",content:null==t.reply?"":String(t.reply),ts:o};return t.tokens&&(a.tokens=t.tokens),"number"==typeof t.costUsd&&(a.costUsd=t.costUsd),t.status&&(a.status=t.status),t.model&&(a.model=t.model),t.provider&&(a.provider=t.provider),t.origin&&(i.origin=t.origin,a.origin=t.origin),n.messages=p(s.concat([i,a])),n.title=n.title||String(t.prompt||"").slice(0,60),t.cwd&&(n.cwd=t.cwd),n.origin=t.origin||n.origin||"unknown",n.updatedAt=Date.now(),n.pending=!0===t.pending,n.seq=c(e),e[r]=n,n}))},setTitle:function(e,n,t,r){const s=String(null==t?"":t).trim().slice(0,200);if(!n||!s)return null;const o=r&&!0===r.named;return l(e,(e=>{const t=e[n];return t?(t.title=s,o&&(t.named=!0),t.updatedAt=Date.now(),t.seq=c(e),t):null}))},listSessions:f,getSession:m,deleteSession:function(e,n){return l(e,(e=>(delete e[n],{ok:!0})))},markSynced:function(e,n,t){return l(e,(e=>{const r=e[n];return r?(r.pending=!1,r.lastSyncedAt=Date.now(),t&&t.remoteId&&(r.remoteId=t.remoteId),r.seq=c(e),r):null}))},markPending:function(e,n){return l(e,(e=>{const t=e[n];return t?(t.pending=!0,t.seq=c(e),t):null}))},listPending:function(e){return f(e).filter((e=>!1!==e.pending))},mergeRemoteSessions:function(e,n){const t=Array.isArray(n)?n:[];return t.length?l(e,(e=>{let n=0;for(const r of t){const t=r&&(r.session_id||r.id);if(!t)continue;const s=e[t],o=a(r.updated_at??r.updatedAt);s&&(s.pending||(s.updatedAt||0)>=o)||(e[t]={id:t,title:r.title||s&&s.title||"",messages:Array.isArray(r.messages)?r.messages:[],updatedAt:o||Date.now(),pending:!1,lastSyncedAt:Date.now(),remoteId:r.session_id||r.id,origin:r.source||s&&s.origin||"cloud",version:2},e[t].seq=c(e),n+=1)}return n})):0},listSummaries:function(e,n=8){return f(e).slice(0,n).map((e=>{const n=Array.isArray(e.messages)?e.messages:[],t=n.find((e=>e&&"user"===e.role));return{id:e.id,cwd:(e.cwd||"").split(/[\\/]/).filter(Boolean).pop()||"~",summary:String(e.title||t&&t.content||"").slice(0,60),time:new Date(e.updatedAt||Date.now()).toISOString(),own:!0,origin:e.origin||"unknown",messages:n.length,pending:!0===e.pending,dir:String(e.cwd||"")}}))},readTranscript:function(e,n){const t=m(e,n);return t?(Array.isArray(t.messages)?t.messages:[]).filter((e=>e&&("user"===e.role||"assistant"===e.role))).map((e=>({role:e.role,text:null==e.content?"":String(e.content)}))):[]},adopt:function(n,t){const r=i(t);if(!(()=>{try{return e.existsSync(r)}catch{return!1}})())return{adopted:!1,sessions:0,from:r,reason:"no legacy store"};const s=(()=>{try{const n=JSON.parse(e.readFileSync(r,"utf8"));return n&&"object"==typeof n&&!Array.isArray(n)?n:{}}catch{return{}}})(),o=Object.values(s).filter((e=>e&&e.id));return o.length?f(n).length?{adopted:!1,sessions:0,from:r,reason:"store already has sessions"}:(l(n,(e=>{for(const n of o)e[n.id]={...n,adoptedFrom:r,version:2},e[n.id].seq=c(e);return e.__seq=Math.max(e.__seq||0,s.__seq||0),e.version=2,null})),{adopted:!0,sessions:o.length,from:r}):{adopted:!1,sessions:0,from:r,reason:"legacy store empty"}},toMarkdown:function(e){const n=e&&(e.title||e.id)||"session",t=e&&Array.isArray(e.messages)?e.messages:[],r=[`# ${n}`,""];for(const e of t){const n=e&&e.role||"unknown",t=n.charAt(0).toUpperCase()+n.slice(1),s=e&&(e.content||e.text)||"";r.push(`## ${t}`,"",s,"")}return r.join("\n")},toJson:function(e){return JSON.stringify(e,null,2)}};
@@ -1,3 +1,3 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- "use strict";const fs=require("node:fs"),os=require("node:os"),path=require("node:path");let envFileLib=null;try{envFileLib=require("../../../client/env-file.js")}catch{try{envFileLib=require("../../vendor/env-file.js")}catch{envFileLib=null}}function claudeConfigDir(e){const n=e||process.env,t=n&&n.CLAUDE_CONFIG_DIR;return t&&String(t).trim()?String(t).trim():path.join(os.homedir(),".claude")}function claudeOAuthToken(e){return envFileLib?envFileLib.resolveForeignSecret("CLAUDE_CODE_OAUTH_TOKEN",{env:e}):""}const SHADOWING_ENV_VARS=Object.freeze(["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN"]);function isAnthropicConsoleKey(e){return"string"==typeof e&&/^sk-ant-[A-Za-z0-9_-]{8,}$/.test(e.trim())}function childEnvPlan(e,n,t){const o={...e||{}},s=[],i=envFileLib&&"function"==typeof envFileLib.credentialLooksUsable?envFileLib.credentialLooksUsable:null,r=!(!t||!t.hasSubscription);if(i)for(const e of SHADOWING_ENV_VARS){const n=o[e];if("string"!=typeof n)continue;let t=null;if(i(n)?r&&"ANTHROPIC_API_KEY"===e&&!isAnthropicConsoleKey(n)&&(t="not-a-console-key"):t="too-short",!t)continue;delete o[e];const a=n.trim().length;a>0&&s.push({name:e,length:a,reason:t})}return n&&(o.CLAUDE_CODE_OAUTH_TOKEN=n),{env:o,dropped:s}}function envDroppedLine(e){const n=Array.isArray(e)?e:[];if(!n.length)return null;const t=n.filter((e=>e&&"not-a-console-key"===e.reason)),o=n.filter((e=>!e||"not-a-console-key"!==e.reason)),s=[];if(o.length){const e=o.map((e=>`${e.name} (${e.length} character${1===e.length?"":"s"})`)).join(", ");s.push(`${e}: too short to be a credential, and the CLI would have spent it instead of your subscription`)}if(t.length){const e=t.map((e=>`${e.name} (${e.length} characters)`)).join(", ");s.push(`${e}: not an Anthropic console key (\`sk-ant-\`), and the CLI would have spent it instead of your subscription`)}return`aegis: not passed to the claude child — ${s.join("; ")}`}function shadowingValue(e,n){const t=e||{},o=envFileLib&&"function"==typeof envFileLib.credentialLooksUsable?envFileLib.credentialLooksUsable:null;if(!o)return null;const s=!(!n||!n.hasSubscription);for(const e of SHADOWING_ENV_VARS){const n=t[e];if("string"!=typeof n)continue;let i=null;if(o(n)?s&&"ANTHROPIC_API_KEY"===e&&!isAnthropicConsoleKey(n)&&(i="not-a-console-key"):i="too-short",i)return{name:e,length:n.trim().length,reason:i}}return null}function claudeProStatus(e){const n=e||{},t=n.env||process.env,o=path.join(n.dir||claudeConfigDir(t),".credentials.json"),s={claude:n.claudeVersion||null,file:o,exists:!1,kind:null,subscription:null,expiresAt:0,loggedIn:!1};let i;try{i=JSON.parse(fs.readFileSync(o,"utf8")),s.exists=!0}catch{i=null}const r=i&&i.claudeAiOauth;r&&(r.accessToken||r.refreshToken)?(s.kind="oauth",s.subscription=r.subscriptionType||null,s.expiresAt=Number(r.refreshTokenExpiresAt)||0,s.loggedIn=!0):i&&"string"==typeof i.token&&i.token?(s.kind="apikey",s.loggedIn=!0):claudeOAuthToken(t)&&(s.kind="env-token",s.loggedIn=!0),s.subscriptionPresent=s.loggedIn&&"apikey"!==s.kind,s.shadowed=shadowingValue(t,{hasSubscription:s.subscriptionPresent});const a=childEnvPlan(t,null,{hasSubscription:s.subscriptionPresent});return s.credentialPresent=s.loggedIn||"string"==typeof a.env.ANTHROPIC_API_KEY||"string"==typeof a.env.ANTHROPIC_AUTH_TOKEN||"string"==typeof a.env.CLAUDE_CODE_OAUTH_TOKEN,s}const PRO_MODELS=Object.freeze([{id:"default",label:"Default (recommended)",note:"the CLI picks for the subscription"},{id:"sonnet",label:"Sonnet",note:"alias the CLI resolves · latest Sonnet"},{id:"opus",label:"Opus",note:"alias the CLI resolves · latest Opus"},{id:"opusplan",label:"Opus Plan",note:"alias the CLI resolves · plan with Opus, act on Sonnet"},{id:"haiku",label:"Haiku",note:"alias the CLI resolves · latest Haiku"},{id:"fable",label:"Fable",note:"alias the CLI resolves · needs usage credits"},{id:"claude-sonnet-5-5",label:"Claude Sonnet 5.5",note:"full name · Anthropic"},{id:"claude-sonnet-4-6",label:"Claude Sonnet 4.6",note:"full name · Anthropic"},{id:"claude-sonnet-4-5-20250929",label:"Claude Sonnet 4.5",note:"full name · Anthropic · dated snapshot"},{id:"claude-opus-5",label:"Claude Opus 5",note:"full name · Anthropic"},{id:"claude-opus-4-7",label:"Claude Opus 4.7",note:"full name · Anthropic"},{id:"claude-opus-4-6",label:"Claude Opus 4.6",note:"full name · Anthropic"},{id:"claude-opus-4-5-20251101",label:"Claude Opus 4.5",note:"full name · Anthropic · dated snapshot"}]);function turnArgs(e){const n=[],t=e||{};return t.system&&String(t.system).trim()&&n.push("--append-system-prompt",String(t.system)),n}function createStreamParser(e){const n=e||{},t=new Map;let o="",s="",i=0,r=null;const a=e=>[...t.values()].find((n=>"collecting"===n.phase&&n.index===e))||[...t.values()].find((e=>"collecting"===e.phase));return{line(e){let l;try{l=JSON.parse(e)}catch{return}if("stream_event"===l.type&&l.event){const e=l.event;if("content_block_start"===e.type&&e.content_block)"tool_use"===e.content_block.type&&t.set(e.content_block.id,{id:e.content_block.id,index:null==e.index?0:e.index,name:e.content_block.name,args:"",startedAt:Date.now(),phase:"collecting"});else if("content_block_delta"===e.type&&e.delta){if("text_delta"===e.delta.type){const t=(e.delta.text||"").replace(/\x00/g,"");o+=t,n.onText&&t&&n.onText(t)}else if("thinking_delta"===e.delta.type){const t=(e.delta.thinking||"").replace(/\x00/g,"");s+=t,n.onThinking&&t&&n.onThinking(t);const o=e.delta.estimated_tokens;"number"==typeof o&&o>0&&Number.isFinite(o)&&(i+=o,n.onThinkingProgress&&n.onThinkingProgress(o))}else if("input_json_delta"===e.delta.type){const n=a(null==e.index?0:e.index);n&&(n.args+=e.delta.partial_json||"")}}else if("content_block_stop"===e.type){const o=a(null==e.index?0:e.index);o&&(e=>{let o=e.args;try{o=e.args?JSON.parse(e.args):{}}catch{o={}}t.set(e.id,{...e,args:o,phase:"run"}),n.onTool&&n.onTool({id:e.id,name:e.name,args:o,phase:"run"})})(o)}}else if("user"===l.type&&l.message){const e=Array.isArray(l.message.content)?l.message.content:[];for(const o of e){if(!o||"tool_result"!==o.type||!o.tool_use_id)continue;const e=t.get(o.tool_use_id);if(!e)continue;const s=Math.max(0,Date.now()-(e.startedAt||Date.now()));n.onTool&&n.onTool({id:e.id,name:e.name,phase:"done",elapsed:s,error:!!o.is_error}),t.delete(o.tool_use_id)}}else"result"===l.type&&(r=l,n.onDone&&n.onDone({text:o||l.result||"",error:l.is_error?l.result||"api error":void 0,usage:l.usage||null,costUsd:"number"==typeof l.total_cost_usd?l.total_cost_usd:void 0,durationMs:l.duration_ms,sessionId:l.session_id,thinking:s||"",thinkingTokens:i}))},get text(){return o},get thinking(){return s},get thinkingTokens(){return i},get resultLine(){return r}}}function loadSeam(e){const n=e||__dirname,t=[path.join(n,"..","..","..","one","src"),path.join(n,"..","..","vendor","one","src"),path.join(n,"..","..","..","..","one","src")];for(const e of t)try{const n=require(path.join(e,"child.js")),t=require(path.join(e,"permissions.js"));if("function"==typeof n.claudeArgv&&"function"==typeof t.resolvePosture)return{child:n,permissions:t}}catch{}throw new Error("aegis: the Claude child argv builder (one/src/child.js + one/src/permissions.js) is missing from this install — refusing to build a second argv, because a second argv is a second policy.")}function seamAvailable(e){try{return loadSeam(e),{ok:!0,error:null}}catch(e){return{ok:!1,error:e&&e.message||String(e)}}}function proMessage(e,n,t){const o={content:e||""},s="string"==typeof n?n:"";return s&&(o.reasoning_content=s),"number"==typeof t&&t>0&&Number.isFinite(t)&&(o.thinking_tokens=t),o}function runClaudePro(e,n){const t=e||{},o=n||{},s=o.seam||loadSeam(o.dir),i=o.spawn||require("node:child_process").spawn,r=s.permissions.resolvePosture({rules:t.rules,gate:t.gate,interactive:!1,childKind:s.permissions.CHILD_KINDS.HEADLESS,env:t.env||process.env}),a=s.child.claudeArgv({posture:r,prompt:t.prompt,model:t.model||void 0,permissionMode:t.permissionMode,resumeSessionId:t.resumeSessionId,sessionId:t.sessionId,addDir:t.addDir,extra:[...turnArgs(t),"--include-partial-messages","--verbose"]});return new Promise((e=>{if(t.signal&&t.signal.aborted)return void e({choices:[{message:{content:""},finish_reason:"stop"}],stopped:!0});const n=t.env||process.env,s=claudeOAuthToken(n);let r=!1;try{r=!!claudeProStatus({env:n}).subscriptionPresent}catch{}const l=childEnvPlan(n,s,{hasSubscription:r}),c=l.env,d=envDroppedLine(l.dropped);if(d&&t.onDelta)try{t.onDelta({delta:"",note:d})}catch{}let u;try{u=i(o.executable||"claude",a.argv,{cwd:t.cwd||process.cwd(),stdio:["ignore","pipe","pipe"],env:c})}catch(n){return void e({choices:[{message:{content:""},finish_reason:"error"}],error:`claude: could not start the child (${n&&n.message||n})`,...l.dropped.length?{envDropped:l.dropped}:{}})}if(t.onSpawn)try{t.onSpawn(u,a.record)}catch{}let p=!1,h="",g="",f=null;const m=Number(t.idleTimeoutMs)||6e5,_=n=>{p||(p=!0,f&&clearTimeout(f),t.signal&&t.signal.removeEventListener("abort",v),e(l.dropped.length?{...n,envDropped:l.dropped}:n))},v=()=>{try{u.kill("SIGTERM")}catch{}setTimeout((()=>{try{u.kill("SIGKILL")}catch{}}),1500)};t.signal&&t.signal.addEventListener("abort",v,{once:!0});const b=()=>{f&&clearTimeout(f),f=setTimeout((()=>{v(),_({choices:[{message:{content:""},finish_reason:"stop"}],error:`claude: the child went silent for ${Math.round(m/1e3)}s and was stopped`})}),m)};b();const k=createStreamParser({onText:e=>{b(),t.onDelta&&t.onDelta({delta:e})},onThinking:e=>{b(),t.onDelta&&t.onDelta({reasoning:e})},onThinkingProgress:e=>{b(),t.onDelta&&t.onDelta({thinkingTokens:e})},onTool:e=>{b(),t.onDelta&&t.onDelta({delta:"",tool:{name:e.name,args:e.args,ok:"done"===e.phase?!e.error:void 0,id:e.id,cwd:t.cwd,phase:e.phase}})},onDone:e=>{e.error?_({choices:[{message:{content:e.text||""},finish_reason:"error"}],usage:e.usage||void 0,error:e.error}):_({choices:[{message:proMessage(e.text||"",e.thinking,e.thinkingTokens),finish_reason:"stop"}],usage:e.usage||void 0,costUsd:e.costUsd,durationMs:e.durationMs,sessionId:e.sessionId,childRecord:a.record})}});u.stdout.on("data",(e=>{b(),g+=e.toString("utf8");const n=g.split("\n");g=n.pop()||"";for(const e of n){const n=e.trim();n&&k.line(n)}})),u.stderr.on("data",(e=>{b(),h.length<8192&&(h+=e.toString("utf8"))})),u.on("error",(e=>{_({choices:[{message:{content:""},finish_reason:"error"}],error:`claude: could not run the child (${e&&e.message||e}). Install it with \`npm i -g @anthropic-ai/claude-code\`, then sign in with \`claude auth login\`.`})})),u.on("close",(e=>{g.trim()&&k.line(g.trim()),_({choices:[{message:proMessage(k.text,k.thinking,k.thinkingTokens),finish_reason:"stop"}],usage:k.resultLine&&k.resultLine.usage||void 0,childRecord:a.record,error:k.text||0===e?void 0:`claude: the child exited with status ${e}${h.trim()?` — ${h.trim().split("\n").slice(-3).join(" ")}`:""}`})}))}))}function childLine(e,n){if(!e)return"";try{return loadSeam(n).child.childRecordLine(e)}catch{const n=e.skipFlag||"no permission flag";return`aegis: claude child [${e.kind}] ${n}`}}module.exports={claudeConfigDir:claudeConfigDir,claudeOAuthToken:claudeOAuthToken,claudeProStatus:claudeProStatus,childEnvPlan:childEnvPlan,envDroppedLine:envDroppedLine,shadowingValue:shadowingValue,SHADOWING_ENV_VARS:SHADOWING_ENV_VARS,PRO_MODELS:PRO_MODELS,turnArgs:turnArgs,createStreamParser:createStreamParser,loadSeam:loadSeam,seamAvailable:seamAvailable,childLine:childLine,runClaudePro:runClaudePro};
3
+ const e=require("node:fs"),n=require("node:os"),t=require("node:path");let o=null;try{o=require("../../../client/env-file.js")}catch{try{o=require("../../vendor/env-file.js")}catch{o=null}}function s(e){const o=e||process.env,s=o&&o.CLAUDE_CONFIG_DIR;return s&&String(s).trim()?String(s).trim():t.join(n.homedir(),".claude")}function i(e){return o?o.resolveForeignSecret("CLAUDE_CODE_OAUTH_TOKEN",{env:e}):""}const r=Object.freeze(["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN"]);function l(e){return"string"==typeof e&&/^sk-ant-[A-Za-z0-9_-]{8,}$/.test(e.trim())}function a(e,n,t){const s={...e||{}},i=[],a=o&&"function"==typeof o.credentialLooksUsable?o.credentialLooksUsable:null,c=!(!t||!t.hasSubscription);if(a)for(const e of r){const n=s[e];if("string"!=typeof n)continue;let t=null;if(a(n)?c&&"ANTHROPIC_API_KEY"===e&&!l(n)&&(t="not-a-console-key"):t="too-short",!t)continue;delete s[e];const o=n.trim().length;o>0&&i.push({name:e,length:o,reason:t})}return n&&(s.CLAUDE_CODE_OAUTH_TOKEN=n),{env:s,dropped:i}}function c(e){const n=Array.isArray(e)?e:[];if(!n.length)return null;const t=n.filter((e=>e&&"not-a-console-key"===e.reason)),o=n.filter((e=>!e||"not-a-console-key"!==e.reason)),s=[];if(o.length){const e=o.map((e=>`${e.name} (${e.length} character${1===e.length?"":"s"})`)).join(", ");s.push(`${e}: too short to be a credential, and the CLI would have spent it instead of your subscription`)}if(t.length){const e=t.map((e=>`${e.name} (${e.length} characters)`)).join(", ");s.push(`${e}: not an Anthropic console key (\`sk-ant-\`), and the CLI would have spent it instead of your subscription`)}return`aegis: not passed to the claude child — ${s.join("; ")}`}function d(e,n){const t=e||{},s=o&&"function"==typeof o.credentialLooksUsable?o.credentialLooksUsable:null;if(!s)return null;const i=!(!n||!n.hasSubscription);for(const e of r){const n=t[e];if("string"!=typeof n)continue;let o=null;if(s(n)?i&&"ANTHROPIC_API_KEY"===e&&!l(n)&&(o="not-a-console-key"):o="too-short",o)return{name:e,length:n.trim().length,reason:o}}return null}function u(n){const o=n||{},r=o.env||process.env,l=t.join(o.dir||s(r),".credentials.json"),c={claude:o.claudeVersion||null,file:l,exists:!1,kind:null,subscription:null,expiresAt:0,loggedIn:!1};let u;try{u=JSON.parse(e.readFileSync(l,"utf8")),c.exists=!0}catch{u=null}const p=u&&u.claudeAiOauth;p&&(p.accessToken||p.refreshToken)?(c.kind="oauth",c.subscription=p.subscriptionType||null,c.expiresAt=Number(p.refreshTokenExpiresAt)||0,c.loggedIn=!0):u&&"string"==typeof u.token&&u.token?(c.kind="apikey",c.loggedIn=!0):i(r)&&(c.kind="env-token",c.loggedIn=!0),c.subscriptionPresent=c.loggedIn&&"apikey"!==c.kind,c.shadowed=d(r,{hasSubscription:c.subscriptionPresent});const h=a(r,null,{hasSubscription:c.subscriptionPresent});return c.credentialPresent=c.loggedIn||"string"==typeof h.env.ANTHROPIC_API_KEY||"string"==typeof h.env.ANTHROPIC_AUTH_TOKEN||"string"==typeof h.env.CLAUDE_CODE_OAUTH_TOKEN,c}const p=Object.freeze([{id:"default",label:"Default (recommended)",note:"the CLI picks for the subscription"},{id:"sonnet",label:"Sonnet",note:"alias the CLI resolves · latest Sonnet"},{id:"opus",label:"Opus",note:"alias the CLI resolves · latest Opus"},{id:"opusplan",label:"Opus Plan",note:"alias the CLI resolves · plan with Opus, act on Sonnet"},{id:"haiku",label:"Haiku",note:"alias the CLI resolves · latest Haiku"},{id:"fable",label:"Fable",note:"alias the CLI resolves · needs usage credits"},{id:"claude-sonnet-5-5",label:"Claude Sonnet 5.5",note:"full name · Anthropic"},{id:"claude-sonnet-4-6",label:"Claude Sonnet 4.6",note:"full name · Anthropic"},{id:"claude-sonnet-4-5-20250929",label:"Claude Sonnet 4.5",note:"full name · Anthropic · dated snapshot"},{id:"claude-opus-5",label:"Claude Opus 5",note:"full name · Anthropic"},{id:"claude-opus-4-7",label:"Claude Opus 4.7",note:"full name · Anthropic"},{id:"claude-opus-4-6",label:"Claude Opus 4.6",note:"full name · Anthropic"},{id:"claude-opus-4-5-20251101",label:"Claude Opus 4.5",note:"full name · Anthropic · dated snapshot"}]);function h(e){const n=[],t=e||{};return t.system&&String(t.system).trim()&&n.push("--append-system-prompt",String(t.system)),n}function g(e){const n=e||{},t=new Map;let o="",s="",i=0,r=null;const l=e=>[...t.values()].find((n=>"collecting"===n.phase&&n.index===e))||[...t.values()].find((e=>"collecting"===e.phase));return{line(e){let a;try{a=JSON.parse(e)}catch{return}if("stream_event"===a.type&&a.event){const e=a.event;if("content_block_start"===e.type&&e.content_block)"tool_use"===e.content_block.type&&t.set(e.content_block.id,{id:e.content_block.id,index:null==e.index?0:e.index,name:e.content_block.name,args:"",startedAt:Date.now(),phase:"collecting"});else if("content_block_delta"===e.type&&e.delta){if("text_delta"===e.delta.type){const t=(e.delta.text||"").replace(/\x00/g,"");o+=t,n.onText&&t&&n.onText(t)}else if("thinking_delta"===e.delta.type){const t=(e.delta.thinking||"").replace(/\x00/g,"");s+=t,n.onThinking&&t&&n.onThinking(t);const o=e.delta.estimated_tokens;"number"==typeof o&&o>0&&Number.isFinite(o)&&(i+=o,n.onThinkingProgress&&n.onThinkingProgress(o))}else if("input_json_delta"===e.delta.type){const n=l(null==e.index?0:e.index);n&&(n.args+=e.delta.partial_json||"")}}else if("content_block_stop"===e.type){const o=l(null==e.index?0:e.index);o&&(e=>{let o=e.args;try{o=e.args?JSON.parse(e.args):{}}catch{o={}}t.set(e.id,{...e,args:o,phase:"run"}),n.onTool&&n.onTool({id:e.id,name:e.name,args:o,phase:"run"})})(o)}}else if("user"===a.type&&a.message){const e=Array.isArray(a.message.content)?a.message.content:[];for(const o of e){if(!o||"tool_result"!==o.type||!o.tool_use_id)continue;const e=t.get(o.tool_use_id);if(!e)continue;const s=Math.max(0,Date.now()-(e.startedAt||Date.now()));n.onTool&&n.onTool({id:e.id,name:e.name,phase:"done",elapsed:s,error:!!o.is_error}),t.delete(o.tool_use_id)}}else"result"===a.type&&(r=a,n.onDone&&n.onDone({text:o||a.result||"",error:a.is_error?a.result||"api error":void 0,usage:a.usage||null,costUsd:"number"==typeof a.total_cost_usd?a.total_cost_usd:void 0,durationMs:a.duration_ms,sessionId:a.session_id,thinking:s||"",thinkingTokens:i}))},get text(){return o},get thinking(){return s},get thinkingTokens(){return i},get resultLine(){return r}}}function f(e){const n=e||__dirname,o=[t.join(n,"..","..","..","one","src"),t.join(n,"..","..","vendor","one","src"),t.join(n,"..","..","..","..","one","src")];for(const e of o)try{const n=require(t.join(e,"child.js")),o=require(t.join(e,"permissions.js"));if("function"==typeof n.claudeArgv&&"function"==typeof o.resolvePosture)return{child:n,permissions:o}}catch{}throw new Error("aegis: the Claude child argv builder (one/src/child.js + one/src/permissions.js) is missing from this install — refusing to build a second argv, because a second argv is a second policy.")}function m(e,n,t){const o={content:e||""},s="string"==typeof n?n:"";return s&&(o.reasoning_content=s),"number"==typeof t&&t>0&&Number.isFinite(t)&&(o.thinking_tokens=t),o}module.exports={claudeConfigDir:s,claudeOAuthToken:i,claudeProStatus:u,childEnvPlan:a,envDroppedLine:c,shadowingValue:d,SHADOWING_ENV_VARS:r,PRO_MODELS:p,turnArgs:h,createStreamParser:g,loadSeam:f,seamAvailable:function(e){try{return f(e),{ok:!0,error:null}}catch(e){return{ok:!1,error:e&&e.message||String(e)}}},childLine:function(e,n){if(!e)return"";try{return f(n).child.childRecordLine(e)}catch{const n=e.skipFlag||"no permission flag";return`aegis: claude child [${e.kind}] ${n}`}},runClaudePro:function(e,n){const t=e||{},o=n||{},s=o.seam||f(o.dir),r=o.spawn||require("node:child_process").spawn,l=s.permissions.resolvePosture({rules:t.rules,gate:t.gate,interactive:!1,childKind:s.permissions.CHILD_KINDS.HEADLESS,env:t.env||process.env}),d=s.child.claudeArgv({posture:l,prompt:t.prompt,model:t.model||void 0,permissionMode:t.permissionMode,resumeSessionId:t.resumeSessionId,sessionId:t.sessionId,addDir:t.addDir,extra:[...h(t),"--include-partial-messages","--verbose"]});return new Promise((e=>{if(t.signal&&t.signal.aborted)return void e({choices:[{message:{content:""},finish_reason:"stop"}],stopped:!0});const n=t.env||process.env,s=i(n);let l=!1;try{l=!!u({env:n}).subscriptionPresent}catch{}const p=a(n,s,{hasSubscription:l}),h=p.env,f=c(p.dropped);if(f&&t.onDelta)try{t.onDelta({delta:"",note:f})}catch{}let _;try{_=r(o.executable||"claude",d.argv,{cwd:t.cwd||process.cwd(),stdio:["ignore","pipe","pipe"],env:h})}catch(n){return void e({choices:[{message:{content:""},finish_reason:"error"}],error:`claude: could not start the child (${n&&n.message||n})`,...p.dropped.length?{envDropped:p.dropped}:{}})}if(t.onSpawn)try{t.onSpawn(_,d.record)}catch{}let k=!1,v="",b="",y=null;const A=Number(t.idleTimeoutMs)||6e5,T=n=>{k||(k=!0,y&&clearTimeout(y),t.signal&&t.signal.removeEventListener("abort",I),e(p.dropped.length?{...n,envDropped:p.dropped}:n))},I=()=>{try{_.kill("SIGTERM")}catch{}setTimeout((()=>{try{_.kill("SIGKILL")}catch{}}),1500)};t.signal&&t.signal.addEventListener("abort",I,{once:!0});const S=()=>{y&&clearTimeout(y),y=setTimeout((()=>{I(),T({choices:[{message:{content:""},finish_reason:"stop"}],error:`claude: the child went silent for ${Math.round(A/1e3)}s and was stopped`})}),A)};S();const D=g({onText:e=>{S(),t.onDelta&&t.onDelta({delta:e})},onThinking:e=>{S(),t.onDelta&&t.onDelta({reasoning:e})},onThinkingProgress:e=>{S(),t.onDelta&&t.onDelta({thinkingTokens:e})},onTool:e=>{S(),t.onDelta&&t.onDelta({delta:"",tool:{name:e.name,args:e.args,ok:"done"===e.phase?!e.error:void 0,id:e.id,cwd:t.cwd,phase:e.phase}})},onDone:e=>{e.error?T({choices:[{message:{content:e.text||""},finish_reason:"error"}],usage:e.usage||void 0,error:e.error}):T({choices:[{message:m(e.text||"",e.thinking,e.thinkingTokens),finish_reason:"stop"}],usage:e.usage||void 0,costUsd:e.costUsd,durationMs:e.durationMs,sessionId:e.sessionId,childRecord:d.record})}});_.stdout.on("data",(e=>{S(),b+=e.toString("utf8");const n=b.split("\n");b=n.pop()||"";for(const e of n){const n=e.trim();n&&D.line(n)}})),_.stderr.on("data",(e=>{S(),v.length<8192&&(v+=e.toString("utf8"))})),_.on("error",(e=>{T({choices:[{message:{content:""},finish_reason:"error"}],error:`claude: could not run the child (${e&&e.message||e}). Install it with \`npm i -g @anthropic-ai/claude-code\`, then sign in with \`claude auth login\`.`})})),_.on("close",(e=>{b.trim()&&D.line(b.trim()),T({choices:[{message:m(D.text,D.thinking,D.thinkingTokens),finish_reason:"stop"}],usage:D.resultLine&&D.resultLine.usage||void 0,childRecord:d.record,error:D.text||0===e?void 0:`claude: the child exited with status ${e}${v.trim()?` — ${v.trim().split("\n").slice(-3).join(" ")}`:""}`})}))}))}};
@@ -1,3 +1,3 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- "use strict";const{randomUUID:randomUUID}=require("node:crypto"),os=require("node:os"),toolsModule=require("./tools.js"),attachmentsModule=require("./attachments.js"),{flattenContent:flattenContent}=attachmentsModule,promptModule=require("./prompt.js"),localTransport=require("./local.js"),{ShellSession:ShellSession}=require("./shell.js"),{planExec:planExec}=require("./exec-plan.js"),claudePro=require("./claude-pro.js"),{agentSystemPrompt:agentSystemPrompt,agentRoleLabel:agentRoleLabel}=require("./agents.js"),{beginTurnGuard:beginTurnGuard,recordWrite:recordWrite,blocksDestructive:blocksDestructive}=require("./turn-guard.js"),{acquireWorktreeLock:acquireWorktreeLock,releaseWorktreeLock:releaseWorktreeLock}=require("./worktree-lock.js"),covenant=require("./covenant.js");let envFile=null;try{envFile=require("../../../client/env-file.js")}catch{try{envFile=require("../../vendor/env-file.js")}catch{envFile=null}}let platformLib=null;try{platformLib=require("../../../client/platform.js")}catch{try{platformLib=require("../../vendor/platform.js")}catch{platformLib=null}}let credentialsLib=null;try{credentialsLib=require("../../../client/credentials.js")}catch{try{credentialsLib=require("../../vendor/credentials.js")}catch{credentialsLib=null}}function normalizeToolArgs(e,o,t,r){const n=e&&"function"==typeof e.normalizeArgs&&e.normalizeArgs||"function"==typeof toolsModule.normalizeArgs&&toolsModule.normalizeArgs||null;return n?n(o,t,r):{ok:!0,args:t&&"object"==typeof t?t:{},error:null}}function detectVcs(e){if(!e)return null;try{const o=require("node:fs"),t=require("node:path");let r=t.resolve(String(e));for(let e=0;e<8;e+=1){if(o.existsSync(t.join(r,".git")))return"git";const e=t.dirname(r);if(e===r)break;r=e}return""}catch{return null}}function hostEnv(e={},o={},t=null){const r=e||{},n=o||{},s=(e,o)=>null!=n[e]?n[e]:o;let a=r.homedir,i=r.cwd;try{a||(a=os.homedir()),i||(i=process.cwd())}catch{}let l=r.shell,c=r.shellKind;try{if(!l||!c){const e=require("./shell.js").resolveSessionShell();l=l||e.cmd,c=c||e.kind}}catch{}let d=r.desktopdir;try{!d&&platformLib&&(d=platformLib.desktopDir())}catch{}let u=r.dataDir;try{!u&&credentialsLib&&(u=credentialsLib.aegisHome())}catch{}let f=r.locale,p=r.localeName;try{!f&&platformLib&&"function"==typeof platformLib.appLocale&&(f=platformLib.appLocale()),f&&!p&&platformLib&&"function"==typeof platformLib.languageName&&(p=platformLib.languageName(f))}catch{}return{platform:s("platform",r.platform||process.platform),arch:s("arch",r.arch||process.arch),homedir:s("homedir",a),desktopdir:s("desktopdir",d),dataDir:s("dataDir",u),locale:s("locale",f),localeName:s("localeName",p),languages:s("languages",r.languages),cwd:s("cwd",i),vcs:s("vcs",null!=r.vcs?r.vcs:detectVcs(i)),shell:s("shell",l),shellKind:s("shellKind",c),roots:s("roots",r.roots),appVersion:s("appVersion",r.appVersion),model:s("model",t&&t.model)}}function requireSharedBrain(){const e=[()=>require("../../../client/brain-catalog.js"),()=>require("../../vendor/brain-catalog.js")];let o=null;for(const t of e)try{return t()}catch(e){o=e}throw o}function requireSharedByokCatalog(){const e=[()=>require("../../../client/byok-catalog.js"),()=>require("../../vendor/byok-catalog.js")];let o=null;for(const t of e)try{return t()}catch(e){o=e}throw o}function requireSharedUserModels(){const e=[()=>require("../../../client/user-models.js"),()=>require("../../vendor/user-models.js")];let o=null;for(const t of e)try{return t()}catch(e){o=e}throw o}function requireSharedCatalogClient(){const e=[()=>require("../../../client/catalog-client.js"),()=>require("../../vendor/catalog-client.js")];let o=null;for(const t of e)try{return t()}catch(e){o=e}throw o}function requireSharedModelDiscovery(){const e=[()=>require("../../../client/model-discovery.js"),()=>require("../../vendor/model-discovery.js")];let o=null;for(const t of e)try{return t()}catch(e){o=e}throw o}const WORKTREE_LOCK_WAIT_MS=1500,MAX_SUBAGENT_DEPTH=4,CLASSES=[{class:"aegis",label:"Aegis Cloud",kind:"cloud"},{class:"byok",label:"Bring your own key",kind:"cloud"},{class:"local",label:"Local model",kind:"local"},{class:"pro",label:"Claude Code Pro",kind:"subscription"}],BYOK_NAMESPACE_PREFIX="byok:";function byokNamespace(e){return`${BYOK_NAMESPACE_PREFIX}${e}`}function splitByokModel(e){const o="string"==typeof e?e:"",t=o.indexOf(":");return t<0?{provider:"",model:o}:{provider:o.slice(0,t),model:o.slice(t+1)}}function providerKeyRecord(e){const o={key:"",env:"",rejected:null};if(!envFile||"function"!=typeof envFile.providerKeyFromEnv)return o;try{const t=envFile.providerKeyFromEnv(e)||o;return{key:"string"==typeof t.key?t.key:"",env:"string"==typeof t.env?t.env:"",rejected:"string"==typeof t.rejected&&t.rejected?t.rejected:null}}catch{return o}}function providerKeyFromEnv(e){if(!envFile||"function"!=typeof envFile.providerKeyFromEnv)return"";try{return envFile.providerKeyFromEnv(e).key||""}catch{return""}}const DEEPSEEK_REASONING_MODEL_RE=/^deepseek-(v4(\.\d+)?-(flash|pro)|flash|pro|reasoner)$/,EFFORT_TOKEN_BUDGET={low:8192,medium:16384,high:32768,max:32768},DEEPSEEK_EFFORT={low:"low",medium:"high",high:"high"},DEEPSEEK_EFFORT_EXTRA={max:"max"},EFFORT_IDENTITY={low:"low",medium:"medium",high:"high"},EFFORT_INERT_RE=/non-reasoning/i,EFFORT_DIALECTS=[{provider:"deepseek",re:DEEPSEEK_REASONING_MODEL_RE,field:"effort",map:DEEPSEEK_EFFORT,extra:DEEPSEEK_EFFORT_EXTRA},{provider:"openai",re:/^(gpt-5|o[0-9])/i,field:"reasoning_effort",map:EFFORT_IDENTITY},{provider:"groq",re:/^(openai\/gpt-oss|qwen\/qwen3)/i,field:"reasoning_effort",map:EFFORT_IDENTITY},{provider:"xai",re:/^grok-(4\.[5-9]|[5-9])/,field:"reasoning_effort",map:EFFORT_IDENTITY},{provider:"google",re:/^gemini-(2\.5|3|[4-9])/,field:"reasoning_effort",map:{...EFFORT_IDENTITY,medium:"high"}}],AUTONOMOUS_IDLE_TIMEOUT_MS=9e5;function reasoningBudget(e,o,t){const r=Number(o);return Number.isFinite(r)&&r>0?r:DEEPSEEK_REASONING_MODEL_RE.test(String(e||""))?EFFORT_TOKEN_BUDGET["low"===t||"medium"===t||"max"===t?t:"high"]:void 0}function nativeEffort(e,o,t){const r=String(o||"");if(EFFORT_INERT_RE.test(r))return;if(null===t)return;const n="low"===t||"medium"===t?t:"max"===t?"max":"high";for(const o of EFFORT_DIALECTS)if(o.provider===e&&o.re.test(r)){const e=Object.prototype.hasOwnProperty.call(o.map,n)?o.map[n]:o.extra&&Object.prototype.hasOwnProperty.call(o.extra,n)?o.extra[n]:void 0;if(void 0===e)return;return{field:o.field,level:e}}}function normalizeCatalog(e){return Array.isArray(e)?e.map((e=>"string"==typeof e?{id:e}:e)).filter((e=>e&&e.id)):[]}const{offerableCatalog:offerableCatalog}=requireSharedBrain(),{withByokAdditions:withByokAdditions,canonicalModelId:canonicalModelId}=requireSharedByokCatalog(),{withUserModels:withUserModels,unmatchedUserProviders:unmatchedUserProviders,load:loadUserModels,addUserModel:addUserModel,removeUserModel:removeUserModel}=requireSharedUserModels(),{withCatalog:withCatalog}=requireSharedCatalogClient(),{discoverModels:discoverVendorModels,canDiscover:canDiscoverVendorModels,endpointFor:vendorEndpointFor,discoverableProviders:discoverableProviders}=requireSharedModelDiscovery();function parseArgs(e){if(null==e)return{};if("object"==typeof e)return e;try{const o=JSON.parse(String(e));return o&&"object"==typeof o?o:{}}catch{return{}}}function extractToolCalls(e){if(!e)return[];if(Array.isArray(e.toolCalls)&&e.toolCalls.length)return e.toolCalls.map((e=>({id:e.id||"",name:e.name||"",args:parseArgs(e.args)}))).filter((e=>e.name));const o=e.choices&&e.choices[0]&&e.choices[0].message,t=o&&o.tool_calls||[];return Array.isArray(t)?t.map((e=>{const o=e&&e.function||{};return{id:e&&e.id||"",name:o.name||e&&e.name||"",args:parseArgs(o.arguments)}})).filter((e=>e.name)):[]}function proTurnPrompt(e){const o=Array.isArray(e.prompt)?flattenContent(e.prompt):e.prompt;if("string"==typeof o&&o.trim())return o;const t=Array.isArray(e.messages)?e.messages:[];for(let e=t.length-1;e>=0;e-=1){const o=t[e];if(!o||"user"!==o.role)continue;const r=flattenContent(o.content);if(r.trim())return r}return o}function assistantText(e){const o=e&&e.choices&&e.choices[0]&&e.choices[0].message;return o&&"string"==typeof o.content&&o.content||""}function finishReasonOf(e){const o=e&&e.choices&&e.choices[0];return o&&o.finish_reason||e&&e.stop_reason||""}function isTruncated(e){const o=finishReasonOf(e);return"length"===o||"max_tokens"===o}function reasoningTextOf(e){if(!e)return"";const o=e.choices&&e.choices[0],t=o&&o.message||{};if(Array.isArray(t.content)){const e=t.content.filter((e=>e&&("thinking"===e.type||"reasoning"===e.type))).map((e=>e.thinking||e.text||"")).join("");if(e)return e}const r=t.content&&"object"==typeof t.content?t.content.reasoning_content:"",n=[t.reasoning_content,t.reasoning,o&&o.reasoning_content,e.reasoning_content,e.reasoning,r];for(const e of n)if("string"==typeof e&&e)return e;return""}function reasoningTokensOf(e){if(!e)return 0;const o=e.choices&&e.choices[0],t=o&&o.message||{},r=e.usage||{},n=r.completion_tokens_details||r.output_tokens_details||{},s=[t.thinking_tokens,t.reasoning_tokens,o&&o.thinking_tokens,e.thinking_tokens,n.reasoning_tokens,n.thinking_tokens];for(const e of s)if("number"==typeof e&&Number.isFinite(e)&&e>0)return e;return 0}function reasonedButSilent(e){return!assistantText(e)&&(""!==reasoningTextOf(e)||reasoningTokensOf(e)>0)}const REASONING_RETRY_FLOOR=32768;function retryBudgetFor(e,o){const t=doubledBudget(e.maxTokens);return o&&ladderRung(e.maxTokens)?Math.max(t,REASONING_RETRY_FLOOR):t}function ladderRung(e){const o=Number(e);return Number.isFinite(o)&&Object.values(EFFORT_TOKEN_BUDGET).includes(o)}function doubledBudget(e){const o=Number(e)||0;return o>0?2*o:8192}function statedCapOf(e){const o=e=>{const o=Number(e);return Number.isFinite(o)&&o>0?o:void 0};return e&&Object.prototype.hasOwnProperty.call(e,"statedMaxTokens")?o(e.statedMaxTokens):o(e&&e.maxTokens)}const EMPTY_TURN_NUDGE="Your previous reply came back empty — it contained no answer and no tool call. Write your answer now, using only the information already gathered above. No tools are available in this reply, so do not call any: respond in plain prose or markdown.",THOUGHT_ONLY_NUDGE="Your previous round was spent entirely on hidden reasoning and produced no visible reply. Answer the user directly and briefly now. Do not reason, explain, or think first — write only the answer, no tools.",FINAL_ANSWER_NUDGE="Write your answer now, in plain prose, using only what is already in this conversation. If your information is incomplete, say what you have and what is missing — an incomplete answer is the expected outcome here and is better than none. No tools, no preface.",RECOVERY_ROUNDS=2,UNMUTATED_TURN_NUDGE="You ended the turn without changing any file, but this request asked for a change. The tools are still available in this reply: make the edit now with editFile or writeFile. If you already know what to change, change it — describing the fix is not the fix. If you genuinely cannot, say precisely what blocks you.",MUTATION_INTENT_RE=new RegExp("\\b(?:fix|implement|add|create|write|refactor|rename|remove|delete|replace|update|patch|migrate|convert|make\\s+(?:it|them|this|that|the|sure)|change|correct|resolve|repair|address|apply|introduce|support|wire\\s+up)\\b","i");function wantsMutation(e,o,t){if(o)return!1;if(!(t>0))return!1;const r=String(e||"");return!!r.trim()&&!/\?\s*$/.test(r.trim())&&MUTATION_INTENT_RE.test(r)}function emptyTurnError({cls:e,model:o,finishReason:t,reasoningChars:r,reasoningTokens:n,effort:s,recoveryRounds:a}){const i=Number(a)||0,l=Number(n)||0,c=new Error(`The model returned no answer after ${e}/${o} was asked to summarise its results`+(i?`, and ${i} extra recovery call${1===i?"":"s"} with a larger budget and a changed ask came back empty too`:"")+` (stop reason: ${t||"none"}`+(s?`, effort: ${s}`:"")+(r?`, hidden reasoning: ${r} chars and no visible text`:l>0?`, ~${l} thinking tokens billed and no visible text`:"")+"). "+(r||l>0?"Every one of those calls spent its output on hidden reasoning instead of writing a word, so this is the model rather than the budget: pick a model that answers without a thinking pass, or ask for a smaller piece of work.":"No visible text came back from any of those calls. Send the request again, in smaller pieces, or from a different model."));return c.status=502,c}function createLocalEngine({aegis:e,settings:o,tools:t,promptBuilder:r,recallProvider:n,env:s,getConfirmMode:a,localTransport:i=localTransport,fetchImpl:l,gitScope:c}){const d=new Map,u=t||toolsModule,f=r&&r.buildSystemPrompt||promptModule.buildSystemPrompt,p=require("./session-rounds.js"),m=()=>{if("function"==typeof a)return!1!==a();if(o&&"function"==typeof o.getConfirmMode){const e=o.getConfirmMode();return void 0===e||Boolean(e)}return!0},g=new Map,h=new Map,y=new Map,k=new Map,v=new Map;function b(e){return`${e} was not executed — the user denied this tool for this conversation. Do NOT retry it and do NOT attempt the same effect by another route (another command, a writeFile instead of an edit, a subagent). Stop calling tools and reply in plain text: say what you were trying to do, what you need, and that the user can re-enable ${e} to let it proceed.`}function E(e,o,t,r){return new Promise((n=>{if(t&&t.aborted)return void n(!1);const s=randomUUID();let a=!1;const i=()=>l(!1),l=e=>{a||(a=!0,v.delete(s),t&&t.removeEventListener("abort",i),n(e))};t&&t.addEventListener("abort",i,{once:!0}),v.set(s,{resolve:l}),"function"==typeof o?o({delta:"",rounds:{id:s,sessionId:e,spent:r.spent,extensions:r.extensions,max:r.max,size:r.size}}):l(!1)}))}async function w(e,o,t){const r=normalizeToolArgs(u,e,o,t||{});if(!r.ok)return{ok:!1,error:r.error};o=r.args;const n=t&&t.guard;if(n&&"exec"===e){const e=blocksDestructive(n,o&&o.command);if(!e.ok)return{ok:!1,error:e.reason}}const s=covenant.preActionAssert({tool:e,args:o||{}});if(!s.allowed){const t=covenant.bindRefusal({tool:e,args:o||{}},s);return{ok:!1,error:`refused by the ÆGIS covenant — ${s.clause} (${s.label}): ${s.reason}`,covenant:t}}const a=await u.executeTool(e,o,t);return n&&("writeFile"===e||"editFile"===e)&&a&&!1!==a.ok&&recordWrite(n,o&&o.file_path),a}async function T(e,{toolCtx:o,rootSessionId:t,rootOnDelta:r,signal:n}){const{name:s}=e,a=normalizeToolArgs(u,s,e.args,o||{});if(!a.ok)return{ok:!1,error:a.error};const i=a.args;if(!u.MUTATING_TOOLS.has(s))return w(s,i,o);if(!m())return w(s,i,o);if(function(e,o){const t=g.get(e);return Boolean(t&&t.has(o))}(t,s))return w(s,i,o);if(function(e,o){const t=h.get(e);return Boolean(t&&t.has(o))}(t,s))return{ok:!1,error:b(s)};let l=null;if(("writeFile"===s||"editFile"===s)&&(l=u.previewMutation(s,i,o||{}),!l.ok))return{ok:!1,error:l.error};const c=await function(e,o,t,r){return new Promise((n=>{if(t&&t.aborted)return void n("cancel");const s=randomUUID();let a=!1;const i=()=>l("cancel"),l=e=>{a||(a=!0,k.delete(s),t&&t.removeEventListener("abort",i),n(e))};t&&t.addEventListener("abort",i,{once:!0}),k.set(s,{resolve:l}),"function"==typeof o?o({delta:"",approval:{id:s,sessionId:e,tool:r.tool,args:r.args,diff:r.diff||null}}):l("cancel")}))}(t,r,n,{tool:s,args:i,diff:l&&l.diff});if("deny"===c)return function(e,o){h.has(e)||h.set(e,new Set),h.get(e).add(o)}(t,s),{ok:!1,error:b(s)};if("session"!==c&&"once"!==c)return{ok:!1,error:`${s} was not executed — the request was cancelled.`};if("session"===c&&function(e,o){g.has(e)||g.set(e,new Set),g.get(e).add(o)}(t,s),l){const e=u.applyChecked(s,i,l,o||{});return e&&!1!==e.ok&&o&&o.guard&&recordWrite(o.guard,i&&i.file_path),e}return w(s,i,o)}function _(e){return hostEnv(s||{},e&&e.env||{},e)}async function S(o,t){if("aegis"===o){const o=!t.singlePass&&(!!t.autonomous||void 0);return e.chatCompletion({prompt:t.prompt,system:t.system,messages:t.messages,model:t.model,mode:t.mode,maxTokens:t.statedMaxTokens,stream:!1!==t.stream,includeUsage:!0,onStream:t.onDelta,onReasoning:t.onReasoning,idleTimeoutMs:t.idleTimeoutMs,signal:t.signal,extra:{aegis_recall:!0,...t.recallDeep?{aegis_recall_deep:!0}:{},session:t.sessionId,...void 0===o?{}:{brain:o},...!1===o?{mode:"brain"}:{},...t.effort?{effort:t.effort}:{},...!0===o&&t.workers?{workers:t.workers}:{},...t.tools.length?{tools:t.tools}:{},...t.toolChoice?{tool_choice:t.toolChoice}:{}},agentKey:t.tools.length&&(process.env.AEGIS_AGENT_KEY||"").trim()||void 0})}if("byok"===o){const{provider:o,model:r}=splitByokModel(t.model),n=canonicalModelId(o,r),s=nativeEffort(o,n,t.effort);try{return await e.byokChatCompletion({provider:o,model:n,providerKey:t.apiKey,baseURL:t.cfg&&t.cfg.baseURL,prompt:t.prompt,system:t.system,messages:t.messages,maxTokens:t.maxTokens,tools:t.tools,toolChoice:t.toolChoice,effort:s&&"effort"===s.field?s.level:void 0,reasoningEffort:s&&"reasoning_effort"===s.field?s.level:void 0,stream:!0,onStream:t.onDelta,signal:t.signal})}catch(e){if(e&&402===e.status){const e=new Error("byok: this account has no AEGIS balance left, and the BYOK handling fee is billed there — your provider key is still valid, this is not a key problem. Top up the account, then try again (or /class aegis to use the pooled lane).");throw e.status=402,e}throw e}}if("local"===o){const e=t.cfg&&t.cfg.baseURL||i.DEFAULT_BASE,o=o=>i.chat({baseURL:e,model:t.model,prompt:t.prompt,system:t.system,messages:t.messages,maxTokens:t.maxTokens,signal:t.signal,onDelta:t.onDelta,...o&&t.tools.length?{tools:t.tools,toolChoice:t.toolChoice}:{}});try{return await o(!0)}catch(e){if(t.tools.length&&e&&400===e.status)return o(!1);throw e}}if("pro"===o){const e=t.sessionKey||t.rootSessionId||t.sessionId,o=e?y.get(e):null,r=function(e){const o=[],t=e=>String(e||"").replace(/[\\/]+$/,""),r=t(e),n=e=>{const n=t(e);n&&n!==r&&!o.includes(n)&&o.push(n)};let s=c;if(void 0===s)try{s=require("./git-scope.js")}catch{s=null}try{s&&"function"==typeof s.gitRoot&&n(s.gitRoot(e))}catch{}try{credentialsLib&&"function"==typeof credentialsLib.aegisHome&&n(credentialsLib.aegisHome())}catch{}return o}(t.cwd),n=await claudePro.runClaudePro({prompt:proTurnPrompt(t),model:t.model&&"default"!==t.model?t.model:void 0,system:t.system,cwd:t.cwd,addDir:r,resumeSessionId:o||void 0,gate:"function"==typeof a?!a():void 0,signal:t.signal,onDelta:t.onDelta,onSpawn:(e,o)=>{t.onDelta&&o&&t.onDelta({delta:"",note:claudePro.childLine(o)})}});return e&&n&&n.sessionId&&!n.error&&y.set(e,n.sessionId),n}throw new Error(`dispatch: unknown model class ${JSON.stringify(o)} — this build ships 'aegis', 'byok', 'local' and 'pro' only`)}async function A(t,r){const n=t&&t.class,s=t&&t.model,a=reasoningBudget("byok"===n?splitByokModel(s).model:s,t&&t.maxTokens,t&&t.effort),l=statedCapOf(t),c="aegis"===n&&Boolean(t&&t.autonomous),m=Boolean(t&&t.roundsAsk),g=t&&t.sessionId||randomUUID(),h=Number.isInteger(t&&t.depth)?t.depth:0,y=t&&t.rootSessionId||g,k=t&&t.rootOnDelta||r,v="function"==typeof r?e=>e&&r({reasoning:e}):void 0,b=new AbortController;d.set(g,b);const w=b.signal,A=!(t&&!1===t.tools),x=A?u.toolsFor({includeSubagent:h<4}):[],N=t&&t.toolChoice||null,O=t&&t.system||f(_(t)),R=Array.isArray(t&&t.messages)?t.messages.filter(Boolean).slice():[];let U=R.length,F=t&&t.prompt||"";const D=String(F||""),L=Array.isArray(t&&t.attachments)?t.attachments.filter((e=>e&&"object"==typeof e)).slice(0,attachmentsModule.MAX_ATTACHMENTS):[];let I=L.length?attachmentsModule.buildContent(F,L):F,C=null;const P=_(t),B=P.cwd,q={getShell:()=>C||(C=new ShellSession({cwd:_(t).cwd})),signal:w,cwd:B,desktopdir:P.desktopdir};try{const d="byok"===n?splitByokModel(s):null,f="byok"===n?o.get(byokNamespace(d.provider))||{}:"local"===n&&o.get("local")||{},b="byok"===n?o.rawKey(byokNamespace(d.provider)):null,_="byok"!==n?null:b||providerKeyFromEnv(d.provider);if(!("byok"!==n||d.provider&&d.model)){const e=new Error('byok: model must be "<provider>:<model>" (pick one from /models) — got '+JSON.stringify(s||""));throw e.status=400,e}if("byok"===n&&!_){const e="anthropic"===d.provider?claudePro.claudeProStatus({env:process.env}):null,o=providerKeyRecord(d.provider).rejected,t=new Error(o?`${o}. That is why this turn has no ${d.provider} key: an env value that short is a paste that lost its payload, not a credential. Fix ${o.split(" ")[0]} in ~/.aegiscode/.env (or the shell that exported it) — or skip keys entirely: /byok-key ${d.provider} <key> to set one here.`:e&&e.loggedIn?`No Anthropic API key on this machine — an "anthropic:…" id is served by your own console key, which a Claude subscription is not. Use the subscription instead: /class pro (it spends your Claude Code ${e.subscription||"Pro"} plan through the claude CLI) — or add a real console key: /byok-key anthropic <key>.`:`No key for "${d.provider}" yet. Easiest fix: /class aegis (uses your AEGIS key, no setup) — or add this provider's own key: /byok-key ${d.provider} <key>.`);throw t.status=400,t}if("byok"===n&&!e.apiKey){const e=new Error("No AEGIS key connected yet. Easiest fix: /class aegis (skips BYOK entirely) — or add your AEGIS key with /login, then try again.");throw e.status=401,e}if("local"===n){const e=i.remoteRefusal(f.baseURL||i.DEFAULT_BASE);if(e)throw e}if("byok"===n&&"custom"===d.provider&&!(f.baseURL||"").trim()){const e=new Error('No endpoint saved for the "custom" provider — its key is on this machine but the address it dials is not, and no default exists for a vendor AEGIS does not know. Fix: /model-add custom <https-base-url> <api-key> <model-id> (writes both halves), or the endpoint field in Settings › Provider (custom).');throw e.status=400,e.code="custom_endpoint_missing",e}const C={cls:n,model:s,mode:t&&t.mode,maxTokens:a,statedMaxTokens:l,autonomous:c,sessionId:g,signal:w,onDelta:r,cfg:f,apiKey:_,toolChoice:N,cwd:B,rootSessionId:y,sessionKey:t&&t.sessionKey||void 0,effort:t&&t.effort,workers:t&&t.workers,recallDeep:t&&!0===t.recallDeep,singlePass:t&&!0===t.singlePass,onReasoning:v,idleTimeoutMs:c?9e5:void 0,stream:!t||!1!==t.stream};let P=!1,j=!1;const K=c?"AEGIS_AUTONOMOUS_MAX_ROUNDS":"AEGIS_CHAT_MAX_ROUNDS",$=(()=>{const e=Number.parseInt(process.env[K]||"",10);return Number.isFinite(e)&&e>0?e:0})(),G=$||(c?40:24);let Y=p.keyFor(t,R),W=p.take(Y);if(!W&&!p.isStatedKey(t)){const e=p.adopt();e&&(W=e.entry,Y=e.key)}if(W){const e=p.resumePreamble(W);0===R.length?Array.isArray(W.messages)&&W.messages.length&&R.push(...W.messages):Array.isArray(W.added)&&W.added.length&&R.push(...W.added),F?(F=`${e}\n\n${F}`,I=L.length?attachmentsModule.buildContent(F,L):F):(R.push({role:"user",content:e}),I=""),k&&k({delta:`\n\n[resuming work this session left unfinished at ${W.rounds} tool rounds`+(W.interruptions>1?` (cut off ${W.interruptions}×)`:"")+"…]\n"})}let z=$||G+(W?p.bonus(G):0),H=0;const V=G,X=8;let J=0;const Q={calls:0},Z=["input_tokens","output_tokens","prompt_tokens","completion_tokens","total_tokens","cache_read_input_tokens","cache_creation_input_tokens","prompt_cache_hit_tokens","prompt_cache_miss_tokens","reasoning_tokens","thinking_tokens"],ee=e=>{const o=e&&e.usage;if(o&&"object"==typeof o){Q.calls+=1;for(const e of Z)"number"==typeof o[e]&&Number.isFinite(o[e])&&(Q[e]=(Q[e]||0)+o[e]);if("number"!=typeof o.total_tokens){const e=(o.prompt_tokens??o.input_tokens??0)+(o.completion_tokens??o.output_tokens??0);e&&(Q.total_tokens=(Q.total_tokens||0)+e)}}},oe=e=>e&&"object"==typeof e&&Q.calls?{...e,usage:{...Q}}:e,te=()=>{if(""===I)return;const e=R[R.length-1],o=e&&"user"===e.role?flattenContent(e.content):null;e&&"user"===e.role&&o===flattenContent(I)||R.push({role:"user",content:I}),F="",I=""};U=R.length;const re=u&&u.MUTATING_TOOLS||new Set;let ne=0,se=0,ae=!1;for(;;){if(H>=z){if(m&&J<X&&!w.aborted&&await E(y,k,w,{spent:z,extensions:J+1,max:X,size:V})){J+=1;const e=z;z+=V,R.push({role:"user",content:`You have used all ${e} tool rounds allowed for this turn; ${V} more have been granted (do not restart). Continue the task from exactly where you stopped — do not re-plan, do not repeat work already done, and finish with an answer.`});continue}const e=m?"":`, or raise ${K} for a longer single turn`,o=`[stopped at ${z} tool rounds`+(Q.total_tokens?`, ${Q.total_tokens.toLocaleString()} tokens`:"")+". This session holds the work: your next message here resumes it automatically"+` (with a continuation preamble)${e}.]`,t=p.record(Y,{rounds:H,tokens:Q.total_tokens||0,note:o,chain:W?W.interruptions:0,messages:R,added:R.slice(U)});return k&&k({delta:`\n\n${o}`}),oe({model:C.model,choices:[{message:{content:o},finish_reason:"length"}],stoppedOnRounds:!0,heldForSession:!0,heldRounds:t.rounds,sessionInterruptions:t.interruptions,resumedFrom:Y})}H+=1;const e={...C,system:O,messages:R,prompt:I,tools:x,recallDeep:C.recallDeep&&1===H};let o;if(o=await S(n,e),ee(o),w.aborted)return oe(o);if(!P&&!assistantText(o)&&(isTruncated(o)||reasonedButSilent(o))){P=!0;const t=reasonedButSilent(o);if(o=await S(n,{...e,singlePass:!0,recallDeep:!1,effort:t?"high":e.effort,maxTokens:retryBudgetFor(e,t),statedMaxTokens:e.statedMaxTokens?doubledBudget(e.statedMaxTokens):void 0}),ee(o),w.aborted)return oe(o)}const a=x.length?extractToolCalls(o):[];if(!a.length){if(assistantText(o)||j||!A){if(!ae&&A&&wantsMutation(D,se>0,ne)){ae=!0,te(),R.push({role:"assistant",content:assistantText(o)}),R.push({role:"user",content:UNMUTATED_TURN_NUDGE}),k&&k({delta:""});continue}return oe(o)}j=!0,te(),R.push({role:"user",content:reasonedButSilent(o)?THOUGHT_ONLY_NUDGE:EMPTY_TURN_NUDGE});const t={...e,singlePass:!0,recallDeep:!1,messages:R,prompt:"",tools:[]};o=await S(n,t);let r=t.maxTokens,a=t.effort;if(ee(o),w.aborted)return oe(o);if(!assistantText(o)&&(isTruncated(o)||reasonedButSilent(o))){const e=reasonedButSilent(o);if(r=retryBudgetFor(t,e),a=e?"high":t.effort,o=await S(n,{...t,effort:a,maxTokens:r,statedMaxTokens:t.statedMaxTokens?doubledBudget(t.statedMaxTokens):void 0}),ee(o),w.aborted)return oe(o)}const i=(()=>{const e=Number(r)||0;if(!e)return r;const o={maxTokens:r};return t.statedMaxTokens&&(o.statedMaxTokens=t.statedMaxTokens),Math.max(e,retryBudgetFor(o,!0))})();let l=0;for(;!assistantText(o)&&l<2&&!w.aborted;){const e=reasonedButSilent(o);if(l+=1,R.push({role:"user",content:e?1===l?THOUGHT_ONLY_NUDGE:FINAL_ANSWER_NUDGE:EMPTY_TURN_NUDGE}),e&&(a="high"),r=i,o=await S(n,{...t,messages:R,effort:a,maxTokens:r,statedMaxTokens:t.statedMaxTokens?doubledBudget(t.statedMaxTokens):void 0}),ee(o),w.aborted)return oe(o)}if(!assistantText(o))throw emptyTurnError({cls:n,model:s,effort:a,recoveryRounds:l,finishReason:finishReasonOf(o),reasoningChars:reasoningTextOf(o).length,reasoningTokens:reasoningTokensOf(o)});return oe(o)}te(),R.push({role:"assistant",content:assistantText(o),tool_calls:a.map((e=>({id:e.id,type:"function",function:{name:e.name,arguments:JSON.stringify(e.args)}})))});const i=new WeakMap,c=e=>{if("exec"!==e.name)return null;if(i.has(e))return i.get(e);const o=planExec(e.args&&e.args.command,{baseCwd:B});return i.set(e,o),o},d=e=>{if(e.name===u.SUBAGENT_TOOL)return!1;if(!re.has(e.name))return!0;const o=c(e);return Boolean(o&&o.oneShot)},f=[];for(const e of a){const o=f[f.length-1];d(e)&&o&&o.parallel?o.calls.push(e):f.push({parallel:d(e),calls:[e]})}const g=async e=>{r&&r({delta:"",tool:{name:e.name,args:e.args,id:e.id,cwd:B,phase:"run"}});const o=c(e),a=o&&o.oneShot?{...q,oneShotExec:!0,cwd:o.cwd||q.cwd}:q,i=e.name===u.SUBAGENT_TOOL?await M(e.args,{cls:n,model:s,statedMaxTokens:l,effort:t&&t.effort,mode:t&&t.mode,parentSignal:w,depth:h,rootSessionId:y,rootOnDelta:k}):await T(e,{toolCtx:a,rootSessionId:y,rootOnDelta:k,signal:w});return i&&i.usage&&ee({usage:i.usage}),r&&r({delta:"",tool:{name:e.name,args:e.args,ok:i.ok,id:e.id,cwd:B,phase:"done"}}),i};for(const e of f){const o=e.parallel&&e.calls.length>1?await Promise.all(e.calls.map((e=>g(e)))):[await g(e.calls[0])];e.calls.forEach(((e,t)=>{const r=o[t];re.has(e.name)&&(ne+=1,r&&r.ok&&(se+=1)),R.push({role:"tool",tool_call_id:e.id,name:e.name,content:u.toolResultText(r)})}))}}}catch(e){throw w.aborted&&e&&"object"==typeof e&&(e.aegisCancelled=!0),e}finally{C&&C.dispose(),d.delete(g)}}async function M({description:e,subagent_type:o,prompt:t}={},{cls:r,model:n,statedMaxTokens:s,effort:a,mode:i,parentSignal:l,depth:c,rootSessionId:d,rootOnDelta:u}={}){const f=String(t||e||"").trim();if(!f)return{ok:!1,error:"task requires a prompt"};const p=o&&"general"!==o?agentRoleLabel(o):"general",m=agentSystemPrompt(o),g=randomUUID();let h;if(l){if(l.aborted)return{ok:!1,error:"aborted"};h=()=>x(g),l.addEventListener("abort",h,{once:!0})}try{const e=await A({class:r,model:n,mode:i,system:m,prompt:f,sessionId:g,depth:(c||0)+1,rootSessionId:d,rootOnDelta:u,statedMaxTokens:s,effort:a},(()=>{})),o=assistantText(e),t=e&&e.usage?{usage:e.usage}:{};return o?{ok:!0,output:o,...t}:{ok:!1,error:`subagent (${p}) produced no output`,...t}}catch(e){return{ok:!1,error:`subagent (${p}) failed: ${e&&e.message?e.message:e}`}}finally{l&&h&&l.removeEventListener("abort",h)}}function x(e){const o=d.get(e);return o&&o.abort(),{ok:Boolean(o)}}return{CLASSES:CLASSES,listClasses:async function(){return CLASSES.map((t=>{if("aegis"===t.class)return{...t,configured:Boolean(e.apiKey)};if("byok"===t.class){const e=(o.list()||[]).some((e=>!(!e||"string"!=typeof e.provider||!e.provider.startsWith("byok:"))&&(!!e.configured||Boolean(providerKeyFromEnv(e.provider.slice(BYOK_NAMESPACE_PREFIX.length))))));return{...t,configured:e}}if("local"===t.class)return{...t,configured:!0};if("pro"===t.class){const e=claudePro.claudeProStatus({env:process.env}),o=claudePro.seamAvailable();return{...t,configured:e.loggedIn,status:e,seam:o}}return{...t,configured:!1}}))},listModels:async function(t){if("aegis"===t){if(!e.apiKey)return{class:t,models:[],needsKey:!0};const o=await e.listModels();return{class:t,models:offerableCatalog(normalizeCatalog(o&&o.models))}}if("byok"===t){let r=[],n=null,s=!1,a=null;try{const o=await e.byokProviders();r=withUserModels(withCatalog(withByokAdditions(o&&o.providers||[]))),n=o&&o.fee||null}catch(e){r=[],s=!0,a=e&&e.message||String(e)}const i=[];for(const e of r){if(!e||!e.id)continue;const t=o.get(byokNamespace(e.id))||{},r=providerKeyRecord(e.id),n=r.key||"",s=Array.isArray(e.models)?e.models:[];for(const o of s){const s="string"==typeof o?o:o&&o.id;s&&i.push({id:`${e.id}:${s}`,label:`${e.label||e.id} — ${s}`,provider:e.id,configured:Boolean(t.configured||n),keyRejected:r.rejected||null})}}return{class:t,models:i,providers:r,needsProviderKey:i.length>0&&!i.some((e=>e.configured)),needsAegisKey:!e.apiKey,fee:n,providersFailed:s,providersError:a,unmatchedProviders:unmatchedUserProviders(r)}}if("local"===t){const e=(o.get("local")||{}).baseURL||i.DEFAULT_BASE,r=await i.probe(e);if(!r.running)return{class:t,models:[],baseURL:r.baseURL,needsDaemon:!0};let n=[],s=!0;try{n=await i.listTags(e)}catch{s=!1}return{class:t,models:n,baseURL:r.baseURL,listed:s}}if("pro"===t){const e=claudePro.claudeProStatus({env:process.env});return{class:t,models:claudePro.PRO_MODELS.map((o=>({id:o.id,label:o.label,note:o.note,configured:e.loggedIn}))),needsProviderKey:!1,needsAegisKey:!1,subscription:e.subscription,loggedIn:e.loggedIn,credentialFile:e.file,shadowed:e.shadowed||null,seam:claudePro.seamAvailable()}}throw new Error(`listModels: unknown model class ${JSON.stringify(t)} — this build ships 'aegis', 'byok', 'local' and 'pro' only`)},chat:A,cancel:x,respondApproval:function(e,o){const t=k.get(e);return t?(k.delete(e),t.resolve("session"===o||"once"===o?o:"deny"),{ok:!0}):{ok:!1}},respondRoundsAsk:function(e,o){const t=v.get(e);return t?(v.delete(e),t.resolve(!0===o||"continue"===o),{ok:!0}):{ok:!1}},clearSessionApprovals:function(e){return g.delete(e),h.delete(e),y.delete(e),{ok:!0}},settings:o,unloadLocalModels:function(){return i.unloadAll()},userModels:()=>loadUserModels(),addUserModel:(e,o)=>addUserModel(e,o),removeUserModel:(e,o)=>removeUserModel(e,o),discoverModels:async e=>{const t=String(null==e?"":e).trim().toLowerCase(),r=function(e){const t=String(null==e?"":e).trim().toLowerCase();if(!t)return"";try{if(o&&"function"==typeof o.rawKey){const e=o.rawKey(byokNamespace(t));if("string"==typeof e&&e.trim())return e.trim()}}catch{}return providerKeyFromEnv(t)}(t),n=await discoverVendorModels(t,{key:r,fetchImpl:l});if(!n||!n.ok)return n;const s=[];try{const e=loadUserModels().map;for(const o of Array.isArray(e[t])?e[t]:[])s.push(o)}catch{}return{...n,declared:s,endpoint:(vendorEndpointFor(t)||{}).url||""}},addUserModels:(e,o)=>{const t=Array.isArray(o)?o:[],r={provider:e,added:0,already:[],failed:[],capped:0,file:""};for(const o of t)try{const t=addUserModel(e,o);r.file=t.file||r.file,t.added?r.added+=1:r.already.push(t.model)}catch(e){const n=e&&e.message||String(e);if(/the cap/.test(n)){r.capped=t.length-r.added-r.already.length-r.failed.length;break}r.failed.push({id:String(o),reason:n})}return r},canDiscoverModels:e=>canDiscoverVendorModels(e),discoverableProviders:()=>discoverableProviders()}}module.exports={CLASSES:CLASSES,createLocalEngine:createLocalEngine,extractToolCalls:extractToolCalls,parseArgs:parseArgs,reasoningBudget:reasoningBudget,nativeEffort:nativeEffort,hostEnv:hostEnv};
3
+ const{randomUUID:e}=require("node:crypto"),o=require("node:os"),t=require("./tools.js"),n=require("./attachments.js"),{flattenContent:r}=n,s=require("./prompt.js"),a=require("./local.js"),{ShellSession:i}=require("./shell.js"),{planExec:l}=require("./exec-plan.js"),c=require("./claude-pro.js"),{agentSystemPrompt:d,agentRoleLabel:u}=require("./agents.js"),{beginTurnGuard:f,recordWrite:p,blocksDestructive:m}=require("./turn-guard.js"),{acquireWorktreeLock:h,releaseWorktreeLock:g}=require("./worktree-lock.js"),y=require("./covenant.js");let k=null;try{k=require("../../../client/env-file.js")}catch{try{k=require("../../vendor/env-file.js")}catch{k=null}}let v=null;try{v=require("../../../client/platform.js")}catch{try{v=require("../../vendor/platform.js")}catch{v=null}}let w=null;try{w=require("../../../client/credentials.js")}catch{try{w=require("../../vendor/credentials.js")}catch{w=null}}function b(e,o,n,r){const s=e&&"function"==typeof e.normalizeArgs&&e.normalizeArgs||"function"==typeof t.normalizeArgs&&t.normalizeArgs||null;return s?s(o,n,r):{ok:!0,args:n&&"object"==typeof n?n:{},error:null}}function x(e){if(!e)return null;try{const o=require("node:fs"),t=require("node:path");let n=t.resolve(String(e));for(let e=0;e<8;e+=1){if(o.existsSync(t.join(n,".git")))return"git";const e=t.dirname(n);if(e===n)break;n=e}return""}catch{return null}}function S(e={},t={},n=null){const r=e||{},s=t||{},a=(e,o)=>null!=s[e]?s[e]:o;let i=r.homedir,l=r.cwd;try{i||(i=o.homedir()),l||(l=process.cwd())}catch{}let c=r.shell,d=r.shellKind;try{if(!c||!d){const e=require("./shell.js").resolveSessionShell();c=c||e.cmd,d=d||e.kind}}catch{}let u=r.desktopdir;try{!u&&v&&(u=v.desktopDir())}catch{}let f=r.dataDir;try{!f&&w&&(f=w.aegisHome())}catch{}let p=r.locale,m=r.localeName;try{!p&&v&&"function"==typeof v.appLocale&&(p=v.appLocale()),p&&!m&&v&&"function"==typeof v.languageName&&(m=v.languageName(p))}catch{}return{platform:a("platform",r.platform||process.platform),arch:a("arch",r.arch||process.arch),homedir:a("homedir",i),desktopdir:a("desktopdir",u),dataDir:a("dataDir",f),locale:a("locale",p),localeName:a("localeName",m),languages:a("languages",r.languages),cwd:a("cwd",l),vcs:a("vcs",null!=r.vcs?r.vcs:x(l)),shell:a("shell",c),shellKind:a("shellKind",d),roots:a("roots",r.roots),appVersion:a("appVersion",r.appVersion),model:a("model",n&&n.model)}}const _=[{class:"aegis",label:"Aegis Cloud",kind:"cloud"},{class:"byok",label:"Bring your own key",kind:"cloud"},{class:"local",label:"Local model",kind:"local"},{class:"pro",label:"Claude Code Pro",kind:"subscription"}],A="byok:";function T(e){return`${A}${e}`}function M(e){const o="string"==typeof e?e:"",t=o.indexOf(":");return t<0?{provider:"",model:o}:{provider:o.slice(0,t),model:o.slice(t+1)}}function j(e){const o={key:"",env:"",rejected:null};if(!k||"function"!=typeof k.providerKeyFromEnv)return o;try{const t=k.providerKeyFromEnv(e)||o;return{key:"string"==typeof t.key?t.key:"",env:"string"==typeof t.env?t.env:"",rejected:"string"==typeof t.rejected&&t.rejected?t.rejected:null}}catch{return o}}function E(e){if(!k||"function"!=typeof k.providerKeyFromEnv)return"";try{return k.providerKeyFromEnv(e).key||""}catch{return""}}const C=/^deepseek-(v4(\.\d+)?-(flash|pro)|flash|pro|reasoner)$/,I={low:8192,medium:16384,high:32768,max:32768},$={low:"low",medium:"medium",high:"high"},N=/non-reasoning/i,q=[{provider:"deepseek",re:C,field:"effort",map:{low:"low",medium:"high",high:"high"},extra:{max:"max"}},{provider:"openai",re:/^(gpt-5|o[0-9])/i,field:"reasoning_effort",map:$},{provider:"groq",re:/^(openai\/gpt-oss|qwen\/qwen3)/i,field:"reasoning_effort",map:$},{provider:"xai",re:/^grok-(4\.[5-9]|[5-9])/,field:"reasoning_effort",map:$},{provider:"google",re:/^gemini-(2\.5|3|[4-9])/,field:"reasoning_effort",map:{...$,medium:"high"}}];function D(e,o,t){const n=Number(o);return Number.isFinite(n)&&n>0?n:C.test(String(e||""))?I["low"===t||"medium"===t||"max"===t?t:"high"]:void 0}function L(e,o,t){const n=String(o||"");if(N.test(n))return;if(null===t)return;const r="low"===t||"medium"===t?t:"max"===t?"max":"high";for(const o of q)if(o.provider===e&&o.re.test(n)){const e=Object.prototype.hasOwnProperty.call(o.map,r)?o.map[r]:o.extra&&Object.prototype.hasOwnProperty.call(o.extra,r)?o.extra[r]:void 0;if(void 0===e)return;return{field:o.field,level:e}}}const{offerableCatalog:O}=function(){const e=[()=>require("../../../client/brain-catalog.js"),()=>require("../../vendor/brain-catalog.js")];let o=null;for(const t of e)try{return t()}catch(e){o=e}throw o}(),{withByokAdditions:U,canonicalModelId:P}=function(){const e=[()=>require("../../../client/byok-catalog.js"),()=>require("../../vendor/byok-catalog.js")];let o=null;for(const t of e)try{return t()}catch(e){o=e}throw o}(),{withUserModels:R,unmatchedUserProviders:K,load:F,addUserModel:B,removeUserModel:G}=function(){const e=[()=>require("../../../client/user-models.js"),()=>require("../../vendor/user-models.js")];let o=null;for(const t of e)try{return t()}catch(e){o=e}throw o}(),{withCatalog:z}=function(){const e=[()=>require("../../../client/catalog-client.js"),()=>require("../../vendor/catalog-client.js")];let o=null;for(const t of e)try{return t()}catch(e){o=e}throw o}(),{discoverModels:W,canDiscover:Y,endpointFor:H,discoverableProviders:J}=function(){const e=[()=>require("../../../client/model-discovery.js"),()=>require("../../vendor/model-discovery.js")];let o=null;for(const t of e)try{return t()}catch(e){o=e}throw o}();function V(e){if(null==e)return{};if("object"==typeof e)return e;try{const o=JSON.parse(String(e));return o&&"object"==typeof o?o:{}}catch{return{}}}function X(e){if(!e)return[];if(Array.isArray(e.toolCalls)&&e.toolCalls.length)return e.toolCalls.map((e=>({id:e.id||"",name:e.name||"",args:V(e.args)}))).filter((e=>e.name));const o=e.choices&&e.choices[0]&&e.choices[0].message,t=o&&o.tool_calls||[];return Array.isArray(t)?t.map((e=>{const o=e&&e.function||{};return{id:e&&e.id||"",name:o.name||e&&e.name||"",args:V(o.arguments)}})).filter((e=>e.name)):[]}function Q(e){const o=Array.isArray(e.prompt)?r(e.prompt):e.prompt;if("string"==typeof o&&o.trim())return o;const t=Array.isArray(e.messages)?e.messages:[];for(let e=t.length-1;e>=0;e-=1){const o=t[e];if(!o||"user"!==o.role)continue;const n=r(o.content);if(n.trim())return n}return o}function Z(e){const o=e&&e.choices&&e.choices[0]&&e.choices[0].message;return o&&"string"==typeof o.content&&o.content||""}function ee(e){const o=e&&e.choices&&e.choices[0];return o&&o.finish_reason||e&&e.stop_reason||""}function oe(e){const o=ee(e);return"length"===o||"max_tokens"===o}function te(e){if(!e)return"";const o=e.choices&&e.choices[0],t=o&&o.message||{};if(Array.isArray(t.content)){const e=t.content.filter((e=>e&&("thinking"===e.type||"reasoning"===e.type))).map((e=>e.thinking||e.text||"")).join("");if(e)return e}const n=t.content&&"object"==typeof t.content?t.content.reasoning_content:"",r=[t.reasoning_content,t.reasoning,o&&o.reasoning_content,e.reasoning_content,e.reasoning,n];for(const e of r)if("string"==typeof e&&e)return e;return""}function ne(e){if(!e)return 0;const o=e.choices&&e.choices[0],t=o&&o.message||{},n=e.usage||{},r=n.completion_tokens_details||n.output_tokens_details||{},s=[t.thinking_tokens,t.reasoning_tokens,o&&o.thinking_tokens,e.thinking_tokens,r.reasoning_tokens,r.thinking_tokens];for(const e of s)if("number"==typeof e&&Number.isFinite(e)&&e>0)return e;return 0}function re(e){return!Z(e)&&(""!==te(e)||ne(e)>0)}function se(e,o){const t=ae(e.maxTokens);return o&&function(e){const o=Number(e);return Number.isFinite(o)&&Object.values(I).includes(o)}(e.maxTokens)?Math.max(t,32768):t}function ae(e){const o=Number(e)||0;return o>0?2*o:8192}const ie="Your previous reply came back empty — it contained no answer and no tool call. Write your answer now, using only the information already gathered above. No tools are available in this reply, so do not call any: respond in plain prose or markdown.",le="Your previous round was spent entirely on hidden reasoning and produced no visible reply. Answer the user directly and briefly now. Do not reason, explain, or think first — write only the answer, no tools.",ce=new RegExp("\\b(?:fix|implement|add|create|write|refactor|rename|remove|delete|replace|update|patch|migrate|convert|make\\s+(?:it|them|this|that|the|sure)|change|correct|resolve|repair|address|apply|introduce|support|wire\\s+up)\\b","i");function de(e,o,t){if(o)return!1;if(!(t>0))return!1;const n=String(e||"");return!!n.trim()&&!/\?\s*$/.test(n.trim())&&ce.test(n)}function ue({cls:e,model:o,finishReason:t,reasoningChars:n,reasoningTokens:r,effort:s,recoveryRounds:a}){const i=Number(a)||0,l=Number(r)||0,c=new Error(`The model returned no answer after ${e}/${o} was asked to summarise its results`+(i?`, and ${i} extra recovery call${1===i?"":"s"} with a larger budget and a changed ask came back empty too`:"")+` (stop reason: ${t||"none"}`+(s?`, effort: ${s}`:"")+(n?`, hidden reasoning: ${n} chars and no visible text`:l>0?`, ~${l} thinking tokens billed and no visible text`:"")+"). "+(n||l>0?"Every one of those calls spent its output on hidden reasoning instead of writing a word, so this is the model rather than the budget: pick a model that answers without a thinking pass, or ask for a smaller piece of work.":"No visible text came back from any of those calls. Send the request again, in smaller pieces, or from a different model."));return c.status=502,c}module.exports={CLASSES:_,createLocalEngine:function({aegis:o,settings:f,tools:h,promptBuilder:g,recallProvider:k,env:v,getConfirmMode:x,localTransport:A=a,fetchImpl:C,gitScope:I}){const $=new Map,N=h||t,q=g&&g.buildSystemPrompt||s.buildSystemPrompt,V=require("./session-rounds.js"),ce=()=>{if("function"==typeof x)return!1!==x();if(f&&"function"==typeof f.getConfirmMode){const e=f.getConfirmMode();return void 0===e||Boolean(e)}return!0},fe=new Map,pe=new Map,me=new Map,he=new Map,ge=new Map;function ye(e){return`${e} was not executed — the user denied this tool for this conversation. Do NOT retry it and do NOT attempt the same effect by another route (another command, a writeFile instead of an edit, a subagent). Stop calling tools and reply in plain text: say what you were trying to do, what you need, and that the user can re-enable ${e} to let it proceed.`}function ke(o,t,n,r){return new Promise((s=>{if(n&&n.aborted)return void s(!1);const a=e();let i=!1;const l=()=>c(!1),c=e=>{i||(i=!0,ge.delete(a),n&&n.removeEventListener("abort",l),s(e))};n&&n.addEventListener("abort",l,{once:!0}),ge.set(a,{resolve:c}),"function"==typeof t?t({delta:"",rounds:{id:a,sessionId:o,spent:r.spent,extensions:r.extensions,max:r.max,size:r.size}}):c(!1)}))}async function ve(e,o,t){const n=b(N,e,o,t||{});if(!n.ok)return{ok:!1,error:n.error};o=n.args;const r=t&&t.guard;if(r&&"exec"===e){const e=m(r,o&&o.command);if(!e.ok)return{ok:!1,error:e.reason}}const s=y.preActionAssert({tool:e,args:o||{}});if(!s.allowed){const t=y.bindRefusal({tool:e,args:o||{}},s);return{ok:!1,error:`refused by the ÆGIS covenant — ${s.clause} (${s.label}): ${s.reason}`,covenant:t}}const a=await N.executeTool(e,o,t);return r&&("writeFile"===e||"editFile"===e)&&a&&!1!==a.ok&&p(r,o&&o.file_path),a}async function we(o,{toolCtx:t,rootSessionId:n,rootOnDelta:r,signal:s}){const{name:a}=o,i=b(N,a,o.args,t||{});if(!i.ok)return{ok:!1,error:i.error};const l=i.args;if(!N.MUTATING_TOOLS.has(a))return ve(a,l,t);if(!ce())return ve(a,l,t);if(function(e,o){const t=fe.get(e);return Boolean(t&&t.has(o))}(n,a))return ve(a,l,t);if(function(e,o){const t=pe.get(e);return Boolean(t&&t.has(o))}(n,a))return{ok:!1,error:ye(a)};let c=null;if(("writeFile"===a||"editFile"===a)&&(c=N.previewMutation(a,l,t||{}),!c.ok))return{ok:!1,error:c.error};const d=await function(o,t,n,r){return new Promise((s=>{if(n&&n.aborted)return void s("cancel");const a=e();let i=!1;const l=()=>c("cancel"),c=e=>{i||(i=!0,he.delete(a),n&&n.removeEventListener("abort",l),s(e))};n&&n.addEventListener("abort",l,{once:!0}),he.set(a,{resolve:c}),"function"==typeof t?t({delta:"",approval:{id:a,sessionId:o,tool:r.tool,args:r.args,diff:r.diff||null}}):c("cancel")}))}(n,r,s,{tool:a,args:l,diff:c&&c.diff});if("deny"===d)return function(e,o){pe.has(e)||pe.set(e,new Set),pe.get(e).add(o)}(n,a),{ok:!1,error:ye(a)};if("session"!==d&&"once"!==d)return{ok:!1,error:`${a} was not executed — the request was cancelled.`};if("session"===d&&function(e,o){fe.has(e)||fe.set(e,new Set),fe.get(e).add(o)}(n,a),c){const e=N.applyChecked(a,l,c,t||{});return e&&!1!==e.ok&&t&&t.guard&&p(t.guard,l&&l.file_path),e}return ve(a,l,t)}function be(e){return S(v||{},e&&e.env||{},e)}async function xe(e,t){if("aegis"===e){const e=!t.singlePass&&(!!t.autonomous||void 0);return o.chatCompletion({prompt:t.prompt,system:t.system,messages:t.messages,model:t.model,mode:t.mode,maxTokens:t.statedMaxTokens,stream:!1!==t.stream,includeUsage:!0,onStream:t.onDelta,onReasoning:t.onReasoning,idleTimeoutMs:t.idleTimeoutMs,signal:t.signal,extra:{aegis_recall:!0,...t.recallDeep?{aegis_recall_deep:!0}:{},session:t.sessionId,...void 0===e?{}:{brain:e},...!1===e?{mode:"brain"}:{},...t.effort?{effort:t.effort}:{},...!0===e&&t.workers?{workers:t.workers}:{},...t.tools.length?{tools:t.tools}:{},...t.toolChoice?{tool_choice:t.toolChoice}:{}},agentKey:t.tools.length&&(process.env.AEGIS_AGENT_KEY||"").trim()||void 0})}if("byok"===e){const{provider:e,model:n}=M(t.model),r=P(e,n),s=L(e,r,t.effort);try{return await o.byokChatCompletion({provider:e,model:r,providerKey:t.apiKey,baseURL:t.cfg&&t.cfg.baseURL,prompt:t.prompt,system:t.system,messages:t.messages,maxTokens:t.maxTokens,tools:t.tools,toolChoice:t.toolChoice,effort:s&&"effort"===s.field?s.level:void 0,reasoningEffort:s&&"reasoning_effort"===s.field?s.level:void 0,stream:!0,onStream:t.onDelta,signal:t.signal})}catch(e){if(e&&402===e.status){const e=new Error("byok: this account has no AEGIS balance left, and the BYOK handling fee is billed there — your provider key is still valid, this is not a key problem. Top up the account, then try again (or /class aegis to use the pooled lane).");throw e.status=402,e}throw e}}if("local"===e){const e=t.cfg&&t.cfg.baseURL||A.DEFAULT_BASE,o=o=>A.chat({baseURL:e,model:t.model,prompt:t.prompt,system:t.system,messages:t.messages,maxTokens:t.maxTokens,signal:t.signal,onDelta:t.onDelta,...o&&t.tools.length?{tools:t.tools,toolChoice:t.toolChoice}:{}});try{return await o(!0)}catch(e){if(t.tools.length&&e&&400===e.status)return o(!1);throw e}}if("pro"===e){const e=t.sessionKey||t.rootSessionId||t.sessionId,o=e?me.get(e):null,n=function(e){const o=[],t=e=>String(e||"").replace(/[\\/]+$/,""),n=t(e),r=e=>{const r=t(e);r&&r!==n&&!o.includes(r)&&o.push(r)};let s=I;if(void 0===s)try{s=require("./git-scope.js")}catch{s=null}try{s&&"function"==typeof s.gitRoot&&r(s.gitRoot(e))}catch{}try{w&&"function"==typeof w.aegisHome&&r(w.aegisHome())}catch{}return o}(t.cwd),r=await c.runClaudePro({prompt:Q(t),model:t.model&&"default"!==t.model?t.model:void 0,system:t.system,cwd:t.cwd,addDir:n,resumeSessionId:o||void 0,gate:"function"==typeof x?!x():void 0,signal:t.signal,onDelta:t.onDelta,onSpawn:(e,o)=>{t.onDelta&&o&&t.onDelta({delta:"",note:c.childLine(o)})}});return e&&r&&r.sessionId&&!r.error&&me.set(e,r.sessionId),r}throw new Error(`dispatch: unknown model class ${JSON.stringify(e)} — this build ships 'aegis', 'byok', 'local' and 'pro' only`)}async function Se(t,s){const a=t&&t.class,d=t&&t.model,u=D("byok"===a?M(d).model:d,t&&t.maxTokens,t&&t.effort),p=function(e){const o=e=>{const o=Number(e);return Number.isFinite(o)&&o>0?o:void 0};return e&&Object.prototype.hasOwnProperty.call(e,"statedMaxTokens")?o(e.statedMaxTokens):o(e&&e.maxTokens)}(t),m="aegis"===a&&Boolean(t&&t.autonomous),h=Boolean(t&&t.roundsAsk),g=t&&t.sessionId||e(),y=Number.isInteger(t&&t.depth)?t.depth:0,k=t&&t.rootSessionId||g,v=t&&t.rootOnDelta||s,w="function"==typeof s?e=>e&&s({reasoning:e}):void 0,b=new AbortController;$.set(g,b);const x=b.signal,S=!(t&&!1===t.tools),_=S?N.toolsFor({includeSubagent:y<4}):[],C=t&&t.toolChoice||null,I=t&&t.system||q(be(t)),L=Array.isArray(t&&t.messages)?t.messages.filter(Boolean).slice():[];let O=L.length,U=t&&t.prompt||"";const P=String(U||""),R=Array.isArray(t&&t.attachments)?t.attachments.filter((e=>e&&"object"==typeof e)).slice(0,n.MAX_ATTACHMENTS):[];let K=R.length?n.buildContent(U,R):U,F=null;const B=be(t),G=B.cwd,z={getShell:()=>F||(F=new i({cwd:be(t).cwd})),signal:x,cwd:G,desktopdir:B.desktopdir};try{const e="byok"===a?M(d):null,i="byok"===a?f.get(T(e.provider))||{}:"local"===a&&f.get("local")||{},b="byok"===a?f.rawKey(T(e.provider)):null,$="byok"!==a?null:b||E(e.provider);if(!("byok"!==a||e.provider&&e.model)){const e=new Error('byok: model must be "<provider>:<model>" (pick one from /models) — got '+JSON.stringify(d||""));throw e.status=400,e}if("byok"===a&&!$){const o="anthropic"===e.provider?c.claudeProStatus({env:process.env}):null,t=j(e.provider).rejected,n=new Error(t?`${t}. That is why this turn has no ${e.provider} key: an env value that short is a paste that lost its payload, not a credential. Fix ${t.split(" ")[0]} in ~/.aegiscode/.env (or the shell that exported it) — or skip keys entirely: /byok-key ${e.provider} <key> to set one here.`:o&&o.loggedIn?`No Anthropic API key on this machine — an "anthropic:…" id is served by your own console key, which a Claude subscription is not. Use the subscription instead: /class pro (it spends your Claude Code ${o.subscription||"Pro"} plan through the claude CLI) — or add a real console key: /byok-key anthropic <key>.`:`No key for "${e.provider}" yet. Easiest fix: /class aegis (uses your AEGIS key, no setup) — or add this provider's own key: /byok-key ${e.provider} <key>.`);throw n.status=400,n}if("byok"===a&&!o.apiKey){const e=new Error("No AEGIS key connected yet. Easiest fix: /class aegis (skips BYOK entirely) — or add your AEGIS key with /login, then try again.");throw e.status=401,e}if("local"===a){const e=A.remoteRefusal(i.baseURL||A.DEFAULT_BASE);if(e)throw e}if("byok"===a&&"custom"===e.provider&&!(i.baseURL||"").trim()){const e=new Error('No endpoint saved for the "custom" provider — its key is on this machine but the address it dials is not, and no default exists for a vendor AEGIS does not know. Fix: /model-add custom <https-base-url> <api-key> <model-id> (writes both halves), or the endpoint field in Settings › Provider (custom).');throw e.status=400,e.code="custom_endpoint_missing",e}const q={cls:a,model:d,mode:t&&t.mode,maxTokens:u,statedMaxTokens:p,autonomous:m,sessionId:g,signal:x,onDelta:s,cfg:i,apiKey:$,toolChoice:C,cwd:G,rootSessionId:k,sessionKey:t&&t.sessionKey||void 0,effort:t&&t.effort,workers:t&&t.workers,recallDeep:t&&!0===t.recallDeep,singlePass:t&&!0===t.singlePass,onReasoning:w,idleTimeoutMs:m?9e5:void 0,stream:!t||!1!==t.stream};let D=!1,F=!1;const B=m?"AEGIS_AUTONOMOUS_MAX_ROUNDS":"AEGIS_CHAT_MAX_ROUNDS",W=(()=>{const e=Number.parseInt(process.env[B]||"",10);return Number.isFinite(e)&&e>0?e:0})(),Y=W||(m?40:24);let H=V.keyFor(t,L),J=V.take(H);if(!J&&!V.isStatedKey(t)){const e=V.adopt();e&&(J=e.entry,H=e.key)}if(J){const e=V.resumePreamble(J);0===L.length?Array.isArray(J.messages)&&J.messages.length&&L.push(...J.messages):Array.isArray(J.added)&&J.added.length&&L.push(...J.added),U?(U=`${e}\n\n${U}`,K=R.length?n.buildContent(U,R):U):(L.push({role:"user",content:e}),K=""),v&&v({delta:`\n\n[resuming work this session left unfinished at ${J.rounds} tool rounds`+(J.interruptions>1?` (cut off ${J.interruptions}×)`:"")+"…]\n"})}let Q=W||Y+(J?V.bonus(Y):0),ce=0;const fe=Y,pe=8;let me=0;const he={calls:0},ge=["input_tokens","output_tokens","prompt_tokens","completion_tokens","total_tokens","cache_read_input_tokens","cache_creation_input_tokens","prompt_cache_hit_tokens","prompt_cache_miss_tokens","reasoning_tokens","thinking_tokens"],ye=e=>{const o=e&&e.usage;if(o&&"object"==typeof o){he.calls+=1;for(const e of ge)"number"==typeof o[e]&&Number.isFinite(o[e])&&(he[e]=(he[e]||0)+o[e]);if("number"!=typeof o.total_tokens){const e=(o.prompt_tokens??o.input_tokens??0)+(o.completion_tokens??o.output_tokens??0);e&&(he.total_tokens=(he.total_tokens||0)+e)}}},ve=e=>e&&"object"==typeof e&&he.calls?{...e,usage:{...he}}:e,be=()=>{if(""===K)return;const e=L[L.length-1],o=e&&"user"===e.role?r(e.content):null;e&&"user"===e.role&&o===r(K)||L.push({role:"user",content:K}),U="",K=""};O=L.length;const Se=N&&N.MUTATING_TOOLS||new Set;let Ae=0,Te=0,Me=!1;for(;;){if(ce>=Q){if(h&&me<pe&&!x.aborted&&await ke(k,v,x,{spent:Q,extensions:me+1,max:pe,size:fe})){me+=1;const e=Q;Q+=fe,L.push({role:"user",content:`You have used all ${e} tool rounds allowed for this turn; ${fe} more have been granted (do not restart). Continue the task from exactly where you stopped — do not re-plan, do not repeat work already done, and finish with an answer.`});continue}const e=h?"":`, or raise ${B} for a longer single turn`,o=`[stopped at ${Q} tool rounds`+(he.total_tokens?`, ${he.total_tokens.toLocaleString()} tokens`:"")+". This session holds the work: your next message here resumes it automatically"+` (with a continuation preamble)${e}.]`,t=V.record(H,{rounds:ce,tokens:he.total_tokens||0,note:o,chain:J?J.interruptions:0,messages:L,added:L.slice(O)});return v&&v({delta:`\n\n${o}`}),ve({model:q.model,choices:[{message:{content:o},finish_reason:"length"}],stoppedOnRounds:!0,heldForSession:!0,heldRounds:t.rounds,sessionInterruptions:t.interruptions,resumedFrom:H})}ce+=1;const e={...q,system:I,messages:L,prompt:K,tools:_,recallDeep:q.recallDeep&&1===ce};let o;if(o=await xe(a,e),ye(o),x.aborted)return ve(o);if(!D&&!Z(o)&&(oe(o)||re(o))){D=!0;const t=re(o);if(o=await xe(a,{...e,singlePass:!0,recallDeep:!1,effort:t?"high":e.effort,maxTokens:se(e,t),statedMaxTokens:e.statedMaxTokens?ae(e.statedMaxTokens):void 0}),ye(o),x.aborted)return ve(o)}const n=_.length?X(o):[];if(!n.length){if(Z(o)||F||!S){if(!Me&&S&&de(P,Te>0,Ae)){Me=!0,be(),L.push({role:"assistant",content:Z(o)}),L.push({role:"user",content:"You ended the turn without changing any file, but this request asked for a change. The tools are still available in this reply: make the edit now with editFile or writeFile. If you already know what to change, change it — describing the fix is not the fix. If you genuinely cannot, say precisely what blocks you."}),v&&v({delta:""});continue}return ve(o)}F=!0,be(),L.push({role:"user",content:re(o)?le:ie});const t={...e,singlePass:!0,recallDeep:!1,messages:L,prompt:"",tools:[]};o=await xe(a,t);let n=t.maxTokens,r=t.effort;if(ye(o),x.aborted)return ve(o);if(!Z(o)&&(oe(o)||re(o))){const e=re(o);if(n=se(t,e),r=e?"high":t.effort,o=await xe(a,{...t,effort:r,maxTokens:n,statedMaxTokens:t.statedMaxTokens?ae(t.statedMaxTokens):void 0}),ye(o),x.aborted)return ve(o)}const s=(()=>{const e=Number(n)||0;if(!e)return n;const o={maxTokens:n};return t.statedMaxTokens&&(o.statedMaxTokens=t.statedMaxTokens),Math.max(e,se(o,!0))})();let i=0;for(;!Z(o)&&i<2&&!x.aborted;){const e=re(o);if(i+=1,L.push({role:"user",content:e?1===i?le:"Write your answer now, in plain prose, using only what is already in this conversation. If your information is incomplete, say what you have and what is missing — an incomplete answer is the expected outcome here and is better than none. No tools, no preface.":ie}),e&&(r="high"),n=s,o=await xe(a,{...t,messages:L,effort:r,maxTokens:n,statedMaxTokens:t.statedMaxTokens?ae(t.statedMaxTokens):void 0}),ye(o),x.aborted)return ve(o)}if(!Z(o))throw ue({cls:a,model:d,effort:r,recoveryRounds:i,finishReason:ee(o),reasoningChars:te(o).length,reasoningTokens:ne(o)});return ve(o)}be(),L.push({role:"assistant",content:Z(o),tool_calls:n.map((e=>({id:e.id,type:"function",function:{name:e.name,arguments:JSON.stringify(e.args)}})))});const r=new WeakMap,i=e=>{if("exec"!==e.name)return null;if(r.has(e))return r.get(e);const o=l(e.args&&e.args.command,{baseCwd:G});return r.set(e,o),o},c=e=>{if(e.name===N.SUBAGENT_TOOL)return!1;if(!Se.has(e.name))return!0;const o=i(e);return Boolean(o&&o.oneShot)},u=[];for(const e of n){const o=u[u.length-1];c(e)&&o&&o.parallel?o.calls.push(e):u.push({parallel:c(e),calls:[e]})}const f=async e=>{s&&s({delta:"",tool:{name:e.name,args:e.args,id:e.id,cwd:G,phase:"run"}});const o=i(e),n=o&&o.oneShot?{...z,oneShotExec:!0,cwd:o.cwd||z.cwd}:z,r=e.name===N.SUBAGENT_TOOL?await _e(e.args,{cls:a,model:d,statedMaxTokens:p,effort:t&&t.effort,mode:t&&t.mode,parentSignal:x,depth:y,rootSessionId:k,rootOnDelta:v}):await we(e,{toolCtx:n,rootSessionId:k,rootOnDelta:v,signal:x});return r&&r.usage&&ye({usage:r.usage}),s&&s({delta:"",tool:{name:e.name,args:e.args,ok:r.ok,id:e.id,cwd:G,phase:"done"}}),r};for(const e of u){const o=e.parallel&&e.calls.length>1?await Promise.all(e.calls.map((e=>f(e)))):[await f(e.calls[0])];e.calls.forEach(((e,t)=>{const n=o[t];Se.has(e.name)&&(Ae+=1,n&&n.ok&&(Te+=1)),L.push({role:"tool",tool_call_id:e.id,name:e.name,content:N.toolResultText(n)})}))}}}catch(e){throw x.aborted&&e&&"object"==typeof e&&(e.aegisCancelled=!0),e}finally{F&&F.dispose(),$.delete(g)}}async function _e({description:o,subagent_type:t,prompt:n}={},{cls:r,model:s,statedMaxTokens:a,effort:i,mode:l,parentSignal:c,depth:f,rootSessionId:p,rootOnDelta:m}={}){const h=String(n||o||"").trim();if(!h)return{ok:!1,error:"task requires a prompt"};const g=t&&"general"!==t?u(t):"general",y=d(t),k=e();let v;if(c){if(c.aborted)return{ok:!1,error:"aborted"};v=()=>Ae(k),c.addEventListener("abort",v,{once:!0})}try{const e=await Se({class:r,model:s,mode:l,system:y,prompt:h,sessionId:k,depth:(f||0)+1,rootSessionId:p,rootOnDelta:m,statedMaxTokens:a,effort:i},(()=>{})),o=Z(e),t=e&&e.usage?{usage:e.usage}:{};return o?{ok:!0,output:o,...t}:{ok:!1,error:`subagent (${g}) produced no output`,...t}}catch(e){return{ok:!1,error:`subagent (${g}) failed: ${e&&e.message?e.message:e}`}}finally{c&&v&&c.removeEventListener("abort",v)}}function Ae(e){const o=$.get(e);return o&&o.abort(),{ok:Boolean(o)}}return{CLASSES:_,listClasses:async function(){return _.map((e=>{if("aegis"===e.class)return{...e,configured:Boolean(o.apiKey)};if("byok"===e.class){const o=(f.list()||[]).some((e=>!(!e||"string"!=typeof e.provider||!e.provider.startsWith("byok:"))&&(!!e.configured||Boolean(E(e.provider.slice(5))))));return{...e,configured:o}}if("local"===e.class)return{...e,configured:!0};if("pro"===e.class){const o=c.claudeProStatus({env:process.env}),t=c.seamAvailable();return{...e,configured:o.loggedIn,status:o,seam:t}}return{...e,configured:!1}}))},listModels:async function(e){if("aegis"===e){if(!o.apiKey)return{class:e,models:[],needsKey:!0};const n=await o.listModels();return{class:e,models:O((t=n&&n.models,Array.isArray(t)?t.map((e=>"string"==typeof e?{id:e}:e)).filter((e=>e&&e.id)):[]))}}var t;if("byok"===e){let t=[],n=null,r=!1,s=null;try{const e=await o.byokProviders();t=R(z(U(e&&e.providers||[]))),n=e&&e.fee||null}catch(e){t=[],r=!0,s=e&&e.message||String(e)}const a=[];for(const e of t){if(!e||!e.id)continue;const o=f.get(T(e.id))||{},t=j(e.id),n=t.key||"",r=Array.isArray(e.models)?e.models:[];for(const s of r){const r="string"==typeof s?s:s&&s.id;r&&a.push({id:`${e.id}:${r}`,label:`${e.label||e.id} — ${r}`,provider:e.id,configured:Boolean(o.configured||n),keyRejected:t.rejected||null})}}return{class:e,models:a,providers:t,needsProviderKey:a.length>0&&!a.some((e=>e.configured)),needsAegisKey:!o.apiKey,fee:n,providersFailed:r,providersError:s,unmatchedProviders:K(t)}}if("local"===e){const o=(f.get("local")||{}).baseURL||A.DEFAULT_BASE,t=await A.probe(o);if(!t.running)return{class:e,models:[],baseURL:t.baseURL,needsDaemon:!0};let n=[],r=!0;try{n=await A.listTags(o)}catch{r=!1}return{class:e,models:n,baseURL:t.baseURL,listed:r}}if("pro"===e){const o=c.claudeProStatus({env:process.env});return{class:e,models:c.PRO_MODELS.map((e=>({id:e.id,label:e.label,note:e.note,configured:o.loggedIn}))),needsProviderKey:!1,needsAegisKey:!1,subscription:o.subscription,loggedIn:o.loggedIn,credentialFile:o.file,shadowed:o.shadowed||null,seam:c.seamAvailable()}}throw new Error(`listModels: unknown model class ${JSON.stringify(e)} — this build ships 'aegis', 'byok', 'local' and 'pro' only`)},chat:Se,cancel:Ae,respondApproval:function(e,o){const t=he.get(e);return t?(he.delete(e),t.resolve("session"===o||"once"===o?o:"deny"),{ok:!0}):{ok:!1}},respondRoundsAsk:function(e,o){const t=ge.get(e);return t?(ge.delete(e),t.resolve(!0===o||"continue"===o),{ok:!0}):{ok:!1}},clearSessionApprovals:function(e){return fe.delete(e),pe.delete(e),me.delete(e),{ok:!0}},settings:f,unloadLocalModels:function(){return A.unloadAll()},userModels:()=>F(),addUserModel:(e,o)=>B(e,o),removeUserModel:(e,o)=>G(e,o),discoverModels:async e=>{const o=String(null==e?"":e).trim().toLowerCase(),t=function(e){const o=String(null==e?"":e).trim().toLowerCase();if(!o)return"";try{if(f&&"function"==typeof f.rawKey){const e=f.rawKey(T(o));if("string"==typeof e&&e.trim())return e.trim()}}catch{}return E(o)}(o),n=await W(o,{key:t,fetchImpl:C});if(!n||!n.ok)return n;const r=[];try{const e=F().map;for(const t of Array.isArray(e[o])?e[o]:[])r.push(t)}catch{}return{...n,declared:r,endpoint:(H(o)||{}).url||""}},addUserModels:(e,o)=>{const t=Array.isArray(o)?o:[],n={provider:e,added:0,already:[],failed:[],capped:0,file:""};for(const o of t)try{const t=B(e,o);n.file=t.file||n.file,t.added?n.added+=1:n.already.push(t.model)}catch(e){const r=e&&e.message||String(e);if(/the cap/.test(r)){n.capped=t.length-n.added-n.already.length-n.failed.length;break}n.failed.push({id:String(o),reason:r})}return n},canDiscoverModels:e=>Y(e),discoverableProviders:()=>J()}},extractToolCalls:X,parseArgs:V,reasoningBudget:D,nativeEffort:L,hostEnv:S};