aegiscode 7.0.28 → 7.0.29
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +2 -3
- package/src/app.js +1 -1
- package/src/art.js +1 -1
- package/src/chatflow.js +1 -1
- package/src/commands.js +1 -1
- package/src/credentials.js +1 -1
- package/src/diffview.js +1 -1
- package/src/export.js +1 -1
- package/src/init.js +1 -1
- package/src/models.js +1 -1
- package/src/panels.js +1 -1
- package/src/screens.js +1 -1
- package/src/theme.js +1 -1
- package/vendor/client/aegis.js +1 -1
- package/vendor/client/attest.js +1 -1
- package/vendor/client/catalog-client.js +1 -1
- package/vendor/client/conversation-export.js +1 -1
- package/vendor/client/credentials.js +1 -1
- package/vendor/client/drive-upload.js +1 -1
- package/vendor/client/env-file.js +1 -1
- package/vendor/client/hooks.js +1 -1
- package/vendor/client/model-discovery.js +1 -1
- package/vendor/client/naming.js +1 -1
- package/vendor/client/platform.js +1 -1
- package/vendor/client/record-vault.js +2 -2
- package/vendor/client/session-store.js +1 -1
- package/vendor/client/user-models.js +1 -1
- package/vendor/desktop/lib/local/claude-pro.js +1 -1
- package/vendor/desktop/lib/local/engine.js +1 -1
- package/vendor/desktop/lib/local/exec-plan.js +269 -1
- package/vendor/desktop/lib/local/integrity.js +163 -1
- package/vendor/desktop/lib/local/shell.js +712 -1
- package/vendor/desktop/lib/local/tools.js +1328 -1
- package/vendor/desktop/main.js +4956 -1
- package/vendor/hosts/install.js +1 -1
- package/vendor/hosts/openai-shim.js +1 -1
- package/vendor/mcp/server.js +1 -1
- package/vendor/mcp/tools.js +1 -1
- package/vendor/one/src/selfhost.js +3 -0
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
2
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
-
const e=require("node:fs"),n=require("node:os"),t=require("node:path");let o=null;try{o=require("../../../client/env-file.js")}catch{try{o=require("../../vendor/env-file.js")}catch{o=null}}function s(e){const o=e||process.env,s=o&&o.CLAUDE_CONFIG_DIR;return s&&String(s).trim()?String(s).trim():t.join(n.homedir(),".claude")}function i(e){return o?o.resolveForeignSecret("CLAUDE_CODE_OAUTH_TOKEN",{env:e}):""}const r=Object.freeze(["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN"]);function l(e){return"string"==typeof e&&/^sk-ant-[A-Za-z0-9_-]{8,}$/.test(e.trim())}function a(e,n,t){const s={...e||{}},i=[],a=o&&"function"==typeof o.credentialLooksUsable?o.credentialLooksUsable:null,c=!(!t||!t.hasSubscription);if(a)for(const e of r){const n=s[e];if("string"!=typeof n)continue;let t=null;if(a(n)?c&&"ANTHROPIC_API_KEY"===e&&!l(n)&&(t="not-a-console-key"):t="too-short",!t)continue;delete s[e];const o=n.trim().length;o>0&&i.push({name:e,length:o,reason:t})}return n&&(s.CLAUDE_CODE_OAUTH_TOKEN=n),{env:s,dropped:i}}function c(e){const n=Array.isArray(e)?e:[];if(!n.length)return null;const t=n.filter((e=>e&&"not-a-console-key"===e.reason)),o=n.filter((e=>!e||"not-a-console-key"!==e.reason)),s=[];if(o.length){const e=o.map((e=>`${e.name} (${e.length} character${1===e.length?"":"s"})`)).join(", ");s.push(`${e}: too short to be a credential, and the CLI would have spent it instead of your subscription`)}if(t.length){const e=t.map((e=>`${e.name} (${e.length} characters)`)).join(", ");s.push(`${e}: not an Anthropic console key (\`sk-ant-\`), and the CLI would have spent it instead of your subscription`)}return`aegis: not passed to the claude child — ${s.join("; ")}`}function d(e,n){const t=e||{},s=o&&"function"==typeof o.credentialLooksUsable?o.credentialLooksUsable:null;if(!s)return null;const i=!(!n||!n.hasSubscription);for(const e of r){const n=t[e];if("string"!=typeof n)continue;let o=null;if(s(n)?i&&"ANTHROPIC_API_KEY"===e&&!l(n)&&(o="not-a-console-key"):o="too-short",o)return{name:e,length:n.trim().length,reason:o}}return null}function u(n){const o=n||{},r=o.env||process.env,l=t.join(o.dir||s(r),".credentials.json"),c={claude:o.claudeVersion||null,file:l,exists:!1,kind:null,subscription:null,expiresAt:0,loggedIn:!1};let u;try{u=JSON.parse(e.readFileSync(l,"utf8")),c.exists=!0}catch{u=null}const p=u&&u.claudeAiOauth;p&&(p.accessToken||p.refreshToken)?(c.kind="oauth",c.subscription=p.subscriptionType||null,c.expiresAt=Number(p.refreshTokenExpiresAt)||0,c.loggedIn=!0):u&&"string"==typeof u.token&&u.token?(c.kind="apikey",c.loggedIn=!0):i(r)&&(c.kind="env-token",c.loggedIn=!0),c.subscriptionPresent=c.loggedIn&&"apikey"!==c.kind,c.shadowed=d(r,{hasSubscription:c.subscriptionPresent});const h=a(r,null,{hasSubscription:c.subscriptionPresent});return c.credentialPresent=c.loggedIn||"string"==typeof h.env.ANTHROPIC_API_KEY||"string"==typeof h.env.ANTHROPIC_AUTH_TOKEN||"string"==typeof h.env.CLAUDE_CODE_OAUTH_TOKEN,c}const p=Object.freeze([{id:"default",label:"Default (recommended)",note:"the CLI picks for the subscription"},{id:"sonnet",label:"Sonnet",note:"alias the CLI resolves · latest Sonnet"},{id:"opus",label:"Opus",note:"alias the CLI resolves · latest Opus"},{id:"opusplan",label:"Opus Plan",note:"alias the CLI resolves · plan with Opus, act on Sonnet"},{id:"haiku",label:"Haiku",note:"alias the CLI resolves · latest Haiku"},{id:"fable",label:"Fable",note:"alias the CLI resolves · needs usage credits"},{id:"claude-sonnet-5-5",label:"Claude Sonnet 5.5",note:"full name · Anthropic"},{id:"claude-sonnet-4-6",label:"Claude Sonnet 4.6",note:"full name · Anthropic"},{id:"claude-sonnet-4-5-20250929",label:"Claude Sonnet 4.5",note:"full name · Anthropic · dated snapshot"},{id:"claude-opus-5",label:"Claude Opus 5",note:"full name · Anthropic"},{id:"claude-opus-4-7",label:"Claude Opus 4.7",note:"full name · Anthropic"},{id:"claude-opus-4-6",label:"Claude Opus 4.6",note:"full name · Anthropic"},{id:"claude-opus-4-5-20251101",label:"Claude Opus 4.5",note:"full name · Anthropic · dated snapshot"}]);function h(e){const n=[],t=e||{};return t.system&&String(t.system).trim()&&n.push("--append-system-prompt",String(t.system)),n}function g(e){const n=e||{},t=new Map;let o="",s="",i=0,r=null;const a=e=>[...t.values()].find((n=>"collecting"===n.phase&&n.index===e))||[...t.values()].find((e=>"collecting"===e.phase));return{line(e){let l;try{l=JSON.parse(e)}catch{return}if("stream_event"===l.type&&l.event){const e=l.event;if("content_block_start"===e.type&&e.content_block)"tool_use"===e.content_block.type&&t.set(e.content_block.id,{id:e.content_block.id,index:null==e.index?0:e.index,name:e.content_block.name,args:"",startedAt:Date.now(),phase:"collecting"});else if("content_block_delta"===e.type&&e.delta){if("text_delta"===e.delta.type){const t=(e.delta.text||"").replace(/\x00/g,"");o+=t,n.onText&&t&&n.onText(t)}else if("thinking_delta"===e.delta.type){const t=(e.delta.thinking||"").replace(/\x00/g,"");s+=t,n.onThinking&&t&&n.onThinking(t);const o=e.delta.estimated_tokens;"number"==typeof o&&o>0&&Number.isFinite(o)&&(i+=o,n.onThinkingProgress&&n.onThinkingProgress(o))}else if("input_json_delta"===e.delta.type){const n=a(null==e.index?0:e.index);n&&(n.args+=e.delta.partial_json||"")}}else if("content_block_stop"===e.type){const o=a(null==e.index?0:e.index);o&&(e=>{let o=e.args;try{o=e.args?JSON.parse(e.args):{}}catch{o={}}t.set(e.id,{...e,args:o,phase:"run"}),n.onTool&&n.onTool({id:e.id,name:e.name,args:o,phase:"run"})})(o)}}else if("user"===l.type&&l.message){const e=Array.isArray(l.message.content)?l.message.content:[];for(const o of e){if(!o||"tool_result"!==o.type||!o.tool_use_id)continue;const e=t.get(o.tool_use_id);if(!e)continue;const s=Math.max(0,Date.now()-(e.startedAt||Date.now()));n.onTool&&n.onTool({id:e.id,name:e.name,phase:"done",elapsed:s,error:!!o.is_error}),t.delete(o.tool_use_id)}}else"result"===l.type&&(r=l,n.onDone&&n.onDone({text:o||l.result||"",error:l.is_error?l.result||"api error":void 0,usage:l.usage||null,costUsd:"number"==typeof l.total_cost_usd?l.total_cost_usd:void 0,durationMs:l.duration_ms,sessionId:l.session_id,thinking:s||"",thinkingTokens:i}))},get text(){return o},get thinking(){return s},get thinkingTokens(){return i},get resultLine(){return r}}}function f(e){const n=e||__dirname,o=[t.join(n,"..","..","..","one","src"),t.join(n,"..","..","vendor","one","src"),t.join(n,"..","..","..","..","one","src")];for(const e of o)try{const n=require(t.join(e,"child.js")),o=require(t.join(e,"permissions.js"));if("function"==typeof n.claudeArgv&&"function"==typeof o.resolvePosture)return{child:n,permissions:o}}catch{}throw new Error("aegis: the Claude child argv builder (one/src/child.js + one/src/permissions.js) is missing from this install — refusing to build a second argv, because a second argv is a second policy.")}function m(e,n,t){const o={content:e||""},s="string"==typeof n?n:"";return s&&(o.reasoning_content=s),"number"==typeof t&&t>0&&Number.isFinite(t)&&(o.thinking_tokens=t),o}module.exports={claudeConfigDir:s,claudeOAuthToken:i,claudeProStatus:u,childEnvPlan:a,envDroppedLine:c,shadowingValue:d,SHADOWING_ENV_VARS:r,PRO_MODELS:p,turnArgs:h,createStreamParser:g,loadSeam:f,seamAvailable:function(e){try{return f(e),{ok:!0,error:null}}catch(e){return{ok:!1,error:e&&e.message||String(e)}}},childLine:function(e,n){if(!e)return"";try{return f(n).child.childRecordLine(e)}catch{const n=e.skipFlag||"no permission flag";return`aegis: claude child [${e.kind}] ${n}`}},runClaudePro:function(e,n){const t=e||{},o=n||{},s=o.seam||f(o.dir),r=o.spawn||require("node:child_process").spawn,l=s.permissions.resolvePosture({rules:t.rules,gate:t.gate,interactive:!1,childKind:s.permissions.CHILD_KINDS.HEADLESS,env:t.env||process.env}),d=s.child.claudeArgv({posture:l,prompt:t.prompt,model:t.model||void 0,permissionMode:t.permissionMode,resumeSessionId:t.resumeSessionId,sessionId:t.sessionId,addDir:t.addDir,extra:[...h(t),"--include-partial-messages","--verbose"]});return new Promise((e=>{if(t.signal&&t.signal.aborted)return void e({choices:[{message:{content:""},finish_reason:"stop"}],stopped:!0});const n=t.env||process.env,s=i(n);let l=!1;try{l=!!u({env:n}).subscriptionPresent}catch{}const p=a(n,s,{hasSubscription:l}),h=p.env,f=c(p.dropped);if(f&&t.onDelta)try{t.onDelta({delta:"",note:f})}catch{}let _;try{_=r(o.executable||"claude",d.argv,{cwd:t.cwd||process.cwd(),stdio:["ignore","pipe","pipe"],env:h})}catch(n){return void e({choices:[{message:{content:""},finish_reason:"error"}],error:`claude: could not start the child (${n&&n.message||n})`,...p.dropped.length?{envDropped:p.dropped}:{}})}if(t.onSpawn)try{t.onSpawn(_,d.record)}catch{}let k=!1,v="",b="",y=null;const A=Number(t.idleTimeoutMs)||6e5,T=n=>{k||(k=!0,y&&clearTimeout(y),t.signal&&t.signal.removeEventListener("abort",I),e(p.dropped.length?{...n,envDropped:p.dropped}:n))},I=()=>{try{_.kill("SIGTERM")}catch{}setTimeout((()=>{try{_.kill("SIGKILL")}catch{}}),1500)};t.signal&&t.signal.addEventListener("abort",I,{once:!0});const S=()=>{y&&clearTimeout(y),y=setTimeout((()=>{I(),T({choices:[{message:{content:""},finish_reason:"stop"}],error:`claude: the child went silent for ${Math.round(A/1e3)}s and was stopped`})}),A)};S();const D=g({onText:e=>{S(),t.onDelta&&t.onDelta({delta:e})},onThinking:e=>{S(),t.onDelta&&t.onDelta({reasoning:e})},onThinkingProgress:e=>{S(),t.onDelta&&t.onDelta({thinkingTokens:e})},onTool:e=>{S(),t.onDelta&&t.onDelta({delta:"",tool:{name:e.name,args:e.args,ok:"done"===e.phase?!e.error:void 0,id:e.id,cwd:t.cwd,phase:e.phase}})},onDone:e=>{e.error?T({choices:[{message:{content:e.text||""},finish_reason:"error"}],usage:e.usage||void 0,error:e.error}):T({choices:[{message:m(e.text||"",e.thinking,e.thinkingTokens),finish_reason:"stop"}],usage:e.usage||void 0,costUsd:e.costUsd,durationMs:e.durationMs,sessionId:e.sessionId,childRecord:d.record})}});_.stdout.on("data",(e=>{S(),b+=e.toString("utf8");const n=b.split("\n");b=n.pop()||"";for(const e of n){const n=e.trim();n&&D.line(n)}})),_.stderr.on("data",(e=>{S(),v.length<8192&&(v+=e.toString("utf8"))})),_.on("error",(e=>{T({choices:[{message:{content:""},finish_reason:"error"}],error:`claude: could not run the child (${e&&e.message||e}). Install it with \`npm i -g @anthropic-ai/claude-code\`, then sign in with \`claude auth login\`.`})})),_.on("close",(e=>{b.trim()&&D.line(b.trim()),T({choices:[{message:m(D.text,D.thinking,D.thinkingTokens),finish_reason:"stop"}],usage:D.resultLine&&D.resultLine.usage||void 0,childRecord:d.record,error:D.text||0===e?void 0:`claude: the child exited with status ${e}${v.trim()?` — ${v.trim().split("\n").slice(-3).join(" ")}`:""}`})}))}))}};
|
|
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};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
2
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
-
const{randomUUID:e}=require("node:crypto"),o=require("node:os"),t=require("./tools.js"),n=require("./attachments.js"),{flattenContent:r}=n,s=require("./prompt.js"),a=require("./local.js"),{ShellSession:i}=require("./shell.js"),{planExec:l}=require("./exec-plan.js"),c=require("./claude-pro.js"),{agentSystemPrompt:d,agentRoleLabel:u}=require("./agents.js"),{beginTurnGuard:f,recordWrite:p,blocksDestructive:m}=require("./turn-guard.js"),{acquireWorktreeLock:h,releaseWorktreeLock:g}=require("./worktree-lock.js"),y=require("./covenant.js");let k=null;try{k=require("../../../client/env-file.js")}catch{try{k=require("../../vendor/env-file.js")}catch{k=null}}let v=null;try{v=require("../../../client/platform.js")}catch{try{v=require("../../vendor/platform.js")}catch{v=null}}let w=null;try{w=require("../../../client/credentials.js")}catch{try{w=require("../../vendor/credentials.js")}catch{w=null}}function b(e,o,n,r){const s=e&&"function"==typeof e.normalizeArgs&&e.normalizeArgs||"function"==typeof t.normalizeArgs&&t.normalizeArgs||null;return s?s(o,n,r):{ok:!0,args:n&&"object"==typeof n?n:{},error:null}}function x(e){if(!e)return null;try{const o=require("node:fs"),t=require("node:path");let n=t.resolve(String(e));for(let e=0;e<8;e+=1){if(o.existsSync(t.join(n,".git")))return"git";const e=t.dirname(n);if(e===n)break;n=e}return""}catch{return null}}function S(e={},t={},n=null){const r=e||{},s=t||{},a=(e,o)=>null!=s[e]?s[e]:o;let i=r.homedir,l=r.cwd;try{i||(i=o.homedir()),l||(l=process.cwd())}catch{}let c=r.shell,d=r.shellKind;try{if(!c||!d){const e=require("./shell.js").resolveSessionShell();c=c||e.cmd,d=d||e.kind}}catch{}let u=r.desktopdir;try{!u&&v&&(u=v.desktopDir())}catch{}let f=r.dataDir;try{!f&&w&&(f=w.aegisHome())}catch{}let p=r.locale,m=r.localeName;try{!p&&v&&"function"==typeof v.appLocale&&(p=v.appLocale()),p&&!m&&v&&"function"==typeof v.languageName&&(m=v.languageName(p))}catch{}return{platform:a("platform",r.platform||process.platform),arch:a("arch",r.arch||process.arch),homedir:a("homedir",i),desktopdir:a("desktopdir",u),dataDir:a("dataDir",f),locale:a("locale",p),localeName:a("localeName",m),languages:a("languages",r.languages),cwd:a("cwd",l),vcs:a("vcs",null!=r.vcs?r.vcs:x(l)),shell:a("shell",c),shellKind:a("shellKind",d),roots:a("roots",r.roots),appVersion:a("appVersion",r.appVersion),model:a("model",n&&n.model)}}const _=[{class:"aegis",label:"Aegis Cloud",kind:"cloud"},{class:"byok",label:"Bring your own key",kind:"cloud"},{class:"local",label:"Local model",kind:"local"},{class:"pro",label:"Claude Code Pro",kind:"subscription"}],A="byok:";function T(e){return`${A}${e}`}function M(e){const o="string"==typeof e?e:"",t=o.indexOf(":");return t<0?{provider:"",model:o}:{provider:o.slice(0,t),model:o.slice(t+1)}}function j(e){const o={key:"",env:"",rejected:null};if(!k||"function"!=typeof k.providerKeyFromEnv)return o;try{const t=k.providerKeyFromEnv(e)||o;return{key:"string"==typeof t.key?t.key:"",env:"string"==typeof t.env?t.env:"",rejected:"string"==typeof t.rejected&&t.rejected?t.rejected:null}}catch{return o}}function E(e){if(!k||"function"!=typeof k.providerKeyFromEnv)return"";try{return k.providerKeyFromEnv(e).key||""}catch{return""}}const C=/^deepseek-(v4(\.\d+)?-(flash|pro)|flash|pro|reasoner)$/,I={low:8192,medium:16384,high:32768,max:32768},$={low:"low",medium:"medium",high:"high"},N=/non-reasoning/i,q=[{provider:"deepseek",re:C,field:"effort",map:{low:"low",medium:"high",high:"high"},extra:{max:"max"}},{provider:"openai",re:/^(gpt-5|o[0-9])/i,field:"reasoning_effort",map:$},{provider:"groq",re:/^(openai\/gpt-oss|qwen\/qwen3)/i,field:"reasoning_effort",map:$},{provider:"xai",re:/^grok-(4\.[5-9]|[5-9])/,field:"reasoning_effort",map:$},{provider:"google",re:/^gemini-(2\.5|3|[4-9])/,field:"reasoning_effort",map:{...$,medium:"high"}}];function D(e,o,t){const n=Number(o);return Number.isFinite(n)&&n>0?n:C.test(String(e||""))?I["low"===t||"medium"===t||"max"===t?t:"high"]:void 0}function L(e,o,t){const n=String(o||"");if(N.test(n))return;if(null===t)return;const r="low"===t||"medium"===t?t:"max"===t?"max":"high";for(const o of q)if(o.provider===e&&o.re.test(n)){const e=Object.prototype.hasOwnProperty.call(o.map,r)?o.map[r]:o.extra&&Object.prototype.hasOwnProperty.call(o.extra,r)?o.extra[r]:void 0;if(void 0===e)return;return{field:o.field,level:e}}}const{offerableCatalog:O}=function(){const e=[()=>require("../../../client/brain-catalog.js"),()=>require("../../vendor/brain-catalog.js")];let o=null;for(const t of e)try{return t()}catch(e){o=e}throw o}(),{withByokAdditions:U,canonicalModelId:P}=function(){const e=[()=>require("../../../client/byok-catalog.js"),()=>require("../../vendor/byok-catalog.js")];let o=null;for(const t of e)try{return t()}catch(e){o=e}throw o}(),{withUserModels:R,unmatchedUserProviders:K,load:F,addUserModel:B,removeUserModel:G}=function(){const e=[()=>require("../../../client/user-models.js"),()=>require("../../vendor/user-models.js")];let o=null;for(const t of e)try{return t()}catch(e){o=e}throw o}(),{withCatalog:z}=function(){const e=[()=>require("../../../client/catalog-client.js"),()=>require("../../vendor/catalog-client.js")];let o=null;for(const t of e)try{return t()}catch(e){o=e}throw o}(),{discoverModels:W,canDiscover:Y,endpointFor:H,discoverableProviders:J}=function(){const e=[()=>require("../../../client/model-discovery.js"),()=>require("../../vendor/model-discovery.js")];let o=null;for(const t of e)try{return t()}catch(e){o=e}throw o}();function V(e){if(null==e)return{};if("object"==typeof e)return e;try{const o=JSON.parse(String(e));return o&&"object"==typeof o?o:{}}catch{return{}}}function X(e){if(!e)return[];if(Array.isArray(e.toolCalls)&&e.toolCalls.length)return e.toolCalls.map((e=>({id:e.id||"",name:e.name||"",args:V(e.args)}))).filter((e=>e.name));const o=e.choices&&e.choices[0]&&e.choices[0].message,t=o&&o.tool_calls||[];return Array.isArray(t)?t.map((e=>{const o=e&&e.function||{};return{id:e&&e.id||"",name:o.name||e&&e.name||"",args:V(o.arguments)}})).filter((e=>e.name)):[]}function Q(e){const o=Array.isArray(e.prompt)?r(e.prompt):e.prompt;if("string"==typeof o&&o.trim())return o;const t=Array.isArray(e.messages)?e.messages:[];for(let e=t.length-1;e>=0;e-=1){const o=t[e];if(!o||"user"!==o.role)continue;const n=r(o.content);if(n.trim())return n}return o}function Z(e){const o=e&&e.choices&&e.choices[0]&&e.choices[0].message;return o&&"string"==typeof o.content&&o.content||""}function ee(e){const o=e&&e.choices&&e.choices[0];return o&&o.finish_reason||e&&e.stop_reason||""}function oe(e){const o=ee(e);return"length"===o||"max_tokens"===o}function te(e){if(!e)return"";const o=e.choices&&e.choices[0],t=o&&o.message||{};if(Array.isArray(t.content)){const e=t.content.filter((e=>e&&("thinking"===e.type||"reasoning"===e.type))).map((e=>e.thinking||e.text||"")).join("");if(e)return e}const n=t.content&&"object"==typeof t.content?t.content.reasoning_content:"",r=[t.reasoning_content,t.reasoning,o&&o.reasoning_content,e.reasoning_content,e.reasoning,n];for(const e of r)if("string"==typeof e&&e)return e;return""}function ne(e){if(!e)return 0;const o=e.choices&&e.choices[0],t=o&&o.message||{},n=e.usage||{},r=n.completion_tokens_details||n.output_tokens_details||{},s=[t.thinking_tokens,t.reasoning_tokens,o&&o.thinking_tokens,e.thinking_tokens,r.reasoning_tokens,r.thinking_tokens];for(const e of s)if("number"==typeof e&&Number.isFinite(e)&&e>0)return e;return 0}function re(e){return!Z(e)&&(""!==te(e)||ne(e)>0)}function se(e,o){const t=ae(e.maxTokens);return o&&function(e){const o=Number(e);return Number.isFinite(o)&&Object.values(I).includes(o)}(e.maxTokens)?Math.max(t,32768):t}function ae(e){const o=Number(e)||0;return o>0?2*o:8192}const ie="Your previous reply came back empty — it contained no answer and no tool call. Write your answer now, using only the information already gathered above. No tools are available in this reply, so do not call any: respond in plain prose or markdown.",le="Your previous round was spent entirely on hidden reasoning and produced no visible reply. Answer the user directly and briefly now. Do not reason, explain, or think first — write only the answer, no tools.",ce=new RegExp("\\b(?:fix|implement|add|create|write|refactor|rename|remove|delete|replace|update|patch|migrate|convert|make\\s+(?:it|them|this|that|the|sure)|change|correct|resolve|repair|address|apply|introduce|support|wire\\s+up)\\b","i");function de(e,o,t){if(o)return!1;if(!(t>0))return!1;const n=String(e||"");return!!n.trim()&&!/\?\s*$/.test(n.trim())&&ce.test(n)}function ue({cls:e,model:o,finishReason:t,reasoningChars:n,reasoningTokens:r,effort:s,recoveryRounds:a}){const i=Number(a)||0,l=Number(r)||0,c=new Error(`The model returned no answer after ${e}/${o} was asked to summarise its results`+(i?`, and ${i} extra recovery call${1===i?"":"s"} with a larger budget and a changed ask came back empty too`:"")+` (stop reason: ${t||"none"}`+(s?`, effort: ${s}`:"")+(n?`, hidden reasoning: ${n} chars and no visible text`:l>0?`, ~${l} thinking tokens billed and no visible text`:"")+"). "+(n||l>0?"Every one of those calls spent its output on hidden reasoning instead of writing a word, so this is the model rather than the budget: pick a model that answers without a thinking pass, or ask for a smaller piece of work.":"No visible text came back from any of those calls. Send the request again, in smaller pieces, or from a different model."));return c.status=502,c}module.exports={CLASSES:_,createLocalEngine:function({aegis:o,settings:f,tools:h,promptBuilder:g,recallProvider:k,env:v,getConfirmMode:x,localTransport:A=a,fetchImpl:$,gitScope:C}){const I=new Map,N=h||t,q=g&&g.buildSystemPrompt||s.buildSystemPrompt,V=require("./session-rounds.js"),ce=()=>{if("function"==typeof x)return!1!==x();if(f&&"function"==typeof f.getConfirmMode){const e=f.getConfirmMode();return void 0===e||Boolean(e)}return!0},fe=new Map,pe=new Map,me=new Map,he=new Map,ge=new Map;function ye(e){return`${e} was not executed — the user denied this tool for this conversation. Do NOT retry it and do NOT attempt the same effect by another route (another command, a writeFile instead of an edit, a subagent). Stop calling tools and reply in plain text: say what you were trying to do, what you need, and that the user can re-enable ${e} to let it proceed.`}function ke(o,t,n,r){return new Promise((s=>{if(n&&n.aborted)return void s(!1);const a=e();let i=!1;const l=()=>c(!1),c=e=>{i||(i=!0,ge.delete(a),n&&n.removeEventListener("abort",l),s(e))};n&&n.addEventListener("abort",l,{once:!0}),ge.set(a,{resolve:c}),"function"==typeof t?t({delta:"",rounds:{id:a,sessionId:o,spent:r.spent,extensions:r.extensions,max:r.max,size:r.size}}):c(!1)}))}async function ve(e,o,t){const n=b(N,e,o,t||{});if(!n.ok)return{ok:!1,error:n.error};o=n.args;const r=t&&t.guard;if(r&&"exec"===e){const e=m(r,o&&o.command);if(!e.ok)return{ok:!1,error:e.reason}}const s=y.preActionAssert({tool:e,args:o||{}});if(!s.allowed){const t=y.bindRefusal({tool:e,args:o||{}},s);return{ok:!1,error:`refused by the ÆGIS covenant — ${s.clause} (${s.label}): ${s.reason}`,covenant:t}}const a=await N.executeTool(e,o,t);return r&&("writeFile"===e||"editFile"===e)&&a&&!1!==a.ok&&p(r,o&&o.file_path),a}async function we(o,{toolCtx:t,rootSessionId:n,rootOnDelta:r,signal:s}){const{name:a}=o,i=b(N,a,o.args,t||{});if(!i.ok)return{ok:!1,error:i.error};const l=i.args;if(!N.MUTATING_TOOLS.has(a))return ve(a,l,t);if(!ce())return ve(a,l,t);if(function(e,o){const t=fe.get(e);return Boolean(t&&t.has(o))}(n,a))return ve(a,l,t);if(function(e,o){const t=pe.get(e);return Boolean(t&&t.has(o))}(n,a))return{ok:!1,error:ye(a)};let c=null;if(("writeFile"===a||"editFile"===a)&&(c=N.previewMutation(a,l,t||{}),!c.ok))return{ok:!1,error:c.error};const d=await function(o,t,n,r){return new Promise((s=>{if(n&&n.aborted)return void s("cancel");const a=e();let i=!1;const l=()=>c("cancel"),c=e=>{i||(i=!0,he.delete(a),n&&n.removeEventListener("abort",l),s(e))};n&&n.addEventListener("abort",l,{once:!0}),he.set(a,{resolve:c}),"function"==typeof t?t({delta:"",approval:{id:a,sessionId:o,tool:r.tool,args:r.args,diff:r.diff||null}}):c("cancel")}))}(n,r,s,{tool:a,args:l,diff:c&&c.diff});if("deny"===d)return function(e,o){pe.has(e)||pe.set(e,new Set),pe.get(e).add(o)}(n,a),{ok:!1,error:ye(a)};if("session"!==d&&"once"!==d)return{ok:!1,error:`${a} was not executed — the request was cancelled.`};if("session"===d&&function(e,o){fe.has(e)||fe.set(e,new Set),fe.get(e).add(o)}(n,a),c){const e=N.applyChecked(a,l,c,t||{});return e&&!1!==e.ok&&t&&t.guard&&p(t.guard,l&&l.file_path),e}return ve(a,l,t)}function be(e){return S(v||{},e&&e.env||{},e)}async function xe(e,t){if("aegis"===e){const e=!t.singlePass&&(!!t.autonomous||void 0);return o.chatCompletion({prompt:t.prompt,system:t.system,messages:t.messages,model:t.model,mode:t.mode,maxTokens:t.statedMaxTokens,stream:!1!==t.stream,includeUsage:!0,onStream:t.onDelta,onReasoning:t.onReasoning,idleTimeoutMs:t.idleTimeoutMs,signal:t.signal,extra:{aegis_recall:!0,...t.recallDeep?{aegis_recall_deep:!0}:{},session:t.sessionId,...void 0===e?{}:{brain:e},...!1===e?{mode:"brain"}:{},...t.effort?{effort:t.effort}:{},...!0===e&&t.workers?{workers:t.workers}:{},...t.tools.length?{tools:t.tools}:{},...t.toolChoice?{tool_choice:t.toolChoice}:{}},agentKey:t.tools.length&&(process.env.AEGIS_AGENT_KEY||"").trim()||void 0})}if("byok"===e){const{provider:n,model:r}=M(t.model),s=P(n,r),a=L(n,s,t.effort);try{return await o.byokChatCompletion({provider:n,model:s,providerKey:t.apiKey,baseURL:t.cfg&&t.cfg.baseURL,prompt:t.prompt,system:t.system,messages:t.messages,maxTokens:t.maxTokens,tools:t.tools,toolChoice:t.toolChoice,effort:a&&"effort"===a.field?a.level:void 0,reasoningEffort:a&&"reasoning_effort"===a.field?a.level:void 0,stream:!0,onStream:t.onDelta,signal:t.signal})}catch(e){if(e&&402===e.status){const e=new Error("byok: this account has no AEGIS balance left, and the BYOK handling fee is billed there — your provider key is still valid, this is not a key problem. Top up the account, then try again (or /class aegis to use the pooled lane).");throw e.status=402,e}throw e}}if("local"===e){const o=t.cfg&&t.cfg.baseURL||A.DEFAULT_BASE,n=e=>A.chat({baseURL:o,model:t.model,prompt:t.prompt,system:t.system,messages:t.messages,maxTokens:t.maxTokens,signal:t.signal,onDelta:t.onDelta,...e&&t.tools.length?{tools:t.tools,toolChoice:t.toolChoice}:{}});try{return await n(!0)}catch(e){if(t.tools.length&&e&&400===e.status)return n(!1);throw e}}if("pro"===e){const e=t.sessionKey||t.rootSessionId||t.sessionId,o=e?me.get(e):null,n=function(e){const o=[],t=e=>String(e||"").replace(/[\\/]+$/,""),n=t(e),r=e=>{const r=t(e);r&&r!==n&&!o.includes(r)&&o.push(r)};let s=C;if(void 0===s)try{s=require("./git-scope.js")}catch{s=null}try{s&&"function"==typeof s.gitRoot&&r(s.gitRoot(e))}catch{}try{w&&"function"==typeof w.aegisHome&&r(w.aegisHome())}catch{}return o}(t.cwd),r=await c.runClaudePro({prompt:Q(t),model:t.model&&"default"!==t.model?t.model:void 0,system:t.system,cwd:t.cwd,addDir:n,resumeSessionId:o||void 0,gate:"function"==typeof x?!x():void 0,signal:t.signal,onDelta:t.onDelta,onSpawn:(e,o)=>{t.onDelta&&o&&t.onDelta({delta:"",note:c.childLine(o)})}});return e&&r&&r.sessionId&&!r.error&&me.set(e,r.sessionId),r}throw new Error(`dispatch: unknown model class ${JSON.stringify(e)} — this build ships 'aegis', 'byok', 'local' and 'pro' only`)}async function Se(t,s){const a=t&&t.class,d=t&&t.model,u=D("byok"===a?M(d).model:d,t&&t.maxTokens,t&&t.effort),p=function(e){const o=e=>{const o=Number(e);return Number.isFinite(o)&&o>0?o:void 0};return e&&Object.prototype.hasOwnProperty.call(e,"statedMaxTokens")?o(e.statedMaxTokens):o(e&&e.maxTokens)}(t),m="aegis"===a&&Boolean(t&&t.autonomous),h=Boolean(t&&t.roundsAsk),g=t&&t.sessionId||e(),y=Number.isInteger(t&&t.depth)?t.depth:0,k=t&&t.rootSessionId||g,v=t&&t.rootOnDelta||s,w="function"==typeof s?e=>e&&s({reasoning:e}):void 0,b=new AbortController;I.set(g,b);const x=b.signal,S=!(t&&!1===t.tools),_=S?N.toolsFor({includeSubagent:y<4}):[],$=t&&t.toolChoice||null,C=t&&t.system||q(be(t)),L=Array.isArray(t&&t.messages)?t.messages.filter(Boolean).slice():[];let O=L.length,U=t&&t.prompt||"";const P=String(U||""),R=Array.isArray(t&&t.attachments)?t.attachments.filter((e=>e&&"object"==typeof e)).slice(0,n.MAX_ATTACHMENTS):[];let F=R.length?n.buildContent(U,R):U,K=null;const B=be(t),G=B.cwd,z={getShell:()=>K||(K=new i({cwd:be(t).cwd})),signal:x,cwd:G,desktopdir:B.desktopdir};try{const e="byok"===a?M(d):null,i="byok"===a?f.get(T(e.provider))||{}:"local"===a&&f.get("local")||{},b="byok"===a?f.rawKey(T(e.provider)):null,I="byok"!==a?null:b||E(e.provider);if(!("byok"!==a||e.provider&&e.model)){const e=new Error('byok: model must be "<provider>:<model>" (pick one from /models) — got '+JSON.stringify(d||""));throw e.status=400,e}if("byok"===a&&!I){const o="anthropic"===e.provider?c.claudeProStatus({env:process.env}):null,t=j(e.provider).rejected,n=new Error(t?`${t}. That is why this turn has no ${e.provider} key: an env value that short is a paste that lost its payload, not a credential. Fix ${t.split(" ")[0]} in ~/.aegiscode/.env (or the shell that exported it) — or skip keys entirely: /byok-key ${e.provider} <key> to set one here.`:o&&o.loggedIn?`No Anthropic API key on this machine — an "anthropic:…" id is served by your own console key, which a Claude subscription is not. Use the subscription instead: /class pro (it spends your Claude Code ${o.subscription||"Pro"} plan through the claude CLI) — or add a real console key: /byok-key anthropic <key>.`:`No key for "${e.provider}" yet. Easiest fix: /class aegis (uses your AEGIS key, no setup) — or add this provider's own key: /byok-key ${e.provider} <key>.`);throw n.status=400,n}if("byok"===a&&!o.apiKey){const e=new Error("No AEGIS key connected yet. Easiest fix: /class aegis (skips BYOK entirely) — or add your AEGIS key with /login, then try again.");throw e.status=401,e}if("local"===a){const e=A.remoteRefusal(i.baseURL||A.DEFAULT_BASE);if(e)throw e}if("byok"===a&&"custom"===e.provider&&!(i.baseURL||"").trim()){const e=new Error('No endpoint saved for the "custom" provider — its key is on this machine but the address it dials is not, and no default exists for a vendor AEGIS does not know. Fix: /model-add custom <https-base-url> <api-key> <model-id> (writes both halves), or the endpoint field in Settings › Provider (custom).');throw e.status=400,e.code="custom_endpoint_missing",e}const q={cls:a,model:d,mode:t&&t.mode,maxTokens:u,statedMaxTokens:p,autonomous:m,sessionId:g,signal:x,onDelta:s,cfg:i,apiKey:I,toolChoice:$,cwd:G,rootSessionId:k,sessionKey:t&&t.sessionKey||void 0,effort:t&&t.effort,workers:t&&t.workers,recallDeep:t&&!0===t.recallDeep,singlePass:t&&!0===t.singlePass,onReasoning:w,idleTimeoutMs:m?9e5:void 0,stream:!t||!1!==t.stream};let D=!1,K=!1;const B=m?"AEGIS_AUTONOMOUS_MAX_ROUNDS":"AEGIS_CHAT_MAX_ROUNDS",W=(()=>{const e=Number.parseInt(process.env[B]||"",10);return Number.isFinite(e)&&e>0?e:0})(),Y=W||(m?40:24);let H=V.keyFor(t,L),J=V.take(H);if(!J&&!V.isStatedKey(t)){const e=V.adopt();e&&(J=e.entry,H=e.key)}if(J){const e=V.resumePreamble(J);0===L.length?Array.isArray(J.messages)&&J.messages.length&&L.push(...J.messages):Array.isArray(J.added)&&J.added.length&&L.push(...J.added),U?(U=`${e}\n\n${U}`,F=R.length?n.buildContent(U,R):U):(L.push({role:"user",content:e}),F=""),v&&v({delta:`\n\n[resuming work this session left unfinished at ${J.rounds} tool rounds`+(J.interruptions>1?` (cut off ${J.interruptions}×)`:"")+"…]\n"})}let Q=W||Y+(J?V.bonus(Y):0),ce=0;const fe=Y,pe=8;let me=0;const he={calls:0},ge=["input_tokens","output_tokens","prompt_tokens","completion_tokens","total_tokens","cache_read_input_tokens","cache_creation_input_tokens","prompt_cache_hit_tokens","prompt_cache_miss_tokens","reasoning_tokens","thinking_tokens"],ye=e=>{const o=e&&e.usage;if(o&&"object"==typeof o){he.calls+=1;for(const e of ge)"number"==typeof o[e]&&Number.isFinite(o[e])&&(he[e]=(he[e]||0)+o[e]);if("number"!=typeof o.total_tokens){const e=(o.prompt_tokens??o.input_tokens??0)+(o.completion_tokens??o.output_tokens??0);e&&(he.total_tokens=(he.total_tokens||0)+e)}}},ve=e=>e&&"object"==typeof e&&he.calls?{...e,usage:{...he}}:e,be=()=>{if(""===F)return;const e=L[L.length-1],o=e&&"user"===e.role?r(e.content):null;e&&"user"===e.role&&o===r(F)||L.push({role:"user",content:F}),U="",F=""};O=L.length;const Se=N&&N.MUTATING_TOOLS||new Set;let Ae=0,Te=0,Me=!1;for(;;){if(ce>=Q){if(h&&me<pe&&!x.aborted&&await ke(k,v,x,{spent:Q,extensions:me+1,max:pe,size:fe})){me+=1;const e=Q;Q+=fe,L.push({role:"user",content:`You have used all ${e} tool rounds allowed for this turn; ${fe} more have been granted (do not restart). Continue the task from exactly where you stopped — do not re-plan, do not repeat work already done, and finish with an answer.`});continue}const e=h?"":`, or raise ${B} for a longer single turn`,o=`[stopped at ${Q} tool rounds`+(he.total_tokens?`, ${he.total_tokens.toLocaleString()} tokens`:"")+". This session holds the work: your next message here resumes it automatically"+` (with a continuation preamble)${e}.]`,t=V.record(H,{rounds:ce,tokens:he.total_tokens||0,note:o,chain:J?J.interruptions:0,messages:L,added:L.slice(O)});return v&&v({delta:`\n\n${o}`}),ve({model:q.model,choices:[{message:{content:o},finish_reason:"length"}],stoppedOnRounds:!0,heldForSession:!0,heldRounds:t.rounds,sessionInterruptions:t.interruptions,resumedFrom:H})}ce+=1;const e={...q,system:C,messages:L,prompt:F,tools:_,recallDeep:q.recallDeep&&1===ce};let o;if(o=await xe(a,e),ye(o),x.aborted)return ve(o);if(!D&&!Z(o)&&(oe(o)||re(o))){D=!0;const t=re(o);if(o=await xe(a,{...e,singlePass:!0,recallDeep:!1,effort:t?"high":e.effort,maxTokens:se(e,t),statedMaxTokens:e.statedMaxTokens?ae(e.statedMaxTokens):void 0}),ye(o),x.aborted)return ve(o)}const n=_.length?X(o):[];if(!n.length){if(Z(o)||K||!S){if(!Me&&S&&de(P,Te>0,Ae)){Me=!0,be(),L.push({role:"assistant",content:Z(o)}),L.push({role:"user",content:"You ended the turn without changing any file, but this request asked for a change. The tools are still available in this reply: make the edit now with editFile or writeFile. If you already know what to change, change it — describing the fix is not the fix. If you genuinely cannot, say precisely what blocks you."}),v&&v({delta:""});continue}return ve(o)}K=!0,be(),L.push({role:"user",content:re(o)?le:ie});const t={...e,singlePass:!0,recallDeep:!1,messages:L,prompt:"",tools:[]};o=await xe(a,t);let n=t.maxTokens,r=t.effort;if(ye(o),x.aborted)return ve(o);if(!Z(o)&&(oe(o)||re(o))){const e=re(o);if(n=se(t,e),r=e?"high":t.effort,o=await xe(a,{...t,effort:r,maxTokens:n,statedMaxTokens:t.statedMaxTokens?ae(t.statedMaxTokens):void 0}),ye(o),x.aborted)return ve(o)}const s=(()=>{const e=Number(n)||0;if(!e)return n;const o={maxTokens:n};return t.statedMaxTokens&&(o.statedMaxTokens=t.statedMaxTokens),Math.max(e,se(o,!0))})();let i=0;for(;!Z(o)&&i<2&&!x.aborted;){const e=re(o);if(i+=1,L.push({role:"user",content:e?1===i?le:"Write your answer now, in plain prose, using only what is already in this conversation. If your information is incomplete, say what you have and what is missing — an incomplete answer is the expected outcome here and is better than none. No tools, no preface.":ie}),e&&(r="high"),n=s,o=await xe(a,{...t,messages:L,effort:r,maxTokens:n,statedMaxTokens:t.statedMaxTokens?ae(t.statedMaxTokens):void 0}),ye(o),x.aborted)return ve(o)}if(!Z(o))throw ue({cls:a,model:d,effort:r,recoveryRounds:i,finishReason:ee(o),reasoningChars:te(o).length,reasoningTokens:ne(o)});return ve(o)}be(),L.push({role:"assistant",content:Z(o),tool_calls:n.map((e=>({id:e.id,type:"function",function:{name:e.name,arguments:JSON.stringify(e.args)}})))});const r=new WeakMap,i=e=>{if("exec"!==e.name)return null;if(r.has(e))return r.get(e);const o=l(e.args&&e.args.command,{baseCwd:G});return r.set(e,o),o},c=e=>{if(e.name===N.SUBAGENT_TOOL)return!1;if(!Se.has(e.name))return!0;const o=i(e);return Boolean(o&&o.oneShot)},u=[];for(const e of n){const o=u[u.length-1];c(e)&&o&&o.parallel?o.calls.push(e):u.push({parallel:c(e),calls:[e]})}const f=async e=>{s&&s({delta:"",tool:{name:e.name,args:e.args,id:e.id,cwd:G,phase:"run"}});const o=i(e),n=o&&o.oneShot?{...z,oneShotExec:!0,cwd:o.cwd||z.cwd}:z,r=e.name===N.SUBAGENT_TOOL?await _e(e.args,{cls:a,model:d,statedMaxTokens:p,effort:t&&t.effort,mode:t&&t.mode,parentSignal:x,depth:y,rootSessionId:k,rootOnDelta:v}):await we(e,{toolCtx:n,rootSessionId:k,rootOnDelta:v,signal:x});return r&&r.usage&&ye({usage:r.usage}),s&&s({delta:"",tool:{name:e.name,args:e.args,ok:r.ok,id:e.id,cwd:G,phase:"done"}}),r};for(const e of u){const o=e.parallel&&e.calls.length>1?await Promise.all(e.calls.map((e=>f(e)))):[await f(e.calls[0])];e.calls.forEach(((e,t)=>{const n=o[t];Se.has(e.name)&&(Ae+=1,n&&n.ok&&(Te+=1)),L.push({role:"tool",tool_call_id:e.id,name:e.name,content:N.toolResultText(n)})}))}}}catch(e){throw x.aborted&&e&&"object"==typeof e&&(e.aegisCancelled=!0),e}finally{K&&K.dispose(),I.delete(g)}}async function _e({description:o,subagent_type:t,prompt:n}={},{cls:r,model:s,statedMaxTokens:a,effort:i,mode:l,parentSignal:c,depth:f,rootSessionId:p,rootOnDelta:m}={}){const h=String(n||o||"").trim();if(!h)return{ok:!1,error:"task requires a prompt"};const g=t&&"general"!==t?u(t):"general",y=d(t),k=e();let v;if(c){if(c.aborted)return{ok:!1,error:"aborted"};v=()=>Ae(k),c.addEventListener("abort",v,{once:!0})}try{const e=await Se({class:r,model:s,mode:l,system:y,prompt:h,sessionId:k,depth:(f||0)+1,rootSessionId:p,rootOnDelta:m,statedMaxTokens:a,effort:i},(()=>{})),o=Z(e),t=e&&e.usage?{usage:e.usage}:{};return o?{ok:!0,output:o,...t}:{ok:!1,error:`subagent (${g}) produced no output`,...t}}catch(e){return{ok:!1,error:`subagent (${g}) failed: ${e&&e.message?e.message:e}`}}finally{c&&v&&c.removeEventListener("abort",v)}}function Ae(e){const o=I.get(e);return o&&o.abort(),{ok:Boolean(o)}}return{CLASSES:_,listClasses:async function(){return _.map((e=>{if("aegis"===e.class)return{...e,configured:Boolean(o.apiKey)};if("byok"===e.class){const o=(f.list()||[]).some((e=>!(!e||"string"!=typeof e.provider||!e.provider.startsWith("byok:"))&&(!!e.configured||Boolean(E(e.provider.slice(5))))));return{...e,configured:o}}if("local"===e.class)return{...e,configured:!0};if("pro"===e.class){const o=c.claudeProStatus({env:process.env}),t=c.seamAvailable();return{...e,configured:o.loggedIn,status:o,seam:t}}return{...e,configured:!1}}))},listModels:async function(e){if("aegis"===e){if(!o.apiKey)return{class:e,models:[],needsKey:!0};const n=await o.listModels();return{class:e,models:O((t=n&&n.models,Array.isArray(t)?t.map((e=>"string"==typeof e?{id:e}:e)).filter((e=>e&&e.id)):[]))}}var t;if("byok"===e){let t=[],n=null,r=!1,s=null;try{const e=await o.byokProviders();t=R(z(U(e&&e.providers||[]))),n=e&&e.fee||null}catch(e){t=[],r=!0,s=e&&e.message||String(e)}const a=[];for(const e of t){if(!e||!e.id)continue;const o=f.get(T(e.id))||{},t=j(e.id),n=t.key||"",r=Array.isArray(e.models)?e.models:[];for(const s of r){const r="string"==typeof s?s:s&&s.id;r&&a.push({id:`${e.id}:${r}`,label:`${e.label||e.id} — ${r}`,provider:e.id,configured:Boolean(o.configured||n),keyRejected:t.rejected||null})}}return{class:e,models:a,providers:t,needsProviderKey:a.length>0&&!a.some((e=>e.configured)),needsAegisKey:!o.apiKey,fee:n,providersFailed:r,providersError:s,unmatchedProviders:K(t)}}if("local"===e){const o=(f.get("local")||{}).baseURL||A.DEFAULT_BASE,t=await A.probe(o);if(!t.running)return{class:e,models:[],baseURL:t.baseURL,needsDaemon:!0};let n=[],r=!0;try{n=await A.listTags(o)}catch{r=!1}return{class:e,models:n,baseURL:t.baseURL,listed:r}}if("pro"===e){const o=c.claudeProStatus({env:process.env});return{class:e,models:c.PRO_MODELS.map((e=>({id:e.id,label:e.label,note:e.note,configured:o.loggedIn}))),needsProviderKey:!1,needsAegisKey:!1,subscription:o.subscription,loggedIn:o.loggedIn,credentialFile:o.file,shadowed:o.shadowed||null,seam:c.seamAvailable()}}throw new Error(`listModels: unknown model class ${JSON.stringify(e)} — this build ships 'aegis', 'byok', 'local' and 'pro' only`)},chat:Se,cancel:Ae,respondApproval:function(e,o){const t=he.get(e);return t?(he.delete(e),t.resolve("session"===o||"once"===o?o:"deny"),{ok:!0}):{ok:!1}},respondRoundsAsk:function(e,o){const t=ge.get(e);return t?(ge.delete(e),t.resolve(!0===o||"continue"===o),{ok:!0}):{ok:!1}},clearSessionApprovals:function(e){return fe.delete(e),pe.delete(e),me.delete(e),{ok:!0}},settings:f,unloadLocalModels:function(){return A.unloadAll()},userModels:()=>F(),addUserModel:(e,o)=>B(e,o),removeUserModel:(e,o)=>G(e,o),discoverModels:async e=>{const o=String(null==e?"":e).trim().toLowerCase(),t=function(e){const o=String(null==e?"":e).trim().toLowerCase();if(!o)return"";try{if(f&&"function"==typeof f.rawKey){const e=f.rawKey(T(o));if("string"==typeof e&&e.trim())return e.trim()}}catch{}return E(o)}(o),n=await W(o,{key:t,fetchImpl:$});if(!n||!n.ok)return n;const r=[];try{const e=F().map;for(const t of Array.isArray(e[o])?e[o]:[])r.push(t)}catch{}return{...n,declared:r,endpoint:(H(o)||{}).url||""}},addUserModels:(e,o)=>{const t=Array.isArray(o)?o:[],n={provider:e,added:0,already:[],failed:[],capped:0,file:""};for(const o of t)try{const t=B(e,o);n.file=t.file||n.file,t.added?n.added+=1:n.already.push(t.model)}catch(e){const r=e&&e.message||String(e);if(/the cap/.test(r)){n.capped=t.length-n.added-n.already.length-n.failed.length;break}n.failed.push({id:String(o),reason:r})}return n},canDiscoverModels:e=>Y(e),discoverableProviders:()=>J()}},extractToolCalls:X,parseArgs:V,reasoningBudget:D,nativeEffort:L,hostEnv:S};
|
|
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};
|
|
@@ -1,3 +1,271 @@
|
|
|
1
1
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
2
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
-
|
|
3
|
+
// AEGIS Code (aegiscode) — source: https://github.com/aegisinfo/aegiscode-plugin
|
|
4
|
+
// Conveying a modified copy, or running one as a network service, owes the
|
|
5
|
+
// corresponding source under this licence (§5/§13) — see LICENSING.md.
|
|
6
|
+
/**
|
|
7
|
+
* Which `exec` calls are safe to run WITHOUT the turn's persistent shell.
|
|
8
|
+
*
|
|
9
|
+
* WHY THIS EXISTS. `engine.js` batches the read-only calls in a round into one
|
|
10
|
+
* `Promise.all`, but `exec` was excluded from that batching because it is in
|
|
11
|
+
* `MUTATING_TOOLS` — one persistent shell per turn means two concurrent
|
|
12
|
+
* commands would interleave their streams and the `__AEGIS_SH_…EXIT` sentinel
|
|
13
|
+
* each one parses would resolve the wrong call. That exclusion is correct, but
|
|
14
|
+
* it is also where the wall-clock went: across the measured SWE-bench runs
|
|
15
|
+
* 81.7% of tool calls are `exec` (438/536) and only 10.4% are readFile/grep/
|
|
16
|
+
* listDir/glob, so the parallel window covered a tenth of the work. Total time
|
|
17
|
+
* was 2223s against another harness's 1322s for the SAME patches while the
|
|
18
|
+
* medians matched (120s vs 126s) — a serial dispatch shows up as tail, not as
|
|
19
|
+
* median.
|
|
20
|
+
*
|
|
21
|
+
* THE OPENING. Most of those exec calls are not mutations at all. They are
|
|
22
|
+
* reads dressed as shell — `grep`, `sed -n`, `git log`, `ls`, `cat` — and
|
|
23
|
+
* 378 of 438 chain an absolute `cd` first, which is the habit the `exec` schema
|
|
24
|
+
* teaches ("state does not persist"? — it does, but the model writes `cd` anyway
|
|
25
|
+
* because every one-shot example it has seen does). A leading `cd <abs> &&` is
|
|
26
|
+
* therefore not state TO the command, it is an address the command carries with
|
|
27
|
+
* it: run that command with `cwd` set to that directory and the shell it does
|
|
28
|
+
* not touch is irrelevant.
|
|
29
|
+
*
|
|
30
|
+
* SO THE TEST IS: could this exact command run in a FRESH process, with `cwd`
|
|
31
|
+
* set as the lead-in says, and produce the same output? Everything below is an
|
|
32
|
+
* attempt to answer that conservatively. The bias is deliberate and one-way —
|
|
33
|
+
* a false negative costs a round of serial execution, a false positive corrupts
|
|
34
|
+
* a user's repository, so every uncertainty resolves to "keep it sequential".
|
|
35
|
+
*
|
|
36
|
+
* WHAT IS REJECTED, and why each one is not merely cautious:
|
|
37
|
+
* - a write verb anywhere in the command (`rm`, `mv`, `tee`, `>`, `>>`, `sed -i`,
|
|
38
|
+
* `pip install`, `patch`, `git commit`, …) — obviously not read-only;
|
|
39
|
+
* - `cd` that is NOT the sole leading `cd <path> &&` — a mid-command `cd`
|
|
40
|
+
* changes what a LATER command in the same string sees;
|
|
41
|
+
* - shell variables (`$FOO`, `${FOO}`), bare `export`, `source`, `.` — these
|
|
42
|
+
* only mean anything if session state exists, and with a fresh process they
|
|
43
|
+
* would expand to empty strings and silently produce a DIFFERENT result
|
|
44
|
+
* rather than an error;
|
|
45
|
+
* - job control / backgrounding (`&`, `nohup`), pipelines into a pager;
|
|
46
|
+
* - here-docs and multi-line commands — the exit sentinel logic is per-line
|
|
47
|
+
* and a multi-line body is the shape most likely to hide a write;
|
|
48
|
+
* - any command whose leading `cd` target is relative or `~`-relative beyond
|
|
49
|
+
* the first segment, because it would resolve against the SESSION's cwd,
|
|
50
|
+
* not this process's.
|
|
51
|
+
*/
|
|
52
|
+
|
|
53
|
+
// Read-shaped verbs that are safe as the FIRST word of a pipeline segment.
|
|
54
|
+
// Deliberately a small allow-list rather than a deny-list of write verbs: a
|
|
55
|
+
// deny-list fails open the moment someone invents a write verb we did not
|
|
56
|
+
// imagine, and the cost of failing open here is a corrupted tree.
|
|
57
|
+
//
|
|
58
|
+
// NOT in this set, on purpose: `python`, `python3`, `node`, `sh`, `bash`.
|
|
59
|
+
// They are arbitrary programs, and the contract this classifier has to prove is
|
|
60
|
+
// not "the command is a read the USER would call a read" but "the command cannot
|
|
61
|
+
// produce a filesystem mutation a CONCURRENT peer could observe". No text scan
|
|
62
|
+
// can prove that about an interpreter — `python -c "open(p,'w')"` is one line,
|
|
63
|
+
// and chasing every spelling of a write (`write`, `os.remove`, `shutil`,
|
|
64
|
+
// `subprocess`, `-m pip`) is an unbounded guess. So interpreter invocations stay
|
|
65
|
+
// on the sequential path. That is a real limit on how much of the measured
|
|
66
|
+
// exec traffic this opens up (most SWE-bench commands are `python -c`), and it
|
|
67
|
+
// is the reason the wall-clock gain here is bounded rather than dramatic.
|
|
68
|
+
const READ_VERBS = new Set([
|
|
69
|
+
'cat', 'head', 'tail', 'less', 'more', 'wc', 'grep', 'egrep', 'fgrep', 'rg',
|
|
70
|
+
'sed', 'awk', 'cut', 'sort', 'uniq', 'tr', 'diff', 'comm', 'join', 'nl',
|
|
71
|
+
'ls', 'dir', 'tree', 'stat', 'file', 'du', 'df', 'pwd', 'which', 'type',
|
|
72
|
+
'basename', 'dirname', 'realpath', 'readlink', 'find', 'locate',
|
|
73
|
+
'echo', 'printf', 'date', 'uname', 'whoami', 'id', 'env', 'printenv',
|
|
74
|
+
'true', 'test',
|
|
75
|
+
]);
|
|
76
|
+
|
|
77
|
+
// `git` subcommands that only read. `git diff/status/log/show/blame/grep` are
|
|
78
|
+
// the ones that actually appear in agent transcripts; anything else (`git
|
|
79
|
+
// checkout`, `git apply`, `git stash`, `git reset`) is not on this list on
|
|
80
|
+
// purpose.
|
|
81
|
+
const GIT_READ_SUBCOMMANDS = new Set([
|
|
82
|
+
'diff', 'status', 'log', 'show', 'blame', 'grep', 'ls-files', 'rev-parse',
|
|
83
|
+
'describe', 'cat-file', 'shortlog', 'whatchanged', 'reflog', 'show-ref',
|
|
84
|
+
'ls-tree', 'diff-tree', 'diff-files', 'diff-index', 'merge-base',
|
|
85
|
+
]);
|
|
86
|
+
|
|
87
|
+
// Absolute-write shapes. Any hit anywhere (not just at a segment start) makes
|
|
88
|
+
// the whole command sequential — `find . -delete`, `sed -i`, `python -c
|
|
89
|
+
// "open(p,'w')"` all hide their write behind a read-shaped verb.
|
|
90
|
+
const WRITE_PATTERNS = [
|
|
91
|
+
/(^|[\s;&|(])rm(\s|$)/,
|
|
92
|
+
/(^|[\s;&|(])rmdir(\s|$)/,
|
|
93
|
+
/(^|[\s;&|(])mv(\s|$)/,
|
|
94
|
+
/(^|[\s;&|(])cp(\s|$)/,
|
|
95
|
+
/(^|[\s;&|(])ln(\s|$)/,
|
|
96
|
+
/(^|[\s;&|(])mkdir(\s|$)/,
|
|
97
|
+
/(^|[\s;&|(])touch(\s|$)/,
|
|
98
|
+
/(^|[\s;&|(])chmod(\s|$)/,
|
|
99
|
+
/(^|[\s;&|(])chown(\s|$)/,
|
|
100
|
+
/(^|[\s;&|(])truncate(\s|$)/,
|
|
101
|
+
/(^|[\s;&|(])dd(\s|$)/,
|
|
102
|
+
/(^|[\s;&|(])tee(\s|$)/,
|
|
103
|
+
/(^|[\s;&|(])install(\s|$)/,
|
|
104
|
+
/(^|[\s;&|(])patch(\s|$)/,
|
|
105
|
+
/(^|[\s;&|(])git\s+(commit|add|rm|mv|checkout|switch|reset|apply|revert|merge|rebase|stash|clean|init|clone|pull|push|fetch|tag|branch|config)\b/,
|
|
106
|
+
/(^|[\s;&|(])sed\s+(-[a-zA-Z]*i|--in-place)/,
|
|
107
|
+
// `sort -o f`, `uniq -o`? — only a few read verbs take a write flag, and it
|
|
108
|
+
// is easy to miss because the verb is allow-listed. `grep -o` is NOT this
|
|
109
|
+
// (it only changes the OUTPUT shape), so the match is verb-qualified.
|
|
110
|
+
/(^|[\s;&|(])sort\b[^|;]*\s-o(\s|$)/,
|
|
111
|
+
/(^|[\s;&|(])sort\b[^|;]*--output=/,
|
|
112
|
+
/(^|[\s;&|(])dd\b[^|;]*\bof=/,
|
|
113
|
+
/(^|[\s;&|(])find\b[^|;]*\s-(fprint|fprint0|fls)\b/,
|
|
114
|
+
/(^|[\s;&|(])find\b[^|]*\s-(delete|exec|execdir|ok|okdir)\b/,
|
|
115
|
+
/(^|[\s;&|(])(pip|pip3)\s+(install|uninstall|download)\b/,
|
|
116
|
+
/(^|[\s;&|(])npm\s+(install|i|ci|uninstall|publish|run)\b/,
|
|
117
|
+
/(^|[\s;&|(])yarn\s+(add|install|remove)\b/,
|
|
118
|
+
/(^|[\s;&|(])apt(-get)?\s+(install|remove|purge|update|upgrade)\b/,
|
|
119
|
+
/(^|[\s;&|(])(python|python3)\s+-m\s+pip\s+install\b/,
|
|
120
|
+
/(^|[\s;&|(])pytest\b[^|]*--(cov|junitxml)/,
|
|
121
|
+
// Shell-level writes. `>` redirect is matched conservatively: `2>&1` and
|
|
122
|
+
// `>&-` are not writes, so the digit/`&` cases are excluded explicitly.
|
|
123
|
+
/(?<![0-9&])>>?(?![&-])/,
|
|
124
|
+
/\bexport\s+[A-Za-z_]/,
|
|
125
|
+
/(^|[\s;&|(])source(\s|$)/,
|
|
126
|
+
];
|
|
127
|
+
|
|
128
|
+
// Commands that only make sense against session state.
|
|
129
|
+
const STATEFUL_PATTERNS = [
|
|
130
|
+
/\$\{?[A-Za-z_][A-Za-z0-9_]*\}?/,
|
|
131
|
+
/(^|[\s;&|(])pushd(\s|$)/,
|
|
132
|
+
/(^|[\s;&|(])popd(\s|$)/,
|
|
133
|
+
/(^|[\s;&|(])nohup(\s|$)/,
|
|
134
|
+
/(^|[\s;&|(])disown(\s|$)/,
|
|
135
|
+
/<<-?\s*['"]?[A-Za-z_]/,
|
|
136
|
+
/(^|[\s;&|(])\&$/,
|
|
137
|
+
/(^|[\s;&|(])exec(\s|$)/,
|
|
138
|
+
/(^|[\s;&|(])history(\s|$)/,
|
|
139
|
+
/(^|[\s;&|(])jobs(\s|$)/,
|
|
140
|
+
];
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* Strip leading wrapper programs (`timeout 300`, `time`, `command`, `env -i`)
|
|
144
|
+
* down to the verb that actually runs. A wrapper must NOT be trusted on its
|
|
145
|
+
* own: `timeout 550 python x.py` starts with `timeout`, but the thing being
|
|
146
|
+
* run is an interpreter, and the allow-list has to judge THAT.
|
|
147
|
+
* Returns null when the wrapper chain hides something we cannot name.
|
|
148
|
+
*/
|
|
149
|
+
function effectiveVerb(words) {
|
|
150
|
+
let i = 0;
|
|
151
|
+
// Bound the walk: a pathological chain of wrappers is not worth reasoning
|
|
152
|
+
// about, and stopping early only costs a miss (stays sequential).
|
|
153
|
+
for (let guard = 0; guard < 4 && i < words.length; guard++) {
|
|
154
|
+
const w = words[i];
|
|
155
|
+
if (w === 'time' || w === 'command') { i += 1; continue; }
|
|
156
|
+
if (w === 'env') {
|
|
157
|
+
i += 1;
|
|
158
|
+
// `env -i`, `env -u X`, and `env FOO=1` prefixes are all local to this
|
|
159
|
+
// invocation (they are not session state), so skip them.
|
|
160
|
+
while (i < words.length && (words[i].startsWith('-') || /^[A-Za-z_][A-Za-z0-9_]*=/.test(words[i]))) i += 1;
|
|
161
|
+
continue;
|
|
162
|
+
}
|
|
163
|
+
if (w === 'timeout') {
|
|
164
|
+
i += 1;
|
|
165
|
+
while (i < words.length && words[i].startsWith('-')) i += 1;
|
|
166
|
+
// the duration argument
|
|
167
|
+
if (i < words.length && /^[0-9]+(\.[0-9]+)?[smhd]?$/.test(words[i])) i += 1;
|
|
168
|
+
continue;
|
|
169
|
+
}
|
|
170
|
+
if (w === 'nice') {
|
|
171
|
+
i += 1;
|
|
172
|
+
if (i < words.length && words[i] === '-n') i += 2;
|
|
173
|
+
else if (i < words.length && /^-?\d+$/.test(words[i])) i += 1;
|
|
174
|
+
continue;
|
|
175
|
+
}
|
|
176
|
+
break;
|
|
177
|
+
}
|
|
178
|
+
return i < words.length ? { verb: words[i], rest: words.slice(i) } : null;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** Split on `;`/`&&`/`||`/`|` into [ {sep, text} ] keeping the separators. */
|
|
182
|
+
function segments(command) {
|
|
183
|
+
const out = [];
|
|
184
|
+
const re = /(\|\||&&|[;|])/g;
|
|
185
|
+
let last = 0;
|
|
186
|
+
let m;
|
|
187
|
+
while ((m = re.exec(command))) {
|
|
188
|
+
out.push({ sep: null, text: command.slice(last, m.index) });
|
|
189
|
+
out.push({ sep: m[1] });
|
|
190
|
+
last = m.index + m[1].length;
|
|
191
|
+
}
|
|
192
|
+
out.push({ sep: null, text: command.slice(last) });
|
|
193
|
+
return out;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* Pull a single leading `cd <absolute path> &&` off the front.
|
|
198
|
+
* Returns { cwd, rest } — `cwd` is null when there is no such lead-in.
|
|
199
|
+
* Only an ABSOLUTE path qualifies: a relative one would resolve against the
|
|
200
|
+
* session's directory, which a one-shot process does not share.
|
|
201
|
+
*/
|
|
202
|
+
function leadingCd(command) {
|
|
203
|
+
const m = /^\s*cd\s+(?:--\s+)?(?:"([^"]+)"|'([^']+)'|([^\s;&|]+))\s*&&\s*([\s\S]+)$/.exec(command);
|
|
204
|
+
if (!m) return { cwd: null, rest: command };
|
|
205
|
+
const target = (m[1] || m[2] || m[3] || '').trim();
|
|
206
|
+
if (!target.startsWith('/')) return { cwd: null, rest: command };
|
|
207
|
+
// `cd /a && cd /b && …` — the second cd is not the lead-in, so the rest must
|
|
208
|
+
// be judged on its own (it will then be rejected as a non-leading cd).
|
|
209
|
+
return { cwd: target, rest: m[4] };
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* Decide whether `command` may run as a one-shot process with an explicit cwd.
|
|
214
|
+
*
|
|
215
|
+
* @param {string} command raw command the model asked `exec` to run
|
|
216
|
+
* @param {object} [opts]
|
|
217
|
+
* @param {string} [opts.baseCwd] the turn's cwd, used when there is no lead-in
|
|
218
|
+
* @returns {{ oneShot: boolean, cwd: string|null, reason: string }}
|
|
219
|
+
* `reason` is for tests and diagnostics; it is never shown to the model.
|
|
220
|
+
*/
|
|
221
|
+
function planExec(command, opts = {}) {
|
|
222
|
+
const baseCwd = opts.baseCwd || null;
|
|
223
|
+
const raw = typeof command === 'string' ? command : '';
|
|
224
|
+
const no = (reason) => ({ oneShot: false, cwd: null, reason });
|
|
225
|
+
|
|
226
|
+
if (!raw.trim()) return no('empty command');
|
|
227
|
+
// A newline means a multi-command body. The session's exit sentinel is
|
|
228
|
+
// appended per command and a multi-line body is where a write hides; not
|
|
229
|
+
// worth the risk for the handful of these a turn contains.
|
|
230
|
+
if (raw.includes('\n')) return no('multi-line command');
|
|
231
|
+
|
|
232
|
+
for (const re of STATEFUL_PATTERNS) {
|
|
233
|
+
if (re.test(raw)) return no('depends on session state');
|
|
234
|
+
}
|
|
235
|
+
for (const re of WRITE_PATTERNS) {
|
|
236
|
+
if (re.test(raw)) return no('contains a write');
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
const { cwd, rest } = leadingCd(raw);
|
|
240
|
+
const restText = rest.trim();
|
|
241
|
+
if (!restText) return no('nothing after the cd');
|
|
242
|
+
|
|
243
|
+
// Every segment must start with a read-shaped verb. `git` is special-cased
|
|
244
|
+
// on its subcommand; a bare `git` with no subcommand reads the status, which
|
|
245
|
+
// is read-only, and `git --version` likewise.
|
|
246
|
+
const segs = segments(restText).filter((s) => !s.sep);
|
|
247
|
+
if (!segs.length) return no('no command');
|
|
248
|
+
for (const seg of segs) {
|
|
249
|
+
const words = seg.text.trim().replace(/^\(+\s*/, '').split(/\s+/).filter(Boolean);
|
|
250
|
+
if (!words.length) continue;
|
|
251
|
+
const eff = effectiveVerb(words);
|
|
252
|
+
if (!eff) return no('empty command after wrappers');
|
|
253
|
+
const verb = eff.verb;
|
|
254
|
+
if (verb === 'git') {
|
|
255
|
+
const sub = eff.rest[1];
|
|
256
|
+
if (!sub || sub.startsWith('-')) continue; // `git`, `git --version`
|
|
257
|
+
if (!GIT_READ_SUBCOMMANDS.has(sub)) return no(`git ${sub} is not read-only`);
|
|
258
|
+
continue;
|
|
259
|
+
}
|
|
260
|
+
if (!READ_VERBS.has(verb)) return no(`${verb} is not a known read verb`);
|
|
261
|
+
// `sed -i` is already caught by WRITE_PATTERNS above, but `sed … -w file`
|
|
262
|
+
// and `awk … > file` write without an `-i`.
|
|
263
|
+
if ((verb === 'sed' || verb === 'awk') && /(^|\s)-[a-zA-Z]*w\s/.test(eff.rest.join(' '))) {
|
|
264
|
+
return no(`${verb} writes a file`);
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
return { oneShot: true, cwd: cwd || baseCwd, reason: 'read-only' };
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
module.exports = { planExec, READ_VERBS, GIT_READ_SUBCOMMANDS, WRITE_PATTERNS, STATEFUL_PATTERNS };
|