aegiscode 7.0.35 → 7.0.36
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 +5 -5
- package/package.json +2 -2
- package/src/deps.js +1 -1
- package/vendor/desktop/lib/local/engine.js +1 -1
- package/vendor/desktop/lib/local/integrity.js +1 -1
- package/vendor/desktop/lib/local/prompt.js +1 -1
- package/vendor/desktop/lib/local/tools.js +1 -1
- package/vendor/desktop/lib/settings.js +1 -1
- package/vendor/desktop/main.js +669 -22
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# aegiscode — the terminal host
|
|
2
2
|
|
|
3
|
-
`aegiscode` in your shell — the command-line version of AEGIS
|
|
3
|
+
`aegiscode` in your shell — the command-line version of AEGIS One. The same
|
|
4
4
|
tool surface the Claude Code plugin exposes over MCP, plus a terminal instead of
|
|
5
5
|
an editor — built on the same two shared pieces and no others:
|
|
6
6
|
|
|
@@ -117,9 +117,9 @@ wins**, so a stale file can never shadow `AEGIS_API_KEY=… aegiscode` in CI; an
|
|
|
117
117
|
the loader only ever reads. If the file is group- or world-readable you are told,
|
|
118
118
|
not silently fixed — the 0600 store stays the only secret this repo writes.
|
|
119
119
|
|
|
120
|
-
That one file is shared: the MCP plugin and AEGIS
|
|
120
|
+
That one file is shared: the MCP plugin and AEGIS One read the same store and
|
|
121
121
|
the same `.env`, so signing in here signs you in everywhere (see [One memory,
|
|
122
|
-
shared with AEGIS
|
|
122
|
+
shared with AEGIS One](#one-memory-shared-with-aegis-one)).
|
|
123
123
|
|
|
124
124
|
## Launch options
|
|
125
125
|
|
|
@@ -542,7 +542,7 @@ echo "why is the sky blue" | aegiscode -p -
|
|
|
542
542
|
```
|
|
543
543
|
|
|
544
544
|
`/config` writes through the same split every other surface uses: the keys in
|
|
545
|
-
`SHARED_PREF_KEYS` go to `preferences.json`, the file AEGIS
|
|
545
|
+
`SHARED_PREF_KEYS` go to `preferences.json`, the file AEGIS One's settings
|
|
546
546
|
window reads and writes too, and this shell's own keys (`lastCwd`,
|
|
547
547
|
`updateCheck`) stay in `config.json`. It never writes a file directly, so it
|
|
548
548
|
cannot leave the window and the shell holding two answers to one question.
|
|
@@ -612,7 +612,7 @@ out, not as "sync failed". Imported remote sessions land in the same store
|
|
|
612
612
|
`/resume` reads, and are marked `imported` with estimated token counts — never
|
|
613
613
|
passed off as measured here.
|
|
614
614
|
|
|
615
|
-
## One memory, shared with AEGIS
|
|
615
|
+
## One memory, shared with AEGIS One
|
|
616
616
|
|
|
617
617
|
`~/.aegiscode/` is the data dir for **every** AEGIS host — this CLI, AEGIS
|
|
618
618
|
Desktop and the MCP plugin built on the same account:
|
package/package.json
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "aegiscode",
|
|
3
3
|
"productName": "AEGIS Code",
|
|
4
|
-
"version": "7.0.
|
|
5
|
-
"description": "aegiscode — the command-line version of AEGIS
|
|
4
|
+
"version": "7.0.36",
|
|
5
|
+
"description": "aegiscode — the command-line version of AEGIS One. The shared tool surface in your shell, over the same thin transport and tool registry as the MCP plugin and the desktop app. Ships transport + UI only; no brain.",
|
|
6
6
|
"author": {
|
|
7
7
|
"name": "AEGIS Code",
|
|
8
8
|
"email": "nborneklint@gmail.com"
|
package/src/deps.js
CHANGED
|
@@ -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 path=require("node:path"),{roots:roots,resolveShared:resolveShared}=require("./sharedpaths.js"),clientPath=resolveShared(path.join("client","aegis.js")),toolsPath=resolveShared(path.join("mcp","tools.js")),usagePath=resolveShared(path.join("desktop","renderer","usage.js")),enginePath=resolveShared(path.join("desktop","lib","local","engine.js")),settingsPath=resolveShared(path.join("desktop","lib","settings.js")),agentsPath=resolveShared(path.join("desktop","lib","local","agents.js")),promptPath=resolveShared(path.join("desktop","lib","local","prompt.js")),claudeProPath=resolveShared(path.join("desktop","lib","local","claude-pro.js")),updatePath=resolveShared(path.join("client","update.js")),queuePath=resolveShared(path.join("desktop","lib","local","queue.js")),autonomousPath=resolveShared(path.join("desktop","lib","local","autonomous.js")),autoProvisionPath=resolveShared(path.join("client","auto-provision.js")),{createClient:createClient}=require(clientPath),{createTools:createTools}=require(toolsPath),{usageTokens:usageTokens,usageBuckets:usageBuckets}=require(usagePath),{createLocalEngine:createLocalEngine,hostEnv:hostEnv}=require(enginePath),{createSettingsStore:createSettingsStore,isReservedNamespace:isReservedNamespace}=require(settingsPath),{agentRoles:agentRoles,agentRoleLabel:agentRoleLabel}=require(agentsPath),{buildSystemPrompt:buildSystemPrompt}=require(promptPath),claudePro=require(claudeProPath),updater=require(updatePath),queue=require(queuePath),autonomousModule=require(autonomousPath);function withModelRelease(e,t){const o=o=>{const a=e[o];return"function"!=typeof a?a:async(...o)=>{try{return await a.apply(e,o)}finally{await(async()=>{try{t&&"function"==typeof t.unloadLocalModels&&await t.unloadLocalModels()}catch{}})()}}};return{...e,proceed:o("proceed"),reconcile:o("reconcile")}}const autonomous={...autonomousModule,createQueueWorker:(e={})=>autonomousModule.createQueueWorker?withModelRelease(autonomousModule.createQueueWorker(e),e&&e.engine):autonomousModule.createQueueWorker},{autoProvisionApiKey:autoProvisionApiKey,provisionFailureText:provisionFailureText,trialOutcomeNote:trialOutcomeNote}=require(autoProvisionPath),trialNote="function"==typeof trialOutcomeNote?trialOutcomeNote:()=>"";module.exports={resolveShared:resolveShared,createClient:createClient,createTools:createTools,usageTokens:usageTokens,usageBuckets:usageBuckets,createLocalEngine:createLocalEngine,hostEnv:hostEnv,createSettingsStore:createSettingsStore,isReservedNamespace:isReservedNamespace,agentRoles:agentRoles,agentRoleLabel:agentRoleLabel,buildSystemPrompt:buildSystemPrompt,claudePro:claudePro,updater:updater,queue:queue,autonomous:autonomous,autoProvisionApiKey:autoProvisionApiKey,provisionFailureText:provisionFailureText,trialNote:trialNote,paths:{client:clientPath,tools:toolsPath,usage:usagePath,engine:enginePath,settings:settingsPath,agents:agentsPath,prompt:promptPath,claudePro:claudeProPath,update:updatePath,queue:queuePath,autonomous:autonomousPath,autoProvision:autoProvisionPath},roots:roots};
|
|
3
|
+
"use strict";const path=require("node:path"),{roots:roots,resolveShared:resolveShared}=require("./sharedpaths.js"),clientPath=resolveShared(path.join("client","aegis.js")),toolsPath=resolveShared(path.join("mcp","tools.js")),usagePath=resolveShared(path.join("desktop","renderer","usage.js")),enginePath=resolveShared(path.join("desktop","lib","local","engine.js")),settingsPath=resolveShared(path.join("desktop","lib","settings.js")),agentsPath=resolveShared(path.join("desktop","lib","local","agents.js")),promptPath=resolveShared(path.join("desktop","lib","local","prompt.js")),claudeProPath=resolveShared(path.join("desktop","lib","local","claude-pro.js")),updatePath=resolveShared(path.join("client","update.js")),queuePath=resolveShared(path.join("desktop","lib","local","queue.js")),autonomousPath=resolveShared(path.join("desktop","lib","local","autonomous.js")),autoProvisionPath=resolveShared(path.join("client","auto-provision.js")),{createClient:createClient}=require(clientPath),{createTools:createTools}=require(toolsPath),{usageTokens:usageTokens,usageBuckets:usageBuckets}=require(usagePath),{createLocalEngine:createLocalEngine,hostEnv:hostEnv}=require(enginePath),{createSettingsStore:createSettingsStore,isReservedNamespace:isReservedNamespace}=require(settingsPath),{agentRoles:agentRoles,agentRoleLabel:agentRoleLabel}=require(agentsPath),{buildSystemPrompt:buildSystemPrompt}=require(promptPath),claudePro=require(claudeProPath),updater=require(updatePath),queue=require(queuePath),autonomousModule=require(autonomousPath);let integrityPath;function integrityArmed(){try{void 0===integrityPath&&(integrityPath=resolveShared("desktop/lib/local/integrity.js"));const e=require(integrityPath);return Boolean(e&&e.armed())}catch{return!1}}function refusedDrain(e){return{ok:!1,error:e,ran:[{id:"refused",ok:!1,error:e,ms:0}]}}function withModelRelease(e,t){const o=o=>{const a=e[o];return"function"!=typeof a?a:async(...o)=>{if(integrityArmed())return refusedDrain('the tool layer is sealed off (desktop interlock armed), so every write would be refused — nothing was run. Reseal with `AEGIS_DESKTOP_SEAL="why" node tools/desktop-seal.mjs --write` from the repo root.');try{return await a.apply(e,o)}finally{await(async()=>{try{t&&"function"==typeof t.unloadLocalModels&&await t.unloadLocalModels()}catch{}})()}}};return{...e,proceed:o("proceed"),reconcile:o("reconcile")}}const autonomous={...autonomousModule,createQueueWorker:(e={})=>autonomousModule.createQueueWorker?withModelRelease(autonomousModule.createQueueWorker(e),e&&e.engine):autonomousModule.createQueueWorker},{autoProvisionApiKey:autoProvisionApiKey,provisionFailureText:provisionFailureText,trialOutcomeNote:trialOutcomeNote}=require(autoProvisionPath),trialNote="function"==typeof trialOutcomeNote?trialOutcomeNote:()=>"";module.exports={resolveShared:resolveShared,createClient:createClient,createTools:createTools,usageTokens:usageTokens,usageBuckets:usageBuckets,createLocalEngine:createLocalEngine,hostEnv:hostEnv,createSettingsStore:createSettingsStore,isReservedNamespace:isReservedNamespace,agentRoles:agentRoles,agentRoleLabel:agentRoleLabel,buildSystemPrompt:buildSystemPrompt,claudePro:claudePro,updater:updater,queue:queue,autonomous:autonomous,autoProvisionApiKey:autoProvisionApiKey,provisionFailureText:provisionFailureText,trialNote:trialNote,paths:{client:clientPath,tools:toolsPath,usage:usagePath,engine:enginePath,settings:settingsPath,agents:agentsPath,prompt:promptPath,claudePro:claudeProPath,update:updatePath,queue:queuePath,autonomous:autonomousPath,autoProvision:autoProvisionPath},roots:roots};
|
|
@@ -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}const WORKTREE_LOCK_WAIT_MS=1500,MAX_SUBAGENT_DEPTH=4,CLASSES=[{class:"aegis",label:"Aegis Cloud",kind:"cloud"},{class:"byok",label:"Bring your own key",kind:"cloud"},{class:"local",label:"Local model",kind:"local"},{class:"pro",label:"Claude Code Pro",kind:"subscription"}],BYOK_NAMESPACE_PREFIX="byok:";function byokNamespace(e){return`${BYOK_NAMESPACE_PREFIX}${e}`}function splitByokModel(e){const t="string"==typeof e?e:"",o=t.indexOf(":");return o<0?{provider:"",model:t}:{provider:t.slice(0,o),model:t.slice(o+1)}}function providerKeyRecord(e){const t={key:"",env:"",rejected:null};if(!envFile||"function"!=typeof envFile.providerKeyFromEnv)return t;try{const o=envFile.providerKeyFromEnv(e)||t;return{key:"string"==typeof o.key?o.key:"",env:"string"==typeof o.env?o.env:"",rejected:"string"==typeof o.rejected&&o.rejected?o.rejected:null}}catch{return t}}function providerKeyFromEnv(e){if(!envFile||"function"!=typeof envFile.providerKeyFromEnv)return"";try{return envFile.providerKeyFromEnv(e).key||""}catch{return""}}const DEEPSEEK_REASONING_MODEL_RE=/^deepseek-(v4(\.\d+)?-(flash|pro)|flash|pro|reasoner)$/,EFFORT_TOKEN_BUDGET={low:8192,medium:16384,high:32768,max:32768},DEEPSEEK_EFFORT={low:"low",medium:"high",high:"high"},DEEPSEEK_EFFORT_EXTRA={max:"max"},EFFORT_IDENTITY={low:"low",medium:"medium",high:"high"},EFFORT_INERT_RE=/non-reasoning/i,EFFORT_DIALECTS=[{provider:"deepseek",re:DEEPSEEK_REASONING_MODEL_RE,field:"effort",map:DEEPSEEK_EFFORT,extra:DEEPSEEK_EFFORT_EXTRA},{provider:"openai",re:/^(gpt-5|o[0-9])/i,field:"reasoning_effort",map:EFFORT_IDENTITY},{provider:"groq",re:/^(openai\/gpt-oss|qwen\/qwen3)/i,field:"reasoning_effort",map:EFFORT_IDENTITY},{provider:"xai",re:/^grok-(4\.[5-9]|[5-9])/,field:"reasoning_effort",map:EFFORT_IDENTITY},{provider:"google",re:/^gemini-(2\.5|3|[4-9])/,field:"reasoning_effort",map:{...EFFORT_IDENTITY,medium:"high"}}],AUTONOMOUS_IDLE_TIMEOUT_MS=9e5;function reasoningBudget(e,t,o){const 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();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,REASONING_RETRY_FLOOR):o}function ladderRung(e){const t=Number(e);return Number.isFinite(t)&&Object.values(EFFORT_TOKEN_BUDGET).includes(t)}function doubledBudget(e){const t=Number(e)||0;return t>0?2*t:8192}function statedCapOf(e){const t=e=>{const t=Number(e);return Number.isFinite(t)&&t>0?t:void 0};return e&&Object.prototype.hasOwnProperty.call(e,"statedMaxTokens")?t(e.statedMaxTokens):t(e&&e.maxTokens)}const EMPTY_TURN_NUDGE="Your previous reply came back empty — it contained no answer and no tool call. Write your answer now, using only the information already gathered above. No tools are available in this reply, so do not call any: respond in plain prose or markdown.",THOUGHT_ONLY_NUDGE="Your previous round was spent entirely on hidden reasoning and produced no visible reply. Answer the user directly and briefly now. Do not reason, explain, or think first — write only the answer, no tools.",FINAL_ANSWER_NUDGE="Write your answer now, in plain prose, using only what is already in this conversation. If your information is incomplete, say what you have and what is missing — an incomplete answer is the expected outcome here and is better than none. No tools, no preface.",RECOVERY_ROUNDS=2,UNMUTATED_TURN_NUDGE="You ended the turn without changing any file, but this request asked for a change. The tools are still available in this reply: make the edit now with editFile or writeFile. If you already know what to change, change it — describing the fix is not the fix. If you genuinely cannot, say precisely what blocks you.",MUTATION_INTENT_RE=new RegExp("\\b(?:fix|implement|add|create|write|refactor|rename|remove|delete|replace|update|patch|migrate|convert|make\\s+(?:it|them|this|that|the|sure)|change|correct|resolve|repair|address|apply|introduce|support|wire\\s+up)\\b","i");function wantsMutation(e,t,o){if(t)return!1;if(!(o>0))return!1;const 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,g=f&&"function"==typeof f.rulesVerdict?f.rulesVerdict:null,y=f&&"function"==typeof f.alwaysAllow?f.alwaysAllow:null,k=f&&"function"==typeof f.subjectFor?f.subjectFor:null,v=require("./session-rounds.js"),b=()=>{if("function"==typeof a)return!1!==a();if(t&&"function"==typeof t.getConfirmMode){const e=t.getConfirmMode();return void 0===e||Boolean(e)}return!0},w=()=>"function"==typeof i?"plan"===i():!(!t||"function"!=typeof t.getPermissionMode)&&"plan"===t.getPermissionMode();function E(e,t){return`${e} was not executed — this session is in plan mode (read-only). Plan mode may read files, search, run read-only shell commands and deploy subagents to research, but may not create, edit or delete files, run a mutating command, or install packages`+(t?` (this command: ${t})`:"")+". Do NOT retry it or attempt the same effect by another route. Finish your research and present a plan in plain text; the user exits plan mode (`/permissions mode off`) before any edit can run."}const _=new Map,T=new Map,S=new Map,x=200,A=new Map,M=require("./pro-sessions.js"),O=new Map,N=new Map;function F(e,t){if("function"!=typeof k)return e;let o="";try{o=String(k(e,t||{})||"")}catch{o=""}return`${e}\0${o}`}function R(e,t,o){_.has(e)||_.set(e,new Set),_.get(e).add(F(t,o))}function D(e,t){const o=T.get(e);return Boolean(o&&o.has(t))}function U(e,t){T.has(e)||T.set(e,new Set),T.get(e).add(t)}function I(e){if(!e)return null;try{return{existed:!0,content:fs.readFileSync(e,"utf8")}}catch(e){return e&&"ENOENT"===e.code?{existed:!1,content:null}:null}}function L(e){return`${e} was not executed — the user denied this tool for this conversation. Do NOT retry it and do NOT attempt the same effect by another route (another command, a writeFile instead of an edit, a subagent). Stop calling tools and reply in plain text: say what you were trying to do, what you need, and that the user can re-enable ${e} to let it proceed.`}function C(e,t,o,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,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:"",approval:{id:s,sessionId:e,tool:r.tool,args:r.args,diff:r.diff||null,canPersist:"function"==typeof y}}):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 $(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?I(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=I(t&&t.file_path);o&&function(e,t){if(!e)return;S.has(e)||S.set(e,[]);const o=S.get(e);o.push(t),o.length>x&&o.shift()}(r,{id:n||randomUUID(),tool:e,path:t&&t.file_path,before:u,after:o,at:Date.now()})}return l&&l.note?j(f,l.note):f}function j(e,t){if(!e||"object"!=typeof e)return{ok:!0,content:`${t}\n${null==e?"":e}`};if(!1===e.ok||!0===e.isError){const o=e.error||e.content||"";return{...e,error:`${t}\n${o}`,content:`${t}\n${o}`}}const o=null!=e.content?e.content:null!=e.output?e.output:"";return{...e,content:`${t}\n${o}`}}async function 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 $(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?$(s,i,t,o,e.id):{ok:!1,error:E(s,r.reason)}}return{ok:!1,error:E(s)}}if(!b())return $(s,i,t,o,e.id);if(function(e,t,o){const r=_.get(e);return Boolean(r&&r.has(F(t,o)))}(o,s,i))return $(s,i,t,o,e.id);if("function"==typeof g){let r;try{r=g(s,i)}catch(e){r={verdict:null,source:"error",error:e&&e.message||String(e)}}if(r&&"deny"===r.verdict)return U(o,s),{ok:!1,error:L(s),permissionRule:r.rule||null};if(r&&"allow"===r.verdict)return $(s,i,t,o,e.id)}if(D(o,s))return{ok:!1,error:L(s)};let l=null;if(("writeFile"===s||"editFile"===s)&&(l=m.previewMutation(s,i,t||{}),!l.ok))return{ok:!1,error:l.error};const c=await C(o,r,n,{tool:s,args:i,diff:l&&l.diff});if("deny"===c)return U(o,s),{ok:!1,error:L(s)};if("session"!==c&&"once"!==c&&"always"!==c)return{ok:!1,error:`${s} was not executed — the request was cancelled.`};let d=null;if("always"===c){let e=null;if("function"==typeof y)try{e=y(s,i)}catch(t){e={ok:!1,reason:t&&t.message||String(t)}}else e={ok:!1,reason:"no durable store is wired on this host"};d=e&&e.ok?`[permission_rule] stored ${e.rule} — this command will not ask again`:`[permission_rule] nothing was stored — ${e&&e.reason||"unknown reason"}; this call was allowed once only`}if("session"===c&&R(o,s,i),l){const e=m.applyChecked(s,i,l,t||{});return e&&!1!==e.ok&&t&&t.guard&&recordWrite(t.guard,i&&i.file_path),d?j(e,d):e}const u=await $(s,i,t,o,e.id);return d?j(u,d):u}function B(e){return hostEnv(s||{},e&&e.env||{},e)}function K(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=A.get(e)||null,!t)){try{t=M.get(e,s)||null}catch{}t&&A.set(e,t)}const r=K(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 g){let e;try{e=g(s,a)}catch{e=null}if(e&&"deny"===e.verdict)return r&&r({delta:"",note:L(s)}),"deny";if(e&&"allow"===e.verdict)return"once"}if(D(t,s))return r&&r({delta:"",note:L(s)}),"deny";const l=await C(t,r,o.signal,{tool:s,args:a,diff:null});if("deny"===l)return U(t,s),"deny";if("session"!==l&&"once"!==l&&"always"!==l)return"deny";if("session"===l&&R(t,s,a),"always"===l&&"function"==typeof y)try{y(s,a)}catch{}return l},signal:o.signal,onDelta:o.onDelta,onSpawn:(e,t)=>{o.onDelta&&t&&o.onDelta({delta:"",note:claudePro.childLine(t)})}});let a=await n(t);if(a&&a.resumeStale){A.delete(e);try{M.del(e,s)}catch{}o.onDelta&&o.onDelta({delta:"",note:"aegis: the remembered Claude session no longer exists on this machine — continuing as a new conversation (earlier turns are not in its context)"}),a=await n(null)}if(e&&a&&a.sessionId&&!a.error){A.set(e,a.sessionId);try{M.set(e,a.sessionId,s)}catch{}}return a}throw new Error(`dispatch: unknown model class ${JSON.stringify(t)} — this build ships 'aegis', 'byok', 'local' and 'pro' only`)}async function Y(o,r){const n=o&&o.class,s=o&&o.model,a=reasoningBudget("byok"===n?splitByokModel(s).model:s,o&&o.maxTokens,o&&o.effort),i=statedCapOf(o),d="aegis"===n&&Boolean(o&&o.autonomous),u=Boolean(o&&o.roundsAsk),f=o&&o.sessionId||randomUUID(),g=Number.isInteger(o&&o.depth)?o.depth:0,y=o&&o.rootSessionId||f,k=o&&o.rootOnDelta||r,b="function"==typeof r?e=>e&&r({reasoning:e}):void 0,w=new AbortController,E=p.get(f)||null;p.set(f,w);const _=w.signal,T=!(o&&!1===o.tools),S=T?m.toolsFor({includeSubagent:g<4}):[],x=o&&o.toolChoice||null,A=o&&o.system||h(B(o)),M=Array.isArray(o&&o.messages)?o.messages.filter(Boolean).slice():[];let O=M.length,N=o&&o.prompt||"";const F=String(N||""),R=Array.isArray(o&&o.attachments)?o.attachments.filter((e=>e&&"object"==typeof e)).slice(0,attachmentsModule.MAX_ATTACHMENTS):[];let D=R.length?attachmentsModule.buildContent(N,R):N,U=null;const I=B(o),L=((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 K(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}})(I,n),C=I.cwd,$={getShell:()=>U||(U=new ShellSession({cwd:I.cwd,sandbox:L})),signal:_,cwd:C,desktopdir:I.desktopdir,sandbox:L,repeat:repeatGuard.beginRepeatGuard({cwd:C}),verify:verifyGuard.beginVerifyGuard({cwd:C}),guard:beginTurnGuard(C)};try{const l="byok"===n?splitByokModel(s):null;let p=null;const h="byok"===n?t.get(byokNamespace(l.provider))||{}:"local"===n&&t.get("local")||{},w="byok"===n?t.rawKey(byokNamespace(l.provider)):null,E="byok"!==n?null:w||providerKeyFromEnv(l.provider);if(!("byok"!==n||l.provider&&l.model)){const e=new Error('byok: model must be "<provider>:<model>" (pick one from /models) — got '+JSON.stringify(s||""));throw e.status=400,e}if("byok"===n&&!E){const t="anthropic"===l.provider?claudePro.claudeProStatus({env:process.env}):null,o=providerKeyRecord(l.provider).rejected,r=nexusFallbackModel({provider:l.provider,providerKey:E,providerKeyRefused:o,aegisKey:E?"":e.apiKey});if(!r){const e=new Error(o?`${o}. That is why this turn has no ${l.provider} key: an env value that short is a paste that lost its payload, not a credential. Fix ${o.split(" ")[0]} in ~/.aegiscode/.env (or the shell that exported it) — or skip keys entirely: /byok-key ${l.provider} <key> to set one here.`:t&&t.loggedIn?`No Anthropic API key on this machine — an "anthropic:…" id is served by your own console key, which a Claude subscription is not. Use the subscription instead: /class pro (it spends your Claude Code ${t.subscription||"Pro"} plan through the claude CLI) — or add a real console key: /byok-key anthropic <key>.`:`No key for "${l.provider}" yet. Easiest fix: /class aegis (uses your AEGIS key, no setup) — or add this provider's own key: /byok-key ${l.provider} <key>.`);throw e.status=400,e}p={from:l.provider,model:r}}if("byok"===n&&!e.apiKey){const e=new Error("No AEGIS key connected yet. Easiest fix: /class aegis (skips BYOK entirely) — or add your AEGIS key with /login, then try again.");throw e.status=401,e}if("local"===n){const e=c.remoteRefusal(h.baseURL||c.DEFAULT_BASE);if(e)throw e}if("byok"===n&&"custom"===l.provider&&!(h.baseURL||"").trim()){const e=new Error('No endpoint saved for the "custom" provider — its key is on this machine but the address it dials is not, and no default exists for a vendor AEGIS does not know. Fix: /model-add custom <https-base-url> <api-key> <model-id> (writes both halves), or the endpoint field in Settings › Provider (custom).');throw e.status=400,e.code="custom_endpoint_missing",e}const U=p?"aegis":n,I={cls:U,model:p?p.model:s,mode:o&&o.mode,maxTokens:a,statedMaxTokens:i,autonomous:d,sessionId:f,signal:_,onDelta:r,cfg:h,apiKey:E,toolChoice:x,pooledFrom:p?p.from:void 0,cwd:C,rootSessionId:y,sessionKey:o&&o.sessionKey||void 0,rootOnDelta:k,effort:o&&o.effort,workers:o&&o.workers,recallDeep:o&&!0===o.recallDeep,singlePass:o&&!0===o.singlePass,onReasoning:b,idleTimeoutMs:d?9e5:void 0,stream:!o||!1!==o.stream};let L=!1,j=!1;const B=d?"AEGIS_AUTONOMOUS_MAX_ROUNDS":"AEGIS_CHAT_MAX_ROUNDS",K=(()=>{const e=Number.parseInt(process.env[B]||"",10);return Number.isFinite(e)&&e>0?e:0})(),Y=K||(d?40:24);let z=v.keyFor(o,M),V=v.take(z);if(!V&&!v.isStatedKey(o)){const e=v.adopt();e&&(V=e.entry,z=e.key)}if(V){const e=v.resumePreamble(V);0===M.length?Array.isArray(V.messages)&&V.messages.length&&M.push(...V.messages):Array.isArray(V.added)&&V.added.length&&M.push(...V.added),N?(N=`${e}\n\n${N}`,D=R.length?attachmentsModule.buildContent(N,R):N):(M.push({role:"user",content:e}),D=""),k&&k({delta:`\n\n[resuming work this session left unfinished at ${V.rounds} tool rounds`+(V.interruptions>1?` (cut off ${V.interruptions}×)`:"")+"…]\n"})}let H=K||Y+(V?v.bonus(Y):0),X=0;const J=Y,Q=8;let Z=0;const ee={calls:0},te=["input_tokens","output_tokens","prompt_tokens","completion_tokens","total_tokens","cache_read_input_tokens","cache_creation_input_tokens","prompt_cache_hit_tokens","prompt_cache_miss_tokens","reasoning_tokens","thinking_tokens"],oe=e=>{const t=e&&e.usage;if(t&&"object"==typeof t){ee.calls+=1;for(const e of te)"number"==typeof t[e]&&Number.isFinite(t[e])&&(ee[e]=(ee[e]||0)+t[e]);if("number"!=typeof t.total_tokens){const e=(t.prompt_tokens??t.input_tokens??0)+(t.completion_tokens??t.output_tokens??0);e&&(ee.total_tokens=(ee.total_tokens||0)+e)}}},re=e=>{if(!e||"object"!=typeof e)return e;const t=p?{...e,pooled_from:p.from,pooled_model:p.model,pooled_notice:requireSharedByokCatalog().nexusFallbackNotice({pooled_from:p.from,pooled_model:p.model})}:e;return ee.calls?{...t,usage:{...ee}}:t},ne=()=>{if(""===D)return;const e=M[M.length-1],t=e&&"user"===e.role?flattenContent(e.content):null;e&&"user"===e.role&&t===flattenContent(D)||M.push({role:"user",content:D}),N="",D=""};O=M.length;const se=m&&m.MUTATING_TOOLS||new Set;let ae=0,ie=0,le=!1,ce=!1;for(;;){if(X>=H){if(u&&Z<Q&&!_.aborted&&await P(y,k,_,{spent:H,extensions:Z+1,max:Q,size:J})){Z+=1;const e=H;H+=J,M.push({role:"user",content:`You have used all ${e} tool rounds allowed for this turn; ${J} more have been granted (do not restart). Continue the task from exactly where you stopped — do not re-plan, do not repeat work already done, and finish with an answer.`});continue}const e=u?"":`, or raise ${B} 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(z,{rounds:X,tokens:ee.total_tokens||0,note:t,chain:V?V.interruptions:0,messages:M,added:M.slice(O)});return k&&k({delta:`\n\n${t}`}),re({model:I.model,choices:[{message:{content:t},finish_reason:"length"}],stoppedOnRounds:!0,heldForSession:!0,heldRounds:o.rounds,sessionInterruptions:o.interruptions,resumedFrom:z})}X+=1;const e={...I,system:A,messages:M,prompt:D,tools:S,recallDeep:I.recallDeep&&1===X};let t;if(t=await G(U,e),oe(t),_.aborted)return re(t);if(!L&&!assistantText(t)&&(isTruncated(t)||reasonedButSilent(t))){L=!0;const o=reasonedButSilent(t);if(t=await G(U,{...e,singlePass:!0,recallDeep:!1,effort:o?"high":e.effort,maxTokens:retryBudgetFor(e,o),statedMaxTokens:e.statedMaxTokens?doubledBudget(e.statedMaxTokens):void 0}),oe(t),_.aborted)return re(t)}const a=S.length?extractToolCalls(t):[];if(!a.length){if(assistantText(t)||j||!T){if(!le&&T&&wantsMutation(F,ie>0,ae)){le=!0,ne(),M.push({role:"assistant",content:assistantText(t)}),M.push({role:"user",content:UNMUTATED_TURN_NUDGE}),k&&k({delta:""});continue}if($.verify&&!ce){const e=verifyGuard.shouldNudge($.verify);if(e.nudge){ce=!0,ne(),M.push({role:"assistant",content:assistantText(t)}),M.push({role:"user",content:e.text}),k&&k({delta:""});continue}}return re(t)}j=!0,ne(),M.push({role:"user",content:reasonedButSilent(t)?THOUGHT_ONLY_NUDGE:EMPTY_TURN_NUDGE});const o={...e,singlePass:!0,recallDeep:!1,messages:M,prompt:"",tools:[]};t=await G(U,o);let r=o.maxTokens,a=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),a=e?"high":o.effort,t=await G(U,{...o,effort:a,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,M.push({role:"user",content:e?1===l?THOUGHT_ONLY_NUDGE:FINAL_ANSWER_NUDGE:EMPTY_TURN_NUDGE}),e&&(a="high"),r=i,t=await G(U,{...o,messages:M,effort:a,maxTokens:r,statedMaxTokens:o.statedMaxTokens?doubledBudget(o.statedMaxTokens):void 0}),oe(t),_.aborted)return re(t)}if(!assistantText(t))throw emptyTurnError({cls:n,model:s,effort:a,recoveryRounds:l,finishReason:finishReasonOf(t),reasoningChars:reasoningTextOf(t).length,reasoningTokens:reasoningTokensOf(t)});return re(t)}ne(),M.push({role:"assistant",content:assistantText(t),tool_calls:a.map((e=>({id:e.id,type:"function",function:{name:e.name,arguments:JSON.stringify(e.args)}})))});const l=new WeakMap,c=e=>{if("exec"!==e.name)return null;if(l.has(e))return l.get(e);const t=planExec(e.args&&e.args.command,{baseCwd:C});return l.set(e,t),t},d=e=>{if(!se.has(e.name))return!0;const t=c(e);return Boolean(t&&t.oneShot)},f=[];for(const e of a){const t=f[f.length-1];d(e)&&t&&t.parallel?t.calls.push(e):f.push({parallel:d(e),calls:[e]})}const p=async e=>{r&&r({delta:"",tool:{name:e.name,args:e.args,id:e.id,cwd:C,phase:"run"}});const t=c(e),a=t&&t.oneShot?{...$,oneShotExec:!0,cwd:t.cwd||$.cwd}:$,l=e.name===m.SUBAGENT_TOOL?await W(e.args,{cls:n,model:s,statedMaxTokens:i,effort:o&&o.effort,mode:o&&o.mode,parentSignal:_,depth:g,rootSessionId:y,rootOnDelta:k}):await q(e,{toolCtx:a,rootSessionId:y,rootOnDelta:k,signal:_});return l&&l.usage&&oe({usage:l.usage}),r&&r({delta:"",tool:{name:e.name,args:e.args,ok:l.ok,id:e.id,cwd:C,phase:"done"}}),l};for(const e of f){const t=e.parallel&&e.calls.length>1?await Promise.all(e.calls.map((e=>p(e)))):[await p(e.calls[0])];e.calls.forEach(((e,o)=>{const r=t[o];se.has(e.name)&&(ae+=1,r&&r.ok&&(ie+=1)),M.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{U&&U.dispose(),p.get(f)===w&&(E&&!E.signal.aborted?p.set(f,E):p.delete(f))}}async function W({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 g;if(l){if(l.aborted)return{ok:!1,error:"aborted"};g=()=>z(h),l.addEventListener("abort",g,{once:!0})}try{const e=await Y({class: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&&g&&l.removeEventListener("abort",g)}}function z(e){const t=p.get(e);return t&&t.abort(),{ok:Boolean(t)}}return{CLASSES:CLASSES,listClasses:async function(){return CLASSES.map((o=>{if("aegis"===o.class)return{...o,configured:Boolean(e.apiKey)};if("byok"===o.class){const e=(t.list()||[]).some((e=>!(!e||"string"!=typeof e.provider||!e.provider.startsWith("byok:"))&&(!!e.configured||Boolean(providerKeyFromEnv(e.provider.slice(BYOK_NAMESPACE_PREFIX.length))))));return{...o,configured:e}}if("local"===o.class)return{...o,configured:!0};if("pro"===o.class){const e=claudePro.claudeProStatus({env:process.env}),t=claudePro.seamAvailable();return{...o,configured:e.loggedIn,status:e,seam:t}}return{...o,configured:!1}}))},listModels:async function(o){if("aegis"===o){if(!e.apiKey)return{class:o,models:[],needsKey:!0};const t=await e.listModels();return{class:o,models:offerableCatalog(normalizeCatalog(t&&t.models))}}if("byok"===o){let 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:Y,cancel:z,respondApproval:function(e,t){const o=O.get(e);return o?(O.delete(e),o.resolve("session"===t||"once"===t||"always"===t?t:"deny"),{ok:!0}):{ok:!1}},respondRoundsAsk:function(e,t){const o=N.get(e);return o?(N.delete(e),o.resolve(!0===t||"continue"===t),{ok:!0}):{ok:!1}},clearSessionApprovals:function(e){_.delete(e),T.delete(e),S.delete(e),A.delete(e);try{M.del(e,s)}catch{}return{ok:!0}},listUndoable:function(e){return(S.get(e)||[]).map((e=>({id:e.id,tool:e.tool,path:e.path,at:e.at}))).reverse()},undoMutation:function(e,t){const o=S.get(e)||[],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=I(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 o=String(null==e?"":e).trim().toLowerCase(),r=function(e){const o=String(null==e?"":e).trim().toLowerCase();if(!o)return"";try{if(t&&"function"==typeof t.rawKey){const e=t.rawKey(byokNamespace(o));if("string"==typeof e&&e.trim())return e.trim()}}catch{}return providerKeyFromEnv(o)}(o),n=await discoverVendorModels(o,{key:r,fetchImpl:d});if(!n||!n.ok)return n;const s=[];try{const e=loadUserModels().map;for(const t of Array.isArray(e[o])?e[o]:[])s.push(t)}catch{}return{...n,declared:s,endpoint:(vendorEndpointFor(o)||{}).url||""}},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)}}function requireSharedBrain(){const e=[()=>require("../../../client/brain-catalog.js"),()=>require("../../vendor/brain-catalog.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}function requireSharedByokCatalog(){const e=[()=>require("../../../client/byok-catalog.js"),()=>require("../../vendor/byok-catalog.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}function requireSharedUserModels(){const e=[()=>require("../../../client/user-models.js"),()=>require("../../vendor/user-models.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}function requireSharedCatalogClient(){const e=[()=>require("../../../client/catalog-client.js"),()=>require("../../vendor/catalog-client.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}function requireSharedModelDiscovery(){const e=[()=>require("../../../client/model-discovery.js"),()=>require("../../vendor/model-discovery.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}const WORKTREE_LOCK_WAIT_MS=1500,MAX_SUBAGENT_DEPTH=4,CLASSES=[{class:"aegis",label:"Aegis Cloud",kind:"cloud"},{class:"byok",label:"Bring your own key",kind:"cloud"},{class:"local",label:"Local model",kind:"local"},{class:"pro",label:"Claude Code Pro",kind:"subscription"}],BYOK_NAMESPACE_PREFIX="byok:";function byokNamespace(e){return`${BYOK_NAMESPACE_PREFIX}${e}`}function splitByokModel(e){const t="string"==typeof e?e:"",o=t.indexOf(":");return o<0?{provider:"",model:t}:{provider:t.slice(0,o),model:t.slice(o+1)}}function providerKeyRecord(e){const t={key:"",env:"",rejected:null};if(!envFile||"function"!=typeof envFile.providerKeyFromEnv)return t;try{const o=envFile.providerKeyFromEnv(e)||t;return{key:"string"==typeof o.key?o.key:"",env:"string"==typeof o.env?o.env:"",rejected:"string"==typeof o.rejected&&o.rejected?o.rejected:null}}catch{return t}}function providerKeyFromEnv(e){if(!envFile||"function"!=typeof envFile.providerKeyFromEnv)return"";try{return envFile.providerKeyFromEnv(e).key||""}catch{return""}}const DEEPSEEK_REASONING_MODEL_RE=/^deepseek-(v4(\.\d+)?-(flash|pro)|flash|pro|reasoner)$/,EFFORT_TOKEN_BUDGET={low:8192,medium:16384,high:32768,max:32768},DEEPSEEK_EFFORT={low:"low",medium:"high",high:"high"},DEEPSEEK_EFFORT_EXTRA={max:"max"},EFFORT_IDENTITY={low:"low",medium:"medium",high:"high"},EFFORT_INERT_RE=/non-reasoning/i,EFFORT_DIALECTS=[{provider:"deepseek",re:DEEPSEEK_REASONING_MODEL_RE,field:"effort",map:DEEPSEEK_EFFORT,extra:DEEPSEEK_EFFORT_EXTRA},{provider:"openai",re:/^(gpt-5|o[0-9])/i,field:"reasoning_effort",map:EFFORT_IDENTITY},{provider:"groq",re:/^(openai\/gpt-oss|qwen\/qwen3)/i,field:"reasoning_effort",map:EFFORT_IDENTITY},{provider:"xai",re:/^grok-(4\.[5-9]|[5-9])/,field:"reasoning_effort",map:EFFORT_IDENTITY},{provider:"google",re:/^gemini-(2\.5|3|[4-9])/,field:"reasoning_effort",map:{...EFFORT_IDENTITY,medium:"high"}}],AUTONOMOUS_IDLE_TIMEOUT_MS=9e5;function reasoningBudget(e,t,o){const 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();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,REASONING_RETRY_FLOOR):o}function ladderRung(e){const t=Number(e);return Number.isFinite(t)&&Object.values(EFFORT_TOKEN_BUDGET).includes(t)}function doubledBudget(e){const t=Number(e)||0;return t>0?2*t:8192}function statedCapOf(e){const t=e=>{const t=Number(e);return Number.isFinite(t)&&t>0?t:void 0};return e&&Object.prototype.hasOwnProperty.call(e,"statedMaxTokens")?t(e.statedMaxTokens):t(e&&e.maxTokens)}const EMPTY_TURN_NUDGE="Your previous reply came back empty — it contained no answer and no tool call. Write your answer now, using only the information already gathered above. No tools are available in this reply, so do not call any: respond in plain prose or markdown.",THOUGHT_ONLY_NUDGE="Your previous round was spent entirely on hidden reasoning and produced no visible reply. Answer the user directly and briefly now. Do not reason, explain, or think first — write only the answer, no tools.",FINAL_ANSWER_NUDGE="Write your answer now, in plain prose, using only what is already in this conversation. If your information is incomplete, say what you have and what is missing — an incomplete answer is the expected outcome here and is better than none. No tools, no preface.",RECOVERY_ROUNDS=2,UNMUTATED_TURN_NUDGE="You ended the turn without changing any file, but this request asked for a change. The tools are still available in this reply: make the edit now with editFile or writeFile. If you already know what to change, change it — describing the fix is not the fix. If you genuinely cannot, say precisely what blocks you.",MUTATION_INTENT_RE=new RegExp("\\b(?:fix|implement|add|create|write|refactor|rename|remove|delete|replace|update|patch|migrate|convert|make\\s+(?:it|them|this|that|the|sure)|change|correct|resolve|repair|address|apply|introduce|support|wire\\s+up)\\b","i");function wantsMutation(e,t,o){if(t)return!1;if(!(o>0))return!1;const 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,g=f&&"function"==typeof f.rulesVerdict?f.rulesVerdict:null,y=f&&"function"==typeof f.alwaysAllow?f.alwaysAllow:null,k=f&&"function"==typeof f.subjectFor?f.subjectFor:null,v=require("./session-rounds.js"),b=()=>{if("function"==typeof a)return!1!==a();if(t&&"function"==typeof t.getConfirmMode){const e=t.getConfirmMode();return void 0===e||Boolean(e)}return!0},w=()=>"function"==typeof i?"plan"===i():!(!t||"function"!=typeof t.getPermissionMode)&&"plan"===t.getPermissionMode();function E(e,t){return`${e} was not executed — this session is in plan mode (read-only). Plan mode may read files, search, run read-only shell commands and deploy subagents to research, but may not create, edit or delete files, run a mutating command, or install packages`+(t?` (this command: ${t})`:"")+". Do NOT retry it or attempt the same effect by another route. Finish your research and present a plan in plain text; the user exits plan mode (`/permissions mode off`) before any edit can run."}const _=new Map,T=new Map,S=new Map,x=200,A=new Map,M=require("./pro-sessions.js"),O=new Map,N=new Map;function F(e,t){if("function"!=typeof k)return e;let o="";try{o=String(k(e,t||{})||"")}catch{o=""}return`${e}\0${o}`}function R(e,t,o){_.has(e)||_.set(e,new Set),_.get(e).add(F(t,o))}function D(e,t){const o=T.get(e);return Boolean(o&&o.has(t))}function U(e,t){T.has(e)||T.set(e,new Set),T.get(e).add(t)}function I(e){if(!e)return null;try{return{existed:!0,content:fs.readFileSync(e,"utf8")}}catch(e){return e&&"ENOENT"===e.code?{existed:!1,content:null}:null}}function L(e){return`${e} was not executed — the user denied this tool for this conversation. Do NOT retry it and do NOT attempt the same effect by another route (another command, a writeFile instead of an edit, a subagent). Stop calling tools and reply in plain text: say what you were trying to do, what you need, and that the user can re-enable ${e} to let it proceed.`}function C(e,t,o,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,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:"",approval:{id:s,sessionId:e,tool:r.tool,args:r.args,diff:r.diff||null,canPersist:"function"==typeof y}}):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 $(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?I(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=I(t&&t.file_path);o&&function(e,t){if(!e)return;S.has(e)||S.set(e,[]);const o=S.get(e);o.push(t),o.length>x&&o.shift()}(r,{id:n||randomUUID(),tool:e,path:t&&t.file_path,before:u,after:o,at:Date.now()})}return l&&l.note?j(f,l.note):f}function j(e,t){if(!e||"object"!=typeof e)return{ok:!0,content:`${t}\n${null==e?"":e}`};if(!1===e.ok||!0===e.isError){const o=e.error||e.content||"";return{...e,error:`${t}\n${o}`,content:`${t}\n${o}`}}const o=null!=e.content?e.content:null!=e.output?e.output:"";return{...e,content:`${t}\n${o}`}}async function 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 $(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?$(s,i,t,o,e.id):{ok:!1,error:E(s,r.reason)}}return{ok:!1,error:E(s)}}if(!b())return $(s,i,t,o,e.id);if(function(e,t,o){const r=_.get(e);return Boolean(r&&r.has(F(t,o)))}(o,s,i))return $(s,i,t,o,e.id);if("function"==typeof g){let r;try{r=g(s,i)}catch(e){r={verdict:null,source:"error",error:e&&e.message||String(e)}}if(r&&"deny"===r.verdict)return U(o,s),{ok:!1,error:L(s),permissionRule:r.rule||null};if(r&&"allow"===r.verdict)return $(s,i,t,o,e.id)}if(D(o,s))return{ok:!1,error:L(s)};let l=null;if(("writeFile"===s||"editFile"===s)&&(l=m.previewMutation(s,i,t||{}),!l.ok))return{ok:!1,error:l.error};const c=await C(o,r,n,{tool:s,args:i,diff:l&&l.diff});if("deny"===c)return U(o,s),{ok:!1,error:L(s)};if("session"!==c&&"once"!==c&&"always"!==c)return{ok:!1,error:`${s} was not executed — the request was cancelled.`};let d=null;if("always"===c){let e=null;if("function"==typeof y)try{e=y(s,i)}catch(t){e={ok:!1,reason:t&&t.message||String(t)}}else e={ok:!1,reason:"no durable store is wired on this host"};d=e&&e.ok?`[permission_rule] stored ${e.rule} — this command will not ask again`:`[permission_rule] nothing was stored — ${e&&e.reason||"unknown reason"}; this call was allowed once only`}if("session"===c&&R(o,s,i),l){const e=m.applyChecked(s,i,l,t||{});return e&&!1!==e.ok&&t&&t.guard&&recordWrite(t.guard,i&&i.file_path),d?j(e,d):e}const u=await $(s,i,t,o,e.id);return d?j(u,d):u}function B(e){return hostEnv(s||{},e&&e.env||{},e)}function K(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=A.get(e)||null,!t)){try{t=M.get(e,s)||null}catch{}t&&A.set(e,t)}const r=K(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 g){let e;try{e=g(s,a)}catch{e=null}if(e&&"deny"===e.verdict)return r&&r({delta:"",note:L(s)}),"deny";if(e&&"allow"===e.verdict)return"once"}if(D(t,s))return r&&r({delta:"",note:L(s)}),"deny";const l=await C(t,r,o.signal,{tool:s,args:a,diff:null});if("deny"===l)return U(t,s),"deny";if("session"!==l&&"once"!==l&&"always"!==l)return"deny";if("session"===l&&R(t,s,a),"always"===l&&"function"==typeof y)try{y(s,a)}catch{}return l},signal:o.signal,onDelta:o.onDelta,onSpawn:(e,t)=>{o.onDelta&&t&&o.onDelta({delta:"",note:claudePro.childLine(t)})}});let a=await n(t);if(a&&a.resumeStale){A.delete(e);try{M.del(e,s)}catch{}o.onDelta&&o.onDelta({delta:"",note:"aegis: the remembered Claude session no longer exists on this machine — continuing as a new conversation (earlier turns are not in its context)"}),a=await n(null)}if(e&&a&&a.sessionId&&!a.error){A.set(e,a.sessionId);try{M.set(e,a.sessionId,s)}catch{}}return a}throw new Error(`dispatch: unknown model class ${JSON.stringify(t)} — this build ships 'aegis', 'byok', 'local' and 'pro' only`)}async function Y(o,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),g=o&&o.sessionId||randomUUID(),y=Number.isInteger(o&&o.depth)?o.depth:0,k=o&&o.rootSessionId||g,b=o&&o.rootOnDelta||r,w="function"==typeof r?e=>e&&r({reasoning:e}):void 0,E=new AbortController,_=p.get(g)||null;p.set(g,E);const T=E.signal,S=!(o&&!1===o.tools),x=S?m.toolsFor({includeSubagent:y<4}):[],A=o&&o.toolChoice||null,M=o&&o.system||h(B(o)),O=n?await n({payload:o,env:B(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 R=F.length,D=o&&o.prompt||"";const U=String(D||""),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(D,I):D,C=null;const $=B(o),j=((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 K(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),Y=$.cwd,z={getShell:()=>C||(C=new ShellSession({cwd:$.cwd,sandbox:j})),signal:T,cwd:Y,desktopdir:$.desktopdir,sandbox:j,repeat:repeatGuard.beginRepeatGuard({cwd:Y}),verify:verifyGuard.beginVerifyGuard({cwd:Y}),guard:beginTurnGuard(Y)};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 _=l?"aegis":s,M={cls:_,model:l?l.model:a,mode:o&&o.mode,maxTokens:i,statedMaxTokens:d,autonomous:u,sessionId:g,signal:T,onDelta:r,cfg:p,apiKey:E,toolChoice:A,pooledFrom:l?l.from:void 0,cwd:Y,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,C=!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),D?(D=`${e}\n\n${D}`,L=I.length?attachmentsModule.buildContent(D,I):D):(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}),D="",L=""};R=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&&!T.aborted&&await P(k,b,T,{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(R)});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(_,e),oe(t),T.aborted)return re(t);if(!O&&!assistantText(t)&&(isTruncated(t)||reasonedButSilent(t))){O=!0;const o=reasonedButSilent(t);if(t=await G(_,{...e,singlePass:!0,recallDeep:!1,effort:o?"high":e.effort,maxTokens:retryBudgetFor(e,o),statedMaxTokens:e.statedMaxTokens?doubledBudget(e.statedMaxTokens):void 0}),oe(t),T.aborted)return re(t)}const n=x.length?extractToolCalls(t):[];if(!n.length){if(assistantText(t)||C||!S){if(!le&&S&&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)}C=!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(_,o);let r=o.maxTokens,n=o.effort;if(oe(t),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(_,{...o,effort:n,maxTokens:r,statedMaxTokens:o.statedMaxTokens?doubledBudget(o.statedMaxTokens):void 0}),oe(t),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&&!T.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(_,{...o,messages:F,effort:n,maxTokens:r,statedMaxTokens:o.statedMaxTokens?doubledBudget(o.statedMaxTokens):void 0}),oe(t),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:Y});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:Y,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 W(e.args,{cls:s,model:a,statedMaxTokens:d,effort:o&&o.effort,mode:o&&o.mode,parentSignal:T,depth:y,rootSessionId:k,rootOnDelta:b}):await q(e,{toolCtx:n,rootSessionId:k,rootOnDelta:b,signal:T});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:Y,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 T.aborted&&e&&"object"==typeof e&&(e.aegisCancelled=!0),e}finally{C&&C.dispose(),p.get(g)===E&&(_&&!_.signal.aborted?p.set(g,_):p.delete(g))}}async function W({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 g;if(l){if(l.aborted)return{ok:!1,error:"aborted"};g=()=>z(h),l.addEventListener("abort",g,{once:!0})}try{const e=await Y({class: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&&g&&l.removeEventListener("abort",g)}}function z(e){const t=p.get(e);return t&&t.abort(),{ok:Boolean(t)}}return{CLASSES:CLASSES,listClasses:async function(){return CLASSES.map((o=>{if("aegis"===o.class)return{...o,configured:Boolean(e.apiKey)};if("byok"===o.class){const e=(t.list()||[]).some((e=>!(!e||"string"!=typeof e.provider||!e.provider.startsWith("byok:"))&&(!!e.configured||Boolean(providerKeyFromEnv(e.provider.slice(BYOK_NAMESPACE_PREFIX.length))))));return{...o,configured:e}}if("local"===o.class)return{...o,configured:!0};if("pro"===o.class){const e=claudePro.claudeProStatus({env:process.env}),t=claudePro.seamAvailable();return{...o,configured:e.loggedIn,status:e,seam:t}}return{...o,configured:!1}}))},listModels:async function(o){if("aegis"===o){if(!e.apiKey)return{class:o,models:[],needsKey:!0};const t=await e.listModels();return{class:o,models:offerableCatalog(normalizeCatalog(t&&t.models))}}if("byok"===o){let 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:Y,cancel:z,respondApproval:function(e,t){const o=O.get(e);return o?(O.delete(e),o.resolve("session"===t||"once"===t||"always"===t?t:"deny"),{ok:!0}):{ok:!1}},respondRoundsAsk:function(e,t){const o=N.get(e);return o?(N.delete(e),o.resolve(!0===t||"continue"===t),{ok:!0}):{ok:!1}},clearSessionApprovals:function(e){_.delete(e),T.delete(e),S.delete(e),A.delete(e);try{M.del(e,s)}catch{}return{ok:!0}},listUndoable:function(e){return(S.get(e)||[]).map((e=>({id:e.id,tool:e.tool,path:e.path,at:e.at}))).reverse()},undoMutation:function(e,t){const o=S.get(e)||[],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=I(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 o=String(null==e?"":e).trim().toLowerCase(),r=function(e){const o=String(null==e?"":e).trim().toLowerCase();if(!o)return"";try{if(t&&"function"==typeof t.rawKey){const e=t.rawKey(byokNamespace(o));if("string"==typeof e&&e.trim())return e.trim()}}catch{}return providerKeyFromEnv(o)}(o),n=await discoverVendorModels(o,{key:r,fetchImpl:d});if(!n||!n.ok)return n;const s=[];try{const e=loadUserModels().map;for(const t of Array.isArray(e[o])?e[o]:[])s.push(t)}catch{}return{...n,declared:s,endpoint:(vendorEndpointFor(o)||{}).url||""}},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};
|
|
@@ -134,7 +134,7 @@ const UNITS = Object.freeze([
|
|
|
134
134
|
* (`tools/desktop-seal.mjs` in the source tree, `tools/obfuscate-faces.mjs`
|
|
135
135
|
* after obfuscation), never by hand.
|
|
136
136
|
*/
|
|
137
|
-
const SEALED = '
|
|
137
|
+
const SEALED = '018887de47c1831abc08b71f33ca8fd0563f08f7a15547b4c2130a4d6567fcd9';
|
|
138
138
|
|
|
139
139
|
/**
|
|
140
140
|
* Ask the question. Never throws — a check that can break the program it is
|
|
@@ -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(`
|
|
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>PROJECT_DOC_MAX_CHARS?s.slice(0,PROJECT_DOC_MAX_CHARS)+`\n\n[${t} truncated at ${PROJECT_DOC_MAX_CHARS} 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:PROJECT_DOC_MAX_CHARS,environmentPreamble:environmentPreamble,commandDialectLine:commandDialectLine,readProjectDoc:readProjectDoc,buildSystemPrompt:buildSystemPrompt};
|
|
@@ -503,7 +503,7 @@ function normalizeArgs(name, args, ctx = {}) {
|
|
|
503
503
|
*
|
|
504
504
|
* `process.cwd()` is wrong here and was visibly wrong off Linux: the Electron
|
|
505
505
|
* main process inherits whatever the OS launched the app from — `/` from a .desktop
|
|
506
|
-
* entry, `C:\Program Files\
|
|
506
|
+
* entry, `C:\Program Files\aegis one` from a Windows shortcut — so a bare
|
|
507
507
|
* `listDir`/`glob`/`grep` searched the install directory instead of the user's
|
|
508
508
|
* repo. It stays the fallback for a direct call that supplies no ctx.
|
|
509
509
|
*/
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
2
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
-
"use strict";const fs=require("node:fs"),path=require("node:path"),{execFileSync:execFileSync}=require("node:child_process"),prefs=(()=>{try{return require("../../client/prefs.js")}catch{return require("../vendor/prefs.js")}})(),credentials=(()=>{try{return require("../../client/credentials.js")}catch{return require("../vendor/credentials.js")}})(),localTransport=require("./local/local.js"),LOCAL_NAMESPACE="local",SETTINGS_FILE="settings.json",AEGIS_KEY_NAMESPACE="__aegis",LEGACY_AEGIS_NAMESPACE="aegis",QUICK_LAUNCHER_NAMESPACE="__quickLauncher",DEFAULT_QUICK_LAUNCHER_SHORTCUT="CmdOrCtrl+Shift+Space",VAULT_BACKEND_NAMESPACE="__vaultBackend",DEFAULT_VAULT_BACKEND="aegiscloud",VAULT_BACKEND_VALUES=Object.freeze(["aegiscloud","drive","off"]),CONFIRM_MODE_NAMESPACE="__confirmMode",MEMORY_PERSIST_NAMESPACE="__memoryPersist",AVATAR_NAMESPACE="__avatar",TELEMETRY_NAMESPACE="__telemetry",AUTO_DRAIN_NAMESPACE="__autoDrain",AUTO_MINT_NAMESPACE="__autoMint",AUTO_DRAIN_INTERVAL_DEFAULT_MS=6e4,AUTO_DRAIN_INTERVAL_MIN_MS=15e3,AUTO_DRAIN_INTERVAL_MAX_MS=18e5,RESERVED_NAMESPACES=Object.freeze(["__aegis","aegis","__quickLauncher","__vaultBackend","__confirmMode","__memoryPersist","__avatar","__telemetry","__autoDrain","__autoMint"]),AVATAR_MOTION_MODES=Object.freeze(["system","full","minimal"]);function isReservedNamespace(e){return RESERVED_NAMESPACES.includes(e)}function maskKey(e){return e?e.length<=10?"configured":`${e.slice(0,9)}…${e.slice(-4)}`:null}const IS_WIN32="win32"===process.platform;function restrictFile(e){if(IS_WIN32){const n=process.env.USERNAME||process.env.USER||process.env.USERDOMAIN;if(!n)return void console.error(`[settings] cannot restrict ${e}: no current user to grant (USERNAME unset)`);try{execFileSync("icacls",[e,"/inheritance:r","/grant:r",`${n}:(F)`],{stdio:"ignore"})}catch(n){console.error(`[settings] failed to restrict ACL on ${e}: ${n.message}`)}}else try{fs.chmodSync(e,384)}catch(n){console.error(`[settings] failed to chmod ${e} to 0600: ${n.message}`)}}function createSettingsStore({dir:e,safeStorage:n,prefsDir:t,env:r}={}){if(!e)throw new Error("createSettingsStore requires a storage dir");const o=path.join(e,SETTINGS_FILE),i=(()=>{const e=null==t?"":String(t).trim();return e?path.resolve(e):credentials.aegisHome(r)})(),s=(()=>{try{return prefs.adopt({dir:i,legacyDir:e})}catch(e){return(process.env.AEGISCODE_DEBUG||process.env.AEGIS_HIST_DEBUG)&&process.stderr.write(`aegis-desktop: shared-preference adoption failed: ${e.message}\n`),{adopted:!1,keys:[],reason:`adoption failed: ${e.message}`}}})();function a(){try{return prefs.load({dir:i})}catch{return{}}}function c(e){if(!prefs.SHARED_PREF_KEYS.includes(e))throw new Error(`"${e}" is not a shared preference (see client/prefs.js SHARED_PREF_KEYS)`);const n=a()[e];return void 0===n?null:n}const u=()=>Boolean(n&&"function"==typeof n.isEncryptionAvailable&&n.isEncryptionAvailable());function _(e){return null==e?null:u()?n.encryptString(String(e)).toString("base64"):Buffer.from(String(e),"utf8").toString("base64")}function l(e){if(!e)return null;try{const t=Buffer.from(String(e),"base64");return u()?n.decryptString(t):t.toString("utf8")}catch{return null}}function d(){try{return JSON.parse(fs.readFileSync(o,"utf8"))||{}}catch{return{}}}function f(e){fs.mkdirSync(path.dirname(o),{recursive:!0});const n=`${o}.tmp-${process.pid}`;fs.writeFileSync(n,JSON.stringify(e,null,2),{mode:384}),fs.renameSync(n,o),restrictFile(o)}function A(e){if(isReservedNamespace(e))throw new Error(`reserved namespace "${e}" is not a provider config — use setAegisKey()/aegisRawKey() for the AEGIS key`)}function E(e){const n=d()[e]||{},t=l(n.key);return{provider:e,baseURL:n.baseURL||"",configured:Boolean(t),keyMask:maskKey(t)}}function S(){const e=l((d().__aegis||{}).key);return{configured:Boolean(e),keyMask:maskKey(e)}}function m(){const e=d().__quickLauncher||{},n="string"==typeof e.shortcut&&e.shortcut.trim()?e.shortcut.trim():"CmdOrCtrl+Shift+Space";return{enabled:Boolean(e.enabled),shortcut:n}}function M(){const e=d().__vaultBackend||{};return{backend:VAULT_BACKEND_VALUES.includes(e.backend)?e.backend:"aegiscloud"}}function p(){const e=a();if("boolean"==typeof e.confirmMode)return{enabled:e.confirmMode,source:"config"};const n=d().__confirmMode||{};return void 0===n.enabled?{enabled:!0,source:"default"}:{enabled:Boolean(n.enabled),source:"config"}}function y(){const e=a().sandboxPolicy;return e&&"object"==typeof e?e:null}function g(){const e=a();return"string"==typeof e.permissionMode?e.permissionMode:null}function N(){return!0===(d().__telemetry||{}).enabled}function b(){const e=a();if("boolean"==typeof e.memoryPersist)return{enabled:e.memoryPersist,source:"config"};const n=d().__memoryPersist||{};return void 0===n.enabled?{enabled:!0,source:"default"}:{enabled:Boolean(n.enabled),source:"config"}}function v(){const e=d().__avatar||{};return{enabled:void 0===e.enabled||Boolean(e.enabled),showLevel:void 0===e.showLevel||Boolean(e.showLevel),motion:AVATAR_MOTION_MODES.includes(e.motion)?e.motion:"system"}}function R(){const e=d().__avatar||{};return{...v(),source:void 0===e.enabled?"default":"config"}}function T(e){const n=Number(e);if(!Number.isFinite(n))return 6e4;const t=Math.round(n);return t<15e3||t>18e5?6e4:t}function h(){const e=d().__autoDrain||{};return{enabled:!1!==e.enabled,intervalMs:T(e.intervalMs)}}function C(){const e=d().__autoDrain||{};return{...h(),source:void 0===e.enabled?"default":"config"}}function I(){const e=d().__autoMint||{};return{enabled:!1!==e.enabled,publish:!0===e.publish}}function L(){const e=d().__autoMint||{};return{...I(),source:void 0===e.enabled?"default":"config"}}return{file:o,sharedDir:i,adoption:s,sharedFile:function(){return prefs.prefsFile({dir:i})},getSharedPref:c,setSharedPref:function(e,n){if(!prefs.SHARED_PREF_KEYS.includes(e))throw new Error(`"${e}" is not a shared preference (see client/prefs.js SHARED_PREF_KEYS)`);return prefs.set({[e]:n},{dir:i}),c(e)},get:E,set:function(e,{baseURL:n,key:t}={}){A(e);let r=n;if("local"===e&&n){const e=localTransport.remoteRefusal(n);if(e)throw e;r=localTransport.normalizeBase(n)}const o=d(),i=o[e]||{};return void 0!==r&&(i.baseURL=r),void 0!==t&&(i.key=t?_(t):null),o[e]=i,f(o),E(e)},rawKey:function(e){return l((d()[e]||{}).key)},remove:function(e){A(e);const n=d();return delete n[e],f(n),{ok:!0}},list:function(){const e=d();return Object.keys(e).filter((e=>!isReservedNamespace(e))).map((e=>E(e)))},maskKey:maskKey,aegisKey:S,aegisRawKey:function(){return l((d().__aegis||{}).key)},aegisKeySavedAt:function(){return(d().__aegis||{}).savedAt||null},setAegisKey:function(e){const n=d();return n.__aegis={...n.__aegis||{},key:e?_(e):null,savedAt:e?(new Date).toISOString():null},f(n),S()},migrateLegacyAegisKey:function(){try{const e=d();if(!e.aegis)return{migrated:!1};const n=e.aegis||{},t=e.__aegis||{},r={...e};return n.key&&!t.key&&(r.__aegis={...t,key:n.key}),delete r.aegis,f(r),{migrated:!0}}catch{return{migrated:!1}}},quickLauncherConfig:m,setQuickLauncherConfig:function({enabled:e,shortcut:n}={}){const t=d();return t.__quickLauncher={enabled:Boolean(e),shortcut:"string"==typeof n&&n.trim()?n.trim():"CmdOrCtrl+Shift+Space"},f(t),m()},vaultBackendConfig:M,setVaultBackendConfig:function(e){if(!VAULT_BACKEND_VALUES.includes(e))return M();const n=d();return n.__vaultBackend={backend:e},f(n),M()},getConfirmMode:function(){return p().enabled},setConfirmMode:function(e){prefs.set({confirmMode:Boolean(e)},{dir:i});const n=d();return void 0!==n.__confirmMode&&(delete n.__confirmMode,f(n)),p().enabled},confirmModeState:p,getPermissionMode:g,setPermissionMode:function(e){if(null==e||""===e||"off"===e||"none"===e)return prefs.remove("permissionMode",{dir:i}),null;const n=String(e),t=function(){const e=[path.join(__dirname,"..","..","one","src","permissions.js"),path.join(__dirname,"..","vendor","one","src","permissions.js")];for(const n of e)try{const e=require(n);if(e&&Array.isArray(e.PERMISSION_MODES)&&e.PERMISSION_MODES.length)return[...e.PERMISSION_MODES]}catch{}return["acceptEdits","auto","bypassPermissions","manual","dontAsk","plan"]}();if(!t.includes(n))throw new Error(`"${n}" is not one of ${t.join("|")} (or 'off' to clear it)`);return prefs.set({permissionMode:n},{dir:i}),g()},getSandboxPolicy:y,setSandboxPolicy:function(e){return e&&"object"==typeof e?(prefs.set({sandboxPolicy:e},{dir:i}),y()):(prefs.set({sandboxPolicy:null},{dir:i}),null)},getTelemetryOptIn:N,setTelemetryOptIn:function(e){const n=d();return n.__telemetry={enabled:Boolean(e)},f(n),N()},getMemoryPersist:function(){return b().enabled},memoryPersistState:b,setMemoryPersist:function(e){prefs.set({memoryPersist:Boolean(e)},{dir:i});const n=d();return void 0!==n.__memoryPersist&&(delete n.__memoryPersist,f(n)),b()},getAvatar:v,avatarState:R,setAvatar:function(e={}){const n=v(),t=e&&"object"==typeof e?e:{},r={enabled:void 0===t.enabled?n.enabled:Boolean(t.enabled),showLevel:void 0===t.showLevel?n.showLevel:Boolean(t.showLevel),motion:AVATAR_MOTION_MODES.includes(t.motion)?t.motion:n.motion},o=d();return o.__avatar=r,f(o),R()},getAutoDrain:h,autoDrainState:C,setAutoDrain:function(e={}){const n=h(),t=e&&"object"==typeof e?e:{},r=d();return r.__autoDrain={enabled:void 0===t.enabled?n.enabled:Boolean(t.enabled),intervalMs:void 0===t.intervalMs?n.intervalMs:T(t.intervalMs)},f(r),C()},getAutoMint:I,autoMintState:L,setAutoMint:function(e={}){const n=I(),t=e&&"object"==typeof e?e:{},r=d();return r.__autoMint={enabled:void 0===t.enabled?n.enabled:Boolean(t.enabled),publish:void 0===t.publish?n.publish:Boolean(t.publish)},f(r),L()},clampAutoDrainInterval:T}}module.exports={SETTINGS_FILE:SETTINGS_FILE,AEGIS_KEY_NAMESPACE:"__aegis",LEGACY_AEGIS_NAMESPACE:"aegis",QUICK_LAUNCHER_NAMESPACE:"__quickLauncher",VAULT_BACKEND_NAMESPACE:"__vaultBackend",CONFIRM_MODE_NAMESPACE:"__confirmMode",MEMORY_PERSIST_NAMESPACE:"__memoryPersist",AVATAR_NAMESPACE:"__avatar",TELEMETRY_NAMESPACE:"__telemetry",AUTO_DRAIN_NAMESPACE:"__autoDrain",AUTO_MINT_NAMESPACE:"__autoMint",AUTO_DRAIN_INTERVAL_DEFAULT_MS:6e4,AUTO_DRAIN_INTERVAL_MIN_MS:15e3,AUTO_DRAIN_INTERVAL_MAX_MS:18e5,AVATAR_MOTION_MODES:AVATAR_MOTION_MODES,DEFAULT_QUICK_LAUNCHER_SHORTCUT:"CmdOrCtrl+Shift+Space",DEFAULT_VAULT_BACKEND:"aegiscloud",VAULT_BACKEND_VALUES:VAULT_BACKEND_VALUES,RESERVED_NAMESPACES:RESERVED_NAMESPACES,isReservedNamespace:isReservedNamespace,maskKey:maskKey,createSettingsStore:createSettingsStore};
|
|
3
|
+
"use strict";const fs=require("node:fs"),path=require("node:path"),{execFileSync:execFileSync}=require("node:child_process"),prefs=(()=>{try{return require("../../client/prefs.js")}catch{return require("../vendor/prefs.js")}})(),credentials=(()=>{try{return require("../../client/credentials.js")}catch{return require("../vendor/credentials.js")}})(),localTransport=require("./local/local.js"),LOCAL_NAMESPACE="local",SETTINGS_FILE="settings.json",AEGIS_KEY_NAMESPACE="__aegis",LEGACY_AEGIS_NAMESPACE="aegis",QUICK_LAUNCHER_NAMESPACE="__quickLauncher",DEFAULT_QUICK_LAUNCHER_SHORTCUT="CmdOrCtrl+Shift+Space",VAULT_BACKEND_NAMESPACE="__vaultBackend",DEFAULT_VAULT_BACKEND="aegiscloud",VAULT_BACKEND_VALUES=Object.freeze(["aegiscloud","drive","off"]),CONFIRM_MODE_NAMESPACE="__confirmMode",FONT_SCALE_NAMESPACE="__fontScale",ACCENT_NAMESPACE="__accent",MEMORY_PERSIST_NAMESPACE="__memoryPersist",AVATAR_NAMESPACE="__avatar",TELEMETRY_NAMESPACE="__telemetry",AUTO_DRAIN_NAMESPACE="__autoDrain",AUTO_MINT_NAMESPACE="__autoMint",AUTO_DRAIN_INTERVAL_DEFAULT_MS=6e4,AUTO_DRAIN_INTERVAL_MIN_MS=15e3,AUTO_DRAIN_INTERVAL_MAX_MS=18e5,RESERVED_NAMESPACES=Object.freeze(["__aegis","aegis","__quickLauncher","__vaultBackend","__confirmMode","__memoryPersist","__avatar","__telemetry","__autoDrain","__autoMint"]),AVATAR_MOTION_MODES=Object.freeze(["system","full","minimal"]);function isReservedNamespace(e){return RESERVED_NAMESPACES.includes(e)}function maskKey(e){return e?e.length<=10?"configured":`${e.slice(0,9)}…${e.slice(-4)}`:null}const IS_WIN32="win32"===process.platform;function restrictFile(e){if(IS_WIN32){const n=process.env.USERNAME||process.env.USER||process.env.USERDOMAIN;if(!n)return void console.error(`[settings] cannot restrict ${e}: no current user to grant (USERNAME unset)`);try{execFileSync("icacls",[e,"/inheritance:r","/grant:r",`${n}:(F)`],{stdio:"ignore"})}catch(n){console.error(`[settings] failed to restrict ACL on ${e}: ${n.message}`)}}else try{fs.chmodSync(e,384)}catch(n){console.error(`[settings] failed to chmod ${e} to 0600: ${n.message}`)}}function createSettingsStore({dir:e,safeStorage:n,prefsDir:t,env:r}={}){if(!e)throw new Error("createSettingsStore requires a storage dir");const o=path.join(e,SETTINGS_FILE),i=(()=>{const e=null==t?"":String(t).trim();return e?path.resolve(e):credentials.aegisHome(r)})(),s=(()=>{try{return prefs.adopt({dir:i,legacyDir:e})}catch(e){return(process.env.AEGISCODE_DEBUG||process.env.AEGIS_HIST_DEBUG)&&process.stderr.write(`aegis-desktop: shared-preference adoption failed: ${e.message}\n`),{adopted:!1,keys:[],reason:`adoption failed: ${e.message}`}}})();function a(){try{return prefs.load({dir:i})}catch{return{}}}function c(e){if(!prefs.SHARED_PREF_KEYS.includes(e))throw new Error(`"${e}" is not a shared preference (see client/prefs.js SHARED_PREF_KEYS)`);const n=a()[e];return void 0===n?null:n}const u=()=>Boolean(n&&"function"==typeof n.isEncryptionAvailable&&n.isEncryptionAvailable());function _(e){return null==e?null:u()?n.encryptString(String(e)).toString("base64"):Buffer.from(String(e),"utf8").toString("base64")}function l(e){if(!e)return null;try{const t=Buffer.from(String(e),"base64");return u()?n.decryptString(t):t.toString("utf8")}catch{return null}}function d(){try{return JSON.parse(fs.readFileSync(o,"utf8"))||{}}catch{return{}}}function f(e){fs.mkdirSync(path.dirname(o),{recursive:!0});const n=`${o}.tmp-${process.pid}`;fs.writeFileSync(n,JSON.stringify(e,null,2),{mode:384}),fs.renameSync(n,o),restrictFile(o)}function A(e){if(isReservedNamespace(e))throw new Error(`reserved namespace "${e}" is not a provider config — use setAegisKey()/aegisRawKey() for the AEGIS key`)}function E(e){const n=d()[e]||{},t=l(n.key);return{provider:e,baseURL:n.baseURL||"",configured:Boolean(t),keyMask:maskKey(t)}}function S(){const e=l((d().__aegis||{}).key);return{configured:Boolean(e),keyMask:maskKey(e)}}function m(e){return Number.isFinite(e)?Math.min(1.3,Math.max(.85,Math.round(100*e)/100)):1}function M(){return m((d().__fontScale||{}).scale)}const p=["default","cobalt","amber"];function g(e){const n="string"==typeof e?e.trim().toLowerCase():"";return p.includes(n)?n:"default"}function y(){return g((d().__accent||{}).name)}function N(){const e=d().__quickLauncher||{},n="string"==typeof e.shortcut&&e.shortcut.trim()?e.shortcut.trim():"CmdOrCtrl+Shift+Space";return{enabled:Boolean(e.enabled),shortcut:n}}function b(){const e=d().__vaultBackend||{};return{backend:VAULT_BACKEND_VALUES.includes(e.backend)?e.backend:"aegiscloud"}}function v(){const e=a();if("boolean"==typeof e.confirmMode)return{enabled:e.confirmMode,source:"config"};const n=d().__confirmMode||{};return void 0===n.enabled?{enabled:!0,source:"default"}:{enabled:Boolean(n.enabled),source:"config"}}function C(){const e=a().sandboxPolicy;return e&&"object"==typeof e?e:null}function T(){const e=a();return"string"==typeof e.permissionMode?e.permissionMode:null}function h(){return!0===(d().__telemetry||{}).enabled}function R(){const e=a();if("boolean"==typeof e.memoryPersist)return{enabled:e.memoryPersist,source:"config"};const n=d().__memoryPersist||{};return void 0===n.enabled?{enabled:!0,source:"default"}:{enabled:Boolean(n.enabled),source:"config"}}function I(){const e=d().__avatar||{};return{enabled:void 0===e.enabled||Boolean(e.enabled),showLevel:void 0===e.showLevel||Boolean(e.showLevel),motion:AVATAR_MOTION_MODES.includes(e.motion)?e.motion:"system"}}function L(){const e=d().__avatar||{};return{...I(),source:void 0===e.enabled?"default":"config"}}function D(e){const n=Number(e);if(!Number.isFinite(n))return 6e4;const t=Math.round(n);return t<15e3||t>18e5?6e4:t}function P(){const e=d().__autoDrain||{};return{enabled:!1!==e.enabled,intervalMs:D(e.intervalMs)}}function O(){const e=d().__autoDrain||{};return{...P(),source:void 0===e.enabled?"default":"config"}}function U(){const e=d().__autoMint||{};return{enabled:!1!==e.enabled,publish:!0===e.publish}}function k(){const e=d().__autoMint||{};return{...U(),source:void 0===e.enabled?"default":"config"}}return{file:o,sharedDir:i,adoption:s,sharedFile:function(){return prefs.prefsFile({dir:i})},getSharedPref:c,setSharedPref:function(e,n){if(!prefs.SHARED_PREF_KEYS.includes(e))throw new Error(`"${e}" is not a shared preference (see client/prefs.js SHARED_PREF_KEYS)`);return prefs.set({[e]:n},{dir:i}),c(e)},get:E,set:function(e,{baseURL:n,key:t}={}){A(e);let r=n;if("local"===e&&n){const e=localTransport.remoteRefusal(n);if(e)throw e;r=localTransport.normalizeBase(n)}const o=d(),i=o[e]||{};return void 0!==r&&(i.baseURL=r),void 0!==t&&(i.key=t?_(t):null),o[e]=i,f(o),E(e)},rawKey:function(e){return l((d()[e]||{}).key)},remove:function(e){A(e);const n=d();return delete n[e],f(n),{ok:!0}},list:function(){const e=d();return Object.keys(e).filter((e=>!isReservedNamespace(e))).map((e=>E(e)))},maskKey:maskKey,aegisKey:S,aegisRawKey:function(){return l((d().__aegis||{}).key)},aegisKeySavedAt:function(){return(d().__aegis||{}).savedAt||null},setAegisKey:function(e){const n=d();return n.__aegis={...n.__aegis||{},key:e?_(e):null,savedAt:e?(new Date).toISOString():null},f(n),S()},migrateLegacyAegisKey:function(){try{const e=d();if(!e.aegis)return{migrated:!1};const n=e.aegis||{},t=e.__aegis||{},r={...e};return n.key&&!t.key&&(r.__aegis={...t,key:n.key}),delete r.aegis,f(r),{migrated:!0}}catch{return{migrated:!1}}},quickLauncherConfig:N,setQuickLauncherConfig:function({enabled:e,shortcut:n}={}){const t=d();return t.__quickLauncher={enabled:Boolean(e),shortcut:"string"==typeof n&&n.trim()?n.trim():"CmdOrCtrl+Shift+Space"},f(t),N()},vaultBackendConfig:b,setVaultBackendConfig:function(e){if(!VAULT_BACKEND_VALUES.includes(e))return b();const n=d();return n.__vaultBackend={backend:e},f(n),b()},getConfirmMode:function(){return v().enabled},setConfirmMode:function(e){prefs.set({confirmMode:Boolean(e)},{dir:i});const n=d();return void 0!==n.__confirmMode&&(delete n.__confirmMode,f(n)),v().enabled},confirmModeState:v,getFontScale:M,setFontScale:function(e){const n=d();return n.__fontScale={scale:m(e)},f(n),M()},clampFontScale:m,getAccent:y,setAccent:function(e){const n=d();return n.__accent={name:g(e)},f(n),y()},clampAccent:g,ACCENT_SKINS:p,getPermissionMode:T,setPermissionMode:function(e){if(null==e||""===e||"off"===e||"none"===e)return prefs.remove("permissionMode",{dir:i}),null;const n=String(e),t=function(){const e=[path.join(__dirname,"..","..","one","src","permissions.js"),path.join(__dirname,"..","vendor","one","src","permissions.js")];for(const n of e)try{const e=require(n);if(e&&Array.isArray(e.PERMISSION_MODES)&&e.PERMISSION_MODES.length)return[...e.PERMISSION_MODES]}catch{}return["acceptEdits","auto","bypassPermissions","manual","dontAsk","plan"]}();if(!t.includes(n))throw new Error(`"${n}" is not one of ${t.join("|")} (or 'off' to clear it)`);return prefs.set({permissionMode:n},{dir:i}),T()},getSandboxPolicy:C,setSandboxPolicy:function(e){return e&&"object"==typeof e?(prefs.set({sandboxPolicy:e},{dir:i}),C()):(prefs.set({sandboxPolicy:null},{dir:i}),null)},getTelemetryOptIn:h,setTelemetryOptIn:function(e){const n=d();return n.__telemetry={enabled:Boolean(e)},f(n),h()},getMemoryPersist:function(){return R().enabled},memoryPersistState:R,setMemoryPersist:function(e){prefs.set({memoryPersist:Boolean(e)},{dir:i});const n=d();return void 0!==n.__memoryPersist&&(delete n.__memoryPersist,f(n)),R()},getAvatar:I,avatarState:L,setAvatar:function(e={}){const n=I(),t=e&&"object"==typeof e?e:{},r={enabled:void 0===t.enabled?n.enabled:Boolean(t.enabled),showLevel:void 0===t.showLevel?n.showLevel:Boolean(t.showLevel),motion:AVATAR_MOTION_MODES.includes(t.motion)?t.motion:n.motion},o=d();return o.__avatar=r,f(o),L()},getAutoDrain:P,autoDrainState:O,setAutoDrain:function(e={}){const n=P(),t=e&&"object"==typeof e?e:{},r=d();return r.__autoDrain={enabled:void 0===t.enabled?n.enabled:Boolean(t.enabled),intervalMs:void 0===t.intervalMs?n.intervalMs:D(t.intervalMs)},f(r),O()},getAutoMint:U,autoMintState:k,setAutoMint:function(e={}){const n=U(),t=e&&"object"==typeof e?e:{},r=d();return r.__autoMint={enabled:void 0===t.enabled?n.enabled:Boolean(t.enabled),publish:void 0===t.publish?n.publish:Boolean(t.publish)},f(r),k()},clampAutoDrainInterval:D}}module.exports={SETTINGS_FILE:SETTINGS_FILE,AEGIS_KEY_NAMESPACE:"__aegis",LEGACY_AEGIS_NAMESPACE:"aegis",QUICK_LAUNCHER_NAMESPACE:"__quickLauncher",VAULT_BACKEND_NAMESPACE:"__vaultBackend",CONFIRM_MODE_NAMESPACE:"__confirmMode",MEMORY_PERSIST_NAMESPACE:"__memoryPersist",AVATAR_NAMESPACE:"__avatar",TELEMETRY_NAMESPACE:"__telemetry",AUTO_DRAIN_NAMESPACE:"__autoDrain",AUTO_MINT_NAMESPACE:"__autoMint",AUTO_DRAIN_INTERVAL_DEFAULT_MS:6e4,AUTO_DRAIN_INTERVAL_MIN_MS:15e3,AUTO_DRAIN_INTERVAL_MAX_MS:18e5,AVATAR_MOTION_MODES:AVATAR_MOTION_MODES,DEFAULT_QUICK_LAUNCHER_SHORTCUT:"CmdOrCtrl+Shift+Space",DEFAULT_VAULT_BACKEND:"aegiscloud",VAULT_BACKEND_VALUES:VAULT_BACKEND_VALUES,RESERVED_NAMESPACES:RESERVED_NAMESPACES,isReservedNamespace:isReservedNamespace,maskKey:maskKey,createSettingsStore:createSettingsStore};
|