aegisone 1.0.43 → 1.0.44

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.
Files changed (50) hide show
  1. package/README.md +2 -2
  2. package/package.json +1 -1
  3. package/src/doctor.js +1 -1
  4. package/vendor/cli/README.md +5 -5
  5. package/vendor/cli/package.json +2 -2
  6. package/vendor/cli/src/deps.js +1 -1
  7. package/vendor/cli/vendor/desktop/lib/local/engine.js +1 -1
  8. package/vendor/cli/vendor/desktop/lib/local/integrity.js +1 -1
  9. package/vendor/cli/vendor/desktop/lib/local/prompt.js +1 -1
  10. package/vendor/cli/vendor/desktop/lib/local/tools.js +1 -1
  11. package/vendor/cli/vendor/desktop/lib/settings.js +1 -1
  12. package/vendor/cli/vendor/desktop/main.js +669 -22
  13. package/vendor/desktop/README.md +3 -3
  14. package/vendor/desktop/bin/aegis.js +1 -1
  15. package/vendor/desktop/lib/avatar/events.js +1 -1
  16. package/vendor/desktop/lib/avatar/persona.js +1 -1
  17. package/vendor/desktop/lib/avatar/store.js +1 -1
  18. package/vendor/desktop/lib/local/cli-face.js +3 -0
  19. package/vendor/desktop/lib/local/engine.js +1 -1
  20. package/vendor/desktop/lib/local/integrity.js +1 -1
  21. package/vendor/desktop/lib/local/prompt.js +1 -1
  22. package/vendor/desktop/lib/local/tools.js +1 -1
  23. package/vendor/desktop/lib/settings.js +1 -1
  24. package/vendor/desktop/main.js +669 -22
  25. package/vendor/desktop/package.json +7 -4
  26. package/vendor/desktop/preload.js +1 -1
  27. package/vendor/desktop/renderer/app.js +3 -3
  28. package/vendor/desktop/renderer/avatar/pane.js +1 -1
  29. package/vendor/desktop/renderer/avatar/parts.js +1 -1
  30. package/vendor/desktop/renderer/commands.js +3 -0
  31. package/vendor/desktop/renderer/composer-triggers.js +3 -0
  32. package/vendor/desktop/renderer/find-in-conversation.js +3 -0
  33. package/vendor/desktop/renderer/fonts/fonts.css +42 -0
  34. package/vendor/desktop/renderer/fonts/ubuntu-vf-italic.woff2 +0 -0
  35. package/vendor/desktop/renderer/fonts/ubuntu-vf.woff2 +0 -0
  36. package/vendor/desktop/renderer/index.html +918 -489
  37. package/vendor/desktop/renderer/nav-history.js +3 -0
  38. package/vendor/desktop/renderer/palette-filter.js +3 -0
  39. package/vendor/desktop/renderer/shortcuts.js +3 -0
  40. package/vendor/desktop/renderer/style.css +2474 -401
  41. package/vendor/desktop/renderer/transcript-view.js +1 -1
  42. package/vendor/desktop/renderer/welcome-rows.js +3 -0
  43. package/vendor/desktop/vendor/faces/cli/README.md +5 -5
  44. package/vendor/desktop/vendor/faces/cli/package.json +2 -2
  45. package/vendor/desktop/vendor/faces/cli/src/deps.js +1 -1
  46. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/engine.js +1 -1
  47. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/integrity.js +1 -1
  48. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/prompt.js +1 -1
  49. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/settings.js +1 -1
  50. package/vendor/desktop/vendor/faces/cli/vendor/desktop/main.js +3 -3
@@ -1,6 +1,6 @@
1
- # AEGIS Desktop
1
+ # aegis one
2
2
 
3
- ![AEGIS Desktop running: the three-class model picker, an agent turn, a gated tool-approval diff, and the unattended work queue](docs/demo.gif)
3
+ ![aegis one running: the three-class model picker, an agent turn, a gated tool-approval diff, and the unattended work queue](docs/demo.gif)
4
4
 
5
5
  A standalone Electron chat app over the [AEGIS](https://aegiscloud.org) API,
6
6
  with an **agentic tool loop**: the model can read, write, and edit files,
@@ -286,7 +286,7 @@ than silent.
286
286
 
287
287
  `Cmd/Ctrl+Shift+Space` (default, configurable in the sidebar's **Quick
288
288
  Launcher** card) toggles a small, frameless, always-on-top prompt window near
289
- your cursor — from anywhere on the desktop, even when AEGIS Desktop isn't the
289
+ your cursor — from anywhere on the desktop, even when aegis one isn't the
290
290
  focused app. It streams a one-shot answer over the same transport the main
291
291
  window uses, with the agent's tool-calling loop turned off (no file/shell
292
292
  access, no approval prompts) — just a fast question and an answer.
@@ -1,4 +1,4 @@
1
1
  #!/usr/bin/env node
2
2
  // SPDX-License-Identifier: AGPL-3.0-or-later
