aegiscode 7.0.30 → 7.0.32

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/LICENSING.md +186 -0
  2. package/package.json +4 -2
  3. package/src/app.js +1 -1
  4. package/src/chatflow.js +1 -1
  5. package/src/commands.js +3 -1
  6. package/src/config.js +1 -1
  7. package/src/engine.js +1 -1
  8. package/src/history.js +1 -1
  9. package/src/models.js +1 -1
  10. package/src/overlays.js +1 -1
  11. package/src/panels.js +1 -1
  12. package/vendor/client/brain-catalog.js +1 -1
  13. package/vendor/client/byok-catalog.js +1 -1
  14. package/vendor/client/credits.js +45 -0
  15. package/vendor/client/foreign-sessions.js +3 -0
  16. package/vendor/client/naming.js +1 -1
  17. package/vendor/client/prefs.js +1 -1
  18. package/vendor/client/session-search.js +3 -0
  19. package/vendor/desktop/lib/local/claude-pro.js +1 -1
  20. package/vendor/desktop/lib/local/engine.js +1 -1
  21. package/vendor/desktop/lib/local/integrity.js +42 -2
  22. package/vendor/desktop/lib/local/perm-rules.js +206 -0
  23. package/vendor/desktop/lib/local/perm-store.js +298 -0
  24. package/vendor/desktop/lib/local/perm-write.js +199 -0
  25. package/vendor/desktop/lib/local/pro-sessions.js +3 -0
  26. package/vendor/desktop/lib/local/sandbox-appcontainer.js +242 -0
  27. package/vendor/desktop/lib/local/sandbox-bwrap.js +316 -0
  28. package/vendor/desktop/lib/local/sandbox-seatbelt.js +380 -0
  29. package/vendor/desktop/lib/local/sandbox.js +493 -0
  30. package/vendor/desktop/lib/local/shell.js +155 -20
  31. package/vendor/desktop/lib/local/tools.js +29 -4
  32. package/vendor/desktop/lib/settings.js +1 -1
  33. package/vendor/desktop/main.js +774 -37
  34. package/vendor/desktop/renderer/usage.js +1 -1
  35. package/vendor/mcp/admission.js +3 -0
  36. package/vendor/mcp/server.js +1 -1
  37. package/vendor/one/src/child.js +1 -1
  38. package/vendor/one/src/permissions.js +1 -1
