aegiscode 7.0.27 → 7.0.28

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "aegiscode",
3
3
  "productName": "AEGIS Code",
4
- "version": "7.0.27",
4
+ "version": "7.0.28",
5
5
  "description": "aegiscode — the command-line version of AEGIS Desktop. The shared tool surface in your shell, over the same thin transport and tool registry as the MCP plugin and the desktop app. Ships transport + UI only; no brain.",
6
6
  "author": {
7
7
  "name": "AEGIS Code",
@@ -1,4 +1,4 @@
1
1
  #!/usr/bin/env node
2
2
  // SPDX-License-Identifier: AGPL-3.0-or-later
3
3
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
4
- "use strict";function envVar(e){if("undefined"==typeof process||!process.env)return"";const t=process.env[e];return t&&!/^\$\{[A-Z_]+\}$/.test(t)?t:""}function envIdleMs(e){const t=envVar(e);if(!t)return 0;const n=Number(t);return Number.isFinite(n)&&n>0?n:0}const DSML_RE_INVOKE=/<\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call)\b\s*([^>]*?)\s*>([\s\S]*?)<\s*\/\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call)\b\s*>/g,DSML_RE_PARAM=/<\s*|\s*(?:DSML\s*)?|\s*(?:parameter|param|arg)\b\s*([^>]*?)\s*>([\s\S]*?)<\s*\/\s*|\s*(?:DSML\s*)?|\s*(?:parameter|param|arg)\b\s*>/g,DSML_RE_LEADER=/<\s*\/?\s*|\s*(?:DSML\s*)?|\s*(?:(?:tool|function)[_▁ ]*calls?|reasoning)[_▁ ]*(?:begin|end)?\s*>/gi,DSML_RE_ANY_TAG=/<\s*\/?\s*|\s*(?:DSML\s*)?|\s*[A-Za-z_][A-Za-z0-9_]*[^>]{0,120}>/g,DSML_RE_SKELETON=/<\s*\/?\s*(?:tool_calls|function_calls|invoke|parameter|param|reasoning)\b[^>]{0,120}>/gi,DSML_RE_JSON_CALLS=/|[ \t]*(?:tool|function)[_▁ ]*calls?[_▁ ]*begin[ \t]*|([\s\S]*?)|[ \t]*(?:tool|function)[_▁ ]*calls?[_▁ ]*end[ \t]*|/gi,DSML_RE_JSON_CALLS_OPEN=/|[ \t]*(?:tool|function)[_▁ ]*calls?[_▁ ]*begin[ \t]*|/gi,DSML_RE_JSON_CALLS_CLOSE=/|[ \t]*(?:tool|function)[_▁ ]*calls?[_▁ ]*end[ \t]*|/gi,DSML_RE_ENVELOPE_TOKEN=/|[ \t]?[A-Za-z0-9_▁]*[ \t]?|/g,DSML_RE_DRIFT_INVOKE=/<\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call)\b\s*([^>]*?)\s*>/gi,DSML_RE_DRIFT_PARAM=/<\s*|\s*(?:DSML\s*)?|\s*(?:parameter|param|arg)\b\s*([^>]*?)\s*>/gi,DSML_RE_PARAM_CLOSE=/<\s*\/\s*|\s*(?:DSML\s*)?|\s*(?:parameter|param|arg)\b\s*>/gi,DSML_RE_ATTR=/([A-Za-z_][A-Za-z0-9_.-]*)\s*=\s*(?:"([^"]*)"|'([^']*)')/g,DSML_RE_STRUCT_TAG=/<\s*\/?\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call|parameter|param|arg|reasoning|(?:tool|function)[_▁ ]*calls?)\b/gi,DSML_RE_STRUCT_CLOSER=/<\s*\/\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call|parameter|param|arg|reasoning|(?:tool|function)[_▁ ]*calls?)\b/gi,DSML_RE_WRAPPER_TAG=/<\s*\/?\s*|\s*(?:DSML\s*)?|\s*(?!(?:invoke|call|tool_call|parameter|param|arg)\b)[A-Za-z_][A-Za-z0-9_]*[^>]{0,120}>/g,DSML_RE_TRAILING_LT=/<\s*\/?\s*$/,DSML_RE_OPEN_TOKEN=/^|[ \t]?[A-Za-z0-9_▁]*[ \t]?$/,DSML_HOLD_MAX=4194304;function dsmlAttrs(e){const t={};if(!e)return t;let n;for(DSML_RE_ATTR.lastIndex=0;n=DSML_RE_ATTR.exec(e);)t[n[1].toLowerCase()]=null!=n[2]?n[2]:n[3];return t}function dsmlJson(e){const t=String(null==e?"":e).trim();try{const e=JSON.parse(t);return void 0===e?t:e}catch{return t}}function dsmlArgs(e){const t={};let n;for(DSML_RE_PARAM.lastIndex=0;n=DSML_RE_PARAM.exec(e);){const e=dsmlAttrs(n[1]),r=e.name||e.key||`arg${Object.keys(t).length}`,o="false"===String(e.string||"").toLowerCase()||"true"===String(e.json||"").toLowerCase();t[r]=o?dsmlJson(n[2]):n[2]}return t}function decodeDeepSeekDSML(e){if("string"!=typeof e||!e||-1===e.indexOf("|"))return{text:e||"",calls:[]};const t=[];let n=e;DSML_RE_INVOKE.lastIndex=0;const r=[];let o;for(;o=DSML_RE_INVOKE.exec(n);){const e=dsmlAttrs(o[1]),n=e.name||e.function||e.tool||"";n&&t.push({name:n,args:dsmlArgs(o[2])}),r.push([o.index,o.index+o[0].length])}for(let e=r.length-1;e>=0;e--)n=n.slice(0,r[e][0])+n.slice(r[e][1]);return n=n.replace(DSML_RE_JSON_CALLS,((e,n)=>{const r=dsmlJson(n),o=Array.isArray(r)?r:r&&Array.isArray(r.tool_calls)?r.tool_calls:[];for(const e of o){const n=e&&e.function||e||{},r=n.name||e&&e.name||"";if(!r)continue;let o=null!=n.arguments?n.arguments:e&&e.arguments;"string"==typeof o&&(o=dsmlJson(o)),t.push({name:r,args:o&&"object"==typeof o?o:{}})}return""})),n=n.replace(DSML_RE_LEADER,""),{text:n,calls:t}}function decodeDeepSeekDSMLDrift(e){if("string"!=typeof e||!e||-1===e.indexOf("|"))return{text:e||"",calls:[]};const t=[];let n;for(DSML_RE_DRIFT_INVOKE.lastIndex=0;n=DSML_RE_DRIFT_INVOKE.exec(e);)t.push({at:n.index,attrs:n[1],body:DSML_RE_DRIFT_INVOKE.lastIndex});if(!t.length)return{text:e,calls:[]};const r=[];let o="",s=0;for(let n=0;n<t.length;n++){const a=n+1<t.length?t[n+1].at:e.length,i=e.slice(t[n].body,a),c=dsmlAttrs(t[n].attrs),l=c.name||c.function||c.tool||"",u={},d=[];let m;for(DSML_RE_DRIFT_PARAM.lastIndex=0;m=DSML_RE_DRIFT_PARAM.exec(i);)d.push({at:m.index,attrs:m[1],from:DSML_RE_DRIFT_PARAM.lastIndex});for(let e=0;e<d.length;e++){const t=e+1<d.length?d[e+1].at:i.length,n=i.slice(d[e].from,t).replace(DSML_RE_PARAM_CLOSE,""),r=dsmlAttrs(d[e].attrs),o=r.name||r.key||`arg${Object.keys(u).length}`,s="false"===String(r.string||"").toLowerCase();u[o]=s?dsmlJson(n):n}o+=e.slice(s,t[n].at),s=a,l&&r.push({name:l,args:u})}return o+=e.slice(s),{text:o,calls:r}}function dsmlResidue(e){return e?-1===e.indexOf("|")?e.replace(DSML_RE_SKELETON,""):e.replace(DSML_RE_ANY_TAG,"").replace(DSML_RE_SKELETON,"").replace(DSML_RE_ENVELOPE_TOKEN,""):e}function dsmlUnterminated(e){return!!DSML_RE_OPEN_TOKEN.test(e)||(e.match(DSML_RE_STRUCT_TAG)||[]).length>(e.match(DSML_RE_STRUCT_CLOSER)||[]).length}function dsmlHoldFrom(e){const t=e.search(/<\s*\/?\s*|/);if(-1!==t)return t;const n=e.search(DSML_RE_JSON_CALLS_OPEN);if(-1!==n&&-1===e.slice(n).search(DSML_RE_JSON_CALLS_CLOSE))return n;const r=DSML_RE_TRAILING_LT.exec(e);if(r)return r.index;const o=e.indexOf("|");return-1!==o&&dsmlUnterminated(e.slice(o))?o:-1}function makeDeepSeekEnvelopeStripper(){let e="";const t=[],n=n=>{e+="string"==typeof n?n:"";const r=decodeDeepSeekDSML(e);e=r.text;for(const e of r.calls)t.push(e);e=e.replace(DSML_RE_WRAPPER_TAG,"");const o=dsmlHoldFrom(e);let s;return-1!==o&&e.length-o<=DSML_HOLD_MAX?(s=e.slice(0,o),e=e.slice(o)):(s=e,e=""),dsmlResidue(s)};return n.flush=()=>{const n=decodeDeepSeekDSML(e);e="";for(const e of n.calls)t.push(e);const r=decodeDeepSeekDSMLDrift(n.text);for(const e of r.calls)t.push(e);return dsmlResidue(r.text)},n.calls=()=>t.slice(),n}function randomUUID(){const e="undefined"!=typeof globalThis&&globalThis||"undefined"!=typeof self&&self||null,t=e&&e.crypto;if(t&&"function"==typeof t.randomUUID)try{return t.randomUUID()}catch(e){}if(t&&"function"==typeof t.getRandomValues)try{const e=new Uint8Array(16);t.getRandomValues(e),e[6]=15&e[6]|64,e[8]=63&e[8]|128;const n=Array.from(e,(e=>e.toString(16).padStart(2,"0"))).join("");return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`}catch(e){}if("function"==typeof require)try{const e=require("crypto");if(e&&"function"==typeof e.randomUUID)return e.randomUUID()}catch(e){}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}))}const DEFAULT_API_BASE="https://aegiscloud.org",CLIENT_VERSION="3.2.0",DEFAULT_TIMEOUT_MS=6e4,MAX_BODY_BYTES=8388608,RATE_LIMIT_RETRIES=4,RATE_LIMIT_MAX_WAIT_MS=3e4,RATE_LIMIT_BASE_WAIT_MS=1e3,TRANSIENT_STREAM_ERROR_PATTERN=/connection reset by peer|broken pipe|connection aborted|errno 104|errno 32|errno 54|econnreset|epipe/i,TRANSIENT_STREAM_RETRIES=2,TRANSIENT_STREAM_BASE_WAIT_MS=500,TRANSIENT_SOCKET_CODE_PATTERN=/^(ECONNRESET|EPIPE|ECONNABORTED|UND_ERR_SOCKET|UND_ERR_CLOSED)$/,TRANSIENT_SOCKET_RETRIES=2,SSE_UPSTREAM_TIMEOUT_PATTERN=/request timed out|timed out waiting|upstream timeout/i;function upstreamTimeoutMessage(e,t){const n=Number(t);return`${e} — the upstream provider gave up before answering${null!=t&&Number.isFinite(n)?n>=1e3?` after ${(n/1e3).toFixed(1)}s`:` after ${Math.max(0,Math.round(n))}ms`:""}. That is the provider's own deadline, not this client's stream budget, so raising AEGIS_SSE_IDLE_TIMEOUT_MS cannot help`}function createClient(e={}){const t=(e.apiBase||envVar("AEGIS_API_BASE")||DEFAULT_API_BASE).replace(/\/+$/,"");let n=void 0!==e.apiKey?e.apiKey:envVar("AEGIS_API_KEY");const r=void 0!==e.memoryToken?e.memoryToken:envVar("AEGIS_MEMORY_TOKEN"),o=e.clientVersion||"3.2.0",s="cli"===e.channel?"cli":"desktop";function a(e){return n&&"string"==typeof e?e.split(n).join("[redacted]"):e}const i={ECONNRESET:"connection reset by the backend",ECONNREFUSED:"connection refused — is the backend running?",EPIPE:"connection closed while sending the request",ETIMEDOUT:"connection timed out",ENOTFOUND:"host not found — check the endpoint URL",EAI_AGAIN:"DNS lookup failed temporarily",EHOSTUNREACH:"host unreachable",ENETUNREACH:"network unreachable",CERT_HAS_EXPIRED:"TLS certificate has expired",DEPTH_ZERO_SELF_SIGNED_CERT:"TLS certificate is self-signed",UND_ERR_SOCKET:"the socket closed before the response finished",UND_ERR_CLOSED:"the connection was closed",UND_ERR_CONNECT_TIMEOUT:"timed out connecting to the backend",UND_ERR_HEADERS_TIMEOUT:"the backend accepted the connection but never sent a response",UND_ERR_BODY_TIMEOUT:"the backend stalled mid-response",UND_ERR_ABORTED:"the request was aborted"};function c(e,t){const n=e instanceof Error?e:new Error(String(e)),r=n&&n.name;if("AbortError"===r||"TimeoutError"===r)return e;const o=l(n),s=t||"the backend",a=new Error(o?`Could not reach ${s} (${o}).`:`Could not reach ${s}: ${n.message||"network failure"}.`);return a.status=0,a.code="network",a.networkCode=o||null,a.data=null,a.cause=n,a}function l(e,t=0){if(!e||t>4)return null;const n=e.code||e.cause&&e.cause.code,r=e.cause,o=r?l(r,t+1):null;return i[n]?i[n]:o||(r&&r.message&&r.message!==e.message?r.message:n||null)}async function u(e,n){const r=n&&n.signal,o="function"==typeof AbortController?new AbortController:null;let s=null;o&&(s=setTimeout((()=>o.abort()),S),s&&"function"==typeof s.unref&&s.unref(),r&&(r.aborted?o.abort():"function"==typeof r.addEventListener&&r.addEventListener("abort",(()=>{o&&o.abort()}),{once:!0})));try{return await fetch(e,{...n||{},signal:o?o.signal:r})}catch(e){if(o&&o.signal.aborted&&(!r||!r.aborted)){const e=new Error(`Timed out after ${S/1e3}s waiting for ${t}.`);throw e.status=0,e.code="timeout",e.data=null,e}throw c(e,t)}finally{s&&clearTimeout(s)}}function d(e,t){const n=e&&e.headers&&"function"==typeof e.headers.get?e.headers.get("retry-after"):null;let r=0;if(n){const e=Number(n);if(Number.isFinite(e)&&e>=0)r=1e3*e;else{const e=Date.parse(n);Number.isFinite(e)&&(r=e-Date.now())}}return r||(r=R*Math.pow(2,t)),Math.min(r,A)}function m(e,t){return new Promise((n=>{const r=setTimeout(n,e);if(r&&"function"==typeof r.unref&&r.unref(),t&&"function"==typeof t.addEventListener)return t.aborted?(clearTimeout(r),void n()):void t.addEventListener("abort",(()=>{clearTimeout(r),n()}),{once:!0})}))}function _(e,t=0){if(!e||t>4)return null;const n=e.code;return"string"==typeof n&&"network"!==n?n:_(e.cause,t+1)}async function f(e,t){let n=0;for(;;)try{return await u(e,t)}catch(e){const r=e&&"network"===e.code?String(_(e)||""):"";if(n>=2||!TRANSIENT_SOCKET_CODE_PATTERN.test(r))throw e;if(t&&t.signal&&t.signal.aborted)throw e;if(await m(500*Math.pow(2,n),t&&t.signal),t&&t.signal&&t.signal.aborted)throw e;n++}}async function E(e,t){let n=await f(e,t);for(let r=0;n&&429===n.status&&r<T;r++){const o=d(n,r);try{n.body&&await n.body.cancel()}catch{}await m(o,t&&t.signal),n=await f(e,t)}for(let r=0;n&&n.status>=500&&n.status<600&&r<2;r++){let o="";try{o=await g(n.clone())}catch{break}if(!TRANSIENT_STREAM_ERROR_PATTERN.test(o))break;await m(500*Math.pow(2,r),t&&t.signal),n=await f(e,t)}return n}function p(e){if(!e)return e;if("AbortError"===e.name||"TimeoutError"===e.name)return e;if("network"===e.code||"timeout"===e.code||"ABORT_ERR"===e.code)return e;if(/^stream stalled - /.test(String(e.message||"")))return e;if(!_(e))return e;const n=c(e,t);return n.bodyPhase=!0,n}async function g(e){if(!e||!e.body||"function"!=typeof e.body.getReader){let t;try{t=await e.text()}catch(e){const t=p(e);throw t&&"network"===t.code&&(t.bytesRead=0),t||e}return t.length>h?t.slice(0,h):t}const n=e.body.getReader(),r=new TextDecoder;let o="",s=0;try{for(;;){let a;try{a=await n.read()}catch(e){const t=p(e);throw t&&"network"===t.code&&(t.bytesRead=s),t||e}const{done:i,value:c}=a;if(i)break;if(s+=c?c.byteLength:0,s>h){const n=new Error(`Response from ${t} exceeded the ${h/1048576}MB cap.`);throw n.status=e.status,n.code="body_too_large",n.data=null,n}o+=r.decode(c,{stream:!0})}return o+=r.decode(),o}finally{try{await n.cancel()}catch{}}}let y=null;const S=Number(e.timeoutMs)>0?Number(e.timeoutMs):Number(envVar("AEGIS_HTTP_TIMEOUT_MS"))>0?Number(envVar("AEGIS_HTTP_TIMEOUT_MS")):6e4,h=Number(e.maxBodyBytes)>0?Number(e.maxBodyBytes):8388608,T=Number(e.rateLimitRetries)>=0?Number(e.rateLimitRetries):4,R=Number(e.rateLimitBaseWaitMs)>=0?Number(e.rateLimitBaseWaitMs):1e3,A=Number(e.rateLimitMaxWaitMs)>0?Number(e.rateLimitMaxWaitMs):3e4;function M(e,n){try{const r=new URL(`/go/${String(e||"upgrade").replace(/^\/+|\/+$/g,"")}`,t);r.searchParams.set("s",s);const o=String(n||"").trim().toLowerCase();return/^[a-z0-9][a-z0-9_-]{0,63}$/.test(o)&&r.searchParams.set("c",o),r.toString()}catch(e){return""}}function D(e){const t={"Content-Type":"application/json","X-AEGIS-Version":o,...e};return n&&(t["X-API-Key"]=n,t.Authorization=`Bearer ${n}`),t}async function L(e,n){return O(await E(`${t}${e}`,n))}async function I(e,t){let n=0;for(;;)try{return await L(e,t)}catch(e){if(!e||"network"!==e.code||!0!==e.bodyPhase||0!==e.bytesRead||n>=2)throw e;if(t&&t.signal&&t.signal.aborted)throw e;if(await m(500*Math.pow(2,n),t&&t.signal),t&&t.signal&&t.signal.aborted)throw e;n++}}async function w(e,t,n,r){return I(e,{method:"POST",headers:n||D(),body:JSON.stringify(t||{}),signal:r&&r.signal})}async function b(e,t,n){return I(e,{method:"GET",headers:t||D(),signal:n&&n.signal})}function N(e,t){const n=e||{},r=n.latest_cli||"",s=n.latest_desktop||"",a=r||s||n.required||"",i=new Error(a?`This client (v${o}) is out of date — upgrade to v${a}.`:`This client (v${o}) is out of date.`);return i.status=t,i.code="version_mismatch",i.data=n,i.upgrade={required:n.required||"",latestCli:r,latestDesktop:s,url:M("upgrade","version_gate")||n.update_url||""},i}async function O(e){const t=await g(e);let n;try{n=t?JSON.parse(t):{}}catch{n={raw:a(t)}}if(!e.ok){if(function(e,t){return 426===e||t&&"version_mismatch"===t.code}(e.status,n))throw N(n,e.status);const t=n&&(n.error?.message||n.error||n.message)||`HTTP ${e.status}`,r=new Error(a("string"==typeof t?t:JSON.stringify(t)));throw e.status>=500&&e.status<600&&SSE_UPSTREAM_TIMEOUT_PATTERN.test(r.message)?(r.serverStatus=e.status,r.status=0,r.code="timeout",r.message=upstreamTimeoutMessage(r.message)):r.status=e.status,r.data=n,r}if(n&&"version_mismatch"===n.code)throw N(n,e.status);return n}function v(e){if(!e)return"";const t=e.error;return"string"==typeof t?t:t&&"string"==typeof t.message?t.message:t&&"string"==typeof t.error?t.error:"string"==typeof e.message?e.message:"string"==typeof e.error_message?e.error_message:""}async function k(){if(r)return r;if(y)return y;const e=await w("/api/verify-api-key",{api_key:n});if(!e||!e.memory_token){const e=M("upgrade","memory_quota");throw new Error("This AEGIS account has no memory token. "+(e?`Enable cloud memory at ${e}`:"Enable cloud memory in your AEGIS account settings."))}return y=e.memory_token,y}function x(e){return{"Content-Type":"application/json","X-AEGIS-Version":o,Authorization:`Bearer ${e}`}}function U(e){if(null==e)return"";if("string"==typeof e)return e;if(!Array.isArray(e))return String(e);let t="";for(let n=0;n<e.length;n+=1){const r=e[n];r&&"object"==typeof r&&("string"==typeof r.text?t+=(t?"\n":"")+r.text:"image_url"===r.type&&(t+=(t?"\n":"")+"[image]"))}return t}function C(e,t,n){const r=Array.isArray(e)?e.filter(Boolean):[],o=[];if(t&&!r.some((e=>e&&"system"===e.role))&&o.push({role:"system",content:t}),o.push(...r),null!=n&&("string"==typeof n?""!==n:Array.isArray(n)&&n.length>0)){const e=o[o.length-1];(Array.isArray(n)&&e&&"user"===e.role?U(e.content)===U(n):e&&"user"===e.role&&e.content===n)||o.push({role:"user",content:n})}return o}function P(e){const t=e&&e.choices&&e.choices[0],n=t&&t.message&&t.message.content;return"string"==typeof n?n:""}function $(e){const t=e&&e.choices&&e.choices[0],n=t&&t.message&&t.message.content;if("string"!=typeof n||-1===n.indexOf("|"))return e;const r=decodeDeepSeekDSML(n),o=decodeDeepSeekDSMLDrift(r.text);t.message.content=dsmlResidue(o.text);const s=[...r.calls,...o.calls];return s.length&&(e.toolCalls=[...Array.isArray(e.toolCalls)?e.toolCalls:[],...s.map((e=>({id:"",name:e.name,args:e.args||{}})))]),e}async function B(e,n,r,o,s,i){const{onReasoning:c,idleTimeoutMs:l,retryWithoutStreamOptions:u,_transientStreamAttempt:d=0}=i||{},_=n=>E(`${t}${e}`,{method:"POST",headers:r,body:JSON.stringify({...n,stream:!0}),signal:s});let f;try{f=await _(n)}catch(e){throw e}if(!f.ok&&426===f.status){let e={};try{const t=await g(f);e=t?JSON.parse(t):{}}catch{e={}}throw N(e,f.status)}if(!f.ok&&u&&n.stream_options){try{f.body&&await f.body.cancel()}catch{}const e={...n};delete e.stream_options,n=e;try{f=await _(n)}catch(e){throw e}}if(!f.ok){const t={...n};delete t.stream_options;const a=$(await w(e,{...t,stream:!1},r,{signal:s})),i=P(a);return i&&o({delta:i}),a}if(!(f.headers.get("content-type")||"").includes("text/event-stream")){const e=$(await O(f)),t=P(e);return t?o({delta:t}):function(e,t){if(e&&"version_mismatch"===e.code)throw N(e,t||426);const n=a(v(e));if(!n)return;const r=new Error(n);throw r.status=t||500,r.data=e,r}(e,f.status),e}const y=f.body.getReader(),S=new TextDecoder;let h="",T="",R="",A=n.model,M=null,D="";const L=new Map;let I=null,b="";const k=makeDeepSeekEnvelopeStripper(),x=idleBudgetFor(f,l);let U=Date.now();const C=U;let K=0;async function G(){let e,t=null;const n=Math.max(0,x-(Date.now()-U)),r=new Promise(((t,r)=>{e=setTimeout((()=>{r(new Error(K>0?`stream stalled - only keep-alives for ${x/1e3}s`:`stream stalled - no data for ${x/1e3}s`))}),n)})),o=s&&"function"==typeof s.addEventListener?new Promise(((e,n)=>{t=()=>{const e=new Error("The turn was stopped.");e.name="AbortError",e.code="ABORT_ERR",n(e)},s.aborted?t():s.addEventListener("abort",t,{once:!0})})):null;try{return await(o?Promise.race([y.read(),r,o]):Promise.race([y.read(),r]))}finally{clearTimeout(e),s&&t&&"function"==typeof s.removeEventListener&&s.removeEventListener("abort",t)}}for(;;){let t,l;try{({done:t,value:l}=await G())}catch(t){y.cancel().catch((()=>{}));const a=p(t);if(a&&"network"===a.code&&(a.bytesRead=b?1:0,0===a.bytesRead&&d<2&&(!s||!s.aborted))){if(await m(500*Math.pow(2,d),s),s&&s.aborted)throw a;return B(e,n,r,o,s,{...i,_transientStreamAttempt:d+1})}throw a||t}if(t)break;h+=S.decode(l,{stream:!0});const u=h.split("\n");h=u.pop();for(const e of u){const t=e.trim();if(!t.startsWith("data:")){t.startsWith(":")&&K++;continue}U=Date.now();const n=t.slice(5).trim();if(!n||"[DONE]"===n)continue;let r;try{r=JSON.parse(n)}catch{continue}if(r.error){if(!D){const e=r.error;D="string"==typeof e?e:v({error:e})||"stream error",D=a(D)}continue}r.model&&(A=r.model),r.usage&&(M=r.usage);const s=r.choices&&r.choices[0];s&&s.finish_reason&&(I=s.finish_reason);const i=(e,t,n,r)=>{if("string"==typeof e&&e)return r(e),n+e;if("string"==typeof t&&t){if(!n)return r(t),t;if(t.startsWith(n)){const e=t.slice(n.length);return e&&r(e),t}return n}return n};R=i(s&&s.delta&&s.delta.reasoning_content,s&&s.message&&s.message.reasoning_content,R,(e=>{"function"==typeof c?c(e):o({reasoning:e})})),T=i(s&&s.delta&&s.delta.content,s&&s.message&&s.message.content,T,(e=>{const t=k(e);t&&(b+=t,o({delta:t}))}));const l=s&&s.delta&&s.delta.tool_calls||s&&s.message&&s.message.tool_calls;if(Array.isArray(l))for(const e of l){const t=null==e.index?0:e.index,n=L.get(t)||{id:"",type:"function",function:{name:"",arguments:""}};e.id&&(n.id=e.id),e.type&&(n.type=e.type);const r=e.function||{};r.name&&(n.function.name=r.name),"string"==typeof r.arguments&&(n.function.arguments+=r.arguments),L.set(t,n)}}}if(!T&&D){if(d<2&&TRANSIENT_STREAM_ERROR_PATTERN.test(D))return await m(500*Math.pow(2,d),s),B(e,n,r,o,s,{...i,_transientStreamAttempt:d+1});const t=SSE_UPSTREAM_TIMEOUT_PATTERN.test(D),a=new Error(t?upstreamTimeoutMessage(D,Date.now()-C):D);throw a.status=t?0:f.status,t&&(a.code="timeout"),a}const V=k.flush();V&&(b+=V,o({delta:V}));const F=[...L.entries()].sort(((e,t)=>e[0]-t[0])).map((([e,t])=>({...t,id:t.id||`call_${e}`}))),J={content:b};R&&(J.reasoning_content=R),F.length&&(J.tool_calls=F);const W={model:A,choices:[{message:J,...I?{finish_reason:I}:{}}]};M&&(W.usage=M);const X=k.calls();return(F.length||X.length)&&(W.toolCalls=[...F.map((e=>({id:e.id,name:e.function.name,args:e.function.arguments}))),...X.map((e=>({id:"",name:e.name,args:e.args||{}})))]),W}return{apiBase:t,get apiKey(){return n},setApiKey:function(e){return n="string"==typeof e?e.trim():"",y=null,n},get clientVersion(){return o},get channel(){return s},promptUrl:M,verifyApiKey:async function(){return w("/api/verify-api-key",{api_key:n})},registerDevice:async function(e,t){return w("/api/v1/auth/register-device",{fingerprint:e,app:t&&t.app},void 0,t)},chatCompletion:async function({prompt:e,system:t,messages:n,model:r,mode:o,maxTokens:s,stream:a=!1,onStream:i,onReasoning:c,idleTimeoutMs:l,includeUsage:u,signal:d,extra:m,agentKey:_}={}){const f={messages:C(n,t,e),...s?{max_tokens:s}:{},...m||{}};r?f.model=r:o&&(f.mode=o);const E=D(_?{"X-AEGIS-Agent-Key":_}:void 0);return a&&"function"==typeof i?(u&&(f.stream_options={include_usage:!0}),B("/api/v1/chat/completions",f,E,i,d,{onReasoning:c,idleTimeoutMs:l,retryWithoutStreamOptions:Boolean(u)})):$(await w("/api/v1/chat/completions",{...f,stream:!1},E,{signal:d}))},byokChatCompletion:async function({provider:t="openai",model:r,messages:s,prompt:a,system:i,maxTokens:c,effort:l,reasoningEffort:u,tools:d,toolChoice:m,stream:_=!1,onStream:f,signal:E,providerKey:p,baseURL:g}={}){const y=void 0!==p?p:e.providerKey;if("custom"===t&&!g){const e=new Error('the "custom" provider dials the endpoint you name, and this call names none — save the address first: /model-add custom <https-base-url> <api-key> <model-id>, or the endpoint field in Settings › Provider (custom).');throw e.status=400,e.code="custom_endpoint_missing",e}const S={provider:t,messages:C(s,i,a),...c?{max_tokens:c}:{},...l?{effort:l}:{},...u?{reasoning_effort:u}:{},...Array.isArray(d)&&d.length?{tools:d}:{},...m?{tool_choice:m}:{},...g?{base_url:g}:{}};r&&(S.model=r);const h={"Content-Type":"application/json","X-AEGIS-Version":o,"X-Provider-Key":y};return n&&(h["X-AEGIS-Key"]=n),_&&"function"==typeof f?B("/api/v1/byok/chat/completions",S,h,f,E):$(await w("/api/v1/byok/chat/completions",{...S,stream:!1},h))},listModels:async function(e){return b("/api/v1/models",null,e)},tokenBankBalance:async function(e){return b("/api/token-bank/balance",null,e)},tokenBankTopup:async function(e){return w("/api/token-bank/topup",{amount_eur:e})},billingCheckout:async function(){return w("/api/billing/checkout",{})},byokStatus:async function(e){return b("/api/user/api-keys",null,e)},byokProviders:async function(e){return b("/api/v1/byok/providers",null,e)},catalog:async function(e,t,n){const r=(e||"models").replace(/^\/+/,""),o=new URLSearchParams;for(const[e,n]of Object.entries(t||{}))null!=n&&""!==n&&o.set(e,String(n));const s=o.toString();return b(`/api/v1/catalog/${r}${s?`?${s}`:""}`,n&&n.etag?{...D(),"If-None-Match":n.etag}:D(),n)},byokSet:async function(e,t){return w("/api/user/api-keys",{provider:e,api_key:t||""})},getMemoryToken:k,memorySearch:async function(e,t){return w("/api/memory/search",{query:e||"",limit:t||5},x(await k()))},memorySave:async function(e){return w("/api/memory/save",{entry:e},x(await k()))},memoryList:async function(e){return w("/api/memory/search",{query:"",limit:e||10},x(await k()))},verifyToken:async function(e){return w("/api/verify-token",{token:e||""},{"Content-Type":"application/json","X-AEGIS-Version":o,Authorization:`Bearer ${e}`})},memoryActivate:async function(e){return w("/api/memory/activate",{},x(e||await k()))},memoryPull:async function(e){return w("/api/memory/pull",{since:e||0},x(await k()))},memorySaveBatch:async function(e){return w("/api/memory/save",{entries:e||[]},x(await k()))},conversationSyncPush:async function(e){const t=await k();return w("/api/conversations/sync",{session_id:e&&e.session_id,title:e&&e.title||"",messages:e&&e.messages||[],source:e&&e.source||"aegis-desktop"},x(t))},conversationSyncPull:async function(){return w("/api/conversations/sync",{},x(await k()))},importConversation:async function({messages:e,url:t,title:n,source:r}={}){return w("/api/import",{messages:e||[],url:t||"",title:n||"",source:r||"aegiscode-plugin"})},driveToken:async function(){try{return await b("/api/drive/token")}catch(e){if(e&&404===e.status)return{connected:!1,access_token:null,email:null};throw e}},randomUUID:randomUUID}}const SSE_IDLE_TIMEOUT_MS=6e4,BRAIN_IDLE_TIMEOUT_MS=9e5;function idleBudgetFor(e,t){const n=Number(t),r=envIdleMs("AEGIS_SSE_IDLE_TIMEOUT_MS"),o=n>0?n:r>0?r:SSE_IDLE_TIMEOUT_MS;let s="";try{const t=e&&e.headers&&"function"==typeof e.headers.get?e.headers.get.bind(e.headers):null;s=t&&t("X-AEGIS-Brain")||""}catch{s=""}const a=envIdleMs("AEGIS_BRAIN_IDLE_TIMEOUT_MS")||BRAIN_IDLE_TIMEOUT_MS;return s&&String(s).trim()?Math.max(o,a):o}function isVersionGateError(e){return!(!e||"version_mismatch"!==e.code)}const api={createClient:createClient,envVar:envVar,randomUUID:randomUUID,DEFAULT_API_BASE:DEFAULT_API_BASE,CLIENT_VERSION:"3.2.0",isVersionGateError:isVersionGateError,idleBudgetFor:idleBudgetFor,SSE_IDLE_TIMEOUT_MS:SSE_IDLE_TIMEOUT_MS,BRAIN_IDLE_TIMEOUT_MS:BRAIN_IDLE_TIMEOUT_MS};"undefined"!=typeof module&&module.exports&&(module.exports=api),"undefined"!=typeof window&&(window.AegisClient=api);
4
+ "use strict";function envVar(e){if("undefined"==typeof process||!process.env)return"";const t=process.env[e];return t&&!/^\$\{[A-Z_]+\}$/.test(t)?t:""}function envIdleMs(e){const t=envVar(e);if(!t)return 0;const n=Number(t);return Number.isFinite(n)&&n>0?n:0}const DSML_RE_INVOKE=/<\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call)\b\s*([^>]*?)\s*>([\s\S]*?)<\s*\/\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call)\b\s*>/g,DSML_RE_PARAM=/<\s*|\s*(?:DSML\s*)?|\s*(?:parameter|param|arg)\b\s*([^>]*?)\s*>([\s\S]*?)<\s*\/\s*|\s*(?:DSML\s*)?|\s*(?:parameter|param|arg)\b\s*>/g,DSML_RE_LEADER=/<\s*\/?\s*|\s*(?:DSML\s*)?|\s*(?:(?:tool|function)[_▁ ]*calls?|reasoning)[_▁ ]*(?:begin|end)?\s*>/gi,DSML_RE_ANY_TAG=/<\s*\/?\s*|\s*(?:DSML\s*)?|\s*[A-Za-z_][A-Za-z0-9_]*[^>]{0,120}>/g,DSML_RE_SKELETON=/<\s*\/?\s*(?:tool_calls|function_calls|invoke|parameter|param|reasoning)\b[^>]{0,120}>/gi,DSML_RE_JSON_CALLS=/|[ \t]*(?:tool|function)[_▁ ]*calls?[_▁ ]*begin[ \t]*|([\s\S]*?)|[ \t]*(?:tool|function)[_▁ ]*calls?[_▁ ]*end[ \t]*|/gi,DSML_RE_JSON_CALLS_OPEN=/|[ \t]*(?:tool|function)[_▁ ]*calls?[_▁ ]*begin[ \t]*|/gi,DSML_RE_JSON_CALLS_CLOSE=/|[ \t]*(?:tool|function)[_▁ ]*calls?[_▁ ]*end[ \t]*|/gi,DSML_RE_ENVELOPE_TOKEN=/|[ \t]?[A-Za-z0-9_▁]*[ \t]?|/g,DSML_RE_DRIFT_INVOKE=/<\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call)\b\s*([^>]*?)\s*>/gi,DSML_RE_DRIFT_PARAM=/<\s*|\s*(?:DSML\s*)?|\s*(?:parameter|param|arg)\b\s*([^>]*?)\s*>/gi,DSML_RE_PARAM_CLOSE=/<\s*\/\s*|\s*(?:DSML\s*)?|\s*(?:parameter|param|arg)\b\s*>/gi,DSML_RE_ATTR=/([A-Za-z_][A-Za-z0-9_.-]*)\s*=\s*(?:"([^"]*)"|'([^']*)')/g,DSML_RE_STRUCT_TAG=/<\s*\/?\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call|parameter|param|arg|reasoning|(?:tool|function)[_▁ ]*calls?)\b/gi,DSML_RE_STRUCT_CLOSER=/<\s*\/\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call|parameter|param|arg|reasoning|(?:tool|function)[_▁ ]*calls?)\b/gi,DSML_RE_WRAPPER_TAG=/<\s*\/?\s*|\s*(?:DSML\s*)?|\s*(?!(?:invoke|call|tool_call|parameter|param|arg)\b)[A-Za-z_][A-Za-z0-9_]*[^>]{0,120}>/g,DSML_RE_TRAILING_LT=/<\s*\/?\s*$/,DSML_RE_OPEN_TOKEN=/^|[ \t]?[A-Za-z0-9_▁]*[ \t]?$/,DSML_HOLD_MAX=4194304;function dsmlAttrs(e){const t={};if(!e)return t;let n;for(DSML_RE_ATTR.lastIndex=0;n=DSML_RE_ATTR.exec(e);)t[n[1].toLowerCase()]=null!=n[2]?n[2]:n[3];return t}function dsmlJson(e){const t=String(null==e?"":e).trim();try{const e=JSON.parse(t);return void 0===e?t:e}catch{return t}}function dsmlArgs(e){const t={};let n;for(DSML_RE_PARAM.lastIndex=0;n=DSML_RE_PARAM.exec(e);){const e=dsmlAttrs(n[1]),r=e.name||e.key||`arg${Object.keys(t).length}`,o="false"===String(e.string||"").toLowerCase()||"true"===String(e.json||"").toLowerCase();t[r]=o?dsmlJson(n[2]):n[2]}return t}function decodeDeepSeekDSML(e){if("string"!=typeof e||!e||-1===e.indexOf("|"))return{text:e||"",calls:[]};const t=[];let n=e;DSML_RE_INVOKE.lastIndex=0;const r=[];let o;for(;o=DSML_RE_INVOKE.exec(n);){const e=dsmlAttrs(o[1]),n=e.name||e.function||e.tool||"";n&&t.push({name:n,args:dsmlArgs(o[2])}),r.push([o.index,o.index+o[0].length])}for(let e=r.length-1;e>=0;e--)n=n.slice(0,r[e][0])+n.slice(r[e][1]);return n=n.replace(DSML_RE_JSON_CALLS,((e,n)=>{const r=dsmlJson(n),o=Array.isArray(r)?r:r&&Array.isArray(r.tool_calls)?r.tool_calls:[];for(const e of o){const n=e&&e.function||e||{},r=n.name||e&&e.name||"";if(!r)continue;let o=null!=n.arguments?n.arguments:e&&e.arguments;"string"==typeof o&&(o=dsmlJson(o)),t.push({name:r,args:o&&"object"==typeof o?o:{}})}return""})),n=n.replace(DSML_RE_LEADER,""),{text:n,calls:t}}function decodeDeepSeekDSMLDrift(e){if("string"!=typeof e||!e||-1===e.indexOf("|"))return{text:e||"",calls:[]};const t=[];let n;for(DSML_RE_DRIFT_INVOKE.lastIndex=0;n=DSML_RE_DRIFT_INVOKE.exec(e);)t.push({at:n.index,attrs:n[1],body:DSML_RE_DRIFT_INVOKE.lastIndex});if(!t.length)return{text:e,calls:[]};const r=[];let o="",s=0;for(let n=0;n<t.length;n++){const a=n+1<t.length?t[n+1].at:e.length,i=e.slice(t[n].body,a),c=dsmlAttrs(t[n].attrs),l=c.name||c.function||c.tool||"",u={},d=[];let m;for(DSML_RE_DRIFT_PARAM.lastIndex=0;m=DSML_RE_DRIFT_PARAM.exec(i);)d.push({at:m.index,attrs:m[1],from:DSML_RE_DRIFT_PARAM.lastIndex});for(let e=0;e<d.length;e++){const t=e+1<d.length?d[e+1].at:i.length,n=i.slice(d[e].from,t).replace(DSML_RE_PARAM_CLOSE,""),r=dsmlAttrs(d[e].attrs),o=r.name||r.key||`arg${Object.keys(u).length}`,s="false"===String(r.string||"").toLowerCase();u[o]=s?dsmlJson(n):n}o+=e.slice(s,t[n].at),s=a,l&&r.push({name:l,args:u})}return o+=e.slice(s),{text:o,calls:r}}function dsmlResidue(e){return e?-1===e.indexOf("|")?e.replace(DSML_RE_SKELETON,""):e.replace(DSML_RE_ANY_TAG,"").replace(DSML_RE_SKELETON,"").replace(DSML_RE_ENVELOPE_TOKEN,""):e}function dsmlUnterminated(e){return!!DSML_RE_OPEN_TOKEN.test(e)||(e.match(DSML_RE_STRUCT_TAG)||[]).length>(e.match(DSML_RE_STRUCT_CLOSER)||[]).length}function dsmlHoldFrom(e){const t=e.search(/<\s*\/?\s*|/);if(-1!==t)return t;const n=e.search(DSML_RE_JSON_CALLS_OPEN);if(-1!==n&&-1===e.slice(n).search(DSML_RE_JSON_CALLS_CLOSE))return n;const r=DSML_RE_TRAILING_LT.exec(e);if(r)return r.index;const o=e.indexOf("|");return-1!==o&&dsmlUnterminated(e.slice(o))?o:-1}function makeDeepSeekEnvelopeStripper(){let e="";const t=[],n=n=>{e+="string"==typeof n?n:"";const r=decodeDeepSeekDSML(e);e=r.text;for(const e of r.calls)t.push(e);e=e.replace(DSML_RE_WRAPPER_TAG,"");const o=dsmlHoldFrom(e);let s;return-1!==o&&e.length-o<=DSML_HOLD_MAX?(s=e.slice(0,o),e=e.slice(o)):(s=e,e=""),dsmlResidue(s)};return n.flush=()=>{const n=decodeDeepSeekDSML(e);e="";for(const e of n.calls)t.push(e);const r=decodeDeepSeekDSMLDrift(n.text);for(const e of r.calls)t.push(e);return dsmlResidue(r.text)},n.calls=()=>t.slice(),n}function randomUUID(){const e="undefined"!=typeof globalThis&&globalThis||"undefined"!=typeof self&&self||null,t=e&&e.crypto;if(t&&"function"==typeof t.randomUUID)try{return t.randomUUID()}catch(e){}if(t&&"function"==typeof t.getRandomValues)try{const e=new Uint8Array(16);t.getRandomValues(e),e[6]=15&e[6]|64,e[8]=63&e[8]|128;const n=Array.from(e,(e=>e.toString(16).padStart(2,"0"))).join("");return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`}catch(e){}if("function"==typeof require)try{const e=require("crypto");if(e&&"function"==typeof e.randomUUID)return e.randomUUID()}catch(e){}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}))}const DEFAULT_API_BASE="https://aegiscloud.org",CLIENT_VERSION="3.2.0",DEFAULT_TIMEOUT_MS=6e4,MAX_BODY_BYTES=8388608,RATE_LIMIT_RETRIES=4,RATE_LIMIT_MAX_WAIT_MS=3e4,RATE_LIMIT_BASE_WAIT_MS=1e3,TRANSIENT_STREAM_ERROR_PATTERN=/connection reset by peer|broken pipe|connection aborted|errno 104|errno 32|errno 54|econnreset|epipe/i,TRANSIENT_STREAM_RETRIES=2,TRANSIENT_STREAM_BASE_WAIT_MS=500,TRANSIENT_SOCKET_CODE_PATTERN=/^(ECONNRESET|EPIPE|ECONNABORTED|UND_ERR_SOCKET|UND_ERR_CLOSED)$/,TRANSIENT_SOCKET_RETRIES=2,SSE_UPSTREAM_TIMEOUT_PATTERN=/request timed out|timed out waiting|upstream timeout/i;function upstreamTimeoutMessage(e,t){const n=Number(t);return`${e} — the upstream provider gave up before answering${null!=t&&Number.isFinite(n)?n>=1e3?` after ${(n/1e3).toFixed(1)}s`:` after ${Math.max(0,Math.round(n))}ms`:""}. That is the provider's own deadline, not this client's stream budget, so raising AEGIS_SSE_IDLE_TIMEOUT_MS cannot help`}function createClient(e={}){const t=(e.apiBase||envVar("AEGIS_API_BASE")||DEFAULT_API_BASE).replace(/\/+$/,"");let n=void 0!==e.apiKey?e.apiKey:envVar("AEGIS_API_KEY");const r=void 0!==e.memoryToken?e.memoryToken:envVar("AEGIS_MEMORY_TOKEN"),o=e.clientVersion||"3.2.0",s="cli"===e.channel?"cli":"desktop";function a(e){return n&&"string"==typeof e?e.split(n).join("[redacted]"):e}const i={ECONNRESET:"connection reset by the backend",ECONNREFUSED:"connection refused — is the backend running?",EPIPE:"connection closed while sending the request",ETIMEDOUT:"connection timed out",ENOTFOUND:"host not found — check the endpoint URL",EAI_AGAIN:"DNS lookup failed temporarily",EHOSTUNREACH:"host unreachable",ENETUNREACH:"network unreachable",CERT_HAS_EXPIRED:"TLS certificate has expired",DEPTH_ZERO_SELF_SIGNED_CERT:"TLS certificate is self-signed",UND_ERR_SOCKET:"the socket closed before the response finished",UND_ERR_CLOSED:"the connection was closed",UND_ERR_CONNECT_TIMEOUT:"timed out connecting to the backend",UND_ERR_HEADERS_TIMEOUT:"the backend accepted the connection but never sent a response",UND_ERR_BODY_TIMEOUT:"the backend stalled mid-response",UND_ERR_ABORTED:"the request was aborted"};function c(e,t){const n=e instanceof Error?e:new Error(String(e)),r=n&&n.name;if("AbortError"===r||"TimeoutError"===r)return e;const o=l(n),s=t||"the backend",a=new Error(o?`Could not reach ${s} (${o}).`:`Could not reach ${s}: ${n.message||"network failure"}.`);return a.status=0,a.code="network",a.networkCode=o||null,a.data=null,a.cause=n,a}function l(e,t=0){if(!e||t>4)return null;const n=e.code||e.cause&&e.cause.code,r=e.cause,o=r?l(r,t+1):null;return i[n]?i[n]:o||(r&&r.message&&r.message!==e.message?r.message:n||null)}async function u(e,n){const r=n&&n.signal,o="function"==typeof AbortController?new AbortController:null;let s=null;o&&(s=setTimeout((()=>o.abort()),S),s&&"function"==typeof s.unref&&s.unref(),r&&(r.aborted?o.abort():"function"==typeof r.addEventListener&&r.addEventListener("abort",(()=>{o&&o.abort()}),{once:!0})));try{return await fetch(e,{...n||{},signal:o?o.signal:r})}catch(e){if(o&&o.signal.aborted&&(!r||!r.aborted)){const e=new Error(`Timed out after ${S/1e3}s waiting for ${t}.`);throw e.status=0,e.code="timeout",e.data=null,e}throw c(e,t)}finally{s&&clearTimeout(s)}}function d(e,t){const n=e&&e.headers&&"function"==typeof e.headers.get?e.headers.get("retry-after"):null;let r=0;if(n){const e=Number(n);if(Number.isFinite(e)&&e>=0)r=1e3*e;else{const e=Date.parse(n);Number.isFinite(e)&&(r=e-Date.now())}}return r||(r=R*Math.pow(2,t)),Math.min(r,A)}function m(e,t){return new Promise((n=>{const r=setTimeout(n,e);if(r&&"function"==typeof r.unref&&r.unref(),t&&"function"==typeof t.addEventListener)return t.aborted?(clearTimeout(r),void n()):void t.addEventListener("abort",(()=>{clearTimeout(r),n()}),{once:!0})}))}function _(e,t=0){if(!e||t>4)return null;const n=e.code;return"string"==typeof n&&"network"!==n?n:_(e.cause,t+1)}async function f(e,t){let n=0;for(;;)try{return await u(e,t)}catch(e){const r=e&&"network"===e.code?String(_(e)||""):"";if(n>=2||!TRANSIENT_SOCKET_CODE_PATTERN.test(r))throw e;if(t&&t.signal&&t.signal.aborted)throw e;if(await m(500*Math.pow(2,n),t&&t.signal),t&&t.signal&&t.signal.aborted)throw e;n++}}async function E(e,t){let n=await f(e,t);for(let r=0;n&&429===n.status&&r<T;r++){const o=d(n,r);try{n.body&&await n.body.cancel()}catch{}await m(o,t&&t.signal),n=await f(e,t)}for(let r=0;n&&n.status>=500&&n.status<600&&r<2;r++){let o="";try{o=await g(n.clone())}catch{break}if(!TRANSIENT_STREAM_ERROR_PATTERN.test(o))break;await m(500*Math.pow(2,r),t&&t.signal),n=await f(e,t)}return n}function p(e){if(!e)return e;if("AbortError"===e.name||"TimeoutError"===e.name)return e;if("network"===e.code||"timeout"===e.code||"ABORT_ERR"===e.code)return e;if(/^stream stalled - /.test(String(e.message||"")))return e;if(!_(e))return e;const n=c(e,t);return n.bodyPhase=!0,n}async function g(e){if(!e||!e.body||"function"!=typeof e.body.getReader){let t;try{t=await e.text()}catch(e){const t=p(e);throw t&&"network"===t.code&&(t.bytesRead=0),t||e}return t.length>h?t.slice(0,h):t}const n=e.body.getReader(),r=new TextDecoder;let o="",s=0;try{for(;;){let a;try{a=await n.read()}catch(e){const t=p(e);throw t&&"network"===t.code&&(t.bytesRead=s),t||e}const{done:i,value:c}=a;if(i)break;if(s+=c?c.byteLength:0,s>h){const n=new Error(`Response from ${t} exceeded the ${h/1048576}MB cap.`);throw n.status=e.status,n.code="body_too_large",n.data=null,n}o+=r.decode(c,{stream:!0})}return o+=r.decode(),o}finally{try{await n.cancel()}catch{}}}let y=null;const S=Number(e.timeoutMs)>0?Number(e.timeoutMs):Number(envVar("AEGIS_HTTP_TIMEOUT_MS"))>0?Number(envVar("AEGIS_HTTP_TIMEOUT_MS")):6e4,h=Number(e.maxBodyBytes)>0?Number(e.maxBodyBytes):8388608,T=Number(e.rateLimitRetries)>=0?Number(e.rateLimitRetries):4,R=Number(e.rateLimitBaseWaitMs)>=0?Number(e.rateLimitBaseWaitMs):1e3,A=Number(e.rateLimitMaxWaitMs)>0?Number(e.rateLimitMaxWaitMs):3e4;function M(e,n){try{const r=new URL(`/go/${String(e||"upgrade").replace(/^\/+|\/+$/g,"")}`,t);r.searchParams.set("s",s);const o=String(n||"").trim().toLowerCase();return/^[a-z0-9][a-z0-9_-]{0,63}$/.test(o)&&r.searchParams.set("c",o),r.toString()}catch(e){return""}}function D(e){const t={"Content-Type":"application/json","X-AEGIS-Version":o,...e};return n&&(t["X-API-Key"]=n,t.Authorization=`Bearer ${n}`),t}async function L(e,n){return O(await E(`${t}${e}`,n))}async function I(e,t){let n=0;for(;;)try{return await L(e,t)}catch(e){if(!e||"network"!==e.code||!0!==e.bodyPhase||0!==e.bytesRead||n>=2)throw e;if(t&&t.signal&&t.signal.aborted)throw e;if(await m(500*Math.pow(2,n),t&&t.signal),t&&t.signal&&t.signal.aborted)throw e;n++}}async function w(e,t,n,r){return I(e,{method:"POST",headers:n||D(),body:JSON.stringify(t||{}),signal:r&&r.signal})}async function b(e,t,n){return I(e,{method:"GET",headers:t||D(),signal:n&&n.signal})}function N(e,t){const n=e||{},r=n.latest_cli||"",s=n.latest_desktop||"",a=r||s||n.required||"",i=new Error(a?`This client (v${o}) is out of date — upgrade to v${a}.`:`This client (v${o}) is out of date.`);return i.status=t,i.code="version_mismatch",i.data=n,i.upgrade={required:n.required||"",latestCli:r,latestDesktop:s,url:M("upgrade","version_gate")||n.update_url||""},i}async function O(e){const t=await g(e);let n;try{n=t?JSON.parse(t):{}}catch{n={raw:a(t)}}if(!e.ok){if(function(e,t){return 426===e||t&&"version_mismatch"===t.code}(e.status,n))throw N(n,e.status);const t=n&&(n.error?.message||n.error||n.message)||`HTTP ${e.status}`,r=new Error(a("string"==typeof t?t:JSON.stringify(t)));throw e.status>=500&&e.status<600&&SSE_UPSTREAM_TIMEOUT_PATTERN.test(r.message)?(r.serverStatus=e.status,r.status=0,r.code="timeout",r.message=upstreamTimeoutMessage(r.message)):r.status=e.status,r.data=n,r}if(n&&"version_mismatch"===n.code)throw N(n,e.status);return n}function v(e){if(!e)return"";const t=e.error;return"string"==typeof t?t:t&&"string"==typeof t.message?t.message:t&&"string"==typeof t.error?t.error:"string"==typeof e.message?e.message:"string"==typeof e.error_message?e.error_message:""}async function k(){if(r)return r;if(y)return y;const e=await w("/api/verify-api-key",{api_key:n});if(!e||!e.memory_token){const e=M("upgrade","memory_quota");throw new Error("This AEGIS account has no memory token. "+(e?`Enable cloud memory at ${e}`:"Enable cloud memory in your AEGIS account settings."))}return y=e.memory_token,y}function x(e){return{"Content-Type":"application/json","X-AEGIS-Version":o,Authorization:`Bearer ${e}`}}function U(e){if(null==e)return"";if("string"==typeof e)return e;if(!Array.isArray(e))return String(e);let t="";for(let n=0;n<e.length;n+=1){const r=e[n];r&&"object"==typeof r&&("string"==typeof r.text?t+=(t?"\n":"")+r.text:"image_url"===r.type&&(t+=(t?"\n":"")+"[image]"))}return t}function C(e,t,n){const r=Array.isArray(e)?e.filter(Boolean):[],o=[];if(t&&!r.some((e=>e&&"system"===e.role))&&o.push({role:"system",content:t}),o.push(...r),null!=n&&("string"==typeof n?""!==n:Array.isArray(n)&&n.length>0)){const e=o[o.length-1];(Array.isArray(n)&&e&&"user"===e.role?U(e.content)===U(n):e&&"user"===e.role&&e.content===n)||o.push({role:"user",content:n})}return o}function P(e){const t=e&&e.choices&&e.choices[0],n=t&&t.message&&t.message.content;return"string"==typeof n?n:""}function $(e){const t=e&&e.choices&&e.choices[0],n=t&&t.message&&t.message.content;if("string"!=typeof n||-1===n.indexOf("|"))return e;const r=decodeDeepSeekDSML(n),o=decodeDeepSeekDSMLDrift(r.text);t.message.content=dsmlResidue(o.text);const s=[...r.calls,...o.calls];return s.length&&(e.toolCalls=[...Array.isArray(e.toolCalls)?e.toolCalls:[],...s.map((e=>({id:"",name:e.name,args:e.args||{}})))]),e}async function B(e,n,r,o,s,i){const{onReasoning:c,idleTimeoutMs:l,retryWithoutStreamOptions:u,_transientStreamAttempt:d=0}=i||{},_=n=>E(`${t}${e}`,{method:"POST",headers:r,body:JSON.stringify({...n,stream:!0}),signal:s});let f;try{f=await _(n)}catch(e){throw e}if(!f.ok&&426===f.status){let e={};try{const t=await g(f);e=t?JSON.parse(t):{}}catch{e={}}throw N(e,f.status)}if(!f.ok&&u&&n.stream_options){try{f.body&&await f.body.cancel()}catch{}const t={...n};delete t.stream_options,n=t;try{f=await _(n)}catch(e){throw e}}if(!f.ok){const t={...n};delete t.stream_options;const a=$(await w(e,{...t,stream:!1},r,{signal:s})),i=P(a);return i&&o({delta:i}),a}if(!(f.headers.get("content-type")||"").includes("text/event-stream")){const e=$(await O(f)),t=P(e);return t?o({delta:t}):function(e,t){if(e&&"version_mismatch"===e.code)throw N(e,t||426);const n=a(v(e));if(!n)return;const r=new Error(n);throw r.status=t||500,r.data=e,r}(e,f.status),e}const y=f.body.getReader(),S=new TextDecoder;let h="",T="",R="",A=n.model,M=null,D="";const L=new Map;let I=null,b="";const k=makeDeepSeekEnvelopeStripper(),x=idleBudgetFor(f,l);let U=Date.now();const C=U;let K=0;async function G(){let e,t=null;const n=Math.max(0,x-(Date.now()-U)),r=new Promise(((t,r)=>{e=setTimeout((()=>{r(new Error(K>0?`stream stalled - only keep-alives for ${x/1e3}s`:`stream stalled - no data for ${x/1e3}s`))}),n)})),o=s&&"function"==typeof s.addEventListener?new Promise(((e,n)=>{t=()=>{const e=new Error("The turn was stopped.");e.name="AbortError",e.code="ABORT_ERR",n(e)},s.aborted?t():s.addEventListener("abort",t,{once:!0})})):null;try{return await(o?Promise.race([y.read(),r,o]):Promise.race([y.read(),r]))}finally{clearTimeout(e),s&&t&&"function"==typeof s.removeEventListener&&s.removeEventListener("abort",t)}}for(;;){let t,l;try{({done:t,value:l}=await G())}catch(t){y.cancel().catch((()=>{}));const a=p(t);if(a&&"network"===a.code&&(a.bytesRead=b?1:0,0===a.bytesRead&&d<2&&(!s||!s.aborted))){if(await m(500*Math.pow(2,d),s),s&&s.aborted)throw a;return B(e,n,r,o,s,{...i,_transientStreamAttempt:d+1})}throw a||t}if(t)break;h+=S.decode(l,{stream:!0});const u=h.split("\n");h=u.pop();for(const e of u){const t=e.trim();if(!t.startsWith("data:")){t.startsWith(":")&&K++;continue}U=Date.now();const n=t.slice(5).trim();if(!n||"[DONE]"===n)continue;let r;try{r=JSON.parse(n)}catch{continue}if(r.error){if(!D){const e=r.error;D="string"==typeof e?e:v({error:e})||"stream error",D=a(D)}continue}r.model&&(A=r.model),r.usage&&(M=r.usage);const s=r.choices&&r.choices[0];s&&s.finish_reason&&(I=s.finish_reason);const i=(e,t,n,r)=>{if("string"==typeof e&&e)return r(e),n+e;if("string"==typeof t&&t){if(!n)return r(t),t;if(t.startsWith(n)){const e=t.slice(n.length);return e&&r(e),t}return n}return n};R=i(s&&s.delta&&s.delta.reasoning_content,s&&s.message&&s.message.reasoning_content,R,(e=>{"function"==typeof c?c(e):o({reasoning:e})})),T=i(s&&s.delta&&s.delta.content,s&&s.message&&s.message.content,T,(e=>{const t=k(e);t&&(b+=t,o({delta:t}))}));const l=s&&s.delta&&s.delta.tool_calls||s&&s.message&&s.message.tool_calls;if(Array.isArray(l))for(const e of l){const t=null==e.index?0:e.index,n=L.get(t)||{id:"",type:"function",function:{name:"",arguments:""}};e.id&&(n.id=e.id),e.type&&(n.type=e.type);const r=e.function||{};r.name&&(n.function.name=r.name),"string"==typeof r.arguments&&(n.function.arguments+=r.arguments),L.set(t,n)}}}if(!T&&D){if(d<2&&TRANSIENT_STREAM_ERROR_PATTERN.test(D))return await m(500*Math.pow(2,d),s),B(e,n,r,o,s,{...i,_transientStreamAttempt:d+1});const t=SSE_UPSTREAM_TIMEOUT_PATTERN.test(D),a=new Error(t?upstreamTimeoutMessage(D,Date.now()-C):D);throw a.status=t?0:f.status,t&&(a.code="timeout"),a}const V=k.flush();V&&(b+=V,o({delta:V}));const F=[...L.entries()].sort(((e,t)=>e[0]-t[0])).map((([e,t])=>({...t,id:t.id||`call_${e}`}))),J={content:b};R&&(J.reasoning_content=R),F.length&&(J.tool_calls=F);const W={model:A,choices:[{message:J,...I?{finish_reason:I}:{}}]};M&&(W.usage=M);const X=k.calls();return(F.length||X.length)&&(W.toolCalls=[...F.map((e=>({id:e.id,name:e.function.name,args:e.function.arguments}))),...X.map((e=>({id:"",name:e.name,args:e.args||{}})))]),W}return{apiBase:t,get apiKey(){return n},setApiKey:function(e){return n="string"==typeof e?e.trim():"",y=null,n},get clientVersion(){return o},get channel(){return s},promptUrl:M,verifyApiKey:async function(){return w("/api/verify-api-key",{api_key:n})},registerDevice:async function(e,t){return w("/api/v1/auth/register-device",{fingerprint:e,app:t&&t.app},void 0,t)},chatCompletion:async function({prompt:e,system:t,messages:n,model:r,mode:o,maxTokens:s,stream:a=!1,onStream:i,onReasoning:c,idleTimeoutMs:l,includeUsage:u,signal:d,extra:m,agentKey:_}={}){const f={messages:C(n,t,e),...s?{max_tokens:s}:{},...m||{}};r?f.model=r:o&&(f.mode=o);const E=D(_?{"X-AEGIS-Agent-Key":_}:void 0);return a&&"function"==typeof i?(u&&(f.stream_options={include_usage:!0}),B("/api/v1/chat/completions",f,E,i,d,{onReasoning:c,idleTimeoutMs:l,retryWithoutStreamOptions:Boolean(u)})):$(await w("/api/v1/chat/completions",{...f,stream:!1},E,{signal:d}))},byokChatCompletion:async function({provider:t="openai",model:r,messages:s,prompt:a,system:i,maxTokens:c,effort:l,reasoningEffort:u,tools:d,toolChoice:m,stream:_=!1,onStream:f,signal:E,providerKey:p,baseURL:g}={}){const y=void 0!==p?p:e.providerKey;if("custom"===t&&!g){const e=new Error('the "custom" provider dials the endpoint you name, and this call names none — save the address first: /model-add custom <https-base-url> <api-key> <model-id>, or the endpoint field in Settings › Provider (custom).');throw e.status=400,e.code="custom_endpoint_missing",e}const S={provider:t,messages:C(s,i,a),...c?{max_tokens:c}:{},...l?{effort:l}:{},...u?{reasoning_effort:u}:{},...Array.isArray(d)&&d.length?{tools:d}:{},...m?{tool_choice:m}:{},...g?{base_url:g}:{}};r&&(S.model=r);const h={"Content-Type":"application/json","X-AEGIS-Version":o,"X-Provider-Key":y};return n&&(h["X-AEGIS-Key"]=n),_&&"function"==typeof f?B("/api/v1/byok/chat/completions",S,h,f,E):$(await w("/api/v1/byok/chat/completions",{...S,stream:!1},h))},listModels:async function(e){return b("/api/v1/models",null,e)},tokenBankBalance:async function(e){return b("/api/token-bank/balance",null,e)},tokenBankTopup:async function(e){return w("/api/token-bank/topup",{amount_eur:e})},billingCheckout:async function(){return w("/api/billing/checkout",{})},byokStatus:async function(e){return b("/api/user/api-keys",null,e)},byokProviders:async function(e){return b("/api/v1/byok/providers",null,e)},catalog:async function(e,t,n){const r=(e||"models").replace(/^\/+/,""),o=new URLSearchParams;for(const[e,n]of Object.entries(t||{}))null!=n&&""!==n&&o.set(e,String(n));const s=o.toString();return b(`/api/v1/catalog/${r}${s?`?${s}`:""}`,n&&n.etag?{...D(),"If-None-Match":n.etag}:D(),n)},byokSet:async function(e,t){return w("/api/user/api-keys",{provider:e,api_key:t||""})},getMemoryToken:k,memorySearch:async function(e,t){return w("/api/memory/search",{query:e||"",limit:t||5},x(await k()))},memorySave:async function(e){return w("/api/memory/save",{entry:e},x(await k()))},memoryList:async function(e){return w("/api/memory/search",{query:"",limit:e||10},x(await k()))},verifyToken:async function(e){return w("/api/verify-token",{token:e||""},{"Content-Type":"application/json","X-AEGIS-Version":o,Authorization:`Bearer ${e}`})},memoryActivate:async function(e){return w("/api/memory/activate",{},x(e||await k()))},memoryPull:async function(e){return w("/api/memory/pull",{since:e||0},x(await k()))},memorySaveBatch:async function(e){return w("/api/memory/save",{entries:e||[]},x(await k()))},conversationSyncPush:async function(e){const t=await k();return w("/api/conversations/sync",{session_id:e&&e.session_id,title:e&&e.title||"",messages:e&&e.messages||[],source:e&&e.source||"aegis-desktop"},x(t))},conversationSyncPull:async function(){return w("/api/conversations/sync",{},x(await k()))},importConversation:async function({messages:e,url:t,title:n,source:r}={}){return w("/api/import",{messages:e||[],url:t||"",title:n||"",source:r||"aegiscode-plugin"})},driveToken:async function(){try{return await b("/api/drive/token")}catch(e){if(e&&404===e.status)return{connected:!1,access_token:null,email:null};throw e}},randomUUID:randomUUID}}const SSE_IDLE_TIMEOUT_MS=6e4,BRAIN_IDLE_TIMEOUT_MS=9e5;function idleBudgetFor(e,t){const n=Number(t),r=envIdleMs("AEGIS_SSE_IDLE_TIMEOUT_MS"),o=n>0?n:r>0?r:SSE_IDLE_TIMEOUT_MS;let s="";try{const t=e&&e.headers&&"function"==typeof e.headers.get?e.headers.get.bind(e.headers):null;s=t&&t("X-AEGIS-Brain")||""}catch{s=""}const a=envIdleMs("AEGIS_BRAIN_IDLE_TIMEOUT_MS")||BRAIN_IDLE_TIMEOUT_MS;return s&&String(s).trim()?Math.max(o,a):o}function isVersionGateError(e){return!(!e||"version_mismatch"!==e.code)}const api={createClient:createClient,envVar:envVar,randomUUID:randomUUID,DEFAULT_API_BASE:DEFAULT_API_BASE,CLIENT_VERSION:"3.2.0",isVersionGateError:isVersionGateError,idleBudgetFor:idleBudgetFor,SSE_IDLE_TIMEOUT_MS:SSE_IDLE_TIMEOUT_MS,BRAIN_IDLE_TIMEOUT_MS:BRAIN_IDLE_TIMEOUT_MS};"undefined"!=typeof module&&module.exports&&(module.exports=api),"undefined"!=typeof window&&(window.AegisClient=api);
@@ -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
- const e=require("node:crypto"),t=require("node:fs"),o=require("node:path"),r=require("./fingerprint.js"),n=require("./authorship-key.js"),s=require("./env-file.js"),i=()=>o.join(n.dataDir(),"history.jsonl"),c=["cwd","dir","workspace","root"],l=["demand","prompt","task","text","content"],a=["outcome","status","result"],u=["session","sessionId","session_id"],f=["reply","answer","response"],d=["model","aiModel","modelId"],p=t=>e.createHash("sha256").update(String(t||""),"utf8").digest("hex"),S="AEGIS_AI_SECRET";function y(e,t){for(const o of t){const t=e[o];if(null==t)continue;const r="string"==typeof t?t:String(t);if(""!==r.trim())return r}return null}function m(e){if(!t.existsSync(e))throw new Error(`attest: no session log at ${e}`);const o=[];let r=0;for(const n of t.readFileSync(e,"utf8").split("\n")){const e=n.trim();if(e)try{const t=JSON.parse(e);t&&"object"==typeof t?o.push(t):r+=1}catch{r+=1}}return{entries:o,skipped:r}}function E(e){for(let t=e.length-1;t>=0;t-=1){const o=y(e[t],u);if(o)return o}return null}function v(e,{session:t=null,turns:o=null}={}){let r=e;if(t){const o=String(t);r=e.filter((e=>y(e,u)===o))}return o&&Number.isFinite(Number(o))&&Number(o)>0&&(r=r.slice(-Math.floor(Number(o)))),r}function h(e){const t=[];for(const r of Array.isArray(e)?e:[]){if(!r||"object"!=typeof r)continue;const e=y(r,c),n=y(r,l);t.push({tool:n||e?"turn":null,target:`${e?o.basename(e):"?"}#${p(n||"").slice(0,8)}`,outcome:y(r,a)})}return t}function _(e){const t=[];for(const o of Array.isArray(e)?e:[]){if(!o||"object"!=typeof o)continue;const e=y(o,f),r=y(o,a),n=y(o,d),s=Boolean(e||r||n);t.push({tool:s?"reply":null,target:s?`reply#${p(e||"").slice(0,8)}`:null,outcome:r||null,model:n})}return t}function b(e={}){const o=e.argv||[],r=e.env||{},n=function(e,t){for(const t of["--ai-secret","--ai-secret-file"]){const o=e.indexOf(t);if(-1!==o&&void 0!==e[o+1]&&!String(e[o+1]).startsWith("--"))return e[o+1]}return null}(o);if(n){const e=t.readFileSync(n,"utf8").trim();if(!e)throw new Error(`attest: ${n} is empty — an empty AI credential is not one`);return{secret:e,source:n}}const i=r[S]&&String(r[S]).trim();if(i)return{secret:i,source:S};const c=String(e.aiModel||e.model||"").trim();if(c&&"function"==typeof s.providerForModelId){const o=s.providerForModelId(c,e.cls);if(o){const e=s.providerKeyFromEnv(o,r);if(e&&e.key)return{secret:e.key,source:e.env};const n=function(e,o){const r="function"==typeof s.envVarFor?s.envVarFor(e):"";if(!r)return null;const n=o&&(o.AEGIS_HOME||o.AEGISCODE_HOME)?String(o.AEGIS_HOME||o.AEGISCODE_HOME):void 0;let i;try{i=s.parseEnvText(t.readFileSync(s.envFileFor(n),"utf8"))}catch{return null}const c=i&&"string"==typeof i[r]?i[r].trim():"";return c&&("function"!=typeof s.credentialLooksUsable||s.credentialLooksUsable(c))?{secret:c,source:r}:null}(o,r);if(n)return n}}return{secret:null,source:"none"}}const g=new Set([".git","node_modules","dist","build","out","vendor",".venv","venv","__pycache__",".next",".cache","release","coverage"]),I=2097152;module.exports={DEFAULT_HISTORY:i,DIR_KEYS:c,DEMAND_KEYS:l,OUTCOME_KEYS:a,SESSION_KEYS:u,REPLY_KEYS:f,MODEL_KEYS:d,AI_SECRET_ENV:S,TIME_KEYS:["at","ts","time","createdAt"],SKIP_DIRS:g,MAX_FILE_BYTES:I,MAX_FILES:4096,firstKey:y,readHistory:m,lastSessionId:E,selectTurns:v,observationsFromTurns:h,aiObservationsFromTurns:_,resolveAiSecret:b,collectCode:function({roots:e=[],files:n=[],skip:s=[]}={}){const i=new Set(s),c=[],l=(e,o)=>{const n=t.statSync(o);if(!n.isFile())return;if(n.size>I)throw new Error(`attest: ${o} is ${n.size} bytes — too large to attest (max 2097152)`);if(c.length>=4096)throw new Error("attest: more than 4096 files — refusing to attest a partial walk");const s=r.normaliseCodePath(e);s&&c.push({path:s,content:t.readFileSync(o,"utf8")})};for(const r of e){const e=o.resolve(r),n=(e,r)=>{for(const s of t.readdirSync(e).sort()){const c=o.join(e,s),a=r?`${r}/${s}`:s,u=t.lstatSync(c);if(!u.isSymbolicLink())if(u.isDirectory()){if(g.has(s)||i.has(s))continue;n(c,a)}else l(a,c)}};n(e,"")}for(const e of n){const t=o.resolve(e);l(o.basename(t),t)}return c},mintSession:function(e={}){const t=e.key||n.resolveKey(e);if(!t.secret)throw new Error(`attest: no authorship key — run \`aegiscode fingerprint keygen\`, set ${n.SECRET_ENV}, or pass --secret <file>`);const o=e.history||i(),{entries:s,skipped:c}=m(o),l=v(s,{session:e.session||E(s),turns:e.turns}),a=h(l),u=e.code||[],f=e.aiObservations||_(l),d=void 0!==e.aiModel&&null!==e.aiModel?e.aiModel:f.map((e=>e.model)).filter(Boolean).pop()||"",p=void 0===e.aiSecret?b({...e,aiModel:d}):{secret:e.aiSecret,source:e.aiSecret?"caller":"none"},S=r.mint({secret:t.secret,label:e.label,account:e.account,model:e.model,tools:e.tools,observations:a,code:u,codeDirty:void 0===e.codeDirty?null:e.codeDirty,aiSecret:p.secret,aiModel:d,aiObservations:f,createdAt:e.createdAt||void 0});return{record:S,keySource:t.source,public:t.public,samples:S.behaviourSamples,observations:a.length,aiKeySource:p.source,aiSamples:S.aiSamples,skippedLines:c}}};
3
+ const e=require("node:crypto"),t=require("node:fs"),o=require("node:path"),r=require("./fingerprint.js"),n=require("./authorship-key.js"),s=require("./env-file.js"),i=()=>o.join(n.dataDir(),"history.jsonl"),c=["cwd","dir","workspace","root"],l=["demand","prompt","task","text","content"],a=["outcome","status","result"],u=["session","sessionId","session_id"],f=["reply","answer","response"],d=["model","aiModel","modelId"],p=t=>e.createHash("sha256").update(String(t||""),"utf8").digest("hex"),S="AEGIS_AI_SECRET";function y(e,t){for(const o of t){const t=e[o];if(null==t)continue;const r="string"==typeof t?t:String(t);if(""!==r.trim())return r}return null}function m(e){if(!t.existsSync(e))throw new Error(`attest: no session log at ${e}`);const o=[];let r=0;for(const n of t.readFileSync(e,"utf8").split("\n")){const e=n.trim();if(e)try{const t=JSON.parse(e);t&&"object"==typeof t?o.push(t):r+=1}catch{r+=1}}return{entries:o,skipped:r}}function E(e){for(let t=e.length-1;t>=0;t-=1){const o=y(e[t],u);if(o)return o}return null}function v(e,{session:t=null,turns:o=null}={}){let r=e;if(t){const o=String(t);r=e.filter((e=>y(e,u)===o))}return o&&Number.isFinite(Number(o))&&Number(o)>0&&(r=r.slice(-Math.floor(Number(o)))),r}function h(e){const t=[];for(const r of Array.isArray(e)?e:[]){if(!r||"object"!=typeof r)continue;const e=y(r,c),n=y(r,l);t.push({tool:n||e?"turn":null,target:`${e?o.basename(e):"?"}#${p(n||"").slice(0,8)}`,outcome:y(r,a)})}return t}function _(e){const t=[];for(const o of Array.isArray(e)?e:[]){if(!o||"object"!=typeof o)continue;const e=y(o,f),r=y(o,a),n=y(o,d),s=Boolean(e||r||n);t.push({tool:s?"reply":null,target:s?`reply#${p(e||"").slice(0,8)}`:null,outcome:r||null,model:n})}return t}function b(e={}){const o=e.argv||[],r=e.env||{},n=function(e,t){for(const t of["--ai-secret","--ai-secret-file"]){const o=e.indexOf(t);if(-1!==o&&void 0!==e[o+1]&&!String(e[o+1]).startsWith("--"))return e[o+1]}return null}(o);if(n){const e=t.readFileSync(n,"utf8").trim();if(!e)throw new Error(`attest: ${n} is empty — an empty AI credential is not one`);return{secret:e,source:n}}const i=r[S]&&String(r[S]).trim();if(i)return{secret:i,source:S};const c=String(e.aiModel||e.model||"").trim();if(c&&"function"==typeof s.providerForModelId){const o=s.providerForModelId(c,e.cls);if(o){const e=s.providerKeyFromEnv(o,r);if(e&&e.key)return{secret:e.key,source:e.env};const n=function(e,o){const r="function"==typeof s.envVarFor?s.envVarFor(e):"";if(!r)return null;const n=o&&(o.AEGIS_HOME||o.AEGISCODE_HOME)?String(o.AEGIS_HOME||o.AEGISCODE_HOME):void 0;let i;try{i=s.parseEnvText(t.readFileSync(s.envFileFor(n),"utf8"))}catch{return null}const c=i&&"string"==typeof i[r]?i[r].trim():"";return c&&("function"!=typeof s.credentialLooksUsable||s.credentialLooksUsable(c))?{secret:c,source:r}:null}(o,r);if(n)return n}}return{secret:null,source:"none"}}const g=new Set([".git","node_modules","dist","build","out","vendor",".venv","venv","__pycache__",".next",".cache","release","coverage"]),I=2097152;module.exports={DEFAULT_HISTORY:i,DIR_KEYS:c,DEMAND_KEYS:l,OUTCOME_KEYS:a,SESSION_KEYS:u,REPLY_KEYS:f,MODEL_KEYS:d,AI_SECRET_ENV:S,TIME_KEYS:["at","ts","time","createdAt"],SKIP_DIRS:g,MAX_FILE_BYTES:I,MAX_FILES:4096,firstKey:y,readHistory:m,lastSessionId:E,selectTurns:v,observationsFromTurns:h,aiObservationsFromTurns:_,resolveAiSecret:b,collectCode:function({roots:e=[],files:n=[],skip:s=[]}={}){const i=new Set(s),c=[],l=(e,o)=>{const n=t.statSync(o);if(!n.isFile())return;if(n.size>I)throw new Error(`attest: ${o} is ${n.size} bytes — too large to attest (max 2097152)`);if(c.length>=4096)throw new Error("attest: more than 4096 files — refusing to attest a partial walk");const s=r.normaliseCodePath(e);s&&c.push({path:s,content:t.readFileSync(o,"utf8")})};for(const r of e){const e=o.resolve(r),n=(e,r)=>{for(const s of t.readdirSync(e).sort()){const c=o.join(e,s),a=r?`${r}/${s}`:s,u=t.lstatSync(c);if(!u.isSymbolicLink())if(u.isDirectory()){if(g.has(s)||i.has(s))continue;n(c,a)}else l(a,c)}};n(e,"")}for(const e of n){const t=o.resolve(e);l(o.basename(t),t)}return c},mintSession:function(e={}){const t=e.key||n.resolveKey(e);if(!t.secret)throw new Error(`attest: no authorship key — run \`aegiscode fingerprint keygen\`, set ${n.SECRET_ENV}, or pass --secret <file>`);const o=e.history||i(),{entries:s,skipped:c}=m(o),l=v(s,{session:e.session||E(s),turns:e.turns}),a=h(l),u=e.code||[],f=e.aiObservations||_(l),d=void 0!==e.aiModel&&null!==e.aiModel?e.aiModel:f.map((e=>e.model)).filter(Boolean).pop()||"",y=void 0===e.aiSecret?b({...e,aiModel:d}):{secret:e.aiSecret,source:e.aiSecret?"caller":"none"},S=r.mint({secret:t.secret,label:e.label,account:e.account,model:e.model,tools:e.tools,observations:a,code:u,codeDirty:void 0===e.codeDirty?null:e.codeDirty,aiSecret:y.secret,aiModel:d,aiObservations:f,createdAt:e.createdAt||void 0});return{record:S,keySource:t.source,public:t.public,samples:S.behaviourSamples,observations:a.length,aiKeySource:y.source,aiSamples:S.aiSamples,skippedLines:c}}};
@@ -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("fs"),path=require("path"),credentials=require("./credentials.js"),CATALOG_FILE="catalog.json",STALE_AFTER_MS=864e5;function catalogDir(e){return e&&e.dir||credentials.aegisHome(e&&e.env)}function catalogPath(e){return path.join(catalogDir(e),CATALOG_FILE)}function modelIdsOf(e){return(Array.isArray(e&&e.models)?e.models:[]).map((e=>"string"==typeof e?e:e&&e.id)).map((e=>"string"==typeof e?e.trim():"")).filter(Boolean)}function providerArray(e){return Array.isArray(e)?e:Array.isArray(e&&e.providers)?e.providers:null}function indexCatalog(e){const t=Object.create(null),r=Array.isArray(e&&e.models)?e.models:[];for(const e of r){if(!e||"object"!=typeof e)continue;const r="string"==typeof e.provider_id?e.provider_id.trim():"",o="string"==typeof e.model_id?e.model_id.trim():"";r&&o&&("active"===("string"==typeof e.status?e.status.toLowerCase():"active")&&(t[r]||(t[r]=[])).push(o))}return t}function read(e){const t=catalogPath(e);let r,o;try{r=fs.readFileSync(t,"utf8")}catch(e){return null}try{o=JSON.parse(r)}catch(e){return null}if(!o||"object"!=typeof o||!Array.isArray(o.providers))return null;let n=null;const a=o.snapshot&&(o.snapshot.fetched_at||o.snapshot.fetchedAt);if("string"==typeof a&&a){const e=Date.parse(a);Number.isNaN(e)||(n=e)}if(null===n)try{n=fs.statSync(t).mtimeMs}catch(e){n=null}const s=null===n?null:Math.max(0,Date.now()-n);let i=null;const l=o.snapshot&&o.snapshot.revalidated_at;if("string"==typeof l&&l){const e=Date.parse(l);Number.isNaN(e)||(i=e)}const d=null!==i&&(null===n||i>n)?i:n;return{data:o,fetchedAt:n,revalidatedAt:i,ageMs:s,stale:null===d||Date.now()-d>STALE_AFTER_MS,path:t}}function write(e,t){const r=catalogPath(t);fs.mkdirSync(path.dirname(r),{recursive:!0});const o=`${r}.${process.pid}.tmp`;return fs.writeFileSync(o,JSON.stringify(e),"utf8"),fs.renameSync(o,r),r}function withCatalog(e,t,r){const o=providerArray(e);if(!o)return[];let n=t;if(void 0===n){const e=read(r);n=e?e.data:null}const a=indexCatalog(n);if(!Object.keys(a).length)return o.slice();const s=[];for(const e of o){if(!e||"object"!=typeof e)continue;const t="string"==typeof e.id?e.id.trim():"",r=t?a[t]:null;if(!r||!r.length){s.push(e);continue}const o=new Set(modelIdsOf(e)),n=r.filter((e=>!o.has(e)));if(!n.length){s.push(e);continue}const i=Array.isArray(e.models)?e.models:[];s.push({...e,models:[...i,...n]})}return s}function addedModelsFor(e,t,r,o){const n="string"==typeof e?e.trim():"";if(!n)return[];let a=r;if(void 0===a){const e=read(o);a=e?e.data:null}const s=indexCatalog(a)[n]||[],i=(providerArray(t)||[]).find((e=>e&&"string"==typeof e.id&&e.id.trim()===n)),l=new Set(modelIdsOf(i));return s.filter((e=>!l.has(e)))}const MAX_PAGES=200;async function refresh(e,t){const r=t||{},o=r.limit||500,n=r.maxPages||200,a=read(r),s=a&&a.data||null,i=[];let l=null,d=0,c=r.etag||null,u=null,f=!1;try{for(;;){const t=await e({cursor:l,limit:o,etag:c});if(!t||t.notModified){f=!0;break}0===d&&t.etag&&(u=t.etag);const r=Array.isArray(t.models)?t.models:[];for(const e of r)e&&"object"==typeof e&&i.push(e);if(d+=1,!t.has_more||!t.next_cursor)break;if(d>=n)return _refreshResult({ok:!1,changed:!1,pages:d,models:i.length,providers:0,staleKept:Boolean(s),reason:`stopped after ${d} pages; cache left untouched`});l=t.next_cursor,c=null}}catch(e){return _refreshResult({ok:!1,changed:!1,pages:d,models:0,providers:0,staleKept:Boolean(s),reason:e&&e.message||String(e)})}if(f){let e=null;if(s)try{const t="function"==typeof r.now?r.now():Date.now();e=write({...s,snapshot:{...s.snapshot||{},revalidated_at:new Date(t).toISOString(),...u?{etag:u}:{}}},r)}catch{e=null}return _refreshResult({ok:!0,changed:!1,pages:0,models:0,providers:0,staleKept:!e,written:e,reason:"not-modified"})}if(!i.length)return _refreshResult({ok:!1,changed:!1,pages:d,models:0,providers:0,staleKept:Boolean(s),reason:"empty catalog; cache left untouched"});const p=s&&Array.isArray(s.providers)?s.providers:[],h="function"==typeof r.now?r.now():Date.now(),g={schema_version:s&&s.schema_version||1,providers:p,models:i,snapshot:{fetched_at:new Date(h).toISOString(),models_seen:i.length,providers_seen:p.length,source:"catalog-api",...u?{etag:u}:{}}};let m=null;try{m=write(g,r)}catch(e){return _refreshResult({ok:!1,changed:!1,pages:d,models:i.length,providers:p.length,staleKept:Boolean(s),reason:e&&e.message||String(e)})}return _refreshResult({ok:!0,changed:!0,pages:d,models:i.length,providers:p.length,staleKept:!1,written:m})}function _refreshResult(e){return{ok:Boolean(e.ok),changed:Boolean(e.changed),written:e.written||null,pages:e.pages||0,models:e.models||0,providers:e.providers||0,staleKept:Boolean(e.staleKept),...e.reason?{reason:e.reason}:{}}}module.exports={CATALOG_FILE:CATALOG_FILE,STALE_AFTER_MS:STALE_AFTER_MS,MAX_PAGES:200,catalogDir:catalogDir,catalogPath:catalogPath,indexCatalog:indexCatalog,read:read,write:write,refresh:refresh,withCatalog:withCatalog,addedModelsFor:addedModelsFor};
3
+ "use strict";const fs=require("fs"),path=require("path"),credentials=require("./credentials.js"),CATALOG_FILE="catalog.json",STALE_AFTER_MS=864e5;function catalogDir(e){return e&&e.dir||credentials.aegisHome(e&&e.env)}function catalogPath(e){return path.join(catalogDir(e),CATALOG_FILE)}function modelIdsOf(e){return(Array.isArray(e&&e.models)?e.models:[]).map((e=>"string"==typeof e?e:e&&e.id)).map((e=>"string"==typeof e?e.trim():"")).filter(Boolean)}function providerArray(e){return Array.isArray(e)?e:Array.isArray(e&&e.providers)?e.providers:null}function indexCatalog(e){const t=Object.create(null),r=Array.isArray(e&&e.models)?e.models:[];for(const e of r){if(!e||"object"!=typeof e)continue;const r="string"==typeof e.provider_id?e.provider_id.trim():"",o="string"==typeof e.model_id?e.model_id.trim():"";r&&o&&"active"===("string"==typeof e.status?e.status.toLowerCase():"active")&&(t[r]||(t[r]=[])).push(o)}return t}function read(e){const t=catalogPath(e);let r,o;try{r=fs.readFileSync(t,"utf8")}catch(e){return null}try{o=JSON.parse(r)}catch(e){return null}if(!o||"object"!=typeof o||!Array.isArray(o.providers))return null;let n=null;const a=o.snapshot&&(o.snapshot.fetched_at||o.snapshot.fetchedAt);if("string"==typeof a&&a){const e=Date.parse(a);Number.isNaN(e)||(n=e)}if(null===n)try{n=fs.statSync(t).mtimeMs}catch(e){n=null}const s=null===n?null:Math.max(0,Date.now()-n);let i=null;const l=o.snapshot&&o.snapshot.revalidated_at;if("string"==typeof l&&l){const e=Date.parse(l);Number.isNaN(e)||(i=e)}const d=null!==i&&(null===n||i>n)?i:n;return{data:o,fetchedAt:n,revalidatedAt:i,ageMs:s,stale:null===d||Date.now()-d>STALE_AFTER_MS,path:t}}function write(e,t){const r=catalogPath(t);fs.mkdirSync(path.dirname(r),{recursive:!0});const o=`${r}.${process.pid}.tmp`;return fs.writeFileSync(o,JSON.stringify(e),"utf8"),fs.renameSync(o,r),r}function withCatalog(e,t,r){const o=providerArray(e);if(!o)return[];let n=t;if(void 0===n){const e=read(r);n=e?e.data:null}const a=indexCatalog(n);if(!Object.keys(a).length)return o.slice();const s=[];for(const e of o){if(!e||"object"!=typeof e)continue;const t="string"==typeof e.id?e.id.trim():"",r=t?a[t]:null;if(!r||!r.length){s.push(e);continue}const o=new Set(modelIdsOf(e)),n=r.filter((e=>!o.has(e)));if(!n.length){s.push(e);continue}const i=Array.isArray(e.models)?e.models:[];s.push({...e,models:[...i,...n]})}return s}function addedModelsFor(e,t,r,o){const n="string"==typeof e?e.trim():"";if(!n)return[];let a=r;if(void 0===a){const e=read(o);a=e?e.data:null}const s=indexCatalog(a)[n]||[],i=(providerArray(t)||[]).find((e=>e&&"string"==typeof e.id&&e.id.trim()===n)),l=new Set(modelIdsOf(i));return s.filter((e=>!l.has(e)))}const MAX_PAGES=200;async function refresh(e,t){const r=t||{},o=r.limit||500,n=r.maxPages||200,a=read(r),s=a&&a.data||null,i=[];let l=null,d=0,c=r.etag||null,u=null,f=!1;try{for(;;){const t=await e({cursor:l,limit:o,etag:c});if(!t||t.notModified){f=!0;break}0===d&&t.etag&&(u=t.etag);const r=Array.isArray(t.models)?t.models:[];for(const e of r)e&&"object"==typeof e&&i.push(e);if(d+=1,!t.has_more||!t.next_cursor)break;if(d>=n)return _refreshResult({ok:!1,changed:!1,pages:d,models:i.length,providers:0,staleKept:Boolean(s),reason:`stopped after ${d} pages; cache left untouched`});l=t.next_cursor,c=null}}catch(e){return _refreshResult({ok:!1,changed:!1,pages:d,models:0,providers:0,staleKept:Boolean(s),reason:e&&e.message||String(e)})}if(f){let e=null;if(s)try{const t="function"==typeof r.now?r.now():Date.now();e=write({...s,snapshot:{...s.snapshot||{},revalidated_at:new Date(t).toISOString(),...u?{etag:u}:{}}},r)}catch{e=null}return _refreshResult({ok:!0,changed:!1,pages:0,models:0,providers:0,staleKept:!e,written:e,reason:"not-modified"})}if(!i.length)return _refreshResult({ok:!1,changed:!1,pages:d,models:0,providers:0,staleKept:Boolean(s),reason:"empty catalog; cache left untouched"});const p=s&&Array.isArray(s.providers)?s.providers:[],h="function"==typeof r.now?r.now():Date.now(),g={schema_version:s&&s.schema_version||1,providers:p,models:i,snapshot:{fetched_at:new Date(h).toISOString(),models_seen:i.length,providers_seen:p.length,source:"catalog-api",...u?{etag:u}:{}}};let m=null;try{m=write(g,r)}catch(e){return _refreshResult({ok:!1,changed:!1,pages:d,models:i.length,providers:p.length,staleKept:Boolean(s),reason:e&&e.message||String(e)})}return _refreshResult({ok:!0,changed:!0,pages:d,models:i.length,providers:p.length,staleKept:!1,written:m})}function _refreshResult(e){return{ok:Boolean(e.ok),changed:Boolean(e.changed),written:e.written||null,pages:e.pages||0,models:e.models||0,providers:e.providers||0,staleKept:Boolean(e.staleKept),...e.reason?{reason:e.reason}:{}}}module.exports={CATALOG_FILE:CATALOG_FILE,STALE_AFTER_MS:STALE_AFTER_MS,MAX_PAGES:200,catalogDir:catalogDir,catalogPath:catalogPath,indexCatalog:indexCatalog,read:read,write:write,refresh:refresh,withCatalog:withCatalog,addedModelsFor:addedModelsFor};
@@ -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"),{execFileSync:execFileSync}=require("node:child_process"),SETTINGS_DIRS=[".aegis",".aegiscode"];function hookSettingPaths(o={}){const e=platformPath(o.platform),t=homeDir(o),n=o.cwd||process.cwd(),s=[];for(const o of SETTINGS_DIRS)s.push(e.join(t,o,"settings.json")),s.push(e.join(n,o,"settings.json"));return s.push(e.join(t,".claude","settings.json")),dedupe(s)}function platformPath(o){return"win32"===(o||process.platform)?path.win32:path.posix}function homeDir(o={}){if(o.home)return String(o.home);const e=o.env||process.env,t="win32"===(o.platform||process.platform)?["USERPROFILE","HOME"]:["HOME","USERPROFILE"];for(const o of t)if(e&&e[o])return String(e[o]);return os.homedir()}function hookSourceKind(o){const e=path.posix.basename(String(o).replace(/\\/g,"/")),t=path.posix.basename(path.posix.dirname(String(o).replace(/\\/g,"/")));return"settings.json"!==e?"other":".claude"===t?"foreign":SETTINGS_DIRS.includes(t)?"aegis":"other"}function dedupe(o){const e=new Set,t=[];for(const n of o){const o=String(n).replace(/\\/g,"/");e.has(o)||(e.add(o),t.push(n))}return t}function shorten(o,e={}){const t=homeDir(e),n=String(o);if(!t)return n;const s=n.replace(/\\/g,"/"),r=String(t).replace(/\\/g,"/").replace(/\/+$/,"");return s===r?"~":s.startsWith(`${r}/`)?`~${s.slice(r.length)}`:n}function readHookConfig(o={}){const e=o.readFile||defaultReadFile,t=o.paths||hookSettingPaths(o),n={},s=[],r=[],i=[];for(const a of t){let t,c=null;try{c=e(a)}catch{c=null}if(null==c){i.push({path:a,exists:!1,kind:hookSourceKind(a)});continue}try{t=JSON.parse(String(c))}catch{i.push({path:a,exists:!0,parsed:!1,kind:hookSourceKind(a)});continue}const h=hookSourceKind(a),u=eventsOf(t),d=Object.keys(u);if(i.push({path:a,exists:!0,parsed:!0,kind:h,events:d}),"foreign"!==h){if(d.length){s.push(shorten(a,o));for(const[o,e]of Object.entries(u))Array.isArray(e)&&e.length&&(n[o]=[...n[o]||[],...e])}}else r.push(shorten(a,o))}return{hooks:n,from:s,foreign:r,files:i}}function eventsOf(o){if(!o||"object"!=typeof o)return{};if(o.hooks&&"object"==typeof o.hooks&&!Array.isArray(o.hooks)){const e={};for(const[t,n]of Object.entries(o.hooks))Array.isArray(n)&&(e[t]=n);return e}const e={};for(const t of HOOK_EVENTS)Array.isArray(o[t])&&(e[t]=o[t]);return e}const HOOK_EVENTS=["PreToolUse","PostToolUse","PostToolUseFailure","PermissionRequest","UserPromptSubmit","SessionStart","SessionEnd","Stop","SubagentStop","Notification","Compaction"];function hookStats(o){const e=o&&"object"==typeof o?o:{},t=Object.keys(e);let n=0;const s={};for(const o of t){const t=Array.isArray(e[o])?e[o]:[];s[o]=t.length,n+=t.length}return{enabled:n>0,hooks:n,events:t,byEvent:s}}const REQUIRED_HOOKS=["pre-commit","pre-push"],OPTIONAL_HOOKS=["post-merge","lib-gate.sh","push-policy"];function defaultRunGit(o,{cwd:e,env:t}={}){try{const n=execFileSync("git",o,{cwd:e,env:t||process.env,encoding:"utf8",stdio:["ignore","pipe","pipe"],windowsHide:!0});return{ok:!0,out:String(n).trim(),err:""}}catch(o){return{ok:!1,out:String(o&&o.stdout?o.stdout:"").trim(),err:String(o&&o.stderr?o.stderr:o&&o.message||o).trim()}}}function defaultReadFile(o){return fs.readFileSync(o,"utf8")}function defaultExists(o){try{return fs.statSync(o).isFile()}catch{return!1}}function defaultChmod(o){fs.chmodSync(o,493)}function repoHookStatus(o={}){const e=o.platform||process.platform,t=platformPath(e),n=o.cwd||process.cwd(),s=o.exists||defaultExists,r=o.runGit||defaultRunGit,i=t.join(n,".githooks"),a=[],c=[];for(const o of[...REQUIRED_HOOKS,...OPTIONAL_HOOKS])s(t.join(i,o))?a.push(o):c.push(o);const h=r(["rev-parse","--is-inside-work-tree"],{cwd:n,env:o.env}),u=h.ok&&"true"===h.out;let d=null;if(u){const e=r(["config","--get","core.hooksPath"],{cwd:n,env:o.env});d=e.ok&&e.out?e.out:null}const f=".githooks";var l;return{repo:n,hooksDir:i,platform:e,inGitRepo:u,configured:d,wanted:f,installed:u&&(null==(l=d)?null:String(l).replace(/\\/g,"/").replace(/\/+$/,""))===f,present:a,missing:c,execBit:"win32"!==e,execNote:"win32"===e?"Windows: the exec bit is not enforced and not needed — git for Windows runs hooks with its bundled sh.":"POSIX: the hooks are chmod 0755 so git can execute them."}}function installRepoHooks(o={}){const e=o.platform||process.platform,t=platformPath(e),n=o.cwd||process.cwd(),s=o.runGit||defaultRunGit,r=o.exists||defaultExists,i=o.chmod||defaultChmod,a=Boolean(o.dryRun),c=repoHookStatus({...o,platform:e,cwd:n,runGit:s,exists:r}),h=[];if(!r(t.join(c.hooksDir,"pre-commit")))return{ok:!1,changed:!1,code:"no-hooks",actions:h,status:c,error:`no ${c.wanted}/pre-commit under ${n} — nothing to install. A tree that never had the hooks needs them restored (\`git checkout -- .githooks/\`) or created (\`agent-gate.mjs init --hooks\`).`};if(!c.inGitRepo)return{ok:!1,changed:!1,code:"no-git",actions:h,status:c,error:`${n} is not inside a git work tree (core.hooksPath is a per-repo setting), or git is not on PATH.`};if(!c.installed&&(h.push(`git -C ${n} config core.hooksPath ${c.wanted}`),!a)){const e=s(["config","core.hooksPath",c.wanted],{cwd:n,env:o.env});if(!e.ok)return{ok:!1,changed:!1,code:"git-failed",actions:h,status:c,error:`git config refused: ${e.err||"unknown error"}`};const t=s(["config","--get","core.hooksPath"],{cwd:n,env:o.env}),r=t.ok?String(t.out).replace(/\\/g,"/").replace(/\/+$/,""):null;if(r!==c.wanted)return{ok:!1,changed:!0,code:"verify-failed",actions:h,status:c,error:`core.hooksPath reads back as "${r||"(unset)"}", not "${c.wanted}"`}}const u=[];if("win32"!==e){const e=o.modeOf||(o=>{try{return 511&fs.statSync(o).mode}catch{return null}});for(const o of c.present.filter((o=>"push-policy"!==o))){const n=t.join(c.hooksDir,o);if(493!==e(n))if(a)u.push(`chmod 0755 ${n}`);else try{i(n,493),u.push(`chmod 0755 ${o}`)}catch(e){u.push(`chmod 0755 ${o} FAILED: ${e&&e.message||e}`)}}h.push(...u)}return d={modes:u,note:c.execNote},{ok:!0,changed:h.length>0,code:"installed",actions:h,status:c,...d};var d}function hooksSummary(o={}){const e=o.platform||process.platform,t=o.config||readHookConfig({...o,platform:e}),n=o.stats||hookStats(t.hooks),s=o.repo||repoHookStatus({...o,platform:e}),r=[];if(r.push(`hooks: ${n.enabled?"enabled":"disabled"} · ${n.hooks} matcher(s) in ${n.events.length} event(s)`),n.events.length)for(const o of n.events)r.push(` ${o}: ${n.byEvent[o]}`);else r.push(" (no settings.json declares hooks — checked "+hookSettingPaths({...o,platform:e}).map((e=>shorten(e,o))).join(", ")+")");return t.from.length&&r.push(` from: ${t.from.join(", ")}`),t.foreign&&t.foreign.length&&r.push(` foreign host files (read, listed—${n.hooks&&t.foreign.length?"may outrank ours":"no hooks"}): ${t.foreign.join(", ")}`),r.push(""),r.push(`repo guard hooks (${s.wanted}/): ${s.present.length?s.present.join(", "):"none found"}`),s.missing.length&&r.push(` missing: ${s.missing.join(", ")}`),r.push(" core.hooksPath: "+(s.installed?`${s.wanted} (installed)`:`${s.configured||"(unset)"} — NOT installed, so a commit runs NO guard hooks`)),r.push(` ${s.execNote}`),r.join("\n")}module.exports={HOOK_EVENTS:HOOK_EVENTS,SETTINGS_DIRS:SETTINGS_DIRS,hooksSummary:hooksSummary,REQUIRED_HOOKS:REQUIRED_HOOKS,OPTIONAL_HOOKS:OPTIONAL_HOOKS,hookSettingPaths:hookSettingPaths,hookSourceKind:hookSourceKind,homeDir:homeDir,platformPath:platformPath,shorten:shorten,readHookConfig:readHookConfig,hookStats:hookStats,repoHookStatus:repoHookStatus,installRepoHooks:installRepoHooks};
3
+ "use strict";const fs=require("node:fs"),os=require("node:os"),path=require("node:path"),{execFileSync:execFileSync}=require("node:child_process"),SETTINGS_DIRS=[".aegis",".aegiscode"];function hookSettingPaths(o={}){const e=platformPath(o.platform),t=homeDir(o),n=o.cwd||process.cwd(),s=[];for(const o of SETTINGS_DIRS)s.push(e.join(t,o,"settings.json")),s.push(e.join(n,o,"settings.json"));return s.push(e.join(t,".claude","settings.json")),dedupe(s)}function platformPath(o){return"win32"===(o||process.platform)?path.win32:path.posix}function homeDir(o={}){if(o.home)return String(o.home);const e=o.env||process.env,t="win32"===(o.platform||process.platform)?["USERPROFILE","HOME"]:["HOME","USERPROFILE"];for(const o of t)if(e&&e[o])return String(e[o]);return os.homedir()}function hookSourceKind(o){const e=path.posix.basename(String(o).replace(/\\/g,"/")),t=path.posix.basename(path.posix.dirname(String(o).replace(/\\/g,"/")));return"settings.json"!==e?"other":".claude"===t?"foreign":SETTINGS_DIRS.includes(t)?"aegis":"other"}function dedupe(o){const e=new Set,t=[];for(const n of o){const o=String(n).replace(/\\/g,"/");e.has(o)||(e.add(o),t.push(n))}return t}function shorten(o,e={}){const t=homeDir(e),n=String(o);if(!t)return n;const s=n.replace(/\\/g,"/"),r=String(t).replace(/\\/g,"/").replace(/\/+$/,"");return s===r?"~":s.startsWith(`${r}/`)?`~${s.slice(r.length)}`:n}function readHookConfig(o={}){const e=o.readFile||defaultReadFile,t=o.paths||hookSettingPaths(o),n={},s=[],r=[],i=[];for(const a of t){let t,c=null;try{c=e(a)}catch{c=null}if(null==c){i.push({path:a,exists:!1,kind:hookSourceKind(a)});continue}try{t=JSON.parse(String(c))}catch{i.push({path:a,exists:!0,parsed:!1,kind:hookSourceKind(a)});continue}const h=hookSourceKind(a),u=eventsOf(t),d=Object.keys(u);if(i.push({path:a,exists:!0,parsed:!0,kind:h,events:d}),"foreign"!==h){if(d.length){s.push(shorten(a,o));for(const[o,e]of Object.entries(u))Array.isArray(e)&&e.length&&(n[o]=[...n[o]||[],...e])}}else r.push(shorten(a,o))}return{hooks:n,from:s,foreign:r,files:i}}function eventsOf(o){if(!o||"object"!=typeof o)return{};if(o.hooks&&"object"==typeof o.hooks&&!Array.isArray(o.hooks)){const e={};for(const[t,n]of Object.entries(o.hooks))Array.isArray(n)&&(e[t]=n);return e}const e={};for(const t of HOOK_EVENTS)Array.isArray(o[t])&&(e[t]=o[t]);return e}const HOOK_EVENTS=["PreToolUse","PostToolUse","PostToolUseFailure","PermissionRequest","UserPromptSubmit","SessionStart","SessionEnd","Stop","SubagentStop","Notification","Compaction"];function hookStats(o){const e=o&&"object"==typeof o?o:{},t=Object.keys(e);let n=0;const s={};for(const o of t){const t=Array.isArray(e[o])?e[o]:[];s[o]=t.length,n+=t.length}return{enabled:n>0,hooks:n,events:t,byEvent:s}}const REQUIRED_HOOKS=["pre-commit","pre-push"],OPTIONAL_HOOKS=["post-merge","lib-gate.sh","push-policy"];function defaultRunGit(o,{cwd:e,env:t}={}){try{const n=execFileSync("git",o,{cwd:e,env:t||process.env,encoding:"utf8",stdio:["ignore","pipe","pipe"],windowsHide:!0});return{ok:!0,out:String(n).trim(),err:""}}catch(o){return{ok:!1,out:String(o&&o.stdout?o.stdout:"").trim(),err:String(o&&o.stderr?o.stderr:o&&o.message||o).trim()}}}function defaultReadFile(o){return fs.readFileSync(o,"utf8")}function defaultExists(o){try{return fs.statSync(o).isFile()}catch{return!1}}function defaultChmod(o){fs.chmodSync(o,493)}function repoHookStatus(o={}){const e=o.platform||process.platform,t=platformPath(e),n=o.cwd||process.cwd(),s=o.exists||defaultExists,r=o.runGit||defaultRunGit,i=t.join(n,".githooks"),a=[],c=[];for(const o of[...REQUIRED_HOOKS,...OPTIONAL_HOOKS])s(t.join(i,o))?a.push(o):c.push(o);const h=r(["rev-parse","--is-inside-work-tree"],{cwd:n,env:o.env}),u=h.ok&&"true"===h.out;let d=null;if(u){const e=r(["config","--get","core.hooksPath"],{cwd:n,env:o.env});d=e.ok&&e.out?e.out:null}const f=".githooks";var l;return{repo:n,hooksDir:i,platform:e,inGitRepo:u,configured:d,wanted:f,installed:u&&(null==(l=d)?null:String(l).replace(/\\/g,"/").replace(/\/+$/,""))===f,present:a,missing:c,execBit:"win32"!==e,execNote:"win32"===e?"Windows: the exec bit is not enforced and not needed — git for Windows runs hooks with its bundled sh.":"POSIX: the hooks are chmod 0755 so git can execute them."}}function installRepoHooks(o={}){const e=o.platform||process.platform,t=platformPath(e),n=o.cwd||process.cwd(),s=o.runGit||defaultRunGit,r=o.exists||defaultExists,i=o.chmod||defaultChmod,a=Boolean(o.dryRun),c=repoHookStatus({...o,platform:e,cwd:n,runGit:s,exists:r}),h=[];if(!r(t.join(c.hooksDir,"pre-commit")))return{ok:!1,changed:!1,code:"no-hooks",actions:h,status:c,error:`no ${c.wanted}/pre-commit under ${n} — nothing to install. A tree that never had the hooks needs them restored (\`git checkout -- .githooks/\`) or created (\`agent-gate.mjs init --hooks\`).`};if(!c.inGitRepo)return{ok:!1,changed:!1,code:"no-git",actions:h,status:c,error:`${n} is not inside a git work tree (core.hooksPath is a per-repo setting), or git is not on PATH.`};if(!c.installed&&(h.push(`git -C ${n} config core.hooksPath ${c.wanted}`),!a)){const e=s(["config","core.hooksPath",c.wanted],{cwd:n,env:o.env});if(!e.ok)return{ok:!1,changed:!1,code:"git-failed",actions:h,status:c,error:`git config refused: ${e.err||"unknown error"}`};const t=s(["config","--get","core.hooksPath"],{cwd:n,env:o.env}),r=t.ok?String(t.out).replace(/\\/g,"/").replace(/\/+$/,""):null;if(r!==c.wanted)return{ok:!1,changed:!0,code:"verify-failed",actions:h,status:c,error:`core.hooksPath reads back as "${r||"(unset)"}", not "${c.wanted}"`}}const u=[];if("win32"!==e){const n=o.modeOf||(o=>{try{return 511&fs.statSync(o).mode}catch{return null}});for(const o of c.present.filter((o=>"push-policy"!==o))){const s=t.join(c.hooksDir,o);if(493!==n(s))if(a)u.push(`chmod 0755 ${s}`);else try{i(s,493),u.push(`chmod 0755 ${o}`)}catch(e){u.push(`chmod 0755 ${o} FAILED: ${e&&e.message||e}`)}}h.push(...u)}return d={modes:u,note:c.execNote},{ok:!0,changed:h.length>0,code:"installed",actions:h,status:c,...d};var d}function hooksSummary(o={}){const e=o.platform||process.platform,t=o.config||readHookConfig({...o,platform:e}),n=o.stats||hookStats(t.hooks),s=o.repo||repoHookStatus({...o,platform:e}),r=[];if(r.push(`hooks: ${n.enabled?"enabled":"disabled"} · ${n.hooks} matcher(s) in ${n.events.length} event(s)`),n.events.length)for(const o of n.events)r.push(` ${o}: ${n.byEvent[o]}`);else r.push(" (no settings.json declares hooks — checked "+hookSettingPaths({...o,platform:e}).map((e=>shorten(e,o))).join(", ")+")");return t.from.length&&r.push(` from: ${t.from.join(", ")}`),t.foreign&&t.foreign.length&&r.push(` foreign host files (read, listed—${n.hooks&&t.foreign.length?"may outrank ours":"no hooks"}): ${t.foreign.join(", ")}`),r.push(""),r.push(`repo guard hooks (${s.wanted}/): ${s.present.length?s.present.join(", "):"none found"}`),s.missing.length&&r.push(` missing: ${s.missing.join(", ")}`),r.push(" core.hooksPath: "+(s.installed?`${s.wanted} (installed)`:`${s.configured||"(unset)"} — NOT installed, so a commit runs NO guard hooks`)),r.push(` ${s.execNote}`),r.join("\n")}module.exports={HOOK_EVENTS:HOOK_EVENTS,SETTINGS_DIRS:SETTINGS_DIRS,hooksSummary:hooksSummary,REQUIRED_HOOKS:REQUIRED_HOOKS,OPTIONAL_HOOKS:OPTIONAL_HOOKS,hookSettingPaths:hookSettingPaths,hookSourceKind:hookSourceKind,homeDir:homeDir,platformPath:platformPath,shorten:shorten,readHookConfig:readHookConfig,hookStats:hookStats,repoHookStatus:repoHookStatus,installRepoHooks:installRepoHooks};
@@ -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{sanitizeModel:sanitizeModel}=require("./user-models.js"),DISCOVERY_TIMEOUT_MS=8e3;function bearer(e){return{authorization:`Bearer ${e}`}}const ENDPOINTS=Object.freeze({anthropic:Object.freeze({url:"https://api.anthropic.com/v1/models",headers:e=>({"x-api-key":e,"anthropic-version":"2023-06-01"}),note:"the vendor requires anthropic-version; the console key is sent as x-api-key"}),openai:Object.freeze({url:"https://api.openai.com/v1/models",headers:bearer,note:"OpenAI-compatible: { data: [ { id } ] }"}),deepseek:Object.freeze({url:"https://api.deepseek.com/models",headers:bearer,note:"OpenAI-compatible; /v1/models answers the same list"}),grok:Object.freeze({url:"https://api.x.ai/v1/models",headers:bearer,note:"xAI answers on /v1/models under the vendor id grok"}),gemini:Object.freeze({url:"https://generativelanguage.googleapis.com/v1beta/models",headers:()=>({}),query:e=>({key:e}),note:'the key travels in the query string; ids come back as "models/<id>"'}),groq:Object.freeze({url:"https://api.groq.com/openai/v1/models",headers:bearer,note:"OpenAI-compatible under /openai/v1"}),mistral:Object.freeze({url:"https://api.mistral.ai/v1/models",headers:bearer,note:"OpenAI-compatible"}),openrouter:Object.freeze({url:"https://openrouter.ai/api/v1/models",headers:bearer,note:'OpenAI-compatible; ids are prefixed "vendor/model"'}),together:Object.freeze({url:"https://api.together.xyz/v1/models",headers:bearer,note:"OpenAI-compatible"}),cerebras:Object.freeze({url:"https://api.cerebras.ai/v1/models",headers:bearer,note:"OpenAI-compatible under /v1"}),fireworks:Object.freeze({url:"https://api.fireworks.ai/inference/v1/models",headers:bearer,note:'OpenAI-compatible under /inference/v1; ids are "accounts/fireworks/models/<id>"'}),nvidia_nim:Object.freeze({url:"https://integrate.api.nvidia.com/v1/models",headers:bearer,note:'OpenAI-compatible; ids are "<vendor>/<model>"'}),sakana:Object.freeze({url:"https://api.sakana.ai/v1/models",headers:bearer,note:"OpenAI-compatible under /v1"})}),ALIASES=Object.freeze({"x.ai":"grok",xai:"grok",google:"gemini","google-ai":"gemini",googleai:"gemini","open-ai":"openai","deep-seek":"deepseek","openai-gpt4o-mini":"openai","anthropic-haiku":"anthropic"}),NON_CHAT_RE=/embed|whisper|\btts\b|dall-e|moderation|rerank|imagen|\bveo\b|\baqa\b|transcribe|audio|speech|synthia|guard-content/i;function endpointFor(e){const r=String(null==e?"":e).trim().toLowerCase();if(!r)return null;const o=ALIASES[r]||r,t=ENDPOINTS[o];return t?Object.freeze({id:o,...t}):null}function canDiscover(e){return Boolean(endpointFor(e))}function discoverableProviders(){return Object.keys(ENDPOINTS).sort()}function looksNonChat(e){return NON_CHAT_RE.test(String(e))}function idsFromPayload(e){const r=Array.isArray(e)?e:Array.isArray(e&&e.data)?e.data:Array.isArray(e&&e.models)?e.models:null;if(!r)return null;const o=[],t=[];for(const e of r){if(null==e)continue;const r="string"==typeof e?e:e.id||e.name||e.model;if("string"!=typeof r||!r.trim())continue;const n=r.trim().replace(/^models\//,""),i=e&&Array.isArray(e.supportedGenerationMethods)?e.supportedGenerationMethods:e&&Array.isArray(e.supported_actions)?e.supported_actions:null,s=i?i.includes("generateContent")||i.includes("generate"):null;let a;try{a=sanitizeModel(n)}catch{continue}!1===s||null===s&&looksNonChat(a)?t.push(a):o.push(a)}const n=e=>[...new Set(e)];return{ids:n(o),others:n(t).filter((e=>!o.includes(e)))}}async function discoverModels(e,r={}){const o=endpointFor(e),t=String(null==e?"":e).trim().toLowerCase(),n=String(null==r.key?"":r.key).trim();if(!o)return{ok:!1,provider:t,supported:!1,error:`${t||"that provider"} has no model-list endpoint this client knows`};if(!n)return{ok:!1,provider:o.id,supported:!0,error:`no ${o.id} key on this machine`};const i=r.fetchImpl||("function"==typeof fetch?fetch:null);if(!i)return{ok:!1,provider:o.id,supported:!0,error:"no fetch implementation available"};const s=Number.isFinite(r.timeoutMs)?r.timeoutMs:8e3,a="function"==typeof AbortController?new AbortController:null,d=a?setTimeout((()=>a.abort()),s):null,l=()=>a&&a.abort();a&&r.signal&&(r.signal.aborted?l():"function"==typeof r.signal.addEventListener&&r.signal.addEventListener("abort",l,{once:!0}));try{const e=new URL(o.url);if("function"==typeof o.query)for(const[r,t]of Object.entries(o.query(n)||{}))e.searchParams.set(r,t);const r={accept:"application/json"};for(const[e,t]of Object.entries(o.headers(n)||{}))r["authorization"===e?"Authorization":e]=t;const t=await i(e.toString(),{method:"GET",headers:r,signal:a?a.signal:void 0}),s=t&&"number"==typeof t.status?t.status:0;if(!t||"boolean"==typeof t.ok&&!t.ok){const r=401===s||403===s?`the vendor refused the key (HTTP ${s})`:404===s?`the vendor has no model list at ${e.pathname} (HTTP 404)`:`the vendor answered HTTP ${s||"nothing"}`;return{ok:!1,provider:o.id,supported:!0,status:s,error:r}}let d;try{d=await t.json()}catch(e){return{ok:!1,provider:o.id,supported:!0,status:s,error:`the vendor's reply was not JSON (${e&&e.message||e})`}}const l=idsFromPayload(d);return l?{ok:!0,provider:o.id,endpoint:o.url,ids:l.ids,others:l.others,count:l.ids.length}:{ok:!1,provider:o.id,supported:!0,status:s,error:'the vendor answered in a shape this client does not know (no "data" or "models" list)'}}catch(e){const r=e&&("AbortError"===e.name||"ABORT_ERR"===e.code)||a&&a.signal.aborted;return{ok:!1,provider:o.id,supported:!0,error:r?`the vendor did not answer within ${s} ms`:`could not reach the vendor (${e&&e.message||e})`}}finally{d&&clearTimeout(d),a&&r.signal&&"function"==typeof r.signal.removeEventListener&&r.signal.removeEventListener("abort",l)}}module.exports={DISCOVERY_TIMEOUT_MS:8e3,ENDPOINTS:ENDPOINTS,ALIASES:ALIASES,NON_CHAT_RE:NON_CHAT_RE,endpointFor:endpointFor,canDiscover:canDiscover,discoverableProviders:discoverableProviders,looksNonChat:looksNonChat,idsFromPayload:idsFromPayload,discoverModels:discoverModels};
3
+ "use strict";const{sanitizeModel:sanitizeModel}=require("./user-models.js"),DISCOVERY_TIMEOUT_MS=8e3;function bearer(e){return{authorization:`Bearer ${e}`}}const ENDPOINTS=Object.freeze({anthropic:Object.freeze({url:"https://api.anthropic.com/v1/models",headers:e=>({"x-api-key":e,"anthropic-version":"2023-06-01"}),note:"the vendor requires anthropic-version; the console key is sent as x-api-key"}),openai:Object.freeze({url:"https://api.openai.com/v1/models",headers:bearer,note:"OpenAI-compatible: { data: [ { id } ] }"}),deepseek:Object.freeze({url:"https://api.deepseek.com/models",headers:bearer,note:"OpenAI-compatible; /v1/models answers the same list"}),grok:Object.freeze({url:"https://api.x.ai/v1/models",headers:bearer,note:"xAI answers on /v1/models under the vendor id grok"}),gemini:Object.freeze({url:"https://generativelanguage.googleapis.com/v1beta/models",headers:()=>({}),query:e=>({key:e}),note:'the key travels in the query string; ids come back as "models/<id>"'}),groq:Object.freeze({url:"https://api.groq.com/openai/v1/models",headers:bearer,note:"OpenAI-compatible under /openai/v1"}),mistral:Object.freeze({url:"https://api.mistral.ai/v1/models",headers:bearer,note:"OpenAI-compatible"}),openrouter:Object.freeze({url:"https://openrouter.ai/api/v1/models",headers:bearer,note:'OpenAI-compatible; ids are prefixed "vendor/model"'}),together:Object.freeze({url:"https://api.together.xyz/v1/models",headers:bearer,note:"OpenAI-compatible"}),cerebras:Object.freeze({url:"https://api.cerebras.ai/v1/models",headers:bearer,note:"OpenAI-compatible under /v1"}),fireworks:Object.freeze({url:"https://api.fireworks.ai/inference/v1/models",headers:bearer,note:'OpenAI-compatible under /inference/v1; ids are "accounts/fireworks/models/<id>"'}),nvidia_nim:Object.freeze({url:"https://integrate.api.nvidia.com/v1/models",headers:bearer,note:'OpenAI-compatible; ids are "<vendor>/<model>"'}),sakana:Object.freeze({url:"https://api.sakana.ai/v1/models",headers:bearer,note:"OpenAI-compatible under /v1"})}),ALIASES=Object.freeze({"x.ai":"grok",xai:"grok",google:"gemini","google-ai":"gemini",googleai:"gemini","open-ai":"openai","deep-seek":"deepseek","openai-gpt4o-mini":"openai","anthropic-haiku":"anthropic"}),NON_CHAT_RE=/embed|whisper|\btts\b|dall-e|moderation|rerank|imagen|\bveo\b|\baqa\b|transcribe|audio|speech|synthia|guard-content/i;function endpointFor(e){const r=String(null==e?"":e).trim().toLowerCase();if(!r)return null;const o=ALIASES[r]||r,t=ENDPOINTS[o];return t?Object.freeze({id:o,...t}):null}function canDiscover(e){return Boolean(endpointFor(e))}function discoverableProviders(){return Object.keys(ENDPOINTS).sort()}function looksNonChat(e){return NON_CHAT_RE.test(String(e))}function idsFromPayload(e){const r=Array.isArray(e)?e:Array.isArray(e&&e.data)?e.data:Array.isArray(e&&e.models)?e.models:null;if(!r)return null;const o=[],t=[];for(const e of r){if(null==e)continue;const r="string"==typeof e?e:e.id||e.name||e.model;if("string"!=typeof r||!r.trim())continue;const n=r.trim().replace(/^models\//,""),i=e&&Array.isArray(e.supportedGenerationMethods)?e.supportedGenerationMethods:e&&Array.isArray(e.supported_actions)?e.supported_actions:null,s=i?i.includes("generateContent")||i.includes("generate"):null;let a;try{a=sanitizeModel(n)}catch{continue}!1===s||null===s&&looksNonChat(a)?t.push(a):o.push(a)}const n=e=>[...new Set(e)];return{ids:n(o),others:n(t).filter((e=>!o.includes(e)))}}async function discoverModels(e,r={}){const o=endpointFor(e),t=String(null==e?"":e).trim().toLowerCase(),n=String(null==r.key?"":r.key).trim();if(!o)return{ok:!1,provider:t,supported:!1,error:`${t||"that provider"} has no model-list endpoint this client knows`};if(!n)return{ok:!1,provider:o.id,supported:!0,error:`no ${o.id} key on this machine`};const i=r.fetchImpl||("function"==typeof fetch?fetch:null);if(!i)return{ok:!1,provider:o.id,supported:!0,error:"no fetch implementation available"};const s=Number.isFinite(r.timeoutMs)?r.timeoutMs:8e3,a="function"==typeof AbortController?new AbortController:null,d=a?setTimeout((()=>a.abort()),s):null,l=()=>a&&a.abort();a&&r.signal&&(r.signal.aborted?l():"function"==typeof r.signal.addEventListener&&r.signal.addEventListener("abort",l,{once:!0}));try{const r=new URL(o.url);if("function"==typeof o.query)for(const[e,t]of Object.entries(o.query(n)||{}))r.searchParams.set(e,t);const t={accept:"application/json"};for(const[e,r]of Object.entries(o.headers(n)||{}))t["authorization"===e?"Authorization":e]=r;const s=await i(r.toString(),{method:"GET",headers:t,signal:a?a.signal:void 0}),d=s&&"number"==typeof s.status?s.status:0;if(!s||"boolean"==typeof s.ok&&!s.ok){const e=401===d||403===d?`the vendor refused the key (HTTP ${d})`:404===d?`the vendor has no model list at ${r.pathname} (HTTP 404)`:`the vendor answered HTTP ${d||"nothing"}`;return{ok:!1,provider:o.id,supported:!0,status:d,error:e}}let l;try{l=await s.json()}catch(e){return{ok:!1,provider:o.id,supported:!0,status:d,error:`the vendor's reply was not JSON (${e&&e.message||e})`}}const c=idsFromPayload(l);return c?{ok:!0,provider:o.id,endpoint:o.url,ids:c.ids,others:c.others,count:c.ids.length}:{ok:!1,provider:o.id,supported:!0,status:d,error:'the vendor answered in a shape this client does not know (no "data" or "models" list)'}}catch(e){const r=e&&("AbortError"===e.name||"ABORT_ERR"===e.code)||a&&a.signal.aborted;return{ok:!1,provider:o.id,supported:!0,error:r?`the vendor did not answer within ${s} ms`:`could not reach the vendor (${e&&e.message||e})`}}finally{d&&clearTimeout(d),a&&r.signal&&"function"==typeof r.signal.removeEventListener&&r.signal.removeEventListener("abort",l)}}module.exports={DISCOVERY_TIMEOUT_MS:8e3,ENDPOINTS:ENDPOINTS,ALIASES:ALIASES,NON_CHAT_RE:NON_CHAT_RE,endpointFor:endpointFor,canDiscover:canDiscover,discoverableProviders:discoverableProviders,looksNonChat:looksNonChat,idsFromPayload:idsFromPayload,discoverModels:discoverModels};
@@ -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
- 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}};
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,a,s={}){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={...s,seeded:!(!l||l.named)},h=await g(u,a,c);if(h){try{t.setTitle(i,r,h,{named:!0})}catch{return null}return h}if(o(a)&&l&&!l.named&&!n(u)){try{t.setTitle(i,r,e)}catch{return null}return e}return null}};
@@ -95,11 +95,11 @@
95
95
  * user's Drive or their account. The remote/root are overridable the same way
96
96
  * (`AEGIS_VAULT_REMOTE`/`AEGIS_VAULT_ROOT`, `AEGIS_VAULT_BACKEND`), which is
97
97
  * also what keeps a misconfigured vault from writing into an unrelated folder.
98
- */const crypto=require("node:crypto"),fs=require("node:fs"),os=require("node:os"),path=require("node:path"),{execFileSync:execFileSync}=require("node:child_process"),fp=require("./fingerprint.js"),authorship=require("./authorship-key.js"),BACKEND_CLOUD="aegiscloud",BACKEND_RCLONE="rclone",DEFAULT_BACKEND=BACKEND_CLOUD,DEFAULT_REMOTE="gdrive",DEFAULT_ROOT="AEGIS-AGPL",RECORDS_DIR="records",INDEX_NAME="index.jsonl",ANCHOR_SUFFIX=".anchor.json",ANCHOR_VERSION=1,ANCHOR_KIND="aegiscode.record.anchor",INDEX_KIND="aegiscode.record.index",RCLONE_ENV="AEGIS_VAULT_RCLONE",REMOTE_ENV="AEGIS_VAULT_REMOTE",ROOT_ENV="AEGIS_VAULT_ROOT",BACKEND_ENV="AEGIS_VAULT_BACKEND",API_BASE_ENV="AEGIS_API_BASE",CLOUD_PREFIX="/api/v1/vault",RCLONE_TIMEOUT_MS=6e4,MAX_INSPECT_BYTES=2097152,MAX_AUDIT_FILES=500,KEY_PATH_PATTERNS=[/(^|\/)keys?\//i,/\.key$/i,/\.pem$/i,/(^|\/)id_(rsa|dsa|ecdsa|ed25519)(\.|$)/i,/(^|\/)agent\.key(\.|$)/i],BARE_TOKEN=/^[A-Za-z0-9_\-+/=]{40,}$/,BARE_HEX=/^[0-9a-fA-F]{32,}$/,PEM_PRIVATE=/-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----/;function flag(e,t,r=null){const n=Array.isArray(e)?e:[],o=n.indexOf(t);return-1===o||void 0===n[o+1]||String(n[o+1]).startsWith("--")?r:n[o+1]}function has(e,t){return(Array.isArray(e)?e:[]).includes(t)}function rcloneBinary(e=process.env,t=[]){return flag(t,"--rclone")||e[RCLONE_ENV]||"rclone"}function vaultTarget(e=process.env,t=[],r=null){const n=flag(t,"--remote")||e[REMOTE_ENV]||r&&r.remote||DEFAULT_REMOTE;return{backend:backendFor(e,t,n,r),remote:n,root:flag(t,"--root")||e[ROOT_ENV]||r&&r.root||DEFAULT_ROOT,apiBase:String(flag(t,"--base")||e[API_BASE_ENV]||"https://aegiscloud.org").replace(/\/+$/,""),rclone:rcloneBinary(e,t),env:e}}function backendFor(e,t,r,n=null){const o=String(flag(t,"--backend")||e[BACKEND_ENV]||"").trim().toLowerCase();if(o){if(o!==BACKEND_CLOUD&&o!==BACKEND_RCLONE)throw new Error(`vault: unknown backend "${o}" — expected ${BACKEND_CLOUD} or ${BACKEND_RCLONE}`);return o}return flag(t,"--remote")||e[REMOTE_ENV]?BACKEND_RCLONE:!n||n.backend!==BACKEND_CLOUD&&n.backend!==BACKEND_RCLONE?n&&void 0===n.backend&&n.remote&&n.remote!==DEFAULT_REMOTE?BACKEND_RCLONE:DEFAULT_BACKEND:n.backend}function remoteSpec(e,...t){return`${e.remote}:${[e.root,...t].filter(Boolean).join("/")}`}
98
+ */const crypto=require("node:crypto"),fs=require("node:fs"),os=require("node:os"),path=require("node:path"),{execFileSync:execFileSync}=require("node:child_process"),fp=require("./fingerprint.js"),authorship=require("./authorship-key.js"),BACKEND_CLOUD="aegiscloud",BACKEND_RCLONE="rclone",DEFAULT_BACKEND=BACKEND_CLOUD,DEFAULT_REMOTE="gdrive",DEFAULT_ROOT="AEGIS-AGPL",RECORDS_DIR="records",INDEX_NAME="index.jsonl",ANCHOR_SUFFIX=".anchor.json",ANCHOR_VERSION=1,ANCHOR_KIND="aegiscode.record.anchor",INDEX_KIND="aegiscode.record.index",RCLONE_ENV="AEGIS_VAULT_RCLONE",REMOTE_ENV="AEGIS_VAULT_REMOTE",ROOT_ENV="AEGIS_VAULT_ROOT",BACKEND_ENV="AEGIS_VAULT_BACKEND",API_BASE_ENV="AEGIS_API_BASE",CLOUD_PREFIX="/api/v1/vault",RCLONE_TIMEOUT_MS=6e4,MAX_INSPECT_BYTES=2097152,MAX_AUDIT_FILES=500,KEY_PATH_PATTERNS=[/(^|\/)keys?\//i,/\.key$/i,/\.pem$/i,/(^|\/)id_(rsa|dsa|ecdsa|ed25519)(\.|$)/i,/(^|\/)agent\.key(\.|$)/i],BARE_TOKEN=/^[A-Za-z0-9_\-+/=]{40,}$/,BARE_HEX=/^[0-9a-fA-F]{32,}$/,PEM_PRIVATE=/-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----/;function flag(e,t,r=null){const n=Array.isArray(e)?e:[],o=n.indexOf(t);return-1===o||void 0===n[o+1]||String(n[o+1]).startsWith("--")?r:n[o+1]}function has(e,t){return(Array.isArray(e)?e:[]).includes(t)}function rcloneBinary(e=process.env,t=[]){return flag(t,"--rclone")||e[RCLONE_ENV]||"rclone"}function vaultTarget(e=process.env,t=[],r=null){const n=flag(t,"--remote")||e[REMOTE_ENV]||r&&r.remote||DEFAULT_REMOTE;return{backend:backendFor(e,t,n,r),remote:n,root:flag(t,"--root")||e[ROOT_ENV]||r&&r.root||DEFAULT_ROOT,apiBase:String(flag(t,"--base")||e[API_BASE_ENV]||"https://aegiscloud.org").replace(/\/+$/,""),rclone:rcloneBinary(e,t),env:e}}function backendFor(e,t,r,n=null){const o=String(flag(t,"--backend")||e[BACKEND_ENV]||"").trim().toLowerCase();if(o){if(o!==BACKEND_CLOUD&&o!==BACKEND_RCLONE)throw new Error(`vault: unknown backend "${o}" — expected ${BACKEND_CLOUD} or ${BACKEND_RCLONE}`);return o}return flag(t,"--remote")||e[REMOTE_ENV]?BACKEND_RCLONE:!n||n.backend!==BACKEND_CLOUD&&n.backend!==BACKEND_RCLONE?n&&void 0===n.backend&&n.remote&&n.remote!==DEFAULT_REMOTE?BACKEND_RCLONE:DEFAULT_BACKEND:n.backend}function remoteSpec(e,...t){return`${e.remote}:${[e.root,...t].filter(Boolean).join("/")}`
99
99
  /**
100
100
  * A path *below* the root, however it was written: `records/x.json`,
101
101
  * `<root>/records/x.json`, or an absolute `remote:…` spec. Everything that
102
102
  * reads tolerates all three, because the anchor stores the browsable
103
103
  * root-prefixed form (a human reads `AEGIS-AGPL/records/x.json`) while rclone
104
104
  * wants it relative.
105
- */function relativeToRoot(e,t){let r=String(t||"").replace(/^\/+/,"");const n=`${e.remote}:`;return r.startsWith(n)&&(r=r.slice(n.length)),r===e.root?"":(r.startsWith(`${e.root}/`)&&(r=r.slice(e.root.length+1)),r)}function remoteSpecOf(e,t){const r=relativeToRoot(e,t);return r?remoteSpec(e,r):remoteSpec(e)}function rcloneRun(e,t,{timeout:r=RCLONE_TIMEOUT_MS}={}){try{return execFileSync(e.rclone,t,{encoding:"utf8",timeout:r,stdio:["ignore","pipe","pipe"],maxBuffer:33554432,env:e.env?{...process.env,...e.env}:process.env})}catch(e){const r=String(e&&e.stderr||"").trim().split("\n").filter((e=>!/NOTICE:/.test(e))).pop()||e&&e.message||String(e),n=new Error(`vault: rclone ${t[0]} failed — ${r}`);throw n.code="ERCLONE",n.stderr=String(e&&e.stderr||""),n}}function tempDir(){return fs.mkdtempSync(path.join(os.tmpdir(),"aegis-vault-"))}function cloudApiKey(e={}){if(e.apiKey)return String(e.apiKey).trim();const t=e.env||process.env;try{const e=require("./credentials.js");return String(e.resolveApiKey({env:t,dir:e.aegisHome(t)}).key||"").trim()}catch{return""}}async function cloudRun(e,t,r,{body:n=null,raw:o=!1,timeout:a=RCLONE_TIMEOUT_MS,fetchImpl:s=null,apiKey:i=null}={}){const c=i||"";if(!c){const e=new Error("vault: no AEGIS account key on this machine — the aegiscloud vault is the account you already have. Run `aegiscode login`, or publish to a folder you own with `--backend rclone --remote <name>`.");throw e.code="ENOKEY",e}const l=s||("function"==typeof fetch?fetch:null);if(!l){const e=new Error("vault: this Node has no global fetch — upgrade to Node 22+ to use the aegiscloud vault");throw e.code="ENOFETCH",e}const u=new AbortController,d=setTimeout((()=>u.abort()),a);let h;try{h=await l(`${e.apiBase}${CLOUD_PREFIX}${r}`,{method:t,headers:{"Content-Type":"application/json","X-API-Key":c,Authorization:`Bearer ${c}`},body:null===n?void 0:JSON.stringify(n),signal:u.signal})}catch(t){const r=new Error(`vault: could not reach ${e.apiBase} — ${t&&t.message||t}`);throw r.code="ENETWORK",r}finally{clearTimeout(d)}const E=await h.text();let p=null;try{p=E?JSON.parse(E):null}catch{p=null}if(!h.ok){if(404===h.status&&(""===r||r.startsWith("?"))){const t=new Error(`vault: ${e.apiBase} does not serve the account vault yet (${CLOUD_PREFIX} is missing on this server). Publish to a folder you own instead: \`--backend rclone --remote <name> --root <folder>\`.`);throw t.code="ENOVAULT",t.status=404,t}const n=p&&(p.error||p.message)||E.slice(0,200)||`HTTP ${h.status}`,o=new Error(`vault: ${t} ${CLOUD_PREFIX}${r} failed — ${n}`);throw o.code="ECLOUD",o.status=h.status,o}return o?E:null===p?{}:p}function cloudObject(e,t){return`/${String(t||"").split("/").filter(Boolean).map((e=>encodeURIComponent(e))).join("/")}`}function transportFor(e,t={}){if(e.backend===BACKEND_CLOUD){const r=cloudApiKey(t),n=(n,o,a)=>cloudRun(e,n,o,{...a,fetchImpl:t.fetch,apiKey:r});return{backend:BACKEND_CLOUD,async put(t,r){await n("PUT",cloudObject(e,remoteObjectName(t)),{body:{content:r}})},async putFile(e,t){await this.put(e,fs.readFileSync(t,"utf8"))},async cat(t){try{const r=await n("GET",cloudObject(e,remoteObjectName(t)));return r&&"string"==typeof r.content?r.content:null}catch(e){if(404===e.status)return null;throw e}},async list(t){const r=await n("GET",`?dir=${encodeURIComponent(relativeToRoot(e,t))}`);return Array.isArray(r&&r.files)?r.files:[]},async listRecursive(t){const r=await n("GET",`?dir=${encodeURIComponent(relativeToRoot(e,t))}&recursive=1`);return Array.isArray(r&&r.files)?r.files:[]},describe:`${e.apiBase} (account vault)`}}return{backend:BACKEND_RCLONE,async put(t,r,{name:n="object"}={}){const o=tempDir();try{const a=path.join(o,n);fs.writeFileSync(a,r),rcloneRun(e,["copyto",a,remoteSpecOf(e,t)])}finally{fs.rmSync(o,{recursive:!0,force:!0})}},async putFile(t,r){rcloneRun(e,["copyto",r,remoteSpecOf(e,t)])},async cat(t){try{return rcloneRun(e,["cat",remoteSpecOf(e,t)])}catch(e){if("ERCLONE"===e.code&&/not found|does not exist|error 404/i.test(e.stderr||e.message))return null;throw e}},list:async t=>listRaw(e,t),listRecursive:async t=>rcloneLsjsonRecursive(e,t),describe:`${e.remote}:${e.root}`}}function remoteObjectName(e){return relativeToRoot({remote:"",root:""},e).replace(/^\/+/,"")}function inspect(e,t,{secret:r=null,keyPath:n=null}={}){const o=String(e||"");for(const e of KEY_PATH_PATTERNS)if(e.test(o))return{dangerous:!0,reason:`the path looks like key material (${e})`};if(n&&path.resolve(o)===path.resolve(n))return{dangerous:!0,reason:"this path IS the authorship key"};const a=String(null==t?"":t),s=a.trim();if(r&&s.includes(String(r)))return{dangerous:!0,reason:"the content carries the authorship key verbatim"};if(PEM_PRIVATE.test(a))return{dangerous:!0,reason:"the content is a PEM private key"};const i=1===s.split("\n").length;if(i&&BARE_TOKEN.test(s)&&!BARE_HEX.test(s))return{dangerous:!0,reason:"the content is a bare high-entropy token (a raw secret)"};if(i&&BARE_HEX.test(s))return{dangerous:!0,reason:"the content is an unlabelled hex blob (a raw digest or key)"};let c=null;try{c=JSON.parse(a)}catch{c=null}if(c&&"object"==typeof c&&!Array.isArray(c)){if("string"==typeof c.kind&&c.kind.startsWith("aegiscode."))return inspectArtifact(c,r);try{fp.assertNoLeak(c,r||"")}catch(e){return{dangerous:!0,reason:e&&e.message||"failed the leak check"}}}return{dangerous:!1,reason:null}}function inspectArtifact(e,t){const r=new Set(["sha256","attestation","code"]);for(const[n,o]of Object.entries(e)){if(null==o)continue;const e=Array.isArray(o)?o.join("\0"):String(o);if(t&&e.includes(String(t)))return{dangerous:!0,reason:`the link carries the authorship key verbatim in "${n}"`};if(!r.has(n)&&fp.longHexRun(e))return{dangerous:!0,reason:`the link carries a long hex run in "${n}"`}}return void 0===e.sha256||/^[0-9a-f]{64}$/.test(String(e.sha256))?void 0===e.attestation||/^[0-9a-f]{32}$/.test(String(e.attestation))?{dangerous:!1,reason:null}:{dangerous:!0,reason:"the link's attestation is not a 32-hex tag"}:{dangerous:!0,reason:"the link's sha256 is not a 64-hex digest"}}function assertPublishable(e,t,r={}){const n=inspect(e,t,r);if(n.dangerous)throw new Error(`vault: refusing to publish ${e} — ${n.reason}. The vault carries sealed records only: a key that reaches cloud storage can mint records indistinguishable from yours, so it is never a backup. Keep it in ${authorship.defaultKeyPath(r.env||process.env)} (0600) and back it up to a local disk or a password manager.`);return!0}function baseName(e,t=null){const r=e&&e.behaviour?String(e.behaviour):"unobserved",n=String(t||e&&e.createdAt||(new Date).toISOString()).replace(/[:.]/g,"-");return`${e.keyFingerprint}-${r}.${n}`}function driveUrl(e){return e?`https://drive.google.com/open?id=${encodeURIComponent(e)}`:null}function sha256(e){return crypto.createHash("sha256").update(e,"utf8").digest("hex")}function readRecord({file:e=null,record:t=null,secret:r=null,env:n=process.env}){if(e){const t=path.resolve(e);if(!fs.existsSync(t))throw new Error(`vault: no record at ${t}`);const o=fs.readFileSync(t,"utf8");let a;assertPublishable(t,o,{secret:r,keyPath:authorship.defaultKeyPath(n),env:n});try{a=JSON.parse(o)}catch(e){throw new Error(`vault: ${t} is not JSON — ${e.message}`)}return{text:o,record:a,file:t,serialised:o}}if(t){const e=JSON.stringify(t,null,2)+"\n";return{text:e,record:t,file:null,serialised:e}}throw new Error("vault: publish needs a record file or a record")}async function publish(e={}){const t=e.env||process.env,r=e.argv||[],n=vaultTarget(t,r),o=Boolean(e.dryRun)||has(r,"--dry-run"),a=void 0===e.index?!has(r,"--no-index"):Boolean(e.index),s=e.secret||null,{text:i,record:c,file:l}=readRecord({...e,secret:s,env:t});let u;try{u=fp.id(c)}catch(e){throw new Error(`vault: not a sealed φ(α) record — ${e&&e.message||e}`)}const d=authorship.defaultKeyPath(t);assertPublishable(path.basename(l||"record.json"),i,{secret:s,keyPath:d,env:t});const h=`${baseName(c)}.json`,E=`${h}${ANCHOR_SUFFIX}`,p=`${RECORDS_DIR}/${h}`,f=`${RECORDS_DIR}/${E}`,N=sha256(i),y={v:1,kind:ANCHOR_KIND,id:u,keyFingerprint:c.keyFingerprint,behaviour:c.behaviour||null,code:c.code||null,createdAt:c.createdAt,attestation:c.attestation,sha256:N,bytes:Buffer.byteLength(i,"utf8"),backend:n.backend,remote:n.remote,root:n.root,path:n.backend===BACKEND_CLOUD?`${CLOUD_PREFIX}/${p}`:`${n.root}/${p}`,key:p,emittedAt:new Date(e.now||Date.now()).toISOString(),driveId:null,url:null,index:a?`${n.root}/${RECORDS_DIR}/${INDEX_NAME}`:null},A=transportFor(n,e);if(o)return{ok:!0,dryRun:!0,backend:n.backend,anchor:y,url:null,remotePath:y.path,commands:n.backend===BACKEND_CLOUD?[`PUT ${n.apiBase}${CLOUD_PREFIX}/${p}`,`PUT ${n.apiBase}${CLOUD_PREFIX}/${f}`]:[`rclone copyto ${l||"<record>"} ${remoteSpec(n,p)}`,`rclone copyto <anchor> ${remoteSpec(n,f)}`]};l?await A.putFile(p,l):await A.put(p,i,{name:h});const g=(await A.list(RECORDS_DIR)).find((e=>String(e.Name)===h))||null;g&&(y.driveId=g.ID||null,y.url=g.url||(n.backend===BACKEND_CLOUD?null:driveUrl(g.ID)));const O=l?`${l}${ANCHOR_SUFFIX}`:null,R=JSON.stringify(y,null,2)+"\n";await A.put(f,R,{name:E}),O&&fs.writeFileSync(O,R);let _=null;return a&&(_=await appendIndex(n,y,A)),{ok:!0,dryRun:!1,backend:n.backend,anchor:y,url:y.url,localAnchor:O,remotePath:y.path,bytes:y.bytes,sha256:N,indexLines:_}}function rcloneCat(e,t){try{return rcloneRun(e,["cat",remoteSpecOf(e,t)])}catch(e){if("ERCLONE"===e.code&&/not found|does not exist|error 404/i.test(e.stderr||e.message))return null;throw e}}function listRaw(e,t){let r;try{r=rcloneRun(e,["lsjson",remoteSpecOf(e,t),"--files-only"])}catch(e){if("ERCLONE"===e.code&&/not found|does not exist|error 404|directory not found/i.test(e.stderr||e.message))return[];throw e}const n=String(r).trim();if(!n)return[];const o=JSON.parse(n);return Array.isArray(o)?o:[]}async function appendIndex(e,t,r=transportFor(e)){const n=`${RECORDS_DIR}/${INDEX_NAME}`,o=await r.cat(n)||"",a=JSON.stringify({kind:INDEX_KIND,id:t.id,keyFingerprint:t.keyFingerprint,sha256:t.sha256,path:t.path,url:t.url,driveId:t.driveId,emittedAt:t.emittedAt});return await r.put(n,o+a+"\n",{name:INDEX_NAME}),(o.trim()?o.trim().split("\n").length:0)+1}function localAnchor(e){const t=`${path.resolve(e)}${ANCHOR_SUFFIX}`;if(!fs.existsSync(t))return null;try{return JSON.parse(fs.readFileSync(t,"utf8"))}catch{return null}}async function checkAnchor(e={}){const t=e.env||process.env,r=e.argv||[],n=e.anchor||(e.file?localAnchor(e.file):null);if(!n)return{ok:!1,reason:"not linked — no anchor beside this record (publish it first)",present:!1,unchanged:null,attested:null};const o=transportFor(vaultTarget(t,r,n),e),a=await o.cat(n.key||n.path);if(null===a)return{ok:!1,reason:`no copy at ${n.path}`,present:!1,unchanged:!1,attested:null,anchor:n};const s=sha256(a)===n.sha256;let i=null,c=null;try{const n=e.key||authorship.resolveKey({argv:r,env:t});if(n.secret){const e=fp.verify(JSON.parse(a),n.secret);i=e.ok,c=e.reason}else c="no authorship key on this machine to recompute with"}catch(e){c=e&&e.message||String(e)}return{ok:s&&!1!==i,anchor:n,present:!0,unchanged:s,attested:i,attestationReason:c,remotePath:n.path,url:n.url,reason:s?!1===i?`the published copy does not verify: ${c}`:null:"the published copy is not the bytes that were sealed (sha256 differs)"}}async function list(e={}){const t=vaultTarget(e.env||process.env,e.argv||[]),r=transportFor(t,e),n=RECORDS_DIR,o=await r.list(n),a=o.filter((e=>String(e.Name).endsWith(ANCHOR_SUFFIX))),s=o.filter((e=>!String(e.Name).endsWith(ANCHOR_SUFFIX)&&String(e.Name).endsWith(".json")&&e.Name!==INDEX_NAME)),i=[];for(const e of s){const t=a.find((t=>String(t.Name)===`${e.Name}${ANCHOR_SUFFIX}`));let o=null;if(t){const e=await r.cat(`${n}/${t.Name}`);try{o=JSON.parse(e)}catch{o={unreadable:!0}}}i.push({name:e.Name,bytes:e.Size,emittedAt:e.ModTime,id:o?o.id:null,keyFingerprint:o?o.keyFingerprint:null,sha256:o?o.sha256:null,driveId:o&&o.driveId||e.ID||null,url:o&&o.url||e.url||driveUrl(e.ID),linked:Boolean(o)})}return{ok:!0,backend:t.backend,remote:t.remote,root:t.root,where:r.describe,records:i}}async function audit(e={}){const t=e.env||process.env,r=e.argv||[],n=vaultTarget(t,r),o=transportFor(n,e),a=Number(flag(r,"--max"))||500;let s;try{s=await o.listRecursive("")}catch(e){return{ok:!1,backend:n.backend,where:o.describe,error:e&&e.message||String(e),findings:[],checked:0}}const i=e.secret||null,c=[],l=[];let u=0;for(const e of s){const t=String(e.Path||e.Name);if(u>=a){l.push({path:t,reason:`stopped after ${a} files`});continue}if(Number(e.Size)>2097152){l.push({path:t,reason:"larger than 2097152 bytes"});continue}let r;u+=1;try{r=await o.cat(t)}catch(e){l.push({path:t,reason:e&&e.message||String(e)});continue}const n=inspect(t,r,{secret:i});n.dangerous&&c.push({path:t,reason:n.reason})}return{ok:0===c.length,backend:n.backend,remote:n.remote,root:n.root,where:o.describe,checked:u,files:s.length,uninspected:l,findings:c}}function rcloneLsjsonRecursive(e,t){const r=rcloneRun(e,["lsjson",remoteSpecOf(e,t),"--files-only","--recursive"]),n=String(r).trim();if(!n)return[];const o=JSON.parse(n);return Array.isArray(o)?o:[]}module.exports={DEFAULT_REMOTE:DEFAULT_REMOTE,DEFAULT_ROOT:DEFAULT_ROOT,DEFAULT_BACKEND:DEFAULT_BACKEND,BACKEND_CLOUD:BACKEND_CLOUD,BACKEND_RCLONE:BACKEND_RCLONE,CLOUD_PREFIX:CLOUD_PREFIX,BACKEND_ENV:BACKEND_ENV,API_BASE_ENV:API_BASE_ENV,RECORDS_DIR:RECORDS_DIR,INDEX_NAME:INDEX_NAME,ANCHOR_SUFFIX:ANCHOR_SUFFIX,ANCHOR_KIND:ANCHOR_KIND,INDEX_KIND:INDEX_KIND,RCLONE_ENV:RCLONE_ENV,REMOTE_ENV:REMOTE_ENV,ROOT_ENV:ROOT_ENV,inspect:inspect,assertPublishable:assertPublishable,publish:publish,checkAnchor:checkAnchor,list:list,audit:audit,localAnchor:localAnchor,relativeToRoot:relativeToRoot,remoteSpecOf:remoteSpecOf,baseName:baseName,driveUrl:driveUrl,vaultTarget:vaultTarget,rcloneBinary:rcloneBinary,rcloneCat:rcloneCat,transportFor:transportFor,cloudApiKey:cloudApiKey,backendFor:backendFor,sha256:sha256,flag:flag,has:has};
105
+ */}function relativeToRoot(e,t){let r=String(t||"").replace(/^\/+/,"");const n=`${e.remote}:`;return r.startsWith(n)&&(r=r.slice(n.length)),r===e.root?"":(r.startsWith(`${e.root}/`)&&(r=r.slice(e.root.length+1)),r)}function remoteSpecOf(e,t){const r=relativeToRoot(e,t);return r?remoteSpec(e,r):remoteSpec(e)}function rcloneRun(e,t,{timeout:r=RCLONE_TIMEOUT_MS}={}){try{return execFileSync(e.rclone,t,{encoding:"utf8",timeout:r,stdio:["ignore","pipe","pipe"],maxBuffer:33554432,env:e.env?{...process.env,...e.env}:process.env})}catch(e){const r=String(e&&e.stderr||"").trim().split("\n").filter((e=>!/NOTICE:/.test(e))).pop()||e&&e.message||String(e),n=new Error(`vault: rclone ${t[0]} failed — ${r}`);throw n.code="ERCLONE",n.stderr=String(e&&e.stderr||""),n}}function tempDir(){return fs.mkdtempSync(path.join(os.tmpdir(),"aegis-vault-"))}function cloudApiKey(e={}){if(e.apiKey)return String(e.apiKey).trim();const t=e.env||process.env;try{const e=require("./credentials.js");return String(e.resolveApiKey({env:t,dir:e.aegisHome(t)}).key||"").trim()}catch{return""}}async function cloudRun(e,t,r,{body:n=null,raw:o=!1,timeout:a=RCLONE_TIMEOUT_MS,fetchImpl:s=null,apiKey:i=null}={}){const c=i||"";if(!c){const e=new Error("vault: no AEGIS account key on this machine — the aegiscloud vault is the account you already have. Run `aegiscode login`, or publish to a folder you own with `--backend rclone --remote <name>`.");throw e.code="ENOKEY",e}const l=s||("function"==typeof fetch?fetch:null);if(!l){const e=new Error("vault: this Node has no global fetch — upgrade to Node 22+ to use the aegiscloud vault");throw e.code="ENOFETCH",e}const u=new AbortController,d=setTimeout((()=>u.abort()),a);let h;try{h=await l(`${e.apiBase}${CLOUD_PREFIX}${r}`,{method:t,headers:{"Content-Type":"application/json","X-API-Key":c,Authorization:`Bearer ${c}`},body:null===n?void 0:JSON.stringify(n),signal:u.signal})}catch(t){const r=new Error(`vault: could not reach ${e.apiBase} — ${t&&t.message||t}`);throw r.code="ENETWORK",r}finally{clearTimeout(d)}const E=await h.text();let p=null;try{p=E?JSON.parse(E):null}catch{p=null}if(!h.ok){if(404===h.status&&(""===r||r.startsWith("?"))){const t=new Error(`vault: ${e.apiBase} does not serve the account vault yet (${CLOUD_PREFIX} is missing on this server). Publish to a folder you own instead: \`--backend rclone --remote <name> --root <folder>\`.`);throw t.code="ENOVAULT",t.status=404,t}const n=p&&(p.error||p.message)||E.slice(0,200)||`HTTP ${h.status}`,o=new Error(`vault: ${t} ${CLOUD_PREFIX}${r} failed — ${n}`);throw o.code="ECLOUD",o.status=h.status,o}return o?E:null===p?{}:p}function cloudObject(e,t){return`/${String(t||"").split("/").filter(Boolean).map((e=>encodeURIComponent(e))).join("/")}`}function transportFor(e,t={}){if(e.backend===BACKEND_CLOUD){const r=cloudApiKey(t),n=(n,o,a)=>cloudRun(e,n,o,{...a,fetchImpl:t.fetch,apiKey:r});return{backend:BACKEND_CLOUD,async put(t,r){await n("PUT",cloudObject(e,remoteObjectName(t)),{body:{content:r}})},async putFile(e,t){await this.put(e,fs.readFileSync(t,"utf8"))},async cat(t){try{const r=await n("GET",cloudObject(e,remoteObjectName(t)));return r&&"string"==typeof r.content?r.content:null}catch(e){if(404===e.status)return null;throw e}},async list(t){const r=await n("GET",`?dir=${encodeURIComponent(relativeToRoot(e,t))}`);return Array.isArray(r&&r.files)?r.files:[]},async listRecursive(t){const r=await n("GET",`?dir=${encodeURIComponent(relativeToRoot(e,t))}&recursive=1`);return Array.isArray(r&&r.files)?r.files:[]},describe:`${e.apiBase} (account vault)`}}return{backend:BACKEND_RCLONE,async put(t,r,{name:n="object"}={}){const o=tempDir();try{const a=path.join(o,n);fs.writeFileSync(a,r),rcloneRun(e,["copyto",a,remoteSpecOf(e,t)])}finally{fs.rmSync(o,{recursive:!0,force:!0})}},async putFile(t,r){rcloneRun(e,["copyto",r,remoteSpecOf(e,t)])},async cat(t){try{return rcloneRun(e,["cat",remoteSpecOf(e,t)])}catch(e){if("ERCLONE"===e.code&&/not found|does not exist|error 404/i.test(e.stderr||e.message))return null;throw e}},list:async t=>listRaw(e,t),listRecursive:async t=>rcloneLsjsonRecursive(e,t),describe:`${e.remote}:${e.root}`}}function remoteObjectName(e){return relativeToRoot({remote:"",root:""},e).replace(/^\/+/,"")}function inspect(e,t,{secret:r=null,keyPath:n=null}={}){const o=String(e||"");for(const e of KEY_PATH_PATTERNS)if(e.test(o))return{dangerous:!0,reason:`the path looks like key material (${e})`};if(n&&path.resolve(o)===path.resolve(n))return{dangerous:!0,reason:"this path IS the authorship key"};const a=String(null==t?"":t),s=a.trim();if(r&&s.includes(String(r)))return{dangerous:!0,reason:"the content carries the authorship key verbatim"};if(PEM_PRIVATE.test(a))return{dangerous:!0,reason:"the content is a PEM private key"};const i=1===s.split("\n").length;if(i&&BARE_TOKEN.test(s)&&!BARE_HEX.test(s))return{dangerous:!0,reason:"the content is a bare high-entropy token (a raw secret)"};if(i&&BARE_HEX.test(s))return{dangerous:!0,reason:"the content is an unlabelled hex blob (a raw digest or key)"};let c=null;try{c=JSON.parse(a)}catch{c=null}if(c&&"object"==typeof c&&!Array.isArray(c)){if("string"==typeof c.kind&&c.kind.startsWith("aegiscode."))return inspectArtifact(c,r);try{fp.assertNoLeak(c,r||"")}catch(e){return{dangerous:!0,reason:e&&e.message||"failed the leak check"}}}return{dangerous:!1,reason:null}}function inspectArtifact(e,t){const r=new Set(["sha256","attestation","code"]);for(const[n,o]of Object.entries(e)){if(null==o)continue;const e=Array.isArray(o)?o.join("\0"):String(o);if(t&&e.includes(String(t)))return{dangerous:!0,reason:`the link carries the authorship key verbatim in "${n}"`};if(!r.has(n)&&fp.longHexRun(e))return{dangerous:!0,reason:`the link carries a long hex run in "${n}"`}}return void 0===e.sha256||/^[0-9a-f]{64}$/.test(String(e.sha256))?void 0===e.attestation||/^[0-9a-f]{32}$/.test(String(e.attestation))?{dangerous:!1,reason:null}:{dangerous:!0,reason:"the link's attestation is not a 32-hex tag"}:{dangerous:!0,reason:"the link's sha256 is not a 64-hex digest"}}function assertPublishable(e,t,r={}){const n=inspect(e,t,r);if(n.dangerous)throw new Error(`vault: refusing to publish ${e} — ${n.reason}. The vault carries sealed records only: a key that reaches cloud storage can mint records indistinguishable from yours, so it is never a backup. Keep it in ${authorship.defaultKeyPath(r.env||process.env)} (0600) and back it up to a local disk or a password manager.`);return!0}function baseName(e,t=null){const r=e&&e.behaviour?String(e.behaviour):"unobserved",n=String(t||e&&e.createdAt||(new Date).toISOString()).replace(/[:.]/g,"-");return`${e.keyFingerprint}-${r}.${n}`}function driveUrl(e){return e?`https://drive.google.com/open?id=${encodeURIComponent(e)}`:null}function sha256(e){return crypto.createHash("sha256").update(e,"utf8").digest("hex")}function readRecord({file:e=null,record:t=null,secret:r=null,env:n=process.env}){if(e){const t=path.resolve(e);if(!fs.existsSync(t))throw new Error(`vault: no record at ${t}`);const o=fs.readFileSync(t,"utf8");let a;assertPublishable(t,o,{secret:r,keyPath:authorship.defaultKeyPath(n),env:n});try{a=JSON.parse(o)}catch(e){throw new Error(`vault: ${t} is not JSON — ${e.message}`)}return{text:o,record:a,file:t,serialised:o}}if(t){const e=JSON.stringify(t,null,2)+"\n";return{text:e,record:t,file:null,serialised:e}}throw new Error("vault: publish needs a record file or a record")}async function publish(e={}){const t=e.env||process.env,r=e.argv||[],n=vaultTarget(t,r),o=Boolean(e.dryRun)||has(r,"--dry-run"),a=void 0===e.index?!has(r,"--no-index"):Boolean(e.index),s=e.secret||null,{text:i,record:c,file:l}=readRecord({...e,secret:s,env:t});let u;try{u=fp.id(c)}catch(e){throw new Error(`vault: not a sealed φ(α) record — ${e&&e.message||e}`)}const d=authorship.defaultKeyPath(t);assertPublishable(path.basename(l||"record.json"),i,{secret:s,keyPath:d,env:t});const h=`${baseName(c)}.json`,E=`${h}${ANCHOR_SUFFIX}`,p=`${RECORDS_DIR}/${h}`,f=`${RECORDS_DIR}/${E}`,N=sha256(i),y={v:1,kind:ANCHOR_KIND,id:u,keyFingerprint:c.keyFingerprint,behaviour:c.behaviour||null,code:c.code||null,createdAt:c.createdAt,attestation:c.attestation,sha256:N,bytes:Buffer.byteLength(i,"utf8"),backend:n.backend,remote:n.remote,root:n.root,path:n.backend===BACKEND_CLOUD?`${CLOUD_PREFIX}/${p}`:`${n.root}/${p}`,key:p,emittedAt:new Date(e.now||Date.now()).toISOString(),driveId:null,url:null,index:a?`${n.root}/${RECORDS_DIR}/${INDEX_NAME}`:null},A=transportFor(n,e);if(o)return{ok:!0,dryRun:!0,backend:n.backend,anchor:y,url:null,remotePath:y.path,commands:n.backend===BACKEND_CLOUD?[`PUT ${n.apiBase}${CLOUD_PREFIX}/${p}`,`PUT ${n.apiBase}${CLOUD_PREFIX}/${f}`]:[`rclone copyto ${l||"<record>"} ${remoteSpec(n,p)}`,`rclone copyto <anchor> ${remoteSpec(n,f)}`]};l?await A.putFile(p,l):await A.put(p,i,{name:h});const g=(await A.list(RECORDS_DIR)).find((e=>String(e.Name)===h))||null;g&&(y.driveId=g.ID||null,y.url=g.url||(n.backend===BACKEND_CLOUD?null:driveUrl(g.ID)));const O=l?`${l}${ANCHOR_SUFFIX}`:null,R=JSON.stringify(y,null,2)+"\n";await A.put(f,R,{name:E}),O&&fs.writeFileSync(O,R);let _=null;return a&&(_=await appendIndex(n,y,A)),{ok:!0,dryRun:!1,backend:n.backend,anchor:y,url:y.url,localAnchor:O,remotePath:y.path,bytes:y.bytes,sha256:N,indexLines:_}}function rcloneCat(e,t){try{return rcloneRun(e,["cat",remoteSpecOf(e,t)])}catch(e){if("ERCLONE"===e.code&&/not found|does not exist|error 404/i.test(e.stderr||e.message))return null;throw e}}function listRaw(e,t){let r;try{r=rcloneRun(e,["lsjson",remoteSpecOf(e,t),"--files-only"])}catch(e){if("ERCLONE"===e.code&&/not found|does not exist|error 404|directory not found/i.test(e.stderr||e.message))return[];throw e}const n=String(r).trim();if(!n)return[];const o=JSON.parse(n);return Array.isArray(o)?o:[]}async function appendIndex(e,t,r=transportFor(e)){const n=`${RECORDS_DIR}/${INDEX_NAME}`,o=await r.cat(n)||"",a=JSON.stringify({kind:INDEX_KIND,id:t.id,keyFingerprint:t.keyFingerprint,sha256:t.sha256,path:t.path,url:t.url,driveId:t.driveId,emittedAt:t.emittedAt});return await r.put(n,o+a+"\n",{name:INDEX_NAME}),(o.trim()?o.trim().split("\n").length:0)+1}function localAnchor(e){const t=`${path.resolve(e)}${ANCHOR_SUFFIX}`;if(!fs.existsSync(t))return null;try{return JSON.parse(fs.readFileSync(t,"utf8"))}catch{return null}}async function checkAnchor(e={}){const t=e.env||process.env,r=e.argv||[],n=e.anchor||(e.file?localAnchor(e.file):null);if(!n)return{ok:!1,reason:"not linked — no anchor beside this record (publish it first)",present:!1,unchanged:null,attested:null};const o=transportFor(vaultTarget(t,r,n),e),a=await o.cat(n.key||n.path);if(null===a)return{ok:!1,reason:`no copy at ${n.path}`,present:!1,unchanged:!1,attested:null,anchor:n};const s=sha256(a)===n.sha256;let i=null,c=null;try{const n=e.key||authorship.resolveKey({argv:r,env:t});if(n.secret){const e=fp.verify(JSON.parse(a),n.secret);i=e.ok,c=e.reason}else c="no authorship key on this machine to recompute with"}catch(e){c=e&&e.message||String(e)}return{ok:s&&!1!==i,anchor:n,present:!0,unchanged:s,attested:i,attestationReason:c,remotePath:n.path,url:n.url,reason:s?!1===i?`the published copy does not verify: ${c}`:null:"the published copy is not the bytes that were sealed (sha256 differs)"}}async function list(e={}){const t=vaultTarget(e.env||process.env,e.argv||[]),r=transportFor(t,e),n=RECORDS_DIR,o=await r.list(n),a=o.filter((e=>String(e.Name).endsWith(ANCHOR_SUFFIX))),s=o.filter((e=>!String(e.Name).endsWith(ANCHOR_SUFFIX)&&String(e.Name).endsWith(".json")&&e.Name!==INDEX_NAME)),i=[];for(const e of s){const t=a.find((t=>String(t.Name)===`${e.Name}${ANCHOR_SUFFIX}`));let o=null;if(t){const e=await r.cat(`${n}/${t.Name}`);try{o=JSON.parse(e)}catch{o={unreadable:!0}}}i.push({name:e.Name,bytes:e.Size,emittedAt:e.ModTime,id:o?o.id:null,keyFingerprint:o?o.keyFingerprint:null,sha256:o?o.sha256:null,driveId:o&&o.driveId||e.ID||null,url:o&&o.url||e.url||driveUrl(e.ID),linked:Boolean(o)})}return{ok:!0,backend:t.backend,remote:t.remote,root:t.root,where:r.describe,records:i}}async function audit(e={}){const t=e.env||process.env,r=e.argv||[],n=vaultTarget(t,r),o=transportFor(n,e),a=Number(flag(r,"--max"))||500;let s;try{s=await o.listRecursive("")}catch(e){return{ok:!1,backend:n.backend,where:o.describe,error:e&&e.message||String(e),findings:[],checked:0}}const i=e.secret||null,c=[],l=[];let u=0;for(const t of s){const r=String(t.Path||t.Name);if(u>=a){l.push({path:r,reason:`stopped after ${a} files`});continue}if(Number(t.Size)>2097152){l.push({path:r,reason:"larger than 2097152 bytes"});continue}let n;u+=1;try{n=await o.cat(r)}catch(e){l.push({path:r,reason:e&&e.message||String(e)});continue}const s=inspect(r,n,{secret:i});s.dangerous&&c.push({path:r,reason:s.reason})}return{ok:0===c.length,backend:n.backend,remote:n.remote,root:n.root,where:o.describe,checked:u,files:s.length,uninspected:l,findings:c}}function rcloneLsjsonRecursive(e,t){const r=rcloneRun(e,["lsjson",remoteSpecOf(e,t),"--files-only","--recursive"]),n=String(r).trim();if(!n)return[];const o=JSON.parse(n);return Array.isArray(o)?o:[]}module.exports={DEFAULT_REMOTE:DEFAULT_REMOTE,DEFAULT_ROOT:DEFAULT_ROOT,DEFAULT_BACKEND:DEFAULT_BACKEND,BACKEND_CLOUD:BACKEND_CLOUD,BACKEND_RCLONE:BACKEND_RCLONE,CLOUD_PREFIX:CLOUD_PREFIX,BACKEND_ENV:BACKEND_ENV,API_BASE_ENV:API_BASE_ENV,RECORDS_DIR:RECORDS_DIR,INDEX_NAME:INDEX_NAME,ANCHOR_SUFFIX:ANCHOR_SUFFIX,ANCHOR_KIND:ANCHOR_KIND,INDEX_KIND:INDEX_KIND,RCLONE_ENV:RCLONE_ENV,REMOTE_ENV:REMOTE_ENV,ROOT_ENV:ROOT_ENV,inspect:inspect,assertPublishable:assertPublishable,publish:publish,checkAnchor:checkAnchor,list:list,audit:audit,localAnchor:localAnchor,relativeToRoot:relativeToRoot,remoteSpecOf:remoteSpecOf,baseName:baseName,driveUrl:driveUrl,vaultTarget:vaultTarget,rcloneBinary:rcloneBinary,rcloneCat:rcloneCat,transportFor:transportFor,cloudApiKey:cloudApiKey,backendFor:backendFor,sha256:sha256,flag:flag,has:has};
@@ -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"),USER_MODELS_FILE="models.json",FILE_MODE=384,MAX_MODELS_PER_PROVIDER=32,MAX_PROVIDERS=64,PROVIDER_RE=/^[a-z0-9][a-z0-9._-]{0,63}$/,MODEL_RE=/^[A-Za-z0-9][A-Za-z0-9._/-]{0,95}$/;function userModelsDir(e){return e&&e.dir||credentials.aegisHome(e&&e.env)}function userModelsPath(e){return path.join(userModelsDir(e),USER_MODELS_FILE)}function badValue(e,r,o){return new Error(`aegiscode: ${e} ${JSON.stringify(String(r))} is not usable — ${o}`)}function sanitizeProvider(e){const r=String(null==e?"":e).trim().toLowerCase();if(!r)throw badValue("provider",e,"the provider id is empty");if(!PROVIDER_RE.test(r))throw badValue("provider",e,"a provider id is lowercase letters, digits, dot, dash or underscore (the id `/byok` prints)");return r}function sanitizeModel(e){const r=String(null==e?"":e).trim();if(!r)throw badValue("model id",e,"the model id is empty");if(/:/.test(r))throw badValue("model id",e,"'provider:model' is how a picked model is addressed, so a model id cannot contain a colon");if(!MODEL_RE.test(r))throw badValue("model id",e,"a model id has no spaces — it is the string sent to the vendor (e.g. deepseek-v4.2-preview, claude-opus-9-1)");return r}function isPlainObject(e){return Boolean(e)&&"object"==typeof e&&!Array.isArray(e)}function load(e){const r=userModelsPath(e),o=[];let s;try{s=JSON.parse(fs.readFileSync(r,"utf8"))}catch(s){return s&&"ENOENT"===s.code||o.push({provider:null,model:null,reason:`unreadable: ${s&&s.message||s}`}),{dir:userModelsDir(e),file:r,map:{},invalid:o}}const i={};if(!isPlainObject(s))return o.push({provider:null,model:null,reason:"the file must be an object of provider → [model ids]"}),{dir:userModelsDir(e),file:r,map:i,invalid:o};for(const[e,r]of Object.entries(s)){if("version"===e||"$schema"===e)continue;let s;try{s=sanitizeProvider(e)}catch(r){o.push({provider:e,model:null,reason:r.message});continue}const t=Array.isArray(r)?r:[r],d=new Set,n=[];for(const e of t){let r;try{r=sanitizeModel(e)}catch(r){o.push({provider:s,model:e,reason:r.message});continue}d.has(r)||(d.add(r),n.push(r))}n.length&&(i[s]=n)}return{dir:userModelsDir(e),file:r,map:i,invalid:o}}function readUserModels(e){return load(e).map}function userModelIdsFor(e,r){let o;try{o=sanitizeProvider(e)}catch{return[]}const s=readUserModels(r);return Array.isArray(s[o])?s[o].slice():[]}function writeMap(e,r){const o=userModelsPath(r);fs.mkdirSync(path.dirname(o),{recursive:!0});const s=`${o}.tmp-${process.pid}`;fs.writeFileSync(s,JSON.stringify(e,null,2)+"\n",{mode:FILE_MODE}),fs.renameSync(s,o);try{fs.chmodSync(o,FILE_MODE)}catch{}return e}function addUserModel(e,r,o){const s=sanitizeProvider(e),i=sanitizeModel(r),t=readUserModels(o),d=Array.isArray(t[s])?t[s].slice():[];if(d.includes(i))return{file:userModelsPath(o),provider:s,model:i,added:!1,models:d};if(d.length>=32)throw new Error(`aegiscode: ${s} already carries ${d.length} user models (the cap) — remove one with /model-rm before adding another.`);if(!t[s]&&Object.keys(t).length>=64)throw new Error(`aegiscode: ${Object.keys(t).length} providers already carry user models (the cap).`);const n=[...d,i];return writeMap({...t,[s]:n},o),{file:userModelsPath(o),provider:s,model:i,added:!0,models:n}}function removeUserModel(e,r,o){const s=sanitizeProvider(e),i=sanitizeModel(r),t=readUserModels(o),d=Array.isArray(t[s])?t[s].slice():[];if(!d.includes(i))return{file:userModelsPath(o),provider:s,model:i,removed:!1,models:d};const n=d.filter((e=>e!==i)),a={...t};return n.length?a[s]=n:delete a[s],writeMap(a,o),{file:userModelsPath(o),provider:s,model:i,removed:!0,models:n}}function modelIdsOf(e){return(Array.isArray(e&&e.models)?e.models:[]).map((e=>"string"==typeof e?e:e&&e.id)).map((e=>"string"==typeof e?e.trim():"")).filter(Boolean)}function providerArray(e){return Array.isArray(e)?e:Array.isArray(e&&e.providers)?e.providers:null}function withUserModels(e,r){const o=providerArray(e);if(!o)return[];const s=void 0===r?readUserModels():isPlainObject(r)?r:{},i=[];for(const e of o){if(!e||"object"!=typeof e)continue;const r="string"==typeof e.id?e.id.trim():"",o=r&&Array.isArray(s[r])?s[r]:null;if(!o||!o.length){i.push(e);continue}const t=new Set(modelIdsOf(e)),d=o.map((e=>String(e).trim())).filter((e=>e&&!t.has(e)));if(!d.length){i.push(e);continue}const n=Array.isArray(e.models)?e.models:[];i.push({...e,models:[...n,...d]})}return i}function unmatchedUserProviders(e,r){const o=providerArray(e)||[],s=void 0===r?readUserModels():isPlainObject(r)?r:{},i=new Set(o.map((e=>e&&"string"==typeof e.id?e.id.trim():"")).filter(Boolean));return Object.keys(s).filter((e=>!i.has(e)))}module.exports={USER_MODELS_FILE:USER_MODELS_FILE,MAX_MODELS_PER_PROVIDER:32,userModelsDir:userModelsDir,userModelsPath:userModelsPath,sanitizeProvider:sanitizeProvider,sanitizeModel:sanitizeModel,load:load,readUserModels:readUserModels,userModelIdsFor:userModelIdsFor,addUserModel:addUserModel,removeUserModel:removeUserModel,withUserModels:withUserModels,unmatchedUserProviders:unmatchedUserProviders};
3
+ "use strict";const fs=require("node:fs"),path=require("node:path"),credentials=require("./credentials.js"),USER_MODELS_FILE="models.json",FILE_MODE=384,MAX_MODELS_PER_PROVIDER=32,MAX_PROVIDERS=64,PROVIDER_RE=/^[a-z0-9][a-z0-9._-]{0,63}$/,MODEL_RE=/^[A-Za-z0-9][A-Za-z0-9._/-]{0,95}$/;function userModelsDir(e){return e&&e.dir||credentials.aegisHome(e&&e.env)}function userModelsPath(e){return path.join(userModelsDir(e),USER_MODELS_FILE)}function badValue(e,r,o){return new Error(`aegiscode: ${e} ${JSON.stringify(String(r))} is not usable — ${o}`)}function sanitizeProvider(e){const r=String(null==e?"":e).trim().toLowerCase();if(!r)throw badValue("provider",e,"the provider id is empty");if(!PROVIDER_RE.test(r))throw badValue("provider",e,"a provider id is lowercase letters, digits, dot, dash or underscore (the id `/byok` prints)");return r}function sanitizeModel(e){const r=String(null==e?"":e).trim();if(!r)throw badValue("model id",e,"the model id is empty");if(/:/.test(r))throw badValue("model id",e,"'provider:model' is how a picked model is addressed, so a model id cannot contain a colon");if(!MODEL_RE.test(r))throw badValue("model id",e,"a model id has no spaces — it is the string sent to the vendor (e.g. deepseek-v4.2-preview, claude-opus-9-1)");return r}function isPlainObject(e){return Boolean(e)&&"object"==typeof e&&!Array.isArray(e)}function load(e){const r=userModelsPath(e),o=[];let s;try{s=JSON.parse(fs.readFileSync(r,"utf8"))}catch(s){return s&&"ENOENT"===s.code||o.push({provider:null,model:null,reason:`unreadable: ${s&&s.message||s}`}),{dir:userModelsDir(e),file:r,map:{},invalid:o}}const i={};if(!isPlainObject(s))return o.push({provider:null,model:null,reason:"the file must be an object of provider → [model ids]"}),{dir:userModelsDir(e),file:r,map:i,invalid:o};for(const[e,t]of Object.entries(s)){if("version"===e||"$schema"===e)continue;let s;try{s=sanitizeProvider(e)}catch(r){o.push({provider:e,model:null,reason:r.message});continue}const d=Array.isArray(t)?t:[t],n=new Set,a=[];for(const e of d){let i;try{i=sanitizeModel(e)}catch(r){o.push({provider:s,model:e,reason:r.message});continue}n.has(i)||(n.add(i),a.push(i))}a.length&&(i[s]=a)}return{dir:userModelsDir(e),file:r,map:i,invalid:o}}function readUserModels(e){return load(e).map}function userModelIdsFor(e,r){let o;try{o=sanitizeProvider(e)}catch{return[]}const s=readUserModels(r);return Array.isArray(s[o])?s[o].slice():[]}function writeMap(e,r){const o=userModelsPath(r);fs.mkdirSync(path.dirname(o),{recursive:!0});const s=`${o}.tmp-${process.pid}`;fs.writeFileSync(s,JSON.stringify(e,null,2)+"\n",{mode:FILE_MODE}),fs.renameSync(s,o);try{fs.chmodSync(o,FILE_MODE)}catch{}return e}function addUserModel(e,r,o){const s=sanitizeProvider(e),i=sanitizeModel(r),t=readUserModels(o),d=Array.isArray(t[s])?t[s].slice():[];if(d.includes(i))return{file:userModelsPath(o),provider:s,model:i,added:!1,models:d};if(d.length>=32)throw new Error(`aegiscode: ${s} already carries ${d.length} user models (the cap) — remove one with /model-rm before adding another.`);if(!t[s]&&Object.keys(t).length>=64)throw new Error(`aegiscode: ${Object.keys(t).length} providers already carry user models (the cap).`);const n=[...d,i];return writeMap({...t,[s]:n},o),{file:userModelsPath(o),provider:s,model:i,added:!0,models:n}}function removeUserModel(e,r,o){const s=sanitizeProvider(e),i=sanitizeModel(r),t=readUserModels(o),d=Array.isArray(t[s])?t[s].slice():[];if(!d.includes(i))return{file:userModelsPath(o),provider:s,model:i,removed:!1,models:d};const n=d.filter((e=>e!==i)),a={...t};return n.length?a[s]=n:delete a[s],writeMap(a,o),{file:userModelsPath(o),provider:s,model:i,removed:!0,models:n}}function modelIdsOf(e){return(Array.isArray(e&&e.models)?e.models:[]).map((e=>"string"==typeof e?e:e&&e.id)).map((e=>"string"==typeof e?e.trim():"")).filter(Boolean)}function providerArray(e){return Array.isArray(e)?e:Array.isArray(e&&e.providers)?e.providers:null}function withUserModels(e,r){const o=providerArray(e);if(!o)return[];const s=void 0===r?readUserModels():isPlainObject(r)?r:{},i=[];for(const e of o){if(!e||"object"!=typeof e)continue;const r="string"==typeof e.id?e.id.trim():"",o=r&&Array.isArray(s[r])?s[r]:null;if(!o||!o.length){i.push(e);continue}const t=new Set(modelIdsOf(e)),d=o.map((e=>String(e).trim())).filter((e=>e&&!t.has(e)));if(!d.length){i.push(e);continue}const n=Array.isArray(e.models)?e.models:[];i.push({...e,models:[...n,...d]})}return i}function unmatchedUserProviders(e,r){const o=providerArray(e)||[],s=void 0===r?readUserModels():isPlainObject(r)?r:{},i=new Set(o.map((e=>e&&"string"==typeof e.id?e.id.trim():"")).filter(Boolean));return Object.keys(s).filter((e=>!i.has(e)))}module.exports={USER_MODELS_FILE:USER_MODELS_FILE,MAX_MODELS_PER_PROVIDER:32,userModelsDir:userModelsDir,userModelsPath:userModelsPath,sanitizeProvider:sanitizeProvider,sanitizeModel:sanitizeModel,load:load,readUserModels:readUserModels,userModelIdsFor:userModelIdsFor,addUserModel:addUserModel,removeUserModel:removeUserModel,withUserModels:withUserModels,unmatchedUserProviders:unmatchedUserProviders};
@@ -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
- 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(" ")}`:""}`})}))}))}};
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 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 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
- 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};
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:$,gitScope:C}){const I=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:n,model:r}=M(t.model),s=P(n,r),a=L(n,s,t.effort);try{return await o.byokChatCompletion({provider:n,model:s,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:a&&"effort"===a.field?a.level:void 0,reasoningEffort:a&&"reasoning_effort"===a.field?a.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 o=t.cfg&&t.cfg.baseURL||A.DEFAULT_BASE,n=e=>A.chat({baseURL:o,model:t.model,prompt:t.prompt,system:t.system,messages:t.messages,maxTokens:t.maxTokens,signal:t.signal,onDelta:t.onDelta,...e&&t.tools.length?{tools:t.tools,toolChoice:t.toolChoice}:{}});try{return await n(!0)}catch(e){if(t.tools.length&&e&&400===e.status)return n(!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=C;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;I.set(g,b);const x=b.signal,S=!(t&&!1===t.tools),_=S?N.toolsFor({includeSubagent:y<4}):[],$=t&&t.toolChoice||null,C=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 F=R.length?n.buildContent(U,R):U,K=null;const B=be(t),G=B.cwd,z={getShell:()=>K||(K=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,I="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&&!I){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:I,toolChoice:$,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,K=!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}`,F=R.length?n.buildContent(U,R):U):(L.push({role:"user",content:e}),F=""),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(""===F)return;const e=L[L.length-1],o=e&&"user"===e.role?r(e.content):null;e&&"user"===e.role&&o===r(F)||L.push({role:"user",content:F}),U="",F=""};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:C,messages:L,prompt:F,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)||K||!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)}K=!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{K&&K.dispose(),I.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=I.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:$});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};
@@ -1,6 +1,4 @@
1
1
  #!/usr/bin/env node
2
2
  // SPDX-License-Identifier: AGPL-3.0-or-later
3
3
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
4
- const e=require("node:path"),t=require("node:fs"),{execFile:n}=require("node:child_process"),{pathToFileURL:r}=require("node:url");let o;try{o=require("../client/aegis.js")}catch{o=require("./vendor/aegis.js")}const{createClient:s}=o;let i,a,u,l,c,d,p,f;try{i=require("../client/credentials.js")}catch{i=require("./vendor/credentials.js")}try{a=require("../client/auto-provision.js")}catch{a=require("./vendor/auto-provision.js")}try{u=require("../client/presence.js")}catch{u=require("./vendor/presence.js")}try{l=require("../client/topup.js")}catch{l=require("./vendor/topup.js")}try{c=require("../client/google-signin.js")}catch{c=require("./vendor/google-signin.js")}try{d=require("../client/drive-connect.js")}catch{d=require("./vendor/drive-connect.js")}try{p=require("../client/drive-upload.js")}catch{p=require("./vendor/drive-upload.js")}try{f=require("../client/conversation-export.js")}catch{try{f=require("./vendor/conversation-export.js")}catch{f=null}}const{createGoogleConnect:m}=require("./lib/google-connect.js");let g;try{g=require("../client/device-fingerprint.js")}catch{g=require("./vendor/device-fingerprint.js")}const{createFingerprintService:h}=require("./lib/fingerprint.js"),{createAutoDrain:y,createAutoMint:k}=require("./lib/auto.js");let b=null;try{b=require("../client/env-file.js")}catch{try{b=require("./vendor/env-file.js")}catch{}}let v=null;try{v=require("electron")}catch{}const w=require("node:os"),{createLocalEngine:S}=require("./lib/local/engine.js"),{createAccountKey:A,startupKeyOverride:E}=require("./lib/account-key.js"),{createSettingsStore:M,isReservedNamespace:q}=require("./lib/settings.js"),_=require("./lib/sync/sessions.js"),C=require("./lib/sync/memory-queue.js"),D=require("./lib/sync/persist-gate.js"),j=require("./lib/avatar/store.js"),I=require("./lib/window-state.js"),$=require("./lib/deep-link.js"),P=require("./lib/quick-launcher.js");let R;try{R=require("../client/foreign-memory.js")}catch{R=require("./vendor/foreign-memory.js")}require("./lib/local/tools.js");const T=require("./lib/local/queue.js"),B=require("./lib/local/autonomous.js"),{autoContinuePlan:L,autoContinueLimit:N,autoRoundsDefault:x}=require("./lib/local/autonomous.js"),U=require("./lib/local/entitlement.js"),O=require("./lib/local/telemetry.js"),F=require("./lib/local/covenant.js"),{createTelemetry:K,telemetryEnabled:V}=O,z="aegis:",W="model:",H="sync:",G="quick:",Q="queue:",X="auto:",Y=Object.freeze(["aegis","byok","local"]),J=`${z}chatDelta`,Z=`${z}menuNewChat`,ee=`${z}menuSearch`,te=`${z}menuExportMarkdown`,ne=`${z}menuExportJson`,re=`${z}menuFingerprint`,oe=`${z}menuGoogleDrive`,se=`${z}deepLink`,ie=`${z}quickLauncherPush`,ae=`${Q}progress`,ue=8e3,le=200,ce=8,de=new Set(["low","medium","high","max"]);function pe(e,t){return{...e&&"object"==typeof e?e:{delta:e},id:t}}const fe=require("./package.json").version;function me(e){return e?e.length<=10?"configured":`${e.slice(0,9)}…${e.slice(-4)}`:null}function ge(e){const t=e&&e.status,n=e&&e.data||{},r="string"==typeof n.error?n.error:"";if(402!==t&&"free_session_limit_reached"!==r)return null;const o=null!=n.tokensUsed?n.tokensUsed:null!=n.sessionsUsed?n.sessionsUsed:null,s=null!=n.tokenLimit?n.tokenLimit:null!=n.freeSessionLimit?n.freeSessionLimit:null;return{url:n.upgradeUrl||"https://aegiscloud.org/go/upgrade?s=desktop&c=status_card",used:o,limit:s,code:r||"free_session_limit_reached"}}function he(e){return e&&e.message?e.message:String(e)}function ye(e){return!(!e||"object"!=typeof e||!0!==e.aegisCancelled&&"AbortError"!==e.name&&"ABORT_ERR"!==e.code)}function ke(e){return{aborted:!0,status:0,code:"ABORT_ERR",message:he(e),choices:[{message:{content:""}}]}}function be(e){const t=e&&(e.status||e.response&&e.response.status)||0,n=he(e);return ge(e)?{kind:"quota",status:t||402,message:n,hint:"the plan's synced-token ceiling is reached — free space in the account dashboard or upgrade to keep syncing"}:401===t?{kind:"auth",status:t,message:n,hint:"the memory token was refused — re-enter your AEGIS API key to exchange a new one"}:{kind:"error",status:t||null,message:n,hint:null}}function ve(e){return e?e.hint?`${e.message} — ${e.hint}`:e.message:"sync failed"}const{bankAmount:we,parseTopupAmount:Se,startTopup:Ae,createCreditWatch:Ee,TOPUP_POLL_MS:Me,TOPUP_POLL_TRIES:qe}=l;let _e=null;function Ce(e,t){const n=t||{},r=n.intervalMs||Me,o=n.log;_e&&clearInterval(_e);const s=Ee(e,n.maxTries?{maxTries:n.maxTries}:void 0),i=()=>{_e&&clearInterval(_e),_e=null,s.stop()},a=async()=>{const e=await s.tick();"credited"===e.state?(i(),(e=>{if("function"!=typeof n.notify)try{const t=v&&v.Notification;t&&t.isSupported()&&new t({title:"AEGIS Desktop",body:`Bank credited — €${e.toFixed(2)} available`}).show()}catch{}else n.notify(e)})(e.amount)):"expired"===e.state&&(i(),o&&o("top-up: no credit observed within the watch window; stopping"))};return _e=setInterval(a,r),_e&&"function"==typeof _e.unref&&_e.unref(),{stop:i,tick:a,get baseline(){return s.baseline}}}async function De(e){try{const t=await e,n=function(e){if(!e||"object"!=typeof e)return null;const t=null!=e.tokensUsed?e.tokensUsed:null,n=null!=e.tokenLimit?e.tokenLimit:null;return null==t||null==n||n<=0||t<n?null:{url:"https://aegiscloud.org/go/upgrade?s=desktop&c=memory_quota",used:t,limit:n,code:"sync_quota_reached"}}(t);return n?Object.assign({},t,{upgrade:n}):t}catch(e){const t=ge(e);if(!t)throw e;return{entries:[],upgrade:t}}}async function je(e,t,n,r){const o=n||{},s=R.scan({sources:o.sources,limit:o.limit||1e3}),i=R.describe(s),a=s.sources.map((e=>({id:e.id,label:e.label,verified:e.verified,present:e.present,count:e.count,skipped:e.skipped,files:e.files}))),u={summary:i,totals:s.totals,sources:a};if(!o.confirm||!s.entries.length)return{...u,ok:!0,dryRun:!o.confirm,saved:0,queued:0};let l=0,c=0;const d=[];let p=null;for(const n of R.chunk(s.entries,200))try{const t=await e.memorySaveBatch(n);if(l+=t&&t.saved||n.length,r&&n.length){const e=n[0]||{};r.awardImports(n,{source:e.session||e.source||"foreign-import"})}}catch(e){if(p=ge(e),!p&&t)for(const e of n)C.enqueue(t,e),c+=1,r&&r.awardQueued(e,{session:e&&e.session});d.push(he(e));break}return{...u,ok:0===d.length,dryRun:!1,saved:l,queued:c,upgrade:p,reason:d[0]||null}}function Ie(t,n,r){return t?e.join(n,"icons"):e.join(r,"build")}function $e(t,n){return"darwin"===n?e.join(t,"icon.icns"):"win32"===n?e.join(t,"icon.ico"):e.join(t,"icon.png")}function Pe(e){if("string"!=typeof e||!e)return!1;try{const t=new URL(e);return"http:"===t.protocol||"https:"===t.protocol}catch{return!1}}function Re(e){try{const t=e&&e.settings&&e.settings.list;return"function"==typeof t&&(t.call(e.settings)||[]).some((e=>{if(!e||!e.provider||q(e.provider))return!1;const t="string"==typeof e.baseURL?e.baseURL.trim():"";return Boolean(e.configured||t)}))}catch{return!1}}function Te(e,t,n,r,o,s,i){let a=null;const u=new Proxy({},{get(e,n){a||(a=h({dir:t,getVaultBackend:i}));const r=a[n];return"function"==typeof r?r.bind(a):r},has:(e,n)=>(a||(a=h({dir:t,getVaultBackend:i})),n in a)}),l=()=>{try{return Boolean("function"==typeof o&&o())}catch{return!1}},c=r||(()=>Promise.reject(new Error("no opener configured"))),d={status:()=>({appVersion:fe,clientVersion:e.clientVersion,apiBase:e.apiBase,keyConfigured:Boolean(e.apiKey),keyMask:me(e.apiKey),providerConfigured:l()}),setApiKey:t=>{try{const r=t&&t.key;return e.setApiKey(r||""),n&&n(e.apiKey),{ok:!0,keyConfigured:Boolean(e.apiKey),keyMask:me(e.apiKey)}}catch(e){return{ok:!1,error:e&&e.message||String(e)}}},verifyApiKey:async()=>{try{return{ok:!0,...await e.verifyApiKey()}}catch(e){return{ok:!1,error:e&&e.message||String(e)}}},tokenBankBalance:()=>e.tokenBankBalance(),billingCheckout:()=>async function(t){try{const t=await e.billingCheckout();return{ok:!0,url:t&&t.url||null,status:0,reason:null,setupRequired:!1,upgrade:null}}catch(e){const t=e&&e.data||{};return{ok:!1,url:null,status:e&&e.status||0,reason:he(e),setupRequired:Boolean(t.setup_required),upgrade:ge(e)}}}(),tokenBankTopup:async t=>{const n=Se(t&&t.amountEur);if(!n.ok)return{ok:!1,url:null,status:400,reason:n.message,setupRequired:!1,upgrade:null};const r=await Ae(e,n.amount);return!0===r.ok&&r.url&&Ce(e),{ok:!0===r.ok,url:r.url,status:r.status,reason:r.ok?null:r.hint?`${r.message} — ${r.hint}`:r.message,setupRequired:r.setupRequired,upgrade:null}},listModels:()=>e.listModels(),chatCompletion:t=>e.chatCompletion({prompt:t&&t.prompt,system:t&&t.system,model:t&&t.model,mode:t&&t.mode,maxTokens:t&&t.maxTokens,stream:t&&t.stream,onStream:t&&t.onStream}),fingerprintStatus:()=>u.status(),fingerprintKeygen:e=>u.keygen(e||{}),fingerprintMint:e=>u.mint(e||{}),fingerprintVerify:e=>u.verify(e||{}),fingerprintBackup:e=>u.backup(e||{})
5
- // gdrive:AEGIS-AGPL/records and writes the `.anchor.json` link beside the
6
- ,fingerprintPublish:e=>u.publish(e||{}),fingerprintAnchor:e=>u.anchor(e||{}),fingerprintVault:()=>u.vaultList(),fingerprintVaultAudit:()=>u.vaultAudit(),byokStatus:()=>e.byokStatus(),byokSet:t=>e.byokSet(t&&t.provider,t&&t.apiKey),memorySearch:t=>De(e.memorySearch(t&&t.query,t&&t.limit)),memorySave:n=>async function(e,t,n,r){const o=j.normalizeMemoryEntry(n);try{const t=await e.memorySave(o);return r&&o&&"object"==typeof o&&r.awardSave(o,{session:o.session}),t}catch(e){const s=ge(e);if(s)return{ok:!1,queued:0,saved:0,upgrade:s,reason:he(e)};if(!t||!n)throw e;return C.enqueue(t,o),r&&o&&"object"==typeof o&&r.awardQueued(o,{session:o.session}),{ok:!0,queued:!0,reason:he(e)}}}(e,t,n&&n.entry,s),memoryList:t=>De(e.memoryList(t&&t.limit)),verifyToken:t=>e.verifyToken(t&&t.token),memoryActivate:t=>e.memoryActivate(t&&t.token),memoryPull:t=>e.memoryPull(t&&t.since),memorySaveBatch:t=>e.memorySaveBatch(t&&t.entries),memoryImport:n=>je(e,t,n,s),importConversation:t=>e.importConversation(t||{}),openExternal:e=>{const t=e&&e.url;return Pe(t)?Promise.resolve(c(t)).then((()=>({ok:!0})),(e=>({ok:!1,reason:he(e)}))):Promise.resolve({ok:!1,reason:"unsupported URL scheme"})}};return d}function Be(e,t,n){return n?e.then((e=>(n(t,e),e))):e}function Le(e,t,n,r,o,s,i,a){const u=Te(t,n,r,o,i,void 0,a);for(const[t,n]of Object.entries(u))"chatCompletion"!==t?e.handle(`${z}${t}`,((e,t)=>n(t))):e.handle(`${z}${t}`,((e,t)=>{const r={...t||{}};if(!r.stream)return Be(n(r),e,s);const o=e&&e.sender;return Be(n({...r,stream:!0,onStream:e=>{o&&"function"==typeof o.send&&!o.isDestroyed()&&o.send(J,pe(e,r.sessionId))}}),e,s)}));return u}function Ne(e){if(!e)throw new Error("createConfirmModeDispatch requires a settings store");return{getConfirmMode:()=>({enabled:e.getConfirmMode()}),setConfirmMode:t=>{const n=t&&t.enabled;return"boolean"!=typeof n?{enabled:e.getConfirmMode()}:{enabled:e.setConfirmMode(n)}}}}function xe(e,t){const n=e.setConfirmMode;return{...e,setConfirmMode:e=>{const r=n(e);return e&&"boolean"==typeof e.enabled&&t&&"function"==typeof t.setAutoRounds&&t.setAutoRounds(!1===e.enabled),r}}}function Ue(e,t){for(const[n,r]of Object.entries(t))e.handle(`${z}${n}`,((e,t)=>r(t)));return t}function Oe(e){if(!e)throw new Error("createVaultBackendDispatch requires a settings store");return{getVaultBackend:()=>e.vaultBackendConfig(),setVaultBackend:t=>e.setVaultBackendConfig(t&&t.backend)}}function Fe(e){const t=e||null;return{telemetryEvent:e=>{try{if(!t||"function"!=typeof t.record)return{ok:!1,reason:"telemetry off"};const n=e&&"object"==typeof e?e:{};return t.record(n.event,{campaign:n.campaign,surface:n.surface})?{ok:!0}:{ok:!1,reason:"not an allowlisted funnel event"}}catch(e){return{ok:!1,reason:he(e)}}},telemetryReport:()=>{try{return t&&"function"==typeof t.report?t.report():{enabled:!1,transport:"off"}}catch(e){return{enabled:!1,error:he(e)}}}}}function Ke(e){return{covenantStatus:()=>({ok:!0,covenant:e.snapshot(),gapReport:e.gapReport()}),covenantGapReport:()=>({ok:!0,gapReport:e.gapReport()})}}function Ve(e,t){for(const[n,r]of Object.entries(t))e.handle(`${z}${n}`,((e,t)=>r(t)));return t}function ze(e,t){for(const[n,r]of Object.entries(t))e.handle(`${z}${n}`,((e,t)=>r(t)));return t}function We(e){return(e&&(e.title||e.id)||"session").replace(/[^\w.-]+/g,"_").slice(0,80)||"session"}function He(e,t,n,r){return{exportSession:async o=>{const s=o&&o.sessionId,i=o&&"json"===o.format?"json":"markdown",a=s?e.getSession(t,s):null;if(!a)return{ok:!1,reason:"session not found"};const u="json"===i?e.toJson(a):e.toMarkdown(a),l="json"===i?"json":"md",c="json"===i?[{name:"JSON",extensions:["json"]}]:[{name:"Markdown",extensions:["md"]}],d=await n({defaultPath:`${We(a)}.${l}`,filters:c});if(!d||d.canceled||!d.filePath)return{ok:!1,canceled:!0};try{await r(d.filePath,u)}catch(e){return{ok:!1,reason:he(e)}}return{ok:!0,filePath:d.filePath}}}}function Ge(e,t,n,r,o){const s=He(t,n,r,o);for(const[t,n]of Object.entries(s))e.handle(`${z}${t}`,((e,t)=>n(t)));return s}function Qe(e,t={}){const n=Boolean(t.isPackaged),r=t.applyConfig||(()=>({active:!1,reason:null})),o=t.pushToMain||(()=>({ok:!1,reason:"no main window"}));let s={active:!1,reason:null};return{status:function(){return{...e.quickLauncherConfig(),packaged:n,...s}},setConfig:function(t){const o=e.setQuickLauncherConfig({enabled:t&&t.enabled,shortcut:t&&t.shortcut});return s=r(o)||{active:!1,reason:null},{...o,packaged:n,...s}},pushToMain:(e,t)=>o(e,t)}}function Xe(e,t){for(const[n,r]of Object.entries(t))"pushToMain"!==n?e.handle(`${G}${n}`,((e,t)=>r(t))):e.handle(`${G}${n}`,((e,t)=>r(t,e)));return t}function Ye(t){if(t&&"function"==typeof t.getPath)try{return t.getPath("userData")}catch{}return e.join(w.homedir(),".aegiscode")}function Je(e,{app:t,safeStorage:n,dir:r,sessionsDir:o}={}){const s=r||Ye(t),i=M({dir:s,safeStorage:n});return i.migrateLegacyAegisKey(),{engine:S({aegis:e,settings:i}),sessionsDir:o||_.resolveStoreDir(s),settingsDir:s,settings:i}}const Ze=524288;function et(n){try{const r=n&&"string"==typeof n.file?n.file:"",o=n&&"string"==typeof n.cwd?n.cwd:"";if(!r||!o||!e.isAbsolute(o))return null;const s=t.realpathSync(o),i=t.realpathSync(e.resolve(s,r)),a=e.relative(s,i);if(""===a||a.startsWith("..")||e.isAbsolute(a))return null;const u=t.statSync(i);if(!u.isFile())return null;if(u.size<=Ze)return{text:t.readFileSync(i,"utf8"),truncated:!1};const l=t.openSync(i,"r");try{const e=Buffer.alloc(Ze),n=t.readSync(l,e,0,Ze,0);let r=e.toString("utf8",0,n);const o=r.lastIndexOf("\n");return o>0&&(r=r.slice(0,o+1)),{text:r,truncated:!0}}finally{t.closeSync(l)}}catch{return null}}const tt=require("./lib/local/attachments.js");function nt(e,t){try{const{nativeImage:n}=require("electron");if(!n)return null;const r=n.createFromBuffer(e);if(!r||r.isEmpty())return null;const o=r.getSize(),s=Math.max(o.width,o.height),i=s>1568?r.resize({width:Math.round(1568*o.width/s)}):r,a="image/png"===t?i.toPNG():i.toJPEG(82);return a&&a.length?{buffer:a,mime:"image/png"===t?"image/png":"image/jpeg"}:null}catch{return null}}function rt(n,{resize:r=nt}={}){const o=n&&"string"==typeof n.path?n.path.trim():"";if(!o)return{ok:!1,reason:"no path"};if(!e.isAbsolute(o))return{ok:!1,reason:"not an absolute path"};let s,i,a;try{s=t.realpathSync(o),i=t.statSync(s)}catch{return{ok:!1,reason:"not found"}}if(!i.isFile())return{ok:!1,reason:"not a regular file"};if(0===i.size)return{ok:!1,reason:"empty file"};if(i.size>tt.MAX_FILE_BYTES)return{ok:!1,reason:`too large (${tt.humanBytes(i.size)})`};try{a=t.readFileSync(s)}catch{return{ok:!1,reason:"unreadable"}}const u=tt.sniff(a),l={path:s,name:e.basename(s),size:i.size,mime:u.mime,kind:u.kind};if("image"===u.kind){let{mime:e}=u,t=a,n=!1;if(t.length>tt.MAX_IMAGE_BYTES&&"function"==typeof r){const o=r(a,e);o&&o.buffer&&o.buffer.length<t.length&&(t=o.buffer,e=o.mime,n=!0)}const o=tt.toDataUrl(t,e);return o?{ok:!0,attachment:{...l,kind:"image",mime:e,size:t.length,dataUrl:o,scaled:n,vision:tt.isVisionMime(e)}}:{ok:!1,reason:"could not encode image"}}if("text"===u.kind){if(i.size>tt.MAX_TEXT_BYTES){let e=a.subarray(0,tt.MAX_TEXT_BYTES).toString("utf8");const t=e.lastIndexOf("\n");return t>0&&(e=e.slice(0,t+1)),{ok:!0,attachment:{...l,kind:"text",text:e,truncated:!0}}}return{ok:!0,attachment:{...l,kind:"text",text:a.toString("utf8"),truncated:!1}}}return"pdf"===u.kind?{ok:!0,attachment:{...l,kind:"pdf"}}:{ok:!0,attachment:{...l,kind:"binary"}}}function ot(e,{env:t=process.env,settings:n}={}){const r=new Map;let o,s=x(t),i=!1;const a=()=>{const t=n||e&&e.settings||null,r=e=>"boolean"==typeof e?e:void 0;let a;try{if(t&&"function"==typeof t.confirmModeState){const e=t.confirmModeState();a=r(e&&e.enabled)}void 0===a&&t&&"function"==typeof t.getConfirmMode&&(a=r(t.getConfirmMode()))}catch{}return i||void 0===a||(void 0===o?o=a:a!==o&&(i=!0,s=!0)),!(!s||!t||void 0===a)&&!1===a},u={listClasses:async()=>(await e.listClasses()).filter((e=>Y.includes(e.class))),listModels:t=>e.listModels(t&&t.class),chat:n=>{const o=n&&n.onStream;if("function"!=typeof o)return e.chat(n,o);const s=n&&n.sessionId||"";return e.chat(n,(n=>{if(n&&n.rounds&&n.rounds.id&&a()){const i=L({on:!0,used:r.get(s)||0,limit:N(t)});if(r.set(s,i.used),i.auto){const t="function"==typeof e.respondRoundsAsk?e.respondRoundsAsk(n.rounds.id,!0):{ok:!1};if(t&&t.ok){const e=Number(n.rounds.spent)||0;return void o({note:`auto mode: the ${e}-round limit was reached — continuing automatically (${i.used}/${i.cap}, then it asks).`})}}}o(n)}))},"settings.get":()=>e.settings.list().filter((e=>!(e&&q(e.provider)))),"settings.set":t=>e.settings.set(t&&t.provider,{baseURL:t&&t.baseURL,key:t&&t.key}),"settings.remove":t=>e.settings.remove(t&&t.provider),"userModels.get":()=>e.userModels(),"userModels.add":t=>e.addUserModel(t&&t.provider,t&&t.model),"userModels.remove":t=>e.removeUserModel(t&&t.provider,t&&t.model),"userModels.discover":t=>e.discoverModels(t&&t.provider),"userModels.addAll":t=>e.addUserModels(t&&t.provider,t&&t.ids),"userModels.canDiscover":t=>Boolean(e.canDiscoverModels(t&&t.provider)),"userModels.discoverable":()=>e.discoverableProviders(),"memoryPersist.get":()=>e.settings.memoryPersistState(),"memoryPersist.set":t=>e.settings.setMemoryPersist(Boolean(t&&t.enabled)),cancel:t=>e.cancel(t&&t.sessionId),respondApproval:t=>e.respondApproval(t&&t.approvalId,t&&t.decision),respondRoundsAsk:t=>"function"==typeof e.respondRoundsAsk?e.respondRoundsAsk(t&&t.roundsAskId,t&&t.decision):{ok:!1},clearApprovals:t=>e.clearSessionApprovals(t&&t.sessionId)};return Object.defineProperties(u,{autoRoundsOn:{value:a,enumerable:!1},setAutoRounds:{value:e=>{s=Boolean(e),i=!0},enumerable:!1}}),u}function st(e,t,n,r,o){let s=null;function i(){return Boolean(n&&n.apiKey)}async function a(){const r=e.listPending(t);if(!i())return{ok:!1,queued:r.length,reason:"no AEGIS key configured"};const o=await async function(){const e=C.listQueued(t);if(!e.length)return{flushed:0,remaining:0,upgrade:null};const r=[];let o=0,s=null;for(let t=0;t<e.length;t+=1)try{await n.memorySave(e[t]),o+=1}catch(n){const o=ge(n);if(o){s=o,r.push(...e.slice(t));break}r.push(e[t])}return C.save(t,r),{flushed:o,remaining:r.length,upgrade:s}}();if(!r.length)return{ok:!0,queued:0,pushed:0,memoryFlushed:o.flushed,upgrade:o.upgrade};let a=0,u=null,l=null;for(const o of r)try{const r=await n.conversationSyncPush({session_id:o.id,title:o.title,messages:o.messages}),s=r&&(r.session_id||r.id);e.markSynced(t,o.id,{remoteId:s}),a+=1}catch(e){if(u=e,l=be(e),"quota"===l.kind||"auth"===l.kind)break}const c=e.listPending(t).length;a&&(s=Date.now());const d=(u?ge(u):null)||o.upgrade;return 0===a&&u?{ok:!1,queued:c,reason:ve(l),failed:l?[l]:[],kind:l?l.kind:"error",status:l?l.status:0,hint:l?l.hint:null,memoryFlushed:o.flushed,upgrade:d}:{ok:!0,queued:c,pushed:a,failed:l?[l]:[],memoryFlushed:o.flushed,upgrade:d}}const u=D.createAutoPush({push:a,dir:r||t});return{auto:()=>u.auto(),memoryPersistState:()=>u.gate(),listSessions:()=>({sessions:e.listSessions(t)}),open:n=>e.getSession(t,n&&n.sessionId),save:n=>e.upsertSession(t,n||{}),append:n=>e.appendMessage(t,n&&n.sessionId,n&&n.message),delete:n=>e.deleteSession(t,n&&n.sessionId),nameSession:async n=>{const r=n&&n.sessionId,s=n&&n.prompt;if(!r||!String(null==s?"":s).trim())return null;let i;for(const e of["../client/naming.js","./vendor/naming.js","./vendor/client/naming.js"])try{i=require(e);break}catch{}if(!i)return null;const a=async(e,t={})=>{if(!o||"function"!=typeof o.chat)return null;try{const s=await o.chat({class:n&&n.class||"model",model:n&&n.model,prompt:e,system:t.system,maxTokens:64,sessionId:r,tools:!1}),i=s&&s.choices&&s.choices[0]||{};return i.message&&i.message.content||null}catch{return null}};try{return await i.nameSession(e,t,r,s,{callModel:a})}catch{return null}},push:a,pull:async function(){if(!i())return{ok:!1,merged:0,reason:"no AEGIS key configured"};try{const r=await n.conversationSyncPull(),o=e.mergeRemoteSessions(t,r&&r.sessions||[]);return s=Date.now(),{ok:!0,merged:o,failed:[],upgrade:null}}catch(e){const t=be(e);return{ok:!1,merged:0,reason:ve(t),failed:[t],kind:t.kind,status:t.status,hint:t.hint,upgrade:ge(e)}}},status:()=>({count:e.listSessions(t).length,pending:e.listPending(t).length,cloud:i(),lastSyncAt:s})}}const it=5e3,at=3e4;function ut(e,t={}){const n="function"==typeof t.now?t.now:()=>Date.now(),r=Number(t.baseMs)>0?Number(t.baseMs):it,o=Number(t.maxMs)>0?Number(t.maxMs):at;let s=0,i=0,a=null,u=!1;function l(e){s+=1;const t=Math.min(o,r*2**Math.max(0,s-1));return a=e||"push failed",i=n()+t,{attempted:!0,ok:!1,error:a,failures:s,retryInMs:t}}return{run:async function(){const t=n();if(s>0&&t<i)return{attempted:!1,ok:!1,error:a,failures:s,retryInMs:i-t};if(u)return{attempted:!1,ok:!1,error:a,failures:s,retryInMs:0};u=!0;try{const t=await e();return t&&!1===t.ok?l(t.reason||t.kind||"push failed"):(s=0,i=0,a=null,{attempted:!0,ok:!0,error:null,failures:0,retryInMs:0,result:t})}catch(e){return l(he(e))}finally{u=!1}},state:function(){const e=n();return{failures:s,lastError:a,retryInMs:s>0&&i>e?i-e:0}},recordFailure:e=>l(he(e))}}function lt(e,t,n,r,o,s,i){const a=ot(t),u=st(_,n,r,i,a),l=ut((()=>u.push()),s);function c(){const e=l.run();e&&"function"==typeof e.catch&&e.catch((e=>l.recordFailure(e)))}for(const[t,n]of Object.entries(a))"chat"!==t?"listModels"!==t?e.handle(`${W}${t}`,((e,t)=>n(t))):e.handle(`${W}${t}`,((e,t)=>(c(),n(t)))):e.handle(`${W}${t}`,((e,t)=>{const r={...t||{}},s=!0===r.bestEffort;delete r.bestEffort;const i="low"===r.effort||"medium"===r.effort||"max"===r.effort?r.effort:"high";r.effort=i;const a=e&&e.sender,u=r.class||"model",l=n({...r,onStream:e=>{a&&"function"==typeof a.send&&!a.isDestroyed()&&a.send(J,pe(e,r.sessionId))}});return s?l.then((t=>(o&&o(e,t),t)),(e=>{const t=e&&"number"==typeof e.status?e.status:0,n=e&&e.code||"";return console.warn(`[model] background ${u} turn produced no answer: ${he(e)}${t?` (status ${t})`:""}${n?` [${n}]`:""}`),{bestEffortFailed:!0,status:t,code:n||void 0,message:he(e),choices:[{message:{content:""}}]}})):Be(l,e,o).catch((e=>{if(!ye(e))throw e;return console.warn(`[model] ${u} turn stopped before it finished: ${he(e)} [ABORT_ERR]`),ke(e)}))}));e.on(`${W}readTextFile`,((e,t)=>{e.returnValue=et(t)})),e.handle(`${z}attachments:ingest`,(async(e,t)=>rt(t)));for(const[t,n]of Object.entries(u))"status"!==t?e.handle(`${H}${t}`,((e,t)=>n(t))):e.handle(`${H}${t}`,((e,t)=>{c();const r=n(t);return r&&"object"==typeof r?{...r,retry:l.state()}:r}));return{modelDispatch:a,syncDispatch:u,heartbeat:l}}function ct(e,t){return S({aegis:e,settings:t,getConfirmMode:()=>!1})}function dt(e){return e&&"function"==typeof e.chat?{...e,chat:(t,n)=>e.chat(t,(t=>{(t=>{const n=t&&t.approval;if(n&&n.id&&"function"==typeof e.respondApproval)try{e.respondApproval(n.id,"deny")}catch{}})(t),(t=>{const n=t&&t.rounds;if(n&&n.id&&"function"==typeof e.respondRoundsAsk)try{e.respondRoundsAsk(n.id,!1)}catch{}})(t),"function"==typeof n&&n(t)}))}:e}function pt(e,t,n){const r=Number(e);return!Number.isInteger(r)||r<t||r>n?null:r}function ft({engine:n,env:r=process.env,queue:o=T,autonomous:s=B,entitlement:i=U.createEntitlement({}),log:a=(()=>{})}={}){if(!n||"function"!=typeof n.chat)throw new Error("createQueueDispatch: a local engine with chat() is required");let u=null,l=!1,c=!1;const d=s.createQueueWorker({engine:dt(n),env:r,log:e=>{e&&"start"===e.type&&(u=e.taskId),e&&"finish"===e.type&&(u=null),a(e)},canFanOut:()=>i.current().entitled});function p(){const e=o.loadQueue(r);return{ok:!0,items:e,pending:o.pendingCount(e),running:e.find((e=>e&&"running"===e.status))||null,draining:c,stopping:l,defaultCwd:process.cwd(),defaultModel:s.resolveModel({env:r}),queueFile:o.queuePath(r),runs:o.readRuns(r,{limit:20}),entitlement:i.current()}}const f=e=>(e||[]).map((e=>({id:e.id,ok:Boolean(e.ok),error:e.error||null})));return{enqueue:async n=>{await i.refresh();const a=i.gateFanout({workers:pt(n&&n.workers,1,ce),fanout:Boolean(n&&!0===n.fanout)});if(!a.ok)return{...a,...p()};const{opts:u,error:l}=function(n){const r=n||{},o=String(null==r.task?"":r.task).trim();if(!o)return{error:"a queued task needs text"};if(o.length>ue)return{error:`task text is too long (${o.length} > ${ue} chars)`};const i=String(null==r.cwd?"":r.cwd).trim()||process.cwd();if(!e.isAbsolute(i))return{error:"the working directory must be an absolute path"};if(!function(e){try{return t.statSync(e).isDirectory()}catch{return!1}}(i))return{error:`not a directory: ${i}`};const a=s.normalizeClass(r.class),u=String(null==r.model?"":r.model).trim().slice(0,120)||null,l=s.modelRefusal(u,a);if(l)return{error:l};const c=String(null==r.effort?"":r.effort).trim().toLowerCase();return{opts:{task:o,cwd:i,class:a,model:u,effort:de.has(c)?c:null,workers:pt(r.workers,1,ce),maxRounds:pt(r.maxRounds,1,le),singlePass:!(!0===r.fanout||!0===r.autonomous),commit:Boolean(r.commit),source:"desktop"}}}(n);return l?{ok:!1,reason:l,...p()}:{ok:!0,item:o.addTask(r,u),...p()}},list:()=>p(),entitlement:async e=>(await i.refresh({force:Boolean(e&&!0===e.force)}),{ok:!0,...p()}),clear:e=>({...o.clearQueue(r,{all:Boolean(e&&e.all)}),ok:!0,...p()}),retry:e=>{const t=e&&e.id,n=o.retryTask(r,t);return n?{ok:!0,item:n,...p()}:{ok:!1,reason:`no task #${t}`,...p()}},remove:e=>{const t=e&&e.id,n=o.loadQueue(r),s=o.findTask(n,t);return s?"running"===s.status?{ok:!1,reason:`task #${s.id} is running — stop the drain first`,...p()}:(o.saveQueue(r,n.filter((e=>Number(e&&e.id)!==Number(s.id)))),{ok:!0,removed:s.id,...p()}):{ok:!1,reason:`no task #${t}`,...p()}},drain:()=>async function(){if(c)return{ok:!1,reason:"a drain is already running in this window",...p()};let e;c=!0,l=!1;try{const t=await d.proceed({max:1});e=t.locked?{ok:!1,locked:!0,holder:t.holder,ran:[]}:{ok:!0,ran:f(t.ran)}}catch(t){e={ok:!1,reason:he(t),ran:[]}}return c=!1,u=null,{...e,...p()}}(),proceed:()=>async function(){if(c)return{ok:!1,reason:"a drain is already running in this window",...p()};c=!0,l=!1;const e=[];let t;try{for(;;){const n=await d.proceed({max:1});if(n.locked){t={ok:!1,locked:!0,holder:n.holder,ran:f(e)};break}if(!n.ran.length){t={ok:!0,stopped:l,ran:f(e)};break}if(e.push(...n.ran),l){t={ok:!0,stopped:!0,ran:f(e)};break}}}catch(n){t={ok:!1,reason:he(n),ran:f(e)}}return c=!1,u=null,{...t,...p()}}(),stop:e=>{l=!0;const t=e&&null!=e.id?e.id:u,n=null==t?null:d.cancel(t);return{ok:!0,wasDraining:c,cancelled:n,...p()}}}}function mt({autoDrain:e,autoMint:t}={}){if(!e||"function"!=typeof e.state)throw new Error("createAutoDispatch: the auto-drain automation is required");if(!t||"function"!=typeof t.state)throw new Error("createAutoDispatch: the auto-mint automation is required");return{autoStatus:()=>({ok:!0,drain:e.state(),mint:t.state()}),autoSetDrain:t=>{const n=t||{},r={};null!=n.enabled&&(r.enabled=Boolean(n.enabled)),null!=n.intervalMs&&(r.intervalMs=Number(n.intervalMs));try{return{ok:!0,drain:e.set(r)}}catch(e){return{ok:!1,error:he(e)}}},autoSetMint:e=>{const n=e||{},r={};null!=n.enabled&&(r.enabled=Boolean(n.enabled)),null!=n.publish&&(r.publish=Boolean(n.publish));try{return{ok:!0,mint:t.set(r)}}catch(e){return{ok:!1,error:he(e)}}},autoSealNow:async e=>{const n=e||{};null!=n.publish&&t.set({publish:Boolean(n.publish)});try{const e=await t.flush();return t.reset(),{ok:!0,...e}}catch(e){return t.reset(),{ok:!1,error:he(e)}}}}}function gt(e,{engine:t,env:n,queue:r,autonomous:o,entitlement:s,aegis:i}={}){let a=null;const u=ft({engine:t,env:n,queue:r,autonomous:o,entitlement:s||U.createEntitlement({probe:i&&"function"==typeof i.verifyApiKey?async()=>{const e=await i.verifyApiKey(),t=e&&"object"==typeof e?{...e}:{};if("function"==typeof i.tokenBankBalance)try{const e=await i.tokenBankBalance();e&&"object"==typeof e&&(null!=e.balance_micros?t.balance_micros=e.balance_micros:null!=e.balance_eur&&(t.balance_eur=e.balance_eur))}catch{}return t}:void 0}),log:e=>{a&&"function"==typeof a.send&&("function"==typeof a.isDestroyed&&a.isDestroyed()||a.send(ae,e))}});for(const[t,n]of Object.entries(u))e.handle(`${Q}${t}`,((e,t)=>(a=e&&e.sender||null,n(t))));return u}function ht(e,t){for(const[n,r]of Object.entries(t))e.handle(`${X}${n}`,((e,t)=>r(t)));return t}const yt=`${z}updateStatus`,kt=`${z}accountStatusChanged`,bt=144e5,vt=[6e4,3e5,9e5,36e5];function wt(e,t,n){switch(e){case"not-found":return`${n} is not published on the npm registry (404)`;case"forbidden":return`the npm registry refused the request (${t||"auth"})`;case"malformed":return"the npm registry sent a response this app could not read";case"too-large":return"the npm registry response was too large to read";case"timeout":return"the npm registry did not respond in time";case"network":return"the npm registry could not be reached";default:return"the update check did not complete"}}function St({onStatus:r,packaged:o=!1,now:s=(()=>Date.now()),fetchImpl:i,setTimeoutImpl:a=setTimeout,clearTimeoutImpl:u=clearTimeout,runUpgrade:l,relaunch:c}={}){const d="aegis-desktop";let p="unknown";try{p=require("./package.json").version}catch{}let f={status:"idle",version:null,error:null,channel:"npm",reason:null,transient:!1,attempts:0,retryInMs:0,command:null,plan:null,method:null,canDownload:!1};const m=e=>(f={...f,...e},r&&r(f),f);let g=null;try{g=require("../client/update.js")}catch{try{g=require("./vendor/update.js")}catch{g=null}}let h=0,y=0,k=null,b=null,v=null,w=null;function S(){k&&u(k),k=null}async function A({announce:n=!1}={}){if(!g)return m({status:"disabled",error:"update checker unavailable"});if(b)return b;b=(async()=>{const r=f.status,u=f.version;let l;m({status:"checking",error:null,reason:null,transient:!1});try{l=await async function(){if(i)return i({pkg:d});if(g&&"function"==typeof g.checkPublished){const e=await g.checkPublished({current:p,pkg:d,now:s(),intervalMs:0});return e?{ok:e.ok,latest:e.latest,reason:e.reason,status:e.status}:{ok:!1,latest:null,reason:"unknown",status:null}}return{ok:!1,latest:null,reason:"unavailable",status:null}}()}catch(e){l={ok:!1,latest:null,reason:"unknown",status:null,error:he(e)}}if(l.ok){if(h=0,y=0,S(),!g.isNewer(l.latest,p))return m({status:"up-to-date",version:l.latest,error:null,reason:null,transient:!1,attempts:0,retryInMs:0});const n=function(){if(w)return w;const n=g&&g.detectInstallMethod;if("function"!=typeof n)return w="npm",w;try{w=n({env:process.env,argv:process.argv,pkg:d,entry:__dirname,fileExists:n=>t.existsSync(e.resolve(__dirname,"..",n))})}catch{w="npm"}return w}(),r="function"==typeof g.updatePlan?g.updatePlan({current:p,latest:l.latest,behind:!0,channel:"npm",pkg:d,method:n}):null;return m({status:"available",version:l.latest,error:null,reason:null,transient:!1,attempts:0,retryInMs:0,plan:r,method:n,command:o?`${l.latest} is published — reinstall AEGIS Desktop from the installer to pick it up`:r&&r.instruction||`npm i -g ${d}@latest`,commandIsSentence:o||Boolean(r&&!r.apply),canDownload:Boolean(r&&r.apply)&&!o})}h+=1;const c=l.error||wt(l.reason,l.status,d);return b=l.reason,v=l.status,("function"==typeof g.isTransientReason?g.isTransientReason(b,v):"unknown"===b)?(function(){S();const e=vt[Math.min(Math.max(h-1,0),vt.length-1)];y=s()+e,k=a((()=>{k=null,A().catch((()=>{}))}),e),k&&k.unref&&k.unref(),m({retryInMs:e})}(),m(n?{status:"error",error:c,reason:l.reason,transient:!0,attempts:h}:{status:"available"===r?"available":"unavailable",version:u,error:c,reason:l.reason,transient:!0,attempts:h})):(S(),y=0,m({status:"error",error:c,reason:l.reason,transient:!1,attempts:h,retryInMs:0}));var b,v})();try{return await b}finally{b=null}}return{status:()=>f,check:A,download:async()=>{const e=!o&&f.plan&&f.plan.apply;if(!e)return m({status:"available"===f.status?"available":f.status,command:f.plan&&f.plan.instruction||f.command,canDownload:!1});m({status:"downloading",error:null,progress:0});const t=await function(e){const t=l||((e,t)=>new Promise((r=>{n(e,t,{timeout:18e4,windowsHide:!0},((e,t,n)=>{if(e)return r({ok:!1,output:String(n||t||e.message||e)});r({ok:!0,output:String(t||"")})}))}))),r=!l&&g&&"function"==typeof g.installSpawn?g.installSpawn(e,{env:process.env}):null,o=r?r.command:e.command,s=r?r.args:e.args;return Promise.resolve(t(o,s)).then((e=>({ok:Boolean(e&&e.ok),output:String(e&&e.output||"")})),(e=>({ok:!1,output:he(e)})))}(e);return t.ok?m({status:"downloaded",version:f.version,error:null,progress:100,command:`npm i -g ${d}@latest`,canDownload:!1}):m({status:"error",transient:!1,error:t.output.trim().split("\n").slice(-3).join(" ").trim()||"the installer failed",command:`${e.command} ${e.args.join(" ")}`})},quitAndInstall:()=>{"downloaded"===f.status&&(c||(()=>{try{const{app:e}=require("electron");e.relaunch(),e.exit(0)}catch{}}))()},start:()=>{A().catch((()=>{})),v=setInterval((()=>A().catch((()=>{}))),bt),v.unref&&v.unref()},stop:()=>{S(),v&&clearInterval(v),v=null},retryState:()=>({attempts:h,retryAt:y,inFlight:!!b,hasTimer:!!k})}}function At({isPackaged:e,onStatus:t}){let n={status:"idle",version:null,error:null,canDownload:!1};return St({onStatus:function(e){n={...n,...e},t&&t(n)},packaged:Boolean(e)})}function Et(e){return{checkForUpdates:()=>e.check({announce:!0}),downloadUpdate:()=>e.download(),quitAndInstallUpdate:()=>(e.quitAndInstall(),{ok:!0}),updateStatus:()=>Promise.resolve(e.status())}}function Mt(e,t){const n=Et(t);for(const[t,r]of Object.entries(n))e.handle(`${z}${t}`,((e,t)=>r(t)));return n}let qt=null;function _t(e,t){const n="function"==typeof qt?qt():null,r=n&&!n.isDestroyed()?n:e.getFocusedWindow()||e.getAllWindows()[0];r&&!r.isDestroyed()&&r.webContents.send(t)}function Ct(e,t){if(!e||e.isDestroyed()||!t)return;const n=()=>{e.isDestroyed()||e.webContents.send(se,t)};e.webContents.isLoadingMainFrame()?e.webContents.once("did-finish-load",n):n()}function Dt({app:e,Menu:t,BrowserWindow:n,updateManager:r,loggedIn:o}){const s="darwin"===process.platform;e.setAboutPanelOptions({applicationName:e.getName(),applicationVersion:e.getVersion(),version:e.getVersion()});const i={label:"Check for Updates…",click:()=>r.check({announce:!0})},a={label:"New Chat",accelerator:"CmdOrCtrl+N",click:()=>_t(n,Z)},u={label:"Search…",accelerator:"CmdOrCtrl+K",click:()=>_t(n,ee)},l={label:"Save as…",accelerator:"CmdOrCtrl+S",click:()=>_t(n,te)},c={label:"Export Session…",click:()=>_t(n,ne)},d={label:"Authorship Panel…",click:()=>_t(n,re)},p={label:"Google Drive Backup…",enabled:Boolean(o),click:()=>_t(n,oe)},f=[...s?[{label:e.getName(),submenu:[{role:"about"},i,{type:"separator"},{role:"services"},{type:"separator"},{role:"hide"},{role:"hideOthers"},{role:"unhide"},{type:"separator"},{role:"quit"}]}]:[],{label:"File",submenu:[a,{type:"separator"},l,c,{type:"separator"},...s?[]:[i,{type:"separator"}],s?{role:"close"}:{role:"quit"}]},{label:"Edit",submenu:[{role:"undo"},{role:"redo"},{type:"separator"},{role:"cut"},{role:"copy"},{role:"paste"},{role:"selectAll"}]},{label:"View",submenu:[u,{type:"separator"},d,p,{type:"separator"},{role:"reload",accelerator:"CmdOrCtrl+R"},{role:"forceReload"},{type:"separator"},{role:"toggleDevTools",accelerator:"CmdOrCtrl+Shift+I"}]},...s?[]:[{label:"Help",submenu:[{role:"about"}]}]];return t.buildFromTemplate(f)}v&&v.app&&function(){let n=!1;try{n=require("./lib/local/integrity.js").armed()}catch{n=!0,process.env.AEGIS_REDUCED_MODE="1",process.stderr.write("aegis-desktop: reduced mode (d1) — this build is not the one that was published.\n")}if(n){try{const{app:e}=v;e&&"function"==typeof e.quit&&e.quit()}catch{}return}const{app:o,BrowserWindow:l,ipcMain:w,safeStorage:S,shell:M,Menu:q,Notification:C,screen:D,dialog:j,globalShortcut:R}=v;if(o.disableHardwareAcceleration(),o.commandLine.appendSwitch("disable-gpu"),o.commandLine.appendSwitch("disable-software-rasterizer"),o.commandLine.appendSwitch("disable-gpu-compositing"),o.commandLine.appendSwitch("disable-features","UsePortalAccentColor"),process.argv.some((e=>/^--(log-level|enable-logging)/.test(e)))||process.env.ELECTRON_ENABLE_LOGGING||o.commandLine.appendSwitch("log-level","3"),!o.requestSingleInstanceLock())return void o.quit();if(o.setName("AEGIS Desktop"),b&&"function"==typeof b.loadEnvFile)try{const e=b.loadEnvFile();e.loose&&console.warn(`aegis: ${e.file} is readable by other accounts (mode ${e.mode.toString(8)}) — consider \`chmod 600\` on it.`)}catch(e){console.warn(`aegis: could not read ${b.envFileFor()}: ${e&&e.message}`)}o.setAsDefaultProtocolClient($.PROTOCOL);let B=$.parseDeepLinkArgv(process.argv);o.on("open-url",((e,t)=>{e.preventDefault();const n=$.parseDeepLinkUrl(t);if(!n)return;const r="function"==typeof qt?qt():null;r&&!r.isDestroyed()?Ct(r,n):B=n}));const L=s(i.clientOptions()),N=Ye(o),{engine:x,sessionsDir:U,settingsDir:O,settings:W}=Je(L,{app:o,safeStorage:S,dir:N}),H=A({aegis:L,credentials:i,persistKey:e=>W.setAegisKey(e),provision:(e,t)=>a.autoProvisionApiKey(e,t,{app:"desktop"}),describeFailure:a.provisionFailureText,onChange:e=>fe(e)});let G=null;const Q=m({aegis:L,credentials:i,persistKey:e=>W.setAegisKey(e),openUrl:e=>!!Pe(e)&&(M.openExternal(e),!0),googleSignIn:c,driveConnect:d,driveUpload:p,conversationExport:f?{...f,toTranscript:e=>_.toMarkdown(e)}:null,getSession:e=>_.getSession(U,e),getAuthor:()=>{try{G||(G=h({dir:N,getVaultBackend:()=>W.vaultBackendConfig().backend}));const e=G.status();return e&&e.ok?e:null}catch{return null}},onAccountChange:()=>fe(H.status())}),X=Boolean(L.apiKey),Y=a.autoProvisionApiKey(L,i,{app:"desktop"}).then((e=>{if(H.recordStartup(e),!e.key&&!L.apiKey){const t=e.error&&(e.error.status||e.error.message||String(e.error))||"no key returned";console.warn(`auto-provision: no account key from register-device (${t})`)}return e}));try{const{wrapProviderKeyMirror:e}=require("./lib/provider-key-mirror.js"),t=e=>console.warn(`aegis: ${e}`);e(W,b,{onWarn:t}),x&&x.settings&&x.settings!==W&&e(x.settings,b,{onWarn:t})}catch(e){console.warn(`aegis: could not wire the shared env-file key mirror: ${e&&e.message}`)}let J=null;const Z=(e,t)=>{if(function(e){const t=e&&e.sender,n=t&&l.fromWebContents(t);if(!n||n.isDestroyed())return;if(n.isFocused()&&n.isVisible())return;if(!C||!C.isSupported())return;const r=new C({title:"AEGIS Desktop",body:"Reply ready"});r.on("click",(()=>{n.isDestroyed()||(n.isMinimized()&&n.restore(),n.isVisible()||n.show(),n.focus())})),r.show()}(e),J&&"function"==typeof J.note){const e=t&&(t.model||t.modelId)||void 0;J.note({sessionId:t&&t.sessionId||null,model:e})}};Le(w,L,N,(e=>{const t=W.setAegisKey(e);return e?i.saveApiKey(e):i.clearApiKey(),t}),(e=>M.openExternal(e)),Z,(()=>Re(x)),(()=>W.vaultBackendConfig().backend));const ee=lt(w,x,U,L,Z,void 0,O);Ue(w,xe(Ne(W),ee.modelDispatch)),Ue(w,Oe(W)),ze(w,Fe(K({dir:O,enabled:V(process.env,W),appVersion:(()=>{try{return"function"==typeof o.getVersion?o.getVersion():""}catch{return""}})()}))),Ve(w,Ke(F));const te=gt(w,{engine:ct(L,W),aegis:L}),ne=y({proceed:()=>te.proceed(),settings:W,queue:T,env:process.env,log:e=>{e&&"skip"!==e.type&&console.log("[auto-drain]",e.type,e.reason||e.error||"")}});let re=null;J=k({mint:e=>(re||(re=h({dir:N,getVaultBackend:()=>W.vaultBackendConfig().backend})),re.mint(e||{})),settings:W}),ht(w,mt({autoDrain:ne,autoMint:J})),ne.start(),J.start();let oe=null,se=null;function ae(){return se&&!se.isDestroyed()||(se=new l({width:560,height:320,show:!1,frame:!1,alwaysOnTop:!0,skipTaskbar:!0,resizable:!1,movable:!0,fullscreenable:!1,minimizable:!1,maximizable:!1,backgroundColor:"#0d1117",icon:$e(Ie(o.isPackaged,process.resourcesPath,__dirname),process.platform),webPreferences:{preload:e.join(__dirname,"preload.js"),contextIsolation:!0,nodeIntegration:!1,sandbox:!0}}),se.setMenuBarVisibility(!1),se.loadFile(e.join(__dirname,"renderer","quick.html")),se.webContents.on("before-input-event",((e,t)=>{"keyDown"!==t.type||"Escape"!==t.key||se.isDestroyed()||se.hide()})),se.on("blur",(()=>{!se.isDestroyed()&&se.isVisible()&&se.hide()})),se.on("closed",(()=>{se=null}))),se}function ue(){const e=ae();e.isVisible()?e.hide():function(){const e=ae(),t=D.getCursorScreenPoint(),n=D.getAllDisplays(),r=e.getBounds(),o=P.computeQuickLauncherBounds({cursor:t,displays:n,size:{width:r.width,height:r.height}});e.setBounds(o),e.show(),e.focus()}()}qt=()=>{if(oe&&!oe.isDestroyed())return oe;const e=l.getFocusedWindow();return e&&!e.isDestroyed()&&e!==se?e:l.getAllWindows().find((e=>e!==se))||null};const le=Qe(W,{isPackaged:o.isPackaged,applyConfig:function(e){if(R.unregisterAll(),!P.shouldEnableGlobalShortcut({isPackaged:o.isPackaged,enabled:e.enabled}))return{active:!1,reason:null};try{if(!R.register(e.shortcut,ue)){const t=`"${e.shortcut}" could not be registered — it may already be in use by another application.`;return console.warn(`[quick-launcher] ${t}`),{active:!1,reason:t}}return{active:!0,reason:null}}catch(t){const n=he(t);return console.warn(`[quick-launcher] failed to register shortcut "${e.shortcut}": ${n}`),{active:!1,reason:n}}},pushToMain:function(e,t){const n=t&&t.sender&&l.fromWebContents(t.sender);n&&!n.isDestroyed()&&n.hide();const r=oe&&!oe.isDestroyed()?oe:l.getAllWindows().find((e=>e!==n))||null;return r?(r.webContents.send(ie,e||{}),r.isMinimized()&&r.restore(),r.isVisible()||r.show(),r.focus(),{ok:!0}):{ok:!1,reason:"no main window is open"}}});Xe(w,le);let ce=null;o.on("will-quit",(()=>{ce&&"function"==typeof ce.stop&&ce.stop(),R.unregisterAll(),ge&&"function"==typeof ge.stop&&ge.stop()}));let de=!1;o.on("before-quit",(e=>{!de&&x&&"function"==typeof x.unloadLocalModels&&(e.preventDefault(),Promise.resolve().then((()=>x.unloadLocalModels())).catch((()=>{})).finally((()=>{de=!0,o.quit()})))}));const pe=new Set;function fe(e){for(const t of pe)t.isDestroyed()||t.webContents.send(kt,e);me()}function me(){q.setApplicationMenu(Dt({app:o,Menu:q,BrowserWindow:l,updateManager:ge,loggedIn:Boolean(L.apiKey)}))}const ge=At({isPackaged:o.isPackaged,onStatus:function(e){for(const t of pe)t.isDestroyed()||t.webContents.send(yt,e)}});Mt(w,ge),w.handle(`${z}accountStatus`,(()=>H.status())),w.handle(`${z}registerAccount`,(()=>H.registerAccount())),w.handle(`${z}driveSignIn`,(()=>Q.signInWithGoogle())),w.handle(`${z}driveConnect`,(()=>Q.connectDrive())),w.handle(`${z}driveStatus`,(()=>Q.status())),w.handle(`${z}driveSyncMemory`,(()=>Q.syncMemoryNow())),w.handle(`${z}driveBackupConversation`,((e,t)=>Q.backupConversation({sessionId:t&&t.sessionId}))),Ge(w,_,U,(e=>j.showSaveDialog(l.getFocusedWindow(),e)),((e,n)=>t.promises.writeFile(e,n,"utf8"))),me();const ye=r(e.join(__dirname,"renderer","index.html")).href;function ke(){const t=I.load(N),n=I.clampToDisplay(t,D.getAllDisplays(),{width:1080,height:720}),r=Ie(o.isPackaged,process.resourcesPath,__dirname),s=new l({...n,minWidth:720,minHeight:480,show:!0,backgroundColor:"#0d1117",title:"AEGIS Desktop",icon:$e(r,process.platform),webPreferences:{preload:e.join(__dirname,"preload.js"),contextIsolation:!0,nodeIntegration:!1,sandbox:!0,spellcheck:!0}});t&&t.isMaximized&&s.maximize(),s.webContents.setWindowOpenHandler((({url:e})=>(Pe(e)&&M.openExternal(e),{action:"deny"}))),s.webContents.on("will-navigate",((e,t)=>{t!==ye&&(e.preventDefault(),Pe(t)&&M.openExternal(t))}));let i=null;function a(){if(s.isDestroyed())return;const e=s.isMaximized(),t=e?s.getNormalBounds():s.getBounds();I.save(N,{...t,isMaximized:e})}function u(){i&&clearTimeout(i),i=setTimeout(a,500)}return s.on("resize",u),s.on("move",u),s.on("close",(()=>{i&&clearTimeout(i),a()})),s.loadFile(e.join(__dirname,"renderer","index.html")),pe.add(s),oe=s,s.on("closed",(()=>{pe.delete(s),oe===s&&(oe=null)})),s}o.whenReady().then((async()=>{if(!i.normalizeApiKey(process.env[i.KEY_ENV])){const e=await Y,t=E({mintedKey:X?"":e.key,hostKey:i.normalizeApiKey(W.aegisRawKey())});if(t)i.saveApiKey(t),L.setApiKey(t);else{const e=i.preferNewest(W.aegisRawKey(),W.aegisKeySavedAt());e.key&&(L.setApiKey(e.key),"shared"===e.source&&W.setAegisKey(e.key))}}try{ce&&"function"==typeof ce.stop&&ce.stop(),ce=u.createPresence({apiKey:L.apiKey,app:"desktop",version:o.getVersion(),platform:process.platform,install:g.machineFingerprint(),queueDepth:()=>{try{return T.readQueue(T.queuePath()).filter((e=>e&&"pending"===e.status)).length}catch{return 0}},autonomous:!1,log:(e,t)=>{"debug"!==e&&console.warn(t)}}),ce.start()}catch(e){console.warn("presence: beacon not started",e&&e.message)}try{const{backfillProviderKeys:e}=require("./lib/provider-key-mirror.js"),t=e=>console.warn(`aegis: ${e}`),n=e(W,b,{onWarn:t});n.mirrored.length&&console.warn(`aegis: shared ${n.mirrored.join(", ")} key(s) with the other hosts (${b.envFileFor()})`),x&&x.settings&&x.settings!==W&&e(x.settings,b,{onWarn:t})}catch(e){console.warn(`aegis: could not backfill the shared env-file key mirror: ${e&&e.message}`)}le.setConfig(W.quickLauncherConfig());const e=ke();ge.start(),B&&Ct(e,B)})),o.on("window-all-closed",(()=>{"darwin"!==process.platform&&o.quit()})),o.on("activate",(()=>{const e=l.getAllWindows();if(0===e.length)return void ke();const t=qt()||e[0];t.isMinimized()&&t.restore(),t.isVisible()||t.show(),t.focus()})),o.on("second-instance",((e,t)=>{const n=qt(),r=$.parseDeepLinkArgv(t);if(n)n.isMinimized()&&n.restore(),n.isVisible()||n.show(),n.focus(),r&&Ct(n,r);else{const e=ke();r&&Ct(e,r)}}))}(),module.exports={createIpcDispatch:Te,registerIpc:Le,providerRouteConfigured:Re,IPC_PREFIX:z,MODEL_PREFIX:W,SYNC_PREFIX:H,watchTopupCredit:Ce,bankAmount:we,TOPUP_POLL_MS:Me,TOPUP_POLL_TRIES:qe,CHAT_DELTA_CHANNEL:J,MENU_NEW_CHAT_CHANNEL:Z,MENU_SEARCH_CHANNEL:ee,MENU_EXPORT_MARKDOWN_CHANNEL:te,MENU_EXPORT_JSON_CHANNEL:ne,MENU_FINGERPRINT_CHANNEL:re,MENU_GOOGLE_DRIVE_CHANNEL:oe,DEEP_LINK_CHANNEL:se,UPDATE_STATUS_CHANNEL:yt,UPDATE_CHECK_INTERVAL_MS:bt,taggedChunk:pe,maskKey:me,createModelDispatch:ot,DESKTOP_CLASSES:Y,readTextFileForPreview:et,PREVIEW_READ_MAX_BYTES:Ze,ingestAttachment:rt,nativeImageResizer:nt,createSyncDispatch:st,registerModelIpc:lt,createHeartbeatRetry:ut,describeSyncError:be,HEARTBEAT_RETRY_BASE_MS:it,HEARTBEAT_RETRY_MAX_MS:at,createEngine:Je,resolveUserDataDir:Ye,importForeignMemory:je,isSafeExternalUrl:Pe,createUpdateManager:At,createNpmUpdateManager:St,createUpdateDispatch:Et,describeRegistryFailure:wt,UPDATE_RETRY_BACKOFF_MS:vt,registerUpdateIpc:Mt,buildAppMenu:Dt,createExportDispatch:He,registerExportIpc:Ge,safeExportBasename:We,sendDeepLinkToWindow:Ct,QUICK_PREFIX:G,QUICK_LAUNCHER_PUSH_CHANNEL:ie,createQuickLauncherDispatch:Qe,registerQuickLauncherIpc:Xe,createConfirmModeDispatch:Ne,createVaultBackendDispatch:Oe,withAutoRoundsSwitch:xe,createTelemetryDispatch:Fe,registerTelemetryIpc:ze,createCovenantDispatch:Ke,registerCovenantIpc:Ve,registerConfirmModeIpc:Ue,QUEUE_PREFIX:Q,QUEUE_PROGRESS_CHANNEL:ae,QUEUE_MAX_TASK_CHARS:ue,QUEUE_MAX_ROUNDS:le,createQueueEngine:ct,queueEngineWithDeniedApprovals:dt,createQueueDispatch:ft,registerQueueIpc:gt,AUTO_PREFIX:X,createAutoDispatch:mt,registerAutoIpc:ht};
4
+ const e=require("node:path"),t=require("node:fs"),{execFile:n}=require("node:child_process"),{pathToFileURL:r}=require("node:url");let o;try{o=require("../client/aegis.js")}catch{o=require("./vendor/aegis.js")}const{createClient:s}=o;let i,a,u,l,c,d,p,f;try{i=require("../client/credentials.js")}catch{i=require("./vendor/credentials.js")}try{a=require("../client/auto-provision.js")}catch{a=require("./vendor/auto-provision.js")}try{u=require("../client/presence.js")}catch{u=require("./vendor/presence.js")}try{l=require("../client/topup.js")}catch{l=require("./vendor/topup.js")}try{c=require("../client/google-signin.js")}catch{c=require("./vendor/google-signin.js")}try{d=require("../client/drive-connect.js")}catch{d=require("./vendor/drive-connect.js")}try{p=require("../client/drive-upload.js")}catch{p=require("./vendor/drive-upload.js")}try{f=require("../client/conversation-export.js")}catch{try{f=require("./vendor/conversation-export.js")}catch{f=null}}const{createGoogleConnect:m}=require("./lib/google-connect.js");let g;try{g=require("../client/device-fingerprint.js")}catch{g=require("./vendor/device-fingerprint.js")}const{createFingerprintService:h}=require("./lib/fingerprint.js"),{createAutoDrain:y,createAutoMint:k}=require("./lib/auto.js");let b=null;try{b=require("../client/env-file.js")}catch{try{b=require("./vendor/env-file.js")}catch{}}let v=null;try{v=require("electron")}catch{}const w=require("node:os"),{createLocalEngine:S}=require("./lib/local/engine.js"),{createAccountKey:A,startupKeyOverride:E}=require("./lib/account-key.js"),{createSettingsStore:M,isReservedNamespace:q}=require("./lib/settings.js"),_=require("./lib/sync/sessions.js"),C=require("./lib/sync/memory-queue.js"),D=require("./lib/sync/persist-gate.js"),j=require("./lib/avatar/store.js"),I=require("./lib/window-state.js"),$=require("./lib/deep-link.js"),P=require("./lib/quick-launcher.js");let R;try{R=require("../client/foreign-memory.js")}catch{R=require("./vendor/foreign-memory.js")}require("./lib/local/tools.js");const T=require("./lib/local/queue.js"),B=require("./lib/local/autonomous.js"),{autoContinuePlan:L,autoContinueLimit:N,autoRoundsDefault:x}=require("./lib/local/autonomous.js"),U=require("./lib/local/entitlement.js"),O=require("./lib/local/telemetry.js"),F=require("./lib/local/covenant.js"),{createTelemetry:K,telemetryEnabled:V}=O,z="aegis:",W="model:",H="sync:",G="quick:",Q="queue:",X="auto:",Y=Object.freeze(["aegis","byok","local"]),J=`${z}chatDelta`,Z=`${z}menuNewChat`,ee=`${z}menuSearch`,te=`${z}menuExportMarkdown`,ne=`${z}menuExportJson`,re=`${z}menuFingerprint`,oe=`${z}menuGoogleDrive`,se=`${z}deepLink`,ie=`${z}quickLauncherPush`,ae=`${Q}progress`,ue=8e3,le=200,ce=8,de=new Set(["low","medium","high","max"]);function pe(e,t){return{...e&&"object"==typeof e?e:{delta:e},id:t}}const fe=require("./package.json").version;function me(e){return e?e.length<=10?"configured":`${e.slice(0,9)}…${e.slice(-4)}`:null}function ge(e){const t=e&&e.status,n=e&&e.data||{},r="string"==typeof n.error?n.error:"";if(402!==t&&"free_session_limit_reached"!==r)return null;const o=null!=n.tokensUsed?n.tokensUsed:null!=n.sessionsUsed?n.sessionsUsed:null,s=null!=n.tokenLimit?n.tokenLimit:null!=n.freeSessionLimit?n.freeSessionLimit:null;return{url:n.upgradeUrl||"https://aegiscloud.org/go/upgrade?s=desktop&c=status_card",used:o,limit:s,code:r||"free_session_limit_reached"}}function he(e){return e&&e.message?e.message:String(e)}function ye(e){return!(!e||"object"!=typeof e||!0!==e.aegisCancelled&&"AbortError"!==e.name&&"ABORT_ERR"!==e.code)}function ke(e){return{aborted:!0,status:0,code:"ABORT_ERR",message:he(e),choices:[{message:{content:""}}]}}function be(e){const t=e&&(e.status||e.response&&e.response.status)||0,n=he(e);return ge(e)?{kind:"quota",status:t||402,message:n,hint:"the plan's synced-token ceiling is reached — free space in the account dashboard or upgrade to keep syncing"}:401===t?{kind:"auth",status:t,message:n,hint:"the memory token was refused — re-enter your AEGIS API key to exchange a new one"}:{kind:"error",status:t||null,message:n,hint:null}}function ve(e){return e?e.hint?`${e.message} — ${e.hint}`:e.message:"sync failed"}const{bankAmount:we,parseTopupAmount:Se,startTopup:Ae,createCreditWatch:Ee,TOPUP_POLL_MS:Me,TOPUP_POLL_TRIES:qe}=l;let _e=null;function Ce(e,t){const n=t||{},r=n.intervalMs||Me,o=n.log;_e&&clearInterval(_e);const s=Ee(e,n.maxTries?{maxTries:n.maxTries}:void 0),i=()=>{_e&&clearInterval(_e),_e=null,s.stop()},a=async()=>{const e=await s.tick();"credited"===e.state?(i(),(e=>{if("function"!=typeof n.notify)try{const t=v&&v.Notification;t&&t.isSupported()&&new t({title:"AEGIS Desktop",body:`Bank credited — €${e.toFixed(2)} available`}).show()}catch{}else n.notify(e)})(e.amount)):"expired"===e.state&&(i(),o&&o("top-up: no credit observed within the watch window; stopping"))};return _e=setInterval(a,r),_e&&"function"==typeof _e.unref&&_e.unref(),{stop:i,tick:a,get baseline(){return s.baseline}}}async function De(e){try{const t=await e,n=function(e){if(!e||"object"!=typeof e)return null;const t=null!=e.tokensUsed?e.tokensUsed:null,n=null!=e.tokenLimit?e.tokenLimit:null;return null==t||null==n||n<=0||t<n?null:{url:"https://aegiscloud.org/go/upgrade?s=desktop&c=memory_quota",used:t,limit:n,code:"sync_quota_reached"}}(t);return n?Object.assign({},t,{upgrade:n}):t}catch(e){const t=ge(e);if(!t)throw e;return{entries:[],upgrade:t}}}async function je(e,t,n,r){const o=n||{},s=R.scan({sources:o.sources,limit:o.limit||1e3}),i=R.describe(s),a=s.sources.map((e=>({id:e.id,label:e.label,verified:e.verified,present:e.present,count:e.count,skipped:e.skipped,files:e.files}))),u={summary:i,totals:s.totals,sources:a};if(!o.confirm||!s.entries.length)return{...u,ok:!0,dryRun:!o.confirm,saved:0,queued:0};let l=0,c=0;const d=[];let p=null;for(const n of R.chunk(s.entries,200))try{const t=await e.memorySaveBatch(n);if(l+=t&&t.saved||n.length,r&&n.length){const e=n[0]||{};r.awardImports(n,{source:e.session||e.source||"foreign-import"})}}catch(e){if(p=ge(e),!p&&t)for(const e of n)C.enqueue(t,e),c+=1,r&&r.awardQueued(e,{session:e&&e.session});d.push(he(e));break}return{...u,ok:0===d.length,dryRun:!1,saved:l,queued:c,upgrade:p,reason:d[0]||null}}function Ie(t,n,r){return t?e.join(n,"icons"):e.join(r,"build")}function $e(t,n){return"darwin"===n?e.join(t,"icon.icns"):"win32"===n?e.join(t,"icon.ico"):e.join(t,"icon.png")}function Pe(e){if("string"!=typeof e||!e)return!1;try{const t=new URL(e);return"http:"===t.protocol||"https:"===t.protocol}catch{return!1}}function Re(e){try{const t=e&&e.settings&&e.settings.list;return"function"==typeof t&&(t.call(e.settings)||[]).some((e=>{if(!e||!e.provider||q(e.provider))return!1;const t="string"==typeof e.baseURL?e.baseURL.trim():"";return Boolean(e.configured||t)}))}catch{return!1}}function Te(e,t,n,r,o,s,i){let a=null;const u=new Proxy({},{get(e,n){a||(a=h({dir:t,getVaultBackend:i}));const r=a[n];return"function"==typeof r?r.bind(a):r},has:(e,n)=>(a||(a=h({dir:t,getVaultBackend:i})),n in a)}),l=()=>{try{return Boolean("function"==typeof o&&o())}catch{return!1}},c=r||(()=>Promise.reject(new Error("no opener configured"))),d={status:()=>({appVersion:fe,clientVersion:e.clientVersion,apiBase:e.apiBase,keyConfigured:Boolean(e.apiKey),keyMask:me(e.apiKey),providerConfigured:l()}),setApiKey:t=>{try{const r=t&&t.key;return e.setApiKey(r||""),n&&n(e.apiKey),{ok:!0,keyConfigured:Boolean(e.apiKey),keyMask:me(e.apiKey)}}catch(e){return{ok:!1,error:e&&e.message||String(e)}}},verifyApiKey:async()=>{try{return{ok:!0,...await e.verifyApiKey()}}catch(e){return{ok:!1,error:e&&e.message||String(e)}}},tokenBankBalance:()=>e.tokenBankBalance(),billingCheckout:()=>async function(t){try{const t=await e.billingCheckout();return{ok:!0,url:t&&t.url||null,status:0,reason:null,setupRequired:!1,upgrade:null}}catch(e){const t=e&&e.data||{};return{ok:!1,url:null,status:e&&e.status||0,reason:he(e),setupRequired:Boolean(t.setup_required),upgrade:ge(e)}}}(),tokenBankTopup:async t=>{const n=Se(t&&t.amountEur);if(!n.ok)return{ok:!1,url:null,status:400,reason:n.message,setupRequired:!1,upgrade:null};const r=await Ae(e,n.amount);return!0===r.ok&&r.url&&Ce(e),{ok:!0===r.ok,url:r.url,status:r.status,reason:r.ok?null:r.hint?`${r.message} — ${r.hint}`:r.message,setupRequired:r.setupRequired,upgrade:null}},listModels:()=>e.listModels(),chatCompletion:t=>e.chatCompletion({prompt:t&&t.prompt,system:t&&t.system,model:t&&t.model,mode:t&&t.mode,maxTokens:t&&t.maxTokens,stream:t&&t.stream,onStream:t&&t.onStream}),fingerprintStatus:()=>u.status(),fingerprintKeygen:e=>u.keygen(e||{}),fingerprintMint:e=>u.mint(e||{}),fingerprintVerify:e=>u.verify(e||{}),fingerprintBackup:e=>u.backup(e||{}),fingerprintPublish:e=>u.publish(e||{}),fingerprintAnchor:e=>u.anchor(e||{}),fingerprintVault:()=>u.vaultList(),fingerprintVaultAudit:()=>u.vaultAudit(),byokStatus:()=>e.byokStatus(),byokSet:t=>e.byokSet(t&&t.provider,t&&t.apiKey),memorySearch:t=>De(e.memorySearch(t&&t.query,t&&t.limit)),memorySave:n=>async function(e,t,n,r){const o=j.normalizeMemoryEntry(n);try{const t=await e.memorySave(o);return r&&o&&"object"==typeof o&&r.awardSave(o,{session:o.session}),t}catch(e){const s=ge(e);if(s)return{ok:!1,queued:0,saved:0,upgrade:s,reason:he(e)};if(!t||!n)throw e;return C.enqueue(t,o),r&&o&&"object"==typeof o&&r.awardQueued(o,{session:o.session}),{ok:!0,queued:!0,reason:he(e)}}}(e,t,n&&n.entry,s),memoryList:t=>De(e.memoryList(t&&t.limit)),verifyToken:t=>e.verifyToken(t&&t.token),memoryActivate:t=>e.memoryActivate(t&&t.token),memoryPull:t=>e.memoryPull(t&&t.since),memorySaveBatch:t=>e.memorySaveBatch(t&&t.entries),memoryImport:n=>je(e,t,n,s),importConversation:t=>e.importConversation(t||{}),openExternal:e=>{const t=e&&e.url;return Pe(t)?Promise.resolve(c(t)).then((()=>({ok:!0})),(e=>({ok:!1,reason:he(e)}))):Promise.resolve({ok:!1,reason:"unsupported URL scheme"})}};return d}function Be(e,t,n){return n?e.then((e=>(n(t,e),e))):e}function Le(e,t,n,r,o,s,i,a){const u=Te(t,n,r,o,i,void 0,a);for(const[t,n]of Object.entries(u))"chatCompletion"!==t?e.handle(`${z}${t}`,((e,t)=>n(t))):e.handle(`${z}${t}`,((e,t)=>{const r={...t||{}};if(!r.stream)return Be(n(r),e,s);const o=e&&e.sender;return Be(n({...r,stream:!0,onStream:e=>{o&&"function"==typeof o.send&&!o.isDestroyed()&&o.send(J,pe(e,r.sessionId))}}),e,s)}));return u}function Ne(e){if(!e)throw new Error("createConfirmModeDispatch requires a settings store");return{getConfirmMode:()=>({enabled:e.getConfirmMode()}),setConfirmMode:t=>{const n=t&&t.enabled;return"boolean"!=typeof n?{enabled:e.getConfirmMode()}:{enabled:e.setConfirmMode(n)}}}}function xe(e,t){const n=e.setConfirmMode;return{...e,setConfirmMode:e=>{const r=n(e);return e&&"boolean"==typeof e.enabled&&t&&"function"==typeof t.setAutoRounds&&t.setAutoRounds(!1===e.enabled),r}}}function Ue(e,t){for(const[n,r]of Object.entries(t))e.handle(`${z}${n}`,((e,t)=>r(t)));return t}function Oe(e){if(!e)throw new Error("createVaultBackendDispatch requires a settings store");return{getVaultBackend:()=>e.vaultBackendConfig(),setVaultBackend:t=>e.setVaultBackendConfig(t&&t.backend)}}function Fe(e){const t=e||null;return{telemetryEvent:e=>{try{if(!t||"function"!=typeof t.record)return{ok:!1,reason:"telemetry off"};const n=e&&"object"==typeof e?e:{};return t.record(n.event,{campaign:n.campaign,surface:n.surface})?{ok:!0}:{ok:!1,reason:"not an allowlisted funnel event"}}catch(e){return{ok:!1,reason:he(e)}}},telemetryReport:()=>{try{return t&&"function"==typeof t.report?t.report():{enabled:!1,transport:"off"}}catch(e){return{enabled:!1,error:he(e)}}}}}function Ke(e){return{covenantStatus:()=>({ok:!0,covenant:e.snapshot(),gapReport:e.gapReport()}),covenantGapReport:()=>({ok:!0,gapReport:e.gapReport()})}}function Ve(e,t){for(const[n,r]of Object.entries(t))e.handle(`${z}${n}`,((e,t)=>r(t)));return t}function ze(e,t){for(const[n,r]of Object.entries(t))e.handle(`${z}${n}`,((e,t)=>r(t)));return t}function We(e){return(e&&(e.title||e.id)||"session").replace(/[^\w.-]+/g,"_").slice(0,80)||"session"}function He(e,t,n,r){return{exportSession:async o=>{const s=o&&o.sessionId,i=o&&"json"===o.format?"json":"markdown",a=s?e.getSession(t,s):null;if(!a)return{ok:!1,reason:"session not found"};const u="json"===i?e.toJson(a):e.toMarkdown(a),l="json"===i?"json":"md",c="json"===i?[{name:"JSON",extensions:["json"]}]:[{name:"Markdown",extensions:["md"]}],d=await n({defaultPath:`${We(a)}.${l}`,filters:c});if(!d||d.canceled||!d.filePath)return{ok:!1,canceled:!0};try{await r(d.filePath,u)}catch(e){return{ok:!1,reason:he(e)}}return{ok:!0,filePath:d.filePath}}}}function Ge(e,t,n,r,o){const s=He(t,n,r,o);for(const[t,n]of Object.entries(s))e.handle(`${z}${t}`,((e,t)=>n(t)));return s}function Qe(e,t={}){const n=Boolean(t.isPackaged),r=t.applyConfig||(()=>({active:!1,reason:null})),o=t.pushToMain||(()=>({ok:!1,reason:"no main window"}));let s={active:!1,reason:null};return{status:function(){return{...e.quickLauncherConfig(),packaged:n,...s}},setConfig:function(t){const o=e.setQuickLauncherConfig({enabled:t&&t.enabled,shortcut:t&&t.shortcut});return s=r(o)||{active:!1,reason:null},{...o,packaged:n,...s}},pushToMain:(e,t)=>o(e,t)}}function Xe(e,t){for(const[n,r]of Object.entries(t))"pushToMain"!==n?e.handle(`${G}${n}`,((e,t)=>r(t))):e.handle(`${G}${n}`,((e,t)=>r(t,e)));return t}function Ye(t){if(t&&"function"==typeof t.getPath)try{return t.getPath("userData")}catch{}return e.join(w.homedir(),".aegiscode")}function Je(e,{app:t,safeStorage:n,dir:r,sessionsDir:o}={}){const s=r||Ye(t),i=M({dir:s,safeStorage:n});return i.migrateLegacyAegisKey(),{engine:S({aegis:e,settings:i}),sessionsDir:o||_.resolveStoreDir(s),settingsDir:s,settings:i}}const Ze=524288;function et(n){try{const r=n&&"string"==typeof n.file?n.file:"",o=n&&"string"==typeof n.cwd?n.cwd:"";if(!r||!o||!e.isAbsolute(o))return null;const s=t.realpathSync(o),i=t.realpathSync(e.resolve(s,r)),a=e.relative(s,i);if(""===a||a.startsWith("..")||e.isAbsolute(a))return null;const u=t.statSync(i);if(!u.isFile())return null;if(u.size<=Ze)return{text:t.readFileSync(i,"utf8"),truncated:!1};const l=t.openSync(i,"r");try{const e=Buffer.alloc(Ze),n=t.readSync(l,e,0,Ze,0);let r=e.toString("utf8",0,n);const o=r.lastIndexOf("\n");return o>0&&(r=r.slice(0,o+1)),{text:r,truncated:!0}}finally{t.closeSync(l)}}catch{return null}}const tt=require("./lib/local/attachments.js");function nt(e,t){try{const{nativeImage:n}=require("electron");if(!n)return null;const r=n.createFromBuffer(e);if(!r||r.isEmpty())return null;const o=r.getSize(),s=Math.max(o.width,o.height),i=s>1568?r.resize({width:Math.round(1568*o.width/s)}):r,a="image/png"===t?i.toPNG():i.toJPEG(82);return a&&a.length?{buffer:a,mime:"image/png"===t?"image/png":"image/jpeg"}:null}catch{return null}}function rt(n,{resize:r=nt}={}){const o=n&&"string"==typeof n.path?n.path.trim():"";if(!o)return{ok:!1,reason:"no path"};if(!e.isAbsolute(o))return{ok:!1,reason:"not an absolute path"};let s,i,a;try{s=t.realpathSync(o),i=t.statSync(s)}catch{return{ok:!1,reason:"not found"}}if(!i.isFile())return{ok:!1,reason:"not a regular file"};if(0===i.size)return{ok:!1,reason:"empty file"};if(i.size>tt.MAX_FILE_BYTES)return{ok:!1,reason:`too large (${tt.humanBytes(i.size)})`};try{a=t.readFileSync(s)}catch{return{ok:!1,reason:"unreadable"}}const u=tt.sniff(a),l={path:s,name:e.basename(s),size:i.size,mime:u.mime,kind:u.kind};if("image"===u.kind){let{mime:e}=u,t=a,n=!1;if(t.length>tt.MAX_IMAGE_BYTES&&"function"==typeof r){const o=r(a,e);o&&o.buffer&&o.buffer.length<t.length&&(t=o.buffer,e=o.mime,n=!0)}const o=tt.toDataUrl(t,e);return o?{ok:!0,attachment:{...l,kind:"image",mime:e,size:t.length,dataUrl:o,scaled:n,vision:tt.isVisionMime(e)}}:{ok:!1,reason:"could not encode image"}}if("text"===u.kind){if(i.size>tt.MAX_TEXT_BYTES){let e=a.subarray(0,tt.MAX_TEXT_BYTES).toString("utf8");const t=e.lastIndexOf("\n");return t>0&&(e=e.slice(0,t+1)),{ok:!0,attachment:{...l,kind:"text",text:e,truncated:!0}}}return{ok:!0,attachment:{...l,kind:"text",text:a.toString("utf8"),truncated:!1}}}return"pdf"===u.kind?{ok:!0,attachment:{...l,kind:"pdf"}}:{ok:!0,attachment:{...l,kind:"binary"}}}function ot(e,{env:t=process.env,settings:n}={}){const r=new Map;let o,s=x(t),i=!1;const a=()=>{const t=n||e&&e.settings||null,r=e=>"boolean"==typeof e?e:void 0;let a;try{if(t&&"function"==typeof t.confirmModeState){const e=t.confirmModeState();a=r(e&&e.enabled)}void 0===a&&t&&"function"==typeof t.getConfirmMode&&(a=r(t.getConfirmMode()))}catch{}return i||void 0===a||(void 0===o?o=a:a!==o&&(i=!0,s=!0)),!(!s||!t||void 0===a)&&!1===a},u={listClasses:async()=>(await e.listClasses()).filter((e=>Y.includes(e.class))),listModels:t=>e.listModels(t&&t.class),chat:n=>{const o=n&&n.onStream;if("function"!=typeof o)return e.chat(n,o);const s=n&&n.sessionId||"";return e.chat(n,(n=>{if(n&&n.rounds&&n.rounds.id&&a()){const i=L({on:!0,used:r.get(s)||0,limit:N(t)});if(r.set(s,i.used),i.auto){const t="function"==typeof e.respondRoundsAsk?e.respondRoundsAsk(n.rounds.id,!0):{ok:!1};if(t&&t.ok){const e=Number(n.rounds.spent)||0;return void o({note:`auto mode: the ${e}-round limit was reached — continuing automatically (${i.used}/${i.cap}, then it asks).`})}}}o(n)}))},"settings.get":()=>e.settings.list().filter((e=>!(e&&q(e.provider)))),"settings.set":t=>e.settings.set(t&&t.provider,{baseURL:t&&t.baseURL,key:t&&t.key}),"settings.remove":t=>e.settings.remove(t&&t.provider),"userModels.get":()=>e.userModels(),"userModels.add":t=>e.addUserModel(t&&t.provider,t&&t.model),"userModels.remove":t=>e.removeUserModel(t&&t.provider,t&&t.model),"userModels.discover":t=>e.discoverModels(t&&t.provider),"userModels.addAll":t=>e.addUserModels(t&&t.provider,t&&t.ids),"userModels.canDiscover":t=>Boolean(e.canDiscoverModels(t&&t.provider)),"userModels.discoverable":()=>e.discoverableProviders(),"memoryPersist.get":()=>e.settings.memoryPersistState(),"memoryPersist.set":t=>e.settings.setMemoryPersist(Boolean(t&&t.enabled)),cancel:t=>e.cancel(t&&t.sessionId),respondApproval:t=>e.respondApproval(t&&t.approvalId,t&&t.decision),respondRoundsAsk:t=>"function"==typeof e.respondRoundsAsk?e.respondRoundsAsk(t&&t.roundsAskId,t&&t.decision):{ok:!1},clearApprovals:t=>e.clearSessionApprovals(t&&t.sessionId)};return Object.defineProperties(u,{autoRoundsOn:{value:a,enumerable:!1},setAutoRounds:{value:e=>{s=Boolean(e),i=!0},enumerable:!1}}),u}function st(e,t,n,r,o){let s=null;function i(){return Boolean(n&&n.apiKey)}async function a(){const r=e.listPending(t);if(!i())return{ok:!1,queued:r.length,reason:"no AEGIS key configured"};const o=await async function(){const e=C.listQueued(t);if(!e.length)return{flushed:0,remaining:0,upgrade:null};const r=[];let o=0,s=null;for(let t=0;t<e.length;t+=1)try{await n.memorySave(e[t]),o+=1}catch(n){const o=ge(n);if(o){s=o,r.push(...e.slice(t));break}r.push(e[t])}return C.save(t,r),{flushed:o,remaining:r.length,upgrade:s}}();if(!r.length)return{ok:!0,queued:0,pushed:0,memoryFlushed:o.flushed,upgrade:o.upgrade};let a=0,u=null,l=null;for(const o of r)try{const r=await n.conversationSyncPush({session_id:o.id,title:o.title,messages:o.messages}),s=r&&(r.session_id||r.id);e.markSynced(t,o.id,{remoteId:s}),a+=1}catch(e){if(u=e,l=be(e),"quota"===l.kind||"auth"===l.kind)break}const c=e.listPending(t).length;a&&(s=Date.now());const d=(u?ge(u):null)||o.upgrade;return 0===a&&u?{ok:!1,queued:c,reason:ve(l),failed:l?[l]:[],kind:l?l.kind:"error",status:l?l.status:0,hint:l?l.hint:null,memoryFlushed:o.flushed,upgrade:d}:{ok:!0,queued:c,pushed:a,failed:l?[l]:[],memoryFlushed:o.flushed,upgrade:d}}const u=D.createAutoPush({push:a,dir:r||t});return{auto:()=>u.auto(),memoryPersistState:()=>u.gate(),listSessions:()=>({sessions:e.listSessions(t)}),open:n=>e.getSession(t,n&&n.sessionId),save:n=>e.upsertSession(t,n||{}),append:n=>e.appendMessage(t,n&&n.sessionId,n&&n.message),delete:n=>e.deleteSession(t,n&&n.sessionId),nameSession:async n=>{const r=n&&n.sessionId,s=n&&n.prompt;if(!r||!String(null==s?"":s).trim())return null;let i;for(const e of["../client/naming.js","./vendor/naming.js","./vendor/client/naming.js"])try{i=require(e);break}catch{}if(!i)return null;const a=async(e,t={})=>{if(!o||"function"!=typeof o.chat)return null;try{const s=await o.chat({class:n&&n.class||"model",model:n&&n.model,prompt:e,system:t.system,maxTokens:64,sessionId:r,tools:!1}),i=s&&s.choices&&s.choices[0]||{};return i.message&&i.message.content||null}catch{return null}};try{return await i.nameSession(e,t,r,s,{callModel:a})}catch{return null}},push:a,pull:async function(){if(!i())return{ok:!1,merged:0,reason:"no AEGIS key configured"};try{const r=await n.conversationSyncPull(),o=e.mergeRemoteSessions(t,r&&r.sessions||[]);return s=Date.now(),{ok:!0,merged:o,failed:[],upgrade:null}}catch(e){const t=be(e);return{ok:!1,merged:0,reason:ve(t),failed:[t],kind:t.kind,status:t.status,hint:t.hint,upgrade:ge(e)}}},status:()=>({count:e.listSessions(t).length,pending:e.listPending(t).length,cloud:i(),lastSyncAt:s})}}const it=5e3,at=3e4;function ut(e,t={}){const n="function"==typeof t.now?t.now:()=>Date.now(),r=Number(t.baseMs)>0?Number(t.baseMs):it,o=Number(t.maxMs)>0?Number(t.maxMs):at;let s=0,i=0,a=null,u=!1;function l(e){s+=1;const t=Math.min(o,r*2**Math.max(0,s-1));return a=e||"push failed",i=n()+t,{attempted:!0,ok:!1,error:a,failures:s,retryInMs:t}}return{run:async function(){const t=n();if(s>0&&t<i)return{attempted:!1,ok:!1,error:a,failures:s,retryInMs:i-t};if(u)return{attempted:!1,ok:!1,error:a,failures:s,retryInMs:0};u=!0;try{const t=await e();return t&&!1===t.ok?l(t.reason||t.kind||"push failed"):(s=0,i=0,a=null,{attempted:!0,ok:!0,error:null,failures:0,retryInMs:0,result:t})}catch(e){return l(he(e))}finally{u=!1}},state:function(){const e=n();return{failures:s,lastError:a,retryInMs:s>0&&i>e?i-e:0}},recordFailure:e=>l(he(e))}}function lt(e,t,n,r,o,s,i){const a=ot(t),u=st(_,n,r,i,a),l=ut((()=>u.push()),s);function c(){const e=l.run();e&&"function"==typeof e.catch&&e.catch((e=>l.recordFailure(e)))}for(const[t,n]of Object.entries(a))"chat"!==t?"listModels"!==t?e.handle(`${W}${t}`,((e,t)=>n(t))):e.handle(`${W}${t}`,((e,t)=>(c(),n(t)))):e.handle(`${W}${t}`,((e,t)=>{const r={...t||{}},s=!0===r.bestEffort;delete r.bestEffort;const i="low"===r.effort||"medium"===r.effort||"max"===r.effort?r.effort:"high";r.effort=i;const a=e&&e.sender,u=r.class||"model",l=n({...r,onStream:e=>{a&&"function"==typeof a.send&&!a.isDestroyed()&&a.send(J,pe(e,r.sessionId))}});return s?l.then((t=>(o&&o(e,t),t)),(e=>{const t=e&&"number"==typeof e.status?e.status:0,n=e&&e.code||"";return console.warn(`[model] background ${u} turn produced no answer: ${he(e)}${t?` (status ${t})`:""}${n?` [${n}]`:""}`),{bestEffortFailed:!0,status:t,code:n||void 0,message:he(e),choices:[{message:{content:""}}]}})):Be(l,e,o).catch((e=>{if(!ye(e))throw e;return console.warn(`[model] ${u} turn stopped before it finished: ${he(e)} [ABORT_ERR]`),ke(e)}))}));e.on(`${W}readTextFile`,((e,t)=>{e.returnValue=et(t)})),e.handle(`${z}attachments:ingest`,(async(e,t)=>rt(t)));for(const[t,n]of Object.entries(u))"status"!==t?e.handle(`${H}${t}`,((e,t)=>n(t))):e.handle(`${H}${t}`,((e,t)=>{c();const r=n(t);return r&&"object"==typeof r?{...r,retry:l.state()}:r}));return{modelDispatch:a,syncDispatch:u,heartbeat:l}}function ct(e,t){return S({aegis:e,settings:t,getConfirmMode:()=>!1})}function dt(e){return e&&"function"==typeof e.chat?{...e,chat:(t,n)=>e.chat(t,(t=>{(t=>{const n=t&&t.approval;if(n&&n.id&&"function"==typeof e.respondApproval)try{e.respondApproval(n.id,"deny")}catch{}})(t),(t=>{const n=t&&t.rounds;if(n&&n.id&&"function"==typeof e.respondRoundsAsk)try{e.respondRoundsAsk(n.id,!1)}catch{}})(t),"function"==typeof n&&n(t)}))}:e}function pt(e,t,n){const r=Number(e);return!Number.isInteger(r)||r<t||r>n?null:r}function ft({engine:n,env:r=process.env,queue:o=T,autonomous:s=B,entitlement:i=U.createEntitlement({}),log:a=(()=>{})}={}){if(!n||"function"!=typeof n.chat)throw new Error("createQueueDispatch: a local engine with chat() is required");let u=null,l=!1,c=!1;const d=s.createQueueWorker({engine:dt(n),env:r,log:e=>{e&&"start"===e.type&&(u=e.taskId),e&&"finish"===e.type&&(u=null),a(e)},canFanOut:()=>i.current().entitled});function p(){const e=o.loadQueue(r);return{ok:!0,items:e,pending:o.pendingCount(e),running:e.find((e=>e&&"running"===e.status))||null,draining:c,stopping:l,defaultCwd:process.cwd(),defaultModel:s.resolveModel({env:r}),queueFile:o.queuePath(r),runs:o.readRuns(r,{limit:20}),entitlement:i.current()}}const f=e=>(e||[]).map((e=>({id:e.id,ok:Boolean(e.ok),error:e.error||null})));return{enqueue:async n=>{await i.refresh();const a=i.gateFanout({workers:pt(n&&n.workers,1,ce),fanout:Boolean(n&&!0===n.fanout)});if(!a.ok)return{...a,...p()};const{opts:u,error:l}=function(n){const r=n||{},o=String(null==r.task?"":r.task).trim();if(!o)return{error:"a queued task needs text"};if(o.length>ue)return{error:`task text is too long (${o.length} > ${ue} chars)`};const i=String(null==r.cwd?"":r.cwd).trim()||process.cwd();if(!e.isAbsolute(i))return{error:"the working directory must be an absolute path"};if(!function(e){try{return t.statSync(e).isDirectory()}catch{return!1}}(i))return{error:`not a directory: ${i}`};const a=s.normalizeClass(r.class),u=String(null==r.model?"":r.model).trim().slice(0,120)||null,l=s.modelRefusal(u,a);if(l)return{error:l};const c=String(null==r.effort?"":r.effort).trim().toLowerCase();return{opts:{task:o,cwd:i,class:a,model:u,effort:de.has(c)?c:null,workers:pt(r.workers,1,ce),maxRounds:pt(r.maxRounds,1,le),singlePass:!(!0===r.fanout||!0===r.autonomous),commit:Boolean(r.commit),source:"desktop"}}}(n);return l?{ok:!1,reason:l,...p()}:{ok:!0,item:o.addTask(r,u),...p()}},list:()=>p(),entitlement:async e=>(await i.refresh({force:Boolean(e&&!0===e.force)}),{ok:!0,...p()}),clear:e=>({...o.clearQueue(r,{all:Boolean(e&&e.all)}),ok:!0,...p()}),retry:e=>{const t=e&&e.id,n=o.retryTask(r,t);return n?{ok:!0,item:n,...p()}:{ok:!1,reason:`no task #${t}`,...p()}},remove:e=>{const t=e&&e.id,n=o.loadQueue(r),s=o.findTask(n,t);return s?"running"===s.status?{ok:!1,reason:`task #${s.id} is running — stop the drain first`,...p()}:(o.saveQueue(r,n.filter((e=>Number(e&&e.id)!==Number(s.id)))),{ok:!0,removed:s.id,...p()}):{ok:!1,reason:`no task #${t}`,...p()}},drain:()=>async function(){if(c)return{ok:!1,reason:"a drain is already running in this window",...p()};let e;c=!0,l=!1;try{const t=await d.proceed({max:1});e=t.locked?{ok:!1,locked:!0,holder:t.holder,ran:[]}:{ok:!0,ran:f(t.ran)}}catch(t){e={ok:!1,reason:he(t),ran:[]}}return c=!1,u=null,{...e,...p()}}(),proceed:()=>async function(){if(c)return{ok:!1,reason:"a drain is already running in this window",...p()};c=!0,l=!1;const e=[];let t;try{for(;;){const n=await d.proceed({max:1});if(n.locked){t={ok:!1,locked:!0,holder:n.holder,ran:f(e)};break}if(!n.ran.length){t={ok:!0,stopped:l,ran:f(e)};break}if(e.push(...n.ran),l){t={ok:!0,stopped:!0,ran:f(e)};break}}}catch(n){t={ok:!1,reason:he(n),ran:f(e)}}return c=!1,u=null,{...t,...p()}}(),stop:e=>{l=!0;const t=e&&null!=e.id?e.id:u,n=null==t?null:d.cancel(t);return{ok:!0,wasDraining:c,cancelled:n,...p()}}}}function mt({autoDrain:e,autoMint:t}={}){if(!e||"function"!=typeof e.state)throw new Error("createAutoDispatch: the auto-drain automation is required");if(!t||"function"!=typeof t.state)throw new Error("createAutoDispatch: the auto-mint automation is required");return{autoStatus:()=>({ok:!0,drain:e.state(),mint:t.state()}),autoSetDrain:t=>{const n=t||{},r={};null!=n.enabled&&(r.enabled=Boolean(n.enabled)),null!=n.intervalMs&&(r.intervalMs=Number(n.intervalMs));try{return{ok:!0,drain:e.set(r)}}catch(e){return{ok:!1,error:he(e)}}},autoSetMint:e=>{const n=e||{},r={};null!=n.enabled&&(r.enabled=Boolean(n.enabled)),null!=n.publish&&(r.publish=Boolean(n.publish));try{return{ok:!0,mint:t.set(r)}}catch(e){return{ok:!1,error:he(e)}}},autoSealNow:async e=>{const n=e||{};null!=n.publish&&t.set({publish:Boolean(n.publish)});try{const e=await t.flush();return t.reset(),{ok:!0,...e}}catch(e){return t.reset(),{ok:!1,error:he(e)}}}}}function gt(e,{engine:t,env:n,queue:r,autonomous:o,entitlement:s,aegis:i}={}){let a=null;const u=ft({engine:t,env:n,queue:r,autonomous:o,entitlement:s||U.createEntitlement({probe:i&&"function"==typeof i.verifyApiKey?async()=>{const e=await i.verifyApiKey(),t=e&&"object"==typeof e?{...e}:{};if("function"==typeof i.tokenBankBalance)try{const e=await i.tokenBankBalance();e&&"object"==typeof e&&(null!=e.balance_micros?t.balance_micros=e.balance_micros:null!=e.balance_eur&&(t.balance_eur=e.balance_eur))}catch{}return t}:void 0}),log:e=>{a&&"function"==typeof a.send&&("function"==typeof a.isDestroyed&&a.isDestroyed()||a.send(ae,e))}});for(const[t,n]of Object.entries(u))e.handle(`${Q}${t}`,((e,t)=>(a=e&&e.sender||null,n(t))));return u}function ht(e,t){for(const[n,r]of Object.entries(t))e.handle(`${X}${n}`,((e,t)=>r(t)));return t}const yt=`${z}updateStatus`,kt=`${z}accountStatusChanged`,bt=144e5,vt=[6e4,3e5,9e5,36e5];function wt(e,t,n){switch(e){case"not-found":return`${n} is not published on the npm registry (404)`;case"forbidden":return`the npm registry refused the request (${t||"auth"})`;case"malformed":return"the npm registry sent a response this app could not read";case"too-large":return"the npm registry response was too large to read";case"timeout":return"the npm registry did not respond in time";case"network":return"the npm registry could not be reached";default:return"the update check did not complete"}}function St({onStatus:r,packaged:o=!1,now:s=(()=>Date.now()),fetchImpl:i,setTimeoutImpl:a=setTimeout,clearTimeoutImpl:u=clearTimeout,runUpgrade:l,relaunch:c}={}){const d="aegis-desktop";let p="unknown";try{p=require("./package.json").version}catch{}let f={status:"idle",version:null,error:null,channel:"npm",reason:null,transient:!1,attempts:0,retryInMs:0,command:null,plan:null,method:null,canDownload:!1};const m=e=>(f={...f,...e},r&&r(f),f);let g=null;try{g=require("../client/update.js")}catch{try{g=require("./vendor/update.js")}catch{g=null}}let h=0,y=0,k=null,b=null,v=null,w=null;function S(){k&&u(k),k=null}async function A({announce:n=!1}={}){if(!g)return m({status:"disabled",error:"update checker unavailable"});if(b)return b;b=(async()=>{const r=f.status,u=f.version;let l;m({status:"checking",error:null,reason:null,transient:!1});try{l=await async function(){if(i)return i({pkg:d});if(g&&"function"==typeof g.checkPublished){const e=await g.checkPublished({current:p,pkg:d,now:s(),intervalMs:0});return e?{ok:e.ok,latest:e.latest,reason:e.reason,status:e.status}:{ok:!1,latest:null,reason:"unknown",status:null}}return{ok:!1,latest:null,reason:"unavailable",status:null}}()}catch(e){l={ok:!1,latest:null,reason:"unknown",status:null,error:he(e)}}if(l.ok){if(h=0,y=0,S(),!g.isNewer(l.latest,p))return m({status:"up-to-date",version:l.latest,error:null,reason:null,transient:!1,attempts:0,retryInMs:0});const n=function(){if(w)return w;const n=g&&g.detectInstallMethod;if("function"!=typeof n)return w="npm",w;try{w=n({env:process.env,argv:process.argv,pkg:d,entry:__dirname,fileExists:n=>t.existsSync(e.resolve(__dirname,"..",n))})}catch{w="npm"}return w}(),r="function"==typeof g.updatePlan?g.updatePlan({current:p,latest:l.latest,behind:!0,channel:"npm",pkg:d,method:n}):null;return m({status:"available",version:l.latest,error:null,reason:null,transient:!1,attempts:0,retryInMs:0,plan:r,method:n,command:o?`${l.latest} is published — reinstall AEGIS Desktop from the installer to pick it up`:r&&r.instruction||`npm i -g ${d}@latest`,commandIsSentence:o||Boolean(r&&!r.apply),canDownload:Boolean(r&&r.apply)&&!o})}h+=1;const c=l.error||wt(l.reason,l.status,d);return b=l.reason,v=l.status,("function"==typeof g.isTransientReason?g.isTransientReason(b,v):"unknown"===b)?(function(){S();const e=vt[Math.min(Math.max(h-1,0),vt.length-1)];y=s()+e,k=a((()=>{k=null,A().catch((()=>{}))}),e),k&&k.unref&&k.unref(),m({retryInMs:e})}(),m(n?{status:"error",error:c,reason:l.reason,transient:!0,attempts:h}:{status:"available"===r?"available":"unavailable",version:u,error:c,reason:l.reason,transient:!0,attempts:h})):(S(),y=0,m({status:"error",error:c,reason:l.reason,transient:!1,attempts:h,retryInMs:0}));var b,v})();try{return await b}finally{b=null}}return{status:()=>f,check:A,download:async()=>{const e=!o&&f.plan&&f.plan.apply;if(!e)return m({status:"available"===f.status?"available":f.status,command:f.plan&&f.plan.instruction||f.command,canDownload:!1});m({status:"downloading",error:null,progress:0});const t=await function(e){const t=l||((e,t)=>new Promise((r=>{n(e,t,{timeout:18e4,windowsHide:!0},((e,t,n)=>{if(e)return r({ok:!1,output:String(n||t||e.message||e)});r({ok:!0,output:String(t||"")})}))}))),r=!l&&g&&"function"==typeof g.installSpawn?g.installSpawn(e,{env:process.env}):null,o=r?r.command:e.command,s=r?r.args:e.args;return Promise.resolve(t(o,s)).then((e=>({ok:Boolean(e&&e.ok),output:String(e&&e.output||"")})),(e=>({ok:!1,output:he(e)})))}(e);return t.ok?m({status:"downloaded",version:f.version,error:null,progress:100,command:`npm i -g ${d}@latest`,canDownload:!1}):m({status:"error",transient:!1,error:t.output.trim().split("\n").slice(-3).join(" ").trim()||"the installer failed",command:`${e.command} ${e.args.join(" ")}`})},quitAndInstall:()=>{"downloaded"===f.status&&(c||(()=>{try{const{app:e}=require("electron");e.relaunch(),e.exit(0)}catch{}}))()},start:()=>{A().catch((()=>{})),v=setInterval((()=>A().catch((()=>{}))),bt),v.unref&&v.unref()},stop:()=>{S(),v&&clearInterval(v),v=null},retryState:()=>({attempts:h,retryAt:y,inFlight:!!b,hasTimer:!!k})}}function At({isPackaged:e,onStatus:t}){let n={status:"idle",version:null,error:null,canDownload:!1};return St({onStatus:function(e){n={...n,...e},t&&t(n)},packaged:Boolean(e)})}function Et(e){return{checkForUpdates:()=>e.check({announce:!0}),downloadUpdate:()=>e.download(),quitAndInstallUpdate:()=>(e.quitAndInstall(),{ok:!0}),updateStatus:()=>Promise.resolve(e.status())}}function Mt(e,t){const n=Et(t);for(const[t,r]of Object.entries(n))e.handle(`${z}${t}`,((e,t)=>r(t)));return n}let qt=null;function _t(e,t){const n="function"==typeof qt?qt():null,r=n&&!n.isDestroyed()?n:e.getFocusedWindow()||e.getAllWindows()[0];r&&!r.isDestroyed()&&r.webContents.send(t)}function Ct(e,t){if(!e||e.isDestroyed()||!t)return;const n=()=>{e.isDestroyed()||e.webContents.send(se,t)};e.webContents.isLoadingMainFrame()?e.webContents.once("did-finish-load",n):n()}function Dt({app:e,Menu:t,BrowserWindow:n,updateManager:r,loggedIn:o}){const s="darwin"===process.platform;e.setAboutPanelOptions({applicationName:e.getName(),applicationVersion:e.getVersion(),version:e.getVersion()});const i={label:"Check for Updates…",click:()=>r.check({announce:!0})},a={label:"New Chat",accelerator:"CmdOrCtrl+N",click:()=>_t(n,Z)},u={label:"Search…",accelerator:"CmdOrCtrl+K",click:()=>_t(n,ee)},l={label:"Save as…",accelerator:"CmdOrCtrl+S",click:()=>_t(n,te)},c={label:"Export Session…",click:()=>_t(n,ne)},d={label:"Authorship Panel…",click:()=>_t(n,re)},p={label:"Google Drive Backup…",enabled:Boolean(o),click:()=>_t(n,oe)},f=[...s?[{label:e.getName(),submenu:[{role:"about"},i,{type:"separator"},{role:"services"},{type:"separator"},{role:"hide"},{role:"hideOthers"},{role:"unhide"},{type:"separator"},{role:"quit"}]}]:[],{label:"File",submenu:[a,{type:"separator"},l,c,{type:"separator"},...s?[]:[i,{type:"separator"}],s?{role:"close"}:{role:"quit"}]},{label:"Edit",submenu:[{role:"undo"},{role:"redo"},{type:"separator"},{role:"cut"},{role:"copy"},{role:"paste"},{role:"selectAll"}]},{label:"View",submenu:[u,{type:"separator"},d,p,{type:"separator"},{role:"reload",accelerator:"CmdOrCtrl+R"},{role:"forceReload"},{type:"separator"},{role:"toggleDevTools",accelerator:"CmdOrCtrl+Shift+I"}]},...s?[]:[{label:"Help",submenu:[{role:"about"}]}]];return t.buildFromTemplate(f)}v&&v.app&&function(){let n=!1;try{n=require("./lib/local/integrity.js").armed()}catch{n=!0,process.env.AEGIS_REDUCED_MODE="1",process.stderr.write("aegis-desktop: reduced mode (d1) — this build is not the one that was published.\n")}if(n){try{const{app:e}=v;e&&"function"==typeof e.quit&&e.quit()}catch{}return}const{app:o,BrowserWindow:l,ipcMain:w,safeStorage:S,shell:M,Menu:q,Notification:C,screen:D,dialog:j,globalShortcut:R}=v;if(o.disableHardwareAcceleration(),o.commandLine.appendSwitch("disable-gpu"),o.commandLine.appendSwitch("disable-software-rasterizer"),o.commandLine.appendSwitch("disable-gpu-compositing"),o.commandLine.appendSwitch("disable-features","UsePortalAccentColor"),process.argv.some((e=>/^--(log-level|enable-logging)/.test(e)))||process.env.ELECTRON_ENABLE_LOGGING||o.commandLine.appendSwitch("log-level","3"),!o.requestSingleInstanceLock())return void o.quit();if(o.setName("AEGIS Desktop"),b&&"function"==typeof b.loadEnvFile)try{const e=b.loadEnvFile();e.loose&&console.warn(`aegis: ${e.file} is readable by other accounts (mode ${e.mode.toString(8)}) — consider \`chmod 600\` on it.`)}catch(e){console.warn(`aegis: could not read ${b.envFileFor()}: ${e&&e.message}`)}o.setAsDefaultProtocolClient($.PROTOCOL);let B=$.parseDeepLinkArgv(process.argv);o.on("open-url",((e,t)=>{e.preventDefault();const n=$.parseDeepLinkUrl(t);if(!n)return;const r="function"==typeof qt?qt():null;r&&!r.isDestroyed()?Ct(r,n):B=n}));const L=s(i.clientOptions()),N=Ye(o),{engine:x,sessionsDir:U,settingsDir:O,settings:W}=Je(L,{app:o,safeStorage:S,dir:N}),H=A({aegis:L,credentials:i,persistKey:e=>W.setAegisKey(e),provision:(e,t)=>a.autoProvisionApiKey(e,t,{app:"desktop"}),describeFailure:a.provisionFailureText,onChange:e=>fe(e)});let G=null;const Q=m({aegis:L,credentials:i,persistKey:e=>W.setAegisKey(e),openUrl:e=>!!Pe(e)&&(M.openExternal(e),!0),googleSignIn:c,driveConnect:d,driveUpload:p,conversationExport:f?{...f,toTranscript:e=>_.toMarkdown(e)}:null,getSession:e=>_.getSession(U,e),getAuthor:()=>{try{G||(G=h({dir:N,getVaultBackend:()=>W.vaultBackendConfig().backend}));const e=G.status();return e&&e.ok?e:null}catch{return null}},onAccountChange:()=>fe(H.status())}),X=Boolean(L.apiKey),Y=a.autoProvisionApiKey(L,i,{app:"desktop"}).then((e=>{if(H.recordStartup(e),!e.key&&!L.apiKey){const t=e.error&&(e.error.status||e.error.message||String(e.error))||"no key returned";console.warn(`auto-provision: no account key from register-device (${t})`)}return e}));try{const{wrapProviderKeyMirror:e}=require("./lib/provider-key-mirror.js"),t=e=>console.warn(`aegis: ${e}`);e(W,b,{onWarn:t}),x&&x.settings&&x.settings!==W&&e(x.settings,b,{onWarn:t})}catch(e){console.warn(`aegis: could not wire the shared env-file key mirror: ${e&&e.message}`)}let J=null;const Z=(e,t)=>{if(function(e){const t=e&&e.sender,n=t&&l.fromWebContents(t);if(!n||n.isDestroyed())return;if(n.isFocused()&&n.isVisible())return;if(!C||!C.isSupported())return;const r=new C({title:"AEGIS Desktop",body:"Reply ready"});r.on("click",(()=>{n.isDestroyed()||(n.isMinimized()&&n.restore(),n.isVisible()||n.show(),n.focus())})),r.show()}(e),J&&"function"==typeof J.note){const e=t&&(t.model||t.modelId)||void 0;J.note({sessionId:t&&t.sessionId||null,model:e})}};Le(w,L,N,(e=>{const t=W.setAegisKey(e);return e?i.saveApiKey(e):i.clearApiKey(),t}),(e=>M.openExternal(e)),Z,(()=>Re(x)),(()=>W.vaultBackendConfig().backend));const ee=lt(w,x,U,L,Z,void 0,O);Ue(w,xe(Ne(W),ee.modelDispatch)),Ue(w,Oe(W)),ze(w,Fe(K({dir:O,enabled:V(process.env,W),appVersion:(()=>{try{return"function"==typeof o.getVersion?o.getVersion():""}catch{return""}})()}))),Ve(w,Ke(F));const te=gt(w,{engine:ct(L,W),aegis:L}),ne=y({proceed:()=>te.proceed(),settings:W,queue:T,env:process.env,log:e=>{e&&"skip"!==e.type&&console.log("[auto-drain]",e.type,e.reason||e.error||"")}});let re=null;J=k({mint:e=>(re||(re=h({dir:N,getVaultBackend:()=>W.vaultBackendConfig().backend})),re.mint(e||{})),settings:W}),ht(w,mt({autoDrain:ne,autoMint:J})),ne.start(),J.start();let oe=null,se=null;function ae(){return se&&!se.isDestroyed()||(se=new l({width:560,height:320,show:!1,frame:!1,alwaysOnTop:!0,skipTaskbar:!0,resizable:!1,movable:!0,fullscreenable:!1,minimizable:!1,maximizable:!1,backgroundColor:"#0d1117",icon:$e(Ie(o.isPackaged,process.resourcesPath,__dirname),process.platform),webPreferences:{preload:e.join(__dirname,"preload.js"),contextIsolation:!0,nodeIntegration:!1,sandbox:!0}}),se.setMenuBarVisibility(!1),se.loadFile(e.join(__dirname,"renderer","quick.html")),se.webContents.on("before-input-event",((e,t)=>{"keyDown"!==t.type||"Escape"!==t.key||se.isDestroyed()||se.hide()})),se.on("blur",(()=>{!se.isDestroyed()&&se.isVisible()&&se.hide()})),se.on("closed",(()=>{se=null}))),se}function ue(){const e=ae();e.isVisible()?e.hide():function(){const e=ae(),t=D.getCursorScreenPoint(),n=D.getAllDisplays(),r=e.getBounds(),o=P.computeQuickLauncherBounds({cursor:t,displays:n,size:{width:r.width,height:r.height}});e.setBounds(o),e.show(),e.focus()}()}qt=()=>{if(oe&&!oe.isDestroyed())return oe;const e=l.getFocusedWindow();return e&&!e.isDestroyed()&&e!==se?e:l.getAllWindows().find((e=>e!==se))||null};const le=Qe(W,{isPackaged:o.isPackaged,applyConfig:function(e){if(R.unregisterAll(),!P.shouldEnableGlobalShortcut({isPackaged:o.isPackaged,enabled:e.enabled}))return{active:!1,reason:null};try{if(!R.register(e.shortcut,ue)){const t=`"${e.shortcut}" could not be registered — it may already be in use by another application.`;return console.warn(`[quick-launcher] ${t}`),{active:!1,reason:t}}return{active:!0,reason:null}}catch(t){const n=he(t);return console.warn(`[quick-launcher] failed to register shortcut "${e.shortcut}": ${n}`),{active:!1,reason:n}}},pushToMain:function(e,t){const n=t&&t.sender&&l.fromWebContents(t.sender);n&&!n.isDestroyed()&&n.hide();const r=oe&&!oe.isDestroyed()?oe:l.getAllWindows().find((e=>e!==n))||null;return r?(r.webContents.send(ie,e||{}),r.isMinimized()&&r.restore(),r.isVisible()||r.show(),r.focus(),{ok:!0}):{ok:!1,reason:"no main window is open"}}});Xe(w,le);let ce=null;o.on("will-quit",(()=>{ce&&"function"==typeof ce.stop&&ce.stop(),R.unregisterAll(),ge&&"function"==typeof ge.stop&&ge.stop()}));let de=!1;o.on("before-quit",(e=>{!de&&x&&"function"==typeof x.unloadLocalModels&&(e.preventDefault(),Promise.resolve().then((()=>x.unloadLocalModels())).catch((()=>{})).finally((()=>{de=!0,o.quit()})))}));const pe=new Set;function fe(e){for(const t of pe)t.isDestroyed()||t.webContents.send(kt,e);me()}function me(){q.setApplicationMenu(Dt({app:o,Menu:q,BrowserWindow:l,updateManager:ge,loggedIn:Boolean(L.apiKey)}))}const ge=At({isPackaged:o.isPackaged,onStatus:function(e){for(const t of pe)t.isDestroyed()||t.webContents.send(yt,e)}});Mt(w,ge),w.handle(`${z}accountStatus`,(()=>H.status())),w.handle(`${z}registerAccount`,(()=>H.registerAccount())),w.handle(`${z}driveSignIn`,(()=>Q.signInWithGoogle())),w.handle(`${z}driveConnect`,(()=>Q.connectDrive())),w.handle(`${z}driveStatus`,(()=>Q.status())),w.handle(`${z}driveSyncMemory`,(()=>Q.syncMemoryNow())),w.handle(`${z}driveBackupConversation`,((e,t)=>Q.backupConversation({sessionId:t&&t.sessionId}))),Ge(w,_,U,(e=>j.showSaveDialog(l.getFocusedWindow(),e)),((e,n)=>t.promises.writeFile(e,n,"utf8"))),me();const ye=r(e.join(__dirname,"renderer","index.html")).href;function ke(){const t=I.load(N),n=I.clampToDisplay(t,D.getAllDisplays(),{width:1080,height:720}),r=Ie(o.isPackaged,process.resourcesPath,__dirname),s=new l({...n,minWidth:720,minHeight:480,show:!0,backgroundColor:"#0d1117",title:"AEGIS Desktop",icon:$e(r,process.platform),webPreferences:{preload:e.join(__dirname,"preload.js"),contextIsolation:!0,nodeIntegration:!1,sandbox:!0,spellcheck:!0}});t&&t.isMaximized&&s.maximize(),s.webContents.setWindowOpenHandler((({url:e})=>(Pe(e)&&M.openExternal(e),{action:"deny"}))),s.webContents.on("will-navigate",((e,t)=>{t!==ye&&(e.preventDefault(),Pe(t)&&M.openExternal(t))}));let i=null;function a(){if(s.isDestroyed())return;const e=s.isMaximized(),t=e?s.getNormalBounds():s.getBounds();I.save(N,{...t,isMaximized:e})}function u(){i&&clearTimeout(i),i=setTimeout(a,500)}return s.on("resize",u),s.on("move",u),s.on("close",(()=>{i&&clearTimeout(i),a()})),s.loadFile(e.join(__dirname,"renderer","index.html")),pe.add(s),oe=s,s.on("closed",(()=>{pe.delete(s),oe===s&&(oe=null)})),s}o.whenReady().then((async()=>{if(!i.normalizeApiKey(process.env[i.KEY_ENV])){const e=await Y,t=E({mintedKey:X?"":e.key,hostKey:i.normalizeApiKey(W.aegisRawKey())});if(t)i.saveApiKey(t),L.setApiKey(t);else{const e=i.preferNewest(W.aegisRawKey(),W.aegisKeySavedAt());e.key&&(L.setApiKey(e.key),"shared"===e.source&&W.setAegisKey(e.key))}}try{ce&&"function"==typeof ce.stop&&ce.stop(),ce=u.createPresence({apiKey:L.apiKey,app:"desktop",version:o.getVersion(),platform:process.platform,install:g.machineFingerprint(),queueDepth:()=>{try{return T.readQueue(T.queuePath()).filter((e=>e&&"pending"===e.status)).length}catch{return 0}},autonomous:!1,log:(e,t)=>{"debug"!==e&&console.warn(t)}}),ce.start()}catch(e){console.warn("presence: beacon not started",e&&e.message)}try{const{backfillProviderKeys:e}=require("./lib/provider-key-mirror.js"),t=e=>console.warn(`aegis: ${e}`),n=e(W,b,{onWarn:t});n.mirrored.length&&console.warn(`aegis: shared ${n.mirrored.join(", ")} key(s) with the other hosts (${b.envFileFor()})`),x&&x.settings&&x.settings!==W&&e(x.settings,b,{onWarn:t})}catch(e){console.warn(`aegis: could not backfill the shared env-file key mirror: ${e&&e.message}`)}le.setConfig(W.quickLauncherConfig());const e=ke();ge.start(),B&&Ct(e,B)})),o.on("window-all-closed",(()=>{"darwin"!==process.platform&&o.quit()})),o.on("activate",(()=>{const e=l.getAllWindows();if(0===e.length)return void ke();const t=qt()||e[0];t.isMinimized()&&t.restore(),t.isVisible()||t.show(),t.focus()})),o.on("second-instance",((e,t)=>{const n=qt(),r=$.parseDeepLinkArgv(t);if(n)n.isMinimized()&&n.restore(),n.isVisible()||n.show(),n.focus(),r&&Ct(n,r);else{const e=ke();r&&Ct(e,r)}}))}(),module.exports={createIpcDispatch:Te,registerIpc:Le,providerRouteConfigured:Re,IPC_PREFIX:z,MODEL_PREFIX:W,SYNC_PREFIX:H,watchTopupCredit:Ce,bankAmount:we,TOPUP_POLL_MS:Me,TOPUP_POLL_TRIES:qe,CHAT_DELTA_CHANNEL:J,MENU_NEW_CHAT_CHANNEL:Z,MENU_SEARCH_CHANNEL:ee,MENU_EXPORT_MARKDOWN_CHANNEL:te,MENU_EXPORT_JSON_CHANNEL:ne,MENU_FINGERPRINT_CHANNEL:re,MENU_GOOGLE_DRIVE_CHANNEL:oe,DEEP_LINK_CHANNEL:se,UPDATE_STATUS_CHANNEL:yt,UPDATE_CHECK_INTERVAL_MS:bt,taggedChunk:pe,maskKey:me,createModelDispatch:ot,DESKTOP_CLASSES:Y,readTextFileForPreview:et,PREVIEW_READ_MAX_BYTES:Ze,ingestAttachment:rt,nativeImageResizer:nt,createSyncDispatch:st,registerModelIpc:lt,createHeartbeatRetry:ut,describeSyncError:be,HEARTBEAT_RETRY_BASE_MS:it,HEARTBEAT_RETRY_MAX_MS:at,createEngine:Je,resolveUserDataDir:Ye,importForeignMemory:je,isSafeExternalUrl:Pe,createUpdateManager:At,createNpmUpdateManager:St,createUpdateDispatch:Et,describeRegistryFailure:wt,UPDATE_RETRY_BACKOFF_MS:vt,registerUpdateIpc:Mt,buildAppMenu:Dt,createExportDispatch:He,registerExportIpc:Ge,safeExportBasename:We,sendDeepLinkToWindow:Ct,QUICK_PREFIX:G,QUICK_LAUNCHER_PUSH_CHANNEL:ie,createQuickLauncherDispatch:Qe,registerQuickLauncherIpc:Xe,createConfirmModeDispatch:Ne,createVaultBackendDispatch:Oe,withAutoRoundsSwitch:xe,createTelemetryDispatch:Fe,registerTelemetryIpc:ze,createCovenantDispatch:Ke,registerCovenantIpc:Ve,registerConfirmModeIpc:Ue,QUEUE_PREFIX:Q,QUEUE_PROGRESS_CHANNEL:ae,QUEUE_MAX_TASK_CHARS:ue,QUEUE_MAX_ROUNDS:le,createQueueEngine:ct,queueEngineWithDeniedApprovals:dt,createQueueDispatch:ft,registerQueueIpc:gt,AUTO_PREFIX:X,createAutoDispatch:mt,registerAutoIpc:ht};
@@ -1 +1 @@
1
- "use strict";const fs=require("node:fs"),path=require("node:path"),{TARGETS:TARGETS,getTarget:getTarget,appConfig:appConfig}=require("./targets.js"),{buildSpec:buildSpec,resolveServer:resolveServer}=require("./spec.js");function hostCtx(e={}){return{env:process.env,platform:process.platform,home:null,cwd:process.cwd(),...e}}function readText(e){try{return{text:fs.readFileSync(e,"utf8"),exists:!0}}catch(e){if("ENOENT"===e.code)return{text:null,exists:!1};throw e}}function isFile(e){try{return fs.statSync(e).isFile()}catch{return!1}}function parseJson(e,t){if(null===e||""===e.trim())return{};try{return JSON.parse(e)}catch(e){throw new Error(`${t} is not valid JSON (${e.message}) — refusing to overwrite it`)}}function setPath(e,t,r){const n=t.split(".");let s=e;for(const e of n.slice(0,-1))(null===s[e]||"object"!=typeof s[e]||Array.isArray(s[e]))&&(s[e]={}),s=s[e];return s[n[n.length-1]]=r,e}function getPath(e,t){let r=e;for(const e of t.split(".")){if(null===r||"object"!=typeof r)return;r=r[e]}return r}function delPath(e,t,r=!1){const n=t.split("."),s=[];let o=e;for(const t of n.slice(0,-1)){if(null===o||"object"!=typeof o)return e;s.push([o,t]),o=o[t]}if(o&&"object"==typeof o&&delete o[n[n.length-1]],!r)return e;for(let e=s.length-1;e>=0;e--){const[t,r]=s[e],n=t[r];if(!n||"object"!=typeof n||0!==Object.keys(n).length)break;delete t[r]}return e}const TOML_BARE=/^[A-Za-z0-9_-]+$/;function tomlKey(e){return TOML_BARE.test(e)?e:JSON.stringify(e)}function tomlString(e){return JSON.stringify(String(e))}function tomlArray(e){return`[${e.map(tomlString).join(", ")}]`}function tomlHeaderName(e){const t=e.trim();return/^\[/.test(t)?t.replace(/^\[+\s*/,"").replace(/\s*\]+$/,""):null}function ownedTomlHeader(e,t){const r=tomlHeaderName(e);return null!==r&&(r===t||r.startsWith(`${t}.`))}function upsertTomlSection(e,t,r){const n=`[${t}]`,s=(e||"").split("\n"),o=[];let i=!1,a=0;for(;a<s.length;)if(s[a].trim()!==n)o.push(s[a]),a++;else{for(o.push(n,...r,""),i=!0,a++;a<s.length&&!/^\s*\[/.test(s[a]);)a++;for(;a<s.length&&ownedTomlHeader(s[a],t);)for(a++;a<s.length&&!/^\s*\[/.test(s[a]);)a++}if(!i){for(;o.length&&""===o[o.length-1].trim();)o.pop();o.length&&o.push(""),o.push(n,...r,"")}return o.join("\n")}function removeTomlSection(e,t){const r=`[${t}]`,n=(e||"").split("\n"),s=[];let o=0;for(;o<n.length;)if(n[o].trim()!==r)s.push(n[o]),o++;else{for(o++;o<n.length&&!/^\s*\[/.test(n[o]);)o++;for(;o<n.length&&ownedTomlHeader(n[o],t);)for(o++;o<n.length&&!/^\s*\[/.test(n[o]);)o++}return s.join("\n")}function renderEntry(e,t){if("mcp-toml"===e.kind){const r=[`# Added by \`aegiscode mcp install ${e.id}\`. Key resolution lives in`,"# ~/.aegiscode/.env and the 0600 store `aegiscode login` writes.","command = "+tomlString(t.command),"args = "+tomlArray(t.args)];if(t.env&&Object.keys(t.env).length){r.push("",`[${e.container}.${t.name}.env]`);for(const[e,n]of Object.entries(t.env))r.push(`${tomlKey(e)} = ${tomlString(n)}`)}return r}return e.entry(t)}function planTarget(e,t,r={}){const n=r.ctx||hostCtx(),s=r.spec||buildSpec(r.specOpts||{}),o=e.path(t,n),i={target:e,scope:t,file:o,exists:!1,changed:!1,before:null,after:null,error:null,backupOf:null};let a,c=null;try{const e=readText(o);c=e.text,i.exists=e.exists}catch(e){return i.error=e,i}if(i.exists)try{i.mode=511&fs.statSync(o).mode}catch{}if("mcp-toml"===e.kind){const t=`${e.container}.${s.name}`,r=renderEntry(e,s);return i.before=c,i.after=upsertTomlSection(c,t,r),i.changed=i.after!==(c||""),i}try{a=parseJson(c,o)}catch(e){return i.error=e,i}if(null===a||"object"!=typeof a||Array.isArray(a))return i.error=new Error(`${o} does not contain a JSON object — refusing to overwrite it`),i;if(setPath(a,`${e.container}.${s.name}`,renderEntry(e,s)),"function"==typeof e.extras){const t=e.extras(s);if(t&&t.inputs){const e=Array.isArray(a.inputs)?a.inputs:[];for(const r of t.inputs){const t=e.findIndex((e=>e&&e.id===r.id));-1===t?e.push(r):e[t]=r}a.inputs=e}}return i.before=c,i.after=JSON.stringify(a,null,2)+"\n",i.changed=i.after!==(c||""),i}function planRemove(e,t,r={}){const n=r.ctx||hostCtx(),s=r.spec||buildSpec(r.specOpts||{}),o=e.path(t,n),i={target:e,scope:t,file:o,exists:!1,changed:!1,before:null,after:null,error:null,backupOf:null};let a,c=null;try{const e=readText(o);c=e.text,i.exists=e.exists}catch(e){return i.error=e,i}if(!i.exists)return i;try{i.mode=511&fs.statSync(o).mode}catch{}if("mcp-toml"===e.kind)return i.before=c,i.after=removeTomlSection(c,`${e.container}.${s.name}`),i.changed=i.after!==c,i;try{a=parseJson(c,o)}catch(e){return i.error=e,i}const l=`${e.container}.${s.name}`,u=void 0!==getPath(a,l),f=Array.isArray(a.inputs)&&a.inputs.some((e=>e&&"aegis-api-key"===e.id));if(!u&&!f)return i.before=c,i.after=c,i.changed=!1,i;delPath(a,l,!0);const p=Array.isArray(a.inputs)?a.inputs.filter((e=>!(e&&"aegis-api-key"===e.id))):null;return p&&(p.length?a.inputs=p:delete a.inputs),i.before=c,i.after=JSON.stringify(a,null,2)+"\n",i.changed=i.after!==c,i}function modeFor(e){return e.withKey?384:e.mode||420}function apply(e,t={}){if(e.error)return{...e,applied:!1};if(!e.changed)return{...e,applied:!1};if(t.dryRun)return{...e,applied:!1,dryRun:!0};if(e.withKey=Boolean(t.withKey),fs.mkdirSync(path.dirname(e.file),{recursive:!0}),e.exists&&null!==e.before){const t=`${e.file}.aegis-backup-${Date.now()}`;fs.writeFileSync(t,e.before,{mode:384}),e.backupOf=t}const r=`${e.file}.aegis-tmp-${process.pid}`;try{fs.writeFileSync(r,e.after,{mode:384}),fs.renameSync(r,e.file),fs.chmodSync(e.file,modeFor(e))}finally{try{fs.unlinkSync(r)}catch{}}return{...e,applied:!0}}function parseTomlEntry(e,t){if(!e)return null;const r=t.replace(/[.[\]*+?^$(){}|]/g,"\\$&"),n=new RegExp("^\\s*\\["+r+"\\]\\s*$","m").exec(e);if(!n)return null;const s=e.slice(n.index+n[0].length).split("\n"),o=[];let i=0;for(;i<s.length&&(!/^\s*\[/.test(s[i])||ownedTomlHeader(s[i],t));)o.push(s[i]),i++;const a={command:null,args:[],env:{}},c=/^\s*command\s*=\s*"((?:[^"\\]|\\.)*)"/m.exec(o.join("\n"));c&&(a.command=JSON.parse('"'+c[1]+'"'));const l=/^\s*args\s*=\s*\[([\s\S]*?)\]/m.exec(o.join("\n"));l&&(a.args=[...l[1].matchAll(/"((?:[^"\\]|\\.)*)"/g)].map((e=>JSON.parse('"'+e[1]+'"'))));for(const e of o.join("\n").matchAll(/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*"((?:[^"\\]|\\.)*)"\s*$/gm))"command"!==e[1]&&"args"!==e[1]&&(a.env[e[1]]=JSON.parse('"'+e[2]+'"'));return a}function entryServerPath(e){return e&&(Array.isArray(e.args)?e.args:[]).find((e=>"string"==typeof e&&/\.(js|mjs|cjs)$/.test(e)))||null}const HOST_VAR_RE=/\$\{?[A-Za-z_][A-Za-z0-9_]*\}?|%[A-Za-z_][A-Za-z0-9_]*%/;function hasHostVar(e){return"string"==typeof e&&HOST_VAR_RE.test(e)}function status(e,t={}){const r=t.ctx||hostCtx(),n=t.spec||buildSpec(t.specOpts||{}),s=e&&e.length?e.map((e=>getTarget(e))).filter(Boolean):TARGETS,o=[];for(const e of s)for(const t of e.scopes||["user"]){const s=e.path(t,r),i={id:e.id,label:e.label,scope:t,file:s,exists:!1,installed:!1,entry:null,error:null,docs:e.docs,verified:e.verified};let a;try{a=readText(s)}catch(e){i.error=e.message,o.push(i);continue}if(i.exists=a.exists,a.exists&&null!==a.text)if("mcp-toml"===e.kind)i.entry=parseTomlEntry(a.text,`${e.container}.${n.name}`),i.installed=Boolean(i.entry);else try{const t=parseJson(a.text,s);i.entry=getPath(t,`${e.container}.${n.name}`)||null,i.installed=Boolean(i.entry)}catch(e){i.error=e.message}i.installed&&(i.serverPath=entryServerPath(i.entry),i.serverUnverifiable=hasHostVar(i.serverPath),i.serverExists=i.serverPath&&!i.serverUnverifiable?isFile(i.serverPath):null),o.push(i)}return o}function detected(e={}){const t=e.ctx||hostCtx(),r=new Set;for(const e of TARGETS)for(const n of e.scopes||["user"])try{fs.accessSync(e.path(n,t)),r.add(e.id)}catch{}for(const[e,n]of[["Code","vscode"],["Code - Insiders","vscode-insiders"],["VSCodium","vscodium"],["Cursor","cursor"]])try{fs.accessSync(path.join(appConfig(t),e)),r.add(n)}catch{}for(const[e,n]of[[[".codeium"],"windsurf"],[[".gemini"],"gemini"],[[".codex"],"codex"],[[".continue"],"continue"],[[".junie"],"junie"],[[".cursor"],"cursor"]])try{fs.accessSync(path.join(t.home||t.env.HOME||t.env.USERPROFILE,...e)),r.add(n)}catch{}return r}module.exports={hostCtx:hostCtx,planTarget:planTarget,planRemove:planRemove,apply:apply,status:status,detected:detected,renderEntry:renderEntry,entryServerPath:entryServerPath,hasHostVar:hasHostVar,parseTomlEntry:parseTomlEntry,upsertTomlSection:upsertTomlSection,removeTomlSection:removeTomlSection,setPath:setPath,getPath:getPath,delPath:delPath,readText:readText,resolveServer:resolveServer};
1
+ "use strict";const fs=require("node:fs"),path=require("node:path"),{TARGETS:TARGETS,getTarget:getTarget,appConfig:appConfig}=require("./targets.js"),{buildSpec:buildSpec,resolveServer:resolveServer}=require("./spec.js");function hostCtx(e={}){return{env:process.env,platform:process.platform,home:null,cwd:process.cwd(),...e}}function readText(e){try{return{text:fs.readFileSync(e,"utf8"),exists:!0}}catch(e){if("ENOENT"===e.code)return{text:null,exists:!1};throw e}}function isFile(e){try{return fs.statSync(e).isFile()}catch{return!1}}function parseJson(e,t){if(null===e||""===e.trim())return{};try{return JSON.parse(e)}catch(e){throw new Error(`${t} is not valid JSON (${e.message}) — refusing to overwrite it`)}}function setPath(e,t,r){const n=t.split(".");let s=e;for(const e of n.slice(0,-1))(null===s[e]||"object"!=typeof s[e]||Array.isArray(s[e]))&&(s[e]={}),s=s[e];return s[n[n.length-1]]=r,e}function getPath(e,t){let r=e;for(const e of t.split(".")){if(null===r||"object"!=typeof r)return;r=r[e]}return r}function delPath(e,t,r=!1){const n=t.split("."),s=[];let o=e;for(const t of n.slice(0,-1)){if(null===o||"object"!=typeof o)return e;s.push([o,t]),o=o[t]}if(o&&"object"==typeof o&&delete o[n[n.length-1]],!r)return e;for(let e=s.length-1;e>=0;e--){const[t,r]=s[e],n=t[r];if(!n||"object"!=typeof n||0!==Object.keys(n).length)break;delete t[r]}return e}const TOML_BARE=/^[A-Za-z0-9_-]+$/;function tomlKey(e){return TOML_BARE.test(e)?e:JSON.stringify(e)}function tomlString(e){return JSON.stringify(String(e))}function tomlArray(e){return`[${e.map(tomlString).join(", ")}]`}function tomlHeaderName(e){const t=e.trim();return/^\[/.test(t)?t.replace(/^\[+\s*/,"").replace(/\s*\]+$/,""):null}function ownedTomlHeader(e,t){const r=tomlHeaderName(e);return null!==r&&(r===t||r.startsWith(`${t}.`))}function upsertTomlSection(e,t,r){const n=`[${t}]`,s=(e||"").split("\n"),o=[];let i=!1,a=0;for(;a<s.length;)if(s[a].trim()!==n)o.push(s[a]),a++;else{for(o.push(n,...r,""),i=!0,a++;a<s.length&&!/^\s*\[/.test(s[a]);)a++;for(;a<s.length&&ownedTomlHeader(s[a],t);)for(a++;a<s.length&&!/^\s*\[/.test(s[a]);)a++}if(!i){for(;o.length&&""===o[o.length-1].trim();)o.pop();o.length&&o.push(""),o.push(n,...r,"")}return o.join("\n")}function removeTomlSection(e,t){const r=`[${t}]`,n=(e||"").split("\n"),s=[];let o=0;for(;o<n.length;)if(n[o].trim()!==r)s.push(n[o]),o++;else{for(o++;o<n.length&&!/^\s*\[/.test(n[o]);)o++;for(;o<n.length&&ownedTomlHeader(n[o],t);)for(o++;o<n.length&&!/^\s*\[/.test(n[o]);)o++}return s.join("\n")}function renderEntry(e,t){if("mcp-toml"===e.kind){const r=[`# Added by \`aegiscode mcp install ${e.id}\`. Key resolution lives in`,"# ~/.aegiscode/.env and the 0600 store `aegiscode login` writes.","command = "+tomlString(t.command),"args = "+tomlArray(t.args)];if(t.env&&Object.keys(t.env).length){r.push("",`[${e.container}.${t.name}.env]`);for(const[e,n]of Object.entries(t.env))r.push(`${tomlKey(e)} = ${tomlString(n)}`)}return r}return e.entry(t)}function planTarget(e,t,r={}){const n=r.ctx||hostCtx(),s=r.spec||buildSpec(r.specOpts||{}),o=e.path(t,n),i={target:e,scope:t,file:o,exists:!1,changed:!1,before:null,after:null,error:null,backupOf:null};let a,c=null;try{const e=readText(o);c=e.text,i.exists=e.exists}catch(e){return i.error=e,i}if(i.exists)try{i.mode=511&fs.statSync(o).mode}catch{}if("mcp-toml"===e.kind){const t=`${e.container}.${s.name}`,r=renderEntry(e,s);return i.before=c,i.after=upsertTomlSection(c,t,r),i.changed=i.after!==(c||""),i}try{a=parseJson(c,o)}catch(e){return i.error=e,i}if(null===a||"object"!=typeof a||Array.isArray(a))return i.error=new Error(`${o} does not contain a JSON object — refusing to overwrite it`),i;if(setPath(a,`${e.container}.${s.name}`,renderEntry(e,s)),"function"==typeof e.extras){const t=e.extras(s);if(t&&t.inputs){const e=Array.isArray(a.inputs)?a.inputs:[];for(const r of t.inputs){const t=e.findIndex((e=>e&&e.id===r.id));-1===t?e.push(r):e[t]=r}a.inputs=e}}return i.before=c,i.after=JSON.stringify(a,null,2)+"\n",i.changed=i.after!==(c||""),i}function planRemove(e,t,r={}){const n=r.ctx||hostCtx(),s=r.spec||buildSpec(r.specOpts||{}),o=e.path(t,n),i={target:e,scope:t,file:o,exists:!1,changed:!1,before:null,after:null,error:null,backupOf:null};let a,c=null;try{const e=readText(o);c=e.text,i.exists=e.exists}catch(e){return i.error=e,i}if(!i.exists)return i;try{i.mode=511&fs.statSync(o).mode}catch{}if("mcp-toml"===e.kind)return i.before=c,i.after=removeTomlSection(c,`${e.container}.${s.name}`),i.changed=i.after!==c,i;try{a=parseJson(c,o)}catch(e){return i.error=e,i}const l=`${e.container}.${s.name}`,u=void 0!==getPath(a,l),f=Array.isArray(a.inputs)&&a.inputs.some((e=>e&&"aegis-api-key"===e.id));if(!u&&!f)return i.before=c,i.after=c,i.changed=!1,i;delPath(a,l,!0);const p=Array.isArray(a.inputs)?a.inputs.filter((e=>!(e&&"aegis-api-key"===e.id))):null;return p&&(p.length?a.inputs=p:delete a.inputs),i.before=c,i.after=JSON.stringify(a,null,2)+"\n",i.changed=i.after!==c,i}function modeFor(e){return e.withKey?384:e.mode||420}function apply(e,t={}){if(e.error)return{...e,applied:!1};if(!e.changed)return{...e,applied:!1};if(t.dryRun)return{...e,applied:!1,dryRun:!0};if(e.withKey=Boolean(t.withKey),fs.mkdirSync(path.dirname(e.file),{recursive:!0}),e.exists&&null!==e.before){const t=`${e.file}.aegis-backup-${Date.now()}`;fs.writeFileSync(t,e.before,{mode:384}),e.backupOf=t}const r=`${e.file}.aegis-tmp-${process.pid}`;try{fs.writeFileSync(r,e.after,{mode:384}),fs.renameSync(r,e.file),fs.chmodSync(e.file,modeFor(e))}finally{try{fs.unlinkSync(r)}catch{}}return{...e,applied:!0}}function parseTomlEntry(e,t){if(!e)return null;const r=t.replace(/[.[\]*+?^$(){}|]/g,"\\$&"),n=new RegExp("^\\s*\\["+r+"\\]\\s*$","m").exec(e);if(!n)return null;const s=e.slice(n.index+n[0].length).split("\n"),o=[];let i=0;for(;i<s.length&&(!/^\s*\[/.test(s[i])||ownedTomlHeader(s[i],t));)o.push(s[i]),i++;const a={command:null,args:[],env:{}},c=/^\s*command\s*=\s*"((?:[^"\\]|\\.)*)"/m.exec(o.join("\n"));c&&(a.command=JSON.parse('"'+c[1]+'"'));const l=/^\s*args\s*=\s*\[([\s\S]*?)\]/m.exec(o.join("\n"));l&&(a.args=[...l[1].matchAll(/"((?:[^"\\]|\\.)*)"/g)].map((e=>JSON.parse('"'+e[1]+'"'))));for(const e of o.join("\n").matchAll(/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*"((?:[^"\\]|\\.)*)"\s*$/gm))"command"!==e[1]&&"args"!==e[1]&&(a.env[e[1]]=JSON.parse('"'+e[2]+'"'));return a}function entryServerPath(e){return e&&(Array.isArray(e.args)?e.args:[]).find((e=>"string"==typeof e&&/\.(js|mjs|cjs)$/.test(e)))||null}const HOST_VAR_RE=/\$\{?[A-Za-z_][A-Za-z0-9_]*\}?|%[A-Za-z_][A-Za-z0-9_]*%/;function hasHostVar(e){return"string"==typeof e&&HOST_VAR_RE.test(e)}function status(e,t={}){const r=t.ctx||hostCtx(),n=t.spec||buildSpec(t.specOpts||{}),s=e&&e.length?e.map((e=>getTarget(e))).filter(Boolean):TARGETS,o=[];for(const t of s)for(const s of t.scopes||["user"]){const i=t.path(s,r),a={id:t.id,label:t.label,scope:s,file:i,exists:!1,installed:!1,entry:null,error:null,docs:t.docs,verified:t.verified};let c;try{c=readText(i)}catch(e){a.error=e.message,o.push(a);continue}if(a.exists=c.exists,c.exists&&null!==c.text)if("mcp-toml"===t.kind)a.entry=parseTomlEntry(c.text,`${t.container}.${n.name}`),a.installed=Boolean(a.entry);else try{const e=parseJson(c.text,i);a.entry=getPath(e,`${t.container}.${n.name}`)||null,a.installed=Boolean(a.entry)}catch(e){a.error=e.message}a.installed&&(a.serverPath=entryServerPath(a.entry),a.serverUnverifiable=hasHostVar(a.serverPath),a.serverExists=a.serverPath&&!a.serverUnverifiable?isFile(a.serverPath):null),o.push(a)}return o}function detected(e={}){const t=e.ctx||hostCtx(),r=new Set;for(const e of TARGETS)for(const n of e.scopes||["user"])try{fs.accessSync(e.path(n,t)),r.add(e.id)}catch{}for(const[e,n]of[["Code","vscode"],["Code - Insiders","vscode-insiders"],["VSCodium","vscodium"],["Cursor","cursor"]])try{fs.accessSync(path.join(appConfig(t),e)),r.add(n)}catch{}for(const[e,n]of[[[".codeium"],"windsurf"],[[".gemini"],"gemini"],[[".codex"],"codex"],[[".continue"],"continue"],[[".junie"],"junie"],[[".cursor"],"cursor"]])try{fs.accessSync(path.join(t.home||t.env.HOME||t.env.USERPROFILE,...e)),r.add(n)}catch{}return r}module.exports={hostCtx:hostCtx,planTarget:planTarget,planRemove:planRemove,apply:apply,status:status,detected:detected,renderEntry:renderEntry,entryServerPath:entryServerPath,hasHostVar:hasHostVar,parseTomlEntry:parseTomlEntry,upsertTomlSection:upsertTomlSection,removeTomlSection:removeTomlSection,setPath:setPath,getPath:getPath,delPath:delPath,readText:readText,resolveServer:resolveServer};
@@ -1,4 +1,4 @@
1
1
  #!/usr/bin/env node
2
2
  // SPDX-License-Identifier: AGPL-3.0-or-later
3
3
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
4
- const{createClient:e}=require("../client/aegis.js"),t=require("../client/credentials.js"),{autoProvisionApiKey:o}=require("../client/auto-provision.js"),{createTools:i}=require("./tools.js");try{const e=require("../client/env-file.js").loadEnvFile();e.loose&&process.stderr.write(`aegis: ${e.file} is readable by other accounts (mode ${e.mode.toString(8)}) — consider \`chmod 600\` on it.\n`)}catch{}const n=e(t.clientOptions()),{TOOLS:r,toolList:s}=i(n);function a(){const{path:e}=t.keyStatus();return["No AEGIS API key is configured for this session.","","Set one with any of:"," • `aegiscode login` in a terminal (saves it to "+e+", mode 0600)"," • export AEGIS_API_KEY=… in the environment Claude Code was launched from"," • put `AEGIS_API_KEY=…` in ~/.aegiscode/.env (read at startup, every host)","","Then restart Claude Code. Get a key at https://aegiscloud.org."].join("\n")}n.apiBase;let c=!1;function l(e){process.stdout.write(JSON.stringify(e)+"\n")}function u(e,t){l({jsonrpc:"2.0",id:e,result:t})}function d(e,t,o){l({jsonrpc:"2.0",id:e,error:{code:t,message:o}})}let p=0,f=!1;function y(){f&&0===p&&process.exit(0)}async function g(e){const{id:i,method:l,params:p}=e,f=null==i;try{switch(l){case"initialize":return void u(i,{protocolVersion:p&&p.protocolVersion||"2024-11-05",capabilities:{tools:{}},serverInfo:{name:"aegis",version:"0.4.0"}});case"notifications/initialized":case"notifications/cancelled":return;case"ping":return void(f||u(i,{}));case"tools/list":return void u(i,{tools:s()});case"tools/call":{const e=p&&p.name,s=r[e];if(!s)return void u(i,{content:[{type:"text",text:`Unknown tool: ${e}`}],isError:!0});if(n.apiKey||await async function(){if(n.apiKey||c)return;c=!0;const e=await o(n,t,{app:"mcp"});e.error?process.stderr.write(`aegis: device auto-registration failed (${e.error.message}) — falling back to manual setup.\n`):e.key?process.stderr.write("aegis: no API key was configured — auto-provisioned a free AEGIS account"+(e.ok?` (key saved to ${t.keyStatus().path}).\n`:" (could not save it — see above).\n")+`Fund it at ${n.promptUrl("topup","device_autoprovision")} or set your own BYOK key with aegis_byok_set.\n`):process.stderr.write("aegis: device auto-registration returned no usable key — falling back to manual setup.\n")}(),!n.apiKey)return void u(i,{content:[{type:"text",text:a()}],isError:!0});try{u(i,{content:[{type:"text",text:await s.run(p&&p.arguments||{})}],isError:!1})}catch(e){u(i,{content:[{type:"text",text:`AEGIS error: ${e.message}`}],isError:!0})}return}default:return void(f||d(i,-32601,`Method not found: ${l}`))}}catch(e){f||d(i,-32603,e.message)}}let v="";process.stdin.setEncoding("utf8"),process.stdin.on("data",(e=>{let t;for(v+=e;-1!==(t=v.indexOf("\n"));){const e=v.slice(0,t).trim();if(v=v.slice(t+1),!e)continue;let o;try{o=JSON.parse(e)}catch{continue}p++,Promise.resolve(g(o)).finally((()=>{p--,y()}))}})),process.stdin.on("end",(()=>{f=!0,y()}));
4
+ const{createClient:e}=require("../client/aegis.js"),t=require("../client/credentials.js"),{autoProvisionApiKey:o}=require("../client/auto-provision.js"),{createTools:i}=require("./tools.js");try{const e=require("../client/env-file.js").loadEnvFile();e.loose&&process.stderr.write(`aegis: ${e.file} is readable by other accounts (mode ${e.mode.toString(8)}) — consider \`chmod 600\` on it.\n`)}catch{}const n=e(t.clientOptions()),{TOOLS:r,toolList:s}=i(n);function a(){const{path:e}=t.keyStatus();return["No AEGIS API key is configured for this session.","","Set one with any of:"," • `aegiscode login` in a terminal (saves it to "+e+", mode 0600)"," • export AEGIS_API_KEY=… in the environment Claude Code was launched from"," • put `AEGIS_API_KEY=…` in ~/.aegiscode/.env (read at startup, every host)","","Then restart Claude Code. Get a key at https://aegiscloud.org."].join("\n")}n.apiBase;let c=!1;function l(e){process.stdout.write(JSON.stringify(e)+"\n")}function u(e,t){l({jsonrpc:"2.0",id:e,result:t})}function d(e,t,o){l({jsonrpc:"2.0",id:e,error:{code:t,message:o}})}let p=0,f=!1;function y(){f&&0===p&&process.exit(0)}async function g(e){const{id:i,method:l,params:p}=e,f=null==i;try{switch(l){case"initialize":return void u(i,{protocolVersion:p&&p.protocolVersion||"2024-11-05",capabilities:{tools:{}},serverInfo:{name:"aegis",version:"0.4.0"}});case"notifications/initialized":case"notifications/cancelled":return;case"ping":return void(f||u(i,{}));case"tools/list":return void u(i,{tools:s()});case"tools/call":{const s=p&&p.name,l=r[s];if(!l)return void u(i,{content:[{type:"text",text:`Unknown tool: ${s}`}],isError:!0});if(n.apiKey||await async function(){if(n.apiKey||c)return;c=!0;const e=await o(n,t,{app:"mcp"});e.error?process.stderr.write(`aegis: device auto-registration failed (${e.error.message}) — falling back to manual setup.\n`):e.key?process.stderr.write("aegis: no API key was configured — auto-provisioned a free AEGIS account"+(e.ok?` (key saved to ${t.keyStatus().path}).\n`:" (could not save it — see above).\n")+`Fund it at ${n.promptUrl("topup","device_autoprovision")} or set your own BYOK key with aegis_byok_set.\n`):process.stderr.write("aegis: device auto-registration returned no usable key — falling back to manual setup.\n")}(),!n.apiKey)return void u(i,{content:[{type:"text",text:a()}],isError:!0});try{u(i,{content:[{type:"text",text:await l.run(p&&p.arguments||{})}],isError:!1})}catch(e){u(i,{content:[{type:"text",text:`AEGIS error: ${e.message}`}],isError:!0})}return}default:return void(f||d(i,-32601,`Method not found: ${l}`))}}catch(e){f||d(i,-32603,e.message)}}let v="";process.stdin.setEncoding("utf8"),process.stdin.on("data",(e=>{let t;for(v+=e;-1!==(t=v.indexOf("\n"));){const e=v.slice(0,t).trim();if(v=v.slice(t+1),!e)continue;let o;try{o=JSON.parse(e)}catch{continue}p++,Promise.resolve(g(o)).finally((()=>{p--,y()}))}})),process.stdin.on("end",(()=>{f=!0,y()}));
@@ -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 foreignMemory=require("../client/foreign-memory.js");function createTools(e){if(!e||"object"!=typeof e)throw new TypeError("createTools(client): a client instance is required");const t=e,o={aegis_status:{description:"Check the current AEGIS account: validates the API key and reports the plan, email, and whether cloud memory is enabled. Call this first to confirm setup.",inputSchema:{type:"object",properties:{},additionalProperties:!1},async run(){const e=await t.verifyApiKey();return["Key valid: "+(e.valid?"yes":"no"),`Plan: ${e.plan||"unknown"}`,e.email?`Account: ${e.email}`:null,"Memory: "+(e.memory_token?"enabled (cloud sync available)":"not enabled"),`API base: ${t.apiBase}`].filter(Boolean).join("\n")}},aegis_ask:{description:"Send a prompt to AEGIS pooled inference, billed against the account's token bank. List models with aegis_list_models and pass any id as `model`; omit `model` to let the server pick its default. `mode` is a legacy server-side shorthand and is never required.",inputSchema:{type:"object",properties:{prompt:{type:"string",description:"The user prompt / question."},model:{type:"string",description:"Pin any model id from aegis_list_models — or omit for the server default."},mode:{type:"string",description:"Legacy server-side shorthand (e.g. 'fast', 'smart', 'neo'). Optional — never defaulted client-side."},system:{type:"string",description:"Optional system instruction."},max_tokens:{type:"integer",description:"Max output tokens. The server enforces the true ceiling; omit for the server default.",minimum:1,maximum:64e3}},required:["prompt"],additionalProperties:!1},async run(e){const o=await t.chatCompletion({prompt:e.prompt,system:e.system,model:e.model,mode:e.mode,maxTokens:e.max_tokens}),s=o.choices&&o.choices[0]||{};return`${s.message&&s.message.content||"(empty response)"}\n\n— ${[o.model?`model: ${o.model}`:null,o.usage?`tokens: ${o.usage.total_tokens}`:null].filter(Boolean).join(" · ")}`}},aegis_list_models:{description:"List the exact models available to pin with aegis_ask's `model` argument — the server's model list is the truth, and omitting `model` uses the server default.",inputSchema:{type:"object",properties:{},additionalProperties:!1},async run(){const e=(await t.listModels()).models||[];return e.length?["Pass one of these as aegis_ask's `model` argument:","",...e.map((e=>` ${e.id} (${(e.capabilities||[]).join(", ")})`))].join("\n"):"No pinnable models are currently configured on AEGIS."}},aegis_balance:{description:"Check the AEGIS token bank balance and recent spend. Call this before aegis_ask if you're unsure whether the account has funds, or to see what recent calls cost.",inputSchema:{type:"object",properties:{},additionalProperties:!1},async run(){const e=await t.tokenBankBalance(),o=[`Balance: €${Number(e.balance_eur||0).toFixed(2)}`],s=(e.ledger||[]).slice(0,5);if(s.length){o.push("","Recent activity:");for(const e of s){const t=null!=e.amount_eur?Number(e.amount_eur):-Number(e.charged_micros||0)/1e6,s=Math.abs(t),r=`${t<0?"-":"+"}€${s<.01?s.toFixed(4):s.toFixed(2)}`,i="topup"===e.kind?"top-up":e.kind||"",n=e.model_key||i||"",a=e.tokens_in||e.tokens_out?` ${e.tokens_in||0}/${e.tokens_out||0} tokens`:"";o.push(` ${e.created_at||""} ${n}${a} ${r}`)}}else o.push("No spend yet.");var r;return(e.balance_eur||0)<=0&&o.push("",`Balance is empty — top up at ${r="topup","topup_bank","function"==typeof t.promptUrl?t.promptUrl(r,"topup_bank"):`https://aegiscloud.org/go/${r}`}, or set your own provider key with aegis_byok_set to use aegis_ask for free at cost.`),o.join("\n")}},aegis_byok_providers:{description:"List every provider that accepts a Bring-Your-Own-Key on AEGIS: the exact provider id to pass to aegis_byok_set, the models each one unlocks, where to create the key, and the prefix a valid key starts with. Call this before aegis_byok_set so the user knows which key to go get rather than guessing a provider id.",inputSchema:{type:"object",properties:{},additionalProperties:!1},async run(){const e=(await t.byokProviders()).providers||[];if(!e.length)return"AEGIS is not advertising any BYOK providers right now.";const o=["Set one with aegis_byok_set — pass the id exactly as shown:"];for(const t of e){const e=(t.models||[]).map((e=>"string"==typeof e?e:e&&e.id)).filter(Boolean),s=t.configured?" ✓ set"+(t.masked?` (${t.masked})`:""):"";o.push(""),o.push(` ${t.id}${s}`),t.label&&o.push(` ${t.label}`),e.length&&o.push(` models: ${e.join(", ")}`),t.key_prefix&&o.push(` key starts with: ${t.key_prefix}`),t.key_url&&o.push(` get a key: ${t.key_url}`)}return o.join("\n")}},aegis_byok_status:{description:"List which providers have a Bring-Your-Own-Key configured on this AEGIS account (known ids: openai, anthropic, groq, openrouter, together, deepseek, gemini, …). A configured BYOK key is used automatically by aegis_ask instead of the pooled balance for that provider, so calls no longer cost AEGIS token-bank funds.",inputSchema:{type:"object",properties:{},additionalProperties:!1},async run(){const e=await t.byokStatus(),o=Object.entries(e||{});if(!o.length)return"No BYOK providers are configured. Run aegis_byok_providers to see what you can set.";let s={};try{const e=await t.byokProviders();for(const t of e.providers||[])s[t.id]=t.label||""}catch{}return`BYOK keys:\n${o.map((([e,t])=>{const o=t&&t.set;return` ${e}${s[e]?` ${s[e]}`:""}: ${o?`set (${t.masked})`:"not set"}`})).join("\n")}`}},aegis_byok_set:{description:"Set or remove a Bring-Your-Own-Key API key for a provider on this AEGIS account (known ids: openai, anthropic, groq, openrouter, together, deepseek, gemini, …; the server validates what it supports). Once set, aegis_ask uses that key directly for that provider instead of the pooled AEGIS balance — unlimited use at the user's own cost. Omit api_key to remove a previously set key.",inputSchema:{type:"object",properties:{provider:{type:"string",description:"Which provider this key is for (known ids: openai, anthropic, groq, openrouter, together, deepseek, gemini, …)."},api_key:{type:"string",description:"The provider's own API key. Omit to delete the stored key instead."}},required:["provider"],additionalProperties:!1},run:async e=>(await t.byokSet(e.provider,e.api_key)).message||(e.api_key?`${e.provider} key saved.`:`${e.provider} key removed.`)},aegis_memory_search:{description:"Search the user's AEGIS cloud memory (persists across machines and sessions). Returns the most relevant stored entries for a query.",inputSchema:{type:"object",properties:{query:{type:"string",description:"Search text. Empty returns most recent."},limit:{type:"integer",description:"Max entries (1-50). Default 5.",minimum:1,maximum:50}},required:["query"],additionalProperties:!1},async run(e){const o=(await t.memorySearch(e.query,e.limit||5)).entries||[];return o.length?o.map(((e,t)=>{const o=e.timestamp||e.createdAt||"",s=e.tags&&e.tags.length?` [${e.tags.join(", ")}]`:"";return`${t+1}. ${e.content}${s}${o?`\n (${o})`:""}`})).join("\n"):`No memory entries matched "${e.query}".`}},aegis_memory_save:{description:"Save a note to the user's AEGIS cloud memory so it persists across machines and future sessions. Use for durable facts, decisions, or preferences the user asks you to remember.",inputSchema:{type:"object",properties:{content:{type:"string",description:"The fact/note to store."},tags:{type:"array",items:{type:"string"},description:"Optional tags."},importance:{type:"integer",description:"Optional 1-10 salience. Default 5.",minimum:1,maximum:10},session:{type:"string",description:"Optional session/label to group under."}},required:["content"],additionalProperties:!1},async run(e){const o={id:t.randomUUID(),content:e.content,role:"assistant",source:"claude-code",session:e.session||"claude-code",tags:e.tags||[],importance:"number"==typeof e.importance?e.importance:5,timestamp:(new Date).toISOString()};return`Saved ${(await t.memorySave(o)).saved||1} memory entry (id ${o.id}).`}},aegis_memory_import:{description:"Import memory and past conversation context from OTHER AI coding tools installed on this machine (Claude Code, Codex, Cursor, Gemini CLI, Continue, Goose, opencode, Windsurf, Zed, and a local AEGIS engine) into the user's AEGIS cloud memory. Scans read-only; nothing in the other tools' directories is modified. Defaults to a DRY RUN that only reports what it found — pass confirm:true to actually save. Entries are content-addressed, so re-running never duplicates.",inputSchema:{type:"object",properties:{confirm:{type:"boolean",description:"false (default) = report only. true = actually write the entries to AEGIS memory."},sources:{type:"array",items:{type:"string"},description:'Optional subset of source ids to import (e.g. ["claude-code"]). Omit for every source found on this machine.'},limit:{type:"integer",description:"Max entries to import (1-5000). Default 1000.",minimum:1,maximum:5e3}},additionalProperties:!1},async run(e){const o=e.limit||1e3,s=foreignMemory.scan({sources:e.sources,limit:o}),r=foreignMemory.describe(s);if(!s.entries.length)return`${r}\n\nNothing to import.`;if(!e.confirm)return[r,"",`Dry run — ${s.totals.entries} entries would be saved to AEGIS memory under ${s.totals.sourcesWithEntries} session(s) (${s.totals.skipped} skipped as too short/noise).`,"Call this tool again with confirm:true to save them."].join("\n");let i=0;const n=[];for(const e of foreignMemory.chunk(s.entries,200))try{const o=await t.memorySaveBatch(e);i+=o&&o.saved||e.length}catch(e){n.push(e.message);break}return n.length?`${r}\n\nSaved ${i} of ${s.totals.entries} entries, then stopped: ${n[0]}`:`${r}\n\nSaved ${i} entries to AEGIS memory. They are searchable now with aegis_memory_search.`}},aegis_memory_list:{description:"List the most recent entries in the user's AEGIS cloud memory. Useful to review what AEGIS already remembers.",inputSchema:{type:"object",properties:{limit:{type:"integer",description:"Max entries (1-50). Default 10.",minimum:1,maximum:50}},additionalProperties:!1},async run(e){const o=(await t.memoryList(e.limit||10)).entries||[];if(!o.length)return"AEGIS cloud memory is empty.";const s=o.map(((e,t)=>`${t+1}. ${e.content}`)).join("\n");return`Recent ${o.length} entries:\n${s}`}}};return{TOOLS:o,toolList:function(){return Object.entries(o).map((([e,t])=>({name:e,description:t.description,inputSchema:t.inputSchema})))}}}module.exports={createTools:createTools};
3
+ "use strict";const foreignMemory=require("../client/foreign-memory.js");function createTools(e){if(!e||"object"!=typeof e)throw new TypeError("createTools(client): a client instance is required");const t=e,o={aegis_status:{description:"Check the current AEGIS account: validates the API key and reports the plan, email, and whether cloud memory is enabled. Call this first to confirm setup.",inputSchema:{type:"object",properties:{},additionalProperties:!1},async run(){const e=await t.verifyApiKey();return["Key valid: "+(e.valid?"yes":"no"),`Plan: ${e.plan||"unknown"}`,e.email?`Account: ${e.email}`:null,"Memory: "+(e.memory_token?"enabled (cloud sync available)":"not enabled"),`API base: ${t.apiBase}`].filter(Boolean).join("\n")}},aegis_ask:{description:"Send a prompt to AEGIS pooled inference, billed against the account's token bank. List models with aegis_list_models and pass any id as `model`; omit `model` to let the server pick its default. `mode` is a legacy server-side shorthand and is never required.",inputSchema:{type:"object",properties:{prompt:{type:"string",description:"The user prompt / question."},model:{type:"string",description:"Pin any model id from aegis_list_models — or omit for the server default."},mode:{type:"string",description:"Legacy server-side shorthand (e.g. 'fast', 'smart', 'neo'). Optional — never defaulted client-side."},system:{type:"string",description:"Optional system instruction."},max_tokens:{type:"integer",description:"Max output tokens. The server enforces the true ceiling; omit for the server default.",minimum:1,maximum:64e3}},required:["prompt"],additionalProperties:!1},async run(e){const o=await t.chatCompletion({prompt:e.prompt,system:e.system,model:e.model,mode:e.mode,maxTokens:e.max_tokens}),s=o.choices&&o.choices[0]||{};return`${s.message&&s.message.content||"(empty response)"}\n\n— ${[o.model?`model: ${o.model}`:null,o.usage?`tokens: ${o.usage.total_tokens}`:null].filter(Boolean).join(" · ")}`}},aegis_list_models:{description:"List the exact models available to pin with aegis_ask's `model` argument — the server's model list is the truth, and omitting `model` uses the server default.",inputSchema:{type:"object",properties:{},additionalProperties:!1},async run(){const e=(await t.listModels()).models||[];return e.length?["Pass one of these as aegis_ask's `model` argument:","",...e.map((e=>` ${e.id} (${(e.capabilities||[]).join(", ")})`))].join("\n"):"No pinnable models are currently configured on AEGIS."}},aegis_balance:{description:"Check the AEGIS token bank balance and recent spend. Call this before aegis_ask if you're unsure whether the account has funds, or to see what recent calls cost.",inputSchema:{type:"object",properties:{},additionalProperties:!1},async run(){const e=await t.tokenBankBalance(),o=[`Balance: €${Number(e.balance_eur||0).toFixed(2)}`],s=(e.ledger||[]).slice(0,5);if(s.length){o.push("","Recent activity:");for(const e of s){const t=null!=e.amount_eur?Number(e.amount_eur):-Number(e.charged_micros||0)/1e6,s=Math.abs(t),r=`${t<0?"-":"+"}€${s<.01?s.toFixed(4):s.toFixed(2)}`,i="topup"===e.kind?"top-up":e.kind||"",n=e.model_key||i||"",a=e.tokens_in||e.tokens_out?` ${e.tokens_in||0}/${e.tokens_out||0} tokens`:"";o.push(` ${e.created_at||""} ${n}${a} ${r}`)}}else o.push("No spend yet.");var r;return(e.balance_eur||0)<=0&&o.push("",`Balance is empty — top up at ${r="topup","function"==typeof t.promptUrl?t.promptUrl(r,"topup_bank"):`https://aegiscloud.org/go/${r}`}, or set your own provider key with aegis_byok_set to use aegis_ask for free at cost.`),o.join("\n")}},aegis_byok_providers:{description:"List every provider that accepts a Bring-Your-Own-Key on AEGIS: the exact provider id to pass to aegis_byok_set, the models each one unlocks, where to create the key, and the prefix a valid key starts with. Call this before aegis_byok_set so the user knows which key to go get rather than guessing a provider id.",inputSchema:{type:"object",properties:{},additionalProperties:!1},async run(){const e=(await t.byokProviders()).providers||[];if(!e.length)return"AEGIS is not advertising any BYOK providers right now.";const o=["Set one with aegis_byok_set — pass the id exactly as shown:"];for(const t of e){const e=(t.models||[]).map((e=>"string"==typeof e?e:e&&e.id)).filter(Boolean),s=t.configured?" ✓ set"+(t.masked?` (${t.masked})`:""):"";o.push(""),o.push(` ${t.id}${s}`),t.label&&o.push(` ${t.label}`),e.length&&o.push(` models: ${e.join(", ")}`),t.key_prefix&&o.push(` key starts with: ${t.key_prefix}`),t.key_url&&o.push(` get a key: ${t.key_url}`)}return o.join("\n")}},aegis_byok_status:{description:"List which providers have a Bring-Your-Own-Key configured on this AEGIS account (known ids: openai, anthropic, groq, openrouter, together, deepseek, gemini, …). A configured BYOK key is used automatically by aegis_ask instead of the pooled balance for that provider, so calls no longer cost AEGIS token-bank funds.",inputSchema:{type:"object",properties:{},additionalProperties:!1},async run(){const e=await t.byokStatus(),o=Object.entries(e||{});if(!o.length)return"No BYOK providers are configured. Run aegis_byok_providers to see what you can set.";let s={};try{const e=await t.byokProviders();for(const t of e.providers||[])s[t.id]=t.label||""}catch{}return`BYOK keys:\n${o.map((([e,t])=>{const o=t&&t.set;return` ${e}${s[e]?` ${s[e]}`:""}: ${o?`set (${t.masked})`:"not set"}`})).join("\n")}`}},aegis_byok_set:{description:"Set or remove a Bring-Your-Own-Key API key for a provider on this AEGIS account (known ids: openai, anthropic, groq, openrouter, together, deepseek, gemini, …; the server validates what it supports). Once set, aegis_ask uses that key directly for that provider instead of the pooled AEGIS balance — unlimited use at the user's own cost. Omit api_key to remove a previously set key.",inputSchema:{type:"object",properties:{provider:{type:"string",description:"Which provider this key is for (known ids: openai, anthropic, groq, openrouter, together, deepseek, gemini, …)."},api_key:{type:"string",description:"The provider's own API key. Omit to delete the stored key instead."}},required:["provider"],additionalProperties:!1},run:async e=>(await t.byokSet(e.provider,e.api_key)).message||(e.api_key?`${e.provider} key saved.`:`${e.provider} key removed.`)},aegis_memory_search:{description:"Search the user's AEGIS cloud memory (persists across machines and sessions). Returns the most relevant stored entries for a query.",inputSchema:{type:"object",properties:{query:{type:"string",description:"Search text. Empty returns most recent."},limit:{type:"integer",description:"Max entries (1-50). Default 5.",minimum:1,maximum:50}},required:["query"],additionalProperties:!1},async run(e){const o=(await t.memorySearch(e.query,e.limit||5)).entries||[];return o.length?o.map(((e,t)=>{const o=e.timestamp||e.createdAt||"",s=e.tags&&e.tags.length?` [${e.tags.join(", ")}]`:"";return`${t+1}. ${e.content}${s}${o?`\n (${o})`:""}`})).join("\n"):`No memory entries matched "${e.query}".`}},aegis_memory_save:{description:"Save a note to the user's AEGIS cloud memory so it persists across machines and future sessions. Use for durable facts, decisions, or preferences the user asks you to remember.",inputSchema:{type:"object",properties:{content:{type:"string",description:"The fact/note to store."},tags:{type:"array",items:{type:"string"},description:"Optional tags."},importance:{type:"integer",description:"Optional 1-10 salience. Default 5.",minimum:1,maximum:10},session:{type:"string",description:"Optional session/label to group under."}},required:["content"],additionalProperties:!1},async run(e){const o={id:t.randomUUID(),content:e.content,role:"assistant",source:"claude-code",session:e.session||"claude-code",tags:e.tags||[],importance:"number"==typeof e.importance?e.importance:5,timestamp:(new Date).toISOString()};return`Saved ${(await t.memorySave(o)).saved||1} memory entry (id ${o.id}).`}},aegis_memory_import:{description:"Import memory and past conversation context from OTHER AI coding tools installed on this machine (Claude Code, Codex, Cursor, Gemini CLI, Continue, Goose, opencode, Windsurf, Zed, and a local AEGIS engine) into the user's AEGIS cloud memory. Scans read-only; nothing in the other tools' directories is modified. Defaults to a DRY RUN that only reports what it found — pass confirm:true to actually save. Entries are content-addressed, so re-running never duplicates.",inputSchema:{type:"object",properties:{confirm:{type:"boolean",description:"false (default) = report only. true = actually write the entries to AEGIS memory."},sources:{type:"array",items:{type:"string"},description:'Optional subset of source ids to import (e.g. ["claude-code"]). Omit for every source found on this machine.'},limit:{type:"integer",description:"Max entries to import (1-5000). Default 1000.",minimum:1,maximum:5e3}},additionalProperties:!1},async run(e){const o=e.limit||1e3,s=foreignMemory.scan({sources:e.sources,limit:o}),r=foreignMemory.describe(s);if(!s.entries.length)return`${r}\n\nNothing to import.`;if(!e.confirm)return[r,"",`Dry run — ${s.totals.entries} entries would be saved to AEGIS memory under ${s.totals.sourcesWithEntries} session(s) (${s.totals.skipped} skipped as too short/noise).`,"Call this tool again with confirm:true to save them."].join("\n");let i=0;const n=[];for(const o of foreignMemory.chunk(s.entries,200))try{const e=await t.memorySaveBatch(o);i+=e&&e.saved||o.length}catch(e){n.push(e.message);break}return n.length?`${r}\n\nSaved ${i} of ${s.totals.entries} entries, then stopped: ${n[0]}`:`${r}\n\nSaved ${i} entries to AEGIS memory. They are searchable now with aegis_memory_search.`}},aegis_memory_list:{description:"List the most recent entries in the user's AEGIS cloud memory. Useful to review what AEGIS already remembers.",inputSchema:{type:"object",properties:{limit:{type:"integer",description:"Max entries (1-50). Default 10.",minimum:1,maximum:50}},additionalProperties:!1},async run(e){const o=(await t.memoryList(e.limit||10)).entries||[];if(!o.length)return"AEGIS cloud memory is empty.";const s=o.map(((e,t)=>`${t+1}. ${e.content}`)).join("\n");return`Recent ${o.length} entries:\n${s}`}}};return{TOOLS:o,toolList:function(){return Object.entries(o).map((([e,t])=>({name:e,description:t.description,inputSchema:t.inputSchema})))}}}module.exports={createTools:createTools};