3
3
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
4
- "use strict";const path=require("node:path"),{spawn:spawn}=require("node:child_process"),appDir=path.join(__dirname,"..");let electronPath;(process.argv.includes("--version")||process.argv.includes("-v"))&&(console.log(require(path.join(appDir,"package.json")).version),process.exit(0));try{electronPath=require("electron")}catch(e){console.error("Failed to launch AEGIS Desktop: the electron runtime is not installed.\nIt ships as an optional dependency, so an install run with --omit=optional\n(or --no-optional, or a registry/proxy that skipped it) leaves it out.\nFix it with: npm i -g electron@^44 — or reinstall without that flag."),process.env.AEGIS_DEBUG&&console.error(e),process.exit(1)}const child=spawn(electronPath,[appDir,...process.argv.slice(2)],{stdio:"inherit"});child.on("error",(e=>{console.error("Failed to launch AEGIS Desktop:",e.message),process.exit(1)})),child.on("close",(e=>process.exit(null==e?0:e)));
4
+ "use strict";const path=require("node:path"),{spawn:spawn}=require("node:child_process"),appDir=path.join(__dirname,"..");let electronPath;(process.argv.includes("--version")||process.argv.includes("-v"))&&(console.log(require(path.join(appDir,"package.json")).version),process.exit(0));try{electronPath=require("electron")}catch(e){console.error("Failed to launch aegis one: the electron runtime is not installed.\nIt ships as an optional dependency, so an install run with --omit=optional\n(or --no-optional, or a registry/proxy that skipped it) leaves it out.\nFix it with: npm i -g electron@^44 — or reinstall without that flag."),process.env.AEGIS_DEBUG&&console.error(e),process.exit(1)}const child=spawn(electronPath,[appDir,...process.argv.slice(2)],{stdio:"inherit"});child.on("error",(e=>{console.error("Failed to launch aegis one:",e.message),process.exit(1)})),child.on("close",(e=>process.exit(null==e?0:e)));
@@ -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 STATES=Object.freeze(["idle","listening","thinking","reading","writing","running","awaiting-you","celebrating","dozing","error"]),SIGNALS=Object.freeze(["turn.start","turn.stream","turn.end","tool.read","tool.write","tool.run","approval.card","approval.decided","queue.progress","sync.error","sync.ok","celebrate.done","poke","reset","idle.timeout"]),ACTIVITY_SIGNALS=Object.freeze(["turn.start","turn.stream","tool.read","tool.write","tool.run","approval.card","approval.decided","queue.progress","poke"]),DEFAULT_IDLE_TIMEOUT_MS=3e5;function afterTurnEnd(e){return e&&e.green?"celebrating":"idle"}const TABLE=Object.freeze({idle:{"turn.start":"listening","approval.card":"awaiting-you","queue.progress":"running","idle.timeout":"dozing","sync.error":"error",reset:"idle"},listening:{"turn.start":"listening","turn.stream":"thinking","tool.read":"reading","tool.write":"writing","tool.run":"running","approval.card":"awaiting-you","turn.end":afterTurnEnd,"sync.error":"error",reset:"idle"},thinking:{"turn.stream":"thinking","tool.read":"reading","tool.write":"writing","tool.run":"running","approval.card":"awaiting-you","turn.end":afterTurnEnd,"sync.error":"error",reset:"idle"},reading:{"tool.read":"reading","tool.write":"writing","tool.run":"running","turn.stream":"thinking","approval.card":"awaiting-you","turn.end":afterTurnEnd,"sync.error":"error",reset:"idle"},writing:{"tool.write":"writing","tool.read":"reading","tool.run":"running","turn.stream":"thinking","approval.card":"awaiting-you","turn.end":afterTurnEnd,"sync.error":"error",reset:"idle"},running:{"tool.run":"running","tool.read":"reading","tool.write":"writing","queue.progress":"running","turn.stream":"thinking","approval.card":"awaiting-you","turn.end":afterTurnEnd,"sync.error":"error",reset:"idle"},"awaiting-you":{"approval.card":"awaiting-you","approval.decided":"thinking","turn.end":afterTurnEnd,"sync.error":"error",reset:"idle"},celebrating:{"celebrate.done":"idle","turn.start":"listening","sync.error":"error",reset:"idle"},dozing:{poke:"idle","turn.start":"listening","approval.card":"awaiting-you","sync.error":"error",reset:"idle"},error:{reset:"idle","sync.ok":"idle","turn.start":"listening","sync.error":"error"}}),EXPRESSIONS=Object.freeze({idle:"neutral",listening:"attentive",thinking:"focused",reading:"focused",writing:"focused",running:"focused","awaiting-you":"waiting",celebrating:"happy",dozing:"sleepy",error:"concerned"});function isState(e){return STATES.includes(e)}function expressionFor(e){return EXPRESSIONS[e]||"neutral"}function createMachine(e){const r=e&&"object"==typeof e?e:{},t=Number.isFinite(r.idleTimeoutMs)&&r.idleTimeoutMs>0?r.idleTimeoutMs:3e5;let n=isState(r.state)?r.state:"idle",i=Number.isFinite(r.now)?r.now:0,o=i,a=0;const s=Number.isFinite(r.historyLimit)&&r.historyLimit>0?r.historyLimit:64,u=[],l=new Set;function d(e,r){const t=n,a=(TABLE[n]||{})[String(e)];let d=n;"function"==typeof a?d=a(r||{}):"string"==typeof a&&(d=a),isState(d)||(d=n);const g=d!==t;return g&&(n=d),ACTIVITY_SIGNALS.includes(String(e))&&(o=i),function(e){u.push(e),u.length>s&&u.shift();for(const r of l)try{r(e)}catch{}}({signal:String(e),prev:t,state:n,changed:g,meta:r||null,t:i}),{changed:g,state:n,prev:t,signal:String(e)}}return{get state(){return n},get expression(){return expressionFor(n)},get lastActivity(){return o},get ticks(){return a},history:u,send:d,tick:function(e){return Number.isFinite(e)&&(i=Math.max(i,e)),a+=1,"idle"!==n||i-o<t?{changed:!1,state:n,prev:n,signal:null}:d("idle.timeout")},setNow:e=>(Number.isFinite(e)&&(i=Math.max(i,e)),i),on(e){if("function"!=typeof e)throw new TypeError("listener must be a function");return l.add(e),()=>l.delete(e)},reset:e=>(l.clear(),u.length=0,n="idle",o=Number.isFinite(e)?e:i,n)}}function transitions(){const e=[];for(const r of STATES)for(const t of Object.keys(TABLE[r]||{}))e.push({state:r,signal:t});return e}module.exports={STATES:STATES,SIGNALS:SIGNALS,ACTIVITY_SIGNALS:ACTIVITY_SIGNALS,EXPRESSIONS:EXPRESSIONS,TABLE:TABLE,DEFAULT_IDLE_TIMEOUT_MS:3e5,isState:isState,expressionFor:expressionFor,createMachine:createMachine,transitions:transitions};
3
+ "use strict";!function(){const e=Object.freeze(["idle","listening","thinking","reading","writing","running","awaiting-you","celebrating","dozing","error"]),r=Object.freeze(["turn.start","turn.stream","turn.end","tool.read","tool.write","tool.run","approval.card","approval.decided","queue.progress","sync.error","sync.ok","celebrate.done","poke","reset","idle.timeout"]),t=Object.freeze(["turn.start","turn.stream","tool.read","tool.write","tool.run","approval.card","approval.decided","queue.progress","poke"]),n=3e5;function i(e){return e&&e.green?"celebrating":"idle"}const o=Object.freeze({idle:{"turn.start":"listening","approval.card":"awaiting-you","queue.progress":"running","idle.timeout":"dozing","sync.error":"error",reset:"idle"},listening:{"turn.start":"listening","turn.stream":"thinking","tool.read":"reading","tool.write":"writing","tool.run":"running","approval.card":"awaiting-you","turn.end":i,"sync.error":"error",reset:"idle"},thinking:{"turn.stream":"thinking","tool.read":"reading","tool.write":"writing","tool.run":"running","approval.card":"awaiting-you","turn.end":i,"sync.error":"error",reset:"idle"},reading:{"tool.read":"reading","tool.write":"writing","tool.run":"running","turn.stream":"thinking","approval.card":"awaiting-you","turn.end":i,"sync.error":"error",reset:"idle"},writing:{"tool.write":"writing","tool.read":"reading","tool.run":"running","turn.stream":"thinking","approval.card":"awaiting-you","turn.end":i,"sync.error":"error",reset:"idle"},running:{"tool.run":"running","tool.read":"reading","tool.write":"writing","queue.progress":"running","turn.stream":"thinking","approval.card":"awaiting-you","turn.end":i,"sync.error":"error",reset:"idle"},"awaiting-you":{"approval.card":"awaiting-you","approval.decided":"thinking","turn.end":i,"sync.error":"error",reset:"idle"},celebrating:{"celebrate.done":"idle","turn.start":"listening","sync.error":"error",reset:"idle"},dozing:{poke:"idle","turn.start":"listening","approval.card":"awaiting-you","sync.error":"error",reset:"idle"},error:{reset:"idle","sync.ok":"idle","turn.start":"listening","sync.error":"error"}}),a=Object.freeze({idle:"neutral",listening:"attentive",thinking:"focused",reading:"focused",writing:"focused",running:"focused","awaiting-you":"waiting",celebrating:"happy",dozing:"sleepy",error:"concerned"});function s(r){return e.includes(r)}function u(e){return a[e]||"neutral"}const l=Object.freeze({STATES:e,SIGNALS:r,ACTIVITY_SIGNALS:t,EXPRESSIONS:a,TABLE:o,DEFAULT_IDLE_TIMEOUT_MS:n,isState:s,expressionFor:u,createMachine:function(e){const r=e&&"object"==typeof e?e:{},i=Number.isFinite(r.idleTimeoutMs)&&r.idleTimeoutMs>0?r.idleTimeoutMs:n;let a=s(r.state)?r.state:"idle",l=Number.isFinite(r.now)?r.now:0,d=l,g=0;const c=Number.isFinite(r.historyLimit)&&r.historyLimit>0?r.historyLimit:64,p=[],y=new Set;function f(e,r){const n=a,i=(o[a]||{})[String(e)];let u=a;"function"==typeof i?u=i(r||{}):"string"==typeof i&&(u=i),s(u)||(u=a);const g=u!==n;return g&&(a=u),t.includes(String(e))&&(d=l),function(e){p.push(e),p.length>c&&p.shift();for(const r of y)try{r(e)}catch{}}({signal:String(e),prev:n,state:a,changed:g,meta:r||null,t:l}),{changed:g,state:a,prev:n,signal:String(e)}}return{get state(){return a},get expression(){return u(a)},get lastActivity(){return d},get ticks(){return g},history:p,send:f,tick:function(e){return Number.isFinite(e)&&(l=Math.max(l,e)),g+=1,"idle"!==a||l-d<i?{changed:!1,state:a,prev:a,signal:null}:f("idle.timeout")},setNow:e=>(Number.isFinite(e)&&(l=Math.max(l,e)),l),on(e){if("function"!=typeof e)throw new TypeError("listener must be a function");return y.add(e),()=>y.delete(e)},reset:e=>(y.clear(),p.length=0,a="idle",d=Number.isFinite(e)?e:l,a)}},transitions:function(){const r=[];for(const t of e)for(const e of Object.keys(o[t]||{}))r.push({state:t,signal:e});return r}});"undefined"!=typeof module&&module.exports?module.exports=l:"undefined"!=typeof globalThis&&(globalThis.AegisAvatarEvents=l)}();
@@ -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 SCHEMA_VERSION=1,PARTS=Object.freeze({frame:Object.freeze(["A","B","C"]),skin:Object.freeze([0,1,2,3,4,5]),hair:Object.freeze(["short-1","bob-2","long-3","curly-4","buzz-5","ponytail-6","braids-7","wavy-8"]),eyes:Object.freeze(["soft","sharp","sleepy","bright"]),outfit:Object.freeze(["hoodie","tshirt","flannel","jacket","headphones","glasses","scarf","apron","seasonal-winter","archive-coat"]),palette:Object.freeze(["amber","slate","moss","plum","mono","sunset"]),motion:Object.freeze(["full","reduced","minimal"]),size:Object.freeze(["small","medium","large"]),expressionPack:Object.freeze(["core","trusted","companion","confidant","archivist"]),proactivity:Object.freeze(["off","hints","brief"]),voiceEngine:Object.freeze(["none","local","system"])}),MAX_OUTFIT_LAYERS=3,LIMITS=Object.freeze({name:40,pronouns:24,selfDesc:120,address:32,voiceId:64,customExpressions:24}),HEX_COLOR=/^#[0-9a-f]{6}$/i,UNSAFE_TEXT=/[\u0000-\u001f\u007f\u2028\u2029]+/g;function has(e,t){return e.some((e=>e===t))}function cleanText(e,t){return"string"!=typeof e?"":e.replace(UNSAFE_TEXT," ").replace(/\s+/g," ").trim().slice(0,t)}function clamp01(e,t){const r="number"==typeof e&&Number.isFinite(e)?e:t;return Math.min(1,Math.max(0,r))}function pick(e,t,r){return has(e,t)?t:r}function nonEmptyId(e,t,r){if("string"!=typeof e)return t;const n=e.trim();return has(r,n)?n:t}const DEFAULT_PERSONA=Object.freeze({schema:SCHEMA_VERSION,identity:Object.freeze({name:"Aegis",pronouns:"they/them",selfDesc:"your build partner"}),presentation:Object.freeze({frame:"A",skin:2,hair:"bob-2",hairColor:"#3b2a20",eyes:"soft",outfit:Object.freeze(["hoodie"]),palette:"amber"}),expressions:Object.freeze({pack:"core",custom:Object.freeze({})}),voice:Object.freeze({enabled:!1,engine:"none",id:null,rate:1}),register:Object.freeze({formality:.3,humor:.4,verbosity:.5,proactivity:"hints",address:"you",emojis:!1}),appearance:Object.freeze({motion:"full",size:"medium",docked:!0})});function defaultPersona(){return JSON.parse(JSON.stringify(DEFAULT_PERSONA))}const MIGRATIONS=Object.freeze({0:e=>Object.assign({},e)});function migrate(e){if(!e||"object"!=typeof e)return{persona:defaultPersona(),migrated:!1};let t=e,r=Number.isInteger(t.schema)?t.schema:0,n=!1;for(;r<SCHEMA_VERSION;){const e=MIGRATIONS[r];t=e?e(t):t,r+=1,n=!0}return{persona:t,migrated:n,fromSchema:Number.isInteger(e.schema)?e.schema:0}}function validate(e){const t=[],r=[];if(null==e)return{ok:!0,persona:defaultPersona(),errors:t,warnings:["no persona stored yet — using defaults"],migrated:!1};if("object"!=typeof e||Array.isArray(e))return{ok:!1,persona:defaultPersona(),errors:["persona must be a JSON object"],warnings:r,migrated:!1};if(Number.isInteger(e.schema)&&e.schema>SCHEMA_VERSION)return{ok:!1,persona:defaultPersona(),errors:[`persona schema ${e.schema} is newer than this build supports (${SCHEMA_VERSION})`],warnings:r,migrated:!1};const{persona:n,migrated:i}=migrate(e),s=n,o=DEFAULT_PERSONA,a=s.identity&&"object"==typeof s.identity?s.identity:{},c=cleanText(a.name,LIMITS.name)||o.identity.name;void 0!==a.name&&c!==a.name&&r.push("identity.name was trimmed to a single line and length-capped");const p={name:c,pronouns:cleanText(a.pronouns,LIMITS.pronouns)||o.identity.pronouns,selfDesc:cleanText(a.selfDesc,LIMITS.selfDesc)},u=s.presentation&&"object"==typeof s.presentation?s.presentation:{},l=has(PARTS.skin,u.skin)?u.skin:(Number.isInteger(u.skin),o.presentation.skin);void 0===u.skin||has(PARTS.skin,u.skin)||r.push(`unknown skin index ${JSON.stringify(u.skin)} — using ${l}`);for(const e of["frame","hair","eyes","palette"]){const t=u[e];void 0===t||has(PARTS[e],t)||r.push(`unknown ${e} ${JSON.stringify(t)} — using ${o.presentation[e]}`)}const f=HEX_COLOR.test(String(u.hairColor||""))?String(u.hairColor).toLowerCase():o.presentation.hairColor;void 0!==u.hairColor&&f!==u.hairColor&&r.push(`hairColor must be a #rrggbb hex — using ${f}`);let m=Array.isArray(u.outfit)?u.outfit:o.presentation.outfit;const d=[];for(const e of m)has(PARTS.outfit,e)?d.includes(e)||d.push(e):r.push(`unknown outfit item ${JSON.stringify(e)} — dropped`);d.length>MAX_OUTFIT_LAYERS&&(r.push(`at most ${MAX_OUTFIT_LAYERS} outfit layers — extra layers dropped`),d.length=MAX_OUTFIT_LAYERS),m=d;const y={frame:pick(PARTS.frame,u.frame,o.presentation.frame),skin:l,hair:pick(PARTS.hair,u.hair,o.presentation.hair),hairColor:f,eyes:pick(PARTS.eyes,u.eyes,o.presentation.eyes),outfit:m,palette:pick(PARTS.palette,u.palette,o.presentation.palette)},h=s.expressions&&"object"==typeof s.expressions?s.expressions:{},b={};if(h.custom&&"object"==typeof h.custom&&!Array.isArray(h.custom)){let e=0;for(const[t,n]of Object.entries(h.custom)){if(e>=LIMITS.customExpressions){r.push(`at most ${LIMITS.customExpressions} custom expressions — extras dropped`);break}const i=cleanText(t,40);i&&"object"==typeof n&&null!==n&&(b[i]=JSON.parse(JSON.stringify(n)),e+=1)}}const S={pack:pick(PARTS.expressionPack,h.pack,o.expressions.pack),custom:b},g=s.voice&&"object"==typeof s.voice?s.voice:{},O=pick(PARTS.voiceEngine,g.engine,o.voice.engine),A="number"==typeof g.rate&&Number.isFinite(g.rate)?Math.min(2,Math.max(.5,g.rate)):o.voice.rate,T={enabled:!0===g.enabled,engine:O,id:"none"===O?null:cleanText(g.id,LIMITS.voiceId)||null,rate:A};T.id&&/clone|voiceprint|imitat/i.test(T.id)&&(r.push("voice.id looks like a cloned voice — refused (no cloning of real people)"),T.id=null,T.enabled=!1);const k=s.register&&"object"==typeof s.register?s.register:{},E={formality:clamp01(k.formality,o.register.formality),humor:clamp01(k.humor,o.register.humor),verbosity:clamp01(k.verbosity,o.register.verbosity),proactivity:pick(PARTS.proactivity,k.proactivity,o.register.proactivity),address:cleanText(k.address,LIMITS.address)||o.register.address,emojis:!0===k.emojis},I=s.appearance&&"object"==typeof s.appearance?s.appearance:{},j={motion:pick(PARTS.motion,I.motion,o.appearance.motion),size:pick(PARTS.size,I.size,o.appearance.size),docked:!1!==I.docked},v=["schema","identity","presentation","expressions","voice","register","appearance"];for(const e of Object.keys(s))v.includes(e)||r.push(`unknown persona key ${JSON.stringify(e)} — ignored`);return{ok:!0,errors:t,warnings:r,migrated:i,persona:{schema:SCHEMA_VERSION,identity:p,presentation:y,expressions:S,voice:T,register:E,appearance:j}}}function load(e){return validate(e).persona}function update(e,t){const r=validate(e).persona;return validate(t&&"object"==typeof t?{schema:SCHEMA_VERSION,identity:{...r.identity,...t.identity||{}},presentation:{...r.presentation,...t.presentation||{}},expressions:{...r.expressions,...t.expressions||{}},voice:{...r.voice,...t.voice||{}},register:{...r.register,...t.register||{}},appearance:{...r.appearance,...t.appearance||{}}}:r)}function appliesMotion(e,t){const r=t?"minimal":e.appearance.motion;return"minimal"===r?"minimal":r}module.exports={SCHEMA_VERSION:SCHEMA_VERSION,PARTS:PARTS,LIMITS:LIMITS,MAX_OUTFIT_LAYERS:MAX_OUTFIT_LAYERS,DEFAULT_PERSONA:DEFAULT_PERSONA,defaultPersona:defaultPersona,migrate:migrate,validate:validate,load:load,update:update,appliesMotion:appliesMotion,cleanText:cleanText};
3
+ "use strict";!function(){const e=1,t=Object.freeze({frame:Object.freeze(["A","B","C"]),skin:Object.freeze([0,1,2,3,4,5]),hair:Object.freeze(["short-1","bob-2","long-3","curly-4","buzz-5","ponytail-6","braids-7","wavy-8"]),eyes:Object.freeze(["soft","sharp","sleepy","bright"]),outfit:Object.freeze(["hoodie","tshirt","flannel","jacket","headphones","glasses","scarf","apron","seasonal-winter","archive-coat"]),palette:Object.freeze(["amber","slate","moss","plum","mono","sunset"]),motion:Object.freeze(["full","reduced","minimal"]),size:Object.freeze(["small","medium","large"]),expressionPack:Object.freeze(["core","trusted","companion","confidant","archivist"]),proactivity:Object.freeze(["off","hints","brief"]),voiceEngine:Object.freeze(["none","local","system"])}),r=Object.freeze({name:40,pronouns:24,selfDesc:120,address:32,voiceId:64,customExpressions:24}),n=/^#[0-9a-f]{6}$/i,s=/[\u0000-\u001f\u007f\u2028\u2029]+/g;function i(e,t){return e.some((e=>e===t))}function o(e,t){return"string"!=typeof e?"":e.replace(s," ").replace(/\s+/g," ").trim().slice(0,t)}function a(e,t){const r="number"==typeof e&&Number.isFinite(e)?e:t;return Math.min(1,Math.max(0,r))}function c(e,t,r){return i(e,t)?t:r}const p=Object.freeze({schema:e,identity:Object.freeze({name:"Aegis",pronouns:"they/them",selfDesc:"your build partner"}),presentation:Object.freeze({frame:"A",skin:2,hair:"bob-2",hairColor:"#3b2a20",eyes:"soft",outfit:Object.freeze(["hoodie"]),palette:"amber"}),expressions:Object.freeze({pack:"core",custom:Object.freeze({})}),voice:Object.freeze({enabled:!1,engine:"none",id:null,rate:1}),register:Object.freeze({formality:.3,humor:.4,verbosity:.5,proactivity:"hints",address:"you",emojis:!1}),appearance:Object.freeze({motion:"full",size:"medium",docked:!0})});function u(){return JSON.parse(JSON.stringify(p))}const f=Object.freeze({0:e=>Object.assign({},e)});function m(t){if(!t||"object"!=typeof t)return{persona:u(),migrated:!1};let r=t,n=Number.isInteger(r.schema)?r.schema:0,s=!1;for(;n<e;){const e=f[n];r=e?e(r):r,n+=1,s=!0}return{persona:r,migrated:s,fromSchema:Number.isInteger(t.schema)?t.schema:0}}function l(s){const f=[],l=[];if(null==s)return{ok:!0,persona:u(),errors:f,warnings:["no persona stored yet — using defaults"],migrated:!1};if("object"!=typeof s||Array.isArray(s))return{ok:!1,persona:u(),errors:["persona must be a JSON object"],warnings:l,migrated:!1};if(Number.isInteger(s.schema)&&s.schema>e)return{ok:!1,persona:u(),errors:[`persona schema ${s.schema} is newer than this build supports (${e})`],warnings:l,migrated:!1};const{persona:d,migrated:b}=m(s),y=d,g=p,h=y.identity&&"object"==typeof y.identity?y.identity:{},j=o(h.name,r.name)||g.identity.name;void 0!==h.name&&j!==h.name&&l.push("identity.name was trimmed to a single line and length-capped");const O={name:j,pronouns:o(h.pronouns,r.pronouns)||g.identity.pronouns,selfDesc:o(h.selfDesc,r.selfDesc)},v=y.presentation&&"object"==typeof y.presentation?y.presentation:{},k=i(t.skin,v.skin)?v.skin:(Number.isInteger(v.skin),g.presentation.skin);void 0===v.skin||i(t.skin,v.skin)||l.push(`unknown skin index ${JSON.stringify(v.skin)} — using ${k}`);for(const e of["frame","hair","eyes","palette"]){const r=v[e];void 0===r||i(t[e],r)||l.push(`unknown ${e} ${JSON.stringify(r)} — using ${g.presentation[e]}`)}const z=n.test(String(v.hairColor||""))?String(v.hairColor).toLowerCase():g.presentation.hairColor;void 0!==v.hairColor&&z!==v.hairColor&&l.push(`hairColor must be a #rrggbb hex — using ${z}`);let x=Array.isArray(v.outfit)?v.outfit:g.presentation.outfit;const S=[];for(const e of x)i(t.outfit,e)?S.includes(e)||S.push(e):l.push(`unknown outfit item ${JSON.stringify(e)} — dropped`);S.length>3&&(l.push("at most 3 outfit layers — extra layers dropped"),S.length=3),x=S;const A={frame:c(t.frame,v.frame,g.presentation.frame),skin:k,hair:c(t.hair,v.hair,g.presentation.hair),hairColor:z,eyes:c(t.eyes,v.eyes,g.presentation.eyes),outfit:x,palette:c(t.palette,v.palette,g.presentation.palette)},N=y.expressions&&"object"==typeof y.expressions?y.expressions:{},w={};if(N.custom&&"object"==typeof N.custom&&!Array.isArray(N.custom)){let e=0;for(const[t,n]of Object.entries(N.custom)){if(e>=r.customExpressions){l.push(`at most ${r.customExpressions} custom expressions — extras dropped`);break}const s=o(t,40);s&&"object"==typeof n&&null!==n&&(w[s]=JSON.parse(JSON.stringify(n)),e+=1)}}const $={pack:c(t.expressionPack,N.pack,g.expressions.pack),custom:w},C=y.voice&&"object"==typeof y.voice?y.voice:{},E=c(t.voiceEngine,C.engine,g.voice.engine),I="number"==typeof C.rate&&Number.isFinite(C.rate)?Math.min(2,Math.max(.5,C.rate)):g.voice.rate,J={enabled:!0===C.enabled,engine:E,id:"none"===E?null:o(C.id,r.voiceId)||null,rate:I};J.id&&/clone|voiceprint|imitat/i.test(J.id)&&(l.push("voice.id looks like a cloned voice — refused (no cloning of real people)"),J.id=null,J.enabled=!1);const M=y.register&&"object"==typeof y.register?y.register:{},T={formality:a(M.formality,g.register.formality),humor:a(M.humor,g.register.humor),verbosity:a(M.verbosity,g.register.verbosity),proactivity:c(t.proactivity,M.proactivity,g.register.proactivity),address:o(M.address,r.address)||g.register.address,emojis:!0===M.emojis},D=y.appearance&&"object"==typeof y.appearance?y.appearance:{},P={motion:c(t.motion,D.motion,g.appearance.motion),size:c(t.size,D.size,g.appearance.size),docked:!1!==D.docked},F=["schema","identity","presentation","expressions","voice","register","appearance"];for(const e of Object.keys(y))F.includes(e)||l.push(`unknown persona key ${JSON.stringify(e)} — ignored`);return{ok:!0,errors:f,warnings:l,migrated:b,persona:{schema:e,identity:O,presentation:A,expressions:$,voice:J,register:T,appearance:P}}}const d=Object.freeze({SCHEMA_VERSION:e,PARTS:t,LIMITS:r,MAX_OUTFIT_LAYERS:3,DEFAULT_PERSONA:p,defaultPersona:u,migrate:m,validate:l,load:function(e){return l(e).persona},update:function(t,r){const n=l(t).persona;return l(r&&"object"==typeof r?{schema:e,identity:{...n.identity,...r.identity||{}},presentation:{...n.presentation,...r.presentation||{}},expressions:{...n.expressions,...r.expressions||{}},voice:{...n.voice,...r.voice||{}},register:{...n.register,...r.register||{}},appearance:{...n.appearance,...r.appearance||{}}}:n)},appliesMotion:function(e,t){const r=t?"minimal":e.appearance.motion;return"minimal"===r?"minimal":r},cleanText:o});"undefined"!=typeof module&&module.exports?module.exports=d:"undefined"!=typeof globalThis&&(globalThis.AegisAvatarPersona=d)}();
@@ -1,3 +1,3 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- "use strict";const fs=require("node:fs"),path=require("node:path"),crypto=require("node:crypto"),xp=require("./xp.js"),level=require("./level.js"),personaModule=require("./persona.js"),LEDGER_DIR="avatar",LEDGER_FILE="ledger.jsonl",PERSONA_FILE="persona.json",DIGEST_CHARS=16;function avatarHome(e){return path.join(e,LEDGER_DIR)}function ledgerPath(e){return path.join(avatarHome(e),LEDGER_FILE)}function personaPath(e){return path.join(avatarHome(e),PERSONA_FILE)}function fingerprint(e){return crypto.createHash("sha1").update(String(null==e?"":e)).digest("hex").slice(0,DIGEST_CHARS)}function memoryEntryId(e){return`note-${fingerprint(`${e&&e.source||"aegis-desktop"}|${String(e&&(null!=e.content?e.content:e.text)||"").trim().toLowerCase()}`)}`}function normalizeMemoryEntry(e){if(!e||"object"!=typeof e)return e;const t="string"==typeof e.content&&e.content?e.content:"string"==typeof e.text?e.text:"";if(!t)return e;const r=Object.assign({},e);return r.content||(r.content=t),r.role||(r.role="user"),r.source||(r.source="aegis-desktop"),r.id||(r.id=memoryEntryId(r)),r}function createAvatarStore({dir:e,now:t=(()=>Date.now()),env:r=process.env,log:n=(()=>{})}={}){if(!e||"string"!=typeof e)throw new Error("createAvatarStore: a user-data directory is required");const o=ledgerPath(e);let s=null;const i=new Map,a=new Set,c=new Map,u=new Set;function l(){try{const e=fs.statSync(o);if(s&&s.size===e.size&&s.mtimeMs===e.mtimeMs)return s.parsed;const t=xp.parseLedger(fs.readFileSync(o,"utf8"));return s={size:e.size,mtimeMs:e.mtimeMs,parsed:t},t}catch(e){return e&&"ENOENT"===e.code?{entries:[],corrupt:0}:(n(`aegis: could not read ${o}: ${e&&e.message}`),{entries:[],corrupt:0,error:e&&e.message||"unreadable"})}}function d(e,r={}){const i="number"==typeof r.t&&r.t?r.t:t();return function(e){const t=`${JSON.stringify(e)}\n`;try{return fs.mkdirSync(path.dirname(o),{recursive:!0,mode:448}),fs.appendFileSync(o,t),s&&(s={size:s.size+Buffer.byteLength(t),mtimeMs:0,parsed:{entries:s.parsed.entries.concat([e]),corrupt:s.parsed.corrupt}}),e}catch(t){return n(`aegis: could not append to ${o}: ${t&&t.message}`),s=null,e}}(xp.makeEntry(e,Object.assign({},r,{t:i}),{t:i}))}function f(e,t){if(null==e||""===e)return"new";const r=String(e),n=fingerprint(t),o=c.get(r),s=a.has(r);return c.set(r,n),a.add(r),void 0===o?s?"same":"new":o===n?"same":"changed"}function p(){if(!a.size)return null;const e=new Set(a);for(const t of u)e.delete(t);return e}function m(e={}){const t=null==e.session?null:e.session,n=l(),s=null!=t&&i.get(t)||null,a=xp.evaluate(n.entries,{liveRefs:p(),held:s,session:t}),c=level.applyEnvOverrides(level.capabilities(a.level),e.env||r);return null!=t&&i.set(t,xp.nextHeld(a,t)),Object.assign({},a,{capabilities:c.caps,envIgnored:c.ignored,ledger:{file:o,entries:n.entries.length,corrupt:n.corrupt||0}})}return{dir:e,file:o,read:l,append:d,award:d,observe:f,awardSave:function(e={},t={}){const r=e&&null!=e.id?String(e.id):null,n=f(r,e&&(null!=e.content?e.content:e.text)),o="new"===n?"memory.saved":"changed"===n?"memory.corrected":"memory.reinforced";return{kind:o,ref:r,class:n,entry:d(o,Object.assign({ref:r,source:e&&e.source},t))}},awardQueued:function(e={},t={}){const r=e&&null!=e.id?String(e.id):null;return f(r,e&&(null!=e.content?e.content:e.text)),{kind:"memory.queued",ref:r,entry:d("memory.queued",Object.assign({ref:r,source:e&&e.source},t))}},awardRecalls:function(e,t={}){const r=Array.isArray(e)?e:[],n=r.slice(0,xp.RECALL_PER_TURN_CAP);for(const e of n)f(e&&e.id,e&&(null!=e.content?e.content:e.text)),d("memory.recalled",{ref:e&&null!=e.id?String(e.id):null,session:t.session,turn:t.turn});return{awarded:n.length,injected:r.length}},awardImports:function(e,t={}){const r=Array.isArray(e)?e:[],n=r.slice(0,xp.IMPORT_PER_SOURCE_CAP);for(const e of n)f(e&&e.id,e&&(null!=e.content?e.content:e.text)),d("memory.imported",{ref:e&&null!=e.id?String(e.id):null,source:t.source,session:t.session});return{awarded:n.length,injected:r.length}},markGone:function(e){const t=Array.isArray(e)?e:[e];for(const e of t)null!=e&&""!==e&&u.add(String(e));return u.size},liveRefs:p,state:m,capabilities:function(e={}){return m(e).capabilities},verifyAtBoot:function(){const e=level.verifyInvariants();return level.assertCarveOuts(level.capabilities(1)),{ok:0===e.length,violations:e}}}}module.exports={LEDGER_DIR:LEDGER_DIR,LEDGER_FILE:LEDGER_FILE,avatarHome:avatarHome,ledgerPath:ledgerPath,fingerprint:fingerprint,memoryEntryId:memoryEntryId,normalizeMemoryEntry:normalizeMemoryEntry,createAvatarStore:createAvatarStore};
3
+ "use strict";const fs=require("node:fs"),path=require("node:path"),crypto=require("node:crypto"),xp=require("./xp.js"),level=require("./level.js"),personaModule=require("./persona.js"),LEDGER_DIR="avatar",LEDGER_FILE="ledger.jsonl",PERSONA_FILE="persona.json",DIGEST_CHARS=16;function avatarHome(e){return path.join(e,LEDGER_DIR)}function ledgerPath(e){return path.join(avatarHome(e),LEDGER_FILE)}function personaPath(e){return path.join(avatarHome(e),PERSONA_FILE)}function fingerprint(e){return crypto.createHash("sha1").update(String(null==e?"":e)).digest("hex").slice(0,DIGEST_CHARS)}function memoryEntryId(e){return`note-${fingerprint(`${e&&e.source||"aegis-desktop"}|${String(e&&(null!=e.content?e.content:e.text)||"").trim().toLowerCase()}`)}`}function normalizeMemoryEntry(e){if(!e||"object"!=typeof e)return e;const n="string"==typeof e.content&&e.content?e.content:"string"==typeof e.text?e.text:"";if(!n)return e;const r=Object.assign({},e);return r.content||(r.content=n),r.role||(r.role="user"),r.source||(r.source="aegis-desktop"),r.id||(r.id=memoryEntryId(r)),r}function createAvatarStore({dir:e,now:n=(()=>Date.now()),env:r=process.env,log:t=(()=>{})}={}){if(!e||"string"!=typeof e)throw new Error("createAvatarStore: a user-data directory is required");const s=ledgerPath(e),o=personaPath(e);let i=null;const a=new Map,c=new Set,l=new Map,u=new Set;function d(){try{const e=fs.statSync(s);if(i&&i.size===e.size&&i.mtimeMs===e.mtimeMs)return i.parsed;const n=xp.parseLedger(fs.readFileSync(s,"utf8"));return i={size:e.size,mtimeMs:e.mtimeMs,parsed:n},n}catch(e){return e&&"ENOENT"===e.code?{entries:[],corrupt:0}:(t(`aegis: could not read ${s}: ${e&&e.message}`),{entries:[],corrupt:0,error:e&&e.message||"unreadable"})}}function p(e,r={}){const o="number"==typeof r.t&&r.t?r.t:n();return function(e){const n=`${JSON.stringify(e)}\n`;try{return fs.mkdirSync(path.dirname(s),{recursive:!0,mode:448}),fs.appendFileSync(s,n),i&&(i={size:i.size+Buffer.byteLength(n),mtimeMs:0,parsed:{entries:i.parsed.entries.concat([e]),corrupt:i.parsed.corrupt}}),e}catch(n){return t(`aegis: could not append to ${s}: ${n&&n.message}`),i=null,e}}(xp.makeEntry(e,Object.assign({},r,{t:o}),{t:o}))}function f(){let e=null,n=!1,r=null;try{e=JSON.parse(fs.readFileSync(o,"utf8")),n=!0}catch(e){e&&"ENOENT"!==e.code&&(r=e&&e.message||"unreadable",t(`aegis: could not read ${o}: ${r}`))}const s=personaModule.validate(e);return{persona:s.persona,warnings:s.warnings?s.warnings.slice():[],exists:n,error:r,file:o}}function m(e,n){if(null==e||""===e)return"new";const r=String(e),t=fingerprint(n),s=l.get(r),o=c.has(r);return l.set(r,t),c.add(r),void 0===s?o?"same":"new":s===t?"same":"changed"}function g(){if(!c.size)return null;const e=new Set(c);for(const n of u)e.delete(n);return e}function y(e={}){const n=null==e.session?null:e.session,t=d(),o=null!=n&&a.get(n)||null,i=xp.evaluate(t.entries,{liveRefs:g(),held:o,session:n}),c=level.applyEnvOverrides(level.capabilities(i.level),e.env||r);return null!=n&&a.set(n,xp.nextHeld(i,n)),Object.assign({},i,{capabilities:c.caps,envIgnored:c.ignored,ledger:{file:s,entries:t.entries.length,corrupt:t.corrupt||0}})}return{dir:e,file:s,read:d,append:p,award:p,observe:m,awardSave:function(e={},n={}){const r=e&&null!=e.id?String(e.id):null,t=m(r,e&&(null!=e.content?e.content:e.text)),s="new"===t?"memory.saved":"changed"===t?"memory.corrected":"memory.reinforced";return{kind:s,ref:r,class:t,entry:p(s,Object.assign({ref:r,source:e&&e.source},n))}},awardQueued:function(e={},n={}){const r=e&&null!=e.id?String(e.id):null;return m(r,e&&(null!=e.content?e.content:e.text)),{kind:"memory.queued",ref:r,entry:p("memory.queued",Object.assign({ref:r,source:e&&e.source},n))}},awardRecalls:function(e,n={}){const r=Array.isArray(e)?e:[],t=r.slice(0,xp.RECALL_PER_TURN_CAP);for(const e of t)m(e&&e.id,e&&(null!=e.content?e.content:e.text)),p("memory.recalled",{ref:e&&null!=e.id?String(e.id):null,session:n.session,turn:n.turn});return{awarded:t.length,injected:r.length}},awardImports:function(e,n={}){const r=Array.isArray(e)?e:[],t=r.slice(0,xp.IMPORT_PER_SOURCE_CAP);for(const e of t)m(e&&e.id,e&&(null!=e.content?e.content:e.text)),p("memory.imported",{ref:e&&null!=e.id?String(e.id):null,source:n.source,session:n.session});return{awarded:t.length,injected:r.length}},markGone:function(e){const n=Array.isArray(e)?e:[e];for(const e of n)null!=e&&""!==e&&u.add(String(e));return u.size},liveRefs:g,state:y,capabilities:function(e={}){return y(e).capabilities},verifyAtBoot:function(){const e=level.verifyInvariants();return level.assertCarveOuts(level.capabilities(1)),{ok:0===e.length,violations:e}},readPersona:f,writePersona:function(e){const n=f(),r=personaModule.update(n.persona,e),t={...r.persona,schema:personaModule.SCHEMA_VERSION};fs.mkdirSync(path.dirname(o),{recursive:!0,mode:448});const s=`${o}.tmp-${process.pid}`;fs.writeFileSync(s,JSON.stringify(t,null,2),{mode:384}),fs.renameSync(s,o);try{fs.chmodSync(o,384)}catch{}return{...f(),warnings:(r.warnings||[]).slice(),saved:!0}}}}module.exports={LEDGER_DIR:LEDGER_DIR,LEDGER_FILE:LEDGER_FILE,avatarHome:avatarHome,ledgerPath:ledgerPath,fingerprint:fingerprint,memoryEntryId:memoryEntryId,normalizeMemoryEntry:normalizeMemoryEntry,createAvatarStore:createAvatarStore};
@@ -0,0 +1,3 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
+ "use strict";const path=require("node:path"),CLI_BIN="aegiscode",EMULATORS=Object.freeze({linux:[{cmd:"x-terminal-emulator",style:"-e"},{cmd:"gnome-terminal",style:"-e"},{cmd:"konsole",style:"-e"},{cmd:"xfce4-terminal",style:"-e"},{cmd:"mate-terminal",style:"-e"},{cmd:"lxterminal",style:"-e"},{cmd:"kitty",style:"--"},{cmd:"alacritty",style:"--"},{cmd:"xterm",style:"-e"}],darwin:[{cmd:"osascript",style:"termapp"}],win32:[{cmd:"wt.exe",style:"exec"},{cmd:"cmd.exe",style:"exec"}]}),VENDOR_FACE=Object.freeze(["vendor","faces","cli","bin",`${CLI_BIN}.js`]);function cliEntry({packaged:e,resourcesPath:t,appDir:r,entryExists:n}={}){if(e)return t?path.join(t,"faces","cli","bin",`${CLI_BIN}.js`):null;if(!r)return null;const c=path.join(r,...VENDOR_FACE);let a=!1;try{a=Boolean(n&&n(c))}catch{a=!1}return a?c:path.join(r,"..","cli","bin",`${CLI_BIN}.js`)}function isBundledEntry(e){return/[\\/]faces[\\/]cli[\\/]bin[\\/]/.test(String(e||""))}function cliArgv(e,t){const r=Array.isArray(t)?t.map(String):[];return e?[e,...r]:r}function pickEmulator({platform:e,exists:t,candidates:r}={}){const n=r||EMULATORS[e]||[];if(!n.length)return{ok:!1,reason:`no terminal emulator known for ${e||"this host"}`};for(const e of n){let r=!1;try{r=Boolean(t&&t(e.cmd))}catch{r=!1}if(r)return{ok:!0,emulator:e}}return{ok:!1,reason:`no terminal emulator found (tried ${n.map((e=>e.cmd)).join(", ")}) — run the command in the plan by hand`}}function emulatorArgv(e,t){const r=t&&t.exec||"",n=t&&t.args||[];if(!e||!r)return[];switch(e.style){case"-e":return["-e",r,...n];case"--":return["--",r,...n];case"exec":return"cmd.exe"===e.cmd?["/c","start",'""',r,...n]:[r,...n];default:return[r,...n]}}function macScript(e){return`tell application "Terminal"\n activate\n do script "${[e&&e.exec||"",...e&&e.args||[]].map((e=>shellQuote(e))).join(" ").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"\nend tell`}function shellQuote(e){const t=String(null==e?"":e);return t?`'${t.replace(/'/g,"'\\''")}'`:"''"}function plan(e){const t=e||{},r=cliEntry(t);if(!r)return{ok:!1,reason:"could not locate the aegiscode entry point for this build",command:CLI_BIN};const n=Boolean(t.packaged)||isBundledEntry(r),c={exec:n?t.execPath:t.nodePath||"node",args:cliArgv(r,t.args)},a=n?{ELECTRON_RUN_AS_NODE:"1"}:void 0,l=[c.exec,...c.args].map((e=>shellQuote(e))).join(" "),o=pickEmulator({platform:t.platform,exists:t.exists,candidates:t.candidates});return o.ok?"termapp"===o.emulator.style?{ok:!0,exec:o.emulator.cmd,args:["-e",macScript(c)],env:a,command:l}:{ok:!0,exec:o.emulator.cmd,args:emulatorArgv(o.emulator,c),env:a,command:l}:{ok:!1,reason:o.reason,command:l}}module.exports={CLI_BIN:CLI_BIN,EMULATORS:EMULATORS,VENDOR_FACE:VENDOR_FACE,cliEntry:cliEntry,isBundledEntry:isBundledEntry,cliArgv:cliArgv,pickEmulator:pickEmulator,emulatorArgv:emulatorArgv,macScript:macScript,shellQuote:shellQuote,plan:plan};
@@ -1,3 +1,3 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- "use strict";const{randomUUID:randomUUID}=require("node:crypto"),os=require("node:os"),fs=require("node:fs"),toolsModule=require("./tools.js"),attachmentsModule=require("./attachments.js"),{flattenContent:flattenContent}=attachmentsModule,promptModule=require("./prompt.js"),localTransport=require("./local.js"),{ShellSession:ShellSession}=require("./shell.js"),{planExec:planExec}=require("./exec-plan.js"),claudePro=require("./claude-pro.js"),{agentSystemPrompt:agentSystemPrompt,agentRoleLabel:agentRoleLabel}=require("./agents.js"),{beginTurnGuard:beginTurnGuard,recordWrite:recordWrite,blocksDestructive:blocksDestructive}=require("./turn-guard.js"),repeatGuard=require("./repeat-guard.js"),verifyGuard=require("./verify-stop.js"),{acquireWorktreeLock:acquireWorktreeLock,releaseWorktreeLock:releaseWorktreeLock}=require("./worktree-lock.js"),covenant=require("./covenant.js");let envFile=null;try{envFile=require("../../../client/env-file.js")}catch{try{envFile=require("../../vendor/env-file.js")}catch{envFile=null}}let platformLib=null;try{platformLib=require("../../../client/platform.js")}catch{try{platformLib=require("../../vendor/platform.js")}catch{platformLib=null}}let credentialsLib=null;try{credentialsLib=require("../../../client/credentials.js")}catch{try{credentialsLib=require("../../vendor/credentials.js")}catch{credentialsLib=null}}const PRO_TOOL_MAP=Object.freeze({Write:"writeFile",Edit:"editFile",MultiEdit:"editFile",NotebookEdit:"editFile",Bash:"exec",BashOutput:"exec"}),PRO_PLAN_MODE_SAFE=Object.freeze(new Set(["Read","Glob","Grep"]));function proAskArgs(e,t){const o=e&&"object"==typeof e?e:{};return"exec"===t?"string"==typeof o.command?{command:o.command}:{}:"writeFile"===t?"string"==typeof o.file_path?{file_path:o.file_path,content:o.content}:{}:"editFile"===t?Array.isArray(o.edits)?{file_path:o.file_path,edits:o.edits}:"string"==typeof o.file_path?{file_path:o.file_path,old_string:o.old_string,new_string:o.new_string,replace_all:!0===o.replace_all}:{}:o}function normalizeToolArgs(e,t,o,r){const n=e&&"function"==typeof e.normalizeArgs&&e.normalizeArgs||"function"==typeof toolsModule.normalizeArgs&&toolsModule.normalizeArgs||null;return n?n(t,o,r):{ok:!0,args:o&&"object"==typeof o?o:{},error:null}}function detectVcs(e){if(!e)return null;try{const t=require("node:fs"),o=require("node:path");let r=o.resolve(String(e));for(let e=0;e<8;e+=1){if(t.existsSync(o.join(r,".git")))return"git";const e=o.dirname(r);if(e===r)break;r=e}return""}catch{return null}}function hostEnv(e={},t={},o=null){const r=e||{},n=t||{},s=(e,t)=>null!=n[e]?n[e]:t;let a=r.homedir,i=r.cwd;try{a||(a=os.homedir()),i||(i=process.cwd())}catch{}let l=r.shell,c=r.shellKind;try{if(!l||!c){const e=require("./shell.js").resolveSessionShell();l=l||e.cmd,c=c||e.kind}}catch{}let d=r.desktopdir;try{!d&&platformLib&&(d=platformLib.desktopDir())}catch{}let u=r.dataDir;try{!u&&credentialsLib&&(u=credentialsLib.aegisHome())}catch{}let f=r.locale,p=r.localeName;try{!f&&platformLib&&"function"==typeof platformLib.appLocale&&(f=platformLib.appLocale()),f&&!p&&platformLib&&"function"==typeof platformLib.languageName&&(p=platformLib.languageName(f))}catch{}return{platform:s("platform",r.platform||process.platform),arch:s("arch",r.arch||process.arch),homedir:s("homedir",a),desktopdir:s("desktopdir",d),dataDir:s("dataDir",u),locale:s("locale",f),localeName:s("localeName",p),languages:s("languages",r.languages),cwd:s("cwd",i),vcs:s("vcs",null!=r.vcs?r.vcs:detectVcs(i)),shell:s("shell",l),shellKind:s("shellKind",c),roots:s("roots",r.roots),appVersion:s("appVersion",r.appVersion),model:s("model",o&&o.model)}}function requireSharedBrain(){const e=[()=>require("../../../client/brain-catalog.js"),()=>require("../../vendor/brain-catalog.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}function requireSharedByokCatalog(){const e=[()=>require("../../../client/byok-catalog.js"),()=>require("../../vendor/byok-catalog.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}function requireSharedUserModels(){const e=[()=>require("../../../client/user-models.js"),()=>require("../../vendor/user-models.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}function requireSharedCatalogClient(){const e=[()=>require("../../../client/catalog-client.js"),()=>require("../../vendor/catalog-client.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}function requireSharedModelDiscovery(){const e=[()=>require("../../../client/model-discovery.js"),()=>require("../../vendor/model-discovery.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}const WORKTREE_LOCK_WAIT_MS=1500,MAX_SUBAGENT_DEPTH=4,CLASSES=[{class:"aegis",label:"Aegis Cloud",kind:"cloud"},{class:"byok",label:"Bring your own key",kind:"cloud"},{class:"local",label:"Local model",kind:"local"},{class:"pro",label:"Claude Code Pro",kind:"subscription"}],BYOK_NAMESPACE_PREFIX="byok:";function byokNamespace(e){return`${BYOK_NAMESPACE_PREFIX}${e}`}function splitByokModel(e){const t="string"==typeof e?e:"",o=t.indexOf(":");return o<0?{provider:"",model:t}:{provider:t.slice(0,o),model:t.slice(o+1)}}function providerKeyRecord(e){const t={key:"",env:"",rejected:null};if(!envFile||"function"!=typeof envFile.providerKeyFromEnv)return t;try{const o=envFile.providerKeyFromEnv(e)||t;return{key:"string"==typeof o.key?o.key:"",env:"string"==typeof o.env?o.env:"",rejected:"string"==typeof o.rejected&&o.rejected?o.rejected:null}}catch{return t}}function providerKeyFromEnv(e){if(!envFile||"function"!=typeof envFile.providerKeyFromEnv)return"";try{return envFile.providerKeyFromEnv(e).key||""}catch{return""}}const DEEPSEEK_REASONING_MODEL_RE=/^deepseek-(v4(\.\d+)?-(flash|pro)|flash|pro|reasoner)$/,EFFORT_TOKEN_BUDGET={low:8192,medium:16384,high:32768,max:32768},DEEPSEEK_EFFORT={low:"low",medium:"high",high:"high"},DEEPSEEK_EFFORT_EXTRA={max:"max"},EFFORT_IDENTITY={low:"low",medium:"medium",high:"high"},EFFORT_INERT_RE=/non-reasoning/i,EFFORT_DIALECTS=[{provider:"deepseek",re:DEEPSEEK_REASONING_MODEL_RE,field:"effort",map:DEEPSEEK_EFFORT,extra:DEEPSEEK_EFFORT_EXTRA},{provider:"openai",re:/^(gpt-5|o[0-9])/i,field:"reasoning_effort",map:EFFORT_IDENTITY},{provider:"groq",re:/^(openai\/gpt-oss|qwen\/qwen3)/i,field:"reasoning_effort",map:EFFORT_IDENTITY},{provider:"xai",re:/^grok-(4\.[5-9]|[5-9])/,field:"reasoning_effort",map:EFFORT_IDENTITY},{provider:"google",re:/^gemini-(2\.5|3|[4-9])/,field:"reasoning_effort",map:{...EFFORT_IDENTITY,medium:"high"}}],AUTONOMOUS_IDLE_TIMEOUT_MS=9e5;function reasoningBudget(e,t,o){const r=Number(t);return Number.isFinite(r)&&r>0?r:DEEPSEEK_REASONING_MODEL_RE.test(String(e||""))?EFFORT_TOKEN_BUDGET["low"===o||"medium"===o||"max"===o?o:"high"]:void 0}function nativeEffort(e,t,o){const r=String(t||"");if(EFFORT_INERT_RE.test(r))return;if(null===o)return;const n="low"===o||"medium"===o?o:"max"===o?"max":"high";for(const t of EFFORT_DIALECTS)if(t.provider===e&&t.re.test(r)){const e=Object.prototype.hasOwnProperty.call(t.map,n)?t.map[n]:t.extra&&Object.prototype.hasOwnProperty.call(t.extra,n)?t.extra[n]:void 0;if(void 0===e)return;return{field:t.field,level:e}}}function normalizeCatalog(e){return Array.isArray(e)?e.map((e=>"string"==typeof e?{id:e}:e)).filter((e=>e&&e.id)):[]}const{offerableCatalog:offerableCatalog}=requireSharedBrain(),{withByokAdditions:withByokAdditions,canonicalModelId:canonicalModelId,nexusFallbackModel:nexusFallbackModel}=requireSharedByokCatalog(),{withUserModels:withUserModels,unmatchedUserProviders:unmatchedUserProviders,load:loadUserModels,addUserModel:addUserModel,removeUserModel:removeUserModel}=requireSharedUserModels(),{withCatalog:withCatalog}=requireSharedCatalogClient(),{discoverModels:discoverVendorModels,canDiscover:canDiscoverVendorModels,endpointFor:vendorEndpointFor,discoverableProviders:discoverableProviders}=requireSharedModelDiscovery();function parseArgs(e){if(null==e)return{};if("object"==typeof e)return e;try{const t=JSON.parse(String(e));return t&&"object"==typeof t?t:{}}catch{return{}}}function extractToolCalls(e){if(!e)return[];if(Array.isArray(e.toolCalls)&&e.toolCalls.length)return e.toolCalls.map((e=>({id:e.id||"",name:e.name||"",args:parseArgs(e.args)}))).filter((e=>e.name));const t=e.choices&&e.choices[0]&&e.choices[0].message,o=t&&t.tool_calls||[];return Array.isArray(o)?o.map((e=>{const t=e&&e.function||{};return{id:e&&e.id||"",name:t.name||e&&e.name||"",args:parseArgs(t.arguments)}})).filter((e=>e.name)):[]}function proTurnPrompt(e){const t=Array.isArray(e.prompt)?flattenContent(e.prompt):e.prompt;if("string"==typeof t&&t.trim())return t;const o=Array.isArray(e.messages)?e.messages:[];for(let e=o.length-1;e>=0;e-=1){const t=o[e];if(!t||"user"!==t.role)continue;const r=flattenContent(t.content);if(r.trim())return r}return t}function assistantText(e){const t=e&&e.choices&&e.choices[0]&&e.choices[0].message;return t&&"string"==typeof t.content&&t.content||""}function finishReasonOf(e){const t=e&&e.choices&&e.choices[0];return t&&t.finish_reason||e&&e.stop_reason||""}function isTruncated(e){const t=finishReasonOf(e);return"length"===t||"max_tokens"===t}function reasoningTextOf(e){if(!e)return"";const t=e.choices&&e.choices[0],o=t&&t.message||{};if(Array.isArray(o.content)){const e=o.content.filter((e=>e&&("thinking"===e.type||"reasoning"===e.type))).map((e=>e.thinking||e.text||"")).join("");if(e)return e}const r=o.content&&"object"==typeof o.content?o.content.reasoning_content:"",n=[o.reasoning_content,o.reasoning,t&&t.reasoning_content,e.reasoning_content,e.reasoning,r];for(const e of n)if("string"==typeof e&&e)return e;return""}function reasoningTokensOf(e){if(!e)return 0;const t=e.choices&&e.choices[0],o=t&&t.message||{},r=e.usage||{},n=r.completion_tokens_details||r.output_tokens_details||{},s=[o.thinking_tokens,o.reasoning_tokens,t&&t.thinking_tokens,e.thinking_tokens,n.reasoning_tokens,n.thinking_tokens];for(const e of s)if("number"==typeof e&&Number.isFinite(e)&&e>0)return e;return 0}function reasonedButSilent(e){return!assistantText(e)&&(""!==reasoningTextOf(e)||reasoningTokensOf(e)>0)}const REASONING_RETRY_FLOOR=32768;function retryBudgetFor(e,t){const o=doubledBudget(e.maxTokens);return t&&ladderRung(e.maxTokens)?Math.max(o,REASONING_RETRY_FLOOR):o}function ladderRung(e){const t=Number(e);return Number.isFinite(t)&&Object.values(EFFORT_TOKEN_BUDGET).includes(t)}function doubledBudget(e){const t=Number(e)||0;return t>0?2*t:8192}function statedCapOf(e){const t=e=>{const t=Number(e);return Number.isFinite(t)&&t>0?t:void 0};return e&&Object.prototype.hasOwnProperty.call(e,"statedMaxTokens")?t(e.statedMaxTokens):t(e&&e.maxTokens)}const EMPTY_TURN_NUDGE="Your previous reply came back empty — it contained no answer and no tool call. Write your answer now, using only the information already gathered above. No tools are available in this reply, so do not call any: respond in plain prose or markdown.",THOUGHT_ONLY_NUDGE="Your previous round was spent entirely on hidden reasoning and produced no visible reply. Answer the user directly and briefly now. Do not reason, explain, or think first — write only the answer, no tools.",FINAL_ANSWER_NUDGE="Write your answer now, in plain prose, using only what is already in this conversation. If your information is incomplete, say what you have and what is missing — an incomplete answer is the expected outcome here and is better than none. No tools, no preface.",RECOVERY_ROUNDS=2,UNMUTATED_TURN_NUDGE="You ended the turn without changing any file, but this request asked for a change. The tools are still available in this reply: make the edit now with editFile or writeFile. If you already know what to change, change it — describing the fix is not the fix. If you genuinely cannot, say precisely what blocks you.",MUTATION_INTENT_RE=new RegExp("\\b(?:fix|implement|add|create|write|refactor|rename|remove|delete|replace|update|patch|migrate|convert|make\\s+(?:it|them|this|that|the|sure)|change|correct|resolve|repair|address|apply|introduce|support|wire\\s+up)\\b","i");function wantsMutation(e,t,o){if(t)return!1;if(!(o>0))return!1;const r=String(e||"");return!!r.trim()&&!/\?\s*$/.test(r.trim())&&MUTATION_INTENT_RE.test(r)}function emptyTurnError({cls:e,model:t,finishReason:o,reasoningChars:r,reasoningTokens:n,effort:s,recoveryRounds:a}){const i=Number(a)||0,l=Number(n)||0,c=new Error(`The model returned no answer after ${e}/${t} was asked to summarise its results`+(i?`, and ${i} extra recovery call${1===i?"":"s"} with a larger budget and a changed ask came back empty too`:"")+` (stop reason: ${o||"none"}`+(s?`, effort: ${s}`:"")+(r?`, hidden reasoning: ${r} chars and no visible text`:l>0?`, ~${l} thinking tokens billed and no visible text`:"")+"). "+(r||l>0?"Every one of those calls spent its output on hidden reasoning instead of writing a word, so this is the model rather than the budget: pick a model that answers without a thinking pass, or ask for a smaller piece of work.":"No visible text came back from any of those calls. Send the request again, in smaller pieces, or from a different model."));return c.status=502,c}function createLocalEngine({aegis:e,settings:t,tools:o,promptBuilder:r,recallProvider:n,env:s,getConfirmMode:a,getPermissionMode:i,sandbox:l,localTransport:c=localTransport,fetchImpl:d,gitScope:u,permissionRules:f}){const p=new Map,m=o||toolsModule,h=r&&r.buildSystemPrompt||promptModule.buildSystemPrompt,g=f&&"function"==typeof f.rulesVerdict?f.rulesVerdict:null,y=f&&"function"==typeof f.alwaysAllow?f.alwaysAllow:null,k=f&&"function"==typeof f.subjectFor?f.subjectFor:null,v=require("./session-rounds.js"),b=()=>{if("function"==typeof a)return!1!==a();if(t&&"function"==typeof t.getConfirmMode){const e=t.getConfirmMode();return void 0===e||Boolean(e)}return!0},w=()=>"function"==typeof i?"plan"===i():!(!t||"function"!=typeof t.getPermissionMode)&&"plan"===t.getPermissionMode();function E(e,t){return`${e} was not executed — this session is in plan mode (read-only). Plan mode may read files, search, run read-only shell commands and deploy subagents to research, but may not create, edit or delete files, run a mutating command, or install packages`+(t?` (this command: ${t})`:"")+". Do NOT retry it or attempt the same effect by another route. Finish your research and present a plan in plain text; the user exits plan mode (`/permissions mode off`) before any edit can run."}const _=new Map,T=new Map,S=new Map,x=200,A=new Map,M=require("./pro-sessions.js"),O=new Map,N=new Map;function F(e,t){if("function"!=typeof k)return e;let o="";try{o=String(k(e,t||{})||"")}catch{o=""}return`${e}\0${o}`}function R(e,t,o){_.has(e)||_.set(e,new Set),_.get(e).add(F(t,o))}function D(e,t){const o=T.get(e);return Boolean(o&&o.has(t))}function U(e,t){T.has(e)||T.set(e,new Set),T.get(e).add(t)}function I(e){if(!e)return null;try{return{existed:!0,content:fs.readFileSync(e,"utf8")}}catch(e){return e&&"ENOENT"===e.code?{existed:!1,content:null}:null}}function L(e){return`${e} was not executed — the user denied this tool for this conversation. Do NOT retry it and do NOT attempt the same effect by another route (another command, a writeFile instead of an edit, a subagent). Stop calling tools and reply in plain text: say what you were trying to do, what you need, and that the user can re-enable ${e} to let it proceed.`}function C(e,t,o,r){return new Promise((n=>{if(o&&o.aborted)return void n("cancel");const s=randomUUID();let a=!1;const i=()=>l("cancel"),l=e=>{a||(a=!0,O.delete(s),o&&o.removeEventListener("abort",i),n(e))};o&&o.addEventListener("abort",i,{once:!0}),O.set(s,{resolve:l}),"function"==typeof t?t({delta:"",approval:{id:s,sessionId:e,tool:r.tool,args:r.args,diff:r.diff||null,canPersist:"function"==typeof y}}):l("cancel")}))}function P(e,t,o,r){return new Promise((n=>{if(o&&o.aborted)return void n(!1);const s=randomUUID();let a=!1;const i=()=>l(!1),l=e=>{a||(a=!0,N.delete(s),o&&o.removeEventListener("abort",i),n(e))};o&&o.addEventListener("abort",i,{once:!0}),N.set(s,{resolve:l}),"function"==typeof t?t({delta:"",rounds:{id:s,sessionId:e,spent:r.spent,extensions:r.extensions,max:r.max,size:r.size}}):l(!1)}))}async function $(e,t,o,r,n){const s=normalizeToolArgs(m,e,t,o||{});if(!s.ok)return{ok:!1,error:s.error};t=s.args;const a=o&&o.guard;if(a&&"exec"===e){const e=blocksDestructive(a,t&&t.command);if(!e.ok)return{ok:!1,error:e.reason}}const i=o&&o.repeat,l=i?repeatGuard.check(i,e,t):null;if(l&&"refuse"===l.action)return{ok:!1,error:l.error};const c=covenant.preActionAssert({tool:e,args:t||{}});if(!c.allowed){const o=covenant.bindRefusal({tool:e,args:t||{}},c);return{ok:!1,error:`refused by the ÆGIS covenant — ${c.clause} (${c.label}): ${c.reason}`,covenant:o}}const d="writeFile"===e||"editFile"===e,u=d?I(t&&t.file_path):null,f=await m.executeTool(e,t,o);a&&d&&f&&!1!==f.ok&&recordWrite(a,t&&t.file_path),i&&d&&f&&!1!==f.ok&&repeatGuard.recordWrite(i,t&&t.file_path);const p=o&&o.verify;if(p&&(verifyGuard.EXEC_TOOLS.has(e)&&f&&!1!==f.ok?verifyGuard.recordExec(p):d&&f&&!1!==f.ok&&verifyGuard.recordMutation(p,t&&t.file_path)),d&&u&&f&&!1!==f.ok){const o=I(t&&t.file_path);o&&function(e,t){if(!e)return;S.has(e)||S.set(e,[]);const o=S.get(e);o.push(t),o.length>x&&o.shift()}(r,{id:n||randomUUID(),tool:e,path:t&&t.file_path,before:u,after:o,at:Date.now()})}return l&&l.note?j(f,l.note):f}function j(e,t){if(!e||"object"!=typeof e)return{ok:!0,content:`${t}\n${null==e?"":e}`};if(!1===e.ok||!0===e.isError){const o=e.error||e.content||"";return{...e,error:`${t}\n${o}`,content:`${t}\n${o}`}}const o=null!=e.content?e.content:null!=e.output?e.output:"";return{...e,content:`${t}\n${o}`}}async function q(e,{toolCtx:t,rootSessionId:o,rootOnDelta:r,signal:n}){const{name:s}=e,a=normalizeToolArgs(m,s,e.args,t||{});if(!a.ok)return{ok:!1,error:a.error};const i=a.args;if(!m.MUTATING_TOOLS.has(s))return $(s,i,t,o,e.id);if(w()){if("exec"===s){const r=planExec(i&&i.command,{baseCwd:t&&t.cwd||void 0});return r.oneShot?$(s,i,t,o,e.id):{ok:!1,error:E(s,r.reason)}}return{ok:!1,error:E(s)}}if(!b())return $(s,i,t,o,e.id);if(function(e,t,o){const r=_.get(e);return Boolean(r&&r.has(F(t,o)))}(o,s,i))return $(s,i,t,o,e.id);if("function"==typeof g){let r;try{r=g(s,i)}catch(e){r={verdict:null,source:"error",error:e&&e.message||String(e)}}if(r&&"deny"===r.verdict)return U(o,s),{ok:!1,error:L(s),permissionRule:r.rule||null};if(r&&"allow"===r.verdict)return $(s,i,t,o,e.id)}if(D(o,s))return{ok:!1,error:L(s)};let l=null;if(("writeFile"===s||"editFile"===s)&&(l=m.previewMutation(s,i,t||{}),!l.ok))return{ok:!1,error:l.error};const c=await C(o,r,n,{tool:s,args:i,diff:l&&l.diff});if("deny"===c)return U(o,s),{ok:!1,error:L(s)};if("session"!==c&&"once"!==c&&"always"!==c)return{ok:!1,error:`${s} was not executed — the request was cancelled.`};let d=null;if("always"===c){let e=null;if("function"==typeof y)try{e=y(s,i)}catch(t){e={ok:!1,reason:t&&t.message||String(t)}}else e={ok:!1,reason:"no durable store is wired on this host"};d=e&&e.ok?`[permission_rule] stored ${e.rule} — this command will not ask again`:`[permission_rule] nothing was stored — ${e&&e.reason||"unknown reason"}; this call was allowed once only`}if("session"===c&&R(o,s,i),l){const e=m.applyChecked(s,i,l,t||{});return e&&!1!==e.ok&&t&&t.guard&&recordWrite(t.guard,i&&i.file_path),d?j(e,d):e}const u=await $(s,i,t,o,e.id);return d?j(u,d):u}function B(e){return hostEnv(s||{},e&&e.env||{},e)}function K(e){const t=[],o=e=>String(e||"").replace(/[\\/]+$/,""),r=o(e),n=e=>{const n=o(e);n&&n!==r&&!t.includes(n)&&t.push(n)};let s=u;if(void 0===s)try{s=require("./git-scope.js")}catch{s=null}try{s&&"function"==typeof s.gitRoot&&n(s.gitRoot(e))}catch{}try{credentialsLib&&"function"==typeof credentialsLib.aegisHome&&n(credentialsLib.aegisHome())}catch{}return t}async function G(t,o){if("aegis"===t){const t=!o.singlePass&&(!!o.autonomous||void 0);return e.chatCompletion({prompt:o.prompt,system:o.system,messages:o.messages,model:o.model,mode:o.mode,maxTokens:o.statedMaxTokens,stream:!1!==o.stream,includeUsage:!0,onStream:o.onDelta,onReasoning:o.onReasoning,idleTimeoutMs:o.idleTimeoutMs,signal:o.signal,extra:{aegis_recall:!0,...o.recallDeep?{aegis_recall_deep:!0}:{},session:o.sessionId,...void 0===t?{}:{brain:t},...!1===t?{mode:"brain"}:{},...o.effort?{effort:o.effort}:{},...!0===t&&o.workers?{workers:o.workers}:{},...o.tools.length?{tools:o.tools}:{},...o.toolChoice?{tool_choice:o.toolChoice}:{}},agentKey:o.tools.length&&(process.env.AEGIS_AGENT_KEY||"").trim()||void 0})}if("byok"===t){const{provider:t,model:r}=splitByokModel(o.model),n=canonicalModelId(t,r),s=nativeEffort(t,n,o.effort);try{return await e.byokChatCompletion({provider:t,model:n,providerKey:o.apiKey,baseURL:o.cfg&&o.cfg.baseURL,prompt:o.prompt,system:o.system,messages:o.messages,maxTokens:o.maxTokens,tools:o.tools,toolChoice:o.toolChoice,effort:s&&"effort"===s.field?s.level:void 0,reasoningEffort:s&&"reasoning_effort"===s.field?s.level:void 0,stream:!0,onStream:o.onDelta,signal:o.signal})}catch(e){if(e&&402===e.status){const e=new Error("byok: this account has no AEGIS balance left, and the BYOK handling fee is billed there — your provider key is still valid, this is not a key problem. Top up the account, then try again (or /class aegis to use the pooled lane).");throw e.status=402,e}throw e}}if("local"===t){const e=o.cfg&&o.cfg.baseURL||c.DEFAULT_BASE,t=t=>c.chat({baseURL:e,model:o.model,prompt:o.prompt,system:o.system,messages:o.messages,maxTokens:o.maxTokens,signal:o.signal,onDelta:o.onDelta,...t&&o.tools.length?{tools:o.tools,toolChoice:o.toolChoice}:{}});try{return await t(!0)}catch(e){if(o.tools.length&&e&&400===e.status)return t(!1);throw e}}if("pro"===t){const e=o.sessionKey||o.rootSessionId||o.sessionId;let t=null;if(e&&(t=A.get(e)||null,!t)){try{t=M.get(e,s)||null}catch{}t&&A.set(e,t)}const r=K(o.cwd),n=e=>claudePro.runClaudePro({prompt:proTurnPrompt(o),model:o.model&&"default"!==o.model?o.model:void 0,system:o.system,cwd:o.cwd,addDir:r,resumeSessionId:e||void 0,gate:b(),onAsk:async e=>{if(!e||!e.requestId)return"deny";const t=o.rootSessionId,r=o.rootOnDelta,n=PRO_TOOL_MAP[String(e.toolName||"")]||null,s=n||String(e.toolName||"unknown"),a=proAskArgs(e.input||{},s),i=covenant.preActionAssert({tool:s,args:a});if(!i.allowed)return r&&r({delta:"",note:`aegis: refused by the ÆGIS covenant — ${i.clause} (${i.label}): ${i.reason}`}),"deny";if(w()){if("exec"===s){const e=planExec(a&&a.command,{baseCwd:o.cwd||void 0});return e.oneShot?"once":(r&&r({delta:"",note:E(s,e.reason)}),"deny")}if(n&&m.MUTATING_TOOLS.has(s))return r&&r({delta:"",note:E(s)}),"deny";if(!n&&!PRO_PLAN_MODE_SAFE.has(s))return r&&r({delta:"",note:E(s)}),"deny"}if(!b())return"once";if("function"==typeof g){let e;try{e=g(s,a)}catch{e=null}if(e&&"deny"===e.verdict)return r&&r({delta:"",note:L(s)}),"deny";if(e&&"allow"===e.verdict)return"once"}if(D(t,s))return r&&r({delta:"",note:L(s)}),"deny";const l=await C(t,r,o.signal,{tool:s,args:a,diff:null});if("deny"===l)return U(t,s),"deny";if("session"!==l&&"once"!==l&&"always"!==l)return"deny";if("session"===l&&R(t,s,a),"always"===l&&"function"==typeof y)try{y(s,a)}catch{}return l},signal:o.signal,onDelta:o.onDelta,onSpawn:(e,t)=>{o.onDelta&&t&&o.onDelta({delta:"",note:claudePro.childLine(t)})}});let a=await n(t);if(a&&a.resumeStale){A.delete(e);try{M.del(e,s)}catch{}o.onDelta&&o.onDelta({delta:"",note:"aegis: the remembered Claude session no longer exists on this machine — continuing as a new conversation (earlier turns are not in its context)"}),a=await n(null)}if(e&&a&&a.sessionId&&!a.error){A.set(e,a.sessionId);try{M.set(e,a.sessionId,s)}catch{}}return a}throw new Error(`dispatch: unknown model class ${JSON.stringify(t)} — this build ships 'aegis', 'byok', 'local' and 'pro' only`)}async function Y(o,r){const n=o&&o.class,s=o&&o.model,a=reasoningBudget("byok"===n?splitByokModel(s).model:s,o&&o.maxTokens,o&&o.effort),i=statedCapOf(o),d="aegis"===n&&Boolean(o&&o.autonomous),u=Boolean(o&&o.roundsAsk),f=o&&o.sessionId||randomUUID(),g=Number.isInteger(o&&o.depth)?o.depth:0,y=o&&o.rootSessionId||f,k=o&&o.rootOnDelta||r,b="function"==typeof r?e=>e&&r({reasoning:e}):void 0,w=new AbortController,E=p.get(f)||null;p.set(f,w);const _=w.signal,T=!(o&&!1===o.tools),S=T?m.toolsFor({includeSubagent:g<4}):[],x=o&&o.toolChoice||null,A=o&&o.system||h(B(o)),M=Array.isArray(o&&o.messages)?o.messages.filter(Boolean).slice():[];let O=M.length,N=o&&o.prompt||"";const F=String(N||""),R=Array.isArray(o&&o.attachments)?o.attachments.filter((e=>e&&"object"==typeof e)).slice(0,attachmentsModule.MAX_ATTACHMENTS):[];let D=R.length?attachmentsModule.buildContent(N,R):N,U=null;const I=B(o),L=((e,t)=>{if(null==l)return null;const o="function"==typeof l.policy?l.policy():l.policy;if(!o)return null;const r=require("./sandbox.js"),n=e&&e.cwd||process.cwd(),s=r.normalize(o,n);if("off"===s.mode)return null;let a=[];try{let e=null;try{e=require("node:os").homedir()}catch{e=null}a=r.autoGrants(n,{home:e,addDirs:(()=>{try{return K(n)}catch{return[]}})()})}catch{a=[]}if(a.length){const e=new Set;for(const t of s.fileSystem.entries)t&&t.path&&"path"===t.path.type&&t.path.path&&e.add(`${t.access}:${t.path.path}`);for(const t of a){const o=`${t.access}:${t.path.path}`;e.has(o)||(e.add(o),s.fileSystem.entries.push(t))}}return"local"===t&&"restricted"===s.network&&(s.network="open",s.networkExempt="local"),{policy:s,state:l.state||r.detect({appDir:l.appDir}),workspace:n,appDir:l.appDir,strict:!0===l.strict}})(I,n),C=I.cwd,$={getShell:()=>U||(U=new ShellSession({cwd:I.cwd,sandbox:L})),signal:_,cwd:C,desktopdir:I.desktopdir,sandbox:L,repeat:repeatGuard.beginRepeatGuard({cwd:C}),verify:verifyGuard.beginVerifyGuard({cwd:C}),guard:beginTurnGuard(C)};try{const l="byok"===n?splitByokModel(s):null;let p=null;const h="byok"===n?t.get(byokNamespace(l.provider))||{}:"local"===n&&t.get("local")||{},w="byok"===n?t.rawKey(byokNamespace(l.provider)):null,E="byok"!==n?null:w||providerKeyFromEnv(l.provider);if(!("byok"!==n||l.provider&&l.model)){const e=new Error('byok: model must be "<provider>:<model>" (pick one from /models) — got '+JSON.stringify(s||""));throw e.status=400,e}if("byok"===n&&!E){const t="anthropic"===l.provider?claudePro.claudeProStatus({env:process.env}):null,o=providerKeyRecord(l.provider).rejected,r=nexusFallbackModel({provider:l.provider,providerKey:E,providerKeyRefused:o,aegisKey:E?"":e.apiKey});if(!r){const e=new Error(o?`${o}. That is why this turn has no ${l.provider} key: an env value that short is a paste that lost its payload, not a credential. Fix ${o.split(" ")[0]} in ~/.aegiscode/.env (or the shell that exported it) — or skip keys entirely: /byok-key ${l.provider} <key> to set one here.`:t&&t.loggedIn?`No Anthropic API key on this machine — an "anthropic:…" id is served by your own console key, which a Claude subscription is not. Use the subscription instead: /class pro (it spends your Claude Code ${t.subscription||"Pro"} plan through the claude CLI) — or add a real console key: /byok-key anthropic <key>.`:`No key for "${l.provider}" yet. Easiest fix: /class aegis (uses your AEGIS key, no setup) — or add this provider's own key: /byok-key ${l.provider} <key>.`);throw e.status=400,e}p={from:l.provider,model:r}}if("byok"===n&&!e.apiKey){const e=new Error("No AEGIS key connected yet. Easiest fix: /class aegis (skips BYOK entirely) — or add your AEGIS key with /login, then try again.");throw e.status=401,e}if("local"===n){const e=c.remoteRefusal(h.baseURL||c.DEFAULT_BASE);if(e)throw e}if("byok"===n&&"custom"===l.provider&&!(h.baseURL||"").trim()){const e=new Error('No endpoint saved for the "custom" provider — its key is on this machine but the address it dials is not, and no default exists for a vendor AEGIS does not know. Fix: /model-add custom <https-base-url> <api-key> <model-id> (writes both halves), or the endpoint field in Settings › Provider (custom).');throw e.status=400,e.code="custom_endpoint_missing",e}const U=p?"aegis":n,I={cls:U,model:p?p.model:s,mode:o&&o.mode,maxTokens:a,statedMaxTokens:i,autonomous:d,sessionId:f,signal:_,onDelta:r,cfg:h,apiKey:E,toolChoice:x,pooledFrom:p?p.from:void 0,cwd:C,rootSessionId:y,sessionKey:o&&o.sessionKey||void 0,rootOnDelta:k,effort:o&&o.effort,workers:o&&o.workers,recallDeep:o&&!0===o.recallDeep,singlePass:o&&!0===o.singlePass,onReasoning:b,idleTimeoutMs:d?9e5:void 0,stream:!o||!1!==o.stream};let L=!1,j=!1;const B=d?"AEGIS_AUTONOMOUS_MAX_ROUNDS":"AEGIS_CHAT_MAX_ROUNDS",K=(()=>{const e=Number.parseInt(process.env[B]||"",10);return Number.isFinite(e)&&e>0?e:0})(),Y=K||(d?40:24);let z=v.keyFor(o,M),V=v.take(z);if(!V&&!v.isStatedKey(o)){const e=v.adopt();e&&(V=e.entry,z=e.key)}if(V){const e=v.resumePreamble(V);0===M.length?Array.isArray(V.messages)&&V.messages.length&&M.push(...V.messages):Array.isArray(V.added)&&V.added.length&&M.push(...V.added),N?(N=`${e}\n\n${N}`,D=R.length?attachmentsModule.buildContent(N,R):N):(M.push({role:"user",content:e}),D=""),k&&k({delta:`\n\n[resuming work this session left unfinished at ${V.rounds} tool rounds`+(V.interruptions>1?` (cut off ${V.interruptions}×)`:"")+"…]\n"})}let H=K||Y+(V?v.bonus(Y):0),X=0;const J=Y,Q=8;let Z=0;const ee={calls:0},te=["input_tokens","output_tokens","prompt_tokens","completion_tokens","total_tokens","cache_read_input_tokens","cache_creation_input_tokens","prompt_cache_hit_tokens","prompt_cache_miss_tokens","reasoning_tokens","thinking_tokens"],oe=e=>{const t=e&&e.usage;if(t&&"object"==typeof t){ee.calls+=1;for(const e of te)"number"==typeof t[e]&&Number.isFinite(t[e])&&(ee[e]=(ee[e]||0)+t[e]);if("number"!=typeof t.total_tokens){const e=(t.prompt_tokens??t.input_tokens??0)+(t.completion_tokens??t.output_tokens??0);e&&(ee.total_tokens=(ee.total_tokens||0)+e)}}},re=e=>{if(!e||"object"!=typeof e)return e;const t=p?{...e,pooled_from:p.from,pooled_model:p.model,pooled_notice:requireSharedByokCatalog().nexusFallbackNotice({pooled_from:p.from,pooled_model:p.model})}:e;return ee.calls?{...t,usage:{...ee}}:t},ne=()=>{if(""===D)return;const e=M[M.length-1],t=e&&"user"===e.role?flattenContent(e.content):null;e&&"user"===e.role&&t===flattenContent(D)||M.push({role:"user",content:D}),N="",D=""};O=M.length;const se=m&&m.MUTATING_TOOLS||new Set;let ae=0,ie=0,le=!1,ce=!1;for(;;){if(X>=H){if(u&&Z<Q&&!_.aborted&&await P(y,k,_,{spent:H,extensions:Z+1,max:Q,size:J})){Z+=1;const e=H;H+=J,M.push({role:"user",content:`You have used all ${e} tool rounds allowed for this turn; ${J} more have been granted (do not restart). Continue the task from exactly where you stopped — do not re-plan, do not repeat work already done, and finish with an answer.`});continue}const e=u?"":`, or raise ${B} for a longer single turn`,t=`[stopped at ${H} tool rounds`+(ee.total_tokens?`, ${ee.total_tokens.toLocaleString()} tokens`:"")+". This session holds the work: your next message here resumes it automatically"+` (with a continuation preamble)${e}.]`,o=v.record(z,{rounds:X,tokens:ee.total_tokens||0,note:t,chain:V?V.interruptions:0,messages:M,added:M.slice(O)});return k&&k({delta:`\n\n${t}`}),re({model:I.model,choices:[{message:{content:t},finish_reason:"length"}],stoppedOnRounds:!0,heldForSession:!0,heldRounds:o.rounds,sessionInterruptions:o.interruptions,resumedFrom:z})}X+=1;const e={...I,system:A,messages:M,prompt:D,tools:S,recallDeep:I.recallDeep&&1===X};let t;if(t=await G(U,e),oe(t),_.aborted)return re(t);if(!L&&!assistantText(t)&&(isTruncated(t)||reasonedButSilent(t))){L=!0;const o=reasonedButSilent(t);if(t=await G(U,{...e,singlePass:!0,recallDeep:!1,effort:o?"high":e.effort,maxTokens:retryBudgetFor(e,o),statedMaxTokens:e.statedMaxTokens?doubledBudget(e.statedMaxTokens):void 0}),oe(t),_.aborted)return re(t)}const a=S.length?extractToolCalls(t):[];if(!a.length){if(assistantText(t)||j||!T){if(!le&&T&&wantsMutation(F,ie>0,ae)){le=!0,ne(),M.push({role:"assistant",content:assistantText(t)}),M.push({role:"user",content:UNMUTATED_TURN_NUDGE}),k&&k({delta:""});continue}if($.verify&&!ce){const e=verifyGuard.shouldNudge($.verify);if(e.nudge){ce=!0,ne(),M.push({role:"assistant",content:assistantText(t)}),M.push({role:"user",content:e.text}),k&&k({delta:""});continue}}return re(t)}j=!0,ne(),M.push({role:"user",content:reasonedButSilent(t)?THOUGHT_ONLY_NUDGE:EMPTY_TURN_NUDGE});const o={...e,singlePass:!0,recallDeep:!1,messages:M,prompt:"",tools:[]};t=await G(U,o);let r=o.maxTokens,a=o.effort;if(oe(t),_.aborted)return re(t);if(!assistantText(t)&&(isTruncated(t)||reasonedButSilent(t))){const e=reasonedButSilent(t);if(r=retryBudgetFor(o,e),a=e?"high":o.effort,t=await G(U,{...o,effort:a,maxTokens:r,statedMaxTokens:o.statedMaxTokens?doubledBudget(o.statedMaxTokens):void 0}),oe(t),_.aborted)return re(t)}const i=(()=>{const e=Number(r)||0;if(!e)return r;const t={maxTokens:r};return o.statedMaxTokens&&(t.statedMaxTokens=o.statedMaxTokens),Math.max(e,retryBudgetFor(t,!0))})();let l=0;for(;!assistantText(t)&&l<2&&!_.aborted;){const e=reasonedButSilent(t);if(l+=1,M.push({role:"user",content:e?1===l?THOUGHT_ONLY_NUDGE:FINAL_ANSWER_NUDGE:EMPTY_TURN_NUDGE}),e&&(a="high"),r=i,t=await G(U,{...o,messages:M,effort:a,maxTokens:r,statedMaxTokens:o.statedMaxTokens?doubledBudget(o.statedMaxTokens):void 0}),oe(t),_.aborted)return re(t)}if(!assistantText(t))throw emptyTurnError({cls:n,model:s,effort:a,recoveryRounds:l,finishReason:finishReasonOf(t),reasoningChars:reasoningTextOf(t).length,reasoningTokens:reasoningTokensOf(t)});return re(t)}ne(),M.push({role:"assistant",content:assistantText(t),tool_calls:a.map((e=>({id:e.id,type:"function",function:{name:e.name,arguments:JSON.stringify(e.args)}})))});const l=new WeakMap,c=e=>{if("exec"!==e.name)return null;if(l.has(e))return l.get(e);const t=planExec(e.args&&e.args.command,{baseCwd:C});return l.set(e,t),t},d=e=>{if(!se.has(e.name))return!0;const t=c(e);return Boolean(t&&t.oneShot)},f=[];for(const e of a){const t=f[f.length-1];d(e)&&t&&t.parallel?t.calls.push(e):f.push({parallel:d(e),calls:[e]})}const p=async e=>{r&&r({delta:"",tool:{name:e.name,args:e.args,id:e.id,cwd:C,phase:"run"}});const t=c(e),a=t&&t.oneShot?{...$,oneShotExec:!0,cwd:t.cwd||$.cwd}:$,l=e.name===m.SUBAGENT_TOOL?await W(e.args,{cls:n,model:s,statedMaxTokens:i,effort:o&&o.effort,mode:o&&o.mode,parentSignal:_,depth:g,rootSessionId:y,rootOnDelta:k}):await q(e,{toolCtx:a,rootSessionId:y,rootOnDelta:k,signal:_});return l&&l.usage&&oe({usage:l.usage}),r&&r({delta:"",tool:{name:e.name,args:e.args,ok:l.ok,id:e.id,cwd:C,phase:"done"}}),l};for(const e of f){const t=e.parallel&&e.calls.length>1?await Promise.all(e.calls.map((e=>p(e)))):[await p(e.calls[0])];e.calls.forEach(((e,o)=>{const r=t[o];se.has(e.name)&&(ae+=1,r&&r.ok&&(ie+=1)),M.push({role:"tool",tool_call_id:e.id,name:e.name,content:m.toolResultText(r)})}))}}}catch(e){throw _.aborted&&e&&"object"==typeof e&&(e.aegisCancelled=!0),e}finally{U&&U.dispose(),p.get(f)===w&&(E&&!E.signal.aborted?p.set(f,E):p.delete(f))}}async function W({description:e,subagent_type:t,prompt:o}={},{cls:r,model:n,statedMaxTokens:s,effort:a,mode:i,parentSignal:l,depth:c,rootSessionId:d,rootOnDelta:u}={}){const f=String(o||e||"").trim();if(!f)return{ok:!1,error:"task requires a prompt"};const p=t&&"general"!==t?agentRoleLabel(t):"general",m=agentSystemPrompt(t),h=randomUUID();let g;if(l){if(l.aborted)return{ok:!1,error:"aborted"};g=()=>z(h),l.addEventListener("abort",g,{once:!0})}try{const e=await Y({class:r,model:n,mode:i,system:m,prompt:f,sessionId:h,depth:(c||0)+1,rootSessionId:d,rootOnDelta:u,statedMaxTokens:s,effort:a},(()=>{})),t=assistantText(e),o=e&&e.usage?{usage:e.usage}:{};return t?{ok:!0,output:t,...o}:{ok:!1,error:`subagent (${p}) produced no output`,...o}}catch(e){return{ok:!1,error:`subagent (${p}) failed: ${e&&e.message?e.message:e}`}}finally{l&&g&&l.removeEventListener("abort",g)}}function z(e){const t=p.get(e);return t&&t.abort(),{ok:Boolean(t)}}return{CLASSES:CLASSES,listClasses:async function(){return CLASSES.map((o=>{if("aegis"===o.class)return{...o,configured:Boolean(e.apiKey)};if("byok"===o.class){const e=(t.list()||[]).some((e=>!(!e||"string"!=typeof e.provider||!e.provider.startsWith("byok:"))&&(!!e.configured||Boolean(providerKeyFromEnv(e.provider.slice(BYOK_NAMESPACE_PREFIX.length))))));return{...o,configured:e}}if("local"===o.class)return{...o,configured:!0};if("pro"===o.class){const e=claudePro.claudeProStatus({env:process.env}),t=claudePro.seamAvailable();return{...o,configured:e.loggedIn,status:e,seam:t}}return{...o,configured:!1}}))},listModels:async function(o){if("aegis"===o){if(!e.apiKey)return{class:o,models:[],needsKey:!0};const t=await e.listModels();return{class:o,models:offerableCatalog(normalizeCatalog(t&&t.models))}}if("byok"===o){let r=[],n=null,s=!1,a=null;try{const t=await e.byokProviders();r=withUserModels(withCatalog(withByokAdditions(t&&t.providers||[]))),n=t&&t.fee||null}catch(e){r=[],s=!0,a=e&&e.message||String(e)}const i=[];for(const e of r){if(!e||!e.id)continue;const o=t.get(byokNamespace(e.id))||{},r=providerKeyRecord(e.id),n=r.key||"",s=Array.isArray(e.models)?e.models:[];for(const t of s){const s="string"==typeof t?t:t&&t.id;s&&i.push({id:`${e.id}:${s}`,label:`${e.label||e.id} — ${s}`,provider:e.id,configured:Boolean(o.configured||n),keyRejected:r.rejected||null})}}return{class:o,models:i,providers:r,needsProviderKey:i.length>0&&!i.some((e=>e.configured)),needsAegisKey:!e.apiKey,fee:n,providersFailed:s,providersError:a,unmatchedProviders:unmatchedUserProviders(r)}}if("local"===o){const e=(t.get("local")||{}).baseURL||c.DEFAULT_BASE,r=await c.probe(e);if(!r.running)return{class:o,models:[],baseURL:r.baseURL,needsDaemon:!0};let n=[],s=!0;try{n=await c.listTags(e)}catch{s=!1}return{class:o,models:n,baseURL:r.baseURL,listed:s}}if("pro"===o){const e=claudePro.claudeProStatus({env:process.env});return{class:o,models:claudePro.PRO_MODELS.map((t=>({id:t.id,label:t.label,note:t.note,configured:e.loggedIn}))),needsProviderKey:!1,needsAegisKey:!1,subscription:e.subscription,loggedIn:e.loggedIn,credentialFile:e.file,shadowed:e.shadowed||null,seam:claudePro.seamAvailable()}}throw new Error(`listModels: unknown model class ${JSON.stringify(o)} — this build ships 'aegis', 'byok', 'local' and 'pro' only`)},chat:Y,cancel:z,respondApproval:function(e,t){const o=O.get(e);return o?(O.delete(e),o.resolve("session"===t||"once"===t||"always"===t?t:"deny"),{ok:!0}):{ok:!1}},respondRoundsAsk:function(e,t){const o=N.get(e);return o?(N.delete(e),o.resolve(!0===t||"continue"===t),{ok:!0}):{ok:!1}},clearSessionApprovals:function(e){_.delete(e),T.delete(e),S.delete(e),A.delete(e);try{M.del(e,s)}catch{}return{ok:!0}},listUndoable:function(e){return(S.get(e)||[]).map((e=>({id:e.id,tool:e.tool,path:e.path,at:e.at}))).reverse()},undoMutation:function(e,t){const o=S.get(e)||[],r=t?o.findIndex((e=>e.id===t)):o.length-1;if(-1===r)return{ok:!1,error:t?`no undo record "${t}" for this conversation`:"nothing to undo in this conversation"};const n=o[r],s=I(n.path);if(!s||s.existed!==n.after.existed||s.content!==n.after.content)return{ok:!1,error:`${n.path} has changed since ${n.tool} ran — undo refused rather than overwriting work this session did not do. Resolve it by hand, or undo a different entry.`};try{n.before.existed?fs.writeFileSync(n.path,n.before.content,"utf8"):fs.unlinkSync(n.path)}catch(e){return{ok:!1,error:`undo failed: ${e&&e.message||e}`}}return o.splice(r,1),{ok:!0,path:n.path,restored:n.before.existed?"content":"deleted"}},settings:t,unloadLocalModels:function(){return c.unloadAll()},userModels:()=>loadUserModels(),addUserModel:(e,t)=>addUserModel(e,t),removeUserModel:(e,t)=>removeUserModel(e,t),discoverModels:async e=>{const o=String(null==e?"":e).trim().toLowerCase(),r=function(e){const o=String(null==e?"":e).trim().toLowerCase();if(!o)return"";try{if(t&&"function"==typeof t.rawKey){const e=t.rawKey(byokNamespace(o));if("string"==typeof e&&e.trim())return e.trim()}}catch{}return providerKeyFromEnv(o)}(o),n=await discoverVendorModels(o,{key:r,fetchImpl:d});if(!n||!n.ok)return n;const s=[];try{const e=loadUserModels().map;for(const t of Array.isArray(e[o])?e[o]:[])s.push(t)}catch{}return{...n,declared:s,endpoint:(vendorEndpointFor(o)||{}).url||""}},addUserModels:(e,t)=>{const o=Array.isArray(t)?t:[],r={provider:e,added:0,already:[],failed:[],capped:0,file:""};for(const t of o)try{const o=addUserModel(e,t);r.file=o.file||r.file,o.added?r.added+=1:r.already.push(o.model)}catch(e){const n=e&&e.message||String(e);if(/the cap/.test(n)){r.capped=o.length-r.added-r.already.length-r.failed.length;break}r.failed.push({id:String(t),reason:n})}return r},canDiscoverModels:e=>canDiscoverVendorModels(e),discoverableProviders:()=>discoverableProviders()}}module.exports={CLASSES:CLASSES,createLocalEngine:createLocalEngine,extractToolCalls:extractToolCalls,parseArgs:parseArgs,reasoningBudget:reasoningBudget,nativeEffort:nativeEffort,hostEnv:hostEnv};
3
+ "use strict";const{randomUUID:randomUUID}=require("node:crypto"),os=require("node:os"),fs=require("node:fs"),toolsModule=require("./tools.js"),attachmentsModule=require("./attachments.js"),{flattenContent:flattenContent}=attachmentsModule,promptModule=require("./prompt.js"),localTransport=require("./local.js"),{ShellSession:ShellSession}=require("./shell.js"),{planExec:planExec}=require("./exec-plan.js"),claudePro=require("./claude-pro.js"),{agentSystemPrompt:agentSystemPrompt,agentRoleLabel:agentRoleLabel}=require("./agents.js"),{beginTurnGuard:beginTurnGuard,recordWrite:recordWrite,blocksDestructive:blocksDestructive}=require("./turn-guard.js"),repeatGuard=require("./repeat-guard.js"),verifyGuard=require("./verify-stop.js"),{acquireWorktreeLock:acquireWorktreeLock,releaseWorktreeLock:releaseWorktreeLock}=require("./worktree-lock.js"),covenant=require("./covenant.js");let envFile=null;try{envFile=require("../../../client/env-file.js")}catch{try{envFile=require("../../vendor/env-file.js")}catch{envFile=null}}let platformLib=null;try{platformLib=require("../../../client/platform.js")}catch{try{platformLib=require("../../vendor/platform.js")}catch{platformLib=null}}let credentialsLib=null;try{credentialsLib=require("../../../client/credentials.js")}catch{try{credentialsLib=require("../../vendor/credentials.js")}catch{credentialsLib=null}}const PRO_TOOL_MAP=Object.freeze({Write:"writeFile",Edit:"editFile",MultiEdit:"editFile",NotebookEdit:"editFile",Bash:"exec",BashOutput:"exec"}),PRO_PLAN_MODE_SAFE=Object.freeze(new Set(["Read","Glob","Grep"]));function proAskArgs(e,t){const o=e&&"object"==typeof e?e:{};return"exec"===t?"string"==typeof o.command?{command:o.command}:{}:"writeFile"===t?"string"==typeof o.file_path?{file_path:o.file_path,content:o.content}:{}:"editFile"===t?Array.isArray(o.edits)?{file_path:o.file_path,edits:o.edits}:"string"==typeof o.file_path?{file_path:o.file_path,old_string:o.old_string,new_string:o.new_string,replace_all:!0===o.replace_all}:{}:o}function normalizeToolArgs(e,t,o,r){const n=e&&"function"==typeof e.normalizeArgs&&e.normalizeArgs||"function"==typeof toolsModule.normalizeArgs&&toolsModule.normalizeArgs||null;return n?n(t,o,r):{ok:!0,args:o&&"object"==typeof o?o:{},error:null}}function detectVcs(e){if(!e)return null;try{const t=require("node:fs"),o=require("node:path");let r=o.resolve(String(e));for(let e=0;e<8;e+=1){if(t.existsSync(o.join(r,".git")))return"git";const e=o.dirname(r);if(e===r)break;r=e}return""}catch{return null}}function hostEnv(e={},t={},o=null){const r=e||{},n=t||{},s=(e,t)=>null!=n[e]?n[e]:t;let a=r.homedir,i=r.cwd;try{a||(a=os.homedir()),i||(i=process.cwd())}catch{}let l=r.shell,c=r.shellKind;try{if(!l||!c){const e=require("./shell.js").resolveSessionShell();l=l||e.cmd,c=c||e.kind}}catch{}let d=r.desktopdir;try{!d&&platformLib&&(d=platformLib.desktopDir())}catch{}let u=r.dataDir;try{!u&&credentialsLib&&(u=credentialsLib.aegisHome())}catch{}let f=r.locale,p=r.localeName;try{!f&&platformLib&&"function"==typeof platformLib.appLocale&&(f=platformLib.appLocale()),f&&!p&&platformLib&&"function"==typeof platformLib.languageName&&(p=platformLib.languageName(f))}catch{}return{platform:s("platform",r.platform||process.platform),arch:s("arch",r.arch||process.arch),homedir:s("homedir",a),desktopdir:s("desktopdir",d),dataDir:s("dataDir",u),locale:s("locale",f),localeName:s("localeName",p),languages:s("languages",r.languages),cwd:s("cwd",i),vcs:s("vcs",null!=r.vcs?r.vcs:detectVcs(i)),shell:s("shell",l),shellKind:s("shellKind",c),roots:s("roots",r.roots),appVersion:s("appVersion",r.appVersion),model:s("model",o&&o.model)}}function requireSharedBrain(){const e=[()=>require("../../../client/brain-catalog.js"),()=>require("../../vendor/brain-catalog.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}function requireSharedByokCatalog(){const e=[()=>require("../../../client/byok-catalog.js"),()=>require("../../vendor/byok-catalog.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}function requireSharedUserModels(){const e=[()=>require("../../../client/user-models.js"),()=>require("../../vendor/user-models.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}function requireSharedCatalogClient(){const e=[()=>require("../../../client/catalog-client.js"),()=>require("../../vendor/catalog-client.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}function requireSharedModelDiscovery(){const e=[()=>require("../../../client/model-discovery.js"),()=>require("../../vendor/model-discovery.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}const WORKTREE_LOCK_WAIT_MS=1500,MAX_SUBAGENT_DEPTH=4,CLASSES=[{class:"aegis",label:"Aegis Cloud",kind:"cloud"},{class:"byok",label:"Bring your own key",kind:"cloud"},{class:"local",label:"Local model",kind:"local"},{class:"pro",label:"Claude Code Pro",kind:"subscription"}],BYOK_NAMESPACE_PREFIX="byok:";function byokNamespace(e){return`${BYOK_NAMESPACE_PREFIX}${e}`}function splitByokModel(e){const t="string"==typeof e?e:"",o=t.indexOf(":");return o<0?{provider:"",model:t}:{provider:t.slice(0,o),model:t.slice(o+1)}}function providerKeyRecord(e){const t={key:"",env:"",rejected:null};if(!envFile||"function"!=typeof envFile.providerKeyFromEnv)return t;try{const o=envFile.providerKeyFromEnv(e)||t;return{key:"string"==typeof o.key?o.key:"",env:"string"==typeof o.env?o.env:"",rejected:"string"==typeof o.rejected&&o.rejected?o.rejected:null}}catch{return t}}function providerKeyFromEnv(e){if(!envFile||"function"!=typeof envFile.providerKeyFromEnv)return"";try{return envFile.providerKeyFromEnv(e).key||""}catch{return""}}const DEEPSEEK_REASONING_MODEL_RE=/^deepseek-(v4(\.\d+)?-(flash|pro)|flash|pro|reasoner)$/,EFFORT_TOKEN_BUDGET={low:8192,medium:16384,high:32768,max:32768},DEEPSEEK_EFFORT={low:"low",medium:"high",high:"high"},DEEPSEEK_EFFORT_EXTRA={max:"max"},EFFORT_IDENTITY={low:"low",medium:"medium",high:"high"},EFFORT_INERT_RE=/non-reasoning/i,EFFORT_DIALECTS=[{provider:"deepseek",re:DEEPSEEK_REASONING_MODEL_RE,field:"effort",map:DEEPSEEK_EFFORT,extra:DEEPSEEK_EFFORT_EXTRA},{provider:"openai",re:/^(gpt-5|o[0-9])/i,field:"reasoning_effort",map:EFFORT_IDENTITY},{provider:"groq",re:/^(openai\/gpt-oss|qwen\/qwen3)/i,field:"reasoning_effort",map:EFFORT_IDENTITY},{provider:"xai",re:/^grok-(4\.[5-9]|[5-9])/,field:"reasoning_effort",map:EFFORT_IDENTITY},{provider:"google",re:/^gemini-(2\.5|3|[4-9])/,field:"reasoning_effort",map:{...EFFORT_IDENTITY,medium:"high"}}],AUTONOMOUS_IDLE_TIMEOUT_MS=9e5;function reasoningBudget(e,t,o){const r=Number(t);return Number.isFinite(r)&&r>0?r:DEEPSEEK_REASONING_MODEL_RE.test(String(e||""))?EFFORT_TOKEN_BUDGET["low"===o||"medium"===o||"max"===o?o:"high"]:void 0}function nativeEffort(e,t,o){const r=String(t||"");if(EFFORT_INERT_RE.test(r))return;if(null===o)return;const n="low"===o||"medium"===o?o:"max"===o?"max":"high";for(const t of EFFORT_DIALECTS)if(t.provider===e&&t.re.test(r)){const e=Object.prototype.hasOwnProperty.call(t.map,n)?t.map[n]:t.extra&&Object.prototype.hasOwnProperty.call(t.extra,n)?t.extra[n]:void 0;if(void 0===e)return;return{field:t.field,level:e}}}function normalizeCatalog(e){return Array.isArray(e)?e.map((e=>"string"==typeof e?{id:e}:e)).filter((e=>e&&e.id)):[]}const{offerableCatalog:offerableCatalog}=requireSharedBrain(),{withByokAdditions:withByokAdditions,canonicalModelId:canonicalModelId,nexusFallbackModel:nexusFallbackModel}=requireSharedByokCatalog(),{withUserModels:withUserModels,unmatchedUserProviders:unmatchedUserProviders,load:loadUserModels,addUserModel:addUserModel,removeUserModel:removeUserModel}=requireSharedUserModels(),{withCatalog:withCatalog}=requireSharedCatalogClient(),{discoverModels:discoverVendorModels,canDiscover:canDiscoverVendorModels,endpointFor:vendorEndpointFor,discoverableProviders:discoverableProviders}=requireSharedModelDiscovery();function parseArgs(e){if(null==e)return{};if("object"==typeof e)return e;try{const t=JSON.parse(String(e));return t&&"object"==typeof t?t:{}}catch{return{}}}function extractToolCalls(e){if(!e)return[];if(Array.isArray(e.toolCalls)&&e.toolCalls.length)return e.toolCalls.map((e=>({id:e.id||"",name:e.name||"",args:parseArgs(e.args)}))).filter((e=>e.name));const t=e.choices&&e.choices[0]&&e.choices[0].message,o=t&&t.tool_calls||[];return Array.isArray(o)?o.map((e=>{const t=e&&e.function||{};return{id:e&&e.id||"",name:t.name||e&&e.name||"",args:parseArgs(t.arguments)}})).filter((e=>e.name)):[]}function proTurnPrompt(e){const t=Array.isArray(e.prompt)?flattenContent(e.prompt):e.prompt;if("string"==typeof t&&t.trim())return t;const o=Array.isArray(e.messages)?e.messages:[];for(let e=o.length-1;e>=0;e-=1){const t=o[e];if(!t||"user"!==t.role)continue;const r=flattenContent(t.content);if(r.trim())return r}return t}function assistantText(e){const t=e&&e.choices&&e.choices[0]&&e.choices[0].message;return t&&"string"==typeof t.content&&t.content||""}function finishReasonOf(e){const t=e&&e.choices&&e.choices[0];return t&&t.finish_reason||e&&e.stop_reason||""}function isTruncated(e){const t=finishReasonOf(e);return"length"===t||"max_tokens"===t}function reasoningTextOf(e){if(!e)return"";const t=e.choices&&e.choices[0],o=t&&t.message||{};if(Array.isArray(o.content)){const e=o.content.filter((e=>e&&("thinking"===e.type||"reasoning"===e.type))).map((e=>e.thinking||e.text||"")).join("");if(e)return e}const r=o.content&&"object"==typeof o.content?o.content.reasoning_content:"",n=[o.reasoning_content,o.reasoning,t&&t.reasoning_content,e.reasoning_content,e.reasoning,r];for(const e of n)if("string"==typeof e&&e)return e;return""}function reasoningTokensOf(e){if(!e)return 0;const t=e.choices&&e.choices[0],o=t&&t.message||{},r=e.usage||{},n=r.completion_tokens_details||r.output_tokens_details||{},s=[o.thinking_tokens,o.reasoning_tokens,t&&t.thinking_tokens,e.thinking_tokens,n.reasoning_tokens,n.thinking_tokens];for(const e of s)if("number"==typeof e&&Number.isFinite(e)&&e>0)return e;return 0}function reasonedButSilent(e){return!assistantText(e)&&(""!==reasoningTextOf(e)||reasoningTokensOf(e)>0)}const REASONING_RETRY_FLOOR=32768;function retryBudgetFor(e,t){const o=doubledBudget(e.maxTokens);return t&&ladderRung(e.maxTokens)?Math.max(o,REASONING_RETRY_FLOOR):o}function ladderRung(e){const t=Number(e);return Number.isFinite(t)&&Object.values(EFFORT_TOKEN_BUDGET).includes(t)}function doubledBudget(e){const t=Number(e)||0;return t>0?2*t:8192}function statedCapOf(e){const t=e=>{const t=Number(e);return Number.isFinite(t)&&t>0?t:void 0};return e&&Object.prototype.hasOwnProperty.call(e,"statedMaxTokens")?t(e.statedMaxTokens):t(e&&e.maxTokens)}const EMPTY_TURN_NUDGE="Your previous reply came back empty — it contained no answer and no tool call. Write your answer now, using only the information already gathered above. No tools are available in this reply, so do not call any: respond in plain prose or markdown.",THOUGHT_ONLY_NUDGE="Your previous round was spent entirely on hidden reasoning and produced no visible reply. Answer the user directly and briefly now. Do not reason, explain, or think first — write only the answer, no tools.",FINAL_ANSWER_NUDGE="Write your answer now, in plain prose, using only what is already in this conversation. If your information is incomplete, say what you have and what is missing — an incomplete answer is the expected outcome here and is better than none. No tools, no preface.",RECOVERY_ROUNDS=2,UNMUTATED_TURN_NUDGE="You ended the turn without changing any file, but this request asked for a change. The tools are still available in this reply: make the edit now with editFile or writeFile. If you already know what to change, change it — describing the fix is not the fix. If you genuinely cannot, say precisely what blocks you.",MUTATION_INTENT_RE=new RegExp("\\b(?:fix|implement|add|create|write|refactor|rename|remove|delete|replace|update|patch|migrate|convert|make\\s+(?:it|them|this|that|the|sure)|change|correct|resolve|repair|address|apply|introduce|support|wire\\s+up)\\b","i");function wantsMutation(e,t,o){if(t)return!1;if(!(o>0))return!1;const r=String(e||"");return!!r.trim()&&!/\?\s*$/.test(r.trim())&&MUTATION_INTENT_RE.test(r)}function emptyTurnError({cls:e,model:t,finishReason:o,reasoningChars:r,reasoningTokens:n,effort:s,recoveryRounds:a}){const i=Number(a)||0,l=Number(n)||0,c=new Error(`The model returned no answer after ${e}/${t} was asked to summarise its results`+(i?`, and ${i} extra recovery call${1===i?"":"s"} with a larger budget and a changed ask came back empty too`:"")+` (stop reason: ${o||"none"}`+(s?`, effort: ${s}`:"")+(r?`, hidden reasoning: ${r} chars and no visible text`:l>0?`, ~${l} thinking tokens billed and no visible text`:"")+"). "+(r||l>0?"Every one of those calls spent its output on hidden reasoning instead of writing a word, so this is the model rather than the budget: pick a model that answers without a thinking pass, or ask for a smaller piece of work.":"No visible text came back from any of those calls. Send the request again, in smaller pieces, or from a different model."));return c.status=502,c}function createLocalEngine({aegis:e,settings:t,tools:o,promptBuilder:r,recallProvider:n,env:s,getConfirmMode:a,getPermissionMode:i,sandbox:l,localTransport:c=localTransport,fetchImpl:d,gitScope:u,permissionRules:f}){const p=new Map,m=o||toolsModule,h=r&&r.buildSystemPrompt||promptModule.buildSystemPrompt,g=f&&"function"==typeof f.rulesVerdict?f.rulesVerdict:null,y=f&&"function"==typeof f.alwaysAllow?f.alwaysAllow:null,k=f&&"function"==typeof f.subjectFor?f.subjectFor:null,v=require("./session-rounds.js"),b=()=>{if("function"==typeof a)return!1!==a();if(t&&"function"==typeof t.getConfirmMode){const e=t.getConfirmMode();return void 0===e||Boolean(e)}return!0},w=()=>"function"==typeof i?"plan"===i():!(!t||"function"!=typeof t.getPermissionMode)&&"plan"===t.getPermissionMode();function E(e,t){return`${e} was not executed — this session is in plan mode (read-only). Plan mode may read files, search, run read-only shell commands and deploy subagents to research, but may not create, edit or delete files, run a mutating command, or install packages`+(t?` (this command: ${t})`:"")+". Do NOT retry it or attempt the same effect by another route. Finish your research and present a plan in plain text; the user exits plan mode (`/permissions mode off`) before any edit can run."}const _=new Map,T=new Map,S=new Map,x=200,A=new Map,M=require("./pro-sessions.js"),O=new Map,N=new Map;function F(e,t){if("function"!=typeof k)return e;let o="";try{o=String(k(e,t||{})||"")}catch{o=""}return`${e}\0${o}`}function R(e,t,o){_.has(e)||_.set(e,new Set),_.get(e).add(F(t,o))}function D(e,t){const o=T.get(e);return Boolean(o&&o.has(t))}function U(e,t){T.has(e)||T.set(e,new Set),T.get(e).add(t)}function I(e){if(!e)return null;try{return{existed:!0,content:fs.readFileSync(e,"utf8")}}catch(e){return e&&"ENOENT"===e.code?{existed:!1,content:null}:null}}function L(e){return`${e} was not executed — the user denied this tool for this conversation. Do NOT retry it and do NOT attempt the same effect by another route (another command, a writeFile instead of an edit, a subagent). Stop calling tools and reply in plain text: say what you were trying to do, what you need, and that the user can re-enable ${e} to let it proceed.`}function C(e,t,o,r){return new Promise((n=>{if(o&&o.aborted)return void n("cancel");const s=randomUUID();let a=!1;const i=()=>l("cancel"),l=e=>{a||(a=!0,O.delete(s),o&&o.removeEventListener("abort",i),n(e))};o&&o.addEventListener("abort",i,{once:!0}),O.set(s,{resolve:l}),"function"==typeof t?t({delta:"",approval:{id:s,sessionId:e,tool:r.tool,args:r.args,diff:r.diff||null,canPersist:"function"==typeof y}}):l("cancel")}))}function P(e,t,o,r){return new Promise((n=>{if(o&&o.aborted)return void n(!1);const s=randomUUID();let a=!1;const i=()=>l(!1),l=e=>{a||(a=!0,N.delete(s),o&&o.removeEventListener("abort",i),n(e))};o&&o.addEventListener("abort",i,{once:!0}),N.set(s,{resolve:l}),"function"==typeof t?t({delta:"",rounds:{id:s,sessionId:e,spent:r.spent,extensions:r.extensions,max:r.max,size:r.size}}):l(!1)}))}async function $(e,t,o,r,n){const s=normalizeToolArgs(m,e,t,o||{});if(!s.ok)return{ok:!1,error:s.error};t=s.args;const a=o&&o.guard;if(a&&"exec"===e){const e=blocksDestructive(a,t&&t.command);if(!e.ok)return{ok:!1,error:e.reason}}const i=o&&o.repeat,l=i?repeatGuard.check(i,e,t):null;if(l&&"refuse"===l.action)return{ok:!1,error:l.error};const c=covenant.preActionAssert({tool:e,args:t||{}});if(!c.allowed){const o=covenant.bindRefusal({tool:e,args:t||{}},c);return{ok:!1,error:`refused by the ÆGIS covenant — ${c.clause} (${c.label}): ${c.reason}`,covenant:o}}const d="writeFile"===e||"editFile"===e,u=d?I(t&&t.file_path):null,f=await m.executeTool(e,t,o);a&&d&&f&&!1!==f.ok&&recordWrite(a,t&&t.file_path),i&&d&&f&&!1!==f.ok&&repeatGuard.recordWrite(i,t&&t.file_path);const p=o&&o.verify;if(p&&(verifyGuard.EXEC_TOOLS.has(e)&&f&&!1!==f.ok?verifyGuard.recordExec(p):d&&f&&!1!==f.ok&&verifyGuard.recordMutation(p,t&&t.file_path)),d&&u&&f&&!1!==f.ok){const o=I(t&&t.file_path);o&&function(e,t){if(!e)return;S.has(e)||S.set(e,[]);const o=S.get(e);o.push(t),o.length>x&&o.shift()}(r,{id:n||randomUUID(),tool:e,path:t&&t.file_path,before:u,after:o,at:Date.now()})}return l&&l.note?j(f,l.note):f}function j(e,t){if(!e||"object"!=typeof e)return{ok:!0,content:`${t}\n${null==e?"":e}`};if(!1===e.ok||!0===e.isError){const o=e.error||e.content||"";return{...e,error:`${t}\n${o}`,content:`${t}\n${o}`}}const o=null!=e.content?e.content:null!=e.output?e.output:"";return{...e,content:`${t}\n${o}`}}async function q(e,{toolCtx:t,rootSessionId:o,rootOnDelta:r,signal:n}){const{name:s}=e,a=normalizeToolArgs(m,s,e.args,t||{});if(!a.ok)return{ok:!1,error:a.error};const i=a.args;if(!m.MUTATING_TOOLS.has(s))return $(s,i,t,o,e.id);if(w()){if("exec"===s){const r=planExec(i&&i.command,{baseCwd:t&&t.cwd||void 0});return r.oneShot?$(s,i,t,o,e.id):{ok:!1,error:E(s,r.reason)}}return{ok:!1,error:E(s)}}if(!b())return $(s,i,t,o,e.id);if(function(e,t,o){const r=_.get(e);return Boolean(r&&r.has(F(t,o)))}(o,s,i))return $(s,i,t,o,e.id);if("function"==typeof g){let r;try{r=g(s,i)}catch(e){r={verdict:null,source:"error",error:e&&e.message||String(e)}}if(r&&"deny"===r.verdict)return U(o,s),{ok:!1,error:L(s),permissionRule:r.rule||null};if(r&&"allow"===r.verdict)return $(s,i,t,o,e.id)}if(D(o,s))return{ok:!1,error:L(s)};let l=null;if(("writeFile"===s||"editFile"===s)&&(l=m.previewMutation(s,i,t||{}),!l.ok))return{ok:!1,error:l.error};const c=await C(o,r,n,{tool:s,args:i,diff:l&&l.diff});if("deny"===c)return U(o,s),{ok:!1,error:L(s)};if("session"!==c&&"once"!==c&&"always"!==c)return{ok:!1,error:`${s} was not executed — the request was cancelled.`};let d=null;if("always"===c){let e=null;if("function"==typeof y)try{e=y(s,i)}catch(t){e={ok:!1,reason:t&&t.message||String(t)}}else e={ok:!1,reason:"no durable store is wired on this host"};d=e&&e.ok?`[permission_rule] stored ${e.rule} — this command will not ask again`:`[permission_rule] nothing was stored — ${e&&e.reason||"unknown reason"}; this call was allowed once only`}if("session"===c&&R(o,s,i),l){const e=m.applyChecked(s,i,l,t||{});return e&&!1!==e.ok&&t&&t.guard&&recordWrite(t.guard,i&&i.file_path),d?j(e,d):e}const u=await $(s,i,t,o,e.id);return d?j(u,d):u}function B(e){return hostEnv(s||{},e&&e.env||{},e)}function K(e){const t=[],o=e=>String(e||"").replace(/[\\/]+$/,""),r=o(e),n=e=>{const n=o(e);n&&n!==r&&!t.includes(n)&&t.push(n)};let s=u;if(void 0===s)try{s=require("./git-scope.js")}catch{s=null}try{s&&"function"==typeof s.gitRoot&&n(s.gitRoot(e))}catch{}try{credentialsLib&&"function"==typeof credentialsLib.aegisHome&&n(credentialsLib.aegisHome())}catch{}return t}async function G(t,o){if("aegis"===t){const t=!o.singlePass&&(!!o.autonomous||void 0);return e.chatCompletion({prompt:o.prompt,system:o.system,messages:o.messages,model:o.model,mode:o.mode,maxTokens:o.statedMaxTokens,stream:!1!==o.stream,includeUsage:!0,onStream:o.onDelta,onReasoning:o.onReasoning,idleTimeoutMs:o.idleTimeoutMs,signal:o.signal,extra:{aegis_recall:!0,...o.recallDeep?{aegis_recall_deep:!0}:{},session:o.sessionId,...void 0===t?{}:{brain:t},...!1===t?{mode:"brain"}:{},...o.effort?{effort:o.effort}:{},...!0===t&&o.workers?{workers:o.workers}:{},...o.tools.length?{tools:o.tools}:{},...o.toolChoice?{tool_choice:o.toolChoice}:{}},agentKey:o.tools.length&&(process.env.AEGIS_AGENT_KEY||"").trim()||void 0})}if("byok"===t){const{provider:t,model:r}=splitByokModel(o.model),n=canonicalModelId(t,r),s=nativeEffort(t,n,o.effort);try{return await e.byokChatCompletion({provider:t,model:n,providerKey:o.apiKey,baseURL:o.cfg&&o.cfg.baseURL,prompt:o.prompt,system:o.system,messages:o.messages,maxTokens:o.maxTokens,tools:o.tools,toolChoice:o.toolChoice,effort:s&&"effort"===s.field?s.level:void 0,reasoningEffort:s&&"reasoning_effort"===s.field?s.level:void 0,stream:!0,onStream:o.onDelta,signal:o.signal})}catch(e){if(e&&402===e.status){const e=new Error("byok: this account has no AEGIS balance left, and the BYOK handling fee is billed there — your provider key is still valid, this is not a key problem. Top up the account, then try again (or /class aegis to use the pooled lane).");throw e.status=402,e}throw e}}if("local"===t){const e=o.cfg&&o.cfg.baseURL||c.DEFAULT_BASE,t=t=>c.chat({baseURL:e,model:o.model,prompt:o.prompt,system:o.system,messages:o.messages,maxTokens:o.maxTokens,signal:o.signal,onDelta:o.onDelta,...t&&o.tools.length?{tools:o.tools,toolChoice:o.toolChoice}:{}});try{return await t(!0)}catch(e){if(o.tools.length&&e&&400===e.status)return t(!1);throw e}}if("pro"===t){const e=o.sessionKey||o.rootSessionId||o.sessionId;let t=null;if(e&&(t=A.get(e)||null,!t)){try{t=M.get(e,s)||null}catch{}t&&A.set(e,t)}const r=K(o.cwd),n=e=>claudePro.runClaudePro({prompt:proTurnPrompt(o),model:o.model&&"default"!==o.model?o.model:void 0,system:o.system,cwd:o.cwd,addDir:r,resumeSessionId:e||void 0,gate:b(),onAsk:async e=>{if(!e||!e.requestId)return"deny";const t=o.rootSessionId,r=o.rootOnDelta,n=PRO_TOOL_MAP[String(e.toolName||"")]||null,s=n||String(e.toolName||"unknown"),a=proAskArgs(e.input||{},s),i=covenant.preActionAssert({tool:s,args:a});if(!i.allowed)return r&&r({delta:"",note:`aegis: refused by the ÆGIS covenant — ${i.clause} (${i.label}): ${i.reason}`}),"deny";if(w()){if("exec"===s){const e=planExec(a&&a.command,{baseCwd:o.cwd||void 0});return e.oneShot?"once":(r&&r({delta:"",note:E(s,e.reason)}),"deny")}if(n&&m.MUTATING_TOOLS.has(s))return r&&r({delta:"",note:E(s)}),"deny";if(!n&&!PRO_PLAN_MODE_SAFE.has(s))return r&&r({delta:"",note:E(s)}),"deny"}if(!b())return"once";if("function"==typeof g){let e;try{e=g(s,a)}catch{e=null}if(e&&"deny"===e.verdict)return r&&r({delta:"",note:L(s)}),"deny";if(e&&"allow"===e.verdict)return"once"}if(D(t,s))return r&&r({delta:"",note:L(s)}),"deny";const l=await C(t,r,o.signal,{tool:s,args:a,diff:null});if("deny"===l)return U(t,s),"deny";if("session"!==l&&"once"!==l&&"always"!==l)return"deny";if("session"===l&&R(t,s,a),"always"===l&&"function"==typeof y)try{y(s,a)}catch{}return l},signal:o.signal,onDelta:o.onDelta,onSpawn:(e,t)=>{o.onDelta&&t&&o.onDelta({delta:"",note:claudePro.childLine(t)})}});let a=await n(t);if(a&&a.resumeStale){A.delete(e);try{M.del(e,s)}catch{}o.onDelta&&o.onDelta({delta:"",note:"aegis: the remembered Claude session no longer exists on this machine — continuing as a new conversation (earlier turns are not in its context)"}),a=await n(null)}if(e&&a&&a.sessionId&&!a.error){A.set(e,a.sessionId);try{M.set(e,a.sessionId,s)}catch{}}return a}throw new Error(`dispatch: unknown model class ${JSON.stringify(t)} — this build ships 'aegis', 'byok', 'local' and 'pro' only`)}async function Y(o,r){const s=o&&o.class,a=o&&o.model,i=reasoningBudget("byok"===s?splitByokModel(a).model:a,o&&o.maxTokens,o&&o.effort),d=statedCapOf(o),u="aegis"===s&&Boolean(o&&o.autonomous),f=Boolean(o&&o.roundsAsk),g=o&&o.sessionId||randomUUID(),y=Number.isInteger(o&&o.depth)?o.depth:0,k=o&&o.rootSessionId||g,b=o&&o.rootOnDelta||r,w="function"==typeof r?e=>e&&r({reasoning:e}):void 0,E=new AbortController,_=p.get(g)||null;p.set(g,E);const T=E.signal,S=!(o&&!1===o.tools),x=S?m.toolsFor({includeSubagent:y<4}):[],A=o&&o.toolChoice||null,M=o&&o.system||h(B(o)),O=n?await n({payload:o,env:B(o),system:M}):null,N="string"==typeof O?O:O&&"string"==typeof O.system?O.system:M,F=Array.isArray(o&&o.messages)?o.messages.filter(Boolean).slice():[];let R=F.length,D=o&&o.prompt||"";const U=String(D||""),I=Array.isArray(o&&o.attachments)?o.attachments.filter((e=>e&&"object"==typeof e)).slice(0,attachmentsModule.MAX_ATTACHMENTS):[];let L=I.length?attachmentsModule.buildContent(D,I):D,C=null;const $=B(o),j=((e,t)=>{if(null==l)return null;const o="function"==typeof l.policy?l.policy():l.policy;if(!o)return null;const r=require("./sandbox.js"),n=e&&e.cwd||process.cwd(),s=r.normalize(o,n);if("off"===s.mode)return null;let a=[];try{let e=null;try{e=require("node:os").homedir()}catch{e=null}a=r.autoGrants(n,{home:e,addDirs:(()=>{try{return K(n)}catch{return[]}})()})}catch{a=[]}if(a.length){const e=new Set;for(const t of s.fileSystem.entries)t&&t.path&&"path"===t.path.type&&t.path.path&&e.add(`${t.access}:${t.path.path}`);for(const t of a){const o=`${t.access}:${t.path.path}`;e.has(o)||(e.add(o),s.fileSystem.entries.push(t))}}return"local"===t&&"restricted"===s.network&&(s.network="open",s.networkExempt="local"),{policy:s,state:l.state||r.detect({appDir:l.appDir}),workspace:n,appDir:l.appDir,strict:!0===l.strict}})($,s),Y=$.cwd,z={getShell:()=>C||(C=new ShellSession({cwd:$.cwd,sandbox:j})),signal:T,cwd:Y,desktopdir:$.desktopdir,sandbox:j,repeat:repeatGuard.beginRepeatGuard({cwd:Y}),verify:verifyGuard.beginVerifyGuard({cwd:Y}),guard:beginTurnGuard(Y)};try{const n="byok"===s?splitByokModel(a):null;let l=null;const p="byok"===s?t.get(byokNamespace(n.provider))||{}:"local"===s&&t.get("local")||{},h="byok"===s?t.rawKey(byokNamespace(n.provider)):null,E="byok"!==s?null:h||providerKeyFromEnv(n.provider);if(!("byok"!==s||n.provider&&n.model)){const e=new Error('byok: model must be "<provider>:<model>" (pick one from /models) — got '+JSON.stringify(a||""));throw e.status=400,e}if("byok"===s&&!E){const t="anthropic"===n.provider?claudePro.claudeProStatus({env:process.env}):null,o=providerKeyRecord(n.provider).rejected,r=nexusFallbackModel({provider:n.provider,providerKey:E,providerKeyRefused:o,aegisKey:E?"":e.apiKey});if(!r){const e=new Error(o?`${o}. That is why this turn has no ${n.provider} key: an env value that short is a paste that lost its payload, not a credential. Fix ${o.split(" ")[0]} in ~/.aegiscode/.env (or the shell that exported it) — or skip keys entirely: /byok-key ${n.provider} <key> to set one here.`:t&&t.loggedIn?`No Anthropic API key on this machine — an "anthropic:…" id is served by your own console key, which a Claude subscription is not. Use the subscription instead: /class pro (it spends your Claude Code ${t.subscription||"Pro"} plan through the claude CLI) — or add a real console key: /byok-key anthropic <key>.`:`No key for "${n.provider}" yet. Easiest fix: /class aegis (uses your AEGIS key, no setup) — or add this provider's own key: /byok-key ${n.provider} <key>.`);throw e.status=400,e}l={from:n.provider,model:r}}if("byok"===s&&!e.apiKey){const e=new Error("No AEGIS key connected yet. Easiest fix: /class aegis (skips BYOK entirely) — or add your AEGIS key with /login, then try again.");throw e.status=401,e}if("local"===s){const e=c.remoteRefusal(p.baseURL||c.DEFAULT_BASE);if(e)throw e}if("byok"===s&&"custom"===n.provider&&!(p.baseURL||"").trim()){const e=new Error('No endpoint saved for the "custom" provider — its key is on this machine but the address it dials is not, and no default exists for a vendor AEGIS does not know. Fix: /model-add custom <https-base-url> <api-key> <model-id> (writes both halves), or the endpoint field in Settings › Provider (custom).');throw e.status=400,e.code="custom_endpoint_missing",e}const _=l?"aegis":s,M={cls:_,model:l?l.model:a,mode:o&&o.mode,maxTokens:i,statedMaxTokens:d,autonomous:u,sessionId:g,signal:T,onDelta:r,cfg:p,apiKey:E,toolChoice:A,pooledFrom:l?l.from:void 0,cwd:Y,rootSessionId:k,sessionKey:o&&o.sessionKey||void 0,rootOnDelta:b,effort:o&&o.effort,workers:o&&o.workers,recallDeep:o&&!0===o.recallDeep,singlePass:o&&!0===o.singlePass,onReasoning:w,idleTimeoutMs:u?9e5:void 0,stream:!o||!1!==o.stream};let O=!1,C=!1;const $=u?"AEGIS_AUTONOMOUS_MAX_ROUNDS":"AEGIS_CHAT_MAX_ROUNDS",j=(()=>{const e=Number.parseInt(process.env[$]||"",10);return Number.isFinite(e)&&e>0?e:0})(),B=j||(u?40:24);let K=v.keyFor(o,F),V=v.take(K);if(!V&&!v.isStatedKey(o)){const e=v.adopt();e&&(V=e.entry,K=e.key)}if(V){const e=v.resumePreamble(V);0===F.length?Array.isArray(V.messages)&&V.messages.length&&F.push(...V.messages):Array.isArray(V.added)&&V.added.length&&F.push(...V.added),D?(D=`${e}\n\n${D}`,L=I.length?attachmentsModule.buildContent(D,I):D):(F.push({role:"user",content:e}),L=""),b&&b({delta:`\n\n[resuming work this session left unfinished at ${V.rounds} tool rounds`+(V.interruptions>1?` (cut off ${V.interruptions}×)`:"")+"…]\n"})}let H=j||B+(V?v.bonus(B):0),X=0;const J=B,Q=8;let Z=0;const ee={calls:0},te=["input_tokens","output_tokens","prompt_tokens","completion_tokens","total_tokens","cache_read_input_tokens","cache_creation_input_tokens","prompt_cache_hit_tokens","prompt_cache_miss_tokens","reasoning_tokens","thinking_tokens"],oe=e=>{const t=e&&e.usage;if(t&&"object"==typeof t){ee.calls+=1;for(const e of te)"number"==typeof t[e]&&Number.isFinite(t[e])&&(ee[e]=(ee[e]||0)+t[e]);if("number"!=typeof t.total_tokens){const e=(t.prompt_tokens??t.input_tokens??0)+(t.completion_tokens??t.output_tokens??0);e&&(ee.total_tokens=(ee.total_tokens||0)+e)}}},re=e=>{if(!e||"object"!=typeof e)return e;const t=l?{...e,pooled_from:l.from,pooled_model:l.model,pooled_notice:requireSharedByokCatalog().nexusFallbackNotice({pooled_from:l.from,pooled_model:l.model})}:e;return ee.calls?{...t,usage:{...ee}}:t},ne=()=>{if(""===L)return;const e=F[F.length-1],t=e&&"user"===e.role?flattenContent(e.content):null;e&&"user"===e.role&&t===flattenContent(L)||F.push({role:"user",content:L}),D="",L=""};R=F.length;const se=m&&m.MUTATING_TOOLS||new Set;let ae=0,ie=0,le=!1,ce=!1;for(;;){if(X>=H){if(f&&Z<Q&&!T.aborted&&await P(k,b,T,{spent:H,extensions:Z+1,max:Q,size:J})){Z+=1;const e=H;H+=J,F.push({role:"user",content:`You have used all ${e} tool rounds allowed for this turn; ${J} more have been granted (do not restart). Continue the task from exactly where you stopped — do not re-plan, do not repeat work already done, and finish with an answer.`});continue}const e=f?"":`, or raise ${$} for a longer single turn`,t=`[stopped at ${H} tool rounds`+(ee.total_tokens?`, ${ee.total_tokens.toLocaleString()} tokens`:"")+". This session holds the work: your next message here resumes it automatically"+` (with a continuation preamble)${e}.]`,o=v.record(K,{rounds:X,tokens:ee.total_tokens||0,note:t,chain:V?V.interruptions:0,messages:F,added:F.slice(R)});return b&&b({delta:`\n\n${t}`}),re({model:M.model,choices:[{message:{content:t},finish_reason:"length"}],stoppedOnRounds:!0,heldForSession:!0,heldRounds:o.rounds,sessionInterruptions:o.interruptions,resumedFrom:K})}X+=1;const e={...M,system:N,messages:F,prompt:L,tools:x,recallDeep:M.recallDeep&&1===X};let t;if(t=await G(_,e),oe(t),T.aborted)return re(t);if(!O&&!assistantText(t)&&(isTruncated(t)||reasonedButSilent(t))){O=!0;const o=reasonedButSilent(t);if(t=await G(_,{...e,singlePass:!0,recallDeep:!1,effort:o?"high":e.effort,maxTokens:retryBudgetFor(e,o),statedMaxTokens:e.statedMaxTokens?doubledBudget(e.statedMaxTokens):void 0}),oe(t),T.aborted)return re(t)}const n=x.length?extractToolCalls(t):[];if(!n.length){if(assistantText(t)||C||!S){if(!le&&S&&wantsMutation(U,ie>0,ae)){le=!0,ne(),F.push({role:"assistant",content:assistantText(t)}),F.push({role:"user",content:UNMUTATED_TURN_NUDGE}),b&&b({delta:""});continue}if(z.verify&&!ce){const e=verifyGuard.shouldNudge(z.verify);if(e.nudge){ce=!0,ne(),F.push({role:"assistant",content:assistantText(t)}),F.push({role:"user",content:e.text}),b&&b({delta:""});continue}}return re(t)}C=!0,ne(),F.push({role:"user",content:reasonedButSilent(t)?THOUGHT_ONLY_NUDGE:EMPTY_TURN_NUDGE});const o={...e,singlePass:!0,recallDeep:!1,messages:F,prompt:"",tools:[]};t=await G(_,o);let r=o.maxTokens,n=o.effort;if(oe(t),T.aborted)return re(t);if(!assistantText(t)&&(isTruncated(t)||reasonedButSilent(t))){const e=reasonedButSilent(t);if(r=retryBudgetFor(o,e),n=e?"high":o.effort,t=await G(_,{...o,effort:n,maxTokens:r,statedMaxTokens:o.statedMaxTokens?doubledBudget(o.statedMaxTokens):void 0}),oe(t),T.aborted)return re(t)}const i=(()=>{const e=Number(r)||0;if(!e)return r;const t={maxTokens:r};return o.statedMaxTokens&&(t.statedMaxTokens=o.statedMaxTokens),Math.max(e,retryBudgetFor(t,!0))})();let l=0;for(;!assistantText(t)&&l<2&&!T.aborted;){const e=reasonedButSilent(t);if(l+=1,F.push({role:"user",content:e?1===l?THOUGHT_ONLY_NUDGE:FINAL_ANSWER_NUDGE:EMPTY_TURN_NUDGE}),e&&(n="high"),r=i,t=await G(_,{...o,messages:F,effort:n,maxTokens:r,statedMaxTokens:o.statedMaxTokens?doubledBudget(o.statedMaxTokens):void 0}),oe(t),T.aborted)return re(t)}if(!assistantText(t))throw emptyTurnError({cls:s,model:a,effort:n,recoveryRounds:l,finishReason:finishReasonOf(t),reasoningChars:reasoningTextOf(t).length,reasoningTokens:reasoningTokensOf(t)});return re(t)}ne(),F.push({role:"assistant",content:assistantText(t),tool_calls:n.map((e=>({id:e.id,type:"function",function:{name:e.name,arguments:JSON.stringify(e.args)}})))});const i=new WeakMap,l=e=>{if("exec"!==e.name)return null;if(i.has(e))return i.get(e);const t=planExec(e.args&&e.args.command,{baseCwd:Y});return i.set(e,t),t},c=e=>{if(!se.has(e.name))return!0;const t=l(e);return Boolean(t&&t.oneShot)},u=[];for(const e of n){const t=u[u.length-1];c(e)&&t&&t.parallel?t.calls.push(e):u.push({parallel:c(e),calls:[e]})}const p=async e=>{r&&r({delta:"",tool:{name:e.name,args:e.args,id:e.id,cwd:Y,phase:"run"}});const t=l(e),n=t&&t.oneShot?{...z,oneShotExec:!0,cwd:t.cwd||z.cwd}:z,i=e.name===m.SUBAGENT_TOOL?await W(e.args,{cls:s,model:a,statedMaxTokens:d,effort:o&&o.effort,mode:o&&o.mode,parentSignal:T,depth:y,rootSessionId:k,rootOnDelta:b}):await q(e,{toolCtx:n,rootSessionId:k,rootOnDelta:b,signal:T});return i&&i.usage&&oe({usage:i.usage}),r&&r({delta:"",tool:{name:e.name,args:e.args,ok:i.ok,id:e.id,cwd:Y,phase:"done"}}),i};for(const e of u){const t=e.parallel&&e.calls.length>1?await Promise.all(e.calls.map((e=>p(e)))):[await p(e.calls[0])];e.calls.forEach(((e,o)=>{const r=t[o];se.has(e.name)&&(ae+=1,r&&r.ok&&(ie+=1)),F.push({role:"tool",tool_call_id:e.id,name:e.name,content:m.toolResultText(r)})}))}}}catch(e){throw T.aborted&&e&&"object"==typeof e&&(e.aegisCancelled=!0),e}finally{C&&C.dispose(),p.get(g)===E&&(_&&!_.signal.aborted?p.set(g,_):p.delete(g))}}async function W({description:e,subagent_type:t,prompt:o}={},{cls:r,model:n,statedMaxTokens:s,effort:a,mode:i,parentSignal:l,depth:c,rootSessionId:d,rootOnDelta:u}={}){const f=String(o||e||"").trim();if(!f)return{ok:!1,error:"task requires a prompt"};const p=t&&"general"!==t?agentRoleLabel(t):"general",m=agentSystemPrompt(t),h=randomUUID();let g;if(l){if(l.aborted)return{ok:!1,error:"aborted"};g=()=>z(h),l.addEventListener("abort",g,{once:!0})}try{const e=await Y({class:r,model:n,mode:i,system:m,prompt:f,sessionId:h,depth:(c||0)+1,rootSessionId:d,rootOnDelta:u,statedMaxTokens:s,effort:a},(()=>{})),t=assistantText(e),o=e&&e.usage?{usage:e.usage}:{};return t?{ok:!0,output:t,...o}:{ok:!1,error:`subagent (${p}) produced no output`,...o}}catch(e){return{ok:!1,error:`subagent (${p}) failed: ${e&&e.message?e.message:e}`}}finally{l&&g&&l.removeEventListener("abort",g)}}function z(e){const t=p.get(e);return t&&t.abort(),{ok:Boolean(t)}}return{CLASSES:CLASSES,listClasses:async function(){return CLASSES.map((o=>{if("aegis"===o.class)return{...o,configured:Boolean(e.apiKey)};if("byok"===o.class){const e=(t.list()||[]).some((e=>!(!e||"string"!=typeof e.provider||!e.provider.startsWith("byok:"))&&(!!e.configured||Boolean(providerKeyFromEnv(e.provider.slice(BYOK_NAMESPACE_PREFIX.length))))));return{...o,configured:e}}if("local"===o.class)return{...o,configured:!0};if("pro"===o.class){const e=claudePro.claudeProStatus({env:process.env}),t=claudePro.seamAvailable();return{...o,configured:e.loggedIn,status:e,seam:t}}return{...o,configured:!1}}))},listModels:async function(o){if("aegis"===o){if(!e.apiKey)return{class:o,models:[],needsKey:!0};const t=await e.listModels();return{class:o,models:offerableCatalog(normalizeCatalog(t&&t.models))}}if("byok"===o){let r=[],n=null,s=!1,a=null;try{const t=await e.byokProviders();r=withUserModels(withCatalog(withByokAdditions(t&&t.providers||[]))),n=t&&t.fee||null}catch(e){r=[],s=!0,a=e&&e.message||String(e)}const i=[];for(const e of r){if(!e||!e.id)continue;const o=t.get(byokNamespace(e.id))||{},r=providerKeyRecord(e.id),n=r.key||"",s=Array.isArray(e.models)?e.models:[];for(const t of s){const s="string"==typeof t?t:t&&t.id;s&&i.push({id:`${e.id}:${s}`,label:`${e.label||e.id} — ${s}`,provider:e.id,configured:Boolean(o.configured||n),keyRejected:r.rejected||null})}}return{class:o,models:i,providers:r,needsProviderKey:i.length>0&&!i.some((e=>e.configured)),needsAegisKey:!e.apiKey,fee:n,providersFailed:s,providersError:a,unmatchedProviders:unmatchedUserProviders(r)}}if("local"===o){const e=(t.get("local")||{}).baseURL||c.DEFAULT_BASE,r=await c.probe(e);if(!r.running)return{class:o,models:[],baseURL:r.baseURL,needsDaemon:!0};let n=[],s=!0;try{n=await c.listTags(e)}catch{s=!1}return{class:o,models:n,baseURL:r.baseURL,listed:s}}if("pro"===o){const e=claudePro.claudeProStatus({env:process.env});return{class:o,models:claudePro.PRO_MODELS.map((t=>({id:t.id,label:t.label,note:t.note,configured:e.loggedIn}))),needsProviderKey:!1,needsAegisKey:!1,subscription:e.subscription,loggedIn:e.loggedIn,credentialFile:e.file,shadowed:e.shadowed||null,seam:claudePro.seamAvailable()}}throw new Error(`listModels: unknown model class ${JSON.stringify(o)} — this build ships 'aegis', 'byok', 'local' and 'pro' only`)},chat:Y,cancel:z,respondApproval:function(e,t){const o=O.get(e);return o?(O.delete(e),o.resolve("session"===t||"once"===t||"always"===t?t:"deny"),{ok:!0}):{ok:!1}},respondRoundsAsk:function(e,t){const o=N.get(e);return o?(N.delete(e),o.resolve(!0===t||"continue"===t),{ok:!0}):{ok:!1}},clearSessionApprovals:function(e){_.delete(e),T.delete(e),S.delete(e),A.delete(e);try{M.del(e,s)}catch{}return{ok:!0}},listUndoable:function(e){return(S.get(e)||[]).map((e=>({id:e.id,tool:e.tool,path:e.path,at:e.at}))).reverse()},undoMutation:function(e,t){const o=S.get(e)||[],r=t?o.findIndex((e=>e.id===t)):o.length-1;if(-1===r)return{ok:!1,error:t?`no undo record "${t}" for this conversation`:"nothing to undo in this conversation"};const n=o[r],s=I(n.path);if(!s||s.existed!==n.after.existed||s.content!==n.after.content)return{ok:!1,error:`${n.path} has changed since ${n.tool} ran — undo refused rather than overwriting work this session did not do. Resolve it by hand, or undo a different entry.`};try{n.before.existed?fs.writeFileSync(n.path,n.before.content,"utf8"):fs.unlinkSync(n.path)}catch(e){return{ok:!1,error:`undo failed: ${e&&e.message||e}`}}return o.splice(r,1),{ok:!0,path:n.path,restored:n.before.existed?"content":"deleted"}},settings:t,unloadLocalModels:function(){return c.unloadAll()},userModels:()=>loadUserModels(),addUserModel:(e,t)=>addUserModel(e,t),removeUserModel:(e,t)=>removeUserModel(e,t),discoverModels:async e=>{const o=String(null==e?"":e).trim().toLowerCase(),r=function(e){const o=String(null==e?"":e).trim().toLowerCase();if(!o)return"";try{if(t&&"function"==typeof t.rawKey){const e=t.rawKey(byokNamespace(o));if("string"==typeof e&&e.trim())return e.trim()}}catch{}return providerKeyFromEnv(o)}(o),n=await discoverVendorModels(o,{key:r,fetchImpl:d});if(!n||!n.ok)return n;const s=[];try{const e=loadUserModels().map;for(const t of Array.isArray(e[o])?e[o]:[])s.push(t)}catch{}return{...n,declared:s,endpoint:(vendorEndpointFor(o)||{}).url||""}},addUserModels:(e,t)=>{const o=Array.isArray(t)?t:[],r={provider:e,added:0,already:[],failed:[],capped:0,file:""};for(const t of o)try{const o=addUserModel(e,t);r.file=o.file||r.file,o.added?r.added+=1:r.already.push(o.model)}catch(e){const n=e&&e.message||String(e);if(/the cap/.test(n)){r.capped=o.length-r.added-r.already.length-r.failed.length;break}r.failed.push({id:String(t),reason:n})}return r},canDiscoverModels:e=>canDiscoverVendorModels(e),discoverableProviders:()=>discoverableProviders()}}module.exports={CLASSES:CLASSES,createLocalEngine:createLocalEngine,extractToolCalls:extractToolCalls,parseArgs:parseArgs,reasoningBudget:reasoningBudget,nativeEffort:nativeEffort,hostEnv:hostEnv};
@@ -134,7 +134,7 @@ const UNITS = Object.freeze([
134
134
  * (`tools/desktop-seal.mjs` in the source tree, `tools/obfuscate-faces.mjs`
135
135
  * after obfuscation), never by hand.
136
136
  */
137
- const SEALED = '2cc769c4c18eaba250015d15c7064f24076d14e0ff390e337abda71a23a4b34f';
137
+ const SEALED = '018887de47c1831abc08b71f33ca8fd0563f08f7a15547b4c2130a4d6567fcd9';
138
138
 
139
139
  /**
140
140
  * Ask the question. Never throws — a check that can break the program it is
@@ -1,3 +1,3 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- "use strict";const MAIN_CHAT_PROMPT='You are Aegiscodex, a terminal coding assistant working in the user\'s repository: read and reason about code, write and edit files, run shell commands, investigate bugs. Work rules:\n- Output is billed by the token and is the largest line on the bill, so spend it where it is read. Before a tool call, one short sentence on what you are about to find out. Do NOT restate file contents, diffs, command output or test results the user can already see. Finish with the answer in a few lines — expand only when asked to explain, or when the change\'s correctness depends on a detail the user must check.\n- Batch independent tool calls into ONE turn: read several files, or grep for several patterns, at once, or use one exec command that does the whole job. Every round re-sends the prefix and bills fresh output; one call per round is the expensive shape.\n- Edit in one call, not one hunk per round: editFile takes an `edits` array, so every hunk you already know about for one file goes in a single call. A fix you can see is a fix you can also write without asking the tool anything in between.\n- Run the thing you changed before you call it done. A patch you never executed is a hypothesis; when the repo has a test or repro command, run it (or the narrowest slice of it) and report what it printed. If you cannot run it, say which command you would have run. - Use tools silently. A one-line reason is enough; do not narrate your plan as a story. - Never claim what a tool found or what a command returned before the tool actually runs. Report only the results you really received. - Before starting a fix or feature, check whether they have asked for it before and whether it was delivered: recalled memory, `queue.jsonl`, `PLAN.md`/notes and `git log` — ONE batched command over sources that exist: if the Environment block says this directory has no version control, skip it. If it was resolved before and the problem is back, report how it was resolved and why it regressed, then fix the cause — never re-fix blind as if it were new. If it was never met, say so plainly before starting. - Match the response to the request. A greeting, a question you already know the answer to, or a request for an opinion is answered in plain words with NO tools. Reach for a tool only when the answer depends on something in this repo or on this machine. "hey" is not a task.\n- WHEN THE USER HAS ASKED FOR WORK: act, don\'t just inspect. After at most 2 rounds of reading or exploration, start making changes with writeFile or editFile. Reconnaissance is not progress — implement, then verify. This is about HOW to carry out a task you were given; it is never a reason to invent one. Never write or modify a file the user did not ask you to touch.\n- Zero tolerance for stalling: once the cause is identified and only the edit remains, make it in the same turn. Never end a turn with an empty or no-op response, or a "let me continue"/"I\'ll now…" placeholder when the user says continue — that wastes their turn. This has been flagged as non-compliance before; treat it as a hard rule. - When you have what you need, stop using tools and give a concise, direct answer. Never end a turn with an intention like "Let me check…" — that is not an answer. - When a focused multi-step sub-task can be delegated, use the task tool to spawn a specialist subagent rather than doing it inline. - If the user references a workflow you don\'t recognize, inspect the repo/scripts for that mechanism before acting.',TOOL_LINE="Tools: readFile, writeFile, editFile, listDir, glob, grep, exec, websearch, task. Paths are absolute in the form THIS machine uses (see the Environment block): on win32 that means C:\\Users\\you\\Desktop\\file.txt, not /home/you/Desktop/file.txt or /tmp/file.txt. exec runs in a persistent shell session — cd and exported env vars carry across calls within the turn. websearch reaches the web for facts this repo cannot answer. task spawns a specialist subagent (its own tool loop, same model).";function languageLine(e){if("string"==typeof e)return e.trim();if(!e||"object"!=typeof e)return"";if("string"==typeof e.value&&e.value.trim())return e.value.trim();const t="string"==typeof e.name?e.name.trim():"",n="string"==typeof e.code?e.code.trim():"string"==typeof e.key?e.key.trim():"";return t&&n?`${t} (${n})`:t||n}function environmentPreamble(e={}){const{platform:t,arch:n,homedir:o,desktopdir:r,dataDir:s,locale:a,localeName:i,languages:h,cwd:l,vcs:c,shell:d,shellKind:u,roots:p,appVersion:m,model:f}=e||{},y=[];if(t&&y.push(`platform: ${t}${n?` (${n})`:""}`),a){const e=String(a).split("-")[0].toLowerCase(),t=i?` (${i})`:"";y.push("en"===e?`locale: ${a}${t}`:`locale: ${a}${t} — the user's own machine and account run in this language, so expect requests written in it and answer in the language the user writes to you in. Use this to resolve an otherwise ambiguous request (a bare path, a pasted error, a one-word command) — never to override a request written in another language.`)}const w=(Array.isArray(h)?h:[]).map((e=>languageLine(e))).filter(Boolean);w.length&&y.push(`recorded language evidence from the user's own saved writing: ${w.join("; ")} — the language of the request in front of you always wins; this is evidence, not an instruction to switch`),o&&y.push(`home directory: ${o}`),r&&y.push(`desktop directory: ${r} — use this exact path when the user says "my desktop"; do NOT build it yourself from the home directory`),s&&y.push(`AEGIS data directory: ${s} — the store itself (config, sessions, credentials, queue). Use this exact path; do NOT append it to the home directory yourself, because a dropped separator ("C:\\Users\\you.aegiscode") names a path that does not exist and looks like an empty directory rather than a mistake`),l&&y.push(`working directory: ${l}`),"git"===c?y.push("version control: this directory IS inside a git work tree, so `git log`, `git diff` and `git status` are usable for checking what was already done"):""===c&&y.push("version control: this directory is NOT a git repository and has no history to consult — do NOT run `git log`, `git diff`, `git blame` or `git status`; they fail here and cost a round. Read the files that exist instead"),d&&y.push(`exec shell: ${d}${u?` (${u})`:""}`),f&&y.push(`model: ${f}`),m&&y.push(`AEGIS Desktop ${m}`);const g=Array.isArray(p)?p.filter(Boolean):[],b=[];y.length&&b.push(y.join("\n")),g.length&&b.push(`repo roots:\n${g.map((e=>` - ${e}`)).join("\n")}`);const v=commandDialectLine(t,u);return v&&b.push(v),b.length?`# Environment\n${b.join("\n")}`:""}function commandDialectLine(e,t){return e?"win32"===e?`This is Windows: exec runs ${"powershell"===t?"PowerShell":"a Windows shell"}, so use Windows-native commands — Get-ChildItem/dir, Get-Content/type, Select-String/findstr, where, New-Item -ItemType Directory — NOT ls, cat, grep, mkdir -p, touch or rm -rf, which do not exist here. Separate paths with \\, and never assume /tmp, /usr or /home exist.`:"darwin"===e?"This is macOS: exec runs a POSIX shell and the standard Unix commands are available, but the userland is BSD, not GNU — sed -i needs an argument (sed -i ''), and readlink -f, date -d and sed -r are absent. Prefer portable forms, or python3.":"This is a POSIX host: the standard Unix commands are available in exec.":""}const PROJECT_DOC_NAMES=["AEGIS.md","AGENTS.md","CLAUDE.md"],PROJECT_DOC_MAX_CHARS=8e3;function readProjectDoc(e,t={}){if(!e)return"";let n=t.fs,o=t.path;try{n||(n=require("node:fs")),o||(o=require("node:path"))}catch(e){return""}for(const t of PROJECT_DOC_NAMES){let r;try{const s=o.join(e,t),a=n.statSync(s);if(!a||!a.isFile())continue;r=n.readFileSync(s,"utf8")}catch(e){continue}if("string"!=typeof r)continue;const s=r.trim();if(s)return`# Project instructions (${t})\nThese are this repository's own rules. They outrank the generic work rules above wherever the two disagree, and they are the source for build/test/lint commands — prefer them over re-deriving commands by exploring.\n\n`+(s.length>PROJECT_DOC_MAX_CHARS?s.slice(0,PROJECT_DOC_MAX_CHARS)+`\n\n[${t} truncated at ${PROJECT_DOC_MAX_CHARS} characters — read the file for the rest]`:s)}return""}function buildSystemPrompt(e={}){const t=[MAIN_CHAT_PROMPT,TOOL_LINE],n="string"==typeof e.projectDoc&&e.projectDoc.trim()?e.projectDoc.trim():readProjectDoc(e.cwd||process.cwd());n&&t.push(n);const o=environmentPreamble(e);return o&&t.push(o),t.join("\n\n")}module.exports={MAIN_CHAT_PROMPT:MAIN_CHAT_PROMPT,TOOL_LINE:TOOL_LINE,PROJECT_DOC_NAMES:PROJECT_DOC_NAMES,PROJECT_DOC_MAX_CHARS:PROJECT_DOC_MAX_CHARS,environmentPreamble:environmentPreamble,commandDialectLine:commandDialectLine,readProjectDoc:readProjectDoc,buildSystemPrompt:buildSystemPrompt};
3
+ "use strict";const MAIN_CHAT_PROMPT='You are Aegiscodex, a terminal coding assistant working in the user\'s repository: read and reason about code, write and edit files, run shell commands, investigate bugs. Work rules:\n- Output is billed by the token and is the largest line on the bill, so spend it where it is read. Before a tool call, one short sentence on what you are about to find out. Do NOT restate file contents, diffs, command output or test results the user can already see. Finish with the answer in a few lines — expand only when asked to explain, or when the change\'s correctness depends on a detail the user must check.\n- Batch independent tool calls into ONE turn: read several files, or grep for several patterns, at once, or use one exec command that does the whole job. Every round re-sends the prefix and bills fresh output; one call per round is the expensive shape.\n- Edit in one call, not one hunk per round: editFile takes an `edits` array, so every hunk you already know about for one file goes in a single call. A fix you can see is a fix you can also write without asking the tool anything in between.\n- Run the thing you changed before you call it done. A patch you never executed is a hypothesis; when the repo has a test or repro command, run it (or the narrowest slice of it) and report what it printed. If you cannot run it, say which command you would have run. - Use tools silently. A one-line reason is enough; do not narrate your plan as a story. - Never claim what a tool found or what a command returned before the tool actually runs. Report only the results you really received. - Before starting a fix or feature, check whether they have asked for it before and whether it was delivered: recalled memory, `queue.jsonl`, `PLAN.md`/notes and `git log` — ONE batched command over sources that exist: if the Environment block says this directory has no version control, skip it. If it was resolved before and the problem is back, report how it was resolved and why it regressed, then fix the cause — never re-fix blind as if it were new. If it was never met, say so plainly before starting. - Match the response to the request. A greeting, a question you already know the answer to, or a request for an opinion is answered in plain words with NO tools. Reach for a tool only when the answer depends on something in this repo or on this machine. "hey" is not a task.\n- WHEN THE USER HAS ASKED FOR WORK: act, don\'t just inspect. After at most 2 rounds of reading or exploration, start making changes with writeFile or editFile. Reconnaissance is not progress — implement, then verify. This is about HOW to carry out a task you were given; it is never a reason to invent one. Never write or modify a file the user did not ask you to touch.\n- Zero tolerance for stalling: once the cause is identified and only the edit remains, make it in the same turn. Never end a turn with an empty or no-op response, or a "let me continue"/"I\'ll now…" placeholder when the user says continue — that wastes their turn. This has been flagged as non-compliance before; treat it as a hard rule. - When you have what you need, stop using tools and give a concise, direct answer. Never end a turn with an intention like "Let me check…" — that is not an answer. - When a focused multi-step sub-task can be delegated, use the task tool to spawn a specialist subagent rather than doing it inline. - If the user references a workflow you don\'t recognize, inspect the repo/scripts for that mechanism before acting.',TOOL_LINE="Tools: readFile, writeFile, editFile, listDir, glob, grep, exec, websearch, task. Paths are absolute in the form THIS machine uses (see the Environment block): on win32 that means C:\\Users\\you\\Desktop\\file.txt, not /home/you/Desktop/file.txt or /tmp/file.txt. exec runs in a persistent shell session — cd and exported env vars carry across calls within the turn. websearch reaches the web for facts this repo cannot answer. task spawns a specialist subagent (its own tool loop, same model).";function languageLine(e){if("string"==typeof e)return e.trim();if(!e||"object"!=typeof e)return"";if("string"==typeof e.value&&e.value.trim())return e.value.trim();const t="string"==typeof e.name?e.name.trim():"",n="string"==typeof e.code?e.code.trim():"string"==typeof e.key?e.key.trim():"";return t&&n?`${t} (${n})`:t||n}function environmentPreamble(e={}){const{platform:t,arch:n,homedir:o,desktopdir:r,dataDir:s,locale:a,localeName:i,languages:h,cwd:l,vcs:c,shell:d,shellKind:u,roots:p,appVersion:m,model:f}=e||{},y=[];if(t&&y.push(`platform: ${t}${n?` (${n})`:""}`),a){const e=String(a).split("-")[0].toLowerCase(),t=i?` (${i})`:"";y.push("en"===e?`locale: ${a}${t}`:`locale: ${a}${t} — the user's own machine and account run in this language, so expect requests written in it and answer in the language the user writes to you in. Use this to resolve an otherwise ambiguous request (a bare path, a pasted error, a one-word command) — never to override a request written in another language.`)}const w=(Array.isArray(h)?h:[]).map((e=>languageLine(e))).filter(Boolean);w.length&&y.push(`recorded language evidence from the user's own saved writing: ${w.join("; ")} — the language of the request in front of you always wins; this is evidence, not an instruction to switch`),o&&y.push(`home directory: ${o}`),r&&y.push(`desktop directory: ${r} — use this exact path when the user says "my desktop"; do NOT build it yourself from the home directory`),s&&y.push(`AEGIS data directory: ${s} — the store itself (config, sessions, credentials, queue). Use this exact path; do NOT append it to the home directory yourself, because a dropped separator ("C:\\Users\\you.aegiscode") names a path that does not exist and looks like an empty directory rather than a mistake`),l&&y.push(`working directory: ${l}`),"git"===c?y.push("version control: this directory IS inside a git work tree, so `git log`, `git diff` and `git status` are usable for checking what was already done"):""===c&&y.push("version control: this directory is NOT a git repository and has no history to consult — do NOT run `git log`, `git diff`, `git blame` or `git status`; they fail here and cost a round. Read the files that exist instead"),d&&y.push(`exec shell: ${d}${u?` (${u})`:""}`),f&&y.push(`model: ${f}`),m&&y.push(`aegis one ${m}`);const g=Array.isArray(p)?p.filter(Boolean):[],b=[];y.length&&b.push(y.join("\n")),g.length&&b.push(`repo roots:\n${g.map((e=>` - ${e}`)).join("\n")}`);const v=commandDialectLine(t,u);return v&&b.push(v),b.length?`# Environment\n${b.join("\n")}`:""}function commandDialectLine(e,t){return e?"win32"===e?`This is Windows: exec runs ${"powershell"===t?"PowerShell":"a Windows shell"}, so use Windows-native commands — Get-ChildItem/dir, Get-Content/type, Select-String/findstr, where, New-Item -ItemType Directory — NOT ls, cat, grep, mkdir -p, touch or rm -rf, which do not exist here. Separate paths with \\, and never assume /tmp, /usr or /home exist.`:"darwin"===e?"This is macOS: exec runs a POSIX shell and the standard Unix commands are available, but the userland is BSD, not GNU — sed -i needs an argument (sed -i ''), and readlink -f, date -d and sed -r are absent. Prefer portable forms, or python3.":"This is a POSIX host: the standard Unix commands are available in exec.":""}const PROJECT_DOC_NAMES=["AEGIS.md","AGENTS.md","CLAUDE.md"],PROJECT_DOC_MAX_CHARS=8e3;function readProjectDoc(e,t={}){if(!e)return"";let n=t.fs,o=t.path;try{n||(n=require("node:fs")),o||(o=require("node:path"))}catch(e){return""}for(const t of PROJECT_DOC_NAMES){let r;try{const s=o.join(e,t),a=n.statSync(s);if(!a||!a.isFile())continue;r=n.readFileSync(s,"utf8")}catch(e){continue}if("string"!=typeof r)continue;const s=r.trim();if(s)return`# Project instructions (${t})\nThese are this repository's own rules. They outrank the generic work rules above wherever the two disagree, and they are the source for build/test/lint commands — prefer them over re-deriving commands by exploring.\n\n`+(s.length>PROJECT_DOC_MAX_CHARS?s.slice(0,PROJECT_DOC_MAX_CHARS)+`\n\n[${t} truncated at ${PROJECT_DOC_MAX_CHARS} characters — read the file for the rest]`:s)}return""}function buildSystemPrompt(e={}){const t=[MAIN_CHAT_PROMPT,TOOL_LINE],n="string"==typeof e.projectDoc&&e.projectDoc.trim()?e.projectDoc.trim():readProjectDoc(e.cwd||process.cwd());n&&t.push(n);const o=environmentPreamble(e);return o&&t.push(o),t.join("\n\n")}module.exports={MAIN_CHAT_PROMPT:MAIN_CHAT_PROMPT,TOOL_LINE:TOOL_LINE,PROJECT_DOC_NAMES:PROJECT_DOC_NAMES,PROJECT_DOC_MAX_CHARS:PROJECT_DOC_MAX_CHARS,environmentPreamble:environmentPreamble,commandDialectLine:commandDialectLine,readProjectDoc:readProjectDoc,buildSystemPrompt:buildSystemPrompt};
@@ -503,7 +503,7 @@ function normalizeArgs(name, args, ctx = {}) {
503
503
  *
504
504
  * `process.cwd()` is wrong here and was visibly wrong off Linux: the Electron
505
505
  * main process inherits whatever the OS launched the app from — `/` from a .desktop
506
- * entry, `C:\Program Files\AEGIS Desktop` from a Windows shortcut — so a bare
506
+ * entry, `C:\Program Files\aegis one` from a Windows shortcut — so a bare
507
507
  * `listDir`/`glob`/`grep` searched the install directory instead of the user's
508
508
  * repo. It stays the fallback for a direct call that supplies no ctx.
509
509
  */
@@ -1,3 +1,3 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- "use strict";const fs=require("node:fs"),path=require("node:path"),{execFileSync:execFileSync}=require("node:child_process"),prefs=(()=>{try{return require("../../client/prefs.js")}catch{return require("../vendor/prefs.js")}})(),credentials=(()=>{try{return require("../../client/credentials.js")}catch{return require("../vendor/credentials.js")}})(),localTransport=require("./local/local.js"),LOCAL_NAMESPACE="local",SETTINGS_FILE="settings.json",AEGIS_KEY_NAMESPACE="__aegis",LEGACY_AEGIS_NAMESPACE="aegis",QUICK_LAUNCHER_NAMESPACE="__quickLauncher",DEFAULT_QUICK_LAUNCHER_SHORTCUT="CmdOrCtrl+Shift+Space",VAULT_BACKEND_NAMESPACE="__vaultBackend",DEFAULT_VAULT_BACKEND="aegiscloud",VAULT_BACKEND_VALUES=Object.freeze(["aegiscloud","drive","off"]),CONFIRM_MODE_NAMESPACE="__confirmMode",MEMORY_PERSIST_NAMESPACE="__memoryPersist",AVATAR_NAMESPACE="__avatar",TELEMETRY_NAMESPACE="__telemetry",AUTO_DRAIN_NAMESPACE="__autoDrain",AUTO_MINT_NAMESPACE="__autoMint",AUTO_DRAIN_INTERVAL_DEFAULT_MS=6e4,AUTO_DRAIN_INTERVAL_MIN_MS=15e3,AUTO_DRAIN_INTERVAL_MAX_MS=18e5,RESERVED_NAMESPACES=Object.freeze(["__aegis","aegis","__quickLauncher","__vaultBackend","__confirmMode","__memoryPersist","__avatar","__telemetry","__autoDrain","__autoMint"]),AVATAR_MOTION_MODES=Object.freeze(["system","full","minimal"]);function isReservedNamespace(e){return RESERVED_NAMESPACES.includes(e)}function maskKey(e){return e?e.length<=10?"configured":`${e.slice(0,9)}…${e.slice(-4)}`:null}const IS_WIN32="win32"===process.platform;function restrictFile(e){if(IS_WIN32){const n=process.env.USERNAME||process.env.USER||process.env.USERDOMAIN;if(!n)return void console.error(`[settings] cannot restrict ${e}: no current user to grant (USERNAME unset)`);try{execFileSync("icacls",[e,"/inheritance:r","/grant:r",`${n}:(F)`],{stdio:"ignore"})}catch(n){console.error(`[settings] failed to restrict ACL on ${e}: ${n.message}`)}}else try{fs.chmodSync(e,384)}catch(n){console.error(`[settings] failed to chmod ${e} to 0600: ${n.message}`)}}function createSettingsStore({dir:e,safeStorage:n,prefsDir:t,env:r}={}){if(!e)throw new Error("createSettingsStore requires a storage dir");const o=path.join(e,SETTINGS_FILE),i=(()=>{const e=null==t?"":String(t).trim();return e?path.resolve(e):credentials.aegisHome(r)})(),s=(()=>{try{return prefs.adopt({dir:i,legacyDir:e})}catch(e){return(process.env.AEGISCODE_DEBUG||process.env.AEGIS_HIST_DEBUG)&&process.stderr.write(`aegis-desktop: shared-preference adoption failed: ${e.message}\n`),{adopted:!1,keys:[],reason:`adoption failed: ${e.message}`}}})();function a(){try{return prefs.load({dir:i})}catch{return{}}}function c(e){if(!prefs.SHARED_PREF_KEYS.includes(e))throw new Error(`"${e}" is not a shared preference (see client/prefs.js SHARED_PREF_KEYS)`);const n=a()[e];return void 0===n?null:n}const u=()=>Boolean(n&&"function"==typeof n.isEncryptionAvailable&&n.isEncryptionAvailable());function _(e){return null==e?null:u()?n.encryptString(String(e)).toString("base64"):Buffer.from(String(e),"utf8").toString("base64")}function l(e){if(!e)return null;try{const t=Buffer.from(String(e),"base64");return u()?n.decryptString(t):t.toString("utf8")}catch{return null}}function d(){try{return JSON.parse(fs.readFileSync(o,"utf8"))||{}}catch{return{}}}function f(e){fs.mkdirSync(path.dirname(o),{recursive:!0});const n=`${o}.tmp-${process.pid}`;fs.writeFileSync(n,JSON.stringify(e,null,2),{mode:384}),fs.renameSync(n,o),restrictFile(o)}function A(e){if(isReservedNamespace(e))throw new Error(`reserved namespace "${e}" is not a provider config — use setAegisKey()/aegisRawKey() for the AEGIS key`)}function E(e){const n=d()[e]||{},t=l(n.key);return{provider:e,baseURL:n.baseURL||"",configured:Boolean(t),keyMask:maskKey(t)}}function S(){const e=l((d().__aegis||{}).key);return{configured:Boolean(e),keyMask:maskKey(e)}}function m(){const e=d().__quickLauncher||{},n="string"==typeof e.shortcut&&e.shortcut.trim()?e.shortcut.trim():"CmdOrCtrl+Shift+Space";return{enabled:Boolean(e.enabled),shortcut:n}}function M(){const e=d().__vaultBackend||{};return{backend:VAULT_BACKEND_VALUES.includes(e.backend)?e.backend:"aegiscloud"}}function p(){const e=a();if("boolean"==typeof e.confirmMode)return{enabled:e.confirmMode,source:"config"};const n=d().__confirmMode||{};return void 0===n.enabled?{enabled:!0,source:"default"}:{enabled:Boolean(n.enabled),source:"config"}}function y(){const e=a().sandboxPolicy;return e&&"object"==typeof e?e:null}function g(){const e=a();return"string"==typeof e.permissionMode?e.permissionMode:null}function N(){return!0===(d().__telemetry||{}).enabled}function b(){const e=a();if("boolean"==typeof e.memoryPersist)return{enabled:e.memoryPersist,source:"config"};const n=d().__memoryPersist||{};return void 0===n.enabled?{enabled:!0,source:"default"}:{enabled:Boolean(n.enabled),source:"config"}}function v(){const e=d().__avatar||{};return{enabled:void 0===e.enabled||Boolean(e.enabled),showLevel:void 0===e.showLevel||Boolean(e.showLevel),motion:AVATAR_MOTION_MODES.includes(e.motion)?e.motion:"system"}}function R(){const e=d().__avatar||{};return{...v(),source:void 0===e.enabled?"default":"config"}}function T(e){const n=Number(e);if(!Number.isFinite(n))return 6e4;const t=Math.round(n);return t<15e3||t>18e5?6e4:t}function h(){const e=d().__autoDrain||{};return{enabled:!1!==e.enabled,intervalMs:T(e.intervalMs)}}function C(){const e=d().__autoDrain||{};return{...h(),source:void 0===e.enabled?"default":"config"}}function I(){const e=d().__autoMint||{};return{enabled:!1!==e.enabled,publish:!0===e.publish}}function L(){const e=d().__autoMint||{};return{...I(),source:void 0===e.enabled?"default":"config"}}return{file:o,sharedDir:i,adoption:s,sharedFile:function(){return prefs.prefsFile({dir:i})},getSharedPref:c,setSharedPref:function(e,n){if(!prefs.SHARED_PREF_KEYS.includes(e))throw new Error(`"${e}" is not a shared preference (see client/prefs.js SHARED_PREF_KEYS)`);return prefs.set({[e]:n},{dir:i}),c(e)},get:E,set:function(e,{baseURL:n,key:t}={}){A(e);let r=n;if("local"===e&&n){const e=localTransport.remoteRefusal(n);if(e)throw e;r=localTransport.normalizeBase(n)}const o=d(),i=o[e]||{};return void 0!==r&&(i.baseURL=r),void 0!==t&&(i.key=t?_(t):null),o[e]=i,f(o),E(e)},rawKey:function(e){return l((d()[e]||{}).key)},remove:function(e){A(e);const n=d();return delete n[e],f(n),{ok:!0}},list:function(){const e=d();return Object.keys(e).filter((e=>!isReservedNamespace(e))).map((e=>E(e)))},maskKey:maskKey,aegisKey:S,aegisRawKey:function(){return l((d().__aegis||{}).key)},aegisKeySavedAt:function(){return(d().__aegis||{}).savedAt||null},setAegisKey:function(e){const n=d();return n.__aegis={...n.__aegis||{},key:e?_(e):null,savedAt:e?(new Date).toISOString():null},f(n),S()},migrateLegacyAegisKey:function(){try{const e=d();if(!e.aegis)return{migrated:!1};const n=e.aegis||{},t=e.__aegis||{},r={...e};return n.key&&!t.key&&(r.__aegis={...t,key:n.key}),delete r.aegis,f(r),{migrated:!0}}catch{return{migrated:!1}}},quickLauncherConfig:m,setQuickLauncherConfig:function({enabled:e,shortcut:n}={}){const t=d();return t.__quickLauncher={enabled:Boolean(e),shortcut:"string"==typeof n&&n.trim()?n.trim():"CmdOrCtrl+Shift+Space"},f(t),m()},vaultBackendConfig:M,setVaultBackendConfig:function(e){if(!VAULT_BACKEND_VALUES.includes(e))return M();const n=d();return n.__vaultBackend={backend:e},f(n),M()},getConfirmMode:function(){return p().enabled},setConfirmMode:function(e){prefs.set({confirmMode:Boolean(e)},{dir:i});const n=d();return void 0!==n.__confirmMode&&(delete n.__confirmMode,f(n)),p().enabled},confirmModeState:p,getPermissionMode:g,setPermissionMode:function(e){if(null==e||""===e||"off"===e||"none"===e)return prefs.remove("permissionMode",{dir:i}),null;const n=String(e),t=function(){const e=[path.join(__dirname,"..","..","one","src","permissions.js"),path.join(__dirname,"..","vendor","one","src","permissions.js")];for(const n of e)try{const e=require(n);if(e&&Array.isArray(e.PERMISSION_MODES)&&e.PERMISSION_MODES.length)return[...e.PERMISSION_MODES]}catch{}return["acceptEdits","auto","bypassPermissions","manual","dontAsk","plan"]}();if(!t.includes(n))throw new Error(`"${n}" is not one of ${t.join("|")} (or 'off' to clear it)`);return prefs.set({permissionMode:n},{dir:i}),g()},getSandboxPolicy:y,setSandboxPolicy:function(e){return e&&"object"==typeof e?(prefs.set({sandboxPolicy:e},{dir:i}),y()):(prefs.set({sandboxPolicy:null},{dir:i}),null)},getTelemetryOptIn:N,setTelemetryOptIn:function(e){const n=d();return n.__telemetry={enabled:Boolean(e)},f(n),N()},getMemoryPersist:function(){return b().enabled},memoryPersistState:b,setMemoryPersist:function(e){prefs.set({memoryPersist:Boolean(e)},{dir:i});const n=d();return void 0!==n.__memoryPersist&&(delete n.__memoryPersist,f(n)),b()},getAvatar:v,avatarState:R,setAvatar:function(e={}){const n=v(),t=e&&"object"==typeof e?e:{},r={enabled:void 0===t.enabled?n.enabled:Boolean(t.enabled),showLevel:void 0===t.showLevel?n.showLevel:Boolean(t.showLevel),motion:AVATAR_MOTION_MODES.includes(t.motion)?t.motion:n.motion},o=d();return o.__avatar=r,f(o),R()},getAutoDrain:h,autoDrainState:C,setAutoDrain:function(e={}){const n=h(),t=e&&"object"==typeof e?e:{},r=d();return r.__autoDrain={enabled:void 0===t.enabled?n.enabled:Boolean(t.enabled),intervalMs:void 0===t.intervalMs?n.intervalMs:T(t.intervalMs)},f(r),C()},getAutoMint:I,autoMintState:L,setAutoMint:function(e={}){const n=I(),t=e&&"object"==typeof e?e:{},r=d();return r.__autoMint={enabled:void 0===t.enabled?n.enabled:Boolean(t.enabled),publish:void 0===t.publish?n.publish:Boolean(t.publish)},f(r),L()},clampAutoDrainInterval:T}}module.exports={SETTINGS_FILE:SETTINGS_FILE,AEGIS_KEY_NAMESPACE:"__aegis",LEGACY_AEGIS_NAMESPACE:"aegis",QUICK_LAUNCHER_NAMESPACE:"__quickLauncher",VAULT_BACKEND_NAMESPACE:"__vaultBackend",CONFIRM_MODE_NAMESPACE:"__confirmMode",MEMORY_PERSIST_NAMESPACE:"__memoryPersist",AVATAR_NAMESPACE:"__avatar",TELEMETRY_NAMESPACE:"__telemetry",AUTO_DRAIN_NAMESPACE:"__autoDrain",AUTO_MINT_NAMESPACE:"__autoMint",AUTO_DRAIN_INTERVAL_DEFAULT_MS:6e4,AUTO_DRAIN_INTERVAL_MIN_MS:15e3,AUTO_DRAIN_INTERVAL_MAX_MS:18e5,AVATAR_MOTION_MODES:AVATAR_MOTION_MODES,DEFAULT_QUICK_LAUNCHER_SHORTCUT:"CmdOrCtrl+Shift+Space",DEFAULT_VAULT_BACKEND:"aegiscloud",VAULT_BACKEND_VALUES:VAULT_BACKEND_VALUES,RESERVED_NAMESPACES:RESERVED_NAMESPACES,isReservedNamespace:isReservedNamespace,maskKey:maskKey,createSettingsStore:createSettingsStore};
3
+ "use strict";const fs=require("node:fs"),path=require("node:path"),{execFileSync:execFileSync}=require("node:child_process"),prefs=(()=>{try{return require("../../client/prefs.js")}catch{return require("../vendor/prefs.js")}})(),credentials=(()=>{try{return require("../../client/credentials.js")}catch{return require("../vendor/credentials.js")}})(),localTransport=require("./local/local.js"),LOCAL_NAMESPACE="local",SETTINGS_FILE="settings.json",AEGIS_KEY_NAMESPACE="__aegis",LEGACY_AEGIS_NAMESPACE="aegis",QUICK_LAUNCHER_NAMESPACE="__quickLauncher",DEFAULT_QUICK_LAUNCHER_SHORTCUT="CmdOrCtrl+Shift+Space",VAULT_BACKEND_NAMESPACE="__vaultBackend",DEFAULT_VAULT_BACKEND="aegiscloud",VAULT_BACKEND_VALUES=Object.freeze(["aegiscloud","drive","off"]),CONFIRM_MODE_NAMESPACE="__confirmMode",FONT_SCALE_NAMESPACE="__fontScale",ACCENT_NAMESPACE="__accent",MEMORY_PERSIST_NAMESPACE="__memoryPersist",AVATAR_NAMESPACE="__avatar",TELEMETRY_NAMESPACE="__telemetry",AUTO_DRAIN_NAMESPACE="__autoDrain",AUTO_MINT_NAMESPACE="__autoMint",AUTO_DRAIN_INTERVAL_DEFAULT_MS=6e4,AUTO_DRAIN_INTERVAL_MIN_MS=15e3,AUTO_DRAIN_INTERVAL_MAX_MS=18e5,RESERVED_NAMESPACES=Object.freeze(["__aegis","aegis","__quickLauncher","__vaultBackend","__confirmMode","__memoryPersist","__avatar","__telemetry","__autoDrain","__autoMint"]),AVATAR_MOTION_MODES=Object.freeze(["system","full","minimal"]);function isReservedNamespace(e){return RESERVED_NAMESPACES.includes(e)}function maskKey(e){return e?e.length<=10?"configured":`${e.slice(0,9)}…${e.slice(-4)}`:null}const IS_WIN32="win32"===process.platform;function restrictFile(e){if(IS_WIN32){const n=process.env.USERNAME||process.env.USER||process.env.USERDOMAIN;if(!n)return void console.error(`[settings] cannot restrict ${e}: no current user to grant (USERNAME unset)`);try{execFileSync("icacls",[e,"/inheritance:r","/grant:r",`${n}:(F)`],{stdio:"ignore"})}catch(n){console.error(`[settings] failed to restrict ACL on ${e}: ${n.message}`)}}else try{fs.chmodSync(e,384)}catch(n){console.error(`[settings] failed to chmod ${e} to 0600: ${n.message}`)}}function createSettingsStore({dir:e,safeStorage:n,prefsDir:t,env:r}={}){if(!e)throw new Error("createSettingsStore requires a storage dir");const o=path.join(e,SETTINGS_FILE),i=(()=>{const e=null==t?"":String(t).trim();return e?path.resolve(e):credentials.aegisHome(r)})(),s=(()=>{try{return prefs.adopt({dir:i,legacyDir:e})}catch(e){return(process.env.AEGISCODE_DEBUG||process.env.AEGIS_HIST_DEBUG)&&process.stderr.write(`aegis-desktop: shared-preference adoption failed: ${e.message}\n`),{adopted:!1,keys:[],reason:`adoption failed: ${e.message}`}}})();function a(){try{return prefs.load({dir:i})}catch{return{}}}function c(e){if(!prefs.SHARED_PREF_KEYS.includes(e))throw new Error(`"${e}" is not a shared preference (see client/prefs.js SHARED_PREF_KEYS)`);const n=a()[e];return void 0===n?null:n}const u=()=>Boolean(n&&"function"==typeof n.isEncryptionAvailable&&n.isEncryptionAvailable());function _(e){return null==e?null:u()?n.encryptString(String(e)).toString("base64"):Buffer.from(String(e),"utf8").toString("base64")}function l(e){if(!e)return null;try{const t=Buffer.from(String(e),"base64");return u()?n.decryptString(t):t.toString("utf8")}catch{return null}}function d(){try{return JSON.parse(fs.readFileSync(o,"utf8"))||{}}catch{return{}}}function f(e){fs.mkdirSync(path.dirname(o),{recursive:!0});const n=`${o}.tmp-${process.pid}`;fs.writeFileSync(n,JSON.stringify(e,null,2),{mode:384}),fs.renameSync(n,o),restrictFile(o)}function A(e){if(isReservedNamespace(e))throw new Error(`reserved namespace "${e}" is not a provider config — use setAegisKey()/aegisRawKey() for the AEGIS key`)}function E(e){const n=d()[e]||{},t=l(n.key);return{provider:e,baseURL:n.baseURL||"",configured:Boolean(t),keyMask:maskKey(t)}}function S(){const e=l((d().__aegis||{}).key);return{configured:Boolean(e),keyMask:maskKey(e)}}function m(e){return Number.isFinite(e)?Math.min(1.3,Math.max(.85,Math.round(100*e)/100)):1}function M(){return m((d().__fontScale||{}).scale)}const p=["default","cobalt","amber"];function g(e){const n="string"==typeof e?e.trim().toLowerCase():"";return p.includes(n)?n:"default"}function y(){return g((d().__accent||{}).name)}function N(){const e=d().__quickLauncher||{},n="string"==typeof e.shortcut&&e.shortcut.trim()?e.shortcut.trim():"CmdOrCtrl+Shift+Space";return{enabled:Boolean(e.enabled),shortcut:n}}function b(){const e=d().__vaultBackend||{};return{backend:VAULT_BACKEND_VALUES.includes(e.backend)?e.backend:"aegiscloud"}}function v(){const e=a();if("boolean"==typeof e.confirmMode)return{enabled:e.confirmMode,source:"config"};const n=d().__confirmMode||{};return void 0===n.enabled?{enabled:!0,source:"default"}:{enabled:Boolean(n.enabled),source:"config"}}function C(){const e=a().sandboxPolicy;return e&&"object"==typeof e?e:null}function T(){const e=a();return"string"==typeof e.permissionMode?e.permissionMode:null}function h(){return!0===(d().__telemetry||{}).enabled}function R(){const e=a();if("boolean"==typeof e.memoryPersist)return{enabled:e.memoryPersist,source:"config"};const n=d().__memoryPersist||{};return void 0===n.enabled?{enabled:!0,source:"default"}:{enabled:Boolean(n.enabled),source:"config"}}function I(){const e=d().__avatar||{};return{enabled:void 0===e.enabled||Boolean(e.enabled),showLevel:void 0===e.showLevel||Boolean(e.showLevel),motion:AVATAR_MOTION_MODES.includes(e.motion)?e.motion:"system"}}function L(){const e=d().__avatar||{};return{...I(),source:void 0===e.enabled?"default":"config"}}function D(e){const n=Number(e);if(!Number.isFinite(n))return 6e4;const t=Math.round(n);return t<15e3||t>18e5?6e4:t}function P(){const e=d().__autoDrain||{};return{enabled:!1!==e.enabled,intervalMs:D(e.intervalMs)}}function O(){const e=d().__autoDrain||{};return{...P(),source:void 0===e.enabled?"default":"config"}}function U(){const e=d().__autoMint||{};return{enabled:!1!==e.enabled,publish:!0===e.publish}}function k(){const e=d().__autoMint||{};return{...U(),source:void 0===e.enabled?"default":"config"}}return{file:o,sharedDir:i,adoption:s,sharedFile:function(){return prefs.prefsFile({dir:i})},getSharedPref:c,setSharedPref:function(e,n){if(!prefs.SHARED_PREF_KEYS.includes(e))throw new Error(`"${e}" is not a shared preference (see client/prefs.js SHARED_PREF_KEYS)`);return prefs.set({[e]:n},{dir:i}),c(e)},get:E,set:function(e,{baseURL:n,key:t}={}){A(e);let r=n;if("local"===e&&n){const e=localTransport.remoteRefusal(n);if(e)throw e;r=localTransport.normalizeBase(n)}const o=d(),i=o[e]||{};return void 0!==r&&(i.baseURL=r),void 0!==t&&(i.key=t?_(t):null),o[e]=i,f(o),E(e)},rawKey:function(e){return l((d()[e]||{}).key)},remove:function(e){A(e);const n=d();return delete n[e],f(n),{ok:!0}},list:function(){const e=d();return Object.keys(e).filter((e=>!isReservedNamespace(e))).map((e=>E(e)))},maskKey:maskKey,aegisKey:S,aegisRawKey:function(){return l((d().__aegis||{}).key)},aegisKeySavedAt:function(){return(d().__aegis||{}).savedAt||null},setAegisKey:function(e){const n=d();return n.__aegis={...n.__aegis||{},key:e?_(e):null,savedAt:e?(new Date).toISOString():null},f(n),S()},migrateLegacyAegisKey:function(){try{const e=d();if(!e.aegis)return{migrated:!1};const n=e.aegis||{},t=e.__aegis||{},r={...e};return n.key&&!t.key&&(r.__aegis={...t,key:n.key}),delete r.aegis,f(r),{migrated:!0}}catch{return{migrated:!1}}},quickLauncherConfig:N,setQuickLauncherConfig:function({enabled:e,shortcut:n}={}){const t=d();return t.__quickLauncher={enabled:Boolean(e),shortcut:"string"==typeof n&&n.trim()?n.trim():"CmdOrCtrl+Shift+Space"},f(t),N()},vaultBackendConfig:b,setVaultBackendConfig:function(e){if(!VAULT_BACKEND_VALUES.includes(e))return b();const n=d();return n.__vaultBackend={backend:e},f(n),b()},getConfirmMode:function(){return v().enabled},setConfirmMode:function(e){prefs.set({confirmMode:Boolean(e)},{dir:i});const n=d();return void 0!==n.__confirmMode&&(delete n.__confirmMode,f(n)),v().enabled},confirmModeState:v,getFontScale:M,setFontScale:function(e){const n=d();return n.__fontScale={scale:m(e)},f(n),M()},clampFontScale:m,getAccent:y,setAccent:function(e){const n=d();return n.__accent={name:g(e)},f(n),y()},clampAccent:g,ACCENT_SKINS:p,getPermissionMode:T,setPermissionMode:function(e){if(null==e||""===e||"off"===e||"none"===e)return prefs.remove("permissionMode",{dir:i}),null;const n=String(e),t=function(){const e=[path.join(__dirname,"..","..","one","src","permissions.js"),path.join(__dirname,"..","vendor","one","src","permissions.js")];for(const n of e)try{const e=require(n);if(e&&Array.isArray(e.PERMISSION_MODES)&&e.PERMISSION_MODES.length)return[...e.PERMISSION_MODES]}catch{}return["acceptEdits","auto","bypassPermissions","manual","dontAsk","plan"]}();if(!t.includes(n))throw new Error(`"${n}" is not one of ${t.join("|")} (or 'off' to clear it)`);return prefs.set({permissionMode:n},{dir:i}),T()},getSandboxPolicy:C,setSandboxPolicy:function(e){return e&&"object"==typeof e?(prefs.set({sandboxPolicy:e},{dir:i}),C()):(prefs.set({sandboxPolicy:null},{dir:i}),null)},getTelemetryOptIn:h,setTelemetryOptIn:function(e){const n=d();return n.__telemetry={enabled:Boolean(e)},f(n),h()},getMemoryPersist:function(){return R().enabled},memoryPersistState:R,setMemoryPersist:function(e){prefs.set({memoryPersist:Boolean(e)},{dir:i});const n=d();return void 0!==n.__memoryPersist&&(delete n.__memoryPersist,f(n)),R()},getAvatar:I,avatarState:L,setAvatar:function(e={}){const n=I(),t=e&&"object"==typeof e?e:{},r={enabled:void 0===t.enabled?n.enabled:Boolean(t.enabled),showLevel:void 0===t.showLevel?n.showLevel:Boolean(t.showLevel),motion:AVATAR_MOTION_MODES.includes(t.motion)?t.motion:n.motion},o=d();return o.__avatar=r,f(o),L()},getAutoDrain:P,autoDrainState:O,setAutoDrain:function(e={}){const n=P(),t=e&&"object"==typeof e?e:{},r=d();return r.__autoDrain={enabled:void 0===t.enabled?n.enabled:Boolean(t.enabled),intervalMs:void 0===t.intervalMs?n.intervalMs:D(t.intervalMs)},f(r),O()},getAutoMint:U,autoMintState:k,setAutoMint:function(e={}){const n=U(),t=e&&"object"==typeof e?e:{},r=d();return r.__autoMint={enabled:void 0===t.enabled?n.enabled:Boolean(t.enabled),publish:void 0===t.publish?n.publish:Boolean(t.publish)},f(r),k()},clampAutoDrainInterval:D}}module.exports={SETTINGS_FILE:SETTINGS_FILE,AEGIS_KEY_NAMESPACE:"__aegis",LEGACY_AEGIS_NAMESPACE:"aegis",QUICK_LAUNCHER_NAMESPACE:"__quickLauncher",VAULT_BACKEND_NAMESPACE:"__vaultBackend",CONFIRM_MODE_NAMESPACE:"__confirmMode",MEMORY_PERSIST_NAMESPACE:"__memoryPersist",AVATAR_NAMESPACE:"__avatar",TELEMETRY_NAMESPACE:"__telemetry",AUTO_DRAIN_NAMESPACE:"__autoDrain",AUTO_MINT_NAMESPACE:"__autoMint",AUTO_DRAIN_INTERVAL_DEFAULT_MS:6e4,AUTO_DRAIN_INTERVAL_MIN_MS:15e3,AUTO_DRAIN_INTERVAL_MAX_MS:18e5,AVATAR_MOTION_MODES:AVATAR_MOTION_MODES,DEFAULT_QUICK_LAUNCHER_SHORTCUT:"CmdOrCtrl+Shift+Space",DEFAULT_VAULT_BACKEND:"aegiscloud",VAULT_BACKEND_VALUES:VAULT_BACKEND_VALUES,RESERVED_NAMESPACES:RESERVED_NAMESPACES,isReservedNamespace:isReservedNamespace,maskKey:maskKey,createSettingsStore:createSettingsStore};