aegisone 1.0.77 → 1.0.78
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/README.md +1 -1
- package/package.json +1 -1
- package/vendor/cli/package.json +1 -1
- package/vendor/cli/src/app.js +1 -1
- package/vendor/cli/src/models.js +1 -1
- package/vendor/cli/vendor/desktop/lib/local/context.js +1 -1
- package/vendor/cli/vendor/desktop/lib/local/engine.js +1 -1
- package/vendor/cli/vendor/desktop/lib/local/local.js +1 -1
- package/vendor/cli/vendor/desktop/lib/local/prompt.js +1 -1
- package/vendor/desktop/lib/local/context.js +1 -1
- package/vendor/desktop/lib/local/engine.js +1 -1
- package/vendor/desktop/lib/local/local.js +1 -1
- package/vendor/desktop/lib/local/memo.js +3 -0
- package/vendor/desktop/lib/local/prompt.js +1 -1
- package/vendor/desktop/lib/sync/memory-rank.js +3 -0
- package/vendor/desktop/lib/sync/memory-store.js +1 -1
- package/vendor/desktop/package.json +1 -1
- package/vendor/desktop/vendor/faces/cli/package.json +1 -1
- package/vendor/desktop/vendor/faces/cli/src/app.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/models.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/context.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/engine.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/local.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/prompt.js +1 -1
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
2
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
-
"use strict";const{randomUUID:randomUUID}=require("node:crypto"),os=require("node:os"),fs=require("node:fs"),toolsModule=require("./tools.js"),attachmentsModule=require("./attachments.js"),{flattenContent:flattenContent}=attachmentsModule,promptModule=require("./prompt.js"),localTransport=require("./local.js"),{ShellSession:ShellSession}=require("./shell.js"),{planExec:planExec}=require("./exec-plan.js"),claudePro=require("./claude-pro.js"),{agentSystemPrompt:agentSystemPrompt,agentRoleLabel:agentRoleLabel}=require("./agents.js"),{beginTurnGuard:beginTurnGuard,recordWrite:recordWrite,blocksDestructive:blocksDestructive}=require("./turn-guard.js"),repeatGuard=require("./repeat-guard.js"),verifyGuard=require("./verify-stop.js"),{acquireWorktreeLock:acquireWorktreeLock,releaseWorktreeLock:releaseWorktreeLock}=require("./worktree-lock.js"),covenant=require("./covenant.js");let envFile=null;try{envFile=require("../../../client/env-file.js")}catch{try{envFile=require("../../vendor/env-file.js")}catch{envFile=null}}let platformLib=null;try{platformLib=require("../../../client/platform.js")}catch{try{platformLib=require("../../vendor/platform.js")}catch{platformLib=null}}let credentialsLib=null;try{credentialsLib=require("../../../client/credentials.js")}catch{try{credentialsLib=require("../../vendor/credentials.js")}catch{credentialsLib=null}}const PRO_TOOL_MAP=Object.freeze({Write:"writeFile",Edit:"editFile",MultiEdit:"editFile",NotebookEdit:"editFile",Bash:"exec",BashOutput:"exec"}),PRO_PLAN_MODE_SAFE=Object.freeze(new Set(["Read","Glob","Grep"]));function proAskArgs(e,t){const o=e&&"object"==typeof e?e:{};return"exec"===t?"string"==typeof o.command?{command:o.command}:{}:"writeFile"===t?"string"==typeof o.file_path?{file_path:o.file_path,content:o.content}:{}:"editFile"===t?Array.isArray(o.edits)?{file_path:o.file_path,edits:o.edits}:"string"==typeof o.file_path?{file_path:o.file_path,old_string:o.old_string,new_string:o.new_string,replace_all:!0===o.replace_all}:{}:o}function normalizeToolArgs(e,t,o,r){const n=e&&"function"==typeof e.normalizeArgs&&e.normalizeArgs||"function"==typeof toolsModule.normalizeArgs&&toolsModule.normalizeArgs||null;return n?n(t,o,r):{ok:!0,args:o&&"object"==typeof o?o:{},error:null}}function detectVcs(e){if(!e)return null;try{const t=require("node:fs"),o=require("node:path");let r=o.resolve(String(e));for(let e=0;e<8;e+=1){if(t.existsSync(o.join(r,".git")))return"git";const e=o.dirname(r);if(e===r)break;r=e}return""}catch{return null}}function hostEnv(e={},t={},o=null){const r=e||{},n=t||{},s=(e,t)=>null!=n[e]?n[e]:t;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",o&&o.model)}}function requireSharedBrain(){const e=[()=>require("../../../client/brain-catalog.js"),()=>require("../../vendor/brain-catalog.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}function requireSharedByokCatalog(){const e=[()=>require("../../../client/byok-catalog.js"),()=>require("../../vendor/byok-catalog.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}function requireSharedUserModels(){const e=[()=>require("../../../client/user-models.js"),()=>require("../../vendor/user-models.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}function requireSharedCatalogClient(){const e=[()=>require("../../../client/catalog-client.js"),()=>require("../../vendor/catalog-client.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}function requireSharedModelDiscovery(){const e=[()=>require("../../../client/model-discovery.js"),()=>require("../../vendor/model-discovery.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}function requireSharedModelSync(){const e=[()=>require("../../../client/model-sync.js"),()=>require("../../vendor/model-sync.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}function requireSharedModelAutoSync(){const e=[()=>require("../../../client/model-autosync.js"),()=>require("../../vendor/model-autosync.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}const WORKTREE_LOCK_WAIT_MS=1500,MAX_SUBAGENT_DEPTH=4,CLASSES=[{class:"aegis",label:"Aegis Cloud",kind:"cloud"},{class:"byok",label:"Bring your own key",kind:"cloud"},{class:"local",label:"Local model",kind:"local"},{class:"pro",label:"Claude Code Pro",kind:"subscription"}],BYOK_NAMESPACE_PREFIX="byok:";function byokNamespace(e){return`byok:${e}`}function splitByokModel(e){const t="string"==typeof e?e:"",o=t.indexOf(":");return o<0?{provider:"",model:t}:{provider:t.slice(0,o),model:t.slice(o+1)}}function providerKeyRecord(e){const t={key:"",env:"",rejected:null};if(!envFile||"function"!=typeof envFile.providerKeyFromEnv)return t;try{const o=envFile.providerKeyFromEnv(e)||t;return{key:"string"==typeof o.key?o.key:"",env:"string"==typeof o.env?o.env:"",rejected:"string"==typeof o.rejected&&o.rejected?o.rejected:null}}catch{return t}}function providerKeyFromEnv(e){if(!envFile||"function"!=typeof envFile.providerKeyFromEnv)return"";try{return envFile.providerKeyFromEnv(e).key||""}catch{return""}}const DEEPSEEK_REASONING_MODEL_RE=/^deepseek-(v4(\.\d+)?-(flash|pro)|flash|pro|reasoner)$/,EFFORT_TOKEN_BUDGET={low:8192,medium:16384,high:32768,max:32768},DEEPSEEK_EFFORT={low:"low",medium:"high",high:"high"},DEEPSEEK_EFFORT_EXTRA={max:"max"},EFFORT_IDENTITY={low:"low",medium:"medium",high:"high"},EFFORT_INERT_RE=/non-reasoning/i,EFFORT_DIALECTS=[{provider:"deepseek",re:DEEPSEEK_REASONING_MODEL_RE,field:"effort",map:DEEPSEEK_EFFORT,extra:DEEPSEEK_EFFORT_EXTRA},{provider:"openai",re:/^(gpt-5|o[0-9])/i,field:"reasoning_effort",map:EFFORT_IDENTITY},{provider:"groq",re:/^(openai\/gpt-oss|qwen\/qwen3)/i,field:"reasoning_effort",map:EFFORT_IDENTITY},{provider:"xai",re:/^grok-(4\.[5-9]|[5-9])/,field:"reasoning_effort",map:EFFORT_IDENTITY},{provider:"google",re:/^gemini-(2\.5|3|[4-9])/,field:"reasoning_effort",map:{...EFFORT_IDENTITY,medium:"high"}}],AUTONOMOUS_IDLE_TIMEOUT_MS=9e5;function reasoningBudget(e,t,o){const r=Number(t);return Number.isFinite(r)&&r>0?r:DEEPSEEK_REASONING_MODEL_RE.test(String(e||""))?EFFORT_TOKEN_BUDGET["low"===o||"medium"===o||"max"===o?o:"high"]:void 0}function nativeEffort(e,t,o){const r=String(t||"");if(EFFORT_INERT_RE.test(r))return;if(null===o)return;const n="low"===o||"medium"===o?o:"max"===o?"max":"high";for(const t of EFFORT_DIALECTS)if(t.provider===e&&t.re.test(r)){const e=Object.prototype.hasOwnProperty.call(t.map,n)?t.map[n]:t.extra&&Object.prototype.hasOwnProperty.call(t.extra,n)?t.extra[n]:void 0;if(void 0===e)return;return{field:t.field,level:e}}}function normalizeCatalog(e){return Array.isArray(e)?e.map(e=>"string"==typeof e?{id:e}:e).filter(e=>e&&e.id):[]}const{offerableCatalog:offerableCatalog}=requireSharedBrain(),{withByokAdditions:withByokAdditions,canonicalModelId:canonicalModelId,nexusFallbackModel:nexusFallbackModel}=requireSharedByokCatalog(),{withUserModels:withUserModels,unmatchedUserProviders:unmatchedUserProviders,load:loadUserModels,addUserModel:addUserModel,removeUserModel:removeUserModel}=requireSharedUserModels(),{withCatalog:withCatalog}=requireSharedCatalogClient(),{discoverModels:discoverVendorModels,canDiscover:canDiscoverVendorModels,endpointFor:vendorEndpointFor,discoverableProviders:discoverableProviders}=requireSharedModelDiscovery(),modelSync=requireSharedModelSync(),{createModelAutoSync:createModelAutoSync}=requireSharedModelAutoSync();function parseArgs(e){if(null==e)return{};if("object"==typeof e)return e;try{const t=JSON.parse(String(e));return t&&"object"==typeof t?t:{}}catch{return{}}}function extractToolCalls(e){if(!e)return[];if(Array.isArray(e.toolCalls)&&e.toolCalls.length)return e.toolCalls.map(e=>({id:e.id||"",name:e.name||"",args:parseArgs(e.args)})).filter(e=>e.name);const t=e.choices&&e.choices[0]&&e.choices[0].message,o=t&&t.tool_calls||[];return Array.isArray(o)?o.map(e=>{const t=e&&e.function||{};return{id:e&&e.id||"",name:t.name||e&&e.name||"",args:parseArgs(t.arguments)}}).filter(e=>e.name):[]}function proTurnPrompt(e){const t=Array.isArray(e.prompt)?flattenContent(e.prompt):e.prompt;if("string"==typeof t&&t.trim())return t;const o=Array.isArray(e.messages)?e.messages:[];for(let e=o.length-1;e>=0;e-=1){const t=o[e];if(!t||"user"!==t.role)continue;const r=flattenContent(t.content);if(r.trim())return r}return t}function assistantText(e){const t=e&&e.choices&&e.choices[0]&&e.choices[0].message;return t&&"string"==typeof t.content&&t.content||""}function finishReasonOf(e){const t=e&&e.choices&&e.choices[0];return t&&t.finish_reason||e&&e.stop_reason||""}function isTruncated(e){const t=finishReasonOf(e);return"length"===t||"max_tokens"===t}function reasoningTextOf(e){if(!e)return"";const t=e.choices&&e.choices[0],o=t&&t.message||{};if(Array.isArray(o.content)){const e=o.content.filter(e=>e&&("thinking"===e.type||"reasoning"===e.type)).map(e=>e.thinking||e.text||"").join("");if(e)return e}const r=o.content&&"object"==typeof o.content?o.content.reasoning_content:"",n=[o.reasoning_content,o.reasoning,t&&t.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 t=e.choices&&e.choices[0],o=t&&t.message||{},r=e.usage||{},n=r.completion_tokens_details||r.output_tokens_details||{},s=[o.thinking_tokens,o.reasoning_tokens,t&&t.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,t){const o=doubledBudget(e.maxTokens);return t&&ladderRung(e.maxTokens)?Math.max(o,32768):o}function ladderRung(e){const t=Number(e);return Number.isFinite(t)&&Object.values(EFFORT_TOKEN_BUDGET).includes(t)}function doubledBudget(e){const t=Number(e)||0;return t>0?2*t:8192}function statedCapOf(e){const t=e=>{const t=Number(e);return Number.isFinite(t)&&t>0?t:void 0};return e&&Object.prototype.hasOwnProperty.call(e,"statedMaxTokens")?t(e.statedMaxTokens):t(e&&e.maxTokens)}const EMPTY_TURN_NUDGE="Your previous reply came back empty — it contained no answer and no tool call. Write your answer now, using only the information already gathered above. No tools are available in this reply, so do not call any: respond in plain prose or markdown.",THOUGHT_ONLY_NUDGE="Your previous round was spent entirely on hidden reasoning and produced no visible reply. Answer the user directly and briefly now. Do not reason, explain, or think first — write only the answer, no tools.",FINAL_ANSWER_NUDGE="Write your answer now, in plain prose, using only what is already in this conversation. If your information is incomplete, say what you have and what is missing — an incomplete answer is the expected outcome here and is better than none. No tools, no preface.",RECOVERY_ROUNDS=2,UNMUTATED_TURN_NUDGE="You ended the turn without changing any file, but this request asked for a change. The tools are still available in this reply: make the edit now with editFile or writeFile. If you already know what to change, change it — describing the fix is not the fix. If you genuinely cannot, say precisely what blocks you.",MUTATION_INTENT_RE=new RegExp("\\b(?:fix|implement|add|create|write|refactor|rename|remove|delete|replace|update|patch|migrate|convert|make\\s+(?:it|them|this|that|the|sure)|change|correct|resolve|repair|address|apply|introduce|support|wire\\s+up)\\b","i");function wantsMutation(e,t,o){if(t)return!1;if(!(o>0))return!1;const r=String(e||"");return!!r.trim()&&!/\?\s*$/.test(r.trim())&&MUTATION_INTENT_RE.test(r)}function emptyTurnError({cls:e,model:t,finishReason:o,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}/${t} was asked to summarise its results`+(i?`, and ${i} extra recovery call${1===i?"":"s"} with a larger budget and a changed ask came back empty too`:"")+` (stop reason: ${o||"none"}`+(s?`, effort: ${s}`:"")+(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:t,tools:o,promptBuilder:r,recallProvider:n,env:s,getConfirmMode:a,getPermissionMode:i,sandbox:l,localTransport:c=localTransport,fetchImpl:d,gitScope:u,permissionRules:f}){const p=new Map,m=o||toolsModule,h=r&&r.buildSystemPrompt||promptModule.buildSystemPrompt,y=f&&"function"==typeof f.rulesVerdict?f.rulesVerdict:null,g=f&&"function"==typeof f.alwaysAllow?f.alwaysAllow:null,k=f&&"function"==typeof f.subjectFor?f.subjectFor:null,v=require("./session-rounds.js"),b=()=>{if("function"==typeof a)return!1!==a();if(t&&"function"==typeof t.getConfirmMode){const e=t.getConfirmMode();return void 0===e||Boolean(e)}return!0},w=()=>"function"==typeof i?"plan"===i():!(!t||"function"!=typeof t.getPermissionMode)&&"plan"===t.getPermissionMode();function E(e,t){return`${e} was not executed — this session is in plan mode (read-only). Plan mode may read files, search, run read-only shell commands and deploy subagents to research, but may not create, edit or delete files, run a mutating command, or install packages`+(t?` (this command: ${t})`:"")+". Do NOT retry it or attempt the same effect by another route. Finish your research and present a plan in plain text; the user exits plan mode (`/permissions mode off`) before any edit can run."}const S=new Map,_=new Map,T=new Map,x=new Map,A=require("./pro-sessions.js"),M=new Map,O=new Map;function N(e,t){if("function"!=typeof k)return e;let o="";try{o=String(k(e,t||{})||"")}catch{o=""}return`${e}\0${o}`}function F(e,t,o){S.has(e)||S.set(e,new Set),S.get(e).add(N(t,o))}function D(e,t){const o=_.get(e);return Boolean(o&&o.has(t))}function R(e,t){_.has(e)||_.set(e,new Set),_.get(e).add(t)}function U(e){if(!e)return null;try{return{existed:!0,content:fs.readFileSync(e,"utf8")}}catch(e){return e&&"ENOENT"===e.code?{existed:!1,content:null}:null}}function I(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 L(e,t,o,r){return new Promise(n=>{if(o&&o.aborted)return void n("cancel");const s=randomUUID();let a=!1;const i=()=>l("cancel"),l=e=>{a||(a=!0,M.delete(s),o&&o.removeEventListener("abort",i),n(e))};o&&o.addEventListener("abort",i,{once:!0}),M.set(s,{resolve:l}),"function"==typeof t?t({delta:"",approval:{id:s,sessionId:e,tool:r.tool,args:r.args,diff:r.diff||null,canPersist:"function"==typeof g}}):l("cancel")})}function C(e,t,o,r){return new Promise(n=>{if(o&&o.aborted)return void n(!1);const s=randomUUID();let a=!1;const i=()=>l(!1),l=e=>{a||(a=!0,O.delete(s),o&&o.removeEventListener("abort",i),n(e))};o&&o.addEventListener("abort",i,{once:!0}),O.set(s,{resolve:l}),"function"==typeof t?t({delta:"",rounds:{id:s,sessionId:e,spent:r.spent,extensions:r.extensions,max:r.max,size:r.size}}):l(!1)})}async function P(e,t,o,r,n){const s=normalizeToolArgs(m,e,t,o||{});if(!s.ok)return{ok:!1,error:s.error};t=s.args;const a=o&&o.guard;if(a&&"exec"===e){const e=blocksDestructive(a,t&&t.command);if(!e.ok)return{ok:!1,error:e.reason}}const i=o&&o.repeat,l=i?repeatGuard.check(i,e,t):null;if(l&&"refuse"===l.action)return{ok:!1,error:l.error};const c=covenant.preActionAssert({tool:e,args:t||{}});if(!c.allowed){const o=covenant.bindRefusal({tool:e,args:t||{}},c);return{ok:!1,error:`refused by the ÆGIS covenant — ${c.clause} (${c.label}): ${c.reason}`,covenant:o}}const d="writeFile"===e||"editFile"===e,u=d?U(t&&t.file_path):null,f=await m.executeTool(e,t,o);a&&d&&f&&!1!==f.ok&&recordWrite(a,t&&t.file_path),i&&d&&f&&!1!==f.ok&&repeatGuard.recordWrite(i,t&&t.file_path);const p=o&&o.verify;if(p&&(verifyGuard.EXEC_TOOLS.has(e)&&f&&!1!==f.ok?verifyGuard.recordExec(p):d&&f&&!1!==f.ok&&verifyGuard.recordMutation(p,t&&t.file_path)),d&&u&&f&&!1!==f.ok){const o=U(t&&t.file_path);o&&function(e,t){if(!e)return;T.has(e)||T.set(e,[]);const o=T.get(e);o.push(t),o.length>200&&o.shift()}(r,{id:n||randomUUID(),tool:e,path:t&&t.file_path,before:u,after:o,at:Date.now()})}return l&&l.note?$(f,l.note):f}function $(e,t){if(!e||"object"!=typeof e)return{ok:!0,content:`${t}\n${null==e?"":e}`};if(!1===e.ok||!0===e.isError){const o=e.error||e.content||"";return{...e,error:`${t}\n${o}`,content:`${t}\n${o}`}}const o=null!=e.content?e.content:null!=e.output?e.output:"";return{...e,content:`${t}\n${o}`}}async function q(e,{toolCtx:t,rootSessionId:o,rootOnDelta:r,signal:n}){const{name:s}=e,a=normalizeToolArgs(m,s,e.args,t||{});if(!a.ok)return{ok:!1,error:a.error};const i=a.args;if(!m.MUTATING_TOOLS.has(s))return P(s,i,t,o,e.id);if(w()){if("exec"===s){const r=planExec(i&&i.command,{baseCwd:t&&t.cwd||void 0});return r.oneShot?P(s,i,t,o,e.id):{ok:!1,error:E(s,r.reason)}}return{ok:!1,error:E(s)}}if(!b())return P(s,i,t,o,e.id);if(function(e,t,o){const r=S.get(e);return Boolean(r&&r.has(N(t,o)))}(o,s,i))return P(s,i,t,o,e.id);if("function"==typeof y){let r;try{r=y(s,i)}catch(e){r={verdict:null,source:"error",error:e&&e.message||String(e)}}if(r&&"deny"===r.verdict)return R(o,s),{ok:!1,error:I(s),permissionRule:r.rule||null};if(r&&"allow"===r.verdict)return P(s,i,t,o,e.id)}if(D(o,s))return{ok:!1,error:I(s)};let l=null;if(("writeFile"===s||"editFile"===s)&&(l=m.previewMutation(s,i,t||{}),!l.ok))return{ok:!1,error:l.error};const c=await L(o,r,n,{tool:s,args:i,diff:l&&l.diff});if("deny"===c)return R(o,s),{ok:!1,error:I(s)};if("session"!==c&&"once"!==c&&"always"!==c)return{ok:!1,error:`${s} was not executed — the request was cancelled.`};let d=null;if("always"===c){let e=null;if("function"==typeof g)try{e=g(s,i)}catch(t){e={ok:!1,reason:t&&t.message||String(t)}}else e={ok:!1,reason:"no durable store is wired on this host"};d=e&&e.ok?`[permission_rule] stored ${e.rule} — this command will not ask again`:`[permission_rule] nothing was stored — ${e&&e.reason||"unknown reason"}; this call was allowed once only`}if("session"===c&&F(o,s,i),l){const e=m.applyChecked(s,i,l,t||{});return e&&!1!==e.ok&&t&&t.guard&&recordWrite(t.guard,i&&i.file_path),d?$(e,d):e}const u=await P(s,i,t,o,e.id);return d?$(u,d):u}function j(e){return hostEnv(s||{},e&&e.env||{},e)}function B(e){const t=[],o=e=>String(e||"").replace(/[\\/]+$/,""),r=o(e),n=e=>{const n=o(e);n&&n!==r&&!t.includes(n)&&t.push(n)};let s=u;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 t}async function G(t,o){if("aegis"===t){const t=!o.singlePass&&(!!o.autonomous||void 0);return e.chatCompletion({prompt:o.prompt,system:o.system,messages:o.messages,model:o.model,mode:o.mode,maxTokens:o.statedMaxTokens,stream:!1!==o.stream,includeUsage:!0,onStream:o.onDelta,onReasoning:o.onReasoning,idleTimeoutMs:o.idleTimeoutMs,signal:o.signal,extra:{aegis_recall:!0,...o.recallDeep?{aegis_recall_deep:!0}:{},session:o.sessionId,...void 0===t?{}:{brain:t},...!1===t?{mode:"brain"}:{},...o.effort?{effort:o.effort}:{},...!0===t&&o.workers?{workers:o.workers}:{},...o.tools.length?{tools:o.tools}:{},...o.toolChoice?{tool_choice:o.toolChoice}:{}},agentKey:o.tools.length&&(process.env.AEGIS_AGENT_KEY||"").trim()||void 0})}if("byok"===t){const{provider:t,model:r}=splitByokModel(o.model),n=canonicalModelId(t,r),s=nativeEffort(t,n,o.effort);try{return await e.byokChatCompletion({provider:t,model:n,providerKey:o.apiKey,baseURL:o.cfg&&o.cfg.baseURL,prompt:o.prompt,system:o.system,messages:o.messages,maxTokens:o.maxTokens,tools:o.tools,toolChoice:o.toolChoice,effort:s&&"effort"===s.field?s.level:void 0,reasoningEffort:s&&"reasoning_effort"===s.field?s.level:void 0,stream:!0,onStream:o.onDelta,signal:o.signal})}catch(e){if(e&&402===e.status){const e=new Error("byok: this account has no AEGIS balance left, and the BYOK handling fee is billed there — your provider key is still valid, this is not a key problem. Top up the account, then try again (or /class aegis to use the pooled lane).");throw e.status=402,e}throw e}}if("local"===t){const e=o.cfg&&o.cfg.baseURL||c.DEFAULT_BASE,t=t=>c.chat({baseURL:e,model:o.model,prompt:o.prompt,system:o.system,messages:o.messages,maxTokens:o.maxTokens,signal:o.signal,onDelta:o.onDelta,...t&&o.tools.length?{tools:o.tools,toolChoice:o.toolChoice}:{}});try{return await t(!0)}catch(e){if(o.tools.length&&e&&400===e.status)return t(!1);throw e}}if("pro"===t){const e=o.sessionKey||o.rootSessionId||o.sessionId;let t=null;if(e&&(t=x.get(e)||null,!t)){try{t=A.get(e,s)||null}catch{}t&&x.set(e,t)}const r=B(o.cwd),n=e=>claudePro.runClaudePro({prompt:proTurnPrompt(o),model:o.model&&"default"!==o.model?o.model:void 0,system:o.system,cwd:o.cwd,addDir:r,resumeSessionId:e||void 0,gate:b(),onAsk:async e=>{if(!e||!e.requestId)return"deny";const t=o.rootSessionId,r=o.rootOnDelta,n=PRO_TOOL_MAP[String(e.toolName||"")]||null,s=n||String(e.toolName||"unknown"),a=proAskArgs(e.input||{},s),i=covenant.preActionAssert({tool:s,args:a});if(!i.allowed)return r&&r({delta:"",note:`aegis: refused by the ÆGIS covenant — ${i.clause} (${i.label}): ${i.reason}`}),"deny";if(w()){if("exec"===s){const e=planExec(a&&a.command,{baseCwd:o.cwd||void 0});return e.oneShot?"once":(r&&r({delta:"",note:E(s,e.reason)}),"deny")}if(n&&m.MUTATING_TOOLS.has(s))return r&&r({delta:"",note:E(s)}),"deny";if(!n&&!PRO_PLAN_MODE_SAFE.has(s))return r&&r({delta:"",note:E(s)}),"deny"}if(!b())return"once";if("function"==typeof y){let e;try{e=y(s,a)}catch{e=null}if(e&&"deny"===e.verdict)return r&&r({delta:"",note:I(s)}),"deny";if(e&&"allow"===e.verdict)return"once"}if(D(t,s))return r&&r({delta:"",note:I(s)}),"deny";const l=await L(t,r,o.signal,{tool:s,args:a,diff:null});if("deny"===l)return R(t,s),"deny";if("session"!==l&&"once"!==l&&"always"!==l)return"deny";if("session"===l&&F(t,s,a),"always"===l&&"function"==typeof g)try{g(s,a)}catch{}return l},signal:o.signal,onDelta:o.onDelta,onSpawn:(e,t)=>{o.onDelta&&t&&o.onDelta({delta:"",note:claudePro.childLine(t)})}});let a=await n(t);if(a&&a.resumeStale){x.delete(e);try{A.del(e,s)}catch{}o.onDelta&&o.onDelta({delta:"",note:"aegis: the remembered Claude session no longer exists on this machine — continuing as a new conversation (earlier turns are not in its context)"}),a=await n(null)}if(e&&a&&a.sessionId&&!a.error){x.set(e,a.sessionId);try{A.set(e,a.sessionId,s)}catch{}}return a}throw new Error(`dispatch: unknown model class ${JSON.stringify(t)} — this build ships 'aegis', 'byok', 'local' and 'pro' only`)}async function K(o,r){const s=o&&o.class,a=o&&o.model,i=reasoningBudget("byok"===s?splitByokModel(a).model:a,o&&o.maxTokens,o&&o.effort),d=statedCapOf(o),u="aegis"===s&&Boolean(o&&o.autonomous),f=Boolean(o&&o.roundsAsk),y=o&&o.sessionId||randomUUID(),g=Number.isInteger(o&&o.depth)?o.depth:0,k=o&&o.rootSessionId||y,b=o&&o.rootOnDelta||r,w="function"==typeof r?e=>e&&r({reasoning:e}):void 0,E=new AbortController,S=p.get(y)||null;p.set(y,E);const _=E.signal,T=!(o&&!1===o.tools),x=T?m.toolsFor({includeSubagent:g<4}):[],A=o&&o.toolChoice||null,M=o&&o.system||h(j(o)),O=n?await n({payload:o,env:j(o),system:M}):null,N="string"==typeof O?O:O&&"string"==typeof O.system?O.system:M,F=Array.isArray(o&&o.messages)?o.messages.filter(Boolean).slice():[];let D=F.length,R=o&&o.prompt||"";const U=String(R||""),I=Array.isArray(o&&o.attachments)?o.attachments.filter(e=>e&&"object"==typeof e).slice(0,attachmentsModule.MAX_ATTACHMENTS):[];let L=I.length?attachmentsModule.buildContent(R,I):R,P=null;const $=j(o),K=((e,t)=>{if(null==l)return null;const o="function"==typeof l.policy?l.policy():l.policy;if(!o)return null;const r=require("./sandbox.js"),n=e&&e.cwd||process.cwd(),s=r.normalize(o,n);if("off"===s.mode)return null;let a=[];try{let e=null;try{e=require("node:os").homedir()}catch{e=null}a=r.autoGrants(n,{home:e,addDirs:(()=>{try{return B(n)}catch{return[]}})()})}catch{a=[]}if(a.length){const e=new Set;for(const t of s.fileSystem.entries)t&&t.path&&"path"===t.path.type&&t.path.path&&e.add(`${t.access}:${t.path.path}`);for(const t of a){const o=`${t.access}:${t.path.path}`;e.has(o)||(e.add(o),s.fileSystem.entries.push(t))}}return"local"===t&&"restricted"===s.network&&(s.network="open",s.networkExempt="local"),{policy:s,state:l.state||r.detect({appDir:l.appDir}),workspace:n,appDir:l.appDir,strict:!0===l.strict}})($,s),W=$.cwd,z={getShell:()=>P||(P=new ShellSession({cwd:$.cwd,sandbox:K})),signal:_,cwd:W,desktopdir:$.desktopdir,sandbox:K,repeat:repeatGuard.beginRepeatGuard({cwd:W}),verify:verifyGuard.beginVerifyGuard({cwd:W}),guard:beginTurnGuard(W)};try{const n="byok"===s?splitByokModel(a):null;let l=null;const p="byok"===s?t.get(byokNamespace(n.provider))||{}:"local"===s&&t.get("local")||{},h="byok"===s?t.rawKey(byokNamespace(n.provider)):null,E="byok"!==s?null:h||providerKeyFromEnv(n.provider);if(!("byok"!==s||n.provider&&n.model)){const e=new Error('byok: model must be "<provider>:<model>" (pick one from /models) — got '+JSON.stringify(a||""));throw e.status=400,e}if("byok"===s&&!E){const t="anthropic"===n.provider?claudePro.claudeProStatus({env:process.env}):null,o=providerKeyRecord(n.provider).rejected,r=nexusFallbackModel({provider:n.provider,providerKey:E,providerKeyRefused:o,aegisKey:E?"":e.apiKey});if(!r){const e=new Error(o?`${o}. That is why this turn has no ${n.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 ${n.provider} <key> to set one here.`:t&&t.loggedIn?`No Anthropic API key on this machine — an "anthropic:…" id is served by your own console key, which a Claude subscription is not. Use the subscription instead: /class pro (it spends your Claude Code ${t.subscription||"Pro"} plan through the claude CLI) — or add a real console key: /byok-key anthropic <key>.`:`No key for "${n.provider}" yet. Easiest fix: /class aegis (uses your AEGIS key, no setup) — or add this provider's own key: /byok-key ${n.provider} <key>.`);throw e.status=400,e}l={from:n.provider,model:r}}if("byok"===s&&!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"===s){const e=c.remoteRefusal(p.baseURL||c.DEFAULT_BASE);if(e)throw e}if("byok"===s&&"custom"===n.provider&&!(p.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 S=l?"aegis":s,M={cls:S,model:l?l.model:a,mode:o&&o.mode,maxTokens:i,statedMaxTokens:d,autonomous:u,sessionId:y,signal:_,onDelta:r,cfg:p,apiKey:E,toolChoice:A,pooledFrom:l?l.from:void 0,cwd:W,rootSessionId:k,sessionKey:o&&o.sessionKey||void 0,rootOnDelta:b,effort:o&&o.effort,workers:o&&o.workers,recallDeep:o&&!0===o.recallDeep,singlePass:o&&!0===o.singlePass,onReasoning:w,idleTimeoutMs:u?9e5:void 0,stream:!o||!1!==o.stream};let O=!1,P=!1;const $=u?"AEGIS_AUTONOMOUS_MAX_ROUNDS":"AEGIS_CHAT_MAX_ROUNDS",j=(()=>{const e=Number.parseInt(process.env[$]||"",10);return Number.isFinite(e)&&e>0?e:0})(),B=j||(u?40:24);let K=v.keyFor(o,F),V=v.take(K);if(!V&&!v.isStatedKey(o)){const e=v.adopt();e&&(V=e.entry,K=e.key)}if(V){const e=v.resumePreamble(V);0===F.length?Array.isArray(V.messages)&&V.messages.length&&F.push(...V.messages):Array.isArray(V.added)&&V.added.length&&F.push(...V.added),R?(R=`${e}\n\n${R}`,L=I.length?attachmentsModule.buildContent(R,I):R):(F.push({role:"user",content:e}),L=""),b&&b({delta:`\n\n[resuming work this session left unfinished at ${V.rounds} tool rounds`+(V.interruptions>1?` (cut off ${V.interruptions}×)`:"")+"…]\n"})}let H=j||B+(V?v.bonus(B):0),X=0;const J=B,Q=8;let Z=0;const ee={calls:0},te=["input_tokens","output_tokens","prompt_tokens","completion_tokens","total_tokens","cache_read_input_tokens","cache_creation_input_tokens","prompt_cache_hit_tokens","prompt_cache_miss_tokens","reasoning_tokens","thinking_tokens"],oe=e=>{const t=e&&e.usage;if(t&&"object"==typeof t){ee.calls+=1;for(const e of te)"number"==typeof t[e]&&Number.isFinite(t[e])&&(ee[e]=(ee[e]||0)+t[e]);if("number"!=typeof t.total_tokens){const e=(t.prompt_tokens??t.input_tokens??0)+(t.completion_tokens??t.output_tokens??0);e&&(ee.total_tokens=(ee.total_tokens||0)+e)}}},re=e=>{if(!e||"object"!=typeof e)return e;const t=l?{...e,pooled_from:l.from,pooled_model:l.model,pooled_notice:requireSharedByokCatalog().nexusFallbackNotice({pooled_from:l.from,pooled_model:l.model})}:e;return ee.calls?{...t,usage:{...ee}}:t},ne=()=>{if(""===L)return;const e=F[F.length-1],t=e&&"user"===e.role?flattenContent(e.content):null;e&&"user"===e.role&&t===flattenContent(L)||F.push({role:"user",content:L}),R="",L=""};D=F.length;const se=m&&m.MUTATING_TOOLS||new Set;let ae=0,ie=0,le=!1,ce=!1;for(;;){if(X>=H){if(f&&Z<Q&&!_.aborted&&await C(k,b,_,{spent:H,extensions:Z+1,max:Q,size:J})){Z+=1;const e=H;H+=J,F.push({role:"user",content:`You have used all ${e} tool rounds allowed for this turn; ${J} more have been granted (do not restart). Continue the task from exactly where you stopped — do not re-plan, do not repeat work already done, and finish with an answer.`});continue}const e=f?"":`, or raise ${$} for a longer single turn`,t=`[stopped at ${H} tool rounds`+(ee.total_tokens?`, ${ee.total_tokens.toLocaleString()} tokens`:"")+". This session holds the work: your next message here resumes it automatically"+` (with a continuation preamble)${e}.]`,o=v.record(K,{rounds:X,tokens:ee.total_tokens||0,note:t,chain:V?V.interruptions:0,messages:F,added:F.slice(D)});return b&&b({delta:`\n\n${t}`}),re({model:M.model,choices:[{message:{content:t},finish_reason:"length"}],stoppedOnRounds:!0,heldForSession:!0,heldRounds:o.rounds,sessionInterruptions:o.interruptions,resumedFrom:K})}X+=1;const e={...M,system:N,messages:F,prompt:L,tools:x,recallDeep:M.recallDeep&&1===X};let t;if(t=await G(S,e),oe(t),_.aborted)return re(t);if(!O&&!assistantText(t)&&(isTruncated(t)||reasonedButSilent(t))){O=!0;const o=reasonedButSilent(t);if(t=await G(S,{...e,singlePass:!0,recallDeep:!1,effort:o?"high":e.effort,maxTokens:retryBudgetFor(e,o),statedMaxTokens:e.statedMaxTokens?doubledBudget(e.statedMaxTokens):void 0}),oe(t),_.aborted)return re(t)}const n=x.length?extractToolCalls(t):[];if(!n.length){if(assistantText(t)||P||!T){if(!le&&T&&wantsMutation(U,ie>0,ae)){le=!0,ne(),F.push({role:"assistant",content:assistantText(t)}),F.push({role:"user",content:UNMUTATED_TURN_NUDGE}),b&&b({delta:""});continue}if(z.verify&&!ce){const e=verifyGuard.shouldNudge(z.verify);if(e.nudge){ce=!0,ne(),F.push({role:"assistant",content:assistantText(t)}),F.push({role:"user",content:e.text}),b&&b({delta:""});continue}}return re(t)}P=!0,ne(),F.push({role:"user",content:reasonedButSilent(t)?THOUGHT_ONLY_NUDGE:EMPTY_TURN_NUDGE});const o={...e,singlePass:!0,recallDeep:!1,messages:F,prompt:"",tools:[]};t=await G(S,o);let r=o.maxTokens,n=o.effort;if(oe(t),_.aborted)return re(t);if(!assistantText(t)&&(isTruncated(t)||reasonedButSilent(t))){const e=reasonedButSilent(t);if(r=retryBudgetFor(o,e),n=e?"high":o.effort,t=await G(S,{...o,effort:n,maxTokens:r,statedMaxTokens:o.statedMaxTokens?doubledBudget(o.statedMaxTokens):void 0}),oe(t),_.aborted)return re(t)}const i=(()=>{const e=Number(r)||0;if(!e)return r;const t={maxTokens:r};return o.statedMaxTokens&&(t.statedMaxTokens=o.statedMaxTokens),Math.max(e,retryBudgetFor(t,!0))})();let l=0;for(;!assistantText(t)&&l<2&&!_.aborted;){const e=reasonedButSilent(t);if(l+=1,F.push({role:"user",content:e?1===l?THOUGHT_ONLY_NUDGE:FINAL_ANSWER_NUDGE:EMPTY_TURN_NUDGE}),e&&(n="high"),r=i,t=await G(S,{...o,messages:F,effort:n,maxTokens:r,statedMaxTokens:o.statedMaxTokens?doubledBudget(o.statedMaxTokens):void 0}),oe(t),_.aborted)return re(t)}if(!assistantText(t))throw emptyTurnError({cls:s,model:a,effort:n,recoveryRounds:l,finishReason:finishReasonOf(t),reasoningChars:reasoningTextOf(t).length,reasoningTokens:reasoningTokensOf(t)});return re(t)}ne(),F.push({role:"assistant",content:assistantText(t),tool_calls:n.map(e=>({id:e.id,type:"function",function:{name:e.name,arguments:JSON.stringify(e.args)}}))});const i=new WeakMap,l=e=>{if("exec"!==e.name)return null;if(i.has(e))return i.get(e);const t=planExec(e.args&&e.args.command,{baseCwd:W});return i.set(e,t),t},c=e=>{if(!se.has(e.name))return!0;const t=l(e);return Boolean(t&&t.oneShot)},u=[];for(const e of n){const t=u[u.length-1];c(e)&&t&&t.parallel?t.calls.push(e):u.push({parallel:c(e),calls:[e]})}const p=async e=>{r&&r({delta:"",tool:{name:e.name,args:e.args,id:e.id,cwd:W,phase:"run"}});const t=l(e),n=t&&t.oneShot?{...z,oneShotExec:!0,cwd:t.cwd||z.cwd}:z,i=e.name===m.SUBAGENT_TOOL?await Y(e.args,{cls:s,model:a,statedMaxTokens:d,effort:o&&o.effort,mode:o&&o.mode,parentSignal:_,depth:g,rootSessionId:k,rootOnDelta:b}):await q(e,{toolCtx:n,rootSessionId:k,rootOnDelta:b,signal:_});return i&&i.usage&&oe({usage:i.usage}),r&&r({delta:"",tool:{name:e.name,args:e.args,ok:i.ok,id:e.id,cwd:W,phase:"done"}}),i};for(const e of u){const t=e.parallel&&e.calls.length>1?await Promise.all(e.calls.map(e=>p(e))):[await p(e.calls[0])];e.calls.forEach((e,o)=>{const r=t[o];se.has(e.name)&&(ae+=1,r&&r.ok&&(ie+=1)),F.push({role:"tool",tool_call_id:e.id,name:e.name,content:m.toolResultText(r)})})}}}catch(e){throw _.aborted&&e&&"object"==typeof e&&(e.aegisCancelled=!0),e}finally{P&&P.dispose(),p.get(y)===E&&(S&&!S.signal.aborted?p.set(y,S):p.delete(y))}}async function Y({description:e,subagent_type:t,prompt:o}={},{cls:r,model:n,statedMaxTokens:s,effort:a,mode:i,parentSignal:l,depth:c,rootSessionId:d,rootOnDelta:u}={}){const f=String(o||e||"").trim();if(!f)return{ok:!1,error:"task requires a prompt"};const p=t&&"general"!==t?agentRoleLabel(t):"general",m=agentSystemPrompt(t),h=randomUUID();let y;if(l){if(l.aborted)return{ok:!1,error:"aborted"};y=()=>W(h),l.addEventListener("abort",y,{once:!0})}try{const e=await K({class:r,model:n,mode:i,system:m,prompt:f,sessionId:h,depth:(c||0)+1,rootSessionId:d,rootOnDelta:u,statedMaxTokens:s,effort:a},()=>{}),t=assistantText(e),o=e&&e.usage?{usage:e.usage}:{};return t?{ok:!0,output:t,...o}:{ok:!1,error:`subagent (${p}) produced no output`,...o}}catch(e){return{ok:!1,error:`subagent (${p}) failed: ${e&&e.message?e.message:e}`}}finally{l&&y&&l.removeEventListener("abort",y)}}function W(e){const t=p.get(e);return t&&t.abort(),{ok:Boolean(t)}}function z(e){const o=String(null==e?"":e).trim().toLowerCase();if(!o)return"";try{if(t&&"function"==typeof t.rawKey){const e=t.rawKey(byokNamespace(o));if("string"==typeof e&&e.trim())return e.trim()}}catch{}return providerKeyFromEnv(o)}async function V(t){let o=[];try{const t=await e.byokProviders();o=withUserModels(withCatalog(withByokAdditions(t&&t.providers||[])))}catch(e){return{ok:!1,providers:[],missing:0,stale:0,skipped:[],failed:[],error:e&&e.message||String(e)}}const r={};for(const e of modelSync.askableProviders(o,t)){const t=z(e);t&&(r[e]=t)}return modelSync.plan(o,{keys:r,fetchImpl:d,only:t})}const H=createModelAutoSync({getPref:()=>{try{return t&&"function"==typeof t.getSharedPref?t.getSharedPref("modelAutoSync"):null}catch{return null}},plan:e=>V(e),apply:(e,t)=>modelSync.apply(e,{only:t})});return{CLASSES:CLASSES,listClasses:async function(){return CLASSES.map(o=>{if("aegis"===o.class)return{...o,configured:Boolean(e.apiKey)};if("byok"===o.class){const e=(t.list()||[]).some(e=>!(!e||"string"!=typeof e.provider||!e.provider.startsWith("byok:"))&&(!!e.configured||Boolean(providerKeyFromEnv(e.provider.slice(5)))));return{...o,configured:e}}if("local"===o.class)return{...o,configured:!0};if("pro"===o.class){const e=claudePro.claudeProStatus({env:process.env}),t=claudePro.seamAvailable();return{...o,configured:e.loggedIn,status:e,seam:t}}return{...o,configured:!1}})},listModels:async function(o){if("aegis"===o){if(!e.apiKey)return{class:o,models:[],needsKey:!0};const t=await e.listModels();return{class:o,models:offerableCatalog(normalizeCatalog(t&&t.models))}}if("byok"===o){let r=[],n=null,s=!1,a=null;try{const t=await e.byokProviders();r=withUserModels(withCatalog(withByokAdditions(t&&t.providers||[]))),n=t&&t.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 o=t.get(byokNamespace(e.id))||{},r=providerKeyRecord(e.id),n=r.key||"",s=Array.isArray(e.models)?e.models:[];for(const t of s){const s="string"==typeof t?t:t&&t.id;s&&i.push({id:`${e.id}:${s}`,label:`${e.label||e.id} — ${s}`,provider:e.id,configured:Boolean(o.configured||n),keyRejected:r.rejected||null})}}return{class:o,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"===o){const e=(t.get("local")||{}).baseURL||c.DEFAULT_BASE,r=await c.probe(e);if(!r.running)return{class:o,models:[],baseURL:r.baseURL,needsDaemon:!0};let n=[],s=!0;try{n=await c.listTags(e)}catch{s=!1}return{class:o,models:n,baseURL:r.baseURL,listed:s}}if("pro"===o){const e=claudePro.claudeProStatus({env:process.env});return{class:o,models:claudePro.PRO_MODELS.map(t=>({id:t.id,label:t.label,note:t.note,configured:e.loggedIn})),needsProviderKey:!1,needsAegisKey:!1,subscription:e.subscription,loggedIn:e.loggedIn,credentialFile:e.file,shadowed:e.shadowed||null,seam:claudePro.seamAvailable()}}throw new Error(`listModels: unknown model class ${JSON.stringify(o)} — this build ships 'aegis', 'byok', 'local' and 'pro' only`)},chat:K,cancel:W,respondApproval:function(e,t){const o=M.get(e);return o?(M.delete(e),o.resolve("session"===t||"once"===t||"always"===t?t:"deny"),{ok:!0}):{ok:!1}},respondRoundsAsk:function(e,t){const o=O.get(e);return o?(O.delete(e),o.resolve(!0===t||"continue"===t),{ok:!0}):{ok:!1}},clearSessionApprovals:function(e){S.delete(e),_.delete(e),T.delete(e),x.delete(e);try{A.del(e,s)}catch{}return{ok:!0}},listUndoable:function(e){return(T.get(e)||[]).map(e=>({id:e.id,tool:e.tool,path:e.path,at:e.at})).reverse()},undoMutation:function(e,t){const o=T.get(e)||[],r=t?o.findIndex(e=>e.id===t):o.length-1;if(-1===r)return{ok:!1,error:t?`no undo record "${t}" for this conversation`:"nothing to undo in this conversation"};const n=o[r],s=U(n.path);if(!s||s.existed!==n.after.existed||s.content!==n.after.content)return{ok:!1,error:`${n.path} has changed since ${n.tool} ran — undo refused rather than overwriting work this session did not do. Resolve it by hand, or undo a different entry.`};try{n.before.existed?fs.writeFileSync(n.path,n.before.content,"utf8"):fs.unlinkSync(n.path)}catch(e){return{ok:!1,error:`undo failed: ${e&&e.message||e}`}}return o.splice(r,1),{ok:!0,path:n.path,restored:n.before.existed?"content":"deleted"}},settings:t,unloadLocalModels:function(){return c.unloadAll()},userModels:()=>loadUserModels(),addUserModel:(e,t)=>addUserModel(e,t),removeUserModel:(e,t)=>removeUserModel(e,t),discoverModels:async e=>{const t=String(null==e?"":e).trim().toLowerCase(),o=z(t),r=await discoverVendorModels(t,{key:o,fetchImpl:d});if(!r||!r.ok)return r;const n=[];try{const e=loadUserModels().map;for(const o of Array.isArray(e[t])?e[t]:[])n.push(o)}catch{}return{...r,declared:n,endpoint:(vendorEndpointFor(t)||{}).url||""}},modelSyncPlan:async e=>V(e),modelSyncApply:(e,t)=>modelSync.apply(e,{only:t}),modelAutoSync:H,modelAutoSyncRun:e=>H.runIfDue(e),modelAutoSyncStatus:()=>H.status(),addUserModels:(e,t)=>{const o=Array.isArray(t)?t:[],r={provider:e,added:0,already:[],failed:[],capped:0,file:""};for(const t of o)try{const o=addUserModel(e,t);r.file=o.file||r.file,o.added?r.added+=1:r.already.push(o.model)}catch(e){const n=e&&e.message||String(e);if(/the cap/.test(n)){r.capped=o.length-r.added-r.already.length-r.failed.length;break}r.failed.push({id:String(t),reason:n})}return r},canDiscoverModels:e=>canDiscoverVendorModels(e),discoverableProviders:()=>discoverableProviders()}}module.exports={CLASSES:CLASSES,createLocalEngine:createLocalEngine,extractToolCalls:extractToolCalls,parseArgs:parseArgs,reasoningBudget:reasoningBudget,nativeEffort:nativeEffort,hostEnv:hostEnv};
|
|
3
|
+
"use strict";const{randomUUID:randomUUID}=require("node:crypto"),os=require("node:os"),fs=require("node:fs"),toolsModule=require("./tools.js"),attachmentsModule=require("./attachments.js"),{flattenContent:flattenContent}=attachmentsModule,promptModule=require("./prompt.js"),localTransport=require("./local.js"),{ShellSession:ShellSession}=require("./shell.js"),{planExec:planExec}=require("./exec-plan.js"),claudePro=require("./claude-pro.js"),{agentSystemPrompt:agentSystemPrompt,agentRoleLabel:agentRoleLabel}=require("./agents.js"),{beginTurnGuard:beginTurnGuard,recordWrite:recordWrite,blocksDestructive:blocksDestructive}=require("./turn-guard.js"),repeatGuard=require("./repeat-guard.js"),verifyGuard=require("./verify-stop.js"),{acquireWorktreeLock:acquireWorktreeLock,releaseWorktreeLock:releaseWorktreeLock}=require("./worktree-lock.js"),covenant=require("./covenant.js");let envFile=null;try{envFile=require("../../../client/env-file.js")}catch{try{envFile=require("../../vendor/env-file.js")}catch{envFile=null}}let platformLib=null;try{platformLib=require("../../../client/platform.js")}catch{try{platformLib=require("../../vendor/platform.js")}catch{platformLib=null}}let credentialsLib=null;try{credentialsLib=require("../../../client/credentials.js")}catch{try{credentialsLib=require("../../vendor/credentials.js")}catch{credentialsLib=null}}const PRO_TOOL_MAP=Object.freeze({Write:"writeFile",Edit:"editFile",MultiEdit:"editFile",NotebookEdit:"editFile",Bash:"exec",BashOutput:"exec"}),PRO_PLAN_MODE_SAFE=Object.freeze(new Set(["Read","Glob","Grep"]));function proAskArgs(e,t){const o=e&&"object"==typeof e?e:{};return"exec"===t?"string"==typeof o.command?{command:o.command}:{}:"writeFile"===t?"string"==typeof o.file_path?{file_path:o.file_path,content:o.content}:{}:"editFile"===t?Array.isArray(o.edits)?{file_path:o.file_path,edits:o.edits}:"string"==typeof o.file_path?{file_path:o.file_path,old_string:o.old_string,new_string:o.new_string,replace_all:!0===o.replace_all}:{}:o}function normalizeToolArgs(e,t,o,r){const n=e&&"function"==typeof e.normalizeArgs&&e.normalizeArgs||"function"==typeof toolsModule.normalizeArgs&&toolsModule.normalizeArgs||null;return n?n(t,o,r):{ok:!0,args:o&&"object"==typeof o?o:{},error:null}}function detectVcs(e){if(!e)return null;try{const t=require("node:fs"),o=require("node:path");let r=o.resolve(String(e));for(let e=0;e<8;e+=1){if(t.existsSync(o.join(r,".git")))return"git";const e=o.dirname(r);if(e===r)break;r=e}return""}catch{return null}}function hostEnv(e={},t={},o=null){const r=e||{},n=t||{},s=(e,t)=>null!=n[e]?n[e]:t;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",o&&o.model),class:s("class",r.class||o&&o.class)}}function requireSharedBrain(){const e=[()=>require("../../../client/brain-catalog.js"),()=>require("../../vendor/brain-catalog.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}function requireSharedByokCatalog(){const e=[()=>require("../../../client/byok-catalog.js"),()=>require("../../vendor/byok-catalog.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}function requireSharedUserModels(){const e=[()=>require("../../../client/user-models.js"),()=>require("../../vendor/user-models.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}function requireSharedCatalogClient(){const e=[()=>require("../../../client/catalog-client.js"),()=>require("../../vendor/catalog-client.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}function requireSharedModelDiscovery(){const e=[()=>require("../../../client/model-discovery.js"),()=>require("../../vendor/model-discovery.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}function requireSharedModelSync(){const e=[()=>require("../../../client/model-sync.js"),()=>require("../../vendor/model-sync.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}function requireSharedModelAutoSync(){const e=[()=>require("../../../client/model-autosync.js"),()=>require("../../vendor/model-autosync.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}const WORKTREE_LOCK_WAIT_MS=1500,MAX_SUBAGENT_DEPTH=4,CLASSES=[{class:"aegis",label:"Aegis Cloud",kind:"cloud"},{class:"byok",label:"Bring your own key",kind:"cloud"},{class:"local",label:"Local model",kind:"local"},{class:"pro",label:"Claude Code Pro",kind:"subscription"}],BYOK_NAMESPACE_PREFIX="byok:";function byokNamespace(e){return`byok:${e}`}function splitByokModel(e){const t="string"==typeof e?e:"",o=t.indexOf(":");return o<0?{provider:"",model:t}:{provider:t.slice(0,o),model:t.slice(o+1)}}function providerKeyRecord(e){const t={key:"",env:"",rejected:null};if(!envFile||"function"!=typeof envFile.providerKeyFromEnv)return t;try{const o=envFile.providerKeyFromEnv(e)||t;return{key:"string"==typeof o.key?o.key:"",env:"string"==typeof o.env?o.env:"",rejected:"string"==typeof o.rejected&&o.rejected?o.rejected:null}}catch{return t}}function providerKeyFromEnv(e){if(!envFile||"function"!=typeof envFile.providerKeyFromEnv)return"";try{return envFile.providerKeyFromEnv(e).key||""}catch{return""}}const DEEPSEEK_REASONING_MODEL_RE=/^deepseek-(v4(\.\d+)?-(flash|pro)|flash|pro|reasoner)$/,EFFORT_TOKEN_BUDGET={low:8192,medium:16384,high:32768,max:32768},DEEPSEEK_EFFORT={low:"low",medium:"high",high:"high"},DEEPSEEK_EFFORT_EXTRA={max:"max"},EFFORT_IDENTITY={low:"low",medium:"medium",high:"high"},EFFORT_INERT_RE=/non-reasoning/i,EFFORT_DIALECTS=[{provider:"deepseek",re:DEEPSEEK_REASONING_MODEL_RE,field:"effort",map:DEEPSEEK_EFFORT,extra:DEEPSEEK_EFFORT_EXTRA},{provider:"openai",re:/^(gpt-5|o[0-9])/i,field:"reasoning_effort",map:EFFORT_IDENTITY},{provider:"groq",re:/^(openai\/gpt-oss|qwen\/qwen3)/i,field:"reasoning_effort",map:EFFORT_IDENTITY},{provider:"xai",re:/^grok-(4\.[5-9]|[5-9])/,field:"reasoning_effort",map:EFFORT_IDENTITY},{provider:"google",re:/^gemini-(2\.5|3|[4-9])/,field:"reasoning_effort",map:{...EFFORT_IDENTITY,medium:"high"}}],AUTONOMOUS_IDLE_TIMEOUT_MS=9e5;function reasoningBudget(e,t,o){const r=Number(t);return Number.isFinite(r)&&r>0?r:DEEPSEEK_REASONING_MODEL_RE.test(String(e||""))?EFFORT_TOKEN_BUDGET["low"===o||"medium"===o||"max"===o?o:"high"]:void 0}function nativeEffort(e,t,o){const r=String(t||"");if(EFFORT_INERT_RE.test(r))return;if(null===o)return;const n="low"===o||"medium"===o?o:"max"===o?"max":"high";for(const t of EFFORT_DIALECTS)if(t.provider===e&&t.re.test(r)){const e=Object.prototype.hasOwnProperty.call(t.map,n)?t.map[n]:t.extra&&Object.prototype.hasOwnProperty.call(t.extra,n)?t.extra[n]:void 0;if(void 0===e)return;return{field:t.field,level:e}}}function normalizeCatalog(e){return Array.isArray(e)?e.map(e=>"string"==typeof e?{id:e}:e).filter(e=>e&&e.id):[]}const{offerableCatalog:offerableCatalog}=requireSharedBrain(),{withByokAdditions:withByokAdditions,canonicalModelId:canonicalModelId,nexusFallbackModel:nexusFallbackModel}=requireSharedByokCatalog(),{withUserModels:withUserModels,unmatchedUserProviders:unmatchedUserProviders,load:loadUserModels,addUserModel:addUserModel,removeUserModel:removeUserModel}=requireSharedUserModels(),{withCatalog:withCatalog}=requireSharedCatalogClient(),{discoverModels:discoverVendorModels,canDiscover:canDiscoverVendorModels,endpointFor:vendorEndpointFor,discoverableProviders:discoverableProviders}=requireSharedModelDiscovery(),modelSync=requireSharedModelSync(),{createModelAutoSync:createModelAutoSync}=requireSharedModelAutoSync();function parseArgs(e){if(null==e)return{};if("object"==typeof e)return e;try{const t=JSON.parse(String(e));return t&&"object"==typeof t?t:{}}catch{return{}}}function extractToolCalls(e){if(!e)return[];if(Array.isArray(e.toolCalls)&&e.toolCalls.length)return e.toolCalls.map(e=>({id:e.id||"",name:e.name||"",args:parseArgs(e.args)})).filter(e=>e.name);const t=e.choices&&e.choices[0]&&e.choices[0].message,o=t&&t.tool_calls||[];return Array.isArray(o)?o.map(e=>{const t=e&&e.function||{};return{id:e&&e.id||"",name:t.name||e&&e.name||"",args:parseArgs(t.arguments)}}).filter(e=>e.name):[]}function proTurnPrompt(e){const t=Array.isArray(e.prompt)?flattenContent(e.prompt):e.prompt;if("string"==typeof t&&t.trim())return t;const o=Array.isArray(e.messages)?e.messages:[];for(let e=o.length-1;e>=0;e-=1){const t=o[e];if(!t||"user"!==t.role)continue;const r=flattenContent(t.content);if(r.trim())return r}return t}function assistantText(e){const t=e&&e.choices&&e.choices[0]&&e.choices[0].message;return t&&"string"==typeof t.content&&t.content||""}function finishReasonOf(e){const t=e&&e.choices&&e.choices[0];return t&&t.finish_reason||e&&e.stop_reason||""}function isTruncated(e){const t=finishReasonOf(e);return"length"===t||"max_tokens"===t}function reasoningTextOf(e){if(!e)return"";const t=e.choices&&e.choices[0],o=t&&t.message||{};if(Array.isArray(o.content)){const e=o.content.filter(e=>e&&("thinking"===e.type||"reasoning"===e.type)).map(e=>e.thinking||e.text||"").join("");if(e)return e}const r=o.content&&"object"==typeof o.content?o.content.reasoning_content:"",n=[o.reasoning_content,o.reasoning,t&&t.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 t=e.choices&&e.choices[0],o=t&&t.message||{},r=e.usage||{},n=r.completion_tokens_details||r.output_tokens_details||{},s=[o.thinking_tokens,o.reasoning_tokens,t&&t.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,t){const o=doubledBudget(e.maxTokens);return t&&ladderRung(e.maxTokens)?Math.max(o,32768):o}function ladderRung(e){const t=Number(e);return Number.isFinite(t)&&Object.values(EFFORT_TOKEN_BUDGET).includes(t)}function doubledBudget(e){const t=Number(e)||0;return t>0?2*t:8192}function statedCapOf(e){const t=e=>{const t=Number(e);return Number.isFinite(t)&&t>0?t:void 0};return e&&Object.prototype.hasOwnProperty.call(e,"statedMaxTokens")?t(e.statedMaxTokens):t(e&&e.maxTokens)}const EMPTY_TURN_NUDGE="Your previous reply came back empty — it contained no answer and no tool call. Write your answer now, using only the information already gathered above. No tools are available in this reply, so do not call any: respond in plain prose or markdown.",THOUGHT_ONLY_NUDGE="Your previous round was spent entirely on hidden reasoning and produced no visible reply. Answer the user directly and briefly now. Do not reason, explain, or think first — write only the answer, no tools.",FINAL_ANSWER_NUDGE="Write your answer now, in plain prose, using only what is already in this conversation. If your information is incomplete, say what you have and what is missing — an incomplete answer is the expected outcome here and is better than none. No tools, no preface.",RECOVERY_ROUNDS=2,UNMUTATED_TURN_NUDGE="You ended the turn without changing any file, but this request asked for a change. The tools are still available in this reply: make the edit now with editFile or writeFile. If you already know what to change, change it — describing the fix is not the fix. If you genuinely cannot, say precisely what blocks you.",MUTATION_INTENT_RE=new RegExp("\\b(?:fix|implement|add|create|write|refactor|rename|remove|delete|replace|update|patch|migrate|convert|make\\s+(?:it|them|this|that|the|sure)|change|correct|resolve|repair|address|apply|introduce|support|wire\\s+up)\\b","i");function wantsMutation(e,t,o){if(t)return!1;if(!(o>0))return!1;const r=String(e||"");return!!r.trim()&&!/\?\s*$/.test(r.trim())&&MUTATION_INTENT_RE.test(r)}function emptyTurnError({cls:e,model:t,finishReason:o,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}/${t} was asked to summarise its results`+(i?`, and ${i} extra recovery call${1===i?"":"s"} with a larger budget and a changed ask came back empty too`:"")+` (stop reason: ${o||"none"}`+(s?`, effort: ${s}`:"")+(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:t,tools:o,promptBuilder:r,recallProvider:n,env:s,getConfirmMode:a,getPermissionMode:i,sandbox:l,localTransport:c=localTransport,fetchImpl:d,gitScope:u,permissionRules:f}){const p=new Map,m=o||toolsModule,h=r&&r.buildSystemPrompt||promptModule.buildSystemPrompt,y=f&&"function"==typeof f.rulesVerdict?f.rulesVerdict:null,g=f&&"function"==typeof f.alwaysAllow?f.alwaysAllow:null,k=f&&"function"==typeof f.subjectFor?f.subjectFor:null,v=require("./session-rounds.js"),b=()=>{if("function"==typeof a)return!1!==a();if(t&&"function"==typeof t.getConfirmMode){const e=t.getConfirmMode();return void 0===e||Boolean(e)}return!0},w=()=>"function"==typeof i?"plan"===i():!(!t||"function"!=typeof t.getPermissionMode)&&"plan"===t.getPermissionMode();function S(e,t){return`${e} was not executed — this session is in plan mode (read-only). Plan mode may read files, search, run read-only shell commands and deploy subagents to research, but may not create, edit or delete files, run a mutating command, or install packages`+(t?` (this command: ${t})`:"")+". Do NOT retry it or attempt the same effect by another route. Finish your research and present a plan in plain text; the user exits plan mode (`/permissions mode off`) before any edit can run."}const E=new Map,_=new Map,T=new Map,x=new Map,A=require("./pro-sessions.js"),M=new Map,N=new Map;function O(e,t){if("function"!=typeof k)return e;let o="";try{o=String(k(e,t||{})||"")}catch{o=""}return`${e}\0${o}`}function F(e,t,o){E.has(e)||E.set(e,new Set),E.get(e).add(O(t,o))}function D(e,t){const o=_.get(e);return Boolean(o&&o.has(t))}function R(e,t){_.has(e)||_.set(e,new Set),_.get(e).add(t)}function U(e){if(!e)return null;try{return{existed:!0,content:fs.readFileSync(e,"utf8")}}catch(e){return e&&"ENOENT"===e.code?{existed:!1,content:null}:null}}function I(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 L(e,t,o,r){return new Promise(n=>{if(o&&o.aborted)return void n("cancel");const s=randomUUID();let a=!1;const i=()=>l("cancel"),l=e=>{a||(a=!0,M.delete(s),o&&o.removeEventListener("abort",i),n(e))};o&&o.addEventListener("abort",i,{once:!0}),M.set(s,{resolve:l}),"function"==typeof t?t({delta:"",approval:{id:s,sessionId:e,tool:r.tool,args:r.args,diff:r.diff||null,canPersist:"function"==typeof g}}):l("cancel")})}function P(e,t,o,r){return new Promise(n=>{if(o&&o.aborted)return void n(!1);const s=randomUUID();let a=!1;const i=()=>l(!1),l=e=>{a||(a=!0,N.delete(s),o&&o.removeEventListener("abort",i),n(e))};o&&o.addEventListener("abort",i,{once:!0}),N.set(s,{resolve:l}),"function"==typeof t?t({delta:"",rounds:{id:s,sessionId:e,spent:r.spent,extensions:r.extensions,max:r.max,size:r.size}}):l(!1)})}async function C(e,t,o,r,n){const s=normalizeToolArgs(m,e,t,o||{});if(!s.ok)return{ok:!1,error:s.error};t=s.args;const a=o&&o.guard;if(a&&"exec"===e){const e=blocksDestructive(a,t&&t.command);if(!e.ok)return{ok:!1,error:e.reason}}const i=o&&o.repeat,l=i?repeatGuard.check(i,e,t):null;if(l&&"refuse"===l.action)return{ok:!1,error:l.error};const c=covenant.preActionAssert({tool:e,args:t||{}});if(!c.allowed){const o=covenant.bindRefusal({tool:e,args:t||{}},c);return{ok:!1,error:`refused by the ÆGIS covenant — ${c.clause} (${c.label}): ${c.reason}`,covenant:o}}const d="writeFile"===e||"editFile"===e,u=d?U(t&&t.file_path):null,f=await m.executeTool(e,t,o);a&&d&&f&&!1!==f.ok&&recordWrite(a,t&&t.file_path),i&&d&&f&&!1!==f.ok&&repeatGuard.recordWrite(i,t&&t.file_path);const p=o&&o.verify;if(p&&(verifyGuard.EXEC_TOOLS.has(e)&&f&&!1!==f.ok?verifyGuard.recordExec(p):d&&f&&!1!==f.ok&&verifyGuard.recordMutation(p,t&&t.file_path)),d&&u&&f&&!1!==f.ok){const o=U(t&&t.file_path);o&&function(e,t){if(!e)return;T.has(e)||T.set(e,[]);const o=T.get(e);o.push(t),o.length>200&&o.shift()}(r,{id:n||randomUUID(),tool:e,path:t&&t.file_path,before:u,after:o,at:Date.now()})}return l&&l.note?$(f,l.note):f}function $(e,t){if(!e||"object"!=typeof e)return{ok:!0,content:`${t}\n${null==e?"":e}`};if(!1===e.ok||!0===e.isError){const o=e.error||e.content||"";return{...e,error:`${t}\n${o}`,content:`${t}\n${o}`}}const o=null!=e.content?e.content:null!=e.output?e.output:"";return{...e,content:`${t}\n${o}`}}async function q(e,{toolCtx:t,rootSessionId:o,rootOnDelta:r,signal:n}){const{name:s}=e,a=normalizeToolArgs(m,s,e.args,t||{});if(!a.ok)return{ok:!1,error:a.error};const i=a.args;if(!m.MUTATING_TOOLS.has(s))return C(s,i,t,o,e.id);if(w()){if("exec"===s){const r=planExec(i&&i.command,{baseCwd:t&&t.cwd||void 0});return r.oneShot?C(s,i,t,o,e.id):{ok:!1,error:S(s,r.reason)}}return{ok:!1,error:S(s)}}if(!b())return C(s,i,t,o,e.id);if(function(e,t,o){const r=E.get(e);return Boolean(r&&r.has(O(t,o)))}(o,s,i))return C(s,i,t,o,e.id);if("function"==typeof y){let r;try{r=y(s,i)}catch(e){r={verdict:null,source:"error",error:e&&e.message||String(e)}}if(r&&"deny"===r.verdict)return R(o,s),{ok:!1,error:I(s),permissionRule:r.rule||null};if(r&&"allow"===r.verdict)return C(s,i,t,o,e.id)}if(D(o,s))return{ok:!1,error:I(s)};let l=null;if(("writeFile"===s||"editFile"===s)&&(l=m.previewMutation(s,i,t||{}),!l.ok))return{ok:!1,error:l.error};const c=await L(o,r,n,{tool:s,args:i,diff:l&&l.diff});if("deny"===c)return R(o,s),{ok:!1,error:I(s)};if("session"!==c&&"once"!==c&&"always"!==c)return{ok:!1,error:`${s} was not executed — the request was cancelled.`};let d=null;if("always"===c){let e=null;if("function"==typeof g)try{e=g(s,i)}catch(t){e={ok:!1,reason:t&&t.message||String(t)}}else e={ok:!1,reason:"no durable store is wired on this host"};d=e&&e.ok?`[permission_rule] stored ${e.rule} — this command will not ask again`:`[permission_rule] nothing was stored — ${e&&e.reason||"unknown reason"}; this call was allowed once only`}if("session"===c&&F(o,s,i),l){const e=m.applyChecked(s,i,l,t||{});return e&&!1!==e.ok&&t&&t.guard&&recordWrite(t.guard,i&&i.file_path),d?$(e,d):e}const u=await C(s,i,t,o,e.id);return d?$(u,d):u}function j(e){return hostEnv(s||{},e&&e.env||{},e)}function B(e){const t=[],o=e=>String(e||"").replace(/[\\/]+$/,""),r=o(e),n=e=>{const n=o(e);n&&n!==r&&!t.includes(n)&&t.push(n)};let s=u;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 t}async function G(t,o){if("aegis"===t){const t=!o.singlePass&&(!!o.autonomous||void 0);return e.chatCompletion({prompt:o.prompt,system:o.system,messages:o.messages,model:o.model,mode:o.mode,maxTokens:o.statedMaxTokens,stream:!1!==o.stream,includeUsage:!0,onStream:o.onDelta,onReasoning:o.onReasoning,idleTimeoutMs:o.idleTimeoutMs,signal:o.signal,extra:{aegis_recall:!0,...o.recallDeep?{aegis_recall_deep:!0}:{},session:o.sessionId,...void 0===t?{}:{brain:t},...!1===t?{mode:"brain"}:{},...o.effort?{effort:o.effort}:{},...!0===t&&o.workers?{workers:o.workers}:{},...o.tools.length?{tools:o.tools}:{},...o.toolChoice?{tool_choice:o.toolChoice}:{}},agentKey:o.tools.length&&(process.env.AEGIS_AGENT_KEY||"").trim()||void 0})}if("byok"===t){const{provider:t,model:r}=splitByokModel(o.model),n=canonicalModelId(t,r),s=nativeEffort(t,n,o.effort);try{return await e.byokChatCompletion({provider:t,model:n,providerKey:o.apiKey,baseURL:o.cfg&&o.cfg.baseURL,prompt:o.prompt,system:o.system,messages:o.messages,maxTokens:o.maxTokens,tools:o.tools,toolChoice:o.toolChoice,effort:s&&"effort"===s.field?s.level:void 0,reasoningEffort:s&&"reasoning_effort"===s.field?s.level:void 0,stream:!0,onStream:o.onDelta,signal:o.signal})}catch(e){if(e&&402===e.status){const e=new Error("byok: this account has no AEGIS balance left, and the BYOK handling fee is billed there — your provider key is still valid, this is not a key problem. Top up the account, then try again (or /class aegis to use the pooled lane).");throw e.status=402,e}throw e}}if("local"===t){const e=o.cfg&&o.cfg.baseURL||c.DEFAULT_BASE,t={...Number.isFinite(o.budgetSecs)?{budgetSecs:o.budgetSecs}:{},...Number.isFinite(o.tokPerSec)?{tokPerSec:o.tokPerSec}:{}},r=r=>c.chat({baseURL:e,model:o.model,prompt:o.prompt,system:o.system,messages:o.messages,maxTokens:o.maxTokens,signal:o.signal,onDelta:o.onDelta,...t,...r&&o.tools.length?{tools:o.tools,toolChoice:o.toolChoice}:{}});try{return await r(!0)}catch(e){if(o.tools.length&&e&&400===e.status)return r(!1);throw e}}if("pro"===t){const e=o.sessionKey||o.rootSessionId||o.sessionId;let t=null;if(e&&(t=x.get(e)||null,!t)){try{t=A.get(e,s)||null}catch{}t&&x.set(e,t)}const r=B(o.cwd),n=e=>claudePro.runClaudePro({prompt:proTurnPrompt(o),model:o.model&&"default"!==o.model?o.model:void 0,system:o.system,cwd:o.cwd,addDir:r,resumeSessionId:e||void 0,gate:b(),onAsk:async e=>{if(!e||!e.requestId)return"deny";const t=o.rootSessionId,r=o.rootOnDelta,n=PRO_TOOL_MAP[String(e.toolName||"")]||null,s=n||String(e.toolName||"unknown"),a=proAskArgs(e.input||{},s),i=covenant.preActionAssert({tool:s,args:a});if(!i.allowed)return r&&r({delta:"",note:`aegis: refused by the ÆGIS covenant — ${i.clause} (${i.label}): ${i.reason}`}),"deny";if(w()){if("exec"===s){const e=planExec(a&&a.command,{baseCwd:o.cwd||void 0});return e.oneShot?"once":(r&&r({delta:"",note:S(s,e.reason)}),"deny")}if(n&&m.MUTATING_TOOLS.has(s))return r&&r({delta:"",note:S(s)}),"deny";if(!n&&!PRO_PLAN_MODE_SAFE.has(s))return r&&r({delta:"",note:S(s)}),"deny"}if(!b())return"once";if("function"==typeof y){let e;try{e=y(s,a)}catch{e=null}if(e&&"deny"===e.verdict)return r&&r({delta:"",note:I(s)}),"deny";if(e&&"allow"===e.verdict)return"once"}if(D(t,s))return r&&r({delta:"",note:I(s)}),"deny";const l=await L(t,r,o.signal,{tool:s,args:a,diff:null});if("deny"===l)return R(t,s),"deny";if("session"!==l&&"once"!==l&&"always"!==l)return"deny";if("session"===l&&F(t,s,a),"always"===l&&"function"==typeof g)try{g(s,a)}catch{}return l},signal:o.signal,onDelta:o.onDelta,onSpawn:(e,t)=>{o.onDelta&&t&&o.onDelta({delta:"",note:claudePro.childLine(t)})}});let a=await n(t);if(a&&a.resumeStale){x.delete(e);try{A.del(e,s)}catch{}o.onDelta&&o.onDelta({delta:"",note:"aegis: the remembered Claude session no longer exists on this machine — continuing as a new conversation (earlier turns are not in its context)"}),a=await n(null)}if(e&&a&&a.sessionId&&!a.error){x.set(e,a.sessionId);try{A.set(e,a.sessionId,s)}catch{}}return a}throw new Error(`dispatch: unknown model class ${JSON.stringify(t)} — this build ships 'aegis', 'byok', 'local' and 'pro' only`)}async function K(o,r){const s=o&&o.class,a=o&&o.model,i=reasoningBudget("byok"===s?splitByokModel(a).model:a,o&&o.maxTokens,o&&o.effort),d=statedCapOf(o),u="aegis"===s&&Boolean(o&&o.autonomous),f=Boolean(o&&o.roundsAsk),y=o&&o.sessionId||randomUUID(),g=Number.isInteger(o&&o.depth)?o.depth:0,k=o&&o.rootSessionId||y,b=o&&o.rootOnDelta||r,w="function"==typeof r?e=>e&&r({reasoning:e}):void 0,S=new AbortController,E=p.get(y)||null;p.set(y,S);const _=S.signal,T=!(o&&!1===o.tools),x="local"!==s&&g<4,A=T?m.toolsFor({includeSubagent:x}):[],M=o&&o.toolChoice||null,N=j(o),O=o&&o.system||h(N),F=n?await n({payload:o,env:N,system:O}):null,D="string"==typeof F?F:F&&"string"==typeof F.system?F.system:O,R=Array.isArray(o&&o.messages)?o.messages.filter(Boolean).slice():[];let U=R.length,I=o&&o.prompt||"";const L=String(I||""),C=Array.isArray(o&&o.attachments)?o.attachments.filter(e=>e&&"object"==typeof e).slice(0,attachmentsModule.MAX_ATTACHMENTS):[];let $=C.length?attachmentsModule.buildContent(I,C):I,K=null;const W=j(o),z=((e,t)=>{if(null==l)return null;const o="function"==typeof l.policy?l.policy():l.policy;if(!o)return null;const r=require("./sandbox.js"),n=e&&e.cwd||process.cwd(),s=r.normalize(o,n);if("off"===s.mode)return null;let a=[];try{let e=null;try{e=require("node:os").homedir()}catch{e=null}a=r.autoGrants(n,{home:e,addDirs:(()=>{try{return B(n)}catch{return[]}})()})}catch{a=[]}if(a.length){const e=new Set;for(const t of s.fileSystem.entries)t&&t.path&&"path"===t.path.type&&t.path.path&&e.add(`${t.access}:${t.path.path}`);for(const t of a){const o=`${t.access}:${t.path.path}`;e.has(o)||(e.add(o),s.fileSystem.entries.push(t))}}return"local"===t&&"restricted"===s.network&&(s.network="open",s.networkExempt="local"),{policy:s,state:l.state||r.detect({appDir:l.appDir}),workspace:n,appDir:l.appDir,strict:!0===l.strict}})(W,s),V=W.cwd,H={getShell:()=>K||(K=new ShellSession({cwd:W.cwd,sandbox:z})),signal:_,cwd:V,desktopdir:W.desktopdir,sandbox:z,repeat:repeatGuard.beginRepeatGuard({cwd:V}),verify:verifyGuard.beginVerifyGuard({cwd:V}),guard:beginTurnGuard(V)};try{const n="byok"===s?splitByokModel(a):null;let l=null;const p="byok"===s?t.get(byokNamespace(n.provider))||{}:"local"===s&&t.get("local")||{},h="byok"===s?t.rawKey(byokNamespace(n.provider)):null,S="byok"!==s?null:h||providerKeyFromEnv(n.provider);if(!("byok"!==s||n.provider&&n.model)){const e=new Error('byok: model must be "<provider>:<model>" (pick one from /models) — got '+JSON.stringify(a||""));throw e.status=400,e}if("byok"===s&&!S){const t="anthropic"===n.provider?claudePro.claudeProStatus({env:process.env}):null,o=providerKeyRecord(n.provider).rejected,r=nexusFallbackModel({provider:n.provider,providerKey:S,providerKeyRefused:o,aegisKey:S?"":e.apiKey});if(!r){const e=new Error(o?`${o}. That is why this turn has no ${n.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 ${n.provider} <key> to set one here.`:t&&t.loggedIn?`No Anthropic API key on this machine — an "anthropic:…" id is served by your own console key, which a Claude subscription is not. Use the subscription instead: /class pro (it spends your Claude Code ${t.subscription||"Pro"} plan through the claude CLI) — or add a real console key: /byok-key anthropic <key>.`:`No key for "${n.provider}" yet. Easiest fix: /class aegis (uses your AEGIS key, no setup) — or add this provider's own key: /byok-key ${n.provider} <key>.`);throw e.status=400,e}l={from:n.provider,model:r}}if("byok"===s&&!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"===s){const e=c.remoteRefusal(p.baseURL||c.DEFAULT_BASE);if(e)throw e}if("byok"===s&&"custom"===n.provider&&!(p.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 E=l?"aegis":s,x={cls:E,model:l?l.model:a,mode:o&&o.mode,maxTokens:i,statedMaxTokens:d,autonomous:u,sessionId:y,signal:_,onDelta:r,cfg:p,apiKey:S,toolChoice:M,pooledFrom:l?l.from:void 0,cwd:V,rootSessionId:k,sessionKey:o&&o.sessionKey||void 0,rootOnDelta:b,effort:o&&o.effort,workers:o&&o.workers,...Number.isFinite(o&&o.budgetSecs)?{budgetSecs:o.budgetSecs}:{},...Number.isFinite(o&&o.tokPerSec)?{tokPerSec:o.tokPerSec}:{},recallDeep:o&&!0===o.recallDeep,singlePass:o&&!0===o.singlePass,onReasoning:w,idleTimeoutMs:u?9e5:void 0,stream:!o||!1!==o.stream};let N=!1,O=!1;const F=u?"AEGIS_AUTONOMOUS_MAX_ROUNDS":"AEGIS_CHAT_MAX_ROUNDS",j=(()=>{const e=Number.parseInt(process.env[F]||"",10);return Number.isFinite(e)&&e>0?e:0})(),B=j||(u?40:24);let K=v.keyFor(o,R),W=v.take(K);if(!W&&!v.isStatedKey(o)){const e=v.adopt();e&&(W=e.entry,K=e.key)}if(W){const e=v.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),I?(I=`${e}\n\n${I}`,$=C.length?attachmentsModule.buildContent(I,C):I):(R.push({role:"user",content:e}),$=""),b&&b({delta:`\n\n[resuming work this session left unfinished at ${W.rounds} tool rounds`+(W.interruptions>1?` (cut off ${W.interruptions}×)`:"")+"…]\n"})}let z=j||B+(W?v.bonus(B):0),X=0;const J=B,Q=8;let Z=0;const ee={calls:0},te=["input_tokens","output_tokens","prompt_tokens","completion_tokens","total_tokens","cache_read_input_tokens","cache_creation_input_tokens","prompt_cache_hit_tokens","prompt_cache_miss_tokens","reasoning_tokens","thinking_tokens"],oe=e=>{const t=e&&e.usage;if(t&&"object"==typeof t){ee.calls+=1;for(const e of te)"number"==typeof t[e]&&Number.isFinite(t[e])&&(ee[e]=(ee[e]||0)+t[e]);if("number"!=typeof t.total_tokens){const e=(t.prompt_tokens??t.input_tokens??0)+(t.completion_tokens??t.output_tokens??0);e&&(ee.total_tokens=(ee.total_tokens||0)+e)}}},re=e=>{if(!e||"object"!=typeof e)return e;const t=l?{...e,pooled_from:l.from,pooled_model:l.model,pooled_notice:requireSharedByokCatalog().nexusFallbackNotice({pooled_from:l.from,pooled_model:l.model})}:e;return ee.calls?{...t,usage:{...ee}}:t},ne=()=>{if(""===$)return;const e=R[R.length-1],t=e&&"user"===e.role?flattenContent(e.content):null;e&&"user"===e.role&&t===flattenContent($)||R.push({role:"user",content:$}),I="",$=""};U=R.length;const se=m&&m.MUTATING_TOOLS||new Set;let ae=0,ie=0,le=!1,ce=!1;for(;;){if(X>=z){if(f&&Z<Q&&!_.aborted&&await P(k,b,_,{spent:z,extensions:Z+1,max:Q,size:J})){Z+=1;const e=z;z+=J,R.push({role:"user",content:`You have used all ${e} tool rounds allowed for this turn; ${J} more have been granted (do not restart). Continue the task from exactly where you stopped — do not re-plan, do not repeat work already done, and finish with an answer.`});continue}const e=f?"":`, or raise ${F} for a longer single turn`,t=`[stopped at ${z} tool rounds`+(ee.total_tokens?`, ${ee.total_tokens.toLocaleString()} tokens`:"")+". This session holds the work: your next message here resumes it automatically"+` (with a continuation preamble)${e}.]`,o=v.record(K,{rounds:X,tokens:ee.total_tokens||0,note:t,chain:W?W.interruptions:0,messages:R,added:R.slice(U)});return b&&b({delta:`\n\n${t}`}),re({model:x.model,choices:[{message:{content:t},finish_reason:"length"}],stoppedOnRounds:!0,heldForSession:!0,heldRounds:o.rounds,sessionInterruptions:o.interruptions,resumedFrom:K})}X+=1;const e={...x,system:D,messages:R,prompt:$,tools:A,recallDeep:x.recallDeep&&1===X};let t;if(t=await G(E,e),oe(t),_.aborted)return re(t);if(!N&&!assistantText(t)&&(isTruncated(t)||reasonedButSilent(t))){N=!0;const o=reasonedButSilent(t);if(t=await G(E,{...e,singlePass:!0,recallDeep:!1,effort:o?"high":e.effort,maxTokens:retryBudgetFor(e,o),statedMaxTokens:e.statedMaxTokens?doubledBudget(e.statedMaxTokens):void 0}),oe(t),_.aborted)return re(t)}const n=A.length?extractToolCalls(t):[];if(!n.length){if(assistantText(t)||O||!T){if(!le&&T&&wantsMutation(L,ie>0,ae)){le=!0,ne(),R.push({role:"assistant",content:assistantText(t)}),R.push({role:"user",content:UNMUTATED_TURN_NUDGE}),b&&b({delta:""});continue}if(H.verify&&!ce){const e=verifyGuard.shouldNudge(H.verify);if(e.nudge){ce=!0,ne(),R.push({role:"assistant",content:assistantText(t)}),R.push({role:"user",content:e.text}),b&&b({delta:""});continue}}return re(t)}O=!0,ne(),R.push({role:"user",content:reasonedButSilent(t)?THOUGHT_ONLY_NUDGE:EMPTY_TURN_NUDGE});const o={...e,singlePass:!0,recallDeep:!1,messages:R,prompt:"",tools:[]};t=await G(E,o);let r=o.maxTokens,n=o.effort;if(oe(t),_.aborted)return re(t);if(!assistantText(t)&&(isTruncated(t)||reasonedButSilent(t))){const e=reasonedButSilent(t);if(r=retryBudgetFor(o,e),n=e?"high":o.effort,t=await G(E,{...o,effort:n,maxTokens:r,statedMaxTokens:o.statedMaxTokens?doubledBudget(o.statedMaxTokens):void 0}),oe(t),_.aborted)return re(t)}const i=(()=>{const e=Number(r)||0;if(!e)return r;const t={maxTokens:r};return o.statedMaxTokens&&(t.statedMaxTokens=o.statedMaxTokens),Math.max(e,retryBudgetFor(t,!0))})();let l=0;for(;!assistantText(t)&&l<2&&!_.aborted;){const e=reasonedButSilent(t);if(l+=1,R.push({role:"user",content:e?1===l?THOUGHT_ONLY_NUDGE:FINAL_ANSWER_NUDGE:EMPTY_TURN_NUDGE}),e&&(n="high"),r=i,t=await G(E,{...o,messages:R,effort:n,maxTokens:r,statedMaxTokens:o.statedMaxTokens?doubledBudget(o.statedMaxTokens):void 0}),oe(t),_.aborted)return re(t)}if(!assistantText(t))throw emptyTurnError({cls:s,model:a,effort:n,recoveryRounds:l,finishReason:finishReasonOf(t),reasoningChars:reasoningTextOf(t).length,reasoningTokens:reasoningTokensOf(t)});return re(t)}ne(),R.push({role:"assistant",content:assistantText(t),tool_calls:n.map(e=>({id:e.id,type:"function",function:{name:e.name,arguments:JSON.stringify(e.args)}}))});const i=new WeakMap,l=e=>{if("exec"!==e.name)return null;if(i.has(e))return i.get(e);const t=planExec(e.args&&e.args.command,{baseCwd:V});return i.set(e,t),t},c=e=>{if(!se.has(e.name))return!0;const t=l(e);return Boolean(t&&t.oneShot)},u=[];for(const e of n){const t=u[u.length-1];c(e)&&t&&t.parallel?t.calls.push(e):u.push({parallel:c(e),calls:[e]})}const p=async e=>{r&&r({delta:"",tool:{name:e.name,args:e.args,id:e.id,cwd:V,phase:"run"}});const t=l(e),n=t&&t.oneShot?{...H,oneShotExec:!0,cwd:t.cwd||H.cwd}:H,i=e.name===m.SUBAGENT_TOOL?await Y(e.args,{cls:s,model:a,statedMaxTokens:d,effort:o&&o.effort,mode:o&&o.mode,parentSignal:_,depth:g,rootSessionId:k,rootOnDelta:b}):await q(e,{toolCtx:n,rootSessionId:k,rootOnDelta:b,signal:_});return i&&i.usage&&oe({usage:i.usage}),r&&r({delta:"",tool:{name:e.name,args:e.args,ok:i.ok,id:e.id,cwd:V,phase:"done"}}),i};for(const e of u){const t=e.parallel&&e.calls.length>1?await Promise.all(e.calls.map(e=>p(e))):[await p(e.calls[0])];e.calls.forEach((e,o)=>{const r=t[o];se.has(e.name)&&(ae+=1,r&&r.ok&&(ie+=1)),R.push({role:"tool",tool_call_id:e.id,name:e.name,content:m.toolResultText(r)})})}}}catch(e){throw _.aborted&&e&&"object"==typeof e&&(e.aegisCancelled=!0),e}finally{K&&K.dispose(),p.get(y)===S&&(E&&!E.signal.aborted?p.set(y,E):p.delete(y))}}async function Y({description:e,subagent_type:t,prompt:o}={},{cls:r,model:n,statedMaxTokens:s,effort:a,mode:i,parentSignal:l,depth:c,rootSessionId:d,rootOnDelta:u}={}){const f=String(o||e||"").trim();if(!f)return{ok:!1,error:"task requires a prompt"};const p=t&&"general"!==t?agentRoleLabel(t):"general",m=agentSystemPrompt(t),h=randomUUID();let y;if(l){if(l.aborted)return{ok:!1,error:"aborted"};y=()=>W(h),l.addEventListener("abort",y,{once:!0})}try{const e=await K({class:r,model:n,mode:i,system:m,prompt:f,sessionId:h,depth:(c||0)+1,rootSessionId:d,rootOnDelta:u,statedMaxTokens:s,effort:a},()=>{}),t=assistantText(e),o=e&&e.usage?{usage:e.usage}:{};return t?{ok:!0,output:t,...o}:{ok:!1,error:`subagent (${p}) produced no output`,...o}}catch(e){return{ok:!1,error:`subagent (${p}) failed: ${e&&e.message?e.message:e}`}}finally{l&&y&&l.removeEventListener("abort",y)}}function W(e){const t=p.get(e);return t&&t.abort(),{ok:Boolean(t)}}function z(e){const o=String(null==e?"":e).trim().toLowerCase();if(!o)return"";try{if(t&&"function"==typeof t.rawKey){const e=t.rawKey(byokNamespace(o));if("string"==typeof e&&e.trim())return e.trim()}}catch{}return providerKeyFromEnv(o)}async function V(t){let o=[];try{const t=await e.byokProviders();o=withUserModels(withCatalog(withByokAdditions(t&&t.providers||[])))}catch(e){return{ok:!1,providers:[],missing:0,stale:0,skipped:[],failed:[],error:e&&e.message||String(e)}}const r={};for(const e of modelSync.askableProviders(o,t)){const t=z(e);t&&(r[e]=t)}return modelSync.plan(o,{keys:r,fetchImpl:d,only:t})}const H=createModelAutoSync({getPref:()=>{try{return t&&"function"==typeof t.getSharedPref?t.getSharedPref("modelAutoSync"):null}catch{return null}},plan:e=>V(e),apply:(e,t)=>modelSync.apply(e,{only:t})});return{CLASSES:CLASSES,listClasses:async function(){return CLASSES.map(o=>{if("aegis"===o.class)return{...o,configured:Boolean(e.apiKey)};if("byok"===o.class){const e=(t.list()||[]).some(e=>!(!e||"string"!=typeof e.provider||!e.provider.startsWith("byok:"))&&(!!e.configured||Boolean(providerKeyFromEnv(e.provider.slice(5)))));return{...o,configured:e}}if("local"===o.class)return{...o,configured:!0};if("pro"===o.class){const e=claudePro.claudeProStatus({env:process.env}),t=claudePro.seamAvailable();return{...o,configured:e.loggedIn,status:e,seam:t}}return{...o,configured:!1}})},listModels:async function(o){if("aegis"===o){if(!e.apiKey)return{class:o,models:[],needsKey:!0};const t=await e.listModels();return{class:o,models:offerableCatalog(normalizeCatalog(t&&t.models))}}if("byok"===o){let r=[],n=null,s=!1,a=null;try{const t=await e.byokProviders();r=withUserModels(withCatalog(withByokAdditions(t&&t.providers||[]))),n=t&&t.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 o=t.get(byokNamespace(e.id))||{},r=providerKeyRecord(e.id),n=r.key||"",s=Array.isArray(e.models)?e.models:[];for(const t of s){const s="string"==typeof t?t:t&&t.id;s&&i.push({id:`${e.id}:${s}`,label:`${e.label||e.id} — ${s}`,provider:e.id,configured:Boolean(o.configured||n),keyRejected:r.rejected||null})}}return{class:o,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"===o){const e=(t.get("local")||{}).baseURL||c.DEFAULT_BASE,r=await c.probe(e);if(!r.running)return{class:o,models:[],baseURL:r.baseURL,needsDaemon:!0};let n=[],s=!0;try{n=await c.listTags(e)}catch{s=!1}return{class:o,models:n,baseURL:r.baseURL,listed:s}}if("pro"===o){const e=claudePro.claudeProStatus({env:process.env});return{class:o,models:claudePro.PRO_MODELS.map(t=>({id:t.id,label:t.label,note:t.note,configured:e.loggedIn})),needsProviderKey:!1,needsAegisKey:!1,subscription:e.subscription,loggedIn:e.loggedIn,credentialFile:e.file,shadowed:e.shadowed||null,seam:claudePro.seamAvailable()}}throw new Error(`listModels: unknown model class ${JSON.stringify(o)} — this build ships 'aegis', 'byok', 'local' and 'pro' only`)},chat:K,cancel:W,respondApproval:function(e,t){const o=M.get(e);return o?(M.delete(e),o.resolve("session"===t||"once"===t||"always"===t?t:"deny"),{ok:!0}):{ok:!1}},respondRoundsAsk:function(e,t){const o=N.get(e);return o?(N.delete(e),o.resolve(!0===t||"continue"===t),{ok:!0}):{ok:!1}},clearSessionApprovals:function(e){E.delete(e),_.delete(e),T.delete(e),x.delete(e);try{A.del(e,s)}catch{}return{ok:!0}},listUndoable:function(e){return(T.get(e)||[]).map(e=>({id:e.id,tool:e.tool,path:e.path,at:e.at})).reverse()},undoMutation:function(e,t){const o=T.get(e)||[],r=t?o.findIndex(e=>e.id===t):o.length-1;if(-1===r)return{ok:!1,error:t?`no undo record "${t}" for this conversation`:"nothing to undo in this conversation"};const n=o[r],s=U(n.path);if(!s||s.existed!==n.after.existed||s.content!==n.after.content)return{ok:!1,error:`${n.path} has changed since ${n.tool} ran — undo refused rather than overwriting work this session did not do. Resolve it by hand, or undo a different entry.`};try{n.before.existed?fs.writeFileSync(n.path,n.before.content,"utf8"):fs.unlinkSync(n.path)}catch(e){return{ok:!1,error:`undo failed: ${e&&e.message||e}`}}return o.splice(r,1),{ok:!0,path:n.path,restored:n.before.existed?"content":"deleted"}},settings:t,unloadLocalModels:function(){return c.unloadAll()},userModels:()=>loadUserModels(),addUserModel:(e,t)=>addUserModel(e,t),removeUserModel:(e,t)=>removeUserModel(e,t),discoverModels:async e=>{const t=String(null==e?"":e).trim().toLowerCase(),o=z(t),r=await discoverVendorModels(t,{key:o,fetchImpl:d});if(!r||!r.ok)return r;const n=[];try{const e=loadUserModels().map;for(const o of Array.isArray(e[t])?e[t]:[])n.push(o)}catch{}return{...r,declared:n,endpoint:(vendorEndpointFor(t)||{}).url||""}},modelSyncPlan:async e=>V(e),modelSyncApply:(e,t)=>modelSync.apply(e,{only:t}),modelAutoSync:H,modelAutoSyncRun:e=>H.runIfDue(e),modelAutoSyncStatus:()=>H.status(),addUserModels:(e,t)=>{const o=Array.isArray(t)?t:[],r={provider:e,added:0,already:[],failed:[],capped:0,file:""};for(const t of o)try{const o=addUserModel(e,t);r.file=o.file||r.file,o.added?r.added+=1:r.already.push(o.model)}catch(e){const n=e&&e.message||String(e);if(/the cap/.test(n)){r.capped=o.length-r.added-r.already.length-r.failed.length;break}r.failed.push({id:String(t),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,3 @@
|
|
|
1
1
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
2
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
-
"use strict";const{estimateTokens:estimateTokens,trimContext:trimContext}=require("./context.js"),attachmentsModule=require("./attachments.js"),DEFAULT_BASE="http://localhost:11434",SSE_IDLE_TIMEOUT_MS=3e5,FIRST_BYTE_TIMEOUT_MS=3e5,HEADERS_DEADLINE_MS=3e5;function isHeadersDeadline(e){if(!e)return!1;const t=e.cause||e;if(!t)return!1;const n=String(t.code||""),s=String(t.name||"");return"UND_ERR_HEADERS_TIMEOUT"===n||"HeadersTimeoutError"===s}const PROBE_TIMEOUT_MS=1500;function normalizeBase(e){const t=String(null==e?"":e).trim();return t?/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(t)?t:`http://${t}`:DEFAULT_BASE}function baseOf(e){return normalizeBase(e).replace(/\/+$/,"")}const DSML_RE_INVOKE=/<\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call)\b\s*([^>]*?)\s*>([\s\S]*?)<\s*\/\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call)\b\s*>/g,DSML_RE_PARAM=/<\s*|\s*(?:DSML\s*)?|\s*(?:parameter|param|arg)\b\s*([^>]*?)\s*>([\s\S]*?)<\s*\/\s*|\s*(?:DSML\s*)?|\s*(?:parameter|param|arg)\b\s*>/g,DSML_RE_LEADER=/<\s*\/?\s*|\s*(?:DSML\s*)?|\s*(?:(?:tool|function)[_▁ ]*calls?|reasoning)[_▁ ]*(?:begin|end)?\s*>/gi,DSML_RE_ANY_TAG=/<\s*\/?\s*|\s*(?:DSML\s*)?|\s*[A-Za-z_][A-Za-z0-9_]*[^>]{0,120}>/g,DSML_RE_SKELETON=/<\s*\/?\s*(?:tool_calls|function_calls|invoke|parameter|param|reasoning)\b[^>]{0,120}>/gi,DSML_RE_JSON_CALLS=/|[ \t]*(?:tool|function)[_▁ ]*calls?[_▁ ]*begin[ \t]*|([\s\S]*?)|[ \t]*(?:tool|function)[_▁ ]*calls?[_▁ ]*end[ \t]*|/gi,DSML_RE_JSON_CALLS_OPEN=/|[ \t]*(?:tool|function)[_▁ ]*calls?[_▁ ]*begin[ \t]*|/gi,DSML_RE_JSON_CALLS_CLOSE=/|[ \t]*(?:tool|function)[_▁ ]*calls?[_▁ ]*end[ \t]*|/gi,DSML_RE_ENVELOPE_TOKEN=/|[ \t]?[A-Za-z0-9_▁]*[ \t]?|/g,DSML_RE_DRIFT_INVOKE=/<\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call)\b\s*([^>]*?)\s*>/gi,DSML_RE_DRIFT_PARAM=/<\s*|\s*(?:DSML\s*)?|\s*(?:parameter|param|arg)\b\s*([^>]*?)\s*>/gi,DSML_RE_PARAM_CLOSE=/<\s*\/\s*|\s*(?:DSML\s*)?|\s*(?:parameter|param|arg)\b\s*>/gi,DSML_RE_ATTR=/([A-Za-z_][A-Za-z0-9_.-]*)\s*=\s*(?:"([^"]*)"|'([^']*)')/g,DSML_RE_STRUCT_TAG=/<\s*\/?\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call|parameter|param|arg|reasoning|(?:tool|function)[_▁ ]*calls?)\b/gi,DSML_RE_STRUCT_CLOSER=/<\s*\/\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call|parameter|param|arg|reasoning|(?:tool|function)[_▁ ]*calls?)\b/gi,DSML_RE_WRAPPER_TAG=/<\s*\/?\s*|\s*(?:DSML\s*)?|\s*(?!(?:invoke|call|tool_call|parameter|param|arg)\b)[A-Za-z_][A-Za-z0-9_]*[^>]{0,120}>/g,DSML_RE_TRAILING_LT=/<\s*\/?\s*$/,DSML_RE_OPEN_TOKEN=/^|[ \t]?[A-Za-z0-9_▁]*[ \t]?$/,DSML_HOLD_MAX=4194304;function dsmlAttrs(e){const t={};if(!e)return t;let n;for(DSML_RE_ATTR.lastIndex=0;n=DSML_RE_ATTR.exec(e);)t[n[1].toLowerCase()]=null!=n[2]?n[2]:n[3];return t}function dsmlJson(e){const t=String(null==e?"":e).trim();try{const e=JSON.parse(t);return void 0===e?t:e}catch{return t}}function dsmlArgs(e){const t={};let n;for(DSML_RE_PARAM.lastIndex=0;n=DSML_RE_PARAM.exec(e);){const e=dsmlAttrs(n[1]),s=e.name||e.key||`arg${Object.keys(t).length}`,o="false"===String(e.string||"").toLowerCase()||"true"===String(e.json||"").toLowerCase();t[s]=o?dsmlJson(n[2]):n[2]}return t}function decodeDeepSeekDSML(e){if("string"!=typeof e||!e||-1===e.indexOf("|"))return{text:e||"",calls:[]};const t=[];let n=e;DSML_RE_INVOKE.lastIndex=0;const s=[];let o;for(;o=DSML_RE_INVOKE.exec(n);){const e=dsmlAttrs(o[1]),n=e.name||e.function||e.tool||"";n&&t.push({name:n,args:dsmlArgs(o[2])}),s.push([o.index,o.index+o[0].length])}for(let e=s.length-1;e>=0;e--)n=n.slice(0,s[e][0])+n.slice(s[e][1]);return n=n.replace(DSML_RE_JSON_CALLS,(e,n)=>{const s=dsmlJson(n),o=Array.isArray(s)?s:s&&Array.isArray(s.tool_calls)?s.tool_calls:[];for(const e of o){const n=e&&e.function||e||{},s=n.name||e&&e.name||"";if(!s)continue;let o=null!=n.arguments?n.arguments:e&&e.arguments;"string"==typeof o&&(o=dsmlJson(o)),t.push({name:s,args:o&&"object"==typeof o?o:{}})}return""}),n=n.replace(DSML_RE_LEADER,""),{text:n,calls:t}}function decodeDeepSeekDSMLDrift(e){if("string"!=typeof e||!e||-1===e.indexOf("|"))return{text:e||"",calls:[]};const t=[];let n;for(DSML_RE_DRIFT_INVOKE.lastIndex=0;n=DSML_RE_DRIFT_INVOKE.exec(e);)t.push({at:n.index,attrs:n[1],body:DSML_RE_DRIFT_INVOKE.lastIndex});if(!t.length)return{text:e,calls:[]};const s=[];let o="",r=0;for(let n=0;n<t.length;n++){const a=n+1<t.length?t[n+1].at:e.length,l=e.slice(t[n].body,a),i=dsmlAttrs(t[n].attrs),c=i.name||i.function||i.tool||"",u={},f=[];let d;for(DSML_RE_DRIFT_PARAM.lastIndex=0;d=DSML_RE_DRIFT_PARAM.exec(l);)f.push({at:d.index,attrs:d[1],from:DSML_RE_DRIFT_PARAM.lastIndex});for(let e=0;e<f.length;e++){const t=e+1<f.length?f[e+1].at:l.length,n=l.slice(f[e].from,t).replace(DSML_RE_PARAM_CLOSE,""),s=dsmlAttrs(f[e].attrs),o=s.name||s.key||`arg${Object.keys(u).length}`,r="false"===String(s.string||"").toLowerCase();u[o]=r?dsmlJson(n):n}o+=e.slice(r,t[n].at),r=a,c&&s.push({name:c,args:u})}return o+=e.slice(r),{text:o,calls:s}}function dsmlResidue(e){return e?-1===e.indexOf("|")?e.replace(DSML_RE_SKELETON,""):e.replace(DSML_RE_ANY_TAG,"").replace(DSML_RE_SKELETON,"").replace(DSML_RE_ENVELOPE_TOKEN,""):e}function dsmlUnterminated(e){return!!DSML_RE_OPEN_TOKEN.test(e)||(e.match(DSML_RE_STRUCT_TAG)||[]).length>(e.match(DSML_RE_STRUCT_CLOSER)||[]).length}function dsmlHoldFrom(e){const t=e.search(/<\s*\/?\s*|/);if(-1!==t)return t;const n=e.search(DSML_RE_JSON_CALLS_OPEN);if(-1!==n&&-1===e.slice(n).search(DSML_RE_JSON_CALLS_CLOSE))return n;const s=DSML_RE_TRAILING_LT.exec(e);if(s)return s.index;const o=e.indexOf("|");return-1!==o&&dsmlUnterminated(e.slice(o))?o:-1}function decodePlainToolCallTags(e,t){if(!e||-1===e.indexOf("<"))return e;let n="",s=0;for(;;){const o=TEXT_TOOL_TAG_OPEN_RE.exec(e.slice(s));if(!o)break;const r=s+o.index,a=o[0];if(a.includes(DSML_TAG_MARK)){n+=e.slice(s,r+a.length),s=r+a.length;continue}const l=e.slice(r+a.length),i=TEXT_TOOL_TAG_CLOSE_RE.exec(l);if(!i)break;const c=textCallsIn(l.slice(0,i.index));if(n+=e.slice(s,r),s=r+a.length+i.index+i[0].length,c.length)for(const e of c)t.push(e);else n+=e.slice(r,s)}return n+e.slice(s)}function plainToolTagHoldAt(e){if(!e||-1===e.indexOf("<"))return-1;let t=0;for(;;){const n=TEXT_TOOL_TAG_OPEN_RE.exec(e.slice(t));if(!n)return-1;const s=t+n.index;if(n[0].includes(DSML_TAG_MARK)){t=s+n[0].length;continue}const o=e.slice(s+n[0].length);return TEXT_TOOL_TAG_CLOSE_RE.test(o)?-1:s}}function makeDeepSeekEnvelopeStripper(){let e="";const t=[],n=e=>dsmlResidue(decodePlainToolCallTags(e,t)),s=s=>{e+="string"==typeof s?s:"";const o=decodeDeepSeekDSML(e);e=o.text;for(const e of o.calls)t.push(e);e=e.replace(DSML_RE_WRAPPER_TAG,"");const r=dsmlHoldFrom(e);let a;-1!==r&&e.length-r<=4194304?(a=e.slice(0,r),e=e.slice(r)):(a=e,e="");const l=plainToolTagHoldAt(a);return-1!==l&&(e=a.slice(l)+e,a=a.slice(0,l)),n(a)};return s.flush=()=>{const s=decodeDeepSeekDSML(e);e="";for(const e of s.calls)t.push(e);const o=decodeDeepSeekDSMLDrift(s.text);for(const e of o.calls)t.push(e);return n(o.text)},s.calls=()=>t.slice(),s}const TEXT_TOOL_TAG_OPEN_RE=/<\s*tool_calls?\b[^>]{0,80}>/i,TEXT_TOOL_TAG_CLOSE_RE=/<\s*\/\s*tool_calls?\s*>/i,TEXT_FENCE_RE=/```[ \t]*[A-Za-z0-9_+-]*[ \t]*\n?([\s\S]*?)```/,TEXT_FENCE_OPEN_RE=/```[ \t]*[A-Za-z0-9_+-]*[ \t]*\n?/,DSML_TAG_MARK="|";function asTextToolCall(e){if(!e||"object"!=typeof e)return null;let t=e;t.function&&"object"==typeof t.function&&(t={...t.function,name:t.function.name||t.name});const n=t.name||t.tool||t.tool_name||t.function_name,s="string"==typeof n?n.trim():"";if(!s)return null;let o=null!=t.arguments?t.arguments:null!=t.parameters?t.parameters:null!=t.args?t.args:null!=t.tool_input?t.tool_input:{};if("string"==typeof o){const e=o.trim()?safeJson(o):{};o=e&&"object"==typeof e?e:{}}return null!=o&&"object"==typeof o||(o={}),{name:s,args:o}}function safeJson(e){try{return JSON.parse(e)}catch{return null}}function textCallsIn(e){const t=String(e||"").trim().replace(/^json\s*/i,"").trim();if(!t)return[];const n=safeJson(t);if(!n)return[];const s=Array.isArray(n)?n:[n],o=[];for(const e of s){const t=asTextToolCall(e);t&&o.push(t)}return o}function nextTextToolEnvelope(e){const t=TEXT_FENCE_RE.exec(e);if(t)return{start:t.index,end:t.index+t[0].length,complete:!0,raw:t[0],body:t[1]};const n=TEXT_FENCE_OPEN_RE.exec(e);return n?{start:n.index,end:e.length,complete:!1,body:e.slice(n.index+n[0].length)}:null}function trailingHeadFrom(e,t=!1){if(!e)return-1;const n=e.search(TEXT_TOOL_HEAD_RE);if(-1!==n)return n;const s=/`{1,2}$/.exec(e);if(s)return s.index;const o=e.lastIndexOf("<");if(-1!==o&&couldBeTextToolHead(e.slice(o)))return o;if(t){const t=e.lastIndexOf("{");if(-1!==t&&/^\{\s*(?:"[^"]*"\s*:[\s\S]*|"[^"]*"?\s*|)$/.test(e.slice(t)))return t}return-1}function couldBeTextToolHead(e){const t=e.replace(/^[\s\uFEFF]+/,"");if(!t)return!0;if(t.length<=3&&"```".startsWith(t))return!0;if(t.startsWith("<")&&!TEXT_TOOL_HEAD_RE.test(t)){const e=t.slice(1).replace(/^\/?\s*/,"").toLowerCase();if(e.length<=10&&/^[a-z_]*$/.test(e))return"tool_call".startsWith(e)||"tool_calls".startsWith(e)}return!1}function balancedJsonEnd(e,t){let n=0,s=!1,o=!1;for(let r=t;r<e.length;r++){const t=e[r];if(s)o?o=!1:"\\"===t?o=!0:'"'===t&&(s=!1);else if('"'===t)s=!0;else if("{"===t||"["===t)n++;else if(("}"===t||"]"===t)&&(n--,n<=0))return r+1}return-1}function makeTextToolCallStripper({toolNames:e=null}={}){const t=e?new Set([...e].map(e=>String(e))):null;let n="";const s=[],o=e=>Boolean(e.length)&&(!t||e.every(e=>t.has(e.name))),r=(e,t)=>{const n=textCallsIn(t);if(!o(n))return e;for(const e of n)s.push(e);return""},a=e=>{n+="string"==typeof e?e:"";let a="",l=!1;for(;;){const e=nextTextToolEnvelope(n);if(e){if(a+=n.slice(0,e.start),n=n.slice(e.start),!e.complete){l=!0;break}a+=r(e.raw,e.body),n=n.slice(e.raw.length);continue}const i=TEXT_TOOL_TAG_OPEN_RE.exec(n);if(i){a+=n.slice(0,i.index),n=n.slice(i.index);const e=n.slice(i[0].length),t=TEXT_TOOL_TAG_CLOSE_RE.exec(e);if(!t){l=!0;break}const s=n.slice(0,i[0].length+t.index+t[0].length);a+=r(s,e.slice(0,t.index)),n=n.slice(s.length);continue}const c=t?/\{\s*"/.exec(n):null;if(!c)break;const u=balancedJsonEnd(n,c.index),f=n.slice(0,c.index);if(-1===u){a+=f,n=n.slice(c.index),l=!0;break}const d=textCallsIn(n.slice(c.index,u));if(a+=f,o(d))for(const e of d)s.push(e);else a+=n.slice(c.index,u);n=n.slice(u)}const i=l?0:trailingHeadFrom(n,Boolean(t));return-1===i?(a+=n,n=""):i>0&&(a+=n.slice(0,i),n=n.slice(i)),n.length>TEXT_TOOL_HOLD_MAX&&(a+=n,n=""),a};return a.flush=()=>{const e=n;if(n="",!e)return"";const s=nextTextToolEnvelope(e);if(s)return e.slice(0,s.start)+r(e.slice(s.start),s.body);const o=TEXT_TOOL_TAG_OPEN_RE.exec(e);if(!o){const n=t?/\{\s*"/.exec(e):null;if(!n)return e;const s=balancedJsonEnd(e,n.index);return-1===s?e:e.slice(0,n.index)+r(e.slice(n.index,s),e.slice(n.index,s))+e.slice(s)}const a=e.slice(o.index+o[0].length).replace(TEXT_TOOL_TAG_CLOSE_RE,"");return e.slice(0,o.index)+r(e.slice(o.index),a)},a.calls=()=>s.slice(),a}const TEXT_TOOL_HEAD_RE=/```|<\s*tool_calls?\b/i,TEXT_TOOL_HOLD_MAX=65536;function isLocalEndpoint(e){let t="",n="";if(""===String(null==e?"":e).trim())return!1;try{const s=new URL(normalizeBase(e));t=s.hostname.toLowerCase(),n=s.protocol.toLowerCase()}catch{return!1}if("http:"!==n&&"https:"!==n)return!1;if(!t)return!1;if(t.startsWith("[")&&t.endsWith("]")&&(t=t.slice(1,-1)),!t||/[\s/\\@]/.test(t))return!1;if("localhost"===t||t.endsWith(".localhost"))return!0;if(/\.(local|internal|lan)$/.test(t))return!0;if(t.includes(":"))return"::1"===t||"0:0:0:0:0:0:0:1"===t||!!/^f[cd][0-9a-f]{2}:/.test(t)||!!/^fe[89ab][0-9a-f]:/.test(t);const s=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(t);if(s){const e=s.slice(1).map(Number);if(e.some(e=>e>255))return!1;const[t,n]=e;return 127===t||10===t||172===t&&n>=16&&n<=31||192===t&&168===n||169===t&&254===n}return!t.includes(".")}function remoteRefusal(e){if(isLocalEndpoint(e))return null;const t=new Error(`local: ${JSON.stringify(String(e||""))} is not on this machine, so it is not the local class. Running a model you own is free because there is no vendor to pay — a remote URL here would be an unpaid turn instead. Use the aegis or byok class for remote models.`);return t.status=400,t}async function probe(e=DEFAULT_BASE){const t=baseOf(e);try{return{running:(await fetch(`${t}/api/tags`,{signal:AbortSignal.timeout(1500)})).ok,baseURL:t}}catch{return{running:!1,baseURL:t}}}async function listTags(e=DEFAULT_BASE){const t=await fetch(`${baseOf(e)}/api/tags`);if(!t.ok){const e=new Error(`local: /api/tags answered ${t.status}`);throw e.status=t.status,e}const n=await t.json();return(n&&n.models||[]).map(e=>({id:e&&e.name,...e&&e.details?{details:e.details}:{}})).filter(e=>e.id)}const UNLOAD_TIMEOUT_MS=4e3,RESIDENT_TIMEOUT_MS=3e5,DEFAULT_WARM_SECS=1800;async function unload(e,t){if(!t)return{ok:!1};const n=baseOf(e);if(!isLocalEndpoint(n))return{ok:!1};try{return{ok:(await fetch(`${n}/api/chat`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({model:String(t),messages:[],stream:!1,keep_alive:0}),signal:AbortSignal.timeout(4e3)})).ok}}catch{return{ok:!1}}}function normalizeRow(e){if(!e||"object"!=typeof e)return null;const t={role:e.role||"user"};return null!=e.content&&(t.content=e.content),e.name&&(t.name=e.name),e.tool_call_id&&(t.tool_call_id=e.tool_call_id),Array.isArray(e.tool_calls)&&e.tool_calls.length&&(t.tool_calls=e.tool_calls),t}function parseEvent(e){const t=String(e).split("\n");let n="",s=!1;for(const e of t){if(!e||e.startsWith(":"))continue;const t=e.indexOf(":"),o=-1===t?e:e.slice(0,t),r=-1===t?"":e.slice(t+1).replace(/^ /,"");"data"===o?(n+=r,s=!0):"event"!==o&&"id"!==o&&"retry"!==o||(s=!0)}if(!s||!n)return null;if("[DONE]"===n)return{done:!0};try{return{json:JSON.parse(n)}}catch{return null}}async function readSSE(e,t,{idleTimeoutMs:n=3e5}={}){const s=e.body.getReader(),o=new TextDecoder;let r="",a=null,l=()=>{};const i=new Promise((e,t)=>{l=t}),c=()=>{a&&clearTimeout(a),a=setTimeout(()=>{l(new Error(`local: the model stopped responding — no output for ${Math.round(n/1e3)}s`))},n)};c();try{for(;;){const e=await Promise.race([s.read(),i]);if(e.done)break;let n;for(r+=o.decode(e.value,{stream:!0}),r=r.replace(/\r\n/g,"\n");(n=r.indexOf("\n\n"))>=0;){const e=r.slice(0,n);r=r.slice(n+2);const s=parseEvent(e);if(s){if(s.done)return;s.json&&(c(),t(s.json))}}}}finally{a&&clearTimeout(a);try{await s.cancel()}catch{}}}const localCallQueues=new Map;function runSerialized(e,t){const n=(localCallQueues.get(e)||Promise.resolve()).then(t,t);return localCallQueues.set(e,n.then(()=>{},()=>{})),n}const activeCountByKey=new Map,warmModelByBase=new Map;function swapWarmModel(e,t){if(!t)return;const n=warmModelByBase.get(e);warmModelByBase.set(e,t),n&&n!==t&&(activeCountByKey.get(`${e}|${n}`)||unload(e,n).catch(()=>{}))}async function unloadAll(){const e=[...warmModelByBase.entries()];warmModelByBase.clear(),await Promise.all(e.map(([e,t])=>unload(e,t)))}function warmSecsFor({warmSecs:e}={}){const t=Number(e);if(Number.isFinite(t)&&t>=0)return Math.floor(t);const n=Number(process.env&&process.env.AEGIS_LOCAL_WARM_SECS);return Number.isFinite(n)&&n>=0?Math.floor(n):1800}const residentMemo=new Map;function residentKey(e,t,n){return`${e}\0${t}\0${n}`}function residentSecsLeft(e,t,n,{dialer:s=fetch,now:o=Date.now()}={}){const r=residentMemo.get(residentKey(e,t,n));if(!r||r.dialer!==s)return 0;const a=Math.round((r.until-o)/1e3);return a<=0?(residentMemo.delete(residentKey(e,t,n)),0):a}function residentEntry(e,t,n,{dialer:s=fetch,now:o=Date.now()}={}){const r=residentMemo.get(residentKey(e,t,n));return r&&r.dialer===s&&r.until-o>0?r:null}function sameModel(e,t){const n=String(e||""),s=String(t||"");return!(!n||!s)&&(n===s||n.startsWith(`${s}:`)||n.startsWith(`${s}@`))}const WINDOW_TIMEOUT_MS=3e3;async function windowOf(e,t,{signal:n}={}){const s=new AbortController,o=()=>s.abort();if(n){if(n.aborted)return null;"function"==typeof n.addEventListener&&n.addEventListener("abort",o,{once:!0})}const r=setTimeout(()=>s.abort(),3e3);r&&"function"==typeof r.unref&&r.unref();try{const n=await fetch(`${e}/api/ps`,{method:"GET",signal:s.signal});if(!n||!n.ok||"function"!=typeof n.json)return null;const o=await n.json(),r=(o&&o.models||[]).find(e=>sameModel(e&&(e.name||e.model),t)),a=r&&Number(r.context_length);return Number.isFinite(a)&&a>0?a:null}catch{return null}finally{clearTimeout(r),n&&"function"==typeof n.removeEventListener&&n.removeEventListener("abort",o)}}async function ensureResident({baseURL:e=DEFAULT_BASE,model:t,system:n="",signal:s,warmSecs:o,firstByteTimeoutMs:r}={}){const a=baseOf(e);if(!isLocalEndpoint(a))return{ok:!1,skipped:"remote"};if(!t||!String(t).trim())return{ok:!1,skipped:"no-model"};const l=warmSecsFor({warmSecs:o}),i="string"==typeof n?n:"",c={warmSecs:l,prefixSource:i?"turn-system":"none",prefixChars:i.length};if(l<=0)return{ok:!1,skipped:"warm-disabled",...c};const u=fetch,f=residentSecsLeft(a,t,i,{dialer:u});if(f>=Math.min(l,60)){const e=residentEntry(a,t,i,{dialer:u});return{ok:!0,already:!0,memo:!0,remainingSecs:f,contextLength:e&&e.contextLength||null,...c}}const d=new AbortController,_=()=>d.abort();s&&(s.aborted?d.abort():"function"==typeof s.addEventListener&&s.addEventListener("abort",_,{once:!0}));const m=Number(r),p=Number.isFinite(m)&&m>0?Math.min(m,3e5):3e5;let E=!1,g=null;const T=setTimeout(()=>{E=!0,d.abort()},p);T&&"function"==typeof T.unref&&T.unref();try{try{const e=await fetch(`${a}/api/ps`,{method:"GET",signal:d.signal});if(e&&e.ok&&"function"==typeof e.json){const n=await e.json(),s=(n&&n.models||[]).find(e=>sameModel(e&&(e.name||e.model),t));if(s&&Number.isFinite(s.context_length)&&s.context_length>0&&(g=s.context_length),s&&s.expires_at){const e=Math.round((new Date(s.expires_at).getTime()-Date.now())/1e3);if(Number.isFinite(e)&&e>=Math.min(l,60))return residentMemo.set(residentKey(a,t,i),{until:Date.now()+1e3*e,dialer:u,contextLength:g}),{ok:!0,already:!0,remainingSecs:e,contextLength:g,...c}}}}catch{}if(d.signal.aborted)return{ok:!1,aborted:!0,timeout:E,contextLength:g,...c};const e=i?[{role:"system",content:i},{role:"user",content:"PONG"}]:[{role:"user",content:"PONG"}],n=await fetch(`${a}/api/chat`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({model:String(t),keep_alive:l,stream:!1,messages:e,options:{num_predict:1}}),signal:d.signal});let s=null,o=null;if(n&&"function"==typeof n.text){const e=await n.text().catch(()=>"");try{const t=JSON.parse(e);Number.isFinite(t.prompt_eval_count)&&(s=t.prompt_eval_count),Number.isFinite(t.eval_count)&&(o=t.eval_count)}catch{}}return n&&n.ok&&(null==g&&(g=await windowOf(a,t,{signal:d.signal})||null),residentMemo.set(residentKey(a,t,i),{until:Date.now()+1e3*l,dialer:u,contextLength:g}),swapWarmModel(a,t)),{ok:!(!n||!n.ok),status:n&&n.status,pinned:!0,promptTokens:s,outputTokens:o,contextLength:g,...c}}catch(e){return{ok:!1,error:String(e&&e.message||e),timeout:E,contextLength:g,...c}}finally{clearTimeout(T),s&&"function"==typeof s.removeEventListener&&s.removeEventListener("abort",_)}}function stoppedTurn(e,{content:t="",usage:n=null}={}){const s={id:"local",model:String(e),choices:[{index:0,message:{role:"assistant",content:t},finish_reason:"stop"}]};return n&&(s.usage=n),s}function fitToWindowOf({rows:e,system:t,tools:n,contextLength:s,maxTokens:o}){const r=Number(s);if(!Number.isFinite(r)||r<=0)return null;const a=(Array.isArray(e)?e:[]).filter(e=>e&&"system"!==e.role),l=Array.isArray(n)&&n.length?estimateTokens(JSON.stringify(n)):0,i=Number(o),c=Number.isFinite(i)&&i>0?i:Math.round(r/4),u=trimContext({messages:a,system:"string"==typeof t?t:"",budgetTokens:r,reserveTokens:c,fixedTokens:l});return{window:r,reserveTokens:c,toolTokens:l,dropped:u.dropped,messages:u.messages,over:u.estimatedTokens>Math.max(0,r-c),estimatedTokens:u.estimatedTokens}}async function chatOne({baseURL:e=DEFAULT_BASE,model:t,messages:n,system:s,prompt:o,maxTokens:r,temperature:a,tools:l,toolChoice:i,signal:c,onDelta:u,firstByteTimeoutMs:f=3e5,contextLength:d}={}){const _=baseOf(e),m=remoteRefusal(_);if(m)throw m;if(!t||!String(t).trim()){const e=new Error("local: no model selected — pick one from the model list, or type a tag");throw e.status=400,e}const p=[];s&&p.push({role:"system",content:s});for(const e of Array.isArray(n)?n:[]){if(e&&"system"===e.role)continue;const t=normalizeRow(e);t&&p.push(t)}const E="string"==typeof o||Array.isArray(o)?o:"";if(!(""===E||Array.isArray(E)&&0===E.length)){const e=p[p.length-1],t=attachmentsModule.flattenContent(E),n=e?attachmentsModule.flattenContent(e.content):null;e&&"user"===e.role&&n===t||p.push({role:"user",content:E})}if(!p.length){const e=new Error("local: nothing to send — no prompt and no messages");throw e.status=400,e}let g=null;if(null!=d){const e=p[0]&&"system"===p[0].role?p[0]:null;if(g=fitToWindowOf({rows:p,system:e&&e.content||s||"",tools:l,contextLength:d,maxTokens:r}),g){const t=g.messages;p.length=0,e&&p.push(e),p.push(...t)}}const T={model:String(t),messages:p,stream:!0,stream_options:{include_usage:!0},...r?{max_tokens:r}:{},...null!=a?{temperature:a}:{},...l&&l.length?{tools:l}:{},...i?{tool_choice:i}:{}},h=new AbortController;let S=!1;const L=setTimeout(()=>{S=!0,h.abort()},f);L&&"function"==typeof L.unref&&L.unref();const y=()=>h.abort();let M;c&&(c.aborted?h.abort():"function"==typeof c.addEventListener&&c.addEventListener("abort",y,{once:!0}));try{M=await fetch(`${_}/v1/chat/completions`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(T),signal:h.signal})}catch(e){if(S||isHeadersDeadline(e)){const e=S?`sent nothing in ${Math.round(f/1e3)}s`:`sent no response headers before this runtime's own ${Math.round(300)}s deadline`,n=new Error(`local: ${t} ${e} — the daemon is still loading the model, or its prompt prefill is longer than that. \`ollama ps\` shows which; a smaller prompt or a smaller model is the way through.`);throw n.status=0,n.code="timeout",n}if(c&&c.aborted||h.signal.aborted)return stoppedTurn(t);throw e}finally{clearTimeout(L)}if(!M.ok){let e="";try{e=await M.text()}catch{}const t=new Error(`local: chat/completions ${M.status}${e?` — ${e.slice(0,400)}`:""}`);throw t.status=M.status,t}let A="",O=null;const x=[],R=new Map,D=makeDeepSeekEnvelopeStripper(),b=makeTextToolCallStripper({toolNames:(Array.isArray(l)?l:[]).map(e=>e&&e.function&&e.function.name||e&&e.name||"").filter(Boolean)});try{await readSSE(M,e=>{e&&e.usage&&(O=e.usage);const t=e&&Array.isArray(e.choices)?e.choices[0]:null;if(!t)return;const n=t.delta||{};if("string"==typeof n.content&&n.content){const e=b(D(n.content));e&&(A+=e,"function"==typeof u&&u({text:e}))}const s=n.tool_calls||[];for(const e of s){const t=Number.isInteger(e.index)?e.index:x.length;let n=R.get(t);n||(n={id:"",type:"function",function:{name:"",arguments:""}},R.set(t,n)),e.id&&(n.id=e.id),e.type&&(n.type=e.type);const s=e.function||{};s.name&&(n.function.name=s.name),s.arguments&&(n.function.arguments+=s.arguments)}},{idleTimeoutMs:3e5})}catch(e){if(c&&c.aborted)return stoppedTurn(t,{content:A,usage:O});throw e}finally{c&&"function"==typeof c.removeEventListener&&c.removeEventListener("abort",y)}const w=`${b(D.flush())||""}${b.flush()||""}`;w&&(A+=w,"function"==typeof u&&u({text:w}));for(const[e,t]of[...R.entries()].sort((e,t)=>e[0]-t[0]))(t.function.name||t.function.arguments)&&(t.id||(t.id=`call_${e}`),x.push(t));const k={role:"assistant",content:A};x.length&&(k.tool_calls=x);const N=D.calls(),C=b.calls(),v={id:"local",model:String(t),choices:[{index:0,message:k,finish_reason:x.length?"tool_calls":"stop"}],...O?{usage:O}:{}};return(x.length||N.length||C.length)&&(v.toolCalls=[...x.map(e=>({id:e.id,name:e.function.name,args:e.function.arguments})),...N.map(e=>({id:"",name:e.name,args:e.args||{}})),...C.map(e=>({id:"",name:e.name,args:e.args||{}}))],(N.length||C.length)&&"tool_calls"!==v.choices[0].finish_reason&&(v.choices[0].finish_reason="tool_calls")),g&&(v.window={contextLength:g.window,dropped:g.dropped,toolTokens:g.toolTokens,estimatedTokens:g.estimatedTokens,reserveTokens:g.reserveTokens,over:g.over}),v}async function chat(e={}){const t=baseOf(e&&e.baseURL),n=e&&e.model,s=`${t}|${n}`;activeCountByKey.set(s,(activeCountByKey.get(s)||0)+1);try{let o=null;const r=await runSerialized(s,async()=>{o=await ensureResident({baseURL:e&&e.baseURL,model:n,system:e&&e.system,signal:e&&e.signal,warmSecs:e&&e.warmSecs,firstByteTimeoutMs:e&&e.firstByteTimeoutMs});let s=o&&o.contextLength||null;const r=isLocalEndpoint(t)&&""!==String(n||"").trim();return!s&&r&&o&&!0!==o.ok&&!o.skipped&&(s=await windowOf(t,n,{signal:e&&e.signal})||null),chatOne({...e,contextLength:s})});return swapWarmModel(t,n),o&&"object"==typeof r&&r&&(r.residency=o),r}finally{const e=(activeCountByKey.get(s)||1)-1;e<=0?activeCountByKey.delete(s):activeCountByKey.set(s,e)}}module.exports={DEFAULT_BASE:DEFAULT_BASE,DEFAULT_WARM_SECS:1800,RESIDENT_TIMEOUT_MS:3e5,SSE_IDLE_TIMEOUT_MS:3e5,FIRST_BYTE_TIMEOUT_MS:3e5,PROBE_TIMEOUT_MS:1500,baseOf:baseOf,normalizeBase:normalizeBase,isLocalEndpoint:isLocalEndpoint,remoteRefusal:remoteRefusal,probe:probe,listTags:listTags,readSSE:readSSE,chat:chat,ensureResident:ensureResident,residentSecsLeft:residentSecsLeft,residentEntry:residentEntry,unload:unload,unloadAll:unloadAll,makeTextToolCallStripper:makeTextToolCallStripper,makeDeepSeekEnvelopeStripper:makeDeepSeekEnvelopeStripper,textCallsIn:textCallsIn,fitToWindowOf:fitToWindowOf,isHeadersDeadline:isHeadersDeadline,HEADERS_DEADLINE_MS:3e5,windowOf:windowOf,stoppedTurn:stoppedTurn};
|
|
3
|
+
"use strict";const{estimateTokens:estimateTokens,trimContext:trimContext,prefillBudgetTokens:prefillBudgetTokens,LOCAL_PREFILL_TOK_PER_SEC:LOCAL_PREFILL_TOK_PER_SEC}=require("./context.js"),attachmentsModule=require("./attachments.js"),DEFAULT_BASE="http://localhost:11434",SSE_IDLE_TIMEOUT_MS=3e5,FIRST_BYTE_TIMEOUT_MS=3e5,HEADERS_DEADLINE_MS=3e5;function isHeadersDeadline(e){if(!e)return!1;const t=e.cause||e;if(!t)return!1;const n=String(t.code||""),s=String(t.name||"");return"UND_ERR_HEADERS_TIMEOUT"===n||"HeadersTimeoutError"===s}const PROBE_TIMEOUT_MS=1500;function normalizeBase(e){const t=String(null==e?"":e).trim();return t?/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(t)?t:`http://${t}`:DEFAULT_BASE}function baseOf(e){return normalizeBase(e).replace(/\/+$/,"")}const DSML_RE_INVOKE=/<\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call)\b\s*([^>]*?)\s*>([\s\S]*?)<\s*\/\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call)\b\s*>/g,DSML_RE_PARAM=/<\s*|\s*(?:DSML\s*)?|\s*(?:parameter|param|arg)\b\s*([^>]*?)\s*>([\s\S]*?)<\s*\/\s*|\s*(?:DSML\s*)?|\s*(?:parameter|param|arg)\b\s*>/g,DSML_RE_LEADER=/<\s*\/?\s*|\s*(?:DSML\s*)?|\s*(?:(?:tool|function)[_▁ ]*calls?|reasoning)[_▁ ]*(?:begin|end)?\s*>/gi,DSML_RE_ANY_TAG=/<\s*\/?\s*|\s*(?:DSML\s*)?|\s*[A-Za-z_][A-Za-z0-9_]*[^>]{0,120}>/g,DSML_RE_SKELETON=/<\s*\/?\s*(?:tool_calls|function_calls|invoke|parameter|param|reasoning)\b[^>]{0,120}>/gi,DSML_RE_JSON_CALLS=/|[ \t]*(?:tool|function)[_▁ ]*calls?[_▁ ]*begin[ \t]*|([\s\S]*?)|[ \t]*(?:tool|function)[_▁ ]*calls?[_▁ ]*end[ \t]*|/gi,DSML_RE_JSON_CALLS_OPEN=/|[ \t]*(?:tool|function)[_▁ ]*calls?[_▁ ]*begin[ \t]*|/gi,DSML_RE_JSON_CALLS_CLOSE=/|[ \t]*(?:tool|function)[_▁ ]*calls?[_▁ ]*end[ \t]*|/gi,DSML_RE_ENVELOPE_TOKEN=/|[ \t]?[A-Za-z0-9_▁]*[ \t]?|/g,DSML_RE_DRIFT_INVOKE=/<\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call)\b\s*([^>]*?)\s*>/gi,DSML_RE_DRIFT_PARAM=/<\s*|\s*(?:DSML\s*)?|\s*(?:parameter|param|arg)\b\s*([^>]*?)\s*>/gi,DSML_RE_PARAM_CLOSE=/<\s*\/\s*|\s*(?:DSML\s*)?|\s*(?:parameter|param|arg)\b\s*>/gi,DSML_RE_ATTR=/([A-Za-z_][A-Za-z0-9_.-]*)\s*=\s*(?:"([^"]*)"|'([^']*)')/g,DSML_RE_STRUCT_TAG=/<\s*\/?\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call|parameter|param|arg|reasoning|(?:tool|function)[_▁ ]*calls?)\b/gi,DSML_RE_STRUCT_CLOSER=/<\s*\/\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call|parameter|param|arg|reasoning|(?:tool|function)[_▁ ]*calls?)\b/gi,DSML_RE_WRAPPER_TAG=/<\s*\/?\s*|\s*(?:DSML\s*)?|\s*(?!(?:invoke|call|tool_call|parameter|param|arg)\b)[A-Za-z_][A-Za-z0-9_]*[^>]{0,120}>/g,DSML_RE_TRAILING_LT=/<\s*\/?\s*$/,DSML_RE_OPEN_TOKEN=/^|[ \t]?[A-Za-z0-9_▁]*[ \t]?$/,DSML_HOLD_MAX=4194304;function dsmlAttrs(e){const t={};if(!e)return t;let n;for(DSML_RE_ATTR.lastIndex=0;n=DSML_RE_ATTR.exec(e);)t[n[1].toLowerCase()]=null!=n[2]?n[2]:n[3];return t}function dsmlJson(e){const t=String(null==e?"":e).trim();try{const e=JSON.parse(t);return void 0===e?t:e}catch{return t}}function dsmlArgs(e){const t={};let n;for(DSML_RE_PARAM.lastIndex=0;n=DSML_RE_PARAM.exec(e);){const e=dsmlAttrs(n[1]),s=e.name||e.key||`arg${Object.keys(t).length}`,o="false"===String(e.string||"").toLowerCase()||"true"===String(e.json||"").toLowerCase();t[s]=o?dsmlJson(n[2]):n[2]}return t}function decodeDeepSeekDSML(e){if("string"!=typeof e||!e||-1===e.indexOf("|"))return{text:e||"",calls:[]};const t=[];let n=e;DSML_RE_INVOKE.lastIndex=0;const s=[];let o;for(;o=DSML_RE_INVOKE.exec(n);){const e=dsmlAttrs(o[1]),n=e.name||e.function||e.tool||"";n&&t.push({name:n,args:dsmlArgs(o[2])}),s.push([o.index,o.index+o[0].length])}for(let e=s.length-1;e>=0;e--)n=n.slice(0,s[e][0])+n.slice(s[e][1]);return n=n.replace(DSML_RE_JSON_CALLS,(e,n)=>{const s=dsmlJson(n),o=Array.isArray(s)?s:s&&Array.isArray(s.tool_calls)?s.tool_calls:[];for(const e of o){const n=e&&e.function||e||{},s=n.name||e&&e.name||"";if(!s)continue;let o=null!=n.arguments?n.arguments:e&&e.arguments;"string"==typeof o&&(o=dsmlJson(o)),t.push({name:s,args:o&&"object"==typeof o?o:{}})}return""}),n=n.replace(DSML_RE_LEADER,""),{text:n,calls:t}}function decodeDeepSeekDSMLDrift(e){if("string"!=typeof e||!e||-1===e.indexOf("|"))return{text:e||"",calls:[]};const t=[];let n;for(DSML_RE_DRIFT_INVOKE.lastIndex=0;n=DSML_RE_DRIFT_INVOKE.exec(e);)t.push({at:n.index,attrs:n[1],body:DSML_RE_DRIFT_INVOKE.lastIndex});if(!t.length)return{text:e,calls:[]};const s=[];let o="",r=0;for(let n=0;n<t.length;n++){const l=n+1<t.length?t[n+1].at:e.length,i=e.slice(t[n].body,l),a=dsmlAttrs(t[n].attrs),c=a.name||a.function||a.tool||"",u={},d=[];let f;for(DSML_RE_DRIFT_PARAM.lastIndex=0;f=DSML_RE_DRIFT_PARAM.exec(i);)d.push({at:f.index,attrs:f[1],from:DSML_RE_DRIFT_PARAM.lastIndex});for(let e=0;e<d.length;e++){const t=e+1<d.length?d[e+1].at:i.length,n=i.slice(d[e].from,t).replace(DSML_RE_PARAM_CLOSE,""),s=dsmlAttrs(d[e].attrs),o=s.name||s.key||`arg${Object.keys(u).length}`,r="false"===String(s.string||"").toLowerCase();u[o]=r?dsmlJson(n):n}o+=e.slice(r,t[n].at),r=l,c&&s.push({name:c,args:u})}return o+=e.slice(r),{text:o,calls:s}}function dsmlResidue(e){return e?-1===e.indexOf("|")?e.replace(DSML_RE_SKELETON,""):e.replace(DSML_RE_ANY_TAG,"").replace(DSML_RE_SKELETON,"").replace(DSML_RE_ENVELOPE_TOKEN,""):e}function dsmlUnterminated(e){return!!DSML_RE_OPEN_TOKEN.test(e)||(e.match(DSML_RE_STRUCT_TAG)||[]).length>(e.match(DSML_RE_STRUCT_CLOSER)||[]).length}function dsmlHoldFrom(e){const t=e.search(/<\s*\/?\s*|/);if(-1!==t)return t;const n=e.search(DSML_RE_JSON_CALLS_OPEN);if(-1!==n&&-1===e.slice(n).search(DSML_RE_JSON_CALLS_CLOSE))return n;const s=DSML_RE_TRAILING_LT.exec(e);if(s)return s.index;const o=e.indexOf("|");return-1!==o&&dsmlUnterminated(e.slice(o))?o:-1}function decodePlainToolCallTags(e,t){if(!e||-1===e.indexOf("<"))return e;let n="",s=0;for(;;){const o=TEXT_TOOL_TAG_OPEN_RE.exec(e.slice(s));if(!o)break;const r=s+o.index,l=o[0];if(l.includes(DSML_TAG_MARK)){n+=e.slice(s,r+l.length),s=r+l.length;continue}const i=e.slice(r+l.length),a=TEXT_TOOL_TAG_CLOSE_RE.exec(i);if(!a)break;const c=textCallsIn(i.slice(0,a.index));if(n+=e.slice(s,r),s=r+l.length+a.index+a[0].length,c.length)for(const e of c)t.push(e);else n+=e.slice(r,s)}return n+e.slice(s)}function plainToolTagHoldAt(e){if(!e||-1===e.indexOf("<"))return-1;let t=0;for(;;){const n=TEXT_TOOL_TAG_OPEN_RE.exec(e.slice(t));if(!n)return-1;const s=t+n.index;if(n[0].includes(DSML_TAG_MARK)){t=s+n[0].length;continue}const o=e.slice(s+n[0].length);return TEXT_TOOL_TAG_CLOSE_RE.test(o)?-1:s}}function makeDeepSeekEnvelopeStripper(){let e="";const t=[],n=e=>dsmlResidue(decodePlainToolCallTags(e,t)),s=s=>{e+="string"==typeof s?s:"";const o=decodeDeepSeekDSML(e);e=o.text;for(const e of o.calls)t.push(e);e=e.replace(DSML_RE_WRAPPER_TAG,"");const r=dsmlHoldFrom(e);let l;-1!==r&&e.length-r<=4194304?(l=e.slice(0,r),e=e.slice(r)):(l=e,e="");const i=plainToolTagHoldAt(l);return-1!==i&&(e=l.slice(i)+e,l=l.slice(0,i)),n(l)};return s.flush=()=>{const s=decodeDeepSeekDSML(e);e="";for(const e of s.calls)t.push(e);const o=decodeDeepSeekDSMLDrift(s.text);for(const e of o.calls)t.push(e);return n(o.text)},s.calls=()=>t.slice(),s}const TEXT_TOOL_TAG_OPEN_RE=/<\s*tool_calls?\b[^>]{0,80}>/i,TEXT_TOOL_TAG_CLOSE_RE=/<\s*\/\s*tool_calls?\s*>/i,TEXT_FENCE_RE=/```[ \t]*[A-Za-z0-9_+-]*[ \t]*\n?([\s\S]*?)```/,TEXT_FENCE_OPEN_RE=/```[ \t]*[A-Za-z0-9_+-]*[ \t]*\n?/,DSML_TAG_MARK="|";function asTextToolCall(e){if(!e||"object"!=typeof e)return null;let t=e;t.function&&"object"==typeof t.function&&(t={...t.function,name:t.function.name||t.name});const n=t.name||t.tool||t.tool_name||t.function_name,s="string"==typeof n?n.trim():"";if(!s)return null;let o=null!=t.arguments?t.arguments:null!=t.parameters?t.parameters:null!=t.args?t.args:null!=t.tool_input?t.tool_input:{};if("string"==typeof o){const e=o.trim()?safeJson(o):{};o=e&&"object"==typeof e?e:{}}return null!=o&&"object"==typeof o||(o={}),{name:s,args:o}}function safeJson(e){try{return JSON.parse(e)}catch{return null}}function textCallsIn(e){const t=String(e||"").trim().replace(/^json\s*/i,"").trim();if(!t)return[];const n=safeJson(t);if(!n)return[];const s=Array.isArray(n)?n:[n],o=[];for(const e of s){const t=asTextToolCall(e);t&&o.push(t)}return o}function nextTextToolEnvelope(e){const t=TEXT_FENCE_RE.exec(e);if(t)return{start:t.index,end:t.index+t[0].length,complete:!0,raw:t[0],body:t[1]};const n=TEXT_FENCE_OPEN_RE.exec(e);return n?{start:n.index,end:e.length,complete:!1,body:e.slice(n.index+n[0].length)}:null}function trailingHeadFrom(e,t=!1){if(!e)return-1;const n=e.search(TEXT_TOOL_HEAD_RE);if(-1!==n)return n;const s=/`{1,2}$/.exec(e);if(s)return s.index;const o=e.lastIndexOf("<");if(-1!==o&&couldBeTextToolHead(e.slice(o)))return o;if(t){const t=e.lastIndexOf("{");if(-1!==t&&/^\{\s*(?:"[^"]*"\s*:[\s\S]*|"[^"]*"?\s*|)$/.test(e.slice(t)))return t}return-1}function couldBeTextToolHead(e){const t=e.replace(/^[\s\uFEFF]+/,"");if(!t)return!0;if(t.length<=3&&"```".startsWith(t))return!0;if(t.startsWith("<")&&!TEXT_TOOL_HEAD_RE.test(t)){const e=t.slice(1).replace(/^\/?\s*/,"").toLowerCase();if(e.length<=10&&/^[a-z_]*$/.test(e))return"tool_call".startsWith(e)||"tool_calls".startsWith(e)}return!1}function balancedJsonEnd(e,t){let n=0,s=!1,o=!1;for(let r=t;r<e.length;r++){const t=e[r];if(s)o?o=!1:"\\"===t?o=!0:'"'===t&&(s=!1);else if('"'===t)s=!0;else if("{"===t||"["===t)n++;else if(("}"===t||"]"===t)&&(n--,n<=0))return r+1}return-1}function makeTextToolCallStripper({toolNames:e=null}={}){const t=e?new Set([...e].map(e=>String(e))):null;let n="";const s=[],o=e=>Boolean(e.length)&&(!t||e.every(e=>t.has(e.name))),r=(e,t)=>{const n=textCallsIn(t);if(!o(n))return e;for(const e of n)s.push(e);return""},l=e=>{n+="string"==typeof e?e:"";let l="",i=!1;for(;;){const e=nextTextToolEnvelope(n);if(e){if(l+=n.slice(0,e.start),n=n.slice(e.start),!e.complete){i=!0;break}l+=r(e.raw,e.body),n=n.slice(e.raw.length);continue}const a=TEXT_TOOL_TAG_OPEN_RE.exec(n);if(a){l+=n.slice(0,a.index),n=n.slice(a.index);const e=n.slice(a[0].length),t=TEXT_TOOL_TAG_CLOSE_RE.exec(e);if(!t){i=!0;break}const s=n.slice(0,a[0].length+t.index+t[0].length);l+=r(s,e.slice(0,t.index)),n=n.slice(s.length);continue}const c=t?/\{\s*"/.exec(n):null;if(!c)break;const u=balancedJsonEnd(n,c.index),d=n.slice(0,c.index);if(-1===u){l+=d,n=n.slice(c.index),i=!0;break}const f=textCallsIn(n.slice(c.index,u));if(l+=d,o(f))for(const e of f)s.push(e);else l+=n.slice(c.index,u);n=n.slice(u)}const a=i?0:trailingHeadFrom(n,Boolean(t));return-1===a?(l+=n,n=""):a>0&&(l+=n.slice(0,a),n=n.slice(a)),n.length>TEXT_TOOL_HOLD_MAX&&(l+=n,n=""),l};return l.flush=()=>{const e=n;if(n="",!e)return"";const s=nextTextToolEnvelope(e);if(s)return e.slice(0,s.start)+r(e.slice(s.start),s.body);const o=TEXT_TOOL_TAG_OPEN_RE.exec(e);if(!o){const n=t?/\{\s*"/.exec(e):null;if(!n)return e;const s=balancedJsonEnd(e,n.index);return-1===s?e:e.slice(0,n.index)+r(e.slice(n.index,s),e.slice(n.index,s))+e.slice(s)}const l=e.slice(o.index+o[0].length).replace(TEXT_TOOL_TAG_CLOSE_RE,"");return e.slice(0,o.index)+r(e.slice(o.index),l)},l.calls=()=>s.slice(),l}const TEXT_TOOL_HEAD_RE=/```|<\s*tool_calls?\b/i,TEXT_TOOL_HOLD_MAX=65536;function isLocalEndpoint(e){let t="",n="";if(""===String(null==e?"":e).trim())return!1;try{const s=new URL(normalizeBase(e));t=s.hostname.toLowerCase(),n=s.protocol.toLowerCase()}catch{return!1}if("http:"!==n&&"https:"!==n)return!1;if(!t)return!1;if(t.startsWith("[")&&t.endsWith("]")&&(t=t.slice(1,-1)),!t||/[\s/\\@]/.test(t))return!1;if("localhost"===t||t.endsWith(".localhost"))return!0;if(/\.(local|internal|lan)$/.test(t))return!0;if(t.includes(":"))return"::1"===t||"0:0:0:0:0:0:0:1"===t||!!/^f[cd][0-9a-f]{2}:/.test(t)||!!/^fe[89ab][0-9a-f]:/.test(t);const s=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(t);if(s){const e=s.slice(1).map(Number);if(e.some(e=>e>255))return!1;const[t,n]=e;return 127===t||10===t||172===t&&n>=16&&n<=31||192===t&&168===n||169===t&&254===n}return!t.includes(".")}function remoteRefusal(e){if(isLocalEndpoint(e))return null;const t=new Error(`local: ${JSON.stringify(String(e||""))} is not on this machine, so it is not the local class. Running a model you own is free because there is no vendor to pay — a remote URL here would be an unpaid turn instead. Use the aegis or byok class for remote models.`);return t.status=400,t}async function probe(e=DEFAULT_BASE){const t=baseOf(e);try{return{running:(await fetch(`${t}/api/tags`,{signal:AbortSignal.timeout(1500)})).ok,baseURL:t}}catch{return{running:!1,baseURL:t}}}async function listTags(e=DEFAULT_BASE){const t=await fetch(`${baseOf(e)}/api/tags`);if(!t.ok){const e=new Error(`local: /api/tags answered ${t.status}`);throw e.status=t.status,e}const n=await t.json();return(n&&n.models||[]).map(e=>({id:e&&e.name,...e&&e.details?{details:e.details}:{}})).filter(e=>e.id)}const UNLOAD_TIMEOUT_MS=4e3,RESIDENT_TIMEOUT_MS=3e5,DEFAULT_WARM_SECS=1800;async function unload(e,t){if(!t)return{ok:!1};const n=baseOf(e);if(!isLocalEndpoint(n))return{ok:!1};try{return{ok:(await fetch(`${n}/api/chat`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({model:String(t),messages:[],stream:!1,keep_alive:0}),signal:AbortSignal.timeout(4e3)})).ok}}catch{return{ok:!1}}}function normalizeRow(e){if(!e||"object"!=typeof e)return null;const t={role:e.role||"user"};return null!=e.content&&(t.content=e.content),e.name&&(t.name=e.name),e.tool_call_id&&(t.tool_call_id=e.tool_call_id),Array.isArray(e.tool_calls)&&e.tool_calls.length&&(t.tool_calls=e.tool_calls),t}function parseEvent(e){const t=String(e).split("\n");let n="",s=!1;for(const e of t){if(!e||e.startsWith(":"))continue;const t=e.indexOf(":"),o=-1===t?e:e.slice(0,t),r=-1===t?"":e.slice(t+1).replace(/^ /,"");"data"===o?(n+=r,s=!0):"event"!==o&&"id"!==o&&"retry"!==o||(s=!0)}if(!s||!n)return null;if("[DONE]"===n)return{done:!0};try{return{json:JSON.parse(n)}}catch{return null}}async function readSSE(e,t,{idleTimeoutMs:n=3e5}={}){const s=e.body.getReader(),o=new TextDecoder;let r="",l=null,i=()=>{};const a=new Promise((e,t)=>{i=t}),c=()=>{l&&clearTimeout(l),l=setTimeout(()=>{i(new Error(`local: the model stopped responding — no output for ${Math.round(n/1e3)}s`))},n)};c();try{for(;;){const e=await Promise.race([s.read(),a]);if(e.done)break;let n;for(r+=o.decode(e.value,{stream:!0}),r=r.replace(/\r\n/g,"\n");(n=r.indexOf("\n\n"))>=0;){const e=r.slice(0,n);r=r.slice(n+2);const s=parseEvent(e);if(s){if(s.done)return;s.json&&(c(),t(s.json))}}}}finally{l&&clearTimeout(l);try{await s.cancel()}catch{}}}const localCallQueues=new Map;function runSerialized(e,t){const n=(localCallQueues.get(e)||Promise.resolve()).then(t,t);return localCallQueues.set(e,n.then(()=>{},()=>{})),n}const activeCountByKey=new Map,warmModelByBase=new Map;function swapWarmModel(e,t){if(!t)return;const n=warmModelByBase.get(e);warmModelByBase.set(e,t),n&&n!==t&&(activeCountByKey.get(`${e}|${n}`)||unload(e,n).catch(()=>{}))}async function unloadAll(){const e=[...warmModelByBase.entries()];warmModelByBase.clear(),await Promise.all(e.map(([e,t])=>unload(e,t)))}function warmSecsFor({warmSecs:e}={}){const t=Number(e);if(Number.isFinite(t)&&t>=0)return Math.floor(t);const n=Number(process.env&&process.env.AEGIS_LOCAL_WARM_SECS);return Number.isFinite(n)&&n>=0?Math.floor(n):1800}const residentMemo=new Map;function residentKey(e,t,n){return`${e}\0${t}\0${n}`}function residentSecsLeft(e,t,n,{dialer:s=fetch,now:o=Date.now()}={}){const r=residentMemo.get(residentKey(e,t,n));if(!r||r.dialer!==s)return 0;const l=Math.round((r.until-o)/1e3);return l<=0?(residentMemo.delete(residentKey(e,t,n)),0):l}function residentEntry(e,t,n,{dialer:s=fetch,now:o=Date.now()}={}){const r=residentMemo.get(residentKey(e,t,n));return r&&r.dialer===s&&r.until-o>0?r:null}function sameModel(e,t){const n=String(e||""),s=String(t||"");return!(!n||!s)&&(n===s||n.startsWith(`${s}:`)||n.startsWith(`${s}@`))}const WINDOW_TIMEOUT_MS=3e3;async function windowOf(e,t,{signal:n}={}){const s=new AbortController,o=()=>s.abort();if(n){if(n.aborted)return null;"function"==typeof n.addEventListener&&n.addEventListener("abort",o,{once:!0})}const r=setTimeout(()=>s.abort(),3e3);r&&"function"==typeof r.unref&&r.unref();try{const n=await fetch(`${e}/api/ps`,{method:"GET",signal:s.signal});if(!n||!n.ok||"function"!=typeof n.json)return null;const o=await n.json(),r=(o&&o.models||[]).find(e=>sameModel(e&&(e.name||e.model),t)),l=r&&Number(r.context_length);return Number.isFinite(l)&&l>0?l:null}catch{return null}finally{clearTimeout(r),n&&"function"==typeof n.removeEventListener&&n.removeEventListener("abort",o)}}async function ensureResident({baseURL:e=DEFAULT_BASE,model:t,system:n="",signal:s,warmSecs:o,firstByteTimeoutMs:r}={}){const l=baseOf(e);if(!isLocalEndpoint(l))return{ok:!1,skipped:"remote"};if(!t||!String(t).trim())return{ok:!1,skipped:"no-model"};const i=warmSecsFor({warmSecs:o}),a="string"==typeof n?n:"",c={warmSecs:i,prefixSource:a?"turn-system":"none",prefixChars:a.length};if(i<=0)return{ok:!1,skipped:"warm-disabled",...c};const u=fetch,d=residentSecsLeft(l,t,a,{dialer:u});if(d>=Math.min(i,60)){const e=residentEntry(l,t,a,{dialer:u});return{ok:!0,already:!0,memo:!0,remainingSecs:d,contextLength:e&&e.contextLength||null,...c}}const f=new AbortController,_=()=>f.abort();s&&(s.aborted?f.abort():"function"==typeof s.addEventListener&&s.addEventListener("abort",_,{once:!0}));const m=Number(r),p=Number.isFinite(m)&&m>0?Math.min(m,3e5):3e5;let E=!1,g=null;const T=setTimeout(()=>{E=!0,f.abort()},p);T&&"function"==typeof T.unref&&T.unref();try{try{const e=await fetch(`${l}/api/ps`,{method:"GET",signal:f.signal});if(e&&e.ok&&"function"==typeof e.json){const n=await e.json(),s=(n&&n.models||[]).find(e=>sameModel(e&&(e.name||e.model),t));if(s&&Number.isFinite(s.context_length)&&s.context_length>0&&(g=s.context_length),s&&s.expires_at){const e=Math.round((new Date(s.expires_at).getTime()-Date.now())/1e3);if(Number.isFinite(e)&&e>=Math.min(i,60))return residentMemo.set(residentKey(l,t,a),{until:Date.now()+1e3*e,dialer:u,contextLength:g}),{ok:!0,already:!0,remainingSecs:e,contextLength:g,...c}}}}catch{}if(f.signal.aborted)return{ok:!1,aborted:!0,timeout:E,contextLength:g,...c};const e=a?[{role:"system",content:a},{role:"user",content:"PONG"}]:[{role:"user",content:"PONG"}],n=await fetch(`${l}/api/chat`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({model:String(t),keep_alive:i,stream:!1,messages:e,options:{num_predict:1}}),signal:f.signal});let s=null,o=null;if(n&&"function"==typeof n.text){const e=await n.text().catch(()=>"");try{const t=JSON.parse(e);Number.isFinite(t.prompt_eval_count)&&(s=t.prompt_eval_count),Number.isFinite(t.eval_count)&&(o=t.eval_count)}catch{}}return n&&n.ok&&(null==g&&(g=await windowOf(l,t,{signal:f.signal})||null),residentMemo.set(residentKey(l,t,a),{until:Date.now()+1e3*i,dialer:u,contextLength:g}),swapWarmModel(l,t)),{ok:!(!n||!n.ok),status:n&&n.status,pinned:!0,promptTokens:s,outputTokens:o,contextLength:g,...c}}catch(e){return{ok:!1,error:String(e&&e.message||e),timeout:E,contextLength:g,...c}}finally{clearTimeout(T),s&&"function"==typeof s.removeEventListener&&s.removeEventListener("abort",_)}}function stoppedTurn(e,{content:t="",usage:n=null}={}){const s={id:"local",model:String(e),choices:[{index:0,message:{role:"assistant",content:t},finish_reason:"stop"}]};return n&&(s.usage=n),s}function fitToWindowOf({rows:e,system:t,tools:n,contextLength:s,maxTokens:o,budgetSecs:r,tokPerSec:l}){const i=Number(s);if(!Number.isFinite(i)||i<=0)return null;const a=Number(r),c=Number(l)>0?Number(l):LOCAL_PREFILL_TOK_PER_SEC,u=Number.isFinite(a)&&a>0?prefillBudgetTokens(a,{tokPerSec:c,windowTokens:i}):null,d=null==u?i:Math.min(i,u),f=(Array.isArray(e)?e:[]).filter(e=>e&&"system"!==e.role),_=Array.isArray(n)&&n.length?estimateTokens(JSON.stringify(n)):0,m=Number(o),p=Number.isFinite(m)&&m>0?m:Math.round(i/4),E=trimContext({messages:f,system:"string"==typeof t?t:"",budgetTokens:d,reserveTokens:p,fixedTokens:_});return{window:i,reserveTokens:p,toolTokens:_,dropped:E.dropped,messages:E.messages,over:E.estimatedTokens>Math.max(0,d-p),estimatedTokens:E.estimatedTokens,budgetTokens:d,prefillSecs:null==u?null:Math.round(E.estimatedTokens/c*10)/10,tokPerSec:null==u?null:c}}async function chatOne({baseURL:e=DEFAULT_BASE,model:t,messages:n,system:s,prompt:o,maxTokens:r,temperature:l,tools:i,toolChoice:a,signal:c,onDelta:u,firstByteTimeoutMs:d=3e5,contextLength:f,budgetSecs:_,tokPerSec:m}={}){const p=baseOf(e),E=remoteRefusal(p);if(E)throw E;if(!t||!String(t).trim()){const e=new Error("local: no model selected — pick one from the model list, or type a tag");throw e.status=400,e}const g=[];s&&g.push({role:"system",content:s});for(const e of Array.isArray(n)?n:[]){if(e&&"system"===e.role)continue;const t=normalizeRow(e);t&&g.push(t)}const T="string"==typeof o||Array.isArray(o)?o:"";if(!(""===T||Array.isArray(T)&&0===T.length)){const e=g[g.length-1],t=attachmentsModule.flattenContent(T),n=e?attachmentsModule.flattenContent(e.content):null;e&&"user"===e.role&&n===t||g.push({role:"user",content:T})}if(!g.length){const e=new Error("local: nothing to send — no prompt and no messages");throw e.status=400,e}let S=null;if(null!=f){const e=g[0]&&"system"===g[0].role?g[0]:null;if(S=fitToWindowOf({rows:g,system:e&&e.content||s||"",tools:i,contextLength:f,maxTokens:r,budgetSecs:_,tokPerSec:m}),S){const t=S.messages;g.length=0,e&&g.push(e),g.push(...t)}}const h={model:String(t),messages:g,stream:!0,stream_options:{include_usage:!0},...r?{max_tokens:r}:{},...null!=l?{temperature:l}:{},...i&&i.length?{tools:i}:{},...a?{tool_choice:a}:{}},L=new AbortController;let y=!1;const M=setTimeout(()=>{y=!0,L.abort()},d);M&&"function"==typeof M.unref&&M.unref();const A=()=>L.abort();let O;c&&(c.aborted?L.abort():"function"==typeof c.addEventListener&&c.addEventListener("abort",A,{once:!0}));try{O=await fetch(`${p}/v1/chat/completions`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(h),signal:L.signal})}catch(e){if(y||isHeadersDeadline(e)){const e=y?`sent nothing in ${Math.round(d/1e3)}s`:`sent no response headers before this runtime's own ${Math.round(300)}s deadline`,n=new Error(`local: ${t} ${e} — the daemon is still loading the model, or its prompt prefill is longer than that. \`ollama ps\` shows which; a smaller prompt or a smaller model is the way through.`);throw n.status=0,n.code="timeout",n}if(c&&c.aborted||L.signal.aborted)return stoppedTurn(t);throw e}finally{clearTimeout(M)}if(!O.ok){let e="";try{e=await O.text()}catch{}const t=new Error(`local: chat/completions ${O.status}${e?` — ${e.slice(0,400)}`:""}`);throw t.status=O.status,t}let R="",x=null;const D=[],b=new Map,w=makeDeepSeekEnvelopeStripper(),k=makeTextToolCallStripper({toolNames:(Array.isArray(i)?i:[]).map(e=>e&&e.function&&e.function.name||e&&e.name||"").filter(Boolean)});try{await readSSE(O,e=>{e&&e.usage&&(x=e.usage);const t=e&&Array.isArray(e.choices)?e.choices[0]:null;if(!t)return;const n=t.delta||{};if("string"==typeof n.content&&n.content){const e=k(w(n.content));e&&(R+=e,"function"==typeof u&&u({text:e}))}const s=n.tool_calls||[];for(const e of s){const t=Number.isInteger(e.index)?e.index:D.length;let n=b.get(t);n||(n={id:"",type:"function",function:{name:"",arguments:""}},b.set(t,n)),e.id&&(n.id=e.id),e.type&&(n.type=e.type);const s=e.function||{};s.name&&(n.function.name=s.name),s.arguments&&(n.function.arguments+=s.arguments)}},{idleTimeoutMs:3e5})}catch(e){if(c&&c.aborted)return stoppedTurn(t,{content:R,usage:x});throw e}finally{c&&"function"==typeof c.removeEventListener&&c.removeEventListener("abort",A)}const N=`${k(w.flush())||""}${k.flush()||""}`;N&&(R+=N,"function"==typeof u&&u({text:N}));for(const[e,t]of[...b.entries()].sort((e,t)=>e[0]-t[0]))(t.function.name||t.function.arguments)&&(t.id||(t.id=`call_${e}`),D.push(t));const C={role:"assistant",content:R};D.length&&(C.tool_calls=D);const v=w.calls(),I=k.calls(),P={id:"local",model:String(t),choices:[{index:0,message:C,finish_reason:D.length?"tool_calls":"stop"}],...x?{usage:x}:{}};return(D.length||v.length||I.length)&&(P.toolCalls=[...D.map(e=>({id:e.id,name:e.function.name,args:e.function.arguments})),...v.map(e=>({id:"",name:e.name,args:e.args||{}})),...I.map(e=>({id:"",name:e.name,args:e.args||{}}))],(v.length||I.length)&&"tool_calls"!==P.choices[0].finish_reason&&(P.choices[0].finish_reason="tool_calls")),S&&(P.window={contextLength:S.window,dropped:S.dropped,toolTokens:S.toolTokens,estimatedTokens:S.estimatedTokens,reserveTokens:S.reserveTokens,over:S.over}),P}async function chat(e={}){const t=baseOf(e&&e.baseURL),n=e&&e.model,s=`${t}|${n}`;activeCountByKey.set(s,(activeCountByKey.get(s)||0)+1);try{let o=null;const r=await runSerialized(s,async()=>{o=await ensureResident({baseURL:e&&e.baseURL,model:n,system:e&&e.system,signal:e&&e.signal,warmSecs:e&&e.warmSecs,firstByteTimeoutMs:e&&e.firstByteTimeoutMs});let s=o&&o.contextLength||null;const r=isLocalEndpoint(t)&&""!==String(n||"").trim();return!s&&r&&o&&!0!==o.ok&&!o.skipped&&(s=await windowOf(t,n,{signal:e&&e.signal})||null),chatOne({...e,contextLength:s})});return swapWarmModel(t,n),o&&"object"==typeof r&&r&&(r.residency=o),r}finally{const e=(activeCountByKey.get(s)||1)-1;e<=0?activeCountByKey.delete(s):activeCountByKey.set(s,e)}}module.exports={DEFAULT_BASE:DEFAULT_BASE,DEFAULT_WARM_SECS:1800,RESIDENT_TIMEOUT_MS:3e5,SSE_IDLE_TIMEOUT_MS:3e5,FIRST_BYTE_TIMEOUT_MS:3e5,PROBE_TIMEOUT_MS:1500,baseOf:baseOf,normalizeBase:normalizeBase,isLocalEndpoint:isLocalEndpoint,remoteRefusal:remoteRefusal,probe:probe,listTags:listTags,readSSE:readSSE,chat:chat,ensureResident:ensureResident,residentSecsLeft:residentSecsLeft,residentEntry:residentEntry,unload:unload,unloadAll:unloadAll,makeTextToolCallStripper:makeTextToolCallStripper,makeDeepSeekEnvelopeStripper:makeDeepSeekEnvelopeStripper,textCallsIn:textCallsIn,fitToWindowOf:fitToWindowOf,isHeadersDeadline:isHeadersDeadline,HEADERS_DEADLINE_MS:3e5,windowOf:windowOf,stoppedTurn:stoppedTurn};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
2
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
-
"use strict";const MAIN_CHAT_PROMPT='You are Aegiscodex, a terminal coding assistant working in the user\'s repository: read and reason about code, write and edit files, run shell commands, investigate bugs. Work rules:\n- Output is billed by the token and is the largest line on the bill, so spend it where it is read. Before a tool call, one short sentence on what you are about to find out. Do NOT restate file contents, diffs, command output or test results the user can already see. Finish with the answer in a few lines — expand only when asked to explain, or when the change\'s correctness depends on a detail the user must check.\n- Batch independent tool calls into ONE turn: read several files, or grep for several patterns, at once, or use one exec command that does the whole job. Every round re-sends the prefix and bills fresh output; one call per round is the expensive shape.\n- Edit in one call, not one hunk per round: editFile takes an `edits` array, so every hunk you already know about for one file goes in a single call. A fix you can see is a fix you can also write without asking the tool anything in between.\n- Run the thing you changed before you call it done. A patch you never executed is a hypothesis; when the repo has a test or repro command, run it (or the narrowest slice of it) and report what it printed. If you cannot run it, say which command you would have run. - Use tools silently. A one-line reason is enough; do not narrate your plan as a story. - Never claim what a tool found or what a command returned before the tool actually runs. Report only the results you really received. - Before starting a fix or feature, check whether they have asked for it before and whether it was delivered: recalled memory, `queue.jsonl`, `PLAN.md`/notes and `git log` — ONE batched command over sources that exist: if the Environment block says this directory has no version control, skip it. If it was resolved before and the problem is back, report how it was resolved and why it regressed, then fix the cause — never re-fix blind as if it were new. If it was never met, say so plainly before starting. - Match the response to the request. A greeting, a question you already know the answer to, or a request for an opinion is answered in plain words with NO tools. Reach for a tool only when the answer depends on something in this repo or on this machine. "hey" is not a task.\n- WHEN THE USER HAS ASKED FOR WORK: act, don\'t just inspect. After at most 2 rounds of reading or exploration, start making changes with writeFile or editFile. Reconnaissance is not progress — implement, then verify. This is about HOW to carry out a task you were given; it is never a reason to invent one. Never write or modify a file the user did not ask you to touch.\n- Zero tolerance for stalling: once the cause is identified and only the edit remains, make it in the same turn. Never end a turn with an empty or no-op response, or a "let me continue"/"I\'ll now…" placeholder when the user says continue — that wastes their turn. This has been flagged as non-compliance before; treat it as a hard rule. - When you have what you need, stop using tools and give a concise, direct answer. Never end a turn with an intention like "Let me check…" — that is not an answer. - When a focused multi-step sub-task can be delegated, use the task tool to spawn a specialist subagent rather than doing it inline. - If the user references a workflow you don\'t recognize, inspect the repo/scripts for that mechanism before acting.',TOOL_LINE="Tools: readFile, writeFile, editFile, listDir, glob, grep, exec, websearch, task. Paths are absolute in the form THIS machine uses (see the Environment block): on win32 that means C:\\Users\\you\\Desktop\\file.txt, not /home/you/Desktop/file.txt or /tmp/file.txt. exec runs in a persistent shell session — cd and exported env vars carry across calls within the turn. websearch reaches the web for facts this repo cannot answer. task spawns a specialist subagent (its own tool loop, same model).";function languageLine(e){if("string"==typeof e)return e.trim();if(!e||"object"!=typeof e)return"";if("string"==typeof e.value&&e.value.trim())return e.value.trim();const t="string"==typeof e.name?e.name.trim():"",n="string"==typeof e.code?e.code.trim():"string"==typeof e.key?e.key.trim():"";return t&&n?`${t} (${n})`:t||n}function environmentPreamble(e={}){const{platform:t,arch:n,homedir:o,desktopdir:r,dataDir:s,locale:a,localeName:i,languages:h,cwd:l,vcs:c,shell:d,shellKind:u,roots:p,appVersion:m,model:f}=e||{},y=[];if(t&&y.push(`platform: ${t}${n?` (${n})`:""}`),a){const e=String(a).split("-")[0].toLowerCase(),t=i?` (${i})`:"";y.push("en"===e?`locale: ${a}${t}`:`locale: ${a}${t} — the user's own machine and account run in this language, so expect requests written in it and answer in the language the user writes to you in. Use this to resolve an otherwise ambiguous request (a bare path, a pasted error, a one-word command) — never to override a request written in another language.`)}const w=(Array.isArray(h)?h:[]).map(e=>languageLine(e)).filter(Boolean);w.length&&y.push(`recorded language evidence from the user's own saved writing: ${w.join("; ")} — the language of the request in front of you always wins; this is evidence, not an instruction to switch`),o&&y.push(`home directory: ${o}`),r&&y.push(`desktop directory: ${r} — use this exact path when the user says "my desktop"; do NOT build it yourself from the home directory`),s&&y.push(`AEGIS data directory: ${s} — the store itself (config, sessions, credentials, queue). Use this exact path; do NOT append it to the home directory yourself, because a dropped separator ("C:\\Users\\you.aegiscode") names a path that does not exist and looks like an empty directory rather than a mistake`),l&&y.push(`working directory: ${l}`),"git"===c?y.push("version control: this directory IS inside a git work tree, so `git log`, `git diff` and `git status` are usable for checking what was already done"):""===c&&y.push("version control: this directory is NOT a git repository and has no history to consult — do NOT run `git log`, `git diff`, `git blame` or `git status`; they fail here and cost a round. Read the files that exist instead"),d&&y.push(`exec shell: ${d}${u?` (${u})`:""}`),f&&y.push(`model: ${f}`),m&&y.push(`aegis one ${m}`);const g=Array.isArray(p)?p.filter(Boolean):[],b=[];y.length&&b.push(y.join("\n")),g.length&&b.push(`repo roots:\n${g.map(e=>` - ${e}`).join("\n")}`);const v=commandDialectLine(t,u);return v&&b.push(v),b.length?`# Environment\n${b.join("\n")}`:""}function commandDialectLine(e,t){return e?"win32"===e?`This is Windows: exec runs ${"powershell"===t?"PowerShell":"a Windows shell"}, so use Windows-native commands — Get-ChildItem/dir, Get-Content/type, Select-String/findstr, where, New-Item -ItemType Directory — NOT ls, cat, grep, mkdir -p, touch or rm -rf, which do not exist here. Separate paths with \\, and never assume /tmp, /usr or /home exist.`:"darwin"===e?"This is macOS: exec runs a POSIX shell and the standard Unix commands are available, but the userland is BSD, not GNU — sed -i needs an argument (sed -i ''), and readlink -f, date -d and sed -r are absent. Prefer portable forms, or python3.":"This is a POSIX host: the standard Unix commands are available in exec.":""}const PROJECT_DOC_NAMES=["AEGIS.md","AGENTS.md","CLAUDE.md"],PROJECT_DOC_MAX_CHARS=8e3;function readProjectDoc(e,t={}){if(!e)return"";let n=t.fs,o=t.path;try{n||(n=require("node:fs")),o||(o=require("node:path"))}catch(e){return""}for(const t of PROJECT_DOC_NAMES){let r;try{const s=o.join(e,t),a=n.statSync(s);if(!a||!a.isFile())continue;r=n.readFileSync(s,"utf8")}catch(e){continue}if("string"!=typeof r)continue;const s=r.trim();if(s)return`# Project instructions (${t})\nThese are this repository's own rules. They outrank the generic work rules above wherever the two disagree, and they are the source for build/test/lint commands — prefer them over re-deriving commands by exploring.\n\n`+(s.length>8e3?s.slice(0,8e3)+`\n\n[${t} truncated at 8000 characters — read the file for the rest]`:s)}return""}function buildSystemPrompt(e={}){const t=[MAIN_CHAT_PROMPT,TOOL_LINE],n="string"==typeof e.projectDoc&&e.projectDoc.trim()?e.projectDoc.trim():readProjectDoc(e.cwd||process.cwd());n&&t.push(n);const o=environmentPreamble(e);return o&&t.push(o),t.join("\n\n")}module.exports={MAIN_CHAT_PROMPT:MAIN_CHAT_PROMPT,TOOL_LINE:TOOL_LINE,PROJECT_DOC_NAMES:PROJECT_DOC_NAMES,PROJECT_DOC_MAX_CHARS:8e3,environmentPreamble:environmentPreamble,commandDialectLine:commandDialectLine,readProjectDoc:readProjectDoc,buildSystemPrompt:buildSystemPrompt};
|
|
3
|
+
"use strict";const MAIN_CHAT_PROMPT='You are Aegiscodex, a terminal coding assistant working in the user\'s repository: read and reason about code, write and edit files, run shell commands, investigate bugs. Work rules:\n- Output is billed by the token and is the largest line on the bill, so spend it where it is read. Before a tool call, one short sentence on what you are about to find out. Do NOT restate file contents, diffs, command output or test results the user can already see. Finish with the answer in a few lines — expand only when asked to explain, or when the change\'s correctness depends on a detail the user must check.\n- Batch independent tool calls into ONE turn: read several files, or grep for several patterns, at once, or use one exec command that does the whole job. Every round re-sends the prefix and bills fresh output; one call per round is the expensive shape.\n- Edit in one call, not one hunk per round: editFile takes an `edits` array, so every hunk you already know about for one file goes in a single call. A fix you can see is a fix you can also write without asking the tool anything in between.\n- Run the thing you changed before you call it done. A patch you never executed is a hypothesis; when the repo has a test or repro command, run it (or the narrowest slice of it) and report what it printed. If you cannot run it, say which command you would have run. - Use tools silently. A one-line reason is enough; do not narrate your plan as a story. - Never claim what a tool found or what a command returned before the tool actually runs. Report only the results you really received. - Before starting a fix or feature, check whether they have asked for it before and whether it was delivered: recalled memory, `queue.jsonl`, `PLAN.md`/notes and `git log` — ONE batched command over sources that exist: if the Environment block says this directory has no version control, skip it. If it was resolved before and the problem is back, report how it was resolved and why it regressed, then fix the cause — never re-fix blind as if it were new. If it was never met, say so plainly before starting. - Match the response to the request. A greeting, a question you already know the answer to, or a request for an opinion is answered in plain words with NO tools. Reach for a tool only when the answer depends on something in this repo or on this machine. "hey" is not a task.\n- WHEN THE USER HAS ASKED FOR WORK: act, don\'t just inspect. After at most 2 rounds of reading or exploration, start making changes with writeFile or editFile. Reconnaissance is not progress — implement, then verify. This is about HOW to carry out a task you were given; it is never a reason to invent one. Never write or modify a file the user did not ask you to touch.\n- Zero tolerance for stalling: once the cause is identified and only the edit remains, make it in the same turn. Never end a turn with an empty or no-op response, or a "let me continue"/"I\'ll now…" placeholder when the user says continue — that wastes their turn. This has been flagged as non-compliance before; treat it as a hard rule. - When you have what you need, stop using tools and give a concise, direct answer. Never end a turn with an intention like "Let me check…" — that is not an answer. - When a focused multi-step sub-task can be delegated, use the task tool to spawn a specialist subagent rather than doing it inline. - If the user references a workflow you don\'t recognize, inspect the repo/scripts for that mechanism before acting.',TOOL_LINE="Tools are listed in your schema. Paths are absolute in the form THIS machine uses (see the Environment block): on win32 that means C:\\Users\\you\\Desktop\\file.txt, not /home/you/Desktop/file.txt or /tmp/file.txt. exec runs in a persistent shell session — cd and exported env vars carry across calls within the turn.",SLIM_TOOL_LINE="Paths are absolute in the form THIS machine uses (see the Environment block): on win32 that means C:\\Users\\you\\Desktop\\file.txt, not /home/you/Desktop/file.txt.";function languageLine(e){if("string"==typeof e)return e.trim();if(!e||"object"!=typeof e)return"";if("string"==typeof e.value&&e.value.trim())return e.value.trim();const t="string"==typeof e.name?e.name.trim():"",n="string"==typeof e.code?e.code.trim():"string"==typeof e.key?e.key.trim():"";return t&&n?`${t} (${n})`:t||n}function environmentPreamble(e={}){const{platform:t,arch:n,homedir:o,desktopdir:r,dataDir:s,locale:a,localeName:i,languages:l,shell:h,shellKind:d,roots:u,appVersion:c}=e||{},m=[];if(t&&m.push(`platform: ${t}${n?` (${n})`:""}`),a){const e=String(a).split("-")[0].toLowerCase(),t=i?` (${i})`:"";m.push("en"===e?`locale: ${a}${t}`:`locale: ${a}${t} — the user's own machine and account run in this language, so expect requests written in it and answer in the language the user writes to you in. Use this to resolve an otherwise ambiguous request (a bare path, a pasted error, a one-word command) — never to override a request written in another language.`)}const p=(Array.isArray(l)?l:[]).map(e=>languageLine(e)).filter(Boolean);p.length&&m.push(`recorded language evidence from the user's own saved writing: ${p.join("; ")} — the language of the request in front of you always wins; this is evidence, not an instruction to switch`),o&&m.push(`home directory: ${o}`),r&&m.push(`desktop directory: ${r} — use this exact path when the user says "my desktop"; do NOT build it yourself from the home directory`),s&&m.push(`AEGIS data directory: ${s} — the store itself (config, sessions, credentials, queue). Use this exact path; do NOT append it to the home directory yourself, because a dropped separator ("C:\\Users\\you.aegiscode") names a path that does not exist and looks like an empty directory rather than a mistake`),h&&m.push(`exec shell: ${h}${d?` (${d})`:""}`),c&&m.push(`aegis one ${c}`);const f=Array.isArray(u)?u.filter(Boolean):[],y=[];m.length&&y.push(m.join("\n")),f.length&&y.push(`repo roots:\n${f.map(e=>` - ${e}`).join("\n")}`);const w=commandDialectLine(t,d);return w&&y.push(w),y.length?`# Environment\n${y.join("\n")}`:""}function volatilePreamble(e={}){const{cwd:t,vcs:n,model:o}=e||{},r=[];return t&&r.push(`working directory: ${t}`),"git"===n?r.push("version control: this directory IS inside a git work tree, so `git log`, `git diff` and `git status` are usable for checking what was already done"):""===n&&r.push("version control: this directory is NOT a git repository and has no history to consult — do NOT run `git log`, `git diff`, `git blame` or `git status`; they fail here and cost a round. Read the files that exist instead"),o&&r.push(`model: ${o}`),r.length?`# Session\n${r.join("\n")}`:""}function commandDialectLine(e,t){return e?"win32"===e?`This is Windows: exec runs ${"powershell"===t?"PowerShell":"a Windows shell"}, so use Windows-native commands — Get-ChildItem/dir, Get-Content/type, Select-String/findstr, where, New-Item -ItemType Directory — NOT ls, cat, grep, mkdir -p, touch or rm -rf, which do not exist here. Separate paths with \\, and never assume /tmp, /usr or /home exist.`:"darwin"===e?"This is macOS: exec runs a POSIX shell and the standard Unix commands are available, but the userland is BSD, not GNU — sed -i needs an argument (sed -i ''), and readlink -f, date -d and sed -r are absent. Prefer portable forms, or python3.":"This is a POSIX host: the standard Unix commands are available in exec.":""}const PROJECT_DOC_NAMES=["AEGIS.md","AGENTS.md","CLAUDE.md"],PROJECT_DOC_MAX_CHARS=8e3;function readProjectDoc(e,t={}){if(!e)return"";let n=t.fs,o=t.path;try{n||(n=require("node:fs")),o||(o=require("node:path"))}catch(e){return""}for(const t of PROJECT_DOC_NAMES){let r;try{const s=o.join(e,t),a=n.statSync(s);if(!a||!a.isFile())continue;r=n.readFileSync(s,"utf8")}catch(e){continue}if("string"!=typeof r)continue;const s=r.trim();if(s)return`# Project instructions (${t})\nThese are this repository's own rules. They outrank the generic work rules above wherever the two disagree, and they are the source for build/test/lint commands — prefer them over re-deriving commands by exploring.\n\n`+(s.length>8e3?s.slice(0,8e3)+`\n\n[${t} truncated at 8000 characters — read the file for the rest]`:s)}return""}const SLIM_CHAT_PROMPT='You are Aegiscodex, a terminal coding assistant in the user\'s repository. Work rules:\n- Match the response to the request. A greeting, a question you already know the answer to, or a request for an opinion is answered in plain words with NO tools. "hey" is not a task. When the user HAS asked for work, act: after at most 2 rounds of reading, start editing. Never write or modify a file the user did not ask you to touch.\n- Batch independent tool calls into ONE turn: several files, or several greps, in one round. Every round re-sends the prefix and bills fresh output.\n- Use tools silently: one short sentence on what you are about to find out, never a narrated plan. Never claim what a tool found before it actually runs.\n- Do NOT restate file contents, diffs, command output or test results the user can already see. Finish with the answer in a few lines.\n- Run the thing you changed before calling it done, or say which command you would run.';function buildSystemPrompt(e={}){const t=e&&"local"===e.class,n=[t?SLIM_CHAT_PROMPT:MAIN_CHAT_PROMPT,t?SLIM_TOOL_LINE:TOOL_LINE],o="string"==typeof e.projectDoc&&e.projectDoc.trim()?e.projectDoc.trim():readProjectDoc(e.cwd||process.cwd());o&&n.push(o);const r=environmentPreamble(e);r&&n.push(r);const s=volatilePreamble(e);return s&&n.push(s),n.join("\n\n")}module.exports={MAIN_CHAT_PROMPT:MAIN_CHAT_PROMPT,SLIM_CHAT_PROMPT:SLIM_CHAT_PROMPT,TOOL_LINE:TOOL_LINE,SLIM_TOOL_LINE:SLIM_TOOL_LINE,PROJECT_DOC_NAMES:PROJECT_DOC_NAMES,PROJECT_DOC_MAX_CHARS:8e3,environmentPreamble:environmentPreamble,volatilePreamble:volatilePreamble,commandDialectLine:commandDialectLine,readProjectDoc:readProjectDoc,buildSystemPrompt:buildSystemPrompt};
|