aegis-desktop 1.0.34 → 1.0.35
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/lib/local/check-command.js +3 -0
- package/lib/local/engine.js +1 -1
- package/lib/local/integrity.js +1 -1
- package/lib/local/perm-store.js +7 -2
- package/lib/local/prompt.js +1 -1
- package/lib/local/repeat-guard.js +3 -0
- package/lib/local/tools.js +185 -1
- package/lib/local/verify-stop.js +3 -0
- package/lib/sync/persist-gate.js +1 -1
- package/lib/sync/sessions.js +1 -1
- package/main.js +133 -32
- package/package.json +3 -2
- package/preload.js +1 -1
- package/renderer/app.js +3 -3
- package/renderer/index.html +43 -15
- package/renderer/library.js +3 -0
- package/renderer/style.css +149 -0
- package/vendor/faces/cli/package.json +1 -1
- package/vendor/faces/cli/src/chatflow.js +1 -1
- package/vendor/faces/cli/src/commands.js +2 -2
- package/vendor/faces/cli/src/limits.js +1 -1
- package/vendor/faces/cli/src/permissions.js +1 -1
- package/vendor/faces/cli/src/provenance.lock.json +2 -2
- package/vendor/faces/cli/vendor/desktop/lib/local/check-command.js +3 -0
- package/vendor/faces/cli/vendor/desktop/lib/local/engine.js +1 -1
- package/vendor/faces/cli/vendor/desktop/lib/local/integrity.js +1 -1
- package/vendor/faces/cli/vendor/desktop/lib/local/perm-store.js +1 -1
- package/vendor/faces/cli/vendor/desktop/lib/local/prompt.js +1 -1
- package/vendor/faces/cli/vendor/desktop/lib/local/repeat-guard.js +3 -0
- package/vendor/faces/cli/vendor/desktop/lib/local/tools.js +1 -1
- package/vendor/faces/cli/vendor/desktop/lib/local/verify-stop.js +3 -0
- package/vendor/faces/cli/vendor/desktop/main.js +3 -3
- package/vendor/sandbox/provenance.json +7 -7
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
|
+
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
+
"use strict";const fs=require("node:fs"),path=require("node:path");function readJson(t,e){try{return JSON.parse(fs.readFileSync(path.join(e,t),"utf8"))}catch{return null}}function exists(t,e){try{return fs.existsSync(path.join(t,e))}catch{return!1}}function extOf(t){const e=String(t||"").split(/[/\\]/).pop()||"",s=e.lastIndexOf(".");return s<=0?"":e.slice(s).toLowerCase()}const TS_EXT=new Set([".ts",".tsx",".mts",".cts"]),JS_EXT=new Set([".js",".mjs",".cjs",".jsx"]);function safeRelPath(t){const e=String(t||"").replace(/\\/g,"/");return!e||e.length>400||e.startsWith("/")||/^[A-Za-z]:/.test(e)||/[\s;&|`$<>(){}[\]'"!*?~\0]/.test(e)||e.split("/").includes("..")?null:e}function detectCheckCommand(t,e){if(!t)return null;const s=extOf(e),n=safeRelPath(e),c=readJson("package.json",t);if(c&&c.scripts&&"object"==typeof c.scripts)for(const t of["typecheck","type-check","lint","check"])if("string"==typeof c.scripts[t])return{cmd:`npm run ${t}`,why:`package.json defines a "${t}" script`};return TS_EXT.has(s)&&exists(t,"tsconfig.json")?exists(t,path.join("node_modules",".bin","tsc"))||exists(t,path.join("node_modules","typescript"))?{cmd:"npx --no-install tsc --noEmit",why:"this repo has a tsconfig.json and a local TypeScript"}:n?{cmd:`node --check ${n}`,why:"no local TypeScript install, so this is a syntax check only"}:null:".js"!==s&&".mjs"!==s&&".cjs"!==s||!n?JS_EXT.has(s)&&exists(t,"node_modules",".bin","eslint")?{cmd:"npx --no-install eslint .",why:"this repo has a local ESLint"}:".py"===s?n?{cmd:`python -m py_compile ${n}`,why:"a stdlib syntax check — not a type check"}:null:".go"===s?{cmd:"go vet ./...",why:"Go ships its own vet"}:".rs"===s?{cmd:"cargo check",why:"Rust ships its own checker"}:".rb"===s&&n?{cmd:`ruby -c ${n}`,why:"a syntax check"}:null:{cmd:`node --check ${n}`,why:"parses the file without executing it"}}module.exports={detectCheckCommand:detectCheckCommand,safeRelPath:safeRelPath,extOf:extOf};
|
package/lib/local/engine.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{randomUUID:randomUUID}=require("node:crypto"),os=require("node:os"),fs=require("node:fs"),toolsModule=require("./tools.js"),attachmentsModule=require("./attachments.js"),{flattenContent:flattenContent}=attachmentsModule,promptModule=require("./prompt.js"),localTransport=require("./local.js"),{ShellSession:ShellSession}=require("./shell.js"),{planExec:planExec}=require("./exec-plan.js"),claudePro=require("./claude-pro.js"),{agentSystemPrompt:agentSystemPrompt,agentRoleLabel:agentRoleLabel}=require("./agents.js"),{beginTurnGuard:beginTurnGuard,recordWrite:recordWrite,blocksDestructive:blocksDestructive}=require("./turn-guard.js"),{acquireWorktreeLock:acquireWorktreeLock,releaseWorktreeLock:releaseWorktreeLock}=require("./worktree-lock.js"),covenant=require("./covenant.js");let envFile=null;try{envFile=require("../../../client/env-file.js")}catch{try{envFile=require("../../vendor/env-file.js")}catch{envFile=null}}let platformLib=null;try{platformLib=require("../../../client/platform.js")}catch{try{platformLib=require("../../vendor/platform.js")}catch{platformLib=null}}let credentialsLib=null;try{credentialsLib=require("../../../client/credentials.js")}catch{try{credentialsLib=require("../../vendor/credentials.js")}catch{credentialsLib=null}}const PRO_TOOL_MAP=Object.freeze({Write:"writeFile",Edit:"editFile",MultiEdit:"editFile",NotebookEdit:"editFile",Bash:"exec",BashOutput:"exec"}),PRO_PLAN_MODE_SAFE=Object.freeze(new Set(["Read","Glob","Grep"]));function proAskArgs(e,t){const o=e&&"object"==typeof e?e:{};return"exec"===t?"string"==typeof o.command?{command:o.command}:{}:"writeFile"===t?"string"==typeof o.file_path?{file_path:o.file_path,content:o.content}:{}:"editFile"===t?Array.isArray(o.edits)?{file_path:o.file_path,edits:o.edits}:"string"==typeof o.file_path?{file_path:o.file_path,old_string:o.old_string,new_string:o.new_string,replace_all:!0===o.replace_all}:{}:o}function normalizeToolArgs(e,t,o,n){const r=e&&"function"==typeof e.normalizeArgs&&e.normalizeArgs||"function"==typeof toolsModule.normalizeArgs&&toolsModule.normalizeArgs||null;return r?r(t,o,n):{ok:!0,args:o&&"object"==typeof o?o:{},error:null}}function detectVcs(e){if(!e)return null;try{const t=require("node:fs"),o=require("node:path");let n=o.resolve(String(e));for(let e=0;e<8;e+=1){if(t.existsSync(o.join(n,".git")))return"git";const e=o.dirname(n);if(e===n)break;n=e}return""}catch{return null}}function hostEnv(e={},t={},o=null){const n=e||{},r=t||{},s=(e,t)=>null!=r[e]?r[e]:t;let a=n.homedir,i=n.cwd;try{a||(a=os.homedir()),i||(i=process.cwd())}catch{}let l=n.shell,c=n.shellKind;try{if(!l||!c){const e=require("./shell.js").resolveSessionShell();l=l||e.cmd,c=c||e.kind}}catch{}let d=n.desktopdir;try{!d&&platformLib&&(d=platformLib.desktopDir())}catch{}let u=n.dataDir;try{!u&&credentialsLib&&(u=credentialsLib.aegisHome())}catch{}let f=n.locale,p=n.localeName;try{!f&&platformLib&&"function"==typeof platformLib.appLocale&&(f=platformLib.appLocale()),f&&!p&&platformLib&&"function"==typeof platformLib.languageName&&(p=platformLib.languageName(f))}catch{}return{platform:s("platform",n.platform||process.platform),arch:s("arch",n.arch||process.arch),homedir:s("homedir",a),desktopdir:s("desktopdir",d),dataDir:s("dataDir",u),locale:s("locale",f),localeName:s("localeName",p),languages:s("languages",n.languages),cwd:s("cwd",i),vcs:s("vcs",null!=n.vcs?n.vcs:detectVcs(i)),shell:s("shell",l),shellKind:s("shellKind",c),roots:s("roots",n.roots),appVersion:s("appVersion",n.appVersion),model:s("model",o&&o.model)}}function requireSharedBrain(){const e=[()=>require("../../../client/brain-catalog.js"),()=>require("../../vendor/brain-catalog.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}function requireSharedByokCatalog(){const e=[()=>require("../../../client/byok-catalog.js"),()=>require("../../vendor/byok-catalog.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}function requireSharedUserModels(){const e=[()=>require("../../../client/user-models.js"),()=>require("../../vendor/user-models.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}function requireSharedCatalogClient(){const e=[()=>require("../../../client/catalog-client.js"),()=>require("../../vendor/catalog-client.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}function requireSharedModelDiscovery(){const e=[()=>require("../../../client/model-discovery.js"),()=>require("../../vendor/model-discovery.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}const WORKTREE_LOCK_WAIT_MS=1500,MAX_SUBAGENT_DEPTH=4,CLASSES=[{class:"aegis",label:"Aegis Cloud",kind:"cloud"},{class:"byok",label:"Bring your own key",kind:"cloud"},{class:"local",label:"Local model",kind:"local"},{class:"pro",label:"Claude Code Pro",kind:"subscription"}],BYOK_NAMESPACE_PREFIX="byok:";function byokNamespace(e){return`${BYOK_NAMESPACE_PREFIX}${e}`}function splitByokModel(e){const t="string"==typeof e?e:"",o=t.indexOf(":");return o<0?{provider:"",model:t}:{provider:t.slice(0,o),model:t.slice(o+1)}}function providerKeyRecord(e){const t={key:"",env:"",rejected:null};if(!envFile||"function"!=typeof envFile.providerKeyFromEnv)return t;try{const o=envFile.providerKeyFromEnv(e)||t;return{key:"string"==typeof o.key?o.key:"",env:"string"==typeof o.env?o.env:"",rejected:"string"==typeof o.rejected&&o.rejected?o.rejected:null}}catch{return t}}function providerKeyFromEnv(e){if(!envFile||"function"!=typeof envFile.providerKeyFromEnv)return"";try{return envFile.providerKeyFromEnv(e).key||""}catch{return""}}const DEEPSEEK_REASONING_MODEL_RE=/^deepseek-(v4(\.\d+)?-(flash|pro)|flash|pro|reasoner)$/,EFFORT_TOKEN_BUDGET={low:8192,medium:16384,high:32768,max:32768},DEEPSEEK_EFFORT={low:"low",medium:"high",high:"high"},DEEPSEEK_EFFORT_EXTRA={max:"max"},EFFORT_IDENTITY={low:"low",medium:"medium",high:"high"},EFFORT_INERT_RE=/non-reasoning/i,EFFORT_DIALECTS=[{provider:"deepseek",re:DEEPSEEK_REASONING_MODEL_RE,field:"effort",map:DEEPSEEK_EFFORT,extra:DEEPSEEK_EFFORT_EXTRA},{provider:"openai",re:/^(gpt-5|o[0-9])/i,field:"reasoning_effort",map:EFFORT_IDENTITY},{provider:"groq",re:/^(openai\/gpt-oss|qwen\/qwen3)/i,field:"reasoning_effort",map:EFFORT_IDENTITY},{provider:"xai",re:/^grok-(4\.[5-9]|[5-9])/,field:"reasoning_effort",map:EFFORT_IDENTITY},{provider:"google",re:/^gemini-(2\.5|3|[4-9])/,field:"reasoning_effort",map:{...EFFORT_IDENTITY,medium:"high"}}],AUTONOMOUS_IDLE_TIMEOUT_MS=9e5;function reasoningBudget(e,t,o){const n=Number(t);return Number.isFinite(n)&&n>0?n:DEEPSEEK_REASONING_MODEL_RE.test(String(e||""))?EFFORT_TOKEN_BUDGET["low"===o||"medium"===o||"max"===o?o:"high"]:void 0}function nativeEffort(e,t,o){const n=String(t||"");if(EFFORT_INERT_RE.test(n))return;if(null===o)return;const r="low"===o||"medium"===o?o:"max"===o?"max":"high";for(const t of EFFORT_DIALECTS)if(t.provider===e&&t.re.test(n)){const e=Object.prototype.hasOwnProperty.call(t.map,r)?t.map[r]:t.extra&&Object.prototype.hasOwnProperty.call(t.extra,r)?t.extra[r]:void 0;if(void 0===e)return;return{field:t.field,level:e}}}function normalizeCatalog(e){return Array.isArray(e)?e.map((e=>"string"==typeof e?{id:e}:e)).filter((e=>e&&e.id)):[]}const{offerableCatalog:offerableCatalog}=requireSharedBrain(),{withByokAdditions:withByokAdditions,canonicalModelId:canonicalModelId,nexusFallbackModel:nexusFallbackModel}=requireSharedByokCatalog(),{withUserModels:withUserModels,unmatchedUserProviders:unmatchedUserProviders,load:loadUserModels,addUserModel:addUserModel,removeUserModel:removeUserModel}=requireSharedUserModels(),{withCatalog:withCatalog}=requireSharedCatalogClient(),{discoverModels:discoverVendorModels,canDiscover:canDiscoverVendorModels,endpointFor:vendorEndpointFor,discoverableProviders:discoverableProviders}=requireSharedModelDiscovery();function parseArgs(e){if(null==e)return{};if("object"==typeof e)return e;try{const t=JSON.parse(String(e));return t&&"object"==typeof t?t:{}}catch{return{}}}function extractToolCalls(e){if(!e)return[];if(Array.isArray(e.toolCalls)&&e.toolCalls.length)return e.toolCalls.map((e=>({id:e.id||"",name:e.name||"",args:parseArgs(e.args)}))).filter((e=>e.name));const t=e.choices&&e.choices[0]&&e.choices[0].message,o=t&&t.tool_calls||[];return Array.isArray(o)?o.map((e=>{const t=e&&e.function||{};return{id:e&&e.id||"",name:t.name||e&&e.name||"",args:parseArgs(t.arguments)}})).filter((e=>e.name)):[]}function proTurnPrompt(e){const t=Array.isArray(e.prompt)?flattenContent(e.prompt):e.prompt;if("string"==typeof t&&t.trim())return t;const o=Array.isArray(e.messages)?e.messages:[];for(let e=o.length-1;e>=0;e-=1){const t=o[e];if(!t||"user"!==t.role)continue;const n=flattenContent(t.content);if(n.trim())return n}return t}function assistantText(e){const t=e&&e.choices&&e.choices[0]&&e.choices[0].message;return t&&"string"==typeof t.content&&t.content||""}function finishReasonOf(e){const t=e&&e.choices&&e.choices[0];return t&&t.finish_reason||e&&e.stop_reason||""}function isTruncated(e){const t=finishReasonOf(e);return"length"===t||"max_tokens"===t}function reasoningTextOf(e){if(!e)return"";const t=e.choices&&e.choices[0],o=t&&t.message||{};if(Array.isArray(o.content)){const e=o.content.filter((e=>e&&("thinking"===e.type||"reasoning"===e.type))).map((e=>e.thinking||e.text||"")).join("");if(e)return e}const n=o.content&&"object"==typeof o.content?o.content.reasoning_content:"",r=[o.reasoning_content,o.reasoning,t&&t.reasoning_content,e.reasoning_content,e.reasoning,n];for(const e of r)if("string"==typeof e&&e)return e;return""}function reasoningTokensOf(e){if(!e)return 0;const t=e.choices&&e.choices[0],o=t&&t.message||{},n=e.usage||{},r=n.completion_tokens_details||n.output_tokens_details||{},s=[o.thinking_tokens,o.reasoning_tokens,t&&t.thinking_tokens,e.thinking_tokens,r.reasoning_tokens,r.thinking_tokens];for(const e of s)if("number"==typeof e&&Number.isFinite(e)&&e>0)return e;return 0}function reasonedButSilent(e){return!assistantText(e)&&(""!==reasoningTextOf(e)||reasoningTokensOf(e)>0)}const REASONING_RETRY_FLOOR=32768;function retryBudgetFor(e,t){const o=doubledBudget(e.maxTokens);return t&&ladderRung(e.maxTokens)?Math.max(o,REASONING_RETRY_FLOOR):o}function ladderRung(e){const t=Number(e);return Number.isFinite(t)&&Object.values(EFFORT_TOKEN_BUDGET).includes(t)}function doubledBudget(e){const t=Number(e)||0;return t>0?2*t:8192}function statedCapOf(e){const t=e=>{const t=Number(e);return Number.isFinite(t)&&t>0?t:void 0};return e&&Object.prototype.hasOwnProperty.call(e,"statedMaxTokens")?t(e.statedMaxTokens):t(e&&e.maxTokens)}const EMPTY_TURN_NUDGE="Your previous reply came back empty — it contained no answer and no tool call. Write your answer now, using only the information already gathered above. No tools are available in this reply, so do not call any: respond in plain prose or markdown.",THOUGHT_ONLY_NUDGE="Your previous round was spent entirely on hidden reasoning and produced no visible reply. Answer the user directly and briefly now. Do not reason, explain, or think first — write only the answer, no tools.",FINAL_ANSWER_NUDGE="Write your answer now, in plain prose, using only what is already in this conversation. If your information is incomplete, say what you have and what is missing — an incomplete answer is the expected outcome here and is better than none. No tools, no preface.",RECOVERY_ROUNDS=2,UNMUTATED_TURN_NUDGE="You ended the turn without changing any file, but this request asked for a change. The tools are still available in this reply: make the edit now with editFile or writeFile. If you already know what to change, change it — describing the fix is not the fix. If you genuinely cannot, say precisely what blocks you.",MUTATION_INTENT_RE=new RegExp("\\b(?:fix|implement|add|create|write|refactor|rename|remove|delete|replace|update|patch|migrate|convert|make\\s+(?:it|them|this|that|the|sure)|change|correct|resolve|repair|address|apply|introduce|support|wire\\s+up)\\b","i");function wantsMutation(e,t,o){if(t)return!1;if(!(o>0))return!1;const n=String(e||"");return!!n.trim()&&!/\?\s*$/.test(n.trim())&&MUTATION_INTENT_RE.test(n)}function emptyTurnError({cls:e,model:t,finishReason:o,reasoningChars:n,reasoningTokens:r,effort:s,recoveryRounds:a}){const i=Number(a)||0,l=Number(r)||0,c=new Error(`The model returned no answer after ${e}/${t} was asked to summarise its results`+(i?`, and ${i} extra recovery call${1===i?"":"s"} with a larger budget and a changed ask came back empty too`:"")+` (stop reason: ${o||"none"}`+(s?`, effort: ${s}`:"")+(n?`, hidden reasoning: ${n} chars and no visible text`:l>0?`, ~${l} thinking tokens billed and no visible text`:"")+"). "+(n||l>0?"Every one of those calls spent its output on hidden reasoning instead of writing a word, so this is the model rather than the budget: pick a model that answers without a thinking pass, or ask for a smaller piece of work.":"No visible text came back from any of those calls. Send the request again, in smaller pieces, or from a different model."));return c.status=502,c}function createLocalEngine({aegis:e,settings:t,tools:o,promptBuilder:n,recallProvider:r,env:s,getConfirmMode:a,getPermissionMode:i,sandbox:l,localTransport:c=localTransport,fetchImpl:d,gitScope:u,permissionRules:f}){const p=new Map,m=o||toolsModule,h=n&&n.buildSystemPrompt||promptModule.buildSystemPrompt,g=f&&"function"==typeof f.rulesVerdict?f.rulesVerdict:null,y=f&&"function"==typeof f.alwaysAllow?f.alwaysAllow:null,k=f&&"function"==typeof f.subjectFor?f.subjectFor:null,v=require("./session-rounds.js"),b=()=>{if("function"==typeof a)return!1!==a();if(t&&"function"==typeof t.getConfirmMode){const e=t.getConfirmMode();return void 0===e||Boolean(e)}return!0},w=()=>"function"==typeof i?"plan"===i():!(!t||"function"!=typeof t.getPermissionMode)&&"plan"===t.getPermissionMode();function E(e,t){return`${e} was not executed — this session is in plan mode (read-only). Plan mode may read files, search, run read-only shell commands and deploy subagents to research, but may not create, edit or delete files, run a mutating command, or install packages`+(t?` (this command: ${t})`:"")+". Do NOT retry it or attempt the same effect by another route. Finish your research and present a plan in plain text; the user exits plan mode (`/permissions mode off`) before any edit can run."}const _=new Map,T=new Map,S=new Map,x=200,A=new Map,M=require("./pro-sessions.js"),O=new Map,N=new Map;function F(e,t){if("function"!=typeof k)return e;let o="";try{o=String(k(e,t||{})||"")}catch{o=""}return`${e}\0${o}`}function R(e,t,o){_.has(e)||_.set(e,new Set),_.get(e).add(F(t,o))}function D(e,t){const o=T.get(e);return Boolean(o&&o.has(t))}function U(e,t){T.has(e)||T.set(e,new Set),T.get(e).add(t)}function I(e){if(!e)return null;try{return{existed:!0,content:fs.readFileSync(e,"utf8")}}catch(e){return e&&"ENOENT"===e.code?{existed:!1,content:null}:null}}function L(e){return`${e} was not executed — the user denied this tool for this conversation. Do NOT retry it and do NOT attempt the same effect by another route (another command, a writeFile instead of an edit, a subagent). Stop calling tools and reply in plain text: say what you were trying to do, what you need, and that the user can re-enable ${e} to let it proceed.`}function C(e,t,o,n){return new Promise((r=>{if(o&&o.aborted)return void r("cancel");const s=randomUUID();let a=!1;const i=()=>l("cancel"),l=e=>{a||(a=!0,O.delete(s),o&&o.removeEventListener("abort",i),r(e))};o&&o.addEventListener("abort",i,{once:!0}),O.set(s,{resolve:l}),"function"==typeof t?t({delta:"",approval:{id:s,sessionId:e,tool:n.tool,args:n.args,diff:n.diff||null,canPersist:"function"==typeof y}}):l("cancel")}))}function P(e,t,o,n){return new Promise((r=>{if(o&&o.aborted)return void r(!1);const s=randomUUID();let a=!1;const i=()=>l(!1),l=e=>{a||(a=!0,N.delete(s),o&&o.removeEventListener("abort",i),r(e))};o&&o.addEventListener("abort",i,{once:!0}),N.set(s,{resolve:l}),"function"==typeof t?t({delta:"",rounds:{id:s,sessionId:e,spent:n.spent,extensions:n.extensions,max:n.max,size:n.size}}):l(!1)}))}async function $(e,t,o,n,r){const s=normalizeToolArgs(m,e,t,o||{});if(!s.ok)return{ok:!1,error:s.error};t=s.args;const a=o&&o.guard;if(a&&"exec"===e){const e=blocksDestructive(a,t&&t.command);if(!e.ok)return{ok:!1,error:e.reason}}const i=covenant.preActionAssert({tool:e,args:t||{}});if(!i.allowed){const o=covenant.bindRefusal({tool:e,args:t||{}},i);return{ok:!1,error:`refused by the ÆGIS covenant — ${i.clause} (${i.label}): ${i.reason}`,covenant:o}}const l="writeFile"===e||"editFile"===e,c=l?I(t&&t.file_path):null,d=await m.executeTool(e,t,o);if(a&&l&&d&&!1!==d.ok&&recordWrite(a,t&&t.file_path),l&&c&&d&&!1!==d.ok){const o=I(t&&t.file_path);o&&function(e,t){if(!e)return;S.has(e)||S.set(e,[]);const o=S.get(e);o.push(t),o.length>x&&o.shift()}(n,{id:r||randomUUID(),tool:e,path:t&&t.file_path,before:c,after:o,at:Date.now()})}return d}function j(e,t){if(!e||"object"!=typeof e)return{ok:!0,content:`${t}\n${null==e?"":e}`};if(!1===e.ok||!0===e.isError){const o=e.error||e.content||"";return{...e,error:`${t}\n${o}`,content:`${t}\n${o}`}}const o=null!=e.content?e.content:null!=e.output?e.output:"";return{...e,content:`${t}\n${o}`}}async function B(e,{toolCtx:t,rootSessionId:o,rootOnDelta:n,signal:r}){const{name:s}=e,a=normalizeToolArgs(m,s,e.args,t||{});if(!a.ok)return{ok:!1,error:a.error};const i=a.args;if(!m.MUTATING_TOOLS.has(s))return $(s,i,t,o,e.id);if(w()){if("exec"===s){const n=planExec(i&&i.command,{baseCwd:t&&t.cwd||void 0});return n.oneShot?$(s,i,t,o,e.id):{ok:!1,error:E(s,n.reason)}}return{ok:!1,error:E(s)}}if(!b())return $(s,i,t,o,e.id);if(function(e,t,o){const n=_.get(e);return Boolean(n&&n.has(F(t,o)))}(o,s,i))return $(s,i,t,o,e.id);if("function"==typeof g){let n;try{n=g(s,i)}catch(e){n={verdict:null,source:"error",error:e&&e.message||String(e)}}if(n&&"deny"===n.verdict)return U(o,s),{ok:!1,error:L(s),permissionRule:n.rule||null};if(n&&"allow"===n.verdict)return $(s,i,t,o,e.id)}if(D(o,s))return{ok:!1,error:L(s)};let l=null;if(("writeFile"===s||"editFile"===s)&&(l=m.previewMutation(s,i,t||{}),!l.ok))return{ok:!1,error:l.error};const c=await C(o,n,r,{tool:s,args:i,diff:l&&l.diff});if("deny"===c)return U(o,s),{ok:!1,error:L(s)};if("session"!==c&&"once"!==c&&"always"!==c)return{ok:!1,error:`${s} was not executed — the request was cancelled.`};let d=null;if("always"===c){let e=null;if("function"==typeof y)try{e=y(s,i)}catch(t){e={ok:!1,reason:t&&t.message||String(t)}}else e={ok:!1,reason:"no durable store is wired on this host"};d=e&&e.ok?`[permission_rule] stored ${e.rule} — this command will not ask again`:`[permission_rule] nothing was stored — ${e&&e.reason||"unknown reason"}; this call was allowed once only`}if("session"===c&&R(o,s,i),l){const e=m.applyChecked(s,i,l,t||{});return e&&!1!==e.ok&&t&&t.guard&&recordWrite(t.guard,i&&i.file_path),d?j(e,d):e}const u=await $(s,i,t,o,e.id);return d?j(u,d):u}function q(e){return hostEnv(s||{},e&&e.env||{},e)}function K(e){const t=[],o=e=>String(e||"").replace(/[\\/]+$/,""),n=o(e),r=e=>{const r=o(e);r&&r!==n&&!t.includes(r)&&t.push(r)};let s=u;if(void 0===s)try{s=require("./git-scope.js")}catch{s=null}try{s&&"function"==typeof s.gitRoot&&r(s.gitRoot(e))}catch{}try{credentialsLib&&"function"==typeof credentialsLib.aegisHome&&r(credentialsLib.aegisHome())}catch{}return t}async function G(t,o){if("aegis"===t){const t=!o.singlePass&&(!!o.autonomous||void 0);return e.chatCompletion({prompt:o.prompt,system:o.system,messages:o.messages,model:o.model,mode:o.mode,maxTokens:o.statedMaxTokens,stream:!1!==o.stream,includeUsage:!0,onStream:o.onDelta,onReasoning:o.onReasoning,idleTimeoutMs:o.idleTimeoutMs,signal:o.signal,extra:{aegis_recall:!0,...o.recallDeep?{aegis_recall_deep:!0}:{},session:o.sessionId,...void 0===t?{}:{brain:t},...!1===t?{mode:"brain"}:{},...o.effort?{effort:o.effort}:{},...!0===t&&o.workers?{workers:o.workers}:{},...o.tools.length?{tools:o.tools}:{},...o.toolChoice?{tool_choice:o.toolChoice}:{}},agentKey:o.tools.length&&(process.env.AEGIS_AGENT_KEY||"").trim()||void 0})}if("byok"===t){const{provider:t,model:n}=splitByokModel(o.model),r=canonicalModelId(t,n),s=nativeEffort(t,r,o.effort);try{return await e.byokChatCompletion({provider:t,model:r,providerKey:o.apiKey,baseURL:o.cfg&&o.cfg.baseURL,prompt:o.prompt,system:o.system,messages:o.messages,maxTokens:o.maxTokens,tools:o.tools,toolChoice:o.toolChoice,effort:s&&"effort"===s.field?s.level:void 0,reasoningEffort:s&&"reasoning_effort"===s.field?s.level:void 0,stream:!0,onStream:o.onDelta,signal:o.signal})}catch(e){if(e&&402===e.status){const e=new Error("byok: this account has no AEGIS balance left, and the BYOK handling fee is billed there — your provider key is still valid, this is not a key problem. Top up the account, then try again (or /class aegis to use the pooled lane).");throw e.status=402,e}throw e}}if("local"===t){const e=o.cfg&&o.cfg.baseURL||c.DEFAULT_BASE,t=t=>c.chat({baseURL:e,model:o.model,prompt:o.prompt,system:o.system,messages:o.messages,maxTokens:o.maxTokens,signal:o.signal,onDelta:o.onDelta,...t&&o.tools.length?{tools:o.tools,toolChoice:o.toolChoice}:{}});try{return await t(!0)}catch(e){if(o.tools.length&&e&&400===e.status)return t(!1);throw e}}if("pro"===t){const e=o.sessionKey||o.rootSessionId||o.sessionId;let t=null;if(e&&(t=A.get(e)||null,!t)){try{t=M.get(e,s)||null}catch{}t&&A.set(e,t)}const n=K(o.cwd),r=e=>claudePro.runClaudePro({prompt:proTurnPrompt(o),model:o.model&&"default"!==o.model?o.model:void 0,system:o.system,cwd:o.cwd,addDir:n,resumeSessionId:e||void 0,gate:b(),onAsk:async e=>{if(!e||!e.requestId)return"deny";const t=o.rootSessionId,n=o.rootOnDelta,r=PRO_TOOL_MAP[String(e.toolName||"")]||null,s=r||String(e.toolName||"unknown"),a=proAskArgs(e.input||{},s),i=covenant.preActionAssert({tool:s,args:a});if(!i.allowed)return n&&n({delta:"",note:`aegis: refused by the ÆGIS covenant — ${i.clause} (${i.label}): ${i.reason}`}),"deny";if(w()){if("exec"===s){const e=planExec(a&&a.command,{baseCwd:o.cwd||void 0});return e.oneShot?"once":(n&&n({delta:"",note:E(s,e.reason)}),"deny")}if(r&&m.MUTATING_TOOLS.has(s))return n&&n({delta:"",note:E(s)}),"deny";if(!r&&!PRO_PLAN_MODE_SAFE.has(s))return n&&n({delta:"",note:E(s)}),"deny"}if(!b())return"once";if("function"==typeof g){let e;try{e=g(s,a)}catch{e=null}if(e&&"deny"===e.verdict)return n&&n({delta:"",note:L(s)}),"deny";if(e&&"allow"===e.verdict)return"once"}if(D(t,s))return n&&n({delta:"",note:L(s)}),"deny";const l=await C(t,n,o.signal,{tool:s,args:a,diff:null});if("deny"===l)return U(t,s),"deny";if("session"!==l&&"once"!==l&&"always"!==l)return"deny";if("session"===l&&R(t,s,a),"always"===l&&"function"==typeof y)try{y(s,a)}catch{}return l},signal:o.signal,onDelta:o.onDelta,onSpawn:(e,t)=>{o.onDelta&&t&&o.onDelta({delta:"",note:claudePro.childLine(t)})}});let a=await r(t);if(a&&a.resumeStale){A.delete(e);try{M.del(e,s)}catch{}o.onDelta&&o.onDelta({delta:"",note:"aegis: the remembered Claude session no longer exists on this machine — continuing as a new conversation (earlier turns are not in its context)"}),a=await r(null)}if(e&&a&&a.sessionId&&!a.error){A.set(e,a.sessionId);try{M.set(e,a.sessionId,s)}catch{}}return a}throw new Error(`dispatch: unknown model class ${JSON.stringify(t)} — this build ships 'aegis', 'byok', 'local' and 'pro' only`)}async function Y(o,n){const r=o&&o.class,s=o&&o.model,a=reasoningBudget("byok"===r?splitByokModel(s).model:s,o&&o.maxTokens,o&&o.effort),i=statedCapOf(o),d="aegis"===r&&Boolean(o&&o.autonomous),u=Boolean(o&&o.roundsAsk),f=o&&o.sessionId||randomUUID(),g=Number.isInteger(o&&o.depth)?o.depth:0,y=o&&o.rootSessionId||f,k=o&&o.rootOnDelta||n,b="function"==typeof n?e=>e&&n({reasoning:e}):void 0,w=new AbortController;p.set(f,w);const E=w.signal,_=!(o&&!1===o.tools),T=_?m.toolsFor({includeSubagent:g<4}):[],S=o&&o.toolChoice||null,x=o&&o.system||h(q(o)),A=Array.isArray(o&&o.messages)?o.messages.filter(Boolean).slice():[];let M=A.length,O=o&&o.prompt||"";const N=String(O||""),F=Array.isArray(o&&o.attachments)?o.attachments.filter((e=>e&&"object"==typeof e)).slice(0,attachmentsModule.MAX_ATTACHMENTS):[];let R=F.length?attachmentsModule.buildContent(O,F):O,D=null;const U=q(o),I=((e,t)=>{if(null==l)return null;const o="function"==typeof l.policy?l.policy():l.policy;if(!o)return null;const n=require("./sandbox.js"),r=e&&e.cwd||process.cwd(),s=n.normalize(o,r);if("off"===s.mode)return null;let a=[];try{let e=null;try{e=require("node:os").homedir()}catch{e=null}a=n.autoGrants(r,{home:e,addDirs:(()=>{try{return K(r)}catch{return[]}})()})}catch{a=[]}if(a.length){const e=new Set;for(const t of s.fileSystem.entries)t&&t.path&&"path"===t.path.type&&t.path.path&&e.add(`${t.access}:${t.path.path}`);for(const t of a){const o=`${t.access}:${t.path.path}`;e.has(o)||(e.add(o),s.fileSystem.entries.push(t))}}return"local"===t&&"restricted"===s.network&&(s.network="open",s.networkExempt="local"),{policy:s,state:l.state||n.detect({appDir:l.appDir}),workspace:r,appDir:l.appDir,strict:!0===l.strict}})(U,r),L=U.cwd,C={getShell:()=>D||(D=new ShellSession({cwd:U.cwd,sandbox:I})),signal:E,cwd:L,desktopdir:U.desktopdir,sandbox:I};try{const l="byok"===r?splitByokModel(s):null;let p=null;const h="byok"===r?t.get(byokNamespace(l.provider))||{}:"local"===r&&t.get("local")||{},w="byok"===r?t.rawKey(byokNamespace(l.provider)):null,D="byok"!==r?null:w||providerKeyFromEnv(l.provider);if(!("byok"!==r||l.provider&&l.model)){const e=new Error('byok: model must be "<provider>:<model>" (pick one from /models) — got '+JSON.stringify(s||""));throw e.status=400,e}if("byok"===r&&!D){const t="anthropic"===l.provider?claudePro.claudeProStatus({env:process.env}):null,o=providerKeyRecord(l.provider).rejected,n=nexusFallbackModel({provider:l.provider,providerKey:D,providerKeyRefused:o,aegisKey:D?"":e.apiKey});if(!n){const e=new Error(o?`${o}. That is why this turn has no ${l.provider} key: an env value that short is a paste that lost its payload, not a credential. Fix ${o.split(" ")[0]} in ~/.aegiscode/.env (or the shell that exported it) — or skip keys entirely: /byok-key ${l.provider} <key> to set one here.`:t&&t.loggedIn?`No Anthropic API key on this machine — an "anthropic:…" id is served by your own console key, which a Claude subscription is not. Use the subscription instead: /class pro (it spends your Claude Code ${t.subscription||"Pro"} plan through the claude CLI) — or add a real console key: /byok-key anthropic <key>.`:`No key for "${l.provider}" yet. Easiest fix: /class aegis (uses your AEGIS key, no setup) — or add this provider's own key: /byok-key ${l.provider} <key>.`);throw e.status=400,e}p={from:l.provider,model:n}}if("byok"===r&&!e.apiKey){const e=new Error("No AEGIS key connected yet. Easiest fix: /class aegis (skips BYOK entirely) — or add your AEGIS key with /login, then try again.");throw e.status=401,e}if("local"===r){const e=c.remoteRefusal(h.baseURL||c.DEFAULT_BASE);if(e)throw e}if("byok"===r&&"custom"===l.provider&&!(h.baseURL||"").trim()){const e=new Error('No endpoint saved for the "custom" provider — its key is on this machine but the address it dials is not, and no default exists for a vendor AEGIS does not know. Fix: /model-add custom <https-base-url> <api-key> <model-id> (writes both halves), or the endpoint field in Settings › Provider (custom).');throw e.status=400,e.code="custom_endpoint_missing",e}const U=p?"aegis":r,I={cls:U,model:p?p.model:s,mode:o&&o.mode,maxTokens:a,statedMaxTokens:i,autonomous:d,sessionId:f,signal:E,onDelta:n,cfg:h,apiKey:D,toolChoice:S,pooledFrom:p?p.from:void 0,cwd:L,rootSessionId:y,sessionKey:o&&o.sessionKey||void 0,rootOnDelta:k,effort:o&&o.effort,workers:o&&o.workers,recallDeep:o&&!0===o.recallDeep,singlePass:o&&!0===o.singlePass,onReasoning:b,idleTimeoutMs:d?9e5:void 0,stream:!o||!1!==o.stream};let $=!1,j=!1;const q=d?"AEGIS_AUTONOMOUS_MAX_ROUNDS":"AEGIS_CHAT_MAX_ROUNDS",K=(()=>{const e=Number.parseInt(process.env[q]||"",10);return Number.isFinite(e)&&e>0?e:0})(),Y=K||(d?40:24);let z=v.keyFor(o,A),H=v.take(z);if(!H&&!v.isStatedKey(o)){const e=v.adopt();e&&(H=e.entry,z=e.key)}if(H){const e=v.resumePreamble(H);0===A.length?Array.isArray(H.messages)&&H.messages.length&&A.push(...H.messages):Array.isArray(H.added)&&H.added.length&&A.push(...H.added),O?(O=`${e}\n\n${O}`,R=F.length?attachmentsModule.buildContent(O,F):O):(A.push({role:"user",content:e}),R=""),k&&k({delta:`\n\n[resuming work this session left unfinished at ${H.rounds} tool rounds`+(H.interruptions>1?` (cut off ${H.interruptions}×)`:"")+"…]\n"})}let V=K||Y+(H?v.bonus(Y):0),X=0;const J=Y,Q=8;let Z=0;const ee={calls:0},te=["input_tokens","output_tokens","prompt_tokens","completion_tokens","total_tokens","cache_read_input_tokens","cache_creation_input_tokens","prompt_cache_hit_tokens","prompt_cache_miss_tokens","reasoning_tokens","thinking_tokens"],oe=e=>{const t=e&&e.usage;if(t&&"object"==typeof t){ee.calls+=1;for(const e of te)"number"==typeof t[e]&&Number.isFinite(t[e])&&(ee[e]=(ee[e]||0)+t[e]);if("number"!=typeof t.total_tokens){const e=(t.prompt_tokens??t.input_tokens??0)+(t.completion_tokens??t.output_tokens??0);e&&(ee.total_tokens=(ee.total_tokens||0)+e)}}},ne=e=>{if(!e||"object"!=typeof e)return e;const t=p?{...e,pooled_from:p.from,pooled_model:p.model,pooled_notice:requireSharedByokCatalog().nexusFallbackNotice({pooled_from:p.from,pooled_model:p.model})}:e;return ee.calls?{...t,usage:{...ee}}:t},re=()=>{if(""===R)return;const e=A[A.length-1],t=e&&"user"===e.role?flattenContent(e.content):null;e&&"user"===e.role&&t===flattenContent(R)||A.push({role:"user",content:R}),O="",R=""};M=A.length;const se=m&&m.MUTATING_TOOLS||new Set;let ae=0,ie=0,le=!1;for(;;){if(X>=V){if(u&&Z<Q&&!E.aborted&&await P(y,k,E,{spent:V,extensions:Z+1,max:Q,size:J})){Z+=1;const e=V;V+=J,A.push({role:"user",content:`You have used all ${e} tool rounds allowed for this turn; ${J} more have been granted (do not restart). Continue the task from exactly where you stopped — do not re-plan, do not repeat work already done, and finish with an answer.`});continue}const e=u?"":`, or raise ${q} for a longer single turn`,t=`[stopped at ${V} tool rounds`+(ee.total_tokens?`, ${ee.total_tokens.toLocaleString()} tokens`:"")+". This session holds the work: your next message here resumes it automatically"+` (with a continuation preamble)${e}.]`,o=v.record(z,{rounds:X,tokens:ee.total_tokens||0,note:t,chain:H?H.interruptions:0,messages:A,added:A.slice(M)});return k&&k({delta:`\n\n${t}`}),ne({model:I.model,choices:[{message:{content:t},finish_reason:"length"}],stoppedOnRounds:!0,heldForSession:!0,heldRounds:o.rounds,sessionInterruptions:o.interruptions,resumedFrom:z})}X+=1;const e={...I,system:x,messages:A,prompt:R,tools:T,recallDeep:I.recallDeep&&1===X};let t;if(t=await G(U,e),oe(t),E.aborted)return ne(t);if(!$&&!assistantText(t)&&(isTruncated(t)||reasonedButSilent(t))){$=!0;const o=reasonedButSilent(t);if(t=await G(U,{...e,singlePass:!0,recallDeep:!1,effort:o?"high":e.effort,maxTokens:retryBudgetFor(e,o),statedMaxTokens:e.statedMaxTokens?doubledBudget(e.statedMaxTokens):void 0}),oe(t),E.aborted)return ne(t)}const a=T.length?extractToolCalls(t):[];if(!a.length){if(assistantText(t)||j||!_){if(!le&&_&&wantsMutation(N,ie>0,ae)){le=!0,re(),A.push({role:"assistant",content:assistantText(t)}),A.push({role:"user",content:UNMUTATED_TURN_NUDGE}),k&&k({delta:""});continue}return ne(t)}j=!0,re(),A.push({role:"user",content:reasonedButSilent(t)?THOUGHT_ONLY_NUDGE:EMPTY_TURN_NUDGE});const o={...e,singlePass:!0,recallDeep:!1,messages:A,prompt:"",tools:[]};t=await G(U,o);let n=o.maxTokens,a=o.effort;if(oe(t),E.aborted)return ne(t);if(!assistantText(t)&&(isTruncated(t)||reasonedButSilent(t))){const e=reasonedButSilent(t);if(n=retryBudgetFor(o,e),a=e?"high":o.effort,t=await G(U,{...o,effort:a,maxTokens:n,statedMaxTokens:o.statedMaxTokens?doubledBudget(o.statedMaxTokens):void 0}),oe(t),E.aborted)return ne(t)}const i=(()=>{const e=Number(n)||0;if(!e)return n;const t={maxTokens:n};return o.statedMaxTokens&&(t.statedMaxTokens=o.statedMaxTokens),Math.max(e,retryBudgetFor(t,!0))})();let l=0;for(;!assistantText(t)&&l<2&&!E.aborted;){const e=reasonedButSilent(t);if(l+=1,A.push({role:"user",content:e?1===l?THOUGHT_ONLY_NUDGE:FINAL_ANSWER_NUDGE:EMPTY_TURN_NUDGE}),e&&(a="high"),n=i,t=await G(U,{...o,messages:A,effort:a,maxTokens:n,statedMaxTokens:o.statedMaxTokens?doubledBudget(o.statedMaxTokens):void 0}),oe(t),E.aborted)return ne(t)}if(!assistantText(t))throw emptyTurnError({cls:r,model:s,effort:a,recoveryRounds:l,finishReason:finishReasonOf(t),reasoningChars:reasoningTextOf(t).length,reasoningTokens:reasoningTokensOf(t)});return ne(t)}re(),A.push({role:"assistant",content:assistantText(t),tool_calls:a.map((e=>({id:e.id,type:"function",function:{name:e.name,arguments:JSON.stringify(e.args)}})))});const l=new WeakMap,c=e=>{if("exec"!==e.name)return null;if(l.has(e))return l.get(e);const t=planExec(e.args&&e.args.command,{baseCwd:L});return l.set(e,t),t},d=e=>{if(!se.has(e.name))return!0;const t=c(e);return Boolean(t&&t.oneShot)},f=[];for(const e of a){const t=f[f.length-1];d(e)&&t&&t.parallel?t.calls.push(e):f.push({parallel:d(e),calls:[e]})}const p=async e=>{n&&n({delta:"",tool:{name:e.name,args:e.args,id:e.id,cwd:L,phase:"run"}});const t=c(e),a=t&&t.oneShot?{...C,oneShotExec:!0,cwd:t.cwd||C.cwd}:C,l=e.name===m.SUBAGENT_TOOL?await W(e.args,{cls:r,model:s,statedMaxTokens:i,effort:o&&o.effort,mode:o&&o.mode,parentSignal:E,depth:g,rootSessionId:y,rootOnDelta:k}):await B(e,{toolCtx:a,rootSessionId:y,rootOnDelta:k,signal:E});return l&&l.usage&&oe({usage:l.usage}),n&&n({delta:"",tool:{name:e.name,args:e.args,ok:l.ok,id:e.id,cwd:L,phase:"done"}}),l};for(const e of f){const t=e.parallel&&e.calls.length>1?await Promise.all(e.calls.map((e=>p(e)))):[await p(e.calls[0])];e.calls.forEach(((e,o)=>{const n=t[o];se.has(e.name)&&(ae+=1,n&&n.ok&&(ie+=1)),A.push({role:"tool",tool_call_id:e.id,name:e.name,content:m.toolResultText(n)})}))}}}catch(e){throw E.aborted&&e&&"object"==typeof e&&(e.aegisCancelled=!0),e}finally{D&&D.dispose(),p.delete(f)}}async function W({description:e,subagent_type:t,prompt:o}={},{cls:n,model:r,statedMaxTokens:s,effort:a,mode:i,parentSignal:l,depth:c,rootSessionId:d,rootOnDelta:u}={}){const f=String(o||e||"").trim();if(!f)return{ok:!1,error:"task requires a prompt"};const p=t&&"general"!==t?agentRoleLabel(t):"general",m=agentSystemPrompt(t),h=randomUUID();let g;if(l){if(l.aborted)return{ok:!1,error:"aborted"};g=()=>z(h),l.addEventListener("abort",g,{once:!0})}try{const e=await Y({class:n,model:r,mode:i,system:m,prompt:f,sessionId:h,depth:(c||0)+1,rootSessionId:d,rootOnDelta:u,statedMaxTokens:s,effort:a},(()=>{})),t=assistantText(e),o=e&&e.usage?{usage:e.usage}:{};return t?{ok:!0,output:t,...o}:{ok:!1,error:`subagent (${p}) produced no output`,...o}}catch(e){return{ok:!1,error:`subagent (${p}) failed: ${e&&e.message?e.message:e}`}}finally{l&&g&&l.removeEventListener("abort",g)}}function z(e){const t=p.get(e);return t&&t.abort(),{ok:Boolean(t)}}return{CLASSES:CLASSES,listClasses:async function(){return CLASSES.map((o=>{if("aegis"===o.class)return{...o,configured:Boolean(e.apiKey)};if("byok"===o.class){const e=(t.list()||[]).some((e=>!(!e||"string"!=typeof e.provider||!e.provider.startsWith("byok:"))&&(!!e.configured||Boolean(providerKeyFromEnv(e.provider.slice(BYOK_NAMESPACE_PREFIX.length))))));return{...o,configured:e}}if("local"===o.class)return{...o,configured:!0};if("pro"===o.class){const e=claudePro.claudeProStatus({env:process.env}),t=claudePro.seamAvailable();return{...o,configured:e.loggedIn,status:e,seam:t}}return{...o,configured:!1}}))},listModels:async function(o){if("aegis"===o){if(!e.apiKey)return{class:o,models:[],needsKey:!0};const t=await e.listModels();return{class:o,models:offerableCatalog(normalizeCatalog(t&&t.models))}}if("byok"===o){let n=[],r=null,s=!1,a=null;try{const t=await e.byokProviders();n=withUserModels(withCatalog(withByokAdditions(t&&t.providers||[]))),r=t&&t.fee||null}catch(e){n=[],s=!0,a=e&&e.message||String(e)}const i=[];for(const e of n){if(!e||!e.id)continue;const o=t.get(byokNamespace(e.id))||{},n=providerKeyRecord(e.id),r=n.key||"",s=Array.isArray(e.models)?e.models:[];for(const t of s){const s="string"==typeof t?t:t&&t.id;s&&i.push({id:`${e.id}:${s}`,label:`${e.label||e.id} — ${s}`,provider:e.id,configured:Boolean(o.configured||r),keyRejected:n.rejected||null})}}return{class:o,models:i,providers:n,needsProviderKey:i.length>0&&!i.some((e=>e.configured)),needsAegisKey:!e.apiKey,fee:r,providersFailed:s,providersError:a,unmatchedProviders:unmatchedUserProviders(n)}}if("local"===o){const e=(t.get("local")||{}).baseURL||c.DEFAULT_BASE,n=await c.probe(e);if(!n.running)return{class:o,models:[],baseURL:n.baseURL,needsDaemon:!0};let r=[],s=!0;try{r=await c.listTags(e)}catch{s=!1}return{class:o,models:r,baseURL:n.baseURL,listed:s}}if("pro"===o){const e=claudePro.claudeProStatus({env:process.env});return{class:o,models:claudePro.PRO_MODELS.map((t=>({id:t.id,label:t.label,note:t.note,configured:e.loggedIn}))),needsProviderKey:!1,needsAegisKey:!1,subscription:e.subscription,loggedIn:e.loggedIn,credentialFile:e.file,shadowed:e.shadowed||null,seam:claudePro.seamAvailable()}}throw new Error(`listModels: unknown model class ${JSON.stringify(o)} — this build ships 'aegis', 'byok', 'local' and 'pro' only`)},chat:Y,cancel:z,respondApproval:function(e,t){const o=O.get(e);return o?(O.delete(e),o.resolve("session"===t||"once"===t||"always"===t?t:"deny"),{ok:!0}):{ok:!1}},respondRoundsAsk:function(e,t){const o=N.get(e);return o?(N.delete(e),o.resolve(!0===t||"continue"===t),{ok:!0}):{ok:!1}},clearSessionApprovals:function(e){_.delete(e),T.delete(e),S.delete(e),A.delete(e);try{M.del(e,s)}catch{}return{ok:!0}},listUndoable:function(e){return(S.get(e)||[]).map((e=>({id:e.id,tool:e.tool,path:e.path,at:e.at}))).reverse()},undoMutation:function(e,t){const o=S.get(e)||[],n=t?o.findIndex((e=>e.id===t)):o.length-1;if(-1===n)return{ok:!1,error:t?`no undo record "${t}" for this conversation`:"nothing to undo in this conversation"};const r=o[n],s=I(r.path);if(!s||s.existed!==r.after.existed||s.content!==r.after.content)return{ok:!1,error:`${r.path} has changed since ${r.tool} ran — undo refused rather than overwriting work this session did not do. Resolve it by hand, or undo a different entry.`};try{r.before.existed?fs.writeFileSync(r.path,r.before.content,"utf8"):fs.unlinkSync(r.path)}catch(e){return{ok:!1,error:`undo failed: ${e&&e.message||e}`}}return o.splice(n,1),{ok:!0,path:r.path,restored:r.before.existed?"content":"deleted"}},settings:t,unloadLocalModels:function(){return c.unloadAll()},userModels:()=>loadUserModels(),addUserModel:(e,t)=>addUserModel(e,t),removeUserModel:(e,t)=>removeUserModel(e,t),discoverModels:async e=>{const o=String(null==e?"":e).trim().toLowerCase(),n=function(e){const o=String(null==e?"":e).trim().toLowerCase();if(!o)return"";try{if(t&&"function"==typeof t.rawKey){const e=t.rawKey(byokNamespace(o));if("string"==typeof e&&e.trim())return e.trim()}}catch{}return providerKeyFromEnv(o)}(o),r=await discoverVendorModels(o,{key:n,fetchImpl:d});if(!r||!r.ok)return r;const s=[];try{const e=loadUserModels().map;for(const t of Array.isArray(e[o])?e[o]:[])s.push(t)}catch{}return{...r,declared:s,endpoint:(vendorEndpointFor(o)||{}).url||""}},addUserModels:(e,t)=>{const o=Array.isArray(t)?t:[],n={provider:e,added:0,already:[],failed:[],capped:0,file:""};for(const t of o)try{const o=addUserModel(e,t);n.file=o.file||n.file,o.added?n.added+=1:n.already.push(o.model)}catch(e){const r=e&&e.message||String(e);if(/the cap/.test(r)){n.capped=o.length-n.added-n.already.length-n.failed.length;break}n.failed.push({id:String(t),reason:r})}return n},canDiscoverModels:e=>canDiscoverVendorModels(e),discoverableProviders:()=>discoverableProviders()}}module.exports={CLASSES:CLASSES,createLocalEngine:createLocalEngine,extractToolCalls:extractToolCalls,parseArgs:parseArgs,reasoningBudget:reasoningBudget,nativeEffort:nativeEffort,hostEnv:hostEnv};
|
|
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};
|
package/lib/local/integrity.js
CHANGED
|
@@ -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 = '2cc769c4c18eaba250015d15c7064f24076d14e0ff390e337abda71a23a4b34f';
|
|
138
138
|
|
|
139
139
|
/**
|
|
140
140
|
* Ask the question. Never throws — a check that can break the program it is
|
package/lib/local/perm-store.js
CHANGED
|
@@ -199,9 +199,14 @@ function validateRule(rule, opts = {}) {
|
|
|
199
199
|
// Removing the ability to express it would push users to `/confirm off`,
|
|
200
200
|
// which is the same state with no visible rule at all.
|
|
201
201
|
if (pattern === undefined || pattern === '') {
|
|
202
|
+
// The multi-`cd` rail only exists for the shell tool; naming it in a
|
|
203
|
+
// warning about `websearch` or `read` would be a sentence about nothing.
|
|
204
|
+
const rail = canonTool(tool) === 'shell'
|
|
205
|
+
? ', including commands that change directory more than once'
|
|
206
|
+
: '';
|
|
202
207
|
return {
|
|
203
208
|
ok: true,
|
|
204
|
-
warning: `a bare ${tool}() rule matches every ${tool} call
|
|
209
|
+
warning: `a bare ${tool}() rule matches every ${tool} call${rail}`,
|
|
205
210
|
};
|
|
206
211
|
}
|
|
207
212
|
return { ok: true };
|
|
@@ -209,7 +214,7 @@ function validateRule(rule, opts = {}) {
|
|
|
209
214
|
|
|
210
215
|
/** The capabilities `cli/src/permissions.js`'s TOOL_ALIAS folds onto. A rule
|
|
211
216
|
* naming anything else is inert, which `validateRule` refuses. */
|
|
212
|
-
const KNOWN_TOOLS = new Set(['shell', 'read', 'write', 'edit', 'list', 'glob', 'grep', 'task']);
|
|
217
|
+
const KNOWN_TOOLS = new Set(['shell', 'read', 'write', 'edit', 'list', 'glob', 'grep', 'websearch', 'task']);
|
|
213
218
|
|
|
214
219
|
/** The file shape, with `explicitAsk` deliberately absent — see listRules. */
|
|
215
220
|
function toFileShape(rules) {
|
package/lib/local/prompt.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 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, 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. 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:
|
|
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 Desktop ${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};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
|
+
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
+
"use strict";const path=require("node:path"),WARN_AT=2,REFUSE_AT=5,MODES=new Set(["off","dark","enforce"]),READ_TOOLS=new Set(["readFile"]);function resolveMode(e){const t=String((e||process.env||{}).AEGIS_REPEAT_GUARD||"").trim().toLowerCase();return MODES.has(t)?t:"dark"}function stableJson(e){return null===e||"object"!=typeof e?JSON.stringify(e):Array.isArray(e)?`[${e.map(stableJson).join(",")}]`:`{${Object.keys(e).filter((t=>void 0!==e[t])).sort().map((t=>`${JSON.stringify(t)}:${stableJson(e[t])}`)).join(",")}}`}function callKey(e,t){let a;try{a=stableJson(t&&"object"==typeof t?t:{})}catch{a=`~unserialisable:${Math.random()}`}return`${e}\0${a}`}function beginRepeatGuard(e){const t=resolveMode(e&&e.env);return{mode:t,active:"off"!==t,cwd:e&&e.cwd||null,counts:new Map,paths:new Map,written:new Set,readKeys:new Map,warned:new Set,refusals:0,warnings:0}}function pathKey(e,t){let a=String(e||"");return a?(!t||a.startsWith("~")||path.isAbsolute(a)||(a=path.resolve(t,a)),a.split("\\").join("/").replace(/^\.\//,"")):""}function recordWrite(e,t){if(!e||!e.active)return;const a=pathKey(t,e.cwd);if(!a)return;e.written.add(a);const n=e.readKeys.get(a);if(n){for(const t of n)e.counts.delete(t),e.paths.delete(t),e.warned.delete(t);n.clear()}}function check(e,t,a){if(!e||!e.active)return{action:"allow"};let n=!1;if(READ_TOOLS.has(t)){const t=pathKey(a&&a.file_path,e.cwd);t&&e.written.has(t)&&(e.written.delete(t),n=!0)}const r=callKey(t,a),s=(e.counts.get(r)||0)+1;if(e.counts.set(r,s),1===s&&e.paths.set(r,summarize(t,a)),READ_TOOLS.has(t)){const t=pathKey(a&&a.file_path,e.cwd);t&&(e.readKeys.has(t)||e.readKeys.set(t,new Set),e.readKeys.get(t).add(r))}if(n)return{action:"allow"};if(s<2)return{action:"allow"};const o=e.paths.get(r)||t;return s>=5?(5===s&&(e.refusals+=1),"enforce"===e.mode?{action:"refuse",error:`refused: this is the ${ordinal(s)} identical call to \`${o}\` this turn, so the result is already in the conversation above and running it again cannot change it. Do not repeat it and do not retry it with a cosmetic variation. Either use what the earlier result already told you, or take a different action (read a different path, change the command, or write the fix). If you are genuinely blocked, stop calling tools and say what blocks you.`}:{action:"allow"}):"enforce"!==e.mode||e.warned.has(r)?{action:"allow"}:(e.warned.add(r),e.warnings+=1,{action:"allow",note:`note: you have now called \`${o}\` ${s} times this turn with identical arguments. Its result is already above — read it again before repeating the call.`})}function summarize(e,t){const a=t&&"object"==typeof t?t:{},n=a.file_path||a.path||a.command||a.pattern||a.query;return"string"==typeof n&&n?`${e} ${n.length>80?`${n.slice(0,77)}…`:n}`:e}function ordinal(e){const t=["th","st","nd","rd"],a=e%100;return t[(a-20)%10]||t[a]||t[0]}function stats(e){if(!e)return{distinct:0,warnings:0,refusals:0,maxRepeat:0,repeats:[]};let t=0;const a=[];for(const[n,r]of e.counts)r>t&&(t=r),r>=2&&a.push({call:e.paths.get(n)||"",times:r});return a.sort(((e,t)=>t.times-e.times)),{distinct:e.counts.size,warnings:e.warnings,refusals:e.refusals,maxRepeat:t,repeats:a.slice(0,5)}}module.exports={WARN_AT:2,REFUSE_AT:5,beginRepeatGuard:beginRepeatGuard,recordWrite:recordWrite,check:check,stats:stats,callKey:callKey,stableJson:stableJson,resolveMode:resolveMode};
|
package/lib/local/tools.js
CHANGED
|
@@ -120,6 +120,14 @@ const sandbox = require('./sandbox.js');
|
|
|
120
120
|
const integrity = require('./integrity.js');
|
|
121
121
|
const READ_LINE_CAP = 2000; // default line limit for readFile
|
|
122
122
|
const MATCH_CAP = 100; // max glob/grep hits per call
|
|
123
|
+
// websearch — see the executor below. The result count is capped so a single
|
|
124
|
+
// call can never spend OUTPUT_CAP on snippets alone.
|
|
125
|
+
const WEBSEARCH_RESULTS = 8;
|
|
126
|
+
const WEBSEARCH_RESULTS_CAP = 20;
|
|
127
|
+
const WEBSEARCH_TIMEOUT = 20_000;
|
|
128
|
+
// A hostile or huge response must not be read into memory; the parsed hits are
|
|
129
|
+
// a few KB, so a truncated document is still a usable one.
|
|
130
|
+
const WEBSEARCH_MAX_BYTES = 2 * 1024 * 1024;
|
|
123
131
|
// readFileSync loads the whole file before `limit` ever truncates — refuse
|
|
124
132
|
// oversized reads outright instead of freezing the turn on a multi-GB log.
|
|
125
133
|
const READ_SIZE_CAP = 25 * 1024 * 1024;
|
|
@@ -315,6 +323,19 @@ const SCHEMAS = {
|
|
|
315
323
|
additionalProperties: false,
|
|
316
324
|
},
|
|
317
325
|
},
|
|
326
|
+
websearch: {
|
|
327
|
+
name: 'websearch',
|
|
328
|
+
description:
|
|
329
|
+
'Search the web (no key needed). Returns titles, URLs, snippets; then read a page with exec + curl.',
|
|
330
|
+
parameters: {
|
|
331
|
+
type: 'object',
|
|
332
|
+
properties: {
|
|
333
|
+
query: { type: 'string', description: 'What to search for' },
|
|
334
|
+
},
|
|
335
|
+
required: ['query'],
|
|
336
|
+
additionalProperties: false,
|
|
337
|
+
},
|
|
338
|
+
},
|
|
318
339
|
task: {
|
|
319
340
|
name: 'task',
|
|
320
341
|
description:
|
|
@@ -1146,6 +1167,159 @@ function hooks({ sub, cwd } = {}) {
|
|
|
1146
1167
|
}
|
|
1147
1168
|
}
|
|
1148
1169
|
|
|
1170
|
+
// ── websearch ───────────────────────────────────────────────────────────────
|
|
1171
|
+
//
|
|
1172
|
+
// Neither host could reach the web before this: the eight advertised tools all
|
|
1173
|
+
// operate on this machine, so a model asked about anything else had to guess,
|
|
1174
|
+
// or shell out and get an HTML soup back. The avatar even matched the word
|
|
1175
|
+
// (`renderer/avatar/machine.js`, a `tool.run` signal) for a tool that did not
|
|
1176
|
+
// exist.
|
|
1177
|
+
//
|
|
1178
|
+
// DuckDuckGo's no-JavaScript endpoint is the backend because it is the only
|
|
1179
|
+
// widely-used one that needs NO key: the CLI and the desktop both run on the
|
|
1180
|
+
// user's own machine with no account required, and a search that only works
|
|
1181
|
+
// after `aegis login` would be a new setup step for a one-line question. The
|
|
1182
|
+
// trade is markup parsing, which is why the parser is deliberately narrow and
|
|
1183
|
+
// every failure is a tool error rather than a throw.
|
|
1184
|
+
//
|
|
1185
|
+
// Two things this deliberately does NOT do: it does not run a browser (no
|
|
1186
|
+
// renderer, no cookies, no JS), and it does not follow result links — the
|
|
1187
|
+
// model gets snippets plus URLs and reads a page itself if it needs to.
|
|
1188
|
+
|
|
1189
|
+
const NAMED_ENTITIES = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", nbsp: ' ' };
|
|
1190
|
+
|
|
1191
|
+
/** Decode the entity forms DDG actually emits (`'`, `&`, `"`…). */
|
|
1192
|
+
function decodeEntities(s) {
|
|
1193
|
+
return String(s == null ? '' : s).replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);/gi, (m, body) => {
|
|
1194
|
+
if (body[0] === '#') {
|
|
1195
|
+
const code = body[1] === 'x' || body[1] === 'X'
|
|
1196
|
+
? parseInt(body.slice(2), 16)
|
|
1197
|
+
: parseInt(body.slice(1), 10);
|
|
1198
|
+
return Number.isFinite(code) && code > 0 && code <= 0x10ffff ? String.fromCodePoint(code) : m;
|
|
1199
|
+
}
|
|
1200
|
+
const named = NAMED_ENTITIES[body.toLowerCase()];
|
|
1201
|
+
return named === undefined ? m : named;
|
|
1202
|
+
});
|
|
1203
|
+
}
|
|
1204
|
+
|
|
1205
|
+
/** Strip tags, decode entities, collapse whitespace — snippet text as prose. */
|
|
1206
|
+
function plainText(html) {
|
|
1207
|
+
return decodeEntities(String(html || '').replace(/<[^>]*>/g, '')).replace(/\s+/g, ' ').trim();
|
|
1208
|
+
}
|
|
1209
|
+
|
|
1210
|
+
/**
|
|
1211
|
+
* DDG wraps every hit as `//duckduckgo.com/l/?uddg=<encoded target>` (plus an
|
|
1212
|
+
* opaque `rut` token). The real URL is the `uddg` parameter; anything that is
|
|
1213
|
+
* not that shape (an ad slot, a malformed href) is returned unchanged so the
|
|
1214
|
+
* model can still see where a hit points instead of the tool silently dropping
|
|
1215
|
+
* it.
|
|
1216
|
+
*/
|
|
1217
|
+
function realUrl(href) {
|
|
1218
|
+
const raw = decodeEntities(String(href || '').trim());
|
|
1219
|
+
if (!raw) return '';
|
|
1220
|
+
let u;
|
|
1221
|
+
try {
|
|
1222
|
+
u = new URL(raw, 'https://duckduckgo.com');
|
|
1223
|
+
} catch {
|
|
1224
|
+
return raw;
|
|
1225
|
+
}
|
|
1226
|
+
const target = u.searchParams.get('uddg');
|
|
1227
|
+
if (target) {
|
|
1228
|
+
try { return decodeURIComponent(target); } catch { return target; }
|
|
1229
|
+
}
|
|
1230
|
+
return raw.startsWith('//') ? `https:${raw}` : raw;
|
|
1231
|
+
}
|
|
1232
|
+
|
|
1233
|
+
/**
|
|
1234
|
+
* Parse one DDG results page into `{title, url, snippet}` entries.
|
|
1235
|
+
*
|
|
1236
|
+
* Written against the shipped markup rather than a real parser (this module
|
|
1237
|
+
* carries no dependencies — see the header). A result is an
|
|
1238
|
+
* `<a class="result__a" href=…>title</a>`; its snippet is the NEXT
|
|
1239
|
+
* `result__snippet` in the document, which is why this walks the matches in
|
|
1240
|
+
* document order in a single pass instead of pairing two independent lists.
|
|
1241
|
+
*/
|
|
1242
|
+
function parseResults(html) {
|
|
1243
|
+
const out = [];
|
|
1244
|
+
const re = /<a\b[^>]*\bclass="[^"]*\bresult__a\b[^"]*"[^>]*>([\s\S]*?)<\/a>|<a\b[^>]*\bclass="[^"]*\bresult__snippet\b[^"]*"[^>]*>([\s\S]*?)<\/a>/gi;
|
|
1245
|
+
const hrefRe = /\bhref="([^"]*)"/i;
|
|
1246
|
+
let m;
|
|
1247
|
+
while ((m = re.exec(html)) !== null) {
|
|
1248
|
+
const tag = m[0];
|
|
1249
|
+
const isTitle = m[1] !== undefined;
|
|
1250
|
+
if (isTitle) {
|
|
1251
|
+
const href = hrefRe.exec(tag);
|
|
1252
|
+
out.push({ title: plainText(m[1]), url: realUrl(href ? href[1] : ''), snippet: '' });
|
|
1253
|
+
} else if (out.length) {
|
|
1254
|
+
// Only the FIRST snippet after a title belongs to it: DDG emits one per
|
|
1255
|
+
// hit, and a stray later one must not overwrite a real description.
|
|
1256
|
+
const last = out[out.length - 1];
|
|
1257
|
+
if (!last.snippet) last.snippet = plainText(m[2]);
|
|
1258
|
+
}
|
|
1259
|
+
}
|
|
1260
|
+
return out.filter((r) => r.title && r.url);
|
|
1261
|
+
}
|
|
1262
|
+
|
|
1263
|
+
/**
|
|
1264
|
+
* Search the web. Read-only from this machine's point of view (it writes no
|
|
1265
|
+
* file, spawns no process), so it is NOT in MUTATING_TOOLS — but it is the one
|
|
1266
|
+
* tool whose text LEAVES the machine, which is why the query is the user's own
|
|
1267
|
+
* words and this never appends anything from the session or the working tree.
|
|
1268
|
+
*/
|
|
1269
|
+
async function websearch({ query, max_results } = {}) {
|
|
1270
|
+
const q = String(query == null ? '' : query).trim();
|
|
1271
|
+
if (!q) return fail('query is required');
|
|
1272
|
+
if (typeof fetch !== 'function') {
|
|
1273
|
+
return fail('this build has no fetch — node >= 18 (or a desktop app on a bundled runtime) is required');
|
|
1274
|
+
}
|
|
1275
|
+
const limit = Math.max(1, Math.min(Math.floor(Number(max_results) || WEBSEARCH_RESULTS), WEBSEARCH_RESULTS_CAP));
|
|
1276
|
+
const endpoint = `https://html.duckduckgo.com/html/?q=${encodeURIComponent(q)}`;
|
|
1277
|
+
const controller = typeof AbortController === 'function' ? new AbortController() : null;
|
|
1278
|
+
const timer = controller ? setTimeout(() => controller.abort(), WEBSEARCH_TIMEOUT) : null;
|
|
1279
|
+
try {
|
|
1280
|
+
const res = await fetch(endpoint, {
|
|
1281
|
+
method: 'GET',
|
|
1282
|
+
redirect: 'follow',
|
|
1283
|
+
signal: controller ? controller.signal : undefined,
|
|
1284
|
+
headers: {
|
|
1285
|
+
// The endpoint is a plain web page: it serves the no-JS markup to a
|
|
1286
|
+
// normal browser UA. The default undici UA gets a challenge page.
|
|
1287
|
+
'user-agent': 'Mozilla/5.0 (compatible; AEGIS-Code; +https://aegiscode.org)',
|
|
1288
|
+
accept: 'text/html,application/xhtml+xml',
|
|
1289
|
+
'accept-language': 'en-US,en;q=0.9',
|
|
1290
|
+
},
|
|
1291
|
+
});
|
|
1292
|
+
if (!res.ok) {
|
|
1293
|
+
return fail(
|
|
1294
|
+
`websearch: the search backend answered HTTP ${res.status}${res.status === 429 ? ' (rate-limited — wait a moment and retry)' : ''}`
|
|
1295
|
+
);
|
|
1296
|
+
}
|
|
1297
|
+
const html = (await res.text()).slice(0, WEBSEARCH_MAX_BYTES);
|
|
1298
|
+
const hits = parseResults(html);
|
|
1299
|
+
if (!hits.length) {
|
|
1300
|
+
// Distinguishable from "no matches": a challenge page, a layout change
|
|
1301
|
+
// and a genuinely empty result set all land here, and the model should
|
|
1302
|
+
// not conclude the web is empty.
|
|
1303
|
+
return fail('websearch: no results were parsed — the search backend returned no recognisable result markup');
|
|
1304
|
+
}
|
|
1305
|
+
const shown = hits.slice(0, limit);
|
|
1306
|
+
const lines = shown.map(
|
|
1307
|
+
(r, i) => `${i + 1}. ${r.title}\n ${r.url}${r.snippet ? `\n ${r.snippet}` : ''}`
|
|
1308
|
+
);
|
|
1309
|
+
const footer = hits.length > shown.length ? `\n\n(showing ${shown.length} of ${hits.length})` : '';
|
|
1310
|
+
return ok(`websearch: ${q}\n\n${lines.join('\n\n')}${footer}`);
|
|
1311
|
+
} catch (e) {
|
|
1312
|
+
if (e && (e.name === 'AbortError' || e.code === 'ABORT_ERR')) {
|
|
1313
|
+
return fail(`websearch: no answer within ${WEBSEARCH_TIMEOUT / 1000}s — retry, or narrow the query`);
|
|
1314
|
+
}
|
|
1315
|
+
// Offline, DNS failure, TLS, a proxy that eats the request: all one line
|
|
1316
|
+
// back to the model, never a throw (the module's contract).
|
|
1317
|
+
return fail(`websearch: ${e && e.message ? e.message : String(e)}`);
|
|
1318
|
+
} finally {
|
|
1319
|
+
if (timer) clearTimeout(timer);
|
|
1320
|
+
}
|
|
1321
|
+
}
|
|
1322
|
+
|
|
1149
1323
|
/** Mutating: install the repo's guard hooks (core.hooksPath -> .githooks/). */
|
|
1150
1324
|
function installHooks({ cwd, dry_run } = {}) {
|
|
1151
1325
|
if (!hooksLib) return fail(HOOKS_LIB_MISSING);
|
|
@@ -1168,7 +1342,7 @@ function installHooks({ cwd, dry_run } = {}) {
|
|
|
1168
1342
|
+ `${plan}\n ${res.status.execNote}\n a commit and a push in this tree are now gated.`);
|
|
1169
1343
|
}
|
|
1170
1344
|
|
|
1171
|
-
const EXECUTORS = { readFile, writeFile, editFile, listDir, glob, grep, exec, hooks, installHooks };
|
|
1345
|
+
const EXECUTORS = { readFile, writeFile, editFile, listDir, glob, grep, exec, websearch, hooks, installHooks };
|
|
1172
1346
|
|
|
1173
1347
|
/** True when `name` is a tool this layer can run (task is excluded — see SUBAGENT_TOOL). */
|
|
1174
1348
|
function isTool(name) {
|
|
@@ -1341,7 +1515,17 @@ module.exports = {
|
|
|
1341
1515
|
normalizeArgs,
|
|
1342
1516
|
TOOL_PATH_ARGS,
|
|
1343
1517
|
PATH_ARG_DESC,
|
|
1518
|
+
// websearch pieces (tests assert the parser against real backend markup
|
|
1519
|
+
// instead of reaching the network, and drive the executor directly so the
|
|
1520
|
+
// unit does not depend on this tree's integrity seal being green)
|
|
1521
|
+
websearch,
|
|
1522
|
+
parseResults,
|
|
1523
|
+
realUrl,
|
|
1524
|
+
decodeEntities,
|
|
1344
1525
|
// limits (unit tests assert against them instead of hard-coding numbers)
|
|
1526
|
+
WEBSEARCH_RESULTS,
|
|
1527
|
+
WEBSEARCH_RESULTS_CAP,
|
|
1528
|
+
WEBSEARCH_TIMEOUT,
|
|
1345
1529
|
OUTPUT_CAP,
|
|
1346
1530
|
READ_LINE_CAP,
|
|
1347
1531
|
MATCH_CAP,
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
|
+
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
+
"use strict";const CODE_EXT=new Set([".js",".mjs",".cjs",".jsx",".ts",".tsx",".mts",".cts",".py",".rb",".go",".rs",".java",".kt",".kts",".scala",".swift",".c",".h",".cc",".cpp",".hpp",".cxx",".hh",".m",".mm",".cs",".fs",".php",".pl",".pm",".lua",".r",".jl",".dart",".ex",".exs",".erl",".hrl",".hs",".clj",".cljs",".ml",".mli",".sh",".bash",".zsh",".fish",".ps1",".sql",".vue",".svelte",".zig",".nim",".cr",".v",".sv",".sol",".tf"]),EXEC_TOOLS=new Set(["exec"]),NUDGE="You edited %s and the turn is ending, but no command has been run since that edit. Editing a file proves it compiles no more than describing it did. Run the project's check now — its tests, a type check, or at minimum the file's own linter — and report what it printed. If you already know the change cannot be checked by a command (a comment, a docs string, a config value), say so explicitly and finish; do not claim the change \"works\" without evidence.",NUDGE_WITH_CMD='You edited %s and the turn is ending, but no command has been run since that edit. Editing a file proves it compiles no more than describing it did. The check for this repo is likely `%s` (%s) — run it and report what it printed. If you disagree with that command, run what actually checks this change. If the change cannot be checked by a command (a comment, a docs string, a config value), say so explicitly and finish; do not claim the change "works" without evidence.',MODES=new Set(["off","dark","enforce"]);function resolveMode(e){const t=String(e&&e.mode||"").trim().toLowerCase();if(MODES.has(t))return t;const n=String(process.env.AEGIS_VERIFY_STOP||"").trim().toLowerCase();return MODES.has(n)?n:"dark"}function beginVerifyGuard(e){const t=resolveMode(e);return{mode:t,cwd:e&&e.cwd||null,active:"off"!==t,dirty:[],ranSince:!1,nudged:!1,fired:0}}function extOf(e){const t=String(e||"").split(/[/\\]/).pop()||"",n=t.lastIndexOf(".");return n<=0?"":t.slice(n).toLowerCase()}function isCodePath(e){return CODE_EXT.has(extOf(e))}function recordMutation(e,t){e&&e.active&&isCodePath(t)&&(e.dirty.push(String(t)),e.ranSince=!1)}function recordExec(e){e&&e.active&&(e.ranSince=!0,e.dirty=[])}function shouldNudge(e){if(!e||!e.active)return{nudge:!1};if(!e.dirty.length)return{nudge:!1};if(e.ranSince)return{nudge:!1};if(e.nudged)return{nudge:!1};const t=e.dirty.slice(-3),n=t.join(", ")+(e.dirty.length>3?` (+${e.dirty.length-3} more)`:"");if(e.fired=1,"enforce"!==e.mode)return{nudge:!1,fired:!0,paths:t};e.nudged=!0;let i=null;if(e.cwd)try{const{detectCheckCommand:t}=require("./check-command.js");i=t(e.cwd,e.dirty[e.dirty.length-1])}catch{i=null}if(i){const e=[n,i.cmd,i.why];let r=0;return{nudge:!0,text:NUDGE_WITH_CMD.replace(/%s/g,(()=>String(e[r++]))),paths:t,cmd:i.cmd}}return{nudge:!0,text:NUDGE.replace("%s",n),paths:t}}module.exports={beginVerifyGuard:beginVerifyGuard,recordMutation:recordMutation,recordExec:recordExec,shouldNudge:shouldNudge,resolveMode:resolveMode,isCodePath:isCodePath,extOf:extOf,EXEC_TOOLS:EXEC_TOOLS,CODE_EXT:CODE_EXT,NUDGE:NUDGE};
|
package/lib/sync/persist-gate.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 fs=require("node:fs"),path=require("node:path"),{MEMORY_PERSIST_NAMESPACE:MEMORY_PERSIST_NAMESPACE,SETTINGS_FILE:SETTINGS_FILE}=require("../settings.js"),prefs=(()=>{try{return require("../../../client/prefs.js")}catch{return require("../../vendor/prefs.js")}})();function settingsFile(e){const t=e||"";return t.endsWith(SETTINGS_FILE)?t:path.join(t,SETTINGS_FILE)}function readSettings(e){try{const t=JSON.parse(fs.readFileSync(settingsFile(e),"utf8"));return t&&"object"==typeof t?t:{}}catch{return{}}}function gateState(e,t){const r=t||{},n=prefs.load({dir:r.prefsDir,env:r.env});if("boolean"==typeof n.memoryPersist)return{enabled:n.memoryPersist,source:"config"};const s=readSettings(e)[MEMORY_PERSIST_NAMESPACE];return s&&void 0!==s.enabled?{enabled:Boolean(s.enabled),source:"config"}:{enabled:!0,source:"default"}}function createAutoPush({push:e,dir:t,gate:r,prefsDir:n,env:s}={}){if("function"!=typeof e)throw new Error("createAutoPush requires a push()");const i="function"==typeof r?r:()=>gateState(t,{prefsDir:n,env:s});let o=null;return{auto:function(){return o||(o=async function(){const t=i();if(!t.enabled)return{ok:!0,skipped:!0,gate:t,reason:"
|
|
3
|
+
"use strict";const fs=require("node:fs"),path=require("node:path"),{MEMORY_PERSIST_NAMESPACE:MEMORY_PERSIST_NAMESPACE,SETTINGS_FILE:SETTINGS_FILE}=require("../settings.js"),prefs=(()=>{try{return require("../../../client/prefs.js")}catch{return require("../../vendor/prefs.js")}})();function settingsFile(e){const t=e||"";return t.endsWith(SETTINGS_FILE)?t:path.join(t,SETTINGS_FILE)}function readSettings(e){try{const t=JSON.parse(fs.readFileSync(settingsFile(e),"utf8"));return t&&"object"==typeof t?t:{}}catch{return{}}}function gateState(e,t){const r=t||{},n=prefs.load({dir:r.prefsDir,env:r.env});if("boolean"==typeof n.memoryPersist)return{enabled:n.memoryPersist,source:"config"};const s=readSettings(e)[MEMORY_PERSIST_NAMESPACE];return s&&void 0!==s.enabled?{enabled:Boolean(s.enabled),source:"config"}:{enabled:!0,source:"default"}}function createAutoPush({push:e,dir:t,gate:r,prefsDir:n,env:s}={}){if("function"!=typeof e)throw new Error("createAutoPush requires a push()");const i="function"==typeof r?r:()=>gateState(t,{prefsDir:n,env:s});let o=null;return{auto:function(){return o||(o=async function(){const t=i();if(!t.enabled)return{ok:!0,skipped:!0,gate:t,reason:"cloud sync is off"};try{const r=await e();return Object.assign({},r,{skipped:!1,gate:t})}catch(e){return{ok:!1,skipped:!1,gate:t,reason:e&&e.message||String(e)}}}().finally((()=>{o=null})),o)},gate:()=>i(),state:()=>i()}}module.exports={settingsFile:settingsFile,readSettings:readSettings,gateState:gateState,createAutoPush:createAutoPush};
|
package/lib/sync/sessions.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 shared=(()=>{try{return require("../../../client/session-store.js")}catch{return require("../../vendor/session-store.js")}})(),credentials=(()=>{try{return require("../../../client/credentials.js")}catch{return require("../../vendor/credentials.js")}})();function resolveStoreDir(e){const s=credentials.aegisHome();return e&&e!==s&&adopt(s,e),s}const{storeFile:storeFile,load:load,save:save,upsertSession:upsertSession,appendMessage:appendMessage,recordExchange:recordExchange,listSessions:listSessions,getSession:getSession,deleteSession:deleteSession,markSynced:markSynced,markPending:markPending,listPending:listPending,mergeRemoteSessions:mergeRemoteSessions,listSummaries:listSummaries,readTranscript:readTranscript,adopt:adopt,toMarkdown:toMarkdown,toJson:toJson}=shared,sessionsFile=storeFile;module.exports={sessionsFile:sessionsFile,storeFile:storeFile,resolveStoreDir:resolveStoreDir,load:load,save:save,upsertSession:upsertSession,appendMessage:appendMessage,recordExchange:recordExchange,listSessions:listSessions,getSession:getSession,deleteSession:deleteSession,markSynced:markSynced,markPending:markPending,listPending:listPending,mergeRemoteSessions:mergeRemoteSessions,listSummaries:listSummaries,readTranscript:readTranscript,adopt:adopt,toMarkdown:toMarkdown,toJson:toJson};
|
|
3
|
+
"use strict";const shared=(()=>{try{return require("../../../client/session-store.js")}catch{return require("../../vendor/session-store.js")}})(),credentials=(()=>{try{return require("../../../client/credentials.js")}catch{return require("../../vendor/credentials.js")}})();function resolveStoreDir(e){const s=credentials.aegisHome();return e&&e!==s&&adopt(s,e),s}const{storeFile:storeFile,load:load,save:save,upsertSession:upsertSession,appendMessage:appendMessage,recordExchange:recordExchange,listSessions:listSessions,getSession:getSession,deleteSession:deleteSession,markSynced:markSynced,markPending:markPending,listPending:listPending,mergeRemoteSessions:mergeRemoteSessions,listSummaries:listSummaries,readTranscript:readTranscript,adopt:adopt,toMarkdown:toMarkdown,toJson:toJson}=shared,sessionsFile=storeFile,namingStore={getSession:getSession,setTitle:(e,s,n,r)=>shared.setTitle(e,s,n,r)};function renameSession(e,s,n){const r=String(null==n?"":n).trim();return s&&r?shared.setTitle(e,s,r,{named:!0}):null}module.exports={sessionsFile:sessionsFile,renameSession:renameSession,namingStore:namingStore,storeFile:storeFile,resolveStoreDir:resolveStoreDir,load:load,save:save,upsertSession:upsertSession,appendMessage:appendMessage,recordExchange:recordExchange,listSessions:listSessions,getSession:getSession,deleteSession:deleteSession,markSynced:markSynced,markPending:markPending,listPending:listPending,mergeRemoteSessions:mergeRemoteSessions,listSummaries:listSummaries,readTranscript:readTranscript,adopt:adopt,toMarkdown:toMarkdown,toJson:toJson};
|