@@ -1,3 +1,3 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- "use strict";const fs=require("node:fs"),os=require("node:os"),path=require("node:path");let envFileLib=null;try{envFileLib=require("../../../client/env-file.js")}catch{try{envFileLib=require("../../vendor/env-file.js")}catch{envFileLib=null}}function claudeConfigDir(e){const n=e||process.env,t=n&&n.CLAUDE_CONFIG_DIR;return t&&String(t).trim()?String(t).trim():path.join(os.homedir(),".claude")}function claudeOAuthToken(e){return envFileLib?envFileLib.resolveForeignSecret("CLAUDE_CODE_OAUTH_TOKEN",{env:e}):""}const SHADOWING_ENV_VARS=Object.freeze(["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN"]);function isAnthropicConsoleKey(e){return"string"==typeof e&&/^sk-ant-[A-Za-z0-9_-]{8,}$/.test(e.trim())}function childEnvPlan(e,n,t){const o={...e||{}},s=[],i=envFileLib&&"function"==typeof envFileLib.credentialLooksUsable?envFileLib.credentialLooksUsable:null,r=!(!t||!t.hasSubscription);if(i)for(const e of SHADOWING_ENV_VARS){const n=o[e];if("string"!=typeof n)continue;let t=null;if(i(n)?r&&"ANTHROPIC_API_KEY"===e&&!isAnthropicConsoleKey(n)&&(t="not-a-console-key"):t="too-short",!t)continue;delete o[e];const a=n.trim().length;a>0&&s.push({name:e,length:a,reason:t})}return n&&(o.CLAUDE_CODE_OAUTH_TOKEN=n),{env:o,dropped:s}}function envDroppedLine(e){const n=Array.isArray(e)?e:[];if(!n.length)return null;const t=n.filter((e=>e&&"not-a-console-key"===e.reason)),o=n.filter((e=>!e||"not-a-console-key"!==e.reason)),s=[];if(o.length){const e=o.map((e=>`${e.name} (${e.length} character${1===e.length?"":"s"})`)).join(", ");s.push(`${e}: too short to be a credential, and the CLI would have spent it instead of your subscription`)}if(t.length){const e=t.map((e=>`${e.name} (${e.length} characters)`)).join(", ");s.push(`${e}: not an Anthropic console key (\`sk-ant-\`), and the CLI would have spent it instead of your subscription`)}return`aegis: not passed to the claude child — ${s.join("; ")}`}function shadowingValue(e,n){const t=e||{},o=envFileLib&&"function"==typeof envFileLib.credentialLooksUsable?envFileLib.credentialLooksUsable:null;if(!o)return null;const s=!(!n||!n.hasSubscription);for(const e of SHADOWING_ENV_VARS){const n=t[e];if("string"!=typeof n)continue;let i=null;if(o(n)?s&&"ANTHROPIC_API_KEY"===e&&!isAnthropicConsoleKey(n)&&(i="not-a-console-key"):i="too-short",i)return{name:e,length:n.trim().length,reason:i}}return null}function claudeProStatus(e){const n=e||{},t=n.env||process.env,o=path.join(n.dir||claudeConfigDir(t),".credentials.json"),s={claude:n.claudeVersion||null,file:o,exists:!1,kind:null,subscription:null,expiresAt:0,loggedIn:!1};let i;try{i=JSON.parse(fs.readFileSync(o,"utf8")),s.exists=!0}catch{i=null}const r=i&&i.claudeAiOauth;r&&(r.accessToken||r.refreshToken)?(s.kind="oauth",s.subscription=r.subscriptionType||null,s.expiresAt=Number(r.refreshTokenExpiresAt)||0,s.loggedIn=!0):i&&"string"==typeof i.token&&i.token?(s.kind="apikey",s.loggedIn=!0):claudeOAuthToken(t)&&(s.kind="env-token",s.loggedIn=!0),s.subscriptionPresent=s.loggedIn&&"apikey"!==s.kind,s.shadowed=shadowingValue(t,{hasSubscription:s.subscriptionPresent});const a=childEnvPlan(t,null,{hasSubscription:s.subscriptionPresent});return s.credentialPresent=s.loggedIn||"string"==typeof a.env.ANTHROPIC_API_KEY||"string"==typeof a.env.ANTHROPIC_AUTH_TOKEN||"string"==typeof a.env.CLAUDE_CODE_OAUTH_TOKEN,s}const PRO_MODELS=Object.freeze([{id:"default",label:"Default (recommended)",note:"the CLI picks for the subscription"},{id:"sonnet",label:"Sonnet",note:"alias the CLI resolves · latest Sonnet"},{id:"opus",label:"Opus",note:"alias the CLI resolves · latest Opus"},{id:"opusplan",label:"Opus Plan",note:"alias the CLI resolves · plan with Opus, act on Sonnet"},{id:"haiku",label:"Haiku",note:"alias the CLI resolves · latest Haiku"},{id:"fable",label:"Fable",note:"alias the CLI resolves · needs usage credits"},{id:"claude-sonnet-5-5",label:"Claude Sonnet 5.5",note:"full name · Anthropic"},{id:"claude-sonnet-4-6",label:"Claude Sonnet 4.6",note:"full name · Anthropic"},{id:"claude-sonnet-4-5-20250929",label:"Claude Sonnet 4.5",note:"full name · Anthropic · dated snapshot"},{id:"claude-opus-5",label:"Claude Opus 5",note:"full name · Anthropic"},{id:"claude-opus-4-7",label:"Claude Opus 4.7",note:"full name · Anthropic"},{id:"claude-opus-4-6",label:"Claude Opus 4.6",note:"full name · Anthropic"},{id:"claude-opus-4-5-20251101",label:"Claude Opus 4.5",note:"full name · Anthropic · dated snapshot"}]);function turnArgs(e){const n=[],t=e||{};return t.system&&String(t.system).trim()&&n.push("--append-system-prompt",String(t.system)),n}function createStreamParser(e){const n=e||{},t=new Map;let o="",s="",i=0,r=null;const a=e=>[...t.values()].find((n=>"collecting"===n.phase&&n.index===e))||[...t.values()].find((e=>"collecting"===e.phase));return{line(e){let l;try{l=JSON.parse(e)}catch{return}if("stream_event"===l.type&&l.event){const e=l.event;if("content_block_start"===e.type&&e.content_block)"tool_use"===e.content_block.type&&t.set(e.content_block.id,{id:e.content_block.id,index:null==e.index?0:e.index,name:e.content_block.name,args:"",startedAt:Date.now(),phase:"collecting"});else if("content_block_delta"===e.type&&e.delta){if("text_delta"===e.delta.type){const t=(e.delta.text||"").replace(/\x00/g,"");o+=t,n.onText&&t&&n.onText(t)}else if("thinking_delta"===e.delta.type){const t=(e.delta.thinking||"").replace(/\x00/g,"");s+=t,n.onThinking&&t&&n.onThinking(t);const o=e.delta.estimated_tokens;"number"==typeof o&&o>0&&Number.isFinite(o)&&(i+=o,n.onThinkingProgress&&n.onThinkingProgress(o))}else if("input_json_delta"===e.delta.type){const n=a(null==e.index?0:e.index);n&&(n.args+=e.delta.partial_json||"")}}else if("content_block_stop"===e.type){const o=a(null==e.index?0:e.index);o&&(e=>{let o=e.args;try{o=e.args?JSON.parse(e.args):{}}catch{o={}}t.set(e.id,{...e,args:o,phase:"run"}),n.onTool&&n.onTool({id:e.id,name:e.name,args:o,phase:"run"})})(o)}}else if("user"===l.type&&l.message){const e=Array.isArray(l.message.content)?l.message.content:[];for(const o of e){if(!o||"tool_result"!==o.type||!o.tool_use_id)continue;const e=t.get(o.tool_use_id);if(!e)continue;const s=Math.max(0,Date.now()-(e.startedAt||Date.now()));n.onTool&&n.onTool({id:e.id,name:e.name,phase:"done",elapsed:s,error:!!o.is_error}),t.delete(o.tool_use_id)}}else"result"===l.type&&(r=l,n.onDone&&n.onDone({text:o||l.result||"",error:l.is_error?l.result||"api error":void 0,usage:l.usage||null,costUsd:"number"==typeof l.total_cost_usd?l.total_cost_usd:void 0,durationMs:l.duration_ms,sessionId:l.session_id,thinking:s||"",thinkingTokens:i}))},get text(){return o},get thinking(){return s},get thinkingTokens(){return i},get resultLine(){return r}}}function loadSeam(e){const n=e||__dirname,t=[path.join(n,"..","..","..","one","src"),path.join(n,"..","..","vendor","one","src"),path.join(n,"..","..","..","..","one","src")];for(const e of t)try{const n=require(path.join(e,"child.js")),t=require(path.join(e,"permissions.js"));if("function"==typeof n.claudeArgv&&"function"==typeof t.resolvePosture)return{child:n,permissions:t}}catch{}throw new Error("aegis: the Claude child argv builder (one/src/child.js + one/src/permissions.js) is missing from this install — refusing to build a second argv, because a second argv is a second policy.")}function seamAvailable(e){try{return loadSeam(e),{ok:!0,error:null}}catch(e){return{ok:!1,error:e&&e.message||String(e)}}}function proMessage(e,n,t){const o={content:e||""},s="string"==typeof n?n:"";return s&&(o.reasoning_content=s),"number"==typeof t&&t>0&&Number.isFinite(t)&&(o.thinking_tokens=t),o}function runClaudePro(e,n){const t=e||{},o=n||{},s=o.seam||loadSeam(o.dir),i=o.spawn||require("node:child_process").spawn,r=s.permissions.resolvePosture({rules:t.rules,gate:t.gate,interactive:!1,childKind:s.permissions.CHILD_KINDS.HEADLESS,env:t.env||process.env}),a=s.child.claudeArgv({posture:r,prompt:t.prompt,model:t.model||void 0,permissionMode:t.permissionMode,resumeSessionId:t.resumeSessionId,sessionId:t.sessionId,addDir:t.addDir,extra:[...turnArgs(t),"--include-partial-messages","--verbose"]});return new Promise((e=>{if(t.signal&&t.signal.aborted)return void e({choices:[{message:{content:""},finish_reason:"stop"}],stopped:!0});const n=t.env||process.env,s=claudeOAuthToken(n);let r=!1;try{r=!!claudeProStatus({env:n}).subscriptionPresent}catch{}const l=childEnvPlan(n,s,{hasSubscription:r}),c=l.env,d=envDroppedLine(l.dropped);if(d&&t.onDelta)try{t.onDelta({delta:"",note:d})}catch{}let u;try{u=i(o.executable||"claude",a.argv,{cwd:t.cwd||process.cwd(),stdio:["ignore","pipe","pipe"],env:c})}catch(n){return void e({choices:[{message:{content:""},finish_reason:"error"}],error:`claude: could not start the child (${n&&n.message||n})`,...l.dropped.length?{envDropped:l.dropped}:{}})}if(t.onSpawn)try{t.onSpawn(u,a.record)}catch{}let p=!1,h="",g="",f=null;const m=Number(t.idleTimeoutMs)||6e5,_=n=>{p||(p=!0,f&&clearTimeout(f),t.signal&&t.signal.removeEventListener("abort",v),e(l.dropped.length?{...n,envDropped:l.dropped}:n))},v=()=>{try{u.kill("SIGTERM")}catch{}setTimeout((()=>{try{u.kill("SIGKILL")}catch{}}),1500)};t.signal&&t.signal.addEventListener("abort",v,{once:!0});const b=()=>{f&&clearTimeout(f),f=setTimeout((()=>{v(),_({choices:[{message:{content:""},finish_reason:"stop"}],error:`claude: the child went silent for ${Math.round(m/1e3)}s and was stopped`})}),m)};b();const k=createStreamParser({onText:e=>{b(),t.onDelta&&t.onDelta({delta:e})},onThinking:e=>{b(),t.onDelta&&t.onDelta({reasoning:e})},onThinkingProgress:e=>{b(),t.onDelta&&t.onDelta({thinkingTokens:e})},onTool:e=>{b(),t.onDelta&&t.onDelta({delta:"",tool:{name:e.name,args:e.args,ok:"done"===e.phase?!e.error:void 0,id:e.id,cwd:t.cwd,phase:e.phase}})},onDone:e=>{e.error?_({choices:[{message:{content:e.text||""},finish_reason:"error"}],usage:e.usage||void 0,error:e.error}):_({choices:[{message:proMessage(e.text||"",e.thinking,e.thinkingTokens),finish_reason:"stop"}],usage:e.usage||void 0,costUsd:e.costUsd,durationMs:e.durationMs,sessionId:e.sessionId,childRecord:a.record})}});u.stdout.on("data",(e=>{b(),g+=e.toString("utf8");const n=g.split("\n");g=n.pop()||"";for(const e of n){const n=e.trim();n&&k.line(n)}})),u.stderr.on("data",(e=>{b(),h.length<8192&&(h+=e.toString("utf8"))})),u.on("error",(e=>{_({choices:[{message:{content:""},finish_reason:"error"}],error:`claude: could not run the child (${e&&e.message||e}). Install it with \`npm i -g @anthropic-ai/claude-code\`, then sign in with \`claude auth login\`.`})})),u.on("close",(e=>{g.trim()&&k.line(g.trim()),_({choices:[{message:proMessage(k.text,k.thinking,k.thinkingTokens),finish_reason:"stop"}],usage:k.resultLine&&k.resultLine.usage||void 0,childRecord:a.record,error:k.text||0===e?void 0:`claude: the child exited with status ${e}${h.trim()?` — ${h.trim().split("\n").slice(-3).join(" ")}`:""}`})}))}))}function childLine(e,n){if(!e)return"";try{return loadSeam(n).child.childRecordLine(e)}catch{const n=e.skipFlag||"no permission flag";return`aegis: claude child [${e.kind}] ${n}`}}module.exports={claudeConfigDir:claudeConfigDir,claudeOAuthToken:claudeOAuthToken,claudeProStatus:claudeProStatus,childEnvPlan:childEnvPlan,envDroppedLine:envDroppedLine,shadowingValue:shadowingValue,SHADOWING_ENV_VARS:SHADOWING_ENV_VARS,PRO_MODELS:PRO_MODELS,turnArgs:turnArgs,createStreamParser:createStreamParser,loadSeam:loadSeam,seamAvailable:seamAvailable,childLine:childLine,runClaudePro:runClaudePro};
3
+ "use strict";const fs=require("node:fs"),os=require("node:os"),path=require("node:path");let envFileLib=null;try{envFileLib=require("../../../client/env-file.js")}catch{try{envFileLib=require("../../vendor/env-file.js")}catch{envFileLib=null}}function claudeConfigDir(e){const n=e||process.env,t=n&&n.CLAUDE_CONFIG_DIR;return t&&String(t).trim()?String(t).trim():path.join(os.homedir(),".claude")}function claudeOAuthToken(e){return envFileLib?envFileLib.resolveForeignSecret("CLAUDE_CODE_OAUTH_TOKEN",{env:e}):""}const SHADOWING_ENV_VARS=Object.freeze(["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN"]);function isAnthropicConsoleKey(e){return"string"==typeof e&&/^sk-ant-[A-Za-z0-9_-]{8,}$/.test(e.trim())}function childEnvPlan(e,n,t){const o={...e||{}},s=[],i=envFileLib&&"function"==typeof envFileLib.credentialLooksUsable?envFileLib.credentialLooksUsable:null,r=!(!t||!t.hasSubscription);if(i)for(const e of SHADOWING_ENV_VARS){const n=o[e];if("string"!=typeof n)continue;let t=null;if(i(n)?r&&"ANTHROPIC_API_KEY"===e&&!isAnthropicConsoleKey(n)&&(t="not-a-console-key"):t="too-short",!t)continue;delete o[e];const a=n.trim().length;a>0&&s.push({name:e,length:a,reason:t})}return n&&(o.CLAUDE_CODE_OAUTH_TOKEN=n),{env:o,dropped:s}}function envDroppedLine(e){const n=Array.isArray(e)?e:[];if(!n.length)return null;const t=n.filter((e=>e&&"not-a-console-key"===e.reason)),o=n.filter((e=>!e||"not-a-console-key"!==e.reason)),s=[];if(o.length){const e=o.map((e=>`${e.name} (${e.length} character${1===e.length?"":"s"})`)).join(", ");s.push(`${e}: too short to be a credential, and the CLI would have spent it instead of your subscription`)}if(t.length){const e=t.map((e=>`${e.name} (${e.length} characters)`)).join(", ");s.push(`${e}: not an Anthropic console key (\`sk-ant-\`), and the CLI would have spent it instead of your subscription`)}return`aegis: not passed to the claude child — ${s.join("; ")}`}function shadowingValue(e,n){const t=e||{},o=envFileLib&&"function"==typeof envFileLib.credentialLooksUsable?envFileLib.credentialLooksUsable:null;if(!o)return null;const s=!(!n||!n.hasSubscription);for(const e of SHADOWING_ENV_VARS){const n=t[e];if("string"!=typeof n)continue;let i=null;if(o(n)?s&&"ANTHROPIC_API_KEY"===e&&!isAnthropicConsoleKey(n)&&(i="not-a-console-key"):i="too-short",i)return{name:e,length:n.trim().length,reason:i}}return null}function claudeProStatus(e){const n=e||{},t=n.env||process.env,o=path.join(n.dir||claudeConfigDir(t),".credentials.json"),s={claude:n.claudeVersion||null,file:o,exists:!1,kind:null,subscription:null,expiresAt:0,loggedIn:!1};let i;try{i=JSON.parse(fs.readFileSync(o,"utf8")),s.exists=!0}catch{i=null}const r=i&&i.claudeAiOauth;r&&(r.accessToken||r.refreshToken)?(s.kind="oauth",s.subscription=r.subscriptionType||null,s.expiresAt=Number(r.refreshTokenExpiresAt)||0,s.loggedIn=!0):i&&"string"==typeof i.token&&i.token?(s.kind="apikey",s.loggedIn=!0):claudeOAuthToken(t)&&(s.kind="env-token",s.loggedIn=!0),s.subscriptionPresent=s.loggedIn&&"apikey"!==s.kind,s.shadowed=shadowingValue(t,{hasSubscription:s.subscriptionPresent});const a=childEnvPlan(t,null,{hasSubscription:s.subscriptionPresent});return s.credentialPresent=s.loggedIn||"string"==typeof a.env.ANTHROPIC_API_KEY||"string"==typeof a.env.ANTHROPIC_AUTH_TOKEN||"string"==typeof a.env.CLAUDE_CODE_OAUTH_TOKEN,s}const PRO_MODELS=Object.freeze([{id:"default",label:"Default (recommended)",note:"the CLI picks for the subscription"},{id:"sonnet",label:"Sonnet",note:"alias the CLI resolves · latest Sonnet"},{id:"opus",label:"Opus",note:"alias the CLI resolves · latest Opus"},{id:"opusplan",label:"Opus Plan",note:"alias the CLI resolves · plan with Opus, act on Sonnet"},{id:"haiku",label:"Haiku",note:"alias the CLI resolves · latest Haiku"},{id:"fable",label:"Fable",note:"alias the CLI resolves · needs usage credits"},{id:"claude-sonnet-5-5",label:"Claude Sonnet 5.5",note:"full name · Anthropic"},{id:"claude-sonnet-4-6",label:"Claude Sonnet 4.6",note:"full name · Anthropic"},{id:"claude-sonnet-4-5-20250929",label:"Claude Sonnet 4.5",note:"full name · Anthropic · dated snapshot"},{id:"claude-opus-5",label:"Claude Opus 5",note:"full name · Anthropic"},{id:"claude-opus-4-7",label:"Claude Opus 4.7",note:"full name · Anthropic"},{id:"claude-opus-4-6",label:"Claude Opus 4.6",note:"full name · Anthropic"},{id:"claude-opus-4-5-20251101",label:"Claude Opus 4.5",note:"full name · Anthropic · dated snapshot"}]);function turnArgs(e){const n=[],t=e||{};return t.system&&String(t.system).trim()&&n.push("--append-system-prompt",String(t.system)),n}function createStreamParser(e){const n=e||{},t=new Map;let o="",s="",i=0,r=null;const a=e=>[...t.values()].find((n=>"collecting"===n.phase&&n.index===e))||[...t.values()].find((e=>"collecting"===e.phase));return{line(e){let l;try{l=JSON.parse(e)}catch{return}if("control_request"===l.type&&l.request){const e=l.request;if("can_use_tool"!==e.subtype)return;return n.onAsk?void n.onAsk({requestId:l.request_id,toolName:e.tool_name,input:e.input||{},toolUseId:e.tool_use_id,displayName:e.display_name,description:e.description,suggestions:Array.isArray(e.permission_suggestions)?e.permission_suggestions:[]}):void(n.onAskUnavailable&&n.onAskUnavailable({requestId:l.request_id,request:e}))}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||(Array.isArray(l.errors)?l.errors.find((e=>"string"==typeof e&&e.trim())):void 0)||"api error":void 0,usage:l.usage||null,costUsd:"number"==typeof l.total_cost_usd?l.total_cost_usd:void 0,durationMs:l.duration_ms,sessionId:l.session_id,thinking:s||"",thinkingTokens:i}))},get text(){return o},get thinking(){return s},get thinkingTokens(){return i},get resultLine(){return r}}}function loadSeam(e){const n=e||__dirname,t=[path.join(n,"..","..","..","one","src"),path.join(n,"..","..","vendor","one","src"),path.join(n,"..","..","..","..","one","src")];for(const e of t)try{const n=require(path.join(e,"child.js")),t=require(path.join(e,"permissions.js"));if("function"==typeof n.claudeArgv&&"function"==typeof t.resolvePosture)return{child:n,permissions:t}}catch{}throw new Error("aegis: the Claude child argv builder (one/src/child.js + one/src/permissions.js) is missing from this install — refusing to build a second argv, because a second argv is a second policy.")}function seamAvailable(e){try{return loadSeam(e),{ok:!0,error:null}}catch(e){return{ok:!1,error:e&&e.message||String(e)}}}function proMessage(e,n,t){const o={content:e||""},s="string"==typeof n?n:"";return s&&(o.reasoning_content=s),"number"==typeof t&&t>0&&Number.isFinite(t)&&(o.thinking_tokens=t),o}function runClaudePro(e,n){const t=e||{},o=n||{},s=o.seam||loadSeam(o.dir),i=o.spawn||require("node:child_process").spawn;let r=void 0===t.permissionMode||null===t.permissionMode?null:String(t.permissionMode);if(null===r)try{const e=s.permissions.storedPermissionFacts();r=e&&"string"==typeof e.permissionMode?e.permissionMode:null}catch{}const a=s.permissions.resolvePosture({rules:t.rules,gate:t.gate,interactive:!1,childKind:s.permissions.CHILD_KINDS.HEADLESS,permissionMode:r,env:t.env||process.env}),l=s.child.claudeArgv({posture:a,prompt:t.prompt,model:t.model||void 0,resumeSessionId:t.resumeSessionId,sessionId:t.sessionId,addDir:t.addDir,askBridge:"function"==typeof t.onAsk,extra:[...turnArgs(t),"--include-partial-messages","--verbose"]});return new Promise((e=>{if(t.signal&&t.signal.aborted)return void e({choices:[{message:{content:""},finish_reason:"stop"}],stopped:!0});const n=t.env||process.env,s=claudeOAuthToken(n);let r=!1;try{r=!!claudeProStatus({env:n}).subscriptionPresent}catch{}const a=childEnvPlan(n,s,{hasSubscription:r}),c=a.env,d=envDroppedLine(a.dropped);if(d&&t.onDelta)try{t.onDelta({delta:"",note:d})}catch{}let u;try{u=i(o.executable||"claude",l.argv,{cwd:t.cwd||process.cwd(),stdio:[l.record.askBridge?"pipe":"ignore","pipe","pipe"],env:c})}catch(n){return void e({choices:[{message:{content:""},finish_reason:"error"}],error:`claude: could not start the child (${n&&n.message||n})`,...a.dropped.length?{envDropped:a.dropped}:{}})}if(t.onSpawn)try{t.onSpawn(u,l.record)}catch{}let p=!1,h="",g="",m=null;const f=Number(t.idleTimeoutMs)||6e5,_=l.record.askBridge,v=e=>{if(!_||!u.stdin||u.stdin.destroyed)return!1;try{return u.stdin.write(`${JSON.stringify(e)}\n`),!0}catch{return!1}};_&&v({type:"user",message:{role:"user",content:[{type:"text",text:String(t.prompt||"")}]}});const y=(e,n,t)=>{v({type:"control_response",response:{subtype:"success",request_id:e,response:"session"===n||"once"===n||"always"===n?{behavior:"allow"}:{behavior:"deny",message:t||"AEGIS_USER_DENIED"}}})},A=n=>{if(!p){if(p=!0,m&&clearTimeout(m),t.signal&&t.signal.removeEventListener("abort",k),_&&u.stdin&&!u.stdin.destroyed)try{u.stdin.end()}catch{}e(a.dropped.length?{...n,envDropped:a.dropped}:n)}},k=()=>{try{u.kill("SIGTERM")}catch{}setTimeout((()=>{try{u.kill("SIGKILL")}catch{}}),1500)};t.signal&&t.signal.addEventListener("abort",k,{once:!0});const b=()=>{m&&clearTimeout(m),m=setTimeout((()=>{k(),A({choices:[{message:{content:""},finish_reason:"stop"}],error:`claude: the child went silent for ${Math.round(f/1e3)}s and was stopped`})}),f)};b();const S=createStreamParser({onText:e=>{b(),t.onDelta&&t.onDelta({delta:e})},onThinking:e=>{b(),t.onDelta&&t.onDelta({reasoning:e})},onThinkingProgress:e=>{b(),t.onDelta&&t.onDelta({thinkingTokens:e})},onTool:e=>{b(),t.onDelta&&t.onDelta({delta:"",tool:{name:e.name,args:e.args,ok:"done"===e.phase?!e.error:void 0,id:e.id,cwd:t.cwd,phase:e.phase}})},onAsk:e=>{b(),Promise.resolve().then((()=>t.onAsk(e))).then((n=>y(e.requestId,"session"===n||"once"===n||"always"===n?n:"deny","AEGIS_USER_DENIED")),(n=>{y(e.requestId,"deny",`AEGIS_USER_DENIED (${n&&n.message||String(n)})`)})).catch((()=>{}))},onAskUnavailable:e=>{y(e.requestId,"deny","AEGIS_NO_APPROVAL_CHANNEL")},onDone:e=>{e.error?A({choices:[{message:{content:e.text||""},finish_reason:"error"}],usage:e.usage||void 0,error:e.error,...l.record.resumeSessionId&&isStaleResumeError(e.error)?{resumeStale:!0,resumeSessionId:l.record.resumeSessionId}:{}}):A({choices:[{message:proMessage(e.text||"",e.thinking,e.thinkingTokens),finish_reason:"stop"}],usage:e.usage||void 0,costUsd:e.costUsd,durationMs:e.durationMs,sessionId:e.sessionId,childRecord:l.record})}});u.stdout.on("data",(e=>{b(),g+=e.toString("utf8");const n=g.split("\n");g=n.pop()||"";for(const e of n){const n=e.trim();n&&S.line(n)}})),_&&u.stdin&&u.stdin.on("error",(()=>{})),u.stderr.on("data",(e=>{b(),h.length<8192&&(h+=e.toString("utf8"))})),u.on("error",(e=>{A({choices:[{message:{content:""},finish_reason:"error"}],error:`claude: could not run the child (${e&&e.message||e}). Install it with \`npm i -g @anthropic-ai/claude-code\`, then sign in with \`claude auth login\`.`})})),u.on("close",(e=>{g.trim()&&S.line(g.trim()),A({choices:[{message:proMessage(S.text,S.thinking,S.thinkingTokens),finish_reason:"stop"}],usage:S.resultLine&&S.resultLine.usage||void 0,childRecord:l.record,error:S.text||0===e?void 0:`claude: the child exited with status ${e}${h.trim()?` — ${h.trim().split("\n").slice(-3).join(" ")}`:""}`})}))}))}function isStaleResumeError(e){return!!e&&/no conversation found with session id/i.test(String(e))}function childLine(e,n){if(!e)return"";try{return loadSeam(n).child.childRecordLine(e)}catch{const n=e.skipFlag||"no permission flag";return`aegis: claude child [${e.kind}] ${n}`}}module.exports={claudeConfigDir:claudeConfigDir,claudeOAuthToken:claudeOAuthToken,claudeProStatus:claudeProStatus,childEnvPlan:childEnvPlan,envDroppedLine:envDroppedLine,shadowingValue:shadowingValue,SHADOWING_ENV_VARS:SHADOWING_ENV_VARS,PRO_MODELS:PRO_MODELS,turnArgs:turnArgs,createStreamParser:createStreamParser,loadSeam:loadSeam,seamAvailable:seamAvailable,childLine:childLine,isStaleResumeError:isStaleResumeError,runClaudePro:runClaudePro};
@@ -1,3 +1,3 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- "use strict";const{randomUUID:randomUUID}=require("node:crypto"),os=require("node:os"),toolsModule=require("./tools.js"),attachmentsModule=require("./attachments.js"),{flattenContent:flattenContent}=attachmentsModule,promptModule=require("./prompt.js"),localTransport=require("./local.js"),{ShellSession:ShellSession}=require("./shell.js"),{planExec:planExec}=require("./exec-plan.js"),claudePro=require("./claude-pro.js"),{agentSystemPrompt:agentSystemPrompt,agentRoleLabel:agentRoleLabel}=require("./agents.js"),{beginTurnGuard:beginTurnGuard,recordWrite:recordWrite,blocksDestructive:blocksDestructive}=require("./turn-guard.js"),{acquireWorktreeLock:acquireWorktreeLock,releaseWorktreeLock:releaseWorktreeLock}=require("./worktree-lock.js"),covenant=require("./covenant.js");let envFile=null;try{envFile=require("../../../client/env-file.js")}catch{try{envFile=require("../../vendor/env-file.js")}catch{envFile=null}}let platformLib=null;try{platformLib=require("../../../client/platform.js")}catch{try{platformLib=require("../../vendor/platform.js")}catch{platformLib=null}}let credentialsLib=null;try{credentialsLib=require("../../../client/credentials.js")}catch{try{credentialsLib=require("../../vendor/credentials.js")}catch{credentialsLib=null}}function normalizeToolArgs(e,o,t,r){const n=e&&"function"==typeof e.normalizeArgs&&e.normalizeArgs||"function"==typeof toolsModule.normalizeArgs&&toolsModule.normalizeArgs||null;return n?n(o,t,r):{ok:!0,args:t&&"object"==typeof t?t:{},error:null}}function detectVcs(e){if(!e)return null;try{const o=require("node:fs"),t=require("node:path");let r=t.resolve(String(e));for(let e=0;e<8;e+=1){if(o.existsSync(t.join(r,".git")))return"git";const e=t.dirname(r);if(e===r)break;r=e}return""}catch{return null}}function hostEnv(e={},o={},t=null){const r=e||{},n=o||{},s=(e,o)=>null!=n[e]?n[e]:o;let a=r.homedir,i=r.cwd;try{a||(a=os.homedir()),i||(i=process.cwd())}catch{}let l=r.shell,c=r.shellKind;try{if(!l||!c){const e=require("./shell.js").resolveSessionShell();l=l||e.cmd,c=c||e.kind}}catch{}let d=r.desktopdir;try{!d&&platformLib&&(d=platformLib.desktopDir())}catch{}let u=r.dataDir;try{!u&&credentialsLib&&(u=credentialsLib.aegisHome())}catch{}let f=r.locale,p=r.localeName;try{!f&&platformLib&&"function"==typeof platformLib.appLocale&&(f=platformLib.appLocale()),f&&!p&&platformLib&&"function"==typeof platformLib.languageName&&(p=platformLib.languageName(f))}catch{}return{platform:s("platform",r.platform||process.platform),arch:s("arch",r.arch||process.arch),homedir:s("homedir",a),desktopdir:s("desktopdir",d),dataDir:s("dataDir",u),locale:s("locale",f),localeName:s("localeName",p),languages:s("languages",r.languages),cwd:s("cwd",i),vcs:s("vcs",null!=r.vcs?r.vcs:detectVcs(i)),shell:s("shell",l),shellKind:s("shellKind",c),roots:s("roots",r.roots),appVersion:s("appVersion",r.appVersion),model:s("model",t&&t.model)}}function requireSharedBrain(){const e=[()=>require("../../../client/brain-catalog.js"),()=>require("../../vendor/brain-catalog.js")];let o=null;for(const t of e)try{return t()}catch(e){o=e}throw o}function requireSharedByokCatalog(){const e=[()=>require("../../../client/byok-catalog.js"),()=>require("../../vendor/byok-catalog.js")];let o=null;for(const t of e)try{return t()}catch(e){o=e}throw o}function requireSharedUserModels(){const e=[()=>require("../../../client/user-models.js"),()=>require("../../vendor/user-models.js")];let o=null;for(const t of e)try{return t()}catch(e){o=e}throw o}function requireSharedCatalogClient(){const e=[()=>require("../../../client/catalog-client.js"),()=>require("../../vendor/catalog-client.js")];let o=null;for(const t of e)try{return t()}catch(e){o=e}throw o}function requireSharedModelDiscovery(){const e=[()=>require("../../../client/model-discovery.js"),()=>require("../../vendor/model-discovery.js")];let o=null;for(const t of e)try{return t()}catch(e){o=e}throw o}const WORKTREE_LOCK_WAIT_MS=1500,MAX_SUBAGENT_DEPTH=4,CLASSES=[{class:"aegis",label:"Aegis Cloud",kind:"cloud"},{class:"byok",label:"Bring your own key",kind:"cloud"},{class:"local",label:"Local model",kind:"local"},{class:"pro",label:"Claude Code Pro",kind:"subscription"}],BYOK_NAMESPACE_PREFIX="byok:";function byokNamespace(e){return`${BYOK_NAMESPACE_PREFIX}${e}`}function splitByokModel(e){const o="string"==typeof e?e:"",t=o.indexOf(":");return t<0?{provider:"",model:o}:{provider:o.slice(0,t),model:o.slice(t+1)}}function providerKeyRecord(e){const o={key:"",env:"",rejected:null};if(!envFile||"function"!=typeof envFile.providerKeyFromEnv)return o;try{const t=envFile.providerKeyFromEnv(e)||o;return{key:"string"==typeof t.key?t.key:"",env:"string"==typeof t.env?t.env:"",rejected:"string"==typeof t.rejected&&t.rejected?t.rejected:null}}catch{return o}}function providerKeyFromEnv(e){if(!envFile||"function"!=typeof envFile.providerKeyFromEnv)return"";try{return envFile.providerKeyFromEnv(e).key||""}catch{return""}}const DEEPSEEK_REASONING_MODEL_RE=/^deepseek-(v4(\.\d+)?-(flash|pro)|flash|pro|reasoner)$/,EFFORT_TOKEN_BUDGET={low:8192,medium:16384,high:32768,max:32768},DEEPSEEK_EFFORT={low:"low",medium:"high",high:"high"},DEEPSEEK_EFFORT_EXTRA={max:"max"},EFFORT_IDENTITY={low:"low",medium:"medium",high:"high"},EFFORT_INERT_RE=/non-reasoning/i,EFFORT_DIALECTS=[{provider:"deepseek",re:DEEPSEEK_REASONING_MODEL_RE,field:"effort",map:DEEPSEEK_EFFORT,extra:DEEPSEEK_EFFORT_EXTRA},{provider:"openai",re:/^(gpt-5|o[0-9])/i,field:"reasoning_effort",map:EFFORT_IDENTITY},{provider:"groq",re:/^(openai\/gpt-oss|qwen\/qwen3)/i,field:"reasoning_effort",map:EFFORT_IDENTITY},{provider:"xai",re:/^grok-(4\.[5-9]|[5-9])/,field:"reasoning_effort",map:EFFORT_IDENTITY},{provider:"google",re:/^gemini-(2\.5|3|[4-9])/,field:"reasoning_effort",map:{...EFFORT_IDENTITY,medium:"high"}}],AUTONOMOUS_IDLE_TIMEOUT_MS=9e5;function reasoningBudget(e,o,t){const r=Number(o);return Number.isFinite(r)&&r>0?r:DEEPSEEK_REASONING_MODEL_RE.test(String(e||""))?EFFORT_TOKEN_BUDGET["low"===t||"medium"===t||"max"===t?t:"high"]:void 0}function nativeEffort(e,o,t){const r=String(o||"");if(EFFORT_INERT_RE.test(r))return;if(null===t)return;const n="low"===t||"medium"===t?t:"max"===t?"max":"high";for(const o of EFFORT_DIALECTS)if(o.provider===e&&o.re.test(r)){const e=Object.prototype.hasOwnProperty.call(o.map,n)?o.map[n]:o.extra&&Object.prototype.hasOwnProperty.call(o.extra,n)?o.extra[n]:void 0;if(void 0===e)return;return{field:o.field,level:e}}}function normalizeCatalog(e){return Array.isArray(e)?e.map((e=>"string"==typeof e?{id:e}:e)).filter((e=>e&&e.id)):[]}const{offerableCatalog:offerableCatalog}=requireSharedBrain(),{withByokAdditions:withByokAdditions,canonicalModelId:canonicalModelId}=requireSharedByokCatalog(),{withUserModels:withUserModels,unmatchedUserProviders:unmatchedUserProviders,load:loadUserModels,addUserModel:addUserModel,removeUserModel:removeUserModel}=requireSharedUserModels(),{withCatalog:withCatalog}=requireSharedCatalogClient(),{discoverModels:discoverVendorModels,canDiscover:canDiscoverVendorModels,endpointFor:vendorEndpointFor,discoverableProviders:discoverableProviders}=requireSharedModelDiscovery();function parseArgs(e){if(null==e)return{};if("object"==typeof e)return e;try{const o=JSON.parse(String(e));return o&&"object"==typeof o?o:{}}catch{return{}}}function extractToolCalls(e){if(!e)return[];if(Array.isArray(e.toolCalls)&&e.toolCalls.length)return e.toolCalls.map((e=>({id:e.id||"",name:e.name||"",args:parseArgs(e.args)}))).filter((e=>e.name));const o=e.choices&&e.choices[0]&&e.choices[0].message,t=o&&o.tool_calls||[];return Array.isArray(t)?t.map((e=>{const o=e&&e.function||{};return{id:e&&e.id||"",name:o.name||e&&e.name||"",args:parseArgs(o.arguments)}})).filter((e=>e.name)):[]}function proTurnPrompt(e){const o=Array.isArray(e.prompt)?flattenContent(e.prompt):e.prompt;if("string"==typeof o&&o.trim())return o;const t=Array.isArray(e.messages)?e.messages:[];for(let e=t.length-1;e>=0;e-=1){const o=t[e];if(!o||"user"!==o.role)continue;const r=flattenContent(o.content);if(r.trim())return r}return o}function assistantText(e){const o=e&&e.choices&&e.choices[0]&&e.choices[0].message;return o&&"string"==typeof o.content&&o.content||""}function finishReasonOf(e){const o=e&&e.choices&&e.choices[0];return o&&o.finish_reason||e&&e.stop_reason||""}function isTruncated(e){const o=finishReasonOf(e);return"length"===o||"max_tokens"===o}function reasoningTextOf(e){if(!e)return"";const o=e.choices&&e.choices[0],t=o&&o.message||{};if(Array.isArray(t.content)){const e=t.content.filter((e=>e&&("thinking"===e.type||"reasoning"===e.type))).map((e=>e.thinking||e.text||"")).join("");if(e)return e}const r=t.content&&"object"==typeof t.content?t.content.reasoning_content:"",n=[t.reasoning_content,t.reasoning,o&&o.reasoning_content,e.reasoning_content,e.reasoning,r];for(const e of n)if("string"==typeof e&&e)return e;return""}function reasoningTokensOf(e){if(!e)return 0;const o=e.choices&&e.choices[0],t=o&&o.message||{},r=e.usage||{},n=r.completion_tokens_details||r.output_tokens_details||{},s=[t.thinking_tokens,t.reasoning_tokens,o&&o.thinking_tokens,e.thinking_tokens,n.reasoning_tokens,n.thinking_tokens];for(const e of s)if("number"==typeof e&&Number.isFinite(e)&&e>0)return e;return 0}function reasonedButSilent(e){return!assistantText(e)&&(""!==reasoningTextOf(e)||reasoningTokensOf(e)>0)}const REASONING_RETRY_FLOOR=32768;function retryBudgetFor(e,o){const t=doubledBudget(e.maxTokens);return o&&ladderRung(e.maxTokens)?Math.max(t,REASONING_RETRY_FLOOR):t}function ladderRung(e){const o=Number(e);return Number.isFinite(o)&&Object.values(EFFORT_TOKEN_BUDGET).includes(o)}function doubledBudget(e){const o=Number(e)||0;return o>0?2*o:8192}function statedCapOf(e){const o=e=>{const o=Number(e);return Number.isFinite(o)&&o>0?o:void 0};return e&&Object.prototype.hasOwnProperty.call(e,"statedMaxTokens")?o(e.statedMaxTokens):o(e&&e.maxTokens)}const EMPTY_TURN_NUDGE="Your previous reply came back empty — it contained no answer and no tool call. Write your answer now, using only the information already gathered above. No tools are available in this reply, so do not call any: respond in plain prose or markdown.",THOUGHT_ONLY_NUDGE="Your previous round was spent entirely on hidden reasoning and produced no visible reply. Answer the user directly and briefly now. Do not reason, explain, or think first — write only the answer, no tools.",FINAL_ANSWER_NUDGE="Write your answer now, in plain prose, using only what is already in this conversation. If your information is incomplete, say what you have and what is missing — an incomplete answer is the expected outcome here and is better than none. No tools, no preface.",RECOVERY_ROUNDS=2,UNMUTATED_TURN_NUDGE="You ended the turn without changing any file, but this request asked for a change. The tools are still available in this reply: make the edit now with editFile or writeFile. If you already know what to change, change it — describing the fix is not the fix. If you genuinely cannot, say precisely what blocks you.",MUTATION_INTENT_RE=new RegExp("\\b(?:fix|implement|add|create|write|refactor|rename|remove|delete|replace|update|patch|migrate|convert|make\\s+(?:it|them|this|that|the|sure)|change|correct|resolve|repair|address|apply|introduce|support|wire\\s+up)\\b","i");function wantsMutation(e,o,t){if(o)return!1;if(!(t>0))return!1;const r=String(e||"");return!!r.trim()&&!/\?\s*$/.test(r.trim())&&MUTATION_INTENT_RE.test(r)}function emptyTurnError({cls:e,model:o,finishReason:t,reasoningChars:r,reasoningTokens:n,effort:s,recoveryRounds:a}){const i=Number(a)||0,l=Number(n)||0,c=new Error(`The model returned no answer after ${e}/${o} was asked to summarise its results`+(i?`, and ${i} extra recovery call${1===i?"":"s"} with a larger budget and a changed ask came back empty too`:"")+` (stop reason: ${t||"none"}`+(s?`, effort: ${s}`:"")+(r?`, hidden reasoning: ${r} chars and no visible text`:l>0?`, ~${l} thinking tokens billed and no visible text`:"")+"). "+(r||l>0?"Every one of those calls spent its output on hidden reasoning instead of writing a word, so this is the model rather than the budget: pick a model that answers without a thinking pass, or ask for a smaller piece of work.":"No visible text came back from any of those calls. Send the request again, in smaller pieces, or from a different model."));return c.status=502,c}function createLocalEngine({aegis:e,settings:o,tools:t,promptBuilder:r,recallProvider:n,env:s,getConfirmMode:a,localTransport:i=localTransport,fetchImpl:l,gitScope:c}){const d=new Map,u=t||toolsModule,f=r&&r.buildSystemPrompt||promptModule.buildSystemPrompt,p=require("./session-rounds.js"),m=()=>{if("function"==typeof a)return!1!==a();if(o&&"function"==typeof o.getConfirmMode){const e=o.getConfirmMode();return void 0===e||Boolean(e)}return!0},g=new Map,h=new Map,y=new Map,k=new Map,v=new Map;function b(e){return`${e} was not executed — the user denied this tool for this conversation. Do NOT retry it and do NOT attempt the same effect by another route (another command, a writeFile instead of an edit, a subagent). Stop calling tools and reply in plain text: say what you were trying to do, what you need, and that the user can re-enable ${e} to let it proceed.`}function E(e,o,t,r){return new Promise((n=>{if(t&&t.aborted)return void n(!1);const s=randomUUID();let a=!1;const i=()=>l(!1),l=e=>{a||(a=!0,v.delete(s),t&&t.removeEventListener("abort",i),n(e))};t&&t.addEventListener("abort",i,{once:!0}),v.set(s,{resolve:l}),"function"==typeof o?o({delta:"",rounds:{id:s,sessionId:e,spent:r.spent,extensions:r.extensions,max:r.max,size:r.size}}):l(!1)}))}async function w(e,o,t){const r=normalizeToolArgs(u,e,o,t||{});if(!r.ok)return{ok:!1,error:r.error};o=r.args;const n=t&&t.guard;if(n&&"exec"===e){const e=blocksDestructive(n,o&&o.command);if(!e.ok)return{ok:!1,error:e.reason}}const s=covenant.preActionAssert({tool:e,args:o||{}});if(!s.allowed){const t=covenant.bindRefusal({tool:e,args:o||{}},s);return{ok:!1,error:`refused by the ÆGIS covenant — ${s.clause} (${s.label}): ${s.reason}`,covenant:t}}const a=await u.executeTool(e,o,t);return n&&("writeFile"===e||"editFile"===e)&&a&&!1!==a.ok&&recordWrite(n,o&&o.file_path),a}async function T(e,{toolCtx:o,rootSessionId:t,rootOnDelta:r,signal:n}){const{name:s}=e,a=normalizeToolArgs(u,s,e.args,o||{});if(!a.ok)return{ok:!1,error:a.error};const i=a.args;if(!u.MUTATING_TOOLS.has(s))return w(s,i,o);if(!m())return w(s,i,o);if(function(e,o){const t=g.get(e);return Boolean(t&&t.has(o))}(t,s))return w(s,i,o);if(function(e,o){const t=h.get(e);return Boolean(t&&t.has(o))}(t,s))return{ok:!1,error:b(s)};let l=null;if(("writeFile"===s||"editFile"===s)&&(l=u.previewMutation(s,i,o||{}),!l.ok))return{ok:!1,error:l.error};const c=await function(e,o,t,r){return new Promise((n=>{if(t&&t.aborted)return void n("cancel");const s=randomUUID();let a=!1;const i=()=>l("cancel"),l=e=>{a||(a=!0,k.delete(s),t&&t.removeEventListener("abort",i),n(e))};t&&t.addEventListener("abort",i,{once:!0}),k.set(s,{resolve:l}),"function"==typeof o?o({delta:"",approval:{id:s,sessionId:e,tool:r.tool,args:r.args,diff:r.diff||null}}):l("cancel")}))}(t,r,n,{tool:s,args:i,diff:l&&l.diff});if("deny"===c)return function(e,o){h.has(e)||h.set(e,new Set),h.get(e).add(o)}(t,s),{ok:!1,error:b(s)};if("session"!==c&&"once"!==c)return{ok:!1,error:`${s} was not executed — the request was cancelled.`};if("session"===c&&function(e,o){g.has(e)||g.set(e,new Set),g.get(e).add(o)}(t,s),l){const e=u.applyChecked(s,i,l,o||{});return e&&!1!==e.ok&&o&&o.guard&&recordWrite(o.guard,i&&i.file_path),e}return w(s,i,o)}function _(e){return hostEnv(s||{},e&&e.env||{},e)}async function S(o,t){if("aegis"===o){const o=!t.singlePass&&(!!t.autonomous||void 0);return e.chatCompletion({prompt:t.prompt,system:t.system,messages:t.messages,model:t.model,mode:t.mode,maxTokens:t.statedMaxTokens,stream:!1!==t.stream,includeUsage:!0,onStream:t.onDelta,onReasoning:t.onReasoning,idleTimeoutMs:t.idleTimeoutMs,signal:t.signal,extra:{aegis_recall:!0,...t.recallDeep?{aegis_recall_deep:!0}:{},session:t.sessionId,...void 0===o?{}:{brain:o},...!1===o?{mode:"brain"}:{},...t.effort?{effort:t.effort}:{},...!0===o&&t.workers?{workers:t.workers}:{},...t.tools.length?{tools:t.tools}:{},...t.toolChoice?{tool_choice:t.toolChoice}:{}},agentKey:t.tools.length&&(process.env.AEGIS_AGENT_KEY||"").trim()||void 0})}if("byok"===o){const{provider:o,model:r}=splitByokModel(t.model),n=canonicalModelId(o,r),s=nativeEffort(o,n,t.effort);try{return await e.byokChatCompletion({provider:o,model:n,providerKey:t.apiKey,baseURL:t.cfg&&t.cfg.baseURL,prompt:t.prompt,system:t.system,messages:t.messages,maxTokens:t.maxTokens,tools:t.tools,toolChoice:t.toolChoice,effort:s&&"effort"===s.field?s.level:void 0,reasoningEffort:s&&"reasoning_effort"===s.field?s.level:void 0,stream:!0,onStream:t.onDelta,signal:t.signal})}catch(e){if(e&&402===e.status){const e=new Error("byok: this account has no AEGIS balance left, and the BYOK handling fee is billed there — your provider key is still valid, this is not a key problem. Top up the account, then try again (or /class aegis to use the pooled lane).");throw e.status=402,e}throw e}}if("local"===o){const e=t.cfg&&t.cfg.baseURL||i.DEFAULT_BASE,o=o=>i.chat({baseURL:e,model:t.model,prompt:t.prompt,system:t.system,messages:t.messages,maxTokens:t.maxTokens,signal:t.signal,onDelta:t.onDelta,...o&&t.tools.length?{tools:t.tools,toolChoice:t.toolChoice}:{}});try{return await o(!0)}catch(e){if(t.tools.length&&e&&400===e.status)return o(!1);throw e}}if("pro"===o){const e=t.sessionKey||t.rootSessionId||t.sessionId,o=e?y.get(e):null,r=function(e){const o=[],t=e=>String(e||"").replace(/[\\/]+$/,""),r=t(e),n=e=>{const n=t(e);n&&n!==r&&!o.includes(n)&&o.push(n)};let s=c;if(void 0===s)try{s=require("./git-scope.js")}catch{s=null}try{s&&"function"==typeof s.gitRoot&&n(s.gitRoot(e))}catch{}try{credentialsLib&&"function"==typeof credentialsLib.aegisHome&&n(credentialsLib.aegisHome())}catch{}return o}(t.cwd),n=await claudePro.runClaudePro({prompt:proTurnPrompt(t),model:t.model&&"default"!==t.model?t.model:void 0,system:t.system,cwd:t.cwd,addDir:r,resumeSessionId:o||void 0,gate:"function"==typeof a?!a():void 0,signal:t.signal,onDelta:t.onDelta,onSpawn:(e,o)=>{t.onDelta&&o&&t.onDelta({delta:"",note:claudePro.childLine(o)})}});return e&&n&&n.sessionId&&!n.error&&y.set(e,n.sessionId),n}throw new Error(`dispatch: unknown model class ${JSON.stringify(o)} — this build ships 'aegis', 'byok', 'local' and 'pro' only`)}async function A(t,r){const n=t&&t.class,s=t&&t.model,a=reasoningBudget("byok"===n?splitByokModel(s).model:s,t&&t.maxTokens,t&&t.effort),l=statedCapOf(t),c="aegis"===n&&Boolean(t&&t.autonomous),m=Boolean(t&&t.roundsAsk),g=t&&t.sessionId||randomUUID(),h=Number.isInteger(t&&t.depth)?t.depth:0,y=t&&t.rootSessionId||g,k=t&&t.rootOnDelta||r,v="function"==typeof r?e=>e&&r({reasoning:e}):void 0,b=new AbortController;d.set(g,b);const w=b.signal,A=!(t&&!1===t.tools),x=A?u.toolsFor({includeSubagent:h<4}):[],N=t&&t.toolChoice||null,O=t&&t.system||f(_(t)),R=Array.isArray(t&&t.messages)?t.messages.filter(Boolean).slice():[];let U=R.length,F=t&&t.prompt||"";const D=String(F||""),L=Array.isArray(t&&t.attachments)?t.attachments.filter((e=>e&&"object"==typeof e)).slice(0,attachmentsModule.MAX_ATTACHMENTS):[];let I=L.length?attachmentsModule.buildContent(F,L):F,C=null;const P=_(t),B=P.cwd,q={getShell:()=>C||(C=new ShellSession({cwd:_(t).cwd})),signal:w,cwd:B,desktopdir:P.desktopdir};try{const d="byok"===n?splitByokModel(s):null,f="byok"===n?o.get(byokNamespace(d.provider))||{}:"local"===n&&o.get("local")||{},b="byok"===n?o.rawKey(byokNamespace(d.provider)):null,_="byok"!==n?null:b||providerKeyFromEnv(d.provider);if(!("byok"!==n||d.provider&&d.model)){const e=new Error('byok: model must be "<provider>:<model>" (pick one from /models) — got '+JSON.stringify(s||""));throw e.status=400,e}if("byok"===n&&!_){const e="anthropic"===d.provider?claudePro.claudeProStatus({env:process.env}):null,o=providerKeyRecord(d.provider).rejected,t=new Error(o?`${o}. That is why this turn has no ${d.provider} key: an env value that short is a paste that lost its payload, not a credential. Fix ${o.split(" ")[0]} in ~/.aegiscode/.env (or the shell that exported it) — or skip keys entirely: /byok-key ${d.provider} <key> to set one here.`:e&&e.loggedIn?`No Anthropic API key on this machine — an "anthropic:…" id is served by your own console key, which a Claude subscription is not. Use the subscription instead: /class pro (it spends your Claude Code ${e.subscription||"Pro"} plan through the claude CLI) — or add a real console key: /byok-key anthropic <key>.`:`No key for "${d.provider}" yet. Easiest fix: /class aegis (uses your AEGIS key, no setup) — or add this provider's own key: /byok-key ${d.provider} <key>.`);throw t.status=400,t}if("byok"===n&&!e.apiKey){const e=new Error("No AEGIS key connected yet. Easiest fix: /class aegis (skips BYOK entirely) — or add your AEGIS key with /login, then try again.");throw e.status=401,e}if("local"===n){const e=i.remoteRefusal(f.baseURL||i.DEFAULT_BASE);if(e)throw e}if("byok"===n&&"custom"===d.provider&&!(f.baseURL||"").trim()){const e=new Error('No endpoint saved for the "custom" provider — its key is on this machine but the address it dials is not, and no default exists for a vendor AEGIS does not know. Fix: /model-add custom <https-base-url> <api-key> <model-id> (writes both halves), or the endpoint field in Settings › Provider (custom).');throw e.status=400,e.code="custom_endpoint_missing",e}const C={cls:n,model:s,mode:t&&t.mode,maxTokens:a,statedMaxTokens:l,autonomous:c,sessionId:g,signal:w,onDelta:r,cfg:f,apiKey:_,toolChoice:N,cwd:B,rootSessionId:y,sessionKey:t&&t.sessionKey||void 0,effort:t&&t.effort,workers:t&&t.workers,recallDeep:t&&!0===t.recallDeep,singlePass:t&&!0===t.singlePass,onReasoning:v,idleTimeoutMs:c?9e5:void 0,stream:!t||!1!==t.stream};let P=!1,j=!1;const K=c?"AEGIS_AUTONOMOUS_MAX_ROUNDS":"AEGIS_CHAT_MAX_ROUNDS",$=(()=>{const e=Number.parseInt(process.env[K]||"",10);return Number.isFinite(e)&&e>0?e:0})(),G=$||(c?40:24);let Y=p.keyFor(t,R),W=p.take(Y);if(!W&&!p.isStatedKey(t)){const e=p.adopt();e&&(W=e.entry,Y=e.key)}if(W){const e=p.resumePreamble(W);0===R.length?Array.isArray(W.messages)&&W.messages.length&&R.push(...W.messages):Array.isArray(W.added)&&W.added.length&&R.push(...W.added),F?(F=`${e}\n\n${F}`,I=L.length?attachmentsModule.buildContent(F,L):F):(R.push({role:"user",content:e}),I=""),k&&k({delta:`\n\n[resuming work this session left unfinished at ${W.rounds} tool rounds`+(W.interruptions>1?` (cut off ${W.interruptions}×)`:"")+"…]\n"})}let z=$||G+(W?p.bonus(G):0),H=0;const V=G,X=8;let J=0;const Q={calls:0},Z=["input_tokens","output_tokens","prompt_tokens","completion_tokens","total_tokens","cache_read_input_tokens","cache_creation_input_tokens","prompt_cache_hit_tokens","prompt_cache_miss_tokens","reasoning_tokens","thinking_tokens"],ee=e=>{const o=e&&e.usage;if(o&&"object"==typeof o){Q.calls+=1;for(const e of Z)"number"==typeof o[e]&&Number.isFinite(o[e])&&(Q[e]=(Q[e]||0)+o[e]);if("number"!=typeof o.total_tokens){const e=(o.prompt_tokens??o.input_tokens??0)+(o.completion_tokens??o.output_tokens??0);e&&(Q.total_tokens=(Q.total_tokens||0)+e)}}},oe=e=>e&&"object"==typeof e&&Q.calls?{...e,usage:{...Q}}:e,te=()=>{if(""===I)return;const e=R[R.length-1],o=e&&"user"===e.role?flattenContent(e.content):null;e&&"user"===e.role&&o===flattenContent(I)||R.push({role:"user",content:I}),F="",I=""};U=R.length;const re=u&&u.MUTATING_TOOLS||new Set;let ne=0,se=0,ae=!1;for(;;){if(H>=z){if(m&&J<X&&!w.aborted&&await E(y,k,w,{spent:z,extensions:J+1,max:X,size:V})){J+=1;const e=z;z+=V,R.push({role:"user",content:`You have used all ${e} tool rounds allowed for this turn; ${V} more have been granted (do not restart). Continue the task from exactly where you stopped — do not re-plan, do not repeat work already done, and finish with an answer.`});continue}const e=m?"":`, or raise ${K} for a longer single turn`,o=`[stopped at ${z} tool rounds`+(Q.total_tokens?`, ${Q.total_tokens.toLocaleString()} tokens`:"")+". This session holds the work: your next message here resumes it automatically"+` (with a continuation preamble)${e}.]`,t=p.record(Y,{rounds:H,tokens:Q.total_tokens||0,note:o,chain:W?W.interruptions:0,messages:R,added:R.slice(U)});return k&&k({delta:`\n\n${o}`}),oe({model:C.model,choices:[{message:{content:o},finish_reason:"length"}],stoppedOnRounds:!0,heldForSession:!0,heldRounds:t.rounds,sessionInterruptions:t.interruptions,resumedFrom:Y})}H+=1;const e={...C,system:O,messages:R,prompt:I,tools:x,recallDeep:C.recallDeep&&1===H};let o;if(o=await S(n,e),ee(o),w.aborted)return oe(o);if(!P&&!assistantText(o)&&(isTruncated(o)||reasonedButSilent(o))){P=!0;const t=reasonedButSilent(o);if(o=await S(n,{...e,singlePass:!0,recallDeep:!1,effort:t?"high":e.effort,maxTokens:retryBudgetFor(e,t),statedMaxTokens:e.statedMaxTokens?doubledBudget(e.statedMaxTokens):void 0}),ee(o),w.aborted)return oe(o)}const a=x.length?extractToolCalls(o):[];if(!a.length){if(assistantText(o)||j||!A){if(!ae&&A&&wantsMutation(D,se>0,ne)){ae=!0,te(),R.push({role:"assistant",content:assistantText(o)}),R.push({role:"user",content:UNMUTATED_TURN_NUDGE}),k&&k({delta:""});continue}return oe(o)}j=!0,te(),R.push({role:"user",content:reasonedButSilent(o)?THOUGHT_ONLY_NUDGE:EMPTY_TURN_NUDGE});const t={...e,singlePass:!0,recallDeep:!1,messages:R,prompt:"",tools:[]};o=await S(n,t);let r=t.maxTokens,a=t.effort;if(ee(o),w.aborted)return oe(o);if(!assistantText(o)&&(isTruncated(o)||reasonedButSilent(o))){const e=reasonedButSilent(o);if(r=retryBudgetFor(t,e),a=e?"high":t.effort,o=await S(n,{...t,effort:a,maxTokens:r,statedMaxTokens:t.statedMaxTokens?doubledBudget(t.statedMaxTokens):void 0}),ee(o),w.aborted)return oe(o)}const i=(()=>{const e=Number(r)||0;if(!e)return r;const o={maxTokens:r};return t.statedMaxTokens&&(o.statedMaxTokens=t.statedMaxTokens),Math.max(e,retryBudgetFor(o,!0))})();let l=0;for(;!assistantText(o)&&l<2&&!w.aborted;){const e=reasonedButSilent(o);if(l+=1,R.push({role:"user",content:e?1===l?THOUGHT_ONLY_NUDGE:FINAL_ANSWER_NUDGE:EMPTY_TURN_NUDGE}),e&&(a="high"),r=i,o=await S(n,{...t,messages:R,effort:a,maxTokens:r,statedMaxTokens:t.statedMaxTokens?doubledBudget(t.statedMaxTokens):void 0}),ee(o),w.aborted)return oe(o)}if(!assistantText(o))throw emptyTurnError({cls:n,model:s,effort:a,recoveryRounds:l,finishReason:finishReasonOf(o),reasoningChars:reasoningTextOf(o).length,reasoningTokens:reasoningTokensOf(o)});return oe(o)}te(),R.push({role:"assistant",content:assistantText(o),tool_calls:a.map((e=>({id:e.id,type:"function",function:{name:e.name,arguments:JSON.stringify(e.args)}})))});const i=new WeakMap,c=e=>{if("exec"!==e.name)return null;if(i.has(e))return i.get(e);const o=planExec(e.args&&e.args.command,{baseCwd:B});return i.set(e,o),o},d=e=>{if(e.name===u.SUBAGENT_TOOL)return!1;if(!re.has(e.name))return!0;const o=c(e);return Boolean(o&&o.oneShot)},f=[];for(const e of a){const o=f[f.length-1];d(e)&&o&&o.parallel?o.calls.push(e):f.push({parallel:d(e),calls:[e]})}const g=async e=>{r&&r({delta:"",tool:{name:e.name,args:e.args,id:e.id,cwd:B,phase:"run"}});const o=c(e),a=o&&o.oneShot?{...q,oneShotExec:!0,cwd:o.cwd||q.cwd}:q,i=e.name===u.SUBAGENT_TOOL?await M(e.args,{cls:n,model:s,statedMaxTokens:l,effort:t&&t.effort,mode:t&&t.mode,parentSignal:w,depth:h,rootSessionId:y,rootOnDelta:k}):await T(e,{toolCtx:a,rootSessionId:y,rootOnDelta:k,signal:w});return i&&i.usage&&ee({usage:i.usage}),r&&r({delta:"",tool:{name:e.name,args:e.args,ok:i.ok,id:e.id,cwd:B,phase:"done"}}),i};for(const e of f){const o=e.parallel&&e.calls.length>1?await Promise.all(e.calls.map((e=>g(e)))):[await g(e.calls[0])];e.calls.forEach(((e,t)=>{const r=o[t];re.has(e.name)&&(ne+=1,r&&r.ok&&(se+=1)),R.push({role:"tool",tool_call_id:e.id,name:e.name,content:u.toolResultText(r)})}))}}}catch(e){throw w.aborted&&e&&"object"==typeof e&&(e.aegisCancelled=!0),e}finally{C&&C.dispose(),d.delete(g)}}async function M({description:e,subagent_type:o,prompt:t}={},{cls:r,model:n,statedMaxTokens:s,effort:a,mode:i,parentSignal:l,depth:c,rootSessionId:d,rootOnDelta:u}={}){const f=String(t||e||"").trim();if(!f)return{ok:!1,error:"task requires a prompt"};const p=o&&"general"!==o?agentRoleLabel(o):"general",m=agentSystemPrompt(o),g=randomUUID();let h;if(l){if(l.aborted)return{ok:!1,error:"aborted"};h=()=>x(g),l.addEventListener("abort",h,{once:!0})}try{const e=await A({class:r,model:n,mode:i,system:m,prompt:f,sessionId:g,depth:(c||0)+1,rootSessionId:d,rootOnDelta:u,statedMaxTokens:s,effort:a},(()=>{})),o=assistantText(e),t=e&&e.usage?{usage:e.usage}:{};return o?{ok:!0,output:o,...t}:{ok:!1,error:`subagent (${p}) produced no output`,...t}}catch(e){return{ok:!1,error:`subagent (${p}) failed: ${e&&e.message?e.message:e}`}}finally{l&&h&&l.removeEventListener("abort",h)}}function x(e){const o=d.get(e);return o&&o.abort(),{ok:Boolean(o)}}return{CLASSES:CLASSES,listClasses:async function(){return CLASSES.map((t=>{if("aegis"===t.class)return{...t,configured:Boolean(e.apiKey)};if("byok"===t.class){const e=(o.list()||[]).some((e=>!(!e||"string"!=typeof e.provider||!e.provider.startsWith("byok:"))&&(!!e.configured||Boolean(providerKeyFromEnv(e.provider.slice(BYOK_NAMESPACE_PREFIX.length))))));return{...t,configured:e}}if("local"===t.class)return{...t,configured:!0};if("pro"===t.class){const e=claudePro.claudeProStatus({env:process.env}),o=claudePro.seamAvailable();return{...t,configured:e.loggedIn,status:e,seam:o}}return{...t,configured:!1}}))},listModels:async function(t){if("aegis"===t){if(!e.apiKey)return{class:t,models:[],needsKey:!0};const o=await e.listModels();return{class:t,models:offerableCatalog(normalizeCatalog(o&&o.models))}}if("byok"===t){let r=[],n=null,s=!1,a=null;try{const o=await e.byokProviders();r=withUserModels(withCatalog(withByokAdditions(o&&o.providers||[]))),n=o&&o.fee||null}catch(e){r=[],s=!0,a=e&&e.message||String(e)}const i=[];for(const e of r){if(!e||!e.id)continue;const t=o.get(byokNamespace(e.id))||{},r=providerKeyRecord(e.id),n=r.key||"",s=Array.isArray(e.models)?e.models:[];for(const o of s){const s="string"==typeof o?o:o&&o.id;s&&i.push({id:`${e.id}:${s}`,label:`${e.label||e.id} — ${s}`,provider:e.id,configured:Boolean(t.configured||n),keyRejected:r.rejected||null})}}return{class:t,models:i,providers:r,needsProviderKey:i.length>0&&!i.some((e=>e.configured)),needsAegisKey:!e.apiKey,fee:n,providersFailed:s,providersError:a,unmatchedProviders:unmatchedUserProviders(r)}}if("local"===t){const e=(o.get("local")||{}).baseURL||i.DEFAULT_BASE,r=await i.probe(e);if(!r.running)return{class:t,models:[],baseURL:r.baseURL,needsDaemon:!0};let n=[],s=!0;try{n=await i.listTags(e)}catch{s=!1}return{class:t,models:n,baseURL:r.baseURL,listed:s}}if("pro"===t){const e=claudePro.claudeProStatus({env:process.env});return{class:t,models:claudePro.PRO_MODELS.map((o=>({id:o.id,label:o.label,note:o.note,configured:e.loggedIn}))),needsProviderKey:!1,needsAegisKey:!1,subscription:e.subscription,loggedIn:e.loggedIn,credentialFile:e.file,shadowed:e.shadowed||null,seam:claudePro.seamAvailable()}}throw new Error(`listModels: unknown model class ${JSON.stringify(t)} — this build ships 'aegis', 'byok', 'local' and 'pro' only`)},chat:A,cancel:x,respondApproval:function(e,o){const t=k.get(e);return t?(k.delete(e),t.resolve("session"===o||"once"===o?o:"deny"),{ok:!0}):{ok:!1}},respondRoundsAsk:function(e,o){const t=v.get(e);return t?(v.delete(e),t.resolve(!0===o||"continue"===o),{ok:!0}):{ok:!1}},clearSessionApprovals:function(e){return g.delete(e),h.delete(e),y.delete(e),{ok:!0}},settings:o,unloadLocalModels:function(){return i.unloadAll()},userModels:()=>loadUserModels(),addUserModel:(e,o)=>addUserModel(e,o),removeUserModel:(e,o)=>removeUserModel(e,o),discoverModels:async e=>{const t=String(null==e?"":e).trim().toLowerCase(),r=function(e){const t=String(null==e?"":e).trim().toLowerCase();if(!t)return"";try{if(o&&"function"==typeof o.rawKey){const e=o.rawKey(byokNamespace(t));if("string"==typeof e&&e.trim())return e.trim()}}catch{}return providerKeyFromEnv(t)}(t),n=await discoverVendorModels(t,{key:r,fetchImpl:l});if(!n||!n.ok)return n;const s=[];try{const e=loadUserModels().map;for(const o of Array.isArray(e[t])?e[t]:[])s.push(o)}catch{}return{...n,declared:s,endpoint:(vendorEndpointFor(t)||{}).url||""}},addUserModels:(e,o)=>{const t=Array.isArray(o)?o:[],r={provider:e,added:0,already:[],failed:[],capped:0,file:""};for(const o of t)try{const t=addUserModel(e,o);r.file=t.file||r.file,t.added?r.added+=1:r.already.push(t.model)}catch(e){const n=e&&e.message||String(e);if(/the cap/.test(n)){r.capped=t.length-r.added-r.already.length-r.failed.length;break}r.failed.push({id:String(o),reason:n})}return r},canDiscoverModels:e=>canDiscoverVendorModels(e),discoverableProviders:()=>discoverableProviders()}}module.exports={CLASSES:CLASSES,createLocalEngine:createLocalEngine,extractToolCalls:extractToolCalls,parseArgs:parseArgs,reasoningBudget:reasoningBudget,nativeEffort:nativeEffort,hostEnv:hostEnv};
3
+ "use strict";const{randomUUID:randomUUID}=require("node:crypto"),os=require("node:os"),fs=require("node:fs"),toolsModule=require("./tools.js"),attachmentsModule=require("./attachments.js"),{flattenContent:flattenContent}=attachmentsModule,promptModule=require("./prompt.js"),localTransport=require("./local.js"),{ShellSession:ShellSession}=require("./shell.js"),{planExec:planExec}=require("./exec-plan.js"),claudePro=require("./claude-pro.js"),{agentSystemPrompt:agentSystemPrompt,agentRoleLabel:agentRoleLabel}=require("./agents.js"),{beginTurnGuard:beginTurnGuard,recordWrite:recordWrite,blocksDestructive:blocksDestructive}=require("./turn-guard.js"),{acquireWorktreeLock:acquireWorktreeLock,releaseWorktreeLock:releaseWorktreeLock}=require("./worktree-lock.js"),covenant=require("./covenant.js");let envFile=null;try{envFile=require("../../../client/env-file.js")}catch{try{envFile=require("../../vendor/env-file.js")}catch{envFile=null}}let platformLib=null;try{platformLib=require("../../../client/platform.js")}catch{try{platformLib=require("../../vendor/platform.js")}catch{platformLib=null}}let credentialsLib=null;try{credentialsLib=require("../../../client/credentials.js")}catch{try{credentialsLib=require("../../vendor/credentials.js")}catch{credentialsLib=null}}const PRO_TOOL_MAP=Object.freeze({Write:"writeFile",Edit:"editFile",MultiEdit:"editFile",NotebookEdit:"editFile",Bash:"exec",BashOutput:"exec"}),PRO_PLAN_MODE_SAFE=Object.freeze(new Set(["Read","Glob","Grep"]));function proAskArgs(e,t){const o=e&&"object"==typeof e?e:{};return"exec"===t?"string"==typeof o.command?{command:o.command}:{}:"writeFile"===t?"string"==typeof o.file_path?{file_path:o.file_path,content:o.content}:{}:"editFile"===t?Array.isArray(o.edits)?{file_path:o.file_path,edits:o.edits}:"string"==typeof o.file_path?{file_path:o.file_path,old_string:o.old_string,new_string:o.new_string,replace_all:!0===o.replace_all}:{}:o}function normalizeToolArgs(e,t,o,n){const r=e&&"function"==typeof e.normalizeArgs&&e.normalizeArgs||"function"==typeof toolsModule.normalizeArgs&&toolsModule.normalizeArgs||null;return r?r(t,o,n):{ok:!0,args:o&&"object"==typeof o?o:{},error:null}}function detectVcs(e){if(!e)return null;try{const t=require("node:fs"),o=require("node:path");let n=o.resolve(String(e));for(let e=0;e<8;e+=1){if(t.existsSync(o.join(n,".git")))return"git";const e=o.dirname(n);if(e===n)break;n=e}return""}catch{return null}}function hostEnv(e={},t={},o=null){const n=e||{},r=t||{},s=(e,t)=>null!=r[e]?r[e]:t;let a=n.homedir,i=n.cwd;try{a||(a=os.homedir()),i||(i=process.cwd())}catch{}let l=n.shell,c=n.shellKind;try{if(!l||!c){const e=require("./shell.js").resolveSessionShell();l=l||e.cmd,c=c||e.kind}}catch{}let d=n.desktopdir;try{!d&&platformLib&&(d=platformLib.desktopDir())}catch{}let u=n.dataDir;try{!u&&credentialsLib&&(u=credentialsLib.aegisHome())}catch{}let f=n.locale,p=n.localeName;try{!f&&platformLib&&"function"==typeof platformLib.appLocale&&(f=platformLib.appLocale()),f&&!p&&platformLib&&"function"==typeof platformLib.languageName&&(p=platformLib.languageName(f))}catch{}return{platform:s("platform",n.platform||process.platform),arch:s("arch",n.arch||process.arch),homedir:s("homedir",a),desktopdir:s("desktopdir",d),dataDir:s("dataDir",u),locale:s("locale",f),localeName:s("localeName",p),languages:s("languages",n.languages),cwd:s("cwd",i),vcs:s("vcs",null!=n.vcs?n.vcs:detectVcs(i)),shell:s("shell",l),shellKind:s("shellKind",c),roots:s("roots",n.roots),appVersion:s("appVersion",n.appVersion),model:s("model",o&&o.model)}}function requireSharedBrain(){const e=[()=>require("../../../client/brain-catalog.js"),()=>require("../../vendor/brain-catalog.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}function requireSharedByokCatalog(){const e=[()=>require("../../../client/byok-catalog.js"),()=>require("../../vendor/byok-catalog.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}function requireSharedUserModels(){const e=[()=>require("../../../client/user-models.js"),()=>require("../../vendor/user-models.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}function requireSharedCatalogClient(){const e=[()=>require("../../../client/catalog-client.js"),()=>require("../../vendor/catalog-client.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}function requireSharedModelDiscovery(){const e=[()=>require("../../../client/model-discovery.js"),()=>require("../../vendor/model-discovery.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}const WORKTREE_LOCK_WAIT_MS=1500,MAX_SUBAGENT_DEPTH=4,CLASSES=[{class:"aegis",label:"Aegis Cloud",kind:"cloud"},{class:"byok",label:"Bring your own key",kind:"cloud"},{class:"local",label:"Local model",kind:"local"},{class:"pro",label:"Claude Code Pro",kind:"subscription"}],BYOK_NAMESPACE_PREFIX="byok:";function byokNamespace(e){return`${BYOK_NAMESPACE_PREFIX}${e}`}function splitByokModel(e){const t="string"==typeof e?e:"",o=t.indexOf(":");return o<0?{provider:"",model:t}:{provider:t.slice(0,o),model:t.slice(o+1)}}function providerKeyRecord(e){const t={key:"",env:"",rejected:null};if(!envFile||"function"!=typeof envFile.providerKeyFromEnv)return t;try{const o=envFile.providerKeyFromEnv(e)||t;return{key:"string"==typeof o.key?o.key:"",env:"string"==typeof o.env?o.env:"",rejected:"string"==typeof o.rejected&&o.rejected?o.rejected:null}}catch{return t}}function providerKeyFromEnv(e){if(!envFile||"function"!=typeof envFile.providerKeyFromEnv)return"";try{return envFile.providerKeyFromEnv(e).key||""}catch{return""}}const DEEPSEEK_REASONING_MODEL_RE=/^deepseek-(v4(\.\d+)?-(flash|pro)|flash|pro|reasoner)$/,EFFORT_TOKEN_BUDGET={low:8192,medium:16384,high:32768,max:32768},DEEPSEEK_EFFORT={low:"low",medium:"high",high:"high"},DEEPSEEK_EFFORT_EXTRA={max:"max"},EFFORT_IDENTITY={low:"low",medium:"medium",high:"high"},EFFORT_INERT_RE=/non-reasoning/i,EFFORT_DIALECTS=[{provider:"deepseek",re:DEEPSEEK_REASONING_MODEL_RE,field:"effort",map:DEEPSEEK_EFFORT,extra:DEEPSEEK_EFFORT_EXTRA},{provider:"openai",re:/^(gpt-5|o[0-9])/i,field:"reasoning_effort",map:EFFORT_IDENTITY},{provider:"groq",re:/^(openai\/gpt-oss|qwen\/qwen3)/i,field:"reasoning_effort",map:EFFORT_IDENTITY},{provider:"xai",re:/^grok-(4\.[5-9]|[5-9])/,field:"reasoning_effort",map:EFFORT_IDENTITY},{provider:"google",re:/^gemini-(2\.5|3|[4-9])/,field:"reasoning_effort",map:{...EFFORT_IDENTITY,medium:"high"}}],AUTONOMOUS_IDLE_TIMEOUT_MS=9e5;function reasoningBudget(e,t,o){const n=Number(t);return Number.isFinite(n)&&n>0?n:DEEPSEEK_REASONING_MODEL_RE.test(String(e||""))?EFFORT_TOKEN_BUDGET["low"===o||"medium"===o||"max"===o?o:"high"]:void 0}function nativeEffort(e,t,o){const n=String(t||"");if(EFFORT_INERT_RE.test(n))return;if(null===o)return;const r="low"===o||"medium"===o?o:"max"===o?"max":"high";for(const t of EFFORT_DIALECTS)if(t.provider===e&&t.re.test(n)){const e=Object.prototype.hasOwnProperty.call(t.map,r)?t.map[r]:t.extra&&Object.prototype.hasOwnProperty.call(t.extra,r)?t.extra[r]:void 0;if(void 0===e)return;return{field:t.field,level:e}}}function normalizeCatalog(e){return Array.isArray(e)?e.map((e=>"string"==typeof e?{id:e}:e)).filter((e=>e&&e.id)):[]}const{offerableCatalog:offerableCatalog}=requireSharedBrain(),{withByokAdditions:withByokAdditions,canonicalModelId:canonicalModelId,nexusFallbackModel:nexusFallbackModel}=requireSharedByokCatalog(),{withUserModels:withUserModels,unmatchedUserProviders:unmatchedUserProviders,load:loadUserModels,addUserModel:addUserModel,removeUserModel:removeUserModel}=requireSharedUserModels(),{withCatalog:withCatalog}=requireSharedCatalogClient(),{discoverModels:discoverVendorModels,canDiscover:canDiscoverVendorModels,endpointFor:vendorEndpointFor,discoverableProviders:discoverableProviders}=requireSharedModelDiscovery();function parseArgs(e){if(null==e)return{};if("object"==typeof e)return e;try{const t=JSON.parse(String(e));return t&&"object"==typeof t?t:{}}catch{return{}}}function extractToolCalls(e){if(!e)return[];if(Array.isArray(e.toolCalls)&&e.toolCalls.length)return e.toolCalls.map((e=>({id:e.id||"",name:e.name||"",args:parseArgs(e.args)}))).filter((e=>e.name));const t=e.choices&&e.choices[0]&&e.choices[0].message,o=t&&t.tool_calls||[];return Array.isArray(o)?o.map((e=>{const t=e&&e.function||{};return{id:e&&e.id||"",name:t.name||e&&e.name||"",args:parseArgs(t.arguments)}})).filter((e=>e.name)):[]}function proTurnPrompt(e){const t=Array.isArray(e.prompt)?flattenContent(e.prompt):e.prompt;if("string"==typeof t&&t.trim())return t;const o=Array.isArray(e.messages)?e.messages:[];for(let e=o.length-1;e>=0;e-=1){const t=o[e];if(!t||"user"!==t.role)continue;const n=flattenContent(t.content);if(n.trim())return n}return t}function assistantText(e){const t=e&&e.choices&&e.choices[0]&&e.choices[0].message;return t&&"string"==typeof t.content&&t.content||""}function finishReasonOf(e){const t=e&&e.choices&&e.choices[0];return t&&t.finish_reason||e&&e.stop_reason||""}function isTruncated(e){const t=finishReasonOf(e);return"length"===t||"max_tokens"===t}function reasoningTextOf(e){if(!e)return"";const t=e.choices&&e.choices[0],o=t&&t.message||{};if(Array.isArray(o.content)){const e=o.content.filter((e=>e&&("thinking"===e.type||"reasoning"===e.type))).map((e=>e.thinking||e.text||"")).join("");if(e)return e}const n=o.content&&"object"==typeof o.content?o.content.reasoning_content:"",r=[o.reasoning_content,o.reasoning,t&&t.reasoning_content,e.reasoning_content,e.reasoning,n];for(const e of r)if("string"==typeof e&&e)return e;return""}function reasoningTokensOf(e){if(!e)return 0;const t=e.choices&&e.choices[0],o=t&&t.message||{},n=e.usage||{},r=n.completion_tokens_details||n.output_tokens_details||{},s=[o.thinking_tokens,o.reasoning_tokens,t&&t.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 reasonedButSilent(e){return!assistantText(e)&&(""!==reasoningTextOf(e)||reasoningTokensOf(e)>0)}const REASONING_RETRY_FLOOR=32768;function retryBudgetFor(e,t){const o=doubledBudget(e.maxTokens);return t&&ladderRung(e.maxTokens)?Math.max(o,REASONING_RETRY_FLOOR):o}function ladderRung(e){const t=Number(e);return Number.isFinite(t)&&Object.values(EFFORT_TOKEN_BUDGET).includes(t)}function doubledBudget(e){const t=Number(e)||0;return t>0?2*t:8192}function statedCapOf(e){const t=e=>{const t=Number(e);return Number.isFinite(t)&&t>0?t:void 0};return e&&Object.prototype.hasOwnProperty.call(e,"statedMaxTokens")?t(e.statedMaxTokens):t(e&&e.maxTokens)}const EMPTY_TURN_NUDGE="Your previous reply came back empty — it contained no answer and no tool call. Write your answer now, using only the information already gathered above. No tools are available in this reply, so do not call any: respond in plain prose or markdown.",THOUGHT_ONLY_NUDGE="Your previous round was spent entirely on hidden reasoning and produced no visible reply. Answer the user directly and briefly now. Do not reason, explain, or think first — write only the answer, no tools.",FINAL_ANSWER_NUDGE="Write your answer now, in plain prose, using only what is already in this conversation. If your information is incomplete, say what you have and what is missing — an incomplete answer is the expected outcome here and is better than none. No tools, no preface.",RECOVERY_ROUNDS=2,UNMUTATED_TURN_NUDGE="You ended the turn without changing any file, but this request asked for a change. The tools are still available in this reply: make the edit now with editFile or writeFile. If you already know what to change, change it — describing the fix is not the fix. If you genuinely cannot, say precisely what blocks you.",MUTATION_INTENT_RE=new RegExp("\\b(?:fix|implement|add|create|write|refactor|rename|remove|delete|replace|update|patch|migrate|convert|make\\s+(?:it|them|this|that|the|sure)|change|correct|resolve|repair|address|apply|introduce|support|wire\\s+up)\\b","i");function wantsMutation(e,t,o){if(t)return!1;if(!(o>0))return!1;const n=String(e||"");return!!n.trim()&&!/\?\s*$/.test(n.trim())&&MUTATION_INTENT_RE.test(n)}function emptyTurnError({cls:e,model:t,finishReason:o,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}/${t} 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: ${o||"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}function createLocalEngine({aegis:e,settings:t,tools:o,promptBuilder:n,recallProvider:r,env:s,getConfirmMode:a,getPermissionMode:i,sandbox:l,localTransport:c=localTransport,fetchImpl:d,gitScope:u,permissionRules:f}){const p=new Map,m=o||toolsModule,h=n&&n.buildSystemPrompt||promptModule.buildSystemPrompt,g=f&&"function"==typeof f.rulesVerdict?f.rulesVerdict:null,y=f&&"function"==typeof f.alwaysAllow?f.alwaysAllow:null,k=f&&"function"==typeof f.subjectFor?f.subjectFor:null,v=require("./session-rounds.js"),b=()=>{if("function"==typeof a)return!1!==a();if(t&&"function"==typeof t.getConfirmMode){const e=t.getConfirmMode();return void 0===e||Boolean(e)}return!0},w=()=>"function"==typeof i?"plan"===i():!(!t||"function"!=typeof t.getPermissionMode)&&"plan"===t.getPermissionMode();function E(e,t){return`${e} was not executed — this session is in plan mode (read-only). Plan mode may read files, search, run read-only shell commands and deploy subagents to research, but may not create, edit or delete files, run a mutating command, or install packages`+(t?` (this command: ${t})`:"")+". Do NOT retry it or attempt the same effect by another route. Finish your research and present a plan in plain text; the user exits plan mode (`/permissions mode off`) before any edit can run."}const _=new Map,T=new Map,S=new Map,x=200,A=new Map,M=require("./pro-sessions.js"),O=new Map,N=new Map;function F(e,t){if("function"!=typeof k)return e;let o="";try{o=String(k(e,t||{})||"")}catch{o=""}return`${e}\0${o}`}function R(e,t,o){_.has(e)||_.set(e,new Set),_.get(e).add(F(t,o))}function D(e,t){const o=T.get(e);return Boolean(o&&o.has(t))}function U(e,t){T.has(e)||T.set(e,new Set),T.get(e).add(t)}function I(e){if(!e)return null;try{return{existed:!0,content:fs.readFileSync(e,"utf8")}}catch(e){return e&&"ENOENT"===e.code?{existed:!1,content:null}:null}}function L(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 C(e,t,o,n){return new Promise((r=>{if(o&&o.aborted)return void r("cancel");const s=randomUUID();let a=!1;const i=()=>l("cancel"),l=e=>{a||(a=!0,O.delete(s),o&&o.removeEventListener("abort",i),r(e))};o&&o.addEventListener("abort",i,{once:!0}),O.set(s,{resolve:l}),"function"==typeof t?t({delta:"",approval:{id:s,sessionId:e,tool:n.tool,args:n.args,diff:n.diff||null,canPersist:"function"==typeof y}}):l("cancel")}))}function P(e,t,o,n){return new Promise((r=>{if(o&&o.aborted)return void r(!1);const s=randomUUID();let a=!1;const i=()=>l(!1),l=e=>{a||(a=!0,N.delete(s),o&&o.removeEventListener("abort",i),r(e))};o&&o.addEventListener("abort",i,{once:!0}),N.set(s,{resolve:l}),"function"==typeof t?t({delta:"",rounds:{id:s,sessionId:e,spent:n.spent,extensions:n.extensions,max:n.max,size:n.size}}):l(!1)}))}async function $(e,t,o,n,r){const s=normalizeToolArgs(m,e,t,o||{});if(!s.ok)return{ok:!1,error:s.error};t=s.args;const a=o&&o.guard;if(a&&"exec"===e){const e=blocksDestructive(a,t&&t.command);if(!e.ok)return{ok:!1,error:e.reason}}const i=covenant.preActionAssert({tool:e,args:t||{}});if(!i.allowed){const o=covenant.bindRefusal({tool:e,args:t||{}},i);return{ok:!1,error:`refused by the ÆGIS covenant — ${i.clause} (${i.label}): ${i.reason}`,covenant:o}}const l="writeFile"===e||"editFile"===e,c=l?I(t&&t.file_path):null,d=await m.executeTool(e,t,o);if(a&&l&&d&&!1!==d.ok&&recordWrite(a,t&&t.file_path),l&&c&&d&&!1!==d.ok){const o=I(t&&t.file_path);o&&function(e,t){if(!e)return;S.has(e)||S.set(e,[]);const o=S.get(e);o.push(t),o.length>x&&o.shift()}(n,{id:r||randomUUID(),tool:e,path:t&&t.file_path,before:c,after:o,at:Date.now()})}return d}function j(e,t){if(!e||"object"!=typeof e)return{ok:!0,content:`${t}\n${null==e?"":e}`};if(!1===e.ok||!0===e.isError){const o=e.error||e.content||"";return{...e,error:`${t}\n${o}`,content:`${t}\n${o}`}}const o=null!=e.content?e.content:null!=e.output?e.output:"";return{...e,content:`${t}\n${o}`}}async function B(e,{toolCtx:t,rootSessionId:o,rootOnDelta:n,signal:r}){const{name:s}=e,a=normalizeToolArgs(m,s,e.args,t||{});if(!a.ok)return{ok:!1,error:a.error};const i=a.args;if(!m.MUTATING_TOOLS.has(s))return $(s,i,t,o,e.id);if(w()){if("exec"===s){const n=planExec(i&&i.command,{baseCwd:t&&t.cwd||void 0});return n.oneShot?$(s,i,t,o,e.id):{ok:!1,error:E(s,n.reason)}}return{ok:!1,error:E(s)}}if(!b())return $(s,i,t,o,e.id);if(function(e,t,o){const n=_.get(e);return Boolean(n&&n.has(F(t,o)))}(o,s,i))return $(s,i,t,o,e.id);if("function"==typeof g){let n;try{n=g(s,i)}catch(e){n={verdict:null,source:"error",error:e&&e.message||String(e)}}if(n&&"deny"===n.verdict)return U(o,s),{ok:!1,error:L(s),permissionRule:n.rule||null};if(n&&"allow"===n.verdict)return $(s,i,t,o,e.id)}if(D(o,s))return{ok:!1,error:L(s)};let l=null;if(("writeFile"===s||"editFile"===s)&&(l=m.previewMutation(s,i,t||{}),!l.ok))return{ok:!1,error:l.error};const c=await C(o,n,r,{tool:s,args:i,diff:l&&l.diff});if("deny"===c)return U(o,s),{ok:!1,error:L(s)};if("session"!==c&&"once"!==c&&"always"!==c)return{ok:!1,error:`${s} was not executed — the request was cancelled.`};let d=null;if("always"===c){let e=null;if("function"==typeof y)try{e=y(s,i)}catch(t){e={ok:!1,reason:t&&t.message||String(t)}}else e={ok:!1,reason:"no durable store is wired on this host"};d=e&&e.ok?`[permission_rule] stored ${e.rule} — this command will not ask again`:`[permission_rule] nothing was stored — ${e&&e.reason||"unknown reason"}; this call was allowed once only`}if("session"===c&&R(o,s,i),l){const e=m.applyChecked(s,i,l,t||{});return e&&!1!==e.ok&&t&&t.guard&&recordWrite(t.guard,i&&i.file_path),d?j(e,d):e}const u=await $(s,i,t,o,e.id);return d?j(u,d):u}function q(e){return hostEnv(s||{},e&&e.env||{},e)}function K(e){const t=[],o=e=>String(e||"").replace(/[\\/]+$/,""),n=o(e),r=e=>{const r=o(e);r&&r!==n&&!t.includes(r)&&t.push(r)};let s=u;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{credentialsLib&&"function"==typeof credentialsLib.aegisHome&&r(credentialsLib.aegisHome())}catch{}return t}async function G(t,o){if("aegis"===t){const t=!o.singlePass&&(!!o.autonomous||void 0);return e.chatCompletion({prompt:o.prompt,system:o.system,messages:o.messages,model:o.model,mode:o.mode,maxTokens:o.statedMaxTokens,stream:!1!==o.stream,includeUsage:!0,onStream:o.onDelta,onReasoning:o.onReasoning,idleTimeoutMs:o.idleTimeoutMs,signal:o.signal,extra:{aegis_recall:!0,...o.recallDeep?{aegis_recall_deep:!0}:{},session:o.sessionId,...void 0===t?{}:{brain:t},...!1===t?{mode:"brain"}:{},...o.effort?{effort:o.effort}:{},...!0===t&&o.workers?{workers:o.workers}:{},...o.tools.length?{tools:o.tools}:{},...o.toolChoice?{tool_choice:o.toolChoice}:{}},agentKey:o.tools.length&&(process.env.AEGIS_AGENT_KEY||"").trim()||void 0})}if("byok"===t){const{provider:t,model:n}=splitByokModel(o.model),r=canonicalModelId(t,n),s=nativeEffort(t,r,o.effort);try{return await e.byokChatCompletion({provider:t,model:r,providerKey:o.apiKey,baseURL:o.cfg&&o.cfg.baseURL,prompt:o.prompt,system:o.system,messages:o.messages,maxTokens:o.maxTokens,tools:o.tools,toolChoice:o.toolChoice,effort:s&&"effort"===s.field?s.level:void 0,reasoningEffort:s&&"reasoning_effort"===s.field?s.level:void 0,stream:!0,onStream:o.onDelta,signal:o.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"===t){const e=o.cfg&&o.cfg.baseURL||c.DEFAULT_BASE,t=t=>c.chat({baseURL:e,model:o.model,prompt:o.prompt,system:o.system,messages:o.messages,maxTokens:o.maxTokens,signal:o.signal,onDelta:o.onDelta,...t&&o.tools.length?{tools:o.tools,toolChoice:o.toolChoice}:{}});try{return await t(!0)}catch(e){if(o.tools.length&&e&&400===e.status)return t(!1);throw e}}if("pro"===t){const e=o.sessionKey||o.rootSessionId||o.sessionId;let t=null;if(e&&(t=A.get(e)||null,!t)){try{t=M.get(e,s)||null}catch{}t&&A.set(e,t)}const n=K(o.cwd),r=e=>claudePro.runClaudePro({prompt:proTurnPrompt(o),model:o.model&&"default"!==o.model?o.model:void 0,system:o.system,cwd:o.cwd,addDir:n,resumeSessionId:e||void 0,gate:b(),onAsk:async e=>{if(!e||!e.requestId)return"deny";const t=o.rootSessionId,n=o.rootOnDelta,r=PRO_TOOL_MAP[String(e.toolName||"")]||null,s=r||String(e.toolName||"unknown"),a=proAskArgs(e.input||{},s),i=covenant.preActionAssert({tool:s,args:a});if(!i.allowed)return n&&n({delta:"",note:`aegis: refused by the ÆGIS covenant — ${i.clause} (${i.label}): ${i.reason}`}),"deny";if(w()){if("exec"===s){const e=planExec(a&&a.command,{baseCwd:o.cwd||void 0});return e.oneShot?"once":(n&&n({delta:"",note:E(s,e.reason)}),"deny")}if(r&&m.MUTATING_TOOLS.has(s))return n&&n({delta:"",note:E(s)}),"deny";if(!r&&!PRO_PLAN_MODE_SAFE.has(s))return n&&n({delta:"",note:E(s)}),"deny"}if(!b())return"once";if("function"==typeof g){let e;try{e=g(s,a)}catch{e=null}if(e&&"deny"===e.verdict)return n&&n({delta:"",note:L(s)}),"deny";if(e&&"allow"===e.verdict)return"once"}if(D(t,s))return n&&n({delta:"",note:L(s)}),"deny";const l=await C(t,n,o.signal,{tool:s,args:a,diff:null});if("deny"===l)return U(t,s),"deny";if("session"!==l&&"once"!==l&&"always"!==l)return"deny";if("session"===l&&R(t,s,a),"always"===l&&"function"==typeof y)try{y(s,a)}catch{}return l},signal:o.signal,onDelta:o.onDelta,onSpawn:(e,t)=>{o.onDelta&&t&&o.onDelta({delta:"",note:claudePro.childLine(t)})}});let a=await r(t);if(a&&a.resumeStale){A.delete(e);try{M.del(e,s)}catch{}o.onDelta&&o.onDelta({delta:"",note:"aegis: the remembered Claude session no longer exists on this machine — continuing as a new conversation (earlier turns are not in its context)"}),a=await r(null)}if(e&&a&&a.sessionId&&!a.error){A.set(e,a.sessionId);try{M.set(e,a.sessionId,s)}catch{}}return a}throw new Error(`dispatch: unknown model class ${JSON.stringify(t)} — this build ships 'aegis', 'byok', 'local' and 'pro' only`)}async function Y(o,n){const r=o&&o.class,s=o&&o.model,a=reasoningBudget("byok"===r?splitByokModel(s).model:s,o&&o.maxTokens,o&&o.effort),i=statedCapOf(o),d="aegis"===r&&Boolean(o&&o.autonomous),u=Boolean(o&&o.roundsAsk),f=o&&o.sessionId||randomUUID(),g=Number.isInteger(o&&o.depth)?o.depth:0,y=o&&o.rootSessionId||f,k=o&&o.rootOnDelta||n,b="function"==typeof n?e=>e&&n({reasoning:e}):void 0,w=new AbortController;p.set(f,w);const E=w.signal,_=!(o&&!1===o.tools),T=_?m.toolsFor({includeSubagent:g<4}):[],S=o&&o.toolChoice||null,x=o&&o.system||h(q(o)),A=Array.isArray(o&&o.messages)?o.messages.filter(Boolean).slice():[];let M=A.length,O=o&&o.prompt||"";const N=String(O||""),F=Array.isArray(o&&o.attachments)?o.attachments.filter((e=>e&&"object"==typeof e)).slice(0,attachmentsModule.MAX_ATTACHMENTS):[];let R=F.length?attachmentsModule.buildContent(O,F):O,D=null;const U=q(o),I=((e,t)=>{if(null==l)return null;const o="function"==typeof l.policy?l.policy():l.policy;if(!o)return null;const n=require("./sandbox.js"),r=e&&e.cwd||process.cwd(),s=n.normalize(o,r);if("off"===s.mode)return null;let a=[];try{let e=null;try{e=require("node:os").homedir()}catch{e=null}a=n.autoGrants(r,{home:e,addDirs:(()=>{try{return K(r)}catch{return[]}})()})}catch{a=[]}if(a.length){const e=new Set;for(const t of s.fileSystem.entries)t&&t.path&&"path"===t.path.type&&t.path.path&&e.add(`${t.access}:${t.path.path}`);for(const t of a){const o=`${t.access}:${t.path.path}`;e.has(o)||(e.add(o),s.fileSystem.entries.push(t))}}return"local"===t&&"restricted"===s.network&&(s.network="open",s.networkExempt="local"),{policy:s,state:l.state||n.detect({appDir:l.appDir}),workspace:r,appDir:l.appDir,strict:!0===l.strict}})(U,r),L=U.cwd,C={getShell:()=>D||(D=new ShellSession({cwd:U.cwd,sandbox:I})),signal:E,cwd:L,desktopdir:U.desktopdir,sandbox:I};try{const l="byok"===r?splitByokModel(s):null;let p=null;const h="byok"===r?t.get(byokNamespace(l.provider))||{}:"local"===r&&t.get("local")||{},w="byok"===r?t.rawKey(byokNamespace(l.provider)):null,D="byok"!==r?null:w||providerKeyFromEnv(l.provider);if(!("byok"!==r||l.provider&&l.model)){const e=new Error('byok: model must be "<provider>:<model>" (pick one from /models) — got '+JSON.stringify(s||""));throw e.status=400,e}if("byok"===r&&!D){const t="anthropic"===l.provider?claudePro.claudeProStatus({env:process.env}):null,o=providerKeyRecord(l.provider).rejected,n=nexusFallbackModel({provider:l.provider,providerKey:D,providerKeyRefused:o,aegisKey:D?"":e.apiKey});if(!n){const e=new Error(o?`${o}. That is why this turn has no ${l.provider} key: an env value that short is a paste that lost its payload, not a credential. Fix ${o.split(" ")[0]} in ~/.aegiscode/.env (or the shell that exported it) — or skip keys entirely: /byok-key ${l.provider} <key> to set one here.`:t&&t.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 ${t.subscription||"Pro"} plan through the claude CLI) — or add a real console key: /byok-key anthropic <key>.`:`No key for "${l.provider}" yet. Easiest fix: /class aegis (uses your AEGIS key, no setup) — or add this provider's own key: /byok-key ${l.provider} <key>.`);throw e.status=400,e}p={from:l.provider,model:n}}if("byok"===r&&!e.apiKey){const e=new Error("No AEGIS key connected yet. Easiest fix: /class aegis (skips BYOK entirely) — or add your AEGIS key with /login, then try again.");throw e.status=401,e}if("local"===r){const e=c.remoteRefusal(h.baseURL||c.DEFAULT_BASE);if(e)throw e}if("byok"===r&&"custom"===l.provider&&!(h.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 U=p?"aegis":r,I={cls:U,model:p?p.model:s,mode:o&&o.mode,maxTokens:a,statedMaxTokens:i,autonomous:d,sessionId:f,signal:E,onDelta:n,cfg:h,apiKey:D,toolChoice:S,pooledFrom:p?p.from:void 0,cwd:L,rootSessionId:y,sessionKey:o&&o.sessionKey||void 0,rootOnDelta:k,effort:o&&o.effort,workers:o&&o.workers,recallDeep:o&&!0===o.recallDeep,singlePass:o&&!0===o.singlePass,onReasoning:b,idleTimeoutMs:d?9e5:void 0,stream:!o||!1!==o.stream};let $=!1,j=!1;const q=d?"AEGIS_AUTONOMOUS_MAX_ROUNDS":"AEGIS_CHAT_MAX_ROUNDS",K=(()=>{const e=Number.parseInt(process.env[q]||"",10);return Number.isFinite(e)&&e>0?e:0})(),Y=K||(d?40:24);let z=v.keyFor(o,A),H=v.take(z);if(!H&&!v.isStatedKey(o)){const e=v.adopt();e&&(H=e.entry,z=e.key)}if(H){const e=v.resumePreamble(H);0===A.length?Array.isArray(H.messages)&&H.messages.length&&A.push(...H.messages):Array.isArray(H.added)&&H.added.length&&A.push(...H.added),O?(O=`${e}\n\n${O}`,R=F.length?attachmentsModule.buildContent(O,F):O):(A.push({role:"user",content:e}),R=""),k&&k({delta:`\n\n[resuming work this session left unfinished at ${H.rounds} tool rounds`+(H.interruptions>1?` (cut off ${H.interruptions}×)`:"")+"…]\n"})}let V=K||Y+(H?v.bonus(Y):0),X=0;const J=Y,Q=8;let Z=0;const ee={calls:0},te=["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"],oe=e=>{const t=e&&e.usage;if(t&&"object"==typeof t){ee.calls+=1;for(const e of te)"number"==typeof t[e]&&Number.isFinite(t[e])&&(ee[e]=(ee[e]||0)+t[e]);if("number"!=typeof t.total_tokens){const e=(t.prompt_tokens??t.input_tokens??0)+(t.completion_tokens??t.output_tokens??0);e&&(ee.total_tokens=(ee.total_tokens||0)+e)}}},ne=e=>{if(!e||"object"!=typeof e)return e;const t=p?{...e,pooled_from:p.from,pooled_model:p.model,pooled_notice:requireSharedByokCatalog().nexusFallbackNotice({pooled_from:p.from,pooled_model:p.model})}:e;return ee.calls?{...t,usage:{...ee}}:t},re=()=>{if(""===R)return;const e=A[A.length-1],t=e&&"user"===e.role?flattenContent(e.content):null;e&&"user"===e.role&&t===flattenContent(R)||A.push({role:"user",content:R}),O="",R=""};M=A.length;const se=m&&m.MUTATING_TOOLS||new Set;let ae=0,ie=0,le=!1;for(;;){if(X>=V){if(u&&Z<Q&&!E.aborted&&await P(y,k,E,{spent:V,extensions:Z+1,max:Q,size:J})){Z+=1;const e=V;V+=J,A.push({role:"user",content:`You have used all ${e} tool rounds allowed for this turn; ${J} 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=u?"":`, or raise ${q} for a longer single turn`,t=`[stopped at ${V} tool rounds`+(ee.total_tokens?`, ${ee.total_tokens.toLocaleString()} tokens`:"")+". This session holds the work: your next message here resumes it automatically"+` (with a continuation preamble)${e}.]`,o=v.record(z,{rounds:X,tokens:ee.total_tokens||0,note:t,chain:H?H.interruptions:0,messages:A,added:A.slice(M)});return k&&k({delta:`\n\n${t}`}),ne({model:I.model,choices:[{message:{content:t},finish_reason:"length"}],stoppedOnRounds:!0,heldForSession:!0,heldRounds:o.rounds,sessionInterruptions:o.interruptions,resumedFrom:z})}X+=1;const e={...I,system:x,messages:A,prompt:R,tools:T,recallDeep:I.recallDeep&&1===X};let t;if(t=await G(U,e),oe(t),E.aborted)return ne(t);if(!$&&!assistantText(t)&&(isTruncated(t)||reasonedButSilent(t))){$=!0;const o=reasonedButSilent(t);if(t=await G(U,{...e,singlePass:!0,recallDeep:!1,effort:o?"high":e.effort,maxTokens:retryBudgetFor(e,o),statedMaxTokens:e.statedMaxTokens?doubledBudget(e.statedMaxTokens):void 0}),oe(t),E.aborted)return ne(t)}const a=T.length?extractToolCalls(t):[];if(!a.length){if(assistantText(t)||j||!_){if(!le&&_&&wantsMutation(N,ie>0,ae)){le=!0,re(),A.push({role:"assistant",content:assistantText(t)}),A.push({role:"user",content:UNMUTATED_TURN_NUDGE}),k&&k({delta:""});continue}return ne(t)}j=!0,re(),A.push({role:"user",content:reasonedButSilent(t)?THOUGHT_ONLY_NUDGE:EMPTY_TURN_NUDGE});const o={...e,singlePass:!0,recallDeep:!1,messages:A,prompt:"",tools:[]};t=await G(U,o);let n=o.maxTokens,a=o.effort;if(oe(t),E.aborted)return ne(t);if(!assistantText(t)&&(isTruncated(t)||reasonedButSilent(t))){const e=reasonedButSilent(t);if(n=retryBudgetFor(o,e),a=e?"high":o.effort,t=await G(U,{...o,effort:a,maxTokens:n,statedMaxTokens:o.statedMaxTokens?doubledBudget(o.statedMaxTokens):void 0}),oe(t),E.aborted)return ne(t)}const i=(()=>{const e=Number(n)||0;if(!e)return n;const t={maxTokens:n};return o.statedMaxTokens&&(t.statedMaxTokens=o.statedMaxTokens),Math.max(e,retryBudgetFor(t,!0))})();let l=0;for(;!assistantText(t)&&l<2&&!E.aborted;){const e=reasonedButSilent(t);if(l+=1,A.push({role:"user",content:e?1===l?THOUGHT_ONLY_NUDGE:FINAL_ANSWER_NUDGE:EMPTY_TURN_NUDGE}),e&&(a="high"),n=i,t=await G(U,{...o,messages:A,effort:a,maxTokens:n,statedMaxTokens:o.statedMaxTokens?doubledBudget(o.statedMaxTokens):void 0}),oe(t),E.aborted)return ne(t)}if(!assistantText(t))throw emptyTurnError({cls:r,model:s,effort:a,recoveryRounds:l,finishReason:finishReasonOf(t),reasoningChars:reasoningTextOf(t).length,reasoningTokens:reasoningTokensOf(t)});return ne(t)}re(),A.push({role:"assistant",content:assistantText(t),tool_calls:a.map((e=>({id:e.id,type:"function",function:{name:e.name,arguments:JSON.stringify(e.args)}})))});const l=new WeakMap,c=e=>{if("exec"!==e.name)return null;if(l.has(e))return l.get(e);const t=planExec(e.args&&e.args.command,{baseCwd:L});return l.set(e,t),t},d=e=>{if(!se.has(e.name))return!0;const t=c(e);return Boolean(t&&t.oneShot)},f=[];for(const e of a){const t=f[f.length-1];d(e)&&t&&t.parallel?t.calls.push(e):f.push({parallel:d(e),calls:[e]})}const p=async e=>{n&&n({delta:"",tool:{name:e.name,args:e.args,id:e.id,cwd:L,phase:"run"}});const t=c(e),a=t&&t.oneShot?{...C,oneShotExec:!0,cwd:t.cwd||C.cwd}:C,l=e.name===m.SUBAGENT_TOOL?await W(e.args,{cls:r,model:s,statedMaxTokens:i,effort:o&&o.effort,mode:o&&o.mode,parentSignal:E,depth:g,rootSessionId:y,rootOnDelta:k}):await B(e,{toolCtx:a,rootSessionId:y,rootOnDelta:k,signal:E});return l&&l.usage&&oe({usage:l.usage}),n&&n({delta:"",tool:{name:e.name,args:e.args,ok:l.ok,id:e.id,cwd:L,phase:"done"}}),l};for(const e of f){const t=e.parallel&&e.calls.length>1?await Promise.all(e.calls.map((e=>p(e)))):[await p(e.calls[0])];e.calls.forEach(((e,o)=>{const n=t[o];se.has(e.name)&&(ae+=1,n&&n.ok&&(ie+=1)),A.push({role:"tool",tool_call_id:e.id,name:e.name,content:m.toolResultText(n)})}))}}}catch(e){throw E.aborted&&e&&"object"==typeof e&&(e.aegisCancelled=!0),e}finally{D&&D.dispose(),p.delete(f)}}async function W({description:e,subagent_type:t,prompt:o}={},{cls:n,model:r,statedMaxTokens:s,effort:a,mode:i,parentSignal:l,depth:c,rootSessionId:d,rootOnDelta:u}={}){const f=String(o||e||"").trim();if(!f)return{ok:!1,error:"task requires a prompt"};const p=t&&"general"!==t?agentRoleLabel(t):"general",m=agentSystemPrompt(t),h=randomUUID();let g;if(l){if(l.aborted)return{ok:!1,error:"aborted"};g=()=>z(h),l.addEventListener("abort",g,{once:!0})}try{const e=await Y({class:n,model:r,mode:i,system:m,prompt:f,sessionId:h,depth:(c||0)+1,rootSessionId:d,rootOnDelta:u,statedMaxTokens:s,effort:a},(()=>{})),t=assistantText(e),o=e&&e.usage?{usage:e.usage}:{};return t?{ok:!0,output:t,...o}:{ok:!1,error:`subagent (${p}) produced no output`,...o}}catch(e){return{ok:!1,error:`subagent (${p}) failed: ${e&&e.message?e.message:e}`}}finally{l&&g&&l.removeEventListener("abort",g)}}function z(e){const t=p.get(e);return t&&t.abort(),{ok:Boolean(t)}}return{CLASSES:CLASSES,listClasses:async function(){return CLASSES.map((o=>{if("aegis"===o.class)return{...o,configured:Boolean(e.apiKey)};if("byok"===o.class){const e=(t.list()||[]).some((e=>!(!e||"string"!=typeof e.provider||!e.provider.startsWith("byok:"))&&(!!e.configured||Boolean(providerKeyFromEnv(e.provider.slice(BYOK_NAMESPACE_PREFIX.length))))));return{...o,configured:e}}if("local"===o.class)return{...o,configured:!0};if("pro"===o.class){const e=claudePro.claudeProStatus({env:process.env}),t=claudePro.seamAvailable();return{...o,configured:e.loggedIn,status:e,seam:t}}return{...o,configured:!1}}))},listModels:async function(o){if("aegis"===o){if(!e.apiKey)return{class:o,models:[],needsKey:!0};const t=await e.listModels();return{class:o,models:offerableCatalog(normalizeCatalog(t&&t.models))}}if("byok"===o){let n=[],r=null,s=!1,a=null;try{const t=await e.byokProviders();n=withUserModels(withCatalog(withByokAdditions(t&&t.providers||[]))),r=t&&t.fee||null}catch(e){n=[],s=!0,a=e&&e.message||String(e)}const i=[];for(const e of n){if(!e||!e.id)continue;const o=t.get(byokNamespace(e.id))||{},n=providerKeyRecord(e.id),r=n.key||"",s=Array.isArray(e.models)?e.models:[];for(const t of s){const s="string"==typeof t?t:t&&t.id;s&&i.push({id:`${e.id}:${s}`,label:`${e.label||e.id} — ${s}`,provider:e.id,configured:Boolean(o.configured||r),keyRejected:n.rejected||null})}}return{class:o,models:i,providers:n,needsProviderKey:i.length>0&&!i.some((e=>e.configured)),needsAegisKey:!e.apiKey,fee:r,providersFailed:s,providersError:a,unmatchedProviders:unmatchedUserProviders(n)}}if("local"===o){const e=(t.get("local")||{}).baseURL||c.DEFAULT_BASE,n=await c.probe(e);if(!n.running)return{class:o,models:[],baseURL:n.baseURL,needsDaemon:!0};let r=[],s=!0;try{r=await c.listTags(e)}catch{s=!1}return{class:o,models:r,baseURL:n.baseURL,listed:s}}if("pro"===o){const e=claudePro.claudeProStatus({env:process.env});return{class:o,models:claudePro.PRO_MODELS.map((t=>({id:t.id,label:t.label,note:t.note,configured:e.loggedIn}))),needsProviderKey:!1,needsAegisKey:!1,subscription:e.subscription,loggedIn:e.loggedIn,credentialFile:e.file,shadowed:e.shadowed||null,seam:claudePro.seamAvailable()}}throw new Error(`listModels: unknown model class ${JSON.stringify(o)} — this build ships 'aegis', 'byok', 'local' and 'pro' only`)},chat:Y,cancel:z,respondApproval:function(e,t){const o=O.get(e);return o?(O.delete(e),o.resolve("session"===t||"once"===t||"always"===t?t:"deny"),{ok:!0}):{ok:!1}},respondRoundsAsk:function(e,t){const o=N.get(e);return o?(N.delete(e),o.resolve(!0===t||"continue"===t),{ok:!0}):{ok:!1}},clearSessionApprovals:function(e){_.delete(e),T.delete(e),S.delete(e),A.delete(e);try{M.del(e,s)}catch{}return{ok:!0}},listUndoable:function(e){return(S.get(e)||[]).map((e=>({id:e.id,tool:e.tool,path:e.path,at:e.at}))).reverse()},undoMutation:function(e,t){const o=S.get(e)||[],n=t?o.findIndex((e=>e.id===t)):o.length-1;if(-1===n)return{ok:!1,error:t?`no undo record "${t}" for this conversation`:"nothing to undo in this conversation"};const r=o[n],s=I(r.path);if(!s||s.existed!==r.after.existed||s.content!==r.after.content)return{ok:!1,error:`${r.path} has changed since ${r.tool} ran — undo refused rather than overwriting work this session did not do. Resolve it by hand, or undo a different entry.`};try{r.before.existed?fs.writeFileSync(r.path,r.before.content,"utf8"):fs.unlinkSync(r.path)}catch(e){return{ok:!1,error:`undo failed: ${e&&e.message||e}`}}return o.splice(n,1),{ok:!0,path:r.path,restored:r.before.existed?"content":"deleted"}},settings:t,unloadLocalModels:function(){return c.unloadAll()},userModels:()=>loadUserModels(),addUserModel:(e,t)=>addUserModel(e,t),removeUserModel:(e,t)=>removeUserModel(e,t),discoverModels:async e=>{const o=String(null==e?"":e).trim().toLowerCase(),n=function(e){const o=String(null==e?"":e).trim().toLowerCase();if(!o)return"";try{if(t&&"function"==typeof t.rawKey){const e=t.rawKey(byokNamespace(o));if("string"==typeof e&&e.trim())return e.trim()}}catch{}return providerKeyFromEnv(o)}(o),r=await discoverVendorModels(o,{key:n,fetchImpl:d});if(!r||!r.ok)return r;const s=[];try{const e=loadUserModels().map;for(const t of Array.isArray(e[o])?e[o]:[])s.push(t)}catch{}return{...r,declared:s,endpoint:(vendorEndpointFor(o)||{}).url||""}},addUserModels:(e,t)=>{const o=Array.isArray(t)?t:[],n={provider:e,added:0,already:[],failed:[],capped:0,file:""};for(const t of o)try{const o=addUserModel(e,t);n.file=o.file||n.file,o.added?n.added+=1:n.already.push(o.model)}catch(e){const r=e&&e.message||String(e);if(/the cap/.test(r)){n.capped=o.length-n.added-n.already.length-n.failed.length;break}n.failed.push({id:String(t),reason:r})}return n},canDiscoverModels:e=>canDiscoverVendorModels(e),discoverableProviders:()=>discoverableProviders()}}module.exports={CLASSES:CLASSES,createLocalEngine:createLocalEngine,extractToolCalls:extractToolCalls,parseArgs:parseArgs,reasoningBudget:reasoningBudget,nativeEffort:nativeEffort,hostEnv:hostEnv};
@@ -23,7 +23,16 @@
23
23
  * sites, and the window that serves the renderer;
24
24
  * - `lib/local/shell.js` the process that actually executes `exec`;
25
25
  * - `lib/local/tools.js` the tool surface handed to the model;
26
- * - `lib/local/exec-plan.js` the rule that decides what may run batched.
26
+ * - `lib/local/exec-plan.js` the rule that decides what may run batched;
27
+ * - `lib/local/sandbox.js` the policy that decides what a batch can REACH.
28
+ *
29
+ * The last entry was added with ~/plan/agent-safety-plan.md §1b, and it earns its
30
+ * place differently from the other four: it is not a spawn site, it is what
31
+ * `shell.js` and `tools.js` each consult before spawning. Leaving it unpinned
32
+ * would have been the one hole the set could not see — replacing it with a
33
+ * stub that returns `{ ok: true, file: cmd, args }` disarms the outcome bound
34
+ * while every pinned byte stays byte-identical, so the interlock would report
35
+ * a clean tree. A unit that another unit trusts has to be a unit.
27
36
  *
28
37
  * A digest is taken over those files *as one closed set*, so changing any one
29
38
  * changes the whole, and compared to a value sealed into this file. On a
@@ -87,6 +96,37 @@ const UNITS = Object.freeze([
87
96
  { id: 'd2', rel: Buffer.from('bGliL2xvY2FsL3NoZWxsLmpz', 'base64').toString('utf8') },
88
97
  { id: 'd3', rel: Buffer.from('bGliL2xvY2FsL3Rvb2xzLmpz', 'base64').toString('utf8') },
89
98
  { id: 'd4', rel: Buffer.from('bGliL2xvY2FsL2V4ZWMtcGxhbi5qcw==', 'base64').toString('utf8') },
99
+ { id: 'd5', rel: Buffer.from('bGliL2xvY2FsL3NhbmRib3guanM=', 'base64').toString('utf8') },
100
+ // §2 of ~/plan/agent-safety-plan.md. Pinned for the same reason `sandbox.js`
101
+ // is: `main.js` requires it and it answers 'allow'/'deny' for the approval
102
+ // gate, so a stubbed copy that always returned `null` would leave the gate
103
+ // standing, but one that returned 'allow' would delete it — silently, and
104
+ // with the seal still green if this file were not itself a unit.
105
+ { id: 'd6', rel: Buffer.from('bGliL2xvY2FsL3Blcm0tcnVsZXMuanM=', 'base64').toString('utf8') },
106
+ // §3 of ~/plan/agent-safety-plan.md. The writer, and it earns the pin more
107
+ // sharply than the reader did: this module decides WHAT a durable allow is
108
+ // allowed to say. A stubbed copy that dropped the wildcard and blank-subject
109
+ // refusals would turn "Always allow this command" into "always allow every
110
+ // shell command" on the second click, while the gate, the reader and every
111
+ // other pinned byte stayed byte-identical and the seal reported a clean tree.
112
+ { id: 'd7', rel: Buffer.from('bGliL2xvY2FsL3Blcm0td3JpdGUuanM=', 'base64').toString('utf8') },
113
+ // §4 of ~/plan/agent-safety-plan.md (the rules editor). Pinned because it is the
114
+ // WRITER of the rule list: a stubbed copy could add an allow for every tool
115
+ // the user did not ask for, or silently drop a `deny` while the card on screen
116
+ // still listed it. `perm-rules.js` (d6) only reads what this one stores, so
117
+ // pinning the reader and not the writer would seal the lock and leave the key
118
+ // in the door.
119
+ { id: 'd8', rel: Buffer.from('bGliL2xvY2FsL3Blcm0tc3RvcmUuanM=', 'base64').toString('utf8') },
120
+ // §1d/§1e of ~/plan/agent-safety-plan.md. The per-platform mechanisms behind
121
+ // `sandbox.js`. Pinned because `sandbox.js` is pinned: it now DELEGATES the
122
+ // argv construction and the availability answer to these files, so leaving
123
+ // them out of the set would move the trust rather than remove it. A stubbed
124
+ // `sandbox-seatbelt.js` returning `available: true` with `(allow default)` and
125
+ // no denies would report "sandbox: workspace-write via Seatbelt" while
126
+ // confining nothing — with every previously pinned byte identical.
127
+ { id: 'd9', rel: Buffer.from('bGliL2xvY2FsL3NhbmRib3gtc2VhdGJlbHQuanM=', 'base64').toString('utf8') },
128
+ { id: 'd10', rel: Buffer.from('bGliL2xvY2FsL3NhbmRib3gtYXBwY29udGFpbmVyLmpz', 'base64').toString('utf8') },
129
+ { id: 'd11', rel: Buffer.from('bGliL2xvY2FsL3NhbmRib3gtYndyYXAuanM=', 'base64').toString('utf8') },
90
130
  ]);
91
131
 
92
132
  /**
@@ -94,7 +134,7 @@ const UNITS = Object.freeze([
94
134
  * (`tools/desktop-seal.mjs` in the source tree, `tools/obfuscate-faces.mjs`
95
135
  * after obfuscation), never by hand.
96
136
  */
97
- const SEALED = '48fc29f73f029cb1da82fb44f24bef085525eba53a2c2dc913fefb005e6f3ebf';
137
+ const SEALED = '044aa104fa89c413b18393d8cca3c3574808a312b8d1195ac26bd367978ba237';
98
138
 
99
139
  /**
100
140
  * Ask the question. Never throws — a check that can break the program it is
@@ -0,0 +1,206 @@
1
+ // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
2
+ // AEGIS Code (aegiscode) — source: https://github.com/aegisinfo/aegiscode-plugin
3
+ // SPDX-License-Identifier: AGPL-3.0-or-later
4
+ //
5
+ // ── Stored \/permissions rules, applied to the desktop's approval gate ──────
6
+ //
7
+ // §2 of ~/plan/agent-safety-plan.md. The desktop gate has exactly one setting
8
+ // today (`confirmMode`, one global on/off) plus a per-card yes/no. The CLI has
9
+ // a full tier engine: `defaultMode`, and `allow`/`deny`/`ask` pattern rules in
10
+ // `~/.aegiscode/permissions.json`, matched by `cli/src/permissions.js`. Both
11
+ // faces already share the *store* (`config.js`'s `confirmPosture`), so a user
12
+ // who writes `Bash(git status)` in the CLI expects the desktop to honour it.
13
+ // Before this module the desktop read none of it.
14
+ //
15
+ // ## Why this does NOT call evalPermission
16
+ //
17
+ // `evalPermission` answers `'allow'` for anything no rule matched — because in
18
+ // the CLI the residual allow means "the loop may run it, the interactive gate
19
+ // is elsewhere". The desktop's gate is the opposite shape: it prompts on every
20
+ // MUTATING_TOOLS call while `confirmMode` is on, so an `'allow'` residual piped
21
+ // into the short-circuit chain would silently answer "already approved" for
22
+ // every tool on the machine and remove the gate entirely. That is the failure
23
+ // this module exists to avoid, not to cause.
24
+ //
25
+ // So the only two verdicts taken from the store are the ones the user
26
+ // *explicitly wrote*:
27
+ //
28
+ // deny — a matching `deny` rule. A security floor: refused outright, and
29
+ // the refusal reuses the engine's own `denialText` so the model gets
30
+ // the same anti-retry wording a clicked "Deny" produces.
31
+ // allow — a matching `allow` rule. Skips the card, exactly like an "Allow for
32
+ // this session" decision that the user made in advance.
33
+ // null — no explicit rule. Keep the existing behaviour byte for byte: raise
34
+ // the card. This is the common case and it must stay the common case.
35
+ //
36
+ // ## Two ordering facts inherited from the CLI engine
37
+ //
38
+ // `matchRule` canonicalises tool names (`exec`≡`Bash`, `readFile`≡`Read`), so a
39
+ // rule written against either face's spelling governs both. And an allow rule
40
+ // is matched against `subjectFor(...)` — the command for a shell tool, the path
41
+ // for a file tool — which is why a bare `exec(*)` rule is a footgun worth
42
+ // knowing about: it also suppresses the multi-`cd` rail, since that rail is
43
+ // consulted only after allow rules. This module neither writes nor widens
44
+ // rules; it only reads them.
45
+ //
46
+ // ## The seam
47
+ //
48
+ // Rules are read through `one/src/permissions.js`'s `storedPermissionFacts()`,
49
+ // which resolves `cli/src/config.js` in all three install layouts and returns
50
+ // the CLI's rule shape verbatim. That is deliberate: reading
51
+ // `~/.aegiscode/permissions.json` here with a local `JSON.parse` would be a
52
+ // second rule reader, which is the drift D8 rule 1 forbids. A missing module is
53
+ // reported, never worked around — a gate that cannot see the rules must behave
54
+ // like a gate with no rules (cards for everything), not like a gate with all
55
+ // rules allowed.
56
+
57
+ 'use strict';
58
+
59
+ const path = require('path');
60
+
61
+ // ── Where the shared modules live ─────────────────────────────────────────
62
+
63
+ /**
64
+ * The install layouts, same candidates `claude-pro.js`'s `loadSeam` uses, plus
65
+ * the one the packaged desktop actually has:
66
+ *
67
+ * checkout desktop/lib/local → <repo>/one/src
68
+ * packaged desktop desktop/lib/local → desktop/vendor/one/src
69
+ * mirrored CLI cli/vendor/desktop/lib/local → cli/vendor/one/src
70
+ * packaged desktop, second form — the terminal face is staged under
71
+ * `vendor/faces/`, so `one/src/permissions.js` lands at
72
+ * `vendor/faces/cli/vendor/one/src`. Found by running the obf tree: without
73
+ * this candidate the seam answered `one/src/permissions.js not found` in
74
+ * exactly the build that ships, and the feature would have been dead on
75
+ * arrival while every checkout test stayed green.
76
+ */
77
+ function candidates(dir) {
78
+ const here = dir || __dirname;
79
+ return [
80
+ path.join(here, '..', '..', '..', 'one', 'src'),
81
+ path.join(here, '..', '..', 'vendor', 'one', 'src'),
82
+ path.join(here, '..', '..', '..', '..', 'one', 'src'),
83
+ path.join(here, '..', '..', 'vendor', 'faces', 'cli', 'vendor', 'one', 'src'),
84
+ ];
85
+ }
86
+
87
+ let cachedShared = null;
88
+
89
+ /**
90
+ * `{ permissions }` — `one/src/permissions.js`, which in turn resolves the one
91
+ * rule evaluator (`cli/src/permissions.js`). Returns null rather than throwing:
92
+ * the caller degrades to "no rules", which is safe, and says so once.
93
+ */
94
+ function loadShared(dir) {
95
+ if (cachedShared !== null && dir === undefined) return cachedShared;
96
+ for (const base of candidates(dir)) {
97
+ try {
98
+ const mod = require(path.join(base, 'permissions.js'));
99
+ if (
100
+ mod &&
101
+ typeof mod.storedPermissionFacts === 'function' &&
102
+ typeof mod.loadEvaluator === 'function'
103
+ ) {
104
+ const found = { permissions: mod };
105
+ if (dir === undefined) cachedShared = found;
106
+ return found;
107
+ }
108
+ } catch {
109
+ /* try the next layout */
110
+ }
111
+ }
112
+ return null;
113
+ }
114
+
115
+ // ── The decision ──────────────────────────────────────────────────────────
116
+
117
+ /**
118
+ * Do the stored rules have an explicit opinion about this call?
119
+ *
120
+ * @param {string} name tool name as the engine spells it (`exec`, `writeFile`)
121
+ * @param {object} args the normalised args (`normalizeToolArgs` already ran)
122
+ * @param {object} [opts]
123
+ * @param {object} [opts.facts] injected `storedPermissionFacts()` result, for
124
+ * tests — never read from disk in that case
125
+ * @param {string} [opts.dir] override the module-layout search root
126
+ * @returns {{verdict: 'allow'|'deny'|null, source: string, rule?: string, error?: string}}
127
+ * `verdict: null` means "no explicit rule" — the caller MUST keep whatever it
128
+ * was going to do, i.e. raise the card.
129
+ */
130
+ function rulesVerdict(name, args, opts = {}) {
131
+ const shared = loadShared(opts.dir);
132
+ if (!shared) {
133
+ return { verdict: null, source: 'unavailable', error: 'one/src/permissions.js not found' };
134
+ }
135
+ const { permissions } = shared;
136
+
137
+ let facts = opts.facts;
138
+ if (!facts) {
139
+ try {
140
+ facts = permissions.storedPermissionFacts();
141
+ } catch (e) {
142
+ return { verdict: null, source: 'unavailable', error: (e && e.message) || String(e) };
143
+ }
144
+ }
145
+ const rules = facts && facts.rules;
146
+ // No store, or a store with no readable rule file: no explicit opinion. The
147
+ // card stands. Never infer "the user allowed everything" from absence.
148
+ if (!rules || typeof rules !== 'object') return { verdict: null, source: (facts && facts.source) || 'none' };
149
+
150
+ let evaluator;
151
+ try {
152
+ evaluator = permissions.loadEvaluator();
153
+ } catch (e) {
154
+ return { verdict: null, source: 'unavailable', error: (e && e.message) || String(e) };
155
+ }
156
+ const { matchRule, subjectFor } = evaluator;
157
+ if (typeof matchRule !== 'function' || typeof subjectFor !== 'function') {
158
+ return { verdict: null, source: 'unavailable', error: 'rule evaluator is incomplete' };
159
+ }
160
+
161
+ const subject = subjectFor(name, args || {});
162
+ // deny first: a deny rule is a floor and outranks any allow rule, the same
163
+ // precedence evalPermission applies.
164
+ for (const key of ['deny', 'allow']) {
165
+ const list = Array.isArray(rules[key]) ? rules[key] : [];
166
+ for (const rule of list) {
167
+ let hit = false;
168
+ try {
169
+ hit = matchRule(rule, name, subject);
170
+ } catch {
171
+ hit = false; // a malformed rule matches nothing; it never widens access
172
+ }
173
+ if (hit) return { verdict: key === 'deny' ? 'deny' : 'allow', source: facts.source || 'store', rule };
174
+ }
175
+ }
176
+ return { verdict: null, source: facts.source || 'store' };
177
+ }
178
+
179
+ // ── The subject, from the same evaluator ──────────────────────────────────
180
+
181
+ /**
182
+ * The subject a rule matches against, from the SHARED evaluator.
183
+ *
184
+ * Exported so the engine's session tier can key its grants on the same value
185
+ * the durable tier uses (`perm-write.js` composes rules from it), instead of
186
+ * inventing a second derivation. Answers '' when the evaluator cannot be
187
+ * loaded — the engine reads that as "scoped, but to nothing", which is the safe
188
+ * direction: a grant can only ever cover less than the whole tool.
189
+ *
190
+ * Deliberately silent on failure. A gate that cannot see the evaluator must
191
+ * still gate, and `rulesVerdict` already reports the same unavailability on the
192
+ * path a user can act on.
193
+ */
194
+ function subjectFor(name, args) {
195
+ try {
196
+ const shared = loadShared();
197
+ if (!shared) return '';
198
+ const evaluator = shared.permissions.loadEvaluator();
199
+ if (!evaluator || typeof evaluator.subjectFor !== 'function') return '';
200
+ return evaluator.subjectFor(name, args || {});
201
+ } catch {
202
+ return '';
203
+ }
204
+ }
205
+
206
+ module.exports = { rulesVerdict, loadShared, candidates, subjectFor };