aegisone 1.0.76 → 1.0.78
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/package.json +1 -1
- package/vendor/cli/package.json +1 -1
- package/vendor/cli/src/app.js +1 -1
- package/vendor/cli/src/models.js +1 -1
- package/vendor/cli/vendor/desktop/lib/local/context.js +1 -1
- package/vendor/cli/vendor/desktop/lib/local/engine.js +1 -1
- package/vendor/cli/vendor/desktop/lib/local/local.js +1 -1
- package/vendor/cli/vendor/desktop/lib/local/prompt.js +1 -1
- package/vendor/desktop/lib/local/context.js +1 -1
- package/vendor/desktop/lib/local/engine.js +1 -1
- package/vendor/desktop/lib/local/local.js +1 -1
- package/vendor/desktop/lib/local/memo.js +3 -0
- package/vendor/desktop/lib/local/prompt.js +1 -1
- package/vendor/desktop/lib/sync/memory-rank.js +3 -0
- package/vendor/desktop/lib/sync/memory-store.js +1 -1
- package/vendor/desktop/package.json +1 -1
- package/vendor/desktop/vendor/faces/cli/package.json +1 -1
- package/vendor/desktop/vendor/faces/cli/src/app.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/models.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/context.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/engine.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/local.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/prompt.js +1 -1
|
@@ -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{estimateTokens:estimateTokens,LOCAL_PREFILL_TOK_PER_SEC:LOCAL_PREFILL_TOK_PER_SEC}=require("./context.js"),STAGE_BUDGETS=Object.freeze({ground:1,identify:7,seek:8}),MULTI_HOP=/\b(who|which|when|where|whose|compare|difference|between|linked|related|depends?|before|after|both|neither|and\s+then)\b/i,PRONOUN="they|them|it|this|that|these|those|he|she|his|her|its|their",ANAPHOR=`${PRONOUN}|the above|the former|the latter`,DANGLING_REF=new RegExp(`^(?:(?:what|who|when|where|why|how|which)\\b[^?]*\\b(?:${ANAPHOR})\\b|(?:${ANAPHOR})\\b)`,"i"),BUNDLE_MAX_QUESTION_SHARE=.02,BUNDLE_MIN_TOKENS=600,QUESTION_ANCHOR_MAX=40;function tokens(e,t){return("function"==typeof t?t:estimateTokens)(String(null==e?"":e))}function prefillSecs(e,t=LOCAL_PREFILL_TOK_PER_SEC){const n=Number(t)>0?Number(t):LOCAL_PREFILL_TOK_PER_SEC;return Math.round(Math.max(0,Number(e)||0)/n*10)/10}function anchor(e,t=40){const n=String(null==e?"":e).replace(/\s+/g," ").trim().replace(/[.!?;:,]+$/,"");if(n.length<=t)return n;const s=n.slice(0,t),o=s.lastIndexOf(" ");return`${(o>.6*t?s.slice(0,o):s).trimEnd()}…`}function gist(e,t=120){const n=String(null==e?"":e).replace(/\s+/g," ").trim();if(!n)return"";const s=n.search(/[.!?](\s|$)/),o=s>0?n.slice(0,s+1):n;return o.length>t?`${o.slice(0,t-1).trimEnd()}…`:o}function noteToQuestion(e){const t=String(e&&(e.body||e.text||e.content)||""),n=String(e&&(e.subject||e.topic)||"").trim(),s=gist(t);if(!s)return{question:"",selfContained:!1,reason:"empty"};const o=DANGLING_REF.test(s);return{question:`What is recorded about ${anchor(n||s)}?`,selfContained:!o,reason:o?"dangling-reference":n?"subject-anchored":"gist"}}function partitionNotes(e,{tok:t}={}){const n=(Array.isArray(e)?e:[]).filter(Boolean),s=bundleNotes(n,{tok:t}),o=new Set(s.map(e=>e.subject));return{bundles:s,singles:n.filter(e=>{const t=String(e.subject||e.topic||e.scope||"").trim().toLowerCase();return!t||!o.has(t)})}}function bundleNotes(e,{tok:t}={}){const n=new Map;for(const t of Array.isArray(e)?e:[]){if(!t)continue;const e=String(t.subject||t.topic||t.scope||"").trim().toLowerCase();e&&(n.has(e)||n.set(e,[]),n.get(e).push(t))}const s=[];for(const[e,o]of n){if(o.length<2)continue;const n=o.reduce((e,n)=>e+tokens(n.body||n.text||n.content,t),0);if(n<600)continue;const r=`What does the project record about ${e}?`;tokens(r,t)>.02*n||s.push({subject:e,question:r,members:o.length,bodyTokens:n})}return s}function shouldRecall(e,t,{tokPerSec:n=LOCAL_PREFILL_TOK_PER_SEC,minSavedSecs:s=2}={}){const o=Number(n)>0?Number(n):LOCAL_PREFILL_TOK_PER_SEC,r=(Number(e)-Number(t))/o;return{recall:r>=Number(s),savedSecs:Math.round(10*r)/10}}function stageBudgetFor(e){const t=String(e||"");return MULTI_HOP.test(t)?{...STAGE_BUDGETS}:{ground:1,identify:0,seek:1}}function buildRecallPlan({query:e="",notes:t=[],tokPerSec:n=LOCAL_PREFILL_TOK_PER_SEC,tok:s}={}){const o=stageBudgetFor(e),r=[],i=[];let c=0;const{bundles:u,singles:a}=partitionNotes(t,{tok:s});for(const e of a){const t=noteToQuestion(e);if(!t.question){i.push({...t,reason:t.reason||"empty"});continue}if(!t.selfContained){i.push({question:t.question,reason:"not-self-contained"});continue}const u=tokens(e.body||e.text||e.content,s),a=tokens(t.question,s),l=shouldRecall(u,a,{tokPerSec:n});l.recall?(r.push({stage:o.identify>0?"seek":"ground",question:t.question,bodyTokens:u,questionTokens:a,savesSecs:l.savedSecs}),c+=a):i.push({question:t.question,reason:"question-too-costly",savedSecs:l.savedSecs})}for(const e of u){const t=tokens(e.question,s);r.push({stage:"seek",question:e.question,members:e.members,bodyTokens:e.bodyTokens,questionTokens:t,savesSecs:prefillSecs(e.bodyTokens-t,n)}),c+=t}return{stages:o,queries:r,sendTokens:c,sendSecs:prefillSecs(c,n),skipped:i,budgetTokens:c}}module.exports={STAGE_BUDGETS:STAGE_BUDGETS,BUNDLE_MAX_QUESTION_SHARE:.02,BUNDLE_MIN_TOKENS:600,MULTI_HOP:MULTI_HOP,DANGLING_REF:DANGLING_REF,gist:gist,noteToQuestion:noteToQuestion,bundleNotes:bundleNotes,partitionNotes:partitionNotes,shouldRecall:shouldRecall,stageBudgetFor:stageBudgetFor,buildRecallPlan:buildRecallPlan,estimateTokens:estimateTokens,prefillSecs:prefillSecs};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
2
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
-
"use strict";const MAIN_CHAT_PROMPT='You are Aegiscodex, a terminal coding assistant working in the user\'s repository: read and reason about code, write and edit files, run shell commands, investigate bugs. Work rules:\n- Output is billed by the token and is the largest line on the bill, so spend it where it is read. Before a tool call, one short sentence on what you are about to find out. Do NOT restate file contents, diffs, command output or test results the user can already see. Finish with the answer in a few lines — expand only when asked to explain, or when the change\'s correctness depends on a detail the user must check.\n- Batch independent tool calls into ONE turn: read several files, or grep for several patterns, at once, or use one exec command that does the whole job. Every round re-sends the prefix and bills fresh output; one call per round is the expensive shape.\n- Edit in one call, not one hunk per round: editFile takes an `edits` array, so every hunk you already know about for one file goes in a single call. A fix you can see is a fix you can also write without asking the tool anything in between.\n- Run the thing you changed before you call it done. A patch you never executed is a hypothesis; when the repo has a test or repro command, run it (or the narrowest slice of it) and report what it printed. If you cannot run it, say which command you would have run. - Use tools silently. A one-line reason is enough; do not narrate your plan as a story. - Never claim what a tool found or what a command returned before the tool actually runs. Report only the results you really received. - Before starting a fix or feature, check whether they have asked for it before and whether it was delivered: recalled memory, `queue.jsonl`, `PLAN.md`/notes and `git log` — ONE batched command over sources that exist: if the Environment block says this directory has no version control, skip it. If it was resolved before and the problem is back, report how it was resolved and why it regressed, then fix the cause — never re-fix blind as if it were new. If it was never met, say so plainly before starting. - Match the response to the request. A greeting, a question you already know the answer to, or a request for an opinion is answered in plain words with NO tools. Reach for a tool only when the answer depends on something in this repo or on this machine. "hey" is not a task.\n- WHEN THE USER HAS ASKED FOR WORK: act, don\'t just inspect. After at most 2 rounds of reading or exploration, start making changes with writeFile or editFile. Reconnaissance is not progress — implement, then verify. This is about HOW to carry out a task you were given; it is never a reason to invent one. Never write or modify a file the user did not ask you to touch.\n- Zero tolerance for stalling: once the cause is identified and only the edit remains, make it in the same turn. Never end a turn with an empty or no-op response, or a "let me continue"/"I\'ll now…" placeholder when the user says continue — that wastes their turn. This has been flagged as non-compliance before; treat it as a hard rule. - When you have what you need, stop using tools and give a concise, direct answer. Never end a turn with an intention like "Let me check…" — that is not an answer. - When a focused multi-step sub-task can be delegated, use the task tool to spawn a specialist subagent rather than doing it inline. - If the user references a workflow you don\'t recognize, inspect the repo/scripts for that mechanism before acting.',TOOL_LINE="Tools: readFile, writeFile, editFile, listDir, glob, grep, exec, websearch, task. Paths are absolute in the form THIS machine uses (see the Environment block): on win32 that means C:\\Users\\you\\Desktop\\file.txt, not /home/you/Desktop/file.txt or /tmp/file.txt. exec runs in a persistent shell session — cd and exported env vars carry across calls within the turn. websearch reaches the web for facts this repo cannot answer. task spawns a specialist subagent (its own tool loop, same model).";function languageLine(e){if("string"==typeof e)return e.trim();if(!e||"object"!=typeof e)return"";if("string"==typeof e.value&&e.value.trim())return e.value.trim();const t="string"==typeof e.name?e.name.trim():"",n="string"==typeof e.code?e.code.trim():"string"==typeof e.key?e.key.trim():"";return t&&n?`${t} (${n})`:t||n}function environmentPreamble(e={}){const{platform:t,arch:n,homedir:o,desktopdir:r,dataDir:s,locale:a,localeName:i,languages:h,cwd:l,vcs:c,shell:d,shellKind:u,roots:p,appVersion:m,model:f}=e||{},y=[];if(t&&y.push(`platform: ${t}${n?` (${n})`:""}`),a){const e=String(a).split("-")[0].toLowerCase(),t=i?` (${i})`:"";y.push("en"===e?`locale: ${a}${t}`:`locale: ${a}${t} — the user's own machine and account run in this language, so expect requests written in it and answer in the language the user writes to you in. Use this to resolve an otherwise ambiguous request (a bare path, a pasted error, a one-word command) — never to override a request written in another language.`)}const w=(Array.isArray(h)?h:[]).map(e=>languageLine(e)).filter(Boolean);w.length&&y.push(`recorded language evidence from the user's own saved writing: ${w.join("; ")} — the language of the request in front of you always wins; this is evidence, not an instruction to switch`),o&&y.push(`home directory: ${o}`),r&&y.push(`desktop directory: ${r} — use this exact path when the user says "my desktop"; do NOT build it yourself from the home directory`),s&&y.push(`AEGIS data directory: ${s} — the store itself (config, sessions, credentials, queue). Use this exact path; do NOT append it to the home directory yourself, because a dropped separator ("C:\\Users\\you.aegiscode") names a path that does not exist and looks like an empty directory rather than a mistake`),l&&y.push(`working directory: ${l}`),"git"===c?y.push("version control: this directory IS inside a git work tree, so `git log`, `git diff` and `git status` are usable for checking what was already done"):""===c&&y.push("version control: this directory is NOT a git repository and has no history to consult — do NOT run `git log`, `git diff`, `git blame` or `git status`; they fail here and cost a round. Read the files that exist instead"),d&&y.push(`exec shell: ${d}${u?` (${u})`:""}`),f&&y.push(`model: ${f}`),m&&y.push(`aegis one ${m}`);const g=Array.isArray(p)?p.filter(Boolean):[],b=[];y.length&&b.push(y.join("\n")),g.length&&b.push(`repo roots:\n${g.map(e=>` - ${e}`).join("\n")}`);const v=commandDialectLine(t,u);return v&&b.push(v),b.length?`# Environment\n${b.join("\n")}`:""}function commandDialectLine(e,t){return e?"win32"===e?`This is Windows: exec runs ${"powershell"===t?"PowerShell":"a Windows shell"}, so use Windows-native commands — Get-ChildItem/dir, Get-Content/type, Select-String/findstr, where, New-Item -ItemType Directory — NOT ls, cat, grep, mkdir -p, touch or rm -rf, which do not exist here. Separate paths with \\, and never assume /tmp, /usr or /home exist.`:"darwin"===e?"This is macOS: exec runs a POSIX shell and the standard Unix commands are available, but the userland is BSD, not GNU — sed -i needs an argument (sed -i ''), and readlink -f, date -d and sed -r are absent. Prefer portable forms, or python3.":"This is a POSIX host: the standard Unix commands are available in exec.":""}const PROJECT_DOC_NAMES=["AEGIS.md","AGENTS.md","CLAUDE.md"],PROJECT_DOC_MAX_CHARS=8e3;function readProjectDoc(e,t={}){if(!e)return"";let n=t.fs,o=t.path;try{n||(n=require("node:fs")),o||(o=require("node:path"))}catch(e){return""}for(const t of PROJECT_DOC_NAMES){let r;try{const s=o.join(e,t),a=n.statSync(s);if(!a||!a.isFile())continue;r=n.readFileSync(s,"utf8")}catch(e){continue}if("string"!=typeof r)continue;const s=r.trim();if(s)return`# Project instructions (${t})\nThese are this repository's own rules. They outrank the generic work rules above wherever the two disagree, and they are the source for build/test/lint commands — prefer them over re-deriving commands by exploring.\n\n`+(s.length>8e3?s.slice(0,8e3)+`\n\n[${t} truncated at 8000 characters — read the file for the rest]`:s)}return""}function buildSystemPrompt(e={}){const t=[MAIN_CHAT_PROMPT,TOOL_LINE],n="string"==typeof e.projectDoc&&e.projectDoc.trim()?e.projectDoc.trim():readProjectDoc(e.cwd||process.cwd());n&&t.push(n);const o=environmentPreamble(e);return o&&t.push(o),t.join("\n\n")}module.exports={MAIN_CHAT_PROMPT:MAIN_CHAT_PROMPT,TOOL_LINE:TOOL_LINE,PROJECT_DOC_NAMES:PROJECT_DOC_NAMES,PROJECT_DOC_MAX_CHARS:8e3,environmentPreamble:environmentPreamble,commandDialectLine:commandDialectLine,readProjectDoc:readProjectDoc,buildSystemPrompt:buildSystemPrompt};
|
|
3
|
+
"use strict";const MAIN_CHAT_PROMPT='You are Aegiscodex, a terminal coding assistant working in the user\'s repository: read and reason about code, write and edit files, run shell commands, investigate bugs. Work rules:\n- Output is billed by the token and is the largest line on the bill, so spend it where it is read. Before a tool call, one short sentence on what you are about to find out. Do NOT restate file contents, diffs, command output or test results the user can already see. Finish with the answer in a few lines — expand only when asked to explain, or when the change\'s correctness depends on a detail the user must check.\n- Batch independent tool calls into ONE turn: read several files, or grep for several patterns, at once, or use one exec command that does the whole job. Every round re-sends the prefix and bills fresh output; one call per round is the expensive shape.\n- Edit in one call, not one hunk per round: editFile takes an `edits` array, so every hunk you already know about for one file goes in a single call. A fix you can see is a fix you can also write without asking the tool anything in between.\n- Run the thing you changed before you call it done. A patch you never executed is a hypothesis; when the repo has a test or repro command, run it (or the narrowest slice of it) and report what it printed. If you cannot run it, say which command you would have run. - Use tools silently. A one-line reason is enough; do not narrate your plan as a story. - Never claim what a tool found or what a command returned before the tool actually runs. Report only the results you really received. - Before starting a fix or feature, check whether they have asked for it before and whether it was delivered: recalled memory, `queue.jsonl`, `PLAN.md`/notes and `git log` — ONE batched command over sources that exist: if the Environment block says this directory has no version control, skip it. If it was resolved before and the problem is back, report how it was resolved and why it regressed, then fix the cause — never re-fix blind as if it were new. If it was never met, say so plainly before starting. - Match the response to the request. A greeting, a question you already know the answer to, or a request for an opinion is answered in plain words with NO tools. Reach for a tool only when the answer depends on something in this repo or on this machine. "hey" is not a task.\n- WHEN THE USER HAS ASKED FOR WORK: act, don\'t just inspect. After at most 2 rounds of reading or exploration, start making changes with writeFile or editFile. Reconnaissance is not progress — implement, then verify. This is about HOW to carry out a task you were given; it is never a reason to invent one. Never write or modify a file the user did not ask you to touch.\n- Zero tolerance for stalling: once the cause is identified and only the edit remains, make it in the same turn. Never end a turn with an empty or no-op response, or a "let me continue"/"I\'ll now…" placeholder when the user says continue — that wastes their turn. This has been flagged as non-compliance before; treat it as a hard rule. - When you have what you need, stop using tools and give a concise, direct answer. Never end a turn with an intention like "Let me check…" — that is not an answer. - When a focused multi-step sub-task can be delegated, use the task tool to spawn a specialist subagent rather than doing it inline. - If the user references a workflow you don\'t recognize, inspect the repo/scripts for that mechanism before acting.',TOOL_LINE="Tools are listed in your schema. Paths are absolute in the form THIS machine uses (see the Environment block): on win32 that means C:\\Users\\you\\Desktop\\file.txt, not /home/you/Desktop/file.txt or /tmp/file.txt. exec runs in a persistent shell session — cd and exported env vars carry across calls within the turn.",SLIM_TOOL_LINE="Paths are absolute in the form THIS machine uses (see the Environment block): on win32 that means C:\\Users\\you\\Desktop\\file.txt, not /home/you/Desktop/file.txt.";function languageLine(e){if("string"==typeof e)return e.trim();if(!e||"object"!=typeof e)return"";if("string"==typeof e.value&&e.value.trim())return e.value.trim();const t="string"==typeof e.name?e.name.trim():"",n="string"==typeof e.code?e.code.trim():"string"==typeof e.key?e.key.trim():"";return t&&n?`${t} (${n})`:t||n}function environmentPreamble(e={}){const{platform:t,arch:n,homedir:o,desktopdir:r,dataDir:s,locale:a,localeName:i,languages:l,shell:h,shellKind:d,roots:u,appVersion:c}=e||{},m=[];if(t&&m.push(`platform: ${t}${n?` (${n})`:""}`),a){const e=String(a).split("-")[0].toLowerCase(),t=i?` (${i})`:"";m.push("en"===e?`locale: ${a}${t}`:`locale: ${a}${t} — the user's own machine and account run in this language, so expect requests written in it and answer in the language the user writes to you in. Use this to resolve an otherwise ambiguous request (a bare path, a pasted error, a one-word command) — never to override a request written in another language.`)}const p=(Array.isArray(l)?l:[]).map(e=>languageLine(e)).filter(Boolean);p.length&&m.push(`recorded language evidence from the user's own saved writing: ${p.join("; ")} — the language of the request in front of you always wins; this is evidence, not an instruction to switch`),o&&m.push(`home directory: ${o}`),r&&m.push(`desktop directory: ${r} — use this exact path when the user says "my desktop"; do NOT build it yourself from the home directory`),s&&m.push(`AEGIS data directory: ${s} — the store itself (config, sessions, credentials, queue). Use this exact path; do NOT append it to the home directory yourself, because a dropped separator ("C:\\Users\\you.aegiscode") names a path that does not exist and looks like an empty directory rather than a mistake`),h&&m.push(`exec shell: ${h}${d?` (${d})`:""}`),c&&m.push(`aegis one ${c}`);const f=Array.isArray(u)?u.filter(Boolean):[],y=[];m.length&&y.push(m.join("\n")),f.length&&y.push(`repo roots:\n${f.map(e=>` - ${e}`).join("\n")}`);const w=commandDialectLine(t,d);return w&&y.push(w),y.length?`# Environment\n${y.join("\n")}`:""}function volatilePreamble(e={}){const{cwd:t,vcs:n,model:o}=e||{},r=[];return t&&r.push(`working directory: ${t}`),"git"===n?r.push("version control: this directory IS inside a git work tree, so `git log`, `git diff` and `git status` are usable for checking what was already done"):""===n&&r.push("version control: this directory is NOT a git repository and has no history to consult — do NOT run `git log`, `git diff`, `git blame` or `git status`; they fail here and cost a round. Read the files that exist instead"),o&&r.push(`model: ${o}`),r.length?`# Session\n${r.join("\n")}`:""}function commandDialectLine(e,t){return e?"win32"===e?`This is Windows: exec runs ${"powershell"===t?"PowerShell":"a Windows shell"}, so use Windows-native commands — Get-ChildItem/dir, Get-Content/type, Select-String/findstr, where, New-Item -ItemType Directory — NOT ls, cat, grep, mkdir -p, touch or rm -rf, which do not exist here. Separate paths with \\, and never assume /tmp, /usr or /home exist.`:"darwin"===e?"This is macOS: exec runs a POSIX shell and the standard Unix commands are available, but the userland is BSD, not GNU — sed -i needs an argument (sed -i ''), and readlink -f, date -d and sed -r are absent. Prefer portable forms, or python3.":"This is a POSIX host: the standard Unix commands are available in exec.":""}const PROJECT_DOC_NAMES=["AEGIS.md","AGENTS.md","CLAUDE.md"],PROJECT_DOC_MAX_CHARS=8e3;function readProjectDoc(e,t={}){if(!e)return"";let n=t.fs,o=t.path;try{n||(n=require("node:fs")),o||(o=require("node:path"))}catch(e){return""}for(const t of PROJECT_DOC_NAMES){let r;try{const s=o.join(e,t),a=n.statSync(s);if(!a||!a.isFile())continue;r=n.readFileSync(s,"utf8")}catch(e){continue}if("string"!=typeof r)continue;const s=r.trim();if(s)return`# Project instructions (${t})\nThese are this repository's own rules. They outrank the generic work rules above wherever the two disagree, and they are the source for build/test/lint commands — prefer them over re-deriving commands by exploring.\n\n`+(s.length>8e3?s.slice(0,8e3)+`\n\n[${t} truncated at 8000 characters — read the file for the rest]`:s)}return""}const SLIM_CHAT_PROMPT='You are Aegiscodex, a terminal coding assistant in the user\'s repository. Work rules:\n- Match the response to the request. A greeting, a question you already know the answer to, or a request for an opinion is answered in plain words with NO tools. "hey" is not a task. When the user HAS asked for work, act: after at most 2 rounds of reading, start editing. Never write or modify a file the user did not ask you to touch.\n- Batch independent tool calls into ONE turn: several files, or several greps, in one round. Every round re-sends the prefix and bills fresh output.\n- Use tools silently: one short sentence on what you are about to find out, never a narrated plan. Never claim what a tool found before it actually runs.\n- Do NOT restate file contents, diffs, command output or test results the user can already see. Finish with the answer in a few lines.\n- Run the thing you changed before calling it done, or say which command you would run.';function buildSystemPrompt(e={}){const t=e&&"local"===e.class,n=[t?SLIM_CHAT_PROMPT:MAIN_CHAT_PROMPT,t?SLIM_TOOL_LINE:TOOL_LINE],o="string"==typeof e.projectDoc&&e.projectDoc.trim()?e.projectDoc.trim():readProjectDoc(e.cwd||process.cwd());o&&n.push(o);const r=environmentPreamble(e);r&&n.push(r);const s=volatilePreamble(e);return s&&n.push(s),n.join("\n\n")}module.exports={MAIN_CHAT_PROMPT:MAIN_CHAT_PROMPT,SLIM_CHAT_PROMPT:SLIM_CHAT_PROMPT,TOOL_LINE:TOOL_LINE,SLIM_TOOL_LINE:SLIM_TOOL_LINE,PROJECT_DOC_NAMES:PROJECT_DOC_NAMES,PROJECT_DOC_MAX_CHARS:8e3,environmentPreamble:environmentPreamble,volatilePreamble:volatilePreamble,commandDialectLine:commandDialectLine,readProjectDoc:readProjectDoc,buildSystemPrompt:buildSystemPrompt};
|
|
@@ -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 RRF_K=60,BM25_K1=1.5,BM25_B=.75,MAX_CANDIDATES=500,STOPWORDS=new Set(["the","a","an","and","or","of","to","in","is","it","for","on","that","this","with","as","was","are","be","by","at","from"]);function tokenize(r){return String(null==r?"":r).toLowerCase().replace(/[^\p{L}\p{N}_.:/-]+/gu," ").split(/\s+/).filter(r=>r.length>1&&!STOPWORDS.has(r))}function rowText(r){const e=Array.isArray(r&&r.tags)?r.tags.join(" "):"";return`${r&&(r.body||r.text||r.content)||""} ${e}`}function bm25Rank(r,e){const t=Array.isArray(r)?r.filter(Boolean):[],n=[...new Set(tokenize(e))];if(!t.length||!n.length)return[];const o=t.map(r=>tokenize(rowText(r))),s=o.reduce((r,e)=>r+e.length,0)/o.length||1,a=new Map;for(const r of n){let e=0;for(const t of o)t.includes(r)&&(e+=1);a.set(r,Math.log(1+(o.length-e+.5)/(e+.5)))}return t.map((r,e)=>{const t=o[e];let i=0;for(const r of n){const e=t.filter(e=>e===r).length;if(!e)continue;const n=e+1.5*(.25+.75*t.length/s);i+=(a.get(r)||0)*(2.5*e/n)}return{row:r,score:i}}).filter(r=>r.score>0).sort((r,e)=>e.score-r.score||r.row.id.localeCompare(e.row.id))}function entityRank(r,e){const t=Array.isArray(r)?r.filter(Boolean):[],n=new Set(tokenize(e));if(!t.length||!n.size)return[];const o=r=>String(r).toLowerCase().split(/[\s_.:/-]+/).filter(Boolean);return t.map(r=>{const e=(Array.isArray(r.tags)?r.tags:[]).map(r=>String(r).toLowerCase());let t=0;for(const r of e)(n.has(r)||o(r).some(r=>n.has(r)))&&(t+=1);return{row:r,score:t}}).filter(r=>r.score>0).sort((r,e)=>e.score-r.score||r.row.id.localeCompare(e.row.id))}function denseRank(r,e,{dot:t}={}){const n=Array.isArray(r)?r.filter(Boolean):[],o=Array.isArray(e)?e:null;if(!n.length||!o)return[];const s="function"==typeof t?t:(r,e)=>{let t=0;const n=Math.min(r.length,e.length);for(let o=0;o<n;o+=1)t+=r[o]*e[o];return t};return n.map(r=>({row:r,score:Array.isArray(r.vector)?s(r.vector,o):0})).filter(r=>r.score>0).sort((r,e)=>e.score-r.score||r.row.id.localeCompare(e.row.id))}function recencyRank(r){return(Array.isArray(r)?r.filter(Boolean):[]).slice().sort((r,e)=>(Number(e.updated)||0)-(Number(r.updated)||0)).map(r=>({row:r,score:Number(r.updated)||0}))}function rrfFuse(r,e=60){const t=Number(e)>0?Number(e):60,n=new Map;return(Array.isArray(r)?r:[]).forEach((r,e)=>{(Array.isArray(r)?r:[]).forEach((r,o)=>{if(!r||!r.row)return;const s=r.row.id;n.has(s)||n.set(s,{row:r.row,score:0,ranks:{}});const a=n.get(s);a.score+=1/(t+o+1),a.ranks[e]=o+1})}),[...n.values()].sort((r,e)=>e.score-r.score||r.row.id.localeCompare(e.row.id))}function rank(r,e,{limit:t=5,k:n=60,dense:o=null}={}){const s=Array.isArray(r)?r.filter(Boolean):[],a=Math.max(1,Math.min(200,Number(t)||5)),i=String(null==e?"":e).trim();if(!s.length)return{results:[],signals:[],empty:!0};if(!i)return{results:recencyRank(s).slice(0,a).map(r=>r.row),signals:["recency"],empty:!1};const c=[bm25Rank(s,i),entityRank(s,i)];o&&c.push(denseRank(s,o));const l=rrfFuse(c,n);l.sort((r,e)=>e.score-r.score||(Number(e.row.updated)||0)-(Number(r.row.updated)||0)||String(r.row.id).localeCompare(String(e.row.id)));const u=l.length?l:recencyRank(s).map(r=>({row:r.row,score:0,ranks:{recency:1}}));return{results:u.slice(0,a).map(r=>r.row),signals:o?["lexical","entity","dense"]:["lexical","entity"],ranked:u.slice(0,a),empty:!1}}module.exports={RRF_K:60,BM25_K1:1.5,BM25_B:.75,MAX_CANDIDATES:500,STOPWORDS:STOPWORDS,tokenize:tokenize,rowText:rowText,bm25Rank:bm25Rank,entityRank:entityRank,denseRank:denseRank,recencyRank:recencyRank,rrfFuse:rrfFuse,rank:rank};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
2
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
-
"use strict";const path=require("node:path"),fs=require("node:fs"),MIN_NODE=[22,5,0],SCHEMA_VERSION=1;function versionAtLeast(e){const t=process.versions.node.split(".").map(e=>Number.parseInt(e,10));for(let
|
|
3
|
+
"use strict";const path=require("node:path"),fs=require("node:fs"),ranker=require("./memory-rank.js"),MIN_NODE=[22,5,0],SCHEMA_VERSION=1;function versionAtLeast(e){const t=process.versions.node.split(".").map(e=>Number.parseInt(e,10));for(let s=0;s<e.length;s+=1){const r=t[s]||0;if(r>e[s])return!0;if(r<e[s])return!1}return!0}function loadSqlite(){if(!versionAtLeast(MIN_NODE))return null;const e=process.emitWarning;let t=null;try{process.emitWarning=function(t,...s){const r="string"==typeof s[0]?s[0]:s[0]&&s[0].type,o="string"==typeof t?t:t&&t.message||"";if("ExperimentalWarning"!==r||!/SQLite/i.test(o))return e.call(process,t,...s)},t=require("node:sqlite")}catch{t=null}finally{process.emitWarning=e}return t&&"function"==typeof t.DatabaseSync?t:null}const sqlite=loadSqlite();function isAvailable(){return Boolean(sqlite)}function unavailableReason(){return versionAtLeast(MIN_NODE)?"node:sqlite is not loadable on this runtime":`node:sqlite needs Node >= ${MIN_NODE.join(".")}; this is ${process.versions.node}`}const openHandles=new Map;function entryKey(e){if(e&&"string"==typeof e.id&&e.id)return e.id;const t=String(e&&(e.body||e.text||e.content)||""),s=String(e&&e.scope||"default");return`local:${require("node:crypto").createHash("sha256").update(`${s}\0${t}`).digest("hex").slice(0,32)}`}function normalize(e){const t=e||{},s=String(t.body||t.text||t.content||""),r=Array.isArray(t.tags)?t.tags.map(String):[];return{id:entryKey(t),body:s,scope:String(t.scope||"default"),tags:r,updated:Number(t.updated??t.updated_at??Date.now())||Date.now(),source:String(t.source||"local")}}class MemoryStore{constructor({dir:e,file:t}={}){if(!e&&!t)throw new Error("memory-store: dir or file is required");this.file=t||path.join(e,"memory.db"),this.db=null,this.fts=!1,this.reason=null}open(){if(this.db)return{ok:!0,fts:this.fts,file:this.file};if(!sqlite)return this.reason=unavailableReason(),{ok:!1,reason:this.reason};if(openHandles.get(this.file))throw new Error(`memory-store: a handle for ${this.file} is already open in this process — one owner per file (node:sqlite has no cross-handle locking here)`);try{fs.mkdirSync(path.dirname(this.file),{recursive:!0}),this.db=new sqlite.DatabaseSync(this.file)}catch(e){return this.reason=`open failed: ${e.message}`,this.db=null,{ok:!1,reason:this.reason}}openHandles.set(this.file,this);try{this.db.exec("PRAGMA journal_mode=WAL"),this.db.exec("PRAGMA synchronous=NORMAL"),this.db.exec("PRAGMA busy_timeout=2000")}catch{}const e=this._createSchema();return this._migrate(),{ok:!0,fts:e.fts,file:this.file}}_createSchema(){this.db.exec("\n CREATE TABLE IF NOT EXISTS memory (\n id TEXT PRIMARY KEY,\n body TEXT NOT NULL,\n scope TEXT NOT NULL DEFAULT 'default',\n tags TEXT NOT NULL DEFAULT '[]',\n updated INTEGER NOT NULL,\n source TEXT NOT NULL DEFAULT 'local'\n );\n CREATE INDEX IF NOT EXISTS memory_updated ON memory(updated);\n CREATE INDEX IF NOT EXISTS memory_scope ON memory(scope);\n ");try{this.db.exec("\n CREATE VIRTUAL TABLE IF NOT EXISTS memory_fts\n USING fts5(body, id UNINDEXED, scope UNINDEXED);\n "),this.fts=!0}catch{this.fts=!1}return{fts:this.fts}}_migrate(){if(this.db)try{const e=this.db.prepare("PRAGMA user_version").get(),t=e&&Number(e.user_version)||0;this.fts&&this.db.exec("\n INSERT INTO memory_fts (body, id, scope)\n SELECT m.body, m.id, m.scope FROM memory m\n WHERE NOT EXISTS (SELECT 1 FROM memory_fts f WHERE f.id = m.id)\n "),1!==t&&this.db.exec("PRAGMA user_version = 1")}catch{}}upsert(e){const t=this.open();if(!t.ok)return{ok:!1,reason:t.reason};const s=normalize(e);try{return this.db.prepare("INSERT INTO memory (id, body, scope, tags, updated, source)\n VALUES (?, ?, ?, ?, ?, ?)\n ON CONFLICT(id) DO UPDATE SET\n body = excluded.body,\n scope = excluded.scope,\n tags = excluded.tags,\n updated = excluded.updated,\n source = excluded.source").run(s.id,s.body,s.scope,JSON.stringify(s.tags),s.updated,s.source),this.fts&&(this.db.prepare("DELETE FROM memory_fts WHERE id = ?").run(s.id),this.db.prepare("INSERT INTO memory_fts (body, id, scope) VALUES (?, ?, ?)").run(s.body,s.id,s.scope)),{ok:!0,id:s.id}}catch(e){return{ok:!1,reason:e.message}}}upsertMany(e){const t=this.open();if(!t.ok)return{ok:!1,reason:t.reason,wrote:0,failed:0};const s=Array.isArray(e)?e:[];let r=0,o=0;try{this.db.exec("BEGIN");for(const e of s)this.upsert(e).ok?r+=1:o+=1;this.db.exec("COMMIT")}catch(e){try{this.db.exec("ROLLBACK")}catch{}return{ok:!1,reason:e.message,wrote:r,failed:o}}return{ok:!0,wrote:r,failed:o}}search(e,{limit:t=5,scope:s=null}={}){const r=this.open();if(!r.ok)return{ok:!1,reason:r.reason,results:[]};const o=String(e||"").trim(),n=Math.max(1,Math.min(200,Number(t)||5)),i=o?Math.min(ranker.MAX_CANDIDATES,Math.max(8*n,40)):0;try{let e;if(o)if(this.fts){const t=o.split(/\s+/).filter(Boolean).map(e=>`"${e.replace(/"/g,'""')}"`).join(" ");e=s?this.db.prepare("SELECT m.id, m.body, m.scope, m.tags, m.updated\n FROM memory_fts f JOIN memory m ON m.id = f.id\n WHERE memory_fts MATCH ? AND m.scope = ?\n ORDER BY rank LIMIT ?").all(t,s,i):this.db.prepare("SELECT m.id, m.body, m.scope, m.tags, m.updated\n FROM memory_fts f JOIN memory m ON m.id = f.id\n WHERE memory_fts MATCH ?\n ORDER BY rank LIMIT ?").all(t,i)}else e=s?this.db.prepare("SELECT id, body, scope, tags, updated FROM memory\n WHERE body LIKE '%' || ? || '%' AND scope = ?\n ORDER BY updated DESC LIMIT ?").all(o,s,i):this.db.prepare("SELECT id, body, scope, tags, updated FROM memory\n WHERE body LIKE '%' || ? || '%' ORDER BY updated DESC LIMIT ?").all(o,i);else e=s?this.db.prepare("SELECT id, body, scope, tags, updated FROM memory WHERE scope = ? ORDER BY updated DESC LIMIT ?").all(s,n):this.db.prepare("SELECT id, body, scope, tags, updated FROM memory ORDER BY updated DESC LIMIT ?").all(n);const t=e.map(e=>({id:e.id,body:e.body,scope:e.scope,tags:JSON.parse(e.tags||"[]"),updated:e.updated}));if(o){const e=new Set(t.map(e=>e.id)),r=[...new Set(ranker.tokenize(o))].slice(0,8),n=s?this.db.prepare("SELECT id, body, scope, tags, updated FROM memory\n WHERE tags LIKE '%' || ? || '%' AND scope = ? LIMIT ?"):this.db.prepare("SELECT id, body, scope, tags, updated FROM memory\n WHERE tags LIKE '%' || ? || '%' LIMIT ?");for(const o of r){if(t.length>=ranker.MAX_CANDIDATES)break;const r=s?n.all(o,s,i):n.all(o,i);for(const s of r)e.has(s.id)||(e.add(s.id),t.push({id:s.id,body:s.body,scope:s.scope,tags:JSON.parse(s.tags||"[]"),updated:s.updated}))}}const r=ranker.rank(t,o,{limit:n});return{ok:!0,fts:this.fts,signals:r.signals,results:r.results}}catch(e){return{ok:!1,reason:e.message,results:[]}}}watermark(){if(!this.open().ok)return 0;try{const e=this.db.prepare("SELECT MAX(updated) AS w FROM memory").get();return e&&Number(e.w)||0}catch{return 0}}count(){if(!this.open().ok)return 0;try{const e=this.db.prepare("SELECT COUNT(*) AS n FROM memory").get();return e&&Number(e.n)||0}catch{return 0}}schemaVersion(){if(!this.open().ok)return-1;try{const e=this.db.prepare("PRAGMA user_version").get();return e&&Number(e.user_version)||0}catch{return-1}}close(){if(this.db){try{this.db.close()}catch{}openHandles.delete(this.file),this.db=null}}}function openStore(e){const t=new MemoryStore(e),s=t.open();return{store:t,opened:s}}module.exports={MemoryStore:MemoryStore,openStore:openStore,isAvailable:isAvailable,unavailableReason:unavailableReason,entryKey:entryKey,normalize:normalize,MIN_NODE:MIN_NODE,SCHEMA_VERSION:1};
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"name": "aegis-desktop",
|
|
3
3
|
"productName": "aegis one",
|
|
4
4
|
"desktopName": "aegis-desktop",
|
|
5
|
-
"version": "1.0.
|
|
5
|
+
"version": "1.0.70",
|
|
6
6
|
"description": "Thin Electron host for AEGIS — a local chat UI over the shared client/aegis.js transport. Ships transport + UI only; engine logic stays server-side.",
|
|
7
7
|
"author": {
|
|
8
8
|
"name": "AEGIS Code",
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "aegiscode",
|
|
3
3
|
"productName": "AEGIS Code",
|
|
4
|
-
"version": "7.0.
|
|
4
|
+
"version": "7.0.70",
|
|
5
5
|
"description": "aegiscode — the command-line version of AEGIS One. The shared tool surface in your shell, over the same thin transport and tool registry as the MCP plugin and the desktop app. Ships transport + UI only; no brain.",
|
|
6
6
|
"author": {
|
|
7
7
|
"name": "AEGIS Code",
|
|
@@ -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 readline=require("node:readline"),os=require("node:os"),{randomUUID:randomUUID}=require("node:crypto"),{createTools:createTools,createClient:createClient,usageTokens:usageTokens,usageBuckets:usageBuckets,buildSystemPrompt:buildSystemPrompt,autoProvisionApiKey:autoProvisionApiKey,provisionFailureText:provisionFailureText,trialNote:trialNote,hostEnv:hostEnv,autonomous:autonomous,claudePro:claudePro}=require("./deps.js"),{createEngine:createEngine,HOST_CLASSES:HOST_CLASSES,DEFAULT_CLASS:DEFAULT_CLASS,byokNamespace:byokNamespace,effortRung:effortRung,offeredClasses:offeredClasses,proEnabled:proEnabled}=require("./engine.js"),{GLYPH:GLYPH,VERBS:VERBS,themeOf:themeOf,RESET:RESET,THEME_TABLE:THEME_TABLE,AUTO_THEME_INDEX:AUTO_THEME_INDEX,themeIsLight:themeIsLight,reconcileThemeIndex:reconcileThemeIndex}=require("./theme.js"),{probeTerminalBackground:probeTerminalBackground}=require("./caps.js"),{LiveRegion:LiveRegion,termWidth:termWidth,w:w}=require("./screen.js"),{estimateTokensFromCells:estimateTokensFromCells}=require("./tokens.js"),{editPreview:editPreview}=require("./diff.js"),{defaultOpen:defaultOpen}=require("./diffview.js"),{parseLine:parseLine,COMMANDS:COMMANDS,visibleCommands:visibleCommands,runAutoModelSync:runAutoModelSync}=require("./commands.js"),{updateConfig:updateConfig,loadPermissions:loadPermissions,loadConfig:loadConfig,configExists:configExists,memoryPersistState:memoryPersistState,memoryPersistEnabled:memoryPersistEnabled,setMemoryPersist:setMemoryPersist,confirmPosture:confirmPosture,permissionMode:permissionMode}=require("./config.js"),credentials=require("./credentials.js"),events=require("./events.js"),cloudsync=require("./cloudsync.js"),{readSecret:readSecret}=require("./secret.js"),{normalizeModelCatalog:normalizeModelCatalog,pickerEntries:pickerEntries,catalogIds:catalogIds,providerForModel:providerForModel,withAutoRow:withAutoRow,AUTO_MODEL_ID:AUTO_MODEL_ID}=require("./models.js"),{appendHistory:appendHistory,readSessionTranscript:readSessionTranscript,readOwnSessions:readOwnSessions,setSessionTitle:setSessionTitle}=require("./history.js"),naming=require("./naming.js"),{snapshotCheckpoint:snapshotCheckpoint}=require("./checkpoint.js"),screens=require("./screens.js"),chatflow=require("./chatflow.js"),overlays=require("./overlays.js"),render=require("./render.js"),{fmtTokens:fmtTokens,fmtEur:fmtEur,maskKey:maskKey,feeBillable:feeBillable}=require("./format.js"),{resolveSkip:resolveSkip}=require("./permissions.js"),VERSION=require("../package.json").version;let _defaultSystem=null;function defaultSystemPrompt(){if(null===_defaultSystem)try{_defaultSystem=buildSystemPrompt(hostEnv({},{},null))}catch{_defaultSystem=""}return _defaultSystem||void 0}function normalizeDecision(e){const t="string"==typeof e?e.trim().toLowerCase():"";return"session"===t?"session":"once"===t||"allow"===t||"yes"===t||"approve"===t||"approved"===t?"once":"deny"}const PROVIDER_REFUSAL_PATTERNS=Object.freeze([/^invalid api key\b/i,/^fix external api key\b/i,/^you've hit your session limit\b/i,/^you have hit your session limit\b/i,/^provider request timed out\b/i,/^insufficient (?:credit|balance|quota)\b/i,/^rate limit(?:ed)?\b/i,/^unauthorized\b/i]);function providerRefusal(e,t){if("string"!=typeof e)return null;const n=t&&(t.total_tokens||0),r=t&&(t.output_tokens||t.completion_tokens||0);if(n>0||r>0)return null;const o=e.trim();if(!o||o.length>160||o.includes("\n"))return null;for(const e of PROVIDER_REFUSAL_PATTERNS)if(e.test(o))return o;return null}function briefArgs(e){let t;try{t="string"==typeof e?e:JSON.stringify(e??"")}catch{t=String(e)}return t=String(t).replace(/\s+/g," ").trim(),t.length>140?`${t.slice(0,137)}...`:t}function createApp(e={}){const t={model:null,stream:!0,light:!1,maxTokens:void 0,system:void 0,interactive:!0,...e},n=e.out||process.stdout,r=e.err||process.stderr,o=e.client||createClient(credentials.clientOptions({channel:"cli"})),{createLocalWiki:s}=require("./dream-cmd.js"),{TOOLS:i,toolList:a}=e.tools||createTools(o,{localWiki:s()});let l=!1,c="";async function d(){const e=await autoProvisionApiKey(o,credentials,{app:"cli"});return c=e.key?"":provisionFailureText(e),e}async function u(){if(o.apiKey||l)return;l=!0;const e=await d();e.key&&V(render.renderNotice(S(),"info","auto-provisioned a free account"+(e.ok?` (saved to ${credentials.credentialsPath()})`:" (could not save it — reconfigure with /key)")+trialNote(e)+`. Fund it at ${o.promptUrl("topup","device_autoprovision")} or run /byok to use your own key.`))}let m=!1!==e.confirmMode,f=(()=>{try{return autonomous.autoRoundsDefault(process.env)}catch{return!0}})();const p=e.engine||createEngine({client:o,getClass:()=>g.modelClass,getProEnabled:()=>{try{return proEnabled(loadConfig())}catch{return!1}},getConfirmMode:()=>{if(void 0!==e.confirmMode)return m;try{const e=resolveSkip({env:process.env,interactive:Boolean(process.stdin.isTTY&&process.stdout.isTTY)});if(e.warned&&!skipEnvWarned&&(skipEnvWarned=!0,process.stderr.write(`aegiscode: ${e.warning}\n`)),e.skip)return!1}catch{}try{return confirmPosture().enabled}catch{return m}},getPermissionMode:()=>{try{return permissionMode()}catch{return null}}}),y=e=>"function"==typeof p.classLabel?p.classLabel(e):String(e||""),h=()=>e.width?e.width():termWidth(),g={light:t.light,model:t.model,modelClass:DEFAULT_CLASS,effort:null,thinking:!1,recallDeep:!1,themeIndex:t.light?2:AUTO_THEME_INDEX,vim:!1,stream:t.stream,cwd:process.cwd(),lastRecap:null,sessionId:randomUUID()};g.themeIndex===AUTO_THEME_INDEX&&(g.light=themeIsLight(AUTO_THEME_INDEX));const k=[];let v=!1;const S=()=>({light:g.light}),b={turns:0,calls:0,tokens:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,cost:0,balance:null,seenLedgerRows:new Map,ledgerBaselined:!1,startedAt:Date.now()};let T=null,E=!1;function C(e){if(!e||"object"!=typeof e)return null;if("usage"!==e.kind)return null;const t=null!=e.amount_eur?Number(e.amount_eur):-Number(e.charged_micros||0)/1e6;return Number.isFinite(t)?Math.abs(t):null}function I(e){return[e.created_at||"",e.kind||"",null!=e.amount_eur?e.amount_eur:"",null!=e.charged_micros?e.charged_micros:"",null!=e.id?e.id:"",null!=e.note?e.note:""].join("|")}async function N(){try{const e=await o.tokenBankBalance(),t=Number(e.balance_eur);Number.isFinite(t)&&(b.balance=t);let n=null;const r=Array.isArray(e.ledger)?e.ledger:[],s=new Map;for(const e of r){const t=I(e),n=s.get(t);n?n.n+=1:s.set(t,{n:1,row:e})}for(const[e,{n:t,row:r}]of s){const o=b.seenLedgerRows.get(e)||0;if(b.seenLedgerRows.set(e,t),!b.ledgerBaselined)continue;const s=t-o;if(s<=0)continue;const i=C(r);null!=i&&i>0&&(b.cost+=i*s,null==n&&(n=i))}return b.ledgerBaselined=!0,{balance:b.balance,lastCost:n}}catch{return null}}async function A(e,{verify:t=!0}={}){const n=credentials.saveApiKey(e);if(!n.ok)return n;o.setApiKey(n.key),R.models=[],R.at=0;let r=null,s=null;if(t)try{const e=await o.verifyApiKey()||{};r=e;const t={verifiedAt:(new Date).toISOString()};e.memory_token&&(t.memoryToken=e.memory_token),e.plan&&(t.plan=e.plan),t.account={plan:e.plan||null,email:e.email||null,valid:!1!==e.valid},credentials.writeCredentials(t),e.plan&&(b.plan=e.plan),e.email&&(b.account={...b.account||{},email:e.email})}catch(e){s=e}return{...n,account:r,error:s}}function P(){const e=credentials.clearApiKey();return o.setApiKey(""),R.models=[],R.at=0,e}function M(){try{return memoryPersistEnabled()}catch{return!0}}function x(){try{return memoryPersistState()}catch{return{enabled:!0,source:"default",explicit:!1}}}function O(e){return setMemoryPersist(e)}function L(){try{return"config"!==credentials.resolveApiKey().source?[]:credentials.adoptLegacy().adopted}catch{return[]}}const _=3e5,R={at:0,models:[]},$={at:0,models:[],declared:""},K={at:0,models:[]};async function D({force:e=!1}={}){const t=function(){try{if("function"!=typeof p.userModels)return"";const e=(p.userModels()||{}).map||{};return JSON.stringify(Object.keys(e).sort().map(t=>[t,e[t]]))}catch{return""}}(),n=$.models.length&&Date.now()-$.at<_&&t===$.declared;if(!e&&n)return $.models;if("function"!=typeof p.listModels)return[];const r=await p.listModels("byok");return $.models=(r&&r.models||[]).map(e=>({...e,note:e.configured?"key on this machine":`no key — /byok-key ${e.provider}`})),$.at=Date.now(),$.declared=t,$.models}async function q(e){const t=H();if(e&&!t.includes(e)&&HOST_CLASSES.includes(e))return[];const n=t.includes(e)?e:g.modelClass;try{if("byok"===n){const e=await D();if(!R.models.length)try{await F()}catch{}return B(e,n)}if("pro"===n){const e=await p.listModels("pro");return(e&&e.models||[]).map(e=>({...e,cls:"pro"}))}if("local"===n){const e=await p.listModels("local");return K.models=e&&e.models||[],K.at=Date.now(),K.models}if("aegis"!==n){const e=await p.listModels(n);return e&&e.models||[]}return await F()}catch{return[]}}function j(){return withAutoRow(pickerEntries(R.models)).map(e=>({...e,cls:"aegis"}))}function B(e,t){const n=H(),r=n.includes(t)?t:g.modelClass;if("pro"===t&&!n.includes("pro"))return[];if("pro"===r)return pickerEntries(claudePro.PRO_MODELS.map(e=>({id:e.id,label:e.label,note:e.note}))).map(e=>({...e,cls:"pro"}));if("local"===r)return pickerEntries(K.models).map(e=>({...e,cls:"local"}));if("byok"!==r)return j();const o=Array.isArray(e)?e.map(e=>({...e,cls:"byok"})):pickerEntries($.models).map(e=>({...e,cls:"byok"}));return[...j(),...o]}function U(){return new Set(claudePro.PRO_MODELS.map(e=>String(e.id).toLowerCase()))}function H(){try{return offeredClasses(proEnabled(loadConfig()))}catch{return offeredClasses(!1)}}async function F({force:e=!1}={}){const t=R.models.length&&Date.now()-R.at<_;if(!e&&t)return R.models;const n=await o.listModels();return R.models=normalizeModelCatalog(n&&n.models),R.at=Date.now(),R.models}async function W(){const e=g.model;if(!e)return null;if("byok"===g.modelClass)return String(e).includes(":")?null:(g.model=null,updateConfig({model:null,currentModelId:null}),V(render.renderNotice(S(),"warn",`pinned model "${e}" belongs to the pooled class — on BYOK an id is "<provider>:<model>"; pin cleared, /models lists what this machine can relay.`)),e);if("pro"===g.modelClass){if(!U().has(String(e).toLowerCase()))return g.model=null,updateConfig({model:null,currentModelId:null}),V(render.renderNotice(S(),"warn",`pinned model "${e}" is not one the Claude Code CLI resolves — pin cleared, the CLI will choose; /models lists the aliases (${claudePro.PRO_MODELS.map(e=>e.id).join(", ")}).`)),e;let t=!0;try{t=!!claudePro.claudeProStatus({env:process.env}).credentialPresent}catch{t=!0}return t?null:(g.model=null,updateConfig({model:null,currentModelId:null}),V(render.renderNotice(S(),"warn",`pinned model "${e}" needs a Claude Pro subscription or an ANTHROPIC_API_KEY, and this host has neither — pin cleared. Run \`claude /login\`, export a console key, or \`/class pro off\`.`)),e)}let t;try{t=await F()}catch{return null}return t.length?String(e).trim().toLowerCase()===AUTO_MODEL_ID||catalogIds(t).has(String(e).toLowerCase())?null:(g.model=null,updateConfig({model:null,currentModelId:null}),V(render.renderNotice(S(),"warn",`pinned model "${e}" is not advertised by AEGIS Cloud — pin cleared, the pool will choose; /models lists what you can pin.`)),e):null}function Y(){return render.renderBanner(S(),{width:h(),version:VERSION,model:g.model||"server default",base:o.apiBase,key:maskKey(o.apiKey),stream:g.stream})}function V(e){const t="string"==typeof e?[e]:e;for(const e of t)n.write(e+"\n")}async function G(e,{history:o=[],presenter:s=null,signal:i=null}={}){const a=Date.now(),l=!s&&t.interactive&&t.stream&&n.isTTY?new LiveRegion(n):null;let c=0,d=0,u="",m=0,f=0,y=VERBS[Math.floor(Math.random()*VERBS.length)],k=!1,v=!1;const b=()=>{l&&l.update([render.renderWorking(S(),{tick:c++,verb:y,elapsedMs:Date.now()-a,streamed:estimateTokensFromCells(d+m)+f,streamedFloor:f>0})])},E=l?setInterval(b,90):null;E&&E.unref&&E.unref(),b();const C=s||{},I=new Map,N=randomUUID();T=N;let A=!1;const P=()=>{A=!0,p.cancel(N)},M=()=>P();process.once("SIGINT",M),i&&(i.aborted?P():i.addEventListener("abort",P,{once:!0}));const x=e=>(r.write(`aegiscode: ${e.tool} needs confirmation but this run has no prompt for it — denied (pass --automode (alias --yolo) to auto-approve mutating tools).\n`),Promise.resolve("deny")),O=()=>Promise.resolve(!1),L=e=>{if(e){if(e.thinkingTokens&&(f+=e.thinkingTokens,k||(k=!0,y="Reasoning"),(e=>{C.thinkingTokens&&C.thinkingTokens(e)})(e.thinkingTokens),b()),e.reasoning&&(m+=w(e.reasoning),k||(k=!0,y="Reasoning",b()),(e=>{C.reasoning&&C.reasoning(e)})(e.reasoning)),e.delta&&(d+=w(e.delta),u+=e.delta,(e=>{if(C.text)return C.text(e);l&&c%2==0&&b()})(e.delta)),e.tool&&(v=!0,(e=>{if(C.tool)return C.tool(e);l&&l.clear();const t=(e=>{const t=e&&void 0!==e.id?`id:${e.id}`:`${e&&e.name}:${JSON.stringify(e&&e.args)}`;return I.has(t)||I.set(t,editPreview(e&&e.name,e&&e.args,{cwd:process.cwd()})),I.get(t)})(e);V(render.renderTurn(S(),{role:"tool",label:e.name,args:e.args,ok:e.ok,diff:t,diffOpen:defaultOpen(t)},h())),b()})(e.tool)),e.approval){const t=e.approval;l&&l.clear();const n=C.approval||x;Promise.resolve(n(t)).catch(()=>"deny").then(e=>p.respondApproval(t.id,normalizeDecision(e)))}if(e.rounds){const t=e.rounds;l&&l.clear();const n=C.rounds||O;Promise.resolve(n(t)).catch(()=>!1).then(e=>p.respondRoundsAsk(t.id,!0===e))}}};try{const n=await p.chat({prompt:e,messages:o,model:g.model||void 0,system:t.system||defaultSystemPrompt(),maxTokens:t.maxTokens,effort:effortRung(g.effort),recallDeep:!0===g.recallDeep||void 0,stream:!1!==g.stream,sessionId:N,sessionKey:g.sessionId,rootSessionId:g.sessionId,roundsAsk:Boolean(C.rounds)},L),r=n.choices&&n.choices[0]||{};return{text:r.message&&r.message.content||u,usage:n.usage||null,model:n.model||g.model||null,ms:Date.now()-a,interrupted:A,reasoningChars:m,usedTools:v}}catch(e){if(A&&u)return{text:u,usage:null,model:g.model||null,ms:Date.now()-a,interrupted:!0,reasoningChars:m,usedTools:v};throw e}finally{E&&clearInterval(E),process.removeListener("SIGINT",M),i&&i.removeEventListener("abort",P),l&&l.clear(),T=null}}function z(e){V(render.renderTurn(S(),e,h()))}async function X(e,{label:t="you"}={}){if(!e)return void V(render.renderNotice(S(),"warn","nothing to ask — give /ask a prompt"));if(o.apiKey||await u(),!o.apiKey)return void V(render.renderNotice(S(),"error",`no AEGIS account key — ${credentials.HOW_TO_SET} (or set $${credentials.KEY_ENV})`));const n=k.filter(e=>"user"===e.role||"assistant"===e.role).map(e=>({role:e.role,content:e.text}));let r;z({role:"user",text:e,label:t}),k.push({role:"user",text:e});try{r=await G(e,{history:n})}catch(t){return le(e,{text:"",error:t.message},"error"),void V(render.renderTurn(S(),{role:"error",text:t.message},h()))}r.text&&k.push({role:"assistant",text:r.text});const s=ae(r);let i=null;try{const e=await N();i=e?e.lastCost:null}catch{}le(e,r,r.interrupted?"stopped":r.error?"error":"done",i),z({role:"assistant",text:r.text||"(the pool returned no text — see /balance for what it charged)",meta:{model:r.model,tokens:s,usage:null==r.usage?null:usageBuckets(r.usage),eur:i,ms:r.ms,calls:1}}),r.interrupted&&V(render.renderNotice(S(),"warn","interrupted — the pool may still be running and billing this call"))}async function J(e,t){const n=i[e];if(!n)throw new Error(`unknown tool: ${e}`);if(o.apiKey||await u(),!o.apiKey)throw new Error(`no AEGIS account key — ${credentials.HOW_TO_SET}`);const r=await n.run(t||{});V(render.renderToolResult(S(),e,r,h()))}function Q(e){const t=String(e||"").toLowerCase();if(!t)return null;let n=null;for(const e of COMMANDS)for(const r of[e.name,...e.aliases||[]])r!==t&&(r.startsWith(t)||t.startsWith(r))&&(null==n||Math.abs(r.length-t.length)<Math.abs(n.length-t.length))&&(n=r);return n}function Z(){const e=loadPermissions(),t=confirmPosture();return{version:VERSION,model:g.model||"server default",class:g.modelClass,effort:g.effort,thinking:g.thinking,theme:g.light?"light":"dark",themeIndex:g.themeIndex,vim:g.vim,stream:g.stream,cwd:g.cwd,home:os.homedir(),sessionId:g.sessionId,base:o.apiBase,keyMask:maskKey(o.apiKey),online:!!o.apiKey,turns:b.turns,calls:b.calls,startedAt:b.startedAt,tokens:{input:b.inputTokens,output:b.outputTokens,cacheRead:b.cacheReadTokens,cacheWrite:b.cacheWriteTokens,total:b.tokens},costEur:b.cost,balance:b.balance,plan:b.plan||null,account:b.account||null,permissions:{mode:t.enabled?e.defaultMode:"allow",confirm:t.enabled,source:t.source,rules:e},models:B(),commands:visibleCommands(),transcript:k.slice(),sessions:[],memory:{},lastRecap:g.lastRecap,backend:g.modelClass,url:o.apiBase}}function ee(e){return Array.isArray(e)?e.map(e=>e&&(e.s||"")+(null==e.t?"":e.t)||"").join(""):String(null==e?"":e)}function te(e){if(!e||"object"!=typeof e)return;const t=h();switch(e.role){case"panel":{const t=Array.isArray(e.lines)?e.lines:[];for(const e of t)V(ee(e));return}case"note":case"tip":return void V(render.renderNotice(S(),"info",e.text));case"done":return void V(render.renderNotice(S(),"ok",e.text));case"error":return void V(render.renderNotice(S(),"error",e.text));case"user":return void V(render.renderTurn(S(),{role:"user",text:e.text,label:e.label},t));case"assistant":return void V(render.renderTurn(S(),{role:"assistant",text:e.text},t));case"tool":return void 0===e.diff&&(e.diff=editPreview(e.name||e.label,e.args,{cwd:process.cwd()}),e.diffOpen=defaultOpen(e.diff)),void V(render.renderTurn(S(),{role:"tool",label:e.label||e.name,args:e.args,ok:e.ok,diff:e.diff,diffOpen:!!e.diffOpen},t));default:return void V(render.renderNotice(S(),"info",null==e.text?"":String(e.text)))}}function ne(e){return{t:e,s:"",w:w(e)}}async function re(){return!e.readline&&process.stdin.isTTY&&process.stdout.isTTY&&!1!==e.chatflow?screens.showThemePicker(g):(g.light=!g.light,g.themeIndex=g.light?2:1,V(render.renderNotice(S(),"ok","theme: "+(g.light?"light":"dark"))),g.themeIndex)}function oe(){const e={ctx:g,transcript:k,push:e=>te(e),note:e=>te({role:"note",text:e}),panel:e=>te({role:"panel",lines:e}),render:()=>{},openOverlay:e=>function(e){if(!e||"object"!=typeof e)return;const t=h(),n=Math.max(5,process.stdout&&process.stdout.rows||24);let r=null;if("panel"===e.type?r=e.lines:"palette"===e.type?r=overlays.renderPalette(visibleCommands(),{query:e.query||"",typed:e.query||"",sel:e.sel||0},t,n):"model"===e.type?r=overlays.renderModelPicker(e.items||[],e.sel||0,t,n,null!=e.current?e.current:g.model,e.cls||g.modelClass,y,e.query||""):"effort"===e.type?r=overlays.renderEffortPicker(e.sel||0,t,g.effort):"class"===e.type?r=overlays.renderClassPicker(e.items||[],e.sel||0,t,e.current||g.modelClass,y):"provider"===e.type?r=overlays.renderProviderPicker(e.items||[],e.sel||0,t,e.current,e.hint):"resume"===e.type?r=overlays.renderResumeList(e.items||[],e.sel||0,t,n):"confirm"===e.type&&(r=render.renderApproval(S(),e.info||{},t).map(e=>[ne(e)])),r)for(const e of r)V(ee(e))}(e),closeOverlay:()=>{},setAutoRounds:e=>{f=Boolean(e)},askInput:()=>Promise.resolve(null),withWorking:e=>async function(e){const r=new AbortController,o=t.interactive&&n.isTTY?new LiveRegion(n):null;let s=null;if(o){let e=0;const t=Date.now(),n=()=>o.update([render.renderWorking(S(),{tick:e++,verb:VERBS[0],elapsedMs:Date.now()-t})]);n(),s=setInterval(n,90),s.unref&&s.unref()}try{return await e(r.signal)}finally{s&&clearInterval(s),o&&o.clear()}}(e),runPrompt:e=>X(e),ask:e=>G(e),runTool:(e,t)=>J(e,t),loadModels:()=>q(g.modelClass),settings:()=>p.settings||null,byokNamespace:e=>byokNamespace(e),listModelsFor:e=>q(e),refreshByokModels:()=>D({force:!0}),switchClass:e=>function(e){const t=String(null==e?"":e).trim().toLowerCase(),n=H();if(!n.includes(t))return"pro"===t?{ok:!1,error:"the pro class (your Claude Code subscription) is off by default — enable it once with `/class pro on`"}:{ok:!1,error:`unknown class "${e}" — classes: ${n.join(", ")}`};const r=g.modelClass;g.modelClass=t;let o=null;return r!==t&&g.model&&(function(e,t){const n=String(null==t?"":t);return"byok"===e?n.includes(":"):"pro"===e?U().has(n.toLowerCase()):!n.includes(":")}(t,g.model)||(o=g.model,g.model=null)),updateConfig({modelClass:t,model:g.model,currentModelId:g.model}),{ok:!0,class:t,prev:r,cleared:o}}(e),classLabel:e=>y(e),classes:()=>"function"==typeof p.listClasses?p.listClasses():[],refreshSpend:()=>N(),state:()=>Z(),setInput:()=>{},exit:()=>{v=!0},client:o,TOOLS:i,saveConfig:e=>updateConfig(e),showThemePicker:()=>re(),keyStatus:()=>credentials.keyStatus(),setApiKey:(e,t)=>A(e,t),forgetApiKey:()=>P(),registerAccount:()=>async function(){return o.apiKey?{alreadyKeyed:!0}:d()}(),readSecret:e=>readSecret(e,{stdin:process.stdin,stdout:n}),cloudsync:cloudsync,cloudSyncEnabled:()=>M(),cloudSyncState:()=>x(),setCloudSync:e=>O(e),adoptLegacyKey:()=>L()};return Object.defineProperty(e,"sessionId",{enumerable:!0,get:()=>g.sessionId,set:e=>{g.sessionId=e}}),e.clearConversationMemory=()=>{p&&"function"==typeof p.clearSessionApprovals&&p.clearSessionApprovals(g.sessionId)},e.listUndoable=()=>p&&"function"==typeof p.listUndoable?p.listUndoable(g.sessionId):[],e.undoMutation=e=>p&&"function"==typeof p.undoMutation?p.undoMutation(g.sessionId,e):{ok:!1,error:"undo is not available on this engine"},e}async function se(e,t=null){const r=parseLine(e);if("empty"===r.kind)return!0;if("prompt"===r.kind)return await X(r.text),!0;if("unknown"===r.kind){const e=Q(r.name);return V(render.renderNotice(S(),"error",`unknown command: /${r.name}${e?` — did you mean /${e}?`:" — try /help"}`)),!0}if("unavailable"===r.kind){const e=r.command;if(V(render.renderNotice(S(),"warn",`/${e.name} is not available in aegiscode — ${e.unavailable}`)),e.alt)V(render.renderNotice(S(),"info",`try ${e.alt} instead`));else{const t=Q(e.name);t&&V(render.renderNotice(S(),"info",`try /${t} instead`))}return!0}const s=r.command,i=r.arg;if(s.generic){let t;try{t=s.build(i)}catch(e){return V(render.renderNotice(S(),"error",e.message)),!0}const{tool:n,args:r}=t;if(!n)return V(render.renderNotice(S(),"error","/tool needs a tool name — see /help")),!0;try{await J(n,r)}catch(e){V(render.renderNotice(S(),"error",e.message))}return!0}if("function"==typeof s.handler){const n=function(e,t){const n=String(null==t?"":t),r=Array.isArray(e.args)?e.args:[],o=function(e){const t=[];let n="",r=null,o=!1;for(const s of String(e||""))r?s===r?r=null:n+=s:'"'!==s&&"'"!==s?/\s/.test(s)?(n||o)&&(t.push(n),n="",o=!1):(n+=s,o=!0):(r=s,o=!0);return(n||o)&&t.push(n),t}(n),s={_rest:n.trim()};return r.forEach((e,t)=>{void 0!==o[t]&&(s[e]=o[t])}),s}(s,i),r=t||oe();try{return!1!==await s.handler(r,n)}catch(e){return V(render.renderNotice(S(),"error",e&&e.message?e.message:String(e))),!0}}try{let e=s.build(i);if(s.secret){const t=await async function(e,t){if("function"!=typeof e.secretDescribe)return null;try{const n=await e.secretDescribe(t,o);return n&&"object"==typeof n?n:null}catch{return null}}(s,e);if(t&&t.note&&V(render.renderNotice(S(),"info",t.note)),t&&null===t.prompt)return!0;t&&t.provider&&(e={...e,provider:t.provider});const r=await function(e){const t=themeOf(S());return readSecret(t.gray+e+RESET,{stdin:process.stdin,stdout:n})}(t&&t.prompt||`provider key for ${e.provider}: `);if(!r)return V(render.renderNotice(S(),"warn","empty key — nothing sent")),!0;e={...e,api_key:r}}if("aegis_ask"===s.tool)return await X(e.prompt);await J(s.tool,e),"aegis_memory_list"!==s.tool&&"aegis_memory_search"!==s.tool||function(){let e;try{e=cloudsync.status()}catch{return}const t=e.quota;if(!t)return;const n=fmtTokens(t.used||0),r=fmtTokens(t.limit||0);e.overQuota?V(render.renderNotice(S(),"warn",`cloud memory: ${n} of ${r} synced tokens — at the plan's ceiling. Everything stored stays readable; new writes are paused until there is room. /cloud memory for the full state.`)):V(render.renderNotice(S(),"info",`cloud memory: ${n} of ${r} synced tokens — /cloud memory for the full state`))}()}catch(e){V(render.renderNotice(S(),"error",e.message))}return!0}async function ie(){if(p&&"function"==typeof p.unloadLocalModels)try{await p.unloadLocalModels()}catch{}}function ae(e){b.turns++,b.calls+=Number(e&&e.calls||1)||1;const t=e&&e.usage,n=usageTokens(t);if(null!=n){b.tokens+=n;const e=usageBuckets(t);b.inputTokens+=e.input,b.outputTokens+=e.output,b.cacheReadTokens+=e.cacheRead,b.cacheWriteTokens+=e.cacheWrite}return n}function le(e,t,n="done",r=null){try{const o=t&&t.usage,s="number"==typeof r&&Number.isFinite(r)?r:null,i=String(t&&t.model||g.model||"").trim();appendHistory({sessionId:g.sessionId,prompt:e,reply:t&&t.text||"",status:n,model:i||void 0,provider:i&&providerForModel({id:i,cls:g.modelClass})||void 0,usage:o?{...usageBuckets(o),...null!=s?{costUsd:s}:{}}:null!=s?{input:0,output:0,cacheRead:0,cacheWrite:0,costUsd:s}:null}),snapshotCheckpoint(g.sessionId,k)}catch{}M()&&o.apiKey&&Promise.resolve().then(()=>cloudsync.push(o)).then(e=>{if(e&&e.failed&&e.failed.length){const t=e.failed[0];if(ce.has(t.kind))return;if(ce.add(t.kind),"quota"===t.kind)return void V(render.renderNotice(S(),"warn","cloud memory: the plan's synced-token ceiling is reached — earlier sessions stay readable, only NEW writes pause. /cloud memory shows the quota; /cloud memory off stops trying."));const n=t.hint?` — ${t.hint}`:"";V(render.renderNotice(S(),"error",`cloud sync: ${t.message}${n}`))}}).catch(()=>{})}let ce=new Set;function de(){const e=[b.outputTokens>0?`${fmtTokens(b.outputTokens)} tokens`:`${fmtTokens(b.tokens)} tokens`,`${b.calls} call${1===b.calls?"":"s"}`];return feeBillable()&&(e.push(fmtEur(b.cost)),null!=b.balance&&e.push(`balance ${fmtEur(b.balance)}`)),e.join(" · ")}async function ue(e){if(!e||!e.id)return;const t=readSessionTranscript(e.id);if(t.length){k.length=0;for(const e of t)k.push(e);g.sessionId=e.id,V(render.renderNotice(S(),"ok",`resumed ${e.id} — ${t.length} turn(s)`))}else V(render.renderNotice(S(),"warn",`no stored turns for ${e.id}`))}function me(){return{ctx:g,version:VERSION,transcript:k,session:b,client:o,TOOLS:i,ask:(e,t)=>G(e,t),makeCommandContext:()=>oe(),accountConfigured:()=>!!(credentials.keyStatus()||{}).configured,hasProviderKey:e=>{const t=p.settings;if(!t||!e)return!1;const n=byokNamespace(e);return"function"==typeof t.rawKey?!!String(t.rawKey(n)||"").trim():"function"==typeof t.get&&!!(t.get(n)||{}).configured},loadModels:e=>F(e),buildState:()=>Z(),dispatchLine:(e,t)=>se(e,t),refreshSpend:()=>N(),updateConfig:e=>updateConfig(e),showThemePicker:()=>re(),persistTurn:(e,t,n,r)=>le(e,t,n,r),nameConversation:(e,t)=>async function(e,{signal:t=null}={}){const n=await naming.nameConversation(e,{signal:t,callModel:(e,n)=>G(e,{system:n&&n.system||naming.TITLE_SYSTEM,maxTokens:64,signal:n&&n.signal||t}).then(e=>e&&e.text||null)}),r=String(n||"").trim();return r&&setSessionTitle(g.sessionId,r),r}(e,t),visibleCommands:()=>visibleCommands(),tokensFor:e=>usageTokens(e),recordTurn:e=>ae(e),tokenSummary:()=>de(),resumeSession:e=>ue(e),requestExit:()=>{v=!0},wantsExit:()=>v,keyNotice:()=>o.apiKey?"":c,isYolo:()=>{if(!f)return!1;try{return!1===confirmPosture().enabled}catch{return!1}},setAutoRounds:e=>{f=Boolean(e)}}}async function fe(){V(Y()),await N(),n.write("\n");const t=e.readline||readline.createInterface({input:process.stdin,output:n,terminal:!0}),r=themeOf(S()).gold+GLYPH.cursor+" "+RESET;return t.setPrompt(r),t.prompt(),new Promise(e=>{t.on("line",async e=>{t.pause();let n=!0;try{n=await se(e)}catch(e){V(render.renderNotice(S(),"error",e.message))}if(!n||v)return E=!0,void t.close();t.resume(),t.prompt()}),t.on("close",()=>{E||n.write("\n"),e(0)})})}function pe(){if(e.readline)return;if(!configExists())return;let n;try{n=loadConfig()}catch{return}if(H().includes(n.modelClass)&&(g.modelClass=n.modelClass),t.class){const e=String(t.class).trim().toLowerCase();if(!H().includes(e))throw new Error(`--class ${t.class}: not available on this host (offered: ${H().join(", ")})`);g.modelClass=e}if(!t.model&&n.model&&(g.model=n.model),g.effort=effortRung(t.effort||n.effort),"boolean"==typeof n.vim&&(g.vim=n.vim),n.lastRecap&&(g.lastRecap=n.lastRecap),!t.light&&"number"==typeof n.themeIndex&&THEME_TABLE[n.themeIndex]){g.themeIndex=n.themeIndex,g.light=themeIsLight(n.themeIndex);const e=reconcileThemeIndex(g.themeIndex);if(e.changed){g.themeIndex=e.index,g.light=themeIsLight(e.index),g.themeNotice=e.reason;try{updateConfig({themeIndex:e.index,light:themeIsLight(e.index)})}catch{g.themeNotice+=" (could not save it)"}}}}return{opts:t,session:b,client:o,TOOLS:i,toolList:a,ctx:g,transcript:k,ask:G,runPrompt:X,handleLine:se,runOnce:async function(e,t={}){try{return await async function(e,{json:t=!1}={}){if(pe(),L(),!o.apiKey&&!l){l=!0;const e=await autoProvisionApiKey(o,credentials,{app:"cli"});e.key&&r.write("aegiscode: auto-provisioned a free account"+(e.ok?` (saved to ${credentials.credentialsPath()})`:" (could not save it — reconfigure with /key)")+trialNote(e)+`. Fund it at ${o.promptUrl("topup","device_autoprovision")} or run /byok to use your own key.\n`)}if(!o.apiKey)return r.write(`aegiscode: no AEGIS account key. ${credentials.HOW_TO_SET}, or set $${credentials.KEY_ENV}.\n`),2;await N();const s=[],i=[],a=t?{tool:e=>{if("done"===(e&&e.phase)){const t=e.id&&i.find(t=>t.id===e.id&&!0!==t.settled)||(e.id?null:i[i.length-1]);t?(t.settled=!0,t.ok=!1!==e.ok):(e&&e.name&&s.push(e.name),i.push({name:e&&e.name||null,id:e&&e.id||null,args:briefArgs(e&&e.args),settled:!0,ok:!1!==e.ok}))}else e&&e.name&&s.push(e.name),i.push({name:e&&e.name||null,id:e&&e.id||null,args:briefArgs(e&&e.args),settled:!1,ok:null});const t=e&&void 0!==e.preview?e.preview:null,n=render.renderTurn(S(),{role:"tool",label:e.name,args:e.args,ok:e.ok,diff:t,diffOpen:!1},h());for(const e of Array.isArray(n)?n:[n])r.write(e+"\n")}}:null,c=await G(e,a?{presenter:a}:{});await N();const d=usageTokens(c.usage),u=providerRefusal(c.text,c.usage);if(t)n.write(JSON.stringify({text:c.text,model:c.model,class:g.modelClass,rounds:c.usage&&Number(c.usage.calls)||null,usage:c.usage,reasoning_chars:"number"==typeof c.reasoningChars?c.reasoningChars:null,tokens:d,ms:c.ms,interrupted:c.interrupted,...s.length?{tools:s}:{},...i.length?{tool_log:i}:{},...u?{error:u}:{},balance_eur:b.balance},null,2)+"\n");else if(n.write(c.text+"\n"),u&&r.write(`aegiscode: the provider refused this turn — ${u}\n`),null!=d){const e=themeOf(S());n.write(e.dim+GLYPH.hook+" "+e.blue+(c.model||"aegis")+RESET+e.dim+" "+GLYPH.bullet+" "+RESET+e.white+`${fmtTokens(d)} tokens`+RESET+"\n")}return c.interrupted?130:u?1:0}(e,t)}finally{await ie()}},runInteractive:async function(){try{return await async function(){if(!e.readline&&!1!==e.chatflow&&process.stdin.isTTY&&process.stdout.isTTY){await probeTerminalBackground({onLeftover:e=>events.feedKeys(e,{keystrokes:!0})}),pe(),function(){if(!g.themeNotice)return;const e=g.themeNotice;g.themeNotice="",V(render.renderNotice(S(),"warn",`theme: ${e} (saved)`))}(),L(),o.apiKey||await u();const t=await screens.runOnboarding(g,{continue:!!e.continue,seen:e.seen||configExists,save:e=>updateConfig(e),needsKey:()=>!o.apiKey,submitKey:e=>A(e)});if(!t.ok)return 0;if(t.key&&t.key.set&&V(render.renderNotice(S(),"info",`key saved to ${credentials.credentialsPath()} — no export needed from now on`)),t.key&&t.key.skipped&&!o.apiKey&&V(render.renderNotice(S(),"warn","no key saved — /key <api_key> or `aegiscode login` whenever you are ready")),t.firstRun&&function(){if(!x().enabled)return void V(render.renderNotice(S(),"info","cross-session memory: off (you turned it off) — /cloud memory on stores sessions so an interrupted turn can be picked up later"));const e=cloudsync.status().quota,t=e&&e.limit?` (used ${fmtTokens(e.used||0)} of ${fmtTokens(e.limit)} tokens)`:"";V(render.renderNotice(S(),"info",`cross-session memory: on${t} — sessions are stored to your account so a turn that is interrupted can be resumed. /cloud memory shows the quota; /cloud memory off stops it. Past the ceiling, saved memory stays readable and only new writes pause.`))}(),await W(),e.sessionId)g.continueSession=String(e.sessionId),await ue({id:String(e.sessionId)});else if(e.continue){const e=readOwnSessions(1)[0];e&&(g.continueSession=e.id,await ue({id:e.id}))}return await N(),runAutoModelSync(g).catch(()=>{}),await chatflow.runSession(me()),0}return pe(),L(),fe()}()}finally{await ie()}},runLinearRepl:fe,refreshSpend:N,bannerLines:Y,makeHost:me,loadModels:F,validatePinnedModel:W,recordTurn:ae,persistTurn:le,restorePrefs:pe,setApiKey:A,forgetApiKey:P,adoptLegacyKeyOnce:L,cloudSyncEnabled:M,cloudSyncState:x,setCloudSync:O,cloudsync:cloudsync,keyStatus:()=>credentials.keyStatus(),accountConfigured:()=>!!(credentials.keyStatus()||{}).configured,hasProviderKey:e=>{const t=p.settings;if(!t||!e)return!1;const n=byokNamespace(e);return"function"==typeof t.rawKey?!!String(t.rawKey(n)||"").trim():"function"==typeof t.get&&!!(t.get(n)||{}).configured},sessionId:()=>g.sessionId,tokenSummary:de,resumeSession:ue,makeCommandContext:oe,buildState:Z,get aborted(){return!1}}}module.exports={createApp:createApp,VERSION:VERSION,normalizeDecision:normalizeDecision};
|
|
3
|
+
"use strict";const readline=require("node:readline"),os=require("node:os"),{randomUUID:randomUUID}=require("node:crypto"),{createTools:createTools,createClient:createClient,usageTokens:usageTokens,usageBuckets:usageBuckets,buildSystemPrompt:buildSystemPrompt,autoProvisionApiKey:autoProvisionApiKey,provisionFailureText:provisionFailureText,trialNote:trialNote,hostEnv:hostEnv,autonomous:autonomous,claudePro:claudePro}=require("./deps.js"),{createEngine:createEngine,HOST_CLASSES:HOST_CLASSES,DEFAULT_CLASS:DEFAULT_CLASS,byokNamespace:byokNamespace,effortRung:effortRung,offeredClasses:offeredClasses,proEnabled:proEnabled}=require("./engine.js"),{GLYPH:GLYPH,VERBS:VERBS,themeOf:themeOf,RESET:RESET,THEME_TABLE:THEME_TABLE,AUTO_THEME_INDEX:AUTO_THEME_INDEX,themeIsLight:themeIsLight,reconcileThemeIndex:reconcileThemeIndex}=require("./theme.js"),{probeTerminalBackground:probeTerminalBackground}=require("./caps.js"),{LiveRegion:LiveRegion,termWidth:termWidth,w:w}=require("./screen.js"),{estimateTokensFromCells:estimateTokensFromCells}=require("./tokens.js"),{editPreview:editPreview}=require("./diff.js"),{defaultOpen:defaultOpen}=require("./diffview.js"),{parseLine:parseLine,COMMANDS:COMMANDS,visibleCommands:visibleCommands,runAutoModelSync:runAutoModelSync}=require("./commands.js"),{updateConfig:updateConfig,loadPermissions:loadPermissions,loadConfig:loadConfig,configExists:configExists,memoryPersistState:memoryPersistState,memoryPersistEnabled:memoryPersistEnabled,setMemoryPersist:setMemoryPersist,confirmPosture:confirmPosture,permissionMode:permissionMode}=require("./config.js"),credentials=require("./credentials.js"),events=require("./events.js"),cloudsync=require("./cloudsync.js"),{readSecret:readSecret}=require("./secret.js"),{normalizeModelCatalog:normalizeModelCatalog,pickerEntries:pickerEntries,catalogIds:catalogIds,providerForModel:providerForModel,withAutoRow:withAutoRow,AUTO_MODEL_ID:AUTO_MODEL_ID,localDefaultModel:localDefaultModel}=require("./models.js"),{appendHistory:appendHistory,readSessionTranscript:readSessionTranscript,readOwnSessions:readOwnSessions,setSessionTitle:setSessionTitle}=require("./history.js"),naming=require("./naming.js"),{snapshotCheckpoint:snapshotCheckpoint}=require("./checkpoint.js"),screens=require("./screens.js"),chatflow=require("./chatflow.js"),overlays=require("./overlays.js"),render=require("./render.js"),{fmtTokens:fmtTokens,fmtEur:fmtEur,maskKey:maskKey,feeBillable:feeBillable}=require("./format.js"),{resolveSkip:resolveSkip}=require("./permissions.js"),VERSION=require("../package.json").version,_defaultSystems=new Map;function defaultSystemPrompt(e){const t="local"===e?"local":"cloud";if(!_defaultSystems.has(t))try{_defaultSystems.set(t,buildSystemPrompt(hostEnv({},{},"local"===t?{class:"local"}:null)))}catch{_defaultSystems.set(t,"")}return _defaultSystems.get(t)||void 0}function normalizeDecision(e){const t="string"==typeof e?e.trim().toLowerCase():"";return"session"===t?"session":"once"===t||"allow"===t||"yes"===t||"approve"===t||"approved"===t?"once":"deny"}const PROVIDER_REFUSAL_PATTERNS=Object.freeze([/^invalid api key\b/i,/^fix external api key\b/i,/^you've hit your session limit\b/i,/^you have hit your session limit\b/i,/^provider request timed out\b/i,/^insufficient (?:credit|balance|quota)\b/i,/^rate limit(?:ed)?\b/i,/^unauthorized\b/i]);function providerRefusal(e,t){if("string"!=typeof e)return null;const n=t&&(t.total_tokens||0),r=t&&(t.output_tokens||t.completion_tokens||0);if(n>0||r>0)return null;const o=e.trim();if(!o||o.length>160||o.includes("\n"))return null;for(const e of PROVIDER_REFUSAL_PATTERNS)if(e.test(o))return o;return null}function briefArgs(e){let t;try{t="string"==typeof e?e:JSON.stringify(e??"")}catch{t=String(e)}return t=String(t).replace(/\s+/g," ").trim(),t.length>140?`${t.slice(0,137)}...`:t}function createApp(e={}){const t={model:null,stream:!0,light:!1,maxTokens:void 0,system:void 0,interactive:!0,...e},n=e.out||process.stdout,r=e.err||process.stderr,o=e.client||createClient(credentials.clientOptions({channel:"cli"})),{createLocalWiki:s}=require("./dream-cmd.js"),{TOOLS:i,toolList:a}=e.tools||createTools(o,{localWiki:s()});let l=!1,c="";async function d(){const e=await autoProvisionApiKey(o,credentials,{app:"cli"});return c=e.key?"":provisionFailureText(e),e}async function u(){if(o.apiKey||l)return;l=!0;const e=await d();e.key&&V(render.renderNotice(S(),"info","auto-provisioned a free account"+(e.ok?` (saved to ${credentials.credentialsPath()})`:" (could not save it — reconfigure with /key)")+trialNote(e)+`. Fund it at ${o.promptUrl("topup","device_autoprovision")} or run /byok to use your own key.`))}let m=!1!==e.confirmMode,f=(()=>{try{return autonomous.autoRoundsDefault(process.env)}catch{return!0}})();const p=e.engine||createEngine({client:o,getClass:()=>g.modelClass,getProEnabled:()=>{try{return proEnabled(loadConfig())}catch{return!1}},getConfirmMode:()=>{if(void 0!==e.confirmMode)return m;try{const e=resolveSkip({env:process.env,interactive:Boolean(process.stdin.isTTY&&process.stdout.isTTY)});if(e.warned&&!skipEnvWarned&&(skipEnvWarned=!0,process.stderr.write(`aegiscode: ${e.warning}\n`)),e.skip)return!1}catch{}try{return confirmPosture().enabled}catch{return m}},getPermissionMode:()=>{try{return permissionMode()}catch{return null}}}),y=e=>"function"==typeof p.classLabel?p.classLabel(e):String(e||""),h=()=>e.width?e.width():termWidth(),g={light:t.light,model:t.model,modelClass:DEFAULT_CLASS,effort:null,thinking:!1,recallDeep:!1,themeIndex:t.light?2:AUTO_THEME_INDEX,vim:!1,stream:t.stream,cwd:process.cwd(),lastRecap:null,sessionId:randomUUID()};g.themeIndex===AUTO_THEME_INDEX&&(g.light=themeIsLight(AUTO_THEME_INDEX));const k=[];let v=!1;const S=()=>({light:g.light}),b={turns:0,calls:0,tokens:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,cost:0,balance:null,seenLedgerRows:new Map,ledgerBaselined:!1,startedAt:Date.now()};let T=null,E=!1;function C(e){if(!e||"object"!=typeof e)return null;if("usage"!==e.kind)return null;const t=null!=e.amount_eur?Number(e.amount_eur):-Number(e.charged_micros||0)/1e6;return Number.isFinite(t)?Math.abs(t):null}function I(e){return[e.created_at||"",e.kind||"",null!=e.amount_eur?e.amount_eur:"",null!=e.charged_micros?e.charged_micros:"",null!=e.id?e.id:"",null!=e.note?e.note:""].join("|")}async function M(){try{const e=await o.tokenBankBalance(),t=Number(e.balance_eur);Number.isFinite(t)&&(b.balance=t);let n=null;const r=Array.isArray(e.ledger)?e.ledger:[],s=new Map;for(const e of r){const t=I(e),n=s.get(t);n?n.n+=1:s.set(t,{n:1,row:e})}for(const[e,{n:t,row:r}]of s){const o=b.seenLedgerRows.get(e)||0;if(b.seenLedgerRows.set(e,t),!b.ledgerBaselined)continue;const s=t-o;if(s<=0)continue;const i=C(r);null!=i&&i>0&&(b.cost+=i*s,null==n&&(n=i))}return b.ledgerBaselined=!0,{balance:b.balance,lastCost:n}}catch{return null}}async function N(e,{verify:t=!0}={}){const n=credentials.saveApiKey(e);if(!n.ok)return n;o.setApiKey(n.key),R.models=[],R.at=0;let r=null,s=null;if(t)try{const e=await o.verifyApiKey()||{};r=e;const t={verifiedAt:(new Date).toISOString()};e.memory_token&&(t.memoryToken=e.memory_token),e.plan&&(t.plan=e.plan),t.account={plan:e.plan||null,email:e.email||null,valid:!1!==e.valid},credentials.writeCredentials(t),e.plan&&(b.plan=e.plan),e.email&&(b.account={...b.account||{},email:e.email})}catch(e){s=e}return{...n,account:r,error:s}}function A(){const e=credentials.clearApiKey();return o.setApiKey(""),R.models=[],R.at=0,e}function P(){try{return memoryPersistEnabled()}catch{return!0}}function x(){try{return memoryPersistState()}catch{return{enabled:!0,source:"default",explicit:!1}}}function O(e){return setMemoryPersist(e)}function L(){try{return"config"!==credentials.resolveApiKey().source?[]:credentials.adoptLegacy().adopted}catch{return[]}}const _=3e5,R={at:0,models:[]},$={at:0,models:[],declared:""},D={at:0,models:[]};async function K({force:e=!1}={}){const t=function(){try{if("function"!=typeof p.userModels)return"";const e=(p.userModels()||{}).map||{};return JSON.stringify(Object.keys(e).sort().map(t=>[t,e[t]]))}catch{return""}}(),n=$.models.length&&Date.now()-$.at<_&&t===$.declared;if(!e&&n)return $.models;if("function"!=typeof p.listModels)return[];const r=await p.listModels("byok");return $.models=(r&&r.models||[]).map(e=>({...e,note:e.configured?"key on this machine":`no key — /byok-key ${e.provider}`})),$.at=Date.now(),$.declared=t,$.models}async function q(e){const t=H();if(e&&!t.includes(e)&&HOST_CLASSES.includes(e))return[];const n=t.includes(e)?e:g.modelClass;try{if("byok"===n){const e=await K();if(!R.models.length)try{await F()}catch{}return B(e,n)}if("pro"===n){const e=await p.listModels("pro");return(e&&e.models||[]).map(e=>({...e,cls:"pro"}))}if("local"===n){const e=await p.listModels("local");return D.models=e&&e.models||[],D.at=Date.now(),D.models}if("aegis"!==n){const e=await p.listModels(n);return e&&e.models||[]}return await F()}catch{return[]}}function j(){return withAutoRow(pickerEntries(R.models)).map(e=>({...e,cls:"aegis"}))}function B(e,t){const n=H(),r=n.includes(t)?t:g.modelClass;if("pro"===t&&!n.includes("pro"))return[];if("pro"===r)return pickerEntries(claudePro.PRO_MODELS.map(e=>({id:e.id,label:e.label,note:e.note}))).map(e=>({...e,cls:"pro"}));if("local"===r)return pickerEntries(D.models).map(e=>({...e,cls:"local"}));if("byok"!==r)return j();const o=Array.isArray(e)?e.map(e=>({...e,cls:"byok"})):pickerEntries($.models).map(e=>({...e,cls:"byok"}));return[...j(),...o]}function U(){return new Set(claudePro.PRO_MODELS.map(e=>String(e.id).toLowerCase()))}function H(){try{return offeredClasses(proEnabled(loadConfig()))}catch{return offeredClasses(!1)}}async function F({force:e=!1}={}){const t=R.models.length&&Date.now()-R.at<_;if(!e&&t)return R.models;const n=await o.listModels();return R.models=normalizeModelCatalog(n&&n.models),R.at=Date.now(),R.models}async function W(){const e=g.model;if(!e)return null;if("byok"===g.modelClass)return String(e).includes(":")?null:(g.model=null,updateConfig({model:null,currentModelId:null}),V(render.renderNotice(S(),"warn",`pinned model "${e}" belongs to the pooled class — on BYOK an id is "<provider>:<model>"; pin cleared, /models lists what this machine can relay.`)),e);if("pro"===g.modelClass){if(!U().has(String(e).toLowerCase()))return g.model=null,updateConfig({model:null,currentModelId:null}),V(render.renderNotice(S(),"warn",`pinned model "${e}" is not one the Claude Code CLI resolves — pin cleared, the CLI will choose; /models lists the aliases (${claudePro.PRO_MODELS.map(e=>e.id).join(", ")}).`)),e;let t=!0;try{t=!!claudePro.claudeProStatus({env:process.env}).credentialPresent}catch{t=!0}return t?null:(g.model=null,updateConfig({model:null,currentModelId:null}),V(render.renderNotice(S(),"warn",`pinned model "${e}" needs a Claude Pro subscription or an ANTHROPIC_API_KEY, and this host has neither — pin cleared. Run \`claude /login\`, export a console key, or \`/class pro off\`.`)),e)}if("local"===g.modelClass){try{const t=await p.listModels("local");if(t&&(t.needsDaemon||!t.listed))return null;if(new Set((t&&t.models||[]).map(e=>e&&e.id)).has(String(e)))return null}catch{return null}return g.model=null,updateConfig({model:null,currentModelId:null}),V(render.renderNotice(S(),"warn",`pinned model "${e}" is not listed by the local daemon right now — pin cleared; /models lists what is pulled.`)),e}let t;try{t=await F()}catch{return null}return t.length?String(e).trim().toLowerCase()===AUTO_MODEL_ID||catalogIds(t).has(String(e).toLowerCase())?null:(g.model=null,updateConfig({model:null,currentModelId:null}),V(render.renderNotice(S(),"warn",`pinned model "${e}" is not advertised by AEGIS Cloud — pin cleared, the pool will choose; /models lists what you can pin.`)),e):null}function Y(){return render.renderBanner(S(),{width:h(),version:VERSION,model:g.model||"server default",base:o.apiBase,key:maskKey(o.apiKey),stream:g.stream})}function V(e){const t="string"==typeof e?[e]:e;for(const e of t)n.write(e+"\n")}async function G(e,{history:o=[],presenter:s=null,signal:i=null}={}){const a=Date.now(),l=!s&&t.interactive&&t.stream&&n.isTTY?new LiveRegion(n):null;let c=0,d=0,u="",m=0,f=0,y=VERBS[Math.floor(Math.random()*VERBS.length)],k=!1,v=!1;const b=()=>{l&&l.update([render.renderWorking(S(),{tick:c++,verb:y,elapsedMs:Date.now()-a,streamed:estimateTokensFromCells(d+m)+f,streamedFloor:f>0})])},E=l?setInterval(b,90):null;E&&E.unref&&E.unref(),b();const C=s||{},I=new Map,M=randomUUID();T=M;let N=!1;const A=()=>{N=!0,p.cancel(M)},P=()=>A();process.once("SIGINT",P),i&&(i.aborted?A():i.addEventListener("abort",A,{once:!0}));const x=e=>(r.write(`aegiscode: ${e.tool} needs confirmation but this run has no prompt for it — denied (pass --automode (alias --yolo) to auto-approve mutating tools).\n`),Promise.resolve("deny")),O=()=>Promise.resolve(!1),L=e=>{if(e){if(e.thinkingTokens&&(f+=e.thinkingTokens,k||(k=!0,y="Reasoning"),(e=>{C.thinkingTokens&&C.thinkingTokens(e)})(e.thinkingTokens),b()),e.reasoning&&(m+=w(e.reasoning),k||(k=!0,y="Reasoning",b()),(e=>{C.reasoning&&C.reasoning(e)})(e.reasoning)),e.delta&&(d+=w(e.delta),u+=e.delta,(e=>{if(C.text)return C.text(e);l&&c%2==0&&b()})(e.delta)),e.tool&&(v=!0,(e=>{if(C.tool)return C.tool(e);l&&l.clear();const t=(e=>{const t=e&&void 0!==e.id?`id:${e.id}`:`${e&&e.name}:${JSON.stringify(e&&e.args)}`;return I.has(t)||I.set(t,editPreview(e&&e.name,e&&e.args,{cwd:process.cwd()})),I.get(t)})(e);V(render.renderTurn(S(),{role:"tool",label:e.name,args:e.args,ok:e.ok,diff:t,diffOpen:defaultOpen(t)},h())),b()})(e.tool)),e.approval){const t=e.approval;l&&l.clear();const n=C.approval||x;Promise.resolve(n(t)).catch(()=>"deny").then(e=>p.respondApproval(t.id,normalizeDecision(e)))}if(e.rounds){const t=e.rounds;l&&l.clear();const n=C.rounds||O;Promise.resolve(n(t)).catch(()=>!1).then(e=>p.respondRoundsAsk(t.id,!0===e))}}};if("local"===g.modelClass&&!g.model)try{const e=await p.listModels("local");if(e&&!e.needsDaemon&&e.listed){const t=(e.models||[]).map(e=>e&&e.id).filter(Boolean);g.model=localDefaultModel(t)}}catch{}try{const n=await p.chat({prompt:e,messages:o,model:g.model||void 0,system:t.system||defaultSystemPrompt(g.modelClass),maxTokens:t.maxTokens,effort:effortRung(g.effort),recallDeep:!0===g.recallDeep||void 0,stream:!1!==g.stream,sessionId:M,sessionKey:g.sessionId,rootSessionId:g.sessionId,roundsAsk:Boolean(C.rounds)},L),r=n.choices&&n.choices[0]||{};return{text:r.message&&r.message.content||u,usage:n.usage||null,model:n.model||g.model||null,ms:Date.now()-a,interrupted:N,reasoningChars:m,usedTools:v}}catch(e){if(N&&u)return{text:u,usage:null,model:g.model||null,ms:Date.now()-a,interrupted:!0,reasoningChars:m,usedTools:v};throw e}finally{E&&clearInterval(E),process.removeListener("SIGINT",P),i&&i.removeEventListener("abort",A),l&&l.clear(),T=null}}function z(e){V(render.renderTurn(S(),e,h()))}async function X(e,{label:t="you"}={}){if(!e)return void V(render.renderNotice(S(),"warn","nothing to ask — give /ask a prompt"));if(o.apiKey||await u(),!o.apiKey)return void V(render.renderNotice(S(),"error",`no AEGIS account key — ${credentials.HOW_TO_SET} (or set $${credentials.KEY_ENV})`));const n=k.filter(e=>"user"===e.role||"assistant"===e.role).map(e=>({role:e.role,content:e.text}));let r;z({role:"user",text:e,label:t}),k.push({role:"user",text:e});try{r=await G(e,{history:n})}catch(t){return le(e,{text:"",error:t.message},"error"),void V(render.renderTurn(S(),{role:"error",text:t.message},h()))}r.text&&k.push({role:"assistant",text:r.text});const s=ae(r);let i=null;try{const e=await M();i=e?e.lastCost:null}catch{}le(e,r,r.interrupted?"stopped":r.error?"error":"done",i),z({role:"assistant",text:r.text||"(the pool returned no text — see /balance for what it charged)",meta:{model:r.model,tokens:s,usage:null==r.usage?null:usageBuckets(r.usage),eur:i,ms:r.ms,calls:1}}),r.interrupted&&V(render.renderNotice(S(),"warn","interrupted — the pool may still be running and billing this call"))}async function J(e,t){const n=i[e];if(!n)throw new Error(`unknown tool: ${e}`);if(o.apiKey||await u(),!o.apiKey)throw new Error(`no AEGIS account key — ${credentials.HOW_TO_SET}`);const r=await n.run(t||{});V(render.renderToolResult(S(),e,r,h()))}function Q(e){const t=String(e||"").toLowerCase();if(!t)return null;let n=null;for(const e of COMMANDS)for(const r of[e.name,...e.aliases||[]])r!==t&&(r.startsWith(t)||t.startsWith(r))&&(null==n||Math.abs(r.length-t.length)<Math.abs(n.length-t.length))&&(n=r);return n}function Z(){const e=loadPermissions(),t=confirmPosture();return{version:VERSION,model:g.model||"server default",class:g.modelClass,effort:g.effort,thinking:g.thinking,theme:g.light?"light":"dark",themeIndex:g.themeIndex,vim:g.vim,stream:g.stream,cwd:g.cwd,home:os.homedir(),sessionId:g.sessionId,base:o.apiBase,keyMask:maskKey(o.apiKey),online:!!o.apiKey,turns:b.turns,calls:b.calls,startedAt:b.startedAt,tokens:{input:b.inputTokens,output:b.outputTokens,cacheRead:b.cacheReadTokens,cacheWrite:b.cacheWriteTokens,total:b.tokens},costEur:b.cost,balance:b.balance,plan:b.plan||null,account:b.account||null,permissions:{mode:t.enabled?e.defaultMode:"allow",confirm:t.enabled,source:t.source,rules:e},models:B(),commands:visibleCommands(),transcript:k.slice(),sessions:[],memory:{},lastRecap:g.lastRecap,backend:g.modelClass,url:o.apiBase}}function ee(e){return Array.isArray(e)?e.map(e=>e&&(e.s||"")+(null==e.t?"":e.t)||"").join(""):String(null==e?"":e)}function te(e){if(!e||"object"!=typeof e)return;const t=h();switch(e.role){case"panel":{const t=Array.isArray(e.lines)?e.lines:[];for(const e of t)V(ee(e));return}case"note":case"tip":return void V(render.renderNotice(S(),"info",e.text));case"done":return void V(render.renderNotice(S(),"ok",e.text));case"error":return void V(render.renderNotice(S(),"error",e.text));case"user":return void V(render.renderTurn(S(),{role:"user",text:e.text,label:e.label},t));case"assistant":return void V(render.renderTurn(S(),{role:"assistant",text:e.text},t));case"tool":return void 0===e.diff&&(e.diff=editPreview(e.name||e.label,e.args,{cwd:process.cwd()}),e.diffOpen=defaultOpen(e.diff)),void V(render.renderTurn(S(),{role:"tool",label:e.label||e.name,args:e.args,ok:e.ok,diff:e.diff,diffOpen:!!e.diffOpen},t));default:return void V(render.renderNotice(S(),"info",null==e.text?"":String(e.text)))}}function ne(e){return{t:e,s:"",w:w(e)}}async function re(){return!e.readline&&process.stdin.isTTY&&process.stdout.isTTY&&!1!==e.chatflow?screens.showThemePicker(g):(g.light=!g.light,g.themeIndex=g.light?2:1,V(render.renderNotice(S(),"ok","theme: "+(g.light?"light":"dark"))),g.themeIndex)}function oe(){const e={ctx:g,transcript:k,push:e=>te(e),note:e=>te({role:"note",text:e}),panel:e=>te({role:"panel",lines:e}),render:()=>{},openOverlay:e=>function(e){if(!e||"object"!=typeof e)return;const t=h(),n=Math.max(5,process.stdout&&process.stdout.rows||24);let r=null;if("panel"===e.type?r=e.lines:"palette"===e.type?r=overlays.renderPalette(visibleCommands(),{query:e.query||"",typed:e.query||"",sel:e.sel||0},t,n):"model"===e.type?r=overlays.renderModelPicker(e.items||[],e.sel||0,t,n,null!=e.current?e.current:g.model,e.cls||g.modelClass,y,e.query||""):"effort"===e.type?r=overlays.renderEffortPicker(e.sel||0,t,g.effort):"class"===e.type?r=overlays.renderClassPicker(e.items||[],e.sel||0,t,e.current||g.modelClass,y):"provider"===e.type?r=overlays.renderProviderPicker(e.items||[],e.sel||0,t,e.current,e.hint):"resume"===e.type?r=overlays.renderResumeList(e.items||[],e.sel||0,t,n):"confirm"===e.type&&(r=render.renderApproval(S(),e.info||{},t).map(e=>[ne(e)])),r)for(const e of r)V(ee(e))}(e),closeOverlay:()=>{},setAutoRounds:e=>{f=Boolean(e)},askInput:()=>Promise.resolve(null),withWorking:e=>async function(e){const r=new AbortController,o=t.interactive&&n.isTTY?new LiveRegion(n):null;let s=null;if(o){let e=0;const t=Date.now(),n=()=>o.update([render.renderWorking(S(),{tick:e++,verb:VERBS[0],elapsedMs:Date.now()-t})]);n(),s=setInterval(n,90),s.unref&&s.unref()}try{return await e(r.signal)}finally{s&&clearInterval(s),o&&o.clear()}}(e),runPrompt:e=>X(e),ask:e=>G(e),runTool:(e,t)=>J(e,t),loadModels:()=>q(g.modelClass),settings:()=>p.settings||null,byokNamespace:e=>byokNamespace(e),listModelsFor:e=>q(e),refreshByokModels:()=>K({force:!0}),switchClass:e=>function(e){const t=String(null==e?"":e).trim().toLowerCase(),n=H();if(!n.includes(t))return"pro"===t?{ok:!1,error:"the pro class (your Claude Code subscription) is off by default — enable it once with `/class pro on`"}:{ok:!1,error:`unknown class "${e}" — classes: ${n.join(", ")}`};const r=g.modelClass;g.modelClass=t;let o=null;return r!==t&&g.model&&(function(e,t){const n=String(null==t?"":t);return"byok"===e?n.includes(":"):"pro"===e?U().has(n.toLowerCase()):"local"===e||!n.includes(":")}(t,g.model)||(o=g.model,g.model=null)),updateConfig({modelClass:t,model:g.model,currentModelId:g.model}),{ok:!0,class:t,prev:r,cleared:o}}(e),classLabel:e=>y(e),classes:()=>"function"==typeof p.listClasses?p.listClasses():[],refreshSpend:()=>M(),state:()=>Z(),setInput:()=>{},exit:()=>{v=!0},client:o,TOOLS:i,saveConfig:e=>updateConfig(e),showThemePicker:()=>re(),keyStatus:()=>credentials.keyStatus(),setApiKey:(e,t)=>N(e,t),forgetApiKey:()=>A(),registerAccount:()=>async function(){return o.apiKey?{alreadyKeyed:!0}:d()}(),readSecret:e=>readSecret(e,{stdin:process.stdin,stdout:n}),cloudsync:cloudsync,cloudSyncEnabled:()=>P(),cloudSyncState:()=>x(),setCloudSync:e=>O(e),adoptLegacyKey:()=>L()};return Object.defineProperty(e,"sessionId",{enumerable:!0,get:()=>g.sessionId,set:e=>{g.sessionId=e}}),e.clearConversationMemory=()=>{p&&"function"==typeof p.clearSessionApprovals&&p.clearSessionApprovals(g.sessionId)},e.listUndoable=()=>p&&"function"==typeof p.listUndoable?p.listUndoable(g.sessionId):[],e.undoMutation=e=>p&&"function"==typeof p.undoMutation?p.undoMutation(g.sessionId,e):{ok:!1,error:"undo is not available on this engine"},e}async function se(e,t=null){const r=parseLine(e);if("empty"===r.kind)return!0;if("prompt"===r.kind)return await X(r.text),!0;if("unknown"===r.kind){const e=Q(r.name);return V(render.renderNotice(S(),"error",`unknown command: /${r.name}${e?` — did you mean /${e}?`:" — try /help"}`)),!0}if("unavailable"===r.kind){const e=r.command;if(V(render.renderNotice(S(),"warn",`/${e.name} is not available in aegiscode — ${e.unavailable}`)),e.alt)V(render.renderNotice(S(),"info",`try ${e.alt} instead`));else{const t=Q(e.name);t&&V(render.renderNotice(S(),"info",`try /${t} instead`))}return!0}const s=r.command,i=r.arg;if(s.generic){let t;try{t=s.build(i)}catch(e){return V(render.renderNotice(S(),"error",e.message)),!0}const{tool:n,args:r}=t;if(!n)return V(render.renderNotice(S(),"error","/tool needs a tool name — see /help")),!0;try{await J(n,r)}catch(e){V(render.renderNotice(S(),"error",e.message))}return!0}if("function"==typeof s.handler){const n=function(e,t){const n=String(null==t?"":t),r=Array.isArray(e.args)?e.args:[],o=function(e){const t=[];let n="",r=null,o=!1;for(const s of String(e||""))r?s===r?r=null:n+=s:'"'!==s&&"'"!==s?/\s/.test(s)?(n||o)&&(t.push(n),n="",o=!1):(n+=s,o=!0):(r=s,o=!0);return(n||o)&&t.push(n),t}(n),s={_rest:n.trim()};return r.forEach((e,t)=>{void 0!==o[t]&&(s[e]=o[t])}),s}(s,i),r=t||oe();try{return!1!==await s.handler(r,n)}catch(e){return V(render.renderNotice(S(),"error",e&&e.message?e.message:String(e))),!0}}try{let e=s.build(i);if(s.secret){const t=await async function(e,t){if("function"!=typeof e.secretDescribe)return null;try{const n=await e.secretDescribe(t,o);return n&&"object"==typeof n?n:null}catch{return null}}(s,e);if(t&&t.note&&V(render.renderNotice(S(),"info",t.note)),t&&null===t.prompt)return!0;t&&t.provider&&(e={...e,provider:t.provider});const r=await function(e){const t=themeOf(S());return readSecret(t.gray+e+RESET,{stdin:process.stdin,stdout:n})}(t&&t.prompt||`provider key for ${e.provider}: `);if(!r)return V(render.renderNotice(S(),"warn","empty key — nothing sent")),!0;e={...e,api_key:r}}if("aegis_ask"===s.tool)return await X(e.prompt);await J(s.tool,e),"aegis_memory_list"!==s.tool&&"aegis_memory_search"!==s.tool||function(){let e;try{e=cloudsync.status()}catch{return}const t=e.quota;if(!t)return;const n=fmtTokens(t.used||0),r=fmtTokens(t.limit||0);e.overQuota?V(render.renderNotice(S(),"warn",`cloud memory: ${n} of ${r} synced tokens — at the plan's ceiling. Everything stored stays readable; new writes are paused until there is room. /cloud memory for the full state.`)):V(render.renderNotice(S(),"info",`cloud memory: ${n} of ${r} synced tokens — /cloud memory for the full state`))}()}catch(e){V(render.renderNotice(S(),"error",e.message))}return!0}async function ie(){if(p&&"function"==typeof p.unloadLocalModels)try{await p.unloadLocalModels()}catch{}}function ae(e){b.turns++,b.calls+=Number(e&&e.calls||1)||1;const t=e&&e.usage,n=usageTokens(t);if(null!=n){b.tokens+=n;const e=usageBuckets(t);b.inputTokens+=e.input,b.outputTokens+=e.output,b.cacheReadTokens+=e.cacheRead,b.cacheWriteTokens+=e.cacheWrite}return n}function le(e,t,n="done",r=null){try{const o=t&&t.usage,s="number"==typeof r&&Number.isFinite(r)?r:null,i=String(t&&t.model||g.model||"").trim();appendHistory({sessionId:g.sessionId,prompt:e,reply:t&&t.text||"",status:n,model:i||void 0,provider:i&&providerForModel({id:i,cls:g.modelClass})||void 0,usage:o?{...usageBuckets(o),...null!=s?{costUsd:s}:{}}:null!=s?{input:0,output:0,cacheRead:0,cacheWrite:0,costUsd:s}:null}),snapshotCheckpoint(g.sessionId,k)}catch{}P()&&o.apiKey&&Promise.resolve().then(()=>cloudsync.push(o)).then(e=>{if(e&&e.failed&&e.failed.length){const t=e.failed[0];if(ce.has(t.kind))return;if(ce.add(t.kind),"quota"===t.kind)return void V(render.renderNotice(S(),"warn","cloud memory: the plan's synced-token ceiling is reached — earlier sessions stay readable, only NEW writes pause. /cloud memory shows the quota; /cloud memory off stops trying."));const n=t.hint?` — ${t.hint}`:"";V(render.renderNotice(S(),"error",`cloud sync: ${t.message}${n}`))}}).catch(()=>{})}let ce=new Set;function de(){const e=[b.outputTokens>0?`${fmtTokens(b.outputTokens)} tokens`:`${fmtTokens(b.tokens)} tokens`,`${b.calls} call${1===b.calls?"":"s"}`];return feeBillable()&&(e.push(fmtEur(b.cost)),null!=b.balance&&e.push(`balance ${fmtEur(b.balance)}`)),e.join(" · ")}async function ue(e){if(!e||!e.id)return;const t=readSessionTranscript(e.id);if(t.length){k.length=0;for(const e of t)k.push(e);g.sessionId=e.id,V(render.renderNotice(S(),"ok",`resumed ${e.id} — ${t.length} turn(s)`))}else V(render.renderNotice(S(),"warn",`no stored turns for ${e.id}`))}function me(){return{ctx:g,version:VERSION,transcript:k,session:b,client:o,TOOLS:i,ask:(e,t)=>G(e,t),makeCommandContext:()=>oe(),accountConfigured:()=>!!(credentials.keyStatus()||{}).configured,hasProviderKey:e=>{const t=p.settings;if(!t||!e)return!1;const n=byokNamespace(e);return"function"==typeof t.rawKey?!!String(t.rawKey(n)||"").trim():"function"==typeof t.get&&!!(t.get(n)||{}).configured},loadModels:e=>F(e),buildState:()=>Z(),dispatchLine:(e,t)=>se(e,t),refreshSpend:()=>M(),updateConfig:e=>updateConfig(e),showThemePicker:()=>re(),persistTurn:(e,t,n,r)=>le(e,t,n,r),nameConversation:(e,t)=>async function(e,{signal:t=null}={}){const n="local"===g.modelClass,r=await naming.nameConversation(e,{signal:t,callModel:n?null:(e,n)=>G(e,{system:n&&n.system||naming.TITLE_SYSTEM,maxTokens:64,signal:n&&n.signal||t}).then(e=>e&&e.text||null)}),o=String(r||"").trim();return o&&setSessionTitle(g.sessionId,o),o}(e,t),visibleCommands:()=>visibleCommands(),tokensFor:e=>usageTokens(e),recordTurn:e=>ae(e),tokenSummary:()=>de(),resumeSession:e=>ue(e),requestExit:()=>{v=!0},wantsExit:()=>v,keyNotice:()=>o.apiKey?"":c,isYolo:()=>{if(!f)return!1;try{return!1===confirmPosture().enabled}catch{return!1}},setAutoRounds:e=>{f=Boolean(e)}}}async function fe(){V(Y()),await M(),n.write("\n");const t=e.readline||readline.createInterface({input:process.stdin,output:n,terminal:!0}),r=themeOf(S()).gold+GLYPH.cursor+" "+RESET;return t.setPrompt(r),t.prompt(),new Promise(e=>{t.on("line",async e=>{t.pause();let n=!0;try{n=await se(e)}catch(e){V(render.renderNotice(S(),"error",e.message))}if(!n||v)return E=!0,void t.close();t.resume(),t.prompt()}),t.on("close",()=>{E||n.write("\n"),e(0)})})}function pe(){if(e.readline)return;if(!configExists())return;let n;try{n=loadConfig()}catch{return}if(H().includes(n.modelClass)&&(g.modelClass=n.modelClass),t.class){const e=String(t.class).trim().toLowerCase();if(!H().includes(e))throw new Error(`--class ${t.class}: not available on this host (offered: ${H().join(", ")})`);g.modelClass=e}if(!t.model&&n.model&&(g.model=n.model),!t.model&&g.model&&n.modelClass&&g.modelClass!==n.modelClass&&(g.model=null),g.effort=effortRung(t.effort||n.effort),"boolean"==typeof n.vim&&(g.vim=n.vim),n.lastRecap&&(g.lastRecap=n.lastRecap),!t.light&&"number"==typeof n.themeIndex&&THEME_TABLE[n.themeIndex]){g.themeIndex=n.themeIndex,g.light=themeIsLight(n.themeIndex);const e=reconcileThemeIndex(g.themeIndex);if(e.changed){g.themeIndex=e.index,g.light=themeIsLight(e.index),g.themeNotice=e.reason;try{updateConfig({themeIndex:e.index,light:themeIsLight(e.index)})}catch{g.themeNotice+=" (could not save it)"}}}}return{opts:t,session:b,client:o,TOOLS:i,toolList:a,ctx:g,transcript:k,ask:G,runPrompt:X,handleLine:se,runOnce:async function(e,t={}){try{return await async function(e,{json:t=!1}={}){if(pe(),L(),!o.apiKey&&!l){l=!0;const e=await autoProvisionApiKey(o,credentials,{app:"cli"});e.key&&r.write("aegiscode: auto-provisioned a free account"+(e.ok?` (saved to ${credentials.credentialsPath()})`:" (could not save it — reconfigure with /key)")+trialNote(e)+`. Fund it at ${o.promptUrl("topup","device_autoprovision")} or run /byok to use your own key.\n`)}if(!o.apiKey)return r.write(`aegiscode: no AEGIS account key. ${credentials.HOW_TO_SET}, or set $${credentials.KEY_ENV}.\n`),2;await M();const s=[],i=[],a=t?{tool:e=>{if("done"===(e&&e.phase)){const t=e.id&&i.find(t=>t.id===e.id&&!0!==t.settled)||(e.id?null:i[i.length-1]);t?(t.settled=!0,t.ok=!1!==e.ok):(e&&e.name&&s.push(e.name),i.push({name:e&&e.name||null,id:e&&e.id||null,args:briefArgs(e&&e.args),settled:!0,ok:!1!==e.ok}))}else e&&e.name&&s.push(e.name),i.push({name:e&&e.name||null,id:e&&e.id||null,args:briefArgs(e&&e.args),settled:!1,ok:null});const t=e&&void 0!==e.preview?e.preview:null,n=render.renderTurn(S(),{role:"tool",label:e.name,args:e.args,ok:e.ok,diff:t,diffOpen:!1},h());for(const e of Array.isArray(n)?n:[n])r.write(e+"\n")}}:null,c=await G(e,a?{presenter:a}:{});await M();const d=usageTokens(c.usage),u=providerRefusal(c.text,c.usage);if(t)n.write(JSON.stringify({text:c.text,model:c.model,class:g.modelClass,rounds:c.usage&&Number(c.usage.calls)||null,usage:c.usage,reasoning_chars:"number"==typeof c.reasoningChars?c.reasoningChars:null,tokens:d,ms:c.ms,interrupted:c.interrupted,...s.length?{tools:s}:{},...i.length?{tool_log:i}:{},...u?{error:u}:{},balance_eur:b.balance},null,2)+"\n");else if(n.write(c.text+"\n"),u&&r.write(`aegiscode: the provider refused this turn — ${u}\n`),null!=d){const e=themeOf(S());n.write(e.dim+GLYPH.hook+" "+e.blue+(c.model||"aegis")+RESET+e.dim+" "+GLYPH.bullet+" "+RESET+e.white+`${fmtTokens(d)} tokens`+RESET+"\n")}return c.interrupted?130:u?1:0}(e,t)}finally{await ie()}},runInteractive:async function(){try{return await async function(){if(!e.readline&&!1!==e.chatflow&&process.stdin.isTTY&&process.stdout.isTTY){await probeTerminalBackground({onLeftover:e=>events.feedKeys(e,{keystrokes:!0})}),pe(),function(){if(!g.themeNotice)return;const e=g.themeNotice;g.themeNotice="",V(render.renderNotice(S(),"warn",`theme: ${e} (saved)`))}(),L(),o.apiKey||await u();const t=await screens.runOnboarding(g,{continue:!!e.continue,seen:e.seen||configExists,save:e=>updateConfig(e),needsKey:()=>!o.apiKey,submitKey:e=>N(e)});if(!t.ok)return 0;if(t.key&&t.key.set&&V(render.renderNotice(S(),"info",`key saved to ${credentials.credentialsPath()} — no export needed from now on`)),t.key&&t.key.skipped&&!o.apiKey&&V(render.renderNotice(S(),"warn","no key saved — /key <api_key> or `aegiscode login` whenever you are ready")),t.firstRun&&function(){if(!x().enabled)return void V(render.renderNotice(S(),"info","cross-session memory: off (you turned it off) — /cloud memory on stores sessions so an interrupted turn can be picked up later"));const e=cloudsync.status().quota,t=e&&e.limit?` (used ${fmtTokens(e.used||0)} of ${fmtTokens(e.limit)} tokens)`:"";V(render.renderNotice(S(),"info",`cross-session memory: on${t} — sessions are stored to your account so a turn that is interrupted can be resumed. /cloud memory shows the quota; /cloud memory off stops it. Past the ceiling, saved memory stays readable and only new writes pause.`))}(),await W(),e.sessionId)g.continueSession=String(e.sessionId),await ue({id:String(e.sessionId)});else if(e.continue){const e=readOwnSessions(1)[0];e&&(g.continueSession=e.id,await ue({id:e.id}))}return await M(),runAutoModelSync(g).catch(()=>{}),await chatflow.runSession(me()),0}return pe(),L(),fe()}()}finally{await ie()}},runLinearRepl:fe,refreshSpend:M,bannerLines:Y,makeHost:me,loadModels:F,validatePinnedModel:W,recordTurn:ae,persistTurn:le,restorePrefs:pe,setApiKey:N,forgetApiKey:A,adoptLegacyKeyOnce:L,cloudSyncEnabled:P,cloudSyncState:x,setCloudSync:O,cloudsync:cloudsync,keyStatus:()=>credentials.keyStatus(),accountConfigured:()=>!!(credentials.keyStatus()||{}).configured,hasProviderKey:e=>{const t=p.settings;if(!t||!e)return!1;const n=byokNamespace(e);return"function"==typeof t.rawKey?!!String(t.rawKey(n)||"").trim():"function"==typeof t.get&&!!(t.get(n)||{}).configured},sessionId:()=>g.sessionId,tokenSummary:de,resumeSession:ue,makeCommandContext:oe,buildState:Z,get aborted(){return!1}}}module.exports={createApp:createApp,VERSION:VERSION,normalizeDecision:normalizeDecision};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
2
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
-
"use strict";const path=require("node:path"),{resolveShared:resolveShared}=require("./sharedpaths.js"),{offerableCatalog:offerableCatalog,NEXUS_BRAIN_IDS:NEXUS_BRAIN_IDS,AUTO_MODEL_ID:AUTO_MODEL_ID,AUTO_LABEL:AUTO_LABEL,AUTO_NOTE:AUTO_NOTE}=require(resolveShared(path.join("client","brain-catalog.js"))),envFile=require(resolveShared(path.join("client","env-file.js"))),claudePro=require(resolveShared(path.join("desktop","lib","local","claude-pro.js")));function claudeProLoggedIn(){try{return!!claudePro.claudeProStatus({env:process.env}).loggedIn}catch{return!1}}const NO_PIN=null,ID_NOTES=Object.freeze({"openai-gpt4o-mini":"OpenAI gpt-4o-mini, pooled","anthropic-haiku":"Anthropic Haiku, pooled","nexus-brain":"pooled brain · multi-call fan-out, sized by /effort"});function normalizeModel(e){const o="string"==typeof e?{id:e}:e;if(!o||"object"!=typeof o)return null;const r="string"==typeof o.id?o.id.trim():"";if(!r)return null;const n="string"==typeof o.alias_of&&o.alias_of.trim()?o.alias_of.trim():null,i=Array.isArray(o.capabilities)?o.capabilities.filter(e=>"string"==typeof e&&e):[],t={id:r,label:"string"==typeof o.label&&o.label.trim()||"string"==typeof o.name&&o.name.trim()||r,note:("string"==typeof o.note&&o.note.trim()?o.note.trim():"")||(n?`alias of ${n}`:ID_NOTES[r]||i.join(", ")),hidden:!0===o.hidden,aliasOf:n,capabilities:i};return"string"==typeof o.provider&&o.provider.trim()&&(t.provider=o.provider.trim()),!0===o.configured&&(t.configured=!0),"string"==typeof o.cls&&o.cls.trim()&&(t.cls=o.cls.trim()),t}function normalizeModelCatalog(e){const o=Array.isArray(e)?e:Array.isArray(e&&e.models)?e.models:[],r=[],n=new Set;for(const e of o){const o=normalizeModel(e);o&&!n.has(o.id)&&(n.add(o.id),r.push(o))}return r}function pickerEntries(e){const o=Array.isArray(e)?e.filter(Boolean):[],r=offerableCatalog(o).map(normalizeModel).filter(Boolean);if(r.length)return r;const n=o.filter(e=>!e.aliasOf);return n.length?n:o}function withAutoRow(e){const o=Array.isArray(e)?e:[];if(!o.length)return o;if(o.some(e=>e&&e.id===AUTO_MODEL_ID))return o;const r={id:AUTO_MODEL_ID,label:AUTO_LABEL,note:AUTO_NOTE},n=o.findIndex(e=>e&&e.id===NEXUS_BRAIN_IDS[0]),i=n>=0?n+1:0;return[...o.slice(0,i),r,...o.slice(i)]}function findModel(e,o){const r="string"==typeof o?o.trim():"";return r&&(Array.isArray(e)?e:[]).find(e=>e&&e.id===r)||null}function catalogIds(e){return new Set((Array.isArray(e)?e:[]).map(e=>String(e&&e.id||"").toLowerCase()).filter(Boolean))}function modelKeyPlan(e,o={}){const r=e&&e.id||"",n=envFile.keyForModelId(r,e&&e.cls);if(!n.env)return{needed:!1,env:"",provider:"",pooled:n.pooled,status:null,why:"this id has no key variable"};if(n.foreign){const e=!!envFile.resolveForeignSecret(n.env)||claudeProLoggedIn();return{needed:!e,env:n.env,provider:"",pooled:!1,status:{present:e,inFile:e,source:e?"file":"none"},why:e?`${n.env} is already set aside for Claude Code Pro`:`no ${n.env} is set aside for Claude Code Pro`}}const i=envFile.keyStatus(n.env);if(n.pooled){const e=!i.present&&!o.accountConfigured;return{needed:e,env:n.env,provider:"",pooled:!0,status:i,why:e?`no ${n.env} is set on this machine`:`account key present (${o.accountConfigured&&!i.present?"credentials.json":i.source})`}}const t=!i.inFile&&!o.hasStored;return{needed:t,env:n.env,provider:n.provider,pooled:!1,status:i,why:t?`no ${n.env} is stored for provider "${n.provider}"`:`${n.env} is already stored (${i.inFile?i.source:"provider store"})`}}function modelKeyQueue(e,o={}){const r=e&&e.id||"";if(!String(r).trim())return[];const n=envFile.keyForModelId(r,e&&e.cls);if(!n.env)return[];if(n.foreign)return envFile.resolveForeignSecret(n.env)||claudeProLoggedIn()?[]:[{env:n.env,provider:"",vendor:"",role:"claude-pro",needed:!0,status:{present:!1},why:`no ${n.env} is set aside for Claude Code Pro`}];const i=[],t=envFile.keyStatus(envFile.ACCOUNT_ENV_VAR);t.present||o.accountConfigured||i.push({env:envFile.ACCOUNT_ENV_VAR,provider:"",vendor:"",role:"account",needed:!0,status:t,why:`no ${envFile.ACCOUNT_ENV_VAR} is set on this machine`});const l=n.vendor||"",d=l?envFile.envVarFor(l):"",s=!(!l||"function"!=typeof o.hasStoredFor||!o.hasStoredFor(l));if(d){const e=envFile.keyStatus(d);e.inFile||s||i.push({env:d,provider:l,vendor:l,role:"provider",needed:!0,status:e,why:e.present?`${d} is exported in this shell only — the desktop cannot see it`:`no ${d} is stored for provider "${l}"`})}return i}function storeModelKey(e,o,r={}){const n=envFile.keyForModelId(e&&e.id,e&&e.cls),i=String(r.env||"").trim()||n.env;if(!i)return{ok:!1,file:"",changed:!1,error:`cannot name a key variable for "${e&&e.id||""}"`,env:"",provider:"",pooled:n.pooled};const t={...r};delete t.env;const l=n.foreign?envFile.setForeignSecret(i,o,t):envFile.setEnvValue(i,o,t),d=!n.foreign&&i===envFile.ACCOUNT_ENV_VAR;return{...l,env:i,provider:i===n.env?n.provider:"",pooled:d,foreign:!!n.foreign}}function keyVarForModel(e){return envFile.keyForModelId(e&&e.id,e&&e.cls).env}function providerForModel(e){const o=String(e&&e.id||"").trim();return o&&(envFile.keyForModelId(o,e&&e.cls).provider||envFile.providerForModelId(o,e&&e.cls))||""}module.exports={NO_PIN:null,ID_NOTES:ID_NOTES,normalizeModel:normalizeModel,normalizeModelCatalog:normalizeModelCatalog,pickerEntries:pickerEntries,withAutoRow:withAutoRow,AUTO_MODEL_ID:AUTO_MODEL_ID,findModel:findModel,catalogIds:catalogIds,modelKeyPlan:modelKeyPlan,modelKeyQueue:modelKeyQueue,storeModelKey:storeModelKey,keyVarForModel:keyVarForModel,providerForModel:providerForModel,claudeProLoggedIn:claudeProLoggedIn};
|
|
3
|
+
"use strict";const path=require("node:path"),{resolveShared:resolveShared}=require("./sharedpaths.js"),{offerableCatalog:offerableCatalog,NEXUS_BRAIN_IDS:NEXUS_BRAIN_IDS,AUTO_MODEL_ID:AUTO_MODEL_ID,AUTO_LABEL:AUTO_LABEL,AUTO_NOTE:AUTO_NOTE}=require(resolveShared(path.join("client","brain-catalog.js"))),envFile=require(resolveShared(path.join("client","env-file.js"))),claudePro=require(resolveShared(path.join("desktop","lib","local","claude-pro.js")));function claudeProLoggedIn(){try{return!!claudePro.claudeProStatus({env:process.env}).loggedIn}catch{return!1}}const NO_PIN=null,ID_NOTES=Object.freeze({"openai-gpt4o-mini":"OpenAI gpt-4o-mini, pooled","anthropic-haiku":"Anthropic Haiku, pooled","nexus-brain":"pooled brain · multi-call fan-out, sized by /effort"});function normalizeModel(e){const o="string"==typeof e?{id:e}:e;if(!o||"object"!=typeof o)return null;const r="string"==typeof o.id?o.id.trim():"";if(!r)return null;const n="string"==typeof o.alias_of&&o.alias_of.trim()?o.alias_of.trim():null,i=Array.isArray(o.capabilities)?o.capabilities.filter(e=>"string"==typeof e&&e):[],t={id:r,label:"string"==typeof o.label&&o.label.trim()||"string"==typeof o.name&&o.name.trim()||r,note:("string"==typeof o.note&&o.note.trim()?o.note.trim():"")||(n?`alias of ${n}`:ID_NOTES[r]||i.join(", ")),hidden:!0===o.hidden,aliasOf:n,capabilities:i};return"string"==typeof o.provider&&o.provider.trim()&&(t.provider=o.provider.trim()),!0===o.configured&&(t.configured=!0),"string"==typeof o.cls&&o.cls.trim()&&(t.cls=o.cls.trim()),t}function normalizeModelCatalog(e){const o=Array.isArray(e)?e:Array.isArray(e&&e.models)?e.models:[],r=[],n=new Set;for(const e of o){const o=normalizeModel(e);o&&!n.has(o.id)&&(n.add(o.id),r.push(o))}return r}function pickerEntries(e){const o=Array.isArray(e)?e.filter(Boolean):[],r=offerableCatalog(o).map(normalizeModel).filter(Boolean);if(r.length)return r;const n=o.filter(e=>!e.aliasOf);return n.length?n:o}function withAutoRow(e){const o=Array.isArray(e)?e:[];if(!o.length)return o;if(o.some(e=>e&&e.id===AUTO_MODEL_ID))return o;const r={id:AUTO_MODEL_ID,label:AUTO_LABEL,note:AUTO_NOTE},n=o.findIndex(e=>e&&e.id===NEXUS_BRAIN_IDS[0]),i=n>=0?n+1:0;return[...o.slice(0,i),r,...o.slice(i)]}function findModel(e,o){const r="string"==typeof o?o.trim():"";return r&&(Array.isArray(e)?e:[]).find(e=>e&&e.id===r)||null}function catalogIds(e){return new Set((Array.isArray(e)?e:[]).map(e=>String(e&&e.id||"").toLowerCase()).filter(Boolean))}function modelKeyPlan(e,o={}){const r=e&&e.id||"",n=envFile.keyForModelId(r,e&&e.cls);if(!n.env)return{needed:!1,env:"",provider:"",pooled:n.pooled,status:null,why:"this id has no key variable"};if(n.foreign){const e=!!envFile.resolveForeignSecret(n.env)||claudeProLoggedIn();return{needed:!e,env:n.env,provider:"",pooled:!1,status:{present:e,inFile:e,source:e?"file":"none"},why:e?`${n.env} is already set aside for Claude Code Pro`:`no ${n.env} is set aside for Claude Code Pro`}}const i=envFile.keyStatus(n.env);if(n.pooled){const e=!i.present&&!o.accountConfigured;return{needed:e,env:n.env,provider:"",pooled:!0,status:i,why:e?`no ${n.env} is set on this machine`:`account key present (${o.accountConfigured&&!i.present?"credentials.json":i.source})`}}const t=!i.inFile&&!o.hasStored;return{needed:t,env:n.env,provider:n.provider,pooled:!1,status:i,why:t?`no ${n.env} is stored for provider "${n.provider}"`:`${n.env} is already stored (${i.inFile?i.source:"provider store"})`}}function modelKeyQueue(e,o={}){const r=e&&e.id||"";if(!String(r).trim())return[];const n=envFile.keyForModelId(r,e&&e.cls);if(!n.env)return[];if(n.foreign)return envFile.resolveForeignSecret(n.env)||claudeProLoggedIn()?[]:[{env:n.env,provider:"",vendor:"",role:"claude-pro",needed:!0,status:{present:!1},why:`no ${n.env} is set aside for Claude Code Pro`}];const i=[],t=envFile.keyStatus(envFile.ACCOUNT_ENV_VAR);t.present||o.accountConfigured||i.push({env:envFile.ACCOUNT_ENV_VAR,provider:"",vendor:"",role:"account",needed:!0,status:t,why:`no ${envFile.ACCOUNT_ENV_VAR} is set on this machine`});const l=n.vendor||"",d=l?envFile.envVarFor(l):"",s=!(!l||"function"!=typeof o.hasStoredFor||!o.hasStoredFor(l));if(d){const e=envFile.keyStatus(d);e.inFile||s||i.push({env:d,provider:l,vendor:l,role:"provider",needed:!0,status:e,why:e.present?`${d} is exported in this shell only — the desktop cannot see it`:`no ${d} is stored for provider "${l}"`})}return i}function storeModelKey(e,o,r={}){const n=envFile.keyForModelId(e&&e.id,e&&e.cls),i=String(r.env||"").trim()||n.env;if(!i)return{ok:!1,file:"",changed:!1,error:`cannot name a key variable for "${e&&e.id||""}"`,env:"",provider:"",pooled:n.pooled};const t={...r};delete t.env;const l=n.foreign?envFile.setForeignSecret(i,o,t):envFile.setEnvValue(i,o,t),d=!n.foreign&&i===envFile.ACCOUNT_ENV_VAR;return{...l,env:i,provider:i===n.env?n.provider:"",pooled:d,foreign:!!n.foreign}}function keyVarForModel(e){return envFile.keyForModelId(e&&e.id,e&&e.cls).env}function providerForModel(e){const o=String(e&&e.id||"").trim();return o&&(envFile.keyForModelId(o,e&&e.cls).provider||envFile.providerForModelId(o,e&&e.cls))||""}function localDefaultModel(e){const o=(Array.isArray(e)?e:[]).map(e=>"string"==typeof e?e.trim():"").filter(Boolean);if(!o.length)return null;let r=null,n=-1;for(const e of o){const o=/^aegis-local(?:-v(\d+))?(?::|$)/.exec(e);if(!o)continue;const i=null==o[1]?1:Number(o[1]);i>n&&(n=i,r=e)}return r||o[0]||null}module.exports={NO_PIN:null,localDefaultModel:localDefaultModel,ID_NOTES:ID_NOTES,normalizeModel:normalizeModel,normalizeModelCatalog:normalizeModelCatalog,pickerEntries:pickerEntries,withAutoRow:withAutoRow,AUTO_MODEL_ID:AUTO_MODEL_ID,findModel:findModel,catalogIds:catalogIds,modelKeyPlan:modelKeyPlan,modelKeyQueue:modelKeyQueue,storeModelKey:storeModelKey,keyVarForModel:keyVarForModel,providerForModel:providerForModel,claudeProLoggedIn:claudeProLoggedIn};
|
|
@@ -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 CHARS_PER_TOKEN=4,MESSAGE_OVERHEAD=4,IMAGE_COST=850;function estimateTokens(e){if(null==e)return 0;const t="string"==typeof e?e:String(e);return Math.max(0,Math.ceil(t.length/4))}function messageTokens(e){if(!e)return 0;const t=null!=e.content?e.content:null!=e.text?e.text:"";if(Array.isArray(t)){let e=4;for(const
|
|
3
|
+
"use strict";const CHARS_PER_TOKEN=4,MESSAGE_OVERHEAD=4,IMAGE_COST=850;function estimateTokens(e){if(null==e)return 0;const t="string"==typeof e?e:String(e);return Math.max(0,Math.ceil(t.length/4))}function messageTokens(e){if(!e)return 0;const t=null!=e.content?e.content:null!=e.text?e.text:"";if(Array.isArray(t)){let e=4;for(const n of t)n&&"object"==typeof n&&("string"==typeof n.text?e+=estimateTokens(n.text):("image_url"===n.type||n.image_url)&&(e+=850));return e}return 4+estimateTokens(t)}const LOCAL_PREFILL_TOK_PER_SEC=19;function prefillBudgetTokens(e,{tokPerSec:t=19,windowTokens:n=1/0}={}){const s=Number(t)>0?Number(t):19,o=Number(e);if(!Number.isFinite(o)||o<=0)return Math.max(0,n);const r=Math.floor(o*s);return Math.max(0,Math.min(r,n))}function trimContext({messages:e=[],system:t="",budgetTokens:n=8192,reserveTokens:s=0,fixedTokens:o=0}={}){const r=Math.max(0,n-s),i=[],m=Math.max(0,Number(o)||0);let a=m;t&&(a+=4+estimateTokens(t));for(let t=e.length-1;t>=0;t--){const n=messageTokens(e[t]);if(a+n>r&&i.length>0)break;i.unshift(e[t]),a+=n}return{messages:i,system:t,dropped:e.length-i.length,estimatedTokens:a,fixedTokens:m}}module.exports={CHARS_PER_TOKEN:4,MESSAGE_OVERHEAD:4,IMAGE_COST:850,LOCAL_PREFILL_TOK_PER_SEC:19,estimateTokens:estimateTokens,messageTokens:messageTokens,prefillBudgetTokens:prefillBudgetTokens,trimContext:trimContext};
|